From e940e7d37b2ffcc24595e99868c40e46c57f74b9 Mon Sep 17 00:00:00 2001 From: Joseph Poirier Date: Tue, 6 Jan 2015 12:42:36 -0600 Subject: [PATCH 0001/1263] Test the realtime GC, via long running process in a shared object, without linking nimrtl.dll/so. --- tests/realtimeGC/main.c | 71 +++++++++++++++++++++++++++++++++ tests/realtimeGC/main.nim | 40 +++++++++++++++++++ tests/realtimeGC/main.nim.cfg | 6 +++ tests/realtimeGC/make.bat | 10 +++++ tests/realtimeGC/readme.txt | 21 ++++++++++ tests/realtimeGC/shared.nim | 60 ++++++++++++++++++++++++++++ tests/realtimeGC/shared.nim.cfg | 6 +++ 7 files changed, 214 insertions(+) create mode 100644 tests/realtimeGC/main.c create mode 100644 tests/realtimeGC/main.nim create mode 100644 tests/realtimeGC/main.nim.cfg create mode 100755 tests/realtimeGC/make.bat create mode 100644 tests/realtimeGC/readme.txt create mode 100644 tests/realtimeGC/shared.nim create mode 100644 tests/realtimeGC/shared.nim.cfg diff --git a/tests/realtimeGC/main.c b/tests/realtimeGC/main.c new file mode 100644 index 000000000..0a0ea95b2 --- /dev/null +++ b/tests/realtimeGC/main.c @@ -0,0 +1,71 @@ + +#ifdef WIN +#include +#else +#include +#endif +#include +#include +#include +#include +#include + +#define RUNTIME (35*60) + + +typedef void (*pFunc)(void); + +int main(int argc, char* argv[]) +{ + int i; + void* hndl; + pFunc status; + pFunc count; + pFunc occupiedMem; + +#ifdef WIN + hndl = (void*) LoadLibrary((char const*)"./shared.dll"); + status = (pFunc)GetProcessAddress((HMODULE) hndl, (char const*)"status"); + count = (pFunc)GetProcessAddress((HMODULE) hndl, (char const*)"count"); + occupiedMem = (pFunc)GetProcessAddress((HMODULE) hndl, (char const*)"occupiedMem"); +#else /* OSX || NIX */ + hndl = (void*) dlopen((char const*)"./libshared.so", RTLD_LAZY); + status = (void*) dlsym(hndl, (char const*)"status"); + count = (void*) dlsym(hndl, (char const*)"count"); + occupiedMem = (void*) dlsym(hndl, (char const*)"occupiedMem"); +#endif + + assert(hndl); + assert(status); + assert(count); + assert(occupiedMem); + + time_t startTime = time((time_t*)0); + time_t runTime = (time_t)(RUNTIME); + time_t accumTime = 0; + while (accumTime < runTime) { + for (i = 0; i < 10; i++) + count(); + printf("1. sleeping...\n"); + sleep(1); + for (i = 0; i < 10; i++) + status(); + printf("2. sleeping...\n"); + sleep(1); + occupiedMem(); + accumTime = time((time_t*)0) - startTime; + printf("--- Minutes left to run: %d\n", (int)(runTime-accumTime)/60); + } + printf("Cleaning up the shared object pointer...\n"); +#ifdef WIN + FreeLibrary((HMODULE)hndl); +#else /* OSX || NIX */ + dlclose(hndl); +#endif + printf("Done\n"); + return 0; +} + + + + diff --git a/tests/realtimeGC/main.nim b/tests/realtimeGC/main.nim new file mode 100644 index 000000000..21e90d545 --- /dev/null +++ b/tests/realtimeGC/main.nim @@ -0,0 +1,40 @@ +discard """ + cmd: " nim c main.nim" + final output: "Done!" +""" + +import times +import os + +const RUNTIME = 35 * 60 # 35 minutes + +when defined(windows): + const dllname = "./server.dll" +elif defined(macosx): + const dllname = "./libserver.dylib" +else: + const dllname = "./libserver.so" + +proc status() {.importc: "status", dynlib: dllname.} +proc count() {.importc: "count", dynlib: dllname.} +proc occupiedMem() {.importc: "occupiedMem", dynlib: dllname.} + +proc main() = + let startTime = getTime() + let runTime = cast[Time](RUNTIME) # + var accumTime: Time + while accumTime < runTime: + for i in 0..10: + count() + echo("1. sleeping... ") + sleep(500) + for i in 0..10: + status() + echo("2. sleeping... ") + sleep(500) + occupiedMem() + accumTime = cast[Time]((getTime() - startTime)) + echo("--- Minutes left to run: ", int(int(runTime-accumTime)/60)) + echo("Done") + +main() diff --git a/tests/realtimeGC/main.nim.cfg b/tests/realtimeGC/main.nim.cfg new file mode 100644 index 000000000..fed4fa471 --- /dev/null +++ b/tests/realtimeGC/main.nim.cfg @@ -0,0 +1,6 @@ + +--app:console +--threads:on + +-d:release +-d:useRealtimeGC diff --git a/tests/realtimeGC/make.bat b/tests/realtimeGC/make.bat new file mode 100755 index 000000000..182595270 --- /dev/null +++ b/tests/realtimeGC/make.bat @@ -0,0 +1,10 @@ + +set CXX=gcc +set LIBS=-ldl +set LNFLAGS= +set CFLAGS=-DWIN +set INC= + +nim c shared.nim +nim c -o:nmain main.nim +%CXX% %INC) %DEFS% %CFLAGS% -o cmain main.c %LNFLAGS% %LIBS% diff --git a/tests/realtimeGC/readme.txt b/tests/realtimeGC/readme.txt new file mode 100644 index 000000000..035a00001 --- /dev/null +++ b/tests/realtimeGC/readme.txt @@ -0,0 +1,21 @@ +Test the realtime GC without linking nimrtl.dll/so. + +Note, this is a long running test, default is 35 minutes. To change the +the run time see RUNTIME in main.nim and main.c. + +You can build shared.nim, main.nim, and main.c by running make (nix systems) +or maike.bat (Windows systems). They both assume GCC and that it's in your +path. Output: shared.(dll/so), camin(.exe), nmain(.exe). + +To run the test: execute either nmain or cmain in a shell window. + +To build buy hand: + + - build the shared object (shared.nim): + + $ nim c shared.nim + + - build the client executables: + + $ nim c -o:nmain main.nim + $ gcc -o cmain main.c -ldl diff --git a/tests/realtimeGC/shared.nim b/tests/realtimeGC/shared.nim new file mode 100644 index 000000000..5da1f1fc2 --- /dev/null +++ b/tests/realtimeGC/shared.nim @@ -0,0 +1,60 @@ +discard """ + cmd: " nim c shared.nim" +""" + +import strutils + +var gCounter: uint64 +var gTxStatus: bool +var gRxStatus: bool +var gConnectStatus: bool +var gPttStatus: bool +var gComm1Status: bool +var gComm2Status: bool + +proc getTxStatus(): string = + result = if gTxStatus: "On" else: "Off" + gTxStatus = not gTxStatus + +proc getRxStatus(): string = + result = if gRxStatus: "On" else: "Off" + gRxStatus = not gRxStatus + +proc getConnectStatus(): string = + result = if gConnectStatus: "Yes" else: "No" + gConnectStatus = not gConnectStatus + +proc getPttStatus(): string = + result = if gPttStatus: "PTT: On" else: "PTT: Off" + gPttStatus = not gPttStatus + +proc getComm1Status(): string = + result = if gComm1Status: "On" else: "Off" + gComm1Status = not gComm1Status + +proc getComm2Status(): string = + result = if gComm2Status: "On" else: "Off" + gComm2Status = not gComm2Status + +proc status() {.exportc: "status", dynlib.} = + var tx_status = getTxStatus() + var rx_status = getRxStatus() + var connected = getConnectStatus() + var ptt_status = getPttStatus() + var str1: string = "[PilotEdge] Connected: $1 TX: $2 RX: $3" % [connected, tx_status, rx_status] + var a = getComm1Status() + var b = getComm2Status() + var str2: string = "$1 COM1: $2 COM2: $3" % [ptt_status, a, b] + echo(str1) + echo(str2) + +proc count() {.exportc: "count", dynlib.} = + var temp: uint64 + for i in 0..100_000: + temp += 1 + gCounter += 1 + echo("gCounter: ", gCounter) + +proc occupiedMem() {.exportc: "occupiedMem", dynlib.} = + echo("Occupied Memmory: ", getOccupiedMem()) + diff --git a/tests/realtimeGC/shared.nim.cfg b/tests/realtimeGC/shared.nim.cfg new file mode 100644 index 000000000..5d498029d --- /dev/null +++ b/tests/realtimeGC/shared.nim.cfg @@ -0,0 +1,6 @@ + +--app:lib +--threads:on + +-d:release +-d:useRealtimeGC From 9be15cd3b3f769f834771b48e190a8062bd2d176 Mon Sep 17 00:00:00 2001 From: Joseph Poirier Date: Tue, 6 Jan 2015 13:02:31 -0600 Subject: [PATCH 0002/1263] fixed import object name --- tests/realtimeGC/main.nim | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/realtimeGC/main.nim b/tests/realtimeGC/main.nim index 21e90d545..98cebdd30 100644 --- a/tests/realtimeGC/main.nim +++ b/tests/realtimeGC/main.nim @@ -9,11 +9,11 @@ import os const RUNTIME = 35 * 60 # 35 minutes when defined(windows): - const dllname = "./server.dll" + const dllname = "./shared.dll" elif defined(macosx): - const dllname = "./libserver.dylib" + const dllname = "./libshared.dylib" else: - const dllname = "./libserver.so" + const dllname = "./libshared.so" proc status() {.importc: "status", dynlib: dllname.} proc count() {.importc: "count", dynlib: dllname.} From 4e2192fd1cc1f8281a6992e6252df8ce763a9b7c Mon Sep 17 00:00:00 2001 From: Joseph Poirier Date: Tue, 6 Jan 2015 13:42:02 -0600 Subject: [PATCH 0003/1263] properly typecast the function pointers --- tests/realtimeGC/main.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/realtimeGC/main.c b/tests/realtimeGC/main.c index 0a0ea95b2..8bf7aed19 100644 --- a/tests/realtimeGC/main.c +++ b/tests/realtimeGC/main.c @@ -30,9 +30,9 @@ int main(int argc, char* argv[]) occupiedMem = (pFunc)GetProcessAddress((HMODULE) hndl, (char const*)"occupiedMem"); #else /* OSX || NIX */ hndl = (void*) dlopen((char const*)"./libshared.so", RTLD_LAZY); - status = (void*) dlsym(hndl, (char const*)"status"); - count = (void*) dlsym(hndl, (char const*)"count"); - occupiedMem = (void*) dlsym(hndl, (char const*)"occupiedMem"); + status = (pFunc) dlsym(hndl, (char const*)"status"); + count = (pFunc) dlsym(hndl, (char const*)"count"); + occupiedMem = (pFunc) dlsym(hndl, (char const*)"occupiedMem"); #endif assert(hndl); From 159bbce6d5cf2605f3fbade8807be185a0870657 Mon Sep 17 00:00:00 2001 From: Joseph Poirier Date: Tue, 6 Jan 2015 14:56:50 -0600 Subject: [PATCH 0004/1263] add proper cdm strings and comment out all echos --- tests/realtimeGC/main.nim | 10 +++++----- tests/realtimeGC/shared.nim | 10 +++++----- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/tests/realtimeGC/main.nim b/tests/realtimeGC/main.nim index 98cebdd30..5496cd999 100644 --- a/tests/realtimeGC/main.nim +++ b/tests/realtimeGC/main.nim @@ -1,6 +1,6 @@ discard """ - cmd: " nim c main.nim" - final output: "Done!" + cmd: "nim $target --debuginfo $options $file" + output: "Done" """ import times @@ -26,15 +26,15 @@ proc main() = while accumTime < runTime: for i in 0..10: count() - echo("1. sleeping... ") + #echo("1. sleeping... ") sleep(500) for i in 0..10: status() - echo("2. sleeping... ") + #echo("2. sleeping... ") sleep(500) occupiedMem() accumTime = cast[Time]((getTime() - startTime)) - echo("--- Minutes left to run: ", int(int(runTime-accumTime)/60)) + #echo("--- Minutes left to run: ", int(int(runTime-accumTime)/60)) echo("Done") main() diff --git a/tests/realtimeGC/shared.nim b/tests/realtimeGC/shared.nim index 5da1f1fc2..df11b4ef9 100644 --- a/tests/realtimeGC/shared.nim +++ b/tests/realtimeGC/shared.nim @@ -1,5 +1,5 @@ discard """ - cmd: " nim c shared.nim" + cmd: "nim $target --debuginfo --hints:on --app:lib $options $file" """ import strutils @@ -45,16 +45,16 @@ proc status() {.exportc: "status", dynlib.} = var a = getComm1Status() var b = getComm2Status() var str2: string = "$1 COM1: $2 COM2: $3" % [ptt_status, a, b] - echo(str1) - echo(str2) + #echo(str1) + #echo(str2) proc count() {.exportc: "count", dynlib.} = var temp: uint64 for i in 0..100_000: temp += 1 gCounter += 1 - echo("gCounter: ", gCounter) + #echo("gCounter: ", gCounter) proc occupiedMem() {.exportc: "occupiedMem", dynlib.} = - echo("Occupied Memmory: ", getOccupiedMem()) + #echo("Occupied Memmory: ", getOccupiedMem()) From 5f3d7e8940779cc2f03374d3e29650c6e7dc3d34 Mon Sep 17 00:00:00 2001 From: Joseph Poirier Date: Tue, 6 Jan 2015 15:05:51 -0600 Subject: [PATCH 0005/1263] add test note to the readme --- tests/readme.txt | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/readme.txt b/tests/readme.txt index 0d33a81c7..2cfc79f9a 100644 --- a/tests/readme.txt +++ b/tests/readme.txt @@ -3,8 +3,11 @@ Each test must have a filename of the form: ``t*.nim`` Each test can contain a spec in a ``discard """"""`` block. -The folder ``rodfiles`` contains special tests that test incremental +The folder ``rodfiles`` contains special tests that test incremental compilation via symbol files. The folder ``dll`` contains simple DLL tests. +The folder ``realtimeGC`` contains a test for validating that the realtime GC +can run properly without linking against the nimrtl.dll/so. It includes a C +client and platform specific build files for manual compilation. From b22a3e8237c5b482050b3437baa93b35b21a422e Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Wed, 7 Jan 2015 17:48:43 -0500 Subject: [PATCH 0006/1263] Initial Commit --- .gitignore | 9 +++++++++ are.nimble | 9 +++++++++ 2 files changed, 18 insertions(+) create mode 100644 .gitignore create mode 100644 are.nimble diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..3d647a25e --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +# all executables +* +!*/ +!*.* +*.exe + +# Wildcard patterns. +*.swp +nimcache diff --git a/are.nimble b/are.nimble new file mode 100644 index 000000000..e68994e1c --- /dev/null +++ b/are.nimble @@ -0,0 +1,9 @@ +[Package] +name = "are" +version = "0.1.0" +description = "Yet another PCRE library" +license = "MIT" +srcDir = "src" + +[Deps] +Requires: "nim >= 0.10.1" From e9f9f6f369f54f13eb94a126695989cdc35787a0 Mon Sep 17 00:00:00 2001 From: Joseph Poirier Date: Thu, 8 Jan 2015 13:40:06 -0600 Subject: [PATCH 0007/1263] proper windows get process function name, fix batch file, add echoes back --- tests/realtimeGC/main.c | 6 +++--- tests/realtimeGC/make.bat | 2 +- tests/realtimeGC/shared.nim | 1 + 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/tests/realtimeGC/main.c b/tests/realtimeGC/main.c index 8bf7aed19..a7ac19dda 100644 --- a/tests/realtimeGC/main.c +++ b/tests/realtimeGC/main.c @@ -25,9 +25,9 @@ int main(int argc, char* argv[]) #ifdef WIN hndl = (void*) LoadLibrary((char const*)"./shared.dll"); - status = (pFunc)GetProcessAddress((HMODULE) hndl, (char const*)"status"); - count = (pFunc)GetProcessAddress((HMODULE) hndl, (char const*)"count"); - occupiedMem = (pFunc)GetProcessAddress((HMODULE) hndl, (char const*)"occupiedMem"); + status = (pFunc)GetProcAddress((HMODULE) hndl, (char const*)"status"); + count = (pFunc)GetProcAddress((HMODULE) hndl, (char const*)"count"); + occupiedMem = (pFunc)GetProcAddress((HMODULE) hndl, (char const*)"occupiedMem"); #else /* OSX || NIX */ hndl = (void*) dlopen((char const*)"./libshared.so", RTLD_LAZY); status = (pFunc) dlsym(hndl, (char const*)"status"); diff --git a/tests/realtimeGC/make.bat b/tests/realtimeGC/make.bat index 182595270..cce8292bf 100755 --- a/tests/realtimeGC/make.bat +++ b/tests/realtimeGC/make.bat @@ -7,4 +7,4 @@ set INC= nim c shared.nim nim c -o:nmain main.nim -%CXX% %INC) %DEFS% %CFLAGS% -o cmain main.c %LNFLAGS% %LIBS% +%CXX% %INC% %DEFS% %CFLAGS% -o cmain main.c %LNFLAGS% %LIBS% diff --git a/tests/realtimeGC/shared.nim b/tests/realtimeGC/shared.nim index df11b4ef9..345051bb5 100644 --- a/tests/realtimeGC/shared.nim +++ b/tests/realtimeGC/shared.nim @@ -57,4 +57,5 @@ proc count() {.exportc: "count", dynlib.} = proc occupiedMem() {.exportc: "occupiedMem", dynlib.} = #echo("Occupied Memmory: ", getOccupiedMem()) + discard From b36ba634a687c762fa8062ec0c5296b6f19986c1 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Fri, 9 Jan 2015 16:27:45 -0500 Subject: [PATCH 0008/1263] Add thin PCRE wrapper --- src/private/pcre.h | 630 +++++++++++++++++++++++++++++++++++++++++++ src/private/pcre.nim | 450 +++++++++++++++++++++++++++++++ 2 files changed, 1080 insertions(+) create mode 100644 src/private/pcre.h create mode 100644 src/private/pcre.nim diff --git a/src/private/pcre.h b/src/private/pcre.h new file mode 100644 index 000000000..b2d9c05e5 --- /dev/null +++ b/src/private/pcre.h @@ -0,0 +1,630 @@ +#ifdef C2NIM +#def PCRE_EXP_DECL extern +#prefix PCRE_ +#mangle "'pcre'{[0-9]*}_{.*}" "$2$1" +#header "pcre.h" +#cdecl +#endif + +/************************************************* +* Perl-Compatible Regular Expressions * +*************************************************/ + +/* This is the public header file for the PCRE library, to be #included by +applications that call the PCRE functions. + + Copyright (c) 1997-2014 University of Cambridge + +----------------------------------------------------------------------------- +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * Neither the name of the University of Cambridge nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. +----------------------------------------------------------------------------- +*/ + +/* The current PCRE version information. */ + +#define PCRE_MAJOR 8 +#define PCRE_MINOR 36 +#define PCRE_PRERELEASE +#define PCRE_DATE 2014-09-26 + +/* When an application links to a PCRE DLL in Windows, the symbols that are +imported have to be identified as such. When building PCRE, the appropriate +export setting is defined in pcre_internal.h, which includes this file. So we +don't change existing definitions of PCRE_EXP_DECL and PCRECPP_EXP_DECL. */ + + +/* By default, we use the standard "extern" declarations. */ + + +/* Have to include stdlib.h in order to ensure that size_t is defined; +it is needed here for malloc. */ + +#include + +/* Allow for C++ users */ + +/* Public options. Some are compile-time only, some are run-time only, and some +are both. Most of the compile-time options are saved with the compiled regex so +that they can be inspected during studying (and therefore JIT compiling). Note +that pcre_study() has its own set of options. Originally, all the options +defined here used distinct bits. However, almost all the bits in a 32-bit word +are now used, so in order to conserve them, option bits that were previously +only recognized at matching time (i.e. by pcre_exec() or pcre_dfa_exec()) may +also be used for compile-time options that affect only compiling and are not +relevant for studying or JIT compiling. + +Some options for pcre_compile() change its behaviour but do not affect the +behaviour of the execution functions. Other options are passed through to the +execution functions and affect their behaviour, with or without affecting the +behaviour of pcre_compile(). + +Options that can be passed to pcre_compile() are tagged Cx below, with these +variants: + +C1 Affects compile only +C2 Does not affect compile; affects exec, dfa_exec +C3 Affects compile, exec, dfa_exec +C4 Affects compile, exec, dfa_exec, study +C5 Affects compile, exec, study + +Options that can be set for pcre_exec() and/or pcre_dfa_exec() are flagged with +E and D, respectively. They take precedence over C3, C4, and C5 settings passed +from pcre_compile(). Those that are compatible with JIT execution are flagged +with J. */ + +#define PCRE_CASELESS 0x00000001 /* C1 */ +#define PCRE_MULTILINE 0x00000002 /* C1 */ +#define PCRE_DOTALL 0x00000004 /* C1 */ +#define PCRE_EXTENDED 0x00000008 /* C1 */ +#define PCRE_ANCHORED 0x00000010 /* C4 E D */ +#define PCRE_DOLLAR_ENDONLY 0x00000020 /* C2 */ +#define PCRE_EXTRA 0x00000040 /* C1 */ +#define PCRE_NOTBOL 0x00000080 /* E D J */ +#define PCRE_NOTEOL 0x00000100 /* E D J */ +#define PCRE_UNGREEDY 0x00000200 /* C1 */ +#define PCRE_NOTEMPTY 0x00000400 /* E D J */ +#define PCRE_UTF8 0x00000800 /* C4 ) */ +#define PCRE_UTF16 0x00000800 /* C4 ) Synonyms */ +#define PCRE_UTF32 0x00000800 /* C4 ) */ +#define PCRE_NO_AUTO_CAPTURE 0x00001000 /* C1 */ +#define PCRE_NO_UTF8_CHECK 0x00002000 /* C1 E D J ) */ +#define PCRE_NO_UTF16_CHECK 0x00002000 /* C1 E D J ) Synonyms */ +#define PCRE_NO_UTF32_CHECK 0x00002000 /* C1 E D J ) */ +#define PCRE_AUTO_CALLOUT 0x00004000 /* C1 */ +#define PCRE_PARTIAL_SOFT 0x00008000 /* E D J ) Synonyms */ +#define PCRE_PARTIAL 0x00008000 /* E D J ) */ + +/* This pair use the same bit. */ +#define PCRE_NEVER_UTF 0x00010000 /* C1 ) Overlaid */ +#define PCRE_DFA_SHORTEST 0x00010000 /* D ) Overlaid */ + +/* This pair use the same bit. */ +#define PCRE_NO_AUTO_POSSESS 0x00020000 /* C1 ) Overlaid */ +#define PCRE_DFA_RESTART 0x00020000 /* D ) Overlaid */ + +#define PCRE_FIRSTLINE 0x00040000 /* C3 */ +#define PCRE_DUPNAMES 0x00080000 /* C1 */ +#define PCRE_NEWLINE_CR 0x00100000 /* C3 E D */ +#define PCRE_NEWLINE_LF 0x00200000 /* C3 E D */ +#define PCRE_NEWLINE_CRLF 0x00300000 /* C3 E D */ +#define PCRE_NEWLINE_ANY 0x00400000 /* C3 E D */ +#define PCRE_NEWLINE_ANYCRLF 0x00500000 /* C3 E D */ +#define PCRE_BSR_ANYCRLF 0x00800000 /* C3 E D */ +#define PCRE_BSR_UNICODE 0x01000000 /* C3 E D */ +#define PCRE_JAVASCRIPT_COMPAT 0x02000000 /* C5 */ +#define PCRE_NO_START_OPTIMIZE 0x04000000 /* C2 E D ) Synonyms */ +#define PCRE_NO_START_OPTIMISE 0x04000000 /* C2 E D ) */ +#define PCRE_PARTIAL_HARD 0x08000000 /* E D J */ +#define PCRE_NOTEMPTY_ATSTART 0x10000000 /* E D J */ +#define PCRE_UCP 0x20000000 /* C3 */ + +/* Exec-time and get/set-time error codes */ + +#define PCRE_ERROR_NOMATCH (-1) +#define PCRE_ERROR_NULL (-2) +#define PCRE_ERROR_BADOPTION (-3) +#define PCRE_ERROR_BADMAGIC (-4) +#define PCRE_ERROR_UNKNOWN_OPCODE (-5) +#define PCRE_ERROR_UNKNOWN_NODE (-5) /* For backward compatibility */ +#define PCRE_ERROR_NOMEMORY (-6) +#define PCRE_ERROR_NOSUBSTRING (-7) +#define PCRE_ERROR_MATCHLIMIT (-8) +#define PCRE_ERROR_CALLOUT (-9) /* Never used by PCRE itself */ +#define PCRE_ERROR_BADUTF8 (-10) /* Same for 8/16/32 */ +#define PCRE_ERROR_BADUTF16 (-10) /* Same for 8/16/32 */ +#define PCRE_ERROR_BADUTF32 (-10) /* Same for 8/16/32 */ +#define PCRE_ERROR_BADUTF8_OFFSET (-11) /* Same for 8/16 */ +#define PCRE_ERROR_BADUTF16_OFFSET (-11) /* Same for 8/16 */ +#define PCRE_ERROR_PARTIAL (-12) +#define PCRE_ERROR_BADPARTIAL (-13) +#define PCRE_ERROR_INTERNAL (-14) +#define PCRE_ERROR_BADCOUNT (-15) +#define PCRE_ERROR_DFA_UITEM (-16) +#define PCRE_ERROR_DFA_UCOND (-17) +#define PCRE_ERROR_DFA_UMLIMIT (-18) +#define PCRE_ERROR_DFA_WSSIZE (-19) +#define PCRE_ERROR_DFA_RECURSE (-20) +#define PCRE_ERROR_RECURSIONLIMIT (-21) +#define PCRE_ERROR_NULLWSLIMIT (-22) /* No longer actually used */ +#define PCRE_ERROR_BADNEWLINE (-23) +#define PCRE_ERROR_BADOFFSET (-24) +#define PCRE_ERROR_SHORTUTF8 (-25) +#define PCRE_ERROR_SHORTUTF16 (-25) /* Same for 8/16 */ +#define PCRE_ERROR_RECURSELOOP (-26) +#define PCRE_ERROR_JIT_STACKLIMIT (-27) +#define PCRE_ERROR_BADMODE (-28) +#define PCRE_ERROR_BADENDIANNESS (-29) +#define PCRE_ERROR_DFA_BADRESTART (-30) +#define PCRE_ERROR_JIT_BADOPTION (-31) +#define PCRE_ERROR_BADLENGTH (-32) +#define PCRE_ERROR_UNSET (-33) + +/* Specific error codes for UTF-8 validity checks */ + +#define PCRE_UTF8_ERR0 0 +#define PCRE_UTF8_ERR1 1 +#define PCRE_UTF8_ERR2 2 +#define PCRE_UTF8_ERR3 3 +#define PCRE_UTF8_ERR4 4 +#define PCRE_UTF8_ERR5 5 +#define PCRE_UTF8_ERR6 6 +#define PCRE_UTF8_ERR7 7 +#define PCRE_UTF8_ERR8 8 +#define PCRE_UTF8_ERR9 9 +#define PCRE_UTF8_ERR10 10 +#define PCRE_UTF8_ERR11 11 +#define PCRE_UTF8_ERR12 12 +#define PCRE_UTF8_ERR13 13 +#define PCRE_UTF8_ERR14 14 +#define PCRE_UTF8_ERR15 15 +#define PCRE_UTF8_ERR16 16 +#define PCRE_UTF8_ERR17 17 +#define PCRE_UTF8_ERR18 18 +#define PCRE_UTF8_ERR19 19 +#define PCRE_UTF8_ERR20 20 +#define PCRE_UTF8_ERR21 21 +#define PCRE_UTF8_ERR22 22 /* Unused (was non-character) */ + +/* Specific error codes for UTF-16 validity checks */ + +#define PCRE_UTF16_ERR0 0 +#define PCRE_UTF16_ERR1 1 +#define PCRE_UTF16_ERR2 2 +#define PCRE_UTF16_ERR3 3 +#define PCRE_UTF16_ERR4 4 /* Unused (was non-character) */ + +/* Specific error codes for UTF-32 validity checks */ + +#define PCRE_UTF32_ERR0 0 +#define PCRE_UTF32_ERR1 1 +#define PCRE_UTF32_ERR2 2 /* Unused (was non-character) */ +#define PCRE_UTF32_ERR3 3 + +/* Request types for pcre_fullinfo() */ + +#define PCRE_INFO_OPTIONS 0 +#define PCRE_INFO_SIZE 1 +#define PCRE_INFO_CAPTURECOUNT 2 +#define PCRE_INFO_BACKREFMAX 3 +#define PCRE_INFO_FIRSTBYTE 4 +#define PCRE_INFO_FIRSTCHAR 4 /* For backwards compatibility */ +#define PCRE_INFO_FIRSTTABLE 5 +#define PCRE_INFO_LASTLITERAL 6 +#define PCRE_INFO_NAMEENTRYSIZE 7 +#define PCRE_INFO_NAMECOUNT 8 +#define PCRE_INFO_NAMETABLE 9 +#define PCRE_INFO_STUDYSIZE 10 +#define PCRE_INFO_DEFAULT_TABLES 11 +#define PCRE_INFO_OKPARTIAL 12 +#define PCRE_INFO_JCHANGED 13 +#define PCRE_INFO_HASCRORLF 14 +#define PCRE_INFO_MINLENGTH 15 +#define PCRE_INFO_JIT 16 +#define PCRE_INFO_JITSIZE 17 +#define PCRE_INFO_MAXLOOKBEHIND 18 +#define PCRE_INFO_FIRSTCHARACTER 19 +#define PCRE_INFO_FIRSTCHARACTERFLAGS 20 +#define PCRE_INFO_REQUIREDCHAR 21 +#define PCRE_INFO_REQUIREDCHARFLAGS 22 +#define PCRE_INFO_MATCHLIMIT 23 +#define PCRE_INFO_RECURSIONLIMIT 24 +#define PCRE_INFO_MATCH_EMPTY 25 + +/* Request types for pcre_config(). Do not re-arrange, in order to remain +compatible. */ + +#define PCRE_CONFIG_UTF8 0 +#define PCRE_CONFIG_NEWLINE 1 +#define PCRE_CONFIG_LINK_SIZE 2 +#define PCRE_CONFIG_POSIX_MALLOC_THRESHOLD 3 +#define PCRE_CONFIG_MATCH_LIMIT 4 +#define PCRE_CONFIG_STACKRECURSE 5 +#define PCRE_CONFIG_UNICODE_PROPERTIES 6 +#define PCRE_CONFIG_MATCH_LIMIT_RECURSION 7 +#define PCRE_CONFIG_BSR 8 +#define PCRE_CONFIG_JIT 9 +#define PCRE_CONFIG_UTF16 10 +#define PCRE_CONFIG_JITTARGET 11 +#define PCRE_CONFIG_UTF32 12 +#define PCRE_CONFIG_PARENS_LIMIT 13 + +/* Request types for pcre_study(). Do not re-arrange, in order to remain +compatible. */ + +#define PCRE_STUDY_JIT_COMPILE 0x0001 +#define PCRE_STUDY_JIT_PARTIAL_SOFT_COMPILE 0x0002 +#define PCRE_STUDY_JIT_PARTIAL_HARD_COMPILE 0x0004 +#define PCRE_STUDY_EXTRA_NEEDED 0x0008 + +/* Bit flags for the pcre[16|32]_extra structure. Do not re-arrange or redefine +these bits, just add new ones on the end, in order to remain compatible. */ + +#define PCRE_EXTRA_STUDY_DATA 0x0001 +#define PCRE_EXTRA_MATCH_LIMIT 0x0002 +#define PCRE_EXTRA_CALLOUT_DATA 0x0004 +#define PCRE_EXTRA_TABLES 0x0008 +#define PCRE_EXTRA_MATCH_LIMIT_RECURSION 0x0010 +#define PCRE_EXTRA_MARK 0x0020 +#define PCRE_EXTRA_EXECUTABLE_JIT 0x0040 + +/* Types */ + +struct real_pcre; /* declaration; the definition is private */ +typedef struct real_pcre pcre; + +struct real_pcre16; /* declaration; the definition is private */ +typedef struct real_pcre16 pcre16; + +struct real_pcre32; /* declaration; the definition is private */ +typedef struct real_pcre32 pcre32; + +struct real_pcre_jit_stack; /* declaration; the definition is private */ +typedef struct real_pcre_jit_stack pcre_jit_stack; + +struct real_pcre16_jit_stack; /* declaration; the definition is private */ +typedef struct real_pcre16_jit_stack pcre16_jit_stack; + +struct real_pcre32_jit_stack; /* declaration; the definition is private */ +typedef struct real_pcre32_jit_stack pcre32_jit_stack; + +/* If PCRE is compiled with 16 bit character support, PCRE_UCHAR16 must contain +a 16 bit wide signed data type. Otherwise it can be a dummy data type since +pcre16 functions are not implemented. There is a check for this in pcre_internal.h. */ +typedef unsigned short PCRE_UCHAR16; +typedef const PCRE_UCHAR16 *PCRE_SPTR16; + +/* If PCRE is compiled with 32 bit character support, PCRE_UCHAR32 must contain +a 32 bit wide signed data type. Otherwise it can be a dummy data type since +pcre32 functions are not implemented. There is a check for this in pcre_internal.h. */ +typedef unsigned int PCRE_UCHAR32; +typedef const PCRE_UCHAR32 *PCRE_SPTR32; + +/* When PCRE is compiled as a C++ library, the subject pointer type can be +replaced with a custom type. For conventional use, the public interface is a +const char *. */ +typedef const char *PCRE_SPTR; + +/* The structure for passing additional data to pcre_exec(). This is defined in +such as way as to be extensible. Always add new fields at the end, in order to +remain compatible. */ + +typedef struct pcre_extra { + unsigned long int flags; /* Bits for which fields are set */ + void *study_data; /* Opaque data from pcre_study() */ + unsigned long int match_limit; /* Maximum number of calls to match() */ + void *callout_data; /* Data passed back in callouts */ + const unsigned char *tables; /* Pointer to character tables */ + unsigned long int match_limit_recursion; /* Max recursive calls to match() */ + unsigned char **mark; /* For passing back a mark pointer */ + void *executable_jit; /* Contains a pointer to a compiled jit code */ +} pcre_extra; + +/* Same structure as above, but with 16 bit char pointers. */ + +typedef struct pcre16_extra { + unsigned long int flags; /* Bits for which fields are set */ + void *study_data; /* Opaque data from pcre_study() */ + unsigned long int match_limit; /* Maximum number of calls to match() */ + void *callout_data; /* Data passed back in callouts */ + const unsigned char *tables; /* Pointer to character tables */ + unsigned long int match_limit_recursion; /* Max recursive calls to match() */ + PCRE_UCHAR16 **mark; /* For passing back a mark pointer */ + void *executable_jit; /* Contains a pointer to a compiled jit code */ +} pcre16_extra; + +/* Same structure as above, but with 32 bit char pointers. */ + +typedef struct pcre32_extra { + unsigned long int flags; /* Bits for which fields are set */ + void *study_data; /* Opaque data from pcre_study() */ + unsigned long int match_limit; /* Maximum number of calls to match() */ + void *callout_data; /* Data passed back in callouts */ + const unsigned char *tables; /* Pointer to character tables */ + unsigned long int match_limit_recursion; /* Max recursive calls to match() */ + PCRE_UCHAR32 **mark; /* For passing back a mark pointer */ + void *executable_jit; /* Contains a pointer to a compiled jit code */ +} pcre32_extra; + +/* The structure for passing out data via the pcre_callout_function. We use a +structure so that new fields can be added on the end in future versions, +without changing the API of the function, thereby allowing old clients to work +without modification. */ + +typedef struct pcre_callout_block { + int version; /* Identifies version of block */ + /* ------------------------ Version 0 ------------------------------- */ + int callout_number; /* Number compiled into pattern */ + int *offset_vector; /* The offset vector */ + PCRE_SPTR subject; /* The subject being matched */ + int subject_length; /* The length of the subject */ + int start_match; /* Offset to start of this match attempt */ + int current_position; /* Where we currently are in the subject */ + int capture_top; /* Max current capture */ + int capture_last; /* Most recently closed capture */ + void *callout_data; /* Data passed in with the call */ + /* ------------------- Added for Version 1 -------------------------- */ + int pattern_position; /* Offset to next item in the pattern */ + int next_item_length; /* Length of next item in the pattern */ + /* ------------------- Added for Version 2 -------------------------- */ + const unsigned char *mark; /* Pointer to current mark or NULL */ + /* ------------------------------------------------------------------ */ +} pcre_callout_block; + +/* Same structure as above, but with 16 bit char pointers. */ + +typedef struct pcre16_callout_block { + int version; /* Identifies version of block */ + /* ------------------------ Version 0 ------------------------------- */ + int callout_number; /* Number compiled into pattern */ + int *offset_vector; /* The offset vector */ + PCRE_SPTR16 subject; /* The subject being matched */ + int subject_length; /* The length of the subject */ + int start_match; /* Offset to start of this match attempt */ + int current_position; /* Where we currently are in the subject */ + int capture_top; /* Max current capture */ + int capture_last; /* Most recently closed capture */ + void *callout_data; /* Data passed in with the call */ + /* ------------------- Added for Version 1 -------------------------- */ + int pattern_position; /* Offset to next item in the pattern */ + int next_item_length; /* Length of next item in the pattern */ + /* ------------------- Added for Version 2 -------------------------- */ + const PCRE_UCHAR16 *mark; /* Pointer to current mark or NULL */ + /* ------------------------------------------------------------------ */ +} pcre16_callout_block; + +/* Same structure as above, but with 32 bit char pointers. */ + +typedef struct pcre32_callout_block { + int version; /* Identifies version of block */ + /* ------------------------ Version 0 ------------------------------- */ + int callout_number; /* Number compiled into pattern */ + int *offset_vector; /* The offset vector */ + PCRE_SPTR32 subject; /* The subject being matched */ + int subject_length; /* The length of the subject */ + int start_match; /* Offset to start of this match attempt */ + int current_position; /* Where we currently are in the subject */ + int capture_top; /* Max current capture */ + int capture_last; /* Most recently closed capture */ + void *callout_data; /* Data passed in with the call */ + /* ------------------- Added for Version 1 -------------------------- */ + int pattern_position; /* Offset to next item in the pattern */ + int next_item_length; /* Length of next item in the pattern */ + /* ------------------- Added for Version 2 -------------------------- */ + const PCRE_UCHAR32 *mark; /* Pointer to current mark or NULL */ + /* ------------------------------------------------------------------ */ +} pcre32_callout_block; + +/* Indirection for store get and free functions. These can be set to +alternative malloc/free functions if required. Special ones are used in the +non-recursive case for "frames". There is also an optional callout function +that is triggered by the (?) regex item. For Virtual Pascal, these definitions +have to take another form. */ + +#ifndef VPCOMPAT +PCRE_EXP_DECL void *(*pcre_malloc)(size_t); +PCRE_EXP_DECL void (*pcre_free)(void *); +PCRE_EXP_DECL void *(*pcre_stack_malloc)(size_t); +PCRE_EXP_DECL void (*pcre_stack_free)(void *); +PCRE_EXP_DECL int (*pcre_callout)(pcre_callout_block *); +PCRE_EXP_DECL int (*pcre_stack_guard)(void); + +PCRE_EXP_DECL void *(*pcre16_malloc)(size_t); +PCRE_EXP_DECL void (*pcre16_free)(void *); +PCRE_EXP_DECL void *(*pcre16_stack_malloc)(size_t); +PCRE_EXP_DECL void (*pcre16_stack_free)(void *); +PCRE_EXP_DECL int (*pcre16_callout)(pcre16_callout_block *); +PCRE_EXP_DECL int (*pcre16_stack_guard)(void); + +PCRE_EXP_DECL void *(*pcre32_malloc)(size_t); +PCRE_EXP_DECL void (*pcre32_free)(void *); +PCRE_EXP_DECL void *(*pcre32_stack_malloc)(size_t); +PCRE_EXP_DECL void (*pcre32_stack_free)(void *); +PCRE_EXP_DECL int (*pcre32_callout)(pcre32_callout_block *); +PCRE_EXP_DECL int (*pcre32_stack_guard)(void); +#else /* VPCOMPAT */ +PCRE_EXP_DECL void *pcre_malloc(size_t); +PCRE_EXP_DECL void pcre_free(void *); +PCRE_EXP_DECL void *pcre_stack_malloc(size_t); +PCRE_EXP_DECL void pcre_stack_free(void *); +PCRE_EXP_DECL int pcre_callout(pcre_callout_block *); +PCRE_EXP_DECL int pcre_stack_guard(void); + +PCRE_EXP_DECL void *pcre16_malloc(size_t); +PCRE_EXP_DECL void pcre16_free(void *); +PCRE_EXP_DECL void *pcre16_stack_malloc(size_t); +PCRE_EXP_DECL void pcre16_stack_free(void *); +PCRE_EXP_DECL int pcre16_callout(pcre16_callout_block *); +PCRE_EXP_DECL int pcre16_stack_guard(void); + +PCRE_EXP_DECL void *pcre32_malloc(size_t); +PCRE_EXP_DECL void pcre32_free(void *); +PCRE_EXP_DECL void *pcre32_stack_malloc(size_t); +PCRE_EXP_DECL void pcre32_stack_free(void *); +PCRE_EXP_DECL int pcre32_callout(pcre32_callout_block *); +PCRE_EXP_DECL int pcre32_stack_guard(void); +#endif /* VPCOMPAT */ + +/* User defined callback which provides a stack just before the match starts. */ + +typedef pcre_jit_stack *(*pcre_jit_callback)(void *); +typedef pcre16_jit_stack *(*pcre16_jit_callback)(void *); +typedef pcre32_jit_stack *(*pcre32_jit_callback)(void *); + +/* Exported PCRE functions */ + +PCRE_EXP_DECL pcre *pcre_compile(const char *, int, const char **, int *, + const unsigned char *); +PCRE_EXP_DECL pcre16 *pcre16_compile(PCRE_SPTR16, int, const char **, int *, + const unsigned char *); +PCRE_EXP_DECL pcre32 *pcre32_compile(PCRE_SPTR32, int, const char **, int *, + const unsigned char *); +PCRE_EXP_DECL pcre *pcre_compile2(const char *, int, int *, const char **, + int *, const unsigned char *); +PCRE_EXP_DECL pcre16 *pcre16_compile2(PCRE_SPTR16, int, int *, const char **, + int *, const unsigned char *); +PCRE_EXP_DECL pcre32 *pcre32_compile2(PCRE_SPTR32, int, int *, const char **, + int *, const unsigned char *); +PCRE_EXP_DECL int pcre_config(int, void *); +PCRE_EXP_DECL int pcre16_config(int, void *); +PCRE_EXP_DECL int pcre32_config(int, void *); +PCRE_EXP_DECL int pcre_copy_named_substring(const pcre *, const char *, + int *, int, const char *, char *, int); +PCRE_EXP_DECL int pcre16_copy_named_substring(const pcre16 *, PCRE_SPTR16, + int *, int, PCRE_SPTR16, PCRE_UCHAR16 *, int); +PCRE_EXP_DECL int pcre32_copy_named_substring(const pcre32 *, PCRE_SPTR32, + int *, int, PCRE_SPTR32, PCRE_UCHAR32 *, int); +PCRE_EXP_DECL int pcre_copy_substring(const char *, int *, int, int, + char *, int); +PCRE_EXP_DECL int pcre16_copy_substring(PCRE_SPTR16, int *, int, int, + PCRE_UCHAR16 *, int); +PCRE_EXP_DECL int pcre32_copy_substring(PCRE_SPTR32, int *, int, int, + PCRE_UCHAR32 *, int); +PCRE_EXP_DECL int pcre_dfa_exec(const pcre *, const pcre_extra *, + const char *, int, int, int, int *, int , int *, int); +PCRE_EXP_DECL int pcre16_dfa_exec(const pcre16 *, const pcre16_extra *, + PCRE_SPTR16, int, int, int, int *, int , int *, int); +PCRE_EXP_DECL int pcre32_dfa_exec(const pcre32 *, const pcre32_extra *, + PCRE_SPTR32, int, int, int, int *, int , int *, int); +PCRE_EXP_DECL int pcre_exec(const pcre *, const pcre_extra *, PCRE_SPTR, + int, int, int, int *, int); +PCRE_EXP_DECL int pcre16_exec(const pcre16 *, const pcre16_extra *, + PCRE_SPTR16, int, int, int, int *, int); +PCRE_EXP_DECL int pcre32_exec(const pcre32 *, const pcre32_extra *, + PCRE_SPTR32, int, int, int, int *, int); +PCRE_EXP_DECL int pcre_jit_exec(const pcre *, const pcre_extra *, + PCRE_SPTR, int, int, int, int *, int, + pcre_jit_stack *); +PCRE_EXP_DECL int pcre16_jit_exec(const pcre16 *, const pcre16_extra *, + PCRE_SPTR16, int, int, int, int *, int, + pcre16_jit_stack *); +PCRE_EXP_DECL int pcre32_jit_exec(const pcre32 *, const pcre32_extra *, + PCRE_SPTR32, int, int, int, int *, int, + pcre32_jit_stack *); +PCRE_EXP_DECL void pcre_free_substring(const char *); +PCRE_EXP_DECL void pcre16_free_substring(PCRE_SPTR16); +PCRE_EXP_DECL void pcre32_free_substring(PCRE_SPTR32); +PCRE_EXP_DECL void pcre_free_substring_list(const char **); +PCRE_EXP_DECL void pcre16_free_substring_list(PCRE_SPTR16 *); +PCRE_EXP_DECL void pcre32_free_substring_list(PCRE_SPTR32 *); +PCRE_EXP_DECL int pcre_fullinfo(const pcre *, const pcre_extra *, int, + void *); +PCRE_EXP_DECL int pcre16_fullinfo(const pcre16 *, const pcre16_extra *, int, + void *); +PCRE_EXP_DECL int pcre32_fullinfo(const pcre32 *, const pcre32_extra *, int, + void *); +PCRE_EXP_DECL int pcre_get_named_substring(const pcre *, const char *, + int *, int, const char *, const char **); +PCRE_EXP_DECL int pcre16_get_named_substring(const pcre16 *, PCRE_SPTR16, + int *, int, PCRE_SPTR16, PCRE_SPTR16 *); +PCRE_EXP_DECL int pcre32_get_named_substring(const pcre32 *, PCRE_SPTR32, + int *, int, PCRE_SPTR32, PCRE_SPTR32 *); +PCRE_EXP_DECL int pcre_get_stringnumber(const pcre *, const char *); +PCRE_EXP_DECL int pcre16_get_stringnumber(const pcre16 *, PCRE_SPTR16); +PCRE_EXP_DECL int pcre32_get_stringnumber(const pcre32 *, PCRE_SPTR32); +PCRE_EXP_DECL int pcre_get_stringtable_entries(const pcre *, const char *, + char **, char **); +PCRE_EXP_DECL int pcre16_get_stringtable_entries(const pcre16 *, PCRE_SPTR16, + PCRE_UCHAR16 **, PCRE_UCHAR16 **); +PCRE_EXP_DECL int pcre32_get_stringtable_entries(const pcre32 *, PCRE_SPTR32, + PCRE_UCHAR32 **, PCRE_UCHAR32 **); +PCRE_EXP_DECL int pcre_get_substring(const char *, int *, int, int, + const char **); +PCRE_EXP_DECL int pcre16_get_substring(PCRE_SPTR16, int *, int, int, + PCRE_SPTR16 *); +PCRE_EXP_DECL int pcre32_get_substring(PCRE_SPTR32, int *, int, int, + PCRE_SPTR32 *); +PCRE_EXP_DECL int pcre_get_substring_list(const char *, int *, int, + const char ***); +PCRE_EXP_DECL int pcre16_get_substring_list(PCRE_SPTR16, int *, int, + PCRE_SPTR16 **); +PCRE_EXP_DECL int pcre32_get_substring_list(PCRE_SPTR32, int *, int, + PCRE_SPTR32 **); +PCRE_EXP_DECL const unsigned char *pcre_maketables(void); +PCRE_EXP_DECL const unsigned char *pcre16_maketables(void); +PCRE_EXP_DECL const unsigned char *pcre32_maketables(void); +PCRE_EXP_DECL int pcre_refcount(pcre *, int); +PCRE_EXP_DECL int pcre16_refcount(pcre16 *, int); +PCRE_EXP_DECL int pcre32_refcount(pcre32 *, int); +PCRE_EXP_DECL pcre_extra *pcre_study(const pcre *, int, const char **); +PCRE_EXP_DECL pcre16_extra *pcre16_study(const pcre16 *, int, const char **); +PCRE_EXP_DECL pcre32_extra *pcre32_study(const pcre32 *, int, const char **); +PCRE_EXP_DECL void pcre_free_study(pcre_extra *); +PCRE_EXP_DECL void pcre16_free_study(pcre16_extra *); +PCRE_EXP_DECL void pcre32_free_study(pcre32_extra *); +PCRE_EXP_DECL const char *pcre_version(void); +PCRE_EXP_DECL const char *pcre16_version(void); +PCRE_EXP_DECL const char *pcre32_version(void); + +/* Utility functions for byte order swaps. */ +PCRE_EXP_DECL int pcre_pattern_to_host_byte_order(pcre *, pcre_extra *, + const unsigned char *); +PCRE_EXP_DECL int pcre16_pattern_to_host_byte_order(pcre16 *, pcre16_extra *, + const unsigned char *); +PCRE_EXP_DECL int pcre32_pattern_to_host_byte_order(pcre32 *, pcre32_extra *, + const unsigned char *); +PCRE_EXP_DECL int pcre16_utf16_to_host_byte_order(PCRE_UCHAR16 *, + PCRE_SPTR16, int, int *, int); +PCRE_EXP_DECL int pcre32_utf32_to_host_byte_order(PCRE_UCHAR32 *, + PCRE_SPTR32, int, int *, int); + +/* JIT compiler related functions. */ + +PCRE_EXP_DECL pcre_jit_stack *pcre_jit_stack_alloc(int, int); +PCRE_EXP_DECL pcre16_jit_stack *pcre16_jit_stack_alloc(int, int); +PCRE_EXP_DECL pcre32_jit_stack *pcre32_jit_stack_alloc(int, int); +PCRE_EXP_DECL void pcre_jit_stack_free(pcre_jit_stack *); +PCRE_EXP_DECL void pcre16_jit_stack_free(pcre16_jit_stack *); +PCRE_EXP_DECL void pcre32_jit_stack_free(pcre32_jit_stack *); +PCRE_EXP_DECL void pcre_assign_jit_stack(pcre_extra *, + pcre_jit_callback, void *); +PCRE_EXP_DECL void pcre16_assign_jit_stack(pcre16_extra *, + pcre16_jit_callback, void *); +PCRE_EXP_DECL void pcre32_assign_jit_stack(pcre32_extra *, + pcre32_jit_callback, void *); +PCRE_EXP_DECL void pcre_jit_free_unused_memory(void); +PCRE_EXP_DECL void pcre16_jit_free_unused_memory(void); +PCRE_EXP_DECL void pcre32_jit_free_unused_memory(void); diff --git a/src/private/pcre.nim b/src/private/pcre.nim new file mode 100644 index 000000000..ba717efc6 --- /dev/null +++ b/src/private/pcre.nim @@ -0,0 +1,450 @@ + +when not defined(pcreDll): + when hostOS == "windows": + const pcreDll = "pcre.dll" + elif hostOS == "macosx": + const pcreDll = "libpcre(.3|.1|).dylib" + else: + const pcreDll = "libpcre.so(.3|.1|)" + {.pragma: pcreImport, dynlib: pcreDll.} +else: + {.pragma: pcreImport, header: "".} + + +#************************************************ +# Perl-Compatible Regular Expressions * +#*********************************************** +# This is the public header file for the Pcre library, to be #included by +#applications that call the Pcre functions. +# +# Copyright (c) 1997-2014 University of Cambridge +# +#----------------------------------------------------------------------------- +#Redistribution and use in source and binary forms, with or without +#modification, are permitted provided that the following conditions are met: +# +# Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# +# Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# Neither the name of the University of Cambridge nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +#AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +#IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +#ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +#LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +#CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +#SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +#INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +#ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +#POSSIBILITY OF SUCH DAMAGE. +#----------------------------------------------------------------------------- +# +# The current Pcre version information. + + +const + MAJOR* = 8 + MINOR* = 36 + PRERELEASE* = true + DATE* = 2014 - 9 - 26 + +# When an application links to a Pcre DLL in Windows, the symbols that are +#imported have to be identified as such. When building PCRE, the appropriate +#export setting is defined in pcre_internal.h, which includes this file. So we +#don't change existing definitions of PCRE_EXP_DECL and PCRECPP_EXP_DECL. +# By default, we use the standard "extern" declarations. +# Have to include stdlib.h in order to ensure that size_t is defined; +#it is needed here for malloc. + +# Allow for C++ users +# Public options. Some are compile-time only, some are run-time only, and some +#are both. Most of the compile-time options are saved with the compiled regex so +#that they can be inspected during studying (and therefore JIT compiling). Note +#that pcre_study() has its own set of options. Originally, all the options +#defined here used distinct bits. However, almost all the bits in a 32-bit word +#are now used, so in order to conserve them, option bits that were previously +#only recognized at matching time (i.e. by pcre_exec() or pcre_dfa_exec()) may +#also be used for compile-time options that affect only compiling and are not +#relevant for studying or JIT compiling. +# +#Some options for pcre_compile() change its behaviour but do not affect the +#behaviour of the execution functions. Other options are passed through to the +#execution functions and affect their behaviour, with or without affecting the +#behaviour of pcre_compile(). +# +#Options that can be passed to pcre_compile() are tagged Cx below, with these +#variants: +# +#C1 Affects compile only +#C2 Does not affect compile; affects exec, dfa_exec +#C3 Affects compile, exec, dfa_exec +#C4 Affects compile, exec, dfa_exec, study +#C5 Affects compile, exec, study +# +#Options that can be set for pcre_exec() and/or pcre_dfa_exec() are flagged with +#E and D, respectively. They take precedence over C3, C4, and C5 settings passed +#from pcre_compile(). Those that are compatible with JIT execution are flagged +#with J. + +const + CASELESS* = 0x00000001 + MULTILINE* = 0x00000002 + DOTALL* = 0x00000004 + EXTENDED* = 0x00000008 + ANCHORED* = 0x00000010 + DOLLAR_ENDONLY* = 0x00000020 + EXTRA* = 0x00000040 + NOTBOL* = 0x00000080 + NOTEOL* = 0x00000100 + UNGREEDY* = 0x00000200 + NOTEMPTY* = 0x00000400 + UTF8* = 0x00000800 + UTF16* = 0x00000800 + UTF32* = 0x00000800 + NO_AUTO_CAPTURE* = 0x00001000 + NO_UTF8_CHECK* = 0x00002000 + NO_UTF16_CHECK* = 0x00002000 + NO_UTF32_CHECK* = 0x00002000 + AUTO_CALLOUT* = 0x00004000 + PARTIAL_SOFT* = 0x00008000 + PARTIAL* = 0x00008000 + +# This pair use the same bit. + +const + NEVER_UTF* = 0x00010000 + DFA_SHORTEST* = 0x00010000 + +# This pair use the same bit. + +const + NO_AUTO_POSSESS* = 0x00020000 + DFA_RESTART* = 0x00020000 + FIRSTLINE* = 0x00040000 + DUPNAMES* = 0x00080000 + NEWLINE_CR* = 0x00100000 + NEWLINE_LF* = 0x00200000 + NEWLINE_CRLF* = 0x00300000 + NEWLINE_ANY* = 0x00400000 + NEWLINE_ANYCRLF* = 0x00500000 + BSR_ANYCRLF* = 0x00800000 + BSR_UNICODE* = 0x01000000 + JAVASCRIPT_COMPAT* = 0x02000000 + NO_START_OPTIMIZE* = 0x04000000 + NO_START_OPTIMISE* = 0x04000000 + PARTIAL_HARD* = 0x08000000 + NOTEMPTY_ATSTART* = 0x10000000 + UCP* = 0x20000000 + +# Exec-time and get/set-time error codes + +const + ERROR_NOMATCH* = (- 1) + ERROR_NULL* = (- 2) + ERROR_BADOPTION* = (- 3) + ERROR_BADMAGIC* = (- 4) + ERROR_UNKNOWN_OPCODE* = (- 5) + ERROR_UNKNOWN_NODE* = (- 5) # For backward compatibility + ERROR_NOMEMORY* = (- 6) + ERROR_NOSUBSTRING* = (- 7) + ERROR_MATCHLIMIT* = (- 8) + ERROR_CALLOUT* = (- 9) # Never used by Pcre itself + ERROR_BADUTF8* = (- 10) # Same for 8/16/32 + ERROR_BADUTF16* = (- 10) # Same for 8/16/32 + ERROR_BADUTF32* = (- 10) # Same for 8/16/32 + ERROR_BADUTF8_OFFSET* = (- 11) # Same for 8/16 + ERROR_BADUTF16_OFFSET* = (- 11) # Same for 8/16 + ERROR_PARTIAL* = (- 12) + ERROR_BADPARTIAL* = (- 13) + ERROR_INTERNAL* = (- 14) + ERROR_BADCOUNT* = (- 15) + ERROR_DFA_UITEM* = (- 16) + ERROR_DFA_UCOND* = (- 17) + ERROR_DFA_UMLIMIT* = (- 18) + ERROR_DFA_WSSIZE* = (- 19) + ERROR_DFA_RECURSE* = (- 20) + ERROR_RECURSIONLIMIT* = (- 21) + ERROR_NULLWSLIMIT* = (- 22) # No longer actually used + ERROR_BADNEWLINE* = (- 23) + ERROR_BADOFFSET* = (- 24) + ERROR_SHORTUTF8* = (- 25) + ERROR_SHORTUTF16* = (- 25) # Same for 8/16 + ERROR_RECURSELOOP* = (- 26) + ERROR_JIT_STACKLIMIT* = (- 27) + ERROR_BADMODE* = (- 28) + ERROR_BADENDIANNESS* = (- 29) + ERROR_DFA_BADRESTART* = (- 30) + ERROR_JIT_BADOPTION* = (- 31) + ERROR_BADLENGTH* = (- 32) + ERROR_UNSET* = (- 33) + +# Specific error codes for UTF-8 validity checks + +const + UTF8_ERR0* = 0 + UTF8_ERR1* = 1 + UTF8_ERR2* = 2 + UTF8_ERR3* = 3 + UTF8_ERR4* = 4 + UTF8_ERR5* = 5 + UTF8_ERR6* = 6 + UTF8_ERR7* = 7 + UTF8_ERR8* = 8 + UTF8_ERR9* = 9 + UTF8_ERR10* = 10 + UTF8_ERR11* = 11 + UTF8_ERR12* = 12 + UTF8_ERR13* = 13 + UTF8_ERR14* = 14 + UTF8_ERR15* = 15 + UTF8_ERR16* = 16 + UTF8_ERR17* = 17 + UTF8_ERR18* = 18 + UTF8_ERR19* = 19 + UTF8_ERR20* = 20 + UTF8_ERR21* = 21 + UTF8_ERR22* = 22 + +# Specific error codes for UTF-16 validity checks + +const + UTF16_ERR0* = 0 + UTF16_ERR1* = 1 + UTF16_ERR2* = 2 + UTF16_ERR3* = 3 + UTF16_ERR4* = 4 + +# Specific error codes for UTF-32 validity checks + +const + UTF32_ERR0* = 0 + UTF32_ERR1* = 1 + UTF32_ERR2* = 2 + UTF32_ERR3* = 3 + +# Request types for pcre_fullinfo() + +const + INFO_OPTIONS* = 0 + INFO_SIZE* = 1 + INFO_CAPTURECOUNT* = 2 + INFO_BACKREFMAX* = 3 + INFO_FIRSTBYTE* = 4 + INFO_FIRSTCHAR* = 4 + INFO_FIRSTTABLE* = 5 + INFO_LASTLITERAL* = 6 + INFO_NAMEENTRYSIZE* = 7 + INFO_NAMECOUNT* = 8 + INFO_NAMETABLE* = 9 + INFO_STUDYSIZE* = 10 + INFO_DEFAULT_TABLES* = 11 + INFO_OKPARTIAL* = 12 + INFO_JCHANGED* = 13 + INFO_HASCRORLF* = 14 + INFO_MINLENGTH* = 15 + INFO_JIT* = 16 + INFO_JITSIZE* = 17 + INFO_MAXLOOKBEHIND* = 18 + INFO_FIRSTCHARACTER* = 19 + INFO_FIRSTCHARACTERFLAGS* = 20 + INFO_REQUIREDCHAR* = 21 + INFO_REQUIREDCHARFLAGS* = 22 + INFO_MATCHLIMIT* = 23 + INFO_RECURSIONLIMIT* = 24 + INFO_MATCH_EMPTY* = 25 + +# Request types for pcre_config(). Do not re-arrange, in order to remain +#compatible. + +const + CONFIG_UTF8* = 0 + CONFIG_NEWLINE* = 1 + CONFIG_LINK_SIZE* = 2 + CONFIG_POSIX_MALLOC_THRESHOLD* = 3 + CONFIG_MATCH_LIMIT* = 4 + CONFIG_STACKRECURSE* = 5 + CONFIG_UNICODE_PROPERTIES* = 6 + CONFIG_MATCH_LIMIT_RECURSION* = 7 + CONFIG_BSR* = 8 + CONFIG_JIT* = 9 + CONFIG_UTF16* = 10 + CONFIG_JITTARGET* = 11 + CONFIG_UTF32* = 12 + CONFIG_PARENS_LIMIT* = 13 + +# Request types for pcre_study(). Do not re-arrange, in order to remain +#compatible. + +const + STUDY_JIT_COMPILE* = 0x00000001 + STUDY_JIT_PARTIAL_SOFT_COMPILE* = 0x00000002 + STUDY_JIT_PARTIAL_HARD_COMPILE* = 0x00000004 + STUDY_EXTRA_NEEDED* = 0x00000008 + +# Bit flags for the pcre[16|32]_extra structure. Do not re-arrange or redefine +#these bits, just add new ones on the end, in order to remain compatible. + +const + EXTRA_STUDY_DATA* = 0x00000001 + EXTRA_MATCH_LIMIT* = 0x00000002 + EXTRA_CALLOUT_DATA* = 0x00000004 + EXTRA_TABLES* = 0x00000008 + EXTRA_MATCH_LIMIT_RECURSION* = 0x00000010 + EXTRA_MARK* = 0x00000020 + EXTRA_EXECUTABLE_JIT* = 0x00000040 + +# Types + +type + Pcre* = object + Pcre16* = object + Pcre32* = object + jit_stack* = object + jit_stack16* = object + jit_stack32* = object + + +# When Pcre is compiled as a C++ library, the subject pointer type can be +#replaced with a custom type. For conventional use, the public interface is a +#const char *. + +type + SPTR* = cstring + +# The structure for passing additional data to pcre_exec(). This is defined in +#such as way as to be extensible. Always add new fields at the end, in order to +#remain compatible. + +type + ExtraData* {.importc: "pcre_extra", header: "".} = object + flags* {.importc: "flags".}: culong # Bits for which fields are set + study_data* {.importc: "study_data".}: pointer # Opaque data from pcre_study() + match_limit* {.importc: "match_limit".}: culong # Maximum number of calls to match() + callout_data* {.importc: "callout_data".}: pointer # Data passed back in callouts + tables* {.importc: "tables".}: ptr cuchar # Pointer to character tables + match_limit_recursion* {.importc: "match_limit_recursion".}: culong # Max + # recursive calls to match() + mark* {.importc: "mark".}: ptr ptr cuchar # For passing back a mark pointer + executable_jit* {.importc: "executable_jit".}: pointer # Contains a pointer to a compiled jit code + +# The structure for passing out data via the pcre_callout_function. We use a +#structure so that new fields can be added on the end in future versions, +#without changing the API of the function, thereby allowing old clients to work +#without modification. + +type + callout_block* {.importc: "pcre_callout_block", header: "".} = object + version* {.importc: "version".}: cint # Identifies version of block + # ------------------------ Version 0 ------------------------------- + callout_number* {.importc: "callout_number".}: cint # Number compiled into pattern + offset_vector* {.importc: "offset_vector".}: ptr cint # The offset vector + subject* {.importc: "subject".}: SPTR # The subject being matched + subject_length* {.importc: "subject_length".}: cint # The length of the subject + start_match* {.importc: "start_match".}: cint # Offset to start of this match attempt + current_position* {.importc: "current_position".}: cint # Where we currently are in the subject + capture_top* {.importc: "capture_top".}: cint # Max current capture + capture_last* {.importc: "capture_last".}: cint # Most recently closed capture + callout_data* {.importc: "callout_data".}: pointer # Data passed in with the call + # ------------------- Added for Version 1 + # -------------------------- + pattern_position* {.importc: "pattern_position".}: cint # Offset to next item in the pattern + next_item_length* {.importc: "next_item_length".}: cint # Length of next item in the pattern + # ------------------- Added for Version 2 + # -------------------------- + mark* {.importc: "mark".}: ptr cuchar # Pointer to current mark or NULL + # + # ------------------------------------------------------------------ +# Indirection for store get and free functions. These can be set to +#alternative malloc/free functions if required. Special ones are used in the +#non-recursive case for "frames". There is also an optional callout function +#that is triggered by the (?) regex item. For Virtual Pascal, these definitions +#have to take another form. + +var malloc*: proc (a2: csize): pointer {.cdecl.} +var free*: proc (a2: pointer) {.cdecl.} +var stack_malloc*: proc (a2: csize): pointer {.cdecl.} +var stack_free*: proc (a2: pointer) {.cdecl.} +var callout*: proc (a2: ptr callout_block): cint {.cdecl.} +var stack_guard*: proc (): cint {.cdecl.} + +# User defined callback which provides a stack just before the match starts. + +type + jit_callback* = proc (a2: pointer): ptr jit_stack {.cdecl.} + +# Exported Pcre functions + +proc compile*(a2: cstring; a3: cint; a4: ptr cstring; a5: ptr cint; + a6: ptr cuchar): ptr Pcre {.cdecl, importc: "pcre_compile", + pcreImport.} +proc compile2*(a2: cstring; a3: cint; a4: ptr cint; a5: ptr cstring; + a6: ptr cint; a7: ptr cuchar): ptr Pcre {.cdecl, + importc: "pcre_compile2", pcreImport.} +proc config*(a2: cint; a3: pointer): cint {.cdecl, importc: "pcre_config", + pcreImport.} +proc copy_named_substring*(a2: ptr Pcre; a3: cstring; a4: ptr cint; a5: cint; + a6: cstring; a7: cstring; a8: cint): cint {.cdecl, + importc: "pcre_copy_named_substring", pcreImport.} +proc copy_substring*(a2: cstring; a3: ptr cint; a4: cint; a5: cint; a6: cstring; + a7: cint): cint {.cdecl, importc: "pcre_copy_substring", + pcreImport.} +proc dfa_exec*(a2: ptr Pcre; a3: ptr ExtraData; a4: cstring; a5: cint; a6: cint; + a7: cint; a8: ptr cint; a9: cint; a10: ptr cint; a11: cint): cint {. + cdecl, importc: "pcre_dfa_exec", pcreImport.} +proc exec*(a2: ptr Pcre; a3: ptr ExtraData; a4: SPTR; a5: cint; a6: cint; a7: cint; + a8: ptr cint; a9: cint): cint {.cdecl, importc: "pcre_exec", + pcreImport.} +proc jit_exec*(a2: ptr Pcre; a3: ptr ExtraData; a4: SPTR; a5: cint; a6: cint; + a7: cint; a8: ptr cint; a9: cint; a10: ptr jit_stack): cint {. + cdecl, importc: "pcre_jit_exec", pcreImport.} +proc free_substring*(a2: cstring) {.cdecl, importc: "pcre_free_substring", + pcreImport.} +proc free_substring_list*(a2: ptr cstring) {.cdecl, + importc: "pcre_free_substring_list", pcreImport.} +proc fullinfo*(a2: ptr Pcre; a3: ptr ExtraData; a4: cint; a5: pointer): cint {. + cdecl, importc: "pcre_fullinfo", pcreImport.} +proc get_named_substring*(a2: ptr Pcre; a3: cstring; a4: ptr cint; a5: cint; + a6: cstring; a7: cstringArray): cint {.cdecl, + importc: "pcre_get_named_substring", pcreImport.} +proc get_stringnumber*(a2: ptr Pcre; a3: cstring): cint {.cdecl, + importc: "pcre_get_stringnumber", pcreImport.} +proc get_stringtable_entries*(a2: ptr Pcre; a3: cstring; a4: cstringArray; + a5: cstringArray): cint {.cdecl, + importc: "pcre_get_stringtable_entries", pcreImport.} +proc get_substring*(a2: cstring; a3: ptr cint; a4: cint; a5: cint; + a6: cstringArray): cint {.cdecl, + importc: "pcre_get_substring", pcreImport.} +proc get_substring_list*(a2: cstring; a3: ptr cint; a4: cint; + a5: ptr cstringArray): cint {.cdecl, + importc: "pcre_get_substring_list", pcreImport.} +proc maketables*(): ptr cuchar {.cdecl, importc: "pcre_maketables", + pcreImport.} +proc refcount*(a2: ptr Pcre; a3: cint): cint {.cdecl, importc: "pcre_refcount", + pcreImport.} +proc study*(a2: ptr Pcre; a3: cint; a4: ptr cstring): ptr ExtraData {.cdecl, + importc: "pcre_study", pcreImport.} +proc free_study*(a2: ptr ExtraData) {.cdecl, importc: "pcre_free_study", + pcreImport.} +proc version*(): cstring {.cdecl, importc: "pcre_version", pcreImport.} +# Utility functions for byte order swaps. + +proc pattern_to_host_byte_order*(a2: ptr Pcre; a3: ptr ExtraData; a4: ptr cuchar): cint {. + cdecl, importc: "pcre_pattern_to_host_byte_order", pcreImport.} +# JIT compiler related functions. + +proc jit_stack_alloc*(a2: cint; a3: cint): ptr jit_stack {.cdecl, + importc: "pcre_jit_stack_alloc", pcreImport.} +proc jit_stack_free*(a2: ptr jit_stack) {.cdecl, importc: "pcre_jit_stack_free", + pcreImport.} +proc assign_jit_stack*(a2: ptr ExtraData; a3: jit_callback; a4: pointer) {.cdecl, + importc: "pcre_assign_jit_stack", pcreImport.} +proc jit_free_unused_memory*() {.cdecl, importc: "pcre_jit_free_unused_memory", + pcreImport.} From dec2f9efa9dd88d4bce0d42fa25dd758b90fa1a1 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Fri, 9 Jan 2015 19:40:41 -0500 Subject: [PATCH 0009/1263] Implement regex initialization --- src/nre.nim | 97 ++++++++++++++++++++++++++++++++++++++++++++ src/private/util.nim | 7 ++++ 2 files changed, 104 insertions(+) create mode 100644 src/nre.nim create mode 100644 src/private/util.nim diff --git a/src/nre.nim b/src/nre.nim new file mode 100644 index 000000000..79d689bcd --- /dev/null +++ b/src/nre.nim @@ -0,0 +1,97 @@ +import private.pcre as pcre +import private.util +import tables +import unsigned +from strutils import toLower + +# PCRE Options {{{ + +let Options: Table[string, int] = { + "8" : pcre.UTF8, + "9" : pcre.NEVER_UTF, + "?" : pcre.NO_UTF8_CHECK, + "A" : pcre.ANCHORED, + # "C" : pcre.AUTO_CALLOUT, unsuported XXX + "E" : pcre.DOLLAR_ENDONLY, + "f" : pcre.FIRSTLINE, + "i" : pcre.CASELESS, + "J" : pcre.DUPNAMES, + "m" : pcre.MULTILINE, + "N" : pcre.NO_AUTO_CAPTURE, + "O" : pcre.NO_AUTO_POSSESS, + "s" : pcre.DOTALL, + "U" : pcre.UNGREEDY, + "W" : pcre.UCP, + "X" : pcre.EXTRA, + "x" : pcre.EXTENDED, + "Y" : pcre.NO_START_OPTIMIZE, + + "any" : pcre.NEWLINE_ANY, + "anycrlf" : pcre.NEWLINE_ANYCRLF, + "cr" : pcre.NEWLINE_CR, + "crlf" : pcre.NEWLINE_CRLF, + "lf" : pcre.NEWLINE_LF, + "bsr_anycrlf" : pcre.BSR_ANYCRLF, + "bsr_unicode" : pcre.BSR_UNICODE, + "js" : pcre.JAVASCRIPT_COMPAT, +}.toTable + +proc tokenizeOptions(opts: string): tuple[flags: int, study: bool] = + result = (0, false) + + var longOpt: string = nil + for i, c in opts: + # Handle long options {{{ + if c == '<': + longOpt = "" + continue + + if longOpt != nil: + if c == '>': + result.flags = result.flags or Options.fget(longOpt) + longOpt = nil + else: + longOpt.add(c.toLower) + continue + # }}} + + if c == 'S': # handle study + result.study = true + continue + + result.flags = result.flags or Options.fget($c) + +# }}} + +type + Regex* = ref object + pcreObj: ptr pcre.Pcre + pcreExtra: ptr pcre.ExtraData + + SyntaxError* = ref object of Exception + pos*: int ## the location of the syntax error in bytes + pattern*: string ## the pattern that caused the problem + + StudyError* = ref object of Exception + +proc initRegex*(pattern: string, options = "Sx"): Regex = + new result + + var errorMsg: cstring + var errOffset: cint + + let opts = tokenizeOptions(options) + + result.pcreObj = pcre.compile(cstring(pattern), + # better hope int is at least 4 bytes.. + cint(opts.flags), addr errorMsg, + addr errOffset, nil) + if result.pcreObj == nil: + # failed to compile + raise SyntaxError(msg: $errorMsg, pos: errOffset, pattern: pattern) + + if opts.study: + # XXX investigate JIT + result.pcreExtra = pcre.study(result.pcreObj, 0x0, addr errorMsg) + if result.pcreExtra == nil: + raise StudyError(msg: $errorMsg) diff --git a/src/private/util.nim b/src/private/util.nim new file mode 100644 index 000000000..afd90a485 --- /dev/null +++ b/src/private/util.nim @@ -0,0 +1,7 @@ +import tables + +proc fget*[K, V](self: Table[K, V], key: K): V = + if self.hasKey(key): + return self[key] + else: + raise newException(KeyError, "Key does not exist in table: " & $key) From 685e4a1f0b9038e102e18bf9ed18c9d0f5a67b98 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Fri, 9 Jan 2015 19:41:12 -0500 Subject: [PATCH 0010/1263] Add unit tests --- test/init.nim | 26 ++++++++++++++++++++++++++ test/testall.nim | 1 + 2 files changed, 27 insertions(+) create mode 100644 test/init.nim create mode 100644 test/testall.nim diff --git a/test/init.nim b/test/init.nim new file mode 100644 index 000000000..a3c9f24fe --- /dev/null +++ b/test/init.nim @@ -0,0 +1,26 @@ +import unittest +include nre + +suite "Test NRE initialization": + test "correct intialization": + check(initRegex("[0-9]+") != nil) + check(initRegex("[0-9]+", "iS") != nil) + + test "correct options": + expect(SyntaxError): # ValueError would be bad + discard initRegex("[0-9]+", + "89?AEfiJmNOsUWXxY") + + test "incorrect options": + expect(KeyError): discard initRegex("[0-9]+", "a") + expect(KeyError): discard initRegex("[0-9]+", "") + + test "invalid regex": + expect(SyntaxError): discard initRegex("[0-9") + try: + discard initRegex("[0-9") + except SyntaxError: + let ex = SyntaxError(getCurrentException()) + check(ex.pos == 4) + check(ex.pattern == "[0-9") + diff --git a/test/testall.nim b/test/testall.nim new file mode 100644 index 000000000..214787264 --- /dev/null +++ b/test/testall.nim @@ -0,0 +1 @@ +include init From 3a6e7941cfbf2714c8ee67e5c91f6fcb644caa43 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Fri, 9 Jan 2015 20:07:33 -0500 Subject: [PATCH 0011/1263] Fix typos --- are.nimble => nre.nimble | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename are.nimble => nre.nimble (88%) diff --git a/are.nimble b/nre.nimble similarity index 88% rename from are.nimble rename to nre.nimble index e68994e1c..74e982222 100644 --- a/are.nimble +++ b/nre.nimble @@ -1,5 +1,5 @@ [Package] -name = "are" +name = "nre" version = "0.1.0" description = "Yet another PCRE library" license = "MIT" From c4d536f5817ec8b1e4a6342547e67f34884890f7 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 10 Jan 2015 08:14:49 -0500 Subject: [PATCH 0012/1263] Extend Regex, add RegexMatch --- src/nre.nim | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/nre.nim b/src/nre.nim index 79d689bcd..381c80708 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -65,8 +65,13 @@ proc tokenizeOptions(opts: string): tuple[flags: int, study: bool] = type Regex* = ref object - pcreObj: ptr pcre.Pcre - pcreExtra: ptr pcre.ExtraData + pattern: string # not nil + pcreObj: ptr pcre.Pcre # not nil + pcreExtra: ptr pcre.ExtraData ## nil + + RegexMatch* = object + pattern: Regex + matchBounds: Slice[int] SyntaxError* = ref object of Exception pos*: int ## the location of the syntax error in bytes @@ -76,6 +81,7 @@ type proc initRegex*(pattern: string, options = "Sx"): Regex = new result + result.pattern = pattern var errorMsg: cstring var errOffset: cint From bfba4b99833b0f92ba58e549117cfa7c66367eac Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 10 Jan 2015 08:16:09 -0500 Subject: [PATCH 0013/1263] Remove DUPNAMES option It makes the rest of the implementation more complicated and is confusing anyway. The user expects a 1:1 mapping between a match and a name --- src/nre.nim | 1 - test/init.nim | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/src/nre.nim b/src/nre.nim index 381c80708..feae0c228 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -15,7 +15,6 @@ let Options: Table[string, int] = { "E" : pcre.DOLLAR_ENDONLY, "f" : pcre.FIRSTLINE, "i" : pcre.CASELESS, - "J" : pcre.DUPNAMES, "m" : pcre.MULTILINE, "N" : pcre.NO_AUTO_CAPTURE, "O" : pcre.NO_AUTO_POSSESS, diff --git a/test/init.nim b/test/init.nim index a3c9f24fe..eddcd6aca 100644 --- a/test/init.nim +++ b/test/init.nim @@ -9,7 +9,7 @@ suite "Test NRE initialization": test "correct options": expect(SyntaxError): # ValueError would be bad discard initRegex("[0-9]+", - "89?AEfiJmNOsUWXxY") + "89?AEfimNOsUWXxY") test "incorrect options": expect(KeyError): discard initRegex("[0-9]+", "a") From 00b047a6600b53a6439e9bf78d05894c5dd10297 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 10 Jan 2015 11:27:46 -0500 Subject: [PATCH 0014/1263] Implement foundation for named captures --- src/nre.nim | 33 ++++++++++++++++++++++++++++++++- test/captures.nim | 7 +++++++ 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 test/captures.nim diff --git a/src/nre.nim b/src/nre.nim index feae0c228..3f06d33bb 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -2,7 +2,7 @@ import private.pcre as pcre import private.util import tables import unsigned -from strutils import toLower +from strutils import toLower, `%` # PCRE Options {{{ @@ -100,3 +100,34 @@ proc initRegex*(pattern: string, options = "Sx"): Regex = result.pcreExtra = pcre.study(result.pcreObj, 0x0, addr errorMsg) if result.pcreExtra == nil: raise StudyError(msg: $errorMsg) + +proc getinfo[T](self: Regex, opt: cint): T = + let retcode = pcre.fullinfo(self.pcreObj, self.pcreExtra, opt, addr result) + + if retcode < 0: + raise newException(FieldError, "Invalid getinfo for $1, errno $2" % [$opt, $retcode]) + +proc getCaptureCount(self: Regex): int = + # get the maximum number of captures + return getinfo[int](self, pcre.INFO_CAPTURECOUNT) + +type UncheckedArray {.unchecked.}[T] = array[0 .. 0, T] +proc getNameToNumberTable(self: Regex): Table[string, int] = + let entryCount = getinfo[cint](self, pcre.INFO_NAMECOUNT) + let entrySize = getinfo[cint](self, pcre.INFO_NAMEENTRYSIZE) + let table = cast[ptr UncheckedArray[uint8]]( + getinfo[int](self, pcre.INFO_NAMETABLE)) + + result = initTable[string, int]() + + for i in 0 .. 1(?2(?3))(?'v4'4))()")) == + { "v1" : 1, "v2" : 2, "v3" : 3, "v4" : 4 }.toTable()) From ca4cf242991ca46fea9cd94afe8207b8bb8fe2f1 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 10 Jan 2015 12:30:43 -0500 Subject: [PATCH 0015/1263] Implement correct destruction --- src/nre.nim | 11 ++++++++++- src/private/pcre.nim | 15 +++++++-------- 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/src/nre.nim b/src/nre.nim index 3f06d33bb..2611ee7f6 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -78,8 +78,14 @@ type StudyError* = ref object of Exception +proc destroyRegex(self: Regex) = + pcre.free_substring(cast[cstring](self.pcreObj)) + self.pcreObj = nil + if self.pcreExtra != nil: + pcre.free_study(self.pcreExtra) + proc initRegex*(pattern: string, options = "Sx"): Regex = - new result + new(result, destroyRegex) result.pattern = pattern var errorMsg: cstring @@ -131,3 +137,6 @@ proc getNameToNumberTable(self: Regex): Table[string, int] = idx += 1 result[name] = num + +proc exec*(self: Regex, str: string): RegexMatch = + discard diff --git a/src/private/pcre.nim b/src/private/pcre.nim index ba717efc6..385f85bc1 100644 --- a/src/private/pcre.nim +++ b/src/private/pcre.nim @@ -1,4 +1,3 @@ - when not defined(pcreDll): when hostOS == "windows": const pcreDll = "pcre.dll" @@ -10,7 +9,6 @@ when not defined(pcreDll): else: {.pragma: pcreImport, header: "".} - #************************************************ # Perl-Compatible Regular Expressions * #*********************************************** @@ -368,12 +366,13 @@ type #that is triggered by the (?) regex item. For Virtual Pascal, these definitions #have to take another form. -var malloc*: proc (a2: csize): pointer {.cdecl.} -var free*: proc (a2: pointer) {.cdecl.} -var stack_malloc*: proc (a2: csize): pointer {.cdecl.} -var stack_free*: proc (a2: pointer) {.cdecl.} -var callout*: proc (a2: ptr callout_block): cint {.cdecl.} -var stack_guard*: proc (): cint {.cdecl.} +{.emit: "#include ".} +proc malloc*(a2: csize): pointer {.cdecl, importc: "pcre_malloc", pcreImport.} +proc free*(a2: pointer) {.cdecl, importc: "pcre_free", pcreImport.} +proc stack_malloc*(a2: csize): pointer {.cdecl, importc: "pcre_stack_malloc", pcreImport.} +proc stack_free*(a2: pointer) {.cdecl, importc: "pcre_free", pcreImport.} +proc callout*(a2: ptr callout_block): cint {.cdecl, importc: "pcre_callout", pcreImport.} +proc stack_guard*(): cint {.cdecl, importc: "pcre_stack_guard", pcreImport.} # User defined callback which provides a stack just before the match starts. From be984d3b0758dae281f2778b2ee07519715d474d Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 10 Jan 2015 12:31:03 -0500 Subject: [PATCH 0016/1263] Change test execution technique --- test/testall.nim | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/test/testall.nim b/test/testall.nim index 214787264..71f486805 100644 --- a/test/testall.nim +++ b/test/testall.nim @@ -1 +1,3 @@ -include init +import nre +import init +import captures From 613d12c7bfc9e191c1dfcf697d55dbe434e47d06 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 10 Jan 2015 13:31:13 -0500 Subject: [PATCH 0017/1263] Simplify thin wrapper --- src/nre.nim | 3 +++ src/private/pcre.nim | 14 +++----------- 2 files changed, 6 insertions(+), 11 deletions(-) diff --git a/src/nre.nim b/src/nre.nim index 2611ee7f6..1cd534cc0 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -78,6 +78,7 @@ type StudyError* = ref object of Exception +# Creation & Destruction {{{ proc destroyRegex(self: Regex) = pcre.free_substring(cast[cstring](self.pcreObj)) self.pcreObj = nil @@ -106,11 +107,13 @@ proc initRegex*(pattern: string, options = "Sx"): Regex = result.pcreExtra = pcre.study(result.pcreObj, 0x0, addr errorMsg) if result.pcreExtra == nil: raise StudyError(msg: $errorMsg) +# }}} proc getinfo[T](self: Regex, opt: cint): T = let retcode = pcre.fullinfo(self.pcreObj, self.pcreExtra, opt, addr result) if retcode < 0: + # XXX Error message that doesn't expose implementation details raise newException(FieldError, "Invalid getinfo for $1, errno $2" % [$opt, $retcode]) proc getCaptureCount(self: Regex): int = diff --git a/src/private/pcre.nim b/src/private/pcre.nim index 385f85bc1..41afa72fb 100644 --- a/src/private/pcre.nim +++ b/src/private/pcre.nim @@ -309,14 +309,6 @@ type jit_stack16* = object jit_stack32* = object - -# When Pcre is compiled as a C++ library, the subject pointer type can be -#replaced with a custom type. For conventional use, the public interface is a -#const char *. - -type - SPTR* = cstring - # The structure for passing additional data to pcre_exec(). This is defined in #such as way as to be extensible. Always add new fields at the end, in order to #remain compatible. @@ -344,7 +336,7 @@ type # ------------------------ Version 0 ------------------------------- callout_number* {.importc: "callout_number".}: cint # Number compiled into pattern offset_vector* {.importc: "offset_vector".}: ptr cint # The offset vector - subject* {.importc: "subject".}: SPTR # The subject being matched + subject* {.importc: "subject".}: cstring # The subject being matched subject_length* {.importc: "subject_length".}: cint # The length of the subject start_match* {.importc: "start_match".}: cint # Offset to start of this match attempt current_position* {.importc: "current_position".}: cint # Where we currently are in the subject @@ -398,10 +390,10 @@ proc copy_substring*(a2: cstring; a3: ptr cint; a4: cint; a5: cint; a6: cstring; proc dfa_exec*(a2: ptr Pcre; a3: ptr ExtraData; a4: cstring; a5: cint; a6: cint; a7: cint; a8: ptr cint; a9: cint; a10: ptr cint; a11: cint): cint {. cdecl, importc: "pcre_dfa_exec", pcreImport.} -proc exec*(a2: ptr Pcre; a3: ptr ExtraData; a4: SPTR; a5: cint; a6: cint; a7: cint; +proc exec*(a2: ptr Pcre; a3: ptr ExtraData; a4: cstring; a5: cint; a6: cint; a7: cint; a8: ptr cint; a9: cint): cint {.cdecl, importc: "pcre_exec", pcreImport.} -proc jit_exec*(a2: ptr Pcre; a3: ptr ExtraData; a4: SPTR; a5: cint; a6: cint; +proc jit_exec*(a2: ptr Pcre; a3: ptr ExtraData; a4: cstring; a5: cint; a6: cint; a7: cint; a8: ptr cint; a9: cint; a10: ptr jit_stack): cint {. cdecl, importc: "pcre_jit_exec", pcreImport.} proc free_substring*(a2: cstring) {.cdecl, importc: "pcre_free_substring", From 2db1a54710db4684f5f816ea4541f0998c11de9e Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 10 Jan 2015 14:11:43 -0500 Subject: [PATCH 0018/1263] Implement regex execution --- nre.nimble | 4 +++- src/nre.nim | 32 +++++++++++++++++++++++++++++--- 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/nre.nimble b/nre.nimble index 74e982222..48cabc177 100644 --- a/nre.nimble +++ b/nre.nimble @@ -1,9 +1,11 @@ [Package] name = "nre" +author = "Flaviu Tamas" version = "0.1.0" description = "Yet another PCRE library" license = "MIT" srcDir = "src" [Deps] -Requires: "nim >= 0.10.1" +Requires: "nim >= 0.10.0" +Requires: "optional_t >= 1.0" diff --git a/src/nre.nim b/src/nre.nim index 1cd534cc0..5839cab2a 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -3,6 +3,8 @@ import private.util import tables import unsigned from strutils import toLower, `%` +from math import ceil +import optional_t # PCRE Options {{{ @@ -70,7 +72,9 @@ type RegexMatch* = object pattern: Regex - matchBounds: Slice[int] + matchBounds: seq[Slice[cint]] ## First item is the bounds of the match + ## Other items are the captures + ## `a` is inclusive start, `b` is exclusive end SyntaxError* = ref object of Exception pos*: int ## the location of the syntax error in bytes @@ -141,5 +145,27 @@ proc getNameToNumberTable(self: Regex): Table[string, int] = result[name] = num -proc exec*(self: Regex, str: string): RegexMatch = - discard +proc exec*(self: Regex, str: string, start = 0): Option[RegexMatch] = + var result: RegexMatch + result.pattern = self + # See PCRE man pages. + # 2x capture count to make room for start-end pairs + # 1x capture count as slack space for PCRE + let vecsize = (self.getCaptureCount() + 1) * 3 + # div 2 because each element is 2 cints long + result.matchBounds = newSeq[Slice[cint]](ceil(vecsize / 2).int) + result.matchBounds.setLen(vecsize div 3) + + let execRet = pcre.exec(self.pcreObj, + self.pcreExtra, + cstring(str), + cint(str.len), + cint(start), + cint(0), + cast[ptr cint](addr result.matchBounds[0]), cint(vecsize)) + if execRet >= 0: + return Some(result) + elif execRet == pcre.ERROR_NOMATCH: + return None[RegexMatch]() + else: + raise newException(AssertionError, "Internal error: errno " & $execRet) From 721ea11628a3717b07c1867096e817f06068a24e Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 10 Jan 2015 16:20:25 -0500 Subject: [PATCH 0019/1263] Implement captures --- src/nre.nim | 142 +++++++++++++++++++++++++++++++++------------- test/captures.nim | 30 +++++++++- 2 files changed, 133 insertions(+), 39 deletions(-) diff --git a/src/nre.nim b/src/nre.nim index 5839cab2a..cb15fb260 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -70,11 +70,18 @@ type pcreObj: ptr pcre.Pcre # not nil pcreExtra: ptr pcre.ExtraData ## nil - RegexMatch* = object + captureNameToId: Table[string, int] + + RegexMatch* = ref object pattern: Regex - matchBounds: seq[Slice[cint]] ## First item is the bounds of the match + inputStr: string + pcreMatchBounds: seq[Slice[cint]] ## First item is the bounds of the match ## Other items are the captures ## `a` is inclusive start, `b` is exclusive end + matchCache: seq[string] + + Captures* = distinct RegexMatch + CaptureBounds* = distinct RegexMatch SyntaxError* = ref object of Exception pos*: int ## the location of the syntax error in bytes @@ -82,6 +89,72 @@ type StudyError* = ref object of Exception +proc getinfo[T](self: Regex, opt: cint): T = + let retcode = pcre.fullinfo(self.pcreObj, self.pcreExtra, opt, addr result) + + if retcode < 0: + # XXX Error message that doesn't expose implementation details + raise newException(FieldError, "Invalid getinfo for $1, errno $2" % [$opt, $retcode]) + +proc captureCount*(self: Regex): int = + ## get the maximum number of captures + ## + ## Does not return the number of captured captures + return getinfo[int](self, pcre.INFO_CAPTURECOUNT) + +# Capture accessors {{{ +proc captureBounds*(self: RegexMatch): CaptureBounds = return CaptureBounds(self) + +proc captures*(self: RegexMatch): Captures = return Captures(self) + +proc `[]`*(self: CaptureBounds, i: int): Option[Slice[int]] = + ## Gets the bounds of the `i`th capture. + ## Undefined behavior if `i` is out of bounds + ## If `i` is a failed optional capture, returns None + ## If `i == -1`, returns the whole match + let self = RegexMatch(self) + if self.pcreMatchBounds[i + 1].a != -1: + let bounds = self.pcreMatchBounds[i + 1] + return Some(int(bounds.a) .. int(bounds.b)) + else: + return None[Slice[int]]() + +proc `[]`*(self: Captures, i: int): string = + ## gets the `i`th capture + ## Undefined behavior if `i` is out of bounds + ## If `i` is a failed optional capture, returns nil + ## If `i == -1`, returns the whole match + let self = RegexMatch(self) + let bounds = self.captureBounds[i] + + if bounds: + let bounds = bounds.get + if self.matchCache == nil: + # capture count, plus the entire string + self.matchCache = newSeq[string](self.pattern.captureCount + 1) + if self.matchCache[i + 1] == nil: + self.matchCache[i + 1] = self.inputStr[bounds.a .. bounds.b-1] + return self.matchCache[i + 1] + else: + return nil + +proc match*(self: RegexMatch): string = + return self.captures[-1] + +proc matchBounds*(self: RegexMatch): Slice[int] = + return self.captureBounds[-1].get + +proc `[]`*(self: CaptureBounds, name: string): Option[Slice[int]] = + ## Will fail with KeyError if `name` is not a real named capture + let self = RegexMatch(self) + return self.captureBounds[self.pattern.captureNameToId.fget(name)] + +proc `[]`*(self: Captures, name: string): string = + ## Will fail with KeyError if `name` is not a real named capture + let self = RegexMatch(self) + return self.captures[self.pattern.captureNameToId.fget(name)] +# }}} + # Creation & Destruction {{{ proc destroyRegex(self: Regex) = pcre.free_substring(cast[cstring](self.pcreObj)) @@ -89,6 +162,27 @@ proc destroyRegex(self: Regex) = if self.pcreExtra != nil: pcre.free_study(self.pcreExtra) +type UncheckedArray {.unchecked.}[T] = array[0 .. 0, T] +proc getNameToNumberTable(self: Regex): Table[string, int] = + let entryCount = getinfo[cint](self, pcre.INFO_NAMECOUNT) + let entrySize = getinfo[cint](self, pcre.INFO_NAMEENTRYSIZE) + let table = cast[ptr UncheckedArray[uint8]]( + getinfo[int](self, pcre.INFO_NAMETABLE)) + + result = initTable[string, int]() + + for i in 0 .. = 0: return Some(result) elif execRet == pcre.ERROR_NOMATCH: diff --git a/test/captures.nim b/test/captures.nim index 769e9e4f0..91b780ad3 100644 --- a/test/captures.nim +++ b/test/captures.nim @@ -4,4 +4,32 @@ include nre suite "captures": test "map capture names to numbers": check(getNameToNumberTable(initRegex("(?1(?2(?3))(?'v4'4))()")) == - { "v1" : 1, "v2" : 2, "v3" : 3, "v4" : 4 }.toTable()) + { "v1" : 0, "v2" : 1, "v3" : 2, "v4" : 3 }.toTable()) + + test "capture bounds are correct": + let ex1 = initRegex("([0-9])") + check(ex1.exec("1 23").get.matchBounds == 0 .. 1) + check(ex1.exec("1 23").get.captureBounds[0].get == 0 .. 1) + check(ex1.exec("1 23", 1).get.matchBounds == 2 .. 3) + check(ex1.exec("1 23", 3).get.matchBounds == 3 .. 4) + + let ex2 = initRegex("()()()()()()()()()()([0-9])") + check(ex2.exec("824").get.captureBounds[0].get == 0 .. 0) + check(ex2.exec("824").get.captureBounds[10].get == 0 .. 1) + + let ex3 = initRegex("([0-9]+)") + check(ex3.exec("824").get.captureBounds[0].get == 0 .. 3) + + test "named captures": + let ex1 = initRegex("(?foo)(?bar)").exec("foobar").get + check(ex1.captures["foo"] == "foo") + check(ex1.captures["bar"] == "bar") + + let ex2 = initRegex("(?foo)(?bar)?").exec("foo").get + check(ex2.captures["foo"] == "foo") + check(ex2.captures["bar"] == nil) + + test "named capture bounds": + let ex1 = initRegex("(?foo)(?bar)?").exec("foo").get + check(ex1.captureBounds["foo"] == Some(0..3)) + check(ex1.captureBounds["bar"] == None[Slice[int]]()) From d2c20a32edd8ecb0d2ddaa3cfe39774caedceceb Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 10 Jan 2015 16:21:11 -0500 Subject: [PATCH 0020/1263] captureCount doesn't need to be exposed that way --- src/nre.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/nre.nim b/src/nre.nim index cb15fb260..338b26944 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -96,7 +96,7 @@ proc getinfo[T](self: Regex, opt: cint): T = # XXX Error message that doesn't expose implementation details raise newException(FieldError, "Invalid getinfo for $1, errno $2" % [$opt, $retcode]) -proc captureCount*(self: Regex): int = +proc captureCount(self: Regex): int = ## get the maximum number of captures ## ## Does not return the number of captured captures From 48c29ac9052b4ade187c51063693c3ed2ec27855 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 10 Jan 2015 16:36:51 -0500 Subject: [PATCH 0021/1263] Add access to capture count and names --- src/nre.nim | 7 ++++++- test/captures.nim | 6 ++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/nre.nim b/src/nre.nim index 338b26944..e457306d6 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -96,13 +96,18 @@ proc getinfo[T](self: Regex, opt: cint): T = # XXX Error message that doesn't expose implementation details raise newException(FieldError, "Invalid getinfo for $1, errno $2" % [$opt, $retcode]) +# Capture accessors {{{ proc captureCount(self: Regex): int = ## get the maximum number of captures ## ## Does not return the number of captured captures return getinfo[int](self, pcre.INFO_CAPTURECOUNT) -# Capture accessors {{{ +proc captureNames*(self: Regex): seq[string] = + result = @[] + for key in self.captureNameToId.keys: + result.add(key) + proc captureBounds*(self: RegexMatch): CaptureBounds = return CaptureBounds(self) proc captures*(self: RegexMatch): Captures = return Captures(self) diff --git a/test/captures.nim b/test/captures.nim index 91b780ad3..f2699c935 100644 --- a/test/captures.nim +++ b/test/captures.nim @@ -33,3 +33,9 @@ suite "captures": let ex1 = initRegex("(?foo)(?bar)?").exec("foo").get check(ex1.captureBounds["foo"] == Some(0..3)) check(ex1.captureBounds["bar"] == None[Slice[int]]()) + + test "capture count": + let ex1 = initRegex("(?foo)(?bar)?") + check(ex1.captureCount == 2) + # Don't have sets, do this :< + check(ex1.captureNames == @["foo", "bar"] or ex1.captureNames == @["bar", "foo"]) From 0888b84126dae6526a3dedc5c996033eb7d3a418 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 10 Jan 2015 16:41:55 -0500 Subject: [PATCH 0022/1263] Move some things around --- src/nre.nim | 119 ++++++++++++++++++++++++++-------------------------- 1 file changed, 60 insertions(+), 59 deletions(-) diff --git a/src/nre.nim b/src/nre.nim index e457306d6..5a5cbaa45 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -6,64 +6,7 @@ from strutils import toLower, `%` from math import ceil import optional_t -# PCRE Options {{{ - -let Options: Table[string, int] = { - "8" : pcre.UTF8, - "9" : pcre.NEVER_UTF, - "?" : pcre.NO_UTF8_CHECK, - "A" : pcre.ANCHORED, - # "C" : pcre.AUTO_CALLOUT, unsuported XXX - "E" : pcre.DOLLAR_ENDONLY, - "f" : pcre.FIRSTLINE, - "i" : pcre.CASELESS, - "m" : pcre.MULTILINE, - "N" : pcre.NO_AUTO_CAPTURE, - "O" : pcre.NO_AUTO_POSSESS, - "s" : pcre.DOTALL, - "U" : pcre.UNGREEDY, - "W" : pcre.UCP, - "X" : pcre.EXTRA, - "x" : pcre.EXTENDED, - "Y" : pcre.NO_START_OPTIMIZE, - - "any" : pcre.NEWLINE_ANY, - "anycrlf" : pcre.NEWLINE_ANYCRLF, - "cr" : pcre.NEWLINE_CR, - "crlf" : pcre.NEWLINE_CRLF, - "lf" : pcre.NEWLINE_LF, - "bsr_anycrlf" : pcre.BSR_ANYCRLF, - "bsr_unicode" : pcre.BSR_UNICODE, - "js" : pcre.JAVASCRIPT_COMPAT, -}.toTable - -proc tokenizeOptions(opts: string): tuple[flags: int, study: bool] = - result = (0, false) - - var longOpt: string = nil - for i, c in opts: - # Handle long options {{{ - if c == '<': - longOpt = "" - continue - - if longOpt != nil: - if c == '>': - result.flags = result.flags or Options.fget(longOpt) - longOpt = nil - else: - longOpt.add(c.toLower) - continue - # }}} - - if c == 'S': # handle study - result.study = true - continue - - result.flags = result.flags or Options.fget($c) - -# }}} - +# Type definitions {{{ type Regex* = ref object pattern: string # not nil @@ -88,6 +31,7 @@ type pattern*: string ## the pattern that caused the problem StudyError* = ref object of Exception +# }}} proc getinfo[T](self: Regex, opt: cint): T = let retcode = pcre.fullinfo(self.pcreObj, self.pcreExtra, opt, addr result) @@ -161,13 +105,70 @@ proc `[]`*(self: Captures, name: string): string = # }}} # Creation & Destruction {{{ +# PCRE Options {{{ +let Options: Table[string, int] = { + "8" : pcre.UTF8, + "9" : pcre.NEVER_UTF, + "?" : pcre.NO_UTF8_CHECK, + "A" : pcre.ANCHORED, + # "C" : pcre.AUTO_CALLOUT, unsuported XXX + "E" : pcre.DOLLAR_ENDONLY, + "f" : pcre.FIRSTLINE, + "i" : pcre.CASELESS, + "m" : pcre.MULTILINE, + "N" : pcre.NO_AUTO_CAPTURE, + "O" : pcre.NO_AUTO_POSSESS, + "s" : pcre.DOTALL, + "U" : pcre.UNGREEDY, + "W" : pcre.UCP, + "X" : pcre.EXTRA, + "x" : pcre.EXTENDED, + "Y" : pcre.NO_START_OPTIMIZE, + + "any" : pcre.NEWLINE_ANY, + "anycrlf" : pcre.NEWLINE_ANYCRLF, + "cr" : pcre.NEWLINE_CR, + "crlf" : pcre.NEWLINE_CRLF, + "lf" : pcre.NEWLINE_LF, + "bsr_anycrlf" : pcre.BSR_ANYCRLF, + "bsr_unicode" : pcre.BSR_UNICODE, + "js" : pcre.JAVASCRIPT_COMPAT, +}.toTable + +proc tokenizeOptions(opts: string): tuple[flags: int, study: bool] = + result = (0, false) + + var longOpt: string = nil + for i, c in opts: + # Handle long options {{{ + if c == '<': + longOpt = "" + continue + + if longOpt != nil: + if c == '>': + result.flags = result.flags or Options.fget(longOpt) + longOpt = nil + else: + longOpt.add(c.toLower) + continue + # }}} + + if c == 'S': # handle study + result.study = true + continue + + result.flags = result.flags or Options.fget($c) +# }}} + +type UncheckedArray {.unchecked.}[T] = array[0 .. 0, T] + proc destroyRegex(self: Regex) = pcre.free_substring(cast[cstring](self.pcreObj)) self.pcreObj = nil if self.pcreExtra != nil: pcre.free_study(self.pcreExtra) -type UncheckedArray {.unchecked.}[T] = array[0 .. 0, T] proc getNameToNumberTable(self: Regex): Table[string, int] = let entryCount = getinfo[cint](self, pcre.INFO_NAMECOUNT) let entrySize = getinfo[cint](self, pcre.INFO_NAMEENTRYSIZE) From f692042bb835642d7d0f3296b3c6b2ea60737ecf Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 10 Jan 2015 16:49:39 -0500 Subject: [PATCH 0023/1263] Remove Option from exec(Regex, string, int) --- src/nre.nim | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/nre.nim b/src/nre.nim index 5a5cbaa45..631be2176 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -215,7 +215,10 @@ proc initRegex*(pattern: string, options = "Sx"): Regex = result.captureNameToId = result.getNameToNumberTable() # }}} -proc exec*(self: Regex, str: string, start = 0): Option[RegexMatch] = +proc exec*(self: Regex, str: string, start = 0): RegexMatch = + ## Tries to match the regex on the string `str` starting at `start`. + ## On fail, returns `nil` + ## On success, returns RegexMatch var result: RegexMatch new(result) result.pattern = self @@ -236,8 +239,8 @@ proc exec*(self: Regex, str: string, start = 0): Option[RegexMatch] = cint(0), cast[ptr cint](addr result.pcreMatchBounds[0]), cint(vecsize)) if execRet >= 0: - return Some(result) + return result elif execRet == pcre.ERROR_NOMATCH: - return None[RegexMatch]() + return nil else: raise newException(AssertionError, "Internal error: errno " & $execRet) From cc33942d893b339f87976008b06bc55b8a36d5f0 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 10 Jan 2015 18:00:07 -0500 Subject: [PATCH 0024/1263] Revert "Remove Option from exec(Regex, string, int)" This reverts commit f692042bb835642d7d0f3296b3c6b2ea60737ecf. --- src/nre.nim | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/src/nre.nim b/src/nre.nim index 631be2176..5a5cbaa45 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -215,10 +215,7 @@ proc initRegex*(pattern: string, options = "Sx"): Regex = result.captureNameToId = result.getNameToNumberTable() # }}} -proc exec*(self: Regex, str: string, start = 0): RegexMatch = - ## Tries to match the regex on the string `str` starting at `start`. - ## On fail, returns `nil` - ## On success, returns RegexMatch +proc exec*(self: Regex, str: string, start = 0): Option[RegexMatch] = var result: RegexMatch new(result) result.pattern = self @@ -239,8 +236,8 @@ proc exec*(self: Regex, str: string, start = 0): RegexMatch = cint(0), cast[ptr cint](addr result.pcreMatchBounds[0]), cint(vecsize)) if execRet >= 0: - return result + return Some(result) elif execRet == pcre.ERROR_NOMATCH: - return nil + return None[RegexMatch]() else: raise newException(AssertionError, "Internal error: errno " & $execRet) From 0f4b142c757f7d46071d0cbff959d5c1002d0c05 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 10 Jan 2015 19:10:43 -0500 Subject: [PATCH 0025/1263] Implement toTable(Captures), toSeq(Captures) --- src/nre.nim | 35 +++++++++++++++++++++++++++++++++++ test/captures.nim | 19 +++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/src/nre.nim b/src/nre.nim index 5a5cbaa45..64ed8c75d 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -2,6 +2,7 @@ import private.pcre as pcre import private.util import tables import unsigned +from future import lc, `[]` from strutils import toLower, `%` from math import ceil import optional_t @@ -102,6 +103,40 @@ proc `[]`*(self: Captures, name: string): string = ## Will fail with KeyError if `name` is not a real named capture let self = RegexMatch(self) return self.captures[self.pattern.captureNameToId.fget(name)] + +template asTableImpl(cond: bool): stmt {.immediate, dirty.} = + for key in RegexMatch(self).pattern.captureNames: + let nextVal = self[key] + if cond: + result[key] = default + else: + result[key] = nextVal + +proc asTable*(self: Captures, default: string = nil): Table[string, string] = + ## Gets all the named captures and returns them + result = initTable[string, string]() + asTableImpl(nextVal == nil) + +proc asTable*(self: CaptureBounds, default = None[Slice[int]]()): + Table[string, Option[Slice[int]]] = + ## Gets all the named captures and returns them + result = initTable[string, Option[Slice[int]]]() + asTableImpl(nextVal.isNone) + +template asSeqImpl(cond: bool): stmt {.immediate, dirty.} = + result = @[] + for i in 0 .. foo)(?bar)?").exec("foo").get + check(ex1.captures.asTable == {"foo" : "foo", "bar" : nil}.toTable()) + check(ex1.captureBounds.asTable == {"foo" : Some(0..3), "bar" : None[Slice[int]]()}.toTable()) + check(ex1.captures.asTable("") == {"foo" : "foo", "bar" : ""}.toTable()) + + let ex2 = initRegex("(?foo)(?bar)?").exec("foobar").get + check(ex2.captures.asTable == {"foo" : "foo", "bar" : "bar"}.toTable()) + + test "capture sequence": + let ex1 = initRegex("(?foo)(?bar)?").exec("foo").get + check(ex1.captures.asSeq == @["foo", nil]) + check(ex1.captureBounds.asSeq == @[Some(0..3), None[Slice[int]]()]) + check(ex1.captures.asSeq("") == @["foo", ""]) + + let ex2 = initRegex("(?foo)(?bar)?").exec("foobar").get + check(ex2.captures.asSeq == @["foo", "bar"]) + From ccf57714417146d0701bee70c5dbb696782f070c Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 10 Jan 2015 19:12:21 -0500 Subject: [PATCH 0026/1263] Allow `u` for unicode matching --- src/nre.nim | 1 + 1 file changed, 1 insertion(+) diff --git a/src/nre.nim b/src/nre.nim index 64ed8c75d..044d25d4e 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -155,6 +155,7 @@ let Options: Table[string, int] = { "O" : pcre.NO_AUTO_POSSESS, "s" : pcre.DOTALL, "U" : pcre.UNGREEDY, + "u" : pcre.UTF8, "W" : pcre.UCP, "X" : pcre.EXTRA, "x" : pcre.EXTENDED, From 4f4a7dfa5b00e39114b6779f84e6dc2fd21723c4 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 10 Jan 2015 19:19:25 -0500 Subject: [PATCH 0027/1263] Expose pattern and input string --- src/nre.nim | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/nre.nim b/src/nre.nim index 044d25d4e..76532efee 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -17,11 +17,13 @@ type captureNameToId: Table[string, int] RegexMatch* = ref object - pattern: Regex - inputStr: string + pattern*: Regex ## The regex doing the matching. + ## Not nil. + str*: string ## The string that was matched against. + ## Not nil. pcreMatchBounds: seq[Slice[cint]] ## First item is the bounds of the match - ## Other items are the captures - ## `a` is inclusive start, `b` is exclusive end + ## Other items are the captures + ## `a` is inclusive start, `b` is exclusive end matchCache: seq[string] Captures* = distinct RegexMatch @@ -83,7 +85,7 @@ proc `[]`*(self: Captures, i: int): string = # capture count, plus the entire string self.matchCache = newSeq[string](self.pattern.captureCount + 1) if self.matchCache[i + 1] == nil: - self.matchCache[i + 1] = self.inputStr[bounds.a .. bounds.b-1] + self.matchCache[i + 1] = self.str[bounds.a .. bounds.b-1] return self.matchCache[i + 1] else: return nil @@ -255,7 +257,7 @@ proc exec*(self: Regex, str: string, start = 0): Option[RegexMatch] = var result: RegexMatch new(result) result.pattern = self - result.inputStr = str + result.str = str # See PCRE man pages. # 2x capture count to make room for start-end pairs # 1x capture count as slack space for PCRE From d7dbf7e01177c67e8438aff814aa9263312d87b1 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 10 Jan 2015 19:23:15 -0500 Subject: [PATCH 0028/1263] Rename exec(...) and extend it --- src/nre.nim | 8 ++++++-- test/captures.nim | 28 ++++++++++++++-------------- 2 files changed, 20 insertions(+), 16 deletions(-) diff --git a/src/nre.nim b/src/nre.nim index 76532efee..b6835bd00 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -253,7 +253,11 @@ proc initRegex*(pattern: string, options = "Sx"): Regex = result.captureNameToId = result.getNameToNumberTable() # }}} -proc exec*(self: Regex, str: string, start = 0): Option[RegexMatch] = +proc match*(self: Regex, str: string, start = 0, endpos = -1): Option[RegexMatch] = + ## Returns Some if there is a match between `start` and `endpos`, otherwise + ## it returns None. + ## + ## if `endpos == -1`, then `endpos = str.len` var result: RegexMatch new(result) result.pattern = self @@ -269,7 +273,7 @@ proc exec*(self: Regex, str: string, start = 0): Option[RegexMatch] = let execRet = pcre.exec(self.pcreObj, self.pcreExtra, cstring(str), - cint(str.len), + cint(max(str.len, endpos)), cint(start), cint(0), cast[ptr cint](addr result.pcreMatchBounds[0]), cint(vecsize)) diff --git a/test/captures.nim b/test/captures.nim index b52c283b6..e987e9ca4 100644 --- a/test/captures.nim +++ b/test/captures.nim @@ -8,29 +8,29 @@ suite "captures": test "capture bounds are correct": let ex1 = initRegex("([0-9])") - check(ex1.exec("1 23").get.matchBounds == 0 .. 1) - check(ex1.exec("1 23").get.captureBounds[0].get == 0 .. 1) - check(ex1.exec("1 23", 1).get.matchBounds == 2 .. 3) - check(ex1.exec("1 23", 3).get.matchBounds == 3 .. 4) + check(ex1.match("1 23").get.matchBounds == 0 .. 1) + check(ex1.match("1 23").get.captureBounds[0].get == 0 .. 1) + check(ex1.match("1 23", 1).get.matchBounds == 2 .. 3) + check(ex1.match("1 23", 3).get.matchBounds == 3 .. 4) let ex2 = initRegex("()()()()()()()()()()([0-9])") - check(ex2.exec("824").get.captureBounds[0].get == 0 .. 0) - check(ex2.exec("824").get.captureBounds[10].get == 0 .. 1) + check(ex2.match("824").get.captureBounds[0].get == 0 .. 0) + check(ex2.match("824").get.captureBounds[10].get == 0 .. 1) let ex3 = initRegex("([0-9]+)") - check(ex3.exec("824").get.captureBounds[0].get == 0 .. 3) + check(ex3.match("824").get.captureBounds[0].get == 0 .. 3) test "named captures": - let ex1 = initRegex("(?foo)(?bar)").exec("foobar").get + let ex1 = initRegex("(?foo)(?bar)").match("foobar").get check(ex1.captures["foo"] == "foo") check(ex1.captures["bar"] == "bar") - let ex2 = initRegex("(?foo)(?bar)?").exec("foo").get + let ex2 = initRegex("(?foo)(?bar)?").match("foo").get check(ex2.captures["foo"] == "foo") check(ex2.captures["bar"] == nil) test "named capture bounds": - let ex1 = initRegex("(?foo)(?bar)?").exec("foo").get + let ex1 = initRegex("(?foo)(?bar)?").match("foo").get check(ex1.captureBounds["foo"] == Some(0..3)) check(ex1.captureBounds["bar"] == None[Slice[int]]()) @@ -41,20 +41,20 @@ suite "captures": check(ex1.captureNames == @["foo", "bar"] or ex1.captureNames == @["bar", "foo"]) test "named capture table": - let ex1 = initRegex("(?foo)(?bar)?").exec("foo").get + let ex1 = initRegex("(?foo)(?bar)?").match("foo").get check(ex1.captures.asTable == {"foo" : "foo", "bar" : nil}.toTable()) check(ex1.captureBounds.asTable == {"foo" : Some(0..3), "bar" : None[Slice[int]]()}.toTable()) check(ex1.captures.asTable("") == {"foo" : "foo", "bar" : ""}.toTable()) - let ex2 = initRegex("(?foo)(?bar)?").exec("foobar").get + let ex2 = initRegex("(?foo)(?bar)?").match("foobar").get check(ex2.captures.asTable == {"foo" : "foo", "bar" : "bar"}.toTable()) test "capture sequence": - let ex1 = initRegex("(?foo)(?bar)?").exec("foo").get + let ex1 = initRegex("(?foo)(?bar)?").match("foo").get check(ex1.captures.asSeq == @["foo", nil]) check(ex1.captureBounds.asSeq == @[Some(0..3), None[Slice[int]]()]) check(ex1.captures.asSeq("") == @["foo", ""]) - let ex2 = initRegex("(?foo)(?bar)?").exec("foobar").get + let ex2 = initRegex("(?foo)(?bar)?").match("foobar").get check(ex2.captures.asSeq == @["foo", "bar"]) From fb51221aa890df5535103c4056c2b09c994addbb Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 10 Jan 2015 20:36:34 -0500 Subject: [PATCH 0029/1263] Expose the pattern string, rename some procs --- src/nre.nim | 20 +++++++++++--------- test/captures.nim | 3 +-- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/src/nre.nim b/src/nre.nim index b6835bd00..92cc7bbf4 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -10,7 +10,7 @@ import optional_t # Type definitions {{{ type Regex* = ref object - pattern: string # not nil + pattern*: string # not nil pcreObj: ptr pcre.Pcre # not nil pcreExtra: ptr pcre.ExtraData ## nil @@ -43,18 +43,20 @@ proc getinfo[T](self: Regex, opt: cint): T = # XXX Error message that doesn't expose implementation details raise newException(FieldError, "Invalid getinfo for $1, errno $2" % [$opt, $retcode]) -# Capture accessors {{{ -proc captureCount(self: Regex): int = - ## get the maximum number of captures +# Regex accessors {{{ +proc captureCount*(self: Regex): int = + ## Get the maximum number of captures ## ## Does not return the number of captured captures return getinfo[int](self, pcre.INFO_CAPTURECOUNT) -proc captureNames*(self: Regex): seq[string] = - result = @[] - for key in self.captureNameToId.keys: - result.add(key) +proc captureNameId*(self: Regex): Table[string, int] = + ## Returns a map from named capture groups to their numerical + ## identifier + return self.captureNameToId +# }}} +# Capture accessors {{{ proc captureBounds*(self: RegexMatch): CaptureBounds = return CaptureBounds(self) proc captures*(self: RegexMatch): Captures = return Captures(self) @@ -107,7 +109,7 @@ proc `[]`*(self: Captures, name: string): string = return self.captures[self.pattern.captureNameToId.fget(name)] template asTableImpl(cond: bool): stmt {.immediate, dirty.} = - for key in RegexMatch(self).pattern.captureNames: + for key in RegexMatch(self).pattern.captureNameId.keys: let nextVal = self[key] if cond: result[key] = default diff --git a/test/captures.nim b/test/captures.nim index e987e9ca4..340c3d638 100644 --- a/test/captures.nim +++ b/test/captures.nim @@ -37,8 +37,7 @@ suite "captures": test "capture count": let ex1 = initRegex("(?foo)(?bar)?") check(ex1.captureCount == 2) - # Don't have sets, do this :< - check(ex1.captureNames == @["foo", "bar"] or ex1.captureNames == @["bar", "foo"]) + check(ex1.captureNameId == {"foo" : 0, "bar" : 1}.toTable()) test "named capture table": let ex1 = initRegex("(?foo)(?bar)?").match("foo").get From 6fe0de0639fe3163376acfb3dad75e2264a88363 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 10 Jan 2015 20:54:36 -0500 Subject: [PATCH 0030/1263] Fix incorrect check pcre_study can return nil and still succeed The indicator of failure is a non-nil error message --- src/nre.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/nre.nim b/src/nre.nim index 92cc7bbf4..29313e9eb 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -249,7 +249,7 @@ proc initRegex*(pattern: string, options = "Sx"): Regex = if opts.study: # XXX investigate JIT result.pcreExtra = pcre.study(result.pcreObj, 0x0, addr errorMsg) - if result.pcreExtra == nil: + if errorMsg != nil: raise StudyError(msg: $errorMsg) result.captureNameToId = result.getNameToNumberTable() From 2474758ed52bcdd48212ea51f7f05003c2468e4e Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Mon, 12 Jan 2015 20:09:19 -0500 Subject: [PATCH 0031/1263] Implement match, find, split --- nre.nimble | 2 +- src/nre.nim | 126 ++++++++++++++++++++++++++++++++++++++++++++--- test/find.nim | 14 ++++++ test/split.nim | 9 ++++ test/testall.nim | 2 + 5 files changed, 145 insertions(+), 8 deletions(-) create mode 100644 test/find.nim create mode 100644 test/split.nim diff --git a/nre.nimble b/nre.nimble index 48cabc177..cad375a9a 100644 --- a/nre.nimble +++ b/nre.nimble @@ -8,4 +8,4 @@ srcDir = "src" [Deps] Requires: "nim >= 0.10.0" -Requires: "optional_t >= 1.0" +Requires: "optional_t >= 1.1.0" diff --git a/src/nre.nim b/src/nre.nim index 29313e9eb..c9e9d9ecd 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -6,6 +6,7 @@ from future import lc, `[]` from strutils import toLower, `%` from math import ceil import optional_t +from unicode import runeLenAt # Type definitions {{{ type @@ -54,6 +55,27 @@ proc captureNameId*(self: Regex): Table[string, int] = ## Returns a map from named capture groups to their numerical ## identifier return self.captureNameToId + +proc matchesCrLf(self: Regex): bool = + let flags = getinfo[cint](self, pcre.INFO_OPTIONS) + let newlineFlags = flags and (pcre.NEWLINE_CRLF or + pcre.NEWLINE_ANY or + pcre.NEWLINE_ANYCRLF) + if newLineFlags > 0: + return true + + # get flags from build config + var confFlags: cint + if pcre.config(pcre.CONFIG_NEWLINE, addr confFlags) != 0: + assert(false, "CONFIG_NEWLINE apparently got screwed up") + + case confFlags + of 13: return false + of 10: return false + of (13 shl 8) or 10: return true + of -2: return true + of -1: return true + else: return false # }}} # Capture accessors {{{ @@ -255,11 +277,7 @@ proc initRegex*(pattern: string, options = "Sx"): Regex = result.captureNameToId = result.getNameToNumberTable() # }}} -proc match*(self: Regex, str: string, start = 0, endpos = -1): Option[RegexMatch] = - ## Returns Some if there is a match between `start` and `endpos`, otherwise - ## it returns None. - ## - ## if `endpos == -1`, then `endpos = str.len` +proc matchImpl*(self: Regex, str: string, start, endpos: int, flags: int): Option[RegexMatch] = var result: RegexMatch new(result) result.pattern = self @@ -277,11 +295,105 @@ proc match*(self: Regex, str: string, start = 0, endpos = -1): Option[RegexMatch cstring(str), cint(max(str.len, endpos)), cint(start), - cint(0), - cast[ptr cint](addr result.pcreMatchBounds[0]), cint(vecsize)) + cint(flags), + cast[ptr cint](addr result.pcreMatchBounds[0]), + cint(vecsize)) if execRet >= 0: return Some(result) elif execRet == pcre.ERROR_NOMATCH: return None[RegexMatch]() else: raise newException(AssertionError, "Internal error: errno " & $execRet) + +proc match*(self: Regex, str: string, start = 0, endpos = -1): Option[RegexMatch] = + ## Returns Some if there is a match between `start` and `endpos`, otherwise + ## it returns None. + ## + ## if `endpos == -1`, then `endpos = str.len` + return matchImpl(self, str, start, endpos, 0) + +iterator findIter*(self: Regex, str: string, start = 0, endpos = -1): RegexMatch = + # see pcredemo for explaination + let matchesCrLf = self.matchesCrLf() + let unicode = bool(getinfo[cint](self, pcre.INFO_OPTIONS) and pcre.UTF8) + let endpos = if endpos == -1: str.len else: endpos + + var offset = start + var previousMatch: RegexMatch + while offset != endpos: + if offset > endpos: + # eos occurs in the middle of a unicode char? die. + raise newException(AssertionError, "Input string has malformed unicode") + + var flags = 0 + + if previousMatch != nil and + previousMatch.matchBounds.a == previousMatch.matchBounds.b: + # 0-len match + flags = pcre.NOTEMPTY_ATSTART or pcre.ANCHORED + + let currentMatch = self.matchImpl(str, offset, endpos, flags) + previousMatch = currentMatch.get(nil) + + if currentMatch.isNone: + # either the end of the input or the string + # cannot be split here + offset += 1 + + if matchesCrLf and offset < (str.len - 1) and + str[offset] == '\r' and str[offset + 1] == '\l': + # if PCRE treats CrLf as newline, skip both at the same time + offset += 1 + elif unicode: + # XXX what about invalid unicode? + offset += str.runeLenAt(offset) + else: + let currentMatch = currentMatch.get + offset = currentMatch.matchBounds.b + + yield currentMatch + +proc find*(self: Regex, str: string, start = 0, endpos = -1): Option[RegexMatch] = + for match in self.findIter(str, start, endpos): + return Some(match) + + return None[RegexMatch]() + +proc findAll*(self: Regex, str: string, start = 0, endpos = -1): seq[RegexMatch] = + accumulateResult(self.findIter(str, start, endpos)) + +proc renderBounds(str: string, bounds: Slice[int]): string = + result = " " & str & "⫞\n" + for i in -1 .. Date: Mon, 12 Jan 2015 20:56:34 -0500 Subject: [PATCH 0032/1263] Flip parameter string-pattern order --- src/nre.nim | 132 +++++++++++++++++++++++----------------------- test/captures.nim | 28 +++++----- test/find.nim | 6 +-- test/split.nim | 8 +-- 4 files changed, 87 insertions(+), 87 deletions(-) diff --git a/src/nre.nim b/src/nre.nim index c9e9d9ecd..13d0a2056 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -37,27 +37,27 @@ type StudyError* = ref object of Exception # }}} -proc getinfo[T](self: Regex, opt: cint): T = - let retcode = pcre.fullinfo(self.pcreObj, self.pcreExtra, opt, addr result) +proc getinfo[T](pattern: Regex, opt: cint): T = + let retcode = pcre.fullinfo(pattern.pcreObj, pattern.pcreExtra, opt, addr result) if retcode < 0: # XXX Error message that doesn't expose implementation details raise newException(FieldError, "Invalid getinfo for $1, errno $2" % [$opt, $retcode]) # Regex accessors {{{ -proc captureCount*(self: Regex): int = +proc captureCount*(pattern: Regex): int = ## Get the maximum number of captures ## ## Does not return the number of captured captures - return getinfo[int](self, pcre.INFO_CAPTURECOUNT) + return getinfo[int](pattern, pcre.INFO_CAPTURECOUNT) -proc captureNameId*(self: Regex): Table[string, int] = +proc captureNameId*(pattern: Regex): Table[string, int] = ## Returns a map from named capture groups to their numerical ## identifier - return self.captureNameToId + return pattern.captureNameToId -proc matchesCrLf(self: Regex): bool = - let flags = getinfo[cint](self, pcre.INFO_OPTIONS) +proc matchesCrLf(pattern: Regex): bool = + let flags = getinfo[cint](pattern, pcre.INFO_OPTIONS) let newlineFlags = flags and (pcre.NEWLINE_CRLF or pcre.NEWLINE_ANY or pcre.NEWLINE_ANYCRLF) @@ -79,71 +79,71 @@ proc matchesCrLf(self: Regex): bool = # }}} # Capture accessors {{{ -proc captureBounds*(self: RegexMatch): CaptureBounds = return CaptureBounds(self) +proc captureBounds*(pattern: RegexMatch): CaptureBounds = return CaptureBounds(pattern) -proc captures*(self: RegexMatch): Captures = return Captures(self) +proc captures*(pattern: RegexMatch): Captures = return Captures(pattern) -proc `[]`*(self: CaptureBounds, i: int): Option[Slice[int]] = +proc `[]`*(pattern: CaptureBounds, i: int): Option[Slice[int]] = ## Gets the bounds of the `i`th capture. ## Undefined behavior if `i` is out of bounds ## If `i` is a failed optional capture, returns None ## If `i == -1`, returns the whole match - let self = RegexMatch(self) - if self.pcreMatchBounds[i + 1].a != -1: - let bounds = self.pcreMatchBounds[i + 1] + let pattern = RegexMatch(pattern) + if pattern.pcreMatchBounds[i + 1].a != -1: + let bounds = pattern.pcreMatchBounds[i + 1] return Some(int(bounds.a) .. int(bounds.b)) else: return None[Slice[int]]() -proc `[]`*(self: Captures, i: int): string = +proc `[]`*(pattern: Captures, i: int): string = ## gets the `i`th capture ## Undefined behavior if `i` is out of bounds ## If `i` is a failed optional capture, returns nil ## If `i == -1`, returns the whole match - let self = RegexMatch(self) - let bounds = self.captureBounds[i] + let pattern = RegexMatch(pattern) + let bounds = pattern.captureBounds[i] if bounds: let bounds = bounds.get - if self.matchCache == nil: + if pattern.matchCache == nil: # capture count, plus the entire string - self.matchCache = newSeq[string](self.pattern.captureCount + 1) - if self.matchCache[i + 1] == nil: - self.matchCache[i + 1] = self.str[bounds.a .. bounds.b-1] - return self.matchCache[i + 1] + pattern.matchCache = newSeq[string](pattern.pattern.captureCount + 1) + if pattern.matchCache[i + 1] == nil: + pattern.matchCache[i + 1] = pattern.str[bounds.a .. bounds.b-1] + return pattern.matchCache[i + 1] else: return nil -proc match*(self: RegexMatch): string = - return self.captures[-1] +proc match*(pattern: RegexMatch): string = + return pattern.captures[-1] -proc matchBounds*(self: RegexMatch): Slice[int] = - return self.captureBounds[-1].get +proc matchBounds*(pattern: RegexMatch): Slice[int] = + return pattern.captureBounds[-1].get -proc `[]`*(self: CaptureBounds, name: string): Option[Slice[int]] = +proc `[]`*(pattern: CaptureBounds, name: string): Option[Slice[int]] = ## Will fail with KeyError if `name` is not a real named capture - let self = RegexMatch(self) - return self.captureBounds[self.pattern.captureNameToId.fget(name)] + let pattern = RegexMatch(pattern) + return pattern.captureBounds[pattern.pattern.captureNameToId.fget(name)] -proc `[]`*(self: Captures, name: string): string = +proc `[]`*(pattern: Captures, name: string): string = ## Will fail with KeyError if `name` is not a real named capture - let self = RegexMatch(self) - return self.captures[self.pattern.captureNameToId.fget(name)] + let pattern = RegexMatch(pattern) + return pattern.captures[pattern.pattern.captureNameToId.fget(name)] template asTableImpl(cond: bool): stmt {.immediate, dirty.} = - for key in RegexMatch(self).pattern.captureNameId.keys: - let nextVal = self[key] + for key in RegexMatch(pattern).pattern.captureNameId.keys: + let nextVal = pattern[key] if cond: result[key] = default else: result[key] = nextVal -proc asTable*(self: Captures, default: string = nil): Table[string, string] = +proc asTable*(pattern: Captures, default: string = nil): Table[string, string] = ## Gets all the named captures and returns them result = initTable[string, string]() asTableImpl(nextVal == nil) -proc asTable*(self: CaptureBounds, default = None[Slice[int]]()): +proc asTable*(pattern: CaptureBounds, default = None[Slice[int]]()): Table[string, Option[Slice[int]]] = ## Gets all the named captures and returns them result = initTable[string, Option[Slice[int]]]() @@ -151,17 +151,17 @@ proc asTable*(self: CaptureBounds, default = None[Slice[int]]()): template asSeqImpl(cond: bool): stmt {.immediate, dirty.} = result = @[] - for i in 0 .. foo)(?bar)").match("foobar").get + let ex1 = "foobar".match(initRegex("(?foo)(?bar)")).get check(ex1.captures["foo"] == "foo") check(ex1.captures["bar"] == "bar") - let ex2 = initRegex("(?foo)(?bar)?").match("foo").get + let ex2 = "foo".match(initRegex("(?foo)(?bar)?")).get check(ex2.captures["foo"] == "foo") check(ex2.captures["bar"] == nil) test "named capture bounds": - let ex1 = initRegex("(?foo)(?bar)?").match("foo").get + let ex1 = "foo".match(initRegex("(?foo)(?bar)?")).get check(ex1.captureBounds["foo"] == Some(0..3)) check(ex1.captureBounds["bar"] == None[Slice[int]]()) @@ -40,20 +40,20 @@ suite "captures": check(ex1.captureNameId == {"foo" : 0, "bar" : 1}.toTable()) test "named capture table": - let ex1 = initRegex("(?foo)(?bar)?").match("foo").get + let ex1 = "foo".match(initRegex("(?foo)(?bar)?")).get check(ex1.captures.asTable == {"foo" : "foo", "bar" : nil}.toTable()) check(ex1.captureBounds.asTable == {"foo" : Some(0..3), "bar" : None[Slice[int]]()}.toTable()) check(ex1.captures.asTable("") == {"foo" : "foo", "bar" : ""}.toTable()) - let ex2 = initRegex("(?foo)(?bar)?").match("foobar").get + let ex2 = "foobar".match(initRegex("(?foo)(?bar)?")).get check(ex2.captures.asTable == {"foo" : "foo", "bar" : "bar"}.toTable()) test "capture sequence": - let ex1 = initRegex("(?foo)(?bar)?").match("foo").get + let ex1 = "foo".match(initRegex("(?foo)(?bar)?")).get check(ex1.captures.asSeq == @["foo", nil]) check(ex1.captureBounds.asSeq == @[Some(0..3), None[Slice[int]]()]) check(ex1.captures.asSeq("") == @["foo", ""]) - let ex2 = initRegex("(?foo)(?bar)?").match("foobar").get + let ex2 = "foobar".match(initRegex("(?foo)(?bar)?")).get check(ex2.captures.asSeq == @["foo", "bar"]) diff --git a/test/find.nim b/test/find.nim index a8dbdf016..fc58bb48c 100644 --- a/test/find.nim +++ b/test/find.nim @@ -3,12 +3,12 @@ include nre suite "find": test "find text": - check(initRegex(r"[a-z]").find("3213a").get.match == "a") - check(initRegex(r" ", "S").findAll("1 2 3 4 5 6 7 8 ").map( + check("3213a".find(initRegex(r"[a-z]")).get.match == "a") + check("1 2 3 4 5 6 7 8 ".findAll(initRegex(r" ", "S")).map( proc (a: RegexMatch): string = a.match ) == @[" ", " ", " ", " ", " ", " ", " ", " "]) test "find bounds": - check(initRegex(r" ", "S").findAll("1 2 3 4 5 ").map( + check("1 2 3 4 5 ".findAll(initRegex(r" ", "S")).map( proc (a: RegexMatch): Slice[int] = a.matchBounds ) == @[1..2, 3..4, 5..6, 7..8, 9..10]) diff --git a/test/split.nim b/test/split.nim index acdd41be9..aee522991 100644 --- a/test/split.nim +++ b/test/split.nim @@ -3,7 +3,7 @@ include nre suite "string splitting": test "splitting strings": - check(initRegex("").split("12345") == @["1", "2", "3", "4", "5"]) - check(initRegex(" ", "S").split("1 2 3 4 5 6 ") == @["1", "2", "3", "4", "5", "6", ""]) - check(initRegex(" ", "S").split("1 2 ") == @["1", "", "2", "", ""]) - check(initRegex(" ", "S").split("1 2") == @["1", "2"]) + check("12345".split(initRegex("")) == @["1", "2", "3", "4", "5"]) + check("1 2 3 4 5 6 ".split(initRegex(" ", "S")) == @["1", "2", "3", "4", "5", "6", ""]) + check("1 2 ".split(initRegex(" ", "S")) == @["1", "", "2", "", ""]) + check("1 2".split(initRegex(" ", "S")) == @["1", "2"]) From 1652cdbaff61cd50f7bb4e58570805f051310677 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Mon, 12 Jan 2015 20:57:20 -0500 Subject: [PATCH 0033/1263] Unexpose implementation detail --- src/nre.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/nre.nim b/src/nre.nim index 13d0a2056..b25b1ad30 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -277,7 +277,7 @@ proc initRegex*(pattern: string, options = "Sx"): Regex = result.captureNameToId = result.getNameToNumberTable() # }}} -proc matchImpl*(str: string, pattern: Regex, start, endpos: int, flags: int): Option[RegexMatch] = +proc matchImpl(str: string, pattern: Regex, start, endpos: int, flags: int): Option[RegexMatch] = var result: RegexMatch new(result) result.pattern = pattern From e0cdad635bb7ae15259d8a7b365f441918f09fb3 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Mon, 12 Jan 2015 21:00:25 -0500 Subject: [PATCH 0034/1263] Add findAllStr --- src/nre.nim | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/nre.nim b/src/nre.nim index b25b1ad30..72a5aa760 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -362,6 +362,11 @@ proc find*(str: string, pattern: Regex, start = 0, endpos = -1): Option[RegexMat proc findAll*(str: string, pattern: Regex, start = 0, endpos = -1): seq[RegexMatch] = accumulateResult(str.findIter(pattern, start, endpos)) +proc findAllStr*(str: string, pattern: Regex, start = 0, endpos = -1): seq[string] = + result = @[] + for match in str.findIter(pattern, start, endpos): + result.add(match.match) + proc renderBounds(str: string, bounds: Slice[int]): string = result = " " & str & "⫞\n" for i in -1 .. Date: Mon, 12 Jan 2015 21:06:25 -0500 Subject: [PATCH 0035/1263] Added some documentation --- src/nre.nim | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/nre.nim b/src/nre.nim index 72a5aa760..d2ee0f13b 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -11,13 +11,15 @@ from unicode import runeLenAt # Type definitions {{{ type Regex* = ref object - pattern*: string # not nil - pcreObj: ptr pcre.Pcre # not nil + ## Represents a compiled pattern + pattern*: string ## not nil + pcreObj: ptr pcre.Pcre ## not nil pcreExtra: ptr pcre.ExtraData ## nil captureNameToId: Table[string, int] RegexMatch* = ref object + ## Is returned upon a match. pattern*: Regex ## The regex doing the matching. ## Not nil. str*: string ## The string that was matched against. @@ -31,10 +33,15 @@ type CaptureBounds* = distinct RegexMatch SyntaxError* = ref object of Exception + ## Thrown when there is a syntax error in the + ## regular expression string passed in pos*: int ## the location of the syntax error in bytes pattern*: string ## the pattern that caused the problem StudyError* = ref object of Exception + ## Thrown when studying the regular expression failes + ## for whatever reason. The message contains the error + ## code. # }}} proc getinfo[T](pattern: Regex, opt: cint): T = From aac71d0fc9b3e381ed9a6a30ac5fac38b9665116 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Mon, 12 Jan 2015 21:12:23 -0500 Subject: [PATCH 0036/1263] Remove all optional RegexMatch returns --- src/nre.nim | 24 +++++++++++------------- test/captures.nim | 28 ++++++++++++++-------------- test/find.nim | 2 +- 3 files changed, 26 insertions(+), 28 deletions(-) diff --git a/src/nre.nim b/src/nre.nim index d2ee0f13b..d11a95497 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -284,8 +284,7 @@ proc initRegex*(pattern: string, options = "Sx"): Regex = result.captureNameToId = result.getNameToNumberTable() # }}} -proc matchImpl(str: string, pattern: Regex, start, endpos: int, flags: int): Option[RegexMatch] = - var result: RegexMatch +proc matchImpl(str: string, pattern: Regex, start, endpos: int, flags: int): RegexMatch = new(result) result.pattern = pattern result.str = str @@ -306,15 +305,15 @@ proc matchImpl(str: string, pattern: Regex, start, endpos: int, flags: int): Opt cast[ptr cint](addr result.pcreMatchBounds[0]), cint(vecsize)) if execRet >= 0: - return Some(result) + return result elif execRet == pcre.ERROR_NOMATCH: - return None[RegexMatch]() + return nil else: raise newException(AssertionError, "Internal error: errno " & $execRet) -proc match*(str: string, pattern: Regex, start = 0, endpos = -1): Option[RegexMatch] = - ## Returns Some if there is a match between `start` and `endpos`, otherwise - ## it returns None. +proc match*(str: string, pattern: Regex, start = 0, endpos = -1): RegexMatch = + ## Returns a `RegexMatch` if there is a match between `start` and `endpos`, otherwise + ## it returns nil. ## ## if `endpos == -1`, then `endpos = str.len` return str.matchImpl(pattern, start, endpos, 0) @@ -340,9 +339,9 @@ iterator findIter*(str: string, pattern: Regex, start = 0, endpos = -1): RegexMa flags = pcre.NOTEMPTY_ATSTART or pcre.ANCHORED let currentMatch = str.matchImpl(pattern, offset, endpos, flags) - previousMatch = currentMatch.get(nil) + previousMatch = currentMatch - if currentMatch.isNone: + if currentMatch == nil: # either the end of the input or the string # cannot be split here offset += 1 @@ -355,16 +354,15 @@ iterator findIter*(str: string, pattern: Regex, start = 0, endpos = -1): RegexMa # XXX what about invalid unicode? offset += str.runeLenAt(offset) else: - let currentMatch = currentMatch.get offset = currentMatch.matchBounds.b yield currentMatch -proc find*(str: string, pattern: Regex, start = 0, endpos = -1): Option[RegexMatch] = +proc find*(str: string, pattern: Regex, start = 0, endpos = -1): RegexMatch = for match in str.findIter(pattern, start, endpos): - return Some(match) + return match - return None[RegexMatch]() + return nil proc findAll*(str: string, pattern: Regex, start = 0, endpos = -1): seq[RegexMatch] = accumulateResult(str.findIter(pattern, start, endpos)) diff --git a/test/captures.nim b/test/captures.nim index fd37afe0f..9b8a7580e 100644 --- a/test/captures.nim +++ b/test/captures.nim @@ -8,29 +8,29 @@ suite "captures": test "capture bounds are correct": let ex1 = initRegex("([0-9])") - check("1 23".match(ex1).get.matchBounds == 0 .. 1) - check("1 23".match(ex1).get.captureBounds[0].get == 0 .. 1) - check("1 23".match(ex1, 1).get.matchBounds == 2 .. 3) - check("1 23".match(ex1, 3).get.matchBounds == 3 .. 4) + check("1 23".match(ex1).matchBounds == 0 .. 1) + check("1 23".match(ex1).captureBounds[0].get == 0 .. 1) + check("1 23".match(ex1, 1).matchBounds == 2 .. 3) + check("1 23".match(ex1, 3).matchBounds == 3 .. 4) let ex2 = initRegex("()()()()()()()()()()([0-9])") - check("824".match(ex2).get.captureBounds[0].get == 0 .. 0) - check("824".match(ex2).get.captureBounds[10].get == 0 .. 1) + check("824".match(ex2).captureBounds[0].get == 0 .. 0) + check("824".match(ex2).captureBounds[10].get == 0 .. 1) let ex3 = initRegex("([0-9]+)") - check("824".match(ex3).get.captureBounds[0].get == 0 .. 3) + check("824".match(ex3).captureBounds[0].get == 0 .. 3) test "named captures": - let ex1 = "foobar".match(initRegex("(?foo)(?bar)")).get + let ex1 = "foobar".match(initRegex("(?foo)(?bar)")) check(ex1.captures["foo"] == "foo") check(ex1.captures["bar"] == "bar") - let ex2 = "foo".match(initRegex("(?foo)(?bar)?")).get + let ex2 = "foo".match(initRegex("(?foo)(?bar)?")) check(ex2.captures["foo"] == "foo") check(ex2.captures["bar"] == nil) test "named capture bounds": - let ex1 = "foo".match(initRegex("(?foo)(?bar)?")).get + let ex1 = "foo".match(initRegex("(?foo)(?bar)?")) check(ex1.captureBounds["foo"] == Some(0..3)) check(ex1.captureBounds["bar"] == None[Slice[int]]()) @@ -40,20 +40,20 @@ suite "captures": check(ex1.captureNameId == {"foo" : 0, "bar" : 1}.toTable()) test "named capture table": - let ex1 = "foo".match(initRegex("(?foo)(?bar)?")).get + let ex1 = "foo".match(initRegex("(?foo)(?bar)?")) check(ex1.captures.asTable == {"foo" : "foo", "bar" : nil}.toTable()) check(ex1.captureBounds.asTable == {"foo" : Some(0..3), "bar" : None[Slice[int]]()}.toTable()) check(ex1.captures.asTable("") == {"foo" : "foo", "bar" : ""}.toTable()) - let ex2 = "foobar".match(initRegex("(?foo)(?bar)?")).get + let ex2 = "foobar".match(initRegex("(?foo)(?bar)?")) check(ex2.captures.asTable == {"foo" : "foo", "bar" : "bar"}.toTable()) test "capture sequence": - let ex1 = "foo".match(initRegex("(?foo)(?bar)?")).get + let ex1 = "foo".match(initRegex("(?foo)(?bar)?")) check(ex1.captures.asSeq == @["foo", nil]) check(ex1.captureBounds.asSeq == @[Some(0..3), None[Slice[int]]()]) check(ex1.captures.asSeq("") == @["foo", ""]) - let ex2 = "foobar".match(initRegex("(?foo)(?bar)?")).get + let ex2 = "foobar".match(initRegex("(?foo)(?bar)?")) check(ex2.captures.asSeq == @["foo", "bar"]) diff --git a/test/find.nim b/test/find.nim index fc58bb48c..87f8e0aae 100644 --- a/test/find.nim +++ b/test/find.nim @@ -3,7 +3,7 @@ include nre suite "find": test "find text": - check("3213a".find(initRegex(r"[a-z]")).get.match == "a") + check("3213a".find(initRegex(r"[a-z]")).match == "a") check("1 2 3 4 5 6 7 8 ".findAll(initRegex(r" ", "S")).map( proc (a: RegexMatch): string = a.match ) == @[" ", " ", " ", " ", " ", " ", " ", " "]) From cfb0385a02214dc04862651c4981821384a7e193 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Mon, 12 Jan 2015 21:50:55 -0500 Subject: [PATCH 0037/1263] Add shorthand initialization --- src/nre.nim | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/nre.nim b/src/nre.nim index d11a95497..613b3897f 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -282,6 +282,8 @@ proc initRegex*(pattern: string, options = "Sx"): Regex = raise StudyError(msg: $errorMsg) result.captureNameToId = result.getNameToNumberTable() + +proc re*(pattern: string, options = "Sx"): Regex = initRegex(pattern, options) # }}} proc matchImpl(str: string, pattern: Regex, start, endpos: int, flags: int): RegexMatch = From 5ac61da7e30c0ab1b2fc5170eecb3e0023c08d01 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Wed, 14 Jan 2015 20:11:47 -0500 Subject: [PATCH 0038/1263] Add readme --- README.md | 68 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 000000000..e89f70a07 --- /dev/null +++ b/README.md @@ -0,0 +1,68 @@ +# N___ RegEx Library + +## What is NRE? + +A new regular expression library for Nim using PCRE to do the hard work. + +## Why? + +The [re.nim][] module that [Nim][] provides in it's standard library is +inadequate: + + - It provides only a limited number of captures, while the underling library + (PCRE) allows an unlimited number. + - Instead of having one proc that returns both the bounds and substring, it + has one for the bounds and another for the substring. + - If the splitting regex is empty (`""`), then it returns the input string + instead of following [Perl][], [Javascript][], and [Java][]'s precedent of + returning a list of each character (`"123".split(re"") == @["1", "2", "3"]`). + +[re.nim]: http://nim-lang.org/re.html +[Nim]: http://nim-lang.org/ +[Perl]: https://ideone.com/dDMjmz +[Javascript]: http://jsfiddle.net/xtcbxurg/ +[Java]: https://ideone.com/hYJuJ5 + + +# Documentation + +## Construction + +Creating a pattern is easy: `re"([0-9]+)"`. By default, the extended flag is +passed in order to encourage readable expressions, so `[0-9]+` is equivalent to +`[0-9] + # foo`. If you'd like to pass your own flags, then `re(r"([0-9]+)", +"")` will work. Here is a list of the available flags: + + - `8` - treat both the pattern and subject as UTF8 + - `9` - prevents the pattern from being interpreted as UTF, no matter what + - `A` - as if the pattern had a `^` at the beginning + - `E` - DOLLAR_ENDONLY + - `f` - fails if there is not a match on the first line + - `i` - case insensitive + - `m` - multi-line, `^` and `$` match the beginning and end of lines, not of + the subject string + - `N` - turn off auto-capture, `(?foo)` is necessary to capture. + - `s` - `.` matches newline + - `U` - expressions are not greedy by default. `?` can be added to a + qualifier to make it greedy. + - `u` - same as `8` + - `W` - Unicode character properties + - `X` - "Extra", character escapes without special meaning (`\w` vs. `\a`) + are errors + - `x` - extended, comments (`#`) and newlines are ignored (extended) + - `Y` - pcre.NO_START_OPTIMIZE, + - `` - newlines are separated by `\r` + - `` - newlines are separated by `\r\n` (Windows default) + - `` - newlines are separated by `\n` (UNIX default) + - `` - newlines are separated by any of the above + - `` - newlines are separated by any of the above and Unicode newlines: + > single characters VT (vertical tab, U+000B), FF (form feed, U+000C), NEL + > (next line, U+0085), LS (line separator, U+2028), and PS (paragraph + > separator, U+2029). For the 8-bit library, the last two are recognized + > only in UTF-8 mode. + - `` - `\R` matches CR, LF, or CRLF + - `` - `\R` matches any unicode newline + - `` - Javascript compatibility + +`Sx` is enabled by default in order to encourage use of whitespace for better +readability. From aee43d976ba1b6eb13175b5a7c9bda1695ff840b Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Wed, 14 Jan 2015 20:12:53 -0500 Subject: [PATCH 0039/1263] Remove unnecessary options --- src/nre.nim | 2 -- test/init.nim | 2 +- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/src/nre.nim b/src/nre.nim index 613b3897f..ce51b6cd5 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -177,7 +177,6 @@ proc asSeq*(pattern: Captures, default: string = nil): seq[string] = let Options: Table[string, int] = { "8" : pcre.UTF8, "9" : pcre.NEVER_UTF, - "?" : pcre.NO_UTF8_CHECK, "A" : pcre.ANCHORED, # "C" : pcre.AUTO_CALLOUT, unsuported XXX "E" : pcre.DOLLAR_ENDONLY, @@ -185,7 +184,6 @@ let Options: Table[string, int] = { "i" : pcre.CASELESS, "m" : pcre.MULTILINE, "N" : pcre.NO_AUTO_CAPTURE, - "O" : pcre.NO_AUTO_POSSESS, "s" : pcre.DOTALL, "U" : pcre.UNGREEDY, "u" : pcre.UTF8, diff --git a/test/init.nim b/test/init.nim index eddcd6aca..9bf7c3c42 100644 --- a/test/init.nim +++ b/test/init.nim @@ -9,7 +9,7 @@ suite "Test NRE initialization": test "correct options": expect(SyntaxError): # ValueError would be bad discard initRegex("[0-9]+", - "89?AEfimNOsUWXxY") + "89AEfimNsUWXxY") test "incorrect options": expect(KeyError): discard initRegex("[0-9]+", "a") From a198c10d6c4f2c2c5434c0edb0fb4f519906433c Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Thu, 15 Jan 2015 16:19:56 -0500 Subject: [PATCH 0040/1263] Add study to docs --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index e89f70a07..303506bd8 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,8 @@ passed in order to encourage readable expressions, so `[0-9]+` is equivalent to the subject string - `N` - turn off auto-capture, `(?foo)` is necessary to capture. - `s` - `.` matches newline + - `S` - study the pattern to hopefully improve performance. JIT is unspported + at the moment. - `U` - expressions are not greedy by default. `?` can be added to a qualifier to make it greedy. - `u` - same as `8` From d649cec033e961e7d6e16a24e1551083e1ec187a Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Thu, 15 Jan 2015 17:07:07 -0500 Subject: [PATCH 0041/1263] s/asSeq/toSeq `toSeq` is a better name for it --- src/nre.nim | 10 +++++----- test/captures.nim | 8 ++++---- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/nre.nim b/src/nre.nim index ce51b6cd5..f5eaaf418 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -156,7 +156,7 @@ proc asTable*(pattern: CaptureBounds, default = None[Slice[int]]()): result = initTable[string, Option[Slice[int]]]() asTableImpl(nextVal.isNone) -template asSeqImpl(cond: bool): stmt {.immediate, dirty.} = +template toSeqImpl(cond: bool): stmt {.immediate, dirty.} = result = @[] for i in 0 .. foo)(?bar)?")) - check(ex1.captures.asSeq == @["foo", nil]) - check(ex1.captureBounds.asSeq == @[Some(0..3), None[Slice[int]]()]) - check(ex1.captures.asSeq("") == @["foo", ""]) + check(ex1.captures.toSeq == @["foo", nil]) + check(ex1.captureBounds.toSeq == @[Some(0..3), None[Slice[int]]()]) + check(ex1.captures.toSeq("") == @["foo", ""]) let ex2 = "foobar".match(initRegex("(?foo)(?bar)?")) - check(ex2.captures.asSeq == @["foo", "bar"]) + check(ex2.captures.toSeq == @["foo", "bar"]) From c0c0920d198381060c643af53a14e4b0751f5c39 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Thu, 15 Jan 2015 17:39:20 -0500 Subject: [PATCH 0042/1263] Add another split testcase Thanks Oleh Prypin for the suggestion! --- test/split.nim | 1 + 1 file changed, 1 insertion(+) diff --git a/test/split.nim b/test/split.nim index aee522991..dc12a2bb4 100644 --- a/test/split.nim +++ b/test/split.nim @@ -7,3 +7,4 @@ suite "string splitting": check("1 2 3 4 5 6 ".split(initRegex(" ", "S")) == @["1", "2", "3", "4", "5", "6", ""]) check("1 2 ".split(initRegex(" ", "S")) == @["1", "", "2", "", ""]) check("1 2".split(initRegex(" ", "S")) == @["1", "2"]) + check("foo".split(initRegex("foo")) == @["", ""]) From a03d178a561e50259465ba8b8e9972fad73e9dbc Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Thu, 15 Jan 2015 19:53:31 -0500 Subject: [PATCH 0043/1263] Implement capture iterator --- src/nre.nim | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/src/nre.nim b/src/nre.nim index f5eaaf418..1c803f27f 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -156,20 +156,25 @@ proc asTable*(pattern: CaptureBounds, default = None[Slice[int]]()): result = initTable[string, Option[Slice[int]]]() asTableImpl(nextVal.isNone) -template toSeqImpl(cond: bool): stmt {.immediate, dirty.} = - result = @[] +template itemsImpl(cond: bool): stmt {.immediate, dirty.} = for i in 0 .. Date: Thu, 15 Jan 2015 19:53:43 -0500 Subject: [PATCH 0044/1263] Add captures in split --- src/nre.nim | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/nre.nim b/src/nre.nim index 1c803f27f..3c1645456 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -408,6 +408,10 @@ proc split*(str: string, pattern: Regex): seq[string] = lastIdx = bounds.b + for cap in match.captures: + # if there are captures, include them in the result + result.add(cap) + # last match: Each match takes the previous substring, # but "1 2".split(/ /) needs to return @["1", "2"]. # This handles "2" From ca3e72ee27be61ea5d89357867906da9cd0b2f05 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Fri, 16 Jan 2015 19:10:48 -0500 Subject: [PATCH 0045/1263] Add `match(...)` to documentation --- README.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/README.md b/README.md index 303506bd8..5ffb2e5a0 100644 --- a/README.md +++ b/README.md @@ -68,3 +68,19 @@ passed in order to encourage readable expressions, so `[0-9]+` is equivalent to `Sx` is enabled by default in order to encourage use of whitespace for better readability. + +## Usage + +### `proc match(str: string, pattern: Regex, start = 0, endpos = -1): RegexMatch` +Tries to match the pattern, starting at start. This means that +`"foo".match(re"f") == true`, but `"foo".match(re"o") == false`. + +
+
`start`
+
The start point at which to start matching. `|abc` is `0`; `a|bc` is +`1`
+ +
`endpos`
+
The maximum index for a match; `-1` means the end of the string, otherwise +it's an exclusive upper bound.
+
From 1a5401ebcffdfa2e90888c1ce4e9126d993c67e8 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Fri, 16 Jan 2015 19:11:28 -0500 Subject: [PATCH 0046/1263] s/match/find/g The implementation needs to match the API after all ;) --- src/nre.nim | 15 ++++++--------- test/captures.nim | 28 ++++++++++++++-------------- 2 files changed, 20 insertions(+), 23 deletions(-) diff --git a/src/nre.nim b/src/nre.nim index 3c1645456..eb0210084 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -317,11 +317,7 @@ proc matchImpl(str: string, pattern: Regex, start, endpos: int, flags: int): Reg raise newException(AssertionError, "Internal error: errno " & $execRet) proc match*(str: string, pattern: Regex, start = 0, endpos = -1): RegexMatch = - ## Returns a `RegexMatch` if there is a match between `start` and `endpos`, otherwise - ## it returns nil. - ## - ## if `endpos == -1`, then `endpos = str.len` - return str.matchImpl(pattern, start, endpos, 0) + return str.matchImpl(pattern, start, endpos, pcre.ANCHORED) iterator findIter*(str: string, pattern: Regex, start = 0, endpos = -1): RegexMatch = # see pcredemo for explaination @@ -364,10 +360,11 @@ iterator findIter*(str: string, pattern: Regex, start = 0, endpos = -1): RegexMa yield currentMatch proc find*(str: string, pattern: Regex, start = 0, endpos = -1): RegexMatch = - for match in str.findIter(pattern, start, endpos): - return match - - return nil + ## Returns a `RegexMatch` if there is a match between `start` and `endpos`, otherwise + ## it returns nil. + ## + ## if `endpos == -1`, then `endpos = str.len` + return str.matchImpl(pattern, start, endpos, 0) proc findAll*(str: string, pattern: Regex, start = 0, endpos = -1): seq[RegexMatch] = accumulateResult(str.findIter(pattern, start, endpos)) diff --git a/test/captures.nim b/test/captures.nim index 9e7698f6b..15bdca7d9 100644 --- a/test/captures.nim +++ b/test/captures.nim @@ -8,29 +8,29 @@ suite "captures": test "capture bounds are correct": let ex1 = initRegex("([0-9])") - check("1 23".match(ex1).matchBounds == 0 .. 1) - check("1 23".match(ex1).captureBounds[0].get == 0 .. 1) - check("1 23".match(ex1, 1).matchBounds == 2 .. 3) - check("1 23".match(ex1, 3).matchBounds == 3 .. 4) + check("1 23".find(ex1).matchBounds == 0 .. 1) + check("1 23".find(ex1).captureBounds[0].get == 0 .. 1) + check("1 23".find(ex1, 1).matchBounds == 2 .. 3) + check("1 23".find(ex1, 3).matchBounds == 3 .. 4) let ex2 = initRegex("()()()()()()()()()()([0-9])") - check("824".match(ex2).captureBounds[0].get == 0 .. 0) - check("824".match(ex2).captureBounds[10].get == 0 .. 1) + check("824".find(ex2).captureBounds[0].get == 0 .. 0) + check("824".find(ex2).captureBounds[10].get == 0 .. 1) let ex3 = initRegex("([0-9]+)") - check("824".match(ex3).captureBounds[0].get == 0 .. 3) + check("824".find(ex3).captureBounds[0].get == 0 .. 3) test "named captures": - let ex1 = "foobar".match(initRegex("(?foo)(?bar)")) + let ex1 = "foobar".find(initRegex("(?foo)(?bar)")) check(ex1.captures["foo"] == "foo") check(ex1.captures["bar"] == "bar") - let ex2 = "foo".match(initRegex("(?foo)(?bar)?")) + let ex2 = "foo".find(initRegex("(?foo)(?bar)?")) check(ex2.captures["foo"] == "foo") check(ex2.captures["bar"] == nil) test "named capture bounds": - let ex1 = "foo".match(initRegex("(?foo)(?bar)?")) + let ex1 = "foo".find(initRegex("(?foo)(?bar)?")) check(ex1.captureBounds["foo"] == Some(0..3)) check(ex1.captureBounds["bar"] == None[Slice[int]]()) @@ -40,20 +40,20 @@ suite "captures": check(ex1.captureNameId == {"foo" : 0, "bar" : 1}.toTable()) test "named capture table": - let ex1 = "foo".match(initRegex("(?foo)(?bar)?")) + let ex1 = "foo".find(initRegex("(?foo)(?bar)?")) check(ex1.captures.asTable == {"foo" : "foo", "bar" : nil}.toTable()) check(ex1.captureBounds.asTable == {"foo" : Some(0..3), "bar" : None[Slice[int]]()}.toTable()) check(ex1.captures.asTable("") == {"foo" : "foo", "bar" : ""}.toTable()) - let ex2 = "foobar".match(initRegex("(?foo)(?bar)?")) + let ex2 = "foobar".find(initRegex("(?foo)(?bar)?")) check(ex2.captures.asTable == {"foo" : "foo", "bar" : "bar"}.toTable()) test "capture sequence": - let ex1 = "foo".match(initRegex("(?foo)(?bar)?")) + let ex1 = "foo".find(initRegex("(?foo)(?bar)?")) check(ex1.captures.toSeq == @["foo", nil]) check(ex1.captureBounds.toSeq == @[Some(0..3), None[Slice[int]]()]) check(ex1.captures.toSeq("") == @["foo", ""]) - let ex2 = "foobar".match(initRegex("(?foo)(?bar)?")) + let ex2 = "foobar".find(initRegex("(?foo)(?bar)?")) check(ex2.captures.toSeq == @["foo", "bar"]) From d4450aa1ee7eac491025073c010679ab31236f40 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Fri, 16 Jan 2015 19:12:05 -0500 Subject: [PATCH 0047/1263] Add additional tests for match --- test/match.nim | 6 ++++++ test/testall.nim | 1 + 2 files changed, 7 insertions(+) create mode 100644 test/match.nim diff --git a/test/match.nim b/test/match.nim new file mode 100644 index 000000000..b3cf1c5e5 --- /dev/null +++ b/test/match.nim @@ -0,0 +1,6 @@ +include nre, unittest + +suite "match": + test "upper bound must be exclusive": + check("abc".match(re"abc", endpos = 0) == nil) + check("abc".match(re"abc", endpos = 3) != nil) diff --git a/test/testall.nim b/test/testall.nim index 935bfde29..6fa3e9bca 100644 --- a/test/testall.nim +++ b/test/testall.nim @@ -3,3 +3,4 @@ import init import captures import find import split +import match From 4a67b723a0f986ab35dfe884c66ff750f2138791 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Fri, 16 Jan 2015 19:14:16 -0500 Subject: [PATCH 0048/1263] Update readme formatting --- README.md | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 5ffb2e5a0..934882951 100644 --- a/README.md +++ b/README.md @@ -71,16 +71,13 @@ readability. ## Usage -### `proc match(str: string, pattern: Regex, start = 0, endpos = -1): RegexMatch` +#### `proc match(str: string, pattern: Regex, start = 0, endpos = -1): RegexMatch` + Tries to match the pattern, starting at start. This means that `"foo".match(re"f") == true`, but `"foo".match(re"o") == false`. -
-
`start`
-
The start point at which to start matching. `|abc` is `0`; `a|bc` is -`1`
- -
`endpos`
-
The maximum index for a match; `-1` means the end of the string, otherwise -it's an exclusive upper bound.
-
+ - `start` + - The start point at which to start matching. `|abc` is `0`; `a|bc` is `1` + - `endpos` + - The maximum index for a match; `-1` means the end of the string, otherwise + it's an exclusive upper bound. From 01e22abb1978f51c6a7b3698b7dce3e63ec29e8a Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Fri, 16 Jan 2015 19:22:21 -0500 Subject: [PATCH 0049/1263] Fix upper bound handling --- src/nre.nim | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/nre.nim b/src/nre.nim index eb0210084..f41091009 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -301,10 +301,12 @@ proc matchImpl(str: string, pattern: Regex, start, endpos: int, flags: int): Reg result.pcreMatchBounds = newSeq[Slice[cint]](ceil(vecsize / 2).int) result.pcreMatchBounds.setLen(vecsize div 3) + let strlen = if endpos == -1: str.len else: endpos + let execRet = pcre.exec(pattern.pcreObj, pattern.pcreExtra, cstring(str), - cint(max(str.len, endpos)), + cint(strlen), cint(start), cint(flags), cast[ptr cint](addr result.pcreMatchBounds[0]), From 6a2ebb804fa95a874edb04237c542906170c946d Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Fri, 16 Jan 2015 19:22:36 -0500 Subject: [PATCH 0050/1263] Make it easier to run tests Now it's just `$ ./runtests.sh`! --- runtests.sh | 4 ++++ 1 file changed, 4 insertions(+) create mode 100755 runtests.sh diff --git a/runtests.sh b/runtests.sh new file mode 100755 index 000000000..39f9db286 --- /dev/null +++ b/runtests.sh @@ -0,0 +1,4 @@ +#!/usr/bin/sh +nim c --path:src -r --verbosity:0 --hints:off --linedir:on --debuginfo \ + --stacktrace:on --linetrace:on ./test/testall.nim \ + | grep -vE 'ProveInit|instantiation from here' From 39e13ba5d0f0a365967050ba0857842df1437127 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Fri, 16 Jan 2015 19:53:29 -0500 Subject: [PATCH 0051/1263] Document `find___(...)` --- README.md | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 934882951..7bea43564 100644 --- a/README.md +++ b/README.md @@ -71,7 +71,7 @@ readability. ## Usage -#### `proc match(str: string, pattern: Regex, start = 0, endpos = -1): RegexMatch` +#### `match(string, Regex, start = 0, endpos = -1): RegexMatch` Tries to match the pattern, starting at start. This means that `"foo".match(re"f") == true`, but `"foo".match(re"o") == false`. @@ -81,3 +81,26 @@ Tries to match the pattern, starting at start. This means that - `endpos` - The maximum index for a match; `-1` means the end of the string, otherwise it's an exclusive upper bound. + +[proc-match]: #match-string-regex-start--0-endpos---1-regexmatch + +#### `find(string, Regex, start = 0, endpos = -1): RegexMatch` + +Finds the given pattern in the string. Bounds work the same as for +[`match()`][proc-match], but instead of being anchored to the start of the string, +it can match at any point between `start` and `endpos`. + +[proc-find]: #find-string-regex-start--0-endpos---1-regexmatch + +#### `findIter(string, Regex, start = 0, endpos = -1): RegexMatch` + +Works the same as [find][proc-find], but finds every non-overlapping match. +`"2222".find(re"22")` is `"22", "22"`, not `"22", "22", "22"`. + +Arguments are the same as [`match()`][proc-match] + +Variants: + - `findAll` returns a `seq[RegexMatch]` + - `findAllStr` returns a `seq[string]` + +[iter-find]: #finditer-string-regex-start--0-endpos---1-regexmatch From 3fd514055448997a7d20715e5be12913e46599d4 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Fri, 16 Jan 2015 19:54:39 -0500 Subject: [PATCH 0052/1263] Update anchor values --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 7bea43564..10bd55896 100644 --- a/README.md +++ b/README.md @@ -82,7 +82,7 @@ Tries to match the pattern, starting at start. This means that - The maximum index for a match; `-1` means the end of the string, otherwise it's an exclusive upper bound. -[proc-match]: #match-string-regex-start--0-endpos---1-regexmatch +[proc-match]: #matchstring-regex-start--0-endpos---1-regexmatch #### `find(string, Regex, start = 0, endpos = -1): RegexMatch` @@ -90,7 +90,7 @@ Finds the given pattern in the string. Bounds work the same as for [`match()`][proc-match], but instead of being anchored to the start of the string, it can match at any point between `start` and `endpos`. -[proc-find]: #find-string-regex-start--0-endpos---1-regexmatch +[proc-find]: #findstring-regex-start--0-endpos---1-regexmatch #### `findIter(string, Regex, start = 0, endpos = -1): RegexMatch` @@ -103,4 +103,4 @@ Variants: - `findAll` returns a `seq[RegexMatch]` - `findAllStr` returns a `seq[string]` -[iter-find]: #finditer-string-regex-start--0-endpos---1-regexmatch +[iter-find]: #finditerstring-regex-start--0-endpos---1-regexmatch From 085903cd1063f401c710a5a0dd888fbda5a1bdb9 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Fri, 16 Jan 2015 19:56:05 -0500 Subject: [PATCH 0053/1263] Update readme formatting --- README.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 10bd55896..1f5f40cb7 100644 --- a/README.md +++ b/README.md @@ -87,20 +87,20 @@ Tries to match the pattern, starting at start. This means that #### `find(string, Regex, start = 0, endpos = -1): RegexMatch` Finds the given pattern in the string. Bounds work the same as for -[`match()`][proc-match], but instead of being anchored to the start of the string, -it can match at any point between `start` and `endpos`. +[`match(...)`][proc-match], but instead of being anchored to the start of the +string, it can match at any point between `start` and `endpos`. [proc-find]: #findstring-regex-start--0-endpos---1-regexmatch #### `findIter(string, Regex, start = 0, endpos = -1): RegexMatch` -Works the same as [find][proc-find], but finds every non-overlapping match. -`"2222".find(re"22")` is `"22", "22"`, not `"22", "22", "22"`. +Works the same as [`find(...)`][proc-find], but finds every non-overlapping +match. `"2222".find(re"22")` is `"22", "22"`, not `"22", "22", "22"`. -Arguments are the same as [`match()`][proc-match] +Arguments are the same as [`match(...)`][proc-match] Variants: - - `findAll` returns a `seq[RegexMatch]` - - `findAllStr` returns a `seq[string]` + - `findAll(...)` returns a `seq[RegexMatch]` + - `findAllStr(...)` returns a `seq[string]` [iter-find]: #finditerstring-regex-start--0-endpos---1-regexmatch From abccac2f06d0d8732d79843fda7c50814c8038a3 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Fri, 16 Jan 2015 20:04:20 -0500 Subject: [PATCH 0054/1263] Add `split(...)` --- README.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/README.md b/README.md index 1f5f40cb7..1a4b49fdd 100644 --- a/README.md +++ b/README.md @@ -104,3 +104,15 @@ Variants: - `findAllStr(...)` returns a `seq[string]` [iter-find]: #finditerstring-regex-start--0-endpos---1-regexmatch + +#### `split(string, Regex): seq[string]` + +Splits the string with the given regex. This works according to the rules that +Perl and Javascript use. + + - If the match is zero-width, then the string is still split: + `"123".split(r"") == @["1", "2", "3"]`. + - If the pattern has a capture in it, it is added after the string split: + `"12".split(re"(\d)") == @["", "1", "", "2", ""]`. + +[proc-split]: #splitstring-regex-seqstring From a7ce05b42fca227eb28e06a100219e2f07df6098 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Fri, 16 Jan 2015 20:04:38 -0500 Subject: [PATCH 0055/1263] Add tests for claims in documentation --- test/find.nim | 4 ++++ test/split.nim | 3 +++ 2 files changed, 7 insertions(+) diff --git a/test/find.nim b/test/find.nim index 87f8e0aae..6ea4f51e8 100644 --- a/test/find.nim +++ b/test/find.nim @@ -12,3 +12,7 @@ suite "find": check("1 2 3 4 5 ".findAll(initRegex(r" ", "S")).map( proc (a: RegexMatch): Slice[int] = a.matchBounds ) == @[1..2, 3..4, 5..6, 7..8, 9..10]) + + test "overlapping find": + check("222".findAllStr(re"22") == @["22"]) + check("2222".findAllStr(re"22") == @["22", "22"]) diff --git a/test/split.nim b/test/split.nim index dc12a2bb4..8366f801f 100644 --- a/test/split.nim +++ b/test/split.nim @@ -8,3 +8,6 @@ suite "string splitting": check("1 2 ".split(initRegex(" ", "S")) == @["1", "", "2", "", ""]) check("1 2".split(initRegex(" ", "S")) == @["1", "2"]) check("foo".split(initRegex("foo")) == @["", ""]) + + test "captured patterns": + check("12".split(re"(\d)") == @["", "1", "", "2", ""]) From 4d25a89ba990b602fdf19b1174a3eba180482029 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 17 Jan 2015 16:21:25 -0500 Subject: [PATCH 0056/1263] Add replace Also came a cross a find bug with 0-length subject strings --- src/nre.nim | 26 +++++++++++++++++++++----- test/find.nim | 4 ++++ test/replace.nim | 8 ++++++++ test/testall.nim | 1 + 4 files changed, 34 insertions(+), 5 deletions(-) create mode 100644 test/replace.nim diff --git a/src/nre.nim b/src/nre.nim index f41091009..89680ea5d 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -329,11 +329,7 @@ iterator findIter*(str: string, pattern: Regex, start = 0, endpos = -1): RegexMa var offset = start var previousMatch: RegexMatch - while offset != endpos: - if offset > endpos: - # eos occurs in the middle of a unicode char? die. - raise newException(AssertionError, "Input string has malformed unicode") - + while true: var flags = 0 if previousMatch != nil and @@ -356,11 +352,16 @@ iterator findIter*(str: string, pattern: Regex, start = 0, endpos = -1): RegexMa elif unicode: # XXX what about invalid unicode? offset += str.runeLenAt(offset) + assert(offset <= endpos) else: offset = currentMatch.matchBounds.b yield currentMatch + if offset >= endpos: + # do while + break + proc find*(str: string, pattern: Regex, start = 0, endpos = -1): RegexMatch = ## Returns a `RegexMatch` if there is a match between `start` and `endpos`, otherwise ## it returns nil. @@ -415,3 +416,18 @@ proc split*(str: string, pattern: Regex): seq[string] = # but "1 2".split(/ /) needs to return @["1", "2"]. # This handles "2" result.add(str.substr(lastIdx, str.len - 1)) + +proc replace*(str: string, pattern: Regex, + subproc: proc (match: RegexMatch): string): string = + # XXX seems very similar to split, maybe I can reduce code duplication + # somehow? + result = "" + var lastIdx = 0 + for match in str.findIter(pattern): + let bounds = match.matchBounds + result.add(str.substr(lastIdx, bounds.a - 1)) + result.add(subproc(match)) + + lastIdx = bounds.b + + result.add(str.substr(lastIdx, str.len - 1)) diff --git a/test/find.nim b/test/find.nim index 6ea4f51e8..1fd91f0d2 100644 --- a/test/find.nim +++ b/test/find.nim @@ -16,3 +16,7 @@ suite "find": test "overlapping find": check("222".findAllStr(re"22") == @["22"]) check("2222".findAllStr(re"22") == @["22", "22"]) + + test "len 0 find": + check("".findAllStr(re"\ ") == newSeq[string]()) + check("".findAllStr(re"") == @[""]) diff --git a/test/replace.nim b/test/replace.nim new file mode 100644 index 000000000..df7227f0b --- /dev/null +++ b/test/replace.nim @@ -0,0 +1,8 @@ +include nre +import unittest + +suite "replace": + test "replace with 0-length strings": + check("".replace(re"1", proc (v: RegexMatch): string = "1") == "") + check(" ".replace(re"", proc (v: RegexMatch): string = "1") == "1 ") + check("".replace(re"", proc (v: RegexMatch): string = "1") == "1") diff --git a/test/testall.nim b/test/testall.nim index 6fa3e9bca..89b661a2a 100644 --- a/test/testall.nim +++ b/test/testall.nim @@ -4,3 +4,4 @@ import captures import find import split import match +import replace From 447d0e0e8b7f3126ddbf21b44a3d182978805dfe Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 17 Jan 2015 22:45:23 -0500 Subject: [PATCH 0057/1263] Add more typical string replace --- src/nre.nim | 4 ++++ test/replace.nim | 5 +++++ 2 files changed, 9 insertions(+) diff --git a/src/nre.nim b/src/nre.nim index 89680ea5d..b66a1f6da 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -431,3 +431,7 @@ proc replace*(str: string, pattern: Regex, lastIdx = bounds.b result.add(str.substr(lastIdx, str.len - 1)) + +proc replace*(str: string, pattern: Regex, sub: string): string = + return str.replace(pattern, proc (match: RegexMatch): string = + sub % match.captures.toSeq ) diff --git a/test/replace.nim b/test/replace.nim index df7227f0b..ff2c4a2b5 100644 --- a/test/replace.nim +++ b/test/replace.nim @@ -6,3 +6,8 @@ suite "replace": check("".replace(re"1", proc (v: RegexMatch): string = "1") == "") check(" ".replace(re"", proc (v: RegexMatch): string = "1") == "1 ") check("".replace(re"", proc (v: RegexMatch): string = "1") == "1") + + test "regular replace": + check("123".replace(re"\d", "foo") == "foofoofoo") + check("123".replace(re"(\d)", "$1$1") == "112233") + check("123".replace(re"(\d)(\d)", "$1$2") == "123") From 2e80d64aaecf8eaf3bbd37387d3f7e08a2f8da85 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 17 Jan 2015 22:49:34 -0500 Subject: [PATCH 0058/1263] Update documentation --- README.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/README.md b/README.md index 1a4b49fdd..da9e62f4b 100644 --- a/README.md +++ b/README.md @@ -116,3 +116,15 @@ Perl and Javascript use. `"12".split(re"(\d)") == @["", "1", "", "2", ""]`. [proc-split]: #splitstring-regex-seqstring + +#### `replace(string, Regex, sub): string` + +Replaces each match of Regex in the string with `sub`. If `sub` is a `proc +(RegexMatch): string`, then it is executed with each match and the return value +is the replacement value. + +If `sub` is a string, then each match is replaced with that string, where the +captures are accessable as `$1`, `$2`, and so on. A literal `$` can be added by +doubling up like so: `$$`. + +[proc-replace]: #replacestring-regex-sub-string From 5f4095fd94f7fb2ac200038c93e1a3bb63b6b679 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sun, 18 Jan 2015 11:03:36 -0500 Subject: [PATCH 0059/1263] Add type documentation --- README.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/README.md b/README.md index da9e62f4b..554c461b9 100644 --- a/README.md +++ b/README.md @@ -128,3 +128,34 @@ captures are accessable as `$1`, `$2`, and so on. A literal `$` can be added by doubling up like so: `$$`. [proc-replace]: #replacestring-regex-sub-string + +### `RegexMatch` + +Represents the result of an execution. On failure, it is `nil`. The available +fields are as follows: + + - `pattern: Regex` - the pattern that is being matched + - `str: string` - the string that was matched against + - `captures[int|string]: string` - the string value of whatever was captured + at that id. If the value is invalid, then behavior is undefined. If the id + is `-1`, then the whole match is returned. If the given capture was not + matched, `nil` is returned. + - `captureBounds[int|string]: Option[Slice[int]]` - gets the bounds of the + given capture according to the same rules as the above. If the capture is + not filled, then `None` is returned. The upper bound is exclusive, the lower + bound is inclusive. + - `match: string` - the full text of the match. + - `matchBounds: Slice[int]` - the bounds of the match, as in `captureBounds[]` + - `(captureBounds|captures).asTable` - returns a table with each named capture + as a key. + - `(captureBounds|capture).toSeq` - returns all the captures by their number. + +### `Pattern` + +Represents the pattern that things are matched against, constructed with +`initRegex(string)` or `re(string)`. + + - `pattern: string` - the string that was used to create the pattern. + - `captureCount: int` - the number of captures that the pattern has. + - `captureNameId: Table[string, int]` - a table from the capture names to + their numeric id. From 88a4e6c740ebf0440f4bfe232a6088b4419b9f6c Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sun, 18 Jan 2015 11:34:56 -0500 Subject: [PATCH 0060/1263] Translate readme to asciidoc --- README.asciidoc | 152 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 152 insertions(+) create mode 100644 README.asciidoc diff --git a/README.asciidoc b/README.asciidoc new file mode 100644 index 000000000..94cf2dc6f --- /dev/null +++ b/README.asciidoc @@ -0,0 +1,152 @@ += N___ RegEx Library + +== What is NRE? + +A new regular expression library for Nim using PCRE to do the hard work. + +== Why? + +The http://nim-lang.org/re.html[re.nim] module that http://nim-lang.org/[Nim] +provides in it's standard library is inadequate: + + - It provides only a limited number of captures, while the underling library + (PCRE) allows an unlimited number. + - Instead of having one proc that returns both the bounds and substring, it + has one for the bounds and another for the substring. + - If the splitting regex is empty (`""`), then it returns the input string + instead of following https://ideone.com/dDMjmz[Perl], + http://jsfiddle.net/xtcbxurg/[Javascript], and + https://ideone.com/hYJuJ5[Java]'s precedent of returning a list of each + character (`"123".split(re"") == @["1", "2", "3"]`). + +== Documentation + +Creating a pattern is easy: `re"([0-9]+)"`. By default, the extended flag is +passed in order to encourage readable expressions, so `[0-9]+` is equivalent to +`[0-9] + # foo`. If you'd like to pass your own flags, then `re(r"([0-9]+)", +"")` will work. Here is a list of the available flags: + + - `8` - treat both the pattern and subject as UTF8 + - `9` - prevents the pattern from being interpreted as UTF, no matter what + - `A` - as if the pattern had a `^` at the beginning + - `E` - DOLLAR_ENDONLY + - `f` - fails if there is not a match on the first line + - `i` - case insensitive + - `m` - multi-line, `^` and `$` match the beginning and end of lines, not of the + subject string + - `N` - turn off auto-capture, `(?foo)` is necessary to capture. + - `s` - `.` matches newline + - `S` - study the pattern to hopefully improve performance. JIT is unspported at + the moment. + - `U` - expressions are not greedy by default. `?` can be added to a qualifier + to make it greedy. + - `u` - same as `8` + - `W` - Unicode character properties + - `X` - "Extra", character escapes without special meaning (`\w` vs. `\a`) are + errors + - `x` - extended, comments (`#`) and newlines are ignored (extended) + - `Y` - pcre.NO_START_OPTIMIZE, + - `` - newlines are separated by `\r` + - `` - newlines are separated by `\r\n` (Windows default) + - `` - newlines are separated by `\n` (UNIX default) + - `` - newlines are separated by any of the above + - `` - newlines are separated by any of the above and Unicode newlines: + [quote, , man pcre] + ____ + single characters VT (vertical tab, U+000B), FF (form feed, U+000C), NEL + (next line, U+0085), LS (line separator, U+2028), and PS (paragraph + separator, U+2029). For the 8-bit library, the last two are recognized + only in UTF-8 mode. + ____ + - `` - `\R` matches CR, LF, or CRLF + - `` - `\R` matches any unicode newline + - `` - Javascript compatibility + +`Sx` is enabled by default in order to encourage use of whitespace for better +readability. + +=== Procedures + +[[proc-match]] +==== `match(string, Regex, start = 0, endpos = -1): RegexMatch` + +Tries to match the pattern, starting at start. This means that +`"foo".match(re"f") == true`, but `"foo".match(re"o") == false`. + +`start` :: The start point at which to start matching. `|abc` is `0`; `a|bc` + is `1` +`endpos` :: The maximum index for a match; `-1` means the end of the string, + otherwise it's an exclusive upper bound. + +[[proc-find]] +==== `find(string, Regex, start = 0, endpos = -1): RegexMatch` + +Finds the given pattern in the string. Bounds work the same as for +link:#proc-match[`match(...)`], but instead of being anchored to the start of +the string, it can match at any point between `start` and `endpos`. + +[[iter-find]] +==== `findIter(string, Regex, start = 0, endpos = -1): RegexMatch` + +Works the same as link:#proc-find[`find(...)`], but finds every non-overlapping +match. `"2222".find(re"22")` is `"22", "22"`, not `"22", "22", "22"`. + +Arguments are the same as link:#proc-match[`match(...)`] + +Variants: + - `findAll(...)` returns a `seq[RegexMatch]` + - `findAllStr(...)` returns a `seq[string]` + +[[proc-split]] +==== `split(string, Regex): seq[string]` + +Splits the string with the given regex. This works according to the rules that +Perl and Javascript use. + + - If the match is zero-width, then the string is still split: + `"123".split(r"") == @["1", "2", "3"]`. + - If the pattern has a capture in it, it is added after the string split: + `"12".split(re"(\d)") == @["", "1", "", "2", ""]`. + +[[proc-replace]] +==== `replace(string, Regex, sub): string` + +Replaces each match of Regex in the string with `sub`. + +If `sub` is a `proc (RegexMatch): string`, then it is executed with each match +and the return value is the replacement value. + +If `sub` is a string, then each match is replaced with that string, where the +captures are accessable as `$1`, `$2`, and so on. A literal `$` can be added by +doubling up like so: `$$`. + +=== `RegexMatch` + +Represents the result of an execution. On failure, it is `nil`. The available +fields are as follows: + +`pattern: Regex` :: the pattern that is being matched +`str: string` :: the string that was matched against +`captures[int|string]: string` :: the string value of whatever was captured + at that id. If the value is invalid, then behavior is undefined. If the id + is `-1`, then the whole match is returned. If the given capture was not + matched, `nil` is returned. +`captureBounds[int|string]: Option[Slice[int]]` :: gets the bounds of the + given capture according to the same rules as the above. If the capture is + not filled, then `None` is returned. The upper bound is exclusive, the lower + bound is inclusive. +`match: string` :: the full text of the match. +`matchBounds: Slice[int]` :: the bounds of the match, as in `captureBounds[]` +`(captureBounds|captures).asTable` :: returns a table with each named capture + as a key. +`(captureBounds|capture).toSeq` :: returns all the captures by their number. + +=== `Pattern` + +Represents the pattern that things are matched against, constructed with +`initRegex(string)` or `re(string)`. + +`pattern: string` :: the string that was used to create the pattern. +`captureCount: int` :: the number of captures that the pattern has. +`captureNameId: Table[string, int]` :: a table from the capture names to + their numeric id. From a922418443f7aa754f7eee105fd10238c2ba5e6c Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sun, 18 Jan 2015 11:37:23 -0500 Subject: [PATCH 0061/1263] Fix readme formatting --- README.asciidoc | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README.asciidoc b/README.asciidoc index 94cf2dc6f..519df2238 100644 --- a/README.asciidoc +++ b/README.asciidoc @@ -51,13 +51,13 @@ passed in order to encourage readable expressions, so `[0-9]+` is equivalent to - `` - newlines are separated by `\n` (UNIX default) - `` - newlines are separated by any of the above - `` - newlines are separated by any of the above and Unicode newlines: - [quote, , man pcre] - ____ - single characters VT (vertical tab, U+000B), FF (form feed, U+000C), NEL - (next line, U+0085), LS (line separator, U+2028), and PS (paragraph - separator, U+2029). For the 8-bit library, the last two are recognized - only in UTF-8 mode. - ____ +[quote, , man pcre] +____ +single characters VT (vertical tab, U+000B), FF (form feed, U+000C), NEL +(next line, U+0085), LS (line separator, U+2028), and PS (paragraph +separator, U+2029). For the 8-bit library, the last two are recognized +only in UTF-8 mode. +____ - `` - `\R` matches CR, LF, or CRLF - `` - `\R` matches any unicode newline - `` - Javascript compatibility From cc0d16c5ee33b3050b83371ac2c3385a5f5154da Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sun, 18 Jan 2015 11:37:44 -0500 Subject: [PATCH 0062/1263] Remove markdown readme --- README.md | 161 ------------------------------------------------------ 1 file changed, 161 deletions(-) delete mode 100644 README.md diff --git a/README.md b/README.md deleted file mode 100644 index 554c461b9..000000000 --- a/README.md +++ /dev/null @@ -1,161 +0,0 @@ -# N___ RegEx Library - -## What is NRE? - -A new regular expression library for Nim using PCRE to do the hard work. - -## Why? - -The [re.nim][] module that [Nim][] provides in it's standard library is -inadequate: - - - It provides only a limited number of captures, while the underling library - (PCRE) allows an unlimited number. - - Instead of having one proc that returns both the bounds and substring, it - has one for the bounds and another for the substring. - - If the splitting regex is empty (`""`), then it returns the input string - instead of following [Perl][], [Javascript][], and [Java][]'s precedent of - returning a list of each character (`"123".split(re"") == @["1", "2", "3"]`). - -[re.nim]: http://nim-lang.org/re.html -[Nim]: http://nim-lang.org/ -[Perl]: https://ideone.com/dDMjmz -[Javascript]: http://jsfiddle.net/xtcbxurg/ -[Java]: https://ideone.com/hYJuJ5 - - -# Documentation - -## Construction - -Creating a pattern is easy: `re"([0-9]+)"`. By default, the extended flag is -passed in order to encourage readable expressions, so `[0-9]+` is equivalent to -`[0-9] + # foo`. If you'd like to pass your own flags, then `re(r"([0-9]+)", -"")` will work. Here is a list of the available flags: - - - `8` - treat both the pattern and subject as UTF8 - - `9` - prevents the pattern from being interpreted as UTF, no matter what - - `A` - as if the pattern had a `^` at the beginning - - `E` - DOLLAR_ENDONLY - - `f` - fails if there is not a match on the first line - - `i` - case insensitive - - `m` - multi-line, `^` and `$` match the beginning and end of lines, not of - the subject string - - `N` - turn off auto-capture, `(?foo)` is necessary to capture. - - `s` - `.` matches newline - - `S` - study the pattern to hopefully improve performance. JIT is unspported - at the moment. - - `U` - expressions are not greedy by default. `?` can be added to a - qualifier to make it greedy. - - `u` - same as `8` - - `W` - Unicode character properties - - `X` - "Extra", character escapes without special meaning (`\w` vs. `\a`) - are errors - - `x` - extended, comments (`#`) and newlines are ignored (extended) - - `Y` - pcre.NO_START_OPTIMIZE, - - `` - newlines are separated by `\r` - - `` - newlines are separated by `\r\n` (Windows default) - - `` - newlines are separated by `\n` (UNIX default) - - `` - newlines are separated by any of the above - - `` - newlines are separated by any of the above and Unicode newlines: - > single characters VT (vertical tab, U+000B), FF (form feed, U+000C), NEL - > (next line, U+0085), LS (line separator, U+2028), and PS (paragraph - > separator, U+2029). For the 8-bit library, the last two are recognized - > only in UTF-8 mode. - - `` - `\R` matches CR, LF, or CRLF - - `` - `\R` matches any unicode newline - - `` - Javascript compatibility - -`Sx` is enabled by default in order to encourage use of whitespace for better -readability. - -## Usage - -#### `match(string, Regex, start = 0, endpos = -1): RegexMatch` - -Tries to match the pattern, starting at start. This means that -`"foo".match(re"f") == true`, but `"foo".match(re"o") == false`. - - - `start` - - The start point at which to start matching. `|abc` is `0`; `a|bc` is `1` - - `endpos` - - The maximum index for a match; `-1` means the end of the string, otherwise - it's an exclusive upper bound. - -[proc-match]: #matchstring-regex-start--0-endpos---1-regexmatch - -#### `find(string, Regex, start = 0, endpos = -1): RegexMatch` - -Finds the given pattern in the string. Bounds work the same as for -[`match(...)`][proc-match], but instead of being anchored to the start of the -string, it can match at any point between `start` and `endpos`. - -[proc-find]: #findstring-regex-start--0-endpos---1-regexmatch - -#### `findIter(string, Regex, start = 0, endpos = -1): RegexMatch` - -Works the same as [`find(...)`][proc-find], but finds every non-overlapping -match. `"2222".find(re"22")` is `"22", "22"`, not `"22", "22", "22"`. - -Arguments are the same as [`match(...)`][proc-match] - -Variants: - - `findAll(...)` returns a `seq[RegexMatch]` - - `findAllStr(...)` returns a `seq[string]` - -[iter-find]: #finditerstring-regex-start--0-endpos---1-regexmatch - -#### `split(string, Regex): seq[string]` - -Splits the string with the given regex. This works according to the rules that -Perl and Javascript use. - - - If the match is zero-width, then the string is still split: - `"123".split(r"") == @["1", "2", "3"]`. - - If the pattern has a capture in it, it is added after the string split: - `"12".split(re"(\d)") == @["", "1", "", "2", ""]`. - -[proc-split]: #splitstring-regex-seqstring - -#### `replace(string, Regex, sub): string` - -Replaces each match of Regex in the string with `sub`. If `sub` is a `proc -(RegexMatch): string`, then it is executed with each match and the return value -is the replacement value. - -If `sub` is a string, then each match is replaced with that string, where the -captures are accessable as `$1`, `$2`, and so on. A literal `$` can be added by -doubling up like so: `$$`. - -[proc-replace]: #replacestring-regex-sub-string - -### `RegexMatch` - -Represents the result of an execution. On failure, it is `nil`. The available -fields are as follows: - - - `pattern: Regex` - the pattern that is being matched - - `str: string` - the string that was matched against - - `captures[int|string]: string` - the string value of whatever was captured - at that id. If the value is invalid, then behavior is undefined. If the id - is `-1`, then the whole match is returned. If the given capture was not - matched, `nil` is returned. - - `captureBounds[int|string]: Option[Slice[int]]` - gets the bounds of the - given capture according to the same rules as the above. If the capture is - not filled, then `None` is returned. The upper bound is exclusive, the lower - bound is inclusive. - - `match: string` - the full text of the match. - - `matchBounds: Slice[int]` - the bounds of the match, as in `captureBounds[]` - - `(captureBounds|captures).asTable` - returns a table with each named capture - as a key. - - `(captureBounds|capture).toSeq` - returns all the captures by their number. - -### `Pattern` - -Represents the pattern that things are matched against, constructed with -`initRegex(string)` or `re(string)`. - - - `pattern: string` - the string that was used to create the pattern. - - `captureCount: int` - the number of captures that the pattern has. - - `captureNameId: Table[string, int]` - a table from the capture names to - their numeric id. From 39bc8c2bfbf4894f2fd411d1db62d31f3788d001 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sun, 18 Jan 2015 11:47:05 -0500 Subject: [PATCH 0063/1263] Update Readme --- README.asciidoc | 90 +++++++++++++++++++++++-------------------------- 1 file changed, 42 insertions(+), 48 deletions(-) diff --git a/README.asciidoc b/README.asciidoc index 519df2238..d16f9e0ac 100644 --- a/README.asciidoc +++ b/README.asciidoc @@ -1,13 +1,13 @@ -= N___ RegEx Library += NRE == What is NRE? -A new regular expression library for Nim using PCRE to do the hard work. +A regular expression library for Nim using PCRE to do the hard work. == Why? The http://nim-lang.org/re.html[re.nim] module that http://nim-lang.org/[Nim] -provides in it's standard library is inadequate: +provides in its standard library is inadequate: - It provides only a limited number of captures, while the underling library (PCRE) allows an unlimited number. @@ -21,50 +21,6 @@ provides in it's standard library is inadequate: == Documentation -Creating a pattern is easy: `re"([0-9]+)"`. By default, the extended flag is -passed in order to encourage readable expressions, so `[0-9]+` is equivalent to -`[0-9] + # foo`. If you'd like to pass your own flags, then `re(r"([0-9]+)", -"")` will work. Here is a list of the available flags: - - - `8` - treat both the pattern and subject as UTF8 - - `9` - prevents the pattern from being interpreted as UTF, no matter what - - `A` - as if the pattern had a `^` at the beginning - - `E` - DOLLAR_ENDONLY - - `f` - fails if there is not a match on the first line - - `i` - case insensitive - - `m` - multi-line, `^` and `$` match the beginning and end of lines, not of the - subject string - - `N` - turn off auto-capture, `(?foo)` is necessary to capture. - - `s` - `.` matches newline - - `S` - study the pattern to hopefully improve performance. JIT is unspported at - the moment. - - `U` - expressions are not greedy by default. `?` can be added to a qualifier - to make it greedy. - - `u` - same as `8` - - `W` - Unicode character properties - - `X` - "Extra", character escapes without special meaning (`\w` vs. `\a`) are - errors - - `x` - extended, comments (`#`) and newlines are ignored (extended) - - `Y` - pcre.NO_START_OPTIMIZE, - - `` - newlines are separated by `\r` - - `` - newlines are separated by `\r\n` (Windows default) - - `` - newlines are separated by `\n` (UNIX default) - - `` - newlines are separated by any of the above - - `` - newlines are separated by any of the above and Unicode newlines: -[quote, , man pcre] -____ -single characters VT (vertical tab, U+000B), FF (form feed, U+000C), NEL -(next line, U+0085), LS (line separator, U+2028), and PS (paragraph -separator, U+2029). For the 8-bit library, the last two are recognized -only in UTF-8 mode. -____ - - `` - `\R` matches CR, LF, or CRLF - - `` - `\R` matches any unicode newline - - `` - Javascript compatibility - -`Sx` is enabled by default in order to encourage use of whitespace for better -readability. - === Procedures [[proc-match]] @@ -144,9 +100,47 @@ fields are as follows: === `Pattern` Represents the pattern that things are matched against, constructed with -`initRegex(string)` or `re(string)`. +`initRegex(string)` or `re(string)`. Examples: `re"foo"`, `re(r"foo # comment", +"Sx")`. `pattern: string` :: the string that was used to create the pattern. `captureCount: int` :: the number of captures that the pattern has. `captureNameId: Table[string, int]` :: a table from the capture names to their numeric id. + +==== Flags + - `8` - treat both the pattern and subject as UTF8 + - `9` - prevents the pattern from being interpreted as UTF, no matter what + - `A` - as if the pattern had a `^` at the beginning + - `E` - DOLLAR_ENDONLY + - `f` - fails if there is not a match on the first line + - `i` - case insensitive + - `m` - multi-line, `^` and `$` match the beginning and end of lines, not of the + subject string + - `N` - turn off auto-capture, `(?foo)` is necessary to capture. + - `s` - `.` matches newline + - `S` - study the pattern to hopefully improve performance. JIT is unspported at + the moment. + - `U` - expressions are not greedy by default. `?` can be added to a qualifier + to make it greedy. + - `u` - same as `8` + - `W` - Unicode character properties + - `X` - "Extra", character escapes without special meaning (`\w` vs. `\a`) are + errors + - `x` - extended, comments (`#`) and newlines are ignored (extended) + - `Y` - pcre.NO_START_OPTIMIZE, + - `` - newlines are separated by `\r` + - `` - newlines are separated by `\r\n` (Windows default) + - `` - newlines are separated by `\n` (UNIX default) + - `` - newlines are separated by any of the above + - `` - newlines are separated by any of the above and Unicode newlines: +[quote, , man pcre] +____ +single characters VT (vertical tab, U+000B), FF (form feed, U+000C), NEL +(next line, U+0085), LS (line separator, U+2028), and PS (paragraph +separator, U+2029). For the 8-bit library, the last two are recognized +only in UTF-8 mode. +____ + - `` - `\R` matches CR, LF, or CRLF + - `` - `\R` matches any unicode newline + - `` - Javascript compatibility From 79b43b19a8254ef8e2e6c1ea7d18e9d252849a52 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sun, 18 Jan 2015 12:04:09 -0500 Subject: [PATCH 0064/1263] Add examples --- README.asciidoc | 24 +++++++++++++++--------- test/match.nim | 7 +++++++ 2 files changed, 22 insertions(+), 9 deletions(-) diff --git a/README.asciidoc b/README.asciidoc index d16f9e0ac..f4a87b65a 100644 --- a/README.asciidoc +++ b/README.asciidoc @@ -83,18 +83,24 @@ fields are as follows: `pattern: Regex` :: the pattern that is being matched `str: string` :: the string that was matched against -`captures[int|string]: string` :: the string value of whatever was captured - at that id. If the value is invalid, then behavior is undefined. If the id - is `-1`, then the whole match is returned. If the given capture was not - matched, `nil` is returned. -`captureBounds[int|string]: Option[Slice[int]]` :: gets the bounds of the - given capture according to the same rules as the above. If the capture is - not filled, then `None` is returned. The upper bound is exclusive, the lower - bound is inclusive. +`captures[]: string` :: the string value of whatever was captured +at that id. If the value is invalid, then behavior is undefined. If the id is +`-1`, then the whole match is returned. If the given capture was not matched, +`nil` is returned. + - `"abc".match(re"(\w)").captures[0] == "a"` + - `"abc".match(re"(?\w)").captures["letter"] == "a"` + - `"abc".match(re"(\w)\w").captures[-1] == "ab"` +`captureBounds[]: Option[Slice[int]]` :: gets the bounds of the +given capture according to the same rules as the above. If the capture is not +filled, then `None` is returned. The upper bound is exclusive, the lower bound +is inclusive. + - `"abc".match(re"(\w)").captureBounds[0] == 0..1` + - `"abc".match(re"").captureBounds[-1] == 0..0` + - `"abc".match(re"abc").captureBounds[-1] == 0..3` `match: string` :: the full text of the match. `matchBounds: Slice[int]` :: the bounds of the match, as in `captureBounds[]` `(captureBounds|captures).asTable` :: returns a table with each named capture - as a key. +as a key. `(captureBounds|capture).toSeq` :: returns all the captures by their number. === `Pattern` diff --git a/test/match.nim b/test/match.nim index b3cf1c5e5..7fa00610a 100644 --- a/test/match.nim +++ b/test/match.nim @@ -4,3 +4,10 @@ suite "match": test "upper bound must be exclusive": check("abc".match(re"abc", endpos = 0) == nil) check("abc".match(re"abc", endpos = 3) != nil) + test "examples": + check("abc".match(re"(\w)").captures[0] == "a") + check("abc".match(re"(?\w)").captures["letter"] == "a") + check("abc".match(re"(\w)\w").captures[-1] == "ab") + check("abc".match(re"(\w)").captureBounds[0].get == 0..1) + check("abc".match(re"").captureBounds[-1].get == 0..0) + check("abc".match(re"abc").captureBounds[-1].get == 0..3) From c70a9932b909cc773ff4778f75dacca98a56c722 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sun, 18 Jan 2015 12:05:45 -0500 Subject: [PATCH 0065/1263] Adjust formatting --- README.asciidoc | 1 + 1 file changed, 1 insertion(+) diff --git a/README.asciidoc b/README.asciidoc index f4a87b65a..702e6cc6b 100644 --- a/README.asciidoc +++ b/README.asciidoc @@ -50,6 +50,7 @@ match. `"2222".find(re"22")` is `"22", "22"`, not `"22", "22", "22"`. Arguments are the same as link:#proc-match[`match(...)`] Variants: + - `findAll(...)` returns a `seq[RegexMatch]` - `findAllStr(...)` returns a `seq[string]` From d407282e357e1d649e884b24df00a1d959b10d20 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sun, 18 Jan 2015 12:07:31 -0500 Subject: [PATCH 0066/1263] Change readme formatting --- README.asciidoc | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/README.asciidoc b/README.asciidoc index 702e6cc6b..67454e445 100644 --- a/README.asciidoc +++ b/README.asciidoc @@ -21,10 +21,10 @@ provides in its standard library is inadequate: == Documentation -=== Procedures +=== Operations [[proc-match]] -==== `match(string, Regex, start = 0, endpos = -1): RegexMatch` +==== match(string, Regex, start = 0, endpos = -1): RegexMatch Tries to match the pattern, starting at start. This means that `"foo".match(re"f") == true`, but `"foo".match(re"o") == false`. @@ -35,14 +35,14 @@ Tries to match the pattern, starting at start. This means that otherwise it's an exclusive upper bound. [[proc-find]] -==== `find(string, Regex, start = 0, endpos = -1): RegexMatch` +==== find(string, Regex, start = 0, endpos = -1): RegexMatch Finds the given pattern in the string. Bounds work the same as for link:#proc-match[`match(...)`], but instead of being anchored to the start of the string, it can match at any point between `start` and `endpos`. [[iter-find]] -==== `findIter(string, Regex, start = 0, endpos = -1): RegexMatch` +==== findIter(string, Regex, start = 0, endpos = -1): RegexMatch Works the same as link:#proc-find[`find(...)`], but finds every non-overlapping match. `"2222".find(re"22")` is `"22", "22"`, not `"22", "22", "22"`. @@ -55,7 +55,7 @@ Variants: - `findAllStr(...)` returns a `seq[string]` [[proc-split]] -==== `split(string, Regex): seq[string]` +==== split(string, Regex): seq[string] Splits the string with the given regex. This works according to the rules that Perl and Javascript use. @@ -66,7 +66,7 @@ Perl and Javascript use. `"12".split(re"(\d)") == @["", "1", "", "2", ""]`. [[proc-replace]] -==== `replace(string, Regex, sub): string` +==== replace(string, Regex, sub): string Replaces each match of Regex in the string with `sub`. @@ -77,7 +77,7 @@ If `sub` is a string, then each match is replaced with that string, where the captures are accessable as `$1`, `$2`, and so on. A literal `$` can be added by doubling up like so: `$$`. -=== `RegexMatch` +=== RegexMatch Represents the result of an execution. On failure, it is `nil`. The available fields are as follows: @@ -104,7 +104,7 @@ is inclusive. as a key. `(captureBounds|capture).toSeq` :: returns all the captures by their number. -=== `Pattern` +=== Pattern Represents the pattern that things are matched against, constructed with `initRegex(string)` or `re(string)`. Examples: `re"foo"`, `re(r"foo # comment", From 0aaad199a47405a4bf6faca256d0a905ab9b893c Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sun, 18 Jan 2015 12:08:49 -0500 Subject: [PATCH 0067/1263] Clarify iterator status --- README.asciidoc | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.asciidoc b/README.asciidoc index 67454e445..5a5b7d41a 100644 --- a/README.asciidoc +++ b/README.asciidoc @@ -42,7 +42,7 @@ link:#proc-match[`match(...)`], but instead of being anchored to the start of the string, it can match at any point between `start` and `endpos`. [[iter-find]] -==== findIter(string, Regex, start = 0, endpos = -1): RegexMatch +==== iterator findIter(string, Regex, start = 0, endpos = -1): RegexMatch Works the same as link:#proc-find[`find(...)`], but finds every non-overlapping match. `"2222".find(re"22")` is `"22", "22"`, not `"22", "22", "22"`. @@ -51,8 +51,8 @@ Arguments are the same as link:#proc-match[`match(...)`] Variants: - - `findAll(...)` returns a `seq[RegexMatch]` - - `findAllStr(...)` returns a `seq[string]` + - `proc findAll(...)` returns a `seq[RegexMatch]` + - `proc findAllStr(...)` returns a `seq[string]` [[proc-split]] ==== split(string, Regex): seq[string] From ff2e3de580e798c4061b8b8a359392974c9091a0 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sun, 18 Jan 2015 12:18:43 -0500 Subject: [PATCH 0068/1263] Make find more prominent --- README.asciidoc | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/README.asciidoc b/README.asciidoc index 5a5b7d41a..877ffce47 100644 --- a/README.asciidoc +++ b/README.asciidoc @@ -23,23 +23,22 @@ provides in its standard library is inadequate: === Operations -[[proc-match]] -==== match(string, Regex, start = 0, endpos = -1): RegexMatch +[[proc-find]] +==== find(string, Regex, start = 0, endpos = -1): RegexMatch -Tries to match the pattern, starting at start. This means that -`"foo".match(re"f") == true`, but `"foo".match(re"o") == false`. +Finds the given pattern in the string between the end and start positions. `start` :: The start point at which to start matching. `|abc` is `0`; `a|bc` is `1` `endpos` :: The maximum index for a match; `-1` means the end of the string, otherwise it's an exclusive upper bound. -[[proc-find]] -==== find(string, Regex, start = 0, endpos = -1): RegexMatch +[[proc-match]] +==== match(string, Regex, start = 0, endpos = -1): RegexMatch -Finds the given pattern in the string. Bounds work the same as for -link:#proc-match[`match(...)`], but instead of being anchored to the start of -the string, it can match at any point between `start` and `endpos`. +Like link:#proc-find[`find(...)`], but anchored to the start of the string. +This means that `"foo".match(re"f") == true`, but `"foo".match(re"o") == +false`. [[iter-find]] ==== iterator findIter(string, Regex, start = 0, endpos = -1): RegexMatch @@ -47,7 +46,7 @@ the string, it can match at any point between `start` and `endpos`. Works the same as link:#proc-find[`find(...)`], but finds every non-overlapping match. `"2222".find(re"22")` is `"22", "22"`, not `"22", "22", "22"`. -Arguments are the same as link:#proc-match[`match(...)`] +Arguments are the same as link:#proc-find[`find(...)`] Variants: From 1bcaa2172967f78513cb638bfc958e2e39d9a049 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sun, 18 Jan 2015 12:28:19 -0500 Subject: [PATCH 0069/1263] Add maxsplit --- README.asciidoc | 4 +++- src/nre.nim | 7 ++++++- test/split.nim | 5 +++++ 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/README.asciidoc b/README.asciidoc index 877ffce47..2fcc05ded 100644 --- a/README.asciidoc +++ b/README.asciidoc @@ -54,7 +54,7 @@ Variants: - `proc findAllStr(...)` returns a `seq[string]` [[proc-split]] -==== split(string, Regex): seq[string] +==== split(string, Regex, maxsplit = -1): seq[string] Splits the string with the given regex. This works according to the rules that Perl and Javascript use. @@ -63,6 +63,8 @@ Perl and Javascript use. `"123".split(r"") == @["1", "2", "3"]`. - If the pattern has a capture in it, it is added after the string split: `"12".split(re"(\d)") == @["", "1", "", "2", ""]`. + - If `maxsplit != -1`, then the string will only be split `maxsplit` times. + `"123".split(re"", maxsplit = 1) == @["1", "23"]` [[proc-replace]] ==== replace(string, Regex, sub): string diff --git a/src/nre.nim b/src/nre.nim index b66a1f6da..6ba5f560f 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -384,9 +384,10 @@ proc renderBounds(str: string, bounds: Slice[int]): string = for i in bounds.a .. bounds.b: result.add("^") -proc split*(str: string, pattern: Regex): seq[string] = +proc split*(str: string, pattern: Regex, maxSplit = -1): seq[string] = result = @[] var lastIdx = 0 + var splits = 0 for match in str.findIter(pattern): # upper bound is exclusive, lower is inclusive: @@ -405,6 +406,7 @@ proc split*(str: string, pattern: Regex): seq[string] = discard else: result.add(str.substr(lastIdx, bounds.a - 1)) + splits += 1 lastIdx = bounds.b @@ -412,6 +414,9 @@ proc split*(str: string, pattern: Regex): seq[string] = # if there are captures, include them in the result result.add(cap) + if splits == maxSplit: + break + # last match: Each match takes the previous substring, # but "1 2".split(/ /) needs to return @["1", "2"]. # This handles "2" diff --git a/test/split.nim b/test/split.nim index 8366f801f..838f06261 100644 --- a/test/split.nim +++ b/test/split.nim @@ -11,3 +11,8 @@ suite "string splitting": test "captured patterns": check("12".split(re"(\d)") == @["", "1", "", "2", ""]) + + test "maxsplit": + check("123".split(re"", maxsplit = 1) == @["1", "23"]) + check("123".split(re"", maxsplit = 0) == @["123"]) + check("123".split(re"", maxsplit = -1) == @["1", "2", "3"]) From d62b41fa1cd7746166d7951f74f8599473c2e148 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sun, 18 Jan 2015 12:29:10 -0500 Subject: [PATCH 0070/1263] s/asTable/toTable/ toTable is more consistent with toSeq --- README.asciidoc | 2 +- src/nre.nim | 10 +++++----- test/captures.nim | 8 ++++---- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/README.asciidoc b/README.asciidoc index 2fcc05ded..424a37a9f 100644 --- a/README.asciidoc +++ b/README.asciidoc @@ -101,7 +101,7 @@ is inclusive. - `"abc".match(re"abc").captureBounds[-1] == 0..3` `match: string` :: the full text of the match. `matchBounds: Slice[int]` :: the bounds of the match, as in `captureBounds[]` -`(captureBounds|captures).asTable` :: returns a table with each named capture +`(captureBounds|captures).toTable` :: returns a table with each named capture as a key. `(captureBounds|capture).toSeq` :: returns all the captures by their number. diff --git a/src/nre.nim b/src/nre.nim index 6ba5f560f..fbc143cd1 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -137,7 +137,7 @@ proc `[]`*(pattern: Captures, name: string): string = let pattern = RegexMatch(pattern) return pattern.captures[pattern.pattern.captureNameToId.fget(name)] -template asTableImpl(cond: bool): stmt {.immediate, dirty.} = +template toTableImpl(cond: bool): stmt {.immediate, dirty.} = for key in RegexMatch(pattern).pattern.captureNameId.keys: let nextVal = pattern[key] if cond: @@ -145,16 +145,16 @@ template asTableImpl(cond: bool): stmt {.immediate, dirty.} = else: result[key] = nextVal -proc asTable*(pattern: Captures, default: string = nil): Table[string, string] = +proc toTable*(pattern: Captures, default: string = nil): Table[string, string] = ## Gets all the named captures and returns them result = initTable[string, string]() - asTableImpl(nextVal == nil) + toTableImpl(nextVal == nil) -proc asTable*(pattern: CaptureBounds, default = None[Slice[int]]()): +proc toTable*(pattern: CaptureBounds, default = None[Slice[int]]()): Table[string, Option[Slice[int]]] = ## Gets all the named captures and returns them result = initTable[string, Option[Slice[int]]]() - asTableImpl(nextVal.isNone) + toTableImpl(nextVal.isNone) template itemsImpl(cond: bool): stmt {.immediate, dirty.} = for i in 0 .. foo)(?bar)?")) - check(ex1.captures.asTable == {"foo" : "foo", "bar" : nil}.toTable()) - check(ex1.captureBounds.asTable == {"foo" : Some(0..3), "bar" : None[Slice[int]]()}.toTable()) - check(ex1.captures.asTable("") == {"foo" : "foo", "bar" : ""}.toTable()) + check(ex1.captures.toTable == {"foo" : "foo", "bar" : nil}.toTable()) + check(ex1.captureBounds.toTable == {"foo" : Some(0..3), "bar" : None[Slice[int]]()}.toTable()) + check(ex1.captures.toTable("") == {"foo" : "foo", "bar" : ""}.toTable()) let ex2 = "foobar".find(initRegex("(?foo)(?bar)?")) - check(ex2.captures.asTable == {"foo" : "foo", "bar" : "bar"}.toTable()) + check(ex2.captures.toTable == {"foo" : "foo", "bar" : "bar"}.toTable()) test "capture sequence": let ex1 = "foo".find(initRegex("(?foo)(?bar)?")) From 02a93b11aa94a09a74aabccc45ee85be404a396c Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sun, 18 Jan 2015 12:31:15 -0500 Subject: [PATCH 0071/1263] Add a test case with 0-length match Thanks Oleh Prypin --- test/match.nim | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/test/match.nim b/test/match.nim index 7fa00610a..c02cc8e42 100644 --- a/test/match.nim +++ b/test/match.nim @@ -4,10 +4,14 @@ suite "match": test "upper bound must be exclusive": check("abc".match(re"abc", endpos = 0) == nil) check("abc".match(re"abc", endpos = 3) != nil) - test "examples": + + test "match examples": check("abc".match(re"(\w)").captures[0] == "a") check("abc".match(re"(?\w)").captures["letter"] == "a") check("abc".match(re"(\w)\w").captures[-1] == "ab") check("abc".match(re"(\w)").captureBounds[0].get == 0..1) check("abc".match(re"").captureBounds[-1].get == 0..0) check("abc".match(re"abc").captureBounds[-1].get == 0..3) + + test "match test cases": + check("123".match(re"").matchBounds == 0..0) From 85a7be9cf062df0a8de3c469d770168055246e9e Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sun, 18 Jan 2015 12:36:57 -0500 Subject: [PATCH 0072/1263] Improve readme confusion --- README.asciidoc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.asciidoc b/README.asciidoc index 424a37a9f..46dfa1f5d 100644 --- a/README.asciidoc +++ b/README.asciidoc @@ -64,7 +64,7 @@ Perl and Javascript use. - If the pattern has a capture in it, it is added after the string split: `"12".split(re"(\d)") == @["", "1", "", "2", ""]`. - If `maxsplit != -1`, then the string will only be split `maxsplit` times. - `"123".split(re"", maxsplit = 1) == @["1", "23"]` + `"1.2.3".split(re"\.", maxsplit = 1) == @["1", "2.3"]` [[proc-replace]] ==== replace(string, Regex, sub): string From a80617fd4c01839824b22d1879c69c092886d835 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sun, 18 Jan 2015 12:41:43 -0500 Subject: [PATCH 0073/1263] Disable extended default --- src/nre.nim | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/nre.nim b/src/nre.nim index fbc143cd1..6cc9bfddf 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -261,7 +261,7 @@ proc getNameToNumberTable(pattern: Regex): Table[string, int] = result[name] = num -proc initRegex*(pattern: string, options = "Sx"): Regex = +proc initRegex*(pattern: string, options = "S"): Regex = new(result, destroyRegex) result.pattern = pattern @@ -286,7 +286,7 @@ proc initRegex*(pattern: string, options = "Sx"): Regex = result.captureNameToId = result.getNameToNumberTable() -proc re*(pattern: string, options = "Sx"): Regex = initRegex(pattern, options) +proc re*(pattern: string, options = "S"): Regex = initRegex(pattern, options) # }}} proc matchImpl(str: string, pattern: Regex, start, endpos: int, flags: int): RegexMatch = From ca299504d1dc3a23968c4ddf33fd64aa3f1a9422 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sun, 18 Jan 2015 12:49:22 -0500 Subject: [PATCH 0074/1263] Make study a negatable option instead --- README.asciidoc | 5 ++--- test/find.nim | 4 ++-- test/split.nim | 6 +++--- 3 files changed, 7 insertions(+), 8 deletions(-) diff --git a/README.asciidoc b/README.asciidoc index 46dfa1f5d..54afe8dcf 100644 --- a/README.asciidoc +++ b/README.asciidoc @@ -109,7 +109,7 @@ as a key. Represents the pattern that things are matched against, constructed with `initRegex(string)` or `re(string)`. Examples: `re"foo"`, `re(r"foo # comment", -"Sx")`. +"x")`. `pattern: string` :: the string that was used to create the pattern. `captureCount: int` :: the number of captures that the pattern has. @@ -127,8 +127,6 @@ Represents the pattern that things are matched against, constructed with subject string - `N` - turn off auto-capture, `(?foo)` is necessary to capture. - `s` - `.` matches newline - - `S` - study the pattern to hopefully improve performance. JIT is unspported at - the moment. - `U` - expressions are not greedy by default. `?` can be added to a qualifier to make it greedy. - `u` - same as `8` @@ -152,3 +150,4 @@ ____ - `` - `\R` matches CR, LF, or CRLF - `` - `\R` matches any unicode newline - `` - Javascript compatibility + - `` - turn off studying; study is enabled by deafault diff --git a/test/find.nim b/test/find.nim index 1fd91f0d2..06f4d22cc 100644 --- a/test/find.nim +++ b/test/find.nim @@ -4,12 +4,12 @@ include nre suite "find": test "find text": check("3213a".find(initRegex(r"[a-z]")).match == "a") - check("1 2 3 4 5 6 7 8 ".findAll(initRegex(r" ", "S")).map( + check("1 2 3 4 5 6 7 8 ".findAll(re" ").map( proc (a: RegexMatch): string = a.match ) == @[" ", " ", " ", " ", " ", " ", " ", " "]) test "find bounds": - check("1 2 3 4 5 ".findAll(initRegex(r" ", "S")).map( + check("1 2 3 4 5 ".findAll(re" ")).map( proc (a: RegexMatch): Slice[int] = a.matchBounds ) == @[1..2, 3..4, 5..6, 7..8, 9..10]) diff --git a/test/split.nim b/test/split.nim index 838f06261..2dbb835d2 100644 --- a/test/split.nim +++ b/test/split.nim @@ -4,9 +4,9 @@ include nre suite "string splitting": test "splitting strings": check("12345".split(initRegex("")) == @["1", "2", "3", "4", "5"]) - check("1 2 3 4 5 6 ".split(initRegex(" ", "S")) == @["1", "2", "3", "4", "5", "6", ""]) - check("1 2 ".split(initRegex(" ", "S")) == @["1", "", "2", "", ""]) - check("1 2".split(initRegex(" ", "S")) == @["1", "2"]) + check("1 2 3 4 5 6 ".split(re" ") == @["1", "2", "3", "4", "5", "6", ""]) + check("1 2 ".split(initRegex(" ")) == @["1", "", "2", "", ""]) + check("1 2".split(initRegex(" ")) == @["1", "2"]) check("foo".split(initRegex("foo")) == @["", ""]) test "captured patterns": From f141737b9f677fadfd24a7e84bed6d3f9102c780 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sun, 18 Jan 2015 13:04:56 -0500 Subject: [PATCH 0075/1263] Remove initRegex --- README.asciidoc | 2 +- src/nre.nim | 15 +++++++-------- test/captures.nim | 24 ++++++++++++------------ test/find.nim | 4 ++-- test/init.nim | 18 +++++++++--------- test/split.nim | 8 ++++---- 6 files changed, 35 insertions(+), 36 deletions(-) diff --git a/README.asciidoc b/README.asciidoc index 54afe8dcf..38adab639 100644 --- a/README.asciidoc +++ b/README.asciidoc @@ -108,7 +108,7 @@ as a key. === Pattern Represents the pattern that things are matched against, constructed with -`initRegex(string)` or `re(string)`. Examples: `re"foo"`, `re(r"foo # comment", +`re(string, string)`. Examples: `re"foo"`, `re(r"foo # comment", "x")`. `pattern: string` :: the string that was used to create the pattern. diff --git a/src/nre.nim b/src/nre.nim index 6cc9bfddf..539a91005 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -208,7 +208,7 @@ let Options: Table[string, int] = { }.toTable proc tokenizeOptions(opts: string): tuple[flags: int, study: bool] = - result = (0, false) + result = (0, true) var longOpt: string = nil for i, c in opts: @@ -219,17 +219,16 @@ proc tokenizeOptions(opts: string): tuple[flags: int, study: bool] = if longOpt != nil: if c == '>': - result.flags = result.flags or Options.fget(longOpt) + if longOpt == "no_study": + result.study = false + else: + result.flags = result.flags or Options.fget(longOpt) longOpt = nil else: longOpt.add(c.toLower) continue # }}} - if c == 'S': # handle study - result.study = true - continue - result.flags = result.flags or Options.fget($c) # }}} @@ -261,7 +260,7 @@ proc getNameToNumberTable(pattern: Regex): Table[string, int] = result[name] = num -proc initRegex*(pattern: string, options = "S"): Regex = +proc initRegex(pattern: string, options: string): Regex = new(result, destroyRegex) result.pattern = pattern @@ -286,7 +285,7 @@ proc initRegex*(pattern: string, options = "S"): Regex = result.captureNameToId = result.getNameToNumberTable() -proc re*(pattern: string, options = "S"): Regex = initRegex(pattern, options) +proc re*(pattern: string, options = ""): Regex = initRegex(pattern, options) # }}} proc matchImpl(str: string, pattern: Regex, start, endpos: int, flags: int): RegexMatch = diff --git a/test/captures.nim b/test/captures.nim index bccbc0993..31bf1c6a2 100644 --- a/test/captures.nim +++ b/test/captures.nim @@ -3,57 +3,57 @@ include nre suite "captures": test "map capture names to numbers": - check(getNameToNumberTable(initRegex("(?1(?2(?3))(?'v4'4))()")) == + check(getNameToNumberTable(re("(?1(?2(?3))(?'v4'4))()")) == { "v1" : 0, "v2" : 1, "v3" : 2, "v4" : 3 }.toTable()) test "capture bounds are correct": - let ex1 = initRegex("([0-9])") + let ex1 = re("([0-9])") check("1 23".find(ex1).matchBounds == 0 .. 1) check("1 23".find(ex1).captureBounds[0].get == 0 .. 1) check("1 23".find(ex1, 1).matchBounds == 2 .. 3) check("1 23".find(ex1, 3).matchBounds == 3 .. 4) - let ex2 = initRegex("()()()()()()()()()()([0-9])") + let ex2 = re("()()()()()()()()()()([0-9])") check("824".find(ex2).captureBounds[0].get == 0 .. 0) check("824".find(ex2).captureBounds[10].get == 0 .. 1) - let ex3 = initRegex("([0-9]+)") + let ex3 = re("([0-9]+)") check("824".find(ex3).captureBounds[0].get == 0 .. 3) test "named captures": - let ex1 = "foobar".find(initRegex("(?foo)(?bar)")) + let ex1 = "foobar".find(re("(?foo)(?bar)")) check(ex1.captures["foo"] == "foo") check(ex1.captures["bar"] == "bar") - let ex2 = "foo".find(initRegex("(?foo)(?bar)?")) + let ex2 = "foo".find(re("(?foo)(?bar)?")) check(ex2.captures["foo"] == "foo") check(ex2.captures["bar"] == nil) test "named capture bounds": - let ex1 = "foo".find(initRegex("(?foo)(?bar)?")) + let ex1 = "foo".find(re("(?foo)(?bar)?")) check(ex1.captureBounds["foo"] == Some(0..3)) check(ex1.captureBounds["bar"] == None[Slice[int]]()) test "capture count": - let ex1 = initRegex("(?foo)(?bar)?") + let ex1 = re("(?foo)(?bar)?") check(ex1.captureCount == 2) check(ex1.captureNameId == {"foo" : 0, "bar" : 1}.toTable()) test "named capture table": - let ex1 = "foo".find(initRegex("(?foo)(?bar)?")) + let ex1 = "foo".find(re("(?foo)(?bar)?")) check(ex1.captures.toTable == {"foo" : "foo", "bar" : nil}.toTable()) check(ex1.captureBounds.toTable == {"foo" : Some(0..3), "bar" : None[Slice[int]]()}.toTable()) check(ex1.captures.toTable("") == {"foo" : "foo", "bar" : ""}.toTable()) - let ex2 = "foobar".find(initRegex("(?foo)(?bar)?")) + let ex2 = "foobar".find(re("(?foo)(?bar)?")) check(ex2.captures.toTable == {"foo" : "foo", "bar" : "bar"}.toTable()) test "capture sequence": - let ex1 = "foo".find(initRegex("(?foo)(?bar)?")) + let ex1 = "foo".find(re("(?foo)(?bar)?")) check(ex1.captures.toSeq == @["foo", nil]) check(ex1.captureBounds.toSeq == @[Some(0..3), None[Slice[int]]()]) check(ex1.captures.toSeq("") == @["foo", ""]) - let ex2 = "foobar".find(initRegex("(?foo)(?bar)?")) + let ex2 = "foobar".find(re("(?foo)(?bar)?")) check(ex2.captures.toSeq == @["foo", "bar"]) diff --git a/test/find.nim b/test/find.nim index 06f4d22cc..ddbfcdfdb 100644 --- a/test/find.nim +++ b/test/find.nim @@ -3,13 +3,13 @@ include nre suite "find": test "find text": - check("3213a".find(initRegex(r"[a-z]")).match == "a") + check("3213a".find(re"[a-z]").match == "a") check("1 2 3 4 5 6 7 8 ".findAll(re" ").map( proc (a: RegexMatch): string = a.match ) == @[" ", " ", " ", " ", " ", " ", " ", " "]) test "find bounds": - check("1 2 3 4 5 ".findAll(re" ")).map( + check("1 2 3 4 5 ".findAll(re" ").map( proc (a: RegexMatch): Slice[int] = a.matchBounds ) == @[1..2, 3..4, 5..6, 7..8, 9..10]) diff --git a/test/init.nim b/test/init.nim index 9bf7c3c42..105e6a19e 100644 --- a/test/init.nim +++ b/test/init.nim @@ -1,24 +1,24 @@ import unittest -include nre +import nre suite "Test NRE initialization": test "correct intialization": - check(initRegex("[0-9]+") != nil) - check(initRegex("[0-9]+", "iS") != nil) + check(re("[0-9]+") != nil) + check(re("[0-9]+", "i") != nil) test "correct options": expect(SyntaxError): # ValueError would be bad - discard initRegex("[0-9]+", - "89AEfimNsUWXxY") + discard re("[0-9]+", + "89AEfimNsUWXxY") test "incorrect options": - expect(KeyError): discard initRegex("[0-9]+", "a") - expect(KeyError): discard initRegex("[0-9]+", "") + expect(KeyError): discard re("[0-9]+", "a") + expect(KeyError): discard re("[0-9]+", "") test "invalid regex": - expect(SyntaxError): discard initRegex("[0-9") + expect(SyntaxError): discard re("[0-9") try: - discard initRegex("[0-9") + discard re("[0-9") except SyntaxError: let ex = SyntaxError(getCurrentException()) check(ex.pos == 4) diff --git a/test/split.nim b/test/split.nim index 2dbb835d2..184b5f9e2 100644 --- a/test/split.nim +++ b/test/split.nim @@ -3,11 +3,11 @@ include nre suite "string splitting": test "splitting strings": - check("12345".split(initRegex("")) == @["1", "2", "3", "4", "5"]) + check("12345".split(re("")) == @["1", "2", "3", "4", "5"]) check("1 2 3 4 5 6 ".split(re" ") == @["1", "2", "3", "4", "5", "6", ""]) - check("1 2 ".split(initRegex(" ")) == @["1", "", "2", "", ""]) - check("1 2".split(initRegex(" ")) == @["1", "2"]) - check("foo".split(initRegex("foo")) == @["", ""]) + check("1 2 ".split(re(" ")) == @["1", "", "2", "", ""]) + check("1 2".split(re(" ")) == @["1", "2"]) + check("foo".split(re("foo")) == @["", ""]) test "captured patterns": check("12".split(re"(\d)") == @["", "1", "", "2", ""]) From 2598909ffdd04f8153aed0d827c9b572493601ba Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sun, 18 Jan 2015 13:10:19 -0500 Subject: [PATCH 0076/1263] Add `$` operator --- README.asciidoc | 1 + src/nre.nim | 3 +++ 2 files changed, 4 insertions(+) diff --git a/README.asciidoc b/README.asciidoc index 38adab639..1d0070ca9 100644 --- a/README.asciidoc +++ b/README.asciidoc @@ -104,6 +104,7 @@ is inclusive. `(captureBounds|captures).toTable` :: returns a table with each named capture as a key. `(captureBounds|capture).toSeq` :: returns all the captures by their number. +`$: string` :: same as `match` === Pattern diff --git a/src/nre.nim b/src/nre.nim index 539a91005..b4ce99c65 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -175,6 +175,9 @@ proc toSeq*(pattern: CaptureBounds, default = None[Slice[int]]()): seq[Option[Sl proc toSeq*(pattern: Captures, default: string = nil): seq[string] = accumulateResult(pattern.items(default)) + +proc `$`*(pattern: RegexMatch): string = + return pattern.captures[-1] # }}} # Creation & Destruction {{{ From 0b24ba0d26f4bd1abb11d3cbe10b06d5ee7bb433 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sun, 18 Jan 2015 13:10:50 -0500 Subject: [PATCH 0077/1263] Fix typo --- README.asciidoc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.asciidoc b/README.asciidoc index 1d0070ca9..87903b497 100644 --- a/README.asciidoc +++ b/README.asciidoc @@ -103,7 +103,7 @@ is inclusive. `matchBounds: Slice[int]` :: the bounds of the match, as in `captureBounds[]` `(captureBounds|captures).toTable` :: returns a table with each named capture as a key. -`(captureBounds|capture).toSeq` :: returns all the captures by their number. +`(captureBounds|captures).toSeq` :: returns all the captures by their number. `$: string` :: same as `match` === Pattern From 7bce00b4cdb31cd5a72230b937d781778954eb67 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sun, 18 Jan 2015 13:45:56 -0500 Subject: [PATCH 0078/1263] Add escapeRe --- README.asciidoc | 6 ++++++ src/nre.nim | 7 +++++++ test/escape.nim | 7 +++++++ test/testall.nim | 1 + 4 files changed, 21 insertions(+) create mode 100644 test/escape.nim diff --git a/README.asciidoc b/README.asciidoc index 87903b497..dd7b78dc7 100644 --- a/README.asciidoc +++ b/README.asciidoc @@ -78,6 +78,12 @@ If `sub` is a string, then each match is replaced with that string, where the captures are accessable as `$1`, `$2`, and so on. A literal `$` can be added by doubling up like so: `$$`. +[[proc-escapere]] +==== escapeRe(string): string + +Escapes the string so it doesn't match any special characters. Incompatible +with the Extra flag (`X`). + === RegexMatch Represents the result of an execution. On failure, it is `nil`. The available diff --git a/src/nre.nim b/src/nre.nim index b4ce99c65..d907cae62 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -291,6 +291,7 @@ proc initRegex(pattern: string, options: string): Regex = proc re*(pattern: string, options = ""): Regex = initRegex(pattern, options) # }}} +# Operations {{{ proc matchImpl(str: string, pattern: Regex, start, endpos: int, flags: int): RegexMatch = new(result) result.pattern = pattern @@ -442,3 +443,9 @@ proc replace*(str: string, pattern: Regex, proc replace*(str: string, pattern: Regex, sub: string): string = return str.replace(pattern, proc (match: RegexMatch): string = sub % match.captures.toSeq ) + +# }}} + +let SpecialCharMatcher = re"([\\+*?[^\]$(){}=!<>|:-])" +proc escapeRe*(str: string): string = + str.replace(SpecialCharMatcher, "\\$1") diff --git a/test/escape.nim b/test/escape.nim new file mode 100644 index 000000000..db5e8a001 --- /dev/null +++ b/test/escape.nim @@ -0,0 +1,7 @@ +import nre, unittest + +suite "escape strings": + test "escape strings": + check("123".escapeRe() == "123") + check("[]".escapeRe() == r"\[\]") + check("()".escapeRe() == r"\(\)") diff --git a/test/testall.nim b/test/testall.nim index 89b661a2a..7b11fbb91 100644 --- a/test/testall.nim +++ b/test/testall.nim @@ -5,3 +5,4 @@ import find import split import match import replace +import escape From 7db05feac67986d327ab475373b855a1074ce7ac Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sun, 18 Jan 2015 14:01:25 -0500 Subject: [PATCH 0079/1263] Add licence --- LICENCE | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 LICENCE diff --git a/LICENCE b/LICENCE new file mode 100644 index 000000000..561f818ac --- /dev/null +++ b/LICENCE @@ -0,0 +1,19 @@ +Copyright (c) 2015 Flaviu Tamas + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. From 260ab8b01bb4daa0488232cada81d3a5befa8e91 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sun, 18 Jan 2015 18:32:10 -0500 Subject: [PATCH 0080/1263] Include pcre sources with library Advantages are that it works better on non-linux --- src/private/pcre.nim | 35 +- src/private/pcre_src/config.h | 349 + src/private/pcre_src/pcre.h | 677 ++ src/private/pcre_src/pcre_byte_order.c | 319 + src/private/pcre_src/pcre_chartables.c | 198 + src/private/pcre_src/pcre_compile.c | 9515 ++++++++++++++++++ src/private/pcre_src/pcre_config.c | 190 + src/private/pcre_src/pcre_dfa_exec.c | 3673 +++++++ src/private/pcre_src/pcre_exec.c | 7160 ++++++++++++++ src/private/pcre_src/pcre_fullinfo.c | 245 + src/private/pcre_src/pcre_get.c | 662 ++ src/private/pcre_src/pcre_globals.c | 86 + src/private/pcre_src/pcre_internal.h | 2781 ++++++ src/private/pcre_src/pcre_jit_compile.c | 10704 +++++++++++++++++++++ src/private/pcre_src/pcre_maketables.c | 156 + src/private/pcre_src/pcre_newline.c | 210 + src/private/pcre_src/pcre_ord2utf8.c | 94 + src/private/pcre_src/pcre_refcount.c | 92 + src/private/pcre_src/pcre_string_utils.c | 211 + src/private/pcre_src/pcre_study.c | 1643 ++++ src/private/pcre_src/pcre_tables.c | 727 ++ src/private/pcre_src/pcre_ucd.c | 3630 +++++++ src/private/pcre_src/pcre_valid_utf8.c | 301 + src/private/pcre_src/pcre_version.c | 98 + src/private/pcre_src/pcre_xclass.c | 268 + src/private/pcre_src/ucp.h | 224 + 26 files changed, 44238 insertions(+), 10 deletions(-) create mode 100644 src/private/pcre_src/config.h create mode 100644 src/private/pcre_src/pcre.h create mode 100644 src/private/pcre_src/pcre_byte_order.c create mode 100644 src/private/pcre_src/pcre_chartables.c create mode 100644 src/private/pcre_src/pcre_compile.c create mode 100644 src/private/pcre_src/pcre_config.c create mode 100644 src/private/pcre_src/pcre_dfa_exec.c create mode 100644 src/private/pcre_src/pcre_exec.c create mode 100644 src/private/pcre_src/pcre_fullinfo.c create mode 100644 src/private/pcre_src/pcre_get.c create mode 100644 src/private/pcre_src/pcre_globals.c create mode 100644 src/private/pcre_src/pcre_internal.h create mode 100644 src/private/pcre_src/pcre_jit_compile.c create mode 100644 src/private/pcre_src/pcre_maketables.c create mode 100644 src/private/pcre_src/pcre_newline.c create mode 100644 src/private/pcre_src/pcre_ord2utf8.c create mode 100644 src/private/pcre_src/pcre_refcount.c create mode 100644 src/private/pcre_src/pcre_string_utils.c create mode 100644 src/private/pcre_src/pcre_study.c create mode 100644 src/private/pcre_src/pcre_tables.c create mode 100644 src/private/pcre_src/pcre_ucd.c create mode 100644 src/private/pcre_src/pcre_valid_utf8.c create mode 100644 src/private/pcre_src/pcre_version.c create mode 100644 src/private/pcre_src/pcre_xclass.c create mode 100644 src/private/pcre_src/ucp.h diff --git a/src/private/pcre.nim b/src/private/pcre.nim index 41afa72fb..008013592 100644 --- a/src/private/pcre.nim +++ b/src/private/pcre.nim @@ -1,13 +1,28 @@ -when not defined(pcreDll): - when hostOS == "windows": - const pcreDll = "pcre.dll" - elif hostOS == "macosx": - const pcreDll = "libpcre(.3|.1|).dylib" - else: - const pcreDll = "libpcre.so(.3|.1|)" - {.pragma: pcreImport, dynlib: pcreDll.} -else: - {.pragma: pcreImport, header: "".} +{. passC: "-DHAVE_CONFIG_H", passC: "-I private/pcre_src", + passL: "-I private/pcre_src" .} +{. compile: "private/pcre_src/pcre_byte_order.c" .} +{. compile: "private/pcre_src/pcre_compile.c" .} +{. compile: "private/pcre_src/pcre_config.c" .} +{. compile: "private/pcre_src/pcre_dfa_exec.c" .} +{. compile: "private/pcre_src/pcre_exec.c" .} +{. compile: "private/pcre_src/pcre_fullinfo.c" .} +{. compile: "private/pcre_src/pcre_get.c" .} +{. compile: "private/pcre_src/pcre_globals.c" .} +{. compile: "private/pcre_src/pcre_jit_compile.c" .} +{. compile: "private/pcre_src/pcre_maketables.c" .} +{. compile: "private/pcre_src/pcre_newline.c" .} +{. compile: "private/pcre_src/pcre_ord2utf8.c" .} +{. compile: "private/pcre_src/pcre_refcount.c" .} +{. compile: "private/pcre_src/pcre_string_utils.c" .} +{. compile: "private/pcre_src/pcre_study.c" .} +{. compile: "private/pcre_src/pcre_tables.c" .} +{. compile: "private/pcre_src/pcre_ucd.c" .} +{. compile: "private/pcre_src/pcre_valid_utf8.c" .} +{. compile: "private/pcre_src/pcre_version.c" .} +{. compile: "private/pcre_src/pcre_xclass.c" .} +{. compile: "private/pcre_src/pcre_chartables.c" .} + +{.pragma: pcreImport, header: "".} #************************************************ # Perl-Compatible Regular Expressions * diff --git a/src/private/pcre_src/config.h b/src/private/pcre_src/config.h new file mode 100644 index 000000000..aa1a530c4 --- /dev/null +++ b/src/private/pcre_src/config.h @@ -0,0 +1,349 @@ +/* config.h. Generated from config.h.in by configure. */ +/* config.h.in. Generated from configure.ac by autoheader. */ + + +/* PCRE is written in Standard C, but there are a few non-standard things it +can cope with, allowing it to run on SunOS4 and other "close to standard" +systems. + +In environments that support the GNU autotools, config.h.in is converted into +config.h by the "configure" script. In environments that use CMake, +config-cmake.in is converted into config.h. If you are going to build PCRE "by +hand" without using "configure" or CMake, you should copy the distributed +config.h.generic to config.h, and edit the macro definitions to be the way you +need them. You must then add -DHAVE_CONFIG_H to all of your compile commands, +so that config.h is included at the start of every source. + +Alternatively, you can avoid editing by using -D on the compiler command line +to set the macro values. In this case, you do not have to set -DHAVE_CONFIG_H, +but if you do, default values will be taken from config.h for non-boolean +macros that are not defined on the command line. + +Boolean macros such as HAVE_STDLIB_H and SUPPORT_PCRE8 should either be defined +(conventionally to 1) for TRUE, and not defined at all for FALSE. All such +macros are listed as a commented #undef in config.h.generic. Macros such as +MATCH_LIMIT, whose actual value is relevant, have defaults defined, but are +surrounded by #ifndef/#endif lines so that the value can be overridden by -D. + +PCRE uses memmove() if HAVE_MEMMOVE is defined; otherwise it uses bcopy() if +HAVE_BCOPY is defined. If your system has neither bcopy() nor memmove(), make +sure both macros are undefined; an emulation function will then be used. */ + +/* By default, the \R escape sequence matches any Unicode line ending + character or sequence of characters. If BSR_ANYCRLF is defined (to any + value), this is changed so that backslash-R matches only CR, LF, or CRLF. + The build-time default can be overridden by the user of PCRE at runtime. */ +/* #undef BSR_ANYCRLF */ + +/* If you are compiling for a system that uses EBCDIC instead of ASCII + character codes, define this macro to any value. You must also edit the + NEWLINE macro below to set a suitable EBCDIC newline, commonly 21 (0x15). + On systems that can use "configure" or CMake to set EBCDIC, NEWLINE is + automatically adjusted. When EBCDIC is set, PCRE assumes that all input + strings are in EBCDIC. If you do not define this macro, PCRE will assume + input strings are ASCII or UTF-8/16/32 Unicode. It is not possible to build + a version of PCRE that supports both EBCDIC and UTF-8/16/32. */ +/* #undef EBCDIC */ + +/* In an EBCDIC environment, define this macro to any value to arrange for the + NL character to be 0x25 instead of the default 0x15. NL plays the role that + LF does in an ASCII/Unicode environment. The value must also be set in the + NEWLINE macro below. On systems that can use "configure" or CMake to set + EBCDIC_NL25, the adjustment of NEWLINE is automatic. */ +/* #undef EBCDIC_NL25 */ + +/* Define to 1 if you have the `bcopy' function. */ +#define HAVE_BCOPY 1 + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_BITS_TYPE_TRAITS_H */ + +/* Define to 1 if you have the header file. */ +#define HAVE_BZLIB_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_DIRENT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_DLFCN_H 1 + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_EDITLINE_READLINE_H */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_EDIT_READLINE_READLINE_H */ + +/* Define to 1 if you have the header file. */ +#define HAVE_INTTYPES_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_LIMITS_H 1 + +/* Define to 1 if the system has the type `long long'. */ +/* #undef HAVE_LONG_LONG */ + +/* Define to 1 if you have the `memmove' function. */ +#define HAVE_MEMMOVE 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_MEMORY_H 1 + +/* Define if you have POSIX threads libraries and header files. */ +/* #undef HAVE_PTHREAD */ + +/* Have PTHREAD_PRIO_INHERIT. */ +/* #undef HAVE_PTHREAD_PRIO_INHERIT */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_READLINE_HISTORY_H */ + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_READLINE_READLINE_H */ + +/* Define to 1 if you have the header file. */ +#define HAVE_STDINT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDLIB_H 1 + +/* Define to 1 if you have the `strerror' function. */ +#define HAVE_STRERROR 1 + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_STRING */ + +/* Define to 1 if you have the header file. */ +#define HAVE_STRINGS_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STRING_H 1 + +/* Define to 1 if you have `strtoimax'. */ +/* #undef HAVE_STRTOIMAX */ + +/* Define to 1 if you have `strtoll'. */ +/* #undef HAVE_STRTOLL */ + +/* Define to 1 if you have `strtoq'. */ +/* #undef HAVE_STRTOQ */ + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_STAT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_TYPES_H 1 + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_TYPE_TRAITS_H */ + +/* Define to 1 if you have the header file. */ +#define HAVE_UNISTD_H 1 + +/* Define to 1 if the system has the type `unsigned long long'. */ +/* #undef HAVE_UNSIGNED_LONG_LONG */ + +/* Define to 1 if the compiler supports simple visibility declarations. */ +#define HAVE_VISIBILITY 1 + +/* Define to 1 if you have the header file. */ +/* #undef HAVE_WINDOWS_H */ + +/* Define to 1 if you have the header file. */ +#define HAVE_ZLIB_H 1 + +/* Define to 1 if you have `_strtoi64'. */ +/* #undef HAVE__STRTOI64 */ + +/* The value of LINK_SIZE determines the number of bytes used to store links + as offsets within the compiled regex. The default is 2, which allows for + compiled patterns up to 64K long. This covers the vast majority of cases. + However, PCRE can also be compiled to use 3 or 4 bytes instead. This allows + for longer patterns in extreme cases. */ +#define LINK_SIZE 2 + +/* Define to the sub-directory in which libtool stores uninstalled libraries. + */ +#define LT_OBJDIR ".libs/" + +/* The value of MATCH_LIMIT determines the default number of times the + internal match() function can be called during a single execution of + pcre_exec(). There is a runtime interface for setting a different limit. + The limit exists in order to catch runaway regular expressions that take + for ever to determine that they do not match. The default is set very large + so that it does not accidentally catch legitimate cases. */ +#define MATCH_LIMIT 10000000 + +/* The above limit applies to all calls of match(), whether or not they + increase the recursion depth. In some environments it is desirable to limit + the depth of recursive calls of match() more strictly, in order to restrict + the maximum amount of stack (or heap, if NO_RECURSE is defined) that is + used. The value of MATCH_LIMIT_RECURSION applies only to recursive calls of + match(). To have any useful effect, it must be less than the value of + MATCH_LIMIT. The default is to use the same value as MATCH_LIMIT. There is + a runtime method for setting a different limit. */ +#define MATCH_LIMIT_RECURSION MATCH_LIMIT + +/* This limit is parameterized just in case anybody ever wants to change it. + Care must be taken if it is increased, because it guards against integer + overflow caused by enormously large patterns. */ +#define MAX_NAME_COUNT 10000 + +/* This limit is parameterized just in case anybody ever wants to change it. + Care must be taken if it is increased, because it guards against integer + overflow caused by enormously large patterns. */ +#define MAX_NAME_SIZE 32 + +/* The value of NEWLINE determines the default newline character sequence. + PCRE client programs can override this by selecting other values at run + time. In ASCII environments, the value can be 10 (LF), 13 (CR), or 3338 + (CRLF); in EBCDIC environments the value can be 21 or 37 (LF), 13 (CR), or + 3349 or 3365 (CRLF) because there are two alternative codepoints (0x15 and + 0x25) that are used as the NL line terminator that is equivalent to ASCII + LF. In both ASCII and EBCDIC environments the value can also be -1 (ANY), + or -2 (ANYCRLF). */ +#define NEWLINE -2 + +/* PCRE uses recursive function calls to handle backtracking while matching. + This can sometimes be a problem on systems that have stacks of limited + size. Define NO_RECURSE to any value to get a version that doesn't use + recursion in the match() function; instead it creates its own stack by + steam using pcre_recurse_malloc() to obtain memory from the heap. For more + detail, see the comments and other stuff just above the match() function. + */ +/* #undef NO_RECURSE */ + +/* Name of package */ +#define PACKAGE "pcre" + +/* Define to the address where bug reports for this package should be sent. */ +#define PACKAGE_BUGREPORT "" + +/* Define to the full name of this package. */ +#define PACKAGE_NAME "PCRE" + +/* Define to the full name and version of this package. */ +#define PACKAGE_STRING "PCRE 8.36" + +/* Define to the one symbol short name of this package. */ +#define PACKAGE_TARNAME "pcre" + +/* Define to the home page for this package. */ +#define PACKAGE_URL "" + +/* Define to the version of this package. */ +#define PACKAGE_VERSION "8.36" + +/* The value of PARENS_NEST_LIMIT specifies the maximum depth of nested + parentheses (of any kind) in a pattern. This limits the amount of system + stack that is used while compiling a pattern. */ +#define PARENS_NEST_LIMIT 250 + +/* to make a symbol visible */ +#define PCRECPP_EXP_DECL extern __attribute__ ((visibility ("default"))) + +/* to make a symbol visible */ +#define PCRECPP_EXP_DEFN __attribute__ ((visibility ("default"))) + +/* The value of PCREGREP_BUFSIZE determines the size of buffer used by + pcregrep to hold parts of the file it is searching. This is also the + minimum value. The actual amount of memory used by pcregrep is three times + this number, because it allows for the buffering of "before" and "after" + lines. */ +#define PCREGREP_BUFSIZE 20480 + +/* to make a symbol visible */ +#define PCREPOSIX_EXP_DECL extern __attribute__ ((visibility ("default"))) + +/* to make a symbol visible */ +#define PCREPOSIX_EXP_DEFN extern __attribute__ ((visibility ("default"))) + +/* to make a symbol visible */ +#define PCRE_EXP_DATA_DEFN __attribute__ ((visibility ("default"))) + +/* to make a symbol visible */ +#define PCRE_EXP_DECL extern __attribute__ ((visibility ("default"))) + + +/* If you are compiling for a system other than a Unix-like system or + Win32, and it needs some magic to be inserted before the definition + of a function that is exported by the library, define this macro to + contain the relevant magic. If you do not define this macro, a suitable + __declspec value is used for Windows systems; in other environments + "extern" is used for a C compiler and "extern C" for a C++ compiler. + This macro apears at the start of every exported function that is part + of the external API. It does not appear on functions that are "external" + in the C sense, but which are internal to the library. */ +#define PCRE_EXP_DEFN __attribute__ ((visibility ("default"))) + +/* Define to any value if linking statically (TODO: make nice with Libtool) */ +/* #undef PCRE_STATIC */ + +/* When calling PCRE via the POSIX interface, additional working storage is + required for holding the pointers to capturing substrings because PCRE + requires three integers per substring, whereas the POSIX interface provides + only two. If the number of expected substrings is small, the wrapper + function uses space on the stack, because this is faster than using + malloc() for each call. The threshold above which the stack is no longer + used is defined by POSIX_MALLOC_THRESHOLD. */ +#define POSIX_MALLOC_THRESHOLD 10 + +/* Define to necessary symbol if this constant uses a non-standard name on + your system. */ +/* #undef PTHREAD_CREATE_JOINABLE */ + +/* Define to 1 if you have the ANSI C header files. */ +#define STDC_HEADERS 1 + +/* Define to any value to enable support for Just-In-Time compiling. */ +/* #undef SUPPORT_JIT */ + +/* Define to any value to allow pcregrep to be linked with libbz2, so that it + is able to handle .bz2 files. */ +/* #undef SUPPORT_LIBBZ2 */ + +/* Define to any value to allow pcretest to be linked with libedit. */ +/* #undef SUPPORT_LIBEDIT */ + +/* Define to any value to allow pcretest to be linked with libreadline. */ +/* #undef SUPPORT_LIBREADLINE */ + +/* Define to any value to allow pcregrep to be linked with libz, so that it is + able to handle .gz files. */ +/* #undef SUPPORT_LIBZ */ + +/* Define to any value to enable the 16 bit PCRE library. */ +/* #undef SUPPORT_PCRE16 */ + +/* Define to any value to enable the 32 bit PCRE library. */ +/* #undef SUPPORT_PCRE32 */ + +/* Define to any value to enable the 8 bit PCRE library. */ +#define SUPPORT_PCRE8 /**/ + +/* Define to any value to enable JIT support in pcregrep. */ +/* #undef SUPPORT_PCREGREP_JIT */ + +/* Define to any value to enable support for Unicode properties. */ +/* #undef SUPPORT_UCP */ + +/* Define to any value to enable support for the UTF-8/16/32 Unicode encoding. + This will work even in an EBCDIC environment, but it is incompatible with + the EBCDIC macro. That is, PCRE can support *either* EBCDIC code *or* + ASCII/UTF-8/16/32, but not both at once. */ +/* #undef SUPPORT_UTF */ + +/* Define to any value for valgrind support to find invalid memory reads. */ +/* #undef SUPPORT_VALGRIND */ + +/* Version number of package */ +#define VERSION "8.36" + +/* Define to empty if `const' does not conform to ANSI C. */ +/* #undef const */ + +/* Define to the type of a signed integer type of width exactly 64 bits if + such a type exists and the standard includes do not define it. */ +/* #undef int64_t */ + +/* Define to `unsigned int' if does not define. */ +/* #undef size_t */ diff --git a/src/private/pcre_src/pcre.h b/src/private/pcre_src/pcre.h new file mode 100644 index 000000000..9216d55b0 --- /dev/null +++ b/src/private/pcre_src/pcre.h @@ -0,0 +1,677 @@ +/************************************************* +* Perl-Compatible Regular Expressions * +*************************************************/ + +/* This is the public header file for the PCRE library, to be #included by +applications that call the PCRE functions. + + Copyright (c) 1997-2014 University of Cambridge + +----------------------------------------------------------------------------- +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * Neither the name of the University of Cambridge nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. +----------------------------------------------------------------------------- +*/ + +#ifndef _PCRE_H +#define _PCRE_H + +/* The current PCRE version information. */ + +#define PCRE_MAJOR 8 +#define PCRE_MINOR 36 +#define PCRE_PRERELEASE +#define PCRE_DATE 2014-09-26 + +/* When an application links to a PCRE DLL in Windows, the symbols that are +imported have to be identified as such. When building PCRE, the appropriate +export setting is defined in pcre_internal.h, which includes this file. So we +don't change existing definitions of PCRE_EXP_DECL and PCRECPP_EXP_DECL. */ + +#if defined(_WIN32) && !defined(PCRE_STATIC) +# ifndef PCRE_EXP_DECL +# define PCRE_EXP_DECL extern __declspec(dllimport) +# endif +# ifdef __cplusplus +# ifndef PCRECPP_EXP_DECL +# define PCRECPP_EXP_DECL extern __declspec(dllimport) +# endif +# ifndef PCRECPP_EXP_DEFN +# define PCRECPP_EXP_DEFN __declspec(dllimport) +# endif +# endif +#endif + +/* By default, we use the standard "extern" declarations. */ + +#ifndef PCRE_EXP_DECL +# ifdef __cplusplus +# define PCRE_EXP_DECL extern "C" +# else +# define PCRE_EXP_DECL extern +# endif +#endif + +#ifdef __cplusplus +# ifndef PCRECPP_EXP_DECL +# define PCRECPP_EXP_DECL extern +# endif +# ifndef PCRECPP_EXP_DEFN +# define PCRECPP_EXP_DEFN +# endif +#endif + +/* Have to include stdlib.h in order to ensure that size_t is defined; +it is needed here for malloc. */ + +#include + +/* Allow for C++ users */ + +#ifdef __cplusplus +extern "C" { +#endif + +/* Public options. Some are compile-time only, some are run-time only, and some +are both. Most of the compile-time options are saved with the compiled regex so +that they can be inspected during studying (and therefore JIT compiling). Note +that pcre_study() has its own set of options. Originally, all the options +defined here used distinct bits. However, almost all the bits in a 32-bit word +are now used, so in order to conserve them, option bits that were previously +only recognized at matching time (i.e. by pcre_exec() or pcre_dfa_exec()) may +also be used for compile-time options that affect only compiling and are not +relevant for studying or JIT compiling. + +Some options for pcre_compile() change its behaviour but do not affect the +behaviour of the execution functions. Other options are passed through to the +execution functions and affect their behaviour, with or without affecting the +behaviour of pcre_compile(). + +Options that can be passed to pcre_compile() are tagged Cx below, with these +variants: + +C1 Affects compile only +C2 Does not affect compile; affects exec, dfa_exec +C3 Affects compile, exec, dfa_exec +C4 Affects compile, exec, dfa_exec, study +C5 Affects compile, exec, study + +Options that can be set for pcre_exec() and/or pcre_dfa_exec() are flagged with +E and D, respectively. They take precedence over C3, C4, and C5 settings passed +from pcre_compile(). Those that are compatible with JIT execution are flagged +with J. */ + +#define PCRE_CASELESS 0x00000001 /* C1 */ +#define PCRE_MULTILINE 0x00000002 /* C1 */ +#define PCRE_DOTALL 0x00000004 /* C1 */ +#define PCRE_EXTENDED 0x00000008 /* C1 */ +#define PCRE_ANCHORED 0x00000010 /* C4 E D */ +#define PCRE_DOLLAR_ENDONLY 0x00000020 /* C2 */ +#define PCRE_EXTRA 0x00000040 /* C1 */ +#define PCRE_NOTBOL 0x00000080 /* E D J */ +#define PCRE_NOTEOL 0x00000100 /* E D J */ +#define PCRE_UNGREEDY 0x00000200 /* C1 */ +#define PCRE_NOTEMPTY 0x00000400 /* E D J */ +#define PCRE_UTF8 0x00000800 /* C4 ) */ +#define PCRE_UTF16 0x00000800 /* C4 ) Synonyms */ +#define PCRE_UTF32 0x00000800 /* C4 ) */ +#define PCRE_NO_AUTO_CAPTURE 0x00001000 /* C1 */ +#define PCRE_NO_UTF8_CHECK 0x00002000 /* C1 E D J ) */ +#define PCRE_NO_UTF16_CHECK 0x00002000 /* C1 E D J ) Synonyms */ +#define PCRE_NO_UTF32_CHECK 0x00002000 /* C1 E D J ) */ +#define PCRE_AUTO_CALLOUT 0x00004000 /* C1 */ +#define PCRE_PARTIAL_SOFT 0x00008000 /* E D J ) Synonyms */ +#define PCRE_PARTIAL 0x00008000 /* E D J ) */ + +/* This pair use the same bit. */ +#define PCRE_NEVER_UTF 0x00010000 /* C1 ) Overlaid */ +#define PCRE_DFA_SHORTEST 0x00010000 /* D ) Overlaid */ + +/* This pair use the same bit. */ +#define PCRE_NO_AUTO_POSSESS 0x00020000 /* C1 ) Overlaid */ +#define PCRE_DFA_RESTART 0x00020000 /* D ) Overlaid */ + +#define PCRE_FIRSTLINE 0x00040000 /* C3 */ +#define PCRE_DUPNAMES 0x00080000 /* C1 */ +#define PCRE_NEWLINE_CR 0x00100000 /* C3 E D */ +#define PCRE_NEWLINE_LF 0x00200000 /* C3 E D */ +#define PCRE_NEWLINE_CRLF 0x00300000 /* C3 E D */ +#define PCRE_NEWLINE_ANY 0x00400000 /* C3 E D */ +#define PCRE_NEWLINE_ANYCRLF 0x00500000 /* C3 E D */ +#define PCRE_BSR_ANYCRLF 0x00800000 /* C3 E D */ +#define PCRE_BSR_UNICODE 0x01000000 /* C3 E D */ +#define PCRE_JAVASCRIPT_COMPAT 0x02000000 /* C5 */ +#define PCRE_NO_START_OPTIMIZE 0x04000000 /* C2 E D ) Synonyms */ +#define PCRE_NO_START_OPTIMISE 0x04000000 /* C2 E D ) */ +#define PCRE_PARTIAL_HARD 0x08000000 /* E D J */ +#define PCRE_NOTEMPTY_ATSTART 0x10000000 /* E D J */ +#define PCRE_UCP 0x20000000 /* C3 */ + +/* Exec-time and get/set-time error codes */ + +#define PCRE_ERROR_NOMATCH (-1) +#define PCRE_ERROR_NULL (-2) +#define PCRE_ERROR_BADOPTION (-3) +#define PCRE_ERROR_BADMAGIC (-4) +#define PCRE_ERROR_UNKNOWN_OPCODE (-5) +#define PCRE_ERROR_UNKNOWN_NODE (-5) /* For backward compatibility */ +#define PCRE_ERROR_NOMEMORY (-6) +#define PCRE_ERROR_NOSUBSTRING (-7) +#define PCRE_ERROR_MATCHLIMIT (-8) +#define PCRE_ERROR_CALLOUT (-9) /* Never used by PCRE itself */ +#define PCRE_ERROR_BADUTF8 (-10) /* Same for 8/16/32 */ +#define PCRE_ERROR_BADUTF16 (-10) /* Same for 8/16/32 */ +#define PCRE_ERROR_BADUTF32 (-10) /* Same for 8/16/32 */ +#define PCRE_ERROR_BADUTF8_OFFSET (-11) /* Same for 8/16 */ +#define PCRE_ERROR_BADUTF16_OFFSET (-11) /* Same for 8/16 */ +#define PCRE_ERROR_PARTIAL (-12) +#define PCRE_ERROR_BADPARTIAL (-13) +#define PCRE_ERROR_INTERNAL (-14) +#define PCRE_ERROR_BADCOUNT (-15) +#define PCRE_ERROR_DFA_UITEM (-16) +#define PCRE_ERROR_DFA_UCOND (-17) +#define PCRE_ERROR_DFA_UMLIMIT (-18) +#define PCRE_ERROR_DFA_WSSIZE (-19) +#define PCRE_ERROR_DFA_RECURSE (-20) +#define PCRE_ERROR_RECURSIONLIMIT (-21) +#define PCRE_ERROR_NULLWSLIMIT (-22) /* No longer actually used */ +#define PCRE_ERROR_BADNEWLINE (-23) +#define PCRE_ERROR_BADOFFSET (-24) +#define PCRE_ERROR_SHORTUTF8 (-25) +#define PCRE_ERROR_SHORTUTF16 (-25) /* Same for 8/16 */ +#define PCRE_ERROR_RECURSELOOP (-26) +#define PCRE_ERROR_JIT_STACKLIMIT (-27) +#define PCRE_ERROR_BADMODE (-28) +#define PCRE_ERROR_BADENDIANNESS (-29) +#define PCRE_ERROR_DFA_BADRESTART (-30) +#define PCRE_ERROR_JIT_BADOPTION (-31) +#define PCRE_ERROR_BADLENGTH (-32) +#define PCRE_ERROR_UNSET (-33) + +/* Specific error codes for UTF-8 validity checks */ + +#define PCRE_UTF8_ERR0 0 +#define PCRE_UTF8_ERR1 1 +#define PCRE_UTF8_ERR2 2 +#define PCRE_UTF8_ERR3 3 +#define PCRE_UTF8_ERR4 4 +#define PCRE_UTF8_ERR5 5 +#define PCRE_UTF8_ERR6 6 +#define PCRE_UTF8_ERR7 7 +#define PCRE_UTF8_ERR8 8 +#define PCRE_UTF8_ERR9 9 +#define PCRE_UTF8_ERR10 10 +#define PCRE_UTF8_ERR11 11 +#define PCRE_UTF8_ERR12 12 +#define PCRE_UTF8_ERR13 13 +#define PCRE_UTF8_ERR14 14 +#define PCRE_UTF8_ERR15 15 +#define PCRE_UTF8_ERR16 16 +#define PCRE_UTF8_ERR17 17 +#define PCRE_UTF8_ERR18 18 +#define PCRE_UTF8_ERR19 19 +#define PCRE_UTF8_ERR20 20 +#define PCRE_UTF8_ERR21 21 +#define PCRE_UTF8_ERR22 22 /* Unused (was non-character) */ + +/* Specific error codes for UTF-16 validity checks */ + +#define PCRE_UTF16_ERR0 0 +#define PCRE_UTF16_ERR1 1 +#define PCRE_UTF16_ERR2 2 +#define PCRE_UTF16_ERR3 3 +#define PCRE_UTF16_ERR4 4 /* Unused (was non-character) */ + +/* Specific error codes for UTF-32 validity checks */ + +#define PCRE_UTF32_ERR0 0 +#define PCRE_UTF32_ERR1 1 +#define PCRE_UTF32_ERR2 2 /* Unused (was non-character) */ +#define PCRE_UTF32_ERR3 3 + +/* Request types for pcre_fullinfo() */ + +#define PCRE_INFO_OPTIONS 0 +#define PCRE_INFO_SIZE 1 +#define PCRE_INFO_CAPTURECOUNT 2 +#define PCRE_INFO_BACKREFMAX 3 +#define PCRE_INFO_FIRSTBYTE 4 +#define PCRE_INFO_FIRSTCHAR 4 /* For backwards compatibility */ +#define PCRE_INFO_FIRSTTABLE 5 +#define PCRE_INFO_LASTLITERAL 6 +#define PCRE_INFO_NAMEENTRYSIZE 7 +#define PCRE_INFO_NAMECOUNT 8 +#define PCRE_INFO_NAMETABLE 9 +#define PCRE_INFO_STUDYSIZE 10 +#define PCRE_INFO_DEFAULT_TABLES 11 +#define PCRE_INFO_OKPARTIAL 12 +#define PCRE_INFO_JCHANGED 13 +#define PCRE_INFO_HASCRORLF 14 +#define PCRE_INFO_MINLENGTH 15 +#define PCRE_INFO_JIT 16 +#define PCRE_INFO_JITSIZE 17 +#define PCRE_INFO_MAXLOOKBEHIND 18 +#define PCRE_INFO_FIRSTCHARACTER 19 +#define PCRE_INFO_FIRSTCHARACTERFLAGS 20 +#define PCRE_INFO_REQUIREDCHAR 21 +#define PCRE_INFO_REQUIREDCHARFLAGS 22 +#define PCRE_INFO_MATCHLIMIT 23 +#define PCRE_INFO_RECURSIONLIMIT 24 +#define PCRE_INFO_MATCH_EMPTY 25 + +/* Request types for pcre_config(). Do not re-arrange, in order to remain +compatible. */ + +#define PCRE_CONFIG_UTF8 0 +#define PCRE_CONFIG_NEWLINE 1 +#define PCRE_CONFIG_LINK_SIZE 2 +#define PCRE_CONFIG_POSIX_MALLOC_THRESHOLD 3 +#define PCRE_CONFIG_MATCH_LIMIT 4 +#define PCRE_CONFIG_STACKRECURSE 5 +#define PCRE_CONFIG_UNICODE_PROPERTIES 6 +#define PCRE_CONFIG_MATCH_LIMIT_RECURSION 7 +#define PCRE_CONFIG_BSR 8 +#define PCRE_CONFIG_JIT 9 +#define PCRE_CONFIG_UTF16 10 +#define PCRE_CONFIG_JITTARGET 11 +#define PCRE_CONFIG_UTF32 12 +#define PCRE_CONFIG_PARENS_LIMIT 13 + +/* Request types for pcre_study(). Do not re-arrange, in order to remain +compatible. */ + +#define PCRE_STUDY_JIT_COMPILE 0x0001 +#define PCRE_STUDY_JIT_PARTIAL_SOFT_COMPILE 0x0002 +#define PCRE_STUDY_JIT_PARTIAL_HARD_COMPILE 0x0004 +#define PCRE_STUDY_EXTRA_NEEDED 0x0008 + +/* Bit flags for the pcre[16|32]_extra structure. Do not re-arrange or redefine +these bits, just add new ones on the end, in order to remain compatible. */ + +#define PCRE_EXTRA_STUDY_DATA 0x0001 +#define PCRE_EXTRA_MATCH_LIMIT 0x0002 +#define PCRE_EXTRA_CALLOUT_DATA 0x0004 +#define PCRE_EXTRA_TABLES 0x0008 +#define PCRE_EXTRA_MATCH_LIMIT_RECURSION 0x0010 +#define PCRE_EXTRA_MARK 0x0020 +#define PCRE_EXTRA_EXECUTABLE_JIT 0x0040 + +/* Types */ + +struct real_pcre; /* declaration; the definition is private */ +typedef struct real_pcre pcre; + +struct real_pcre16; /* declaration; the definition is private */ +typedef struct real_pcre16 pcre16; + +struct real_pcre32; /* declaration; the definition is private */ +typedef struct real_pcre32 pcre32; + +struct real_pcre_jit_stack; /* declaration; the definition is private */ +typedef struct real_pcre_jit_stack pcre_jit_stack; + +struct real_pcre16_jit_stack; /* declaration; the definition is private */ +typedef struct real_pcre16_jit_stack pcre16_jit_stack; + +struct real_pcre32_jit_stack; /* declaration; the definition is private */ +typedef struct real_pcre32_jit_stack pcre32_jit_stack; + +/* If PCRE is compiled with 16 bit character support, PCRE_UCHAR16 must contain +a 16 bit wide signed data type. Otherwise it can be a dummy data type since +pcre16 functions are not implemented. There is a check for this in pcre_internal.h. */ +#ifndef PCRE_UCHAR16 +#define PCRE_UCHAR16 unsigned short +#endif + +#ifndef PCRE_SPTR16 +#define PCRE_SPTR16 const PCRE_UCHAR16 * +#endif + +/* If PCRE is compiled with 32 bit character support, PCRE_UCHAR32 must contain +a 32 bit wide signed data type. Otherwise it can be a dummy data type since +pcre32 functions are not implemented. There is a check for this in pcre_internal.h. */ +#ifndef PCRE_UCHAR32 +#define PCRE_UCHAR32 unsigned int +#endif + +#ifndef PCRE_SPTR32 +#define PCRE_SPTR32 const PCRE_UCHAR32 * +#endif + +/* When PCRE is compiled as a C++ library, the subject pointer type can be +replaced with a custom type. For conventional use, the public interface is a +const char *. */ + +#ifndef PCRE_SPTR +#define PCRE_SPTR const char * +#endif + +/* The structure for passing additional data to pcre_exec(). This is defined in +such as way as to be extensible. Always add new fields at the end, in order to +remain compatible. */ + +typedef struct pcre_extra { + unsigned long int flags; /* Bits for which fields are set */ + void *study_data; /* Opaque data from pcre_study() */ + unsigned long int match_limit; /* Maximum number of calls to match() */ + void *callout_data; /* Data passed back in callouts */ + const unsigned char *tables; /* Pointer to character tables */ + unsigned long int match_limit_recursion; /* Max recursive calls to match() */ + unsigned char **mark; /* For passing back a mark pointer */ + void *executable_jit; /* Contains a pointer to a compiled jit code */ +} pcre_extra; + +/* Same structure as above, but with 16 bit char pointers. */ + +typedef struct pcre16_extra { + unsigned long int flags; /* Bits for which fields are set */ + void *study_data; /* Opaque data from pcre_study() */ + unsigned long int match_limit; /* Maximum number of calls to match() */ + void *callout_data; /* Data passed back in callouts */ + const unsigned char *tables; /* Pointer to character tables */ + unsigned long int match_limit_recursion; /* Max recursive calls to match() */ + PCRE_UCHAR16 **mark; /* For passing back a mark pointer */ + void *executable_jit; /* Contains a pointer to a compiled jit code */ +} pcre16_extra; + +/* Same structure as above, but with 32 bit char pointers. */ + +typedef struct pcre32_extra { + unsigned long int flags; /* Bits for which fields are set */ + void *study_data; /* Opaque data from pcre_study() */ + unsigned long int match_limit; /* Maximum number of calls to match() */ + void *callout_data; /* Data passed back in callouts */ + const unsigned char *tables; /* Pointer to character tables */ + unsigned long int match_limit_recursion; /* Max recursive calls to match() */ + PCRE_UCHAR32 **mark; /* For passing back a mark pointer */ + void *executable_jit; /* Contains a pointer to a compiled jit code */ +} pcre32_extra; + +/* The structure for passing out data via the pcre_callout_function. We use a +structure so that new fields can be added on the end in future versions, +without changing the API of the function, thereby allowing old clients to work +without modification. */ + +typedef struct pcre_callout_block { + int version; /* Identifies version of block */ + /* ------------------------ Version 0 ------------------------------- */ + int callout_number; /* Number compiled into pattern */ + int *offset_vector; /* The offset vector */ + PCRE_SPTR subject; /* The subject being matched */ + int subject_length; /* The length of the subject */ + int start_match; /* Offset to start of this match attempt */ + int current_position; /* Where we currently are in the subject */ + int capture_top; /* Max current capture */ + int capture_last; /* Most recently closed capture */ + void *callout_data; /* Data passed in with the call */ + /* ------------------- Added for Version 1 -------------------------- */ + int pattern_position; /* Offset to next item in the pattern */ + int next_item_length; /* Length of next item in the pattern */ + /* ------------------- Added for Version 2 -------------------------- */ + const unsigned char *mark; /* Pointer to current mark or NULL */ + /* ------------------------------------------------------------------ */ +} pcre_callout_block; + +/* Same structure as above, but with 16 bit char pointers. */ + +typedef struct pcre16_callout_block { + int version; /* Identifies version of block */ + /* ------------------------ Version 0 ------------------------------- */ + int callout_number; /* Number compiled into pattern */ + int *offset_vector; /* The offset vector */ + PCRE_SPTR16 subject; /* The subject being matched */ + int subject_length; /* The length of the subject */ + int start_match; /* Offset to start of this match attempt */ + int current_position; /* Where we currently are in the subject */ + int capture_top; /* Max current capture */ + int capture_last; /* Most recently closed capture */ + void *callout_data; /* Data passed in with the call */ + /* ------------------- Added for Version 1 -------------------------- */ + int pattern_position; /* Offset to next item in the pattern */ + int next_item_length; /* Length of next item in the pattern */ + /* ------------------- Added for Version 2 -------------------------- */ + const PCRE_UCHAR16 *mark; /* Pointer to current mark or NULL */ + /* ------------------------------------------------------------------ */ +} pcre16_callout_block; + +/* Same structure as above, but with 32 bit char pointers. */ + +typedef struct pcre32_callout_block { + int version; /* Identifies version of block */ + /* ------------------------ Version 0 ------------------------------- */ + int callout_number; /* Number compiled into pattern */ + int *offset_vector; /* The offset vector */ + PCRE_SPTR32 subject; /* The subject being matched */ + int subject_length; /* The length of the subject */ + int start_match; /* Offset to start of this match attempt */ + int current_position; /* Where we currently are in the subject */ + int capture_top; /* Max current capture */ + int capture_last; /* Most recently closed capture */ + void *callout_data; /* Data passed in with the call */ + /* ------------------- Added for Version 1 -------------------------- */ + int pattern_position; /* Offset to next item in the pattern */ + int next_item_length; /* Length of next item in the pattern */ + /* ------------------- Added for Version 2 -------------------------- */ + const PCRE_UCHAR32 *mark; /* Pointer to current mark or NULL */ + /* ------------------------------------------------------------------ */ +} pcre32_callout_block; + +/* Indirection for store get and free functions. These can be set to +alternative malloc/free functions if required. Special ones are used in the +non-recursive case for "frames". There is also an optional callout function +that is triggered by the (?) regex item. For Virtual Pascal, these definitions +have to take another form. */ + +#ifndef VPCOMPAT +PCRE_EXP_DECL void *(*pcre_malloc)(size_t); +PCRE_EXP_DECL void (*pcre_free)(void *); +PCRE_EXP_DECL void *(*pcre_stack_malloc)(size_t); +PCRE_EXP_DECL void (*pcre_stack_free)(void *); +PCRE_EXP_DECL int (*pcre_callout)(pcre_callout_block *); +PCRE_EXP_DECL int (*pcre_stack_guard)(void); + +PCRE_EXP_DECL void *(*pcre16_malloc)(size_t); +PCRE_EXP_DECL void (*pcre16_free)(void *); +PCRE_EXP_DECL void *(*pcre16_stack_malloc)(size_t); +PCRE_EXP_DECL void (*pcre16_stack_free)(void *); +PCRE_EXP_DECL int (*pcre16_callout)(pcre16_callout_block *); +PCRE_EXP_DECL int (*pcre16_stack_guard)(void); + +PCRE_EXP_DECL void *(*pcre32_malloc)(size_t); +PCRE_EXP_DECL void (*pcre32_free)(void *); +PCRE_EXP_DECL void *(*pcre32_stack_malloc)(size_t); +PCRE_EXP_DECL void (*pcre32_stack_free)(void *); +PCRE_EXP_DECL int (*pcre32_callout)(pcre32_callout_block *); +PCRE_EXP_DECL int (*pcre32_stack_guard)(void); +#else /* VPCOMPAT */ +PCRE_EXP_DECL void *pcre_malloc(size_t); +PCRE_EXP_DECL void pcre_free(void *); +PCRE_EXP_DECL void *pcre_stack_malloc(size_t); +PCRE_EXP_DECL void pcre_stack_free(void *); +PCRE_EXP_DECL int pcre_callout(pcre_callout_block *); +PCRE_EXP_DECL int pcre_stack_guard(void); + +PCRE_EXP_DECL void *pcre16_malloc(size_t); +PCRE_EXP_DECL void pcre16_free(void *); +PCRE_EXP_DECL void *pcre16_stack_malloc(size_t); +PCRE_EXP_DECL void pcre16_stack_free(void *); +PCRE_EXP_DECL int pcre16_callout(pcre16_callout_block *); +PCRE_EXP_DECL int pcre16_stack_guard(void); + +PCRE_EXP_DECL void *pcre32_malloc(size_t); +PCRE_EXP_DECL void pcre32_free(void *); +PCRE_EXP_DECL void *pcre32_stack_malloc(size_t); +PCRE_EXP_DECL void pcre32_stack_free(void *); +PCRE_EXP_DECL int pcre32_callout(pcre32_callout_block *); +PCRE_EXP_DECL int pcre32_stack_guard(void); +#endif /* VPCOMPAT */ + +/* User defined callback which provides a stack just before the match starts. */ + +typedef pcre_jit_stack *(*pcre_jit_callback)(void *); +typedef pcre16_jit_stack *(*pcre16_jit_callback)(void *); +typedef pcre32_jit_stack *(*pcre32_jit_callback)(void *); + +/* Exported PCRE functions */ + +PCRE_EXP_DECL pcre *pcre_compile(const char *, int, const char **, int *, + const unsigned char *); +PCRE_EXP_DECL pcre16 *pcre16_compile(PCRE_SPTR16, int, const char **, int *, + const unsigned char *); +PCRE_EXP_DECL pcre32 *pcre32_compile(PCRE_SPTR32, int, const char **, int *, + const unsigned char *); +PCRE_EXP_DECL pcre *pcre_compile2(const char *, int, int *, const char **, + int *, const unsigned char *); +PCRE_EXP_DECL pcre16 *pcre16_compile2(PCRE_SPTR16, int, int *, const char **, + int *, const unsigned char *); +PCRE_EXP_DECL pcre32 *pcre32_compile2(PCRE_SPTR32, int, int *, const char **, + int *, const unsigned char *); +PCRE_EXP_DECL int pcre_config(int, void *); +PCRE_EXP_DECL int pcre16_config(int, void *); +PCRE_EXP_DECL int pcre32_config(int, void *); +PCRE_EXP_DECL int pcre_copy_named_substring(const pcre *, const char *, + int *, int, const char *, char *, int); +PCRE_EXP_DECL int pcre16_copy_named_substring(const pcre16 *, PCRE_SPTR16, + int *, int, PCRE_SPTR16, PCRE_UCHAR16 *, int); +PCRE_EXP_DECL int pcre32_copy_named_substring(const pcre32 *, PCRE_SPTR32, + int *, int, PCRE_SPTR32, PCRE_UCHAR32 *, int); +PCRE_EXP_DECL int pcre_copy_substring(const char *, int *, int, int, + char *, int); +PCRE_EXP_DECL int pcre16_copy_substring(PCRE_SPTR16, int *, int, int, + PCRE_UCHAR16 *, int); +PCRE_EXP_DECL int pcre32_copy_substring(PCRE_SPTR32, int *, int, int, + PCRE_UCHAR32 *, int); +PCRE_EXP_DECL int pcre_dfa_exec(const pcre *, const pcre_extra *, + const char *, int, int, int, int *, int , int *, int); +PCRE_EXP_DECL int pcre16_dfa_exec(const pcre16 *, const pcre16_extra *, + PCRE_SPTR16, int, int, int, int *, int , int *, int); +PCRE_EXP_DECL int pcre32_dfa_exec(const pcre32 *, const pcre32_extra *, + PCRE_SPTR32, int, int, int, int *, int , int *, int); +PCRE_EXP_DECL int pcre_exec(const pcre *, const pcre_extra *, PCRE_SPTR, + int, int, int, int *, int); +PCRE_EXP_DECL int pcre16_exec(const pcre16 *, const pcre16_extra *, + PCRE_SPTR16, int, int, int, int *, int); +PCRE_EXP_DECL int pcre32_exec(const pcre32 *, const pcre32_extra *, + PCRE_SPTR32, int, int, int, int *, int); +PCRE_EXP_DECL int pcre_jit_exec(const pcre *, const pcre_extra *, + PCRE_SPTR, int, int, int, int *, int, + pcre_jit_stack *); +PCRE_EXP_DECL int pcre16_jit_exec(const pcre16 *, const pcre16_extra *, + PCRE_SPTR16, int, int, int, int *, int, + pcre16_jit_stack *); +PCRE_EXP_DECL int pcre32_jit_exec(const pcre32 *, const pcre32_extra *, + PCRE_SPTR32, int, int, int, int *, int, + pcre32_jit_stack *); +PCRE_EXP_DECL void pcre_free_substring(const char *); +PCRE_EXP_DECL void pcre16_free_substring(PCRE_SPTR16); +PCRE_EXP_DECL void pcre32_free_substring(PCRE_SPTR32); +PCRE_EXP_DECL void pcre_free_substring_list(const char **); +PCRE_EXP_DECL void pcre16_free_substring_list(PCRE_SPTR16 *); +PCRE_EXP_DECL void pcre32_free_substring_list(PCRE_SPTR32 *); +PCRE_EXP_DECL int pcre_fullinfo(const pcre *, const pcre_extra *, int, + void *); +PCRE_EXP_DECL int pcre16_fullinfo(const pcre16 *, const pcre16_extra *, int, + void *); +PCRE_EXP_DECL int pcre32_fullinfo(const pcre32 *, const pcre32_extra *, int, + void *); +PCRE_EXP_DECL int pcre_get_named_substring(const pcre *, const char *, + int *, int, const char *, const char **); +PCRE_EXP_DECL int pcre16_get_named_substring(const pcre16 *, PCRE_SPTR16, + int *, int, PCRE_SPTR16, PCRE_SPTR16 *); +PCRE_EXP_DECL int pcre32_get_named_substring(const pcre32 *, PCRE_SPTR32, + int *, int, PCRE_SPTR32, PCRE_SPTR32 *); +PCRE_EXP_DECL int pcre_get_stringnumber(const pcre *, const char *); +PCRE_EXP_DECL int pcre16_get_stringnumber(const pcre16 *, PCRE_SPTR16); +PCRE_EXP_DECL int pcre32_get_stringnumber(const pcre32 *, PCRE_SPTR32); +PCRE_EXP_DECL int pcre_get_stringtable_entries(const pcre *, const char *, + char **, char **); +PCRE_EXP_DECL int pcre16_get_stringtable_entries(const pcre16 *, PCRE_SPTR16, + PCRE_UCHAR16 **, PCRE_UCHAR16 **); +PCRE_EXP_DECL int pcre32_get_stringtable_entries(const pcre32 *, PCRE_SPTR32, + PCRE_UCHAR32 **, PCRE_UCHAR32 **); +PCRE_EXP_DECL int pcre_get_substring(const char *, int *, int, int, + const char **); +PCRE_EXP_DECL int pcre16_get_substring(PCRE_SPTR16, int *, int, int, + PCRE_SPTR16 *); +PCRE_EXP_DECL int pcre32_get_substring(PCRE_SPTR32, int *, int, int, + PCRE_SPTR32 *); +PCRE_EXP_DECL int pcre_get_substring_list(const char *, int *, int, + const char ***); +PCRE_EXP_DECL int pcre16_get_substring_list(PCRE_SPTR16, int *, int, + PCRE_SPTR16 **); +PCRE_EXP_DECL int pcre32_get_substring_list(PCRE_SPTR32, int *, int, + PCRE_SPTR32 **); +PCRE_EXP_DECL const unsigned char *pcre_maketables(void); +PCRE_EXP_DECL const unsigned char *pcre16_maketables(void); +PCRE_EXP_DECL const unsigned char *pcre32_maketables(void); +PCRE_EXP_DECL int pcre_refcount(pcre *, int); +PCRE_EXP_DECL int pcre16_refcount(pcre16 *, int); +PCRE_EXP_DECL int pcre32_refcount(pcre32 *, int); +PCRE_EXP_DECL pcre_extra *pcre_study(const pcre *, int, const char **); +PCRE_EXP_DECL pcre16_extra *pcre16_study(const pcre16 *, int, const char **); +PCRE_EXP_DECL pcre32_extra *pcre32_study(const pcre32 *, int, const char **); +PCRE_EXP_DECL void pcre_free_study(pcre_extra *); +PCRE_EXP_DECL void pcre16_free_study(pcre16_extra *); +PCRE_EXP_DECL void pcre32_free_study(pcre32_extra *); +PCRE_EXP_DECL const char *pcre_version(void); +PCRE_EXP_DECL const char *pcre16_version(void); +PCRE_EXP_DECL const char *pcre32_version(void); + +/* Utility functions for byte order swaps. */ +PCRE_EXP_DECL int pcre_pattern_to_host_byte_order(pcre *, pcre_extra *, + const unsigned char *); +PCRE_EXP_DECL int pcre16_pattern_to_host_byte_order(pcre16 *, pcre16_extra *, + const unsigned char *); +PCRE_EXP_DECL int pcre32_pattern_to_host_byte_order(pcre32 *, pcre32_extra *, + const unsigned char *); +PCRE_EXP_DECL int pcre16_utf16_to_host_byte_order(PCRE_UCHAR16 *, + PCRE_SPTR16, int, int *, int); +PCRE_EXP_DECL int pcre32_utf32_to_host_byte_order(PCRE_UCHAR32 *, + PCRE_SPTR32, int, int *, int); + +/* JIT compiler related functions. */ + +PCRE_EXP_DECL pcre_jit_stack *pcre_jit_stack_alloc(int, int); +PCRE_EXP_DECL pcre16_jit_stack *pcre16_jit_stack_alloc(int, int); +PCRE_EXP_DECL pcre32_jit_stack *pcre32_jit_stack_alloc(int, int); +PCRE_EXP_DECL void pcre_jit_stack_free(pcre_jit_stack *); +PCRE_EXP_DECL void pcre16_jit_stack_free(pcre16_jit_stack *); +PCRE_EXP_DECL void pcre32_jit_stack_free(pcre32_jit_stack *); +PCRE_EXP_DECL void pcre_assign_jit_stack(pcre_extra *, + pcre_jit_callback, void *); +PCRE_EXP_DECL void pcre16_assign_jit_stack(pcre16_extra *, + pcre16_jit_callback, void *); +PCRE_EXP_DECL void pcre32_assign_jit_stack(pcre32_extra *, + pcre32_jit_callback, void *); +PCRE_EXP_DECL void pcre_jit_free_unused_memory(void); +PCRE_EXP_DECL void pcre16_jit_free_unused_memory(void); +PCRE_EXP_DECL void pcre32_jit_free_unused_memory(void); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif /* End of pcre.h */ diff --git a/src/private/pcre_src/pcre_byte_order.c b/src/private/pcre_src/pcre_byte_order.c new file mode 100644 index 000000000..cf5f12b04 --- /dev/null +++ b/src/private/pcre_src/pcre_byte_order.c @@ -0,0 +1,319 @@ +/************************************************* +* Perl-Compatible Regular Expressions * +*************************************************/ + +/* PCRE is a library of functions to support regular expressions whose syntax +and semantics are as close as possible to those of the Perl 5 language. + + Written by Philip Hazel + Copyright (c) 1997-2014 University of Cambridge + +----------------------------------------------------------------------------- +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * Neither the name of the University of Cambridge nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. +----------------------------------------------------------------------------- +*/ + + +/* This module contains an internal function that tests a compiled pattern to +see if it was compiled with the opposite endianness. If so, it uses an +auxiliary local function to flip the appropriate bytes. */ + + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "pcre_internal.h" + + +/************************************************* +* Swap byte functions * +*************************************************/ + +/* The following functions swap the bytes of a pcre_uint16 +and pcre_uint32 value. + +Arguments: + value any number + +Returns: the byte swapped value +*/ + +static pcre_uint32 +swap_uint32(pcre_uint32 value) +{ +return ((value & 0x000000ff) << 24) | + ((value & 0x0000ff00) << 8) | + ((value & 0x00ff0000) >> 8) | + (value >> 24); +} + +static pcre_uint16 +swap_uint16(pcre_uint16 value) +{ +return (value >> 8) | (value << 8); +} + + +/************************************************* +* Test for a byte-flipped compiled regex * +*************************************************/ + +/* This function swaps the bytes of a compiled pattern usually +loaded form the disk. It also sets the tables pointer, which +is likely an invalid pointer after reload. + +Arguments: + argument_re points to the compiled expression + extra_data points to extra data or is NULL + tables points to the character tables or NULL + +Returns: 0 if the swap is successful, negative on error +*/ + +#if defined COMPILE_PCRE8 +PCRE_EXP_DECL int pcre_pattern_to_host_byte_order(pcre *argument_re, + pcre_extra *extra_data, const unsigned char *tables) +#elif defined COMPILE_PCRE16 +PCRE_EXP_DECL int pcre16_pattern_to_host_byte_order(pcre16 *argument_re, + pcre16_extra *extra_data, const unsigned char *tables) +#elif defined COMPILE_PCRE32 +PCRE_EXP_DECL int pcre32_pattern_to_host_byte_order(pcre32 *argument_re, + pcre32_extra *extra_data, const unsigned char *tables) +#endif +{ +REAL_PCRE *re = (REAL_PCRE *)argument_re; +pcre_study_data *study; +#ifndef COMPILE_PCRE8 +pcre_uchar *ptr; +int length; +#if defined SUPPORT_UTF && defined COMPILE_PCRE16 +BOOL utf; +BOOL utf16_char; +#endif /* SUPPORT_UTF && COMPILE_PCRE16 */ +#endif /* !COMPILE_PCRE8 */ + +if (re == NULL) return PCRE_ERROR_NULL; +if (re->magic_number == MAGIC_NUMBER) + { + if ((re->flags & PCRE_MODE) == 0) return PCRE_ERROR_BADMODE; + re->tables = tables; + return 0; + } + +if (re->magic_number != REVERSED_MAGIC_NUMBER) return PCRE_ERROR_BADMAGIC; +if ((swap_uint32(re->flags) & PCRE_MODE) == 0) return PCRE_ERROR_BADMODE; + +re->magic_number = MAGIC_NUMBER; +re->size = swap_uint32(re->size); +re->options = swap_uint32(re->options); +re->flags = swap_uint32(re->flags); +re->limit_match = swap_uint32(re->limit_match); +re->limit_recursion = swap_uint32(re->limit_recursion); + +#if defined COMPILE_PCRE8 || defined COMPILE_PCRE16 +re->first_char = swap_uint16(re->first_char); +re->req_char = swap_uint16(re->req_char); +#elif defined COMPILE_PCRE32 +re->first_char = swap_uint32(re->first_char); +re->req_char = swap_uint32(re->req_char); +#endif + +re->max_lookbehind = swap_uint16(re->max_lookbehind); +re->top_bracket = swap_uint16(re->top_bracket); +re->top_backref = swap_uint16(re->top_backref); +re->name_table_offset = swap_uint16(re->name_table_offset); +re->name_entry_size = swap_uint16(re->name_entry_size); +re->name_count = swap_uint16(re->name_count); +re->ref_count = swap_uint16(re->ref_count); +re->tables = tables; + +if (extra_data != NULL && (extra_data->flags & PCRE_EXTRA_STUDY_DATA) != 0) + { + study = (pcre_study_data *)extra_data->study_data; + study->size = swap_uint32(study->size); + study->flags = swap_uint32(study->flags); + study->minlength = swap_uint32(study->minlength); + } + +#ifndef COMPILE_PCRE8 +ptr = (pcre_uchar *)re + re->name_table_offset; +length = re->name_count * re->name_entry_size; +#if defined SUPPORT_UTF && defined COMPILE_PCRE16 +utf = (re->options & PCRE_UTF16) != 0; +utf16_char = FALSE; +#endif /* SUPPORT_UTF && COMPILE_PCRE16 */ + +while(TRUE) + { + /* Swap previous characters. */ + while (length-- > 0) + { +#if defined COMPILE_PCRE16 + *ptr = swap_uint16(*ptr); +#elif defined COMPILE_PCRE32 + *ptr = swap_uint32(*ptr); +#endif + ptr++; + } +#if defined SUPPORT_UTF && defined COMPILE_PCRE16 + if (utf16_char) + { + if (HAS_EXTRALEN(ptr[-1])) + { + /* We know that there is only one extra character in UTF-16. */ + *ptr = swap_uint16(*ptr); + ptr++; + } + } + utf16_char = FALSE; +#endif /* SUPPORT_UTF */ + + /* Get next opcode. */ + length = 0; +#if defined COMPILE_PCRE16 + *ptr = swap_uint16(*ptr); +#elif defined COMPILE_PCRE32 + *ptr = swap_uint32(*ptr); +#endif + switch (*ptr) + { + case OP_END: + return 0; + +#if defined SUPPORT_UTF && defined COMPILE_PCRE16 + case OP_CHAR: + case OP_CHARI: + case OP_NOT: + case OP_NOTI: + case OP_STAR: + case OP_MINSTAR: + case OP_PLUS: + case OP_MINPLUS: + case OP_QUERY: + case OP_MINQUERY: + case OP_UPTO: + case OP_MINUPTO: + case OP_EXACT: + case OP_POSSTAR: + case OP_POSPLUS: + case OP_POSQUERY: + case OP_POSUPTO: + case OP_STARI: + case OP_MINSTARI: + case OP_PLUSI: + case OP_MINPLUSI: + case OP_QUERYI: + case OP_MINQUERYI: + case OP_UPTOI: + case OP_MINUPTOI: + case OP_EXACTI: + case OP_POSSTARI: + case OP_POSPLUSI: + case OP_POSQUERYI: + case OP_POSUPTOI: + case OP_NOTSTAR: + case OP_NOTMINSTAR: + case OP_NOTPLUS: + case OP_NOTMINPLUS: + case OP_NOTQUERY: + case OP_NOTMINQUERY: + case OP_NOTUPTO: + case OP_NOTMINUPTO: + case OP_NOTEXACT: + case OP_NOTPOSSTAR: + case OP_NOTPOSPLUS: + case OP_NOTPOSQUERY: + case OP_NOTPOSUPTO: + case OP_NOTSTARI: + case OP_NOTMINSTARI: + case OP_NOTPLUSI: + case OP_NOTMINPLUSI: + case OP_NOTQUERYI: + case OP_NOTMINQUERYI: + case OP_NOTUPTOI: + case OP_NOTMINUPTOI: + case OP_NOTEXACTI: + case OP_NOTPOSSTARI: + case OP_NOTPOSPLUSI: + case OP_NOTPOSQUERYI: + case OP_NOTPOSUPTOI: + if (utf) utf16_char = TRUE; +#endif + /* Fall through. */ + + default: + length = PRIV(OP_lengths)[*ptr] - 1; + break; + + case OP_CLASS: + case OP_NCLASS: + /* Skip the character bit map. */ + ptr += 32/sizeof(pcre_uchar); + length = 0; + break; + + case OP_XCLASS: + /* Reverse the size of the XCLASS instance. */ + ptr++; +#if defined COMPILE_PCRE16 + *ptr = swap_uint16(*ptr); +#elif defined COMPILE_PCRE32 + *ptr = swap_uint32(*ptr); +#endif +#ifndef COMPILE_PCRE32 + if (LINK_SIZE > 1) + { + /* LINK_SIZE can be 1 or 2 in 16 bit mode. */ + ptr++; + *ptr = swap_uint16(*ptr); + } +#endif + ptr++; + length = (GET(ptr, -LINK_SIZE)) - (1 + LINK_SIZE + 1); +#if defined COMPILE_PCRE16 + *ptr = swap_uint16(*ptr); +#elif defined COMPILE_PCRE32 + *ptr = swap_uint32(*ptr); +#endif + if ((*ptr & XCL_MAP) != 0) + { + /* Skip the character bit map. */ + ptr += 32/sizeof(pcre_uchar); + length -= 32/sizeof(pcre_uchar); + } + break; + } + ptr++; + } +/* Control should never reach here in 16/32 bit mode. */ +#else /* In 8-bit mode, the pattern does not need to be processed. */ +return 0; +#endif /* !COMPILE_PCRE8 */ +} + +/* End of pcre_byte_order.c */ diff --git a/src/private/pcre_src/pcre_chartables.c b/src/private/pcre_src/pcre_chartables.c new file mode 100644 index 000000000..1e20ec29d --- /dev/null +++ b/src/private/pcre_src/pcre_chartables.c @@ -0,0 +1,198 @@ +/************************************************* +* Perl-Compatible Regular Expressions * +*************************************************/ + +/* This file contains character tables that are used when no external tables +are passed to PCRE by the application that calls it. The tables are used only +for characters whose code values are less than 256. + +This is a default version of the tables that assumes ASCII encoding. A program +called dftables (which is distributed with PCRE) can be used to build +alternative versions of this file. This is necessary if you are running in an +EBCDIC environment, or if you want to default to a different encoding, for +example ISO-8859-1. When dftables is run, it creates these tables in the +current locale. If PCRE is configured with --enable-rebuild-chartables, this +happens automatically. + +The following #includes are present because without them gcc 4.x may remove the +array definition from the final binary if PCRE is built into a static library +and dead code stripping is activated. This leads to link errors. Pulling in the +header ensures that the array gets flagged as "someone outside this compilation +unit might reference this" and so it will always be supplied to the linker. */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "pcre_internal.h" + +const pcre_uint8 PRIV(default_tables)[] = { + +/* This table is a lower casing table. */ + + 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, + +/* This table is a case flipping table. */ + + 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, 65, 66, 67, 68, 69, 70, 71, + 72, 73, 74, 75, 76, 77, 78, 79, + 80, 81, 82, 83, 84, 85, 86, 87, + 88, 89, 90,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, + +/* This table contains bit maps for various character classes. Each map is 32 +bytes long and the bits run from the least significant end of each byte. The +classes that have their own maps are: space, xdigit, digit, upper, lower, word, +graph, print, punct, and cntrl. Other classes are built from combinations. */ + + 0x00,0x3e,0x00,0x00,0x01,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + + 0x00,0x00,0x00,0x00,0x00,0x00,0xff,0x03, + 0x7e,0x00,0x00,0x00,0x7e,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + + 0x00,0x00,0x00,0x00,0x00,0x00,0xff,0x03, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0xfe,0xff,0xff,0x07,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0xfe,0xff,0xff,0x07, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + + 0x00,0x00,0x00,0x00,0x00,0x00,0xff,0x03, + 0xfe,0xff,0xff,0x87,0xfe,0xff,0xff,0x07, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + + 0x00,0x00,0x00,0x00,0xfe,0xff,0xff,0xff, + 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x7f, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + + 0x00,0x00,0x00,0x00,0xff,0xff,0xff,0xff, + 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x7f, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + + 0x00,0x00,0x00,0x00,0xfe,0xff,0x00,0xfc, + 0x01,0x00,0x00,0xf8,0x01,0x00,0x00,0x78, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + + 0xff,0xff,0xff,0xff,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + +/* This table identifies various classes of character by individual bits: + 0x01 white space character + 0x02 letter + 0x04 decimal digit + 0x08 hexadecimal digit + 0x10 alphanumeric or '_' + 0x80 regular expression metacharacter or binary zero +*/ + + 0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 0- 7 */ + 0x00,0x01,0x01,0x01,0x01,0x01,0x00,0x00, /* 8- 15 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 16- 23 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 24- 31 */ + 0x01,0x00,0x00,0x00,0x80,0x00,0x00,0x00, /* - ' */ + 0x80,0x80,0x80,0x80,0x00,0x00,0x80,0x00, /* ( - / */ + 0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c, /* 0 - 7 */ + 0x1c,0x1c,0x00,0x00,0x00,0x00,0x00,0x80, /* 8 - ? */ + 0x00,0x1a,0x1a,0x1a,0x1a,0x1a,0x1a,0x12, /* @ - G */ + 0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /* H - O */ + 0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /* P - W */ + 0x12,0x12,0x12,0x80,0x80,0x00,0x80,0x10, /* X - _ */ + 0x00,0x1a,0x1a,0x1a,0x1a,0x1a,0x1a,0x12, /* ` - g */ + 0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /* h - o */ + 0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /* p - w */ + 0x12,0x12,0x12,0x80,0x80,0x00,0x00,0x00, /* x -127 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 128-135 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 136-143 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 144-151 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 152-159 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 160-167 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 168-175 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 176-183 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 184-191 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 192-199 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 200-207 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 208-215 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 216-223 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 224-231 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 232-239 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 240-247 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};/* 248-255 */ + +/* End of pcre_chartables.c */ diff --git a/src/private/pcre_src/pcre_compile.c b/src/private/pcre_src/pcre_compile.c new file mode 100644 index 000000000..efc0b21fd --- /dev/null +++ b/src/private/pcre_src/pcre_compile.c @@ -0,0 +1,9515 @@ +/************************************************* +* Perl-Compatible Regular Expressions * +*************************************************/ + +/* PCRE is a library of functions to support regular expressions whose syntax +and semantics are as close as possible to those of the Perl 5 language. + + Written by Philip Hazel + Copyright (c) 1997-2014 University of Cambridge + +----------------------------------------------------------------------------- +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * Neither the name of the University of Cambridge nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. +----------------------------------------------------------------------------- +*/ + + +/* This module contains the external function pcre_compile(), along with +supporting internal functions that are not used by other modules. */ + + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#define NLBLOCK cd /* Block containing newline information */ +#define PSSTART start_pattern /* Field containing pattern start */ +#define PSEND end_pattern /* Field containing pattern end */ + +#include "pcre_internal.h" + + +/* When PCRE_DEBUG is defined, we need the pcre(16|32)_printint() function, which +is also used by pcretest. PCRE_DEBUG is not defined when building a production +library. We do not need to select pcre16_printint.c specially, because the +COMPILE_PCREx macro will already be appropriately set. */ + +#ifdef PCRE_DEBUG +/* pcre_printint.c should not include any headers */ +#define PCRE_INCLUDED +#include "pcre_printint.c" +#undef PCRE_INCLUDED +#endif + + +/* Macro for setting individual bits in class bitmaps. */ + +#define SETBIT(a,b) a[(b)/8] |= (1 << ((b)&7)) + +/* Maximum length value to check against when making sure that the integer that +holds the compiled pattern length does not overflow. We make it a bit less than +INT_MAX to allow for adding in group terminating bytes, so that we don't have +to check them every time. */ + +#define OFLOW_MAX (INT_MAX - 20) + +/* Definitions to allow mutual recursion */ + +static int + add_list_to_class(pcre_uint8 *, pcre_uchar **, int, compile_data *, + const pcre_uint32 *, unsigned int); + +static BOOL + compile_regex(int, pcre_uchar **, const pcre_uchar **, int *, BOOL, BOOL, int, int, + pcre_uint32 *, pcre_int32 *, pcre_uint32 *, pcre_int32 *, branch_chain *, + compile_data *, int *); + + + +/************************************************* +* Code parameters and static tables * +*************************************************/ + +/* This value specifies the size of stack workspace that is used during the +first pre-compile phase that determines how much memory is required. The regex +is partly compiled into this space, but the compiled parts are discarded as +soon as they can be, so that hopefully there will never be an overrun. The code +does, however, check for an overrun. The largest amount I've seen used is 218, +so this number is very generous. + +The same workspace is used during the second, actual compile phase for +remembering forward references to groups so that they can be filled in at the +end. Each entry in this list occupies LINK_SIZE bytes, so even when LINK_SIZE +is 4 there is plenty of room for most patterns. However, the memory can get +filled up by repetitions of forward references, for example patterns like +/(?1){0,1999}(b)/, and one user did hit the limit. The code has been changed so +that the workspace is expanded using malloc() in this situation. The value +below is therefore a minimum, and we put a maximum on it for safety. The +minimum is now also defined in terms of LINK_SIZE so that the use of malloc() +kicks in at the same number of forward references in all cases. */ + +#define COMPILE_WORK_SIZE (2048*LINK_SIZE) +#define COMPILE_WORK_SIZE_MAX (100*COMPILE_WORK_SIZE) + +/* This value determines the size of the initial vector that is used for +remembering named groups during the pre-compile. It is allocated on the stack, +but if it is too small, it is expanded using malloc(), in a similar way to the +workspace. The value is the number of slots in the list. */ + +#define NAMED_GROUP_LIST_SIZE 20 + +/* The overrun tests check for a slightly smaller size so that they detect the +overrun before it actually does run off the end of the data block. */ + +#define WORK_SIZE_SAFETY_MARGIN (100) + +/* Private flags added to firstchar and reqchar. */ + +#define REQ_CASELESS (1 << 0) /* Indicates caselessness */ +#define REQ_VARY (1 << 1) /* Reqchar followed non-literal item */ +/* Negative values for the firstchar and reqchar flags */ +#define REQ_UNSET (-2) +#define REQ_NONE (-1) + +/* Repeated character flags. */ + +#define UTF_LENGTH 0x10000000l /* The char contains its length. */ + +/* Table for handling escaped characters in the range '0'-'z'. Positive returns +are simple data values; negative values are for special things like \d and so +on. Zero means further processing is needed (for things like \x), or the escape +is invalid. */ + +#ifndef EBCDIC + +/* This is the "normal" table for ASCII systems or for EBCDIC systems running +in UTF-8 mode. */ + +static const short int escapes[] = { + 0, 0, + 0, 0, + 0, 0, + 0, 0, + 0, 0, + CHAR_COLON, CHAR_SEMICOLON, + CHAR_LESS_THAN_SIGN, CHAR_EQUALS_SIGN, + CHAR_GREATER_THAN_SIGN, CHAR_QUESTION_MARK, + CHAR_COMMERCIAL_AT, -ESC_A, + -ESC_B, -ESC_C, + -ESC_D, -ESC_E, + 0, -ESC_G, + -ESC_H, 0, + 0, -ESC_K, + 0, 0, + -ESC_N, 0, + -ESC_P, -ESC_Q, + -ESC_R, -ESC_S, + 0, 0, + -ESC_V, -ESC_W, + -ESC_X, 0, + -ESC_Z, CHAR_LEFT_SQUARE_BRACKET, + CHAR_BACKSLASH, CHAR_RIGHT_SQUARE_BRACKET, + CHAR_CIRCUMFLEX_ACCENT, CHAR_UNDERSCORE, + CHAR_GRAVE_ACCENT, 7, + -ESC_b, 0, + -ESC_d, ESC_e, + ESC_f, 0, + -ESC_h, 0, + 0, -ESC_k, + 0, 0, + ESC_n, 0, + -ESC_p, 0, + ESC_r, -ESC_s, + ESC_tee, 0, + -ESC_v, -ESC_w, + 0, 0, + -ESC_z +}; + +#else + +/* This is the "abnormal" table for EBCDIC systems without UTF-8 support. */ + +static const short int escapes[] = { +/* 48 */ 0, 0, 0, '.', '<', '(', '+', '|', +/* 50 */ '&', 0, 0, 0, 0, 0, 0, 0, +/* 58 */ 0, 0, '!', '$', '*', ')', ';', '~', +/* 60 */ '-', '/', 0, 0, 0, 0, 0, 0, +/* 68 */ 0, 0, '|', ',', '%', '_', '>', '?', +/* 70 */ 0, 0, 0, 0, 0, 0, 0, 0, +/* 78 */ 0, '`', ':', '#', '@', '\'', '=', '"', +/* 80 */ 0, 7, -ESC_b, 0, -ESC_d, ESC_e, ESC_f, 0, +/* 88 */-ESC_h, 0, 0, '{', 0, 0, 0, 0, +/* 90 */ 0, 0, -ESC_k, 'l', 0, ESC_n, 0, -ESC_p, +/* 98 */ 0, ESC_r, 0, '}', 0, 0, 0, 0, +/* A0 */ 0, '~', -ESC_s, ESC_tee, 0,-ESC_v, -ESC_w, 0, +/* A8 */ 0,-ESC_z, 0, 0, 0, '[', 0, 0, +/* B0 */ 0, 0, 0, 0, 0, 0, 0, 0, +/* B8 */ 0, 0, 0, 0, 0, ']', '=', '-', +/* C0 */ '{',-ESC_A, -ESC_B, -ESC_C, -ESC_D,-ESC_E, 0, -ESC_G, +/* C8 */-ESC_H, 0, 0, 0, 0, 0, 0, 0, +/* D0 */ '}', 0, -ESC_K, 0, 0,-ESC_N, 0, -ESC_P, +/* D8 */-ESC_Q,-ESC_R, 0, 0, 0, 0, 0, 0, +/* E0 */ '\\', 0, -ESC_S, 0, 0,-ESC_V, -ESC_W, -ESC_X, +/* E8 */ 0,-ESC_Z, 0, 0, 0, 0, 0, 0, +/* F0 */ 0, 0, 0, 0, 0, 0, 0, 0, +/* F8 */ 0, 0, 0, 0, 0, 0, 0, 0 +}; +#endif + + +/* Table of special "verbs" like (*PRUNE). This is a short table, so it is +searched linearly. Put all the names into a single string, in order to reduce +the number of relocations when a shared library is dynamically linked. The +string is built from string macros so that it works in UTF-8 mode on EBCDIC +platforms. */ + +typedef struct verbitem { + int len; /* Length of verb name */ + int op; /* Op when no arg, or -1 if arg mandatory */ + int op_arg; /* Op when arg present, or -1 if not allowed */ +} verbitem; + +static const char verbnames[] = + "\0" /* Empty name is a shorthand for MARK */ + STRING_MARK0 + STRING_ACCEPT0 + STRING_COMMIT0 + STRING_F0 + STRING_FAIL0 + STRING_PRUNE0 + STRING_SKIP0 + STRING_THEN; + +static const verbitem verbs[] = { + { 0, -1, OP_MARK }, + { 4, -1, OP_MARK }, + { 6, OP_ACCEPT, -1 }, + { 6, OP_COMMIT, -1 }, + { 1, OP_FAIL, -1 }, + { 4, OP_FAIL, -1 }, + { 5, OP_PRUNE, OP_PRUNE_ARG }, + { 4, OP_SKIP, OP_SKIP_ARG }, + { 4, OP_THEN, OP_THEN_ARG } +}; + +static const int verbcount = sizeof(verbs)/sizeof(verbitem); + + +/* Substitutes for [[:<:]] and [[:>:]], which mean start and end of word in +another regex library. */ + +static const pcre_uchar sub_start_of_word[] = { + CHAR_BACKSLASH, CHAR_b, CHAR_LEFT_PARENTHESIS, CHAR_QUESTION_MARK, + CHAR_EQUALS_SIGN, CHAR_BACKSLASH, CHAR_w, CHAR_RIGHT_PARENTHESIS, '\0' }; + +static const pcre_uchar sub_end_of_word[] = { + CHAR_BACKSLASH, CHAR_b, CHAR_LEFT_PARENTHESIS, CHAR_QUESTION_MARK, + CHAR_LESS_THAN_SIGN, CHAR_EQUALS_SIGN, CHAR_BACKSLASH, CHAR_w, + CHAR_RIGHT_PARENTHESIS, '\0' }; + + +/* Tables of names of POSIX character classes and their lengths. The names are +now all in a single string, to reduce the number of relocations when a shared +library is dynamically loaded. The list of lengths is terminated by a zero +length entry. The first three must be alpha, lower, upper, as this is assumed +for handling case independence. The indices for graph, print, and punct are +needed, so identify them. */ + +static const char posix_names[] = + STRING_alpha0 STRING_lower0 STRING_upper0 STRING_alnum0 + STRING_ascii0 STRING_blank0 STRING_cntrl0 STRING_digit0 + STRING_graph0 STRING_print0 STRING_punct0 STRING_space0 + STRING_word0 STRING_xdigit; + +static const pcre_uint8 posix_name_lengths[] = { + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 4, 6, 0 }; + +#define PC_GRAPH 8 +#define PC_PRINT 9 +#define PC_PUNCT 10 + + +/* Table of class bit maps for each POSIX class. Each class is formed from a +base map, with an optional addition or removal of another map. Then, for some +classes, there is some additional tweaking: for [:blank:] the vertical space +characters are removed, and for [:alpha:] and [:alnum:] the underscore +character is removed. The triples in the table consist of the base map offset, +second map offset or -1 if no second map, and a non-negative value for map +addition or a negative value for map subtraction (if there are two maps). The +absolute value of the third field has these meanings: 0 => no tweaking, 1 => +remove vertical space characters, 2 => remove underscore. */ + +static const int posix_class_maps[] = { + cbit_word, cbit_digit, -2, /* alpha */ + cbit_lower, -1, 0, /* lower */ + cbit_upper, -1, 0, /* upper */ + cbit_word, -1, 2, /* alnum - word without underscore */ + cbit_print, cbit_cntrl, 0, /* ascii */ + cbit_space, -1, 1, /* blank - a GNU extension */ + cbit_cntrl, -1, 0, /* cntrl */ + cbit_digit, -1, 0, /* digit */ + cbit_graph, -1, 0, /* graph */ + cbit_print, -1, 0, /* print */ + cbit_punct, -1, 0, /* punct */ + cbit_space, -1, 0, /* space */ + cbit_word, -1, 0, /* word - a Perl extension */ + cbit_xdigit,-1, 0 /* xdigit */ +}; + +/* Table of substitutes for \d etc when PCRE_UCP is set. They are replaced by +Unicode property escapes. */ + +#ifdef SUPPORT_UCP +static const pcre_uchar string_PNd[] = { + CHAR_BACKSLASH, CHAR_P, CHAR_LEFT_CURLY_BRACKET, + CHAR_N, CHAR_d, CHAR_RIGHT_CURLY_BRACKET, '\0' }; +static const pcre_uchar string_pNd[] = { + CHAR_BACKSLASH, CHAR_p, CHAR_LEFT_CURLY_BRACKET, + CHAR_N, CHAR_d, CHAR_RIGHT_CURLY_BRACKET, '\0' }; +static const pcre_uchar string_PXsp[] = { + CHAR_BACKSLASH, CHAR_P, CHAR_LEFT_CURLY_BRACKET, + CHAR_X, CHAR_s, CHAR_p, CHAR_RIGHT_CURLY_BRACKET, '\0' }; +static const pcre_uchar string_pXsp[] = { + CHAR_BACKSLASH, CHAR_p, CHAR_LEFT_CURLY_BRACKET, + CHAR_X, CHAR_s, CHAR_p, CHAR_RIGHT_CURLY_BRACKET, '\0' }; +static const pcre_uchar string_PXwd[] = { + CHAR_BACKSLASH, CHAR_P, CHAR_LEFT_CURLY_BRACKET, + CHAR_X, CHAR_w, CHAR_d, CHAR_RIGHT_CURLY_BRACKET, '\0' }; +static const pcre_uchar string_pXwd[] = { + CHAR_BACKSLASH, CHAR_p, CHAR_LEFT_CURLY_BRACKET, + CHAR_X, CHAR_w, CHAR_d, CHAR_RIGHT_CURLY_BRACKET, '\0' }; + +static const pcre_uchar *substitutes[] = { + string_PNd, /* \D */ + string_pNd, /* \d */ + string_PXsp, /* \S */ /* Xsp is Perl space, but from 8.34, Perl */ + string_pXsp, /* \s */ /* space and POSIX space are the same. */ + string_PXwd, /* \W */ + string_pXwd /* \w */ +}; + +/* The POSIX class substitutes must be in the order of the POSIX class names, +defined above, and there are both positive and negative cases. NULL means no +general substitute of a Unicode property escape (\p or \P). However, for some +POSIX classes (e.g. graph, print, punct) a special property code is compiled +directly. */ + +static const pcre_uchar string_pL[] = { + CHAR_BACKSLASH, CHAR_p, CHAR_LEFT_CURLY_BRACKET, + CHAR_L, CHAR_RIGHT_CURLY_BRACKET, '\0' }; +static const pcre_uchar string_pLl[] = { + CHAR_BACKSLASH, CHAR_p, CHAR_LEFT_CURLY_BRACKET, + CHAR_L, CHAR_l, CHAR_RIGHT_CURLY_BRACKET, '\0' }; +static const pcre_uchar string_pLu[] = { + CHAR_BACKSLASH, CHAR_p, CHAR_LEFT_CURLY_BRACKET, + CHAR_L, CHAR_u, CHAR_RIGHT_CURLY_BRACKET, '\0' }; +static const pcre_uchar string_pXan[] = { + CHAR_BACKSLASH, CHAR_p, CHAR_LEFT_CURLY_BRACKET, + CHAR_X, CHAR_a, CHAR_n, CHAR_RIGHT_CURLY_BRACKET, '\0' }; +static const pcre_uchar string_h[] = { + CHAR_BACKSLASH, CHAR_h, '\0' }; +static const pcre_uchar string_pXps[] = { + CHAR_BACKSLASH, CHAR_p, CHAR_LEFT_CURLY_BRACKET, + CHAR_X, CHAR_p, CHAR_s, CHAR_RIGHT_CURLY_BRACKET, '\0' }; +static const pcre_uchar string_PL[] = { + CHAR_BACKSLASH, CHAR_P, CHAR_LEFT_CURLY_BRACKET, + CHAR_L, CHAR_RIGHT_CURLY_BRACKET, '\0' }; +static const pcre_uchar string_PLl[] = { + CHAR_BACKSLASH, CHAR_P, CHAR_LEFT_CURLY_BRACKET, + CHAR_L, CHAR_l, CHAR_RIGHT_CURLY_BRACKET, '\0' }; +static const pcre_uchar string_PLu[] = { + CHAR_BACKSLASH, CHAR_P, CHAR_LEFT_CURLY_BRACKET, + CHAR_L, CHAR_u, CHAR_RIGHT_CURLY_BRACKET, '\0' }; +static const pcre_uchar string_PXan[] = { + CHAR_BACKSLASH, CHAR_P, CHAR_LEFT_CURLY_BRACKET, + CHAR_X, CHAR_a, CHAR_n, CHAR_RIGHT_CURLY_BRACKET, '\0' }; +static const pcre_uchar string_H[] = { + CHAR_BACKSLASH, CHAR_H, '\0' }; +static const pcre_uchar string_PXps[] = { + CHAR_BACKSLASH, CHAR_P, CHAR_LEFT_CURLY_BRACKET, + CHAR_X, CHAR_p, CHAR_s, CHAR_RIGHT_CURLY_BRACKET, '\0' }; + +static const pcre_uchar *posix_substitutes[] = { + string_pL, /* alpha */ + string_pLl, /* lower */ + string_pLu, /* upper */ + string_pXan, /* alnum */ + NULL, /* ascii */ + string_h, /* blank */ + NULL, /* cntrl */ + string_pNd, /* digit */ + NULL, /* graph */ + NULL, /* print */ + NULL, /* punct */ + string_pXps, /* space */ /* Xps is POSIX space, but from 8.34 */ + string_pXwd, /* word */ /* Perl and POSIX space are the same */ + NULL, /* xdigit */ + /* Negated cases */ + string_PL, /* ^alpha */ + string_PLl, /* ^lower */ + string_PLu, /* ^upper */ + string_PXan, /* ^alnum */ + NULL, /* ^ascii */ + string_H, /* ^blank */ + NULL, /* ^cntrl */ + string_PNd, /* ^digit */ + NULL, /* ^graph */ + NULL, /* ^print */ + NULL, /* ^punct */ + string_PXps, /* ^space */ /* Xps is POSIX space, but from 8.34 */ + string_PXwd, /* ^word */ /* Perl and POSIX space are the same */ + NULL /* ^xdigit */ +}; +#define POSIX_SUBSIZE (sizeof(posix_substitutes) / sizeof(pcre_uchar *)) +#endif + +#define STRING(a) # a +#define XSTRING(s) STRING(s) + +/* The texts of compile-time error messages. These are "char *" because they +are passed to the outside world. Do not ever re-use any error number, because +they are documented. Always add a new error instead. Messages marked DEAD below +are no longer used. This used to be a table of strings, but in order to reduce +the number of relocations needed when a shared library is loaded dynamically, +it is now one long string. We cannot use a table of offsets, because the +lengths of inserts such as XSTRING(MAX_NAME_SIZE) are not known. Instead, we +simply count through to the one we want - this isn't a performance issue +because these strings are used only when there is a compilation error. + +Each substring ends with \0 to insert a null character. This includes the final +substring, so that the whole string ends with \0\0, which can be detected when +counting through. */ + +static const char error_texts[] = + "no error\0" + "\\ at end of pattern\0" + "\\c at end of pattern\0" + "unrecognized character follows \\\0" + "numbers out of order in {} quantifier\0" + /* 5 */ + "number too big in {} quantifier\0" + "missing terminating ] for character class\0" + "invalid escape sequence in character class\0" + "range out of order in character class\0" + "nothing to repeat\0" + /* 10 */ + "operand of unlimited repeat could match the empty string\0" /** DEAD **/ + "internal error: unexpected repeat\0" + "unrecognized character after (? or (?-\0" + "POSIX named classes are supported only within a class\0" + "missing )\0" + /* 15 */ + "reference to non-existent subpattern\0" + "erroffset passed as NULL\0" + "unknown option bit(s) set\0" + "missing ) after comment\0" + "parentheses nested too deeply\0" /** DEAD **/ + /* 20 */ + "regular expression is too large\0" + "failed to get memory\0" + "unmatched parentheses\0" + "internal error: code overflow\0" + "unrecognized character after (?<\0" + /* 25 */ + "lookbehind assertion is not fixed length\0" + "malformed number or name after (?(\0" + "conditional group contains more than two branches\0" + "assertion expected after (?(\0" + "(?R or (?[+-]digits must be followed by )\0" + /* 30 */ + "unknown POSIX class name\0" + "POSIX collating elements are not supported\0" + "this version of PCRE is compiled without UTF support\0" + "spare error\0" /** DEAD **/ + "character value in \\x{} or \\o{} is too large\0" + /* 35 */ + "invalid condition (?(0)\0" + "\\C not allowed in lookbehind assertion\0" + "PCRE does not support \\L, \\l, \\N{name}, \\U, or \\u\0" + "number after (?C is > 255\0" + "closing ) for (?C expected\0" + /* 40 */ + "recursive call could loop indefinitely\0" + "unrecognized character after (?P\0" + "syntax error in subpattern name (missing terminator)\0" + "two named subpatterns have the same name\0" + "invalid UTF-8 string\0" + /* 45 */ + "support for \\P, \\p, and \\X has not been compiled\0" + "malformed \\P or \\p sequence\0" + "unknown property name after \\P or \\p\0" + "subpattern name is too long (maximum " XSTRING(MAX_NAME_SIZE) " characters)\0" + "too many named subpatterns (maximum " XSTRING(MAX_NAME_COUNT) ")\0" + /* 50 */ + "repeated subpattern is too long\0" /** DEAD **/ + "octal value is greater than \\377 in 8-bit non-UTF-8 mode\0" + "internal error: overran compiling workspace\0" + "internal error: previously-checked referenced subpattern not found\0" + "DEFINE group contains more than one branch\0" + /* 55 */ + "repeating a DEFINE group is not allowed\0" /** DEAD **/ + "inconsistent NEWLINE options\0" + "\\g is not followed by a braced, angle-bracketed, or quoted name/number or by a plain number\0" + "a numbered reference must not be zero\0" + "an argument is not allowed for (*ACCEPT), (*FAIL), or (*COMMIT)\0" + /* 60 */ + "(*VERB) not recognized or malformed\0" + "number is too big\0" + "subpattern name expected\0" + "digit expected after (?+\0" + "] is an invalid data character in JavaScript compatibility mode\0" + /* 65 */ + "different names for subpatterns of the same number are not allowed\0" + "(*MARK) must have an argument\0" + "this version of PCRE is not compiled with Unicode property support\0" + "\\c must be followed by an ASCII character\0" + "\\k is not followed by a braced, angle-bracketed, or quoted name\0" + /* 70 */ + "internal error: unknown opcode in find_fixedlength()\0" + "\\N is not supported in a class\0" + "too many forward references\0" + "disallowed Unicode code point (>= 0xd800 && <= 0xdfff)\0" + "invalid UTF-16 string\0" + /* 75 */ + "name is too long in (*MARK), (*PRUNE), (*SKIP), or (*THEN)\0" + "character value in \\u.... sequence is too large\0" + "invalid UTF-32 string\0" + "setting UTF is disabled by the application\0" + "non-hex character in \\x{} (closing brace missing?)\0" + /* 80 */ + "non-octal character in \\o{} (closing brace missing?)\0" + "missing opening brace after \\o\0" + "parentheses are too deeply nested\0" + "invalid range in character class\0" + "group name must start with a non-digit\0" + /* 85 */ + "parentheses are too deeply nested (stack check)\0" + "digits missing in \\x{} or \\o{}\0" + ; + +/* Table to identify digits and hex digits. This is used when compiling +patterns. Note that the tables in chartables are dependent on the locale, and +may mark arbitrary characters as digits - but the PCRE compiling code expects +to handle only 0-9, a-z, and A-Z as digits when compiling. That is why we have +a private table here. It costs 256 bytes, but it is a lot faster than doing +character value tests (at least in some simple cases I timed), and in some +applications one wants PCRE to compile efficiently as well as match +efficiently. + +For convenience, we use the same bit definitions as in chartables: + + 0x04 decimal digit + 0x08 hexadecimal digit + +Then we can use ctype_digit and ctype_xdigit in the code. */ + +/* Using a simple comparison for decimal numbers rather than a memory read +is much faster, and the resulting code is simpler (the compiler turns it +into a subtraction and unsigned comparison). */ + +#define IS_DIGIT(x) ((x) >= CHAR_0 && (x) <= CHAR_9) + +#ifndef EBCDIC + +/* This is the "normal" case, for ASCII systems, and EBCDIC systems running in +UTF-8 mode. */ + +static const pcre_uint8 digitab[] = + { + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 0- 7 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 8- 15 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 16- 23 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 24- 31 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* - ' */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* ( - / */ + 0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c, /* 0 - 7 */ + 0x0c,0x0c,0x00,0x00,0x00,0x00,0x00,0x00, /* 8 - ? */ + 0x00,0x08,0x08,0x08,0x08,0x08,0x08,0x00, /* @ - G */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* H - O */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* P - W */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* X - _ */ + 0x00,0x08,0x08,0x08,0x08,0x08,0x08,0x00, /* ` - g */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* h - o */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* p - w */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* x -127 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 128-135 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 136-143 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 144-151 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 152-159 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 160-167 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 168-175 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 176-183 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 184-191 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 192-199 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 200-207 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 208-215 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 216-223 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 224-231 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 232-239 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 240-247 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};/* 248-255 */ + +#else + +/* This is the "abnormal" case, for EBCDIC systems not running in UTF-8 mode. */ + +static const pcre_uint8 digitab[] = + { + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 0- 7 0 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 8- 15 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 16- 23 10 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 24- 31 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 32- 39 20 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 40- 47 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 48- 55 30 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 56- 63 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* - 71 40 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 72- | */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* & - 87 50 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 88- 95 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* - -103 60 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 104- ? */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 112-119 70 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 120- " */ + 0x00,0x08,0x08,0x08,0x08,0x08,0x08,0x00, /* 128- g 80 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* h -143 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 144- p 90 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* q -159 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 160- x A0 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* y -175 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* ^ -183 B0 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 184-191 */ + 0x00,0x08,0x08,0x08,0x08,0x08,0x08,0x00, /* { - G C0 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* H -207 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* } - P D0 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* Q -223 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* \ - X E0 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* Y -239 */ + 0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c, /* 0 - 7 F0 */ + 0x0c,0x0c,0x00,0x00,0x00,0x00,0x00,0x00};/* 8 -255 */ + +static const pcre_uint8 ebcdic_chartab[] = { /* chartable partial dup */ + 0x80,0x00,0x00,0x00,0x00,0x01,0x00,0x00, /* 0- 7 */ + 0x00,0x00,0x00,0x00,0x01,0x01,0x00,0x00, /* 8- 15 */ + 0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00, /* 16- 23 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 24- 31 */ + 0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00, /* 32- 39 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 40- 47 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 48- 55 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 56- 63 */ + 0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* - 71 */ + 0x00,0x00,0x00,0x80,0x00,0x80,0x80,0x80, /* 72- | */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* & - 87 */ + 0x00,0x00,0x00,0x80,0x80,0x80,0x00,0x00, /* 88- 95 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* - -103 */ + 0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x80, /* 104- ? */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 112-119 */ + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 120- " */ + 0x00,0x1a,0x1a,0x1a,0x1a,0x1a,0x1a,0x12, /* 128- g */ + 0x12,0x12,0x00,0x00,0x00,0x00,0x00,0x00, /* h -143 */ + 0x00,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /* 144- p */ + 0x12,0x12,0x00,0x00,0x00,0x00,0x00,0x00, /* q -159 */ + 0x00,0x00,0x12,0x12,0x12,0x12,0x12,0x12, /* 160- x */ + 0x12,0x12,0x00,0x00,0x00,0x00,0x00,0x00, /* y -175 */ + 0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* ^ -183 */ + 0x00,0x00,0x80,0x00,0x00,0x00,0x00,0x00, /* 184-191 */ + 0x80,0x1a,0x1a,0x1a,0x1a,0x1a,0x1a,0x12, /* { - G */ + 0x12,0x12,0x00,0x00,0x00,0x00,0x00,0x00, /* H -207 */ + 0x00,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /* } - P */ + 0x12,0x12,0x00,0x00,0x00,0x00,0x00,0x00, /* Q -223 */ + 0x00,0x00,0x12,0x12,0x12,0x12,0x12,0x12, /* \ - X */ + 0x12,0x12,0x00,0x00,0x00,0x00,0x00,0x00, /* Y -239 */ + 0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c, /* 0 - 7 */ + 0x1c,0x1c,0x00,0x00,0x00,0x00,0x00,0x00};/* 8 -255 */ +#endif + + +/* This table is used to check whether auto-possessification is possible +between adjacent character-type opcodes. The left-hand (repeated) opcode is +used to select the row, and the right-hand opcode is use to select the column. +A value of 1 means that auto-possessification is OK. For example, the second +value in the first row means that \D+\d can be turned into \D++\d. + +The Unicode property types (\P and \p) have to be present to fill out the table +because of what their opcode values are, but the table values should always be +zero because property types are handled separately in the code. The last four +columns apply to items that cannot be repeated, so there is no need to have +rows for them. Note that OP_DIGIT etc. are generated only when PCRE_UCP is +*not* set. When it is set, \d etc. are converted into OP_(NOT_)PROP codes. */ + +#define APTROWS (LAST_AUTOTAB_LEFT_OP - FIRST_AUTOTAB_OP + 1) +#define APTCOLS (LAST_AUTOTAB_RIGHT_OP - FIRST_AUTOTAB_OP + 1) + +static const pcre_uint8 autoposstab[APTROWS][APTCOLS] = { +/* \D \d \S \s \W \w . .+ \C \P \p \R \H \h \V \v \X \Z \z $ $M */ + { 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 }, /* \D */ + { 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1 }, /* \d */ + { 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1 }, /* \S */ + { 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 }, /* \s */ + { 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 }, /* \W */ + { 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1 }, /* \w */ + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0 }, /* . */ + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 }, /* .+ */ + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 }, /* \C */ + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* \P */ + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* \p */ + { 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0 }, /* \R */ + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0 }, /* \H */ + { 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0 }, /* \h */ + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0 }, /* \V */ + { 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0 }, /* \v */ + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 } /* \X */ +}; + + +/* This table is used to check whether auto-possessification is possible +between adjacent Unicode property opcodes (OP_PROP and OP_NOTPROP). The +left-hand (repeated) opcode is used to select the row, and the right-hand +opcode is used to select the column. The values are as follows: + + 0 Always return FALSE (never auto-possessify) + 1 Character groups are distinct (possessify if both are OP_PROP) + 2 Check character categories in the same group (general or particular) + 3 TRUE if the two opcodes are not the same (PROP vs NOTPROP) + + 4 Check left general category vs right particular category + 5 Check right general category vs left particular category + + 6 Left alphanum vs right general category + 7 Left space vs right general category + 8 Left word vs right general category + + 9 Right alphanum vs left general category + 10 Right space vs left general category + 11 Right word vs left general category + + 12 Left alphanum vs right particular category + 13 Left space vs right particular category + 14 Left word vs right particular category + + 15 Right alphanum vs left particular category + 16 Right space vs left particular category + 17 Right word vs left particular category +*/ + +static const pcre_uint8 propposstab[PT_TABSIZE][PT_TABSIZE] = { +/* ANY LAMP GC PC SC ALNUM SPACE PXSPACE WORD CLIST UCNC */ + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* PT_ANY */ + { 0, 3, 0, 0, 0, 3, 1, 1, 0, 0, 0 }, /* PT_LAMP */ + { 0, 0, 2, 4, 0, 9, 10, 10, 11, 0, 0 }, /* PT_GC */ + { 0, 0, 5, 2, 0, 15, 16, 16, 17, 0, 0 }, /* PT_PC */ + { 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0 }, /* PT_SC */ + { 0, 3, 6, 12, 0, 3, 1, 1, 0, 0, 0 }, /* PT_ALNUM */ + { 0, 1, 7, 13, 0, 1, 3, 3, 1, 0, 0 }, /* PT_SPACE */ + { 0, 1, 7, 13, 0, 1, 3, 3, 1, 0, 0 }, /* PT_PXSPACE */ + { 0, 0, 8, 14, 0, 0, 1, 1, 3, 0, 0 }, /* PT_WORD */ + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* PT_CLIST */ + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3 } /* PT_UCNC */ +}; + +/* This table is used to check whether auto-possessification is possible +between adjacent Unicode property opcodes (OP_PROP and OP_NOTPROP) when one +specifies a general category and the other specifies a particular category. The +row is selected by the general category and the column by the particular +category. The value is 1 if the particular category is not part of the general +category. */ + +static const pcre_uint8 catposstab[7][30] = { +/* Cc Cf Cn Co Cs Ll Lm Lo Lt Lu Mc Me Mn Nd Nl No Pc Pd Pe Pf Pi Po Ps Sc Sk Sm So Zl Zp Zs */ + { 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, /* C */ + { 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, /* L */ + { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, /* M */ + { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, /* N */ + { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1 }, /* P */ + { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1 }, /* S */ + { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0 } /* Z */ +}; + +/* This table is used when checking ALNUM, (PX)SPACE, SPACE, and WORD against +a general or particular category. The properties in each row are those +that apply to the character set in question. Duplication means that a little +unnecessary work is done when checking, but this keeps things much simpler +because they can all use the same code. For more details see the comment where +this table is used. + +Note: SPACE and PXSPACE used to be different because Perl excluded VT from +"space", but from Perl 5.18 it's included, so both categories are treated the +same here. */ + +static const pcre_uint8 posspropstab[3][4] = { + { ucp_L, ucp_N, ucp_N, ucp_Nl }, /* ALNUM, 3rd and 4th values redundant */ + { ucp_Z, ucp_Z, ucp_C, ucp_Cc }, /* SPACE and PXSPACE, 2nd value redundant */ + { ucp_L, ucp_N, ucp_P, ucp_Po } /* WORD */ +}; + +/* This table is used when converting repeating opcodes into possessified +versions as a result of an explicit possessive quantifier such as ++. A zero +value means there is no possessified version - in those cases the item in +question must be wrapped in ONCE brackets. The table is truncated at OP_CALLOUT +because all relevant opcodes are less than that. */ + +static const pcre_uint8 opcode_possessify[] = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0 - 15 */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 16 - 31 */ + + 0, /* NOTI */ + OP_POSSTAR, 0, /* STAR, MINSTAR */ + OP_POSPLUS, 0, /* PLUS, MINPLUS */ + OP_POSQUERY, 0, /* QUERY, MINQUERY */ + OP_POSUPTO, 0, /* UPTO, MINUPTO */ + 0, /* EXACT */ + 0, 0, 0, 0, /* POS{STAR,PLUS,QUERY,UPTO} */ + + OP_POSSTARI, 0, /* STARI, MINSTARI */ + OP_POSPLUSI, 0, /* PLUSI, MINPLUSI */ + OP_POSQUERYI, 0, /* QUERYI, MINQUERYI */ + OP_POSUPTOI, 0, /* UPTOI, MINUPTOI */ + 0, /* EXACTI */ + 0, 0, 0, 0, /* POS{STARI,PLUSI,QUERYI,UPTOI} */ + + OP_NOTPOSSTAR, 0, /* NOTSTAR, NOTMINSTAR */ + OP_NOTPOSPLUS, 0, /* NOTPLUS, NOTMINPLUS */ + OP_NOTPOSQUERY, 0, /* NOTQUERY, NOTMINQUERY */ + OP_NOTPOSUPTO, 0, /* NOTUPTO, NOTMINUPTO */ + 0, /* NOTEXACT */ + 0, 0, 0, 0, /* NOTPOS{STAR,PLUS,QUERY,UPTO} */ + + OP_NOTPOSSTARI, 0, /* NOTSTARI, NOTMINSTARI */ + OP_NOTPOSPLUSI, 0, /* NOTPLUSI, NOTMINPLUSI */ + OP_NOTPOSQUERYI, 0, /* NOTQUERYI, NOTMINQUERYI */ + OP_NOTPOSUPTOI, 0, /* NOTUPTOI, NOTMINUPTOI */ + 0, /* NOTEXACTI */ + 0, 0, 0, 0, /* NOTPOS{STARI,PLUSI,QUERYI,UPTOI} */ + + OP_TYPEPOSSTAR, 0, /* TYPESTAR, TYPEMINSTAR */ + OP_TYPEPOSPLUS, 0, /* TYPEPLUS, TYPEMINPLUS */ + OP_TYPEPOSQUERY, 0, /* TYPEQUERY, TYPEMINQUERY */ + OP_TYPEPOSUPTO, 0, /* TYPEUPTO, TYPEMINUPTO */ + 0, /* TYPEEXACT */ + 0, 0, 0, 0, /* TYPEPOS{STAR,PLUS,QUERY,UPTO} */ + + OP_CRPOSSTAR, 0, /* CRSTAR, CRMINSTAR */ + OP_CRPOSPLUS, 0, /* CRPLUS, CRMINPLUS */ + OP_CRPOSQUERY, 0, /* CRQUERY, CRMINQUERY */ + OP_CRPOSRANGE, 0, /* CRRANGE, CRMINRANGE */ + 0, 0, 0, 0, /* CRPOS{STAR,PLUS,QUERY,RANGE} */ + + 0, 0, 0, /* CLASS, NCLASS, XCLASS */ + 0, 0, /* REF, REFI */ + 0, 0, /* DNREF, DNREFI */ + 0, 0 /* RECURSE, CALLOUT */ +}; + + + +/************************************************* +* Find an error text * +*************************************************/ + +/* The error texts are now all in one long string, to save on relocations. As +some of the text is of unknown length, we can't use a table of offsets. +Instead, just count through the strings. This is not a performance issue +because it happens only when there has been a compilation error. + +Argument: the error number +Returns: pointer to the error string +*/ + +static const char * +find_error_text(int n) +{ +const char *s = error_texts; +for (; n > 0; n--) + { + while (*s++ != CHAR_NULL) {}; + if (*s == CHAR_NULL) return "Error text not found (please report)"; + } +return s; +} + + + +/************************************************* +* Expand the workspace * +*************************************************/ + +/* This function is called during the second compiling phase, if the number of +forward references fills the existing workspace, which is originally a block on +the stack. A larger block is obtained from malloc() unless the ultimate limit +has been reached or the increase will be rather small. + +Argument: pointer to the compile data block +Returns: 0 if all went well, else an error number +*/ + +static int +expand_workspace(compile_data *cd) +{ +pcre_uchar *newspace; +int newsize = cd->workspace_size * 2; + +if (newsize > COMPILE_WORK_SIZE_MAX) newsize = COMPILE_WORK_SIZE_MAX; +if (cd->workspace_size >= COMPILE_WORK_SIZE_MAX || + newsize - cd->workspace_size < WORK_SIZE_SAFETY_MARGIN) + return ERR72; + +newspace = (PUBL(malloc))(IN_UCHARS(newsize)); +if (newspace == NULL) return ERR21; +memcpy(newspace, cd->start_workspace, cd->workspace_size * sizeof(pcre_uchar)); +cd->hwm = (pcre_uchar *)newspace + (cd->hwm - cd->start_workspace); +if (cd->workspace_size > COMPILE_WORK_SIZE) + (PUBL(free))((void *)cd->start_workspace); +cd->start_workspace = newspace; +cd->workspace_size = newsize; +return 0; +} + + + +/************************************************* +* Check for counted repeat * +*************************************************/ + +/* This function is called when a '{' is encountered in a place where it might +start a quantifier. It looks ahead to see if it really is a quantifier or not. +It is only a quantifier if it is one of the forms {ddd} {ddd,} or {ddd,ddd} +where the ddds are digits. + +Arguments: + p pointer to the first char after '{' + +Returns: TRUE or FALSE +*/ + +static BOOL +is_counted_repeat(const pcre_uchar *p) +{ +if (!IS_DIGIT(*p)) return FALSE; +p++; +while (IS_DIGIT(*p)) p++; +if (*p == CHAR_RIGHT_CURLY_BRACKET) return TRUE; + +if (*p++ != CHAR_COMMA) return FALSE; +if (*p == CHAR_RIGHT_CURLY_BRACKET) return TRUE; + +if (!IS_DIGIT(*p)) return FALSE; +p++; +while (IS_DIGIT(*p)) p++; + +return (*p == CHAR_RIGHT_CURLY_BRACKET); +} + + + +/************************************************* +* Handle escapes * +*************************************************/ + +/* This function is called when a \ has been encountered. It either returns a +positive value for a simple escape such as \n, or 0 for a data character which +will be placed in chptr. A backreference to group n is returned as negative n. +When UTF-8 is enabled, a positive value greater than 255 may be returned in +chptr. On entry, ptr is pointing at the \. On exit, it is on the final +character of the escape sequence. + +Arguments: + ptrptr points to the pattern position pointer + chptr points to a returned data character + errorcodeptr points to the errorcode variable + bracount number of previous extracting brackets + options the options bits + isclass TRUE if inside a character class + +Returns: zero => a data character + positive => a special escape sequence + negative => a back reference + on error, errorcodeptr is set +*/ + +static int +check_escape(const pcre_uchar **ptrptr, pcre_uint32 *chptr, int *errorcodeptr, + int bracount, int options, BOOL isclass) +{ +/* PCRE_UTF16 has the same value as PCRE_UTF8. */ +BOOL utf = (options & PCRE_UTF8) != 0; +const pcre_uchar *ptr = *ptrptr + 1; +pcre_uint32 c; +int escape = 0; +int i; + +GETCHARINCTEST(c, ptr); /* Get character value, increment pointer */ +ptr--; /* Set pointer back to the last byte */ + +/* If backslash is at the end of the pattern, it's an error. */ + +if (c == CHAR_NULL) *errorcodeptr = ERR1; + +/* Non-alphanumerics are literals. For digits or letters, do an initial lookup +in a table. A non-zero result is something that can be returned immediately. +Otherwise further processing may be required. */ + +#ifndef EBCDIC /* ASCII/UTF-8 coding */ +/* Not alphanumeric */ +else if (c < CHAR_0 || c > CHAR_z) {} +else if ((i = escapes[c - CHAR_0]) != 0) + { if (i > 0) c = (pcre_uint32)i; else escape = -i; } + +#else /* EBCDIC coding */ +/* Not alphanumeric */ +else if (c < CHAR_a || (!MAX_255(c) || (ebcdic_chartab[c] & 0x0E) == 0)) {} +else if ((i = escapes[c - 0x48]) != 0) { if (i > 0) c = (pcre_uint32)i; else escape = -i; } +#endif + +/* Escapes that need further processing, or are illegal. */ + +else + { + const pcre_uchar *oldptr; + BOOL braced, negated, overflow; + int s; + + switch (c) + { + /* A number of Perl escapes are not handled by PCRE. We give an explicit + error. */ + + case CHAR_l: + case CHAR_L: + *errorcodeptr = ERR37; + break; + + case CHAR_u: + if ((options & PCRE_JAVASCRIPT_COMPAT) != 0) + { + /* In JavaScript, \u must be followed by four hexadecimal numbers. + Otherwise it is a lowercase u letter. */ + if (MAX_255(ptr[1]) && (digitab[ptr[1]] & ctype_xdigit) != 0 + && MAX_255(ptr[2]) && (digitab[ptr[2]] & ctype_xdigit) != 0 + && MAX_255(ptr[3]) && (digitab[ptr[3]] & ctype_xdigit) != 0 + && MAX_255(ptr[4]) && (digitab[ptr[4]] & ctype_xdigit) != 0) + { + c = 0; + for (i = 0; i < 4; ++i) + { + register pcre_uint32 cc = *(++ptr); +#ifndef EBCDIC /* ASCII/UTF-8 coding */ + if (cc >= CHAR_a) cc -= 32; /* Convert to upper case */ + c = (c << 4) + cc - ((cc < CHAR_A)? CHAR_0 : (CHAR_A - 10)); +#else /* EBCDIC coding */ + if (cc >= CHAR_a && cc <= CHAR_z) cc += 64; /* Convert to upper case */ + c = (c << 4) + cc - ((cc >= CHAR_0)? CHAR_0 : (CHAR_A - 10)); +#endif + } + +#if defined COMPILE_PCRE8 + if (c > (utf ? 0x10ffffU : 0xffU)) +#elif defined COMPILE_PCRE16 + if (c > (utf ? 0x10ffffU : 0xffffU)) +#elif defined COMPILE_PCRE32 + if (utf && c > 0x10ffffU) +#endif + { + *errorcodeptr = ERR76; + } + else if (utf && c >= 0xd800 && c <= 0xdfff) *errorcodeptr = ERR73; + } + } + else + *errorcodeptr = ERR37; + break; + + case CHAR_U: + /* In JavaScript, \U is an uppercase U letter. */ + if ((options & PCRE_JAVASCRIPT_COMPAT) == 0) *errorcodeptr = ERR37; + break; + + /* In a character class, \g is just a literal "g". Outside a character + class, \g must be followed by one of a number of specific things: + + (1) A number, either plain or braced. If positive, it is an absolute + backreference. If negative, it is a relative backreference. This is a Perl + 5.10 feature. + + (2) Perl 5.10 also supports \g{name} as a reference to a named group. This + is part of Perl's movement towards a unified syntax for back references. As + this is synonymous with \k{name}, we fudge it up by pretending it really + was \k. + + (3) For Oniguruma compatibility we also support \g followed by a name or a + number either in angle brackets or in single quotes. However, these are + (possibly recursive) subroutine calls, _not_ backreferences. Just return + the ESC_g code (cf \k). */ + + case CHAR_g: + if (isclass) break; + if (ptr[1] == CHAR_LESS_THAN_SIGN || ptr[1] == CHAR_APOSTROPHE) + { + escape = ESC_g; + break; + } + + /* Handle the Perl-compatible cases */ + + if (ptr[1] == CHAR_LEFT_CURLY_BRACKET) + { + const pcre_uchar *p; + for (p = ptr+2; *p != CHAR_NULL && *p != CHAR_RIGHT_CURLY_BRACKET; p++) + if (*p != CHAR_MINUS && !IS_DIGIT(*p)) break; + if (*p != CHAR_NULL && *p != CHAR_RIGHT_CURLY_BRACKET) + { + escape = ESC_k; + break; + } + braced = TRUE; + ptr++; + } + else braced = FALSE; + + if (ptr[1] == CHAR_MINUS) + { + negated = TRUE; + ptr++; + } + else negated = FALSE; + + /* The integer range is limited by the machine's int representation. */ + s = 0; + overflow = FALSE; + while (IS_DIGIT(ptr[1])) + { + if (s > INT_MAX / 10 - 1) /* Integer overflow */ + { + overflow = TRUE; + break; + } + s = s * 10 + (int)(*(++ptr) - CHAR_0); + } + if (overflow) /* Integer overflow */ + { + while (IS_DIGIT(ptr[1])) + ptr++; + *errorcodeptr = ERR61; + break; + } + + if (braced && *(++ptr) != CHAR_RIGHT_CURLY_BRACKET) + { + *errorcodeptr = ERR57; + break; + } + + if (s == 0) + { + *errorcodeptr = ERR58; + break; + } + + if (negated) + { + if (s > bracount) + { + *errorcodeptr = ERR15; + break; + } + s = bracount - (s - 1); + } + + escape = -s; + break; + + /* The handling of escape sequences consisting of a string of digits + starting with one that is not zero is not straightforward. Perl has changed + over the years. Nowadays \g{} for backreferences and \o{} for octal are + recommended to avoid the ambiguities in the old syntax. + + Outside a character class, the digits are read as a decimal number. If the + number is less than 8 (used to be 10), or if there are that many previous + extracting left brackets, then it is a back reference. Otherwise, up to + three octal digits are read to form an escaped byte. Thus \123 is likely to + be octal 123 (cf \0123, which is octal 012 followed by the literal 3). If + the octal value is greater than 377, the least significant 8 bits are + taken. \8 and \9 are treated as the literal characters 8 and 9. + + Inside a character class, \ followed by a digit is always either a literal + 8 or 9 or an octal number. */ + + case CHAR_1: case CHAR_2: case CHAR_3: case CHAR_4: case CHAR_5: + case CHAR_6: case CHAR_7: case CHAR_8: case CHAR_9: + + if (!isclass) + { + oldptr = ptr; + /* The integer range is limited by the machine's int representation. */ + s = (int)(c -CHAR_0); + overflow = FALSE; + while (IS_DIGIT(ptr[1])) + { + if (s > INT_MAX / 10 - 1) /* Integer overflow */ + { + overflow = TRUE; + break; + } + s = s * 10 + (int)(*(++ptr) - CHAR_0); + } + if (overflow) /* Integer overflow */ + { + while (IS_DIGIT(ptr[1])) + ptr++; + *errorcodeptr = ERR61; + break; + } + if (s < 8 || s <= bracount) /* Check for back reference */ + { + escape = -s; + break; + } + ptr = oldptr; /* Put the pointer back and fall through */ + } + + /* Handle a digit following \ when the number is not a back reference. If + the first digit is 8 or 9, Perl used to generate a binary zero byte and + then treat the digit as a following literal. At least by Perl 5.18 this + changed so as not to insert the binary zero. */ + + if ((c = *ptr) >= CHAR_8) break; + + /* Fall through with a digit less than 8 */ + + /* \0 always starts an octal number, but we may drop through to here with a + larger first octal digit. The original code used just to take the least + significant 8 bits of octal numbers (I think this is what early Perls used + to do). Nowadays we allow for larger numbers in UTF-8 mode and 16-bit mode, + but no more than 3 octal digits. */ + + case CHAR_0: + c -= CHAR_0; + while(i++ < 2 && ptr[1] >= CHAR_0 && ptr[1] <= CHAR_7) + c = c * 8 + *(++ptr) - CHAR_0; +#ifdef COMPILE_PCRE8 + if (!utf && c > 0xff) *errorcodeptr = ERR51; +#endif + break; + + /* \o is a relatively new Perl feature, supporting a more general way of + specifying character codes in octal. The only supported form is \o{ddd}. */ + + case CHAR_o: + if (ptr[1] != CHAR_LEFT_CURLY_BRACKET) *errorcodeptr = ERR81; else + if (ptr[2] == CHAR_RIGHT_CURLY_BRACKET) *errorcodeptr = ERR86; else + { + ptr += 2; + c = 0; + overflow = FALSE; + while (*ptr >= CHAR_0 && *ptr <= CHAR_7) + { + register pcre_uint32 cc = *ptr++; + if (c == 0 && cc == CHAR_0) continue; /* Leading zeroes */ +#ifdef COMPILE_PCRE32 + if (c >= 0x20000000l) { overflow = TRUE; break; } +#endif + c = (c << 3) + cc - CHAR_0 ; +#if defined COMPILE_PCRE8 + if (c > (utf ? 0x10ffffU : 0xffU)) { overflow = TRUE; break; } +#elif defined COMPILE_PCRE16 + if (c > (utf ? 0x10ffffU : 0xffffU)) { overflow = TRUE; break; } +#elif defined COMPILE_PCRE32 + if (utf && c > 0x10ffffU) { overflow = TRUE; break; } +#endif + } + if (overflow) + { + while (*ptr >= CHAR_0 && *ptr <= CHAR_7) ptr++; + *errorcodeptr = ERR34; + } + else if (*ptr == CHAR_RIGHT_CURLY_BRACKET) + { + if (utf && c >= 0xd800 && c <= 0xdfff) *errorcodeptr = ERR73; + } + else *errorcodeptr = ERR80; + } + break; + + /* \x is complicated. In JavaScript, \x must be followed by two hexadecimal + numbers. Otherwise it is a lowercase x letter. */ + + case CHAR_x: + if ((options & PCRE_JAVASCRIPT_COMPAT) != 0) + { + if (MAX_255(ptr[1]) && (digitab[ptr[1]] & ctype_xdigit) != 0 + && MAX_255(ptr[2]) && (digitab[ptr[2]] & ctype_xdigit) != 0) + { + c = 0; + for (i = 0; i < 2; ++i) + { + register pcre_uint32 cc = *(++ptr); +#ifndef EBCDIC /* ASCII/UTF-8 coding */ + if (cc >= CHAR_a) cc -= 32; /* Convert to upper case */ + c = (c << 4) + cc - ((cc < CHAR_A)? CHAR_0 : (CHAR_A - 10)); +#else /* EBCDIC coding */ + if (cc >= CHAR_a && cc <= CHAR_z) cc += 64; /* Convert to upper case */ + c = (c << 4) + cc - ((cc >= CHAR_0)? CHAR_0 : (CHAR_A - 10)); +#endif + } + } + } /* End JavaScript handling */ + + /* Handle \x in Perl's style. \x{ddd} is a character number which can be + greater than 0xff in utf or non-8bit mode, but only if the ddd are hex + digits. If not, { used to be treated as a data character. However, Perl + seems to read hex digits up to the first non-such, and ignore the rest, so + that, for example \x{zz} matches a binary zero. This seems crazy, so PCRE + now gives an error. */ + + else + { + if (ptr[1] == CHAR_LEFT_CURLY_BRACKET) + { + ptr += 2; + if (*ptr == CHAR_RIGHT_CURLY_BRACKET) + { + *errorcodeptr = ERR86; + break; + } + c = 0; + overflow = FALSE; + while (MAX_255(*ptr) && (digitab[*ptr] & ctype_xdigit) != 0) + { + register pcre_uint32 cc = *ptr++; + if (c == 0 && cc == CHAR_0) continue; /* Leading zeroes */ + +#ifdef COMPILE_PCRE32 + if (c >= 0x10000000l) { overflow = TRUE; break; } +#endif + +#ifndef EBCDIC /* ASCII/UTF-8 coding */ + if (cc >= CHAR_a) cc -= 32; /* Convert to upper case */ + c = (c << 4) + cc - ((cc < CHAR_A)? CHAR_0 : (CHAR_A - 10)); +#else /* EBCDIC coding */ + if (cc >= CHAR_a && cc <= CHAR_z) cc += 64; /* Convert to upper case */ + c = (c << 4) + cc - ((cc >= CHAR_0)? CHAR_0 : (CHAR_A - 10)); +#endif + +#if defined COMPILE_PCRE8 + if (c > (utf ? 0x10ffffU : 0xffU)) { overflow = TRUE; break; } +#elif defined COMPILE_PCRE16 + if (c > (utf ? 0x10ffffU : 0xffffU)) { overflow = TRUE; break; } +#elif defined COMPILE_PCRE32 + if (utf && c > 0x10ffffU) { overflow = TRUE; break; } +#endif + } + + if (overflow) + { + while (MAX_255(*ptr) && (digitab[*ptr] & ctype_xdigit) != 0) ptr++; + *errorcodeptr = ERR34; + } + + else if (*ptr == CHAR_RIGHT_CURLY_BRACKET) + { + if (utf && c >= 0xd800 && c <= 0xdfff) *errorcodeptr = ERR73; + } + + /* If the sequence of hex digits does not end with '}', give an error. + We used just to recognize this construct and fall through to the normal + \x handling, but nowadays Perl gives an error, which seems much more + sensible, so we do too. */ + + else *errorcodeptr = ERR79; + } /* End of \x{} processing */ + + /* Read a single-byte hex-defined char (up to two hex digits after \x) */ + + else + { + c = 0; + while (i++ < 2 && MAX_255(ptr[1]) && (digitab[ptr[1]] & ctype_xdigit) != 0) + { + pcre_uint32 cc; /* Some compilers don't like */ + cc = *(++ptr); /* ++ in initializers */ +#ifndef EBCDIC /* ASCII/UTF-8 coding */ + if (cc >= CHAR_a) cc -= 32; /* Convert to upper case */ + c = c * 16 + cc - ((cc < CHAR_A)? CHAR_0 : (CHAR_A - 10)); +#else /* EBCDIC coding */ + if (cc <= CHAR_z) cc += 64; /* Convert to upper case */ + c = c * 16 + cc - ((cc >= CHAR_0)? CHAR_0 : (CHAR_A - 10)); +#endif + } + } /* End of \xdd handling */ + } /* End of Perl-style \x handling */ + break; + + /* For \c, a following letter is upper-cased; then the 0x40 bit is flipped. + An error is given if the byte following \c is not an ASCII character. This + coding is ASCII-specific, but then the whole concept of \cx is + ASCII-specific. (However, an EBCDIC equivalent has now been added.) */ + + case CHAR_c: + c = *(++ptr); + if (c == CHAR_NULL) + { + *errorcodeptr = ERR2; + break; + } +#ifndef EBCDIC /* ASCII/UTF-8 coding */ + if (c > 127) /* Excludes all non-ASCII in either mode */ + { + *errorcodeptr = ERR68; + break; + } + if (c >= CHAR_a && c <= CHAR_z) c -= 32; + c ^= 0x40; +#else /* EBCDIC coding */ + if (c >= CHAR_a && c <= CHAR_z) c += 64; + c ^= 0xC0; +#endif + break; + + /* PCRE_EXTRA enables extensions to Perl in the matter of escapes. Any + other alphanumeric following \ is an error if PCRE_EXTRA was set; + otherwise, for Perl compatibility, it is a literal. This code looks a bit + odd, but there used to be some cases other than the default, and there may + be again in future, so I haven't "optimized" it. */ + + default: + if ((options & PCRE_EXTRA) != 0) switch(c) + { + default: + *errorcodeptr = ERR3; + break; + } + break; + } + } + +/* Perl supports \N{name} for character names, as well as plain \N for "not +newline". PCRE does not support \N{name}. However, it does support +quantification such as \N{2,3}. */ + +if (escape == ESC_N && ptr[1] == CHAR_LEFT_CURLY_BRACKET && + !is_counted_repeat(ptr+2)) + *errorcodeptr = ERR37; + +/* If PCRE_UCP is set, we change the values for \d etc. */ + +if ((options & PCRE_UCP) != 0 && escape >= ESC_D && escape <= ESC_w) + escape += (ESC_DU - ESC_D); + +/* Set the pointer to the final character before returning. */ + +*ptrptr = ptr; +*chptr = c; +return escape; +} + + + +#ifdef SUPPORT_UCP +/************************************************* +* Handle \P and \p * +*************************************************/ + +/* This function is called after \P or \p has been encountered, provided that +PCRE is compiled with support for Unicode properties. On entry, ptrptr is +pointing at the P or p. On exit, it is pointing at the final character of the +escape sequence. + +Argument: + ptrptr points to the pattern position pointer + negptr points to a boolean that is set TRUE for negation else FALSE + ptypeptr points to an unsigned int that is set to the type value + pdataptr points to an unsigned int that is set to the detailed property value + errorcodeptr points to the error code variable + +Returns: TRUE if the type value was found, or FALSE for an invalid type +*/ + +static BOOL +get_ucp(const pcre_uchar **ptrptr, BOOL *negptr, unsigned int *ptypeptr, + unsigned int *pdataptr, int *errorcodeptr) +{ +pcre_uchar c; +int i, bot, top; +const pcre_uchar *ptr = *ptrptr; +pcre_uchar name[32]; + +c = *(++ptr); +if (c == CHAR_NULL) goto ERROR_RETURN; + +*negptr = FALSE; + +/* \P or \p can be followed by a name in {}, optionally preceded by ^ for +negation. */ + +if (c == CHAR_LEFT_CURLY_BRACKET) + { + if (ptr[1] == CHAR_CIRCUMFLEX_ACCENT) + { + *negptr = TRUE; + ptr++; + } + for (i = 0; i < (int)(sizeof(name) / sizeof(pcre_uchar)) - 1; i++) + { + c = *(++ptr); + if (c == CHAR_NULL) goto ERROR_RETURN; + if (c == CHAR_RIGHT_CURLY_BRACKET) break; + name[i] = c; + } + if (c != CHAR_RIGHT_CURLY_BRACKET) goto ERROR_RETURN; + name[i] = 0; + } + +/* Otherwise there is just one following character */ + +else + { + name[0] = c; + name[1] = 0; + } + +*ptrptr = ptr; + +/* Search for a recognized property name using binary chop */ + +bot = 0; +top = PRIV(utt_size); + +while (bot < top) + { + int r; + i = (bot + top) >> 1; + r = STRCMP_UC_C8(name, PRIV(utt_names) + PRIV(utt)[i].name_offset); + if (r == 0) + { + *ptypeptr = PRIV(utt)[i].type; + *pdataptr = PRIV(utt)[i].value; + return TRUE; + } + if (r > 0) bot = i + 1; else top = i; + } + +*errorcodeptr = ERR47; +*ptrptr = ptr; +return FALSE; + +ERROR_RETURN: +*errorcodeptr = ERR46; +*ptrptr = ptr; +return FALSE; +} +#endif + + + +/************************************************* +* Read repeat counts * +*************************************************/ + +/* Read an item of the form {n,m} and return the values. This is called only +after is_counted_repeat() has confirmed that a repeat-count quantifier exists, +so the syntax is guaranteed to be correct, but we need to check the values. + +Arguments: + p pointer to first char after '{' + minp pointer to int for min + maxp pointer to int for max + returned as -1 if no max + errorcodeptr points to error code variable + +Returns: pointer to '}' on success; + current ptr on error, with errorcodeptr set non-zero +*/ + +static const pcre_uchar * +read_repeat_counts(const pcre_uchar *p, int *minp, int *maxp, int *errorcodeptr) +{ +int min = 0; +int max = -1; + +while (IS_DIGIT(*p)) + { + min = min * 10 + (int)(*p++ - CHAR_0); + if (min > 65535) + { + *errorcodeptr = ERR5; + return p; + } + } + +if (*p == CHAR_RIGHT_CURLY_BRACKET) max = min; else + { + if (*(++p) != CHAR_RIGHT_CURLY_BRACKET) + { + max = 0; + while(IS_DIGIT(*p)) + { + max = max * 10 + (int)(*p++ - CHAR_0); + if (max > 65535) + { + *errorcodeptr = ERR5; + return p; + } + } + if (max < min) + { + *errorcodeptr = ERR4; + return p; + } + } + } + +*minp = min; +*maxp = max; +return p; +} + + + +/************************************************* +* Find first significant op code * +*************************************************/ + +/* This is called by several functions that scan a compiled expression looking +for a fixed first character, or an anchoring op code etc. It skips over things +that do not influence this. For some calls, it makes sense to skip negative +forward and all backward assertions, and also the \b assertion; for others it +does not. + +Arguments: + code pointer to the start of the group + skipassert TRUE if certain assertions are to be skipped + +Returns: pointer to the first significant opcode +*/ + +static const pcre_uchar* +first_significant_code(const pcre_uchar *code, BOOL skipassert) +{ +for (;;) + { + switch ((int)*code) + { + case OP_ASSERT_NOT: + case OP_ASSERTBACK: + case OP_ASSERTBACK_NOT: + if (!skipassert) return code; + do code += GET(code, 1); while (*code == OP_ALT); + code += PRIV(OP_lengths)[*code]; + break; + + case OP_WORD_BOUNDARY: + case OP_NOT_WORD_BOUNDARY: + if (!skipassert) return code; + /* Fall through */ + + case OP_CALLOUT: + case OP_CREF: + case OP_DNCREF: + case OP_RREF: + case OP_DNRREF: + case OP_DEF: + code += PRIV(OP_lengths)[*code]; + break; + + default: + return code; + } + } +/* Control never reaches here */ +} + + + +/************************************************* +* Find the fixed length of a branch * +*************************************************/ + +/* Scan a branch and compute the fixed length of subject that will match it, +if the length is fixed. This is needed for dealing with backward assertions. +In UTF8 mode, the result is in characters rather than bytes. The branch is +temporarily terminated with OP_END when this function is called. + +This function is called when a backward assertion is encountered, so that if it +fails, the error message can point to the correct place in the pattern. +However, we cannot do this when the assertion contains subroutine calls, +because they can be forward references. We solve this by remembering this case +and doing the check at the end; a flag specifies which mode we are running in. + +Arguments: + code points to the start of the pattern (the bracket) + utf TRUE in UTF-8 / UTF-16 / UTF-32 mode + atend TRUE if called when the pattern is complete + cd the "compile data" structure + +Returns: the fixed length, + or -1 if there is no fixed length, + or -2 if \C was encountered (in UTF-8 mode only) + or -3 if an OP_RECURSE item was encountered and atend is FALSE + or -4 if an unknown opcode was encountered (internal error) +*/ + +static int +find_fixedlength(pcre_uchar *code, BOOL utf, BOOL atend, compile_data *cd) +{ +int length = -1; + +register int branchlength = 0; +register pcre_uchar *cc = code + 1 + LINK_SIZE; + +/* Scan along the opcodes for this branch. If we get to the end of the +branch, check the length against that of the other branches. */ + +for (;;) + { + int d; + pcre_uchar *ce, *cs; + register pcre_uchar op = *cc; + + switch (op) + { + /* We only need to continue for OP_CBRA (normal capturing bracket) and + OP_BRA (normal non-capturing bracket) because the other variants of these + opcodes are all concerned with unlimited repeated groups, which of course + are not of fixed length. */ + + case OP_CBRA: + case OP_BRA: + case OP_ONCE: + case OP_ONCE_NC: + case OP_COND: + d = find_fixedlength(cc + ((op == OP_CBRA)? IMM2_SIZE : 0), utf, atend, cd); + if (d < 0) return d; + branchlength += d; + do cc += GET(cc, 1); while (*cc == OP_ALT); + cc += 1 + LINK_SIZE; + break; + + /* Reached end of a branch; if it's a ket it is the end of a nested call. + If it's ALT it is an alternation in a nested call. An ACCEPT is effectively + an ALT. If it is END it's the end of the outer call. All can be handled by + the same code. Note that we must not include the OP_KETRxxx opcodes here, + because they all imply an unlimited repeat. */ + + case OP_ALT: + case OP_KET: + case OP_END: + case OP_ACCEPT: + case OP_ASSERT_ACCEPT: + if (length < 0) length = branchlength; + else if (length != branchlength) return -1; + if (*cc != OP_ALT) return length; + cc += 1 + LINK_SIZE; + branchlength = 0; + break; + + /* A true recursion implies not fixed length, but a subroutine call may + be OK. If the subroutine is a forward reference, we can't deal with + it until the end of the pattern, so return -3. */ + + case OP_RECURSE: + if (!atend) return -3; + cs = ce = (pcre_uchar *)cd->start_code + GET(cc, 1); /* Start subpattern */ + do ce += GET(ce, 1); while (*ce == OP_ALT); /* End subpattern */ + if (cc > cs && cc < ce) return -1; /* Recursion */ + d = find_fixedlength(cs + IMM2_SIZE, utf, atend, cd); + if (d < 0) return d; + branchlength += d; + cc += 1 + LINK_SIZE; + break; + + /* Skip over assertive subpatterns */ + + case OP_ASSERT: + case OP_ASSERT_NOT: + case OP_ASSERTBACK: + case OP_ASSERTBACK_NOT: + do cc += GET(cc, 1); while (*cc == OP_ALT); + cc += PRIV(OP_lengths)[*cc]; + break; + + /* Skip over things that don't match chars */ + + case OP_MARK: + case OP_PRUNE_ARG: + case OP_SKIP_ARG: + case OP_THEN_ARG: + cc += cc[1] + PRIV(OP_lengths)[*cc]; + break; + + case OP_CALLOUT: + case OP_CIRC: + case OP_CIRCM: + case OP_CLOSE: + case OP_COMMIT: + case OP_CREF: + case OP_DEF: + case OP_DNCREF: + case OP_DNRREF: + case OP_DOLL: + case OP_DOLLM: + case OP_EOD: + case OP_EODN: + case OP_FAIL: + case OP_NOT_WORD_BOUNDARY: + case OP_PRUNE: + case OP_REVERSE: + case OP_RREF: + case OP_SET_SOM: + case OP_SKIP: + case OP_SOD: + case OP_SOM: + case OP_THEN: + case OP_WORD_BOUNDARY: + cc += PRIV(OP_lengths)[*cc]; + break; + + /* Handle literal characters */ + + case OP_CHAR: + case OP_CHARI: + case OP_NOT: + case OP_NOTI: + branchlength++; + cc += 2; +#ifdef SUPPORT_UTF + if (utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]); +#endif + break; + + /* Handle exact repetitions. The count is already in characters, but we + need to skip over a multibyte character in UTF8 mode. */ + + case OP_EXACT: + case OP_EXACTI: + case OP_NOTEXACT: + case OP_NOTEXACTI: + branchlength += (int)GET2(cc,1); + cc += 2 + IMM2_SIZE; +#ifdef SUPPORT_UTF + if (utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]); +#endif + break; + + case OP_TYPEEXACT: + branchlength += GET2(cc,1); + if (cc[1 + IMM2_SIZE] == OP_PROP || cc[1 + IMM2_SIZE] == OP_NOTPROP) + cc += 2; + cc += 1 + IMM2_SIZE + 1; + break; + + /* Handle single-char matchers */ + + case OP_PROP: + case OP_NOTPROP: + cc += 2; + /* Fall through */ + + case OP_HSPACE: + case OP_VSPACE: + case OP_NOT_HSPACE: + case OP_NOT_VSPACE: + case OP_NOT_DIGIT: + case OP_DIGIT: + case OP_NOT_WHITESPACE: + case OP_WHITESPACE: + case OP_NOT_WORDCHAR: + case OP_WORDCHAR: + case OP_ANY: + case OP_ALLANY: + branchlength++; + cc++; + break; + + /* The single-byte matcher isn't allowed. This only happens in UTF-8 mode; + otherwise \C is coded as OP_ALLANY. */ + + case OP_ANYBYTE: + return -2; + + /* Check a class for variable quantification */ + + case OP_CLASS: + case OP_NCLASS: +#if defined SUPPORT_UTF || defined COMPILE_PCRE16 || defined COMPILE_PCRE32 + case OP_XCLASS: + /* The original code caused an unsigned overflow in 64 bit systems, + so now we use a conditional statement. */ + if (op == OP_XCLASS) + cc += GET(cc, 1); + else + cc += PRIV(OP_lengths)[OP_CLASS]; +#else + cc += PRIV(OP_lengths)[OP_CLASS]; +#endif + + switch (*cc) + { + case OP_CRSTAR: + case OP_CRMINSTAR: + case OP_CRPLUS: + case OP_CRMINPLUS: + case OP_CRQUERY: + case OP_CRMINQUERY: + case OP_CRPOSSTAR: + case OP_CRPOSPLUS: + case OP_CRPOSQUERY: + return -1; + + case OP_CRRANGE: + case OP_CRMINRANGE: + case OP_CRPOSRANGE: + if (GET2(cc,1) != GET2(cc,1+IMM2_SIZE)) return -1; + branchlength += (int)GET2(cc,1); + cc += 1 + 2 * IMM2_SIZE; + break; + + default: + branchlength++; + } + break; + + /* Anything else is variable length */ + + case OP_ANYNL: + case OP_BRAMINZERO: + case OP_BRAPOS: + case OP_BRAPOSZERO: + case OP_BRAZERO: + case OP_CBRAPOS: + case OP_EXTUNI: + case OP_KETRMAX: + case OP_KETRMIN: + case OP_KETRPOS: + case OP_MINPLUS: + case OP_MINPLUSI: + case OP_MINQUERY: + case OP_MINQUERYI: + case OP_MINSTAR: + case OP_MINSTARI: + case OP_MINUPTO: + case OP_MINUPTOI: + case OP_NOTMINPLUS: + case OP_NOTMINPLUSI: + case OP_NOTMINQUERY: + case OP_NOTMINQUERYI: + case OP_NOTMINSTAR: + case OP_NOTMINSTARI: + case OP_NOTMINUPTO: + case OP_NOTMINUPTOI: + case OP_NOTPLUS: + case OP_NOTPLUSI: + case OP_NOTPOSPLUS: + case OP_NOTPOSPLUSI: + case OP_NOTPOSQUERY: + case OP_NOTPOSQUERYI: + case OP_NOTPOSSTAR: + case OP_NOTPOSSTARI: + case OP_NOTPOSUPTO: + case OP_NOTPOSUPTOI: + case OP_NOTQUERY: + case OP_NOTQUERYI: + case OP_NOTSTAR: + case OP_NOTSTARI: + case OP_NOTUPTO: + case OP_NOTUPTOI: + case OP_PLUS: + case OP_PLUSI: + case OP_POSPLUS: + case OP_POSPLUSI: + case OP_POSQUERY: + case OP_POSQUERYI: + case OP_POSSTAR: + case OP_POSSTARI: + case OP_POSUPTO: + case OP_POSUPTOI: + case OP_QUERY: + case OP_QUERYI: + case OP_REF: + case OP_REFI: + case OP_DNREF: + case OP_DNREFI: + case OP_SBRA: + case OP_SBRAPOS: + case OP_SCBRA: + case OP_SCBRAPOS: + case OP_SCOND: + case OP_SKIPZERO: + case OP_STAR: + case OP_STARI: + case OP_TYPEMINPLUS: + case OP_TYPEMINQUERY: + case OP_TYPEMINSTAR: + case OP_TYPEMINUPTO: + case OP_TYPEPLUS: + case OP_TYPEPOSPLUS: + case OP_TYPEPOSQUERY: + case OP_TYPEPOSSTAR: + case OP_TYPEPOSUPTO: + case OP_TYPEQUERY: + case OP_TYPESTAR: + case OP_TYPEUPTO: + case OP_UPTO: + case OP_UPTOI: + return -1; + + /* Catch unrecognized opcodes so that when new ones are added they + are not forgotten, as has happened in the past. */ + + default: + return -4; + } + } +/* Control never gets here */ +} + + + +/************************************************* +* Scan compiled regex for specific bracket * +*************************************************/ + +/* This little function scans through a compiled pattern until it finds a +capturing bracket with the given number, or, if the number is negative, an +instance of OP_REVERSE for a lookbehind. The function is global in the C sense +so that it can be called from pcre_study() when finding the minimum matching +length. + +Arguments: + code points to start of expression + utf TRUE in UTF-8 / UTF-16 / UTF-32 mode + number the required bracket number or negative to find a lookbehind + +Returns: pointer to the opcode for the bracket, or NULL if not found +*/ + +const pcre_uchar * +PRIV(find_bracket)(const pcre_uchar *code, BOOL utf, int number) +{ +for (;;) + { + register pcre_uchar c = *code; + + if (c == OP_END) return NULL; + + /* XCLASS is used for classes that cannot be represented just by a bit + map. This includes negated single high-valued characters. The length in + the table is zero; the actual length is stored in the compiled code. */ + + if (c == OP_XCLASS) code += GET(code, 1); + + /* Handle recursion */ + + else if (c == OP_REVERSE) + { + if (number < 0) return (pcre_uchar *)code; + code += PRIV(OP_lengths)[c]; + } + + /* Handle capturing bracket */ + + else if (c == OP_CBRA || c == OP_SCBRA || + c == OP_CBRAPOS || c == OP_SCBRAPOS) + { + int n = (int)GET2(code, 1+LINK_SIZE); + if (n == number) return (pcre_uchar *)code; + code += PRIV(OP_lengths)[c]; + } + + /* Otherwise, we can get the item's length from the table, except that for + repeated character types, we have to test for \p and \P, which have an extra + two bytes of parameters, and for MARK/PRUNE/SKIP/THEN with an argument, we + must add in its length. */ + + else + { + switch(c) + { + case OP_TYPESTAR: + case OP_TYPEMINSTAR: + case OP_TYPEPLUS: + case OP_TYPEMINPLUS: + case OP_TYPEQUERY: + case OP_TYPEMINQUERY: + case OP_TYPEPOSSTAR: + case OP_TYPEPOSPLUS: + case OP_TYPEPOSQUERY: + if (code[1] == OP_PROP || code[1] == OP_NOTPROP) code += 2; + break; + + case OP_TYPEUPTO: + case OP_TYPEMINUPTO: + case OP_TYPEEXACT: + case OP_TYPEPOSUPTO: + if (code[1 + IMM2_SIZE] == OP_PROP || code[1 + IMM2_SIZE] == OP_NOTPROP) + code += 2; + break; + + case OP_MARK: + case OP_PRUNE_ARG: + case OP_SKIP_ARG: + case OP_THEN_ARG: + code += code[1]; + break; + } + + /* Add in the fixed length from the table */ + + code += PRIV(OP_lengths)[c]; + + /* In UTF-8 mode, opcodes that are followed by a character may be followed by + a multi-byte character. The length in the table is a minimum, so we have to + arrange to skip the extra bytes. */ + +#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 + if (utf) switch(c) + { + case OP_CHAR: + case OP_CHARI: + case OP_EXACT: + case OP_EXACTI: + case OP_UPTO: + case OP_UPTOI: + case OP_MINUPTO: + case OP_MINUPTOI: + case OP_POSUPTO: + case OP_POSUPTOI: + case OP_STAR: + case OP_STARI: + case OP_MINSTAR: + case OP_MINSTARI: + case OP_POSSTAR: + case OP_POSSTARI: + case OP_PLUS: + case OP_PLUSI: + case OP_MINPLUS: + case OP_MINPLUSI: + case OP_POSPLUS: + case OP_POSPLUSI: + case OP_QUERY: + case OP_QUERYI: + case OP_MINQUERY: + case OP_MINQUERYI: + case OP_POSQUERY: + case OP_POSQUERYI: + if (HAS_EXTRALEN(code[-1])) code += GET_EXTRALEN(code[-1]); + break; + } +#else + (void)(utf); /* Keep compiler happy by referencing function argument */ +#endif + } + } +} + + + +/************************************************* +* Scan compiled regex for recursion reference * +*************************************************/ + +/* This little function scans through a compiled pattern until it finds an +instance of OP_RECURSE. + +Arguments: + code points to start of expression + utf TRUE in UTF-8 / UTF-16 / UTF-32 mode + +Returns: pointer to the opcode for OP_RECURSE, or NULL if not found +*/ + +static const pcre_uchar * +find_recurse(const pcre_uchar *code, BOOL utf) +{ +for (;;) + { + register pcre_uchar c = *code; + if (c == OP_END) return NULL; + if (c == OP_RECURSE) return code; + + /* XCLASS is used for classes that cannot be represented just by a bit + map. This includes negated single high-valued characters. The length in + the table is zero; the actual length is stored in the compiled code. */ + + if (c == OP_XCLASS) code += GET(code, 1); + + /* Otherwise, we can get the item's length from the table, except that for + repeated character types, we have to test for \p and \P, which have an extra + two bytes of parameters, and for MARK/PRUNE/SKIP/THEN with an argument, we + must add in its length. */ + + else + { + switch(c) + { + case OP_TYPESTAR: + case OP_TYPEMINSTAR: + case OP_TYPEPLUS: + case OP_TYPEMINPLUS: + case OP_TYPEQUERY: + case OP_TYPEMINQUERY: + case OP_TYPEPOSSTAR: + case OP_TYPEPOSPLUS: + case OP_TYPEPOSQUERY: + if (code[1] == OP_PROP || code[1] == OP_NOTPROP) code += 2; + break; + + case OP_TYPEPOSUPTO: + case OP_TYPEUPTO: + case OP_TYPEMINUPTO: + case OP_TYPEEXACT: + if (code[1 + IMM2_SIZE] == OP_PROP || code[1 + IMM2_SIZE] == OP_NOTPROP) + code += 2; + break; + + case OP_MARK: + case OP_PRUNE_ARG: + case OP_SKIP_ARG: + case OP_THEN_ARG: + code += code[1]; + break; + } + + /* Add in the fixed length from the table */ + + code += PRIV(OP_lengths)[c]; + + /* In UTF-8 mode, opcodes that are followed by a character may be followed + by a multi-byte character. The length in the table is a minimum, so we have + to arrange to skip the extra bytes. */ + +#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 + if (utf) switch(c) + { + case OP_CHAR: + case OP_CHARI: + case OP_NOT: + case OP_NOTI: + case OP_EXACT: + case OP_EXACTI: + case OP_NOTEXACT: + case OP_NOTEXACTI: + case OP_UPTO: + case OP_UPTOI: + case OP_NOTUPTO: + case OP_NOTUPTOI: + case OP_MINUPTO: + case OP_MINUPTOI: + case OP_NOTMINUPTO: + case OP_NOTMINUPTOI: + case OP_POSUPTO: + case OP_POSUPTOI: + case OP_NOTPOSUPTO: + case OP_NOTPOSUPTOI: + case OP_STAR: + case OP_STARI: + case OP_NOTSTAR: + case OP_NOTSTARI: + case OP_MINSTAR: + case OP_MINSTARI: + case OP_NOTMINSTAR: + case OP_NOTMINSTARI: + case OP_POSSTAR: + case OP_POSSTARI: + case OP_NOTPOSSTAR: + case OP_NOTPOSSTARI: + case OP_PLUS: + case OP_PLUSI: + case OP_NOTPLUS: + case OP_NOTPLUSI: + case OP_MINPLUS: + case OP_MINPLUSI: + case OP_NOTMINPLUS: + case OP_NOTMINPLUSI: + case OP_POSPLUS: + case OP_POSPLUSI: + case OP_NOTPOSPLUS: + case OP_NOTPOSPLUSI: + case OP_QUERY: + case OP_QUERYI: + case OP_NOTQUERY: + case OP_NOTQUERYI: + case OP_MINQUERY: + case OP_MINQUERYI: + case OP_NOTMINQUERY: + case OP_NOTMINQUERYI: + case OP_POSQUERY: + case OP_POSQUERYI: + case OP_NOTPOSQUERY: + case OP_NOTPOSQUERYI: + if (HAS_EXTRALEN(code[-1])) code += GET_EXTRALEN(code[-1]); + break; + } +#else + (void)(utf); /* Keep compiler happy by referencing function argument */ +#endif + } + } +} + + + +/************************************************* +* Scan compiled branch for non-emptiness * +*************************************************/ + +/* This function scans through a branch of a compiled pattern to see whether it +can match the empty string or not. It is called from could_be_empty() +below and from compile_branch() when checking for an unlimited repeat of a +group that can match nothing. Note that first_significant_code() skips over +backward and negative forward assertions when its final argument is TRUE. If we +hit an unclosed bracket, we return "empty" - this means we've struck an inner +bracket whose current branch will already have been scanned. + +Arguments: + code points to start of search + endcode points to where to stop + utf TRUE if in UTF-8 / UTF-16 / UTF-32 mode + cd contains pointers to tables etc. + recurses chain of recurse_check to catch mutual recursion + +Returns: TRUE if what is matched could be empty +*/ + +typedef struct recurse_check { + struct recurse_check *prev; + const pcre_uchar *group; +} recurse_check; + +static BOOL +could_be_empty_branch(const pcre_uchar *code, const pcre_uchar *endcode, + BOOL utf, compile_data *cd, recurse_check *recurses) +{ +register pcre_uchar c; +recurse_check this_recurse; + +for (code = first_significant_code(code + PRIV(OP_lengths)[*code], TRUE); + code < endcode; + code = first_significant_code(code + PRIV(OP_lengths)[c], TRUE)) + { + const pcre_uchar *ccode; + + c = *code; + + /* Skip over forward assertions; the other assertions are skipped by + first_significant_code() with a TRUE final argument. */ + + if (c == OP_ASSERT) + { + do code += GET(code, 1); while (*code == OP_ALT); + c = *code; + continue; + } + + /* For a recursion/subroutine call, if its end has been reached, which + implies a backward reference subroutine call, we can scan it. If it's a + forward reference subroutine call, we can't. To detect forward reference + we have to scan up the list that is kept in the workspace. This function is + called only when doing the real compile, not during the pre-compile that + measures the size of the compiled pattern. */ + + if (c == OP_RECURSE) + { + const pcre_uchar *scode = cd->start_code + GET(code, 1); + const pcre_uchar *endgroup = scode; + BOOL empty_branch; + + /* Test for forward reference or uncompleted reference. This is disabled + when called to scan a completed pattern by setting cd->start_workspace to + NULL. */ + + if (cd->start_workspace != NULL) + { + const pcre_uchar *tcode; + for (tcode = cd->start_workspace; tcode < cd->hwm; tcode += LINK_SIZE) + if ((int)GET(tcode, 0) == (int)(code + 1 - cd->start_code)) return TRUE; + if (GET(scode, 1) == 0) return TRUE; /* Unclosed */ + } + + /* If the reference is to a completed group, we need to detect whether this + is a recursive call, as otherwise there will be an infinite loop. If it is + a recursion, just skip over it. Simple recursions are easily detected. For + mutual recursions we keep a chain on the stack. */ + + do endgroup += GET(endgroup, 1); while (*endgroup == OP_ALT); + if (code >= scode && code <= endgroup) continue; /* Simple recursion */ + else + { + recurse_check *r = recurses; + for (r = recurses; r != NULL; r = r->prev) + if (r->group == scode) break; + if (r != NULL) continue; /* Mutual recursion */ + } + + /* Completed reference; scan the referenced group, remembering it on the + stack chain to detect mutual recursions. */ + + empty_branch = FALSE; + this_recurse.prev = recurses; + this_recurse.group = scode; + + do + { + if (could_be_empty_branch(scode, endcode, utf, cd, &this_recurse)) + { + empty_branch = TRUE; + break; + } + scode += GET(scode, 1); + } + while (*scode == OP_ALT); + + if (!empty_branch) return FALSE; /* All branches are non-empty */ + continue; + } + + /* Groups with zero repeats can of course be empty; skip them. */ + + if (c == OP_BRAZERO || c == OP_BRAMINZERO || c == OP_SKIPZERO || + c == OP_BRAPOSZERO) + { + code += PRIV(OP_lengths)[c]; + do code += GET(code, 1); while (*code == OP_ALT); + c = *code; + continue; + } + + /* A nested group that is already marked as "could be empty" can just be + skipped. */ + + if (c == OP_SBRA || c == OP_SBRAPOS || + c == OP_SCBRA || c == OP_SCBRAPOS) + { + do code += GET(code, 1); while (*code == OP_ALT); + c = *code; + continue; + } + + /* For other groups, scan the branches. */ + + if (c == OP_BRA || c == OP_BRAPOS || + c == OP_CBRA || c == OP_CBRAPOS || + c == OP_ONCE || c == OP_ONCE_NC || + c == OP_COND) + { + BOOL empty_branch; + if (GET(code, 1) == 0) return TRUE; /* Hit unclosed bracket */ + + /* If a conditional group has only one branch, there is a second, implied, + empty branch, so just skip over the conditional, because it could be empty. + Otherwise, scan the individual branches of the group. */ + + if (c == OP_COND && code[GET(code, 1)] != OP_ALT) + code += GET(code, 1); + else + { + empty_branch = FALSE; + do + { + if (!empty_branch && could_be_empty_branch(code, endcode, utf, cd, NULL)) + empty_branch = TRUE; + code += GET(code, 1); + } + while (*code == OP_ALT); + if (!empty_branch) return FALSE; /* All branches are non-empty */ + } + + c = *code; + continue; + } + + /* Handle the other opcodes */ + + switch (c) + { + /* Check for quantifiers after a class. XCLASS is used for classes that + cannot be represented just by a bit map. This includes negated single + high-valued characters. The length in PRIV(OP_lengths)[] is zero; the + actual length is stored in the compiled code, so we must update "code" + here. */ + +#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 + case OP_XCLASS: + ccode = code += GET(code, 1); + goto CHECK_CLASS_REPEAT; +#endif + + case OP_CLASS: + case OP_NCLASS: + ccode = code + PRIV(OP_lengths)[OP_CLASS]; + +#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 + CHECK_CLASS_REPEAT: +#endif + + switch (*ccode) + { + case OP_CRSTAR: /* These could be empty; continue */ + case OP_CRMINSTAR: + case OP_CRQUERY: + case OP_CRMINQUERY: + case OP_CRPOSSTAR: + case OP_CRPOSQUERY: + break; + + default: /* Non-repeat => class must match */ + case OP_CRPLUS: /* These repeats aren't empty */ + case OP_CRMINPLUS: + case OP_CRPOSPLUS: + return FALSE; + + case OP_CRRANGE: + case OP_CRMINRANGE: + case OP_CRPOSRANGE: + if (GET2(ccode, 1) > 0) return FALSE; /* Minimum > 0 */ + break; + } + break; + + /* Opcodes that must match a character */ + + case OP_ANY: + case OP_ALLANY: + case OP_ANYBYTE: + + case OP_PROP: + case OP_NOTPROP: + case OP_ANYNL: + + case OP_NOT_HSPACE: + case OP_HSPACE: + case OP_NOT_VSPACE: + case OP_VSPACE: + case OP_EXTUNI: + + case OP_NOT_DIGIT: + case OP_DIGIT: + case OP_NOT_WHITESPACE: + case OP_WHITESPACE: + case OP_NOT_WORDCHAR: + case OP_WORDCHAR: + + case OP_CHAR: + case OP_CHARI: + case OP_NOT: + case OP_NOTI: + + case OP_PLUS: + case OP_PLUSI: + case OP_MINPLUS: + case OP_MINPLUSI: + + case OP_NOTPLUS: + case OP_NOTPLUSI: + case OP_NOTMINPLUS: + case OP_NOTMINPLUSI: + + case OP_POSPLUS: + case OP_POSPLUSI: + case OP_NOTPOSPLUS: + case OP_NOTPOSPLUSI: + + case OP_EXACT: + case OP_EXACTI: + case OP_NOTEXACT: + case OP_NOTEXACTI: + + case OP_TYPEPLUS: + case OP_TYPEMINPLUS: + case OP_TYPEPOSPLUS: + case OP_TYPEEXACT: + + return FALSE; + + /* These are going to continue, as they may be empty, but we have to + fudge the length for the \p and \P cases. */ + + case OP_TYPESTAR: + case OP_TYPEMINSTAR: + case OP_TYPEPOSSTAR: + case OP_TYPEQUERY: + case OP_TYPEMINQUERY: + case OP_TYPEPOSQUERY: + if (code[1] == OP_PROP || code[1] == OP_NOTPROP) code += 2; + break; + + /* Same for these */ + + case OP_TYPEUPTO: + case OP_TYPEMINUPTO: + case OP_TYPEPOSUPTO: + if (code[1 + IMM2_SIZE] == OP_PROP || code[1 + IMM2_SIZE] == OP_NOTPROP) + code += 2; + break; + + /* End of branch */ + + case OP_KET: + case OP_KETRMAX: + case OP_KETRMIN: + case OP_KETRPOS: + case OP_ALT: + return TRUE; + + /* In UTF-8 mode, STAR, MINSTAR, POSSTAR, QUERY, MINQUERY, POSQUERY, UPTO, + MINUPTO, and POSUPTO and their caseless and negative versions may be + followed by a multibyte character. */ + +#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 + case OP_STAR: + case OP_STARI: + case OP_NOTSTAR: + case OP_NOTSTARI: + + case OP_MINSTAR: + case OP_MINSTARI: + case OP_NOTMINSTAR: + case OP_NOTMINSTARI: + + case OP_POSSTAR: + case OP_POSSTARI: + case OP_NOTPOSSTAR: + case OP_NOTPOSSTARI: + + case OP_QUERY: + case OP_QUERYI: + case OP_NOTQUERY: + case OP_NOTQUERYI: + + case OP_MINQUERY: + case OP_MINQUERYI: + case OP_NOTMINQUERY: + case OP_NOTMINQUERYI: + + case OP_POSQUERY: + case OP_POSQUERYI: + case OP_NOTPOSQUERY: + case OP_NOTPOSQUERYI: + + if (utf && HAS_EXTRALEN(code[1])) code += GET_EXTRALEN(code[1]); + break; + + case OP_UPTO: + case OP_UPTOI: + case OP_NOTUPTO: + case OP_NOTUPTOI: + + case OP_MINUPTO: + case OP_MINUPTOI: + case OP_NOTMINUPTO: + case OP_NOTMINUPTOI: + + case OP_POSUPTO: + case OP_POSUPTOI: + case OP_NOTPOSUPTO: + case OP_NOTPOSUPTOI: + + if (utf && HAS_EXTRALEN(code[1 + IMM2_SIZE])) code += GET_EXTRALEN(code[1 + IMM2_SIZE]); + break; +#endif + + /* MARK, and PRUNE/SKIP/THEN with an argument must skip over the argument + string. */ + + case OP_MARK: + case OP_PRUNE_ARG: + case OP_SKIP_ARG: + case OP_THEN_ARG: + code += code[1]; + break; + + /* None of the remaining opcodes are required to match a character. */ + + default: + break; + } + } + +return TRUE; +} + + + +/************************************************* +* Scan compiled regex for non-emptiness * +*************************************************/ + +/* This function is called to check for left recursive calls. We want to check +the current branch of the current pattern to see if it could match the empty +string. If it could, we must look outwards for branches at other levels, +stopping when we pass beyond the bracket which is the subject of the recursion. +This function is called only during the real compile, not during the +pre-compile. + +Arguments: + code points to start of the recursion + endcode points to where to stop (current RECURSE item) + bcptr points to the chain of current (unclosed) branch starts + utf TRUE if in UTF-8 / UTF-16 / UTF-32 mode + cd pointers to tables etc + +Returns: TRUE if what is matched could be empty +*/ + +static BOOL +could_be_empty(const pcre_uchar *code, const pcre_uchar *endcode, + branch_chain *bcptr, BOOL utf, compile_data *cd) +{ +while (bcptr != NULL && bcptr->current_branch >= code) + { + if (!could_be_empty_branch(bcptr->current_branch, endcode, utf, cd, NULL)) + return FALSE; + bcptr = bcptr->outer; + } +return TRUE; +} + + + +/************************************************* +* Base opcode of repeated opcodes * +*************************************************/ + +/* Returns the base opcode for repeated single character type opcodes. If the +opcode is not a repeated character type, it returns with the original value. + +Arguments: c opcode +Returns: base opcode for the type +*/ + +static pcre_uchar +get_repeat_base(pcre_uchar c) +{ +return (c > OP_TYPEPOSUPTO)? c : + (c >= OP_TYPESTAR)? OP_TYPESTAR : + (c >= OP_NOTSTARI)? OP_NOTSTARI : + (c >= OP_NOTSTAR)? OP_NOTSTAR : + (c >= OP_STARI)? OP_STARI : + OP_STAR; +} + + + +#ifdef SUPPORT_UCP +/************************************************* +* Check a character and a property * +*************************************************/ + +/* This function is called by check_auto_possessive() when a property item +is adjacent to a fixed character. + +Arguments: + c the character + ptype the property type + pdata the data for the type + negated TRUE if it's a negated property (\P or \p{^) + +Returns: TRUE if auto-possessifying is OK +*/ + +static BOOL +check_char_prop(pcre_uint32 c, unsigned int ptype, unsigned int pdata, + BOOL negated) +{ +const pcre_uint32 *p; +const ucd_record *prop = GET_UCD(c); + +switch(ptype) + { + case PT_LAMP: + return (prop->chartype == ucp_Lu || + prop->chartype == ucp_Ll || + prop->chartype == ucp_Lt) == negated; + + case PT_GC: + return (pdata == PRIV(ucp_gentype)[prop->chartype]) == negated; + + case PT_PC: + return (pdata == prop->chartype) == negated; + + case PT_SC: + return (pdata == prop->script) == negated; + + /* These are specials */ + + case PT_ALNUM: + return (PRIV(ucp_gentype)[prop->chartype] == ucp_L || + PRIV(ucp_gentype)[prop->chartype] == ucp_N) == negated; + + /* Perl space used to exclude VT, but from Perl 5.18 it is included, which + means that Perl space and POSIX space are now identical. PCRE was changed + at release 8.34. */ + + case PT_SPACE: /* Perl space */ + case PT_PXSPACE: /* POSIX space */ + switch(c) + { + HSPACE_CASES: + VSPACE_CASES: + return negated; + + default: + return (PRIV(ucp_gentype)[prop->chartype] == ucp_Z) == negated; + } + break; /* Control never reaches here */ + + case PT_WORD: + return (PRIV(ucp_gentype)[prop->chartype] == ucp_L || + PRIV(ucp_gentype)[prop->chartype] == ucp_N || + c == CHAR_UNDERSCORE) == negated; + + case PT_CLIST: + p = PRIV(ucd_caseless_sets) + prop->caseset; + for (;;) + { + if (c < *p) return !negated; + if (c == *p++) return negated; + } + break; /* Control never reaches here */ + } + +return FALSE; +} +#endif /* SUPPORT_UCP */ + + + +/************************************************* +* Fill the character property list * +*************************************************/ + +/* Checks whether the code points to an opcode that can take part in auto- +possessification, and if so, fills a list with its properties. + +Arguments: + code points to start of expression + utf TRUE if in UTF-8 / UTF-16 / UTF-32 mode + fcc points to case-flipping table + list points to output list + list[0] will be filled with the opcode + list[1] will be non-zero if this opcode + can match an empty character string + list[2..7] depends on the opcode + +Returns: points to the start of the next opcode if *code is accepted + NULL if *code is not accepted +*/ + +static const pcre_uchar * +get_chr_property_list(const pcre_uchar *code, BOOL utf, + const pcre_uint8 *fcc, pcre_uint32 *list) +{ +pcre_uchar c = *code; +pcre_uchar base; +const pcre_uchar *end; +pcre_uint32 chr; + +#ifdef SUPPORT_UCP +pcre_uint32 *clist_dest; +const pcre_uint32 *clist_src; +#else +utf = utf; /* Suppress "unused parameter" compiler warning */ +#endif + +list[0] = c; +list[1] = FALSE; +code++; + +if (c >= OP_STAR && c <= OP_TYPEPOSUPTO) + { + base = get_repeat_base(c); + c -= (base - OP_STAR); + + if (c == OP_UPTO || c == OP_MINUPTO || c == OP_EXACT || c == OP_POSUPTO) + code += IMM2_SIZE; + + list[1] = (c != OP_PLUS && c != OP_MINPLUS && c != OP_EXACT && c != OP_POSPLUS); + + switch(base) + { + case OP_STAR: + list[0] = OP_CHAR; + break; + + case OP_STARI: + list[0] = OP_CHARI; + break; + + case OP_NOTSTAR: + list[0] = OP_NOT; + break; + + case OP_NOTSTARI: + list[0] = OP_NOTI; + break; + + case OP_TYPESTAR: + list[0] = *code; + code++; + break; + } + c = list[0]; + } + +switch(c) + { + case OP_NOT_DIGIT: + case OP_DIGIT: + case OP_NOT_WHITESPACE: + case OP_WHITESPACE: + case OP_NOT_WORDCHAR: + case OP_WORDCHAR: + case OP_ANY: + case OP_ALLANY: + case OP_ANYNL: + case OP_NOT_HSPACE: + case OP_HSPACE: + case OP_NOT_VSPACE: + case OP_VSPACE: + case OP_EXTUNI: + case OP_EODN: + case OP_EOD: + case OP_DOLL: + case OP_DOLLM: + return code; + + case OP_CHAR: + case OP_NOT: + GETCHARINCTEST(chr, code); + list[2] = chr; + list[3] = NOTACHAR; + return code; + + case OP_CHARI: + case OP_NOTI: + list[0] = (c == OP_CHARI) ? OP_CHAR : OP_NOT; + GETCHARINCTEST(chr, code); + list[2] = chr; + +#ifdef SUPPORT_UCP + if (chr < 128 || (chr < 256 && !utf)) + list[3] = fcc[chr]; + else + list[3] = UCD_OTHERCASE(chr); +#elif defined SUPPORT_UTF || !defined COMPILE_PCRE8 + list[3] = (chr < 256) ? fcc[chr] : chr; +#else + list[3] = fcc[chr]; +#endif + + /* The othercase might be the same value. */ + + if (chr == list[3]) + list[3] = NOTACHAR; + else + list[4] = NOTACHAR; + return code; + +#ifdef SUPPORT_UCP + case OP_PROP: + case OP_NOTPROP: + if (code[0] != PT_CLIST) + { + list[2] = code[0]; + list[3] = code[1]; + return code + 2; + } + + /* Convert only if we have enough space. */ + + clist_src = PRIV(ucd_caseless_sets) + code[1]; + clist_dest = list + 2; + code += 2; + + do { + if (clist_dest >= list + 8) + { + /* Early return if there is not enough space. This should never + happen, since all clists are shorter than 5 character now. */ + list[2] = code[0]; + list[3] = code[1]; + return code; + } + *clist_dest++ = *clist_src; + } + while(*clist_src++ != NOTACHAR); + + /* All characters are stored. The terminating NOTACHAR + is copied form the clist itself. */ + + list[0] = (c == OP_PROP) ? OP_CHAR : OP_NOT; + return code; +#endif + + case OP_NCLASS: + case OP_CLASS: +#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 + case OP_XCLASS: + if (c == OP_XCLASS) + end = code + GET(code, 0) - 1; + else +#endif + end = code + 32 / sizeof(pcre_uchar); + + switch(*end) + { + case OP_CRSTAR: + case OP_CRMINSTAR: + case OP_CRQUERY: + case OP_CRMINQUERY: + case OP_CRPOSSTAR: + case OP_CRPOSQUERY: + list[1] = TRUE; + end++; + break; + + case OP_CRPLUS: + case OP_CRMINPLUS: + case OP_CRPOSPLUS: + end++; + break; + + case OP_CRRANGE: + case OP_CRMINRANGE: + case OP_CRPOSRANGE: + list[1] = (GET2(end, 1) == 0); + end += 1 + 2 * IMM2_SIZE; + break; + } + list[2] = (pcre_uint32)(end - code); + return end; + } +return NULL; /* Opcode not accepted */ +} + + + +/************************************************* +* Scan further character sets for match * +*************************************************/ + +/* Checks whether the base and the current opcode have a common character, in +which case the base cannot be possessified. + +Arguments: + code points to the byte code + utf TRUE in UTF-8 / UTF-16 / UTF-32 mode + cd static compile data + base_list the data list of the base opcode + +Returns: TRUE if the auto-possessification is possible +*/ + +static BOOL +compare_opcodes(const pcre_uchar *code, BOOL utf, const compile_data *cd, + const pcre_uint32 *base_list, const pcre_uchar *base_end) +{ +pcre_uchar c; +pcre_uint32 list[8]; +const pcre_uint32 *chr_ptr; +const pcre_uint32 *ochr_ptr; +const pcre_uint32 *list_ptr; +const pcre_uchar *next_code; +#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 +const pcre_uchar *xclass_flags; +#endif +const pcre_uint8 *class_bitset; +const pcre_uint8 *set1, *set2, *set_end; +pcre_uint32 chr; +BOOL accepted, invert_bits; +BOOL entered_a_group = FALSE; + +/* Note: the base_list[1] contains whether the current opcode has greedy +(represented by a non-zero value) quantifier. This is a different from +other character type lists, which stores here that the character iterator +matches to an empty string (also represented by a non-zero value). */ + +for(;;) + { + /* All operations move the code pointer forward. + Therefore infinite recursions are not possible. */ + + c = *code; + + /* Skip over callouts */ + + if (c == OP_CALLOUT) + { + code += PRIV(OP_lengths)[c]; + continue; + } + + if (c == OP_ALT) + { + do code += GET(code, 1); while (*code == OP_ALT); + c = *code; + } + + switch(c) + { + case OP_END: + case OP_KETRPOS: + /* TRUE only in greedy case. The non-greedy case could be replaced by + an OP_EXACT, but it is probably not worth it. (And note that OP_EXACT + uses more memory, which we cannot get at this stage.) */ + + return base_list[1] != 0; + + case OP_KET: + /* If the bracket is capturing, and referenced by an OP_RECURSE, or + it is an atomic sub-pattern (assert, once, etc.) the non-greedy case + cannot be converted to a possessive form. */ + + if (base_list[1] == 0) return FALSE; + + switch(*(code - GET(code, 1))) + { + case OP_ASSERT: + case OP_ASSERT_NOT: + case OP_ASSERTBACK: + case OP_ASSERTBACK_NOT: + case OP_ONCE: + case OP_ONCE_NC: + /* Atomic sub-patterns and assertions can always auto-possessify their + last iterator. However, if the group was entered as a result of checking + a previous iterator, this is not possible. */ + + return !entered_a_group; + } + + code += PRIV(OP_lengths)[c]; + continue; + + case OP_ONCE: + case OP_ONCE_NC: + case OP_BRA: + case OP_CBRA: + next_code = code + GET(code, 1); + code += PRIV(OP_lengths)[c]; + + while (*next_code == OP_ALT) + { + if (!compare_opcodes(code, utf, cd, base_list, base_end)) return FALSE; + code = next_code + 1 + LINK_SIZE; + next_code += GET(next_code, 1); + } + + entered_a_group = TRUE; + continue; + + case OP_BRAZERO: + case OP_BRAMINZERO: + + next_code = code + 1; + if (*next_code != OP_BRA && *next_code != OP_CBRA + && *next_code != OP_ONCE && *next_code != OP_ONCE_NC) return FALSE; + + do next_code += GET(next_code, 1); while (*next_code == OP_ALT); + + /* The bracket content will be checked by the + OP_BRA/OP_CBRA case above. */ + next_code += 1 + LINK_SIZE; + if (!compare_opcodes(next_code, utf, cd, base_list, base_end)) + return FALSE; + + code += PRIV(OP_lengths)[c]; + continue; + + default: + break; + } + + /* Check for a supported opcode, and load its properties. */ + + code = get_chr_property_list(code, utf, cd->fcc, list); + if (code == NULL) return FALSE; /* Unsupported */ + + /* If either opcode is a small character list, set pointers for comparing + characters from that list with another list, or with a property. */ + + if (base_list[0] == OP_CHAR) + { + chr_ptr = base_list + 2; + list_ptr = list; + } + else if (list[0] == OP_CHAR) + { + chr_ptr = list + 2; + list_ptr = base_list; + } + + /* Character bitsets can also be compared to certain opcodes. */ + + else if (base_list[0] == OP_CLASS || list[0] == OP_CLASS +#ifdef COMPILE_PCRE8 + /* In 8 bit, non-UTF mode, OP_CLASS and OP_NCLASS are the same. */ + || (!utf && (base_list[0] == OP_NCLASS || list[0] == OP_NCLASS)) +#endif + ) + { +#ifdef COMPILE_PCRE8 + if (base_list[0] == OP_CLASS || (!utf && base_list[0] == OP_NCLASS)) +#else + if (base_list[0] == OP_CLASS) +#endif + { + set1 = (pcre_uint8 *)(base_end - base_list[2]); + list_ptr = list; + } + else + { + set1 = (pcre_uint8 *)(code - list[2]); + list_ptr = base_list; + } + + invert_bits = FALSE; + switch(list_ptr[0]) + { + case OP_CLASS: + case OP_NCLASS: + set2 = (pcre_uint8 *) + ((list_ptr == list ? code : base_end) - list_ptr[2]); + break; + +#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 + case OP_XCLASS: + xclass_flags = (list_ptr == list ? code : base_end) - list_ptr[2] + LINK_SIZE; + if ((*xclass_flags & XCL_HASPROP) != 0) return FALSE; + if ((*xclass_flags & XCL_MAP) == 0) + { + /* No bits are set for characters < 256. */ + if (list[1] == 0) return TRUE; + /* Might be an empty repeat. */ + continue; + } + set2 = (pcre_uint8 *)(xclass_flags + 1); + break; +#endif + + case OP_NOT_DIGIT: + invert_bits = TRUE; + /* Fall through */ + case OP_DIGIT: + set2 = (pcre_uint8 *)(cd->cbits + cbit_digit); + break; + + case OP_NOT_WHITESPACE: + invert_bits = TRUE; + /* Fall through */ + case OP_WHITESPACE: + set2 = (pcre_uint8 *)(cd->cbits + cbit_space); + break; + + case OP_NOT_WORDCHAR: + invert_bits = TRUE; + /* Fall through */ + case OP_WORDCHAR: + set2 = (pcre_uint8 *)(cd->cbits + cbit_word); + break; + + default: + return FALSE; + } + + /* Because the sets are unaligned, we need + to perform byte comparison here. */ + set_end = set1 + 32; + if (invert_bits) + { + do + { + if ((*set1++ & ~(*set2++)) != 0) return FALSE; + } + while (set1 < set_end); + } + else + { + do + { + if ((*set1++ & *set2++) != 0) return FALSE; + } + while (set1 < set_end); + } + + if (list[1] == 0) return TRUE; + /* Might be an empty repeat. */ + continue; + } + + /* Some property combinations also acceptable. Unicode property opcodes are + processed specially; the rest can be handled with a lookup table. */ + + else + { + pcre_uint32 leftop, rightop; + + leftop = base_list[0]; + rightop = list[0]; + +#ifdef SUPPORT_UCP + accepted = FALSE; /* Always set in non-unicode case. */ + if (leftop == OP_PROP || leftop == OP_NOTPROP) + { + if (rightop == OP_EOD) + accepted = TRUE; + else if (rightop == OP_PROP || rightop == OP_NOTPROP) + { + int n; + const pcre_uint8 *p; + BOOL same = leftop == rightop; + BOOL lisprop = leftop == OP_PROP; + BOOL risprop = rightop == OP_PROP; + BOOL bothprop = lisprop && risprop; + + /* There's a table that specifies how each combination is to be + processed: + 0 Always return FALSE (never auto-possessify) + 1 Character groups are distinct (possessify if both are OP_PROP) + 2 Check character categories in the same group (general or particular) + 3 Return TRUE if the two opcodes are not the same + ... see comments below + */ + + n = propposstab[base_list[2]][list[2]]; + switch(n) + { + case 0: break; + case 1: accepted = bothprop; break; + case 2: accepted = (base_list[3] == list[3]) != same; break; + case 3: accepted = !same; break; + + case 4: /* Left general category, right particular category */ + accepted = risprop && catposstab[base_list[3]][list[3]] == same; + break; + + case 5: /* Right general category, left particular category */ + accepted = lisprop && catposstab[list[3]][base_list[3]] == same; + break; + + /* This code is logically tricky. Think hard before fiddling with it. + The posspropstab table has four entries per row. Each row relates to + one of PCRE's special properties such as ALNUM or SPACE or WORD. + Only WORD actually needs all four entries, but using repeats for the + others means they can all use the same code below. + + The first two entries in each row are Unicode general categories, and + apply always, because all the characters they include are part of the + PCRE character set. The third and fourth entries are a general and a + particular category, respectively, that include one or more relevant + characters. One or the other is used, depending on whether the check + is for a general or a particular category. However, in both cases the + category contains more characters than the specials that are defined + for the property being tested against. Therefore, it cannot be used + in a NOTPROP case. + + Example: the row for WORD contains ucp_L, ucp_N, ucp_P, ucp_Po. + Underscore is covered by ucp_P or ucp_Po. */ + + case 6: /* Left alphanum vs right general category */ + case 7: /* Left space vs right general category */ + case 8: /* Left word vs right general category */ + p = posspropstab[n-6]; + accepted = risprop && lisprop == + (list[3] != p[0] && + list[3] != p[1] && + (list[3] != p[2] || !lisprop)); + break; + + case 9: /* Right alphanum vs left general category */ + case 10: /* Right space vs left general category */ + case 11: /* Right word vs left general category */ + p = posspropstab[n-9]; + accepted = lisprop && risprop == + (base_list[3] != p[0] && + base_list[3] != p[1] && + (base_list[3] != p[2] || !risprop)); + break; + + case 12: /* Left alphanum vs right particular category */ + case 13: /* Left space vs right particular category */ + case 14: /* Left word vs right particular category */ + p = posspropstab[n-12]; + accepted = risprop && lisprop == + (catposstab[p[0]][list[3]] && + catposstab[p[1]][list[3]] && + (list[3] != p[3] || !lisprop)); + break; + + case 15: /* Right alphanum vs left particular category */ + case 16: /* Right space vs left particular category */ + case 17: /* Right word vs left particular category */ + p = posspropstab[n-15]; + accepted = lisprop && risprop == + (catposstab[p[0]][base_list[3]] && + catposstab[p[1]][base_list[3]] && + (base_list[3] != p[3] || !risprop)); + break; + } + } + } + + else +#endif /* SUPPORT_UCP */ + + accepted = leftop >= FIRST_AUTOTAB_OP && leftop <= LAST_AUTOTAB_LEFT_OP && + rightop >= FIRST_AUTOTAB_OP && rightop <= LAST_AUTOTAB_RIGHT_OP && + autoposstab[leftop - FIRST_AUTOTAB_OP][rightop - FIRST_AUTOTAB_OP]; + + if (!accepted) return FALSE; + + if (list[1] == 0) return TRUE; + /* Might be an empty repeat. */ + continue; + } + + /* Control reaches here only if one of the items is a small character list. + All characters are checked against the other side. */ + + do + { + chr = *chr_ptr; + + switch(list_ptr[0]) + { + case OP_CHAR: + ochr_ptr = list_ptr + 2; + do + { + if (chr == *ochr_ptr) return FALSE; + ochr_ptr++; + } + while(*ochr_ptr != NOTACHAR); + break; + + case OP_NOT: + ochr_ptr = list_ptr + 2; + do + { + if (chr == *ochr_ptr) + break; + ochr_ptr++; + } + while(*ochr_ptr != NOTACHAR); + if (*ochr_ptr == NOTACHAR) return FALSE; /* Not found */ + break; + + /* Note that OP_DIGIT etc. are generated only when PCRE_UCP is *not* + set. When it is set, \d etc. are converted into OP_(NOT_)PROP codes. */ + + case OP_DIGIT: + if (chr < 256 && (cd->ctypes[chr] & ctype_digit) != 0) return FALSE; + break; + + case OP_NOT_DIGIT: + if (chr > 255 || (cd->ctypes[chr] & ctype_digit) == 0) return FALSE; + break; + + case OP_WHITESPACE: + if (chr < 256 && (cd->ctypes[chr] & ctype_space) != 0) return FALSE; + break; + + case OP_NOT_WHITESPACE: + if (chr > 255 || (cd->ctypes[chr] & ctype_space) == 0) return FALSE; + break; + + case OP_WORDCHAR: + if (chr < 255 && (cd->ctypes[chr] & ctype_word) != 0) return FALSE; + break; + + case OP_NOT_WORDCHAR: + if (chr > 255 || (cd->ctypes[chr] & ctype_word) == 0) return FALSE; + break; + + case OP_HSPACE: + switch(chr) + { + HSPACE_CASES: return FALSE; + default: break; + } + break; + + case OP_NOT_HSPACE: + switch(chr) + { + HSPACE_CASES: break; + default: return FALSE; + } + break; + + case OP_ANYNL: + case OP_VSPACE: + switch(chr) + { + VSPACE_CASES: return FALSE; + default: break; + } + break; + + case OP_NOT_VSPACE: + switch(chr) + { + VSPACE_CASES: break; + default: return FALSE; + } + break; + + case OP_DOLL: + case OP_EODN: + switch (chr) + { + case CHAR_CR: + case CHAR_LF: + case CHAR_VT: + case CHAR_FF: + case CHAR_NEL: +#ifndef EBCDIC + case 0x2028: + case 0x2029: +#endif /* Not EBCDIC */ + return FALSE; + } + break; + + case OP_EOD: /* Can always possessify before \z */ + break; + +#ifdef SUPPORT_UCP + case OP_PROP: + case OP_NOTPROP: + if (!check_char_prop(chr, list_ptr[2], list_ptr[3], + list_ptr[0] == OP_NOTPROP)) + return FALSE; + break; +#endif + + case OP_NCLASS: + if (chr > 255) return FALSE; + /* Fall through */ + + case OP_CLASS: + if (chr > 255) break; + class_bitset = (pcre_uint8 *) + ((list_ptr == list ? code : base_end) - list_ptr[2]); + if ((class_bitset[chr >> 3] & (1 << (chr & 7))) != 0) return FALSE; + break; + +#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 + case OP_XCLASS: + if (PRIV(xclass)(chr, (list_ptr == list ? code : base_end) - + list_ptr[2] + LINK_SIZE, utf)) return FALSE; + break; +#endif + + default: + return FALSE; + } + + chr_ptr++; + } + while(*chr_ptr != NOTACHAR); + + /* At least one character must be matched from this opcode. */ + + if (list[1] == 0) return TRUE; + } + +/* Control never reaches here. There used to be a fail-save return FALSE; here, +but some compilers complain about an unreachable statement. */ + +} + + + +/************************************************* +* Scan compiled regex for auto-possession * +*************************************************/ + +/* Replaces single character iterations with their possessive alternatives +if appropriate. This function modifies the compiled opcode! + +Arguments: + code points to start of the byte code + utf TRUE in UTF-8 / UTF-16 / UTF-32 mode + cd static compile data + +Returns: nothing +*/ + +static void +auto_possessify(pcre_uchar *code, BOOL utf, const compile_data *cd) +{ +register pcre_uchar c; +const pcre_uchar *end; +pcre_uchar *repeat_opcode; +pcre_uint32 list[8]; + +for (;;) + { + c = *code; + + if (c >= OP_STAR && c <= OP_TYPEPOSUPTO) + { + c -= get_repeat_base(c) - OP_STAR; + end = (c <= OP_MINUPTO) ? + get_chr_property_list(code, utf, cd->fcc, list) : NULL; + list[1] = c == OP_STAR || c == OP_PLUS || c == OP_QUERY || c == OP_UPTO; + + if (end != NULL && compare_opcodes(end, utf, cd, list, end)) + { + switch(c) + { + case OP_STAR: + *code += OP_POSSTAR - OP_STAR; + break; + + case OP_MINSTAR: + *code += OP_POSSTAR - OP_MINSTAR; + break; + + case OP_PLUS: + *code += OP_POSPLUS - OP_PLUS; + break; + + case OP_MINPLUS: + *code += OP_POSPLUS - OP_MINPLUS; + break; + + case OP_QUERY: + *code += OP_POSQUERY - OP_QUERY; + break; + + case OP_MINQUERY: + *code += OP_POSQUERY - OP_MINQUERY; + break; + + case OP_UPTO: + *code += OP_POSUPTO - OP_UPTO; + break; + + case OP_MINUPTO: + *code += OP_POSUPTO - OP_MINUPTO; + break; + } + } + c = *code; + } + else if (c == OP_CLASS || c == OP_NCLASS || c == OP_XCLASS) + { +#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 + if (c == OP_XCLASS) + repeat_opcode = code + GET(code, 1); + else +#endif + repeat_opcode = code + 1 + (32 / sizeof(pcre_uchar)); + + c = *repeat_opcode; + if (c >= OP_CRSTAR && c <= OP_CRMINRANGE) + { + /* end must not be NULL. */ + end = get_chr_property_list(code, utf, cd->fcc, list); + + list[1] = (c & 1) == 0; + + if (compare_opcodes(end, utf, cd, list, end)) + { + switch (c) + { + case OP_CRSTAR: + case OP_CRMINSTAR: + *repeat_opcode = OP_CRPOSSTAR; + break; + + case OP_CRPLUS: + case OP_CRMINPLUS: + *repeat_opcode = OP_CRPOSPLUS; + break; + + case OP_CRQUERY: + case OP_CRMINQUERY: + *repeat_opcode = OP_CRPOSQUERY; + break; + + case OP_CRRANGE: + case OP_CRMINRANGE: + *repeat_opcode = OP_CRPOSRANGE; + break; + } + } + } + c = *code; + } + + switch(c) + { + case OP_END: + return; + + case OP_TYPESTAR: + case OP_TYPEMINSTAR: + case OP_TYPEPLUS: + case OP_TYPEMINPLUS: + case OP_TYPEQUERY: + case OP_TYPEMINQUERY: + case OP_TYPEPOSSTAR: + case OP_TYPEPOSPLUS: + case OP_TYPEPOSQUERY: + if (code[1] == OP_PROP || code[1] == OP_NOTPROP) code += 2; + break; + + case OP_TYPEUPTO: + case OP_TYPEMINUPTO: + case OP_TYPEEXACT: + case OP_TYPEPOSUPTO: + if (code[1 + IMM2_SIZE] == OP_PROP || code[1 + IMM2_SIZE] == OP_NOTPROP) + code += 2; + break; + +#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 + case OP_XCLASS: + code += GET(code, 1); + break; +#endif + + case OP_MARK: + case OP_PRUNE_ARG: + case OP_SKIP_ARG: + case OP_THEN_ARG: + code += code[1]; + break; + } + + /* Add in the fixed length from the table */ + + code += PRIV(OP_lengths)[c]; + + /* In UTF-8 mode, opcodes that are followed by a character may be followed by + a multi-byte character. The length in the table is a minimum, so we have to + arrange to skip the extra bytes. */ + +#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 + if (utf) switch(c) + { + case OP_CHAR: + case OP_CHARI: + case OP_NOT: + case OP_NOTI: + case OP_STAR: + case OP_MINSTAR: + case OP_PLUS: + case OP_MINPLUS: + case OP_QUERY: + case OP_MINQUERY: + case OP_UPTO: + case OP_MINUPTO: + case OP_EXACT: + case OP_POSSTAR: + case OP_POSPLUS: + case OP_POSQUERY: + case OP_POSUPTO: + case OP_STARI: + case OP_MINSTARI: + case OP_PLUSI: + case OP_MINPLUSI: + case OP_QUERYI: + case OP_MINQUERYI: + case OP_UPTOI: + case OP_MINUPTOI: + case OP_EXACTI: + case OP_POSSTARI: + case OP_POSPLUSI: + case OP_POSQUERYI: + case OP_POSUPTOI: + case OP_NOTSTAR: + case OP_NOTMINSTAR: + case OP_NOTPLUS: + case OP_NOTMINPLUS: + case OP_NOTQUERY: + case OP_NOTMINQUERY: + case OP_NOTUPTO: + case OP_NOTMINUPTO: + case OP_NOTEXACT: + case OP_NOTPOSSTAR: + case OP_NOTPOSPLUS: + case OP_NOTPOSQUERY: + case OP_NOTPOSUPTO: + case OP_NOTSTARI: + case OP_NOTMINSTARI: + case OP_NOTPLUSI: + case OP_NOTMINPLUSI: + case OP_NOTQUERYI: + case OP_NOTMINQUERYI: + case OP_NOTUPTOI: + case OP_NOTMINUPTOI: + case OP_NOTEXACTI: + case OP_NOTPOSSTARI: + case OP_NOTPOSPLUSI: + case OP_NOTPOSQUERYI: + case OP_NOTPOSUPTOI: + if (HAS_EXTRALEN(code[-1])) code += GET_EXTRALEN(code[-1]); + break; + } +#else + (void)(utf); /* Keep compiler happy by referencing function argument */ +#endif + } +} + + + +/************************************************* +* Check for POSIX class syntax * +*************************************************/ + +/* This function is called when the sequence "[:" or "[." or "[=" is +encountered in a character class. It checks whether this is followed by a +sequence of characters terminated by a matching ":]" or ".]" or "=]". If we +reach an unescaped ']' without the special preceding character, return FALSE. + +Originally, this function only recognized a sequence of letters between the +terminators, but it seems that Perl recognizes any sequence of characters, +though of course unknown POSIX names are subsequently rejected. Perl gives an +"Unknown POSIX class" error for [:f\oo:] for example, where previously PCRE +didn't consider this to be a POSIX class. Likewise for [:1234:]. + +The problem in trying to be exactly like Perl is in the handling of escapes. We +have to be sure that [abc[:x\]pqr] is *not* treated as containing a POSIX +class, but [abc[:x\]pqr:]] is (so that an error can be generated). The code +below handles the special case of \], but does not try to do any other escape +processing. This makes it different from Perl for cases such as [:l\ower:] +where Perl recognizes it as the POSIX class "lower" but PCRE does not recognize +"l\ower". This is a lesser evil than not diagnosing bad classes when Perl does, +I think. + +A user pointed out that PCRE was rejecting [:a[:digit:]] whereas Perl was not. +It seems that the appearance of a nested POSIX class supersedes an apparent +external class. For example, [:a[:digit:]b:] matches "a", "b", ":", or +a digit. + +In Perl, unescaped square brackets may also appear as part of class names. For +example, [:a[:abc]b:] gives unknown POSIX class "[:abc]b:]". However, for +[:a[:abc]b][b:] it gives unknown POSIX class "[:abc]b][b:]", which does not +seem right at all. PCRE does not allow closing square brackets in POSIX class +names. + +Arguments: + ptr pointer to the initial [ + endptr where to return the end pointer + +Returns: TRUE or FALSE +*/ + +static BOOL +check_posix_syntax(const pcre_uchar *ptr, const pcre_uchar **endptr) +{ +pcre_uchar terminator; /* Don't combine these lines; the Solaris cc */ +terminator = *(++ptr); /* compiler warns about "non-constant" initializer. */ +for (++ptr; *ptr != CHAR_NULL; ptr++) + { + if (*ptr == CHAR_BACKSLASH && ptr[1] == CHAR_RIGHT_SQUARE_BRACKET) + ptr++; + else if (*ptr == CHAR_RIGHT_SQUARE_BRACKET) return FALSE; + else + { + if (*ptr == terminator && ptr[1] == CHAR_RIGHT_SQUARE_BRACKET) + { + *endptr = ptr; + return TRUE; + } + if (*ptr == CHAR_LEFT_SQUARE_BRACKET && + (ptr[1] == CHAR_COLON || ptr[1] == CHAR_DOT || + ptr[1] == CHAR_EQUALS_SIGN) && + check_posix_syntax(ptr, endptr)) + return FALSE; + } + } +return FALSE; +} + + + + +/************************************************* +* Check POSIX class name * +*************************************************/ + +/* This function is called to check the name given in a POSIX-style class entry +such as [:alnum:]. + +Arguments: + ptr points to the first letter + len the length of the name + +Returns: a value representing the name, or -1 if unknown +*/ + +static int +check_posix_name(const pcre_uchar *ptr, int len) +{ +const char *pn = posix_names; +register int yield = 0; +while (posix_name_lengths[yield] != 0) + { + if (len == posix_name_lengths[yield] && + STRNCMP_UC_C8(ptr, pn, (unsigned int)len) == 0) return yield; + pn += posix_name_lengths[yield] + 1; + yield++; + } +return -1; +} + + +/************************************************* +* Adjust OP_RECURSE items in repeated group * +*************************************************/ + +/* OP_RECURSE items contain an offset from the start of the regex to the group +that is referenced. This means that groups can be replicated for fixed +repetition simply by copying (because the recursion is allowed to refer to +earlier groups that are outside the current group). However, when a group is +optional (i.e. the minimum quantifier is zero), OP_BRAZERO or OP_SKIPZERO is +inserted before it, after it has been compiled. This means that any OP_RECURSE +items within it that refer to the group itself or any contained groups have to +have their offsets adjusted. That one of the jobs of this function. Before it +is called, the partially compiled regex must be temporarily terminated with +OP_END. + +This function has been extended with the possibility of forward references for +recursions and subroutine calls. It must also check the list of such references +for the group we are dealing with. If it finds that one of the recursions in +the current group is on this list, it adjusts the offset in the list, not the +value in the reference (which is a group number). + +Arguments: + group points to the start of the group + adjust the amount by which the group is to be moved + utf TRUE in UTF-8 / UTF-16 / UTF-32 mode + cd contains pointers to tables etc. + save_hwm the hwm forward reference pointer at the start of the group + +Returns: nothing +*/ + +static void +adjust_recurse(pcre_uchar *group, int adjust, BOOL utf, compile_data *cd, + pcre_uchar *save_hwm) +{ +pcre_uchar *ptr = group; + +while ((ptr = (pcre_uchar *)find_recurse(ptr, utf)) != NULL) + { + int offset; + pcre_uchar *hc; + + /* See if this recursion is on the forward reference list. If so, adjust the + reference. */ + + for (hc = save_hwm; hc < cd->hwm; hc += LINK_SIZE) + { + offset = (int)GET(hc, 0); + if (cd->start_code + offset == ptr + 1) + { + PUT(hc, 0, offset + adjust); + break; + } + } + + /* Otherwise, adjust the recursion offset if it's after the start of this + group. */ + + if (hc >= cd->hwm) + { + offset = (int)GET(ptr, 1); + if (cd->start_code + offset >= group) PUT(ptr, 1, offset + adjust); + } + + ptr += 1 + LINK_SIZE; + } +} + + + +/************************************************* +* Insert an automatic callout point * +*************************************************/ + +/* This function is called when the PCRE_AUTO_CALLOUT option is set, to insert +callout points before each pattern item. + +Arguments: + code current code pointer + ptr current pattern pointer + cd pointers to tables etc + +Returns: new code pointer +*/ + +static pcre_uchar * +auto_callout(pcre_uchar *code, const pcre_uchar *ptr, compile_data *cd) +{ +*code++ = OP_CALLOUT; +*code++ = 255; +PUT(code, 0, (int)(ptr - cd->start_pattern)); /* Pattern offset */ +PUT(code, LINK_SIZE, 0); /* Default length */ +return code + 2 * LINK_SIZE; +} + + + +/************************************************* +* Complete a callout item * +*************************************************/ + +/* A callout item contains the length of the next item in the pattern, which +we can't fill in till after we have reached the relevant point. This is used +for both automatic and manual callouts. + +Arguments: + previous_callout points to previous callout item + ptr current pattern pointer + cd pointers to tables etc + +Returns: nothing +*/ + +static void +complete_callout(pcre_uchar *previous_callout, const pcre_uchar *ptr, compile_data *cd) +{ +int length = (int)(ptr - cd->start_pattern - GET(previous_callout, 2)); +PUT(previous_callout, 2 + LINK_SIZE, length); +} + + + +#ifdef SUPPORT_UCP +/************************************************* +* Get othercase range * +*************************************************/ + +/* This function is passed the start and end of a class range, in UTF-8 mode +with UCP support. It searches up the characters, looking for ranges of +characters in the "other" case. Each call returns the next one, updating the +start address. A character with multiple other cases is returned on its own +with a special return value. + +Arguments: + cptr points to starting character value; updated + d end value + ocptr where to put start of othercase range + odptr where to put end of othercase range + +Yield: -1 when no more + 0 when a range is returned + >0 the CASESET offset for char with multiple other cases + in this case, ocptr contains the original +*/ + +static int +get_othercase_range(pcre_uint32 *cptr, pcre_uint32 d, pcre_uint32 *ocptr, + pcre_uint32 *odptr) +{ +pcre_uint32 c, othercase, next; +unsigned int co; + +/* Find the first character that has an other case. If it has multiple other +cases, return its case offset value. */ + +for (c = *cptr; c <= d; c++) + { + if ((co = UCD_CASESET(c)) != 0) + { + *ocptr = c++; /* Character that has the set */ + *cptr = c; /* Rest of input range */ + return (int)co; + } + if ((othercase = UCD_OTHERCASE(c)) != c) break; + } + +if (c > d) return -1; /* Reached end of range */ + +/* Found a character that has a single other case. Search for the end of the +range, which is either the end of the input range, or a character that has zero +or more than one other cases. */ + +*ocptr = othercase; +next = othercase + 1; + +for (++c; c <= d; c++) + { + if ((co = UCD_CASESET(c)) != 0 || UCD_OTHERCASE(c) != next) break; + next++; + } + +*odptr = next - 1; /* End of othercase range */ +*cptr = c; /* Rest of input range */ +return 0; +} +#endif /* SUPPORT_UCP */ + + + +/************************************************* +* Add a character or range to a class * +*************************************************/ + +/* This function packages up the logic of adding a character or range of +characters to a class. The character values in the arguments will be within the +valid values for the current mode (8-bit, 16-bit, UTF, etc). This function is +mutually recursive with the function immediately below. + +Arguments: + classbits the bit map for characters < 256 + uchardptr points to the pointer for extra data + options the options word + cd contains pointers to tables etc. + start start of range character + end end of range character + +Returns: the number of < 256 characters added + the pointer to extra data is updated +*/ + +static int +add_to_class(pcre_uint8 *classbits, pcre_uchar **uchardptr, int options, + compile_data *cd, pcre_uint32 start, pcre_uint32 end) +{ +pcre_uint32 c; +pcre_uint32 classbits_end = (end <= 0xff ? end : 0xff); +int n8 = 0; + +/* If caseless matching is required, scan the range and process alternate +cases. In Unicode, there are 8-bit characters that have alternate cases that +are greater than 255 and vice-versa. Sometimes we can just extend the original +range. */ + +if ((options & PCRE_CASELESS) != 0) + { +#ifdef SUPPORT_UCP + if ((options & PCRE_UTF8) != 0) + { + int rc; + pcre_uint32 oc, od; + + options &= ~PCRE_CASELESS; /* Remove for recursive calls */ + c = start; + + while ((rc = get_othercase_range(&c, end, &oc, &od)) >= 0) + { + /* Handle a single character that has more than one other case. */ + + if (rc > 0) n8 += add_list_to_class(classbits, uchardptr, options, cd, + PRIV(ucd_caseless_sets) + rc, oc); + + /* Do nothing if the other case range is within the original range. */ + + else if (oc >= start && od <= end) continue; + + /* Extend the original range if there is overlap, noting that if oc < c, we + can't have od > end because a subrange is always shorter than the basic + range. Otherwise, use a recursive call to add the additional range. */ + + else if (oc < start && od >= start - 1) start = oc; /* Extend downwards */ + else if (od > end && oc <= end + 1) end = od; /* Extend upwards */ + else n8 += add_to_class(classbits, uchardptr, options, cd, oc, od); + } + } + else +#endif /* SUPPORT_UCP */ + + /* Not UTF-mode, or no UCP */ + + for (c = start; c <= classbits_end; c++) + { + SETBIT(classbits, cd->fcc[c]); + n8++; + } + } + +/* Now handle the original range. Adjust the final value according to the bit +length - this means that the same lists of (e.g.) horizontal spaces can be used +in all cases. */ + +#if defined COMPILE_PCRE8 +#ifdef SUPPORT_UTF + if ((options & PCRE_UTF8) == 0) +#endif + if (end > 0xff) end = 0xff; + +#elif defined COMPILE_PCRE16 +#ifdef SUPPORT_UTF + if ((options & PCRE_UTF16) == 0) +#endif + if (end > 0xffff) end = 0xffff; + +#endif /* COMPILE_PCRE[8|16] */ + +/* Use the bitmap for characters < 256. Otherwise use extra data.*/ + +for (c = start; c <= classbits_end; c++) + { + /* Regardless of start, c will always be <= 255. */ + SETBIT(classbits, c); + n8++; + } + +#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 +if (start <= 0xff) start = 0xff + 1; + +if (end >= start) + { + pcre_uchar *uchardata = *uchardptr; +#ifdef SUPPORT_UTF + if ((options & PCRE_UTF8) != 0) /* All UTFs use the same flag bit */ + { + if (start < end) + { + *uchardata++ = XCL_RANGE; + uchardata += PRIV(ord2utf)(start, uchardata); + uchardata += PRIV(ord2utf)(end, uchardata); + } + else if (start == end) + { + *uchardata++ = XCL_SINGLE; + uchardata += PRIV(ord2utf)(start, uchardata); + } + } + else +#endif /* SUPPORT_UTF */ + + /* Without UTF support, character values are constrained by the bit length, + and can only be > 256 for 16-bit and 32-bit libraries. */ + +#ifdef COMPILE_PCRE8 + {} +#else + if (start < end) + { + *uchardata++ = XCL_RANGE; + *uchardata++ = start; + *uchardata++ = end; + } + else if (start == end) + { + *uchardata++ = XCL_SINGLE; + *uchardata++ = start; + } +#endif + + *uchardptr = uchardata; /* Updata extra data pointer */ + } +#endif /* SUPPORT_UTF || !COMPILE_PCRE8 */ + +return n8; /* Number of 8-bit characters */ +} + + + + +/************************************************* +* Add a list of characters to a class * +*************************************************/ + +/* This function is used for adding a list of case-equivalent characters to a +class, and also for adding a list of horizontal or vertical whitespace. If the +list is in order (which it should be), ranges of characters are detected and +handled appropriately. This function is mutually recursive with the function +above. + +Arguments: + classbits the bit map for characters < 256 + uchardptr points to the pointer for extra data + options the options word + cd contains pointers to tables etc. + p points to row of 32-bit values, terminated by NOTACHAR + except character to omit; this is used when adding lists of + case-equivalent characters to avoid including the one we + already know about + +Returns: the number of < 256 characters added + the pointer to extra data is updated +*/ + +static int +add_list_to_class(pcre_uint8 *classbits, pcre_uchar **uchardptr, int options, + compile_data *cd, const pcre_uint32 *p, unsigned int except) +{ +int n8 = 0; +while (p[0] < NOTACHAR) + { + int n = 0; + if (p[0] != except) + { + while(p[n+1] == p[0] + n + 1) n++; + n8 += add_to_class(classbits, uchardptr, options, cd, p[0], p[n]); + } + p += n + 1; + } +return n8; +} + + + +/************************************************* +* Add characters not in a list to a class * +*************************************************/ + +/* This function is used for adding the complement of a list of horizontal or +vertical whitespace to a class. The list must be in order. + +Arguments: + classbits the bit map for characters < 256 + uchardptr points to the pointer for extra data + options the options word + cd contains pointers to tables etc. + p points to row of 32-bit values, terminated by NOTACHAR + +Returns: the number of < 256 characters added + the pointer to extra data is updated +*/ + +static int +add_not_list_to_class(pcre_uint8 *classbits, pcre_uchar **uchardptr, + int options, compile_data *cd, const pcre_uint32 *p) +{ +BOOL utf = (options & PCRE_UTF8) != 0; +int n8 = 0; +if (p[0] > 0) + n8 += add_to_class(classbits, uchardptr, options, cd, 0, p[0] - 1); +while (p[0] < NOTACHAR) + { + while (p[1] == p[0] + 1) p++; + n8 += add_to_class(classbits, uchardptr, options, cd, p[0] + 1, + (p[1] == NOTACHAR) ? (utf ? 0x10ffffu : 0xffffffffu) : p[1] - 1); + p++; + } +return n8; +} + + + +/************************************************* +* Compile one branch * +*************************************************/ + +/* Scan the pattern, compiling it into the a vector. If the options are +changed during the branch, the pointer is used to change the external options +bits. This function is used during the pre-compile phase when we are trying +to find out the amount of memory needed, as well as during the real compile +phase. The value of lengthptr distinguishes the two phases. + +Arguments: + optionsptr pointer to the option bits + codeptr points to the pointer to the current code point + ptrptr points to the current pattern pointer + errorcodeptr points to error code variable + firstcharptr place to put the first required character + firstcharflagsptr place to put the first character flags, or a negative number + reqcharptr place to put the last required character + reqcharflagsptr place to put the last required character flags, or a negative number + bcptr points to current branch chain + cond_depth conditional nesting depth + cd contains pointers to tables etc. + lengthptr NULL during the real compile phase + points to length accumulator during pre-compile phase + +Returns: TRUE on success + FALSE, with *errorcodeptr set non-zero on error +*/ + +static BOOL +compile_branch(int *optionsptr, pcre_uchar **codeptr, + const pcre_uchar **ptrptr, int *errorcodeptr, + pcre_uint32 *firstcharptr, pcre_int32 *firstcharflagsptr, + pcre_uint32 *reqcharptr, pcre_int32 *reqcharflagsptr, + branch_chain *bcptr, int cond_depth, + compile_data *cd, int *lengthptr) +{ +int repeat_type, op_type; +int repeat_min = 0, repeat_max = 0; /* To please picky compilers */ +int bravalue = 0; +int greedy_default, greedy_non_default; +pcre_uint32 firstchar, reqchar; +pcre_int32 firstcharflags, reqcharflags; +pcre_uint32 zeroreqchar, zerofirstchar; +pcre_int32 zeroreqcharflags, zerofirstcharflags; +pcre_int32 req_caseopt, reqvary, tempreqvary; +int options = *optionsptr; /* May change dynamically */ +int after_manual_callout = 0; +int length_prevgroup = 0; +register pcre_uint32 c; +int escape; +register pcre_uchar *code = *codeptr; +pcre_uchar *last_code = code; +pcre_uchar *orig_code = code; +pcre_uchar *tempcode; +BOOL inescq = FALSE; +BOOL groupsetfirstchar = FALSE; +const pcre_uchar *ptr = *ptrptr; +const pcre_uchar *tempptr; +const pcre_uchar *nestptr = NULL; +pcre_uchar *previous = NULL; +pcre_uchar *previous_callout = NULL; +pcre_uchar *save_hwm = NULL; +pcre_uint8 classbits[32]; + +/* We can fish out the UTF-8 setting once and for all into a BOOL, but we +must not do this for other options (e.g. PCRE_EXTENDED) because they may change +dynamically as we process the pattern. */ + +#ifdef SUPPORT_UTF +/* PCRE_UTF[16|32] have the same value as PCRE_UTF8. */ +BOOL utf = (options & PCRE_UTF8) != 0; +#ifndef COMPILE_PCRE32 +pcre_uchar utf_chars[6]; +#endif +#else +BOOL utf = FALSE; +#endif + +/* Helper variables for OP_XCLASS opcode (for characters > 255). We define +class_uchardata always so that it can be passed to add_to_class() always, +though it will not be used in non-UTF 8-bit cases. This avoids having to supply +alternative calls for the different cases. */ + +pcre_uchar *class_uchardata; +#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 +BOOL xclass; +pcre_uchar *class_uchardata_base; +#endif + +#ifdef PCRE_DEBUG +if (lengthptr != NULL) DPRINTF((">> start branch\n")); +#endif + +/* Set up the default and non-default settings for greediness */ + +greedy_default = ((options & PCRE_UNGREEDY) != 0); +greedy_non_default = greedy_default ^ 1; + +/* Initialize no first byte, no required byte. REQ_UNSET means "no char +matching encountered yet". It gets changed to REQ_NONE if we hit something that +matches a non-fixed char first char; reqchar just remains unset if we never +find one. + +When we hit a repeat whose minimum is zero, we may have to adjust these values +to take the zero repeat into account. This is implemented by setting them to +zerofirstbyte and zeroreqchar when such a repeat is encountered. The individual +item types that can be repeated set these backoff variables appropriately. */ + +firstchar = reqchar = zerofirstchar = zeroreqchar = 0; +firstcharflags = reqcharflags = zerofirstcharflags = zeroreqcharflags = REQ_UNSET; + +/* The variable req_caseopt contains either the REQ_CASELESS value +or zero, according to the current setting of the caseless flag. The +REQ_CASELESS leaves the lower 28 bit empty. It is added into the +firstchar or reqchar variables to record the case status of the +value. This is used only for ASCII characters. */ + +req_caseopt = ((options & PCRE_CASELESS) != 0)? REQ_CASELESS:0; + +/* Switch on next character until the end of the branch */ + +for (;; ptr++) + { + BOOL negate_class; + BOOL should_flip_negation; + BOOL possessive_quantifier; + BOOL is_quantifier; + BOOL is_recurse; + BOOL reset_bracount; + int class_has_8bitchar; + int class_one_char; +#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 + BOOL xclass_has_prop; +#endif + int newoptions; + int recno; + int refsign; + int skipbytes; + pcre_uint32 subreqchar, subfirstchar; + pcre_int32 subreqcharflags, subfirstcharflags; + int terminator; + unsigned int mclength; + unsigned int tempbracount; + pcre_uint32 ec; + pcre_uchar mcbuffer[8]; + + /* Get next character in the pattern */ + + c = *ptr; + + /* If we are at the end of a nested substitution, revert to the outer level + string. Nesting only happens one level deep. */ + + if (c == CHAR_NULL && nestptr != NULL) + { + ptr = nestptr; + nestptr = NULL; + c = *ptr; + } + + /* If we are in the pre-compile phase, accumulate the length used for the + previous cycle of this loop. */ + + if (lengthptr != NULL) + { +#ifdef PCRE_DEBUG + if (code > cd->hwm) cd->hwm = code; /* High water info */ +#endif + if (code > cd->start_workspace + cd->workspace_size - + WORK_SIZE_SAFETY_MARGIN) /* Check for overrun */ + { + *errorcodeptr = ERR52; + goto FAILED; + } + + /* There is at least one situation where code goes backwards: this is the + case of a zero quantifier after a class (e.g. [ab]{0}). At compile time, + the class is simply eliminated. However, it is created first, so we have to + allow memory for it. Therefore, don't ever reduce the length at this point. + */ + + if (code < last_code) code = last_code; + + /* Paranoid check for integer overflow */ + + if (OFLOW_MAX - *lengthptr < code - last_code) + { + *errorcodeptr = ERR20; + goto FAILED; + } + + *lengthptr += (int)(code - last_code); + DPRINTF(("length=%d added %d c=%c (0x%x)\n", *lengthptr, + (int)(code - last_code), c, c)); + + /* If "previous" is set and it is not at the start of the work space, move + it back to there, in order to avoid filling up the work space. Otherwise, + if "previous" is NULL, reset the current code pointer to the start. */ + + if (previous != NULL) + { + if (previous > orig_code) + { + memmove(orig_code, previous, IN_UCHARS(code - previous)); + code -= previous - orig_code; + previous = orig_code; + } + } + else code = orig_code; + + /* Remember where this code item starts so we can pick up the length + next time round. */ + + last_code = code; + } + + /* In the real compile phase, just check the workspace used by the forward + reference list. */ + + else if (cd->hwm > cd->start_workspace + cd->workspace_size - + WORK_SIZE_SAFETY_MARGIN) + { + *errorcodeptr = ERR52; + goto FAILED; + } + + /* If in \Q...\E, check for the end; if not, we have a literal */ + + if (inescq && c != CHAR_NULL) + { + if (c == CHAR_BACKSLASH && ptr[1] == CHAR_E) + { + inescq = FALSE; + ptr++; + continue; + } + else + { + if (previous_callout != NULL) + { + if (lengthptr == NULL) /* Don't attempt in pre-compile phase */ + complete_callout(previous_callout, ptr, cd); + previous_callout = NULL; + } + if ((options & PCRE_AUTO_CALLOUT) != 0) + { + previous_callout = code; + code = auto_callout(code, ptr, cd); + } + goto NORMAL_CHAR; + } + /* Control does not reach here. */ + } + + /* In extended mode, skip white space and comments. We need a loop in order + to check for more white space and more comments after a comment. */ + + if ((options & PCRE_EXTENDED) != 0) + { + for (;;) + { + while (MAX_255(c) && (cd->ctypes[c] & ctype_space) != 0) c = *(++ptr); + if (c != CHAR_NUMBER_SIGN) break; + ptr++; + while (*ptr != CHAR_NULL) + { + if (IS_NEWLINE(ptr)) /* For non-fixed-length newline cases, */ + { /* IS_NEWLINE sets cd->nllen. */ + ptr += cd->nllen; + break; + } + ptr++; +#ifdef SUPPORT_UTF + if (utf) FORWARDCHAR(ptr); +#endif + } + c = *ptr; /* Either NULL or the char after a newline */ + } + } + + /* See if the next thing is a quantifier. */ + + is_quantifier = + c == CHAR_ASTERISK || c == CHAR_PLUS || c == CHAR_QUESTION_MARK || + (c == CHAR_LEFT_CURLY_BRACKET && is_counted_repeat(ptr+1)); + + /* Fill in length of a previous callout, except when the next thing is a + quantifier or when processing a property substitution string in UCP mode. */ + + if (!is_quantifier && previous_callout != NULL && nestptr == NULL && + after_manual_callout-- <= 0) + { + if (lengthptr == NULL) /* Don't attempt in pre-compile phase */ + complete_callout(previous_callout, ptr, cd); + previous_callout = NULL; + } + + /* Create auto callout, except for quantifiers, or while processing property + strings that are substituted for \w etc in UCP mode. */ + + if ((options & PCRE_AUTO_CALLOUT) != 0 && !is_quantifier && nestptr == NULL) + { + previous_callout = code; + code = auto_callout(code, ptr, cd); + } + + /* Process the next pattern item. */ + + switch(c) + { + /* ===================================================================*/ + case CHAR_NULL: /* The branch terminates at string end */ + case CHAR_VERTICAL_LINE: /* or | or ) */ + case CHAR_RIGHT_PARENTHESIS: + *firstcharptr = firstchar; + *firstcharflagsptr = firstcharflags; + *reqcharptr = reqchar; + *reqcharflagsptr = reqcharflags; + *codeptr = code; + *ptrptr = ptr; + if (lengthptr != NULL) + { + if (OFLOW_MAX - *lengthptr < code - last_code) + { + *errorcodeptr = ERR20; + goto FAILED; + } + *lengthptr += (int)(code - last_code); /* To include callout length */ + DPRINTF((">> end branch\n")); + } + return TRUE; + + + /* ===================================================================*/ + /* Handle single-character metacharacters. In multiline mode, ^ disables + the setting of any following char as a first character. */ + + case CHAR_CIRCUMFLEX_ACCENT: + previous = NULL; + if ((options & PCRE_MULTILINE) != 0) + { + if (firstcharflags == REQ_UNSET) + zerofirstcharflags = firstcharflags = REQ_NONE; + *code++ = OP_CIRCM; + } + else *code++ = OP_CIRC; + break; + + case CHAR_DOLLAR_SIGN: + previous = NULL; + *code++ = ((options & PCRE_MULTILINE) != 0)? OP_DOLLM : OP_DOLL; + break; + + /* There can never be a first char if '.' is first, whatever happens about + repeats. The value of reqchar doesn't change either. */ + + case CHAR_DOT: + if (firstcharflags == REQ_UNSET) firstcharflags = REQ_NONE; + zerofirstchar = firstchar; + zerofirstcharflags = firstcharflags; + zeroreqchar = reqchar; + zeroreqcharflags = reqcharflags; + previous = code; + *code++ = ((options & PCRE_DOTALL) != 0)? OP_ALLANY: OP_ANY; + break; + + + /* ===================================================================*/ + /* Character classes. If the included characters are all < 256, we build a + 32-byte bitmap of the permitted characters, except in the special case + where there is only one such character. For negated classes, we build the + map as usual, then invert it at the end. However, we use a different opcode + so that data characters > 255 can be handled correctly. + + If the class contains characters outside the 0-255 range, a different + opcode is compiled. It may optionally have a bit map for characters < 256, + but those above are are explicitly listed afterwards. A flag byte tells + whether the bitmap is present, and whether this is a negated class or not. + + In JavaScript compatibility mode, an isolated ']' causes an error. In + default (Perl) mode, it is treated as a data character. */ + + case CHAR_RIGHT_SQUARE_BRACKET: + if ((cd->external_options & PCRE_JAVASCRIPT_COMPAT) != 0) + { + *errorcodeptr = ERR64; + goto FAILED; + } + goto NORMAL_CHAR; + + /* In another (POSIX) regex library, the ugly syntax [[:<:]] and [[:>:]] is + used for "start of word" and "end of word". As these are otherwise illegal + sequences, we don't break anything by recognizing them. They are replaced + by \b(?=\w) and \b(?<=\w) respectively. Sequences like [a[:<:]] are + erroneous and are handled by the normal code below. */ + + case CHAR_LEFT_SQUARE_BRACKET: + if (STRNCMP_UC_C8(ptr+1, STRING_WEIRD_STARTWORD, 6) == 0) + { + nestptr = ptr + 7; + ptr = sub_start_of_word - 1; + continue; + } + + if (STRNCMP_UC_C8(ptr+1, STRING_WEIRD_ENDWORD, 6) == 0) + { + nestptr = ptr + 7; + ptr = sub_end_of_word - 1; + continue; + } + + /* Handle a real character class. */ + + previous = code; + + /* PCRE supports POSIX class stuff inside a class. Perl gives an error if + they are encountered at the top level, so we'll do that too. */ + + if ((ptr[1] == CHAR_COLON || ptr[1] == CHAR_DOT || + ptr[1] == CHAR_EQUALS_SIGN) && + check_posix_syntax(ptr, &tempptr)) + { + *errorcodeptr = (ptr[1] == CHAR_COLON)? ERR13 : ERR31; + goto FAILED; + } + + /* If the first character is '^', set the negation flag and skip it. Also, + if the first few characters (either before or after ^) are \Q\E or \E we + skip them too. This makes for compatibility with Perl. */ + + negate_class = FALSE; + for (;;) + { + c = *(++ptr); + if (c == CHAR_BACKSLASH) + { + if (ptr[1] == CHAR_E) + ptr++; + else if (STRNCMP_UC_C8(ptr + 1, STR_Q STR_BACKSLASH STR_E, 3) == 0) + ptr += 3; + else + break; + } + else if (!negate_class && c == CHAR_CIRCUMFLEX_ACCENT) + negate_class = TRUE; + else break; + } + + /* Empty classes are allowed in JavaScript compatibility mode. Otherwise, + an initial ']' is taken as a data character -- the code below handles + that. In JS mode, [] must always fail, so generate OP_FAIL, whereas + [^] must match any character, so generate OP_ALLANY. */ + + if (c == CHAR_RIGHT_SQUARE_BRACKET && + (cd->external_options & PCRE_JAVASCRIPT_COMPAT) != 0) + { + *code++ = negate_class? OP_ALLANY : OP_FAIL; + if (firstcharflags == REQ_UNSET) firstcharflags = REQ_NONE; + zerofirstchar = firstchar; + zerofirstcharflags = firstcharflags; + break; + } + + /* If a class contains a negative special such as \S, we need to flip the + negation flag at the end, so that support for characters > 255 works + correctly (they are all included in the class). */ + + should_flip_negation = FALSE; + + /* Extended class (xclass) will be used when characters > 255 + might match. */ + +#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 + xclass = FALSE; + class_uchardata = code + LINK_SIZE + 2; /* For XCLASS items */ + class_uchardata_base = class_uchardata; /* Save the start */ +#endif + + /* For optimization purposes, we track some properties of the class: + class_has_8bitchar will be non-zero if the class contains at least one < + 256 character; class_one_char will be 1 if the class contains just one + character; xclass_has_prop will be TRUE if unicode property checks + are present in the class. */ + + class_has_8bitchar = 0; + class_one_char = 0; +#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 + xclass_has_prop = FALSE; +#endif + + /* Initialize the 32-char bit map to all zeros. We build the map in a + temporary bit of memory, in case the class contains fewer than two + 8-bit characters because in that case the compiled code doesn't use the bit + map. */ + + memset(classbits, 0, 32 * sizeof(pcre_uint8)); + + /* Process characters until ] is reached. By writing this as a "do" it + means that an initial ] is taken as a data character. At the start of the + loop, c contains the first byte of the character. */ + + if (c != CHAR_NULL) do + { + const pcre_uchar *oldptr; + +#ifdef SUPPORT_UTF + if (utf && HAS_EXTRALEN(c)) + { /* Braces are required because the */ + GETCHARLEN(c, ptr, ptr); /* macro generates multiple statements */ + } +#endif + +#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 + /* In the pre-compile phase, accumulate the length of any extra + data and reset the pointer. This is so that very large classes that + contain a zillion > 255 characters no longer overwrite the work space + (which is on the stack). We have to remember that there was XCLASS data, + however. */ + + if (lengthptr != NULL && class_uchardata > class_uchardata_base) + { + xclass = TRUE; + *lengthptr += (int)(class_uchardata - class_uchardata_base); + class_uchardata = class_uchardata_base; + } +#endif + + /* Inside \Q...\E everything is literal except \E */ + + if (inescq) + { + if (c == CHAR_BACKSLASH && ptr[1] == CHAR_E) /* If we are at \E */ + { + inescq = FALSE; /* Reset literal state */ + ptr++; /* Skip the 'E' */ + continue; /* Carry on with next */ + } + goto CHECK_RANGE; /* Could be range if \E follows */ + } + + /* Handle POSIX class names. Perl allows a negation extension of the + form [:^name:]. A square bracket that doesn't match the syntax is + treated as a literal. We also recognize the POSIX constructions + [.ch.] and [=ch=] ("collating elements") and fault them, as Perl + 5.6 and 5.8 do. */ + + if (c == CHAR_LEFT_SQUARE_BRACKET && + (ptr[1] == CHAR_COLON || ptr[1] == CHAR_DOT || + ptr[1] == CHAR_EQUALS_SIGN) && check_posix_syntax(ptr, &tempptr)) + { + BOOL local_negate = FALSE; + int posix_class, taboffset, tabopt; + register const pcre_uint8 *cbits = cd->cbits; + pcre_uint8 pbits[32]; + + if (ptr[1] != CHAR_COLON) + { + *errorcodeptr = ERR31; + goto FAILED; + } + + ptr += 2; + if (*ptr == CHAR_CIRCUMFLEX_ACCENT) + { + local_negate = TRUE; + should_flip_negation = TRUE; /* Note negative special */ + ptr++; + } + + posix_class = check_posix_name(ptr, (int)(tempptr - ptr)); + if (posix_class < 0) + { + *errorcodeptr = ERR30; + goto FAILED; + } + + /* If matching is caseless, upper and lower are converted to + alpha. This relies on the fact that the class table starts with + alpha, lower, upper as the first 3 entries. */ + + if ((options & PCRE_CASELESS) != 0 && posix_class <= 2) + posix_class = 0; + + /* When PCRE_UCP is set, some of the POSIX classes are converted to + different escape sequences that use Unicode properties \p or \P. Others + that are not available via \p or \P generate XCL_PROP/XCL_NOTPROP + directly. */ + +#ifdef SUPPORT_UCP + if ((options & PCRE_UCP) != 0) + { + unsigned int ptype = 0; + int pc = posix_class + ((local_negate)? POSIX_SUBSIZE/2 : 0); + + /* The posix_substitutes table specifies which POSIX classes can be + converted to \p or \P items. */ + + if (posix_substitutes[pc] != NULL) + { + nestptr = tempptr + 1; + ptr = posix_substitutes[pc] - 1; + continue; + } + + /* There are three other classes that generate special property calls + that are recognized only in an XCLASS. */ + + else switch(posix_class) + { + case PC_GRAPH: + ptype = PT_PXGRAPH; + /* Fall through */ + case PC_PRINT: + if (ptype == 0) ptype = PT_PXPRINT; + /* Fall through */ + case PC_PUNCT: + if (ptype == 0) ptype = PT_PXPUNCT; + *class_uchardata++ = local_negate? XCL_NOTPROP : XCL_PROP; + *class_uchardata++ = ptype; + *class_uchardata++ = 0; + xclass_has_prop = TRUE; + ptr = tempptr + 1; + continue; + + /* For all other POSIX classes, no special action is taken in UCP + mode. Fall through to the non_UCP case. */ + + default: + break; + } + } +#endif + /* In the non-UCP case, or when UCP makes no difference, we build the + bit map for the POSIX class in a chunk of local store because we may be + adding and subtracting from it, and we don't want to subtract bits that + may be in the main map already. At the end we or the result into the + bit map that is being built. */ + + posix_class *= 3; + + /* Copy in the first table (always present) */ + + memcpy(pbits, cbits + posix_class_maps[posix_class], + 32 * sizeof(pcre_uint8)); + + /* If there is a second table, add or remove it as required. */ + + taboffset = posix_class_maps[posix_class + 1]; + tabopt = posix_class_maps[posix_class + 2]; + + if (taboffset >= 0) + { + if (tabopt >= 0) + for (c = 0; c < 32; c++) pbits[c] |= cbits[c + taboffset]; + else + for (c = 0; c < 32; c++) pbits[c] &= ~cbits[c + taboffset]; + } + + /* Now see if we need to remove any special characters. An option + value of 1 removes vertical space and 2 removes underscore. */ + + if (tabopt < 0) tabopt = -tabopt; + if (tabopt == 1) pbits[1] &= ~0x3c; + else if (tabopt == 2) pbits[11] &= 0x7f; + + /* Add the POSIX table or its complement into the main table that is + being built and we are done. */ + + if (local_negate) + for (c = 0; c < 32; c++) classbits[c] |= ~pbits[c]; + else + for (c = 0; c < 32; c++) classbits[c] |= pbits[c]; + + ptr = tempptr + 1; + /* Every class contains at least one < 256 character. */ + class_has_8bitchar = 1; + /* Every class contains at least two characters. */ + class_one_char = 2; + continue; /* End of POSIX syntax handling */ + } + + /* Backslash may introduce a single character, or it may introduce one + of the specials, which just set a flag. The sequence \b is a special + case. Inside a class (and only there) it is treated as backspace. We + assume that other escapes have more than one character in them, so + speculatively set both class_has_8bitchar and class_one_char bigger + than one. Unrecognized escapes fall through and are either treated + as literal characters (by default), or are faulted if + PCRE_EXTRA is set. */ + + if (c == CHAR_BACKSLASH) + { + escape = check_escape(&ptr, &ec, errorcodeptr, cd->bracount, options, + TRUE); + if (*errorcodeptr != 0) goto FAILED; + if (escape == 0) c = ec; + else if (escape == ESC_b) c = CHAR_BS; /* \b is backspace in a class */ + else if (escape == ESC_N) /* \N is not supported in a class */ + { + *errorcodeptr = ERR71; + goto FAILED; + } + else if (escape == ESC_Q) /* Handle start of quoted string */ + { + if (ptr[1] == CHAR_BACKSLASH && ptr[2] == CHAR_E) + { + ptr += 2; /* avoid empty string */ + } + else inescq = TRUE; + continue; + } + else if (escape == ESC_E) continue; /* Ignore orphan \E */ + + else + { + register const pcre_uint8 *cbits = cd->cbits; + /* Every class contains at least two < 256 characters. */ + class_has_8bitchar++; + /* Every class contains at least two characters. */ + class_one_char += 2; + + switch (escape) + { +#ifdef SUPPORT_UCP + case ESC_du: /* These are the values given for \d etc */ + case ESC_DU: /* when PCRE_UCP is set. We replace the */ + case ESC_wu: /* escape sequence with an appropriate \p */ + case ESC_WU: /* or \P to test Unicode properties instead */ + case ESC_su: /* of the default ASCII testing. */ + case ESC_SU: + nestptr = ptr; + ptr = substitutes[escape - ESC_DU] - 1; /* Just before substitute */ + class_has_8bitchar--; /* Undo! */ + continue; +#endif + case ESC_d: + for (c = 0; c < 32; c++) classbits[c] |= cbits[c+cbit_digit]; + continue; + + case ESC_D: + should_flip_negation = TRUE; + for (c = 0; c < 32; c++) classbits[c] |= ~cbits[c+cbit_digit]; + continue; + + case ESC_w: + for (c = 0; c < 32; c++) classbits[c] |= cbits[c+cbit_word]; + continue; + + case ESC_W: + should_flip_negation = TRUE; + for (c = 0; c < 32; c++) classbits[c] |= ~cbits[c+cbit_word]; + continue; + + /* Perl 5.004 onwards omitted VT from \s, but restored it at Perl + 5.18. Before PCRE 8.34, we had to preserve the VT bit if it was + previously set by something earlier in the character class. + Luckily, the value of CHAR_VT is 0x0b in both ASCII and EBCDIC, so + we could just adjust the appropriate bit. From PCRE 8.34 we no + longer treat \s and \S specially. */ + + case ESC_s: + for (c = 0; c < 32; c++) classbits[c] |= cbits[c+cbit_space]; + continue; + + case ESC_S: + should_flip_negation = TRUE; + for (c = 0; c < 32; c++) classbits[c] |= ~cbits[c+cbit_space]; + continue; + + /* The rest apply in both UCP and non-UCP cases. */ + + case ESC_h: + (void)add_list_to_class(classbits, &class_uchardata, options, cd, + PRIV(hspace_list), NOTACHAR); + continue; + + case ESC_H: + (void)add_not_list_to_class(classbits, &class_uchardata, options, + cd, PRIV(hspace_list)); + continue; + + case ESC_v: + (void)add_list_to_class(classbits, &class_uchardata, options, cd, + PRIV(vspace_list), NOTACHAR); + continue; + + case ESC_V: + (void)add_not_list_to_class(classbits, &class_uchardata, options, + cd, PRIV(vspace_list)); + continue; + +#ifdef SUPPORT_UCP + case ESC_p: + case ESC_P: + { + BOOL negated; + unsigned int ptype = 0, pdata = 0; + if (!get_ucp(&ptr, &negated, &ptype, &pdata, errorcodeptr)) + goto FAILED; + *class_uchardata++ = ((escape == ESC_p) != negated)? + XCL_PROP : XCL_NOTPROP; + *class_uchardata++ = ptype; + *class_uchardata++ = pdata; + xclass_has_prop = TRUE; + class_has_8bitchar--; /* Undo! */ + continue; + } +#endif + /* Unrecognized escapes are faulted if PCRE is running in its + strict mode. By default, for compatibility with Perl, they are + treated as literals. */ + + default: + if ((options & PCRE_EXTRA) != 0) + { + *errorcodeptr = ERR7; + goto FAILED; + } + class_has_8bitchar--; /* Undo the speculative increase. */ + class_one_char -= 2; /* Undo the speculative increase. */ + c = *ptr; /* Get the final character and fall through */ + break; + } + } + + /* Fall through if the escape just defined a single character (c >= 0). + This may be greater than 256. */ + + escape = 0; + + } /* End of backslash handling */ + + /* A character may be followed by '-' to form a range. However, Perl does + not permit ']' to be the end of the range. A '-' character at the end is + treated as a literal. Perl ignores orphaned \E sequences entirely. The + code for handling \Q and \E is messy. */ + + CHECK_RANGE: + while (ptr[1] == CHAR_BACKSLASH && ptr[2] == CHAR_E) + { + inescq = FALSE; + ptr += 2; + } + oldptr = ptr; + + /* Remember if \r or \n were explicitly used */ + + if (c == CHAR_CR || c == CHAR_NL) cd->external_flags |= PCRE_HASCRORLF; + + /* Check for range */ + + if (!inescq && ptr[1] == CHAR_MINUS) + { + pcre_uint32 d; + ptr += 2; + while (*ptr == CHAR_BACKSLASH && ptr[1] == CHAR_E) ptr += 2; + + /* If we hit \Q (not followed by \E) at this point, go into escaped + mode. */ + + while (*ptr == CHAR_BACKSLASH && ptr[1] == CHAR_Q) + { + ptr += 2; + if (*ptr == CHAR_BACKSLASH && ptr[1] == CHAR_E) + { ptr += 2; continue; } + inescq = TRUE; + break; + } + + /* Minus (hyphen) at the end of a class is treated as a literal, so put + back the pointer and jump to handle the character that preceded it. */ + + if (*ptr == CHAR_NULL || (!inescq && *ptr == CHAR_RIGHT_SQUARE_BRACKET)) + { + ptr = oldptr; + goto CLASS_SINGLE_CHARACTER; + } + + /* Otherwise, we have a potential range; pick up the next character */ + +#ifdef SUPPORT_UTF + if (utf) + { /* Braces are required because the */ + GETCHARLEN(d, ptr, ptr); /* macro generates multiple statements */ + } + else +#endif + d = *ptr; /* Not UTF-8 mode */ + + /* The second part of a range can be a single-character escape + sequence, but not any of the other escapes. Perl treats a hyphen as a + literal in such circumstances. However, in Perl's warning mode, a + warning is given, so PCRE now faults it as it is almost certainly a + mistake on the user's part. */ + + if (!inescq) + { + if (d == CHAR_BACKSLASH) + { + int descape; + descape = check_escape(&ptr, &d, errorcodeptr, cd->bracount, options, TRUE); + if (*errorcodeptr != 0) goto FAILED; + + /* 0 means a character was put into d; \b is backspace; any other + special causes an error. */ + + if (descape != 0) + { + if (descape == ESC_b) d = CHAR_BS; else + { + *errorcodeptr = ERR83; + goto FAILED; + } + } + } + + /* A hyphen followed by a POSIX class is treated in the same way. */ + + else if (d == CHAR_LEFT_SQUARE_BRACKET && + (ptr[1] == CHAR_COLON || ptr[1] == CHAR_DOT || + ptr[1] == CHAR_EQUALS_SIGN) && + check_posix_syntax(ptr, &tempptr)) + { + *errorcodeptr = ERR83; + goto FAILED; + } + } + + /* Check that the two values are in the correct order. Optimize + one-character ranges. */ + + if (d < c) + { + *errorcodeptr = ERR8; + goto FAILED; + } + if (d == c) goto CLASS_SINGLE_CHARACTER; /* A few lines below */ + + /* We have found a character range, so single character optimizations + cannot be done anymore. Any value greater than 1 indicates that there + is more than one character. */ + + class_one_char = 2; + + /* Remember an explicit \r or \n, and add the range to the class. */ + + if (d == CHAR_CR || d == CHAR_NL) cd->external_flags |= PCRE_HASCRORLF; + + class_has_8bitchar += + add_to_class(classbits, &class_uchardata, options, cd, c, d); + + continue; /* Go get the next char in the class */ + } + + /* Handle a single character - we can get here for a normal non-escape + char, or after \ that introduces a single character or for an apparent + range that isn't. Only the value 1 matters for class_one_char, so don't + increase it if it is already 2 or more ... just in case there's a class + with a zillion characters in it. */ + + CLASS_SINGLE_CHARACTER: + if (class_one_char < 2) class_one_char++; + + /* If class_one_char is 1, we have the first single character in the + class, and there have been no prior ranges, or XCLASS items generated by + escapes. If this is the final character in the class, we can optimize by + turning the item into a 1-character OP_CHAR[I] if it's positive, or + OP_NOT[I] if it's negative. In the positive case, it can cause firstchar + to be set. Otherwise, there can be no first char if this item is first, + whatever repeat count may follow. In the case of reqchar, save the + previous value for reinstating. */ + + if (!inescq && class_one_char == 1 && ptr[1] == CHAR_RIGHT_SQUARE_BRACKET) + { + ptr++; + zeroreqchar = reqchar; + zeroreqcharflags = reqcharflags; + + if (negate_class) + { +#ifdef SUPPORT_UCP + int d; +#endif + if (firstcharflags == REQ_UNSET) firstcharflags = REQ_NONE; + zerofirstchar = firstchar; + zerofirstcharflags = firstcharflags; + + /* For caseless UTF-8 mode when UCP support is available, check + whether this character has more than one other case. If so, generate + a special OP_NOTPROP item instead of OP_NOTI. */ + +#ifdef SUPPORT_UCP + if (utf && (options & PCRE_CASELESS) != 0 && + (d = UCD_CASESET(c)) != 0) + { + *code++ = OP_NOTPROP; + *code++ = PT_CLIST; + *code++ = d; + } + else +#endif + /* Char has only one other case, or UCP not available */ + + { + *code++ = ((options & PCRE_CASELESS) != 0)? OP_NOTI: OP_NOT; +#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 + if (utf && c > MAX_VALUE_FOR_SINGLE_CHAR) + code += PRIV(ord2utf)(c, code); + else +#endif + *code++ = c; + } + + /* We are finished with this character class */ + + goto END_CLASS; + } + + /* For a single, positive character, get the value into mcbuffer, and + then we can handle this with the normal one-character code. */ + +#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 + if (utf && c > MAX_VALUE_FOR_SINGLE_CHAR) + mclength = PRIV(ord2utf)(c, mcbuffer); + else +#endif + { + mcbuffer[0] = c; + mclength = 1; + } + goto ONE_CHAR; + } /* End of 1-char optimization */ + + /* There is more than one character in the class, or an XCLASS item + has been generated. Add this character to the class. */ + + class_has_8bitchar += + add_to_class(classbits, &class_uchardata, options, cd, c, c); + } + + /* Loop until ']' reached. This "while" is the end of the "do" far above. + If we are at the end of an internal nested string, revert to the outer + string. */ + + while (((c = *(++ptr)) != CHAR_NULL || + (nestptr != NULL && + (ptr = nestptr, nestptr = NULL, c = *(++ptr)) != CHAR_NULL)) && + (c != CHAR_RIGHT_SQUARE_BRACKET || inescq)); + + /* Check for missing terminating ']' */ + + if (c == CHAR_NULL) + { + *errorcodeptr = ERR6; + goto FAILED; + } + + /* We will need an XCLASS if data has been placed in class_uchardata. In + the second phase this is a sufficient test. However, in the pre-compile + phase, class_uchardata gets emptied to prevent workspace overflow, so it + only if the very last character in the class needs XCLASS will it contain + anything at this point. For this reason, xclass gets set TRUE above when + uchar_classdata is emptied, and that's why this code is the way it is here + instead of just doing a test on class_uchardata below. */ + +#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 + if (class_uchardata > class_uchardata_base) xclass = TRUE; +#endif + + /* If this is the first thing in the branch, there can be no first char + setting, whatever the repeat count. Any reqchar setting must remain + unchanged after any kind of repeat. */ + + if (firstcharflags == REQ_UNSET) firstcharflags = REQ_NONE; + zerofirstchar = firstchar; + zerofirstcharflags = firstcharflags; + zeroreqchar = reqchar; + zeroreqcharflags = reqcharflags; + + /* If there are characters with values > 255, we have to compile an + extended class, with its own opcode, unless there was a negated special + such as \S in the class, and PCRE_UCP is not set, because in that case all + characters > 255 are in the class, so any that were explicitly given as + well can be ignored. If (when there are explicit characters > 255 that must + be listed) there are no characters < 256, we can omit the bitmap in the + actual compiled code. */ + +#ifdef SUPPORT_UTF + if (xclass && (!should_flip_negation || (options & PCRE_UCP) != 0)) +#elif !defined COMPILE_PCRE8 + if (xclass && !should_flip_negation) +#endif +#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 + { + *class_uchardata++ = XCL_END; /* Marks the end of extra data */ + *code++ = OP_XCLASS; + code += LINK_SIZE; + *code = negate_class? XCL_NOT:0; + if (xclass_has_prop) *code |= XCL_HASPROP; + + /* If the map is required, move up the extra data to make room for it; + otherwise just move the code pointer to the end of the extra data. */ + + if (class_has_8bitchar > 0) + { + *code++ |= XCL_MAP; + memmove(code + (32 / sizeof(pcre_uchar)), code, + IN_UCHARS(class_uchardata - code)); + if (negate_class && !xclass_has_prop) + for (c = 0; c < 32; c++) classbits[c] = ~classbits[c]; + memcpy(code, classbits, 32); + code = class_uchardata + (32 / sizeof(pcre_uchar)); + } + else code = class_uchardata; + + /* Now fill in the complete length of the item */ + + PUT(previous, 1, (int)(code - previous)); + break; /* End of class handling */ + } +#endif + + /* If there are no characters > 255, or they are all to be included or + excluded, set the opcode to OP_CLASS or OP_NCLASS, depending on whether the + whole class was negated and whether there were negative specials such as \S + (non-UCP) in the class. Then copy the 32-byte map into the code vector, + negating it if necessary. */ + + *code++ = (negate_class == should_flip_negation) ? OP_CLASS : OP_NCLASS; + if (lengthptr == NULL) /* Save time in the pre-compile phase */ + { + if (negate_class) + for (c = 0; c < 32; c++) classbits[c] = ~classbits[c]; + memcpy(code, classbits, 32); + } + code += 32 / sizeof(pcre_uchar); + + END_CLASS: + break; + + + /* ===================================================================*/ + /* Various kinds of repeat; '{' is not necessarily a quantifier, but this + has been tested above. */ + + case CHAR_LEFT_CURLY_BRACKET: + if (!is_quantifier) goto NORMAL_CHAR; + ptr = read_repeat_counts(ptr+1, &repeat_min, &repeat_max, errorcodeptr); + if (*errorcodeptr != 0) goto FAILED; + goto REPEAT; + + case CHAR_ASTERISK: + repeat_min = 0; + repeat_max = -1; + goto REPEAT; + + case CHAR_PLUS: + repeat_min = 1; + repeat_max = -1; + goto REPEAT; + + case CHAR_QUESTION_MARK: + repeat_min = 0; + repeat_max = 1; + + REPEAT: + if (previous == NULL) + { + *errorcodeptr = ERR9; + goto FAILED; + } + + if (repeat_min == 0) + { + firstchar = zerofirstchar; /* Adjust for zero repeat */ + firstcharflags = zerofirstcharflags; + reqchar = zeroreqchar; /* Ditto */ + reqcharflags = zeroreqcharflags; + } + + /* Remember whether this is a variable length repeat */ + + reqvary = (repeat_min == repeat_max)? 0 : REQ_VARY; + + op_type = 0; /* Default single-char op codes */ + possessive_quantifier = FALSE; /* Default not possessive quantifier */ + + /* Save start of previous item, in case we have to move it up in order to + insert something before it. */ + + tempcode = previous; + + /* Before checking for a possessive quantifier, we must skip over + whitespace and comments in extended mode because Perl allows white space at + this point. */ + + if ((options & PCRE_EXTENDED) != 0) + { + const pcre_uchar *p = ptr + 1; + for (;;) + { + while (MAX_255(*p) && (cd->ctypes[*p] & ctype_space) != 0) p++; + if (*p != CHAR_NUMBER_SIGN) break; + p++; + while (*p != CHAR_NULL) + { + if (IS_NEWLINE(p)) /* For non-fixed-length newline cases, */ + { /* IS_NEWLINE sets cd->nllen. */ + p += cd->nllen; + break; + } + p++; +#ifdef SUPPORT_UTF + if (utf) FORWARDCHAR(p); +#endif + } /* Loop for comment characters */ + } /* Loop for multiple comments */ + ptr = p - 1; /* Character before the next significant one. */ + } + + /* If the next character is '+', we have a possessive quantifier. This + implies greediness, whatever the setting of the PCRE_UNGREEDY option. + If the next character is '?' this is a minimizing repeat, by default, + but if PCRE_UNGREEDY is set, it works the other way round. We change the + repeat type to the non-default. */ + + if (ptr[1] == CHAR_PLUS) + { + repeat_type = 0; /* Force greedy */ + possessive_quantifier = TRUE; + ptr++; + } + else if (ptr[1] == CHAR_QUESTION_MARK) + { + repeat_type = greedy_non_default; + ptr++; + } + else repeat_type = greedy_default; + + /* If previous was a recursion call, wrap it in atomic brackets so that + previous becomes the atomic group. All recursions were so wrapped in the + past, but it no longer happens for non-repeated recursions. In fact, the + repeated ones could be re-implemented independently so as not to need this, + but for the moment we rely on the code for repeating groups. */ + + if (*previous == OP_RECURSE) + { + memmove(previous + 1 + LINK_SIZE, previous, IN_UCHARS(1 + LINK_SIZE)); + *previous = OP_ONCE; + PUT(previous, 1, 2 + 2*LINK_SIZE); + previous[2 + 2*LINK_SIZE] = OP_KET; + PUT(previous, 3 + 2*LINK_SIZE, 2 + 2*LINK_SIZE); + code += 2 + 2 * LINK_SIZE; + length_prevgroup = 3 + 3*LINK_SIZE; + + /* When actually compiling, we need to check whether this was a forward + reference, and if so, adjust the offset. */ + + if (lengthptr == NULL && cd->hwm >= cd->start_workspace + LINK_SIZE) + { + int offset = GET(cd->hwm, -LINK_SIZE); + if (offset == previous + 1 - cd->start_code) + PUT(cd->hwm, -LINK_SIZE, offset + 1 + LINK_SIZE); + } + } + + /* Now handle repetition for the different types of item. */ + + /* If previous was a character or negated character match, abolish the item + and generate a repeat item instead. If a char item has a minimum of more + than one, ensure that it is set in reqchar - it might not be if a sequence + such as x{3} is the first thing in a branch because the x will have gone + into firstchar instead. */ + + if (*previous == OP_CHAR || *previous == OP_CHARI + || *previous == OP_NOT || *previous == OP_NOTI) + { + switch (*previous) + { + default: /* Make compiler happy. */ + case OP_CHAR: op_type = OP_STAR - OP_STAR; break; + case OP_CHARI: op_type = OP_STARI - OP_STAR; break; + case OP_NOT: op_type = OP_NOTSTAR - OP_STAR; break; + case OP_NOTI: op_type = OP_NOTSTARI - OP_STAR; break; + } + + /* Deal with UTF characters that take up more than one character. It's + easier to write this out separately than try to macrify it. Use c to + hold the length of the character in bytes, plus UTF_LENGTH to flag that + it's a length rather than a small character. */ + +#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 + if (utf && NOT_FIRSTCHAR(code[-1])) + { + pcre_uchar *lastchar = code - 1; + BACKCHAR(lastchar); + c = (int)(code - lastchar); /* Length of UTF-8 character */ + memcpy(utf_chars, lastchar, IN_UCHARS(c)); /* Save the char */ + c |= UTF_LENGTH; /* Flag c as a length */ + } + else +#endif /* SUPPORT_UTF */ + + /* Handle the case of a single charater - either with no UTF support, or + with UTF disabled, or for a single character UTF character. */ + { + c = code[-1]; + if (*previous <= OP_CHARI && repeat_min > 1) + { + reqchar = c; + reqcharflags = req_caseopt | cd->req_varyopt; + } + } + + goto OUTPUT_SINGLE_REPEAT; /* Code shared with single character types */ + } + + /* If previous was a character type match (\d or similar), abolish it and + create a suitable repeat item. The code is shared with single-character + repeats by setting op_type to add a suitable offset into repeat_type. Note + the the Unicode property types will be present only when SUPPORT_UCP is + defined, but we don't wrap the little bits of code here because it just + makes it horribly messy. */ + + else if (*previous < OP_EODN) + { + pcre_uchar *oldcode; + int prop_type, prop_value; + op_type = OP_TYPESTAR - OP_STAR; /* Use type opcodes */ + c = *previous; + + OUTPUT_SINGLE_REPEAT: + if (*previous == OP_PROP || *previous == OP_NOTPROP) + { + prop_type = previous[1]; + prop_value = previous[2]; + } + else prop_type = prop_value = -1; + + oldcode = code; + code = previous; /* Usually overwrite previous item */ + + /* If the maximum is zero then the minimum must also be zero; Perl allows + this case, so we do too - by simply omitting the item altogether. */ + + if (repeat_max == 0) goto END_REPEAT; + + /* Combine the op_type with the repeat_type */ + + repeat_type += op_type; + + /* A minimum of zero is handled either as the special case * or ?, or as + an UPTO, with the maximum given. */ + + if (repeat_min == 0) + { + if (repeat_max == -1) *code++ = OP_STAR + repeat_type; + else if (repeat_max == 1) *code++ = OP_QUERY + repeat_type; + else + { + *code++ = OP_UPTO + repeat_type; + PUT2INC(code, 0, repeat_max); + } + } + + /* A repeat minimum of 1 is optimized into some special cases. If the + maximum is unlimited, we use OP_PLUS. Otherwise, the original item is + left in place and, if the maximum is greater than 1, we use OP_UPTO with + one less than the maximum. */ + + else if (repeat_min == 1) + { + if (repeat_max == -1) + *code++ = OP_PLUS + repeat_type; + else + { + code = oldcode; /* leave previous item in place */ + if (repeat_max == 1) goto END_REPEAT; + *code++ = OP_UPTO + repeat_type; + PUT2INC(code, 0, repeat_max - 1); + } + } + + /* The case {n,n} is just an EXACT, while the general case {n,m} is + handled as an EXACT followed by an UPTO. */ + + else + { + *code++ = OP_EXACT + op_type; /* NB EXACT doesn't have repeat_type */ + PUT2INC(code, 0, repeat_min); + + /* If the maximum is unlimited, insert an OP_STAR. Before doing so, + we have to insert the character for the previous code. For a repeated + Unicode property match, there are two extra bytes that define the + required property. In UTF-8 mode, long characters have their length in + c, with the UTF_LENGTH bit as a flag. */ + + if (repeat_max < 0) + { +#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 + if (utf && (c & UTF_LENGTH) != 0) + { + memcpy(code, utf_chars, IN_UCHARS(c & 7)); + code += c & 7; + } + else +#endif + { + *code++ = c; + if (prop_type >= 0) + { + *code++ = prop_type; + *code++ = prop_value; + } + } + *code++ = OP_STAR + repeat_type; + } + + /* Else insert an UPTO if the max is greater than the min, again + preceded by the character, for the previously inserted code. If the + UPTO is just for 1 instance, we can use QUERY instead. */ + + else if (repeat_max != repeat_min) + { +#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 + if (utf && (c & UTF_LENGTH) != 0) + { + memcpy(code, utf_chars, IN_UCHARS(c & 7)); + code += c & 7; + } + else +#endif + *code++ = c; + if (prop_type >= 0) + { + *code++ = prop_type; + *code++ = prop_value; + } + repeat_max -= repeat_min; + + if (repeat_max == 1) + { + *code++ = OP_QUERY + repeat_type; + } + else + { + *code++ = OP_UPTO + repeat_type; + PUT2INC(code, 0, repeat_max); + } + } + } + + /* The character or character type itself comes last in all cases. */ + +#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 + if (utf && (c & UTF_LENGTH) != 0) + { + memcpy(code, utf_chars, IN_UCHARS(c & 7)); + code += c & 7; + } + else +#endif + *code++ = c; + + /* For a repeated Unicode property match, there are two extra bytes that + define the required property. */ + +#ifdef SUPPORT_UCP + if (prop_type >= 0) + { + *code++ = prop_type; + *code++ = prop_value; + } +#endif + } + + /* If previous was a character class or a back reference, we put the repeat + stuff after it, but just skip the item if the repeat was {0,0}. */ + + else if (*previous == OP_CLASS || *previous == OP_NCLASS || +#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 + *previous == OP_XCLASS || +#endif + *previous == OP_REF || *previous == OP_REFI || + *previous == OP_DNREF || *previous == OP_DNREFI) + { + if (repeat_max == 0) + { + code = previous; + goto END_REPEAT; + } + + if (repeat_min == 0 && repeat_max == -1) + *code++ = OP_CRSTAR + repeat_type; + else if (repeat_min == 1 && repeat_max == -1) + *code++ = OP_CRPLUS + repeat_type; + else if (repeat_min == 0 && repeat_max == 1) + *code++ = OP_CRQUERY + repeat_type; + else + { + *code++ = OP_CRRANGE + repeat_type; + PUT2INC(code, 0, repeat_min); + if (repeat_max == -1) repeat_max = 0; /* 2-byte encoding for max */ + PUT2INC(code, 0, repeat_max); + } + } + + /* If previous was a bracket group, we may have to replicate it in certain + cases. Note that at this point we can encounter only the "basic" bracket + opcodes such as BRA and CBRA, as this is the place where they get converted + into the more special varieties such as BRAPOS and SBRA. A test for >= + OP_ASSERT and <= OP_COND includes ASSERT, ASSERT_NOT, ASSERTBACK, + ASSERTBACK_NOT, ONCE, ONCE_NC, BRA, BRAPOS, CBRA, CBRAPOS, and COND. + Originally, PCRE did not allow repetition of assertions, but now it does, + for Perl compatibility. */ + + else if (*previous >= OP_ASSERT && *previous <= OP_COND) + { + register int i; + int len = (int)(code - previous); + pcre_uchar *bralink = NULL; + pcre_uchar *brazeroptr = NULL; + + /* Repeating a DEFINE group is pointless, but Perl allows the syntax, so + we just ignore the repeat. */ + + if (*previous == OP_COND && previous[LINK_SIZE+1] == OP_DEF) + goto END_REPEAT; + + /* There is no sense in actually repeating assertions. The only potential + use of repetition is in cases when the assertion is optional. Therefore, + if the minimum is greater than zero, just ignore the repeat. If the + maximum is not zero or one, set it to 1. */ + + if (*previous < OP_ONCE) /* Assertion */ + { + if (repeat_min > 0) goto END_REPEAT; + if (repeat_max < 0 || repeat_max > 1) repeat_max = 1; + } + + /* The case of a zero minimum is special because of the need to stick + OP_BRAZERO in front of it, and because the group appears once in the + data, whereas in other cases it appears the minimum number of times. For + this reason, it is simplest to treat this case separately, as otherwise + the code gets far too messy. There are several special subcases when the + minimum is zero. */ + + if (repeat_min == 0) + { + /* If the maximum is also zero, we used to just omit the group from the + output altogether, like this: + + ** if (repeat_max == 0) + ** { + ** code = previous; + ** goto END_REPEAT; + ** } + + However, that fails when a group or a subgroup within it is referenced + as a subroutine from elsewhere in the pattern, so now we stick in + OP_SKIPZERO in front of it so that it is skipped on execution. As we + don't have a list of which groups are referenced, we cannot do this + selectively. + + If the maximum is 1 or unlimited, we just have to stick in the BRAZERO + and do no more at this point. However, we do need to adjust any + OP_RECURSE calls inside the group that refer to the group itself or any + internal or forward referenced group, because the offset is from the + start of the whole regex. Temporarily terminate the pattern while doing + this. */ + + if (repeat_max <= 1) /* Covers 0, 1, and unlimited */ + { + *code = OP_END; + adjust_recurse(previous, 1, utf, cd, save_hwm); + memmove(previous + 1, previous, IN_UCHARS(len)); + code++; + if (repeat_max == 0) + { + *previous++ = OP_SKIPZERO; + goto END_REPEAT; + } + brazeroptr = previous; /* Save for possessive optimizing */ + *previous++ = OP_BRAZERO + repeat_type; + } + + /* If the maximum is greater than 1 and limited, we have to replicate + in a nested fashion, sticking OP_BRAZERO before each set of brackets. + The first one has to be handled carefully because it's the original + copy, which has to be moved up. The remainder can be handled by code + that is common with the non-zero minimum case below. We have to + adjust the value or repeat_max, since one less copy is required. Once + again, we may have to adjust any OP_RECURSE calls inside the group. */ + + else + { + int offset; + *code = OP_END; + adjust_recurse(previous, 2 + LINK_SIZE, utf, cd, save_hwm); + memmove(previous + 2 + LINK_SIZE, previous, IN_UCHARS(len)); + code += 2 + LINK_SIZE; + *previous++ = OP_BRAZERO + repeat_type; + *previous++ = OP_BRA; + + /* We chain together the bracket offset fields that have to be + filled in later when the ends of the brackets are reached. */ + + offset = (bralink == NULL)? 0 : (int)(previous - bralink); + bralink = previous; + PUTINC(previous, 0, offset); + } + + repeat_max--; + } + + /* If the minimum is greater than zero, replicate the group as many + times as necessary, and adjust the maximum to the number of subsequent + copies that we need. If we set a first char from the group, and didn't + set a required char, copy the latter from the former. If there are any + forward reference subroutine calls in the group, there will be entries on + the workspace list; replicate these with an appropriate increment. */ + + else + { + if (repeat_min > 1) + { + /* In the pre-compile phase, we don't actually do the replication. We + just adjust the length as if we had. Do some paranoid checks for + potential integer overflow. The INT64_OR_DOUBLE type is a 64-bit + integer type when available, otherwise double. */ + + if (lengthptr != NULL) + { + int delta = (repeat_min - 1)*length_prevgroup; + if ((INT64_OR_DOUBLE)(repeat_min - 1)* + (INT64_OR_DOUBLE)length_prevgroup > + (INT64_OR_DOUBLE)INT_MAX || + OFLOW_MAX - *lengthptr < delta) + { + *errorcodeptr = ERR20; + goto FAILED; + } + *lengthptr += delta; + } + + /* This is compiling for real. If there is a set first byte for + the group, and we have not yet set a "required byte", set it. Make + sure there is enough workspace for copying forward references before + doing the copy. */ + + else + { + if (groupsetfirstchar && reqcharflags < 0) + { + reqchar = firstchar; + reqcharflags = firstcharflags; + } + + for (i = 1; i < repeat_min; i++) + { + pcre_uchar *hc; + pcre_uchar *this_hwm = cd->hwm; + memcpy(code, previous, IN_UCHARS(len)); + + while (cd->hwm > cd->start_workspace + cd->workspace_size - + WORK_SIZE_SAFETY_MARGIN - (this_hwm - save_hwm)) + { + size_t save_offset = save_hwm - cd->start_workspace; + size_t this_offset = this_hwm - cd->start_workspace; + *errorcodeptr = expand_workspace(cd); + if (*errorcodeptr != 0) goto FAILED; + save_hwm = (pcre_uchar *)cd->start_workspace + save_offset; + this_hwm = (pcre_uchar *)cd->start_workspace + this_offset; + } + + for (hc = save_hwm; hc < this_hwm; hc += LINK_SIZE) + { + PUT(cd->hwm, 0, GET(hc, 0) + len); + cd->hwm += LINK_SIZE; + } + save_hwm = this_hwm; + code += len; + } + } + } + + if (repeat_max > 0) repeat_max -= repeat_min; + } + + /* This code is common to both the zero and non-zero minimum cases. If + the maximum is limited, it replicates the group in a nested fashion, + remembering the bracket starts on a stack. In the case of a zero minimum, + the first one was set up above. In all cases the repeat_max now specifies + the number of additional copies needed. Again, we must remember to + replicate entries on the forward reference list. */ + + if (repeat_max >= 0) + { + /* In the pre-compile phase, we don't actually do the replication. We + just adjust the length as if we had. For each repetition we must add 1 + to the length for BRAZERO and for all but the last repetition we must + add 2 + 2*LINKSIZE to allow for the nesting that occurs. Do some + paranoid checks to avoid integer overflow. The INT64_OR_DOUBLE type is + a 64-bit integer type when available, otherwise double. */ + + if (lengthptr != NULL && repeat_max > 0) + { + int delta = repeat_max * (length_prevgroup + 1 + 2 + 2*LINK_SIZE) - + 2 - 2*LINK_SIZE; /* Last one doesn't nest */ + if ((INT64_OR_DOUBLE)repeat_max * + (INT64_OR_DOUBLE)(length_prevgroup + 1 + 2 + 2*LINK_SIZE) + > (INT64_OR_DOUBLE)INT_MAX || + OFLOW_MAX - *lengthptr < delta) + { + *errorcodeptr = ERR20; + goto FAILED; + } + *lengthptr += delta; + } + + /* This is compiling for real */ + + else for (i = repeat_max - 1; i >= 0; i--) + { + pcre_uchar *hc; + pcre_uchar *this_hwm = cd->hwm; + + *code++ = OP_BRAZERO + repeat_type; + + /* All but the final copy start a new nesting, maintaining the + chain of brackets outstanding. */ + + if (i != 0) + { + int offset; + *code++ = OP_BRA; + offset = (bralink == NULL)? 0 : (int)(code - bralink); + bralink = code; + PUTINC(code, 0, offset); + } + + memcpy(code, previous, IN_UCHARS(len)); + + /* Ensure there is enough workspace for forward references before + copying them. */ + + while (cd->hwm > cd->start_workspace + cd->workspace_size - + WORK_SIZE_SAFETY_MARGIN - (this_hwm - save_hwm)) + { + size_t save_offset = save_hwm - cd->start_workspace; + size_t this_offset = this_hwm - cd->start_workspace; + *errorcodeptr = expand_workspace(cd); + if (*errorcodeptr != 0) goto FAILED; + save_hwm = (pcre_uchar *)cd->start_workspace + save_offset; + this_hwm = (pcre_uchar *)cd->start_workspace + this_offset; + } + + for (hc = save_hwm; hc < this_hwm; hc += LINK_SIZE) + { + PUT(cd->hwm, 0, GET(hc, 0) + len + ((i != 0)? 2+LINK_SIZE : 1)); + cd->hwm += LINK_SIZE; + } + save_hwm = this_hwm; + code += len; + } + + /* Now chain through the pending brackets, and fill in their length + fields (which are holding the chain links pro tem). */ + + while (bralink != NULL) + { + int oldlinkoffset; + int offset = (int)(code - bralink + 1); + pcre_uchar *bra = code - offset; + oldlinkoffset = GET(bra, 1); + bralink = (oldlinkoffset == 0)? NULL : bralink - oldlinkoffset; + *code++ = OP_KET; + PUTINC(code, 0, offset); + PUT(bra, 1, offset); + } + } + + /* If the maximum is unlimited, set a repeater in the final copy. For + ONCE brackets, that's all we need to do. However, possessively repeated + ONCE brackets can be converted into non-capturing brackets, as the + behaviour of (?:xx)++ is the same as (?>xx)++ and this saves having to + deal with possessive ONCEs specially. + + Otherwise, when we are doing the actual compile phase, check to see + whether this group is one that could match an empty string. If so, + convert the initial operator to the S form (e.g. OP_BRA -> OP_SBRA) so + that runtime checking can be done. [This check is also applied to ONCE + groups at runtime, but in a different way.] + + Then, if the quantifier was possessive and the bracket is not a + conditional, we convert the BRA code to the POS form, and the KET code to + KETRPOS. (It turns out to be convenient at runtime to detect this kind of + subpattern at both the start and at the end.) The use of special opcodes + makes it possible to reduce greatly the stack usage in pcre_exec(). If + the group is preceded by OP_BRAZERO, convert this to OP_BRAPOSZERO. + + Then, if the minimum number of matches is 1 or 0, cancel the possessive + flag so that the default action below, of wrapping everything inside + atomic brackets, does not happen. When the minimum is greater than 1, + there will be earlier copies of the group, and so we still have to wrap + the whole thing. */ + + else + { + pcre_uchar *ketcode = code - 1 - LINK_SIZE; + pcre_uchar *bracode = ketcode - GET(ketcode, 1); + + /* Convert possessive ONCE brackets to non-capturing */ + + if ((*bracode == OP_ONCE || *bracode == OP_ONCE_NC) && + possessive_quantifier) *bracode = OP_BRA; + + /* For non-possessive ONCE brackets, all we need to do is to + set the KET. */ + + if (*bracode == OP_ONCE || *bracode == OP_ONCE_NC) + *ketcode = OP_KETRMAX + repeat_type; + + /* Handle non-ONCE brackets and possessive ONCEs (which have been + converted to non-capturing above). */ + + else + { + /* In the compile phase, check for empty string matching. */ + + if (lengthptr == NULL) + { + pcre_uchar *scode = bracode; + do + { + if (could_be_empty_branch(scode, ketcode, utf, cd, NULL)) + { + *bracode += OP_SBRA - OP_BRA; + break; + } + scode += GET(scode, 1); + } + while (*scode == OP_ALT); + } + + /* Handle possessive quantifiers. */ + + if (possessive_quantifier) + { + /* For COND brackets, we wrap the whole thing in a possessively + repeated non-capturing bracket, because we have not invented POS + versions of the COND opcodes. Because we are moving code along, we + must ensure that any pending recursive references are updated. */ + + if (*bracode == OP_COND || *bracode == OP_SCOND) + { + int nlen = (int)(code - bracode); + *code = OP_END; + adjust_recurse(bracode, 1 + LINK_SIZE, utf, cd, save_hwm); + memmove(bracode + 1 + LINK_SIZE, bracode, IN_UCHARS(nlen)); + code += 1 + LINK_SIZE; + nlen += 1 + LINK_SIZE; + *bracode = OP_BRAPOS; + *code++ = OP_KETRPOS; + PUTINC(code, 0, nlen); + PUT(bracode, 1, nlen); + } + + /* For non-COND brackets, we modify the BRA code and use KETRPOS. */ + + else + { + *bracode += 1; /* Switch to xxxPOS opcodes */ + *ketcode = OP_KETRPOS; + } + + /* If the minimum is zero, mark it as possessive, then unset the + possessive flag when the minimum is 0 or 1. */ + + if (brazeroptr != NULL) *brazeroptr = OP_BRAPOSZERO; + if (repeat_min < 2) possessive_quantifier = FALSE; + } + + /* Non-possessive quantifier */ + + else *ketcode = OP_KETRMAX + repeat_type; + } + } + } + + /* If previous is OP_FAIL, it was generated by an empty class [] in + JavaScript mode. The other ways in which OP_FAIL can be generated, that is + by (*FAIL) or (?!) set previous to NULL, which gives a "nothing to repeat" + error above. We can just ignore the repeat in JS case. */ + + else if (*previous == OP_FAIL) goto END_REPEAT; + + /* Else there's some kind of shambles */ + + else + { + *errorcodeptr = ERR11; + goto FAILED; + } + + /* If the character following a repeat is '+', possessive_quantifier is + TRUE. For some opcodes, there are special alternative opcodes for this + case. For anything else, we wrap the entire repeated item inside OP_ONCE + brackets. Logically, the '+' notation is just syntactic sugar, taken from + Sun's Java package, but the special opcodes can optimize it. + + Some (but not all) possessively repeated subpatterns have already been + completely handled in the code just above. For them, possessive_quantifier + is always FALSE at this stage. Note that the repeated item starts at + tempcode, not at previous, which might be the first part of a string whose + (former) last char we repeated. */ + + if (possessive_quantifier) + { + int len; + + /* Possessifying an EXACT quantifier has no effect, so we can ignore it. + However, QUERY, STAR, or UPTO may follow (for quantifiers such as {5,6}, + {5,}, or {5,10}). We skip over an EXACT item; if the length of what + remains is greater than zero, there's a further opcode that can be + handled. If not, do nothing, leaving the EXACT alone. */ + + switch(*tempcode) + { + case OP_TYPEEXACT: + tempcode += PRIV(OP_lengths)[*tempcode] + + ((tempcode[1 + IMM2_SIZE] == OP_PROP + || tempcode[1 + IMM2_SIZE] == OP_NOTPROP)? 2 : 0); + break; + + /* CHAR opcodes are used for exacts whose count is 1. */ + + case OP_CHAR: + case OP_CHARI: + case OP_NOT: + case OP_NOTI: + case OP_EXACT: + case OP_EXACTI: + case OP_NOTEXACT: + case OP_NOTEXACTI: + tempcode += PRIV(OP_lengths)[*tempcode]; +#ifdef SUPPORT_UTF + if (utf && HAS_EXTRALEN(tempcode[-1])) + tempcode += GET_EXTRALEN(tempcode[-1]); +#endif + break; + + /* For the class opcodes, the repeat operator appears at the end; + adjust tempcode to point to it. */ + + case OP_CLASS: + case OP_NCLASS: + tempcode += 1 + 32/sizeof(pcre_uchar); + break; + +#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 + case OP_XCLASS: + tempcode += GET(tempcode, 1); + break; +#endif + } + + /* If tempcode is equal to code (which points to the end of the repeated + item), it means we have skipped an EXACT item but there is no following + QUERY, STAR, or UPTO; the value of len will be 0, and we do nothing. In + all other cases, tempcode will be pointing to the repeat opcode, and will + be less than code, so the value of len will be greater than 0. */ + + len = (int)(code - tempcode); + if (len > 0) + { + unsigned int repcode = *tempcode; + + /* There is a table for possessifying opcodes, all of which are less + than OP_CALLOUT. A zero entry means there is no possessified version. + */ + + if (repcode < OP_CALLOUT && opcode_possessify[repcode] > 0) + *tempcode = opcode_possessify[repcode]; + + /* For opcode without a special possessified version, wrap the item in + ONCE brackets. Because we are moving code along, we must ensure that any + pending recursive references are updated. */ + + else + { + *code = OP_END; + adjust_recurse(tempcode, 1 + LINK_SIZE, utf, cd, save_hwm); + memmove(tempcode + 1 + LINK_SIZE, tempcode, IN_UCHARS(len)); + code += 1 + LINK_SIZE; + len += 1 + LINK_SIZE; + tempcode[0] = OP_ONCE; + *code++ = OP_KET; + PUTINC(code, 0, len); + PUT(tempcode, 1, len); + } + } + +#ifdef NEVER + if (len > 0) switch (*tempcode) + { + case OP_STAR: *tempcode = OP_POSSTAR; break; + case OP_PLUS: *tempcode = OP_POSPLUS; break; + case OP_QUERY: *tempcode = OP_POSQUERY; break; + case OP_UPTO: *tempcode = OP_POSUPTO; break; + + case OP_STARI: *tempcode = OP_POSSTARI; break; + case OP_PLUSI: *tempcode = OP_POSPLUSI; break; + case OP_QUERYI: *tempcode = OP_POSQUERYI; break; + case OP_UPTOI: *tempcode = OP_POSUPTOI; break; + + case OP_NOTSTAR: *tempcode = OP_NOTPOSSTAR; break; + case OP_NOTPLUS: *tempcode = OP_NOTPOSPLUS; break; + case OP_NOTQUERY: *tempcode = OP_NOTPOSQUERY; break; + case OP_NOTUPTO: *tempcode = OP_NOTPOSUPTO; break; + + case OP_NOTSTARI: *tempcode = OP_NOTPOSSTARI; break; + case OP_NOTPLUSI: *tempcode = OP_NOTPOSPLUSI; break; + case OP_NOTQUERYI: *tempcode = OP_NOTPOSQUERYI; break; + case OP_NOTUPTOI: *tempcode = OP_NOTPOSUPTOI; break; + + case OP_TYPESTAR: *tempcode = OP_TYPEPOSSTAR; break; + case OP_TYPEPLUS: *tempcode = OP_TYPEPOSPLUS; break; + case OP_TYPEQUERY: *tempcode = OP_TYPEPOSQUERY; break; + case OP_TYPEUPTO: *tempcode = OP_TYPEPOSUPTO; break; + + case OP_CRSTAR: *tempcode = OP_CRPOSSTAR; break; + case OP_CRPLUS: *tempcode = OP_CRPOSPLUS; break; + case OP_CRQUERY: *tempcode = OP_CRPOSQUERY; break; + case OP_CRRANGE: *tempcode = OP_CRPOSRANGE; break; + + /* Because we are moving code along, we must ensure that any + pending recursive references are updated. */ + + default: + *code = OP_END; + adjust_recurse(tempcode, 1 + LINK_SIZE, utf, cd, save_hwm); + memmove(tempcode + 1 + LINK_SIZE, tempcode, IN_UCHARS(len)); + code += 1 + LINK_SIZE; + len += 1 + LINK_SIZE; + tempcode[0] = OP_ONCE; + *code++ = OP_KET; + PUTINC(code, 0, len); + PUT(tempcode, 1, len); + break; + } +#endif + } + + /* In all case we no longer have a previous item. We also set the + "follows varying string" flag for subsequently encountered reqchars if + it isn't already set and we have just passed a varying length item. */ + + END_REPEAT: + previous = NULL; + cd->req_varyopt |= reqvary; + break; + + + /* ===================================================================*/ + /* Start of nested parenthesized sub-expression, or comment or lookahead or + lookbehind or option setting or condition or all the other extended + parenthesis forms. */ + + case CHAR_LEFT_PARENTHESIS: + newoptions = options; + skipbytes = 0; + bravalue = OP_CBRA; + save_hwm = cd->hwm; + reset_bracount = FALSE; + + /* First deal with various "verbs" that can be introduced by '*'. */ + + ptr++; + if (ptr[0] == CHAR_ASTERISK && (ptr[1] == ':' + || (MAX_255(ptr[1]) && ((cd->ctypes[ptr[1]] & ctype_letter) != 0)))) + { + int i, namelen; + int arglen = 0; + const char *vn = verbnames; + const pcre_uchar *name = ptr + 1; + const pcre_uchar *arg = NULL; + previous = NULL; + ptr++; + while (MAX_255(*ptr) && (cd->ctypes[*ptr] & ctype_letter) != 0) ptr++; + namelen = (int)(ptr - name); + + /* It appears that Perl allows any characters whatsoever, other than + a closing parenthesis, to appear in arguments, so we no longer insist on + letters, digits, and underscores. */ + + if (*ptr == CHAR_COLON) + { + arg = ++ptr; + while (*ptr != CHAR_NULL && *ptr != CHAR_RIGHT_PARENTHESIS) ptr++; + arglen = (int)(ptr - arg); + if ((unsigned int)arglen > MAX_MARK) + { + *errorcodeptr = ERR75; + goto FAILED; + } + } + + if (*ptr != CHAR_RIGHT_PARENTHESIS) + { + *errorcodeptr = ERR60; + goto FAILED; + } + + /* Scan the table of verb names */ + + for (i = 0; i < verbcount; i++) + { + if (namelen == verbs[i].len && + STRNCMP_UC_C8(name, vn, namelen) == 0) + { + int setverb; + + /* Check for open captures before ACCEPT and convert it to + ASSERT_ACCEPT if in an assertion. */ + + if (verbs[i].op == OP_ACCEPT) + { + open_capitem *oc; + if (arglen != 0) + { + *errorcodeptr = ERR59; + goto FAILED; + } + cd->had_accept = TRUE; + for (oc = cd->open_caps; oc != NULL; oc = oc->next) + { + *code++ = OP_CLOSE; + PUT2INC(code, 0, oc->number); + } + setverb = *code++ = + (cd->assert_depth > 0)? OP_ASSERT_ACCEPT : OP_ACCEPT; + + /* Do not set firstchar after *ACCEPT */ + if (firstcharflags == REQ_UNSET) firstcharflags = REQ_NONE; + } + + /* Handle other cases with/without an argument */ + + else if (arglen == 0) + { + if (verbs[i].op < 0) /* Argument is mandatory */ + { + *errorcodeptr = ERR66; + goto FAILED; + } + setverb = *code++ = verbs[i].op; + } + + else + { + if (verbs[i].op_arg < 0) /* Argument is forbidden */ + { + *errorcodeptr = ERR59; + goto FAILED; + } + setverb = *code++ = verbs[i].op_arg; + *code++ = arglen; + memcpy(code, arg, IN_UCHARS(arglen)); + code += arglen; + *code++ = 0; + } + + switch (setverb) + { + case OP_THEN: + case OP_THEN_ARG: + cd->external_flags |= PCRE_HASTHEN; + break; + + case OP_PRUNE: + case OP_PRUNE_ARG: + case OP_SKIP: + case OP_SKIP_ARG: + cd->had_pruneorskip = TRUE; + break; + } + + break; /* Found verb, exit loop */ + } + + vn += verbs[i].len + 1; + } + + if (i < verbcount) continue; /* Successfully handled a verb */ + *errorcodeptr = ERR60; /* Verb not recognized */ + goto FAILED; + } + + /* Deal with the extended parentheses; all are introduced by '?', and the + appearance of any of them means that this is not a capturing group. */ + + else if (*ptr == CHAR_QUESTION_MARK) + { + int i, set, unset, namelen; + int *optset; + const pcre_uchar *name; + pcre_uchar *slot; + + switch (*(++ptr)) + { + case CHAR_NUMBER_SIGN: /* Comment; skip to ket */ + ptr++; + while (*ptr != CHAR_NULL && *ptr != CHAR_RIGHT_PARENTHESIS) ptr++; + if (*ptr == CHAR_NULL) + { + *errorcodeptr = ERR18; + goto FAILED; + } + continue; + + + /* ------------------------------------------------------------ */ + case CHAR_VERTICAL_LINE: /* Reset capture count for each branch */ + reset_bracount = TRUE; + /* Fall through */ + + /* ------------------------------------------------------------ */ + case CHAR_COLON: /* Non-capturing bracket */ + bravalue = OP_BRA; + ptr++; + break; + + + /* ------------------------------------------------------------ */ + case CHAR_LEFT_PARENTHESIS: + bravalue = OP_COND; /* Conditional group */ + tempptr = ptr; + + /* A condition can be an assertion, a number (referring to a numbered + group's having been set), a name (referring to a named group), or 'R', + referring to recursion. R and R&name are also permitted for + recursion tests. + + There are ways of testing a named group: (?(name)) is used by Python; + Perl 5.10 onwards uses (?() or (?('name')). + + There is one unfortunate ambiguity, caused by history. 'R' can be the + recursive thing or the name 'R' (and similarly for 'R' followed by + digits). We look for a name first; if not found, we try the other case. + + For compatibility with auto-callouts, we allow a callout to be + specified before a condition that is an assertion. First, check for the + syntax of a callout; if found, adjust the temporary pointer that is + used to check for an assertion condition. That's all that is needed! */ + + if (ptr[1] == CHAR_QUESTION_MARK && ptr[2] == CHAR_C) + { + for (i = 3;; i++) if (!IS_DIGIT(ptr[i])) break; + if (ptr[i] == CHAR_RIGHT_PARENTHESIS) + tempptr += i + 1; + } + + /* For conditions that are assertions, check the syntax, and then exit + the switch. This will take control down to where bracketed groups, + including assertions, are processed. */ + + if (tempptr[1] == CHAR_QUESTION_MARK && + (tempptr[2] == CHAR_EQUALS_SIGN || + tempptr[2] == CHAR_EXCLAMATION_MARK || + tempptr[2] == CHAR_LESS_THAN_SIGN)) + break; + + /* Other conditions use OP_CREF/OP_DNCREF/OP_RREF/OP_DNRREF, and all + need to skip at least 1+IMM2_SIZE bytes at the start of the group. */ + + code[1+LINK_SIZE] = OP_CREF; + skipbytes = 1+IMM2_SIZE; + refsign = -1; /* => not a number */ + namelen = -1; /* => not a name; must set to avoid warning */ + name = NULL; /* Always set to avoid warning */ + recno = 0; /* Always set to avoid warning */ + + /* Check for a test for recursion in a named group. */ + + ptr++; + if (*ptr == CHAR_R && ptr[1] == CHAR_AMPERSAND) + { + terminator = -1; + ptr += 2; + code[1+LINK_SIZE] = OP_RREF; /* Change the type of test */ + } + + /* Check for a test for a named group's having been set, using the Perl + syntax (?() or (?('name'), and also allow for the original PCRE + syntax of (?(name) or for (?(+n), (?(-n), and just (?(n). */ + + else if (*ptr == CHAR_LESS_THAN_SIGN) + { + terminator = CHAR_GREATER_THAN_SIGN; + ptr++; + } + else if (*ptr == CHAR_APOSTROPHE) + { + terminator = CHAR_APOSTROPHE; + ptr++; + } + else + { + terminator = CHAR_NULL; + if (*ptr == CHAR_MINUS || *ptr == CHAR_PLUS) refsign = *ptr++; + else if (IS_DIGIT(*ptr)) refsign = 0; + } + + /* Handle a number */ + + if (refsign >= 0) + { + while (IS_DIGIT(*ptr)) + { + recno = recno * 10 + (int)(*ptr - CHAR_0); + ptr++; + } + } + + /* Otherwise we expect to read a name; anything else is an error. When + a name is one of a number of duplicates, a different opcode is used and + it needs more memory. Unfortunately we cannot tell whether a name is a + duplicate in the first pass, so we have to allow for more memory. */ + + else + { + if (IS_DIGIT(*ptr)) + { + *errorcodeptr = ERR84; + goto FAILED; + } + if (!MAX_255(*ptr) || (cd->ctypes[*ptr] & ctype_word) == 0) + { + *errorcodeptr = ERR28; /* Assertion expected */ + goto FAILED; + } + name = ptr++; + while (MAX_255(*ptr) && (cd->ctypes[*ptr] & ctype_word) != 0) + { + ptr++; + } + namelen = (int)(ptr - name); + if (lengthptr != NULL && (options & PCRE_DUPNAMES) != 0) + *lengthptr += IMM2_SIZE; + } + + /* Check the terminator */ + + if ((terminator > 0 && *ptr++ != (pcre_uchar)terminator) || + *ptr++ != CHAR_RIGHT_PARENTHESIS) + { + ptr--; /* Error offset */ + *errorcodeptr = ERR26; /* Malformed number or name */ + goto FAILED; + } + + /* Do no further checking in the pre-compile phase. */ + + if (lengthptr != NULL) break; + + /* In the real compile we do the work of looking for the actual + reference. If refsign is not negative, it means we have a number in + recno. */ + + if (refsign >= 0) + { + if (recno <= 0) + { + *errorcodeptr = ERR35; + goto FAILED; + } + if (refsign != 0) recno = (refsign == CHAR_MINUS)? + cd->bracount - recno + 1 : recno + cd->bracount; + if (recno <= 0 || recno > cd->final_bracount) + { + *errorcodeptr = ERR15; + goto FAILED; + } + PUT2(code, 2+LINK_SIZE, recno); + break; + } + + /* Otherwise look for the name. */ + + slot = cd->name_table; + for (i = 0; i < cd->names_found; i++) + { + if (STRNCMP_UC_UC(name, slot+IMM2_SIZE, namelen) == 0) break; + slot += cd->name_entry_size; + } + + /* Found the named subpattern. If the name is duplicated, add one to + the opcode to change CREF/RREF into DNCREF/DNRREF and insert + appropriate data values. Otherwise, just insert the unique subpattern + number. */ + + if (i < cd->names_found) + { + int offset = i++; + int count = 1; + recno = GET2(slot, 0); /* Number from first found */ + for (; i < cd->names_found; i++) + { + slot += cd->name_entry_size; + if (STRNCMP_UC_UC(name, slot+IMM2_SIZE, namelen) != 0 || + (slot+IMM2_SIZE)[namelen] != 0) break; + count++; + } + + if (count > 1) + { + PUT2(code, 2+LINK_SIZE, offset); + PUT2(code, 2+LINK_SIZE+IMM2_SIZE, count); + skipbytes += IMM2_SIZE; + code[1+LINK_SIZE]++; + } + else /* Not a duplicated name */ + { + PUT2(code, 2+LINK_SIZE, recno); + } + } + + /* If terminator == CHAR_NULL it means that the name followed directly + after the opening parenthesis [e.g. (?(abc)...] and in this case there + are some further alternatives to try. For the cases where terminator != + CHAR_NULL [things like (?(... or (?('name')... or (?(R&name)... ] + we have now checked all the possibilities, so give an error. */ + + else if (terminator != CHAR_NULL) + { + *errorcodeptr = ERR15; + goto FAILED; + } + + /* Check for (?(R) for recursion. Allow digits after R to specify a + specific group number. */ + + else if (*name == CHAR_R) + { + recno = 0; + for (i = 1; i < namelen; i++) + { + if (!IS_DIGIT(name[i])) + { + *errorcodeptr = ERR15; + goto FAILED; + } + recno = recno * 10 + name[i] - CHAR_0; + } + if (recno == 0) recno = RREF_ANY; + code[1+LINK_SIZE] = OP_RREF; /* Change test type */ + PUT2(code, 2+LINK_SIZE, recno); + } + + /* Similarly, check for the (?(DEFINE) "condition", which is always + false. */ + + else if (namelen == 6 && STRNCMP_UC_C8(name, STRING_DEFINE, 6) == 0) + { + code[1+LINK_SIZE] = OP_DEF; + skipbytes = 1; + } + + /* Reference to an unidentified subpattern. */ + + else + { + *errorcodeptr = ERR15; + goto FAILED; + } + break; + + + /* ------------------------------------------------------------ */ + case CHAR_EQUALS_SIGN: /* Positive lookahead */ + bravalue = OP_ASSERT; + cd->assert_depth += 1; + ptr++; + break; + + /* Optimize (?!) to (*FAIL) unless it is quantified - which is a weird + thing to do, but Perl allows all assertions to be quantified, and when + they contain capturing parentheses there may be a potential use for + this feature. Not that that applies to a quantified (?!) but we allow + it for uniformity. */ + + /* ------------------------------------------------------------ */ + case CHAR_EXCLAMATION_MARK: /* Negative lookahead */ + ptr++; + if (*ptr == CHAR_RIGHT_PARENTHESIS && ptr[1] != CHAR_ASTERISK && + ptr[1] != CHAR_PLUS && ptr[1] != CHAR_QUESTION_MARK && + (ptr[1] != CHAR_LEFT_CURLY_BRACKET || !is_counted_repeat(ptr+2))) + { + *code++ = OP_FAIL; + previous = NULL; + continue; + } + bravalue = OP_ASSERT_NOT; + cd->assert_depth += 1; + break; + + + /* ------------------------------------------------------------ */ + case CHAR_LESS_THAN_SIGN: /* Lookbehind or named define */ + switch (ptr[1]) + { + case CHAR_EQUALS_SIGN: /* Positive lookbehind */ + bravalue = OP_ASSERTBACK; + cd->assert_depth += 1; + ptr += 2; + break; + + case CHAR_EXCLAMATION_MARK: /* Negative lookbehind */ + bravalue = OP_ASSERTBACK_NOT; + cd->assert_depth += 1; + ptr += 2; + break; + + default: /* Could be name define, else bad */ + if (MAX_255(ptr[1]) && (cd->ctypes[ptr[1]] & ctype_word) != 0) + goto DEFINE_NAME; + ptr++; /* Correct offset for error */ + *errorcodeptr = ERR24; + goto FAILED; + } + break; + + + /* ------------------------------------------------------------ */ + case CHAR_GREATER_THAN_SIGN: /* One-time brackets */ + bravalue = OP_ONCE; + ptr++; + break; + + + /* ------------------------------------------------------------ */ + case CHAR_C: /* Callout - may be followed by digits; */ + previous_callout = code; /* Save for later completion */ + after_manual_callout = 1; /* Skip one item before completing */ + *code++ = OP_CALLOUT; + { + int n = 0; + ptr++; + while(IS_DIGIT(*ptr)) + n = n * 10 + *ptr++ - CHAR_0; + if (*ptr != CHAR_RIGHT_PARENTHESIS) + { + *errorcodeptr = ERR39; + goto FAILED; + } + if (n > 255) + { + *errorcodeptr = ERR38; + goto FAILED; + } + *code++ = n; + PUT(code, 0, (int)(ptr - cd->start_pattern + 1)); /* Pattern offset */ + PUT(code, LINK_SIZE, 0); /* Default length */ + code += 2 * LINK_SIZE; + } + previous = NULL; + continue; + + + /* ------------------------------------------------------------ */ + case CHAR_P: /* Python-style named subpattern handling */ + if (*(++ptr) == CHAR_EQUALS_SIGN || + *ptr == CHAR_GREATER_THAN_SIGN) /* Reference or recursion */ + { + is_recurse = *ptr == CHAR_GREATER_THAN_SIGN; + terminator = CHAR_RIGHT_PARENTHESIS; + goto NAMED_REF_OR_RECURSE; + } + else if (*ptr != CHAR_LESS_THAN_SIGN) /* Test for Python-style defn */ + { + *errorcodeptr = ERR41; + goto FAILED; + } + /* Fall through to handle (?P< as (?< is handled */ + + + /* ------------------------------------------------------------ */ + DEFINE_NAME: /* Come here from (?< handling */ + case CHAR_APOSTROPHE: + terminator = (*ptr == CHAR_LESS_THAN_SIGN)? + CHAR_GREATER_THAN_SIGN : CHAR_APOSTROPHE; + name = ++ptr; + if (IS_DIGIT(*ptr)) + { + *errorcodeptr = ERR84; /* Group name must start with non-digit */ + goto FAILED; + } + while (MAX_255(*ptr) && (cd->ctypes[*ptr] & ctype_word) != 0) ptr++; + namelen = (int)(ptr - name); + + /* In the pre-compile phase, do a syntax check, remember the longest + name, and then remember the group in a vector, expanding it if + necessary. Duplicates for the same number are skipped; other duplicates + are checked for validity. In the actual compile, there is nothing to + do. */ + + if (lengthptr != NULL) + { + named_group *ng; + pcre_uint32 number = cd->bracount + 1; + + if (*ptr != (pcre_uchar)terminator) + { + *errorcodeptr = ERR42; + goto FAILED; + } + + if (cd->names_found >= MAX_NAME_COUNT) + { + *errorcodeptr = ERR49; + goto FAILED; + } + + if (namelen + IMM2_SIZE + 1 > cd->name_entry_size) + { + cd->name_entry_size = namelen + IMM2_SIZE + 1; + if (namelen > MAX_NAME_SIZE) + { + *errorcodeptr = ERR48; + goto FAILED; + } + } + + /* Scan the list to check for duplicates. For duplicate names, if the + number is the same, break the loop, which causes the name to be + discarded; otherwise, if DUPNAMES is not set, give an error. + If it is set, allow the name with a different number, but continue + scanning in case this is a duplicate with the same number. For + non-duplicate names, give an error if the number is duplicated. */ + + ng = cd->named_groups; + for (i = 0; i < cd->names_found; i++, ng++) + { + if (namelen == ng->length && + STRNCMP_UC_UC(name, ng->name, namelen) == 0) + { + if (ng->number == number) break; + if ((options & PCRE_DUPNAMES) == 0) + { + *errorcodeptr = ERR43; + goto FAILED; + } + cd->dupnames = TRUE; /* Duplicate names exist */ + } + else if (ng->number == number) + { + *errorcodeptr = ERR65; + goto FAILED; + } + } + + if (i >= cd->names_found) /* Not a duplicate with same number */ + { + /* Increase the list size if necessary */ + + if (cd->names_found >= cd->named_group_list_size) + { + int newsize = cd->named_group_list_size * 2; + named_group *newspace = (PUBL(malloc)) + (newsize * sizeof(named_group)); + + if (newspace == NULL) + { + *errorcodeptr = ERR21; + goto FAILED; + } + + memcpy(newspace, cd->named_groups, + cd->named_group_list_size * sizeof(named_group)); + if (cd->named_group_list_size > NAMED_GROUP_LIST_SIZE) + (PUBL(free))((void *)cd->named_groups); + cd->named_groups = newspace; + cd->named_group_list_size = newsize; + } + + cd->named_groups[cd->names_found].name = name; + cd->named_groups[cd->names_found].length = namelen; + cd->named_groups[cd->names_found].number = number; + cd->names_found++; + } + } + + ptr++; /* Move past > or ' in both passes. */ + goto NUMBERED_GROUP; + + + /* ------------------------------------------------------------ */ + case CHAR_AMPERSAND: /* Perl recursion/subroutine syntax */ + terminator = CHAR_RIGHT_PARENTHESIS; + is_recurse = TRUE; + /* Fall through */ + + /* We come here from the Python syntax above that handles both + references (?P=name) and recursion (?P>name), as well as falling + through from the Perl recursion syntax (?&name). We also come here from + the Perl \k or \k'name' back reference syntax and the \k{name} + .NET syntax, and the Oniguruma \g<...> and \g'...' subroutine syntax. */ + + NAMED_REF_OR_RECURSE: + name = ++ptr; + if (IS_DIGIT(*ptr)) + { + *errorcodeptr = ERR84; /* Group name must start with non-digit */ + goto FAILED; + } + while (MAX_255(*ptr) && (cd->ctypes[*ptr] & ctype_word) != 0) ptr++; + namelen = (int)(ptr - name); + + /* In the pre-compile phase, do a syntax check. We used to just set + a dummy reference number, because it was not used in the first pass. + However, with the change of recursive back references to be atomic, + we have to look for the number so that this state can be identified, as + otherwise the incorrect length is computed. If it's not a backwards + reference, the dummy number will do. */ + + if (lengthptr != NULL) + { + named_group *ng; + + if (namelen == 0) + { + *errorcodeptr = ERR62; + goto FAILED; + } + if (*ptr != (pcre_uchar)terminator) + { + *errorcodeptr = ERR42; + goto FAILED; + } + if (namelen > MAX_NAME_SIZE) + { + *errorcodeptr = ERR48; + goto FAILED; + } + + /* The name table does not exist in the first pass; instead we must + scan the list of names encountered so far in order to get the + number. If the name is not found, set the value to 0 for a forward + reference. */ + + ng = cd->named_groups; + for (i = 0; i < cd->names_found; i++, ng++) + { + if (namelen == ng->length && + STRNCMP_UC_UC(name, ng->name, namelen) == 0) + break; + } + recno = (i < cd->names_found)? ng->number : 0; + + /* Count named back references. */ + + if (!is_recurse) cd->namedrefcount++; + + /* If duplicate names are permitted, we have to allow for a named + reference to a duplicated name (this cannot be determined until the + second pass). This needs an extra 16-bit data item. */ + + if ((options & PCRE_DUPNAMES) != 0) *lengthptr += IMM2_SIZE; + } + + /* In the real compile, search the name table. We check the name + first, and then check that we have reached the end of the name in the + table. That way, if the name is longer than any in the table, the + comparison will fail without reading beyond the table entry. */ + + else + { + slot = cd->name_table; + for (i = 0; i < cd->names_found; i++) + { + if (STRNCMP_UC_UC(name, slot+IMM2_SIZE, namelen) == 0 && + slot[IMM2_SIZE+namelen] == 0) + break; + slot += cd->name_entry_size; + } + + if (i < cd->names_found) + { + recno = GET2(slot, 0); + } + else + { + *errorcodeptr = ERR15; + goto FAILED; + } + } + + /* In both phases, for recursions, we can now go to the code than + handles numerical recursion. */ + + if (is_recurse) goto HANDLE_RECURSION; + + /* In the second pass we must see if the name is duplicated. If so, we + generate a different opcode. */ + + if (lengthptr == NULL && cd->dupnames) + { + int count = 1; + unsigned int index = i; + pcre_uchar *cslot = slot + cd->name_entry_size; + + for (i++; i < cd->names_found; i++) + { + if (STRCMP_UC_UC(slot + IMM2_SIZE, cslot + IMM2_SIZE) != 0) break; + + + count++; + cslot += cd->name_entry_size; + } + + if (count > 1) + { + if (firstcharflags == REQ_UNSET) firstcharflags = REQ_NONE; + previous = code; + *code++ = ((options & PCRE_CASELESS) != 0)? OP_DNREFI : OP_DNREF; + PUT2INC(code, 0, index); + PUT2INC(code, 0, count); + + /* Process each potentially referenced group. */ + + for (; slot < cslot; slot += cd->name_entry_size) + { + open_capitem *oc; + recno = GET2(slot, 0); + cd->backref_map |= (recno < 32)? (1 << recno) : 1; + if (recno > cd->top_backref) cd->top_backref = recno; + + /* Check to see if this back reference is recursive, that it, it + is inside the group that it references. A flag is set so that the + group can be made atomic. */ + + for (oc = cd->open_caps; oc != NULL; oc = oc->next) + { + if (oc->number == recno) + { + oc->flag = TRUE; + break; + } + } + } + + continue; /* End of back ref handling */ + } + } + + /* First pass, or a non-duplicated name. */ + + goto HANDLE_REFERENCE; + + + /* ------------------------------------------------------------ */ + case CHAR_R: /* Recursion */ + ptr++; /* Same as (?0) */ + /* Fall through */ + + + /* ------------------------------------------------------------ */ + case CHAR_MINUS: case CHAR_PLUS: /* Recursion or subroutine */ + case CHAR_0: case CHAR_1: case CHAR_2: case CHAR_3: case CHAR_4: + case CHAR_5: case CHAR_6: case CHAR_7: case CHAR_8: case CHAR_9: + { + const pcre_uchar *called; + terminator = CHAR_RIGHT_PARENTHESIS; + + /* Come here from the \g<...> and \g'...' code (Oniguruma + compatibility). However, the syntax has been checked to ensure that + the ... are a (signed) number, so that neither ERR63 nor ERR29 will + be called on this path, nor with the jump to OTHER_CHAR_AFTER_QUERY + ever be taken. */ + + HANDLE_NUMERICAL_RECURSION: + + if ((refsign = *ptr) == CHAR_PLUS) + { + ptr++; + if (!IS_DIGIT(*ptr)) + { + *errorcodeptr = ERR63; + goto FAILED; + } + } + else if (refsign == CHAR_MINUS) + { + if (!IS_DIGIT(ptr[1])) + goto OTHER_CHAR_AFTER_QUERY; + ptr++; + } + + recno = 0; + while(IS_DIGIT(*ptr)) + recno = recno * 10 + *ptr++ - CHAR_0; + + if (*ptr != (pcre_uchar)terminator) + { + *errorcodeptr = ERR29; + goto FAILED; + } + + if (refsign == CHAR_MINUS) + { + if (recno == 0) + { + *errorcodeptr = ERR58; + goto FAILED; + } + recno = cd->bracount - recno + 1; + if (recno <= 0) + { + *errorcodeptr = ERR15; + goto FAILED; + } + } + else if (refsign == CHAR_PLUS) + { + if (recno == 0) + { + *errorcodeptr = ERR58; + goto FAILED; + } + recno += cd->bracount; + } + + /* Come here from code above that handles a named recursion */ + + HANDLE_RECURSION: + + previous = code; + called = cd->start_code; + + /* When we are actually compiling, find the bracket that is being + referenced. Temporarily end the regex in case it doesn't exist before + this point. If we end up with a forward reference, first check that + the bracket does occur later so we can give the error (and position) + now. Then remember this forward reference in the workspace so it can + be filled in at the end. */ + + if (lengthptr == NULL) + { + *code = OP_END; + if (recno != 0) + called = PRIV(find_bracket)(cd->start_code, utf, recno); + + /* Forward reference */ + + if (called == NULL) + { + if (recno > cd->final_bracount) + { + *errorcodeptr = ERR15; + goto FAILED; + } + + /* Fudge the value of "called" so that when it is inserted as an + offset below, what it actually inserted is the reference number + of the group. Then remember the forward reference. */ + + called = cd->start_code + recno; + if (cd->hwm >= cd->start_workspace + cd->workspace_size - + WORK_SIZE_SAFETY_MARGIN) + { + *errorcodeptr = expand_workspace(cd); + if (*errorcodeptr != 0) goto FAILED; + } + PUTINC(cd->hwm, 0, (int)(code + 1 - cd->start_code)); + } + + /* If not a forward reference, and the subpattern is still open, + this is a recursive call. We check to see if this is a left + recursion that could loop for ever, and diagnose that case. We + must not, however, do this check if we are in a conditional + subpattern because the condition might be testing for recursion in + a pattern such as /(?(R)a+|(?R)b)/, which is perfectly valid. + Forever loops are also detected at runtime, so those that occur in + conditional subpatterns will be picked up then. */ + + else if (GET(called, 1) == 0 && cond_depth <= 0 && + could_be_empty(called, code, bcptr, utf, cd)) + { + *errorcodeptr = ERR40; + goto FAILED; + } + } + + /* Insert the recursion/subroutine item. It does not have a set first + character (relevant if it is repeated, because it will then be + wrapped with ONCE brackets). */ + + *code = OP_RECURSE; + PUT(code, 1, (int)(called - cd->start_code)); + code += 1 + LINK_SIZE; + groupsetfirstchar = FALSE; + } + + /* Can't determine a first byte now */ + + if (firstcharflags == REQ_UNSET) firstcharflags = REQ_NONE; + continue; + + + /* ------------------------------------------------------------ */ + default: /* Other characters: check option setting */ + OTHER_CHAR_AFTER_QUERY: + set = unset = 0; + optset = &set; + + while (*ptr != CHAR_RIGHT_PARENTHESIS && *ptr != CHAR_COLON) + { + switch (*ptr++) + { + case CHAR_MINUS: optset = &unset; break; + + case CHAR_J: /* Record that it changed in the external options */ + *optset |= PCRE_DUPNAMES; + cd->external_flags |= PCRE_JCHANGED; + break; + + case CHAR_i: *optset |= PCRE_CASELESS; break; + case CHAR_m: *optset |= PCRE_MULTILINE; break; + case CHAR_s: *optset |= PCRE_DOTALL; break; + case CHAR_x: *optset |= PCRE_EXTENDED; break; + case CHAR_U: *optset |= PCRE_UNGREEDY; break; + case CHAR_X: *optset |= PCRE_EXTRA; break; + + default: *errorcodeptr = ERR12; + ptr--; /* Correct the offset */ + goto FAILED; + } + } + + /* Set up the changed option bits, but don't change anything yet. */ + + newoptions = (options | set) & (~unset); + + /* If the options ended with ')' this is not the start of a nested + group with option changes, so the options change at this level. If this + item is right at the start of the pattern, the options can be + abstracted and made external in the pre-compile phase, and ignored in + the compile phase. This can be helpful when matching -- for instance in + caseless checking of required bytes. + + If the code pointer is not (cd->start_code + 1 + LINK_SIZE), we are + definitely *not* at the start of the pattern because something has been + compiled. In the pre-compile phase, however, the code pointer can have + that value after the start, because it gets reset as code is discarded + during the pre-compile. However, this can happen only at top level - if + we are within parentheses, the starting BRA will still be present. At + any parenthesis level, the length value can be used to test if anything + has been compiled at that level. Thus, a test for both these conditions + is necessary to ensure we correctly detect the start of the pattern in + both phases. + + If we are not at the pattern start, reset the greedy defaults and the + case value for firstchar and reqchar. */ + + if (*ptr == CHAR_RIGHT_PARENTHESIS) + { + if (code == cd->start_code + 1 + LINK_SIZE && + (lengthptr == NULL || *lengthptr == 2 + 2*LINK_SIZE)) + { + cd->external_options = newoptions; + } + else + { + greedy_default = ((newoptions & PCRE_UNGREEDY) != 0); + greedy_non_default = greedy_default ^ 1; + req_caseopt = ((newoptions & PCRE_CASELESS) != 0)? REQ_CASELESS:0; + } + + /* Change options at this level, and pass them back for use + in subsequent branches. */ + + *optionsptr = options = newoptions; + previous = NULL; /* This item can't be repeated */ + continue; /* It is complete */ + } + + /* If the options ended with ':' we are heading into a nested group + with possible change of options. Such groups are non-capturing and are + not assertions of any kind. All we need to do is skip over the ':'; + the newoptions value is handled below. */ + + bravalue = OP_BRA; + ptr++; + } /* End of switch for character following (? */ + } /* End of (? handling */ + + /* Opening parenthesis not followed by '*' or '?'. If PCRE_NO_AUTO_CAPTURE + is set, all unadorned brackets become non-capturing and behave like (?:...) + brackets. */ + + else if ((options & PCRE_NO_AUTO_CAPTURE) != 0) + { + bravalue = OP_BRA; + } + + /* Else we have a capturing group. */ + + else + { + NUMBERED_GROUP: + cd->bracount += 1; + PUT2(code, 1+LINK_SIZE, cd->bracount); + skipbytes = IMM2_SIZE; + } + + /* Process nested bracketed regex. First check for parentheses nested too + deeply. */ + + if ((cd->parens_depth += 1) > PARENS_NEST_LIMIT) + { + *errorcodeptr = ERR82; + goto FAILED; + } + + /* Assertions used not to be repeatable, but this was changed for Perl + compatibility, so all kinds can now be repeated. We copy code into a + non-register variable (tempcode) in order to be able to pass its address + because some compilers complain otherwise. */ + + previous = code; /* For handling repetition */ + *code = bravalue; + tempcode = code; + tempreqvary = cd->req_varyopt; /* Save value before bracket */ + tempbracount = cd->bracount; /* Save value before bracket */ + length_prevgroup = 0; /* Initialize for pre-compile phase */ + + if (!compile_regex( + newoptions, /* The complete new option state */ + &tempcode, /* Where to put code (updated) */ + &ptr, /* Input pointer (updated) */ + errorcodeptr, /* Where to put an error message */ + (bravalue == OP_ASSERTBACK || + bravalue == OP_ASSERTBACK_NOT), /* TRUE if back assert */ + reset_bracount, /* True if (?| group */ + skipbytes, /* Skip over bracket number */ + cond_depth + + ((bravalue == OP_COND)?1:0), /* Depth of condition subpatterns */ + &subfirstchar, /* For possible first char */ + &subfirstcharflags, + &subreqchar, /* For possible last char */ + &subreqcharflags, + bcptr, /* Current branch chain */ + cd, /* Tables block */ + (lengthptr == NULL)? NULL : /* Actual compile phase */ + &length_prevgroup /* Pre-compile phase */ + )) + goto FAILED; + + cd->parens_depth -= 1; + + /* If this was an atomic group and there are no capturing groups within it, + generate OP_ONCE_NC instead of OP_ONCE. */ + + if (bravalue == OP_ONCE && cd->bracount <= tempbracount) + *code = OP_ONCE_NC; + + if (bravalue >= OP_ASSERT && bravalue <= OP_ASSERTBACK_NOT) + cd->assert_depth -= 1; + + /* At the end of compiling, code is still pointing to the start of the + group, while tempcode has been updated to point past the end of the group. + The pattern pointer (ptr) is on the bracket. + + If this is a conditional bracket, check that there are no more than + two branches in the group, or just one if it's a DEFINE group. We do this + in the real compile phase, not in the pre-pass, where the whole group may + not be available. */ + + if (bravalue == OP_COND && lengthptr == NULL) + { + pcre_uchar *tc = code; + int condcount = 0; + + do { + condcount++; + tc += GET(tc,1); + } + while (*tc != OP_KET); + + /* A DEFINE group is never obeyed inline (the "condition" is always + false). It must have only one branch. */ + + if (code[LINK_SIZE+1] == OP_DEF) + { + if (condcount > 1) + { + *errorcodeptr = ERR54; + goto FAILED; + } + bravalue = OP_DEF; /* Just a flag to suppress char handling below */ + } + + /* A "normal" conditional group. If there is just one branch, we must not + make use of its firstchar or reqchar, because this is equivalent to an + empty second branch. */ + + else + { + if (condcount > 2) + { + *errorcodeptr = ERR27; + goto FAILED; + } + if (condcount == 1) subfirstcharflags = subreqcharflags = REQ_NONE; + } + } + + /* Error if hit end of pattern */ + + if (*ptr != CHAR_RIGHT_PARENTHESIS) + { + *errorcodeptr = ERR14; + goto FAILED; + } + + /* In the pre-compile phase, update the length by the length of the group, + less the brackets at either end. Then reduce the compiled code to just a + set of non-capturing brackets so that it doesn't use much memory if it is + duplicated by a quantifier.*/ + + if (lengthptr != NULL) + { + if (OFLOW_MAX - *lengthptr < length_prevgroup - 2 - 2*LINK_SIZE) + { + *errorcodeptr = ERR20; + goto FAILED; + } + *lengthptr += length_prevgroup - 2 - 2*LINK_SIZE; + code++; /* This already contains bravalue */ + PUTINC(code, 0, 1 + LINK_SIZE); + *code++ = OP_KET; + PUTINC(code, 0, 1 + LINK_SIZE); + break; /* No need to waste time with special character handling */ + } + + /* Otherwise update the main code pointer to the end of the group. */ + + code = tempcode; + + /* For a DEFINE group, required and first character settings are not + relevant. */ + + if (bravalue == OP_DEF) break; + + /* Handle updating of the required and first characters for other types of + group. Update for normal brackets of all kinds, and conditions with two + branches (see code above). If the bracket is followed by a quantifier with + zero repeat, we have to back off. Hence the definition of zeroreqchar and + zerofirstchar outside the main loop so that they can be accessed for the + back off. */ + + zeroreqchar = reqchar; + zeroreqcharflags = reqcharflags; + zerofirstchar = firstchar; + zerofirstcharflags = firstcharflags; + groupsetfirstchar = FALSE; + + if (bravalue >= OP_ONCE) + { + /* If we have not yet set a firstchar in this branch, take it from the + subpattern, remembering that it was set here so that a repeat of more + than one can replicate it as reqchar if necessary. If the subpattern has + no firstchar, set "none" for the whole branch. In both cases, a zero + repeat forces firstchar to "none". */ + + if (firstcharflags == REQ_UNSET) + { + if (subfirstcharflags >= 0) + { + firstchar = subfirstchar; + firstcharflags = subfirstcharflags; + groupsetfirstchar = TRUE; + } + else firstcharflags = REQ_NONE; + zerofirstcharflags = REQ_NONE; + } + + /* If firstchar was previously set, convert the subpattern's firstchar + into reqchar if there wasn't one, using the vary flag that was in + existence beforehand. */ + + else if (subfirstcharflags >= 0 && subreqcharflags < 0) + { + subreqchar = subfirstchar; + subreqcharflags = subfirstcharflags | tempreqvary; + } + + /* If the subpattern set a required byte (or set a first byte that isn't + really the first byte - see above), set it. */ + + if (subreqcharflags >= 0) + { + reqchar = subreqchar; + reqcharflags = subreqcharflags; + } + } + + /* For a forward assertion, we take the reqchar, if set. This can be + helpful if the pattern that follows the assertion doesn't set a different + char. For example, it's useful for /(?=abcde).+/. We can't set firstchar + for an assertion, however because it leads to incorrect effect for patterns + such as /(?=a)a.+/ when the "real" "a" would then become a reqchar instead + of a firstchar. This is overcome by a scan at the end if there's no + firstchar, looking for an asserted first char. */ + + else if (bravalue == OP_ASSERT && subreqcharflags >= 0) + { + reqchar = subreqchar; + reqcharflags = subreqcharflags; + } + break; /* End of processing '(' */ + + + /* ===================================================================*/ + /* Handle metasequences introduced by \. For ones like \d, the ESC_ values + are arranged to be the negation of the corresponding OP_values in the + default case when PCRE_UCP is not set. For the back references, the values + are negative the reference number. Only back references and those types + that consume a character may be repeated. We can test for values between + ESC_b and ESC_Z for the latter; this may have to change if any new ones are + ever created. */ + + case CHAR_BACKSLASH: + tempptr = ptr; + escape = check_escape(&ptr, &ec, errorcodeptr, cd->bracount, options, FALSE); + if (*errorcodeptr != 0) goto FAILED; + + if (escape == 0) /* The escape coded a single character */ + c = ec; + else + { + if (escape == ESC_Q) /* Handle start of quoted string */ + { + if (ptr[1] == CHAR_BACKSLASH && ptr[2] == CHAR_E) + ptr += 2; /* avoid empty string */ + else inescq = TRUE; + continue; + } + + if (escape == ESC_E) continue; /* Perl ignores an orphan \E */ + + /* For metasequences that actually match a character, we disable the + setting of a first character if it hasn't already been set. */ + + if (firstcharflags == REQ_UNSET && escape > ESC_b && escape < ESC_Z) + firstcharflags = REQ_NONE; + + /* Set values to reset to if this is followed by a zero repeat. */ + + zerofirstchar = firstchar; + zerofirstcharflags = firstcharflags; + zeroreqchar = reqchar; + zeroreqcharflags = reqcharflags; + + /* \g or \g'name' is a subroutine call by name and \g or \g'n' + is a subroutine call by number (Oniguruma syntax). In fact, the value + ESC_g is returned only for these cases. So we don't need to check for < + or ' if the value is ESC_g. For the Perl syntax \g{n} the value is + -n, and for the Perl syntax \g{name} the result is ESC_k (as + that is a synonym for a named back reference). */ + + if (escape == ESC_g) + { + const pcre_uchar *p; + pcre_uint32 cf; + + save_hwm = cd->hwm; /* Normally this is set when '(' is read */ + terminator = (*(++ptr) == CHAR_LESS_THAN_SIGN)? + CHAR_GREATER_THAN_SIGN : CHAR_APOSTROPHE; + + /* These two statements stop the compiler for warning about possibly + unset variables caused by the jump to HANDLE_NUMERICAL_RECURSION. In + fact, because we do the check for a number below, the paths that + would actually be in error are never taken. */ + + skipbytes = 0; + reset_bracount = FALSE; + + /* If it's not a signed or unsigned number, treat it as a name. */ + + cf = ptr[1]; + if (cf != CHAR_PLUS && cf != CHAR_MINUS && !IS_DIGIT(cf)) + { + is_recurse = TRUE; + goto NAMED_REF_OR_RECURSE; + } + + /* Signed or unsigned number (cf = ptr[1]) is known to be plus or minus + or a digit. */ + + p = ptr + 2; + while (IS_DIGIT(*p)) p++; + if (*p != (pcre_uchar)terminator) + { + *errorcodeptr = ERR57; + break; + } + ptr++; + goto HANDLE_NUMERICAL_RECURSION; + } + + /* \k or \k'name' is a back reference by name (Perl syntax). + We also support \k{name} (.NET syntax). */ + + if (escape == ESC_k) + { + if ((ptr[1] != CHAR_LESS_THAN_SIGN && + ptr[1] != CHAR_APOSTROPHE && ptr[1] != CHAR_LEFT_CURLY_BRACKET)) + { + *errorcodeptr = ERR69; + break; + } + is_recurse = FALSE; + terminator = (*(++ptr) == CHAR_LESS_THAN_SIGN)? + CHAR_GREATER_THAN_SIGN : (*ptr == CHAR_APOSTROPHE)? + CHAR_APOSTROPHE : CHAR_RIGHT_CURLY_BRACKET; + goto NAMED_REF_OR_RECURSE; + } + + /* Back references are handled specially; must disable firstchar if + not set to cope with cases like (?=(\w+))\1: which would otherwise set + ':' later. */ + + if (escape < 0) + { + open_capitem *oc; + recno = -escape; + + /* Come here from named backref handling when the reference is to a + single group (i.e. not to a duplicated name. */ + + HANDLE_REFERENCE: + if (firstcharflags == REQ_UNSET) firstcharflags = REQ_NONE; + previous = code; + *code++ = ((options & PCRE_CASELESS) != 0)? OP_REFI : OP_REF; + PUT2INC(code, 0, recno); + cd->backref_map |= (recno < 32)? (1 << recno) : 1; + if (recno > cd->top_backref) cd->top_backref = recno; + + /* Check to see if this back reference is recursive, that it, it + is inside the group that it references. A flag is set so that the + group can be made atomic. */ + + for (oc = cd->open_caps; oc != NULL; oc = oc->next) + { + if (oc->number == recno) + { + oc->flag = TRUE; + break; + } + } + } + + /* So are Unicode property matches, if supported. */ + +#ifdef SUPPORT_UCP + else if (escape == ESC_P || escape == ESC_p) + { + BOOL negated; + unsigned int ptype = 0, pdata = 0; + if (!get_ucp(&ptr, &negated, &ptype, &pdata, errorcodeptr)) + goto FAILED; + previous = code; + *code++ = ((escape == ESC_p) != negated)? OP_PROP : OP_NOTPROP; + *code++ = ptype; + *code++ = pdata; + } +#else + + /* If Unicode properties are not supported, \X, \P, and \p are not + allowed. */ + + else if (escape == ESC_X || escape == ESC_P || escape == ESC_p) + { + *errorcodeptr = ERR45; + goto FAILED; + } +#endif + + /* For the rest (including \X when Unicode properties are supported), we + can obtain the OP value by negating the escape value in the default + situation when PCRE_UCP is not set. When it *is* set, we substitute + Unicode property tests. Note that \b and \B do a one-character + lookbehind, and \A also behaves as if it does. */ + + else + { + if ((escape == ESC_b || escape == ESC_B || escape == ESC_A) && + cd->max_lookbehind == 0) + cd->max_lookbehind = 1; +#ifdef SUPPORT_UCP + if (escape >= ESC_DU && escape <= ESC_wu) + { + nestptr = ptr + 1; /* Where to resume */ + ptr = substitutes[escape - ESC_DU] - 1; /* Just before substitute */ + } + else +#endif + /* In non-UTF-8 mode, we turn \C into OP_ALLANY instead of OP_ANYBYTE + so that it works in DFA mode and in lookbehinds. */ + + { + previous = (escape > ESC_b && escape < ESC_Z)? code : NULL; + *code++ = (!utf && escape == ESC_C)? OP_ALLANY : escape; + } + } + continue; + } + + /* We have a data character whose value is in c. In UTF-8 mode it may have + a value > 127. We set its representation in the length/buffer, and then + handle it as a data character. */ + +#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 + if (utf && c > MAX_VALUE_FOR_SINGLE_CHAR) + mclength = PRIV(ord2utf)(c, mcbuffer); + else +#endif + + { + mcbuffer[0] = c; + mclength = 1; + } + goto ONE_CHAR; + + + /* ===================================================================*/ + /* Handle a literal character. It is guaranteed not to be whitespace or # + when the extended flag is set. If we are in a UTF mode, it may be a + multi-unit literal character. */ + + default: + NORMAL_CHAR: + mclength = 1; + mcbuffer[0] = c; + +#ifdef SUPPORT_UTF + if (utf && HAS_EXTRALEN(c)) + ACROSSCHAR(TRUE, ptr[1], mcbuffer[mclength++] = *(++ptr)); +#endif + + /* At this point we have the character's bytes in mcbuffer, and the length + in mclength. When not in UTF-8 mode, the length is always 1. */ + + ONE_CHAR: + previous = code; + + /* For caseless UTF-8 mode when UCP support is available, check whether + this character has more than one other case. If so, generate a special + OP_PROP item instead of OP_CHARI. */ + +#ifdef SUPPORT_UCP + if (utf && (options & PCRE_CASELESS) != 0) + { + GETCHAR(c, mcbuffer); + if ((c = UCD_CASESET(c)) != 0) + { + *code++ = OP_PROP; + *code++ = PT_CLIST; + *code++ = c; + if (firstcharflags == REQ_UNSET) + firstcharflags = zerofirstcharflags = REQ_NONE; + break; + } + } +#endif + + /* Caseful matches, or not one of the multicase characters. */ + + *code++ = ((options & PCRE_CASELESS) != 0)? OP_CHARI : OP_CHAR; + for (c = 0; c < mclength; c++) *code++ = mcbuffer[c]; + + /* Remember if \r or \n were seen */ + + if (mcbuffer[0] == CHAR_CR || mcbuffer[0] == CHAR_NL) + cd->external_flags |= PCRE_HASCRORLF; + + /* Set the first and required bytes appropriately. If no previous first + byte, set it from this character, but revert to none on a zero repeat. + Otherwise, leave the firstchar value alone, and don't change it on a zero + repeat. */ + + if (firstcharflags == REQ_UNSET) + { + zerofirstcharflags = REQ_NONE; + zeroreqchar = reqchar; + zeroreqcharflags = reqcharflags; + + /* If the character is more than one byte long, we can set firstchar + only if it is not to be matched caselessly. */ + + if (mclength == 1 || req_caseopt == 0) + { + firstchar = mcbuffer[0] | req_caseopt; + firstchar = mcbuffer[0]; + firstcharflags = req_caseopt; + + if (mclength != 1) + { + reqchar = code[-1]; + reqcharflags = cd->req_varyopt; + } + } + else firstcharflags = reqcharflags = REQ_NONE; + } + + /* firstchar was previously set; we can set reqchar only if the length is + 1 or the matching is caseful. */ + + else + { + zerofirstchar = firstchar; + zerofirstcharflags = firstcharflags; + zeroreqchar = reqchar; + zeroreqcharflags = reqcharflags; + if (mclength == 1 || req_caseopt == 0) + { + reqchar = code[-1]; + reqcharflags = req_caseopt | cd->req_varyopt; + } + } + + break; /* End of literal character handling */ + } + } /* end of big loop */ + + +/* Control never reaches here by falling through, only by a goto for all the +error states. Pass back the position in the pattern so that it can be displayed +to the user for diagnosing the error. */ + +FAILED: +*ptrptr = ptr; +return FALSE; +} + + + +/************************************************* +* Compile sequence of alternatives * +*************************************************/ + +/* On entry, ptr is pointing past the bracket character, but on return it +points to the closing bracket, or vertical bar, or end of string. The code +variable is pointing at the byte into which the BRA operator has been stored. +This function is used during the pre-compile phase when we are trying to find +out the amount of memory needed, as well as during the real compile phase. The +value of lengthptr distinguishes the two phases. + +Arguments: + options option bits, including any changes for this subpattern + codeptr -> the address of the current code pointer + ptrptr -> the address of the current pattern pointer + errorcodeptr -> pointer to error code variable + lookbehind TRUE if this is a lookbehind assertion + reset_bracount TRUE to reset the count for each branch + skipbytes skip this many bytes at start (for brackets and OP_COND) + cond_depth depth of nesting for conditional subpatterns + firstcharptr place to put the first required character + firstcharflagsptr place to put the first character flags, or a negative number + reqcharptr place to put the last required character + reqcharflagsptr place to put the last required character flags, or a negative number + bcptr pointer to the chain of currently open branches + cd points to the data block with tables pointers etc. + lengthptr NULL during the real compile phase + points to length accumulator during pre-compile phase + +Returns: TRUE on success +*/ + +static BOOL +compile_regex(int options, pcre_uchar **codeptr, const pcre_uchar **ptrptr, + int *errorcodeptr, BOOL lookbehind, BOOL reset_bracount, int skipbytes, + int cond_depth, + pcre_uint32 *firstcharptr, pcre_int32 *firstcharflagsptr, + pcre_uint32 *reqcharptr, pcre_int32 *reqcharflagsptr, + branch_chain *bcptr, compile_data *cd, int *lengthptr) +{ +const pcre_uchar *ptr = *ptrptr; +pcre_uchar *code = *codeptr; +pcre_uchar *last_branch = code; +pcre_uchar *start_bracket = code; +pcre_uchar *reverse_count = NULL; +open_capitem capitem; +int capnumber = 0; +pcre_uint32 firstchar, reqchar; +pcre_int32 firstcharflags, reqcharflags; +pcre_uint32 branchfirstchar, branchreqchar; +pcre_int32 branchfirstcharflags, branchreqcharflags; +int length; +unsigned int orig_bracount; +unsigned int max_bracount; +branch_chain bc; + +/* If set, call the external function that checks for stack availability. */ + +if (PUBL(stack_guard) != NULL && PUBL(stack_guard)()) + { + *errorcodeptr= ERR85; + return FALSE; + } + +/* Miscellaneous initialization */ + +bc.outer = bcptr; +bc.current_branch = code; + +firstchar = reqchar = 0; +firstcharflags = reqcharflags = REQ_UNSET; + +/* Accumulate the length for use in the pre-compile phase. Start with the +length of the BRA and KET and any extra bytes that are required at the +beginning. We accumulate in a local variable to save frequent testing of +lenthptr for NULL. We cannot do this by looking at the value of code at the +start and end of each alternative, because compiled items are discarded during +the pre-compile phase so that the work space is not exceeded. */ + +length = 2 + 2*LINK_SIZE + skipbytes; + +/* WARNING: If the above line is changed for any reason, you must also change +the code that abstracts option settings at the start of the pattern and makes +them global. It tests the value of length for (2 + 2*LINK_SIZE) in the +pre-compile phase to find out whether anything has yet been compiled or not. */ + +/* If this is a capturing subpattern, add to the chain of open capturing items +so that we can detect them if (*ACCEPT) is encountered. This is also used to +detect groups that contain recursive back references to themselves. Note that +only OP_CBRA need be tested here; changing this opcode to one of its variants, +e.g. OP_SCBRAPOS, happens later, after the group has been compiled. */ + +if (*code == OP_CBRA) + { + capnumber = GET2(code, 1 + LINK_SIZE); + capitem.number = capnumber; + capitem.next = cd->open_caps; + capitem.flag = FALSE; + cd->open_caps = &capitem; + } + +/* Offset is set zero to mark that this bracket is still open */ + +PUT(code, 1, 0); +code += 1 + LINK_SIZE + skipbytes; + +/* Loop for each alternative branch */ + +orig_bracount = max_bracount = cd->bracount; +for (;;) + { + /* For a (?| group, reset the capturing bracket count so that each branch + uses the same numbers. */ + + if (reset_bracount) cd->bracount = orig_bracount; + + /* Set up dummy OP_REVERSE if lookbehind assertion */ + + if (lookbehind) + { + *code++ = OP_REVERSE; + reverse_count = code; + PUTINC(code, 0, 0); + length += 1 + LINK_SIZE; + } + + /* Now compile the branch; in the pre-compile phase its length gets added + into the length. */ + + if (!compile_branch(&options, &code, &ptr, errorcodeptr, &branchfirstchar, + &branchfirstcharflags, &branchreqchar, &branchreqcharflags, &bc, + cond_depth, cd, (lengthptr == NULL)? NULL : &length)) + { + *ptrptr = ptr; + return FALSE; + } + + /* Keep the highest bracket count in case (?| was used and some branch + has fewer than the rest. */ + + if (cd->bracount > max_bracount) max_bracount = cd->bracount; + + /* In the real compile phase, there is some post-processing to be done. */ + + if (lengthptr == NULL) + { + /* If this is the first branch, the firstchar and reqchar values for the + branch become the values for the regex. */ + + if (*last_branch != OP_ALT) + { + firstchar = branchfirstchar; + firstcharflags = branchfirstcharflags; + reqchar = branchreqchar; + reqcharflags = branchreqcharflags; + } + + /* If this is not the first branch, the first char and reqchar have to + match the values from all the previous branches, except that if the + previous value for reqchar didn't have REQ_VARY set, it can still match, + and we set REQ_VARY for the regex. */ + + else + { + /* If we previously had a firstchar, but it doesn't match the new branch, + we have to abandon the firstchar for the regex, but if there was + previously no reqchar, it takes on the value of the old firstchar. */ + + if (firstcharflags >= 0 && + (firstcharflags != branchfirstcharflags || firstchar != branchfirstchar)) + { + if (reqcharflags < 0) + { + reqchar = firstchar; + reqcharflags = firstcharflags; + } + firstcharflags = REQ_NONE; + } + + /* If we (now or from before) have no firstchar, a firstchar from the + branch becomes a reqchar if there isn't a branch reqchar. */ + + if (firstcharflags < 0 && branchfirstcharflags >= 0 && branchreqcharflags < 0) + { + branchreqchar = branchfirstchar; + branchreqcharflags = branchfirstcharflags; + } + + /* Now ensure that the reqchars match */ + + if (((reqcharflags & ~REQ_VARY) != (branchreqcharflags & ~REQ_VARY)) || + reqchar != branchreqchar) + reqcharflags = REQ_NONE; + else + { + reqchar = branchreqchar; + reqcharflags |= branchreqcharflags; /* To "or" REQ_VARY */ + } + } + + /* If lookbehind, check that this branch matches a fixed-length string, and + put the length into the OP_REVERSE item. Temporarily mark the end of the + branch with OP_END. If the branch contains OP_RECURSE, the result is -3 + because there may be forward references that we can't check here. Set a + flag to cause another lookbehind check at the end. Why not do it all at the + end? Because common, erroneous checks are picked up here and the offset of + the problem can be shown. */ + + if (lookbehind) + { + int fixed_length; + *code = OP_END; + fixed_length = find_fixedlength(last_branch, (options & PCRE_UTF8) != 0, + FALSE, cd); + DPRINTF(("fixed length = %d\n", fixed_length)); + if (fixed_length == -3) + { + cd->check_lookbehind = TRUE; + } + else if (fixed_length < 0) + { + *errorcodeptr = (fixed_length == -2)? ERR36 : + (fixed_length == -4)? ERR70: ERR25; + *ptrptr = ptr; + return FALSE; + } + else + { + if (fixed_length > cd->max_lookbehind) + cd->max_lookbehind = fixed_length; + PUT(reverse_count, 0, fixed_length); + } + } + } + + /* Reached end of expression, either ')' or end of pattern. In the real + compile phase, go back through the alternative branches and reverse the chain + of offsets, with the field in the BRA item now becoming an offset to the + first alternative. If there are no alternatives, it points to the end of the + group. The length in the terminating ket is always the length of the whole + bracketed item. Return leaving the pointer at the terminating char. */ + + if (*ptr != CHAR_VERTICAL_LINE) + { + if (lengthptr == NULL) + { + int branch_length = (int)(code - last_branch); + do + { + int prev_length = GET(last_branch, 1); + PUT(last_branch, 1, branch_length); + branch_length = prev_length; + last_branch -= branch_length; + } + while (branch_length > 0); + } + + /* Fill in the ket */ + + *code = OP_KET; + PUT(code, 1, (int)(code - start_bracket)); + code += 1 + LINK_SIZE; + + /* If it was a capturing subpattern, check to see if it contained any + recursive back references. If so, we must wrap it in atomic brackets. + Because we are moving code along, we must ensure that any pending recursive + references are updated. In any event, remove the block from the chain. */ + + if (capnumber > 0) + { + if (cd->open_caps->flag) + { + *code = OP_END; + adjust_recurse(start_bracket, 1 + LINK_SIZE, + (options & PCRE_UTF8) != 0, cd, cd->hwm); + memmove(start_bracket + 1 + LINK_SIZE, start_bracket, + IN_UCHARS(code - start_bracket)); + *start_bracket = OP_ONCE; + code += 1 + LINK_SIZE; + PUT(start_bracket, 1, (int)(code - start_bracket)); + *code = OP_KET; + PUT(code, 1, (int)(code - start_bracket)); + code += 1 + LINK_SIZE; + length += 2 + 2*LINK_SIZE; + } + cd->open_caps = cd->open_caps->next; + } + + /* Retain the highest bracket number, in case resetting was used. */ + + cd->bracount = max_bracount; + + /* Set values to pass back */ + + *codeptr = code; + *ptrptr = ptr; + *firstcharptr = firstchar; + *firstcharflagsptr = firstcharflags; + *reqcharptr = reqchar; + *reqcharflagsptr = reqcharflags; + if (lengthptr != NULL) + { + if (OFLOW_MAX - *lengthptr < length) + { + *errorcodeptr = ERR20; + return FALSE; + } + *lengthptr += length; + } + return TRUE; + } + + /* Another branch follows. In the pre-compile phase, we can move the code + pointer back to where it was for the start of the first branch. (That is, + pretend that each branch is the only one.) + + In the real compile phase, insert an ALT node. Its length field points back + to the previous branch while the bracket remains open. At the end the chain + is reversed. It's done like this so that the start of the bracket has a + zero offset until it is closed, making it possible to detect recursion. */ + + if (lengthptr != NULL) + { + code = *codeptr + 1 + LINK_SIZE + skipbytes; + length += 1 + LINK_SIZE; + } + else + { + *code = OP_ALT; + PUT(code, 1, (int)(code - last_branch)); + bc.current_branch = last_branch = code; + code += 1 + LINK_SIZE; + } + + ptr++; + } +/* Control never reaches here */ +} + + + + +/************************************************* +* Check for anchored expression * +*************************************************/ + +/* Try to find out if this is an anchored regular expression. Consider each +alternative branch. If they all start with OP_SOD or OP_CIRC, or with a bracket +all of whose alternatives start with OP_SOD or OP_CIRC (recurse ad lib), then +it's anchored. However, if this is a multiline pattern, then only OP_SOD will +be found, because ^ generates OP_CIRCM in that mode. + +We can also consider a regex to be anchored if OP_SOM starts all its branches. +This is the code for \G, which means "match at start of match position, taking +into account the match offset". + +A branch is also implicitly anchored if it starts with .* and DOTALL is set, +because that will try the rest of the pattern at all possible matching points, +so there is no point trying again.... er .... + +.... except when the .* appears inside capturing parentheses, and there is a +subsequent back reference to those parentheses. We haven't enough information +to catch that case precisely. + +At first, the best we could do was to detect when .* was in capturing brackets +and the highest back reference was greater than or equal to that level. +However, by keeping a bitmap of the first 31 back references, we can catch some +of the more common cases more precisely. + +... A second exception is when the .* appears inside an atomic group, because +this prevents the number of characters it matches from being adjusted. + +Arguments: + code points to start of expression (the bracket) + bracket_map a bitmap of which brackets we are inside while testing; this + handles up to substring 31; after that we just have to take + the less precise approach + cd points to the compile data block + atomcount atomic group level + +Returns: TRUE or FALSE +*/ + +static BOOL +is_anchored(register const pcre_uchar *code, unsigned int bracket_map, + compile_data *cd, int atomcount) +{ +do { + const pcre_uchar *scode = first_significant_code( + code + PRIV(OP_lengths)[*code], FALSE); + register int op = *scode; + + /* Non-capturing brackets */ + + if (op == OP_BRA || op == OP_BRAPOS || + op == OP_SBRA || op == OP_SBRAPOS) + { + if (!is_anchored(scode, bracket_map, cd, atomcount)) return FALSE; + } + + /* Capturing brackets */ + + else if (op == OP_CBRA || op == OP_CBRAPOS || + op == OP_SCBRA || op == OP_SCBRAPOS) + { + int n = GET2(scode, 1+LINK_SIZE); + int new_map = bracket_map | ((n < 32)? (1 << n) : 1); + if (!is_anchored(scode, new_map, cd, atomcount)) return FALSE; + } + + /* Positive forward assertions and conditions */ + + else if (op == OP_ASSERT || op == OP_COND) + { + if (!is_anchored(scode, bracket_map, cd, atomcount)) return FALSE; + } + + /* Atomic groups */ + + else if (op == OP_ONCE || op == OP_ONCE_NC) + { + if (!is_anchored(scode, bracket_map, cd, atomcount + 1)) + return FALSE; + } + + /* .* is not anchored unless DOTALL is set (which generates OP_ALLANY) and + it isn't in brackets that are or may be referenced or inside an atomic + group. */ + + else if ((op == OP_TYPESTAR || op == OP_TYPEMINSTAR || + op == OP_TYPEPOSSTAR)) + { + if (scode[1] != OP_ALLANY || (bracket_map & cd->backref_map) != 0 || + atomcount > 0 || cd->had_pruneorskip) + return FALSE; + } + + /* Check for explicit anchoring */ + + else if (op != OP_SOD && op != OP_SOM && op != OP_CIRC) return FALSE; + + code += GET(code, 1); + } +while (*code == OP_ALT); /* Loop for each alternative */ +return TRUE; +} + + + +/************************************************* +* Check for starting with ^ or .* * +*************************************************/ + +/* This is called to find out if every branch starts with ^ or .* so that +"first char" processing can be done to speed things up in multiline +matching and for non-DOTALL patterns that start with .* (which must start at +the beginning or after \n). As in the case of is_anchored() (see above), we +have to take account of back references to capturing brackets that contain .* +because in that case we can't make the assumption. Also, the appearance of .* +inside atomic brackets or in a pattern that contains *PRUNE or *SKIP does not +count, because once again the assumption no longer holds. + +Arguments: + code points to start of expression (the bracket) + bracket_map a bitmap of which brackets we are inside while testing; this + handles up to substring 31; after that we just have to take + the less precise approach + cd points to the compile data + atomcount atomic group level + +Returns: TRUE or FALSE +*/ + +static BOOL +is_startline(const pcre_uchar *code, unsigned int bracket_map, + compile_data *cd, int atomcount) +{ +do { + const pcre_uchar *scode = first_significant_code( + code + PRIV(OP_lengths)[*code], FALSE); + register int op = *scode; + + /* If we are at the start of a conditional assertion group, *both* the + conditional assertion *and* what follows the condition must satisfy the test + for start of line. Other kinds of condition fail. Note that there may be an + auto-callout at the start of a condition. */ + + if (op == OP_COND) + { + scode += 1 + LINK_SIZE; + if (*scode == OP_CALLOUT) scode += PRIV(OP_lengths)[OP_CALLOUT]; + switch (*scode) + { + case OP_CREF: + case OP_DNCREF: + case OP_RREF: + case OP_DNRREF: + case OP_DEF: + return FALSE; + + default: /* Assertion */ + if (!is_startline(scode, bracket_map, cd, atomcount)) return FALSE; + do scode += GET(scode, 1); while (*scode == OP_ALT); + scode += 1 + LINK_SIZE; + break; + } + scode = first_significant_code(scode, FALSE); + op = *scode; + } + + /* Non-capturing brackets */ + + if (op == OP_BRA || op == OP_BRAPOS || + op == OP_SBRA || op == OP_SBRAPOS) + { + if (!is_startline(scode, bracket_map, cd, atomcount)) return FALSE; + } + + /* Capturing brackets */ + + else if (op == OP_CBRA || op == OP_CBRAPOS || + op == OP_SCBRA || op == OP_SCBRAPOS) + { + int n = GET2(scode, 1+LINK_SIZE); + int new_map = bracket_map | ((n < 32)? (1 << n) : 1); + if (!is_startline(scode, new_map, cd, atomcount)) return FALSE; + } + + /* Positive forward assertions */ + + else if (op == OP_ASSERT) + { + if (!is_startline(scode, bracket_map, cd, atomcount)) return FALSE; + } + + /* Atomic brackets */ + + else if (op == OP_ONCE || op == OP_ONCE_NC) + { + if (!is_startline(scode, bracket_map, cd, atomcount + 1)) return FALSE; + } + + /* .* means "start at start or after \n" if it isn't in atomic brackets or + brackets that may be referenced, as long as the pattern does not contain + *PRUNE or *SKIP, because these break the feature. Consider, for example, + /.*?a(*PRUNE)b/ with the subject "aab", which matches "ab", i.e. not at the + start of a line. */ + + else if (op == OP_TYPESTAR || op == OP_TYPEMINSTAR || op == OP_TYPEPOSSTAR) + { + if (scode[1] != OP_ANY || (bracket_map & cd->backref_map) != 0 || + atomcount > 0 || cd->had_pruneorskip) + return FALSE; + } + + /* Check for explicit circumflex; anything else gives a FALSE result. Note + in particular that this includes atomic brackets OP_ONCE and OP_ONCE_NC + because the number of characters matched by .* cannot be adjusted inside + them. */ + + else if (op != OP_CIRC && op != OP_CIRCM) return FALSE; + + /* Move on to the next alternative */ + + code += GET(code, 1); + } +while (*code == OP_ALT); /* Loop for each alternative */ +return TRUE; +} + + + +/************************************************* +* Check for asserted fixed first char * +*************************************************/ + +/* During compilation, the "first char" settings from forward assertions are +discarded, because they can cause conflicts with actual literals that follow. +However, if we end up without a first char setting for an unanchored pattern, +it is worth scanning the regex to see if there is an initial asserted first +char. If all branches start with the same asserted char, or with a +non-conditional bracket all of whose alternatives start with the same asserted +char (recurse ad lib), then we return that char, with the flags set to zero or +REQ_CASELESS; otherwise return zero with REQ_NONE in the flags. + +Arguments: + code points to start of expression (the bracket) + flags points to the first char flags, or to REQ_NONE + inassert TRUE if in an assertion + +Returns: the fixed first char, or 0 with REQ_NONE in flags +*/ + +static pcre_uint32 +find_firstassertedchar(const pcre_uchar *code, pcre_int32 *flags, + BOOL inassert) +{ +register pcre_uint32 c = 0; +int cflags = REQ_NONE; + +*flags = REQ_NONE; +do { + pcre_uint32 d; + int dflags; + int xl = (*code == OP_CBRA || *code == OP_SCBRA || + *code == OP_CBRAPOS || *code == OP_SCBRAPOS)? IMM2_SIZE:0; + const pcre_uchar *scode = first_significant_code(code + 1+LINK_SIZE + xl, + TRUE); + register pcre_uchar op = *scode; + + switch(op) + { + default: + return 0; + + case OP_BRA: + case OP_BRAPOS: + case OP_CBRA: + case OP_SCBRA: + case OP_CBRAPOS: + case OP_SCBRAPOS: + case OP_ASSERT: + case OP_ONCE: + case OP_ONCE_NC: + d = find_firstassertedchar(scode, &dflags, op == OP_ASSERT); + if (dflags < 0) + return 0; + if (cflags < 0) { c = d; cflags = dflags; } else if (c != d || cflags != dflags) return 0; + break; + + case OP_EXACT: + scode += IMM2_SIZE; + /* Fall through */ + + case OP_CHAR: + case OP_PLUS: + case OP_MINPLUS: + case OP_POSPLUS: + if (!inassert) return 0; + if (cflags < 0) { c = scode[1]; cflags = 0; } + else if (c != scode[1]) return 0; + break; + + case OP_EXACTI: + scode += IMM2_SIZE; + /* Fall through */ + + case OP_CHARI: + case OP_PLUSI: + case OP_MINPLUSI: + case OP_POSPLUSI: + if (!inassert) return 0; + if (cflags < 0) { c = scode[1]; cflags = REQ_CASELESS; } + else if (c != scode[1]) return 0; + break; + } + + code += GET(code, 1); + } +while (*code == OP_ALT); + +*flags = cflags; +return c; +} + + + +/************************************************* +* Add an entry to the name/number table * +*************************************************/ + +/* This function is called between compiling passes to add an entry to the +name/number table, maintaining alphabetical order. Checking for permitted +and forbidden duplicates has already been done. + +Arguments: + cd the compile data block + name the name to add + length the length of the name + groupno the group number + +Returns: nothing +*/ + +static void +add_name(compile_data *cd, const pcre_uchar *name, int length, + unsigned int groupno) +{ +int i; +pcre_uchar *slot = cd->name_table; + +for (i = 0; i < cd->names_found; i++) + { + int crc = memcmp(name, slot+IMM2_SIZE, IN_UCHARS(length)); + if (crc == 0 && slot[IMM2_SIZE+length] != 0) + crc = -1; /* Current name is a substring */ + + /* Make space in the table and break the loop for an earlier name. For a + duplicate or later name, carry on. We do this for duplicates so that in the + simple case (when ?(| is not used) they are in order of their numbers. In all + cases they are in the order in which they appear in the pattern. */ + + if (crc < 0) + { + memmove(slot + cd->name_entry_size, slot, + IN_UCHARS((cd->names_found - i) * cd->name_entry_size)); + break; + } + + /* Continue the loop for a later or duplicate name */ + + slot += cd->name_entry_size; + } + +PUT2(slot, 0, groupno); +memcpy(slot + IMM2_SIZE, name, IN_UCHARS(length)); +slot[IMM2_SIZE + length] = 0; +cd->names_found++; +} + + + +/************************************************* +* Compile a Regular Expression * +*************************************************/ + +/* This function takes a string and returns a pointer to a block of store +holding a compiled version of the expression. The original API for this +function had no error code return variable; it is retained for backwards +compatibility. The new function is given a new name. + +Arguments: + pattern the regular expression + options various option bits + errorcodeptr pointer to error code variable (pcre_compile2() only) + can be NULL if you don't want a code value + errorptr pointer to pointer to error text + erroroffset ptr offset in pattern where error was detected + tables pointer to character tables or NULL + +Returns: pointer to compiled data block, or NULL on error, + with errorptr and erroroffset set +*/ + +#if defined COMPILE_PCRE8 +PCRE_EXP_DEFN pcre * PCRE_CALL_CONVENTION +pcre_compile(const char *pattern, int options, const char **errorptr, + int *erroroffset, const unsigned char *tables) +#elif defined COMPILE_PCRE16 +PCRE_EXP_DEFN pcre16 * PCRE_CALL_CONVENTION +pcre16_compile(PCRE_SPTR16 pattern, int options, const char **errorptr, + int *erroroffset, const unsigned char *tables) +#elif defined COMPILE_PCRE32 +PCRE_EXP_DEFN pcre32 * PCRE_CALL_CONVENTION +pcre32_compile(PCRE_SPTR32 pattern, int options, const char **errorptr, + int *erroroffset, const unsigned char *tables) +#endif +{ +#if defined COMPILE_PCRE8 +return pcre_compile2(pattern, options, NULL, errorptr, erroroffset, tables); +#elif defined COMPILE_PCRE16 +return pcre16_compile2(pattern, options, NULL, errorptr, erroroffset, tables); +#elif defined COMPILE_PCRE32 +return pcre32_compile2(pattern, options, NULL, errorptr, erroroffset, tables); +#endif +} + + +#if defined COMPILE_PCRE8 +PCRE_EXP_DEFN pcre * PCRE_CALL_CONVENTION +pcre_compile2(const char *pattern, int options, int *errorcodeptr, + const char **errorptr, int *erroroffset, const unsigned char *tables) +#elif defined COMPILE_PCRE16 +PCRE_EXP_DEFN pcre16 * PCRE_CALL_CONVENTION +pcre16_compile2(PCRE_SPTR16 pattern, int options, int *errorcodeptr, + const char **errorptr, int *erroroffset, const unsigned char *tables) +#elif defined COMPILE_PCRE32 +PCRE_EXP_DEFN pcre32 * PCRE_CALL_CONVENTION +pcre32_compile2(PCRE_SPTR32 pattern, int options, int *errorcodeptr, + const char **errorptr, int *erroroffset, const unsigned char *tables) +#endif +{ +REAL_PCRE *re; +int length = 1; /* For final END opcode */ +pcre_int32 firstcharflags, reqcharflags; +pcre_uint32 firstchar, reqchar; +pcre_uint32 limit_match = PCRE_UINT32_MAX; +pcre_uint32 limit_recursion = PCRE_UINT32_MAX; +int newline; +int errorcode = 0; +int skipatstart = 0; +BOOL utf; +BOOL never_utf = FALSE; +size_t size; +pcre_uchar *code; +const pcre_uchar *codestart; +const pcre_uchar *ptr; +compile_data compile_block; +compile_data *cd = &compile_block; + +/* This space is used for "compiling" into during the first phase, when we are +computing the amount of memory that is needed. Compiled items are thrown away +as soon as possible, so that a fairly large buffer should be sufficient for +this purpose. The same space is used in the second phase for remembering where +to fill in forward references to subpatterns. That may overflow, in which case +new memory is obtained from malloc(). */ + +pcre_uchar cworkspace[COMPILE_WORK_SIZE]; + +/* This vector is used for remembering name groups during the pre-compile. In a +similar way to cworkspace, it can be expanded using malloc() if necessary. */ + +named_group named_groups[NAMED_GROUP_LIST_SIZE]; + +/* Set this early so that early errors get offset 0. */ + +ptr = (const pcre_uchar *)pattern; + +/* We can't pass back an error message if errorptr is NULL; I guess the best we +can do is just return NULL, but we can set a code value if there is a code +pointer. */ + +if (errorptr == NULL) + { + if (errorcodeptr != NULL) *errorcodeptr = 99; + return NULL; + } + +*errorptr = NULL; +if (errorcodeptr != NULL) *errorcodeptr = ERR0; + +/* However, we can give a message for this error */ + +if (erroroffset == NULL) + { + errorcode = ERR16; + goto PCRE_EARLY_ERROR_RETURN2; + } + +*erroroffset = 0; + +/* Set up pointers to the individual character tables */ + +if (tables == NULL) tables = PRIV(default_tables); +cd->lcc = tables + lcc_offset; +cd->fcc = tables + fcc_offset; +cd->cbits = tables + cbits_offset; +cd->ctypes = tables + ctypes_offset; + +/* Check that all undefined public option bits are zero */ + +if ((options & ~PUBLIC_COMPILE_OPTIONS) != 0) + { + errorcode = ERR17; + goto PCRE_EARLY_ERROR_RETURN; + } + +/* If PCRE_NEVER_UTF is set, remember it. */ + +if ((options & PCRE_NEVER_UTF) != 0) never_utf = TRUE; + +/* Check for global one-time settings at the start of the pattern, and remember +the offset for later. */ + +cd->external_flags = 0; /* Initialize here for LIMIT_MATCH/RECURSION */ + +while (ptr[skipatstart] == CHAR_LEFT_PARENTHESIS && + ptr[skipatstart+1] == CHAR_ASTERISK) + { + int newnl = 0; + int newbsr = 0; + +/* For completeness and backward compatibility, (*UTFn) is supported in the +relevant libraries, but (*UTF) is generic and always supported. Note that +PCRE_UTF8 == PCRE_UTF16 == PCRE_UTF32. */ + +#ifdef COMPILE_PCRE8 + if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_UTF8_RIGHTPAR, 5) == 0) + { skipatstart += 7; options |= PCRE_UTF8; continue; } +#endif +#ifdef COMPILE_PCRE16 + if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_UTF16_RIGHTPAR, 6) == 0) + { skipatstart += 8; options |= PCRE_UTF16; continue; } +#endif +#ifdef COMPILE_PCRE32 + if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_UTF32_RIGHTPAR, 6) == 0) + { skipatstart += 8; options |= PCRE_UTF32; continue; } +#endif + + else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_UTF_RIGHTPAR, 4) == 0) + { skipatstart += 6; options |= PCRE_UTF8; continue; } + else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_UCP_RIGHTPAR, 4) == 0) + { skipatstart += 6; options |= PCRE_UCP; continue; } + else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_NO_AUTO_POSSESS_RIGHTPAR, 16) == 0) + { skipatstart += 18; options |= PCRE_NO_AUTO_POSSESS; continue; } + else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_NO_START_OPT_RIGHTPAR, 13) == 0) + { skipatstart += 15; options |= PCRE_NO_START_OPTIMIZE; continue; } + + else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_LIMIT_MATCH_EQ, 12) == 0) + { + pcre_uint32 c = 0; + int p = skipatstart + 14; + while (isdigit(ptr[p])) + { + if (c > PCRE_UINT32_MAX / 10 - 1) break; /* Integer overflow */ + c = c*10 + ptr[p++] - CHAR_0; + } + if (ptr[p++] != CHAR_RIGHT_PARENTHESIS) break; + if (c < limit_match) + { + limit_match = c; + cd->external_flags |= PCRE_MLSET; + } + skipatstart = p; + continue; + } + + else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_LIMIT_RECURSION_EQ, 16) == 0) + { + pcre_uint32 c = 0; + int p = skipatstart + 18; + while (isdigit(ptr[p])) + { + if (c > PCRE_UINT32_MAX / 10 - 1) break; /* Integer overflow check */ + c = c*10 + ptr[p++] - CHAR_0; + } + if (ptr[p++] != CHAR_RIGHT_PARENTHESIS) break; + if (c < limit_recursion) + { + limit_recursion = c; + cd->external_flags |= PCRE_RLSET; + } + skipatstart = p; + continue; + } + + if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_CR_RIGHTPAR, 3) == 0) + { skipatstart += 5; newnl = PCRE_NEWLINE_CR; } + else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_LF_RIGHTPAR, 3) == 0) + { skipatstart += 5; newnl = PCRE_NEWLINE_LF; } + else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_CRLF_RIGHTPAR, 5) == 0) + { skipatstart += 7; newnl = PCRE_NEWLINE_CR + PCRE_NEWLINE_LF; } + else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_ANY_RIGHTPAR, 4) == 0) + { skipatstart += 6; newnl = PCRE_NEWLINE_ANY; } + else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_ANYCRLF_RIGHTPAR, 8) == 0) + { skipatstart += 10; newnl = PCRE_NEWLINE_ANYCRLF; } + + else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_BSR_ANYCRLF_RIGHTPAR, 12) == 0) + { skipatstart += 14; newbsr = PCRE_BSR_ANYCRLF; } + else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_BSR_UNICODE_RIGHTPAR, 12) == 0) + { skipatstart += 14; newbsr = PCRE_BSR_UNICODE; } + + if (newnl != 0) + options = (options & ~PCRE_NEWLINE_BITS) | newnl; + else if (newbsr != 0) + options = (options & ~(PCRE_BSR_ANYCRLF|PCRE_BSR_UNICODE)) | newbsr; + else break; + } + +/* PCRE_UTF(16|32) have the same value as PCRE_UTF8. */ +utf = (options & PCRE_UTF8) != 0; +if (utf && never_utf) + { + errorcode = ERR78; + goto PCRE_EARLY_ERROR_RETURN2; + } + +/* Can't support UTF unless PCRE has been compiled to include the code. The +return of an error code from PRIV(valid_utf)() is a new feature, introduced in +release 8.13. It is passed back from pcre_[dfa_]exec(), but at the moment is +not used here. */ + +#ifdef SUPPORT_UTF +if (utf && (options & PCRE_NO_UTF8_CHECK) == 0 && + (errorcode = PRIV(valid_utf)((PCRE_PUCHAR)pattern, -1, erroroffset)) != 0) + { +#if defined COMPILE_PCRE8 + errorcode = ERR44; +#elif defined COMPILE_PCRE16 + errorcode = ERR74; +#elif defined COMPILE_PCRE32 + errorcode = ERR77; +#endif + goto PCRE_EARLY_ERROR_RETURN2; + } +#else +if (utf) + { + errorcode = ERR32; + goto PCRE_EARLY_ERROR_RETURN; + } +#endif + +/* Can't support UCP unless PCRE has been compiled to include the code. */ + +#ifndef SUPPORT_UCP +if ((options & PCRE_UCP) != 0) + { + errorcode = ERR67; + goto PCRE_EARLY_ERROR_RETURN; + } +#endif + +/* Check validity of \R options. */ + +if ((options & (PCRE_BSR_ANYCRLF|PCRE_BSR_UNICODE)) == + (PCRE_BSR_ANYCRLF|PCRE_BSR_UNICODE)) + { + errorcode = ERR56; + goto PCRE_EARLY_ERROR_RETURN; + } + +/* Handle different types of newline. The three bits give seven cases. The +current code allows for fixed one- or two-byte sequences, plus "any" and +"anycrlf". */ + +switch (options & PCRE_NEWLINE_BITS) + { + case 0: newline = NEWLINE; break; /* Build-time default */ + case PCRE_NEWLINE_CR: newline = CHAR_CR; break; + case PCRE_NEWLINE_LF: newline = CHAR_NL; break; + case PCRE_NEWLINE_CR+ + PCRE_NEWLINE_LF: newline = (CHAR_CR << 8) | CHAR_NL; break; + case PCRE_NEWLINE_ANY: newline = -1; break; + case PCRE_NEWLINE_ANYCRLF: newline = -2; break; + default: errorcode = ERR56; goto PCRE_EARLY_ERROR_RETURN; + } + +if (newline == -2) + { + cd->nltype = NLTYPE_ANYCRLF; + } +else if (newline < 0) + { + cd->nltype = NLTYPE_ANY; + } +else + { + cd->nltype = NLTYPE_FIXED; + if (newline > 255) + { + cd->nllen = 2; + cd->nl[0] = (newline >> 8) & 255; + cd->nl[1] = newline & 255; + } + else + { + cd->nllen = 1; + cd->nl[0] = newline; + } + } + +/* Maximum back reference and backref bitmap. The bitmap records up to 31 back +references to help in deciding whether (.*) can be treated as anchored or not. +*/ + +cd->top_backref = 0; +cd->backref_map = 0; + +/* Reflect pattern for debugging output */ + +DPRINTF(("------------------------------------------------------------------\n")); +#ifdef PCRE_DEBUG +print_puchar(stdout, (PCRE_PUCHAR)pattern); +#endif +DPRINTF(("\n")); + +/* Pretend to compile the pattern while actually just accumulating the length +of memory required. This behaviour is triggered by passing a non-NULL final +argument to compile_regex(). We pass a block of workspace (cworkspace) for it +to compile parts of the pattern into; the compiled code is discarded when it is +no longer needed, so hopefully this workspace will never overflow, though there +is a test for its doing so. */ + +cd->bracount = cd->final_bracount = 0; +cd->names_found = 0; +cd->name_entry_size = 0; +cd->name_table = NULL; +cd->dupnames = FALSE; +cd->namedrefcount = 0; +cd->start_code = cworkspace; +cd->hwm = cworkspace; +cd->start_workspace = cworkspace; +cd->workspace_size = COMPILE_WORK_SIZE; +cd->named_groups = named_groups; +cd->named_group_list_size = NAMED_GROUP_LIST_SIZE; +cd->start_pattern = (const pcre_uchar *)pattern; +cd->end_pattern = (const pcre_uchar *)(pattern + STRLEN_UC((const pcre_uchar *)pattern)); +cd->req_varyopt = 0; +cd->parens_depth = 0; +cd->assert_depth = 0; +cd->max_lookbehind = 0; +cd->external_options = options; +cd->open_caps = NULL; + +/* Now do the pre-compile. On error, errorcode will be set non-zero, so we +don't need to look at the result of the function here. The initial options have +been put into the cd block so that they can be changed if an option setting is +found within the regex right at the beginning. Bringing initial option settings +outside can help speed up starting point checks. */ + +ptr += skipatstart; +code = cworkspace; +*code = OP_BRA; + +(void)compile_regex(cd->external_options, &code, &ptr, &errorcode, FALSE, + FALSE, 0, 0, &firstchar, &firstcharflags, &reqchar, &reqcharflags, NULL, + cd, &length); +if (errorcode != 0) goto PCRE_EARLY_ERROR_RETURN; + +DPRINTF(("end pre-compile: length=%d workspace=%d\n", length, + (int)(cd->hwm - cworkspace))); + +if (length > MAX_PATTERN_SIZE) + { + errorcode = ERR20; + goto PCRE_EARLY_ERROR_RETURN; + } + +/* If there are groups with duplicate names and there are also references by +name, we must allow for the possibility of named references to duplicated +groups. These require an extra data item each. */ + +if (cd->dupnames && cd->namedrefcount > 0) + length += cd->namedrefcount * IMM2_SIZE * sizeof(pcre_uchar); + +/* Compute the size of the data block for storing the compiled pattern. Integer +overflow should no longer be possible because nowadays we limit the maximum +value of cd->names_found and cd->name_entry_size. */ + +size = sizeof(REAL_PCRE) + + (length + cd->names_found * cd->name_entry_size) * sizeof(pcre_uchar); + +/* Get the memory. */ + +re = (REAL_PCRE *)(PUBL(malloc))(size); +if (re == NULL) + { + errorcode = ERR21; + goto PCRE_EARLY_ERROR_RETURN; + } + +/* Put in the magic number, and save the sizes, initial options, internal +flags, and character table pointer. NULL is used for the default character +tables. The nullpad field is at the end; it's there to help in the case when a +regex compiled on a system with 4-byte pointers is run on another with 8-byte +pointers. */ + +re->magic_number = MAGIC_NUMBER; +re->size = (int)size; +re->options = cd->external_options; +re->flags = cd->external_flags; +re->limit_match = limit_match; +re->limit_recursion = limit_recursion; +re->first_char = 0; +re->req_char = 0; +re->name_table_offset = sizeof(REAL_PCRE) / sizeof(pcre_uchar); +re->name_entry_size = cd->name_entry_size; +re->name_count = cd->names_found; +re->ref_count = 0; +re->tables = (tables == PRIV(default_tables))? NULL : tables; +re->nullpad = NULL; +#ifdef COMPILE_PCRE32 +re->dummy = 0; +#else +re->dummy1 = re->dummy2 = re->dummy3 = 0; +#endif + +/* The starting points of the name/number translation table and of the code are +passed around in the compile data block. The start/end pattern and initial +options are already set from the pre-compile phase, as is the name_entry_size +field. Reset the bracket count and the names_found field. Also reset the hwm +field; this time it's used for remembering forward references to subpatterns. +*/ + +cd->final_bracount = cd->bracount; /* Save for checking forward references */ +cd->parens_depth = 0; +cd->assert_depth = 0; +cd->bracount = 0; +cd->max_lookbehind = 0; +cd->name_table = (pcre_uchar *)re + re->name_table_offset; +codestart = cd->name_table + re->name_entry_size * re->name_count; +cd->start_code = codestart; +cd->hwm = (pcre_uchar *)(cd->start_workspace); +cd->req_varyopt = 0; +cd->had_accept = FALSE; +cd->had_pruneorskip = FALSE; +cd->check_lookbehind = FALSE; +cd->open_caps = NULL; + +/* If any named groups were found, create the name/number table from the list +created in the first pass. */ + +if (cd->names_found > 0) + { + int i = cd->names_found; + named_group *ng = cd->named_groups; + cd->names_found = 0; + for (; i > 0; i--, ng++) + add_name(cd, ng->name, ng->length, ng->number); + if (cd->named_group_list_size > NAMED_GROUP_LIST_SIZE) + (PUBL(free))((void *)cd->named_groups); + } + +/* Set up a starting, non-extracting bracket, then compile the expression. On +error, errorcode will be set non-zero, so we don't need to look at the result +of the function here. */ + +ptr = (const pcre_uchar *)pattern + skipatstart; +code = (pcre_uchar *)codestart; +*code = OP_BRA; +(void)compile_regex(re->options, &code, &ptr, &errorcode, FALSE, FALSE, 0, 0, + &firstchar, &firstcharflags, &reqchar, &reqcharflags, NULL, cd, NULL); +re->top_bracket = cd->bracount; +re->top_backref = cd->top_backref; +re->max_lookbehind = cd->max_lookbehind; +re->flags = cd->external_flags | PCRE_MODE; + +if (cd->had_accept) + { + reqchar = 0; /* Must disable after (*ACCEPT) */ + reqcharflags = REQ_NONE; + } + +/* If not reached end of pattern on success, there's an excess bracket. */ + +if (errorcode == 0 && *ptr != CHAR_NULL) errorcode = ERR22; + +/* Fill in the terminating state and check for disastrous overflow, but +if debugging, leave the test till after things are printed out. */ + +*code++ = OP_END; + +#ifndef PCRE_DEBUG +if (code - codestart > length) errorcode = ERR23; +#endif + +#ifdef SUPPORT_VALGRIND +/* If the estimated length exceeds the really used length, mark the extra +allocated memory as unaddressable, so that any out-of-bound reads can be +detected. */ +VALGRIND_MAKE_MEM_NOACCESS(code, (length - (code - codestart)) * sizeof(pcre_uchar)); +#endif + +/* Fill in any forward references that are required. There may be repeated +references; optimize for them, as searching a large regex takes time. */ + +if (cd->hwm > cd->start_workspace) + { + int prev_recno = -1; + const pcre_uchar *groupptr = NULL; + while (errorcode == 0 && cd->hwm > cd->start_workspace) + { + int offset, recno; + cd->hwm -= LINK_SIZE; + offset = GET(cd->hwm, 0); + recno = GET(codestart, offset); + if (recno != prev_recno) + { + groupptr = PRIV(find_bracket)(codestart, utf, recno); + prev_recno = recno; + } + if (groupptr == NULL) errorcode = ERR53; + else PUT(((pcre_uchar *)codestart), offset, (int)(groupptr - codestart)); + } + } + +/* If the workspace had to be expanded, free the new memory. Set the pointer to +NULL to indicate that forward references have been filled in. */ + +if (cd->workspace_size > COMPILE_WORK_SIZE) + (PUBL(free))((void *)cd->start_workspace); +cd->start_workspace = NULL; + +/* Give an error if there's back reference to a non-existent capturing +subpattern. */ + +if (errorcode == 0 && re->top_backref > re->top_bracket) errorcode = ERR15; + +/* Unless disabled, check whether any single character iterators can be +auto-possessified. The function overwrites the appropriate opcode values, so +the type of the pointer must be cast. NOTE: the intermediate variable "temp" is +used in this code because at least one compiler gives a warning about loss of +"const" attribute if the cast (pcre_uchar *)codestart is used directly in the +function call. */ + +if ((options & PCRE_NO_AUTO_POSSESS) == 0) + { + pcre_uchar *temp = (pcre_uchar *)codestart; + auto_possessify(temp, utf, cd); + } + +/* If there were any lookbehind assertions that contained OP_RECURSE +(recursions or subroutine calls), a flag is set for them to be checked here, +because they may contain forward references. Actual recursions cannot be fixed +length, but subroutine calls can. It is done like this so that those without +OP_RECURSE that are not fixed length get a diagnosic with a useful offset. The +exceptional ones forgo this. We scan the pattern to check that they are fixed +length, and set their lengths. */ + +if (cd->check_lookbehind) + { + pcre_uchar *cc = (pcre_uchar *)codestart; + + /* Loop, searching for OP_REVERSE items, and process those that do not have + their length set. (Actually, it will also re-process any that have a length + of zero, but that is a pathological case, and it does no harm.) When we find + one, we temporarily terminate the branch it is in while we scan it. */ + + for (cc = (pcre_uchar *)PRIV(find_bracket)(codestart, utf, -1); + cc != NULL; + cc = (pcre_uchar *)PRIV(find_bracket)(cc, utf, -1)) + { + if (GET(cc, 1) == 0) + { + int fixed_length; + pcre_uchar *be = cc - 1 - LINK_SIZE + GET(cc, -LINK_SIZE); + int end_op = *be; + *be = OP_END; + fixed_length = find_fixedlength(cc, (re->options & PCRE_UTF8) != 0, TRUE, + cd); + *be = end_op; + DPRINTF(("fixed length = %d\n", fixed_length)); + if (fixed_length < 0) + { + errorcode = (fixed_length == -2)? ERR36 : + (fixed_length == -4)? ERR70 : ERR25; + break; + } + if (fixed_length > cd->max_lookbehind) cd->max_lookbehind = fixed_length; + PUT(cc, 1, fixed_length); + } + cc += 1 + LINK_SIZE; + } + } + +/* Failed to compile, or error while post-processing */ + +if (errorcode != 0) + { + (PUBL(free))(re); + PCRE_EARLY_ERROR_RETURN: + *erroroffset = (int)(ptr - (const pcre_uchar *)pattern); + PCRE_EARLY_ERROR_RETURN2: + *errorptr = find_error_text(errorcode); + if (errorcodeptr != NULL) *errorcodeptr = errorcode; + return NULL; + } + +/* If the anchored option was not passed, set the flag if we can determine that +the pattern is anchored by virtue of ^ characters or \A or anything else, such +as starting with non-atomic .* when DOTALL is set and there are no occurrences +of *PRUNE or *SKIP. + +Otherwise, if we know what the first byte has to be, save it, because that +speeds up unanchored matches no end. If not, see if we can set the +PCRE_STARTLINE flag. This is helpful for multiline matches when all branches +start with ^. and also when all branches start with non-atomic .* for +non-DOTALL matches when *PRUNE and SKIP are not present. */ + +if ((re->options & PCRE_ANCHORED) == 0) + { + if (is_anchored(codestart, 0, cd, 0)) re->options |= PCRE_ANCHORED; + else + { + if (firstcharflags < 0) + firstchar = find_firstassertedchar(codestart, &firstcharflags, FALSE); + if (firstcharflags >= 0) /* Remove caseless flag for non-caseable chars */ + { +#if defined COMPILE_PCRE8 + re->first_char = firstchar & 0xff; +#elif defined COMPILE_PCRE16 + re->first_char = firstchar & 0xffff; +#elif defined COMPILE_PCRE32 + re->first_char = firstchar; +#endif + if ((firstcharflags & REQ_CASELESS) != 0) + { +#if defined SUPPORT_UCP && !(defined COMPILE_PCRE8) + /* We ignore non-ASCII first chars in 8 bit mode. */ + if (utf) + { + if (re->first_char < 128) + { + if (cd->fcc[re->first_char] != re->first_char) + re->flags |= PCRE_FCH_CASELESS; + } + else if (UCD_OTHERCASE(re->first_char) != re->first_char) + re->flags |= PCRE_FCH_CASELESS; + } + else +#endif + if (MAX_255(re->first_char) + && cd->fcc[re->first_char] != re->first_char) + re->flags |= PCRE_FCH_CASELESS; + } + + re->flags |= PCRE_FIRSTSET; + } + + else if (is_startline(codestart, 0, cd, 0)) re->flags |= PCRE_STARTLINE; + } + } + +/* For an anchored pattern, we use the "required byte" only if it follows a +variable length item in the regex. Remove the caseless flag for non-caseable +bytes. */ + +if (reqcharflags >= 0 && + ((re->options & PCRE_ANCHORED) == 0 || (reqcharflags & REQ_VARY) != 0)) + { +#if defined COMPILE_PCRE8 + re->req_char = reqchar & 0xff; +#elif defined COMPILE_PCRE16 + re->req_char = reqchar & 0xffff; +#elif defined COMPILE_PCRE32 + re->req_char = reqchar; +#endif + if ((reqcharflags & REQ_CASELESS) != 0) + { +#if defined SUPPORT_UCP && !(defined COMPILE_PCRE8) + /* We ignore non-ASCII first chars in 8 bit mode. */ + if (utf) + { + if (re->req_char < 128) + { + if (cd->fcc[re->req_char] != re->req_char) + re->flags |= PCRE_RCH_CASELESS; + } + else if (UCD_OTHERCASE(re->req_char) != re->req_char) + re->flags |= PCRE_RCH_CASELESS; + } + else +#endif + if (MAX_255(re->req_char) && cd->fcc[re->req_char] != re->req_char) + re->flags |= PCRE_RCH_CASELESS; + } + + re->flags |= PCRE_REQCHSET; + } + +/* Print out the compiled data if debugging is enabled. This is never the +case when building a production library. */ + +#ifdef PCRE_DEBUG +printf("Length = %d top_bracket = %d top_backref = %d\n", + length, re->top_bracket, re->top_backref); + +printf("Options=%08x\n", re->options); + +if ((re->flags & PCRE_FIRSTSET) != 0) + { + pcre_uchar ch = re->first_char; + const char *caseless = + ((re->flags & PCRE_FCH_CASELESS) == 0)? "" : " (caseless)"; + if (PRINTABLE(ch)) printf("First char = %c%s\n", ch, caseless); + else printf("First char = \\x%02x%s\n", ch, caseless); + } + +if ((re->flags & PCRE_REQCHSET) != 0) + { + pcre_uchar ch = re->req_char; + const char *caseless = + ((re->flags & PCRE_RCH_CASELESS) == 0)? "" : " (caseless)"; + if (PRINTABLE(ch)) printf("Req char = %c%s\n", ch, caseless); + else printf("Req char = \\x%02x%s\n", ch, caseless); + } + +#if defined COMPILE_PCRE8 +pcre_printint((pcre *)re, stdout, TRUE); +#elif defined COMPILE_PCRE16 +pcre16_printint((pcre *)re, stdout, TRUE); +#elif defined COMPILE_PCRE32 +pcre32_printint((pcre *)re, stdout, TRUE); +#endif + +/* This check is done here in the debugging case so that the code that +was compiled can be seen. */ + +if (code - codestart > length) + { + (PUBL(free))(re); + *errorptr = find_error_text(ERR23); + *erroroffset = ptr - (pcre_uchar *)pattern; + if (errorcodeptr != NULL) *errorcodeptr = ERR23; + return NULL; + } +#endif /* PCRE_DEBUG */ + +/* Check for a pattern than can match an empty string, so that this information +can be provided to applications. */ + +do + { + if (could_be_empty_branch(codestart, code, utf, cd, NULL)) + { + re->flags |= PCRE_MATCH_EMPTY; + break; + } + codestart += GET(codestart, 1); + } +while (*codestart == OP_ALT); + +#if defined COMPILE_PCRE8 +return (pcre *)re; +#elif defined COMPILE_PCRE16 +return (pcre16 *)re; +#elif defined COMPILE_PCRE32 +return (pcre32 *)re; +#endif +} + +/* End of pcre_compile.c */ + diff --git a/src/private/pcre_src/pcre_config.c b/src/private/pcre_src/pcre_config.c new file mode 100644 index 000000000..1cbdd9c96 --- /dev/null +++ b/src/private/pcre_src/pcre_config.c @@ -0,0 +1,190 @@ +/************************************************* +* Perl-Compatible Regular Expressions * +*************************************************/ + +/* PCRE is a library of functions to support regular expressions whose syntax +and semantics are as close as possible to those of the Perl 5 language. + + Written by Philip Hazel + Copyright (c) 1997-2012 University of Cambridge + +----------------------------------------------------------------------------- +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * Neither the name of the University of Cambridge nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. +----------------------------------------------------------------------------- +*/ + + +/* This module contains the external function pcre_config(). */ + + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +/* Keep the original link size. */ +static int real_link_size = LINK_SIZE; + +#include "pcre_internal.h" + + +/************************************************* +* Return info about what features are configured * +*************************************************/ + +/* This function has an extensible interface so that additional items can be +added compatibly. + +Arguments: + what what information is required + where where to put the information + +Returns: 0 if data returned, negative on error +*/ + +#if defined COMPILE_PCRE8 +PCRE_EXP_DEFN int PCRE_CALL_CONVENTION +pcre_config(int what, void *where) +#elif defined COMPILE_PCRE16 +PCRE_EXP_DEFN int PCRE_CALL_CONVENTION +pcre16_config(int what, void *where) +#elif defined COMPILE_PCRE32 +PCRE_EXP_DEFN int PCRE_CALL_CONVENTION +pcre32_config(int what, void *where) +#endif +{ +switch (what) + { + case PCRE_CONFIG_UTF8: +#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 + *((int *)where) = 0; + return PCRE_ERROR_BADOPTION; +#else +#if defined SUPPORT_UTF + *((int *)where) = 1; +#else + *((int *)where) = 0; +#endif + break; +#endif + + case PCRE_CONFIG_UTF16: +#if defined COMPILE_PCRE8 || defined COMPILE_PCRE32 + *((int *)where) = 0; + return PCRE_ERROR_BADOPTION; +#else +#if defined SUPPORT_UTF + *((int *)where) = 1; +#else + *((int *)where) = 0; +#endif + break; +#endif + + case PCRE_CONFIG_UTF32: +#if defined COMPILE_PCRE8 || defined COMPILE_PCRE16 + *((int *)where) = 0; + return PCRE_ERROR_BADOPTION; +#else +#if defined SUPPORT_UTF + *((int *)where) = 1; +#else + *((int *)where) = 0; +#endif + break; +#endif + + case PCRE_CONFIG_UNICODE_PROPERTIES: +#ifdef SUPPORT_UCP + *((int *)where) = 1; +#else + *((int *)where) = 0; +#endif + break; + + case PCRE_CONFIG_JIT: +#ifdef SUPPORT_JIT + *((int *)where) = 1; +#else + *((int *)where) = 0; +#endif + break; + + case PCRE_CONFIG_JITTARGET: +#ifdef SUPPORT_JIT + *((const char **)where) = PRIV(jit_get_target)(); +#else + *((const char **)where) = NULL; +#endif + break; + + case PCRE_CONFIG_NEWLINE: + *((int *)where) = NEWLINE; + break; + + case PCRE_CONFIG_BSR: +#ifdef BSR_ANYCRLF + *((int *)where) = 1; +#else + *((int *)where) = 0; +#endif + break; + + case PCRE_CONFIG_LINK_SIZE: + *((int *)where) = real_link_size; + break; + + case PCRE_CONFIG_POSIX_MALLOC_THRESHOLD: + *((int *)where) = POSIX_MALLOC_THRESHOLD; + break; + + case PCRE_CONFIG_PARENS_LIMIT: + *((unsigned long int *)where) = PARENS_NEST_LIMIT; + break; + + case PCRE_CONFIG_MATCH_LIMIT: + *((unsigned long int *)where) = MATCH_LIMIT; + break; + + case PCRE_CONFIG_MATCH_LIMIT_RECURSION: + *((unsigned long int *)where) = MATCH_LIMIT_RECURSION; + break; + + case PCRE_CONFIG_STACKRECURSE: +#ifdef NO_RECURSE + *((int *)where) = 0; +#else + *((int *)where) = 1; +#endif + break; + + default: return PCRE_ERROR_BADOPTION; + } + +return 0; +} + +/* End of pcre_config.c */ diff --git a/src/private/pcre_src/pcre_dfa_exec.c b/src/private/pcre_src/pcre_dfa_exec.c new file mode 100644 index 000000000..87f4aef9a --- /dev/null +++ b/src/private/pcre_src/pcre_dfa_exec.c @@ -0,0 +1,3673 @@ +/************************************************* +* Perl-Compatible Regular Expressions * +*************************************************/ + +/* PCRE is a library of functions to support regular expressions whose syntax +and semantics are as close as possible to those of the Perl 5 language (but see +below for why this module is different). + + Written by Philip Hazel + Copyright (c) 1997-2014 University of Cambridge + +----------------------------------------------------------------------------- +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * Neither the name of the University of Cambridge nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. +----------------------------------------------------------------------------- +*/ + +/* This module contains the external function pcre_dfa_exec(), which is an +alternative matching function that uses a sort of DFA algorithm (not a true +FSM). This is NOT Perl-compatible, but it has advantages in certain +applications. */ + + +/* NOTE ABOUT PERFORMANCE: A user of this function sent some code that improved +the performance of his patterns greatly. I could not use it as it stood, as it +was not thread safe, and made assumptions about pattern sizes. Also, it caused +test 7 to loop, and test 9 to crash with a segfault. + +The issue is the check for duplicate states, which is done by a simple linear +search up the state list. (Grep for "duplicate" below to find the code.) For +many patterns, there will never be many states active at one time, so a simple +linear search is fine. In patterns that have many active states, it might be a +bottleneck. The suggested code used an indexing scheme to remember which states +had previously been used for each character, and avoided the linear search when +it knew there was no chance of a duplicate. This was implemented when adding +states to the state lists. + +I wrote some thread-safe, not-limited code to try something similar at the time +of checking for duplicates (instead of when adding states), using index vectors +on the stack. It did give a 13% improvement with one specially constructed +pattern for certain subject strings, but on other strings and on many of the +simpler patterns in the test suite it did worse. The major problem, I think, +was the extra time to initialize the index. This had to be done for each call +of internal_dfa_exec(). (The supplied patch used a static vector, initialized +only once - I suspect this was the cause of the problems with the tests.) + +Overall, I concluded that the gains in some cases did not outweigh the losses +in others, so I abandoned this code. */ + + + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#define NLBLOCK md /* Block containing newline information */ +#define PSSTART start_subject /* Field containing processed string start */ +#define PSEND end_subject /* Field containing processed string end */ + +#include "pcre_internal.h" + + +/* For use to indent debugging output */ + +#define SP " " + + +/************************************************* +* Code parameters and static tables * +*************************************************/ + +/* These are offsets that are used to turn the OP_TYPESTAR and friends opcodes +into others, under special conditions. A gap of 20 between the blocks should be +enough. The resulting opcodes don't have to be less than 256 because they are +never stored, so we push them well clear of the normal opcodes. */ + +#define OP_PROP_EXTRA 300 +#define OP_EXTUNI_EXTRA 320 +#define OP_ANYNL_EXTRA 340 +#define OP_HSPACE_EXTRA 360 +#define OP_VSPACE_EXTRA 380 + + +/* This table identifies those opcodes that are followed immediately by a +character that is to be tested in some way. This makes it possible to +centralize the loading of these characters. In the case of Type * etc, the +"character" is the opcode for \D, \d, \S, \s, \W, or \w, which will always be a +small value. Non-zero values in the table are the offsets from the opcode where +the character is to be found. ***NOTE*** If the start of this table is +modified, the three tables that follow must also be modified. */ + +static const pcre_uint8 coptable[] = { + 0, /* End */ + 0, 0, 0, 0, 0, /* \A, \G, \K, \B, \b */ + 0, 0, 0, 0, 0, 0, /* \D, \d, \S, \s, \W, \w */ + 0, 0, 0, /* Any, AllAny, Anybyte */ + 0, 0, /* \P, \p */ + 0, 0, 0, 0, 0, /* \R, \H, \h, \V, \v */ + 0, /* \X */ + 0, 0, 0, 0, 0, 0, /* \Z, \z, $, $M, ^, ^M */ + 1, /* Char */ + 1, /* Chari */ + 1, /* not */ + 1, /* noti */ + /* Positive single-char repeats */ + 1, 1, 1, 1, 1, 1, /* *, *?, +, +?, ?, ?? */ + 1+IMM2_SIZE, 1+IMM2_SIZE, /* upto, minupto */ + 1+IMM2_SIZE, /* exact */ + 1, 1, 1, 1+IMM2_SIZE, /* *+, ++, ?+, upto+ */ + 1, 1, 1, 1, 1, 1, /* *I, *?I, +I, +?I, ?I, ??I */ + 1+IMM2_SIZE, 1+IMM2_SIZE, /* upto I, minupto I */ + 1+IMM2_SIZE, /* exact I */ + 1, 1, 1, 1+IMM2_SIZE, /* *+I, ++I, ?+I, upto+I */ + /* Negative single-char repeats - only for chars < 256 */ + 1, 1, 1, 1, 1, 1, /* NOT *, *?, +, +?, ?, ?? */ + 1+IMM2_SIZE, 1+IMM2_SIZE, /* NOT upto, minupto */ + 1+IMM2_SIZE, /* NOT exact */ + 1, 1, 1, 1+IMM2_SIZE, /* NOT *+, ++, ?+, upto+ */ + 1, 1, 1, 1, 1, 1, /* NOT *I, *?I, +I, +?I, ?I, ??I */ + 1+IMM2_SIZE, 1+IMM2_SIZE, /* NOT upto I, minupto I */ + 1+IMM2_SIZE, /* NOT exact I */ + 1, 1, 1, 1+IMM2_SIZE, /* NOT *+I, ++I, ?+I, upto+I */ + /* Positive type repeats */ + 1, 1, 1, 1, 1, 1, /* Type *, *?, +, +?, ?, ?? */ + 1+IMM2_SIZE, 1+IMM2_SIZE, /* Type upto, minupto */ + 1+IMM2_SIZE, /* Type exact */ + 1, 1, 1, 1+IMM2_SIZE, /* Type *+, ++, ?+, upto+ */ + /* Character class & ref repeats */ + 0, 0, 0, 0, 0, 0, /* *, *?, +, +?, ?, ?? */ + 0, 0, /* CRRANGE, CRMINRANGE */ + 0, 0, 0, 0, /* Possessive *+, ++, ?+, CRPOSRANGE */ + 0, /* CLASS */ + 0, /* NCLASS */ + 0, /* XCLASS - variable length */ + 0, /* REF */ + 0, /* REFI */ + 0, /* DNREF */ + 0, /* DNREFI */ + 0, /* RECURSE */ + 0, /* CALLOUT */ + 0, /* Alt */ + 0, /* Ket */ + 0, /* KetRmax */ + 0, /* KetRmin */ + 0, /* KetRpos */ + 0, /* Reverse */ + 0, /* Assert */ + 0, /* Assert not */ + 0, /* Assert behind */ + 0, /* Assert behind not */ + 0, 0, /* ONCE, ONCE_NC */ + 0, 0, 0, 0, 0, /* BRA, BRAPOS, CBRA, CBRAPOS, COND */ + 0, 0, 0, 0, 0, /* SBRA, SBRAPOS, SCBRA, SCBRAPOS, SCOND */ + 0, 0, /* CREF, DNCREF */ + 0, 0, /* RREF, DNRREF */ + 0, /* DEF */ + 0, 0, 0, /* BRAZERO, BRAMINZERO, BRAPOSZERO */ + 0, 0, 0, /* MARK, PRUNE, PRUNE_ARG */ + 0, 0, 0, 0, /* SKIP, SKIP_ARG, THEN, THEN_ARG */ + 0, 0, 0, 0, /* COMMIT, FAIL, ACCEPT, ASSERT_ACCEPT */ + 0, 0 /* CLOSE, SKIPZERO */ +}; + +/* This table identifies those opcodes that inspect a character. It is used to +remember the fact that a character could have been inspected when the end of +the subject is reached. ***NOTE*** If the start of this table is modified, the +two tables that follow must also be modified. */ + +static const pcre_uint8 poptable[] = { + 0, /* End */ + 0, 0, 0, 1, 1, /* \A, \G, \K, \B, \b */ + 1, 1, 1, 1, 1, 1, /* \D, \d, \S, \s, \W, \w */ + 1, 1, 1, /* Any, AllAny, Anybyte */ + 1, 1, /* \P, \p */ + 1, 1, 1, 1, 1, /* \R, \H, \h, \V, \v */ + 1, /* \X */ + 0, 0, 0, 0, 0, 0, /* \Z, \z, $, $M, ^, ^M */ + 1, /* Char */ + 1, /* Chari */ + 1, /* not */ + 1, /* noti */ + /* Positive single-char repeats */ + 1, 1, 1, 1, 1, 1, /* *, *?, +, +?, ?, ?? */ + 1, 1, 1, /* upto, minupto, exact */ + 1, 1, 1, 1, /* *+, ++, ?+, upto+ */ + 1, 1, 1, 1, 1, 1, /* *I, *?I, +I, +?I, ?I, ??I */ + 1, 1, 1, /* upto I, minupto I, exact I */ + 1, 1, 1, 1, /* *+I, ++I, ?+I, upto+I */ + /* Negative single-char repeats - only for chars < 256 */ + 1, 1, 1, 1, 1, 1, /* NOT *, *?, +, +?, ?, ?? */ + 1, 1, 1, /* NOT upto, minupto, exact */ + 1, 1, 1, 1, /* NOT *+, ++, ?+, upto+ */ + 1, 1, 1, 1, 1, 1, /* NOT *I, *?I, +I, +?I, ?I, ??I */ + 1, 1, 1, /* NOT upto I, minupto I, exact I */ + 1, 1, 1, 1, /* NOT *+I, ++I, ?+I, upto+I */ + /* Positive type repeats */ + 1, 1, 1, 1, 1, 1, /* Type *, *?, +, +?, ?, ?? */ + 1, 1, 1, /* Type upto, minupto, exact */ + 1, 1, 1, 1, /* Type *+, ++, ?+, upto+ */ + /* Character class & ref repeats */ + 1, 1, 1, 1, 1, 1, /* *, *?, +, +?, ?, ?? */ + 1, 1, /* CRRANGE, CRMINRANGE */ + 1, 1, 1, 1, /* Possessive *+, ++, ?+, CRPOSRANGE */ + 1, /* CLASS */ + 1, /* NCLASS */ + 1, /* XCLASS - variable length */ + 0, /* REF */ + 0, /* REFI */ + 0, /* DNREF */ + 0, /* DNREFI */ + 0, /* RECURSE */ + 0, /* CALLOUT */ + 0, /* Alt */ + 0, /* Ket */ + 0, /* KetRmax */ + 0, /* KetRmin */ + 0, /* KetRpos */ + 0, /* Reverse */ + 0, /* Assert */ + 0, /* Assert not */ + 0, /* Assert behind */ + 0, /* Assert behind not */ + 0, 0, /* ONCE, ONCE_NC */ + 0, 0, 0, 0, 0, /* BRA, BRAPOS, CBRA, CBRAPOS, COND */ + 0, 0, 0, 0, 0, /* SBRA, SBRAPOS, SCBRA, SCBRAPOS, SCOND */ + 0, 0, /* CREF, DNCREF */ + 0, 0, /* RREF, DNRREF */ + 0, /* DEF */ + 0, 0, 0, /* BRAZERO, BRAMINZERO, BRAPOSZERO */ + 0, 0, 0, /* MARK, PRUNE, PRUNE_ARG */ + 0, 0, 0, 0, /* SKIP, SKIP_ARG, THEN, THEN_ARG */ + 0, 0, 0, 0, /* COMMIT, FAIL, ACCEPT, ASSERT_ACCEPT */ + 0, 0 /* CLOSE, SKIPZERO */ +}; + +/* These 2 tables allow for compact code for testing for \D, \d, \S, \s, \W, +and \w */ + +static const pcre_uint8 toptable1[] = { + 0, 0, 0, 0, 0, 0, + ctype_digit, ctype_digit, + ctype_space, ctype_space, + ctype_word, ctype_word, + 0, 0 /* OP_ANY, OP_ALLANY */ +}; + +static const pcre_uint8 toptable2[] = { + 0, 0, 0, 0, 0, 0, + ctype_digit, 0, + ctype_space, 0, + ctype_word, 0, + 1, 1 /* OP_ANY, OP_ALLANY */ +}; + + +/* Structure for holding data about a particular state, which is in effect the +current data for an active path through the match tree. It must consist +entirely of ints because the working vector we are passed, and which we put +these structures in, is a vector of ints. */ + +typedef struct stateblock { + int offset; /* Offset to opcode */ + int count; /* Count for repeats */ + int data; /* Some use extra data */ +} stateblock; + +#define INTS_PER_STATEBLOCK (int)(sizeof(stateblock)/sizeof(int)) + + +#ifdef PCRE_DEBUG +/************************************************* +* Print character string * +*************************************************/ + +/* Character string printing function for debugging. + +Arguments: + p points to string + length number of bytes + f where to print + +Returns: nothing +*/ + +static void +pchars(const pcre_uchar *p, int length, FILE *f) +{ +pcre_uint32 c; +while (length-- > 0) + { + if (isprint(c = *(p++))) + fprintf(f, "%c", c); + else + fprintf(f, "\\x{%02x}", c); + } +} +#endif + + + +/************************************************* +* Execute a Regular Expression - DFA engine * +*************************************************/ + +/* This internal function applies a compiled pattern to a subject string, +starting at a given point, using a DFA engine. This function is called from the +external one, possibly multiple times if the pattern is not anchored. The +function calls itself recursively for some kinds of subpattern. + +Arguments: + md the match_data block with fixed information + this_start_code the opening bracket of this subexpression's code + current_subject where we currently are in the subject string + start_offset start offset in the subject string + offsets vector to contain the matching string offsets + offsetcount size of same + workspace vector of workspace + wscount size of same + rlevel function call recursion level + +Returns: > 0 => number of match offset pairs placed in offsets + = 0 => offsets overflowed; longest matches are present + -1 => failed to match + < -1 => some kind of unexpected problem + +The following macros are used for adding states to the two state vectors (one +for the current character, one for the following character). */ + +#define ADD_ACTIVE(x,y) \ + if (active_count++ < wscount) \ + { \ + next_active_state->offset = (x); \ + next_active_state->count = (y); \ + next_active_state++; \ + DPRINTF(("%.*sADD_ACTIVE(%d,%d)\n", rlevel*2-2, SP, (x), (y))); \ + } \ + else return PCRE_ERROR_DFA_WSSIZE + +#define ADD_ACTIVE_DATA(x,y,z) \ + if (active_count++ < wscount) \ + { \ + next_active_state->offset = (x); \ + next_active_state->count = (y); \ + next_active_state->data = (z); \ + next_active_state++; \ + DPRINTF(("%.*sADD_ACTIVE_DATA(%d,%d,%d)\n", rlevel*2-2, SP, (x), (y), (z))); \ + } \ + else return PCRE_ERROR_DFA_WSSIZE + +#define ADD_NEW(x,y) \ + if (new_count++ < wscount) \ + { \ + next_new_state->offset = (x); \ + next_new_state->count = (y); \ + next_new_state++; \ + DPRINTF(("%.*sADD_NEW(%d,%d)\n", rlevel*2-2, SP, (x), (y))); \ + } \ + else return PCRE_ERROR_DFA_WSSIZE + +#define ADD_NEW_DATA(x,y,z) \ + if (new_count++ < wscount) \ + { \ + next_new_state->offset = (x); \ + next_new_state->count = (y); \ + next_new_state->data = (z); \ + next_new_state++; \ + DPRINTF(("%.*sADD_NEW_DATA(%d,%d,%d) line %d\n", rlevel*2-2, SP, \ + (x), (y), (z), __LINE__)); \ + } \ + else return PCRE_ERROR_DFA_WSSIZE + +/* And now, here is the code */ + +static int +internal_dfa_exec( + dfa_match_data *md, + const pcre_uchar *this_start_code, + const pcre_uchar *current_subject, + int start_offset, + int *offsets, + int offsetcount, + int *workspace, + int wscount, + int rlevel) +{ +stateblock *active_states, *new_states, *temp_states; +stateblock *next_active_state, *next_new_state; + +const pcre_uint8 *ctypes, *lcc, *fcc; +const pcre_uchar *ptr; +const pcre_uchar *end_code, *first_op; + +dfa_recursion_info new_recursive; + +int active_count, new_count, match_count; + +/* Some fields in the md block are frequently referenced, so we load them into +independent variables in the hope that this will perform better. */ + +const pcre_uchar *start_subject = md->start_subject; +const pcre_uchar *end_subject = md->end_subject; +const pcre_uchar *start_code = md->start_code; + +#ifdef SUPPORT_UTF +BOOL utf = (md->poptions & PCRE_UTF8) != 0; +#else +BOOL utf = FALSE; +#endif + +BOOL reset_could_continue = FALSE; + +rlevel++; +offsetcount &= (-2); + +wscount -= 2; +wscount = (wscount - (wscount % (INTS_PER_STATEBLOCK * 2))) / + (2 * INTS_PER_STATEBLOCK); + +DPRINTF(("\n%.*s---------------------\n" + "%.*sCall to internal_dfa_exec f=%d\n", + rlevel*2-2, SP, rlevel*2-2, SP, rlevel)); + +ctypes = md->tables + ctypes_offset; +lcc = md->tables + lcc_offset; +fcc = md->tables + fcc_offset; + +match_count = PCRE_ERROR_NOMATCH; /* A negative number */ + +active_states = (stateblock *)(workspace + 2); +next_new_state = new_states = active_states + wscount; +new_count = 0; + +first_op = this_start_code + 1 + LINK_SIZE + + ((*this_start_code == OP_CBRA || *this_start_code == OP_SCBRA || + *this_start_code == OP_CBRAPOS || *this_start_code == OP_SCBRAPOS) + ? IMM2_SIZE:0); + +/* The first thing in any (sub) pattern is a bracket of some sort. Push all +the alternative states onto the list, and find out where the end is. This +makes is possible to use this function recursively, when we want to stop at a +matching internal ket rather than at the end. + +If the first opcode in the first alternative is OP_REVERSE, we are dealing with +a backward assertion. In that case, we have to find out the maximum amount to +move back, and set up each alternative appropriately. */ + +if (*first_op == OP_REVERSE) + { + int max_back = 0; + int gone_back; + + end_code = this_start_code; + do + { + int back = GET(end_code, 2+LINK_SIZE); + if (back > max_back) max_back = back; + end_code += GET(end_code, 1); + } + while (*end_code == OP_ALT); + + /* If we can't go back the amount required for the longest lookbehind + pattern, go back as far as we can; some alternatives may still be viable. */ + +#ifdef SUPPORT_UTF + /* In character mode we have to step back character by character */ + + if (utf) + { + for (gone_back = 0; gone_back < max_back; gone_back++) + { + if (current_subject <= start_subject) break; + current_subject--; + ACROSSCHAR(current_subject > start_subject, *current_subject, current_subject--); + } + } + else +#endif + + /* In byte-mode we can do this quickly. */ + + { + gone_back = (current_subject - max_back < start_subject)? + (int)(current_subject - start_subject) : max_back; + current_subject -= gone_back; + } + + /* Save the earliest consulted character */ + + if (current_subject < md->start_used_ptr) + md->start_used_ptr = current_subject; + + /* Now we can process the individual branches. */ + + end_code = this_start_code; + do + { + int back = GET(end_code, 2+LINK_SIZE); + if (back <= gone_back) + { + int bstate = (int)(end_code - start_code + 2 + 2*LINK_SIZE); + ADD_NEW_DATA(-bstate, 0, gone_back - back); + } + end_code += GET(end_code, 1); + } + while (*end_code == OP_ALT); + } + +/* This is the code for a "normal" subpattern (not a backward assertion). The +start of a whole pattern is always one of these. If we are at the top level, +we may be asked to restart matching from the same point that we reached for a +previous partial match. We still have to scan through the top-level branches to +find the end state. */ + +else + { + end_code = this_start_code; + + /* Restarting */ + + if (rlevel == 1 && (md->moptions & PCRE_DFA_RESTART) != 0) + { + do { end_code += GET(end_code, 1); } while (*end_code == OP_ALT); + new_count = workspace[1]; + if (!workspace[0]) + memcpy(new_states, active_states, new_count * sizeof(stateblock)); + } + + /* Not restarting */ + + else + { + int length = 1 + LINK_SIZE + + ((*this_start_code == OP_CBRA || *this_start_code == OP_SCBRA || + *this_start_code == OP_CBRAPOS || *this_start_code == OP_SCBRAPOS) + ? IMM2_SIZE:0); + do + { + ADD_NEW((int)(end_code - start_code + length), 0); + end_code += GET(end_code, 1); + length = 1 + LINK_SIZE; + } + while (*end_code == OP_ALT); + } + } + +workspace[0] = 0; /* Bit indicating which vector is current */ + +DPRINTF(("%.*sEnd state = %d\n", rlevel*2-2, SP, (int)(end_code - start_code))); + +/* Loop for scanning the subject */ + +ptr = current_subject; +for (;;) + { + int i, j; + int clen, dlen; + pcre_uint32 c, d; + int forced_fail = 0; + BOOL partial_newline = FALSE; + BOOL could_continue = reset_could_continue; + reset_could_continue = FALSE; + + /* Make the new state list into the active state list and empty the + new state list. */ + + temp_states = active_states; + active_states = new_states; + new_states = temp_states; + active_count = new_count; + new_count = 0; + + workspace[0] ^= 1; /* Remember for the restarting feature */ + workspace[1] = active_count; + +#ifdef PCRE_DEBUG + printf("%.*sNext character: rest of subject = \"", rlevel*2-2, SP); + pchars(ptr, STRLEN_UC(ptr), stdout); + printf("\"\n"); + + printf("%.*sActive states: ", rlevel*2-2, SP); + for (i = 0; i < active_count; i++) + printf("%d/%d ", active_states[i].offset, active_states[i].count); + printf("\n"); +#endif + + /* Set the pointers for adding new states */ + + next_active_state = active_states + active_count; + next_new_state = new_states; + + /* Load the current character from the subject outside the loop, as many + different states may want to look at it, and we assume that at least one + will. */ + + if (ptr < end_subject) + { + clen = 1; /* Number of data items in the character */ +#ifdef SUPPORT_UTF + GETCHARLENTEST(c, ptr, clen); +#else + c = *ptr; +#endif /* SUPPORT_UTF */ + } + else + { + clen = 0; /* This indicates the end of the subject */ + c = NOTACHAR; /* This value should never actually be used */ + } + + /* Scan up the active states and act on each one. The result of an action + may be to add more states to the currently active list (e.g. on hitting a + parenthesis) or it may be to put states on the new list, for considering + when we move the character pointer on. */ + + for (i = 0; i < active_count; i++) + { + stateblock *current_state = active_states + i; + BOOL caseless = FALSE; + const pcre_uchar *code; + int state_offset = current_state->offset; + int codevalue, rrc; + int count; + +#ifdef PCRE_DEBUG + printf ("%.*sProcessing state %d c=", rlevel*2-2, SP, state_offset); + if (clen == 0) printf("EOL\n"); + else if (c > 32 && c < 127) printf("'%c'\n", c); + else printf("0x%02x\n", c); +#endif + + /* A negative offset is a special case meaning "hold off going to this + (negated) state until the number of characters in the data field have + been skipped". If the could_continue flag was passed over from a previous + state, arrange for it to passed on. */ + + if (state_offset < 0) + { + if (current_state->data > 0) + { + DPRINTF(("%.*sSkipping this character\n", rlevel*2-2, SP)); + ADD_NEW_DATA(state_offset, current_state->count, + current_state->data - 1); + if (could_continue) reset_could_continue = TRUE; + continue; + } + else + { + current_state->offset = state_offset = -state_offset; + } + } + + /* Check for a duplicate state with the same count, and skip if found. + See the note at the head of this module about the possibility of improving + performance here. */ + + for (j = 0; j < i; j++) + { + if (active_states[j].offset == state_offset && + active_states[j].count == current_state->count) + { + DPRINTF(("%.*sDuplicate state: skipped\n", rlevel*2-2, SP)); + goto NEXT_ACTIVE_STATE; + } + } + + /* The state offset is the offset to the opcode */ + + code = start_code + state_offset; + codevalue = *code; + + /* If this opcode inspects a character, but we are at the end of the + subject, remember the fact for use when testing for a partial match. */ + + if (clen == 0 && poptable[codevalue] != 0) + could_continue = TRUE; + + /* If this opcode is followed by an inline character, load it. It is + tempting to test for the presence of a subject character here, but that + is wrong, because sometimes zero repetitions of the subject are + permitted. + + We also use this mechanism for opcodes such as OP_TYPEPLUS that take an + argument that is not a data character - but is always one byte long because + the values are small. We have to take special action to deal with \P, \p, + \H, \h, \V, \v and \X in this case. To keep the other cases fast, convert + these ones to new opcodes. */ + + if (coptable[codevalue] > 0) + { + dlen = 1; +#ifdef SUPPORT_UTF + if (utf) { GETCHARLEN(d, (code + coptable[codevalue]), dlen); } else +#endif /* SUPPORT_UTF */ + d = code[coptable[codevalue]]; + if (codevalue >= OP_TYPESTAR) + { + switch(d) + { + case OP_ANYBYTE: return PCRE_ERROR_DFA_UITEM; + case OP_NOTPROP: + case OP_PROP: codevalue += OP_PROP_EXTRA; break; + case OP_ANYNL: codevalue += OP_ANYNL_EXTRA; break; + case OP_EXTUNI: codevalue += OP_EXTUNI_EXTRA; break; + case OP_NOT_HSPACE: + case OP_HSPACE: codevalue += OP_HSPACE_EXTRA; break; + case OP_NOT_VSPACE: + case OP_VSPACE: codevalue += OP_VSPACE_EXTRA; break; + default: break; + } + } + } + else + { + dlen = 0; /* Not strictly necessary, but compilers moan */ + d = NOTACHAR; /* if these variables are not set. */ + } + + + /* Now process the individual opcodes */ + + switch (codevalue) + { +/* ========================================================================== */ + /* These cases are never obeyed. This is a fudge that causes a compile- + time error if the vectors coptable or poptable, which are indexed by + opcode, are not the correct length. It seems to be the only way to do + such a check at compile time, as the sizeof() operator does not work + in the C preprocessor. */ + + case OP_TABLE_LENGTH: + case OP_TABLE_LENGTH + + ((sizeof(coptable) == OP_TABLE_LENGTH) && + (sizeof(poptable) == OP_TABLE_LENGTH)): + break; + +/* ========================================================================== */ + /* Reached a closing bracket. If not at the end of the pattern, carry + on with the next opcode. For repeating opcodes, also add the repeat + state. Note that KETRPOS will always be encountered at the end of the + subpattern, because the possessive subpattern repeats are always handled + using recursive calls. Thus, it never adds any new states. + + At the end of the (sub)pattern, unless we have an empty string and + PCRE_NOTEMPTY is set, or PCRE_NOTEMPTY_ATSTART is set and we are at the + start of the subject, save the match data, shifting up all previous + matches so we always have the longest first. */ + + case OP_KET: + case OP_KETRMIN: + case OP_KETRMAX: + case OP_KETRPOS: + if (code != end_code) + { + ADD_ACTIVE(state_offset + 1 + LINK_SIZE, 0); + if (codevalue != OP_KET) + { + ADD_ACTIVE(state_offset - GET(code, 1), 0); + } + } + else + { + if (ptr > current_subject || + ((md->moptions & PCRE_NOTEMPTY) == 0 && + ((md->moptions & PCRE_NOTEMPTY_ATSTART) == 0 || + current_subject > start_subject + md->start_offset))) + { + if (match_count < 0) match_count = (offsetcount >= 2)? 1 : 0; + else if (match_count > 0 && ++match_count * 2 > offsetcount) + match_count = 0; + count = ((match_count == 0)? offsetcount : match_count * 2) - 2; + if (count > 0) memmove(offsets + 2, offsets, count * sizeof(int)); + if (offsetcount >= 2) + { + offsets[0] = (int)(current_subject - start_subject); + offsets[1] = (int)(ptr - start_subject); + DPRINTF(("%.*sSet matched string = \"%.*s\"\n", rlevel*2-2, SP, + offsets[1] - offsets[0], (char *)current_subject)); + } + if ((md->moptions & PCRE_DFA_SHORTEST) != 0) + { + DPRINTF(("%.*sEnd of internal_dfa_exec %d: returning %d\n" + "%.*s---------------------\n\n", rlevel*2-2, SP, rlevel, + match_count, rlevel*2-2, SP)); + return match_count; + } + } + } + break; + +/* ========================================================================== */ + /* These opcodes add to the current list of states without looking + at the current character. */ + + /*-----------------------------------------------------------------*/ + case OP_ALT: + do { code += GET(code, 1); } while (*code == OP_ALT); + ADD_ACTIVE((int)(code - start_code), 0); + break; + + /*-----------------------------------------------------------------*/ + case OP_BRA: + case OP_SBRA: + do + { + ADD_ACTIVE((int)(code - start_code + 1 + LINK_SIZE), 0); + code += GET(code, 1); + } + while (*code == OP_ALT); + break; + + /*-----------------------------------------------------------------*/ + case OP_CBRA: + case OP_SCBRA: + ADD_ACTIVE((int)(code - start_code + 1 + LINK_SIZE + IMM2_SIZE), 0); + code += GET(code, 1); + while (*code == OP_ALT) + { + ADD_ACTIVE((int)(code - start_code + 1 + LINK_SIZE), 0); + code += GET(code, 1); + } + break; + + /*-----------------------------------------------------------------*/ + case OP_BRAZERO: + case OP_BRAMINZERO: + ADD_ACTIVE(state_offset + 1, 0); + code += 1 + GET(code, 2); + while (*code == OP_ALT) code += GET(code, 1); + ADD_ACTIVE((int)(code - start_code + 1 + LINK_SIZE), 0); + break; + + /*-----------------------------------------------------------------*/ + case OP_SKIPZERO: + code += 1 + GET(code, 2); + while (*code == OP_ALT) code += GET(code, 1); + ADD_ACTIVE((int)(code - start_code + 1 + LINK_SIZE), 0); + break; + + /*-----------------------------------------------------------------*/ + case OP_CIRC: + if (ptr == start_subject && (md->moptions & PCRE_NOTBOL) == 0) + { ADD_ACTIVE(state_offset + 1, 0); } + break; + + /*-----------------------------------------------------------------*/ + case OP_CIRCM: + if ((ptr == start_subject && (md->moptions & PCRE_NOTBOL) == 0) || + (ptr != end_subject && WAS_NEWLINE(ptr))) + { ADD_ACTIVE(state_offset + 1, 0); } + break; + + /*-----------------------------------------------------------------*/ + case OP_EOD: + if (ptr >= end_subject) + { + if ((md->moptions & PCRE_PARTIAL_HARD) != 0) + could_continue = TRUE; + else { ADD_ACTIVE(state_offset + 1, 0); } + } + break; + + /*-----------------------------------------------------------------*/ + case OP_SOD: + if (ptr == start_subject) { ADD_ACTIVE(state_offset + 1, 0); } + break; + + /*-----------------------------------------------------------------*/ + case OP_SOM: + if (ptr == start_subject + start_offset) { ADD_ACTIVE(state_offset + 1, 0); } + break; + + +/* ========================================================================== */ + /* These opcodes inspect the next subject character, and sometimes + the previous one as well, but do not have an argument. The variable + clen contains the length of the current character and is zero if we are + at the end of the subject. */ + + /*-----------------------------------------------------------------*/ + case OP_ANY: + if (clen > 0 && !IS_NEWLINE(ptr)) + { + if (ptr + 1 >= md->end_subject && + (md->moptions & (PCRE_PARTIAL_HARD)) != 0 && + NLBLOCK->nltype == NLTYPE_FIXED && + NLBLOCK->nllen == 2 && + c == NLBLOCK->nl[0]) + { + could_continue = partial_newline = TRUE; + } + else + { + ADD_NEW(state_offset + 1, 0); + } + } + break; + + /*-----------------------------------------------------------------*/ + case OP_ALLANY: + if (clen > 0) + { ADD_NEW(state_offset + 1, 0); } + break; + + /*-----------------------------------------------------------------*/ + case OP_EODN: + if (clen == 0 && (md->moptions & PCRE_PARTIAL_HARD) != 0) + could_continue = TRUE; + else if (clen == 0 || (IS_NEWLINE(ptr) && ptr == end_subject - md->nllen)) + { ADD_ACTIVE(state_offset + 1, 0); } + break; + + /*-----------------------------------------------------------------*/ + case OP_DOLL: + if ((md->moptions & PCRE_NOTEOL) == 0) + { + if (clen == 0 && (md->moptions & PCRE_PARTIAL_HARD) != 0) + could_continue = TRUE; + else if (clen == 0 || + ((md->poptions & PCRE_DOLLAR_ENDONLY) == 0 && IS_NEWLINE(ptr) && + (ptr == end_subject - md->nllen) + )) + { ADD_ACTIVE(state_offset + 1, 0); } + else if (ptr + 1 >= md->end_subject && + (md->moptions & (PCRE_PARTIAL_HARD|PCRE_PARTIAL_SOFT)) != 0 && + NLBLOCK->nltype == NLTYPE_FIXED && + NLBLOCK->nllen == 2 && + c == NLBLOCK->nl[0]) + { + if ((md->moptions & PCRE_PARTIAL_HARD) != 0) + { + reset_could_continue = TRUE; + ADD_NEW_DATA(-(state_offset + 1), 0, 1); + } + else could_continue = partial_newline = TRUE; + } + } + break; + + /*-----------------------------------------------------------------*/ + case OP_DOLLM: + if ((md->moptions & PCRE_NOTEOL) == 0) + { + if (clen == 0 && (md->moptions & PCRE_PARTIAL_HARD) != 0) + could_continue = TRUE; + else if (clen == 0 || + ((md->poptions & PCRE_DOLLAR_ENDONLY) == 0 && IS_NEWLINE(ptr))) + { ADD_ACTIVE(state_offset + 1, 0); } + else if (ptr + 1 >= md->end_subject && + (md->moptions & (PCRE_PARTIAL_HARD|PCRE_PARTIAL_SOFT)) != 0 && + NLBLOCK->nltype == NLTYPE_FIXED && + NLBLOCK->nllen == 2 && + c == NLBLOCK->nl[0]) + { + if ((md->moptions & PCRE_PARTIAL_HARD) != 0) + { + reset_could_continue = TRUE; + ADD_NEW_DATA(-(state_offset + 1), 0, 1); + } + else could_continue = partial_newline = TRUE; + } + } + else if (IS_NEWLINE(ptr)) + { ADD_ACTIVE(state_offset + 1, 0); } + break; + + /*-----------------------------------------------------------------*/ + + case OP_DIGIT: + case OP_WHITESPACE: + case OP_WORDCHAR: + if (clen > 0 && c < 256 && + ((ctypes[c] & toptable1[codevalue]) ^ toptable2[codevalue]) != 0) + { ADD_NEW(state_offset + 1, 0); } + break; + + /*-----------------------------------------------------------------*/ + case OP_NOT_DIGIT: + case OP_NOT_WHITESPACE: + case OP_NOT_WORDCHAR: + if (clen > 0 && (c >= 256 || + ((ctypes[c] & toptable1[codevalue]) ^ toptable2[codevalue]) != 0)) + { ADD_NEW(state_offset + 1, 0); } + break; + + /*-----------------------------------------------------------------*/ + case OP_WORD_BOUNDARY: + case OP_NOT_WORD_BOUNDARY: + { + int left_word, right_word; + + if (ptr > start_subject) + { + const pcre_uchar *temp = ptr - 1; + if (temp < md->start_used_ptr) md->start_used_ptr = temp; +#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 + if (utf) { BACKCHAR(temp); } +#endif + GETCHARTEST(d, temp); +#ifdef SUPPORT_UCP + if ((md->poptions & PCRE_UCP) != 0) + { + if (d == '_') left_word = TRUE; else + { + int cat = UCD_CATEGORY(d); + left_word = (cat == ucp_L || cat == ucp_N); + } + } + else +#endif + left_word = d < 256 && (ctypes[d] & ctype_word) != 0; + } + else left_word = FALSE; + + if (clen > 0) + { +#ifdef SUPPORT_UCP + if ((md->poptions & PCRE_UCP) != 0) + { + if (c == '_') right_word = TRUE; else + { + int cat = UCD_CATEGORY(c); + right_word = (cat == ucp_L || cat == ucp_N); + } + } + else +#endif + right_word = c < 256 && (ctypes[c] & ctype_word) != 0; + } + else right_word = FALSE; + + if ((left_word == right_word) == (codevalue == OP_NOT_WORD_BOUNDARY)) + { ADD_ACTIVE(state_offset + 1, 0); } + } + break; + + + /*-----------------------------------------------------------------*/ + /* Check the next character by Unicode property. We will get here only + if the support is in the binary; otherwise a compile-time error occurs. + */ + +#ifdef SUPPORT_UCP + case OP_PROP: + case OP_NOTPROP: + if (clen > 0) + { + BOOL OK; + const pcre_uint32 *cp; + const ucd_record * prop = GET_UCD(c); + switch(code[1]) + { + case PT_ANY: + OK = TRUE; + break; + + case PT_LAMP: + OK = prop->chartype == ucp_Lu || prop->chartype == ucp_Ll || + prop->chartype == ucp_Lt; + break; + + case PT_GC: + OK = PRIV(ucp_gentype)[prop->chartype] == code[2]; + break; + + case PT_PC: + OK = prop->chartype == code[2]; + break; + + case PT_SC: + OK = prop->script == code[2]; + break; + + /* These are specials for combination cases. */ + + case PT_ALNUM: + OK = PRIV(ucp_gentype)[prop->chartype] == ucp_L || + PRIV(ucp_gentype)[prop->chartype] == ucp_N; + break; + + /* Perl space used to exclude VT, but from Perl 5.18 it is included, + which means that Perl space and POSIX space are now identical. PCRE + was changed at release 8.34. */ + + case PT_SPACE: /* Perl space */ + case PT_PXSPACE: /* POSIX space */ + switch(c) + { + HSPACE_CASES: + VSPACE_CASES: + OK = TRUE; + break; + + default: + OK = PRIV(ucp_gentype)[prop->chartype] == ucp_Z; + break; + } + break; + + case PT_WORD: + OK = PRIV(ucp_gentype)[prop->chartype] == ucp_L || + PRIV(ucp_gentype)[prop->chartype] == ucp_N || + c == CHAR_UNDERSCORE; + break; + + case PT_CLIST: + cp = PRIV(ucd_caseless_sets) + code[2]; + for (;;) + { + if (c < *cp) { OK = FALSE; break; } + if (c == *cp++) { OK = TRUE; break; } + } + break; + + case PT_UCNC: + OK = c == CHAR_DOLLAR_SIGN || c == CHAR_COMMERCIAL_AT || + c == CHAR_GRAVE_ACCENT || (c >= 0xa0 && c <= 0xd7ff) || + c >= 0xe000; + break; + + /* Should never occur, but keep compilers from grumbling. */ + + default: + OK = codevalue != OP_PROP; + break; + } + + if (OK == (codevalue == OP_PROP)) { ADD_NEW(state_offset + 3, 0); } + } + break; +#endif + + + +/* ========================================================================== */ + /* These opcodes likewise inspect the subject character, but have an + argument that is not a data character. It is one of these opcodes: + OP_ANY, OP_ALLANY, OP_DIGIT, OP_NOT_DIGIT, OP_WHITESPACE, OP_NOT_SPACE, + OP_WORDCHAR, OP_NOT_WORDCHAR. The value is loaded into d. */ + + case OP_TYPEPLUS: + case OP_TYPEMINPLUS: + case OP_TYPEPOSPLUS: + count = current_state->count; /* Already matched */ + if (count > 0) { ADD_ACTIVE(state_offset + 2, 0); } + if (clen > 0) + { + if (d == OP_ANY && ptr + 1 >= md->end_subject && + (md->moptions & (PCRE_PARTIAL_HARD)) != 0 && + NLBLOCK->nltype == NLTYPE_FIXED && + NLBLOCK->nllen == 2 && + c == NLBLOCK->nl[0]) + { + could_continue = partial_newline = TRUE; + } + else if ((c >= 256 && d != OP_DIGIT && d != OP_WHITESPACE && d != OP_WORDCHAR) || + (c < 256 && + (d != OP_ANY || !IS_NEWLINE(ptr)) && + ((ctypes[c] & toptable1[d]) ^ toptable2[d]) != 0)) + { + if (count > 0 && codevalue == OP_TYPEPOSPLUS) + { + active_count--; /* Remove non-match possibility */ + next_active_state--; + } + count++; + ADD_NEW(state_offset, count); + } + } + break; + + /*-----------------------------------------------------------------*/ + case OP_TYPEQUERY: + case OP_TYPEMINQUERY: + case OP_TYPEPOSQUERY: + ADD_ACTIVE(state_offset + 2, 0); + if (clen > 0) + { + if (d == OP_ANY && ptr + 1 >= md->end_subject && + (md->moptions & (PCRE_PARTIAL_HARD)) != 0 && + NLBLOCK->nltype == NLTYPE_FIXED && + NLBLOCK->nllen == 2 && + c == NLBLOCK->nl[0]) + { + could_continue = partial_newline = TRUE; + } + else if ((c >= 256 && d != OP_DIGIT && d != OP_WHITESPACE && d != OP_WORDCHAR) || + (c < 256 && + (d != OP_ANY || !IS_NEWLINE(ptr)) && + ((ctypes[c] & toptable1[d]) ^ toptable2[d]) != 0)) + { + if (codevalue == OP_TYPEPOSQUERY) + { + active_count--; /* Remove non-match possibility */ + next_active_state--; + } + ADD_NEW(state_offset + 2, 0); + } + } + break; + + /*-----------------------------------------------------------------*/ + case OP_TYPESTAR: + case OP_TYPEMINSTAR: + case OP_TYPEPOSSTAR: + ADD_ACTIVE(state_offset + 2, 0); + if (clen > 0) + { + if (d == OP_ANY && ptr + 1 >= md->end_subject && + (md->moptions & (PCRE_PARTIAL_HARD)) != 0 && + NLBLOCK->nltype == NLTYPE_FIXED && + NLBLOCK->nllen == 2 && + c == NLBLOCK->nl[0]) + { + could_continue = partial_newline = TRUE; + } + else if ((c >= 256 && d != OP_DIGIT && d != OP_WHITESPACE && d != OP_WORDCHAR) || + (c < 256 && + (d != OP_ANY || !IS_NEWLINE(ptr)) && + ((ctypes[c] & toptable1[d]) ^ toptable2[d]) != 0)) + { + if (codevalue == OP_TYPEPOSSTAR) + { + active_count--; /* Remove non-match possibility */ + next_active_state--; + } + ADD_NEW(state_offset, 0); + } + } + break; + + /*-----------------------------------------------------------------*/ + case OP_TYPEEXACT: + count = current_state->count; /* Number already matched */ + if (clen > 0) + { + if (d == OP_ANY && ptr + 1 >= md->end_subject && + (md->moptions & (PCRE_PARTIAL_HARD)) != 0 && + NLBLOCK->nltype == NLTYPE_FIXED && + NLBLOCK->nllen == 2 && + c == NLBLOCK->nl[0]) + { + could_continue = partial_newline = TRUE; + } + else if ((c >= 256 && d != OP_DIGIT && d != OP_WHITESPACE && d != OP_WORDCHAR) || + (c < 256 && + (d != OP_ANY || !IS_NEWLINE(ptr)) && + ((ctypes[c] & toptable1[d]) ^ toptable2[d]) != 0)) + { + if (++count >= (int)GET2(code, 1)) + { ADD_NEW(state_offset + 1 + IMM2_SIZE + 1, 0); } + else + { ADD_NEW(state_offset, count); } + } + } + break; + + /*-----------------------------------------------------------------*/ + case OP_TYPEUPTO: + case OP_TYPEMINUPTO: + case OP_TYPEPOSUPTO: + ADD_ACTIVE(state_offset + 2 + IMM2_SIZE, 0); + count = current_state->count; /* Number already matched */ + if (clen > 0) + { + if (d == OP_ANY && ptr + 1 >= md->end_subject && + (md->moptions & (PCRE_PARTIAL_HARD)) != 0 && + NLBLOCK->nltype == NLTYPE_FIXED && + NLBLOCK->nllen == 2 && + c == NLBLOCK->nl[0]) + { + could_continue = partial_newline = TRUE; + } + else if ((c >= 256 && d != OP_DIGIT && d != OP_WHITESPACE && d != OP_WORDCHAR) || + (c < 256 && + (d != OP_ANY || !IS_NEWLINE(ptr)) && + ((ctypes[c] & toptable1[d]) ^ toptable2[d]) != 0)) + { + if (codevalue == OP_TYPEPOSUPTO) + { + active_count--; /* Remove non-match possibility */ + next_active_state--; + } + if (++count >= (int)GET2(code, 1)) + { ADD_NEW(state_offset + 2 + IMM2_SIZE, 0); } + else + { ADD_NEW(state_offset, count); } + } + } + break; + +/* ========================================================================== */ + /* These are virtual opcodes that are used when something like + OP_TYPEPLUS has OP_PROP, OP_NOTPROP, OP_ANYNL, or OP_EXTUNI as its + argument. It keeps the code above fast for the other cases. The argument + is in the d variable. */ + +#ifdef SUPPORT_UCP + case OP_PROP_EXTRA + OP_TYPEPLUS: + case OP_PROP_EXTRA + OP_TYPEMINPLUS: + case OP_PROP_EXTRA + OP_TYPEPOSPLUS: + count = current_state->count; /* Already matched */ + if (count > 0) { ADD_ACTIVE(state_offset + 4, 0); } + if (clen > 0) + { + BOOL OK; + const pcre_uint32 *cp; + const ucd_record * prop = GET_UCD(c); + switch(code[2]) + { + case PT_ANY: + OK = TRUE; + break; + + case PT_LAMP: + OK = prop->chartype == ucp_Lu || prop->chartype == ucp_Ll || + prop->chartype == ucp_Lt; + break; + + case PT_GC: + OK = PRIV(ucp_gentype)[prop->chartype] == code[3]; + break; + + case PT_PC: + OK = prop->chartype == code[3]; + break; + + case PT_SC: + OK = prop->script == code[3]; + break; + + /* These are specials for combination cases. */ + + case PT_ALNUM: + OK = PRIV(ucp_gentype)[prop->chartype] == ucp_L || + PRIV(ucp_gentype)[prop->chartype] == ucp_N; + break; + + /* Perl space used to exclude VT, but from Perl 5.18 it is included, + which means that Perl space and POSIX space are now identical. PCRE + was changed at release 8.34. */ + + case PT_SPACE: /* Perl space */ + case PT_PXSPACE: /* POSIX space */ + switch(c) + { + HSPACE_CASES: + VSPACE_CASES: + OK = TRUE; + break; + + default: + OK = PRIV(ucp_gentype)[prop->chartype] == ucp_Z; + break; + } + break; + + case PT_WORD: + OK = PRIV(ucp_gentype)[prop->chartype] == ucp_L || + PRIV(ucp_gentype)[prop->chartype] == ucp_N || + c == CHAR_UNDERSCORE; + break; + + case PT_CLIST: + cp = PRIV(ucd_caseless_sets) + code[3]; + for (;;) + { + if (c < *cp) { OK = FALSE; break; } + if (c == *cp++) { OK = TRUE; break; } + } + break; + + case PT_UCNC: + OK = c == CHAR_DOLLAR_SIGN || c == CHAR_COMMERCIAL_AT || + c == CHAR_GRAVE_ACCENT || (c >= 0xa0 && c <= 0xd7ff) || + c >= 0xe000; + break; + + /* Should never occur, but keep compilers from grumbling. */ + + default: + OK = codevalue != OP_PROP; + break; + } + + if (OK == (d == OP_PROP)) + { + if (count > 0 && codevalue == OP_PROP_EXTRA + OP_TYPEPOSPLUS) + { + active_count--; /* Remove non-match possibility */ + next_active_state--; + } + count++; + ADD_NEW(state_offset, count); + } + } + break; + + /*-----------------------------------------------------------------*/ + case OP_EXTUNI_EXTRA + OP_TYPEPLUS: + case OP_EXTUNI_EXTRA + OP_TYPEMINPLUS: + case OP_EXTUNI_EXTRA + OP_TYPEPOSPLUS: + count = current_state->count; /* Already matched */ + if (count > 0) { ADD_ACTIVE(state_offset + 2, 0); } + if (clen > 0) + { + int lgb, rgb; + const pcre_uchar *nptr = ptr + clen; + int ncount = 0; + if (count > 0 && codevalue == OP_EXTUNI_EXTRA + OP_TYPEPOSPLUS) + { + active_count--; /* Remove non-match possibility */ + next_active_state--; + } + lgb = UCD_GRAPHBREAK(c); + while (nptr < end_subject) + { + dlen = 1; + if (!utf) d = *nptr; else { GETCHARLEN(d, nptr, dlen); } + rgb = UCD_GRAPHBREAK(d); + if ((PRIV(ucp_gbtable)[lgb] & (1 << rgb)) == 0) break; + ncount++; + lgb = rgb; + nptr += dlen; + } + count++; + ADD_NEW_DATA(-state_offset, count, ncount); + } + break; +#endif + + /*-----------------------------------------------------------------*/ + case OP_ANYNL_EXTRA + OP_TYPEPLUS: + case OP_ANYNL_EXTRA + OP_TYPEMINPLUS: + case OP_ANYNL_EXTRA + OP_TYPEPOSPLUS: + count = current_state->count; /* Already matched */ + if (count > 0) { ADD_ACTIVE(state_offset + 2, 0); } + if (clen > 0) + { + int ncount = 0; + switch (c) + { + case CHAR_VT: + case CHAR_FF: + case CHAR_NEL: +#ifndef EBCDIC + case 0x2028: + case 0x2029: +#endif /* Not EBCDIC */ + if ((md->moptions & PCRE_BSR_ANYCRLF) != 0) break; + goto ANYNL01; + + case CHAR_CR: + if (ptr + 1 < end_subject && UCHAR21TEST(ptr + 1) == CHAR_LF) ncount = 1; + /* Fall through */ + + ANYNL01: + case CHAR_LF: + if (count > 0 && codevalue == OP_ANYNL_EXTRA + OP_TYPEPOSPLUS) + { + active_count--; /* Remove non-match possibility */ + next_active_state--; + } + count++; + ADD_NEW_DATA(-state_offset, count, ncount); + break; + + default: + break; + } + } + break; + + /*-----------------------------------------------------------------*/ + case OP_VSPACE_EXTRA + OP_TYPEPLUS: + case OP_VSPACE_EXTRA + OP_TYPEMINPLUS: + case OP_VSPACE_EXTRA + OP_TYPEPOSPLUS: + count = current_state->count; /* Already matched */ + if (count > 0) { ADD_ACTIVE(state_offset + 2, 0); } + if (clen > 0) + { + BOOL OK; + switch (c) + { + VSPACE_CASES: + OK = TRUE; + break; + + default: + OK = FALSE; + break; + } + + if (OK == (d == OP_VSPACE)) + { + if (count > 0 && codevalue == OP_VSPACE_EXTRA + OP_TYPEPOSPLUS) + { + active_count--; /* Remove non-match possibility */ + next_active_state--; + } + count++; + ADD_NEW_DATA(-state_offset, count, 0); + } + } + break; + + /*-----------------------------------------------------------------*/ + case OP_HSPACE_EXTRA + OP_TYPEPLUS: + case OP_HSPACE_EXTRA + OP_TYPEMINPLUS: + case OP_HSPACE_EXTRA + OP_TYPEPOSPLUS: + count = current_state->count; /* Already matched */ + if (count > 0) { ADD_ACTIVE(state_offset + 2, 0); } + if (clen > 0) + { + BOOL OK; + switch (c) + { + HSPACE_CASES: + OK = TRUE; + break; + + default: + OK = FALSE; + break; + } + + if (OK == (d == OP_HSPACE)) + { + if (count > 0 && codevalue == OP_HSPACE_EXTRA + OP_TYPEPOSPLUS) + { + active_count--; /* Remove non-match possibility */ + next_active_state--; + } + count++; + ADD_NEW_DATA(-state_offset, count, 0); + } + } + break; + + /*-----------------------------------------------------------------*/ +#ifdef SUPPORT_UCP + case OP_PROP_EXTRA + OP_TYPEQUERY: + case OP_PROP_EXTRA + OP_TYPEMINQUERY: + case OP_PROP_EXTRA + OP_TYPEPOSQUERY: + count = 4; + goto QS1; + + case OP_PROP_EXTRA + OP_TYPESTAR: + case OP_PROP_EXTRA + OP_TYPEMINSTAR: + case OP_PROP_EXTRA + OP_TYPEPOSSTAR: + count = 0; + + QS1: + + ADD_ACTIVE(state_offset + 4, 0); + if (clen > 0) + { + BOOL OK; + const pcre_uint32 *cp; + const ucd_record * prop = GET_UCD(c); + switch(code[2]) + { + case PT_ANY: + OK = TRUE; + break; + + case PT_LAMP: + OK = prop->chartype == ucp_Lu || prop->chartype == ucp_Ll || + prop->chartype == ucp_Lt; + break; + + case PT_GC: + OK = PRIV(ucp_gentype)[prop->chartype] == code[3]; + break; + + case PT_PC: + OK = prop->chartype == code[3]; + break; + + case PT_SC: + OK = prop->script == code[3]; + break; + + /* These are specials for combination cases. */ + + case PT_ALNUM: + OK = PRIV(ucp_gentype)[prop->chartype] == ucp_L || + PRIV(ucp_gentype)[prop->chartype] == ucp_N; + break; + + /* Perl space used to exclude VT, but from Perl 5.18 it is included, + which means that Perl space and POSIX space are now identical. PCRE + was changed at release 8.34. */ + + case PT_SPACE: /* Perl space */ + case PT_PXSPACE: /* POSIX space */ + switch(c) + { + HSPACE_CASES: + VSPACE_CASES: + OK = TRUE; + break; + + default: + OK = PRIV(ucp_gentype)[prop->chartype] == ucp_Z; + break; + } + break; + + case PT_WORD: + OK = PRIV(ucp_gentype)[prop->chartype] == ucp_L || + PRIV(ucp_gentype)[prop->chartype] == ucp_N || + c == CHAR_UNDERSCORE; + break; + + case PT_CLIST: + cp = PRIV(ucd_caseless_sets) + code[3]; + for (;;) + { + if (c < *cp) { OK = FALSE; break; } + if (c == *cp++) { OK = TRUE; break; } + } + break; + + case PT_UCNC: + OK = c == CHAR_DOLLAR_SIGN || c == CHAR_COMMERCIAL_AT || + c == CHAR_GRAVE_ACCENT || (c >= 0xa0 && c <= 0xd7ff) || + c >= 0xe000; + break; + + /* Should never occur, but keep compilers from grumbling. */ + + default: + OK = codevalue != OP_PROP; + break; + } + + if (OK == (d == OP_PROP)) + { + if (codevalue == OP_PROP_EXTRA + OP_TYPEPOSSTAR || + codevalue == OP_PROP_EXTRA + OP_TYPEPOSQUERY) + { + active_count--; /* Remove non-match possibility */ + next_active_state--; + } + ADD_NEW(state_offset + count, 0); + } + } + break; + + /*-----------------------------------------------------------------*/ + case OP_EXTUNI_EXTRA + OP_TYPEQUERY: + case OP_EXTUNI_EXTRA + OP_TYPEMINQUERY: + case OP_EXTUNI_EXTRA + OP_TYPEPOSQUERY: + count = 2; + goto QS2; + + case OP_EXTUNI_EXTRA + OP_TYPESTAR: + case OP_EXTUNI_EXTRA + OP_TYPEMINSTAR: + case OP_EXTUNI_EXTRA + OP_TYPEPOSSTAR: + count = 0; + + QS2: + + ADD_ACTIVE(state_offset + 2, 0); + if (clen > 0) + { + int lgb, rgb; + const pcre_uchar *nptr = ptr + clen; + int ncount = 0; + if (codevalue == OP_EXTUNI_EXTRA + OP_TYPEPOSSTAR || + codevalue == OP_EXTUNI_EXTRA + OP_TYPEPOSQUERY) + { + active_count--; /* Remove non-match possibility */ + next_active_state--; + } + lgb = UCD_GRAPHBREAK(c); + while (nptr < end_subject) + { + dlen = 1; + if (!utf) d = *nptr; else { GETCHARLEN(d, nptr, dlen); } + rgb = UCD_GRAPHBREAK(d); + if ((PRIV(ucp_gbtable)[lgb] & (1 << rgb)) == 0) break; + ncount++; + lgb = rgb; + nptr += dlen; + } + ADD_NEW_DATA(-(state_offset + count), 0, ncount); + } + break; +#endif + + /*-----------------------------------------------------------------*/ + case OP_ANYNL_EXTRA + OP_TYPEQUERY: + case OP_ANYNL_EXTRA + OP_TYPEMINQUERY: + case OP_ANYNL_EXTRA + OP_TYPEPOSQUERY: + count = 2; + goto QS3; + + case OP_ANYNL_EXTRA + OP_TYPESTAR: + case OP_ANYNL_EXTRA + OP_TYPEMINSTAR: + case OP_ANYNL_EXTRA + OP_TYPEPOSSTAR: + count = 0; + + QS3: + ADD_ACTIVE(state_offset + 2, 0); + if (clen > 0) + { + int ncount = 0; + switch (c) + { + case CHAR_VT: + case CHAR_FF: + case CHAR_NEL: +#ifndef EBCDIC + case 0x2028: + case 0x2029: +#endif /* Not EBCDIC */ + if ((md->moptions & PCRE_BSR_ANYCRLF) != 0) break; + goto ANYNL02; + + case CHAR_CR: + if (ptr + 1 < end_subject && UCHAR21TEST(ptr + 1) == CHAR_LF) ncount = 1; + /* Fall through */ + + ANYNL02: + case CHAR_LF: + if (codevalue == OP_ANYNL_EXTRA + OP_TYPEPOSSTAR || + codevalue == OP_ANYNL_EXTRA + OP_TYPEPOSQUERY) + { + active_count--; /* Remove non-match possibility */ + next_active_state--; + } + ADD_NEW_DATA(-(state_offset + (int)count), 0, ncount); + break; + + default: + break; + } + } + break; + + /*-----------------------------------------------------------------*/ + case OP_VSPACE_EXTRA + OP_TYPEQUERY: + case OP_VSPACE_EXTRA + OP_TYPEMINQUERY: + case OP_VSPACE_EXTRA + OP_TYPEPOSQUERY: + count = 2; + goto QS4; + + case OP_VSPACE_EXTRA + OP_TYPESTAR: + case OP_VSPACE_EXTRA + OP_TYPEMINSTAR: + case OP_VSPACE_EXTRA + OP_TYPEPOSSTAR: + count = 0; + + QS4: + ADD_ACTIVE(state_offset + 2, 0); + if (clen > 0) + { + BOOL OK; + switch (c) + { + VSPACE_CASES: + OK = TRUE; + break; + + default: + OK = FALSE; + break; + } + if (OK == (d == OP_VSPACE)) + { + if (codevalue == OP_VSPACE_EXTRA + OP_TYPEPOSSTAR || + codevalue == OP_VSPACE_EXTRA + OP_TYPEPOSQUERY) + { + active_count--; /* Remove non-match possibility */ + next_active_state--; + } + ADD_NEW_DATA(-(state_offset + (int)count), 0, 0); + } + } + break; + + /*-----------------------------------------------------------------*/ + case OP_HSPACE_EXTRA + OP_TYPEQUERY: + case OP_HSPACE_EXTRA + OP_TYPEMINQUERY: + case OP_HSPACE_EXTRA + OP_TYPEPOSQUERY: + count = 2; + goto QS5; + + case OP_HSPACE_EXTRA + OP_TYPESTAR: + case OP_HSPACE_EXTRA + OP_TYPEMINSTAR: + case OP_HSPACE_EXTRA + OP_TYPEPOSSTAR: + count = 0; + + QS5: + ADD_ACTIVE(state_offset + 2, 0); + if (clen > 0) + { + BOOL OK; + switch (c) + { + HSPACE_CASES: + OK = TRUE; + break; + + default: + OK = FALSE; + break; + } + + if (OK == (d == OP_HSPACE)) + { + if (codevalue == OP_HSPACE_EXTRA + OP_TYPEPOSSTAR || + codevalue == OP_HSPACE_EXTRA + OP_TYPEPOSQUERY) + { + active_count--; /* Remove non-match possibility */ + next_active_state--; + } + ADD_NEW_DATA(-(state_offset + (int)count), 0, 0); + } + } + break; + + /*-----------------------------------------------------------------*/ +#ifdef SUPPORT_UCP + case OP_PROP_EXTRA + OP_TYPEEXACT: + case OP_PROP_EXTRA + OP_TYPEUPTO: + case OP_PROP_EXTRA + OP_TYPEMINUPTO: + case OP_PROP_EXTRA + OP_TYPEPOSUPTO: + if (codevalue != OP_PROP_EXTRA + OP_TYPEEXACT) + { ADD_ACTIVE(state_offset + 1 + IMM2_SIZE + 3, 0); } + count = current_state->count; /* Number already matched */ + if (clen > 0) + { + BOOL OK; + const pcre_uint32 *cp; + const ucd_record * prop = GET_UCD(c); + switch(code[1 + IMM2_SIZE + 1]) + { + case PT_ANY: + OK = TRUE; + break; + + case PT_LAMP: + OK = prop->chartype == ucp_Lu || prop->chartype == ucp_Ll || + prop->chartype == ucp_Lt; + break; + + case PT_GC: + OK = PRIV(ucp_gentype)[prop->chartype] == code[1 + IMM2_SIZE + 2]; + break; + + case PT_PC: + OK = prop->chartype == code[1 + IMM2_SIZE + 2]; + break; + + case PT_SC: + OK = prop->script == code[1 + IMM2_SIZE + 2]; + break; + + /* These are specials for combination cases. */ + + case PT_ALNUM: + OK = PRIV(ucp_gentype)[prop->chartype] == ucp_L || + PRIV(ucp_gentype)[prop->chartype] == ucp_N; + break; + + /* Perl space used to exclude VT, but from Perl 5.18 it is included, + which means that Perl space and POSIX space are now identical. PCRE + was changed at release 8.34. */ + + case PT_SPACE: /* Perl space */ + case PT_PXSPACE: /* POSIX space */ + switch(c) + { + HSPACE_CASES: + VSPACE_CASES: + OK = TRUE; + break; + + default: + OK = PRIV(ucp_gentype)[prop->chartype] == ucp_Z; + break; + } + break; + + case PT_WORD: + OK = PRIV(ucp_gentype)[prop->chartype] == ucp_L || + PRIV(ucp_gentype)[prop->chartype] == ucp_N || + c == CHAR_UNDERSCORE; + break; + + case PT_CLIST: + cp = PRIV(ucd_caseless_sets) + code[1 + IMM2_SIZE + 2]; + for (;;) + { + if (c < *cp) { OK = FALSE; break; } + if (c == *cp++) { OK = TRUE; break; } + } + break; + + case PT_UCNC: + OK = c == CHAR_DOLLAR_SIGN || c == CHAR_COMMERCIAL_AT || + c == CHAR_GRAVE_ACCENT || (c >= 0xa0 && c <= 0xd7ff) || + c >= 0xe000; + break; + + /* Should never occur, but keep compilers from grumbling. */ + + default: + OK = codevalue != OP_PROP; + break; + } + + if (OK == (d == OP_PROP)) + { + if (codevalue == OP_PROP_EXTRA + OP_TYPEPOSUPTO) + { + active_count--; /* Remove non-match possibility */ + next_active_state--; + } + if (++count >= (int)GET2(code, 1)) + { ADD_NEW(state_offset + 1 + IMM2_SIZE + 3, 0); } + else + { ADD_NEW(state_offset, count); } + } + } + break; + + /*-----------------------------------------------------------------*/ + case OP_EXTUNI_EXTRA + OP_TYPEEXACT: + case OP_EXTUNI_EXTRA + OP_TYPEUPTO: + case OP_EXTUNI_EXTRA + OP_TYPEMINUPTO: + case OP_EXTUNI_EXTRA + OP_TYPEPOSUPTO: + if (codevalue != OP_EXTUNI_EXTRA + OP_TYPEEXACT) + { ADD_ACTIVE(state_offset + 2 + IMM2_SIZE, 0); } + count = current_state->count; /* Number already matched */ + if (clen > 0) + { + int lgb, rgb; + const pcre_uchar *nptr = ptr + clen; + int ncount = 0; + if (codevalue == OP_EXTUNI_EXTRA + OP_TYPEPOSUPTO) + { + active_count--; /* Remove non-match possibility */ + next_active_state--; + } + lgb = UCD_GRAPHBREAK(c); + while (nptr < end_subject) + { + dlen = 1; + if (!utf) d = *nptr; else { GETCHARLEN(d, nptr, dlen); } + rgb = UCD_GRAPHBREAK(d); + if ((PRIV(ucp_gbtable)[lgb] & (1 << rgb)) == 0) break; + ncount++; + lgb = rgb; + nptr += dlen; + } + if (nptr >= end_subject && (md->moptions & PCRE_PARTIAL_HARD) != 0) + reset_could_continue = TRUE; + if (++count >= (int)GET2(code, 1)) + { ADD_NEW_DATA(-(state_offset + 2 + IMM2_SIZE), 0, ncount); } + else + { ADD_NEW_DATA(-state_offset, count, ncount); } + } + break; +#endif + + /*-----------------------------------------------------------------*/ + case OP_ANYNL_EXTRA + OP_TYPEEXACT: + case OP_ANYNL_EXTRA + OP_TYPEUPTO: + case OP_ANYNL_EXTRA + OP_TYPEMINUPTO: + case OP_ANYNL_EXTRA + OP_TYPEPOSUPTO: + if (codevalue != OP_ANYNL_EXTRA + OP_TYPEEXACT) + { ADD_ACTIVE(state_offset + 2 + IMM2_SIZE, 0); } + count = current_state->count; /* Number already matched */ + if (clen > 0) + { + int ncount = 0; + switch (c) + { + case CHAR_VT: + case CHAR_FF: + case CHAR_NEL: +#ifndef EBCDIC + case 0x2028: + case 0x2029: +#endif /* Not EBCDIC */ + if ((md->moptions & PCRE_BSR_ANYCRLF) != 0) break; + goto ANYNL03; + + case CHAR_CR: + if (ptr + 1 < end_subject && UCHAR21TEST(ptr + 1) == CHAR_LF) ncount = 1; + /* Fall through */ + + ANYNL03: + case CHAR_LF: + if (codevalue == OP_ANYNL_EXTRA + OP_TYPEPOSUPTO) + { + active_count--; /* Remove non-match possibility */ + next_active_state--; + } + if (++count >= (int)GET2(code, 1)) + { ADD_NEW_DATA(-(state_offset + 2 + IMM2_SIZE), 0, ncount); } + else + { ADD_NEW_DATA(-state_offset, count, ncount); } + break; + + default: + break; + } + } + break; + + /*-----------------------------------------------------------------*/ + case OP_VSPACE_EXTRA + OP_TYPEEXACT: + case OP_VSPACE_EXTRA + OP_TYPEUPTO: + case OP_VSPACE_EXTRA + OP_TYPEMINUPTO: + case OP_VSPACE_EXTRA + OP_TYPEPOSUPTO: + if (codevalue != OP_VSPACE_EXTRA + OP_TYPEEXACT) + { ADD_ACTIVE(state_offset + 2 + IMM2_SIZE, 0); } + count = current_state->count; /* Number already matched */ + if (clen > 0) + { + BOOL OK; + switch (c) + { + VSPACE_CASES: + OK = TRUE; + break; + + default: + OK = FALSE; + } + + if (OK == (d == OP_VSPACE)) + { + if (codevalue == OP_VSPACE_EXTRA + OP_TYPEPOSUPTO) + { + active_count--; /* Remove non-match possibility */ + next_active_state--; + } + if (++count >= (int)GET2(code, 1)) + { ADD_NEW_DATA(-(state_offset + 2 + IMM2_SIZE), 0, 0); } + else + { ADD_NEW_DATA(-state_offset, count, 0); } + } + } + break; + + /*-----------------------------------------------------------------*/ + case OP_HSPACE_EXTRA + OP_TYPEEXACT: + case OP_HSPACE_EXTRA + OP_TYPEUPTO: + case OP_HSPACE_EXTRA + OP_TYPEMINUPTO: + case OP_HSPACE_EXTRA + OP_TYPEPOSUPTO: + if (codevalue != OP_HSPACE_EXTRA + OP_TYPEEXACT) + { ADD_ACTIVE(state_offset + 2 + IMM2_SIZE, 0); } + count = current_state->count; /* Number already matched */ + if (clen > 0) + { + BOOL OK; + switch (c) + { + HSPACE_CASES: + OK = TRUE; + break; + + default: + OK = FALSE; + break; + } + + if (OK == (d == OP_HSPACE)) + { + if (codevalue == OP_HSPACE_EXTRA + OP_TYPEPOSUPTO) + { + active_count--; /* Remove non-match possibility */ + next_active_state--; + } + if (++count >= (int)GET2(code, 1)) + { ADD_NEW_DATA(-(state_offset + 2 + IMM2_SIZE), 0, 0); } + else + { ADD_NEW_DATA(-state_offset, count, 0); } + } + } + break; + +/* ========================================================================== */ + /* These opcodes are followed by a character that is usually compared + to the current subject character; it is loaded into d. We still get + here even if there is no subject character, because in some cases zero + repetitions are permitted. */ + + /*-----------------------------------------------------------------*/ + case OP_CHAR: + if (clen > 0 && c == d) { ADD_NEW(state_offset + dlen + 1, 0); } + break; + + /*-----------------------------------------------------------------*/ + case OP_CHARI: + if (clen == 0) break; + +#ifdef SUPPORT_UTF + if (utf) + { + if (c == d) { ADD_NEW(state_offset + dlen + 1, 0); } else + { + unsigned int othercase; + if (c < 128) + othercase = fcc[c]; + else + /* If we have Unicode property support, we can use it to test the + other case of the character. */ +#ifdef SUPPORT_UCP + othercase = UCD_OTHERCASE(c); +#else + othercase = NOTACHAR; +#endif + + if (d == othercase) { ADD_NEW(state_offset + dlen + 1, 0); } + } + } + else +#endif /* SUPPORT_UTF */ + /* Not UTF mode */ + { + if (TABLE_GET(c, lcc, c) == TABLE_GET(d, lcc, d)) + { ADD_NEW(state_offset + 2, 0); } + } + break; + + +#ifdef SUPPORT_UCP + /*-----------------------------------------------------------------*/ + /* This is a tricky one because it can match more than one character. + Find out how many characters to skip, and then set up a negative state + to wait for them to pass before continuing. */ + + case OP_EXTUNI: + if (clen > 0) + { + int lgb, rgb; + const pcre_uchar *nptr = ptr + clen; + int ncount = 0; + lgb = UCD_GRAPHBREAK(c); + while (nptr < end_subject) + { + dlen = 1; + if (!utf) d = *nptr; else { GETCHARLEN(d, nptr, dlen); } + rgb = UCD_GRAPHBREAK(d); + if ((PRIV(ucp_gbtable)[lgb] & (1 << rgb)) == 0) break; + ncount++; + lgb = rgb; + nptr += dlen; + } + if (nptr >= end_subject && (md->moptions & PCRE_PARTIAL_HARD) != 0) + reset_could_continue = TRUE; + ADD_NEW_DATA(-(state_offset + 1), 0, ncount); + } + break; +#endif + + /*-----------------------------------------------------------------*/ + /* This is a tricky like EXTUNI because it too can match more than one + character (when CR is followed by LF). In this case, set up a negative + state to wait for one character to pass before continuing. */ + + case OP_ANYNL: + if (clen > 0) switch(c) + { + case CHAR_VT: + case CHAR_FF: + case CHAR_NEL: +#ifndef EBCDIC + case 0x2028: + case 0x2029: +#endif /* Not EBCDIC */ + if ((md->moptions & PCRE_BSR_ANYCRLF) != 0) break; + + case CHAR_LF: + ADD_NEW(state_offset + 1, 0); + break; + + case CHAR_CR: + if (ptr + 1 >= end_subject) + { + ADD_NEW(state_offset + 1, 0); + if ((md->moptions & PCRE_PARTIAL_HARD) != 0) + reset_could_continue = TRUE; + } + else if (UCHAR21TEST(ptr + 1) == CHAR_LF) + { + ADD_NEW_DATA(-(state_offset + 1), 0, 1); + } + else + { + ADD_NEW(state_offset + 1, 0); + } + break; + } + break; + + /*-----------------------------------------------------------------*/ + case OP_NOT_VSPACE: + if (clen > 0) switch(c) + { + VSPACE_CASES: + break; + + default: + ADD_NEW(state_offset + 1, 0); + break; + } + break; + + /*-----------------------------------------------------------------*/ + case OP_VSPACE: + if (clen > 0) switch(c) + { + VSPACE_CASES: + ADD_NEW(state_offset + 1, 0); + break; + + default: + break; + } + break; + + /*-----------------------------------------------------------------*/ + case OP_NOT_HSPACE: + if (clen > 0) switch(c) + { + HSPACE_CASES: + break; + + default: + ADD_NEW(state_offset + 1, 0); + break; + } + break; + + /*-----------------------------------------------------------------*/ + case OP_HSPACE: + if (clen > 0) switch(c) + { + HSPACE_CASES: + ADD_NEW(state_offset + 1, 0); + break; + + default: + break; + } + break; + + /*-----------------------------------------------------------------*/ + /* Match a negated single character casefully. */ + + case OP_NOT: + if (clen > 0 && c != d) { ADD_NEW(state_offset + dlen + 1, 0); } + break; + + /*-----------------------------------------------------------------*/ + /* Match a negated single character caselessly. */ + + case OP_NOTI: + if (clen > 0) + { + unsigned int otherd; +#ifdef SUPPORT_UTF + if (utf && d >= 128) + { +#ifdef SUPPORT_UCP + otherd = UCD_OTHERCASE(d); +#endif /* SUPPORT_UCP */ + } + else +#endif /* SUPPORT_UTF */ + otherd = TABLE_GET(d, fcc, d); + if (c != d && c != otherd) + { ADD_NEW(state_offset + dlen + 1, 0); } + } + break; + + /*-----------------------------------------------------------------*/ + case OP_PLUSI: + case OP_MINPLUSI: + case OP_POSPLUSI: + case OP_NOTPLUSI: + case OP_NOTMINPLUSI: + case OP_NOTPOSPLUSI: + caseless = TRUE; + codevalue -= OP_STARI - OP_STAR; + + /* Fall through */ + case OP_PLUS: + case OP_MINPLUS: + case OP_POSPLUS: + case OP_NOTPLUS: + case OP_NOTMINPLUS: + case OP_NOTPOSPLUS: + count = current_state->count; /* Already matched */ + if (count > 0) { ADD_ACTIVE(state_offset + dlen + 1, 0); } + if (clen > 0) + { + pcre_uint32 otherd = NOTACHAR; + if (caseless) + { +#ifdef SUPPORT_UTF + if (utf && d >= 128) + { +#ifdef SUPPORT_UCP + otherd = UCD_OTHERCASE(d); +#endif /* SUPPORT_UCP */ + } + else +#endif /* SUPPORT_UTF */ + otherd = TABLE_GET(d, fcc, d); + } + if ((c == d || c == otherd) == (codevalue < OP_NOTSTAR)) + { + if (count > 0 && + (codevalue == OP_POSPLUS || codevalue == OP_NOTPOSPLUS)) + { + active_count--; /* Remove non-match possibility */ + next_active_state--; + } + count++; + ADD_NEW(state_offset, count); + } + } + break; + + /*-----------------------------------------------------------------*/ + case OP_QUERYI: + case OP_MINQUERYI: + case OP_POSQUERYI: + case OP_NOTQUERYI: + case OP_NOTMINQUERYI: + case OP_NOTPOSQUERYI: + caseless = TRUE; + codevalue -= OP_STARI - OP_STAR; + /* Fall through */ + case OP_QUERY: + case OP_MINQUERY: + case OP_POSQUERY: + case OP_NOTQUERY: + case OP_NOTMINQUERY: + case OP_NOTPOSQUERY: + ADD_ACTIVE(state_offset + dlen + 1, 0); + if (clen > 0) + { + pcre_uint32 otherd = NOTACHAR; + if (caseless) + { +#ifdef SUPPORT_UTF + if (utf && d >= 128) + { +#ifdef SUPPORT_UCP + otherd = UCD_OTHERCASE(d); +#endif /* SUPPORT_UCP */ + } + else +#endif /* SUPPORT_UTF */ + otherd = TABLE_GET(d, fcc, d); + } + if ((c == d || c == otherd) == (codevalue < OP_NOTSTAR)) + { + if (codevalue == OP_POSQUERY || codevalue == OP_NOTPOSQUERY) + { + active_count--; /* Remove non-match possibility */ + next_active_state--; + } + ADD_NEW(state_offset + dlen + 1, 0); + } + } + break; + + /*-----------------------------------------------------------------*/ + case OP_STARI: + case OP_MINSTARI: + case OP_POSSTARI: + case OP_NOTSTARI: + case OP_NOTMINSTARI: + case OP_NOTPOSSTARI: + caseless = TRUE; + codevalue -= OP_STARI - OP_STAR; + /* Fall through */ + case OP_STAR: + case OP_MINSTAR: + case OP_POSSTAR: + case OP_NOTSTAR: + case OP_NOTMINSTAR: + case OP_NOTPOSSTAR: + ADD_ACTIVE(state_offset + dlen + 1, 0); + if (clen > 0) + { + pcre_uint32 otherd = NOTACHAR; + if (caseless) + { +#ifdef SUPPORT_UTF + if (utf && d >= 128) + { +#ifdef SUPPORT_UCP + otherd = UCD_OTHERCASE(d); +#endif /* SUPPORT_UCP */ + } + else +#endif /* SUPPORT_UTF */ + otherd = TABLE_GET(d, fcc, d); + } + if ((c == d || c == otherd) == (codevalue < OP_NOTSTAR)) + { + if (codevalue == OP_POSSTAR || codevalue == OP_NOTPOSSTAR) + { + active_count--; /* Remove non-match possibility */ + next_active_state--; + } + ADD_NEW(state_offset, 0); + } + } + break; + + /*-----------------------------------------------------------------*/ + case OP_EXACTI: + case OP_NOTEXACTI: + caseless = TRUE; + codevalue -= OP_STARI - OP_STAR; + /* Fall through */ + case OP_EXACT: + case OP_NOTEXACT: + count = current_state->count; /* Number already matched */ + if (clen > 0) + { + pcre_uint32 otherd = NOTACHAR; + if (caseless) + { +#ifdef SUPPORT_UTF + if (utf && d >= 128) + { +#ifdef SUPPORT_UCP + otherd = UCD_OTHERCASE(d); +#endif /* SUPPORT_UCP */ + } + else +#endif /* SUPPORT_UTF */ + otherd = TABLE_GET(d, fcc, d); + } + if ((c == d || c == otherd) == (codevalue < OP_NOTSTAR)) + { + if (++count >= (int)GET2(code, 1)) + { ADD_NEW(state_offset + dlen + 1 + IMM2_SIZE, 0); } + else + { ADD_NEW(state_offset, count); } + } + } + break; + + /*-----------------------------------------------------------------*/ + case OP_UPTOI: + case OP_MINUPTOI: + case OP_POSUPTOI: + case OP_NOTUPTOI: + case OP_NOTMINUPTOI: + case OP_NOTPOSUPTOI: + caseless = TRUE; + codevalue -= OP_STARI - OP_STAR; + /* Fall through */ + case OP_UPTO: + case OP_MINUPTO: + case OP_POSUPTO: + case OP_NOTUPTO: + case OP_NOTMINUPTO: + case OP_NOTPOSUPTO: + ADD_ACTIVE(state_offset + dlen + 1 + IMM2_SIZE, 0); + count = current_state->count; /* Number already matched */ + if (clen > 0) + { + pcre_uint32 otherd = NOTACHAR; + if (caseless) + { +#ifdef SUPPORT_UTF + if (utf && d >= 128) + { +#ifdef SUPPORT_UCP + otherd = UCD_OTHERCASE(d); +#endif /* SUPPORT_UCP */ + } + else +#endif /* SUPPORT_UTF */ + otherd = TABLE_GET(d, fcc, d); + } + if ((c == d || c == otherd) == (codevalue < OP_NOTSTAR)) + { + if (codevalue == OP_POSUPTO || codevalue == OP_NOTPOSUPTO) + { + active_count--; /* Remove non-match possibility */ + next_active_state--; + } + if (++count >= (int)GET2(code, 1)) + { ADD_NEW(state_offset + dlen + 1 + IMM2_SIZE, 0); } + else + { ADD_NEW(state_offset, count); } + } + } + break; + + +/* ========================================================================== */ + /* These are the class-handling opcodes */ + + case OP_CLASS: + case OP_NCLASS: + case OP_XCLASS: + { + BOOL isinclass = FALSE; + int next_state_offset; + const pcre_uchar *ecode; + + /* For a simple class, there is always just a 32-byte table, and we + can set isinclass from it. */ + + if (codevalue != OP_XCLASS) + { + ecode = code + 1 + (32 / sizeof(pcre_uchar)); + if (clen > 0) + { + isinclass = (c > 255)? (codevalue == OP_NCLASS) : + ((((pcre_uint8 *)(code + 1))[c/8] & (1 << (c&7))) != 0); + } + } + + /* An extended class may have a table or a list of single characters, + ranges, or both, and it may be positive or negative. There's a + function that sorts all this out. */ + + else + { + ecode = code + GET(code, 1); + if (clen > 0) isinclass = PRIV(xclass)(c, code + 1 + LINK_SIZE, utf); + } + + /* At this point, isinclass is set for all kinds of class, and ecode + points to the byte after the end of the class. If there is a + quantifier, this is where it will be. */ + + next_state_offset = (int)(ecode - start_code); + + switch (*ecode) + { + case OP_CRSTAR: + case OP_CRMINSTAR: + case OP_CRPOSSTAR: + ADD_ACTIVE(next_state_offset + 1, 0); + if (isinclass) + { + if (*ecode == OP_CRPOSSTAR) + { + active_count--; /* Remove non-match possibility */ + next_active_state--; + } + ADD_NEW(state_offset, 0); + } + break; + + case OP_CRPLUS: + case OP_CRMINPLUS: + case OP_CRPOSPLUS: + count = current_state->count; /* Already matched */ + if (count > 0) { ADD_ACTIVE(next_state_offset + 1, 0); } + if (isinclass) + { + if (count > 0 && *ecode == OP_CRPOSPLUS) + { + active_count--; /* Remove non-match possibility */ + next_active_state--; + } + count++; + ADD_NEW(state_offset, count); + } + break; + + case OP_CRQUERY: + case OP_CRMINQUERY: + case OP_CRPOSQUERY: + ADD_ACTIVE(next_state_offset + 1, 0); + if (isinclass) + { + if (*ecode == OP_CRPOSQUERY) + { + active_count--; /* Remove non-match possibility */ + next_active_state--; + } + ADD_NEW(next_state_offset + 1, 0); + } + break; + + case OP_CRRANGE: + case OP_CRMINRANGE: + case OP_CRPOSRANGE: + count = current_state->count; /* Already matched */ + if (count >= (int)GET2(ecode, 1)) + { ADD_ACTIVE(next_state_offset + 1 + 2 * IMM2_SIZE, 0); } + if (isinclass) + { + int max = (int)GET2(ecode, 1 + IMM2_SIZE); + if (*ecode == OP_CRPOSRANGE) + { + active_count--; /* Remove non-match possibility */ + next_active_state--; + } + if (++count >= max && max != 0) /* Max 0 => no limit */ + { ADD_NEW(next_state_offset + 1 + 2 * IMM2_SIZE, 0); } + else + { ADD_NEW(state_offset, count); } + } + break; + + default: + if (isinclass) { ADD_NEW(next_state_offset, 0); } + break; + } + } + break; + +/* ========================================================================== */ + /* These are the opcodes for fancy brackets of various kinds. We have + to use recursion in order to handle them. The "always failing" assertion + (?!) is optimised to OP_FAIL when compiling, so we have to support that, + though the other "backtracking verbs" are not supported. */ + + case OP_FAIL: + forced_fail++; /* Count FAILs for multiple states */ + break; + + case OP_ASSERT: + case OP_ASSERT_NOT: + case OP_ASSERTBACK: + case OP_ASSERTBACK_NOT: + { + int rc; + int local_offsets[2]; + int local_workspace[1000]; + const pcre_uchar *endasscode = code + GET(code, 1); + + while (*endasscode == OP_ALT) endasscode += GET(endasscode, 1); + + rc = internal_dfa_exec( + md, /* static match data */ + code, /* this subexpression's code */ + ptr, /* where we currently are */ + (int)(ptr - start_subject), /* start offset */ + local_offsets, /* offset vector */ + sizeof(local_offsets)/sizeof(int), /* size of same */ + local_workspace, /* workspace vector */ + sizeof(local_workspace)/sizeof(int), /* size of same */ + rlevel); /* function recursion level */ + + if (rc == PCRE_ERROR_DFA_UITEM) return rc; + if ((rc >= 0) == (codevalue == OP_ASSERT || codevalue == OP_ASSERTBACK)) + { ADD_ACTIVE((int)(endasscode + LINK_SIZE + 1 - start_code), 0); } + } + break; + + /*-----------------------------------------------------------------*/ + case OP_COND: + case OP_SCOND: + { + int local_offsets[1000]; + int local_workspace[1000]; + int codelink = GET(code, 1); + int condcode; + + /* Because of the way auto-callout works during compile, a callout item + is inserted between OP_COND and an assertion condition. This does not + happen for the other conditions. */ + + if (code[LINK_SIZE+1] == OP_CALLOUT) + { + rrc = 0; + if (PUBL(callout) != NULL) + { + PUBL(callout_block) cb; + cb.version = 1; /* Version 1 of the callout block */ + cb.callout_number = code[LINK_SIZE+2]; + cb.offset_vector = offsets; +#if defined COMPILE_PCRE8 + cb.subject = (PCRE_SPTR)start_subject; +#elif defined COMPILE_PCRE16 + cb.subject = (PCRE_SPTR16)start_subject; +#elif defined COMPILE_PCRE32 + cb.subject = (PCRE_SPTR32)start_subject; +#endif + cb.subject_length = (int)(end_subject - start_subject); + cb.start_match = (int)(current_subject - start_subject); + cb.current_position = (int)(ptr - start_subject); + cb.pattern_position = GET(code, LINK_SIZE + 3); + cb.next_item_length = GET(code, 3 + 2*LINK_SIZE); + cb.capture_top = 1; + cb.capture_last = -1; + cb.callout_data = md->callout_data; + cb.mark = NULL; /* No (*MARK) support */ + if ((rrc = (*PUBL(callout))(&cb)) < 0) return rrc; /* Abandon */ + } + if (rrc > 0) break; /* Fail this thread */ + code += PRIV(OP_lengths)[OP_CALLOUT]; /* Skip callout data */ + } + + condcode = code[LINK_SIZE+1]; + + /* Back reference conditions and duplicate named recursion conditions + are not supported */ + + if (condcode == OP_CREF || condcode == OP_DNCREF || + condcode == OP_DNRREF) + return PCRE_ERROR_DFA_UCOND; + + /* The DEFINE condition is always false */ + + if (condcode == OP_DEF) + { ADD_ACTIVE(state_offset + codelink + LINK_SIZE + 1, 0); } + + /* The only supported version of OP_RREF is for the value RREF_ANY, + which means "test if in any recursion". We can't test for specifically + recursed groups. */ + + else if (condcode == OP_RREF) + { + int value = GET2(code, LINK_SIZE + 2); + if (value != RREF_ANY) return PCRE_ERROR_DFA_UCOND; + if (md->recursive != NULL) + { ADD_ACTIVE(state_offset + LINK_SIZE + 2 + IMM2_SIZE, 0); } + else { ADD_ACTIVE(state_offset + codelink + LINK_SIZE + 1, 0); } + } + + /* Otherwise, the condition is an assertion */ + + else + { + int rc; + const pcre_uchar *asscode = code + LINK_SIZE + 1; + const pcre_uchar *endasscode = asscode + GET(asscode, 1); + + while (*endasscode == OP_ALT) endasscode += GET(endasscode, 1); + + rc = internal_dfa_exec( + md, /* fixed match data */ + asscode, /* this subexpression's code */ + ptr, /* where we currently are */ + (int)(ptr - start_subject), /* start offset */ + local_offsets, /* offset vector */ + sizeof(local_offsets)/sizeof(int), /* size of same */ + local_workspace, /* workspace vector */ + sizeof(local_workspace)/sizeof(int), /* size of same */ + rlevel); /* function recursion level */ + + if (rc == PCRE_ERROR_DFA_UITEM) return rc; + if ((rc >= 0) == + (condcode == OP_ASSERT || condcode == OP_ASSERTBACK)) + { ADD_ACTIVE((int)(endasscode + LINK_SIZE + 1 - start_code), 0); } + else + { ADD_ACTIVE(state_offset + codelink + LINK_SIZE + 1, 0); } + } + } + break; + + /*-----------------------------------------------------------------*/ + case OP_RECURSE: + { + dfa_recursion_info *ri; + int local_offsets[1000]; + int local_workspace[1000]; + const pcre_uchar *callpat = start_code + GET(code, 1); + int recno = (callpat == md->start_code)? 0 : + GET2(callpat, 1 + LINK_SIZE); + int rc; + + DPRINTF(("%.*sStarting regex recursion\n", rlevel*2-2, SP)); + + /* Check for repeating a recursion without advancing the subject + pointer. This should catch convoluted mutual recursions. (Some simple + cases are caught at compile time.) */ + + for (ri = md->recursive; ri != NULL; ri = ri->prevrec) + if (recno == ri->group_num && ptr == ri->subject_position) + return PCRE_ERROR_RECURSELOOP; + + /* Remember this recursion and where we started it so as to + catch infinite loops. */ + + new_recursive.group_num = recno; + new_recursive.subject_position = ptr; + new_recursive.prevrec = md->recursive; + md->recursive = &new_recursive; + + rc = internal_dfa_exec( + md, /* fixed match data */ + callpat, /* this subexpression's code */ + ptr, /* where we currently are */ + (int)(ptr - start_subject), /* start offset */ + local_offsets, /* offset vector */ + sizeof(local_offsets)/sizeof(int), /* size of same */ + local_workspace, /* workspace vector */ + sizeof(local_workspace)/sizeof(int), /* size of same */ + rlevel); /* function recursion level */ + + md->recursive = new_recursive.prevrec; /* Done this recursion */ + + DPRINTF(("%.*sReturn from regex recursion: rc=%d\n", rlevel*2-2, SP, + rc)); + + /* Ran out of internal offsets */ + + if (rc == 0) return PCRE_ERROR_DFA_RECURSE; + + /* For each successful matched substring, set up the next state with a + count of characters to skip before trying it. Note that the count is in + characters, not bytes. */ + + if (rc > 0) + { + for (rc = rc*2 - 2; rc >= 0; rc -= 2) + { + int charcount = local_offsets[rc+1] - local_offsets[rc]; +#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 + if (utf) + { + const pcre_uchar *p = start_subject + local_offsets[rc]; + const pcre_uchar *pp = start_subject + local_offsets[rc+1]; + while (p < pp) if (NOT_FIRSTCHAR(*p++)) charcount--; + } +#endif + if (charcount > 0) + { + ADD_NEW_DATA(-(state_offset + LINK_SIZE + 1), 0, (charcount - 1)); + } + else + { + ADD_ACTIVE(state_offset + LINK_SIZE + 1, 0); + } + } + } + else if (rc != PCRE_ERROR_NOMATCH) return rc; + } + break; + + /*-----------------------------------------------------------------*/ + case OP_BRAPOS: + case OP_SBRAPOS: + case OP_CBRAPOS: + case OP_SCBRAPOS: + case OP_BRAPOSZERO: + { + int charcount, matched_count; + const pcre_uchar *local_ptr = ptr; + BOOL allow_zero; + + if (codevalue == OP_BRAPOSZERO) + { + allow_zero = TRUE; + codevalue = *(++code); /* Codevalue will be one of above BRAs */ + } + else allow_zero = FALSE; + + /* Loop to match the subpattern as many times as possible as if it were + a complete pattern. */ + + for (matched_count = 0;; matched_count++) + { + int local_offsets[2]; + int local_workspace[1000]; + + int rc = internal_dfa_exec( + md, /* fixed match data */ + code, /* this subexpression's code */ + local_ptr, /* where we currently are */ + (int)(ptr - start_subject), /* start offset */ + local_offsets, /* offset vector */ + sizeof(local_offsets)/sizeof(int), /* size of same */ + local_workspace, /* workspace vector */ + sizeof(local_workspace)/sizeof(int), /* size of same */ + rlevel); /* function recursion level */ + + /* Failed to match */ + + if (rc < 0) + { + if (rc != PCRE_ERROR_NOMATCH) return rc; + break; + } + + /* Matched: break the loop if zero characters matched. */ + + charcount = local_offsets[1] - local_offsets[0]; + if (charcount == 0) break; + local_ptr += charcount; /* Advance temporary position ptr */ + } + + /* At this point we have matched the subpattern matched_count + times, and local_ptr is pointing to the character after the end of the + last match. */ + + if (matched_count > 0 || allow_zero) + { + const pcre_uchar *end_subpattern = code; + int next_state_offset; + + do { end_subpattern += GET(end_subpattern, 1); } + while (*end_subpattern == OP_ALT); + next_state_offset = + (int)(end_subpattern - start_code + LINK_SIZE + 1); + + /* Optimization: if there are no more active states, and there + are no new states yet set up, then skip over the subject string + right here, to save looping. Otherwise, set up the new state to swing + into action when the end of the matched substring is reached. */ + + if (i + 1 >= active_count && new_count == 0) + { + ptr = local_ptr; + clen = 0; + ADD_NEW(next_state_offset, 0); + } + else + { + const pcre_uchar *p = ptr; + const pcre_uchar *pp = local_ptr; + charcount = (int)(pp - p); +#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 + if (utf) while (p < pp) if (NOT_FIRSTCHAR(*p++)) charcount--; +#endif + ADD_NEW_DATA(-next_state_offset, 0, (charcount - 1)); + } + } + } + break; + + /*-----------------------------------------------------------------*/ + case OP_ONCE: + case OP_ONCE_NC: + { + int local_offsets[2]; + int local_workspace[1000]; + + int rc = internal_dfa_exec( + md, /* fixed match data */ + code, /* this subexpression's code */ + ptr, /* where we currently are */ + (int)(ptr - start_subject), /* start offset */ + local_offsets, /* offset vector */ + sizeof(local_offsets)/sizeof(int), /* size of same */ + local_workspace, /* workspace vector */ + sizeof(local_workspace)/sizeof(int), /* size of same */ + rlevel); /* function recursion level */ + + if (rc >= 0) + { + const pcre_uchar *end_subpattern = code; + int charcount = local_offsets[1] - local_offsets[0]; + int next_state_offset, repeat_state_offset; + + do { end_subpattern += GET(end_subpattern, 1); } + while (*end_subpattern == OP_ALT); + next_state_offset = + (int)(end_subpattern - start_code + LINK_SIZE + 1); + + /* If the end of this subpattern is KETRMAX or KETRMIN, we must + arrange for the repeat state also to be added to the relevant list. + Calculate the offset, or set -1 for no repeat. */ + + repeat_state_offset = (*end_subpattern == OP_KETRMAX || + *end_subpattern == OP_KETRMIN)? + (int)(end_subpattern - start_code - GET(end_subpattern, 1)) : -1; + + /* If we have matched an empty string, add the next state at the + current character pointer. This is important so that the duplicate + checking kicks in, which is what breaks infinite loops that match an + empty string. */ + + if (charcount == 0) + { + ADD_ACTIVE(next_state_offset, 0); + } + + /* Optimization: if there are no more active states, and there + are no new states yet set up, then skip over the subject string + right here, to save looping. Otherwise, set up the new state to swing + into action when the end of the matched substring is reached. */ + + else if (i + 1 >= active_count && new_count == 0) + { + ptr += charcount; + clen = 0; + ADD_NEW(next_state_offset, 0); + + /* If we are adding a repeat state at the new character position, + we must fudge things so that it is the only current state. + Otherwise, it might be a duplicate of one we processed before, and + that would cause it to be skipped. */ + + if (repeat_state_offset >= 0) + { + next_active_state = active_states; + active_count = 0; + i = -1; + ADD_ACTIVE(repeat_state_offset, 0); + } + } + else + { +#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 + if (utf) + { + const pcre_uchar *p = start_subject + local_offsets[0]; + const pcre_uchar *pp = start_subject + local_offsets[1]; + while (p < pp) if (NOT_FIRSTCHAR(*p++)) charcount--; + } +#endif + ADD_NEW_DATA(-next_state_offset, 0, (charcount - 1)); + if (repeat_state_offset >= 0) + { ADD_NEW_DATA(-repeat_state_offset, 0, (charcount - 1)); } + } + } + else if (rc != PCRE_ERROR_NOMATCH) return rc; + } + break; + + +/* ========================================================================== */ + /* Handle callouts */ + + case OP_CALLOUT: + rrc = 0; + if (PUBL(callout) != NULL) + { + PUBL(callout_block) cb; + cb.version = 1; /* Version 1 of the callout block */ + cb.callout_number = code[1]; + cb.offset_vector = offsets; +#if defined COMPILE_PCRE8 + cb.subject = (PCRE_SPTR)start_subject; +#elif defined COMPILE_PCRE16 + cb.subject = (PCRE_SPTR16)start_subject; +#elif defined COMPILE_PCRE32 + cb.subject = (PCRE_SPTR32)start_subject; +#endif + cb.subject_length = (int)(end_subject - start_subject); + cb.start_match = (int)(current_subject - start_subject); + cb.current_position = (int)(ptr - start_subject); + cb.pattern_position = GET(code, 2); + cb.next_item_length = GET(code, 2 + LINK_SIZE); + cb.capture_top = 1; + cb.capture_last = -1; + cb.callout_data = md->callout_data; + cb.mark = NULL; /* No (*MARK) support */ + if ((rrc = (*PUBL(callout))(&cb)) < 0) return rrc; /* Abandon */ + } + if (rrc == 0) + { ADD_ACTIVE(state_offset + PRIV(OP_lengths)[OP_CALLOUT], 0); } + break; + + +/* ========================================================================== */ + default: /* Unsupported opcode */ + return PCRE_ERROR_DFA_UITEM; + } + + NEXT_ACTIVE_STATE: continue; + + } /* End of loop scanning active states */ + + /* We have finished the processing at the current subject character. If no + new states have been set for the next character, we have found all the + matches that we are going to find. If we are at the top level and partial + matching has been requested, check for appropriate conditions. + + The "forced_ fail" variable counts the number of (*F) encountered for the + character. If it is equal to the original active_count (saved in + workspace[1]) it means that (*F) was found on every active state. In this + case we don't want to give a partial match. + + The "could_continue" variable is true if a state could have continued but + for the fact that the end of the subject was reached. */ + + if (new_count <= 0) + { + if (rlevel == 1 && /* Top level, and */ + could_continue && /* Some could go on, and */ + forced_fail != workspace[1] && /* Not all forced fail & */ + ( /* either... */ + (md->moptions & PCRE_PARTIAL_HARD) != 0 /* Hard partial */ + || /* or... */ + ((md->moptions & PCRE_PARTIAL_SOFT) != 0 && /* Soft partial and */ + match_count < 0) /* no matches */ + ) && /* And... */ + ( + partial_newline || /* Either partial NL */ + ( /* or ... */ + ptr >= end_subject && /* End of subject and */ + ptr > md->start_used_ptr) /* Inspected non-empty string */ + ) + ) + match_count = PCRE_ERROR_PARTIAL; + DPRINTF(("%.*sEnd of internal_dfa_exec %d: returning %d\n" + "%.*s---------------------\n\n", rlevel*2-2, SP, rlevel, match_count, + rlevel*2-2, SP)); + break; /* In effect, "return", but see the comment below */ + } + + /* One or more states are active for the next character. */ + + ptr += clen; /* Advance to next subject character */ + } /* Loop to move along the subject string */ + +/* Control gets here from "break" a few lines above. We do it this way because +if we use "return" above, we have compiler trouble. Some compilers warn if +there's nothing here because they think the function doesn't return a value. On +the other hand, if we put a dummy statement here, some more clever compilers +complain that it can't be reached. Sigh. */ + +return match_count; +} + + + + +/************************************************* +* Execute a Regular Expression - DFA engine * +*************************************************/ + +/* This external function applies a compiled re to a subject string using a DFA +engine. This function calls the internal function multiple times if the pattern +is not anchored. + +Arguments: + argument_re points to the compiled expression + extra_data points to extra data or is NULL + subject points to the subject string + length length of subject string (may contain binary zeros) + start_offset where to start in the subject string + options option bits + offsets vector of match offsets + offsetcount size of same + workspace workspace vector + wscount size of same + +Returns: > 0 => number of match offset pairs placed in offsets + = 0 => offsets overflowed; longest matches are present + -1 => failed to match + < -1 => some kind of unexpected problem +*/ + +#if defined COMPILE_PCRE8 +PCRE_EXP_DEFN int PCRE_CALL_CONVENTION +pcre_dfa_exec(const pcre *argument_re, const pcre_extra *extra_data, + const char *subject, int length, int start_offset, int options, int *offsets, + int offsetcount, int *workspace, int wscount) +#elif defined COMPILE_PCRE16 +PCRE_EXP_DEFN int PCRE_CALL_CONVENTION +pcre16_dfa_exec(const pcre16 *argument_re, const pcre16_extra *extra_data, + PCRE_SPTR16 subject, int length, int start_offset, int options, int *offsets, + int offsetcount, int *workspace, int wscount) +#elif defined COMPILE_PCRE32 +PCRE_EXP_DEFN int PCRE_CALL_CONVENTION +pcre32_dfa_exec(const pcre32 *argument_re, const pcre32_extra *extra_data, + PCRE_SPTR32 subject, int length, int start_offset, int options, int *offsets, + int offsetcount, int *workspace, int wscount) +#endif +{ +REAL_PCRE *re = (REAL_PCRE *)argument_re; +dfa_match_data match_block; +dfa_match_data *md = &match_block; +BOOL utf, anchored, startline, firstline; +const pcre_uchar *current_subject, *end_subject; +const pcre_study_data *study = NULL; + +const pcre_uchar *req_char_ptr; +const pcre_uint8 *start_bits = NULL; +BOOL has_first_char = FALSE; +BOOL has_req_char = FALSE; +pcre_uchar first_char = 0; +pcre_uchar first_char2 = 0; +pcre_uchar req_char = 0; +pcre_uchar req_char2 = 0; +int newline; + +/* Plausibility checks */ + +if ((options & ~PUBLIC_DFA_EXEC_OPTIONS) != 0) return PCRE_ERROR_BADOPTION; +if (re == NULL || subject == NULL || workspace == NULL || + (offsets == NULL && offsetcount > 0)) return PCRE_ERROR_NULL; +if (offsetcount < 0) return PCRE_ERROR_BADCOUNT; +if (wscount < 20) return PCRE_ERROR_DFA_WSSIZE; +if (length < 0) return PCRE_ERROR_BADLENGTH; +if (start_offset < 0 || start_offset > length) return PCRE_ERROR_BADOFFSET; + +/* Check that the first field in the block is the magic number. If it is not, +return with PCRE_ERROR_BADMAGIC. However, if the magic number is equal to +REVERSED_MAGIC_NUMBER we return with PCRE_ERROR_BADENDIANNESS, which +means that the pattern is likely compiled with different endianness. */ + +if (re->magic_number != MAGIC_NUMBER) + return re->magic_number == REVERSED_MAGIC_NUMBER? + PCRE_ERROR_BADENDIANNESS:PCRE_ERROR_BADMAGIC; +if ((re->flags & PCRE_MODE) == 0) return PCRE_ERROR_BADMODE; + +/* If restarting after a partial match, do some sanity checks on the contents +of the workspace. */ + +if ((options & PCRE_DFA_RESTART) != 0) + { + if ((workspace[0] & (-2)) != 0 || workspace[1] < 1 || + workspace[1] > (wscount - 2)/INTS_PER_STATEBLOCK) + return PCRE_ERROR_DFA_BADRESTART; + } + +/* Set up study, callout, and table data */ + +md->tables = re->tables; +md->callout_data = NULL; + +if (extra_data != NULL) + { + unsigned long int flags = extra_data->flags; + if ((flags & PCRE_EXTRA_STUDY_DATA) != 0) + study = (const pcre_study_data *)extra_data->study_data; + if ((flags & PCRE_EXTRA_MATCH_LIMIT) != 0) return PCRE_ERROR_DFA_UMLIMIT; + if ((flags & PCRE_EXTRA_MATCH_LIMIT_RECURSION) != 0) + return PCRE_ERROR_DFA_UMLIMIT; + if ((flags & PCRE_EXTRA_CALLOUT_DATA) != 0) + md->callout_data = extra_data->callout_data; + if ((flags & PCRE_EXTRA_TABLES) != 0) + md->tables = extra_data->tables; + } + +/* Set some local values */ + +current_subject = (const pcre_uchar *)subject + start_offset; +end_subject = (const pcre_uchar *)subject + length; +req_char_ptr = current_subject - 1; + +#ifdef SUPPORT_UTF +/* PCRE_UTF(16|32) have the same value as PCRE_UTF8. */ +utf = (re->options & PCRE_UTF8) != 0; +#else +utf = FALSE; +#endif + +anchored = (options & (PCRE_ANCHORED|PCRE_DFA_RESTART)) != 0 || + (re->options & PCRE_ANCHORED) != 0; + +/* The remaining fixed data for passing around. */ + +md->start_code = (const pcre_uchar *)argument_re + + re->name_table_offset + re->name_count * re->name_entry_size; +md->start_subject = (const pcre_uchar *)subject; +md->end_subject = end_subject; +md->start_offset = start_offset; +md->moptions = options; +md->poptions = re->options; + +/* If the BSR option is not set at match time, copy what was set +at compile time. */ + +if ((md->moptions & (PCRE_BSR_ANYCRLF|PCRE_BSR_UNICODE)) == 0) + { + if ((re->options & (PCRE_BSR_ANYCRLF|PCRE_BSR_UNICODE)) != 0) + md->moptions |= re->options & (PCRE_BSR_ANYCRLF|PCRE_BSR_UNICODE); +#ifdef BSR_ANYCRLF + else md->moptions |= PCRE_BSR_ANYCRLF; +#endif + } + +/* Handle different types of newline. The three bits give eight cases. If +nothing is set at run time, whatever was used at compile time applies. */ + +switch ((((options & PCRE_NEWLINE_BITS) == 0)? re->options : (pcre_uint32)options) & + PCRE_NEWLINE_BITS) + { + case 0: newline = NEWLINE; break; /* Compile-time default */ + case PCRE_NEWLINE_CR: newline = CHAR_CR; break; + case PCRE_NEWLINE_LF: newline = CHAR_NL; break; + case PCRE_NEWLINE_CR+ + PCRE_NEWLINE_LF: newline = (CHAR_CR << 8) | CHAR_NL; break; + case PCRE_NEWLINE_ANY: newline = -1; break; + case PCRE_NEWLINE_ANYCRLF: newline = -2; break; + default: return PCRE_ERROR_BADNEWLINE; + } + +if (newline == -2) + { + md->nltype = NLTYPE_ANYCRLF; + } +else if (newline < 0) + { + md->nltype = NLTYPE_ANY; + } +else + { + md->nltype = NLTYPE_FIXED; + if (newline > 255) + { + md->nllen = 2; + md->nl[0] = (newline >> 8) & 255; + md->nl[1] = newline & 255; + } + else + { + md->nllen = 1; + md->nl[0] = newline; + } + } + +/* Check a UTF-8 string if required. Unfortunately there's no way of passing +back the character offset. */ + +#ifdef SUPPORT_UTF +if (utf && (options & PCRE_NO_UTF8_CHECK) == 0) + { + int erroroffset; + int errorcode = PRIV(valid_utf)((pcre_uchar *)subject, length, &erroroffset); + if (errorcode != 0) + { + if (offsetcount >= 2) + { + offsets[0] = erroroffset; + offsets[1] = errorcode; + } +#if defined COMPILE_PCRE8 + return (errorcode <= PCRE_UTF8_ERR5 && (options & PCRE_PARTIAL_HARD) != 0) ? + PCRE_ERROR_SHORTUTF8 : PCRE_ERROR_BADUTF8; +#elif defined COMPILE_PCRE16 + return (errorcode <= PCRE_UTF16_ERR1 && (options & PCRE_PARTIAL_HARD) != 0) ? + PCRE_ERROR_SHORTUTF16 : PCRE_ERROR_BADUTF16; +#elif defined COMPILE_PCRE32 + return PCRE_ERROR_BADUTF32; +#endif + } +#if defined COMPILE_PCRE8 || defined COMPILE_PCRE16 + if (start_offset > 0 && start_offset < length && + NOT_FIRSTCHAR(((PCRE_PUCHAR)subject)[start_offset])) + return PCRE_ERROR_BADUTF8_OFFSET; +#endif + } +#endif + +/* If the exec call supplied NULL for tables, use the inbuilt ones. This +is a feature that makes it possible to save compiled regex and re-use them +in other programs later. */ + +if (md->tables == NULL) md->tables = PRIV(default_tables); + +/* The "must be at the start of a line" flags are used in a loop when finding +where to start. */ + +startline = (re->flags & PCRE_STARTLINE) != 0; +firstline = (re->options & PCRE_FIRSTLINE) != 0; + +/* Set up the first character to match, if available. The first_byte value is +never set for an anchored regular expression, but the anchoring may be forced +at run time, so we have to test for anchoring. The first char may be unset for +an unanchored pattern, of course. If there's no first char and the pattern was +studied, there may be a bitmap of possible first characters. */ + +if (!anchored) + { + if ((re->flags & PCRE_FIRSTSET) != 0) + { + has_first_char = TRUE; + first_char = first_char2 = (pcre_uchar)(re->first_char); + if ((re->flags & PCRE_FCH_CASELESS) != 0) + { + first_char2 = TABLE_GET(first_char, md->tables + fcc_offset, first_char); +#if defined SUPPORT_UCP && !(defined COMPILE_PCRE8) + if (utf && first_char > 127) + first_char2 = UCD_OTHERCASE(first_char); +#endif + } + } + else + { + if (!startline && study != NULL && + (study->flags & PCRE_STUDY_MAPPED) != 0) + start_bits = study->start_bits; + } + } + +/* For anchored or unanchored matches, there may be a "last known required +character" set. */ + +if ((re->flags & PCRE_REQCHSET) != 0) + { + has_req_char = TRUE; + req_char = req_char2 = (pcre_uchar)(re->req_char); + if ((re->flags & PCRE_RCH_CASELESS) != 0) + { + req_char2 = TABLE_GET(req_char, md->tables + fcc_offset, req_char); +#if defined SUPPORT_UCP && !(defined COMPILE_PCRE8) + if (utf && req_char > 127) + req_char2 = UCD_OTHERCASE(req_char); +#endif + } + } + +/* Call the main matching function, looping for a non-anchored regex after a +failed match. If not restarting, perform certain optimizations at the start of +a match. */ + +for (;;) + { + int rc; + + if ((options & PCRE_DFA_RESTART) == 0) + { + const pcre_uchar *save_end_subject = end_subject; + + /* If firstline is TRUE, the start of the match is constrained to the first + line of a multiline string. Implement this by temporarily adjusting + end_subject so that we stop scanning at a newline. If the match fails at + the newline, later code breaks this loop. */ + + if (firstline) + { + PCRE_PUCHAR t = current_subject; +#ifdef SUPPORT_UTF + if (utf) + { + while (t < md->end_subject && !IS_NEWLINE(t)) + { + t++; + ACROSSCHAR(t < end_subject, *t, t++); + } + } + else +#endif + while (t < md->end_subject && !IS_NEWLINE(t)) t++; + end_subject = t; + } + + /* There are some optimizations that avoid running the match if a known + starting point is not found. However, there is an option that disables + these, for testing and for ensuring that all callouts do actually occur. + The option can be set in the regex by (*NO_START_OPT) or passed in + match-time options. */ + + if (((options | re->options) & PCRE_NO_START_OPTIMIZE) == 0) + { + /* Advance to a known first pcre_uchar (i.e. data item) */ + + if (has_first_char) + { + if (first_char != first_char2) + { + pcre_uchar csc; + while (current_subject < end_subject && + (csc = UCHAR21TEST(current_subject)) != first_char && csc != first_char2) + current_subject++; + } + else + while (current_subject < end_subject && + UCHAR21TEST(current_subject) != first_char) + current_subject++; + } + + /* Or to just after a linebreak for a multiline match if possible */ + + else if (startline) + { + if (current_subject > md->start_subject + start_offset) + { +#ifdef SUPPORT_UTF + if (utf) + { + while (current_subject < end_subject && + !WAS_NEWLINE(current_subject)) + { + current_subject++; + ACROSSCHAR(current_subject < end_subject, *current_subject, + current_subject++); + } + } + else +#endif + while (current_subject < end_subject && !WAS_NEWLINE(current_subject)) + current_subject++; + + /* If we have just passed a CR and the newline option is ANY or + ANYCRLF, and we are now at a LF, advance the match position by one + more character. */ + + if (UCHAR21TEST(current_subject - 1) == CHAR_CR && + (md->nltype == NLTYPE_ANY || md->nltype == NLTYPE_ANYCRLF) && + current_subject < end_subject && + UCHAR21TEST(current_subject) == CHAR_NL) + current_subject++; + } + } + + /* Advance to a non-unique first pcre_uchar after study */ + + else if (start_bits != NULL) + { + while (current_subject < end_subject) + { + register pcre_uint32 c = UCHAR21TEST(current_subject); +#ifndef COMPILE_PCRE8 + if (c > 255) c = 255; +#endif + if ((start_bits[c/8] & (1 << (c&7))) != 0) break; + current_subject++; + } + } + } + + /* Restore fudged end_subject */ + + end_subject = save_end_subject; + + /* The following two optimizations are disabled for partial matching or if + disabling is explicitly requested (and of course, by the test above, this + code is not obeyed when restarting after a partial match). */ + + if (((options | re->options) & PCRE_NO_START_OPTIMIZE) == 0 && + (options & (PCRE_PARTIAL_HARD|PCRE_PARTIAL_SOFT)) == 0) + { + /* If the pattern was studied, a minimum subject length may be set. This + is a lower bound; no actual string of that length may actually match the + pattern. Although the value is, strictly, in characters, we treat it as + in pcre_uchar units to avoid spending too much time in this optimization. + */ + + if (study != NULL && (study->flags & PCRE_STUDY_MINLEN) != 0 && + (pcre_uint32)(end_subject - current_subject) < study->minlength) + return PCRE_ERROR_NOMATCH; + + /* If req_char is set, we know that that pcre_uchar must appear in the + subject for the match to succeed. If the first pcre_uchar is set, + req_char must be later in the subject; otherwise the test starts at the + match point. This optimization can save a huge amount of work in patterns + with nested unlimited repeats that aren't going to match. Writing + separate code for cased/caseless versions makes it go faster, as does + using an autoincrement and backing off on a match. + + HOWEVER: when the subject string is very, very long, searching to its end + can take a long time, and give bad performance on quite ordinary + patterns. This showed up when somebody was matching /^C/ on a 32-megabyte + string... so we don't do this when the string is sufficiently long. */ + + if (has_req_char && end_subject - current_subject < REQ_BYTE_MAX) + { + register PCRE_PUCHAR p = current_subject + (has_first_char? 1:0); + + /* We don't need to repeat the search if we haven't yet reached the + place we found it at last time. */ + + if (p > req_char_ptr) + { + if (req_char != req_char2) + { + while (p < end_subject) + { + register pcre_uint32 pp = UCHAR21INCTEST(p); + if (pp == req_char || pp == req_char2) { p--; break; } + } + } + else + { + while (p < end_subject) + { + if (UCHAR21INCTEST(p) == req_char) { p--; break; } + } + } + + /* If we can't find the required pcre_uchar, break the matching loop, + which will cause a return or PCRE_ERROR_NOMATCH. */ + + if (p >= end_subject) break; + + /* If we have found the required pcre_uchar, save the point where we + found it, so that we don't search again next time round the loop if + the start hasn't passed this point yet. */ + + req_char_ptr = p; + } + } + } + } /* End of optimizations that are done when not restarting */ + + /* OK, now we can do the business */ + + md->start_used_ptr = current_subject; + md->recursive = NULL; + + rc = internal_dfa_exec( + md, /* fixed match data */ + md->start_code, /* this subexpression's code */ + current_subject, /* where we currently are */ + start_offset, /* start offset in subject */ + offsets, /* offset vector */ + offsetcount, /* size of same */ + workspace, /* workspace vector */ + wscount, /* size of same */ + 0); /* function recurse level */ + + /* Anything other than "no match" means we are done, always; otherwise, carry + on only if not anchored. */ + + if (rc != PCRE_ERROR_NOMATCH || anchored) + { + if (rc == PCRE_ERROR_PARTIAL && offsetcount >= 2) + { + offsets[0] = (int)(md->start_used_ptr - (PCRE_PUCHAR)subject); + offsets[1] = (int)(end_subject - (PCRE_PUCHAR)subject); + if (offsetcount > 2) + offsets[2] = (int)(current_subject - (PCRE_PUCHAR)subject); + } + return rc; + } + + /* Advance to the next subject character unless we are at the end of a line + and firstline is set. */ + + if (firstline && IS_NEWLINE(current_subject)) break; + current_subject++; +#ifdef SUPPORT_UTF + if (utf) + { + ACROSSCHAR(current_subject < end_subject, *current_subject, + current_subject++); + } +#endif + if (current_subject > end_subject) break; + + /* If we have just passed a CR and we are now at a LF, and the pattern does + not contain any explicit matches for \r or \n, and the newline option is CRLF + or ANY or ANYCRLF, advance the match position by one more character. */ + + if (UCHAR21TEST(current_subject - 1) == CHAR_CR && + current_subject < end_subject && + UCHAR21TEST(current_subject) == CHAR_NL && + (re->flags & PCRE_HASCRORLF) == 0 && + (md->nltype == NLTYPE_ANY || + md->nltype == NLTYPE_ANYCRLF || + md->nllen == 2)) + current_subject++; + + } /* "Bumpalong" loop */ + +return PCRE_ERROR_NOMATCH; +} + +/* End of pcre_dfa_exec.c */ diff --git a/src/private/pcre_src/pcre_exec.c b/src/private/pcre_src/pcre_exec.c new file mode 100644 index 000000000..654eb9e27 --- /dev/null +++ b/src/private/pcre_src/pcre_exec.c @@ -0,0 +1,7160 @@ +/************************************************* +* Perl-Compatible Regular Expressions * +*************************************************/ + +/* PCRE is a library of functions to support regular expressions whose syntax +and semantics are as close as possible to those of the Perl 5 language. + + Written by Philip Hazel + Copyright (c) 1997-2014 University of Cambridge + +----------------------------------------------------------------------------- +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * Neither the name of the University of Cambridge nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. +----------------------------------------------------------------------------- +*/ + +/* This module contains pcre_exec(), the externally visible function that does +pattern matching using an NFA algorithm, trying to mimic Perl as closely as +possible. There are also some static supporting functions. */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#define NLBLOCK md /* Block containing newline information */ +#define PSSTART start_subject /* Field containing processed string start */ +#define PSEND end_subject /* Field containing processed string end */ + +#include "pcre_internal.h" + +/* Undefine some potentially clashing cpp symbols */ + +#undef min +#undef max + +/* The md->capture_last field uses the lower 16 bits for the last captured +substring (which can never be greater than 65535) and a bit in the top half +to mean "capture vector overflowed". This odd way of doing things was +implemented when it was realized that preserving and restoring the overflow bit +whenever the last capture number was saved/restored made for a neater +interface, and doing it this way saved on (a) another variable, which would +have increased the stack frame size (a big NO-NO in PCRE) and (b) another +separate set of save/restore instructions. The following defines are used in +implementing this. */ + +#define CAPLMASK 0x0000ffff /* The bits used for last_capture */ +#define OVFLMASK 0xffff0000 /* The bits used for the overflow flag */ +#define OVFLBIT 0x00010000 /* The bit that is set for overflow */ + +/* Values for setting in md->match_function_type to indicate two special types +of call to match(). We do it this way to save on using another stack variable, +as stack usage is to be discouraged. */ + +#define MATCH_CONDASSERT 1 /* Called to check a condition assertion */ +#define MATCH_CBEGROUP 2 /* Could-be-empty unlimited repeat group */ + +/* Non-error returns from the match() function. Error returns are externally +defined PCRE_ERROR_xxx codes, which are all negative. */ + +#define MATCH_MATCH 1 +#define MATCH_NOMATCH 0 + +/* Special internal returns from the match() function. Make them sufficiently +negative to avoid the external error codes. */ + +#define MATCH_ACCEPT (-999) +#define MATCH_KETRPOS (-998) +#define MATCH_ONCE (-997) +/* The next 5 must be kept together and in sequence so that a test that checks +for any one of them can use a range. */ +#define MATCH_COMMIT (-996) +#define MATCH_PRUNE (-995) +#define MATCH_SKIP (-994) +#define MATCH_SKIP_ARG (-993) +#define MATCH_THEN (-992) +#define MATCH_BACKTRACK_MAX MATCH_THEN +#define MATCH_BACKTRACK_MIN MATCH_COMMIT + +/* Maximum number of ints of offset to save on the stack for recursive calls. +If the offset vector is bigger, malloc is used. This should be a multiple of 3, +because the offset vector is always a multiple of 3 long. */ + +#define REC_STACK_SAVE_MAX 30 + +/* Min and max values for the common repeats; for the maxima, 0 => infinity */ + +static const char rep_min[] = { 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, }; +static const char rep_max[] = { 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, }; + +#ifdef PCRE_DEBUG +/************************************************* +* Debugging function to print chars * +*************************************************/ + +/* Print a sequence of chars in printable format, stopping at the end of the +subject if the requested. + +Arguments: + p points to characters + length number to print + is_subject TRUE if printing from within md->start_subject + md pointer to matching data block, if is_subject is TRUE + +Returns: nothing +*/ + +static void +pchars(const pcre_uchar *p, int length, BOOL is_subject, match_data *md) +{ +pcre_uint32 c; +BOOL utf = md->utf; +if (is_subject && length > md->end_subject - p) length = md->end_subject - p; +while (length-- > 0) + if (isprint(c = UCHAR21INCTEST(p))) printf("%c", (char)c); else printf("\\x{%02x}", c); +} +#endif + + + +/************************************************* +* Match a back-reference * +*************************************************/ + +/* Normally, if a back reference hasn't been set, the length that is passed is +negative, so the match always fails. However, in JavaScript compatibility mode, +the length passed is zero. Note that in caseless UTF-8 mode, the number of +subject bytes matched may be different to the number of reference bytes. + +Arguments: + offset index into the offset vector + eptr pointer into the subject + length length of reference to be matched (number of bytes) + md points to match data block + caseless TRUE if caseless + +Returns: >= 0 the number of subject bytes matched + -1 no match + -2 partial match; always given if at end subject +*/ + +static int +match_ref(int offset, register PCRE_PUCHAR eptr, int length, match_data *md, + BOOL caseless) +{ +PCRE_PUCHAR eptr_start = eptr; +register PCRE_PUCHAR p = md->start_subject + md->offset_vector[offset]; +#if defined SUPPORT_UTF && defined SUPPORT_UCP +BOOL utf = md->utf; +#endif + +#ifdef PCRE_DEBUG +if (eptr >= md->end_subject) + printf("matching subject "); +else + { + printf("matching subject "); + pchars(eptr, length, TRUE, md); + } +printf(" against backref "); +pchars(p, length, FALSE, md); +printf("\n"); +#endif + +/* Always fail if reference not set (and not JavaScript compatible - in that +case the length is passed as zero). */ + +if (length < 0) return -1; + +/* Separate the caseless case for speed. In UTF-8 mode we can only do this +properly if Unicode properties are supported. Otherwise, we can check only +ASCII characters. */ + +if (caseless) + { +#if defined SUPPORT_UTF && defined SUPPORT_UCP + if (utf) + { + /* Match characters up to the end of the reference. NOTE: the number of + data units matched may differ, because in UTF-8 there are some characters + whose upper and lower case versions code have different numbers of bytes. + For example, U+023A (2 bytes in UTF-8) is the upper case version of U+2C65 + (3 bytes in UTF-8); a sequence of 3 of the former uses 6 bytes, as does a + sequence of two of the latter. It is important, therefore, to check the + length along the reference, not along the subject (earlier code did this + wrong). */ + + PCRE_PUCHAR endptr = p + length; + while (p < endptr) + { + pcre_uint32 c, d; + const ucd_record *ur; + if (eptr >= md->end_subject) return -2; /* Partial match */ + GETCHARINC(c, eptr); + GETCHARINC(d, p); + ur = GET_UCD(d); + if (c != d && c != d + ur->other_case) + { + const pcre_uint32 *pp = PRIV(ucd_caseless_sets) + ur->caseset; + for (;;) + { + if (c < *pp) return -1; + if (c == *pp++) break; + } + } + } + } + else +#endif + + /* The same code works when not in UTF-8 mode and in UTF-8 mode when there + is no UCP support. */ + { + while (length-- > 0) + { + pcre_uint32 cc, cp; + if (eptr >= md->end_subject) return -2; /* Partial match */ + cc = UCHAR21TEST(eptr); + cp = UCHAR21TEST(p); + if (TABLE_GET(cp, md->lcc, cp) != TABLE_GET(cc, md->lcc, cc)) return -1; + p++; + eptr++; + } + } + } + +/* In the caseful case, we can just compare the bytes, whether or not we +are in UTF-8 mode. */ + +else + { + while (length-- > 0) + { + if (eptr >= md->end_subject) return -2; /* Partial match */ + if (UCHAR21INCTEST(p) != UCHAR21INCTEST(eptr)) return -1; + } + } + +return (int)(eptr - eptr_start); +} + + + +/*************************************************************************** +**************************************************************************** + RECURSION IN THE match() FUNCTION + +The match() function is highly recursive, though not every recursive call +increases the recursive depth. Nevertheless, some regular expressions can cause +it to recurse to a great depth. I was writing for Unix, so I just let it call +itself recursively. This uses the stack for saving everything that has to be +saved for a recursive call. On Unix, the stack can be large, and this works +fine. + +It turns out that on some non-Unix-like systems there are problems with +programs that use a lot of stack. (This despite the fact that every last chip +has oodles of memory these days, and techniques for extending the stack have +been known for decades.) So.... + +There is a fudge, triggered by defining NO_RECURSE, which avoids recursive +calls by keeping local variables that need to be preserved in blocks of memory +obtained from malloc() instead instead of on the stack. Macros are used to +achieve this so that the actual code doesn't look very different to what it +always used to. + +The original heap-recursive code used longjmp(). However, it seems that this +can be very slow on some operating systems. Following a suggestion from Stan +Switzer, the use of longjmp() has been abolished, at the cost of having to +provide a unique number for each call to RMATCH. There is no way of generating +a sequence of numbers at compile time in C. I have given them names, to make +them stand out more clearly. + +Crude tests on x86 Linux show a small speedup of around 5-8%. However, on +FreeBSD, avoiding longjmp() more than halves the time taken to run the standard +tests. Furthermore, not using longjmp() means that local dynamic variables +don't have indeterminate values; this has meant that the frame size can be +reduced because the result can be "passed back" by straight setting of the +variable instead of being passed in the frame. +**************************************************************************** +***************************************************************************/ + +/* Numbers for RMATCH calls. When this list is changed, the code at HEAP_RETURN +below must be updated in sync. */ + +enum { RM1=1, RM2, RM3, RM4, RM5, RM6, RM7, RM8, RM9, RM10, + RM11, RM12, RM13, RM14, RM15, RM16, RM17, RM18, RM19, RM20, + RM21, RM22, RM23, RM24, RM25, RM26, RM27, RM28, RM29, RM30, + RM31, RM32, RM33, RM34, RM35, RM36, RM37, RM38, RM39, RM40, + RM41, RM42, RM43, RM44, RM45, RM46, RM47, RM48, RM49, RM50, + RM51, RM52, RM53, RM54, RM55, RM56, RM57, RM58, RM59, RM60, + RM61, RM62, RM63, RM64, RM65, RM66, RM67 }; + +/* These versions of the macros use the stack, as normal. There are debugging +versions and production versions. Note that the "rw" argument of RMATCH isn't +actually used in this definition. */ + +#ifndef NO_RECURSE +#define REGISTER register + +#ifdef PCRE_DEBUG +#define RMATCH(ra,rb,rc,rd,re,rw) \ + { \ + printf("match() called in line %d\n", __LINE__); \ + rrc = match(ra,rb,mstart,rc,rd,re,rdepth+1); \ + printf("to line %d\n", __LINE__); \ + } +#define RRETURN(ra) \ + { \ + printf("match() returned %d from line %d\n", ra, __LINE__); \ + return ra; \ + } +#else +#define RMATCH(ra,rb,rc,rd,re,rw) \ + rrc = match(ra,rb,mstart,rc,rd,re,rdepth+1) +#define RRETURN(ra) return ra +#endif + +#else + + +/* These versions of the macros manage a private stack on the heap. Note that +the "rd" argument of RMATCH isn't actually used in this definition. It's the md +argument of match(), which never changes. */ + +#define REGISTER + +#define RMATCH(ra,rb,rc,rd,re,rw)\ + {\ + heapframe *newframe = frame->Xnextframe;\ + if (newframe == NULL)\ + {\ + newframe = (heapframe *)(PUBL(stack_malloc))(sizeof(heapframe));\ + if (newframe == NULL) RRETURN(PCRE_ERROR_NOMEMORY);\ + newframe->Xnextframe = NULL;\ + frame->Xnextframe = newframe;\ + }\ + frame->Xwhere = rw;\ + newframe->Xeptr = ra;\ + newframe->Xecode = rb;\ + newframe->Xmstart = mstart;\ + newframe->Xoffset_top = rc;\ + newframe->Xeptrb = re;\ + newframe->Xrdepth = frame->Xrdepth + 1;\ + newframe->Xprevframe = frame;\ + frame = newframe;\ + DPRINTF(("restarting from line %d\n", __LINE__));\ + goto HEAP_RECURSE;\ + L_##rw:\ + DPRINTF(("jumped back to line %d\n", __LINE__));\ + } + +#define RRETURN(ra)\ + {\ + heapframe *oldframe = frame;\ + frame = oldframe->Xprevframe;\ + if (frame != NULL)\ + {\ + rrc = ra;\ + goto HEAP_RETURN;\ + }\ + return ra;\ + } + + +/* Structure for remembering the local variables in a private frame */ + +typedef struct heapframe { + struct heapframe *Xprevframe; + struct heapframe *Xnextframe; + + /* Function arguments that may change */ + + PCRE_PUCHAR Xeptr; + const pcre_uchar *Xecode; + PCRE_PUCHAR Xmstart; + int Xoffset_top; + eptrblock *Xeptrb; + unsigned int Xrdepth; + + /* Function local variables */ + + PCRE_PUCHAR Xcallpat; +#ifdef SUPPORT_UTF + PCRE_PUCHAR Xcharptr; +#endif + PCRE_PUCHAR Xdata; + PCRE_PUCHAR Xnext; + PCRE_PUCHAR Xpp; + PCRE_PUCHAR Xprev; + PCRE_PUCHAR Xsaved_eptr; + + recursion_info Xnew_recursive; + + BOOL Xcur_is_word; + BOOL Xcondition; + BOOL Xprev_is_word; + +#ifdef SUPPORT_UCP + int Xprop_type; + unsigned int Xprop_value; + int Xprop_fail_result; + int Xoclength; + pcre_uchar Xocchars[6]; +#endif + + int Xcodelink; + int Xctype; + unsigned int Xfc; + int Xfi; + int Xlength; + int Xmax; + int Xmin; + unsigned int Xnumber; + int Xoffset; + unsigned int Xop; + pcre_int32 Xsave_capture_last; + int Xsave_offset1, Xsave_offset2, Xsave_offset3; + int Xstacksave[REC_STACK_SAVE_MAX]; + + eptrblock Xnewptrb; + + /* Where to jump back to */ + + int Xwhere; + +} heapframe; + +#endif + + +/*************************************************************************** +***************************************************************************/ + + + +/************************************************* +* Match from current position * +*************************************************/ + +/* This function is called recursively in many circumstances. Whenever it +returns a negative (error) response, the outer incarnation must also return the +same response. */ + +/* These macros pack up tests that are used for partial matching, and which +appear several times in the code. We set the "hit end" flag if the pointer is +at the end of the subject and also past the start of the subject (i.e. +something has been matched). For hard partial matching, we then return +immediately. The second one is used when we already know we are past the end of +the subject. */ + +#define CHECK_PARTIAL()\ + if (md->partial != 0 && eptr >= md->end_subject && \ + eptr > md->start_used_ptr) \ + { \ + md->hitend = TRUE; \ + if (md->partial > 1) RRETURN(PCRE_ERROR_PARTIAL); \ + } + +#define SCHECK_PARTIAL()\ + if (md->partial != 0 && eptr > md->start_used_ptr) \ + { \ + md->hitend = TRUE; \ + if (md->partial > 1) RRETURN(PCRE_ERROR_PARTIAL); \ + } + + +/* Performance note: It might be tempting to extract commonly used fields from +the md structure (e.g. utf, end_subject) into individual variables to improve +performance. Tests using gcc on a SPARC disproved this; in the first case, it +made performance worse. + +Arguments: + eptr pointer to current character in subject + ecode pointer to current position in compiled code + mstart pointer to the current match start position (can be modified + by encountering \K) + offset_top current top pointer + md pointer to "static" info for the match + eptrb pointer to chain of blocks containing eptr at start of + brackets - for testing for empty matches + rdepth the recursion depth + +Returns: MATCH_MATCH if matched ) these values are >= 0 + MATCH_NOMATCH if failed to match ) + a negative MATCH_xxx value for PRUNE, SKIP, etc + a negative PCRE_ERROR_xxx value if aborted by an error condition + (e.g. stopped by repeated call or recursion limit) +*/ + +static int +match(REGISTER PCRE_PUCHAR eptr, REGISTER const pcre_uchar *ecode, + PCRE_PUCHAR mstart, int offset_top, match_data *md, eptrblock *eptrb, + unsigned int rdepth) +{ +/* These variables do not need to be preserved over recursion in this function, +so they can be ordinary variables in all cases. Mark some of them with +"register" because they are used a lot in loops. */ + +register int rrc; /* Returns from recursive calls */ +register int i; /* Used for loops not involving calls to RMATCH() */ +register pcre_uint32 c; /* Character values not kept over RMATCH() calls */ +register BOOL utf; /* Local copy of UTF flag for speed */ + +BOOL minimize, possessive; /* Quantifier options */ +BOOL caseless; +int condcode; + +/* When recursion is not being used, all "local" variables that have to be +preserved over calls to RMATCH() are part of a "frame". We set up the top-level +frame on the stack here; subsequent instantiations are obtained from the heap +whenever RMATCH() does a "recursion". See the macro definitions above. Putting +the top-level on the stack rather than malloc-ing them all gives a performance +boost in many cases where there is not much "recursion". */ + +#ifdef NO_RECURSE +heapframe *frame = (heapframe *)md->match_frames_base; + +/* Copy in the original argument variables */ + +frame->Xeptr = eptr; +frame->Xecode = ecode; +frame->Xmstart = mstart; +frame->Xoffset_top = offset_top; +frame->Xeptrb = eptrb; +frame->Xrdepth = rdepth; + +/* This is where control jumps back to to effect "recursion" */ + +HEAP_RECURSE: + +/* Macros make the argument variables come from the current frame */ + +#define eptr frame->Xeptr +#define ecode frame->Xecode +#define mstart frame->Xmstart +#define offset_top frame->Xoffset_top +#define eptrb frame->Xeptrb +#define rdepth frame->Xrdepth + +/* Ditto for the local variables */ + +#ifdef SUPPORT_UTF +#define charptr frame->Xcharptr +#endif +#define callpat frame->Xcallpat +#define codelink frame->Xcodelink +#define data frame->Xdata +#define next frame->Xnext +#define pp frame->Xpp +#define prev frame->Xprev +#define saved_eptr frame->Xsaved_eptr + +#define new_recursive frame->Xnew_recursive + +#define cur_is_word frame->Xcur_is_word +#define condition frame->Xcondition +#define prev_is_word frame->Xprev_is_word + +#ifdef SUPPORT_UCP +#define prop_type frame->Xprop_type +#define prop_value frame->Xprop_value +#define prop_fail_result frame->Xprop_fail_result +#define oclength frame->Xoclength +#define occhars frame->Xocchars +#endif + +#define ctype frame->Xctype +#define fc frame->Xfc +#define fi frame->Xfi +#define length frame->Xlength +#define max frame->Xmax +#define min frame->Xmin +#define number frame->Xnumber +#define offset frame->Xoffset +#define op frame->Xop +#define save_capture_last frame->Xsave_capture_last +#define save_offset1 frame->Xsave_offset1 +#define save_offset2 frame->Xsave_offset2 +#define save_offset3 frame->Xsave_offset3 +#define stacksave frame->Xstacksave + +#define newptrb frame->Xnewptrb + +/* When recursion is being used, local variables are allocated on the stack and +get preserved during recursion in the normal way. In this environment, fi and +i, and fc and c, can be the same variables. */ + +#else /* NO_RECURSE not defined */ +#define fi i +#define fc c + +/* Many of the following variables are used only in small blocks of the code. +My normal style of coding would have declared them within each of those blocks. +However, in order to accommodate the version of this code that uses an external +"stack" implemented on the heap, it is easier to declare them all here, so the +declarations can be cut out in a block. The only declarations within blocks +below are for variables that do not have to be preserved over a recursive call +to RMATCH(). */ + +#ifdef SUPPORT_UTF +const pcre_uchar *charptr; +#endif +const pcre_uchar *callpat; +const pcre_uchar *data; +const pcre_uchar *next; +PCRE_PUCHAR pp; +const pcre_uchar *prev; +PCRE_PUCHAR saved_eptr; + +recursion_info new_recursive; + +BOOL cur_is_word; +BOOL condition; +BOOL prev_is_word; + +#ifdef SUPPORT_UCP +int prop_type; +unsigned int prop_value; +int prop_fail_result; +int oclength; +pcre_uchar occhars[6]; +#endif + +int codelink; +int ctype; +int length; +int max; +int min; +unsigned int number; +int offset; +unsigned int op; +pcre_int32 save_capture_last; +int save_offset1, save_offset2, save_offset3; +int stacksave[REC_STACK_SAVE_MAX]; + +eptrblock newptrb; + +/* There is a special fudge for calling match() in a way that causes it to +measure the size of its basic stack frame when the stack is being used for +recursion. The second argument (ecode) being NULL triggers this behaviour. It +cannot normally ever be NULL. The return is the negated value of the frame +size. */ + +if (ecode == NULL) + { + if (rdepth == 0) + return match((PCRE_PUCHAR)&rdepth, NULL, NULL, 0, NULL, NULL, 1); + else + { + int len = (char *)&rdepth - (char *)eptr; + return (len > 0)? -len : len; + } + } +#endif /* NO_RECURSE */ + +/* To save space on the stack and in the heap frame, I have doubled up on some +of the local variables that are used only in localised parts of the code, but +still need to be preserved over recursive calls of match(). These macros define +the alternative names that are used. */ + +#define allow_zero cur_is_word +#define cbegroup condition +#define code_offset codelink +#define condassert condition +#define matched_once prev_is_word +#define foc number +#define save_mark data + +/* These statements are here to stop the compiler complaining about unitialized +variables. */ + +#ifdef SUPPORT_UCP +prop_value = 0; +prop_fail_result = 0; +#endif + + +/* This label is used for tail recursion, which is used in a few cases even +when NO_RECURSE is not defined, in order to reduce the amount of stack that is +used. Thanks to Ian Taylor for noticing this possibility and sending the +original patch. */ + +TAIL_RECURSE: + +/* OK, now we can get on with the real code of the function. Recursive calls +are specified by the macro RMATCH and RRETURN is used to return. When +NO_RECURSE is *not* defined, these just turn into a recursive call to match() +and a "return", respectively (possibly with some debugging if PCRE_DEBUG is +defined). However, RMATCH isn't like a function call because it's quite a +complicated macro. It has to be used in one particular way. This shouldn't, +however, impact performance when true recursion is being used. */ + +#ifdef SUPPORT_UTF +utf = md->utf; /* Local copy of the flag */ +#else +utf = FALSE; +#endif + +/* First check that we haven't called match() too many times, or that we +haven't exceeded the recursive call limit. */ + +if (md->match_call_count++ >= md->match_limit) RRETURN(PCRE_ERROR_MATCHLIMIT); +if (rdepth >= md->match_limit_recursion) RRETURN(PCRE_ERROR_RECURSIONLIMIT); + +/* At the start of a group with an unlimited repeat that may match an empty +string, the variable md->match_function_type is set to MATCH_CBEGROUP. It is +done this way to save having to use another function argument, which would take +up space on the stack. See also MATCH_CONDASSERT below. + +When MATCH_CBEGROUP is set, add the current subject pointer to the chain of +such remembered pointers, to be checked when we hit the closing ket, in order +to break infinite loops that match no characters. When match() is called in +other circumstances, don't add to the chain. The MATCH_CBEGROUP feature must +NOT be used with tail recursion, because the memory block that is used is on +the stack, so a new one may be required for each match(). */ + +if (md->match_function_type == MATCH_CBEGROUP) + { + newptrb.epb_saved_eptr = eptr; + newptrb.epb_prev = eptrb; + eptrb = &newptrb; + md->match_function_type = 0; + } + +/* Now start processing the opcodes. */ + +for (;;) + { + minimize = possessive = FALSE; + op = *ecode; + + switch(op) + { + case OP_MARK: + md->nomatch_mark = ecode + 2; + md->mark = NULL; /* In case previously set by assertion */ + RMATCH(eptr, ecode + PRIV(OP_lengths)[*ecode] + ecode[1], offset_top, md, + eptrb, RM55); + if ((rrc == MATCH_MATCH || rrc == MATCH_ACCEPT) && + md->mark == NULL) md->mark = ecode + 2; + + /* A return of MATCH_SKIP_ARG means that matching failed at SKIP with an + argument, and we must check whether that argument matches this MARK's + argument. It is passed back in md->start_match_ptr (an overloading of that + variable). If it does match, we reset that variable to the current subject + position and return MATCH_SKIP. Otherwise, pass back the return code + unaltered. */ + + else if (rrc == MATCH_SKIP_ARG && + STRCMP_UC_UC_TEST(ecode + 2, md->start_match_ptr) == 0) + { + md->start_match_ptr = eptr; + RRETURN(MATCH_SKIP); + } + RRETURN(rrc); + + case OP_FAIL: + RRETURN(MATCH_NOMATCH); + + case OP_COMMIT: + RMATCH(eptr, ecode + PRIV(OP_lengths)[*ecode], offset_top, md, + eptrb, RM52); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + RRETURN(MATCH_COMMIT); + + case OP_PRUNE: + RMATCH(eptr, ecode + PRIV(OP_lengths)[*ecode], offset_top, md, + eptrb, RM51); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + RRETURN(MATCH_PRUNE); + + case OP_PRUNE_ARG: + md->nomatch_mark = ecode + 2; + md->mark = NULL; /* In case previously set by assertion */ + RMATCH(eptr, ecode + PRIV(OP_lengths)[*ecode] + ecode[1], offset_top, md, + eptrb, RM56); + if ((rrc == MATCH_MATCH || rrc == MATCH_ACCEPT) && + md->mark == NULL) md->mark = ecode + 2; + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + RRETURN(MATCH_PRUNE); + + case OP_SKIP: + RMATCH(eptr, ecode + PRIV(OP_lengths)[*ecode], offset_top, md, + eptrb, RM53); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + md->start_match_ptr = eptr; /* Pass back current position */ + RRETURN(MATCH_SKIP); + + /* Note that, for Perl compatibility, SKIP with an argument does NOT set + nomatch_mark. When a pattern match ends with a SKIP_ARG for which there was + not a matching mark, we have to re-run the match, ignoring the SKIP_ARG + that failed and any that precede it (either they also failed, or were not + triggered). To do this, we maintain a count of executed SKIP_ARGs. If a + SKIP_ARG gets to top level, the match is re-run with md->ignore_skip_arg + set to the count of the one that failed. */ + + case OP_SKIP_ARG: + md->skip_arg_count++; + if (md->skip_arg_count <= md->ignore_skip_arg) + { + ecode += PRIV(OP_lengths)[*ecode] + ecode[1]; + break; + } + RMATCH(eptr, ecode + PRIV(OP_lengths)[*ecode] + ecode[1], offset_top, md, + eptrb, RM57); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + + /* Pass back the current skip name by overloading md->start_match_ptr and + returning the special MATCH_SKIP_ARG return code. This will either be + caught by a matching MARK, or get to the top, where it causes a rematch + with md->ignore_skip_arg set to the value of md->skip_arg_count. */ + + md->start_match_ptr = ecode + 2; + RRETURN(MATCH_SKIP_ARG); + + /* For THEN (and THEN_ARG) we pass back the address of the opcode, so that + the branch in which it occurs can be determined. Overload the start of + match pointer to do this. */ + + case OP_THEN: + RMATCH(eptr, ecode + PRIV(OP_lengths)[*ecode], offset_top, md, + eptrb, RM54); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + md->start_match_ptr = ecode; + RRETURN(MATCH_THEN); + + case OP_THEN_ARG: + md->nomatch_mark = ecode + 2; + md->mark = NULL; /* In case previously set by assertion */ + RMATCH(eptr, ecode + PRIV(OP_lengths)[*ecode] + ecode[1], offset_top, + md, eptrb, RM58); + if ((rrc == MATCH_MATCH || rrc == MATCH_ACCEPT) && + md->mark == NULL) md->mark = ecode + 2; + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + md->start_match_ptr = ecode; + RRETURN(MATCH_THEN); + + /* Handle an atomic group that does not contain any capturing parentheses. + This can be handled like an assertion. Prior to 8.13, all atomic groups + were handled this way. In 8.13, the code was changed as below for ONCE, so + that backups pass through the group and thereby reset captured values. + However, this uses a lot more stack, so in 8.20, atomic groups that do not + contain any captures generate OP_ONCE_NC, which can be handled in the old, + less stack intensive way. + + Check the alternative branches in turn - the matching won't pass the KET + for this kind of subpattern. If any one branch matches, we carry on as at + the end of a normal bracket, leaving the subject pointer, but resetting + the start-of-match value in case it was changed by \K. */ + + case OP_ONCE_NC: + prev = ecode; + saved_eptr = eptr; + save_mark = md->mark; + do + { + RMATCH(eptr, ecode + 1 + LINK_SIZE, offset_top, md, eptrb, RM64); + if (rrc == MATCH_MATCH) /* Note: _not_ MATCH_ACCEPT */ + { + mstart = md->start_match_ptr; + break; + } + if (rrc == MATCH_THEN) + { + next = ecode + GET(ecode,1); + if (md->start_match_ptr < next && + (*ecode == OP_ALT || *next == OP_ALT)) + rrc = MATCH_NOMATCH; + } + + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + ecode += GET(ecode,1); + md->mark = save_mark; + } + while (*ecode == OP_ALT); + + /* If hit the end of the group (which could be repeated), fail */ + + if (*ecode != OP_ONCE_NC && *ecode != OP_ALT) RRETURN(MATCH_NOMATCH); + + /* Continue as from after the group, updating the offsets high water + mark, since extracts may have been taken. */ + + do ecode += GET(ecode, 1); while (*ecode == OP_ALT); + + offset_top = md->end_offset_top; + eptr = md->end_match_ptr; + + /* For a non-repeating ket, just continue at this level. This also + happens for a repeating ket if no characters were matched in the group. + This is the forcible breaking of infinite loops as implemented in Perl + 5.005. */ + + if (*ecode == OP_KET || eptr == saved_eptr) + { + ecode += 1+LINK_SIZE; + break; + } + + /* The repeating kets try the rest of the pattern or restart from the + preceding bracket, in the appropriate order. The second "call" of match() + uses tail recursion, to avoid using another stack frame. */ + + if (*ecode == OP_KETRMIN) + { + RMATCH(eptr, ecode + 1 + LINK_SIZE, offset_top, md, eptrb, RM65); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + ecode = prev; + goto TAIL_RECURSE; + } + else /* OP_KETRMAX */ + { + RMATCH(eptr, prev, offset_top, md, eptrb, RM66); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + ecode += 1 + LINK_SIZE; + goto TAIL_RECURSE; + } + /* Control never gets here */ + + /* Handle a capturing bracket, other than those that are possessive with an + unlimited repeat. If there is space in the offset vector, save the current + subject position in the working slot at the top of the vector. We mustn't + change the current values of the data slot, because they may be set from a + previous iteration of this group, and be referred to by a reference inside + the group. A failure to match might occur after the group has succeeded, + if something later on doesn't match. For this reason, we need to restore + the working value and also the values of the final offsets, in case they + were set by a previous iteration of the same bracket. + + If there isn't enough space in the offset vector, treat this as if it were + a non-capturing bracket. Don't worry about setting the flag for the error + case here; that is handled in the code for KET. */ + + case OP_CBRA: + case OP_SCBRA: + number = GET2(ecode, 1+LINK_SIZE); + offset = number << 1; + +#ifdef PCRE_DEBUG + printf("start bracket %d\n", number); + printf("subject="); + pchars(eptr, 16, TRUE, md); + printf("\n"); +#endif + + if (offset < md->offset_max) + { + save_offset1 = md->offset_vector[offset]; + save_offset2 = md->offset_vector[offset+1]; + save_offset3 = md->offset_vector[md->offset_end - number]; + save_capture_last = md->capture_last; + save_mark = md->mark; + + DPRINTF(("saving %d %d %d\n", save_offset1, save_offset2, save_offset3)); + md->offset_vector[md->offset_end - number] = + (int)(eptr - md->start_subject); + + for (;;) + { + if (op >= OP_SBRA) md->match_function_type = MATCH_CBEGROUP; + RMATCH(eptr, ecode + PRIV(OP_lengths)[*ecode], offset_top, md, + eptrb, RM1); + if (rrc == MATCH_ONCE) break; /* Backing up through an atomic group */ + + /* If we backed up to a THEN, check whether it is within the current + branch by comparing the address of the THEN that is passed back with + the end of the branch. If it is within the current branch, and the + branch is one of two or more alternatives (it either starts or ends + with OP_ALT), we have reached the limit of THEN's action, so convert + the return code to NOMATCH, which will cause normal backtracking to + happen from now on. Otherwise, THEN is passed back to an outer + alternative. This implements Perl's treatment of parenthesized groups, + where a group not containing | does not affect the current alternative, + that is, (X) is NOT the same as (X|(*F)). */ + + if (rrc == MATCH_THEN) + { + next = ecode + GET(ecode,1); + if (md->start_match_ptr < next && + (*ecode == OP_ALT || *next == OP_ALT)) + rrc = MATCH_NOMATCH; + } + + /* Anything other than NOMATCH is passed back. */ + + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + md->capture_last = save_capture_last; + ecode += GET(ecode, 1); + md->mark = save_mark; + if (*ecode != OP_ALT) break; + } + + DPRINTF(("bracket %d failed\n", number)); + md->offset_vector[offset] = save_offset1; + md->offset_vector[offset+1] = save_offset2; + md->offset_vector[md->offset_end - number] = save_offset3; + + /* At this point, rrc will be one of MATCH_ONCE or MATCH_NOMATCH. */ + + RRETURN(rrc); + } + + /* FALL THROUGH ... Insufficient room for saving captured contents. Treat + as a non-capturing bracket. */ + + /* VVVVVVVVVVVVVVVVVVVVVVVVV */ + /* VVVVVVVVVVVVVVVVVVVVVVVVV */ + + DPRINTF(("insufficient capture room: treat as non-capturing\n")); + + /* VVVVVVVVVVVVVVVVVVVVVVVVV */ + /* VVVVVVVVVVVVVVVVVVVVVVVVV */ + + /* Non-capturing or atomic group, except for possessive with unlimited + repeat and ONCE group with no captures. Loop for all the alternatives. + + When we get to the final alternative within the brackets, we used to return + the result of a recursive call to match() whatever happened so it was + possible to reduce stack usage by turning this into a tail recursion, + except in the case of a possibly empty group. However, now that there is + the possiblity of (*THEN) occurring in the final alternative, this + optimization is no longer always possible. + + We can optimize if we know there are no (*THEN)s in the pattern; at present + this is the best that can be done. + + MATCH_ONCE is returned when the end of an atomic group is successfully + reached, but subsequent matching fails. It passes back up the tree (causing + captured values to be reset) until the original atomic group level is + reached. This is tested by comparing md->once_target with the start of the + group. At this point, the return is converted into MATCH_NOMATCH so that + previous backup points can be taken. */ + + case OP_ONCE: + case OP_BRA: + case OP_SBRA: + DPRINTF(("start non-capturing bracket\n")); + + for (;;) + { + if (op >= OP_SBRA || op == OP_ONCE) + md->match_function_type = MATCH_CBEGROUP; + + /* If this is not a possibly empty group, and there are no (*THEN)s in + the pattern, and this is the final alternative, optimize as described + above. */ + + else if (!md->hasthen && ecode[GET(ecode, 1)] != OP_ALT) + { + ecode += PRIV(OP_lengths)[*ecode]; + goto TAIL_RECURSE; + } + + /* In all other cases, we have to make another call to match(). */ + + save_mark = md->mark; + save_capture_last = md->capture_last; + RMATCH(eptr, ecode + PRIV(OP_lengths)[*ecode], offset_top, md, eptrb, + RM2); + + /* See comment in the code for capturing groups above about handling + THEN. */ + + if (rrc == MATCH_THEN) + { + next = ecode + GET(ecode,1); + if (md->start_match_ptr < next && + (*ecode == OP_ALT || *next == OP_ALT)) + rrc = MATCH_NOMATCH; + } + + if (rrc != MATCH_NOMATCH) + { + if (rrc == MATCH_ONCE) + { + const pcre_uchar *scode = ecode; + if (*scode != OP_ONCE) /* If not at start, find it */ + { + while (*scode == OP_ALT) scode += GET(scode, 1); + scode -= GET(scode, 1); + } + if (md->once_target == scode) rrc = MATCH_NOMATCH; + } + RRETURN(rrc); + } + ecode += GET(ecode, 1); + md->mark = save_mark; + if (*ecode != OP_ALT) break; + md->capture_last = save_capture_last; + } + + RRETURN(MATCH_NOMATCH); + + /* Handle possessive capturing brackets with an unlimited repeat. We come + here from BRAZERO with allow_zero set TRUE. The offset_vector values are + handled similarly to the normal case above. However, the matching is + different. The end of these brackets will always be OP_KETRPOS, which + returns MATCH_KETRPOS without going further in the pattern. By this means + we can handle the group by iteration rather than recursion, thereby + reducing the amount of stack needed. */ + + case OP_CBRAPOS: + case OP_SCBRAPOS: + allow_zero = FALSE; + + POSSESSIVE_CAPTURE: + number = GET2(ecode, 1+LINK_SIZE); + offset = number << 1; + +#ifdef PCRE_DEBUG + printf("start possessive bracket %d\n", number); + printf("subject="); + pchars(eptr, 16, TRUE, md); + printf("\n"); +#endif + + if (offset < md->offset_max) + { + matched_once = FALSE; + code_offset = (int)(ecode - md->start_code); + + save_offset1 = md->offset_vector[offset]; + save_offset2 = md->offset_vector[offset+1]; + save_offset3 = md->offset_vector[md->offset_end - number]; + save_capture_last = md->capture_last; + + DPRINTF(("saving %d %d %d\n", save_offset1, save_offset2, save_offset3)); + + /* Each time round the loop, save the current subject position for use + when the group matches. For MATCH_MATCH, the group has matched, so we + restart it with a new subject starting position, remembering that we had + at least one match. For MATCH_NOMATCH, carry on with the alternatives, as + usual. If we haven't matched any alternatives in any iteration, check to + see if a previous iteration matched. If so, the group has matched; + continue from afterwards. Otherwise it has failed; restore the previous + capture values before returning NOMATCH. */ + + for (;;) + { + md->offset_vector[md->offset_end - number] = + (int)(eptr - md->start_subject); + if (op >= OP_SBRA) md->match_function_type = MATCH_CBEGROUP; + RMATCH(eptr, ecode + PRIV(OP_lengths)[*ecode], offset_top, md, + eptrb, RM63); + if (rrc == MATCH_KETRPOS) + { + offset_top = md->end_offset_top; + ecode = md->start_code + code_offset; + save_capture_last = md->capture_last; + matched_once = TRUE; + mstart = md->start_match_ptr; /* In case \K changed it */ + if (eptr == md->end_match_ptr) /* Matched an empty string */ + { + do ecode += GET(ecode, 1); while (*ecode == OP_ALT); + break; + } + eptr = md->end_match_ptr; + continue; + } + + /* See comment in the code for capturing groups above about handling + THEN. */ + + if (rrc == MATCH_THEN) + { + next = ecode + GET(ecode,1); + if (md->start_match_ptr < next && + (*ecode == OP_ALT || *next == OP_ALT)) + rrc = MATCH_NOMATCH; + } + + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + md->capture_last = save_capture_last; + ecode += GET(ecode, 1); + if (*ecode != OP_ALT) break; + } + + if (!matched_once) + { + md->offset_vector[offset] = save_offset1; + md->offset_vector[offset+1] = save_offset2; + md->offset_vector[md->offset_end - number] = save_offset3; + } + + if (allow_zero || matched_once) + { + ecode += 1 + LINK_SIZE; + break; + } + + RRETURN(MATCH_NOMATCH); + } + + /* FALL THROUGH ... Insufficient room for saving captured contents. Treat + as a non-capturing bracket. */ + + /* VVVVVVVVVVVVVVVVVVVVVVVVV */ + /* VVVVVVVVVVVVVVVVVVVVVVVVV */ + + DPRINTF(("insufficient capture room: treat as non-capturing\n")); + + /* VVVVVVVVVVVVVVVVVVVVVVVVV */ + /* VVVVVVVVVVVVVVVVVVVVVVVVV */ + + /* Non-capturing possessive bracket with unlimited repeat. We come here + from BRAZERO with allow_zero = TRUE. The code is similar to the above, + without the capturing complication. It is written out separately for speed + and cleanliness. */ + + case OP_BRAPOS: + case OP_SBRAPOS: + allow_zero = FALSE; + + POSSESSIVE_NON_CAPTURE: + matched_once = FALSE; + code_offset = (int)(ecode - md->start_code); + save_capture_last = md->capture_last; + + for (;;) + { + if (op >= OP_SBRA) md->match_function_type = MATCH_CBEGROUP; + RMATCH(eptr, ecode + PRIV(OP_lengths)[*ecode], offset_top, md, + eptrb, RM48); + if (rrc == MATCH_KETRPOS) + { + offset_top = md->end_offset_top; + ecode = md->start_code + code_offset; + matched_once = TRUE; + mstart = md->start_match_ptr; /* In case \K reset it */ + if (eptr == md->end_match_ptr) /* Matched an empty string */ + { + do ecode += GET(ecode, 1); while (*ecode == OP_ALT); + break; + } + eptr = md->end_match_ptr; + continue; + } + + /* See comment in the code for capturing groups above about handling + THEN. */ + + if (rrc == MATCH_THEN) + { + next = ecode + GET(ecode,1); + if (md->start_match_ptr < next && + (*ecode == OP_ALT || *next == OP_ALT)) + rrc = MATCH_NOMATCH; + } + + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + ecode += GET(ecode, 1); + if (*ecode != OP_ALT) break; + md->capture_last = save_capture_last; + } + + if (matched_once || allow_zero) + { + ecode += 1 + LINK_SIZE; + break; + } + RRETURN(MATCH_NOMATCH); + + /* Control never reaches here. */ + + /* Conditional group: compilation checked that there are no more than two + branches. If the condition is false, skipping the first branch takes us + past the end of the item if there is only one branch, but that's exactly + what we want. */ + + case OP_COND: + case OP_SCOND: + + /* The variable codelink will be added to ecode when the condition is + false, to get to the second branch. Setting it to the offset to the ALT + or KET, then incrementing ecode achieves this effect. We now have ecode + pointing to the condition or callout. */ + + codelink = GET(ecode, 1); /* Offset to the second branch */ + ecode += 1 + LINK_SIZE; /* From this opcode */ + + /* Because of the way auto-callout works during compile, a callout item is + inserted between OP_COND and an assertion condition. */ + + if (*ecode == OP_CALLOUT) + { + if (PUBL(callout) != NULL) + { + PUBL(callout_block) cb; + cb.version = 2; /* Version 1 of the callout block */ + cb.callout_number = ecode[1]; + cb.offset_vector = md->offset_vector; +#if defined COMPILE_PCRE8 + cb.subject = (PCRE_SPTR)md->start_subject; +#elif defined COMPILE_PCRE16 + cb.subject = (PCRE_SPTR16)md->start_subject; +#elif defined COMPILE_PCRE32 + cb.subject = (PCRE_SPTR32)md->start_subject; +#endif + cb.subject_length = (int)(md->end_subject - md->start_subject); + cb.start_match = (int)(mstart - md->start_subject); + cb.current_position = (int)(eptr - md->start_subject); + cb.pattern_position = GET(ecode, 2); + cb.next_item_length = GET(ecode, 2 + LINK_SIZE); + cb.capture_top = offset_top/2; + cb.capture_last = md->capture_last & CAPLMASK; + /* Internal change requires this for API compatibility. */ + if (cb.capture_last == 0) cb.capture_last = -1; + cb.callout_data = md->callout_data; + cb.mark = md->nomatch_mark; + if ((rrc = (*PUBL(callout))(&cb)) > 0) RRETURN(MATCH_NOMATCH); + if (rrc < 0) RRETURN(rrc); + } + + /* Advance ecode past the callout, so it now points to the condition. We + must adjust codelink so that the value of ecode+codelink is unchanged. */ + + ecode += PRIV(OP_lengths)[OP_CALLOUT]; + codelink -= PRIV(OP_lengths)[OP_CALLOUT]; + } + + /* Test the various possible conditions */ + + condition = FALSE; + switch(condcode = *ecode) + { + case OP_RREF: /* Numbered group recursion test */ + if (md->recursive != NULL) /* Not recursing => FALSE */ + { + unsigned int recno = GET2(ecode, 1); /* Recursion group number*/ + condition = (recno == RREF_ANY || recno == md->recursive->group_num); + } + break; + + case OP_DNRREF: /* Duplicate named group recursion test */ + if (md->recursive != NULL) + { + int count = GET2(ecode, 1 + IMM2_SIZE); + pcre_uchar *slot = md->name_table + GET2(ecode, 1) * md->name_entry_size; + while (count-- > 0) + { + unsigned int recno = GET2(slot, 0); + condition = recno == md->recursive->group_num; + if (condition) break; + slot += md->name_entry_size; + } + } + break; + + case OP_CREF: /* Numbered group used test */ + offset = GET2(ecode, 1) << 1; /* Doubled ref number */ + condition = offset < offset_top && md->offset_vector[offset] >= 0; + break; + + case OP_DNCREF: /* Duplicate named group used test */ + { + int count = GET2(ecode, 1 + IMM2_SIZE); + pcre_uchar *slot = md->name_table + GET2(ecode, 1) * md->name_entry_size; + while (count-- > 0) + { + offset = GET2(slot, 0) << 1; + condition = offset < offset_top && md->offset_vector[offset] >= 0; + if (condition) break; + slot += md->name_entry_size; + } + } + break; + + case OP_DEF: /* DEFINE - always false */ + break; + + /* The condition is an assertion. Call match() to evaluate it - setting + md->match_function_type to MATCH_CONDASSERT causes it to stop at the end + of an assertion. */ + + default: + md->match_function_type = MATCH_CONDASSERT; + RMATCH(eptr, ecode, offset_top, md, NULL, RM3); + if (rrc == MATCH_MATCH) + { + if (md->end_offset_top > offset_top) + offset_top = md->end_offset_top; /* Captures may have happened */ + condition = TRUE; + + /* Advance ecode past the assertion to the start of the first branch, + but adjust it so that the general choosing code below works. */ + + ecode += GET(ecode, 1); + while (*ecode == OP_ALT) ecode += GET(ecode, 1); + ecode += 1 + LINK_SIZE - PRIV(OP_lengths)[condcode]; + } + + /* PCRE doesn't allow the effect of (*THEN) to escape beyond an + assertion; it is therefore treated as NOMATCH. Any other return is an + error. */ + + else if (rrc != MATCH_NOMATCH && rrc != MATCH_THEN) + { + RRETURN(rrc); /* Need braces because of following else */ + } + break; + } + + /* Choose branch according to the condition */ + + ecode += condition? PRIV(OP_lengths)[condcode] : codelink; + + /* We are now at the branch that is to be obeyed. As there is only one, we + can use tail recursion to avoid using another stack frame, except when + there is unlimited repeat of a possibly empty group. In the latter case, a + recursive call to match() is always required, unless the second alternative + doesn't exist, in which case we can just plough on. Note that, for + compatibility with Perl, the | in a conditional group is NOT treated as + creating two alternatives. If a THEN is encountered in the branch, it + propagates out to the enclosing alternative (unless nested in a deeper set + of alternatives, of course). */ + + if (condition || ecode[-(1+LINK_SIZE)] == OP_ALT) + { + if (op != OP_SCOND) + { + goto TAIL_RECURSE; + } + + md->match_function_type = MATCH_CBEGROUP; + RMATCH(eptr, ecode, offset_top, md, eptrb, RM49); + RRETURN(rrc); + } + + /* Condition false & no alternative; continue after the group. */ + + else + { + } + break; + + + /* Before OP_ACCEPT there may be any number of OP_CLOSE opcodes, + to close any currently open capturing brackets. */ + + case OP_CLOSE: + number = GET2(ecode, 1); /* Must be less than 65536 */ + offset = number << 1; + +#ifdef PCRE_DEBUG + printf("end bracket %d at *ACCEPT", number); + printf("\n"); +#endif + + md->capture_last = (md->capture_last & OVFLMASK) | number; + if (offset >= md->offset_max) md->capture_last |= OVFLBIT; else + { + md->offset_vector[offset] = + md->offset_vector[md->offset_end - number]; + md->offset_vector[offset+1] = (int)(eptr - md->start_subject); + if (offset_top <= offset) offset_top = offset + 2; + } + ecode += 1 + IMM2_SIZE; + break; + + + /* End of the pattern, either real or forced. */ + + case OP_END: + case OP_ACCEPT: + case OP_ASSERT_ACCEPT: + + /* If we have matched an empty string, fail if not in an assertion and not + in a recursion if either PCRE_NOTEMPTY is set, or if PCRE_NOTEMPTY_ATSTART + is set and we have matched at the start of the subject. In both cases, + backtracking will then try other alternatives, if any. */ + + if (eptr == mstart && op != OP_ASSERT_ACCEPT && + md->recursive == NULL && + (md->notempty || + (md->notempty_atstart && + mstart == md->start_subject + md->start_offset))) + RRETURN(MATCH_NOMATCH); + + /* Otherwise, we have a match. */ + + md->end_match_ptr = eptr; /* Record where we ended */ + md->end_offset_top = offset_top; /* and how many extracts were taken */ + md->start_match_ptr = mstart; /* and the start (\K can modify) */ + + /* For some reason, the macros don't work properly if an expression is + given as the argument to RRETURN when the heap is in use. */ + + rrc = (op == OP_END)? MATCH_MATCH : MATCH_ACCEPT; + RRETURN(rrc); + + /* Assertion brackets. Check the alternative branches in turn - the + matching won't pass the KET for an assertion. If any one branch matches, + the assertion is true. Lookbehind assertions have an OP_REVERSE item at the + start of each branch to move the current point backwards, so the code at + this level is identical to the lookahead case. When the assertion is part + of a condition, we want to return immediately afterwards. The caller of + this incarnation of the match() function will have set MATCH_CONDASSERT in + md->match_function type, and one of these opcodes will be the first opcode + that is processed. We use a local variable that is preserved over calls to + match() to remember this case. */ + + case OP_ASSERT: + case OP_ASSERTBACK: + save_mark = md->mark; + if (md->match_function_type == MATCH_CONDASSERT) + { + condassert = TRUE; + md->match_function_type = 0; + } + else condassert = FALSE; + + /* Loop for each branch */ + + do + { + RMATCH(eptr, ecode + 1 + LINK_SIZE, offset_top, md, NULL, RM4); + + /* A match means that the assertion is true; break out of the loop + that matches its alternatives. */ + + if (rrc == MATCH_MATCH || rrc == MATCH_ACCEPT) + { + mstart = md->start_match_ptr; /* In case \K reset it */ + break; + } + + /* If not matched, restore the previous mark setting. */ + + md->mark = save_mark; + + /* See comment in the code for capturing groups above about handling + THEN. */ + + if (rrc == MATCH_THEN) + { + next = ecode + GET(ecode,1); + if (md->start_match_ptr < next && + (*ecode == OP_ALT || *next == OP_ALT)) + rrc = MATCH_NOMATCH; + } + + /* Anything other than NOMATCH causes the entire assertion to fail, + passing back the return code. This includes COMMIT, SKIP, PRUNE and an + uncaptured THEN, which means they take their normal effect. This + consistent approach does not always have exactly the same effect as in + Perl. */ + + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + ecode += GET(ecode, 1); + } + while (*ecode == OP_ALT); /* Continue for next alternative */ + + /* If we have tried all the alternative branches, the assertion has + failed. If not, we broke out after a match. */ + + if (*ecode == OP_KET) RRETURN(MATCH_NOMATCH); + + /* If checking an assertion for a condition, return MATCH_MATCH. */ + + if (condassert) RRETURN(MATCH_MATCH); + + /* Continue from after a successful assertion, updating the offsets high + water mark, since extracts may have been taken during the assertion. */ + + do ecode += GET(ecode,1); while (*ecode == OP_ALT); + ecode += 1 + LINK_SIZE; + offset_top = md->end_offset_top; + continue; + + /* Negative assertion: all branches must fail to match for the assertion to + succeed. */ + + case OP_ASSERT_NOT: + case OP_ASSERTBACK_NOT: + save_mark = md->mark; + if (md->match_function_type == MATCH_CONDASSERT) + { + condassert = TRUE; + md->match_function_type = 0; + } + else condassert = FALSE; + + /* Loop for each alternative branch. */ + + do + { + RMATCH(eptr, ecode + 1 + LINK_SIZE, offset_top, md, NULL, RM5); + md->mark = save_mark; /* Always restore the mark setting */ + + switch(rrc) + { + case MATCH_MATCH: /* A successful match means */ + case MATCH_ACCEPT: /* the assertion has failed. */ + RRETURN(MATCH_NOMATCH); + + case MATCH_NOMATCH: /* Carry on with next branch */ + break; + + /* See comment in the code for capturing groups above about handling + THEN. */ + + case MATCH_THEN: + next = ecode + GET(ecode,1); + if (md->start_match_ptr < next && + (*ecode == OP_ALT || *next == OP_ALT)) + { + rrc = MATCH_NOMATCH; + break; + } + /* Otherwise fall through. */ + + /* COMMIT, SKIP, PRUNE, and an uncaptured THEN cause the whole + assertion to fail to match, without considering any more alternatives. + Failing to match means the assertion is true. This is a consistent + approach, but does not always have the same effect as in Perl. */ + + case MATCH_COMMIT: + case MATCH_SKIP: + case MATCH_SKIP_ARG: + case MATCH_PRUNE: + do ecode += GET(ecode,1); while (*ecode == OP_ALT); + goto NEG_ASSERT_TRUE; /* Break out of alternation loop */ + + /* Anything else is an error */ + + default: + RRETURN(rrc); + } + + /* Continue with next branch */ + + ecode += GET(ecode,1); + } + while (*ecode == OP_ALT); + + /* All branches in the assertion failed to match. */ + + NEG_ASSERT_TRUE: + if (condassert) RRETURN(MATCH_MATCH); /* Condition assertion */ + ecode += 1 + LINK_SIZE; /* Continue with current branch */ + continue; + + /* Move the subject pointer back. This occurs only at the start of + each branch of a lookbehind assertion. If we are too close to the start to + move back, this match function fails. When working with UTF-8 we move + back a number of characters, not bytes. */ + + case OP_REVERSE: +#ifdef SUPPORT_UTF + if (utf) + { + i = GET(ecode, 1); + while (i-- > 0) + { + eptr--; + if (eptr < md->start_subject) RRETURN(MATCH_NOMATCH); + BACKCHAR(eptr); + } + } + else +#endif + + /* No UTF-8 support, or not in UTF-8 mode: count is byte count */ + + { + eptr -= GET(ecode, 1); + if (eptr < md->start_subject) RRETURN(MATCH_NOMATCH); + } + + /* Save the earliest consulted character, then skip to next op code */ + + if (eptr < md->start_used_ptr) md->start_used_ptr = eptr; + ecode += 1 + LINK_SIZE; + break; + + /* The callout item calls an external function, if one is provided, passing + details of the match so far. This is mainly for debugging, though the + function is able to force a failure. */ + + case OP_CALLOUT: + if (PUBL(callout) != NULL) + { + PUBL(callout_block) cb; + cb.version = 2; /* Version 1 of the callout block */ + cb.callout_number = ecode[1]; + cb.offset_vector = md->offset_vector; +#if defined COMPILE_PCRE8 + cb.subject = (PCRE_SPTR)md->start_subject; +#elif defined COMPILE_PCRE16 + cb.subject = (PCRE_SPTR16)md->start_subject; +#elif defined COMPILE_PCRE32 + cb.subject = (PCRE_SPTR32)md->start_subject; +#endif + cb.subject_length = (int)(md->end_subject - md->start_subject); + cb.start_match = (int)(mstart - md->start_subject); + cb.current_position = (int)(eptr - md->start_subject); + cb.pattern_position = GET(ecode, 2); + cb.next_item_length = GET(ecode, 2 + LINK_SIZE); + cb.capture_top = offset_top/2; + cb.capture_last = md->capture_last & CAPLMASK; + /* Internal change requires this for API compatibility. */ + if (cb.capture_last == 0) cb.capture_last = -1; + cb.callout_data = md->callout_data; + cb.mark = md->nomatch_mark; + if ((rrc = (*PUBL(callout))(&cb)) > 0) RRETURN(MATCH_NOMATCH); + if (rrc < 0) RRETURN(rrc); + } + ecode += 2 + 2*LINK_SIZE; + break; + + /* Recursion either matches the current regex, or some subexpression. The + offset data is the offset to the starting bracket from the start of the + whole pattern. (This is so that it works from duplicated subpatterns.) + + The state of the capturing groups is preserved over recursion, and + re-instated afterwards. We don't know how many are started and not yet + finished (offset_top records the completed total) so we just have to save + all the potential data. There may be up to 65535 such values, which is too + large to put on the stack, but using malloc for small numbers seems + expensive. As a compromise, the stack is used when there are no more than + REC_STACK_SAVE_MAX values to store; otherwise malloc is used. + + There are also other values that have to be saved. We use a chained + sequence of blocks that actually live on the stack. Thanks to Robin Houston + for the original version of this logic. It has, however, been hacked around + a lot, so he is not to blame for the current way it works. */ + + case OP_RECURSE: + { + recursion_info *ri; + unsigned int recno; + + callpat = md->start_code + GET(ecode, 1); + recno = (callpat == md->start_code)? 0 : + GET2(callpat, 1 + LINK_SIZE); + + /* Check for repeating a recursion without advancing the subject pointer. + This should catch convoluted mutual recursions. (Some simple cases are + caught at compile time.) */ + + for (ri = md->recursive; ri != NULL; ri = ri->prevrec) + if (recno == ri->group_num && eptr == ri->subject_position) + RRETURN(PCRE_ERROR_RECURSELOOP); + + /* Add to "recursing stack" */ + + new_recursive.group_num = recno; + new_recursive.saved_capture_last = md->capture_last; + new_recursive.subject_position = eptr; + new_recursive.prevrec = md->recursive; + md->recursive = &new_recursive; + + /* Where to continue from afterwards */ + + ecode += 1 + LINK_SIZE; + + /* Now save the offset data */ + + new_recursive.saved_max = md->offset_end; + if (new_recursive.saved_max <= REC_STACK_SAVE_MAX) + new_recursive.offset_save = stacksave; + else + { + new_recursive.offset_save = + (int *)(PUBL(malloc))(new_recursive.saved_max * sizeof(int)); + if (new_recursive.offset_save == NULL) RRETURN(PCRE_ERROR_NOMEMORY); + } + memcpy(new_recursive.offset_save, md->offset_vector, + new_recursive.saved_max * sizeof(int)); + + /* OK, now we can do the recursion. After processing each alternative, + restore the offset data and the last captured value. If there were nested + recursions, md->recursive might be changed, so reset it before looping. + */ + + DPRINTF(("Recursing into group %d\n", new_recursive.group_num)); + cbegroup = (*callpat >= OP_SBRA); + do + { + if (cbegroup) md->match_function_type = MATCH_CBEGROUP; + RMATCH(eptr, callpat + PRIV(OP_lengths)[*callpat], offset_top, + md, eptrb, RM6); + memcpy(md->offset_vector, new_recursive.offset_save, + new_recursive.saved_max * sizeof(int)); + md->capture_last = new_recursive.saved_capture_last; + md->recursive = new_recursive.prevrec; + if (rrc == MATCH_MATCH || rrc == MATCH_ACCEPT) + { + DPRINTF(("Recursion matched\n")); + if (new_recursive.offset_save != stacksave) + (PUBL(free))(new_recursive.offset_save); + + /* Set where we got to in the subject, and reset the start in case + it was changed by \K. This *is* propagated back out of a recursion, + for Perl compatibility. */ + + eptr = md->end_match_ptr; + mstart = md->start_match_ptr; + goto RECURSION_MATCHED; /* Exit loop; end processing */ + } + + /* PCRE does not allow THEN, SKIP, PRUNE or COMMIT to escape beyond a + recursion; they cause a NOMATCH for the entire recursion. These codes + are defined in a range that can be tested for. */ + + if (rrc >= MATCH_BACKTRACK_MIN && rrc <= MATCH_BACKTRACK_MAX) + RRETURN(MATCH_NOMATCH); + + /* Any return code other than NOMATCH is an error. */ + + if (rrc != MATCH_NOMATCH) + { + DPRINTF(("Recursion gave error %d\n", rrc)); + if (new_recursive.offset_save != stacksave) + (PUBL(free))(new_recursive.offset_save); + RRETURN(rrc); + } + + md->recursive = &new_recursive; + callpat += GET(callpat, 1); + } + while (*callpat == OP_ALT); + + DPRINTF(("Recursion didn't match\n")); + md->recursive = new_recursive.prevrec; + if (new_recursive.offset_save != stacksave) + (PUBL(free))(new_recursive.offset_save); + RRETURN(MATCH_NOMATCH); + } + + RECURSION_MATCHED: + break; + + /* An alternation is the end of a branch; scan along to find the end of the + bracketed group and go to there. */ + + case OP_ALT: + do ecode += GET(ecode,1); while (*ecode == OP_ALT); + break; + + /* BRAZERO, BRAMINZERO and SKIPZERO occur just before a bracket group, + indicating that it may occur zero times. It may repeat infinitely, or not + at all - i.e. it could be ()* or ()? or even (){0} in the pattern. Brackets + with fixed upper repeat limits are compiled as a number of copies, with the + optional ones preceded by BRAZERO or BRAMINZERO. */ + + case OP_BRAZERO: + next = ecode + 1; + RMATCH(eptr, next, offset_top, md, eptrb, RM10); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + do next += GET(next, 1); while (*next == OP_ALT); + ecode = next + 1 + LINK_SIZE; + break; + + case OP_BRAMINZERO: + next = ecode + 1; + do next += GET(next, 1); while (*next == OP_ALT); + RMATCH(eptr, next + 1+LINK_SIZE, offset_top, md, eptrb, RM11); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + ecode++; + break; + + case OP_SKIPZERO: + next = ecode+1; + do next += GET(next,1); while (*next == OP_ALT); + ecode = next + 1 + LINK_SIZE; + break; + + /* BRAPOSZERO occurs before a possessive bracket group. Don't do anything + here; just jump to the group, with allow_zero set TRUE. */ + + case OP_BRAPOSZERO: + op = *(++ecode); + allow_zero = TRUE; + if (op == OP_CBRAPOS || op == OP_SCBRAPOS) goto POSSESSIVE_CAPTURE; + goto POSSESSIVE_NON_CAPTURE; + + /* End of a group, repeated or non-repeating. */ + + case OP_KET: + case OP_KETRMIN: + case OP_KETRMAX: + case OP_KETRPOS: + prev = ecode - GET(ecode, 1); + + /* If this was a group that remembered the subject start, in order to break + infinite repeats of empty string matches, retrieve the subject start from + the chain. Otherwise, set it NULL. */ + + if (*prev >= OP_SBRA || *prev == OP_ONCE) + { + saved_eptr = eptrb->epb_saved_eptr; /* Value at start of group */ + eptrb = eptrb->epb_prev; /* Backup to previous group */ + } + else saved_eptr = NULL; + + /* If we are at the end of an assertion group or a non-capturing atomic + group, stop matching and return MATCH_MATCH, but record the current high + water mark for use by positive assertions. We also need to record the match + start in case it was changed by \K. */ + + if ((*prev >= OP_ASSERT && *prev <= OP_ASSERTBACK_NOT) || + *prev == OP_ONCE_NC) + { + md->end_match_ptr = eptr; /* For ONCE_NC */ + md->end_offset_top = offset_top; + md->start_match_ptr = mstart; + RRETURN(MATCH_MATCH); /* Sets md->mark */ + } + + /* For capturing groups we have to check the group number back at the start + and if necessary complete handling an extraction by setting the offsets and + bumping the high water mark. Whole-pattern recursion is coded as a recurse + into group 0, so it won't be picked up here. Instead, we catch it when the + OP_END is reached. Other recursion is handled here. We just have to record + the current subject position and start match pointer and give a MATCH + return. */ + + if (*prev == OP_CBRA || *prev == OP_SCBRA || + *prev == OP_CBRAPOS || *prev == OP_SCBRAPOS) + { + number = GET2(prev, 1+LINK_SIZE); + offset = number << 1; + +#ifdef PCRE_DEBUG + printf("end bracket %d", number); + printf("\n"); +#endif + + /* Handle a recursively called group. */ + + if (md->recursive != NULL && md->recursive->group_num == number) + { + md->end_match_ptr = eptr; + md->start_match_ptr = mstart; + RRETURN(MATCH_MATCH); + } + + /* Deal with capturing */ + + md->capture_last = (md->capture_last & OVFLMASK) | number; + if (offset >= md->offset_max) md->capture_last |= OVFLBIT; else + { + /* If offset is greater than offset_top, it means that we are + "skipping" a capturing group, and that group's offsets must be marked + unset. In earlier versions of PCRE, all the offsets were unset at the + start of matching, but this doesn't work because atomic groups and + assertions can cause a value to be set that should later be unset. + Example: matching /(?>(a))b|(a)c/ against "ac". This sets group 1 as + part of the atomic group, but this is not on the final matching path, + so must be unset when 2 is set. (If there is no group 2, there is no + problem, because offset_top will then be 2, indicating no capture.) */ + + if (offset > offset_top) + { + register int *iptr = md->offset_vector + offset_top; + register int *iend = md->offset_vector + offset; + while (iptr < iend) *iptr++ = -1; + } + + /* Now make the extraction */ + + md->offset_vector[offset] = + md->offset_vector[md->offset_end - number]; + md->offset_vector[offset+1] = (int)(eptr - md->start_subject); + if (offset_top <= offset) offset_top = offset + 2; + } + } + + /* OP_KETRPOS is a possessive repeating ket. Remember the current position, + and return the MATCH_KETRPOS. This makes it possible to do the repeats one + at a time from the outer level, thus saving stack. This must precede the + empty string test - in this case that test is done at the outer level. */ + + if (*ecode == OP_KETRPOS) + { + md->start_match_ptr = mstart; /* In case \K reset it */ + md->end_match_ptr = eptr; + md->end_offset_top = offset_top; + RRETURN(MATCH_KETRPOS); + } + + /* For an ordinary non-repeating ket, just continue at this level. This + also happens for a repeating ket if no characters were matched in the + group. This is the forcible breaking of infinite loops as implemented in + Perl 5.005. For a non-repeating atomic group that includes captures, + establish a backup point by processing the rest of the pattern at a lower + level. If this results in a NOMATCH return, pass MATCH_ONCE back to the + original OP_ONCE level, thereby bypassing intermediate backup points, but + resetting any captures that happened along the way. */ + + if (*ecode == OP_KET || eptr == saved_eptr) + { + if (*prev == OP_ONCE) + { + RMATCH(eptr, ecode + 1 + LINK_SIZE, offset_top, md, eptrb, RM12); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + md->once_target = prev; /* Level at which to change to MATCH_NOMATCH */ + RRETURN(MATCH_ONCE); + } + ecode += 1 + LINK_SIZE; /* Carry on at this level */ + break; + } + + /* The normal repeating kets try the rest of the pattern or restart from + the preceding bracket, in the appropriate order. In the second case, we can + use tail recursion to avoid using another stack frame, unless we have an + an atomic group or an unlimited repeat of a group that can match an empty + string. */ + + if (*ecode == OP_KETRMIN) + { + RMATCH(eptr, ecode + 1 + LINK_SIZE, offset_top, md, eptrb, RM7); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (*prev == OP_ONCE) + { + RMATCH(eptr, prev, offset_top, md, eptrb, RM8); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + md->once_target = prev; /* Level at which to change to MATCH_NOMATCH */ + RRETURN(MATCH_ONCE); + } + if (*prev >= OP_SBRA) /* Could match an empty string */ + { + RMATCH(eptr, prev, offset_top, md, eptrb, RM50); + RRETURN(rrc); + } + ecode = prev; + goto TAIL_RECURSE; + } + else /* OP_KETRMAX */ + { + RMATCH(eptr, prev, offset_top, md, eptrb, RM13); + if (rrc == MATCH_ONCE && md->once_target == prev) rrc = MATCH_NOMATCH; + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (*prev == OP_ONCE) + { + RMATCH(eptr, ecode + 1 + LINK_SIZE, offset_top, md, eptrb, RM9); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + md->once_target = prev; + RRETURN(MATCH_ONCE); + } + ecode += 1 + LINK_SIZE; + goto TAIL_RECURSE; + } + /* Control never gets here */ + + /* Not multiline mode: start of subject assertion, unless notbol. */ + + case OP_CIRC: + if (md->notbol && eptr == md->start_subject) RRETURN(MATCH_NOMATCH); + + /* Start of subject assertion */ + + case OP_SOD: + if (eptr != md->start_subject) RRETURN(MATCH_NOMATCH); + ecode++; + break; + + /* Multiline mode: start of subject unless notbol, or after any newline. */ + + case OP_CIRCM: + if (md->notbol && eptr == md->start_subject) RRETURN(MATCH_NOMATCH); + if (eptr != md->start_subject && + (eptr == md->end_subject || !WAS_NEWLINE(eptr))) + RRETURN(MATCH_NOMATCH); + ecode++; + break; + + /* Start of match assertion */ + + case OP_SOM: + if (eptr != md->start_subject + md->start_offset) RRETURN(MATCH_NOMATCH); + ecode++; + break; + + /* Reset the start of match point */ + + case OP_SET_SOM: + mstart = eptr; + ecode++; + break; + + /* Multiline mode: assert before any newline, or before end of subject + unless noteol is set. */ + + case OP_DOLLM: + if (eptr < md->end_subject) + { + if (!IS_NEWLINE(eptr)) + { + if (md->partial != 0 && + eptr + 1 >= md->end_subject && + NLBLOCK->nltype == NLTYPE_FIXED && + NLBLOCK->nllen == 2 && + UCHAR21TEST(eptr) == NLBLOCK->nl[0]) + { + md->hitend = TRUE; + if (md->partial > 1) RRETURN(PCRE_ERROR_PARTIAL); + } + RRETURN(MATCH_NOMATCH); + } + } + else + { + if (md->noteol) RRETURN(MATCH_NOMATCH); + SCHECK_PARTIAL(); + } + ecode++; + break; + + /* Not multiline mode: assert before a terminating newline or before end of + subject unless noteol is set. */ + + case OP_DOLL: + if (md->noteol) RRETURN(MATCH_NOMATCH); + if (!md->endonly) goto ASSERT_NL_OR_EOS; + + /* ... else fall through for endonly */ + + /* End of subject assertion (\z) */ + + case OP_EOD: + if (eptr < md->end_subject) RRETURN(MATCH_NOMATCH); + SCHECK_PARTIAL(); + ecode++; + break; + + /* End of subject or ending \n assertion (\Z) */ + + case OP_EODN: + ASSERT_NL_OR_EOS: + if (eptr < md->end_subject && + (!IS_NEWLINE(eptr) || eptr != md->end_subject - md->nllen)) + { + if (md->partial != 0 && + eptr + 1 >= md->end_subject && + NLBLOCK->nltype == NLTYPE_FIXED && + NLBLOCK->nllen == 2 && + UCHAR21TEST(eptr) == NLBLOCK->nl[0]) + { + md->hitend = TRUE; + if (md->partial > 1) RRETURN(PCRE_ERROR_PARTIAL); + } + RRETURN(MATCH_NOMATCH); + } + + /* Either at end of string or \n before end. */ + + SCHECK_PARTIAL(); + ecode++; + break; + + /* Word boundary assertions */ + + case OP_NOT_WORD_BOUNDARY: + case OP_WORD_BOUNDARY: + { + + /* Find out if the previous and current characters are "word" characters. + It takes a bit more work in UTF-8 mode. Characters > 255 are assumed to + be "non-word" characters. Remember the earliest consulted character for + partial matching. */ + +#ifdef SUPPORT_UTF + if (utf) + { + /* Get status of previous character */ + + if (eptr == md->start_subject) prev_is_word = FALSE; else + { + PCRE_PUCHAR lastptr = eptr - 1; + BACKCHAR(lastptr); + if (lastptr < md->start_used_ptr) md->start_used_ptr = lastptr; + GETCHAR(c, lastptr); +#ifdef SUPPORT_UCP + if (md->use_ucp) + { + if (c == '_') prev_is_word = TRUE; else + { + int cat = UCD_CATEGORY(c); + prev_is_word = (cat == ucp_L || cat == ucp_N); + } + } + else +#endif + prev_is_word = c < 256 && (md->ctypes[c] & ctype_word) != 0; + } + + /* Get status of next character */ + + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + cur_is_word = FALSE; + } + else + { + GETCHAR(c, eptr); +#ifdef SUPPORT_UCP + if (md->use_ucp) + { + if (c == '_') cur_is_word = TRUE; else + { + int cat = UCD_CATEGORY(c); + cur_is_word = (cat == ucp_L || cat == ucp_N); + } + } + else +#endif + cur_is_word = c < 256 && (md->ctypes[c] & ctype_word) != 0; + } + } + else +#endif + + /* Not in UTF-8 mode, but we may still have PCRE_UCP set, and for + consistency with the behaviour of \w we do use it in this case. */ + + { + /* Get status of previous character */ + + if (eptr == md->start_subject) prev_is_word = FALSE; else + { + if (eptr <= md->start_used_ptr) md->start_used_ptr = eptr - 1; +#ifdef SUPPORT_UCP + if (md->use_ucp) + { + c = eptr[-1]; + if (c == '_') prev_is_word = TRUE; else + { + int cat = UCD_CATEGORY(c); + prev_is_word = (cat == ucp_L || cat == ucp_N); + } + } + else +#endif + prev_is_word = MAX_255(eptr[-1]) + && ((md->ctypes[eptr[-1]] & ctype_word) != 0); + } + + /* Get status of next character */ + + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + cur_is_word = FALSE; + } + else +#ifdef SUPPORT_UCP + if (md->use_ucp) + { + c = *eptr; + if (c == '_') cur_is_word = TRUE; else + { + int cat = UCD_CATEGORY(c); + cur_is_word = (cat == ucp_L || cat == ucp_N); + } + } + else +#endif + cur_is_word = MAX_255(*eptr) + && ((md->ctypes[*eptr] & ctype_word) != 0); + } + + /* Now see if the situation is what we want */ + + if ((*ecode++ == OP_WORD_BOUNDARY)? + cur_is_word == prev_is_word : cur_is_word != prev_is_word) + RRETURN(MATCH_NOMATCH); + } + break; + + /* Match any single character type except newline; have to take care with + CRLF newlines and partial matching. */ + + case OP_ANY: + if (IS_NEWLINE(eptr)) RRETURN(MATCH_NOMATCH); + if (md->partial != 0 && + eptr + 1 >= md->end_subject && + NLBLOCK->nltype == NLTYPE_FIXED && + NLBLOCK->nllen == 2 && + UCHAR21TEST(eptr) == NLBLOCK->nl[0]) + { + md->hitend = TRUE; + if (md->partial > 1) RRETURN(PCRE_ERROR_PARTIAL); + } + + /* Fall through */ + + /* Match any single character whatsoever. */ + + case OP_ALLANY: + if (eptr >= md->end_subject) /* DO NOT merge the eptr++ here; it must */ + { /* not be updated before SCHECK_PARTIAL. */ + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + eptr++; +#ifdef SUPPORT_UTF + if (utf) ACROSSCHAR(eptr < md->end_subject, *eptr, eptr++); +#endif + ecode++; + break; + + /* Match a single byte, even in UTF-8 mode. This opcode really does match + any byte, even newline, independent of the setting of PCRE_DOTALL. */ + + case OP_ANYBYTE: + if (eptr >= md->end_subject) /* DO NOT merge the eptr++ here; it must */ + { /* not be updated before SCHECK_PARTIAL. */ + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + eptr++; + ecode++; + break; + + case OP_NOT_DIGIT: + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINCTEST(c, eptr); + if ( +#if defined SUPPORT_UTF || !(defined COMPILE_PCRE8) + c < 256 && +#endif + (md->ctypes[c] & ctype_digit) != 0 + ) + RRETURN(MATCH_NOMATCH); + ecode++; + break; + + case OP_DIGIT: + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINCTEST(c, eptr); + if ( +#if defined SUPPORT_UTF || !(defined COMPILE_PCRE8) + c > 255 || +#endif + (md->ctypes[c] & ctype_digit) == 0 + ) + RRETURN(MATCH_NOMATCH); + ecode++; + break; + + case OP_NOT_WHITESPACE: + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINCTEST(c, eptr); + if ( +#if defined SUPPORT_UTF || !(defined COMPILE_PCRE8) + c < 256 && +#endif + (md->ctypes[c] & ctype_space) != 0 + ) + RRETURN(MATCH_NOMATCH); + ecode++; + break; + + case OP_WHITESPACE: + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINCTEST(c, eptr); + if ( +#if defined SUPPORT_UTF || !(defined COMPILE_PCRE8) + c > 255 || +#endif + (md->ctypes[c] & ctype_space) == 0 + ) + RRETURN(MATCH_NOMATCH); + ecode++; + break; + + case OP_NOT_WORDCHAR: + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINCTEST(c, eptr); + if ( +#if defined SUPPORT_UTF || !(defined COMPILE_PCRE8) + c < 256 && +#endif + (md->ctypes[c] & ctype_word) != 0 + ) + RRETURN(MATCH_NOMATCH); + ecode++; + break; + + case OP_WORDCHAR: + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINCTEST(c, eptr); + if ( +#if defined SUPPORT_UTF || !(defined COMPILE_PCRE8) + c > 255 || +#endif + (md->ctypes[c] & ctype_word) == 0 + ) + RRETURN(MATCH_NOMATCH); + ecode++; + break; + + case OP_ANYNL: + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINCTEST(c, eptr); + switch(c) + { + default: RRETURN(MATCH_NOMATCH); + + case CHAR_CR: + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + } + else if (UCHAR21TEST(eptr) == CHAR_LF) eptr++; + break; + + case CHAR_LF: + break; + + case CHAR_VT: + case CHAR_FF: + case CHAR_NEL: +#ifndef EBCDIC + case 0x2028: + case 0x2029: +#endif /* Not EBCDIC */ + if (md->bsr_anycrlf) RRETURN(MATCH_NOMATCH); + break; + } + ecode++; + break; + + case OP_NOT_HSPACE: + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINCTEST(c, eptr); + switch(c) + { + HSPACE_CASES: RRETURN(MATCH_NOMATCH); /* Byte and multibyte cases */ + default: break; + } + ecode++; + break; + + case OP_HSPACE: + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINCTEST(c, eptr); + switch(c) + { + HSPACE_CASES: break; /* Byte and multibyte cases */ + default: RRETURN(MATCH_NOMATCH); + } + ecode++; + break; + + case OP_NOT_VSPACE: + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINCTEST(c, eptr); + switch(c) + { + VSPACE_CASES: RRETURN(MATCH_NOMATCH); + default: break; + } + ecode++; + break; + + case OP_VSPACE: + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINCTEST(c, eptr); + switch(c) + { + VSPACE_CASES: break; + default: RRETURN(MATCH_NOMATCH); + } + ecode++; + break; + +#ifdef SUPPORT_UCP + /* Check the next character by Unicode property. We will get here only + if the support is in the binary; otherwise a compile-time error occurs. */ + + case OP_PROP: + case OP_NOTPROP: + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINCTEST(c, eptr); + { + const pcre_uint32 *cp; + const ucd_record *prop = GET_UCD(c); + + switch(ecode[1]) + { + case PT_ANY: + if (op == OP_NOTPROP) RRETURN(MATCH_NOMATCH); + break; + + case PT_LAMP: + if ((prop->chartype == ucp_Lu || + prop->chartype == ucp_Ll || + prop->chartype == ucp_Lt) == (op == OP_NOTPROP)) + RRETURN(MATCH_NOMATCH); + break; + + case PT_GC: + if ((ecode[2] != PRIV(ucp_gentype)[prop->chartype]) == (op == OP_PROP)) + RRETURN(MATCH_NOMATCH); + break; + + case PT_PC: + if ((ecode[2] != prop->chartype) == (op == OP_PROP)) + RRETURN(MATCH_NOMATCH); + break; + + case PT_SC: + if ((ecode[2] != prop->script) == (op == OP_PROP)) + RRETURN(MATCH_NOMATCH); + break; + + /* These are specials */ + + case PT_ALNUM: + if ((PRIV(ucp_gentype)[prop->chartype] == ucp_L || + PRIV(ucp_gentype)[prop->chartype] == ucp_N) == (op == OP_NOTPROP)) + RRETURN(MATCH_NOMATCH); + break; + + /* Perl space used to exclude VT, but from Perl 5.18 it is included, + which means that Perl space and POSIX space are now identical. PCRE + was changed at release 8.34. */ + + case PT_SPACE: /* Perl space */ + case PT_PXSPACE: /* POSIX space */ + switch(c) + { + HSPACE_CASES: + VSPACE_CASES: + if (op == OP_NOTPROP) RRETURN(MATCH_NOMATCH); + break; + + default: + if ((PRIV(ucp_gentype)[prop->chartype] == ucp_Z) == + (op == OP_NOTPROP)) RRETURN(MATCH_NOMATCH); + break; + } + break; + + case PT_WORD: + if ((PRIV(ucp_gentype)[prop->chartype] == ucp_L || + PRIV(ucp_gentype)[prop->chartype] == ucp_N || + c == CHAR_UNDERSCORE) == (op == OP_NOTPROP)) + RRETURN(MATCH_NOMATCH); + break; + + case PT_CLIST: + cp = PRIV(ucd_caseless_sets) + ecode[2]; + for (;;) + { + if (c < *cp) + { if (op == OP_PROP) { RRETURN(MATCH_NOMATCH); } else break; } + if (c == *cp++) + { if (op == OP_PROP) break; else { RRETURN(MATCH_NOMATCH); } } + } + break; + + case PT_UCNC: + if ((c == CHAR_DOLLAR_SIGN || c == CHAR_COMMERCIAL_AT || + c == CHAR_GRAVE_ACCENT || (c >= 0xa0 && c <= 0xd7ff) || + c >= 0xe000) == (op == OP_NOTPROP)) + RRETURN(MATCH_NOMATCH); + break; + + /* This should never occur */ + + default: + RRETURN(PCRE_ERROR_INTERNAL); + } + + ecode += 3; + } + break; + + /* Match an extended Unicode sequence. We will get here only if the support + is in the binary; otherwise a compile-time error occurs. */ + + case OP_EXTUNI: + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + else + { + int lgb, rgb; + GETCHARINCTEST(c, eptr); + lgb = UCD_GRAPHBREAK(c); + while (eptr < md->end_subject) + { + int len = 1; + if (!utf) c = *eptr; else { GETCHARLEN(c, eptr, len); } + rgb = UCD_GRAPHBREAK(c); + if ((PRIV(ucp_gbtable)[lgb] & (1 << rgb)) == 0) break; + lgb = rgb; + eptr += len; + } + } + CHECK_PARTIAL(); + ecode++; + break; +#endif /* SUPPORT_UCP */ + + + /* Match a back reference, possibly repeatedly. Look past the end of the + item to see if there is repeat information following. The code is similar + to that for character classes, but repeated for efficiency. Then obey + similar code to character type repeats - written out again for speed. + However, if the referenced string is the empty string, always treat + it as matched, any number of times (otherwise there could be infinite + loops). If the reference is unset, there are two possibilities: + + (a) In the default, Perl-compatible state, set the length negative; + this ensures that every attempt at a match fails. We can't just fail + here, because of the possibility of quantifiers with zero minima. + + (b) If the JavaScript compatibility flag is set, set the length to zero + so that the back reference matches an empty string. + + Otherwise, set the length to the length of what was matched by the + referenced subpattern. + + The OP_REF and OP_REFI opcodes are used for a reference to a numbered group + or to a non-duplicated named group. For a duplicated named group, OP_DNREF + and OP_DNREFI are used. In this case we must scan the list of groups to + which the name refers, and use the first one that is set. */ + + case OP_DNREF: + case OP_DNREFI: + caseless = op == OP_DNREFI; + { + int count = GET2(ecode, 1+IMM2_SIZE); + pcre_uchar *slot = md->name_table + GET2(ecode, 1) * md->name_entry_size; + ecode += 1 + 2*IMM2_SIZE; + + /* Setting the default length first and initializing 'offset' avoids + compiler warnings in the REF_REPEAT code. */ + + length = (md->jscript_compat)? 0 : -1; + offset = 0; + + while (count-- > 0) + { + offset = GET2(slot, 0) << 1; + if (offset < offset_top && md->offset_vector[offset] >= 0) + { + length = md->offset_vector[offset+1] - md->offset_vector[offset]; + break; + } + slot += md->name_entry_size; + } + } + goto REF_REPEAT; + + case OP_REF: + case OP_REFI: + caseless = op == OP_REFI; + offset = GET2(ecode, 1) << 1; /* Doubled ref number */ + ecode += 1 + IMM2_SIZE; + if (offset >= offset_top || md->offset_vector[offset] < 0) + length = (md->jscript_compat)? 0 : -1; + else + length = md->offset_vector[offset+1] - md->offset_vector[offset]; + + /* Set up for repetition, or handle the non-repeated case */ + + REF_REPEAT: + switch (*ecode) + { + case OP_CRSTAR: + case OP_CRMINSTAR: + case OP_CRPLUS: + case OP_CRMINPLUS: + case OP_CRQUERY: + case OP_CRMINQUERY: + c = *ecode++ - OP_CRSTAR; + minimize = (c & 1) != 0; + min = rep_min[c]; /* Pick up values from tables; */ + max = rep_max[c]; /* zero for max => infinity */ + if (max == 0) max = INT_MAX; + break; + + case OP_CRRANGE: + case OP_CRMINRANGE: + minimize = (*ecode == OP_CRMINRANGE); + min = GET2(ecode, 1); + max = GET2(ecode, 1 + IMM2_SIZE); + if (max == 0) max = INT_MAX; + ecode += 1 + 2 * IMM2_SIZE; + break; + + default: /* No repeat follows */ + if ((length = match_ref(offset, eptr, length, md, caseless)) < 0) + { + if (length == -2) eptr = md->end_subject; /* Partial match */ + CHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + eptr += length; + continue; /* With the main loop */ + } + + /* Handle repeated back references. If the length of the reference is + zero, just continue with the main loop. If the length is negative, it + means the reference is unset in non-Java-compatible mode. If the minimum is + zero, we can continue at the same level without recursion. For any other + minimum, carrying on will result in NOMATCH. */ + + if (length == 0) continue; + if (length < 0 && min == 0) continue; + + /* First, ensure the minimum number of matches are present. We get back + the length of the reference string explicitly rather than passing the + address of eptr, so that eptr can be a register variable. */ + + for (i = 1; i <= min; i++) + { + int slength; + if ((slength = match_ref(offset, eptr, length, md, caseless)) < 0) + { + if (slength == -2) eptr = md->end_subject; /* Partial match */ + CHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + eptr += slength; + } + + /* If min = max, continue at the same level without recursion. + They are not both allowed to be zero. */ + + if (min == max) continue; + + /* If minimizing, keep trying and advancing the pointer */ + + if (minimize) + { + for (fi = min;; fi++) + { + int slength; + RMATCH(eptr, ecode, offset_top, md, eptrb, RM14); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (fi >= max) RRETURN(MATCH_NOMATCH); + if ((slength = match_ref(offset, eptr, length, md, caseless)) < 0) + { + if (slength == -2) eptr = md->end_subject; /* Partial match */ + CHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + eptr += slength; + } + /* Control never gets here */ + } + + /* If maximizing, find the longest string and work backwards */ + + else + { + pp = eptr; + for (i = min; i < max; i++) + { + int slength; + if ((slength = match_ref(offset, eptr, length, md, caseless)) < 0) + { + /* Can't use CHECK_PARTIAL because we don't want to update eptr in + the soft partial matching case. */ + + if (slength == -2 && md->partial != 0 && + md->end_subject > md->start_used_ptr) + { + md->hitend = TRUE; + if (md->partial > 1) RRETURN(PCRE_ERROR_PARTIAL); + } + break; + } + eptr += slength; + } + + while (eptr >= pp) + { + RMATCH(eptr, ecode, offset_top, md, eptrb, RM15); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + eptr -= length; + } + RRETURN(MATCH_NOMATCH); + } + /* Control never gets here */ + + /* Match a bit-mapped character class, possibly repeatedly. This op code is + used when all the characters in the class have values in the range 0-255, + and either the matching is caseful, or the characters are in the range + 0-127 when UTF-8 processing is enabled. The only difference between + OP_CLASS and OP_NCLASS occurs when a data character outside the range is + encountered. + + First, look past the end of the item to see if there is repeat information + following. Then obey similar code to character type repeats - written out + again for speed. */ + + case OP_NCLASS: + case OP_CLASS: + { + /* The data variable is saved across frames, so the byte map needs to + be stored there. */ +#define BYTE_MAP ((pcre_uint8 *)data) + data = ecode + 1; /* Save for matching */ + ecode += 1 + (32 / sizeof(pcre_uchar)); /* Advance past the item */ + + switch (*ecode) + { + case OP_CRSTAR: + case OP_CRMINSTAR: + case OP_CRPLUS: + case OP_CRMINPLUS: + case OP_CRQUERY: + case OP_CRMINQUERY: + case OP_CRPOSSTAR: + case OP_CRPOSPLUS: + case OP_CRPOSQUERY: + c = *ecode++ - OP_CRSTAR; + if (c < OP_CRPOSSTAR - OP_CRSTAR) minimize = (c & 1) != 0; + else possessive = TRUE; + min = rep_min[c]; /* Pick up values from tables; */ + max = rep_max[c]; /* zero for max => infinity */ + if (max == 0) max = INT_MAX; + break; + + case OP_CRRANGE: + case OP_CRMINRANGE: + case OP_CRPOSRANGE: + minimize = (*ecode == OP_CRMINRANGE); + possessive = (*ecode == OP_CRPOSRANGE); + min = GET2(ecode, 1); + max = GET2(ecode, 1 + IMM2_SIZE); + if (max == 0) max = INT_MAX; + ecode += 1 + 2 * IMM2_SIZE; + break; + + default: /* No repeat follows */ + min = max = 1; + break; + } + + /* First, ensure the minimum number of matches are present. */ + +#ifdef SUPPORT_UTF + if (utf) + { + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINC(c, eptr); + if (c > 255) + { + if (op == OP_CLASS) RRETURN(MATCH_NOMATCH); + } + else + if ((BYTE_MAP[c/8] & (1 << (c&7))) == 0) RRETURN(MATCH_NOMATCH); + } + } + else +#endif + /* Not UTF mode */ + { + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + c = *eptr++; +#ifndef COMPILE_PCRE8 + if (c > 255) + { + if (op == OP_CLASS) RRETURN(MATCH_NOMATCH); + } + else +#endif + if ((BYTE_MAP[c/8] & (1 << (c&7))) == 0) RRETURN(MATCH_NOMATCH); + } + } + + /* If max == min we can continue with the main loop without the + need to recurse. */ + + if (min == max) continue; + + /* If minimizing, keep testing the rest of the expression and advancing + the pointer while it matches the class. */ + + if (minimize) + { +#ifdef SUPPORT_UTF + if (utf) + { + for (fi = min;; fi++) + { + RMATCH(eptr, ecode, offset_top, md, eptrb, RM16); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (fi >= max) RRETURN(MATCH_NOMATCH); + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINC(c, eptr); + if (c > 255) + { + if (op == OP_CLASS) RRETURN(MATCH_NOMATCH); + } + else + if ((BYTE_MAP[c/8] & (1 << (c&7))) == 0) RRETURN(MATCH_NOMATCH); + } + } + else +#endif + /* Not UTF mode */ + { + for (fi = min;; fi++) + { + RMATCH(eptr, ecode, offset_top, md, eptrb, RM17); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (fi >= max) RRETURN(MATCH_NOMATCH); + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + c = *eptr++; +#ifndef COMPILE_PCRE8 + if (c > 255) + { + if (op == OP_CLASS) RRETURN(MATCH_NOMATCH); + } + else +#endif + if ((BYTE_MAP[c/8] & (1 << (c&7))) == 0) RRETURN(MATCH_NOMATCH); + } + } + /* Control never gets here */ + } + + /* If maximizing, find the longest possible run, then work backwards. */ + + else + { + pp = eptr; + +#ifdef SUPPORT_UTF + if (utf) + { + for (i = min; i < max; i++) + { + int len = 1; + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + break; + } + GETCHARLEN(c, eptr, len); + if (c > 255) + { + if (op == OP_CLASS) break; + } + else + if ((BYTE_MAP[c/8] & (1 << (c&7))) == 0) break; + eptr += len; + } + + if (possessive) continue; /* No backtracking */ + + for (;;) + { + RMATCH(eptr, ecode, offset_top, md, eptrb, RM18); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (eptr-- == pp) break; /* Stop if tried at original pos */ + BACKCHAR(eptr); + } + } + else +#endif + /* Not UTF mode */ + { + for (i = min; i < max; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + break; + } + c = *eptr; +#ifndef COMPILE_PCRE8 + if (c > 255) + { + if (op == OP_CLASS) break; + } + else +#endif + if ((BYTE_MAP[c/8] & (1 << (c&7))) == 0) break; + eptr++; + } + + if (possessive) continue; /* No backtracking */ + + while (eptr >= pp) + { + RMATCH(eptr, ecode, offset_top, md, eptrb, RM19); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + eptr--; + } + } + + RRETURN(MATCH_NOMATCH); + } +#undef BYTE_MAP + } + /* Control never gets here */ + + + /* Match an extended character class. In the 8-bit library, this opcode is + encountered only when UTF-8 mode mode is supported. In the 16-bit and + 32-bit libraries, codepoints greater than 255 may be encountered even when + UTF is not supported. */ + +#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 + case OP_XCLASS: + { + data = ecode + 1 + LINK_SIZE; /* Save for matching */ + ecode += GET(ecode, 1); /* Advance past the item */ + + switch (*ecode) + { + case OP_CRSTAR: + case OP_CRMINSTAR: + case OP_CRPLUS: + case OP_CRMINPLUS: + case OP_CRQUERY: + case OP_CRMINQUERY: + case OP_CRPOSSTAR: + case OP_CRPOSPLUS: + case OP_CRPOSQUERY: + c = *ecode++ - OP_CRSTAR; + if (c < OP_CRPOSSTAR - OP_CRSTAR) minimize = (c & 1) != 0; + else possessive = TRUE; + min = rep_min[c]; /* Pick up values from tables; */ + max = rep_max[c]; /* zero for max => infinity */ + if (max == 0) max = INT_MAX; + break; + + case OP_CRRANGE: + case OP_CRMINRANGE: + case OP_CRPOSRANGE: + minimize = (*ecode == OP_CRMINRANGE); + possessive = (*ecode == OP_CRPOSRANGE); + min = GET2(ecode, 1); + max = GET2(ecode, 1 + IMM2_SIZE); + if (max == 0) max = INT_MAX; + ecode += 1 + 2 * IMM2_SIZE; + break; + + default: /* No repeat follows */ + min = max = 1; + break; + } + + /* First, ensure the minimum number of matches are present. */ + + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINCTEST(c, eptr); + if (!PRIV(xclass)(c, data, utf)) RRETURN(MATCH_NOMATCH); + } + + /* If max == min we can continue with the main loop without the + need to recurse. */ + + if (min == max) continue; + + /* If minimizing, keep testing the rest of the expression and advancing + the pointer while it matches the class. */ + + if (minimize) + { + for (fi = min;; fi++) + { + RMATCH(eptr, ecode, offset_top, md, eptrb, RM20); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (fi >= max) RRETURN(MATCH_NOMATCH); + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINCTEST(c, eptr); + if (!PRIV(xclass)(c, data, utf)) RRETURN(MATCH_NOMATCH); + } + /* Control never gets here */ + } + + /* If maximizing, find the longest possible run, then work backwards. */ + + else + { + pp = eptr; + for (i = min; i < max; i++) + { + int len = 1; + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + break; + } +#ifdef SUPPORT_UTF + GETCHARLENTEST(c, eptr, len); +#else + c = *eptr; +#endif + if (!PRIV(xclass)(c, data, utf)) break; + eptr += len; + } + + if (possessive) continue; /* No backtracking */ + + for(;;) + { + RMATCH(eptr, ecode, offset_top, md, eptrb, RM21); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (eptr-- == pp) break; /* Stop if tried at original pos */ +#ifdef SUPPORT_UTF + if (utf) BACKCHAR(eptr); +#endif + } + RRETURN(MATCH_NOMATCH); + } + + /* Control never gets here */ + } +#endif /* End of XCLASS */ + + /* Match a single character, casefully */ + + case OP_CHAR: +#ifdef SUPPORT_UTF + if (utf) + { + length = 1; + ecode++; + GETCHARLEN(fc, ecode, length); + if (length > md->end_subject - eptr) + { + CHECK_PARTIAL(); /* Not SCHECK_PARTIAL() */ + RRETURN(MATCH_NOMATCH); + } + while (length-- > 0) if (*ecode++ != UCHAR21INC(eptr)) RRETURN(MATCH_NOMATCH); + } + else +#endif + /* Not UTF mode */ + { + if (md->end_subject - eptr < 1) + { + SCHECK_PARTIAL(); /* This one can use SCHECK_PARTIAL() */ + RRETURN(MATCH_NOMATCH); + } + if (ecode[1] != *eptr++) RRETURN(MATCH_NOMATCH); + ecode += 2; + } + break; + + /* Match a single character, caselessly. If we are at the end of the + subject, give up immediately. */ + + case OP_CHARI: + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + +#ifdef SUPPORT_UTF + if (utf) + { + length = 1; + ecode++; + GETCHARLEN(fc, ecode, length); + + /* If the pattern character's value is < 128, we have only one byte, and + we know that its other case must also be one byte long, so we can use the + fast lookup table. We know that there is at least one byte left in the + subject. */ + + if (fc < 128) + { + pcre_uint32 cc = UCHAR21(eptr); + if (md->lcc[fc] != TABLE_GET(cc, md->lcc, cc)) RRETURN(MATCH_NOMATCH); + ecode++; + eptr++; + } + + /* Otherwise we must pick up the subject character. Note that we cannot + use the value of "length" to check for sufficient bytes left, because the + other case of the character may have more or fewer bytes. */ + + else + { + pcre_uint32 dc; + GETCHARINC(dc, eptr); + ecode += length; + + /* If we have Unicode property support, we can use it to test the other + case of the character, if there is one. */ + + if (fc != dc) + { +#ifdef SUPPORT_UCP + if (dc != UCD_OTHERCASE(fc)) +#endif + RRETURN(MATCH_NOMATCH); + } + } + } + else +#endif /* SUPPORT_UTF */ + + /* Not UTF mode */ + { + if (TABLE_GET(ecode[1], md->lcc, ecode[1]) + != TABLE_GET(*eptr, md->lcc, *eptr)) RRETURN(MATCH_NOMATCH); + eptr++; + ecode += 2; + } + break; + + /* Match a single character repeatedly. */ + + case OP_EXACT: + case OP_EXACTI: + min = max = GET2(ecode, 1); + ecode += 1 + IMM2_SIZE; + goto REPEATCHAR; + + case OP_POSUPTO: + case OP_POSUPTOI: + possessive = TRUE; + /* Fall through */ + + case OP_UPTO: + case OP_UPTOI: + case OP_MINUPTO: + case OP_MINUPTOI: + min = 0; + max = GET2(ecode, 1); + minimize = *ecode == OP_MINUPTO || *ecode == OP_MINUPTOI; + ecode += 1 + IMM2_SIZE; + goto REPEATCHAR; + + case OP_POSSTAR: + case OP_POSSTARI: + possessive = TRUE; + min = 0; + max = INT_MAX; + ecode++; + goto REPEATCHAR; + + case OP_POSPLUS: + case OP_POSPLUSI: + possessive = TRUE; + min = 1; + max = INT_MAX; + ecode++; + goto REPEATCHAR; + + case OP_POSQUERY: + case OP_POSQUERYI: + possessive = TRUE; + min = 0; + max = 1; + ecode++; + goto REPEATCHAR; + + case OP_STAR: + case OP_STARI: + case OP_MINSTAR: + case OP_MINSTARI: + case OP_PLUS: + case OP_PLUSI: + case OP_MINPLUS: + case OP_MINPLUSI: + case OP_QUERY: + case OP_QUERYI: + case OP_MINQUERY: + case OP_MINQUERYI: + c = *ecode++ - ((op < OP_STARI)? OP_STAR : OP_STARI); + minimize = (c & 1) != 0; + min = rep_min[c]; /* Pick up values from tables; */ + max = rep_max[c]; /* zero for max => infinity */ + if (max == 0) max = INT_MAX; + + /* Common code for all repeated single-character matches. We first check + for the minimum number of characters. If the minimum equals the maximum, we + are done. Otherwise, if minimizing, check the rest of the pattern for a + match; if there isn't one, advance up to the maximum, one character at a + time. + + If maximizing, advance up to the maximum number of matching characters, + until eptr is past the end of the maximum run. If possessive, we are + then done (no backing up). Otherwise, match at this position; anything + other than no match is immediately returned. For nomatch, back up one + character, unless we are matching \R and the last thing matched was + \r\n, in which case, back up two bytes. When we reach the first optional + character position, we can save stack by doing a tail recurse. + + The various UTF/non-UTF and caseful/caseless cases are handled separately, + for speed. */ + + REPEATCHAR: +#ifdef SUPPORT_UTF + if (utf) + { + length = 1; + charptr = ecode; + GETCHARLEN(fc, ecode, length); + ecode += length; + + /* Handle multibyte character matching specially here. There is + support for caseless matching if UCP support is present. */ + + if (length > 1) + { +#ifdef SUPPORT_UCP + pcre_uint32 othercase; + if (op >= OP_STARI && /* Caseless */ + (othercase = UCD_OTHERCASE(fc)) != fc) + oclength = PRIV(ord2utf)(othercase, occhars); + else oclength = 0; +#endif /* SUPPORT_UCP */ + + for (i = 1; i <= min; i++) + { + if (eptr <= md->end_subject - length && + memcmp(eptr, charptr, IN_UCHARS(length)) == 0) eptr += length; +#ifdef SUPPORT_UCP + else if (oclength > 0 && + eptr <= md->end_subject - oclength && + memcmp(eptr, occhars, IN_UCHARS(oclength)) == 0) eptr += oclength; +#endif /* SUPPORT_UCP */ + else + { + CHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + } + + if (min == max) continue; + + if (minimize) + { + for (fi = min;; fi++) + { + RMATCH(eptr, ecode, offset_top, md, eptrb, RM22); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (fi >= max) RRETURN(MATCH_NOMATCH); + if (eptr <= md->end_subject - length && + memcmp(eptr, charptr, IN_UCHARS(length)) == 0) eptr += length; +#ifdef SUPPORT_UCP + else if (oclength > 0 && + eptr <= md->end_subject - oclength && + memcmp(eptr, occhars, IN_UCHARS(oclength)) == 0) eptr += oclength; +#endif /* SUPPORT_UCP */ + else + { + CHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + } + /* Control never gets here */ + } + + else /* Maximize */ + { + pp = eptr; + for (i = min; i < max; i++) + { + if (eptr <= md->end_subject - length && + memcmp(eptr, charptr, IN_UCHARS(length)) == 0) eptr += length; +#ifdef SUPPORT_UCP + else if (oclength > 0 && + eptr <= md->end_subject - oclength && + memcmp(eptr, occhars, IN_UCHARS(oclength)) == 0) eptr += oclength; +#endif /* SUPPORT_UCP */ + else + { + CHECK_PARTIAL(); + break; + } + } + + if (possessive) continue; /* No backtracking */ + for(;;) + { + if (eptr == pp) goto TAIL_RECURSE; + RMATCH(eptr, ecode, offset_top, md, eptrb, RM23); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); +#ifdef SUPPORT_UCP + eptr--; + BACKCHAR(eptr); +#else /* without SUPPORT_UCP */ + eptr -= length; +#endif /* SUPPORT_UCP */ + } + } + /* Control never gets here */ + } + + /* If the length of a UTF-8 character is 1, we fall through here, and + obey the code as for non-UTF-8 characters below, though in this case the + value of fc will always be < 128. */ + } + else +#endif /* SUPPORT_UTF */ + /* When not in UTF-8 mode, load a single-byte character. */ + fc = *ecode++; + + /* The value of fc at this point is always one character, though we may + or may not be in UTF mode. The code is duplicated for the caseless and + caseful cases, for speed, since matching characters is likely to be quite + common. First, ensure the minimum number of matches are present. If min = + max, continue at the same level without recursing. Otherwise, if + minimizing, keep trying the rest of the expression and advancing one + matching character if failing, up to the maximum. Alternatively, if + maximizing, find the maximum number of characters and work backwards. */ + + DPRINTF(("matching %c{%d,%d} against subject %.*s\n", fc, min, max, + max, (char *)eptr)); + + if (op >= OP_STARI) /* Caseless */ + { +#ifdef COMPILE_PCRE8 + /* fc must be < 128 if UTF is enabled. */ + foc = md->fcc[fc]; +#else +#ifdef SUPPORT_UTF +#ifdef SUPPORT_UCP + if (utf && fc > 127) + foc = UCD_OTHERCASE(fc); +#else + if (utf && fc > 127) + foc = fc; +#endif /* SUPPORT_UCP */ + else +#endif /* SUPPORT_UTF */ + foc = TABLE_GET(fc, md->fcc, fc); +#endif /* COMPILE_PCRE8 */ + + for (i = 1; i <= min; i++) + { + pcre_uint32 cc; /* Faster than pcre_uchar */ + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + cc = UCHAR21TEST(eptr); + if (fc != cc && foc != cc) RRETURN(MATCH_NOMATCH); + eptr++; + } + if (min == max) continue; + if (minimize) + { + for (fi = min;; fi++) + { + pcre_uint32 cc; /* Faster than pcre_uchar */ + RMATCH(eptr, ecode, offset_top, md, eptrb, RM24); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (fi >= max) RRETURN(MATCH_NOMATCH); + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + cc = UCHAR21TEST(eptr); + if (fc != cc && foc != cc) RRETURN(MATCH_NOMATCH); + eptr++; + } + /* Control never gets here */ + } + else /* Maximize */ + { + pp = eptr; + for (i = min; i < max; i++) + { + pcre_uint32 cc; /* Faster than pcre_uchar */ + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + break; + } + cc = UCHAR21TEST(eptr); + if (fc != cc && foc != cc) break; + eptr++; + } + if (possessive) continue; /* No backtracking */ + for (;;) + { + if (eptr == pp) goto TAIL_RECURSE; + RMATCH(eptr, ecode, offset_top, md, eptrb, RM25); + eptr--; + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + } + /* Control never gets here */ + } + } + + /* Caseful comparisons (includes all multi-byte characters) */ + + else + { + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + if (fc != UCHAR21INCTEST(eptr)) RRETURN(MATCH_NOMATCH); + } + + if (min == max) continue; + + if (minimize) + { + for (fi = min;; fi++) + { + RMATCH(eptr, ecode, offset_top, md, eptrb, RM26); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (fi >= max) RRETURN(MATCH_NOMATCH); + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + if (fc != UCHAR21INCTEST(eptr)) RRETURN(MATCH_NOMATCH); + } + /* Control never gets here */ + } + else /* Maximize */ + { + pp = eptr; + for (i = min; i < max; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + break; + } + if (fc != UCHAR21TEST(eptr)) break; + eptr++; + } + if (possessive) continue; /* No backtracking */ + for (;;) + { + if (eptr == pp) goto TAIL_RECURSE; + RMATCH(eptr, ecode, offset_top, md, eptrb, RM27); + eptr--; + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + } + /* Control never gets here */ + } + } + /* Control never gets here */ + + /* Match a negated single one-byte character. The character we are + checking can be multibyte. */ + + case OP_NOT: + case OP_NOTI: + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } +#ifdef SUPPORT_UTF + if (utf) + { + register pcre_uint32 ch, och; + + ecode++; + GETCHARINC(ch, ecode); + GETCHARINC(c, eptr); + + if (op == OP_NOT) + { + if (ch == c) RRETURN(MATCH_NOMATCH); + } + else + { +#ifdef SUPPORT_UCP + if (ch > 127) + och = UCD_OTHERCASE(ch); +#else + if (ch > 127) + och = ch; +#endif /* SUPPORT_UCP */ + else + och = TABLE_GET(ch, md->fcc, ch); + if (ch == c || och == c) RRETURN(MATCH_NOMATCH); + } + } + else +#endif + { + register pcre_uint32 ch = ecode[1]; + c = *eptr++; + if (ch == c || (op == OP_NOTI && TABLE_GET(ch, md->fcc, ch) == c)) + RRETURN(MATCH_NOMATCH); + ecode += 2; + } + break; + + /* Match a negated single one-byte character repeatedly. This is almost a + repeat of the code for a repeated single character, but I haven't found a + nice way of commoning these up that doesn't require a test of the + positive/negative option for each character match. Maybe that wouldn't add + very much to the time taken, but character matching *is* what this is all + about... */ + + case OP_NOTEXACT: + case OP_NOTEXACTI: + min = max = GET2(ecode, 1); + ecode += 1 + IMM2_SIZE; + goto REPEATNOTCHAR; + + case OP_NOTUPTO: + case OP_NOTUPTOI: + case OP_NOTMINUPTO: + case OP_NOTMINUPTOI: + min = 0; + max = GET2(ecode, 1); + minimize = *ecode == OP_NOTMINUPTO || *ecode == OP_NOTMINUPTOI; + ecode += 1 + IMM2_SIZE; + goto REPEATNOTCHAR; + + case OP_NOTPOSSTAR: + case OP_NOTPOSSTARI: + possessive = TRUE; + min = 0; + max = INT_MAX; + ecode++; + goto REPEATNOTCHAR; + + case OP_NOTPOSPLUS: + case OP_NOTPOSPLUSI: + possessive = TRUE; + min = 1; + max = INT_MAX; + ecode++; + goto REPEATNOTCHAR; + + case OP_NOTPOSQUERY: + case OP_NOTPOSQUERYI: + possessive = TRUE; + min = 0; + max = 1; + ecode++; + goto REPEATNOTCHAR; + + case OP_NOTPOSUPTO: + case OP_NOTPOSUPTOI: + possessive = TRUE; + min = 0; + max = GET2(ecode, 1); + ecode += 1 + IMM2_SIZE; + goto REPEATNOTCHAR; + + case OP_NOTSTAR: + case OP_NOTSTARI: + case OP_NOTMINSTAR: + case OP_NOTMINSTARI: + case OP_NOTPLUS: + case OP_NOTPLUSI: + case OP_NOTMINPLUS: + case OP_NOTMINPLUSI: + case OP_NOTQUERY: + case OP_NOTQUERYI: + case OP_NOTMINQUERY: + case OP_NOTMINQUERYI: + c = *ecode++ - ((op >= OP_NOTSTARI)? OP_NOTSTARI: OP_NOTSTAR); + minimize = (c & 1) != 0; + min = rep_min[c]; /* Pick up values from tables; */ + max = rep_max[c]; /* zero for max => infinity */ + if (max == 0) max = INT_MAX; + + /* Common code for all repeated single-byte matches. */ + + REPEATNOTCHAR: + GETCHARINCTEST(fc, ecode); + + /* The code is duplicated for the caseless and caseful cases, for speed, + since matching characters is likely to be quite common. First, ensure the + minimum number of matches are present. If min = max, continue at the same + level without recursing. Otherwise, if minimizing, keep trying the rest of + the expression and advancing one matching character if failing, up to the + maximum. Alternatively, if maximizing, find the maximum number of + characters and work backwards. */ + + DPRINTF(("negative matching %c{%d,%d} against subject %.*s\n", fc, min, max, + max, (char *)eptr)); + + if (op >= OP_NOTSTARI) /* Caseless */ + { +#ifdef SUPPORT_UTF +#ifdef SUPPORT_UCP + if (utf && fc > 127) + foc = UCD_OTHERCASE(fc); +#else + if (utf && fc > 127) + foc = fc; +#endif /* SUPPORT_UCP */ + else +#endif /* SUPPORT_UTF */ + foc = TABLE_GET(fc, md->fcc, fc); + +#ifdef SUPPORT_UTF + if (utf) + { + register pcre_uint32 d; + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINC(d, eptr); + if (fc == d || (unsigned int)foc == d) RRETURN(MATCH_NOMATCH); + } + } + else +#endif /* SUPPORT_UTF */ + /* Not UTF mode */ + { + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + if (fc == *eptr || foc == *eptr) RRETURN(MATCH_NOMATCH); + eptr++; + } + } + + if (min == max) continue; + + if (minimize) + { +#ifdef SUPPORT_UTF + if (utf) + { + register pcre_uint32 d; + for (fi = min;; fi++) + { + RMATCH(eptr, ecode, offset_top, md, eptrb, RM28); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (fi >= max) RRETURN(MATCH_NOMATCH); + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINC(d, eptr); + if (fc == d || (unsigned int)foc == d) RRETURN(MATCH_NOMATCH); + } + } + else +#endif /*SUPPORT_UTF */ + /* Not UTF mode */ + { + for (fi = min;; fi++) + { + RMATCH(eptr, ecode, offset_top, md, eptrb, RM29); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (fi >= max) RRETURN(MATCH_NOMATCH); + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + if (fc == *eptr || foc == *eptr) RRETURN(MATCH_NOMATCH); + eptr++; + } + } + /* Control never gets here */ + } + + /* Maximize case */ + + else + { + pp = eptr; + +#ifdef SUPPORT_UTF + if (utf) + { + register pcre_uint32 d; + for (i = min; i < max; i++) + { + int len = 1; + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + break; + } + GETCHARLEN(d, eptr, len); + if (fc == d || (unsigned int)foc == d) break; + eptr += len; + } + if (possessive) continue; /* No backtracking */ + for(;;) + { + if (eptr == pp) goto TAIL_RECURSE; + RMATCH(eptr, ecode, offset_top, md, eptrb, RM30); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + eptr--; + BACKCHAR(eptr); + } + } + else +#endif /* SUPPORT_UTF */ + /* Not UTF mode */ + { + for (i = min; i < max; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + break; + } + if (fc == *eptr || foc == *eptr) break; + eptr++; + } + if (possessive) continue; /* No backtracking */ + for (;;) + { + if (eptr == pp) goto TAIL_RECURSE; + RMATCH(eptr, ecode, offset_top, md, eptrb, RM31); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + eptr--; + } + } + /* Control never gets here */ + } + } + + /* Caseful comparisons */ + + else + { +#ifdef SUPPORT_UTF + if (utf) + { + register pcre_uint32 d; + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINC(d, eptr); + if (fc == d) RRETURN(MATCH_NOMATCH); + } + } + else +#endif + /* Not UTF mode */ + { + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + if (fc == *eptr++) RRETURN(MATCH_NOMATCH); + } + } + + if (min == max) continue; + + if (minimize) + { +#ifdef SUPPORT_UTF + if (utf) + { + register pcre_uint32 d; + for (fi = min;; fi++) + { + RMATCH(eptr, ecode, offset_top, md, eptrb, RM32); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (fi >= max) RRETURN(MATCH_NOMATCH); + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINC(d, eptr); + if (fc == d) RRETURN(MATCH_NOMATCH); + } + } + else +#endif + /* Not UTF mode */ + { + for (fi = min;; fi++) + { + RMATCH(eptr, ecode, offset_top, md, eptrb, RM33); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (fi >= max) RRETURN(MATCH_NOMATCH); + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + if (fc == *eptr++) RRETURN(MATCH_NOMATCH); + } + } + /* Control never gets here */ + } + + /* Maximize case */ + + else + { + pp = eptr; + +#ifdef SUPPORT_UTF + if (utf) + { + register pcre_uint32 d; + for (i = min; i < max; i++) + { + int len = 1; + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + break; + } + GETCHARLEN(d, eptr, len); + if (fc == d) break; + eptr += len; + } + if (possessive) continue; /* No backtracking */ + for(;;) + { + if (eptr == pp) goto TAIL_RECURSE; + RMATCH(eptr, ecode, offset_top, md, eptrb, RM34); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + eptr--; + BACKCHAR(eptr); + } + } + else +#endif + /* Not UTF mode */ + { + for (i = min; i < max; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + break; + } + if (fc == *eptr) break; + eptr++; + } + if (possessive) continue; /* No backtracking */ + for (;;) + { + if (eptr == pp) goto TAIL_RECURSE; + RMATCH(eptr, ecode, offset_top, md, eptrb, RM35); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + eptr--; + } + } + /* Control never gets here */ + } + } + /* Control never gets here */ + + /* Match a single character type repeatedly; several different opcodes + share code. This is very similar to the code for single characters, but we + repeat it in the interests of efficiency. */ + + case OP_TYPEEXACT: + min = max = GET2(ecode, 1); + minimize = TRUE; + ecode += 1 + IMM2_SIZE; + goto REPEATTYPE; + + case OP_TYPEUPTO: + case OP_TYPEMINUPTO: + min = 0; + max = GET2(ecode, 1); + minimize = *ecode == OP_TYPEMINUPTO; + ecode += 1 + IMM2_SIZE; + goto REPEATTYPE; + + case OP_TYPEPOSSTAR: + possessive = TRUE; + min = 0; + max = INT_MAX; + ecode++; + goto REPEATTYPE; + + case OP_TYPEPOSPLUS: + possessive = TRUE; + min = 1; + max = INT_MAX; + ecode++; + goto REPEATTYPE; + + case OP_TYPEPOSQUERY: + possessive = TRUE; + min = 0; + max = 1; + ecode++; + goto REPEATTYPE; + + case OP_TYPEPOSUPTO: + possessive = TRUE; + min = 0; + max = GET2(ecode, 1); + ecode += 1 + IMM2_SIZE; + goto REPEATTYPE; + + case OP_TYPESTAR: + case OP_TYPEMINSTAR: + case OP_TYPEPLUS: + case OP_TYPEMINPLUS: + case OP_TYPEQUERY: + case OP_TYPEMINQUERY: + c = *ecode++ - OP_TYPESTAR; + minimize = (c & 1) != 0; + min = rep_min[c]; /* Pick up values from tables; */ + max = rep_max[c]; /* zero for max => infinity */ + if (max == 0) max = INT_MAX; + + /* Common code for all repeated single character type matches. Note that + in UTF-8 mode, '.' matches a character of any length, but for the other + character types, the valid characters are all one-byte long. */ + + REPEATTYPE: + ctype = *ecode++; /* Code for the character type */ + +#ifdef SUPPORT_UCP + if (ctype == OP_PROP || ctype == OP_NOTPROP) + { + prop_fail_result = ctype == OP_NOTPROP; + prop_type = *ecode++; + prop_value = *ecode++; + } + else prop_type = -1; +#endif + + /* First, ensure the minimum number of matches are present. Use inline + code for maximizing the speed, and do the type test once at the start + (i.e. keep it out of the loop). Separate the UTF-8 code completely as that + is tidier. Also separate the UCP code, which can be the same for both UTF-8 + and single-bytes. */ + + if (min > 0) + { +#ifdef SUPPORT_UCP + if (prop_type >= 0) + { + switch(prop_type) + { + case PT_ANY: + if (prop_fail_result) RRETURN(MATCH_NOMATCH); + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINCTEST(c, eptr); + } + break; + + case PT_LAMP: + for (i = 1; i <= min; i++) + { + int chartype; + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINCTEST(c, eptr); + chartype = UCD_CHARTYPE(c); + if ((chartype == ucp_Lu || + chartype == ucp_Ll || + chartype == ucp_Lt) == prop_fail_result) + RRETURN(MATCH_NOMATCH); + } + break; + + case PT_GC: + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINCTEST(c, eptr); + if ((UCD_CATEGORY(c) == prop_value) == prop_fail_result) + RRETURN(MATCH_NOMATCH); + } + break; + + case PT_PC: + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINCTEST(c, eptr); + if ((UCD_CHARTYPE(c) == prop_value) == prop_fail_result) + RRETURN(MATCH_NOMATCH); + } + break; + + case PT_SC: + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINCTEST(c, eptr); + if ((UCD_SCRIPT(c) == prop_value) == prop_fail_result) + RRETURN(MATCH_NOMATCH); + } + break; + + case PT_ALNUM: + for (i = 1; i <= min; i++) + { + int category; + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINCTEST(c, eptr); + category = UCD_CATEGORY(c); + if ((category == ucp_L || category == ucp_N) == prop_fail_result) + RRETURN(MATCH_NOMATCH); + } + break; + + /* Perl space used to exclude VT, but from Perl 5.18 it is included, + which means that Perl space and POSIX space are now identical. PCRE + was changed at release 8.34. */ + + case PT_SPACE: /* Perl space */ + case PT_PXSPACE: /* POSIX space */ + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINCTEST(c, eptr); + switch(c) + { + HSPACE_CASES: + VSPACE_CASES: + if (prop_fail_result) RRETURN(MATCH_NOMATCH); + break; + + default: + if ((UCD_CATEGORY(c) == ucp_Z) == prop_fail_result) + RRETURN(MATCH_NOMATCH); + break; + } + } + break; + + case PT_WORD: + for (i = 1; i <= min; i++) + { + int category; + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINCTEST(c, eptr); + category = UCD_CATEGORY(c); + if ((category == ucp_L || category == ucp_N || c == CHAR_UNDERSCORE) + == prop_fail_result) + RRETURN(MATCH_NOMATCH); + } + break; + + case PT_CLIST: + for (i = 1; i <= min; i++) + { + const pcre_uint32 *cp; + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINCTEST(c, eptr); + cp = PRIV(ucd_caseless_sets) + prop_value; + for (;;) + { + if (c < *cp) + { if (prop_fail_result) break; else { RRETURN(MATCH_NOMATCH); } } + if (c == *cp++) + { if (prop_fail_result) { RRETURN(MATCH_NOMATCH); } else break; } + } + } + break; + + case PT_UCNC: + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINCTEST(c, eptr); + if ((c == CHAR_DOLLAR_SIGN || c == CHAR_COMMERCIAL_AT || + c == CHAR_GRAVE_ACCENT || (c >= 0xa0 && c <= 0xd7ff) || + c >= 0xe000) == prop_fail_result) + RRETURN(MATCH_NOMATCH); + } + break; + + /* This should not occur */ + + default: + RRETURN(PCRE_ERROR_INTERNAL); + } + } + + /* Match extended Unicode sequences. We will get here only if the + support is in the binary; otherwise a compile-time error occurs. */ + + else if (ctype == OP_EXTUNI) + { + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + else + { + int lgb, rgb; + GETCHARINCTEST(c, eptr); + lgb = UCD_GRAPHBREAK(c); + while (eptr < md->end_subject) + { + int len = 1; + if (!utf) c = *eptr; else { GETCHARLEN(c, eptr, len); } + rgb = UCD_GRAPHBREAK(c); + if ((PRIV(ucp_gbtable)[lgb] & (1 << rgb)) == 0) break; + lgb = rgb; + eptr += len; + } + } + CHECK_PARTIAL(); + } + } + + else +#endif /* SUPPORT_UCP */ + +/* Handle all other cases when the coding is UTF-8 */ + +#ifdef SUPPORT_UTF + if (utf) switch(ctype) + { + case OP_ANY: + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + if (IS_NEWLINE(eptr)) RRETURN(MATCH_NOMATCH); + if (md->partial != 0 && + eptr + 1 >= md->end_subject && + NLBLOCK->nltype == NLTYPE_FIXED && + NLBLOCK->nllen == 2 && + UCHAR21(eptr) == NLBLOCK->nl[0]) + { + md->hitend = TRUE; + if (md->partial > 1) RRETURN(PCRE_ERROR_PARTIAL); + } + eptr++; + ACROSSCHAR(eptr < md->end_subject, *eptr, eptr++); + } + break; + + case OP_ALLANY: + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + eptr++; + ACROSSCHAR(eptr < md->end_subject, *eptr, eptr++); + } + break; + + case OP_ANYBYTE: + if (eptr > md->end_subject - min) RRETURN(MATCH_NOMATCH); + eptr += min; + break; + + case OP_ANYNL: + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINC(c, eptr); + switch(c) + { + default: RRETURN(MATCH_NOMATCH); + + case CHAR_CR: + if (eptr < md->end_subject && UCHAR21(eptr) == CHAR_LF) eptr++; + break; + + case CHAR_LF: + break; + + case CHAR_VT: + case CHAR_FF: + case CHAR_NEL: +#ifndef EBCDIC + case 0x2028: + case 0x2029: +#endif /* Not EBCDIC */ + if (md->bsr_anycrlf) RRETURN(MATCH_NOMATCH); + break; + } + } + break; + + case OP_NOT_HSPACE: + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINC(c, eptr); + switch(c) + { + HSPACE_CASES: RRETURN(MATCH_NOMATCH); /* Byte and multibyte cases */ + default: break; + } + } + break; + + case OP_HSPACE: + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINC(c, eptr); + switch(c) + { + HSPACE_CASES: break; /* Byte and multibyte cases */ + default: RRETURN(MATCH_NOMATCH); + } + } + break; + + case OP_NOT_VSPACE: + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINC(c, eptr); + switch(c) + { + VSPACE_CASES: RRETURN(MATCH_NOMATCH); + default: break; + } + } + break; + + case OP_VSPACE: + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINC(c, eptr); + switch(c) + { + VSPACE_CASES: break; + default: RRETURN(MATCH_NOMATCH); + } + } + break; + + case OP_NOT_DIGIT: + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINC(c, eptr); + if (c < 128 && (md->ctypes[c] & ctype_digit) != 0) + RRETURN(MATCH_NOMATCH); + } + break; + + case OP_DIGIT: + for (i = 1; i <= min; i++) + { + pcre_uint32 cc; + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + cc = UCHAR21(eptr); + if (cc >= 128 || (md->ctypes[cc] & ctype_digit) == 0) + RRETURN(MATCH_NOMATCH); + eptr++; + /* No need to skip more bytes - we know it's a 1-byte character */ + } + break; + + case OP_NOT_WHITESPACE: + for (i = 1; i <= min; i++) + { + pcre_uint32 cc; + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + cc = UCHAR21(eptr); + if (cc < 128 && (md->ctypes[cc] & ctype_space) != 0) + RRETURN(MATCH_NOMATCH); + eptr++; + ACROSSCHAR(eptr < md->end_subject, *eptr, eptr++); + } + break; + + case OP_WHITESPACE: + for (i = 1; i <= min; i++) + { + pcre_uint32 cc; + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + cc = UCHAR21(eptr); + if (cc >= 128 || (md->ctypes[cc] & ctype_space) == 0) + RRETURN(MATCH_NOMATCH); + eptr++; + /* No need to skip more bytes - we know it's a 1-byte character */ + } + break; + + case OP_NOT_WORDCHAR: + for (i = 1; i <= min; i++) + { + pcre_uint32 cc; + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + cc = UCHAR21(eptr); + if (cc < 128 && (md->ctypes[cc] & ctype_word) != 0) + RRETURN(MATCH_NOMATCH); + eptr++; + ACROSSCHAR(eptr < md->end_subject, *eptr, eptr++); + } + break; + + case OP_WORDCHAR: + for (i = 1; i <= min; i++) + { + pcre_uint32 cc; + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + cc = UCHAR21(eptr); + if (cc >= 128 || (md->ctypes[cc] & ctype_word) == 0) + RRETURN(MATCH_NOMATCH); + eptr++; + /* No need to skip more bytes - we know it's a 1-byte character */ + } + break; + + default: + RRETURN(PCRE_ERROR_INTERNAL); + } /* End switch(ctype) */ + + else +#endif /* SUPPORT_UTF */ + + /* Code for the non-UTF-8 case for minimum matching of operators other + than OP_PROP and OP_NOTPROP. */ + + switch(ctype) + { + case OP_ANY: + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + if (IS_NEWLINE(eptr)) RRETURN(MATCH_NOMATCH); + if (md->partial != 0 && + eptr + 1 >= md->end_subject && + NLBLOCK->nltype == NLTYPE_FIXED && + NLBLOCK->nllen == 2 && + *eptr == NLBLOCK->nl[0]) + { + md->hitend = TRUE; + if (md->partial > 1) RRETURN(PCRE_ERROR_PARTIAL); + } + eptr++; + } + break; + + case OP_ALLANY: + if (eptr > md->end_subject - min) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + eptr += min; + break; + + case OP_ANYBYTE: + if (eptr > md->end_subject - min) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + eptr += min; + break; + + case OP_ANYNL: + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + switch(*eptr++) + { + default: RRETURN(MATCH_NOMATCH); + + case CHAR_CR: + if (eptr < md->end_subject && *eptr == CHAR_LF) eptr++; + break; + + case CHAR_LF: + break; + + case CHAR_VT: + case CHAR_FF: + case CHAR_NEL: +#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 + case 0x2028: + case 0x2029: +#endif + if (md->bsr_anycrlf) RRETURN(MATCH_NOMATCH); + break; + } + } + break; + + case OP_NOT_HSPACE: + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + switch(*eptr++) + { + default: break; + HSPACE_BYTE_CASES: +#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 + HSPACE_MULTIBYTE_CASES: +#endif + RRETURN(MATCH_NOMATCH); + } + } + break; + + case OP_HSPACE: + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + switch(*eptr++) + { + default: RRETURN(MATCH_NOMATCH); + HSPACE_BYTE_CASES: +#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 + HSPACE_MULTIBYTE_CASES: +#endif + break; + } + } + break; + + case OP_NOT_VSPACE: + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + switch(*eptr++) + { + VSPACE_BYTE_CASES: +#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 + VSPACE_MULTIBYTE_CASES: +#endif + RRETURN(MATCH_NOMATCH); + default: break; + } + } + break; + + case OP_VSPACE: + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + switch(*eptr++) + { + default: RRETURN(MATCH_NOMATCH); + VSPACE_BYTE_CASES: +#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 + VSPACE_MULTIBYTE_CASES: +#endif + break; + } + } + break; + + case OP_NOT_DIGIT: + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + if (MAX_255(*eptr) && (md->ctypes[*eptr] & ctype_digit) != 0) + RRETURN(MATCH_NOMATCH); + eptr++; + } + break; + + case OP_DIGIT: + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + if (!MAX_255(*eptr) || (md->ctypes[*eptr] & ctype_digit) == 0) + RRETURN(MATCH_NOMATCH); + eptr++; + } + break; + + case OP_NOT_WHITESPACE: + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + if (MAX_255(*eptr) && (md->ctypes[*eptr] & ctype_space) != 0) + RRETURN(MATCH_NOMATCH); + eptr++; + } + break; + + case OP_WHITESPACE: + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + if (!MAX_255(*eptr) || (md->ctypes[*eptr] & ctype_space) == 0) + RRETURN(MATCH_NOMATCH); + eptr++; + } + break; + + case OP_NOT_WORDCHAR: + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + if (MAX_255(*eptr) && (md->ctypes[*eptr] & ctype_word) != 0) + RRETURN(MATCH_NOMATCH); + eptr++; + } + break; + + case OP_WORDCHAR: + for (i = 1; i <= min; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + if (!MAX_255(*eptr) || (md->ctypes[*eptr] & ctype_word) == 0) + RRETURN(MATCH_NOMATCH); + eptr++; + } + break; + + default: + RRETURN(PCRE_ERROR_INTERNAL); + } + } + + /* If min = max, continue at the same level without recursing */ + + if (min == max) continue; + + /* If minimizing, we have to test the rest of the pattern before each + subsequent match. Again, separate the UTF-8 case for speed, and also + separate the UCP cases. */ + + if (minimize) + { +#ifdef SUPPORT_UCP + if (prop_type >= 0) + { + switch(prop_type) + { + case PT_ANY: + for (fi = min;; fi++) + { + RMATCH(eptr, ecode, offset_top, md, eptrb, RM36); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (fi >= max) RRETURN(MATCH_NOMATCH); + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINCTEST(c, eptr); + if (prop_fail_result) RRETURN(MATCH_NOMATCH); + } + /* Control never gets here */ + + case PT_LAMP: + for (fi = min;; fi++) + { + int chartype; + RMATCH(eptr, ecode, offset_top, md, eptrb, RM37); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (fi >= max) RRETURN(MATCH_NOMATCH); + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINCTEST(c, eptr); + chartype = UCD_CHARTYPE(c); + if ((chartype == ucp_Lu || + chartype == ucp_Ll || + chartype == ucp_Lt) == prop_fail_result) + RRETURN(MATCH_NOMATCH); + } + /* Control never gets here */ + + case PT_GC: + for (fi = min;; fi++) + { + RMATCH(eptr, ecode, offset_top, md, eptrb, RM38); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (fi >= max) RRETURN(MATCH_NOMATCH); + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINCTEST(c, eptr); + if ((UCD_CATEGORY(c) == prop_value) == prop_fail_result) + RRETURN(MATCH_NOMATCH); + } + /* Control never gets here */ + + case PT_PC: + for (fi = min;; fi++) + { + RMATCH(eptr, ecode, offset_top, md, eptrb, RM39); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (fi >= max) RRETURN(MATCH_NOMATCH); + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINCTEST(c, eptr); + if ((UCD_CHARTYPE(c) == prop_value) == prop_fail_result) + RRETURN(MATCH_NOMATCH); + } + /* Control never gets here */ + + case PT_SC: + for (fi = min;; fi++) + { + RMATCH(eptr, ecode, offset_top, md, eptrb, RM40); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (fi >= max) RRETURN(MATCH_NOMATCH); + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINCTEST(c, eptr); + if ((UCD_SCRIPT(c) == prop_value) == prop_fail_result) + RRETURN(MATCH_NOMATCH); + } + /* Control never gets here */ + + case PT_ALNUM: + for (fi = min;; fi++) + { + int category; + RMATCH(eptr, ecode, offset_top, md, eptrb, RM59); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (fi >= max) RRETURN(MATCH_NOMATCH); + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINCTEST(c, eptr); + category = UCD_CATEGORY(c); + if ((category == ucp_L || category == ucp_N) == prop_fail_result) + RRETURN(MATCH_NOMATCH); + } + /* Control never gets here */ + + /* Perl space used to exclude VT, but from Perl 5.18 it is included, + which means that Perl space and POSIX space are now identical. PCRE + was changed at release 8.34. */ + + case PT_SPACE: /* Perl space */ + case PT_PXSPACE: /* POSIX space */ + for (fi = min;; fi++) + { + RMATCH(eptr, ecode, offset_top, md, eptrb, RM61); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (fi >= max) RRETURN(MATCH_NOMATCH); + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINCTEST(c, eptr); + switch(c) + { + HSPACE_CASES: + VSPACE_CASES: + if (prop_fail_result) RRETURN(MATCH_NOMATCH); + break; + + default: + if ((UCD_CATEGORY(c) == ucp_Z) == prop_fail_result) + RRETURN(MATCH_NOMATCH); + break; + } + } + /* Control never gets here */ + + case PT_WORD: + for (fi = min;; fi++) + { + int category; + RMATCH(eptr, ecode, offset_top, md, eptrb, RM62); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (fi >= max) RRETURN(MATCH_NOMATCH); + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINCTEST(c, eptr); + category = UCD_CATEGORY(c); + if ((category == ucp_L || + category == ucp_N || + c == CHAR_UNDERSCORE) + == prop_fail_result) + RRETURN(MATCH_NOMATCH); + } + /* Control never gets here */ + + case PT_CLIST: + for (fi = min;; fi++) + { + const pcre_uint32 *cp; + RMATCH(eptr, ecode, offset_top, md, eptrb, RM67); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (fi >= max) RRETURN(MATCH_NOMATCH); + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINCTEST(c, eptr); + cp = PRIV(ucd_caseless_sets) + prop_value; + for (;;) + { + if (c < *cp) + { if (prop_fail_result) break; else { RRETURN(MATCH_NOMATCH); } } + if (c == *cp++) + { if (prop_fail_result) { RRETURN(MATCH_NOMATCH); } else break; } + } + } + /* Control never gets here */ + + case PT_UCNC: + for (fi = min;; fi++) + { + RMATCH(eptr, ecode, offset_top, md, eptrb, RM60); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (fi >= max) RRETURN(MATCH_NOMATCH); + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + GETCHARINCTEST(c, eptr); + if ((c == CHAR_DOLLAR_SIGN || c == CHAR_COMMERCIAL_AT || + c == CHAR_GRAVE_ACCENT || (c >= 0xa0 && c <= 0xd7ff) || + c >= 0xe000) == prop_fail_result) + RRETURN(MATCH_NOMATCH); + } + /* Control never gets here */ + + /* This should never occur */ + default: + RRETURN(PCRE_ERROR_INTERNAL); + } + } + + /* Match extended Unicode sequences. We will get here only if the + support is in the binary; otherwise a compile-time error occurs. */ + + else if (ctype == OP_EXTUNI) + { + for (fi = min;; fi++) + { + RMATCH(eptr, ecode, offset_top, md, eptrb, RM41); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (fi >= max) RRETURN(MATCH_NOMATCH); + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + else + { + int lgb, rgb; + GETCHARINCTEST(c, eptr); + lgb = UCD_GRAPHBREAK(c); + while (eptr < md->end_subject) + { + int len = 1; + if (!utf) c = *eptr; else { GETCHARLEN(c, eptr, len); } + rgb = UCD_GRAPHBREAK(c); + if ((PRIV(ucp_gbtable)[lgb] & (1 << rgb)) == 0) break; + lgb = rgb; + eptr += len; + } + } + CHECK_PARTIAL(); + } + } + else +#endif /* SUPPORT_UCP */ + +#ifdef SUPPORT_UTF + if (utf) + { + for (fi = min;; fi++) + { + RMATCH(eptr, ecode, offset_top, md, eptrb, RM42); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (fi >= max) RRETURN(MATCH_NOMATCH); + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + if (ctype == OP_ANY && IS_NEWLINE(eptr)) + RRETURN(MATCH_NOMATCH); + GETCHARINC(c, eptr); + switch(ctype) + { + case OP_ANY: /* This is the non-NL case */ + if (md->partial != 0 && /* Take care with CRLF partial */ + eptr >= md->end_subject && + NLBLOCK->nltype == NLTYPE_FIXED && + NLBLOCK->nllen == 2 && + c == NLBLOCK->nl[0]) + { + md->hitend = TRUE; + if (md->partial > 1) RRETURN(PCRE_ERROR_PARTIAL); + } + break; + + case OP_ALLANY: + case OP_ANYBYTE: + break; + + case OP_ANYNL: + switch(c) + { + default: RRETURN(MATCH_NOMATCH); + case CHAR_CR: + if (eptr < md->end_subject && UCHAR21(eptr) == CHAR_LF) eptr++; + break; + + case CHAR_LF: + break; + + case CHAR_VT: + case CHAR_FF: + case CHAR_NEL: +#ifndef EBCDIC + case 0x2028: + case 0x2029: +#endif /* Not EBCDIC */ + if (md->bsr_anycrlf) RRETURN(MATCH_NOMATCH); + break; + } + break; + + case OP_NOT_HSPACE: + switch(c) + { + HSPACE_CASES: RRETURN(MATCH_NOMATCH); + default: break; + } + break; + + case OP_HSPACE: + switch(c) + { + HSPACE_CASES: break; + default: RRETURN(MATCH_NOMATCH); + } + break; + + case OP_NOT_VSPACE: + switch(c) + { + VSPACE_CASES: RRETURN(MATCH_NOMATCH); + default: break; + } + break; + + case OP_VSPACE: + switch(c) + { + VSPACE_CASES: break; + default: RRETURN(MATCH_NOMATCH); + } + break; + + case OP_NOT_DIGIT: + if (c < 256 && (md->ctypes[c] & ctype_digit) != 0) + RRETURN(MATCH_NOMATCH); + break; + + case OP_DIGIT: + if (c >= 256 || (md->ctypes[c] & ctype_digit) == 0) + RRETURN(MATCH_NOMATCH); + break; + + case OP_NOT_WHITESPACE: + if (c < 256 && (md->ctypes[c] & ctype_space) != 0) + RRETURN(MATCH_NOMATCH); + break; + + case OP_WHITESPACE: + if (c >= 256 || (md->ctypes[c] & ctype_space) == 0) + RRETURN(MATCH_NOMATCH); + break; + + case OP_NOT_WORDCHAR: + if (c < 256 && (md->ctypes[c] & ctype_word) != 0) + RRETURN(MATCH_NOMATCH); + break; + + case OP_WORDCHAR: + if (c >= 256 || (md->ctypes[c] & ctype_word) == 0) + RRETURN(MATCH_NOMATCH); + break; + + default: + RRETURN(PCRE_ERROR_INTERNAL); + } + } + } + else +#endif + /* Not UTF mode */ + { + for (fi = min;; fi++) + { + RMATCH(eptr, ecode, offset_top, md, eptrb, RM43); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + if (fi >= max) RRETURN(MATCH_NOMATCH); + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + RRETURN(MATCH_NOMATCH); + } + if (ctype == OP_ANY && IS_NEWLINE(eptr)) + RRETURN(MATCH_NOMATCH); + c = *eptr++; + switch(ctype) + { + case OP_ANY: /* This is the non-NL case */ + if (md->partial != 0 && /* Take care with CRLF partial */ + eptr >= md->end_subject && + NLBLOCK->nltype == NLTYPE_FIXED && + NLBLOCK->nllen == 2 && + c == NLBLOCK->nl[0]) + { + md->hitend = TRUE; + if (md->partial > 1) RRETURN(PCRE_ERROR_PARTIAL); + } + break; + + case OP_ALLANY: + case OP_ANYBYTE: + break; + + case OP_ANYNL: + switch(c) + { + default: RRETURN(MATCH_NOMATCH); + case CHAR_CR: + if (eptr < md->end_subject && *eptr == CHAR_LF) eptr++; + break; + + case CHAR_LF: + break; + + case CHAR_VT: + case CHAR_FF: + case CHAR_NEL: +#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 + case 0x2028: + case 0x2029: +#endif + if (md->bsr_anycrlf) RRETURN(MATCH_NOMATCH); + break; + } + break; + + case OP_NOT_HSPACE: + switch(c) + { + default: break; + HSPACE_BYTE_CASES: +#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 + HSPACE_MULTIBYTE_CASES: +#endif + RRETURN(MATCH_NOMATCH); + } + break; + + case OP_HSPACE: + switch(c) + { + default: RRETURN(MATCH_NOMATCH); + HSPACE_BYTE_CASES: +#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 + HSPACE_MULTIBYTE_CASES: +#endif + break; + } + break; + + case OP_NOT_VSPACE: + switch(c) + { + default: break; + VSPACE_BYTE_CASES: +#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 + VSPACE_MULTIBYTE_CASES: +#endif + RRETURN(MATCH_NOMATCH); + } + break; + + case OP_VSPACE: + switch(c) + { + default: RRETURN(MATCH_NOMATCH); + VSPACE_BYTE_CASES: +#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 + VSPACE_MULTIBYTE_CASES: +#endif + break; + } + break; + + case OP_NOT_DIGIT: + if (MAX_255(c) && (md->ctypes[c] & ctype_digit) != 0) RRETURN(MATCH_NOMATCH); + break; + + case OP_DIGIT: + if (!MAX_255(c) || (md->ctypes[c] & ctype_digit) == 0) RRETURN(MATCH_NOMATCH); + break; + + case OP_NOT_WHITESPACE: + if (MAX_255(c) && (md->ctypes[c] & ctype_space) != 0) RRETURN(MATCH_NOMATCH); + break; + + case OP_WHITESPACE: + if (!MAX_255(c) || (md->ctypes[c] & ctype_space) == 0) RRETURN(MATCH_NOMATCH); + break; + + case OP_NOT_WORDCHAR: + if (MAX_255(c) && (md->ctypes[c] & ctype_word) != 0) RRETURN(MATCH_NOMATCH); + break; + + case OP_WORDCHAR: + if (!MAX_255(c) || (md->ctypes[c] & ctype_word) == 0) RRETURN(MATCH_NOMATCH); + break; + + default: + RRETURN(PCRE_ERROR_INTERNAL); + } + } + } + /* Control never gets here */ + } + + /* If maximizing, it is worth using inline code for speed, doing the type + test once at the start (i.e. keep it out of the loop). Again, keep the + UTF-8 and UCP stuff separate. */ + + else + { + pp = eptr; /* Remember where we started */ + +#ifdef SUPPORT_UCP + if (prop_type >= 0) + { + switch(prop_type) + { + case PT_ANY: + for (i = min; i < max; i++) + { + int len = 1; + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + break; + } + GETCHARLENTEST(c, eptr, len); + if (prop_fail_result) break; + eptr+= len; + } + break; + + case PT_LAMP: + for (i = min; i < max; i++) + { + int chartype; + int len = 1; + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + break; + } + GETCHARLENTEST(c, eptr, len); + chartype = UCD_CHARTYPE(c); + if ((chartype == ucp_Lu || + chartype == ucp_Ll || + chartype == ucp_Lt) == prop_fail_result) + break; + eptr+= len; + } + break; + + case PT_GC: + for (i = min; i < max; i++) + { + int len = 1; + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + break; + } + GETCHARLENTEST(c, eptr, len); + if ((UCD_CATEGORY(c) == prop_value) == prop_fail_result) break; + eptr+= len; + } + break; + + case PT_PC: + for (i = min; i < max; i++) + { + int len = 1; + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + break; + } + GETCHARLENTEST(c, eptr, len); + if ((UCD_CHARTYPE(c) == prop_value) == prop_fail_result) break; + eptr+= len; + } + break; + + case PT_SC: + for (i = min; i < max; i++) + { + int len = 1; + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + break; + } + GETCHARLENTEST(c, eptr, len); + if ((UCD_SCRIPT(c) == prop_value) == prop_fail_result) break; + eptr+= len; + } + break; + + case PT_ALNUM: + for (i = min; i < max; i++) + { + int category; + int len = 1; + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + break; + } + GETCHARLENTEST(c, eptr, len); + category = UCD_CATEGORY(c); + if ((category == ucp_L || category == ucp_N) == prop_fail_result) + break; + eptr+= len; + } + break; + + /* Perl space used to exclude VT, but from Perl 5.18 it is included, + which means that Perl space and POSIX space are now identical. PCRE + was changed at release 8.34. */ + + case PT_SPACE: /* Perl space */ + case PT_PXSPACE: /* POSIX space */ + for (i = min; i < max; i++) + { + int len = 1; + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + break; + } + GETCHARLENTEST(c, eptr, len); + switch(c) + { + HSPACE_CASES: + VSPACE_CASES: + if (prop_fail_result) goto ENDLOOP99; /* Break the loop */ + break; + + default: + if ((UCD_CATEGORY(c) == ucp_Z) == prop_fail_result) + goto ENDLOOP99; /* Break the loop */ + break; + } + eptr+= len; + } + ENDLOOP99: + break; + + case PT_WORD: + for (i = min; i < max; i++) + { + int category; + int len = 1; + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + break; + } + GETCHARLENTEST(c, eptr, len); + category = UCD_CATEGORY(c); + if ((category == ucp_L || category == ucp_N || + c == CHAR_UNDERSCORE) == prop_fail_result) + break; + eptr+= len; + } + break; + + case PT_CLIST: + for (i = min; i < max; i++) + { + const pcre_uint32 *cp; + int len = 1; + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + break; + } + GETCHARLENTEST(c, eptr, len); + cp = PRIV(ucd_caseless_sets) + prop_value; + for (;;) + { + if (c < *cp) + { if (prop_fail_result) break; else goto GOT_MAX; } + if (c == *cp++) + { if (prop_fail_result) goto GOT_MAX; else break; } + } + eptr += len; + } + GOT_MAX: + break; + + case PT_UCNC: + for (i = min; i < max; i++) + { + int len = 1; + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + break; + } + GETCHARLENTEST(c, eptr, len); + if ((c == CHAR_DOLLAR_SIGN || c == CHAR_COMMERCIAL_AT || + c == CHAR_GRAVE_ACCENT || (c >= 0xa0 && c <= 0xd7ff) || + c >= 0xe000) == prop_fail_result) + break; + eptr += len; + } + break; + + default: + RRETURN(PCRE_ERROR_INTERNAL); + } + + /* eptr is now past the end of the maximum run */ + + if (possessive) continue; /* No backtracking */ + for(;;) + { + if (eptr == pp) goto TAIL_RECURSE; + RMATCH(eptr, ecode, offset_top, md, eptrb, RM44); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + eptr--; + if (utf) BACKCHAR(eptr); + } + } + + /* Match extended Unicode grapheme clusters. We will get here only if the + support is in the binary; otherwise a compile-time error occurs. */ + + else if (ctype == OP_EXTUNI) + { + for (i = min; i < max; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + break; + } + else + { + int lgb, rgb; + GETCHARINCTEST(c, eptr); + lgb = UCD_GRAPHBREAK(c); + while (eptr < md->end_subject) + { + int len = 1; + if (!utf) c = *eptr; else { GETCHARLEN(c, eptr, len); } + rgb = UCD_GRAPHBREAK(c); + if ((PRIV(ucp_gbtable)[lgb] & (1 << rgb)) == 0) break; + lgb = rgb; + eptr += len; + } + } + CHECK_PARTIAL(); + } + + /* eptr is now past the end of the maximum run */ + + if (possessive) continue; /* No backtracking */ + + for(;;) + { + int lgb, rgb; + PCRE_PUCHAR fptr; + + if (eptr == pp) goto TAIL_RECURSE; /* At start of char run */ + RMATCH(eptr, ecode, offset_top, md, eptrb, RM45); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + + /* Backtracking over an extended grapheme cluster involves inspecting + the previous two characters (if present) to see if a break is + permitted between them. */ + + eptr--; + if (!utf) c = *eptr; else + { + BACKCHAR(eptr); + GETCHAR(c, eptr); + } + rgb = UCD_GRAPHBREAK(c); + + for (;;) + { + if (eptr == pp) goto TAIL_RECURSE; /* At start of char run */ + fptr = eptr - 1; + if (!utf) c = *fptr; else + { + BACKCHAR(fptr); + GETCHAR(c, fptr); + } + lgb = UCD_GRAPHBREAK(c); + if ((PRIV(ucp_gbtable)[lgb] & (1 << rgb)) == 0) break; + eptr = fptr; + rgb = lgb; + } + } + } + + else +#endif /* SUPPORT_UCP */ + +#ifdef SUPPORT_UTF + if (utf) + { + switch(ctype) + { + case OP_ANY: + for (i = min; i < max; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + break; + } + if (IS_NEWLINE(eptr)) break; + if (md->partial != 0 && /* Take care with CRLF partial */ + eptr + 1 >= md->end_subject && + NLBLOCK->nltype == NLTYPE_FIXED && + NLBLOCK->nllen == 2 && + UCHAR21(eptr) == NLBLOCK->nl[0]) + { + md->hitend = TRUE; + if (md->partial > 1) RRETURN(PCRE_ERROR_PARTIAL); + } + eptr++; + ACROSSCHAR(eptr < md->end_subject, *eptr, eptr++); + } + break; + + case OP_ALLANY: + if (max < INT_MAX) + { + for (i = min; i < max; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + break; + } + eptr++; + ACROSSCHAR(eptr < md->end_subject, *eptr, eptr++); + } + } + else + { + eptr = md->end_subject; /* Unlimited UTF-8 repeat */ + SCHECK_PARTIAL(); + } + break; + + /* The byte case is the same as non-UTF8 */ + + case OP_ANYBYTE: + c = max - min; + if (c > (unsigned int)(md->end_subject - eptr)) + { + eptr = md->end_subject; + SCHECK_PARTIAL(); + } + else eptr += c; + break; + + case OP_ANYNL: + for (i = min; i < max; i++) + { + int len = 1; + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + break; + } + GETCHARLEN(c, eptr, len); + if (c == CHAR_CR) + { + if (++eptr >= md->end_subject) break; + if (UCHAR21(eptr) == CHAR_LF) eptr++; + } + else + { + if (c != CHAR_LF && + (md->bsr_anycrlf || + (c != CHAR_VT && c != CHAR_FF && c != CHAR_NEL +#ifndef EBCDIC + && c != 0x2028 && c != 0x2029 +#endif /* Not EBCDIC */ + ))) + break; + eptr += len; + } + } + break; + + case OP_NOT_HSPACE: + case OP_HSPACE: + for (i = min; i < max; i++) + { + BOOL gotspace; + int len = 1; + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + break; + } + GETCHARLEN(c, eptr, len); + switch(c) + { + HSPACE_CASES: gotspace = TRUE; break; + default: gotspace = FALSE; break; + } + if (gotspace == (ctype == OP_NOT_HSPACE)) break; + eptr += len; + } + break; + + case OP_NOT_VSPACE: + case OP_VSPACE: + for (i = min; i < max; i++) + { + BOOL gotspace; + int len = 1; + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + break; + } + GETCHARLEN(c, eptr, len); + switch(c) + { + VSPACE_CASES: gotspace = TRUE; break; + default: gotspace = FALSE; break; + } + if (gotspace == (ctype == OP_NOT_VSPACE)) break; + eptr += len; + } + break; + + case OP_NOT_DIGIT: + for (i = min; i < max; i++) + { + int len = 1; + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + break; + } + GETCHARLEN(c, eptr, len); + if (c < 256 && (md->ctypes[c] & ctype_digit) != 0) break; + eptr+= len; + } + break; + + case OP_DIGIT: + for (i = min; i < max; i++) + { + int len = 1; + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + break; + } + GETCHARLEN(c, eptr, len); + if (c >= 256 ||(md->ctypes[c] & ctype_digit) == 0) break; + eptr+= len; + } + break; + + case OP_NOT_WHITESPACE: + for (i = min; i < max; i++) + { + int len = 1; + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + break; + } + GETCHARLEN(c, eptr, len); + if (c < 256 && (md->ctypes[c] & ctype_space) != 0) break; + eptr+= len; + } + break; + + case OP_WHITESPACE: + for (i = min; i < max; i++) + { + int len = 1; + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + break; + } + GETCHARLEN(c, eptr, len); + if (c >= 256 ||(md->ctypes[c] & ctype_space) == 0) break; + eptr+= len; + } + break; + + case OP_NOT_WORDCHAR: + for (i = min; i < max; i++) + { + int len = 1; + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + break; + } + GETCHARLEN(c, eptr, len); + if (c < 256 && (md->ctypes[c] & ctype_word) != 0) break; + eptr+= len; + } + break; + + case OP_WORDCHAR: + for (i = min; i < max; i++) + { + int len = 1; + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + break; + } + GETCHARLEN(c, eptr, len); + if (c >= 256 || (md->ctypes[c] & ctype_word) == 0) break; + eptr+= len; + } + break; + + default: + RRETURN(PCRE_ERROR_INTERNAL); + } + + if (possessive) continue; /* No backtracking */ + for(;;) + { + if (eptr == pp) goto TAIL_RECURSE; + RMATCH(eptr, ecode, offset_top, md, eptrb, RM46); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + eptr--; + BACKCHAR(eptr); + if (ctype == OP_ANYNL && eptr > pp && UCHAR21(eptr) == CHAR_NL && + UCHAR21(eptr - 1) == CHAR_CR) eptr--; + } + } + else +#endif /* SUPPORT_UTF */ + /* Not UTF mode */ + { + switch(ctype) + { + case OP_ANY: + for (i = min; i < max; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + break; + } + if (IS_NEWLINE(eptr)) break; + if (md->partial != 0 && /* Take care with CRLF partial */ + eptr + 1 >= md->end_subject && + NLBLOCK->nltype == NLTYPE_FIXED && + NLBLOCK->nllen == 2 && + *eptr == NLBLOCK->nl[0]) + { + md->hitend = TRUE; + if (md->partial > 1) RRETURN(PCRE_ERROR_PARTIAL); + } + eptr++; + } + break; + + case OP_ALLANY: + case OP_ANYBYTE: + c = max - min; + if (c > (unsigned int)(md->end_subject - eptr)) + { + eptr = md->end_subject; + SCHECK_PARTIAL(); + } + else eptr += c; + break; + + case OP_ANYNL: + for (i = min; i < max; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + break; + } + c = *eptr; + if (c == CHAR_CR) + { + if (++eptr >= md->end_subject) break; + if (*eptr == CHAR_LF) eptr++; + } + else + { + if (c != CHAR_LF && (md->bsr_anycrlf || + (c != CHAR_VT && c != CHAR_FF && c != CHAR_NEL +#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 + && c != 0x2028 && c != 0x2029 +#endif + ))) break; + eptr++; + } + } + break; + + case OP_NOT_HSPACE: + for (i = min; i < max; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + break; + } + switch(*eptr) + { + default: eptr++; break; + HSPACE_BYTE_CASES: +#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 + HSPACE_MULTIBYTE_CASES: +#endif + goto ENDLOOP00; + } + } + ENDLOOP00: + break; + + case OP_HSPACE: + for (i = min; i < max; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + break; + } + switch(*eptr) + { + default: goto ENDLOOP01; + HSPACE_BYTE_CASES: +#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 + HSPACE_MULTIBYTE_CASES: +#endif + eptr++; break; + } + } + ENDLOOP01: + break; + + case OP_NOT_VSPACE: + for (i = min; i < max; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + break; + } + switch(*eptr) + { + default: eptr++; break; + VSPACE_BYTE_CASES: +#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 + VSPACE_MULTIBYTE_CASES: +#endif + goto ENDLOOP02; + } + } + ENDLOOP02: + break; + + case OP_VSPACE: + for (i = min; i < max; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + break; + } + switch(*eptr) + { + default: goto ENDLOOP03; + VSPACE_BYTE_CASES: +#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 + VSPACE_MULTIBYTE_CASES: +#endif + eptr++; break; + } + } + ENDLOOP03: + break; + + case OP_NOT_DIGIT: + for (i = min; i < max; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + break; + } + if (MAX_255(*eptr) && (md->ctypes[*eptr] & ctype_digit) != 0) break; + eptr++; + } + break; + + case OP_DIGIT: + for (i = min; i < max; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + break; + } + if (!MAX_255(*eptr) || (md->ctypes[*eptr] & ctype_digit) == 0) break; + eptr++; + } + break; + + case OP_NOT_WHITESPACE: + for (i = min; i < max; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + break; + } + if (MAX_255(*eptr) && (md->ctypes[*eptr] & ctype_space) != 0) break; + eptr++; + } + break; + + case OP_WHITESPACE: + for (i = min; i < max; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + break; + } + if (!MAX_255(*eptr) || (md->ctypes[*eptr] & ctype_space) == 0) break; + eptr++; + } + break; + + case OP_NOT_WORDCHAR: + for (i = min; i < max; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + break; + } + if (MAX_255(*eptr) && (md->ctypes[*eptr] & ctype_word) != 0) break; + eptr++; + } + break; + + case OP_WORDCHAR: + for (i = min; i < max; i++) + { + if (eptr >= md->end_subject) + { + SCHECK_PARTIAL(); + break; + } + if (!MAX_255(*eptr) || (md->ctypes[*eptr] & ctype_word) == 0) break; + eptr++; + } + break; + + default: + RRETURN(PCRE_ERROR_INTERNAL); + } + + if (possessive) continue; /* No backtracking */ + for (;;) + { + if (eptr == pp) goto TAIL_RECURSE; + RMATCH(eptr, ecode, offset_top, md, eptrb, RM47); + if (rrc != MATCH_NOMATCH) RRETURN(rrc); + eptr--; + if (ctype == OP_ANYNL && eptr > pp && *eptr == CHAR_LF && + eptr[-1] == CHAR_CR) eptr--; + } + } + + /* Control never gets here */ + } + + /* There's been some horrible disaster. Arrival here can only mean there is + something seriously wrong in the code above or the OP_xxx definitions. */ + + default: + DPRINTF(("Unknown opcode %d\n", *ecode)); + RRETURN(PCRE_ERROR_UNKNOWN_OPCODE); + } + + /* Do not stick any code in here without much thought; it is assumed + that "continue" in the code above comes out to here to repeat the main + loop. */ + + } /* End of main loop */ +/* Control never reaches here */ + + +/* When compiling to use the heap rather than the stack for recursive calls to +match(), the RRETURN() macro jumps here. The number that is saved in +frame->Xwhere indicates which label we actually want to return to. */ + +#ifdef NO_RECURSE +#define LBL(val) case val: goto L_RM##val; +HEAP_RETURN: +switch (frame->Xwhere) + { + LBL( 1) LBL( 2) LBL( 3) LBL( 4) LBL( 5) LBL( 6) LBL( 7) LBL( 8) + LBL( 9) LBL(10) LBL(11) LBL(12) LBL(13) LBL(14) LBL(15) LBL(17) + LBL(19) LBL(24) LBL(25) LBL(26) LBL(27) LBL(29) LBL(31) LBL(33) + LBL(35) LBL(43) LBL(47) LBL(48) LBL(49) LBL(50) LBL(51) LBL(52) + LBL(53) LBL(54) LBL(55) LBL(56) LBL(57) LBL(58) LBL(63) LBL(64) + LBL(65) LBL(66) +#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 + LBL(20) LBL(21) +#endif +#ifdef SUPPORT_UTF + LBL(16) LBL(18) + LBL(22) LBL(23) LBL(28) LBL(30) + LBL(32) LBL(34) LBL(42) LBL(46) +#ifdef SUPPORT_UCP + LBL(36) LBL(37) LBL(38) LBL(39) LBL(40) LBL(41) LBL(44) LBL(45) + LBL(59) LBL(60) LBL(61) LBL(62) LBL(67) +#endif /* SUPPORT_UCP */ +#endif /* SUPPORT_UTF */ + default: + DPRINTF(("jump error in pcre match: label %d non-existent\n", frame->Xwhere)); + return PCRE_ERROR_INTERNAL; + } +#undef LBL +#endif /* NO_RECURSE */ +} + + +/*************************************************************************** +**************************************************************************** + RECURSION IN THE match() FUNCTION + +Undefine all the macros that were defined above to handle this. */ + +#ifdef NO_RECURSE +#undef eptr +#undef ecode +#undef mstart +#undef offset_top +#undef eptrb +#undef flags + +#undef callpat +#undef charptr +#undef data +#undef next +#undef pp +#undef prev +#undef saved_eptr + +#undef new_recursive + +#undef cur_is_word +#undef condition +#undef prev_is_word + +#undef ctype +#undef length +#undef max +#undef min +#undef number +#undef offset +#undef op +#undef save_capture_last +#undef save_offset1 +#undef save_offset2 +#undef save_offset3 +#undef stacksave + +#undef newptrb + +#endif + +/* These two are defined as macros in both cases */ + +#undef fc +#undef fi + +/*************************************************************************** +***************************************************************************/ + + +#ifdef NO_RECURSE +/************************************************* +* Release allocated heap frames * +*************************************************/ + +/* This function releases all the allocated frames. The base frame is on the +machine stack, and so must not be freed. + +Argument: the address of the base frame +Returns: nothing +*/ + +static void +release_match_heapframes (heapframe *frame_base) +{ +heapframe *nextframe = frame_base->Xnextframe; +while (nextframe != NULL) + { + heapframe *oldframe = nextframe; + nextframe = nextframe->Xnextframe; + (PUBL(stack_free))(oldframe); + } +} +#endif + + +/************************************************* +* Execute a Regular Expression * +*************************************************/ + +/* This function applies a compiled re to a subject string and picks out +portions of the string if it matches. Two elements in the vector are set for +each substring: the offsets to the start and end of the substring. + +Arguments: + argument_re points to the compiled expression + extra_data points to extra data or is NULL + subject points to the subject string + length length of subject string (may contain binary zeros) + start_offset where to start in the subject string + options option bits + offsets points to a vector of ints to be filled in with offsets + offsetcount the number of elements in the vector + +Returns: > 0 => success; value is the number of elements filled in + = 0 => success, but offsets is not big enough + -1 => failed to match + < -1 => some kind of unexpected problem +*/ + +#if defined COMPILE_PCRE8 +PCRE_EXP_DEFN int PCRE_CALL_CONVENTION +pcre_exec(const pcre *argument_re, const pcre_extra *extra_data, + PCRE_SPTR subject, int length, int start_offset, int options, int *offsets, + int offsetcount) +#elif defined COMPILE_PCRE16 +PCRE_EXP_DEFN int PCRE_CALL_CONVENTION +pcre16_exec(const pcre16 *argument_re, const pcre16_extra *extra_data, + PCRE_SPTR16 subject, int length, int start_offset, int options, int *offsets, + int offsetcount) +#elif defined COMPILE_PCRE32 +PCRE_EXP_DEFN int PCRE_CALL_CONVENTION +pcre32_exec(const pcre32 *argument_re, const pcre32_extra *extra_data, + PCRE_SPTR32 subject, int length, int start_offset, int options, int *offsets, + int offsetcount) +#endif +{ +int rc, ocount, arg_offset_max; +int newline; +BOOL using_temporary_offsets = FALSE; +BOOL anchored; +BOOL startline; +BOOL firstline; +BOOL utf; +BOOL has_first_char = FALSE; +BOOL has_req_char = FALSE; +pcre_uchar first_char = 0; +pcre_uchar first_char2 = 0; +pcre_uchar req_char = 0; +pcre_uchar req_char2 = 0; +match_data match_block; +match_data *md = &match_block; +const pcre_uint8 *tables; +const pcre_uint8 *start_bits = NULL; +PCRE_PUCHAR start_match = (PCRE_PUCHAR)subject + start_offset; +PCRE_PUCHAR end_subject; +PCRE_PUCHAR start_partial = NULL; +PCRE_PUCHAR match_partial = NULL; +PCRE_PUCHAR req_char_ptr = start_match - 1; + +const pcre_study_data *study; +const REAL_PCRE *re = (const REAL_PCRE *)argument_re; + +#ifdef NO_RECURSE +heapframe frame_zero; +frame_zero.Xprevframe = NULL; /* Marks the top level */ +frame_zero.Xnextframe = NULL; /* None are allocated yet */ +md->match_frames_base = &frame_zero; +#endif + +/* Check for the special magic call that measures the size of the stack used +per recursive call of match(). Without the funny casting for sizeof, a Windows +compiler gave this error: "unary minus operator applied to unsigned type, +result still unsigned". Hopefully the cast fixes that. */ + +if (re == NULL && extra_data == NULL && subject == NULL && length == -999 && + start_offset == -999) +#ifdef NO_RECURSE + return -((int)sizeof(heapframe)); +#else + return match(NULL, NULL, NULL, 0, NULL, NULL, 0); +#endif + +/* Plausibility checks */ + +if ((options & ~PUBLIC_EXEC_OPTIONS) != 0) return PCRE_ERROR_BADOPTION; +if (re == NULL || subject == NULL || (offsets == NULL && offsetcount > 0)) + return PCRE_ERROR_NULL; +if (offsetcount < 0) return PCRE_ERROR_BADCOUNT; +if (length < 0) return PCRE_ERROR_BADLENGTH; +if (start_offset < 0 || start_offset > length) return PCRE_ERROR_BADOFFSET; + +/* Check that the first field in the block is the magic number. If it is not, +return with PCRE_ERROR_BADMAGIC. However, if the magic number is equal to +REVERSED_MAGIC_NUMBER we return with PCRE_ERROR_BADENDIANNESS, which +means that the pattern is likely compiled with different endianness. */ + +if (re->magic_number != MAGIC_NUMBER) + return re->magic_number == REVERSED_MAGIC_NUMBER? + PCRE_ERROR_BADENDIANNESS:PCRE_ERROR_BADMAGIC; +if ((re->flags & PCRE_MODE) == 0) return PCRE_ERROR_BADMODE; + +/* These two settings are used in the code for checking a UTF-8 string that +follows immediately afterwards. Other values in the md block are used only +during "normal" pcre_exec() processing, not when the JIT support is in use, +so they are set up later. */ + +/* PCRE_UTF16 has the same value as PCRE_UTF8. */ +utf = md->utf = (re->options & PCRE_UTF8) != 0; +md->partial = ((options & PCRE_PARTIAL_HARD) != 0)? 2 : + ((options & PCRE_PARTIAL_SOFT) != 0)? 1 : 0; + +/* Check a UTF-8 string if required. Pass back the character offset and error +code for an invalid string if a results vector is available. */ + +#ifdef SUPPORT_UTF +if (utf && (options & PCRE_NO_UTF8_CHECK) == 0) + { + int erroroffset; + int errorcode = PRIV(valid_utf)((PCRE_PUCHAR)subject, length, &erroroffset); + if (errorcode != 0) + { + if (offsetcount >= 2) + { + offsets[0] = erroroffset; + offsets[1] = errorcode; + } +#if defined COMPILE_PCRE8 + return (errorcode <= PCRE_UTF8_ERR5 && md->partial > 1)? + PCRE_ERROR_SHORTUTF8 : PCRE_ERROR_BADUTF8; +#elif defined COMPILE_PCRE16 + return (errorcode <= PCRE_UTF16_ERR1 && md->partial > 1)? + PCRE_ERROR_SHORTUTF16 : PCRE_ERROR_BADUTF16; +#elif defined COMPILE_PCRE32 + return PCRE_ERROR_BADUTF32; +#endif + } +#if defined COMPILE_PCRE8 || defined COMPILE_PCRE16 + /* Check that a start_offset points to the start of a UTF character. */ + if (start_offset > 0 && start_offset < length && + NOT_FIRSTCHAR(((PCRE_PUCHAR)subject)[start_offset])) + return PCRE_ERROR_BADUTF8_OFFSET; +#endif + } +#endif + +/* If the pattern was successfully studied with JIT support, run the JIT +executable instead of the rest of this function. Most options must be set at +compile time for the JIT code to be usable. Fallback to the normal code path if +an unsupported flag is set. */ + +#ifdef SUPPORT_JIT +if (extra_data != NULL + && (extra_data->flags & (PCRE_EXTRA_EXECUTABLE_JIT | + PCRE_EXTRA_TABLES)) == PCRE_EXTRA_EXECUTABLE_JIT + && extra_data->executable_jit != NULL + && (options & ~PUBLIC_JIT_EXEC_OPTIONS) == 0) + { + rc = PRIV(jit_exec)(extra_data, (const pcre_uchar *)subject, length, + start_offset, options, offsets, offsetcount); + + /* PCRE_ERROR_NULL means that the selected normal or partial matching + mode is not compiled. In this case we simply fallback to interpreter. */ + + if (rc != PCRE_ERROR_JIT_BADOPTION) return rc; + } +#endif + +/* Carry on with non-JIT matching. This information is for finding all the +numbers associated with a given name, for condition testing. */ + +md->name_table = (pcre_uchar *)re + re->name_table_offset; +md->name_count = re->name_count; +md->name_entry_size = re->name_entry_size; + +/* Fish out the optional data from the extra_data structure, first setting +the default values. */ + +study = NULL; +md->match_limit = MATCH_LIMIT; +md->match_limit_recursion = MATCH_LIMIT_RECURSION; +md->callout_data = NULL; + +/* The table pointer is always in native byte order. */ + +tables = re->tables; + +/* The two limit values override the defaults, whatever their value. */ + +if (extra_data != NULL) + { + unsigned long int flags = extra_data->flags; + if ((flags & PCRE_EXTRA_STUDY_DATA) != 0) + study = (const pcre_study_data *)extra_data->study_data; + if ((flags & PCRE_EXTRA_MATCH_LIMIT) != 0) + md->match_limit = extra_data->match_limit; + if ((flags & PCRE_EXTRA_MATCH_LIMIT_RECURSION) != 0) + md->match_limit_recursion = extra_data->match_limit_recursion; + if ((flags & PCRE_EXTRA_CALLOUT_DATA) != 0) + md->callout_data = extra_data->callout_data; + if ((flags & PCRE_EXTRA_TABLES) != 0) tables = extra_data->tables; + } + +/* Limits in the regex override only if they are smaller. */ + +if ((re->flags & PCRE_MLSET) != 0 && re->limit_match < md->match_limit) + md->match_limit = re->limit_match; + +if ((re->flags & PCRE_RLSET) != 0 && + re->limit_recursion < md->match_limit_recursion) + md->match_limit_recursion = re->limit_recursion; + +/* If the exec call supplied NULL for tables, use the inbuilt ones. This +is a feature that makes it possible to save compiled regex and re-use them +in other programs later. */ + +if (tables == NULL) tables = PRIV(default_tables); + +/* Set up other data */ + +anchored = ((re->options | options) & PCRE_ANCHORED) != 0; +startline = (re->flags & PCRE_STARTLINE) != 0; +firstline = (re->options & PCRE_FIRSTLINE) != 0; + +/* The code starts after the real_pcre block and the capture name table. */ + +md->start_code = (const pcre_uchar *)re + re->name_table_offset + + re->name_count * re->name_entry_size; + +md->start_subject = (PCRE_PUCHAR)subject; +md->start_offset = start_offset; +md->end_subject = md->start_subject + length; +end_subject = md->end_subject; + +md->endonly = (re->options & PCRE_DOLLAR_ENDONLY) != 0; +md->use_ucp = (re->options & PCRE_UCP) != 0; +md->jscript_compat = (re->options & PCRE_JAVASCRIPT_COMPAT) != 0; +md->ignore_skip_arg = 0; + +/* Some options are unpacked into BOOL variables in the hope that testing +them will be faster than individual option bits. */ + +md->notbol = (options & PCRE_NOTBOL) != 0; +md->noteol = (options & PCRE_NOTEOL) != 0; +md->notempty = (options & PCRE_NOTEMPTY) != 0; +md->notempty_atstart = (options & PCRE_NOTEMPTY_ATSTART) != 0; + +md->hitend = FALSE; +md->mark = md->nomatch_mark = NULL; /* In case never set */ + +md->recursive = NULL; /* No recursion at top level */ +md->hasthen = (re->flags & PCRE_HASTHEN) != 0; + +md->lcc = tables + lcc_offset; +md->fcc = tables + fcc_offset; +md->ctypes = tables + ctypes_offset; + +/* Handle different \R options. */ + +switch (options & (PCRE_BSR_ANYCRLF|PCRE_BSR_UNICODE)) + { + case 0: + if ((re->options & (PCRE_BSR_ANYCRLF|PCRE_BSR_UNICODE)) != 0) + md->bsr_anycrlf = (re->options & PCRE_BSR_ANYCRLF) != 0; + else +#ifdef BSR_ANYCRLF + md->bsr_anycrlf = TRUE; +#else + md->bsr_anycrlf = FALSE; +#endif + break; + + case PCRE_BSR_ANYCRLF: + md->bsr_anycrlf = TRUE; + break; + + case PCRE_BSR_UNICODE: + md->bsr_anycrlf = FALSE; + break; + + default: return PCRE_ERROR_BADNEWLINE; + } + +/* Handle different types of newline. The three bits give eight cases. If +nothing is set at run time, whatever was used at compile time applies. */ + +switch ((((options & PCRE_NEWLINE_BITS) == 0)? re->options : + (pcre_uint32)options) & PCRE_NEWLINE_BITS) + { + case 0: newline = NEWLINE; break; /* Compile-time default */ + case PCRE_NEWLINE_CR: newline = CHAR_CR; break; + case PCRE_NEWLINE_LF: newline = CHAR_NL; break; + case PCRE_NEWLINE_CR+ + PCRE_NEWLINE_LF: newline = (CHAR_CR << 8) | CHAR_NL; break; + case PCRE_NEWLINE_ANY: newline = -1; break; + case PCRE_NEWLINE_ANYCRLF: newline = -2; break; + default: return PCRE_ERROR_BADNEWLINE; + } + +if (newline == -2) + { + md->nltype = NLTYPE_ANYCRLF; + } +else if (newline < 0) + { + md->nltype = NLTYPE_ANY; + } +else + { + md->nltype = NLTYPE_FIXED; + if (newline > 255) + { + md->nllen = 2; + md->nl[0] = (newline >> 8) & 255; + md->nl[1] = newline & 255; + } + else + { + md->nllen = 1; + md->nl[0] = newline; + } + } + +/* Partial matching was originally supported only for a restricted set of +regexes; from release 8.00 there are no restrictions, but the bits are still +defined (though never set). So there's no harm in leaving this code. */ + +if (md->partial && (re->flags & PCRE_NOPARTIAL) != 0) + return PCRE_ERROR_BADPARTIAL; + +/* If the expression has got more back references than the offsets supplied can +hold, we get a temporary chunk of working store to use during the matching. +Otherwise, we can use the vector supplied, rounding down its size to a multiple +of 3. */ + +ocount = offsetcount - (offsetcount % 3); +arg_offset_max = (2*ocount)/3; + +if (re->top_backref > 0 && re->top_backref >= ocount/3) + { + ocount = re->top_backref * 3 + 3; + md->offset_vector = (int *)(PUBL(malloc))(ocount * sizeof(int)); + if (md->offset_vector == NULL) return PCRE_ERROR_NOMEMORY; + using_temporary_offsets = TRUE; + DPRINTF(("Got memory to hold back references\n")); + } +else md->offset_vector = offsets; +md->offset_end = ocount; +md->offset_max = (2*ocount)/3; +md->capture_last = 0; + +/* Reset the working variable associated with each extraction. These should +never be used unless previously set, but they get saved and restored, and so we +initialize them to avoid reading uninitialized locations. Also, unset the +offsets for the matched string. This is really just for tidiness with callouts, +in case they inspect these fields. */ + +if (md->offset_vector != NULL) + { + register int *iptr = md->offset_vector + ocount; + register int *iend = iptr - re->top_bracket; + if (iend < md->offset_vector + 2) iend = md->offset_vector + 2; + while (--iptr >= iend) *iptr = -1; + md->offset_vector[0] = md->offset_vector[1] = -1; + } + +/* Set up the first character to match, if available. The first_char value is +never set for an anchored regular expression, but the anchoring may be forced +at run time, so we have to test for anchoring. The first char may be unset for +an unanchored pattern, of course. If there's no first char and the pattern was +studied, there may be a bitmap of possible first characters. */ + +if (!anchored) + { + if ((re->flags & PCRE_FIRSTSET) != 0) + { + has_first_char = TRUE; + first_char = first_char2 = (pcre_uchar)(re->first_char); + if ((re->flags & PCRE_FCH_CASELESS) != 0) + { + first_char2 = TABLE_GET(first_char, md->fcc, first_char); +#if defined SUPPORT_UCP && !(defined COMPILE_PCRE8) + if (utf && first_char > 127) + first_char2 = UCD_OTHERCASE(first_char); +#endif + } + } + else + if (!startline && study != NULL && + (study->flags & PCRE_STUDY_MAPPED) != 0) + start_bits = study->start_bits; + } + +/* For anchored or unanchored matches, there may be a "last known required +character" set. */ + +if ((re->flags & PCRE_REQCHSET) != 0) + { + has_req_char = TRUE; + req_char = req_char2 = (pcre_uchar)(re->req_char); + if ((re->flags & PCRE_RCH_CASELESS) != 0) + { + req_char2 = TABLE_GET(req_char, md->fcc, req_char); +#if defined SUPPORT_UCP && !(defined COMPILE_PCRE8) + if (utf && req_char > 127) + req_char2 = UCD_OTHERCASE(req_char); +#endif + } + } + + +/* ==========================================================================*/ + +/* Loop for handling unanchored repeated matching attempts; for anchored regexs +the loop runs just once. */ + +for(;;) + { + PCRE_PUCHAR save_end_subject = end_subject; + PCRE_PUCHAR new_start_match; + + /* If firstline is TRUE, the start of the match is constrained to the first + line of a multiline string. That is, the match must be before or at the first + newline. Implement this by temporarily adjusting end_subject so that we stop + scanning at a newline. If the match fails at the newline, later code breaks + this loop. */ + + if (firstline) + { + PCRE_PUCHAR t = start_match; +#ifdef SUPPORT_UTF + if (utf) + { + while (t < md->end_subject && !IS_NEWLINE(t)) + { + t++; + ACROSSCHAR(t < end_subject, *t, t++); + } + } + else +#endif + while (t < md->end_subject && !IS_NEWLINE(t)) t++; + end_subject = t; + } + + /* There are some optimizations that avoid running the match if a known + starting point is not found, or if a known later character is not present. + However, there is an option that disables these, for testing and for ensuring + that all callouts do actually occur. The option can be set in the regex by + (*NO_START_OPT) or passed in match-time options. */ + + if (((options | re->options) & PCRE_NO_START_OPTIMIZE) == 0) + { + /* Advance to a unique first char if there is one. */ + + if (has_first_char) + { + pcre_uchar smc; + + if (first_char != first_char2) + while (start_match < end_subject && + (smc = UCHAR21TEST(start_match)) != first_char && smc != first_char2) + start_match++; + else + while (start_match < end_subject && UCHAR21TEST(start_match) != first_char) + start_match++; + } + + /* Or to just after a linebreak for a multiline match */ + + else if (startline) + { + if (start_match > md->start_subject + start_offset) + { +#ifdef SUPPORT_UTF + if (utf) + { + while (start_match < end_subject && !WAS_NEWLINE(start_match)) + { + start_match++; + ACROSSCHAR(start_match < end_subject, *start_match, + start_match++); + } + } + else +#endif + while (start_match < end_subject && !WAS_NEWLINE(start_match)) + start_match++; + + /* If we have just passed a CR and the newline option is ANY or ANYCRLF, + and we are now at a LF, advance the match position by one more character. + */ + + if (start_match[-1] == CHAR_CR && + (md->nltype == NLTYPE_ANY || md->nltype == NLTYPE_ANYCRLF) && + start_match < end_subject && + UCHAR21TEST(start_match) == CHAR_NL) + start_match++; + } + } + + /* Or to a non-unique first byte after study */ + + else if (start_bits != NULL) + { + while (start_match < end_subject) + { + register pcre_uint32 c = UCHAR21TEST(start_match); +#ifndef COMPILE_PCRE8 + if (c > 255) c = 255; +#endif + if ((start_bits[c/8] & (1 << (c&7))) != 0) break; + start_match++; + } + } + } /* Starting optimizations */ + + /* Restore fudged end_subject */ + + end_subject = save_end_subject; + + /* The following two optimizations are disabled for partial matching or if + disabling is explicitly requested. */ + + if (((options | re->options) & PCRE_NO_START_OPTIMIZE) == 0 && !md->partial) + { + /* If the pattern was studied, a minimum subject length may be set. This is + a lower bound; no actual string of that length may actually match the + pattern. Although the value is, strictly, in characters, we treat it as + bytes to avoid spending too much time in this optimization. */ + + if (study != NULL && (study->flags & PCRE_STUDY_MINLEN) != 0 && + (pcre_uint32)(end_subject - start_match) < study->minlength) + { + rc = MATCH_NOMATCH; + break; + } + + /* If req_char is set, we know that that character must appear in the + subject for the match to succeed. If the first character is set, req_char + must be later in the subject; otherwise the test starts at the match point. + This optimization can save a huge amount of backtracking in patterns with + nested unlimited repeats that aren't going to match. Writing separate code + for cased/caseless versions makes it go faster, as does using an + autoincrement and backing off on a match. + + HOWEVER: when the subject string is very, very long, searching to its end + can take a long time, and give bad performance on quite ordinary patterns. + This showed up when somebody was matching something like /^\d+C/ on a + 32-megabyte string... so we don't do this when the string is sufficiently + long. */ + + if (has_req_char && end_subject - start_match < REQ_BYTE_MAX) + { + register PCRE_PUCHAR p = start_match + (has_first_char? 1:0); + + /* We don't need to repeat the search if we haven't yet reached the + place we found it at last time. */ + + if (p > req_char_ptr) + { + if (req_char != req_char2) + { + while (p < end_subject) + { + register pcre_uint32 pp = UCHAR21INCTEST(p); + if (pp == req_char || pp == req_char2) { p--; break; } + } + } + else + { + while (p < end_subject) + { + if (UCHAR21INCTEST(p) == req_char) { p--; break; } + } + } + + /* If we can't find the required character, break the matching loop, + forcing a match failure. */ + + if (p >= end_subject) + { + rc = MATCH_NOMATCH; + break; + } + + /* If we have found the required character, save the point where we + found it, so that we don't search again next time round the loop if + the start hasn't passed this character yet. */ + + req_char_ptr = p; + } + } + } + +#ifdef PCRE_DEBUG /* Sigh. Some compilers never learn. */ + printf(">>>> Match against: "); + pchars(start_match, end_subject - start_match, TRUE, md); + printf("\n"); +#endif + + /* OK, we can now run the match. If "hitend" is set afterwards, remember the + first starting point for which a partial match was found. */ + + md->start_match_ptr = start_match; + md->start_used_ptr = start_match; + md->match_call_count = 0; + md->match_function_type = 0; + md->end_offset_top = 0; + md->skip_arg_count = 0; + rc = match(start_match, md->start_code, start_match, 2, md, NULL, 0); + if (md->hitend && start_partial == NULL) + { + start_partial = md->start_used_ptr; + match_partial = start_match; + } + + switch(rc) + { + /* If MATCH_SKIP_ARG reaches this level it means that a MARK that matched + the SKIP's arg was not found. In this circumstance, Perl ignores the SKIP + entirely. The only way we can do that is to re-do the match at the same + point, with a flag to force SKIP with an argument to be ignored. Just + treating this case as NOMATCH does not work because it does not check other + alternatives in patterns such as A(*SKIP:A)B|AC when the subject is AC. */ + + case MATCH_SKIP_ARG: + new_start_match = start_match; + md->ignore_skip_arg = md->skip_arg_count; + break; + + /* SKIP passes back the next starting point explicitly, but if it is no + greater than the match we have just done, treat it as NOMATCH. */ + + case MATCH_SKIP: + if (md->start_match_ptr > start_match) + { + new_start_match = md->start_match_ptr; + break; + } + /* Fall through */ + + /* NOMATCH and PRUNE advance by one character. THEN at this level acts + exactly like PRUNE. Unset ignore SKIP-with-argument. */ + + case MATCH_NOMATCH: + case MATCH_PRUNE: + case MATCH_THEN: + md->ignore_skip_arg = 0; + new_start_match = start_match + 1; +#ifdef SUPPORT_UTF + if (utf) + ACROSSCHAR(new_start_match < end_subject, *new_start_match, + new_start_match++); +#endif + break; + + /* COMMIT disables the bumpalong, but otherwise behaves as NOMATCH. */ + + case MATCH_COMMIT: + rc = MATCH_NOMATCH; + goto ENDLOOP; + + /* Any other return is either a match, or some kind of error. */ + + default: + goto ENDLOOP; + } + + /* Control reaches here for the various types of "no match at this point" + result. Reset the code to MATCH_NOMATCH for subsequent checking. */ + + rc = MATCH_NOMATCH; + + /* If PCRE_FIRSTLINE is set, the match must happen before or at the first + newline in the subject (though it may continue over the newline). Therefore, + if we have just failed to match, starting at a newline, do not continue. */ + + if (firstline && IS_NEWLINE(start_match)) break; + + /* Advance to new matching position */ + + start_match = new_start_match; + + /* Break the loop if the pattern is anchored or if we have passed the end of + the subject. */ + + if (anchored || start_match > end_subject) break; + + /* If we have just passed a CR and we are now at a LF, and the pattern does + not contain any explicit matches for \r or \n, and the newline option is CRLF + or ANY or ANYCRLF, advance the match position by one more character. In + normal matching start_match will aways be greater than the first position at + this stage, but a failed *SKIP can cause a return at the same point, which is + why the first test exists. */ + + if (start_match > (PCRE_PUCHAR)subject + start_offset && + start_match[-1] == CHAR_CR && + start_match < end_subject && + *start_match == CHAR_NL && + (re->flags & PCRE_HASCRORLF) == 0 && + (md->nltype == NLTYPE_ANY || + md->nltype == NLTYPE_ANYCRLF || + md->nllen == 2)) + start_match++; + + md->mark = NULL; /* Reset for start of next match attempt */ + } /* End of for(;;) "bumpalong" loop */ + +/* ==========================================================================*/ + +/* We reach here when rc is not MATCH_NOMATCH, or if one of the stopping +conditions is true: + +(1) The pattern is anchored or the match was failed by (*COMMIT); + +(2) We are past the end of the subject; + +(3) PCRE_FIRSTLINE is set and we have failed to match at a newline, because + this option requests that a match occur at or before the first newline in + the subject. + +When we have a match and the offset vector is big enough to deal with any +backreferences, captured substring offsets will already be set up. In the case +where we had to get some local store to hold offsets for backreference +processing, copy those that we can. In this case there need not be overflow if +certain parts of the pattern were not used, even though there are more +capturing parentheses than vector slots. */ + +ENDLOOP: + +if (rc == MATCH_MATCH || rc == MATCH_ACCEPT) + { + if (using_temporary_offsets) + { + if (arg_offset_max >= 4) + { + memcpy(offsets + 2, md->offset_vector + 2, + (arg_offset_max - 2) * sizeof(int)); + DPRINTF(("Copied offsets from temporary memory\n")); + } + if (md->end_offset_top > arg_offset_max) md->capture_last |= OVFLBIT; + DPRINTF(("Freeing temporary memory\n")); + (PUBL(free))(md->offset_vector); + } + + /* Set the return code to the number of captured strings, or 0 if there were + too many to fit into the vector. */ + + rc = ((md->capture_last & OVFLBIT) != 0 && + md->end_offset_top >= arg_offset_max)? + 0 : md->end_offset_top/2; + + /* If there is space in the offset vector, set any unused pairs at the end of + the pattern to -1 for backwards compatibility. It is documented that this + happens. In earlier versions, the whole set of potential capturing offsets + was set to -1 each time round the loop, but this is handled differently now. + "Gaps" are set to -1 dynamically instead (this fixes a bug). Thus, it is only + those at the end that need unsetting here. We can't just unset them all at + the start of the whole thing because they may get set in one branch that is + not the final matching branch. */ + + if (md->end_offset_top/2 <= re->top_bracket && offsets != NULL) + { + register int *iptr, *iend; + int resetcount = 2 + re->top_bracket * 2; + if (resetcount > offsetcount) resetcount = offsetcount; + iptr = offsets + md->end_offset_top; + iend = offsets + resetcount; + while (iptr < iend) *iptr++ = -1; + } + + /* If there is space, set up the whole thing as substring 0. The value of + md->start_match_ptr might be modified if \K was encountered on the success + matching path. */ + + if (offsetcount < 2) rc = 0; else + { + offsets[0] = (int)(md->start_match_ptr - md->start_subject); + offsets[1] = (int)(md->end_match_ptr - md->start_subject); + } + + /* Return MARK data if requested */ + + if (extra_data != NULL && (extra_data->flags & PCRE_EXTRA_MARK) != 0) + *(extra_data->mark) = (pcre_uchar *)md->mark; + DPRINTF((">>>> returning %d\n", rc)); +#ifdef NO_RECURSE + release_match_heapframes(&frame_zero); +#endif + return rc; + } + +/* Control gets here if there has been an error, or if the overall match +attempt has failed at all permitted starting positions. */ + +if (using_temporary_offsets) + { + DPRINTF(("Freeing temporary memory\n")); + (PUBL(free))(md->offset_vector); + } + +/* For anything other than nomatch or partial match, just return the code. */ + +if (rc != MATCH_NOMATCH && rc != PCRE_ERROR_PARTIAL) + { + DPRINTF((">>>> error: returning %d\n", rc)); +#ifdef NO_RECURSE + release_match_heapframes(&frame_zero); +#endif + return rc; + } + +/* Handle partial matches - disable any mark data */ + +if (match_partial != NULL) + { + DPRINTF((">>>> returning PCRE_ERROR_PARTIAL\n")); + md->mark = NULL; + if (offsetcount > 1) + { + offsets[0] = (int)(start_partial - (PCRE_PUCHAR)subject); + offsets[1] = (int)(end_subject - (PCRE_PUCHAR)subject); + if (offsetcount > 2) + offsets[2] = (int)(match_partial - (PCRE_PUCHAR)subject); + } + rc = PCRE_ERROR_PARTIAL; + } + +/* This is the classic nomatch case */ + +else + { + DPRINTF((">>>> returning PCRE_ERROR_NOMATCH\n")); + rc = PCRE_ERROR_NOMATCH; + } + +/* Return the MARK data if it has been requested. */ + +if (extra_data != NULL && (extra_data->flags & PCRE_EXTRA_MARK) != 0) + *(extra_data->mark) = (pcre_uchar *)md->nomatch_mark; +#ifdef NO_RECURSE + release_match_heapframes(&frame_zero); +#endif +return rc; +} + +/* End of pcre_exec.c */ diff --git a/src/private/pcre_src/pcre_fullinfo.c b/src/private/pcre_src/pcre_fullinfo.c new file mode 100644 index 000000000..a6c2ece6c --- /dev/null +++ b/src/private/pcre_src/pcre_fullinfo.c @@ -0,0 +1,245 @@ +/************************************************* +* Perl-Compatible Regular Expressions * +*************************************************/ + +/* PCRE is a library of functions to support regular expressions whose syntax +and semantics are as close as possible to those of the Perl 5 language. + + Written by Philip Hazel + Copyright (c) 1997-2013 University of Cambridge + +----------------------------------------------------------------------------- +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * Neither the name of the University of Cambridge nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. +----------------------------------------------------------------------------- +*/ + + +/* This module contains the external function pcre_fullinfo(), which returns +information about a compiled pattern. */ + + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "pcre_internal.h" + + +/************************************************* +* Return info about compiled pattern * +*************************************************/ + +/* This is a newer "info" function which has an extensible interface so +that additional items can be added compatibly. + +Arguments: + argument_re points to compiled code + extra_data points extra data, or NULL + what what information is required + where where to put the information + +Returns: 0 if data returned, negative on error +*/ + +#if defined COMPILE_PCRE8 +PCRE_EXP_DEFN int PCRE_CALL_CONVENTION +pcre_fullinfo(const pcre *argument_re, const pcre_extra *extra_data, + int what, void *where) +#elif defined COMPILE_PCRE16 +PCRE_EXP_DEFN int PCRE_CALL_CONVENTION +pcre16_fullinfo(const pcre16 *argument_re, const pcre16_extra *extra_data, + int what, void *where) +#elif defined COMPILE_PCRE32 +PCRE_EXP_DEFN int PCRE_CALL_CONVENTION +pcre32_fullinfo(const pcre32 *argument_re, const pcre32_extra *extra_data, + int what, void *where) +#endif +{ +const REAL_PCRE *re = (const REAL_PCRE *)argument_re; +const pcre_study_data *study = NULL; + +if (re == NULL || where == NULL) return PCRE_ERROR_NULL; + +if (extra_data != NULL && (extra_data->flags & PCRE_EXTRA_STUDY_DATA) != 0) + study = (const pcre_study_data *)extra_data->study_data; + +/* Check that the first field in the block is the magic number. If it is not, +return with PCRE_ERROR_BADMAGIC. However, if the magic number is equal to +REVERSED_MAGIC_NUMBER we return with PCRE_ERROR_BADENDIANNESS, which +means that the pattern is likely compiled with different endianness. */ + +if (re->magic_number != MAGIC_NUMBER) + return re->magic_number == REVERSED_MAGIC_NUMBER? + PCRE_ERROR_BADENDIANNESS:PCRE_ERROR_BADMAGIC; + +/* Check that this pattern was compiled in the correct bit mode */ + +if ((re->flags & PCRE_MODE) == 0) return PCRE_ERROR_BADMODE; + +switch (what) + { + case PCRE_INFO_OPTIONS: + *((unsigned long int *)where) = re->options & PUBLIC_COMPILE_OPTIONS; + break; + + case PCRE_INFO_SIZE: + *((size_t *)where) = re->size; + break; + + case PCRE_INFO_STUDYSIZE: + *((size_t *)where) = (study == NULL)? 0 : study->size; + break; + + case PCRE_INFO_JITSIZE: +#ifdef SUPPORT_JIT + *((size_t *)where) = + (extra_data != NULL && + (extra_data->flags & PCRE_EXTRA_EXECUTABLE_JIT) != 0 && + extra_data->executable_jit != NULL)? + PRIV(jit_get_size)(extra_data->executable_jit) : 0; +#else + *((size_t *)where) = 0; +#endif + break; + + case PCRE_INFO_CAPTURECOUNT: + *((int *)where) = re->top_bracket; + break; + + case PCRE_INFO_BACKREFMAX: + *((int *)where) = re->top_backref; + break; + + case PCRE_INFO_FIRSTBYTE: + *((int *)where) = + ((re->flags & PCRE_FIRSTSET) != 0)? (int)re->first_char : + ((re->flags & PCRE_STARTLINE) != 0)? -1 : -2; + break; + + case PCRE_INFO_FIRSTCHARACTER: + *((pcre_uint32 *)where) = + (re->flags & PCRE_FIRSTSET) != 0 ? re->first_char : 0; + break; + + case PCRE_INFO_FIRSTCHARACTERFLAGS: + *((int *)where) = + ((re->flags & PCRE_FIRSTSET) != 0) ? 1 : + ((re->flags & PCRE_STARTLINE) != 0) ? 2 : 0; + break; + + /* Make sure we pass back the pointer to the bit vector in the external + block, not the internal copy (with flipped integer fields). */ + + case PCRE_INFO_FIRSTTABLE: + *((const pcre_uint8 **)where) = + (study != NULL && (study->flags & PCRE_STUDY_MAPPED) != 0)? + ((const pcre_study_data *)extra_data->study_data)->start_bits : NULL; + break; + + case PCRE_INFO_MINLENGTH: + *((int *)where) = + (study != NULL && (study->flags & PCRE_STUDY_MINLEN) != 0)? + (int)(study->minlength) : -1; + break; + + case PCRE_INFO_JIT: + *((int *)where) = extra_data != NULL && + (extra_data->flags & PCRE_EXTRA_EXECUTABLE_JIT) != 0 && + extra_data->executable_jit != NULL; + break; + + case PCRE_INFO_LASTLITERAL: + *((int *)where) = + ((re->flags & PCRE_REQCHSET) != 0)? (int)re->req_char : -1; + break; + + case PCRE_INFO_REQUIREDCHAR: + *((pcre_uint32 *)where) = + ((re->flags & PCRE_REQCHSET) != 0) ? re->req_char : 0; + break; + + case PCRE_INFO_REQUIREDCHARFLAGS: + *((int *)where) = + ((re->flags & PCRE_REQCHSET) != 0); + break; + + case PCRE_INFO_NAMEENTRYSIZE: + *((int *)where) = re->name_entry_size; + break; + + case PCRE_INFO_NAMECOUNT: + *((int *)where) = re->name_count; + break; + + case PCRE_INFO_NAMETABLE: + *((const pcre_uchar **)where) = (const pcre_uchar *)re + re->name_table_offset; + break; + + case PCRE_INFO_DEFAULT_TABLES: + *((const pcre_uint8 **)where) = (const pcre_uint8 *)(PRIV(default_tables)); + break; + + /* From release 8.00 this will always return TRUE because NOPARTIAL is + no longer ever set (the restrictions have been removed). */ + + case PCRE_INFO_OKPARTIAL: + *((int *)where) = (re->flags & PCRE_NOPARTIAL) == 0; + break; + + case PCRE_INFO_JCHANGED: + *((int *)where) = (re->flags & PCRE_JCHANGED) != 0; + break; + + case PCRE_INFO_HASCRORLF: + *((int *)where) = (re->flags & PCRE_HASCRORLF) != 0; + break; + + case PCRE_INFO_MAXLOOKBEHIND: + *((int *)where) = re->max_lookbehind; + break; + + case PCRE_INFO_MATCHLIMIT: + if ((re->flags & PCRE_MLSET) == 0) return PCRE_ERROR_UNSET; + *((pcre_uint32 *)where) = re->limit_match; + break; + + case PCRE_INFO_RECURSIONLIMIT: + if ((re->flags & PCRE_RLSET) == 0) return PCRE_ERROR_UNSET; + *((pcre_uint32 *)where) = re->limit_recursion; + break; + + case PCRE_INFO_MATCH_EMPTY: + *((int *)where) = (re->flags & PCRE_MATCH_EMPTY) != 0; + break; + + default: return PCRE_ERROR_BADOPTION; + } + +return 0; +} + +/* End of pcre_fullinfo.c */ diff --git a/src/private/pcre_src/pcre_get.c b/src/private/pcre_src/pcre_get.c new file mode 100644 index 000000000..8094b34bb --- /dev/null +++ b/src/private/pcre_src/pcre_get.c @@ -0,0 +1,662 @@ +/************************************************* +* Perl-Compatible Regular Expressions * +*************************************************/ + +/* PCRE is a library of functions to support regular expressions whose syntax +and semantics are as close as possible to those of the Perl 5 language. + + Written by Philip Hazel + Copyright (c) 1997-2012 University of Cambridge + +----------------------------------------------------------------------------- +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * Neither the name of the University of Cambridge nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. +----------------------------------------------------------------------------- +*/ + + +/* This module contains some convenience functions for extracting substrings +from the subject string after a regex match has succeeded. The original idea +for these functions came from Scott Wimer. */ + + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "pcre_internal.h" + + +/************************************************* +* Find number for named string * +*************************************************/ + +/* This function is used by the get_first_set() function below, as well +as being generally available. It assumes that names are unique. + +Arguments: + code the compiled regex + stringname the name whose number is required + +Returns: the number of the named parentheses, or a negative number + (PCRE_ERROR_NOSUBSTRING) if not found +*/ + +#if defined COMPILE_PCRE8 +PCRE_EXP_DEFN int PCRE_CALL_CONVENTION +pcre_get_stringnumber(const pcre *code, const char *stringname) +#elif defined COMPILE_PCRE16 +PCRE_EXP_DEFN int PCRE_CALL_CONVENTION +pcre16_get_stringnumber(const pcre16 *code, PCRE_SPTR16 stringname) +#elif defined COMPILE_PCRE32 +PCRE_EXP_DEFN int PCRE_CALL_CONVENTION +pcre32_get_stringnumber(const pcre32 *code, PCRE_SPTR32 stringname) +#endif +{ +int rc; +int entrysize; +int top, bot; +pcre_uchar *nametable; + +#ifdef COMPILE_PCRE8 +if ((rc = pcre_fullinfo(code, NULL, PCRE_INFO_NAMECOUNT, &top)) != 0) + return rc; +if (top <= 0) return PCRE_ERROR_NOSUBSTRING; + +if ((rc = pcre_fullinfo(code, NULL, PCRE_INFO_NAMEENTRYSIZE, &entrysize)) != 0) + return rc; +if ((rc = pcre_fullinfo(code, NULL, PCRE_INFO_NAMETABLE, &nametable)) != 0) + return rc; +#endif +#ifdef COMPILE_PCRE16 +if ((rc = pcre16_fullinfo(code, NULL, PCRE_INFO_NAMECOUNT, &top)) != 0) + return rc; +if (top <= 0) return PCRE_ERROR_NOSUBSTRING; + +if ((rc = pcre16_fullinfo(code, NULL, PCRE_INFO_NAMEENTRYSIZE, &entrysize)) != 0) + return rc; +if ((rc = pcre16_fullinfo(code, NULL, PCRE_INFO_NAMETABLE, &nametable)) != 0) + return rc; +#endif +#ifdef COMPILE_PCRE32 +if ((rc = pcre32_fullinfo(code, NULL, PCRE_INFO_NAMECOUNT, &top)) != 0) + return rc; +if (top <= 0) return PCRE_ERROR_NOSUBSTRING; + +if ((rc = pcre32_fullinfo(code, NULL, PCRE_INFO_NAMEENTRYSIZE, &entrysize)) != 0) + return rc; +if ((rc = pcre32_fullinfo(code, NULL, PCRE_INFO_NAMETABLE, &nametable)) != 0) + return rc; +#endif + +bot = 0; +while (top > bot) + { + int mid = (top + bot) / 2; + pcre_uchar *entry = nametable + entrysize*mid; + int c = STRCMP_UC_UC((pcre_uchar *)stringname, + (pcre_uchar *)(entry + IMM2_SIZE)); + if (c == 0) return GET2(entry, 0); + if (c > 0) bot = mid + 1; else top = mid; + } + +return PCRE_ERROR_NOSUBSTRING; +} + + + +/************************************************* +* Find (multiple) entries for named string * +*************************************************/ + +/* This is used by the get_first_set() function below, as well as being +generally available. It is used when duplicated names are permitted. + +Arguments: + code the compiled regex + stringname the name whose entries required + firstptr where to put the pointer to the first entry + lastptr where to put the pointer to the last entry + +Returns: the length of each entry, or a negative number + (PCRE_ERROR_NOSUBSTRING) if not found +*/ + +#if defined COMPILE_PCRE8 +PCRE_EXP_DEFN int PCRE_CALL_CONVENTION +pcre_get_stringtable_entries(const pcre *code, const char *stringname, + char **firstptr, char **lastptr) +#elif defined COMPILE_PCRE16 +PCRE_EXP_DEFN int PCRE_CALL_CONVENTION +pcre16_get_stringtable_entries(const pcre16 *code, PCRE_SPTR16 stringname, + PCRE_UCHAR16 **firstptr, PCRE_UCHAR16 **lastptr) +#elif defined COMPILE_PCRE32 +PCRE_EXP_DEFN int PCRE_CALL_CONVENTION +pcre32_get_stringtable_entries(const pcre32 *code, PCRE_SPTR32 stringname, + PCRE_UCHAR32 **firstptr, PCRE_UCHAR32 **lastptr) +#endif +{ +int rc; +int entrysize; +int top, bot; +pcre_uchar *nametable, *lastentry; + +#ifdef COMPILE_PCRE8 +if ((rc = pcre_fullinfo(code, NULL, PCRE_INFO_NAMECOUNT, &top)) != 0) + return rc; +if (top <= 0) return PCRE_ERROR_NOSUBSTRING; + +if ((rc = pcre_fullinfo(code, NULL, PCRE_INFO_NAMEENTRYSIZE, &entrysize)) != 0) + return rc; +if ((rc = pcre_fullinfo(code, NULL, PCRE_INFO_NAMETABLE, &nametable)) != 0) + return rc; +#endif +#ifdef COMPILE_PCRE16 +if ((rc = pcre16_fullinfo(code, NULL, PCRE_INFO_NAMECOUNT, &top)) != 0) + return rc; +if (top <= 0) return PCRE_ERROR_NOSUBSTRING; + +if ((rc = pcre16_fullinfo(code, NULL, PCRE_INFO_NAMEENTRYSIZE, &entrysize)) != 0) + return rc; +if ((rc = pcre16_fullinfo(code, NULL, PCRE_INFO_NAMETABLE, &nametable)) != 0) + return rc; +#endif +#ifdef COMPILE_PCRE32 +if ((rc = pcre32_fullinfo(code, NULL, PCRE_INFO_NAMECOUNT, &top)) != 0) + return rc; +if (top <= 0) return PCRE_ERROR_NOSUBSTRING; + +if ((rc = pcre32_fullinfo(code, NULL, PCRE_INFO_NAMEENTRYSIZE, &entrysize)) != 0) + return rc; +if ((rc = pcre32_fullinfo(code, NULL, PCRE_INFO_NAMETABLE, &nametable)) != 0) + return rc; +#endif + +lastentry = nametable + entrysize * (top - 1); +bot = 0; +while (top > bot) + { + int mid = (top + bot) / 2; + pcre_uchar *entry = nametable + entrysize*mid; + int c = STRCMP_UC_UC((pcre_uchar *)stringname, + (pcre_uchar *)(entry + IMM2_SIZE)); + if (c == 0) + { + pcre_uchar *first = entry; + pcre_uchar *last = entry; + while (first > nametable) + { + if (STRCMP_UC_UC((pcre_uchar *)stringname, + (pcre_uchar *)(first - entrysize + IMM2_SIZE)) != 0) break; + first -= entrysize; + } + while (last < lastentry) + { + if (STRCMP_UC_UC((pcre_uchar *)stringname, + (pcre_uchar *)(last + entrysize + IMM2_SIZE)) != 0) break; + last += entrysize; + } +#if defined COMPILE_PCRE8 + *firstptr = (char *)first; + *lastptr = (char *)last; +#elif defined COMPILE_PCRE16 + *firstptr = (PCRE_UCHAR16 *)first; + *lastptr = (PCRE_UCHAR16 *)last; +#elif defined COMPILE_PCRE32 + *firstptr = (PCRE_UCHAR32 *)first; + *lastptr = (PCRE_UCHAR32 *)last; +#endif + return entrysize; + } + if (c > 0) bot = mid + 1; else top = mid; + } + +return PCRE_ERROR_NOSUBSTRING; +} + + + +/************************************************* +* Find first set of multiple named strings * +*************************************************/ + +/* This function allows for duplicate names in the table of named substrings. +It returns the number of the first one that was set in a pattern match. + +Arguments: + code the compiled regex + stringname the name of the capturing substring + ovector the vector of matched substrings + +Returns: the number of the first that is set, + or the number of the last one if none are set, + or a negative number on error +*/ + +#if defined COMPILE_PCRE8 +static int +get_first_set(const pcre *code, const char *stringname, int *ovector) +#elif defined COMPILE_PCRE16 +static int +get_first_set(const pcre16 *code, PCRE_SPTR16 stringname, int *ovector) +#elif defined COMPILE_PCRE32 +static int +get_first_set(const pcre32 *code, PCRE_SPTR32 stringname, int *ovector) +#endif +{ +const REAL_PCRE *re = (const REAL_PCRE *)code; +int entrysize; +pcre_uchar *entry; +#if defined COMPILE_PCRE8 +char *first, *last; +#elif defined COMPILE_PCRE16 +PCRE_UCHAR16 *first, *last; +#elif defined COMPILE_PCRE32 +PCRE_UCHAR32 *first, *last; +#endif + +#if defined COMPILE_PCRE8 +if ((re->options & PCRE_DUPNAMES) == 0 && (re->flags & PCRE_JCHANGED) == 0) + return pcre_get_stringnumber(code, stringname); +entrysize = pcre_get_stringtable_entries(code, stringname, &first, &last); +#elif defined COMPILE_PCRE16 +if ((re->options & PCRE_DUPNAMES) == 0 && (re->flags & PCRE_JCHANGED) == 0) + return pcre16_get_stringnumber(code, stringname); +entrysize = pcre16_get_stringtable_entries(code, stringname, &first, &last); +#elif defined COMPILE_PCRE32 +if ((re->options & PCRE_DUPNAMES) == 0 && (re->flags & PCRE_JCHANGED) == 0) + return pcre32_get_stringnumber(code, stringname); +entrysize = pcre32_get_stringtable_entries(code, stringname, &first, &last); +#endif +if (entrysize <= 0) return entrysize; +for (entry = (pcre_uchar *)first; entry <= (pcre_uchar *)last; entry += entrysize) + { + int n = GET2(entry, 0); + if (ovector[n*2] >= 0) return n; + } +return GET2(entry, 0); +} + + + + +/************************************************* +* Copy captured string to given buffer * +*************************************************/ + +/* This function copies a single captured substring into a given buffer. +Note that we use memcpy() rather than strncpy() in case there are binary zeros +in the string. + +Arguments: + subject the subject string that was matched + ovector pointer to the offsets table + stringcount the number of substrings that were captured + (i.e. the yield of the pcre_exec call, unless + that was zero, in which case it should be 1/3 + of the offset table size) + stringnumber the number of the required substring + buffer where to put the substring + size the size of the buffer + +Returns: if successful: + the length of the copied string, not including the zero + that is put on the end; can be zero + if not successful: + PCRE_ERROR_NOMEMORY (-6) buffer too small + PCRE_ERROR_NOSUBSTRING (-7) no such captured substring +*/ + +#if defined COMPILE_PCRE8 +PCRE_EXP_DEFN int PCRE_CALL_CONVENTION +pcre_copy_substring(const char *subject, int *ovector, int stringcount, + int stringnumber, char *buffer, int size) +#elif defined COMPILE_PCRE16 +PCRE_EXP_DEFN int PCRE_CALL_CONVENTION +pcre16_copy_substring(PCRE_SPTR16 subject, int *ovector, int stringcount, + int stringnumber, PCRE_UCHAR16 *buffer, int size) +#elif defined COMPILE_PCRE32 +PCRE_EXP_DEFN int PCRE_CALL_CONVENTION +pcre32_copy_substring(PCRE_SPTR32 subject, int *ovector, int stringcount, + int stringnumber, PCRE_UCHAR32 *buffer, int size) +#endif +{ +int yield; +if (stringnumber < 0 || stringnumber >= stringcount) + return PCRE_ERROR_NOSUBSTRING; +stringnumber *= 2; +yield = ovector[stringnumber+1] - ovector[stringnumber]; +if (size < yield + 1) return PCRE_ERROR_NOMEMORY; +memcpy(buffer, subject + ovector[stringnumber], IN_UCHARS(yield)); +buffer[yield] = 0; +return yield; +} + + + +/************************************************* +* Copy named captured string to given buffer * +*************************************************/ + +/* This function copies a single captured substring into a given buffer, +identifying it by name. If the regex permits duplicate names, the first +substring that is set is chosen. + +Arguments: + code the compiled regex + subject the subject string that was matched + ovector pointer to the offsets table + stringcount the number of substrings that were captured + (i.e. the yield of the pcre_exec call, unless + that was zero, in which case it should be 1/3 + of the offset table size) + stringname the name of the required substring + buffer where to put the substring + size the size of the buffer + +Returns: if successful: + the length of the copied string, not including the zero + that is put on the end; can be zero + if not successful: + PCRE_ERROR_NOMEMORY (-6) buffer too small + PCRE_ERROR_NOSUBSTRING (-7) no such captured substring +*/ + +#if defined COMPILE_PCRE8 +PCRE_EXP_DEFN int PCRE_CALL_CONVENTION +pcre_copy_named_substring(const pcre *code, const char *subject, + int *ovector, int stringcount, const char *stringname, + char *buffer, int size) +#elif defined COMPILE_PCRE16 +PCRE_EXP_DEFN int PCRE_CALL_CONVENTION +pcre16_copy_named_substring(const pcre16 *code, PCRE_SPTR16 subject, + int *ovector, int stringcount, PCRE_SPTR16 stringname, + PCRE_UCHAR16 *buffer, int size) +#elif defined COMPILE_PCRE32 +PCRE_EXP_DEFN int PCRE_CALL_CONVENTION +pcre32_copy_named_substring(const pcre32 *code, PCRE_SPTR32 subject, + int *ovector, int stringcount, PCRE_SPTR32 stringname, + PCRE_UCHAR32 *buffer, int size) +#endif +{ +int n = get_first_set(code, stringname, ovector); +if (n <= 0) return n; +#if defined COMPILE_PCRE8 +return pcre_copy_substring(subject, ovector, stringcount, n, buffer, size); +#elif defined COMPILE_PCRE16 +return pcre16_copy_substring(subject, ovector, stringcount, n, buffer, size); +#elif defined COMPILE_PCRE32 +return pcre32_copy_substring(subject, ovector, stringcount, n, buffer, size); +#endif +} + + + +/************************************************* +* Copy all captured strings to new store * +*************************************************/ + +/* This function gets one chunk of store and builds a list of pointers and all +of the captured substrings in it. A NULL pointer is put on the end of the list. + +Arguments: + subject the subject string that was matched + ovector pointer to the offsets table + stringcount the number of substrings that were captured + (i.e. the yield of the pcre_exec call, unless + that was zero, in which case it should be 1/3 + of the offset table size) + listptr set to point to the list of pointers + +Returns: if successful: 0 + if not successful: + PCRE_ERROR_NOMEMORY (-6) failed to get store +*/ + +#if defined COMPILE_PCRE8 +PCRE_EXP_DEFN int PCRE_CALL_CONVENTION +pcre_get_substring_list(const char *subject, int *ovector, int stringcount, + const char ***listptr) +#elif defined COMPILE_PCRE16 +PCRE_EXP_DEFN int PCRE_CALL_CONVENTION +pcre16_get_substring_list(PCRE_SPTR16 subject, int *ovector, int stringcount, + PCRE_SPTR16 **listptr) +#elif defined COMPILE_PCRE32 +PCRE_EXP_DEFN int PCRE_CALL_CONVENTION +pcre32_get_substring_list(PCRE_SPTR32 subject, int *ovector, int stringcount, + PCRE_SPTR32 **listptr) +#endif +{ +int i; +int size = sizeof(pcre_uchar *); +int double_count = stringcount * 2; +pcre_uchar **stringlist; +pcre_uchar *p; + +for (i = 0; i < double_count; i += 2) + size += sizeof(pcre_uchar *) + IN_UCHARS(ovector[i+1] - ovector[i] + 1); + +stringlist = (pcre_uchar **)(PUBL(malloc))(size); +if (stringlist == NULL) return PCRE_ERROR_NOMEMORY; + +#if defined COMPILE_PCRE8 +*listptr = (const char **)stringlist; +#elif defined COMPILE_PCRE16 +*listptr = (PCRE_SPTR16 *)stringlist; +#elif defined COMPILE_PCRE32 +*listptr = (PCRE_SPTR32 *)stringlist; +#endif +p = (pcre_uchar *)(stringlist + stringcount + 1); + +for (i = 0; i < double_count; i += 2) + { + int len = ovector[i+1] - ovector[i]; + memcpy(p, subject + ovector[i], IN_UCHARS(len)); + *stringlist++ = p; + p += len; + *p++ = 0; + } + +*stringlist = NULL; +return 0; +} + + + +/************************************************* +* Free store obtained by get_substring_list * +*************************************************/ + +/* This function exists for the benefit of people calling PCRE from non-C +programs that can call its functions, but not free() or (PUBL(free))() +directly. + +Argument: the result of a previous pcre_get_substring_list() +Returns: nothing +*/ + +#if defined COMPILE_PCRE8 +PCRE_EXP_DEFN void PCRE_CALL_CONVENTION +pcre_free_substring_list(const char **pointer) +#elif defined COMPILE_PCRE16 +PCRE_EXP_DEFN void PCRE_CALL_CONVENTION +pcre16_free_substring_list(PCRE_SPTR16 *pointer) +#elif defined COMPILE_PCRE32 +PCRE_EXP_DEFN void PCRE_CALL_CONVENTION +pcre32_free_substring_list(PCRE_SPTR32 *pointer) +#endif +{ +(PUBL(free))((void *)pointer); +} + + + +/************************************************* +* Copy captured string to new store * +*************************************************/ + +/* This function copies a single captured substring into a piece of new +store + +Arguments: + subject the subject string that was matched + ovector pointer to the offsets table + stringcount the number of substrings that were captured + (i.e. the yield of the pcre_exec call, unless + that was zero, in which case it should be 1/3 + of the offset table size) + stringnumber the number of the required substring + stringptr where to put a pointer to the substring + +Returns: if successful: + the length of the string, not including the zero that + is put on the end; can be zero + if not successful: + PCRE_ERROR_NOMEMORY (-6) failed to get store + PCRE_ERROR_NOSUBSTRING (-7) substring not present +*/ + +#if defined COMPILE_PCRE8 +PCRE_EXP_DEFN int PCRE_CALL_CONVENTION +pcre_get_substring(const char *subject, int *ovector, int stringcount, + int stringnumber, const char **stringptr) +#elif defined COMPILE_PCRE16 +PCRE_EXP_DEFN int PCRE_CALL_CONVENTION +pcre16_get_substring(PCRE_SPTR16 subject, int *ovector, int stringcount, + int stringnumber, PCRE_SPTR16 *stringptr) +#elif defined COMPILE_PCRE32 +PCRE_EXP_DEFN int PCRE_CALL_CONVENTION +pcre32_get_substring(PCRE_SPTR32 subject, int *ovector, int stringcount, + int stringnumber, PCRE_SPTR32 *stringptr) +#endif +{ +int yield; +pcre_uchar *substring; +if (stringnumber < 0 || stringnumber >= stringcount) + return PCRE_ERROR_NOSUBSTRING; +stringnumber *= 2; +yield = ovector[stringnumber+1] - ovector[stringnumber]; +substring = (pcre_uchar *)(PUBL(malloc))(IN_UCHARS(yield + 1)); +if (substring == NULL) return PCRE_ERROR_NOMEMORY; +memcpy(substring, subject + ovector[stringnumber], IN_UCHARS(yield)); +substring[yield] = 0; +#if defined COMPILE_PCRE8 +*stringptr = (const char *)substring; +#elif defined COMPILE_PCRE16 +*stringptr = (PCRE_SPTR16)substring; +#elif defined COMPILE_PCRE32 +*stringptr = (PCRE_SPTR32)substring; +#endif +return yield; +} + + + +/************************************************* +* Copy named captured string to new store * +*************************************************/ + +/* This function copies a single captured substring, identified by name, into +new store. If the regex permits duplicate names, the first substring that is +set is chosen. + +Arguments: + code the compiled regex + subject the subject string that was matched + ovector pointer to the offsets table + stringcount the number of substrings that were captured + (i.e. the yield of the pcre_exec call, unless + that was zero, in which case it should be 1/3 + of the offset table size) + stringname the name of the required substring + stringptr where to put the pointer + +Returns: if successful: + the length of the copied string, not including the zero + that is put on the end; can be zero + if not successful: + PCRE_ERROR_NOMEMORY (-6) couldn't get memory + PCRE_ERROR_NOSUBSTRING (-7) no such captured substring +*/ + +#if defined COMPILE_PCRE8 +PCRE_EXP_DEFN int PCRE_CALL_CONVENTION +pcre_get_named_substring(const pcre *code, const char *subject, + int *ovector, int stringcount, const char *stringname, + const char **stringptr) +#elif defined COMPILE_PCRE16 +PCRE_EXP_DEFN int PCRE_CALL_CONVENTION +pcre16_get_named_substring(const pcre16 *code, PCRE_SPTR16 subject, + int *ovector, int stringcount, PCRE_SPTR16 stringname, + PCRE_SPTR16 *stringptr) +#elif defined COMPILE_PCRE32 +PCRE_EXP_DEFN int PCRE_CALL_CONVENTION +pcre32_get_named_substring(const pcre32 *code, PCRE_SPTR32 subject, + int *ovector, int stringcount, PCRE_SPTR32 stringname, + PCRE_SPTR32 *stringptr) +#endif +{ +int n = get_first_set(code, stringname, ovector); +if (n <= 0) return n; +#if defined COMPILE_PCRE8 +return pcre_get_substring(subject, ovector, stringcount, n, stringptr); +#elif defined COMPILE_PCRE16 +return pcre16_get_substring(subject, ovector, stringcount, n, stringptr); +#elif defined COMPILE_PCRE32 +return pcre32_get_substring(subject, ovector, stringcount, n, stringptr); +#endif +} + + + + +/************************************************* +* Free store obtained by get_substring * +*************************************************/ + +/* This function exists for the benefit of people calling PCRE from non-C +programs that can call its functions, but not free() or (PUBL(free))() +directly. + +Argument: the result of a previous pcre_get_substring() +Returns: nothing +*/ + +#if defined COMPILE_PCRE8 +PCRE_EXP_DEFN void PCRE_CALL_CONVENTION +pcre_free_substring(const char *pointer) +#elif defined COMPILE_PCRE16 +PCRE_EXP_DEFN void PCRE_CALL_CONVENTION +pcre16_free_substring(PCRE_SPTR16 pointer) +#elif defined COMPILE_PCRE32 +PCRE_EXP_DEFN void PCRE_CALL_CONVENTION +pcre32_free_substring(PCRE_SPTR32 pointer) +#endif +{ +(PUBL(free))((void *)pointer); +} + +/* End of pcre_get.c */ diff --git a/src/private/pcre_src/pcre_globals.c b/src/private/pcre_src/pcre_globals.c new file mode 100644 index 000000000..0f106aa90 --- /dev/null +++ b/src/private/pcre_src/pcre_globals.c @@ -0,0 +1,86 @@ +/************************************************* +* Perl-Compatible Regular Expressions * +*************************************************/ + +/* PCRE is a library of functions to support regular expressions whose syntax +and semantics are as close as possible to those of the Perl 5 language. + + Written by Philip Hazel + Copyright (c) 1997-2014 University of Cambridge + +----------------------------------------------------------------------------- +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * Neither the name of the University of Cambridge nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. +----------------------------------------------------------------------------- +*/ + + +/* This module contains global variables that are exported by the PCRE library. +PCRE is thread-clean and doesn't use any global variables in the normal sense. +However, it calls memory allocation and freeing functions via the four +indirections below, and it can optionally do callouts, using the fifth +indirection. These values can be changed by the caller, but are shared between +all threads. + +For MS Visual Studio and Symbian OS, there are problems in initializing these +variables to non-local functions. In these cases, therefore, an indirection via +a local function is used. + +Also, when compiling for Virtual Pascal, things are done differently, and +global variables are not used. */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "pcre_internal.h" + +#if defined _MSC_VER || defined __SYMBIAN32__ +static void* LocalPcreMalloc(size_t aSize) + { + return malloc(aSize); + } +static void LocalPcreFree(void* aPtr) + { + free(aPtr); + } +PCRE_EXP_DATA_DEFN void *(*PUBL(malloc))(size_t) = LocalPcreMalloc; +PCRE_EXP_DATA_DEFN void (*PUBL(free))(void *) = LocalPcreFree; +PCRE_EXP_DATA_DEFN void *(*PUBL(stack_malloc))(size_t) = LocalPcreMalloc; +PCRE_EXP_DATA_DEFN void (*PUBL(stack_free))(void *) = LocalPcreFree; +PCRE_EXP_DATA_DEFN int (*PUBL(callout))(PUBL(callout_block) *) = NULL; +PCRE_EXP_DATA_DEFN int (*PUBL(stack_guard))(void) = NULL; + +#elif !defined VPCOMPAT +PCRE_EXP_DATA_DEFN void *(*PUBL(malloc))(size_t) = malloc; +PCRE_EXP_DATA_DEFN void (*PUBL(free))(void *) = free; +PCRE_EXP_DATA_DEFN void *(*PUBL(stack_malloc))(size_t) = malloc; +PCRE_EXP_DATA_DEFN void (*PUBL(stack_free))(void *) = free; +PCRE_EXP_DATA_DEFN int (*PUBL(callout))(PUBL(callout_block) *) = NULL; +PCRE_EXP_DATA_DEFN int (*PUBL(stack_guard))(void) = NULL; +#endif + +/* End of pcre_globals.c */ diff --git a/src/private/pcre_src/pcre_internal.h b/src/private/pcre_src/pcre_internal.h new file mode 100644 index 000000000..02d3ab17c --- /dev/null +++ b/src/private/pcre_src/pcre_internal.h @@ -0,0 +1,2781 @@ +/************************************************* +* Perl-Compatible Regular Expressions * +*************************************************/ + + +/* PCRE is a library of functions to support regular expressions whose syntax +and semantics are as close as possible to those of the Perl 5 language. + + Written by Philip Hazel + Copyright (c) 1997-2014 University of Cambridge + +----------------------------------------------------------------------------- +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * Neither the name of the University of Cambridge nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. +----------------------------------------------------------------------------- +*/ + +/* This header contains definitions that are shared between the different +modules, but which are not relevant to the exported API. This includes some +functions whose names all begin with "_pcre_", "_pcre16_" or "_pcre32_" +depending on the PRIV macro. */ + +#ifndef PCRE_INTERNAL_H +#define PCRE_INTERNAL_H + +/* Define PCRE_DEBUG to get debugging output on stdout. */ + +#if 0 +#define PCRE_DEBUG +#endif + +/* PCRE is compiled as an 8 bit library if it is not requested otherwise. */ + +#if !defined COMPILE_PCRE16 && !defined COMPILE_PCRE32 +#define COMPILE_PCRE8 +#endif + +/* If SUPPORT_UCP is defined, SUPPORT_UTF must also be defined. The +"configure" script ensures this, but not everybody uses "configure". */ + +#if defined SUPPORT_UCP && !(defined SUPPORT_UTF) +#define SUPPORT_UTF 1 +#endif + +/* We define SUPPORT_UTF if SUPPORT_UTF8 is enabled for compatibility +reasons with existing code. */ + +#if defined SUPPORT_UTF8 && !(defined SUPPORT_UTF) +#define SUPPORT_UTF 1 +#endif + +/* Fixme: SUPPORT_UTF8 should be eventually disappear from the code. +Until then we define it if SUPPORT_UTF is defined. */ + +#if defined SUPPORT_UTF && !(defined SUPPORT_UTF8) +#define SUPPORT_UTF8 1 +#endif + +/* We do not support both EBCDIC and UTF-8/16/32 at the same time. The "configure" +script prevents both being selected, but not everybody uses "configure". */ + +#if defined EBCDIC && defined SUPPORT_UTF +#error The use of both EBCDIC and SUPPORT_UTF is not supported. +#endif + +/* Use a macro for debugging printing, 'cause that eliminates the use of #ifdef +inline, and there are *still* stupid compilers about that don't like indented +pre-processor statements, or at least there were when I first wrote this. After +all, it had only been about 10 years then... + +It turns out that the Mac Debugging.h header also defines the macro DPRINTF, so +be absolutely sure we get our version. */ + +#undef DPRINTF +#ifdef PCRE_DEBUG +#define DPRINTF(p) printf p +#else +#define DPRINTF(p) /* Nothing */ +#endif + + +/* Standard C headers plus the external interface definition. The only time +setjmp and stdarg are used is when NO_RECURSE is set. */ + +#include +#include +#include +#include +#include +#include + +/* Valgrind (memcheck) support */ + +#ifdef SUPPORT_VALGRIND +#include +#endif + +/* When compiling a DLL for Windows, the exported symbols have to be declared +using some MS magic. I found some useful information on this web page: +http://msdn2.microsoft.com/en-us/library/y4h7bcy6(VS.80).aspx. According to the +information there, using __declspec(dllexport) without "extern" we have a +definition; with "extern" we have a declaration. The settings here override the +setting in pcre.h (which is included below); it defines only PCRE_EXP_DECL, +which is all that is needed for applications (they just import the symbols). We +use: + + PCRE_EXP_DECL for declarations + PCRE_EXP_DEFN for definitions of exported functions + PCRE_EXP_DATA_DEFN for definitions of exported variables + +The reason for the two DEFN macros is that in non-Windows environments, one +does not want to have "extern" before variable definitions because it leads to +compiler warnings. So we distinguish between functions and variables. In +Windows, the two should always be the same. + +The reason for wrapping this in #ifndef PCRE_EXP_DECL is so that pcretest, +which is an application, but needs to import this file in order to "peek" at +internals, can #include pcre.h first to get an application's-eye view. + +In principle, people compiling for non-Windows, non-Unix-like (i.e. uncommon, +special-purpose environments) might want to stick other stuff in front of +exported symbols. That's why, in the non-Windows case, we set PCRE_EXP_DEFN and +PCRE_EXP_DATA_DEFN only if they are not already set. */ + +#ifndef PCRE_EXP_DECL +# ifdef _WIN32 +# ifndef PCRE_STATIC +# define PCRE_EXP_DECL extern __declspec(dllexport) +# define PCRE_EXP_DEFN __declspec(dllexport) +# define PCRE_EXP_DATA_DEFN __declspec(dllexport) +# else +# define PCRE_EXP_DECL extern +# define PCRE_EXP_DEFN +# define PCRE_EXP_DATA_DEFN +# endif +# else +# ifdef __cplusplus +# define PCRE_EXP_DECL extern "C" +# else +# define PCRE_EXP_DECL extern +# endif +# ifndef PCRE_EXP_DEFN +# define PCRE_EXP_DEFN PCRE_EXP_DECL +# endif +# ifndef PCRE_EXP_DATA_DEFN +# define PCRE_EXP_DATA_DEFN +# endif +# endif +#endif + +/* When compiling with the MSVC compiler, it is sometimes necessary to include +a "calling convention" before exported function names. (This is secondhand +information; I know nothing about MSVC myself). For example, something like + + void __cdecl function(....) + +might be needed. In order so make this easy, all the exported functions have +PCRE_CALL_CONVENTION just before their names. It is rarely needed; if not +set, we ensure here that it has no effect. */ + +#ifndef PCRE_CALL_CONVENTION +#define PCRE_CALL_CONVENTION +#endif + +/* We need to have types that specify unsigned 8, 16 and 32-bit integers. We +cannot determine these outside the compilation (e.g. by running a program as +part of "configure") because PCRE is often cross-compiled for use on other +systems. Instead we make use of the maximum sizes that are available at +preprocessor time in standard C environments. */ + +typedef unsigned char pcre_uint8; + +#if USHRT_MAX == 65535 +typedef unsigned short pcre_uint16; +typedef short pcre_int16; +#define PCRE_UINT16_MAX USHRT_MAX +#define PCRE_INT16_MAX SHRT_MAX +#elif UINT_MAX == 65535 +typedef unsigned int pcre_uint16; +typedef int pcre_int16; +#define PCRE_UINT16_MAX UINT_MAX +#define PCRE_INT16_MAX INT_MAX +#else +#error Cannot determine a type for 16-bit integers +#endif + +#if UINT_MAX == 4294967295U +typedef unsigned int pcre_uint32; +typedef int pcre_int32; +#define PCRE_UINT32_MAX UINT_MAX +#define PCRE_INT32_MAX INT_MAX +#elif ULONG_MAX == 4294967295UL +typedef unsigned long int pcre_uint32; +typedef long int pcre_int32; +#define PCRE_UINT32_MAX ULONG_MAX +#define PCRE_INT32_MAX LONG_MAX +#else +#error Cannot determine a type for 32-bit integers +#endif + +/* When checking for integer overflow in pcre_compile(), we need to handle +large integers. If a 64-bit integer type is available, we can use that. +Otherwise we have to cast to double, which of course requires floating point +arithmetic. Handle this by defining a macro for the appropriate type. If +stdint.h is available, include it; it may define INT64_MAX. Systems that do not +have stdint.h (e.g. Solaris) may have inttypes.h. The macro int64_t may be set +by "configure". */ + +#if defined HAVE_STDINT_H +#include +#elif defined HAVE_INTTYPES_H +#include +#endif + +#if defined INT64_MAX || defined int64_t +#define INT64_OR_DOUBLE int64_t +#else +#define INT64_OR_DOUBLE double +#endif + +/* All character handling must be done as unsigned characters. Otherwise there +are problems with top-bit-set characters and functions such as isspace(). +However, we leave the interface to the outside world as char * or short *, +because that should make things easier for callers. This character type is +called pcre_uchar. + +The IN_UCHARS macro multiply its argument with the byte size of the current +pcre_uchar type. Useful for memcpy and such operations, whose require the +byte size of their input/output buffers. + +The MAX_255 macro checks whether its pcre_uchar input is less than 256. + +The TABLE_GET macro is designed for accessing elements of tables whose contain +exactly 256 items. When the character is able to contain more than 256 +items, some check is needed before accessing these tables. +*/ + +#if defined COMPILE_PCRE8 + +typedef unsigned char pcre_uchar; +#define IN_UCHARS(x) (x) +#define MAX_255(c) 1 +#define TABLE_GET(c, table, default) ((table)[c]) + +#elif defined COMPILE_PCRE16 + +#if USHRT_MAX != 65535 +/* This is a warning message. Change PCRE_UCHAR16 to a 16 bit data type in +pcre.h(.in) and disable (comment out) this message. */ +#error Warning: PCRE_UCHAR16 is not a 16 bit data type. +#endif + +typedef pcre_uint16 pcre_uchar; +#define UCHAR_SHIFT (1) +#define IN_UCHARS(x) ((x) << UCHAR_SHIFT) +#define MAX_255(c) ((c) <= 255u) +#define TABLE_GET(c, table, default) (MAX_255(c)? ((table)[c]):(default)) + +#elif defined COMPILE_PCRE32 + +typedef pcre_uint32 pcre_uchar; +#define UCHAR_SHIFT (2) +#define IN_UCHARS(x) ((x) << UCHAR_SHIFT) +#define MAX_255(c) ((c) <= 255u) +#define TABLE_GET(c, table, default) (MAX_255(c)? ((table)[c]):(default)) + +#else +#error Unsupported compiling mode +#endif /* COMPILE_PCRE[8|16|32] */ + +/* This is an unsigned int value that no character can ever have. UTF-8 +characters only go up to 0x7fffffff (though Unicode doesn't go beyond +0x0010ffff). */ + +#define NOTACHAR 0xffffffff + +/* PCRE is able to support several different kinds of newline (CR, LF, CRLF, +"any" and "anycrlf" at present). The following macros are used to package up +testing for newlines. NLBLOCK, PSSTART, and PSEND are defined in the various +modules to indicate in which datablock the parameters exist, and what the +start/end of string field names are. */ + +#define NLTYPE_FIXED 0 /* Newline is a fixed length string */ +#define NLTYPE_ANY 1 /* Newline is any Unicode line ending */ +#define NLTYPE_ANYCRLF 2 /* Newline is CR, LF, or CRLF */ + +/* This macro checks for a newline at the given position */ + +#define IS_NEWLINE(p) \ + ((NLBLOCK->nltype != NLTYPE_FIXED)? \ + ((p) < NLBLOCK->PSEND && \ + PRIV(is_newline)((p), NLBLOCK->nltype, NLBLOCK->PSEND, \ + &(NLBLOCK->nllen), utf)) \ + : \ + ((p) <= NLBLOCK->PSEND - NLBLOCK->nllen && \ + UCHAR21TEST(p) == NLBLOCK->nl[0] && \ + (NLBLOCK->nllen == 1 || UCHAR21TEST(p+1) == NLBLOCK->nl[1]) \ + ) \ + ) + +/* This macro checks for a newline immediately preceding the given position */ + +#define WAS_NEWLINE(p) \ + ((NLBLOCK->nltype != NLTYPE_FIXED)? \ + ((p) > NLBLOCK->PSSTART && \ + PRIV(was_newline)((p), NLBLOCK->nltype, NLBLOCK->PSSTART, \ + &(NLBLOCK->nllen), utf)) \ + : \ + ((p) >= NLBLOCK->PSSTART + NLBLOCK->nllen && \ + UCHAR21TEST(p - NLBLOCK->nllen) == NLBLOCK->nl[0] && \ + (NLBLOCK->nllen == 1 || UCHAR21TEST(p - NLBLOCK->nllen + 1) == NLBLOCK->nl[1]) \ + ) \ + ) + +/* When PCRE is compiled as a C++ library, the subject pointer can be replaced +with a custom type. This makes it possible, for example, to allow pcre_exec() +to process subject strings that are discontinuous by using a smart pointer +class. It must always be possible to inspect all of the subject string in +pcre_exec() because of the way it backtracks. Two macros are required in the +normal case, for sign-unspecified and unsigned char pointers. The former is +used for the external interface and appears in pcre.h, which is why its name +must begin with PCRE_. */ + +#ifdef CUSTOM_SUBJECT_PTR +#define PCRE_PUCHAR CUSTOM_SUBJECT_PTR +#else +#define PCRE_PUCHAR const pcre_uchar * +#endif + +/* Include the public PCRE header and the definitions of UCP character property +values. */ + +#include "pcre.h" +#include "ucp.h" + +#ifdef COMPILE_PCRE32 +/* Assert that the public PCRE_UCHAR32 is a 32-bit type */ +typedef int __assert_pcre_uchar32_size[sizeof(PCRE_UCHAR32) == 4 ? 1 : -1]; +#endif + +/* When compiling for use with the Virtual Pascal compiler, these functions +need to have their names changed. PCRE must be compiled with the -DVPCOMPAT +option on the command line. */ + +#ifdef VPCOMPAT +#define strlen(s) _strlen(s) +#define strncmp(s1,s2,m) _strncmp(s1,s2,m) +#define memcmp(s,c,n) _memcmp(s,c,n) +#define memcpy(d,s,n) _memcpy(d,s,n) +#define memmove(d,s,n) _memmove(d,s,n) +#define memset(s,c,n) _memset(s,c,n) +#else /* VPCOMPAT */ + +/* To cope with SunOS4 and other systems that lack memmove() but have bcopy(), +define a macro for memmove() if HAVE_MEMMOVE is false, provided that HAVE_BCOPY +is set. Otherwise, include an emulating function for those systems that have +neither (there some non-Unix environments where this is the case). */ + +#ifndef HAVE_MEMMOVE +#undef memmove /* some systems may have a macro */ +#ifdef HAVE_BCOPY +#define memmove(a, b, c) bcopy(b, a, c) +#else /* HAVE_BCOPY */ +static void * +pcre_memmove(void *d, const void *s, size_t n) +{ +size_t i; +unsigned char *dest = (unsigned char *)d; +const unsigned char *src = (const unsigned char *)s; +if (dest > src) + { + dest += n; + src += n; + for (i = 0; i < n; ++i) *(--dest) = *(--src); + return (void *)dest; + } +else + { + for (i = 0; i < n; ++i) *dest++ = *src++; + return (void *)(dest - n); + } +} +#define memmove(a, b, c) pcre_memmove(a, b, c) +#endif /* not HAVE_BCOPY */ +#endif /* not HAVE_MEMMOVE */ +#endif /* not VPCOMPAT */ + + +/* PCRE keeps offsets in its compiled code as 2-byte quantities (always stored +in big-endian order) by default. These are used, for example, to link from the +start of a subpattern to its alternatives and its end. The use of 2 bytes per +offset limits the size of the compiled regex to around 64K, which is big enough +for almost everybody. However, I received a request for an even bigger limit. +For this reason, and also to make the code easier to maintain, the storing and +loading of offsets from the byte string is now handled by the macros that are +defined here. + +The macros are controlled by the value of LINK_SIZE. This defaults to 2 in +the config.h file, but can be overridden by using -D on the command line. This +is automated on Unix systems via the "configure" command. */ + +#if defined COMPILE_PCRE8 + +#if LINK_SIZE == 2 + +#define PUT(a,n,d) \ + (a[n] = (d) >> 8), \ + (a[(n)+1] = (d) & 255) + +#define GET(a,n) \ + (((a)[n] << 8) | (a)[(n)+1]) + +#define MAX_PATTERN_SIZE (1 << 16) + + +#elif LINK_SIZE == 3 + +#define PUT(a,n,d) \ + (a[n] = (d) >> 16), \ + (a[(n)+1] = (d) >> 8), \ + (a[(n)+2] = (d) & 255) + +#define GET(a,n) \ + (((a)[n] << 16) | ((a)[(n)+1] << 8) | (a)[(n)+2]) + +#define MAX_PATTERN_SIZE (1 << 24) + + +#elif LINK_SIZE == 4 + +#define PUT(a,n,d) \ + (a[n] = (d) >> 24), \ + (a[(n)+1] = (d) >> 16), \ + (a[(n)+2] = (d) >> 8), \ + (a[(n)+3] = (d) & 255) + +#define GET(a,n) \ + (((a)[n] << 24) | ((a)[(n)+1] << 16) | ((a)[(n)+2] << 8) | (a)[(n)+3]) + +/* Keep it positive */ +#define MAX_PATTERN_SIZE (1 << 30) + +#else +#error LINK_SIZE must be either 2, 3, or 4 +#endif + +#elif defined COMPILE_PCRE16 + +#if LINK_SIZE == 2 + +/* Redefine LINK_SIZE as a multiple of sizeof(pcre_uchar) */ +#undef LINK_SIZE +#define LINK_SIZE 1 + +#define PUT(a,n,d) \ + (a[n] = (d)) + +#define GET(a,n) \ + (a[n]) + +#define MAX_PATTERN_SIZE (1 << 16) + +#elif LINK_SIZE == 3 || LINK_SIZE == 4 + +/* Redefine LINK_SIZE as a multiple of sizeof(pcre_uchar) */ +#undef LINK_SIZE +#define LINK_SIZE 2 + +#define PUT(a,n,d) \ + (a[n] = (d) >> 16), \ + (a[(n)+1] = (d) & 65535) + +#define GET(a,n) \ + (((a)[n] << 16) | (a)[(n)+1]) + +/* Keep it positive */ +#define MAX_PATTERN_SIZE (1 << 30) + +#else +#error LINK_SIZE must be either 2, 3, or 4 +#endif + +#elif defined COMPILE_PCRE32 + +/* Only supported LINK_SIZE is 4 */ +/* Redefine LINK_SIZE as a multiple of sizeof(pcre_uchar) */ +#undef LINK_SIZE +#define LINK_SIZE 1 + +#define PUT(a,n,d) \ + (a[n] = (d)) + +#define GET(a,n) \ + (a[n]) + +/* Keep it positive */ +#define MAX_PATTERN_SIZE (1 << 30) + +#else +#error Unsupported compiling mode +#endif /* COMPILE_PCRE[8|16|32] */ + +/* Convenience macro defined in terms of the others */ + +#define PUTINC(a,n,d) PUT(a,n,d), a += LINK_SIZE + + +/* PCRE uses some other 2-byte quantities that do not change when the size of +offsets changes. There are used for repeat counts and for other things such as +capturing parenthesis numbers in back references. */ + +#if defined COMPILE_PCRE8 + +#define IMM2_SIZE 2 + +#define PUT2(a,n,d) \ + a[n] = (d) >> 8; \ + a[(n)+1] = (d) & 255 + +/* For reasons that I do not understand, the expression in this GET2 macro is +treated by gcc as a signed expression, even when a is declared as unsigned. It +seems that any kind of arithmetic results in a signed value. */ + +#define GET2(a,n) \ + (unsigned int)(((a)[n] << 8) | (a)[(n)+1]) + +#elif defined COMPILE_PCRE16 + +#define IMM2_SIZE 1 + +#define PUT2(a,n,d) \ + a[n] = d + +#define GET2(a,n) \ + a[n] + +#elif defined COMPILE_PCRE32 + +#define IMM2_SIZE 1 + +#define PUT2(a,n,d) \ + a[n] = d + +#define GET2(a,n) \ + a[n] + +#else +#error Unsupported compiling mode +#endif /* COMPILE_PCRE[8|16|32] */ + +#define PUT2INC(a,n,d) PUT2(a,n,d), a += IMM2_SIZE + +/* The maximum length of a MARK name is currently one data unit; it may be +changed in future to be a fixed number of bytes or to depend on LINK_SIZE. */ + +#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 +#define MAX_MARK ((1u << 16) - 1) +#else +#define MAX_MARK ((1u << 8) - 1) +#endif + +/* There is a proposed future special "UTF-21" mode, in which only the lowest +21 bits of a 32-bit character are interpreted as UTF, with the remaining 11 +high-order bits available to the application for other uses. In preparation for +the future implementation of this mode, there are macros that load a data item +and, if in this special mode, mask it to 21 bits. These macros all have names +starting with UCHAR21. In all other modes, including the normal 32-bit +library, the macros all have the same simple definitions. When the new mode is +implemented, it is expected that these definitions will be varied appropriately +using #ifdef when compiling the library that supports the special mode. */ + +#define UCHAR21(eptr) (*(eptr)) +#define UCHAR21TEST(eptr) (*(eptr)) +#define UCHAR21INC(eptr) (*(eptr)++) +#define UCHAR21INCTEST(eptr) (*(eptr)++) + +/* When UTF encoding is being used, a character is no longer just a single +byte in 8-bit mode or a single short in 16-bit mode. The macros for character +handling generate simple sequences when used in the basic mode, and more +complicated ones for UTF characters. GETCHARLENTEST and other macros are not +used when UTF is not supported. To make sure they can never even appear when +UTF support is omitted, we don't even define them. */ + +#ifndef SUPPORT_UTF + +/* #define MAX_VALUE_FOR_SINGLE_CHAR */ +/* #define HAS_EXTRALEN(c) */ +/* #define GET_EXTRALEN(c) */ +/* #define NOT_FIRSTCHAR(c) */ +#define GETCHAR(c, eptr) c = *eptr; +#define GETCHARTEST(c, eptr) c = *eptr; +#define GETCHARINC(c, eptr) c = *eptr++; +#define GETCHARINCTEST(c, eptr) c = *eptr++; +#define GETCHARLEN(c, eptr, len) c = *eptr; +/* #define GETCHARLENTEST(c, eptr, len) */ +/* #define BACKCHAR(eptr) */ +/* #define FORWARDCHAR(eptr) */ +/* #define ACROSSCHAR(condition, eptr, action) */ + +#else /* SUPPORT_UTF */ + +/* Tests whether the code point needs extra characters to decode. */ + +#define HASUTF8EXTRALEN(c) ((c) >= 0xc0) + +/* Base macro to pick up the remaining bytes of a UTF-8 character, not +advancing the pointer. */ + +#define GETUTF8(c, eptr) \ + { \ + if ((c & 0x20) == 0) \ + c = ((c & 0x1f) << 6) | (eptr[1] & 0x3f); \ + else if ((c & 0x10) == 0) \ + c = ((c & 0x0f) << 12) | ((eptr[1] & 0x3f) << 6) | (eptr[2] & 0x3f); \ + else if ((c & 0x08) == 0) \ + c = ((c & 0x07) << 18) | ((eptr[1] & 0x3f) << 12) | \ + ((eptr[2] & 0x3f) << 6) | (eptr[3] & 0x3f); \ + else if ((c & 0x04) == 0) \ + c = ((c & 0x03) << 24) | ((eptr[1] & 0x3f) << 18) | \ + ((eptr[2] & 0x3f) << 12) | ((eptr[3] & 0x3f) << 6) | \ + (eptr[4] & 0x3f); \ + else \ + c = ((c & 0x01) << 30) | ((eptr[1] & 0x3f) << 24) | \ + ((eptr[2] & 0x3f) << 18) | ((eptr[3] & 0x3f) << 12) | \ + ((eptr[4] & 0x3f) << 6) | (eptr[5] & 0x3f); \ + } + +/* Base macro to pick up the remaining bytes of a UTF-8 character, advancing +the pointer. */ + +#define GETUTF8INC(c, eptr) \ + { \ + if ((c & 0x20) == 0) \ + c = ((c & 0x1f) << 6) | (*eptr++ & 0x3f); \ + else if ((c & 0x10) == 0) \ + { \ + c = ((c & 0x0f) << 12) | ((*eptr & 0x3f) << 6) | (eptr[1] & 0x3f); \ + eptr += 2; \ + } \ + else if ((c & 0x08) == 0) \ + { \ + c = ((c & 0x07) << 18) | ((*eptr & 0x3f) << 12) | \ + ((eptr[1] & 0x3f) << 6) | (eptr[2] & 0x3f); \ + eptr += 3; \ + } \ + else if ((c & 0x04) == 0) \ + { \ + c = ((c & 0x03) << 24) | ((*eptr & 0x3f) << 18) | \ + ((eptr[1] & 0x3f) << 12) | ((eptr[2] & 0x3f) << 6) | \ + (eptr[3] & 0x3f); \ + eptr += 4; \ + } \ + else \ + { \ + c = ((c & 0x01) << 30) | ((*eptr & 0x3f) << 24) | \ + ((eptr[1] & 0x3f) << 18) | ((eptr[2] & 0x3f) << 12) | \ + ((eptr[3] & 0x3f) << 6) | (eptr[4] & 0x3f); \ + eptr += 5; \ + } \ + } + +#if defined COMPILE_PCRE8 + +/* These macros were originally written in the form of loops that used data +from the tables whose names start with PRIV(utf8_table). They were rewritten by +a user so as not to use loops, because in some environments this gives a +significant performance advantage, and it seems never to do any harm. */ + +/* Tells the biggest code point which can be encoded as a single character. */ + +#define MAX_VALUE_FOR_SINGLE_CHAR 127 + +/* Tests whether the code point needs extra characters to decode. */ + +#define HAS_EXTRALEN(c) ((c) >= 0xc0) + +/* Returns with the additional number of characters if IS_MULTICHAR(c) is TRUE. +Otherwise it has an undefined behaviour. */ + +#define GET_EXTRALEN(c) (PRIV(utf8_table4)[(c) & 0x3f]) + +/* Returns TRUE, if the given character is not the first character +of a UTF sequence. */ + +#define NOT_FIRSTCHAR(c) (((c) & 0xc0) == 0x80) + +/* Get the next UTF-8 character, not advancing the pointer. This is called when +we know we are in UTF-8 mode. */ + +#define GETCHAR(c, eptr) \ + c = *eptr; \ + if (c >= 0xc0) GETUTF8(c, eptr); + +/* Get the next UTF-8 character, testing for UTF-8 mode, and not advancing the +pointer. */ + +#define GETCHARTEST(c, eptr) \ + c = *eptr; \ + if (utf && c >= 0xc0) GETUTF8(c, eptr); + +/* Get the next UTF-8 character, advancing the pointer. This is called when we +know we are in UTF-8 mode. */ + +#define GETCHARINC(c, eptr) \ + c = *eptr++; \ + if (c >= 0xc0) GETUTF8INC(c, eptr); + +/* Get the next character, testing for UTF-8 mode, and advancing the pointer. +This is called when we don't know if we are in UTF-8 mode. */ + +#define GETCHARINCTEST(c, eptr) \ + c = *eptr++; \ + if (utf && c >= 0xc0) GETUTF8INC(c, eptr); + +/* Base macro to pick up the remaining bytes of a UTF-8 character, not +advancing the pointer, incrementing the length. */ + +#define GETUTF8LEN(c, eptr, len) \ + { \ + if ((c & 0x20) == 0) \ + { \ + c = ((c & 0x1f) << 6) | (eptr[1] & 0x3f); \ + len++; \ + } \ + else if ((c & 0x10) == 0) \ + { \ + c = ((c & 0x0f) << 12) | ((eptr[1] & 0x3f) << 6) | (eptr[2] & 0x3f); \ + len += 2; \ + } \ + else if ((c & 0x08) == 0) \ + {\ + c = ((c & 0x07) << 18) | ((eptr[1] & 0x3f) << 12) | \ + ((eptr[2] & 0x3f) << 6) | (eptr[3] & 0x3f); \ + len += 3; \ + } \ + else if ((c & 0x04) == 0) \ + { \ + c = ((c & 0x03) << 24) | ((eptr[1] & 0x3f) << 18) | \ + ((eptr[2] & 0x3f) << 12) | ((eptr[3] & 0x3f) << 6) | \ + (eptr[4] & 0x3f); \ + len += 4; \ + } \ + else \ + {\ + c = ((c & 0x01) << 30) | ((eptr[1] & 0x3f) << 24) | \ + ((eptr[2] & 0x3f) << 18) | ((eptr[3] & 0x3f) << 12) | \ + ((eptr[4] & 0x3f) << 6) | (eptr[5] & 0x3f); \ + len += 5; \ + } \ + } + +/* Get the next UTF-8 character, not advancing the pointer, incrementing length +if there are extra bytes. This is called when we know we are in UTF-8 mode. */ + +#define GETCHARLEN(c, eptr, len) \ + c = *eptr; \ + if (c >= 0xc0) GETUTF8LEN(c, eptr, len); + +/* Get the next UTF-8 character, testing for UTF-8 mode, not advancing the +pointer, incrementing length if there are extra bytes. This is called when we +do not know if we are in UTF-8 mode. */ + +#define GETCHARLENTEST(c, eptr, len) \ + c = *eptr; \ + if (utf && c >= 0xc0) GETUTF8LEN(c, eptr, len); + +/* If the pointer is not at the start of a character, move it back until +it is. This is called only in UTF-8 mode - we don't put a test within the macro +because almost all calls are already within a block of UTF-8 only code. */ + +#define BACKCHAR(eptr) while((*eptr & 0xc0) == 0x80) eptr-- + +/* Same as above, just in the other direction. */ +#define FORWARDCHAR(eptr) while((*eptr & 0xc0) == 0x80) eptr++ + +/* Same as above, but it allows a fully customizable form. */ +#define ACROSSCHAR(condition, eptr, action) \ + while((condition) && ((eptr) & 0xc0) == 0x80) action + +#elif defined COMPILE_PCRE16 + +/* Tells the biggest code point which can be encoded as a single character. */ + +#define MAX_VALUE_FOR_SINGLE_CHAR 65535 + +/* Tests whether the code point needs extra characters to decode. */ + +#define HAS_EXTRALEN(c) (((c) & 0xfc00) == 0xd800) + +/* Returns with the additional number of characters if IS_MULTICHAR(c) is TRUE. +Otherwise it has an undefined behaviour. */ + +#define GET_EXTRALEN(c) 1 + +/* Returns TRUE, if the given character is not the first character +of a UTF sequence. */ + +#define NOT_FIRSTCHAR(c) (((c) & 0xfc00) == 0xdc00) + +/* Base macro to pick up the low surrogate of a UTF-16 character, not +advancing the pointer. */ + +#define GETUTF16(c, eptr) \ + { c = (((c & 0x3ff) << 10) | (eptr[1] & 0x3ff)) + 0x10000; } + +/* Get the next UTF-16 character, not advancing the pointer. This is called when +we know we are in UTF-16 mode. */ + +#define GETCHAR(c, eptr) \ + c = *eptr; \ + if ((c & 0xfc00) == 0xd800) GETUTF16(c, eptr); + +/* Get the next UTF-16 character, testing for UTF-16 mode, and not advancing the +pointer. */ + +#define GETCHARTEST(c, eptr) \ + c = *eptr; \ + if (utf && (c & 0xfc00) == 0xd800) GETUTF16(c, eptr); + +/* Base macro to pick up the low surrogate of a UTF-16 character, advancing +the pointer. */ + +#define GETUTF16INC(c, eptr) \ + { c = (((c & 0x3ff) << 10) | (*eptr++ & 0x3ff)) + 0x10000; } + +/* Get the next UTF-16 character, advancing the pointer. This is called when we +know we are in UTF-16 mode. */ + +#define GETCHARINC(c, eptr) \ + c = *eptr++; \ + if ((c & 0xfc00) == 0xd800) GETUTF16INC(c, eptr); + +/* Get the next character, testing for UTF-16 mode, and advancing the pointer. +This is called when we don't know if we are in UTF-16 mode. */ + +#define GETCHARINCTEST(c, eptr) \ + c = *eptr++; \ + if (utf && (c & 0xfc00) == 0xd800) GETUTF16INC(c, eptr); + +/* Base macro to pick up the low surrogate of a UTF-16 character, not +advancing the pointer, incrementing the length. */ + +#define GETUTF16LEN(c, eptr, len) \ + { c = (((c & 0x3ff) << 10) | (eptr[1] & 0x3ff)) + 0x10000; len++; } + +/* Get the next UTF-16 character, not advancing the pointer, incrementing +length if there is a low surrogate. This is called when we know we are in +UTF-16 mode. */ + +#define GETCHARLEN(c, eptr, len) \ + c = *eptr; \ + if ((c & 0xfc00) == 0xd800) GETUTF16LEN(c, eptr, len); + +/* Get the next UTF-816character, testing for UTF-16 mode, not advancing the +pointer, incrementing length if there is a low surrogate. This is called when +we do not know if we are in UTF-16 mode. */ + +#define GETCHARLENTEST(c, eptr, len) \ + c = *eptr; \ + if (utf && (c & 0xfc00) == 0xd800) GETUTF16LEN(c, eptr, len); + +/* If the pointer is not at the start of a character, move it back until +it is. This is called only in UTF-16 mode - we don't put a test within the +macro because almost all calls are already within a block of UTF-16 only +code. */ + +#define BACKCHAR(eptr) if ((*eptr & 0xfc00) == 0xdc00) eptr-- + +/* Same as above, just in the other direction. */ +#define FORWARDCHAR(eptr) if ((*eptr & 0xfc00) == 0xdc00) eptr++ + +/* Same as above, but it allows a fully customizable form. */ +#define ACROSSCHAR(condition, eptr, action) \ + if ((condition) && ((eptr) & 0xfc00) == 0xdc00) action + +#elif defined COMPILE_PCRE32 + +/* These are trivial for the 32-bit library, since all UTF-32 characters fit +into one pcre_uchar unit. */ +#define MAX_VALUE_FOR_SINGLE_CHAR (0x10ffffu) +#define HAS_EXTRALEN(c) (0) +#define GET_EXTRALEN(c) (0) +#define NOT_FIRSTCHAR(c) (0) + +/* Get the next UTF-32 character, not advancing the pointer. This is called when +we know we are in UTF-32 mode. */ + +#define GETCHAR(c, eptr) \ + c = *(eptr); + +/* Get the next UTF-32 character, testing for UTF-32 mode, and not advancing the +pointer. */ + +#define GETCHARTEST(c, eptr) \ + c = *(eptr); + +/* Get the next UTF-32 character, advancing the pointer. This is called when we +know we are in UTF-32 mode. */ + +#define GETCHARINC(c, eptr) \ + c = *((eptr)++); + +/* Get the next character, testing for UTF-32 mode, and advancing the pointer. +This is called when we don't know if we are in UTF-32 mode. */ + +#define GETCHARINCTEST(c, eptr) \ + c = *((eptr)++); + +/* Get the next UTF-32 character, not advancing the pointer, not incrementing +length (since all UTF-32 is of length 1). This is called when we know we are in +UTF-32 mode. */ + +#define GETCHARLEN(c, eptr, len) \ + GETCHAR(c, eptr) + +/* Get the next UTF-32character, testing for UTF-32 mode, not advancing the +pointer, not incrementing the length (since all UTF-32 is of length 1). +This is called when we do not know if we are in UTF-32 mode. */ + +#define GETCHARLENTEST(c, eptr, len) \ + GETCHARTEST(c, eptr) + +/* If the pointer is not at the start of a character, move it back until +it is. This is called only in UTF-32 mode - we don't put a test within the +macro because almost all calls are already within a block of UTF-32 only +code. +These are all no-ops since all UTF-32 characters fit into one pcre_uchar. */ + +#define BACKCHAR(eptr) do { } while (0) + +/* Same as above, just in the other direction. */ +#define FORWARDCHAR(eptr) do { } while (0) + +/* Same as above, but it allows a fully customizable form. */ +#define ACROSSCHAR(condition, eptr, action) do { } while (0) + +#else +#error Unsupported compiling mode +#endif /* COMPILE_PCRE[8|16|32] */ + +#endif /* SUPPORT_UTF */ + +/* Tests for Unicode horizontal and vertical whitespace characters must check a +number of different values. Using a switch statement for this generates the +fastest code (no loop, no memory access), and there are several places in the +interpreter code where this happens. In order to ensure that all the case lists +remain in step, we use macros so that there is only one place where the lists +are defined. + +These values are also required as lists in pcre_compile.c when processing \h, +\H, \v and \V in a character class. The lists are defined in pcre_tables.c, but +macros that define the values are here so that all the definitions are +together. The lists must be in ascending character order, terminated by +NOTACHAR (which is 0xffffffff). + +Any changes should ensure that the various macros are kept in step with each +other. NOTE: The values also appear in pcre_jit_compile.c. */ + +/* ------ ASCII/Unicode environments ------ */ + +#ifndef EBCDIC + +#define HSPACE_LIST \ + CHAR_HT, CHAR_SPACE, 0xa0, \ + 0x1680, 0x180e, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, \ + 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202f, 0x205f, 0x3000, \ + NOTACHAR + +#define HSPACE_MULTIBYTE_CASES \ + case 0x1680: /* OGHAM SPACE MARK */ \ + case 0x180e: /* MONGOLIAN VOWEL SEPARATOR */ \ + case 0x2000: /* EN QUAD */ \ + case 0x2001: /* EM QUAD */ \ + case 0x2002: /* EN SPACE */ \ + case 0x2003: /* EM SPACE */ \ + case 0x2004: /* THREE-PER-EM SPACE */ \ + case 0x2005: /* FOUR-PER-EM SPACE */ \ + case 0x2006: /* SIX-PER-EM SPACE */ \ + case 0x2007: /* FIGURE SPACE */ \ + case 0x2008: /* PUNCTUATION SPACE */ \ + case 0x2009: /* THIN SPACE */ \ + case 0x200A: /* HAIR SPACE */ \ + case 0x202f: /* NARROW NO-BREAK SPACE */ \ + case 0x205f: /* MEDIUM MATHEMATICAL SPACE */ \ + case 0x3000 /* IDEOGRAPHIC SPACE */ + +#define HSPACE_BYTE_CASES \ + case CHAR_HT: \ + case CHAR_SPACE: \ + case 0xa0 /* NBSP */ + +#define HSPACE_CASES \ + HSPACE_BYTE_CASES: \ + HSPACE_MULTIBYTE_CASES + +#define VSPACE_LIST \ + CHAR_LF, CHAR_VT, CHAR_FF, CHAR_CR, CHAR_NEL, 0x2028, 0x2029, NOTACHAR + +#define VSPACE_MULTIBYTE_CASES \ + case 0x2028: /* LINE SEPARATOR */ \ + case 0x2029 /* PARAGRAPH SEPARATOR */ + +#define VSPACE_BYTE_CASES \ + case CHAR_LF: \ + case CHAR_VT: \ + case CHAR_FF: \ + case CHAR_CR: \ + case CHAR_NEL + +#define VSPACE_CASES \ + VSPACE_BYTE_CASES: \ + VSPACE_MULTIBYTE_CASES + +/* ------ EBCDIC environments ------ */ + +#else +#define HSPACE_LIST CHAR_HT, CHAR_SPACE + +#define HSPACE_BYTE_CASES \ + case CHAR_HT: \ + case CHAR_SPACE + +#define HSPACE_CASES HSPACE_BYTE_CASES + +#ifdef EBCDIC_NL25 +#define VSPACE_LIST \ + CHAR_VT, CHAR_FF, CHAR_CR, CHAR_NEL, CHAR_LF, NOTACHAR +#else +#define VSPACE_LIST \ + CHAR_VT, CHAR_FF, CHAR_CR, CHAR_LF, CHAR_NEL, NOTACHAR +#endif + +#define VSPACE_BYTE_CASES \ + case CHAR_LF: \ + case CHAR_VT: \ + case CHAR_FF: \ + case CHAR_CR: \ + case CHAR_NEL + +#define VSPACE_CASES VSPACE_BYTE_CASES +#endif /* EBCDIC */ + +/* ------ End of whitespace macros ------ */ + + + +/* Private flags containing information about the compiled regex. They used to +live at the top end of the options word, but that got almost full, so they were +moved to a 16-bit flags word - which got almost full, so now they are in a +32-bit flags word. From release 8.00, PCRE_NOPARTIAL is unused, as the +restrictions on partial matching have been lifted. It remains for backwards +compatibility. */ + +#define PCRE_MODE8 0x00000001 /* compiled in 8 bit mode */ +#define PCRE_MODE16 0x00000002 /* compiled in 16 bit mode */ +#define PCRE_MODE32 0x00000004 /* compiled in 32 bit mode */ +#define PCRE_FIRSTSET 0x00000010 /* first_char is set */ +#define PCRE_FCH_CASELESS 0x00000020 /* caseless first char */ +#define PCRE_REQCHSET 0x00000040 /* req_byte is set */ +#define PCRE_RCH_CASELESS 0x00000080 /* caseless requested char */ +#define PCRE_STARTLINE 0x00000100 /* start after \n for multiline */ +#define PCRE_NOPARTIAL 0x00000200 /* can't use partial with this regex */ +#define PCRE_JCHANGED 0x00000400 /* j option used in regex */ +#define PCRE_HASCRORLF 0x00000800 /* explicit \r or \n in pattern */ +#define PCRE_HASTHEN 0x00001000 /* pattern contains (*THEN) */ +#define PCRE_MLSET 0x00002000 /* match limit set by regex */ +#define PCRE_RLSET 0x00004000 /* recursion limit set by regex */ +#define PCRE_MATCH_EMPTY 0x00008000 /* pattern can match empty string */ + +#if defined COMPILE_PCRE8 +#define PCRE_MODE PCRE_MODE8 +#elif defined COMPILE_PCRE16 +#define PCRE_MODE PCRE_MODE16 +#elif defined COMPILE_PCRE32 +#define PCRE_MODE PCRE_MODE32 +#endif +#define PCRE_MODE_MASK (PCRE_MODE8 | PCRE_MODE16 | PCRE_MODE32) + +/* Flags for the "extra" block produced by pcre_study(). */ + +#define PCRE_STUDY_MAPPED 0x0001 /* a map of starting chars exists */ +#define PCRE_STUDY_MINLEN 0x0002 /* a minimum length field exists */ + +/* Masks for identifying the public options that are permitted at compile +time, run time, or study time, respectively. */ + +#define PCRE_NEWLINE_BITS (PCRE_NEWLINE_CR|PCRE_NEWLINE_LF|PCRE_NEWLINE_ANY| \ + PCRE_NEWLINE_ANYCRLF) + +#define PUBLIC_COMPILE_OPTIONS \ + (PCRE_CASELESS|PCRE_EXTENDED|PCRE_ANCHORED|PCRE_MULTILINE| \ + PCRE_DOTALL|PCRE_DOLLAR_ENDONLY|PCRE_EXTRA|PCRE_UNGREEDY|PCRE_UTF8| \ + PCRE_NO_AUTO_CAPTURE|PCRE_NO_AUTO_POSSESS| \ + PCRE_NO_UTF8_CHECK|PCRE_AUTO_CALLOUT|PCRE_FIRSTLINE| \ + PCRE_DUPNAMES|PCRE_NEWLINE_BITS|PCRE_BSR_ANYCRLF|PCRE_BSR_UNICODE| \ + PCRE_JAVASCRIPT_COMPAT|PCRE_UCP|PCRE_NO_START_OPTIMIZE|PCRE_NEVER_UTF) + +#define PUBLIC_EXEC_OPTIONS \ + (PCRE_ANCHORED|PCRE_NOTBOL|PCRE_NOTEOL|PCRE_NOTEMPTY|PCRE_NOTEMPTY_ATSTART| \ + PCRE_NO_UTF8_CHECK|PCRE_PARTIAL_HARD|PCRE_PARTIAL_SOFT|PCRE_NEWLINE_BITS| \ + PCRE_BSR_ANYCRLF|PCRE_BSR_UNICODE|PCRE_NO_START_OPTIMIZE) + +#define PUBLIC_DFA_EXEC_OPTIONS \ + (PCRE_ANCHORED|PCRE_NOTBOL|PCRE_NOTEOL|PCRE_NOTEMPTY|PCRE_NOTEMPTY_ATSTART| \ + PCRE_NO_UTF8_CHECK|PCRE_PARTIAL_HARD|PCRE_PARTIAL_SOFT|PCRE_DFA_SHORTEST| \ + PCRE_DFA_RESTART|PCRE_NEWLINE_BITS|PCRE_BSR_ANYCRLF|PCRE_BSR_UNICODE| \ + PCRE_NO_START_OPTIMIZE) + +#define PUBLIC_STUDY_OPTIONS \ + (PCRE_STUDY_JIT_COMPILE|PCRE_STUDY_JIT_PARTIAL_SOFT_COMPILE| \ + PCRE_STUDY_JIT_PARTIAL_HARD_COMPILE|PCRE_STUDY_EXTRA_NEEDED) + +#define PUBLIC_JIT_EXEC_OPTIONS \ + (PCRE_NO_UTF8_CHECK|PCRE_NOTBOL|PCRE_NOTEOL|PCRE_NOTEMPTY|\ + PCRE_NOTEMPTY_ATSTART|PCRE_PARTIAL_SOFT|PCRE_PARTIAL_HARD) + +/* Magic number to provide a small check against being handed junk. */ + +#define MAGIC_NUMBER 0x50435245UL /* 'PCRE' */ + +/* This variable is used to detect a loaded regular expression +in different endianness. */ + +#define REVERSED_MAGIC_NUMBER 0x45524350UL /* 'ERCP' */ + +/* The maximum remaining length of subject we are prepared to search for a +req_byte match. */ + +#define REQ_BYTE_MAX 1000 + +/* Miscellaneous definitions. The #ifndef is to pacify compiler warnings in +environments where these macros are defined elsewhere. Unfortunately, there +is no way to do the same for the typedef. */ + +typedef int BOOL; + +#ifndef FALSE +#define FALSE 0 +#define TRUE 1 +#endif + +/* If PCRE is to support UTF-8 on EBCDIC platforms, we cannot use normal +character constants like '*' because the compiler would emit their EBCDIC code, +which is different from their ASCII/UTF-8 code. Instead we define macros for +the characters so that they always use the ASCII/UTF-8 code when UTF-8 support +is enabled. When UTF-8 support is not enabled, the definitions use character +literals. Both character and string versions of each character are needed, and +there are some longer strings as well. + +This means that, on EBCDIC platforms, the PCRE library can handle either +EBCDIC, or UTF-8, but not both. To support both in the same compiled library +would need different lookups depending on whether PCRE_UTF8 was set or not. +This would make it impossible to use characters in switch/case statements, +which would reduce performance. For a theoretical use (which nobody has asked +for) in a minority area (EBCDIC platforms), this is not sensible. Any +application that did need both could compile two versions of the library, using +macros to give the functions distinct names. */ + +#ifndef SUPPORT_UTF + +/* UTF-8 support is not enabled; use the platform-dependent character literals +so that PCRE works in both ASCII and EBCDIC environments, but only in non-UTF +mode. Newline characters are problematic in EBCDIC. Though it has CR and LF +characters, a common practice has been to use its NL (0x15) character as the +line terminator in C-like processing environments. However, sometimes the LF +(0x25) character is used instead, according to this Unicode document: + +http://unicode.org/standard/reports/tr13/tr13-5.html + +PCRE defaults EBCDIC NL to 0x15, but has a build-time option to select 0x25 +instead. Whichever is *not* chosen is defined as NEL. + +In both ASCII and EBCDIC environments, CHAR_NL and CHAR_LF are synonyms for the +same code point. */ + +#ifdef EBCDIC + +#ifndef EBCDIC_NL25 +#define CHAR_NL '\x15' +#define CHAR_NEL '\x25' +#define STR_NL "\x15" +#define STR_NEL "\x25" +#else +#define CHAR_NL '\x25' +#define CHAR_NEL '\x15' +#define STR_NL "\x25" +#define STR_NEL "\x15" +#endif + +#define CHAR_LF CHAR_NL +#define STR_LF STR_NL + +#define CHAR_ESC '\047' +#define CHAR_DEL '\007' +#define STR_ESC "\047" +#define STR_DEL "\007" + +#else /* Not EBCDIC */ + +/* In ASCII/Unicode, linefeed is '\n' and we equate this to NL for +compatibility. NEL is the Unicode newline character; make sure it is +a positive value. */ + +#define CHAR_LF '\n' +#define CHAR_NL CHAR_LF +#define CHAR_NEL ((unsigned char)'\x85') +#define CHAR_ESC '\033' +#define CHAR_DEL '\177' + +#define STR_LF "\n" +#define STR_NL STR_LF +#define STR_NEL "\x85" +#define STR_ESC "\033" +#define STR_DEL "\177" + +#endif /* EBCDIC */ + +/* The remaining definitions work in both environments. */ + +#define CHAR_NULL '\0' +#define CHAR_HT '\t' +#define CHAR_VT '\v' +#define CHAR_FF '\f' +#define CHAR_CR '\r' +#define CHAR_BS '\b' +#define CHAR_BEL '\a' + +#define CHAR_SPACE ' ' +#define CHAR_EXCLAMATION_MARK '!' +#define CHAR_QUOTATION_MARK '"' +#define CHAR_NUMBER_SIGN '#' +#define CHAR_DOLLAR_SIGN '$' +#define CHAR_PERCENT_SIGN '%' +#define CHAR_AMPERSAND '&' +#define CHAR_APOSTROPHE '\'' +#define CHAR_LEFT_PARENTHESIS '(' +#define CHAR_RIGHT_PARENTHESIS ')' +#define CHAR_ASTERISK '*' +#define CHAR_PLUS '+' +#define CHAR_COMMA ',' +#define CHAR_MINUS '-' +#define CHAR_DOT '.' +#define CHAR_SLASH '/' +#define CHAR_0 '0' +#define CHAR_1 '1' +#define CHAR_2 '2' +#define CHAR_3 '3' +#define CHAR_4 '4' +#define CHAR_5 '5' +#define CHAR_6 '6' +#define CHAR_7 '7' +#define CHAR_8 '8' +#define CHAR_9 '9' +#define CHAR_COLON ':' +#define CHAR_SEMICOLON ';' +#define CHAR_LESS_THAN_SIGN '<' +#define CHAR_EQUALS_SIGN '=' +#define CHAR_GREATER_THAN_SIGN '>' +#define CHAR_QUESTION_MARK '?' +#define CHAR_COMMERCIAL_AT '@' +#define CHAR_A 'A' +#define CHAR_B 'B' +#define CHAR_C 'C' +#define CHAR_D 'D' +#define CHAR_E 'E' +#define CHAR_F 'F' +#define CHAR_G 'G' +#define CHAR_H 'H' +#define CHAR_I 'I' +#define CHAR_J 'J' +#define CHAR_K 'K' +#define CHAR_L 'L' +#define CHAR_M 'M' +#define CHAR_N 'N' +#define CHAR_O 'O' +#define CHAR_P 'P' +#define CHAR_Q 'Q' +#define CHAR_R 'R' +#define CHAR_S 'S' +#define CHAR_T 'T' +#define CHAR_U 'U' +#define CHAR_V 'V' +#define CHAR_W 'W' +#define CHAR_X 'X' +#define CHAR_Y 'Y' +#define CHAR_Z 'Z' +#define CHAR_LEFT_SQUARE_BRACKET '[' +#define CHAR_BACKSLASH '\\' +#define CHAR_RIGHT_SQUARE_BRACKET ']' +#define CHAR_CIRCUMFLEX_ACCENT '^' +#define CHAR_UNDERSCORE '_' +#define CHAR_GRAVE_ACCENT '`' +#define CHAR_a 'a' +#define CHAR_b 'b' +#define CHAR_c 'c' +#define CHAR_d 'd' +#define CHAR_e 'e' +#define CHAR_f 'f' +#define CHAR_g 'g' +#define CHAR_h 'h' +#define CHAR_i 'i' +#define CHAR_j 'j' +#define CHAR_k 'k' +#define CHAR_l 'l' +#define CHAR_m 'm' +#define CHAR_n 'n' +#define CHAR_o 'o' +#define CHAR_p 'p' +#define CHAR_q 'q' +#define CHAR_r 'r' +#define CHAR_s 's' +#define CHAR_t 't' +#define CHAR_u 'u' +#define CHAR_v 'v' +#define CHAR_w 'w' +#define CHAR_x 'x' +#define CHAR_y 'y' +#define CHAR_z 'z' +#define CHAR_LEFT_CURLY_BRACKET '{' +#define CHAR_VERTICAL_LINE '|' +#define CHAR_RIGHT_CURLY_BRACKET '}' +#define CHAR_TILDE '~' + +#define STR_HT "\t" +#define STR_VT "\v" +#define STR_FF "\f" +#define STR_CR "\r" +#define STR_BS "\b" +#define STR_BEL "\a" + +#define STR_SPACE " " +#define STR_EXCLAMATION_MARK "!" +#define STR_QUOTATION_MARK "\"" +#define STR_NUMBER_SIGN "#" +#define STR_DOLLAR_SIGN "$" +#define STR_PERCENT_SIGN "%" +#define STR_AMPERSAND "&" +#define STR_APOSTROPHE "'" +#define STR_LEFT_PARENTHESIS "(" +#define STR_RIGHT_PARENTHESIS ")" +#define STR_ASTERISK "*" +#define STR_PLUS "+" +#define STR_COMMA "," +#define STR_MINUS "-" +#define STR_DOT "." +#define STR_SLASH "/" +#define STR_0 "0" +#define STR_1 "1" +#define STR_2 "2" +#define STR_3 "3" +#define STR_4 "4" +#define STR_5 "5" +#define STR_6 "6" +#define STR_7 "7" +#define STR_8 "8" +#define STR_9 "9" +#define STR_COLON ":" +#define STR_SEMICOLON ";" +#define STR_LESS_THAN_SIGN "<" +#define STR_EQUALS_SIGN "=" +#define STR_GREATER_THAN_SIGN ">" +#define STR_QUESTION_MARK "?" +#define STR_COMMERCIAL_AT "@" +#define STR_A "A" +#define STR_B "B" +#define STR_C "C" +#define STR_D "D" +#define STR_E "E" +#define STR_F "F" +#define STR_G "G" +#define STR_H "H" +#define STR_I "I" +#define STR_J "J" +#define STR_K "K" +#define STR_L "L" +#define STR_M "M" +#define STR_N "N" +#define STR_O "O" +#define STR_P "P" +#define STR_Q "Q" +#define STR_R "R" +#define STR_S "S" +#define STR_T "T" +#define STR_U "U" +#define STR_V "V" +#define STR_W "W" +#define STR_X "X" +#define STR_Y "Y" +#define STR_Z "Z" +#define STR_LEFT_SQUARE_BRACKET "[" +#define STR_BACKSLASH "\\" +#define STR_RIGHT_SQUARE_BRACKET "]" +#define STR_CIRCUMFLEX_ACCENT "^" +#define STR_UNDERSCORE "_" +#define STR_GRAVE_ACCENT "`" +#define STR_a "a" +#define STR_b "b" +#define STR_c "c" +#define STR_d "d" +#define STR_e "e" +#define STR_f "f" +#define STR_g "g" +#define STR_h "h" +#define STR_i "i" +#define STR_j "j" +#define STR_k "k" +#define STR_l "l" +#define STR_m "m" +#define STR_n "n" +#define STR_o "o" +#define STR_p "p" +#define STR_q "q" +#define STR_r "r" +#define STR_s "s" +#define STR_t "t" +#define STR_u "u" +#define STR_v "v" +#define STR_w "w" +#define STR_x "x" +#define STR_y "y" +#define STR_z "z" +#define STR_LEFT_CURLY_BRACKET "{" +#define STR_VERTICAL_LINE "|" +#define STR_RIGHT_CURLY_BRACKET "}" +#define STR_TILDE "~" + +#define STRING_ACCEPT0 "ACCEPT\0" +#define STRING_COMMIT0 "COMMIT\0" +#define STRING_F0 "F\0" +#define STRING_FAIL0 "FAIL\0" +#define STRING_MARK0 "MARK\0" +#define STRING_PRUNE0 "PRUNE\0" +#define STRING_SKIP0 "SKIP\0" +#define STRING_THEN "THEN" + +#define STRING_alpha0 "alpha\0" +#define STRING_lower0 "lower\0" +#define STRING_upper0 "upper\0" +#define STRING_alnum0 "alnum\0" +#define STRING_ascii0 "ascii\0" +#define STRING_blank0 "blank\0" +#define STRING_cntrl0 "cntrl\0" +#define STRING_digit0 "digit\0" +#define STRING_graph0 "graph\0" +#define STRING_print0 "print\0" +#define STRING_punct0 "punct\0" +#define STRING_space0 "space\0" +#define STRING_word0 "word\0" +#define STRING_xdigit "xdigit" + +#define STRING_DEFINE "DEFINE" +#define STRING_WEIRD_STARTWORD "[:<:]]" +#define STRING_WEIRD_ENDWORD "[:>:]]" + +#define STRING_CR_RIGHTPAR "CR)" +#define STRING_LF_RIGHTPAR "LF)" +#define STRING_CRLF_RIGHTPAR "CRLF)" +#define STRING_ANY_RIGHTPAR "ANY)" +#define STRING_ANYCRLF_RIGHTPAR "ANYCRLF)" +#define STRING_BSR_ANYCRLF_RIGHTPAR "BSR_ANYCRLF)" +#define STRING_BSR_UNICODE_RIGHTPAR "BSR_UNICODE)" +#define STRING_UTF8_RIGHTPAR "UTF8)" +#define STRING_UTF16_RIGHTPAR "UTF16)" +#define STRING_UTF32_RIGHTPAR "UTF32)" +#define STRING_UTF_RIGHTPAR "UTF)" +#define STRING_UCP_RIGHTPAR "UCP)" +#define STRING_NO_AUTO_POSSESS_RIGHTPAR "NO_AUTO_POSSESS)" +#define STRING_NO_START_OPT_RIGHTPAR "NO_START_OPT)" +#define STRING_LIMIT_MATCH_EQ "LIMIT_MATCH=" +#define STRING_LIMIT_RECURSION_EQ "LIMIT_RECURSION=" + +#else /* SUPPORT_UTF */ + +/* UTF-8 support is enabled; always use UTF-8 (=ASCII) character codes. This +works in both modes non-EBCDIC platforms, and on EBCDIC platforms in UTF-8 mode +only. */ + +#define CHAR_HT '\011' +#define CHAR_VT '\013' +#define CHAR_FF '\014' +#define CHAR_CR '\015' +#define CHAR_LF '\012' +#define CHAR_NL CHAR_LF +#define CHAR_NEL ((unsigned char)'\x85') +#define CHAR_BS '\010' +#define CHAR_BEL '\007' +#define CHAR_ESC '\033' +#define CHAR_DEL '\177' + +#define CHAR_NULL '\0' +#define CHAR_SPACE '\040' +#define CHAR_EXCLAMATION_MARK '\041' +#define CHAR_QUOTATION_MARK '\042' +#define CHAR_NUMBER_SIGN '\043' +#define CHAR_DOLLAR_SIGN '\044' +#define CHAR_PERCENT_SIGN '\045' +#define CHAR_AMPERSAND '\046' +#define CHAR_APOSTROPHE '\047' +#define CHAR_LEFT_PARENTHESIS '\050' +#define CHAR_RIGHT_PARENTHESIS '\051' +#define CHAR_ASTERISK '\052' +#define CHAR_PLUS '\053' +#define CHAR_COMMA '\054' +#define CHAR_MINUS '\055' +#define CHAR_DOT '\056' +#define CHAR_SLASH '\057' +#define CHAR_0 '\060' +#define CHAR_1 '\061' +#define CHAR_2 '\062' +#define CHAR_3 '\063' +#define CHAR_4 '\064' +#define CHAR_5 '\065' +#define CHAR_6 '\066' +#define CHAR_7 '\067' +#define CHAR_8 '\070' +#define CHAR_9 '\071' +#define CHAR_COLON '\072' +#define CHAR_SEMICOLON '\073' +#define CHAR_LESS_THAN_SIGN '\074' +#define CHAR_EQUALS_SIGN '\075' +#define CHAR_GREATER_THAN_SIGN '\076' +#define CHAR_QUESTION_MARK '\077' +#define CHAR_COMMERCIAL_AT '\100' +#define CHAR_A '\101' +#define CHAR_B '\102' +#define CHAR_C '\103' +#define CHAR_D '\104' +#define CHAR_E '\105' +#define CHAR_F '\106' +#define CHAR_G '\107' +#define CHAR_H '\110' +#define CHAR_I '\111' +#define CHAR_J '\112' +#define CHAR_K '\113' +#define CHAR_L '\114' +#define CHAR_M '\115' +#define CHAR_N '\116' +#define CHAR_O '\117' +#define CHAR_P '\120' +#define CHAR_Q '\121' +#define CHAR_R '\122' +#define CHAR_S '\123' +#define CHAR_T '\124' +#define CHAR_U '\125' +#define CHAR_V '\126' +#define CHAR_W '\127' +#define CHAR_X '\130' +#define CHAR_Y '\131' +#define CHAR_Z '\132' +#define CHAR_LEFT_SQUARE_BRACKET '\133' +#define CHAR_BACKSLASH '\134' +#define CHAR_RIGHT_SQUARE_BRACKET '\135' +#define CHAR_CIRCUMFLEX_ACCENT '\136' +#define CHAR_UNDERSCORE '\137' +#define CHAR_GRAVE_ACCENT '\140' +#define CHAR_a '\141' +#define CHAR_b '\142' +#define CHAR_c '\143' +#define CHAR_d '\144' +#define CHAR_e '\145' +#define CHAR_f '\146' +#define CHAR_g '\147' +#define CHAR_h '\150' +#define CHAR_i '\151' +#define CHAR_j '\152' +#define CHAR_k '\153' +#define CHAR_l '\154' +#define CHAR_m '\155' +#define CHAR_n '\156' +#define CHAR_o '\157' +#define CHAR_p '\160' +#define CHAR_q '\161' +#define CHAR_r '\162' +#define CHAR_s '\163' +#define CHAR_t '\164' +#define CHAR_u '\165' +#define CHAR_v '\166' +#define CHAR_w '\167' +#define CHAR_x '\170' +#define CHAR_y '\171' +#define CHAR_z '\172' +#define CHAR_LEFT_CURLY_BRACKET '\173' +#define CHAR_VERTICAL_LINE '\174' +#define CHAR_RIGHT_CURLY_BRACKET '\175' +#define CHAR_TILDE '\176' + +#define STR_HT "\011" +#define STR_VT "\013" +#define STR_FF "\014" +#define STR_CR "\015" +#define STR_NL "\012" +#define STR_BS "\010" +#define STR_BEL "\007" +#define STR_ESC "\033" +#define STR_DEL "\177" + +#define STR_SPACE "\040" +#define STR_EXCLAMATION_MARK "\041" +#define STR_QUOTATION_MARK "\042" +#define STR_NUMBER_SIGN "\043" +#define STR_DOLLAR_SIGN "\044" +#define STR_PERCENT_SIGN "\045" +#define STR_AMPERSAND "\046" +#define STR_APOSTROPHE "\047" +#define STR_LEFT_PARENTHESIS "\050" +#define STR_RIGHT_PARENTHESIS "\051" +#define STR_ASTERISK "\052" +#define STR_PLUS "\053" +#define STR_COMMA "\054" +#define STR_MINUS "\055" +#define STR_DOT "\056" +#define STR_SLASH "\057" +#define STR_0 "\060" +#define STR_1 "\061" +#define STR_2 "\062" +#define STR_3 "\063" +#define STR_4 "\064" +#define STR_5 "\065" +#define STR_6 "\066" +#define STR_7 "\067" +#define STR_8 "\070" +#define STR_9 "\071" +#define STR_COLON "\072" +#define STR_SEMICOLON "\073" +#define STR_LESS_THAN_SIGN "\074" +#define STR_EQUALS_SIGN "\075" +#define STR_GREATER_THAN_SIGN "\076" +#define STR_QUESTION_MARK "\077" +#define STR_COMMERCIAL_AT "\100" +#define STR_A "\101" +#define STR_B "\102" +#define STR_C "\103" +#define STR_D "\104" +#define STR_E "\105" +#define STR_F "\106" +#define STR_G "\107" +#define STR_H "\110" +#define STR_I "\111" +#define STR_J "\112" +#define STR_K "\113" +#define STR_L "\114" +#define STR_M "\115" +#define STR_N "\116" +#define STR_O "\117" +#define STR_P "\120" +#define STR_Q "\121" +#define STR_R "\122" +#define STR_S "\123" +#define STR_T "\124" +#define STR_U "\125" +#define STR_V "\126" +#define STR_W "\127" +#define STR_X "\130" +#define STR_Y "\131" +#define STR_Z "\132" +#define STR_LEFT_SQUARE_BRACKET "\133" +#define STR_BACKSLASH "\134" +#define STR_RIGHT_SQUARE_BRACKET "\135" +#define STR_CIRCUMFLEX_ACCENT "\136" +#define STR_UNDERSCORE "\137" +#define STR_GRAVE_ACCENT "\140" +#define STR_a "\141" +#define STR_b "\142" +#define STR_c "\143" +#define STR_d "\144" +#define STR_e "\145" +#define STR_f "\146" +#define STR_g "\147" +#define STR_h "\150" +#define STR_i "\151" +#define STR_j "\152" +#define STR_k "\153" +#define STR_l "\154" +#define STR_m "\155" +#define STR_n "\156" +#define STR_o "\157" +#define STR_p "\160" +#define STR_q "\161" +#define STR_r "\162" +#define STR_s "\163" +#define STR_t "\164" +#define STR_u "\165" +#define STR_v "\166" +#define STR_w "\167" +#define STR_x "\170" +#define STR_y "\171" +#define STR_z "\172" +#define STR_LEFT_CURLY_BRACKET "\173" +#define STR_VERTICAL_LINE "\174" +#define STR_RIGHT_CURLY_BRACKET "\175" +#define STR_TILDE "\176" + +#define STRING_ACCEPT0 STR_A STR_C STR_C STR_E STR_P STR_T "\0" +#define STRING_COMMIT0 STR_C STR_O STR_M STR_M STR_I STR_T "\0" +#define STRING_F0 STR_F "\0" +#define STRING_FAIL0 STR_F STR_A STR_I STR_L "\0" +#define STRING_MARK0 STR_M STR_A STR_R STR_K "\0" +#define STRING_PRUNE0 STR_P STR_R STR_U STR_N STR_E "\0" +#define STRING_SKIP0 STR_S STR_K STR_I STR_P "\0" +#define STRING_THEN STR_T STR_H STR_E STR_N + +#define STRING_alpha0 STR_a STR_l STR_p STR_h STR_a "\0" +#define STRING_lower0 STR_l STR_o STR_w STR_e STR_r "\0" +#define STRING_upper0 STR_u STR_p STR_p STR_e STR_r "\0" +#define STRING_alnum0 STR_a STR_l STR_n STR_u STR_m "\0" +#define STRING_ascii0 STR_a STR_s STR_c STR_i STR_i "\0" +#define STRING_blank0 STR_b STR_l STR_a STR_n STR_k "\0" +#define STRING_cntrl0 STR_c STR_n STR_t STR_r STR_l "\0" +#define STRING_digit0 STR_d STR_i STR_g STR_i STR_t "\0" +#define STRING_graph0 STR_g STR_r STR_a STR_p STR_h "\0" +#define STRING_print0 STR_p STR_r STR_i STR_n STR_t "\0" +#define STRING_punct0 STR_p STR_u STR_n STR_c STR_t "\0" +#define STRING_space0 STR_s STR_p STR_a STR_c STR_e "\0" +#define STRING_word0 STR_w STR_o STR_r STR_d "\0" +#define STRING_xdigit STR_x STR_d STR_i STR_g STR_i STR_t + +#define STRING_DEFINE STR_D STR_E STR_F STR_I STR_N STR_E +#define STRING_WEIRD_STARTWORD STR_LEFT_SQUARE_BRACKET STR_COLON STR_LESS_THAN_SIGN STR_COLON STR_RIGHT_SQUARE_BRACKET STR_RIGHT_SQUARE_BRACKET +#define STRING_WEIRD_ENDWORD STR_LEFT_SQUARE_BRACKET STR_COLON STR_GREATER_THAN_SIGN STR_COLON STR_RIGHT_SQUARE_BRACKET STR_RIGHT_SQUARE_BRACKET + +#define STRING_CR_RIGHTPAR STR_C STR_R STR_RIGHT_PARENTHESIS +#define STRING_LF_RIGHTPAR STR_L STR_F STR_RIGHT_PARENTHESIS +#define STRING_CRLF_RIGHTPAR STR_C STR_R STR_L STR_F STR_RIGHT_PARENTHESIS +#define STRING_ANY_RIGHTPAR STR_A STR_N STR_Y STR_RIGHT_PARENTHESIS +#define STRING_ANYCRLF_RIGHTPAR STR_A STR_N STR_Y STR_C STR_R STR_L STR_F STR_RIGHT_PARENTHESIS +#define STRING_BSR_ANYCRLF_RIGHTPAR STR_B STR_S STR_R STR_UNDERSCORE STR_A STR_N STR_Y STR_C STR_R STR_L STR_F STR_RIGHT_PARENTHESIS +#define STRING_BSR_UNICODE_RIGHTPAR STR_B STR_S STR_R STR_UNDERSCORE STR_U STR_N STR_I STR_C STR_O STR_D STR_E STR_RIGHT_PARENTHESIS +#define STRING_UTF8_RIGHTPAR STR_U STR_T STR_F STR_8 STR_RIGHT_PARENTHESIS +#define STRING_UTF16_RIGHTPAR STR_U STR_T STR_F STR_1 STR_6 STR_RIGHT_PARENTHESIS +#define STRING_UTF32_RIGHTPAR STR_U STR_T STR_F STR_3 STR_2 STR_RIGHT_PARENTHESIS +#define STRING_UTF_RIGHTPAR STR_U STR_T STR_F STR_RIGHT_PARENTHESIS +#define STRING_UCP_RIGHTPAR STR_U STR_C STR_P STR_RIGHT_PARENTHESIS +#define STRING_NO_AUTO_POSSESS_RIGHTPAR STR_N STR_O STR_UNDERSCORE STR_A STR_U STR_T STR_O STR_UNDERSCORE STR_P STR_O STR_S STR_S STR_E STR_S STR_S STR_RIGHT_PARENTHESIS +#define STRING_NO_START_OPT_RIGHTPAR STR_N STR_O STR_UNDERSCORE STR_S STR_T STR_A STR_R STR_T STR_UNDERSCORE STR_O STR_P STR_T STR_RIGHT_PARENTHESIS +#define STRING_LIMIT_MATCH_EQ STR_L STR_I STR_M STR_I STR_T STR_UNDERSCORE STR_M STR_A STR_T STR_C STR_H STR_EQUALS_SIGN +#define STRING_LIMIT_RECURSION_EQ STR_L STR_I STR_M STR_I STR_T STR_UNDERSCORE STR_R STR_E STR_C STR_U STR_R STR_S STR_I STR_O STR_N STR_EQUALS_SIGN + +#endif /* SUPPORT_UTF */ + +/* Escape items that are just an encoding of a particular data value. */ + +#ifndef ESC_e +#define ESC_e CHAR_ESC +#endif + +#ifndef ESC_f +#define ESC_f CHAR_FF +#endif + +#ifndef ESC_n +#define ESC_n CHAR_LF +#endif + +#ifndef ESC_r +#define ESC_r CHAR_CR +#endif + +/* We can't officially use ESC_t because it is a POSIX reserved identifier +(presumably because of all the others like size_t). */ + +#ifndef ESC_tee +#define ESC_tee CHAR_HT +#endif + +/* Codes for different types of Unicode property */ + +#define PT_ANY 0 /* Any property - matches all chars */ +#define PT_LAMP 1 /* L& - the union of Lu, Ll, Lt */ +#define PT_GC 2 /* Specified general characteristic (e.g. L) */ +#define PT_PC 3 /* Specified particular characteristic (e.g. Lu) */ +#define PT_SC 4 /* Script (e.g. Han) */ +#define PT_ALNUM 5 /* Alphanumeric - the union of L and N */ +#define PT_SPACE 6 /* Perl space - Z plus 9,10,12,13 */ +#define PT_PXSPACE 7 /* POSIX space - Z plus 9,10,11,12,13 */ +#define PT_WORD 8 /* Word - L plus N plus underscore */ +#define PT_CLIST 9 /* Pseudo-property: match character list */ +#define PT_UCNC 10 /* Universal Character nameable character */ +#define PT_TABSIZE 11 /* Size of square table for autopossessify tests */ + +/* The following special properties are used only in XCLASS items, when POSIX +classes are specified and PCRE_UCP is set - in other words, for Unicode +handling of these classes. They are not available via the \p or \P escapes like +those in the above list, and so they do not take part in the autopossessifying +table. */ + +#define PT_PXGRAPH 11 /* [:graph:] - characters that mark the paper */ +#define PT_PXPRINT 12 /* [:print:] - [:graph:] plus non-control spaces */ +#define PT_PXPUNCT 13 /* [:punct:] - punctuation characters */ + +/* Flag bits and data types for the extended class (OP_XCLASS) for classes that +contain characters with values greater than 255. */ + +#define XCL_NOT 0x01 /* Flag: this is a negative class */ +#define XCL_MAP 0x02 /* Flag: a 32-byte map is present */ +#define XCL_HASPROP 0x04 /* Flag: property checks are present. */ + +#define XCL_END 0 /* Marks end of individual items */ +#define XCL_SINGLE 1 /* Single item (one multibyte char) follows */ +#define XCL_RANGE 2 /* A range (two multibyte chars) follows */ +#define XCL_PROP 3 /* Unicode property (2-byte property code follows) */ +#define XCL_NOTPROP 4 /* Unicode inverted property (ditto) */ + +/* These are escaped items that aren't just an encoding of a particular data +value such as \n. They must have non-zero values, as check_escape() returns 0 +for a data character. Also, they must appear in the same order as in the +opcode definitions below, up to ESC_z. There's a dummy for OP_ALLANY because it +corresponds to "." in DOTALL mode rather than an escape sequence. It is also +used for [^] in JavaScript compatibility mode, and for \C in non-utf mode. In +non-DOTALL mode, "." behaves like \N. + +The special values ESC_DU, ESC_du, etc. are used instead of ESC_D, ESC_d, etc. +when PCRE_UCP is set and replacement of \d etc by \p sequences is required. +They must be contiguous, and remain in order so that the replacements can be +looked up from a table. + +Negative numbers are used to encode a backreference (\1, \2, \3, etc.) in +check_escape(). There are two tests in the code for an escape +greater than ESC_b and less than ESC_Z to detect the types that may be +repeated. These are the types that consume characters. If any new escapes are +put in between that don't consume a character, that code will have to change. +*/ + +enum { ESC_A = 1, ESC_G, ESC_K, ESC_B, ESC_b, ESC_D, ESC_d, ESC_S, ESC_s, + ESC_W, ESC_w, ESC_N, ESC_dum, ESC_C, ESC_P, ESC_p, ESC_R, ESC_H, + ESC_h, ESC_V, ESC_v, ESC_X, ESC_Z, ESC_z, + ESC_E, ESC_Q, ESC_g, ESC_k, + ESC_DU, ESC_du, ESC_SU, ESC_su, ESC_WU, ESC_wu }; + + +/********************** Opcode definitions ******************/ + +/****** NOTE NOTE NOTE ****** + +Starting from 1 (i.e. after OP_END), the values up to OP_EOD must correspond in +order to the list of escapes immediately above. Furthermore, values up to +OP_DOLLM must not be changed without adjusting the table called autoposstab in +pcre_compile.c + +Whenever this list is updated, the two macro definitions that follow must be +updated to match. The possessification table called "opcode_possessify" in +pcre_compile.c must also be updated, and also the tables called "coptable" +and "poptable" in pcre_dfa_exec.c. + +****** NOTE NOTE NOTE ******/ + + +/* The values between FIRST_AUTOTAB_OP and LAST_AUTOTAB_RIGHT_OP, inclusive, +are used in a table for deciding whether a repeated character type can be +auto-possessified. */ + +#define FIRST_AUTOTAB_OP OP_NOT_DIGIT +#define LAST_AUTOTAB_LEFT_OP OP_EXTUNI +#define LAST_AUTOTAB_RIGHT_OP OP_DOLLM + +enum { + OP_END, /* 0 End of pattern */ + + /* Values corresponding to backslashed metacharacters */ + + OP_SOD, /* 1 Start of data: \A */ + OP_SOM, /* 2 Start of match (subject + offset): \G */ + OP_SET_SOM, /* 3 Set start of match (\K) */ + OP_NOT_WORD_BOUNDARY, /* 4 \B */ + OP_WORD_BOUNDARY, /* 5 \b */ + OP_NOT_DIGIT, /* 6 \D */ + OP_DIGIT, /* 7 \d */ + OP_NOT_WHITESPACE, /* 8 \S */ + OP_WHITESPACE, /* 9 \s */ + OP_NOT_WORDCHAR, /* 10 \W */ + OP_WORDCHAR, /* 11 \w */ + + OP_ANY, /* 12 Match any character except newline (\N) */ + OP_ALLANY, /* 13 Match any character */ + OP_ANYBYTE, /* 14 Match any byte (\C); different to OP_ANY for UTF-8 */ + OP_NOTPROP, /* 15 \P (not Unicode property) */ + OP_PROP, /* 16 \p (Unicode property) */ + OP_ANYNL, /* 17 \R (any newline sequence) */ + OP_NOT_HSPACE, /* 18 \H (not horizontal whitespace) */ + OP_HSPACE, /* 19 \h (horizontal whitespace) */ + OP_NOT_VSPACE, /* 20 \V (not vertical whitespace) */ + OP_VSPACE, /* 21 \v (vertical whitespace) */ + OP_EXTUNI, /* 22 \X (extended Unicode sequence */ + OP_EODN, /* 23 End of data or \n at end of data (\Z) */ + OP_EOD, /* 24 End of data (\z) */ + + /* Line end assertions */ + + OP_DOLL, /* 25 End of line - not multiline */ + OP_DOLLM, /* 26 End of line - multiline */ + OP_CIRC, /* 27 Start of line - not multiline */ + OP_CIRCM, /* 28 Start of line - multiline */ + + /* Single characters; caseful must precede the caseless ones */ + + OP_CHAR, /* 29 Match one character, casefully */ + OP_CHARI, /* 30 Match one character, caselessly */ + OP_NOT, /* 31 Match one character, not the given one, casefully */ + OP_NOTI, /* 32 Match one character, not the given one, caselessly */ + + /* The following sets of 13 opcodes must always be kept in step because + the offset from the first one is used to generate the others. */ + + /* Repeated characters; caseful must precede the caseless ones */ + + OP_STAR, /* 33 The maximizing and minimizing versions of */ + OP_MINSTAR, /* 34 these six opcodes must come in pairs, with */ + OP_PLUS, /* 35 the minimizing one second. */ + OP_MINPLUS, /* 36 */ + OP_QUERY, /* 37 */ + OP_MINQUERY, /* 38 */ + + OP_UPTO, /* 39 From 0 to n matches of one character, caseful*/ + OP_MINUPTO, /* 40 */ + OP_EXACT, /* 41 Exactly n matches */ + + OP_POSSTAR, /* 42 Possessified star, caseful */ + OP_POSPLUS, /* 43 Possessified plus, caseful */ + OP_POSQUERY, /* 44 Posesssified query, caseful */ + OP_POSUPTO, /* 45 Possessified upto, caseful */ + + /* Repeated characters; caseless must follow the caseful ones */ + + OP_STARI, /* 46 */ + OP_MINSTARI, /* 47 */ + OP_PLUSI, /* 48 */ + OP_MINPLUSI, /* 49 */ + OP_QUERYI, /* 50 */ + OP_MINQUERYI, /* 51 */ + + OP_UPTOI, /* 52 From 0 to n matches of one character, caseless */ + OP_MINUPTOI, /* 53 */ + OP_EXACTI, /* 54 */ + + OP_POSSTARI, /* 55 Possessified star, caseless */ + OP_POSPLUSI, /* 56 Possessified plus, caseless */ + OP_POSQUERYI, /* 57 Posesssified query, caseless */ + OP_POSUPTOI, /* 58 Possessified upto, caseless */ + + /* The negated ones must follow the non-negated ones, and match them */ + /* Negated repeated character, caseful; must precede the caseless ones */ + + OP_NOTSTAR, /* 59 The maximizing and minimizing versions of */ + OP_NOTMINSTAR, /* 60 these six opcodes must come in pairs, with */ + OP_NOTPLUS, /* 61 the minimizing one second. They must be in */ + OP_NOTMINPLUS, /* 62 exactly the same order as those above. */ + OP_NOTQUERY, /* 63 */ + OP_NOTMINQUERY, /* 64 */ + + OP_NOTUPTO, /* 65 From 0 to n matches, caseful */ + OP_NOTMINUPTO, /* 66 */ + OP_NOTEXACT, /* 67 Exactly n matches */ + + OP_NOTPOSSTAR, /* 68 Possessified versions, caseful */ + OP_NOTPOSPLUS, /* 69 */ + OP_NOTPOSQUERY, /* 70 */ + OP_NOTPOSUPTO, /* 71 */ + + /* Negated repeated character, caseless; must follow the caseful ones */ + + OP_NOTSTARI, /* 72 */ + OP_NOTMINSTARI, /* 73 */ + OP_NOTPLUSI, /* 74 */ + OP_NOTMINPLUSI, /* 75 */ + OP_NOTQUERYI, /* 76 */ + OP_NOTMINQUERYI, /* 77 */ + + OP_NOTUPTOI, /* 78 From 0 to n matches, caseless */ + OP_NOTMINUPTOI, /* 79 */ + OP_NOTEXACTI, /* 80 Exactly n matches */ + + OP_NOTPOSSTARI, /* 81 Possessified versions, caseless */ + OP_NOTPOSPLUSI, /* 82 */ + OP_NOTPOSQUERYI, /* 83 */ + OP_NOTPOSUPTOI, /* 84 */ + + /* Character types */ + + OP_TYPESTAR, /* 85 The maximizing and minimizing versions of */ + OP_TYPEMINSTAR, /* 86 these six opcodes must come in pairs, with */ + OP_TYPEPLUS, /* 87 the minimizing one second. These codes must */ + OP_TYPEMINPLUS, /* 88 be in exactly the same order as those above. */ + OP_TYPEQUERY, /* 89 */ + OP_TYPEMINQUERY, /* 90 */ + + OP_TYPEUPTO, /* 91 From 0 to n matches */ + OP_TYPEMINUPTO, /* 92 */ + OP_TYPEEXACT, /* 93 Exactly n matches */ + + OP_TYPEPOSSTAR, /* 94 Possessified versions */ + OP_TYPEPOSPLUS, /* 95 */ + OP_TYPEPOSQUERY, /* 96 */ + OP_TYPEPOSUPTO, /* 97 */ + + /* These are used for character classes and back references; only the + first six are the same as the sets above. */ + + OP_CRSTAR, /* 98 The maximizing and minimizing versions of */ + OP_CRMINSTAR, /* 99 all these opcodes must come in pairs, with */ + OP_CRPLUS, /* 100 the minimizing one second. These codes must */ + OP_CRMINPLUS, /* 101 be in exactly the same order as those above. */ + OP_CRQUERY, /* 102 */ + OP_CRMINQUERY, /* 103 */ + + OP_CRRANGE, /* 104 These are different to the three sets above. */ + OP_CRMINRANGE, /* 105 */ + + OP_CRPOSSTAR, /* 106 Possessified versions */ + OP_CRPOSPLUS, /* 107 */ + OP_CRPOSQUERY, /* 108 */ + OP_CRPOSRANGE, /* 109 */ + + /* End of quantifier opcodes */ + + OP_CLASS, /* 110 Match a character class, chars < 256 only */ + OP_NCLASS, /* 111 Same, but the bitmap was created from a negative + class - the difference is relevant only when a + character > 255 is encountered. */ + OP_XCLASS, /* 112 Extended class for handling > 255 chars within the + class. This does both positive and negative. */ + OP_REF, /* 113 Match a back reference, casefully */ + OP_REFI, /* 114 Match a back reference, caselessly */ + OP_DNREF, /* 115 Match a duplicate name backref, casefully */ + OP_DNREFI, /* 116 Match a duplicate name backref, caselessly */ + OP_RECURSE, /* 117 Match a numbered subpattern (possibly recursive) */ + OP_CALLOUT, /* 118 Call out to external function if provided */ + + OP_ALT, /* 119 Start of alternation */ + OP_KET, /* 120 End of group that doesn't have an unbounded repeat */ + OP_KETRMAX, /* 121 These two must remain together and in this */ + OP_KETRMIN, /* 122 order. They are for groups the repeat for ever. */ + OP_KETRPOS, /* 123 Possessive unlimited repeat. */ + + /* The assertions must come before BRA, CBRA, ONCE, and COND, and the four + asserts must remain in order. */ + + OP_REVERSE, /* 124 Move pointer back - used in lookbehind assertions */ + OP_ASSERT, /* 125 Positive lookahead */ + OP_ASSERT_NOT, /* 126 Negative lookahead */ + OP_ASSERTBACK, /* 127 Positive lookbehind */ + OP_ASSERTBACK_NOT, /* 128 Negative lookbehind */ + + /* ONCE, ONCE_NC, BRA, BRAPOS, CBRA, CBRAPOS, and COND must come immediately + after the assertions, with ONCE first, as there's a test for >= ONCE for a + subpattern that isn't an assertion. The POS versions must immediately follow + the non-POS versions in each case. */ + + OP_ONCE, /* 129 Atomic group, contains captures */ + OP_ONCE_NC, /* 130 Atomic group containing no captures */ + OP_BRA, /* 131 Start of non-capturing bracket */ + OP_BRAPOS, /* 132 Ditto, with unlimited, possessive repeat */ + OP_CBRA, /* 133 Start of capturing bracket */ + OP_CBRAPOS, /* 134 Ditto, with unlimited, possessive repeat */ + OP_COND, /* 135 Conditional group */ + + /* These five must follow the previous five, in the same order. There's a + check for >= SBRA to distinguish the two sets. */ + + OP_SBRA, /* 136 Start of non-capturing bracket, check empty */ + OP_SBRAPOS, /* 137 Ditto, with unlimited, possessive repeat */ + OP_SCBRA, /* 138 Start of capturing bracket, check empty */ + OP_SCBRAPOS, /* 139 Ditto, with unlimited, possessive repeat */ + OP_SCOND, /* 140 Conditional group, check empty */ + + /* The next two pairs must (respectively) be kept together. */ + + OP_CREF, /* 141 Used to hold a capture number as condition */ + OP_DNCREF, /* 142 Used to point to duplicate names as a condition */ + OP_RREF, /* 143 Used to hold a recursion number as condition */ + OP_DNRREF, /* 144 Used to point to duplicate names as a condition */ + OP_DEF, /* 145 The DEFINE condition */ + + OP_BRAZERO, /* 146 These two must remain together and in this */ + OP_BRAMINZERO, /* 147 order. */ + OP_BRAPOSZERO, /* 148 */ + + /* These are backtracking control verbs */ + + OP_MARK, /* 149 always has an argument */ + OP_PRUNE, /* 150 */ + OP_PRUNE_ARG, /* 151 same, but with argument */ + OP_SKIP, /* 152 */ + OP_SKIP_ARG, /* 153 same, but with argument */ + OP_THEN, /* 154 */ + OP_THEN_ARG, /* 155 same, but with argument */ + OP_COMMIT, /* 156 */ + + /* These are forced failure and success verbs */ + + OP_FAIL, /* 157 */ + OP_ACCEPT, /* 158 */ + OP_ASSERT_ACCEPT, /* 159 Used inside assertions */ + OP_CLOSE, /* 160 Used before OP_ACCEPT to close open captures */ + + /* This is used to skip a subpattern with a {0} quantifier */ + + OP_SKIPZERO, /* 161 */ + + /* This is not an opcode, but is used to check that tables indexed by opcode + are the correct length, in order to catch updating errors - there have been + some in the past. */ + + OP_TABLE_LENGTH +}; + +/* *** NOTE NOTE NOTE *** Whenever the list above is updated, the two macro +definitions that follow must also be updated to match. There are also tables +called "opcode_possessify" in pcre_compile.c and "coptable" and "poptable" in +pcre_dfa_exec.c that must be updated. */ + + +/* This macro defines textual names for all the opcodes. These are used only +for debugging, and some of them are only partial names. The macro is referenced +only in pcre_printint.c, which fills out the full names in many cases (and in +some cases doesn't actually use these names at all). */ + +#define OP_NAME_LIST \ + "End", "\\A", "\\G", "\\K", "\\B", "\\b", "\\D", "\\d", \ + "\\S", "\\s", "\\W", "\\w", "Any", "AllAny", "Anybyte", \ + "notprop", "prop", "\\R", "\\H", "\\h", "\\V", "\\v", \ + "extuni", "\\Z", "\\z", \ + "$", "$", "^", "^", "char", "chari", "not", "noti", \ + "*", "*?", "+", "+?", "?", "??", \ + "{", "{", "{", \ + "*+","++", "?+", "{", \ + "*", "*?", "+", "+?", "?", "??", \ + "{", "{", "{", \ + "*+","++", "?+", "{", \ + "*", "*?", "+", "+?", "?", "??", \ + "{", "{", "{", \ + "*+","++", "?+", "{", \ + "*", "*?", "+", "+?", "?", "??", \ + "{", "{", "{", \ + "*+","++", "?+", "{", \ + "*", "*?", "+", "+?", "?", "??", "{", "{", "{", \ + "*+","++", "?+", "{", \ + "*", "*?", "+", "+?", "?", "??", "{", "{", \ + "*+","++", "?+", "{", \ + "class", "nclass", "xclass", "Ref", "Refi", "DnRef", "DnRefi", \ + "Recurse", "Callout", \ + "Alt", "Ket", "KetRmax", "KetRmin", "KetRpos", \ + "Reverse", "Assert", "Assert not", "AssertB", "AssertB not", \ + "Once", "Once_NC", \ + "Bra", "BraPos", "CBra", "CBraPos", \ + "Cond", \ + "SBra", "SBraPos", "SCBra", "SCBraPos", \ + "SCond", \ + "Cond ref", "Cond dnref", "Cond rec", "Cond dnrec", "Cond def", \ + "Brazero", "Braminzero", "Braposzero", \ + "*MARK", "*PRUNE", "*PRUNE", "*SKIP", "*SKIP", \ + "*THEN", "*THEN", "*COMMIT", "*FAIL", \ + "*ACCEPT", "*ASSERT_ACCEPT", \ + "Close", "Skip zero" + + +/* This macro defines the length of fixed length operations in the compiled +regex. The lengths are used when searching for specific things, and also in the +debugging printing of a compiled regex. We use a macro so that it can be +defined close to the definitions of the opcodes themselves. + +As things have been extended, some of these are no longer fixed lenths, but are +minima instead. For example, the length of a single-character repeat may vary +in UTF-8 mode. The code that uses this table must know about such things. */ + +#define OP_LENGTHS \ + 1, /* End */ \ + 1, 1, 1, 1, 1, /* \A, \G, \K, \B, \b */ \ + 1, 1, 1, 1, 1, 1, /* \D, \d, \S, \s, \W, \w */ \ + 1, 1, 1, /* Any, AllAny, Anybyte */ \ + 3, 3, /* \P, \p */ \ + 1, 1, 1, 1, 1, /* \R, \H, \h, \V, \v */ \ + 1, /* \X */ \ + 1, 1, 1, 1, 1, 1, /* \Z, \z, $, $M ^, ^M */ \ + 2, /* Char - the minimum length */ \ + 2, /* Chari - the minimum length */ \ + 2, /* not */ \ + 2, /* noti */ \ + /* Positive single-char repeats ** These are */ \ + 2, 2, 2, 2, 2, 2, /* *, *?, +, +?, ?, ?? ** minima in */ \ + 2+IMM2_SIZE, 2+IMM2_SIZE, /* upto, minupto ** mode */ \ + 2+IMM2_SIZE, /* exact */ \ + 2, 2, 2, 2+IMM2_SIZE, /* *+, ++, ?+, upto+ */ \ + 2, 2, 2, 2, 2, 2, /* *I, *?I, +I, +?I, ?I, ??I ** UTF-8 */ \ + 2+IMM2_SIZE, 2+IMM2_SIZE, /* upto I, minupto I */ \ + 2+IMM2_SIZE, /* exact I */ \ + 2, 2, 2, 2+IMM2_SIZE, /* *+I, ++I, ?+I, upto+I */ \ + /* Negative single-char repeats - only for chars < 256 */ \ + 2, 2, 2, 2, 2, 2, /* NOT *, *?, +, +?, ?, ?? */ \ + 2+IMM2_SIZE, 2+IMM2_SIZE, /* NOT upto, minupto */ \ + 2+IMM2_SIZE, /* NOT exact */ \ + 2, 2, 2, 2+IMM2_SIZE, /* Possessive NOT *, +, ?, upto */ \ + 2, 2, 2, 2, 2, 2, /* NOT *I, *?I, +I, +?I, ?I, ??I */ \ + 2+IMM2_SIZE, 2+IMM2_SIZE, /* NOT upto I, minupto I */ \ + 2+IMM2_SIZE, /* NOT exact I */ \ + 2, 2, 2, 2+IMM2_SIZE, /* Possessive NOT *I, +I, ?I, upto I */ \ + /* Positive type repeats */ \ + 2, 2, 2, 2, 2, 2, /* Type *, *?, +, +?, ?, ?? */ \ + 2+IMM2_SIZE, 2+IMM2_SIZE, /* Type upto, minupto */ \ + 2+IMM2_SIZE, /* Type exact */ \ + 2, 2, 2, 2+IMM2_SIZE, /* Possessive *+, ++, ?+, upto+ */ \ + /* Character class & ref repeats */ \ + 1, 1, 1, 1, 1, 1, /* *, *?, +, +?, ?, ?? */ \ + 1+2*IMM2_SIZE, 1+2*IMM2_SIZE, /* CRRANGE, CRMINRANGE */ \ + 1, 1, 1, 1+2*IMM2_SIZE, /* Possessive *+, ++, ?+, CRPOSRANGE */ \ + 1+(32/sizeof(pcre_uchar)), /* CLASS */ \ + 1+(32/sizeof(pcre_uchar)), /* NCLASS */ \ + 0, /* XCLASS - variable length */ \ + 1+IMM2_SIZE, /* REF */ \ + 1+IMM2_SIZE, /* REFI */ \ + 1+2*IMM2_SIZE, /* DNREF */ \ + 1+2*IMM2_SIZE, /* DNREFI */ \ + 1+LINK_SIZE, /* RECURSE */ \ + 2+2*LINK_SIZE, /* CALLOUT */ \ + 1+LINK_SIZE, /* Alt */ \ + 1+LINK_SIZE, /* Ket */ \ + 1+LINK_SIZE, /* KetRmax */ \ + 1+LINK_SIZE, /* KetRmin */ \ + 1+LINK_SIZE, /* KetRpos */ \ + 1+LINK_SIZE, /* Reverse */ \ + 1+LINK_SIZE, /* Assert */ \ + 1+LINK_SIZE, /* Assert not */ \ + 1+LINK_SIZE, /* Assert behind */ \ + 1+LINK_SIZE, /* Assert behind not */ \ + 1+LINK_SIZE, /* ONCE */ \ + 1+LINK_SIZE, /* ONCE_NC */ \ + 1+LINK_SIZE, /* BRA */ \ + 1+LINK_SIZE, /* BRAPOS */ \ + 1+LINK_SIZE+IMM2_SIZE, /* CBRA */ \ + 1+LINK_SIZE+IMM2_SIZE, /* CBRAPOS */ \ + 1+LINK_SIZE, /* COND */ \ + 1+LINK_SIZE, /* SBRA */ \ + 1+LINK_SIZE, /* SBRAPOS */ \ + 1+LINK_SIZE+IMM2_SIZE, /* SCBRA */ \ + 1+LINK_SIZE+IMM2_SIZE, /* SCBRAPOS */ \ + 1+LINK_SIZE, /* SCOND */ \ + 1+IMM2_SIZE, 1+2*IMM2_SIZE, /* CREF, DNCREF */ \ + 1+IMM2_SIZE, 1+2*IMM2_SIZE, /* RREF, DNRREF */ \ + 1, /* DEF */ \ + 1, 1, 1, /* BRAZERO, BRAMINZERO, BRAPOSZERO */ \ + 3, 1, 3, /* MARK, PRUNE, PRUNE_ARG */ \ + 1, 3, /* SKIP, SKIP_ARG */ \ + 1, 3, /* THEN, THEN_ARG */ \ + 1, 1, 1, 1, /* COMMIT, FAIL, ACCEPT, ASSERT_ACCEPT */ \ + 1+IMM2_SIZE, 1 /* CLOSE, SKIPZERO */ + +/* A magic value for OP_RREF to indicate the "any recursion" condition. */ + +#define RREF_ANY 0xffff + +/* Compile time error code numbers. They are given names so that they can more +easily be tracked. When a new number is added, the table called eint in +pcreposix.c must be updated. */ + +enum { ERR0, ERR1, ERR2, ERR3, ERR4, ERR5, ERR6, ERR7, ERR8, ERR9, + ERR10, ERR11, ERR12, ERR13, ERR14, ERR15, ERR16, ERR17, ERR18, ERR19, + ERR20, ERR21, ERR22, ERR23, ERR24, ERR25, ERR26, ERR27, ERR28, ERR29, + ERR30, ERR31, ERR32, ERR33, ERR34, ERR35, ERR36, ERR37, ERR38, ERR39, + ERR40, ERR41, ERR42, ERR43, ERR44, ERR45, ERR46, ERR47, ERR48, ERR49, + ERR50, ERR51, ERR52, ERR53, ERR54, ERR55, ERR56, ERR57, ERR58, ERR59, + ERR60, ERR61, ERR62, ERR63, ERR64, ERR65, ERR66, ERR67, ERR68, ERR69, + ERR70, ERR71, ERR72, ERR73, ERR74, ERR75, ERR76, ERR77, ERR78, ERR79, + ERR80, ERR81, ERR82, ERR83, ERR84, ERR85, ERR86, ERRCOUNT }; + +/* JIT compiling modes. The function list is indexed by them. */ + +enum { JIT_COMPILE, JIT_PARTIAL_SOFT_COMPILE, JIT_PARTIAL_HARD_COMPILE, + JIT_NUMBER_OF_COMPILE_MODES }; + +/* The real format of the start of the pcre block; the index of names and the +code vector run on as long as necessary after the end. We store an explicit +offset to the name table so that if a regex is compiled on one host, saved, and +then run on another where the size of pointers is different, all might still +be well. + +The size of the structure must be a multiple of 8 bytes. For the case of +compiled-on-4 and run-on-8, we include an extra pointer that is always NULL so +that there are an even number of pointers which therefore are a multiple of 8 +bytes. + +It is necessary to fork the struct for the 32 bit library, since it needs to +use pcre_uint32 for first_char and req_char. We can't put an ifdef inside the +typedef because pcretest needs access to the struct of the 8-, 16- and 32-bit +variants. + +*** WARNING *** +When new fields are added to these structures, remember to adjust the code in +pcre_byte_order.c that is concerned with swapping the byte order of the fields +when a compiled regex is reloaded on a host with different endianness. +*** WARNING *** +There is also similar byte-flipping code in pcretest.c, which is used for +testing the byte-flipping features. It must also be kept in step. +*** WARNING *** +*/ + +typedef struct real_pcre8_or_16 { + pcre_uint32 magic_number; + pcre_uint32 size; /* Total that was malloced */ + pcre_uint32 options; /* Public options */ + pcre_uint32 flags; /* Private flags */ + pcre_uint32 limit_match; /* Limit set from regex */ + pcre_uint32 limit_recursion; /* Limit set from regex */ + pcre_uint16 first_char; /* Starting character */ + pcre_uint16 req_char; /* This character must be seen */ + pcre_uint16 max_lookbehind; /* Longest lookbehind (characters) */ + pcre_uint16 top_bracket; /* Highest numbered group */ + pcre_uint16 top_backref; /* Highest numbered back reference */ + pcre_uint16 name_table_offset; /* Offset to name table that follows */ + pcre_uint16 name_entry_size; /* Size of any name items */ + pcre_uint16 name_count; /* Number of name items */ + pcre_uint16 ref_count; /* Reference count */ + pcre_uint16 dummy1; /* To ensure size is a multiple of 8 */ + pcre_uint16 dummy2; /* To ensure size is a multiple of 8 */ + pcre_uint16 dummy3; /* To ensure size is a multiple of 8 */ + const pcre_uint8 *tables; /* Pointer to tables or NULL for std */ + void *nullpad; /* NULL padding */ +} real_pcre8_or_16; + +typedef struct real_pcre8_or_16 real_pcre; +typedef struct real_pcre8_or_16 real_pcre16; + +typedef struct real_pcre32 { + pcre_uint32 magic_number; + pcre_uint32 size; /* Total that was malloced */ + pcre_uint32 options; /* Public options */ + pcre_uint32 flags; /* Private flags */ + pcre_uint32 limit_match; /* Limit set from regex */ + pcre_uint32 limit_recursion; /* Limit set from regex */ + pcre_uint32 first_char; /* Starting character */ + pcre_uint32 req_char; /* This character must be seen */ + pcre_uint16 max_lookbehind; /* Longest lookbehind (characters) */ + pcre_uint16 top_bracket; /* Highest numbered group */ + pcre_uint16 top_backref; /* Highest numbered back reference */ + pcre_uint16 name_table_offset; /* Offset to name table that follows */ + pcre_uint16 name_entry_size; /* Size of any name items */ + pcre_uint16 name_count; /* Number of name items */ + pcre_uint16 ref_count; /* Reference count */ + pcre_uint16 dummy; /* To ensure size is a multiple of 8 */ + const pcre_uint8 *tables; /* Pointer to tables or NULL for std */ + void *nullpad; /* NULL padding */ +} real_pcre32; + +#if defined COMPILE_PCRE8 +#define REAL_PCRE real_pcre +#elif defined COMPILE_PCRE16 +#define REAL_PCRE real_pcre16 +#elif defined COMPILE_PCRE32 +#define REAL_PCRE real_pcre32 +#endif + +/* Assert that the size of REAL_PCRE is divisible by 8 */ +typedef int __assert_real_pcre_size_divisible_8[(sizeof(REAL_PCRE) % 8) == 0 ? 1 : -1]; + +/* Needed in pcretest to access some fields in the real_pcre* structures + * directly. They're unified for 8/16/32 bits since the structs only differ + * after these fields; if that ever changes, need to fork those defines into + * 8/16 and 32 bit versions. */ +#define REAL_PCRE_MAGIC(re) (((REAL_PCRE*)re)->magic_number) +#define REAL_PCRE_SIZE(re) (((REAL_PCRE*)re)->size) +#define REAL_PCRE_OPTIONS(re) (((REAL_PCRE*)re)->options) +#define REAL_PCRE_FLAGS(re) (((REAL_PCRE*)re)->flags) + +/* The format of the block used to store data from pcre_study(). The same +remark (see NOTE above) about extending this structure applies. */ + +typedef struct pcre_study_data { + pcre_uint32 size; /* Total that was malloced */ + pcre_uint32 flags; /* Private flags */ + pcre_uint8 start_bits[32]; /* Starting char bits */ + pcre_uint32 minlength; /* Minimum subject length */ +} pcre_study_data; + +/* Structure for building a chain of open capturing subpatterns during +compiling, so that instructions to close them can be compiled when (*ACCEPT) is +encountered. This is also used to identify subpatterns that contain recursive +back references to themselves, so that they can be made atomic. */ + +typedef struct open_capitem { + struct open_capitem *next; /* Chain link */ + pcre_uint16 number; /* Capture number */ + pcre_uint16 flag; /* Set TRUE if recursive back ref */ +} open_capitem; + +/* Structure for building a list of named groups during the first pass of +compiling. */ + +typedef struct named_group { + const pcre_uchar *name; /* Points to the name in the pattern */ + int length; /* Length of the name */ + pcre_uint32 number; /* Group number */ +} named_group; + +/* Structure for passing "static" information around between the functions +doing the compiling, so that they are thread-safe. */ + +typedef struct compile_data { + const pcre_uint8 *lcc; /* Points to lower casing table */ + const pcre_uint8 *fcc; /* Points to case-flipping table */ + const pcre_uint8 *cbits; /* Points to character type table */ + const pcre_uint8 *ctypes; /* Points to table of type maps */ + const pcre_uchar *start_workspace;/* The start of working space */ + const pcre_uchar *start_code; /* The start of the compiled code */ + const pcre_uchar *start_pattern; /* The start of the pattern */ + const pcre_uchar *end_pattern; /* The end of the pattern */ + pcre_uchar *hwm; /* High watermark of workspace */ + open_capitem *open_caps; /* Chain of open capture items */ + named_group *named_groups; /* Points to vector in pre-compile */ + pcre_uchar *name_table; /* The name/number table */ + int names_found; /* Number of entries so far */ + int name_entry_size; /* Size of each entry */ + int named_group_list_size; /* Number of entries in the list */ + int workspace_size; /* Size of workspace */ + unsigned int bracount; /* Count of capturing parens as we compile */ + int final_bracount; /* Saved value after first pass */ + int max_lookbehind; /* Maximum lookbehind (characters) */ + int top_backref; /* Maximum back reference */ + unsigned int backref_map; /* Bitmap of low back refs */ + unsigned int namedrefcount; /* Number of backreferences by name */ + int parens_depth; /* Depth of nested parentheses */ + int assert_depth; /* Depth of nested assertions */ + pcre_uint32 external_options; /* External (initial) options */ + pcre_uint32 external_flags; /* External flag bits to be set */ + int req_varyopt; /* "After variable item" flag for reqbyte */ + BOOL had_accept; /* (*ACCEPT) encountered */ + BOOL had_pruneorskip; /* (*PRUNE) or (*SKIP) encountered */ + BOOL check_lookbehind; /* Lookbehinds need later checking */ + BOOL dupnames; /* Duplicate names exist */ + int nltype; /* Newline type */ + int nllen; /* Newline string length */ + pcre_uchar nl[4]; /* Newline string when fixed length */ +} compile_data; + +/* Structure for maintaining a chain of pointers to the currently incomplete +branches, for testing for left recursion while compiling. */ + +typedef struct branch_chain { + struct branch_chain *outer; + pcre_uchar *current_branch; +} branch_chain; + +/* Structure for items in a linked list that represents an explicit recursive +call within the pattern; used by pcre_exec(). */ + +typedef struct recursion_info { + struct recursion_info *prevrec; /* Previous recursion record (or NULL) */ + unsigned int group_num; /* Number of group that was called */ + int *offset_save; /* Pointer to start of saved offsets */ + int saved_max; /* Number of saved offsets */ + int saved_capture_last; /* Last capture number */ + PCRE_PUCHAR subject_position; /* Position at start of recursion */ +} recursion_info; + +/* A similar structure for pcre_dfa_exec(). */ + +typedef struct dfa_recursion_info { + struct dfa_recursion_info *prevrec; + int group_num; + PCRE_PUCHAR subject_position; +} dfa_recursion_info; + +/* Structure for building a chain of data for holding the values of the subject +pointer at the start of each subpattern, so as to detect when an empty string +has been matched by a subpattern - to break infinite loops; used by +pcre_exec(). */ + +typedef struct eptrblock { + struct eptrblock *epb_prev; + PCRE_PUCHAR epb_saved_eptr; +} eptrblock; + + +/* Structure for passing "static" information around between the functions +doing traditional NFA matching, so that they are thread-safe. */ + +typedef struct match_data { + unsigned long int match_call_count; /* As it says */ + unsigned long int match_limit; /* As it says */ + unsigned long int match_limit_recursion; /* As it says */ + int *offset_vector; /* Offset vector */ + int offset_end; /* One past the end */ + int offset_max; /* The maximum usable for return data */ + int nltype; /* Newline type */ + int nllen; /* Newline string length */ + int name_count; /* Number of names in name table */ + int name_entry_size; /* Size of entry in names table */ + unsigned int skip_arg_count; /* For counting SKIP_ARGs */ + unsigned int ignore_skip_arg; /* For re-run when SKIP arg name not found */ + pcre_uchar *name_table; /* Table of names */ + pcre_uchar nl[4]; /* Newline string when fixed */ + const pcre_uint8 *lcc; /* Points to lower casing table */ + const pcre_uint8 *fcc; /* Points to case-flipping table */ + const pcre_uint8 *ctypes; /* Points to table of type maps */ + BOOL notbol; /* NOTBOL flag */ + BOOL noteol; /* NOTEOL flag */ + BOOL utf; /* UTF-8 / UTF-16 flag */ + BOOL jscript_compat; /* JAVASCRIPT_COMPAT flag */ + BOOL use_ucp; /* PCRE_UCP flag */ + BOOL endonly; /* Dollar not before final \n */ + BOOL notempty; /* Empty string match not wanted */ + BOOL notempty_atstart; /* Empty string match at start not wanted */ + BOOL hitend; /* Hit the end of the subject at some point */ + BOOL bsr_anycrlf; /* \R is just any CRLF, not full Unicode */ + BOOL hasthen; /* Pattern contains (*THEN) */ + const pcre_uchar *start_code; /* For use when recursing */ + PCRE_PUCHAR start_subject; /* Start of the subject string */ + PCRE_PUCHAR end_subject; /* End of the subject string */ + PCRE_PUCHAR start_match_ptr; /* Start of matched string */ + PCRE_PUCHAR end_match_ptr; /* Subject position at end match */ + PCRE_PUCHAR start_used_ptr; /* Earliest consulted character */ + int partial; /* PARTIAL options */ + int end_offset_top; /* Highwater mark at end of match */ + pcre_int32 capture_last; /* Most recent capture number + overflow flag */ + int start_offset; /* The start offset value */ + int match_function_type; /* Set for certain special calls of MATCH() */ + eptrblock *eptrchain; /* Chain of eptrblocks for tail recursions */ + int eptrn; /* Next free eptrblock */ + recursion_info *recursive; /* Linked list of recursion data */ + void *callout_data; /* To pass back to callouts */ + const pcre_uchar *mark; /* Mark pointer to pass back on success */ + const pcre_uchar *nomatch_mark;/* Mark pointer to pass back on failure */ + const pcre_uchar *once_target; /* Where to back up to for atomic groups */ +#ifdef NO_RECURSE + void *match_frames_base; /* For remembering malloc'd frames */ +#endif +} match_data; + +/* A similar structure is used for the same purpose by the DFA matching +functions. */ + +typedef struct dfa_match_data { + const pcre_uchar *start_code; /* Start of the compiled pattern */ + const pcre_uchar *start_subject ; /* Start of the subject string */ + const pcre_uchar *end_subject; /* End of subject string */ + const pcre_uchar *start_used_ptr; /* Earliest consulted character */ + const pcre_uint8 *tables; /* Character tables */ + int start_offset; /* The start offset value */ + int moptions; /* Match options */ + int poptions; /* Pattern options */ + int nltype; /* Newline type */ + int nllen; /* Newline string length */ + pcre_uchar nl[4]; /* Newline string when fixed */ + void *callout_data; /* To pass back to callouts */ + dfa_recursion_info *recursive; /* Linked list of recursion data */ +} dfa_match_data; + +/* Bit definitions for entries in the pcre_ctypes table. */ + +#define ctype_space 0x01 +#define ctype_letter 0x02 +#define ctype_digit 0x04 +#define ctype_xdigit 0x08 +#define ctype_word 0x10 /* alphanumeric or '_' */ +#define ctype_meta 0x80 /* regexp meta char or zero (end pattern) */ + +/* Offsets for the bitmap tables in pcre_cbits. Each table contains a set +of bits for a class map. Some classes are built by combining these tables. */ + +#define cbit_space 0 /* [:space:] or \s */ +#define cbit_xdigit 32 /* [:xdigit:] */ +#define cbit_digit 64 /* [:digit:] or \d */ +#define cbit_upper 96 /* [:upper:] */ +#define cbit_lower 128 /* [:lower:] */ +#define cbit_word 160 /* [:word:] or \w */ +#define cbit_graph 192 /* [:graph:] */ +#define cbit_print 224 /* [:print:] */ +#define cbit_punct 256 /* [:punct:] */ +#define cbit_cntrl 288 /* [:cntrl:] */ +#define cbit_length 320 /* Length of the cbits table */ + +/* Offsets of the various tables from the base tables pointer, and +total length. */ + +#define lcc_offset 0 +#define fcc_offset 256 +#define cbits_offset 512 +#define ctypes_offset (cbits_offset + cbit_length) +#define tables_length (ctypes_offset + 256) + +/* Internal function and data prefixes. */ + +#if defined COMPILE_PCRE8 +#ifndef PUBL +#define PUBL(name) pcre_##name +#endif +#ifndef PRIV +#define PRIV(name) _pcre_##name +#endif +#elif defined COMPILE_PCRE16 +#ifndef PUBL +#define PUBL(name) pcre16_##name +#endif +#ifndef PRIV +#define PRIV(name) _pcre16_##name +#endif +#elif defined COMPILE_PCRE32 +#ifndef PUBL +#define PUBL(name) pcre32_##name +#endif +#ifndef PRIV +#define PRIV(name) _pcre32_##name +#endif +#else +#error Unsupported compiling mode +#endif /* COMPILE_PCRE[8|16|32] */ + +/* Layout of the UCP type table that translates property names into types and +codes. Each entry used to point directly to a name, but to reduce the number of +relocations in shared libraries, it now has an offset into a single string +instead. */ + +typedef struct { + pcre_uint16 name_offset; + pcre_uint16 type; + pcre_uint16 value; +} ucp_type_table; + + +/* Internal shared data tables. These are tables that are used by more than one +of the exported public functions. They have to be "external" in the C sense, +but are not part of the PCRE public API. The data for these tables is in the +pcre_tables.c module. */ + +#ifdef COMPILE_PCRE8 +extern const int PRIV(utf8_table1)[]; +extern const int PRIV(utf8_table1_size); +extern const int PRIV(utf8_table2)[]; +extern const int PRIV(utf8_table3)[]; +extern const pcre_uint8 PRIV(utf8_table4)[]; +#endif /* COMPILE_PCRE8 */ + +extern const char PRIV(utt_names)[]; +extern const ucp_type_table PRIV(utt)[]; +extern const int PRIV(utt_size); + +extern const pcre_uint8 PRIV(OP_lengths)[]; +extern const pcre_uint8 PRIV(default_tables)[]; + +extern const pcre_uint32 PRIV(hspace_list)[]; +extern const pcre_uint32 PRIV(vspace_list)[]; + + +/* Internal shared functions. These are functions that are used by more than +one of the exported public functions. They have to be "external" in the C +sense, but are not part of the PCRE public API. */ + +/* String comparison functions. */ +#if defined COMPILE_PCRE8 + +#define STRCMP_UC_UC(str1, str2) \ + strcmp((char *)(str1), (char *)(str2)) +#define STRCMP_UC_C8(str1, str2) \ + strcmp((char *)(str1), (str2)) +#define STRNCMP_UC_UC(str1, str2, num) \ + strncmp((char *)(str1), (char *)(str2), (num)) +#define STRNCMP_UC_C8(str1, str2, num) \ + strncmp((char *)(str1), (str2), (num)) +#define STRLEN_UC(str) strlen((const char *)str) + +#elif defined COMPILE_PCRE16 || defined COMPILE_PCRE32 + +extern int PRIV(strcmp_uc_uc)(const pcre_uchar *, + const pcre_uchar *); +extern int PRIV(strcmp_uc_c8)(const pcre_uchar *, + const char *); +extern int PRIV(strncmp_uc_uc)(const pcre_uchar *, + const pcre_uchar *, unsigned int num); +extern int PRIV(strncmp_uc_c8)(const pcre_uchar *, + const char *, unsigned int num); +extern unsigned int PRIV(strlen_uc)(const pcre_uchar *str); + +#define STRCMP_UC_UC(str1, str2) \ + PRIV(strcmp_uc_uc)((str1), (str2)) +#define STRCMP_UC_C8(str1, str2) \ + PRIV(strcmp_uc_c8)((str1), (str2)) +#define STRNCMP_UC_UC(str1, str2, num) \ + PRIV(strncmp_uc_uc)((str1), (str2), (num)) +#define STRNCMP_UC_C8(str1, str2, num) \ + PRIV(strncmp_uc_c8)((str1), (str2), (num)) +#define STRLEN_UC(str) PRIV(strlen_uc)(str) + +#endif /* COMPILE_PCRE[8|16|32] */ + +#if defined COMPILE_PCRE8 || defined COMPILE_PCRE16 + +#define STRCMP_UC_UC_TEST(str1, str2) STRCMP_UC_UC(str1, str2) +#define STRCMP_UC_C8_TEST(str1, str2) STRCMP_UC_C8(str1, str2) + +#elif defined COMPILE_PCRE32 + +extern int PRIV(strcmp_uc_uc_utf)(const pcre_uchar *, + const pcre_uchar *); +extern int PRIV(strcmp_uc_c8_utf)(const pcre_uchar *, + const char *); + +#define STRCMP_UC_UC_TEST(str1, str2) \ + (utf ? PRIV(strcmp_uc_uc_utf)((str1), (str2)) : PRIV(strcmp_uc_uc)((str1), (str2))) +#define STRCMP_UC_C8_TEST(str1, str2) \ + (utf ? PRIV(strcmp_uc_c8_utf)((str1), (str2)) : PRIV(strcmp_uc_c8)((str1), (str2))) + +#endif /* COMPILE_PCRE[8|16|32] */ + +extern const pcre_uchar *PRIV(find_bracket)(const pcre_uchar *, BOOL, int); +extern BOOL PRIV(is_newline)(PCRE_PUCHAR, int, PCRE_PUCHAR, + int *, BOOL); +extern unsigned int PRIV(ord2utf)(pcre_uint32, pcre_uchar *); +extern int PRIV(valid_utf)(PCRE_PUCHAR, int, int *); +extern BOOL PRIV(was_newline)(PCRE_PUCHAR, int, PCRE_PUCHAR, + int *, BOOL); +extern BOOL PRIV(xclass)(pcre_uint32, const pcre_uchar *, BOOL); + +#ifdef SUPPORT_JIT +extern void PRIV(jit_compile)(const REAL_PCRE *, + PUBL(extra) *, int); +extern int PRIV(jit_exec)(const PUBL(extra) *, + const pcre_uchar *, int, int, int, int *, int); +extern void PRIV(jit_free)(void *); +extern int PRIV(jit_get_size)(void *); +extern const char* PRIV(jit_get_target)(void); +#endif + +/* Unicode character database (UCD) */ + +typedef struct { + pcre_uint8 script; /* ucp_Arabic, etc. */ + pcre_uint8 chartype; /* ucp_Cc, etc. (general categories) */ + pcre_uint8 gbprop; /* ucp_gbControl, etc. (grapheme break property) */ + pcre_uint8 caseset; /* offset to multichar other cases or zero */ + pcre_int32 other_case; /* offset to other case, or zero if none */ +} ucd_record; + +extern const pcre_uint32 PRIV(ucd_caseless_sets)[]; +extern const ucd_record PRIV(ucd_records)[]; +extern const pcre_uint8 PRIV(ucd_stage1)[]; +extern const pcre_uint16 PRIV(ucd_stage2)[]; +extern const pcre_uint32 PRIV(ucp_gentype)[]; +extern const pcre_uint32 PRIV(ucp_gbtable)[]; +#ifdef SUPPORT_JIT +extern const int PRIV(ucp_typerange)[]; +#endif + +#ifdef SUPPORT_UCP +/* UCD access macros */ + +#define UCD_BLOCK_SIZE 128 +#define GET_UCD(ch) (PRIV(ucd_records) + \ + PRIV(ucd_stage2)[PRIV(ucd_stage1)[(int)(ch) / UCD_BLOCK_SIZE] * \ + UCD_BLOCK_SIZE + (int)(ch) % UCD_BLOCK_SIZE]) + +#define UCD_CHARTYPE(ch) GET_UCD(ch)->chartype +#define UCD_SCRIPT(ch) GET_UCD(ch)->script +#define UCD_CATEGORY(ch) PRIV(ucp_gentype)[UCD_CHARTYPE(ch)] +#define UCD_GRAPHBREAK(ch) GET_UCD(ch)->gbprop +#define UCD_CASESET(ch) GET_UCD(ch)->caseset +#define UCD_OTHERCASE(ch) ((pcre_uint32)((int)ch + (int)(GET_UCD(ch)->other_case))) + +#endif /* SUPPORT_UCP */ + +#endif + +/* End of pcre_internal.h */ diff --git a/src/private/pcre_src/pcre_jit_compile.c b/src/private/pcre_src/pcre_jit_compile.c new file mode 100644 index 000000000..256e3a45b --- /dev/null +++ b/src/private/pcre_src/pcre_jit_compile.c @@ -0,0 +1,10704 @@ +/************************************************* +* Perl-Compatible Regular Expressions * +*************************************************/ + +/* PCRE is a library of functions to support regular expressions whose syntax +and semantics are as close as possible to those of the Perl 5 language. + + Written by Philip Hazel + Copyright (c) 1997-2013 University of Cambridge + + The machine code generator part (this module) was written by Zoltan Herczeg + Copyright (c) 2010-2013 + +----------------------------------------------------------------------------- +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * Neither the name of the University of Cambridge nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. +----------------------------------------------------------------------------- +*/ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "pcre_internal.h" + +#if defined SUPPORT_JIT + +/* All-in-one: Since we use the JIT compiler only from here, +we just include it. This way we don't need to touch the build +system files. */ + +#define SLJIT_MALLOC(size) (PUBL(malloc))(size) +#define SLJIT_FREE(ptr) (PUBL(free))(ptr) +#define SLJIT_CONFIG_AUTO 1 +#define SLJIT_CONFIG_STATIC 1 +#define SLJIT_VERBOSE 0 +#define SLJIT_DEBUG 0 + +#include "sljit/sljitLir.c" + +#if defined SLJIT_CONFIG_UNSUPPORTED && SLJIT_CONFIG_UNSUPPORTED +#error Unsupported architecture +#endif + +/* Defines for debugging purposes. */ + +/* 1 - Use unoptimized capturing brackets. + 2 - Enable capture_last_ptr (includes option 1). */ +/* #define DEBUG_FORCE_UNOPTIMIZED_CBRAS 2 */ + +/* 1 - Always have a control head. */ +/* #define DEBUG_FORCE_CONTROL_HEAD 1 */ + +/* Allocate memory for the regex stack on the real machine stack. +Fast, but limited size. */ +#define MACHINE_STACK_SIZE 32768 + +/* Growth rate for stack allocated by the OS. Should be the multiply +of page size. */ +#define STACK_GROWTH_RATE 8192 + +/* Enable to check that the allocation could destroy temporaries. */ +#if defined SLJIT_DEBUG && SLJIT_DEBUG +#define DESTROY_REGISTERS 1 +#endif + +/* +Short summary about the backtracking mechanism empolyed by the jit code generator: + +The code generator follows the recursive nature of the PERL compatible regular +expressions. The basic blocks of regular expressions are condition checkers +whose execute different commands depending on the result of the condition check. +The relationship between the operators can be horizontal (concatenation) and +vertical (sub-expression) (See struct backtrack_common for more details). + + 'ab' - 'a' and 'b' regexps are concatenated + 'a+' - 'a' is the sub-expression of the '+' operator + +The condition checkers are boolean (true/false) checkers. Machine code is generated +for the checker itself and for the actions depending on the result of the checker. +The 'true' case is called as the matching path (expected path), and the other is called as +the 'backtrack' path. Branch instructions are expesive for all CPUs, so we avoid taken +branches on the matching path. + + Greedy star operator (*) : + Matching path: match happens. + Backtrack path: match failed. + Non-greedy star operator (*?) : + Matching path: no need to perform a match. + Backtrack path: match is required. + +The following example shows how the code generated for a capturing bracket +with two alternatives. Let A, B, C, D are arbirary regular expressions, and +we have the following regular expression: + + A(B|C)D + +The generated code will be the following: + + A matching path + '(' matching path (pushing arguments to the stack) + B matching path + ')' matching path (pushing arguments to the stack) + D matching path + return with successful match + + D backtrack path + ')' backtrack path (If we arrived from "C" jump to the backtrack of "C") + B backtrack path + C expected path + jump to D matching path + C backtrack path + A backtrack path + + Notice, that the order of backtrack code paths are the opposite of the fast + code paths. In this way the topmost value on the stack is always belong + to the current backtrack code path. The backtrack path must check + whether there is a next alternative. If so, it needs to jump back to + the matching path eventually. Otherwise it needs to clear out its own stack + frame and continue the execution on the backtrack code paths. +*/ + +/* +Saved stack frames: + +Atomic blocks and asserts require reloading the values of private data +when the backtrack mechanism performed. Because of OP_RECURSE, the data +are not necessarly known in compile time, thus we need a dynamic restore +mechanism. + +The stack frames are stored in a chain list, and have the following format: +([ capturing bracket offset ][ start value ][ end value ])+ ... [ 0 ] [ previous head ] + +Thus we can restore the private data to a particular point in the stack. +*/ + +typedef struct jit_arguments { + /* Pointers first. */ + struct sljit_stack *stack; + const pcre_uchar *str; + const pcre_uchar *begin; + const pcre_uchar *end; + int *offsets; + pcre_uchar *uchar_ptr; + pcre_uchar *mark_ptr; + void *callout_data; + /* Everything else after. */ + pcre_uint32 limit_match; + int real_offset_count; + int offset_count; + pcre_uint8 notbol; + pcre_uint8 noteol; + pcre_uint8 notempty; + pcre_uint8 notempty_atstart; +} jit_arguments; + +typedef struct executable_functions { + void *executable_funcs[JIT_NUMBER_OF_COMPILE_MODES]; + sljit_uw *read_only_data[JIT_NUMBER_OF_COMPILE_MODES]; + sljit_uw executable_sizes[JIT_NUMBER_OF_COMPILE_MODES]; + PUBL(jit_callback) callback; + void *userdata; + pcre_uint32 top_bracket; + pcre_uint32 limit_match; +} executable_functions; + +typedef struct jump_list { + struct sljit_jump *jump; + struct jump_list *next; +} jump_list; + +typedef struct stub_list { + struct sljit_jump *start; + struct sljit_label *quit; + struct stub_list *next; +} stub_list; + +typedef struct label_addr_list { + struct sljit_label *label; + sljit_uw *update_addr; + struct label_addr_list *next; +} label_addr_list; + +enum frame_types { + no_frame = -1, + no_stack = -2 +}; + +enum control_types { + type_mark = 0, + type_then_trap = 1 +}; + +typedef int (SLJIT_CALL *jit_function)(jit_arguments *args); + +/* The following structure is the key data type for the recursive +code generator. It is allocated by compile_matchingpath, and contains +the arguments for compile_backtrackingpath. Must be the first member +of its descendants. */ +typedef struct backtrack_common { + /* Concatenation stack. */ + struct backtrack_common *prev; + jump_list *nextbacktracks; + /* Internal stack (for component operators). */ + struct backtrack_common *top; + jump_list *topbacktracks; + /* Opcode pointer. */ + pcre_uchar *cc; +} backtrack_common; + +typedef struct assert_backtrack { + backtrack_common common; + jump_list *condfailed; + /* Less than 0 if a frame is not needed. */ + int framesize; + /* Points to our private memory word on the stack. */ + int private_data_ptr; + /* For iterators. */ + struct sljit_label *matchingpath; +} assert_backtrack; + +typedef struct bracket_backtrack { + backtrack_common common; + /* Where to coninue if an alternative is successfully matched. */ + struct sljit_label *alternative_matchingpath; + /* For rmin and rmax iterators. */ + struct sljit_label *recursive_matchingpath; + /* For greedy ? operator. */ + struct sljit_label *zero_matchingpath; + /* Contains the branches of a failed condition. */ + union { + /* Both for OP_COND, OP_SCOND. */ + jump_list *condfailed; + assert_backtrack *assert; + /* For OP_ONCE. Less than 0 if not needed. */ + int framesize; + } u; + /* Points to our private memory word on the stack. */ + int private_data_ptr; +} bracket_backtrack; + +typedef struct bracketpos_backtrack { + backtrack_common common; + /* Points to our private memory word on the stack. */ + int private_data_ptr; + /* Reverting stack is needed. */ + int framesize; + /* Allocated stack size. */ + int stacksize; +} bracketpos_backtrack; + +typedef struct braminzero_backtrack { + backtrack_common common; + struct sljit_label *matchingpath; +} braminzero_backtrack; + +typedef struct iterator_backtrack { + backtrack_common common; + /* Next iteration. */ + struct sljit_label *matchingpath; +} iterator_backtrack; + +typedef struct recurse_entry { + struct recurse_entry *next; + /* Contains the function entry. */ + struct sljit_label *entry; + /* Collects the calls until the function is not created. */ + jump_list *calls; + /* Points to the starting opcode. */ + sljit_sw start; +} recurse_entry; + +typedef struct recurse_backtrack { + backtrack_common common; + BOOL inlined_pattern; +} recurse_backtrack; + +#define OP_THEN_TRAP OP_TABLE_LENGTH + +typedef struct then_trap_backtrack { + backtrack_common common; + /* If then_trap is not NULL, this structure contains the real + then_trap for the backtracking path. */ + struct then_trap_backtrack *then_trap; + /* Points to the starting opcode. */ + sljit_sw start; + /* Exit point for the then opcodes of this alternative. */ + jump_list *quit; + /* Frame size of the current alternative. */ + int framesize; +} then_trap_backtrack; + +#define MAX_RANGE_SIZE 4 + +typedef struct compiler_common { + /* The sljit ceneric compiler. */ + struct sljit_compiler *compiler; + /* First byte code. */ + pcre_uchar *start; + /* Maps private data offset to each opcode. */ + sljit_si *private_data_ptrs; + /* This read-only data is available during runtime. */ + sljit_uw *read_only_data; + /* The total size of the read-only data. */ + sljit_uw read_only_data_size; + /* The next free entry of the read_only_data. */ + sljit_uw *read_only_data_ptr; + /* Tells whether the capturing bracket is optimized. */ + pcre_uint8 *optimized_cbracket; + /* Tells whether the starting offset is a target of then. */ + pcre_uint8 *then_offsets; + /* Current position where a THEN must jump. */ + then_trap_backtrack *then_trap; + /* Starting offset of private data for capturing brackets. */ + int cbra_ptr; + /* Output vector starting point. Must be divisible by 2. */ + int ovector_start; + /* Last known position of the requested byte. */ + int req_char_ptr; + /* Head of the last recursion. */ + int recursive_head_ptr; + /* First inspected character for partial matching. */ + int start_used_ptr; + /* Starting pointer for partial soft matches. */ + int hit_start; + /* End pointer of the first line. */ + int first_line_end; + /* Points to the marked string. */ + int mark_ptr; + /* Recursive control verb management chain. */ + int control_head_ptr; + /* Points to the last matched capture block index. */ + int capture_last_ptr; + /* Points to the starting position of the current match. */ + int start_ptr; + + /* Flipped and lower case tables. */ + const pcre_uint8 *fcc; + sljit_sw lcc; + /* Mode can be PCRE_STUDY_JIT_COMPILE and others. */ + int mode; + /* TRUE, when minlength is greater than 0. */ + BOOL might_be_empty; + /* \K is found in the pattern. */ + BOOL has_set_som; + /* (*SKIP:arg) is found in the pattern. */ + BOOL has_skip_arg; + /* (*THEN) is found in the pattern. */ + BOOL has_then; + /* Needs to know the start position anytime. */ + BOOL needs_start_ptr; + /* Currently in recurse or negative assert. */ + BOOL local_exit; + /* Currently in a positive assert. */ + BOOL positive_assert; + /* Newline control. */ + int nltype; + pcre_uint32 nlmax; + pcre_uint32 nlmin; + int newline; + int bsr_nltype; + pcre_uint32 bsr_nlmax; + pcre_uint32 bsr_nlmin; + /* Dollar endonly. */ + int endonly; + /* Tables. */ + sljit_sw ctypes; + /* Named capturing brackets. */ + pcre_uchar *name_table; + sljit_sw name_count; + sljit_sw name_entry_size; + + /* Labels and jump lists. */ + struct sljit_label *partialmatchlabel; + struct sljit_label *quit_label; + struct sljit_label *forced_quit_label; + struct sljit_label *accept_label; + struct sljit_label *ff_newline_shortcut; + stub_list *stubs; + label_addr_list *label_addrs; + recurse_entry *entries; + recurse_entry *currententry; + jump_list *partialmatch; + jump_list *quit; + jump_list *positive_assert_quit; + jump_list *forced_quit; + jump_list *accept; + jump_list *calllimit; + jump_list *stackalloc; + jump_list *revertframes; + jump_list *wordboundary; + jump_list *anynewline; + jump_list *hspace; + jump_list *vspace; + jump_list *casefulcmp; + jump_list *caselesscmp; + jump_list *reset_match; + BOOL jscript_compat; +#ifdef SUPPORT_UTF + BOOL utf; +#ifdef SUPPORT_UCP + BOOL use_ucp; +#endif +#ifdef COMPILE_PCRE8 + jump_list *utfreadchar; + jump_list *utfreadchar16; + jump_list *utfreadtype8; +#endif +#endif /* SUPPORT_UTF */ +#ifdef SUPPORT_UCP + jump_list *getucd; +#endif +} compiler_common; + +/* For byte_sequence_compare. */ + +typedef struct compare_context { + int length; + int sourcereg; +#if defined SLJIT_UNALIGNED && SLJIT_UNALIGNED + int ucharptr; + union { + sljit_si asint; + sljit_uh asushort; +#if defined COMPILE_PCRE8 + sljit_ub asbyte; + sljit_ub asuchars[4]; +#elif defined COMPILE_PCRE16 + sljit_uh asuchars[2]; +#elif defined COMPILE_PCRE32 + sljit_ui asuchars[1]; +#endif + } c; + union { + sljit_si asint; + sljit_uh asushort; +#if defined COMPILE_PCRE8 + sljit_ub asbyte; + sljit_ub asuchars[4]; +#elif defined COMPILE_PCRE16 + sljit_uh asuchars[2]; +#elif defined COMPILE_PCRE32 + sljit_ui asuchars[1]; +#endif + } oc; +#endif +} compare_context; + +/* Undefine sljit macros. */ +#undef CMP + +/* Used for accessing the elements of the stack. */ +#define STACK(i) ((-(i) - 1) * (int)sizeof(sljit_sw)) + +#define TMP1 SLJIT_R0 +#define TMP2 SLJIT_R2 +#define TMP3 SLJIT_R3 +#define STR_PTR SLJIT_S0 +#define STR_END SLJIT_S1 +#define STACK_TOP SLJIT_R1 +#define STACK_LIMIT SLJIT_S2 +#define COUNT_MATCH SLJIT_S3 +#define ARGUMENTS SLJIT_S4 +#define RETURN_ADDR SLJIT_R4 + +/* Local space layout. */ +/* These two locals can be used by the current opcode. */ +#define LOCALS0 (0 * sizeof(sljit_sw)) +#define LOCALS1 (1 * sizeof(sljit_sw)) +/* Two local variables for possessive quantifiers (char1 cannot use them). */ +#define POSSESSIVE0 (2 * sizeof(sljit_sw)) +#define POSSESSIVE1 (3 * sizeof(sljit_sw)) +/* Max limit of recursions. */ +#define LIMIT_MATCH (4 * sizeof(sljit_sw)) +/* The output vector is stored on the stack, and contains pointers +to characters. The vector data is divided into two groups: the first +group contains the start / end character pointers, and the second is +the start pointers when the end of the capturing group has not yet reached. */ +#define OVECTOR_START (common->ovector_start) +#define OVECTOR(i) (OVECTOR_START + (i) * (sljit_sw)sizeof(sljit_sw)) +#define OVECTOR_PRIV(i) (common->cbra_ptr + (i) * (sljit_sw)sizeof(sljit_sw)) +#define PRIVATE_DATA(cc) (common->private_data_ptrs[(cc) - common->start]) + +#if defined COMPILE_PCRE8 +#define MOV_UCHAR SLJIT_MOV_UB +#define MOVU_UCHAR SLJIT_MOVU_UB +#elif defined COMPILE_PCRE16 +#define MOV_UCHAR SLJIT_MOV_UH +#define MOVU_UCHAR SLJIT_MOVU_UH +#elif defined COMPILE_PCRE32 +#define MOV_UCHAR SLJIT_MOV_UI +#define MOVU_UCHAR SLJIT_MOVU_UI +#else +#error Unsupported compiling mode +#endif + +/* Shortcuts. */ +#define DEFINE_COMPILER \ + struct sljit_compiler *compiler = common->compiler +#define OP1(op, dst, dstw, src, srcw) \ + sljit_emit_op1(compiler, (op), (dst), (dstw), (src), (srcw)) +#define OP2(op, dst, dstw, src1, src1w, src2, src2w) \ + sljit_emit_op2(compiler, (op), (dst), (dstw), (src1), (src1w), (src2), (src2w)) +#define LABEL() \ + sljit_emit_label(compiler) +#define JUMP(type) \ + sljit_emit_jump(compiler, (type)) +#define JUMPTO(type, label) \ + sljit_set_label(sljit_emit_jump(compiler, (type)), (label)) +#define JUMPHERE(jump) \ + sljit_set_label((jump), sljit_emit_label(compiler)) +#define SET_LABEL(jump, label) \ + sljit_set_label((jump), (label)) +#define CMP(type, src1, src1w, src2, src2w) \ + sljit_emit_cmp(compiler, (type), (src1), (src1w), (src2), (src2w)) +#define CMPTO(type, src1, src1w, src2, src2w, label) \ + sljit_set_label(sljit_emit_cmp(compiler, (type), (src1), (src1w), (src2), (src2w)), (label)) +#define OP_FLAGS(op, dst, dstw, src, srcw, type) \ + sljit_emit_op_flags(compiler, (op), (dst), (dstw), (src), (srcw), (type)) +#define GET_LOCAL_BASE(dst, dstw, offset) \ + sljit_get_local_base(compiler, (dst), (dstw), (offset)) + +#define READ_CHAR_MAX 0x7fffffff + +static pcre_uchar* bracketend(pcre_uchar* cc) +{ +SLJIT_ASSERT((*cc >= OP_ASSERT && *cc <= OP_ASSERTBACK_NOT) || (*cc >= OP_ONCE && *cc <= OP_SCOND)); +do cc += GET(cc, 1); while (*cc == OP_ALT); +SLJIT_ASSERT(*cc >= OP_KET && *cc <= OP_KETRPOS); +cc += 1 + LINK_SIZE; +return cc; +} + +static int no_alternatives(pcre_uchar* cc) +{ +int count = 0; +SLJIT_ASSERT((*cc >= OP_ASSERT && *cc <= OP_ASSERTBACK_NOT) || (*cc >= OP_ONCE && *cc <= OP_SCOND)); +do + { + cc += GET(cc, 1); + count++; + } +while (*cc == OP_ALT); +SLJIT_ASSERT(*cc >= OP_KET && *cc <= OP_KETRPOS); +return count; +} + +static int ones_in_half_byte[16] = { + /* 0 */ 0, 1, 1, 2, /* 4 */ 1, 2, 2, 3, + /* 8 */ 1, 2, 2, 3, /* 12 */ 2, 3, 3, 4 +}; + +/* Functions whose might need modification for all new supported opcodes: + next_opcode + check_opcode_types + set_private_data_ptrs + get_framesize + init_frame + get_private_data_copy_length + copy_private_data + compile_matchingpath + compile_backtrackingpath +*/ + +static pcre_uchar *next_opcode(compiler_common *common, pcre_uchar *cc) +{ +SLJIT_UNUSED_ARG(common); +switch(*cc) + { + case OP_SOD: + case OP_SOM: + case OP_SET_SOM: + case OP_NOT_WORD_BOUNDARY: + case OP_WORD_BOUNDARY: + case OP_NOT_DIGIT: + case OP_DIGIT: + case OP_NOT_WHITESPACE: + case OP_WHITESPACE: + case OP_NOT_WORDCHAR: + case OP_WORDCHAR: + case OP_ANY: + case OP_ALLANY: + case OP_NOTPROP: + case OP_PROP: + case OP_ANYNL: + case OP_NOT_HSPACE: + case OP_HSPACE: + case OP_NOT_VSPACE: + case OP_VSPACE: + case OP_EXTUNI: + case OP_EODN: + case OP_EOD: + case OP_CIRC: + case OP_CIRCM: + case OP_DOLL: + case OP_DOLLM: + case OP_CRSTAR: + case OP_CRMINSTAR: + case OP_CRPLUS: + case OP_CRMINPLUS: + case OP_CRQUERY: + case OP_CRMINQUERY: + case OP_CRRANGE: + case OP_CRMINRANGE: + case OP_CRPOSSTAR: + case OP_CRPOSPLUS: + case OP_CRPOSQUERY: + case OP_CRPOSRANGE: + case OP_CLASS: + case OP_NCLASS: + case OP_REF: + case OP_REFI: + case OP_DNREF: + case OP_DNREFI: + case OP_RECURSE: + case OP_CALLOUT: + case OP_ALT: + case OP_KET: + case OP_KETRMAX: + case OP_KETRMIN: + case OP_KETRPOS: + case OP_REVERSE: + case OP_ASSERT: + case OP_ASSERT_NOT: + case OP_ASSERTBACK: + case OP_ASSERTBACK_NOT: + case OP_ONCE: + case OP_ONCE_NC: + case OP_BRA: + case OP_BRAPOS: + case OP_CBRA: + case OP_CBRAPOS: + case OP_COND: + case OP_SBRA: + case OP_SBRAPOS: + case OP_SCBRA: + case OP_SCBRAPOS: + case OP_SCOND: + case OP_CREF: + case OP_DNCREF: + case OP_RREF: + case OP_DNRREF: + case OP_DEF: + case OP_BRAZERO: + case OP_BRAMINZERO: + case OP_BRAPOSZERO: + case OP_PRUNE: + case OP_SKIP: + case OP_THEN: + case OP_COMMIT: + case OP_FAIL: + case OP_ACCEPT: + case OP_ASSERT_ACCEPT: + case OP_CLOSE: + case OP_SKIPZERO: + return cc + PRIV(OP_lengths)[*cc]; + + case OP_CHAR: + case OP_CHARI: + case OP_NOT: + case OP_NOTI: + case OP_STAR: + case OP_MINSTAR: + case OP_PLUS: + case OP_MINPLUS: + case OP_QUERY: + case OP_MINQUERY: + case OP_UPTO: + case OP_MINUPTO: + case OP_EXACT: + case OP_POSSTAR: + case OP_POSPLUS: + case OP_POSQUERY: + case OP_POSUPTO: + case OP_STARI: + case OP_MINSTARI: + case OP_PLUSI: + case OP_MINPLUSI: + case OP_QUERYI: + case OP_MINQUERYI: + case OP_UPTOI: + case OP_MINUPTOI: + case OP_EXACTI: + case OP_POSSTARI: + case OP_POSPLUSI: + case OP_POSQUERYI: + case OP_POSUPTOI: + case OP_NOTSTAR: + case OP_NOTMINSTAR: + case OP_NOTPLUS: + case OP_NOTMINPLUS: + case OP_NOTQUERY: + case OP_NOTMINQUERY: + case OP_NOTUPTO: + case OP_NOTMINUPTO: + case OP_NOTEXACT: + case OP_NOTPOSSTAR: + case OP_NOTPOSPLUS: + case OP_NOTPOSQUERY: + case OP_NOTPOSUPTO: + case OP_NOTSTARI: + case OP_NOTMINSTARI: + case OP_NOTPLUSI: + case OP_NOTMINPLUSI: + case OP_NOTQUERYI: + case OP_NOTMINQUERYI: + case OP_NOTUPTOI: + case OP_NOTMINUPTOI: + case OP_NOTEXACTI: + case OP_NOTPOSSTARI: + case OP_NOTPOSPLUSI: + case OP_NOTPOSQUERYI: + case OP_NOTPOSUPTOI: + cc += PRIV(OP_lengths)[*cc]; +#ifdef SUPPORT_UTF + if (common->utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]); +#endif + return cc; + + /* Special cases. */ + case OP_TYPESTAR: + case OP_TYPEMINSTAR: + case OP_TYPEPLUS: + case OP_TYPEMINPLUS: + case OP_TYPEQUERY: + case OP_TYPEMINQUERY: + case OP_TYPEUPTO: + case OP_TYPEMINUPTO: + case OP_TYPEEXACT: + case OP_TYPEPOSSTAR: + case OP_TYPEPOSPLUS: + case OP_TYPEPOSQUERY: + case OP_TYPEPOSUPTO: + return cc + PRIV(OP_lengths)[*cc] - 1; + + case OP_ANYBYTE: +#ifdef SUPPORT_UTF + if (common->utf) return NULL; +#endif + return cc + 1; + +#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 + case OP_XCLASS: + return cc + GET(cc, 1); +#endif + + case OP_MARK: + case OP_PRUNE_ARG: + case OP_SKIP_ARG: + case OP_THEN_ARG: + return cc + 1 + 2 + cc[1]; + + default: + /* All opcodes are supported now! */ + SLJIT_ASSERT_STOP(); + return NULL; + } +} + +static BOOL check_opcode_types(compiler_common *common, pcre_uchar *cc, pcre_uchar *ccend) +{ +int count; +pcre_uchar *slot; + +/* Calculate important variables (like stack size) and checks whether all opcodes are supported. */ +while (cc < ccend) + { + switch(*cc) + { + case OP_SET_SOM: + common->has_set_som = TRUE; + common->might_be_empty = TRUE; + cc += 1; + break; + + case OP_REF: + case OP_REFI: + common->optimized_cbracket[GET2(cc, 1)] = 0; + cc += 1 + IMM2_SIZE; + break; + + case OP_BRA: + case OP_CBRA: + case OP_SBRA: + case OP_SCBRA: + count = no_alternatives(cc); + if (count > 4) + common->read_only_data_size += count * sizeof(sljit_uw); + cc += 1 + LINK_SIZE + (*cc == OP_CBRA || *cc == OP_SCBRA ? IMM2_SIZE : 0); + break; + + case OP_CBRAPOS: + case OP_SCBRAPOS: + common->optimized_cbracket[GET2(cc, 1 + LINK_SIZE)] = 0; + cc += 1 + LINK_SIZE + IMM2_SIZE; + break; + + case OP_COND: + case OP_SCOND: + /* Only AUTO_CALLOUT can insert this opcode. We do + not intend to support this case. */ + if (cc[1 + LINK_SIZE] == OP_CALLOUT) + return FALSE; + cc += 1 + LINK_SIZE; + break; + + case OP_CREF: + common->optimized_cbracket[GET2(cc, 1)] = 0; + cc += 1 + IMM2_SIZE; + break; + + case OP_DNREF: + case OP_DNREFI: + case OP_DNCREF: + count = GET2(cc, 1 + IMM2_SIZE); + slot = common->name_table + GET2(cc, 1) * common->name_entry_size; + while (count-- > 0) + { + common->optimized_cbracket[GET2(slot, 0)] = 0; + slot += common->name_entry_size; + } + cc += 1 + 2 * IMM2_SIZE; + break; + + case OP_RECURSE: + /* Set its value only once. */ + if (common->recursive_head_ptr == 0) + { + common->recursive_head_ptr = common->ovector_start; + common->ovector_start += sizeof(sljit_sw); + } + cc += 1 + LINK_SIZE; + break; + + case OP_CALLOUT: + if (common->capture_last_ptr == 0) + { + common->capture_last_ptr = common->ovector_start; + common->ovector_start += sizeof(sljit_sw); + } + cc += 2 + 2 * LINK_SIZE; + break; + + case OP_THEN_ARG: + common->has_then = TRUE; + common->control_head_ptr = 1; + /* Fall through. */ + + case OP_PRUNE_ARG: + common->needs_start_ptr = TRUE; + /* Fall through. */ + + case OP_MARK: + if (common->mark_ptr == 0) + { + common->mark_ptr = common->ovector_start; + common->ovector_start += sizeof(sljit_sw); + } + cc += 1 + 2 + cc[1]; + break; + + case OP_THEN: + common->has_then = TRUE; + common->control_head_ptr = 1; + /* Fall through. */ + + case OP_PRUNE: + case OP_SKIP: + common->needs_start_ptr = TRUE; + cc += 1; + break; + + case OP_SKIP_ARG: + common->control_head_ptr = 1; + common->has_skip_arg = TRUE; + cc += 1 + 2 + cc[1]; + break; + + default: + cc = next_opcode(common, cc); + if (cc == NULL) + return FALSE; + break; + } + } +return TRUE; +} + +static int get_class_iterator_size(pcre_uchar *cc) +{ +switch(*cc) + { + case OP_CRSTAR: + case OP_CRPLUS: + return 2; + + case OP_CRMINSTAR: + case OP_CRMINPLUS: + case OP_CRQUERY: + case OP_CRMINQUERY: + return 1; + + case OP_CRRANGE: + case OP_CRMINRANGE: + if (GET2(cc, 1) == GET2(cc, 1 + IMM2_SIZE)) + return 0; + return 2; + + default: + return 0; + } +} + +static BOOL detect_repeat(compiler_common *common, pcre_uchar *begin) +{ +pcre_uchar *end = bracketend(begin); +pcre_uchar *next; +pcre_uchar *next_end; +pcre_uchar *max_end; +pcre_uchar type; +sljit_sw length = end - begin; +int min, max, i; + +/* Detect fixed iterations first. */ +if (end[-(1 + LINK_SIZE)] != OP_KET) + return FALSE; + +/* Already detected repeat. */ +if (common->private_data_ptrs[end - common->start - LINK_SIZE] != 0) + return TRUE; + +next = end; +min = 1; +while (1) + { + if (*next != *begin) + break; + next_end = bracketend(next); + if (next_end - next != length || memcmp(begin, next, IN_UCHARS(length)) != 0) + break; + next = next_end; + min++; + } + +if (min == 2) + return FALSE; + +max = 0; +max_end = next; +if (*next == OP_BRAZERO || *next == OP_BRAMINZERO) + { + type = *next; + while (1) + { + if (next[0] != type || next[1] != OP_BRA || next[2 + LINK_SIZE] != *begin) + break; + next_end = bracketend(next + 2 + LINK_SIZE); + if (next_end - next != (length + 2 + LINK_SIZE) || memcmp(begin, next + 2 + LINK_SIZE, IN_UCHARS(length)) != 0) + break; + next = next_end; + max++; + } + + if (next[0] == type && next[1] == *begin && max >= 1) + { + next_end = bracketend(next + 1); + if (next_end - next == (length + 1) && memcmp(begin, next + 1, IN_UCHARS(length)) == 0) + { + for (i = 0; i < max; i++, next_end += 1 + LINK_SIZE) + if (*next_end != OP_KET) + break; + + if (i == max) + { + common->private_data_ptrs[max_end - common->start - LINK_SIZE] = next_end - max_end; + common->private_data_ptrs[max_end - common->start - LINK_SIZE + 1] = (type == OP_BRAZERO) ? OP_UPTO : OP_MINUPTO; + /* +2 the original and the last. */ + common->private_data_ptrs[max_end - common->start - LINK_SIZE + 2] = max + 2; + if (min == 1) + return TRUE; + min--; + max_end -= (1 + LINK_SIZE) + GET(max_end, -LINK_SIZE); + } + } + } + } + +if (min >= 3) + { + common->private_data_ptrs[end - common->start - LINK_SIZE] = max_end - end; + common->private_data_ptrs[end - common->start - LINK_SIZE + 1] = OP_EXACT; + common->private_data_ptrs[end - common->start - LINK_SIZE + 2] = min; + return TRUE; + } + +return FALSE; +} + +#define CASE_ITERATOR_PRIVATE_DATA_1 \ + case OP_MINSTAR: \ + case OP_MINPLUS: \ + case OP_QUERY: \ + case OP_MINQUERY: \ + case OP_MINSTARI: \ + case OP_MINPLUSI: \ + case OP_QUERYI: \ + case OP_MINQUERYI: \ + case OP_NOTMINSTAR: \ + case OP_NOTMINPLUS: \ + case OP_NOTQUERY: \ + case OP_NOTMINQUERY: \ + case OP_NOTMINSTARI: \ + case OP_NOTMINPLUSI: \ + case OP_NOTQUERYI: \ + case OP_NOTMINQUERYI: + +#define CASE_ITERATOR_PRIVATE_DATA_2A \ + case OP_STAR: \ + case OP_PLUS: \ + case OP_STARI: \ + case OP_PLUSI: \ + case OP_NOTSTAR: \ + case OP_NOTPLUS: \ + case OP_NOTSTARI: \ + case OP_NOTPLUSI: + +#define CASE_ITERATOR_PRIVATE_DATA_2B \ + case OP_UPTO: \ + case OP_MINUPTO: \ + case OP_UPTOI: \ + case OP_MINUPTOI: \ + case OP_NOTUPTO: \ + case OP_NOTMINUPTO: \ + case OP_NOTUPTOI: \ + case OP_NOTMINUPTOI: + +#define CASE_ITERATOR_TYPE_PRIVATE_DATA_1 \ + case OP_TYPEMINSTAR: \ + case OP_TYPEMINPLUS: \ + case OP_TYPEQUERY: \ + case OP_TYPEMINQUERY: + +#define CASE_ITERATOR_TYPE_PRIVATE_DATA_2A \ + case OP_TYPESTAR: \ + case OP_TYPEPLUS: + +#define CASE_ITERATOR_TYPE_PRIVATE_DATA_2B \ + case OP_TYPEUPTO: \ + case OP_TYPEMINUPTO: + +static void set_private_data_ptrs(compiler_common *common, int *private_data_start, pcre_uchar *ccend) +{ +pcre_uchar *cc = common->start; +pcre_uchar *alternative; +pcre_uchar *end = NULL; +int private_data_ptr = *private_data_start; +int space, size, bracketlen; + +while (cc < ccend) + { + space = 0; + size = 0; + bracketlen = 0; + if (private_data_ptr > SLJIT_MAX_LOCAL_SIZE) + return; + + if (*cc == OP_ONCE || *cc == OP_ONCE_NC || *cc == OP_BRA || *cc == OP_CBRA || *cc == OP_COND) + if (detect_repeat(common, cc)) + { + /* These brackets are converted to repeats, so no global + based single character repeat is allowed. */ + if (cc >= end) + end = bracketend(cc); + } + + switch(*cc) + { + case OP_KET: + if (common->private_data_ptrs[cc + 1 - common->start] != 0) + { + common->private_data_ptrs[cc - common->start] = private_data_ptr; + private_data_ptr += sizeof(sljit_sw); + cc += common->private_data_ptrs[cc + 1 - common->start]; + } + cc += 1 + LINK_SIZE; + break; + + case OP_ASSERT: + case OP_ASSERT_NOT: + case OP_ASSERTBACK: + case OP_ASSERTBACK_NOT: + case OP_ONCE: + case OP_ONCE_NC: + case OP_BRAPOS: + case OP_SBRA: + case OP_SBRAPOS: + case OP_SCOND: + common->private_data_ptrs[cc - common->start] = private_data_ptr; + private_data_ptr += sizeof(sljit_sw); + bracketlen = 1 + LINK_SIZE; + break; + + case OP_CBRAPOS: + case OP_SCBRAPOS: + common->private_data_ptrs[cc - common->start] = private_data_ptr; + private_data_ptr += sizeof(sljit_sw); + bracketlen = 1 + LINK_SIZE + IMM2_SIZE; + break; + + case OP_COND: + /* Might be a hidden SCOND. */ + alternative = cc + GET(cc, 1); + if (*alternative == OP_KETRMAX || *alternative == OP_KETRMIN) + { + common->private_data_ptrs[cc - common->start] = private_data_ptr; + private_data_ptr += sizeof(sljit_sw); + } + bracketlen = 1 + LINK_SIZE; + break; + + case OP_BRA: + bracketlen = 1 + LINK_SIZE; + break; + + case OP_CBRA: + case OP_SCBRA: + bracketlen = 1 + LINK_SIZE + IMM2_SIZE; + break; + + CASE_ITERATOR_PRIVATE_DATA_1 + space = 1; + size = -2; + break; + + CASE_ITERATOR_PRIVATE_DATA_2A + space = 2; + size = -2; + break; + + CASE_ITERATOR_PRIVATE_DATA_2B + space = 2; + size = -(2 + IMM2_SIZE); + break; + + CASE_ITERATOR_TYPE_PRIVATE_DATA_1 + space = 1; + size = 1; + break; + + CASE_ITERATOR_TYPE_PRIVATE_DATA_2A + if (cc[1] != OP_ANYNL && cc[1] != OP_EXTUNI) + space = 2; + size = 1; + break; + + CASE_ITERATOR_TYPE_PRIVATE_DATA_2B + if (cc[1 + IMM2_SIZE] != OP_ANYNL && cc[1 + IMM2_SIZE] != OP_EXTUNI) + space = 2; + size = 1 + IMM2_SIZE; + break; + + case OP_CLASS: + case OP_NCLASS: + size += 1 + 32 / sizeof(pcre_uchar); + space = get_class_iterator_size(cc + size); + break; + +#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 + case OP_XCLASS: + size = GET(cc, 1); + space = get_class_iterator_size(cc + size); + break; +#endif + + default: + cc = next_opcode(common, cc); + SLJIT_ASSERT(cc != NULL); + break; + } + + /* Character iterators, which are not inside a repeated bracket, + gets a private slot instead of allocating it on the stack. */ + if (space > 0 && cc >= end) + { + common->private_data_ptrs[cc - common->start] = private_data_ptr; + private_data_ptr += sizeof(sljit_sw) * space; + } + + if (size != 0) + { + if (size < 0) + { + cc += -size; +#ifdef SUPPORT_UTF + if (common->utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]); +#endif + } + else + cc += size; + } + + if (bracketlen > 0) + { + if (cc >= end) + { + end = bracketend(cc); + if (end[-1 - LINK_SIZE] == OP_KET) + end = NULL; + } + cc += bracketlen; + } + } +*private_data_start = private_data_ptr; +} + +/* Returns with a frame_types (always < 0) if no need for frame. */ +static int get_framesize(compiler_common *common, pcre_uchar *cc, pcre_uchar *ccend, BOOL recursive, BOOL* needs_control_head) +{ +int length = 0; +int possessive = 0; +BOOL stack_restore = FALSE; +BOOL setsom_found = recursive; +BOOL setmark_found = recursive; +/* The last capture is a local variable even for recursions. */ +BOOL capture_last_found = FALSE; + +#if defined DEBUG_FORCE_CONTROL_HEAD && DEBUG_FORCE_CONTROL_HEAD +SLJIT_ASSERT(common->control_head_ptr != 0); +*needs_control_head = TRUE; +#else +*needs_control_head = FALSE; +#endif + +if (ccend == NULL) + { + ccend = bracketend(cc) - (1 + LINK_SIZE); + if (!recursive && (*cc == OP_CBRAPOS || *cc == OP_SCBRAPOS)) + { + possessive = length = (common->capture_last_ptr != 0) ? 5 : 3; + /* This is correct regardless of common->capture_last_ptr. */ + capture_last_found = TRUE; + } + cc = next_opcode(common, cc); + } + +SLJIT_ASSERT(cc != NULL); +while (cc < ccend) + switch(*cc) + { + case OP_SET_SOM: + SLJIT_ASSERT(common->has_set_som); + stack_restore = TRUE; + if (!setsom_found) + { + length += 2; + setsom_found = TRUE; + } + cc += 1; + break; + + case OP_MARK: + case OP_PRUNE_ARG: + case OP_THEN_ARG: + SLJIT_ASSERT(common->mark_ptr != 0); + stack_restore = TRUE; + if (!setmark_found) + { + length += 2; + setmark_found = TRUE; + } + if (common->control_head_ptr != 0) + *needs_control_head = TRUE; + cc += 1 + 2 + cc[1]; + break; + + case OP_RECURSE: + stack_restore = TRUE; + if (common->has_set_som && !setsom_found) + { + length += 2; + setsom_found = TRUE; + } + if (common->mark_ptr != 0 && !setmark_found) + { + length += 2; + setmark_found = TRUE; + } + if (common->capture_last_ptr != 0 && !capture_last_found) + { + length += 2; + capture_last_found = TRUE; + } + cc += 1 + LINK_SIZE; + break; + + case OP_CBRA: + case OP_CBRAPOS: + case OP_SCBRA: + case OP_SCBRAPOS: + stack_restore = TRUE; + if (common->capture_last_ptr != 0 && !capture_last_found) + { + length += 2; + capture_last_found = TRUE; + } + length += 3; + cc += 1 + LINK_SIZE + IMM2_SIZE; + break; + + default: + stack_restore = TRUE; + /* Fall through. */ + + case OP_NOT_WORD_BOUNDARY: + case OP_WORD_BOUNDARY: + case OP_NOT_DIGIT: + case OP_DIGIT: + case OP_NOT_WHITESPACE: + case OP_WHITESPACE: + case OP_NOT_WORDCHAR: + case OP_WORDCHAR: + case OP_ANY: + case OP_ALLANY: + case OP_ANYBYTE: + case OP_NOTPROP: + case OP_PROP: + case OP_ANYNL: + case OP_NOT_HSPACE: + case OP_HSPACE: + case OP_NOT_VSPACE: + case OP_VSPACE: + case OP_EXTUNI: + case OP_EODN: + case OP_EOD: + case OP_CIRC: + case OP_CIRCM: + case OP_DOLL: + case OP_DOLLM: + case OP_CHAR: + case OP_CHARI: + case OP_NOT: + case OP_NOTI: + + case OP_EXACT: + case OP_POSSTAR: + case OP_POSPLUS: + case OP_POSQUERY: + case OP_POSUPTO: + + case OP_EXACTI: + case OP_POSSTARI: + case OP_POSPLUSI: + case OP_POSQUERYI: + case OP_POSUPTOI: + + case OP_NOTEXACT: + case OP_NOTPOSSTAR: + case OP_NOTPOSPLUS: + case OP_NOTPOSQUERY: + case OP_NOTPOSUPTO: + + case OP_NOTEXACTI: + case OP_NOTPOSSTARI: + case OP_NOTPOSPLUSI: + case OP_NOTPOSQUERYI: + case OP_NOTPOSUPTOI: + + case OP_TYPEEXACT: + case OP_TYPEPOSSTAR: + case OP_TYPEPOSPLUS: + case OP_TYPEPOSQUERY: + case OP_TYPEPOSUPTO: + + case OP_CLASS: + case OP_NCLASS: + case OP_XCLASS: + + cc = next_opcode(common, cc); + SLJIT_ASSERT(cc != NULL); + break; + } + +/* Possessive quantifiers can use a special case. */ +if (SLJIT_UNLIKELY(possessive == length)) + return stack_restore ? no_frame : no_stack; + +if (length > 0) + return length + 1; +return stack_restore ? no_frame : no_stack; +} + +static void init_frame(compiler_common *common, pcre_uchar *cc, pcre_uchar *ccend, int stackpos, int stacktop, BOOL recursive) +{ +DEFINE_COMPILER; +BOOL setsom_found = recursive; +BOOL setmark_found = recursive; +/* The last capture is a local variable even for recursions. */ +BOOL capture_last_found = FALSE; +int offset; + +/* >= 1 + shortest item size (2) */ +SLJIT_UNUSED_ARG(stacktop); +SLJIT_ASSERT(stackpos >= stacktop + 2); + +stackpos = STACK(stackpos); +if (ccend == NULL) + { + ccend = bracketend(cc) - (1 + LINK_SIZE); + if (recursive || (*cc != OP_CBRAPOS && *cc != OP_SCBRAPOS)) + cc = next_opcode(common, cc); + } + +SLJIT_ASSERT(cc != NULL); +while (cc < ccend) + switch(*cc) + { + case OP_SET_SOM: + SLJIT_ASSERT(common->has_set_som); + if (!setsom_found) + { + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(0)); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, SLJIT_IMM, -OVECTOR(0)); + stackpos += (int)sizeof(sljit_sw); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, TMP1, 0); + stackpos += (int)sizeof(sljit_sw); + setsom_found = TRUE; + } + cc += 1; + break; + + case OP_MARK: + case OP_PRUNE_ARG: + case OP_THEN_ARG: + SLJIT_ASSERT(common->mark_ptr != 0); + if (!setmark_found) + { + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->mark_ptr); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, SLJIT_IMM, -common->mark_ptr); + stackpos += (int)sizeof(sljit_sw); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, TMP1, 0); + stackpos += (int)sizeof(sljit_sw); + setmark_found = TRUE; + } + cc += 1 + 2 + cc[1]; + break; + + case OP_RECURSE: + if (common->has_set_som && !setsom_found) + { + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(0)); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, SLJIT_IMM, -OVECTOR(0)); + stackpos += (int)sizeof(sljit_sw); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, TMP1, 0); + stackpos += (int)sizeof(sljit_sw); + setsom_found = TRUE; + } + if (common->mark_ptr != 0 && !setmark_found) + { + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->mark_ptr); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, SLJIT_IMM, -common->mark_ptr); + stackpos += (int)sizeof(sljit_sw); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, TMP1, 0); + stackpos += (int)sizeof(sljit_sw); + setmark_found = TRUE; + } + if (common->capture_last_ptr != 0 && !capture_last_found) + { + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->capture_last_ptr); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, SLJIT_IMM, -common->capture_last_ptr); + stackpos += (int)sizeof(sljit_sw); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, TMP1, 0); + stackpos += (int)sizeof(sljit_sw); + capture_last_found = TRUE; + } + cc += 1 + LINK_SIZE; + break; + + case OP_CBRA: + case OP_CBRAPOS: + case OP_SCBRA: + case OP_SCBRAPOS: + if (common->capture_last_ptr != 0 && !capture_last_found) + { + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->capture_last_ptr); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, SLJIT_IMM, -common->capture_last_ptr); + stackpos += (int)sizeof(sljit_sw); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, TMP1, 0); + stackpos += (int)sizeof(sljit_sw); + capture_last_found = TRUE; + } + offset = (GET2(cc, 1 + LINK_SIZE)) << 1; + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, SLJIT_IMM, OVECTOR(offset)); + stackpos += (int)sizeof(sljit_sw); + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset)); + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1)); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, TMP1, 0); + stackpos += (int)sizeof(sljit_sw); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, TMP2, 0); + stackpos += (int)sizeof(sljit_sw); + + cc += 1 + LINK_SIZE + IMM2_SIZE; + break; + + default: + cc = next_opcode(common, cc); + SLJIT_ASSERT(cc != NULL); + break; + } + +OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, SLJIT_IMM, 0); +SLJIT_ASSERT(stackpos == STACK(stacktop)); +} + +static SLJIT_INLINE int get_private_data_copy_length(compiler_common *common, pcre_uchar *cc, pcre_uchar *ccend, BOOL needs_control_head) +{ +int private_data_length = needs_control_head ? 3 : 2; +int size; +pcre_uchar *alternative; +/* Calculate the sum of the private machine words. */ +while (cc < ccend) + { + size = 0; + switch(*cc) + { + case OP_KET: + if (PRIVATE_DATA(cc) != 0) + private_data_length++; + cc += 1 + LINK_SIZE; + break; + + case OP_ASSERT: + case OP_ASSERT_NOT: + case OP_ASSERTBACK: + case OP_ASSERTBACK_NOT: + case OP_ONCE: + case OP_ONCE_NC: + case OP_BRAPOS: + case OP_SBRA: + case OP_SBRAPOS: + case OP_SCOND: + private_data_length++; + cc += 1 + LINK_SIZE; + break; + + case OP_CBRA: + case OP_SCBRA: + if (common->optimized_cbracket[GET2(cc, 1 + LINK_SIZE)] == 0) + private_data_length++; + cc += 1 + LINK_SIZE + IMM2_SIZE; + break; + + case OP_CBRAPOS: + case OP_SCBRAPOS: + private_data_length += 2; + cc += 1 + LINK_SIZE + IMM2_SIZE; + break; + + case OP_COND: + /* Might be a hidden SCOND. */ + alternative = cc + GET(cc, 1); + if (*alternative == OP_KETRMAX || *alternative == OP_KETRMIN) + private_data_length++; + cc += 1 + LINK_SIZE; + break; + + CASE_ITERATOR_PRIVATE_DATA_1 + if (PRIVATE_DATA(cc)) + private_data_length++; + cc += 2; +#ifdef SUPPORT_UTF + if (common->utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]); +#endif + break; + + CASE_ITERATOR_PRIVATE_DATA_2A + if (PRIVATE_DATA(cc)) + private_data_length += 2; + cc += 2; +#ifdef SUPPORT_UTF + if (common->utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]); +#endif + break; + + CASE_ITERATOR_PRIVATE_DATA_2B + if (PRIVATE_DATA(cc)) + private_data_length += 2; + cc += 2 + IMM2_SIZE; +#ifdef SUPPORT_UTF + if (common->utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]); +#endif + break; + + CASE_ITERATOR_TYPE_PRIVATE_DATA_1 + if (PRIVATE_DATA(cc)) + private_data_length++; + cc += 1; + break; + + CASE_ITERATOR_TYPE_PRIVATE_DATA_2A + if (PRIVATE_DATA(cc)) + private_data_length += 2; + cc += 1; + break; + + CASE_ITERATOR_TYPE_PRIVATE_DATA_2B + if (PRIVATE_DATA(cc)) + private_data_length += 2; + cc += 1 + IMM2_SIZE; + break; + + case OP_CLASS: + case OP_NCLASS: +#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 + case OP_XCLASS: + size = (*cc == OP_XCLASS) ? GET(cc, 1) : 1 + 32 / (int)sizeof(pcre_uchar); +#else + size = 1 + 32 / (int)sizeof(pcre_uchar); +#endif + if (PRIVATE_DATA(cc)) + private_data_length += get_class_iterator_size(cc + size); + cc += size; + break; + + default: + cc = next_opcode(common, cc); + SLJIT_ASSERT(cc != NULL); + break; + } + } +SLJIT_ASSERT(cc == ccend); +return private_data_length; +} + +static void copy_private_data(compiler_common *common, pcre_uchar *cc, pcre_uchar *ccend, + BOOL save, int stackptr, int stacktop, BOOL needs_control_head) +{ +DEFINE_COMPILER; +int srcw[2]; +int count, size; +BOOL tmp1next = TRUE; +BOOL tmp1empty = TRUE; +BOOL tmp2empty = TRUE; +pcre_uchar *alternative; +enum { + start, + loop, + end +} status; + +status = save ? start : loop; +stackptr = STACK(stackptr - 2); +stacktop = STACK(stacktop - 1); + +if (!save) + { + stackptr += (needs_control_head ? 2 : 1) * sizeof(sljit_sw); + if (stackptr < stacktop) + { + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), stackptr); + stackptr += sizeof(sljit_sw); + tmp1empty = FALSE; + } + if (stackptr < stacktop) + { + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), stackptr); + stackptr += sizeof(sljit_sw); + tmp2empty = FALSE; + } + /* The tmp1next must be TRUE in either way. */ + } + +do + { + count = 0; + switch(status) + { + case start: + SLJIT_ASSERT(save && common->recursive_head_ptr != 0); + count = 1; + srcw[0] = common->recursive_head_ptr; + if (needs_control_head) + { + SLJIT_ASSERT(common->control_head_ptr != 0); + count = 2; + srcw[1] = common->control_head_ptr; + } + status = loop; + break; + + case loop: + if (cc >= ccend) + { + status = end; + break; + } + + switch(*cc) + { + case OP_KET: + if (PRIVATE_DATA(cc) != 0) + { + count = 1; + srcw[0] = PRIVATE_DATA(cc); + } + cc += 1 + LINK_SIZE; + break; + + case OP_ASSERT: + case OP_ASSERT_NOT: + case OP_ASSERTBACK: + case OP_ASSERTBACK_NOT: + case OP_ONCE: + case OP_ONCE_NC: + case OP_BRAPOS: + case OP_SBRA: + case OP_SBRAPOS: + case OP_SCOND: + count = 1; + srcw[0] = PRIVATE_DATA(cc); + SLJIT_ASSERT(srcw[0] != 0); + cc += 1 + LINK_SIZE; + break; + + case OP_CBRA: + case OP_SCBRA: + if (common->optimized_cbracket[GET2(cc, 1 + LINK_SIZE)] == 0) + { + count = 1; + srcw[0] = OVECTOR_PRIV(GET2(cc, 1 + LINK_SIZE)); + } + cc += 1 + LINK_SIZE + IMM2_SIZE; + break; + + case OP_CBRAPOS: + case OP_SCBRAPOS: + count = 2; + srcw[0] = PRIVATE_DATA(cc); + srcw[1] = OVECTOR_PRIV(GET2(cc, 1 + LINK_SIZE)); + SLJIT_ASSERT(srcw[0] != 0 && srcw[1] != 0); + cc += 1 + LINK_SIZE + IMM2_SIZE; + break; + + case OP_COND: + /* Might be a hidden SCOND. */ + alternative = cc + GET(cc, 1); + if (*alternative == OP_KETRMAX || *alternative == OP_KETRMIN) + { + count = 1; + srcw[0] = PRIVATE_DATA(cc); + SLJIT_ASSERT(srcw[0] != 0); + } + cc += 1 + LINK_SIZE; + break; + + CASE_ITERATOR_PRIVATE_DATA_1 + if (PRIVATE_DATA(cc)) + { + count = 1; + srcw[0] = PRIVATE_DATA(cc); + } + cc += 2; +#ifdef SUPPORT_UTF + if (common->utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]); +#endif + break; + + CASE_ITERATOR_PRIVATE_DATA_2A + if (PRIVATE_DATA(cc)) + { + count = 2; + srcw[0] = PRIVATE_DATA(cc); + srcw[1] = PRIVATE_DATA(cc) + sizeof(sljit_sw); + } + cc += 2; +#ifdef SUPPORT_UTF + if (common->utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]); +#endif + break; + + CASE_ITERATOR_PRIVATE_DATA_2B + if (PRIVATE_DATA(cc)) + { + count = 2; + srcw[0] = PRIVATE_DATA(cc); + srcw[1] = PRIVATE_DATA(cc) + sizeof(sljit_sw); + } + cc += 2 + IMM2_SIZE; +#ifdef SUPPORT_UTF + if (common->utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]); +#endif + break; + + CASE_ITERATOR_TYPE_PRIVATE_DATA_1 + if (PRIVATE_DATA(cc)) + { + count = 1; + srcw[0] = PRIVATE_DATA(cc); + } + cc += 1; + break; + + CASE_ITERATOR_TYPE_PRIVATE_DATA_2A + if (PRIVATE_DATA(cc)) + { + count = 2; + srcw[0] = PRIVATE_DATA(cc); + srcw[1] = srcw[0] + sizeof(sljit_sw); + } + cc += 1; + break; + + CASE_ITERATOR_TYPE_PRIVATE_DATA_2B + if (PRIVATE_DATA(cc)) + { + count = 2; + srcw[0] = PRIVATE_DATA(cc); + srcw[1] = srcw[0] + sizeof(sljit_sw); + } + cc += 1 + IMM2_SIZE; + break; + + case OP_CLASS: + case OP_NCLASS: +#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 + case OP_XCLASS: + size = (*cc == OP_XCLASS) ? GET(cc, 1) : 1 + 32 / (int)sizeof(pcre_uchar); +#else + size = 1 + 32 / (int)sizeof(pcre_uchar); +#endif + if (PRIVATE_DATA(cc)) + switch(get_class_iterator_size(cc + size)) + { + case 1: + count = 1; + srcw[0] = PRIVATE_DATA(cc); + break; + + case 2: + count = 2; + srcw[0] = PRIVATE_DATA(cc); + srcw[1] = srcw[0] + sizeof(sljit_sw); + break; + + default: + SLJIT_ASSERT_STOP(); + break; + } + cc += size; + break; + + default: + cc = next_opcode(common, cc); + SLJIT_ASSERT(cc != NULL); + break; + } + break; + + case end: + SLJIT_ASSERT_STOP(); + break; + } + + while (count > 0) + { + count--; + if (save) + { + if (tmp1next) + { + if (!tmp1empty) + { + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackptr, TMP1, 0); + stackptr += sizeof(sljit_sw); + } + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), srcw[count]); + tmp1empty = FALSE; + tmp1next = FALSE; + } + else + { + if (!tmp2empty) + { + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackptr, TMP2, 0); + stackptr += sizeof(sljit_sw); + } + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), srcw[count]); + tmp2empty = FALSE; + tmp1next = TRUE; + } + } + else + { + if (tmp1next) + { + SLJIT_ASSERT(!tmp1empty); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), srcw[count], TMP1, 0); + tmp1empty = stackptr >= stacktop; + if (!tmp1empty) + { + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), stackptr); + stackptr += sizeof(sljit_sw); + } + tmp1next = FALSE; + } + else + { + SLJIT_ASSERT(!tmp2empty); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), srcw[count], TMP2, 0); + tmp2empty = stackptr >= stacktop; + if (!tmp2empty) + { + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), stackptr); + stackptr += sizeof(sljit_sw); + } + tmp1next = TRUE; + } + } + } + } +while (status != end); + +if (save) + { + if (tmp1next) + { + if (!tmp1empty) + { + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackptr, TMP1, 0); + stackptr += sizeof(sljit_sw); + } + if (!tmp2empty) + { + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackptr, TMP2, 0); + stackptr += sizeof(sljit_sw); + } + } + else + { + if (!tmp2empty) + { + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackptr, TMP2, 0); + stackptr += sizeof(sljit_sw); + } + if (!tmp1empty) + { + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackptr, TMP1, 0); + stackptr += sizeof(sljit_sw); + } + } + } +SLJIT_ASSERT(cc == ccend && stackptr == stacktop && (save || (tmp1empty && tmp2empty))); +} + +static SLJIT_INLINE pcre_uchar *set_then_offsets(compiler_common *common, pcre_uchar *cc, pcre_uint8 *current_offset) +{ +pcre_uchar *end = bracketend(cc); +BOOL has_alternatives = cc[GET(cc, 1)] == OP_ALT; + +/* Assert captures then. */ +if (*cc >= OP_ASSERT && *cc <= OP_ASSERTBACK_NOT) + current_offset = NULL; +/* Conditional block does not. */ +if (*cc == OP_COND || *cc == OP_SCOND) + has_alternatives = FALSE; + +cc = next_opcode(common, cc); +if (has_alternatives) + current_offset = common->then_offsets + (cc - common->start); + +while (cc < end) + { + if ((*cc >= OP_ASSERT && *cc <= OP_ASSERTBACK_NOT) || (*cc >= OP_ONCE && *cc <= OP_SCOND)) + cc = set_then_offsets(common, cc, current_offset); + else + { + if (*cc == OP_ALT && has_alternatives) + current_offset = common->then_offsets + (cc + 1 + LINK_SIZE - common->start); + if (*cc >= OP_THEN && *cc <= OP_THEN_ARG && current_offset != NULL) + *current_offset = 1; + cc = next_opcode(common, cc); + } + } + +return end; +} + +#undef CASE_ITERATOR_PRIVATE_DATA_1 +#undef CASE_ITERATOR_PRIVATE_DATA_2A +#undef CASE_ITERATOR_PRIVATE_DATA_2B +#undef CASE_ITERATOR_TYPE_PRIVATE_DATA_1 +#undef CASE_ITERATOR_TYPE_PRIVATE_DATA_2A +#undef CASE_ITERATOR_TYPE_PRIVATE_DATA_2B + +static SLJIT_INLINE BOOL is_powerof2(unsigned int value) +{ +return (value & (value - 1)) == 0; +} + +static SLJIT_INLINE void set_jumps(jump_list *list, struct sljit_label *label) +{ +while (list) + { + /* sljit_set_label is clever enough to do nothing + if either the jump or the label is NULL. */ + SET_LABEL(list->jump, label); + list = list->next; + } +} + +static SLJIT_INLINE void add_jump(struct sljit_compiler *compiler, jump_list **list, struct sljit_jump* jump) +{ +jump_list *list_item = sljit_alloc_memory(compiler, sizeof(jump_list)); +if (list_item) + { + list_item->next = *list; + list_item->jump = jump; + *list = list_item; + } +} + +static void add_stub(compiler_common *common, struct sljit_jump *start) +{ +DEFINE_COMPILER; +stub_list* list_item = sljit_alloc_memory(compiler, sizeof(stub_list)); + +if (list_item) + { + list_item->start = start; + list_item->quit = LABEL(); + list_item->next = common->stubs; + common->stubs = list_item; + } +} + +static void flush_stubs(compiler_common *common) +{ +DEFINE_COMPILER; +stub_list* list_item = common->stubs; + +while (list_item) + { + JUMPHERE(list_item->start); + add_jump(compiler, &common->stackalloc, JUMP(SLJIT_FAST_CALL)); + JUMPTO(SLJIT_JUMP, list_item->quit); + list_item = list_item->next; + } +common->stubs = NULL; +} + +static void add_label_addr(compiler_common *common, sljit_uw *update_addr) +{ +DEFINE_COMPILER; +label_addr_list *label_addr; + +label_addr = sljit_alloc_memory(compiler, sizeof(label_addr_list)); +if (label_addr == NULL) + return; +label_addr->label = LABEL(); +label_addr->update_addr = update_addr; +label_addr->next = common->label_addrs; +common->label_addrs = label_addr; +} + +static SLJIT_INLINE void count_match(compiler_common *common) +{ +DEFINE_COMPILER; + +OP2(SLJIT_SUB | SLJIT_SET_E, COUNT_MATCH, 0, COUNT_MATCH, 0, SLJIT_IMM, 1); +add_jump(compiler, &common->calllimit, JUMP(SLJIT_C_ZERO)); +} + +static SLJIT_INLINE void allocate_stack(compiler_common *common, int size) +{ +/* May destroy all locals and registers except TMP2. */ +DEFINE_COMPILER; + +OP2(SLJIT_ADD, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, size * sizeof(sljit_sw)); +#ifdef DESTROY_REGISTERS +OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, 12345); +OP1(SLJIT_MOV, TMP3, 0, TMP1, 0); +OP1(SLJIT_MOV, RETURN_ADDR, 0, TMP1, 0); +OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS0, TMP1, 0); +OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS1, TMP1, 0); +#endif +add_stub(common, CMP(SLJIT_C_GREATER, STACK_TOP, 0, STACK_LIMIT, 0)); +} + +static SLJIT_INLINE void free_stack(compiler_common *common, int size) +{ +DEFINE_COMPILER; +OP2(SLJIT_SUB, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, size * sizeof(sljit_sw)); +} + +static SLJIT_INLINE void reset_ovector(compiler_common *common, int length) +{ +DEFINE_COMPILER; +struct sljit_label *loop; +int i; + +/* At this point we can freely use all temporary registers. */ +SLJIT_ASSERT(length > 1); +/* TMP1 returns with begin - 1. */ +OP2(SLJIT_SUB, SLJIT_R0, 0, SLJIT_MEM1(SLJIT_S0), SLJIT_OFFSETOF(jit_arguments, begin), SLJIT_IMM, IN_UCHARS(1)); +if (length < 8) + { + for (i = 1; i < length; i++) + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(i), SLJIT_R0, 0); + } +else + { + GET_LOCAL_BASE(SLJIT_R1, 0, OVECTOR_START); + OP1(SLJIT_MOV, SLJIT_R2, 0, SLJIT_IMM, length - 1); + loop = LABEL(); + OP1(SLJIT_MOVU, SLJIT_MEM1(SLJIT_R1), sizeof(sljit_sw), SLJIT_R0, 0); + OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_R2, 0, SLJIT_R2, 0, SLJIT_IMM, 1); + JUMPTO(SLJIT_C_NOT_ZERO, loop); + } +} + +static SLJIT_INLINE void do_reset_match(compiler_common *common, int length) +{ +DEFINE_COMPILER; +struct sljit_label *loop; +int i; + +SLJIT_ASSERT(length > 1); +/* OVECTOR(1) contains the "string begin - 1" constant. */ +if (length > 2) + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(1)); +if (length < 8) + { + for (i = 2; i < length; i++) + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(i), TMP1, 0); + } +else + { + GET_LOCAL_BASE(TMP2, 0, OVECTOR_START + sizeof(sljit_sw)); + OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_IMM, length - 2); + loop = LABEL(); + OP1(SLJIT_MOVU, SLJIT_MEM1(TMP2), sizeof(sljit_sw), TMP1, 0); + OP2(SLJIT_SUB | SLJIT_SET_E, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, 1); + JUMPTO(SLJIT_C_NOT_ZERO, loop); + } + +OP1(SLJIT_MOV, STACK_TOP, 0, ARGUMENTS, 0); +if (common->mark_ptr != 0) + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->mark_ptr, SLJIT_IMM, 0); +if (common->control_head_ptr != 0) + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, SLJIT_IMM, 0); +OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(STACK_TOP), SLJIT_OFFSETOF(jit_arguments, stack)); +OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->start_ptr); +OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(STACK_TOP), SLJIT_OFFSETOF(struct sljit_stack, base)); +} + +static sljit_sw SLJIT_CALL do_search_mark(sljit_sw *current, const pcre_uchar *skip_arg) +{ +while (current != NULL) + { + switch (current[-2]) + { + case type_then_trap: + break; + + case type_mark: + if (STRCMP_UC_UC(skip_arg, (pcre_uchar *)current[-3]) == 0) + return current[-4]; + break; + + default: + SLJIT_ASSERT_STOP(); + break; + } + current = (sljit_sw*)current[-1]; + } +return -1; +} + +static SLJIT_INLINE void copy_ovector(compiler_common *common, int topbracket) +{ +DEFINE_COMPILER; +struct sljit_label *loop; +struct sljit_jump *early_quit; + +/* At this point we can freely use all registers. */ +OP1(SLJIT_MOV, SLJIT_S2, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(1)); +OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(1), STR_PTR, 0); + +OP1(SLJIT_MOV, SLJIT_R0, 0, ARGUMENTS, 0); +if (common->mark_ptr != 0) + OP1(SLJIT_MOV, SLJIT_R2, 0, SLJIT_MEM1(SLJIT_SP), common->mark_ptr); +OP1(SLJIT_MOV_SI, SLJIT_R1, 0, SLJIT_MEM1(SLJIT_R0), SLJIT_OFFSETOF(jit_arguments, offset_count)); +if (common->mark_ptr != 0) + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_R0), SLJIT_OFFSETOF(jit_arguments, mark_ptr), SLJIT_R2, 0); +OP2(SLJIT_SUB, SLJIT_R2, 0, SLJIT_MEM1(SLJIT_R0), SLJIT_OFFSETOF(jit_arguments, offsets), SLJIT_IMM, sizeof(int)); +OP1(SLJIT_MOV, SLJIT_R0, 0, SLJIT_MEM1(SLJIT_R0), SLJIT_OFFSETOF(jit_arguments, begin)); +GET_LOCAL_BASE(SLJIT_S0, 0, OVECTOR_START); +/* Unlikely, but possible */ +early_quit = CMP(SLJIT_C_EQUAL, SLJIT_R1, 0, SLJIT_IMM, 0); +loop = LABEL(); +OP2(SLJIT_SUB, SLJIT_S1, 0, SLJIT_MEM1(SLJIT_S0), 0, SLJIT_R0, 0); +OP2(SLJIT_ADD, SLJIT_S0, 0, SLJIT_S0, 0, SLJIT_IMM, sizeof(sljit_sw)); +/* Copy the integer value to the output buffer */ +#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 +OP2(SLJIT_ASHR, SLJIT_S1, 0, SLJIT_S1, 0, SLJIT_IMM, UCHAR_SHIFT); +#endif +OP1(SLJIT_MOVU_SI, SLJIT_MEM1(SLJIT_R2), sizeof(int), SLJIT_S1, 0); +OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_R1, 0, SLJIT_R1, 0, SLJIT_IMM, 1); +JUMPTO(SLJIT_C_NOT_ZERO, loop); +JUMPHERE(early_quit); + +/* Calculate the return value, which is the maximum ovector value. */ +if (topbracket > 1) + { + GET_LOCAL_BASE(SLJIT_R0, 0, OVECTOR_START + topbracket * 2 * sizeof(sljit_sw)); + OP1(SLJIT_MOV, SLJIT_R1, 0, SLJIT_IMM, topbracket + 1); + + /* OVECTOR(0) is never equal to SLJIT_S2. */ + loop = LABEL(); + OP1(SLJIT_MOVU, SLJIT_R2, 0, SLJIT_MEM1(SLJIT_R0), -(2 * (sljit_sw)sizeof(sljit_sw))); + OP2(SLJIT_SUB, SLJIT_R1, 0, SLJIT_R1, 0, SLJIT_IMM, 1); + CMPTO(SLJIT_C_EQUAL, SLJIT_R2, 0, SLJIT_S2, 0, loop); + OP1(SLJIT_MOV, SLJIT_RETURN_REG, 0, SLJIT_R1, 0); + } +else + OP1(SLJIT_MOV, SLJIT_RETURN_REG, 0, SLJIT_IMM, 1); +} + +static SLJIT_INLINE void return_with_partial_match(compiler_common *common, struct sljit_label *quit) +{ +DEFINE_COMPILER; +struct sljit_jump *jump; + +SLJIT_COMPILE_ASSERT(STR_END == SLJIT_S1, str_end_must_be_saved_reg2); +SLJIT_ASSERT(common->start_used_ptr != 0 && common->start_ptr != 0 + && (common->mode == JIT_PARTIAL_SOFT_COMPILE ? common->hit_start != 0 : common->hit_start == 0)); + +OP1(SLJIT_MOV, SLJIT_R1, 0, ARGUMENTS, 0); +OP1(SLJIT_MOV, SLJIT_RETURN_REG, 0, SLJIT_IMM, PCRE_ERROR_PARTIAL); +OP1(SLJIT_MOV_SI, SLJIT_R2, 0, SLJIT_MEM1(SLJIT_R1), SLJIT_OFFSETOF(jit_arguments, real_offset_count)); +CMPTO(SLJIT_C_SIG_LESS, SLJIT_R2, 0, SLJIT_IMM, 2, quit); + +/* Store match begin and end. */ +OP1(SLJIT_MOV, SLJIT_S0, 0, SLJIT_MEM1(SLJIT_R1), SLJIT_OFFSETOF(jit_arguments, begin)); +OP1(SLJIT_MOV, SLJIT_R1, 0, SLJIT_MEM1(SLJIT_R1), SLJIT_OFFSETOF(jit_arguments, offsets)); + +jump = CMP(SLJIT_C_SIG_LESS, SLJIT_R2, 0, SLJIT_IMM, 3); +OP2(SLJIT_SUB, SLJIT_R2, 0, SLJIT_MEM1(SLJIT_SP), common->mode == JIT_PARTIAL_HARD_COMPILE ? common->start_ptr : (common->hit_start + (int)sizeof(sljit_sw)), SLJIT_S0, 0); +#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 +OP2(SLJIT_ASHR, SLJIT_R2, 0, SLJIT_R2, 0, SLJIT_IMM, UCHAR_SHIFT); +#endif +OP1(SLJIT_MOV_SI, SLJIT_MEM1(SLJIT_R1), 2 * sizeof(int), SLJIT_R2, 0); +JUMPHERE(jump); + +OP1(SLJIT_MOV, SLJIT_R2, 0, SLJIT_MEM1(SLJIT_SP), common->mode == JIT_PARTIAL_HARD_COMPILE ? common->start_used_ptr : common->hit_start); +OP2(SLJIT_SUB, SLJIT_S1, 0, STR_END, 0, SLJIT_S0, 0); +#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 +OP2(SLJIT_ASHR, SLJIT_S1, 0, SLJIT_S1, 0, SLJIT_IMM, UCHAR_SHIFT); +#endif +OP1(SLJIT_MOV_SI, SLJIT_MEM1(SLJIT_R1), sizeof(int), SLJIT_S1, 0); + +OP2(SLJIT_SUB, SLJIT_R2, 0, SLJIT_R2, 0, SLJIT_S0, 0); +#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 +OP2(SLJIT_ASHR, SLJIT_R2, 0, SLJIT_R2, 0, SLJIT_IMM, UCHAR_SHIFT); +#endif +OP1(SLJIT_MOV_SI, SLJIT_MEM1(SLJIT_R1), 0, SLJIT_R2, 0); + +JUMPTO(SLJIT_JUMP, quit); +} + +static SLJIT_INLINE void check_start_used_ptr(compiler_common *common) +{ +/* May destroy TMP1. */ +DEFINE_COMPILER; +struct sljit_jump *jump; + +if (common->mode == JIT_PARTIAL_SOFT_COMPILE) + { + /* The value of -1 must be kept for start_used_ptr! */ + OP2(SLJIT_ADD, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->start_used_ptr, SLJIT_IMM, 1); + /* Jumps if start_used_ptr < STR_PTR, or start_used_ptr == -1. Although overwriting + is not necessary if start_used_ptr == STR_PTR, it does not hurt as well. */ + jump = CMP(SLJIT_C_LESS_EQUAL, TMP1, 0, STR_PTR, 0); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->start_used_ptr, STR_PTR, 0); + JUMPHERE(jump); + } +else if (common->mode == JIT_PARTIAL_HARD_COMPILE) + { + jump = CMP(SLJIT_C_LESS_EQUAL, SLJIT_MEM1(SLJIT_SP), common->start_used_ptr, STR_PTR, 0); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->start_used_ptr, STR_PTR, 0); + JUMPHERE(jump); + } +} + +static SLJIT_INLINE BOOL char_has_othercase(compiler_common *common, pcre_uchar* cc) +{ +/* Detects if the character has an othercase. */ +unsigned int c; + +#ifdef SUPPORT_UTF +if (common->utf) + { + GETCHAR(c, cc); + if (c > 127) + { +#ifdef SUPPORT_UCP + return c != UCD_OTHERCASE(c); +#else + return FALSE; +#endif + } +#ifndef COMPILE_PCRE8 + return common->fcc[c] != c; +#endif + } +else +#endif + c = *cc; +return MAX_255(c) ? common->fcc[c] != c : FALSE; +} + +static SLJIT_INLINE unsigned int char_othercase(compiler_common *common, unsigned int c) +{ +/* Returns with the othercase. */ +#ifdef SUPPORT_UTF +if (common->utf && c > 127) + { +#ifdef SUPPORT_UCP + return UCD_OTHERCASE(c); +#else + return c; +#endif + } +#endif +return TABLE_GET(c, common->fcc, c); +} + +static unsigned int char_get_othercase_bit(compiler_common *common, pcre_uchar* cc) +{ +/* Detects if the character and its othercase has only 1 bit difference. */ +unsigned int c, oc, bit; +#if defined SUPPORT_UTF && defined COMPILE_PCRE8 +int n; +#endif + +#ifdef SUPPORT_UTF +if (common->utf) + { + GETCHAR(c, cc); + if (c <= 127) + oc = common->fcc[c]; + else + { +#ifdef SUPPORT_UCP + oc = UCD_OTHERCASE(c); +#else + oc = c; +#endif + } + } +else + { + c = *cc; + oc = TABLE_GET(c, common->fcc, c); + } +#else +c = *cc; +oc = TABLE_GET(c, common->fcc, c); +#endif + +SLJIT_ASSERT(c != oc); + +bit = c ^ oc; +/* Optimized for English alphabet. */ +if (c <= 127 && bit == 0x20) + return (0 << 8) | 0x20; + +/* Since c != oc, they must have at least 1 bit difference. */ +if (!is_powerof2(bit)) + return 0; + +#if defined COMPILE_PCRE8 + +#ifdef SUPPORT_UTF +if (common->utf && c > 127) + { + n = GET_EXTRALEN(*cc); + while ((bit & 0x3f) == 0) + { + n--; + bit >>= 6; + } + return (n << 8) | bit; + } +#endif /* SUPPORT_UTF */ +return (0 << 8) | bit; + +#elif defined COMPILE_PCRE16 || defined COMPILE_PCRE32 + +#ifdef SUPPORT_UTF +if (common->utf && c > 65535) + { + if (bit >= (1 << 10)) + bit >>= 10; + else + return (bit < 256) ? ((2 << 8) | bit) : ((3 << 8) | (bit >> 8)); + } +#endif /* SUPPORT_UTF */ +return (bit < 256) ? ((0 << 8) | bit) : ((1 << 8) | (bit >> 8)); + +#endif /* COMPILE_PCRE[8|16|32] */ +} + +static void check_partial(compiler_common *common, BOOL force) +{ +/* Checks whether a partial matching is occurred. Does not modify registers. */ +DEFINE_COMPILER; +struct sljit_jump *jump = NULL; + +SLJIT_ASSERT(!force || common->mode != JIT_COMPILE); + +if (common->mode == JIT_COMPILE) + return; + +if (!force) + jump = CMP(SLJIT_C_GREATER_EQUAL, SLJIT_MEM1(SLJIT_SP), common->start_used_ptr, STR_PTR, 0); +else if (common->mode == JIT_PARTIAL_SOFT_COMPILE) + jump = CMP(SLJIT_C_EQUAL, SLJIT_MEM1(SLJIT_SP), common->start_used_ptr, SLJIT_IMM, -1); + +if (common->mode == JIT_PARTIAL_SOFT_COMPILE) + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->hit_start, SLJIT_IMM, 0); +else + { + if (common->partialmatchlabel != NULL) + JUMPTO(SLJIT_JUMP, common->partialmatchlabel); + else + add_jump(compiler, &common->partialmatch, JUMP(SLJIT_JUMP)); + } + +if (jump != NULL) + JUMPHERE(jump); +} + +static void check_str_end(compiler_common *common, jump_list **end_reached) +{ +/* Does not affect registers. Usually used in a tight spot. */ +DEFINE_COMPILER; +struct sljit_jump *jump; + +if (common->mode == JIT_COMPILE) + { + add_jump(compiler, end_reached, CMP(SLJIT_C_GREATER_EQUAL, STR_PTR, 0, STR_END, 0)); + return; + } + +jump = CMP(SLJIT_C_LESS, STR_PTR, 0, STR_END, 0); +if (common->mode == JIT_PARTIAL_SOFT_COMPILE) + { + add_jump(compiler, end_reached, CMP(SLJIT_C_GREATER_EQUAL, SLJIT_MEM1(SLJIT_SP), common->start_used_ptr, STR_PTR, 0)); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->hit_start, SLJIT_IMM, 0); + add_jump(compiler, end_reached, JUMP(SLJIT_JUMP)); + } +else + { + add_jump(compiler, end_reached, CMP(SLJIT_C_GREATER_EQUAL, SLJIT_MEM1(SLJIT_SP), common->start_used_ptr, STR_PTR, 0)); + if (common->partialmatchlabel != NULL) + JUMPTO(SLJIT_JUMP, common->partialmatchlabel); + else + add_jump(compiler, &common->partialmatch, JUMP(SLJIT_JUMP)); + } +JUMPHERE(jump); +} + +static void detect_partial_match(compiler_common *common, jump_list **backtracks) +{ +DEFINE_COMPILER; +struct sljit_jump *jump; + +if (common->mode == JIT_COMPILE) + { + add_jump(compiler, backtracks, CMP(SLJIT_C_GREATER_EQUAL, STR_PTR, 0, STR_END, 0)); + return; + } + +/* Partial matching mode. */ +jump = CMP(SLJIT_C_LESS, STR_PTR, 0, STR_END, 0); +add_jump(compiler, backtracks, CMP(SLJIT_C_GREATER_EQUAL, SLJIT_MEM1(SLJIT_SP), common->start_used_ptr, STR_PTR, 0)); +if (common->mode == JIT_PARTIAL_SOFT_COMPILE) + { + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->hit_start, SLJIT_IMM, 0); + add_jump(compiler, backtracks, JUMP(SLJIT_JUMP)); + } +else + { + if (common->partialmatchlabel != NULL) + JUMPTO(SLJIT_JUMP, common->partialmatchlabel); + else + add_jump(compiler, &common->partialmatch, JUMP(SLJIT_JUMP)); + } +JUMPHERE(jump); +} + +static void peek_char(compiler_common *common, pcre_uint32 max) +{ +/* Reads the character into TMP1, keeps STR_PTR. +Does not check STR_END. TMP2 Destroyed. */ +DEFINE_COMPILER; +#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 +struct sljit_jump *jump; +#endif + +SLJIT_UNUSED_ARG(max); + +OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), 0); +#if defined SUPPORT_UTF && defined COMPILE_PCRE8 +if (common->utf) + { + if (max < 128) return; + + jump = CMP(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, 0xc0); + OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); + add_jump(compiler, &common->utfreadchar, JUMP(SLJIT_FAST_CALL)); + OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, TMP2, 0); + JUMPHERE(jump); + } +#endif /* SUPPORT_UTF && !COMPILE_PCRE32 */ + +#if defined SUPPORT_UTF && defined COMPILE_PCRE16 +if (common->utf) + { + if (max < 0xd800) return; + + OP2(SLJIT_SUB, TMP2, 0, TMP1, 0, SLJIT_IMM, 0xd800); + jump = CMP(SLJIT_C_GREATER, TMP2, 0, SLJIT_IMM, 0xdc00 - 0xd800 - 1); + /* TMP2 contains the high surrogate. */ + OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); + OP2(SLJIT_ADD, TMP2, 0, TMP2, 0, SLJIT_IMM, 0x40); + OP2(SLJIT_SHL, TMP2, 0, TMP2, 0, SLJIT_IMM, 10); + OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x3ff); + OP2(SLJIT_OR, TMP1, 0, TMP1, 0, TMP2, 0); + JUMPHERE(jump); + } +#endif +} + +#if defined SUPPORT_UTF && defined COMPILE_PCRE8 + +static BOOL is_char7_bitset(const pcre_uint8 *bitset, BOOL nclass) +{ +/* Tells whether the character codes below 128 are enough +to determine a match. */ +const pcre_uint8 value = nclass ? 0xff : 0; +const pcre_uint8* end = bitset + 32; + +bitset += 16; +do + { + if (*bitset++ != value) + return FALSE; + } +while (bitset < end); +return TRUE; +} + +static void read_char7_type(compiler_common *common, BOOL full_read) +{ +/* Reads the precise character type of a character into TMP1, if the character +is less than 128. Otherwise it returns with zero. Does not check STR_END. The +full_read argument tells whether characters above max are accepted or not. */ +DEFINE_COMPILER; +struct sljit_jump *jump; + +SLJIT_ASSERT(common->utf); + +OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), 0); +OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); + +OP1(SLJIT_MOV_UB, TMP1, 0, SLJIT_MEM1(TMP2), common->ctypes); + +if (full_read) + { + jump = CMP(SLJIT_C_LESS, TMP2, 0, SLJIT_IMM, 0xc0); + OP1(SLJIT_MOV_UB, TMP2, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(utf8_table4) - 0xc0); + OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP2, 0); + JUMPHERE(jump); + } +} + +#endif /* SUPPORT_UTF && COMPILE_PCRE8 */ + +static void read_char_range(compiler_common *common, pcre_uint32 min, pcre_uint32 max, BOOL update_str_ptr) +{ +/* Reads the precise value of a character into TMP1, if the character is +between min and max (c >= min && c <= max). Otherwise it returns with a value +outside the range. Does not check STR_END. */ +DEFINE_COMPILER; +#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 +struct sljit_jump *jump; +#endif +#if defined SUPPORT_UTF && defined COMPILE_PCRE8 +struct sljit_jump *jump2; +#endif + +SLJIT_UNUSED_ARG(update_str_ptr); +SLJIT_UNUSED_ARG(min); +SLJIT_UNUSED_ARG(max); +SLJIT_ASSERT(min <= max); + +OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); +OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); + +#if defined SUPPORT_UTF && defined COMPILE_PCRE8 +if (common->utf) + { + if (max < 128 && !update_str_ptr) return; + + jump = CMP(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, 0xc0); + if (min >= 0x10000) + { + OP2(SLJIT_SUB, TMP2, 0, TMP1, 0, SLJIT_IMM, 0xf0); + if (update_str_ptr) + OP1(SLJIT_MOV_UB, RETURN_ADDR, 0, SLJIT_MEM1(TMP1), (sljit_sw)PRIV(utf8_table4) - 0xc0); + OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); + jump2 = CMP(SLJIT_C_GREATER, TMP2, 0, SLJIT_IMM, 0x7); + OP2(SLJIT_SHL, TMP2, 0, TMP2, 0, SLJIT_IMM, 6); + OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x3f); + OP2(SLJIT_OR, TMP1, 0, TMP1, 0, TMP2, 0); + OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(1)); + OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 6); + OP2(SLJIT_AND, TMP2, 0, TMP2, 0, SLJIT_IMM, 0x3f); + OP2(SLJIT_OR, TMP1, 0, TMP1, 0, TMP2, 0); + OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(2)); + if (!update_str_ptr) + OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(3)); + OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 6); + OP2(SLJIT_AND, TMP2, 0, TMP2, 0, SLJIT_IMM, 0x3f); + OP2(SLJIT_OR, TMP1, 0, TMP1, 0, TMP2, 0); + JUMPHERE(jump2); + if (update_str_ptr) + OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, RETURN_ADDR, 0); + } + else if (min >= 0x800 && max <= 0xffff) + { + OP2(SLJIT_SUB, TMP2, 0, TMP1, 0, SLJIT_IMM, 0xe0); + if (update_str_ptr) + OP1(SLJIT_MOV_UB, RETURN_ADDR, 0, SLJIT_MEM1(TMP1), (sljit_sw)PRIV(utf8_table4) - 0xc0); + OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); + jump2 = CMP(SLJIT_C_GREATER, TMP2, 0, SLJIT_IMM, 0xf); + OP2(SLJIT_SHL, TMP2, 0, TMP2, 0, SLJIT_IMM, 6); + OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x3f); + OP2(SLJIT_OR, TMP1, 0, TMP1, 0, TMP2, 0); + OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(1)); + if (!update_str_ptr) + OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(2)); + OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 6); + OP2(SLJIT_AND, TMP2, 0, TMP2, 0, SLJIT_IMM, 0x3f); + OP2(SLJIT_OR, TMP1, 0, TMP1, 0, TMP2, 0); + JUMPHERE(jump2); + if (update_str_ptr) + OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, RETURN_ADDR, 0); + } + else if (max >= 0x800) + add_jump(compiler, (max < 0x10000) ? &common->utfreadchar16 : &common->utfreadchar, JUMP(SLJIT_FAST_CALL)); + else if (max < 128) + { + OP1(SLJIT_MOV_UB, TMP2, 0, SLJIT_MEM1(TMP1), (sljit_sw)PRIV(utf8_table4) - 0xc0); + OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP2, 0); + } + else + { + OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); + if (!update_str_ptr) + OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); + else + OP1(SLJIT_MOV_UB, RETURN_ADDR, 0, SLJIT_MEM1(TMP1), (sljit_sw)PRIV(utf8_table4) - 0xc0); + OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x3f); + OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 6); + OP2(SLJIT_AND, TMP2, 0, TMP2, 0, SLJIT_IMM, 0x3f); + OP2(SLJIT_OR, TMP1, 0, TMP1, 0, TMP2, 0); + if (update_str_ptr) + OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, RETURN_ADDR, 0); + } + JUMPHERE(jump); + } +#endif + +#if defined SUPPORT_UTF && defined COMPILE_PCRE16 +if (common->utf) + { + if (max >= 0x10000) + { + OP2(SLJIT_SUB, TMP2, 0, TMP1, 0, SLJIT_IMM, 0xd800); + jump = CMP(SLJIT_C_GREATER, TMP2, 0, SLJIT_IMM, 0xdc00 - 0xd800 - 1); + /* TMP2 contains the high surrogate. */ + OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); + OP2(SLJIT_ADD, TMP2, 0, TMP2, 0, SLJIT_IMM, 0x40); + OP2(SLJIT_SHL, TMP2, 0, TMP2, 0, SLJIT_IMM, 10); + OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); + OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x3ff); + OP2(SLJIT_OR, TMP1, 0, TMP1, 0, TMP2, 0); + JUMPHERE(jump); + return; + } + + if (max < 0xd800 && !update_str_ptr) return; + + /* Skip low surrogate if necessary. */ + OP2(SLJIT_SUB, TMP2, 0, TMP1, 0, SLJIT_IMM, 0xd800); + jump = CMP(SLJIT_C_GREATER, TMP2, 0, SLJIT_IMM, 0xdc00 - 0xd800 - 1); + if (update_str_ptr) + OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); + if (max >= 0xd800) + OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, 0x10000); + JUMPHERE(jump); + } +#endif +} + +static SLJIT_INLINE void read_char(compiler_common *common) +{ +read_char_range(common, 0, READ_CHAR_MAX, TRUE); +} + +static void read_char8_type(compiler_common *common, BOOL update_str_ptr) +{ +/* Reads the character type into TMP1, updates STR_PTR. Does not check STR_END. */ +DEFINE_COMPILER; +#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 +struct sljit_jump *jump; +#endif +#if defined SUPPORT_UTF && defined COMPILE_PCRE8 +struct sljit_jump *jump2; +#endif + +SLJIT_UNUSED_ARG(update_str_ptr); + +OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), 0); +OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); + +#if defined SUPPORT_UTF && defined COMPILE_PCRE8 +if (common->utf) + { + /* This can be an extra read in some situations, but hopefully + it is needed in most cases. */ + OP1(SLJIT_MOV_UB, TMP1, 0, SLJIT_MEM1(TMP2), common->ctypes); + jump = CMP(SLJIT_C_LESS, TMP2, 0, SLJIT_IMM, 0xc0); + if (!update_str_ptr) + { + OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); + OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); + OP2(SLJIT_AND, TMP2, 0, TMP2, 0, SLJIT_IMM, 0x3f); + OP2(SLJIT_SHL, TMP2, 0, TMP2, 0, SLJIT_IMM, 6); + OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x3f); + OP2(SLJIT_OR, TMP2, 0, TMP2, 0, TMP1, 0); + OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, 0); + jump2 = CMP(SLJIT_C_GREATER, TMP2, 0, SLJIT_IMM, 255); + OP1(SLJIT_MOV_UB, TMP1, 0, SLJIT_MEM1(TMP2), common->ctypes); + JUMPHERE(jump2); + } + else + add_jump(compiler, &common->utfreadtype8, JUMP(SLJIT_FAST_CALL)); + JUMPHERE(jump); + return; + } +#endif /* SUPPORT_UTF && COMPILE_PCRE8 */ + +#if !defined COMPILE_PCRE8 +/* The ctypes array contains only 256 values. */ +OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, 0); +jump = CMP(SLJIT_C_GREATER, TMP2, 0, SLJIT_IMM, 255); +#endif +OP1(SLJIT_MOV_UB, TMP1, 0, SLJIT_MEM1(TMP2), common->ctypes); +#if !defined COMPILE_PCRE8 +JUMPHERE(jump); +#endif + +#if defined SUPPORT_UTF && defined COMPILE_PCRE16 +if (common->utf && update_str_ptr) + { + /* Skip low surrogate if necessary. */ + OP2(SLJIT_SUB, TMP2, 0, TMP2, 0, SLJIT_IMM, 0xd800); + jump = CMP(SLJIT_C_GREATER, TMP2, 0, SLJIT_IMM, 0xdc00 - 0xd800 - 1); + OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); + JUMPHERE(jump); + } +#endif /* SUPPORT_UTF && COMPILE_PCRE16 */ +} + +static void skip_char_back(compiler_common *common) +{ +/* Goes one character back. Affects STR_PTR and TMP1. Does not check begin. */ +DEFINE_COMPILER; +#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 +#if defined COMPILE_PCRE8 +struct sljit_label *label; + +if (common->utf) + { + label = LABEL(); + OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), -IN_UCHARS(1)); + OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); + OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0xc0); + CMPTO(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, 0x80, label); + return; + } +#elif defined COMPILE_PCRE16 +if (common->utf) + { + OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), -IN_UCHARS(1)); + OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); + /* Skip low surrogate if necessary. */ + OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0xfc00); + OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0xdc00); + OP_FLAGS(SLJIT_MOV, TMP1, 0, SLJIT_UNUSED, 0, SLJIT_C_EQUAL); + OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 1); + OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, TMP1, 0); + return; + } +#endif /* COMPILE_PCRE[8|16] */ +#endif /* SUPPORT_UTF && !COMPILE_PCRE32 */ +OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); +} + +static void check_newlinechar(compiler_common *common, int nltype, jump_list **backtracks, BOOL jumpifmatch) +{ +/* Character comes in TMP1. Checks if it is a newline. TMP2 may be destroyed. */ +DEFINE_COMPILER; +struct sljit_jump *jump; + +if (nltype == NLTYPE_ANY) + { + add_jump(compiler, &common->anynewline, JUMP(SLJIT_FAST_CALL)); + add_jump(compiler, backtracks, JUMP(jumpifmatch ? SLJIT_C_NOT_ZERO : SLJIT_C_ZERO)); + } +else if (nltype == NLTYPE_ANYCRLF) + { + if (jumpifmatch) + { + add_jump(compiler, backtracks, CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, CHAR_CR)); + add_jump(compiler, backtracks, CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, CHAR_NL)); + } + else + { + jump = CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, CHAR_CR); + add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, CHAR_NL)); + JUMPHERE(jump); + } + } +else + { + SLJIT_ASSERT(nltype == NLTYPE_FIXED && common->newline < 256); + add_jump(compiler, backtracks, CMP(jumpifmatch ? SLJIT_C_EQUAL : SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, common->newline)); + } +} + +#ifdef SUPPORT_UTF + +#if defined COMPILE_PCRE8 +static void do_utfreadchar(compiler_common *common) +{ +/* Fast decoding a UTF-8 character. TMP1 contains the first byte +of the character (>= 0xc0). Return char value in TMP1, length in TMP2. */ +DEFINE_COMPILER; +struct sljit_jump *jump; + +sljit_emit_fast_enter(compiler, RETURN_ADDR, 0); +OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); +OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x3f); +OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 6); +OP2(SLJIT_AND, TMP2, 0, TMP2, 0, SLJIT_IMM, 0x3f); +OP2(SLJIT_OR, TMP1, 0, TMP1, 0, TMP2, 0); + +/* Searching for the first zero. */ +OP2(SLJIT_AND | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x800); +jump = JUMP(SLJIT_C_NOT_ZERO); +/* Two byte sequence. */ +OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); +OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, IN_UCHARS(2)); +sljit_emit_fast_return(compiler, RETURN_ADDR, 0); + +JUMPHERE(jump); +OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(1)); +OP2(SLJIT_XOR, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x800); +OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 6); +OP2(SLJIT_AND, TMP2, 0, TMP2, 0, SLJIT_IMM, 0x3f); +OP2(SLJIT_OR, TMP1, 0, TMP1, 0, TMP2, 0); + +OP2(SLJIT_AND | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x10000); +jump = JUMP(SLJIT_C_NOT_ZERO); +/* Three byte sequence. */ +OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(2)); +OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, IN_UCHARS(3)); +sljit_emit_fast_return(compiler, RETURN_ADDR, 0); + +/* Four byte sequence. */ +JUMPHERE(jump); +OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(2)); +OP2(SLJIT_XOR, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x10000); +OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 6); +OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(3)); +OP2(SLJIT_AND, TMP2, 0, TMP2, 0, SLJIT_IMM, 0x3f); +OP2(SLJIT_OR, TMP1, 0, TMP1, 0, TMP2, 0); +OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, IN_UCHARS(4)); +sljit_emit_fast_return(compiler, RETURN_ADDR, 0); +} + +static void do_utfreadchar16(compiler_common *common) +{ +/* Fast decoding a UTF-8 character. TMP1 contains the first byte +of the character (>= 0xc0). Return value in TMP1. */ +DEFINE_COMPILER; +struct sljit_jump *jump; + +sljit_emit_fast_enter(compiler, RETURN_ADDR, 0); +OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); +OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x3f); +OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 6); +OP2(SLJIT_AND, TMP2, 0, TMP2, 0, SLJIT_IMM, 0x3f); +OP2(SLJIT_OR, TMP1, 0, TMP1, 0, TMP2, 0); + +/* Searching for the first zero. */ +OP2(SLJIT_AND | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x800); +jump = JUMP(SLJIT_C_NOT_ZERO); +/* Two byte sequence. */ +OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); +sljit_emit_fast_return(compiler, RETURN_ADDR, 0); + +JUMPHERE(jump); +OP2(SLJIT_AND | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x400); +OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_UNUSED, 0, SLJIT_C_NOT_ZERO); +/* This code runs only in 8 bit mode. No need to shift the value. */ +OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP2, 0); +OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(1)); +OP2(SLJIT_XOR, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x800); +OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 6); +OP2(SLJIT_AND, TMP2, 0, TMP2, 0, SLJIT_IMM, 0x3f); +OP2(SLJIT_OR, TMP1, 0, TMP1, 0, TMP2, 0); +/* Three byte sequence. */ +OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(2)); +sljit_emit_fast_return(compiler, RETURN_ADDR, 0); +} + +static void do_utfreadtype8(compiler_common *common) +{ +/* Fast decoding a UTF-8 character type. TMP2 contains the first byte +of the character (>= 0xc0). Return value in TMP1. */ +DEFINE_COMPILER; +struct sljit_jump *jump; +struct sljit_jump *compare; + +sljit_emit_fast_enter(compiler, RETURN_ADDR, 0); + +OP2(SLJIT_AND | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP2, 0, SLJIT_IMM, 0x20); +jump = JUMP(SLJIT_C_NOT_ZERO); +/* Two byte sequence. */ +OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); +OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); +OP2(SLJIT_AND, TMP2, 0, TMP2, 0, SLJIT_IMM, 0x1f); +/* The upper 5 bits are known at this point. */ +compare = CMP(SLJIT_C_GREATER, TMP2, 0, SLJIT_IMM, 0x3); +OP2(SLJIT_SHL, TMP2, 0, TMP2, 0, SLJIT_IMM, 6); +OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x3f); +OP2(SLJIT_OR, TMP2, 0, TMP2, 0, TMP1, 0); +OP1(SLJIT_MOV_UB, TMP1, 0, SLJIT_MEM1(TMP2), common->ctypes); +sljit_emit_fast_return(compiler, RETURN_ADDR, 0); + +JUMPHERE(compare); +OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, 0); +sljit_emit_fast_return(compiler, RETURN_ADDR, 0); + +/* We only have types for characters less than 256. */ +JUMPHERE(jump); +OP1(SLJIT_MOV_UB, TMP2, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(utf8_table4) - 0xc0); +OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, 0); +OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP2, 0); +sljit_emit_fast_return(compiler, RETURN_ADDR, 0); +} + +#endif /* COMPILE_PCRE8 */ + +#endif /* SUPPORT_UTF */ + +#ifdef SUPPORT_UCP + +/* UCD_BLOCK_SIZE must be 128 (see the assert below). */ +#define UCD_BLOCK_MASK 127 +#define UCD_BLOCK_SHIFT 7 + +static void do_getucd(compiler_common *common) +{ +/* Search the UCD record for the character comes in TMP1. +Returns chartype in TMP1 and UCD offset in TMP2. */ +DEFINE_COMPILER; + +SLJIT_ASSERT(UCD_BLOCK_SIZE == 128 && sizeof(ucd_record) == 8); + +sljit_emit_fast_enter(compiler, RETURN_ADDR, 0); +OP2(SLJIT_LSHR, TMP2, 0, TMP1, 0, SLJIT_IMM, UCD_BLOCK_SHIFT); +OP1(SLJIT_MOV_UB, TMP2, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(ucd_stage1)); +OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, UCD_BLOCK_MASK); +OP2(SLJIT_SHL, TMP2, 0, TMP2, 0, SLJIT_IMM, UCD_BLOCK_SHIFT); +OP2(SLJIT_ADD, TMP1, 0, TMP1, 0, TMP2, 0); +OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, (sljit_sw)PRIV(ucd_stage2)); +OP1(SLJIT_MOV_UH, TMP2, 0, SLJIT_MEM2(TMP2, TMP1), 1); +OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, chartype)); +OP1(SLJIT_MOV_UB, TMP1, 0, SLJIT_MEM2(TMP1, TMP2), 3); +sljit_emit_fast_return(compiler, RETURN_ADDR, 0); +} +#endif + +static SLJIT_INLINE struct sljit_label *mainloop_entry(compiler_common *common, BOOL hascrorlf, BOOL firstline) +{ +DEFINE_COMPILER; +struct sljit_label *mainloop; +struct sljit_label *newlinelabel = NULL; +struct sljit_jump *start; +struct sljit_jump *end = NULL; +struct sljit_jump *nl = NULL; +#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 +struct sljit_jump *singlechar; +#endif +jump_list *newline = NULL; +BOOL newlinecheck = FALSE; +BOOL readuchar = FALSE; + +if (!(hascrorlf || firstline) && (common->nltype == NLTYPE_ANY || + common->nltype == NLTYPE_ANYCRLF || common->newline > 255)) + newlinecheck = TRUE; + +if (firstline) + { + /* Search for the end of the first line. */ + SLJIT_ASSERT(common->first_line_end != 0); + OP1(SLJIT_MOV, TMP3, 0, STR_PTR, 0); + + if (common->nltype == NLTYPE_FIXED && common->newline > 255) + { + mainloop = LABEL(); + OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); + end = CMP(SLJIT_C_GREATER_EQUAL, STR_PTR, 0, STR_END, 0); + OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(-1)); + OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); + CMPTO(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, (common->newline >> 8) & 0xff, mainloop); + CMPTO(SLJIT_C_NOT_EQUAL, TMP2, 0, SLJIT_IMM, common->newline & 0xff, mainloop); + JUMPHERE(end); + OP2(SLJIT_SUB, SLJIT_MEM1(SLJIT_SP), common->first_line_end, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); + } + else + { + end = CMP(SLJIT_C_GREATER_EQUAL, STR_PTR, 0, STR_END, 0); + mainloop = LABEL(); + /* Continual stores does not cause data dependency. */ + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->first_line_end, STR_PTR, 0); + read_char_range(common, common->nlmin, common->nlmax, TRUE); + check_newlinechar(common, common->nltype, &newline, TRUE); + CMPTO(SLJIT_C_LESS, STR_PTR, 0, STR_END, 0, mainloop); + JUMPHERE(end); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->first_line_end, STR_PTR, 0); + set_jumps(newline, LABEL()); + } + + OP1(SLJIT_MOV, STR_PTR, 0, TMP3, 0); + } + +start = JUMP(SLJIT_JUMP); + +if (newlinecheck) + { + newlinelabel = LABEL(); + OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); + end = CMP(SLJIT_C_GREATER_EQUAL, STR_PTR, 0, STR_END, 0); + OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), 0); + OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, common->newline & 0xff); + OP_FLAGS(SLJIT_MOV, TMP1, 0, SLJIT_UNUSED, 0, SLJIT_C_EQUAL); +#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 + OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, UCHAR_SHIFT); +#endif + OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP1, 0); + nl = JUMP(SLJIT_JUMP); + } + +mainloop = LABEL(); + +/* Increasing the STR_PTR here requires one less jump in the most common case. */ +#ifdef SUPPORT_UTF +if (common->utf) readuchar = TRUE; +#endif +if (newlinecheck) readuchar = TRUE; + +if (readuchar) + OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), 0); + +if (newlinecheck) + CMPTO(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, (common->newline >> 8) & 0xff, newlinelabel); + +OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); +#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 +#if defined COMPILE_PCRE8 +if (common->utf) + { + singlechar = CMP(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, 0xc0); + OP1(SLJIT_MOV_UB, TMP1, 0, SLJIT_MEM1(TMP1), (sljit_sw)PRIV(utf8_table4) - 0xc0); + OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP1, 0); + JUMPHERE(singlechar); + } +#elif defined COMPILE_PCRE16 +if (common->utf) + { + singlechar = CMP(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, 0xd800); + OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0xfc00); + OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0xd800); + OP_FLAGS(SLJIT_MOV, TMP1, 0, SLJIT_UNUSED, 0, SLJIT_C_EQUAL); + OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 1); + OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP1, 0); + JUMPHERE(singlechar); + } +#endif /* COMPILE_PCRE[8|16] */ +#endif /* SUPPORT_UTF && !COMPILE_PCRE32 */ +JUMPHERE(start); + +if (newlinecheck) + { + JUMPHERE(end); + JUMPHERE(nl); + } + +return mainloop; +} + +#define MAX_N_CHARS 16 +#define MAX_N_BYTES 8 + +static SLJIT_INLINE void add_prefix_byte(pcre_uint8 byte, pcre_uint8 *bytes) +{ +pcre_uint8 len = bytes[0]; +int i; + +if (len == 255) + return; + +if (len == 0) + { + bytes[0] = 1; + bytes[1] = byte; + return; + } + +for (i = len; i > 0; i--) + if (bytes[i] == byte) + return; + +if (len >= MAX_N_BYTES - 1) + { + bytes[0] = 255; + return; + } + +len++; +bytes[len] = byte; +bytes[0] = len; +} + +static int scan_prefix(compiler_common *common, pcre_uchar *cc, pcre_uint32 *chars, pcre_uint8 *bytes, int max_chars) +{ +/* Recursive function, which scans prefix literals. */ +BOOL last, any, caseless; +int len, repeat, len_save, consumed = 0; +pcre_uint32 chr, mask; +pcre_uchar *alternative, *cc_save, *oc; +#if defined SUPPORT_UTF && defined COMPILE_PCRE8 +pcre_uchar othercase[8]; +#elif defined SUPPORT_UTF && defined COMPILE_PCRE16 +pcre_uchar othercase[2]; +#else +pcre_uchar othercase[1]; +#endif + +repeat = 1; +while (TRUE) + { + last = TRUE; + any = FALSE; + caseless = FALSE; + switch (*cc) + { + case OP_CHARI: + caseless = TRUE; + case OP_CHAR: + last = FALSE; + cc++; + break; + + case OP_SOD: + case OP_SOM: + case OP_SET_SOM: + case OP_NOT_WORD_BOUNDARY: + case OP_WORD_BOUNDARY: + case OP_EODN: + case OP_EOD: + case OP_CIRC: + case OP_CIRCM: + case OP_DOLL: + case OP_DOLLM: + /* Zero width assertions. */ + cc++; + continue; + + case OP_ASSERT: + case OP_ASSERT_NOT: + case OP_ASSERTBACK: + case OP_ASSERTBACK_NOT: + cc = bracketend(cc); + continue; + + case OP_PLUSI: + case OP_MINPLUSI: + case OP_POSPLUSI: + caseless = TRUE; + case OP_PLUS: + case OP_MINPLUS: + case OP_POSPLUS: + cc++; + break; + + case OP_EXACTI: + caseless = TRUE; + case OP_EXACT: + repeat = GET2(cc, 1); + last = FALSE; + cc += 1 + IMM2_SIZE; + break; + + case OP_QUERYI: + case OP_MINQUERYI: + case OP_POSQUERYI: + caseless = TRUE; + case OP_QUERY: + case OP_MINQUERY: + case OP_POSQUERY: + len = 1; + cc++; +#ifdef SUPPORT_UTF + if (common->utf && HAS_EXTRALEN(*cc)) len += GET_EXTRALEN(*cc); +#endif + max_chars = scan_prefix(common, cc + len, chars, bytes, max_chars); + if (max_chars == 0) + return consumed; + last = FALSE; + break; + + case OP_KET: + cc += 1 + LINK_SIZE; + continue; + + case OP_ALT: + cc += GET(cc, 1); + continue; + + case OP_ONCE: + case OP_ONCE_NC: + case OP_BRA: + case OP_BRAPOS: + case OP_CBRA: + case OP_CBRAPOS: + alternative = cc + GET(cc, 1); + while (*alternative == OP_ALT) + { + max_chars = scan_prefix(common, alternative + 1 + LINK_SIZE, chars, bytes, max_chars); + if (max_chars == 0) + return consumed; + alternative += GET(alternative, 1); + } + + if (*cc == OP_CBRA || *cc == OP_CBRAPOS) + cc += IMM2_SIZE; + cc += 1 + LINK_SIZE; + continue; + + case OP_CLASS: +#if defined SUPPORT_UTF && defined COMPILE_PCRE8 + if (common->utf && !is_char7_bitset((const pcre_uint8 *)(cc + 1), FALSE)) return consumed; +#endif + any = TRUE; + cc += 1 + 32 / sizeof(pcre_uchar); + break; + + case OP_NCLASS: +#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 + if (common->utf) return consumed; +#endif + any = TRUE; + cc += 1 + 32 / sizeof(pcre_uchar); + break; + +#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 + case OP_XCLASS: +#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 + if (common->utf) return consumed; +#endif + any = TRUE; + cc += GET(cc, 1); + break; +#endif + + case OP_DIGIT: +#if defined SUPPORT_UTF && defined COMPILE_PCRE8 + if (common->utf && !is_char7_bitset((const pcre_uint8 *)common->ctypes - cbit_length + cbit_digit, FALSE)) + return consumed; +#endif + any = TRUE; + cc++; + break; + + case OP_WHITESPACE: +#if defined SUPPORT_UTF && defined COMPILE_PCRE8 + if (common->utf && !is_char7_bitset((const pcre_uint8 *)common->ctypes - cbit_length + cbit_space, FALSE)) + return consumed; +#endif + any = TRUE; + cc++; + break; + + case OP_WORDCHAR: +#if defined SUPPORT_UTF && defined COMPILE_PCRE8 + if (common->utf && !is_char7_bitset((const pcre_uint8 *)common->ctypes - cbit_length + cbit_word, FALSE)) + return consumed; +#endif + any = TRUE; + cc++; + break; + + case OP_NOT: + case OP_NOTI: + cc++; + /* Fall through. */ + case OP_NOT_DIGIT: + case OP_NOT_WHITESPACE: + case OP_NOT_WORDCHAR: + case OP_ANY: + case OP_ALLANY: +#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 + if (common->utf) return consumed; +#endif + any = TRUE; + cc++; + break; + +#ifdef SUPPORT_UCP + case OP_NOTPROP: + case OP_PROP: +#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 + if (common->utf) return consumed; +#endif + any = TRUE; + cc += 1 + 2; + break; +#endif + + case OP_TYPEEXACT: + repeat = GET2(cc, 1); + cc += 1 + IMM2_SIZE; + continue; + + case OP_NOTEXACT: + case OP_NOTEXACTI: +#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 + if (common->utf) return consumed; +#endif + any = TRUE; + repeat = GET2(cc, 1); + cc += 1 + IMM2_SIZE + 1; + break; + + default: + return consumed; + } + + if (any) + { +#if defined COMPILE_PCRE8 + mask = 0xff; +#elif defined COMPILE_PCRE16 + mask = 0xffff; +#elif defined COMPILE_PCRE32 + mask = 0xffffffff; +#else + SLJIT_ASSERT_STOP(); +#endif + + do + { + chars[0] = mask; + chars[1] = mask; + bytes[0] = 255; + + consumed++; + if (--max_chars == 0) + return consumed; + chars += 2; + bytes += MAX_N_BYTES; + } + while (--repeat > 0); + + repeat = 1; + continue; + } + + len = 1; +#ifdef SUPPORT_UTF + if (common->utf && HAS_EXTRALEN(*cc)) len += GET_EXTRALEN(*cc); +#endif + + if (caseless && char_has_othercase(common, cc)) + { +#ifdef SUPPORT_UTF + if (common->utf) + { + GETCHAR(chr, cc); + if ((int)PRIV(ord2utf)(char_othercase(common, chr), othercase) != len) + return consumed; + } + else +#endif + { + chr = *cc; + othercase[0] = TABLE_GET(chr, common->fcc, chr); + } + } + else + caseless = FALSE; + + len_save = len; + cc_save = cc; + while (TRUE) + { + oc = othercase; + do + { + chr = *cc; +#ifdef COMPILE_PCRE32 + if (SLJIT_UNLIKELY(chr == NOTACHAR)) + return consumed; +#endif + add_prefix_byte((pcre_uint8)chr, bytes); + + mask = 0; + if (caseless) + { + add_prefix_byte((pcre_uint8)*oc, bytes); + mask = *cc ^ *oc; + chr |= mask; + } + +#ifdef COMPILE_PCRE32 + if (chars[0] == NOTACHAR && chars[1] == 0) +#else + if (chars[0] == NOTACHAR) +#endif + { + chars[0] = chr; + chars[1] = mask; + } + else + { + mask |= chars[0] ^ chr; + chr |= mask; + chars[0] = chr; + chars[1] |= mask; + } + + len--; + consumed++; + if (--max_chars == 0) + return consumed; + chars += 2; + bytes += MAX_N_BYTES; + cc++; + oc++; + } + while (len > 0); + + if (--repeat == 0) + break; + + len = len_save; + cc = cc_save; + } + + repeat = 1; + if (last) + return consumed; + } +} + +static SLJIT_INLINE BOOL fast_forward_first_n_chars(compiler_common *common, BOOL firstline) +{ +DEFINE_COMPILER; +struct sljit_label *start; +struct sljit_jump *quit; +pcre_uint32 chars[MAX_N_CHARS * 2]; +pcre_uint8 bytes[MAX_N_CHARS * MAX_N_BYTES]; +pcre_uint8 ones[MAX_N_CHARS]; +int offsets[3]; +pcre_uint32 mask; +pcre_uint8 *byte_set, *byte_set_end; +int i, max, from; +int range_right = -1, range_len = 3 - 1; +sljit_ub *update_table = NULL; +BOOL in_range; + +/* This is even TRUE, if both are NULL. */ +SLJIT_ASSERT(common->read_only_data_ptr == common->read_only_data); + +for (i = 0; i < MAX_N_CHARS; i++) + { + chars[i << 1] = NOTACHAR; + chars[(i << 1) + 1] = 0; + bytes[i * MAX_N_BYTES] = 0; + } + +max = scan_prefix(common, common->start, chars, bytes, MAX_N_CHARS); + +if (max <= 1) + return FALSE; + +for (i = 0; i < max; i++) + { + mask = chars[(i << 1) + 1]; + ones[i] = ones_in_half_byte[mask & 0xf]; + mask >>= 4; + while (mask != 0) + { + ones[i] += ones_in_half_byte[mask & 0xf]; + mask >>= 4; + } + } + +in_range = FALSE; +from = 0; /* Prevent compiler "uninitialized" warning */ +for (i = 0; i <= max; i++) + { + if (in_range && (i - from) > range_len && (bytes[(i - 1) * MAX_N_BYTES] <= 4)) + { + range_len = i - from; + range_right = i - 1; + } + + if (i < max && bytes[i * MAX_N_BYTES] < 255) + { + if (!in_range) + { + in_range = TRUE; + from = i; + } + } + else if (in_range) + in_range = FALSE; + } + +if (range_right >= 0) + { + /* Since no data is consumed (see the assert in the beginning + of this function), this space can be reallocated. */ + if (common->read_only_data) + SLJIT_FREE(common->read_only_data); + + common->read_only_data_size += 256; + common->read_only_data = (sljit_uw *)SLJIT_MALLOC(common->read_only_data_size); + if (common->read_only_data == NULL) + return TRUE; + + update_table = (sljit_ub *)common->read_only_data; + common->read_only_data_ptr = (sljit_uw *)(update_table + 256); + memset(update_table, IN_UCHARS(range_len), 256); + + for (i = 0; i < range_len; i++) + { + byte_set = bytes + ((range_right - i) * MAX_N_BYTES); + SLJIT_ASSERT(byte_set[0] > 0 && byte_set[0] < 255); + byte_set_end = byte_set + byte_set[0]; + byte_set++; + while (byte_set <= byte_set_end) + { + if (update_table[*byte_set] > IN_UCHARS(i)) + update_table[*byte_set] = IN_UCHARS(i); + byte_set++; + } + } + } + +offsets[0] = -1; +/* Scan forward. */ +for (i = 0; i < max; i++) + if (ones[i] <= 2) { + offsets[0] = i; + break; + } + +if (offsets[0] < 0 && range_right < 0) + return FALSE; + +if (offsets[0] >= 0) + { + /* Scan backward. */ + offsets[1] = -1; + for (i = max - 1; i > offsets[0]; i--) + if (ones[i] <= 2 && i != range_right) + { + offsets[1] = i; + break; + } + + /* This case is handled better by fast_forward_first_char. */ + if (offsets[1] == -1 && offsets[0] == 0 && range_right < 0) + return FALSE; + + offsets[2] = -1; + /* We only search for a middle character if there is no range check. */ + if (offsets[1] >= 0 && range_right == -1) + { + /* Scan from middle. */ + for (i = (offsets[0] + offsets[1]) / 2 + 1; i < offsets[1]; i++) + if (ones[i] <= 2) + { + offsets[2] = i; + break; + } + + if (offsets[2] == -1) + { + for (i = (offsets[0] + offsets[1]) / 2; i > offsets[0]; i--) + if (ones[i] <= 2) + { + offsets[2] = i; + break; + } + } + } + + SLJIT_ASSERT(offsets[1] == -1 || (offsets[0] < offsets[1])); + SLJIT_ASSERT(offsets[2] == -1 || (offsets[0] < offsets[2] && offsets[1] > offsets[2])); + + chars[0] = chars[offsets[0] << 1]; + chars[1] = chars[(offsets[0] << 1) + 1]; + if (offsets[2] >= 0) + { + chars[2] = chars[offsets[2] << 1]; + chars[3] = chars[(offsets[2] << 1) + 1]; + } + if (offsets[1] >= 0) + { + chars[4] = chars[offsets[1] << 1]; + chars[5] = chars[(offsets[1] << 1) + 1]; + } + } + +max -= 1; +if (firstline) + { + SLJIT_ASSERT(common->first_line_end != 0); + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->first_line_end); + OP1(SLJIT_MOV, TMP3, 0, STR_END, 0); + OP2(SLJIT_SUB, STR_END, 0, STR_END, 0, SLJIT_IMM, IN_UCHARS(max)); + quit = CMP(SLJIT_C_LESS_EQUAL, STR_END, 0, TMP1, 0); + OP1(SLJIT_MOV, STR_END, 0, TMP1, 0); + JUMPHERE(quit); + } +else + OP2(SLJIT_SUB, STR_END, 0, STR_END, 0, SLJIT_IMM, IN_UCHARS(max)); + +#if !(defined SLJIT_CONFIG_X86_32 && SLJIT_CONFIG_X86_32) +if (range_right >= 0) + OP1(SLJIT_MOV, RETURN_ADDR, 0, SLJIT_IMM, (sljit_sw)update_table); +#endif + +start = LABEL(); +quit = CMP(SLJIT_C_GREATER_EQUAL, STR_PTR, 0, STR_END, 0); + +SLJIT_ASSERT(range_right >= 0 || offsets[0] >= 0); + +if (range_right >= 0) + { +#if defined COMPILE_PCRE8 || (defined SLJIT_LITTLE_ENDIAN && SLJIT_LITTLE_ENDIAN) + OP1(SLJIT_MOV_UB, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(range_right)); +#else + OP1(SLJIT_MOV_UB, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(range_right + 1) - 1); +#endif + +#if !(defined SLJIT_CONFIG_X86_32 && SLJIT_CONFIG_X86_32) + OP1(SLJIT_MOV_UB, TMP1, 0, SLJIT_MEM2(RETURN_ADDR, TMP1), 0); +#else + OP1(SLJIT_MOV_UB, TMP1, 0, SLJIT_MEM1(TMP1), (sljit_sw)update_table); +#endif + OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP1, 0); + CMPTO(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, 0, start); + } + +if (offsets[0] >= 0) + { + OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(offsets[0])); + if (offsets[1] >= 0) + OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(offsets[1])); + OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); + + if (chars[1] != 0) + OP2(SLJIT_OR, TMP1, 0, TMP1, 0, SLJIT_IMM, chars[1]); + CMPTO(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, chars[0], start); + if (offsets[2] >= 0) + OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(offsets[2] - 1)); + + if (offsets[1] >= 0) + { + if (chars[5] != 0) + OP2(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_IMM, chars[5]); + CMPTO(SLJIT_C_NOT_EQUAL, TMP2, 0, SLJIT_IMM, chars[4], start); + } + + if (offsets[2] >= 0) + { + if (chars[3] != 0) + OP2(SLJIT_OR, TMP1, 0, TMP1, 0, SLJIT_IMM, chars[3]); + CMPTO(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, chars[2], start); + } + OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); + } + +JUMPHERE(quit); + +if (firstline) + { + if (range_right >= 0) + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->first_line_end); + OP1(SLJIT_MOV, STR_END, 0, TMP3, 0); + if (range_right >= 0) + { + quit = CMP(SLJIT_C_LESS_EQUAL, STR_PTR, 0, TMP1, 0); + OP1(SLJIT_MOV, STR_PTR, 0, TMP1, 0); + JUMPHERE(quit); + } + } +else + OP2(SLJIT_ADD, STR_END, 0, STR_END, 0, SLJIT_IMM, IN_UCHARS(max)); +return TRUE; +} + +#undef MAX_N_CHARS +#undef MAX_N_BYTES + +static SLJIT_INLINE void fast_forward_first_char(compiler_common *common, pcre_uchar first_char, BOOL caseless, BOOL firstline) +{ +DEFINE_COMPILER; +struct sljit_label *start; +struct sljit_jump *quit; +struct sljit_jump *found; +pcre_uchar oc, bit; + +if (firstline) + { + SLJIT_ASSERT(common->first_line_end != 0); + OP1(SLJIT_MOV, TMP3, 0, STR_END, 0); + OP1(SLJIT_MOV, STR_END, 0, SLJIT_MEM1(SLJIT_SP), common->first_line_end); + } + +start = LABEL(); +quit = CMP(SLJIT_C_GREATER_EQUAL, STR_PTR, 0, STR_END, 0); +OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), 0); + +oc = first_char; +if (caseless) + { + oc = TABLE_GET(first_char, common->fcc, first_char); +#if defined SUPPORT_UCP && !(defined COMPILE_PCRE8) + if (first_char > 127 && common->utf) + oc = UCD_OTHERCASE(first_char); +#endif + } +if (first_char == oc) + found = CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, first_char); +else + { + bit = first_char ^ oc; + if (is_powerof2(bit)) + { + OP2(SLJIT_OR, TMP2, 0, TMP1, 0, SLJIT_IMM, bit); + found = CMP(SLJIT_C_EQUAL, TMP2, 0, SLJIT_IMM, first_char | bit); + } + else + { + OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, first_char); + OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_UNUSED, 0, SLJIT_C_EQUAL); + OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, oc); + OP_FLAGS(SLJIT_OR | SLJIT_SET_E, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); + found = JUMP(SLJIT_C_NOT_ZERO); + } + } + +OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); +JUMPTO(SLJIT_JUMP, start); +JUMPHERE(found); +JUMPHERE(quit); + +if (firstline) + OP1(SLJIT_MOV, STR_END, 0, TMP3, 0); +} + +static SLJIT_INLINE void fast_forward_newline(compiler_common *common, BOOL firstline) +{ +DEFINE_COMPILER; +struct sljit_label *loop; +struct sljit_jump *lastchar; +struct sljit_jump *firstchar; +struct sljit_jump *quit; +struct sljit_jump *foundcr = NULL; +struct sljit_jump *notfoundnl; +jump_list *newline = NULL; + +if (firstline) + { + SLJIT_ASSERT(common->first_line_end != 0); + OP1(SLJIT_MOV, TMP3, 0, STR_END, 0); + OP1(SLJIT_MOV, STR_END, 0, SLJIT_MEM1(SLJIT_SP), common->first_line_end); + } + +if (common->nltype == NLTYPE_FIXED && common->newline > 255) + { + lastchar = CMP(SLJIT_C_GREATER_EQUAL, STR_PTR, 0, STR_END, 0); + OP1(SLJIT_MOV, TMP1, 0, ARGUMENTS, 0); + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, str)); + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, begin)); + firstchar = CMP(SLJIT_C_LESS_EQUAL, STR_PTR, 0, TMP2, 0); + + OP2(SLJIT_ADD, TMP1, 0, TMP1, 0, SLJIT_IMM, IN_UCHARS(2)); + OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, STR_PTR, 0, TMP1, 0); + OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_UNUSED, 0, SLJIT_C_GREATER_EQUAL); +#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 + OP2(SLJIT_SHL, TMP2, 0, TMP2, 0, SLJIT_IMM, UCHAR_SHIFT); +#endif + OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, TMP2, 0); + + loop = LABEL(); + OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); + quit = CMP(SLJIT_C_GREATER_EQUAL, STR_PTR, 0, STR_END, 0); + OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(-2)); + OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(-1)); + CMPTO(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, (common->newline >> 8) & 0xff, loop); + CMPTO(SLJIT_C_NOT_EQUAL, TMP2, 0, SLJIT_IMM, common->newline & 0xff, loop); + + JUMPHERE(quit); + JUMPHERE(firstchar); + JUMPHERE(lastchar); + + if (firstline) + OP1(SLJIT_MOV, STR_END, 0, TMP3, 0); + return; + } + +OP1(SLJIT_MOV, TMP1, 0, ARGUMENTS, 0); +OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, str)); +firstchar = CMP(SLJIT_C_LESS_EQUAL, STR_PTR, 0, TMP2, 0); +skip_char_back(common); + +loop = LABEL(); +common->ff_newline_shortcut = loop; + +read_char_range(common, common->nlmin, common->nlmax, TRUE); +lastchar = CMP(SLJIT_C_GREATER_EQUAL, STR_PTR, 0, STR_END, 0); +if (common->nltype == NLTYPE_ANY || common->nltype == NLTYPE_ANYCRLF) + foundcr = CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, CHAR_CR); +check_newlinechar(common, common->nltype, &newline, FALSE); +set_jumps(newline, loop); + +if (common->nltype == NLTYPE_ANY || common->nltype == NLTYPE_ANYCRLF) + { + quit = JUMP(SLJIT_JUMP); + JUMPHERE(foundcr); + notfoundnl = CMP(SLJIT_C_GREATER_EQUAL, STR_PTR, 0, STR_END, 0); + OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), 0); + OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, CHAR_NL); + OP_FLAGS(SLJIT_MOV, TMP1, 0, SLJIT_UNUSED, 0, SLJIT_C_EQUAL); +#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 + OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, UCHAR_SHIFT); +#endif + OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP1, 0); + JUMPHERE(notfoundnl); + JUMPHERE(quit); + } +JUMPHERE(lastchar); +JUMPHERE(firstchar); + +if (firstline) + OP1(SLJIT_MOV, STR_END, 0, TMP3, 0); +} + +static BOOL check_class_ranges(compiler_common *common, const pcre_uint8 *bits, BOOL nclass, BOOL invert, jump_list **backtracks); + +static SLJIT_INLINE void fast_forward_start_bits(compiler_common *common, pcre_uint8 *start_bits, BOOL firstline) +{ +DEFINE_COMPILER; +struct sljit_label *start; +struct sljit_jump *quit; +struct sljit_jump *found = NULL; +jump_list *matches = NULL; +#ifndef COMPILE_PCRE8 +struct sljit_jump *jump; +#endif + +if (firstline) + { + SLJIT_ASSERT(common->first_line_end != 0); + OP1(SLJIT_MOV, RETURN_ADDR, 0, STR_END, 0); + OP1(SLJIT_MOV, STR_END, 0, SLJIT_MEM1(SLJIT_SP), common->first_line_end); + } + +start = LABEL(); +quit = CMP(SLJIT_C_GREATER_EQUAL, STR_PTR, 0, STR_END, 0); +OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), 0); +#ifdef SUPPORT_UTF +if (common->utf) + OP1(SLJIT_MOV, TMP3, 0, TMP1, 0); +#endif + +if (!check_class_ranges(common, start_bits, (start_bits[31] & 0x80) != 0, TRUE, &matches)) + { +#ifndef COMPILE_PCRE8 + jump = CMP(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, 255); + OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, 255); + JUMPHERE(jump); +#endif + OP2(SLJIT_AND, TMP2, 0, TMP1, 0, SLJIT_IMM, 0x7); + OP2(SLJIT_LSHR, TMP1, 0, TMP1, 0, SLJIT_IMM, 3); + OP1(SLJIT_MOV_UB, TMP1, 0, SLJIT_MEM1(TMP1), (sljit_sw)start_bits); + OP2(SLJIT_SHL, TMP2, 0, SLJIT_IMM, 1, TMP2, 0); + OP2(SLJIT_AND | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, TMP2, 0); + found = JUMP(SLJIT_C_NOT_ZERO); + } + +#ifdef SUPPORT_UTF +if (common->utf) + OP1(SLJIT_MOV, TMP1, 0, TMP3, 0); +#endif +OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); +#ifdef SUPPORT_UTF +#if defined COMPILE_PCRE8 +if (common->utf) + { + CMPTO(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, 0xc0, start); + OP1(SLJIT_MOV_UB, TMP1, 0, SLJIT_MEM1(TMP1), (sljit_sw)PRIV(utf8_table4) - 0xc0); + OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP1, 0); + } +#elif defined COMPILE_PCRE16 +if (common->utf) + { + CMPTO(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, 0xd800, start); + OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0xfc00); + OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0xd800); + OP_FLAGS(SLJIT_MOV, TMP1, 0, SLJIT_UNUSED, 0, SLJIT_C_EQUAL); + OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 1); + OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP1, 0); + } +#endif /* COMPILE_PCRE[8|16] */ +#endif /* SUPPORT_UTF */ +JUMPTO(SLJIT_JUMP, start); +if (found != NULL) + JUMPHERE(found); +if (matches != NULL) + set_jumps(matches, LABEL()); +JUMPHERE(quit); + +if (firstline) + OP1(SLJIT_MOV, STR_END, 0, RETURN_ADDR, 0); +} + +static SLJIT_INLINE struct sljit_jump *search_requested_char(compiler_common *common, pcre_uchar req_char, BOOL caseless, BOOL has_firstchar) +{ +DEFINE_COMPILER; +struct sljit_label *loop; +struct sljit_jump *toolong; +struct sljit_jump *alreadyfound; +struct sljit_jump *found; +struct sljit_jump *foundoc = NULL; +struct sljit_jump *notfound; +pcre_uint32 oc, bit; + +SLJIT_ASSERT(common->req_char_ptr != 0); +OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), common->req_char_ptr); +OP2(SLJIT_ADD, TMP1, 0, STR_PTR, 0, SLJIT_IMM, REQ_BYTE_MAX); +toolong = CMP(SLJIT_C_LESS, TMP1, 0, STR_END, 0); +alreadyfound = CMP(SLJIT_C_LESS, STR_PTR, 0, TMP2, 0); + +if (has_firstchar) + OP2(SLJIT_ADD, TMP1, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); +else + OP1(SLJIT_MOV, TMP1, 0, STR_PTR, 0); + +loop = LABEL(); +notfound = CMP(SLJIT_C_GREATER_EQUAL, TMP1, 0, STR_END, 0); + +OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(TMP1), 0); +oc = req_char; +if (caseless) + { + oc = TABLE_GET(req_char, common->fcc, req_char); +#if defined SUPPORT_UCP && !(defined COMPILE_PCRE8) + if (req_char > 127 && common->utf) + oc = UCD_OTHERCASE(req_char); +#endif + } +if (req_char == oc) + found = CMP(SLJIT_C_EQUAL, TMP2, 0, SLJIT_IMM, req_char); +else + { + bit = req_char ^ oc; + if (is_powerof2(bit)) + { + OP2(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_IMM, bit); + found = CMP(SLJIT_C_EQUAL, TMP2, 0, SLJIT_IMM, req_char | bit); + } + else + { + found = CMP(SLJIT_C_EQUAL, TMP2, 0, SLJIT_IMM, req_char); + foundoc = CMP(SLJIT_C_EQUAL, TMP2, 0, SLJIT_IMM, oc); + } + } +OP2(SLJIT_ADD, TMP1, 0, TMP1, 0, SLJIT_IMM, IN_UCHARS(1)); +JUMPTO(SLJIT_JUMP, loop); + +JUMPHERE(found); +if (foundoc) + JUMPHERE(foundoc); +OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->req_char_ptr, TMP1, 0); +JUMPHERE(alreadyfound); +JUMPHERE(toolong); +return notfound; +} + +static void do_revertframes(compiler_common *common) +{ +DEFINE_COMPILER; +struct sljit_jump *jump; +struct sljit_label *mainloop; + +sljit_emit_fast_enter(compiler, RETURN_ADDR, 0); +OP1(SLJIT_MOV, TMP1, 0, STACK_TOP, 0); +GET_LOCAL_BASE(TMP3, 0, 0); + +/* Drop frames until we reach STACK_TOP. */ +mainloop = LABEL(); +OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(TMP1), 0); +OP2(SLJIT_SUB | SLJIT_SET_S, SLJIT_UNUSED, 0, TMP2, 0, SLJIT_IMM, 0); +jump = JUMP(SLJIT_C_SIG_LESS_EQUAL); + +OP2(SLJIT_ADD, TMP2, 0, TMP2, 0, TMP3, 0); +OP1(SLJIT_MOV, SLJIT_MEM1(TMP2), 0, SLJIT_MEM1(TMP1), sizeof(sljit_sw)); +OP1(SLJIT_MOV, SLJIT_MEM1(TMP2), sizeof(sljit_sw), SLJIT_MEM1(TMP1), 2 * sizeof(sljit_sw)); +OP2(SLJIT_ADD, TMP1, 0, TMP1, 0, SLJIT_IMM, 3 * sizeof(sljit_sw)); +JUMPTO(SLJIT_JUMP, mainloop); + +JUMPHERE(jump); +jump = JUMP(SLJIT_C_SIG_LESS); +/* End of dropping frames. */ +sljit_emit_fast_return(compiler, RETURN_ADDR, 0); + +JUMPHERE(jump); +OP1(SLJIT_NEG, TMP2, 0, TMP2, 0); +OP2(SLJIT_ADD, TMP2, 0, TMP2, 0, TMP3, 0); +OP1(SLJIT_MOV, SLJIT_MEM1(TMP2), 0, SLJIT_MEM1(TMP1), sizeof(sljit_sw)); +OP2(SLJIT_ADD, TMP1, 0, TMP1, 0, SLJIT_IMM, 2 * sizeof(sljit_sw)); +JUMPTO(SLJIT_JUMP, mainloop); +} + +static void check_wordboundary(compiler_common *common) +{ +DEFINE_COMPILER; +struct sljit_jump *skipread; +jump_list *skipread_list = NULL; +#if !(defined COMPILE_PCRE8) || defined SUPPORT_UTF +struct sljit_jump *jump; +#endif + +SLJIT_COMPILE_ASSERT(ctype_word == 0x10, ctype_word_must_be_16); + +sljit_emit_fast_enter(compiler, SLJIT_MEM1(SLJIT_SP), LOCALS0); +/* Get type of the previous char, and put it to LOCALS1. */ +OP1(SLJIT_MOV, TMP1, 0, ARGUMENTS, 0); +OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, begin)); +OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS1, SLJIT_IMM, 0); +skipread = CMP(SLJIT_C_LESS_EQUAL, STR_PTR, 0, TMP1, 0); +skip_char_back(common); +check_start_used_ptr(common); +read_char(common); + +/* Testing char type. */ +#ifdef SUPPORT_UCP +if (common->use_ucp) + { + OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, 1); + jump = CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, CHAR_UNDERSCORE); + add_jump(compiler, &common->getucd, JUMP(SLJIT_FAST_CALL)); + OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, ucp_Ll); + OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, ucp_Lu - ucp_Ll); + OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_UNUSED, 0, SLJIT_C_LESS_EQUAL); + OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, ucp_Nd - ucp_Ll); + OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, ucp_No - ucp_Nd); + OP_FLAGS(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_C_LESS_EQUAL); + JUMPHERE(jump); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS1, TMP2, 0); + } +else +#endif + { +#ifndef COMPILE_PCRE8 + jump = CMP(SLJIT_C_GREATER, TMP1, 0, SLJIT_IMM, 255); +#elif defined SUPPORT_UTF + /* Here LOCALS1 has already been zeroed. */ + jump = NULL; + if (common->utf) + jump = CMP(SLJIT_C_GREATER, TMP1, 0, SLJIT_IMM, 255); +#endif /* COMPILE_PCRE8 */ + OP1(SLJIT_MOV_UB, TMP1, 0, SLJIT_MEM1(TMP1), common->ctypes); + OP2(SLJIT_LSHR, TMP1, 0, TMP1, 0, SLJIT_IMM, 4 /* ctype_word */); + OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 1); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS1, TMP1, 0); +#ifndef COMPILE_PCRE8 + JUMPHERE(jump); +#elif defined SUPPORT_UTF + if (jump != NULL) + JUMPHERE(jump); +#endif /* COMPILE_PCRE8 */ + } +JUMPHERE(skipread); + +OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, 0); +check_str_end(common, &skipread_list); +peek_char(common, READ_CHAR_MAX); + +/* Testing char type. This is a code duplication. */ +#ifdef SUPPORT_UCP +if (common->use_ucp) + { + OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, 1); + jump = CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, CHAR_UNDERSCORE); + add_jump(compiler, &common->getucd, JUMP(SLJIT_FAST_CALL)); + OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, ucp_Ll); + OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, ucp_Lu - ucp_Ll); + OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_UNUSED, 0, SLJIT_C_LESS_EQUAL); + OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, ucp_Nd - ucp_Ll); + OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, ucp_No - ucp_Nd); + OP_FLAGS(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_C_LESS_EQUAL); + JUMPHERE(jump); + } +else +#endif + { +#ifndef COMPILE_PCRE8 + /* TMP2 may be destroyed by peek_char. */ + OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, 0); + jump = CMP(SLJIT_C_GREATER, TMP1, 0, SLJIT_IMM, 255); +#elif defined SUPPORT_UTF + OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, 0); + jump = NULL; + if (common->utf) + jump = CMP(SLJIT_C_GREATER, TMP1, 0, SLJIT_IMM, 255); +#endif + OP1(SLJIT_MOV_UB, TMP2, 0, SLJIT_MEM1(TMP1), common->ctypes); + OP2(SLJIT_LSHR, TMP2, 0, TMP2, 0, SLJIT_IMM, 4 /* ctype_word */); + OP2(SLJIT_AND, TMP2, 0, TMP2, 0, SLJIT_IMM, 1); +#ifndef COMPILE_PCRE8 + JUMPHERE(jump); +#elif defined SUPPORT_UTF + if (jump != NULL) + JUMPHERE(jump); +#endif /* COMPILE_PCRE8 */ + } +set_jumps(skipread_list, LABEL()); + +OP2(SLJIT_XOR | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP2, 0, SLJIT_MEM1(SLJIT_SP), LOCALS1); +sljit_emit_fast_return(compiler, SLJIT_MEM1(SLJIT_SP), LOCALS0); +} + +static BOOL check_class_ranges(compiler_common *common, const pcre_uint8 *bits, BOOL nclass, BOOL invert, jump_list **backtracks) +{ +DEFINE_COMPILER; +int ranges[MAX_RANGE_SIZE]; +pcre_uint8 bit, cbit, all; +int i, byte, length = 0; + +bit = bits[0] & 0x1; +/* All bits will be zero or one (since bit is zero or one). */ +all = -bit; + +for (i = 0; i < 256; ) + { + byte = i >> 3; + if ((i & 0x7) == 0 && bits[byte] == all) + i += 8; + else + { + cbit = (bits[byte] >> (i & 0x7)) & 0x1; + if (cbit != bit) + { + if (length >= MAX_RANGE_SIZE) + return FALSE; + ranges[length] = i; + length++; + bit = cbit; + all = -cbit; + } + i++; + } + } + +if (((bit == 0) && nclass) || ((bit == 1) && !nclass)) + { + if (length >= MAX_RANGE_SIZE) + return FALSE; + ranges[length] = 256; + length++; + } + +if (length < 0 || length > 4) + return FALSE; + +bit = bits[0] & 0x1; +if (invert) bit ^= 0x1; + +/* No character is accepted. */ +if (length == 0 && bit == 0) + add_jump(compiler, backtracks, JUMP(SLJIT_JUMP)); + +switch(length) + { + case 0: + /* When bit != 0, all characters are accepted. */ + return TRUE; + + case 1: + add_jump(compiler, backtracks, CMP(bit == 0 ? SLJIT_C_LESS : SLJIT_C_GREATER_EQUAL, TMP1, 0, SLJIT_IMM, ranges[0])); + return TRUE; + + case 2: + if (ranges[0] + 1 != ranges[1]) + { + OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, ranges[0]); + add_jump(compiler, backtracks, CMP(bit != 0 ? SLJIT_C_LESS : SLJIT_C_GREATER_EQUAL, TMP1, 0, SLJIT_IMM, ranges[1] - ranges[0])); + } + else + add_jump(compiler, backtracks, CMP(bit != 0 ? SLJIT_C_EQUAL : SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, ranges[0])); + return TRUE; + + case 3: + if (bit != 0) + { + add_jump(compiler, backtracks, CMP(SLJIT_C_GREATER_EQUAL, TMP1, 0, SLJIT_IMM, ranges[2])); + if (ranges[0] + 1 != ranges[1]) + { + OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, ranges[0]); + add_jump(compiler, backtracks, CMP(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, ranges[1] - ranges[0])); + } + else + add_jump(compiler, backtracks, CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, ranges[0])); + return TRUE; + } + + add_jump(compiler, backtracks, CMP(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, ranges[0])); + if (ranges[1] + 1 != ranges[2]) + { + OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, ranges[1]); + add_jump(compiler, backtracks, CMP(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, ranges[2] - ranges[1])); + } + else + add_jump(compiler, backtracks, CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, ranges[1])); + return TRUE; + + case 4: + if ((ranges[1] - ranges[0]) == (ranges[3] - ranges[2]) + && (ranges[0] | (ranges[2] - ranges[0])) == ranges[2] + && is_powerof2(ranges[2] - ranges[0])) + { + OP2(SLJIT_OR, TMP1, 0, TMP1, 0, SLJIT_IMM, ranges[2] - ranges[0]); + if (ranges[2] + 1 != ranges[3]) + { + OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, ranges[2]); + add_jump(compiler, backtracks, CMP(bit != 0 ? SLJIT_C_LESS : SLJIT_C_GREATER_EQUAL, TMP1, 0, SLJIT_IMM, ranges[3] - ranges[2])); + } + else + add_jump(compiler, backtracks, CMP(bit != 0 ? SLJIT_C_EQUAL : SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, ranges[2])); + return TRUE; + } + + if (bit != 0) + { + i = 0; + if (ranges[0] + 1 != ranges[1]) + { + OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, ranges[0]); + add_jump(compiler, backtracks, CMP(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, ranges[1] - ranges[0])); + i = ranges[0]; + } + else + add_jump(compiler, backtracks, CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, ranges[0])); + + if (ranges[2] + 1 != ranges[3]) + { + OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, ranges[2] - i); + add_jump(compiler, backtracks, CMP(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, ranges[3] - ranges[2])); + } + else + add_jump(compiler, backtracks, CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, ranges[2] - i)); + return TRUE; + } + + OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, ranges[0]); + add_jump(compiler, backtracks, CMP(SLJIT_C_GREATER_EQUAL, TMP1, 0, SLJIT_IMM, ranges[3] - ranges[0])); + if (ranges[1] + 1 != ranges[2]) + { + OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, ranges[1] - ranges[0]); + add_jump(compiler, backtracks, CMP(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, ranges[2] - ranges[1])); + } + else + add_jump(compiler, backtracks, CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, ranges[1] - ranges[0])); + return TRUE; + + default: + SLJIT_ASSERT_STOP(); + return FALSE; + } +} + +static void check_anynewline(compiler_common *common) +{ +/* Check whether TMP1 contains a newline character. TMP2 destroyed. */ +DEFINE_COMPILER; + +sljit_emit_fast_enter(compiler, RETURN_ADDR, 0); + +OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x0a); +OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x0d - 0x0a); +OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_UNUSED, 0, SLJIT_C_LESS_EQUAL); +OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x85 - 0x0a); +#if defined SUPPORT_UTF || defined COMPILE_PCRE16 || defined COMPILE_PCRE32 +#ifdef COMPILE_PCRE8 +if (common->utf) + { +#endif + OP_FLAGS(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); + OP2(SLJIT_OR, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x1); + OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x2029 - 0x0a); +#ifdef COMPILE_PCRE8 + } +#endif +#endif /* SUPPORT_UTF || COMPILE_PCRE16 || COMPILE_PCRE32 */ +OP_FLAGS(SLJIT_OR | SLJIT_SET_E, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); +sljit_emit_fast_return(compiler, RETURN_ADDR, 0); +} + +static void check_hspace(compiler_common *common) +{ +/* Check whether TMP1 contains a newline character. TMP2 destroyed. */ +DEFINE_COMPILER; + +sljit_emit_fast_enter(compiler, RETURN_ADDR, 0); + +OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x09); +OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_UNUSED, 0, SLJIT_C_EQUAL); +OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x20); +OP_FLAGS(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); +OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0xa0); +#if defined SUPPORT_UTF || defined COMPILE_PCRE16 || defined COMPILE_PCRE32 +#ifdef COMPILE_PCRE8 +if (common->utf) + { +#endif + OP_FLAGS(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); + OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x1680); + OP_FLAGS(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); + OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x180e); + OP_FLAGS(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); + OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x2000); + OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x200A - 0x2000); + OP_FLAGS(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_C_LESS_EQUAL); + OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x202f - 0x2000); + OP_FLAGS(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); + OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x205f - 0x2000); + OP_FLAGS(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); + OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x3000 - 0x2000); +#ifdef COMPILE_PCRE8 + } +#endif +#endif /* SUPPORT_UTF || COMPILE_PCRE16 || COMPILE_PCRE32 */ +OP_FLAGS(SLJIT_OR | SLJIT_SET_E, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); + +sljit_emit_fast_return(compiler, RETURN_ADDR, 0); +} + +static void check_vspace(compiler_common *common) +{ +/* Check whether TMP1 contains a newline character. TMP2 destroyed. */ +DEFINE_COMPILER; + +sljit_emit_fast_enter(compiler, RETURN_ADDR, 0); + +OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x0a); +OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x0d - 0x0a); +OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_UNUSED, 0, SLJIT_C_LESS_EQUAL); +OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x85 - 0x0a); +#if defined SUPPORT_UTF || defined COMPILE_PCRE16 || defined COMPILE_PCRE32 +#ifdef COMPILE_PCRE8 +if (common->utf) + { +#endif + OP_FLAGS(SLJIT_OR | SLJIT_SET_E, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); + OP2(SLJIT_OR, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x1); + OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x2029 - 0x0a); +#ifdef COMPILE_PCRE8 + } +#endif +#endif /* SUPPORT_UTF || COMPILE_PCRE16 || COMPILE_PCRE32 */ +OP_FLAGS(SLJIT_OR | SLJIT_SET_E, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); + +sljit_emit_fast_return(compiler, RETURN_ADDR, 0); +} + +#define CHAR1 STR_END +#define CHAR2 STACK_TOP + +static void do_casefulcmp(compiler_common *common) +{ +DEFINE_COMPILER; +struct sljit_jump *jump; +struct sljit_label *label; + +sljit_emit_fast_enter(compiler, RETURN_ADDR, 0); +OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, TMP2, 0); +OP1(SLJIT_MOV, TMP3, 0, CHAR1, 0); +OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS0, CHAR2, 0); +OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, IN_UCHARS(1)); +OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); + +label = LABEL(); +OP1(MOVU_UCHAR, CHAR1, 0, SLJIT_MEM1(TMP1), IN_UCHARS(1)); +OP1(MOVU_UCHAR, CHAR2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(1)); +jump = CMP(SLJIT_C_NOT_EQUAL, CHAR1, 0, CHAR2, 0); +OP2(SLJIT_SUB | SLJIT_SET_E, TMP2, 0, TMP2, 0, SLJIT_IMM, IN_UCHARS(1)); +JUMPTO(SLJIT_C_NOT_ZERO, label); + +JUMPHERE(jump); +OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); +OP1(SLJIT_MOV, CHAR1, 0, TMP3, 0); +OP1(SLJIT_MOV, CHAR2, 0, SLJIT_MEM1(SLJIT_SP), LOCALS0); +sljit_emit_fast_return(compiler, RETURN_ADDR, 0); +} + +#define LCC_TABLE STACK_LIMIT + +static void do_caselesscmp(compiler_common *common) +{ +DEFINE_COMPILER; +struct sljit_jump *jump; +struct sljit_label *label; + +sljit_emit_fast_enter(compiler, RETURN_ADDR, 0); +OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, TMP2, 0); + +OP1(SLJIT_MOV, TMP3, 0, LCC_TABLE, 0); +OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS0, CHAR1, 0); +OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS1, CHAR2, 0); +OP1(SLJIT_MOV, LCC_TABLE, 0, SLJIT_IMM, common->lcc); +OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, IN_UCHARS(1)); +OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); + +label = LABEL(); +OP1(MOVU_UCHAR, CHAR1, 0, SLJIT_MEM1(TMP1), IN_UCHARS(1)); +OP1(MOVU_UCHAR, CHAR2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(1)); +#ifndef COMPILE_PCRE8 +jump = CMP(SLJIT_C_GREATER, CHAR1, 0, SLJIT_IMM, 255); +#endif +OP1(SLJIT_MOV_UB, CHAR1, 0, SLJIT_MEM2(LCC_TABLE, CHAR1), 0); +#ifndef COMPILE_PCRE8 +JUMPHERE(jump); +jump = CMP(SLJIT_C_GREATER, CHAR2, 0, SLJIT_IMM, 255); +#endif +OP1(SLJIT_MOV_UB, CHAR2, 0, SLJIT_MEM2(LCC_TABLE, CHAR2), 0); +#ifndef COMPILE_PCRE8 +JUMPHERE(jump); +#endif +jump = CMP(SLJIT_C_NOT_EQUAL, CHAR1, 0, CHAR2, 0); +OP2(SLJIT_SUB | SLJIT_SET_E, TMP2, 0, TMP2, 0, SLJIT_IMM, IN_UCHARS(1)); +JUMPTO(SLJIT_C_NOT_ZERO, label); + +JUMPHERE(jump); +OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); +OP1(SLJIT_MOV, LCC_TABLE, 0, TMP3, 0); +OP1(SLJIT_MOV, CHAR1, 0, SLJIT_MEM1(SLJIT_SP), LOCALS0); +OP1(SLJIT_MOV, CHAR2, 0, SLJIT_MEM1(SLJIT_SP), LOCALS1); +sljit_emit_fast_return(compiler, RETURN_ADDR, 0); +} + +#undef LCC_TABLE +#undef CHAR1 +#undef CHAR2 + +#if defined SUPPORT_UTF && defined SUPPORT_UCP + +static const pcre_uchar * SLJIT_CALL do_utf_caselesscmp(pcre_uchar *src1, jit_arguments *args, pcre_uchar *end1) +{ +/* This function would be ineffective to do in JIT level. */ +pcre_uint32 c1, c2; +const pcre_uchar *src2 = args->uchar_ptr; +const pcre_uchar *end2 = args->end; +const ucd_record *ur; +const pcre_uint32 *pp; + +while (src1 < end1) + { + if (src2 >= end2) + return (pcre_uchar*)1; + GETCHARINC(c1, src1); + GETCHARINC(c2, src2); + ur = GET_UCD(c2); + if (c1 != c2 && c1 != c2 + ur->other_case) + { + pp = PRIV(ucd_caseless_sets) + ur->caseset; + for (;;) + { + if (c1 < *pp) return NULL; + if (c1 == *pp++) break; + } + } + } +return src2; +} + +#endif /* SUPPORT_UTF && SUPPORT_UCP */ + +static pcre_uchar *byte_sequence_compare(compiler_common *common, BOOL caseless, pcre_uchar *cc, + compare_context* context, jump_list **backtracks) +{ +DEFINE_COMPILER; +unsigned int othercasebit = 0; +pcre_uchar *othercasechar = NULL; +#ifdef SUPPORT_UTF +int utflength; +#endif + +if (caseless && char_has_othercase(common, cc)) + { + othercasebit = char_get_othercase_bit(common, cc); + SLJIT_ASSERT(othercasebit); + /* Extracting bit difference info. */ +#if defined COMPILE_PCRE8 + othercasechar = cc + (othercasebit >> 8); + othercasebit &= 0xff; +#elif defined COMPILE_PCRE16 || defined COMPILE_PCRE32 + /* Note that this code only handles characters in the BMP. If there + ever are characters outside the BMP whose othercase differs in only one + bit from itself (there currently are none), this code will need to be + revised for COMPILE_PCRE32. */ + othercasechar = cc + (othercasebit >> 9); + if ((othercasebit & 0x100) != 0) + othercasebit = (othercasebit & 0xff) << 8; + else + othercasebit &= 0xff; +#endif /* COMPILE_PCRE[8|16|32] */ + } + +if (context->sourcereg == -1) + { +#if defined COMPILE_PCRE8 +#if defined SLJIT_UNALIGNED && SLJIT_UNALIGNED + if (context->length >= 4) + OP1(SLJIT_MOV_SI, TMP1, 0, SLJIT_MEM1(STR_PTR), -context->length); + else if (context->length >= 2) + OP1(SLJIT_MOV_UH, TMP1, 0, SLJIT_MEM1(STR_PTR), -context->length); + else +#endif + OP1(SLJIT_MOV_UB, TMP1, 0, SLJIT_MEM1(STR_PTR), -context->length); +#elif defined COMPILE_PCRE16 +#if defined SLJIT_UNALIGNED && SLJIT_UNALIGNED + if (context->length >= 4) + OP1(SLJIT_MOV_SI, TMP1, 0, SLJIT_MEM1(STR_PTR), -context->length); + else +#endif + OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), -context->length); +#elif defined COMPILE_PCRE32 + OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), -context->length); +#endif /* COMPILE_PCRE[8|16|32] */ + context->sourcereg = TMP2; + } + +#ifdef SUPPORT_UTF +utflength = 1; +if (common->utf && HAS_EXTRALEN(*cc)) + utflength += GET_EXTRALEN(*cc); + +do + { +#endif + + context->length -= IN_UCHARS(1); +#if (defined SLJIT_UNALIGNED && SLJIT_UNALIGNED) && (defined COMPILE_PCRE8 || defined COMPILE_PCRE16) + + /* Unaligned read is supported. */ + if (othercasebit != 0 && othercasechar == cc) + { + context->c.asuchars[context->ucharptr] = *cc | othercasebit; + context->oc.asuchars[context->ucharptr] = othercasebit; + } + else + { + context->c.asuchars[context->ucharptr] = *cc; + context->oc.asuchars[context->ucharptr] = 0; + } + context->ucharptr++; + +#if defined COMPILE_PCRE8 + if (context->ucharptr >= 4 || context->length == 0 || (context->ucharptr == 2 && context->length == 1)) +#else + if (context->ucharptr >= 2 || context->length == 0) +#endif + { + if (context->length >= 4) + OP1(SLJIT_MOV_SI, context->sourcereg, 0, SLJIT_MEM1(STR_PTR), -context->length); + else if (context->length >= 2) + OP1(SLJIT_MOV_UH, context->sourcereg, 0, SLJIT_MEM1(STR_PTR), -context->length); +#if defined COMPILE_PCRE8 + else if (context->length >= 1) + OP1(SLJIT_MOV_UB, context->sourcereg, 0, SLJIT_MEM1(STR_PTR), -context->length); +#endif /* COMPILE_PCRE8 */ + context->sourcereg = context->sourcereg == TMP1 ? TMP2 : TMP1; + + switch(context->ucharptr) + { + case 4 / sizeof(pcre_uchar): + if (context->oc.asint != 0) + OP2(SLJIT_OR, context->sourcereg, 0, context->sourcereg, 0, SLJIT_IMM, context->oc.asint); + add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, context->sourcereg, 0, SLJIT_IMM, context->c.asint | context->oc.asint)); + break; + + case 2 / sizeof(pcre_uchar): + if (context->oc.asushort != 0) + OP2(SLJIT_OR, context->sourcereg, 0, context->sourcereg, 0, SLJIT_IMM, context->oc.asushort); + add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, context->sourcereg, 0, SLJIT_IMM, context->c.asushort | context->oc.asushort)); + break; + +#ifdef COMPILE_PCRE8 + case 1: + if (context->oc.asbyte != 0) + OP2(SLJIT_OR, context->sourcereg, 0, context->sourcereg, 0, SLJIT_IMM, context->oc.asbyte); + add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, context->sourcereg, 0, SLJIT_IMM, context->c.asbyte | context->oc.asbyte)); + break; +#endif + + default: + SLJIT_ASSERT_STOP(); + break; + } + context->ucharptr = 0; + } + +#else + + /* Unaligned read is unsupported or in 32 bit mode. */ + if (context->length >= 1) + OP1(MOV_UCHAR, context->sourcereg, 0, SLJIT_MEM1(STR_PTR), -context->length); + + context->sourcereg = context->sourcereg == TMP1 ? TMP2 : TMP1; + + if (othercasebit != 0 && othercasechar == cc) + { + OP2(SLJIT_OR, context->sourcereg, 0, context->sourcereg, 0, SLJIT_IMM, othercasebit); + add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, context->sourcereg, 0, SLJIT_IMM, *cc | othercasebit)); + } + else + add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, context->sourcereg, 0, SLJIT_IMM, *cc)); + +#endif + + cc++; +#ifdef SUPPORT_UTF + utflength--; + } +while (utflength > 0); +#endif + +return cc; +} + +#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 + +#define SET_TYPE_OFFSET(value) \ + if ((value) != typeoffset) \ + { \ + if ((value) < typeoffset) \ + OP2(SLJIT_ADD, typereg, 0, typereg, 0, SLJIT_IMM, typeoffset - (value)); \ + else \ + OP2(SLJIT_SUB, typereg, 0, typereg, 0, SLJIT_IMM, (value) - typeoffset); \ + } \ + typeoffset = (value); + +#define SET_CHAR_OFFSET(value) \ + if ((value) != charoffset) \ + { \ + if ((value) < charoffset) \ + OP2(SLJIT_ADD, TMP1, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)(charoffset - (value))); \ + else \ + OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)((value) - charoffset)); \ + } \ + charoffset = (value); + +static void compile_xclass_matchingpath(compiler_common *common, pcre_uchar *cc, jump_list **backtracks) +{ +DEFINE_COMPILER; +jump_list *found = NULL; +jump_list **list = (cc[0] & XCL_NOT) == 0 ? &found : backtracks; +sljit_uw c, charoffset, max = 256, min = READ_CHAR_MAX; +struct sljit_jump *jump = NULL; +pcre_uchar *ccbegin; +int compares, invertcmp, numberofcmps; +#if defined SUPPORT_UTF && (defined COMPILE_PCRE8 || defined COMPILE_PCRE16) +BOOL utf = common->utf; +#endif + +#ifdef SUPPORT_UCP +BOOL needstype = FALSE, needsscript = FALSE, needschar = FALSE; +BOOL charsaved = FALSE; +int typereg = TMP1, scriptreg = TMP1; +const pcre_uint32 *other_cases; +sljit_uw typeoffset; +#endif + +/* Scanning the necessary info. */ +cc++; +ccbegin = cc; +compares = 0; +if (cc[-1] & XCL_MAP) + { + min = 0; + cc += 32 / sizeof(pcre_uchar); + } + +while (*cc != XCL_END) + { + compares++; + if (*cc == XCL_SINGLE) + { + cc ++; + GETCHARINCTEST(c, cc); + if (c > max) max = c; + if (c < min) min = c; +#ifdef SUPPORT_UCP + needschar = TRUE; +#endif + } + else if (*cc == XCL_RANGE) + { + cc ++; + GETCHARINCTEST(c, cc); + if (c < min) min = c; + GETCHARINCTEST(c, cc); + if (c > max) max = c; +#ifdef SUPPORT_UCP + needschar = TRUE; +#endif + } +#ifdef SUPPORT_UCP + else + { + SLJIT_ASSERT(*cc == XCL_PROP || *cc == XCL_NOTPROP); + cc++; + if (*cc == PT_CLIST) + { + other_cases = PRIV(ucd_caseless_sets) + cc[1]; + while (*other_cases != NOTACHAR) + { + if (*other_cases > max) max = *other_cases; + if (*other_cases < min) min = *other_cases; + other_cases++; + } + } + else + { + max = READ_CHAR_MAX; + min = 0; + } + + switch(*cc) + { + case PT_ANY: + break; + + case PT_LAMP: + case PT_GC: + case PT_PC: + case PT_ALNUM: + needstype = TRUE; + break; + + case PT_SC: + needsscript = TRUE; + break; + + case PT_SPACE: + case PT_PXSPACE: + case PT_WORD: + case PT_PXGRAPH: + case PT_PXPRINT: + case PT_PXPUNCT: + needstype = TRUE; + needschar = TRUE; + break; + + case PT_CLIST: + case PT_UCNC: + needschar = TRUE; + break; + + default: + SLJIT_ASSERT_STOP(); + break; + } + cc += 2; + } +#endif + } + +/* We are not necessary in utf mode even in 8 bit mode. */ +cc = ccbegin; +detect_partial_match(common, backtracks); +read_char_range(common, min, max, (cc[-1] & XCL_NOT) != 0); + +if ((cc[-1] & XCL_HASPROP) == 0) + { + if ((cc[-1] & XCL_MAP) != 0) + { + jump = CMP(SLJIT_C_GREATER, TMP1, 0, SLJIT_IMM, 255); + if (!check_class_ranges(common, (const pcre_uint8 *)cc, (((const pcre_uint8 *)cc)[31] & 0x80) != 0, TRUE, &found)) + { + OP2(SLJIT_AND, TMP2, 0, TMP1, 0, SLJIT_IMM, 0x7); + OP2(SLJIT_LSHR, TMP1, 0, TMP1, 0, SLJIT_IMM, 3); + OP1(SLJIT_MOV_UB, TMP1, 0, SLJIT_MEM1(TMP1), (sljit_sw)cc); + OP2(SLJIT_SHL, TMP2, 0, SLJIT_IMM, 1, TMP2, 0); + OP2(SLJIT_AND | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, TMP2, 0); + add_jump(compiler, &found, JUMP(SLJIT_C_NOT_ZERO)); + } + + add_jump(compiler, backtracks, JUMP(SLJIT_JUMP)); + JUMPHERE(jump); + + cc += 32 / sizeof(pcre_uchar); + } + else + { + OP2(SLJIT_SUB, TMP2, 0, TMP1, 0, SLJIT_IMM, min); + add_jump(compiler, (cc[-1] & XCL_NOT) == 0 ? backtracks : &found, CMP(SLJIT_C_GREATER, TMP2, 0, SLJIT_IMM, max - min)); + } + } +else if ((cc[-1] & XCL_MAP) != 0) + { + OP1(SLJIT_MOV, TMP3, 0, TMP1, 0); +#ifdef SUPPORT_UCP + charsaved = TRUE; +#endif + if (!check_class_ranges(common, (const pcre_uint8 *)cc, FALSE, TRUE, list)) + { +#ifdef COMPILE_PCRE8 + SLJIT_ASSERT(common->utf); +#endif + jump = CMP(SLJIT_C_GREATER, TMP1, 0, SLJIT_IMM, 255); + + OP2(SLJIT_AND, TMP2, 0, TMP1, 0, SLJIT_IMM, 0x7); + OP2(SLJIT_LSHR, TMP1, 0, TMP1, 0, SLJIT_IMM, 3); + OP1(SLJIT_MOV_UB, TMP1, 0, SLJIT_MEM1(TMP1), (sljit_sw)cc); + OP2(SLJIT_SHL, TMP2, 0, SLJIT_IMM, 1, TMP2, 0); + OP2(SLJIT_AND | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, TMP2, 0); + add_jump(compiler, list, JUMP(SLJIT_C_NOT_ZERO)); + + JUMPHERE(jump); + } + + OP1(SLJIT_MOV, TMP1, 0, TMP3, 0); + cc += 32 / sizeof(pcre_uchar); + } + +#ifdef SUPPORT_UCP +/* Simple register allocation. TMP1 is preferred if possible. */ +if (needstype || needsscript) + { + if (needschar && !charsaved) + OP1(SLJIT_MOV, TMP3, 0, TMP1, 0); + add_jump(compiler, &common->getucd, JUMP(SLJIT_FAST_CALL)); + if (needschar) + { + if (needstype) + { + OP1(SLJIT_MOV, RETURN_ADDR, 0, TMP1, 0); + typereg = RETURN_ADDR; + } + + if (needsscript) + scriptreg = TMP3; + OP1(SLJIT_MOV, TMP1, 0, TMP3, 0); + } + else if (needstype && needsscript) + scriptreg = TMP3; + /* In all other cases only one of them was specified, and that can goes to TMP1. */ + + if (needsscript) + { + if (scriptreg == TMP1) + { + OP1(SLJIT_MOV, scriptreg, 0, SLJIT_IMM, (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, script)); + OP1(SLJIT_MOV_UB, scriptreg, 0, SLJIT_MEM2(scriptreg, TMP2), 3); + } + else + { + OP2(SLJIT_SHL, TMP2, 0, TMP2, 0, SLJIT_IMM, 3); + OP2(SLJIT_ADD, TMP2, 0, TMP2, 0, SLJIT_IMM, (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, script)); + OP1(SLJIT_MOV_UB, scriptreg, 0, SLJIT_MEM1(TMP2), 0); + } + } + } +#endif + +/* Generating code. */ +charoffset = 0; +numberofcmps = 0; +#ifdef SUPPORT_UCP +typeoffset = 0; +#endif + +while (*cc != XCL_END) + { + compares--; + invertcmp = (compares == 0 && list != backtracks); + jump = NULL; + + if (*cc == XCL_SINGLE) + { + cc ++; + GETCHARINCTEST(c, cc); + + if (numberofcmps < 3 && (*cc == XCL_SINGLE || *cc == XCL_RANGE)) + { + OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset)); + OP_FLAGS(numberofcmps == 0 ? SLJIT_MOV : SLJIT_OR, TMP2, 0, numberofcmps == 0 ? SLJIT_UNUSED : TMP2, 0, SLJIT_C_EQUAL); + numberofcmps++; + } + else if (numberofcmps > 0) + { + OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset)); + OP_FLAGS(SLJIT_OR | SLJIT_SET_E, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); + jump = JUMP(SLJIT_C_NOT_ZERO ^ invertcmp); + numberofcmps = 0; + } + else + { + jump = CMP(SLJIT_C_EQUAL ^ invertcmp, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset)); + numberofcmps = 0; + } + } + else if (*cc == XCL_RANGE) + { + cc ++; + GETCHARINCTEST(c, cc); + SET_CHAR_OFFSET(c); + GETCHARINCTEST(c, cc); + + if (numberofcmps < 3 && (*cc == XCL_SINGLE || *cc == XCL_RANGE)) + { + OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset)); + OP_FLAGS(numberofcmps == 0 ? SLJIT_MOV : SLJIT_OR, TMP2, 0, numberofcmps == 0 ? SLJIT_UNUSED : TMP2, 0, SLJIT_C_LESS_EQUAL); + numberofcmps++; + } + else if (numberofcmps > 0) + { + OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset)); + OP_FLAGS(SLJIT_OR | SLJIT_SET_E, TMP2, 0, TMP2, 0, SLJIT_C_LESS_EQUAL); + jump = JUMP(SLJIT_C_NOT_ZERO ^ invertcmp); + numberofcmps = 0; + } + else + { + jump = CMP(SLJIT_C_LESS_EQUAL ^ invertcmp, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset)); + numberofcmps = 0; + } + } +#ifdef SUPPORT_UCP + else + { + if (*cc == XCL_NOTPROP) + invertcmp ^= 0x1; + cc++; + switch(*cc) + { + case PT_ANY: + if (list != backtracks) + { + if ((cc[-1] == XCL_NOTPROP && compares > 0) || (cc[-1] == XCL_PROP && compares == 0)) + continue; + } + else if (cc[-1] == XCL_NOTPROP) + continue; + jump = JUMP(SLJIT_JUMP); + break; + + case PT_LAMP: + OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, typereg, 0, SLJIT_IMM, ucp_Lu - typeoffset); + OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_UNUSED, 0, SLJIT_C_EQUAL); + OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, typereg, 0, SLJIT_IMM, ucp_Ll - typeoffset); + OP_FLAGS(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); + OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, typereg, 0, SLJIT_IMM, ucp_Lt - typeoffset); + OP_FLAGS(SLJIT_OR | SLJIT_SET_E, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); + jump = JUMP(SLJIT_C_NOT_ZERO ^ invertcmp); + break; + + case PT_GC: + c = PRIV(ucp_typerange)[(int)cc[1] * 2]; + SET_TYPE_OFFSET(c); + jump = CMP(SLJIT_C_LESS_EQUAL ^ invertcmp, typereg, 0, SLJIT_IMM, PRIV(ucp_typerange)[(int)cc[1] * 2 + 1] - c); + break; + + case PT_PC: + jump = CMP(SLJIT_C_EQUAL ^ invertcmp, typereg, 0, SLJIT_IMM, (int)cc[1] - typeoffset); + break; + + case PT_SC: + jump = CMP(SLJIT_C_EQUAL ^ invertcmp, scriptreg, 0, SLJIT_IMM, (int)cc[1]); + break; + + case PT_SPACE: + case PT_PXSPACE: + SET_CHAR_OFFSET(9); + OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0xd - 0x9); + OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_UNUSED, 0, SLJIT_C_LESS_EQUAL); + + OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x85 - 0x9); + OP_FLAGS(SLJIT_OR | SLJIT_SET_E, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); + + OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x180e - 0x9); + OP_FLAGS(SLJIT_OR | SLJIT_SET_E, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); + + SET_TYPE_OFFSET(ucp_Zl); + OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, typereg, 0, SLJIT_IMM, ucp_Zs - ucp_Zl); + OP_FLAGS(SLJIT_OR | SLJIT_SET_E, TMP2, 0, TMP2, 0, SLJIT_C_LESS_EQUAL); + jump = JUMP(SLJIT_C_NOT_ZERO ^ invertcmp); + break; + + case PT_WORD: + OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)(CHAR_UNDERSCORE - charoffset)); + OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_UNUSED, 0, SLJIT_C_EQUAL); + /* Fall through. */ + + case PT_ALNUM: + SET_TYPE_OFFSET(ucp_Ll); + OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, typereg, 0, SLJIT_IMM, ucp_Lu - ucp_Ll); + OP_FLAGS((*cc == PT_ALNUM) ? SLJIT_MOV : SLJIT_OR, TMP2, 0, (*cc == PT_ALNUM) ? SLJIT_UNUSED : TMP2, 0, SLJIT_C_LESS_EQUAL); + SET_TYPE_OFFSET(ucp_Nd); + OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, typereg, 0, SLJIT_IMM, ucp_No - ucp_Nd); + OP_FLAGS(SLJIT_OR | SLJIT_SET_E, TMP2, 0, TMP2, 0, SLJIT_C_LESS_EQUAL); + jump = JUMP(SLJIT_C_NOT_ZERO ^ invertcmp); + break; + + case PT_CLIST: + other_cases = PRIV(ucd_caseless_sets) + cc[1]; + + /* At least three characters are required. + Otherwise this case would be handled by the normal code path. */ + SLJIT_ASSERT(other_cases[0] != NOTACHAR && other_cases[1] != NOTACHAR && other_cases[2] != NOTACHAR); + SLJIT_ASSERT(other_cases[0] < other_cases[1] && other_cases[1] < other_cases[2]); + + /* Optimizing character pairs, if their difference is power of 2. */ + if (is_powerof2(other_cases[1] ^ other_cases[0])) + { + if (charoffset == 0) + OP2(SLJIT_OR, TMP2, 0, TMP1, 0, SLJIT_IMM, other_cases[1] ^ other_cases[0]); + else + { + OP2(SLJIT_ADD, TMP2, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)charoffset); + OP2(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_IMM, other_cases[1] ^ other_cases[0]); + } + OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP2, 0, SLJIT_IMM, other_cases[1]); + OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_UNUSED, 0, SLJIT_C_EQUAL); + other_cases += 2; + } + else if (is_powerof2(other_cases[2] ^ other_cases[1])) + { + if (charoffset == 0) + OP2(SLJIT_OR, TMP2, 0, TMP1, 0, SLJIT_IMM, other_cases[2] ^ other_cases[1]); + else + { + OP2(SLJIT_ADD, TMP2, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)charoffset); + OP2(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_IMM, other_cases[1] ^ other_cases[0]); + } + OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP2, 0, SLJIT_IMM, other_cases[2]); + OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_UNUSED, 0, SLJIT_C_EQUAL); + + OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)(other_cases[0] - charoffset)); + OP_FLAGS(SLJIT_OR | ((other_cases[3] == NOTACHAR) ? SLJIT_SET_E : 0), TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); + + other_cases += 3; + } + else + { + OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)(*other_cases++ - charoffset)); + OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_UNUSED, 0, SLJIT_C_EQUAL); + } + + while (*other_cases != NOTACHAR) + { + OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)(*other_cases++ - charoffset)); + OP_FLAGS(SLJIT_OR | ((*other_cases == NOTACHAR) ? SLJIT_SET_E : 0), TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); + } + jump = JUMP(SLJIT_C_NOT_ZERO ^ invertcmp); + break; + + case PT_UCNC: + OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)(CHAR_DOLLAR_SIGN - charoffset)); + OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_UNUSED, 0, SLJIT_C_EQUAL); + OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)(CHAR_COMMERCIAL_AT - charoffset)); + OP_FLAGS(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); + OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)(CHAR_GRAVE_ACCENT - charoffset)); + OP_FLAGS(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); + + SET_CHAR_OFFSET(0xa0); + OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)(0xd7ff - charoffset)); + OP_FLAGS(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_C_LESS_EQUAL); + SET_CHAR_OFFSET(0); + OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0xe000 - 0); + OP_FLAGS(SLJIT_OR | SLJIT_SET_E, TMP2, 0, TMP2, 0, SLJIT_C_GREATER_EQUAL); + jump = JUMP(SLJIT_C_NOT_ZERO ^ invertcmp); + break; + + case PT_PXGRAPH: + /* C and Z groups are the farthest two groups. */ + SET_TYPE_OFFSET(ucp_Ll); + OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, typereg, 0, SLJIT_IMM, ucp_So - ucp_Ll); + OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_UNUSED, 0, SLJIT_C_GREATER); + + jump = CMP(SLJIT_C_NOT_EQUAL, typereg, 0, SLJIT_IMM, ucp_Cf - ucp_Ll); + + /* In case of ucp_Cf, we overwrite the result. */ + SET_CHAR_OFFSET(0x2066); + OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x2069 - 0x2066); + OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_UNUSED, 0, SLJIT_C_LESS_EQUAL); + + OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x061c - 0x2066); + OP_FLAGS(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); + + OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x180e - 0x2066); + OP_FLAGS(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); + + JUMPHERE(jump); + jump = CMP(SLJIT_C_ZERO ^ invertcmp, TMP2, 0, SLJIT_IMM, 0); + break; + + case PT_PXPRINT: + /* C and Z groups are the farthest two groups. */ + SET_TYPE_OFFSET(ucp_Ll); + OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, typereg, 0, SLJIT_IMM, ucp_So - ucp_Ll); + OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_UNUSED, 0, SLJIT_C_GREATER); + + OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, typereg, 0, SLJIT_IMM, ucp_Zs - ucp_Ll); + OP_FLAGS(SLJIT_AND, TMP2, 0, TMP2, 0, SLJIT_C_NOT_EQUAL); + + jump = CMP(SLJIT_C_NOT_EQUAL, typereg, 0, SLJIT_IMM, ucp_Cf - ucp_Ll); + + /* In case of ucp_Cf, we overwrite the result. */ + SET_CHAR_OFFSET(0x2066); + OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x2069 - 0x2066); + OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_UNUSED, 0, SLJIT_C_LESS_EQUAL); + + OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x061c - 0x2066); + OP_FLAGS(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); + + JUMPHERE(jump); + jump = CMP(SLJIT_C_ZERO ^ invertcmp, TMP2, 0, SLJIT_IMM, 0); + break; + + case PT_PXPUNCT: + SET_TYPE_OFFSET(ucp_Sc); + OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, typereg, 0, SLJIT_IMM, ucp_So - ucp_Sc); + OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_UNUSED, 0, SLJIT_C_LESS_EQUAL); + + SET_CHAR_OFFSET(0); + OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0xff); + OP_FLAGS(SLJIT_AND, TMP2, 0, TMP2, 0, SLJIT_C_LESS_EQUAL); + + SET_TYPE_OFFSET(ucp_Pc); + OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, typereg, 0, SLJIT_IMM, ucp_Ps - ucp_Pc); + OP_FLAGS(SLJIT_OR | SLJIT_SET_E, TMP2, 0, TMP2, 0, SLJIT_C_LESS_EQUAL); + jump = JUMP(SLJIT_C_NOT_ZERO ^ invertcmp); + break; + } + cc += 2; + } +#endif + + if (jump != NULL) + add_jump(compiler, compares > 0 ? list : backtracks, jump); + } + +if (found != NULL) + set_jumps(found, LABEL()); +} + +#undef SET_TYPE_OFFSET +#undef SET_CHAR_OFFSET + +#endif + +static pcre_uchar *compile_char1_matchingpath(compiler_common *common, pcre_uchar type, pcre_uchar *cc, jump_list **backtracks) +{ +DEFINE_COMPILER; +int length; +unsigned int c, oc, bit; +compare_context context; +struct sljit_jump *jump[4]; +jump_list *end_list; +#ifdef SUPPORT_UTF +struct sljit_label *label; +#ifdef SUPPORT_UCP +pcre_uchar propdata[5]; +#endif +#endif /* SUPPORT_UTF */ + +switch(type) + { + case OP_SOD: + OP1(SLJIT_MOV, TMP1, 0, ARGUMENTS, 0); + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, begin)); + add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, STR_PTR, 0, TMP1, 0)); + return cc; + + case OP_SOM: + OP1(SLJIT_MOV, TMP1, 0, ARGUMENTS, 0); + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, str)); + add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, STR_PTR, 0, TMP1, 0)); + return cc; + + case OP_NOT_WORD_BOUNDARY: + case OP_WORD_BOUNDARY: + add_jump(compiler, &common->wordboundary, JUMP(SLJIT_FAST_CALL)); + add_jump(compiler, backtracks, JUMP(type == OP_NOT_WORD_BOUNDARY ? SLJIT_C_NOT_ZERO : SLJIT_C_ZERO)); + return cc; + + case OP_NOT_DIGIT: + case OP_DIGIT: + /* Digits are usually 0-9, so it is worth to optimize them. */ + detect_partial_match(common, backtracks); +#if defined SUPPORT_UTF && defined COMPILE_PCRE8 + if (common->utf && is_char7_bitset((const pcre_uint8*)common->ctypes - cbit_length + cbit_digit, FALSE)) + read_char7_type(common, type == OP_NOT_DIGIT); + else +#endif + read_char8_type(common, type == OP_NOT_DIGIT); + /* Flip the starting bit in the negative case. */ + OP2(SLJIT_AND | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, ctype_digit); + add_jump(compiler, backtracks, JUMP(type == OP_DIGIT ? SLJIT_C_ZERO : SLJIT_C_NOT_ZERO)); + return cc; + + case OP_NOT_WHITESPACE: + case OP_WHITESPACE: + detect_partial_match(common, backtracks); +#if defined SUPPORT_UTF && defined COMPILE_PCRE8 + if (common->utf && is_char7_bitset((const pcre_uint8*)common->ctypes - cbit_length + cbit_space, FALSE)) + read_char7_type(common, type == OP_NOT_WHITESPACE); + else +#endif + read_char8_type(common, type == OP_NOT_WHITESPACE); + OP2(SLJIT_AND | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, ctype_space); + add_jump(compiler, backtracks, JUMP(type == OP_WHITESPACE ? SLJIT_C_ZERO : SLJIT_C_NOT_ZERO)); + return cc; + + case OP_NOT_WORDCHAR: + case OP_WORDCHAR: + detect_partial_match(common, backtracks); +#if defined SUPPORT_UTF && defined COMPILE_PCRE8 + if (common->utf && is_char7_bitset((const pcre_uint8*)common->ctypes - cbit_length + cbit_word, FALSE)) + read_char7_type(common, type == OP_NOT_WORDCHAR); + else +#endif + read_char8_type(common, type == OP_NOT_WORDCHAR); + OP2(SLJIT_AND | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, ctype_word); + add_jump(compiler, backtracks, JUMP(type == OP_WORDCHAR ? SLJIT_C_ZERO : SLJIT_C_NOT_ZERO)); + return cc; + + case OP_ANY: + detect_partial_match(common, backtracks); + read_char_range(common, common->nlmin, common->nlmax, TRUE); + if (common->nltype == NLTYPE_FIXED && common->newline > 255) + { + jump[0] = CMP(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, (common->newline >> 8) & 0xff); + end_list = NULL; + if (common->mode != JIT_PARTIAL_HARD_COMPILE) + add_jump(compiler, &end_list, CMP(SLJIT_C_GREATER_EQUAL, STR_PTR, 0, STR_END, 0)); + else + check_str_end(common, &end_list); + + OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), 0); + add_jump(compiler, backtracks, CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, common->newline & 0xff)); + set_jumps(end_list, LABEL()); + JUMPHERE(jump[0]); + } + else + check_newlinechar(common, common->nltype, backtracks, TRUE); + return cc; + + case OP_ALLANY: + detect_partial_match(common, backtracks); +#ifdef SUPPORT_UTF + if (common->utf) + { + OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), 0); + OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); +#if defined COMPILE_PCRE8 || defined COMPILE_PCRE16 +#if defined COMPILE_PCRE8 + jump[0] = CMP(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, 0xc0); + OP1(SLJIT_MOV_UB, TMP1, 0, SLJIT_MEM1(TMP1), (sljit_sw)PRIV(utf8_table4) - 0xc0); + OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP1, 0); +#elif defined COMPILE_PCRE16 + jump[0] = CMP(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, 0xd800); + OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0xfc00); + OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0xd800); + OP_FLAGS(SLJIT_MOV, TMP1, 0, SLJIT_UNUSED, 0, SLJIT_C_EQUAL); + OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 1); + OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP1, 0); +#endif + JUMPHERE(jump[0]); +#endif /* COMPILE_PCRE[8|16] */ + return cc; + } +#endif + OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); + return cc; + + case OP_ANYBYTE: + detect_partial_match(common, backtracks); + OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); + return cc; + +#ifdef SUPPORT_UTF +#ifdef SUPPORT_UCP + case OP_NOTPROP: + case OP_PROP: + propdata[0] = XCL_HASPROP; + propdata[1] = type == OP_NOTPROP ? XCL_NOTPROP : XCL_PROP; + propdata[2] = cc[0]; + propdata[3] = cc[1]; + propdata[4] = XCL_END; + compile_xclass_matchingpath(common, propdata, backtracks); + return cc + 2; +#endif +#endif + + case OP_ANYNL: + detect_partial_match(common, backtracks); + read_char_range(common, common->bsr_nlmin, common->bsr_nlmax, FALSE); + jump[0] = CMP(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, CHAR_CR); + /* We don't need to handle soft partial matching case. */ + end_list = NULL; + if (common->mode != JIT_PARTIAL_HARD_COMPILE) + add_jump(compiler, &end_list, CMP(SLJIT_C_GREATER_EQUAL, STR_PTR, 0, STR_END, 0)); + else + check_str_end(common, &end_list); + OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), 0); + jump[1] = CMP(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, CHAR_NL); + OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); + jump[2] = JUMP(SLJIT_JUMP); + JUMPHERE(jump[0]); + check_newlinechar(common, common->bsr_nltype, backtracks, FALSE); + set_jumps(end_list, LABEL()); + JUMPHERE(jump[1]); + JUMPHERE(jump[2]); + return cc; + + case OP_NOT_HSPACE: + case OP_HSPACE: + detect_partial_match(common, backtracks); + read_char_range(common, 0x9, 0x3000, type == OP_NOT_HSPACE); + add_jump(compiler, &common->hspace, JUMP(SLJIT_FAST_CALL)); + add_jump(compiler, backtracks, JUMP(type == OP_NOT_HSPACE ? SLJIT_C_NOT_ZERO : SLJIT_C_ZERO)); + return cc; + + case OP_NOT_VSPACE: + case OP_VSPACE: + detect_partial_match(common, backtracks); + read_char_range(common, 0xa, 0x2029, type == OP_NOT_VSPACE); + add_jump(compiler, &common->vspace, JUMP(SLJIT_FAST_CALL)); + add_jump(compiler, backtracks, JUMP(type == OP_NOT_VSPACE ? SLJIT_C_NOT_ZERO : SLJIT_C_ZERO)); + return cc; + +#ifdef SUPPORT_UCP + case OP_EXTUNI: + detect_partial_match(common, backtracks); + read_char(common); + add_jump(compiler, &common->getucd, JUMP(SLJIT_FAST_CALL)); + OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, gbprop)); + /* Optimize register allocation: use a real register. */ + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS0, STACK_TOP, 0); + OP1(SLJIT_MOV_UB, STACK_TOP, 0, SLJIT_MEM2(TMP1, TMP2), 3); + + label = LABEL(); + jump[0] = CMP(SLJIT_C_GREATER_EQUAL, STR_PTR, 0, STR_END, 0); + OP1(SLJIT_MOV, TMP3, 0, STR_PTR, 0); + read_char(common); + add_jump(compiler, &common->getucd, JUMP(SLJIT_FAST_CALL)); + OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, gbprop)); + OP1(SLJIT_MOV_UB, TMP2, 0, SLJIT_MEM2(TMP1, TMP2), 3); + + OP2(SLJIT_SHL, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, 2); + OP1(SLJIT_MOV_UI, TMP1, 0, SLJIT_MEM1(STACK_TOP), (sljit_sw)PRIV(ucp_gbtable)); + OP1(SLJIT_MOV, STACK_TOP, 0, TMP2, 0); + OP2(SLJIT_SHL, TMP2, 0, SLJIT_IMM, 1, TMP2, 0); + OP2(SLJIT_AND | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, TMP2, 0); + JUMPTO(SLJIT_C_NOT_ZERO, label); + + OP1(SLJIT_MOV, STR_PTR, 0, TMP3, 0); + JUMPHERE(jump[0]); + OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), LOCALS0); + + if (common->mode == JIT_PARTIAL_HARD_COMPILE) + { + jump[0] = CMP(SLJIT_C_LESS, STR_PTR, 0, STR_END, 0); + /* Since we successfully read a char above, partial matching must occure. */ + check_partial(common, TRUE); + JUMPHERE(jump[0]); + } + return cc; +#endif + + case OP_EODN: + /* Requires rather complex checks. */ + jump[0] = CMP(SLJIT_C_GREATER_EQUAL, STR_PTR, 0, STR_END, 0); + if (common->nltype == NLTYPE_FIXED && common->newline > 255) + { + OP2(SLJIT_ADD, TMP2, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(2)); + OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); + if (common->mode == JIT_COMPILE) + add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, TMP2, 0, STR_END, 0)); + else + { + jump[1] = CMP(SLJIT_C_EQUAL, TMP2, 0, STR_END, 0); + OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, TMP2, 0, STR_END, 0); + OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_UNUSED, 0, SLJIT_C_LESS); + OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, (common->newline >> 8) & 0xff); + OP_FLAGS(SLJIT_OR | SLJIT_SET_E, TMP2, 0, TMP2, 0, SLJIT_C_NOT_EQUAL); + add_jump(compiler, backtracks, JUMP(SLJIT_C_NOT_EQUAL)); + check_partial(common, TRUE); + add_jump(compiler, backtracks, JUMP(SLJIT_JUMP)); + JUMPHERE(jump[1]); + } + OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(1)); + add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, (common->newline >> 8) & 0xff)); + add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, TMP2, 0, SLJIT_IMM, common->newline & 0xff)); + } + else if (common->nltype == NLTYPE_FIXED) + { + OP2(SLJIT_ADD, TMP2, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); + OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); + add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, TMP2, 0, STR_END, 0)); + add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, common->newline)); + } + else + { + OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); + jump[1] = CMP(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, CHAR_CR); + OP2(SLJIT_ADD, TMP2, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(2)); + OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, TMP2, 0, STR_END, 0); + jump[2] = JUMP(SLJIT_C_GREATER); + add_jump(compiler, backtracks, JUMP(SLJIT_C_LESS)); + /* Equal. */ + OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(1)); + jump[3] = CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, CHAR_NL); + add_jump(compiler, backtracks, JUMP(SLJIT_JUMP)); + + JUMPHERE(jump[1]); + if (common->nltype == NLTYPE_ANYCRLF) + { + OP2(SLJIT_ADD, TMP2, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); + add_jump(compiler, backtracks, CMP(SLJIT_C_LESS, TMP2, 0, STR_END, 0)); + add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, CHAR_NL)); + } + else + { + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS1, STR_PTR, 0); + read_char_range(common, common->nlmin, common->nlmax, TRUE); + add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, STR_PTR, 0, STR_END, 0)); + add_jump(compiler, &common->anynewline, JUMP(SLJIT_FAST_CALL)); + add_jump(compiler, backtracks, JUMP(SLJIT_C_ZERO)); + OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(SLJIT_SP), LOCALS1); + } + JUMPHERE(jump[2]); + JUMPHERE(jump[3]); + } + JUMPHERE(jump[0]); + check_partial(common, FALSE); + return cc; + + case OP_EOD: + add_jump(compiler, backtracks, CMP(SLJIT_C_LESS, STR_PTR, 0, STR_END, 0)); + check_partial(common, FALSE); + return cc; + + case OP_CIRC: + OP1(SLJIT_MOV, TMP2, 0, ARGUMENTS, 0); + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(TMP2), SLJIT_OFFSETOF(jit_arguments, begin)); + add_jump(compiler, backtracks, CMP(SLJIT_C_GREATER, STR_PTR, 0, TMP1, 0)); + OP1(SLJIT_MOV_UB, TMP2, 0, SLJIT_MEM1(TMP2), SLJIT_OFFSETOF(jit_arguments, notbol)); + add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, TMP2, 0, SLJIT_IMM, 0)); + return cc; + + case OP_CIRCM: + OP1(SLJIT_MOV, TMP2, 0, ARGUMENTS, 0); + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(TMP2), SLJIT_OFFSETOF(jit_arguments, begin)); + jump[1] = CMP(SLJIT_C_GREATER, STR_PTR, 0, TMP1, 0); + OP1(SLJIT_MOV_UB, TMP2, 0, SLJIT_MEM1(TMP2), SLJIT_OFFSETOF(jit_arguments, notbol)); + add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, TMP2, 0, SLJIT_IMM, 0)); + jump[0] = JUMP(SLJIT_JUMP); + JUMPHERE(jump[1]); + + add_jump(compiler, backtracks, CMP(SLJIT_C_GREATER_EQUAL, STR_PTR, 0, STR_END, 0)); + if (common->nltype == NLTYPE_FIXED && common->newline > 255) + { + OP2(SLJIT_SUB, TMP2, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(2)); + add_jump(compiler, backtracks, CMP(SLJIT_C_LESS, TMP2, 0, TMP1, 0)); + OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(-2)); + OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(-1)); + add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, (common->newline >> 8) & 0xff)); + add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, TMP2, 0, SLJIT_IMM, common->newline & 0xff)); + } + else + { + skip_char_back(common); + read_char_range(common, common->nlmin, common->nlmax, TRUE); + check_newlinechar(common, common->nltype, backtracks, FALSE); + } + JUMPHERE(jump[0]); + return cc; + + case OP_DOLL: + OP1(SLJIT_MOV, TMP2, 0, ARGUMENTS, 0); + OP1(SLJIT_MOV_UB, TMP2, 0, SLJIT_MEM1(TMP2), SLJIT_OFFSETOF(jit_arguments, noteol)); + add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, TMP2, 0, SLJIT_IMM, 0)); + + if (!common->endonly) + compile_char1_matchingpath(common, OP_EODN, cc, backtracks); + else + { + add_jump(compiler, backtracks, CMP(SLJIT_C_LESS, STR_PTR, 0, STR_END, 0)); + check_partial(common, FALSE); + } + return cc; + + case OP_DOLLM: + jump[1] = CMP(SLJIT_C_LESS, STR_PTR, 0, STR_END, 0); + OP1(SLJIT_MOV, TMP2, 0, ARGUMENTS, 0); + OP1(SLJIT_MOV_UB, TMP2, 0, SLJIT_MEM1(TMP2), SLJIT_OFFSETOF(jit_arguments, noteol)); + add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, TMP2, 0, SLJIT_IMM, 0)); + check_partial(common, FALSE); + jump[0] = JUMP(SLJIT_JUMP); + JUMPHERE(jump[1]); + + if (common->nltype == NLTYPE_FIXED && common->newline > 255) + { + OP2(SLJIT_ADD, TMP2, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(2)); + OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); + if (common->mode == JIT_COMPILE) + add_jump(compiler, backtracks, CMP(SLJIT_C_GREATER, TMP2, 0, STR_END, 0)); + else + { + jump[1] = CMP(SLJIT_C_LESS_EQUAL, TMP2, 0, STR_END, 0); + /* STR_PTR = STR_END - IN_UCHARS(1) */ + add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, (common->newline >> 8) & 0xff)); + check_partial(common, TRUE); + add_jump(compiler, backtracks, JUMP(SLJIT_JUMP)); + JUMPHERE(jump[1]); + } + + OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(1)); + add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, (common->newline >> 8) & 0xff)); + add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, TMP2, 0, SLJIT_IMM, common->newline & 0xff)); + } + else + { + peek_char(common, common->nlmax); + check_newlinechar(common, common->nltype, backtracks, FALSE); + } + JUMPHERE(jump[0]); + return cc; + + case OP_CHAR: + case OP_CHARI: + length = 1; +#ifdef SUPPORT_UTF + if (common->utf && HAS_EXTRALEN(*cc)) length += GET_EXTRALEN(*cc); +#endif + if (common->mode == JIT_COMPILE && (type == OP_CHAR || !char_has_othercase(common, cc) || char_get_othercase_bit(common, cc) != 0)) + { + OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(length)); + add_jump(compiler, backtracks, CMP(SLJIT_C_GREATER, STR_PTR, 0, STR_END, 0)); + + context.length = IN_UCHARS(length); + context.sourcereg = -1; +#if defined SLJIT_UNALIGNED && SLJIT_UNALIGNED + context.ucharptr = 0; +#endif + return byte_sequence_compare(common, type == OP_CHARI, cc, &context, backtracks); + } + + detect_partial_match(common, backtracks); +#ifdef SUPPORT_UTF + if (common->utf) + { + GETCHAR(c, cc); + } + else +#endif + c = *cc; + + if (type == OP_CHAR || !char_has_othercase(common, cc)) + { + read_char_range(common, c, c, FALSE); + add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, c)); + return cc + length; + } + oc = char_othercase(common, c); + read_char_range(common, c < oc ? c : oc, c > oc ? c : oc, FALSE); + bit = c ^ oc; + if (is_powerof2(bit)) + { + OP2(SLJIT_OR, TMP1, 0, TMP1, 0, SLJIT_IMM, bit); + add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, c | bit)); + return cc + length; + } + jump[0] = CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, c); + add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, oc)); + JUMPHERE(jump[0]); + return cc + length; + + case OP_NOT: + case OP_NOTI: + detect_partial_match(common, backtracks); + length = 1; +#ifdef SUPPORT_UTF + if (common->utf) + { +#ifdef COMPILE_PCRE8 + c = *cc; + if (c < 128) + { + OP1(SLJIT_MOV_UB, TMP1, 0, SLJIT_MEM1(STR_PTR), 0); + if (type == OP_NOT || !char_has_othercase(common, cc)) + add_jump(compiler, backtracks, CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, c)); + else + { + /* Since UTF8 code page is fixed, we know that c is in [a-z] or [A-Z] range. */ + OP2(SLJIT_OR, TMP2, 0, TMP1, 0, SLJIT_IMM, 0x20); + add_jump(compiler, backtracks, CMP(SLJIT_C_EQUAL, TMP2, 0, SLJIT_IMM, c | 0x20)); + } + /* Skip the variable-length character. */ + OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); + jump[0] = CMP(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, 0xc0); + OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(TMP1), (sljit_sw)PRIV(utf8_table4) - 0xc0); + OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP1, 0); + JUMPHERE(jump[0]); + return cc + 1; + } + else +#endif /* COMPILE_PCRE8 */ + { + GETCHARLEN(c, cc, length); + } + } + else +#endif /* SUPPORT_UTF */ + c = *cc; + + if (type == OP_NOT || !char_has_othercase(common, cc)) + { + read_char_range(common, c, c, TRUE); + add_jump(compiler, backtracks, CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, c)); + } + else + { + oc = char_othercase(common, c); + read_char_range(common, c < oc ? c : oc, c > oc ? c : oc, TRUE); + bit = c ^ oc; + if (is_powerof2(bit)) + { + OP2(SLJIT_OR, TMP1, 0, TMP1, 0, SLJIT_IMM, bit); + add_jump(compiler, backtracks, CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, c | bit)); + } + else + { + add_jump(compiler, backtracks, CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, c)); + add_jump(compiler, backtracks, CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, oc)); + } + } + return cc + length; + + case OP_CLASS: + case OP_NCLASS: + detect_partial_match(common, backtracks); + +#if defined SUPPORT_UTF && defined COMPILE_PCRE8 + bit = (common->utf && is_char7_bitset((const pcre_uint8 *)cc, type == OP_NCLASS)) ? 127 : 255; + read_char_range(common, 0, bit, type == OP_NCLASS); +#else + read_char_range(common, 0, 255, type == OP_NCLASS); +#endif + + if (check_class_ranges(common, (const pcre_uint8 *)cc, type == OP_NCLASS, FALSE, backtracks)) + return cc + 32 / sizeof(pcre_uchar); + +#if defined SUPPORT_UTF && defined COMPILE_PCRE8 + jump[0] = NULL; + if (common->utf) + { + jump[0] = CMP(SLJIT_C_GREATER, TMP1, 0, SLJIT_IMM, bit); + if (type == OP_CLASS) + { + add_jump(compiler, backtracks, jump[0]); + jump[0] = NULL; + } + } +#elif !defined COMPILE_PCRE8 + jump[0] = CMP(SLJIT_C_GREATER, TMP1, 0, SLJIT_IMM, 255); + if (type == OP_CLASS) + { + add_jump(compiler, backtracks, jump[0]); + jump[0] = NULL; + } +#endif /* SUPPORT_UTF && COMPILE_PCRE8 */ + + OP2(SLJIT_AND, TMP2, 0, TMP1, 0, SLJIT_IMM, 0x7); + OP2(SLJIT_LSHR, TMP1, 0, TMP1, 0, SLJIT_IMM, 3); + OP1(SLJIT_MOV_UB, TMP1, 0, SLJIT_MEM1(TMP1), (sljit_sw)cc); + OP2(SLJIT_SHL, TMP2, 0, SLJIT_IMM, 1, TMP2, 0); + OP2(SLJIT_AND | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, TMP2, 0); + add_jump(compiler, backtracks, JUMP(SLJIT_C_ZERO)); + +#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 + if (jump[0] != NULL) + JUMPHERE(jump[0]); +#endif + + return cc + 32 / sizeof(pcre_uchar); + +#if defined SUPPORT_UTF || defined COMPILE_PCRE16 || defined COMPILE_PCRE32 + case OP_XCLASS: + compile_xclass_matchingpath(common, cc + LINK_SIZE, backtracks); + return cc + GET(cc, 0) - 1; +#endif + + case OP_REVERSE: + length = GET(cc, 0); + if (length == 0) + return cc + LINK_SIZE; + OP1(SLJIT_MOV, TMP1, 0, ARGUMENTS, 0); +#ifdef SUPPORT_UTF + if (common->utf) + { + OP1(SLJIT_MOV, TMP3, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, begin)); + OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, length); + label = LABEL(); + add_jump(compiler, backtracks, CMP(SLJIT_C_LESS_EQUAL, STR_PTR, 0, TMP3, 0)); + skip_char_back(common); + OP2(SLJIT_SUB | SLJIT_SET_E, TMP2, 0, TMP2, 0, SLJIT_IMM, 1); + JUMPTO(SLJIT_C_NOT_ZERO, label); + } + else +#endif + { + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, begin)); + OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(length)); + add_jump(compiler, backtracks, CMP(SLJIT_C_LESS, STR_PTR, 0, TMP1, 0)); + } + check_start_used_ptr(common); + return cc + LINK_SIZE; + } +SLJIT_ASSERT_STOP(); +return cc; +} + +static SLJIT_INLINE pcre_uchar *compile_charn_matchingpath(compiler_common *common, pcre_uchar *cc, pcre_uchar *ccend, jump_list **backtracks) +{ +/* This function consumes at least one input character. */ +/* To decrease the number of length checks, we try to concatenate the fixed length character sequences. */ +DEFINE_COMPILER; +pcre_uchar *ccbegin = cc; +compare_context context; +int size; + +context.length = 0; +do + { + if (cc >= ccend) + break; + + if (*cc == OP_CHAR) + { + size = 1; +#ifdef SUPPORT_UTF + if (common->utf && HAS_EXTRALEN(cc[1])) + size += GET_EXTRALEN(cc[1]); +#endif + } + else if (*cc == OP_CHARI) + { + size = 1; +#ifdef SUPPORT_UTF + if (common->utf) + { + if (char_has_othercase(common, cc + 1) && char_get_othercase_bit(common, cc + 1) == 0) + size = 0; + else if (HAS_EXTRALEN(cc[1])) + size += GET_EXTRALEN(cc[1]); + } + else +#endif + if (char_has_othercase(common, cc + 1) && char_get_othercase_bit(common, cc + 1) == 0) + size = 0; + } + else + size = 0; + + cc += 1 + size; + context.length += IN_UCHARS(size); + } +while (size > 0 && context.length <= 128); + +cc = ccbegin; +if (context.length > 0) + { + /* We have a fixed-length byte sequence. */ + OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, context.length); + add_jump(compiler, backtracks, CMP(SLJIT_C_GREATER, STR_PTR, 0, STR_END, 0)); + + context.sourcereg = -1; +#if defined SLJIT_UNALIGNED && SLJIT_UNALIGNED + context.ucharptr = 0; +#endif + do cc = byte_sequence_compare(common, *cc == OP_CHARI, cc + 1, &context, backtracks); while (context.length > 0); + return cc; + } + +/* A non-fixed length character will be checked if length == 0. */ +return compile_char1_matchingpath(common, *cc, cc + 1, backtracks); +} + +/* Forward definitions. */ +static void compile_matchingpath(compiler_common *, pcre_uchar *, pcre_uchar *, backtrack_common *); +static void compile_backtrackingpath(compiler_common *, struct backtrack_common *); + +#define PUSH_BACKTRACK(size, ccstart, error) \ + do \ + { \ + backtrack = sljit_alloc_memory(compiler, (size)); \ + if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) \ + return error; \ + memset(backtrack, 0, size); \ + backtrack->prev = parent->top; \ + backtrack->cc = (ccstart); \ + parent->top = backtrack; \ + } \ + while (0) + +#define PUSH_BACKTRACK_NOVALUE(size, ccstart) \ + do \ + { \ + backtrack = sljit_alloc_memory(compiler, (size)); \ + if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) \ + return; \ + memset(backtrack, 0, size); \ + backtrack->prev = parent->top; \ + backtrack->cc = (ccstart); \ + parent->top = backtrack; \ + } \ + while (0) + +#define BACKTRACK_AS(type) ((type *)backtrack) + +static void compile_dnref_search(compiler_common *common, pcre_uchar *cc, jump_list **backtracks) +{ +/* The OVECTOR offset goes to TMP2. */ +DEFINE_COMPILER; +int count = GET2(cc, 1 + IMM2_SIZE); +pcre_uchar *slot = common->name_table + GET2(cc, 1) * common->name_entry_size; +unsigned int offset; +jump_list *found = NULL; + +SLJIT_ASSERT(*cc == OP_DNREF || *cc == OP_DNREFI); + +OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(1)); + +count--; +while (count-- > 0) + { + offset = GET2(slot, 0) << 1; + GET_LOCAL_BASE(TMP2, 0, OVECTOR(offset)); + add_jump(compiler, &found, CMP(SLJIT_C_NOT_EQUAL, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset), TMP1, 0)); + slot += common->name_entry_size; + } + +offset = GET2(slot, 0) << 1; +GET_LOCAL_BASE(TMP2, 0, OVECTOR(offset)); +if (backtracks != NULL && !common->jscript_compat) + add_jump(compiler, backtracks, CMP(SLJIT_C_EQUAL, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset), TMP1, 0)); + +set_jumps(found, LABEL()); +} + +static void compile_ref_matchingpath(compiler_common *common, pcre_uchar *cc, jump_list **backtracks, BOOL withchecks, BOOL emptyfail) +{ +DEFINE_COMPILER; +BOOL ref = (*cc == OP_REF || *cc == OP_REFI); +int offset = 0; +struct sljit_jump *jump = NULL; +struct sljit_jump *partial; +struct sljit_jump *nopartial; + +if (ref) + { + offset = GET2(cc, 1) << 1; + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset)); + /* OVECTOR(1) contains the "string begin - 1" constant. */ + if (withchecks && !common->jscript_compat) + add_jump(compiler, backtracks, CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(1))); + } +else + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(TMP2), 0); + +#if defined SUPPORT_UTF && defined SUPPORT_UCP +if (common->utf && *cc == OP_REFI) + { + SLJIT_ASSERT(TMP1 == SLJIT_R0 && STACK_TOP == SLJIT_R1 && TMP2 == SLJIT_R2); + if (ref) + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1)); + else + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(TMP2), sizeof(sljit_sw)); + + if (withchecks) + jump = CMP(SLJIT_C_EQUAL, TMP1, 0, TMP2, 0); + + /* Needed to save important temporary registers. */ + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS0, STACK_TOP, 0); + OP1(SLJIT_MOV, SLJIT_R1, 0, ARGUMENTS, 0); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_R1), SLJIT_OFFSETOF(jit_arguments, uchar_ptr), STR_PTR, 0); + sljit_emit_ijump(compiler, SLJIT_CALL3, SLJIT_IMM, SLJIT_FUNC_OFFSET(do_utf_caselesscmp)); + OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), LOCALS0); + if (common->mode == JIT_COMPILE) + add_jump(compiler, backtracks, CMP(SLJIT_C_LESS_EQUAL, SLJIT_RETURN_REG, 0, SLJIT_IMM, 1)); + else + { + add_jump(compiler, backtracks, CMP(SLJIT_C_EQUAL, SLJIT_RETURN_REG, 0, SLJIT_IMM, 0)); + nopartial = CMP(SLJIT_C_NOT_EQUAL, SLJIT_RETURN_REG, 0, SLJIT_IMM, 1); + check_partial(common, FALSE); + add_jump(compiler, backtracks, JUMP(SLJIT_JUMP)); + JUMPHERE(nopartial); + } + OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_RETURN_REG, 0); + } +else +#endif /* SUPPORT_UTF && SUPPORT_UCP */ + { + if (ref) + OP2(SLJIT_SUB | SLJIT_SET_E, TMP2, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1), TMP1, 0); + else + OP2(SLJIT_SUB | SLJIT_SET_E, TMP2, 0, SLJIT_MEM1(TMP2), sizeof(sljit_sw), TMP1, 0); + + if (withchecks) + jump = JUMP(SLJIT_C_ZERO); + + OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP2, 0); + partial = CMP(SLJIT_C_GREATER, STR_PTR, 0, STR_END, 0); + if (common->mode == JIT_COMPILE) + add_jump(compiler, backtracks, partial); + + add_jump(compiler, *cc == OP_REF ? &common->casefulcmp : &common->caselesscmp, JUMP(SLJIT_FAST_CALL)); + add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, TMP2, 0, SLJIT_IMM, 0)); + + if (common->mode != JIT_COMPILE) + { + nopartial = JUMP(SLJIT_JUMP); + JUMPHERE(partial); + /* TMP2 -= STR_END - STR_PTR */ + OP2(SLJIT_SUB, TMP2, 0, TMP2, 0, STR_PTR, 0); + OP2(SLJIT_ADD, TMP2, 0, TMP2, 0, STR_END, 0); + partial = CMP(SLJIT_C_EQUAL, TMP2, 0, SLJIT_IMM, 0); + OP1(SLJIT_MOV, STR_PTR, 0, STR_END, 0); + add_jump(compiler, *cc == OP_REF ? &common->casefulcmp : &common->caselesscmp, JUMP(SLJIT_FAST_CALL)); + add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, TMP2, 0, SLJIT_IMM, 0)); + JUMPHERE(partial); + check_partial(common, FALSE); + add_jump(compiler, backtracks, JUMP(SLJIT_JUMP)); + JUMPHERE(nopartial); + } + } + +if (jump != NULL) + { + if (emptyfail) + add_jump(compiler, backtracks, jump); + else + JUMPHERE(jump); + } +} + +static SLJIT_INLINE pcre_uchar *compile_ref_iterator_matchingpath(compiler_common *common, pcre_uchar *cc, backtrack_common *parent) +{ +DEFINE_COMPILER; +BOOL ref = (*cc == OP_REF || *cc == OP_REFI); +backtrack_common *backtrack; +pcre_uchar type; +int offset = 0; +struct sljit_label *label; +struct sljit_jump *zerolength; +struct sljit_jump *jump = NULL; +pcre_uchar *ccbegin = cc; +int min = 0, max = 0; +BOOL minimize; + +PUSH_BACKTRACK(sizeof(iterator_backtrack), cc, NULL); + +if (ref) + offset = GET2(cc, 1) << 1; +else + cc += IMM2_SIZE; +type = cc[1 + IMM2_SIZE]; + +SLJIT_COMPILE_ASSERT((OP_CRSTAR & 0x1) == 0, crstar_opcode_must_be_even); +minimize = (type & 0x1) != 0; +switch(type) + { + case OP_CRSTAR: + case OP_CRMINSTAR: + min = 0; + max = 0; + cc += 1 + IMM2_SIZE + 1; + break; + case OP_CRPLUS: + case OP_CRMINPLUS: + min = 1; + max = 0; + cc += 1 + IMM2_SIZE + 1; + break; + case OP_CRQUERY: + case OP_CRMINQUERY: + min = 0; + max = 1; + cc += 1 + IMM2_SIZE + 1; + break; + case OP_CRRANGE: + case OP_CRMINRANGE: + min = GET2(cc, 1 + IMM2_SIZE + 1); + max = GET2(cc, 1 + IMM2_SIZE + 1 + IMM2_SIZE); + cc += 1 + IMM2_SIZE + 1 + 2 * IMM2_SIZE; + break; + default: + SLJIT_ASSERT_STOP(); + break; + } + +if (!minimize) + { + if (min == 0) + { + allocate_stack(common, 2); + if (ref) + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset)); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(1), SLJIT_IMM, 0); + /* Temporary release of STR_PTR. */ + OP2(SLJIT_SUB, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, sizeof(sljit_sw)); + /* Handles both invalid and empty cases. Since the minimum repeat, + is zero the invalid case is basically the same as an empty case. */ + if (ref) + zerolength = CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1)); + else + { + compile_dnref_search(common, ccbegin, NULL); + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(TMP2), 0); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), POSSESSIVE1, TMP2, 0); + zerolength = CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_MEM1(TMP2), sizeof(sljit_sw)); + } + /* Restore if not zero length. */ + OP2(SLJIT_ADD, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, sizeof(sljit_sw)); + } + else + { + allocate_stack(common, 1); + if (ref) + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset)); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); + if (ref) + { + add_jump(compiler, &backtrack->topbacktracks, CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(1))); + zerolength = CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1)); + } + else + { + compile_dnref_search(common, ccbegin, &backtrack->topbacktracks); + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(TMP2), 0); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), POSSESSIVE1, TMP2, 0); + zerolength = CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_MEM1(TMP2), sizeof(sljit_sw)); + } + } + + if (min > 1 || max > 1) + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), POSSESSIVE0, SLJIT_IMM, 0); + + label = LABEL(); + if (!ref) + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), POSSESSIVE1); + compile_ref_matchingpath(common, ccbegin, &backtrack->topbacktracks, FALSE, FALSE); + + if (min > 1 || max > 1) + { + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), POSSESSIVE0); + OP2(SLJIT_ADD, TMP1, 0, TMP1, 0, SLJIT_IMM, 1); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), POSSESSIVE0, TMP1, 0); + if (min > 1) + CMPTO(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, min, label); + if (max > 1) + { + jump = CMP(SLJIT_C_GREATER_EQUAL, TMP1, 0, SLJIT_IMM, max); + allocate_stack(common, 1); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); + JUMPTO(SLJIT_JUMP, label); + JUMPHERE(jump); + } + } + + if (max == 0) + { + /* Includes min > 1 case as well. */ + allocate_stack(common, 1); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); + JUMPTO(SLJIT_JUMP, label); + } + + JUMPHERE(zerolength); + BACKTRACK_AS(iterator_backtrack)->matchingpath = LABEL(); + + count_match(common); + return cc; + } + +allocate_stack(common, ref ? 2 : 3); +if (ref) + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset)); +OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); +if (type != OP_CRMINSTAR) + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(1), SLJIT_IMM, 0); + +if (min == 0) + { + /* Handles both invalid and empty cases. Since the minimum repeat, + is zero the invalid case is basically the same as an empty case. */ + if (ref) + zerolength = CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1)); + else + { + compile_dnref_search(common, ccbegin, NULL); + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(TMP2), 0); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(2), TMP2, 0); + zerolength = CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_MEM1(TMP2), sizeof(sljit_sw)); + } + /* Length is non-zero, we can match real repeats. */ + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); + jump = JUMP(SLJIT_JUMP); + } +else + { + if (ref) + { + add_jump(compiler, &backtrack->topbacktracks, CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(1))); + zerolength = CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1)); + } + else + { + compile_dnref_search(common, ccbegin, &backtrack->topbacktracks); + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(TMP2), 0); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(2), TMP2, 0); + zerolength = CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_MEM1(TMP2), sizeof(sljit_sw)); + } + } + +BACKTRACK_AS(iterator_backtrack)->matchingpath = LABEL(); +if (max > 0) + add_jump(compiler, &backtrack->topbacktracks, CMP(SLJIT_C_GREATER_EQUAL, SLJIT_MEM1(STACK_TOP), STACK(1), SLJIT_IMM, max)); + +if (!ref) + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), STACK(2)); +compile_ref_matchingpath(common, ccbegin, &backtrack->topbacktracks, TRUE, TRUE); +OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); + +if (min > 1) + { + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(1)); + OP2(SLJIT_ADD, TMP1, 0, TMP1, 0, SLJIT_IMM, 1); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(1), TMP1, 0); + CMPTO(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, min, BACKTRACK_AS(iterator_backtrack)->matchingpath); + } +else if (max > 0) + OP2(SLJIT_ADD, SLJIT_MEM1(STACK_TOP), STACK(1), SLJIT_MEM1(STACK_TOP), STACK(1), SLJIT_IMM, 1); + +if (jump != NULL) + JUMPHERE(jump); +JUMPHERE(zerolength); + +count_match(common); +return cc; +} + +static SLJIT_INLINE pcre_uchar *compile_recurse_matchingpath(compiler_common *common, pcre_uchar *cc, backtrack_common *parent) +{ +DEFINE_COMPILER; +backtrack_common *backtrack; +recurse_entry *entry = common->entries; +recurse_entry *prev = NULL; +sljit_sw start = GET(cc, 1); +pcre_uchar *start_cc; +BOOL needs_control_head; + +PUSH_BACKTRACK(sizeof(recurse_backtrack), cc, NULL); + +/* Inlining simple patterns. */ +if (get_framesize(common, common->start + start, NULL, TRUE, &needs_control_head) == no_stack) + { + start_cc = common->start + start; + compile_matchingpath(common, next_opcode(common, start_cc), bracketend(start_cc) - (1 + LINK_SIZE), backtrack); + BACKTRACK_AS(recurse_backtrack)->inlined_pattern = TRUE; + return cc + 1 + LINK_SIZE; + } + +while (entry != NULL) + { + if (entry->start == start) + break; + prev = entry; + entry = entry->next; + } + +if (entry == NULL) + { + entry = sljit_alloc_memory(compiler, sizeof(recurse_entry)); + if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) + return NULL; + entry->next = NULL; + entry->entry = NULL; + entry->calls = NULL; + entry->start = start; + + if (prev != NULL) + prev->next = entry; + else + common->entries = entry; + } + +if (common->has_set_som && common->mark_ptr != 0) + { + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(0)); + allocate_stack(common, 2); + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->mark_ptr); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), TMP2, 0); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(1), TMP1, 0); + } +else if (common->has_set_som || common->mark_ptr != 0) + { + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), common->has_set_som ? (int)(OVECTOR(0)) : common->mark_ptr); + allocate_stack(common, 1); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), TMP2, 0); + } + +if (entry->entry == NULL) + add_jump(compiler, &entry->calls, JUMP(SLJIT_FAST_CALL)); +else + JUMPTO(SLJIT_FAST_CALL, entry->entry); +/* Leave if the match is failed. */ +add_jump(compiler, &backtrack->topbacktracks, CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, 0)); +return cc + 1 + LINK_SIZE; +} + +static int SLJIT_CALL do_callout(struct jit_arguments* arguments, PUBL(callout_block) *callout_block, pcre_uchar **jit_ovector) +{ +const pcre_uchar *begin = arguments->begin; +int *offset_vector = arguments->offsets; +int offset_count = arguments->offset_count; +int i; + +if (PUBL(callout) == NULL) + return 0; + +callout_block->version = 2; +callout_block->callout_data = arguments->callout_data; + +/* Offsets in subject. */ +callout_block->subject_length = arguments->end - arguments->begin; +callout_block->start_match = (pcre_uchar*)callout_block->subject - arguments->begin; +callout_block->current_position = (pcre_uchar*)callout_block->offset_vector - arguments->begin; +#if defined COMPILE_PCRE8 +callout_block->subject = (PCRE_SPTR)begin; +#elif defined COMPILE_PCRE16 +callout_block->subject = (PCRE_SPTR16)begin; +#elif defined COMPILE_PCRE32 +callout_block->subject = (PCRE_SPTR32)begin; +#endif + +/* Convert and copy the JIT offset vector to the offset_vector array. */ +callout_block->capture_top = 0; +callout_block->offset_vector = offset_vector; +for (i = 2; i < offset_count; i += 2) + { + offset_vector[i] = jit_ovector[i] - begin; + offset_vector[i + 1] = jit_ovector[i + 1] - begin; + if (jit_ovector[i] >= begin) + callout_block->capture_top = i; + } + +callout_block->capture_top = (callout_block->capture_top >> 1) + 1; +if (offset_count > 0) + offset_vector[0] = -1; +if (offset_count > 1) + offset_vector[1] = -1; +return (*PUBL(callout))(callout_block); +} + +/* Aligning to 8 byte. */ +#define CALLOUT_ARG_SIZE \ + (((int)sizeof(PUBL(callout_block)) + 7) & ~7) + +#define CALLOUT_ARG_OFFSET(arg) \ + (-CALLOUT_ARG_SIZE + SLJIT_OFFSETOF(PUBL(callout_block), arg)) + +static SLJIT_INLINE pcre_uchar *compile_callout_matchingpath(compiler_common *common, pcre_uchar *cc, backtrack_common *parent) +{ +DEFINE_COMPILER; +backtrack_common *backtrack; + +PUSH_BACKTRACK(sizeof(backtrack_common), cc, NULL); + +allocate_stack(common, CALLOUT_ARG_SIZE / sizeof(sljit_sw)); + +OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), common->capture_last_ptr); +OP1(SLJIT_MOV, TMP1, 0, ARGUMENTS, 0); +SLJIT_ASSERT(common->capture_last_ptr != 0); +OP1(SLJIT_MOV_SI, SLJIT_MEM1(STACK_TOP), CALLOUT_ARG_OFFSET(callout_number), SLJIT_IMM, cc[1]); +OP1(SLJIT_MOV_SI, SLJIT_MEM1(STACK_TOP), CALLOUT_ARG_OFFSET(capture_last), TMP2, 0); + +/* These pointer sized fields temporarly stores internal variables. */ +OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(0)); +OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), CALLOUT_ARG_OFFSET(offset_vector), STR_PTR, 0); +OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), CALLOUT_ARG_OFFSET(subject), TMP2, 0); + +if (common->mark_ptr != 0) + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, mark_ptr)); +OP1(SLJIT_MOV_SI, SLJIT_MEM1(STACK_TOP), CALLOUT_ARG_OFFSET(pattern_position), SLJIT_IMM, GET(cc, 2)); +OP1(SLJIT_MOV_SI, SLJIT_MEM1(STACK_TOP), CALLOUT_ARG_OFFSET(next_item_length), SLJIT_IMM, GET(cc, 2 + LINK_SIZE)); +OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), CALLOUT_ARG_OFFSET(mark), (common->mark_ptr != 0) ? TMP2 : SLJIT_IMM, 0); + +/* Needed to save important temporary registers. */ +OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS0, STACK_TOP, 0); +OP2(SLJIT_SUB, SLJIT_R1, 0, STACK_TOP, 0, SLJIT_IMM, CALLOUT_ARG_SIZE); +GET_LOCAL_BASE(SLJIT_R2, 0, OVECTOR_START); +sljit_emit_ijump(compiler, SLJIT_CALL3, SLJIT_IMM, SLJIT_FUNC_OFFSET(do_callout)); +OP1(SLJIT_MOV_SI, SLJIT_RETURN_REG, 0, SLJIT_RETURN_REG, 0); +OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), LOCALS0); +free_stack(common, CALLOUT_ARG_SIZE / sizeof(sljit_sw)); + +/* Check return value. */ +OP2(SLJIT_SUB | SLJIT_SET_S, SLJIT_UNUSED, 0, SLJIT_RETURN_REG, 0, SLJIT_IMM, 0); +add_jump(compiler, &backtrack->topbacktracks, JUMP(SLJIT_C_SIG_GREATER)); +if (common->forced_quit_label == NULL) + add_jump(compiler, &common->forced_quit, JUMP(SLJIT_C_SIG_LESS)); +else + JUMPTO(SLJIT_C_SIG_LESS, common->forced_quit_label); +return cc + 2 + 2 * LINK_SIZE; +} + +#undef CALLOUT_ARG_SIZE +#undef CALLOUT_ARG_OFFSET + +static pcre_uchar *compile_assert_matchingpath(compiler_common *common, pcre_uchar *cc, assert_backtrack *backtrack, BOOL conditional) +{ +DEFINE_COMPILER; +int framesize; +int extrasize; +BOOL needs_control_head; +int private_data_ptr; +backtrack_common altbacktrack; +pcre_uchar *ccbegin; +pcre_uchar opcode; +pcre_uchar bra = OP_BRA; +jump_list *tmp = NULL; +jump_list **target = (conditional) ? &backtrack->condfailed : &backtrack->common.topbacktracks; +jump_list **found; +/* Saving previous accept variables. */ +BOOL save_local_exit = common->local_exit; +BOOL save_positive_assert = common->positive_assert; +then_trap_backtrack *save_then_trap = common->then_trap; +struct sljit_label *save_quit_label = common->quit_label; +struct sljit_label *save_accept_label = common->accept_label; +jump_list *save_quit = common->quit; +jump_list *save_positive_assert_quit = common->positive_assert_quit; +jump_list *save_accept = common->accept; +struct sljit_jump *jump; +struct sljit_jump *brajump = NULL; + +/* Assert captures then. */ +common->then_trap = NULL; + +if (*cc == OP_BRAZERO || *cc == OP_BRAMINZERO) + { + SLJIT_ASSERT(!conditional); + bra = *cc; + cc++; + } +private_data_ptr = PRIVATE_DATA(cc); +SLJIT_ASSERT(private_data_ptr != 0); +framesize = get_framesize(common, cc, NULL, FALSE, &needs_control_head); +backtrack->framesize = framesize; +backtrack->private_data_ptr = private_data_ptr; +opcode = *cc; +SLJIT_ASSERT(opcode >= OP_ASSERT && opcode <= OP_ASSERTBACK_NOT); +found = (opcode == OP_ASSERT || opcode == OP_ASSERTBACK) ? &tmp : target; +ccbegin = cc; +cc += GET(cc, 1); + +if (bra == OP_BRAMINZERO) + { + /* This is a braminzero backtrack path. */ + OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); + free_stack(common, 1); + brajump = CMP(SLJIT_C_EQUAL, STR_PTR, 0, SLJIT_IMM, 0); + } + +if (framesize < 0) + { + extrasize = needs_control_head ? 2 : 1; + if (framesize == no_frame) + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, STACK_TOP, 0); + allocate_stack(common, extrasize); + if (needs_control_head) + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); + if (needs_control_head) + { + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, SLJIT_IMM, 0); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(1), TMP1, 0); + } + } +else + { + extrasize = needs_control_head ? 3 : 2; + allocate_stack(common, framesize + extrasize); + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); + OP2(SLJIT_SUB, TMP2, 0, STACK_TOP, 0, SLJIT_IMM, (framesize + extrasize) * sizeof(sljit_sw)); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, TMP2, 0); + if (needs_control_head) + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); + if (needs_control_head) + { + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(2), TMP1, 0); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(1), TMP2, 0); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, SLJIT_IMM, 0); + } + else + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(1), TMP1, 0); + init_frame(common, ccbegin, NULL, framesize + extrasize - 1, extrasize, FALSE); + } + +memset(&altbacktrack, 0, sizeof(backtrack_common)); +if (opcode == OP_ASSERT_NOT || opcode == OP_ASSERTBACK_NOT) + { + /* Negative assert is stronger than positive assert. */ + common->local_exit = TRUE; + common->quit_label = NULL; + common->quit = NULL; + common->positive_assert = FALSE; + } +else + common->positive_assert = TRUE; +common->positive_assert_quit = NULL; + +while (1) + { + common->accept_label = NULL; + common->accept = NULL; + altbacktrack.top = NULL; + altbacktrack.topbacktracks = NULL; + + if (*ccbegin == OP_ALT) + OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); + + altbacktrack.cc = ccbegin; + compile_matchingpath(common, ccbegin + 1 + LINK_SIZE, cc, &altbacktrack); + if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) + { + if (opcode == OP_ASSERT_NOT || opcode == OP_ASSERTBACK_NOT) + { + common->local_exit = save_local_exit; + common->quit_label = save_quit_label; + common->quit = save_quit; + } + common->positive_assert = save_positive_assert; + common->then_trap = save_then_trap; + common->accept_label = save_accept_label; + common->positive_assert_quit = save_positive_assert_quit; + common->accept = save_accept; + return NULL; + } + common->accept_label = LABEL(); + if (common->accept != NULL) + set_jumps(common->accept, common->accept_label); + + /* Reset stack. */ + if (framesize < 0) + { + if (framesize == no_frame) + OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); + else + free_stack(common, extrasize); + if (needs_control_head) + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, SLJIT_MEM1(STACK_TOP), 0); + } + else + { + if ((opcode != OP_ASSERT_NOT && opcode != OP_ASSERTBACK_NOT) || conditional) + { + /* We don't need to keep the STR_PTR, only the previous private_data_ptr. */ + OP2(SLJIT_ADD, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr, SLJIT_IMM, (framesize + 1) * sizeof(sljit_sw)); + if (needs_control_head) + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, SLJIT_MEM1(STACK_TOP), 0); + } + else + { + OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); + if (needs_control_head) + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, SLJIT_MEM1(STACK_TOP), (framesize + 1) * sizeof(sljit_sw)); + add_jump(compiler, &common->revertframes, JUMP(SLJIT_FAST_CALL)); + } + } + + if (opcode == OP_ASSERT_NOT || opcode == OP_ASSERTBACK_NOT) + { + /* We know that STR_PTR was stored on the top of the stack. */ + if (conditional) + OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), needs_control_head ? sizeof(sljit_sw) : 0); + else if (bra == OP_BRAZERO) + { + if (framesize < 0) + OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), (extrasize - 1) * sizeof(sljit_sw)); + else + { + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), framesize * sizeof(sljit_sw)); + OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), (framesize + extrasize - 1) * sizeof(sljit_sw)); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, TMP1, 0); + } + OP2(SLJIT_ADD, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, sizeof(sljit_sw)); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); + } + else if (framesize >= 0) + { + /* For OP_BRA and OP_BRAMINZERO. */ + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, SLJIT_MEM1(STACK_TOP), framesize * sizeof(sljit_sw)); + } + } + add_jump(compiler, found, JUMP(SLJIT_JUMP)); + + compile_backtrackingpath(common, altbacktrack.top); + if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) + { + if (opcode == OP_ASSERT_NOT || opcode == OP_ASSERTBACK_NOT) + { + common->local_exit = save_local_exit; + common->quit_label = save_quit_label; + common->quit = save_quit; + } + common->positive_assert = save_positive_assert; + common->then_trap = save_then_trap; + common->accept_label = save_accept_label; + common->positive_assert_quit = save_positive_assert_quit; + common->accept = save_accept; + return NULL; + } + set_jumps(altbacktrack.topbacktracks, LABEL()); + + if (*cc != OP_ALT) + break; + + ccbegin = cc; + cc += GET(cc, 1); + } + +if (opcode == OP_ASSERT_NOT || opcode == OP_ASSERTBACK_NOT) + { + SLJIT_ASSERT(common->positive_assert_quit == NULL); + /* Makes the check less complicated below. */ + common->positive_assert_quit = common->quit; + } + +/* None of them matched. */ +if (common->positive_assert_quit != NULL) + { + jump = JUMP(SLJIT_JUMP); + set_jumps(common->positive_assert_quit, LABEL()); + SLJIT_ASSERT(framesize != no_stack); + if (framesize < 0) + OP2(SLJIT_ADD, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr, SLJIT_IMM, extrasize * sizeof(sljit_sw)); + else + { + OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); + add_jump(compiler, &common->revertframes, JUMP(SLJIT_FAST_CALL)); + OP2(SLJIT_ADD, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, (framesize + extrasize) * sizeof(sljit_sw)); + } + JUMPHERE(jump); + } + +if (needs_control_head) + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, SLJIT_MEM1(STACK_TOP), STACK(1)); + +if (opcode == OP_ASSERT || opcode == OP_ASSERTBACK) + { + /* Assert is failed. */ + if (conditional || bra == OP_BRAZERO) + OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); + + if (framesize < 0) + { + /* The topmost item should be 0. */ + if (bra == OP_BRAZERO) + { + if (extrasize == 2) + free_stack(common, 1); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); + } + else + free_stack(common, extrasize); + } + else + { + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(extrasize - 1)); + /* The topmost item should be 0. */ + if (bra == OP_BRAZERO) + { + free_stack(common, framesize + extrasize - 1); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); + } + else + free_stack(common, framesize + extrasize); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, TMP1, 0); + } + jump = JUMP(SLJIT_JUMP); + if (bra != OP_BRAZERO) + add_jump(compiler, target, jump); + + /* Assert is successful. */ + set_jumps(tmp, LABEL()); + if (framesize < 0) + { + /* We know that STR_PTR was stored on the top of the stack. */ + OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), (extrasize - 1) * sizeof(sljit_sw)); + /* Keep the STR_PTR on the top of the stack. */ + if (bra == OP_BRAZERO) + { + OP2(SLJIT_ADD, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, sizeof(sljit_sw)); + if (extrasize == 2) + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); + } + else if (bra == OP_BRAMINZERO) + { + OP2(SLJIT_ADD, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, sizeof(sljit_sw)); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); + } + } + else + { + if (bra == OP_BRA) + { + /* We don't need to keep the STR_PTR, only the previous private_data_ptr. */ + OP2(SLJIT_ADD, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr, SLJIT_IMM, (framesize + 1) * sizeof(sljit_sw)); + OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), (extrasize - 2) * sizeof(sljit_sw)); + } + else + { + /* We don't need to keep the STR_PTR, only the previous private_data_ptr. */ + OP2(SLJIT_ADD, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr, SLJIT_IMM, (framesize + 2) * sizeof(sljit_sw)); + if (extrasize == 2) + { + OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); + if (bra == OP_BRAMINZERO) + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); + } + else + { + OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), 0); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), bra == OP_BRAZERO ? STR_PTR : SLJIT_IMM, 0); + } + } + } + + if (bra == OP_BRAZERO) + { + backtrack->matchingpath = LABEL(); + SET_LABEL(jump, backtrack->matchingpath); + } + else if (bra == OP_BRAMINZERO) + { + JUMPTO(SLJIT_JUMP, backtrack->matchingpath); + JUMPHERE(brajump); + if (framesize >= 0) + { + OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); + add_jump(compiler, &common->revertframes, JUMP(SLJIT_FAST_CALL)); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, SLJIT_MEM1(STACK_TOP), framesize * sizeof(sljit_sw)); + } + set_jumps(backtrack->common.topbacktracks, LABEL()); + } + } +else + { + /* AssertNot is successful. */ + if (framesize < 0) + { + OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); + if (bra != OP_BRA) + { + if (extrasize == 2) + free_stack(common, 1); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); + } + else + free_stack(common, extrasize); + } + else + { + OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(extrasize - 1)); + /* The topmost item should be 0. */ + if (bra != OP_BRA) + { + free_stack(common, framesize + extrasize - 1); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); + } + else + free_stack(common, framesize + extrasize); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, TMP1, 0); + } + + if (bra == OP_BRAZERO) + backtrack->matchingpath = LABEL(); + else if (bra == OP_BRAMINZERO) + { + JUMPTO(SLJIT_JUMP, backtrack->matchingpath); + JUMPHERE(brajump); + } + + if (bra != OP_BRA) + { + SLJIT_ASSERT(found == &backtrack->common.topbacktracks); + set_jumps(backtrack->common.topbacktracks, LABEL()); + backtrack->common.topbacktracks = NULL; + } + } + +if (opcode == OP_ASSERT_NOT || opcode == OP_ASSERTBACK_NOT) + { + common->local_exit = save_local_exit; + common->quit_label = save_quit_label; + common->quit = save_quit; + } +common->positive_assert = save_positive_assert; +common->then_trap = save_then_trap; +common->accept_label = save_accept_label; +common->positive_assert_quit = save_positive_assert_quit; +common->accept = save_accept; +return cc + 1 + LINK_SIZE; +} + +static SLJIT_INLINE void match_once_common(compiler_common *common, pcre_uchar ket, int framesize, int private_data_ptr, BOOL has_alternatives, BOOL needs_control_head) +{ +DEFINE_COMPILER; +int stacksize; + +if (framesize < 0) + { + if (framesize == no_frame) + OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); + else + { + stacksize = needs_control_head ? 1 : 0; + if (ket != OP_KET || has_alternatives) + stacksize++; + free_stack(common, stacksize); + } + + if (needs_control_head) + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), (ket != OP_KET || has_alternatives) ? sizeof(sljit_sw) : 0); + + /* TMP2 which is set here used by OP_KETRMAX below. */ + if (ket == OP_KETRMAX) + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), 0); + else if (ket == OP_KETRMIN) + { + /* Move the STR_PTR to the private_data_ptr. */ + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, SLJIT_MEM1(STACK_TOP), 0); + } + } +else + { + stacksize = (ket != OP_KET || has_alternatives) ? 2 : 1; + OP2(SLJIT_ADD, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr, SLJIT_IMM, (framesize + stacksize) * sizeof(sljit_sw)); + if (needs_control_head) + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), 0); + + if (ket == OP_KETRMAX) + { + /* TMP2 which is set here used by OP_KETRMAX below. */ + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); + } + } +if (needs_control_head) + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, TMP1, 0); +} + +static SLJIT_INLINE int match_capture_common(compiler_common *common, int stacksize, int offset, int private_data_ptr) +{ +DEFINE_COMPILER; + +if (common->capture_last_ptr != 0) + { + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->capture_last_ptr); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->capture_last_ptr, SLJIT_IMM, offset >> 1); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), TMP1, 0); + stacksize++; + } +if (common->optimized_cbracket[offset >> 1] == 0) + { + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset)); + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1)); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), TMP1, 0); + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize + 1), TMP2, 0); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1), STR_PTR, 0); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset), TMP1, 0); + stacksize += 2; + } +return stacksize; +} + +/* + Handling bracketed expressions is probably the most complex part. + + Stack layout naming characters: + S - Push the current STR_PTR + 0 - Push a 0 (NULL) + A - Push the current STR_PTR. Needed for restoring the STR_PTR + before the next alternative. Not pushed if there are no alternatives. + M - Any values pushed by the current alternative. Can be empty, or anything. + C - Push the previous OVECTOR(i), OVECTOR(i+1) and OVECTOR_PRIV(i) to the stack. + L - Push the previous local (pointed by localptr) to the stack + () - opional values stored on the stack + ()* - optonal, can be stored multiple times + + The following list shows the regular expression templates, their PCRE byte codes + and stack layout supported by pcre-sljit. + + (?:) OP_BRA | OP_KET A M + () OP_CBRA | OP_KET C M + (?:)+ OP_BRA | OP_KETRMAX 0 A M S ( A M S )* + OP_SBRA | OP_KETRMAX 0 L M S ( L M S )* + (?:)+? OP_BRA | OP_KETRMIN 0 A M S ( A M S )* + OP_SBRA | OP_KETRMIN 0 L M S ( L M S )* + ()+ OP_CBRA | OP_KETRMAX 0 C M S ( C M S )* + OP_SCBRA | OP_KETRMAX 0 C M S ( C M S )* + ()+? OP_CBRA | OP_KETRMIN 0 C M S ( C M S )* + OP_SCBRA | OP_KETRMIN 0 C M S ( C M S )* + (?:)? OP_BRAZERO | OP_BRA | OP_KET S ( A M 0 ) + (?:)?? OP_BRAMINZERO | OP_BRA | OP_KET S ( A M 0 ) + ()? OP_BRAZERO | OP_CBRA | OP_KET S ( C M 0 ) + ()?? OP_BRAMINZERO | OP_CBRA | OP_KET S ( C M 0 ) + (?:)* OP_BRAZERO | OP_BRA | OP_KETRMAX S 0 ( A M S )* + OP_BRAZERO | OP_SBRA | OP_KETRMAX S 0 ( L M S )* + (?:)*? OP_BRAMINZERO | OP_BRA | OP_KETRMIN S 0 ( A M S )* + OP_BRAMINZERO | OP_SBRA | OP_KETRMIN S 0 ( L M S )* + ()* OP_BRAZERO | OP_CBRA | OP_KETRMAX S 0 ( C M S )* + OP_BRAZERO | OP_SCBRA | OP_KETRMAX S 0 ( C M S )* + ()*? OP_BRAMINZERO | OP_CBRA | OP_KETRMIN S 0 ( C M S )* + OP_BRAMINZERO | OP_SCBRA | OP_KETRMIN S 0 ( C M S )* + + + Stack layout naming characters: + A - Push the alternative index (starting from 0) on the stack. + Not pushed if there is no alternatives. + M - Any values pushed by the current alternative. Can be empty, or anything. + + The next list shows the possible content of a bracket: + (|) OP_*BRA | OP_ALT ... M A + (?()|) OP_*COND | OP_ALT M A + (?>|) OP_ONCE | OP_ALT ... [stack trace] M A + (?>|) OP_ONCE_NC | OP_ALT ... [stack trace] M A + Or nothing, if trace is unnecessary +*/ + +static pcre_uchar *compile_bracket_matchingpath(compiler_common *common, pcre_uchar *cc, backtrack_common *parent) +{ +DEFINE_COMPILER; +backtrack_common *backtrack; +pcre_uchar opcode; +int private_data_ptr = 0; +int offset = 0; +int i, stacksize; +int repeat_ptr = 0, repeat_length = 0; +int repeat_type = 0, repeat_count = 0; +pcre_uchar *ccbegin; +pcre_uchar *matchingpath; +pcre_uchar *slot; +pcre_uchar bra = OP_BRA; +pcre_uchar ket; +assert_backtrack *assert; +BOOL has_alternatives; +BOOL needs_control_head = FALSE; +struct sljit_jump *jump; +struct sljit_jump *skip; +struct sljit_label *rmax_label = NULL; +struct sljit_jump *braminzero = NULL; + +PUSH_BACKTRACK(sizeof(bracket_backtrack), cc, NULL); + +if (*cc == OP_BRAZERO || *cc == OP_BRAMINZERO) + { + bra = *cc; + cc++; + opcode = *cc; + } + +opcode = *cc; +ccbegin = cc; +matchingpath = bracketend(cc) - 1 - LINK_SIZE; +ket = *matchingpath; +if (ket == OP_KET && PRIVATE_DATA(matchingpath) != 0) + { + repeat_ptr = PRIVATE_DATA(matchingpath); + repeat_length = PRIVATE_DATA(matchingpath + 1); + repeat_type = PRIVATE_DATA(matchingpath + 2); + repeat_count = PRIVATE_DATA(matchingpath + 3); + SLJIT_ASSERT(repeat_length != 0 && repeat_type != 0 && repeat_count != 0); + if (repeat_type == OP_UPTO) + ket = OP_KETRMAX; + if (repeat_type == OP_MINUPTO) + ket = OP_KETRMIN; + } + +if ((opcode == OP_COND || opcode == OP_SCOND) && cc[1 + LINK_SIZE] == OP_DEF) + { + /* Drop this bracket_backtrack. */ + parent->top = backtrack->prev; + return matchingpath + 1 + LINK_SIZE + repeat_length; + } + +matchingpath = ccbegin + 1 + LINK_SIZE; +SLJIT_ASSERT(ket == OP_KET || ket == OP_KETRMAX || ket == OP_KETRMIN); +SLJIT_ASSERT(!((bra == OP_BRAZERO && ket == OP_KETRMIN) || (bra == OP_BRAMINZERO && ket == OP_KETRMAX))); +cc += GET(cc, 1); + +has_alternatives = *cc == OP_ALT; +if (SLJIT_UNLIKELY(opcode == OP_COND || opcode == OP_SCOND)) + has_alternatives = (*matchingpath == OP_RREF || *matchingpath == OP_DNRREF) ? FALSE : TRUE; + +if (SLJIT_UNLIKELY(opcode == OP_COND) && (*cc == OP_KETRMAX || *cc == OP_KETRMIN)) + opcode = OP_SCOND; +if (SLJIT_UNLIKELY(opcode == OP_ONCE_NC)) + opcode = OP_ONCE; + +if (opcode == OP_CBRA || opcode == OP_SCBRA) + { + /* Capturing brackets has a pre-allocated space. */ + offset = GET2(ccbegin, 1 + LINK_SIZE); + if (common->optimized_cbracket[offset] == 0) + { + private_data_ptr = OVECTOR_PRIV(offset); + offset <<= 1; + } + else + { + offset <<= 1; + private_data_ptr = OVECTOR(offset); + } + BACKTRACK_AS(bracket_backtrack)->private_data_ptr = private_data_ptr; + matchingpath += IMM2_SIZE; + } +else if (opcode == OP_ONCE || opcode == OP_SBRA || opcode == OP_SCOND) + { + /* Other brackets simply allocate the next entry. */ + private_data_ptr = PRIVATE_DATA(ccbegin); + SLJIT_ASSERT(private_data_ptr != 0); + BACKTRACK_AS(bracket_backtrack)->private_data_ptr = private_data_ptr; + if (opcode == OP_ONCE) + BACKTRACK_AS(bracket_backtrack)->u.framesize = get_framesize(common, ccbegin, NULL, FALSE, &needs_control_head); + } + +/* Instructions before the first alternative. */ +stacksize = 0; +if (ket == OP_KETRMAX || (ket == OP_KETRMIN && bra != OP_BRAMINZERO)) + stacksize++; +if (bra == OP_BRAZERO) + stacksize++; + +if (stacksize > 0) + allocate_stack(common, stacksize); + +stacksize = 0; +if (ket == OP_KETRMAX || (ket == OP_KETRMIN && bra != OP_BRAMINZERO)) + { + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), SLJIT_IMM, 0); + stacksize++; + } + +if (bra == OP_BRAZERO) + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), STR_PTR, 0); + +if (bra == OP_BRAMINZERO) + { + /* This is a backtrack path! (Since the try-path of OP_BRAMINZERO matches to the empty string) */ + OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); + if (ket != OP_KETRMIN) + { + free_stack(common, 1); + braminzero = CMP(SLJIT_C_EQUAL, STR_PTR, 0, SLJIT_IMM, 0); + } + else + { + if (opcode == OP_ONCE || opcode >= OP_SBRA) + { + jump = CMP(SLJIT_C_NOT_EQUAL, STR_PTR, 0, SLJIT_IMM, 0); + OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(1)); + /* Nothing stored during the first run. */ + skip = JUMP(SLJIT_JUMP); + JUMPHERE(jump); + /* Checking zero-length iteration. */ + if (opcode != OP_ONCE || BACKTRACK_AS(bracket_backtrack)->u.framesize < 0) + { + /* When we come from outside, private_data_ptr contains the previous STR_PTR. */ + braminzero = CMP(SLJIT_C_EQUAL, STR_PTR, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); + } + else + { + /* Except when the whole stack frame must be saved. */ + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); + braminzero = CMP(SLJIT_C_EQUAL, STR_PTR, 0, SLJIT_MEM1(TMP1), (BACKTRACK_AS(bracket_backtrack)->u.framesize + 1) * sizeof(sljit_sw)); + } + JUMPHERE(skip); + } + else + { + jump = CMP(SLJIT_C_NOT_EQUAL, STR_PTR, 0, SLJIT_IMM, 0); + OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(1)); + JUMPHERE(jump); + } + } + } + +if (repeat_type != 0) + { + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), repeat_ptr, SLJIT_IMM, repeat_count); + if (repeat_type == OP_EXACT) + rmax_label = LABEL(); + } + +if (ket == OP_KETRMIN) + BACKTRACK_AS(bracket_backtrack)->recursive_matchingpath = LABEL(); + +if (ket == OP_KETRMAX) + { + rmax_label = LABEL(); + if (has_alternatives && opcode != OP_ONCE && opcode < OP_SBRA && repeat_type == 0) + BACKTRACK_AS(bracket_backtrack)->alternative_matchingpath = rmax_label; + } + +/* Handling capturing brackets and alternatives. */ +if (opcode == OP_ONCE) + { + stacksize = 0; + if (needs_control_head) + { + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr); + stacksize++; + } + + if (BACKTRACK_AS(bracket_backtrack)->u.framesize < 0) + { + /* Neither capturing brackets nor recursions are found in the block. */ + if (ket == OP_KETRMIN) + { + stacksize += 2; + if (!needs_control_head) + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); + } + else + { + if (BACKTRACK_AS(bracket_backtrack)->u.framesize == no_frame) + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, STACK_TOP, 0); + if (ket == OP_KETRMAX || has_alternatives) + stacksize++; + } + + if (stacksize > 0) + allocate_stack(common, stacksize); + + stacksize = 0; + if (needs_control_head) + { + stacksize++; + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), TMP2, 0); + } + + if (ket == OP_KETRMIN) + { + if (needs_control_head) + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), STR_PTR, 0); + if (BACKTRACK_AS(bracket_backtrack)->u.framesize == no_frame) + OP2(SLJIT_SUB, SLJIT_MEM1(SLJIT_SP), private_data_ptr, STACK_TOP, 0, SLJIT_IMM, needs_control_head ? (2 * sizeof(sljit_sw)) : sizeof(sljit_sw)); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize + 1), TMP2, 0); + } + else if (ket == OP_KETRMAX || has_alternatives) + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), STR_PTR, 0); + } + else + { + if (ket != OP_KET || has_alternatives) + stacksize++; + + stacksize += BACKTRACK_AS(bracket_backtrack)->u.framesize + 1; + allocate_stack(common, stacksize); + + if (needs_control_head) + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), TMP2, 0); + + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); + OP2(SLJIT_SUB, TMP2, 0, STACK_TOP, 0, SLJIT_IMM, stacksize * sizeof(sljit_sw)); + + stacksize = needs_control_head ? 1 : 0; + if (ket != OP_KET || has_alternatives) + { + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), STR_PTR, 0); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, TMP2, 0); + stacksize++; + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), TMP1, 0); + } + else + { + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, TMP2, 0); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), TMP1, 0); + } + init_frame(common, ccbegin, NULL, BACKTRACK_AS(bracket_backtrack)->u.framesize + stacksize, stacksize + 1, FALSE); + } + } +else if (opcode == OP_CBRA || opcode == OP_SCBRA) + { + /* Saving the previous values. */ + if (common->optimized_cbracket[offset >> 1] != 0) + { + SLJIT_ASSERT(private_data_ptr == OVECTOR(offset)); + allocate_stack(common, 2); + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr + sizeof(sljit_sw)); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, STR_PTR, 0); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), TMP1, 0); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(1), TMP2, 0); + } + else + { + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); + allocate_stack(common, 1); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, STR_PTR, 0); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), TMP2, 0); + } + } +else if (opcode == OP_SBRA || opcode == OP_SCOND) + { + /* Saving the previous value. */ + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); + allocate_stack(common, 1); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, STR_PTR, 0); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), TMP2, 0); + } +else if (has_alternatives) + { + /* Pushing the starting string pointer. */ + allocate_stack(common, 1); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); + } + +/* Generating code for the first alternative. */ +if (opcode == OP_COND || opcode == OP_SCOND) + { + if (*matchingpath == OP_CREF) + { + SLJIT_ASSERT(has_alternatives); + add_jump(compiler, &(BACKTRACK_AS(bracket_backtrack)->u.condfailed), + CMP(SLJIT_C_EQUAL, SLJIT_MEM1(SLJIT_SP), OVECTOR(GET2(matchingpath, 1) << 1), SLJIT_MEM1(SLJIT_SP), OVECTOR(1))); + matchingpath += 1 + IMM2_SIZE; + } + else if (*matchingpath == OP_DNCREF) + { + SLJIT_ASSERT(has_alternatives); + + i = GET2(matchingpath, 1 + IMM2_SIZE); + slot = common->name_table + GET2(matchingpath, 1) * common->name_entry_size; + OP1(SLJIT_MOV, TMP3, 0, STR_PTR, 0); + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(1)); + OP2(SLJIT_SUB | SLJIT_SET_E, TMP2, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(GET2(slot, 0) << 1), TMP1, 0); + slot += common->name_entry_size; + i--; + while (i-- > 0) + { + OP2(SLJIT_SUB, STR_PTR, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(GET2(slot, 0) << 1), TMP1, 0); + OP2(SLJIT_OR | SLJIT_SET_E, TMP2, 0, TMP2, 0, STR_PTR, 0); + slot += common->name_entry_size; + } + OP1(SLJIT_MOV, STR_PTR, 0, TMP3, 0); + add_jump(compiler, &(BACKTRACK_AS(bracket_backtrack)->u.condfailed), JUMP(SLJIT_C_ZERO)); + matchingpath += 1 + 2 * IMM2_SIZE; + } + else if (*matchingpath == OP_RREF || *matchingpath == OP_DNRREF) + { + /* Never has other case. */ + BACKTRACK_AS(bracket_backtrack)->u.condfailed = NULL; + SLJIT_ASSERT(!has_alternatives); + + if (*matchingpath == OP_RREF) + { + stacksize = GET2(matchingpath, 1); + if (common->currententry == NULL) + stacksize = 0; + else if (stacksize == RREF_ANY) + stacksize = 1; + else if (common->currententry->start == 0) + stacksize = stacksize == 0; + else + stacksize = stacksize == (int)GET2(common->start, common->currententry->start + 1 + LINK_SIZE); + + if (stacksize != 0) + matchingpath += 1 + IMM2_SIZE; + } + else + { + if (common->currententry == NULL || common->currententry->start == 0) + stacksize = 0; + else + { + stacksize = GET2(matchingpath, 1 + IMM2_SIZE); + slot = common->name_table + GET2(matchingpath, 1) * common->name_entry_size; + i = (int)GET2(common->start, common->currententry->start + 1 + LINK_SIZE); + while (stacksize > 0) + { + if ((int)GET2(slot, 0) == i) + break; + slot += common->name_entry_size; + stacksize--; + } + } + + if (stacksize != 0) + matchingpath += 1 + 2 * IMM2_SIZE; + } + + /* The stacksize == 0 is a common "else" case. */ + if (stacksize == 0) + { + if (*cc == OP_ALT) + { + matchingpath = cc + 1 + LINK_SIZE; + cc += GET(cc, 1); + } + else + matchingpath = cc; + } + } + else + { + SLJIT_ASSERT(has_alternatives && *matchingpath >= OP_ASSERT && *matchingpath <= OP_ASSERTBACK_NOT); + /* Similar code as PUSH_BACKTRACK macro. */ + assert = sljit_alloc_memory(compiler, sizeof(assert_backtrack)); + if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) + return NULL; + memset(assert, 0, sizeof(assert_backtrack)); + assert->common.cc = matchingpath; + BACKTRACK_AS(bracket_backtrack)->u.assert = assert; + matchingpath = compile_assert_matchingpath(common, matchingpath, assert, TRUE); + } + } + +compile_matchingpath(common, matchingpath, cc, backtrack); +if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) + return NULL; + +if (opcode == OP_ONCE) + match_once_common(common, ket, BACKTRACK_AS(bracket_backtrack)->u.framesize, private_data_ptr, has_alternatives, needs_control_head); + +stacksize = 0; +if (repeat_type == OP_MINUPTO) + { + /* We need to preserve the counter. TMP2 will be used below. */ + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), repeat_ptr); + stacksize++; + } +if (ket != OP_KET || bra != OP_BRA) + stacksize++; +if (offset != 0) + { + if (common->capture_last_ptr != 0) + stacksize++; + if (common->optimized_cbracket[offset >> 1] == 0) + stacksize += 2; + } +if (has_alternatives && opcode != OP_ONCE) + stacksize++; + +if (stacksize > 0) + allocate_stack(common, stacksize); + +stacksize = 0; +if (repeat_type == OP_MINUPTO) + { + /* TMP2 was set above. */ + OP2(SLJIT_SUB, SLJIT_MEM1(STACK_TOP), STACK(stacksize), TMP2, 0, SLJIT_IMM, 1); + stacksize++; + } + +if (ket != OP_KET || bra != OP_BRA) + { + if (ket != OP_KET) + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), STR_PTR, 0); + else + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), SLJIT_IMM, 0); + stacksize++; + } + +if (offset != 0) + stacksize = match_capture_common(common, stacksize, offset, private_data_ptr); + +if (has_alternatives) + { + if (opcode != OP_ONCE) + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), SLJIT_IMM, 0); + if (ket != OP_KETRMAX) + BACKTRACK_AS(bracket_backtrack)->alternative_matchingpath = LABEL(); + } + +/* Must be after the matchingpath label. */ +if (offset != 0 && common->optimized_cbracket[offset >> 1] != 0) + { + SLJIT_ASSERT(private_data_ptr == OVECTOR(offset + 0)); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1), STR_PTR, 0); + } + +if (ket == OP_KETRMAX) + { + if (repeat_type != 0) + { + if (has_alternatives) + BACKTRACK_AS(bracket_backtrack)->alternative_matchingpath = LABEL(); + OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_MEM1(SLJIT_SP), repeat_ptr, SLJIT_MEM1(SLJIT_SP), repeat_ptr, SLJIT_IMM, 1); + JUMPTO(SLJIT_C_NOT_ZERO, rmax_label); + /* Drop STR_PTR for greedy plus quantifier. */ + if (opcode != OP_ONCE) + free_stack(common, 1); + } + else if (opcode == OP_ONCE || opcode >= OP_SBRA) + { + if (has_alternatives) + BACKTRACK_AS(bracket_backtrack)->alternative_matchingpath = LABEL(); + /* Checking zero-length iteration. */ + if (opcode != OP_ONCE) + { + CMPTO(SLJIT_C_NOT_EQUAL, SLJIT_MEM1(SLJIT_SP), private_data_ptr, STR_PTR, 0, rmax_label); + /* Drop STR_PTR for greedy plus quantifier. */ + if (bra != OP_BRAZERO) + free_stack(common, 1); + } + else + /* TMP2 must contain the starting STR_PTR. */ + CMPTO(SLJIT_C_NOT_EQUAL, TMP2, 0, STR_PTR, 0, rmax_label); + } + else + JUMPTO(SLJIT_JUMP, rmax_label); + BACKTRACK_AS(bracket_backtrack)->recursive_matchingpath = LABEL(); + } + +if (repeat_type == OP_EXACT) + { + count_match(common); + OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_MEM1(SLJIT_SP), repeat_ptr, SLJIT_MEM1(SLJIT_SP), repeat_ptr, SLJIT_IMM, 1); + JUMPTO(SLJIT_C_NOT_ZERO, rmax_label); + } +else if (repeat_type == OP_UPTO) + { + /* We need to preserve the counter. */ + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), repeat_ptr); + allocate_stack(common, 1); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), TMP2, 0); + } + +if (bra == OP_BRAZERO) + BACKTRACK_AS(bracket_backtrack)->zero_matchingpath = LABEL(); + +if (bra == OP_BRAMINZERO) + { + /* This is a backtrack path! (From the viewpoint of OP_BRAMINZERO) */ + JUMPTO(SLJIT_JUMP, ((braminzero_backtrack *)parent)->matchingpath); + if (braminzero != NULL) + { + JUMPHERE(braminzero); + /* We need to release the end pointer to perform the + backtrack for the zero-length iteration. When + framesize is < 0, OP_ONCE will do the release itself. */ + if (opcode == OP_ONCE && BACKTRACK_AS(bracket_backtrack)->u.framesize >= 0) + { + OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); + add_jump(compiler, &common->revertframes, JUMP(SLJIT_FAST_CALL)); + } + else if (ket == OP_KETRMIN && opcode != OP_ONCE) + free_stack(common, 1); + } + /* Continue to the normal backtrack. */ + } + +if ((ket != OP_KET && bra != OP_BRAMINZERO) || bra == OP_BRAZERO) + count_match(common); + +/* Skip the other alternatives. */ +while (*cc == OP_ALT) + cc += GET(cc, 1); +cc += 1 + LINK_SIZE; + +/* Temporarily encoding the needs_control_head in framesize. */ +if (opcode == OP_ONCE) + BACKTRACK_AS(bracket_backtrack)->u.framesize = (BACKTRACK_AS(bracket_backtrack)->u.framesize << 1) | (needs_control_head ? 1 : 0); +return cc + repeat_length; +} + +static pcre_uchar *compile_bracketpos_matchingpath(compiler_common *common, pcre_uchar *cc, backtrack_common *parent) +{ +DEFINE_COMPILER; +backtrack_common *backtrack; +pcre_uchar opcode; +int private_data_ptr; +int cbraprivptr = 0; +BOOL needs_control_head; +int framesize; +int stacksize; +int offset = 0; +BOOL zero = FALSE; +pcre_uchar *ccbegin = NULL; +int stack; /* Also contains the offset of control head. */ +struct sljit_label *loop = NULL; +struct jump_list *emptymatch = NULL; + +PUSH_BACKTRACK(sizeof(bracketpos_backtrack), cc, NULL); +if (*cc == OP_BRAPOSZERO) + { + zero = TRUE; + cc++; + } + +opcode = *cc; +private_data_ptr = PRIVATE_DATA(cc); +SLJIT_ASSERT(private_data_ptr != 0); +BACKTRACK_AS(bracketpos_backtrack)->private_data_ptr = private_data_ptr; +switch(opcode) + { + case OP_BRAPOS: + case OP_SBRAPOS: + ccbegin = cc + 1 + LINK_SIZE; + break; + + case OP_CBRAPOS: + case OP_SCBRAPOS: + offset = GET2(cc, 1 + LINK_SIZE); + /* This case cannot be optimized in the same was as + normal capturing brackets. */ + SLJIT_ASSERT(common->optimized_cbracket[offset] == 0); + cbraprivptr = OVECTOR_PRIV(offset); + offset <<= 1; + ccbegin = cc + 1 + LINK_SIZE + IMM2_SIZE; + break; + + default: + SLJIT_ASSERT_STOP(); + break; + } + +framesize = get_framesize(common, cc, NULL, FALSE, &needs_control_head); +BACKTRACK_AS(bracketpos_backtrack)->framesize = framesize; +if (framesize < 0) + { + if (offset != 0) + { + stacksize = 2; + if (common->capture_last_ptr != 0) + stacksize++; + } + else + stacksize = 1; + + if (needs_control_head) + stacksize++; + if (!zero) + stacksize++; + + BACKTRACK_AS(bracketpos_backtrack)->stacksize = stacksize; + allocate_stack(common, stacksize); + if (framesize == no_frame) + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, STACK_TOP, 0); + + stack = 0; + if (offset != 0) + { + stack = 2; + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset)); + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1)); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), TMP1, 0); + if (common->capture_last_ptr != 0) + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->capture_last_ptr); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(1), TMP2, 0); + if (needs_control_head) + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr); + if (common->capture_last_ptr != 0) + { + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(2), TMP1, 0); + stack = 3; + } + } + else + { + if (needs_control_head) + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); + stack = 1; + } + + if (needs_control_head) + stack++; + if (!zero) + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stack), SLJIT_IMM, 1); + if (needs_control_head) + { + stack--; + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stack), TMP2, 0); + } + } +else + { + stacksize = framesize + 1; + if (!zero) + stacksize++; + if (needs_control_head) + stacksize++; + if (offset == 0) + stacksize++; + BACKTRACK_AS(bracketpos_backtrack)->stacksize = stacksize; + + allocate_stack(common, stacksize); + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); + if (needs_control_head) + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr); + OP2(SLJIT_SUB, SLJIT_MEM1(SLJIT_SP), private_data_ptr, STACK_TOP, 0, SLJIT_IMM, -STACK(stacksize - 1)); + + stack = 0; + if (!zero) + { + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 1); + stack = 1; + } + if (needs_control_head) + { + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stack), TMP2, 0); + stack++; + } + if (offset == 0) + { + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stack), STR_PTR, 0); + stack++; + } + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stack), TMP1, 0); + init_frame(common, cc, NULL, stacksize - 1, stacksize - framesize, FALSE); + stack -= 1 + (offset == 0); + } + +if (offset != 0) + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), cbraprivptr, STR_PTR, 0); + +loop = LABEL(); +while (*cc != OP_KETRPOS) + { + backtrack->top = NULL; + backtrack->topbacktracks = NULL; + cc += GET(cc, 1); + + compile_matchingpath(common, ccbegin, cc, backtrack); + if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) + return NULL; + + if (framesize < 0) + { + if (framesize == no_frame) + OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); + + if (offset != 0) + { + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), cbraprivptr); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1), STR_PTR, 0); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), cbraprivptr, STR_PTR, 0); + if (common->capture_last_ptr != 0) + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->capture_last_ptr, SLJIT_IMM, offset >> 1); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset), TMP1, 0); + } + else + { + if (opcode == OP_SBRAPOS) + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); + } + + if (opcode == OP_SBRAPOS || opcode == OP_SCBRAPOS) + add_jump(compiler, &emptymatch, CMP(SLJIT_C_EQUAL, TMP1, 0, STR_PTR, 0)); + + if (!zero) + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize - 1), SLJIT_IMM, 0); + } + else + { + if (offset != 0) + { + OP2(SLJIT_ADD, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr, SLJIT_IMM, stacksize * sizeof(sljit_sw)); + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), cbraprivptr); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1), STR_PTR, 0); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), cbraprivptr, STR_PTR, 0); + if (common->capture_last_ptr != 0) + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->capture_last_ptr, SLJIT_IMM, offset >> 1); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset), TMP1, 0); + } + else + { + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); + OP2(SLJIT_ADD, STACK_TOP, 0, TMP2, 0, SLJIT_IMM, stacksize * sizeof(sljit_sw)); + if (opcode == OP_SBRAPOS) + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(TMP2), (framesize + 1) * sizeof(sljit_sw)); + OP1(SLJIT_MOV, SLJIT_MEM1(TMP2), (framesize + 1) * sizeof(sljit_sw), STR_PTR, 0); + } + + if (opcode == OP_SBRAPOS || opcode == OP_SCBRAPOS) + add_jump(compiler, &emptymatch, CMP(SLJIT_C_EQUAL, TMP1, 0, STR_PTR, 0)); + + if (!zero) + { + if (framesize < 0) + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize - 1), SLJIT_IMM, 0); + else + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); + } + } + + if (needs_control_head) + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, SLJIT_MEM1(STACK_TOP), STACK(stack)); + + JUMPTO(SLJIT_JUMP, loop); + flush_stubs(common); + + compile_backtrackingpath(common, backtrack->top); + if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) + return NULL; + set_jumps(backtrack->topbacktracks, LABEL()); + + if (framesize < 0) + { + if (offset != 0) + OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(SLJIT_SP), cbraprivptr); + else + OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); + } + else + { + if (offset != 0) + { + /* Last alternative. */ + if (*cc == OP_KETRPOS) + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); + OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(SLJIT_SP), cbraprivptr); + } + else + { + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); + OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(TMP2), (framesize + 1) * sizeof(sljit_sw)); + } + } + + if (*cc == OP_KETRPOS) + break; + ccbegin = cc + 1 + LINK_SIZE; + } + +/* We don't have to restore the control head in case of a failed match. */ + +backtrack->topbacktracks = NULL; +if (!zero) + { + if (framesize < 0) + add_jump(compiler, &backtrack->topbacktracks, CMP(SLJIT_C_NOT_EQUAL, SLJIT_MEM1(STACK_TOP), STACK(stacksize - 1), SLJIT_IMM, 0)); + else /* TMP2 is set to [private_data_ptr] above. */ + add_jump(compiler, &backtrack->topbacktracks, CMP(SLJIT_C_NOT_EQUAL, SLJIT_MEM1(TMP2), (stacksize - 1) * sizeof(sljit_sw), SLJIT_IMM, 0)); + } + +/* None of them matched. */ +set_jumps(emptymatch, LABEL()); +count_match(common); +return cc + 1 + LINK_SIZE; +} + +static SLJIT_INLINE pcre_uchar *get_iterator_parameters(compiler_common *common, pcre_uchar *cc, pcre_uchar *opcode, pcre_uchar *type, int *max, int *min, pcre_uchar **end) +{ +int class_len; + +*opcode = *cc; +if (*opcode >= OP_STAR && *opcode <= OP_POSUPTO) + { + cc++; + *type = OP_CHAR; + } +else if (*opcode >= OP_STARI && *opcode <= OP_POSUPTOI) + { + cc++; + *type = OP_CHARI; + *opcode -= OP_STARI - OP_STAR; + } +else if (*opcode >= OP_NOTSTAR && *opcode <= OP_NOTPOSUPTO) + { + cc++; + *type = OP_NOT; + *opcode -= OP_NOTSTAR - OP_STAR; + } +else if (*opcode >= OP_NOTSTARI && *opcode <= OP_NOTPOSUPTOI) + { + cc++; + *type = OP_NOTI; + *opcode -= OP_NOTSTARI - OP_STAR; + } +else if (*opcode >= OP_TYPESTAR && *opcode <= OP_TYPEPOSUPTO) + { + cc++; + *opcode -= OP_TYPESTAR - OP_STAR; + *type = 0; + } +else + { + SLJIT_ASSERT(*opcode == OP_CLASS || *opcode == OP_NCLASS || *opcode == OP_XCLASS); + *type = *opcode; + cc++; + class_len = (*type < OP_XCLASS) ? (int)(1 + (32 / sizeof(pcre_uchar))) : GET(cc, 0); + *opcode = cc[class_len - 1]; + if (*opcode >= OP_CRSTAR && *opcode <= OP_CRMINQUERY) + { + *opcode -= OP_CRSTAR - OP_STAR; + if (end != NULL) + *end = cc + class_len; + } + else if (*opcode >= OP_CRPOSSTAR && *opcode <= OP_CRPOSQUERY) + { + *opcode -= OP_CRPOSSTAR - OP_POSSTAR; + if (end != NULL) + *end = cc + class_len; + } + else + { + SLJIT_ASSERT(*opcode == OP_CRRANGE || *opcode == OP_CRMINRANGE || *opcode == OP_CRPOSRANGE); + *max = GET2(cc, (class_len + IMM2_SIZE)); + *min = GET2(cc, class_len); + + if (*min == 0) + { + SLJIT_ASSERT(*max != 0); + *opcode = (*opcode == OP_CRRANGE) ? OP_UPTO : (*opcode == OP_CRMINRANGE ? OP_MINUPTO : OP_POSUPTO); + } + if (*max == *min) + *opcode = OP_EXACT; + + if (end != NULL) + *end = cc + class_len + 2 * IMM2_SIZE; + } + return cc; + } + +if (*opcode == OP_UPTO || *opcode == OP_MINUPTO || *opcode == OP_EXACT || *opcode == OP_POSUPTO) + { + *max = GET2(cc, 0); + cc += IMM2_SIZE; + } + +if (*type == 0) + { + *type = *cc; + if (end != NULL) + *end = next_opcode(common, cc); + cc++; + return cc; + } + +if (end != NULL) + { + *end = cc + 1; +#ifdef SUPPORT_UTF + if (common->utf && HAS_EXTRALEN(*cc)) *end += GET_EXTRALEN(*cc); +#endif + } +return cc; +} + +static pcre_uchar *compile_iterator_matchingpath(compiler_common *common, pcre_uchar *cc, backtrack_common *parent) +{ +DEFINE_COMPILER; +backtrack_common *backtrack; +pcre_uchar opcode; +pcre_uchar type; +int max = -1, min = -1; +pcre_uchar* end; +jump_list *nomatch = NULL; +struct sljit_jump *jump = NULL; +struct sljit_label *label; +int private_data_ptr = PRIVATE_DATA(cc); +int base = (private_data_ptr == 0) ? SLJIT_MEM1(STACK_TOP) : SLJIT_MEM1(SLJIT_SP); +int offset0 = (private_data_ptr == 0) ? STACK(0) : private_data_ptr; +int offset1 = (private_data_ptr == 0) ? STACK(1) : private_data_ptr + (int)sizeof(sljit_sw); +int tmp_base, tmp_offset; + +PUSH_BACKTRACK(sizeof(iterator_backtrack), cc, NULL); + +cc = get_iterator_parameters(common, cc, &opcode, &type, &max, &min, &end); + +switch(type) + { + case OP_NOT_DIGIT: + case OP_DIGIT: + case OP_NOT_WHITESPACE: + case OP_WHITESPACE: + case OP_NOT_WORDCHAR: + case OP_WORDCHAR: + case OP_ANY: + case OP_ALLANY: + case OP_ANYBYTE: + case OP_ANYNL: + case OP_NOT_HSPACE: + case OP_HSPACE: + case OP_NOT_VSPACE: + case OP_VSPACE: + case OP_CHAR: + case OP_CHARI: + case OP_NOT: + case OP_NOTI: + case OP_CLASS: + case OP_NCLASS: + tmp_base = TMP3; + tmp_offset = 0; + break; + + default: + SLJIT_ASSERT_STOP(); + /* Fall through. */ + + case OP_EXTUNI: + case OP_XCLASS: + case OP_NOTPROP: + case OP_PROP: + tmp_base = SLJIT_MEM1(SLJIT_SP); + tmp_offset = POSSESSIVE0; + break; + } + +switch(opcode) + { + case OP_STAR: + case OP_PLUS: + case OP_UPTO: + case OP_CRRANGE: + if (type == OP_ANYNL || type == OP_EXTUNI) + { + SLJIT_ASSERT(private_data_ptr == 0); + if (opcode == OP_STAR || opcode == OP_UPTO) + { + allocate_stack(common, 2); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(1), SLJIT_IMM, 0); + } + else + { + allocate_stack(common, 1); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); + } + + if (opcode == OP_UPTO || opcode == OP_CRRANGE) + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), POSSESSIVE0, SLJIT_IMM, 0); + + label = LABEL(); + compile_char1_matchingpath(common, type, cc, &backtrack->topbacktracks); + if (opcode == OP_UPTO || opcode == OP_CRRANGE) + { + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), POSSESSIVE0); + OP2(SLJIT_ADD, TMP1, 0, TMP1, 0, SLJIT_IMM, 1); + if (opcode == OP_CRRANGE && min > 0) + CMPTO(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, min, label); + if (opcode == OP_UPTO || (opcode == OP_CRRANGE && max > 0)) + jump = CMP(SLJIT_C_GREATER_EQUAL, TMP1, 0, SLJIT_IMM, max); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), POSSESSIVE0, TMP1, 0); + } + + /* We cannot use TMP3 because of this allocate_stack. */ + allocate_stack(common, 1); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); + JUMPTO(SLJIT_JUMP, label); + if (jump != NULL) + JUMPHERE(jump); + } + else + { + if (opcode == OP_PLUS) + compile_char1_matchingpath(common, type, cc, &backtrack->topbacktracks); + if (private_data_ptr == 0) + allocate_stack(common, 2); + OP1(SLJIT_MOV, base, offset0, STR_PTR, 0); + if (opcode <= OP_PLUS) + OP1(SLJIT_MOV, base, offset1, STR_PTR, 0); + else + OP1(SLJIT_MOV, base, offset1, SLJIT_IMM, 1); + label = LABEL(); + compile_char1_matchingpath(common, type, cc, &nomatch); + OP1(SLJIT_MOV, base, offset0, STR_PTR, 0); + if (opcode <= OP_PLUS) + JUMPTO(SLJIT_JUMP, label); + else if (opcode == OP_CRRANGE && max == 0) + { + OP2(SLJIT_ADD, base, offset1, base, offset1, SLJIT_IMM, 1); + JUMPTO(SLJIT_JUMP, label); + } + else + { + OP1(SLJIT_MOV, TMP1, 0, base, offset1); + OP2(SLJIT_ADD, TMP1, 0, TMP1, 0, SLJIT_IMM, 1); + OP1(SLJIT_MOV, base, offset1, TMP1, 0); + CMPTO(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, max + 1, label); + } + set_jumps(nomatch, LABEL()); + if (opcode == OP_CRRANGE) + add_jump(compiler, &backtrack->topbacktracks, CMP(SLJIT_C_LESS, base, offset1, SLJIT_IMM, min + 1)); + OP1(SLJIT_MOV, STR_PTR, 0, base, offset0); + } + BACKTRACK_AS(iterator_backtrack)->matchingpath = LABEL(); + break; + + case OP_MINSTAR: + case OP_MINPLUS: + if (opcode == OP_MINPLUS) + compile_char1_matchingpath(common, type, cc, &backtrack->topbacktracks); + if (private_data_ptr == 0) + allocate_stack(common, 1); + OP1(SLJIT_MOV, base, offset0, STR_PTR, 0); + BACKTRACK_AS(iterator_backtrack)->matchingpath = LABEL(); + break; + + case OP_MINUPTO: + case OP_CRMINRANGE: + if (private_data_ptr == 0) + allocate_stack(common, 2); + OP1(SLJIT_MOV, base, offset0, STR_PTR, 0); + OP1(SLJIT_MOV, base, offset1, SLJIT_IMM, 1); + if (opcode == OP_CRMINRANGE) + add_jump(compiler, &backtrack->topbacktracks, JUMP(SLJIT_JUMP)); + BACKTRACK_AS(iterator_backtrack)->matchingpath = LABEL(); + break; + + case OP_QUERY: + case OP_MINQUERY: + if (private_data_ptr == 0) + allocate_stack(common, 1); + OP1(SLJIT_MOV, base, offset0, STR_PTR, 0); + if (opcode == OP_QUERY) + compile_char1_matchingpath(common, type, cc, &backtrack->topbacktracks); + BACKTRACK_AS(iterator_backtrack)->matchingpath = LABEL(); + break; + + case OP_EXACT: + OP1(SLJIT_MOV, tmp_base, tmp_offset, SLJIT_IMM, max); + label = LABEL(); + compile_char1_matchingpath(common, type, cc, &backtrack->topbacktracks); + OP2(SLJIT_SUB | SLJIT_SET_E, tmp_base, tmp_offset, tmp_base, tmp_offset, SLJIT_IMM, 1); + JUMPTO(SLJIT_C_NOT_ZERO, label); + break; + + case OP_POSSTAR: + case OP_POSPLUS: + case OP_POSUPTO: + if (opcode == OP_POSPLUS) + compile_char1_matchingpath(common, type, cc, &backtrack->topbacktracks); + if (opcode == OP_POSUPTO) + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), POSSESSIVE1, SLJIT_IMM, max); + OP1(SLJIT_MOV, tmp_base, tmp_offset, STR_PTR, 0); + label = LABEL(); + compile_char1_matchingpath(common, type, cc, &nomatch); + OP1(SLJIT_MOV, tmp_base, tmp_offset, STR_PTR, 0); + if (opcode != OP_POSUPTO) + JUMPTO(SLJIT_JUMP, label); + else + { + OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_MEM1(SLJIT_SP), POSSESSIVE1, SLJIT_MEM1(SLJIT_SP), POSSESSIVE1, SLJIT_IMM, 1); + JUMPTO(SLJIT_C_NOT_ZERO, label); + } + set_jumps(nomatch, LABEL()); + OP1(SLJIT_MOV, STR_PTR, 0, tmp_base, tmp_offset); + break; + + case OP_POSQUERY: + OP1(SLJIT_MOV, tmp_base, tmp_offset, STR_PTR, 0); + compile_char1_matchingpath(common, type, cc, &nomatch); + OP1(SLJIT_MOV, tmp_base, tmp_offset, STR_PTR, 0); + set_jumps(nomatch, LABEL()); + OP1(SLJIT_MOV, STR_PTR, 0, tmp_base, tmp_offset); + break; + + case OP_CRPOSRANGE: + /* Combination of OP_EXACT and OP_POSSTAR or OP_POSUPTO */ + OP1(SLJIT_MOV, tmp_base, tmp_offset, SLJIT_IMM, min); + label = LABEL(); + compile_char1_matchingpath(common, type, cc, &backtrack->topbacktracks); + OP2(SLJIT_SUB | SLJIT_SET_E, tmp_base, tmp_offset, tmp_base, tmp_offset, SLJIT_IMM, 1); + JUMPTO(SLJIT_C_NOT_ZERO, label); + + if (max != 0) + { + SLJIT_ASSERT(max - min > 0); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), POSSESSIVE1, SLJIT_IMM, max - min); + } + OP1(SLJIT_MOV, tmp_base, tmp_offset, STR_PTR, 0); + label = LABEL(); + compile_char1_matchingpath(common, type, cc, &nomatch); + OP1(SLJIT_MOV, tmp_base, tmp_offset, STR_PTR, 0); + if (max == 0) + JUMPTO(SLJIT_JUMP, label); + else + { + OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_MEM1(SLJIT_SP), POSSESSIVE1, SLJIT_MEM1(SLJIT_SP), POSSESSIVE1, SLJIT_IMM, 1); + JUMPTO(SLJIT_C_NOT_ZERO, label); + } + set_jumps(nomatch, LABEL()); + OP1(SLJIT_MOV, STR_PTR, 0, tmp_base, tmp_offset); + break; + + default: + SLJIT_ASSERT_STOP(); + break; + } + +count_match(common); +return end; +} + +static SLJIT_INLINE pcre_uchar *compile_fail_accept_matchingpath(compiler_common *common, pcre_uchar *cc, backtrack_common *parent) +{ +DEFINE_COMPILER; +backtrack_common *backtrack; + +PUSH_BACKTRACK(sizeof(backtrack_common), cc, NULL); + +if (*cc == OP_FAIL) + { + add_jump(compiler, &backtrack->topbacktracks, JUMP(SLJIT_JUMP)); + return cc + 1; + } + +if (*cc == OP_ASSERT_ACCEPT || common->currententry != NULL || !common->might_be_empty) + { + /* No need to check notempty conditions. */ + if (common->accept_label == NULL) + add_jump(compiler, &common->accept, JUMP(SLJIT_JUMP)); + else + JUMPTO(SLJIT_JUMP, common->accept_label); + return cc + 1; + } + +if (common->accept_label == NULL) + add_jump(compiler, &common->accept, CMP(SLJIT_C_NOT_EQUAL, STR_PTR, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(0))); +else + CMPTO(SLJIT_C_NOT_EQUAL, STR_PTR, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(0), common->accept_label); +OP1(SLJIT_MOV, TMP1, 0, ARGUMENTS, 0); +OP1(SLJIT_MOV_UB, TMP2, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, notempty)); +add_jump(compiler, &backtrack->topbacktracks, CMP(SLJIT_C_NOT_EQUAL, TMP2, 0, SLJIT_IMM, 0)); +OP1(SLJIT_MOV_UB, TMP2, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, notempty_atstart)); +if (common->accept_label == NULL) + add_jump(compiler, &common->accept, CMP(SLJIT_C_EQUAL, TMP2, 0, SLJIT_IMM, 0)); +else + CMPTO(SLJIT_C_EQUAL, TMP2, 0, SLJIT_IMM, 0, common->accept_label); +OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, str)); +if (common->accept_label == NULL) + add_jump(compiler, &common->accept, CMP(SLJIT_C_NOT_EQUAL, TMP2, 0, STR_PTR, 0)); +else + CMPTO(SLJIT_C_NOT_EQUAL, TMP2, 0, STR_PTR, 0, common->accept_label); +add_jump(compiler, &backtrack->topbacktracks, JUMP(SLJIT_JUMP)); +return cc + 1; +} + +static SLJIT_INLINE pcre_uchar *compile_close_matchingpath(compiler_common *common, pcre_uchar *cc) +{ +DEFINE_COMPILER; +int offset = GET2(cc, 1); +BOOL optimized_cbracket = common->optimized_cbracket[offset] != 0; + +/* Data will be discarded anyway... */ +if (common->currententry != NULL) + return cc + 1 + IMM2_SIZE; + +if (!optimized_cbracket) + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR_PRIV(offset)); +offset <<= 1; +OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1), STR_PTR, 0); +if (!optimized_cbracket) + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset), TMP1, 0); +return cc + 1 + IMM2_SIZE; +} + +static SLJIT_INLINE pcre_uchar *compile_control_verb_matchingpath(compiler_common *common, pcre_uchar *cc, backtrack_common *parent) +{ +DEFINE_COMPILER; +backtrack_common *backtrack; +pcre_uchar opcode = *cc; +pcre_uchar *ccend = cc + 1; + +if (opcode == OP_PRUNE_ARG || opcode == OP_SKIP_ARG || opcode == OP_THEN_ARG) + ccend += 2 + cc[1]; + +PUSH_BACKTRACK(sizeof(backtrack_common), cc, NULL); + +if (opcode == OP_SKIP) + { + allocate_stack(common, 1); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); + return ccend; + } + +if (opcode == OP_PRUNE_ARG || opcode == OP_THEN_ARG) + { + OP1(SLJIT_MOV, TMP1, 0, ARGUMENTS, 0); + OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, (sljit_sw)(cc + 2)); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->mark_ptr, TMP2, 0); + OP1(SLJIT_MOV, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, mark_ptr), TMP2, 0); + } + +return ccend; +} + +static pcre_uchar then_trap_opcode[1] = { OP_THEN_TRAP }; + +static SLJIT_INLINE void compile_then_trap_matchingpath(compiler_common *common, pcre_uchar *cc, pcre_uchar *ccend, backtrack_common *parent) +{ +DEFINE_COMPILER; +backtrack_common *backtrack; +BOOL needs_control_head; +int size; + +PUSH_BACKTRACK_NOVALUE(sizeof(then_trap_backtrack), cc); +common->then_trap = BACKTRACK_AS(then_trap_backtrack); +BACKTRACK_AS(then_trap_backtrack)->common.cc = then_trap_opcode; +BACKTRACK_AS(then_trap_backtrack)->start = (sljit_sw)(cc - common->start); +BACKTRACK_AS(then_trap_backtrack)->framesize = get_framesize(common, cc, ccend, FALSE, &needs_control_head); + +size = BACKTRACK_AS(then_trap_backtrack)->framesize; +size = 3 + (size < 0 ? 0 : size); + +OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr); +allocate_stack(common, size); +if (size > 3) + OP2(SLJIT_SUB, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, STACK_TOP, 0, SLJIT_IMM, (size - 3) * sizeof(sljit_sw)); +else + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, STACK_TOP, 0); +OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(size - 1), SLJIT_IMM, BACKTRACK_AS(then_trap_backtrack)->start); +OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(size - 2), SLJIT_IMM, type_then_trap); +OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(size - 3), TMP2, 0); + +size = BACKTRACK_AS(then_trap_backtrack)->framesize; +if (size >= 0) + init_frame(common, cc, ccend, size - 1, 0, FALSE); +} + +static void compile_matchingpath(compiler_common *common, pcre_uchar *cc, pcre_uchar *ccend, backtrack_common *parent) +{ +DEFINE_COMPILER; +backtrack_common *backtrack; +BOOL has_then_trap = FALSE; +then_trap_backtrack *save_then_trap = NULL; + +SLJIT_ASSERT(*ccend == OP_END || (*ccend >= OP_ALT && *ccend <= OP_KETRPOS)); + +if (common->has_then && common->then_offsets[cc - common->start] != 0) + { + SLJIT_ASSERT(*ccend != OP_END && common->control_head_ptr != 0); + has_then_trap = TRUE; + save_then_trap = common->then_trap; + /* Tail item on backtrack. */ + compile_then_trap_matchingpath(common, cc, ccend, parent); + } + +while (cc < ccend) + { + switch(*cc) + { + case OP_SOD: + case OP_SOM: + case OP_NOT_WORD_BOUNDARY: + case OP_WORD_BOUNDARY: + case OP_NOT_DIGIT: + case OP_DIGIT: + case OP_NOT_WHITESPACE: + case OP_WHITESPACE: + case OP_NOT_WORDCHAR: + case OP_WORDCHAR: + case OP_ANY: + case OP_ALLANY: + case OP_ANYBYTE: + case OP_NOTPROP: + case OP_PROP: + case OP_ANYNL: + case OP_NOT_HSPACE: + case OP_HSPACE: + case OP_NOT_VSPACE: + case OP_VSPACE: + case OP_EXTUNI: + case OP_EODN: + case OP_EOD: + case OP_CIRC: + case OP_CIRCM: + case OP_DOLL: + case OP_DOLLM: + case OP_NOT: + case OP_NOTI: + case OP_REVERSE: + cc = compile_char1_matchingpath(common, *cc, cc + 1, parent->top != NULL ? &parent->top->nextbacktracks : &parent->topbacktracks); + break; + + case OP_SET_SOM: + PUSH_BACKTRACK_NOVALUE(sizeof(backtrack_common), cc); + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(0)); + allocate_stack(common, 1); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(0), STR_PTR, 0); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), TMP2, 0); + cc++; + break; + + case OP_CHAR: + case OP_CHARI: + if (common->mode == JIT_COMPILE) + cc = compile_charn_matchingpath(common, cc, ccend, parent->top != NULL ? &parent->top->nextbacktracks : &parent->topbacktracks); + else + cc = compile_char1_matchingpath(common, *cc, cc + 1, parent->top != NULL ? &parent->top->nextbacktracks : &parent->topbacktracks); + break; + + case OP_STAR: + case OP_MINSTAR: + case OP_PLUS: + case OP_MINPLUS: + case OP_QUERY: + case OP_MINQUERY: + case OP_UPTO: + case OP_MINUPTO: + case OP_EXACT: + case OP_POSSTAR: + case OP_POSPLUS: + case OP_POSQUERY: + case OP_POSUPTO: + case OP_STARI: + case OP_MINSTARI: + case OP_PLUSI: + case OP_MINPLUSI: + case OP_QUERYI: + case OP_MINQUERYI: + case OP_UPTOI: + case OP_MINUPTOI: + case OP_EXACTI: + case OP_POSSTARI: + case OP_POSPLUSI: + case OP_POSQUERYI: + case OP_POSUPTOI: + case OP_NOTSTAR: + case OP_NOTMINSTAR: + case OP_NOTPLUS: + case OP_NOTMINPLUS: + case OP_NOTQUERY: + case OP_NOTMINQUERY: + case OP_NOTUPTO: + case OP_NOTMINUPTO: + case OP_NOTEXACT: + case OP_NOTPOSSTAR: + case OP_NOTPOSPLUS: + case OP_NOTPOSQUERY: + case OP_NOTPOSUPTO: + case OP_NOTSTARI: + case OP_NOTMINSTARI: + case OP_NOTPLUSI: + case OP_NOTMINPLUSI: + case OP_NOTQUERYI: + case OP_NOTMINQUERYI: + case OP_NOTUPTOI: + case OP_NOTMINUPTOI: + case OP_NOTEXACTI: + case OP_NOTPOSSTARI: + case OP_NOTPOSPLUSI: + case OP_NOTPOSQUERYI: + case OP_NOTPOSUPTOI: + case OP_TYPESTAR: + case OP_TYPEMINSTAR: + case OP_TYPEPLUS: + case OP_TYPEMINPLUS: + case OP_TYPEQUERY: + case OP_TYPEMINQUERY: + case OP_TYPEUPTO: + case OP_TYPEMINUPTO: + case OP_TYPEEXACT: + case OP_TYPEPOSSTAR: + case OP_TYPEPOSPLUS: + case OP_TYPEPOSQUERY: + case OP_TYPEPOSUPTO: + cc = compile_iterator_matchingpath(common, cc, parent); + break; + + case OP_CLASS: + case OP_NCLASS: + if (cc[1 + (32 / sizeof(pcre_uchar))] >= OP_CRSTAR && cc[1 + (32 / sizeof(pcre_uchar))] <= OP_CRPOSRANGE) + cc = compile_iterator_matchingpath(common, cc, parent); + else + cc = compile_char1_matchingpath(common, *cc, cc + 1, parent->top != NULL ? &parent->top->nextbacktracks : &parent->topbacktracks); + break; + +#if defined SUPPORT_UTF || defined COMPILE_PCRE16 || defined COMPILE_PCRE32 + case OP_XCLASS: + if (*(cc + GET(cc, 1)) >= OP_CRSTAR && *(cc + GET(cc, 1)) <= OP_CRPOSRANGE) + cc = compile_iterator_matchingpath(common, cc, parent); + else + cc = compile_char1_matchingpath(common, *cc, cc + 1, parent->top != NULL ? &parent->top->nextbacktracks : &parent->topbacktracks); + break; +#endif + + case OP_REF: + case OP_REFI: + if (cc[1 + IMM2_SIZE] >= OP_CRSTAR && cc[1 + IMM2_SIZE] <= OP_CRPOSRANGE) + cc = compile_ref_iterator_matchingpath(common, cc, parent); + else + { + compile_ref_matchingpath(common, cc, parent->top != NULL ? &parent->top->nextbacktracks : &parent->topbacktracks, TRUE, FALSE); + cc += 1 + IMM2_SIZE; + } + break; + + case OP_DNREF: + case OP_DNREFI: + if (cc[1 + 2 * IMM2_SIZE] >= OP_CRSTAR && cc[1 + 2 * IMM2_SIZE] <= OP_CRPOSRANGE) + cc = compile_ref_iterator_matchingpath(common, cc, parent); + else + { + compile_dnref_search(common, cc, parent->top != NULL ? &parent->top->nextbacktracks : &parent->topbacktracks); + compile_ref_matchingpath(common, cc, parent->top != NULL ? &parent->top->nextbacktracks : &parent->topbacktracks, TRUE, FALSE); + cc += 1 + 2 * IMM2_SIZE; + } + break; + + case OP_RECURSE: + cc = compile_recurse_matchingpath(common, cc, parent); + break; + + case OP_CALLOUT: + cc = compile_callout_matchingpath(common, cc, parent); + break; + + case OP_ASSERT: + case OP_ASSERT_NOT: + case OP_ASSERTBACK: + case OP_ASSERTBACK_NOT: + PUSH_BACKTRACK_NOVALUE(sizeof(assert_backtrack), cc); + cc = compile_assert_matchingpath(common, cc, BACKTRACK_AS(assert_backtrack), FALSE); + break; + + case OP_BRAMINZERO: + PUSH_BACKTRACK_NOVALUE(sizeof(braminzero_backtrack), cc); + cc = bracketend(cc + 1); + if (*(cc - 1 - LINK_SIZE) != OP_KETRMIN) + { + allocate_stack(common, 1); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); + } + else + { + allocate_stack(common, 2); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(1), STR_PTR, 0); + } + BACKTRACK_AS(braminzero_backtrack)->matchingpath = LABEL(); + if (cc[1] > OP_ASSERTBACK_NOT) + count_match(common); + break; + + case OP_ONCE: + case OP_ONCE_NC: + case OP_BRA: + case OP_CBRA: + case OP_COND: + case OP_SBRA: + case OP_SCBRA: + case OP_SCOND: + cc = compile_bracket_matchingpath(common, cc, parent); + break; + + case OP_BRAZERO: + if (cc[1] > OP_ASSERTBACK_NOT) + cc = compile_bracket_matchingpath(common, cc, parent); + else + { + PUSH_BACKTRACK_NOVALUE(sizeof(assert_backtrack), cc); + cc = compile_assert_matchingpath(common, cc, BACKTRACK_AS(assert_backtrack), FALSE); + } + break; + + case OP_BRAPOS: + case OP_CBRAPOS: + case OP_SBRAPOS: + case OP_SCBRAPOS: + case OP_BRAPOSZERO: + cc = compile_bracketpos_matchingpath(common, cc, parent); + break; + + case OP_MARK: + PUSH_BACKTRACK_NOVALUE(sizeof(backtrack_common), cc); + SLJIT_ASSERT(common->mark_ptr != 0); + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), common->mark_ptr); + allocate_stack(common, common->has_skip_arg ? 5 : 1); + OP1(SLJIT_MOV, TMP1, 0, ARGUMENTS, 0); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(common->has_skip_arg ? 4 : 0), TMP2, 0); + OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, (sljit_sw)(cc + 2)); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->mark_ptr, TMP2, 0); + OP1(SLJIT_MOV, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, mark_ptr), TMP2, 0); + if (common->has_skip_arg) + { + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, STACK_TOP, 0); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(1), SLJIT_IMM, type_mark); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(2), SLJIT_IMM, (sljit_sw)(cc + 2)); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(3), STR_PTR, 0); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), TMP1, 0); + } + cc += 1 + 2 + cc[1]; + break; + + case OP_PRUNE: + case OP_PRUNE_ARG: + case OP_SKIP: + case OP_SKIP_ARG: + case OP_THEN: + case OP_THEN_ARG: + case OP_COMMIT: + cc = compile_control_verb_matchingpath(common, cc, parent); + break; + + case OP_FAIL: + case OP_ACCEPT: + case OP_ASSERT_ACCEPT: + cc = compile_fail_accept_matchingpath(common, cc, parent); + break; + + case OP_CLOSE: + cc = compile_close_matchingpath(common, cc); + break; + + case OP_SKIPZERO: + cc = bracketend(cc + 1); + break; + + default: + SLJIT_ASSERT_STOP(); + return; + } + if (cc == NULL) + return; + } + +if (has_then_trap) + { + /* Head item on backtrack. */ + PUSH_BACKTRACK_NOVALUE(sizeof(then_trap_backtrack), cc); + BACKTRACK_AS(then_trap_backtrack)->common.cc = then_trap_opcode; + BACKTRACK_AS(then_trap_backtrack)->then_trap = common->then_trap; + common->then_trap = save_then_trap; + } +SLJIT_ASSERT(cc == ccend); +} + +#undef PUSH_BACKTRACK +#undef PUSH_BACKTRACK_NOVALUE +#undef BACKTRACK_AS + +#define COMPILE_BACKTRACKINGPATH(current) \ + do \ + { \ + compile_backtrackingpath(common, (current)); \ + if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) \ + return; \ + } \ + while (0) + +#define CURRENT_AS(type) ((type *)current) + +static void compile_iterator_backtrackingpath(compiler_common *common, struct backtrack_common *current) +{ +DEFINE_COMPILER; +pcre_uchar *cc = current->cc; +pcre_uchar opcode; +pcre_uchar type; +int max = -1, min = -1; +struct sljit_label *label = NULL; +struct sljit_jump *jump = NULL; +jump_list *jumplist = NULL; +int private_data_ptr = PRIVATE_DATA(cc); +int base = (private_data_ptr == 0) ? SLJIT_MEM1(STACK_TOP) : SLJIT_MEM1(SLJIT_SP); +int offset0 = (private_data_ptr == 0) ? STACK(0) : private_data_ptr; +int offset1 = (private_data_ptr == 0) ? STACK(1) : private_data_ptr + (int)sizeof(sljit_sw); + +cc = get_iterator_parameters(common, cc, &opcode, &type, &max, &min, NULL); + +switch(opcode) + { + case OP_STAR: + case OP_PLUS: + case OP_UPTO: + case OP_CRRANGE: + if (type == OP_ANYNL || type == OP_EXTUNI) + { + SLJIT_ASSERT(private_data_ptr == 0); + set_jumps(current->topbacktracks, LABEL()); + OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); + free_stack(common, 1); + CMPTO(SLJIT_C_NOT_EQUAL, STR_PTR, 0, SLJIT_IMM, 0, CURRENT_AS(iterator_backtrack)->matchingpath); + } + else + { + if (opcode == OP_UPTO) + min = 0; + if (opcode <= OP_PLUS) + { + OP1(SLJIT_MOV, STR_PTR, 0, base, offset0); + jump = CMP(SLJIT_C_LESS_EQUAL, STR_PTR, 0, base, offset1); + } + else + { + OP1(SLJIT_MOV, TMP1, 0, base, offset1); + OP1(SLJIT_MOV, STR_PTR, 0, base, offset0); + jump = CMP(SLJIT_C_LESS_EQUAL, TMP1, 0, SLJIT_IMM, min + 1); + OP2(SLJIT_SUB, base, offset1, TMP1, 0, SLJIT_IMM, 1); + } + skip_char_back(common); + OP1(SLJIT_MOV, base, offset0, STR_PTR, 0); + JUMPTO(SLJIT_JUMP, CURRENT_AS(iterator_backtrack)->matchingpath); + if (opcode == OP_CRRANGE) + set_jumps(current->topbacktracks, LABEL()); + JUMPHERE(jump); + if (private_data_ptr == 0) + free_stack(common, 2); + if (opcode == OP_PLUS) + set_jumps(current->topbacktracks, LABEL()); + } + break; + + case OP_MINSTAR: + case OP_MINPLUS: + OP1(SLJIT_MOV, STR_PTR, 0, base, offset0); + compile_char1_matchingpath(common, type, cc, &jumplist); + OP1(SLJIT_MOV, base, offset0, STR_PTR, 0); + JUMPTO(SLJIT_JUMP, CURRENT_AS(iterator_backtrack)->matchingpath); + set_jumps(jumplist, LABEL()); + if (private_data_ptr == 0) + free_stack(common, 1); + if (opcode == OP_MINPLUS) + set_jumps(current->topbacktracks, LABEL()); + break; + + case OP_MINUPTO: + case OP_CRMINRANGE: + if (opcode == OP_CRMINRANGE) + { + label = LABEL(); + set_jumps(current->topbacktracks, label); + } + OP1(SLJIT_MOV, STR_PTR, 0, base, offset0); + compile_char1_matchingpath(common, type, cc, &jumplist); + + OP1(SLJIT_MOV, TMP1, 0, base, offset1); + OP1(SLJIT_MOV, base, offset0, STR_PTR, 0); + OP2(SLJIT_ADD, TMP1, 0, TMP1, 0, SLJIT_IMM, 1); + OP1(SLJIT_MOV, base, offset1, TMP1, 0); + + if (opcode == OP_CRMINRANGE) + CMPTO(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, min + 1, label); + + if (opcode == OP_CRMINRANGE && max == 0) + JUMPTO(SLJIT_JUMP, CURRENT_AS(iterator_backtrack)->matchingpath); + else + CMPTO(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, max + 2, CURRENT_AS(iterator_backtrack)->matchingpath); + + set_jumps(jumplist, LABEL()); + if (private_data_ptr == 0) + free_stack(common, 2); + break; + + case OP_QUERY: + OP1(SLJIT_MOV, STR_PTR, 0, base, offset0); + OP1(SLJIT_MOV, base, offset0, SLJIT_IMM, 0); + CMPTO(SLJIT_C_NOT_EQUAL, STR_PTR, 0, SLJIT_IMM, 0, CURRENT_AS(iterator_backtrack)->matchingpath); + jump = JUMP(SLJIT_JUMP); + set_jumps(current->topbacktracks, LABEL()); + OP1(SLJIT_MOV, STR_PTR, 0, base, offset0); + OP1(SLJIT_MOV, base, offset0, SLJIT_IMM, 0); + JUMPTO(SLJIT_JUMP, CURRENT_AS(iterator_backtrack)->matchingpath); + JUMPHERE(jump); + if (private_data_ptr == 0) + free_stack(common, 1); + break; + + case OP_MINQUERY: + OP1(SLJIT_MOV, STR_PTR, 0, base, offset0); + OP1(SLJIT_MOV, base, offset0, SLJIT_IMM, 0); + jump = CMP(SLJIT_C_EQUAL, STR_PTR, 0, SLJIT_IMM, 0); + compile_char1_matchingpath(common, type, cc, &jumplist); + JUMPTO(SLJIT_JUMP, CURRENT_AS(iterator_backtrack)->matchingpath); + set_jumps(jumplist, LABEL()); + JUMPHERE(jump); + if (private_data_ptr == 0) + free_stack(common, 1); + break; + + case OP_EXACT: + case OP_POSPLUS: + case OP_CRPOSRANGE: + set_jumps(current->topbacktracks, LABEL()); + break; + + case OP_POSSTAR: + case OP_POSQUERY: + case OP_POSUPTO: + break; + + default: + SLJIT_ASSERT_STOP(); + break; + } +} + +static SLJIT_INLINE void compile_ref_iterator_backtrackingpath(compiler_common *common, struct backtrack_common *current) +{ +DEFINE_COMPILER; +pcre_uchar *cc = current->cc; +BOOL ref = (*cc == OP_REF || *cc == OP_REFI); +pcre_uchar type; + +type = cc[ref ? 1 + IMM2_SIZE : 1 + 2 * IMM2_SIZE]; + +if ((type & 0x1) == 0) + { + /* Maximize case. */ + set_jumps(current->topbacktracks, LABEL()); + OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); + free_stack(common, 1); + CMPTO(SLJIT_C_NOT_EQUAL, STR_PTR, 0, SLJIT_IMM, 0, CURRENT_AS(iterator_backtrack)->matchingpath); + return; + } + +OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); +CMPTO(SLJIT_C_NOT_EQUAL, STR_PTR, 0, SLJIT_IMM, 0, CURRENT_AS(iterator_backtrack)->matchingpath); +set_jumps(current->topbacktracks, LABEL()); +free_stack(common, ref ? 2 : 3); +} + +static SLJIT_INLINE void compile_recurse_backtrackingpath(compiler_common *common, struct backtrack_common *current) +{ +DEFINE_COMPILER; + +if (CURRENT_AS(recurse_backtrack)->inlined_pattern) + compile_backtrackingpath(common, current->top); +set_jumps(current->topbacktracks, LABEL()); +if (CURRENT_AS(recurse_backtrack)->inlined_pattern) + return; + +if (common->has_set_som && common->mark_ptr != 0) + { + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(1)); + free_stack(common, 2); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(0), TMP2, 0); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->mark_ptr, TMP1, 0); + } +else if (common->has_set_som || common->mark_ptr != 0) + { + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); + free_stack(common, 1); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->has_set_som ? (int)(OVECTOR(0)) : common->mark_ptr, TMP2, 0); + } +} + +static void compile_assert_backtrackingpath(compiler_common *common, struct backtrack_common *current) +{ +DEFINE_COMPILER; +pcre_uchar *cc = current->cc; +pcre_uchar bra = OP_BRA; +struct sljit_jump *brajump = NULL; + +SLJIT_ASSERT(*cc != OP_BRAMINZERO); +if (*cc == OP_BRAZERO) + { + bra = *cc; + cc++; + } + +if (bra == OP_BRAZERO) + { + SLJIT_ASSERT(current->topbacktracks == NULL); + OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); + } + +if (CURRENT_AS(assert_backtrack)->framesize < 0) + { + set_jumps(current->topbacktracks, LABEL()); + + if (bra == OP_BRAZERO) + { + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); + CMPTO(SLJIT_C_NOT_EQUAL, STR_PTR, 0, SLJIT_IMM, 0, CURRENT_AS(assert_backtrack)->matchingpath); + free_stack(common, 1); + } + return; + } + +if (bra == OP_BRAZERO) + { + if (*cc == OP_ASSERT_NOT || *cc == OP_ASSERTBACK_NOT) + { + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); + CMPTO(SLJIT_C_NOT_EQUAL, STR_PTR, 0, SLJIT_IMM, 0, CURRENT_AS(assert_backtrack)->matchingpath); + free_stack(common, 1); + return; + } + free_stack(common, 1); + brajump = CMP(SLJIT_C_EQUAL, STR_PTR, 0, SLJIT_IMM, 0); + } + +if (*cc == OP_ASSERT || *cc == OP_ASSERTBACK) + { + OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), CURRENT_AS(assert_backtrack)->private_data_ptr); + add_jump(compiler, &common->revertframes, JUMP(SLJIT_FAST_CALL)); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), CURRENT_AS(assert_backtrack)->private_data_ptr, SLJIT_MEM1(STACK_TOP), CURRENT_AS(assert_backtrack)->framesize * sizeof(sljit_sw)); + + set_jumps(current->topbacktracks, LABEL()); + } +else + set_jumps(current->topbacktracks, LABEL()); + +if (bra == OP_BRAZERO) + { + /* We know there is enough place on the stack. */ + OP2(SLJIT_ADD, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, sizeof(sljit_sw)); + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); + JUMPTO(SLJIT_JUMP, CURRENT_AS(assert_backtrack)->matchingpath); + JUMPHERE(brajump); + } +} + +static void compile_bracket_backtrackingpath(compiler_common *common, struct backtrack_common *current) +{ +DEFINE_COMPILER; +int opcode, stacksize, alt_count, alt_max; +int offset = 0; +int private_data_ptr = CURRENT_AS(bracket_backtrack)->private_data_ptr; +int repeat_ptr = 0, repeat_type = 0, repeat_count = 0; +pcre_uchar *cc = current->cc; +pcre_uchar *ccbegin; +pcre_uchar *ccprev; +pcre_uchar bra = OP_BRA; +pcre_uchar ket; +assert_backtrack *assert; +sljit_uw *next_update_addr = NULL; +BOOL has_alternatives; +BOOL needs_control_head = FALSE; +struct sljit_jump *brazero = NULL; +struct sljit_jump *alt1 = NULL; +struct sljit_jump *alt2 = NULL; +struct sljit_jump *once = NULL; +struct sljit_jump *cond = NULL; +struct sljit_label *rmin_label = NULL; +struct sljit_label *exact_label = NULL; + +if (*cc == OP_BRAZERO || *cc == OP_BRAMINZERO) + { + bra = *cc; + cc++; + } + +opcode = *cc; +ccbegin = bracketend(cc) - 1 - LINK_SIZE; +ket = *ccbegin; +if (ket == OP_KET && PRIVATE_DATA(ccbegin) != 0) + { + repeat_ptr = PRIVATE_DATA(ccbegin); + repeat_type = PRIVATE_DATA(ccbegin + 2); + repeat_count = PRIVATE_DATA(ccbegin + 3); + SLJIT_ASSERT(repeat_type != 0 && repeat_count != 0); + if (repeat_type == OP_UPTO) + ket = OP_KETRMAX; + if (repeat_type == OP_MINUPTO) + ket = OP_KETRMIN; + } +ccbegin = cc; +cc += GET(cc, 1); +has_alternatives = *cc == OP_ALT; +if (SLJIT_UNLIKELY(opcode == OP_COND) || SLJIT_UNLIKELY(opcode == OP_SCOND)) + has_alternatives = (ccbegin[1 + LINK_SIZE] >= OP_ASSERT && ccbegin[1 + LINK_SIZE] <= OP_ASSERTBACK_NOT) || CURRENT_AS(bracket_backtrack)->u.condfailed != NULL; +if (opcode == OP_CBRA || opcode == OP_SCBRA) + offset = (GET2(ccbegin, 1 + LINK_SIZE)) << 1; +if (SLJIT_UNLIKELY(opcode == OP_COND) && (*cc == OP_KETRMAX || *cc == OP_KETRMIN)) + opcode = OP_SCOND; +if (SLJIT_UNLIKELY(opcode == OP_ONCE_NC)) + opcode = OP_ONCE; + +alt_max = has_alternatives ? no_alternatives(ccbegin) : 0; + +/* Decoding the needs_control_head in framesize. */ +if (opcode == OP_ONCE) + { + needs_control_head = (CURRENT_AS(bracket_backtrack)->u.framesize & 0x1) != 0; + CURRENT_AS(bracket_backtrack)->u.framesize >>= 1; + } + +if (ket != OP_KET && repeat_type != 0) + { + /* TMP1 is used in OP_KETRMIN below. */ + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); + free_stack(common, 1); + if (repeat_type == OP_UPTO) + OP2(SLJIT_ADD, SLJIT_MEM1(SLJIT_SP), repeat_ptr, TMP1, 0, SLJIT_IMM, 1); + else + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), repeat_ptr, TMP1, 0); + } + +if (ket == OP_KETRMAX) + { + if (bra == OP_BRAZERO) + { + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); + free_stack(common, 1); + brazero = CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, 0); + } + } +else if (ket == OP_KETRMIN) + { + if (bra != OP_BRAMINZERO) + { + OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); + if (repeat_type != 0) + { + /* TMP1 was set a few lines above. */ + CMPTO(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, 0, CURRENT_AS(bracket_backtrack)->recursive_matchingpath); + /* Drop STR_PTR for non-greedy plus quantifier. */ + if (opcode != OP_ONCE) + free_stack(common, 1); + } + else if (opcode >= OP_SBRA || opcode == OP_ONCE) + { + /* Checking zero-length iteration. */ + if (opcode != OP_ONCE || CURRENT_AS(bracket_backtrack)->u.framesize < 0) + CMPTO(SLJIT_C_NOT_EQUAL, STR_PTR, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr, CURRENT_AS(bracket_backtrack)->recursive_matchingpath); + else + { + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); + CMPTO(SLJIT_C_NOT_EQUAL, STR_PTR, 0, SLJIT_MEM1(TMP1), (CURRENT_AS(bracket_backtrack)->u.framesize + 1) * sizeof(sljit_sw), CURRENT_AS(bracket_backtrack)->recursive_matchingpath); + } + /* Drop STR_PTR for non-greedy plus quantifier. */ + if (opcode != OP_ONCE) + free_stack(common, 1); + } + else + JUMPTO(SLJIT_JUMP, CURRENT_AS(bracket_backtrack)->recursive_matchingpath); + } + rmin_label = LABEL(); + if (repeat_type != 0) + OP2(SLJIT_ADD, SLJIT_MEM1(SLJIT_SP), repeat_ptr, SLJIT_MEM1(SLJIT_SP), repeat_ptr, SLJIT_IMM, 1); + } +else if (bra == OP_BRAZERO) + { + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); + free_stack(common, 1); + brazero = CMP(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, 0); + } +else if (repeat_type == OP_EXACT) + { + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), repeat_ptr, SLJIT_IMM, 1); + exact_label = LABEL(); + } + +if (offset != 0) + { + if (common->capture_last_ptr != 0) + { + SLJIT_ASSERT(common->optimized_cbracket[offset >> 1] == 0); + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), STACK(1)); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->capture_last_ptr, TMP1, 0); + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(2)); + free_stack(common, 3); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset), TMP2, 0); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1), TMP1, 0); + } + else if (common->optimized_cbracket[offset >> 1] == 0) + { + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), STACK(1)); + free_stack(common, 2); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset), TMP1, 0); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1), TMP2, 0); + } + } + +if (SLJIT_UNLIKELY(opcode == OP_ONCE)) + { + if (CURRENT_AS(bracket_backtrack)->u.framesize >= 0) + { + OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); + add_jump(compiler, &common->revertframes, JUMP(SLJIT_FAST_CALL)); + } + once = JUMP(SLJIT_JUMP); + } +else if (SLJIT_UNLIKELY(opcode == OP_COND) || SLJIT_UNLIKELY(opcode == OP_SCOND)) + { + if (has_alternatives) + { + /* Always exactly one alternative. */ + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); + free_stack(common, 1); + + alt_max = 2; + alt1 = CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, sizeof(sljit_uw)); + } + } +else if (has_alternatives) + { + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); + free_stack(common, 1); + + if (alt_max > 4) + { + /* Table jump if alt_max is greater than 4. */ + next_update_addr = common->read_only_data_ptr; + common->read_only_data_ptr += alt_max; + sljit_emit_ijump(compiler, SLJIT_JUMP, SLJIT_MEM1(TMP1), (sljit_sw)next_update_addr); + add_label_addr(common, next_update_addr++); + } + else + { + if (alt_max == 4) + alt2 = CMP(SLJIT_C_GREATER_EQUAL, TMP1, 0, SLJIT_IMM, 2 * sizeof(sljit_uw)); + alt1 = CMP(SLJIT_C_GREATER_EQUAL, TMP1, 0, SLJIT_IMM, sizeof(sljit_uw)); + } + } + +COMPILE_BACKTRACKINGPATH(current->top); +if (current->topbacktracks) + set_jumps(current->topbacktracks, LABEL()); + +if (SLJIT_UNLIKELY(opcode == OP_COND) || SLJIT_UNLIKELY(opcode == OP_SCOND)) + { + /* Conditional block always has at most one alternative. */ + if (ccbegin[1 + LINK_SIZE] >= OP_ASSERT && ccbegin[1 + LINK_SIZE] <= OP_ASSERTBACK_NOT) + { + SLJIT_ASSERT(has_alternatives); + assert = CURRENT_AS(bracket_backtrack)->u.assert; + if (assert->framesize >= 0 && (ccbegin[1 + LINK_SIZE] == OP_ASSERT || ccbegin[1 + LINK_SIZE] == OP_ASSERTBACK)) + { + OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), assert->private_data_ptr); + add_jump(compiler, &common->revertframes, JUMP(SLJIT_FAST_CALL)); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), assert->private_data_ptr, SLJIT_MEM1(STACK_TOP), assert->framesize * sizeof(sljit_sw)); + } + cond = JUMP(SLJIT_JUMP); + set_jumps(CURRENT_AS(bracket_backtrack)->u.assert->condfailed, LABEL()); + } + else if (CURRENT_AS(bracket_backtrack)->u.condfailed != NULL) + { + SLJIT_ASSERT(has_alternatives); + cond = JUMP(SLJIT_JUMP); + set_jumps(CURRENT_AS(bracket_backtrack)->u.condfailed, LABEL()); + } + else + SLJIT_ASSERT(!has_alternatives); + } + +if (has_alternatives) + { + alt_count = sizeof(sljit_uw); + do + { + current->top = NULL; + current->topbacktracks = NULL; + current->nextbacktracks = NULL; + /* Conditional blocks always have an additional alternative, even if it is empty. */ + if (*cc == OP_ALT) + { + ccprev = cc + 1 + LINK_SIZE; + cc += GET(cc, 1); + if (opcode != OP_COND && opcode != OP_SCOND) + { + if (opcode != OP_ONCE) + { + if (private_data_ptr != 0) + OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); + else + OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); + } + else + OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(needs_control_head ? 1 : 0)); + } + compile_matchingpath(common, ccprev, cc, current); + if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) + return; + } + + /* Instructions after the current alternative is successfully matched. */ + /* There is a similar code in compile_bracket_matchingpath. */ + if (opcode == OP_ONCE) + match_once_common(common, ket, CURRENT_AS(bracket_backtrack)->u.framesize, private_data_ptr, has_alternatives, needs_control_head); + + stacksize = 0; + if (repeat_type == OP_MINUPTO) + { + /* We need to preserve the counter. TMP2 will be used below. */ + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), repeat_ptr); + stacksize++; + } + if (ket != OP_KET || bra != OP_BRA) + stacksize++; + if (offset != 0) + { + if (common->capture_last_ptr != 0) + stacksize++; + if (common->optimized_cbracket[offset >> 1] == 0) + stacksize += 2; + } + if (opcode != OP_ONCE) + stacksize++; + + if (stacksize > 0) + allocate_stack(common, stacksize); + + stacksize = 0; + if (repeat_type == OP_MINUPTO) + { + /* TMP2 was set above. */ + OP2(SLJIT_SUB, SLJIT_MEM1(STACK_TOP), STACK(stacksize), TMP2, 0, SLJIT_IMM, 1); + stacksize++; + } + + if (ket != OP_KET || bra != OP_BRA) + { + if (ket != OP_KET) + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), STR_PTR, 0); + else + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), SLJIT_IMM, 0); + stacksize++; + } + + if (offset != 0) + stacksize = match_capture_common(common, stacksize, offset, private_data_ptr); + + if (opcode != OP_ONCE) + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), SLJIT_IMM, alt_count); + + if (offset != 0 && ket == OP_KETRMAX && common->optimized_cbracket[offset >> 1] != 0) + { + /* If ket is not OP_KETRMAX, this code path is executed after the jump to alternative_matchingpath. */ + SLJIT_ASSERT(private_data_ptr == OVECTOR(offset + 0)); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1), STR_PTR, 0); + } + + JUMPTO(SLJIT_JUMP, CURRENT_AS(bracket_backtrack)->alternative_matchingpath); + + if (opcode != OP_ONCE) + { + if (alt_max > 4) + add_label_addr(common, next_update_addr++); + else + { + if (alt_count != 2 * sizeof(sljit_uw)) + { + JUMPHERE(alt1); + if (alt_max == 3 && alt_count == sizeof(sljit_uw)) + alt2 = CMP(SLJIT_C_GREATER_EQUAL, TMP1, 0, SLJIT_IMM, 2 * sizeof(sljit_uw)); + } + else + { + JUMPHERE(alt2); + if (alt_max == 4) + alt1 = CMP(SLJIT_C_GREATER_EQUAL, TMP1, 0, SLJIT_IMM, 3 * sizeof(sljit_uw)); + } + } + alt_count += sizeof(sljit_uw); + } + + COMPILE_BACKTRACKINGPATH(current->top); + if (current->topbacktracks) + set_jumps(current->topbacktracks, LABEL()); + SLJIT_ASSERT(!current->nextbacktracks); + } + while (*cc == OP_ALT); + + if (cond != NULL) + { + SLJIT_ASSERT(opcode == OP_COND || opcode == OP_SCOND); + assert = CURRENT_AS(bracket_backtrack)->u.assert; + if ((ccbegin[1 + LINK_SIZE] == OP_ASSERT_NOT || ccbegin[1 + LINK_SIZE] == OP_ASSERTBACK_NOT) && assert->framesize >= 0) + { + OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), assert->private_data_ptr); + add_jump(compiler, &common->revertframes, JUMP(SLJIT_FAST_CALL)); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), assert->private_data_ptr, SLJIT_MEM1(STACK_TOP), assert->framesize * sizeof(sljit_sw)); + } + JUMPHERE(cond); + } + + /* Free the STR_PTR. */ + if (private_data_ptr == 0) + free_stack(common, 1); + } + +if (offset != 0) + { + /* Using both tmp register is better for instruction scheduling. */ + if (common->optimized_cbracket[offset >> 1] != 0) + { + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), STACK(1)); + free_stack(common, 2); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset), TMP1, 0); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1), TMP2, 0); + } + else + { + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); + free_stack(common, 1); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, TMP1, 0); + } + } +else if (opcode == OP_SBRA || opcode == OP_SCOND) + { + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, SLJIT_MEM1(STACK_TOP), STACK(0)); + free_stack(common, 1); + } +else if (opcode == OP_ONCE) + { + cc = ccbegin + GET(ccbegin, 1); + stacksize = needs_control_head ? 1 : 0; + + if (CURRENT_AS(bracket_backtrack)->u.framesize >= 0) + { + /* Reset head and drop saved frame. */ + stacksize += CURRENT_AS(bracket_backtrack)->u.framesize + ((ket != OP_KET || *cc == OP_ALT) ? 2 : 1); + } + else if (ket == OP_KETRMAX || (*cc == OP_ALT && ket != OP_KETRMIN)) + { + /* The STR_PTR must be released. */ + stacksize++; + } + free_stack(common, stacksize); + + JUMPHERE(once); + /* Restore previous private_data_ptr */ + if (CURRENT_AS(bracket_backtrack)->u.framesize >= 0) + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, SLJIT_MEM1(STACK_TOP), CURRENT_AS(bracket_backtrack)->u.framesize * sizeof(sljit_sw)); + else if (ket == OP_KETRMIN) + { + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(1)); + /* See the comment below. */ + free_stack(common, 2); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, TMP1, 0); + } + } + +if (repeat_type == OP_EXACT) + { + OP2(SLJIT_ADD, TMP1, 0, SLJIT_MEM1(SLJIT_SP), repeat_ptr, SLJIT_IMM, 1); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), repeat_ptr, TMP1, 0); + CMPTO(SLJIT_C_LESS_EQUAL, TMP1, 0, SLJIT_IMM, repeat_count, exact_label); + } +else if (ket == OP_KETRMAX) + { + OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); + if (bra != OP_BRAZERO) + free_stack(common, 1); + + CMPTO(SLJIT_C_NOT_EQUAL, STR_PTR, 0, SLJIT_IMM, 0, CURRENT_AS(bracket_backtrack)->recursive_matchingpath); + if (bra == OP_BRAZERO) + { + OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(1)); + JUMPTO(SLJIT_JUMP, CURRENT_AS(bracket_backtrack)->zero_matchingpath); + JUMPHERE(brazero); + free_stack(common, 1); + } + } +else if (ket == OP_KETRMIN) + { + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); + + /* OP_ONCE removes everything in case of a backtrack, so we don't + need to explicitly release the STR_PTR. The extra release would + affect badly the free_stack(2) above. */ + if (opcode != OP_ONCE) + free_stack(common, 1); + CMPTO(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, 0, rmin_label); + if (opcode == OP_ONCE) + free_stack(common, bra == OP_BRAMINZERO ? 2 : 1); + else if (bra == OP_BRAMINZERO) + free_stack(common, 1); + } +else if (bra == OP_BRAZERO) + { + OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); + JUMPTO(SLJIT_JUMP, CURRENT_AS(bracket_backtrack)->zero_matchingpath); + JUMPHERE(brazero); + } +} + +static SLJIT_INLINE void compile_bracketpos_backtrackingpath(compiler_common *common, struct backtrack_common *current) +{ +DEFINE_COMPILER; +int offset; +struct sljit_jump *jump; + +if (CURRENT_AS(bracketpos_backtrack)->framesize < 0) + { + if (*current->cc == OP_CBRAPOS || *current->cc == OP_SCBRAPOS) + { + offset = (GET2(current->cc, 1 + LINK_SIZE)) << 1; + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), STACK(1)); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset), TMP1, 0); + if (common->capture_last_ptr != 0) + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(2)); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1), TMP2, 0); + if (common->capture_last_ptr != 0) + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->capture_last_ptr, TMP1, 0); + } + set_jumps(current->topbacktracks, LABEL()); + free_stack(common, CURRENT_AS(bracketpos_backtrack)->stacksize); + return; + } + +OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), CURRENT_AS(bracketpos_backtrack)->private_data_ptr); +add_jump(compiler, &common->revertframes, JUMP(SLJIT_FAST_CALL)); + +if (current->topbacktracks) + { + jump = JUMP(SLJIT_JUMP); + set_jumps(current->topbacktracks, LABEL()); + /* Drop the stack frame. */ + free_stack(common, CURRENT_AS(bracketpos_backtrack)->stacksize); + JUMPHERE(jump); + } +OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), CURRENT_AS(bracketpos_backtrack)->private_data_ptr, SLJIT_MEM1(STACK_TOP), CURRENT_AS(bracketpos_backtrack)->framesize * sizeof(sljit_sw)); +} + +static SLJIT_INLINE void compile_braminzero_backtrackingpath(compiler_common *common, struct backtrack_common *current) +{ +assert_backtrack backtrack; + +current->top = NULL; +current->topbacktracks = NULL; +current->nextbacktracks = NULL; +if (current->cc[1] > OP_ASSERTBACK_NOT) + { + /* Manual call of compile_bracket_matchingpath and compile_bracket_backtrackingpath. */ + compile_bracket_matchingpath(common, current->cc, current); + compile_bracket_backtrackingpath(common, current->top); + } +else + { + memset(&backtrack, 0, sizeof(backtrack)); + backtrack.common.cc = current->cc; + backtrack.matchingpath = CURRENT_AS(braminzero_backtrack)->matchingpath; + /* Manual call of compile_assert_matchingpath. */ + compile_assert_matchingpath(common, current->cc, &backtrack, FALSE); + } +SLJIT_ASSERT(!current->nextbacktracks && !current->topbacktracks); +} + +static SLJIT_INLINE void compile_control_verb_backtrackingpath(compiler_common *common, struct backtrack_common *current) +{ +DEFINE_COMPILER; +pcre_uchar opcode = *current->cc; +struct sljit_label *loop; +struct sljit_jump *jump; + +if (opcode == OP_THEN || opcode == OP_THEN_ARG) + { + if (common->then_trap != NULL) + { + SLJIT_ASSERT(common->control_head_ptr != 0); + + OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr); + OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, type_then_trap); + OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, common->then_trap->start); + jump = JUMP(SLJIT_JUMP); + + loop = LABEL(); + OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(STACK_TOP), -(int)sizeof(sljit_sw)); + JUMPHERE(jump); + CMPTO(SLJIT_C_NOT_EQUAL, SLJIT_MEM1(STACK_TOP), -(int)(2 * sizeof(sljit_sw)), TMP1, 0, loop); + CMPTO(SLJIT_C_NOT_EQUAL, SLJIT_MEM1(STACK_TOP), -(int)(3 * sizeof(sljit_sw)), TMP2, 0, loop); + add_jump(compiler, &common->then_trap->quit, JUMP(SLJIT_JUMP)); + return; + } + else if (common->positive_assert) + { + add_jump(compiler, &common->positive_assert_quit, JUMP(SLJIT_JUMP)); + return; + } + } + +if (common->local_exit) + { + if (common->quit_label == NULL) + add_jump(compiler, &common->quit, JUMP(SLJIT_JUMP)); + else + JUMPTO(SLJIT_JUMP, common->quit_label); + return; + } + +if (opcode == OP_SKIP_ARG) + { + SLJIT_ASSERT(common->control_head_ptr != 0); + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS0, STACK_TOP, 0); + OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_IMM, (sljit_sw)(current->cc + 2)); + sljit_emit_ijump(compiler, SLJIT_CALL2, SLJIT_IMM, SLJIT_FUNC_OFFSET(do_search_mark)); + OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), LOCALS0); + + OP1(SLJIT_MOV, STR_PTR, 0, TMP1, 0); + add_jump(compiler, &common->reset_match, CMP(SLJIT_C_NOT_EQUAL, STR_PTR, 0, SLJIT_IMM, -1)); + return; + } + +if (opcode == OP_SKIP) + OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); +else + OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_IMM, 0); +add_jump(compiler, &common->reset_match, JUMP(SLJIT_JUMP)); +} + +static SLJIT_INLINE void compile_then_trap_backtrackingpath(compiler_common *common, struct backtrack_common *current) +{ +DEFINE_COMPILER; +struct sljit_jump *jump; +int size; + +if (CURRENT_AS(then_trap_backtrack)->then_trap) + { + common->then_trap = CURRENT_AS(then_trap_backtrack)->then_trap; + return; + } + +size = CURRENT_AS(then_trap_backtrack)->framesize; +size = 3 + (size < 0 ? 0 : size); + +OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(size - 3)); +free_stack(common, size); +jump = JUMP(SLJIT_JUMP); + +set_jumps(CURRENT_AS(then_trap_backtrack)->quit, LABEL()); +/* STACK_TOP is set by THEN. */ +if (CURRENT_AS(then_trap_backtrack)->framesize >= 0) + add_jump(compiler, &common->revertframes, JUMP(SLJIT_FAST_CALL)); +OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); +free_stack(common, 3); + +JUMPHERE(jump); +OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, TMP1, 0); +} + +static void compile_backtrackingpath(compiler_common *common, struct backtrack_common *current) +{ +DEFINE_COMPILER; +then_trap_backtrack *save_then_trap = common->then_trap; + +while (current) + { + if (current->nextbacktracks != NULL) + set_jumps(current->nextbacktracks, LABEL()); + switch(*current->cc) + { + case OP_SET_SOM: + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); + free_stack(common, 1); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(0), TMP1, 0); + break; + + case OP_STAR: + case OP_MINSTAR: + case OP_PLUS: + case OP_MINPLUS: + case OP_QUERY: + case OP_MINQUERY: + case OP_UPTO: + case OP_MINUPTO: + case OP_EXACT: + case OP_POSSTAR: + case OP_POSPLUS: + case OP_POSQUERY: + case OP_POSUPTO: + case OP_STARI: + case OP_MINSTARI: + case OP_PLUSI: + case OP_MINPLUSI: + case OP_QUERYI: + case OP_MINQUERYI: + case OP_UPTOI: + case OP_MINUPTOI: + case OP_EXACTI: + case OP_POSSTARI: + case OP_POSPLUSI: + case OP_POSQUERYI: + case OP_POSUPTOI: + case OP_NOTSTAR: + case OP_NOTMINSTAR: + case OP_NOTPLUS: + case OP_NOTMINPLUS: + case OP_NOTQUERY: + case OP_NOTMINQUERY: + case OP_NOTUPTO: + case OP_NOTMINUPTO: + case OP_NOTEXACT: + case OP_NOTPOSSTAR: + case OP_NOTPOSPLUS: + case OP_NOTPOSQUERY: + case OP_NOTPOSUPTO: + case OP_NOTSTARI: + case OP_NOTMINSTARI: + case OP_NOTPLUSI: + case OP_NOTMINPLUSI: + case OP_NOTQUERYI: + case OP_NOTMINQUERYI: + case OP_NOTUPTOI: + case OP_NOTMINUPTOI: + case OP_NOTEXACTI: + case OP_NOTPOSSTARI: + case OP_NOTPOSPLUSI: + case OP_NOTPOSQUERYI: + case OP_NOTPOSUPTOI: + case OP_TYPESTAR: + case OP_TYPEMINSTAR: + case OP_TYPEPLUS: + case OP_TYPEMINPLUS: + case OP_TYPEQUERY: + case OP_TYPEMINQUERY: + case OP_TYPEUPTO: + case OP_TYPEMINUPTO: + case OP_TYPEEXACT: + case OP_TYPEPOSSTAR: + case OP_TYPEPOSPLUS: + case OP_TYPEPOSQUERY: + case OP_TYPEPOSUPTO: + case OP_CLASS: + case OP_NCLASS: +#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 + case OP_XCLASS: +#endif + compile_iterator_backtrackingpath(common, current); + break; + + case OP_REF: + case OP_REFI: + case OP_DNREF: + case OP_DNREFI: + compile_ref_iterator_backtrackingpath(common, current); + break; + + case OP_RECURSE: + compile_recurse_backtrackingpath(common, current); + break; + + case OP_ASSERT: + case OP_ASSERT_NOT: + case OP_ASSERTBACK: + case OP_ASSERTBACK_NOT: + compile_assert_backtrackingpath(common, current); + break; + + case OP_ONCE: + case OP_ONCE_NC: + case OP_BRA: + case OP_CBRA: + case OP_COND: + case OP_SBRA: + case OP_SCBRA: + case OP_SCOND: + compile_bracket_backtrackingpath(common, current); + break; + + case OP_BRAZERO: + if (current->cc[1] > OP_ASSERTBACK_NOT) + compile_bracket_backtrackingpath(common, current); + else + compile_assert_backtrackingpath(common, current); + break; + + case OP_BRAPOS: + case OP_CBRAPOS: + case OP_SBRAPOS: + case OP_SCBRAPOS: + case OP_BRAPOSZERO: + compile_bracketpos_backtrackingpath(common, current); + break; + + case OP_BRAMINZERO: + compile_braminzero_backtrackingpath(common, current); + break; + + case OP_MARK: + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(common->has_skip_arg ? 4 : 0)); + if (common->has_skip_arg) + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); + free_stack(common, common->has_skip_arg ? 5 : 1); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->mark_ptr, TMP1, 0); + if (common->has_skip_arg) + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, TMP2, 0); + break; + + case OP_THEN: + case OP_THEN_ARG: + case OP_PRUNE: + case OP_PRUNE_ARG: + case OP_SKIP: + case OP_SKIP_ARG: + compile_control_verb_backtrackingpath(common, current); + break; + + case OP_COMMIT: + if (!common->local_exit) + OP1(SLJIT_MOV, SLJIT_RETURN_REG, 0, SLJIT_IMM, PCRE_ERROR_NOMATCH); + if (common->quit_label == NULL) + add_jump(compiler, &common->quit, JUMP(SLJIT_JUMP)); + else + JUMPTO(SLJIT_JUMP, common->quit_label); + break; + + case OP_CALLOUT: + case OP_FAIL: + case OP_ACCEPT: + case OP_ASSERT_ACCEPT: + set_jumps(current->topbacktracks, LABEL()); + break; + + case OP_THEN_TRAP: + /* A virtual opcode for then traps. */ + compile_then_trap_backtrackingpath(common, current); + break; + + default: + SLJIT_ASSERT_STOP(); + break; + } + current = current->prev; + } +common->then_trap = save_then_trap; +} + +static SLJIT_INLINE void compile_recurse(compiler_common *common) +{ +DEFINE_COMPILER; +pcre_uchar *cc = common->start + common->currententry->start; +pcre_uchar *ccbegin = cc + 1 + LINK_SIZE + (*cc == OP_BRA ? 0 : IMM2_SIZE); +pcre_uchar *ccend = bracketend(cc); +BOOL needs_control_head; +int framesize = get_framesize(common, cc, NULL, TRUE, &needs_control_head); +int private_data_size = get_private_data_copy_length(common, ccbegin, ccend, needs_control_head); +int alternativesize; +BOOL needs_frame; +backtrack_common altbacktrack; +struct sljit_jump *jump; + +/* Recurse captures then. */ +common->then_trap = NULL; + +SLJIT_ASSERT(*cc == OP_BRA || *cc == OP_CBRA || *cc == OP_CBRAPOS || *cc == OP_SCBRA || *cc == OP_SCBRAPOS); +needs_frame = framesize >= 0; +if (!needs_frame) + framesize = 0; +alternativesize = *(cc + GET(cc, 1)) == OP_ALT ? 1 : 0; + +SLJIT_ASSERT(common->currententry->entry == NULL && common->recursive_head_ptr != 0); +common->currententry->entry = LABEL(); +set_jumps(common->currententry->calls, common->currententry->entry); + +sljit_emit_fast_enter(compiler, TMP2, 0); +allocate_stack(common, private_data_size + framesize + alternativesize); +OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(private_data_size + framesize + alternativesize - 1), TMP2, 0); +copy_private_data(common, ccbegin, ccend, TRUE, private_data_size + framesize + alternativesize, framesize + alternativesize, needs_control_head); +if (needs_control_head) + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, SLJIT_IMM, 0); +OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->recursive_head_ptr, STACK_TOP, 0); +if (needs_frame) + init_frame(common, cc, NULL, framesize + alternativesize - 1, alternativesize, TRUE); + +if (alternativesize > 0) + OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); + +memset(&altbacktrack, 0, sizeof(backtrack_common)); +common->quit_label = NULL; +common->accept_label = NULL; +common->quit = NULL; +common->accept = NULL; +altbacktrack.cc = ccbegin; +cc += GET(cc, 1); +while (1) + { + altbacktrack.top = NULL; + altbacktrack.topbacktracks = NULL; + + if (altbacktrack.cc != ccbegin) + OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); + + compile_matchingpath(common, altbacktrack.cc, cc, &altbacktrack); + if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) + return; + + add_jump(compiler, &common->accept, JUMP(SLJIT_JUMP)); + + compile_backtrackingpath(common, altbacktrack.top); + if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) + return; + set_jumps(altbacktrack.topbacktracks, LABEL()); + + if (*cc != OP_ALT) + break; + + altbacktrack.cc = cc + 1 + LINK_SIZE; + cc += GET(cc, 1); + } + +/* None of them matched. */ +OP1(SLJIT_MOV, TMP3, 0, SLJIT_IMM, 0); +jump = JUMP(SLJIT_JUMP); + +if (common->quit != NULL) + { + set_jumps(common->quit, LABEL()); + OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), common->recursive_head_ptr); + if (needs_frame) + { + OP2(SLJIT_SUB, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, (framesize + alternativesize) * sizeof(sljit_sw)); + add_jump(compiler, &common->revertframes, JUMP(SLJIT_FAST_CALL)); + OP2(SLJIT_ADD, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, (framesize + alternativesize) * sizeof(sljit_sw)); + } + OP1(SLJIT_MOV, TMP3, 0, SLJIT_IMM, 0); + common->quit = NULL; + add_jump(compiler, &common->quit, JUMP(SLJIT_JUMP)); + } + +set_jumps(common->accept, LABEL()); +OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), common->recursive_head_ptr); +if (needs_frame) + { + OP2(SLJIT_SUB, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, (framesize + alternativesize) * sizeof(sljit_sw)); + add_jump(compiler, &common->revertframes, JUMP(SLJIT_FAST_CALL)); + OP2(SLJIT_ADD, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, (framesize + alternativesize) * sizeof(sljit_sw)); + } +OP1(SLJIT_MOV, TMP3, 0, SLJIT_IMM, 1); + +JUMPHERE(jump); +if (common->quit != NULL) + set_jumps(common->quit, LABEL()); +copy_private_data(common, ccbegin, ccend, FALSE, private_data_size + framesize + alternativesize, framesize + alternativesize, needs_control_head); +free_stack(common, private_data_size + framesize + alternativesize); +if (needs_control_head) + { + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), 2 * sizeof(sljit_sw)); + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), sizeof(sljit_sw)); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->recursive_head_ptr, TMP1, 0); + OP1(SLJIT_MOV, TMP1, 0, TMP3, 0); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, TMP2, 0); + } +else + { + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), sizeof(sljit_sw)); + OP1(SLJIT_MOV, TMP1, 0, TMP3, 0); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->recursive_head_ptr, TMP2, 0); + } +sljit_emit_fast_return(compiler, SLJIT_MEM1(STACK_TOP), 0); +} + +#undef COMPILE_BACKTRACKINGPATH +#undef CURRENT_AS + +void +PRIV(jit_compile)(const REAL_PCRE *re, PUBL(extra) *extra, int mode) +{ +struct sljit_compiler *compiler; +backtrack_common rootbacktrack; +compiler_common common_data; +compiler_common *common = &common_data; +const pcre_uint8 *tables = re->tables; +pcre_study_data *study; +int private_data_size; +pcre_uchar *ccend; +executable_functions *functions; +void *executable_func; +sljit_uw executable_size; +sljit_uw total_length; +label_addr_list *label_addr; +struct sljit_label *mainloop_label = NULL; +struct sljit_label *continue_match_label; +struct sljit_label *empty_match_found_label = NULL; +struct sljit_label *empty_match_backtrack_label = NULL; +struct sljit_label *reset_match_label; +struct sljit_label *quit_label; +struct sljit_jump *jump; +struct sljit_jump *minlength_check_failed = NULL; +struct sljit_jump *reqbyte_notfound = NULL; +struct sljit_jump *empty_match = NULL; + +SLJIT_ASSERT((extra->flags & PCRE_EXTRA_STUDY_DATA) != 0); +study = extra->study_data; + +if (!tables) + tables = PRIV(default_tables); + +memset(&rootbacktrack, 0, sizeof(backtrack_common)); +memset(common, 0, sizeof(compiler_common)); +rootbacktrack.cc = (pcre_uchar *)re + re->name_table_offset + re->name_count * re->name_entry_size; + +common->start = rootbacktrack.cc; +common->read_only_data = NULL; +common->read_only_data_size = 0; +common->read_only_data_ptr = NULL; +common->fcc = tables + fcc_offset; +common->lcc = (sljit_sw)(tables + lcc_offset); +common->mode = mode; +common->might_be_empty = study->minlength == 0; +common->nltype = NLTYPE_FIXED; +switch(re->options & PCRE_NEWLINE_BITS) + { + case 0: + /* Compile-time default */ + switch(NEWLINE) + { + case -1: common->newline = (CHAR_CR << 8) | CHAR_NL; common->nltype = NLTYPE_ANY; break; + case -2: common->newline = (CHAR_CR << 8) | CHAR_NL; common->nltype = NLTYPE_ANYCRLF; break; + default: common->newline = NEWLINE; break; + } + break; + case PCRE_NEWLINE_CR: common->newline = CHAR_CR; break; + case PCRE_NEWLINE_LF: common->newline = CHAR_NL; break; + case PCRE_NEWLINE_CR+ + PCRE_NEWLINE_LF: common->newline = (CHAR_CR << 8) | CHAR_NL; break; + case PCRE_NEWLINE_ANY: common->newline = (CHAR_CR << 8) | CHAR_NL; common->nltype = NLTYPE_ANY; break; + case PCRE_NEWLINE_ANYCRLF: common->newline = (CHAR_CR << 8) | CHAR_NL; common->nltype = NLTYPE_ANYCRLF; break; + default: return; + } +common->nlmax = READ_CHAR_MAX; +common->nlmin = 0; +if ((re->options & PCRE_BSR_ANYCRLF) != 0) + common->bsr_nltype = NLTYPE_ANYCRLF; +else if ((re->options & PCRE_BSR_UNICODE) != 0) + common->bsr_nltype = NLTYPE_ANY; +else + { +#ifdef BSR_ANYCRLF + common->bsr_nltype = NLTYPE_ANYCRLF; +#else + common->bsr_nltype = NLTYPE_ANY; +#endif + } +common->bsr_nlmax = READ_CHAR_MAX; +common->bsr_nlmin = 0; +common->endonly = (re->options & PCRE_DOLLAR_ENDONLY) != 0; +common->ctypes = (sljit_sw)(tables + ctypes_offset); +common->name_table = ((pcre_uchar *)re) + re->name_table_offset; +common->name_count = re->name_count; +common->name_entry_size = re->name_entry_size; +common->jscript_compat = (re->options & PCRE_JAVASCRIPT_COMPAT) != 0; +#ifdef SUPPORT_UTF +/* PCRE_UTF[16|32] have the same value as PCRE_UTF8. */ +common->utf = (re->options & PCRE_UTF8) != 0; +#ifdef SUPPORT_UCP +common->use_ucp = (re->options & PCRE_UCP) != 0; +#endif +if (common->utf) + { + if (common->nltype == NLTYPE_ANY) + common->nlmax = 0x2029; + else if (common->nltype == NLTYPE_ANYCRLF) + common->nlmax = (CHAR_CR > CHAR_NL) ? CHAR_CR : CHAR_NL; + else + { + /* We only care about the first newline character. */ + common->nlmax = common->newline & 0xff; + } + + if (common->nltype == NLTYPE_FIXED) + common->nlmin = common->newline & 0xff; + else + common->nlmin = (CHAR_CR < CHAR_NL) ? CHAR_CR : CHAR_NL; + + if (common->bsr_nltype == NLTYPE_ANY) + common->bsr_nlmax = 0x2029; + else + common->bsr_nlmax = (CHAR_CR > CHAR_NL) ? CHAR_CR : CHAR_NL; + common->bsr_nlmin = (CHAR_CR < CHAR_NL) ? CHAR_CR : CHAR_NL; + } +#endif /* SUPPORT_UTF */ +ccend = bracketend(common->start); + +/* Calculate the local space size on the stack. */ +common->ovector_start = LIMIT_MATCH + sizeof(sljit_sw); +common->optimized_cbracket = (pcre_uint8 *)SLJIT_MALLOC(re->top_bracket + 1); +if (!common->optimized_cbracket) + return; +#if defined DEBUG_FORCE_UNOPTIMIZED_CBRAS && DEBUG_FORCE_UNOPTIMIZED_CBRAS == 1 +memset(common->optimized_cbracket, 0, re->top_bracket + 1); +#else +memset(common->optimized_cbracket, 1, re->top_bracket + 1); +#endif + +SLJIT_ASSERT(*common->start == OP_BRA && ccend[-(1 + LINK_SIZE)] == OP_KET); +#if defined DEBUG_FORCE_UNOPTIMIZED_CBRAS && DEBUG_FORCE_UNOPTIMIZED_CBRAS == 2 +common->capture_last_ptr = common->ovector_start; +common->ovector_start += sizeof(sljit_sw); +#endif +if (!check_opcode_types(common, common->start, ccend)) + { + SLJIT_FREE(common->optimized_cbracket); + return; + } + +/* Checking flags and updating ovector_start. */ +if (mode == JIT_COMPILE && (re->flags & PCRE_REQCHSET) != 0 && (re->options & PCRE_NO_START_OPTIMIZE) == 0) + { + common->req_char_ptr = common->ovector_start; + common->ovector_start += sizeof(sljit_sw); + } +if (mode != JIT_COMPILE) + { + common->start_used_ptr = common->ovector_start; + common->ovector_start += sizeof(sljit_sw); + if (mode == JIT_PARTIAL_SOFT_COMPILE) + { + common->hit_start = common->ovector_start; + common->ovector_start += 2 * sizeof(sljit_sw); + } + else + { + SLJIT_ASSERT(mode == JIT_PARTIAL_HARD_COMPILE); + common->needs_start_ptr = TRUE; + } + } +if ((re->options & PCRE_FIRSTLINE) != 0) + { + common->first_line_end = common->ovector_start; + common->ovector_start += sizeof(sljit_sw); + } +#if defined DEBUG_FORCE_CONTROL_HEAD && DEBUG_FORCE_CONTROL_HEAD +common->control_head_ptr = 1; +#endif +if (common->control_head_ptr != 0) + { + common->control_head_ptr = common->ovector_start; + common->ovector_start += sizeof(sljit_sw); + } +if (common->needs_start_ptr && common->has_set_som) + { + /* Saving the real start pointer is necessary. */ + common->start_ptr = common->ovector_start; + common->ovector_start += sizeof(sljit_sw); + } +else + common->needs_start_ptr = FALSE; + +/* Aligning ovector to even number of sljit words. */ +if ((common->ovector_start & sizeof(sljit_sw)) != 0) + common->ovector_start += sizeof(sljit_sw); + +if (common->start_ptr == 0) + common->start_ptr = OVECTOR(0); + +/* Capturing brackets cannot be optimized if callouts are allowed. */ +if (common->capture_last_ptr != 0) + memset(common->optimized_cbracket, 0, re->top_bracket + 1); + +SLJIT_ASSERT(!(common->req_char_ptr != 0 && common->start_used_ptr != 0)); +common->cbra_ptr = OVECTOR_START + (re->top_bracket + 1) * 2 * sizeof(sljit_sw); + +total_length = ccend - common->start; +common->private_data_ptrs = (sljit_si *)SLJIT_MALLOC(total_length * (sizeof(sljit_si) + (common->has_then ? 1 : 0))); +if (!common->private_data_ptrs) + { + SLJIT_FREE(common->optimized_cbracket); + return; + } +memset(common->private_data_ptrs, 0, total_length * sizeof(sljit_si)); + +private_data_size = common->cbra_ptr + (re->top_bracket + 1) * sizeof(sljit_sw); +set_private_data_ptrs(common, &private_data_size, ccend); +if (private_data_size > SLJIT_MAX_LOCAL_SIZE) + { + SLJIT_FREE(common->private_data_ptrs); + SLJIT_FREE(common->optimized_cbracket); + return; + } + +if (common->has_then) + { + common->then_offsets = (pcre_uint8 *)(common->private_data_ptrs + total_length); + memset(common->then_offsets, 0, total_length); + set_then_offsets(common, common->start, NULL); + } + +if (common->read_only_data_size > 0) + { + common->read_only_data = (sljit_uw *)SLJIT_MALLOC(common->read_only_data_size); + if (common->read_only_data == NULL) + { + SLJIT_FREE(common->optimized_cbracket); + SLJIT_FREE(common->private_data_ptrs); + return; + } + common->read_only_data_ptr = common->read_only_data; + } + +compiler = sljit_create_compiler(); +if (!compiler) + { + SLJIT_FREE(common->optimized_cbracket); + SLJIT_FREE(common->private_data_ptrs); + if (common->read_only_data) + SLJIT_FREE(common->read_only_data); + return; + } +common->compiler = compiler; + +/* Main pcre_jit_exec entry. */ +sljit_emit_enter(compiler, 0, 1, 5, 5, 0, 0, private_data_size); + +/* Register init. */ +reset_ovector(common, (re->top_bracket + 1) * 2); +if (common->req_char_ptr != 0) + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->req_char_ptr, SLJIT_R0, 0); + +OP1(SLJIT_MOV, ARGUMENTS, 0, SLJIT_S0, 0); +OP1(SLJIT_MOV, TMP1, 0, SLJIT_S0, 0); +OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, str)); +OP1(SLJIT_MOV, STR_END, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, end)); +OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, stack)); +OP1(SLJIT_MOV_UI, TMP1, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, limit_match)); +OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(TMP2), SLJIT_OFFSETOF(struct sljit_stack, base)); +OP1(SLJIT_MOV, STACK_LIMIT, 0, SLJIT_MEM1(TMP2), SLJIT_OFFSETOF(struct sljit_stack, limit)); +OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LIMIT_MATCH, TMP1, 0); + +if (mode == JIT_PARTIAL_SOFT_COMPILE) + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->hit_start, SLJIT_IMM, -1); +if (common->mark_ptr != 0) + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->mark_ptr, SLJIT_IMM, 0); +if (common->control_head_ptr != 0) + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, SLJIT_IMM, 0); + +/* Main part of the matching */ +if ((re->options & PCRE_ANCHORED) == 0) + { + mainloop_label = mainloop_entry(common, (re->flags & PCRE_HASCRORLF) != 0, (re->options & PCRE_FIRSTLINE) != 0); + continue_match_label = LABEL(); + /* Forward search if possible. */ + if ((re->options & PCRE_NO_START_OPTIMIZE) == 0) + { + if (mode == JIT_COMPILE && fast_forward_first_n_chars(common, (re->options & PCRE_FIRSTLINE) != 0)) + { + /* If read_only_data is reallocated, we might have an allocation failure. */ + if (common->read_only_data_size > 0 && common->read_only_data == NULL) + { + sljit_free_compiler(compiler); + SLJIT_FREE(common->optimized_cbracket); + SLJIT_FREE(common->private_data_ptrs); + return; + } + } + else if ((re->flags & PCRE_FIRSTSET) != 0) + fast_forward_first_char(common, (pcre_uchar)re->first_char, (re->flags & PCRE_FCH_CASELESS) != 0, (re->options & PCRE_FIRSTLINE) != 0); + else if ((re->flags & PCRE_STARTLINE) != 0) + fast_forward_newline(common, (re->options & PCRE_FIRSTLINE) != 0); + else if ((re->flags & PCRE_STARTLINE) == 0 && study != NULL && (study->flags & PCRE_STUDY_MAPPED) != 0) + fast_forward_start_bits(common, study->start_bits, (re->options & PCRE_FIRSTLINE) != 0); + } + } +else + continue_match_label = LABEL(); + +if (mode == JIT_COMPILE && study->minlength > 0 && (re->options & PCRE_NO_START_OPTIMIZE) == 0) + { + OP1(SLJIT_MOV, SLJIT_RETURN_REG, 0, SLJIT_IMM, PCRE_ERROR_NOMATCH); + OP2(SLJIT_ADD, TMP2, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(study->minlength)); + minlength_check_failed = CMP(SLJIT_C_GREATER, TMP2, 0, STR_END, 0); + } +if (common->req_char_ptr != 0) + reqbyte_notfound = search_requested_char(common, (pcre_uchar)re->req_char, (re->flags & PCRE_RCH_CASELESS) != 0, (re->flags & PCRE_FIRSTSET) != 0); + +/* Store the current STR_PTR in OVECTOR(0). */ +OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(0), STR_PTR, 0); +/* Copy the limit of allowed recursions. */ +OP1(SLJIT_MOV, COUNT_MATCH, 0, SLJIT_MEM1(SLJIT_SP), LIMIT_MATCH); +if (common->capture_last_ptr != 0) + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->capture_last_ptr, SLJIT_IMM, -1); + +if (common->needs_start_ptr) + { + SLJIT_ASSERT(common->start_ptr != OVECTOR(0)); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->start_ptr, STR_PTR, 0); + } +else + SLJIT_ASSERT(common->start_ptr == OVECTOR(0)); + +/* Copy the beginning of the string. */ +if (mode == JIT_PARTIAL_SOFT_COMPILE) + { + jump = CMP(SLJIT_C_NOT_EQUAL, SLJIT_MEM1(SLJIT_SP), common->hit_start, SLJIT_IMM, -1); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->start_used_ptr, STR_PTR, 0); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->hit_start + sizeof(sljit_sw), STR_PTR, 0); + JUMPHERE(jump); + } +else if (mode == JIT_PARTIAL_HARD_COMPILE) + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->start_used_ptr, STR_PTR, 0); + +compile_matchingpath(common, common->start, ccend, &rootbacktrack); +if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) + { + sljit_free_compiler(compiler); + SLJIT_FREE(common->optimized_cbracket); + SLJIT_FREE(common->private_data_ptrs); + if (common->read_only_data) + SLJIT_FREE(common->read_only_data); + return; + } + +if (common->might_be_empty) + { + empty_match = CMP(SLJIT_C_EQUAL, STR_PTR, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(0)); + empty_match_found_label = LABEL(); + } + +common->accept_label = LABEL(); +if (common->accept != NULL) + set_jumps(common->accept, common->accept_label); + +/* This means we have a match. Update the ovector. */ +copy_ovector(common, re->top_bracket + 1); +common->quit_label = common->forced_quit_label = LABEL(); +if (common->quit != NULL) + set_jumps(common->quit, common->quit_label); +if (common->forced_quit != NULL) + set_jumps(common->forced_quit, common->forced_quit_label); +if (minlength_check_failed != NULL) + SET_LABEL(minlength_check_failed, common->forced_quit_label); +sljit_emit_return(compiler, SLJIT_MOV, SLJIT_RETURN_REG, 0); + +if (mode != JIT_COMPILE) + { + common->partialmatchlabel = LABEL(); + set_jumps(common->partialmatch, common->partialmatchlabel); + return_with_partial_match(common, common->quit_label); + } + +if (common->might_be_empty) + empty_match_backtrack_label = LABEL(); +compile_backtrackingpath(common, rootbacktrack.top); +if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) + { + sljit_free_compiler(compiler); + SLJIT_FREE(common->optimized_cbracket); + SLJIT_FREE(common->private_data_ptrs); + if (common->read_only_data) + SLJIT_FREE(common->read_only_data); + return; + } + +SLJIT_ASSERT(rootbacktrack.prev == NULL); +reset_match_label = LABEL(); + +if (mode == JIT_PARTIAL_SOFT_COMPILE) + { + /* Update hit_start only in the first time. */ + jump = CMP(SLJIT_C_NOT_EQUAL, SLJIT_MEM1(SLJIT_SP), common->hit_start, SLJIT_IMM, 0); + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->start_used_ptr); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->start_used_ptr, SLJIT_IMM, -1); + OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->hit_start, TMP1, 0); + JUMPHERE(jump); + } + +/* Check we have remaining characters. */ +if ((re->options & PCRE_ANCHORED) == 0 && (re->options & PCRE_FIRSTLINE) != 0) + { + SLJIT_ASSERT(common->first_line_end != 0); + OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->first_line_end); + } + +OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(SLJIT_SP), common->start_ptr); + +if ((re->options & PCRE_ANCHORED) == 0) + { + if (common->ff_newline_shortcut != NULL) + { + if ((re->options & PCRE_FIRSTLINE) == 0) + CMPTO(SLJIT_C_LESS, STR_PTR, 0, STR_END, 0, common->ff_newline_shortcut); + /* There cannot be more newlines here. */ + } + else + { + if ((re->options & PCRE_FIRSTLINE) == 0) + CMPTO(SLJIT_C_LESS, STR_PTR, 0, STR_END, 0, mainloop_label); + else + CMPTO(SLJIT_C_LESS, STR_PTR, 0, TMP1, 0, mainloop_label); + } + } + +/* No more remaining characters. */ +if (reqbyte_notfound != NULL) + JUMPHERE(reqbyte_notfound); + +if (mode == JIT_PARTIAL_SOFT_COMPILE) + CMPTO(SLJIT_C_NOT_EQUAL, SLJIT_MEM1(SLJIT_SP), common->hit_start, SLJIT_IMM, -1, common->partialmatchlabel); + +OP1(SLJIT_MOV, SLJIT_RETURN_REG, 0, SLJIT_IMM, PCRE_ERROR_NOMATCH); +JUMPTO(SLJIT_JUMP, common->quit_label); + +flush_stubs(common); + +if (common->might_be_empty) + { + JUMPHERE(empty_match); + OP1(SLJIT_MOV, TMP1, 0, ARGUMENTS, 0); + OP1(SLJIT_MOV_UB, TMP2, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, notempty)); + CMPTO(SLJIT_C_NOT_EQUAL, TMP2, 0, SLJIT_IMM, 0, empty_match_backtrack_label); + OP1(SLJIT_MOV_UB, TMP2, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, notempty_atstart)); + CMPTO(SLJIT_C_EQUAL, TMP2, 0, SLJIT_IMM, 0, empty_match_found_label); + OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, str)); + CMPTO(SLJIT_C_NOT_EQUAL, TMP2, 0, STR_PTR, 0, empty_match_found_label); + JUMPTO(SLJIT_JUMP, empty_match_backtrack_label); + } + +common->currententry = common->entries; +common->local_exit = TRUE; +quit_label = common->quit_label; +while (common->currententry != NULL) + { + /* Might add new entries. */ + compile_recurse(common); + if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) + { + sljit_free_compiler(compiler); + SLJIT_FREE(common->optimized_cbracket); + SLJIT_FREE(common->private_data_ptrs); + if (common->read_only_data) + SLJIT_FREE(common->read_only_data); + return; + } + flush_stubs(common); + common->currententry = common->currententry->next; + } +common->local_exit = FALSE; +common->quit_label = quit_label; + +/* Allocating stack, returns with PCRE_ERROR_JIT_STACKLIMIT if fails. */ +/* This is a (really) rare case. */ +set_jumps(common->stackalloc, LABEL()); +/* RETURN_ADDR is not a saved register. */ +sljit_emit_fast_enter(compiler, SLJIT_MEM1(SLJIT_SP), LOCALS0); +OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS1, TMP2, 0); +OP1(SLJIT_MOV, TMP1, 0, ARGUMENTS, 0); +OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, stack)); +OP1(SLJIT_MOV, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(struct sljit_stack, top), STACK_TOP, 0); +OP2(SLJIT_ADD, TMP2, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(struct sljit_stack, limit), SLJIT_IMM, STACK_GROWTH_RATE); + +sljit_emit_ijump(compiler, SLJIT_CALL2, SLJIT_IMM, SLJIT_FUNC_OFFSET(sljit_stack_resize)); +jump = CMP(SLJIT_C_NOT_EQUAL, SLJIT_RETURN_REG, 0, SLJIT_IMM, 0); +OP1(SLJIT_MOV, TMP1, 0, ARGUMENTS, 0); +OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, stack)); +OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(struct sljit_stack, top)); +OP1(SLJIT_MOV, STACK_LIMIT, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(struct sljit_stack, limit)); +OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), LOCALS1); +sljit_emit_fast_return(compiler, SLJIT_MEM1(SLJIT_SP), LOCALS0); + +/* Allocation failed. */ +JUMPHERE(jump); +/* We break the return address cache here, but this is a really rare case. */ +OP1(SLJIT_MOV, SLJIT_RETURN_REG, 0, SLJIT_IMM, PCRE_ERROR_JIT_STACKLIMIT); +JUMPTO(SLJIT_JUMP, common->quit_label); + +/* Call limit reached. */ +set_jumps(common->calllimit, LABEL()); +OP1(SLJIT_MOV, SLJIT_RETURN_REG, 0, SLJIT_IMM, PCRE_ERROR_MATCHLIMIT); +JUMPTO(SLJIT_JUMP, common->quit_label); + +if (common->revertframes != NULL) + { + set_jumps(common->revertframes, LABEL()); + do_revertframes(common); + } +if (common->wordboundary != NULL) + { + set_jumps(common->wordboundary, LABEL()); + check_wordboundary(common); + } +if (common->anynewline != NULL) + { + set_jumps(common->anynewline, LABEL()); + check_anynewline(common); + } +if (common->hspace != NULL) + { + set_jumps(common->hspace, LABEL()); + check_hspace(common); + } +if (common->vspace != NULL) + { + set_jumps(common->vspace, LABEL()); + check_vspace(common); + } +if (common->casefulcmp != NULL) + { + set_jumps(common->casefulcmp, LABEL()); + do_casefulcmp(common); + } +if (common->caselesscmp != NULL) + { + set_jumps(common->caselesscmp, LABEL()); + do_caselesscmp(common); + } +if (common->reset_match != NULL) + { + set_jumps(common->reset_match, LABEL()); + do_reset_match(common, (re->top_bracket + 1) * 2); + CMPTO(SLJIT_C_GREATER, STR_PTR, 0, TMP1, 0, continue_match_label); + OP1(SLJIT_MOV, STR_PTR, 0, TMP1, 0); + JUMPTO(SLJIT_JUMP, reset_match_label); + } +#ifdef SUPPORT_UTF +#ifdef COMPILE_PCRE8 +if (common->utfreadchar != NULL) + { + set_jumps(common->utfreadchar, LABEL()); + do_utfreadchar(common); + } +if (common->utfreadchar16 != NULL) + { + set_jumps(common->utfreadchar16, LABEL()); + do_utfreadchar16(common); + } +if (common->utfreadtype8 != NULL) + { + set_jumps(common->utfreadtype8, LABEL()); + do_utfreadtype8(common); + } +#endif /* COMPILE_PCRE8 */ +#endif /* SUPPORT_UTF */ +#ifdef SUPPORT_UCP +if (common->getucd != NULL) + { + set_jumps(common->getucd, LABEL()); + do_getucd(common); + } +#endif + +SLJIT_ASSERT(common->read_only_data + (common->read_only_data_size >> SLJIT_WORD_SHIFT) == common->read_only_data_ptr); +SLJIT_FREE(common->optimized_cbracket); +SLJIT_FREE(common->private_data_ptrs); + +executable_func = sljit_generate_code(compiler); +executable_size = sljit_get_generated_code_size(compiler); +label_addr = common->label_addrs; +while (label_addr != NULL) + { + *label_addr->update_addr = sljit_get_label_addr(label_addr->label); + label_addr = label_addr->next; + } +sljit_free_compiler(compiler); +if (executable_func == NULL) + { + if (common->read_only_data) + SLJIT_FREE(common->read_only_data); + return; + } + +/* Reuse the function descriptor if possible. */ +if ((extra->flags & PCRE_EXTRA_EXECUTABLE_JIT) != 0 && extra->executable_jit != NULL) + functions = (executable_functions *)extra->executable_jit; +else + { + /* Note: If your memory-checker has flagged the allocation below as a + * memory leak, it is probably because you either forgot to call + * pcre_free_study() (or pcre16_free_study()) on the pcre_extra (or + * pcre16_extra) object, or you called said function after having + * cleared the PCRE_EXTRA_EXECUTABLE_JIT bit from the "flags" field + * of the object. (The function will only free the JIT data if the + * bit remains set, as the bit indicates that the pointer to the data + * is valid.) + */ + functions = SLJIT_MALLOC(sizeof(executable_functions)); + if (functions == NULL) + { + /* This case is highly unlikely since we just recently + freed a lot of memory. Not impossible though. */ + sljit_free_code(executable_func); + if (common->read_only_data) + SLJIT_FREE(common->read_only_data); + return; + } + memset(functions, 0, sizeof(executable_functions)); + functions->top_bracket = (re->top_bracket + 1) * 2; + functions->limit_match = (re->flags & PCRE_MLSET) != 0 ? re->limit_match : 0; + extra->executable_jit = functions; + extra->flags |= PCRE_EXTRA_EXECUTABLE_JIT; + } + +functions->executable_funcs[mode] = executable_func; +functions->read_only_data[mode] = common->read_only_data; +functions->executable_sizes[mode] = executable_size; +} + +static int jit_machine_stack_exec(jit_arguments *arguments, void* executable_func) +{ +union { + void* executable_func; + jit_function call_executable_func; +} convert_executable_func; +pcre_uint8 local_space[MACHINE_STACK_SIZE]; +struct sljit_stack local_stack; + +local_stack.top = (sljit_sw)&local_space; +local_stack.base = local_stack.top; +local_stack.limit = local_stack.base + MACHINE_STACK_SIZE; +local_stack.max_limit = local_stack.limit; +arguments->stack = &local_stack; +convert_executable_func.executable_func = executable_func; +return convert_executable_func.call_executable_func(arguments); +} + +int +PRIV(jit_exec)(const PUBL(extra) *extra_data, const pcre_uchar *subject, + int length, int start_offset, int options, int *offsets, int offset_count) +{ +executable_functions *functions = (executable_functions *)extra_data->executable_jit; +union { + void* executable_func; + jit_function call_executable_func; +} convert_executable_func; +jit_arguments arguments; +int max_offset_count; +int retval; +int mode = JIT_COMPILE; + +if ((options & PCRE_PARTIAL_HARD) != 0) + mode = JIT_PARTIAL_HARD_COMPILE; +else if ((options & PCRE_PARTIAL_SOFT) != 0) + mode = JIT_PARTIAL_SOFT_COMPILE; + +if (functions->executable_funcs[mode] == NULL) + return PCRE_ERROR_JIT_BADOPTION; + +/* Sanity checks should be handled by pcre_exec. */ +arguments.str = subject + start_offset; +arguments.begin = subject; +arguments.end = subject + length; +arguments.mark_ptr = NULL; +/* JIT decreases this value less frequently than the interpreter. */ +arguments.limit_match = ((extra_data->flags & PCRE_EXTRA_MATCH_LIMIT) == 0) ? MATCH_LIMIT : (pcre_uint32)(extra_data->match_limit); +if (functions->limit_match != 0 && functions->limit_match < arguments.limit_match) + arguments.limit_match = functions->limit_match; +arguments.notbol = (options & PCRE_NOTBOL) != 0; +arguments.noteol = (options & PCRE_NOTEOL) != 0; +arguments.notempty = (options & PCRE_NOTEMPTY) != 0; +arguments.notempty_atstart = (options & PCRE_NOTEMPTY_ATSTART) != 0; +arguments.offsets = offsets; +arguments.callout_data = (extra_data->flags & PCRE_EXTRA_CALLOUT_DATA) != 0 ? extra_data->callout_data : NULL; +arguments.real_offset_count = offset_count; + +/* pcre_exec() rounds offset_count to a multiple of 3, and then uses only 2/3 of +the output vector for storing captured strings, with the remainder used as +workspace. We don't need the workspace here. For compatibility, we limit the +number of captured strings in the same way as pcre_exec(), so that the user +gets the same result with and without JIT. */ + +if (offset_count != 2) + offset_count = ((offset_count - (offset_count % 3)) * 2) / 3; +max_offset_count = functions->top_bracket; +if (offset_count > max_offset_count) + offset_count = max_offset_count; +arguments.offset_count = offset_count; + +if (functions->callback) + arguments.stack = (struct sljit_stack *)functions->callback(functions->userdata); +else + arguments.stack = (struct sljit_stack *)functions->userdata; + +if (arguments.stack == NULL) + retval = jit_machine_stack_exec(&arguments, functions->executable_funcs[mode]); +else + { + convert_executable_func.executable_func = functions->executable_funcs[mode]; + retval = convert_executable_func.call_executable_func(&arguments); + } + +if (retval * 2 > offset_count) + retval = 0; +if ((extra_data->flags & PCRE_EXTRA_MARK) != 0) + *(extra_data->mark) = arguments.mark_ptr; + +return retval; +} + +#if defined COMPILE_PCRE8 +PCRE_EXP_DEFN int PCRE_CALL_CONVENTION +pcre_jit_exec(const pcre *argument_re, const pcre_extra *extra_data, + PCRE_SPTR subject, int length, int start_offset, int options, + int *offsets, int offset_count, pcre_jit_stack *stack) +#elif defined COMPILE_PCRE16 +PCRE_EXP_DEFN int PCRE_CALL_CONVENTION +pcre16_jit_exec(const pcre16 *argument_re, const pcre16_extra *extra_data, + PCRE_SPTR16 subject, int length, int start_offset, int options, + int *offsets, int offset_count, pcre16_jit_stack *stack) +#elif defined COMPILE_PCRE32 +PCRE_EXP_DEFN int PCRE_CALL_CONVENTION +pcre32_jit_exec(const pcre32 *argument_re, const pcre32_extra *extra_data, + PCRE_SPTR32 subject, int length, int start_offset, int options, + int *offsets, int offset_count, pcre32_jit_stack *stack) +#endif +{ +pcre_uchar *subject_ptr = (pcre_uchar *)subject; +executable_functions *functions = (executable_functions *)extra_data->executable_jit; +union { + void* executable_func; + jit_function call_executable_func; +} convert_executable_func; +jit_arguments arguments; +int max_offset_count; +int retval; +int mode = JIT_COMPILE; + +SLJIT_UNUSED_ARG(argument_re); + +/* Plausibility checks */ +if ((options & ~PUBLIC_JIT_EXEC_OPTIONS) != 0) return PCRE_ERROR_JIT_BADOPTION; + +if ((options & PCRE_PARTIAL_HARD) != 0) + mode = JIT_PARTIAL_HARD_COMPILE; +else if ((options & PCRE_PARTIAL_SOFT) != 0) + mode = JIT_PARTIAL_SOFT_COMPILE; + +if (functions->executable_funcs[mode] == NULL) + return PCRE_ERROR_JIT_BADOPTION; + +/* Sanity checks should be handled by pcre_exec. */ +arguments.stack = (struct sljit_stack *)stack; +arguments.str = subject_ptr + start_offset; +arguments.begin = subject_ptr; +arguments.end = subject_ptr + length; +arguments.mark_ptr = NULL; +/* JIT decreases this value less frequently than the interpreter. */ +arguments.limit_match = ((extra_data->flags & PCRE_EXTRA_MATCH_LIMIT) == 0) ? MATCH_LIMIT : (pcre_uint32)(extra_data->match_limit); +if (functions->limit_match != 0 && functions->limit_match < arguments.limit_match) + arguments.limit_match = functions->limit_match; +arguments.notbol = (options & PCRE_NOTBOL) != 0; +arguments.noteol = (options & PCRE_NOTEOL) != 0; +arguments.notempty = (options & PCRE_NOTEMPTY) != 0; +arguments.notempty_atstart = (options & PCRE_NOTEMPTY_ATSTART) != 0; +arguments.offsets = offsets; +arguments.callout_data = (extra_data->flags & PCRE_EXTRA_CALLOUT_DATA) != 0 ? extra_data->callout_data : NULL; +arguments.real_offset_count = offset_count; + +/* pcre_exec() rounds offset_count to a multiple of 3, and then uses only 2/3 of +the output vector for storing captured strings, with the remainder used as +workspace. We don't need the workspace here. For compatibility, we limit the +number of captured strings in the same way as pcre_exec(), so that the user +gets the same result with and without JIT. */ + +if (offset_count != 2) + offset_count = ((offset_count - (offset_count % 3)) * 2) / 3; +max_offset_count = functions->top_bracket; +if (offset_count > max_offset_count) + offset_count = max_offset_count; +arguments.offset_count = offset_count; + +convert_executable_func.executable_func = functions->executable_funcs[mode]; +retval = convert_executable_func.call_executable_func(&arguments); + +if (retval * 2 > offset_count) + retval = 0; +if ((extra_data->flags & PCRE_EXTRA_MARK) != 0) + *(extra_data->mark) = arguments.mark_ptr; + +return retval; +} + +void +PRIV(jit_free)(void *executable_funcs) +{ +int i; +executable_functions *functions = (executable_functions *)executable_funcs; +for (i = 0; i < JIT_NUMBER_OF_COMPILE_MODES; i++) + { + if (functions->executable_funcs[i] != NULL) + sljit_free_code(functions->executable_funcs[i]); + if (functions->read_only_data[i] != NULL) + SLJIT_FREE(functions->read_only_data[i]); + } +SLJIT_FREE(functions); +} + +int +PRIV(jit_get_size)(void *executable_funcs) +{ +int i; +sljit_uw size = 0; +sljit_uw *executable_sizes = ((executable_functions *)executable_funcs)->executable_sizes; +for (i = 0; i < JIT_NUMBER_OF_COMPILE_MODES; i++) + size += executable_sizes[i]; +return (int)size; +} + +const char* +PRIV(jit_get_target)(void) +{ +return sljit_get_platform_name(); +} + +#if defined COMPILE_PCRE8 +PCRE_EXP_DECL pcre_jit_stack * +pcre_jit_stack_alloc(int startsize, int maxsize) +#elif defined COMPILE_PCRE16 +PCRE_EXP_DECL pcre16_jit_stack * +pcre16_jit_stack_alloc(int startsize, int maxsize) +#elif defined COMPILE_PCRE32 +PCRE_EXP_DECL pcre32_jit_stack * +pcre32_jit_stack_alloc(int startsize, int maxsize) +#endif +{ +if (startsize < 1 || maxsize < 1) + return NULL; +if (startsize > maxsize) + startsize = maxsize; +startsize = (startsize + STACK_GROWTH_RATE - 1) & ~(STACK_GROWTH_RATE - 1); +maxsize = (maxsize + STACK_GROWTH_RATE - 1) & ~(STACK_GROWTH_RATE - 1); +return (PUBL(jit_stack)*)sljit_allocate_stack(startsize, maxsize); +} + +#if defined COMPILE_PCRE8 +PCRE_EXP_DECL void +pcre_jit_stack_free(pcre_jit_stack *stack) +#elif defined COMPILE_PCRE16 +PCRE_EXP_DECL void +pcre16_jit_stack_free(pcre16_jit_stack *stack) +#elif defined COMPILE_PCRE32 +PCRE_EXP_DECL void +pcre32_jit_stack_free(pcre32_jit_stack *stack) +#endif +{ +sljit_free_stack((struct sljit_stack *)stack); +} + +#if defined COMPILE_PCRE8 +PCRE_EXP_DECL void +pcre_assign_jit_stack(pcre_extra *extra, pcre_jit_callback callback, void *userdata) +#elif defined COMPILE_PCRE16 +PCRE_EXP_DECL void +pcre16_assign_jit_stack(pcre16_extra *extra, pcre16_jit_callback callback, void *userdata) +#elif defined COMPILE_PCRE32 +PCRE_EXP_DECL void +pcre32_assign_jit_stack(pcre32_extra *extra, pcre32_jit_callback callback, void *userdata) +#endif +{ +executable_functions *functions; +if (extra != NULL && + (extra->flags & PCRE_EXTRA_EXECUTABLE_JIT) != 0 && + extra->executable_jit != NULL) + { + functions = (executable_functions *)extra->executable_jit; + functions->callback = callback; + functions->userdata = userdata; + } +} + +#if defined COMPILE_PCRE8 +PCRE_EXP_DECL void +pcre_jit_free_unused_memory(void) +#elif defined COMPILE_PCRE16 +PCRE_EXP_DECL void +pcre16_jit_free_unused_memory(void) +#elif defined COMPILE_PCRE32 +PCRE_EXP_DECL void +pcre32_jit_free_unused_memory(void) +#endif +{ +sljit_free_unused_memory_exec(); +} + +#else /* SUPPORT_JIT */ + +/* These are dummy functions to avoid linking errors when JIT support is not +being compiled. */ + +#if defined COMPILE_PCRE8 +PCRE_EXP_DECL pcre_jit_stack * +pcre_jit_stack_alloc(int startsize, int maxsize) +#elif defined COMPILE_PCRE16 +PCRE_EXP_DECL pcre16_jit_stack * +pcre16_jit_stack_alloc(int startsize, int maxsize) +#elif defined COMPILE_PCRE32 +PCRE_EXP_DECL pcre32_jit_stack * +pcre32_jit_stack_alloc(int startsize, int maxsize) +#endif +{ +(void)startsize; +(void)maxsize; +return NULL; +} + +#if defined COMPILE_PCRE8 +PCRE_EXP_DECL void +pcre_jit_stack_free(pcre_jit_stack *stack) +#elif defined COMPILE_PCRE16 +PCRE_EXP_DECL void +pcre16_jit_stack_free(pcre16_jit_stack *stack) +#elif defined COMPILE_PCRE32 +PCRE_EXP_DECL void +pcre32_jit_stack_free(pcre32_jit_stack *stack) +#endif +{ +(void)stack; +} + +#if defined COMPILE_PCRE8 +PCRE_EXP_DECL void +pcre_assign_jit_stack(pcre_extra *extra, pcre_jit_callback callback, void *userdata) +#elif defined COMPILE_PCRE16 +PCRE_EXP_DECL void +pcre16_assign_jit_stack(pcre16_extra *extra, pcre16_jit_callback callback, void *userdata) +#elif defined COMPILE_PCRE32 +PCRE_EXP_DECL void +pcre32_assign_jit_stack(pcre32_extra *extra, pcre32_jit_callback callback, void *userdata) +#endif +{ +(void)extra; +(void)callback; +(void)userdata; +} + +#if defined COMPILE_PCRE8 +PCRE_EXP_DECL void +pcre_jit_free_unused_memory(void) +#elif defined COMPILE_PCRE16 +PCRE_EXP_DECL void +pcre16_jit_free_unused_memory(void) +#elif defined COMPILE_PCRE32 +PCRE_EXP_DECL void +pcre32_jit_free_unused_memory(void) +#endif +{ +} + +#endif + +/* End of pcre_jit_compile.c */ diff --git a/src/private/pcre_src/pcre_maketables.c b/src/private/pcre_src/pcre_maketables.c new file mode 100644 index 000000000..a44a6eaa9 --- /dev/null +++ b/src/private/pcre_src/pcre_maketables.c @@ -0,0 +1,156 @@ +/************************************************* +* Perl-Compatible Regular Expressions * +*************************************************/ + +/* PCRE is a library of functions to support regular expressions whose syntax +and semantics are as close as possible to those of the Perl 5 language. + + Written by Philip Hazel + Copyright (c) 1997-2012 University of Cambridge + +----------------------------------------------------------------------------- +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * Neither the name of the University of Cambridge nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. +----------------------------------------------------------------------------- +*/ + + +/* This module contains the external function pcre_maketables(), which builds +character tables for PCRE in the current locale. The file is compiled on its +own as part of the PCRE library. However, it is also included in the +compilation of dftables.c, in which case the macro DFTABLES is defined. */ + + +#ifndef DFTABLES +# ifdef HAVE_CONFIG_H +# include "config.h" +# endif +# include "pcre_internal.h" +#endif + + +/************************************************* +* Create PCRE character tables * +*************************************************/ + +/* This function builds a set of character tables for use by PCRE and returns +a pointer to them. They are build using the ctype functions, and consequently +their contents will depend upon the current locale setting. When compiled as +part of the library, the store is obtained via PUBL(malloc)(), but when +compiled inside dftables, use malloc(). + +Arguments: none +Returns: pointer to the contiguous block of data +*/ + +#if defined COMPILE_PCRE8 +const unsigned char * +pcre_maketables(void) +#elif defined COMPILE_PCRE16 +const unsigned char * +pcre16_maketables(void) +#elif defined COMPILE_PCRE32 +const unsigned char * +pcre32_maketables(void) +#endif +{ +unsigned char *yield, *p; +int i; + +#ifndef DFTABLES +yield = (unsigned char*)(PUBL(malloc))(tables_length); +#else +yield = (unsigned char*)malloc(tables_length); +#endif + +if (yield == NULL) return NULL; +p = yield; + +/* First comes the lower casing table */ + +for (i = 0; i < 256; i++) *p++ = tolower(i); + +/* Next the case-flipping table */ + +for (i = 0; i < 256; i++) *p++ = islower(i)? toupper(i) : tolower(i); + +/* Then the character class tables. Don't try to be clever and save effort on +exclusive ones - in some locales things may be different. + +Note that the table for "space" includes everything "isspace" gives, including +VT in the default locale. This makes it work for the POSIX class [:space:]. +From release 8.34 is is also correct for Perl space, because Perl added VT at +release 5.18. + +Note also that it is possible for a character to be alnum or alpha without +being lower or upper, such as "male and female ordinals" (\xAA and \xBA) in the +fr_FR locale (at least under Debian Linux's locales as of 12/2005). So we must +test for alnum specially. */ + +memset(p, 0, cbit_length); +for (i = 0; i < 256; i++) + { + if (isdigit(i)) p[cbit_digit + i/8] |= 1 << (i&7); + if (isupper(i)) p[cbit_upper + i/8] |= 1 << (i&7); + if (islower(i)) p[cbit_lower + i/8] |= 1 << (i&7); + if (isalnum(i)) p[cbit_word + i/8] |= 1 << (i&7); + if (i == '_') p[cbit_word + i/8] |= 1 << (i&7); + if (isspace(i)) p[cbit_space + i/8] |= 1 << (i&7); + if (isxdigit(i))p[cbit_xdigit + i/8] |= 1 << (i&7); + if (isgraph(i)) p[cbit_graph + i/8] |= 1 << (i&7); + if (isprint(i)) p[cbit_print + i/8] |= 1 << (i&7); + if (ispunct(i)) p[cbit_punct + i/8] |= 1 << (i&7); + if (iscntrl(i)) p[cbit_cntrl + i/8] |= 1 << (i&7); + } +p += cbit_length; + +/* Finally, the character type table. In this, we used to exclude VT from the +white space chars, because Perl didn't recognize it as such for \s and for +comments within regexes. However, Perl changed at release 5.18, so PCRE changed +at release 8.34. */ + +for (i = 0; i < 256; i++) + { + int x = 0; + if (isspace(i)) x += ctype_space; + if (isalpha(i)) x += ctype_letter; + if (isdigit(i)) x += ctype_digit; + if (isxdigit(i)) x += ctype_xdigit; + if (isalnum(i) || i == '_') x += ctype_word; + + /* Note: strchr includes the terminating zero in the characters it considers. + In this instance, that is ok because we want binary zero to be flagged as a + meta-character, which in this sense is any character that terminates a run + of data characters. */ + + if (strchr("\\*+?{^.$|()[", i) != 0) x += ctype_meta; + *p++ = x; + } + +return yield; +} + +/* End of pcre_maketables.c */ diff --git a/src/private/pcre_src/pcre_newline.c b/src/private/pcre_src/pcre_newline.c new file mode 100644 index 000000000..b8f5a4de1 --- /dev/null +++ b/src/private/pcre_src/pcre_newline.c @@ -0,0 +1,210 @@ +/************************************************* +* Perl-Compatible Regular Expressions * +*************************************************/ + +/* PCRE is a library of functions to support regular expressions whose syntax +and semantics are as close as possible to those of the Perl 5 language. + + Written by Philip Hazel + Copyright (c) 1997-2012 University of Cambridge + +----------------------------------------------------------------------------- +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * Neither the name of the University of Cambridge nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. +----------------------------------------------------------------------------- +*/ + + +/* This module contains internal functions for testing newlines when more than +one kind of newline is to be recognized. When a newline is found, its length is +returned. In principle, we could implement several newline "types", each +referring to a different set of newline characters. At present, PCRE supports +only NLTYPE_FIXED, which gets handled without these functions, NLTYPE_ANYCRLF, +and NLTYPE_ANY. The full list of Unicode newline characters is taken from +http://unicode.org/unicode/reports/tr18/. */ + + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "pcre_internal.h" + + + +/************************************************* +* Check for newline at given position * +*************************************************/ + +/* It is guaranteed that the initial value of ptr is less than the end of the +string that is being processed. + +Arguments: + ptr pointer to possible newline + type the newline type + endptr pointer to the end of the string + lenptr where to return the length + utf TRUE if in utf mode + +Returns: TRUE or FALSE +*/ + +BOOL +PRIV(is_newline)(PCRE_PUCHAR ptr, int type, PCRE_PUCHAR endptr, int *lenptr, + BOOL utf) +{ +pcre_uint32 c; +(void)utf; +#ifdef SUPPORT_UTF +if (utf) + { + GETCHAR(c, ptr); + } +else +#endif /* SUPPORT_UTF */ + c = *ptr; + +/* Note that this function is called only for ANY or ANYCRLF. */ + +if (type == NLTYPE_ANYCRLF) switch(c) + { + case CHAR_LF: *lenptr = 1; return TRUE; + case CHAR_CR: *lenptr = (ptr < endptr - 1 && ptr[1] == CHAR_LF)? 2 : 1; + return TRUE; + default: return FALSE; + } + +/* NLTYPE_ANY */ + +else switch(c) + { +#ifdef EBCDIC + case CHAR_NEL: +#endif + case CHAR_LF: + case CHAR_VT: + case CHAR_FF: *lenptr = 1; return TRUE; + + case CHAR_CR: + *lenptr = (ptr < endptr - 1 && ptr[1] == CHAR_LF)? 2 : 1; + return TRUE; + +#ifndef EBCDIC +#ifdef COMPILE_PCRE8 + case CHAR_NEL: *lenptr = utf? 2 : 1; return TRUE; + case 0x2028: /* LS */ + case 0x2029: *lenptr = 3; return TRUE; /* PS */ +#else /* COMPILE_PCRE16 || COMPILE_PCRE32 */ + case CHAR_NEL: + case 0x2028: /* LS */ + case 0x2029: *lenptr = 1; return TRUE; /* PS */ +#endif /* COMPILE_PCRE8 */ +#endif /* Not EBCDIC */ + + default: return FALSE; + } +} + + + +/************************************************* +* Check for newline at previous position * +*************************************************/ + +/* It is guaranteed that the initial value of ptr is greater than the start of +the string that is being processed. + +Arguments: + ptr pointer to possible newline + type the newline type + startptr pointer to the start of the string + lenptr where to return the length + utf TRUE if in utf mode + +Returns: TRUE or FALSE +*/ + +BOOL +PRIV(was_newline)(PCRE_PUCHAR ptr, int type, PCRE_PUCHAR startptr, int *lenptr, + BOOL utf) +{ +pcre_uint32 c; +(void)utf; +ptr--; +#ifdef SUPPORT_UTF +if (utf) + { + BACKCHAR(ptr); + GETCHAR(c, ptr); + } +else +#endif /* SUPPORT_UTF */ + c = *ptr; + +/* Note that this function is called only for ANY or ANYCRLF. */ + +if (type == NLTYPE_ANYCRLF) switch(c) + { + case CHAR_LF: + *lenptr = (ptr > startptr && ptr[-1] == CHAR_CR)? 2 : 1; + return TRUE; + + case CHAR_CR: *lenptr = 1; return TRUE; + default: return FALSE; + } + +/* NLTYPE_ANY */ + +else switch(c) + { + case CHAR_LF: + *lenptr = (ptr > startptr && ptr[-1] == CHAR_CR)? 2 : 1; + return TRUE; + +#ifdef EBCDIC + case CHAR_NEL: +#endif + case CHAR_VT: + case CHAR_FF: + case CHAR_CR: *lenptr = 1; return TRUE; + +#ifndef EBCDIC +#ifdef COMPILE_PCRE8 + case CHAR_NEL: *lenptr = utf? 2 : 1; return TRUE; + case 0x2028: /* LS */ + case 0x2029: *lenptr = 3; return TRUE; /* PS */ +#else /* COMPILE_PCRE16 || COMPILE_PCRE32 */ + case CHAR_NEL: + case 0x2028: /* LS */ + case 0x2029: *lenptr = 1; return TRUE; /* PS */ +#endif /* COMPILE_PCRE8 */ +#endif /* NotEBCDIC */ + + default: return FALSE; + } +} + +/* End of pcre_newline.c */ diff --git a/src/private/pcre_src/pcre_ord2utf8.c b/src/private/pcre_src/pcre_ord2utf8.c new file mode 100644 index 000000000..95f1beb96 --- /dev/null +++ b/src/private/pcre_src/pcre_ord2utf8.c @@ -0,0 +1,94 @@ +/************************************************* +* Perl-Compatible Regular Expressions * +*************************************************/ + +/* PCRE is a library of functions to support regular expressions whose syntax +and semantics are as close as possible to those of the Perl 5 language. + + Written by Philip Hazel + Copyright (c) 1997-2012 University of Cambridge + +----------------------------------------------------------------------------- +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * Neither the name of the University of Cambridge nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. +----------------------------------------------------------------------------- +*/ + + +/* This file contains a private PCRE function that converts an ordinal +character value into a UTF8 string. */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#define COMPILE_PCRE8 + +#include "pcre_internal.h" + +/************************************************* +* Convert character value to UTF-8 * +*************************************************/ + +/* This function takes an integer value in the range 0 - 0x10ffff +and encodes it as a UTF-8 character in 1 to 4 pcre_uchars. + +Arguments: + cvalue the character value + buffer pointer to buffer for result - at least 6 pcre_uchars long + +Returns: number of characters placed in the buffer +*/ + +unsigned +int +PRIV(ord2utf)(pcre_uint32 cvalue, pcre_uchar *buffer) +{ +#ifdef SUPPORT_UTF + +register int i, j; + +for (i = 0; i < PRIV(utf8_table1_size); i++) + if ((int)cvalue <= PRIV(utf8_table1)[i]) break; +buffer += i; +for (j = i; j > 0; j--) + { + *buffer-- = 0x80 | (cvalue & 0x3f); + cvalue >>= 6; + } +*buffer = PRIV(utf8_table2)[i] | cvalue; +return i + 1; + +#else + +(void)(cvalue); /* Keep compiler happy; this function won't ever be */ +(void)(buffer); /* called when SUPPORT_UTF is not defined. */ +return 0; + +#endif +} + +/* End of pcre_ord2utf8.c */ diff --git a/src/private/pcre_src/pcre_refcount.c b/src/private/pcre_src/pcre_refcount.c new file mode 100644 index 000000000..79efa90f2 --- /dev/null +++ b/src/private/pcre_src/pcre_refcount.c @@ -0,0 +1,92 @@ +/************************************************* +* Perl-Compatible Regular Expressions * +*************************************************/ + +/* PCRE is a library of functions to support regular expressions whose syntax +and semantics are as close as possible to those of the Perl 5 language. + + Written by Philip Hazel + Copyright (c) 1997-2012 University of Cambridge + +----------------------------------------------------------------------------- +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * Neither the name of the University of Cambridge nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. +----------------------------------------------------------------------------- +*/ + + +/* This module contains the external function pcre_refcount(), which is an +auxiliary function that can be used to maintain a reference count in a compiled +pattern data block. This might be helpful in applications where the block is +shared by different users. */ + + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "pcre_internal.h" + + +/************************************************* +* Maintain reference count * +*************************************************/ + +/* The reference count is a 16-bit field, initialized to zero. It is not +possible to transfer a non-zero count from one host to a different host that +has a different byte order - though I can't see why anyone in their right mind +would ever want to do that! + +Arguments: + argument_re points to compiled code + adjust value to add to the count + +Returns: the (possibly updated) count value (a non-negative number), or + a negative error number +*/ + +#if defined COMPILE_PCRE8 +PCRE_EXP_DEFN int PCRE_CALL_CONVENTION +pcre_refcount(pcre *argument_re, int adjust) +#elif defined COMPILE_PCRE16 +PCRE_EXP_DEFN int PCRE_CALL_CONVENTION +pcre16_refcount(pcre16 *argument_re, int adjust) +#elif defined COMPILE_PCRE32 +PCRE_EXP_DEFN int PCRE_CALL_CONVENTION +pcre32_refcount(pcre32 *argument_re, int adjust) +#endif +{ +REAL_PCRE *re = (REAL_PCRE *)argument_re; +if (re == NULL) return PCRE_ERROR_NULL; +if (re->magic_number != MAGIC_NUMBER) return PCRE_ERROR_BADMAGIC; +if ((re->flags & PCRE_MODE) == 0) return PCRE_ERROR_BADMODE; +re->ref_count = (-adjust > re->ref_count)? 0 : + (adjust + re->ref_count > 65535)? 65535 : + re->ref_count + adjust; +return re->ref_count; +} + +/* End of pcre_refcount.c */ diff --git a/src/private/pcre_src/pcre_string_utils.c b/src/private/pcre_src/pcre_string_utils.c new file mode 100644 index 000000000..25eacc850 --- /dev/null +++ b/src/private/pcre_src/pcre_string_utils.c @@ -0,0 +1,211 @@ +/************************************************* +* Perl-Compatible Regular Expressions * +*************************************************/ + +/* PCRE is a library of functions to support regular expressions whose syntax +and semantics are as close as possible to those of the Perl 5 language. + + Written by Philip Hazel + Copyright (c) 1997-2014 University of Cambridge + +----------------------------------------------------------------------------- +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * Neither the name of the University of Cambridge nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. +----------------------------------------------------------------------------- +*/ + + +/* This module contains internal functions for comparing and finding the length +of strings for different data item sizes. */ + + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "pcre_internal.h" + +#ifndef COMPILE_PCRE8 + +/************************************************* +* Compare string utilities * +*************************************************/ + +/* The following two functions compares two strings. Basically a strcmp +for non 8 bit characters. + +Arguments: + str1 first string + str2 second string + +Returns: 0 if both string are equal (like strcmp), 1 otherwise +*/ + +int +PRIV(strcmp_uc_uc)(const pcre_uchar *str1, const pcre_uchar *str2) +{ +pcre_uchar c1; +pcre_uchar c2; + +while (*str1 != '\0' || *str2 != '\0') + { + c1 = *str1++; + c2 = *str2++; + if (c1 != c2) + return ((c1 > c2) << 1) - 1; + } +/* Both length and characters must be equal. */ +return 0; +} + +#ifdef COMPILE_PCRE32 + +int +PRIV(strcmp_uc_uc_utf)(const pcre_uchar *str1, const pcre_uchar *str2) +{ +pcre_uchar c1; +pcre_uchar c2; + +while (*str1 != '\0' || *str2 != '\0') + { + c1 = UCHAR21INC(str1); + c2 = UCHAR21INC(str2); + if (c1 != c2) + return ((c1 > c2) << 1) - 1; + } +/* Both length and characters must be equal. */ +return 0; +} + +#endif /* COMPILE_PCRE32 */ + +int +PRIV(strcmp_uc_c8)(const pcre_uchar *str1, const char *str2) +{ +const pcre_uint8 *ustr2 = (pcre_uint8 *)str2; +pcre_uchar c1; +pcre_uchar c2; + +while (*str1 != '\0' || *ustr2 != '\0') + { + c1 = *str1++; + c2 = (pcre_uchar)*ustr2++; + if (c1 != c2) + return ((c1 > c2) << 1) - 1; + } +/* Both length and characters must be equal. */ +return 0; +} + +#ifdef COMPILE_PCRE32 + +int +PRIV(strcmp_uc_c8_utf)(const pcre_uchar *str1, const char *str2) +{ +const pcre_uint8 *ustr2 = (pcre_uint8 *)str2; +pcre_uchar c1; +pcre_uchar c2; + +while (*str1 != '\0' || *ustr2 != '\0') + { + c1 = UCHAR21INC(str1); + c2 = (pcre_uchar)*ustr2++; + if (c1 != c2) + return ((c1 > c2) << 1) - 1; + } +/* Both length and characters must be equal. */ +return 0; +} + +#endif /* COMPILE_PCRE32 */ + +/* The following two functions compares two, fixed length +strings. Basically an strncmp for non 8 bit characters. + +Arguments: + str1 first string + str2 second string + num size of the string + +Returns: 0 if both string are equal (like strcmp), 1 otherwise +*/ + +int +PRIV(strncmp_uc_uc)(const pcre_uchar *str1, const pcre_uchar *str2, unsigned int num) +{ +pcre_uchar c1; +pcre_uchar c2; + +while (num-- > 0) + { + c1 = *str1++; + c2 = *str2++; + if (c1 != c2) + return ((c1 > c2) << 1) - 1; + } +/* Both length and characters must be equal. */ +return 0; +} + +int +PRIV(strncmp_uc_c8)(const pcre_uchar *str1, const char *str2, unsigned int num) +{ +const pcre_uint8 *ustr2 = (pcre_uint8 *)str2; +pcre_uchar c1; +pcre_uchar c2; + +while (num-- > 0) + { + c1 = *str1++; + c2 = (pcre_uchar)*ustr2++; + if (c1 != c2) + return ((c1 > c2) << 1) - 1; + } +/* Both length and characters must be equal. */ +return 0; +} + +/* The following function returns with the length of +a zero terminated string. Basically an strlen for non 8 bit characters. + +Arguments: + str string + +Returns: length of the string +*/ + +unsigned int +PRIV(strlen_uc)(const pcre_uchar *str) +{ +unsigned int len = 0; +while (*str++ != 0) + len++; +return len; +} + +#endif /* !COMPILE_PCRE8 */ + +/* End of pcre_string_utils.c */ diff --git a/src/private/pcre_src/pcre_study.c b/src/private/pcre_src/pcre_study.c new file mode 100644 index 000000000..f19d9fbb9 --- /dev/null +++ b/src/private/pcre_src/pcre_study.c @@ -0,0 +1,1643 @@ +/************************************************* +* Perl-Compatible Regular Expressions * +*************************************************/ + +/* PCRE is a library of functions to support regular expressions whose syntax +and semantics are as close as possible to those of the Perl 5 language. + + Written by Philip Hazel + Copyright (c) 1997-2012 University of Cambridge + +----------------------------------------------------------------------------- +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * Neither the name of the University of Cambridge nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. +----------------------------------------------------------------------------- +*/ + + +/* This module contains the external function pcre_study(), along with local +supporting functions. */ + + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "pcre_internal.h" + +#define SET_BIT(c) start_bits[c/8] |= (1 << (c&7)) + +/* Returns from set_start_bits() */ + +enum { SSB_FAIL, SSB_DONE, SSB_CONTINUE, SSB_UNKNOWN }; + + + +/************************************************* +* Find the minimum subject length for a group * +*************************************************/ + +/* Scan a parenthesized group and compute the minimum length of subject that +is needed to match it. This is a lower bound; it does not mean there is a +string of that length that matches. In UTF8 mode, the result is in characters +rather than bytes. + +Arguments: + re compiled pattern block + code pointer to start of group (the bracket) + startcode pointer to start of the whole pattern's code + options the compiling options + int RECURSE depth + +Returns: the minimum length + -1 if \C in UTF-8 mode or (*ACCEPT) was encountered + -2 internal error (missing capturing bracket) + -3 internal error (opcode not listed) +*/ + +static int +find_minlength(const REAL_PCRE *re, const pcre_uchar *code, + const pcre_uchar *startcode, int options, int recurse_depth) +{ +int length = -1; +/* PCRE_UTF16 has the same value as PCRE_UTF8. */ +BOOL utf = (options & PCRE_UTF8) != 0; +BOOL had_recurse = FALSE; +register int branchlength = 0; +register pcre_uchar *cc = (pcre_uchar *)code + 1 + LINK_SIZE; + +if (*code == OP_CBRA || *code == OP_SCBRA || + *code == OP_CBRAPOS || *code == OP_SCBRAPOS) cc += IMM2_SIZE; + +/* Scan along the opcodes for this branch. If we get to the end of the +branch, check the length against that of the other branches. */ + +for (;;) + { + int d, min; + pcre_uchar *cs, *ce; + register pcre_uchar op = *cc; + + switch (op) + { + case OP_COND: + case OP_SCOND: + + /* If there is only one branch in a condition, the implied branch has zero + length, so we don't add anything. This covers the DEFINE "condition" + automatically. */ + + cs = cc + GET(cc, 1); + if (*cs != OP_ALT) + { + cc = cs + 1 + LINK_SIZE; + break; + } + + /* Otherwise we can fall through and treat it the same as any other + subpattern. */ + + case OP_CBRA: + case OP_SCBRA: + case OP_BRA: + case OP_SBRA: + case OP_CBRAPOS: + case OP_SCBRAPOS: + case OP_BRAPOS: + case OP_SBRAPOS: + case OP_ONCE: + case OP_ONCE_NC: + d = find_minlength(re, cc, startcode, options, recurse_depth); + if (d < 0) return d; + branchlength += d; + do cc += GET(cc, 1); while (*cc == OP_ALT); + cc += 1 + LINK_SIZE; + break; + + /* ACCEPT makes things far too complicated; we have to give up. */ + + case OP_ACCEPT: + case OP_ASSERT_ACCEPT: + return -1; + + /* Reached end of a branch; if it's a ket it is the end of a nested + call. If it's ALT it is an alternation in a nested call. If it is END it's + the end of the outer call. All can be handled by the same code. If an + ACCEPT was previously encountered, use the length that was in force at that + time, and pass back the shortest ACCEPT length. */ + + case OP_ALT: + case OP_KET: + case OP_KETRMAX: + case OP_KETRMIN: + case OP_KETRPOS: + case OP_END: + if (length < 0 || (!had_recurse && branchlength < length)) + length = branchlength; + if (op != OP_ALT) return length; + cc += 1 + LINK_SIZE; + branchlength = 0; + had_recurse = FALSE; + break; + + /* Skip over assertive subpatterns */ + + case OP_ASSERT: + case OP_ASSERT_NOT: + case OP_ASSERTBACK: + case OP_ASSERTBACK_NOT: + do cc += GET(cc, 1); while (*cc == OP_ALT); + /* Fall through */ + + /* Skip over things that don't match chars */ + + case OP_REVERSE: + case OP_CREF: + case OP_DNCREF: + case OP_RREF: + case OP_DNRREF: + case OP_DEF: + case OP_CALLOUT: + case OP_SOD: + case OP_SOM: + case OP_EOD: + case OP_EODN: + case OP_CIRC: + case OP_CIRCM: + case OP_DOLL: + case OP_DOLLM: + case OP_NOT_WORD_BOUNDARY: + case OP_WORD_BOUNDARY: + cc += PRIV(OP_lengths)[*cc]; + break; + + /* Skip over a subpattern that has a {0} or {0,x} quantifier */ + + case OP_BRAZERO: + case OP_BRAMINZERO: + case OP_BRAPOSZERO: + case OP_SKIPZERO: + cc += PRIV(OP_lengths)[*cc]; + do cc += GET(cc, 1); while (*cc == OP_ALT); + cc += 1 + LINK_SIZE; + break; + + /* Handle literal characters and + repetitions */ + + case OP_CHAR: + case OP_CHARI: + case OP_NOT: + case OP_NOTI: + case OP_PLUS: + case OP_PLUSI: + case OP_MINPLUS: + case OP_MINPLUSI: + case OP_POSPLUS: + case OP_POSPLUSI: + case OP_NOTPLUS: + case OP_NOTPLUSI: + case OP_NOTMINPLUS: + case OP_NOTMINPLUSI: + case OP_NOTPOSPLUS: + case OP_NOTPOSPLUSI: + branchlength++; + cc += 2; +#ifdef SUPPORT_UTF + if (utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]); +#endif + break; + + case OP_TYPEPLUS: + case OP_TYPEMINPLUS: + case OP_TYPEPOSPLUS: + branchlength++; + cc += (cc[1] == OP_PROP || cc[1] == OP_NOTPROP)? 4 : 2; + break; + + /* Handle exact repetitions. The count is already in characters, but we + need to skip over a multibyte character in UTF8 mode. */ + + case OP_EXACT: + case OP_EXACTI: + case OP_NOTEXACT: + case OP_NOTEXACTI: + branchlength += GET2(cc,1); + cc += 2 + IMM2_SIZE; +#ifdef SUPPORT_UTF + if (utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]); +#endif + break; + + case OP_TYPEEXACT: + branchlength += GET2(cc,1); + cc += 2 + IMM2_SIZE + ((cc[1 + IMM2_SIZE] == OP_PROP + || cc[1 + IMM2_SIZE] == OP_NOTPROP)? 2 : 0); + break; + + /* Handle single-char non-literal matchers */ + + case OP_PROP: + case OP_NOTPROP: + cc += 2; + /* Fall through */ + + case OP_NOT_DIGIT: + case OP_DIGIT: + case OP_NOT_WHITESPACE: + case OP_WHITESPACE: + case OP_NOT_WORDCHAR: + case OP_WORDCHAR: + case OP_ANY: + case OP_ALLANY: + case OP_EXTUNI: + case OP_HSPACE: + case OP_NOT_HSPACE: + case OP_VSPACE: + case OP_NOT_VSPACE: + branchlength++; + cc++; + break; + + /* "Any newline" might match two characters, but it also might match just + one. */ + + case OP_ANYNL: + branchlength += 1; + cc++; + break; + + /* The single-byte matcher means we can't proceed in UTF-8 mode. (In + non-UTF-8 mode \C will actually be turned into OP_ALLANY, so won't ever + appear, but leave the code, just in case.) */ + + case OP_ANYBYTE: +#ifdef SUPPORT_UTF + if (utf) return -1; +#endif + branchlength++; + cc++; + break; + + /* For repeated character types, we have to test for \p and \P, which have + an extra two bytes of parameters. */ + + case OP_TYPESTAR: + case OP_TYPEMINSTAR: + case OP_TYPEQUERY: + case OP_TYPEMINQUERY: + case OP_TYPEPOSSTAR: + case OP_TYPEPOSQUERY: + if (cc[1] == OP_PROP || cc[1] == OP_NOTPROP) cc += 2; + cc += PRIV(OP_lengths)[op]; + break; + + case OP_TYPEUPTO: + case OP_TYPEMINUPTO: + case OP_TYPEPOSUPTO: + if (cc[1 + IMM2_SIZE] == OP_PROP + || cc[1 + IMM2_SIZE] == OP_NOTPROP) cc += 2; + cc += PRIV(OP_lengths)[op]; + break; + + /* Check a class for variable quantification */ + + case OP_CLASS: + case OP_NCLASS: +#if defined SUPPORT_UTF || defined COMPILE_PCRE16 || defined COMPILE_PCRE32 + case OP_XCLASS: + /* The original code caused an unsigned overflow in 64 bit systems, + so now we use a conditional statement. */ + if (op == OP_XCLASS) + cc += GET(cc, 1); + else + cc += PRIV(OP_lengths)[OP_CLASS]; +#else + cc += PRIV(OP_lengths)[OP_CLASS]; +#endif + + switch (*cc) + { + case OP_CRPLUS: + case OP_CRMINPLUS: + case OP_CRPOSPLUS: + branchlength++; + /* Fall through */ + + case OP_CRSTAR: + case OP_CRMINSTAR: + case OP_CRQUERY: + case OP_CRMINQUERY: + case OP_CRPOSSTAR: + case OP_CRPOSQUERY: + cc++; + break; + + case OP_CRRANGE: + case OP_CRMINRANGE: + case OP_CRPOSRANGE: + branchlength += GET2(cc,1); + cc += 1 + 2 * IMM2_SIZE; + break; + + default: + branchlength++; + break; + } + break; + + /* Backreferences and subroutine calls are treated in the same way: we find + the minimum length for the subpattern. A recursion, however, causes an + a flag to be set that causes the length of this branch to be ignored. The + logic is that a recursion can only make sense if there is another + alternation that stops the recursing. That will provide the minimum length + (when no recursion happens). A backreference within the group that it is + referencing behaves in the same way. + + If PCRE_JAVASCRIPT_COMPAT is set, a backreference to an unset bracket + matches an empty string (by default it causes a matching failure), so in + that case we must set the minimum length to zero. */ + + case OP_DNREF: /* Duplicate named pattern back reference */ + case OP_DNREFI: + if ((options & PCRE_JAVASCRIPT_COMPAT) == 0) + { + int count = GET2(cc, 1+IMM2_SIZE); + pcre_uchar *slot = (pcre_uchar *)re + + re->name_table_offset + GET2(cc, 1) * re->name_entry_size; + d = INT_MAX; + while (count-- > 0) + { + ce = cs = (pcre_uchar *)PRIV(find_bracket)(startcode, utf, GET2(slot, 0)); + if (cs == NULL) return -2; + do ce += GET(ce, 1); while (*ce == OP_ALT); + if (cc > cs && cc < ce) + { + d = 0; + had_recurse = TRUE; + break; + } + else + { + int dd = find_minlength(re, cs, startcode, options, recurse_depth); + if (dd < d) d = dd; + } + slot += re->name_entry_size; + } + } + else d = 0; + cc += 1 + 2*IMM2_SIZE; + goto REPEAT_BACK_REFERENCE; + + case OP_REF: /* Single back reference */ + case OP_REFI: + if ((options & PCRE_JAVASCRIPT_COMPAT) == 0) + { + ce = cs = (pcre_uchar *)PRIV(find_bracket)(startcode, utf, GET2(cc, 1)); + if (cs == NULL) return -2; + do ce += GET(ce, 1); while (*ce == OP_ALT); + if (cc > cs && cc < ce) + { + d = 0; + had_recurse = TRUE; + } + else + { + d = find_minlength(re, cs, startcode, options, recurse_depth); + } + } + else d = 0; + cc += 1 + IMM2_SIZE; + + /* Handle repeated back references */ + + REPEAT_BACK_REFERENCE: + switch (*cc) + { + case OP_CRSTAR: + case OP_CRMINSTAR: + case OP_CRQUERY: + case OP_CRMINQUERY: + case OP_CRPOSSTAR: + case OP_CRPOSQUERY: + min = 0; + cc++; + break; + + case OP_CRPLUS: + case OP_CRMINPLUS: + case OP_CRPOSPLUS: + min = 1; + cc++; + break; + + case OP_CRRANGE: + case OP_CRMINRANGE: + case OP_CRPOSRANGE: + min = GET2(cc, 1); + cc += 1 + 2 * IMM2_SIZE; + break; + + default: + min = 1; + break; + } + + branchlength += min * d; + break; + + /* We can easily detect direct recursion, but not mutual recursion. This is + caught by a recursion depth count. */ + + case OP_RECURSE: + cs = ce = (pcre_uchar *)startcode + GET(cc, 1); + do ce += GET(ce, 1); while (*ce == OP_ALT); + if ((cc > cs && cc < ce) || recurse_depth > 10) + had_recurse = TRUE; + else + { + branchlength += find_minlength(re, cs, startcode, options, + recurse_depth + 1); + } + cc += 1 + LINK_SIZE; + break; + + /* Anything else does not or need not match a character. We can get the + item's length from the table, but for those that can match zero occurrences + of a character, we must take special action for UTF-8 characters. As it + happens, the "NOT" versions of these opcodes are used at present only for + ASCII characters, so they could be omitted from this list. However, in + future that may change, so we include them here so as not to leave a + gotcha for a future maintainer. */ + + case OP_UPTO: + case OP_UPTOI: + case OP_NOTUPTO: + case OP_NOTUPTOI: + case OP_MINUPTO: + case OP_MINUPTOI: + case OP_NOTMINUPTO: + case OP_NOTMINUPTOI: + case OP_POSUPTO: + case OP_POSUPTOI: + case OP_NOTPOSUPTO: + case OP_NOTPOSUPTOI: + + case OP_STAR: + case OP_STARI: + case OP_NOTSTAR: + case OP_NOTSTARI: + case OP_MINSTAR: + case OP_MINSTARI: + case OP_NOTMINSTAR: + case OP_NOTMINSTARI: + case OP_POSSTAR: + case OP_POSSTARI: + case OP_NOTPOSSTAR: + case OP_NOTPOSSTARI: + + case OP_QUERY: + case OP_QUERYI: + case OP_NOTQUERY: + case OP_NOTQUERYI: + case OP_MINQUERY: + case OP_MINQUERYI: + case OP_NOTMINQUERY: + case OP_NOTMINQUERYI: + case OP_POSQUERY: + case OP_POSQUERYI: + case OP_NOTPOSQUERY: + case OP_NOTPOSQUERYI: + + cc += PRIV(OP_lengths)[op]; +#ifdef SUPPORT_UTF + if (utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]); +#endif + break; + + /* Skip these, but we need to add in the name length. */ + + case OP_MARK: + case OP_PRUNE_ARG: + case OP_SKIP_ARG: + case OP_THEN_ARG: + cc += PRIV(OP_lengths)[op] + cc[1]; + break; + + /* The remaining opcodes are just skipped over. */ + + case OP_CLOSE: + case OP_COMMIT: + case OP_FAIL: + case OP_PRUNE: + case OP_SET_SOM: + case OP_SKIP: + case OP_THEN: + cc += PRIV(OP_lengths)[op]; + break; + + /* This should not occur: we list all opcodes explicitly so that when + new ones get added they are properly considered. */ + + default: + return -3; + } + } +/* Control never gets here */ +} + + + +/************************************************* +* Set a bit and maybe its alternate case * +*************************************************/ + +/* Given a character, set its first byte's bit in the table, and also the +corresponding bit for the other version of a letter if we are caseless. In +UTF-8 mode, for characters greater than 127, we can only do the caseless thing +when Unicode property support is available. + +Arguments: + start_bits points to the bit map + p points to the character + caseless the caseless flag + cd the block with char table pointers + utf TRUE for UTF-8 / UTF-16 / UTF-32 mode + +Returns: pointer after the character +*/ + +static const pcre_uchar * +set_table_bit(pcre_uint8 *start_bits, const pcre_uchar *p, BOOL caseless, + compile_data *cd, BOOL utf) +{ +pcre_uint32 c = *p; + +#ifdef COMPILE_PCRE8 +SET_BIT(c); + +#ifdef SUPPORT_UTF +if (utf && c > 127) + { + GETCHARINC(c, p); +#ifdef SUPPORT_UCP + if (caseless) + { + pcre_uchar buff[6]; + c = UCD_OTHERCASE(c); + (void)PRIV(ord2utf)(c, buff); + SET_BIT(buff[0]); + } +#endif /* Not SUPPORT_UCP */ + return p; + } +#else /* Not SUPPORT_UTF */ +(void)(utf); /* Stops warning for unused parameter */ +#endif /* SUPPORT_UTF */ + +/* Not UTF-8 mode, or character is less than 127. */ + +if (caseless && (cd->ctypes[c] & ctype_letter) != 0) SET_BIT(cd->fcc[c]); +return p + 1; +#endif /* COMPILE_PCRE8 */ + +#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 +if (c > 0xff) + { + c = 0xff; + caseless = FALSE; + } +SET_BIT(c); + +#ifdef SUPPORT_UTF +if (utf && c > 127) + { + GETCHARINC(c, p); +#ifdef SUPPORT_UCP + if (caseless) + { + c = UCD_OTHERCASE(c); + if (c > 0xff) + c = 0xff; + SET_BIT(c); + } +#endif /* SUPPORT_UCP */ + return p; + } +#else /* Not SUPPORT_UTF */ +(void)(utf); /* Stops warning for unused parameter */ +#endif /* SUPPORT_UTF */ + +if (caseless && (cd->ctypes[c] & ctype_letter) != 0) SET_BIT(cd->fcc[c]); +return p + 1; +#endif +} + + + +/************************************************* +* Set bits for a positive character type * +*************************************************/ + +/* This function sets starting bits for a character type. In UTF-8 mode, we can +only do a direct setting for bytes less than 128, as otherwise there can be +confusion with bytes in the middle of UTF-8 characters. In a "traditional" +environment, the tables will only recognize ASCII characters anyway, but in at +least one Windows environment, some higher bytes bits were set in the tables. +So we deal with that case by considering the UTF-8 encoding. + +Arguments: + start_bits the starting bitmap + cbit type the type of character wanted + table_limit 32 for non-UTF-8; 16 for UTF-8 + cd the block with char table pointers + +Returns: nothing +*/ + +static void +set_type_bits(pcre_uint8 *start_bits, int cbit_type, unsigned int table_limit, + compile_data *cd) +{ +register pcre_uint32 c; +for (c = 0; c < table_limit; c++) start_bits[c] |= cd->cbits[c+cbit_type]; +#if defined SUPPORT_UTF && defined COMPILE_PCRE8 +if (table_limit == 32) return; +for (c = 128; c < 256; c++) + { + if ((cd->cbits[c/8] & (1 << (c&7))) != 0) + { + pcre_uchar buff[6]; + (void)PRIV(ord2utf)(c, buff); + SET_BIT(buff[0]); + } + } +#endif +} + + +/************************************************* +* Set bits for a negative character type * +*************************************************/ + +/* This function sets starting bits for a negative character type such as \D. +In UTF-8 mode, we can only do a direct setting for bytes less than 128, as +otherwise there can be confusion with bytes in the middle of UTF-8 characters. +Unlike in the positive case, where we can set appropriate starting bits for +specific high-valued UTF-8 characters, in this case we have to set the bits for +all high-valued characters. The lowest is 0xc2, but we overkill by starting at +0xc0 (192) for simplicity. + +Arguments: + start_bits the starting bitmap + cbit type the type of character wanted + table_limit 32 for non-UTF-8; 16 for UTF-8 + cd the block with char table pointers + +Returns: nothing +*/ + +static void +set_nottype_bits(pcre_uint8 *start_bits, int cbit_type, unsigned int table_limit, + compile_data *cd) +{ +register pcre_uint32 c; +for (c = 0; c < table_limit; c++) start_bits[c] |= ~cd->cbits[c+cbit_type]; +#if defined SUPPORT_UTF && defined COMPILE_PCRE8 +if (table_limit != 32) for (c = 24; c < 32; c++) start_bits[c] = 0xff; +#endif +} + + + +/************************************************* +* Create bitmap of starting bytes * +*************************************************/ + +/* This function scans a compiled unanchored expression recursively and +attempts to build a bitmap of the set of possible starting bytes. As time goes +by, we may be able to get more clever at doing this. The SSB_CONTINUE return is +useful for parenthesized groups in patterns such as (a*)b where the group +provides some optional starting bytes but scanning must continue at the outer +level to find at least one mandatory byte. At the outermost level, this +function fails unless the result is SSB_DONE. + +Arguments: + code points to an expression + start_bits points to a 32-byte table, initialized to 0 + utf TRUE if in UTF-8 / UTF-16 / UTF-32 mode + cd the block with char table pointers + +Returns: SSB_FAIL => Failed to find any starting bytes + SSB_DONE => Found mandatory starting bytes + SSB_CONTINUE => Found optional starting bytes + SSB_UNKNOWN => Hit an unrecognized opcode +*/ + +static int +set_start_bits(const pcre_uchar *code, pcre_uint8 *start_bits, BOOL utf, + compile_data *cd) +{ +register pcre_uint32 c; +int yield = SSB_DONE; +#if defined SUPPORT_UTF && defined COMPILE_PCRE8 +int table_limit = utf? 16:32; +#else +int table_limit = 32; +#endif + +#if 0 +/* ========================================================================= */ +/* The following comment and code was inserted in January 1999. In May 2006, +when it was observed to cause compiler warnings about unused values, I took it +out again. If anybody is still using OS/2, they will have to put it back +manually. */ + +/* This next statement and the later reference to dummy are here in order to +trick the optimizer of the IBM C compiler for OS/2 into generating correct +code. Apparently IBM isn't going to fix the problem, and we would rather not +disable optimization (in this module it actually makes a big difference, and +the pcre module can use all the optimization it can get). */ + +volatile int dummy; +/* ========================================================================= */ +#endif + +do + { + BOOL try_next = TRUE; + const pcre_uchar *tcode = code + 1 + LINK_SIZE; + + if (*code == OP_CBRA || *code == OP_SCBRA || + *code == OP_CBRAPOS || *code == OP_SCBRAPOS) tcode += IMM2_SIZE; + + while (try_next) /* Loop for items in this branch */ + { + int rc; + + switch(*tcode) + { + /* If we reach something we don't understand, it means a new opcode has + been created that hasn't been added to this code. Hopefully this problem + will be discovered during testing. */ + + default: + return SSB_UNKNOWN; + + /* Fail for a valid opcode that implies no starting bits. */ + + case OP_ACCEPT: + case OP_ASSERT_ACCEPT: + case OP_ALLANY: + case OP_ANY: + case OP_ANYBYTE: + case OP_CIRC: + case OP_CIRCM: + case OP_CLOSE: + case OP_COMMIT: + case OP_COND: + case OP_CREF: + case OP_DEF: + case OP_DNCREF: + case OP_DNREF: + case OP_DNREFI: + case OP_DNRREF: + case OP_DOLL: + case OP_DOLLM: + case OP_END: + case OP_EOD: + case OP_EODN: + case OP_EXTUNI: + case OP_FAIL: + case OP_MARK: + case OP_NOT: + case OP_NOTEXACT: + case OP_NOTEXACTI: + case OP_NOTI: + case OP_NOTMINPLUS: + case OP_NOTMINPLUSI: + case OP_NOTMINQUERY: + case OP_NOTMINQUERYI: + case OP_NOTMINSTAR: + case OP_NOTMINSTARI: + case OP_NOTMINUPTO: + case OP_NOTMINUPTOI: + case OP_NOTPLUS: + case OP_NOTPLUSI: + case OP_NOTPOSPLUS: + case OP_NOTPOSPLUSI: + case OP_NOTPOSQUERY: + case OP_NOTPOSQUERYI: + case OP_NOTPOSSTAR: + case OP_NOTPOSSTARI: + case OP_NOTPOSUPTO: + case OP_NOTPOSUPTOI: + case OP_NOTPROP: + case OP_NOTQUERY: + case OP_NOTQUERYI: + case OP_NOTSTAR: + case OP_NOTSTARI: + case OP_NOTUPTO: + case OP_NOTUPTOI: + case OP_NOT_HSPACE: + case OP_NOT_VSPACE: + case OP_PRUNE: + case OP_PRUNE_ARG: + case OP_RECURSE: + case OP_REF: + case OP_REFI: + case OP_REVERSE: + case OP_RREF: + case OP_SCOND: + case OP_SET_SOM: + case OP_SKIP: + case OP_SKIP_ARG: + case OP_SOD: + case OP_SOM: + case OP_THEN: + case OP_THEN_ARG: + return SSB_FAIL; + + /* A "real" property test implies no starting bits, but the fake property + PT_CLIST identifies a list of characters. These lists are short, as they + are used for characters with more than one "other case", so there is no + point in recognizing them for OP_NOTPROP. */ + + case OP_PROP: + if (tcode[1] != PT_CLIST) return SSB_FAIL; + { + const pcre_uint32 *p = PRIV(ucd_caseless_sets) + tcode[2]; + while ((c = *p++) < NOTACHAR) + { +#if defined SUPPORT_UTF && defined COMPILE_PCRE8 + if (utf) + { + pcre_uchar buff[6]; + (void)PRIV(ord2utf)(c, buff); + c = buff[0]; + } +#endif + if (c > 0xff) SET_BIT(0xff); else SET_BIT(c); + } + } + try_next = FALSE; + break; + + /* We can ignore word boundary tests. */ + + case OP_WORD_BOUNDARY: + case OP_NOT_WORD_BOUNDARY: + tcode++; + break; + + /* If we hit a bracket or a positive lookahead assertion, recurse to set + bits from within the subpattern. If it can't find anything, we have to + give up. If it finds some mandatory character(s), we are done for this + branch. Otherwise, carry on scanning after the subpattern. */ + + case OP_BRA: + case OP_SBRA: + case OP_CBRA: + case OP_SCBRA: + case OP_BRAPOS: + case OP_SBRAPOS: + case OP_CBRAPOS: + case OP_SCBRAPOS: + case OP_ONCE: + case OP_ONCE_NC: + case OP_ASSERT: + rc = set_start_bits(tcode, start_bits, utf, cd); + if (rc == SSB_FAIL || rc == SSB_UNKNOWN) return rc; + if (rc == SSB_DONE) try_next = FALSE; else + { + do tcode += GET(tcode, 1); while (*tcode == OP_ALT); + tcode += 1 + LINK_SIZE; + } + break; + + /* If we hit ALT or KET, it means we haven't found anything mandatory in + this branch, though we might have found something optional. For ALT, we + continue with the next alternative, but we have to arrange that the final + result from subpattern is SSB_CONTINUE rather than SSB_DONE. For KET, + return SSB_CONTINUE: if this is the top level, that indicates failure, + but after a nested subpattern, it causes scanning to continue. */ + + case OP_ALT: + yield = SSB_CONTINUE; + try_next = FALSE; + break; + + case OP_KET: + case OP_KETRMAX: + case OP_KETRMIN: + case OP_KETRPOS: + return SSB_CONTINUE; + + /* Skip over callout */ + + case OP_CALLOUT: + tcode += 2 + 2*LINK_SIZE; + break; + + /* Skip over lookbehind and negative lookahead assertions */ + + case OP_ASSERT_NOT: + case OP_ASSERTBACK: + case OP_ASSERTBACK_NOT: + do tcode += GET(tcode, 1); while (*tcode == OP_ALT); + tcode += 1 + LINK_SIZE; + break; + + /* BRAZERO does the bracket, but carries on. */ + + case OP_BRAZERO: + case OP_BRAMINZERO: + case OP_BRAPOSZERO: + rc = set_start_bits(++tcode, start_bits, utf, cd); + if (rc == SSB_FAIL || rc == SSB_UNKNOWN) return rc; +/* ========================================================================= + See the comment at the head of this function concerning the next line, + which was an old fudge for the benefit of OS/2. + dummy = 1; + ========================================================================= */ + do tcode += GET(tcode,1); while (*tcode == OP_ALT); + tcode += 1 + LINK_SIZE; + break; + + /* SKIPZERO skips the bracket. */ + + case OP_SKIPZERO: + tcode++; + do tcode += GET(tcode,1); while (*tcode == OP_ALT); + tcode += 1 + LINK_SIZE; + break; + + /* Single-char * or ? sets the bit and tries the next item */ + + case OP_STAR: + case OP_MINSTAR: + case OP_POSSTAR: + case OP_QUERY: + case OP_MINQUERY: + case OP_POSQUERY: + tcode = set_table_bit(start_bits, tcode + 1, FALSE, cd, utf); + break; + + case OP_STARI: + case OP_MINSTARI: + case OP_POSSTARI: + case OP_QUERYI: + case OP_MINQUERYI: + case OP_POSQUERYI: + tcode = set_table_bit(start_bits, tcode + 1, TRUE, cd, utf); + break; + + /* Single-char upto sets the bit and tries the next */ + + case OP_UPTO: + case OP_MINUPTO: + case OP_POSUPTO: + tcode = set_table_bit(start_bits, tcode + 1 + IMM2_SIZE, FALSE, cd, utf); + break; + + case OP_UPTOI: + case OP_MINUPTOI: + case OP_POSUPTOI: + tcode = set_table_bit(start_bits, tcode + 1 + IMM2_SIZE, TRUE, cd, utf); + break; + + /* At least one single char sets the bit and stops */ + + case OP_EXACT: + tcode += IMM2_SIZE; + /* Fall through */ + case OP_CHAR: + case OP_PLUS: + case OP_MINPLUS: + case OP_POSPLUS: + (void)set_table_bit(start_bits, tcode + 1, FALSE, cd, utf); + try_next = FALSE; + break; + + case OP_EXACTI: + tcode += IMM2_SIZE; + /* Fall through */ + case OP_CHARI: + case OP_PLUSI: + case OP_MINPLUSI: + case OP_POSPLUSI: + (void)set_table_bit(start_bits, tcode + 1, TRUE, cd, utf); + try_next = FALSE; + break; + + /* Special spacing and line-terminating items. These recognize specific + lists of characters. The difference between VSPACE and ANYNL is that the + latter can match the two-character CRLF sequence, but that is not + relevant for finding the first character, so their code here is + identical. */ + + case OP_HSPACE: + SET_BIT(CHAR_HT); + SET_BIT(CHAR_SPACE); +#ifdef SUPPORT_UTF + if (utf) + { +#ifdef COMPILE_PCRE8 + SET_BIT(0xC2); /* For U+00A0 */ + SET_BIT(0xE1); /* For U+1680, U+180E */ + SET_BIT(0xE2); /* For U+2000 - U+200A, U+202F, U+205F */ + SET_BIT(0xE3); /* For U+3000 */ +#elif defined COMPILE_PCRE16 || defined COMPILE_PCRE32 + SET_BIT(0xA0); + SET_BIT(0xFF); /* For characters > 255 */ +#endif /* COMPILE_PCRE[8|16|32] */ + } + else +#endif /* SUPPORT_UTF */ + { +#ifndef EBCDIC + SET_BIT(0xA0); +#endif /* Not EBCDIC */ +#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 + SET_BIT(0xFF); /* For characters > 255 */ +#endif /* COMPILE_PCRE[16|32] */ + } + try_next = FALSE; + break; + + case OP_ANYNL: + case OP_VSPACE: + SET_BIT(CHAR_LF); + SET_BIT(CHAR_VT); + SET_BIT(CHAR_FF); + SET_BIT(CHAR_CR); +#ifdef SUPPORT_UTF + if (utf) + { +#ifdef COMPILE_PCRE8 + SET_BIT(0xC2); /* For U+0085 */ + SET_BIT(0xE2); /* For U+2028, U+2029 */ +#elif defined COMPILE_PCRE16 || defined COMPILE_PCRE32 + SET_BIT(CHAR_NEL); + SET_BIT(0xFF); /* For characters > 255 */ +#endif /* COMPILE_PCRE[8|16|32] */ + } + else +#endif /* SUPPORT_UTF */ + { + SET_BIT(CHAR_NEL); +#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 + SET_BIT(0xFF); /* For characters > 255 */ +#endif + } + try_next = FALSE; + break; + + /* Single character types set the bits and stop. Note that if PCRE_UCP + is set, we do not see these op codes because \d etc are converted to + properties. Therefore, these apply in the case when only characters less + than 256 are recognized to match the types. */ + + case OP_NOT_DIGIT: + set_nottype_bits(start_bits, cbit_digit, table_limit, cd); + try_next = FALSE; + break; + + case OP_DIGIT: + set_type_bits(start_bits, cbit_digit, table_limit, cd); + try_next = FALSE; + break; + + /* The cbit_space table has vertical tab as whitespace; we no longer + have to play fancy tricks because Perl added VT to its whitespace at + release 5.18. PCRE added it at release 8.34. */ + + case OP_NOT_WHITESPACE: + set_nottype_bits(start_bits, cbit_space, table_limit, cd); + try_next = FALSE; + break; + + case OP_WHITESPACE: + set_type_bits(start_bits, cbit_space, table_limit, cd); + try_next = FALSE; + break; + + case OP_NOT_WORDCHAR: + set_nottype_bits(start_bits, cbit_word, table_limit, cd); + try_next = FALSE; + break; + + case OP_WORDCHAR: + set_type_bits(start_bits, cbit_word, table_limit, cd); + try_next = FALSE; + break; + + /* One or more character type fudges the pointer and restarts, knowing + it will hit a single character type and stop there. */ + + case OP_TYPEPLUS: + case OP_TYPEMINPLUS: + case OP_TYPEPOSPLUS: + tcode++; + break; + + case OP_TYPEEXACT: + tcode += 1 + IMM2_SIZE; + break; + + /* Zero or more repeats of character types set the bits and then + try again. */ + + case OP_TYPEUPTO: + case OP_TYPEMINUPTO: + case OP_TYPEPOSUPTO: + tcode += IMM2_SIZE; /* Fall through */ + + case OP_TYPESTAR: + case OP_TYPEMINSTAR: + case OP_TYPEPOSSTAR: + case OP_TYPEQUERY: + case OP_TYPEMINQUERY: + case OP_TYPEPOSQUERY: + switch(tcode[1]) + { + default: + case OP_ANY: + case OP_ALLANY: + return SSB_FAIL; + + case OP_HSPACE: + SET_BIT(CHAR_HT); + SET_BIT(CHAR_SPACE); +#ifdef SUPPORT_UTF + if (utf) + { +#ifdef COMPILE_PCRE8 + SET_BIT(0xC2); /* For U+00A0 */ + SET_BIT(0xE1); /* For U+1680, U+180E */ + SET_BIT(0xE2); /* For U+2000 - U+200A, U+202F, U+205F */ + SET_BIT(0xE3); /* For U+3000 */ +#elif defined COMPILE_PCRE16 || defined COMPILE_PCRE32 + SET_BIT(0xA0); + SET_BIT(0xFF); /* For characters > 255 */ +#endif /* COMPILE_PCRE[8|16|32] */ + } + else +#endif /* SUPPORT_UTF */ +#ifndef EBCDIC + SET_BIT(0xA0); +#endif /* Not EBCDIC */ + break; + + case OP_ANYNL: + case OP_VSPACE: + SET_BIT(CHAR_LF); + SET_BIT(CHAR_VT); + SET_BIT(CHAR_FF); + SET_BIT(CHAR_CR); +#ifdef SUPPORT_UTF + if (utf) + { +#ifdef COMPILE_PCRE8 + SET_BIT(0xC2); /* For U+0085 */ + SET_BIT(0xE2); /* For U+2028, U+2029 */ +#elif defined COMPILE_PCRE16 || defined COMPILE_PCRE32 + SET_BIT(CHAR_NEL); + SET_BIT(0xFF); /* For characters > 255 */ +#endif /* COMPILE_PCRE16 */ + } + else +#endif /* SUPPORT_UTF */ + SET_BIT(CHAR_NEL); + break; + + case OP_NOT_DIGIT: + set_nottype_bits(start_bits, cbit_digit, table_limit, cd); + break; + + case OP_DIGIT: + set_type_bits(start_bits, cbit_digit, table_limit, cd); + break; + + /* The cbit_space table has vertical tab as whitespace; we no longer + have to play fancy tricks because Perl added VT to its whitespace at + release 5.18. PCRE added it at release 8.34. */ + + case OP_NOT_WHITESPACE: + set_nottype_bits(start_bits, cbit_space, table_limit, cd); + break; + + case OP_WHITESPACE: + set_type_bits(start_bits, cbit_space, table_limit, cd); + break; + + case OP_NOT_WORDCHAR: + set_nottype_bits(start_bits, cbit_word, table_limit, cd); + break; + + case OP_WORDCHAR: + set_type_bits(start_bits, cbit_word, table_limit, cd); + break; + } + + tcode += 2; + break; + + /* Character class where all the information is in a bit map: set the + bits and either carry on or not, according to the repeat count. If it was + a negative class, and we are operating with UTF-8 characters, any byte + with a value >= 0xc4 is a potentially valid starter because it starts a + character with a value > 255. */ + +#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 + case OP_XCLASS: + if ((tcode[1 + LINK_SIZE] & XCL_HASPROP) != 0) + return SSB_FAIL; + /* All bits are set. */ + if ((tcode[1 + LINK_SIZE] & XCL_MAP) == 0 && (tcode[1 + LINK_SIZE] & XCL_NOT) != 0) + return SSB_FAIL; +#endif + /* Fall through */ + + case OP_NCLASS: +#if defined SUPPORT_UTF && defined COMPILE_PCRE8 + if (utf) + { + start_bits[24] |= 0xf0; /* Bits for 0xc4 - 0xc8 */ + memset(start_bits+25, 0xff, 7); /* Bits for 0xc9 - 0xff */ + } +#endif +#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 + SET_BIT(0xFF); /* For characters > 255 */ +#endif + /* Fall through */ + + case OP_CLASS: + { + pcre_uint8 *map; +#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 + map = NULL; + if (*tcode == OP_XCLASS) + { + if ((tcode[1 + LINK_SIZE] & XCL_MAP) != 0) + map = (pcre_uint8 *)(tcode + 1 + LINK_SIZE + 1); + tcode += GET(tcode, 1); + } + else +#endif + { + tcode++; + map = (pcre_uint8 *)tcode; + tcode += 32 / sizeof(pcre_uchar); + } + + /* In UTF-8 mode, the bits in a bit map correspond to character + values, not to byte values. However, the bit map we are constructing is + for byte values. So we have to do a conversion for characters whose + value is > 127. In fact, there are only two possible starting bytes for + characters in the range 128 - 255. */ + +#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 + if (map != NULL) +#endif + { +#if defined SUPPORT_UTF && defined COMPILE_PCRE8 + if (utf) + { + for (c = 0; c < 16; c++) start_bits[c] |= map[c]; + for (c = 128; c < 256; c++) + { + if ((map[c/8] && (1 << (c&7))) != 0) + { + int d = (c >> 6) | 0xc0; /* Set bit for this starter */ + start_bits[d/8] |= (1 << (d&7)); /* and then skip on to the */ + c = (c & 0xc0) + 0x40 - 1; /* next relevant character. */ + } + } + } + else +#endif + { + /* In non-UTF-8 mode, the two bit maps are completely compatible. */ + for (c = 0; c < 32; c++) start_bits[c] |= map[c]; + } + } + + /* Advance past the bit map, and act on what follows. For a zero + minimum repeat, continue; otherwise stop processing. */ + + switch (*tcode) + { + case OP_CRSTAR: + case OP_CRMINSTAR: + case OP_CRQUERY: + case OP_CRMINQUERY: + case OP_CRPOSSTAR: + case OP_CRPOSQUERY: + tcode++; + break; + + case OP_CRRANGE: + case OP_CRMINRANGE: + case OP_CRPOSRANGE: + if (GET2(tcode, 1) == 0) tcode += 1 + 2 * IMM2_SIZE; + else try_next = FALSE; + break; + + default: + try_next = FALSE; + break; + } + } + break; /* End of bitmap class handling */ + + } /* End of switch */ + } /* End of try_next loop */ + + code += GET(code, 1); /* Advance to next branch */ + } +while (*code == OP_ALT); +return yield; +} + + + + + +/************************************************* +* Study a compiled expression * +*************************************************/ + +/* This function is handed a compiled expression that it must study to produce +information that will speed up the matching. It returns a pcre[16]_extra block +which then gets handed back to pcre_exec(). + +Arguments: + re points to the compiled expression + options contains option bits + errorptr points to where to place error messages; + set NULL unless error + +Returns: pointer to a pcre[16]_extra block, with study_data filled in and + the appropriate flags set; + NULL on error or if no optimization possible +*/ + +#if defined COMPILE_PCRE8 +PCRE_EXP_DEFN pcre_extra * PCRE_CALL_CONVENTION +pcre_study(const pcre *external_re, int options, const char **errorptr) +#elif defined COMPILE_PCRE16 +PCRE_EXP_DEFN pcre16_extra * PCRE_CALL_CONVENTION +pcre16_study(const pcre16 *external_re, int options, const char **errorptr) +#elif defined COMPILE_PCRE32 +PCRE_EXP_DEFN pcre32_extra * PCRE_CALL_CONVENTION +pcre32_study(const pcre32 *external_re, int options, const char **errorptr) +#endif +{ +int min; +BOOL bits_set = FALSE; +pcre_uint8 start_bits[32]; +PUBL(extra) *extra = NULL; +pcre_study_data *study; +const pcre_uint8 *tables; +pcre_uchar *code; +compile_data compile_block; +const REAL_PCRE *re = (const REAL_PCRE *)external_re; + + +*errorptr = NULL; + +if (re == NULL || re->magic_number != MAGIC_NUMBER) + { + *errorptr = "argument is not a compiled regular expression"; + return NULL; + } + +if ((re->flags & PCRE_MODE) == 0) + { +#if defined COMPILE_PCRE8 + *errorptr = "argument not compiled in 8 bit mode"; +#elif defined COMPILE_PCRE16 + *errorptr = "argument not compiled in 16 bit mode"; +#elif defined COMPILE_PCRE32 + *errorptr = "argument not compiled in 32 bit mode"; +#endif + return NULL; + } + +if ((options & ~PUBLIC_STUDY_OPTIONS) != 0) + { + *errorptr = "unknown or incorrect option bit(s) set"; + return NULL; + } + +code = (pcre_uchar *)re + re->name_table_offset + + (re->name_count * re->name_entry_size); + +/* For an anchored pattern, or an unanchored pattern that has a first char, or +a multiline pattern that matches only at "line starts", there is no point in +seeking a list of starting bytes. */ + +if ((re->options & PCRE_ANCHORED) == 0 && + (re->flags & (PCRE_FIRSTSET|PCRE_STARTLINE)) == 0) + { + int rc; + + /* Set the character tables in the block that is passed around */ + + tables = re->tables; + +#if defined COMPILE_PCRE8 + if (tables == NULL) + (void)pcre_fullinfo(external_re, NULL, PCRE_INFO_DEFAULT_TABLES, + (void *)(&tables)); +#elif defined COMPILE_PCRE16 + if (tables == NULL) + (void)pcre16_fullinfo(external_re, NULL, PCRE_INFO_DEFAULT_TABLES, + (void *)(&tables)); +#elif defined COMPILE_PCRE32 + if (tables == NULL) + (void)pcre32_fullinfo(external_re, NULL, PCRE_INFO_DEFAULT_TABLES, + (void *)(&tables)); +#endif + + compile_block.lcc = tables + lcc_offset; + compile_block.fcc = tables + fcc_offset; + compile_block.cbits = tables + cbits_offset; + compile_block.ctypes = tables + ctypes_offset; + + /* See if we can find a fixed set of initial characters for the pattern. */ + + memset(start_bits, 0, 32 * sizeof(pcre_uint8)); + rc = set_start_bits(code, start_bits, (re->options & PCRE_UTF8) != 0, + &compile_block); + bits_set = rc == SSB_DONE; + if (rc == SSB_UNKNOWN) + { + *errorptr = "internal error: opcode not recognized"; + return NULL; + } + } + +/* Find the minimum length of subject string. */ + +switch(min = find_minlength(re, code, code, re->options, 0)) + { + case -2: *errorptr = "internal error: missing capturing bracket"; return NULL; + case -3: *errorptr = "internal error: opcode not recognized"; return NULL; + default: break; + } + +/* If a set of starting bytes has been identified, or if the minimum length is +greater than zero, or if JIT optimization has been requested, or if +PCRE_STUDY_EXTRA_NEEDED is set, get a pcre[16]_extra block and a +pcre_study_data block. The study data is put in the latter, which is pointed to +by the former, which may also get additional data set later by the calling +program. At the moment, the size of pcre_study_data is fixed. We nevertheless +save it in a field for returning via the pcre_fullinfo() function so that if it +becomes variable in the future, we don't have to change that code. */ + +if (bits_set || min > 0 || (options & ( +#ifdef SUPPORT_JIT + PCRE_STUDY_JIT_COMPILE | PCRE_STUDY_JIT_PARTIAL_SOFT_COMPILE | + PCRE_STUDY_JIT_PARTIAL_HARD_COMPILE | +#endif + PCRE_STUDY_EXTRA_NEEDED)) != 0) + { + extra = (PUBL(extra) *)(PUBL(malloc)) + (sizeof(PUBL(extra)) + sizeof(pcre_study_data)); + if (extra == NULL) + { + *errorptr = "failed to get memory"; + return NULL; + } + + study = (pcre_study_data *)((char *)extra + sizeof(PUBL(extra))); + extra->flags = PCRE_EXTRA_STUDY_DATA; + extra->study_data = study; + + study->size = sizeof(pcre_study_data); + study->flags = 0; + + /* Set the start bits always, to avoid unset memory errors if the + study data is written to a file, but set the flag only if any of the bits + are set, to save time looking when none are. */ + + if (bits_set) + { + study->flags |= PCRE_STUDY_MAPPED; + memcpy(study->start_bits, start_bits, sizeof(start_bits)); + } + else memset(study->start_bits, 0, 32 * sizeof(pcre_uint8)); + +#ifdef PCRE_DEBUG + if (bits_set) + { + pcre_uint8 *ptr = start_bits; + int i; + + printf("Start bits:\n"); + for (i = 0; i < 32; i++) + printf("%3d: %02x%s", i * 8, *ptr++, ((i + 1) & 0x7) != 0? " " : "\n"); + } +#endif + + /* Always set the minlength value in the block, because the JIT compiler + makes use of it. However, don't set the bit unless the length is greater than + zero - the interpretive pcre_exec() and pcre_dfa_exec() needn't waste time + checking the zero case. */ + + if (min > 0) + { + study->flags |= PCRE_STUDY_MINLEN; + study->minlength = min; + } + else study->minlength = 0; + + /* If JIT support was compiled and requested, attempt the JIT compilation. + If no starting bytes were found, and the minimum length is zero, and JIT + compilation fails, abandon the extra block and return NULL, unless + PCRE_STUDY_EXTRA_NEEDED is set. */ + +#ifdef SUPPORT_JIT + extra->executable_jit = NULL; + if ((options & PCRE_STUDY_JIT_COMPILE) != 0) + PRIV(jit_compile)(re, extra, JIT_COMPILE); + if ((options & PCRE_STUDY_JIT_PARTIAL_SOFT_COMPILE) != 0) + PRIV(jit_compile)(re, extra, JIT_PARTIAL_SOFT_COMPILE); + if ((options & PCRE_STUDY_JIT_PARTIAL_HARD_COMPILE) != 0) + PRIV(jit_compile)(re, extra, JIT_PARTIAL_HARD_COMPILE); + + if (study->flags == 0 && (extra->flags & PCRE_EXTRA_EXECUTABLE_JIT) == 0 && + (options & PCRE_STUDY_EXTRA_NEEDED) == 0) + { +#if defined COMPILE_PCRE8 + pcre_free_study(extra); +#elif defined COMPILE_PCRE16 + pcre16_free_study(extra); +#elif defined COMPILE_PCRE32 + pcre32_free_study(extra); +#endif + extra = NULL; + } +#endif + } + +return extra; +} + + +/************************************************* +* Free the study data * +*************************************************/ + +/* This function frees the memory that was obtained by pcre_study(). + +Argument: a pointer to the pcre[16]_extra block +Returns: nothing +*/ + +#if defined COMPILE_PCRE8 +PCRE_EXP_DEFN void +pcre_free_study(pcre_extra *extra) +#elif defined COMPILE_PCRE16 +PCRE_EXP_DEFN void +pcre16_free_study(pcre16_extra *extra) +#elif defined COMPILE_PCRE32 +PCRE_EXP_DEFN void +pcre32_free_study(pcre32_extra *extra) +#endif +{ +if (extra == NULL) + return; +#ifdef SUPPORT_JIT +if ((extra->flags & PCRE_EXTRA_EXECUTABLE_JIT) != 0 && + extra->executable_jit != NULL) + PRIV(jit_free)(extra->executable_jit); +#endif +PUBL(free)(extra); +} + +/* End of pcre_study.c */ diff --git a/src/private/pcre_src/pcre_tables.c b/src/private/pcre_src/pcre_tables.c new file mode 100644 index 000000000..4960af57c --- /dev/null +++ b/src/private/pcre_src/pcre_tables.c @@ -0,0 +1,727 @@ +/************************************************* +* Perl-Compatible Regular Expressions * +*************************************************/ + +/* PCRE is a library of functions to support regular expressions whose syntax +and semantics are as close as possible to those of the Perl 5 language. + + Written by Philip Hazel + Copyright (c) 1997-2012 University of Cambridge + +----------------------------------------------------------------------------- +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * Neither the name of the University of Cambridge nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. +----------------------------------------------------------------------------- +*/ + +#ifndef PCRE_INCLUDED + +/* This module contains some fixed tables that are used by more than one of the +PCRE code modules. The tables are also #included by the pcretest program, which +uses macros to change their names from _pcre_xxx to xxxx, thereby avoiding name +clashes with the library. */ + + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "pcre_internal.h" + +#endif /* PCRE_INCLUDED */ + +/* Table of sizes for the fixed-length opcodes. It's defined in a macro so that +the definition is next to the definition of the opcodes in pcre_internal.h. */ + +const pcre_uint8 PRIV(OP_lengths)[] = { OP_LENGTHS }; + +/* Tables of horizontal and vertical whitespace characters, suitable for +adding to classes. */ + +const pcre_uint32 PRIV(hspace_list)[] = { HSPACE_LIST }; +const pcre_uint32 PRIV(vspace_list)[] = { VSPACE_LIST }; + + + +/************************************************* +* Tables for UTF-8 support * +*************************************************/ + +/* These are the breakpoints for different numbers of bytes in a UTF-8 +character. */ + +#if (defined SUPPORT_UTF && defined COMPILE_PCRE8) \ + || (defined PCRE_INCLUDED && (defined SUPPORT_PCRE16 || defined SUPPORT_PCRE32)) + +/* These tables are also required by pcretest in 16- or 32-bit mode. */ + +const int PRIV(utf8_table1)[] = + { 0x7f, 0x7ff, 0xffff, 0x1fffff, 0x3ffffff, 0x7fffffff}; + +const int PRIV(utf8_table1_size) = sizeof(PRIV(utf8_table1)) / sizeof(int); + +/* These are the indicator bits and the mask for the data bits to set in the +first byte of a character, indexed by the number of additional bytes. */ + +const int PRIV(utf8_table2)[] = { 0, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc}; +const int PRIV(utf8_table3)[] = { 0xff, 0x1f, 0x0f, 0x07, 0x03, 0x01}; + +/* Table of the number of extra bytes, indexed by the first byte masked with +0x3f. The highest number for a valid UTF-8 first byte is in fact 0x3d. */ + +const pcre_uint8 PRIV(utf8_table4)[] = { + 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, + 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5 }; + +#endif /* (SUPPORT_UTF && COMPILE_PCRE8) || (PCRE_INCLUDED && SUPPORT_PCRE[16|32])*/ + +#ifdef SUPPORT_UTF + +/* Table to translate from particular type value to the general value. */ + +const pcre_uint32 PRIV(ucp_gentype)[] = { + ucp_C, ucp_C, ucp_C, ucp_C, ucp_C, /* Cc, Cf, Cn, Co, Cs */ + ucp_L, ucp_L, ucp_L, ucp_L, ucp_L, /* Ll, Lu, Lm, Lo, Lt */ + ucp_M, ucp_M, ucp_M, /* Mc, Me, Mn */ + ucp_N, ucp_N, ucp_N, /* Nd, Nl, No */ + ucp_P, ucp_P, ucp_P, ucp_P, ucp_P, /* Pc, Pd, Pe, Pf, Pi */ + ucp_P, ucp_P, /* Ps, Po */ + ucp_S, ucp_S, ucp_S, ucp_S, /* Sc, Sk, Sm, So */ + ucp_Z, ucp_Z, ucp_Z /* Zl, Zp, Zs */ +}; + +/* This table encodes the rules for finding the end of an extended grapheme +cluster. Every code point has a grapheme break property which is one of the +ucp_gbXX values defined in ucp.h. The 2-dimensional table is indexed by the +properties of two adjacent code points. The left property selects a word from +the table, and the right property selects a bit from that word like this: + + ucp_gbtable[left-property] & (1 << right-property) + +The value is non-zero if a grapheme break is NOT permitted between the relevant +two code points. The breaking rules are as follows: + +1. Break at the start and end of text (pretty obviously). + +2. Do not break between a CR and LF; otherwise, break before and after + controls. + +3. Do not break Hangul syllable sequences, the rules for which are: + + L may be followed by L, V, LV or LVT + LV or V may be followed by V or T + LVT or T may be followed by T + +4. Do not break before extending characters. + +The next two rules are only for extended grapheme clusters (but that's what we +are implementing). + +5. Do not break before SpacingMarks. + +6. Do not break after Prepend characters. + +7. Otherwise, break everywhere. +*/ + +const pcre_uint32 PRIV(ucp_gbtable[]) = { + (1< 0x10ffff is not permitted +PCRE_UTF8_ERR14 3-byte character with value 0xd000-0xdfff is not permitted +PCRE_UTF8_ERR15 Overlong 2-byte sequence +PCRE_UTF8_ERR16 Overlong 3-byte sequence +PCRE_UTF8_ERR17 Overlong 4-byte sequence +PCRE_UTF8_ERR18 Overlong 5-byte sequence (won't ever occur) +PCRE_UTF8_ERR19 Overlong 6-byte sequence (won't ever occur) +PCRE_UTF8_ERR20 Isolated 0x80 byte (not within UTF-8 character) +PCRE_UTF8_ERR21 Byte with the illegal value 0xfe or 0xff +PCRE_UTF8_ERR22 Unused (was non-character) + +Arguments: + string points to the string + length length of string, or -1 if the string is zero-terminated + errp pointer to an error position offset variable + +Returns: = 0 if the string is a valid UTF-8 string + > 0 otherwise, setting the offset of the bad character +*/ + +int +PRIV(valid_utf)(PCRE_PUCHAR string, int length, int *erroroffset) +{ +#ifdef SUPPORT_UTF +register PCRE_PUCHAR p; + +if (length < 0) + { + for (p = string; *p != 0; p++); + length = (int)(p - string); + } + +for (p = string; length-- > 0; p++) + { + register pcre_uchar ab, c, d; + + c = *p; + if (c < 128) continue; /* ASCII character */ + + if (c < 0xc0) /* Isolated 10xx xxxx byte */ + { + *erroroffset = (int)(p - string); + return PCRE_UTF8_ERR20; + } + + if (c >= 0xfe) /* Invalid 0xfe or 0xff bytes */ + { + *erroroffset = (int)(p - string); + return PCRE_UTF8_ERR21; + } + + ab = PRIV(utf8_table4)[c & 0x3f]; /* Number of additional bytes */ + if (length < ab) + { + *erroroffset = (int)(p - string); /* Missing bytes */ + return ab - length; /* Codes ERR1 to ERR5 */ + } + length -= ab; /* Length remaining */ + + /* Check top bits in the second byte */ + + if (((d = *(++p)) & 0xc0) != 0x80) + { + *erroroffset = (int)(p - string) - 1; + return PCRE_UTF8_ERR6; + } + + /* For each length, check that the remaining bytes start with the 0x80 bit + set and not the 0x40 bit. Then check for an overlong sequence, and for the + excluded range 0xd800 to 0xdfff. */ + + switch (ab) + { + /* 2-byte character. No further bytes to check for 0x80. Check first byte + for for xx00 000x (overlong sequence). */ + + case 1: if ((c & 0x3e) == 0) + { + *erroroffset = (int)(p - string) - 1; + return PCRE_UTF8_ERR15; + } + break; + + /* 3-byte character. Check third byte for 0x80. Then check first 2 bytes + for 1110 0000, xx0x xxxx (overlong sequence) or + 1110 1101, 1010 xxxx (0xd800 - 0xdfff) */ + + case 2: + if ((*(++p) & 0xc0) != 0x80) /* Third byte */ + { + *erroroffset = (int)(p - string) - 2; + return PCRE_UTF8_ERR7; + } + if (c == 0xe0 && (d & 0x20) == 0) + { + *erroroffset = (int)(p - string) - 2; + return PCRE_UTF8_ERR16; + } + if (c == 0xed && d >= 0xa0) + { + *erroroffset = (int)(p - string) - 2; + return PCRE_UTF8_ERR14; + } + break; + + /* 4-byte character. Check 3rd and 4th bytes for 0x80. Then check first 2 + bytes for for 1111 0000, xx00 xxxx (overlong sequence), then check for a + character greater than 0x0010ffff (f4 8f bf bf) */ + + case 3: + if ((*(++p) & 0xc0) != 0x80) /* Third byte */ + { + *erroroffset = (int)(p - string) - 2; + return PCRE_UTF8_ERR7; + } + if ((*(++p) & 0xc0) != 0x80) /* Fourth byte */ + { + *erroroffset = (int)(p - string) - 3; + return PCRE_UTF8_ERR8; + } + if (c == 0xf0 && (d & 0x30) == 0) + { + *erroroffset = (int)(p - string) - 3; + return PCRE_UTF8_ERR17; + } + if (c > 0xf4 || (c == 0xf4 && d > 0x8f)) + { + *erroroffset = (int)(p - string) - 3; + return PCRE_UTF8_ERR13; + } + break; + + /* 5-byte and 6-byte characters are not allowed by RFC 3629, and will be + rejected by the length test below. However, we do the appropriate tests + here so that overlong sequences get diagnosed, and also in case there is + ever an option for handling these larger code points. */ + + /* 5-byte character. Check 3rd, 4th, and 5th bytes for 0x80. Then check for + 1111 1000, xx00 0xxx */ + + case 4: + if ((*(++p) & 0xc0) != 0x80) /* Third byte */ + { + *erroroffset = (int)(p - string) - 2; + return PCRE_UTF8_ERR7; + } + if ((*(++p) & 0xc0) != 0x80) /* Fourth byte */ + { + *erroroffset = (int)(p - string) - 3; + return PCRE_UTF8_ERR8; + } + if ((*(++p) & 0xc0) != 0x80) /* Fifth byte */ + { + *erroroffset = (int)(p - string) - 4; + return PCRE_UTF8_ERR9; + } + if (c == 0xf8 && (d & 0x38) == 0) + { + *erroroffset = (int)(p - string) - 4; + return PCRE_UTF8_ERR18; + } + break; + + /* 6-byte character. Check 3rd-6th bytes for 0x80. Then check for + 1111 1100, xx00 00xx. */ + + case 5: + if ((*(++p) & 0xc0) != 0x80) /* Third byte */ + { + *erroroffset = (int)(p - string) - 2; + return PCRE_UTF8_ERR7; + } + if ((*(++p) & 0xc0) != 0x80) /* Fourth byte */ + { + *erroroffset = (int)(p - string) - 3; + return PCRE_UTF8_ERR8; + } + if ((*(++p) & 0xc0) != 0x80) /* Fifth byte */ + { + *erroroffset = (int)(p - string) - 4; + return PCRE_UTF8_ERR9; + } + if ((*(++p) & 0xc0) != 0x80) /* Sixth byte */ + { + *erroroffset = (int)(p - string) - 5; + return PCRE_UTF8_ERR10; + } + if (c == 0xfc && (d & 0x3c) == 0) + { + *erroroffset = (int)(p - string) - 5; + return PCRE_UTF8_ERR19; + } + break; + } + + /* Character is valid under RFC 2279, but 4-byte and 5-byte characters are + excluded by RFC 3629. The pointer p is currently at the last byte of the + character. */ + + if (ab > 3) + { + *erroroffset = (int)(p - string) - ab; + return (ab == 4)? PCRE_UTF8_ERR11 : PCRE_UTF8_ERR12; + } + } + +#else /* Not SUPPORT_UTF */ +(void)(string); /* Keep picky compilers happy */ +(void)(length); +(void)(erroroffset); +#endif + +return PCRE_UTF8_ERR0; /* This indicates success */ +} + +/* End of pcre_valid_utf8.c */ diff --git a/src/private/pcre_src/pcre_version.c b/src/private/pcre_src/pcre_version.c new file mode 100644 index 000000000..ae86ff28b --- /dev/null +++ b/src/private/pcre_src/pcre_version.c @@ -0,0 +1,98 @@ +/************************************************* +* Perl-Compatible Regular Expressions * +*************************************************/ + +/* PCRE is a library of functions to support regular expressions whose syntax +and semantics are as close as possible to those of the Perl 5 language. + + Written by Philip Hazel + Copyright (c) 1997-2012 University of Cambridge + +----------------------------------------------------------------------------- +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * Neither the name of the University of Cambridge nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. +----------------------------------------------------------------------------- +*/ + + +/* This module contains the external function pcre_version(), which returns a +string that identifies the PCRE version that is in use. */ + + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "pcre_internal.h" + + +/************************************************* +* Return version string * +*************************************************/ + +/* These macros are the standard way of turning unquoted text into C strings. +They allow macros like PCRE_MAJOR to be defined without quotes, which is +convenient for user programs that want to test its value. */ + +#define STRING(a) # a +#define XSTRING(s) STRING(s) + +/* A problem turned up with PCRE_PRERELEASE, which is defined empty for +production releases. Originally, it was used naively in this code: + + return XSTRING(PCRE_MAJOR) + "." XSTRING(PCRE_MINOR) + XSTRING(PCRE_PRERELEASE) + " " XSTRING(PCRE_DATE); + +However, when PCRE_PRERELEASE is empty, this leads to an attempted expansion of +STRING(). The C standard states: "If (before argument substitution) any +argument consists of no preprocessing tokens, the behavior is undefined." It +turns out the gcc treats this case as a single empty string - which is what we +really want - but Visual C grumbles about the lack of an argument for the +macro. Unfortunately, both are within their rights. To cope with both ways of +handling this, I had resort to some messy hackery that does a test at run time. +I could find no way of detecting that a macro is defined as an empty string at +pre-processor time. This hack uses a standard trick for avoiding calling +the STRING macro with an empty argument when doing the test. */ + +#if defined COMPILE_PCRE8 +PCRE_EXP_DEFN const char * PCRE_CALL_CONVENTION +pcre_version(void) +#elif defined COMPILE_PCRE16 +PCRE_EXP_DEFN const char * PCRE_CALL_CONVENTION +pcre16_version(void) +#elif defined COMPILE_PCRE32 +PCRE_EXP_DEFN const char * PCRE_CALL_CONVENTION +pcre32_version(void) +#endif +{ +return (XSTRING(Z PCRE_PRERELEASE)[1] == 0)? + XSTRING(PCRE_MAJOR.PCRE_MINOR PCRE_DATE) : + XSTRING(PCRE_MAJOR.PCRE_MINOR) XSTRING(PCRE_PRERELEASE PCRE_DATE); +} + +/* End of pcre_version.c */ diff --git a/src/private/pcre_src/pcre_xclass.c b/src/private/pcre_src/pcre_xclass.c new file mode 100644 index 000000000..c2b61f0f9 --- /dev/null +++ b/src/private/pcre_src/pcre_xclass.c @@ -0,0 +1,268 @@ +/************************************************* +* Perl-Compatible Regular Expressions * +*************************************************/ + +/* PCRE is a library of functions to support regular expressions whose syntax +and semantics are as close as possible to those of the Perl 5 language. + + Written by Philip Hazel + Copyright (c) 1997-2013 University of Cambridge + +----------------------------------------------------------------------------- +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * Neither the name of the University of Cambridge nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. +----------------------------------------------------------------------------- +*/ + + +/* This module contains an internal function that is used to match an extended +class. It is used by both pcre_exec() and pcre_def_exec(). */ + + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "pcre_internal.h" + + +/************************************************* +* Match character against an XCLASS * +*************************************************/ + +/* This function is called to match a character against an extended class that +might contain values > 255 and/or Unicode properties. + +Arguments: + c the character + data points to the flag byte of the XCLASS data + +Returns: TRUE if character matches, else FALSE +*/ + +BOOL +PRIV(xclass)(pcre_uint32 c, const pcre_uchar *data, BOOL utf) +{ +pcre_uchar t; +BOOL negated = (*data & XCL_NOT) != 0; + +(void)utf; +#ifdef COMPILE_PCRE8 +/* In 8 bit mode, this must always be TRUE. Help the compiler to know that. */ +utf = TRUE; +#endif + +/* Character values < 256 are matched against a bitmap, if one is present. If +not, we still carry on, because there may be ranges that start below 256 in the +additional data. */ + +if (c < 256) + { + if ((*data & XCL_HASPROP) == 0) + { + if ((*data & XCL_MAP) == 0) return negated; + return (((pcre_uint8 *)(data + 1))[c/8] & (1 << (c&7))) != 0; + } + if ((*data & XCL_MAP) != 0 && + (((pcre_uint8 *)(data + 1))[c/8] & (1 << (c&7))) != 0) + return !negated; /* char found */ + } + +/* First skip the bit map if present. Then match against the list of Unicode +properties or large chars or ranges that end with a large char. We won't ever +encounter XCL_PROP or XCL_NOTPROP when UCP support is not compiled. */ + +if ((*data++ & XCL_MAP) != 0) data += 32 / sizeof(pcre_uchar); + +while ((t = *data++) != XCL_END) + { + pcre_uint32 x, y; + if (t == XCL_SINGLE) + { +#ifdef SUPPORT_UTF + if (utf) + { + GETCHARINC(x, data); /* macro generates multiple statements */ + } + else +#endif + x = *data++; + if (c == x) return !negated; + } + else if (t == XCL_RANGE) + { +#ifdef SUPPORT_UTF + if (utf) + { + GETCHARINC(x, data); /* macro generates multiple statements */ + GETCHARINC(y, data); /* macro generates multiple statements */ + } + else +#endif + { + x = *data++; + y = *data++; + } + if (c >= x && c <= y) return !negated; + } + +#ifdef SUPPORT_UCP + else /* XCL_PROP & XCL_NOTPROP */ + { + const ucd_record *prop = GET_UCD(c); + BOOL isprop = t == XCL_PROP; + + switch(*data) + { + case PT_ANY: + if (isprop) return !negated; + break; + + case PT_LAMP: + if ((prop->chartype == ucp_Lu || prop->chartype == ucp_Ll || + prop->chartype == ucp_Lt) == isprop) return !negated; + break; + + case PT_GC: + if ((data[1] == PRIV(ucp_gentype)[prop->chartype]) == isprop) + return !negated; + break; + + case PT_PC: + if ((data[1] == prop->chartype) == isprop) return !negated; + break; + + case PT_SC: + if ((data[1] == prop->script) == isprop) return !negated; + break; + + case PT_ALNUM: + if ((PRIV(ucp_gentype)[prop->chartype] == ucp_L || + PRIV(ucp_gentype)[prop->chartype] == ucp_N) == isprop) + return !negated; + break; + + /* Perl space used to exclude VT, but from Perl 5.18 it is included, + which means that Perl space and POSIX space are now identical. PCRE + was changed at release 8.34. */ + + case PT_SPACE: /* Perl space */ + case PT_PXSPACE: /* POSIX space */ + switch(c) + { + HSPACE_CASES: + VSPACE_CASES: + if (isprop) return !negated; + break; + + default: + if ((PRIV(ucp_gentype)[prop->chartype] == ucp_Z) == isprop) + return !negated; + break; + } + break; + + case PT_WORD: + if ((PRIV(ucp_gentype)[prop->chartype] == ucp_L || + PRIV(ucp_gentype)[prop->chartype] == ucp_N || c == CHAR_UNDERSCORE) + == isprop) + return !negated; + break; + + case PT_UCNC: + if (c < 0xa0) + { + if ((c == CHAR_DOLLAR_SIGN || c == CHAR_COMMERCIAL_AT || + c == CHAR_GRAVE_ACCENT) == isprop) + return !negated; + } + else + { + if ((c < 0xd800 || c > 0xdfff) == isprop) + return !negated; + } + break; + + /* The following three properties can occur only in an XCLASS, as there + is no \p or \P coding for them. */ + + /* Graphic character. Implement this as not Z (space or separator) and + not C (other), except for Cf (format) with a few exceptions. This seems + to be what Perl does. The exceptional characters are: + + U+061C Arabic Letter Mark + U+180E Mongolian Vowel Separator + U+2066 - U+2069 Various "isolate"s + */ + + case PT_PXGRAPH: + if ((PRIV(ucp_gentype)[prop->chartype] != ucp_Z && + (PRIV(ucp_gentype)[prop->chartype] != ucp_C || + (prop->chartype == ucp_Cf && + c != 0x061c && c != 0x180e && (c < 0x2066 || c > 0x2069)) + )) == isprop) + return !negated; + break; + + /* Printable character: same as graphic, with the addition of Zs, i.e. + not Zl and not Zp, and U+180E. */ + + case PT_PXPRINT: + if ((prop->chartype != ucp_Zl && + prop->chartype != ucp_Zp && + (PRIV(ucp_gentype)[prop->chartype] != ucp_C || + (prop->chartype == ucp_Cf && + c != 0x061c && (c < 0x2066 || c > 0x2069)) + )) == isprop) + return !negated; + break; + + /* Punctuation: all Unicode punctuation, plus ASCII characters that + Unicode treats as symbols rather than punctuation, for Perl + compatibility (these are $+<=>^`|~). */ + + case PT_PXPUNCT: + if ((PRIV(ucp_gentype)[prop->chartype] == ucp_P || + (c < 256 && PRIV(ucp_gentype)[prop->chartype] == ucp_S)) == isprop) + return !negated; + break; + + /* This should never occur, but compilers may mutter if there is no + default. */ + + default: + return FALSE; + } + + data += 2; + } +#endif /* SUPPORT_UCP */ + } + +return negated; /* char did not match */ +} + +/* End of pcre_xclass.c */ diff --git a/src/private/pcre_src/ucp.h b/src/private/pcre_src/ucp.h new file mode 100644 index 000000000..2fa00296e --- /dev/null +++ b/src/private/pcre_src/ucp.h @@ -0,0 +1,224 @@ +/************************************************* +* Unicode Property Table handler * +*************************************************/ + +#ifndef _UCP_H +#define _UCP_H + +/* This file contains definitions of the property values that are returned by +the UCD access macros. New values that are added for new releases of Unicode +should always be at the end of each enum, for backwards compatibility. + +IMPORTANT: Note also that the specific numeric values of the enums have to be +the same as the values that are generated by the maint/MultiStage2.py script, +where the equivalent property descriptive names are listed in vectors. + +ALSO: The specific values of the first two enums are assumed for the table +called catposstab in pcre_compile.c. */ + +/* These are the general character categories. */ + +enum { + ucp_C, /* Other */ + ucp_L, /* Letter */ + ucp_M, /* Mark */ + ucp_N, /* Number */ + ucp_P, /* Punctuation */ + ucp_S, /* Symbol */ + ucp_Z /* Separator */ +}; + +/* These are the particular character categories. */ + +enum { + ucp_Cc, /* Control */ + ucp_Cf, /* Format */ + ucp_Cn, /* Unassigned */ + ucp_Co, /* Private use */ + ucp_Cs, /* Surrogate */ + ucp_Ll, /* Lower case letter */ + ucp_Lm, /* Modifier letter */ + ucp_Lo, /* Other letter */ + ucp_Lt, /* Title case letter */ + ucp_Lu, /* Upper case letter */ + ucp_Mc, /* Spacing mark */ + ucp_Me, /* Enclosing mark */ + ucp_Mn, /* Non-spacing mark */ + ucp_Nd, /* Decimal number */ + ucp_Nl, /* Letter number */ + ucp_No, /* Other number */ + ucp_Pc, /* Connector punctuation */ + ucp_Pd, /* Dash punctuation */ + ucp_Pe, /* Close punctuation */ + ucp_Pf, /* Final punctuation */ + ucp_Pi, /* Initial punctuation */ + ucp_Po, /* Other punctuation */ + ucp_Ps, /* Open punctuation */ + ucp_Sc, /* Currency symbol */ + ucp_Sk, /* Modifier symbol */ + ucp_Sm, /* Mathematical symbol */ + ucp_So, /* Other symbol */ + ucp_Zl, /* Line separator */ + ucp_Zp, /* Paragraph separator */ + ucp_Zs /* Space separator */ +}; + +/* These are grapheme break properties. Note that the code for processing them +assumes that the values are less than 16. If more values are added that take +the number to 16 or more, the code will have to be rewritten. */ + +enum { + ucp_gbCR, /* 0 */ + ucp_gbLF, /* 1 */ + ucp_gbControl, /* 2 */ + ucp_gbExtend, /* 3 */ + ucp_gbPrepend, /* 4 */ + ucp_gbSpacingMark, /* 5 */ + ucp_gbL, /* 6 Hangul syllable type L */ + ucp_gbV, /* 7 Hangul syllable type V */ + ucp_gbT, /* 8 Hangul syllable type T */ + ucp_gbLV, /* 9 Hangul syllable type LV */ + ucp_gbLVT, /* 10 Hangul syllable type LVT */ + ucp_gbRegionalIndicator, /* 11 */ + ucp_gbOther /* 12 */ +}; + +/* These are the script identifications. */ + +enum { + ucp_Arabic, + ucp_Armenian, + ucp_Bengali, + ucp_Bopomofo, + ucp_Braille, + ucp_Buginese, + ucp_Buhid, + ucp_Canadian_Aboriginal, + ucp_Cherokee, + ucp_Common, + ucp_Coptic, + ucp_Cypriot, + ucp_Cyrillic, + ucp_Deseret, + ucp_Devanagari, + ucp_Ethiopic, + ucp_Georgian, + ucp_Glagolitic, + ucp_Gothic, + ucp_Greek, + ucp_Gujarati, + ucp_Gurmukhi, + ucp_Han, + ucp_Hangul, + ucp_Hanunoo, + ucp_Hebrew, + ucp_Hiragana, + ucp_Inherited, + ucp_Kannada, + ucp_Katakana, + ucp_Kharoshthi, + ucp_Khmer, + ucp_Lao, + ucp_Latin, + ucp_Limbu, + ucp_Linear_B, + ucp_Malayalam, + ucp_Mongolian, + ucp_Myanmar, + ucp_New_Tai_Lue, + ucp_Ogham, + ucp_Old_Italic, + ucp_Old_Persian, + ucp_Oriya, + ucp_Osmanya, + ucp_Runic, + ucp_Shavian, + ucp_Sinhala, + ucp_Syloti_Nagri, + ucp_Syriac, + ucp_Tagalog, + ucp_Tagbanwa, + ucp_Tai_Le, + ucp_Tamil, + ucp_Telugu, + ucp_Thaana, + ucp_Thai, + ucp_Tibetan, + ucp_Tifinagh, + ucp_Ugaritic, + ucp_Yi, + /* New for Unicode 5.0: */ + ucp_Balinese, + ucp_Cuneiform, + ucp_Nko, + ucp_Phags_Pa, + ucp_Phoenician, + /* New for Unicode 5.1: */ + ucp_Carian, + ucp_Cham, + ucp_Kayah_Li, + ucp_Lepcha, + ucp_Lycian, + ucp_Lydian, + ucp_Ol_Chiki, + ucp_Rejang, + ucp_Saurashtra, + ucp_Sundanese, + ucp_Vai, + /* New for Unicode 5.2: */ + ucp_Avestan, + ucp_Bamum, + ucp_Egyptian_Hieroglyphs, + ucp_Imperial_Aramaic, + ucp_Inscriptional_Pahlavi, + ucp_Inscriptional_Parthian, + ucp_Javanese, + ucp_Kaithi, + ucp_Lisu, + ucp_Meetei_Mayek, + ucp_Old_South_Arabian, + ucp_Old_Turkic, + ucp_Samaritan, + ucp_Tai_Tham, + ucp_Tai_Viet, + /* New for Unicode 6.0.0: */ + ucp_Batak, + ucp_Brahmi, + ucp_Mandaic, + /* New for Unicode 6.1.0: */ + ucp_Chakma, + ucp_Meroitic_Cursive, + ucp_Meroitic_Hieroglyphs, + ucp_Miao, + ucp_Sharada, + ucp_Sora_Sompeng, + ucp_Takri, + /* New for Unicode 7.0.0: */ + ucp_Bassa_Vah, + ucp_Caucasian_Albanian, + ucp_Duployan, + ucp_Elbasan, + ucp_Grantha, + ucp_Khojki, + ucp_Khudawadi, + ucp_Linear_A, + ucp_Mahajani, + ucp_Manichaean, + ucp_Mende_Kikakui, + ucp_Modi, + ucp_Mro, + ucp_Nabataean, + ucp_Old_North_Arabian, + ucp_Old_Permic, + ucp_Pahawh_Hmong, + ucp_Palmyrene, + ucp_Psalter_Pahlavi, + ucp_Pau_Cin_Hau, + ucp_Siddham, + ucp_Tirhuta, + ucp_Warang_Citi +}; + +#endif + +/* End of ucp.h */ From 41c0060e6ddc9b413041a8118e48415783253c40 Mon Sep 17 00:00:00 2001 From: Oleh Prypin Date: Mon, 19 Jan 2015 14:33:05 +0200 Subject: [PATCH 0081/1263] Fix last element when splitting with 0-length match --- src/nre.nim | 27 ++++++++++++++------------- test/split.nim | 7 ++++++- 2 files changed, 20 insertions(+), 14 deletions(-) diff --git a/src/nre.nim b/src/nre.nim index d907cae62..d98f55889 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -391,6 +391,7 @@ proc split*(str: string, pattern: Regex, maxSplit = -1): seq[string] = result = @[] var lastIdx = 0 var splits = 0 + var bounds: Slice[int] for match in str.findIter(pattern): # upper bound is exclusive, lower is inclusive: @@ -398,16 +399,12 @@ proc split*(str: string, pattern: Regex, maxSplit = -1): seq[string] = # 0123456 # ^^^ # (1, 4) - var bounds = match.matchBounds + bounds = match.matchBounds - if lastIdx == 0 and - lastIdx == bounds.a and - bounds.a == bounds.b: - # "12".split("") would be @["", "1", "2"], but - # if we skip an empty first match, it's the correct - # @["1", "2"] - discard - else: + # "12".split("") would be @["", "1", "2"], but + # if we skip an empty first match, it's the correct + # @["1", "2"] + if bounds.a < bounds.b or bounds.a > 0: result.add(str.substr(lastIdx, bounds.a - 1)) splits += 1 @@ -420,10 +417,14 @@ proc split*(str: string, pattern: Regex, maxSplit = -1): seq[string] = if splits == maxSplit: break - # last match: Each match takes the previous substring, - # but "1 2".split(/ /) needs to return @["1", "2"]. - # This handles "2" - result.add(str.substr(lastIdx, str.len - 1)) + # "12".split("\b") would be @["1", "2", ""], but + # if we skip an empty last match, it's the correct + # @["1", "2"] + if bounds.a < bounds.b or bounds.b < str.len: + # last match: Each match takes the previous substring, + # but "1 2".split(/ /) needs to return @["1", "2"]. + # This handles "2" + result.add(str.substr(bounds.b, str.len - 1)) proc replace*(str: string, pattern: Regex, subproc: proc (match: RegexMatch): string): string = diff --git a/test/split.nim b/test/split.nim index 184b5f9e2..6cc68a41e 100644 --- a/test/split.nim +++ b/test/split.nim @@ -3,11 +3,11 @@ include nre suite "string splitting": test "splitting strings": - check("12345".split(re("")) == @["1", "2", "3", "4", "5"]) check("1 2 3 4 5 6 ".split(re" ") == @["1", "2", "3", "4", "5", "6", ""]) check("1 2 ".split(re(" ")) == @["1", "", "2", "", ""]) check("1 2".split(re(" ")) == @["1", "2"]) check("foo".split(re("foo")) == @["", ""]) + check("".split(re"foo") == newSeq[string]()) test "captured patterns": check("12".split(re"(\d)") == @["", "1", "", "2", ""]) @@ -16,3 +16,8 @@ suite "string splitting": check("123".split(re"", maxsplit = 1) == @["1", "23"]) check("123".split(re"", maxsplit = 0) == @["123"]) check("123".split(re"", maxsplit = -1) == @["1", "2", "3"]) + + test "split with 0-length match": + check("12345".split(re("")) == @["1", "2", "3", "4", "5"]) + check("".split(re"") == newSeq[string]()) + check("word word".split(re"\b") == @["word", " ", "word"]) From 04699a7587dc83d37bd5e1618409cac11dc04f75 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Mon, 19 Jan 2015 07:37:04 -0500 Subject: [PATCH 0082/1263] Add perl split tests --- test/split.nim | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/test/split.nim b/test/split.nim index 184b5f9e2..9f9ebef36 100644 --- a/test/split.nim +++ b/test/split.nim @@ -1,4 +1,4 @@ -import unittest +import unittest, strutils include nre suite "string splitting": @@ -16,3 +16,25 @@ suite "string splitting": check("123".split(re"", maxsplit = 1) == @["1", "23"]) check("123".split(re"", maxsplit = 0) == @["123"]) check("123".split(re"", maxsplit = -1) == @["1", "2", "3"]) + + test "perl split tests": + check("forty-two" .split(re"") .join(",") == "f,o,r,t,y,-,t,w,o") + check("forty-two" .split(re"", 3) .join(",") == "f,o,rty-two") + check("split this string" .split(re" ") .join(",") == "split,this,string") + check("split this string" .split(re" ", 2) .join(",") == "split,this string") + check("try$this$string" .split(re"\$") .join(",") == "try,this,string") + check("try$this$string" .split(re"\$", 2) .join(",") == "try,this$string") + check("comma, separated, values" .split(re", ") .join("|") == "comma|separated|values") + check("comma, separated, values" .split(re", ", 2) .join("|") == "comma|separated, values") + check("Perl6::Camelia::Test" .split(re"::") .join(",") == "Perl6,Camelia,Test") + check("Perl6::Camelia::Test" .split(re"::", 2) .join(",") == "Perl6,Camelia::Test") + check("split,me,please" .split(re",") .join("|") == "split|me|please") + check("split,me,please" .split(re",", 2) .join("|") == "split|me,please") + check("Hello World Goodbye Mars".split(re"\s+") .join(",") == "Hello,World,Goodbye,Mars") + check("Hello World Goodbye Mars".split(re"\s+", 3).join(",") == "Hello,World,Goodbye Mars") + check("Hello test" .split(re"(\s+)") .join(",") == "Hello, ,test") + check("this will be split" .split(re" ") .join(",") == "this,will,be,split") + check("this will be split" .split(re" ", 3) .join(",") == "this,will,be split") + check("a.b" .split(re"\.") .join(",") == "a,b") + check("" .split(re"") .len == 0) + check(":" .split(re"") .len == 1) From a938d42334822b78d4f84417d066f0f059dcf8ec Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Mon, 19 Jan 2015 07:38:09 -0500 Subject: [PATCH 0083/1263] Fix maxsplit to conform to perl --- README.asciidoc | 5 +++-- src/nre.nim | 2 +- test/split.nim | 4 ++-- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/README.asciidoc b/README.asciidoc index dd7b78dc7..51f616b4e 100644 --- a/README.asciidoc +++ b/README.asciidoc @@ -63,8 +63,9 @@ Perl and Javascript use. `"123".split(r"") == @["1", "2", "3"]`. - If the pattern has a capture in it, it is added after the string split: `"12".split(re"(\d)") == @["", "1", "", "2", ""]`. - - If `maxsplit != -1`, then the string will only be split `maxsplit` times. - `"1.2.3".split(re"\.", maxsplit = 1) == @["1", "2.3"]` + - If `maxsplit != -1`, then the string will only be split `maxsplit - 1` + times. This means that there will be `maxsplit` strings in the output seq. + `"1.2.3".split(re"\.", maxsplit = 2) == @["1", "2.3"]` [[proc-replace]] ==== replace(string, Regex, sub): string diff --git a/src/nre.nim b/src/nre.nim index d907cae62..9e1a6a64e 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -417,7 +417,7 @@ proc split*(str: string, pattern: Regex, maxSplit = -1): seq[string] = # if there are captures, include them in the result result.add(cap) - if splits == maxSplit: + if splits == maxSplit - 1: break # last match: Each match takes the previous substring, diff --git a/test/split.nim b/test/split.nim index 9f9ebef36..6cd67df0a 100644 --- a/test/split.nim +++ b/test/split.nim @@ -13,8 +13,8 @@ suite "string splitting": check("12".split(re"(\d)") == @["", "1", "", "2", ""]) test "maxsplit": - check("123".split(re"", maxsplit = 1) == @["1", "23"]) - check("123".split(re"", maxsplit = 0) == @["123"]) + check("123".split(re"", maxsplit = 2) == @["1", "23"]) + check("123".split(re"", maxsplit = 1) == @["123"]) check("123".split(re"", maxsplit = -1) == @["1", "2", "3"]) test "perl split tests": From e91dd1d95604085ea3e59e2c15955bcf9f35f1e0 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Mon, 19 Jan 2015 07:49:00 -0500 Subject: [PATCH 0084/1263] Add more replace test cases --- test/replace.nim | 3 +++ 1 file changed, 3 insertions(+) diff --git a/test/replace.nim b/test/replace.nim index ff2c4a2b5..f2fad803d 100644 --- a/test/replace.nim +++ b/test/replace.nim @@ -11,3 +11,6 @@ suite "replace": check("123".replace(re"\d", "foo") == "foofoofoo") check("123".replace(re"(\d)", "$1$1") == "112233") check("123".replace(re"(\d)(\d)", "$1$2") == "123") + check("123".replace(re"(\d)(\d)", "$#$#") == "123") + check("123".replace(re"(?\d)(\d)", "$foo$#$#") == "1123") + check("123".replace(re"(?\d)(\d)", "${foo}$#$#") == "1123") From 31dfa97e3d55f68f468c12a2357eb16e8502da25 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Mon, 19 Jan 2015 08:26:32 -0500 Subject: [PATCH 0085/1263] Improve replacement performance --- src/nre.nim | 3 ++- src/private/util.nim | 47 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/src/nre.nim b/src/nre.nim index 2874d66b4..ffa4a6a6e 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -443,7 +443,8 @@ proc replace*(str: string, pattern: Regex, proc replace*(str: string, pattern: Regex, sub: string): string = return str.replace(pattern, proc (match: RegexMatch): string = - sub % match.captures.toSeq ) + # - 1 because the string numbers are 0-indexed + formatStr(sub, match.captures[name], match.captures[id - 1]) ) # }}} diff --git a/src/private/util.nim b/src/private/util.nim index afd90a485..5629e81e6 100644 --- a/src/private/util.nim +++ b/src/private/util.nim @@ -5,3 +5,50 @@ proc fget*[K, V](self: Table[K, V], key: K): V = return self[key] else: raise newException(KeyError, "Key does not exist in table: " & $key) + +const Ident = {'a'..'z', 'A'..'Z', '0'..'9', '_', '\128'..'\255'} +const StartIdent = Ident - {'0'..'9'} + +template formatStr*(howExpr, namegetter, idgetter: expr): expr = + let how = howExpr + result = newStringOfCap(how.len) + var i = 0 + var lastNum = 1 + + while i < how.len: + if how[i] != '$': + result.add(how[i]) + i += 1 + elif how[i + 1] == '$': + result.add('$') + i += 2 + elif how[i + 1] == '#': + var id {.inject.} = lastNum + result.add(idgetter) + lastNum += 1 + i += 2 + elif how[i + 1] in {'0'..'9'}: + i += 1 + var id {.inject.} = 0 + while i < how.len and how[i] in {'0'..'9'}: + id += (id * 10) + (ord(how[i]) - ord('0')) + i += 1 + result.add(idgetter) + lastNum = id + 1 + elif how[i + 1] in StartIdent: + i += 1 + var name {.inject.} = "" + while i < how.len and how[i] in Ident: + name.add(how[i]) + i += 1 + result.add(namegetter) + elif how[i + 1] == '{': + i += 2 + var name {.inject.} = "" + while i < how.len and how[i] != '}': + name.add(how[i]) + i += 1 + i += 1 + result.add(namegetter) + else: + raise newException(Exception, "Syntax error in format string at " & $i) From a929b4825ad5daca1c6b190c9aac37b27e0341cb Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Mon, 19 Jan 2015 10:16:40 -0500 Subject: [PATCH 0086/1263] Clarify replace() syntax --- README.asciidoc | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/README.asciidoc b/README.asciidoc index 51f616b4e..b7f0ba66f 100644 --- a/README.asciidoc +++ b/README.asciidoc @@ -75,9 +75,15 @@ Replaces each match of Regex in the string with `sub`. If `sub` is a `proc (RegexMatch): string`, then it is executed with each match and the return value is the replacement value. -If `sub` is a string, then each match is replaced with that string, where the -captures are accessable as `$1`, `$2`, and so on. A literal `$` can be added by -doubling up like so: `$$`. +If `sub` is a string, the syntax is as follows: + +- `$$` - literal `$` +- `$123` - capture number `123` +- `$foo` - named capture `foo` +- `${foo}` - same as above +- `$1$#` - first and second captures +- `$#` - first capture +- `$0` - full match [[proc-escapere]] ==== escapeRe(string): string From 6bd36602388e2cb6b209445a873dff29b13b3e66 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Mon, 19 Jan 2015 12:07:16 -0500 Subject: [PATCH 0087/1263] Bump version --- nre.nimble | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nre.nimble b/nre.nimble index cad375a9a..7dabdfd8a 100644 --- a/nre.nimble +++ b/nre.nimble @@ -1,7 +1,7 @@ [Package] name = "nre" author = "Flaviu Tamas" -version = "0.1.0" +version = "0.2.0" description = "Yet another PCRE library" license = "MIT" srcDir = "src" From a5693675fb36588b12033d3768d41b4c63d31c4b Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Mon, 19 Jan 2015 15:22:02 -0500 Subject: [PATCH 0088/1263] Remove findAll, rename findAllStr to findAll --- README.asciidoc | 3 +-- src/nre.nim | 5 +---- test/find.nim | 15 +++++++-------- 3 files changed, 9 insertions(+), 14 deletions(-) diff --git a/README.asciidoc b/README.asciidoc index b7f0ba66f..841943fae 100644 --- a/README.asciidoc +++ b/README.asciidoc @@ -50,8 +50,7 @@ Arguments are the same as link:#proc-find[`find(...)`] Variants: - - `proc findAll(...)` returns a `seq[RegexMatch]` - - `proc findAllStr(...)` returns a `seq[string]` + - `proc findAll(...)` returns a `seq[string]` [[proc-split]] ==== split(string, Regex, maxsplit = -1): seq[string] diff --git a/src/nre.nim b/src/nre.nim index ffa4a6a6e..6c5a1ab35 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -372,10 +372,7 @@ proc find*(str: string, pattern: Regex, start = 0, endpos = -1): RegexMatch = ## if `endpos == -1`, then `endpos = str.len` return str.matchImpl(pattern, start, endpos, 0) -proc findAll*(str: string, pattern: Regex, start = 0, endpos = -1): seq[RegexMatch] = - accumulateResult(str.findIter(pattern, start, endpos)) - -proc findAllStr*(str: string, pattern: Regex, start = 0, endpos = -1): seq[string] = +proc findAll*(str: string, pattern: Regex, start = 0, endpos = -1): seq[string] = result = @[] for match in str.findIter(pattern, start, endpos): result.add(match.match) diff --git a/test/find.nim b/test/find.nim index ddbfcdfdb..d8df958f9 100644 --- a/test/find.nim +++ b/test/find.nim @@ -1,22 +1,21 @@ -import unittest -include nre +import unittest, sequtils, nre suite "find": test "find text": check("3213a".find(re"[a-z]").match == "a") - check("1 2 3 4 5 6 7 8 ".findAll(re" ").map( + check(toSeq(findIter("1 2 3 4 5 6 7 8 ", re" ")).map( proc (a: RegexMatch): string = a.match ) == @[" ", " ", " ", " ", " ", " ", " ", " "]) test "find bounds": - check("1 2 3 4 5 ".findAll(re" ").map( + check(toSeq(findIter("1 2 3 4 5 ", re" ")).map( proc (a: RegexMatch): Slice[int] = a.matchBounds ) == @[1..2, 3..4, 5..6, 7..8, 9..10]) test "overlapping find": - check("222".findAllStr(re"22") == @["22"]) - check("2222".findAllStr(re"22") == @["22", "22"]) + check("222".findAll(re"22") == @["22"]) + check("2222".findAll(re"22") == @["22", "22"]) test "len 0 find": - check("".findAllStr(re"\ ") == newSeq[string]()) - check("".findAllStr(re"") == @[""]) + check("".findAll(re"\ ") == newSeq[string]()) + check("".findAll(re"") == @[""]) From f34a7dc1f5829713b0d076f5d182df6f4beb1761 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Mon, 19 Jan 2015 15:59:45 -0500 Subject: [PATCH 0089/1263] Make replace a template Also required me to fix a name conflict with the format template --- src/nre.nim | 21 ++++++++++++++------- src/private/util.nim | 15 ++++++++------- 2 files changed, 22 insertions(+), 14 deletions(-) diff --git a/src/nre.nim b/src/nre.nim index 6c5a1ab35..e56194fd6 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -423,25 +423,32 @@ proc split*(str: string, pattern: Regex, maxSplit = -1): seq[string] = # This handles "2" result.add(str.substr(bounds.b, str.len - 1)) -proc replace*(str: string, pattern: Regex, - subproc: proc (match: RegexMatch): string): string = +template replaceImpl(str: string, pattern: Regex, + replacement: expr): stmt {.immediate, dirty.} = # XXX seems very similar to split, maybe I can reduce code duplication # somehow? result = "" var lastIdx = 0 - for match in str.findIter(pattern): + for match {.inject.} in str.findIter(pattern): let bounds = match.matchBounds result.add(str.substr(lastIdx, bounds.a - 1)) - result.add(subproc(match)) + let nextVal = replacement + assert(nextVal != nil) + result.add(nextVal) lastIdx = bounds.b result.add(str.substr(lastIdx, str.len - 1)) + return result + +proc replace*(str: string, pattern: Regex, + subproc: proc (match: RegexMatch): string): string = + replaceImpl(str, pattern, subproc(match)) proc replace*(str: string, pattern: Regex, sub: string): string = - return str.replace(pattern, proc (match: RegexMatch): string = - # - 1 because the string numbers are 0-indexed - formatStr(sub, match.captures[name], match.captures[id - 1]) ) + # - 1 because the string numbers are 0-indexed + replaceImpl(str, pattern, + formatStr(sub, match.captures[name], match.captures[id - 1])) # }}} diff --git a/src/private/util.nim b/src/private/util.nim index 5629e81e6..72be023b2 100644 --- a/src/private/util.nim +++ b/src/private/util.nim @@ -11,20 +11,20 @@ const StartIdent = Ident - {'0'..'9'} template formatStr*(howExpr, namegetter, idgetter: expr): expr = let how = howExpr - result = newStringOfCap(how.len) + var val = newStringOfCap(how.len) var i = 0 var lastNum = 1 while i < how.len: if how[i] != '$': - result.add(how[i]) + val.add(how[i]) i += 1 elif how[i + 1] == '$': - result.add('$') + val.add('$') i += 2 elif how[i + 1] == '#': var id {.inject.} = lastNum - result.add(idgetter) + val.add(idgetter) lastNum += 1 i += 2 elif how[i + 1] in {'0'..'9'}: @@ -33,7 +33,7 @@ template formatStr*(howExpr, namegetter, idgetter: expr): expr = while i < how.len and how[i] in {'0'..'9'}: id += (id * 10) + (ord(how[i]) - ord('0')) i += 1 - result.add(idgetter) + val.add(idgetter) lastNum = id + 1 elif how[i + 1] in StartIdent: i += 1 @@ -41,7 +41,7 @@ template formatStr*(howExpr, namegetter, idgetter: expr): expr = while i < how.len and how[i] in Ident: name.add(how[i]) i += 1 - result.add(namegetter) + val.add(namegetter) elif how[i + 1] == '{': i += 2 var name {.inject.} = "" @@ -49,6 +49,7 @@ template formatStr*(howExpr, namegetter, idgetter: expr): expr = name.add(how[i]) i += 1 i += 1 - result.add(namegetter) + val.add(namegetter) else: raise newException(Exception, "Syntax error in format string at " & $i) + val From 78afa73e01cbae7925ee3800f0d51a5bf3ea70f5 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Mon, 19 Jan 2015 16:02:35 -0500 Subject: [PATCH 0090/1263] Add replace(proc(string): string) --- README.asciidoc | 3 +++ src/nre.nim | 4 ++++ 2 files changed, 7 insertions(+) diff --git a/README.asciidoc b/README.asciidoc index 841943fae..d51cc017b 100644 --- a/README.asciidoc +++ b/README.asciidoc @@ -74,6 +74,9 @@ Replaces each match of Regex in the string with `sub`. If `sub` is a `proc (RegexMatch): string`, then it is executed with each match and the return value is the replacement value. +If `sub` is a `proc (string): string`, then it is executed with the full text +of the match and and the return value is the replacement value. + If `sub` is a string, the syntax is as follows: - `$$` - literal `$` diff --git a/src/nre.nim b/src/nre.nim index e56194fd6..c0c286b0d 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -445,6 +445,10 @@ proc replace*(str: string, pattern: Regex, subproc: proc (match: RegexMatch): string): string = replaceImpl(str, pattern, subproc(match)) +proc replace*(str: string, pattern: Regex, + subproc: proc (match: string): string): string = + replaceImpl(str, pattern, subproc(match.match)) + proc replace*(str: string, pattern: Regex, sub: string): string = # - 1 because the string numbers are 0-indexed replaceImpl(str, pattern, From 5ae3010e5acff9be58cf4c9e2d5cf5ec129dae8c Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Mon, 19 Jan 2015 16:02:51 -0500 Subject: [PATCH 0091/1263] Clarify replace(...)'s behavior on nil --- README.asciidoc | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.asciidoc b/README.asciidoc index d51cc017b..f5ee91fb5 100644 --- a/README.asciidoc +++ b/README.asciidoc @@ -69,7 +69,8 @@ Perl and Javascript use. [[proc-replace]] ==== replace(string, Regex, sub): string -Replaces each match of Regex in the string with `sub`. +Replaces each match of Regex in the string with `sub`, which should never be +or return `nil`. If `sub` is a `proc (RegexMatch): string`, then it is executed with each match and the return value is the replacement value. From b5f3a662c51ff218bd531f2387bdca58f26ea0b2 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Mon, 19 Jan 2015 16:03:32 -0500 Subject: [PATCH 0092/1263] Bump version number --- nre.nimble | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nre.nimble b/nre.nimble index 7dabdfd8a..3d368cb36 100644 --- a/nre.nimble +++ b/nre.nimble @@ -1,7 +1,7 @@ [Package] name = "nre" author = "Flaviu Tamas" -version = "0.2.0" +version = "0.3.0" description = "Yet another PCRE library" license = "MIT" srcDir = "src" From eb2fd618fe863204c83553c5e5c7c2fe972e7328 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Mon, 19 Jan 2015 16:16:06 -0500 Subject: [PATCH 0093/1263] Fix accidental negative bounds See Araq/Nim #1979 for context --- src/nre.nim | 2 +- test/find.nim | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/nre.nim b/src/nre.nim index c0c286b0d..8bec3d990 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -116,7 +116,7 @@ proc `[]`*(pattern: Captures, i: int): string = # capture count, plus the entire string pattern.matchCache = newSeq[string](pattern.pattern.captureCount + 1) if pattern.matchCache[i + 1] == nil: - pattern.matchCache[i + 1] = pattern.str[bounds.a .. bounds.b-1] + pattern.matchCache[i + 1] = pattern.str.substr(bounds.a, bounds.b-1) return pattern.matchCache[i + 1] else: return nil diff --git a/test/find.nim b/test/find.nim index d8df958f9..f4f72c778 100644 --- a/test/find.nim +++ b/test/find.nim @@ -19,3 +19,4 @@ suite "find": test "len 0 find": check("".findAll(re"\ ") == newSeq[string]()) check("".findAll(re"") == @[""]) + check("word word".findAll(nre.re"\b") == @["", "", "", ""]) From f6b6a429ff1c1852b029e9bf16dbb9e12e103b3f Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Mon, 19 Jan 2015 16:40:32 -0500 Subject: [PATCH 0094/1263] Bump version number --- nre.nimble | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nre.nimble b/nre.nimble index 3d368cb36..ea83286c2 100644 --- a/nre.nimble +++ b/nre.nimble @@ -1,7 +1,7 @@ [Package] name = "nre" author = "Flaviu Tamas" -version = "0.3.0" +version = "0.3.1" description = "Yet another PCRE library" license = "MIT" srcDir = "src" From 7c24290eec2395432b181f3592a578f3c012c095 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Tue, 20 Jan 2015 18:14:24 -0500 Subject: [PATCH 0095/1263] Enable UTF and UCP support in PCRE --- src/private/pcre_src/config.h | 4 ++-- test/misc.nim | 5 +++++ test/testall.nim | 1 + 3 files changed, 8 insertions(+), 2 deletions(-) create mode 100644 test/misc.nim diff --git a/src/private/pcre_src/config.h b/src/private/pcre_src/config.h index aa1a530c4..55c8a27c2 100644 --- a/src/private/pcre_src/config.h +++ b/src/private/pcre_src/config.h @@ -324,13 +324,13 @@ sure both macros are undefined; an emulation function will then be used. */ /* #undef SUPPORT_PCREGREP_JIT */ /* Define to any value to enable support for Unicode properties. */ -/* #undef SUPPORT_UCP */ +#define SUPPORT_UCP /* Define to any value to enable support for the UTF-8/16/32 Unicode encoding. This will work even in an EBCDIC environment, but it is incompatible with the EBCDIC macro. That is, PCRE can support *either* EBCDIC code *or* ASCII/UTF-8/16/32, but not both at once. */ -/* #undef SUPPORT_UTF */ +#define SUPPORT_UTF /* Define to any value for valgrind support to find invalid memory reads. */ /* #undef SUPPORT_VALGRIND */ diff --git a/test/misc.nim b/test/misc.nim new file mode 100644 index 000000000..529ea342e --- /dev/null +++ b/test/misc.nim @@ -0,0 +1,5 @@ +import unittest, nre + +suite "Misc tests": + test "unicode": + check("".find(re("", "8")).match == "") diff --git a/test/testall.nim b/test/testall.nim index 7b11fbb91..f7fe8892a 100644 --- a/test/testall.nim +++ b/test/testall.nim @@ -6,3 +6,4 @@ import split import match import replace import escape +import misc From 256435e8e3c0ff3f3d0837ef5d899ba16446c6c9 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Tue, 20 Jan 2015 18:23:54 -0500 Subject: [PATCH 0096/1263] Fix incorrect property check --- src/nre.nim | 2 +- test/misc.nim | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/nre.nim b/src/nre.nim index 8bec3d990..47e374978 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -327,7 +327,7 @@ proc match*(str: string, pattern: Regex, start = 0, endpos = -1): RegexMatch = iterator findIter*(str: string, pattern: Regex, start = 0, endpos = -1): RegexMatch = # see pcredemo for explaination let matchesCrLf = pattern.matchesCrLf() - let unicode = bool(getinfo[cint](pattern, pcre.INFO_OPTIONS) and pcre.UTF8) + let unicode = (getinfo[cint](pattern, pcre.INFO_OPTIONS) and pcre.UTF8) > 0 let endpos = if endpos == -1: str.len else: endpos var offset = start diff --git a/test/misc.nim b/test/misc.nim index 529ea342e..0b46a393b 100644 --- a/test/misc.nim +++ b/test/misc.nim @@ -3,3 +3,5 @@ import unittest, nre suite "Misc tests": test "unicode": check("".find(re("", "8")).match == "") + check("перевірка".replace(re(r"\w", "uW"), "") == "") + From 91233dfab9d3d81ec85c476494efcb9b9d8d8ddf Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Tue, 20 Jan 2015 20:12:20 -0500 Subject: [PATCH 0097/1263] Elaborate on UCP --- README.asciidoc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.asciidoc b/README.asciidoc index f5ee91fb5..c4d97f8c3 100644 --- a/README.asciidoc +++ b/README.asciidoc @@ -147,7 +147,7 @@ Represents the pattern that things are matched against, constructed with - `U` - expressions are not greedy by default. `?` can be added to a qualifier to make it greedy. - `u` - same as `8` - - `W` - Unicode character properties + - `W` - Unicode character properties; `\w` matches `к`. - `X` - "Extra", character escapes without special meaning (`\w` vs. `\a`) are errors - `x` - extended, comments (`#`) and newlines are ignored (extended) From 1a76edbe021c8b593083ee9e235d584d271e18cd Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Tue, 20 Jan 2015 21:04:24 -0500 Subject: [PATCH 0098/1263] Add dynlib option --- README.asciidoc | 7 +++++ src/private/pcre.nim | 67 ++++++++++++++++++++++++++------------------ 2 files changed, 47 insertions(+), 27 deletions(-) diff --git a/README.asciidoc b/README.asciidoc index c4d97f8c3..a48fefdb9 100644 --- a/README.asciidoc +++ b/README.asciidoc @@ -168,3 +168,10 @@ ____ - `` - `\R` matches any unicode newline - `` - Javascript compatibility - `` - turn off studying; study is enabled by deafault + +== Other Notes + +By default, NRE compiles it's own PCRE. If this is undesirable, pass +`-d:pcreDynlib` to use whatever dynamic library is available on the system. +This may have unexpected consequences if the dynamic library doesn't have +certain features enabled. diff --git a/src/private/pcre.nim b/src/private/pcre.nim index 008013592..89bd5c58c 100644 --- a/src/private/pcre.nim +++ b/src/private/pcre.nim @@ -1,28 +1,42 @@ -{. passC: "-DHAVE_CONFIG_H", passC: "-I private/pcre_src", - passL: "-I private/pcre_src" .} -{. compile: "private/pcre_src/pcre_byte_order.c" .} -{. compile: "private/pcre_src/pcre_compile.c" .} -{. compile: "private/pcre_src/pcre_config.c" .} -{. compile: "private/pcre_src/pcre_dfa_exec.c" .} -{. compile: "private/pcre_src/pcre_exec.c" .} -{. compile: "private/pcre_src/pcre_fullinfo.c" .} -{. compile: "private/pcre_src/pcre_get.c" .} -{. compile: "private/pcre_src/pcre_globals.c" .} -{. compile: "private/pcre_src/pcre_jit_compile.c" .} -{. compile: "private/pcre_src/pcre_maketables.c" .} -{. compile: "private/pcre_src/pcre_newline.c" .} -{. compile: "private/pcre_src/pcre_ord2utf8.c" .} -{. compile: "private/pcre_src/pcre_refcount.c" .} -{. compile: "private/pcre_src/pcre_string_utils.c" .} -{. compile: "private/pcre_src/pcre_study.c" .} -{. compile: "private/pcre_src/pcre_tables.c" .} -{. compile: "private/pcre_src/pcre_ucd.c" .} -{. compile: "private/pcre_src/pcre_valid_utf8.c" .} -{. compile: "private/pcre_src/pcre_version.c" .} -{. compile: "private/pcre_src/pcre_xclass.c" .} -{. compile: "private/pcre_src/pcre_chartables.c" .} +when defined(pcreDynlib): + const pcreHeader = "" + when not defined(pcreDll): + when hostOS == "windows": + const pcreDll = "pcre.dll" + elif hostOS == "macosx": + const pcreDll = "libpcre(.3|.1|).dylib" + else: + const pcreDll = "libpcre.so(.3|.1|)" + {.pragma: pcreImport, dynlib: pcreDll.} + else: + {.pragma: pcreImport, header: pcreHeader.} +else: + {. passC: "-DHAVE_CONFIG_H", passC: "-I private/pcre_src", + passL: "-I private/pcre_src" .} + {. compile: "private/pcre_src/pcre_byte_order.c" .} + {. compile: "private/pcre_src/pcre_compile.c" .} + {. compile: "private/pcre_src/pcre_config.c" .} + {. compile: "private/pcre_src/pcre_dfa_exec.c" .} + {. compile: "private/pcre_src/pcre_exec.c" .} + {. compile: "private/pcre_src/pcre_fullinfo.c" .} + {. compile: "private/pcre_src/pcre_get.c" .} + {. compile: "private/pcre_src/pcre_globals.c" .} + {. compile: "private/pcre_src/pcre_jit_compile.c" .} + {. compile: "private/pcre_src/pcre_maketables.c" .} + {. compile: "private/pcre_src/pcre_newline.c" .} + {. compile: "private/pcre_src/pcre_ord2utf8.c" .} + {. compile: "private/pcre_src/pcre_refcount.c" .} + {. compile: "private/pcre_src/pcre_string_utils.c" .} + {. compile: "private/pcre_src/pcre_study.c" .} + {. compile: "private/pcre_src/pcre_tables.c" .} + {. compile: "private/pcre_src/pcre_ucd.c" .} + {. compile: "private/pcre_src/pcre_valid_utf8.c" .} + {. compile: "private/pcre_src/pcre_version.c" .} + {. compile: "private/pcre_src/pcre_xclass.c" .} + {. compile: "private/pcre_src/pcre_chartables.c" .} -{.pragma: pcreImport, header: "".} + const pcreHeader = "pcre.h" + {.pragma: pcreImport, header: pcreHeader.} #************************************************ # Perl-Compatible Regular Expressions * @@ -329,7 +343,7 @@ type #remain compatible. type - ExtraData* {.importc: "pcre_extra", header: "".} = object + ExtraData* {.importc: "pcre_extra", header: "pcre.h".} = object flags* {.importc: "flags".}: culong # Bits for which fields are set study_data* {.importc: "study_data".}: pointer # Opaque data from pcre_study() match_limit* {.importc: "match_limit".}: culong # Maximum number of calls to match() @@ -346,7 +360,7 @@ type #without modification. type - callout_block* {.importc: "pcre_callout_block", header: "".} = object + callout_block* {.importc: "pcre_callout_block", header: pcreHeader.} = object version* {.importc: "version".}: cint # Identifies version of block # ------------------------ Version 0 ------------------------------- callout_number* {.importc: "callout_number".}: cint # Number compiled into pattern @@ -373,7 +387,6 @@ type #that is triggered by the (?) regex item. For Virtual Pascal, these definitions #have to take another form. -{.emit: "#include ".} proc malloc*(a2: csize): pointer {.cdecl, importc: "pcre_malloc", pcreImport.} proc free*(a2: pointer) {.cdecl, importc: "pcre_free", pcreImport.} proc stack_malloc*(a2: csize): pointer {.cdecl, importc: "pcre_stack_malloc", pcreImport.} From 9a7ec44d9648198da95e5aef1bfa1adf3c1daaa6 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Tue, 20 Jan 2015 21:05:52 -0500 Subject: [PATCH 0099/1263] Add logo --- README.asciidoc | 2 +- web/logo.png | Bin 0 -> 41667 bytes web/logo.svg | 1 + 3 files changed, 2 insertions(+), 1 deletion(-) create mode 100644 web/logo.png create mode 100644 web/logo.svg diff --git a/README.asciidoc b/README.asciidoc index a48fefdb9..d8cb6e096 100644 --- a/README.asciidoc +++ b/README.asciidoc @@ -1,4 +1,4 @@ -= NRE +image::web/logo.png["NRE Logo", width=auto, link="https://github.com/flaviut/nre"] == What is NRE? diff --git a/web/logo.png b/web/logo.png new file mode 100644 index 0000000000000000000000000000000000000000..ca41ec7b7261e2f8e4ae3675bf17591717b589b6 GIT binary patch literal 41667 zcmeEui96J7^!K!&hq7c#wrts#$kx~@VvxO%H8IwZiODh~*-P2?eJe}Wh+&XqC(3RN z*|JX7!C2mVdU}4>?>~62>%HE&u9iXH`@YXP_vd`h=bR~APe=U%`tj{QEmuYu4%i^xfR3(sEXQ(_fi&|zxL`fN@3 zz_$_DH;;k-XU_b*CPcetVt2y6i$Jl{r~xqhnRIAhH{8HeiPa|Fb3)TjFR+yJ&o2J` z?f?6gWQYHo(R}qM^nd&@?O?aNeV_Vpdp{P1jC;|sU5^wmA*Y3`5t zjba<0*OxF*&6_SawT$;8Of4{^he$jbMEf{}8bAKjgH#s`>vNj?3SuYg?Z4si{P`vC z?fJT(T7`gke3XHncgvxAmvN8JD0upxm%rKnM+gYy|0+0fW6u2R3u?Z?v3W1?uc0Bd)>`SvqTo;hrVx*)boFjLSmT~H$X(d#~UNSF>p=LRr>7@f-`}XI*L*eZy6j$pn zkZk(AGvaT`l32IAGVY! zK%)FcURb>Uu)kqmG>rVdajEBPVFLqBdOm;e1HylBOVtKm{bV91Vz_kCSlp*h-hh>W zrGVsf&r4>5e^syee*GXyI{<}*zw^HWHAwXuGa0wDVM&aH$GwJ|%cMN1Ga0taWtq>R zaHFx6WM;uG@Y~GT{`ma0NfRwXTIGU2)dCwk z@Ji>SzxkOh7A%+29wL)oEnN|C9QYJBndZUgox!zMIbT+ABe5Z6*}SqSpwv0y$EtjV z%lL3r@q(MB!NBl5ng;TsuhS9bhuli|f?-Kd4*Yt&>VBjmW2qdc^@HEzeaftbXM3mV zxLx<4nAz3$3mPZr^58+~?1+p5cROPcF}_aK7_{j44^Nx@>h%zJ&&_8kz?kmO_`Fa5 zOCGe-q&mV|nW1%W@fo)~Jci?099Fu{SC?{3`D|1>97RzTF)Mq+)+&uZ z2{S`B>!pI`#b2#Dp!mGAJl*OGOQBM7h^Jv!^eV-e*Se{7Nxx9iL;I{J9~2nai>Qn} z`=aiSJ#m_!d@L-qxK1NDr;rbrP#oJ|0@Tdv;Zbit-A4B2g6oZ1p6|*NNL@WP4MJ~Y z9ig+XnB4N0LY338q47{U20XC)VEy#-TjSBI?|gms=IN0IH_Rraj!J{Z_84$?+l4_8 z^LwC%)|N1J{pXuJ^n18@q#nJVV2GkU(A$0^c_&P&EaW7xHjywHRxsq*`tGhI<*6${1*_p2X63!PeYLVf`IM^XP> zc)E5~mv9d|Oz25onMLd9)@kSCGi;)tE*05_T6u46@l5n*TFIc+<~@b)XBsJ0O(2;e zuRxQV1 zL|1@$0_6W)A*;?$Y1q-NQB&OuZYac8yGIz`hQ{1a$g_+mY!73Du&DZjE?%XE2Ju5D58!~-%t_P_rc)62r#ebam!xKb9);$-C$ zadz>(c*99ZL3}Za07)_@1=r+{tuGT$$um``T5TE9{W>X|O>AoVl(RF&nj+@+j>|k9 z>;wYQbNKJ^;fKZq9(zTl>Lp43UAA*C(#-cZvU?Lf;p7E=mGhhET&BK#*VB6AK9aZR zPsWaZr^@o}X3Wez6aD?AGg#&eGIJ-mQC76E9KLZhay_jvVeL7o6!@2}gY>5Ib$->E z9oh8Q(59aSWA=NZhIco8SC$ws{(I@Y@nlc>N66I|vEO?eb<+<@I zz@fg%@b6|EClcL`fA<;Lm*SZ~z=wbNQ?WoGd`=+8vVirD9vzKEzsH!l&w)ekw|)q9 z{X~ifj2VQXEZdy>fQG`=ck$@V%2c$cd<{g58$6ul#BX{R=j-C|-32EK&Q2ff_HW7( zxQX0R4j5!Va{ka)Z~g;G6=kU-=4X7e)$~1M-R&4MaSg@6?nU z6@Do{{hViK3sabgmHPcN{(KRmGC#8q*q0fhz!!e_uzLdkjxyfPPZogoD`p)NuvZXd zx9-z4P5Lqan#{yo+YG6x<58U&EsUG=NKv^MjT>~&2VVG3jB4P zXws#|u^C6wlV{(YcTJl`gZkWB;V;co`DZkJ`NKYZ5yh!dryY!EdZo;7U%R7-SX-Vc zEd`67?Y5TTI2sJhv}h8?`sU!7v`gZ;jSfE%HdZ)U$FENysX%OR*!=5)=iDQy>_Wua zDD(%;PCnC%^)Kx##5Qx+)ypR0M!(OY$y6k^;h|l}>&>N{4!VT?4eX209rfmOUo+av ze7*MK!EFGCi=z0OXc#I$G#+mTLZ>D&*^`&iWb^=&7;&o&_%pr+*dg%4dqc@A@AimC zwb*a*EG}E%ab2HWRztBgO(*$#eN2A>r2Rj77h$9$PxK(N8zXH$#d=Ay0E9g*on0po z>_WT!Y9YTLS=HArbJ9%iW>2ktdx{hN%|luZ+>A4%qzP^h1j0u37vlsBtXB5s?VyI~ zktk%=?*jmjO_ToZzLH}0U|S5s>qf}l#EF0n^wAjIdO_yg#k!|EBT)SQbn*MX2YMJ+vB>O7(le${uK9Ru}~O5VawPo&H|X8yo3_H_{7%)8;njzkH?v)GYydxP z6vsky6~E&WI`WLeCh-px@=DS{6^~)l zpnp5@82;5a;8Ml6JkB`)M=kAtp+jx15a41ZbO;rLkJ@0Wa4+IBKo?67SNlHPe`Nu9 z+FB`fd?D^vlQ2zNWobo0_I>FKuXpUdc%jRrWbjzGrglx2@Nowos_8`bBGARJtG0d} zJ!dGIShk5hZEaI>`Psu6saA2TIdtyZE|DAN>|*#*D&t*HK=>4>I{6mgvJ0=&yKVuG z*7g=i_;9Xmkda9%w8tD=I*b>u`HhsG{M_4hs%pmYtZaU%Nx8SIj%+D<3C!*fi;T^n$(r|k1Tn?? z%pj9`#q7H#3+Pkv7u;Dv_D0+ttIKP6y!d&OB^~(jAMd-ry3QMcf1X?~UxDoVU^KD{ z>KtdCx)^!g*mVAzKl*=dGKiJ2{+=bx#G zq@@_kcpjxXCnz9&=Kmp59_>+e*>8&oWIhS#vg2s5w_byh$n7|&CK_%bU)7osGyE4j z8LOHGF1^>;b3G-YbVKS4BW}fK8pV?Mdf%1B&5&E#mnpvXgL0kCZZW@c-}1Tl5)+Kt z;Xl5LmzW+d2TSi$?St@ZfZGy#0K-Jcf~=zur*)kv=TVMar|XghYA0uN*zLNy(=5gp zZ2IeeSy*ja8OsbOy?KKcKzQoMCz9S@*WK-rZEc2X1^}36VO{47^;!K}DyScyZ z$vh(B>km^iOT=>sHU)q49^zlSQFf4L5yRo_;h;4!dplJZ8@+5|P;!PF)PoDkH}Kwz zRys|)?SEq9e>QuHVBlxpy_{XD)+oEb?a*37kj)4nyx3$>#F$arfxypbO4(TF#0{Ms z!U*R}P-Y5=MLXE1A~pOIiP(WA_*T4Uq1!h0^z2p*#ZZLn&Sxy(Pm_vqT8AF@PR84Gsoj(UBvKtVv7RI@&3yQd7+t0G?di<-Kl`H& z{tIEJMb;{_PnP|+m($Egk=+&V&b5(?ms((!f%PJOe%=R_fJ~-UqXUr!&H12C2}2a& zXWqmK;3N}6Suq<@KvjJR}s}ke>+uNq=u`eJygc3zS?HE&ro=g<2M%6X}^8c2(2=t zNQK09iUQCWPh`(nM$ejv2xacCGTS%caglZ!GtwVtB7ShzG#pLoR-5mx)w|n;;xlsN zJ(43>eK~xq@YIm@bt0C=GQ(?35^PEc9vuzJ%F=`OVM4%B`i?yl_U-4E9Hzd;!kNj% z6UPN&lb7WVjPON7@+W#pV}97447NB&5#3+kCXu=}92f&>VST6XIkz-cG_Ix`M6n?8P zPjR50l)zP4t&Tr$J7bOm3#c;1svL%q{m%pe0Lor3H9ty}`f%jqT;dps&)|_xdM%5} z-O8vXt^>O~Q~aCG&b{L#DENDECw|z)KDlng6mB*0?D)+TsTM%hz6w2Xzqct~U`15k z>Mm%SM$bFQ)qN9fEEeCzo|^szKuu_!)r24eti#RQonh7ZE2Al6W1Y27Z6y*u6qq}7 z@jdH)_tMDmT(7hip3+QU4ZWz*kfz|?m3y0YagVeSxl4ah@T{IaJnQFvG`rg-*of2T zd2GPw<}TjSq-yUTPIOk#X=c*Cz`~Q5e2-u07ud+Erl;rw#Y2x`;3xHUv;|Fr^wQux z3^eNg-A@g~*dRktQ{6+P>4H~h!?apcm7zrEW0WX>mR-xwKlm*Zzqepo@xJ(_?;_JK7DKGH};kzFWq^#;cd5xu$ zzH1M+9wre7KO{s>fxqzH8RtmXa)$@i{_TqejVtOqGevoLCabR76|0K{7AV9u7rO0^ zZy}MPh|VxzD+na~zq`8#3U9G4P_iP~!n^cLar|atO%+$o^%;my--IG%(}5*k9l9{L-7y_P1@`*7W;CuhGu3}bSLjy7D}2J0eVnKp`XsH0 zj6htMOIy5ClUb{bH3pmtq^keUIyXF3DE`D?8t+fjSvew&S>liEHbeW>?paG7ZTt`p z0E}jA7Co<_pj7S6*Nr;UV&qaRc>PWh;i&Tm@=ydGody;<_#GFSVPZaY@CqMQVQVhq z^{D@m@SlF#?=$~4yH0J4ek&Lw4mR?G%YD(U7`julRm8lujh!)66G+&%?VeZO4?UxN z^6O6tzUWTMCwCQf({^SAnaO-iJ*+DQYlaxQZVzPZUT=zzXP9a}ar7n@HBAL<#hqEg zc#}|H%LeBN>ita92Lr=PBxXH-$6)5m^4fQl%om-MDfVQ2X2KZ6+UDB7?Ku^dN!jvs zKima%8<^U}cYKL5q7ff;C5fYy6Z2uC!Hks1)n8yPe%<1M_SH@08z-7xUjdJ`yjEI3 z8)H}I)-YXQS|J#OF?%5fJp4YPJK&)0NSQdQCpPd4y||N>h8-mS$k!4ccLj;&N|Geh z*Qx$wW9rSG%e%()p3EVvyNogd!uRTLm+9Q|-tfk|#P5y#d+X15hO##^-ssfrox-u- z^teBC*r+88FWtp%+=&sh@B}5C76_gWVPF%nQVaj~v3pyQHt5tV4iP_im4^K~-{dms z9JtEIH7;fB)6lpkt&n`KZTVlQL7G+rX0&k^+`jN4AGgZa-V5yl`Rm03kD-`G3)FN>t-76J%TtQ-Q&>O=F z%AUElzoaw+2w65}vBX3oI16d(O0_;SuHY<2j6&V!SoeiB40K8Z33p#eiGC~v&hj?n z^0-F=K7>b~T?oH_BPV|V*vTSt)2Ksw+3^dkOg zRO^WoW;H{6mDpKw4Xp1E%AH=KCw_+GO;{bEH}c?k36eVka0 zl^-$w)I|53#}0lWW<2hsLFtFSZx~KEHcsx>DBltn?9FDK<#bBO^-g{}of)l+-7!YK}5rR?5rnLR}P9V?O`BtJF)eBCh{-~u))|K@@D-*=9 zMtxzq$FJZ49}4#c!GMm?6G7bm-ercFs#_)i?f4yHQ=Fe5j_*9L`0ZaF3)vfxK+RC& zF0|$Nj~}LEST$i;7{OalB&w2QbP}pvw%0mibYiY&Ka_a(^}ksFdR6#v@j!NPP}GH( zVY$T^`u$M|uat94waH-2KyBI4R`nB~FkM(z@)%W&<=bkr{fGJ3+;+>w$!R%7rmJDe zLz*eYhZ3LDf{yn;){-ecR6ZE5xSbnBRpv{iEaQYczw*q%y|n@GkZ;{$;v$(Flcx8! z>hwI%E`N@HAL*QcMcSVrnr6{=*-`zadmV9+0QFC6-_g+l66={JtS(4Mc)X0o zb`t0kR+QM>UnCof#Ctoq9{~xDIsxdaYe&vHM|$783PCvy`YM1PvLz&^^DZeIEm+^m zEleYa6~5-6&`KG*414p2L-)p_4<$QA9HkT$?8fc={*OTv^pq6}4>dxM6#_~hs|-#B zMd@zsufIu_*1BOfD4*NzG2e8b0@nJg;wSBim>s-d%g12Qu&c>`RoIpd0*ToMsH=k4 z=Kyf^SZ+}t$KE#Ab?{wA;YRfasPr1fkliMr2F%EKQpeBD%AeA$C?;UeY(-VQ)&>3}Uix+GT~;80Oxl%5@vLv1s!1GDPBG4Ij-9{9Vs} zkbmVOg&vIbMBII7SDZ_0&|zWHI2R2)7%?X~ji=5Q+jz#A8Pn+62FHmu+iv~%J#2`Q zZHOK=`JS*8Cx#($;12d-6rYk%gYtZ={p(;lM~^!6Y$j#Ed@ z(BLC3=S7mDPXls$q!sQ}o0q9s-!0#+)CYO~#1m-a_MZ;>B?1|0^cKcL5ThK^m&{EA z#zWLYWGv<0vj4M8Tb^-w%I9hjrOLw{pvZU?++c3p$lPwXT_=g11gw5hU&)Op_@JN_ ztH}ff+IMTp8JEWW{`3m7-fFt)we&1#QVtF}roQlzZAwlTTzW7cO26RKm#pC#<9bQ) zM(-*Ua1IBuuOiL#pGy}0{ss7`pjEFvPhylDgA`P2pQ_(jpedf}H|w2Do)IDC2AK(j z4y}>k$?>QAgJH>7z7U{c&e{U0-c@r|@yD)eU`1ZTT5|HhS1u4~9kvfltM+Clh{NV9 zz#kNYD1_`6q^{|oju=^z2q<+dVm#|qGGo)Nl-9^FV%jAuto;GgS`_{@aw{JCIMFis zx9h3x&VUaJ;tC7k7X00Pfv^$M`J{U-({pq+czY3s4}d5{#;`e>j&mH5cxb0GpJVBm9kq zk4h{;V`gVT^B^Q|4ZiCrRlLc5_7%TWv1FBU+;&7BYunq?)Hd+Nlreziaocfux{+ML zxf|o(KKI6q_pVy?lnf#0Az2+IZ}1OR(KGI#Go>gc`k-H8>WM_MSc&Oo7(S|XEWw3l zdy7_pkJKn$?@`GLa80rpZm19)zWxjSNb=K%jl)7v+5mPq3c9%6zLK{C*>iyKpC5cP z7}ne)CQ%j2tH`@_8mD;b`t3nu-bN>Qrfk)f$Ly!sq@|p%RW(IdYYjHRQf6z<-FyhA zlR{7RSjKI?%+rNAZKd6#EaE$g-VAcX$yUYsQJjLjC{u=BoJd_(Y(ci0+^Sqfv-Y6| z!Suza9M`t5%X;2#0F`((7vl-U5QFvvdRd zq`ahC4bN)c4gtJF;2b%lW>Rvx8=OYNM|DuMU%t&cB2Qd%+z}q&3crTC**qXoMc=#1 z+J)mfA%nfnh^3{?Eq3z<|U&X(J z9womO0W``Q5Ek#dfaa66WZn8lvMRP`l>_!hlk$g>y;_dWAWrjvGu$OQuvw}q8Sa&v zCmQ2#bx~{k=3v?Vk-eNeYz#)I#!G-9c3TWq+`Gyph3-MpLascsq};2aaVxUC^owex zZK1N>(DJ%zA26!rLn1}i6`)Hj?z_sReHU7+NVygG@oP%RLc&Lv-@s-lV?44~ zunBBtX%MuS*Xfd_(<)!(u%L8 z80c5YG_C6j%9W2&@YGpxkMFKJvvu;F@%0DQ>l~0mhWFQ#UQHSJb{T>Tl@Lp%c>UAE zY*J08ckt=mJ?@@WO&BX5O6Q^((<{!{ZQmG~GT(PXJ z|JvTReEDXj!C)kO7YV;V10{z{kF?%qU9h)suSJJuS?_#g9l)g*z&Ehkt{f=yJk>MRZ2D-Ag0y$$uT5_*U)dVkA z%rR;)%|PbvU@v@^N@}*x_Sqx2Vb7{>3`gwKN<7Ee)?dq)14QnRoU4DAryN^7&?81* zKLhz~kL~Dd&N!4!MwjfyeFRfU18UOUmhXW$@gWK;I4&Q zdsH;M5eg_g4CQluayuhAoqx$2X2n$O%n&IbvrY=~l3wI_NLD!*mg!i3N;r*Uf0WGP z>{s^(7;+iZMCO3RNbYsc7D!zWm~mr2(PsqISQ4wwEKSJ+Z(gj?JNUfZHUVNC&O9W7 zWs8~jLpEIHXZCk@R|FP?JpZRH>lU44)jl9*+k_Y)#YOEqTYRN5Rki!nEpygz(HM^C zZFX=G5wx`MVHdda+wFIGb{JoG?Wz33;aevoJ)bd;AdujV-_s%VRbtFLAhN28bk1+@ zo^4yN9G@581M$rtT2o$hTH+LF|D`5-jWxUW%JPhVD*Yp(C-nendiHzHPT*xGQ%>B+ z4kRdm1RkFkVqlR%>kT@=w19fy;n{_|Ky1g{)*J6}$==M|S|qyOlt?n|=u!G`xO|!O zA}|J(rupUQ zC7j{}vUNs8(9Lcl6k=j9P&0sRZP_jGT>z6of$Sduz_z`)8O&`1m({2@p44Y&;DTAn zRB@)5CgU%~aY&(61`T5t4oF)W>+DkI#|XY}K~R4k$&VRM8uP$$fwp06NB(EDVGDLQ zTU2I#J}fv5@Xy*TzXK-Rg-0x4-hq^8H?XJTQqCk}-eXw5+DIZF_S%H}IDN%oLfIB{ zpniY*x(`}o5S1msz0SQ_zk9+5Q;uWUN(;hy1?BnnzIrSt;o7r$14ams9Jpi$ZxUW| zgxMdsw!BOhUV=&aX5wif&0n59b@<-!s+-)a!`o5K%vwAvF$Pi0Onz{5IQN?=;ehr%8zjz2vNka{&wE#Dj;9} z_)NFn-XF9o{uGt@;WvXJQdRF`I1-+gE;6tsYw==j;H%h>M>Zh45u@_NVUjq--+=JJ ze6$Dg`>r=zP!INpd`|n`qKCL|0~enL`QnGeQ8DNv#NnelZCqWPtc~ye>N#IsU>>ri z)+{%cG&-?5cbX_KT~=aOizh!E|G7DAL4v&}W2295r(UuKflAL^j^ow!g4d|-^I`fo zu`hBxf;W+$J(xwJB9ezR>a_;dQMFet^{g7e`n7JfBB>hcGzJmynjgq>km)_rFx*tn z@9W_BrY1@}<;;Cr0})+yfv5m`3$cUAj@@Jo^tnNW;uy#1V@_U2(>9m;M(5rFm3W?74!Z^~WBPRl!|ld9<9DMz^}n-wR|G+Ondg;nTge! z2C;aKXR=y@LFa`bDjU9DbMZA-aQei8<=E4{GYt&s7K#D7$!d21%-KEiqgmv6{-jbC zOFzo>aZ}I5U8lsm8A;(U3bf2Pjb1>nC?;ap7oz-O2%isSOxUA71z|&rhNA)%JFPfB+-MFi`b;S} zH*RBCbFhA?`-73ab!M4L#ZuS#vtDY!2^ylsf@i<=I2dNt1pMkfuglro-MzhTUWZR`sbpT{N-D@YfjVl0+& z9UDf9tlbyhf@Ti}m_`Y{>Tv7(e>6fpN-!T0$Zq8DTKd{MS{16ULJB9nmd;=RV9r}W zL4at|1W}%P2xp90fBOX+lRt0OyJ`d$y(&cv%LAl?w5Y|tXn@XU+6!yv=xy3oN{F5x zkjnDF+!n}GCOV~QTb1~b&R-47Y7^QEen>V=FcsuH3oQWRb_5o*VDEO>389d$@} z%5LyXWAGMERDe>ntE{BFgA{Tdin5iD;W}bK>(#qOX$Q7}#v$8njhH`Z4}}WT>;bzU z?1_nKo@#eA+f>P_^-5<<9h?R0mnxaZgTc(xANjs#7!gEpU@#|ZTjJexa&mGWUbFr) zlIm(tcvrxyQ?Qt1(Zp>-7#(OrclW>rnqp4hrj)yE7;j}7$S4QN(s0pSy|7A#69hT(=a{0{1211KhK|Lv&BP@_`iE`NwNj<%y&P!X^z}v-O3KH-n6Qox;kjMks z>Pf&1gy)lE{lN9QNZfMLQ7&WX^h$Q$gj7bZ^tn0x!%-I5n2iySfqno znfA)BKMj2+!87~`z`m`FxQui;{$%&*NlBW=0?3(?3~6EK^TxpO zTq_>Yiy^gJTl^5nCFAo#&urlVB1^h{$SiA&4P4kyy*YD0RAoJZVe}|m{}Nora6g{m zl0oxE64w%wROCJg^H-vv$<)`QLek)R#8Wv&p$Ggy;2x9j9%XtZZ+h~e9{^>o&E-mS z5aq`i%^K9X@&pHqEON#?>oQuF-iS}Q?JbBw^Z^Zh9B9OCP6CPNR$=1{J!?2q%r>ses#%zv1-8Q1D6$kk!cI&_s2{z4 z4=#WVY>VcGPVCc~&0^}fdhwL8yM1*^I4*(nQqFPPcX90M*=B>}unFGBoG2hhcr8xq zpJchf;}3SGZxwH5;_WqWSQxa*NmESy+B{VLK6lArRA`B1o`QZ@{e^4<8S1HYbBLMf~Lx{&ypXt5R-3dZMK9QyDJG zW61Vw(BnEyJS2-~(GX)Cy%`*$vGW{H{;CuZ$V)YPS64g&8sxdvN+-3>4pt(;+s+WV@A|yDBr$U)Ox^si``%ss@!Kd_+^zcjKfOo!4P8VJ(18thm zVlY|Fdb2^PK6!EFcXEqAV>s9pEzP)(d|*{5Y6z1b1E8lx@1{_bY5 z;?ny43O-tJQvQ6O5vS=S)1XZxg4|9n&v>ww&qBa43bEdwhIq4o*+7nAaq`sSq;VR8 zU+Y2kp~cc{eSMHR9qeQodYayOd+XQ?2yvA7uhc70~=$B<_sSKJJ3bU_IY!Z*&;*4A>&s3w;R68m1zpbE_Nn|S5lh_qYLyrKujhE971 z?(cx9bwS((xrTSaXKGXK>cYcDK!%WTy<{YihKHrhLvIZ>#!Lx1rXbd5`|8x&5#faJ zpJ~1=@&p)cix+ioUsNapYX*u}99@#$&C$(ltNq9Xe&}KXILerO?FiyK-IKn@o_$C0 z2-m>PiO-W)1%F$WQN!VnV_c&dcCa34KVyy!2kZLkV$%^;;$LT80y~hWBTkAAoqG!7 zan$)qD37Nqpu`=EvQ@XPMZJ4t#7tbVfH_9}Am5#>P{uNkE?%Rx1@q>YK{aW}UUaUf zS5vM!N$oV@+U1_Fse@wO(jW~;i0u{RKzdf`W2WY>wFm|T;?FNm+V$00$t^~BIE~AX z%%l;kH;EA^p_{}U=Bj=ob@P`?*v*+E4*G+5tJl`Rxl(;~i3&ArvWt^Wi<9U$9Qnc> zm}x)Et)oYX_sHDf8t(C11ApnTvA#MQ`NfP)_UqAUh$kQl;yF$Bnquk|_}PVHx7nqH zx7bfZVzHQ~Zr0+zb;5r<-E(a&yZc7w?C$IU_@KoC-u{#udF6(Ro47H(n0OZ=C>EBi zb_SVyUq`G#xu+wR}}u-D>OL_x4k_|K_hS&kNA+6u;tnJ*uBr9?68Iw7azBk_EZiR{WJw1 z_9!lPn+Hafj>z=r^E{vy;$55sVI~}-W8lvhZd0vyzV*~|Bv9I#EvM5t9-mufKa3ri ztW0S3R{+CsfhdkMHxoRPvs_MmG(OIBHDgQP;26FzGV(h57Nw8;al<8}q-Q5wo$c(e zX*3_KrlF_gjeD3kX}aYJFY>tQ#_tk1Fz30Mz87dDDNU5wj5M_i)#gh%Nh#iIT zJbk7Jau2Ulf5YsJPc9 z0a&~E;I#78gZWyoee?G;0u336b<0KbteQZHDns6*Abiv#ca=eCI>MNNc%N&wS0354 zIT3Xj8(}>W9i$qMJN*JrfHVgkEn$lCz{j}&vCP>_2B4*J@12Mt7);v$LP2Txk$K$d zCMV^8+CqzBs9r|B=Aj{9z~$TUP-z4p$NCw+=sOKdP! zpxNe^=bg+#Ppb*?Es67{FQu8SK*?j0)p(Co46N~KEUhOR4}eL7@o%#{`r6b(e~Lvj zjOHiP%&@@%rlF@HS93+f8v_-?tr&&yrT-Y`p^($E(l3k8Ko!7*9^>fH&F5K^n-P?B zR1}*!sKWx#IeW`lIJN3tMf${}-erI-7uI6HM^jPOm1{i5K7DoAn7-KU^2NB^9et_d zT~PUKrsaJHc3nxE*OGd^B6*U2-4o1e1%J2d( zX8P%|+$m5JJk-nHD@}L`K+Y1!b@N*N_K_Li(GO&|{=39&E*zb}B1itX7u z7h_Z$^Yky}cc!r2KpKDW?Z>}~E*W@-F03y^XDr@FO`UM5jvyD9ENa*HGZsZOcayMn zxW4; qt9?1QsvWY!@fx<(q;^tqTk?(hpe+gMNTY6%{f2UXCazEN0h08_NFH=f3U zqT;Ks6vh8x_Q_ESWwjj1YP3+tL9)`%hj=l28RxBvh1FJFNY00sb(@%&8*Op*zkSY9 zZegU6Vh(AKoDVAL45#GgMhmI;PAvi{ZEso&u5eFvt`V$iU*X}@|GG6GG|Xk7Z!ilG z!q?+m*7sqmuG>=qCeU+NcPO|$>b%0pAGK*4Ni1#;W-#>qGh@$>_Z=HJdH|YiufMKTt`7eG>82 zTE7*pk#FAo>XJQY{kUTl1*F+9nh44bDIx9=Z@h9oJ1=zuVV2vYF-)O2J^!ZL2sI=& zs$=5>*S;hdTQide)%sZh@zYbaTxvXd;q~_ZY~x9G*x{?N^N#lN!OrQ3vSCoptXcc+ zyIcL@iG@0*%LTx_l6U$`Y8W)8p+O~M&Q--eFVzIC$(L=m5Gty?>=OE1)b$tH;bq@d zP=3)~;PTK0FfjhKQ&qKGX>2lvYNS2G(}Z`Jsqy~k8+@Mmof?9O>fC6XCw>f?&QC)G zhWTl#R*swM%&^ea_4uA-flbXfHtDKb^0iZOCA4K5oq<%;Hpz?@rau%KyCR+81-mND zG8F&o(g3i>qmS3B@XpOS^#h+%!ZgP7lityusk`!M_r`^hHI63$5q}2d-11YfGO&(z zWNIM1iRj?}h`2t@y*T+`jaK53wyGt*5m&%|*6`plUELk%7eN>1Xk%Y|sd!d<2Eo6W zEkK#=Tc70XMChVrA;^diuqvnqb!e;64Pc32_pqlFUXheM4_j7=m&*mV^>2ai$Q^KT zQ0mK+@vk6h`zbJ>)OI)zs7W{|MPnFG~YuaNgoS*I#!qA|9G zV=Gb|@q$7SskiQZtJ^6lG^W;3fg9y6K0dQin=}4vU>Nqwlz`BvtWdiaC5n#YxFET0PGy!tum7mxT1< zqz&D^;u_ocQGT#%Vs%ipF#af=dsB=1XMC>qd=u%~+=qKF?w@Xj?s8RLAF|&)V91FW zBS>585AyXeF&61#SEElqyUA6QBqnrzxV=~BE%3mGihfIt^6pfCE>u-`W6D@{?)JF6 zP78?4>f0*4>Wu^tnt_G~^mLuhp-Hz)RsH*XPfEPrdM!4dM1&m%dPNDE|4c*QB%QwK zmXQo`+W$#q`|2$@)jkdJ>%J%_Oa?oZmWb==3z~9hdd4Dcqp)Bbqid+`R(F%EW^gNX zsMN^NO5kZ>USapQCqED9eng~wmL5Nq^^>c@D$mikuP&Z@Gj&|PU}Iv6*gMYUo<=y% z<=(uv#%8#8VGRQLRurK>v>HTYT=K7?nxQp~TNUH8$SF#HB;;Fs29BF}E}g(H^g}@C z%Pqm86pYTJhn+6hK#KixMvW|$gCUyW80zq(N!+XbNo1ILDLdq@>{V`AAAGM;+?RlZ zGH#olhb{aKgv?>;z{F=wVQfFBuZ7FXE#7ws1=dECC=Jsc2)qZFr1ParNBr_oU*OVw z(5o@YPT<@~1C<~HG5zo0KBmx=`WLqS)1}|Ltr{HuZC&3O#0>|CKq&!kx2>tfk3rRv z_@gu2n`FShCW~oiIqawJ?)c-6bk=B-G7zpoVUs24k0=S@9eAhEW-V`gsOp^Y7t5Ps zTwb_-2(1~hC&&$;OJ(#9b&ISc<{H=3tu^Dkss0AAs zt?e!x?17`|fTM0&;ExuoZ&y>{k1Xl-X~03V-hJbs?%K%Juuem)+i`D-kzC4yKRUHW zE0?d#6kS+-JI%H!l|QBVS!V&Q((~xS`3WO$@wlYGcGG>JKHzE zzt^yq%gMbF-uiK%!3*R7S}O*|)l2lzRwL8{AxdTJ)|VL=$6HTU8pRz*rz{>loNO>t zJywIB)mf{1lzyxSZRedT1fQyX(CLm{kJ{?H0{sB)>u_pEYNHN4of=t|J_sh&pY-$Z zQoaFS-+Sb)+8#KbHTL2v1XAAr^Mw}r;4Q(w$tz4|+mlYvDKzObU!VNt_0lyuy8RNb zb7?6E*W|Eh7?oHMyU%2SkmxNzy)e29ZGCz*M^cS!*6CW(JL~-pVerW$ zPBk*t<1lP_kqGCBd$Jd#C)LdxU%FQGl^5i(QMT7jTB^suhj4%#pP!cj1f8h zT@r=cm{QJS&*?>3sfJYF)}9ergCsF~%42dbZ~XS5Gc9Gexfrn2DDD{ATym5gW(0!C zIu^0+vPKJ`MOrq*~gu>kkp6thd0Qs3MCo8 zzO|*U{7RiqiNwlF^o_m|n8#0zrxP$&xvd8Jt_4edJY#Knh$bAftkF7*5W^1A&1q4-4hB9o+L!x$b6gQdff%d=!GiIj$758r>=Dr6IZjeOhCS-Q%1h>VaUMI2oXJzZgLYaZd?ZA^T4Ci7M8j;NLYR&4iNAbuS?I zPBT3vA4{1Z8~_eKN*-GGx)&w#qwm|fZgoqb^b-Yyervb zQ2yhXZ$O#Xx$CPVs$a&bL+sV&tUlhJ-uA|GGDK4V%o_n&JDuLi~;70&OwIfUR00Ga)x{kCmUyx`1ojNz=VO3d!xm{WbP6j zs1Jo17`OdyK_QkunbshN(|e)APmEMCCG4j!_y&cgWwZa}4Fw0SzHP08GF2u2csuR+ zEGK08y0)s9`cHfF!PU>QmPI@osp;?ZB81?$#plxdSDd|aK0BDKj`Tf$e<7GYvRdl8 z(yv-DHMB9dW`#!p?{@WwZ`;S7`b@L)Zq z-1OPA42)ns6OM2qnT{Kf|7{Sov*99Nz5nmG6ER)6QhWt;dRbqL-n^}j`m5fXWY3F zBYTGSO82G$7932Lh1G}r#zt5WG^hc?I6I8Y>gp#%s+U+YBC{K_2Ul8f4g4*FBX4tW9~$)?b5#MBjT&hLMB z4QF=$E=HHi(-G1d-cx&rqu$+Y{@Yl)Q*JTO#&?~d^QbtHeJ3QW2z!xfPVe!vquhLZ ztK|@e*$FYs z*r{$Age=*Y5ZU)_?1k)OCwtb(HnI-J@;l>xKmY&ZaUb1B@|gGgbzbK@&-0w~e7#0F zV^N(e|(7e9Kq( zr%ss!_-5RLJbW)ESjSxv^27R5x~KS7Qv<7oTMn0=${lW&*8{H~ymVPq;{tNDkKwhs zG;e)&R{;te`SLYJ=+8*Koe@78ZS)l?3kZN8lDOCSjBcWBP??0(m#Ljw=*!5U4hAH$ zf=F-}q3R6WMx3|4{9b;X?}V_cFMiu>dueTyb9i|xH%CHPZoy7{uH4Oa?nIO?D%;hH za#+^&F6G_e^n}Co!-0#ftP0^N2vKW;ys~blFZBwlg$k%arMGC1Yhr$_i1X$82qUnr?sCfET$~W@JaPv}==1PouxK(r9`CA!LQMBz;$(4V zB#Ccz0|yZ2{V&IQ9}{`9R9HL8S-EDVcW$fEWjg)KtAyN~f7Pl`Y_1QUR8s{MXnxc`9(@U#x$`B{={AMD_e5 zb+fF&f`gy`VU-`T-M(86-2gUUxx)(dKf`5Zdl+8*1-O5ez9+>Rn{cN|Uv=!6TgF5- z!!A{roWfE0xj(z2SSn|U_JdXkY+jt?*SBB#kDk$Wt^Us2ULx0MoiBG-c*KgIteX{c zP}s55_59O%8T?O~eS_RnjVAz=2L9NRWSd*Kfj5^RvEmy(LCJ7kK+HqffGqt5a0Fgd zpH(2BwpdJcY-aiOVQ!h#LJC)AKxS{#RSworx5)EA#-J$GQy z4R{OS^iS%`?Q4tiMY)=&>Z3xPw3KV)bisY#k?I&9vr61jZsMrRB3k{a?0DAcCuK5{ zf4IdxJmv%Q3-Y5cO{ke<^%>C`4iqW<*3y=sMA!w)XR!h`)IopLBlg*wPr3bu(TAJm zKq{vnRah7Pbe(6hVutR-hRSJ{t6}6W2G6s(j`KAO0|(kUMyQF%JQY+uh86W+p&)Vg zgs-{q$UJWTOTKMLH8d}F+Zcy2k6YUl?)^^e?(^byB<;LgFp;5l-plG!|M5L2Vvg<^ zP8nNw>pb!0=JtK7)eqny?(T)bsQS2{zvZIA9n!X(@1a18f#UjSb#4u72-;i;?t;HeU4K44|R%2YC2{Y#^Xb{v=-e^ISq53|GDD z3lDytDYBrGI6!;&fjPtct|qy69#ZQybL$#(ZJjOc_`sZ;Ne}Lw^|qbOykZZ@kJXk_ z4W$J$iQIQ47ID>)NsS{sWmn|&lA)%A|F@QbWh6 zLfe~_={>wWCVndFDb$8lY6VlJwgQLyD9O5)_?iu))4!C&T{Y7@AUQoC+0Wv#DEP9= z|60-u^_hOPp^DXnp@EtK&4C`nBvavT;#DnO*Q;EiYC7KjkyzFOKE2ehuBoAY#McB; zy1~5*EoLM$xk~l9b|L}~02C?@ul*xKN&OMGw2!9KEfm6}b{u`!-_1-m)aTfh7|d&m zOee!%2-`<&Pzc(8R3D7rTj=o8%Um1Ccc9dE^;M*j#xrAXKQ->C^A5hHea2gSv+~%* zUAcFcK4|a!-Z-|v;h6jRSz(c_k+OE^=&N6&@5yPsZf5J7#DniRO&_bb+u9fmrp0g7 z+AVN=H59mPe2K<*B3`KLVIHaDxh?fRw7Lh@6~y*3c>a(eMdP)<#2B7};_m}xHyj^Q zh`Gtfk5nkUi@2rT?HBO9O(KSK3+FGJyMEuwDD#J9oWGs=!q#}Zw1$Pr-`e`?8+88e z2ov6^Qyrb^i(F8;_CJ-h&%(aPt|jKyKasVWezV4t1J73)x+Us0P;$TJ9024yP5^_P zeDoIuRPBXJmkYiEvs2D_2%@%Hx#8^&Mk%>>gFm>uheh9!q_yE7a{K^(;LO;qXdtTJ zStYg(m=!t9)Rh&8D4Gfg2$dG+_)+(G2X!O|@&Ui0h?+^;l%n;I^nZX$c@5wFeU-)E zy?Q3iyFr&$ia;XbwQX>b1rmE%k#p}e6kOv8CKV|sMXOT&)a2HS9q+C;q-v^B47MO6 z=_ajh9c2p_yxgtz>o?u!exasJ5gowc&7}?IFbh*N@zHa`uJ70u3oy|_bClbVhIoCB zwHlb4UN~2SJ{+AjJmQj{_IZJUot3%1vr~FEKIP9XgZjg* z?yZEPbmvu$%sz(NMIk!0rLf5m-o*$8bXWd-Ie0=CG#;ecih9 z_Y4JbhYnOw182sGOq*#-qSsPRfxi6ItGFMQe9^n5>& zF~4MEyM4H?+cg|2JT@QWXWYYlDm)nN zneZ1vv|$VV?qx9F<(ES9&vn<VfbW5s~H=?!7-|Gn)P$ zW^ZCX)l>wqQnWK;471>$p*%PuesZO)bHhZGIDkG3J?y)x|Hz2p?*~B5&e6euxN&g- z!3Ud!FncuoNBR3L?cZMr^?I^u0~PV9!V&>RVT?1US)u{FS}I2mGz+!GnOCMjV6(dJ zCp%0*sqpdPmD2mJ&D%nSuG}y%o=-@*x(7*}8M;KJEwZlF9#VR!>eJw{!U}Rw1S4*} z6%ZaelC_Ci!D;x{?fab^a@#4nY;p7K5>SWt3Av@31(%@Q<%ws95Qe$u-Z!n&w? z&09+w!InS<#h_GE=;c%R-ws07ZiJO_{Z$uGm`9(Sy!?xBV47RkVC325%K|u}ZPnk1 z6DhvKbgSp&|Nh{Wv};l|?V3uxs^gQ^Xi{aZ7O&r#f5N(+?bMZO0 zke&f_G~5v5koOMvb@LoTdTaOeVOm{VH?d!223BPQz?!vWDrXM4P=_QtT^qrz z@rty;+$VQx>86Fh8}<(|EZ}`zDAk`uO&>CHe)Wmk?fil(r%o)7^vQimi#eEk5B4xa zSzRKH6Je1tjIy_cX062EC*oR%=Dm-}TN-lex+(}-pXlL>)KkCex_Z~BB>dpB;_DUq zFErC|U$Op=&(bT<+i*JlF&>b7-UtwQg)IECN*Pt}n!;Ym2$Uat!_D4+Jr5o#VpuuM z&;|SH)#H7P+ny*l@XzOQ=#B6-TI@emkb9?nlIM_rPyKSMYlX>~qx8@oJZ0j0EZ#AH z5qF+Js4>%H^4IU_6Ts=FvX=O=U34giRUDvKfDJ8ShoA)i*};w`RLKgC!l4O7*`>=Z zvX*7Y1EO?5J93_@Z}2Q2sxeXp2NAb8{vC-Le(-aimdCwE(7O%ypP5B;^corjCUPrR zqYwXDEzhEEf31=&O4445pHX}DPui-x#jkY@5B;Sm>n`Fc9JefXa1AB~UtKdLe8;WFASu%jXsgItHkunRNcMZTVh z`3A)1*TtzA(#^D(cqZLiH{*@3HkljeP}8Oc3bvF^?hn$=Z{g!v!R`R0Ex8gR5PpaS zFGKF}n%P`N&x^_R9e;VU9L+@~>!Drq^>TRb_eHr)*1FCrV8tp@^fmRVI}EkoKW&Oo za2KVHz~ttIfPmoEYBgteH<3x4&a!5+?fA%MR=Yg^g20O4>OXTZ@X-H3Lr=j%-$S?V zf^*cL9XQ~5MxO>*=U?6a0%Mu@fFM9AY-6bAkY4z_#a3Jr`R=E=Ui`lplhMUn(b1#1 zTmLK^_jCSILX8}(FV5;BGO@AfDQwqtERH<;a9MglGxDERMRnLA5qVXE-NF`zQ-~9Z zDJQw%XUcxG2URbl-#zN~IVPw&ghT31T=FgLbg(?c%;HH{@~^xiZmOO38MY&Ea@a(z;uzBvIJ(kV7 zkoWTBTSbK-Hqx7x`{!?W1+?Xqqiz^%fVm!+e$3Pf(xW_H;P6YMUfqd+JBso%U32tM zzQ%i`pA^0PM7xbU3mmPdo!X=zh{La0pGWAE3u_Pdi{(PUQ5=>2Kt zFjZ6+mlYGJTXJ{8;ckt*>>(hd)!I&`qfZ!r7^l6#->>V#(41G8E9HcPg=sEtP{U3e z&uIBr;CQTMLB6O~=fz7opawac2>AtL1I?#%y)b^jAD{v5!Ba0N2iz{`8k_DW&o@b* z%SQD9+9f@vVZ%Y1!I+CvVFU|tL9Oz4oeRS~WuU+_62>jP8M(K%P_g{nGfjfrXBwQEIX~*BSRGm1J~+R89pSC z4FJ>g=8j`xY6B5*wyCdF^IWQaShjt-m>O#e)6$3i-@z4b&9h=WC445-4+l=v-`Z}j zj;Y#i4QwS@n0Dk5N-+I;TwBXj#=d*K@T8E_{}+n1+Li+TO9umTXW69@7g{@)?r06_ zDC|8RpP?i?lDam48S5O{5`3PW=`^fdXLpSbpDv;NRswLR;J9BGF+&k4oO?@Ij zPo1QH=HUKX*y zH}lsX{Z97Ay_5N)5qv(ibc}4cie(i>*QGuic9%(kg`1f8(@%o;t~=KEcwm3|ayzD! z%sp}7PQI~Ho`;!;38XkHl|Fb@MN4F2ssJGc`5DlhLbRU?5;AaBP37q6VXf#hVGYP? z6&Oid+Yh=zFp?18m{`YB2S)PQ;ka0G!Zk2|l)d!*l`{qAx;%>jINh551-@kWk znUVGAJY1)|7+lFX52>XV%k;{u%Kms%AZk5yL?Q0)i=u01zwOfnc9X$PAYptY?Wbtl zP+{10{$5;o7*7RF^B}&aw~`pZvHRnFS~f`(BRZ}$%r;ueUuJg;C2!=IaOX`Tx2KcC z%9}azfU0DxQHL2vN zpXA@ztFzYMa&uLv76Hx)7*u}mW`fRe)A_GO+=HhB#>H|h|sMJHWhi-(9i?|Utox?M@ zIdn23{>eS>aiIZYbCo+NeM>Rq@Bx4rPi)=3Gni&9UdTX~GPA@|M&4x;sQOlpQ@gXD zQ&*bUE|f8Be+y!-jE|Xc(k(|jwdp>9(Z&9E1iY}!pm;wwNO;qHA<;O_wT)DOL3C{v zzRTY1h~wVw?5|7dOoU!KaNEO-tXOS|zCpc1ob7EZgFKhLwC*>iZA76_7gg(p*RklV zf!}S;Y2_X;shGVa-=of-mfTz!nT1}n|0m7c@yv2 z%oBb`koGWU87(FiIo`d!o4xc{hsw1#IzS$k)>3OKu}m%S85T$@L^D%X;E3IhuVoY3f}U$%<( zz6FVob~61Wyf@~l3re*=H1nQ~@j#0%E+KI%c2~o7YL8*a9djXYW|aQxl~vVQD6ba+ z2O0(d7ne8V%Pvj?)e+J4uW$*5CBlK+&%@`r$PXru5zgx@{C&O0^<(Pv8^yvaftkBq zx!k)i(pja@X!m5QF)n%|?yjM6(FcWy&EvrFmpVGdOW-Wd+afsH7cK(Lq9E-1nP>cv z5MahNz%A@H$R-%VLY#Z%FzTVX{e%0^DaTe0zAMzU)Wa#k4u|{mutz@Y(E1FoJgk04 zjdHqekZ36yQuwDWN9!D!$`{4hGja-Q(k{AvZr|3K_aXoemg0coA|l(mHJ>67qN=L< zDS~tJ{A0%22)Fw-sVV1|?`Rr4NYgN0X!Q2Ynv+^YaX)k2vFd#YNHW#XyC$Wnf|Lg$ zn-I59vAsl(u_Sj8Ur#HP8O^xSdrZ&q?XBELK5knRx!p7`4cg_L=I#?G5C|nB=RO{2 z`^CX5Sf@O5v%Q=|2HkPdqDkl#- z@30Ya9$vW8MPFo2x`ojh#Vm1~JQomnz0a|2;tA?~b^MVg8!u6GtpgUYQ z7@6yRtPQ36bfZ6ewES183gzOm7ipz1@3zHwj}FO=y7;u5G?6_!P+%&fH)sFEZMgfd z?nY7q@S#&1qgt*z8fDA`!vW294w8|^OZUfZbt)?BqjKX)ZpxEy6m|AnncVxa zXN-lbxe>LGfBZqeOJh`GWr@W(kou{+*eT)dmGm+q6)SdMsb#8787#HD{T?M#zCFxc zmbw?|r6$DGI@K1(_(V^{r2_J}U(M)0?LN+@2(z?xvvm=zuQ6Z}`QQ!)Eni)aLG?Yi z*1pHBEg~@?3hEpC#f8DTFAZcHUAU!47RVRV&C+1%;sS*T9f>q{;mdfAQ9;+odp8&> z()XqqrJwyIjK_~>GCLUNI%BlvcONPj9MSlR9u0 zeF5er^pdwwKR;?pxf<^E=xuKQ8eYsTO6S7xjJ??s7A{#2^*=8?74qhx`l6Xh@(f%& z=lu!x;c1Ke(qY8sqdv&aL||8lg7+^!UN7_1^1ZD(=A<009Sc1&u*E^7UH!=Ht-h|Q zg9`OEYSuR|PaRXesPXre&9rRO>$mfw>95zheiXzW=6pv+%i9`a>&76LW28RC_ooFy zL*!@UiQg{9q-5!-l=Z1>hEW`k@w?uYCZbYtMaIMj^MH+%jps$0PRbXVzwDC(P48CP zHDJ@XAIzU-iDd~yK}(I#=^m}e^`IBJ$UlXQfFnz|-*X--!TOt|or?w00G|1C4AgyZ z7UBbTcX|Wq++|L+EmaD>c;YvU-@T>xg$8%gvDzPt>}{5i(40szas2Dv51=6egm_ZW z*Q`at#+-6=AMs6pGhM_Oqd?`Z2z~JI*YdEG&8sQYtHU3({XPSSN0|5mUHcrPxplqb z5e*9@q(O3rJy1Md6M{V=nl)<)<7hGcT5o5iy6YfOPqUoMBeK3ru`ar+L05Fv^yWpmA6T9+V!-JRo z3%l;>`&cr%K37(IdAhCT%a`*=m|CHxuXMe%KUcX2@eAWq8j(8)P0#O3jNlN@a4<0b z%UUumLTBTL0!yM#|BDAg4SDAepTQdMw(NM6uUhSuU+S;WK+z}n1~+i-{0b^|$I7L7 z{9wQIBQYq|`3Qi=Z*MgXDJaJe8xGzEkKdZObYtv|T)LA;psP%@&-3DpRnU z8K)CHAF(#>4mvxjt$5jv2m4(;n1q8*_++rKutM_(+8BK?zf+E!>gMroaqIK1<-7O& zPO^AlwwdX-)F-YzFLR9^q~Y$FrXFlxgW8x|Cs@;d74sHXm4EURwP2;-3LjA~NQ*L| zr?nAT79{lN>q`DH)&6eN+649DesB09q-rq?qY4-aX(>n3sDRPBg6TUAnNscP`V`CB;1Q$;Z5);sZ-{B)V!{%@#km=L%rU66^7NsXC&+tT2-BfK~8 zWHW!gwXTi*sIN3;2{V1C^I{rkSU{_T@N`Vr-w~=@tuMZdVL93l<`;~8tXkCFPfkKw=ipV!&*lgln!iCF$tFC%W>x8`NZGglx| z_|_rfV!+OHLZ2H>$oI{JL8GGTKMO$|R9dJBw!?hSlXcPU3ECgVuC&n(;zib#-)DNj zTLW|Sv0*a0uL{I0EWS{@muY*(e#?+Z6yn~Rn_Ao|7N=-CD~R34gf!oLP>P;Xl4kQ* zPzl|g?;|-!cA(YCG0kx}sl3}h`yO#)KS+jknKaWl$0gaLF%K5qbWngn;W6ZYhZDX( zdv?7H;m-!`bWlo3f$CInLa-uCW+^R8X;4rLV z_3PZSRcD^GD5^IcKHDS&7~e~S)B$)BK^s+zQA6hGqGLN?h=MTrD%>HN3_TiV)rf>U z$AR~ORYQFx5GGlCf$8r0OKZi_nj?GdK;uiDO{e~B(gwy^B~3?Cy{~{6d?%~Yl1mZN zP`xEbn&0GI?g*#k(WnO7FQ;Jbk#FjpLDP8>akWWdEH&}E~^r=+e->KP0`j|y7AEZ@qHiw<3pu!yRM^8 zXss}dR>#(wwT=;!a^=L(3oc#-BH$!2357VoxfC3XHcF&bl~-K=3|qK%pee2>XsvHo zv-YNcuHZt?U7%tIfjcg{uvJdS+NoDiAU6rS=9H}X5zmZwQ<|Ml+wTisv+7?bV)!aS-$1DFUjuoGjZjF?sX=l_z>y~^4z z7?PnV2zjF*@a0DaxCVCFYlQX(m#}o%My$6faadQkIm<43Jr+RdRjNx!y^9ld2ix%5?vcUgWGGOeQ~17;~lvRAv~isWK5JpiOmAmj9;P z$oldahF+DRf*N#vSY~9aW6~HLMiPJN=0xguIe4_(giFD=$p5@ZsBP*a6aX7u7!VYJ zzj+BMZsz6a&m5@X)6iG&7B-^4kuKsI2o;3KVJP4%W)yloxj*NQ`nCMO9TK!Zin(MQ z^_(ufT0GtGj&MUBJt+?gj<8|z+=U^x!f%B&Yv0v`W!j0jQZS}wun z6{IQlHszUHON+8%dH2Zd=l;1a7U<1gtstJ)a*-qbFxBfIENL<^3G2oRaX-r`EU@W` zo$Yu6jxWconp6xsCyFt7ySniPO^Q!S9l4v{<;!3-|IEou$vJQ{_1fTNI<|jhuCLsz zlI@UN0$E!$tBAN5#J2Mz+FMLV&rwG5QP6TcGpk}BsWT5+m#CXh5%rvDC!#83q`hx~ z6N!x1HvX7z`sUaF=`C`(VP&tJ;|X&cY!^fKd*^`Od(karps+zizhO6`^J8x&x zkAk?1d7sGVHK4$}T+yg~@ng04TwA9i)$*-Efk-sGU>vRBp{eoV&l0*?Wss#zKBqB_ zTLPIxf$L>8uc8y)nAgCuhBZl^ia)fZxsU{{dDI(wH`TndFEMp*5(`xU4SJK=9>a$q zzFyqVQcS)69woZ8>>nO;V@A#pPy||oEok*?v_k@_HF7~7PIh z7Np-T40PRB;yLP?BAZ1aIldZjgws;hwv68Qzkr-k9A-hlLGrKmJD^cDM&*vhiFPR} zC_3HCK@CdiDL7jbJfnb(6c_=lc7*_59zl8n_qvbz#CAd_x(nB=?LM?9K&ICb?tl3^U7dsYmRhE;_xYq2X?_2XCRy zqy$9qUzT9c)kcTGASi8`tRl)kau>4{hs_uhj_HAxcN(J;W*#( z2wmEE1krMo=1Jv0D?nih8qASj(I^!V%p$@gSW@BKM7c{^y&{)Ldsgga?q|R2P_X}+ zL9^GWGDpDPpQVf}625Cj7}GGVI+|AOR39y;1n$erFUX|q!&^&f%c)>yct_B0E73j) zYU1z;t}9(wdf4|__}eylWpArEA;CqIbAjG5t6AV|2NCRTAwTtJ-%vsG zV_-PMRa4rBy*jn%_P{@kC1cZpq#Z_c$@Y@Njmp7g9akztM?r*<7;_M*TMnmal$43H zN|XK)wgcA?pRGV>5D}S@bGhQrXPR%eOVK{;DnZ49E*zbW-}e9SlSDe{DIjNU;z^P= zH8b^WU{2ccO{*MQLPkHM;~XP+4?-v`b9 zNsz6<=Ko8PITaWHXoUWX-)4kS3gYv%eK`iUF#+q}$dPs;yOW3rl3O^Ilz3J5hj|DY6|-mq0E>f|tmAOG~tmsRj6F+RrxNhK8wqpHG#v&AZTJY3I5N zL2{Er*{A?hP*ziD0KVePOsJ{wc9o++R^srdL}~ds!*t*%W^$#YlRGf8{Etg0eshr( zK73Q$CKYUTss>rUHm*=!kEun|M8qe7tOLP1Uf;hhm2qg1N2Iq;ct zNTzbl7@`Ra?NlrcZax>%!b#tGFAnR;ug#CFqRpxh(E|j|^cJBF>vWFmgs3W=m;4LY zs1y$qlZbwbAfll3YZFz8g{4zSvs9qipo(^~r2YB+&YoD@NkrNe!zrlk7)+MdengGP z5pH+|3mMq`yZd_fWB7>u|j%~iUzVsy>yaL&IICqu`{pe7jT zaD4XgL?68ZD8Wsf(%L4eEQsei7Xk-$C5>i(((#RF&kU8^r7=4*X`0VS9ES1-z54)F zFS-jksc0Xr3zaypv+7XL8;rQ(&tiQSTB_wwT4N-W*u#IN4 z5hS=Y)K1MnKNS~7UcwvBXEH?7(o@WBteLU%w|`-0&BW_x4LQrw=?3m|D;he4ct-KZPG& zl-5U+`<)nq^=CGI+g(c&Ccs1h;n_=@vUwhX)40gxe?Z3e$A(DIfP-ZSgz#FPe-BOi zH5IXZJHP&9L4uc0S<9}Q&Fr&Aq9(!&&KZWdmlse#{KlvC>3PYpcb7lSgHF>t$fVk3 z?*tP8j{b<|A(xd%(FEH-=){y=fo5d$kr`XSc1d-1O%&57rG@dA#&C{Tk(C9;z_ghY z!vY7Q-MSLWtcy?d7TduB82)T{NvHi+jiBCTS{nE#x#J3Q6i1AS=RAa!BrOvO^w0yi zg|Zzt(s5pT3`vOjK}fmFcB%t-*EbNA#&+bCJll`TEgbF43C+rUARV}=KIHHT^6laA z1WPG#DE??mpp`NRlLnV6O>|{S%*5%Z4NG}c4`lO5mVF3=oYs z*Hl1A+BA_=!He50j*L4UD@LWb>eip-^%X_5H(7&T<_!q>I$;@gsj;RmrwD2Lv0J(y zyC{##NaKZ*UvpH^aGOc9Io)d+($G25kZi-!o9}VHe_v!pJbDF zk=_z`=UC~-GG=)xC-L;zb5gjd{pAFr$(7z#!hP_2^r&7?e!yA^#ArFUkV=cwW%y5 zY{qrX&j&o8KA{AbS&lbqfP$-KtEIDk<#sZN!vDXO1yS6!(IY&_cx>pAmnQ>VVlZLm zblvu9RWEm#HWAsQ0$5F&pZ`$@gC^G`pq7hAVE2GZd2nt$w*h|5MvitDU=#t;1 zS(v!}j68|Ci_?(=2|O)`KyW3Kv2RQnnlYn~Ebdewm-_}J&lTK9lkMRa49-KCX2~!t zaVHIblOL(a9C#&!=Kvx((Ehbvu;z9F#5{WZ?V_KIYdqM~p1RSy2J^Rc2zuH$hn4p~ z1l5^O<(jLk%Gr6o&wM8tp}U5=zi&~uebjUF;6Z}8zT_e z7q^-E1(9*50x`4)pR>2M&IAc(Q79#HXpI|3QT{3Y)bKGjsh`4wC`j<&EMM`1$v2?w z^qZk`$^3u=$@`4Te0jvnZu@WiH8`vP5Z@p#H|a$rh!oW5Pe)@EqA`0q=yjh4d9)G1 z?gFCvctswji(H@(IrL42E0k>r@ZSRDZQ5Mclfwwfi$P zA38Qlp)CNZRjH%|IL--AUZ-(GPsv{uqj3B$F~;ycoW}`3k=*4_f5Z8p!O3WTl!;A#rw(y!p6fki7&<5~+fkUKQ5D9=veUGvB#-1q;!DRJG zQlf|iI`rgGrp*&fjhE~HLbSXFD2{E1?w<4~!>A*36RsmI2ZVLGt}Ilb;Q?X}8KP8~ zL!M7pBA|IGc<&R4bRQFvS2+CL;E786yos>JZs*G3F;p&xE|Ma-_eh%B73-mFiHC`V zJ`}0)0@4dT30DL}*a;x2Ib0klPAF($!G{}xFtqsiC=PPU(?1m*f+X7D7EmtO-g|aU znoVS!9TEAfqciqmK-hZZ&dY^|Ms$!fH!}92MrI#syviwXWSI*N+UB=>zr(Z{g1(xsERs<~ z@9b`Be@vY1pJCd<|9zJP4__W2ue7onBR+rH-sxB@w*r|%C-K^+TiP%Z@a3Y#Fk)bz z%S^wf?C$wA=s|~8iR9ZL9)qF4B_P%Rz9Wo9E5O|WbJ5fkjI|g3=0zkoQ(*e1!~=-a z0{5|>`k+?htk`=t(|?6-ZbI=%_+eN%hsQVs=VLhEJ>ueCKbuG+K0R(A7W|*al(^Lr zR3G|v>)3u#=dxd0+=PMAC;WCk)?f0~JG?6pXSmzwyJYcm)T1E@Qm6#U8cT#8@)7hT z9dh{qlV*0*afJRi%Q7LyTX1QCzsi#m%4LuRt`2v2iTnTi?jo$-PHtB*e-VW+W05`Q z;kvW)&MF(aNHMVb^~x(A832z`k_`g?(*ht0XfsVjOZMogKpS9UJn3?i!g5Ao7&0A^ zz#fA+JEh1gNeTtCkfW)3`%eE6@A@3=u8c0V?>d0UAkaEu2}TrMSi4ik>O2dWW3v01K^~3+qDL+wK`s_? z_cgx!DHqS5{4b($GU%wtkb-hhlnCE(LZgv&!v)GT@uGO`KPOLJ)n_$iwV5Bm zO~{2BYZk5d_Gap)m8Qp1y;{%SeJOA>HJ02v=RjNx8IrHxA+P5Sr)_nw_~M!EC>$?# zn3i_KvQiT+k^R|hEdR9POT?2z(_<0BJ_#I5_4jHUnQWcW(QHg4G+KiwgfOYR;;iB^ z-Ww=??+1IKxzjSSW}+>o3j1QEroLEs|Qr&nFd#AV)ZaNB+_;vhc>! zBgX@H#$^BhJnyzWgHde&vzUEsD<5_?WCZfJACQtitSf7b{fc4YTQ?!7``Tz$Ic z(+Enp>ZjL%L!5|wRi1NoaW*?mh3poCeUsKsf=QQ@Dh$a^%8wCQRT;|^`o^dN-9VRAt$ymJO1tgdI%#t_$=V>M_wTC?>KUm~CIGLJ}FJ@Gv zxj2Pm!>|5q;X*hnEJjd9Ww%=D{O(T;31%BnyZM3UIFNt)6m7~r*Biz@B!_CO?6|4uV%__WT5>Y)WGjhUOtE7} zoveH=*%g;ZN>2I5D>y4Vi{a?1Uy4M`CdrO&CFu=38njg-hwi8fJq%t9ciE+2;Ok-J z#qJ&kHXqVyD5o0DChX7hlthlWx20EVQp=1&ypquFa_Ob)T2Nd0zTWRzt|O-VMb=q-%5)v(QgY9-kpw{e0iy`xEJH@{_BqjXhe^zJ#1r>vo%1w-ara93?D=& zGV(bHuuEmRjlH$xD~b**o9cNPG33^AqHOWz0w<=;*t&v#?FQczud2spe)u z!nJMIwp&%n^roy&TT4EwYIhlEU3u=z3%h_opSg^vE(lcHx{odwMkcSRwjrv=#EXY? zq|4@hE>4jh1_G>0<6qwC zE^V$iade34fV1!-qCsj~Wq1i$WGr#`FT~{96--;z*Zl4xaa_HnQ>B>w_~^^MX=4H^ za^{CLF3xrFw@BC|ykgR&S(-i9!S?Zecy(vH7hRejc~ic7W7$O>3v5M-n(I{!r zB7<+-HkD&LZ9Uiw;;`M-%W};dHpk1CENMHTON8&dO^yiZte^q8D-y2!{HWrRs#aCv z(!)tWt=IDae(&v_7R`>+K8K<_wJB1-CSqvjZy6(DV!+H z63vB^&_UWQ4CypOmlt31$(FAjy;u9e?am>DgriN23y}xspCxT$8wRM27Fx zGgk&IFc(N#eTSF0h~(&}N63Fx3+bG~C|3yL>UW(>OQ%)?UJ}NJU1k%l2wDtDsoj@k ziWbr}h#`S@(6tdU@_YI@#zaRl!)F5TDNgiVO7Tk#LB?VGdf_`BC0XG$lm%H|U3X_$!g`2k>1o|~v1 z(KP(mr1+=VPkg+(5>#(*He&4PbrJzn>R-0#Gt$MKeOfSonN^x@qB0l0!cu1YXaAh# zpmNsN9~n-SuI>tp?{VvTuk`k9Ct~UT2fph1_QRQP373?8@uS{&*$?>2mIp10DCBq? za(u6m^RMb%&7T9}*e8o;^>)T%%RDZExgyOJu^s>@9&29ISm(*U>58!^dM)Y?JMo3= zj(deu!Kf;?r5Zzaq7C{oi7a{26w9?UoG%s7A6<4Z+`UNUgm4vv4XB;nCtK5{LT|!1 zGfi;Grmutx63Xm;LTpqxEgrNab8C6@W~I9MVkjIIQwgGLmIuRJlkiB~F+_Fxb@0Bk zyh-YQ_`Uo~K65|CORjcjx9Og~DVaNy!N(^Sv$i>m>j^Db&qh_c zb(9(ouv+WDjivR9Remk##HW=m_QQGgykcDWxnlOKFKT( zIkmjvPjX;dS_krk$5-L;ea6bjstTqhVJ2I*hcjeY0f&^^RMzYuDb{7;E7qN)@mO&s z@u)5>J16Ze`rA}^d`=>5f@f4LHi7T9Z6comnar#S;Bq1T9uN`l!E(kSTT2#a0(9CP z#s$*{!pJSd2UE?~=??dBzuc#(#u#I!<#T7=nRbN>hIQ%*RPfRW6ke3DQ}b zSs3+;zvtG*QX3L&WGW#7Y$7pDJL!XA3^(RhY$Atx+yKLrJzj2aikJ?}oX$2fupHg; z5LrYn#vW!!J)L?cHGuI$cRih0H#XWH@Engf6Kv|KwCgK!5|kcfDf_P%E0#kCH~5ODe$ZlmR#!8Ho$=6UH6oLzFJsa9JJWFuawMkGhn)$6oYv-{o2tx{-~k7t@?M2U;FMXcQS*Y@~2Lu926P%;hJa zaax+-Olo=slm}p}r#B(#Ie$~(!_>lorv>VR3Yk6Y32Iitg-=lrt$K)RNdr$T(y^Zg z(xs>TEi_WC?8;Rw&sr&}-(&A-0vA4O*?qZ3v|p+tJVQ~G_sT?SZ>6P$-d^n1@9I}> zt|LZ~7H!m+a2Z-U5kDfdLwc9#W(af-u^vYA>^uBP&(Yf4OnpFgb;~85Il7?L^WNL0 ze2}YU8?WnPt_)Ut2-sqlx2~473*QP`xv|7K>a1rNTK)?jGa97xm>POhtnylADW%d( z_{qKL;ua?ZbK?9Vi)2C;qesP%4n z)cd)K1)jAf|FNxS6d;?v#Y$wI((G#;anw1K_J}AcBr1&iyDDAvw{sBJALOl+$^JYY zH!4ismO}ie25Gs7<8LS&!l%?8;_lVP$f<6B#c#BRWz{*QOZ;7k-%v)o3L#~p)Xp^y z9lT{?YM(W0S>!ddgaogZErvtY2aL6G(dLx(gIQ6C<7*&(%00>W@aZS3>(> zy@K2U1>ocgz_)c-0%i3pjY@K)Xf9>ZBYqVog%l-)$edzo<{2-=Z|F{6&>f^_S}JB* z@@2XvoMi9xaAxttX~ae@ZVe7TosE(A5XZ?2t#zA8tH~d0zPu8<^=rG>RS@8EbDv&P z7|NHZH0WV?4;#c`p!V=Fe^Oggh>$=2G0(Um(~{z}fUbG~eo?*_{!8UgGUiVjRpfV* zOezq@up_#|dfY_LHLv@_X<|tEwNqjAwk$hfRfWMv-49L~ScSq?5;~3laWc zcVau;=K1r8VyNr9Mx*WO+r3z|ciME4ic*IJ5tAKHECyFze-qzRkWU@ogKus7&=Z9E zb#-G7zoACPhxG@c5dMf!AG}^0=hAiDG=t|`;N+_4?MukrfP_n|^0hrowpM8Eb4*r} zgC^dmnN)uG-u=j}7w{#-LNgr^&hp#`ntW{9m>L?r89kxoC(t}xGuEM-_Q6&EkB z7OtfBFp6g!{<4&C$r(A`%4DmA);_~@<$7}Kg{TQW`JTlWDfl(( zvD=j?UTIn)BlEG$>u!4CC5=(ks~OqJ*kb~F2SBkpBIj_{1nhh<@OojF=qC8X#5@YHeRnt#K7a3R{&4+>&_ z$X<1<`?_aGRjRr+lCm~Q9&5iOr@HrPmwtDu+n;67t{CxA-a~;hy=V39hH?);;0f5? zU!Gq=u;|*>|7%1nZ^R|O%jX$y!H4?^`zy-T{=hr(B4d5~_qW;EGD<5Zk;h1n(O=S?+sc>5$vy0}r`78>NBdP3|6$upEgqWbeGRw5 z(NfFy5ERdHwU{MY6`f0RwaZ~y#!R-|SG0#UU+4{v;GgYvuC=I0TPyM_8NWQ}xnpNn zzr0X&!*O#h?o8>9j-j804VjBUnQ%!-ci5$uEqhjaqLJoRxhW205pG?_1=BKxgcZ$DM8iA{N@UCb3{+9)7XDv#*Z$PhmB-U%SAOV&bx=_t;NXsc zh=NdFG14w#wTK9cmhgyM#_}dWln@|1v?5}Kt(u@bU1<;^2?Yru1PnfEKwbhNJdzNL zB?uumypmJ{WWP!KFYL^EXEKw?H4U;0%luQlh~M!B9$KA++RjEme**O$BS?BmAHCbokoSQKUb8C?RBG0@VH z$oT3tnMJ3P_#l0+{!3(Al=!A-gPq&*Ryk(nh_dFM;q336)mp4iTin@AOt4+vcdmxjVnA+=p?eE9F7)v9no}4)aS9u)*jN9cVAiy(q421E z>wc~ZYf?HTI*Tym$Vd0y;jX8tUrxC_UZYL9Rd)lOewA2NXuQx#Ac-9@uZL|TA|ls+ zwtzAzQ(3_8k@4y&TbP<{)2w%DSmC4bi^k2_uecOrS~W$I|`}2%VNf& zDSm^;I2}d~oBYwvlGghdSJx2p$LqZyF!1RPbO{#NWImJ^SZih;C3}?l%pYsN(Lbg= zlrgQx0tq=#Hep7BjF+ZGxrsqg6P@KS`=n3u9sT3xZx7TU znIyfxOyxuhC2HZ(Gkc>Sb@4-rLfRSHK6}%|2 zt=WC^Vd`i2JH+`(yX=Q~esBKM6k}2B{z6A2{j3KOICr6vxWD6~As-nczIK<<2Crj$ zIEprl0i_R85W@)90shz^R+o)uzdy}@$`)whzvaf(q{}7vL$gBLDr4|syB3J)V@>6Q z^FDGyvQ^INIH)tz66agIk{;=EC#%@ID{JApfp>E6NI^2NPn1g~h%|8MX703J$vWhv zXAl<3Cbi1_O73jm)fb)}$sNIp9w{{-AehC9$1it%PKlAR?;r50;F;c$7CB5edp~I4 zB@Q?$Y^-u~78TFTs&vOMDje0qMQfG&t5eAKOuxZ03=6@oEE$5wE#LNA2>m>hVE{`@ zRrvwAuL@t7sSJWzep5_IZfpB`8&*AZg)9Dy!wL~2Gt?&!g61L~Yc8?OJz7fls3n12 zKgI+Kn$Zb9G|EMRaFK}@>$>8Cj(7b0oiU^FirwiBmS2T#s%rZ=Yn0Nc3IiT)hUz+Q z;A!BZw?Wz9Mhf^T$zx0V4?kB9j-_kXQdaBVRF#cikkCM27%UL`Z3%YY6fRFZ*h=|z zWcGp$PxDjpc|UGB6b%UY-wjM`ps;OaZl1=K?I36O-!d;3Eig;^2c;f{qN%BnG_7qo zWesMe1SiO15gS;c*bQ(ULhK*3Q2C9Bv)=mr!i;-myL)}dwZi4EUQ}apqLbc^Q`Acv zTY`T}me>Mz?uJyTeu$y5I)QM;$Z5QX(157k)THa_wm{&rHZQ^6E55#qos^)4Fwm)= z0v^6}cUdNzYbdmHX0A43`HJs#`zjyF?}pqCL3TqU`u=FdZ;*)I)3FI6{N$tWD2JcN z)=Vx7pUd-SL3v$z6B%6iVF#<3d=Y?s6AT~9)_RkI4R~1$9-&CTXTBHp?b=M ziGjg)87CYdLLXf*Mrg{o0cs4qjo_+(7@&sZHE>A7qDP9A{>&O5@^wp;2| z2_68wO~eK7h~Pt6c|Ud$t48kXg89n zS#Z{C-kTFi);|<~Tui>F;_S=WNiuC@cAl=U9&XCkIih(W9*RC2rW58X(qfoUEz5>Jbve~fm_zg0wS9sb`0TRt2ttr{(go?u2VmVq zh7!j$5D8w>g#0$9fChf=-9+hmztUbTJJ;<&{HZ6?`$kau4Cs8HRTypESm%nX9NEqs z=#i$n%wxV9n@N8C%E{kRP319w(ZnO$@+Q7bRY-;sbOSki?QE_Wj(=k{Pfl5wm?;Nt zYHRQf?B_nYEv~Mfzbufoq^$ajvT1Nt0mm7adtxkAQ5q`e(qS{0TYuyh)ZaI6hIl+u z%=qM>X1U~sXS{RJiA2lslVaDl^J&`G$9K52Y;!gzzC`=M{VPqJu^5XMjq+e^(i063 z&@5Exlhy z0u@0`k@B010VWuavKPk4HGGe?G*$=0*L!h)S_Lv{?Vp{2pFf;G z$Mv8M{Qx|6Z*tHpUT{gj(VI)fqD%Rlb{$=~~bZ!fX;3)mOn tFMmCD_)E|=Kgdz}5IyPtug!A3=}}bK-p`*?E*Ko~nE#2xtbd-n^j|IzyD$I% literal 0 HcmV?d00001 diff --git a/web/logo.svg b/web/logo.svg new file mode 100644 index 000000000..41d142b2a --- /dev/null +++ b/web/logo.svg @@ -0,0 +1 @@ + From e8d04e142efa3327107b30da25bc803276b478a4 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Wed, 21 Jan 2015 16:34:21 -0500 Subject: [PATCH 0100/1263] Fix build on windows Issues including "pcre.h", but it's not needed anyway! I can just get rid of it. --- src/private/pcre.nim | 49 ++++++++++++++++++++++---------------------- 1 file changed, 24 insertions(+), 25 deletions(-) diff --git a/src/private/pcre.nim b/src/private/pcre.nim index 89bd5c58c..be348444b 100644 --- a/src/private/pcre.nim +++ b/src/private/pcre.nim @@ -35,8 +35,7 @@ else: {. compile: "private/pcre_src/pcre_xclass.c" .} {. compile: "private/pcre_src/pcre_chartables.c" .} - const pcreHeader = "pcre.h" - {.pragma: pcreImport, header: pcreHeader.} + {.pragma: pcreImport.} #************************************************ # Perl-Compatible Regular Expressions * @@ -343,16 +342,16 @@ type #remain compatible. type - ExtraData* {.importc: "pcre_extra", header: "pcre.h".} = object - flags* {.importc: "flags".}: culong # Bits for which fields are set - study_data* {.importc: "study_data".}: pointer # Opaque data from pcre_study() - match_limit* {.importc: "match_limit".}: culong # Maximum number of calls to match() - callout_data* {.importc: "callout_data".}: pointer # Data passed back in callouts - tables* {.importc: "tables".}: ptr cuchar # Pointer to character tables - match_limit_recursion* {.importc: "match_limit_recursion".}: culong # Max + ExtraData* = object + flags*: culong # Bits for which fields are set + study_data*: pointer # Opaque data from pcre_study() + match_limit*: culong # Maximum number of calls to match() + callout_data*: pointer # Data passed back in callouts + tables*: ptr cuchar # Pointer to character tables + match_limit_recursion*: culong # Max # recursive calls to match() - mark* {.importc: "mark".}: ptr ptr cuchar # For passing back a mark pointer - executable_jit* {.importc: "executable_jit".}: pointer # Contains a pointer to a compiled jit code + mark*: ptr ptr cuchar # For passing back a mark pointer + executable_jit*: pointer # Contains a pointer to a compiled jit code # The structure for passing out data via the pcre_callout_function. We use a #structure so that new fields can be added on the end in future versions, @@ -360,25 +359,25 @@ type #without modification. type - callout_block* {.importc: "pcre_callout_block", header: pcreHeader.} = object - version* {.importc: "version".}: cint # Identifies version of block + callout_block* = object + version*: cint # Identifies version of block # ------------------------ Version 0 ------------------------------- - callout_number* {.importc: "callout_number".}: cint # Number compiled into pattern - offset_vector* {.importc: "offset_vector".}: ptr cint # The offset vector - subject* {.importc: "subject".}: cstring # The subject being matched - subject_length* {.importc: "subject_length".}: cint # The length of the subject - start_match* {.importc: "start_match".}: cint # Offset to start of this match attempt - current_position* {.importc: "current_position".}: cint # Where we currently are in the subject - capture_top* {.importc: "capture_top".}: cint # Max current capture - capture_last* {.importc: "capture_last".}: cint # Most recently closed capture - callout_data* {.importc: "callout_data".}: pointer # Data passed in with the call + callout_number*: cint # Number compiled into pattern + offset_vector*: ptr cint # The offset vector + subject*: cstring # The subject being matched + subject_length*: cint # The length of the subject + start_match*: cint # Offset to start of this match attempt + current_position*: cint # Where we currently are in the subject + capture_top*: cint # Max current capture + capture_last*: cint # Most recently closed capture + callout_data*: pointer # Data passed in with the call # ------------------- Added for Version 1 # -------------------------- - pattern_position* {.importc: "pattern_position".}: cint # Offset to next item in the pattern - next_item_length* {.importc: "next_item_length".}: cint # Length of next item in the pattern + pattern_position*: cint # Offset to next item in the pattern + next_item_length*: cint # Length of next item in the pattern # ------------------- Added for Version 2 # -------------------------- - mark* {.importc: "mark".}: ptr cuchar # Pointer to current mark or NULL + mark*: ptr cuchar # Pointer to current mark or NULL # # ------------------------------------------------------------------ # Indirection for store get and free functions. These can be set to From ba3aac1b13d73e515dfed50376d82f57a46d7d2c Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Wed, 21 Jan 2015 21:08:15 -0500 Subject: [PATCH 0101/1263] Bump version --- nre.nimble | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nre.nimble b/nre.nimble index ea83286c2..e13ce79db 100644 --- a/nre.nimble +++ b/nre.nimble @@ -1,7 +1,7 @@ [Package] name = "nre" author = "Flaviu Tamas" -version = "0.3.1" +version = "0.4.0" description = "Yet another PCRE library" license = "MIT" srcDir = "src" From e027ea91395b27849c4b8db11555a263ea894b76 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 24 Jan 2015 14:58:09 -0500 Subject: [PATCH 0102/1263] Add start to split --- README.asciidoc | 6 ++++-- src/nre.nim | 8 ++++---- test/split.nim | 5 +++++ 3 files changed, 13 insertions(+), 6 deletions(-) diff --git a/README.asciidoc b/README.asciidoc index d8cb6e096..a0d5bdcdb 100644 --- a/README.asciidoc +++ b/README.asciidoc @@ -53,10 +53,10 @@ Variants: - `proc findAll(...)` returns a `seq[string]` [[proc-split]] -==== split(string, Regex, maxsplit = -1): seq[string] +==== split(string, Regex, maxsplit = -1, start = 0): seq[string] Splits the string with the given regex. This works according to the rules that -Perl and Javascript use. +Perl and Javascript use: - If the match is zero-width, then the string is still split: `"123".split(r"") == @["1", "2", "3"]`. @@ -66,6 +66,8 @@ Perl and Javascript use. times. This means that there will be `maxsplit` strings in the output seq. `"1.2.3".split(re"\.", maxsplit = 2) == @["1", "2.3"]` +`start` behaves the same as in link:#proc-find[`find(...)`]. + [[proc-replace]] ==== replace(string, Regex, sub): string diff --git a/src/nre.nim b/src/nre.nim index 47e374978..6743a82dc 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -384,13 +384,13 @@ proc renderBounds(str: string, bounds: Slice[int]): string = for i in bounds.a .. bounds.b: result.add("^") -proc split*(str: string, pattern: Regex, maxSplit = -1): seq[string] = +proc split*(str: string, pattern: Regex, maxSplit = -1, start = 0): seq[string] = result = @[] - var lastIdx = 0 + var lastIdx = start var splits = 0 var bounds: Slice[int] - for match in str.findIter(pattern): + for match in str.findIter(pattern, start = start): # upper bound is exclusive, lower is inclusive: # # 0123456 @@ -401,7 +401,7 @@ proc split*(str: string, pattern: Regex, maxSplit = -1): seq[string] = # "12".split("") would be @["", "1", "2"], but # if we skip an empty first match, it's the correct # @["1", "2"] - if bounds.a < bounds.b or bounds.a > 0: + if bounds.a < bounds.b or bounds.a > start: result.add(str.substr(lastIdx, bounds.a - 1)) splits += 1 diff --git a/test/split.nim b/test/split.nim index 7aed714a4..62b88427b 100644 --- a/test/split.nim +++ b/test/split.nim @@ -43,3 +43,8 @@ suite "string splitting": check("a.b" .split(re"\.") .join(",") == "a,b") check("" .split(re"") .len == 0) check(":" .split(re"") .len == 1) + + test "start position": + check("abc".split(re"", start = 1) == @["b", "c"]) + check("abc".split(re"", start = 2) == @["c"]) + check("abc".split(re"", start = 3) == newSeq[string]()) From a064faf1715bc01f0c47f7ee29e75767b2812e11 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 24 Jan 2015 14:58:25 -0500 Subject: [PATCH 0103/1263] Allow custom test parameters --- runtests.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/runtests.sh b/runtests.sh index 39f9db286..ba6fff032 100755 --- a/runtests.sh +++ b/runtests.sh @@ -1,4 +1,4 @@ #!/usr/bin/sh nim c --path:src -r --verbosity:0 --hints:off --linedir:on --debuginfo \ - --stacktrace:on --linetrace:on ./test/testall.nim \ + --stacktrace:on --linetrace:on "$@" ./test/testall.nim \ | grep -vE 'ProveInit|instantiation from here' From 85d71da5958337b33477b973bcc2d1cbd4791216 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 24 Jan 2015 14:58:44 -0500 Subject: [PATCH 0104/1263] Bump version --- nre.nimble | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nre.nimble b/nre.nimble index e13ce79db..afdfbd6d4 100644 --- a/nre.nimble +++ b/nre.nimble @@ -1,7 +1,7 @@ [Package] name = "nre" author = "Flaviu Tamas" -version = "0.4.0" +version = "0.5.0" description = "Yet another PCRE library" license = "MIT" srcDir = "src" From 43127455cb518bd21d4c5c2d63bcb62e4fbccdc9 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Wed, 28 Jan 2015 20:19:35 -0500 Subject: [PATCH 0105/1263] Remove match cache --- src/nre.nim | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/src/nre.nim b/src/nre.nim index 6743a82dc..a8842b2da 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -27,7 +27,6 @@ type pcreMatchBounds: seq[Slice[cint]] ## First item is the bounds of the match ## Other items are the captures ## `a` is inclusive start, `b` is exclusive end - matchCache: seq[string] Captures* = distinct RegexMatch CaptureBounds* = distinct RegexMatch @@ -112,12 +111,7 @@ proc `[]`*(pattern: Captures, i: int): string = if bounds: let bounds = bounds.get - if pattern.matchCache == nil: - # capture count, plus the entire string - pattern.matchCache = newSeq[string](pattern.pattern.captureCount + 1) - if pattern.matchCache[i + 1] == nil: - pattern.matchCache[i + 1] = pattern.str.substr(bounds.a, bounds.b-1) - return pattern.matchCache[i + 1] + return pattern.str.substr(bounds.a, bounds.b-1) else: return nil From a1110ebb14e7ca1bd99ceb05da986ba902662bbc Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Wed, 28 Jan 2015 20:33:33 -0500 Subject: [PATCH 0106/1263] Change RegexMatch from ref to Option Also associated changes to tests and code --- src/nre.nim | 31 ++++++++++++++----------------- test/captures.nim | 2 +- test/find.nim | 2 +- test/match.nim | 6 +++--- test/misc.nim | 2 +- 5 files changed, 20 insertions(+), 23 deletions(-) diff --git a/src/nre.nim b/src/nre.nim index a8842b2da..b9922ad0f 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -18,7 +18,7 @@ type captureNameToId: Table[string, int] - RegexMatch* = ref object + RegexMatch* = object ## Is returned upon a match. pattern*: Regex ## The regex doing the matching. ## Not nil. @@ -286,10 +286,8 @@ proc re*(pattern: string, options = ""): Regex = initRegex(pattern, options) # }}} # Operations {{{ -proc matchImpl(str: string, pattern: Regex, start, endpos: int, flags: int): RegexMatch = - new(result) - result.pattern = pattern - result.str = str +proc matchImpl(str: string, pattern: Regex, start, endpos: int, flags: int): Option[RegexMatch] = + var result = RegexMatch(pattern : pattern, str : str) # See PCRE man pages. # 2x capture count to make room for start-end pairs # 1x capture count as slack space for PCRE @@ -309,13 +307,13 @@ proc matchImpl(str: string, pattern: Regex, start, endpos: int, flags: int): Reg cast[ptr cint](addr result.pcreMatchBounds[0]), cint(vecsize)) if execRet >= 0: - return result + return Some(result) elif execRet == pcre.ERROR_NOMATCH: - return nil + return None[RegexMatch]() else: raise newException(AssertionError, "Internal error: errno " & $execRet) -proc match*(str: string, pattern: Regex, start = 0, endpos = -1): RegexMatch = +proc match*(str: string, pattern: Regex, start = 0, endpos = -1): Option[RegexMatch] = return str.matchImpl(pattern, start, endpos, pcre.ANCHORED) iterator findIter*(str: string, pattern: Regex, start = 0, endpos = -1): RegexMatch = @@ -325,19 +323,18 @@ iterator findIter*(str: string, pattern: Regex, start = 0, endpos = -1): RegexMa let endpos = if endpos == -1: str.len else: endpos var offset = start - var previousMatch: RegexMatch + var match: Option[RegexMatch] while true: var flags = 0 - if previousMatch != nil and - previousMatch.matchBounds.a == previousMatch.matchBounds.b: + if match and + match.get.matchBounds.a == match.get.matchBounds.b: # 0-len match flags = pcre.NOTEMPTY_ATSTART or pcre.ANCHORED - let currentMatch = str.matchImpl(pattern, offset, endpos, flags) - previousMatch = currentMatch + match = str.matchImpl(pattern, offset, endpos, flags) - if currentMatch == nil: + if match.isNone: # either the end of the input or the string # cannot be split here offset += 1 @@ -351,15 +348,15 @@ iterator findIter*(str: string, pattern: Regex, start = 0, endpos = -1): RegexMa offset += str.runeLenAt(offset) assert(offset <= endpos) else: - offset = currentMatch.matchBounds.b + offset = match.get.matchBounds.b - yield currentMatch + yield match.get if offset >= endpos: # do while break -proc find*(str: string, pattern: Regex, start = 0, endpos = -1): RegexMatch = +proc find*(str: string, pattern: Regex, start = 0, endpos = -1): Option[RegexMatch] = ## Returns a `RegexMatch` if there is a match between `start` and `endpos`, otherwise ## it returns nil. ## diff --git a/test/captures.nim b/test/captures.nim index 31bf1c6a2..4bf3a81ce 100644 --- a/test/captures.nim +++ b/test/captures.nim @@ -1,4 +1,4 @@ -import unittest +import unittest, optional_t.nonstrict include nre suite "captures": diff --git a/test/find.nim b/test/find.nim index f4f72c778..b4be08e88 100644 --- a/test/find.nim +++ b/test/find.nim @@ -1,4 +1,4 @@ -import unittest, sequtils, nre +import unittest, sequtils, nre, optional_t.nonstrict suite "find": test "find text": diff --git a/test/match.nim b/test/match.nim index c02cc8e42..277e8b3b0 100644 --- a/test/match.nim +++ b/test/match.nim @@ -1,9 +1,9 @@ -include nre, unittest +include nre, unittest, optional_t.nonstrict suite "match": test "upper bound must be exclusive": - check("abc".match(re"abc", endpos = 0) == nil) - check("abc".match(re"abc", endpos = 3) != nil) + check("abc".match(re"abc", endpos = 0) == None[RegexMatch]()) + check("abc".match(re"abc", endpos = 3) != None[RegexMatch]()) test "match examples": check("abc".match(re"(\w)").captures[0] == "a") diff --git a/test/misc.nim b/test/misc.nim index 0b46a393b..8ec0ea878 100644 --- a/test/misc.nim +++ b/test/misc.nim @@ -1,4 +1,4 @@ -import unittest, nre +import unittest, nre, optional_t.nonstrict suite "Misc tests": test "unicode": From bc37a338530fa5fd0ead8eb89eaf695d4c7ad143 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 31 Jan 2015 18:07:55 -0500 Subject: [PATCH 0107/1263] Update documentation --- README.asciidoc | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.asciidoc b/README.asciidoc index a0d5bdcdb..2b19ea5e4 100644 --- a/README.asciidoc +++ b/README.asciidoc @@ -96,10 +96,11 @@ If `sub` is a string, the syntax is as follows: Escapes the string so it doesn't match any special characters. Incompatible with the Extra flag (`X`). -=== RegexMatch +=== Option[RegexMatch] -Represents the result of an execution. On failure, it is `nil`. The available -fields are as follows: +Represents the result of an execution. On failure, it is `None[RegexMatch]`, +but if you want automated derefrence, import `optional_t.nonstrict`. The +available fields are as follows: `pattern: Regex` :: the pattern that is being matched `str: string` :: the string that was matched against From 18a401886d5833b7fb26a2b9121497197811c1c5 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 31 Jan 2015 18:05:13 -0500 Subject: [PATCH 0108/1263] Bump version number --- nre.nimble | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nre.nimble b/nre.nimble index afdfbd6d4..232c46493 100644 --- a/nre.nimble +++ b/nre.nimble @@ -1,11 +1,11 @@ [Package] name = "nre" author = "Flaviu Tamas" -version = "0.5.0" +version = "0.6.0" description = "Yet another PCRE library" license = "MIT" srcDir = "src" [Deps] Requires: "nim >= 0.10.0" -Requires: "optional_t >= 1.1.0" +Requires: "optional_t >= 1.2.0" From 7191869d0943466441f975cef0a841d0e68ec195 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 7 Feb 2015 09:46:03 -0500 Subject: [PATCH 0109/1263] Use /bin/sh Apparently /usr/bin/sh only works in Arch Linux --- runtests.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/runtests.sh b/runtests.sh index ba6fff032..c15ef088a 100755 --- a/runtests.sh +++ b/runtests.sh @@ -1,4 +1,4 @@ -#!/usr/bin/sh +#!/bin/sh nim c --path:src -r --verbosity:0 --hints:off --linedir:on --debuginfo \ --stacktrace:on --linetrace:on "$@" ./test/testall.nim \ | grep -vE 'ProveInit|instantiation from here' From 5cbaa1ba371a9a681aadd55641400308d4bf28a6 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 7 Feb 2015 13:19:43 -0500 Subject: [PATCH 0110/1263] Remove unnecessary filter The things it was filtering do not need to be filtered --- runtests.sh | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/runtests.sh b/runtests.sh index c15ef088a..51dbcaf35 100755 --- a/runtests.sh +++ b/runtests.sh @@ -1,4 +1,3 @@ #!/bin/sh nim c --path:src -r --verbosity:0 --hints:off --linedir:on --debuginfo \ - --stacktrace:on --linetrace:on "$@" ./test/testall.nim \ - | grep -vE 'ProveInit|instantiation from here' + --stacktrace:on --linetrace:on "$@" ./test/testall.nim From cba3b788f19deb6310d0e063f1e081dcf4b68299 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Wed, 11 Feb 2015 14:05:52 -0500 Subject: [PATCH 0111/1263] Add more details about modifier syntax See discussion on #4 for details. --- README.asciidoc | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/README.asciidoc b/README.asciidoc index 2b19ea5e4..c211acda2 100644 --- a/README.asciidoc +++ b/README.asciidoc @@ -129,7 +129,13 @@ as a key. Represents the pattern that things are matched against, constructed with `re(string, string)`. Examples: `re"foo"`, `re(r"foo # comment", -"x")`. +"x")`, `re"(?x)(*ANYCRLF)foo # comment"`. +For more details on the leading option groups, see the +link:http://man7.org/linux/man-pages/man3/pcresyntax.3.html#OPTION_SETTING[Option Setting] +and the +link:http://man7.org/linux/man-pages/man3/pcresyntax.3.html#NEWLINE_CONVENTION[Newline Convention] +sections of the +link:http://man7.org/linux/man-pages/man3/pcresyntax.3.html[PCRE syntax manual]. `pattern: string` :: the string that was used to create the pattern. `captureCount: int` :: the number of captures that the pattern has. From 7296c6d649ada6838b3c0e93fa87721c882eab2c Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Tue, 3 Mar 2015 18:42:38 -0500 Subject: [PATCH 0112/1263] Add equality operator for RegexMatch and Regex - Technically a breaking change, but I doubt anyone depends on a compile-time error for long ;) --- nre.nimble | 2 +- src/nre.nim | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/nre.nimble b/nre.nimble index 232c46493..b007ff617 100644 --- a/nre.nimble +++ b/nre.nimble @@ -1,7 +1,7 @@ [Package] name = "nre" author = "Flaviu Tamas" -version = "0.6.0" +version = "0.6.1" description = "Yet another PCRE library" license = "MIT" srcDir = "src" diff --git a/src/nre.nim b/src/nre.nim index b9922ad0f..421b6a282 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -172,6 +172,18 @@ proc toSeq*(pattern: Captures, default: string = nil): seq[string] = proc `$`*(pattern: RegexMatch): string = return pattern.captures[-1] + +proc `==`*(a, b: Regex): bool = + # name-to-number table is generated at init time, doesn't need to be checked + return a.pattern == b.pattern and + a.pcreObj == b.pcreObj and + a.pcreExtra == b.pcreExtra + +proc `==`*(a, b: RegexMatch): bool = + # don't need to compare matchbounds, if pattern and str equal, everything + # else will equal (unless callbacks, maybe? TODO) + return a.pattern == b.pattern and + a.str == b.str # }}} # Creation & Destruction {{{ From b556bd9abf563e7bcff2cf244a512d99ad0ac10f Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Wed, 4 Mar 2015 19:15:53 -0500 Subject: [PATCH 0113/1263] Fix "could not import: pcre_stack_guard" kanaka/mal#20 related, seems like some systems have older PCREs, without pcre_stack_guard. Since it isn't expclitly used, this will *hopefully* prevent errors from occurring. --- src/private/pcre.nim | 1 + 1 file changed, 1 insertion(+) diff --git a/src/private/pcre.nim b/src/private/pcre.nim index be348444b..3d619d268 100644 --- a/src/private/pcre.nim +++ b/src/private/pcre.nim @@ -10,6 +10,7 @@ when defined(pcreDynlib): {.pragma: pcreImport, dynlib: pcreDll.} else: {.pragma: pcreImport, header: pcreHeader.} + {.deadCodeElim: on.} # Don't error unless unsupported features are used else: {. passC: "-DHAVE_CONFIG_H", passC: "-I private/pcre_src", passL: "-I private/pcre_src" .} From ab6e83ad4185e9623947dc82e4176c84eb05716a Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Wed, 4 Mar 2015 19:29:35 -0500 Subject: [PATCH 0114/1263] Fix tests broken in 7296c6d 7296c6d doesn't do any nil checking, so it segfaults on `==` on `Regex` --- src/nre.nim | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/nre.nim b/src/nre.nim index 421b6a282..dd00cf822 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -175,7 +175,8 @@ proc `$`*(pattern: RegexMatch): string = proc `==`*(a, b: Regex): bool = # name-to-number table is generated at init time, doesn't need to be checked - return a.pattern == b.pattern and + return not a.isNil and not b.isNil and + a.pattern == b.pattern and a.pcreObj == b.pcreObj and a.pcreExtra == b.pcreExtra From e5e5970d93f3b823b1f219f36f1be7cd6050637a Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Wed, 4 Mar 2015 21:45:56 -0500 Subject: [PATCH 0115/1263] Fix broken logic in 7296c6d Thanks @fowlmouth for pointing this problem out in IRC. --- src/nre.nim | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/nre.nim b/src/nre.nim index dd00cf822..6d6f90046 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -175,10 +175,12 @@ proc `$`*(pattern: RegexMatch): string = proc `==`*(a, b: Regex): bool = # name-to-number table is generated at init time, doesn't need to be checked - return not a.isNil and not b.isNil and - a.pattern == b.pattern and - a.pcreObj == b.pcreObj and - a.pcreExtra == b.pcreExtra + if not a.isNil and not b.isNil: + return a.pattern == b.pattern and + a.pcreObj == b.pcreObj and + a.pcreExtra == b.pcreExtra + else: + return system.`==`(a, b) proc `==`*(a, b: RegexMatch): bool = # don't need to compare matchbounds, if pattern and str equal, everything From 763e902b655d412cec0050a1dad5b564238a7186 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Thu, 5 Mar 2015 10:42:37 -0500 Subject: [PATCH 0116/1263] Remove renderBounds() A debug proc, it's not really useful and throws warnings anyway. --- src/nre.nim | 7 ------- 1 file changed, 7 deletions(-) diff --git a/src/nre.nim b/src/nre.nim index 6d6f90046..83b0d9db1 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -383,13 +383,6 @@ proc findAll*(str: string, pattern: Regex, start = 0, endpos = -1): seq[string] for match in str.findIter(pattern, start, endpos): result.add(match.match) -proc renderBounds(str: string, bounds: Slice[int]): string = - result = " " & str & "⫞\n" - for i in -1 .. Date: Tue, 31 Mar 2015 00:04:31 +0200 Subject: [PATCH 0117/1263] Rename mget to `[]` - In sets, tables, strtabs, critbits, xmltree - This uses the new var parameter overloading - mget variants still exist, but are deprecated in favor of `[]` - Includes tests and fixed tests and usages of mget - The non-var `[]` now throws an exception instead of returning binary 0 or an empty string --- lib/pure/collections/critbits.nim | 48 ++++++---- lib/pure/collections/sets.nim | 9 +- lib/pure/collections/tables.nim | 138 +++++++++++++++++----------- lib/pure/strtabs.nim | 31 ++++--- lib/pure/xmltree.nim | 9 +- lib/system/sets.nim | 2 +- tests/actiontable/tactiontable.nim | 15 ++- tests/collections/ttables.nim | 19 ++-- tests/collections/ttablesref.nim | 21 +++-- tests/misc/teventemitter.nim | 9 +- tests/stdlib/tmget.nim | 141 +++++++++++++++++++++++++++++ tests/stdlib/tmitems.nim | 2 +- 12 files changed, 322 insertions(+), 122 deletions(-) create mode 100644 tests/stdlib/tmget.nim diff --git a/lib/pure/collections/critbits.nim b/lib/pure/collections/critbits.nim index 3d10e39aa..fb5fd7f36 100644 --- a/lib/pure/collections/critbits.nim +++ b/lib/pure/collections/critbits.nim @@ -17,11 +17,11 @@ type otherbits: char case isLeaf: bool of false: child: array[0..1, ref NodeObj[T]] - of true: + of true: key: string when T isnot void: val: T - + Node[T] = ref NodeObj[T] CritBitTree*[T] = object ## The crit bit tree can either be used ## as a mapping from strings to @@ -66,7 +66,7 @@ proc rawInsert[T](c: var CritBitTree[T], key: string): Node[T] = let ch = if it.byte < key.len: key[it.byte] else: '\0' let dir = (1 + (ch.ord or it.otherBits.ord)) shr 8 it = it.child[dir] - + var newOtherBits = 0 var newByte = 0 block blockX: @@ -84,7 +84,7 @@ proc rawInsert[T](c: var CritBitTree[T], key: string): Node[T] = newOtherBits = newOtherBits xor 255 let ch = it.key[newByte] let dir = (1 + (ord(ch) or newOtherBits)) shr 8 - + var inner: Node[T] new inner new result @@ -93,7 +93,7 @@ proc rawInsert[T](c: var CritBitTree[T], key: string): Node[T] = inner.otherBits = chr(newOtherBits) inner.byte = newByte inner.child[1 - dir] = result - + var wherep = addr(c.root) while true: var p = wherep[] @@ -132,20 +132,31 @@ proc `[]=`*[T](c: var CritBitTree[T], key: string, val: T) = var n = rawInsert(c, key) n.val = val -proc `[]`*[T](c: CritBitTree[T], key: string): T {.inline.} = - ## retrieves the value at ``c[key]``. If `key` is not in `t`, - ## default empty value for the type `B` is returned - ## and no exception is raised. One can check with ``hasKey`` whether the key - ## exists. +template get[T](c: CritBitTree[T], key: string): T {.immediate.} = let n = rawGet(c, key) if n != nil: result = n.val + else: + when compiles($key): + raise newException(KeyError, "key not found: " & $key) + else: + raise newException(KeyError, "key not found") -proc mget*[T](c: var CritBitTree[T], key: string): var T {.inline.} = +proc `[]`*[T](c: CritBitTree[T], key: string): T {.inline.} = + ## retrieves the value at ``c[key]``. If `key` is not in `t`, the + ## ``KeyError`` exception is raised. One can check with ``hasKey`` whether + ## the key exists. + get(c, key) + +proc `[]`*[T](c: var CritBitTree[T], key: string): var T {.inline.} = ## retrieves the value at ``c[key]``. The value can be modified. ## If `key` is not in `t`, the ``KeyError`` exception is raised. - let n = rawGet(c, key) - if n != nil: result = n.val - else: raise newException(KeyError, "key not found: " & $key) + get(c, key) + +proc mget*[T](c: var CritBitTree[T], key: string): var T {.inline, deprecated.} = + ## retrieves the value at ``c[key]``. The value can be modified. + ## If `key` is not in `t`, the ``KeyError`` exception is raised. + ## Use ```[]``` instead. + get(c, key) proc excl*[T](c: var CritBitTree[T], key: string) = ## removes `key` (and its associated value) from the set `c`. @@ -176,7 +187,7 @@ iterator leaves[T](n: Node[T]): Node[T] = # XXX actually we could compute the necessary stack size in advance: # it's roughly log2(c.count). var stack = @[n] - while stack.len > 0: + while stack.len > 0: var it = stack.pop while not it.isLeaf: stack.add(it.child[1]) @@ -205,7 +216,7 @@ iterator items*[T](c: CritBitTree[T]): string = iterator pairs*[T](c: CritBitTree[T]): tuple[key: string, val: T] = ## yields all (key, value)-pairs of `c`. for x in leaves(c.root): yield (x.key, x.val) - + iterator mpairs*[T](c: var CritBitTree[T]): tuple[key: string, val: var T] = ## yields all (key, value)-pairs of `c`. The yielded values can be modified. for x in leaves(c.root): yield (x.key, x.val) @@ -251,7 +262,7 @@ iterator pairsWithPrefix*[T](c: CritBitTree[T], ## yields all (key, value)-pairs of `c` starting with `prefix`. let top = allprefixedAux(c, prefix) for x in leaves(top): yield (x.key, x.val) - + iterator mpairsWithPrefix*[T](c: var CritBitTree[T], prefix: string): tuple[key: string, val: var T] = ## yields all (key, value)-pairs of `c` starting with `prefix`. @@ -297,7 +308,6 @@ when isMainModule: for w in r.items: echo w - + for w in r.itemsWithPrefix("de"): echo w - diff --git a/lib/pure/collections/sets.nim b/lib/pure/collections/sets.nim index 4a20d00a4..49271e2c9 100644 --- a/lib/pure/collections/sets.nim +++ b/lib/pure/collections/sets.nim @@ -154,7 +154,7 @@ proc rawGetKnownHC[A](s: HashSet[A], key: A, hc: THash): int {.inline.} = proc rawGet[A](s: HashSet[A], key: A, hc: var THash): int {.inline.} = rawGetImpl() -proc mget*[A](s: var HashSet[A], key: A): var A = +proc `[]`*[A](s: var HashSet[A], key: A): var A = ## returns the element that is actually stored in 's' which has the same ## value as 'key' or raises the ``EInvalidKey`` exception. This is useful ## when one overloaded 'hash' and '==' but still needs reference semantics @@ -165,6 +165,13 @@ proc mget*[A](s: var HashSet[A], key: A): var A = if index >= 0: result = s.data[index].key else: raise newException(KeyError, "key not found: " & $key) +proc mget*[A](s: var HashSet[A], key: A): var A {.deprecated.} = + ## returns the element that is actually stored in 's' which has the same + ## value as 'key' or raises the ``EInvalidKey`` exception. This is useful + ## when one overloaded 'hash' and '==' but still needs reference semantics + ## for sharing. Use ```[]``` instead. + s[key] + proc contains*[A](s: HashSet[A], key: A): bool = ## Returns true iff `key` is in `s`. ## diff --git a/lib/pure/collections/tables.nim b/lib/pure/collections/tables.nim index f85acef22..adc9c6d8d 100644 --- a/lib/pure/collections/tables.nim +++ b/lib/pure/collections/tables.nim @@ -181,18 +181,7 @@ proc rawGetDeep[A, B](t: Table[A, B], key: A, hc: var THash): int {.inline.} = proc rawGet[A, B](t: Table[A, B], key: A, hc: var THash): int {.inline.} = rawGetImpl() -proc `[]`*[A, B](t: Table[A, B], key: A): B = - ## retrieves the value at ``t[key]``. If `key` is not in `t`, - ## default empty value for the type `B` is returned - ## and no exception is raised. One can check with ``hasKey`` whether the key - ## exists. - var hc: THash - var index = rawGet(t, key, hc) - if index >= 0: result = t.data[index].val - -proc mget*[A, B](t: var Table[A, B], key: A): var B = - ## retrieves the value at ``t[key]``. The value can be modified. - ## If `key` is not in `t`, the ``KeyError`` exception is raised. +template get[A, B](t: Table[A, B], key: A): B {.immediate.} = var hc: THash var index = rawGet(t, key, hc) if index >= 0: result = t.data[index].val @@ -202,6 +191,23 @@ proc mget*[A, B](t: var Table[A, B], key: A): var B = else: raise newException(KeyError, "key not found") +proc `[]`*[A, B](t: Table[A, B], key: A): B = + ## retrieves the value at ``t[key]``. If `key` is not in `t`, the + ## ``KeyError`` exception is raised. One can check with ``hasKey`` whether + ## the key exists. + get(t, key) + +proc `[]`*[A, B](t: var Table[A, B], key: A): var B = + ## retrieves the value at ``t[key]``. The value can be modified. + ## If `key` is not in `t`, the ``KeyError`` exception is raised. + get(t, key) + +proc mget*[A, B](t: var Table[A, B], key: A): var B {.deprecated.} = + ## retrieves the value at ``t[key]``. The value can be modified. + ## If `key` is not in `t`, the ``KeyError`` exception is raised. Use ```[]``` + ## instead. + get(t, key) + iterator allValues*[A, B](t: Table[A, B]; key: A): B = ## iterates over any value in the table `t` that belongs to the given `key`. var h: THash = hash(key) and high(t.data) @@ -386,17 +392,17 @@ iterator mvalues*[A, B](t: TableRef[A, B]): var B = for h in 0..high(t.data): if isFilled(t.data[h].hcode): yield t.data[h].val -proc `[]`*[A, B](t: TableRef[A, B], key: A): B = - ## retrieves the value at ``t[key]``. If `key` is not in `t`, - ## default empty value for the type `B` is returned - ## and no exception is raised. One can check with ``hasKey`` whether the key - ## exists. +proc `[]`*[A, B](t: TableRef[A, B], key: A): var B = + ## retrieves the value at ``t[key]``. If `key` is not in `t`, the + ## ``KeyError`` exception is raised. One can check with ``hasKey`` whether + ## the key exists. result = t[][key] -proc mget*[A, B](t: TableRef[A, B], key: A): var B = +proc mget*[A, B](t: TableRef[A, B], key: A): var B {.deprecated.} = ## retrieves the value at ``t[key]``. The value can be modified. - ## If `key` is not in `t`, the ``EInvalidKey`` exception is raised. - t[].mget(key) + ## If `key` is not in `t`, the ``KeyError`` exception is raised. + ## Use ```[]``` instead. + t[][key] proc mgetOrPut*[A, B](t: TableRef[A, B], key: A, val: B): var B = ## retrieves value at ``t[key]`` or puts ``val`` if not present, either way @@ -510,22 +516,32 @@ proc rawGetDeep[A, B](t: OrderedTable[A, B], key: A, hc: var THash): int {.inlin proc rawGet[A, B](t: OrderedTable[A, B], key: A, hc: var THash): int = rawGetImpl() -proc `[]`*[A, B](t: OrderedTable[A, B], key: A): B = - ## retrieves the value at ``t[key]``. If `key` is not in `t`, - ## default empty value for the type `B` is returned - ## and no exception is raised. One can check with ``hasKey`` whether the key - ## exists. +template get[A, B](t: OrderedTable[A, B], key: A): B {.immediate.} = var hc: THash var index = rawGet(t, key, hc) if index >= 0: result = t.data[index].val + else: + when compiles($key): + raise newException(KeyError, "key not found: " & $key) + else: + raise newException(KeyError, "key not found") -proc mget*[A, B](t: var OrderedTable[A, B], key: A): var B = +proc `[]`*[A, B](t: OrderedTable[A, B], key: A): B = + ## retrieves the value at ``t[key]``. If `key` is not in `t`, the + ## ``KeyError`` exception is raised. One can check with ``hasKey`` whether + ## the key exists. + get(t, key) + +proc `[]`*[A, B](t: var OrderedTable[A, B], key: A): var B = ## retrieves the value at ``t[key]``. The value can be modified. - ## If `key` is not in `t`, the ``EInvalidKey`` exception is raised. - var hc: THash - var index = rawGet(t, key, hc) - if index >= 0: result = t.data[index].val - else: raise newException(KeyError, "key not found: " & $key) + ## If `key` is not in `t`, the ``KeyError`` exception is raised. + get(t, key) + +proc mget*[A, B](t: var OrderedTable[A, B], key: A): var B {.deprecated.} = + ## retrieves the value at ``t[key]``. The value can be modified. + ## If `key` is not in `t`, the ``KeyError`` exception is raised. + ## Use ```[]``` instead. + get(t, key) proc hasKey*[A, B](t: OrderedTable[A, B], key: A): bool = ## returns true iff `key` is in the table `t`. @@ -679,17 +695,17 @@ iterator mvalues*[A, B](t: OrderedTableRef[A, B]): var B = forAllOrderedPairs: yield t.data[h].val -proc `[]`*[A, B](t: OrderedTableRef[A, B], key: A): B = - ## retrieves the value at ``t[key]``. If `key` is not in `t`, - ## default empty value for the type `B` is returned - ## and no exception is raised. One can check with ``hasKey`` whether the key - ## exists. +proc `[]`*[A, B](t: OrderedTableRef[A, B], key: A): var B = + ## retrieves the value at ``t[key]``. If `key` is not in `t`, the + ## ``KeyError`` exception is raised. One can check with ``hasKey`` whether + ## the key exists. result = t[][key] -proc mget*[A, B](t: OrderedTableRef[A, B], key: A): var B = +proc mget*[A, B](t: OrderedTableRef[A, B], key: A): var B {.deprecated.} = ## retrieves the value at ``t[key]``. The value can be modified. - ## If `key` is not in `t`, the ``EInvalidKey`` exception is raised. - result = t[].mget(key) + ## If `key` is not in `t`, the ``KeyError`` exception is raised. + ## Use ```[]``` instead. + result = t[][key] proc mgetOrPut*[A, B](t: OrderedTableRef[A, B], key: A, val: B): var B = ## retrieves value at ``t[key]`` or puts ``val`` if not present, either way @@ -786,19 +802,31 @@ proc rawGet[A](t: CountTable[A], key: A): int = h = nextTry(h, high(t.data)) result = -1 - h # < 0 => MISSING; insert idx = -1 - result +template get[A](t: CountTable[A], key: A): int {.immediate.} = + var index = rawGet(t, key) + if index >= 0: result = t.data[index].val + else: + when compiles($key): + raise newException(KeyError, "key not found: " & $key) + else: + raise newException(KeyError, "key not found") + proc `[]`*[A](t: CountTable[A], key: A): int = ## retrieves the value at ``t[key]``. If `key` is not in `t`, - ## 0 is returned. One can check with ``hasKey`` whether the key - ## exists. - var index = rawGet(t, key) - if index >= 0: result = t.data[index].val + ## the ``KeyError`` exception is raised. One can check with ``hasKey`` + ## whether the key exists. + get(t, key) -proc mget*[A](t: var CountTable[A], key: A): var int = +proc `[]`*[A](t: var CountTable[A], key: A): var int = ## retrieves the value at ``t[key]``. The value can be modified. - ## If `key` is not in `t`, the ``EInvalidKey`` exception is raised. - var index = rawGet(t, key) - if index >= 0: result = t.data[index].val - else: raise newException(KeyError, "key not found: " & $key) + ## If `key` is not in `t`, the ``KeyError`` exception is raised. + get(t, key) + +proc mget*[A](t: var CountTable[A], key: A): var int {.deprecated.} = + ## retrieves the value at ``t[key]``. The value can be modified. + ## If `key` is not in `t`, the ``KeyError`` exception is raised. + ## Use ```[]``` instead. + get(t, key) proc hasKey*[A](t: CountTable[A], key: A): bool = ## returns true iff `key` is in the table `t`. @@ -927,16 +955,16 @@ iterator mvalues*[A](t: CountTableRef[A]): var int = for h in 0..high(t.data): if t.data[h].val != 0: yield t.data[h].val -proc `[]`*[A](t: CountTableRef[A], key: A): int = - ## retrieves the value at ``t[key]``. If `key` is not in `t`, - ## 0 is returned. One can check with ``hasKey`` whether the key - ## exists. +proc `[]`*[A](t: CountTableRef[A], key: A): var int = + ## retrieves the value at ``t[key]``. The value can be modified. + ## If `key` is not in `t`, the ``KeyError`` exception is raised. result = t[][key] -proc mget*[A](t: CountTableRef[A], key: A): var int = +proc mget*[A](t: CountTableRef[A], key: A): var int {.deprecated.} = ## retrieves the value at ``t[key]``. The value can be modified. - ## If `key` is not in `t`, the ``EInvalidKey`` exception is raised. - result = t[].mget(key) + ## If `key` is not in `t`, the ``KeyError`` exception is raised. + ## Use ```[]``` instead. + result = t[][key] proc hasKey*[A](t: CountTableRef[A], key: A): bool = ## returns true iff `key` is in the table `t`. diff --git a/lib/pure/strtabs.nim b/lib/pure/strtabs.nim index 727d5a386..6ed1bb9d8 100644 --- a/lib/pure/strtabs.nim +++ b/lib/pure/strtabs.nim @@ -101,21 +101,26 @@ proc rawGet(t: StringTableRef, key: string): int = h = nextTry(h, high(t.data)) result = - 1 -proc `[]`*(t: StringTableRef, key: string): string {.rtl, extern: "nstGet".} = - ## retrieves the value at ``t[key]``. If `key` is not in `t`, "" is returned - ## and no exception is raised. One can check with ``hasKey`` whether the key - ## exists. +template get(t: StringTableRef, key: string): stmt {.immediate.} = var index = rawGet(t, key) if index >= 0: result = t.data[index].val - else: result = "" + else: + when compiles($key): + raise newException(KeyError, "key not found: " & $key) + else: + raise newException(KeyError, "key not found") -proc mget*(t: StringTableRef, key: string): var string {. - rtl, extern: "nstTake".} = +proc `[]`*(t: StringTableRef, key: string): var string {. + rtl, extern: "nstTake".} = ## retrieves the location at ``t[key]``. If `key` is not in `t`, the - ## ``KeyError`` exception is raised. - var index = rawGet(t, key) - if index >= 0: result = t.data[index].val - else: raise newException(KeyError, "key does not exist: " & key) + ## ``KeyError`` exception is raised. One can check with ``hasKey`` whether + ## the key exists. + get(t, key) + +proc mget*(t: StringTableRef, key: string): var string {.deprecated.} = + ## retrieves the location at ``t[key]``. If `key` is not in `t`, the + ## ``KeyError`` exception is raised. Use ```[]``` instead. + get(t, key) proc hasKey*(t: StringTableRef, key: string): bool {.rtl, extern: "nst$1".} = ## returns true iff `key` is in the table `t`. @@ -227,7 +232,7 @@ proc `$`*(t: StringTableRef): string {.rtl, extern: "nstDollar".} = result = "{:}" else: result = "{" - for key, val in pairs(t): + for key, val in pairs(t): if result.len > 1: result.add(", ") result.add(key) result.add(": ") @@ -239,6 +244,6 @@ when isMainModule: assert x["k"] == "v" assert x["11"] == "22" assert x["565"] == "67" - x.mget("11") = "23" + x["11"] = "23" assert x["11"] == "23" diff --git a/lib/pure/xmltree.nim b/lib/pure/xmltree.nim index 0bf5b52a4..832cedf47 100644 --- a/lib/pure/xmltree.nim +++ b/lib/pure/xmltree.nim @@ -115,11 +115,16 @@ proc `[]`* (n: XmlNode, i: int): XmlNode {.inline.} = assert n.k == xnElement result = n.s[i] -proc mget* (n: var XmlNode, i: int): var XmlNode {.inline.} = +proc `[]`* (n: var XmlNode, i: int): var XmlNode {.inline.} = ## returns the `i`'th child of `n` so that it can be modified assert n.k == xnElement result = n.s[i] +proc mget* (n: var XmlNode, i: int): var XmlNode {.inline, deprecated.} = + ## returns the `i`'th child of `n` so that it can be modified. Use ```[]``` + ## instead. + n[i] + iterator items*(n: XmlNode): XmlNode {.inline.} = ## iterates over any child of `n`. assert n.k == xnElement @@ -128,7 +133,7 @@ iterator items*(n: XmlNode): XmlNode {.inline.} = iterator mitems*(n: var XmlNode): var XmlNode {.inline.} = ## iterates over any child of `n`. assert n.k == xnElement - for i in 0 .. n.len-1: yield mget(n, i) + for i in 0 .. n.len-1: yield n[i] proc attrs*(n: XmlNode): XmlAttributes {.inline.} = ## gets the attributes belonging to `n`. diff --git a/lib/system/sets.nim b/lib/system/sets.nim index 626d43c33..7826fd4b7 100644 --- a/lib/system/sets.nim +++ b/lib/system/sets.nim @@ -18,7 +18,7 @@ proc countBits32(n: int32): int {.compilerproc.} = v = (v and 0x33333333'i32) +% ((v shr 2'i32) and 0x33333333'i32) result = ((v +% (v shr 4'i32) and 0xF0F0F0F'i32) *% 0x1010101'i32) shr 24'i32 -proc countBits64(n: int64): int {.compilerproc.} = +proc countBits64(n: int64): int {.compilerproc.} = result = countBits32(toU32(n and 0xffff'i64)) + countBits32(toU32(n shr 16'i64)) diff --git a/tests/actiontable/tactiontable.nim b/tests/actiontable/tactiontable.nim index e2f19a099..4560d0f7f 100644 --- a/tests/actiontable/tactiontable.nim +++ b/tests/actiontable/tactiontable.nim @@ -4,24 +4,23 @@ discard """ import tables -proc action1(arg: string) = +proc action1(arg: string) = echo "action 1 ", arg -proc action2(arg: string) = +proc action2(arg: string) = echo "action 2 ", arg -proc action3(arg: string) = +proc action3(arg: string) = echo "action 3 ", arg -proc action4(arg: string) = +proc action4(arg: string) = echo "action 4 ", arg var actionTable = { - "A": action1, - "B": action2, - "C": action3, + "A": action1, + "B": action2, + "C": action3, "D": action4}.toTable actionTable["C"]("arg") - diff --git a/tests/collections/ttables.nim b/tests/collections/ttables.nim index 3a923610e..e4cff7c7e 100644 --- a/tests/collections/ttables.nim +++ b/tests/collections/ttables.nim @@ -22,15 +22,15 @@ const "---00": 346677844, "0": 34404, "1": 344004, - "10": 34484, + "10": 34484, "11": 34474, "12": 789, "19": 34464, - "2": 344774, "20": 34454, + "2": 344774, "20": 34454, "3": 342244, "30": 34141244, "34": 123456, "4": 3412344, "40": 344114, - "5": 341232144, "50": 344490, + "5": 341232144, "50": 344490, "6": 34214544, "60": 344491, "7": 3434544, "70": 344492, "8": 344544, "80": 344497, @@ -46,7 +46,7 @@ block tableTest1: for x in 0..1: for y in 0..1: assert t[(x,y)] == $x & $y - assert($t == + assert($t == "{(x: 0, y: 1): 01, (x: 0, y: 0): 00, (x: 1, y: 0): 10, (x: 1, y: 1): 11}") block tableTest2: @@ -55,14 +55,17 @@ block tableTest2: t["111"] = 1.000043 t["123"] = 1.23 t.del("111") - + t["012"] = 67.9 t["123"] = 1.5 # test overwriting - + assert t["123"] == 1.5 - assert t["111"] == 0.0 # deleted + try: + echo t["111"] # deleted + except KeyError: + discard assert(not hasKey(t, "111")) - + for key, val in items(data): t[key] = val.toFloat for key, val in items(data): assert t[key] == val.toFloat diff --git a/tests/collections/ttablesref.nim b/tests/collections/ttablesref.nim index 16b0d831e..92bc65da3 100644 --- a/tests/collections/ttablesref.nim +++ b/tests/collections/ttablesref.nim @@ -22,15 +22,15 @@ const "---00": 346677844, "0": 34404, "1": 344004, - "10": 34484, + "10": 34484, "11": 34474, "12": 789, "19": 34464, - "2": 344774, "20": 34454, + "2": 344774, "20": 34454, "3": 342244, "30": 34141244, "34": 123456, "4": 3412344, "40": 344114, - "5": 341232144, "50": 344490, + "5": 341232144, "50": 344490, "6": 34214544, "60": 344491, "7": 3434544, "70": 344492, "8": 344544, "80": 344497, @@ -46,7 +46,7 @@ block tableTest1: for x in 0..1: for y in 0..1: assert t[(x,y)] == $x & $y - assert($t == + assert($t == "{(x: 0, y: 1): 01, (x: 0, y: 0): 00, (x: 1, y: 0): 10, (x: 1, y: 1): 11}") block tableTest2: @@ -55,17 +55,20 @@ block tableTest2: t["111"] = 1.000043 t["123"] = 1.23 t.del("111") - + t["012"] = 67.9 t["123"] = 1.5 # test overwriting - + assert t["123"] == 1.5 - assert t["111"] == 0.0 # deleted + try: + echo t["111"] # deleted + except KeyError: + discard assert(not hasKey(t, "111")) - + for key, val in items(data): t[key] = val.toFloat for key, val in items(data): assert t[key] == val.toFloat - + block orderedTableTest1: var t = newOrderedTable[string, int](2) diff --git a/tests/misc/teventemitter.nim b/tests/misc/teventemitter.nim index c1cc3d3a9..7da1a2522 100644 --- a/tests/misc/teventemitter.nim +++ b/tests/misc/teventemitter.nim @@ -13,21 +13,20 @@ proc emit*(emitter: EventEmitter, event: string, args: EventArgs) = for fn in nodes(emitter.events[event]): fn.value(args) #call function with args. -proc on*(emitter: var EventEmitter, event: string, +proc on*(emitter: var EventEmitter, event: string, fn: proc(e: EventArgs) {.nimcall.}) = if not hasKey(emitter.events, event): var list: DoublyLinkedList[proc(e: EventArgs) {.nimcall.}] add(emitter.events, event, list) #if not, add it. - append(emitter.events.mget(event), fn) + append(emitter.events[event], fn) proc initEmitter(emitter: var EventEmitter) = - emitter.events = initTable[string, + emitter.events = initTable[string, DoublyLinkedList[proc(e: EventArgs) {.nimcall.}]]() -var +var ee: EventEmitter args: EventArgs initEmitter(ee) ee.on("print", proc(e: EventArgs) = echo("pie")) ee.emit("print", args) - diff --git a/tests/stdlib/tmget.nim b/tests/stdlib/tmget.nim new file mode 100644 index 000000000..5792b6282 --- /dev/null +++ b/tests/stdlib/tmget.nim @@ -0,0 +1,141 @@ +discard """ + output: '''Can't access 6 +10 +11 +Can't access 6 +10 +11 +Can't access 6 +10 +11 +Can't access 6 +10 +11 +Can't access 6 +10 +11 +Can't access 6 +10 +11 +Can't access 6 +5 +Can't access 6 +10 +11 +Can't access 6 +10 +11''' +""" + +import tables + +block: + var x = initTable[int, int]() + x[5] = 10 + try: + echo x[6] + except KeyError: + echo "Can't access 6" + echo x[5] + x[5] += 1 + var c = x[5] + echo c + +block: + var x = newTable[int, int]() + x[5] = 10 + try: + echo x[6] + except KeyError: + echo "Can't access 6" + echo x[5] + x[5] += 1 + var c = x[5] + echo c + +block: + var x = initOrderedTable[int, int]() + x[5] = 10 + try: + echo x[6] + except KeyError: + echo "Can't access 6" + echo x[5] + x[5] += 1 + var c = x[5] + echo c + +block: + var x = newOrderedTable[int, int]() + x[5] = 10 + try: + echo x[6] + except KeyError: + echo "Can't access 6" + echo x[5] + x[5] += 1 + var c = x[5] + echo c + +block: + var x = initCountTable[int]() + x[5] = 10 + try: + echo x[6] + except KeyError: + echo "Can't access 6" + echo x[5] + x[5] += 1 + var c = x[5] + echo c + +block: + var x = newCountTable[int]() + x[5] = 10 + try: + echo x[6] + except KeyError: + echo "Can't access 6" + echo x[5] + x[5] += 1 + var c = x[5] + echo c + +import sets + +block: + var x = initSet[int]() + x.incl 5 + try: + echo x[6] + except KeyError: + echo "Can't access 6" + echo x[5] + +import critbits + +block: + var x: CritBitTree[int] + x["5"] = 10 + try: + echo x["6"] + except KeyError: + echo "Can't access 6" + echo x["5"] + x["5"] += 1 + var c = x["5"] + echo c + +import strtabs + +block: + var x = newStringTable() + x["5"] = "10" + try: + echo x["6"] + except KeyError: + echo "Can't access 6" + echo x["5"] + x["5"][1] = '1' + var c = x["5"] + echo c diff --git a/tests/stdlib/tmitems.nim b/tests/stdlib/tmitems.nim index 2c0a0392a..f2307aeb3 100644 --- a/tests/stdlib/tmitems.nim +++ b/tests/stdlib/tmitems.nim @@ -132,5 +132,5 @@ block: """) for x in d.mitems: x = <>Student(Name=x.attrs["Name"] & "foo") - d.mget(1).attrs["Name"] = "bar" + d[1].attrs["Name"] = "bar" echo d From 4a471d82310659bcb9683b9e81ba9e4af5e23062 Mon Sep 17 00:00:00 2001 From: def Date: Tue, 31 Mar 2015 00:33:53 +0200 Subject: [PATCH 0118/1263] Don't use deprecated intsets.empty --- compiler/importer.nim | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/compiler/importer.nim b/compiler/importer.nim index d619725db..657f41eab 100644 --- a/compiler/importer.nim +++ b/compiler/importer.nim @@ -121,7 +121,7 @@ proc importAllSymbolsExcept(c: PContext, fromMod: PSym, exceptSet: IntSet) = if s.kind != skEnumField: if s.kind notin ExportableSymKinds: internalError(s.info, "importAllSymbols: " & $s.kind) - if exceptSet.empty or s.name.id notin exceptSet: + if s.name.id notin exceptSet: rawImportSymbol(c, s) s = nextIter(i, fromMod.tab) @@ -138,7 +138,7 @@ proc importForwarded(c: PContext, n: PNode, exceptSet: IntSet) = let s = a.sym if s.kind == skModule: importAllSymbolsExcept(c, s, exceptSet) - elif exceptSet.empty or s.name.id notin exceptSet: + elif s.name.id notin exceptSet: rawImportSymbol(c, s) of nkExportExceptStmt: localError(n.info, errGenerated, "'export except' not implemented") From eb117e239f1fddf862ce02a64434cd0e550f53e6 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Mon, 30 Mar 2015 19:39:06 -0400 Subject: [PATCH 0119/1263] Adjust readme formatting - Add table of contents - Move image to bottom --- README.asciidoc | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/README.asciidoc b/README.asciidoc index c211acda2..0584a6051 100644 --- a/README.asciidoc +++ b/README.asciidoc @@ -1,4 +1,9 @@ -image::web/logo.png["NRE Logo", width=auto, link="https://github.com/flaviut/nre"] += NRE +:toc: +:toclevels: 4 +:toc-placement!: + +toc::[] == What is NRE? @@ -184,3 +189,5 @@ By default, NRE compiles it's own PCRE. If this is undesirable, pass `-d:pcreDynlib` to use whatever dynamic library is available on the system. This may have unexpected consequences if the dynamic library doesn't have certain features enabled. + +image::web/logo.png["NRE Logo", width=auto, link="https://github.com/flaviut/nre"] From c1d0b2403b3f1c9ca487c362658aefb954ee7d96 Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Sat, 4 Apr 2015 16:31:50 -0500 Subject: [PATCH 0120/1263] 15 minutes, bit better messages --- tests/realtimeGC/main.c | 6 +++--- tests/realtimeGC/main.nim | 2 +- tests/realtimeGC/shared.nim | 8 ++++---- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/tests/realtimeGC/main.c b/tests/realtimeGC/main.c index a7ac19dda..bbe80b23d 100644 --- a/tests/realtimeGC/main.c +++ b/tests/realtimeGC/main.c @@ -10,7 +10,7 @@ #include #include -#define RUNTIME (35*60) +#define RUNTIME (15*60) typedef void (*pFunc)(void); @@ -46,11 +46,11 @@ int main(int argc, char* argv[]) while (accumTime < runTime) { for (i = 0; i < 10; i++) count(); - printf("1. sleeping...\n"); + /* printf("1. sleeping...\n"); */ sleep(1); for (i = 0; i < 10; i++) status(); - printf("2. sleeping...\n"); + /* printf("2. sleeping...\n"); */ sleep(1); occupiedMem(); accumTime = time((time_t*)0) - startTime; diff --git a/tests/realtimeGC/main.nim b/tests/realtimeGC/main.nim index 5496cd999..d2d404271 100644 --- a/tests/realtimeGC/main.nim +++ b/tests/realtimeGC/main.nim @@ -6,7 +6,7 @@ discard """ import times import os -const RUNTIME = 35 * 60 # 35 minutes +const RUNTIME = 15 * 60 # 15 minutes when defined(windows): const dllname = "./shared.dll" diff --git a/tests/realtimeGC/shared.nim b/tests/realtimeGC/shared.nim index 345051bb5..c8a70e1ee 100644 --- a/tests/realtimeGC/shared.nim +++ b/tests/realtimeGC/shared.nim @@ -45,17 +45,17 @@ proc status() {.exportc: "status", dynlib.} = var a = getComm1Status() var b = getComm2Status() var str2: string = "$1 COM1: $2 COM2: $3" % [ptt_status, a, b] - #echo(str1) - #echo(str2) + # echo(str1) + # echo(str2) proc count() {.exportc: "count", dynlib.} = var temp: uint64 for i in 0..100_000: temp += 1 gCounter += 1 - #echo("gCounter: ", gCounter) + # echo("gCounter: ", gCounter) proc occupiedMem() {.exportc: "occupiedMem", dynlib.} = - #echo("Occupied Memmory: ", getOccupiedMem()) + echo("Occupied Memmory: ", getOccupiedMem()) discard From bdd8567f50ceb27efa3cc15b6682444a6ba4a4c6 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Thu, 9 Apr 2015 16:02:42 -0400 Subject: [PATCH 0121/1263] Add CircleCI --- circle.yml | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 circle.yml diff --git a/circle.yml b/circle.yml new file mode 100644 index 000000000..b6105af65 --- /dev/null +++ b/circle.yml @@ -0,0 +1,39 @@ +dependencies: + pre: + - | + if [ ! -x ~/nim/bin/nim ]; then + sudo apt-get install gcc + git clone -b devel --depth 1 git://github.com/araq/nim ~/nim/ + git clone -b devel --depth 1 git://github.com/nim-lang/csources ~/nim/csources/ + cd ~/nim/csources; sh build.sh; cd .. + rm -rf csources + bin/nim c koch + ./koch boot -d:release + ln -fs ~/nim/bin/nim ~/bin/nim + else + cd ~/nim + git fetch origin + if ! git merge FETCH_HEAD | grep "Already up-to-date"; then + bin/nim c koch + ./koch boot -d:release + fi + fi + - | + if [ ! -x ~/.nimble/bin/nimble ]; then + git clone --depth 1 git://github.com/nim-lang/nimble ~/nimble/ + cd ~/nimble/ + nim c src/nimble.nim + ./src/nimble install + ln -fs ~/.nimble/bin/nimble ~/bin/nimble + fi + - nimble update + - nimble build + + cache_directories: + - "~/bin/" + - "~/nim/" + - "~/.nimble/" + +test: + override: + - ./runtests.sh From 4e83fc5867f004258c2744ef4cd7d064fad82578 Mon Sep 17 00:00:00 2001 From: Oleh Prypin Date: Thu, 9 Apr 2015 23:14:00 +0300 Subject: [PATCH 0122/1263] Change capture upper bounds to inclusive --- README.asciidoc | 9 ++++----- src/nre.nim | 20 ++++++++++---------- test/captures.nim | 20 ++++++++++---------- test/find.nim | 2 +- test/match.nim | 8 ++++---- 5 files changed, 29 insertions(+), 30 deletions(-) diff --git a/README.asciidoc b/README.asciidoc index 0584a6051..a54a786a4 100644 --- a/README.asciidoc +++ b/README.asciidoc @@ -118,11 +118,10 @@ at that id. If the value is invalid, then behavior is undefined. If the id is - `"abc".match(re"(\w)\w").captures[-1] == "ab"` `captureBounds[]: Option[Slice[int]]` :: gets the bounds of the given capture according to the same rules as the above. If the capture is not -filled, then `None` is returned. The upper bound is exclusive, the lower bound -is inclusive. - - `"abc".match(re"(\w)").captureBounds[0] == 0..1` - - `"abc".match(re"").captureBounds[-1] == 0..0` - - `"abc".match(re"abc").captureBounds[-1] == 0..3` +filled, then `None` is returned. The bounds are both inclusive. + - `"abc".match(re"(\w)").captureBounds[0] == 0 .. 0` + - `"abc".match(re"").captureBounds[-1] == 0 .. -1` + - `"abc".match(re"abc").captureBounds[-1] == 0 .. 2` `match: string` :: the full text of the match. `matchBounds: Slice[int]` :: the bounds of the match, as in `captureBounds[]` `(captureBounds|captures).toTable` :: returns a table with each named capture diff --git a/src/nre.nim b/src/nre.nim index 83b0d9db1..14b15cf5c 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -97,7 +97,7 @@ proc `[]`*(pattern: CaptureBounds, i: int): Option[Slice[int]] = let pattern = RegexMatch(pattern) if pattern.pcreMatchBounds[i + 1].a != -1: let bounds = pattern.pcreMatchBounds[i + 1] - return Some(int(bounds.a) .. int(bounds.b)) + return Some(int(bounds.a) .. int(bounds.b-1)) else: return None[Slice[int]]() @@ -111,7 +111,7 @@ proc `[]`*(pattern: Captures, i: int): string = if bounds: let bounds = bounds.get - return pattern.str.substr(bounds.a, bounds.b-1) + return pattern.str.substr(bounds.a, bounds.b) else: return nil @@ -343,7 +343,7 @@ iterator findIter*(str: string, pattern: Regex, start = 0, endpos = -1): RegexMa var flags = 0 if match and - match.get.matchBounds.a == match.get.matchBounds.b: + match.get.matchBounds.a > match.get.matchBounds.b: # 0-len match flags = pcre.NOTEMPTY_ATSTART or pcre.ANCHORED @@ -363,7 +363,7 @@ iterator findIter*(str: string, pattern: Regex, start = 0, endpos = -1): RegexMa offset += str.runeLenAt(offset) assert(offset <= endpos) else: - offset = match.get.matchBounds.b + offset = match.get.matchBounds.b + 1 yield match.get @@ -387,7 +387,7 @@ proc split*(str: string, pattern: Regex, maxSplit = -1, start = 0): seq[string] result = @[] var lastIdx = start var splits = 0 - var bounds: Slice[int] + var bounds = 0 .. -1 for match in str.findIter(pattern, start = start): # upper bound is exclusive, lower is inclusive: @@ -400,11 +400,11 @@ proc split*(str: string, pattern: Regex, maxSplit = -1, start = 0): seq[string] # "12".split("") would be @["", "1", "2"], but # if we skip an empty first match, it's the correct # @["1", "2"] - if bounds.a < bounds.b or bounds.a > start: + if bounds.a <= bounds.b or bounds.a > start: result.add(str.substr(lastIdx, bounds.a - 1)) splits += 1 - lastIdx = bounds.b + lastIdx = bounds.b + 1 for cap in match.captures: # if there are captures, include them in the result @@ -416,11 +416,11 @@ proc split*(str: string, pattern: Regex, maxSplit = -1, start = 0): seq[string] # "12".split("\b") would be @["1", "2", ""], but # if we skip an empty last match, it's the correct # @["1", "2"] - if bounds.a < bounds.b or bounds.b < str.len: + if bounds.a <= bounds.b or bounds.b < str.high: # last match: Each match takes the previous substring, # but "1 2".split(/ /) needs to return @["1", "2"]. # This handles "2" - result.add(str.substr(bounds.b, str.len - 1)) + result.add(str.substr(bounds.b + 1, str.high)) template replaceImpl(str: string, pattern: Regex, replacement: expr): stmt {.immediate, dirty.} = @@ -435,7 +435,7 @@ template replaceImpl(str: string, pattern: Regex, assert(nextVal != nil) result.add(nextVal) - lastIdx = bounds.b + lastIdx = bounds.b + 1 result.add(str.substr(lastIdx, str.len - 1)) return result diff --git a/test/captures.nim b/test/captures.nim index 4bf3a81ce..24ba021f5 100644 --- a/test/captures.nim +++ b/test/captures.nim @@ -8,17 +8,17 @@ suite "captures": test "capture bounds are correct": let ex1 = re("([0-9])") - check("1 23".find(ex1).matchBounds == 0 .. 1) - check("1 23".find(ex1).captureBounds[0].get == 0 .. 1) - check("1 23".find(ex1, 1).matchBounds == 2 .. 3) - check("1 23".find(ex1, 3).matchBounds == 3 .. 4) + check("1 23".find(ex1).matchBounds == 0 .. 0) + check("1 23".find(ex1).captureBounds[0].get == 0 .. 0) + check("1 23".find(ex1, 1).matchBounds == 2 .. 2) + check("1 23".find(ex1, 3).matchBounds == 3 .. 3) let ex2 = re("()()()()()()()()()()([0-9])") - check("824".find(ex2).captureBounds[0].get == 0 .. 0) - check("824".find(ex2).captureBounds[10].get == 0 .. 1) + check("824".find(ex2).captureBounds[0].get == 0 .. -1) + check("824".find(ex2).captureBounds[10].get == 0 .. 0) let ex3 = re("([0-9]+)") - check("824".find(ex3).captureBounds[0].get == 0 .. 3) + check("824".find(ex3).captureBounds[0].get == 0 .. 2) test "named captures": let ex1 = "foobar".find(re("(?foo)(?bar)")) @@ -31,7 +31,7 @@ suite "captures": test "named capture bounds": let ex1 = "foo".find(re("(?foo)(?bar)?")) - check(ex1.captureBounds["foo"] == Some(0..3)) + check(ex1.captureBounds["foo"] == Some(0..2)) check(ex1.captureBounds["bar"] == None[Slice[int]]()) test "capture count": @@ -42,7 +42,7 @@ suite "captures": test "named capture table": let ex1 = "foo".find(re("(?foo)(?bar)?")) check(ex1.captures.toTable == {"foo" : "foo", "bar" : nil}.toTable()) - check(ex1.captureBounds.toTable == {"foo" : Some(0..3), "bar" : None[Slice[int]]()}.toTable()) + check(ex1.captureBounds.toTable == {"foo" : Some(0..2), "bar" : None[Slice[int]]()}.toTable()) check(ex1.captures.toTable("") == {"foo" : "foo", "bar" : ""}.toTable()) let ex2 = "foobar".find(re("(?foo)(?bar)?")) @@ -51,7 +51,7 @@ suite "captures": test "capture sequence": let ex1 = "foo".find(re("(?foo)(?bar)?")) check(ex1.captures.toSeq == @["foo", nil]) - check(ex1.captureBounds.toSeq == @[Some(0..3), None[Slice[int]]()]) + check(ex1.captureBounds.toSeq == @[Some(0..2), None[Slice[int]]()]) check(ex1.captures.toSeq("") == @["foo", ""]) let ex2 = "foobar".find(re("(?foo)(?bar)?")) diff --git a/test/find.nim b/test/find.nim index b4be08e88..8ab70fb42 100644 --- a/test/find.nim +++ b/test/find.nim @@ -10,7 +10,7 @@ suite "find": test "find bounds": check(toSeq(findIter("1 2 3 4 5 ", re" ")).map( proc (a: RegexMatch): Slice[int] = a.matchBounds - ) == @[1..2, 3..4, 5..6, 7..8, 9..10]) + ) == @[1..1, 3..3, 5..5, 7..7, 9..9]) test "overlapping find": check("222".findAll(re"22") == @["22"]) diff --git a/test/match.nim b/test/match.nim index 277e8b3b0..6cc76643c 100644 --- a/test/match.nim +++ b/test/match.nim @@ -9,9 +9,9 @@ suite "match": check("abc".match(re"(\w)").captures[0] == "a") check("abc".match(re"(?\w)").captures["letter"] == "a") check("abc".match(re"(\w)\w").captures[-1] == "ab") - check("abc".match(re"(\w)").captureBounds[0].get == 0..1) - check("abc".match(re"").captureBounds[-1].get == 0..0) - check("abc".match(re"abc").captureBounds[-1].get == 0..3) + check("abc".match(re"(\w)").captureBounds[0].get == 0 .. 0) + check("abc".match(re"").captureBounds[-1].get == 0 .. -1) + check("abc".match(re"abc").captureBounds[-1].get == 0 .. 2) test "match test cases": - check("123".match(re"").matchBounds == 0..0) + check("123".match(re"").matchBounds == 0 .. -1) From 7e44c08270004a7783e130e5b43dbca5d9a10245 Mon Sep 17 00:00:00 2001 From: Oleh Prypin Date: Thu, 9 Apr 2015 23:42:11 +0300 Subject: [PATCH 0123/1263] Change endpos default from -1 to int.high --- README.asciidoc | 10 +++++----- src/nre.nim | 14 +++++++------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/README.asciidoc b/README.asciidoc index a54a786a4..dfdc305fe 100644 --- a/README.asciidoc +++ b/README.asciidoc @@ -29,24 +29,24 @@ provides in its standard library is inadequate: === Operations [[proc-find]] -==== find(string, Regex, start = 0, endpos = -1): RegexMatch +==== find(string, Regex, start = 0, endpos = int.high): RegexMatch Finds the given pattern in the string between the end and start positions. `start` :: The start point at which to start matching. `|abc` is `0`; `a|bc` is `1` -`endpos` :: The maximum index for a match; `-1` means the end of the string, - otherwise it's an exclusive upper bound. +`endpos` :: The maximum index for a match; `int.high` means the end of the + string, otherwise it's an exclusive upper bound. [[proc-match]] -==== match(string, Regex, start = 0, endpos = -1): RegexMatch +==== match(string, Regex, start = 0, endpos = int.high): RegexMatch Like link:#proc-find[`find(...)`], but anchored to the start of the string. This means that `"foo".match(re"f") == true`, but `"foo".match(re"o") == false`. [[iter-find]] -==== iterator findIter(string, Regex, start = 0, endpos = -1): RegexMatch +==== iterator findIter(string, Regex, start = 0, endpos = int.high): RegexMatch Works the same as link:#proc-find[`find(...)`], but finds every non-overlapping match. `"2222".find(re"22")` is `"22", "22"`, not `"22", "22", "22"`. diff --git a/src/nre.nim b/src/nre.nim index 14b15cf5c..a9bbc31d5 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -311,7 +311,7 @@ proc matchImpl(str: string, pattern: Regex, start, endpos: int, flags: int): Opt result.pcreMatchBounds = newSeq[Slice[cint]](ceil(vecsize / 2).int) result.pcreMatchBounds.setLen(vecsize div 3) - let strlen = if endpos == -1: str.len else: endpos + let strlen = if endpos == int.high: str.len else: endpos let execRet = pcre.exec(pattern.pcreObj, pattern.pcreExtra, @@ -328,14 +328,14 @@ proc matchImpl(str: string, pattern: Regex, start, endpos: int, flags: int): Opt else: raise newException(AssertionError, "Internal error: errno " & $execRet) -proc match*(str: string, pattern: Regex, start = 0, endpos = -1): Option[RegexMatch] = +proc match*(str: string, pattern: Regex, start = 0, endpos = int.high): Option[RegexMatch] = return str.matchImpl(pattern, start, endpos, pcre.ANCHORED) -iterator findIter*(str: string, pattern: Regex, start = 0, endpos = -1): RegexMatch = +iterator findIter*(str: string, pattern: Regex, start = 0, endpos = int.high): RegexMatch = # see pcredemo for explaination let matchesCrLf = pattern.matchesCrLf() let unicode = (getinfo[cint](pattern, pcre.INFO_OPTIONS) and pcre.UTF8) > 0 - let endpos = if endpos == -1: str.len else: endpos + let endpos = if endpos == int.high: str.len else: endpos var offset = start var match: Option[RegexMatch] @@ -371,14 +371,14 @@ iterator findIter*(str: string, pattern: Regex, start = 0, endpos = -1): RegexMa # do while break -proc find*(str: string, pattern: Regex, start = 0, endpos = -1): Option[RegexMatch] = +proc find*(str: string, pattern: Regex, start = 0, endpos = int.high): Option[RegexMatch] = ## Returns a `RegexMatch` if there is a match between `start` and `endpos`, otherwise ## it returns nil. ## - ## if `endpos == -1`, then `endpos = str.len` + ## if `endpos == int.high`, then `endpos = str.len` return str.matchImpl(pattern, start, endpos, 0) -proc findAll*(str: string, pattern: Regex, start = 0, endpos = -1): seq[string] = +proc findAll*(str: string, pattern: Regex, start = 0, endpos = int.high): seq[string] = result = @[] for match in str.findIter(pattern, start, endpos): result.add(match.match) From 2f0375c4c814ffec2dcad38bd576e288fb81c4f3 Mon Sep 17 00:00:00 2001 From: Oleh Prypin Date: Thu, 9 Apr 2015 23:49:26 +0300 Subject: [PATCH 0124/1263] Change endpos to inclusive --- README.asciidoc | 2 +- src/nre.nim | 12 ++++++------ test/match.nim | 7 ++++--- 3 files changed, 11 insertions(+), 10 deletions(-) diff --git a/README.asciidoc b/README.asciidoc index dfdc305fe..26a9c6616 100644 --- a/README.asciidoc +++ b/README.asciidoc @@ -36,7 +36,7 @@ Finds the given pattern in the string between the end and start positions. `start` :: The start point at which to start matching. `|abc` is `0`; `a|bc` is `1` `endpos` :: The maximum index for a match; `int.high` means the end of the - string, otherwise it's an exclusive upper bound. + string, otherwise it's an inclusive upper bound. [[proc-match]] ==== match(string, Regex, start = 0, endpos = int.high): RegexMatch diff --git a/src/nre.nim b/src/nre.nim index a9bbc31d5..af5dab785 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -311,7 +311,7 @@ proc matchImpl(str: string, pattern: Regex, start, endpos: int, flags: int): Opt result.pcreMatchBounds = newSeq[Slice[cint]](ceil(vecsize / 2).int) result.pcreMatchBounds.setLen(vecsize div 3) - let strlen = if endpos == int.high: str.len else: endpos + let strlen = if endpos == int.high: str.len else: endpos+1 let execRet = pcre.exec(pattern.pcreObj, pattern.pcreExtra, @@ -335,7 +335,7 @@ iterator findIter*(str: string, pattern: Regex, start = 0, endpos = int.high): R # see pcredemo for explaination let matchesCrLf = pattern.matchesCrLf() let unicode = (getinfo[cint](pattern, pcre.INFO_OPTIONS) and pcre.UTF8) > 0 - let endpos = if endpos == int.high: str.len else: endpos + let strlen = if endpos == int.high: str.len else: endpos+1 var offset = start var match: Option[RegexMatch] @@ -361,13 +361,13 @@ iterator findIter*(str: string, pattern: Regex, start = 0, endpos = int.high): R elif unicode: # XXX what about invalid unicode? offset += str.runeLenAt(offset) - assert(offset <= endpos) + assert(offset <= strlen) else: offset = match.get.matchBounds.b + 1 yield match.get - if offset >= endpos: + if offset >= strlen: # do while break @@ -390,11 +390,11 @@ proc split*(str: string, pattern: Regex, maxSplit = -1, start = 0): seq[string] var bounds = 0 .. -1 for match in str.findIter(pattern, start = start): - # upper bound is exclusive, lower is inclusive: + # bounds are inclusive: # # 0123456 # ^^^ - # (1, 4) + # (1, 3) bounds = match.matchBounds # "12".split("") would be @["", "1", "2"], but diff --git a/test/match.nim b/test/match.nim index 6cc76643c..16fb931c0 100644 --- a/test/match.nim +++ b/test/match.nim @@ -1,9 +1,10 @@ include nre, unittest, optional_t.nonstrict suite "match": - test "upper bound must be exclusive": - check("abc".match(re"abc", endpos = 0) == None[RegexMatch]()) - check("abc".match(re"abc", endpos = 3) != None[RegexMatch]()) + test "upper bound must be inclusive": + check("abc".match(re"abc", endpos = -1) == None[RegexMatch]()) + check("abc".match(re"abc", endpos = 1) == None[RegexMatch]()) + check("abc".match(re"abc", endpos = 2) != None[RegexMatch]()) test "match examples": check("abc".match(re"(\w)").captures[0] == "a") From 1fe69b94c9bc4ace9b4f0a6c105ffd4d12b877b9 Mon Sep 17 00:00:00 2001 From: Oleh Prypin Date: Fri, 10 Apr 2015 00:19:00 +0300 Subject: [PATCH 0125/1263] Make splitting an empty string give 1 empty result --- src/nre.nim | 2 +- test/split.nim | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/nre.nim b/src/nre.nim index af5dab785..f9c6b3509 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -387,7 +387,7 @@ proc split*(str: string, pattern: Regex, maxSplit = -1, start = 0): seq[string] result = @[] var lastIdx = start var splits = 0 - var bounds = 0 .. -1 + var bounds = 0 .. 0 for match in str.findIter(pattern, start = start): # bounds are inclusive: diff --git a/test/split.nim b/test/split.nim index 62b88427b..0f4e8d24a 100644 --- a/test/split.nim +++ b/test/split.nim @@ -7,7 +7,7 @@ suite "string splitting": check("1 2 ".split(re(" ")) == @["1", "", "2", "", ""]) check("1 2".split(re(" ")) == @["1", "2"]) check("foo".split(re("foo")) == @["", ""]) - check("".split(re"foo") == newSeq[string]()) + check("".split(re"foo") == @[""]) test "captured patterns": check("12".split(re"(\d)") == @["", "1", "", "2", ""]) From 16577f816749859f8d169ffbdd4415ca4747e75a Mon Sep 17 00:00:00 2001 From: Oleh Prypin Date: Fri, 10 Apr 2015 11:20:05 +0300 Subject: [PATCH 0126/1263] Fix zero-length matches for multibyte characters --- src/nre.nim | 6 +++--- test/find.nim | 4 +++- test/misc.nim | 1 - test/split.nim | 2 ++ 4 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/nre.nim b/src/nre.nim index f9c6b3509..b601d8222 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -352,16 +352,16 @@ iterator findIter*(str: string, pattern: Regex, start = 0, endpos = int.high): R if match.isNone: # either the end of the input or the string # cannot be split here - offset += 1 - if matchesCrLf and offset < (str.len - 1) and str[offset] == '\r' and str[offset + 1] == '\l': # if PCRE treats CrLf as newline, skip both at the same time - offset += 1 + offset += 2 elif unicode: # XXX what about invalid unicode? offset += str.runeLenAt(offset) assert(offset <= strlen) + else: + offset += 1 else: offset = match.get.matchBounds.b + 1 diff --git a/test/find.nim b/test/find.nim index 8ab70fb42..c138c2b28 100644 --- a/test/find.nim +++ b/test/find.nim @@ -19,4 +19,6 @@ suite "find": test "len 0 find": check("".findAll(re"\ ") == newSeq[string]()) check("".findAll(re"") == @[""]) - check("word word".findAll(nre.re"\b") == @["", "", "", ""]) + check("word word".findAll(re"\b") == @["", "", "", ""]) + check("word\r\lword".findAll(re(r"$", "m")) == @["", ""]) + check("слово слово".findAll(re(r"\b", "uW")) == @["", "", "", ""]) diff --git a/test/misc.nim b/test/misc.nim index 8ec0ea878..a515db889 100644 --- a/test/misc.nim +++ b/test/misc.nim @@ -4,4 +4,3 @@ suite "Misc tests": test "unicode": check("".find(re("", "8")).match == "") check("перевірка".replace(re(r"\w", "uW"), "") == "") - diff --git a/test/split.nim b/test/split.nim index 0f4e8d24a..fc2bbe1b4 100644 --- a/test/split.nim +++ b/test/split.nim @@ -21,6 +21,8 @@ suite "string splitting": check("12345".split(re("")) == @["1", "2", "3", "4", "5"]) check("".split(re"") == newSeq[string]()) check("word word".split(re"\b") == @["word", " ", "word"]) + check("word\r\lword".split(re(r"$", "m")) == @["word", "\r\lword"]) + check("слово слово".split(re(r"(\b)", "uW")) == @["", "слово", "", " ", "", "слово", ""]) test "perl split tests": check("forty-two" .split(re"") .join(",") == "f,o,r,t,y,-,t,w,o") From e6d662e6b96edbe61eea7d1cce43893566c28039 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Fri, 10 Apr 2015 13:18:08 -0400 Subject: [PATCH 0127/1263] Fix potential buffer overflow Under certain circumstances, it would be possible for a too-large number sent cause a buffer overflow by passing a too-large endpos. --- src/nre.nim | 1 + 1 file changed, 1 insertion(+) diff --git a/src/nre.nim b/src/nre.nim index b601d8222..a222da6c0 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -312,6 +312,7 @@ proc matchImpl(str: string, pattern: Regex, start, endpos: int, flags: int): Opt result.pcreMatchBounds.setLen(vecsize div 3) let strlen = if endpos == int.high: str.len else: endpos+1 + doAssert(strlen <= str.len) # don't want buffer overflows let execRet = pcre.exec(pattern.pcreObj, pattern.pcreExtra, From 62a8ab9006413b9a74db75aacdecc9dc463088ff Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Fri, 10 Apr 2015 13:54:24 -0400 Subject: [PATCH 0128/1263] Throw an exception when replacing with a nil value --- README.asciidoc | 2 ++ src/private/util.nim | 71 ++++++++++++++++++++++++-------------------- test/replace.nim | 4 +++ 3 files changed, 45 insertions(+), 32 deletions(-) diff --git a/README.asciidoc b/README.asciidoc index 26a9c6616..c307cc153 100644 --- a/README.asciidoc +++ b/README.asciidoc @@ -95,6 +95,8 @@ If `sub` is a string, the syntax is as follows: - `$#` - first capture - `$0` - full match +If a given capture is missing, a `ValueError` exception is thrown. + [[proc-escapere]] ==== escapeRe(string): string diff --git a/src/private/util.nim b/src/private/util.nim index 72be023b2..00fd40fac 100644 --- a/src/private/util.nim +++ b/src/private/util.nim @@ -9,6 +9,12 @@ proc fget*[K, V](self: Table[K, V], key: K): V = const Ident = {'a'..'z', 'A'..'Z', '0'..'9', '_', '\128'..'\255'} const StartIdent = Ident - {'0'..'9'} +proc checkNil(arg: string): string = + if arg == nil: + raise newException(ValueError, "Cannot use nil capture") + else: + return arg + template formatStr*(howExpr, namegetter, idgetter: expr): expr = let how = howExpr var val = newStringOfCap(how.len) @@ -19,37 +25,38 @@ template formatStr*(howExpr, namegetter, idgetter: expr): expr = if how[i] != '$': val.add(how[i]) i += 1 - elif how[i + 1] == '$': - val.add('$') - i += 2 - elif how[i + 1] == '#': - var id {.inject.} = lastNum - val.add(idgetter) - lastNum += 1 - i += 2 - elif how[i + 1] in {'0'..'9'}: - i += 1 - var id {.inject.} = 0 - while i < how.len and how[i] in {'0'..'9'}: - id += (id * 10) + (ord(how[i]) - ord('0')) - i += 1 - val.add(idgetter) - lastNum = id + 1 - elif how[i + 1] in StartIdent: - i += 1 - var name {.inject.} = "" - while i < how.len and how[i] in Ident: - name.add(how[i]) - i += 1 - val.add(namegetter) - elif how[i + 1] == '{': - i += 2 - var name {.inject.} = "" - while i < how.len and how[i] != '}': - name.add(how[i]) - i += 1 - i += 1 - val.add(namegetter) else: - raise newException(Exception, "Syntax error in format string at " & $i) + if how[i + 1] == '$': + val.add('$') + i += 2 + elif how[i + 1] == '#': + var id {.inject.} = lastNum + val.add(checkNil(idgetter)) + lastNum += 1 + i += 2 + elif how[i + 1] in {'0'..'9'}: + i += 1 + var id {.inject.} = 0 + while i < how.len and how[i] in {'0'..'9'}: + id += (id * 10) + (ord(how[i]) - ord('0')) + i += 1 + val.add(checkNil(idgetter)) + lastNum = id + 1 + elif how[i + 1] in StartIdent: + i += 1 + var name {.inject.} = "" + while i < how.len and how[i] in Ident: + name.add(how[i]) + i += 1 + val.add(checkNil(namegetter)) + elif how[i + 1] == '{': + i += 2 + var name {.inject.} = "" + while i < how.len and how[i] != '}': + name.add(how[i]) + i += 1 + i += 1 + val.add(checkNil(namegetter)) + else: + raise newException(Exception, "Syntax error in format string at " & $i) val diff --git a/test/replace.nim b/test/replace.nim index f2fad803d..4e0b6e372 100644 --- a/test/replace.nim +++ b/test/replace.nim @@ -14,3 +14,7 @@ suite "replace": check("123".replace(re"(\d)(\d)", "$#$#") == "123") check("123".replace(re"(?\d)(\d)", "$foo$#$#") == "1123") check("123".replace(re"(?\d)(\d)", "${foo}$#$#") == "1123") + + test "replacing missing captures should throw instead of segfaulting": + expect ValueError: discard "ab".replace(re"(a)|(b)", "$1$2") + expect ValueError: discard "b".replace(re"(a)?(b)", "$1$2") From 4b42ddfdfa2e13755cb790467717d4f447db84ce Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Fri, 10 Apr 2015 14:01:05 -0400 Subject: [PATCH 0129/1263] Fix result shadowing warning --- src/nre.nim | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/nre.nim b/src/nre.nim index a222da6c0..f22164c1b 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -302,14 +302,14 @@ proc re*(pattern: string, options = ""): Regex = initRegex(pattern, options) # Operations {{{ proc matchImpl(str: string, pattern: Regex, start, endpos: int, flags: int): Option[RegexMatch] = - var result = RegexMatch(pattern : pattern, str : str) + var myResult = RegexMatch(pattern : pattern, str : str) # See PCRE man pages. # 2x capture count to make room for start-end pairs # 1x capture count as slack space for PCRE let vecsize = (pattern.captureCount() + 1) * 3 # div 2 because each element is 2 cints long - result.pcreMatchBounds = newSeq[Slice[cint]](ceil(vecsize / 2).int) - result.pcreMatchBounds.setLen(vecsize div 3) + myResult.pcreMatchBounds = newSeq[Slice[cint]](ceil(vecsize / 2).int) + myResult.pcreMatchBounds.setLen(vecsize div 3) let strlen = if endpos == int.high: str.len else: endpos+1 doAssert(strlen <= str.len) # don't want buffer overflows @@ -320,10 +320,10 @@ proc matchImpl(str: string, pattern: Regex, start, endpos: int, flags: int): Opt cint(strlen), cint(start), cint(flags), - cast[ptr cint](addr result.pcreMatchBounds[0]), + cast[ptr cint](addr myResult.pcreMatchBounds[0]), cint(vecsize)) if execRet >= 0: - return Some(result) + return Some(myResult) elif execRet == pcre.ERROR_NOMATCH: return None[RegexMatch]() else: From 0dc86145ea4ac2a0fad2b4b3625361ade4ed4970 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 11 Apr 2015 08:51:33 -0400 Subject: [PATCH 0130/1263] Convert readme to RST --- README.asciidoc | 194 ---------------------------------- README.rst | 269 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 269 insertions(+), 194 deletions(-) delete mode 100644 README.asciidoc create mode 100644 README.rst diff --git a/README.asciidoc b/README.asciidoc deleted file mode 100644 index c307cc153..000000000 --- a/README.asciidoc +++ /dev/null @@ -1,194 +0,0 @@ -= NRE -:toc: -:toclevels: 4 -:toc-placement!: - -toc::[] - -== What is NRE? - -A regular expression library for Nim using PCRE to do the hard work. - -== Why? - -The http://nim-lang.org/re.html[re.nim] module that http://nim-lang.org/[Nim] -provides in its standard library is inadequate: - - - It provides only a limited number of captures, while the underling library - (PCRE) allows an unlimited number. - - Instead of having one proc that returns both the bounds and substring, it - has one for the bounds and another for the substring. - - If the splitting regex is empty (`""`), then it returns the input string - instead of following https://ideone.com/dDMjmz[Perl], - http://jsfiddle.net/xtcbxurg/[Javascript], and - https://ideone.com/hYJuJ5[Java]'s precedent of returning a list of each - character (`"123".split(re"") == @["1", "2", "3"]`). - -== Documentation - -=== Operations - -[[proc-find]] -==== find(string, Regex, start = 0, endpos = int.high): RegexMatch - -Finds the given pattern in the string between the end and start positions. - -`start` :: The start point at which to start matching. `|abc` is `0`; `a|bc` - is `1` -`endpos` :: The maximum index for a match; `int.high` means the end of the - string, otherwise it's an inclusive upper bound. - -[[proc-match]] -==== match(string, Regex, start = 0, endpos = int.high): RegexMatch - -Like link:#proc-find[`find(...)`], but anchored to the start of the string. -This means that `"foo".match(re"f") == true`, but `"foo".match(re"o") == -false`. - -[[iter-find]] -==== iterator findIter(string, Regex, start = 0, endpos = int.high): RegexMatch - -Works the same as link:#proc-find[`find(...)`], but finds every non-overlapping -match. `"2222".find(re"22")` is `"22", "22"`, not `"22", "22", "22"`. - -Arguments are the same as link:#proc-find[`find(...)`] - -Variants: - - - `proc findAll(...)` returns a `seq[string]` - -[[proc-split]] -==== split(string, Regex, maxsplit = -1, start = 0): seq[string] - -Splits the string with the given regex. This works according to the rules that -Perl and Javascript use: - - - If the match is zero-width, then the string is still split: - `"123".split(r"") == @["1", "2", "3"]`. - - If the pattern has a capture in it, it is added after the string split: - `"12".split(re"(\d)") == @["", "1", "", "2", ""]`. - - If `maxsplit != -1`, then the string will only be split `maxsplit - 1` - times. This means that there will be `maxsplit` strings in the output seq. - `"1.2.3".split(re"\.", maxsplit = 2) == @["1", "2.3"]` - -`start` behaves the same as in link:#proc-find[`find(...)`]. - -[[proc-replace]] -==== replace(string, Regex, sub): string - -Replaces each match of Regex in the string with `sub`, which should never be -or return `nil`. - -If `sub` is a `proc (RegexMatch): string`, then it is executed with each match -and the return value is the replacement value. - -If `sub` is a `proc (string): string`, then it is executed with the full text -of the match and and the return value is the replacement value. - -If `sub` is a string, the syntax is as follows: - -- `$$` - literal `$` -- `$123` - capture number `123` -- `$foo` - named capture `foo` -- `${foo}` - same as above -- `$1$#` - first and second captures -- `$#` - first capture -- `$0` - full match - -If a given capture is missing, a `ValueError` exception is thrown. - -[[proc-escapere]] -==== escapeRe(string): string - -Escapes the string so it doesn't match any special characters. Incompatible -with the Extra flag (`X`). - -=== Option[RegexMatch] - -Represents the result of an execution. On failure, it is `None[RegexMatch]`, -but if you want automated derefrence, import `optional_t.nonstrict`. The -available fields are as follows: - -`pattern: Regex` :: the pattern that is being matched -`str: string` :: the string that was matched against -`captures[]: string` :: the string value of whatever was captured -at that id. If the value is invalid, then behavior is undefined. If the id is -`-1`, then the whole match is returned. If the given capture was not matched, -`nil` is returned. - - `"abc".match(re"(\w)").captures[0] == "a"` - - `"abc".match(re"(?\w)").captures["letter"] == "a"` - - `"abc".match(re"(\w)\w").captures[-1] == "ab"` -`captureBounds[]: Option[Slice[int]]` :: gets the bounds of the -given capture according to the same rules as the above. If the capture is not -filled, then `None` is returned. The bounds are both inclusive. - - `"abc".match(re"(\w)").captureBounds[0] == 0 .. 0` - - `"abc".match(re"").captureBounds[-1] == 0 .. -1` - - `"abc".match(re"abc").captureBounds[-1] == 0 .. 2` -`match: string` :: the full text of the match. -`matchBounds: Slice[int]` :: the bounds of the match, as in `captureBounds[]` -`(captureBounds|captures).toTable` :: returns a table with each named capture -as a key. -`(captureBounds|captures).toSeq` :: returns all the captures by their number. -`$: string` :: same as `match` - -=== Pattern - -Represents the pattern that things are matched against, constructed with -`re(string, string)`. Examples: `re"foo"`, `re(r"foo # comment", -"x")`, `re"(?x)(*ANYCRLF)foo # comment"`. -For more details on the leading option groups, see the -link:http://man7.org/linux/man-pages/man3/pcresyntax.3.html#OPTION_SETTING[Option Setting] -and the -link:http://man7.org/linux/man-pages/man3/pcresyntax.3.html#NEWLINE_CONVENTION[Newline Convention] -sections of the -link:http://man7.org/linux/man-pages/man3/pcresyntax.3.html[PCRE syntax manual]. - -`pattern: string` :: the string that was used to create the pattern. -`captureCount: int` :: the number of captures that the pattern has. -`captureNameId: Table[string, int]` :: a table from the capture names to - their numeric id. - -==== Flags - - `8` - treat both the pattern and subject as UTF8 - - `9` - prevents the pattern from being interpreted as UTF, no matter what - - `A` - as if the pattern had a `^` at the beginning - - `E` - DOLLAR_ENDONLY - - `f` - fails if there is not a match on the first line - - `i` - case insensitive - - `m` - multi-line, `^` and `$` match the beginning and end of lines, not of the - subject string - - `N` - turn off auto-capture, `(?foo)` is necessary to capture. - - `s` - `.` matches newline - - `U` - expressions are not greedy by default. `?` can be added to a qualifier - to make it greedy. - - `u` - same as `8` - - `W` - Unicode character properties; `\w` matches `к`. - - `X` - "Extra", character escapes without special meaning (`\w` vs. `\a`) are - errors - - `x` - extended, comments (`#`) and newlines are ignored (extended) - - `Y` - pcre.NO_START_OPTIMIZE, - - `` - newlines are separated by `\r` - - `` - newlines are separated by `\r\n` (Windows default) - - `` - newlines are separated by `\n` (UNIX default) - - `` - newlines are separated by any of the above - - `` - newlines are separated by any of the above and Unicode newlines: -[quote, , man pcre] -____ -single characters VT (vertical tab, U+000B), FF (form feed, U+000C), NEL -(next line, U+0085), LS (line separator, U+2028), and PS (paragraph -separator, U+2029). For the 8-bit library, the last two are recognized -only in UTF-8 mode. -____ - - `` - `\R` matches CR, LF, or CRLF - - `` - `\R` matches any unicode newline - - `` - Javascript compatibility - - `` - turn off studying; study is enabled by deafault - -== Other Notes - -By default, NRE compiles it's own PCRE. If this is undesirable, pass -`-d:pcreDynlib` to use whatever dynamic library is available on the system. -This may have unexpected consequences if the dynamic library doesn't have -certain features enabled. - -image::web/logo.png["NRE Logo", width=auto, link="https://github.com/flaviut/nre"] diff --git a/README.rst b/README.rst new file mode 100644 index 000000000..920bbdf27 --- /dev/null +++ b/README.rst @@ -0,0 +1,269 @@ +What is NRE? +============ + +A regular expression library for Nim using PCRE to do the hard work. + +Why? +==== + +The `re.nim `__ module that +`Nim `__ provides in its standard library is +inadequate: + +- It provides only a limited number of captures, while the underling + library (PCRE) allows an unlimited number. + +- Instead of having one proc that returns both the bounds and + substring, it has one for the bounds and another for the substring. + +- If the splitting regex is empty (``""``), then it returns the input + string instead of following `Perl `__, + `Javascript `__, and + `Java `__'s precedent of returning a list + of each character (``"123".split(re"") == @["1", "2", "3"]``). + +Documentation +============= + +Operations +---------- + +find(string, Regex, start = 0, endpos = int.high): RegexMatch +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Finds the given pattern in the string between the end and start +positions. + +``start`` + The start point at which to start matching. ``|abc`` is ``0``; + ``a|bc`` is ``1`` + +``endpos`` + The maximum index for a match; ``int.high`` means the end of the + string, otherwise it’s an inclusive upper bound. + +match(string, Regex, start = 0, endpos = int.high): RegexMatch +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Like ```find(...)`` <#proc-find>`__, but anchored to the start of the +string. This means that ``"foo".match(re"f") == true``, but +``"foo".match(re"o") == +false``. + +iterator findIter(string, Regex, start = 0, endpos = int.high): RegexMatch +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Works the same as ```find(...)`` <#proc-find>`__, but finds every +non-overlapping match. ``"2222".find(re"22")`` is ``"22", "22"``, not +``"22", "22", "22"``. + +Arguments are the same as ```find(...)`` <#proc-find>`__ + +Variants: + +- ``proc findAll(...)`` returns a ``seq[string]`` + +split(string, Regex, maxsplit = -1, start = 0): seq[string] +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Splits the string with the given regex. This works according to the +rules that Perl and Javascript use: + +- If the match is zero-width, then the string is still split: + ``"123".split(r"") == @["1", "2", "3"]``. + +- If the pattern has a capture in it, it is added after the string + split: ``"12".split(re"(\d)") == @["", "1", "", "2", ""]``. + +- If ``maxsplit != -1``, then the string will only be split + ``maxsplit - 1`` times. This means that there will be ``maxsplit`` + strings in the output seq. + ``"1.2.3".split(re"\.", maxsplit = 2) == @["1", "2.3"]`` + +``start`` behaves the same as in ```find(...)`` <#proc-find>`__. + +replace(string, Regex, sub): string +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Replaces each match of Regex in the string with ``sub``, which should +never be or return ``nil``. + +If ``sub`` is a ``proc (RegexMatch): string``, then it is executed with +each match and the return value is the replacement value. + +If ``sub`` is a ``proc (string): string``, then it is executed with the +full text of the match and and the return value is the replacement +value. + +If ``sub`` is a string, the syntax is as follows: + +- ``$$`` - literal ``$`` + +- ``$123`` - capture number ``123`` + +- ``$foo`` - named capture ``foo`` + +- ``${foo}`` - same as above + +- ``$1$#`` - first and second captures + +- ``$#`` - first capture + +- ``$0`` - full match + +If a given capture is missing, a ``ValueError`` exception is thrown. + +escapeRe(string): string +~~~~~~~~~~~~~~~~~~~~~~~~ + +Escapes the string so it doesn’t match any special characters. +Incompatible with the Extra flag (``X``). + +Option[RegexMatch] +------------------ + +Represents the result of an execution. On failure, it is +``None[RegexMatch]``, but if you want automated derefrence, import +``optional_t.nonstrict``. The available fields are as follows: + +``pattern: Regex`` + the pattern that is being matched + +``str: string`` + the string that was matched against + +``captures[]: string`` + the string value of whatever was captured at that id. If the value + is invalid, then behavior is undefined. If the id is ``-1``, then + the whole match is returned. If the given capture was not matched, + ``nil`` is returned. + + - ``"abc".match(re"(\w)").captures[0] == "a"`` + + - ``"abc".match(re"(?\w)").captures["letter"] == "a"`` + + - ``"abc".match(re"(\w)\w").captures[-1] == "ab"`` + +``captureBounds[]: Option[Slice[int]]`` + gets the bounds of the given capture according to the same rules as + the above. If the capture is not filled, then ``None`` is returned. + The bounds are both inclusive. + + - ``"abc".match(re"(\w)").captureBounds[0] == 0 .. 0`` + + - ``"abc".match(re"").captureBounds[-1] == 0 .. -1`` + + - ``"abc".match(re"abc").captureBounds[-1] == 0 .. 2`` + +``match: string`` + the full text of the match. + +``matchBounds: Slice[int]`` + the bounds of the match, as in ``captureBounds[]`` + +``(captureBounds|captures).toTable`` + returns a table with each named capture as a key. + +``(captureBounds|captures).toSeq`` + returns all the captures by their number. + +``$: string`` + same as ``match`` + +Pattern +------- + +Represents the pattern that things are matched against, constructed with +``re(string, string)``. Examples: ``re"foo"``, ``re(r"foo # comment", +"x")``, ``re"(?x)(*ANYCRLF)foo # comment"``. For more details +on the leading option groups, see the `Option +Setting `__ +and the `Newline +Convention `__ +sections of the `PCRE syntax +manual `__. + +``pattern: string`` + the string that was used to create the pattern. + +``captureCount: int`` + the number of captures that the pattern has. + +``captureNameId: Table[string, int]`` + a table from the capture names to their numeric id. + +Flags +~~~~~ + +- ``8`` - treat both the pattern and subject as UTF8 + +- ``9`` - prevents the pattern from being interpreted as UTF, no matter + what + +- ``A`` - as if the pattern had a ``^`` at the beginning + +- ``E`` - DOLLAR\_ENDONLY + +- ``f`` - fails if there is not a match on the first line + +- ``i`` - case insensitive + +- ``m`` - multi-line, ``^`` and ``$`` match the beginning and end of + lines, not of the subject string + +- ``N`` - turn off auto-capture, ``(?foo)`` is necessary to capture. + +- ``s`` - ``.`` matches newline + +- ``U`` - expressions are not greedy by default. ``?`` can be added to + a qualifier to make it greedy. + +- ``u`` - same as ``8`` + +- ``W`` - Unicode character properties; ``\w`` matches ``к``. + +- ``X`` - "Extra", character escapes without special meaning (``\w`` + vs. ``\a``) are errors + +- ``x`` - extended, comments (``#``) and newlines are ignored + (extended) + +- ``Y`` - pcre.NO\_START\_OPTIMIZE, + +- ```` - newlines are separated by ``\r`` + +- ```` - newlines are separated by ``\r\n`` (Windows default) + +- ```` - newlines are separated by ``\n`` (UNIX default) + +- ```` - newlines are separated by any of the above + +- ```` - newlines are separated by any of the above and Unicode + newlines: + + single characters VT (vertical tab, U+000B), FF (form feed, U+000C), + NEL (next line, U+0085), LS (line separator, U+2028), and PS + (paragraph separator, U+2029). For the 8-bit library, the last two + are recognized only in UTF-8 mode. + + — man pcre + +- ```` - ``\R`` matches CR, LF, or CRLF + +- ```` - ``\R`` matches any unicode newline + +- ```` - Javascript compatibility + +- ```` - turn off studying; study is enabled by deafault + +Other Notes +=========== + +By default, NRE compiles it’s own PCRE. If this is undesirable, pass +``-d:pcreDynlib`` to use whatever dynamic library is available on the +system. This may have unexpected consequences if the dynamic library +doesn’t have certain features enabled. + +|"NRE Logo"| + +.. |"NRE Logo"| image:: web/logo.png From bc27d06e394d19661508da260bf5a10bd5eb11bc Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 11 Apr 2015 10:54:38 -0400 Subject: [PATCH 0131/1263] Use docweave The readme file is now generated from the contents of the nre module. --- README.rst | 337 ++++++++++++++++++++++++---------------------------- src/nre.nim | 223 ++++++++++++++++++++++++++++++---- 2 files changed, 355 insertions(+), 205 deletions(-) diff --git a/README.rst b/README.rst index 920bbdf27..7bf58f866 100644 --- a/README.rst +++ b/README.rst @@ -4,7 +4,7 @@ What is NRE? A regular expression library for Nim using PCRE to do the hard work. Why? -==== +---- The `re.nim `__ module that `Nim `__ provides in its standard library is @@ -22,157 +22,20 @@ inadequate: `Java `__'s precedent of returning a list of each character (``"123".split(re"") == @["1", "2", "3"]``). -Documentation -============= -Operations ----------- +Other Notes +----------- -find(string, Regex, start = 0, endpos = int.high): RegexMatch -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +By default, NRE compiles it’s own PCRE. If this is undesirable, pass +``-d:pcreDynlib`` to use whatever dynamic library is available on the +system. This may have unexpected consequences if the dynamic library +doesn’t have certain features enabled. -Finds the given pattern in the string between the end and start -positions. - -``start`` - The start point at which to start matching. ``|abc`` is ``0``; - ``a|bc`` is ``1`` - -``endpos`` - The maximum index for a match; ``int.high`` means the end of the - string, otherwise it’s an inclusive upper bound. - -match(string, Regex, start = 0, endpos = int.high): RegexMatch -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Like ```find(...)`` <#proc-find>`__, but anchored to the start of the -string. This means that ``"foo".match(re"f") == true``, but -``"foo".match(re"o") == -false``. - -iterator findIter(string, Regex, start = 0, endpos = int.high): RegexMatch -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Works the same as ```find(...)`` <#proc-find>`__, but finds every -non-overlapping match. ``"2222".find(re"22")`` is ``"22", "22"``, not -``"22", "22", "22"``. - -Arguments are the same as ```find(...)`` <#proc-find>`__ - -Variants: - -- ``proc findAll(...)`` returns a ``seq[string]`` - -split(string, Regex, maxsplit = -1, start = 0): seq[string] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Splits the string with the given regex. This works according to the -rules that Perl and Javascript use: - -- If the match is zero-width, then the string is still split: - ``"123".split(r"") == @["1", "2", "3"]``. - -- If the pattern has a capture in it, it is added after the string - split: ``"12".split(re"(\d)") == @["", "1", "", "2", ""]``. - -- If ``maxsplit != -1``, then the string will only be split - ``maxsplit - 1`` times. This means that there will be ``maxsplit`` - strings in the output seq. - ``"1.2.3".split(re"\.", maxsplit = 2) == @["1", "2.3"]`` - -``start`` behaves the same as in ```find(...)`` <#proc-find>`__. - -replace(string, Regex, sub): string -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Replaces each match of Regex in the string with ``sub``, which should -never be or return ``nil``. - -If ``sub`` is a ``proc (RegexMatch): string``, then it is executed with -each match and the return value is the replacement value. - -If ``sub`` is a ``proc (string): string``, then it is executed with the -full text of the match and and the return value is the replacement -value. - -If ``sub`` is a string, the syntax is as follows: - -- ``$$`` - literal ``$`` - -- ``$123`` - capture number ``123`` - -- ``$foo`` - named capture ``foo`` - -- ``${foo}`` - same as above - -- ``$1$#`` - first and second captures - -- ``$#`` - first capture - -- ``$0`` - full match - -If a given capture is missing, a ``ValueError`` exception is thrown. - -escapeRe(string): string -~~~~~~~~~~~~~~~~~~~~~~~~ - -Escapes the string so it doesn’t match any special characters. -Incompatible with the Extra flag (``X``). - -Option[RegexMatch] ------------------- - -Represents the result of an execution. On failure, it is -``None[RegexMatch]``, but if you want automated derefrence, import -``optional_t.nonstrict``. The available fields are as follows: - -``pattern: Regex`` - the pattern that is being matched - -``str: string`` - the string that was matched against - -``captures[]: string`` - the string value of whatever was captured at that id. If the value - is invalid, then behavior is undefined. If the id is ``-1``, then - the whole match is returned. If the given capture was not matched, - ``nil`` is returned. - - - ``"abc".match(re"(\w)").captures[0] == "a"`` - - - ``"abc".match(re"(?\w)").captures["letter"] == "a"`` - - - ``"abc".match(re"(\w)\w").captures[-1] == "ab"`` - -``captureBounds[]: Option[Slice[int]]`` - gets the bounds of the given capture according to the same rules as - the above. If the capture is not filled, then ``None`` is returned. - The bounds are both inclusive. - - - ``"abc".match(re"(\w)").captureBounds[0] == 0 .. 0`` - - - ``"abc".match(re"").captureBounds[-1] == 0 .. -1`` - - - ``"abc".match(re"abc").captureBounds[-1] == 0 .. 2`` - -``match: string`` - the full text of the match. - -``matchBounds: Slice[int]`` - the bounds of the match, as in ``captureBounds[]`` - -``(captureBounds|captures).toTable`` - returns a table with each named capture as a key. - -``(captureBounds|captures).toSeq`` - returns all the captures by their number. - -``$: string`` - same as ``match`` - -Pattern -------- +Types +----- +``type Regex* = ref object`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Represents the pattern that things are matched against, constructed with ``re(string, string)``. Examples: ``re"foo"``, ``re(r"foo # comment", "x")``, ``re"(?x)(*ANYCRLF)foo # comment"``. For more details @@ -192,52 +55,34 @@ manual `__. ``captureNameId: Table[string, int]`` a table from the capture names to their numeric id. + Flags -~~~~~ +..... - ``8`` - treat both the pattern and subject as UTF8 - - ``9`` - prevents the pattern from being interpreted as UTF, no matter what - - ``A`` - as if the pattern had a ``^`` at the beginning - - ``E`` - DOLLAR\_ENDONLY - - ``f`` - fails if there is not a match on the first line - - ``i`` - case insensitive - - ``m`` - multi-line, ``^`` and ``$`` match the beginning and end of lines, not of the subject string - - ``N`` - turn off auto-capture, ``(?foo)`` is necessary to capture. - - ``s`` - ``.`` matches newline - - ``U`` - expressions are not greedy by default. ``?`` can be added to a qualifier to make it greedy. - - ``u`` - same as ``8`` - - ``W`` - Unicode character properties; ``\w`` matches ``к``. - - ``X`` - "Extra", character escapes without special meaning (``\w`` vs. ``\a``) are errors - - ``x`` - extended, comments (``#``) and newlines are ignored (extended) - - ``Y`` - pcre.NO\_START\_OPTIMIZE, - - ```` - newlines are separated by ``\r`` - - ```` - newlines are separated by ``\r\n`` (Windows default) - - ```` - newlines are separated by ``\n`` (UNIX default) - - ```` - newlines are separated by any of the above - - ```` - newlines are separated by any of the above and Unicode newlines: @@ -245,25 +90,157 @@ Flags NEL (next line, U+0085), LS (line separator, U+2028), and PS (paragraph separator, U+2029). For the 8-bit library, the last two are recognized only in UTF-8 mode. - — man pcre - ```` - ``\R`` matches CR, LF, or CRLF - - ```` - ``\R`` matches any unicode newline - - ```` - Javascript compatibility - - ```` - turn off studying; study is enabled by deafault -Other Notes -=========== -By default, NRE compiles it’s own PCRE. If this is undesirable, pass -``-d:pcreDynlib`` to use whatever dynamic library is available on the -system. This may have unexpected consequences if the dynamic library -doesn’t have certain features enabled. +``type RegexMatch* = object`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Usually seen as Option[RegexMatch], it represents the result of an +execution. On failure, it is ``None[RegexMatch]``, but if you want +automated derefrence, import ``optional_t.nonstrict``. The available +fields are as follows: -|"NRE Logo"| +``pattern: Regex`` + the pattern that is being matched -.. |"NRE Logo"| image:: web/logo.png +``str: string`` + the string that was matched against + +``captures[]: string`` + the string value of whatever was captured at that id. If the value + is invalid, then behavior is undefined. If the id is ``-1``, then + the whole match is returned. If the given capture was not matched, + ``nil`` is returned. + + - ``"abc".match(re"(\w)").captures[0] == "a"`` + - ``"abc".match(re"(?\w)").captures["letter"] == "a"`` + - ``"abc".match(re"(\w)\w").captures[-1] == "ab"`` + +``captureBounds[]: Option[Slice[int]]`` + gets the bounds of the given capture according to the same rules as + the above. If the capture is not filled, then ``None`` is returned. + The bounds are both inclusive. + + - ``"abc".match(re"(\w)").captureBounds[0] == 0 .. 0`` + - ``"abc".match(re"").captureBounds[-1] == 0 .. -1`` + - ``"abc".match(re"abc").captureBounds[-1] == 0 .. 2`` + +``match: string`` + the full text of the match. + +``matchBounds: Slice[int]`` + the bounds of the match, as in ``captureBounds[]`` + +``(captureBounds|captures).toTable`` + returns a table with each named capture as a key. + +``(captureBounds|captures).toSeq`` + returns all the captures by their number. + +``$: string`` + same as ``match`` + + +``type SyntaxError* = ref object of Exception`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Thrown when there is a syntax error in the +regular expression string passed in + + +``type StudyError* = ref object of Exception`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Thrown when studying the regular expression failes +for whatever reason. The message contains the error +code. + + +Operations +---------- + +``proc match*(str: string, pattern: Regex, start = 0, endpos = int.high): Option[RegexMatch]`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Like ```find(...)`` <#proc-find>`__, but anchored to the start of the +string. This means that ``"foo".match(re"f") == true``, but +``"foo".match(re"o") == false``. + + +``iterator findIter*(str: string, pattern: Regex, start = 0, endpos = int.high): RegexMatch`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Works the same as ```find(...)`` <#proc-find>`__, but finds every +non-overlapping match. ``"2222".find(re"22")`` is ``"22", "22"``, not +``"22", "22", "22"``. + +Arguments are the same as ```find(...)`` <#proc-find>`__ + +Variants: + +- ``proc findAll(...)`` returns a ``seq[string]`` + + +``proc find*(str: string, pattern: Regex, start = 0, endpos = int.high): Option[RegexMatch]`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Finds the given pattern in the string between the end and start +positions. + +``start`` + The start point at which to start matching. ``|abc`` is ``0``; + ``a|bc`` is ``1`` + +``endpos`` + The maximum index for a match; ``int.high`` means the end of the + string, otherwise it’s an inclusive upper bound. + + +``proc split*(str: string, pattern: Regex, maxSplit = -1, start = 0): seq[string]`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Splits the string with the given regex. This works according to the +rules that Perl and Javascript use: + +- If the match is zero-width, then the string is still split: + ``"123".split(r"") == @["1", "2", "3"]``. + +- If the pattern has a capture in it, it is added after the string + split: ``"12".split(re"(\d)") == @["", "1", "", "2", ""]``. + +- If ``maxsplit != -1``, then the string will only be split + ``maxsplit - 1`` times. This means that there will be ``maxsplit`` + strings in the output seq. + ``"1.2.3".split(re"\.", maxsplit = 2) == @["1", "2.3"]`` + +``start`` behaves the same as in ```find(...)`` <#proc-find>`__. + + +``proc replace*(str: string, pattern: Regex, subproc: proc (match: RegexMatch): string): string`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Replaces each match of Regex in the string with ``sub``, which should +never be or return ``nil``. + +If ``sub`` is a ``proc (RegexMatch): string``, then it is executed with +each match and the return value is the replacement value. + +If ``sub`` is a ``proc (string): string``, then it is executed with the +full text of the match and and the return value is the replacement +value. + +If ``sub`` is a string, the syntax is as follows: + +- ``$$`` - literal ``$`` +- ``$123`` - capture number ``123`` +- ``$foo`` - named capture ``foo`` +- ``${foo}`` - same as above +- ``$1$#`` - first and second captures +- ``$#`` - first capture +- ``$0`` - full match + +If a given capture is missing, a ``ValueError`` exception is thrown. + + +``proc escapeRe*(str: string): string`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Escapes the string so it doesn’t match any special characters. +Incompatible with the Extra flag (``X``). diff --git a/src/nre.nim b/src/nre.nim index f22164c1b..cf99c8d5d 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -8,10 +8,104 @@ from math import ceil import optional_t from unicode import runeLenAt + +## What is NRE? +## ============ +## +## A regular expression library for Nim using PCRE to do the hard work. +## +## Why? +## ---- +## +## The `re.nim `__ module that +## `Nim `__ provides in its standard library is +## inadequate: +## +## - It provides only a limited number of captures, while the underling +## library (PCRE) allows an unlimited number. +## +## - Instead of having one proc that returns both the bounds and +## substring, it has one for the bounds and another for the substring. +## +## - If the splitting regex is empty (``""``), then it returns the input +## string instead of following `Perl `__, +## `Javascript `__, and +## `Java `__'s precedent of returning a list +## of each character (``"123".split(re"") == @["1", "2", "3"]``). +## +## +## Other Notes +## ----------- +## +## By default, NRE compiles it’s own PCRE. If this is undesirable, pass +## ``-d:pcreDynlib`` to use whatever dynamic library is available on the +## system. This may have unexpected consequences if the dynamic library +## doesn’t have certain features enabled. + + # Type definitions {{{ type Regex* = ref object - ## Represents a compiled pattern + ## Represents the pattern that things are matched against, constructed with + ## ``re(string, string)``. Examples: ``re"foo"``, ``re(r"foo # comment", + ## "x")``, ``re"(?x)(*ANYCRLF)foo # comment"``. For more details + ## on the leading option groups, see the `Option + ## Setting `__ + ## and the `Newline + ## Convention `__ + ## sections of the `PCRE syntax + ## manual `__. + ## + ## ``pattern: string`` + ## the string that was used to create the pattern. + ## + ## ``captureCount: int`` + ## the number of captures that the pattern has. + ## + ## ``captureNameId: Table[string, int]`` + ## a table from the capture names to their numeric id. + ## + ## + ## Flags + ## ..... + ## + ## - ``8`` - treat both the pattern and subject as UTF8 + ## - ``9`` - prevents the pattern from being interpreted as UTF, no matter + ## what + ## - ``A`` - as if the pattern had a ``^`` at the beginning + ## - ``E`` - DOLLAR\_ENDONLY + ## - ``f`` - fails if there is not a match on the first line + ## - ``i`` - case insensitive + ## - ``m`` - multi-line, ``^`` and ``$`` match the beginning and end of + ## lines, not of the subject string + ## - ``N`` - turn off auto-capture, ``(?foo)`` is necessary to capture. + ## - ``s`` - ``.`` matches newline + ## - ``U`` - expressions are not greedy by default. ``?`` can be added to + ## a qualifier to make it greedy. + ## - ``u`` - same as ``8`` + ## - ``W`` - Unicode character properties; ``\w`` matches ``к``. + ## - ``X`` - "Extra", character escapes without special meaning (``\w`` + ## vs. ``\a``) are errors + ## - ``x`` - extended, comments (``#``) and newlines are ignored + ## (extended) + ## - ``Y`` - pcre.NO\_START\_OPTIMIZE, + ## - ```` - newlines are separated by ``\r`` + ## - ```` - newlines are separated by ``\r\n`` (Windows default) + ## - ```` - newlines are separated by ``\n`` (UNIX default) + ## - ```` - newlines are separated by any of the above + ## - ```` - newlines are separated by any of the above and Unicode + ## newlines: + ## + ## single characters VT (vertical tab, U+000B), FF (form feed, U+000C), + ## NEL (next line, U+0085), LS (line separator, U+2028), and PS + ## (paragraph separator, U+2029). For the 8-bit library, the last two + ## are recognized only in UTF-8 mode. + ## — man pcre + ## + ## - ```` - ``\R`` matches CR, LF, or CRLF + ## - ```` - ``\R`` matches any unicode newline + ## - ```` - Javascript compatibility + ## - ```` - turn off studying; study is enabled by deafault pattern*: string ## not nil pcreObj: ptr pcre.Pcre ## not nil pcreExtra: ptr pcre.ExtraData ## nil @@ -19,7 +113,50 @@ type captureNameToId: Table[string, int] RegexMatch* = object - ## Is returned upon a match. + ## Usually seen as Option[RegexMatch], it represents the result of an + ## execution. On failure, it is ``None[RegexMatch]``, but if you want + ## automated derefrence, import ``optional_t.nonstrict``. The available + ## fields are as follows: + ## + ## ``pattern: Regex`` + ## the pattern that is being matched + ## + ## ``str: string`` + ## the string that was matched against + ## + ## ``captures[]: string`` + ## the string value of whatever was captured at that id. If the value + ## is invalid, then behavior is undefined. If the id is ``-1``, then + ## the whole match is returned. If the given capture was not matched, + ## ``nil`` is returned. + ## + ## - ``"abc".match(re"(\w)").captures[0] == "a"`` + ## - ``"abc".match(re"(?\w)").captures["letter"] == "a"`` + ## - ``"abc".match(re"(\w)\w").captures[-1] == "ab"`` + ## + ## ``captureBounds[]: Option[Slice[int]]`` + ## gets the bounds of the given capture according to the same rules as + ## the above. If the capture is not filled, then ``None`` is returned. + ## The bounds are both inclusive. + ## + ## - ``"abc".match(re"(\w)").captureBounds[0] == 0 .. 0`` + ## - ``"abc".match(re"").captureBounds[-1] == 0 .. -1`` + ## - ``"abc".match(re"abc").captureBounds[-1] == 0 .. 2`` + ## + ## ``match: string`` + ## the full text of the match. + ## + ## ``matchBounds: Slice[int]`` + ## the bounds of the match, as in ``captureBounds[]`` + ## + ## ``(captureBounds|captures).toTable`` + ## returns a table with each named capture as a key. + ## + ## ``(captureBounds|captures).toSeq`` + ## returns all the captures by their number. + ## + ## ``$: string`` + ## same as ``match`` pattern*: Regex ## The regex doing the matching. ## Not nil. str*: string ## The string that was matched against. @@ -52,14 +189,9 @@ proc getinfo[T](pattern: Regex, opt: cint): T = # Regex accessors {{{ proc captureCount*(pattern: Regex): int = - ## Get the maximum number of captures - ## - ## Does not return the number of captured captures return getinfo[int](pattern, pcre.INFO_CAPTURECOUNT) proc captureNameId*(pattern: Regex): Table[string, int] = - ## Returns a map from named capture groups to their numerical - ## identifier return pattern.captureNameToId proc matchesCrLf(pattern: Regex): bool = @@ -90,10 +222,6 @@ proc captureBounds*(pattern: RegexMatch): CaptureBounds = return CaptureBounds(p proc captures*(pattern: RegexMatch): Captures = return Captures(pattern) proc `[]`*(pattern: CaptureBounds, i: int): Option[Slice[int]] = - ## Gets the bounds of the `i`th capture. - ## Undefined behavior if `i` is out of bounds - ## If `i` is a failed optional capture, returns None - ## If `i == -1`, returns the whole match let pattern = RegexMatch(pattern) if pattern.pcreMatchBounds[i + 1].a != -1: let bounds = pattern.pcreMatchBounds[i + 1] @@ -102,10 +230,6 @@ proc `[]`*(pattern: CaptureBounds, i: int): Option[Slice[int]] = return None[Slice[int]]() proc `[]`*(pattern: Captures, i: int): string = - ## gets the `i`th capture - ## Undefined behavior if `i` is out of bounds - ## If `i` is a failed optional capture, returns nil - ## If `i == -1`, returns the whole match let pattern = RegexMatch(pattern) let bounds = pattern.captureBounds[i] @@ -122,12 +246,10 @@ proc matchBounds*(pattern: RegexMatch): Slice[int] = return pattern.captureBounds[-1].get proc `[]`*(pattern: CaptureBounds, name: string): Option[Slice[int]] = - ## Will fail with KeyError if `name` is not a real named capture let pattern = RegexMatch(pattern) return pattern.captureBounds[pattern.pattern.captureNameToId.fget(name)] proc `[]`*(pattern: Captures, name: string): string = - ## Will fail with KeyError if `name` is not a real named capture let pattern = RegexMatch(pattern) return pattern.captures[pattern.pattern.captureNameToId.fget(name)] @@ -140,13 +262,11 @@ template toTableImpl(cond: bool): stmt {.immediate, dirty.} = result[key] = nextVal proc toTable*(pattern: Captures, default: string = nil): Table[string, string] = - ## Gets all the named captures and returns them result = initTable[string, string]() toTableImpl(nextVal == nil) proc toTable*(pattern: CaptureBounds, default = None[Slice[int]]()): Table[string, Option[Slice[int]]] = - ## Gets all the named captures and returns them result = initTable[string, Option[Slice[int]]]() toTableImpl(nextVal.isNone) @@ -174,7 +294,6 @@ proc `$`*(pattern: RegexMatch): string = return pattern.captures[-1] proc `==`*(a, b: Regex): bool = - # name-to-number table is generated at init time, doesn't need to be checked if not a.isNil and not b.isNil: return a.pattern == b.pattern and a.pcreObj == b.pcreObj and @@ -183,8 +302,6 @@ proc `==`*(a, b: Regex): bool = return system.`==`(a, b) proc `==`*(a, b: RegexMatch): bool = - # don't need to compare matchbounds, if pattern and str equal, everything - # else will equal (unless callbacks, maybe? TODO) return a.pattern == b.pattern and a.str == b.str # }}} @@ -330,9 +447,21 @@ proc matchImpl(str: string, pattern: Regex, start, endpos: int, flags: int): Opt raise newException(AssertionError, "Internal error: errno " & $execRet) proc match*(str: string, pattern: Regex, start = 0, endpos = int.high): Option[RegexMatch] = + ## Like ```find(...)`` <#proc-find>`__, but anchored to the start of the + ## string. This means that ``"foo".match(re"f") == true``, but + ## ``"foo".match(re"o") == false``. return str.matchImpl(pattern, start, endpos, pcre.ANCHORED) iterator findIter*(str: string, pattern: Regex, start = 0, endpos = int.high): RegexMatch = + ## Works the same as ```find(...)`` <#proc-find>`__, but finds every + ## non-overlapping match. ``"2222".find(re"22")`` is ``"22", "22"``, not + ## ``"22", "22", "22"``. + ## + ## Arguments are the same as ```find(...)`` <#proc-find>`__ + ## + ## Variants: + ## + ## - ``proc findAll(...)`` returns a ``seq[string]`` # see pcredemo for explaination let matchesCrLf = pattern.matchesCrLf() let unicode = (getinfo[cint](pattern, pcre.INFO_OPTIONS) and pcre.UTF8) > 0 @@ -373,10 +502,16 @@ iterator findIter*(str: string, pattern: Regex, start = 0, endpos = int.high): R break proc find*(str: string, pattern: Regex, start = 0, endpos = int.high): Option[RegexMatch] = - ## Returns a `RegexMatch` if there is a match between `start` and `endpos`, otherwise - ## it returns nil. + ## Finds the given pattern in the string between the end and start + ## positions. ## - ## if `endpos == int.high`, then `endpos = str.len` + ## ``start`` + ## The start point at which to start matching. ``|abc`` is ``0``; + ## ``a|bc`` is ``1`` + ## + ## ``endpos`` + ## The maximum index for a match; ``int.high`` means the end of the + ## string, otherwise it’s an inclusive upper bound. return str.matchImpl(pattern, start, endpos, 0) proc findAll*(str: string, pattern: Regex, start = 0, endpos = int.high): seq[string] = @@ -385,6 +520,21 @@ proc findAll*(str: string, pattern: Regex, start = 0, endpos = int.high): seq[st result.add(match.match) proc split*(str: string, pattern: Regex, maxSplit = -1, start = 0): seq[string] = + ## Splits the string with the given regex. This works according to the + ## rules that Perl and Javascript use: + ## + ## - If the match is zero-width, then the string is still split: + ## ``"123".split(r"") == @["1", "2", "3"]``. + ## + ## - If the pattern has a capture in it, it is added after the string + ## split: ``"12".split(re"(\d)") == @["", "1", "", "2", ""]``. + ## + ## - If ``maxsplit != -1``, then the string will only be split + ## ``maxsplit - 1`` times. This means that there will be ``maxsplit`` + ## strings in the output seq. + ## ``"1.2.3".split(re"\.", maxsplit = 2) == @["1", "2.3"]`` + ## + ## ``start`` behaves the same as in ```find(...)`` <#proc-find>`__. result = @[] var lastIdx = start var splits = 0 @@ -443,6 +593,27 @@ template replaceImpl(str: string, pattern: Regex, proc replace*(str: string, pattern: Regex, subproc: proc (match: RegexMatch): string): string = + ## Replaces each match of Regex in the string with ``sub``, which should + ## never be or return ``nil``. + ## + ## If ``sub`` is a ``proc (RegexMatch): string``, then it is executed with + ## each match and the return value is the replacement value. + ## + ## If ``sub`` is a ``proc (string): string``, then it is executed with the + ## full text of the match and and the return value is the replacement + ## value. + ## + ## If ``sub`` is a string, the syntax is as follows: + ## + ## - ``$$`` - literal ``$`` + ## - ``$123`` - capture number ``123`` + ## - ``$foo`` - named capture ``foo`` + ## - ``${foo}`` - same as above + ## - ``$1$#`` - first and second captures + ## - ``$#`` - first capture + ## - ``$0`` - full match + ## + ## If a given capture is missing, a ``ValueError`` exception is thrown. replaceImpl(str, pattern, subproc(match)) proc replace*(str: string, pattern: Regex, @@ -458,4 +629,6 @@ proc replace*(str: string, pattern: Regex, sub: string): string = let SpecialCharMatcher = re"([\\+*?[^\]$(){}=!<>|:-])" proc escapeRe*(str: string): string = + ## Escapes the string so it doesn’t match any special characters. + ## Incompatible with the Extra flag (``X``). str.replace(SpecialCharMatcher, "\\$1") From 4ce267c08dd8287668b99d546b3679a9b1347d43 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 11 Apr 2015 11:15:51 -0400 Subject: [PATCH 0132/1263] Fix getinfo overflows --- src/nre.nim | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/nre.nim b/src/nre.nim index cf99c8d5d..3ff4bade2 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -189,17 +189,17 @@ proc getinfo[T](pattern: Regex, opt: cint): T = # Regex accessors {{{ proc captureCount*(pattern: Regex): int = - return getinfo[int](pattern, pcre.INFO_CAPTURECOUNT) + return getinfo[cint](pattern, pcre.INFO_CAPTURECOUNT) proc captureNameId*(pattern: Regex): Table[string, int] = return pattern.captureNameToId proc matchesCrLf(pattern: Regex): bool = - let flags = getinfo[cint](pattern, pcre.INFO_OPTIONS) + let flags = uint32(getinfo[culong](pattern, pcre.INFO_OPTIONS)) let newlineFlags = flags and (pcre.NEWLINE_CRLF or pcre.NEWLINE_ANY or pcre.NEWLINE_ANYCRLF) - if newLineFlags > 0: + if newLineFlags > 0u32: return true # get flags from build config @@ -464,7 +464,8 @@ iterator findIter*(str: string, pattern: Regex, start = 0, endpos = int.high): R ## - ``proc findAll(...)`` returns a ``seq[string]`` # see pcredemo for explaination let matchesCrLf = pattern.matchesCrLf() - let unicode = (getinfo[cint](pattern, pcre.INFO_OPTIONS) and pcre.UTF8) > 0 + let unicode = uint32(getinfo[culong](pattern, pcre.INFO_OPTIONS) and + pcre.UTF8) > 0u32 let strlen = if endpos == int.high: str.len else: endpos+1 var offset = start From ec1758509ca4ef24e7470ac11e54d67f4bfcd230 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 11 Apr 2015 14:17:53 -0400 Subject: [PATCH 0133/1263] Add longer flags It is now possible to use longer flags instead of the short one-letter ones. --- src/nre.nim | 43 ++++++++++++++++++++++++++++--------------- test/init.nim | 5 +++++ 2 files changed, 33 insertions(+), 15 deletions(-) diff --git a/src/nre.nim b/src/nre.nim index 3ff4bade2..76a45532b 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -69,26 +69,25 @@ type ## Flags ## ..... ## - ## - ``8`` - treat both the pattern and subject as UTF8 - ## - ``9`` - prevents the pattern from being interpreted as UTF, no matter + ## - ``8``, ``u``, ```` - treat both the pattern and subject as UTF8 + ## - ``9``, ```` - prevents the pattern from being interpreted as UTF, no matter ## what - ## - ``A`` - as if the pattern had a ``^`` at the beginning - ## - ``E`` - DOLLAR\_ENDONLY - ## - ``f`` - fails if there is not a match on the first line - ## - ``i`` - case insensitive - ## - ``m`` - multi-line, ``^`` and ``$`` match the beginning and end of + ## - ``A``, ```` - as if the pattern had a ``^`` at the beginning + ## - ``E``, ```` - DOLLAR\_ENDONLY + ## - ``f``, ```` - fails if there is not a match on the first line + ## - ``i``, ```` - case insensitive + ## - ``m``, ```` - multi-line, ``^`` and ``$`` match the beginning and end of ## lines, not of the subject string - ## - ``N`` - turn off auto-capture, ``(?foo)`` is necessary to capture. - ## - ``s`` - ``.`` matches newline - ## - ``U`` - expressions are not greedy by default. ``?`` can be added to + ## - ``N``, ```` - turn off auto-capture, ``(?foo)`` is necessary to capture. + ## - ``s``, ```` - ``.`` matches newline + ## - ``U``, ```` - expressions are not greedy by default. ``?`` can be added to ## a qualifier to make it greedy. - ## - ``u`` - same as ``8`` - ## - ``W`` - Unicode character properties; ``\w`` matches ``к``. - ## - ``X`` - "Extra", character escapes without special meaning (``\w`` + ## - ``W``, ```` - Unicode character properties; ``\w`` matches ``к``. + ## - ``X``, ```` - "Extra", character escapes without special meaning (``\w`` ## vs. ``\a``) are errors - ## - ``x`` - extended, comments (``#``) and newlines are ignored + ## - ``x``, ```` - extended, comments (``#``) and newlines are ignored ## (extended) - ## - ``Y`` - pcre.NO\_START\_OPTIMIZE, + ## - ``Y``, ```` - pcre.NO\_START\_OPTIMIZE, ## - ```` - newlines are separated by ``\r`` ## - ```` - newlines are separated by ``\r\n`` (Windows default) ## - ```` - newlines are separated by ``\n`` (UNIX default) @@ -310,21 +309,35 @@ proc `==`*(a, b: RegexMatch): bool = # PCRE Options {{{ let Options: Table[string, int] = { "8" : pcre.UTF8, + "utf8" : pcre.UTF8, "9" : pcre.NEVER_UTF, + "no_utf8" : pcre.NEVER_UTF, "A" : pcre.ANCHORED, + "anchored" : pcre.ANCHORED, # "C" : pcre.AUTO_CALLOUT, unsuported XXX "E" : pcre.DOLLAR_ENDONLY, + "dollar_endonly" : pcre.DOLLAR_ENDONLY, "f" : pcre.FIRSTLINE, + "firstline" : pcre.FIRSTLINE, "i" : pcre.CASELESS, + "case_insensitive" : pcre.CASELESS, "m" : pcre.MULTILINE, + "multiline" : pcre.MULTILINE, "N" : pcre.NO_AUTO_CAPTURE, + "no_auto_capture" : pcre.NO_AUTO_CAPTURE, "s" : pcre.DOTALL, + "dotall" : pcre.DOTALL, "U" : pcre.UNGREEDY, + "ungreedy" : pcre.UNGREEDY, "u" : pcre.UTF8, "W" : pcre.UCP, + "ucp" : pcre.UCP, "X" : pcre.EXTRA, + "extra" : pcre.EXTRA, "x" : pcre.EXTENDED, + "extended" : pcre.EXTENDED, "Y" : pcre.NO_START_OPTIMIZE, + "no_start_optimize" : pcre.NO_START_OPTIMIZE, "any" : pcre.NEWLINE_ANY, "anycrlf" : pcre.NEWLINE_ANYCRLF, diff --git a/test/init.nim b/test/init.nim index 105e6a19e..2207afad8 100644 --- a/test/init.nim +++ b/test/init.nim @@ -10,6 +10,11 @@ suite "Test NRE initialization": expect(SyntaxError): # ValueError would be bad discard re("[0-9]+", "89AEfimNsUWXxY") + expect(SyntaxError): + discard re("[0-9]+", + "" & + "" & + "") test "incorrect options": expect(KeyError): discard re("[0-9]+", "a") From a7df3ffbe0ed6d10cc952e47f4e92a69403363dc Mon Sep 17 00:00:00 2001 From: Kay Zheng Date: Sun, 12 Apr 2015 12:59:56 +0800 Subject: [PATCH 0134/1263] Ignore EvError in `asyncdispatch.poll(...)` for non-windows systems, so that exceptions can be raised from `send(...)` and `recv(...)` --- lib/pure/asyncdispatch.nim | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/pure/asyncdispatch.nim b/lib/pure/asyncdispatch.nim index 27f77cef2..6ed782545 100644 --- a/lib/pure/asyncdispatch.nim +++ b/lib/pure/asyncdispatch.nim @@ -882,9 +882,9 @@ else: let data = PData(info.key.data) assert data.fd == info.key.fd.TAsyncFD #echo("In poll ", data.fd.cint) - if EvError in info.events: - closeSocket(data.fd) - continue + # There may be EvError here, but we handle them in callbacks, + # so that exceptions can be raised from `send(...)` and + # `recv(...)` routines. if EvRead in info.events: # Callback may add items to ``data.readCBs`` which causes issues if From 02c6e7306f5ab6454136e9cbd7a2a1187e2e2902 Mon Sep 17 00:00:00 2001 From: Oleh Prypin Date: Sun, 12 Apr 2015 15:18:16 +0300 Subject: [PATCH 0135/1263] Fix skipping an empty match at the end --- src/nre.nim | 6 +++--- test/find.nim | 1 + test/replace.nim | 2 +- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/nre.nim b/src/nre.nim index 76a45532b..fbfe7deb1 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -496,6 +496,9 @@ iterator findIter*(str: string, pattern: Regex, start = 0, endpos = int.high): R if match.isNone: # either the end of the input or the string # cannot be split here + if offset >= strlen: + break + if matchesCrLf and offset < (str.len - 1) and str[offset] == '\r' and str[offset + 1] == '\l': # if PCRE treats CrLf as newline, skip both at the same time @@ -511,9 +514,6 @@ iterator findIter*(str: string, pattern: Regex, start = 0, endpos = int.high): R yield match.get - if offset >= strlen: - # do while - break proc find*(str: string, pattern: Regex, start = 0, endpos = int.high): Option[RegexMatch] = ## Finds the given pattern in the string between the end and start diff --git a/test/find.nim b/test/find.nim index c138c2b28..549fd6ecd 100644 --- a/test/find.nim +++ b/test/find.nim @@ -19,6 +19,7 @@ suite "find": test "len 0 find": check("".findAll(re"\ ") == newSeq[string]()) check("".findAll(re"") == @[""]) + check("abc".findAll(re"") == @["", "", "", ""]) check("word word".findAll(re"\b") == @["", "", "", ""]) check("word\r\lword".findAll(re(r"$", "m")) == @["", ""]) check("слово слово".findAll(re(r"\b", "uW")) == @["", "", "", ""]) diff --git a/test/replace.nim b/test/replace.nim index 4e0b6e372..516fd4328 100644 --- a/test/replace.nim +++ b/test/replace.nim @@ -4,7 +4,7 @@ import unittest suite "replace": test "replace with 0-length strings": check("".replace(re"1", proc (v: RegexMatch): string = "1") == "") - check(" ".replace(re"", proc (v: RegexMatch): string = "1") == "1 ") + check(" ".replace(re"", proc (v: RegexMatch): string = "1") == "1 1") check("".replace(re"", proc (v: RegexMatch): string = "1") == "1") test "regular replace": From 8b8224ecaf7ed8cfbe1a205b43c3402aabc1653f Mon Sep 17 00:00:00 2001 From: Oleh Prypin Date: Sun, 12 Apr 2015 17:31:43 +0300 Subject: [PATCH 0136/1263] Add tests for empty or non-empty match --- test/misc.nim | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/test/misc.nim b/test/misc.nim index a515db889..1340cdc43 100644 --- a/test/misc.nim +++ b/test/misc.nim @@ -1,6 +1,16 @@ -import unittest, nre, optional_t.nonstrict +import unittest, nre, strutils, optional_t.nonstrict suite "Misc tests": test "unicode": check("".find(re("", "8")).match == "") check("перевірка".replace(re(r"\w", "uW"), "") == "") + + test "empty or non-empty match": + check("abc".findall(re"|.").join(":") == ":a::b::c:") + check("abc".findall(re".|").join(":") == "a:b:c:") + + check("abc".replace(re"|.", "x") == "xxxxxxx") + check("abc".replace(re".|", "x") == "xxxx") + + check("abc".split(re"|.").join(":") == ":::::") + check("abc".split(re".|").join(":") == ":::") From 90d17c4e03fe0a7ad1567bf9755d8ba836220cd7 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sun, 12 Apr 2015 10:33:21 -0400 Subject: [PATCH 0137/1263] Improve performance Removing ANCHORED means that after findIter is unable to find any more matches, it doesn't bother searching unless there are some promising 0-len matches. This significantly improves performance on problems like `"abccccccccccccc".find(re"a")`. Previously, each "c" would require a call to pcre_exec, which would iterate over [index_of_c..string.len], a O(n^2) process! --- src/nre.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/nre.nim b/src/nre.nim index fbfe7deb1..b960bdc92 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -489,7 +489,7 @@ iterator findIter*(str: string, pattern: Regex, start = 0, endpos = int.high): R if match and match.get.matchBounds.a > match.get.matchBounds.b: # 0-len match - flags = pcre.NOTEMPTY_ATSTART or pcre.ANCHORED + flags = pcre.NOTEMPTY_ATSTART match = str.matchImpl(pattern, offset, endpos, flags) From d0ff06b8c14e3b505d0c14ca5c9c37e8b667c875 Mon Sep 17 00:00:00 2001 From: Josep Sanjuas Date: Sun, 12 Apr 2015 19:40:30 +0200 Subject: [PATCH 0138/1263] Generalize mean to other types --- lib/pure/math.nim | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/lib/pure/math.nim b/lib/pure/math.nim index aa64933fb..0051c9d88 100644 --- a/lib/pure/math.nim +++ b/lib/pure/math.nim @@ -114,10 +114,13 @@ proc sum*[T](x: openArray[T]): T {.noSideEffect.} = ## If `x` is empty, 0 is returned. for i in items(x): result = result + i -proc mean*(x: openArray[float]): float {.noSideEffect.} = +template toFloat(f: float): float = f + +proc mean*[T](x: openArray[T]): float {.noSideEffect.} = ## computes the mean of the elements in `x`. ## If `x` is empty, NaN is returned. - result = sum(x) / toFloat(len(x)) + ## ``toFloat(x: T): float`` must be defined. + result = toFloat(sum(x)) / toFloat(len(x)) proc variance*(x: openArray[float]): float {.noSideEffect.} = ## computes the variance of the elements in `x`. From c31870d31116db562b03e2a3c148c0843dc14ca8 Mon Sep 17 00:00:00 2001 From: Oleh Prypin Date: Sun, 12 Apr 2015 22:21:44 +0300 Subject: [PATCH 0139/1263] Change flags to inline Flags can no longer be specified in a 2nd argument. Now they are part of the regular expression string. --- src/nre.nim | 120 +++++++++++++++++++++++-------------------------- test/find.nim | 4 +- test/init.nim | 35 ++++++++------- test/misc.nim | 4 +- test/split.nim | 4 +- 5 files changed, 81 insertions(+), 86 deletions(-) diff --git a/src/nre.nim b/src/nre.nim index b960bdc92..b119ea739 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -307,71 +307,61 @@ proc `==`*(a, b: RegexMatch): bool = # Creation & Destruction {{{ # PCRE Options {{{ -let Options: Table[string, int] = { - "8" : pcre.UTF8, - "utf8" : pcre.UTF8, - "9" : pcre.NEVER_UTF, - "no_utf8" : pcre.NEVER_UTF, - "A" : pcre.ANCHORED, - "anchored" : pcre.ANCHORED, - # "C" : pcre.AUTO_CALLOUT, unsuported XXX - "E" : pcre.DOLLAR_ENDONLY, - "dollar_endonly" : pcre.DOLLAR_ENDONLY, - "f" : pcre.FIRSTLINE, - "firstline" : pcre.FIRSTLINE, - "i" : pcre.CASELESS, - "case_insensitive" : pcre.CASELESS, - "m" : pcre.MULTILINE, - "multiline" : pcre.MULTILINE, - "N" : pcre.NO_AUTO_CAPTURE, - "no_auto_capture" : pcre.NO_AUTO_CAPTURE, - "s" : pcre.DOTALL, - "dotall" : pcre.DOTALL, - "U" : pcre.UNGREEDY, - "ungreedy" : pcre.UNGREEDY, - "u" : pcre.UTF8, - "W" : pcre.UCP, - "ucp" : pcre.UCP, - "X" : pcre.EXTRA, - "extra" : pcre.EXTRA, - "x" : pcre.EXTENDED, - "extended" : pcre.EXTENDED, - "Y" : pcre.NO_START_OPTIMIZE, - "no_start_optimize" : pcre.NO_START_OPTIMIZE, - - "any" : pcre.NEWLINE_ANY, - "anycrlf" : pcre.NEWLINE_ANYCRLF, - "cr" : pcre.NEWLINE_CR, - "crlf" : pcre.NEWLINE_CRLF, - "lf" : pcre.NEWLINE_LF, - "bsr_anycrlf" : pcre.BSR_ANYCRLF, - "bsr_unicode" : pcre.BSR_UNICODE, - "js" : pcre.JAVASCRIPT_COMPAT, +const PcreOptions = { + "NEVER_UTF": pcre.NEVER_UTF, + "ANCHORED": pcre.ANCHORED, + "DOLLAR_ENDONLY": pcre.DOLLAR_ENDONLY, + "FIRSTLINE": pcre.FIRSTLINE, + "NO_AUTO_CAPTURE": pcre.NO_AUTO_CAPTURE, + "JAVASCRIPT_COMPAT": pcre.JAVASCRIPT_COMPAT, + "U": pcre.UTF8 or pcre.UCP }.toTable -proc tokenizeOptions(opts: string): tuple[flags: int, study: bool] = - result = (0, true) +# Options that are supported inside regular expressions themselves +const SkipOptions = [ + "LIMIT_MATCH=", "LIMIT_RECURSION=", "NO_AUTO_POSSESS", "NO_START_OPT", + "UTF8", "UTF16", "UTF32", "UTF", "UCP", + "CR", "LF", "CRLF", "ANYCRLF", "ANY", "BSR_ANYCRLF", "BSR_UNICODE" +] - var longOpt: string = nil - for i, c in opts: - # Handle long options {{{ - if c == '<': - longOpt = "" - continue +proc extractOptions(pattern: string): tuple[pattern: string, flags: int, study: bool] = + result = ("", 0, true) - if longOpt != nil: - if c == '>': - if longOpt == "no_study": - result.study = false - else: - result.flags = result.flags or Options.fget(longOpt) - longOpt = nil + var optionStart = 0 + var equals = false + for i, c in pattern: + if optionStart == i: + if c != '(': + break + optionStart = i + + elif optionStart == i-1: + if c != '*': + break + + elif c == ')': + let name = pattern[optionStart+2 .. i-1] + if equals or name in SkipOptions: + result.pattern.add pattern[optionStart .. i] + elif PcreOptions.hasKey name: + result.flags = result.flags or PcreOptions[name] + elif name == "NO_STUDY": + result.study = false else: - longOpt.add(c.toLower) - continue - # }}} + break + optionStart = i+1 + equals = false + + elif not equals: + if c == '=': + equals = true + if pattern[optionStart+2 .. i] notin SkipOptions: + break + elif c notin {'A'..'Z', '0'..'9', '_'}: + break + + result.pattern.add pattern[optionStart .. pattern.high] - result.flags = result.flags or Options.fget($c) # }}} type UncheckedArray {.unchecked.}[T] = array[0 .. 0, T] @@ -402,24 +392,22 @@ proc getNameToNumberTable(pattern: Regex): Table[string, int] = result[name] = num -proc initRegex(pattern: string, options: string): Regex = +proc initRegex(pattern: string, flags: int, study = true): Regex = new(result, destroyRegex) result.pattern = pattern var errorMsg: cstring var errOffset: cint - let opts = tokenizeOptions(options) - result.pcreObj = pcre.compile(cstring(pattern), # better hope int is at least 4 bytes.. - cint(opts.flags), addr errorMsg, + cint(flags), addr errorMsg, addr errOffset, nil) if result.pcreObj == nil: # failed to compile raise SyntaxError(msg: $errorMsg, pos: errOffset, pattern: pattern) - if opts.study: + if study: # XXX investigate JIT result.pcreExtra = pcre.study(result.pcreObj, 0x0, addr errorMsg) if errorMsg != nil: @@ -427,7 +415,9 @@ proc initRegex(pattern: string, options: string): Regex = result.captureNameToId = result.getNameToNumberTable() -proc re*(pattern: string, options = ""): Regex = initRegex(pattern, options) +proc re*(pattern: string): Regex = + let (pattern, flags, study) = extractOptions(pattern) + initRegex(pattern, flags, study) # }}} # Operations {{{ diff --git a/test/find.nim b/test/find.nim index 549fd6ecd..90acaf4e1 100644 --- a/test/find.nim +++ b/test/find.nim @@ -21,5 +21,5 @@ suite "find": check("".findAll(re"") == @[""]) check("abc".findAll(re"") == @["", "", "", ""]) check("word word".findAll(re"\b") == @["", "", "", ""]) - check("word\r\lword".findAll(re(r"$", "m")) == @["", ""]) - check("слово слово".findAll(re(r"\b", "uW")) == @["", "", "", ""]) + check("word\r\lword".findAll(re"(*ANYCRLF)(?m)$") == @["", ""]) + check("слово слово".findAll(re"(*U)\b") == @["", "", "", ""]) diff --git a/test/init.nim b/test/init.nim index 2207afad8..76ffaba19 100644 --- a/test/init.nim +++ b/test/init.nim @@ -1,24 +1,30 @@ -import unittest -import nre +import unittest, private/pcre +include nre suite "Test NRE initialization": test "correct intialization": check(re("[0-9]+") != nil) - check(re("[0-9]+", "i") != nil) + check(re("(?i)[0-9]+") != nil) - test "correct options": - expect(SyntaxError): # ValueError would be bad - discard re("[0-9]+", - "89AEfimNsUWXxY") - expect(SyntaxError): - discard re("[0-9]+", - "" & - "" & - "") + test "options": + check(extractOptions("(*NEVER_UTF)") == + ("", pcre.NEVER_UTF, true)) + check(extractOptions("(*UTF8)(*ANCHORED)(*UCP)z") == + ("(*UTF8)(*UCP)z", pcre.ANCHORED, true)) + check(extractOptions("(*ANCHORED)(*UTF8)(*JAVASCRIPT_COMPAT)z") == + ("(*UTF8)z", pcre.ANCHORED or pcre.JAVASCRIPT_COMPAT, true)) + + check(extractOptions("(*NO_STUDY)(") == ("(", 0, false)) + + check(extractOptions("(*LIMIT_MATCH=6)(*ANCHORED)z") == + ("(*LIMIT_MATCH=6)z", pcre.ANCHORED, true)) test "incorrect options": - expect(KeyError): discard re("[0-9]+", "a") - expect(KeyError): discard re("[0-9]+", "") + for s in ["CR", "(CR", "(*CR", "(*abc)", "(*abc)CR", + "(?i)", + "(*LIMIT_MATCH=5", "(*NO_AUTO_POSSESS=5)"]: + let ss = s & "(*NEVER_UTF)" + check(extractOptions(ss) == (ss, 0, true)) test "invalid regex": expect(SyntaxError): discard re("[0-9") @@ -28,4 +34,3 @@ suite "Test NRE initialization": let ex = SyntaxError(getCurrentException()) check(ex.pos == 4) check(ex.pattern == "[0-9") - diff --git a/test/misc.nim b/test/misc.nim index 1340cdc43..f110c3f1e 100644 --- a/test/misc.nim +++ b/test/misc.nim @@ -2,8 +2,8 @@ import unittest, nre, strutils, optional_t.nonstrict suite "Misc tests": test "unicode": - check("".find(re("", "8")).match == "") - check("перевірка".replace(re(r"\w", "uW"), "") == "") + check("".find(re"(*UTF8)").match == "") + check("перевірка".replace(re"(*U)\w", "") == "") test "empty or non-empty match": check("abc".findall(re"|.").join(":") == ":a::b::c:") diff --git a/test/split.nim b/test/split.nim index fc2bbe1b4..8064e40b7 100644 --- a/test/split.nim +++ b/test/split.nim @@ -21,8 +21,8 @@ suite "string splitting": check("12345".split(re("")) == @["1", "2", "3", "4", "5"]) check("".split(re"") == newSeq[string]()) check("word word".split(re"\b") == @["word", " ", "word"]) - check("word\r\lword".split(re(r"$", "m")) == @["word", "\r\lword"]) - check("слово слово".split(re(r"(\b)", "uW")) == @["", "слово", "", " ", "", "слово", ""]) + check("word\r\lword".split(re"(*ANYCRLF)(?m)$") == @["word", "\r\lword"]) + check("слово слово".split(re"(*U)(\b)") == @["", "слово", "", " ", "", "слово", ""]) test "perl split tests": check("forty-two" .split(re"") .join(",") == "f,o,r,t,y,-,t,w,o") From 9a629d72e8560011d1f9351d22ffee8b7ed5bd43 Mon Sep 17 00:00:00 2001 From: apense Date: Sun, 12 Apr 2015 20:38:35 -0400 Subject: [PATCH 0140/1263] Added peeking procedures to streams Adds peeking to streams, which is just like reading, but at the end, the stream position hasn't changed. --- lib/pure/streams.nim | 112 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 111 insertions(+), 1 deletion(-) diff --git a/lib/pure/streams.nim b/lib/pure/streams.nim index e706f2016..798c587a1 100644 --- a/lib/pure/streams.nim +++ b/lib/pure/streams.nim @@ -1,7 +1,7 @@ # # # Nim's Runtime Library -# (c) Copyright 2012 Andreas Rumpf +# (c) Copyright 2015 Andreas Rumpf # # See the file "copying.txt", included in this # distribution, for details about the copyright. @@ -31,6 +31,8 @@ type getPositionImpl*: proc (s: Stream): int {.nimcall, tags: [], gcsafe.} readDataImpl*: proc (s: Stream, buffer: pointer, bufLen: int): int {.nimcall, tags: [ReadIOEffect], gcsafe.} + peekDataImpl*: proc (s: Stream, buffer: pointer, + bufLen: int): int {.nimcall, tags: [ReadIOEffect], gcsafe.} writeDataImpl*: proc (s: Stream, buffer: pointer, bufLen: int) {.nimcall, tags: [WriteIOEffect], gcsafe.} flushImpl*: proc (s: Stream) {.nimcall, tags: [WriteIOEffect], gcsafe.} @@ -84,6 +86,11 @@ proc readData*(s, unused: Stream, buffer: pointer, ## low level proc that reads data into an untyped `buffer` of `bufLen` size. result = s.readDataImpl(s, buffer, bufLen) +proc peekData*(s: Stream, buffer: pointer, bufLen: int): int = + ## low level proc that reads data into an untyped `buffer` of `bufLen` size + ## without moving stream position + result = s.peekDataImpl(s, buffer, bufLen) + proc writeData*(s: Stream, buffer: pointer, bufLen: int) = ## low level proc that writes an untyped `buffer` of `bufLen` size ## to the stream `s`. @@ -121,39 +128,77 @@ proc read[T](s: Stream, result: var T) = if readData(s, addr(result), sizeof(T)) != sizeof(T): raise newEIO("cannot read from stream") +proc peek[T](s: Stream, result: var T) = + ## generic peek procedure. Peeks `result` from the stream `s`. + if peekData(s, addr(result), sizeof(T)) != sizeof(T): + raise newEIO("cannot read from stream") + proc readChar*(s: Stream): char = ## reads a char from the stream `s`. Raises `EIO` if an error occurred. ## Returns '\0' as an EOF marker. if readData(s, addr(result), sizeof(result)) != 1: result = '\0' +proc peekChar*(s: Stream): char = + ## peeks a char from the stream `s`. Raises `EIO` if an error occurred. + ## Returns '\0' as an EOF marker. + if peekData(s, addr(result), sizeof(result)) != 1: result = '\0' + proc readBool*(s: Stream): bool = ## reads a bool from the stream `s`. Raises `EIO` if an error occurred. read(s, result) +proc peekBool*(s: Stream): bool = + ## peeks a bool from the stream `s`. Raises `EIO` if an error occured. + peek(s, result) + proc readInt8*(s: Stream): int8 = ## reads an int8 from the stream `s`. Raises `EIO` if an error occurred. read(s, result) +proc peekInt8*(s: Stream): int8 = + ## peeks an int8 from the stream `s`. Raises `EIO` if an error occurred. + peek(s, result) + proc readInt16*(s: Stream): int16 = ## reads an int16 from the stream `s`. Raises `EIO` if an error occurred. read(s, result) +proc peekInt16*(s: Stream): int16 = + ## peeks an int16 from the stream `s`. Raises `EIO` if an error occurred. + peek(s, result) + proc readInt32*(s: Stream): int32 = ## reads an int32 from the stream `s`. Raises `EIO` if an error occurred. read(s, result) +proc peekInt32*(s: Stream): int32 = + ## peeks an int32 from the stream `s`. Raises `EIO` if an error occurred. + peek(s, result) + proc readInt64*(s: Stream): int64 = ## reads an int64 from the stream `s`. Raises `EIO` if an error occurred. read(s, result) +proc peekInt64*(s: Stream): int64 = + ## peeks an int64 from the stream `s`. Raises `EIO` if an error occurred. + peek(s, result) + proc readFloat32*(s: Stream): float32 = ## reads a float32 from the stream `s`. Raises `EIO` if an error occurred. read(s, result) +proc peekFloat32*(s: Stream): float32 = + ## peeks a float32 from the stream `s`. Raises `EIO` if an error occurred. + peek(s, result) + proc readFloat64*(s: Stream): float64 = ## reads a float64 from the stream `s`. Raises `EIO` if an error occurred. read(s, result) +proc peekFloat64*(s: Stream): float64 = + ## peeks a float64 from the stream `s`. Raises `EIO` if an error occurred. + peek(s, result) + proc readStr*(s: Stream, length: int): TaintedString = ## reads a string of length `length` from the stream `s`. Raises `EIO` if ## an error occurred. @@ -161,6 +206,13 @@ proc readStr*(s: Stream, length: int): TaintedString = var L = readData(s, addr(string(result)[0]), length) if L != length: setLen(result.string, L) +proc peekStr*(s: Stream, length: int): TaintedString = + ## peeks a string of length `length` from the stream `s`. Raises `EIO` if + ## an error occurred. + result = newString(length).TaintedString + var L = peekData(s, addr(string(result)[0]), length) + if L != length: setLen(result.string, L) + proc readLine*(s: Stream, line: var TaintedString): bool = ## reads a line of text from the stream `s` into `line`. `line` must not be ## ``nil``! May throw an IO exception. @@ -181,6 +233,30 @@ proc readLine*(s: Stream, line: var TaintedString): bool = line.string.add(c) result = true +proc peekLine*(s: Stream, line: var TaintedString): bool = + ## peeks a line of text from the stream `s` into `line`. `line` must not be + ## ``nil``! May throw an IO exception. + ## A line of text may be delimited by ``CR``, ``LF`` or + ## ``CRLF``. The newline character(s) are not part of the returned string. + ## Returns ``false`` if the end of the file has been reached, ``true`` + ## otherwise. If ``false`` is returned `line` contains no new data. + line.string.setLen(0) + let pos = getPosition(s) + while true: + var c = readChar(s) + if c == '\c': + c = readChar(s) + break + elif c == '\L': break + elif c == '\0': + if line.len > 0: break + else: + setPosition(s, pos) + return false + line.string.add(c) + setPosition(s, pos) + result = true + proc readLine*(s: Stream): TaintedString = ## Reads a line from a stream `s`. Note: This is not very efficient. Raises ## `EIO` if an error occurred. @@ -195,6 +271,23 @@ proc readLine*(s: Stream): TaintedString = else: result.string.add(c) +proc peekLine*(s: Stream): TaintedString = + ## Peeks a line from a stream `s`. Note: This is not very efficient. Raises + ## `EIO` if an error occurred. + result = TaintedString"" + let pos = getPosition(s) + while true: + var c = readChar(s) + if c == '\c': + c = readChar(s) + setPosition(s, pos) + break + if c == '\L' or c == '\0': + setPosition(s, pos) + break + else: + result.string.add(c) + type StringStream* = ref StringStreamObj ## a stream that encapsulates a string StringStreamObj* = object of StreamObj @@ -222,6 +315,12 @@ proc ssReadData(s: Stream, buffer: pointer, bufLen: int): int = copyMem(buffer, addr(s.data[s.pos]), result) inc(s.pos, result) +proc ssPeekData(s: Stream, buffer: pointer, bufLen: int): int = + var s = StringStream(s) + result = min(bufLen, s.data.len - s.pos) + if result > 0: + copyMem(buffer, addr(s.data[s.pos]), result) + proc ssWriteData(s: Stream, buffer: pointer, bufLen: int) = var s = StringStream(s) if bufLen <= 0: @@ -245,6 +344,7 @@ proc newStringStream*(s: string = ""): StringStream = result.setPositionImpl = ssSetPosition result.getPositionImpl = ssGetPosition result.readDataImpl = ssReadData + result.peekDataImpl = ssPeekData result.writeDataImpl = ssWriteData when not defined(js): @@ -266,6 +366,11 @@ when not defined(js): proc fsReadData(s: Stream, buffer: pointer, bufLen: int): int = result = readBuffer(FileStream(s).f, buffer, bufLen) + + proc fsPeekData(s: Stream, buffer: pointer, bufLen: int): int = + let pos = fsGetPosition(s) + result = readBuffer(FileStream(s).f, buffer, bufLen) + fsSetPosition(s, pos) proc fsWriteData(s: Stream, buffer: pointer, bufLen: int) = if writeBuffer(FileStream(s).f, buffer, bufLen) != bufLen: @@ -280,6 +385,7 @@ when not defined(js): result.setPositionImpl = fsSetPosition result.getPositionImpl = fsGetPosition result.readDataImpl = fsReadData + result.peekDataImpl = fsPeekData result.writeDataImpl = fsWriteData result.flushImpl = fsFlush @@ -329,6 +435,9 @@ else: proc hsReadData(s: FileHandleStream, buffer: pointer, bufLen: int): int = result = posix.read(s.handle, buffer, bufLen) inc(s.pos, result) + + proc hsPeekData(s: FileHandleStream, buffer: pointer, bufLen: int): int = + result = posix.read(s.handle, buffer, bufLen) proc hsWriteData(s: FileHandleStream, buffer: pointer, bufLen: int) = if posix.write(s.handle, buffer, bufLen) != bufLen: @@ -344,6 +453,7 @@ else: result.setPosition = hsSetPosition result.getPosition = hsGetPosition result.readData = hsReadData + result.peekData = hsPeekData result.writeData = hsWriteData proc newFileHandleStream*(filename: string, From e6dbb350a9def15fad3b3161749989f4c1ff88a4 Mon Sep 17 00:00:00 2001 From: Oleh Prypin Date: Sun, 12 Apr 2015 22:22:56 +0300 Subject: [PATCH 0141/1263] Update documentation --- src/nre.nim | 75 +++++++++++++++++++++++++++-------------------------- 1 file changed, 38 insertions(+), 37 deletions(-) diff --git a/src/nre.nim b/src/nre.nim index b119ea739..f5bb55045 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -47,14 +47,7 @@ from unicode import runeLenAt type Regex* = ref object ## Represents the pattern that things are matched against, constructed with - ## ``re(string, string)``. Examples: ``re"foo"``, ``re(r"foo # comment", - ## "x")``, ``re"(?x)(*ANYCRLF)foo # comment"``. For more details - ## on the leading option groups, see the `Option - ## Setting `__ - ## and the `Newline - ## Convention `__ - ## sections of the `PCRE syntax - ## manual `__. + ## ``re(string)``. Examples: ``re"foo"``, ``re(r"(*ANYCRLF)(?x)foo # comment". ## ## ``pattern: string`` ## the string that was used to create the pattern. @@ -66,33 +59,36 @@ type ## a table from the capture names to their numeric id. ## ## - ## Flags - ## ..... + ## Options + ## ....... ## - ## - ``8``, ``u``, ```` - treat both the pattern and subject as UTF8 - ## - ``9``, ```` - prevents the pattern from being interpreted as UTF, no matter - ## what - ## - ``A``, ```` - as if the pattern had a ``^`` at the beginning - ## - ``E``, ```` - DOLLAR\_ENDONLY - ## - ``f``, ```` - fails if there is not a match on the first line - ## - ``i``, ```` - case insensitive - ## - ``m``, ```` - multi-line, ``^`` and ``$`` match the beginning and end of + ## The following options may appear anywhere in the pattern, and they affect + ## the rest of it. + ## + ## - ``(?i)`` - case insensitive + ## - ``(?m)`` - multi-line: ``^`` and ``$`` match the beginning and end of ## lines, not of the subject string - ## - ``N``, ```` - turn off auto-capture, ``(?foo)`` is necessary to capture. - ## - ``s``, ```` - ``.`` matches newline - ## - ``U``, ```` - expressions are not greedy by default. ``?`` can be added to - ## a qualifier to make it greedy. - ## - ``W``, ```` - Unicode character properties; ``\w`` matches ``к``. - ## - ``X``, ```` - "Extra", character escapes without special meaning (``\w`` - ## vs. ``\a``) are errors - ## - ``x``, ```` - extended, comments (``#``) and newlines are ignored - ## (extended) - ## - ``Y``, ```` - pcre.NO\_START\_OPTIMIZE, - ## - ```` - newlines are separated by ``\r`` - ## - ```` - newlines are separated by ``\r\n`` (Windows default) - ## - ```` - newlines are separated by ``\n`` (UNIX default) - ## - ```` - newlines are separated by any of the above - ## - ```` - newlines are separated by any of the above and Unicode + ## - ``(?s)`` - ``.`` also matches newline (*dotall*) + ## - ``(?U)`` - expressions are not greedy by default. ``?`` can be added + ## to a qualifier to make it greedy + ## - ``(?x)`` - whitespace and comments (``#``) are ignored (*extended*) + ## - ``(?X)`` - character escapes without special meaning (``\w`` vs. + ## ``\a``) are errors (*extra*) + ## + ## One or a combination of these options may appear only at the beginning + ## of the pattern: + ## + ## - ``(*UTF8)`` - treat both the pattern and subject as UTF-8 + ## - ``(*UCP)`` - Unicode character properties; ``\w`` matches ``я`` + ## - ``(*U)`` - a combination of the two options above + ## - ``(*FIRSTLINE*)`` - fails if there is not a match on the first line + ## - ``(*NO_AUTO_CAPTURE)`` - turn off auto-capture for groups; + ## ``(?...)`` can be used to capture + ## - ``(*CR)`` - newlines are separated by ``\r`` + ## - ``(*LF)`` - newlines are separated by ``\n`` (UNIX default) + ## - ``(*CRLF)`` - newlines are separated by ``\r\n`` (Windows default) + ## - ``(*ANYCRLF)`` - newlines are separated by any of the above + ## - ``(*ANY)`` - newlines are separated by any of the above and Unicode ## newlines: ## ## single characters VT (vertical tab, U+000B), FF (form feed, U+000C), @@ -101,10 +97,15 @@ type ## are recognized only in UTF-8 mode. ## — man pcre ## - ## - ```` - ``\R`` matches CR, LF, or CRLF - ## - ```` - ``\R`` matches any unicode newline - ## - ```` - Javascript compatibility - ## - ```` - turn off studying; study is enabled by deafault + ## - ``(*JAVASCRIPT_COMPAT)`` - JavaScript compatibility + ## - ``(*NO_STUDY)`` - turn off studying; study is enabled by default + ## + ## For more details on the leading option groups, see the `Option + ## Setting `__ + ## and the `Newline + ## Convention `__ + ## sections of the `PCRE syntax + ## manual `__. pattern*: string ## not nil pcreObj: ptr pcre.Pcre ## not nil pcreExtra: ptr pcre.ExtraData ## nil From c55f884b5c0ebc0b637138a8de446ba1fd05acdf Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Mon, 13 Apr 2015 22:36:35 -0500 Subject: [PATCH 0142/1263] integrated realtimegc stuff into testament --- tests/realtimeGC/{main.c => cmain.c} | 20 ++++++-------- tests/realtimeGC/make.bat | 10 ------- tests/realtimeGC/{main.nim => nmain.nim} | 28 +++++++++++-------- tests/realtimeGC/shared.nim | 8 ++++-- tests/realtimeGC/shared.nim.cfg | 1 - tests/testament/categories.nim | 14 ++++++++++ tests/testament/tester.nim | 35 +++++++++++++++++++++++- 7 files changed, 78 insertions(+), 38 deletions(-) rename tests/realtimeGC/{main.c => cmain.c} (71%) delete mode 100755 tests/realtimeGC/make.bat rename tests/realtimeGC/{main.nim => nmain.nim} (53%) diff --git a/tests/realtimeGC/main.c b/tests/realtimeGC/cmain.c similarity index 71% rename from tests/realtimeGC/main.c rename to tests/realtimeGC/cmain.c index bbe80b23d..e9a46d7ce 100644 --- a/tests/realtimeGC/main.c +++ b/tests/realtimeGC/cmain.c @@ -21,24 +21,24 @@ int main(int argc, char* argv[]) void* hndl; pFunc status; pFunc count; - pFunc occupiedMem; + pFunc checkOccupiedMem; #ifdef WIN - hndl = (void*) LoadLibrary((char const*)"./shared.dll"); + hndl = (void*) LoadLibrary((char const*)"./tests/realtimeGC/shared.dll"); status = (pFunc)GetProcAddress((HMODULE) hndl, (char const*)"status"); count = (pFunc)GetProcAddress((HMODULE) hndl, (char const*)"count"); - occupiedMem = (pFunc)GetProcAddress((HMODULE) hndl, (char const*)"occupiedMem"); + checkOccupiedMem = (pFunc)GetProcAddress((HMODULE) hndl, (char const*)"checkOccupiedMem"); #else /* OSX || NIX */ - hndl = (void*) dlopen((char const*)"./libshared.so", RTLD_LAZY); + hndl = (void*) dlopen((char const*)"./tests/realtimeGC/libshared.so", RTLD_LAZY); status = (pFunc) dlsym(hndl, (char const*)"status"); count = (pFunc) dlsym(hndl, (char const*)"count"); - occupiedMem = (pFunc) dlsym(hndl, (char const*)"occupiedMem"); + checkOccupiedMem = (pFunc) dlsym(hndl, (char const*)"checkOccupiedMem"); #endif assert(hndl); assert(status); assert(count); - assert(occupiedMem); + assert(checkOccupiedMem); time_t startTime = time((time_t*)0); time_t runTime = (time_t)(RUNTIME); @@ -52,9 +52,9 @@ int main(int argc, char* argv[]) status(); /* printf("2. sleeping...\n"); */ sleep(1); - occupiedMem(); + checkOccupiedMem(); accumTime = time((time_t*)0) - startTime; - printf("--- Minutes left to run: %d\n", (int)(runTime-accumTime)/60); + /* printf("--- Minutes left to run: %d\n", (int)(runTime-accumTime)/60); */ } printf("Cleaning up the shared object pointer...\n"); #ifdef WIN @@ -65,7 +65,3 @@ int main(int argc, char* argv[]) printf("Done\n"); return 0; } - - - - diff --git a/tests/realtimeGC/make.bat b/tests/realtimeGC/make.bat deleted file mode 100755 index cce8292bf..000000000 --- a/tests/realtimeGC/make.bat +++ /dev/null @@ -1,10 +0,0 @@ - -set CXX=gcc -set LIBS=-ldl -set LNFLAGS= -set CFLAGS=-DWIN -set INC= - -nim c shared.nim -nim c -o:nmain main.nim -%CXX% %INC% %DEFS% %CFLAGS% -o cmain main.c %LNFLAGS% %LIBS% diff --git a/tests/realtimeGC/main.nim b/tests/realtimeGC/nmain.nim similarity index 53% rename from tests/realtimeGC/main.nim rename to tests/realtimeGC/nmain.nim index d2d404271..c9f558dbc 100644 --- a/tests/realtimeGC/main.nim +++ b/tests/realtimeGC/nmain.nim @@ -3,38 +3,44 @@ discard """ output: "Done" """ -import times -import os +import times, os, threadpool const RUNTIME = 15 * 60 # 15 minutes when defined(windows): - const dllname = "./shared.dll" + const dllname = "./tests/realtimeGC/shared.dll" elif defined(macosx): - const dllname = "./libshared.dylib" + const dllname = "./tests/realtimeGC/libshared.dylib" else: - const dllname = "./libshared.so" + const dllname = "./tests/realtimeGC/libshared.so" proc status() {.importc: "status", dynlib: dllname.} proc count() {.importc: "count", dynlib: dllname.} -proc occupiedMem() {.importc: "occupiedMem", dynlib: dllname.} +proc checkOccupiedMem() {.importc: "checkOccupiedMem", dynlib: dllname.} -proc main() = +proc process() = let startTime = getTime() let runTime = cast[Time](RUNTIME) # var accumTime: Time while accumTime < runTime: for i in 0..10: count() - #echo("1. sleeping... ") + # echo("1. sleeping... ") sleep(500) for i in 0..10: status() - #echo("2. sleeping... ") + # echo("2. sleeping... ") sleep(500) - occupiedMem() + checkOccupiedMem() accumTime = cast[Time]((getTime() - startTime)) - #echo("--- Minutes left to run: ", int(int(runTime-accumTime)/60)) + # echo("--- Minutes left to run: ", int(int(runTime-accumTime)/60)) + +proc main() = + process() + # parallel: + # for i in 0..0: + # spawn process() + # sync() echo("Done") main() diff --git a/tests/realtimeGC/shared.nim b/tests/realtimeGC/shared.nim index c8a70e1ee..2d1dd6c3c 100644 --- a/tests/realtimeGC/shared.nim +++ b/tests/realtimeGC/shared.nim @@ -4,6 +4,8 @@ discard """ import strutils +# Global state, accessing with threads, no locks. Don't do this at +# home. var gCounter: uint64 var gTxStatus: bool var gRxStatus: bool @@ -55,7 +57,7 @@ proc count() {.exportc: "count", dynlib.} = gCounter += 1 # echo("gCounter: ", gCounter) -proc occupiedMem() {.exportc: "occupiedMem", dynlib.} = - echo("Occupied Memmory: ", getOccupiedMem()) +proc checkOccupiedMem() {.exportc: "checkOccupiedMem", dynlib.} = + if getOccupiedMem() > 10_000_000: + quit 1 discard - diff --git a/tests/realtimeGC/shared.nim.cfg b/tests/realtimeGC/shared.nim.cfg index 5d498029d..e153b26fa 100644 --- a/tests/realtimeGC/shared.nim.cfg +++ b/tests/realtimeGC/shared.nim.cfg @@ -1,4 +1,3 @@ - --app:lib --threads:on diff --git a/tests/testament/categories.nim b/tests/testament/categories.nim index 4476fccf2..2d66d2f8e 100644 --- a/tests/testament/categories.nim +++ b/tests/testament/categories.nim @@ -138,6 +138,18 @@ proc gcTests(r: var TResults, cat: Category, options: string) = test "stackrefleak" test "cyclecollector" +proc longGCTests(r: var TResults, cat: Category, options: string) = + when defined(windows): + let cOptions = "gcc -ldl -DWIN" + else: + let cOptions = "gcc -ldl" + + var c = initResults() + # According to ioTests, this should compile the file + testNoSpec c, makeTest("tests/realtimeGC/shared", options, cat, actionCompile) + # testC r, makeTest("tests/realtimeGC/cmain", cOptions, cat, actionRun) + testSpec r, makeTest("tests/realtimeGC/nmain", options & "--threads: on", cat, actionRun) + # ------------------------- threading tests ----------------------------------- proc threadTests(r: var TResults, cat: Category, options: string) = @@ -340,6 +352,8 @@ proc processCategory(r: var TResults, cat: Category, options: string) = dllTests(r, cat, options) of "gc": gcTests(r, cat, options) + of "longgc": + longGCTests(r, cat, options) of "debugger": debuggerTests(r, cat, options) of "manyloc": diff --git a/tests/testament/tester.nim b/tests/testament/tester.nim index 7391b105e..86ff6a689 100644 --- a/tests/testament/tester.nim +++ b/tests/testament/tester.nim @@ -87,6 +87,25 @@ proc callCompiler(cmdTemplate, filename, options: string, elif suc =~ pegSuccess: result.err = reSuccess +proc callCCompiler(cmdTemplate, filename, options: string, + target: TTarget): TSpec = + let c = parseCmdLine(cmdTemplate % ["target", targetToCmd[target], + "options", options, "file", filename.quoteShell]) + var p = startProcess(command="gcc", args=c[4.. ^1], + options={poStdErrToStdOut, poUsePath}) + let outp = p.outputStream + var x = newStringOfCap(120) + result.nimout = "" + result.msg = "" + result.file = "" + result.outp = "" + result.line = -1 + while outp.readLine(x.TaintedString) or running(p): + result.nimout.add(x & "\n") + close(p) + if p.peekExitCode == 0: + result.err = reSuccess + proc initResults: TResults = result.total = 0 result.passed = 0 @@ -247,8 +266,22 @@ proc testNoSpec(r: var TResults, test: TTest) = r.addResult(test, "", given.msg, given.err) if given.err == reSuccess: inc(r.passed) +proc testC(r: var TResults, test: TTest) = + # runs C code. Doesn't support any specs, just goes by exit code. + let tname = test.name.addFileExt(".c") + inc(r.total) + styledEcho "Processing ", fgCyan, extractFilename(tname) + var given = callCCompiler(cmdTemplate, test.name & ".c", test.options, test.target) + if given.err != reSuccess: + r.addResult(test, "", given.msg, given.err) + elif test.action == actionRun: + let exeFile = changeFileExt(test.name, ExeExt) + var (buf, exitCode) = execCmdEx(exeFile, options = {poStdErrToStdOut, poUseShell}) + if exitCode != 0: given.err = reExitCodesDiffer + if given.err == reSuccess: inc(r.passed) + proc makeTest(test, options: string, cat: Category, action = actionCompile, - target = targetC): TTest = + target = targetC, env: string = ""): TTest = # start with 'actionCompile', will be overwritten in the spec: result = TTest(cat: cat, name: test, options: options, target: target, action: action) From 15c347af693250e60cdf564606fa1f90722b757a Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Tue, 14 Apr 2015 01:58:34 -0500 Subject: [PATCH 0143/1263] sexp parsing & generation --- lib/pure/sexpressions.nim | 716 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 716 insertions(+) create mode 100644 lib/pure/sexpressions.nim diff --git a/lib/pure/sexpressions.nim b/lib/pure/sexpressions.nim new file mode 100644 index 000000000..c30f35c25 --- /dev/null +++ b/lib/pure/sexpressions.nim @@ -0,0 +1,716 @@ +# +# +# Nim's Runtime Library +# (c) Copyright 2015 Andreas Rumpf, Dominik Picheta +# +# See the file "copying.txt", included in this +# distribution, for details about the copyright. +# + +import + hashes, strutils, lexbase, streams, unicode, macros + +type + SexpEventKind* = enum ## enumeration of all events that may occur when parsing + sexpError, ## an error occurred during parsing + sexpEof, ## end of file reached + sexpString, ## a string literal + sexpSymbol, ## a symbol + sexpInt, ## an integer literal + sexpFloat, ## a float literal + sexpNil, ## the value ``nil`` + sexpListStart, ## start of a list: the ``(`` token + sexpListEnd, ## end of a list: the ``)`` token + + TTokKind = enum # must be synchronized with SexpEventKind! + tkError, + tkEof, + tkString, + tkSymbol, + tkInt, + tkFloat, + tkNil, + tkParensLe, + tkParensRi + tkSpace + + SexpError* = enum ## enumeration that lists all errors that can occur + errNone, ## no error + errInvalidToken, ## invalid token + errParensRiExpected, ## ``)`` expected + errQuoteExpected, ## ``"`` expected + errEofExpected, ## EOF expected + + ParserState = enum + stateEof, stateStart, stateList, stateListExpectsSpace + + SexpParser* = object of BaseLexer ## the parser object. + a: string + tok: TTokKind + kind: SexpEventKind + err: SexpError + state: seq[ParserState] + filename: string + +const + errorMessages: array [SexpError, string] = [ + "no error", + "invalid token", + "')' expected", + "'\"' or \"'\" expected", + "EOF expected", + ] + tokToStr: array [TTokKind, string] = [ + "invalid token", + "EOF", + "string literal", + "symbol", + "int literal", + "float literal", + "nil", + "(", ")", " " + ] + +proc open*(my: var SexpParser, input: Stream, filename: string) = + ## initializes the parser with an input stream. `Filename` is only used + ## for nice error messages. + lexbase.open(my, input) + my.filename = filename + my.state = @[stateStart] + my.kind = sexpError + my.a = "" + +proc close*(my: var SexpParser) {.inline.} = + ## closes the parser `my` and its associated input stream. + lexbase.close(my) + +proc str*(my: SexpParser): string {.inline.} = + ## returns the character data for the events: ``sexpInt``, ``sexpFloat``, + ## ``sexpString`` + assert(my.kind in {sexpInt, sexpFloat, sexpString}) + result = my.a + +proc getInt*(my: SexpParser): BiggestInt {.inline.} = + ## returns the number for the event: ``sexpInt`` + assert(my.kind == sexpInt) + result = parseBiggestInt(my.a) + +proc getFloat*(my: SexpParser): float {.inline.} = + ## returns the number for the event: ``sexpFloat`` + assert(my.kind == sexpFloat) + result = parseFloat(my.a) + +proc kind*(my: SexpParser): SexpEventKind {.inline.} = + ## returns the current event type for the SEXP parser + result = my.kind + +proc getColumn*(my: SexpParser): int {.inline.} = + ## get the current column the parser has arrived at. + result = getColNumber(my, my.bufpos) + +proc getLine*(my: SexpParser): int {.inline.} = + ## get the current line the parser has arrived at. + result = my.lineNumber + +proc getFilename*(my: SexpParser): string {.inline.} = + ## get the filename of the file that the parser processes. + result = my.filename + +proc errorMsg*(my: SexpParser): string = + ## returns a helpful error message for the event ``sexpError`` + assert(my.kind == sexpError) + result = "$1($2, $3) Error: $4" % [ + my.filename, $getLine(my), $getColumn(my), errorMessages[my.err]] + +proc errorMsgExpected*(my: SexpParser, e: string): string = + ## returns an error message "`e` expected" in the same format as the + ## other error messages + result = "$1($2, $3) Error: $4" % [ + my.filename, $getLine(my), $getColumn(my), e & " expected"] + +proc handleHexChar(c: char, x: var int): bool = + result = true # Success + case c + of '0'..'9': x = (x shl 4) or (ord(c) - ord('0')) + of 'a'..'f': x = (x shl 4) or (ord(c) - ord('a') + 10) + of 'A'..'F': x = (x shl 4) or (ord(c) - ord('A') + 10) + else: result = false # error + +proc parseString(my: var SexpParser): TTokKind = + result = tkString + var pos = my.bufpos + 1 + var buf = my.buf + while true: + case buf[pos] + of '\0': + my.err = errQuoteExpected + result = tkError + break + of '"': + inc(pos) + break + of '\\': + case buf[pos+1] + of '\\', '"', '\'', '/': + add(my.a, buf[pos+1]) + inc(pos, 2) + of 'b': + add(my.a, '\b') + inc(pos, 2) + of 'f': + add(my.a, '\f') + inc(pos, 2) + of 'n': + add(my.a, '\L') + inc(pos, 2) + of 'r': + add(my.a, '\C') + inc(pos, 2) + of 't': + add(my.a, '\t') + inc(pos, 2) + of 'u': + inc(pos, 2) + var r: int + if handleHexChar(buf[pos], r): inc(pos) + if handleHexChar(buf[pos], r): inc(pos) + if handleHexChar(buf[pos], r): inc(pos) + if handleHexChar(buf[pos], r): inc(pos) + add(my.a, toUTF8(Rune(r))) + else: + # don't bother with the error + add(my.a, buf[pos]) + inc(pos) + of '\c': + pos = lexbase.handleCR(my, pos) + buf = my.buf + add(my.a, '\c') + of '\L': + pos = lexbase.handleLF(my, pos) + buf = my.buf + add(my.a, '\L') + else: + add(my.a, buf[pos]) + inc(pos) + my.bufpos = pos # store back + +proc parseNumber(my: var SexpParser) = + var pos = my.bufpos + var buf = my.buf + if buf[pos] == '-': + add(my.a, '-') + inc(pos) + if buf[pos] == '.': + add(my.a, "0.") + inc(pos) + else: + while buf[pos] in Digits: + add(my.a, buf[pos]) + inc(pos) + if buf[pos] == '.': + add(my.a, '.') + inc(pos) + # digits after the dot: + while buf[pos] in Digits: + add(my.a, buf[pos]) + inc(pos) + if buf[pos] in {'E', 'e'}: + add(my.a, buf[pos]) + inc(pos) + if buf[pos] in {'+', '-'}: + add(my.a, buf[pos]) + inc(pos) + while buf[pos] in Digits: + add(my.a, buf[pos]) + inc(pos) + my.bufpos = pos + +proc parseSymbol(my: var SexpParser) = + var pos = my.bufpos + var buf = my.buf + if buf[pos] in IdentStartChars: + while buf[pos] in IdentChars: + add(my.a, buf[pos]) + inc(pos) + my.bufpos = pos + +proc getTok(my: var SexpParser): TTokKind = + setLen(my.a, 0) + case my.buf[my.bufpos] + of '-', '.', '0'..'9': + parseNumber(my) + if {'.', 'e', 'E'} in my.a: + result = tkFloat + else: + result = tkInt + of '"': #" # gotta fix nim-mode + result = parseString(my) + of '(': + inc(my.bufpos) + result = tkParensLe + of ')': + inc(my.bufpos) + result = tkParensRi + of '\0': + result = tkEof + of 'a'..'z', 'A'..'Z', '_': + parseSymbol(my) + if my.a == "nil": + result = tkNil + else: + result = tkSymbol + of ' ': + result = tkSpace + inc(my.bufpos) + else: + inc(my.bufpos) + result = tkError + my.tok = result + +proc next*(my: var SexpParser) = + ## retrieves the first/next event. This controls the parser. + var tk = getTok(my) + var i = my.state.len-1 + # the following code is a state machine. If we had proper coroutines, + # the code could be much simpler. + case my.state[i] + of stateEof: + if tk == tkEof: + my.kind = sexpEof + else: + my.kind = sexpError + my.err = errEofExpected + of stateStart: + # tokens allowed? + case tk + of tkString, tkInt, tkFloat, tkSymbol, tkNil: + my.state[i] = stateEof # expect EOF next! + my.kind = SexpEventKind(ord(tk)) + of tkParensLe: + my.state.add(stateList) + my.kind = sexpListStart + of tkEof: + my.kind = sexpEof + else: + my.kind = sexpError + my.err = errEofExpected + of stateList: + case tk + of tkString, tkInt, tkFloat, tkSymbol, tkNil: + my.kind = SexpEventKind(ord(tk)) + my.state.add(stateListExpectsSpace) + of tkParensLe: + my.state.add(stateList) + my.kind = sexpListStart + of tkParensRi: + my.kind = sexpListEnd + discard my.state.pop() + else: + my.kind = sexpError + my.err = errParensRiExpected + of stateListExpectsSpace: + case tk + of tkSpace: + discard my.state.pop() + next(my) + of tkParensLe: + my.kind = sexpListEnd + discard my.state.pop() + discard my.state.pop() + else: + my.kind = sexpError + my.err = errParensRiExpected + +# ------------- higher level interface --------------------------------------- + +type + SexpNodeKind* = enum ## possible SEXP node types + SNil, + SInt, + SFloat, + SString, + SSymbol + SList, + + SexpNode* = ref SexpNodeObj ## SEXP node + SexpNodeObj* {.acyclic.} = object + case kind*: SexpNodeKind + of SString: + str*: string + of SSymbol: + symbol*: string + of SInt: + num*: BiggestInt + of SFloat: + fnum*: float + of SList: + elems*: seq[SexpNode] + of SNil: + discard + + SexpParsingError* = object of ValueError ## is raised for a SEXP error + +proc raiseParseErr*(p: SexpParser, msg: string) {.noinline, noreturn.} = + ## raises an `ESexpParsingError` exception. + raise newException(SexpParsingError, errorMsgExpected(p, msg)) + +proc newSString*(s: string): SexpNode = + ## Creates a new `SString SexpNode`. + new(result) + result.kind = SString + result.str = s + +proc newSStringMove(s: string): SexpNode = + new(result) + result.kind = SString + shallowCopy(result.str, s) + +proc newSInt*(n: BiggestInt): SexpNode = + ## Creates a new `SInt SexpNode`. + new(result) + result.kind = SInt + result.num = n + +proc newSFloat*(n: float): SexpNode = + ## Creates a new `SFloat SexpNode`. + new(result) + result.kind = SFloat + result.fnum = n + +proc newSNil*(): SexpNode = + ## Creates a new `SNil SexpNode`. + new(result) + +proc newSList*(): SexpNode = + ## Creates a new `SList SexpNode` + new(result) + result.kind = SList + result.elems = @[] + +proc newSSymbol*(s: string): SexpNode = + new(result) + result.kind = SSymbol + result.symbol = s + +proc newSSymbolMove(s: string): SexpNode = + new(result) + result.kind = SSymbol + shallowCopy(result.symbol, s) + +proc getStr*(n: SexpNode, default: string = ""): string = + ## Retrieves the string value of a `SString SexpNode`. + ## + ## Returns ``default`` if ``n`` is not a ``SString``. + if n.kind != SString: return default + else: return n.str + +proc getNum*(n: SexpNode, default: BiggestInt = 0): BiggestInt = + ## Retrieves the int value of a `SInt SexpNode`. + ## + ## Returns ``default`` if ``n`` is not a ``SInt``. + if n.kind != SInt: return default + else: return n.num + +proc getFNum*(n: SexpNode, default: float = 0.0): float = + ## Retrieves the float value of a `SFloat SexpNode`. + ## + ## Returns ``default`` if ``n`` is not a ``SFloat``. + if n.kind != SFloat: return default + else: return n.fnum + +proc getSymbol*(n: SexpNode, default: string = ""): string = + ## Retrieves the int value of a `SList SexpNode`. + ## + ## Returns ``default`` if ``n`` is not a ``SList``. + if n.kind != SSymbol: return default + else: return n.symbol + +proc getElems*(n: SexpNode, default: seq[SexpNode] = @[]): seq[SexpNode] = + ## Retrieves the int value of a `SList SexpNode`. + ## + ## Returns ``default`` if ``n`` is not a ``SList``. + if n.kind == SNil: return @[] + elif n.kind != SList: return default + else: return n.elems + +proc `sexp`*(s: string): SexpNode = + ## Generic constructor for SEXP data. Creates a new `SString SexpNode`. + new(result) + result.kind = SString + result.str = s + +proc `sexp`*(n: BiggestInt): SexpNode = + ## Generic constructor for SEXP data. Creates a new `SInt SexpNode`. + new(result) + result.kind = SInt + result.num = n + +proc `sexp`*(n: float): SexpNode = + ## Generic constructor for SEXP data. Creates a new `SFloat SexpNode`. + new(result) + result.kind = SFloat + result.fnum = n + +proc `sexp`*(b: bool): SexpNode = + ## Generic constructor for SEXP data. Creates a new `SSymbol + ## SexpNode` with value t or `SNil SexpNode`. + new(result) + if b: + result.kind = SSymbol + result.symbol = "t" + else: + result.kind = SNil + +proc `sexp`*(elements: openArray[SexpNode]): SexpNode = + ## Generic constructor for SEXP data. Creates a new `SList SexpNode` + new(result) + result.kind = SList + newSeq(result.elems, elements.len) + for i, p in pairs(elements): result.elems[i] = p + +proc toSexp(x: NimNode): NimNode {.compiletime.} = + case x.kind + of nnkBracket: + result = newNimNode(nnkBracket) + for i in 0 .. = 32 and r <= 127: + var c = chr(r) + case c + of '"': result.add("\\\"") #" # gotta fix nim-mode + of '\\': result.add("\\\\") + else: result.add(c) + else: + result.add("\\u") + result.add(toHex(r, 4)) + result.add("\"") +proc copy*(p: SexpNode): SexpNode = + ## Performs a deep copy of `a`. + case p.kind + of SString: + result = newSString(p.str) + of SInt: + result = newSInt(p.num) + of SFloat: + result = newSFloat(p.fnum) + of SNil: + result = newSNil() + of SSymbol: + result = newSSymbol(p.symbol) + of SList: + result = newSList() + for i in items(p.elems): + result.elems.add(copy(i)) + +proc toPretty(result: var string, node: SexpNode, indent = 2, ml = true, + lstArr = false, currIndent = 0) = + case node.kind + of SString: + if lstArr: result.indent(currIndent) + result.add(escapeJson(node.str)) + of SInt: + if lstArr: result.indent(currIndent) + result.add($node.num) + of SFloat: + if lstArr: result.indent(currIndent) + result.add($node.fnum) + of SNil: + if lstArr: result.indent(currIndent) + result.add("nil") + of SSymbol: + if lstArr: result.indent(currIndent) + result.add($node.symbol) + of SList: + if lstArr: result.indent(currIndent) + if len(node.elems) != 0: + result.add("(") + result.nl(ml) + for i in 0..len(node.elems)-1: + if i > 0: + result.add(" ") + result.nl(ml) # New Line + toPretty(result, node.elems[i], indent, ml, + true, newIndent(currIndent, indent, ml)) + result.nl(ml) + result.indent(currIndent) + result.add(")") + else: result.add("nil") + +proc pretty*(node: SexpNode, indent = 2): string = + ## Converts `node` to its JSON Representation, with indentation and + ## on multiple lines. + result = "" + toPretty(result, node, indent) + +proc `$`*(node: SexpNode): string = + ## Converts `node` to its SEXP Representation on one line. + result = "" + toPretty(result, node, 0, false) + +iterator items*(node: SexpNode): SexpNode = + ## Iterator for the items of `node`. `node` has to be a SList. + assert node.kind == SList + for i in items(node.elems): + yield i + +iterator mitems*(node: var SexpNode): var SexpNode = + ## Iterator for the items of `node`. `node` has to be a SList. Items can be + ## modified. + assert node.kind == SList + for i in mitems(node.elems): + yield i + +proc eat(p: var SexpParser, tok: TTokKind) = + if p.tok == tok: discard getTok(p) + else: raiseParseErr(p, tokToStr[tok]) + +proc parseSexp(p: var SexpParser): SexpNode = + ## Parses SEXP from a SEXP Parser `p`. + case p.tok + of tkString: + # we capture 'p.a' here, so we need to give it a fresh buffer afterwards: + result = newSStringMove(p.a) + p.a = "" + discard getTok(p) + of tkInt: + result = newSInt(parseBiggestInt(p.a)) + discard getTok(p) + of tkFloat: + result = newSFloat(parseFloat(p.a)) + discard getTok(p) + of tkNil: + result = newSNil() + discard getTok(p) + of tkSymbol: + result = newSSymbolMove(p.a) + p.a = "" + discard getTok(p) + of tkParensLe: + result = newSList() + discard getTok(p) + while p.tok != tkParensRi: + result.add(parseSexp(p)) + if p.tok != tkSpace: break + discard getTok(p) + eat(p, tkParensRi) + of tkSpace, tkError, tkParensRi, tkEof: + raiseParseErr(p, "(") + +proc parseSexp*(s: Stream, filename: string): SexpNode = + ## Parses from a stream `s` into a `SexpNode`. `filename` is only needed + ## for nice error messages. + var p: SexpParser + p.open(s, filename) + discard getTok(p) # read first token + result = p.parseSexp() + p.close() + +proc parseSexp*(buffer: string): SexpNode = + ## Parses SEXP from `buffer`. + result = parseSexp(newStringStream(buffer), "input") + +proc parseFile*(filename: string): SexpNode = + ## Parses `file` into a `SexpNode`. + var stream = newFileStream(filename, fmRead) + if stream == nil: + raise newException(IOError, "cannot read from file: " & filename) + result = parseSexp(stream, filename) + +when isMainModule: + let testSexp = parseSexp("""(1 (98 2) nil (2) foobar "foo" 9.234)""") + assert(testSexp[0].getNum == 1) + assert(testSexp[1][0].getNum == 98) + assert(testSexp[2].getElems == @[]) + assert(testSexp[4].getSymbol == "foobar") + assert(testSexp[5].getStr == "foo") + + # Generator: + var j = convertSexp([true, false, "foobar", [1, 2, "baz"]]) + assert($j == """(t nil "foobar" (1 2 "baz"))""") From 8fa8f137412f535784a5222f60d45b3e0439ae0a Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Tue, 14 Apr 2015 02:00:23 -0500 Subject: [PATCH 0144/1263] renamed sexp --- lib/pure/{sexpressions.nim => sexp.nim} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename lib/pure/{sexpressions.nim => sexp.nim} (100%) diff --git a/lib/pure/sexpressions.nim b/lib/pure/sexp.nim similarity index 100% rename from lib/pure/sexpressions.nim rename to lib/pure/sexp.nim From 49b953f318b8183056bc67d50571910026d05c43 Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Tue, 14 Apr 2015 02:47:51 -0500 Subject: [PATCH 0145/1263] sexp also accepts cons --- compiler/nimsuggest/nimsuggest.nim | 3 +- lib/pure/sexp.nim | 180 +++++++++++++---------------- 2 files changed, 81 insertions(+), 102 deletions(-) diff --git a/compiler/nimsuggest/nimsuggest.nim b/compiler/nimsuggest/nimsuggest.nim index b45ca475c..ca856ed57 100644 --- a/compiler/nimsuggest/nimsuggest.nim +++ b/compiler/nimsuggest/nimsuggest.nim @@ -11,7 +11,7 @@ import strutils, os, parseopt, parseUtils import options, commands, modules, sem, passes, passaux, msgs, nimconf, - extccomp, condsyms, lists, net, rdstdin + extccomp, condsyms, lists, net, rdstdin, sexp const Usage = """ Nimsuggest - Tool to give every editor IDE like capabilities for Nim @@ -23,6 +23,7 @@ Options: --address:HOST binds to that address, by default "" --stdin read commands from stdin and write results to stdout instead of using sockets + --sexp talk in sexp, mainly for emacs epc. The server then listens to the connection and takes line-based commands. diff --git a/lib/pure/sexp.nim b/lib/pure/sexp.nim index c30f35c25..97edbf52d 100644 --- a/lib/pure/sexp.nim +++ b/lib/pure/sexp.nim @@ -19,6 +19,7 @@ type sexpInt, ## an integer literal sexpFloat, ## a float literal sexpNil, ## the value ``nil`` + sexpDot, ## the dot to separate car/cdr sexpListStart, ## start of a list: the ``(`` token sexpListEnd, ## end of a list: the ``)`` token @@ -30,6 +31,7 @@ type tkInt, tkFloat, tkNil, + tkDot, tkParensLe, tkParensRi tkSpace @@ -41,16 +43,11 @@ type errQuoteExpected, ## ``"`` expected errEofExpected, ## EOF expected - ParserState = enum - stateEof, stateStart, stateList, stateListExpectsSpace - SexpParser* = object of BaseLexer ## the parser object. a: string tok: TTokKind kind: SexpEventKind err: SexpError - state: seq[ParserState] - filename: string const errorMessages: array [SexpError, string] = [ @@ -68,18 +65,10 @@ const "int literal", "float literal", "nil", - "(", ")", " " + ".", + "(", ")", "space" ] -proc open*(my: var SexpParser, input: Stream, filename: string) = - ## initializes the parser with an input stream. `Filename` is only used - ## for nice error messages. - lexbase.open(my, input) - my.filename = filename - my.state = @[stateStart] - my.kind = sexpError - my.a = "" - proc close*(my: var SexpParser) {.inline.} = ## closes the parser `my` and its associated input stream. lexbase.close(my) @@ -112,21 +101,15 @@ proc getLine*(my: SexpParser): int {.inline.} = ## get the current line the parser has arrived at. result = my.lineNumber -proc getFilename*(my: SexpParser): string {.inline.} = - ## get the filename of the file that the parser processes. - result = my.filename - proc errorMsg*(my: SexpParser): string = ## returns a helpful error message for the event ``sexpError`` assert(my.kind == sexpError) - result = "$1($2, $3) Error: $4" % [ - my.filename, $getLine(my), $getColumn(my), errorMessages[my.err]] + result = "($1, $2) Error: $3" % [$getLine(my), $getColumn(my), errorMessages[my.err]] proc errorMsgExpected*(my: SexpParser, e: string): string = ## returns an error message "`e` expected" in the same format as the ## other error messages - result = "$1($2, $3) Error: $4" % [ - my.filename, $getLine(my), $getColumn(my), e & " expected"] + result = "($1, $2) Error: $3" % [$getLine(my), $getColumn(my), e & " expected"] proc handleHexChar(c: char, x: var int): bool = result = true # Success @@ -237,7 +220,8 @@ proc parseSymbol(my: var SexpParser) = proc getTok(my: var SexpParser): TTokKind = setLen(my.a, 0) case my.buf[my.bufpos] - of '-', '.', '0'..'9': + of '-', '0'..'9': # numbers that start with a . are not parsed + # correctly. parseNumber(my) if {'.', 'e', 'E'} in my.a: result = tkFloat @@ -262,65 +246,14 @@ proc getTok(my: var SexpParser): TTokKind = of ' ': result = tkSpace inc(my.bufpos) + of '.': + result = tkDot + inc(my.bufpos) else: inc(my.bufpos) result = tkError my.tok = result -proc next*(my: var SexpParser) = - ## retrieves the first/next event. This controls the parser. - var tk = getTok(my) - var i = my.state.len-1 - # the following code is a state machine. If we had proper coroutines, - # the code could be much simpler. - case my.state[i] - of stateEof: - if tk == tkEof: - my.kind = sexpEof - else: - my.kind = sexpError - my.err = errEofExpected - of stateStart: - # tokens allowed? - case tk - of tkString, tkInt, tkFloat, tkSymbol, tkNil: - my.state[i] = stateEof # expect EOF next! - my.kind = SexpEventKind(ord(tk)) - of tkParensLe: - my.state.add(stateList) - my.kind = sexpListStart - of tkEof: - my.kind = sexpEof - else: - my.kind = sexpError - my.err = errEofExpected - of stateList: - case tk - of tkString, tkInt, tkFloat, tkSymbol, tkNil: - my.kind = SexpEventKind(ord(tk)) - my.state.add(stateListExpectsSpace) - of tkParensLe: - my.state.add(stateList) - my.kind = sexpListStart - of tkParensRi: - my.kind = sexpListEnd - discard my.state.pop() - else: - my.kind = sexpError - my.err = errParensRiExpected - of stateListExpectsSpace: - case tk - of tkSpace: - discard my.state.pop() - next(my) - of tkParensLe: - my.kind = sexpListEnd - discard my.state.pop() - discard my.state.pop() - else: - my.kind = sexpError - my.err = errParensRiExpected - # ------------- higher level interface --------------------------------------- type @@ -329,8 +262,9 @@ type SInt, SFloat, SString, - SSymbol + SSymbol, SList, + SCons SexpNode* = ref SexpNodeObj ## SEXP node SexpNodeObj* {.acyclic.} = object @@ -345,9 +279,14 @@ type fnum*: float of SList: elems*: seq[SexpNode] + of SCons: + car: SexpNode + cdr: SexpNode of SNil: discard + Cons = tuple[car: SexpNode, cdr: SexpNode] + SexpParsingError* = object of ValueError ## is raised for a SEXP error proc raiseParseErr*(p: SexpParser, msg: string) {.noinline, noreturn.} = @@ -381,6 +320,13 @@ proc newSNil*(): SexpNode = ## Creates a new `SNil SexpNode`. new(result) +proc newSCons*(car, cdr: SexpNode): SexpNode = + ## Creates a new `SCons SexpNode` + new(result) + result.kind = SCons + result.car = car + result.cdr = cdr + proc newSList*(): SexpNode = ## Creates a new `SList SexpNode` new(result) @@ -433,6 +379,14 @@ proc getElems*(n: SexpNode, default: seq[SexpNode] = @[]): seq[SexpNode] = elif n.kind != SList: return default else: return n.elems +proc getCons*(n: SexpNode, defaults: Cons = (newSNil(), newSNil())): Cons = + ## Retrieves the cons value of a `SList SexpNode`. + ## + ## Returns ``default`` if ``n`` is not a ``SList``. + if n.kind == SCons: return (n.car, n.cdr) + elif n.kind == SList: return (n.elems[0], n.elems[1]) + else: return defaults + proc `sexp`*(s: string): SexpNode = ## Generic constructor for SEXP data. Creates a new `SString SexpNode`. new(result) @@ -506,6 +460,8 @@ proc `==`* (a,b: SexpNode): bool = a.elems == b.elems of SSymbol: a.symbol == b.symbol + of SCons: + a.car == b.car and a.cdr == b.cdr proc hash* (n:SexpNode): THash = ## Compute the hash for a SEXP node @@ -522,6 +478,8 @@ proc hash* (n:SexpNode): THash = result = hash(0) of SSymbol: result = hash(n.symbol) + of SCons: + result = hash(n.car) !& hash(n.cdr) proc len*(n: SexpNode): int = ## If `n` is a `SList`, it returns the number of elements. @@ -571,6 +529,7 @@ proc escapeJson*(s: string): string = result.add("\\u") result.add(toHex(r, 4)) result.add("\"") + proc copy*(p: SexpNode): SexpNode = ## Performs a deep copy of `a`. case p.kind @@ -588,6 +547,8 @@ proc copy*(p: SexpNode): SexpNode = result = newSList() for i in items(p.elems): result.elems.add(copy(i)) + of SCons: + result = newSCons(copy(p.car), copy(p.cdr)) proc toPretty(result: var string, node: SexpNode, indent = 2, ml = true, lstArr = false, currIndent = 0) = @@ -622,9 +583,18 @@ proc toPretty(result: var string, node: SexpNode, indent = 2, ml = true, result.indent(currIndent) result.add(")") else: result.add("nil") + of SCons: + if lstArr: result.indent(currIndent) + result.add("(") + toPretty(result, node.car, indent, ml, + true, newIndent(currIndent, indent, ml)) + result.add(" . ") + toPretty(result, node.cdr, indent, ml, + true, newIndent(currIndent, indent, ml)) + result.add(")") proc pretty*(node: SexpNode, indent = 2): string = - ## Converts `node` to its JSON Representation, with indentation and + ## Converts `node` to its Sexp Representation, with indentation and ## on multiple lines. result = "" toPretty(result, node, indent) @@ -675,41 +645,49 @@ proc parseSexp(p: var SexpParser): SexpNode = of tkParensLe: result = newSList() discard getTok(p) - while p.tok != tkParensRi: + while p.tok notin {tkParensRi, tkDot}: result.add(parseSexp(p)) if p.tok != tkSpace: break discard getTok(p) + if p.tok == tkDot: + eat(p, tkDot) + eat(p, tkSpace) + result.add(parseSexp(p)) + result = newSCons(result[0], result[1]) eat(p, tkParensRi) - of tkSpace, tkError, tkParensRi, tkEof: + of tkSpace, tkDot, tkError, tkParensRi, tkEof: raiseParseErr(p, "(") -proc parseSexp*(s: Stream, filename: string): SexpNode = - ## Parses from a stream `s` into a `SexpNode`. `filename` is only needed - ## for nice error messages. +proc open*(my: var SexpParser, input: Stream) = + ## initializes the parser with an input stream. + lexbase.open(my, input) + my.kind = sexpError + my.a = "" + +proc parseSexp*(s: Stream): SexpNode = + ## Parses from a buffer `s` into a `SexpNode`. var p: SexpParser - p.open(s, filename) + p.open(s) discard getTok(p) # read first token result = p.parseSexp() p.close() proc parseSexp*(buffer: string): SexpNode = - ## Parses SEXP from `buffer`. - result = parseSexp(newStringStream(buffer), "input") - -proc parseFile*(filename: string): SexpNode = - ## Parses `file` into a `SexpNode`. - var stream = newFileStream(filename, fmRead) - if stream == nil: - raise newException(IOError, "cannot read from file: " & filename) - result = parseSexp(stream, filename) + ## Parses Sexp from `buffer`. + result = parseSexp(newStringStream(buffer)) when isMainModule: - let testSexp = parseSexp("""(1 (98 2) nil (2) foobar "foo" 9.234)""") - assert(testSexp[0].getNum == 1) - assert(testSexp[1][0].getNum == 98) - assert(testSexp[2].getElems == @[]) - assert(testSexp[4].getSymbol == "foobar") - assert(testSexp[5].getStr == "foo") + # let testSexp = parseSexp("""(1 (98 2) nil (2) foobar "foo" 9.234)""") + # assert(testSexp[0].getNum == 1) + # assert(testSexp[1][0].getNum == 98) + # assert(testSexp[2].getElems == @[]) + # assert(testSexp[4].getSymbol == "foobar") + # assert(testSexp[5].getStr == "foo") + + let alist = parseSexp("""((1 . 2) (2 . "foo"))""") + assert(alist[0].getCons.car.getNum == 1) + assert(alist[0].getCons.cdr.getNum == 2) + assert(alist[1].getCons.cdr.getStr == "foo") # Generator: var j = convertSexp([true, false, "foobar", [1, 2, "baz"]]) From 371d2739249ad33267e0b330e582a04d7d28fd98 Mon Sep 17 00:00:00 2001 From: Kay Zheng Date: Fri, 17 Apr 2015 22:24:06 +0800 Subject: [PATCH 0146/1263] Add a test case for the EvError handling issue --- tests/async/tasynceverror.nim | 62 +++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 tests/async/tasynceverror.nim diff --git a/tests/async/tasynceverror.nim b/tests/async/tasynceverror.nim new file mode 100644 index 000000000..564df569e --- /dev/null +++ b/tests/async/tasynceverror.nim @@ -0,0 +1,62 @@ +discard """ + file: "tasynceverror.nim" + exitcode: 1 + outputsub: "Error: unhandled exception: Connection reset by peer [Exception]" +""" + +import + asyncdispatch, + asyncnet, + rawsockets, + os + + +const + testHost = "127.0.0.1" + testPort = Port(17357) + + +proc createListenSocket(host: string, port: Port): TAsyncFD = + result = newAsyncRawSocket() + + SocketHandle(result).setSockOptInt(SOL_SOCKET, SO_REUSEADDR, 1) + + var aiList = getAddrInfo(host, port, AF_INET) + if SocketHandle(result).bindAddr(aiList.ai_addr, aiList.ai_addrlen.Socklen) < 0'i32: + dealloc(aiList) + raiseOSError(osLastError()) + dealloc(aiList) + + if SocketHandle(result).listen(1) < 0'i32: + raiseOSError(osLastError()) + + +proc testAsyncSend() {.async.} = + var + ls = createListenSocket(testHost, testPort) + s = newAsyncSocket() + + await s.connect(testHost, testPort) + + var ps = await ls.accept() + SocketHandle(ls).close() + + await ps.send("test 1", flags={}) + s.close() + # This send should raise EPIPE + await ps.send("test 2", flags={}) + SocketHandle(ps).close() + + +# The bug was, when the poll function handled EvError for us, +# our callbacks may never get executed, thus making the event +# loop block indefinitely. This is a timer to keep everything +# rolling. 400 ms is an arbitrary value, should be enough though. +proc timer() {.async.} = + await sleepAsync(400) + echo("Timer expired.") + quit(2) + + +asyncCheck(testAsyncSend()) +waitFor(timer()) From 3125058b6ab4bd9c3ad2cb103bb326463af0a7ff Mon Sep 17 00:00:00 2001 From: Kay Zheng Date: Fri, 17 Apr 2015 22:40:53 +0800 Subject: [PATCH 0147/1263] Only run the test for the fixed version of poll(...) --- tests/async/tasynceverror.nim | 69 ++++++++++++++++++----------------- 1 file changed, 36 insertions(+), 33 deletions(-) diff --git a/tests/async/tasynceverror.nim b/tests/async/tasynceverror.nim index 564df569e..3b81680cb 100644 --- a/tests/async/tasynceverror.nim +++ b/tests/async/tasynceverror.nim @@ -16,47 +16,50 @@ const testPort = Port(17357) -proc createListenSocket(host: string, port: Port): TAsyncFD = - result = newAsyncRawSocket() +when defined(windows) or defined(nimdoc): + discard +else: + proc createListenSocket(host: string, port: Port): TAsyncFD = + result = newAsyncRawSocket() - SocketHandle(result).setSockOptInt(SOL_SOCKET, SO_REUSEADDR, 1) + SocketHandle(result).setSockOptInt(SOL_SOCKET, SO_REUSEADDR, 1) - var aiList = getAddrInfo(host, port, AF_INET) - if SocketHandle(result).bindAddr(aiList.ai_addr, aiList.ai_addrlen.Socklen) < 0'i32: - dealloc(aiList) - raiseOSError(osLastError()) - dealloc(aiList) + var aiList = getAddrInfo(host, port, AF_INET) + if SocketHandle(result).bindAddr(aiList.ai_addr, aiList.ai_addrlen.Socklen) < 0'i32: + dealloc(aiList) + raiseOSError(osLastError()) + dealloc(aiList) - if SocketHandle(result).listen(1) < 0'i32: - raiseOSError(osLastError()) + if SocketHandle(result).listen(1) < 0'i32: + raiseOSError(osLastError()) -proc testAsyncSend() {.async.} = - var - ls = createListenSocket(testHost, testPort) - s = newAsyncSocket() + proc testAsyncSend() {.async.} = + var + ls = createListenSocket(testHost, testPort) + s = newAsyncSocket() - await s.connect(testHost, testPort) - - var ps = await ls.accept() - SocketHandle(ls).close() + await s.connect(testHost, testPort) + + var ps = await ls.accept() + SocketHandle(ls).close() - await ps.send("test 1", flags={}) - s.close() - # This send should raise EPIPE - await ps.send("test 2", flags={}) - SocketHandle(ps).close() + await ps.send("test 1", flags={}) + s.close() + # This send should raise EPIPE + await ps.send("test 2", flags={}) + SocketHandle(ps).close() -# The bug was, when the poll function handled EvError for us, -# our callbacks may never get executed, thus making the event -# loop block indefinitely. This is a timer to keep everything -# rolling. 400 ms is an arbitrary value, should be enough though. -proc timer() {.async.} = - await sleepAsync(400) - echo("Timer expired.") - quit(2) + # The bug was, when the poll function handled EvError for us, + # our callbacks may never get executed, thus making the event + # loop block indefinitely. This is a timer to keep everything + # rolling. 400 ms is an arbitrary value, should be enough though. + proc timer() {.async.} = + await sleepAsync(400) + echo("Timer expired.") + quit(2) -asyncCheck(testAsyncSend()) -waitFor(timer()) + asyncCheck(testAsyncSend()) + waitFor(timer()) From a11a2f0fdb3ecdd995e4fc1a6cb41de4e7fc12f2 Mon Sep 17 00:00:00 2001 From: Kay Zheng Date: Sat, 18 Apr 2015 10:27:35 +0800 Subject: [PATCH 0148/1263] Check for async errors in --- lib/pure/asyncdispatch.nim | 14 +++++++++++--- tests/async/tasyncconnect.nim | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 3 deletions(-) create mode 100644 tests/async/tasyncconnect.nim diff --git a/lib/pure/asyncdispatch.nim b/lib/pure/asyncdispatch.nim index 6ed782545..ca5b13c78 100644 --- a/lib/pure/asyncdispatch.nim +++ b/lib/pure/asyncdispatch.nim @@ -923,9 +923,17 @@ else: var retFuture = newFuture[void]("connect") proc cb(fd: TAsyncFD): bool = - # We have connected. - retFuture.complete() - return true + var ret = SocketHandle(fd).getSockOptInt(cint(SOL_SOCKET), cint(SO_ERROR)) + if ret == 0: + # We have connected. + retFuture.complete() + return true + elif ret == EINTR: + # interrupted, keep waiting + return false + else: + retFuture.fail(newException(OSError, osErrorMsg(OSErrorCode(ret)))) + return true var aiList = getAddrInfo(address, port, af) var success = false diff --git a/tests/async/tasyncconnect.nim b/tests/async/tasyncconnect.nim new file mode 100644 index 000000000..bc63b8e82 --- /dev/null +++ b/tests/async/tasyncconnect.nim @@ -0,0 +1,33 @@ +discard """ + file: "tasyncconnect.nim" + exitcode: 1 + outputsub: "Error: unhandled exception: Connection refused [Exception]" +""" + +import + asyncdispatch, + posix + + +const + testHost = "127.0.0.1" + testPort = Port(17357) + + +when defined(windows) or defined(nimdoc): + discard +else: + proc testAsyncConnect() {.async.} = + var s = newAsyncRawSocket() + + await s.connect(testHost, testPort) + + var peerAddr: SockAddr + var addrSize = Socklen(sizeof(peerAddr)) + var ret = SocketHandle(s).getpeername(addr(peerAddr), addr(addrSize)) + + if ret < 0: + echo("`connect(...)` failed but no exception was raised.") + quit(2) + + waitFor(testAsyncConnect()) From e76f54e059fc89bb2cdab0a61700988c56b609d3 Mon Sep 17 00:00:00 2001 From: Josep Sanjuas Date: Sat, 18 Apr 2015 13:28:48 +0200 Subject: [PATCH 0149/1263] Generalize variance to other types --- lib/pure/math.nim | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/pure/math.nim b/lib/pure/math.nim index 0051c9d88..ef9c69e3c 100644 --- a/lib/pure/math.nim +++ b/lib/pure/math.nim @@ -122,13 +122,13 @@ proc mean*[T](x: openArray[T]): float {.noSideEffect.} = ## ``toFloat(x: T): float`` must be defined. result = toFloat(sum(x)) / toFloat(len(x)) -proc variance*(x: openArray[float]): float {.noSideEffect.} = +proc variance*[T](x: openArray[T]): float {.noSideEffect.} = ## computes the variance of the elements in `x`. ## If `x` is empty, NaN is returned. result = 0.0 var m = mean(x) - for i in 0 .. high(x): - var diff = x[i] - m + for i in items(x): + var diff = toFloat(i) - m result = result + diff*diff result = result / toFloat(len(x)) From 44246b670921aca1d31cb74dcc00139b5ed9a2c2 Mon Sep 17 00:00:00 2001 From: Josep Sanjuas Date: Sat, 18 Apr 2015 13:38:15 +0200 Subject: [PATCH 0150/1263] Document toFloat is necessary --- lib/pure/math.nim | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/pure/math.nim b/lib/pure/math.nim index ef9c69e3c..05c2cf57c 100644 --- a/lib/pure/math.nim +++ b/lib/pure/math.nim @@ -125,6 +125,7 @@ proc mean*[T](x: openArray[T]): float {.noSideEffect.} = proc variance*[T](x: openArray[T]): float {.noSideEffect.} = ## computes the variance of the elements in `x`. ## If `x` is empty, NaN is returned. + ## ``toFloat(x: T): float`` must be defined. result = 0.0 var m = mean(x) for i in items(x): From f72bb57fff29609336beae56ae148e20d0dd702e Mon Sep 17 00:00:00 2001 From: Josep Sanjuas Date: Sat, 18 Apr 2015 13:40:20 +0200 Subject: [PATCH 0151/1263] Convert to float before sum --- lib/pure/math.nim | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lib/pure/math.nim b/lib/pure/math.nim index 05c2cf57c..9bd594549 100644 --- a/lib/pure/math.nim +++ b/lib/pure/math.nim @@ -117,10 +117,11 @@ proc sum*[T](x: openArray[T]): T {.noSideEffect.} = template toFloat(f: float): float = f proc mean*[T](x: openArray[T]): float {.noSideEffect.} = - ## computes the mean of the elements in `x`. + ## computes the mean of the elements in `x`, which are first converted to floats. ## If `x` is empty, NaN is returned. ## ``toFloat(x: T): float`` must be defined. - result = toFloat(sum(x)) / toFloat(len(x)) + for i in items(x): result = result + toFloat(i) + result = result / toFloat(len(x)) proc variance*[T](x: openArray[T]): float {.noSideEffect.} = ## computes the variance of the elements in `x`. From 518db9eb7ee538f3c33732e5a04cbacd024ee8b7 Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Wed, 22 Apr 2015 06:10:47 +0500 Subject: [PATCH 0152/1263] rewrite suggest.nim for suggestionResultHook --- compiler/suggest.nim | 149 +++++++++++++++++++++++++++++++------------ 1 file changed, 108 insertions(+), 41 deletions(-) diff --git a/compiler/suggest.nim b/compiler/suggest.nim index 6b168670c..072145a70 100644 --- a/compiler/suggest.nim +++ b/compiler/suggest.nim @@ -20,52 +20,119 @@ const sectionContext = "con" sectionUsage = "use" +type + Section = enum sug, def, con, use + Suggest = object + section: Section + qualifiedPath: seq[string] + filePath: string + line: int # Starts at 1 + column: int # Starts at 0 + doc: string # Not escaped (yet) + symkind: TSymKind + forth: string # XXX TODO object on symkind + +var + suggestionResultHook*: proc (result: Suggest) {.closure.} + #template sectionSuggest(): expr = "##begin\n" & getStackTrace() & "##end\n" template origModuleName(m: PSym): string = m.name.s -proc symToStr(s: PSym, isLocal: bool, section: string, li: TLineInfo): string = - result = section - result.add(sep) +proc parseSection(s: string): Section = + case s: + of "sug": result = sug + of "con": result = con + of "use": result = use + of "def": result = def + else: raise newException(ERecoverableError, "Answer type incorrect") + +proc parseSymKind(s: string): TSymKind = + case s: + of "skDynLib": result = skDynLib + of "skParam": result = skParam + of "skGenericParam": result = skGenericParam + of "skTemp": result = skTemp + of "skModule": result = skModule + of "skType": result = skType + of "skVar": result = skVar + of "skLet": result = skLet + of "skConst": result = skConst + of "skResult": result = skResult + of "skProc": result = skProc + of "skMethod": result = skMethod + of "skIterator": result = skIterator + of "skClosureIterator": result = skClosureIterator + of "skConverter": result = skConverter + of "skMacro": result = skMacro + of "skTemplate": result = skTemplate + of "skField": result = skField + of "skEnumField": result = skEnumField + of "skForVar": result = skForVar + of "skLabel": result = skLabel + of "skStub": result = skStub + of "skPackage": result = skPackage + of "skAlias": result = skAlias + else: raise newException(ERecoverableError, "TSymKind not found") + +proc symToSuggest(s: PSym, isLocal: bool, section: string, li: TLineInfo): Suggest = + result.section = parseSection(section) if optIdeTerse in gGlobalOptions: if s.kind in routineKinds: - result.add renderTree(s.ast, {renderNoBody, renderNoComments, - renderDocComments, renderNoPragmas}) + result.symkind = parseSymKind(renderTree(s.ast, {renderNoBody, renderNoComments, + renderDocComments, renderNoPragmas})) else: - result.add s.name.s - result.add(sep) - result.add(toFullPath(li)) - result.add(sep) - result.add($toLinenumber(li)) - result.add(sep) - result.add($toColumn(li)) + result.symkind = parseSymKind(s.name.s) + result.filePath = toFullPath(li) + result.line = toLinenumber(li) + result.column = toColumn(li) else: - result.add($s.kind) - result.add(sep) + result.symkind = s.kind + result.qualifiedPath = @[] if not isLocal and s.kind != skModule: let ow = s.owner if ow.kind != skModule and ow.owner != nil: let ow2 = ow.owner - result.add(ow2.origModuleName) - result.add('.') - result.add(ow.origModuleName) - result.add('.') - result.add(s.name.s) - result.add(sep) - if s.typ != nil: - result.add(typeToString(s.typ)) - result.add(sep) - result.add(toFullPath(li)) - result.add(sep) - result.add($toLinenumber(li)) - result.add(sep) - result.add($toColumn(li)) - result.add(sep) - when not defined(noDocgen): - result.add(s.extractDocComment.escape) + result.qualifiedPath.add(ow2.origModuleName) + result.qualifiedPath.add(ow.origModuleName) + result.qualifiedPath.add(s.name.s) -proc symToStr(s: PSym, isLocal: bool, section: string): string = - result = symToStr(s, isLocal, section, s.info) + if s.typ != nil: + result.forth = typeToString(s.typ) + else: + result.forth = "" + result.filePath = toFullPath(li) + result.line = toLinenumber(li) + result.column = toColumn(li) + when not defined(noDocgen): + result.doc = s.extractDocComment + +proc `$`(suggest: Suggest): string = + result = $suggest.section + result.add(sep) + result.add($suggest.symkind) + result.add(sep) + result.add(suggest.qualifiedPath.join(".")) + result.add(sep) + result.add(suggest.forth) + result.add(sep) + result.add(suggest.filePath) + result.add(sep) + result.add($suggest.line) + result.add(sep) + result.add($suggest.column) + result.add(sep) + when not defined(noDocgen): + result.add(suggest.doc.escape) + +proc symToSuggest(s: PSym, isLocal: bool, section: string): Suggest = + result = symToSuggest(s, isLocal, section, s.info) + +proc suggestResult(s: Suggest) = + if not isNil(suggestionResultHook): + suggestionResultHook(s) + else: + suggestWriteln($(s)) proc filterSym(s: PSym): bool {.inline.} = result = s.kind != skModule @@ -84,7 +151,7 @@ proc fieldVisible*(c: PContext, f: PSym): bool {.inline.} = proc suggestField(c: PContext, s: PSym, outputs: var int) = if filterSym(s) and fieldVisible(c, s): - suggestWriteln(symToStr(s, isLocal=true, sectionSuggest)) + suggestResult(symToSuggest(s, isLocal=true, sectionSuggest)) inc outputs template wholeSymTab(cond, section: expr) {.immediate.} = @@ -97,7 +164,7 @@ template wholeSymTab(cond, section: expr) {.immediate.} = for item in entries: let it {.inject.} = item if cond: - suggestWriteln(symToStr(it, isLocal = isLocal, section)) + suggestResult(symToSuggest(it, isLocal = isLocal, section)) inc outputs proc suggestSymList(c: PContext, list: PNode, outputs: var int) = @@ -166,7 +233,7 @@ proc suggestEverything(c: PContext, n: PNode, outputs: var int) = if scope == c.topLevelScope: isLocal = false for it in items(scope.symbols): if filterSym(it): - suggestWriteln(symToStr(it, isLocal = isLocal, sectionSuggest)) + suggestResult(symToSuggest(it, isLocal = isLocal, sectionSuggest)) inc outputs if scope == c.topLevelScope: break @@ -181,12 +248,12 @@ proc suggestFieldAccess(c: PContext, n: PNode, outputs: var int) = # all symbols accessible, because we are in the current module: for it in items(c.topLevelScope.symbols): if filterSym(it): - suggestWriteln(symToStr(it, isLocal=false, sectionSuggest)) + suggestResult(symToSuggest(it, isLocal=false, sectionSuggest)) inc outputs else: for it in items(n.sym.tab): if filterSym(it): - suggestWriteln(symToStr(it, isLocal=false, sectionSuggest)) + suggestResult(symToSuggest(it, isLocal=false, sectionSuggest)) inc outputs else: # fallback: @@ -263,16 +330,16 @@ var proc findUsages(info: TLineInfo; s: PSym) = if usageSym == nil and isTracked(info, s.name.s.len): usageSym = s - suggestWriteln(symToStr(s, isLocal=false, sectionUsage)) + suggestResult(symToSuggest(s, isLocal=false, sectionUsage)) elif s == usageSym: if lastLineInfo != info: - suggestWriteln(symToStr(s, isLocal=false, sectionUsage, info)) + suggestResult(symToSuggest(s, isLocal=false, sectionUsage, info)) lastLineInfo = info proc findDefinition(info: TLineInfo; s: PSym) = if s.isNil: return if isTracked(info, s.name.s.len): - suggestWriteln(symToStr(s, isLocal=false, sectionDef)) + suggestResult(symToSuggest(s, isLocal=false, sectionDef)) suggestQuit() proc ensureIdx[T](x: var T, y: int) = From 766b7ea61d74532ede74e0aea59b2cda3400cfed Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Wed, 22 Apr 2015 06:11:30 +0500 Subject: [PATCH 0153/1263] enabled sexp tests --- lib/pure/sexp.nim | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/lib/pure/sexp.nim b/lib/pure/sexp.nim index 97edbf52d..2a9678432 100644 --- a/lib/pure/sexp.nim +++ b/lib/pure/sexp.nim @@ -677,12 +677,12 @@ proc parseSexp*(buffer: string): SexpNode = result = parseSexp(newStringStream(buffer)) when isMainModule: - # let testSexp = parseSexp("""(1 (98 2) nil (2) foobar "foo" 9.234)""") - # assert(testSexp[0].getNum == 1) - # assert(testSexp[1][0].getNum == 98) - # assert(testSexp[2].getElems == @[]) - # assert(testSexp[4].getSymbol == "foobar") - # assert(testSexp[5].getStr == "foo") + let testSexp = parseSexp("""(1 (98 2) nil (2) foobar "foo" 9.234)""") + assert(testSexp[0].getNum == 1) + assert(testSexp[1][0].getNum == 98) + assert(testSexp[2].getElems == @[]) + assert(testSexp[4].getSymbol == "foobar") + assert(testSexp[5].getStr == "foo") let alist = parseSexp("""((1 . 2) (2 . "foo"))""") assert(alist[0].getCons.car.getNum == 1) From b01b7675abdbf9814b8c1b05a7df4c05b113e6e6 Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Wed, 22 Apr 2015 06:15:52 +0500 Subject: [PATCH 0154/1263] parseEnum ftw --- compiler/suggest.nim | 44 ++++---------------------------------------- 1 file changed, 4 insertions(+), 40 deletions(-) diff --git a/compiler/suggest.nim b/compiler/suggest.nim index 072145a70..97d0b51c2 100644 --- a/compiler/suggest.nim +++ b/compiler/suggest.nim @@ -11,7 +11,7 @@ # included from sigmatch.nim -import algorithm, sequtils +import algorithm, sequtils, strutils const sep = '\t' @@ -39,50 +39,14 @@ var template origModuleName(m: PSym): string = m.name.s -proc parseSection(s: string): Section = - case s: - of "sug": result = sug - of "con": result = con - of "use": result = use - of "def": result = def - else: raise newException(ERecoverableError, "Answer type incorrect") - -proc parseSymKind(s: string): TSymKind = - case s: - of "skDynLib": result = skDynLib - of "skParam": result = skParam - of "skGenericParam": result = skGenericParam - of "skTemp": result = skTemp - of "skModule": result = skModule - of "skType": result = skType - of "skVar": result = skVar - of "skLet": result = skLet - of "skConst": result = skConst - of "skResult": result = skResult - of "skProc": result = skProc - of "skMethod": result = skMethod - of "skIterator": result = skIterator - of "skClosureIterator": result = skClosureIterator - of "skConverter": result = skConverter - of "skMacro": result = skMacro - of "skTemplate": result = skTemplate - of "skField": result = skField - of "skEnumField": result = skEnumField - of "skForVar": result = skForVar - of "skLabel": result = skLabel - of "skStub": result = skStub - of "skPackage": result = skPackage - of "skAlias": result = skAlias - else: raise newException(ERecoverableError, "TSymKind not found") - proc symToSuggest(s: PSym, isLocal: bool, section: string, li: TLineInfo): Suggest = - result.section = parseSection(section) + result.section = parseEnum[Section](section) if optIdeTerse in gGlobalOptions: if s.kind in routineKinds: - result.symkind = parseSymKind(renderTree(s.ast, {renderNoBody, renderNoComments, + result.symkind = parseEnum[TSymKind](renderTree(s.ast, {renderNoBody, renderNoComments, renderDocComments, renderNoPragmas})) else: - result.symkind = parseSymKind(s.name.s) + result.symkind = parseEnum[TSymKind](s.name.s) result.filePath = toFullPath(li) result.line = toLinenumber(li) result.column = toColumn(li) From f0f72613d87f5bd742eb64f61b75567c205e62e8 Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Wed, 22 Apr 2015 06:32:02 +0500 Subject: [PATCH 0155/1263] epc skeleton --- compiler/nimsuggest/nimsuggest.nim | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/compiler/nimsuggest/nimsuggest.nim b/compiler/nimsuggest/nimsuggest.nim index ca856ed57..caf21fbd0 100644 --- a/compiler/nimsuggest/nimsuggest.nim +++ b/compiler/nimsuggest/nimsuggest.nim @@ -23,18 +23,20 @@ Options: --address:HOST binds to that address, by default "" --stdin read commands from stdin and write results to stdout instead of using sockets - --sexp talk in sexp, mainly for emacs epc. + --epc use emacs epc mode The server then listens to the connection and takes line-based commands. In addition, all command line options of Nim that do not affect code generation are supported. """ +type + Mode = enum mstdin, mtcp, mepc var gPort = 6000.Port gAddress = "" - gUseStdin: bool + gMode: Mode const seps = {':', ';', ' ', '\t'} @@ -109,14 +111,15 @@ proc action(cmd: string) = proc serve() = # do not stop after the first error: msgs.gErrorMax = high(int) - if gUseStdin: + case gMode: + of mstdin: echo Help var line = "" while readLineFromStdin("> ", line): action line echo "" flushFile(stdout) - else: + of mtcp: var server = newSocket() server.bindAddr(gPort, gAddress) var inp = "".TaintedString @@ -134,6 +137,8 @@ proc serve() = stdoutSocket.send("\c\L") stdoutSocket.close() + of mepc: + discard proc mainCommand = registerPass verbosePass @@ -157,9 +162,14 @@ proc processCmdLine*(pass: TCmdLinePass, cmd: string) = of cmdEnd: break of cmdLongoption, cmdShortOption: case p.key.normalize - of "port": gPort = parseInt(p.val).Port - of "address": gAddress = p.val - of "stdin": gUseStdin = true + of "port": + gPort = parseInt(p.val).Port + gMode = mtcp + of "address": + gAddress = p.val + gMode = mtcp + of "stdin": gMode = mstdin + of "epc": gMode = mepc else: processSwitch(pass, p) of cmdArgument: options.gProjectName = unixToNativePath(p.key) From 7d42eb2de2ef85925c2a933e71f7fad3ab411bce Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Wed, 22 Apr 2015 21:53:04 +0500 Subject: [PATCH 0156/1263] barebones in nimsuggest for EPC --- compiler/nimsuggest/nimsuggest.nim | 84 ++++++++++++++++++++++++++++-- compiler/suggest.nim | 23 ++++---- lib/pure/sexp.nim | 24 ++++----- 3 files changed, 104 insertions(+), 27 deletions(-) diff --git a/compiler/nimsuggest/nimsuggest.nim b/compiler/nimsuggest/nimsuggest.nim index caf21fbd0..d6bd01ce7 100644 --- a/compiler/nimsuggest/nimsuggest.nim +++ b/compiler/nimsuggest/nimsuggest.nim @@ -9,9 +9,9 @@ ## Nimsuggest is a tool that helps to give editors IDE like capabilities. -import strutils, os, parseopt, parseUtils +import strutils, os, parseopt, parseutils, sequtils import options, commands, modules, sem, passes, passaux, msgs, nimconf, - extccomp, condsyms, lists, net, rdstdin, sexp + extccomp, condsyms, lists, net, rdstdin, sexp, suggest, ast const Usage = """ Nimsuggest - Tool to give every editor IDE like capabilities for Nim @@ -54,6 +54,35 @@ proc parseQuoted(cmd: string; outp: var string; start: int): int = i += parseUntil(cmd, outp, seps, i) result = i +# make sure it's in the same order as the proc below +let order: SexpNode = + sexp(@["section", "symkind", "qualifiedPath", "filePath", "forth", "line", "column", "doc"].map(newSSymbol)) + +proc sexp(s: Section): SexpNode = sexp($s) + +proc sexp(s: TSymKind): SexpNode = sexp($s) + +proc sexp(s: Suggest): SexpNode = + result = convertSexp([ + s.section, + s.symkind, + s.qualifiedPath.map(newSString), + s.filePath, + s.forth, + s.line, + s.column, + s.doc + ]) + +proc sexp(s: seq[Suggest]): SexpNode = + result = sexp(s) + +proc listEPC(): SexpNode = + discard + +proc executeEPC(body: SexpNode) = + discard + proc action(cmd: string) = template toggle(sw) = if sw in gGlobalOptions: @@ -138,7 +167,52 @@ proc serve() = stdoutSocket.send("\c\L") stdoutSocket.close() of mepc: - discard + let port = 98294 # guaranteed to be random + var server = newSocket() + server.bindaddr(port.Port, "localhost") + var inp = "".TaintedString + server.listen() + echo(port) + while true: + var results: seq[Suggest] = @[] + var client = newSocket() + suggest.suggestionResultHook = proc (s: Suggest) = + results.add(s) + + accept(server, client) + var sizeHex = "" + if client.recv(sizeHex, 6, 1000) != 6: + raise newException(ValueError, "didn't get all the hexbytes") + var size = 0 + if parseHex(sizeHex, size) == 0: + raiseRecoverableError("invalid size hex: " & $sizeHex) + var messageBuffer = "" + if client.recv(messageBuffer, size, 3000) != size: + raise newException(ValueError, "didn't get all the bytes") + let message = parseSexp($messageBuffer) + let messageType = message[0].getSymbol + let body = message[1] + case messageType: + of "call": + executeEPC(body) + let response = $sexp(results) + client.send(toHex(len(response), 6)) + client.send(response) + client.close() + of "return": + raise newException(ValueError, "no return expected") + of "return-error": + raise newException(ValueError, "no return expected") + of "epc-error": + stderr.writeln("recieved epc error: " & $messageBuffer) + raise newException(ValueError, "epc error") + of "methods": + let response = $listEPC() + client.send(toHex(len(response), 6)) + client.send(response) + client.close() + else: + raise newException(ValueError, "unexpected call: " & messageType) proc mainCommand = registerPass verbosePass @@ -169,7 +243,9 @@ proc processCmdLine*(pass: TCmdLinePass, cmd: string) = gAddress = p.val gMode = mtcp of "stdin": gMode = mstdin - of "epc": gMode = mepc + of "epc": + gMode = mepc + gVerbosity = 0 # Port number gotta be first. else: processSwitch(pass, p) of cmdArgument: options.gProjectName = unixToNativePath(p.key) diff --git a/compiler/suggest.nim b/compiler/suggest.nim index 97d0b51c2..539d4bc5d 100644 --- a/compiler/suggest.nim +++ b/compiler/suggest.nim @@ -11,7 +11,8 @@ # included from sigmatch.nim -import algorithm, sequtils, strutils +import algorithm, sequtils, strutils, ast, msgs, options, renderer, + types, docgen, lexer, semdata, astalgo, idents, sigmatch, lookups const sep = '\t' @@ -21,16 +22,16 @@ const sectionUsage = "use" type - Section = enum sug, def, con, use - Suggest = object - section: Section - qualifiedPath: seq[string] - filePath: string - line: int # Starts at 1 - column: int # Starts at 0 - doc: string # Not escaped (yet) - symkind: TSymKind - forth: string # XXX TODO object on symkind + Section* = enum sug, def, con, use + Suggest* = object + section*: Section + qualifiedPath*: seq[string] + filePath*: string + line*: int # Starts at 1 + column*: int # Starts at 0 + doc*: string # Not escaped (yet) + symkind*: TSymKind + forth*: string # XXX TODO object on symkind var suggestionResultHook*: proc (result: Suggest) {.closure.} diff --git a/lib/pure/sexp.nim b/lib/pure/sexp.nim index 2a9678432..b5e67b90f 100644 --- a/lib/pure/sexp.nim +++ b/lib/pure/sexp.nim @@ -293,7 +293,7 @@ proc raiseParseErr*(p: SexpParser, msg: string) {.noinline, noreturn.} = ## raises an `ESexpParsingError` exception. raise newException(SexpParsingError, errorMsgExpected(p, msg)) -proc newSString*(s: string): SexpNode = +proc newSString*(s: string): SexpNode {.procvar.}= ## Creates a new `SString SexpNode`. new(result) result.kind = SString @@ -304,36 +304,36 @@ proc newSStringMove(s: string): SexpNode = result.kind = SString shallowCopy(result.str, s) -proc newSInt*(n: BiggestInt): SexpNode = +proc newSInt*(n: BiggestInt): SexpNode {.procvar.} = ## Creates a new `SInt SexpNode`. new(result) result.kind = SInt result.num = n -proc newSFloat*(n: float): SexpNode = +proc newSFloat*(n: float): SexpNode {.procvar.} = ## Creates a new `SFloat SexpNode`. new(result) result.kind = SFloat result.fnum = n -proc newSNil*(): SexpNode = +proc newSNil*(): SexpNode {.procvar.} = ## Creates a new `SNil SexpNode`. new(result) -proc newSCons*(car, cdr: SexpNode): SexpNode = +proc newSCons*(car, cdr: SexpNode): SexpNode {.procvar.} = ## Creates a new `SCons SexpNode` new(result) result.kind = SCons result.car = car result.cdr = cdr -proc newSList*(): SexpNode = +proc newSList*(): SexpNode {.procvar.} = ## Creates a new `SList SexpNode` new(result) result.kind = SList result.elems = @[] -proc newSSymbol*(s: string): SexpNode = +proc newSSymbol*(s: string): SexpNode {.procvar.} = new(result) result.kind = SSymbol result.symbol = s @@ -387,25 +387,25 @@ proc getCons*(n: SexpNode, defaults: Cons = (newSNil(), newSNil())): Cons = elif n.kind == SList: return (n.elems[0], n.elems[1]) else: return defaults -proc `sexp`*(s: string): SexpNode = +proc sexp*(s: string): SexpNode = ## Generic constructor for SEXP data. Creates a new `SString SexpNode`. new(result) result.kind = SString result.str = s -proc `sexp`*(n: BiggestInt): SexpNode = +proc sexp*(n: BiggestInt): SexpNode = ## Generic constructor for SEXP data. Creates a new `SInt SexpNode`. new(result) result.kind = SInt result.num = n -proc `sexp`*(n: float): SexpNode = +proc sexp*(n: float): SexpNode = ## Generic constructor for SEXP data. Creates a new `SFloat SexpNode`. new(result) result.kind = SFloat result.fnum = n -proc `sexp`*(b: bool): SexpNode = +proc sexp*(b: bool): SexpNode = ## Generic constructor for SEXP data. Creates a new `SSymbol ## SexpNode` with value t or `SNil SexpNode`. new(result) @@ -415,7 +415,7 @@ proc `sexp`*(b: bool): SexpNode = else: result.kind = SNil -proc `sexp`*(elements: openArray[SexpNode]): SexpNode = +proc sexp*(elements: openArray[SexpNode]): SexpNode = ## Generic constructor for SEXP data. Creates a new `SList SexpNode` new(result) result.kind = SList From 9c19ce0698fe8bf5baad5cebf78776c161dceb8e Mon Sep 17 00:00:00 2001 From: Wim Lewis Date: Fri, 10 Apr 2015 15:51:39 -0700 Subject: [PATCH 0157/1263] Add a handshake parameter to wrapSocket() to allow it to work on an already-connected socket. --- lib/pure/asyncnet.nim | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/lib/pure/asyncnet.nim b/lib/pure/asyncnet.nim index 39d05d36b..1b11aaffc 100644 --- a/lib/pure/asyncnet.nim +++ b/lib/pure/asyncnet.nim @@ -87,6 +87,12 @@ type of false: nil AsyncSocket* = ref AsyncSocketDesc +when defined(ssl): + type HandshakeType* = enum + handshakeNone, + handshakeAsClient, + handshakeAsServer + {.deprecated: [PAsyncSocket: AsyncSocket].} # TODO: Save AF, domain etc info and reuse it in procs which need it like connect. @@ -418,7 +424,7 @@ proc close*(socket: AsyncSocket) = socket.closed = true # TODO: Add extra debugging checks for this. when defined(ssl): - proc wrapSocket*(ctx: SslContext, socket: AsyncSocket) = + proc wrapSocket*(ctx: SslContext, socket: AsyncSocket, handshake: HandshakeType = handshakeNone) = ## Wraps a socket in an SSL context. This function effectively turns ## ``socket`` into an SSL socket. ## @@ -434,6 +440,14 @@ when defined(ssl): socket.bioOut = bioNew(bio_s_mem()) sslSetBio(socket.sslHandle, socket.bioIn, socket.bioOut) + case handshake + of handshakeNone: + discard + of handshakeAsClient: + sslSetConnectState(socket.sslHandle) + of handshakeAsServer: + sslSetAcceptState(socket.sslHandle) + proc getSockOpt*(socket: AsyncSocket, opt: SOBool, level = SOL_SOCKET): bool {. tags: [ReadIOEffect].} = ## Retrieves option ``opt`` as a boolean value. From 4f88238761e91192aab9da734c132268a4608284 Mon Sep 17 00:00:00 2001 From: Nycto Date: Fri, 24 Apr 2015 08:18:24 -0700 Subject: [PATCH 0158/1263] Fix floats in tuples in HashSets Previously, the added tests would fail to compile with errors complaining that 'hash(float)' didn't exist --- lib/pure/hashes.nim | 66 +++++++++++++++++++++---------------- tests/collections/tsets.nim | 48 +++++++++++++++++++-------- 2 files changed, 71 insertions(+), 43 deletions(-) diff --git a/lib/pure/hashes.nim b/lib/pure/hashes.nim index a16342d44..2ce8ac796 100644 --- a/lib/pure/hashes.nim +++ b/lib/pure/hashes.nim @@ -37,29 +37,29 @@ ## h = h !& hash(x.bar) ## result = !$h -import +import strutils -type - THash* = int ## a hash value; hash tables using these values should +type + THash* = int ## a hash value; hash tables using these values should ## always have a size of a power of two and can use the ``and`` ## operator instead of ``mod`` for truncation of the hash value. -proc `!&`*(h: THash, val: int): THash {.inline.} = +proc `!&`*(h: THash, val: int): THash {.inline.} = ## mixes a hash value `h` with `val` to produce a new hash value. This is ## only needed if you need to implement a hash proc for a new datatype. result = h +% val result = result +% result shl 10 result = result xor (result shr 6) -proc `!$`*(h: THash): THash {.inline.} = +proc `!$`*(h: THash): THash {.inline.} = ## finishes the computation of the hash value. This is ## only needed if you need to implement a hash proc for a new datatype. result = h +% h shl 3 result = result xor (result shr 11) result = result +% result shl 15 -proc hashData*(data: pointer, size: int): THash = +proc hashData*(data: pointer, size: int): THash = ## hashes an array of bytes of size `size` var h: THash = 0 when defined(js): @@ -69,7 +69,7 @@ proc hashData*(data: pointer, size: int): THash = var p = cast[cstring](data) var i = 0 var s = size - while s > 0: + while s > 0: h = h !& ord(p[i]) inc(i) dec(s) @@ -78,7 +78,7 @@ proc hashData*(data: pointer, size: int): THash = when defined(js): var objectID = 0 -proc hash*(x: pointer): THash {.inline.} = +proc hash*(x: pointer): THash {.inline.} = ## efficient hashing of pointers when defined(js): asm """ @@ -93,7 +93,7 @@ proc hash*(x: pointer): THash {.inline.} = """ else: result = (cast[THash](x)) shr 3 # skip the alignment - + when not defined(booting): proc hash*[T: proc](x: T): THash {.inline.} = ## efficient hashing of proc vars; closures are supported too. @@ -101,58 +101,65 @@ when not defined(booting): result = hash(rawProc(x)) !& hash(rawEnv(x)) else: result = hash(pointer(x)) - -proc hash*(x: int): THash {.inline.} = + +proc hash*(x: int): THash {.inline.} = ## efficient hashing of integers result = x -proc hash*(x: int64): THash {.inline.} = +proc hash*(x: int64): THash {.inline.} = ## efficient hashing of integers result = toU32(x) -proc hash*(x: char): THash {.inline.} = +proc hash*(x: char): THash {.inline.} = ## efficient hashing of characters result = ord(x) -proc hash*(x: string): THash = +proc hash*(x: string): THash = ## efficient hashing of strings var h: THash = 0 - for i in 0..x.len-1: + for i in 0..x.len-1: h = h !& ord(x[i]) result = !$h - -proc hashIgnoreStyle*(x: string): THash = + +proc hashIgnoreStyle*(x: string): THash = ## efficient hashing of strings; style is ignored var h: THash = 0 - for i in 0..x.len-1: + for i in 0..x.len-1: var c = x[i] - if c == '_': + if c == '_': continue # skip _ - if c in {'A'..'Z'}: + if c in {'A'..'Z'}: c = chr(ord(c) + (ord('a') - ord('A'))) # toLower() h = h !& ord(c) result = !$h -proc hashIgnoreCase*(x: string): THash = +proc hashIgnoreCase*(x: string): THash = ## efficient hashing of strings; case is ignored var h: THash = 0 - for i in 0..x.len-1: + for i in 0..x.len-1: var c = x[i] - if c in {'A'..'Z'}: + if c in {'A'..'Z'}: c = chr(ord(c) + (ord('a') - ord('A'))) # toLower() h = h !& ord(c) result = !$h - -proc hash*[T: tuple](x: T): THash = - ## efficient hashing of tuples. - for f in fields(x): - result = result !& hash(f) - result = !$result proc hash*(x: float): THash {.inline.} = var y = x + 1.0 result = cast[ptr THash](addr(y))[] + +# Forward declarations before methods that hash containers. This allows +# containers to contain other containers +proc hash*[A](x: openArray[A]): THash +proc hash*[A](x: set[A]): THash + + +proc hash*[T: tuple](x: T): THash = + ## efficient hashing of tuples. + for f in fields(x): + result = result !& hash(f) + result = !$result + proc hash*[A](x: openArray[A]): THash = for it in items(x): result = result !& hash(it) result = !$result @@ -160,3 +167,4 @@ proc hash*[A](x: openArray[A]): THash = proc hash*[A](x: set[A]): THash = for it in items(x): result = result !& hash(it) result = !$result + diff --git a/tests/collections/tsets.nim b/tests/collections/tsets.nim index 656c5b3f2..a5bbe8dbd 100644 --- a/tests/collections/tsets.nim +++ b/tests/collections/tsets.nim @@ -1,17 +1,37 @@ -discard """ - output: '''true -true''' -""" - import sets -var - a = initSet[int]() - b = initSet[int]() - c = initSet[string]() -for i in 0..5: a.incl(i) -for i in 1..6: b.incl(i) -for i in 0..5: c.incl($i) +block setEquality: + var + a = initSet[int]() + b = initSet[int]() + c = initSet[string]() + + for i in 0..5: a.incl(i) + for i in 1..6: b.incl(i) + for i in 0..5: c.incl($i) + + doAssert map(a, proc(x: int): int = x + 1) == b + doAssert map(a, proc(x: int): string = $x) == c + + +block setsContainingTuples: + var set = initSet[tuple[i: int, i64: int64, f: float]]() + set.incl( (i: 123, i64: 123'i64, f: 3.14) ) + doAssert set.contains( (i: 123, i64: 123'i64, f: 3.14) ) + doAssert( not set.contains( (i: 456, i64: 789'i64, f: 2.78) ) ) + + +block setWithTuplesWithSeqs: + var s = initSet[tuple[s: seq[int]]]() + s.incl( (s: @[1, 2, 3]) ) + doAssert s.contains( (s: @[1, 2, 3]) ) + doAssert( not s.contains((s: @[4, 5, 6])) ) + + +block setWithSequences: + var s = initSet[seq[int]]() + s.incl( @[1, 2, 3] ) + doAssert s.contains(@[1, 2, 3]) + doAssert( not s.contains(@[4, 5, 6]) ) + -echo map(a, proc(x: int): int = x + 1) == b -echo map(a, proc(x: int): string = $x) == c From 147037bd1eddc447341b079020080e61f5ba3385 Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Sun, 26 Apr 2015 08:36:54 +0500 Subject: [PATCH 0159/1263] added id for sexp --- lib/pure/sexp.nim | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lib/pure/sexp.nim b/lib/pure/sexp.nim index b5e67b90f..3c9fbc150 100644 --- a/lib/pure/sexp.nim +++ b/lib/pure/sexp.nim @@ -422,6 +422,9 @@ proc sexp*(elements: openArray[SexpNode]): SexpNode = newSeq(result.elems, elements.len) for i, p in pairs(elements): result.elems[i] = p +proc sexp*(s: SexpNode): SexpNode = + result = s + proc toSexp(x: NimNode): NimNode {.compiletime.} = case x.kind of nnkBracket: From 58570a4a3086852acbd6ee059c9e3427f504b2ab Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Sun, 26 Apr 2015 08:37:55 +0500 Subject: [PATCH 0160/1263] epc request/response barebones --- compiler/nimsuggest/nimsuggest.nim | 29 +++++++++++++++++++---------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/compiler/nimsuggest/nimsuggest.nim b/compiler/nimsuggest/nimsuggest.nim index d6bd01ce7..886590e35 100644 --- a/compiler/nimsuggest/nimsuggest.nim +++ b/compiler/nimsuggest/nimsuggest.nim @@ -80,9 +80,20 @@ proc sexp(s: seq[Suggest]): SexpNode = proc listEPC(): SexpNode = discard -proc executeEPC(body: SexpNode) = +proc executeEPC(section: Section, args: SexpNode) = + let + file = args[0].getStr + line = args[1].getNum + column = args[2].getNum + dirtyfile = args[3].getStr(nil) discard +proc returnEPC(socket: var Socket, uid: string, s: SexpNode) = + let response = $convertSexp([newSSymbol("return"), [uid, s]]) + socket.send(toHex(len(response), 6)) + socket.send(response) + socket.close() + proc action(cmd: string) = template toggle(sw) = if sw in gGlobalOptions: @@ -194,11 +205,12 @@ proc serve() = let body = message[1] case messageType: of "call": - executeEPC(body) - let response = $sexp(results) - client.send(toHex(len(response), 6)) - client.send(response) - client.close() + let + uid = body[0].getStr + section = parseEnum[Section](body[1].getStr) + args = body[2] + executeEPC(section, args) + returnEPC(client, uid, sexp(results)) of "return": raise newException(ValueError, "no return expected") of "return-error": @@ -207,10 +219,7 @@ proc serve() = stderr.writeln("recieved epc error: " & $messageBuffer) raise newException(ValueError, "epc error") of "methods": - let response = $listEPC() - client.send(toHex(len(response), 6)) - client.send(response) - client.close() + returnEPC(client, body[0].getStr, listEPC()) else: raise newException(ValueError, "unexpected call: " & messageType) From b9bbfb4cdfe081b0d0de52b28e1fef4d81fa5db3 Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Sun, 26 Apr 2015 08:41:23 +0500 Subject: [PATCH 0161/1263] always raise ValueException --- compiler/nimsuggest/nimsuggest.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/nimsuggest/nimsuggest.nim b/compiler/nimsuggest/nimsuggest.nim index 886590e35..97bbf6ea3 100644 --- a/compiler/nimsuggest/nimsuggest.nim +++ b/compiler/nimsuggest/nimsuggest.nim @@ -196,7 +196,7 @@ proc serve() = raise newException(ValueError, "didn't get all the hexbytes") var size = 0 if parseHex(sizeHex, size) == 0: - raiseRecoverableError("invalid size hex: " & $sizeHex) + raise newException(ValueError, "invalid size hex: " & $sizeHex) var messageBuffer = "" if client.recv(messageBuffer, size, 3000) != size: raise newException(ValueError, "didn't get all the bytes") From 6836d453988b2ad25783a3a9d64b0cc32cca5b0a Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Sun, 26 Apr 2015 08:42:28 +0500 Subject: [PATCH 0162/1263] findEPCPort defined, but not implemented --- compiler/nimsuggest/nimsuggest.nim | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/compiler/nimsuggest/nimsuggest.nim b/compiler/nimsuggest/nimsuggest.nim index 97bbf6ea3..6cc3bd49a 100644 --- a/compiler/nimsuggest/nimsuggest.nim +++ b/compiler/nimsuggest/nimsuggest.nim @@ -94,6 +94,9 @@ proc returnEPC(socket: var Socket, uid: string, s: SexpNode) = socket.send(response) socket.close() +proc findEPCPort(): int = + 98294 # guaranteed to be random + proc action(cmd: string) = template toggle(sw) = if sw in gGlobalOptions: @@ -178,7 +181,8 @@ proc serve() = stdoutSocket.send("\c\L") stdoutSocket.close() of mepc: - let port = 98294 # guaranteed to be random + let port = findEPCPort() + echo(port) var server = newSocket() server.bindaddr(port.Port, "localhost") var inp = "".TaintedString From 33edba665d45d148216d4a056d0588952e4547fc Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Sun, 26 Apr 2015 08:54:46 +0500 Subject: [PATCH 0163/1263] removed a few consts and rewired to IdeCmd --- compiler/options.nim | 19 +++++++++++++++++-- compiler/suggest.nim | 27 +++++++++++---------------- 2 files changed, 28 insertions(+), 18 deletions(-) diff --git a/compiler/options.nim b/compiler/options.nim index 65250f519..709959cc4 100644 --- a/compiler/options.nim +++ b/compiler/options.nim @@ -83,11 +83,11 @@ type # please make sure we have under 32 options TGCMode* = enum # the selected GC gcNone, gcBoehm, gcMarkAndSweep, gcRefc, gcV2, gcGenerational - TIdeCmd* = enum + IdeCmd* = enum ideNone, ideSug, ideCon, ideDef, ideUse var - gIdeCmd*: TIdeCmd + gIdeCmd*: IdeCmd const ChecksOptions* = {optObjCheck, optFieldCheck, optRangeCheck, optNilCheck, @@ -395,3 +395,18 @@ template cnimdbg*: expr = p.module.module.fileIdx == gProjectMainIdx template pnimdbg*: expr = p.lex.fileIdx == gProjectMainIdx template lnimdbg*: expr = L.fileIdx == gProjectMainIdx +proc parseIdeCmd*(s: string): IdeCmd = + case s: + of "sug": ideSug + of "con": ideCon + of "def": ideDef + of "use": ideUse + else: ideNone + +proc `$`*(c: IdeCmd): string = + case c: + of ideSug: "sug" + of ideCon: "con" + of ideDef: "def" + of ideUse: "use" + of ideNone: "none" diff --git a/compiler/suggest.nim b/compiler/suggest.nim index 539d4bc5d..f1628db94 100644 --- a/compiler/suggest.nim +++ b/compiler/suggest.nim @@ -16,15 +16,10 @@ import algorithm, sequtils, strutils, ast, msgs, options, renderer, const sep = '\t' - sectionSuggest = "sug" - sectionDef = "def" - sectionContext = "con" - sectionUsage = "use" type - Section* = enum sug, def, con, use Suggest* = object - section*: Section + section*: IdeCmd qualifiedPath*: seq[string] filePath*: string line*: int # Starts at 1 @@ -41,7 +36,7 @@ var template origModuleName(m: PSym): string = m.name.s proc symToSuggest(s: PSym, isLocal: bool, section: string, li: TLineInfo): Suggest = - result.section = parseEnum[Section](section) + result.section = parseIdeCmd(section) if optIdeTerse in gGlobalOptions: if s.kind in routineKinds: result.symkind = parseEnum[TSymKind](renderTree(s.ast, {renderNoBody, renderNoComments, @@ -116,7 +111,7 @@ proc fieldVisible*(c: PContext, f: PSym): bool {.inline.} = proc suggestField(c: PContext, s: PSym, outputs: var int) = if filterSym(s) and fieldVisible(c, s): - suggestResult(symToSuggest(s, isLocal=true, sectionSuggest)) + suggestResult(symToSuggest(s, isLocal=true, $ideSug)) inc outputs template wholeSymTab(cond, section: expr) {.immediate.} = @@ -172,7 +167,7 @@ proc argsFit(c: PContext, candidate: PSym, n, nOrig: PNode): bool = proc suggestCall(c: PContext, n, nOrig: PNode, outputs: var int) = wholeSymTab(filterSym(it) and nameFits(c, it, n) and argsFit(c, it, n, nOrig), - sectionContext) + $ideCon) proc typeFits(c: PContext, s: PSym, firstArg: PType): bool {.inline.} = if s.typ != nil and sonsLen(s.typ) > 1 and s.typ.sons[1] != nil: @@ -189,7 +184,7 @@ proc typeFits(c: PContext, s: PSym, firstArg: PType): bool {.inline.} = proc suggestOperations(c: PContext, n: PNode, typ: PType, outputs: var int) = assert typ != nil - wholeSymTab(filterSymNoOpr(it) and typeFits(c, it, typ), sectionSuggest) + wholeSymTab(filterSymNoOpr(it) and typeFits(c, it, typ), $ideSug) proc suggestEverything(c: PContext, n: PNode, outputs: var int) = # do not produce too many symbols: @@ -198,7 +193,7 @@ proc suggestEverything(c: PContext, n: PNode, outputs: var int) = if scope == c.topLevelScope: isLocal = false for it in items(scope.symbols): if filterSym(it): - suggestResult(symToSuggest(it, isLocal = isLocal, sectionSuggest)) + suggestResult(symToSuggest(it, isLocal = isLocal, $ideSug)) inc outputs if scope == c.topLevelScope: break @@ -213,12 +208,12 @@ proc suggestFieldAccess(c: PContext, n: PNode, outputs: var int) = # all symbols accessible, because we are in the current module: for it in items(c.topLevelScope.symbols): if filterSym(it): - suggestResult(symToSuggest(it, isLocal=false, sectionSuggest)) + suggestResult(symToSuggest(it, isLocal=false, $ideSug)) inc outputs else: for it in items(n.sym.tab): if filterSym(it): - suggestResult(symToSuggest(it, isLocal=false, sectionSuggest)) + suggestResult(symToSuggest(it, isLocal=false, $ideSug)) inc outputs else: # fallback: @@ -295,16 +290,16 @@ var proc findUsages(info: TLineInfo; s: PSym) = if usageSym == nil and isTracked(info, s.name.s.len): usageSym = s - suggestResult(symToSuggest(s, isLocal=false, sectionUsage)) + suggestResult(symToSuggest(s, isLocal=false, $ideUse)) elif s == usageSym: if lastLineInfo != info: - suggestResult(symToSuggest(s, isLocal=false, sectionUsage, info)) + suggestResult(symToSuggest(s, isLocal=false, $ideUse, info)) lastLineInfo = info proc findDefinition(info: TLineInfo; s: PSym) = if s.isNil: return if isTracked(info, s.name.s.len): - suggestResult(symToSuggest(s, isLocal=false, sectionDef)) + suggestResult(symToSuggest(s, isLocal=false, $ideDef)) suggestQuit() proc ensureIdx[T](x: var T, y: int) = From bf4a92784e7c90018c6e8fbec3019df2a5dd5c23 Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Sun, 26 Apr 2015 08:56:22 +0500 Subject: [PATCH 0164/1263] final Section -> IdeCmd --- compiler/nimsuggest/nimsuggest.nim | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/compiler/nimsuggest/nimsuggest.nim b/compiler/nimsuggest/nimsuggest.nim index 6cc3bd49a..73325fa48 100644 --- a/compiler/nimsuggest/nimsuggest.nim +++ b/compiler/nimsuggest/nimsuggest.nim @@ -58,7 +58,7 @@ proc parseQuoted(cmd: string; outp: var string; start: int): int = let order: SexpNode = sexp(@["section", "symkind", "qualifiedPath", "filePath", "forth", "line", "column", "doc"].map(newSSymbol)) -proc sexp(s: Section): SexpNode = sexp($s) +proc sexp(s: IdeCmd): SexpNode = sexp($s) proc sexp(s: TSymKind): SexpNode = sexp($s) @@ -80,7 +80,7 @@ proc sexp(s: seq[Suggest]): SexpNode = proc listEPC(): SexpNode = discard -proc executeEPC(section: Section, args: SexpNode) = +proc executeEPC(cmd: IdeCmd, args: SexpNode) = let file = args[0].getStr line = args[1].getNum @@ -211,9 +211,9 @@ proc serve() = of "call": let uid = body[0].getStr - section = parseEnum[Section](body[1].getStr) + cmd = parseIdeCmd(body[1].getStr) args = body[2] - executeEPC(section, args) + executeEPC(cmd, args) returnEPC(client, uid, sexp(results)) of "return": raise newException(ValueError, "no return expected") From 7b7188a8ade72379d9d04c5ad3fdfd0aa0e11337 Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Sun, 26 Apr 2015 09:20:55 +0500 Subject: [PATCH 0165/1263] proc execute / return-error handling --- compiler/nimsuggest/nimsuggest.nim | 108 ++++++++++++++++------------- 1 file changed, 59 insertions(+), 49 deletions(-) diff --git a/compiler/nimsuggest/nimsuggest.nim b/compiler/nimsuggest/nimsuggest.nim index 73325fa48..2f95ceaae 100644 --- a/compiler/nimsuggest/nimsuggest.nim +++ b/compiler/nimsuggest/nimsuggest.nim @@ -45,6 +45,9 @@ const "type 'debug' to toggle debug mode on/off\n" & "type 'terse' to toggle terse mode on/off" +type + EUnexpectedCommand = object of Exception + proc parseQuoted(cmd: string; outp: var string; start: int): int = var i = start i += skipWhitespace(cmd, i) @@ -80,16 +83,38 @@ proc sexp(s: seq[Suggest]): SexpNode = proc listEPC(): SexpNode = discard +proc execute(cmd: IdeCmd, file, dirtyfile: string, line, col: int) = + gIdeCmd = cmd + if cmd == ideUse: + modules.resetAllModules() + var isKnownFile = true + let dirtyIdx = file.fileInfoIdx(isKnownFile) + + if dirtyfile.len != 0: msgs.setDirtyFile(dirtyIdx, dirtyfile) + else: msgs.setDirtyFile(dirtyIdx, nil) + + resetModule dirtyIdx + if dirtyIdx != gProjectMainIdx: + resetModule gProjectMainIdx + + gTrackPos = newLineInfo(dirtyIdx, line, col) + #echo dirtyfile, gDirtyBufferIdx, " project ", gProjectMainIdx + gErrorCounter = 0 + if not isKnownFile: + compileProject(dirtyIdx) + else: + compileProject() + proc executeEPC(cmd: IdeCmd, args: SexpNode) = let file = args[0].getStr line = args[1].getNum column = args[2].getNum dirtyfile = args[3].getStr(nil) - discard + execute(cmd, file, dirtyfile, int(line), int(column)) -proc returnEPC(socket: var Socket, uid: string, s: SexpNode) = - let response = $convertSexp([newSSymbol("return"), [uid, s]]) +proc returnEPC(socket: var Socket, uid: string, s: SexpNode, return_symbol = "return") = + let response = $convertSexp([newSSymbol(return_symbol), [uid, s]]) socket.send(toHex(len(response), 6)) socket.send(response) socket.close() @@ -97,7 +122,7 @@ proc returnEPC(socket: var Socket, uid: string, s: SexpNode) = proc findEPCPort(): int = 98294 # guaranteed to be random -proc action(cmd: string) = +proc parseCmdLine(cmd: string) = template toggle(sw) = if sw in gGlobalOptions: excl(gGlobalOptions, sw) @@ -115,9 +140,7 @@ proc action(cmd: string) = of "sug": gIdeCmd = ideSug of "con": gIdeCmd = ideCon of "def": gIdeCmd = ideDef - of "use": - modules.resetAllModules() - gIdeCmd = ideUse + of "use": gIdeCmd = ideUse of "quit": quit() of "debug": toggle optIdeDebug of "terse": toggle optIdeTerse @@ -133,23 +156,7 @@ proc action(cmd: string) = i += skipWhile(cmd, seps, i) i += parseInt(cmd, col, i) - var isKnownFile = true - if orig.len == 0: err() - let dirtyIdx = orig.fileInfoIdx(isKnownFile) - - if dirtyfile.len != 0: msgs.setDirtyFile(dirtyIdx, dirtyfile) - else: msgs.setDirtyFile(dirtyIdx, nil) - - resetModule dirtyIdx - if dirtyIdx != gProjectMainIdx: - resetModule gProjectMainIdx - gTrackPos = newLineInfo(dirtyIdx, line, col) - #echo dirtyfile, gDirtyBufferIdx, " project ", gProjectMainIdx - gErrorCounter = 0 - if not isKnownFile: - compileProject(dirtyIdx) - else: - compileProject() + execute(gIdeCmd, orig, dirtyfile, line, col) proc serve() = # do not stop after the first error: @@ -159,7 +166,7 @@ proc serve() = echo Help var line = "" while readLineFromStdin("> ", line): - action line + parseCmdLine line echo "" flushFile(stdout) of mtcp: @@ -176,7 +183,7 @@ proc serve() = accept(server, stdoutSocket) stdoutSocket.readLine(inp) - action inp.string + parseCmdLine inp.string stdoutSocket.send("\c\L") stdoutSocket.close() @@ -189,11 +196,7 @@ proc serve() = server.listen() echo(port) while true: - var results: seq[Suggest] = @[] var client = newSocket() - suggest.suggestionResultHook = proc (s: Suggest) = - results.add(s) - accept(server, client) var sizeHex = "" if client.recv(sizeHex, 6, 1000) != 6: @@ -207,25 +210,32 @@ proc serve() = let message = parseSexp($messageBuffer) let messageType = message[0].getSymbol let body = message[1] - case messageType: - of "call": - let - uid = body[0].getStr - cmd = parseIdeCmd(body[1].getStr) - args = body[2] - executeEPC(cmd, args) - returnEPC(client, uid, sexp(results)) - of "return": - raise newException(ValueError, "no return expected") - of "return-error": - raise newException(ValueError, "no return expected") - of "epc-error": - stderr.writeln("recieved epc error: " & $messageBuffer) - raise newException(ValueError, "epc error") - of "methods": - returnEPC(client, body[0].getStr, listEPC()) - else: - raise newException(ValueError, "unexpected call: " & messageType) + try: + case messageType: + of "call": + var results: seq[Suggest] = @[] + suggest.suggestionResultHook = proc (s: Suggest) = + results.add(s) + + let + uid = body[0].getStr + cmd = parseIdeCmd(body[1].getStr) + args = body[2] + executeEPC(cmd, args) + returnEPC(client, uid, sexp(results)) + of "return": + raise newException(EUnexpectedCommand, "no return expected") + of "return-error": + raise newException(EUnexpectedCommand, "no return expected") + of "epc-error": + stderr.writeln("recieved epc error: " & $messageBuffer) + raise newException(IOError, "epc error") + of "methods": + returnEPC(client, body[0].getStr, listEPC()) + else: + raise newException(EUnexpectedCommand, "unexpected call: " & messageType) + except: + returnEPC(client, body[0].getStr, sexp(getCurrentExceptionMsg()), "return-error") proc mainCommand = registerPass verbosePass From 53bc541666565ebb6103afea618b0e680a464dd0 Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Sun, 26 Apr 2015 09:44:22 +0500 Subject: [PATCH 0166/1263] rough guess how methods should look like --- compiler/nimsuggest/nimsuggest.nim | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/compiler/nimsuggest/nimsuggest.nim b/compiler/nimsuggest/nimsuggest.nim index 2f95ceaae..9f672d49b 100644 --- a/compiler/nimsuggest/nimsuggest.nim +++ b/compiler/nimsuggest/nimsuggest.nim @@ -81,7 +81,18 @@ proc sexp(s: seq[Suggest]): SexpNode = result = sexp(s) proc listEPC(): SexpNode = - discard + let + argspecs = sexp("file line column dirtyfile".split(" ").map(newSSymbol)) + docstring = sexp("line starts at 1, column at 0, dirtyfile is optional") + result = newSList() + for command in ["sug", "con", "def", "use"]: + let + cmd = sexp(command) + methodDesc = newSList() + methodDesc.add(cmd) + methodDesc.add(argspecs) + methodDesc.add(docstring) + result.add(methodDesc) proc execute(cmd: IdeCmd, file, dirtyfile: string, line, col: int) = gIdeCmd = cmd From df1cdced1d9ec5663c735065a21dc5b00067b8b2 Mon Sep 17 00:00:00 2001 From: Wim Lewis Date: Sun, 26 Apr 2015 22:10:35 -0700 Subject: [PATCH 0167/1263] Make the post-connection wrapSocket() call available in both the synchronous and asynchrinous net modules. --- lib/pure/asyncnet.nim | 13 ++++--------- lib/pure/net.nim | 29 ++++++++++++++++++++++++++++- 2 files changed, 32 insertions(+), 10 deletions(-) diff --git a/lib/pure/asyncnet.nim b/lib/pure/asyncnet.nim index 1b11aaffc..c328649e5 100644 --- a/lib/pure/asyncnet.nim +++ b/lib/pure/asyncnet.nim @@ -87,12 +87,6 @@ type of false: nil AsyncSocket* = ref AsyncSocketDesc -when defined(ssl): - type HandshakeType* = enum - handshakeNone, - handshakeAsClient, - handshakeAsServer - {.deprecated: [PAsyncSocket: AsyncSocket].} # TODO: Save AF, domain etc info and reuse it in procs which need it like connect. @@ -424,7 +418,7 @@ proc close*(socket: AsyncSocket) = socket.closed = true # TODO: Add extra debugging checks for this. when defined(ssl): - proc wrapSocket*(ctx: SslContext, socket: AsyncSocket, handshake: HandshakeType = handshakeNone) = + proc wrapSocket*(ctx: SslContext, socket: AsyncSocket) = ## Wraps a socket in an SSL context. This function effectively turns ## ``socket`` into an SSL socket. ## @@ -440,9 +434,10 @@ when defined(ssl): socket.bioOut = bioNew(bio_s_mem()) sslSetBio(socket.sslHandle, socket.bioIn, socket.bioOut) + proc wrapSocket*(ctx: SslContext, socket: AsyncSocket, handshake: SslHandshakeType) = + wrapSocket(ctx, socket) + case handshake - of handshakeNone: - discard of handshakeAsClient: sslSetConnectState(socket.sslHandle) of handshakeAsServer: diff --git a/lib/pure/net.nim b/lib/pure/net.nim index ffbc6e320..a21485655 100644 --- a/lib/pure/net.nim +++ b/lib/pure/net.nim @@ -35,6 +35,9 @@ when defined(ssl): SslAcceptResult* = enum AcceptNoClient = 0, AcceptNoHandshake, AcceptSuccess + SslHandshakeType* = enum + handshakeAsClient, handshakeAsServer + {.deprecated: [ESSL: SSLError, TSSLCVerifyMode: SSLCVerifyMode, TSSLProtVersion: SSLProtVersion, PSSLContext: SSLContext, TSSLAcceptResult: SSLAcceptResult].} @@ -97,6 +100,8 @@ type proc isIpAddress*(address_str: string): bool {.tags: [].} proc parseIpAddress*(address_str: string): TIpAddress +proc socketError*(socket: Socket, err: int = -1, async = false, +lastError = (-1).OSErrorCode): void proc isDisconnectionError*(flags: set[SocketFlag], lastError: OSErrorCode): bool = @@ -235,9 +240,13 @@ when defined(ssl): ## Wraps a socket in an SSL context. This function effectively turns ## ``socket`` into an SSL socket. ## + ## This must be called on an unconnected socket; an SSL session will + ## be started when the socket is connected. + ## ## **Disclaimer**: This code is not well tested, may be very unsafe and ## prone to security vulnerabilities. - + + assert (not socket.isSSL) socket.isSSL = true socket.sslContext = ctx socket.sslHandle = SSLNew(SSLCTX(socket.sslContext)) @@ -249,6 +258,24 @@ when defined(ssl): if SSLSetFd(socket.sslHandle, socket.fd) != 1: raiseSSLError() + proc wrapSocket*(ctx: SSLContext, socket: Socket, handshake: SslHandshakeType) = + ## Wraps a socket in an SSL context. This function effectively turns + ## ``socket`` into an SSL socket. + ## + ## This should be called on a connected socket, and will perform + ## an SSL handshake immediately. + ## + ## **Disclaimer**: This code is not well tested, may be very unsafe and + ## prone to security vulnerabilities. + wrapSocket(ctx, socket) + case handshake + of handshakeAsClient: + let ret = SSLConnect(socket.sslHandle) + socketError(socket, ret) + of handshakeAsServer: + let ret = SSLAccept(socket.sslHandle) + socketError(socket, ret) + proc getSocketError*(socket: Socket): OSErrorCode = ## Checks ``osLastError`` for a valid error. If it has been reset it uses ## the last error stored in the socket object. From 00fafd1dbe72e3f6c50f981d286e0c753207bc99 Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Mon, 27 Apr 2015 10:25:45 +0500 Subject: [PATCH 0168/1263] Fixed a few socket things --- compiler/nimsuggest/nimsuggest.nim | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/compiler/nimsuggest/nimsuggest.nim b/compiler/nimsuggest/nimsuggest.nim index 9f672d49b..4e4925fb8 100644 --- a/compiler/nimsuggest/nimsuggest.nim +++ b/compiler/nimsuggest/nimsuggest.nim @@ -9,7 +9,7 @@ ## Nimsuggest is a tool that helps to give editors IDE like capabilities. -import strutils, os, parseopt, parseutils, sequtils +import strutils, os, parseopt, parseutils, sequtils, net import options, commands, modules, sem, passes, passaux, msgs, nimconf, extccomp, condsyms, lists, net, rdstdin, sexp, suggest, ast @@ -131,7 +131,7 @@ proc returnEPC(socket: var Socket, uid: string, s: SexpNode, return_symbol = "re socket.close() proc findEPCPort(): int = - 98294 # guaranteed to be random + 55822 # guaranteed to be random proc parseCmdLine(cmd: string) = template toggle(sw) = @@ -200,9 +200,8 @@ proc serve() = stdoutSocket.close() of mepc: let port = findEPCPort() - echo(port) var server = newSocket() - server.bindaddr(port.Port, "localhost") + server.bindaddr(Port(port), "localhost") var inp = "".TaintedString server.listen() echo(port) From 39378823ae5c0df8d2baa4e1ee07b71786736bef Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Mon, 27 Apr 2015 20:06:17 +0500 Subject: [PATCH 0169/1263] epc waits on recv, not on accept --- compiler/nimsuggest/nimsuggest.nim | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/compiler/nimsuggest/nimsuggest.nim b/compiler/nimsuggest/nimsuggest.nim index 4e4925fb8..7e0d3a399 100644 --- a/compiler/nimsuggest/nimsuggest.nim +++ b/compiler/nimsuggest/nimsuggest.nim @@ -205,17 +205,18 @@ proc serve() = var inp = "".TaintedString server.listen() echo(port) + var client = newSocket() + # Wait for connection + accept(server, client) while true: - var client = newSocket() - accept(server, client) var sizeHex = "" - if client.recv(sizeHex, 6, 1000) != 6: + if client.recv(sizeHex, 6) != 6: raise newException(ValueError, "didn't get all the hexbytes") var size = 0 if parseHex(sizeHex, size) == 0: raise newException(ValueError, "invalid size hex: " & $sizeHex) var messageBuffer = "" - if client.recv(messageBuffer, size, 3000) != size: + if client.recv(messageBuffer, size) != size: raise newException(ValueError, "didn't get all the bytes") let message = parseSexp($messageBuffer) let messageType = message[0].getSymbol From ab58e844da206949c0aed18e69cd25e9a85c6b2d Mon Sep 17 00:00:00 2001 From: Chris Heller Date: Mon, 27 Apr 2015 21:00:07 -0700 Subject: [PATCH 0170/1263] Change dwSize parameter in VirtualAlloc/Free procs to use SIZE_T instead of DWORD to match MSDN --- lib/windows/windows.nim | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/windows/windows.nim b/lib/windows/windows.nim index b76dea6c5..f53446189 100644 --- a/lib/windows/windows.nim +++ b/lib/windows/windows.nim @@ -18564,10 +18564,10 @@ proc LocalCompact*(uMinFree: WINUINT): WINUINT{.stdcall, dynlib: "kernel32", proc FlushInstructionCache*(hProcess: HANDLE, lpBaseAddress: LPCVOID, dwSize: DWORD): WINBOOL{.stdcall, dynlib: "kernel32", importc: "FlushInstructionCache".} -proc VirtualAlloc*(lpAddress: LPVOID, dwSize: DWORD, flAllocationType: DWORD, +proc VirtualAlloc*(lpAddress: LPVOID, dwSize: SIZE_T, flAllocationType: DWORD, flProtect: DWORD): LPVOID{.stdcall, dynlib: "kernel32", importc: "VirtualAlloc".} -proc VirtualFree*(lpAddress: LPVOID, dwSize: DWORD, dwFreeType: DWORD): WINBOOL{. +proc VirtualFree*(lpAddress: LPVOID, dwSize: SIZE_T, dwFreeType: DWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "VirtualFree".} proc VirtualProtect*(lpAddress: LPVOID, dwSize: DWORD, flNewProtect: DWORD, lpflOldProtect: PDWORD): WINBOOL{.stdcall, From ef887d5d9058dd26f9fa11e7d5e1e02675da5a6b Mon Sep 17 00:00:00 2001 From: Chris Heller Date: Mon, 27 Apr 2015 21:02:48 -0700 Subject: [PATCH 0171/1263] Add procs for VirtualAllocEx and VirtualFreeEx in windows.nim --- lib/windows/windows.nim | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/lib/windows/windows.nim b/lib/windows/windows.nim index f53446189..b1bbd9994 100644 --- a/lib/windows/windows.nim +++ b/lib/windows/windows.nim @@ -18567,8 +18567,14 @@ proc FlushInstructionCache*(hProcess: HANDLE, lpBaseAddress: LPCVOID, proc VirtualAlloc*(lpAddress: LPVOID, dwSize: SIZE_T, flAllocationType: DWORD, flProtect: DWORD): LPVOID{.stdcall, dynlib: "kernel32", importc: "VirtualAlloc".} +proc VirtualAllocEx*(hProcess: HANDLE, lpAddress: LPVOID, dwSize: SIZE_T, + flAllocationType: DWORD, flProtect: DWORD): LPVOID + {.stdcall, dynlib: "kernel32", importc: "VirtualAllocEx".} proc VirtualFree*(lpAddress: LPVOID, dwSize: SIZE_T, dwFreeType: DWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "VirtualFree".} +proc VirtualFreeEx*(hProcess: HANDLE, lpAddress: LPVOID, dwSize: SIZE_T, + dwFreeType: DWORD): WINBOOL + {.stdcall, dynlib: "kernel32", importc: "VirtualFree".} proc VirtualProtect*(lpAddress: LPVOID, dwSize: DWORD, flNewProtect: DWORD, lpflOldProtect: PDWORD): WINBOOL{.stdcall, dynlib: "kernel32", importc: "VirtualProtect".} From c750900286af8d78fe7cf982bbb2b61e413ae068 Mon Sep 17 00:00:00 2001 From: Chris Heller Date: Tue, 28 Apr 2015 09:53:01 -0700 Subject: [PATCH 0172/1263] Update other Virtual* procs that were using dwSize: DWORD to use SIZE_T --- lib/windows/windows.nim | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/windows/windows.nim b/lib/windows/windows.nim index b1bbd9994..00a554e15 100644 --- a/lib/windows/windows.nim +++ b/lib/windows/windows.nim @@ -18575,17 +18575,17 @@ proc VirtualFree*(lpAddress: LPVOID, dwSize: SIZE_T, dwFreeType: DWORD): WINBOOL proc VirtualFreeEx*(hProcess: HANDLE, lpAddress: LPVOID, dwSize: SIZE_T, dwFreeType: DWORD): WINBOOL {.stdcall, dynlib: "kernel32", importc: "VirtualFree".} -proc VirtualProtect*(lpAddress: LPVOID, dwSize: DWORD, flNewProtect: DWORD, +proc VirtualProtect*(lpAddress: LPVOID, dwSize: SIZE_T, flNewProtect: DWORD, lpflOldProtect: PDWORD): WINBOOL{.stdcall, dynlib: "kernel32", importc: "VirtualProtect".} proc VirtualQuery*(lpAddress: LPCVOID, lpBuffer: PMEMORY_BASIC_INFORMATION, dwLength: DWORD): DWORD{.stdcall, dynlib: "kernel32", importc: "VirtualQuery".} -proc VirtualProtectEx*(hProcess: HANDLE, lpAddress: LPVOID, dwSize: DWORD, +proc VirtualProtectEx*(hProcess: HANDLE, lpAddress: LPVOID, dwSize: SIZE_T, flNewProtect: DWORD, lpflOldProtect: PDWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "VirtualProtectEx".} proc VirtualQueryEx*(hProcess: HANDLE, lpAddress: LPCVOID, - lpBuffer: PMEMORY_BASIC_INFORMATION, dwLength: DWORD): DWORD{. + lpBuffer: PMEMORY_BASIC_INFORMATION, dwLength: SIZE_T): DWORD{. stdcall, dynlib: "kernel32", importc: "VirtualQueryEx".} proc HeapCreate*(flOptions: DWORD, dwInitialSize: DWORD, dwMaximumSize: DWORD): HANDLE{. stdcall, dynlib: "kernel32", importc: "HeapCreate".} From ef46f755720eb86b73cbed41e7edc166bd8b5dc0 Mon Sep 17 00:00:00 2001 From: Chris Heller Date: Tue, 28 Apr 2015 10:00:10 -0700 Subject: [PATCH 0173/1263] Update Heap* procs in windows.nim that were using DWORD sizes to use SIZE_T --- lib/windows/windows.nim | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/lib/windows/windows.nim b/lib/windows/windows.nim index 00a554e15..fb4451d39 100644 --- a/lib/windows/windows.nim +++ b/lib/windows/windows.nim @@ -18587,21 +18587,21 @@ proc VirtualProtectEx*(hProcess: HANDLE, lpAddress: LPVOID, dwSize: SIZE_T, proc VirtualQueryEx*(hProcess: HANDLE, lpAddress: LPCVOID, lpBuffer: PMEMORY_BASIC_INFORMATION, dwLength: SIZE_T): DWORD{. stdcall, dynlib: "kernel32", importc: "VirtualQueryEx".} -proc HeapCreate*(flOptions: DWORD, dwInitialSize: DWORD, dwMaximumSize: DWORD): HANDLE{. +proc HeapCreate*(flOptions: DWORD, dwInitialSize: SIZE_T, dwMaximumSize: SIZE_T): HANDLE{. stdcall, dynlib: "kernel32", importc: "HeapCreate".} proc HeapDestroy*(hHeap: HANDLE): WINBOOL{.stdcall, dynlib: "kernel32", importc: "HeapDestroy".} -proc HeapAlloc*(hHeap: HANDLE, dwFlags: DWORD, dwBytes: DWORD): LPVOID{.stdcall, +proc HeapAlloc*(hHeap: HANDLE, dwFlags: DWORD, dwBytes: SIZE_T): LPVOID{.stdcall, dynlib: "kernel32", importc: "HeapAlloc".} -proc HeapReAlloc*(hHeap: HANDLE, dwFlags: DWORD, lpMem: LPVOID, dwBytes: DWORD): LPVOID{. +proc HeapReAlloc*(hHeap: HANDLE, dwFlags: DWORD, lpMem: LPVOID, dwBytes: SIZE_T): LPVOID{. stdcall, dynlib: "kernel32", importc: "HeapReAlloc".} proc HeapFree*(hHeap: HANDLE, dwFlags: DWORD, lpMem: LPVOID): WINBOOL{.stdcall, dynlib: "kernel32", importc: "HeapFree".} -proc HeapSize*(hHeap: HANDLE, dwFlags: DWORD, lpMem: LPCVOID): DWORD{.stdcall, +proc HeapSize*(hHeap: HANDLE, dwFlags: DWORD, lpMem: LPCVOID): SIZE_T{.stdcall, dynlib: "kernel32", importc: "HeapSize".} proc HeapValidate*(hHeap: HANDLE, dwFlags: DWORD, lpMem: LPCVOID): WINBOOL{. stdcall, dynlib: "kernel32", importc: "HeapValidate".} -proc HeapCompact*(hHeap: HANDLE, dwFlags: DWORD): WINUINT{.stdcall, +proc HeapCompact*(hHeap: HANDLE, dwFlags: DWORD): SIZE_T{.stdcall, dynlib: "kernel32", importc: "HeapCompact".} proc GetProcessHeap*(): HANDLE{.stdcall, dynlib: "kernel32", importc: "GetProcessHeap".} From 26115027bfd2cf4e2f8d4cd6aa784dabb8de94bb Mon Sep 17 00:00:00 2001 From: Chris Heller Date: Tue, 28 Apr 2015 10:12:06 -0700 Subject: [PATCH 0174/1263] Update the GlobalAlloc/ReAlloc and LocalAlloc/ReAlloc procs to use SIZE_T instead of DWORD. --- lib/windows/windows.nim | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/lib/windows/windows.nim b/lib/windows/windows.nim index fb4451d39..3ba7c9c7f 100644 --- a/lib/windows/windows.nim +++ b/lib/windows/windows.nim @@ -18513,11 +18513,11 @@ proc DisableThreadLibraryCalls*(hLibModule: HMODULE): WINBOOL{.stdcall, proc GetProcAddress*(hModule: HINST, lpProcName: LPCSTR): FARPROC{.stdcall, dynlib: "kernel32", importc: "GetProcAddress".} proc GetVersion*(): DWORD{.stdcall, dynlib: "kernel32", importc: "GetVersion".} -proc GlobalAlloc*(uFlags: int32, dwBytes: DWORD): HGLOBAL{.stdcall, +proc GlobalAlloc*(uFlags: int32, dwBytes: SIZE_T): HGLOBAL{.stdcall, dynlib: "kernel32", importc: "GlobalAlloc".} -proc GlobalReAlloc*(hMem: HGLOBAL, dwBytes: DWORD, uFlags: int32): HGLOBAL{. +proc GlobalReAlloc*(hMem: HGLOBAL, dwBytes: SIZE_T, uFlags: int32): HGLOBAL{. stdcall, dynlib: "kernel32", importc: "GlobalReAlloc".} -proc GlobalSize*(hMem: HGLOBAL): DWORD{.stdcall, dynlib: "kernel32", +proc GlobalSize*(hMem: HGLOBAL): SIZE_T{.stdcall, dynlib: "kernel32", importc: "GlobalSize".} proc GlobalFlags*(hMem: HGLOBAL): WINUINT{.stdcall, dynlib: "kernel32", importc: "GlobalFlags".} @@ -18541,9 +18541,9 @@ proc GlobalUnWire*(hMem: HGLOBAL): WINBOOL{.stdcall, dynlib: "kernel32", importc: "GlobalUnWire".} proc GlobalMemoryStatus*(lpBuffer: LPMEMORYSTATUS){.stdcall, dynlib: "kernel32", importc: "GlobalMemoryStatus".} -proc LocalAlloc*(uFlags: WINUINT, uBytes: WINUINT): HLOCAL{.stdcall, +proc LocalAlloc*(uFlags: WINUINT, uBytes: SIZE_T): HLOCAL{.stdcall, dynlib: "kernel32", importc: "LocalAlloc".} -proc LocalReAlloc*(hMem: HLOCAL, uBytes: WINUINT, uFlags: WINUINT): HLOCAL{.stdcall, +proc LocalReAlloc*(hMem: HLOCAL, uBytes: SIZE_T, uFlags: WINUINT): HLOCAL{.stdcall, dynlib: "kernel32", importc: "LocalReAlloc".} proc LocalLock*(hMem: HLOCAL): LPVOID{.stdcall, dynlib: "kernel32", importc: "LocalLock".} From fcb4d5a44a17c7fd9f477f00ad039ca00de800df Mon Sep 17 00:00:00 2001 From: Chris Heller Date: Tue, 28 Apr 2015 10:19:44 -0700 Subject: [PATCH 0175/1263] Update VirtualLock/Unlock to use SIZE_T instead of DWORD for sizes --- lib/windows/windows.nim | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/windows/windows.nim b/lib/windows/windows.nim index 3ba7c9c7f..1ea34ee21 100644 --- a/lib/windows/windows.nim +++ b/lib/windows/windows.nim @@ -19227,9 +19227,9 @@ proc FindNextChangeNotification*(hChangeHandle: HANDLE): WINBOOL{.stdcall, dynlib: "kernel32", importc: "FindNextChangeNotification".} proc FindCloseChangeNotification*(hChangeHandle: HANDLE): WINBOOL{.stdcall, dynlib: "kernel32", importc: "FindCloseChangeNotification".} -proc VirtualLock*(lpAddress: LPVOID, dwSize: DWORD): WINBOOL{.stdcall, +proc VirtualLock*(lpAddress: LPVOID, dwSize: SIZE_T): WINBOOL{.stdcall, dynlib: "kernel32", importc: "VirtualLock".} -proc VirtualUnlock*(lpAddress: LPVOID, dwSize: DWORD): WINBOOL{.stdcall, +proc VirtualUnlock*(lpAddress: LPVOID, dwSize: SIZE_T): WINBOOL{.stdcall, dynlib: "kernel32", importc: "VirtualUnlock".} proc MapViewOfFileEx*(hFileMappingObject: HANDLE, dwDesiredAccess: DWORD, dwFileOffsetHigh: DWORD, dwFileOffsetLow: DWORD, From 60862c22f5faeabe6b3dd21fcdd7ce7e4d45b6e1 Mon Sep 17 00:00:00 2001 From: def Date: Wed, 29 Apr 2015 21:34:03 +0200 Subject: [PATCH 0176/1263] Year shouldn't be arbitrarily limited to -10_000 .. 10_000. Instead it's an int now. --- lib/pure/times.nim | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/pure/times.nim b/lib/pure/times.nim index 5f8835c6a..1b9fa4599 100644 --- a/lib/pure/times.nim +++ b/lib/pure/times.nim @@ -119,7 +119,7 @@ type ## in the range 0 to 23. monthday*: range[1..31] ## The day of the month, in the range 1 to 31. month*: Month ## The current month. - year*: range[-10_000..10_000] ## The current year. + year*: int ## The current year. weekday*: WeekDay ## The current day of the week. yearday*: range[0..365] ## The number of days since January 1, ## in the range 0 to 365. @@ -379,7 +379,7 @@ when not defined(JS): result.hour = t.hour result.monthday = t.monthday result.month = ord(t.month) - result.year = t.year - 1900 + result.year = cint(t.year - 1900) result.weekday = weekDays[t.weekday] result.yearday = t.yearday result.isdst = if t.isDST: 1 else: 0 From 50f54bf60b55af731e4d6aff098226003b643bca Mon Sep 17 00:00:00 2001 From: msmith491 Date: Thu, 30 Apr 2015 21:36:50 -0700 Subject: [PATCH 0177/1263] Add arbitrary char support to the strutils proc. Issue #2626 --- lib/pure/strutils.nim | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/lib/pure/strutils.nim b/lib/pure/strutils.nim index 59cebf7fa..eb4be719a 100644 --- a/lib/pure/strutils.nim +++ b/lib/pure/strutils.nim @@ -169,14 +169,12 @@ proc cmpIgnoreStyle*(a, b: string): int {.noSideEffect, {.pop.} -proc strip*(s: string, leading = true, trailing = true): string {.noSideEffect, - rtl, extern: "nsuStrip".} = - ## Strips whitespace from `s` and returns the resulting string. +proc strip*(s: string, leading = true, trailing = true, chars: set[char] = Whitespace): string + {.noSideEffect, rtl, extern: "nsuStrip".} = + ## Strips `chars` from `s` and returns the resulting string. ## - ## If `leading` is true, leading whitespace is stripped. - ## If `trailing` is true, trailing whitespace is stripped. - const - chars: set[char] = Whitespace + ## If `leading` is true, leading `chars` are stripped. + ## If `trailing` is true, trailing `chars` are stripped. var first = 0 last = len(s)-1 @@ -1433,3 +1431,11 @@ when isMainModule: doAssert count("foofoofoo", "foofoo", overlapping = true) == 2 doAssert count("foofoofoo", 'f') == 3 doAssert count("foofoofoobar", {'f','b'}) == 4 + + doAssert strip(" foofoofoo ") == "foofoofoo" + doAssert strip("sfoofoofoos", chars = {'s'}) == "foofoofoo" + doAssert strip("barfoofoofoobar", chars = {'b', 'a', 'r'}) == "foofoofoo" + doAssert strip("stripme but don't strip this stripme", + chars = {'s', 't', 'r', 'i', 'p', 'm', 'e'}) == " but don't strip this " + doAssert strip("sfoofoofoos", leading = false, chars = {'s'}) == "sfoofoofoo" + doAssert strip("sfoofoofoos", trailing = false, chars = {'s'}) == "foofoofoos" From a1ee169d09b8d8c001e868d889c517fad4d1efaa Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Sat, 2 May 2015 05:28:53 +0500 Subject: [PATCH 0178/1263] implemented nextFreePort for nimsuggest --- compiler/nimsuggest/nimsuggest.nim | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/compiler/nimsuggest/nimsuggest.nim b/compiler/nimsuggest/nimsuggest.nim index 7e0d3a399..00b3bcbfd 100644 --- a/compiler/nimsuggest/nimsuggest.nim +++ b/compiler/nimsuggest/nimsuggest.nim @@ -13,6 +13,11 @@ import strutils, os, parseopt, parseutils, sequtils, net import options, commands, modules, sem, passes, passaux, msgs, nimconf, extccomp, condsyms, lists, net, rdstdin, sexp, suggest, ast +when defined(windows): + import winlean +else: + import posix + const Usage = """ Nimsuggest - Tool to give every editor IDE like capabilities for Nim Usage: @@ -130,8 +135,21 @@ proc returnEPC(socket: var Socket, uid: string, s: SexpNode, return_symbol = "re socket.send(response) socket.close() -proc findEPCPort(): int = - 55822 # guaranteed to be random +proc nextFreePort(server: Socket, host: string, start = 30000): int = + result = start + while true: + try: + server.bindaddr(Port(result), host) + return + except OsError: + when defined(windows): + let checkFor = WSAEADDRINUSE.OSErrorCode + else: + let checkFor = EADDRINUSE.OSErrorCode + if osLastError() != checkFor: + raise getCurrentException() + else: + result += 1 proc parseCmdLine(cmd: string) = template toggle(sw) = @@ -199,9 +217,8 @@ proc serve() = stdoutSocket.send("\c\L") stdoutSocket.close() of mepc: - let port = findEPCPort() var server = newSocket() - server.bindaddr(Port(port), "localhost") + let port = nextFreePort(server, "localhost") var inp = "".TaintedString server.listen() echo(port) From 7dfa93d3c0dc17541b5b54654f2af3da8bed91f5 Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Sat, 2 May 2015 08:04:17 +0500 Subject: [PATCH 0179/1263] fixed first round of bugs --- compiler/nimsuggest/nimsuggest.nim | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/compiler/nimsuggest/nimsuggest.nim b/compiler/nimsuggest/nimsuggest.nim index 00b3bcbfd..c14c89e16 100644 --- a/compiler/nimsuggest/nimsuggest.nim +++ b/compiler/nimsuggest/nimsuggest.nim @@ -133,7 +133,6 @@ proc returnEPC(socket: var Socket, uid: string, s: SexpNode, return_symbol = "re let response = $convertSexp([newSSymbol(return_symbol), [uid, s]]) socket.send(toHex(len(response), 6)) socket.send(response) - socket.close() proc nextFreePort(server: Socket, host: string, start = 30000): int = result = start @@ -235,9 +234,9 @@ proc serve() = var messageBuffer = "" if client.recv(messageBuffer, size) != size: raise newException(ValueError, "didn't get all the bytes") - let message = parseSexp($messageBuffer) - let messageType = message[0].getSymbol - let body = message[1] + let + message = parseSexp($messageBuffer) + messageType = message[0].getSymbol try: case messageType: of "call": @@ -246,9 +245,9 @@ proc serve() = results.add(s) let - uid = body[0].getStr - cmd = parseIdeCmd(body[1].getStr) - args = body[2] + uid = message[1].getStr + cmd = parseIdeCmd(message[2].getStr) + args = message[3] executeEPC(cmd, args) returnEPC(client, uid, sexp(results)) of "return": @@ -259,11 +258,11 @@ proc serve() = stderr.writeln("recieved epc error: " & $messageBuffer) raise newException(IOError, "epc error") of "methods": - returnEPC(client, body[0].getStr, listEPC()) + returnEPC(client, message[1].getStr, listEPC()) else: raise newException(EUnexpectedCommand, "unexpected call: " & messageType) except: - returnEPC(client, body[0].getStr, sexp(getCurrentExceptionMsg()), "return-error") + returnEPC(client, message[1].getStr, sexp(getCurrentException().getStackTrace()), "return-error") proc mainCommand = registerPass verbosePass From b50090797804ea3f669932c4eb9a26fe4899842c Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Sat, 2 May 2015 08:24:05 +0500 Subject: [PATCH 0180/1263] some more bugs in epc fixed - removed try --- compiler/nimsuggest/nimsuggest.nim | 59 ++++++++++++++++-------------- 1 file changed, 31 insertions(+), 28 deletions(-) diff --git a/compiler/nimsuggest/nimsuggest.nim b/compiler/nimsuggest/nimsuggest.nim index c14c89e16..68d89e6e9 100644 --- a/compiler/nimsuggest/nimsuggest.nim +++ b/compiler/nimsuggest/nimsuggest.nim @@ -83,7 +83,9 @@ proc sexp(s: Suggest): SexpNode = ]) proc sexp(s: seq[Suggest]): SexpNode = - result = sexp(s) + result = newSList() + for sug in s: + result.add(sexp(sug)) proc listEPC(): SexpNode = let @@ -126,11 +128,13 @@ proc executeEPC(cmd: IdeCmd, args: SexpNode) = file = args[0].getStr line = args[1].getNum column = args[2].getNum + var dirtyfile = "" + if len(args) > 3: dirtyfile = args[3].getStr(nil) execute(cmd, file, dirtyfile, int(line), int(column)) -proc returnEPC(socket: var Socket, uid: string, s: SexpNode, return_symbol = "return") = - let response = $convertSexp([newSSymbol(return_symbol), [uid, s]]) +proc returnEPC(socket: var Socket, uid: BiggestInt, s: SexpNode, return_symbol = "return") = + let response = $convertSexp([newSSymbol(return_symbol), uid, s]) socket.send(toHex(len(response), 6)) socket.send(response) @@ -237,32 +241,31 @@ proc serve() = let message = parseSexp($messageBuffer) messageType = message[0].getSymbol - try: - case messageType: - of "call": - var results: seq[Suggest] = @[] - suggest.suggestionResultHook = proc (s: Suggest) = - results.add(s) + echo("received message: " & $message) + case messageType: + of "call": + var results: seq[Suggest] = @[] + suggest.suggestionResultHook = proc (s: Suggest) = + echo(s) + results.add(s) - let - uid = message[1].getStr - cmd = parseIdeCmd(message[2].getStr) - args = message[3] - executeEPC(cmd, args) - returnEPC(client, uid, sexp(results)) - of "return": - raise newException(EUnexpectedCommand, "no return expected") - of "return-error": - raise newException(EUnexpectedCommand, "no return expected") - of "epc-error": - stderr.writeln("recieved epc error: " & $messageBuffer) - raise newException(IOError, "epc error") - of "methods": - returnEPC(client, message[1].getStr, listEPC()) - else: - raise newException(EUnexpectedCommand, "unexpected call: " & messageType) - except: - returnEPC(client, message[1].getStr, sexp(getCurrentException().getStackTrace()), "return-error") + let + uid = message[1].getNum + cmd = parseIdeCmd(message[2].getStr) + args = message[3] + executeEPC(cmd, args) + returnEPC(client, uid, sexp(results)) + of "return": + raise newException(EUnexpectedCommand, "no return expected") + of "return-error": + raise newException(EUnexpectedCommand, "no return expected") + of "epc-error": + stderr.writeln("recieved epc error: " & $messageBuffer) + raise newException(IOError, "epc error") + of "methods": + returnEPC(client, message[1].getNum, listEPC()) + else: + raise newException(EUnexpectedCommand, "unexpected call: " & messageType) proc mainCommand = registerPass verbosePass From 0ff5339590b0acde4c344af7799232ae2d44737f Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Sat, 2 May 2015 08:34:30 +0500 Subject: [PATCH 0181/1263] removed debug echos --- compiler/nimsuggest/nimsuggest.nim | 2 -- 1 file changed, 2 deletions(-) diff --git a/compiler/nimsuggest/nimsuggest.nim b/compiler/nimsuggest/nimsuggest.nim index 68d89e6e9..636d14e7f 100644 --- a/compiler/nimsuggest/nimsuggest.nim +++ b/compiler/nimsuggest/nimsuggest.nim @@ -241,12 +241,10 @@ proc serve() = let message = parseSexp($messageBuffer) messageType = message[0].getSymbol - echo("received message: " & $message) case messageType: of "call": var results: seq[Suggest] = @[] suggest.suggestionResultHook = proc (s: Suggest) = - echo(s) results.add(s) let From 2522049ed2991cf9c8c8c7026646e16472125271 Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Sat, 2 May 2015 09:14:02 +0500 Subject: [PATCH 0182/1263] method arrives as symbol --- compiler/nimsuggest/nimsuggest.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/nimsuggest/nimsuggest.nim b/compiler/nimsuggest/nimsuggest.nim index 636d14e7f..6975c87cc 100644 --- a/compiler/nimsuggest/nimsuggest.nim +++ b/compiler/nimsuggest/nimsuggest.nim @@ -249,7 +249,7 @@ proc serve() = let uid = message[1].getNum - cmd = parseIdeCmd(message[2].getStr) + cmd = parseIdeCmd(message[2].getSymbol) args = message[3] executeEPC(cmd, args) returnEPC(client, uid, sexp(results)) From 1e78c5445d2d2bd7cc5f39579dd8ff0f8bbcb65c Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Sat, 2 May 2015 09:22:26 +0500 Subject: [PATCH 0183/1263] manually reapplied d40098ad --- compiler/nimsuggest/nimsuggest.nim | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/compiler/nimsuggest/nimsuggest.nim b/compiler/nimsuggest/nimsuggest.nim index 6975c87cc..3f8943016 100644 --- a/compiler/nimsuggest/nimsuggest.nim +++ b/compiler/nimsuggest/nimsuggest.nim @@ -183,12 +183,13 @@ proc parseCmdLine(cmd: string) = if cmd[i] == ';': i = parseQuoted(cmd, dirtyfile, i+1) i += skipWhile(cmd, seps, i) - var line, col = -1 + var line = -1 + var col = 0 i += parseInt(cmd, line, i) i += skipWhile(cmd, seps, i) i += parseInt(cmd, col, i) - execute(gIdeCmd, orig, dirtyfile, line, col) + execute(gIdeCmd, orig, dirtyfile, line, col-1) proc serve() = # do not stop after the first error: From 2aa61034ba0fd9962b948b14936c8642f0e64d1c Mon Sep 17 00:00:00 2001 From: Chris Heller Date: Fri, 1 May 2015 23:54:28 -0700 Subject: [PATCH 0184/1263] Add deprecated versions of procs in windows.nim that had DWORD parameters converted to SIZE_T --- lib/windows/windows.nim | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/lib/windows/windows.nim b/lib/windows/windows.nim index 1ea34ee21..02c87132a 100644 --- a/lib/windows/windows.nim +++ b/lib/windows/windows.nim @@ -18515,8 +18515,12 @@ proc GetProcAddress*(hModule: HINST, lpProcName: LPCSTR): FARPROC{.stdcall, proc GetVersion*(): DWORD{.stdcall, dynlib: "kernel32", importc: "GetVersion".} proc GlobalAlloc*(uFlags: int32, dwBytes: SIZE_T): HGLOBAL{.stdcall, dynlib: "kernel32", importc: "GlobalAlloc".} +proc GlobalAlloc*(uFlags: int32, dwBytes: DWORD): HGLOBAL{.stdcall, + dynlib: "kernel32", importc: "GlobalAlloc", deprecated.} proc GlobalReAlloc*(hMem: HGLOBAL, dwBytes: SIZE_T, uFlags: int32): HGLOBAL{. stdcall, dynlib: "kernel32", importc: "GlobalReAlloc".} +proc GlobalReAlloc*(hMem: HGLOBAL, dwBytes: DWORD, uFlags: int32): HGLOBAL{. + stdcall, dynlib: "kernel32", importc: "GlobalReAlloc", deprecated.} proc GlobalSize*(hMem: HGLOBAL): SIZE_T{.stdcall, dynlib: "kernel32", importc: "GlobalSize".} proc GlobalFlags*(hMem: HGLOBAL): WINUINT{.stdcall, dynlib: "kernel32", @@ -18543,8 +18547,12 @@ proc GlobalMemoryStatus*(lpBuffer: LPMEMORYSTATUS){.stdcall, dynlib: "kernel32", importc: "GlobalMemoryStatus".} proc LocalAlloc*(uFlags: WINUINT, uBytes: SIZE_T): HLOCAL{.stdcall, dynlib: "kernel32", importc: "LocalAlloc".} +proc LocalAlloc*(uFlags: WINUINT, uBytes: DWORD): HLOCAL{.stdcall, + dynlib: "kernel32", importc: "LocalAlloc", deprecated.} proc LocalReAlloc*(hMem: HLOCAL, uBytes: SIZE_T, uFlags: WINUINT): HLOCAL{.stdcall, dynlib: "kernel32", importc: "LocalReAlloc".} +proc LocalReAlloc*(hMem: HLOCAL, uBytes: DWORD, uFlags: WINUINT): HLOCAL{.stdcall, + dynlib: "kernel32", importc: "LocalReAlloc", deprecated.} proc LocalLock*(hMem: HLOCAL): LPVOID{.stdcall, dynlib: "kernel32", importc: "LocalLock".} proc LocalHandle*(pMem: LPCVOID): HLOCAL{.stdcall, dynlib: "kernel32", @@ -18567,34 +18575,61 @@ proc FlushInstructionCache*(hProcess: HANDLE, lpBaseAddress: LPCVOID, proc VirtualAlloc*(lpAddress: LPVOID, dwSize: SIZE_T, flAllocationType: DWORD, flProtect: DWORD): LPVOID{.stdcall, dynlib: "kernel32", importc: "VirtualAlloc".} +proc VirtualAlloc*(lpAddress: LPVOID, dwSize: DWORD, flAllocationType: DWORD, + flProtect: DWORD): LPVOID{.stdcall, dynlib: "kernel32", + importc: "VirtualAlloc", deprecated.} proc VirtualAllocEx*(hProcess: HANDLE, lpAddress: LPVOID, dwSize: SIZE_T, flAllocationType: DWORD, flProtect: DWORD): LPVOID {.stdcall, dynlib: "kernel32", importc: "VirtualAllocEx".} +proc VirtualAllocEx*(hProcess: HANDLE, lpAddress: LPVOID, dwSize: DWORD, + flAllocationType: DWORD, flProtect: DWORD): LPVOID + {.stdcall, dynlib: "kernel32", importc: "VirtualAllocEx", + deprecated.} proc VirtualFree*(lpAddress: LPVOID, dwSize: SIZE_T, dwFreeType: DWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "VirtualFree".} +proc VirtualFree*(lpAddress: LPVOID, dwSize: DWORD, dwFreeType: DWORD): WINBOOL{. + stdcall, dynlib: "kernel32", importc: "VirtualFree", deprecated.} proc VirtualFreeEx*(hProcess: HANDLE, lpAddress: LPVOID, dwSize: SIZE_T, dwFreeType: DWORD): WINBOOL {.stdcall, dynlib: "kernel32", importc: "VirtualFree".} +proc VirtualFreeEx*(hProcess: HANDLE, lpAddress: LPVOID, dwSize: DWORD, + dwFreeType: DWORD): WINBOOL + {.stdcall, dynlib: "kernel32", importc: "VirtualFree".} proc VirtualProtect*(lpAddress: LPVOID, dwSize: SIZE_T, flNewProtect: DWORD, lpflOldProtect: PDWORD): WINBOOL{.stdcall, dynlib: "kernel32", importc: "VirtualProtect".} +proc VirtualProtect*(lpAddress: LPVOID, dwSize: DWORD, flNewProtect: DWORD, + lpflOldProtect: PDWORD): WINBOOL{.stdcall, + dynlib: "kernel32", importc: "VirtualProtect", deprecated.} proc VirtualQuery*(lpAddress: LPCVOID, lpBuffer: PMEMORY_BASIC_INFORMATION, dwLength: DWORD): DWORD{.stdcall, dynlib: "kernel32", importc: "VirtualQuery".} proc VirtualProtectEx*(hProcess: HANDLE, lpAddress: LPVOID, dwSize: SIZE_T, flNewProtect: DWORD, lpflOldProtect: PDWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "VirtualProtectEx".} +proc VirtualProtectEx*(hProcess: HANDLE, lpAddress: LPVOID, dwSize: DWORD, + flNewProtect: DWORD, lpflOldProtect: PDWORD): WINBOOL{. + stdcall, dynlib: "kernel32", importc: "VirtualProtectEx", deprecated.} proc VirtualQueryEx*(hProcess: HANDLE, lpAddress: LPCVOID, lpBuffer: PMEMORY_BASIC_INFORMATION, dwLength: SIZE_T): DWORD{. stdcall, dynlib: "kernel32", importc: "VirtualQueryEx".} +proc VirtualQueryEx*(hProcess: HANDLE, lpAddress: LPCVOID, + lpBuffer: PMEMORY_BASIC_INFORMATION, dwLength: DWORD): DWORD{. + stdcall, dynlib: "kernel32", importc: "VirtualQueryEx", deprecated.} proc HeapCreate*(flOptions: DWORD, dwInitialSize: SIZE_T, dwMaximumSize: SIZE_T): HANDLE{. stdcall, dynlib: "kernel32", importc: "HeapCreate".} +proc HeapCreate*(flOptions: DWORD, dwInitialSize: DWORD, dwMaximumSize: DWORD): HANDLE{. + stdcall, dynlib: "kernel32", importc: "HeapCreate", deprecated.} proc HeapDestroy*(hHeap: HANDLE): WINBOOL{.stdcall, dynlib: "kernel32", importc: "HeapDestroy".} proc HeapAlloc*(hHeap: HANDLE, dwFlags: DWORD, dwBytes: SIZE_T): LPVOID{.stdcall, dynlib: "kernel32", importc: "HeapAlloc".} +proc HeapAlloc*(hHeap: HANDLE, dwFlags: DWORD, dwBytes: DWORD): LPVOID{.stdcall, + dynlib: "kernel32", importc: "HeapAlloc", deprecated.} proc HeapReAlloc*(hHeap: HANDLE, dwFlags: DWORD, lpMem: LPVOID, dwBytes: SIZE_T): LPVOID{. stdcall, dynlib: "kernel32", importc: "HeapReAlloc".} +proc HeapReAlloc*(hHeap: HANDLE, dwFlags: DWORD, lpMem: LPVOID, dwBytes: DWORD): LPVOID{. + stdcall, dynlib: "kernel32", importc: "HeapReAlloc", deprecated.} proc HeapFree*(hHeap: HANDLE, dwFlags: DWORD, lpMem: LPVOID): WINBOOL{.stdcall, dynlib: "kernel32", importc: "HeapFree".} proc HeapSize*(hHeap: HANDLE, dwFlags: DWORD, lpMem: LPCVOID): SIZE_T{.stdcall, @@ -19229,8 +19264,12 @@ proc FindCloseChangeNotification*(hChangeHandle: HANDLE): WINBOOL{.stdcall, dynlib: "kernel32", importc: "FindCloseChangeNotification".} proc VirtualLock*(lpAddress: LPVOID, dwSize: SIZE_T): WINBOOL{.stdcall, dynlib: "kernel32", importc: "VirtualLock".} +proc VirtualLock*(lpAddress: LPVOID, dwSize: DWORD): WINBOOL{.stdcall, + dynlib: "kernel32", importc: "VirtualLock", deprecated.} proc VirtualUnlock*(lpAddress: LPVOID, dwSize: SIZE_T): WINBOOL{.stdcall, dynlib: "kernel32", importc: "VirtualUnlock".} +proc VirtualUnlock*(lpAddress: LPVOID, dwSize: DWORD): WINBOOL{.stdcall, + dynlib: "kernel32", importc: "VirtualUnlock", deprecated.} proc MapViewOfFileEx*(hFileMappingObject: HANDLE, dwDesiredAccess: DWORD, dwFileOffsetHigh: DWORD, dwFileOffsetLow: DWORD, dwNumberOfBytesToMap: DWORD, lpBaseAddress: LPVOID): LPVOID{. From 7fb5932b9bad02cd9b056cd3a11e514acc94d781 Mon Sep 17 00:00:00 2001 From: Stephen Sugden Date: Sun, 3 May 2015 00:16:22 +0200 Subject: [PATCH 0185/1263] Resolve base type fields in `[](TAny, string)` --- lib/core/typeinfo.nim | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/core/typeinfo.nim b/lib/core/typeinfo.nim index c3ff66591..f08f74c20 100644 --- a/lib/core/typeinfo.nim +++ b/lib/core/typeinfo.nim @@ -339,6 +339,8 @@ proc `[]`*(x: TAny, fieldName: string): TAny = if n != nil: result.value = x.value +!! n.offset result.rawType = n.typ + elif x.rawType.kind == tyObject and x.rawType.base != nil: + return `[]`(TAny(value: x.value, rawType: x.rawType.base), fieldName) else: raise newException(ValueError, "invalid field name: " & fieldName) From 0e8e57496190f1773667b8c536c72a8b47d1b9e6 Mon Sep 17 00:00:00 2001 From: def Date: Sun, 3 May 2015 03:47:24 +0200 Subject: [PATCH 0186/1263] Use builtin overflow functions of Clang and GCC (WIP, RFC) This only works with recent Clang and GCC 5.0. Currently it doesn't work because __has_builtin can't be defined. This is totally ugly. But we can't reliably detect whether we can use the builtins from Nim, especially with cross-compiling where the user may be using an older compiler version. Switching this on/off manually with a define seems weird as well, this should work automatically. --- lib/system/arithm.nim | 99 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) diff --git a/lib/system/arithm.nim b/lib/system/arithm.nim index f68e2dcd9..e41372bc6 100644 --- a/lib/system/arithm.nim +++ b/lib/system/arithm.nim @@ -8,6 +8,75 @@ # +# Only clang has __has_builtin (so far) +# +# TODO: This is emitted at the wrong position so we don't actually have an +# emit. Could we add this to nimbase.h instead? +{.emit: """#ifndef __has_builtin + #define __has_builtin(x) 0 +#endif""".} + +# Builtin compiler functions for improved performance + +proc checkFunction(name: string): string = + "((__has_builtin(__builtin_" & name & "_overflow)) || __GNUC__ >= 5)" + +# TODO: This is totally ugly. But we can't reliably detect this from Nim, +# especially with cross-compiling where the user may be using an older compiler +# version. Switching this on/off manually with a define seems weird as well. +when sizeof(clong) == 8: + const hasAddInt64Overflow = checkFunction("saddl") + proc addInt64Overflow[T: int64|int](a, b: T, c: var T): bool {. + importc: "__builtin_saddl_overflow", nodecl, nosideeffect.} + + const hasSubInt64Overflow = checkFunction("ssubl") + proc subInt64Overflow[T: int64|int](a, b: T, c: var T): bool {. + importc: "__builtin_ssubl_overflow", nodecl, nosideeffect.} + + const hasMulInt64Overflow = checkFunction("smull") + proc mulInt64Overflow[T: int64|int](a, b: T, c: var T): bool {. + importc: "__builtin_smull_overflow", nodecl, nosideeffect.} + +elif sizeof(clonglong) == 8: + const hasAddInt64Overflow = checkFunction("saddll") + proc addInt64Overflow[T: int64|int](a, b: T, c: var T): bool {. + importc: "__builtin_saddll_overflow", nodecl, nosideeffect.} + + const hasSubInt64Overflow = checkFunction("ssubll") + proc subInt64Overflow[T: int64|int](a, b: T, c: var T): bool {. + importc: "__builtin_ssubll_overflow", nodecl, nosideeffect.} + + const hasMulInt64Overflow = checkFunction("smulll") + proc mulInt64Overflow[T: int64|int](a, b: T, c: var T): bool {. + importc: "__builtin_smulll_overflow", nodecl, nosideeffect.} + +when sizeof(int) == 8: + const hasAddIntOverflow = hasAddInt64Overflow + proc addIntOverflow(a, b: int, c: var int): bool {.inline.} = + addInt64Overflow(a, b, c) + + const hasSubIntOverflow = hasSubInt64Overflow + proc subIntOverflow(a, b: int, c: var int): bool {.inline.} = + subInt64Overflow(a, b, c) + + const hasMulIntOverflow = hasMulInt64Overflow + proc mulIntOverflow(a, b: int, c: var int): bool {.inline.} = + mulInt64Overflow(a, b, c) + +elif sizeof(int) == 4 and sizeof(cint) == 4: + const hasAddIntOverflow = checkFunction("sadd") + proc addIntOverflow(a, b: int, c: var int): bool {. + importc: "__builtin_sadd_overflow", nodecl, nosideeffect.} + + const hasSubIntOverflow = checkFunction("ssub") + proc subIntOverflow(a, b: int, c: var int): bool {. + importc: "__builtin_ssub_overflow", nodecl, nosideeffect.} + + const hasMulIntOverflow = checkFunction("smul") + proc mulIntOverflow(a, b: int, c: var int): bool {. + importc: "__builtin_smul_overflow", nodecl, nosideeffect.} + + # simple integer arithmetic with overflow checking proc raiseOverflow {.compilerproc, noinline, noreturn.} = @@ -18,16 +87,26 @@ proc raiseDivByZero {.compilerproc, noinline, noreturn.} = sysFatal(DivByZeroError, "division by zero") proc addInt64(a, b: int64): int64 {.compilerProc, inline.} = + {.emit: "#if `hasAddInt64Overflow`".} + if addInt64Overflow(a, b, result): + raiseOverflow() + {.emit: "#else".} result = a +% b if (result xor a) >= int64(0) or (result xor b) >= int64(0): return result raiseOverflow() + {.emit: "#endif".} proc subInt64(a, b: int64): int64 {.compilerProc, inline.} = + {.emit: "#if `hasSubInt64Overflow`".} + if subInt64Overflow(a, b, result): + raiseOverflow() + {.emit: "#else".} result = a -% b if (result xor a) >= int64(0) or (result xor not b) >= int64(0): return result raiseOverflow() + {.emit: "#endif".} proc negInt64(a: int64): int64 {.compilerProc, inline.} = if a != low(int64): return -a @@ -72,6 +151,10 @@ proc modInt64(a, b: int64): int64 {.compilerProc, inline.} = # product that must have overflowed. # proc mulInt64(a, b: int64): int64 {.compilerproc.} = + {.emit: "#if `hasMulInt64Overflow`".} + if mulInt64Overflow(a, b, result): + raiseOverflow() + {.emit: "#else".} var resAsFloat, floatProd: float64 result = a *% b @@ -93,6 +176,7 @@ proc mulInt64(a, b: int64): int64 {.compilerproc.} = if 32.0 * abs(resAsFloat - floatProd) <= abs(floatProd): return result raiseOverflow() + {.emit: "#endif".} proc absInt(a: int): int {.compilerProc, inline.} = @@ -249,17 +333,27 @@ elif false: # asmVersion and (defined(gcc) or defined(llvm_gcc)): # Platform independent versions of the above (slower!) when not declared(addInt): proc addInt(a, b: int): int {.compilerProc, inline.} = + {.emit: "#if `hasAddIntOverflow`".} + if addIntOverflow(a, b, result): + raiseOverflow() + {.emit: "#else".} result = a +% b if (result xor a) >= 0 or (result xor b) >= 0: return result raiseOverflow() + {.emit: "#endif".} when not declared(subInt): proc subInt(a, b: int): int {.compilerProc, inline.} = + {.emit: "#if `hasSubIntOverflow`".} + if subIntOverflow(a, b, result): + raiseOverflow() + {.emit: "#else".} result = a -% b if (result xor a) >= 0 or (result xor not b) >= 0: return result raiseOverflow() + {.emit: "#endif".} when not declared(negInt): proc negInt(a: int): int {.compilerProc, inline.} = @@ -302,6 +396,10 @@ when not declared(mulInt): # native int product that must have overflowed. # proc mulInt(a, b: int): int {.compilerProc.} = + {.emit: "#if `hasMulIntOverflow`".} + if mulIntOverflow(a, b, result): + raiseOverflow() + {.emit: "#else".} var resAsFloat, floatProd: float @@ -323,6 +421,7 @@ when not declared(mulInt): if 32.0 * abs(resAsFloat - floatProd) <= abs(floatProd): return result raiseOverflow() + {.emit: "#endif".} # We avoid setting the FPU control word here for compatibility with libraries # written in other languages. From e31bca55fae7e451a2da76fa0b64dec8562f9573 Mon Sep 17 00:00:00 2001 From: Adam Strzelecki Date: Sun, 3 May 2015 18:50:05 +0200 Subject: [PATCH 0187/1263] Make csources a submodule 1. Solves a problem that updating Nim sources we have no indication we need to update csources as well. 2. Using submodule we can explicitly request that some Nim version requires some csources version to bootstrap. 3. build.sh now simply calls: git submodule update --init --depth 1 instead shallow clone on missing csources subdirectory. --- .gitignore | 1 - .gitmodules | 3 +++ build.sh | 2 +- csources | 1 + 4 files changed, 5 insertions(+), 2 deletions(-) create mode 100644 .gitmodules create mode 160000 csources diff --git a/.gitignore b/.gitignore index d804fb8f5..462df4efc 100644 --- a/.gitignore +++ b/.gitignore @@ -41,4 +41,3 @@ xcuserdata/ /testresults.html /testresults.json testament.db -/csources/ diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 000000000..26f35d82c --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "csources"] + path = csources + url = ../../nim-lang/csources.git diff --git a/build.sh b/build.sh index 139c28359..87e12dcfd 100644 --- a/build.sh +++ b/build.sh @@ -3,7 +3,7 @@ set -e set -x if [ ! -d "csources" ]; then - git clone --depth 1 https://github.com/nim-lang/csources.git + git submodule update --init --depth 1 fi cd "csources" diff --git a/csources b/csources new file mode 160000 index 000000000..15724e2e1 --- /dev/null +++ b/csources @@ -0,0 +1 @@ +Subproject commit 15724e2e1f3e7749d508dfcd995e84fea2850802 From 05e072b8c48d05a1bed1a4ccb69a79c22f0d7821 Mon Sep 17 00:00:00 2001 From: Adam Strzelecki Date: Sun, 3 May 2015 18:56:18 +0200 Subject: [PATCH 0188/1263] Make build.sh executable There is no reason build.sh shouldn't be executable and we couldn't build Nim with: ./build.sh --- build.sh | 0 1 file changed, 0 insertions(+), 0 deletions(-) mode change 100644 => 100755 build.sh diff --git a/build.sh b/build.sh old mode 100644 new mode 100755 From 80b5e612c0f92f2bae6e148317a682deb86821f0 Mon Sep 17 00:00:00 2001 From: apense Date: Mon, 4 May 2015 08:49:41 -0400 Subject: [PATCH 0189/1263] Update streams.nim --- lib/pure/streams.nim | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/lib/pure/streams.nim b/lib/pure/streams.nim index 798c587a1..ce33a9625 100644 --- a/lib/pure/streams.nim +++ b/lib/pure/streams.nim @@ -471,3 +471,13 @@ else: var handle = open(filename, flags) if handle < 0: raise newEOS("posix.open() call failed") result = newFileHandleStream(handle) + +when defined(testing): + var ss = newStringStream("The quick brown fox jumped over the lazy dog.\nThe lazy dog ran") + assert(ss.getPosition == 0) + assert(ss.peekStr(5) == "The q") + assert(ss.getPosition == 0) # haven't moved + assert(ss.readStr(5) == "The q") + assert(ss.getPosition == 5) # did move + assert(ss.peekLine() == "uick brown fox jumped over the lazy dog.") + assert(ss.getPosition == 5) # haven't moved From ba0b9e26c6fb98dc8bd76fbe5783f5487454619a Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Mon, 4 May 2015 16:47:31 -0400 Subject: [PATCH 0190/1263] Better handle errors Fixes #7 --- src/nre.nim | 31 +++++++++++++++++++++++++------ 1 file changed, 25 insertions(+), 6 deletions(-) diff --git a/src/nre.nim b/src/nre.nim index b960bdc92..c519180f6 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -167,13 +167,22 @@ type Captures* = distinct RegexMatch CaptureBounds* = distinct RegexMatch - SyntaxError* = ref object of Exception + RegexException* = ref object of Exception + + RegexInternalError* = ref object of RegexException + ## Internal error in the module, this probably means that there is a bug + + InvalidUnicodeError* = ref object of RegexException + ## Thrown when matching fails due to invalid unicode in strings + pos*: int ## the location of the invalid unicode in bytes + + SyntaxError* = ref object of RegexException ## Thrown when there is a syntax error in the ## regular expression string passed in pos*: int ## the location of the syntax error in bytes pattern*: string ## the pattern that caused the problem - StudyError* = ref object of Exception + StudyError* = ref object of RegexException ## Thrown when studying the regular expression failes ## for whatever reason. The message contains the error ## code. @@ -454,10 +463,20 @@ proc matchImpl(str: string, pattern: Regex, start, endpos: int, flags: int): Opt cint(vecsize)) if execRet >= 0: return Some(myResult) - elif execRet == pcre.ERROR_NOMATCH: - return None[RegexMatch]() - else: - raise newException(AssertionError, "Internal error: errno " & $execRet) + + case execRet: + of pcre.ERROR_NOMATCH: + return None[RegexMatch]() + of pcre.ERROR_NULL: + raise newException(AccessViolationError, "Expected non-null parameters") + of pcre.ERROR_BADOPTION: + raise RegexInternalError(msg : "Unknown pattern flag. Either a bug or " & + "outdated PCRE.") + of pcre.ERROR_BADUTF8, pcre.ERROR_SHORTUTF8, pcre.ERROR_BADUTF8_OFFSET: + raise InvalidUnicodeError(msg : "Invalid unicode byte sequence", + pos : myResult.pcreMatchBounds[0].a) + else: + raise RegexInternalError(msg : "Unknown internal error: " & $execRet) proc match*(str: string, pattern: Regex, start = 0, endpos = int.high): Option[RegexMatch] = ## Like ```find(...)`` <#proc-find>`__, but anchored to the start of the From a9fe618756304a765006a54b3f8f8b1cdae0ffb9 Mon Sep 17 00:00:00 2001 From: def Date: Mon, 4 May 2015 23:59:53 +0200 Subject: [PATCH 0191/1263] Pass noReturn pragma to C code. With GCC and Clang this generates __attribute__((noreturn)) in the function declaration. (both tested) With VCC __declspec(noreturn) is used. --- compiler/cgen.nim | 5 +++++ compiler/extccomp.nim | 8 +++++--- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/compiler/cgen.nim b/compiler/cgen.nim index da9c6f653..4743e4576 100644 --- a/compiler/cgen.nim +++ b/compiler/cgen.nim @@ -676,6 +676,9 @@ proc genProcAux(m: BModule, prc: PSym) = closureSetup(p, prc) genStmts(p, prc.getBody) # modifies p.locals, p.init, etc. var generatedProc: Rope + if sfNoReturn in prc.flags: + if hasNoreturnDeclspec in extccomp.CC[extccomp.cCompiler].props: + header = "__declspec(noreturn) " & header if sfPure in prc.flags: if hasNakedDeclspec in extccomp.CC[extccomp.cCompiler].props: header = "__declspec(naked) " & header @@ -722,6 +725,8 @@ proc genProcPrototype(m: BModule, sym: PSym) = header = "extern \"C\" " & header if sfPure in sym.flags and hasNakedAttribute in CC[cCompiler].props: header.add(" __attribute__((naked))") + if sfNoReturn in sym.flags and hasNoreturnAttribute in CC[cCompiler].props: + header.add(" __attribute__((noreturn))") add(m.s[cfsProcHeaders], rfmt(nil, "$1;$n", header)) proc genProcNoForward(m: BModule, prc: PSym) = diff --git a/compiler/extccomp.nim b/compiler/extccomp.nim index 26f0318ee..1bf4eb757 100644 --- a/compiler/extccomp.nim +++ b/compiler/extccomp.nim @@ -27,7 +27,9 @@ type hasGcGuard, # CC supports GC_GUARD to keep stack roots hasGnuAsm, # CC's asm uses the absurd GNU assembler syntax hasNakedDeclspec, # CC has __declspec(naked) - hasNakedAttribute # CC has __attribute__((naked)) + hasNakedAttribute, # CC has __attribute__((naked)) + hasNoreturnAttribute, # CC has __attribute__((noreturn)) + hasNoreturnDeclspec # CC has __declspec(noreturn) TInfoCCProps* = set[TInfoCCProp] TInfoCC* = tuple[ name: string, # the short name of the compiler @@ -85,7 +87,7 @@ compiler gcc: structStmtFmt: "$1 $3 $2 ", # struct|union [packed] $name packedPragma: "__attribute__((__packed__))", props: {hasSwitchRange, hasComputedGoto, hasCpp, hasGcGuard, hasGnuAsm, - hasNakedAttribute}) + hasNakedAttribute, hasNoreturnAttribute}) # LLVM Frontend for GCC/G++ compiler llvmGcc: @@ -127,7 +129,7 @@ compiler vcc: asmStmtFrmt: "__asm{$n$1$n}$n", structStmtFmt: "$3$n$1 $2", packedPragma: "#pragma pack(1)", - props: {hasCpp, hasAssume, hasNakedDeclspec}) + props: {hasCpp, hasAssume, hasNakedDeclspec, hasNoreturnDeclspec}) # Intel C/C++ Compiler compiler icl: From c5db4fc3a27b17cc20fc13de0a325c126e612c16 Mon Sep 17 00:00:00 2001 From: def Date: Tue, 5 May 2015 20:24:54 +0200 Subject: [PATCH 0192/1263] Move the noreturn pragma to sysFatal Now you can choose to implement sysFatal with --os:standalone so that it returns. --- lib/system.nim | 19 ++++++++++--------- lib/system/arithm.nim | 8 ++++---- lib/system/chcks.nim | 6 +++--- tests/manyloc/standalone/panicoverride.nim | 6 +++--- 4 files changed, 20 insertions(+), 19 deletions(-) diff --git a/lib/system.nim b/lib/system.nim index ca4c81411..1e6f76f3d 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -1110,7 +1110,7 @@ var programResult* {.exportc: "nim_program_result".}: int ## prematurely using ``quit``, this value is ignored. proc quit*(errorcode: int = QuitSuccess) {. - magic: "Exit", importc: "exit", header: "", noReturn.} + magic: "Exit", importc: "exit", header: "", noreturn.} ## Stops the program immediately with an exit code. ## ## Before stopping the program the "quit procedures" are called in the @@ -2270,20 +2270,21 @@ when hostOS == "standalone": include panicoverride when not declared(sysFatal): - template sysFatal(exceptn: typedesc, message: string) = - when hostOS == "standalone": + when hostOS == "standalone": + proc sysFatal(exceptn: typedesc, message: string) {.inline.} = panic(message) - else: + + proc sysFatal(exceptn: typedesc, message, arg: string) {.inline.} = + rawoutput(message) + panic(arg) + else: + proc sysFatal(exceptn: typedesc, message: string) {.inline, noReturn.} = var e: ref exceptn new(e) e.msg = message raise e - template sysFatal(exceptn: typedesc, message, arg: string) = - when hostOS == "standalone": - rawoutput(message) - panic(arg) - else: + proc sysFatal(exceptn: typedesc, message, arg: string) {.inline, noReturn.} = var e: ref exceptn new(e) e.msg = message & arg diff --git a/lib/system/arithm.nim b/lib/system/arithm.nim index f68e2dcd9..ef153417c 100644 --- a/lib/system/arithm.nim +++ b/lib/system/arithm.nim @@ -10,11 +10,11 @@ # simple integer arithmetic with overflow checking -proc raiseOverflow {.compilerproc, noinline, noreturn.} = +proc raiseOverflow {.compilerproc, noinline.} = # a single proc to reduce code size to a minimum sysFatal(OverflowError, "over- or underflow") -proc raiseDivByZero {.compilerproc, noinline, noreturn.} = +proc raiseDivByZero {.compilerproc, noinline.} = sysFatal(DivByZeroError, "division by zero") proc addInt64(a, b: int64): int64 {.compilerProc, inline.} = @@ -327,13 +327,13 @@ when not declared(mulInt): # We avoid setting the FPU control word here for compatibility with libraries # written in other languages. -proc raiseFloatInvalidOp {.noinline, noreturn.} = +proc raiseFloatInvalidOp {.noinline.} = sysFatal(FloatInvalidOpError, "FPU operation caused a NaN result") proc nanCheck(x: float64) {.compilerProc, inline.} = if x != x: raiseFloatInvalidOp() -proc raiseFloatOverflow(x: float64) {.noinline, noreturn.} = +proc raiseFloatOverflow(x: float64) {.noinline.} = if x > 0.0: sysFatal(FloatOverflowError, "FPU operation caused an overflow") else: diff --git a/lib/system/chcks.nim b/lib/system/chcks.nim index 2f6d25a12..6caf99d27 100644 --- a/lib/system/chcks.nim +++ b/lib/system/chcks.nim @@ -9,16 +9,16 @@ # Implementation of some runtime checks. -proc raiseRangeError(val: BiggestInt) {.compilerproc, noreturn, noinline.} = +proc raiseRangeError(val: BiggestInt) {.compilerproc, noinline.} = when hostOS == "standalone": sysFatal(RangeError, "value out of range") else: sysFatal(RangeError, "value out of range: ", $val) -proc raiseIndexError() {.compilerproc, noreturn, noinline.} = +proc raiseIndexError() {.compilerproc, noinline.} = sysFatal(IndexError, "index out of bounds") -proc raiseFieldError(f: string) {.compilerproc, noreturn, noinline.} = +proc raiseFieldError(f: string) {.compilerproc, noinline.} = sysFatal(FieldError, f, " is not accessible") proc chckIndx(i, a, b: int): int = diff --git a/tests/manyloc/standalone/panicoverride.nim b/tests/manyloc/standalone/panicoverride.nim index efd2b21f9..d9b3f4388 100644 --- a/tests/manyloc/standalone/panicoverride.nim +++ b/tests/manyloc/standalone/panicoverride.nim @@ -7,13 +7,13 @@ proc exit(code: int) {.importc, header: "", cdecl.} proc rawoutput(s: string) = printf("%s\n", s) -proc panic(s: string) = +proc panic(s: string) {.noreturn.} = rawoutput(s) exit(1) # Alternatively we also could implement these 2 here: # -# template sysFatal(exceptn: typeDesc, message: string) -# template sysFatal(exceptn: typeDesc, message, arg: string) +# proc sysFatal(exceptn: typeDesc, message: string) {.noReturn.} +# proc sysFatal(exceptn: typeDesc, message, arg: string) {.noReturn.} {.pop.} From 78c26cbf18cf1c39964ce32a4991ea4f997a980e Mon Sep 17 00:00:00 2001 From: def Date: Tue, 5 May 2015 20:35:43 +0200 Subject: [PATCH 0193/1263] Distinguish only between __declspec and __attribute__ --- compiler/cgen.nim | 8 ++++---- compiler/extccomp.nim | 12 ++++++------ 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/compiler/cgen.nim b/compiler/cgen.nim index 4743e4576..8e532739b 100644 --- a/compiler/cgen.nim +++ b/compiler/cgen.nim @@ -677,10 +677,10 @@ proc genProcAux(m: BModule, prc: PSym) = genStmts(p, prc.getBody) # modifies p.locals, p.init, etc. var generatedProc: Rope if sfNoReturn in prc.flags: - if hasNoreturnDeclspec in extccomp.CC[extccomp.cCompiler].props: + if {hasNoreturn, hasDeclspec} <= extccomp.CC[extccomp.cCompiler].props: header = "__declspec(noreturn) " & header if sfPure in prc.flags: - if hasNakedDeclspec in extccomp.CC[extccomp.cCompiler].props: + if {hasNaked, hasDeclspec} <= extccomp.CC[extccomp.cCompiler].props: header = "__declspec(naked) " & header generatedProc = rfmt(nil, "$N$1 {$n$2$3$4}$N$N", header, p.s(cpsLocals), p.s(cpsInit), p.s(cpsStmts)) @@ -723,9 +723,9 @@ proc genProcPrototype(m: BModule, sym: PSym) = var header = genProcHeader(m, sym) if sym.typ.callConv != ccInline and crossesCppBoundary(m, sym): header = "extern \"C\" " & header - if sfPure in sym.flags and hasNakedAttribute in CC[cCompiler].props: + if sfPure in sym.flags and {hasNaked, hasAttribute} <= CC[cCompiler].props: header.add(" __attribute__((naked))") - if sfNoReturn in sym.flags and hasNoreturnAttribute in CC[cCompiler].props: + if sfNoReturn in sym.flags and {hasNoreturn, hasAttribute} <= CC[cCompiler].props: header.add(" __attribute__((noreturn))") add(m.s[cfsProcHeaders], rfmt(nil, "$1;$n", header)) diff --git a/compiler/extccomp.nim b/compiler/extccomp.nim index 1bf4eb757..3d4d1a3a5 100644 --- a/compiler/extccomp.nim +++ b/compiler/extccomp.nim @@ -26,10 +26,10 @@ type hasAssume, # CC has __assume (Visual C extension) hasGcGuard, # CC supports GC_GUARD to keep stack roots hasGnuAsm, # CC's asm uses the absurd GNU assembler syntax - hasNakedDeclspec, # CC has __declspec(naked) - hasNakedAttribute, # CC has __attribute__((naked)) - hasNoreturnAttribute, # CC has __attribute__((noreturn)) - hasNoreturnDeclspec # CC has __declspec(noreturn) + hasDeclspec, # CC has __declspec(X) + hasAttribute, # CC has __attribute__((X)) + hasNaked, # CC has naked declspec/attribute + hasNoreturn # CC has noreturn declspec/attribute TInfoCCProps* = set[TInfoCCProp] TInfoCC* = tuple[ name: string, # the short name of the compiler @@ -87,7 +87,7 @@ compiler gcc: structStmtFmt: "$1 $3 $2 ", # struct|union [packed] $name packedPragma: "__attribute__((__packed__))", props: {hasSwitchRange, hasComputedGoto, hasCpp, hasGcGuard, hasGnuAsm, - hasNakedAttribute, hasNoreturnAttribute}) + hasAttribute, hasNaked, hasNoreturn}) # LLVM Frontend for GCC/G++ compiler llvmGcc: @@ -129,7 +129,7 @@ compiler vcc: asmStmtFrmt: "__asm{$n$1$n}$n", structStmtFmt: "$3$n$1 $2", packedPragma: "#pragma pack(1)", - props: {hasCpp, hasAssume, hasNakedDeclspec, hasNoreturnDeclspec}) + props: {hasCpp, hasAssume, hasDeclspec, hasNaked, hasNoreturn}) # Intel C/C++ Compiler compiler icl: From 8e4af5ace0286e0440916d5394f117561b583191 Mon Sep 17 00:00:00 2001 From: Jonathan Date: Tue, 5 May 2015 23:26:58 +0100 Subject: [PATCH 0194/1263] Add contains proc for tables to allow usage of `in` --- lib/pure/collections/tables.nim | 24 ++++++++++++++++++++++++ tests/collections/ttables.nim | 16 +++++++++------- tests/collections/ttablesref.nim | 18 ++++++++++-------- 3 files changed, 43 insertions(+), 15 deletions(-) diff --git a/lib/pure/collections/tables.nim b/lib/pure/collections/tables.nim index a9357ce67..9496fa2fe 100644 --- a/lib/pure/collections/tables.nim +++ b/lib/pure/collections/tables.nim @@ -215,6 +215,10 @@ proc hasKey*[A, B](t: Table[A, B], key: A): bool = var hc: THash result = rawGet(t, key, hc) >= 0 +proc contains*[A, B](t: Table[A, B], key: A): bool = + ## alias of `hasKey` for use with the `in` operator. + return hasKey[A, B](t, key) + proc rawInsert[A, B](t: var Table[A, B], data: var KeyValuePairSeq[A, B], key: A, val: B, hc: THash, h: THash) = rawInsertImpl() @@ -411,6 +415,10 @@ proc hasKey*[A, B](t: TableRef[A, B], key: A): bool = ## returns true iff `key` is in the table `t`. result = t[].hasKey(key) +proc contains*[A, B](t: TableRef[A, B], key: A): bool = + ## alias of `hasKey` for use with the `in` operator. + return hasKey[A, B](t, key) + proc `[]=`*[A, B](t: TableRef[A, B], key: A, val: B) = ## puts a (key, value)-pair into `t`. t[][key] = val @@ -532,6 +540,10 @@ proc hasKey*[A, B](t: OrderedTable[A, B], key: A): bool = var hc: THash result = rawGet(t, key, hc) >= 0 +proc contains*[A, B](t: OrderedTable[A, B], key: A): bool = + ## alias of `hasKey` for use with the `in` operator. + return hasKey[A, B](t, key) + proc rawInsert[A, B](t: var OrderedTable[A, B], data: var OrderedKeyValuePairSeq[A, B], key: A, val: B, hc: THash, h: THash) = @@ -704,6 +716,10 @@ proc hasKey*[A, B](t: OrderedTableRef[A, B], key: A): bool = ## returns true iff `key` is in the table `t`. result = t[].hasKey(key) +proc contains*[A, B](t: OrderedTableRef[A, B], key: A): bool = + ## alias of `hasKey` for use with the `in` operator. + return hasKey[A, B](t, key) + proc `[]=`*[A, B](t: OrderedTableRef[A, B], key: A, val: B) = ## puts a (key, value)-pair into `t`. t[][key] = val @@ -804,6 +820,10 @@ proc hasKey*[A](t: CountTable[A], key: A): bool = ## returns true iff `key` is in the table `t`. result = rawGet(t, key) >= 0 +proc contains*[A](t: CountTable[A], key: A): bool = + ## alias of `hasKey` for use with the `in` operator. + return hasKey[A](t, key) + proc rawInsert[A](t: CountTable[A], data: var seq[tuple[key: A, val: int]], key: A, val: int) = var h: THash = hash(key) and high(data) @@ -945,6 +965,10 @@ proc hasKey*[A](t: CountTableRef[A], key: A): bool = ## returns true iff `key` is in the table `t`. result = t[].hasKey(key) +proc contains*[A](t: CountTableRef[A], key: A): bool = + ## alias of `hasKey` for use with the `in` operator. + return hasKey[A](t, key) + proc `[]=`*[A](t: CountTableRef[A], key: A, val: int) = ## puts a (key, value)-pair into `t`. `val` has to be positive. assert val > 0 diff --git a/tests/collections/ttables.nim b/tests/collections/ttables.nim index 3a923610e..a10606843 100644 --- a/tests/collections/ttables.nim +++ b/tests/collections/ttables.nim @@ -22,15 +22,15 @@ const "---00": 346677844, "0": 34404, "1": 344004, - "10": 34484, + "10": 34484, "11": 34474, "12": 789, "19": 34464, - "2": 344774, "20": 34454, + "2": 344774, "20": 34454, "3": 342244, "30": 34141244, "34": 123456, "4": 3412344, "40": 344114, - "5": 341232144, "50": 344490, + "5": 341232144, "50": 344490, "6": 34214544, "60": 344491, "7": 3434544, "70": 344492, "8": 344544, "80": 344497, @@ -46,7 +46,7 @@ block tableTest1: for x in 0..1: for y in 0..1: assert t[(x,y)] == $x & $y - assert($t == + assert($t == "{(x: 0, y: 1): 01, (x: 0, y: 0): 00, (x: 1, y: 0): 10, (x: 1, y: 1): 11}") block tableTest2: @@ -55,14 +55,16 @@ block tableTest2: t["111"] = 1.000043 t["123"] = 1.23 t.del("111") - + t["012"] = 67.9 t["123"] = 1.5 # test overwriting - + assert t["123"] == 1.5 assert t["111"] == 0.0 # deleted assert(not hasKey(t, "111")) - + assert "123" in t + assert("111" notin t) + for key, val in items(data): t[key] = val.toFloat for key, val in items(data): assert t[key] == val.toFloat diff --git a/tests/collections/ttablesref.nim b/tests/collections/ttablesref.nim index 16b0d831e..0b641ebc7 100644 --- a/tests/collections/ttablesref.nim +++ b/tests/collections/ttablesref.nim @@ -22,15 +22,15 @@ const "---00": 346677844, "0": 34404, "1": 344004, - "10": 34484, + "10": 34484, "11": 34474, "12": 789, "19": 34464, - "2": 344774, "20": 34454, + "2": 344774, "20": 34454, "3": 342244, "30": 34141244, "34": 123456, "4": 3412344, "40": 344114, - "5": 341232144, "50": 344490, + "5": 341232144, "50": 344490, "6": 34214544, "60": 344491, "7": 3434544, "70": 344492, "8": 344544, "80": 344497, @@ -46,7 +46,7 @@ block tableTest1: for x in 0..1: for y in 0..1: assert t[(x,y)] == $x & $y - assert($t == + assert($t == "{(x: 0, y: 1): 01, (x: 0, y: 0): 00, (x: 1, y: 0): 10, (x: 1, y: 1): 11}") block tableTest2: @@ -55,17 +55,19 @@ block tableTest2: t["111"] = 1.000043 t["123"] = 1.23 t.del("111") - + t["012"] = 67.9 t["123"] = 1.5 # test overwriting - + assert t["123"] == 1.5 assert t["111"] == 0.0 # deleted + assert "123" in t assert(not hasKey(t, "111")) - + assert "111" notin t + for key, val in items(data): t[key] = val.toFloat for key, val in items(data): assert t[key] == val.toFloat - + block orderedTableTest1: var t = newOrderedTable[string, int](2) From a0df21edc04f9853ae78788e51b65b3e25a4ba45 Mon Sep 17 00:00:00 2001 From: Araq Date: Wed, 6 May 2015 09:20:50 +0200 Subject: [PATCH 0195/1263] development version is 0.11.3 --- lib/system.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/system.nim b/lib/system.nim index ca4c81411..897faf54c 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -1535,7 +1535,7 @@ const NimMinor*: int = 11 ## is the minor number of Nim's version. - NimPatch*: int = 2 + NimPatch*: int = 3 ## is the patch number of Nim's version. NimVersion*: string = $NimMajor & "." & $NimMinor & "." & $NimPatch From d620f566b23e2a765d2896884ff12b8227d4b306 Mon Sep 17 00:00:00 2001 From: Koala Zen Date: Wed, 6 May 2015 09:09:36 -0700 Subject: [PATCH 0196/1263] Fix comment in re --- lib/impure/re.nim | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/impure/re.nim b/lib/impure/re.nim index fb95610f6..279f8aadd 100644 --- a/lib/impure/re.nim +++ b/lib/impure/re.nim @@ -146,8 +146,8 @@ proc findBounds*(s: string, pattern: Regex, proc findBounds*(s: string, pattern: Regex, start = 0): tuple[first, last: int] = - ## returns the starting position of `pattern` in `s`. If it does not - ## match, ``(-1,0)`` is returned. + ## returns the starting position and end position of ``pattern`` in ``s``. + ## If it does not match, ``(-1,0)`` is returned. var rtarray = initRtArray[cint](3) rawMatches = rtarray.getRawData From cf68d926d89a806e9921ddc69ba813d953d4de11 Mon Sep 17 00:00:00 2001 From: Koala Zen Date: Wed, 6 May 2015 12:37:15 -0700 Subject: [PATCH 0197/1263] fixes isPowerOfTwo returning true on the smallest integer --- lib/pure/math.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/pure/math.nim b/lib/pure/math.nim index daa108460..a5013a3ad 100644 --- a/lib/pure/math.nim +++ b/lib/pure/math.nim @@ -85,7 +85,7 @@ proc fac*(n: int): int {.noSideEffect.} = proc isPowerOfTwo*(x: int): bool {.noSideEffect.} = ## returns true, if `x` is a power of two, false otherwise. ## Zero and negative numbers are not a power of two. - return (x != 0) and ((x and (x - 1)) == 0) + return (x > 0) and ((x and (x - 1)) == 0) proc nextPowerOfTwo*(x: int): int {.noSideEffect.} = ## returns `x` rounded up to the nearest power of two. From 81cff0908e23d5c902f00a86bb19e00de6589cc3 Mon Sep 17 00:00:00 2001 From: def Date: Thu, 7 May 2015 02:29:31 +0200 Subject: [PATCH 0198/1263] Fix the lib path used with --app:staticlib For example if gProjectName is "src/false.nim" the old static lib name was "libsrc/false.nim.a", now it is "libfalse.a". --- compiler/extccomp.nim | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/compiler/extccomp.nim b/compiler/extccomp.nim index 26f0318ee..7d777b0e3 100644 --- a/compiler/extccomp.nim +++ b/compiler/extccomp.nim @@ -668,7 +668,8 @@ proc callCCompiler*(projectfile: string) = it = PStrEntry(it.next) if optGenStaticLib in gGlobalOptions: - linkCmd = CC[c].buildLib % ["libfile", (libNameTmpl() % gProjectName), + let (_, name, _) = splitFile(gProjectName) + linkCmd = CC[c].buildLib % ["libfile", (libNameTmpl() % name), "objfiles", objfiles] else: var linkerExe = getConfigVar(c, ".linkerexe") From 2a08bbdf31ce693ec0741ecbc9ae78a4d7b9a051 Mon Sep 17 00:00:00 2001 From: Reimer Behrends Date: Thu, 7 May 2015 14:35:39 +0200 Subject: [PATCH 0199/1263] Fix GC scanning of registers on x86_64 architectures. It is possible for jmp_buf to not be word-aligned or addresses in the register dump to not be word-aligned. This can result in either addresses in registers being missed or even addresses on the stack past the register area not being scanned properly. --- lib/system/gc.nim | 9 +++++++++ lib/system/gc_ms.nim | 9 +++++++++ 2 files changed, 18 insertions(+) diff --git a/lib/system/gc.nim b/lib/system/gc.nim index c4374d00c..e0d1006d9 100644 --- a/lib/system/gc.nim +++ b/lib/system/gc.nim @@ -922,6 +922,15 @@ else: if c_setjmp(registers) == 0'i32: # To fill the C stack with registers. var max = cast[ByteAddress](gch.stackBottom) var sp = cast[ByteAddress](addr(registers)) + when defined(amd64): + # words within the jmp_buf structure may not be properly aligned. + let regEnd = sp +% sizeof(registers) + while sp <% regEnd: + gcMark(gch, cast[PPointer](sp)[]) + gcMark(gch, cast[PPointer](sp +% sizeof(pointer) div 2)[]) + sp = sp +% sizeof(pointer) + # Make sure sp is word-aligned + sp = sp and not (sizeof(pointer) - 1) # loop unrolled: while sp <% max - 8*sizeof(pointer): gcMark(gch, cast[PStackSlice](sp)[0]) diff --git a/lib/system/gc_ms.nim b/lib/system/gc_ms.nim index e287bf5d9..a0699f46a 100644 --- a/lib/system/gc_ms.nim +++ b/lib/system/gc_ms.nim @@ -514,6 +514,15 @@ else: if c_setjmp(registers) == 0'i32: # To fill the C stack with registers. var max = cast[ByteAddress](gch.stackBottom) var sp = cast[ByteAddress](addr(registers)) + when defined(amd64): + # words within the jmp_buf structure may not be properly aligned. + let regEnd = sp +% sizeof(registers) + while sp <% regEnd: + gcMark(gch, cast[PPointer](sp)[]) + gcMark(gch, cast[PPointer](sp +% sizeof(pointer) div 2)[]) + sp = sp +% sizeof(pointer) + # Make sure sp is word-aligned + sp = sp and not (sizeof(pointer) - 1) # loop unrolled: while sp <% max - 8*sizeof(pointer): gcMark(gch, cast[PStackSlice](sp)[0]) From a7b39e3ebf4e46f946176f3da1b11c4f52345b6f Mon Sep 17 00:00:00 2001 From: def Date: Thu, 7 May 2015 20:35:16 +0200 Subject: [PATCH 0200/1263] Improve code style a bit --- compiler/extccomp.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/extccomp.nim b/compiler/extccomp.nim index 7d777b0e3..75cb1ef27 100644 --- a/compiler/extccomp.nim +++ b/compiler/extccomp.nim @@ -668,7 +668,7 @@ proc callCCompiler*(projectfile: string) = it = PStrEntry(it.next) if optGenStaticLib in gGlobalOptions: - let (_, name, _) = splitFile(gProjectName) + let name = splitFile(gProjectName).name linkCmd = CC[c].buildLib % ["libfile", (libNameTmpl() % name), "objfiles", objfiles] else: From 4a2a0894aee91fac027f9d0cce401bf5c9dc353b Mon Sep 17 00:00:00 2001 From: def Date: Thu, 7 May 2015 22:31:45 +0200 Subject: [PATCH 0201/1263] Implicitly assume compilers to know naked and noreturn attributes --- compiler/cgen.nim | 8 ++++---- compiler/extccomp.nim | 6 ++---- 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/compiler/cgen.nim b/compiler/cgen.nim index 8e532739b..4b0bac28a 100644 --- a/compiler/cgen.nim +++ b/compiler/cgen.nim @@ -677,10 +677,10 @@ proc genProcAux(m: BModule, prc: PSym) = genStmts(p, prc.getBody) # modifies p.locals, p.init, etc. var generatedProc: Rope if sfNoReturn in prc.flags: - if {hasNoreturn, hasDeclspec} <= extccomp.CC[extccomp.cCompiler].props: + if hasDeclspec in extccomp.CC[extccomp.cCompiler].props: header = "__declspec(noreturn) " & header if sfPure in prc.flags: - if {hasNaked, hasDeclspec} <= extccomp.CC[extccomp.cCompiler].props: + if hasDeclspec in extccomp.CC[extccomp.cCompiler].props: header = "__declspec(naked) " & header generatedProc = rfmt(nil, "$N$1 {$n$2$3$4}$N$N", header, p.s(cpsLocals), p.s(cpsInit), p.s(cpsStmts)) @@ -723,9 +723,9 @@ proc genProcPrototype(m: BModule, sym: PSym) = var header = genProcHeader(m, sym) if sym.typ.callConv != ccInline and crossesCppBoundary(m, sym): header = "extern \"C\" " & header - if sfPure in sym.flags and {hasNaked, hasAttribute} <= CC[cCompiler].props: + if sfPure in sym.flags and hasAttribute in CC[cCompiler].props: header.add(" __attribute__((naked))") - if sfNoReturn in sym.flags and {hasNoreturn, hasAttribute} <= CC[cCompiler].props: + if sfNoReturn in sym.flags and hasAttribute in CC[cCompiler].props: header.add(" __attribute__((noreturn))") add(m.s[cfsProcHeaders], rfmt(nil, "$1;$n", header)) diff --git a/compiler/extccomp.nim b/compiler/extccomp.nim index 3d4d1a3a5..31b03f418 100644 --- a/compiler/extccomp.nim +++ b/compiler/extccomp.nim @@ -28,8 +28,6 @@ type hasGnuAsm, # CC's asm uses the absurd GNU assembler syntax hasDeclspec, # CC has __declspec(X) hasAttribute, # CC has __attribute__((X)) - hasNaked, # CC has naked declspec/attribute - hasNoreturn # CC has noreturn declspec/attribute TInfoCCProps* = set[TInfoCCProp] TInfoCC* = tuple[ name: string, # the short name of the compiler @@ -87,7 +85,7 @@ compiler gcc: structStmtFmt: "$1 $3 $2 ", # struct|union [packed] $name packedPragma: "__attribute__((__packed__))", props: {hasSwitchRange, hasComputedGoto, hasCpp, hasGcGuard, hasGnuAsm, - hasAttribute, hasNaked, hasNoreturn}) + hasAttribute}) # LLVM Frontend for GCC/G++ compiler llvmGcc: @@ -129,7 +127,7 @@ compiler vcc: asmStmtFrmt: "__asm{$n$1$n}$n", structStmtFmt: "$3$n$1 $2", packedPragma: "#pragma pack(1)", - props: {hasCpp, hasAssume, hasDeclspec, hasNaked, hasNoreturn}) + props: {hasCpp, hasAssume, hasDeclspec}) # Intel C/C++ Compiler compiler icl: From 7e479993a427cd72947ce06b318226ba0269e5f9 Mon Sep 17 00:00:00 2001 From: Adam Strzelecki Date: Thu, 7 May 2015 23:07:15 +0200 Subject: [PATCH 0202/1263] Fixup: csources is empty after clone We actually need to check for existence of csources/.git and then do git submodule update --init, which pulls the data for submodule. --- build.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.sh b/build.sh index 87e12dcfd..91e169241 100755 --- a/build.sh +++ b/build.sh @@ -2,7 +2,7 @@ set -e set -x -if [ ! -d "csources" ]; then +if [ ! -e csources/.git ]; then git submodule update --init --depth 1 fi From c384f05e49e0716cc99042491f65bcc7d415d4c3 Mon Sep 17 00:00:00 2001 From: Michael Werner Date: Thu, 7 May 2015 22:39:15 +0200 Subject: [PATCH 0203/1263] fixed typo in threadpool.nim --- lib/pure/concurrency/threadpool.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/pure/concurrency/threadpool.nim b/lib/pure/concurrency/threadpool.nim index 9f1e53fb8..a431691ad 100644 --- a/lib/pure/concurrency/threadpool.nim +++ b/lib/pure/concurrency/threadpool.nim @@ -300,7 +300,7 @@ proc setMinPoolSize*(size: range[1..MaxThreadPoolSize]) = minPoolSize = size proc setMaxPoolSize*(size: range[1..MaxThreadPoolSize]) = - ## sets the minimal thread pool size. The default value of this + ## sets the maximal thread pool size. The default value of this ## is ``MaxThreadPoolSize``. maxPoolSize = size if currentPoolSize > maxPoolSize: From 2474c1bb111b38ddef64659c893722b357a27384 Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Fri, 8 May 2015 04:45:48 +0500 Subject: [PATCH 0204/1263] import sigmatch, not suggest in nimsuggest --- compiler/nimsuggest/nimsuggest.nim | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/compiler/nimsuggest/nimsuggest.nim b/compiler/nimsuggest/nimsuggest.nim index 3f8943016..7ba3379c3 100644 --- a/compiler/nimsuggest/nimsuggest.nim +++ b/compiler/nimsuggest/nimsuggest.nim @@ -10,8 +10,11 @@ ## Nimsuggest is a tool that helps to give editors IDE like capabilities. import strutils, os, parseopt, parseutils, sequtils, net +# Do NOT import suggest. It will lead to wierd bugs with +# suggestionResultHook, because suggest.nim is included by sigmatch. +# So we import that one instead. import options, commands, modules, sem, passes, passaux, msgs, nimconf, - extccomp, condsyms, lists, net, rdstdin, sexp, suggest, ast + extccomp, condsyms, lists, net, rdstdin, sexp, sigmatch, ast when defined(windows): import winlean @@ -116,7 +119,6 @@ proc execute(cmd: IdeCmd, file, dirtyfile: string, line, col: int) = resetModule gProjectMainIdx gTrackPos = newLineInfo(dirtyIdx, line, col) - #echo dirtyfile, gDirtyBufferIdx, " project ", gProjectMainIdx gErrorCounter = 0 if not isKnownFile: compileProject(dirtyIdx) @@ -245,7 +247,7 @@ proc serve() = case messageType: of "call": var results: seq[Suggest] = @[] - suggest.suggestionResultHook = proc (s: Suggest) = + suggestionResultHook = proc (s: Suggest) = results.add(s) let From fef21e90031557bc00af80e3d2da98b28780ee2b Mon Sep 17 00:00:00 2001 From: def Date: Fri, 8 May 2015 03:58:44 +0200 Subject: [PATCH 0205/1263] Use -d:builtinOverflow for builtin overflow checks of recent Clang and GCC >= 5.0. Maybe it's better that it's optional after all. GCC's code with builtin overflow checks seems to be a bit slower actually, while Clang's is 3 times faster. --- lib/system/arithm.nim | 273 +++++++++++++++++++----------------------- 1 file changed, 121 insertions(+), 152 deletions(-) diff --git a/lib/system/arithm.nim b/lib/system/arithm.nim index e41372bc6..5455f0981 100644 --- a/lib/system/arithm.nim +++ b/lib/system/arithm.nim @@ -8,75 +8,6 @@ # -# Only clang has __has_builtin (so far) -# -# TODO: This is emitted at the wrong position so we don't actually have an -# emit. Could we add this to nimbase.h instead? -{.emit: """#ifndef __has_builtin - #define __has_builtin(x) 0 -#endif""".} - -# Builtin compiler functions for improved performance - -proc checkFunction(name: string): string = - "((__has_builtin(__builtin_" & name & "_overflow)) || __GNUC__ >= 5)" - -# TODO: This is totally ugly. But we can't reliably detect this from Nim, -# especially with cross-compiling where the user may be using an older compiler -# version. Switching this on/off manually with a define seems weird as well. -when sizeof(clong) == 8: - const hasAddInt64Overflow = checkFunction("saddl") - proc addInt64Overflow[T: int64|int](a, b: T, c: var T): bool {. - importc: "__builtin_saddl_overflow", nodecl, nosideeffect.} - - const hasSubInt64Overflow = checkFunction("ssubl") - proc subInt64Overflow[T: int64|int](a, b: T, c: var T): bool {. - importc: "__builtin_ssubl_overflow", nodecl, nosideeffect.} - - const hasMulInt64Overflow = checkFunction("smull") - proc mulInt64Overflow[T: int64|int](a, b: T, c: var T): bool {. - importc: "__builtin_smull_overflow", nodecl, nosideeffect.} - -elif sizeof(clonglong) == 8: - const hasAddInt64Overflow = checkFunction("saddll") - proc addInt64Overflow[T: int64|int](a, b: T, c: var T): bool {. - importc: "__builtin_saddll_overflow", nodecl, nosideeffect.} - - const hasSubInt64Overflow = checkFunction("ssubll") - proc subInt64Overflow[T: int64|int](a, b: T, c: var T): bool {. - importc: "__builtin_ssubll_overflow", nodecl, nosideeffect.} - - const hasMulInt64Overflow = checkFunction("smulll") - proc mulInt64Overflow[T: int64|int](a, b: T, c: var T): bool {. - importc: "__builtin_smulll_overflow", nodecl, nosideeffect.} - -when sizeof(int) == 8: - const hasAddIntOverflow = hasAddInt64Overflow - proc addIntOverflow(a, b: int, c: var int): bool {.inline.} = - addInt64Overflow(a, b, c) - - const hasSubIntOverflow = hasSubInt64Overflow - proc subIntOverflow(a, b: int, c: var int): bool {.inline.} = - subInt64Overflow(a, b, c) - - const hasMulIntOverflow = hasMulInt64Overflow - proc mulIntOverflow(a, b: int, c: var int): bool {.inline.} = - mulInt64Overflow(a, b, c) - -elif sizeof(int) == 4 and sizeof(cint) == 4: - const hasAddIntOverflow = checkFunction("sadd") - proc addIntOverflow(a, b: int, c: var int): bool {. - importc: "__builtin_sadd_overflow", nodecl, nosideeffect.} - - const hasSubIntOverflow = checkFunction("ssub") - proc subIntOverflow(a, b: int, c: var int): bool {. - importc: "__builtin_ssub_overflow", nodecl, nosideeffect.} - - const hasMulIntOverflow = checkFunction("smul") - proc mulIntOverflow(a, b: int, c: var int): bool {. - importc: "__builtin_smul_overflow", nodecl, nosideeffect.} - - # simple integer arithmetic with overflow checking proc raiseOverflow {.compilerproc, noinline, noreturn.} = @@ -86,27 +17,114 @@ proc raiseOverflow {.compilerproc, noinline, noreturn.} = proc raiseDivByZero {.compilerproc, noinline, noreturn.} = sysFatal(DivByZeroError, "division by zero") -proc addInt64(a, b: int64): int64 {.compilerProc, inline.} = - {.emit: "#if `hasAddInt64Overflow`".} - if addInt64Overflow(a, b, result): - raiseOverflow() - {.emit: "#else".} - result = a +% b - if (result xor a) >= int64(0) or (result xor b) >= int64(0): - return result - raiseOverflow() - {.emit: "#endif".} +when defined(builtinOverflow): +# Builtin compiler functions for improved performance + when sizeof(clong) == 8: + proc addInt64Overflow[T: int64|int](a, b: T, c: var T): bool {. + importc: "__builtin_saddl_overflow", nodecl, nosideeffect.} -proc subInt64(a, b: int64): int64 {.compilerProc, inline.} = - {.emit: "#if `hasSubInt64Overflow`".} - if subInt64Overflow(a, b, result): + proc subInt64Overflow[T: int64|int](a, b: T, c: var T): bool {. + importc: "__builtin_ssubl_overflow", nodecl, nosideeffect.} + + proc mulInt64Overflow[T: int64|int](a, b: T, c: var T): bool {. + importc: "__builtin_smull_overflow", nodecl, nosideeffect.} + + elif sizeof(clonglong) == 8: + proc addInt64Overflow[T: int64|int](a, b: T, c: var T): bool {. + importc: "__builtin_saddll_overflow", nodecl, nosideeffect.} + + proc subInt64Overflow[T: int64|int](a, b: T, c: var T): bool {. + importc: "__builtin_ssubll_overflow", nodecl, nosideeffect.} + + proc mulInt64Overflow[T: int64|int](a, b: T, c: var T): bool {. + importc: "__builtin_smulll_overflow", nodecl, nosideeffect.} + + when sizeof(int) == 8: + proc addIntOverflow(a, b: int, c: var int): bool {.inline.} = + addInt64Overflow(a, b, c) + + proc subIntOverflow(a, b: int, c: var int): bool {.inline.} = + subInt64Overflow(a, b, c) + + proc mulIntOverflow(a, b: int, c: var int): bool {.inline.} = + mulInt64Overflow(a, b, c) + + elif sizeof(int) == 4 and sizeof(cint) == 4: + proc addIntOverflow(a, b: int, c: var int): bool {. + importc: "__builtin_sadd_overflow", nodecl, nosideeffect.} + + proc subIntOverflow(a, b: int, c: var int): bool {. + importc: "__builtin_ssub_overflow", nodecl, nosideeffect.} + + proc mulIntOverflow(a, b: int, c: var int): bool {. + importc: "__builtin_smul_overflow", nodecl, nosideeffect.} + + proc addInt64(a, b: int64): int64 {.compilerProc, inline.} = + if addInt64Overflow(a, b, result): + raiseOverflow() + + proc subInt64(a, b: int64): int64 {.compilerProc, inline.} = + if subInt64Overflow(a, b, result): + raiseOverflow() + + proc mulInt64(a, b: int64): int64 {.compilerproc, inline.} = + if mulInt64Overflow(a, b, result): + raiseOverflow() +else: + proc addInt64(a, b: int64): int64 {.compilerProc, inline.} = + result = a +% b + if (result xor a) >= int64(0) or (result xor b) >= int64(0): + return result + raiseOverflow() + + proc subInt64(a, b: int64): int64 {.compilerProc, inline.} = + result = a -% b + if (result xor a) >= int64(0) or (result xor not b) >= int64(0): + return result + raiseOverflow() + + # + # This code has been inspired by Python's source code. + # The native int product x*y is either exactly right or *way* off, being + # just the last n bits of the true product, where n is the number of bits + # in an int (the delivered product is the true product plus i*2**n for + # some integer i). + # + # The native float64 product x*y is subject to three + # rounding errors: on a sizeof(int)==8 box, each cast to double can lose + # info, and even on a sizeof(int)==4 box, the multiplication can lose info. + # But, unlike the native int product, it's not in *range* trouble: even + # if sizeof(int)==32 (256-bit ints), the product easily fits in the + # dynamic range of a float64. So the leading 50 (or so) bits of the float64 + # product are correct. + # + # We check these two ways against each other, and declare victory if they're + # approximately the same. Else, because the native int product is the only + # one that can lose catastrophic amounts of information, it's the native int + # product that must have overflowed. + # + proc mulInt64(a, b: int64): int64 {.compilerproc.} = + var + resAsFloat, floatProd: float64 + result = a *% b + floatProd = toBiggestFloat(a) # conversion + floatProd = floatProd * toBiggestFloat(b) + resAsFloat = toBiggestFloat(result) + + # Fast path for normal case: small multiplicands, and no info + # is lost in either method. + if resAsFloat == floatProd: return result + + # Somebody somewhere lost info. Close enough, or way off? Note + # that a != 0 and b != 0 (else resAsFloat == floatProd == 0). + # The difference either is or isn't significant compared to the + # true value (of which floatProd is a good approximation). + + # abs(diff)/abs(prod) <= 1/32 iff + # 32 * abs(diff) <= abs(prod) -- 5 good bits is "close enough" + if 32.0 * abs(resAsFloat - floatProd) <= abs(floatProd): + return result raiseOverflow() - {.emit: "#else".} - result = a -% b - if (result xor a) >= int64(0) or (result xor not b) >= int64(0): - return result - raiseOverflow() - {.emit: "#endif".} proc negInt64(a: int64): int64 {.compilerProc, inline.} = if a != low(int64): return -a @@ -130,55 +148,6 @@ proc modInt64(a, b: int64): int64 {.compilerProc, inline.} = raiseDivByZero() return a mod b -# -# This code has been inspired by Python's source code. -# The native int product x*y is either exactly right or *way* off, being -# just the last n bits of the true product, where n is the number of bits -# in an int (the delivered product is the true product plus i*2**n for -# some integer i). -# -# The native float64 product x*y is subject to three -# rounding errors: on a sizeof(int)==8 box, each cast to double can lose -# info, and even on a sizeof(int)==4 box, the multiplication can lose info. -# But, unlike the native int product, it's not in *range* trouble: even -# if sizeof(int)==32 (256-bit ints), the product easily fits in the -# dynamic range of a float64. So the leading 50 (or so) bits of the float64 -# product are correct. -# -# We check these two ways against each other, and declare victory if they're -# approximately the same. Else, because the native int product is the only -# one that can lose catastrophic amounts of information, it's the native int -# product that must have overflowed. -# -proc mulInt64(a, b: int64): int64 {.compilerproc.} = - {.emit: "#if `hasMulInt64Overflow`".} - if mulInt64Overflow(a, b, result): - raiseOverflow() - {.emit: "#else".} - var - resAsFloat, floatProd: float64 - result = a *% b - floatProd = toBiggestFloat(a) # conversion - floatProd = floatProd * toBiggestFloat(b) - resAsFloat = toBiggestFloat(result) - - # Fast path for normal case: small multiplicands, and no info - # is lost in either method. - if resAsFloat == floatProd: return result - - # Somebody somewhere lost info. Close enough, or way off? Note - # that a != 0 and b != 0 (else resAsFloat == floatProd == 0). - # The difference either is or isn't significant compared to the - # true value (of which floatProd is a good approximation). - - # abs(diff)/abs(prod) <= 1/32 iff - # 32 * abs(diff) <= abs(prod) -- 5 good bits is "close enough" - if 32.0 * abs(resAsFloat - floatProd) <= abs(floatProd): - return result - raiseOverflow() - {.emit: "#endif".} - - proc absInt(a: int): int {.compilerProc, inline.} = if a != low(int): if a >= 0: return a @@ -330,30 +299,35 @@ elif false: # asmVersion and (defined(gcc) or defined(llvm_gcc)): :"%edx" """ +when not declared(addInt) and defined(builtinOverflow): + proc addInt(a, b: int): int {.compilerProc, inline.} = + if addIntOverflow(a, b, result): + raiseOverflow() + +when not declared(subInt) and defined(builtinOverflow): + proc subInt(a, b: int): int {.compilerProc, inline.} = + if subIntOverflow(a, b, result): + raiseOverflow() + +when not declared(mulInt) and defined(builtinOverflow): + proc mulInt(a, b: int): int {.compilerProc, inline.} = + if mulIntOverflow(a, b, result): + raiseOverflow() + # Platform independent versions of the above (slower!) when not declared(addInt): proc addInt(a, b: int): int {.compilerProc, inline.} = - {.emit: "#if `hasAddIntOverflow`".} - if addIntOverflow(a, b, result): - raiseOverflow() - {.emit: "#else".} result = a +% b if (result xor a) >= 0 or (result xor b) >= 0: return result raiseOverflow() - {.emit: "#endif".} when not declared(subInt): proc subInt(a, b: int): int {.compilerProc, inline.} = - {.emit: "#if `hasSubIntOverflow`".} - if subIntOverflow(a, b, result): - raiseOverflow() - {.emit: "#else".} result = a -% b if (result xor a) >= 0 or (result xor not b) >= 0: return result raiseOverflow() - {.emit: "#endif".} when not declared(negInt): proc negInt(a: int): int {.compilerProc, inline.} = @@ -396,10 +370,6 @@ when not declared(mulInt): # native int product that must have overflowed. # proc mulInt(a, b: int): int {.compilerProc.} = - {.emit: "#if `hasMulIntOverflow`".} - if mulIntOverflow(a, b, result): - raiseOverflow() - {.emit: "#else".} var resAsFloat, floatProd: float @@ -421,7 +391,6 @@ when not declared(mulInt): if 32.0 * abs(resAsFloat - floatProd) <= abs(floatProd): return result raiseOverflow() - {.emit: "#endif".} # We avoid setting the FPU control word here for compatibility with libraries # written in other languages. From c06672451ad34e1baf727dc4de68a0fa0566dae3 Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Fri, 8 May 2015 19:47:17 +0500 Subject: [PATCH 0206/1263] removed unnecessary deps --- compiler/suggest.nim | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/compiler/suggest.nim b/compiler/suggest.nim index f1628db94..a79d08f71 100644 --- a/compiler/suggest.nim +++ b/compiler/suggest.nim @@ -11,8 +11,7 @@ # included from sigmatch.nim -import algorithm, sequtils, strutils, ast, msgs, options, renderer, - types, docgen, lexer, semdata, astalgo, idents, sigmatch, lookups +import algorithm, sequtils const sep = '\t' From 13e8547fa7825aef0c8a07c67dcad78921c5a820 Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Fri, 8 May 2015 19:47:34 +0500 Subject: [PATCH 0207/1263] hardcoded order --- compiler/nimsuggest/nimsuggest.nim | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/compiler/nimsuggest/nimsuggest.nim b/compiler/nimsuggest/nimsuggest.nim index 7ba3379c3..ad3b5bf0d 100644 --- a/compiler/nimsuggest/nimsuggest.nim +++ b/compiler/nimsuggest/nimsuggest.nim @@ -65,15 +65,13 @@ proc parseQuoted(cmd: string; outp: var string; start: int): int = i += parseUntil(cmd, outp, seps, i) result = i -# make sure it's in the same order as the proc below -let order: SexpNode = - sexp(@["section", "symkind", "qualifiedPath", "filePath", "forth", "line", "column", "doc"].map(newSSymbol)) - proc sexp(s: IdeCmd): SexpNode = sexp($s) proc sexp(s: TSymKind): SexpNode = sexp($s) proc sexp(s: Suggest): SexpNode = + # If you change the oder here, make sure to change it over in + # nim-mode.el too. result = convertSexp([ s.section, s.symkind, From f8af8df91c7e722b8c5034c1fe0255e3ca6b8558 Mon Sep 17 00:00:00 2001 From: def Date: Sun, 10 May 2015 22:20:03 +0200 Subject: [PATCH 0208/1263] Add -ldl with clang cpp compilation This fixes compilation with --cc:clang and cpp. --- config/nim.cfg | 1 + 1 file changed, 1 insertion(+) diff --git a/config/nim.cfg b/config/nim.cfg index fef7df79e..0c3ffef4e 100644 --- a/config/nim.cfg +++ b/config/nim.cfg @@ -78,6 +78,7 @@ path="$lib/pure/unidecode" gcc.options.linker = "-ldl" gcc.cpp.options.linker = "-ldl" clang.options.linker = "-ldl" + clang.cpp.options.linker = "-ldl" tcc.options.linker = "-ldl" @end @if bsd or haiku: From a75cfc98871b07e7670f7dc0bec45012ccbffdf6 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Mon, 11 May 2015 15:45:57 -0400 Subject: [PATCH 0209/1263] Reweave readme Also fix some syntax errors in the RST --- README.rst | 98 ++++++++++++++++++++++++++++++----------------------- src/nre.nim | 3 +- 2 files changed, 57 insertions(+), 44 deletions(-) diff --git a/README.rst b/README.rst index 7bf58f866..c767038db 100644 --- a/README.rst +++ b/README.rst @@ -30,21 +30,14 @@ By default, NRE compiles it’s own PCRE. If this is undesirable, pass ``-d:pcreDynlib`` to use whatever dynamic library is available on the system. This may have unexpected consequences if the dynamic library doesn’t have certain features enabled. - Types ----- ``type Regex* = ref object`` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Represents the pattern that things are matched against, constructed with -``re(string, string)``. Examples: ``re"foo"``, ``re(r"foo # comment", -"x")``, ``re"(?x)(*ANYCRLF)foo # comment"``. For more details -on the leading option groups, see the `Option -Setting `__ -and the `Newline -Convention `__ -sections of the `PCRE syntax -manual `__. +``re(string)``. Examples: ``re"foo"``, ``re(r"(*ANYCRLF)(?x)foo # +comment".`` ``pattern: string`` the string that was used to create the pattern. @@ -56,34 +49,36 @@ manual `__. a table from the capture names to their numeric id. -Flags -..... +Options +....... -- ``8`` - treat both the pattern and subject as UTF8 -- ``9`` - prevents the pattern from being interpreted as UTF, no matter - what -- ``A`` - as if the pattern had a ``^`` at the beginning -- ``E`` - DOLLAR\_ENDONLY -- ``f`` - fails if there is not a match on the first line -- ``i`` - case insensitive -- ``m`` - multi-line, ``^`` and ``$`` match the beginning and end of +The following options may appear anywhere in the pattern, and they affect +the rest of it. + +- ``(?i)`` - case insensitive +- ``(?m)`` - multi-line: ``^`` and ``$`` match the beginning and end of lines, not of the subject string -- ``N`` - turn off auto-capture, ``(?foo)`` is necessary to capture. -- ``s`` - ``.`` matches newline -- ``U`` - expressions are not greedy by default. ``?`` can be added to - a qualifier to make it greedy. -- ``u`` - same as ``8`` -- ``W`` - Unicode character properties; ``\w`` matches ``к``. -- ``X`` - "Extra", character escapes without special meaning (``\w`` - vs. ``\a``) are errors -- ``x`` - extended, comments (``#``) and newlines are ignored - (extended) -- ``Y`` - pcre.NO\_START\_OPTIMIZE, -- ```` - newlines are separated by ``\r`` -- ```` - newlines are separated by ``\r\n`` (Windows default) -- ```` - newlines are separated by ``\n`` (UNIX default) -- ```` - newlines are separated by any of the above -- ```` - newlines are separated by any of the above and Unicode +- ``(?s)`` - ``.`` also matches newline (*dotall*) +- ``(?U)`` - expressions are not greedy by default. ``?`` can be added + to a qualifier to make it greedy +- ``(?x)`` - whitespace and comments (``#``) are ignored (*extended*) +- ``(?X)`` - character escapes without special meaning (``\w`` vs. + ``\a``) are errors (*extra*) + +One or a combination of these options may appear only at the beginning +of the pattern: + +- ``(*UTF8)`` - treat both the pattern and subject as UTF-8 +- ``(*UCP)`` - Unicode character properties; ``\w`` matches ``я`` +- ``(*U)`` - a combination of the two options above +- ``(*FIRSTLINE*)`` - fails if there is not a match on the first line +- ``(*NO_AUTO_CAPTURE)`` - turn off auto-capture for groups; + ``(?...)`` can be used to capture +- ``(*CR)`` - newlines are separated by ``\r`` +- ``(*LF)`` - newlines are separated by ``\n`` (UNIX default) +- ``(*CRLF)`` - newlines are separated by ``\r\n`` (Windows default) +- ``(*ANYCRLF)`` - newlines are separated by any of the above +- ``(*ANY)`` - newlines are separated by any of the above and Unicode newlines: single characters VT (vertical tab, U+000B), FF (form feed, U+000C), @@ -92,10 +87,15 @@ Flags are recognized only in UTF-8 mode. — man pcre -- ```` - ``\R`` matches CR, LF, or CRLF -- ```` - ``\R`` matches any unicode newline -- ```` - Javascript compatibility -- ```` - turn off studying; study is enabled by deafault +- ``(*JAVASCRIPT_COMPAT)`` - JavaScript compatibility +- ``(*NO_STUDY)`` - turn off studying; study is enabled by default + +For more details on the leading option groups, see the `Option +Setting `__ +and the `Newline +Convention `__ +sections of the `PCRE syntax +manual `__. ``type RegexMatch* = object`` @@ -146,14 +146,24 @@ fields are as follows: same as ``match`` -``type SyntaxError* = ref object of Exception`` -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +``type RegexInternalError* = ref object of RegexException`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Internal error in the module, this probably means that there is a bug + + +``type InvalidUnicodeError* = ref object of RegexException`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Thrown when matching fails due to invalid unicode in strings + + +``type SyntaxError* = ref object of RegexException`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Thrown when there is a syntax error in the regular expression string passed in -``type StudyError* = ref object of Exception`` -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +``type StudyError* = ref object of RegexException`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Thrown when studying the regular expression failes for whatever reason. The message contains the error code. @@ -244,3 +254,5 @@ If a given capture is missing, a ``ValueError`` exception is thrown. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Escapes the string so it doesn’t match any special characters. Incompatible with the Extra flag (``X``). + + diff --git a/src/nre.nim b/src/nre.nim index 0585e49b2..f96820b2c 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -47,7 +47,8 @@ from unicode import runeLenAt type Regex* = ref object ## Represents the pattern that things are matched against, constructed with - ## ``re(string)``. Examples: ``re"foo"``, ``re(r"(*ANYCRLF)(?x)foo # comment". + ## ``re(string)``. Examples: ``re"foo"``, ``re(r"(*ANYCRLF)(?x)foo # + ## comment".`` ## ## ``pattern: string`` ## the string that was used to create the pattern. From 749e808e1e76204e7fdbe6649fe20b93ccda7b3e Mon Sep 17 00:00:00 2001 From: Frank Fischer Date: Mon, 11 May 2015 23:29:51 +0200 Subject: [PATCH 0210/1263] logging: make fmtStr public to be used in user defined loggers --- lib/pure/logging.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/pure/logging.nim b/lib/pure/logging.nim index a2ea53472..cc5340211 100644 --- a/lib/pure/logging.nim +++ b/lib/pure/logging.nim @@ -66,7 +66,7 @@ type Logger* = ref object of RootObj ## abstract logger; the base type of all loggers levelThreshold*: Level ## only messages of level >= levelThreshold ## should be processed - fmtStr: string ## = defaultFmtStr by default, see substituteLog for $date etc. + fmtStr*: string ## = defaultFmtStr by default, see substituteLog for $date etc. ConsoleLogger* = ref object of Logger ## logger that writes the messages to the ## console From 373717968eeb851e30a300923aa62e4c2aec519d Mon Sep 17 00:00:00 2001 From: krolik Date: Tue, 12 May 2015 12:45:34 +0300 Subject: [PATCH 0211/1263] new now able to make distinction between ref and non-ref types, so we don't get 'ref ref' type when calling new on ref type --- lib/system.nim | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/lib/system.nim b/lib/system.nim index 1e6f76f3d..a56e91594 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -172,10 +172,16 @@ proc new*[T](a: var ref T) {.magic: "New", noSideEffect.} ## creates a new object of type ``T`` and returns a safe (traced) ## reference to it in ``a``. -proc new*(T: typedesc): ref T = +proc new*(T: typedesc): auto = ## creates a new object of type ``T`` and returns a safe (traced) ## reference to it as result value - new(result) + when (T is ref): + var r: T + else: + var r: ref T + new(r) + return r + proc internalNew*[T](a: var ref T) {.magic: "New", noSideEffect.} ## leaked implementation detail. Do not use. From f9be37e7cb9d919ba423fde5d05aa87962da0259 Mon Sep 17 00:00:00 2001 From: Araq Date: Tue, 12 May 2015 14:45:50 +0200 Subject: [PATCH 0212/1263] prepare for unidecode Nimble package --- doc/lib.txt | 5 ----- 1 file changed, 5 deletions(-) diff --git a/doc/lib.txt b/doc/lib.txt index 1c0278068..15e99ca05 100644 --- a/doc/lib.txt +++ b/doc/lib.txt @@ -123,11 +123,6 @@ String handling Ropes can represent very long strings efficiently; especially concatenation is done in O(1) instead of O(n). -* `unidecode `_ - This module provides Unicode to ASCII transliterations: - It finds the sequence of ASCII characters that is the closest approximation - to the Unicode string. - * `matchers `_ This module contains various string matchers for email addresses, etc. From 3a3a7d012f35b4c40ec212748e58caa7bdc3b0d6 Mon Sep 17 00:00:00 2001 From: Boris Vassilev Date: Tue, 12 May 2015 15:52:38 +0300 Subject: [PATCH 0213/1263] Fill array with same values (was issue #2462) --- lib/pure/algorithm.nim | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/lib/pure/algorithm.nim b/lib/pure/algorithm.nim index f7ccb9234..20920bd44 100644 --- a/lib/pure/algorithm.nim +++ b/lib/pure/algorithm.nim @@ -24,6 +24,17 @@ proc `*`*(x: int, order: SortOrder): int {.inline.} = var y = order.ord - 1 result = (x xor y) - y +proc fill*[T](a: var openArray[T], first, last: Natural, value: T) = + ## fills the array ``a[first..last]`` with `value`. + var x = first + while x <= last: + a[x] = value + inc(x) + +proc fill*[T](a: var openArray[T], value: T) = + ## fills the array `a` with `value`. + fill(a, 0, a.high, value) + proc reverse*[T](a: var openArray[T], first, last: Natural) = ## reverses the array ``a[first..last]``. var x = first From 9723e30647c855a1e87029310b2e28bdf95cd398 Mon Sep 17 00:00:00 2001 From: Boris Vassilev Date: Wed, 13 May 2015 13:00:20 +0300 Subject: [PATCH 0214/1263] Document explicitly the behaviour of math.gcd with float arguments --- lib/pure/math.nim | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lib/pure/math.nim b/lib/pure/math.nim index cb58ea39b..a9e9010f6 100644 --- a/lib/pure/math.nim +++ b/lib/pure/math.nim @@ -352,6 +352,9 @@ proc `^`*[T](x, y: T): T = proc gcd*[T](x, y: T): T = ## Computes the greatest common divisor of ``x`` and ``y``. + ## Note that for floats, the result cannot always be interpreted as + ## "greatest decimal `z` such that ``z*N == x and z*M == y`` + ## where N and M are positive integers." var (x,y) = (x,y) while y != 0: x = x mod y From bd4d5db18e0523819d80182360433095a97deec9 Mon Sep 17 00:00:00 2001 From: Araq Date: Wed, 13 May 2015 12:17:11 +0200 Subject: [PATCH 0215/1263] terminal: doc improvments --- lib/pure/terminal.nim | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/lib/pure/terminal.nim b/lib/pure/terminal.nim index 29f700db5..7b4d548fe 100644 --- a/lib/pure/terminal.nim +++ b/lib/pure/terminal.nim @@ -364,7 +364,13 @@ macro styledEcho*(m: varargs[expr]): stmt = result.add(newCall(bindSym"write", bindSym"stdout", newStrLitNode("\n"))) result.add(newCall(bindSym"resetAttributes")) -when not defined(windows): +when defined(nimdoc): + proc getch*(): char = + ## Read a single character from the terminal, blocking until it is entered. + ## The character is not printed to the terminal. This is not available for + ## Windows. + discard +elif not defined(windows): proc getch*(): char = ## Read a single character from the terminal, blocking until it is entered. ## The character is not printed to the terminal. This is not available for From 75ccdebd1e8ea9ffd81815716c2593cfbc9820c0 Mon Sep 17 00:00:00 2001 From: Araq Date: Wed, 13 May 2015 12:19:08 +0200 Subject: [PATCH 0216/1263] get rid of deprecated effects --- lib/core/locks.nim | 24 ++++++------------------ 1 file changed, 6 insertions(+), 18 deletions(-) diff --git a/lib/core/locks.nim b/lib/core/locks.nim index 8a809fc84..92ae24a37 100644 --- a/lib/core/locks.nim +++ b/lib/core/locks.nim @@ -1,7 +1,7 @@ # # # Nim's Runtime Library -# (c) Copyright 2012 Andreas Rumpf +# (c) Copyright 2015 Andreas Rumpf # # See the file "copying.txt", included in this # distribution, for details about the copyright. @@ -15,18 +15,6 @@ type TLock* = TSysLock ## Nim lock; whether this is re-entrant ## or not is unspecified! TCond* = TSysCond ## Nim condition variable - - LockEffect* {.deprecated.} = object of RootEffect ## \ - ## effect that denotes that some lock operation - ## is performed. Deprecated, do not use anymore! - AquireEffect* {.deprecated.} = object of LockEffect ## \ - ## effect that denotes that some lock is - ## acquired. Deprecated, do not use anymore! - ReleaseEffect* {.deprecated.} = object of LockEffect ## \ - ## effect that denotes that some lock is - ## released. Deprecated, do not use anymore! -{.deprecated: [FLock: LockEffect, FAquireLock: AquireEffect, - FReleaseLock: ReleaseEffect].} proc initLock*(lock: var TLock) {.inline.} = ## Initializes the given lock. @@ -36,14 +24,14 @@ proc deinitLock*(lock: var TLock) {.inline.} = ## Frees the resources associated with the lock. deinitSys(lock) -proc tryAcquire*(lock: var TLock): bool = +proc tryAcquire*(lock: var TLock): bool = ## Tries to acquire the given lock. Returns `true` on success. result = tryAcquireSys(lock) proc acquire*(lock: var TLock) = ## Acquires the given lock. acquireSys(lock) - + proc release*(lock: var TLock) = ## Releases the given lock. releaseSys(lock) @@ -58,10 +46,10 @@ proc deinitCond*(cond: var TCond) {.inline.} = deinitSysCond(cond) proc wait*(cond: var TCond, lock: var TLock) {.inline.} = - ## waits on the condition variable `cond`. + ## waits on the condition variable `cond`. waitSysCond(cond, lock) - + proc signal*(cond: var TCond) {.inline.} = - ## sends a signal to the condition variable `cond`. + ## sends a signal to the condition variable `cond`. signalSysCond(cond) From 28dd0407bbee1bbbfeec92e60f3836d3845a09d6 Mon Sep 17 00:00:00 2001 From: Reimer Behrends Date: Wed, 13 May 2015 12:26:34 +0200 Subject: [PATCH 0217/1263] Fix behavior of os.getFileInfo() for symbolic links. The calls to lstat() and stat() were switched. As a result, links weren't followed for followLink == true and links were followed for followLink == false. --- lib/pure/os.nim | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/pure/os.nim b/lib/pure/os.nim index f53abe81d..3a5bcbfa1 100644 --- a/lib/pure/os.nim +++ b/lib/pure/os.nim @@ -2033,10 +2033,10 @@ proc getFileInfo*(path: string, followSymlink = true): FileInfo = else: var rawInfo: TStat if followSymlink: - if lstat(path, rawInfo) < 0'i32: + if stat(path, rawInfo) < 0'i32: raiseOSError(osLastError()) else: - if stat(path, rawInfo) < 0'i32: + if lstat(path, rawInfo) < 0'i32: raiseOSError(osLastError()) rawToFormalFileInfo(rawInfo, result) From c56a00523861ec3d680478f0facf4a05ea753969 Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Wed, 13 May 2015 18:19:39 +0500 Subject: [PATCH 0218/1263] nextFreePort -> connectToNextFreePort --- compiler/nimsuggest/nimsuggest.nim | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/compiler/nimsuggest/nimsuggest.nim b/compiler/nimsuggest/nimsuggest.nim index ad3b5bf0d..3b4aa658d 100644 --- a/compiler/nimsuggest/nimsuggest.nim +++ b/compiler/nimsuggest/nimsuggest.nim @@ -138,7 +138,7 @@ proc returnEPC(socket: var Socket, uid: BiggestInt, s: SexpNode, return_symbol = socket.send(toHex(len(response), 6)) socket.send(response) -proc nextFreePort(server: Socket, host: string, start = 30000): int = +proc connectToNextFreePort(server: Socket, host: string, start = 30000): int = result = start while true: try: @@ -222,7 +222,7 @@ proc serve() = stdoutSocket.close() of mepc: var server = newSocket() - let port = nextFreePort(server, "localhost") + let port = connectToNextFreePort(server, "localhost") var inp = "".TaintedString server.listen() echo(port) From 5e97780a9411a9702c285acec7922bfe865b8897 Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Wed, 13 May 2015 18:34:29 +0500 Subject: [PATCH 0219/1263] changed from parseEnum to direct copy Let's hope this doesn't break anything --- compiler/suggest.nim | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/compiler/suggest.nim b/compiler/suggest.nim index a79d08f71..659f1fa16 100644 --- a/compiler/suggest.nim +++ b/compiler/suggest.nim @@ -37,11 +37,7 @@ template origModuleName(m: PSym): string = m.name.s proc symToSuggest(s: PSym, isLocal: bool, section: string, li: TLineInfo): Suggest = result.section = parseIdeCmd(section) if optIdeTerse in gGlobalOptions: - if s.kind in routineKinds: - result.symkind = parseEnum[TSymKind](renderTree(s.ast, {renderNoBody, renderNoComments, - renderDocComments, renderNoPragmas})) - else: - result.symkind = parseEnum[TSymKind](s.name.s) + result.symkind = s.kind result.filePath = toFullPath(li) result.line = toLinenumber(li) result.column = toColumn(li) From 86c9fffc417a7a316f5a1e07cffad21f630e9470 Mon Sep 17 00:00:00 2001 From: Jochen Van de Velde Date: Wed, 13 May 2015 18:19:51 +0200 Subject: [PATCH 0220/1263] Fix osproc documentation --- lib/pure/osproc.nim | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/lib/pure/osproc.nim b/lib/pure/osproc.nim index dce0673ba..8150f902a 100644 --- a/lib/pure/osproc.nim +++ b/lib/pure/osproc.nim @@ -195,43 +195,43 @@ proc peekExitCode*(p: Process): int {.tags: [].} proc inputStream*(p: Process): Stream {.rtl, extern: "nosp$1", tags: [].} ## returns ``p``'s input stream for writing to. ## - ## **Warning**: The returned `PStream` should not be closed manually as it - ## is closed when closing the PProcess ``p``. + ## **Warning**: The returned `Stream` should not be closed manually as it + ## is closed when closing the Process ``p``. proc outputStream*(p: Process): Stream {.rtl, extern: "nosp$1", tags: [].} ## returns ``p``'s output stream for reading from. ## - ## **Warning**: The returned `PStream` should not be closed manually as it - ## is closed when closing the PProcess ``p``. + ## **Warning**: The returned `Stream` should not be closed manually as it + ## is closed when closing the Process ``p``. proc errorStream*(p: Process): Stream {.rtl, extern: "nosp$1", tags: [].} ## returns ``p``'s error stream for reading from. ## - ## **Warning**: The returned `PStream` should not be closed manually as it - ## is closed when closing the PProcess ``p``. + ## **Warning**: The returned `Stream` should not be closed manually as it + ## is closed when closing the Process ``p``. proc inputHandle*(p: Process): FileHandle {.rtl, extern: "nosp$1", tags: [].} = ## returns ``p``'s input file handle for writing to. ## - ## **Warning**: The returned `TFileHandle` should not be closed manually as - ## it is closed when closing the PProcess ``p``. + ## **Warning**: The returned `FileHandle` should not be closed manually as + ## it is closed when closing the Process ``p``. result = p.inHandle proc outputHandle*(p: Process): FileHandle {.rtl, extern: "nosp$1", tags: [].} = ## returns ``p``'s output file handle for reading from. ## - ## **Warning**: The returned `TFileHandle` should not be closed manually as - ## it is closed when closing the PProcess ``p``. + ## **Warning**: The returned `FileHandle` should not be closed manually as + ## it is closed when closing the Process ``p``. result = p.outHandle proc errorHandle*(p: Process): FileHandle {.rtl, extern: "nosp$1", tags: [].} = ## returns ``p``'s error file handle for reading from. ## - ## **Warning**: The returned `TFileHandle` should not be closed manually as - ## it is closed when closing the PProcess ``p``. + ## **Warning**: The returned `FileHandle` should not be closed manually as + ## it is closed when closing the Process ``p``. result = p.errHandle proc countProcessors*(): int {.rtl, extern: "nosp$1".} = From 179d82c55bda199b32a108f4ba474f47a83584c9 Mon Sep 17 00:00:00 2001 From: Adam Strzelecki Date: Wed, 13 May 2015 16:53:39 +0200 Subject: [PATCH 0221/1263] Fix #2662: Don't convert subtype typedesc params There is no point to issue implicit HiddenStdConv encountering subtype of typedesc[Base] parameter on overload resolution, since this will anyway never reach codegen. This change effectively fixes compiler bug for: iterator it(T: typedesc[Base]) = ... for s in it(SubclassOfBase): ... Where HiddenStdConv triggered implicit instantiation of variable of type typedesc[Base] in for transform, that eventually fails at getUniqueType, that refuses to work for typedesc. --- compiler/sigmatch.nim | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/compiler/sigmatch.nim b/compiler/sigmatch.nim index 2a9d15b5a..7ea2c3d6f 100644 --- a/compiler/sigmatch.nim +++ b/compiler/sigmatch.nim @@ -1281,7 +1281,10 @@ proc paramTypesMatchAux(m: var TCandidate, f, argType: PType, result = implicitConv(nkHiddenStdConv, f, arg, m, c) of isSubtype: inc(m.subtypeMatches) - result = implicitConv(nkHiddenSubConv, f, arg, m, c) + if f.kind == tyTypeDesc: + result = arg + else: + result = implicitConv(nkHiddenSubConv, f, arg, m, c) of isSubrange: inc(m.subtypeMatches) if f.kind == tyVar: From a8fbaf917b854876a01782c644e01ab2e90c5d9f Mon Sep 17 00:00:00 2001 From: Adam Strzelecki Date: Wed, 13 May 2015 19:01:41 +0200 Subject: [PATCH 0222/1263] Tests for static class proc, methods & iterators This currently covers #2662 & #2710 bugs. --- tests/metatype/ttypedesc3.nim | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 tests/metatype/ttypedesc3.nim diff --git a/tests/metatype/ttypedesc3.nim b/tests/metatype/ttypedesc3.nim new file mode 100644 index 000000000..3d40b25b2 --- /dev/null +++ b/tests/metatype/ttypedesc3.nim @@ -0,0 +1,19 @@ +import typetraits + +type + Base = object of RootObj + Child = object of Base + +proc pr(T: typedesc[Base]) = echo "proc " & T.name +method me(T: typedesc[Base]) = echo "method " & T.name +iterator it(T: typedesc[Base]) = yield "yield " & T.name + +Base.pr +Child.pr + +Base.me +when false: + Child.me #<- bug #2710 + +for s in Base.it: echo s +for s in Child.it: echo s #<- bug #2662 From 2bc1db7a30a52378c0fcf16611bc0faba6ddc390 Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Wed, 13 May 2015 13:13:30 -0500 Subject: [PATCH 0223/1263] run the C test too --- tests/testament/categories.nim | 2 +- tests/testament/tester.nim | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/testament/categories.nim b/tests/testament/categories.nim index 336cf211e..4de1edeee 100644 --- a/tests/testament/categories.nim +++ b/tests/testament/categories.nim @@ -147,7 +147,7 @@ proc longGCTests(r: var TResults, cat: Category, options: string) = var c = initResults() # According to ioTests, this should compile the file testNoSpec c, makeTest("tests/realtimeGC/shared", options, cat, actionCompile) - # testC r, makeTest("tests/realtimeGC/cmain", cOptions, cat, actionRun) + testC r, makeTest("tests/realtimeGC/cmain", cOptions, cat, actionRun) testSpec r, makeTest("tests/realtimeGC/nmain", options & "--threads: on", cat, actionRun) # ------------------------- threading tests ----------------------------------- diff --git a/tests/testament/tester.nim b/tests/testament/tester.nim index 93cb3cc7a..0308ce940 100644 --- a/tests/testament/tester.nim +++ b/tests/testament/tester.nim @@ -93,7 +93,7 @@ proc callCCompiler(cmdTemplate, filename, options: string, target: TTarget): TSpec = let c = parseCmdLine(cmdTemplate % ["target", targetToCmd[target], "options", options, "file", filename.quoteShell]) - var p = startProcess(command="gcc", args=c[4.. ^1], + var p = startProcess(command="gcc", args=c[5.. ^1], options={poStdErrToStdOut, poUsePath}) let outp = p.outputStream var x = newStringOfCap(120) From c0003cc73b1eca79285b4cb61f088f65c7bcd0b4 Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Thu, 14 May 2015 22:57:29 +0500 Subject: [PATCH 0224/1263] added documentation about sexp --- doc/lib.txt | 4 ++++ web/news.txt | 1 + 2 files changed, 5 insertions(+) diff --git a/doc/lib.txt b/doc/lib.txt index 1c0278068..f43228151 100644 --- a/doc/lib.txt +++ b/doc/lib.txt @@ -325,6 +325,10 @@ Parsers * `rstgen `_ This module implements a generator of HTML/Latex from reStructuredText. +* `sexp `_ + High performance sexp parser and generator, mainly for communication + with emacs. + XML Processing -------------- diff --git a/web/news.txt b/web/news.txt index 9719fb8d7..e00d937f5 100644 --- a/web/news.txt +++ b/web/news.txt @@ -223,6 +223,7 @@ Library additions space between ``.. <`` and ``.. ^`` is not necessary anymore. - Added ``system.xlen`` for strings and sequences to get back the old ``len`` operation that doesn't check for ``nil`` for efficiency. +- Added sexp.nim to parse and generate sexp. Bugfixes From 78b7625417783c2c1418046986d8d6080f84160e Mon Sep 17 00:00:00 2001 From: apense Date: Thu, 14 May 2015 14:16:58 -0400 Subject: [PATCH 0225/1263] Corrected sortedByIt example `people` needs `var` --- lib/pure/algorithm.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/pure/algorithm.nim b/lib/pure/algorithm.nim index f7ccb9234..12a5e3358 100644 --- a/lib/pure/algorithm.nim +++ b/lib/pure/algorithm.nim @@ -211,7 +211,7 @@ template sortedByIt*(seq1, op: expr): expr = ## p3: Person = (name: "p3", age: 30) ## p4: Person = (name: "p4", age: 30) ## - ## people = @[p1,p2,p4,p3] + ## var people = @[p1,p2,p4,p3] ## ## echo people.sortedByIt(it.name) ## From 8fc53f29520dd9a5eee86393dad63bd3f16aa54b Mon Sep 17 00:00:00 2001 From: transfuturist Date: Mon, 11 May 2015 00:02:01 -0700 Subject: [PATCH 0226/1263] Add path directive to allow inclusion of config file's path itself --- compiler/commands.nim | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/compiler/commands.nim b/compiler/commands.nim index b6ebb6bcb..d30d8326c 100644 --- a/compiler/commands.nim +++ b/compiler/commands.nim @@ -229,7 +229,8 @@ proc testCompileOption*(switch: string, info: TLineInfo): bool = of "experimental": result = gExperimentalMode else: invalidCmdLineOption(passCmd1, switch, info) -proc processPath(path: string, notRelativeToProj = false): string = +proc processPath(path: string, notRelativeToProj = false, + cfginfo = unknownLineInfo()): string = let p = if notRelativeToProj or os.isAbsolute(path) or '$' in path or path[0] == '.': path @@ -239,6 +240,7 @@ proc processPath(path: string, notRelativeToProj = false): string = "nim", getPrefixDir(), "lib", libpath, "home", removeTrailingDirSep(os.getHomeDir()), + "config", cfginfo.toFullPath().splitFile().dir, "projectname", options.gProjectName, "projectpath", options.gProjectPath]) @@ -281,7 +283,7 @@ proc processSwitch(switch, arg: string, pass: TCmdLinePass, info: TLineInfo) = case switch.normalize of "path", "p": expectArg(switch, arg, pass, info) - addPath(processPath(arg), info) + addPath(processPath(arg, cfginfo=info), info) of "nimblepath", "babelpath": # keep the old name for compat if pass in {passCmd2, passPP} and not options.gNoNimblePath: From e7bc828ef3f0d30f6016c6f10f867e84c4ef5c0f Mon Sep 17 00:00:00 2001 From: apense Date: Thu, 14 May 2015 18:32:26 -0400 Subject: [PATCH 0227/1263] Update algorithm.nim --- lib/pure/algorithm.nim | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/lib/pure/algorithm.nim b/lib/pure/algorithm.nim index 12a5e3358..6dfdff275 100644 --- a/lib/pure/algorithm.nim +++ b/lib/pure/algorithm.nim @@ -210,8 +210,7 @@ template sortedByIt*(seq1, op: expr): expr = ## p2: Person = (name: "p2", age: 20) ## p3: Person = (name: "p3", age: 30) ## p4: Person = (name: "p4", age: 30) - ## - ## var people = @[p1,p2,p4,p3] + ## people = @[p1,p2,p4,p3] ## ## echo people.sortedByIt(it.name) ## From ddbcbab3e7df7d90086ff0c7d0a76a851dddbb87 Mon Sep 17 00:00:00 2001 From: Markus Engelbrecht Date: Fri, 15 May 2015 18:39:56 +0200 Subject: [PATCH 0228/1263] use new syntax for negative slicing --- doc/tut1.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/tut1.txt b/doc/tut1.txt index 58ace1dbe..cf27ac788 100644 --- a/doc/tut1.txt +++ b/doc/tut1.txt @@ -1325,7 +1325,7 @@ define operators which accept Slice objects to define ranges. b = "Slices are useless." echo a[7..12] # --> 'a prog' - b[11.. -2] = "useful" + b[11.. ^2] = "useful" echo b # --> 'Slices are useful.' In the previous example slices are used to modify a part of a string, and even From 7ba5f18e9dfa8767716d8c1a0d7b16f52f0c2ca3 Mon Sep 17 00:00:00 2001 From: Markus Engelbrecht Date: Fri, 15 May 2015 18:42:29 +0200 Subject: [PATCH 0229/1263] fix typo for noSideEffect pragma --- doc/manual/threads.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/manual/threads.txt b/doc/manual/threads.txt index fc3040c87..11380f757 100644 --- a/doc/manual/threads.txt +++ b/doc/manual/threads.txt @@ -37,7 +37,7 @@ that contains GC'ed memory (``string``, ``seq``, ``ref`` or a closure) either directly or indirectly through a call to a GC unsafe proc. The `gcsafe`:idx: annotation can be used to mark a proc to be gcsafe, -otherwise this property is inferred by the compiler. Note that ``noSideEfect`` +otherwise this property is inferred by the compiler. Note that ``noSideEffect`` implies ``gcsafe``. The only way to create a thread is via ``spawn`` or ``createThead``. ``spawn`` is usually the preferable method. Either way the invoked proc must not use ``var`` parameters nor must any of its parameters From cb6f867495ae23779cc7846eb2817b3bb532dbd1 Mon Sep 17 00:00:00 2001 From: pdw Date: Fri, 15 May 2015 20:15:12 -0500 Subject: [PATCH 0230/1263] Fixed 'milliseconds' spelling in code and docs --- lib/pure/asyncdispatch.nim | 2 +- lib/pure/httpclient.nim | 16 ++++++++-------- lib/pure/net.nim | 10 +++++----- lib/pure/osproc.nim | 2 +- lib/pure/rawsockets.nim | 4 ++-- lib/pure/scgi.nim | 2 +- lib/pure/sockets.nim | 18 +++++++++--------- lib/pure/times.nim | 17 +++++++++++------ 8 files changed, 38 insertions(+), 33 deletions(-) diff --git a/lib/pure/asyncdispatch.nim b/lib/pure/asyncdispatch.nim index a4d7a1632..8849a8be3 100644 --- a/lib/pure/asyncdispatch.nim +++ b/lib/pure/asyncdispatch.nim @@ -1154,7 +1154,7 @@ else: proc sleepAsync*(ms: int): Future[void] = ## Suspends the execution of the current async procedure for the next - ## ``ms`` miliseconds. + ## ``ms`` milliseconds. var retFuture = newFuture[void]("sleepAsync") let p = getGlobalDispatcher() p.timers.add((epochTime() + (ms / 1000), retFuture)) diff --git a/lib/pure/httpclient.nim b/lib/pure/httpclient.nim index 9c27ecdab..e083d44ea 100644 --- a/lib/pure/httpclient.nim +++ b/lib/pure/httpclient.nim @@ -64,7 +64,7 @@ ## ======== ## Currently all functions support an optional timeout, by default the timeout is set to ## `-1` which means that the function will never time out. The timeout is -## measured in miliseconds, once it is set any call on a socket which may +## measured in milliseconds, once it is set any call on a socket which may ## block will be susceptible to this timeout, however please remember that the ## function as a whole can take longer than the specified timeout, only ## individual internal calls on the socket are affected. In practice this means @@ -386,7 +386,7 @@ proc request*(url: string, httpMethod: string, extraHeaders = "", ## | Requests ``url`` with the custom method string specified by the ## | ``httpMethod`` parameter. ## | Extra headers can be specified and must be separated by ``\c\L`` - ## | An optional timeout can be specified in miliseconds, if reading from the + ## | An optional timeout can be specified in milliseconds, if reading from the ## server takes longer than specified an ETimeout exception will be raised. var r = if proxy == nil: parseUri(url) else: proxy.url var headers = substr(httpMethod, len("http")) @@ -440,7 +440,7 @@ proc request*(url: string, httpMethod = httpGET, extraHeaders = "", userAgent = defUserAgent, proxy: Proxy = nil): Response = ## | Requests ``url`` with the specified ``httpMethod``. ## | Extra headers can be specified and must be separated by ``\c\L`` - ## | An optional timeout can be specified in miliseconds, if reading from the + ## | An optional timeout can be specified in milliseconds, if reading from the ## server takes longer than specified an ETimeout exception will be raised. result = request(url, $httpMethod, extraHeaders, body, sslContext, timeout, userAgent, proxy) @@ -467,7 +467,7 @@ proc get*(url: string, extraHeaders = "", maxRedirects = 5, ## | GETs the ``url`` and returns a ``Response`` object ## | This proc also handles redirection ## | Extra headers can be specified and must be separated by ``\c\L``. - ## | An optional timeout can be specified in miliseconds, if reading from the + ## | An optional timeout can be specified in milliseconds, if reading from the ## server takes longer than specified an ETimeout exception will be raised. result = request(url, httpGET, extraHeaders, "", sslContext, timeout, userAgent, proxy) @@ -486,7 +486,7 @@ proc getContent*(url: string, extraHeaders = "", maxRedirects = 5, ## | GETs the body and returns it as a string. ## | Raises exceptions for the status codes ``4xx`` and ``5xx`` ## | Extra headers can be specified and must be separated by ``\c\L``. - ## | An optional timeout can be specified in miliseconds, if reading from the + ## | An optional timeout can be specified in milliseconds, if reading from the ## server takes longer than specified an ETimeout exception will be raised. var r = get(url, extraHeaders, maxRedirects, sslContext, timeout, userAgent, proxy) @@ -505,7 +505,7 @@ proc post*(url: string, extraHeaders = "", body = "", ## | This proc adds the necessary Content-Length header. ## | This proc also handles redirection. ## | Extra headers can be specified and must be separated by ``\c\L``. - ## | An optional timeout can be specified in miliseconds, if reading from the + ## | An optional timeout can be specified in milliseconds, if reading from the ## server takes longer than specified an ETimeout exception will be raised. ## | The optional ``multipart`` parameter can be used to create ## ``multipart/form-data`` POSTs comfortably. @@ -542,7 +542,7 @@ proc postContent*(url: string, extraHeaders = "", body = "", ## | POSTs ``body`` to ``url`` and returns the response's body as a string ## | Raises exceptions for the status codes ``4xx`` and ``5xx`` ## | Extra headers can be specified and must be separated by ``\c\L``. - ## | An optional timeout can be specified in miliseconds, if reading from the + ## | An optional timeout can be specified in milliseconds, if reading from the ## server takes longer than specified an ETimeout exception will be raised. ## | The optional ``multipart`` parameter can be used to create ## ``multipart/form-data`` POSTs comfortably. @@ -558,7 +558,7 @@ proc downloadFile*(url: string, outputFilename: string, timeout = -1, userAgent = defUserAgent, proxy: Proxy = nil) = ## | Downloads ``url`` and saves it to ``outputFilename`` - ## | An optional timeout can be specified in miliseconds, if reading from the + ## | An optional timeout can be specified in milliseconds, if reading from the ## server takes longer than specified an ETimeout exception will be raised. var f: File if open(f, outputFilename, fmWrite): diff --git a/lib/pure/net.nim b/lib/pure/net.nim index ffbc6e320..cf37c271e 100644 --- a/lib/pure/net.nim +++ b/lib/pure/net.nim @@ -704,7 +704,7 @@ proc waitFor(socket: Socket, waited: var float, timeout, size: int, proc recv*(socket: Socket, data: pointer, size: int, timeout: int): int {. tags: [ReadIOEffect, TimeEffect].} = - ## overload with a ``timeout`` parameter in miliseconds. + ## overload with a ``timeout`` parameter in milliseconds. var waited = 0.0 # number of seconds already waited var read = 0 @@ -729,7 +729,7 @@ proc recv*(socket: Socket, data: var string, size: int, timeout = -1, ## This function will throw an EOS exception when an error occurs. A value ## lower than 0 is never returned. ## - ## A timeout may be specified in miliseconds, if enough data is not received + ## A timeout may be specified in milliseconds, if enough data is not received ## within the time specified an ETimeout exception will be raised. ## ## **Note**: ``data`` must be initialised. @@ -777,7 +777,7 @@ proc readLine*(socket: Socket, line: var TaintedString, timeout = -1, ## ## An EOS exception will be raised in the case of a socket error. ## - ## A timeout can be specified in miliseconds, if data is not received within + ## A timeout can be specified in milliseconds, if data is not received within ## the specified time an ETimeout exception will be raised. ## ## **Warning**: Only the ``SafeDisconn`` flag is currently supported. @@ -844,7 +844,7 @@ proc recvFrom*(socket: Socket, data: var string, length: int, proc skip*(socket: Socket, size: int, timeout = -1) = ## Skips ``size`` amount of bytes. ## - ## An optional timeout can be specified in miliseconds, if skipping the + ## An optional timeout can be specified in milliseconds, if skipping the ## bytes takes longer than specified an ETimeout exception will be raised. ## ## Returns the number of skipped bytes. @@ -967,7 +967,7 @@ proc connect*(socket: Socket, address: string, port = Port(0), timeout: int, af: Domain = AF_INET) {.tags: [ReadIOEffect, WriteIOEffect].} = ## Connects to server as specified by ``address`` on port specified by ``port``. ## - ## The ``timeout`` paremeter specifies the time in miliseconds to allow for + ## The ``timeout`` paremeter specifies the time in milliseconds to allow for ## the connection to the server to be made. socket.fd.setBlocking(false) diff --git a/lib/pure/osproc.nim b/lib/pure/osproc.nim index 8150f902a..dc6f21174 100644 --- a/lib/pure/osproc.nim +++ b/lib/pure/osproc.nim @@ -303,7 +303,7 @@ proc execProcesses*(cmds: openArray[string], close(p) proc select*(readfds: var seq[Process], timeout = 500): int - ## `select` with a sensible Nim interface. `timeout` is in miliseconds. + ## `select` with a sensible Nim interface. `timeout` is in milliseconds. ## Specify -1 for no timeout. Returns the number of processes that are ## ready to read from. The processes that are ready to be read from are ## removed from `readfds`. diff --git a/lib/pure/rawsockets.nim b/lib/pure/rawsockets.nim index a30c23ada..d08c5b769 100644 --- a/lib/pure/rawsockets.nim +++ b/lib/pure/rawsockets.nim @@ -392,7 +392,7 @@ proc select*(readfds: var seq[SocketHandle], timeout = 500): int = ## Traditional select function. This function will return the number of ## sockets that are ready to be read from, written to, or which have errors. ## If there are none; 0 is returned. - ## ``Timeout`` is in miliseconds and -1 can be specified for no timeout. + ## ``Timeout`` is in milliseconds and -1 can be specified for no timeout. ## ## A socket is removed from the specific ``seq`` when it has data waiting to ## be read/written to or has errors (``exceptfds``). @@ -416,7 +416,7 @@ proc selectWrite*(writefds: var seq[SocketHandle], ## written to. The sockets which can be written to will also be removed ## from ``writefds``. ## - ## ``timeout`` is specified in miliseconds and ``-1`` can be specified for + ## ``timeout`` is specified in milliseconds and ``-1`` can be specified for ## an unlimited time. var tv {.noInit.}: Timeval = timeValFromMilliseconds(timeout) diff --git a/lib/pure/scgi.nim b/lib/pure/scgi.nim index f3e2b583c..3de422c87 100644 --- a/lib/pure/scgi.nim +++ b/lib/pure/scgi.nim @@ -126,7 +126,7 @@ proc close*(s: var ScgiState) = s.server.close() proc next*(s: var ScgiState, timeout: int = -1): bool = - ## proceed to the first/next request. Waits ``timeout`` miliseconds for a + ## proceed to the first/next request. Waits ``timeout`` milliseconds for a ## request, if ``timeout`` is `-1` then this function will never time out. ## Returns `true` if a new request has been processed. var rsocks = @[s.server] diff --git a/lib/pure/sockets.nim b/lib/pure/sockets.nim index 3afb545c8..64e2cdcd3 100644 --- a/lib/pure/sockets.nim +++ b/lib/pure/sockets.nim @@ -986,7 +986,7 @@ proc select*(readfds, writefds, exceptfds: var seq[Socket], ## Traditional select function. This function will return the number of ## sockets that are ready to be read from, written to, or which have errors. ## If there are none; 0 is returned. - ## ``Timeout`` is in miliseconds and -1 can be specified for no timeout. + ## ``Timeout`` is in milliseconds and -1 can be specified for no timeout. ## ## Sockets which are **not** ready for reading, writing or which don't have ## errors waiting on them are removed from the ``readfds``, ``writefds``, @@ -1040,7 +1040,7 @@ proc selectWrite*(writefds: var seq[Socket], ## written to. The sockets which **cannot** be written to will also be removed ## from ``writefds``. ## - ## ``timeout`` is specified in miliseconds and ``-1`` can be specified for + ## ``timeout`` is specified in milliseconds and ``-1`` can be specified for ## an unlimited time. var tv {.noInit.}: Timeval = timeValFromMilliseconds(timeout) @@ -1174,7 +1174,7 @@ proc waitFor(socket: Socket, waited: var float, timeout, size: int, proc recv*(socket: Socket, data: pointer, size: int, timeout: int): int {. tags: [ReadIOEffect, TimeEffect].} = - ## overload with a ``timeout`` parameter in miliseconds. + ## overload with a ``timeout`` parameter in milliseconds. var waited = 0.0 # number of seconds already waited var read = 0 @@ -1197,7 +1197,7 @@ proc recv*(socket: Socket, data: var string, size: int, timeout = -1): int = ## This function will throw an EOS exception when an error occurs. A value ## lower than 0 is never returned. ## - ## A timeout may be specified in miliseconds, if enough data is not received + ## A timeout may be specified in milliseconds, if enough data is not received ## within the time specified an ETimeout exception will be raised. ## ## **Note**: ``data`` must be initialised. @@ -1258,7 +1258,7 @@ proc recvLine*(socket: Socket, line: var TaintedString, timeout = -1): bool {. ## If the socket is disconnected, ``line`` will be set to ``""`` and ``True`` ## will be returned. ## - ## A timeout can be specified in miliseconds, if data is not received within + ## A timeout can be specified in milliseconds, if data is not received within ## the specified time an ETimeout exception will be raised. ## ## **Deprecated since version 0.9.2**: This function has been deprecated in @@ -1302,7 +1302,7 @@ proc readLine*(socket: Socket, line: var TaintedString, timeout = -1) {. ## ## An EOS exception will be raised in the case of a socket error. ## - ## A timeout can be specified in miliseconds, if data is not received within + ## A timeout can be specified in milliseconds, if data is not received within ## the specified time an ETimeout exception will be raised. template addNLIfEmpty(): stmt = @@ -1433,7 +1433,7 @@ proc recv*(socket: Socket): TaintedString {.tags: [ReadIOEffect], deprecated.} = proc recvTimeout*(socket: Socket, timeout: int): TaintedString {. tags: [ReadIOEffect], deprecated.} = ## overloaded variant to support a ``timeout`` parameter, the ``timeout`` - ## parameter specifies the amount of miliseconds to wait for data on the + ## parameter specifies the amount of milliseconds to wait for data on the ## socket. ## ## **Deprecated since version 0.9.2**: This function is not safe for use. @@ -1554,7 +1554,7 @@ proc skip*(socket: Socket) {.tags: [ReadIOEffect], deprecated.} = proc skip*(socket: Socket, size: int, timeout = -1) = ## Skips ``size`` amount of bytes. ## - ## An optional timeout can be specified in miliseconds, if skipping the + ## An optional timeout can be specified in milliseconds, if skipping the ## bytes takes longer than specified an ETimeout exception will be raised. ## ## Returns the number of skipped bytes. @@ -1708,7 +1708,7 @@ proc connect*(socket: Socket, address: string, port = Port(0), timeout: int, af: Domain = AF_INET) {.tags: [ReadIOEffect, WriteIOEffect].} = ## Connects to server as specified by ``address`` on port specified by ``port``. ## - ## The ``timeout`` paremeter specifies the time in miliseconds to allow for + ## The ``timeout`` paremeter specifies the time in milliseconds to allow for ## the connection to the server to be made. let originalStatus = not socket.nonblocking socket.setBlocking(false) diff --git a/lib/pure/times.nim b/lib/pure/times.nim index 1b9fa4599..b8836c15b 100644 --- a/lib/pure/times.nim +++ b/lib/pure/times.nim @@ -134,7 +134,7 @@ type ## everything should be positive or everything negative. Zero is ## fine too. Mixed signs will lead to unexpected results. TimeInterval* = object ## a time interval - miliseconds*: int ## The number of miliseconds + milliseconds*: int ## The number of milliseconds seconds*: int ## The number of seconds minutes*: int ## The number of minutes hours*: int ## The number of hours @@ -145,6 +145,11 @@ type {.deprecated: [TMonth: Month, TWeekDay: WeekDay, TTime: Time, TTimeInterval: TimeInterval, TTimeInfo: TimeInfo].} +proc miliseconds*(t: TimeInterval): int {.deprecated.} = t.milliseconds + +proc `miliseconds=`*(t:var TimeInterval, milliseconds: int) {.deprecated.} = + t.milliseconds = milliseconds + proc getTime*(): Time {.tags: [TimeEffect], benign.} ## gets the current calendar time as a UNIX epoch value (number of seconds ## elapsed since 1970) with integer precission. Use epochTime for higher @@ -208,13 +213,13 @@ proc getTimezone*(): int {.tags: [TimeEffect], raises: [], benign.} ## returns the offset of the local (non-DST) timezone in seconds west of UTC. proc getStartMilsecs*(): int {.deprecated, tags: [TimeEffect], benign.} - ## get the miliseconds from the start of the program. **Deprecated since + ## get the milliseconds from the start of the program. **Deprecated since ## version 0.8.10.** Use ``epochTime`` or ``cpuTime`` instead. -proc initInterval*(miliseconds, seconds, minutes, hours, days, months, +proc initInterval*(milliseconds, seconds, minutes, hours, days, months, years: int = 0): TimeInterval = ## creates a new ``TimeInterval``. - result.miliseconds = miliseconds + result.milliseconds = milliseconds result.seconds = seconds result.minutes = minutes result.hours = hours @@ -264,7 +269,7 @@ proc toSeconds(a: TimeInfo, interval: TimeInterval): float = result += float(newinterv.hours * 60 * 60) result += float(newinterv.minutes * 60) result += float(newinterv.seconds) - result += newinterv.miliseconds / 1000 + result += newinterv.milliseconds / 1000 proc `+`*(a: TimeInfo, interval: TimeInterval): TimeInfo = ## adds ``interval`` time. @@ -530,7 +535,7 @@ elif defined(JS): startMilsecs = getTime() proc getStartMilsecs(): int = - ## get the miliseconds from the start of the program + ## get the milliseconds from the start of the program return int(getTime() - startMilsecs) proc valueOf(time: Time): float {.importcpp: "getTime", tags:[]} From 911c5d45ecba250234a24d7647ffd72c0e59c71a Mon Sep 17 00:00:00 2001 From: Erik O'Leary Date: Fri, 15 May 2015 22:12:31 -0500 Subject: [PATCH 0231/1263] Improved performance of "$" on jsonnode --- lib/pure/json.nim | 58 +++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 49 insertions(+), 9 deletions(-) diff --git a/lib/pure/json.nim b/lib/pure/json.nim index 5d824d6f8..9538e39d5 100644 --- a/lib/pure/json.nim +++ b/lib/pure/json.nim @@ -815,7 +815,7 @@ proc `{}`*(node: JsonNode, keys: varargs[string]): JsonNode = result = node for key in keys: if isNil(result) or result.kind!=JObject: - return nil + return nil result=result[key] proc `{}=`*(node: JsonNode, keys: varargs[string], value: JsonNode) = @@ -949,10 +949,50 @@ proc pretty*(node: JsonNode, indent = 2): string = result = "" toPretty(result, node, indent) +proc toUgly*(result: var string, node: JsonNode) = + ## Converts `node` to its JSON Representation, without + ## regard for human redability. + var comma = false + case node.kind: + of JArray: + result.add "[" + for child in node.elems: + if comma: result.add "," + else: comma = true + result.toUgly child + result.add "]" + of JObject: + result.add "{" + for key, value in items(node.fields): + if comma: result.add "," + else: comma = true + result.add "\"" + result.add key.escapeJson() + result.add "\":" + result.toUgly value + result.add "}" + of JString: + result.add "\"" + result.add node.str.escapeJson() + result.add "\"" + of JInt: + result.add($node.num) + of JFloat: + result.add($node.fnum) + of JBool: + result.add(if node.bval: "true" else: "false") + of JNull: + result.add "null" + +proc toUgly*(node: JsonNode): string = + ## Converts `node` to its JSON Representation on one line. + result = newStringOfCap(node.len shl 1) + toUgly(result, node) + proc `$`*(node: JsonNode): string = ## Converts `node` to its JSON Representation on one line. - result = "" - toPretty(result, node, 0, false) + result = newStringOfCap(node.len shl 1) + toUgly(result, node) iterator items*(node: JsonNode): JsonNode = ## Iterator for the items of `node`. `node` has to be a JArray. @@ -1153,7 +1193,7 @@ when false: when isMainModule: #var node = parse("{ \"test\": null }") #echo(node.existsKey("test56")) - + var parsed = parseFile("tests/testdata/jsontest.json") var parsed2 = parseFile("tests/testdata/jsontest2.json") @@ -1192,17 +1232,17 @@ when isMainModule: except: assert(false, "EInvalidIndex thrown for valid index") - assert(testJson{"b"}.str=="asd", "Couldn't fetch a singly nested key with {}") - assert(isNil(testJson{"nonexistent"}), "Non-existent keys should return nil") + assert(testJson{"b"}.str=="asd", "Couldn't fetch a singly nested key with {}") + assert(isNil(testJson{"nonexistent"}), "Non-existent keys should return nil") assert(parsed2{"repository", "description"}.str=="IRC Library for Haskell", "Couldn't fetch via multiply nested key using {}") assert(isNil(testJson{"a", "b"}), "Indexing through a list should return nil") assert(isNil(testJson{"a", "b"}), "Indexing through a list should return nil") assert(testJson{"a"}==parseJson"[1, 2, 3, 4]", "Didn't return a non-JObject when there was one to be found") assert(isNil(parseJson("[1, 2, 3]"){"foo"}), "Indexing directly into a list should return nil") - + # Generator: var j = %* [{"name": "John", "age": 30}, {"name": "Susan", "age": 31}] - assert j == %[%{"name": %"John", "age": %30}, %{"name": %"Susan", "age": %31}] + assert j == %[%{"name": %"John", "age": %30}, %{"name": %"Susan", "age": %31}] var j2 = %* [ @@ -1230,7 +1270,7 @@ when isMainModule: } ] assert j3 == %[%{"name": %"John", "age": %30}, %{"name": %"Susan", "age": %31}] - + when not defined(testing): discard """ while true: From 7b26df50d75f64216997c71a304c7b413fc65dda Mon Sep 17 00:00:00 2001 From: apense Date: Fri, 15 May 2015 23:52:55 -0400 Subject: [PATCH 0232/1263] Small sequence fix for algorithm.nim Since #853 was fixed, this should work fine. The `result = @[]` was swapped to the same syntax, too. --- lib/pure/algorithm.nim | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/lib/pure/algorithm.nim b/lib/pure/algorithm.nim index 6dfdff275..352b177e2 100644 --- a/lib/pure/algorithm.nim +++ b/lib/pure/algorithm.nim @@ -232,7 +232,7 @@ template sortedByIt*(seq1, op: expr): expr = proc product*[T](x: openArray[seq[T]]): seq[seq[T]] = ## produces the Cartesian product of the array. Warning: complexity ## may explode. - result = @[] + result = newSeq[seq[T]]() if x.len == 0: return if x.len == 1: @@ -242,8 +242,7 @@ proc product*[T](x: openArray[seq[T]]): seq[seq[T]] = indexes = newSeq[int](x.len) initial = newSeq[int](x.len) index = 0 - # replace with newSeq as soon as #853 is fixed - var next: seq[T] = @[] + var next = newSeq[T]() next.setLen(x.len) for i in 0..(x.len-1): if len(x[i]) == 0: return From def61c9fcd618ef9a58dd4671978bff7ceaf601a Mon Sep 17 00:00:00 2001 From: def Date: Sat, 16 May 2015 12:38:53 +0200 Subject: [PATCH 0233/1263] Clean up stdin file reading of compiler. Uses "stdinfile" as the module identifier now, which prevents problems with - colliding with the minus operator. This fixes #2422 and #2702. --- compiler/main.nim | 2 +- compiler/modules.nim | 29 ++++++++++++++++------------- compiler/nim.nim | 8 +++++--- compiler/passes.nim | 6 +----- 4 files changed, 23 insertions(+), 22 deletions(-) diff --git a/compiler/main.nim b/compiler/main.nim index 0c80c19b7..a01b6fe4f 100644 --- a/compiler/main.nim +++ b/compiler/main.nim @@ -63,7 +63,7 @@ proc commandCompileToC = compileProject() cgenWriteModules() if gCmd != cmdRun: - extccomp.callCCompiler(if gProjectName == "-": "stdinfile" else: changeFileExt(gProjectFull, "")) + extccomp.callCCompiler(changeFileExt(gProjectFull, "")) if isServing: # caas will keep track only of the compilation commands diff --git a/compiler/modules.nim b/compiler/modules.nim index a2b739efc..0371f34f3 100644 --- a/compiler/modules.nim +++ b/compiler/modules.nim @@ -10,8 +10,8 @@ ## implements the module handling import - ast, astalgo, magicsys, crc, rodread, msgs, cgendata, sigmatch, options, - idents, os, lexer, idgen, passes, syntaxes + ast, astalgo, magicsys, crc, rodread, msgs, cgendata, sigmatch, options, + idents, os, lexer, idgen, passes, syntaxes, llstream type TNeedRecompile* = enum Maybe, No, Yes, Probing, Recompiled @@ -39,12 +39,12 @@ template crc(x: PSym): expr = proc crcChanged(fileIdx: int32): bool = internalAssert fileIdx >= 0 and fileIdx < gMemCacheData.len - + template updateStatus = gMemCacheData[fileIdx].crcStatus = if result: crcHasChanged else: crcNotChanged # echo "TESTING CRC: ", fileIdx.toFilename, " ", result - + case gMemCacheData[fileIdx].crcStatus: of crcHasChanged: result = true @@ -96,7 +96,7 @@ proc checkDepMem(fileIdx: int32): TNeedRecompile = if optForceFullMake in gGlobalOptions or crcChanged(fileIdx): markDirty - + if gMemCacheData[fileIdx].deps != nil: gMemCacheData[fileIdx].needsRecompile = Probing for dep in gMemCacheData[fileIdx].deps: @@ -104,30 +104,30 @@ proc checkDepMem(fileIdx: int32): TNeedRecompile = if d in {Yes, Recompiled}: # echo fileIdx.toFilename, " depends on ", dep.toFilename, " ", d markDirty - + gMemCacheData[fileIdx].needsRecompile = No return No proc newModule(fileIdx: int32): PSym = # We cannot call ``newSym`` here, because we have to circumvent the ID - # mechanism, which we do in order to assign each module a persistent ID. + # mechanism, which we do in order to assign each module a persistent ID. new(result) result.id = - 1 # for better error checking result.kind = skModule let filename = fileIdx.toFullPath result.name = getIdent(splitFile(filename).name) - if result.name.s != "-" and not isNimIdentifier(result.name.s): + if not isNimIdentifier(result.name.s): rawMessage(errInvalidModuleName, result.name.s) - + result.info = newLineInfo(fileIdx, 1, 1) result.owner = newSym(skPackage, getIdent(getPackageName(filename)), nil, result.info) result.position = fileIdx - + growCache gMemCacheData, fileIdx growCache gCompiledModules, fileIdx gCompiledModules[result.position] = result - + incl(result.flags, sfUsed) initStrTable(result.tab) strTableAdd(result.tab, result) # a module knows itself @@ -143,12 +143,15 @@ proc compileModule*(fileIdx: int32, flags: TSymFlags): PSym = result.flags = result.flags + flags if gCmd in {cmdCompileToC, cmdCompileToCpp, cmdCheck, cmdIdeTools}: rd = handleSymbolFile(result) - if result.id < 0: + if result.id < 0: internalError("handleSymbolFile should have set the module\'s ID") return else: result.id = getID() - processModule(result, nil, rd) + if sfMainModule in flags and gProjectName == "-": + processModule(result, llStreamOpen(stdin), rd) + else: + processModule(result, nil, rd) if optCaasEnabled in gGlobalOptions: gMemCacheData[fileIdx].compiledAt = gLastCmdTime gMemCacheData[fileIdx].needsRecompile = Recompiled diff --git a/compiler/nim.nim b/compiler/nim.nim index b8ba2c6da..f04c616fc 100644 --- a/compiler/nim.nim +++ b/compiler/nim.nim @@ -38,7 +38,11 @@ proc handleCmdLine() = else: # Process command line arguments: processCmdLine(passCmd1, "") - if gProjectName != "": + if gProjectName == "-": + gProjectName = "stdinfile" + gProjectFull = "stdinfile" + gProjectPath = getCurrentDir() + elif gProjectName != "": try: gProjectFull = canonicalizePath(gProjectName) except OSError: @@ -61,8 +65,6 @@ proc handleCmdLine() = if gCmd == cmdRun: tccgen.run(commands.arguments) if optRun in gGlobalOptions: - if gProjectName == "-": - gProjectFull = "stdinfile" if gCmd == cmdCompileToJS: var ex: string if options.outFile.len > 0: diff --git a/compiler/passes.nim b/compiler/passes.nim index 129d8ad47..e031dae10 100644 --- a/compiler/passes.nim +++ b/compiler/passes.nim @@ -170,11 +170,7 @@ proc processModule(module: PSym, stream: PLLStream, rd: PRodReader) = openPasses(a, module) if stream == nil: let filename = fileIdx.toFullPathConsiderDirty - if module.name.s == "-": - module.name.s = "stdinfile" - s = llStreamOpen(stdin) - else: - s = llStreamOpen(filename, fmRead) + s = llStreamOpen(filename, fmRead) if s == nil: rawMessage(errCannotOpenFile, filename) return From 5799f4f1031dc4f019592a5d5625ebe5e89ed114 Mon Sep 17 00:00:00 2001 From: Markus Engelbrecht Date: Sat, 16 May 2015 14:34:11 +0200 Subject: [PATCH 0234/1263] RawFlowVar was renamed to FlowVarBase --- doc/manual/threads.txt | 2 +- doc/spawn.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/doc/manual/threads.txt b/doc/manual/threads.txt index 11380f757..f2b79a34f 100644 --- a/doc/manual/threads.txt +++ b/doc/manual/threads.txt @@ -146,7 +146,7 @@ wait on multiple flow variables at the same time: # wait until 2 out of 3 servers received the update: proc main = - var responses = newSeq[RawFlowVar](3) + var responses = newSeq[FlowVarBase](3) for i in 0..2: responses[i] = spawn tellServer(Update, "key", "value") var index = awaitAny(responses) diff --git a/doc/spawn.txt b/doc/spawn.txt index fb2f851c7..36bd02e96 100644 --- a/doc/spawn.txt +++ b/doc/spawn.txt @@ -33,7 +33,7 @@ variables at the same time: # wait until 2 out of 3 servers received the update: proc main = - var responses = newSeq[RawFlowVar](3) + var responses = newSeq[FlowVarBase](3) for i in 0..2: responses[i] = spawn tellServer(Update, "key", "value") var index = awaitAny(responses) From edce0ca2edcb41e3594ac869dcd45f4edecb2ef7 Mon Sep 17 00:00:00 2001 From: onionhammer Date: Sat, 16 May 2015 11:38:43 -0500 Subject: [PATCH 0235/1263] Fixed typo --- lib/pure/json.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/pure/json.nim b/lib/pure/json.nim index 9538e39d5..0a07da263 100644 --- a/lib/pure/json.nim +++ b/lib/pure/json.nim @@ -951,7 +951,7 @@ proc pretty*(node: JsonNode, indent = 2): string = proc toUgly*(result: var string, node: JsonNode) = ## Converts `node` to its JSON Representation, without - ## regard for human redability. + ## regard for human readability. var comma = false case node.kind: of JArray: From f1343e52e0c079eb11027d6337ba494f22202488 Mon Sep 17 00:00:00 2001 From: onionhammer Date: Sat, 16 May 2015 12:33:00 -0500 Subject: [PATCH 0236/1263] Added comment noting improved performance of non-pretty string conversion --- lib/pure/json.nim | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/pure/json.nim b/lib/pure/json.nim index 0a07da263..8389411c2 100644 --- a/lib/pure/json.nim +++ b/lib/pure/json.nim @@ -951,7 +951,8 @@ proc pretty*(node: JsonNode, indent = 2): string = proc toUgly*(result: var string, node: JsonNode) = ## Converts `node` to its JSON Representation, without - ## regard for human readability. + ## regard for human readability. Meant to improve '$' string + ## conversion performance. var comma = false case node.kind: of JArray: From 11457bc63b53d1ba7215a19fb8663ec215a2f151 Mon Sep 17 00:00:00 2001 From: onionhammer Date: Sat, 16 May 2015 12:35:55 -0500 Subject: [PATCH 0237/1263] Fixed indentation (2 spaces) --- lib/pure/json.nim | 42 +++++++++++++++++++++--------------------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/lib/pure/json.nim b/lib/pure/json.nim index 8389411c2..afb5fc1b1 100644 --- a/lib/pure/json.nim +++ b/lib/pure/json.nim @@ -956,34 +956,34 @@ proc toUgly*(result: var string, node: JsonNode) = var comma = false case node.kind: of JArray: - result.add "[" - for child in node.elems: - if comma: result.add "," - else: comma = true - result.toUgly child - result.add "]" + result.add "[" + for child in node.elems: + if comma: result.add "," + else: comma = true + result.toUgly child + result.add "]" of JObject: - result.add "{" - for key, value in items(node.fields): - if comma: result.add "," - else: comma = true - result.add "\"" - result.add key.escapeJson() - result.add "\":" - result.toUgly value + result.add "{" + for key, value in items(node.fields): + if comma: result.add "," + else: comma = true + result.add "\"" + result.add key.escapeJson() + result.add "\":" + result.toUgly value result.add "}" of JString: - result.add "\"" - result.add node.str.escapeJson() - result.add "\"" + result.add "\"" + result.add node.str.escapeJson() + result.add "\"" of JInt: - result.add($node.num) + result.add($node.num) of JFloat: - result.add($node.fnum) + result.add($node.fnum) of JBool: - result.add(if node.bval: "true" else: "false") + result.add(if node.bval: "true" else: "false") of JNull: - result.add "null" + result.add "null" proc toUgly*(node: JsonNode): string = ## Converts `node` to its JSON Representation on one line. From 30aed77d0419916b724205b519fe54a47be6284b Mon Sep 17 00:00:00 2001 From: onionhammer Date: Sat, 16 May 2015 12:37:07 -0500 Subject: [PATCH 0238/1263] Fixed indentation (2 spaces) part 2 --- lib/pure/json.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/pure/json.nim b/lib/pure/json.nim index afb5fc1b1..7ab4d9ad9 100644 --- a/lib/pure/json.nim +++ b/lib/pure/json.nim @@ -971,7 +971,7 @@ proc toUgly*(result: var string, node: JsonNode) = result.add key.escapeJson() result.add "\":" result.toUgly value - result.add "}" + result.add "}" of JString: result.add "\"" result.add node.str.escapeJson() From 939c0a6bb8c21c036bdb7bc44cf866b947b11696 Mon Sep 17 00:00:00 2001 From: transfuturist Date: Fri, 15 May 2015 21:55:06 -0700 Subject: [PATCH 0239/1263] NimNode needs an items iterator to be used nicely in for statements --- lib/core/macros.nim | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/lib/core/macros.nim b/lib/core/macros.nim index 35f0f61c1..becfd2d94 100644 --- a/lib/core/macros.nim +++ b/lib/core/macros.nim @@ -712,6 +712,10 @@ iterator children*(n: NimNode): NimNode {.inline.}= for i in 0 .. high(n): yield n[i] +iterator items*(n: NimNode): NimNode {.inline.}= + for i in 0 .. high(n): + yield n[i] + template findChild*(n: NimNode; cond: expr): NimNode {. immediate, dirty.} = ## Find the first child node matching condition (or nil). From d1230497ddecdc779fa2b275b2ddb74b1f6a1ba1 Mon Sep 17 00:00:00 2001 From: pdw Date: Sat, 16 May 2015 14:35:41 -0500 Subject: [PATCH 0240/1263] Updated with breaking changes --- web/news.txt | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/web/news.txt b/web/news.txt index 9719fb8d7..097267d11 100644 --- a/web/news.txt +++ b/web/news.txt @@ -9,6 +9,10 @@ News Changes affecting backwards compatibility ----------------------------------------- + - The ``miliseconds`` property of ``times.TimeInterval`` is now ``milliseconds``. + Code accessing that property is deprecated and code using ``miliseconds`` + during object initialization or as a named parameter of ``initInterval()`` + will need to be updated. Language Additions ------------------ From 7500eed0cfb56a1fc4812d57ac301ee9b7f50026 Mon Sep 17 00:00:00 2001 From: transfuturist Date: Sat, 16 May 2015 17:26:47 -0700 Subject: [PATCH 0241/1263] Better solution: deprecation --- lib/core/macros.nim | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/lib/core/macros.nim b/lib/core/macros.nim index becfd2d94..48e4566b3 100644 --- a/lib/core/macros.nim +++ b/lib/core/macros.nim @@ -708,14 +708,12 @@ proc `$`*(node: NimNode): string {.compileTime.} = proc ident*(name: string): NimNode {.compileTime,inline.} = newIdentNode(name) ## Create a new ident node from a string -iterator children*(n: NimNode): NimNode {.inline.}= - for i in 0 .. high(n): - yield n[i] - iterator items*(n: NimNode): NimNode {.inline.}= for i in 0 .. high(n): yield n[i] +{.deprecated: [children: items].} + template findChild*(n: NimNode; cond: expr): NimNode {. immediate, dirty.} = ## Find the first child node matching condition (or nil). From 3d80fcb8c6ff1e03922f517681efad65d79563fb Mon Sep 17 00:00:00 2001 From: transfuturist Date: Sat, 16 May 2015 17:50:01 -0700 Subject: [PATCH 0242/1263] Add value check for NimNode items --- lib/core/macros.nim | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/lib/core/macros.nim b/lib/core/macros.nim index 48e4566b3..41998250e 100644 --- a/lib/core/macros.nim +++ b/lib/core/macros.nim @@ -708,9 +708,10 @@ proc `$`*(node: NimNode): string {.compileTime.} = proc ident*(name: string): NimNode {.compileTime,inline.} = newIdentNode(name) ## Create a new ident node from a string -iterator items*(n: NimNode): NimNode {.inline.}= - for i in 0 .. high(n): - yield n[i] +iterator items*(n: NimNode): NimNode {.inline.} = + if n[0] != nil: + for i in 0 .. high(n): + yield n[i] {.deprecated: [children: items].} From 1d47617d1b72c642fac5543f38aa24330b0f9a19 Mon Sep 17 00:00:00 2001 From: Adam Strzelecki Date: Wed, 13 May 2015 22:32:10 +0200 Subject: [PATCH 0243/1263] Macros: Introduce getType(t: typedesc): NimNode Since typedesc are exception in macros and they are not implicitly converted to NimNode on macro call, we need some means to perform such conversion on demand. Fortunately it is as simple as declaring new magic "NGetType" proc with typedesc parameter. NOTE: Keeping actual macro exceptional behavior for typedesc is important, since it allows passing typedesc macro parameter to other procs or macros expecting type parameter. If typedesc parameter was implicitly converted, then we would lost this ability. --- lib/core/macros.nim | 6 ++++++ tests/macros/tgettype.nim | 20 ++++++++++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 tests/macros/tgettype.nim diff --git a/lib/core/macros.nim b/lib/core/macros.nim index 35f0f61c1..7e6e4ccc9 100644 --- a/lib/core/macros.nim +++ b/lib/core/macros.nim @@ -177,6 +177,12 @@ proc getType*(n: NimNode): NimNode {.magic: "NGetType", noSideEffect.} ## resolve recursive types, you have to call 'getType' again. To see what ## kind of type it is, call `typeKind` on getType's result. +proc getType*(n: typedesc): NimNode {.magic: "NGetType", noSideEffect.} + ## Returns the Nim type node for given type. This can be used to turn macro + ## typedesc parameter into proper NimNode representing type, since typedesc + ## are an exception in macro calls - they are not mapped implicitly to + ## NimNode like any other arguments. + proc typeKind*(n: NimNode): NimTypeKind {.magic: "NGetType", noSideEffect.} ## Returns the type kind of the node 'n' that should represent a type, that ## means the node should have been obtained via `getType`. diff --git a/tests/macros/tgettype.nim b/tests/macros/tgettype.nim new file mode 100644 index 000000000..0eab6c0a0 --- /dev/null +++ b/tests/macros/tgettype.nim @@ -0,0 +1,20 @@ +discard """ +msg: '''ObjectTy(Sym(Model), RecList(Sym(name), Sym(password))) +BracketExpr(Sym(typeDesc), Sym(User))''' +""" +import strutils, macros + +type + Model = object of RootObj + User = object of Model + name : string + password : string + +macro testUser: expr = + return newLit(User.getType.lispRepr) + +macro testGeneric(T: typedesc[Model]): expr = + return newLit(T.getType.lispRepr) + +echo testUser +echo User.testGeneric From 2613110015d52ffdcb6ecfd6f7dbb3369016c252 Mon Sep 17 00:00:00 2001 From: def Date: Sun, 17 May 2015 16:10:46 +0200 Subject: [PATCH 0244/1263] Use gProjectIsStdin instead --- compiler/modules.nim | 2 +- compiler/nim.nim | 1 + compiler/options.nim | 1 + 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/compiler/modules.nim b/compiler/modules.nim index 0371f34f3..2fa46f356 100644 --- a/compiler/modules.nim +++ b/compiler/modules.nim @@ -148,7 +148,7 @@ proc compileModule*(fileIdx: int32, flags: TSymFlags): PSym = return else: result.id = getID() - if sfMainModule in flags and gProjectName == "-": + if sfMainModule in flags and gProjectIsStdin: processModule(result, llStreamOpen(stdin), rd) else: processModule(result, nil, rd) diff --git a/compiler/nim.nim b/compiler/nim.nim index f04c616fc..89db22e8f 100644 --- a/compiler/nim.nim +++ b/compiler/nim.nim @@ -42,6 +42,7 @@ proc handleCmdLine() = gProjectName = "stdinfile" gProjectFull = "stdinfile" gProjectPath = getCurrentDir() + gProjectIsStdin = true elif gProjectName != "": try: gProjectFull = canonicalizePath(gProjectName) diff --git a/compiler/options.nim b/compiler/options.nim index d07342fce..b3060a180 100644 --- a/compiler/options.nim +++ b/compiler/options.nim @@ -149,6 +149,7 @@ var gProjectName* = "" # holds a name like 'nimrod' gProjectPath* = "" # holds a path like /home/alice/projects/nimrod/compiler/ gProjectFull* = "" # projectPath/projectName + gProjectIsStdin* = false # whether we're compiling from stdin gProjectMainIdx*: int32 # the canonical path id of the main module nimcacheDir* = "" command* = "" # the main command (e.g. cc, check, scan, etc) From 46264a0674091a1838e403d44d02cb919fa7a661 Mon Sep 17 00:00:00 2001 From: def Date: Sun, 17 May 2015 16:13:06 +0200 Subject: [PATCH 0245/1263] Make a few json procs inline, improves performance significantly --- lib/pure/json.nim | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/lib/pure/json.nim b/lib/pure/json.nim index 5d824d6f8..91812f603 100644 --- a/lib/pure/json.nim +++ b/lib/pure/json.nim @@ -761,7 +761,7 @@ proc len*(n: JsonNode): int = of JObject: result = n.fields.len else: discard -proc `[]`*(node: JsonNode, name: string): JsonNode = +proc `[]`*(node: JsonNode, name: string): JsonNode {.inline.} = ## Gets a field from a `JObject`, which must not be nil. ## If the value at `name` does not exist, returns nil assert(not isNil(node)) @@ -771,7 +771,7 @@ proc `[]`*(node: JsonNode, name: string): JsonNode = return item return nil -proc `[]`*(node: JsonNode, index: int): JsonNode = +proc `[]`*(node: JsonNode, index: int): JsonNode {.inline.} = ## Gets the node at `index` in an Array. Result is undefined if `index` ## is out of bounds assert(not isNil(node)) @@ -799,7 +799,7 @@ proc add*(obj: JsonNode, key: string, val: JsonNode) = assert obj.kind == JObject obj.fields.add((key, val)) -proc `[]=`*(obj: JsonNode, key: string, val: JsonNode) = +proc `[]=`*(obj: JsonNode, key: string, val: JsonNode) {.inline.} = ## Sets a field from a `JObject`. Performs a check for duplicate keys. assert(obj.kind == JObject) for i in 0..obj.fields.len-1: @@ -815,7 +815,7 @@ proc `{}`*(node: JsonNode, keys: varargs[string]): JsonNode = result = node for key in keys: if isNil(result) or result.kind!=JObject: - return nil + return nil result=result[key] proc `{}=`*(node: JsonNode, keys: varargs[string], value: JsonNode) = @@ -1153,7 +1153,7 @@ when false: when isMainModule: #var node = parse("{ \"test\": null }") #echo(node.existsKey("test56")) - + var parsed = parseFile("tests/testdata/jsontest.json") var parsed2 = parseFile("tests/testdata/jsontest2.json") @@ -1192,17 +1192,17 @@ when isMainModule: except: assert(false, "EInvalidIndex thrown for valid index") - assert(testJson{"b"}.str=="asd", "Couldn't fetch a singly nested key with {}") - assert(isNil(testJson{"nonexistent"}), "Non-existent keys should return nil") + assert(testJson{"b"}.str=="asd", "Couldn't fetch a singly nested key with {}") + assert(isNil(testJson{"nonexistent"}), "Non-existent keys should return nil") assert(parsed2{"repository", "description"}.str=="IRC Library for Haskell", "Couldn't fetch via multiply nested key using {}") assert(isNil(testJson{"a", "b"}), "Indexing through a list should return nil") assert(isNil(testJson{"a", "b"}), "Indexing through a list should return nil") assert(testJson{"a"}==parseJson"[1, 2, 3, 4]", "Didn't return a non-JObject when there was one to be found") assert(isNil(parseJson("[1, 2, 3]"){"foo"}), "Indexing directly into a list should return nil") - + # Generator: var j = %* [{"name": "John", "age": 30}, {"name": "Susan", "age": 31}] - assert j == %[%{"name": %"John", "age": %30}, %{"name": %"Susan", "age": %31}] + assert j == %[%{"name": %"John", "age": %30}, %{"name": %"Susan", "age": %31}] var j2 = %* [ @@ -1230,7 +1230,7 @@ when isMainModule: } ] assert j3 == %[%{"name": %"John", "age": %30}, %{"name": %"Susan", "age": %31}] - + when not defined(testing): discard """ while true: From d937b4cd850b3ee93815622609f7cd1d8a38d484 Mon Sep 17 00:00:00 2001 From: Dominik Picheta Date: Sun, 17 May 2015 18:18:33 +0100 Subject: [PATCH 0246/1263] Removes superfluous toUgly, documents toUgly better. --- lib/pure/json.nim | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/lib/pure/json.nim b/lib/pure/json.nim index 7ab4d9ad9..4f7f11108 100644 --- a/lib/pure/json.nim +++ b/lib/pure/json.nim @@ -951,8 +951,11 @@ proc pretty*(node: JsonNode, indent = 2): string = proc toUgly*(result: var string, node: JsonNode) = ## Converts `node` to its JSON Representation, without - ## regard for human readability. Meant to improve '$' string + ## regard for human readability. Meant to improve ``$`` string ## conversion performance. + ## + ## This provides higher efficiency than the ``toPretty`` procedure as it + ## does **not** attempt to format the resulting JSON to make it human readable. var comma = false case node.kind: of JArray: @@ -985,11 +988,6 @@ proc toUgly*(result: var string, node: JsonNode) = of JNull: result.add "null" -proc toUgly*(node: JsonNode): string = - ## Converts `node` to its JSON Representation on one line. - result = newStringOfCap(node.len shl 1) - toUgly(result, node) - proc `$`*(node: JsonNode): string = ## Converts `node` to its JSON Representation on one line. result = newStringOfCap(node.len shl 1) From bc2aaea853d3bd1ad7641bf32335e3725f03afed Mon Sep 17 00:00:00 2001 From: transfuturist Date: Sun, 17 May 2015 15:05:26 -0700 Subject: [PATCH 0247/1263] Change check for NimNode items to node kind --- lib/core/macros.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/core/macros.nim b/lib/core/macros.nim index 41998250e..0bfdffc5d 100644 --- a/lib/core/macros.nim +++ b/lib/core/macros.nim @@ -709,7 +709,7 @@ proc ident*(name: string): NimNode {.compileTime,inline.} = newIdentNode(name) ## Create a new ident node from a string iterator items*(n: NimNode): NimNode {.inline.} = - if n[0] != nil: + if n.kind in {nnkType, nnkMetaNode .. nnkReturnToken}: for i in 0 .. high(n): yield n[i] From 51de44be7954a1c3f3499c5a2a6adcaceec33e3f Mon Sep 17 00:00:00 2001 From: def Date: Mon, 18 May 2015 21:31:24 +0200 Subject: [PATCH 0248/1263] Make intVal work for uint literals in the VM --- compiler/vm.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/vm.nim b/compiler/vm.nim index 1c6c9a30b..560c38d14 100644 --- a/compiler/vm.nim +++ b/compiler/vm.nim @@ -1121,7 +1121,7 @@ proc rawExecute(c: PCtx, start: int, tos: PStackFrame): TFullReg = decodeB(rkInt) let a = regs[rb].node case a.kind - of nkCharLit..nkInt64Lit: regs[ra].intVal = a.intVal + of nkCharLit..nkUInt64Lit: regs[ra].intVal = a.intVal else: stackTrace(c, tos, pc, errFieldXNotFound, "intVal") of opcNFloatVal: decodeB(rkFloat) From 2076e14a09ea9eb03fd389e1124a7c1847b7d584 Mon Sep 17 00:00:00 2001 From: def Date: Mon, 18 May 2015 21:32:29 +0200 Subject: [PATCH 0249/1263] Update ast spec about uint literals --- compiler/vm.nim | 2 +- doc/astspec.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/compiler/vm.nim b/compiler/vm.nim index 560c38d14..e49bed522 100644 --- a/compiler/vm.nim +++ b/compiler/vm.nim @@ -1276,7 +1276,7 @@ proc rawExecute(c: PCtx, start: int, tos: PStackFrame): TFullReg = of opcNSetIntVal: decodeB(rkNode) var dest = regs[ra].node - if dest.kind in {nkCharLit..nkInt64Lit} and + if dest.kind in {nkCharLit..nkUInt64Lit} and regs[rb].kind in {rkInt}: dest.intVal = regs[rb].intVal else: diff --git a/doc/astspec.txt b/doc/astspec.txt index 4c27272e2..68bb9f1cd 100644 --- a/doc/astspec.txt +++ b/doc/astspec.txt @@ -23,7 +23,7 @@ contains: case kind: NimNodeKind ## the node's kind of nnkNone, nnkEmpty, nnkNilLit: discard ## node contains no additional fields - of nnkCharLit..nnkInt64Lit: + of nnkCharLit..nnkUInt64Lit: intVal: biggestInt ## the int literal of nnkFloatLit..nnkFloat64Lit: floatVal: biggestFloat ## the float literal From 59e95c015ef19512ab9ded6f26956782ea3b61b3 Mon Sep 17 00:00:00 2001 From: Dominik Picheta Date: Mon, 18 May 2015 21:57:59 +0100 Subject: [PATCH 0250/1263] Fixes problems introduced by #2738. Closes 2755. --- lib/pure/json.nim | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/lib/pure/json.nim b/lib/pure/json.nim index 7d22e897b..518572be3 100644 --- a/lib/pure/json.nim +++ b/lib/pure/json.nim @@ -970,15 +970,12 @@ proc toUgly*(result: var string, node: JsonNode) = for key, value in items(node.fields): if comma: result.add "," else: comma = true - result.add "\"" result.add key.escapeJson() - result.add "\":" + result.add ":" result.toUgly value result.add "}" of JString: - result.add "\"" result.add node.str.escapeJson() - result.add "\"" of JInt: result.add($node.num) of JFloat: @@ -1215,6 +1212,11 @@ when isMainModule: testJson{["c", "d"]} = %true assert(testJson["c"]["d"].bval) + # test `$` + let stringified = $testJson + let parsedAgain = parseJson(stringified) + assert(parsedAgain["b"].str == "asd") + # Bounds checking try: let a = testJson["a"][9] From 7a2dce80126dd9397eed8c4461e1aefa33cb3185 Mon Sep 17 00:00:00 2001 From: Koala Zen Date: Fri, 8 May 2015 09:55:57 -0700 Subject: [PATCH 0251/1263] refactored lowerBound in algorithm.nim --- lib/pure/algorithm.nim | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/lib/pure/algorithm.nim b/lib/pure/algorithm.nim index f7ccb9234..e363b6443 100644 --- a/lib/pure/algorithm.nim +++ b/lib/pure/algorithm.nim @@ -88,16 +88,13 @@ proc lowerBound*[T](a: openArray[T], key: T, cmp: proc(x,y: T): int {.closure.}) ## arr.insert(4, arr.lowerBound(4)) ## `after running the above arr is `[1,2,3,4,5,6,7,8,9]` result = a.low - var pos = result - var count, step: int - count = a.high - a.low + 1 + var count = a.high - a.low + 1 + var step, pos: int while count != 0: - pos = result step = count div 2 - pos += step + pos = result + step if cmp(a[pos], key) < 0: - pos.inc - result = pos + result = pos + 1 count -= step + 1 else: count = step @@ -322,3 +319,16 @@ proc prevPermutation*[T](x: var openarray[T]): bool {.discardable.} = swap x[i-1], x[j] result = true + +when isMainModule: + # Tests for lowerBound + var arr = @[1,2,3,5,6,7,8,9] + assert arr.lowerBound(0) == 0 + assert arr.lowerBound(4) == 3 + assert arr.lowerBound(5) == 3 + assert arr.lowerBound(10) == 8 + arr = @[1,5,10] + assert arr.lowerBound(4) == 1 + assert arr.lowerBound(5) == 1 + assert arr.lowerBound(6) == 2 + From 4439b00b19aa03a51c3419056c074f620a7e61f6 Mon Sep 17 00:00:00 2001 From: yglukhov Date: Tue, 19 May 2015 13:41:18 +0300 Subject: [PATCH 0252/1263] Fixed JS call codegen, when first parameters are compile-time. --- compiler/jsgen.nim | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/compiler/jsgen.nim b/compiler/jsgen.nim index 704713243..5c7071498 100644 --- a/compiler/jsgen.nim +++ b/compiler/jsgen.nim @@ -1052,11 +1052,13 @@ proc genArg(p: PProc, n: PNode, r: var TCompRes) = proc genArgs(p: PProc, n: PNode, r: var TCompRes) = add(r.res, "(") + var hasArgs = false for i in countup(1, sonsLen(n) - 1): let it = n.sons[i] if it.typ.isCompileTimeOnly: continue - if i > 1: add(r.res, ", ") + if hasArgs: add(r.res, ", ") genArg(p, it, r) + hasArgs = true add(r.res, ")") r.kind = resExpr From 32ebcfa8ff7cafc34ba60c101e6fe6f59b5be52d Mon Sep 17 00:00:00 2001 From: Oleh Prypin Date: Sat, 11 Apr 2015 04:49:40 +0300 Subject: [PATCH 0253/1263] Implement optionals module --- lib/pure/optionals.nim | 262 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 262 insertions(+) create mode 100644 lib/pure/optionals.nim diff --git a/lib/pure/optionals.nim b/lib/pure/optionals.nim new file mode 100644 index 000000000..ef0b6e108 --- /dev/null +++ b/lib/pure/optionals.nim @@ -0,0 +1,262 @@ +# +# +# Nim's Runtime Library +# (c) Copyright 2015 Nim Contributors +# +# See the file "copying.txt", included in this +# distribution, for details about the copyright. +# + +## :Author: Oleh Prypin +## +## Abstract +## ======== +## +## This module implements types which encapsulate an optional value. +## +## A value of type ``?T`` (``Maybe[T]``) either contains a value `x` +## (represented as ``just(x)``) or is empty (``nothing(T)``). +## +## This can be useful when you have a value that can be present or not. +## The absence of a value is often represented by ``nil``, but it is not always +## available, nor is it always a good solution. +## +## +## Tutorial +## ======== +## +## Let's start with an example: a procedure that finds the index of a character +## in a string. +## +## .. code-block:: nim +## +## import optionals +## +## proc find(haystack: string, needle: char): ?int = +## for i, c in haystack: +## if c == needle: +## return just i +## return nothing(int) # This line is actually optional, +## # because the default is empty +## +## The ``?`` operator (template) is a shortcut for ``Maybe[T]``. +## +## .. code-block:: nim +## +## try: +## assert("abc".find('c')[] == 2) # Immediately extract the value +## except FieldError: # If there is no value +## assert false # This will not be reached, because the value is present +## +## The ``[]`` operator demonstrated above returns the underlying value, or +## raises ``FieldError`` if there is no value. There is another option for +## obtaining the value: ``val``, but you must only use it when you are +## absolutely sure the value is present (e.g. after checking ``has``). If you do +## not care about the tiny overhead that ``[]`` causes, you should simply never +## use ``val``. +## +## How to deal with an absence of a value: +## +## .. code-block:: nim +## +## let result = "team".find('i') +## +## # Nothing was found, so the result is `nothing`. +## assert(result == nothing(int)) +## # It has no value: +## assert(result.has == false) +## # A different way to write it: +## assert(not result) +## +## try: +## echo result[] +## assert(false) # This will not be reached +## except FieldError: # Because an exception is raised +## discard +## +## Now let's try out the extraction template. It returns whether a value +## is present and injects the value into a variable. It is meant to be used in +## a conditional. +## +## .. code-block:: nim +## +## if pos ?= "nim".find('i'): +## assert(pos is int) # This is a normal integer, no tricks. +## echo "Match found at position ", pos +## else: +## assert(false) # This will not be reached +## +## Or maybe you want to get the behavior of the standard library's ``find``, +## which returns `-1` if nothing was found. +## +## .. code-block:: nim +## +## assert(("team".find('i') or -1) == -1) +## assert(("nim".find('i') or -1) == 1) + +import typetraits + + +type + Maybe*[T] = object + ## An optional type that stores its value and state separately in a boolean. + val: T + has: bool + + +template `?`*(T: typedesc): typedesc = + ## ``?T`` is equivalent to ``Maybe[T]``. + Maybe[T] + + +proc just*[T](val: T): Maybe[T] = + ## Returns a ``Maybe`` that has this value. + result.has = true + result.val = val + +proc nothing*(T: typedesc): Maybe[T] = + ## Returns a ``Maybe`` for this type that has no value. + result.has = false + + +proc has*(maybe: Maybe): bool = + ## Returns ``true`` if `maybe` isn't `nothing`. + maybe.has + +converter toBool*(maybe: Maybe): bool = + ## Same as ``has``. Allows to use a ``Maybe`` in boolean context. + maybe.has + + +proc unsafeVal*[T](maybe: Maybe[T]): T = + ## Returns the value of a `just`. Behavior is undefined for `nothing`. + assert maybe.has, "nothing has no val" + maybe.val + +proc `[]`*[T](maybe: Maybe[T]): T = + ## Returns the value of `maybe`. Raises ``FieldError`` if it is `nothing`. + if not maybe: + raise newException(FieldError, "Can't obtain a value from a `nothing`") + maybe.val + + +template `or`*[T](maybe: Maybe[T], default: T): T = + ## Returns the value of `maybe`, or `default` if it is `nothing`. + if maybe: maybe.val + else: default + +template `or`*[T](a, b: Maybe[T]): Maybe[T] = + ## Returns `a` if it is `just`, otherwise `b`. + if a: a + else: b + +template `?=`*(into: expr, maybe: Maybe): bool = + ## Returns ``true`` if `maybe` isn't `nothing`. + ## + ## Injects a variable with the name specified by the argument `into` + ## with the value of `maybe`, or its type's default value if it is `nothing`. + ## + ## .. code-block:: nim + ## + ## proc message(): ?string = + ## just "Hello" + ## + ## if m ?= message(): + ## echo m + var into {.inject.}: type(maybe.val) + if maybe: + into = maybe.val + maybe + + +proc `==`*(a, b: Maybe): bool = + ## Returns ``true`` if both ``Maybe`` are `nothing`, + ## or if they have equal values + (a.has and b.has and a.val == b.val) or (not a.has and not b.has) + +proc `$`[T](maybe: Maybe[T]): string = + ## Converts to string: `"just(value)"` or `"nothing(type)"` + if maybe.has: + "just(" & $maybe.val & ")" + else: + "nothing(" & T.name & ")" + + +when isMainModule: + template expect(E: expr, body: stmt) = + try: + body + assert false, E.type.name & " not raised" + except E: + discard + + + block: # example + proc find(haystack: string, needle: char): ?int = + for i, c in haystack: + if c == needle: + return just i + + assert("abc".find('c')[] == 2) + + let result = "team".find('i') + + assert result == nothing(int) + assert result.has == false + + if pos ?= "nim".find('i'): + assert pos is int + assert pos == 1 + else: + assert false + + assert(("team".find('i') or -1) == -1) + assert(("nim".find('i') or -1) == 1) + + block: # just + assert just(6)[] == 6 + assert just("a").unsafeVal == "a" + assert just(6).has + assert just("a") + + block: # nothing + expect FieldError: + discard nothing(int)[] + assert(not nothing(int).has) + assert(not nothing(string)) + + block: # equality + assert just("a") == just("a") + assert just(7) != just(6) + assert just("a") != nothing(string) + assert nothing(int) == nothing(int) + + when compiles(just("a") == just(5)): + assert false + when compiles(nothing(string) == nothing(int)): + assert false + + block: # stringification + assert "just(7)" == $just(7) + assert "nothing(int)" == $nothing(int) + + block: # or + assert just(1) or just(2) == just(1) + assert nothing(string) or just("a") == just("a") + assert nothing(int) or nothing(int) == nothing(int) + assert just(5) or 2 == 2 + assert nothing(string) or "a" == "a" + + when compiles(just(1) or "2"): + assert false + when compiles(nothing(int) or just("a")): + assert false + + block: # extraction template + if a ?= just(5): + assert a == 5 + else: + assert false + + if b ?= nothing(string): + assert false From a66dcd9d945dbc48745a6f32b097150bb4574145 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Tue, 19 May 2015 16:52:24 -0400 Subject: [PATCH 0254/1263] Simplify optionals module --- lib/pure/optionals.nim | 216 ++++++++++++----------------------------- 1 file changed, 60 insertions(+), 156 deletions(-) diff --git a/lib/pure/optionals.nim b/lib/pure/optionals.nim index ef0b6e108..fb76c9037 100644 --- a/lib/pure/optionals.nim +++ b/lib/pure/optionals.nim @@ -14,11 +14,11 @@ ## ## This module implements types which encapsulate an optional value. ## -## A value of type ``?T`` (``Maybe[T]``) either contains a value `x` -## (represented as ``just(x)``) or is empty (``nothing(T)``). +## A value of type ``Option[T]`` either contains a value `x` (represented as +## ``some(x)``) or is empty (``none(T)``). ## -## This can be useful when you have a value that can be present or not. -## The absence of a value is often represented by ``nil``, but it is not always +## This can be useful when you have a value that can be present or not. The +## absence of a value is often represented by ``nil``, but it is not always ## available, nor is it always a good solution. ## ## @@ -32,28 +32,26 @@ ## ## import optionals ## -## proc find(haystack: string, needle: char): ?int = +## proc find(haystack: string, needle: char): Option[int] = ## for i, c in haystack: ## if c == needle: -## return just i -## return nothing(int) # This line is actually optional, -## # because the default is empty -## -## The ``?`` operator (template) is a shortcut for ``Maybe[T]``. +## return some(i) +## return none(int) # This line is actually optional, +## # because the default is empty ## ## .. code-block:: nim ## ## try: -## assert("abc".find('c')[] == 2) # Immediately extract the value +## assert("abc".find('c').get() == 2) # Immediately extract the value ## except FieldError: # If there is no value ## assert false # This will not be reached, because the value is present ## -## The ``[]`` operator demonstrated above returns the underlying value, or +## The ``get`` operation demonstrated above returns the underlying value, or ## raises ``FieldError`` if there is no value. There is another option for -## obtaining the value: ``val``, but you must only use it when you are -## absolutely sure the value is present (e.g. after checking ``has``). If you do -## not care about the tiny overhead that ``[]`` causes, you should simply never -## use ``val``. +## obtaining the value: ``unsafeGet``, but you must only use it when you are +## absolutely sure the value is present (e.g. after checking ``isSome``). If +## you do not care about the tiny overhead that ``get`` causes, you should +## simply never use ``unsafeGet``. ## ## How to deal with an absence of a value: ## @@ -61,126 +59,62 @@ ## ## let result = "team".find('i') ## -## # Nothing was found, so the result is `nothing`. -## assert(result == nothing(int)) +## # Nothing was found, so the result is `none`. +## assert(result == none(int)) ## # It has no value: -## assert(result.has == false) -## # A different way to write it: -## assert(not result) +## assert(result.isNone) ## ## try: -## echo result[] +## echo result.get() ## assert(false) # This will not be reached ## except FieldError: # Because an exception is raised ## discard -## -## Now let's try out the extraction template. It returns whether a value -## is present and injects the value into a variable. It is meant to be used in -## a conditional. -## -## .. code-block:: nim -## -## if pos ?= "nim".find('i'): -## assert(pos is int) # This is a normal integer, no tricks. -## echo "Match found at position ", pos -## else: -## assert(false) # This will not be reached -## -## Or maybe you want to get the behavior of the standard library's ``find``, -## which returns `-1` if nothing was found. -## -## .. code-block:: nim -## -## assert(("team".find('i') or -1) == -1) -## assert(("nim".find('i') or -1) == 1) import typetraits type - Maybe*[T] = object + Option*[T] = object ## An optional type that stores its value and state separately in a boolean. val: T has: bool -template `?`*(T: typedesc): typedesc = - ## ``?T`` is equivalent to ``Maybe[T]``. - Maybe[T] - - -proc just*[T](val: T): Maybe[T] = - ## Returns a ``Maybe`` that has this value. +proc some*[T](val: T): Option[T] = + ## Returns a ``Option`` that has this value. result.has = true result.val = val -proc nothing*(T: typedesc): Maybe[T] = - ## Returns a ``Maybe`` for this type that has no value. +proc none*(T: typedesc): Option[T] = + ## Returns a ``Option`` for this type that has no value. result.has = false -proc has*(maybe: Maybe): bool = - ## Returns ``true`` if `maybe` isn't `nothing`. - maybe.has +proc isSome*[T](self: Option[T]): bool = + self.has -converter toBool*(maybe: Maybe): bool = - ## Same as ``has``. Allows to use a ``Maybe`` in boolean context. - maybe.has +proc isNone*[T](self: Option[T]): bool = + not self.has -proc unsafeVal*[T](maybe: Maybe[T]): T = - ## Returns the value of a `just`. Behavior is undefined for `nothing`. - assert maybe.has, "nothing has no val" - maybe.val +proc unsafeGet*[T](self: Option[T]): T = + ## Returns the value of a `just`. Behavior is undefined for `none`. + assert self.isSome + self.val -proc `[]`*[T](maybe: Maybe[T]): T = - ## Returns the value of `maybe`. Raises ``FieldError`` if it is `nothing`. - if not maybe: - raise newException(FieldError, "Can't obtain a value from a `nothing`") - maybe.val +proc get*[T](self: Option[T]): T = + ## Returns contents of the Option. If it is none, then an exception is + ## thrown. + if self.isNone: + raise newException(FieldError, "Can't obtain a value from a `none`") + self.val -template `or`*[T](maybe: Maybe[T], default: T): T = - ## Returns the value of `maybe`, or `default` if it is `nothing`. - if maybe: maybe.val - else: default - -template `or`*[T](a, b: Maybe[T]): Maybe[T] = - ## Returns `a` if it is `just`, otherwise `b`. - if a: a - else: b - -template `?=`*(into: expr, maybe: Maybe): bool = - ## Returns ``true`` if `maybe` isn't `nothing`. - ## - ## Injects a variable with the name specified by the argument `into` - ## with the value of `maybe`, or its type's default value if it is `nothing`. - ## - ## .. code-block:: nim - ## - ## proc message(): ?string = - ## just "Hello" - ## - ## if m ?= message(): - ## echo m - var into {.inject.}: type(maybe.val) - if maybe: - into = maybe.val - maybe - - -proc `==`*(a, b: Maybe): bool = - ## Returns ``true`` if both ``Maybe`` are `nothing`, +proc `==`*(a, b: Option): bool = + ## Returns ``true`` if both ``Option``s are `none`, ## or if they have equal values (a.has and b.has and a.val == b.val) or (not a.has and not b.has) -proc `$`[T](maybe: Maybe[T]): string = - ## Converts to string: `"just(value)"` or `"nothing(type)"` - if maybe.has: - "just(" & $maybe.val & ")" - else: - "nothing(" & T.name & ")" - when isMainModule: template expect(E: expr, body: stmt) = @@ -192,71 +126,41 @@ when isMainModule: block: # example - proc find(haystack: string, needle: char): ?int = + proc find(haystack: string, needle: char): Option[int] = for i, c in haystack: if c == needle: - return just i + return some i - assert("abc".find('c')[] == 2) + assert("abc".find('c').get() == 2) let result = "team".find('i') - assert result == nothing(int) + assert result == none(int) assert result.has == false - if pos ?= "nim".find('i'): - assert pos is int - assert pos == 1 - else: - assert false + block: # some + assert some(6).get() == 6 + assert some("a").unsafeGet() == "a" + assert some(6).isSome + assert some("a").isSome - assert(("team".find('i') or -1) == -1) - assert(("nim".find('i') or -1) == 1) - - block: # just - assert just(6)[] == 6 - assert just("a").unsafeVal == "a" - assert just(6).has - assert just("a") - - block: # nothing + block: # none expect FieldError: - discard nothing(int)[] - assert(not nothing(int).has) - assert(not nothing(string)) + discard none(int).get() + assert(none(int).isNone) + assert(not none(string).isSome) block: # equality - assert just("a") == just("a") - assert just(7) != just(6) - assert just("a") != nothing(string) - assert nothing(int) == nothing(int) + assert some("a") == some("a") + assert some(7) != some(6) + assert some("a") != none(string) + assert none(int) == none(int) - when compiles(just("a") == just(5)): + when compiles(some("a") == some(5)): assert false - when compiles(nothing(string) == nothing(int)): + when compiles(none(string) == none(int)): assert false block: # stringification - assert "just(7)" == $just(7) - assert "nothing(int)" == $nothing(int) - - block: # or - assert just(1) or just(2) == just(1) - assert nothing(string) or just("a") == just("a") - assert nothing(int) or nothing(int) == nothing(int) - assert just(5) or 2 == 2 - assert nothing(string) or "a" == "a" - - when compiles(just(1) or "2"): - assert false - when compiles(nothing(int) or just("a")): - assert false - - block: # extraction template - if a ?= just(5): - assert a == 5 - else: - assert false - - if b ?= nothing(string): - assert false + assert "some(7)" == $some(7) + assert "none(int)" == $none(int) From ae0c8573f2ac1840373948b086e1f4d4c6a4180f Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Tue, 19 May 2015 16:58:39 -0400 Subject: [PATCH 0255/1263] Simplify optionals tests --- lib/pure/optionals.nim | 71 ++++++++++++++++++++---------------------- 1 file changed, 33 insertions(+), 38 deletions(-) diff --git a/lib/pure/optionals.nim b/lib/pure/optionals.nim index fb76c9037..30b2505ad 100644 --- a/lib/pure/optionals.nim +++ b/lib/pure/optionals.nim @@ -117,50 +117,45 @@ proc `==`*(a, b: Option): bool = when isMainModule: - template expect(E: expr, body: stmt) = - try: - body - assert false, E.type.name & " not raised" - except E: - discard + import unittest + suite "optionals": + # work around a bug in unittest + let intNone = none(int) + let stringNone = none(string) - block: # example - proc find(haystack: string, needle: char): Option[int] = - for i, c in haystack: - if c == needle: - return some i + test "example": + proc find(haystack: string, needle: char): Option[int] = + for i, c in haystack: + if c == needle: + return some i - assert("abc".find('c').get() == 2) + check("abc".find('c').get() == 2) - let result = "team".find('i') + let result = "team".find('i') - assert result == none(int) - assert result.has == false + check result == intNone + check result.isNone - block: # some - assert some(6).get() == 6 - assert some("a").unsafeGet() == "a" - assert some(6).isSome - assert some("a").isSome + test "some": + check some(6).get() == 6 + check some("a").unsafeGet() == "a" + check some(6).isSome + check some("a").isSome - block: # none - expect FieldError: - discard none(int).get() - assert(none(int).isNone) - assert(not none(string).isSome) + test "none": + expect FieldError: + discard none(int).get() + check(none(int).isNone) + check(not none(string).isSome) - block: # equality - assert some("a") == some("a") - assert some(7) != some(6) - assert some("a") != none(string) - assert none(int) == none(int) + test "equality": + check some("a") == some("a") + check some(7) != some(6) + check some("a") != stringNone + check intNone == intNone - when compiles(some("a") == some(5)): - assert false - when compiles(none(string) == none(int)): - assert false - - block: # stringification - assert "some(7)" == $some(7) - assert "none(int)" == $none(int) + when compiles(some("a") == some(5)): + check false + when compiles(none(string) == none(int)): + check false From caa730127bbe1ba359eb4640ea52cd4e1e5cf540 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Tue, 19 May 2015 17:47:54 -0400 Subject: [PATCH 0256/1263] Use custom exception for option unpack --- lib/pure/optionals.nim | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/lib/pure/optionals.nim b/lib/pure/optionals.nim index 30b2505ad..6fda5996e 100644 --- a/lib/pure/optionals.nim +++ b/lib/pure/optionals.nim @@ -43,11 +43,11 @@ ## ## try: ## assert("abc".find('c').get() == 2) # Immediately extract the value -## except FieldError: # If there is no value +## except UnpackError: # If there is no value ## assert false # This will not be reached, because the value is present ## ## The ``get`` operation demonstrated above returns the underlying value, or -## raises ``FieldError`` if there is no value. There is another option for +## raises ``UnpackError`` if there is no value. There is another option for ## obtaining the value: ``unsafeGet``, but you must only use it when you are ## absolutely sure the value is present (e.g. after checking ``isSome``). If ## you do not care about the tiny overhead that ``get`` causes, you should @@ -67,7 +67,7 @@ ## try: ## echo result.get() ## assert(false) # This will not be reached -## except FieldError: # Because an exception is raised +## except UnpackError: # Because an exception is raised ## discard import typetraits @@ -78,6 +78,7 @@ type ## An optional type that stores its value and state separately in a boolean. val: T has: bool + UnpackError* = ref object of ValueError proc some*[T](val: T): Option[T] = @@ -106,7 +107,7 @@ proc get*[T](self: Option[T]): T = ## Returns contents of the Option. If it is none, then an exception is ## thrown. if self.isNone: - raise newException(FieldError, "Can't obtain a value from a `none`") + raise UnpackError(msg : "Can't obtain a value from a `none`") self.val @@ -144,7 +145,7 @@ when isMainModule: check some("a").isSome test "none": - expect FieldError: + expect UnpackError: discard none(int).get() check(none(int).isNone) check(not none(string).isSome) From 2cceaff88abdc2b25d93f34393bfcf4dc6b5ca3f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?G=C3=B6ran=20Krampe?= Date: Wed, 20 May 2015 11:59:02 +0200 Subject: [PATCH 0257/1263] Fixes #2749, traverse full inheritance for reprRecord --- lib/system/repr.nim | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/lib/system/repr.nim b/lib/system/repr.nim index f1029ff6a..dbb14bd2c 100644 --- a/lib/system/repr.nim +++ b/lib/system/repr.nim @@ -193,11 +193,17 @@ when not defined(useNimRtl): proc reprRecord(result: var string, p: pointer, typ: PNimType, cl: var TReprClosure) = add result, "[" - let oldLen = result.len - reprRecordAux(result, p, typ.node, cl) - if typ.base != nil: - if oldLen != result.len: add result, ",\n" - reprRecordAux(result, p, typ.base.node, cl) + var curTyp = typ + var lastPart = "" + while curTyp.base != nil: + var part = "" + reprRecordAux(part, p, curTyp.node, cl) + if part.len > 0: + if lastPart.len > 0: + add result, ",\n" + add result, part + lastPart = part + curTyp = curTyp.base add result, "]" proc reprRef(result: var string, p: pointer, typ: PNimType, From c936cf9e8ef356ff99b15829164ff664172a1613 Mon Sep 17 00:00:00 2001 From: Philip Witte Date: Wed, 20 May 2015 03:34:48 -0700 Subject: [PATCH 0258/1263] Fix bug with asyncdispatch.async and discard statements. --- lib/pure/asyncdispatch.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/pure/asyncdispatch.nim b/lib/pure/asyncdispatch.nim index 8849a8be3..8010e9ebc 100644 --- a/lib/pure/asyncdispatch.nim +++ b/lib/pure/asyncdispatch.nim @@ -1328,7 +1328,7 @@ proc processBody(node, retFutureSym: NimNode, else: discard of nnkDiscardStmt: # discard await x - if node[0].kind != nnkEmpty and node[0][0].kind == nnkIdent and + if node[0].kind == nnkCommand and node[0][0].kind == nnkIdent and node[0][0].ident == !"await": var newDiscard = node result.createVar("futureDiscard_" & $toStrLit(node[0][1]), node[0][1], From 0fc53151ba00ff31c55798674e21f7e5780320f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?G=C3=B6ran=20Krampe?= Date: Wed, 20 May 2015 12:48:38 +0200 Subject: [PATCH 0259/1263] Tweaked to do commas properly --- lib/system/repr.nim | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/system/repr.nim b/lib/system/repr.nim index dbb14bd2c..be346121a 100644 --- a/lib/system/repr.nim +++ b/lib/system/repr.nim @@ -194,15 +194,15 @@ when not defined(useNimRtl): cl: var TReprClosure) = add result, "[" var curTyp = typ - var lastPart = "" + var first = true while curTyp.base != nil: var part = "" reprRecordAux(part, p, curTyp.node, cl) if part.len > 0: - if lastPart.len > 0: + if not first: add result, ",\n" add result, part - lastPart = part + first = false curTyp = curTyp.base add result, "]" From d48bcb9873e426ece794d517290f262f6345f3b2 Mon Sep 17 00:00:00 2001 From: apense Date: Thu, 21 May 2015 17:51:41 -0400 Subject: [PATCH 0260/1263] Rewrote some peeking procedures Use `defer`s and `read...` procs that are already in place. Someone should check that the `defer`s are written correctly. I'm new to using them. --- lib/pure/streams.nim | 31 ++++--------------------------- 1 file changed, 4 insertions(+), 27 deletions(-) diff --git a/lib/pure/streams.nim b/lib/pure/streams.nim index ce33a9625..9054031e0 100644 --- a/lib/pure/streams.nim +++ b/lib/pure/streams.nim @@ -240,22 +240,9 @@ proc peekLine*(s: Stream, line: var TaintedString): bool = ## ``CRLF``. The newline character(s) are not part of the returned string. ## Returns ``false`` if the end of the file has been reached, ``true`` ## otherwise. If ``false`` is returned `line` contains no new data. - line.string.setLen(0) let pos = getPosition(s) - while true: - var c = readChar(s) - if c == '\c': - c = readChar(s) - break - elif c == '\L': break - elif c == '\0': - if line.len > 0: break - else: - setPosition(s, pos) - return false - line.string.add(c) - setPosition(s, pos) - result = true + defer: setPosition(s, pos) + readLine(s, line) proc readLine*(s: Stream): TaintedString = ## Reads a line from a stream `s`. Note: This is not very efficient. Raises @@ -274,19 +261,9 @@ proc readLine*(s: Stream): TaintedString = proc peekLine*(s: Stream): TaintedString = ## Peeks a line from a stream `s`. Note: This is not very efficient. Raises ## `EIO` if an error occurred. - result = TaintedString"" let pos = getPosition(s) - while true: - var c = readChar(s) - if c == '\c': - c = readChar(s) - setPosition(s, pos) - break - if c == '\L' or c == '\0': - setPosition(s, pos) - break - else: - result.string.add(c) + defer: setPosition(s, pos) + readLine(s) type StringStream* = ref StringStreamObj ## a stream that encapsulates a string From eb6f26dd6a103e5c0eaf7c21c3c66881e8e24700 Mon Sep 17 00:00:00 2001 From: Sergey Avseyev Date: Sat, 23 May 2015 19:32:47 +0300 Subject: [PATCH 0261/1263] Fix typo in tutorial --- doc/tut1.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/tut1.txt b/doc/tut1.txt index cf27ac788..1fa495054 100644 --- a/doc/tut1.txt +++ b/doc/tut1.txt @@ -1303,7 +1303,7 @@ type conversions in this context: myWriteln(stdout, 123, "abc", 4.0) # is transformed by the compiler to: - myWriteln(stdout, [$123, $"def", $4.0]) + myWriteln(stdout, [$123, $"abc", $4.0]) In this example `$ `_ is applied to any argument that is passed to the parameter ``a``. Note that `$ `_ applied to strings is a From 188bba2b3cd3106e0c615e712b8f5fdd995137bb Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 23 May 2015 12:59:15 -0400 Subject: [PATCH 0262/1263] Clean up crc module Use better names, remove quite a bit of dead code. Change `><` to a name that's actually descriptive. --- compiler/crc.nim | 64 ++++++------------------------------------- compiler/extccomp.nim | 14 +++++----- compiler/modules.nim | 8 +++--- compiler/rodread.nim | 12 ++++---- compiler/rodwrite.nim | 8 +++--- 5 files changed, 30 insertions(+), 76 deletions(-) diff --git a/compiler/crc.nim b/compiler/crc.nim index a8b61f2a5..7a2b6e4c2 100644 --- a/compiler/crc.nim +++ b/compiler/crc.nim @@ -11,18 +11,12 @@ import strutils type - TCrc32* = int32 + SecureHash* = int32 const - InitCrc32* = TCrc32(- 1) - InitAdler32* = int32(1) + InitCrc32 = SecureHash(- 1) -proc updateCrc32*(val: int8, crc: TCrc32): TCrc32 {.inline.} -proc updateCrc32*(val: char, crc: TCrc32): TCrc32 {.inline.} -proc crcFromBuf*(buf: pointer, length: int): TCrc32 -proc strCrc32*(s: string): TCrc32 -proc crcFromFile*(filename: string): TCrc32 -proc updateAdler32*(adler: int32, buf: pointer, length: int): int32 +proc secureHashFile*(filename: string): SecureHash # implementation type @@ -74,31 +68,22 @@ const - 1000256840, 1567103746, 711928724, - 1274298825, - 1022587231, 1510334235, 755167117] -proc updateCrc32(val: int8, crc: TCrc32): TCrc32 = - result = TCrc32(crc32table[(int(crc) xor (int(val) and 0x000000FF)) and - 0x000000FF]) xor (crc shr TCrc32(8)) +proc updateCrc32(val: int8, crc: SecureHash): SecureHash = + result = SecureHash(crc32table[(int(crc) xor (int(val) and 0x000000FF)) and + 0x000000FF]) xor (crc shr SecureHash(8)) -proc updateCrc32(val: char, crc: TCrc32): TCrc32 = +proc updateCrc32(val: char, crc: SecureHash): SecureHash = result = updateCrc32(toU8(ord(val)), crc) -proc strCrc32(s: string): TCrc32 = +proc secureHash*(s: string): SecureHash = result = InitCrc32 - for i in countup(0, len(s) - 1): result = updateCrc32(s[i], result) - -proc `><`*(c: TCrc32, s: string): TCrc32 = - result = c for i in 0..len(s)-1: result = updateCrc32(s[i], result) type TByteArray = array[0..10000000, int8] PByteArray = ref TByteArray -proc crcFromBuf(buf: pointer, length: int): TCrc32 = - var p = cast[PByteArray](buf) - result = InitCrc32 - for i in countup(0, length - 1): result = updateCrc32(p[i], result) - -proc crcFromFile(filename: string): TCrc32 = +proc secureHashFile(filename: string): SecureHash = const bufSize = 8000 # don't use 8K for the memory allocator! var @@ -114,34 +99,3 @@ proc crcFromFile(filename: string): TCrc32 = if readBytes != bufSize: break dealloc(buf) close(bin) - -const - base = int32(65521) # largest prime smaller than 65536 - # NMAX = 5552; original code with unsigned 32 bit integer - # NMAX is the largest n - # such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 - nmax = 3854 # code with signed 32 bit integer - # NMAX is the largest n such that - # 255n(n+1)/2 + (n+1)(BASE-1) <= 2^31-1 - # The penalty is the time loss in the extra MOD-calls. - -proc updateAdler32(adler: int32, buf: pointer, length: int): int32 = - var - s1, s2: int32 - L, k, b: int - s1 = adler and int32(0x0000FFFF) - s2 = (adler shr int32(16)) and int32(0x0000FFFF) - L = length - b = 0 - while (L > 0): - if L < nmax: k = L - else: k = nmax - dec(L, k) - while (k > 0): - s1 = s1 +% int32((cast[cstring](buf))[b]) - s2 = s2 +% s1 - inc(b) - dec(k) - s1 = `%%`(s1, base) - s2 = `%%`(s2, base) - result = (s2 shl int32(16)) or s1 diff --git a/compiler/extccomp.nim b/compiler/extccomp.nim index 186a3884d..cd7ac2a68 100644 --- a/compiler/extccomp.nim +++ b/compiler/extccomp.nim @@ -572,13 +572,13 @@ proc getCompileCFileCmd*(cfilename: string, isExternal = false): string = "nim", quoteShell(getPrefixDir()), "lib", quoteShell(libpath)]) -proc footprint(filename: string): TCrc32 = - # note, '><' further modifies a crc value with a string. - result = crcFromFile(filename) >< - platform.OS[targetOS].name >< - platform.CPU[targetCPU].name >< - extccomp.CC[extccomp.cCompiler].name >< - getCompileCFileCmd(filename, true) +proc footprint(filename: string): SecureHash = + result = secureHash( + $secureHashFile(filename) & + platform.OS[targetOS].name & + platform.CPU[targetCPU].name & + extccomp.CC[extccomp.cCompiler].name & + getCompileCFileCmd(filename, true)) proc externalFileChanged(filename: string): bool = if gCmd notin {cmdCompileToC, cmdCompileToCpp, cmdCompileToOC, cmdCompileToLLVM}: diff --git a/compiler/modules.nim b/compiler/modules.nim index 2fa46f356..09abd5da6 100644 --- a/compiler/modules.nim +++ b/compiler/modules.nim @@ -19,7 +19,7 @@ type TModuleInMemory* = object compiledAt*: float - crc*: TCrc32 + crc*: SecureHash deps*: seq[int32] ## XXX: slurped files are currently not tracked needsRecompile*: TNeedRecompile crcStatus*: TCrcStatus @@ -51,19 +51,19 @@ proc crcChanged(fileIdx: int32): bool = of crcNotChanged: result = false of crcCached: - let newCrc = crcFromFile(fileIdx.toFilename) + let newCrc = secureHashFile(fileIdx.toFilename) result = newCrc != gMemCacheData[fileIdx].crc gMemCacheData[fileIdx].crc = newCrc updateStatus() of crcNotTaken: - gMemCacheData[fileIdx].crc = crcFromFile(fileIdx.toFilename) + gMemCacheData[fileIdx].crc = secureHashFile(fileIdx.toFilename) result = true updateStatus() proc doCRC(fileIdx: int32) = if gMemCacheData[fileIdx].crcStatus == crcNotTaken: # echo "FIRST CRC: ", fileIdx.ToFilename - gMemCacheData[fileIdx].crc = crcFromFile(fileIdx.toFilename) + gMemCacheData[fileIdx].crc = secureHashFile(fileIdx.toFilename) proc addDep(x: PSym, dep: int32) = growCache gMemCacheData, dep diff --git a/compiler/rodread.nim b/compiler/rodread.nim index e92f7ecfa..066a02b1d 100644 --- a/compiler/rodread.nim +++ b/compiler/rodread.nim @@ -538,7 +538,7 @@ proc cmdChangeTriggersRecompilation(old, new: TCommands): bool = # else: trigger recompilation: result = true -proc processRodFile(r: PRodReader, crc: TCrc32) = +proc processRodFile(r: PRodReader, crc: SecureHash) = var w: string d, inclCrc: int @@ -598,7 +598,7 @@ proc processRodFile(r: PRodReader, crc: TCrc32) = inc(r.pos) # skip ' ' inclCrc = decodeVInt(r.s, r.pos) if r.reason == rrNone: - if not existsFile(w) or (inclCrc != int(crcFromFile(w))): + if not existsFile(w) or (inclCrc != int(secureHashFile(w))): r.reason = rrInclDeps if r.s[r.pos] == '\x0A': inc(r.pos) @@ -649,7 +649,7 @@ proc startsWith(buf: cstring, token: string, pos = 0): bool = while s < token.len and buf[pos+s] == token[s]: inc s result = s == token.len -proc newRodReader(modfilename: string, crc: TCrc32, +proc newRodReader(modfilename: string, crc: SecureHash, readerIndex: int): PRodReader = new(result) try: @@ -701,7 +701,7 @@ type filename*: string reason*: TReasonForRecompile rd*: PRodReader - crc*: TCrc32 + crc*: SecureHash crcDone*: bool TFileModuleMap = seq[TFileModuleRec] @@ -794,13 +794,13 @@ proc loadMethods(r: PRodReader) = r.methods.add(rrGetSym(r, d, unknownLineInfo())) if r.s[r.pos] == ' ': inc(r.pos) -proc getCRC*(fileIdx: int32): TCrc32 = +proc getCRC*(fileIdx: int32): SecureHash = internalAssert fileIdx >= 0 and fileIdx < gMods.len if gMods[fileIdx].crcDone: return gMods[fileIdx].crc - result = crcFromFile(fileIdx.toFilename) + result = secureHashFile(fileIdx.toFilename) gMods[fileIdx].crc = result template growCache*(cache, pos) = diff --git a/compiler/rodwrite.nim b/compiler/rodwrite.nim index e178b7ce6..c83e728db 100644 --- a/compiler/rodwrite.nim +++ b/compiler/rodwrite.nim @@ -20,7 +20,7 @@ import type TRodWriter = object of TPassContext module: PSym - crc: TCrc32 + crc: SecureHash options: TOptions defines: string inclDeps: string @@ -38,7 +38,7 @@ type PRodWriter = ref TRodWriter -proc newRodWriter(crc: TCrc32, module: PSym): PRodWriter +proc newRodWriter(crc: SecureHash, module: PSym): PRodWriter proc addModDep(w: PRodWriter, dep: string) proc addInclDep(w: PRodWriter, dep: string) proc addInterfaceSym(w: PRodWriter, s: PSym) @@ -62,7 +62,7 @@ proc fileIdx(w: PRodWriter, filename: string): int = template filename*(w: PRodWriter): string = w.module.filename -proc newRodWriter(crc: TCrc32, module: PSym): PRodWriter = +proc newRodWriter(crc: SecureHash, module: PSym): PRodWriter = new(result) result.sstack = @[] result.tstack = @[] @@ -96,7 +96,7 @@ proc addInclDep(w: PRodWriter, dep: string) = var resolved = dep.findModule(w.module.info.toFullPath) encodeVInt(fileIdx(w, dep), w.inclDeps) add(w.inclDeps, " ") - encodeVInt(crcFromFile(resolved), w.inclDeps) + encodeVInt(secureHashFile(resolved), w.inclDeps) add(w.inclDeps, rodNL) proc pushType(w: PRodWriter, t: PType) = From 4873db4c7218d1abc4cf43a17e1330628362801d Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 23 May 2015 13:17:19 -0400 Subject: [PATCH 0263/1263] Rename crc module to "secure_hash" --- compiler/ast.nim | 2 +- compiler/cgen.nim | 11 +++++------ compiler/extccomp.nim | 2 +- compiler/jsgen.nim | 4 ++-- compiler/modules.nim | 2 +- compiler/rodread.nim | 2 +- compiler/rodwrite.nim | 2 +- compiler/{crc.nim => secure_hash.nim} | 0 8 files changed, 12 insertions(+), 13 deletions(-) rename compiler/{crc.nim => secure_hash.nim} (100%) diff --git a/compiler/ast.nim b/compiler/ast.nim index 3798410e8..fd9c5478b 100644 --- a/compiler/ast.nim +++ b/compiler/ast.nim @@ -10,7 +10,7 @@ # abstract syntax tree + symbol table import - msgs, hashes, nversion, options, strutils, crc, ropes, idents, lists, + msgs, hashes, nversion, options, strutils, secure_hash, ropes, idents, lists, intsets, idgen type diff --git a/compiler/cgen.nim b/compiler/cgen.nim index 4b0bac28a..c3e6ac0d6 100644 --- a/compiler/cgen.nim +++ b/compiler/cgen.nim @@ -10,12 +10,11 @@ ## This module implements the C code generator. import - ast, astalgo, hashes, trees, platform, magicsys, extccomp, - options, intsets, - nversion, nimsets, msgs, crc, bitsets, idents, lists, types, ccgutils, os, - ropes, math, passes, rodread, wordrecg, treetab, cgmeth, condsyms, - rodutils, renderer, idgen, cgendata, ccgmerge, semfold, aliases, lowerings, - semparallel + ast, astalgo, hashes, trees, platform, magicsys, extccomp, options, intsets, + nversion, nimsets, msgs, secure_hash, bitsets, idents, lists, types, + ccgutils, os, ropes, math, passes, rodread, wordrecg, treetab, cgmeth, + condsyms, rodutils, renderer, idgen, cgendata, ccgmerge, semfold, aliases, + lowerings, semparallel import strutils except `%` # collides with ropes.`%` diff --git a/compiler/extccomp.nim b/compiler/extccomp.nim index cd7ac2a68..db6057b5e 100644 --- a/compiler/extccomp.nim +++ b/compiler/extccomp.nim @@ -13,7 +13,7 @@ # nim files. import - lists, ropes, os, strutils, osproc, platform, condsyms, options, msgs, crc + lists, ropes, os, strutils, osproc, platform, condsyms, options, msgs, secure_hash type TSystemCC* = enum diff --git a/compiler/jsgen.nim b/compiler/jsgen.nim index 5c7071498..ebcaf32c4 100644 --- a/compiler/jsgen.nim +++ b/compiler/jsgen.nim @@ -30,8 +30,8 @@ implements the required case distinction. import - ast, astalgo, strutils, hashes, trees, platform, magicsys, extccomp, - options, nversion, nimsets, msgs, crc, bitsets, idents, lists, types, os, + ast, astalgo, strutils, hashes, trees, platform, magicsys, extccomp, options, + nversion, nimsets, msgs, secure_hash, bitsets, idents, lists, types, os, times, ropes, math, passes, ccgutils, wordrecg, renderer, rodread, rodutils, intsets, cgmeth, lowerings diff --git a/compiler/modules.nim b/compiler/modules.nim index 09abd5da6..0573b91f8 100644 --- a/compiler/modules.nim +++ b/compiler/modules.nim @@ -10,7 +10,7 @@ ## implements the module handling import - ast, astalgo, magicsys, crc, rodread, msgs, cgendata, sigmatch, options, + ast, astalgo, magicsys, secure_hash, rodread, msgs, cgendata, sigmatch, options, idents, os, lexer, idgen, passes, syntaxes, llstream type diff --git a/compiler/rodread.nim b/compiler/rodread.nim index 066a02b1d..51d60f5b5 100644 --- a/compiler/rodread.nim +++ b/compiler/rodread.nim @@ -90,7 +90,7 @@ import os, options, strutils, nversion, ast, astalgo, msgs, platform, condsyms, - ropes, idents, crc, idgen, types, rodutils, memfiles + ropes, idents, secure_hash, idgen, types, rodutils, memfiles type TReasonForRecompile* = enum ## all the reasons that can trigger recompilation diff --git a/compiler/rodwrite.nim b/compiler/rodwrite.nim index c83e728db..22ecdd8af 100644 --- a/compiler/rodwrite.nim +++ b/compiler/rodwrite.nim @@ -13,7 +13,7 @@ import intsets, os, options, strutils, nversion, ast, astalgo, msgs, platform, - condsyms, ropes, idents, crc, rodread, passes, importer, idgen, rodutils + condsyms, ropes, idents, secure_hash, rodread, passes, importer, idgen, rodutils # implementation diff --git a/compiler/crc.nim b/compiler/secure_hash.nim similarity index 100% rename from compiler/crc.nim rename to compiler/secure_hash.nim From 1dd2379e4c662a090086456fdbe0569332967db0 Mon Sep 17 00:00:00 2001 From: HOLYCOWBATMAN Date: Sun, 24 May 2015 15:29:35 -0400 Subject: [PATCH 0264/1263] system.nim -> disabled Uninit warnings --- lib/system.nim | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/system.nim b/lib/system.nim index 1e6f76f3d..c02ae4bb3 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -61,7 +61,7 @@ const on* = true ## alias for ``true`` off* = false ## alias for ``false`` -{.push warning[GcMem]: off.} +{.push warning[GcMem]: off, warning[Uninit]: off.} {.push hints: off.} type @@ -3273,4 +3273,4 @@ proc xlen*[T](x: seq[T]): int {.magic: "XLenSeq", noSideEffect.} = ## This is an optimization that rarely makes sense. discard -{.pop.} #{.push warning[GcMem]: off.} +{.pop.} #{.push warning[GcMem]: off, warning[Uninit]: off.} From 928b730d1b6ee24e39c0ed5e6c5326f0c3f002a6 Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Sun, 24 May 2015 14:29:43 -0500 Subject: [PATCH 0265/1263] fixes #2694 --- compiler/nimsuggest/nimsuggest.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/nimsuggest/nimsuggest.nim b/compiler/nimsuggest/nimsuggest.nim index 3b4aa658d..b049899cb 100644 --- a/compiler/nimsuggest/nimsuggest.nim +++ b/compiler/nimsuggest/nimsuggest.nim @@ -118,7 +118,7 @@ proc execute(cmd: IdeCmd, file, dirtyfile: string, line, col: int) = gTrackPos = newLineInfo(dirtyIdx, line, col) gErrorCounter = 0 - if not isKnownFile: + if isKnownFile: compileProject(dirtyIdx) else: compileProject() From d3ab60c8310328b2838b42f0998515ddbb8a6ac4 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sun, 24 May 2015 18:20:37 -0400 Subject: [PATCH 0266/1263] Remove Oleah Prypin as author Done on request, see https://github.com/Araq/Nim/pull/2762#issuecomment-105071496 --- lib/pure/optionals.nim | 2 -- 1 file changed, 2 deletions(-) diff --git a/lib/pure/optionals.nim b/lib/pure/optionals.nim index 6fda5996e..d0d832f59 100644 --- a/lib/pure/optionals.nim +++ b/lib/pure/optionals.nim @@ -7,8 +7,6 @@ # distribution, for details about the copyright. # -## :Author: Oleh Prypin -## ## Abstract ## ======== ## From f610f8c5f049940aa5f6140b66830a1b2581a64c Mon Sep 17 00:00:00 2001 From: apense Date: Sun, 24 May 2015 18:36:52 -0400 Subject: [PATCH 0267/1263] Added defer statement All peeks should be covered by defer now, I think --- lib/pure/streams.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/pure/streams.nim b/lib/pure/streams.nim index 9054031e0..77698d329 100644 --- a/lib/pure/streams.nim +++ b/lib/pure/streams.nim @@ -346,8 +346,8 @@ when not defined(js): proc fsPeekData(s: Stream, buffer: pointer, bufLen: int): int = let pos = fsGetPosition(s) + defer: fsSetPosition(s, pos) result = readBuffer(FileStream(s).f, buffer, bufLen) - fsSetPosition(s, pos) proc fsWriteData(s: Stream, buffer: pointer, bufLen: int) = if writeBuffer(FileStream(s).f, buffer, bufLen) != bufLen: From 4cc722a41420e24f53a3a66be08e3b4a41b76d69 Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Sun, 24 May 2015 15:22:22 -0500 Subject: [PATCH 0268/1263] now nimsuggest works on the first sug --- compiler/nimsuggest/nimsuggest.nim | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/compiler/nimsuggest/nimsuggest.nim b/compiler/nimsuggest/nimsuggest.nim index b049899cb..2c785d118 100644 --- a/compiler/nimsuggest/nimsuggest.nim +++ b/compiler/nimsuggest/nimsuggest.nim @@ -118,10 +118,9 @@ proc execute(cmd: IdeCmd, file, dirtyfile: string, line, col: int) = gTrackPos = newLineInfo(dirtyIdx, line, col) gErrorCounter = 0 - if isKnownFile: - compileProject(dirtyIdx) - else: + if not isKnownFile: compileProject() + compileProject(dirtyIdx) proc executeEPC(cmd: IdeCmd, args: SexpNode) = let @@ -192,8 +191,6 @@ proc parseCmdLine(cmd: string) = execute(gIdeCmd, orig, dirtyfile, line, col-1) proc serve() = - # do not stop after the first error: - msgs.gErrorMax = high(int) case gMode: of mstdin: echo Help @@ -278,6 +275,9 @@ proc mainCommand = # current path is always looked first for modules prependStr(searchPaths, gProjectPath) + # do not stop after the first error: + msgs.gErrorMax = high(int) + compileProject() serve() proc processCmdLine*(pass: TCmdLinePass, cmd: string) = From bdb55c5d1d85f9425004f53f7e2cac5d31c90023 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sun, 24 May 2015 22:06:12 -0400 Subject: [PATCH 0269/1263] Fix typo in manual See IRC logs around Sun May 24 22:06:26 EDT 2015 for details --- doc/manual/trmacros.txt | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/doc/manual/trmacros.txt b/doc/manual/trmacros.txt index 90d01e475..53c604f7b 100644 --- a/doc/manual/trmacros.txt +++ b/doc/manual/trmacros.txt @@ -345,15 +345,15 @@ optimization for types that have copying semantics: ## puts a (key, value)-pair into `t`. The semantics of string require ## a copy here: let idx = findInsertionPosition(key) - t[idx] = key - t[idx] = val + t[idx].key = key + t[idx].val = val proc `[]=`*(t: var Table, key: string{call}, val: string{call}) = ## puts a (key, value)-pair into `t`. Optimized version that knows that ## the strings are unique and thus don't need to be copied: let idx = findInsertionPosition(key) - shallowCopy t[idx], key - shallowCopy t[idx], val + shallowCopy t[idx].key, key + shallowCopy t[idx].val, val var t: Table # overloading resolution ensures that the optimized []= is called here: From d8921a44859646d67f38f9bbb039b48e7285790e Mon Sep 17 00:00:00 2001 From: reactormonk Date: Sun, 24 May 2015 21:08:12 -0500 Subject: [PATCH 0270/1263] Revert "Fix typo in manual" --- doc/manual/trmacros.txt | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/doc/manual/trmacros.txt b/doc/manual/trmacros.txt index 53c604f7b..90d01e475 100644 --- a/doc/manual/trmacros.txt +++ b/doc/manual/trmacros.txt @@ -345,15 +345,15 @@ optimization for types that have copying semantics: ## puts a (key, value)-pair into `t`. The semantics of string require ## a copy here: let idx = findInsertionPosition(key) - t[idx].key = key - t[idx].val = val + t[idx] = key + t[idx] = val proc `[]=`*(t: var Table, key: string{call}, val: string{call}) = ## puts a (key, value)-pair into `t`. Optimized version that knows that ## the strings are unique and thus don't need to be copied: let idx = findInsertionPosition(key) - shallowCopy t[idx].key, key - shallowCopy t[idx].val, val + shallowCopy t[idx], key + shallowCopy t[idx], val var t: Table # overloading resolution ensures that the optimized []= is called here: From feff2bae680f4c63182069fee16162fe4e5f9d66 Mon Sep 17 00:00:00 2001 From: Oscar Campbell Date: Mon, 25 May 2015 05:24:47 +0200 Subject: [PATCH 0271/1263] Change wording in some parts. Fix some typos. --- doc/manual/about.txt | 7 +++--- doc/manual/definitions.txt | 2 +- doc/manual/effects.txt | 2 +- doc/manual/lexing.txt | 4 ++-- doc/manual/modules.txt | 3 +-- doc/manual/pragmas.txt | 19 ++++++--------- doc/manual/procs.txt | 47 ++++++++++++++++++++++++++------------ doc/manual/stmts.txt | 20 +++++++--------- doc/manual/trmacros.txt | 17 ++++++++------ doc/manual/type_rel.txt | 6 ++--- doc/manual/types.txt | 4 ++-- 11 files changed, 71 insertions(+), 60 deletions(-) diff --git a/doc/manual/about.txt b/doc/manual/about.txt index 78167efe3..9f76ca9a8 100644 --- a/doc/manual/about.txt +++ b/doc/manual/about.txt @@ -1,9 +1,8 @@ About this document =================== -**Note**: This document is a draft! Several of Nim's features need more -precise wording. This manual will evolve into a proper specification some -day. +**Note**: This document is a draft! Several of Nim's features may need more +precise wording. This manual is constantly evolving until the 1.0 release and is not to be considered as the final proper specification. This document describes the lexis, the syntax, and the semantics of Nim. @@ -33,5 +32,5 @@ and ``a ^* b`` is short for ``(a (b a)*)?``. Example:: arrayConstructor = '[' expr ^* ',' ']' Other parts of Nim - like scoping rules or runtime semantics are only -described in an informal manner for now. +described in the, more easily comprehensible, informal manner for now. diff --git a/doc/manual/definitions.txt b/doc/manual/definitions.txt index 9eb20f70f..9004ce658 100644 --- a/doc/manual/definitions.txt +++ b/doc/manual/definitions.txt @@ -30,7 +30,7 @@ exceptions* or *dying with a fatal error*. However, the implementation provides a means to disable these runtime checks. See the section pragmas_ for details. -Wether a checked runtime error results in an exception or in a fatal error at +Whether a checked runtime error results in an exception or in a fatal error at runtime is implementation specific. Thus the following program is always invalid: diff --git a/doc/manual/effects.txt b/doc/manual/effects.txt index a79f6ea85..40532b080 100644 --- a/doc/manual/effects.txt +++ b/doc/manual/effects.txt @@ -48,7 +48,7 @@ possibly raised exceptions; the algorithm operates on ``p``'s call graph: However if the call is of the form ``f(...)`` where ``f`` is a parameter of the currently analysed routine it is ignored. The call is optimistically assumed to have no effect. Rule 2 compensates for this case. -2. Every expression of some proc type wihtin a call that is not a call +2. Every expression of some proc type within a call that is not a call itself (and not nil) is assumed to be called indirectly somehow and thus its raises list is added to ``p``'s raises list. 3. Every call to a proc ``q`` which has an unknown body (due to a forward diff --git a/doc/manual/lexing.txt b/doc/manual/lexing.txt index df6d85636..ab1cd632d 100644 --- a/doc/manual/lexing.txt +++ b/doc/manual/lexing.txt @@ -25,7 +25,7 @@ a separate token. This trick allows parsing of Nim with only 1 token of lookahead. The parser uses a stack of indentation levels: the stack consists of integers -counting the spaces. The indentation information is queried at strategic +counting the spaces. The indentation information is queried at strategic places in the parser but ignored otherwise: The pseudo terminal ``IND{>}`` denotes an indentation that consists of more spaces than the entry at the top of the stack; IND{=} an indentation that has the same number of spaces. ``DED`` @@ -80,7 +80,7 @@ underscores ``__`` are not allowed:: digit ::= '0'..'9' IDENTIFIER ::= letter ( ['_'] (letter | digit) )* -Currently any unicode character with an ordinal value > 127 (non ASCII) is +Currently any Unicode character with an ordinal value > 127 (non ASCII) is classified as a ``letter`` and may thus be part of an identifier but later versions of the language may assign some Unicode characters to belong to the operator characters instead. diff --git a/doc/manual/modules.txt b/doc/manual/modules.txt index 70f6026b2..fe3360773 100644 --- a/doc/manual/modules.txt +++ b/doc/manual/modules.txt @@ -178,8 +178,7 @@ Module scope ~~~~~~~~~~~~ All identifiers of a module are valid from the point of declaration until the end of the module. Identifiers from indirectly dependent modules are *not* -available. The `system`:idx: module is automatically imported in every other -module. +available. The `system`:idx: module is automatically imported in every module. If a module imports an identifier by two different modules, each occurrence of the identifier has to be qualified, unless it is an overloaded procedure or diff --git a/doc/manual/pragmas.txt b/doc/manual/pragmas.txt index 39aebd826..2ce882495 100644 --- a/doc/manual/pragmas.txt +++ b/doc/manual/pragmas.txt @@ -18,9 +18,7 @@ The deprecated pragma is used to mark a symbol as deprecated: proc p() {.deprecated.} var x {.deprecated.}: char -It can also be used as a statement. Then it takes a list of *renamings*. The -upcoming ``nimfix`` tool can automatically update the code and perform these -renamings: +It can also be used as a statement, in that case it takes a list of *renamings*. .. code-block:: nim type @@ -28,6 +26,8 @@ renamings: Stream = ref object {.deprecated: [TFile: File, PStream: Stream].} +The ``nimfix`` tool can be used to, without effort, automatically update your code and refactor it by performing these renamings. + noSideEffect pragma ------------------- @@ -54,9 +54,7 @@ destructor pragma ----------------- The ``destructor`` pragma is used to mark a proc to act as a type destructor. -Its usage is deprecated, use the ``override`` pragma instead. -See `type bound operations`_. - +Its usage is deprecated, See `type bound operations`_ instead. override pragma --------------- @@ -371,7 +369,7 @@ The ``register`` pragma is for variables only. It declares the variable as in a hardware register for faster access. C compilers usually ignore this though and for good reasons: Often they do a better job without it anyway. -In highly specific cases (a dispatch loop of an bytecode interpreter for +In highly specific cases (a dispatch loop of a bytecode interpreter for example) it may provide benefits, though. @@ -429,13 +427,10 @@ Example: 2. When a top level call is encountered (usually at the very end of the module), the compiler will try to determine the actual types of all of the symbols in the matching overload set. This is a potentially recursive process as the signatures - of the symbols may include other call expressions, whoose types will be resolved + of the symbols may include other call expressions, whose types will be resolved at this point too. - 3. Finally, after the best overload is picked, the compiler will start compiling - the body of the respective symbol. This in turn will lead the compiler to discover - more call expresions that need to be resolved and steps 2 and 3 will be repeated - as necessary. + 3. Finally, after the best overload is picked, the compiler will start compiling the body of the respective symbol. This in turn will lead the compiler to discover more call expressions that need to be resolved and steps 2 and 3 will be repeated as necessary. Please note that if a callable symbol is never used in this scenario, its body will never be compiled. This is the default behavior leading to best compilation diff --git a/doc/manual/procs.txt b/doc/manual/procs.txt index 9de984ecf..7884b9c32 100644 --- a/doc/manual/procs.txt +++ b/doc/manual/procs.txt @@ -3,16 +3,36 @@ Procedures What most programming languages call `methods`:idx: or `functions`:idx: are called `procedures`:idx: in Nim (which is the correct terminology). A -procedure declaration defines an identifier and associates it with a block -of code. -A procedure may call itself recursively. A parameter may be given a default -value that is used if the caller does not provide a value for this parameter. +procedure declaration consists of an identifier, zero or more formal parameters, a return value type and a block of code. +Formal parameters are declared as a list of identifiers separated by either comma or semicolon. A parameter is given a type by ``: typename``. The type applies to all parameters immediately before it, until either the beginning of the parameter list, a semicolon separator or an already typed parameter, is reached. The semicolon can be used to make separation of types and subsequent identifiers more distinct. + +.. code-block:: nim + # Using only commas + proc foo(a, b: int, c, d: bool): int + + # Using semicolon for visual distinction + proc foo(a, b: int; c, d: bool): int + + # Will fail: a is untyped since ';' stops type propagation. + proc foo(a; b: int; c, d: bool): int + +A parameter may be declared with a default value which is used if the caller does not provide a value for the argument. + +.. code-block:: nim + # b is optional, 47 is its default value + proc foo(a, b: int = 47): int + +Parameters can be declared mutable and so allow the proc to modify those arguments, by using the type modifier `var`. + +.. code-block:: nim + # "returning" a value to the caller through the 2nd argument + proc foo(inp: int, outp: var int): void = + outp = inp + 47 If the proc declaration has no body, it is a `forward`:idx: declaration. If the proc returns a value, the procedure body can access an implicitly declared variable named `result`:idx: that represents the return value. Procs can be -overloaded. The overloading resolution algorithm tries to find the proc that is -the best match for the arguments. Example: +overloaded. The overloading resolution algorithm determines which proc is the best match for the arguments. Example: .. code-block:: nim @@ -41,9 +61,8 @@ Calling a procedure can be done in many different ways: # call as a command statement: no () needed: callme 0, 1, "abc", '\t' +A procedure may call itself recursively. -A procedure cannot modify its parameters (unless the parameters have the type -`var`). `Operators`:idx: are procedures with a special operator symbol as identifier: @@ -475,7 +494,7 @@ If the for loop has exactly 2 variables, a ``pairs`` iterator is implicitly invoked. Symbol lookup of the identifiers ``items``/``pairs`` is performed after -the rewriting step, so that all overloadings of ``items``/``pairs`` are taken +the rewriting step, so that all overloads of ``items``/``pairs`` are taken into account. @@ -511,11 +530,11 @@ Closure iterators have other restrictions than inline iterators: 1. ``yield`` in a closure iterator can not occur in a ``try`` statement. 2. For now, a closure iterator cannot be evaluated at compile time. -3. ``return`` is allowed in a closure iterator (but rarely useful). -4. Both inline and closure iterators cannot be recursive. +3. ``return`` is allowed in a closure iterator (but rarely useful) and ends iteration.. +4. Neither inline nor closure iterators can be recursive. Iterators that are neither marked ``{.closure.}`` nor ``{.inline.}`` explicitly -default to being inline, but that this may change in future versions of the +default to being inline, but this may change in future versions of the implementation. The ``iterator`` type is always of the calling convention ``closure`` @@ -612,8 +631,8 @@ parameters of an outer factory proc: Implicit return type -------------------- - Since inline interators must always produce values that will be consumed in - a for loop, the compiler will implicity use the ``auto`` return type if no + Since inline iterators must always produce values that will be consumed in + a for loop, the compiler will implicitly use the ``auto`` return type if no type is given by the user. In contrast, since closure iterators can be used as a collaborative tasking system, ``void`` is a valid return type for them. diff --git a/doc/manual/stmts.txt b/doc/manual/stmts.txt index 5e47110e9..7b4ea9e6d 100644 --- a/doc/manual/stmts.txt +++ b/doc/manual/stmts.txt @@ -10,7 +10,7 @@ Statements are separated into `simple statements`:idx: and Simple statements are statements that cannot contain other statements like assignments, calls or the ``return`` statement; complex statements can contain other statements. To avoid the `dangling else problem`:idx:, complex -statements always have to be intended. The details can be found in the grammar. +statements always have to be indented. The details can be found in the grammar. Statement list expression @@ -229,22 +229,18 @@ the expression after the ``elif`` is evaluated (if there is an ``elif`` branch), if it is true the corresponding statements after the ``:`` are executed. This goes on until the last ``elif``. If all conditions fail, the ``else`` part is executed. If there is no ``else`` -part, execution continues with the statement after the ``if`` statement. +part, execution continues with the next statement. -The scoping for an ``if`` statement is slightly subtle to support an important -use case. A new scope starts for the ``if``/``elif`` condition and ends after -the corresponding *then* block: +In ``if`` statements new scopes begin immediately after the ``if``/``elif``/``else`` keywords and ends after the corresponding *then* block. +For visualization purposes the scopes have been enclosed in ``{| |}`` in the following example: .. code-block:: nim if {| (let m = input =~ re"(\w+)=\w+"; m.isMatch): echo "key ", m[0], " value ", m[1] |} elif {| (let m = input =~ re""; m.isMatch): - echo "new m in this scope" |} - else: - # 'm' not declared here - -In the example the scopes have been enclosed in ``{| |}``. - + echo "new m in this scope" |} + else: {| + echo "m not declared here" |} Case statement -------------- @@ -601,7 +597,7 @@ A table constructor is syntactic sugar for an array constructor: The empty table can be written ``{:}`` (in contrast to the empty set which is ``{}``) which is thus another way to write as the empty array -constructor ``[]``. This slightly unusal way of supporting tables +constructor ``[]``. This slightly unusual way of supporting tables has lots of advantages: * The order of the (key,value)-pairs is preserved, thus it is easy to diff --git a/doc/manual/trmacros.txt b/doc/manual/trmacros.txt index 90d01e475..a5a9fe3e0 100644 --- a/doc/manual/trmacros.txt +++ b/doc/manual/trmacros.txt @@ -43,6 +43,8 @@ Fortunately Nim supports side effect analysis: echo f() * 2 # not optimized ;-) +You can make one overload for constrained match and without, and the constrained will be prioritized, and so you can handle both cases differently. + So what about ``2 * a``? We should tell the compiler ``*`` is commutative. We cannot really do that however as the following code only swaps arguments blindly: @@ -50,7 +52,7 @@ blindly: .. code-block:: nim template mulIsCommutative{`*`(a, b)}(a, b: int): int = b*a -What optimizers really need to do is a *canonicalization*: +What optimizers really need to do is a *canonization*: .. code-block:: nim template canonMul{`*`(a, b)}(a: int{lit}, b: int): int = b*a @@ -106,8 +108,9 @@ Predicate Meaning =================== ===================================================== The ``alias`` and ``noalias`` predicates refer not only to the matching AST, -but also to every other bound parameter; syntactially they need to occur after +but also to every other bound parameter; syntactically they need to occur after the ordinary AST predicates: +Predicates that share their name with a keyword have to be escaped with backticks: `` `const` ``. .. code-block:: nim template ex{a = b + c}(a: int{noalias}, b, c: int) = @@ -144,7 +147,7 @@ constant folding, so the following does not work: The reason is that the compiler already transformed the 1 into "1" for the ``echo`` statement. However, a term rewriting macro should not change the -semantics anyway. In fact they can be deactived with the ``--patterns:off`` +semantics anyway. In fact they can be deactivated with the ``--patterns:off`` command line option or temporarily with the ``patterns`` pragma. @@ -345,15 +348,15 @@ optimization for types that have copying semantics: ## puts a (key, value)-pair into `t`. The semantics of string require ## a copy here: let idx = findInsertionPosition(key) - t[idx] = key - t[idx] = val + t[idx].key = key + t[idx].val = val proc `[]=`*(t: var Table, key: string{call}, val: string{call}) = ## puts a (key, value)-pair into `t`. Optimized version that knows that ## the strings are unique and thus don't need to be copied: let idx = findInsertionPosition(key) - shallowCopy t[idx], key - shallowCopy t[idx], val + shallowCopy t[idx].key, key + shallowCopy t[idx].val, val var t: Table # overloading resolution ensures that the optimized []= is called here: diff --git a/doc/manual/type_rel.txt b/doc/manual/type_rel.txt index d1593a02e..5c8372e1e 100644 --- a/doc/manual/type_rel.txt +++ b/doc/manual/type_rel.txt @@ -9,11 +9,11 @@ Type equality ------------- Nim uses structural type equivalence for most types. Only for objects, enumerations and distinct types name equivalence is used. The following -algorithm (in pseudo-code) determines type equality: +algorithm, *in pseudo-code*, determines type equality: .. code-block:: nim proc typeEqualsAux(a, b: PType, - s: var set[PType * PType]): bool = + s: var HashSet[(PType, PType)]): bool = if (a,b) in s: return true incl(s, (a,b)) if a.kind == b.kind: @@ -43,7 +43,7 @@ algorithm (in pseudo-code) determines type equality: a.callingConvention == b.callingConvention proc typeEquals(a, b: PType): bool = - var s: set[PType * PType] = {} + var s: HashSet[(PType, PType)] = {} result = typeEqualsAux(a, b, s) Since types are graphs which can have cycles, the above algorithm needs an diff --git a/doc/manual/types.txt b/doc/manual/types.txt index bdf51941d..5e3e98ce6 100644 --- a/doc/manual/types.txt +++ b/doc/manual/types.txt @@ -803,7 +803,7 @@ exclude ``nil`` as a valid value with the ``not nil`` annotation: p(x) The compiler ensures that every code path initializes variables which contain -not nilable pointers. The details of this analysis are still to be specified +non nilable pointers. The details of this analysis are still to be specified here. @@ -1132,7 +1132,7 @@ that don't. Distinct types provide a means to introduce a new string type It is an essential property of abstract types that they **do not** imply a -subtype relation between the abtract type and its base type. Explict type +subtype relation between the abstract type and its base type. Explicit type conversions from ``string`` to ``SQL`` are allowed: .. code-block:: nim From 625299e861173266d0393ffdd76e66be9cb0c34d Mon Sep 17 00:00:00 2001 From: Oscar Campbell Date: Mon, 25 May 2015 06:00:37 +0200 Subject: [PATCH 0272/1263] Change to hard word wrap at 80. --- doc/manual/about.txt | 9 +++++---- doc/manual/pragmas.txt | 8 ++++++-- doc/manual/procs.txt | 27 ++++++++++++++++++--------- doc/manual/trmacros.txt | 6 ++++-- 4 files changed, 33 insertions(+), 17 deletions(-) diff --git a/doc/manual/about.txt b/doc/manual/about.txt index 9f76ca9a8..8528ff978 100644 --- a/doc/manual/about.txt +++ b/doc/manual/about.txt @@ -2,13 +2,14 @@ About this document =================== **Note**: This document is a draft! Several of Nim's features may need more -precise wording. This manual is constantly evolving until the 1.0 release and is not to be considered as the final proper specification. +precise wording. This manual is constantly evolving until the 1.0 release and is +not to be considered as the final proper specification. This document describes the lexis, the syntax, and the semantics of Nim. -The language constructs are explained using an extended BNF, in -which ``(a)*`` means 0 or more ``a``'s, ``a+`` means 1 or more ``a``'s, and -``(a)?`` means an optional *a*. Parentheses may be used to group elements. +The language constructs are explained using an extended BNF, in which ``(a)*`` +means 0 or more ``a``'s, ``a+`` means 1 or more ``a``'s, and ``(a)?`` means an +optional *a*. Parentheses may be used to group elements. ``&`` is the lookahead operator; ``&a`` means that an ``a`` is expected but not consumed. It will be consumed in the following rule. diff --git a/doc/manual/pragmas.txt b/doc/manual/pragmas.txt index 2ce882495..51125f576 100644 --- a/doc/manual/pragmas.txt +++ b/doc/manual/pragmas.txt @@ -26,7 +26,8 @@ It can also be used as a statement, in that case it takes a list of *renamings*. Stream = ref object {.deprecated: [TFile: File, PStream: Stream].} -The ``nimfix`` tool can be used to, without effort, automatically update your code and refactor it by performing these renamings. +The ``nimfix`` tool can be used to, without effort, automatically update your +code and refactor it by performing these renamings. noSideEffect pragma @@ -430,7 +431,10 @@ Example: of the symbols may include other call expressions, whose types will be resolved at this point too. - 3. Finally, after the best overload is picked, the compiler will start compiling the body of the respective symbol. This in turn will lead the compiler to discover more call expressions that need to be resolved and steps 2 and 3 will be repeated as necessary. + 3. Finally, after the best overload is picked, the compiler will start + compiling the body of the respective symbol. This in turn will lead the + compiler to discover more call expressions that need to be resolved and steps + 2 and 3 will be repeated as necessary. Please note that if a callable symbol is never used in this scenario, its body will never be compiled. This is the default behavior leading to best compilation diff --git a/doc/manual/procs.txt b/doc/manual/procs.txt index 7884b9c32..b76300e89 100644 --- a/doc/manual/procs.txt +++ b/doc/manual/procs.txt @@ -2,9 +2,14 @@ Procedures ========== What most programming languages call `methods`:idx: or `functions`:idx: are -called `procedures`:idx: in Nim (which is the correct terminology). A -procedure declaration consists of an identifier, zero or more formal parameters, a return value type and a block of code. -Formal parameters are declared as a list of identifiers separated by either comma or semicolon. A parameter is given a type by ``: typename``. The type applies to all parameters immediately before it, until either the beginning of the parameter list, a semicolon separator or an already typed parameter, is reached. The semicolon can be used to make separation of types and subsequent identifiers more distinct. +called `procedures`:idx: in Nim (which is the correct terminology). A procedure +declaration consists of an identifier, zero or more formal parameters, a return +value type and a block of code. Formal parameters are declared as a list of +identifiers separated by either comma or semicolon. A parameter is given a type +by ``: typename``. The type applies to all parameters immediately before it, +until either the beginning of the parameter list, a semicolon separator or an +already typed parameter, is reached. The semicolon can be used to make +separation of types and subsequent identifiers more distinct. .. code-block:: nim # Using only commas @@ -16,23 +21,26 @@ Formal parameters are declared as a list of identifiers separated by either comm # Will fail: a is untyped since ';' stops type propagation. proc foo(a; b: int; c, d: bool): int -A parameter may be declared with a default value which is used if the caller does not provide a value for the argument. +A parameter may be declared with a default value which is used if the caller +does not provide a value for the argument. .. code-block:: nim # b is optional, 47 is its default value proc foo(a, b: int = 47): int -Parameters can be declared mutable and so allow the proc to modify those arguments, by using the type modifier `var`. +Parameters can be declared mutable and so allow the proc to modify those +arguments, by using the type modifier `var`. .. code-block:: nim # "returning" a value to the caller through the 2nd argument proc foo(inp: int, outp: var int): void = outp = inp + 47 -If the proc declaration has no body, it is a `forward`:idx: declaration. If -the proc returns a value, the procedure body can access an implicitly declared +If the proc declaration has no body, it is a `forward`:idx: declaration. If the +proc returns a value, the procedure body can access an implicitly declared variable named `result`:idx: that represents the return value. Procs can be -overloaded. The overloading resolution algorithm determines which proc is the best match for the arguments. Example: +overloaded. The overloading resolution algorithm determines which proc is the +best match for the arguments. Example: .. code-block:: nim @@ -530,7 +538,8 @@ Closure iterators have other restrictions than inline iterators: 1. ``yield`` in a closure iterator can not occur in a ``try`` statement. 2. For now, a closure iterator cannot be evaluated at compile time. -3. ``return`` is allowed in a closure iterator (but rarely useful) and ends iteration.. +3. ``return`` is allowed in a closure iterator (but rarely useful) and ends + iteration.. 4. Neither inline nor closure iterators can be recursive. Iterators that are neither marked ``{.closure.}`` nor ``{.inline.}`` explicitly diff --git a/doc/manual/trmacros.txt b/doc/manual/trmacros.txt index a5a9fe3e0..067349c30 100644 --- a/doc/manual/trmacros.txt +++ b/doc/manual/trmacros.txt @@ -43,7 +43,8 @@ Fortunately Nim supports side effect analysis: echo f() * 2 # not optimized ;-) -You can make one overload for constrained match and without, and the constrained will be prioritized, and so you can handle both cases differently. +You can make one overload for constrained match and without, and the constrained +will be prioritized, and so you can handle both cases differently. So what about ``2 * a``? We should tell the compiler ``*`` is commutative. We cannot really do that however as the following code only swaps arguments @@ -107,10 +108,11 @@ Predicate Meaning with the marked parameter. =================== ===================================================== +Predicates that share their name with a keyword have to be escaped with +backticks: `` `const` ``. The ``alias`` and ``noalias`` predicates refer not only to the matching AST, but also to every other bound parameter; syntactically they need to occur after the ordinary AST predicates: -Predicates that share their name with a keyword have to be escaped with backticks: `` `const` ``. .. code-block:: nim template ex{a = b + c}(a: int{noalias}, b, c: int) = From 513423a08dcc6f2011f9af394c2a66c54445d5eb Mon Sep 17 00:00:00 2001 From: apense Date: Mon, 25 May 2015 02:44:08 -0400 Subject: [PATCH 0273/1263] Corrected various links within documentation Corrected `noSideEffect pragma` links in lib/system (The newer documentation uses slightly different links) Corrected `noSideEffect pragma` in types links to match the updated link names Minor link adjustment in stmts to match the newer link names --- doc/manual/stmts.txt | 6 +++--- doc/manual/types.txt | 2 +- lib/system.nim | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/doc/manual/stmts.txt b/doc/manual/stmts.txt index 5e47110e9..210ca7064 100644 --- a/doc/manual/stmts.txt +++ b/doc/manual/stmts.txt @@ -176,9 +176,9 @@ The rules for compile-time computability are: 1. Literals are compile-time computable. 2. Type conversions are compile-time computable. 3. Procedure calls of the form ``p(X)`` are compile-time computable if - ``p`` is a proc without side-effects (see the `noSideEffect pragma`_ - for details) and if ``X`` is a (possibly empty) list of compile-time - computable arguments. + ``p`` is a proc without side-effects (see the `noSideEffect pragma + <#pragmas-nosideeffect-pragma>`_ for details) and if ``X`` is a + (possibly empty) list of compile-time computable arguments. Constants cannot be of type ``ptr``, ``ref``, ``var`` or ``object``, nor can diff --git a/doc/manual/types.txt b/doc/manual/types.txt index bdf51941d..689605f08 100644 --- a/doc/manual/types.txt +++ b/doc/manual/types.txt @@ -963,7 +963,7 @@ Most calling conventions exist only for the Windows 32-bit platform. Assigning/passing a procedure to a procedural variable is only allowed if one of the following conditions hold: 1) The procedure that is accessed resides in the current module. -2) The procedure is marked with the ``procvar`` pragma (see `procvar pragma`_). +2) The procedure is marked with the ``procvar`` pragma (see `procvar pragma <#pragmas-procvar-pragma>`_). 3) The procedure has a calling convention that differs from ``nimcall``. 4) The procedure is anonymous. diff --git a/lib/system.nim b/lib/system.nim index c02ae4bb3..a4b053ca7 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -2248,14 +2248,14 @@ proc echo*(x: varargs[expr, `$`]) {.magic: "Echo", tags: [WriteIOEffect], ## Unlike other IO operations this is guaranteed to be thread-safe as ## ``echo`` is very often used for debugging convenience. If you want to use ## ``echo`` inside a `proc without side effects - ## `_ you can use `debugEcho <#debugEcho>`_ + ## `_ you can use `debugEcho <#debugEcho>`_ ## instead. proc debugEcho*(x: varargs[expr, `$`]) {.magic: "Echo", noSideEffect, tags: [], raises: [].} ## Same as `echo <#echo>`_, but as a special semantic rule, ``debugEcho`` ## pretends to be free of side effects, so that it can be used for debugging - ## routines marked as `noSideEffect `_. + ## routines marked as `noSideEffect `_. template newException*(exceptn: typedesc, message: string): expr = ## creates an exception object of type ``exceptn`` and sets its ``msg`` field From ae3fc71462fed35b9e280b040c84d54ced44fcca Mon Sep 17 00:00:00 2001 From: Bruce Doan Date: Tue, 26 May 2015 00:01:35 +0700 Subject: [PATCH 0274/1263] Remove dead code in findAll proc --- lib/pure/xmltree.nim | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/lib/pure/xmltree.nim b/lib/pure/xmltree.nim index 7526a989a..bbe3c05b7 100644 --- a/lib/pure/xmltree.nim +++ b/lib/pure/xmltree.nim @@ -337,8 +337,7 @@ proc findAll*(n: XmlNode, tag: string, result: var seq[XmlNode]) = continue if child.tag == tag: result.add(child) - elif child.k == xnElement: - child.findAll(tag, result) + child.findAll(tag, result) proc findAll*(n: XmlNode, tag: string): seq[XmlNode] = ## Shortcut version to assign in let blocks. Example: From 910dce70d6748b41ffbc39c731592716609c33f7 Mon Sep 17 00:00:00 2001 From: Oscar Campbell Date: Mon, 25 May 2015 20:03:12 +0200 Subject: [PATCH 0275/1263] Remove double punctuation. Change "contrained" wording to "constraint". --- doc/manual/procs.txt | 2 +- doc/manual/trmacros.txt | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/doc/manual/procs.txt b/doc/manual/procs.txt index b76300e89..fb2c7a108 100644 --- a/doc/manual/procs.txt +++ b/doc/manual/procs.txt @@ -539,7 +539,7 @@ Closure iterators have other restrictions than inline iterators: 1. ``yield`` in a closure iterator can not occur in a ``try`` statement. 2. For now, a closure iterator cannot be evaluated at compile time. 3. ``return`` is allowed in a closure iterator (but rarely useful) and ends - iteration.. + iteration. 4. Neither inline nor closure iterators can be recursive. Iterators that are neither marked ``{.closure.}`` nor ``{.inline.}`` explicitly diff --git a/doc/manual/trmacros.txt b/doc/manual/trmacros.txt index 067349c30..de98e3a46 100644 --- a/doc/manual/trmacros.txt +++ b/doc/manual/trmacros.txt @@ -43,8 +43,9 @@ Fortunately Nim supports side effect analysis: echo f() * 2 # not optimized ;-) -You can make one overload for constrained match and without, and the constrained -will be prioritized, and so you can handle both cases differently. +You can make one overload matching with a constraint and one without, and the +one with a constraint will have precedence, and so you can handle both cases +differently. So what about ``2 * a``? We should tell the compiler ``*`` is commutative. We cannot really do that however as the following code only swaps arguments From 411e602d134aba05a8d876da41e8abe1b04c374c Mon Sep 17 00:00:00 2001 From: Sergey Avseyev Date: Mon, 25 May 2015 21:16:35 +0300 Subject: [PATCH 0276/1263] Introduce pedantic mode for tester Motivation ---------- External tools need to know whether or not any test in suite failed. For example buildbot, or packaging tool would like to stop the execution and mark it as failed if some tests does not pass. Modification ------------ Add `--pedantic` switch to tester program which will force it to quit with non-zero exit code if at least one failure detected. Also update `tests()` proc in koch to inspect result from tester and propagate it to user. Result ------ Nothing has changed in default behaviour. But following invocations will exit with non-zero code if there failed tests: ./koch tests --pedantic all ./tests/testament/tester --pedantic all --- koch.nim | 4 +++- tests/testament/tester.nim | 7 ++++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/koch.nim b/koch.nim index 55019b544..a951b422f 100644 --- a/koch.nim +++ b/koch.nim @@ -333,8 +333,10 @@ proc tests(args: string) = # taint mode test :-) exec "nim cc --taintMode:on tests/testament/tester" let tester = quoteShell(getCurrentDir() / "tests/testament/tester".exe) - exec tester & " " & (args|"all") + let success = tryExec tester & " " & (args|"all") exec tester & " html" + if not success: + quit("tests failed", QuitFailure) proc temp(args: string) = var output = "compiler" / "nim".exe diff --git a/tests/testament/tester.nim b/tests/testament/tester.nim index 0308ce940..62dafee80 100644 --- a/tests/testament/tester.nim +++ b/tests/testament/tester.nim @@ -31,6 +31,7 @@ Arguments: Options: --print also print results to the console --failing only show failing/ignored tests + --pedantic return non-zero status code if there are failures """ % resultsFile type @@ -310,12 +311,14 @@ proc main() = backend.open() var optPrintResults = false var optFailing = false + var optPedantic = false var p = initOptParser() p.next() while p.kind == cmdLongoption: case p.key.string.normalize of "print", "verbose": optPrintResults = true of "failing": optFailing = true + of "pedantic": optPedantic = true else: quit Usage p.next() if p.kind != cmdArgument: quit Usage @@ -348,8 +351,10 @@ proc main() = if action == "html": openDefaultBrowser(resultsFile) else: echo r, r.data backend.close() + if optPedantic: + var failed = r.total - r.passed - r.skipped + if failed > 0 : quit(QuitFailure) if paramCount() == 0: quit Usage main() - From f51643428359a12185b981e57117d7e8ecf2a776 Mon Sep 17 00:00:00 2001 From: Sergey Avseyev Date: Mon, 25 May 2015 23:27:46 +0300 Subject: [PATCH 0277/1263] Remove trailing spaces --- lib/pure/streams.nim | 94 ++++++++++++++++++++++---------------------- 1 file changed, 47 insertions(+), 47 deletions(-) diff --git a/lib/pure/streams.nim b/lib/pure/streams.nim index 77698d329..f6c65466c 100644 --- a/lib/pure/streams.nim +++ b/lib/pure/streams.nim @@ -31,7 +31,7 @@ type getPositionImpl*: proc (s: Stream): int {.nimcall, tags: [], gcsafe.} readDataImpl*: proc (s: Stream, buffer: pointer, bufLen: int): int {.nimcall, tags: [ReadIOEffect], gcsafe.} - peekDataImpl*: proc (s: Stream, buffer: pointer, + peekDataImpl*: proc (s: Stream, buffer: pointer, bufLen: int): int {.nimcall, tags: [ReadIOEffect], gcsafe.} writeDataImpl*: proc (s: Stream, buffer: pointer, bufLen: int) {.nimcall, tags: [WriteIOEffect], gcsafe.} @@ -81,7 +81,7 @@ proc readData*(s: Stream, buffer: pointer, bufLen: int): int = ## low level proc that reads data into an untyped `buffer` of `bufLen` size. result = s.readDataImpl(s, buffer, bufLen) -proc readData*(s, unused: Stream, buffer: pointer, +proc readData*(s, unused: Stream, buffer: pointer, bufLen: int): int {.deprecated.} = ## low level proc that reads data into an untyped `buffer` of `bufLen` size. result = s.readDataImpl(s, buffer, bufLen) @@ -96,13 +96,13 @@ proc writeData*(s: Stream, buffer: pointer, bufLen: int) = ## to the stream `s`. s.writeDataImpl(s, buffer, bufLen) -proc writeData*(s, unused: Stream, buffer: pointer, +proc writeData*(s, unused: Stream, buffer: pointer, bufLen: int) {.deprecated.} = ## low level proc that writes an untyped `buffer` of `bufLen` size ## to the stream `s`. s.writeDataImpl(s, buffer, bufLen) -proc write*[T](s: Stream, x: T) = +proc write*[T](s: Stream, x: T) = ## generic write procedure. Writes `x` to the stream `s`. Implementation: ## ## .. code-block:: Nim @@ -112,8 +112,8 @@ proc write*[T](s: Stream, x: T) = shallowCopy(y, x) writeData(s, addr(y), sizeof(y)) -proc write*(s: Stream, x: string) = - ## writes the string `x` to the the stream `s`. No length field or +proc write*(s: Stream, x: string) = + ## writes the string `x` to the the stream `s`. No length field or ## terminating zero is written. writeData(s, cstring(x), x.len) @@ -123,7 +123,7 @@ proc writeln*(s: Stream, args: varargs[string, `$`]) = for str in args: write(s, str) write(s, "\n") -proc read[T](s: Stream, result: var T) = +proc read[T](s: Stream, result: var T) = ## generic read procedure. Reads `result` from the stream `s`. if readData(s, addr(result), sizeof(T)) != sizeof(T): raise newEIO("cannot read from stream") @@ -143,7 +143,7 @@ proc peekChar*(s: Stream): char = ## Returns '\0' as an EOF marker. if peekData(s, addr(result), sizeof(result)) != 1: result = '\0' -proc readBool*(s: Stream): bool = +proc readBool*(s: Stream): bool = ## reads a bool from the stream `s`. Raises `EIO` if an error occurred. read(s, result) @@ -151,7 +151,7 @@ proc peekBool*(s: Stream): bool = ## peeks a bool from the stream `s`. Raises `EIO` if an error occured. peek(s, result) -proc readInt8*(s: Stream): int8 = +proc readInt8*(s: Stream): int8 = ## reads an int8 from the stream `s`. Raises `EIO` if an error occurred. read(s, result) @@ -159,55 +159,55 @@ proc peekInt8*(s: Stream): int8 = ## peeks an int8 from the stream `s`. Raises `EIO` if an error occurred. peek(s, result) -proc readInt16*(s: Stream): int16 = +proc readInt16*(s: Stream): int16 = ## reads an int16 from the stream `s`. Raises `EIO` if an error occurred. read(s, result) -proc peekInt16*(s: Stream): int16 = +proc peekInt16*(s: Stream): int16 = ## peeks an int16 from the stream `s`. Raises `EIO` if an error occurred. peek(s, result) -proc readInt32*(s: Stream): int32 = +proc readInt32*(s: Stream): int32 = ## reads an int32 from the stream `s`. Raises `EIO` if an error occurred. read(s, result) -proc peekInt32*(s: Stream): int32 = +proc peekInt32*(s: Stream): int32 = ## peeks an int32 from the stream `s`. Raises `EIO` if an error occurred. peek(s, result) -proc readInt64*(s: Stream): int64 = +proc readInt64*(s: Stream): int64 = ## reads an int64 from the stream `s`. Raises `EIO` if an error occurred. read(s, result) -proc peekInt64*(s: Stream): int64 = +proc peekInt64*(s: Stream): int64 = ## peeks an int64 from the stream `s`. Raises `EIO` if an error occurred. peek(s, result) -proc readFloat32*(s: Stream): float32 = +proc readFloat32*(s: Stream): float32 = ## reads a float32 from the stream `s`. Raises `EIO` if an error occurred. read(s, result) -proc peekFloat32*(s: Stream): float32 = +proc peekFloat32*(s: Stream): float32 = ## peeks a float32 from the stream `s`. Raises `EIO` if an error occurred. peek(s, result) -proc readFloat64*(s: Stream): float64 = +proc readFloat64*(s: Stream): float64 = ## reads a float64 from the stream `s`. Raises `EIO` if an error occurred. read(s, result) -proc peekFloat64*(s: Stream): float64 = +proc peekFloat64*(s: Stream): float64 = ## peeks a float64 from the stream `s`. Raises `EIO` if an error occurred. peek(s, result) -proc readStr*(s: Stream, length: int): TaintedString = - ## reads a string of length `length` from the stream `s`. Raises `EIO` if +proc readStr*(s: Stream, length: int): TaintedString = + ## reads a string of length `length` from the stream `s`. Raises `EIO` if ## an error occurred. result = newString(length).TaintedString var L = readData(s, addr(string(result)[0]), length) if L != length: setLen(result.string, L) -proc peekStr*(s: Stream, length: int): TaintedString = - ## peeks a string of length `length` from the stream `s`. Raises `EIO` if +proc peekStr*(s: Stream, length: int): TaintedString = + ## peeks a string of length `length` from the stream `s`. Raises `EIO` if ## an error occurred. result = newString(length).TaintedString var L = peekData(s, addr(string(result)[0]), length) @@ -223,7 +223,7 @@ proc readLine*(s: Stream, line: var TaintedString): bool = line.string.setLen(0) while true: var c = readChar(s) - if c == '\c': + if c == '\c': c = readChar(s) break elif c == '\L': break @@ -245,12 +245,12 @@ proc peekLine*(s: Stream, line: var TaintedString): bool = readLine(s, line) proc readLine*(s: Stream): TaintedString = - ## Reads a line from a stream `s`. Note: This is not very efficient. Raises + ## Reads a line from a stream `s`. Note: This is not very efficient. Raises ## `EIO` if an error occurred. result = TaintedString"" while true: var c = readChar(s) - if c == '\c': + if c == '\c': c = readChar(s) break if c == '\L' or c == '\0': @@ -259,7 +259,7 @@ proc readLine*(s: Stream): TaintedString = result.string.add(c) proc peekLine*(s: Stream): TaintedString = - ## Peeks a line from a stream `s`. Note: This is not very efficient. Raises + ## Peeks a line from a stream `s`. Note: This is not very efficient. Raises ## `EIO` if an error occurred. let pos = getPosition(s) defer: setPosition(s, pos) @@ -276,8 +276,8 @@ type proc ssAtEnd(s: Stream): bool = var s = StringStream(s) return s.pos >= s.data.len - -proc ssSetPosition(s: Stream, pos: int) = + +proc ssSetPosition(s: Stream, pos: int) = var s = StringStream(s) s.pos = clamp(pos, 0, s.data.high) @@ -288,17 +288,17 @@ proc ssGetPosition(s: Stream): int = proc ssReadData(s: Stream, buffer: pointer, bufLen: int): int = var s = StringStream(s) result = min(bufLen, s.data.len - s.pos) - if result > 0: + if result > 0: copyMem(buffer, addr(s.data[s.pos]), result) inc(s.pos, result) proc ssPeekData(s: Stream, buffer: pointer, bufLen: int): int = var s = StringStream(s) result = min(bufLen, s.data.len - s.pos) - if result > 0: + if result > 0: copyMem(buffer, addr(s.data[s.pos]), result) -proc ssWriteData(s: Stream, buffer: pointer, bufLen: int) = +proc ssWriteData(s: Stream, buffer: pointer, bufLen: int) = var s = StringStream(s) if bufLen <= 0: return @@ -311,7 +311,7 @@ proc ssClose(s: Stream) = var s = StringStream(s) s.data = nil -proc newStringStream*(s: string = ""): StringStream = +proc newStringStream*(s: string = ""): StringStream = ## creates a new stream from the string `s`. new(result) result.data = s @@ -343,7 +343,7 @@ when not defined(js): proc fsReadData(s: Stream, buffer: pointer, bufLen: int): int = result = readBuffer(FileStream(s).f, buffer, bufLen) - + proc fsPeekData(s: Stream, buffer: pointer, bufLen: int): int = let pos = fsGetPosition(s) defer: fsSetPosition(s, pos) @@ -383,14 +383,14 @@ else: handle*: FileHandle pos: int - {.deprecated: [PFileHandleStream: FileHandleStream, + {.deprecated: [PFileHandleStream: FileHandleStream, TFileHandleStream: FileHandleStreamObj].} proc newEOS(msg: string): ref OSError = new(result) result.msg = msg - proc hsGetPosition(s: FileHandleStream): int = + proc hsGetPosition(s: FileHandleStream): int = return s.pos when defined(windows): @@ -398,30 +398,30 @@ else: discard else: import posix - - proc hsSetPosition(s: FileHandleStream, pos: int) = + + proc hsSetPosition(s: FileHandleStream, pos: int) = discard lseek(s.handle, pos, SEEK_SET) proc hsClose(s: FileHandleStream) = discard close(s.handle) - proc hsAtEnd(s: FileHandleStream): bool = + proc hsAtEnd(s: FileHandleStream): bool = var pos = hsGetPosition(s) var theEnd = lseek(s.handle, 0, SEEK_END) result = pos >= theEnd hsSetPosition(s, pos) # set position back - proc hsReadData(s: FileHandleStream, buffer: pointer, bufLen: int): int = + proc hsReadData(s: FileHandleStream, buffer: pointer, bufLen: int): int = result = posix.read(s.handle, buffer, bufLen) inc(s.pos, result) - + proc hsPeekData(s: FileHandleStream, buffer: pointer, bufLen: int): int = result = posix.read(s.handle, buffer, bufLen) - - proc hsWriteData(s: FileHandleStream, buffer: pointer, bufLen: int) = - if posix.write(s.handle, buffer, bufLen) != bufLen: + + proc hsWriteData(s: FileHandleStream, buffer: pointer, bufLen: int) = + if posix.write(s.handle, buffer, bufLen) != bufLen: raise newEIO("cannot write to stream") inc(s.pos, bufLen) - proc newFileHandleStream*(handle: FileHandle): FileHandleStream = + proc newFileHandleStream*(handle: FileHandle): FileHandleStream = new(result) result.handle = handle result.pos = 0 @@ -433,8 +433,8 @@ else: result.peekData = hsPeekData result.writeData = hsWriteData - proc newFileHandleStream*(filename: string, - mode: FileMode): FileHandleStream = + proc newFileHandleStream*(filename: string, + mode: FileMode): FileHandleStream = when defined(windows): discard else: From 116347674c90873366f09c6464ec2c0f22f19b82 Mon Sep 17 00:00:00 2001 From: Sergey Avseyev Date: Tue, 26 May 2015 00:29:58 +0300 Subject: [PATCH 0278/1263] Fix peekLine() for streams Motivation ---------- peekLine procs use defer to reset position in the stream, but it also make them always return nil. Modification ------------ Explicitly set result value in peekLine, and write missing unit test. Result ------ Tests are green and bug is fixed --- lib/pure/streams.nim | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/lib/pure/streams.nim b/lib/pure/streams.nim index f6c65466c..f51c979eb 100644 --- a/lib/pure/streams.nim +++ b/lib/pure/streams.nim @@ -242,7 +242,7 @@ proc peekLine*(s: Stream, line: var TaintedString): bool = ## otherwise. If ``false`` is returned `line` contains no new data. let pos = getPosition(s) defer: setPosition(s, pos) - readLine(s, line) + result = readLine(s, line) proc readLine*(s: Stream): TaintedString = ## Reads a line from a stream `s`. Note: This is not very efficient. Raises @@ -263,7 +263,7 @@ proc peekLine*(s: Stream): TaintedString = ## `EIO` if an error occurred. let pos = getPosition(s) defer: setPosition(s, pos) - readLine(s) + result = readLine(s) type StringStream* = ref StringStreamObj ## a stream that encapsulates a string @@ -458,3 +458,7 @@ when defined(testing): assert(ss.getPosition == 5) # did move assert(ss.peekLine() == "uick brown fox jumped over the lazy dog.") assert(ss.getPosition == 5) # haven't moved + var str = newString(100) + assert(ss.peekLine(str)) + assert(str == "uick brown fox jumped over the lazy dog.") + assert(ss.getPosition == 5) # haven't moved From 55e126c5c8ed63580110110fe56a7c7995940c14 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Mon, 25 May 2015 11:48:49 -0400 Subject: [PATCH 0279/1263] Clean up JSON tests --- lib/pure/json.nim | 29 ++++------------------------- 1 file changed, 4 insertions(+), 25 deletions(-) diff --git a/lib/pure/json.nim b/lib/pure/json.nim index 518572be3..0959bb221 100644 --- a/lib/pure/json.nim +++ b/lib/pure/json.nim @@ -1187,24 +1187,13 @@ when false: # To get that we shall use, obj["json"] when isMainModule: - #var node = parse("{ \"test\": null }") - #echo(node.existsKey("test56")) - var parsed = parseFile("tests/testdata/jsontest.json") var parsed2 = parseFile("tests/testdata/jsontest2.json") - when not defined(testing): - echo(parsed) - echo() - echo(pretty(parsed, 2)) - echo() - echo(parsed["keyÄÖöoßß"]) - echo() - echo(pretty(parsed2)) - try: - echo(parsed["key2"][12123]) - raise newException(ValueError, "That line was expected to fail") - except IndexError: echo() + try: + discard parsed["key2"][12123] + assert(false) + except IndexError: assert(true) let testJson = parseJson"""{ "a": [1, 2, 3, 4], "b": "asd" }""" # nil passthrough @@ -1271,13 +1260,3 @@ when isMainModule: } ] assert j3 == %[%{"name": %"John", "age": %30}, %{"name": %"Susan", "age": %31}] - - when not defined(testing): - discard """ - while true: - var json = stdin.readLine() - var node = parse(json) - echo(node) - echo() - echo() - """ From d3fc943b6d1bf2815bcd77d9a8b5535dc83df468 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Mon, 25 May 2015 11:49:23 -0400 Subject: [PATCH 0280/1263] Fix guard for streams tests --- lib/pure/streams.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/pure/streams.nim b/lib/pure/streams.nim index f51c979eb..c85a09bad 100644 --- a/lib/pure/streams.nim +++ b/lib/pure/streams.nim @@ -449,7 +449,7 @@ else: if handle < 0: raise newEOS("posix.open() call failed") result = newFileHandleStream(handle) -when defined(testing): +when isMainModule and defined(testing): var ss = newStringStream("The quick brown fox jumped over the lazy dog.\nThe lazy dog ran") assert(ss.getPosition == 0) assert(ss.peekStr(5) == "The q") From 1001fd21665ec1662d42e6e2bdc3cc98318b7002 Mon Sep 17 00:00:00 2001 From: Sergey Avseyev Date: Tue, 26 May 2015 08:36:23 +0300 Subject: [PATCH 0281/1263] Fix Boehm GC on linux Motivation ---------- Some linuxes (like Fedora) actually multiarch. And it means that libgc.so.1 not always installed into /usr/lib. It is better to entrust this job to ld and system configuration for it. Modification ------------ Use relative path for Boehm GC on 'other' OS (and linux in particular) Result ------ It is possible now to build nim with --gc:boehm on linux --- lib/system/mmdisp.nim | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/lib/system/mmdisp.nim b/lib/system/mmdisp.nim index a378f86e7..bdbb3a95a 100644 --- a/lib/system/mmdisp.nim +++ b/lib/system/mmdisp.nim @@ -70,7 +70,7 @@ when defined(boehmgc): elif defined(macosx): const boehmLib = "libgc.dylib" else: - const boehmLib = "/usr/lib/libgc.so.1" + const boehmLib = "libgc.so.1" proc boehmGCinit {.importc: "GC_init", dynlib: boehmLib.} proc boehmGC_disable {.importc: "GC_disable", dynlib: boehmLib.} @@ -335,4 +335,3 @@ else: include "system/gc" {.pop.} - From 1156e8ef9d3bc7263f58d86c325cd5a170171d3f Mon Sep 17 00:00:00 2001 From: yglukhov Date: Tue, 26 May 2015 11:32:07 +0300 Subject: [PATCH 0282/1263] Minor cosmetic changes. --- compiler/ast.nim | 22 +++++----------------- 1 file changed, 5 insertions(+), 17 deletions(-) diff --git a/compiler/ast.nim b/compiler/ast.nim index 3798410e8..64cb1b1bc 100644 --- a/compiler/ast.nim +++ b/compiler/ast.nim @@ -1198,23 +1198,11 @@ proc newSons*(father: PType, length: int) = else: setLen(father.sons, length) -proc sonsLen*(n: PType): int = - if isNil(n.sons): result = 0 - else: result = len(n.sons) - -proc len*(n: PType): int = - if isNil(n.sons): result = 0 - else: result = len(n.sons) - -proc sonsLen*(n: PNode): int = - if isNil(n.sons): result = 0 - else: result = len(n.sons) - -proc lastSon*(n: PNode): PNode = - result = n.sons[sonsLen(n) - 1] - -proc lastSon*(n: PType): PType = - result = n.sons[sonsLen(n) - 1] +proc sonsLen*(n: PType): int = n.sons.len +proc len*(n: PType): int = n.sons.len +proc sonsLen*(n: PNode): int = n.sons.len +proc lastSon*(n: PNode): PNode = n.sons[^1] +proc lastSon*(n: PType): PType = n.sons[^1] proc assignType*(dest, src: PType) = dest.kind = src.kind From ba2aa474a1e96acb06190236fbc2896d2e170494 Mon Sep 17 00:00:00 2001 From: Sergey Avseyev Date: Tue, 26 May 2015 12:51:31 +0300 Subject: [PATCH 0283/1263] Implement support for XZ dist tarball Motivation ---------- Currenly tarballs for linux created manually. ZIP files are not suitable, because they do not preserve unix file permissions. Modification ------------ Implement 'koch xz' command to produce dist tarball in xz format. Also the same command implemented in niminst.nim. Result ------ Now it is easy to create source distribution for git stapshot and use it further in packaging scripts. --- koch.nim | 8 ++++++++ tools/niminst/niminst.nim | 42 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/koch.nim b/koch.nim index a951b422f..c6db6893c 100644 --- a/koch.nim +++ b/koch.nim @@ -47,6 +47,7 @@ Possible Commands: csource [options] builds the C sources for installation pdf builds the PDF documentation zip builds the installation ZIP package + xz builds the installation XZ package nsis [options] builds the NSIS Setup installer (for Windows) tests [options] run the testsuite update updates nim to the latest version from github @@ -112,6 +113,12 @@ proc targz(args: string) = exec("$# --var:version=$# --var:mingw=none --main:compiler/nim.nim targz compiler/installer.ini" % ["tools" / "niminst" / "niminst".exe, VersionAsString]) +proc xz(args: string) = + exec("$3 cc -r $2 --var:version=$1 --var:mingw=none --main:compiler/nim.nim scripts compiler/installer.ini" % + [VersionAsString, compileNimInst, findNim()]) + exec("$# --var:version=$# --var:mingw=none --main:compiler/nim.nim xz compiler/installer.ini" % + ["tools" / "niminst" / "niminst".exe, VersionAsString]) + proc buildTool(toolname, args: string) = exec("$# cc $# $#" % [findNim(), args, toolname]) copyFile(dest="bin"/ splitFile(toolname).name.exe, source=toolname.exe) @@ -368,6 +375,7 @@ of cmdArgument: of "csource", "csources": csource(op.cmdLineRest) of "zip": zip(op.cmdLineRest) of "targz": targz(op.cmdLineRest) + of "xz": xz(op.cmdLineRest) of "nsis": nsis(op.cmdLineRest) of "install": install(op.cmdLineRest) of "test", "tests": tests(op.cmdLineRest) diff --git a/tools/niminst/niminst.nim b/tools/niminst/niminst.nim index f0ae45484..aed4624f5 100644 --- a/tools/niminst/niminst.nim +++ b/tools/niminst/niminst.nim @@ -36,6 +36,7 @@ type actionScripts # action: create install and deinstall scripts actionZip, # action: create zip file actionTargz, # action: create targz file + actionXz, # action: create xz file actionDeb # action: prepare deb package FileCategory = enum @@ -173,6 +174,7 @@ proc parseCmdLine(c: var ConfigData) = of "scripts": incl(c.actions, actionScripts) of "zip": incl(c.actions, actionZip) of "targz": incl(c.actions, actionTargz) + of "xz": incl(c.actions, actionXz) of "inno": incl(c.actions, actionInno) of "nsis": incl(c.actions, actionNsis) of "deb": incl(c.actions, actionDeb) @@ -600,6 +602,44 @@ proc targzDist(c: var ConfigData) = finally: setCurrentDir(oldDir) +proc xzDist(c: var ConfigData) = + let proj = toLower(c.name) & "-" & c.version + var n = "$#.tar.xz" % proj + let tmpDir = if c.outdir.len == 0: "build" else: c.outdir + + template processFile(z, dest, src) = + let s = src + let d = dest + echo "Copying ", s, " to ", tmpDir / d + let destdir = tmpdir / d.splitFile.dir + if not dirExists(destdir): createDir(destdir) + copyFile(s, tmpDir / d) + + processFile(z, proj / buildBatFile32, "build" / buildBatFile32) + processFile(z, proj / buildBatFile64, "build" / buildBatFile64) + processFile(z, proj / buildShFile, "build" / buildShFile) + processFile(z, proj / makeFile, "build" / makeFile) + processFile(z, proj / installShFile, installShFile) + processFile(z, proj / deinstallShFile, deinstallShFile) + for f in walkFiles(c.libpath / "lib/*.h"): + processFile(z, proj / "c_code" / extractFilename(f), f) + for osA in 1..c.oses.len: + for cpuA in 1..c.cpus.len: + var dir = buildDir(osA, cpuA) + for k, f in walkDir("build" / dir): + if k == pcFile: processFile(z, proj / dir / extractFilename(f), f) + + for cat in items({fcConfig..fcOther, fcUnix}): + for f in items(c.cat[cat]): processFile(z, proj / f, f) + + let oldDir = getCurrentDir() + setCurrentDir(tmpDir) + try: + if execShellCmd("tar Jcf $1.tar.xz $1" % proj) != 0: + echo("External program failed") + finally: + setCurrentDir(oldDir) + # -- prepare build files for .deb creation proc debDist(c: var ConfigData) = @@ -668,5 +708,7 @@ if actionZip in c.actions: quit("libzip is not installed") if actionTargz in c.actions: targzDist(c) +if actionXz in c.actions: + xzDist(c) if actionDeb in c.actions: debDist(c) From 4caf5482d43fb8230779363c2e7405d25d428b85 Mon Sep 17 00:00:00 2001 From: Sergey Avseyev Date: Tue, 26 May 2015 13:27:02 +0300 Subject: [PATCH 0284/1263] Remove outdated targz from niminst --- koch.nim | 7 ------- tools/niminst/niminst.nim | 44 --------------------------------------- 2 files changed, 51 deletions(-) diff --git a/koch.nim b/koch.nim index c6db6893c..fc292401a 100644 --- a/koch.nim +++ b/koch.nim @@ -107,12 +107,6 @@ proc zip(args: string) = exec("$# --var:version=$# --var:mingw=none --main:compiler/nim.nim zip compiler/installer.ini" % ["tools/niminst/niminst".exe, VersionAsString]) -proc targz(args: string) = - exec("$3 cc -r $2 --var:version=$1 --var:mingw=none --main:compiler/nim.nim scripts compiler/installer.ini" % - [VersionAsString, compileNimInst, findNim()]) - exec("$# --var:version=$# --var:mingw=none --main:compiler/nim.nim targz compiler/installer.ini" % - ["tools" / "niminst" / "niminst".exe, VersionAsString]) - proc xz(args: string) = exec("$3 cc -r $2 --var:version=$1 --var:mingw=none --main:compiler/nim.nim scripts compiler/installer.ini" % [VersionAsString, compileNimInst, findNim()]) @@ -374,7 +368,6 @@ of cmdArgument: of "pdf": pdf() of "csource", "csources": csource(op.cmdLineRest) of "zip": zip(op.cmdLineRest) - of "targz": targz(op.cmdLineRest) of "xz": xz(op.cmdLineRest) of "nsis": nsis(op.cmdLineRest) of "install": install(op.cmdLineRest) diff --git a/tools/niminst/niminst.nim b/tools/niminst/niminst.nim index aed4624f5..0afef125b 100644 --- a/tools/niminst/niminst.nim +++ b/tools/niminst/niminst.nim @@ -35,7 +35,6 @@ type actionNsis, # action: create NSIS installer actionScripts # action: create install and deinstall scripts actionZip, # action: create zip file - actionTargz, # action: create targz file actionXz, # action: create xz file actionDeb # action: prepare deb package @@ -173,7 +172,6 @@ proc parseCmdLine(c: var ConfigData) = of "csource": incl(c.actions, actionCSource) of "scripts": incl(c.actions, actionScripts) of "zip": incl(c.actions, actionZip) - of "targz": incl(c.actions, actionTargz) of "xz": incl(c.actions, actionXz) of "inno": incl(c.actions, actionInno) of "nsis": incl(c.actions, actionNsis) @@ -562,46 +560,6 @@ when haveZipLib: else: quit("Cannot open for writing: " & n) -proc targzDist(c: var ConfigData) = - let proj = toLower(c.name) & "-" & c.version - var n = "$#.tar.gz" % proj - let tmpDir = if c.outdir.len == 0: "build" else: c.outdir - - template processFile(z, dest, src) = - let s = src - let d = dest - echo "Copying ", s, " to ", tmpDir / d - let destdir = tmpdir / d.splitFile.dir - if not dirExists(destdir): createDir(destdir) - copyFile(s, tmpDir / d) - - processFile(z, proj / buildBatFile32, "build" / buildBatFile32) - processFile(z, proj / buildBatFile64, "build" / buildBatFile64) - processFile(z, proj / buildShFile, "build" / buildShFile) - processFile(z, proj / makeFile, "build" / makeFile) - processFile(z, proj / installShFile, installShFile) - processFile(z, proj / deinstallShFile, deinstallShFile) - for f in walkFiles(c.libpath / "lib/*.h"): - processFile(z, proj / "c_code" / extractFilename(f), f) - for osA in 1..c.oses.len: - for cpuA in 1..c.cpus.len: - var dir = buildDir(osA, cpuA) - for k, f in walkDir("build" / dir): - if k == pcFile: processFile(z, proj / dir / extractFilename(f), f) - - for cat in items({fcConfig..fcOther, fcUnix}): - for f in items(c.cat[cat]): processFile(z, proj / f, f) - - let oldDir = getCurrentDir() - setCurrentDir(tmpDir) - try: - #if execShellCmd("7z a -ttar $1.tar $1" % proj) != 0 or - # execShellCmd("7z a -tgzip $1.tar.gz $1.tar" % proj) != 0 or - if execShellCmd("7z a -tzip $1.zip $1" % proj) != 0: - echo("External program failed") - finally: - setCurrentDir(oldDir) - proc xzDist(c: var ConfigData) = let proj = toLower(c.name) & "-" & c.version var n = "$#.tar.xz" % proj @@ -706,8 +664,6 @@ if actionZip in c.actions: zipDist(c) else: quit("libzip is not installed") -if actionTargz in c.actions: - targzDist(c) if actionXz in c.actions: xzDist(c) if actionDeb in c.actions: From 0fd0ace00c5b6cf347cb82b460973c5d6490d45a Mon Sep 17 00:00:00 2001 From: Sergey Avseyev Date: Tue, 26 May 2015 13:43:21 +0300 Subject: [PATCH 0285/1263] Set file permissions when prepare XZ tarball --- tools/niminst/niminst.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/niminst/niminst.nim b/tools/niminst/niminst.nim index 0afef125b..6123259f5 100644 --- a/tools/niminst/niminst.nim +++ b/tools/niminst/niminst.nim @@ -571,7 +571,7 @@ proc xzDist(c: var ConfigData) = echo "Copying ", s, " to ", tmpDir / d let destdir = tmpdir / d.splitFile.dir if not dirExists(destdir): createDir(destdir) - copyFile(s, tmpDir / d) + copyFileWithPermissions(s, tmpDir / d) processFile(z, proj / buildBatFile32, "build" / buildBatFile32) processFile(z, proj / buildBatFile64, "build" / buildBatFile64) From a333cf939fae154ebd562494d5854e0b60ed11d3 Mon Sep 17 00:00:00 2001 From: Sergey Avseyev Date: Tue, 26 May 2015 13:51:22 +0300 Subject: [PATCH 0286/1263] Use maximum compression level for XZ tarball --- tools/niminst/niminst.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/niminst/niminst.nim b/tools/niminst/niminst.nim index 6123259f5..99befa92d 100644 --- a/tools/niminst/niminst.nim +++ b/tools/niminst/niminst.nim @@ -593,7 +593,7 @@ proc xzDist(c: var ConfigData) = let oldDir = getCurrentDir() setCurrentDir(tmpDir) try: - if execShellCmd("tar Jcf $1.tar.xz $1" % proj) != 0: + if execShellCmd("XZ_OPT=-9 tar Jcf $1.tar.xz $1" % proj) != 0: echo("External program failed") finally: setCurrentDir(oldDir) From b77ae66e840ac57463012ab5cc678c76a9cbc086 Mon Sep 17 00:00:00 2001 From: Sergey Avseyev Date: Tue, 26 May 2015 14:16:22 +0300 Subject: [PATCH 0287/1263] Get rid of git submodule --- .gitignore | 1 + .gitmodules | 3 --- build.sh => bootstrap.sh | 2 +- csources | 1 - 4 files changed, 2 insertions(+), 5 deletions(-) delete mode 100644 .gitmodules rename build.sh => bootstrap.sh (74%) delete mode 160000 csources diff --git a/.gitignore b/.gitignore index 462df4efc..1971a23cb 100644 --- a/.gitignore +++ b/.gitignore @@ -41,3 +41,4 @@ xcuserdata/ /testresults.html /testresults.json testament.db +/csources diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index 26f35d82c..000000000 --- a/.gitmodules +++ /dev/null @@ -1,3 +0,0 @@ -[submodule "csources"] - path = csources - url = ../../nim-lang/csources.git diff --git a/build.sh b/bootstrap.sh similarity index 74% rename from build.sh rename to bootstrap.sh index 91e169241..ade74a9aa 100755 --- a/build.sh +++ b/bootstrap.sh @@ -3,7 +3,7 @@ set -e set -x if [ ! -e csources/.git ]; then - git submodule update --init --depth 1 + git clone --depth 1 git://github.com/nim-lang/csources.git csources fi cd "csources" diff --git a/csources b/csources deleted file mode 160000 index 15724e2e1..000000000 --- a/csources +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 15724e2e1f3e7749d508dfcd995e84fea2850802 From b8fbe6c711927c9977c90d5253cb90a83c845314 Mon Sep 17 00:00:00 2001 From: Sergey Avseyev Date: Tue, 26 May 2015 14:55:13 +0300 Subject: [PATCH 0288/1263] Ship all testdata with dist --- compiler/installer.ini | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/compiler/installer.ini b/compiler/installer.ini index fff82cb5b..821309a34 100644 --- a/compiler/installer.ini +++ b/compiler/installer.ini @@ -203,7 +203,11 @@ Files: "tests/stdlib/*.nim" Files: "tests/system/*.nim" Files: "tests/template/*.nim" Files: "tests/testament/*.nim" -Files: "tests/testdata/*.nim" +Files: "tests/testdata/*.csv" +Files: "tests/testdata/*.html" +Files: "tests/testdata/*.json" +Files: "tests/testdata/*.txt" +Files: "tests/testdata/*.xml" Files: "tests/threads/*.nim" Files: "tests/threads/*.cfg" Files: "tests/trmacros/*.nim" From d3c4c7c52feec4d0c9deed0540f849166695ebbb Mon Sep 17 00:00:00 2001 From: yglukhov Date: Tue, 26 May 2015 16:00:48 +0300 Subject: [PATCH 0289/1263] Fixes #2798 --- compiler/jsgen.nim | 7 +++++-- tests/js/tobjfieldbyvar.nim | 20 ++++++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) create mode 100644 tests/js/tobjfieldbyvar.nim diff --git a/compiler/jsgen.nim b/compiler/jsgen.nim index 5c7071498..0f6323abc 100644 --- a/compiler/jsgen.nim +++ b/compiler/jsgen.nim @@ -880,7 +880,7 @@ proc genFieldAccess(p: PProc, n: PNode, r: var TCompRes) = if skipTypes(n.sons[0].typ, abstractVarRange).kind == tyTuple: r.res = "$1.Field$2" % [r.res, getFieldPosition(n.sons[1]).rope] else: - if n.sons[1].kind != nkSym: internalError(n.sons[1].info, "genFieldAddr") + if n.sons[1].kind != nkSym: internalError(n.sons[1].info, "genFieldAccess") var f = n.sons[1].sym if f.loc.r == nil: f.loc.r = mangleName(f) r.res = "$1.$2" % [r.res, f.loc.r] @@ -970,7 +970,10 @@ proc genAddr(p: PProc, n: PNode, r: var TCompRes) = of nkCheckedFieldExpr: genCheckedFieldAddr(p, n, r) of nkDotExpr: - genFieldAddr(p, n.sons[0], r) + if mapType(n.typ) == etyBaseIndex: + genFieldAddr(p, n.sons[0], r) + else: + genFieldAccess(p, n.sons[0], r) of nkBracketExpr: var ty = skipTypes(n.sons[0].typ, abstractVarRange) if ty.kind in {tyRef, tyPtr}: ty = skipTypes(ty.lastSon, abstractVarRange) diff --git a/tests/js/tobjfieldbyvar.nim b/tests/js/tobjfieldbyvar.nim new file mode 100644 index 000000000..91a3c1315 --- /dev/null +++ b/tests/js/tobjfieldbyvar.nim @@ -0,0 +1,20 @@ +discard """ + output: '''5 +''' +""" + +# bug #2798 + +type Inner = object + value: int + +type Outer = object + i: Inner + +proc test(i: var Inner) = + i.value += 5 + +var o: Outer +test(o.i) + +echo o.i.value From f9e95b29878e548c8adc4ac15d5880fa26843515 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Tue, 26 May 2015 09:21:15 -0400 Subject: [PATCH 0290/1263] Amend optionals docstring --- lib/pure/optionals.nim | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/pure/optionals.nim b/lib/pure/optionals.nim index d0d832f59..ef01e1260 100644 --- a/lib/pure/optionals.nim +++ b/lib/pure/optionals.nim @@ -97,7 +97,7 @@ proc isNone*[T](self: Option[T]): bool = proc unsafeGet*[T](self: Option[T]): T = - ## Returns the value of a `just`. Behavior is undefined for `none`. + ## Returns the value of a ``some``. Behavior is undefined for ``none``. assert self.isSome self.val @@ -110,7 +110,7 @@ proc get*[T](self: Option[T]): T = proc `==`*(a, b: Option): bool = - ## Returns ``true`` if both ``Option``s are `none`, + ## Returns ``true`` if both ``Option``s are ``none``, ## or if they have equal values (a.has and b.has and a.val == b.val) or (not a.has and not b.has) From e9516e6308687d3c92564ac54fc63f19470ccf2b Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 23 May 2015 14:34:11 -0400 Subject: [PATCH 0291/1263] Use sha1 instead of crc --- compiler/extccomp.nim | 6 +- compiler/rodread.nim | 14 +- compiler/rodwrite.nim | 4 +- compiler/secure_hash.nim | 269 +++++++++++++++++++++++++++------------ 4 files changed, 197 insertions(+), 96 deletions(-) diff --git a/compiler/extccomp.nim b/compiler/extccomp.nim index db6057b5e..2ddb98aba 100644 --- a/compiler/extccomp.nim +++ b/compiler/extccomp.nim @@ -585,13 +585,11 @@ proc externalFileChanged(filename: string): bool = return false var crcFile = toGeneratedFile(filename.withPackageName, "crc") - var currentCrc = int(footprint(filename)) + var currentCrc = footprint(filename) var f: File if open(f, crcFile, fmRead): - var line = newStringOfCap(40) - if not f.readLine(line): line = "0" + let oldCrc = parseSecureHash(f.readLine()) close(f) - var oldCrc = parseInt(line) result = oldCrc != currentCrc else: result = true diff --git a/compiler/rodread.nim b/compiler/rodread.nim index 51d60f5b5..27cb96ca1 100644 --- a/compiler/rodread.nim +++ b/compiler/rodread.nim @@ -541,7 +541,8 @@ proc cmdChangeTriggersRecompilation(old, new: TCommands): bool = proc processRodFile(r: PRodReader, crc: SecureHash) = var w: string - d, inclCrc: int + d: int + var inclCrc: SecureHash while r.s[r.pos] != '\0': var section = rdWord(r) if r.reason != rrNone: @@ -549,7 +550,8 @@ proc processRodFile(r: PRodReader, crc: SecureHash) = case section of "CRC": inc(r.pos) # skip ':' - if int(crc) != decodeVInt(r.s, r.pos): r.reason = rrCrcChange + if crc != parseSecureHash(decodeStr(r.s, r.pos)): + r.reason = rrCrcChange of "ID": inc(r.pos) # skip ':' r.moduleID = decodeVInt(r.s, r.pos) @@ -596,9 +598,9 @@ proc processRodFile(r: PRodReader, crc: SecureHash) = while r.s[r.pos] != ')': w = r.files[decodeVInt(r.s, r.pos)].toFullPath inc(r.pos) # skip ' ' - inclCrc = decodeVInt(r.s, r.pos) + inclCrc = parseSecureHash(decodeStr(r.s, r.pos)) if r.reason == rrNone: - if not existsFile(w) or (inclCrc != int(secureHashFile(w))): + if not existsFile(w) or (inclCrc != secureHashFile(w)): r.reason = rrInclDeps if r.s[r.pos] == '\x0A': inc(r.pos) @@ -649,7 +651,7 @@ proc startsWith(buf: cstring, token: string, pos = 0): bool = while s < token.len and buf[pos+s] == token[s]: inc s result = s == token.len -proc newRodReader(modfilename: string, crc: SecureHash, +proc newRodReader(modfilename: string, crc: SecureHash, readerIndex: int): PRodReader = new(result) try: @@ -1017,7 +1019,7 @@ proc writeType(f: File; t: PType) = f.write("]\n") proc viewFile(rodfile: string) = - var r = newRodReader(rodfile, 0, 0) + var r = newRodReader(rodfile, secureHash(""), 0) if r == nil: rawMessage(errGenerated, "cannot open file (or maybe wrong version):" & rodfile) diff --git a/compiler/rodwrite.nim b/compiler/rodwrite.nim index 22ecdd8af..3454b9ade 100644 --- a/compiler/rodwrite.nim +++ b/compiler/rodwrite.nim @@ -96,7 +96,7 @@ proc addInclDep(w: PRodWriter, dep: string) = var resolved = dep.findModule(w.module.info.toFullPath) encodeVInt(fileIdx(w, dep), w.inclDeps) add(w.inclDeps, " ") - encodeVInt(secureHashFile(resolved), w.inclDeps) + encodeStr($secureHashFile(resolved), w.inclDeps) add(w.inclDeps, rodNL) proc pushType(w: PRodWriter, t: PType) = @@ -440,7 +440,7 @@ proc writeRod(w: PRodWriter) = f.write(rodNL) var crc = "CRC:" - encodeVInt(w.crc, crc) + encodeStr($w.crc, crc) f.write(crc) f.write(rodNL) diff --git a/compiler/secure_hash.nim b/compiler/secure_hash.nim index 7a2b6e4c2..a2ddd02f0 100644 --- a/compiler/secure_hash.nim +++ b/compiler/secure_hash.nim @@ -1,101 +1,202 @@ # # # The Nim Compiler -# (c) Copyright 2012 Andreas Rumpf +# (c) Copyright 2015 Nim Contributers # # See the file "copying.txt", included in this # distribution, for details about the copyright. # -import - strutils +import + strutils, unsigned -type - SecureHash* = int32 +const sha_digest_size = 20 -const - InitCrc32 = SecureHash(- 1) +type + SHA1Digest = array[0 .. sha_digest_size-1, uint8] + SecureHash* = distinct SHA1Digest -proc secureHashFile*(filename: string): SecureHash -# implementation +const emptySecureHash = SecureHash([ + 0u8, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0, +]) -type - TCRC_TabEntry = int +proc sha1(src: string) : SHA1Digest -const - crc32table: array[0..255, TCRC_TabEntry] = [0, 1996959894, - 301047508, - - 1727442502, 124634137, 1886057615, - 379345611, - 1637575261, 249268274, - 2044508324, - 522852066, - 1747789432, 162941995, 2125561021, - 407360249, - - 1866523247, 498536548, 1789927666, - 205950648, - 2067906082, 450548861, - 1843258603, - 187386543, - 2083289657, 325883990, 1684777152, - 43845254, - - 1973040660, 335633487, 1661365465, - 99664541, - 1928851979, 997073096, - 1281953886, - 715111964, - 1570279054, 1006888145, 1258607687, - 770865667, - - 1526024853, 901097722, 1119000684, - 608450090, - 1396901568, 853044451, - 1172266101, - 589951537, - 1412350631, 651767980, 1373503546, - 925412992, - - 1076862698, 565507253, 1454621731, - 809855591, - 1195530993, 671266974, - 1594198024, - 972236366, - 1324619484, 795835527, 1483230225, - 1050600021, - - 1234817731, 1994146192, 31158534, - 1731059524, - 271249366, 1907459465, - 112637215, - 1614814043, - 390540237, 2013776290, 251722036, - 1777751922, - - 519137256, 2137656763, 141376813, - 1855689577, - 429695999, 1802195444, - 476864866, - 2056965928, - 228458418, 1812370925, 453092731, - 2113342271, - - 183516073, 1706088902, 314042704, - 1950435094, - 54949764, 1658658271, - 366619977, - 1932296973, - 69972891, 1303535960, 984961486, - 1547960204, - - 725929758, 1256170817, 1037604311, - 1529756563, - 740887301, 1131014506, - 879679996, - 1385723834, - 631195440, 1141124467, 855842277, - 1442165665, - - 586318647, 1342533948, 654459306, - 1106571248, - 921952122, 1466479909, - 544179635, - 1184443383, - 832445281, 1591671054, 702138776, - 1328506846, - - 942167884, 1504918807, 783551873, - 1212326853, - 1061524307, - 306674912, - - 1698712650, 62317068, 1957810842, - 355121351, - 1647151185, 81470997, - 1943803523, - 480048366, - 1805370492, 225274430, 2053790376, - 468791541, - - 1828061283, 167816743, 2097651377, - 267414716, - 2029476910, 503444072, - 1762050814, - 144550051, - 2140837941, 426522225, 1852507879, - 19653770, - - 1982649376, 282753626, 1742555852, - 105259153, - 1900089351, 397917763, - 1622183637, - 690576408, - 1580100738, 953729732, 1340076626, - 776247311, - - 1497606297, 1068828381, 1219638859, - 670225446, - 1358292148, 906185462, - 1090812512, - 547295293, - 1469587627, 829329135, 1181335161, - 882789492, - - 1134132454, 628085408, 1382605366, - 871598187, - 1156888829, 570562233, - 1426400815, - 977650754, - 1296233688, 733239954, 1555261956, - 1026031705, - - 1244606671, 752459403, 1541320221, - 1687895376, - 328994266, 1969922972, - 40735498, - 1677130071, - 351390145, 1913087877, 83908371, - 1782625662, - - 491226604, 2075208622, 213261112, - 1831694693, - 438977011, 2094854071, - 198958881, - 2032938284, - 237706686, 1759359992, 534414190, - 2118248755, - - 155638181, 1873836001, 414664567, - 2012718362, - 15766928, 1711684554, - 285281116, - 1889165569, - 127750551, 1634467795, 376229701, - 1609899400, - - 686959890, 1308918612, 956543938, - 1486412191, - 799009033, 1231636301, - 1047427035, - 1362007478, - 640263460, 1088359270, 936918000, - 1447252397, - - 558129467, 1202900863, 817233897, - 1111625188, - 893730166, 1404277552, - 615818150, - 1160759803, - 841546093, 1423857449, 601450431, - 1285129682, - - 1000256840, 1567103746, 711928724, - 1274298825, - 1022587231, 1510334235, - 755167117] +proc secureHash*(str: string): SecureHash = SecureHash(sha1(str)) +proc secureHashFile*(filename: string): SecureHash = secureHash(readFile(filename)) +proc `$`*(self: SecureHash): string = + result = "" + for v in SHA1Digest(self): + result.add(toHex(int(v), 2)) -proc updateCrc32(val: int8, crc: SecureHash): SecureHash = - result = SecureHash(crc32table[(int(crc) xor (int(val) and 0x000000FF)) and - 0x000000FF]) xor (crc shr SecureHash(8)) +proc parseSecureHash*(hash: string): SecureHash = + for i in 0.. = 56: + innerHash(state, w) + clearBuffer(w) + + w[15] = uint32(byteLen) shl 3 + innerHash(state, w) + + # Store hash in result pointer, and make sure we get in in the correct order + # on both endian models. + for i in 0 .. sha_digest_size-1: + result[i] = uint8((int(state[i shr 2]) shr ((3-(i and 3)) * 8)) and 255) + +proc sha1(src: string) : SHA1Digest = + ## Calculate SHA1 from input string + computeInternal(src) From badc3a0929affb14415b178a96ee10151b795196 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 23 May 2015 14:40:33 -0400 Subject: [PATCH 0292/1263] Add simple tests to secure_hash --- compiler/secure_hash.nim | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/compiler/secure_hash.nim b/compiler/secure_hash.nim index a2ddd02f0..3383f23a2 100644 --- a/compiler/secure_hash.nim +++ b/compiler/secure_hash.nim @@ -42,6 +42,11 @@ proc `==`*(a, b: SecureHash): bool = SHA1Digest(a) == SHA1Digest(b) +when isMainModule: + let hash1 = secureHash("a93tgj0p34jagp9[agjp98ajrhp9aej]") + doAssert hash1 == hash1 + doAssert parseSecureHash($hash1) == hash1 + # Copyright (c) 2011, Micael Hildenborg # All rights reserved. From c593c476965d8f019a86b51987aa62a685040d39 Mon Sep 17 00:00:00 2001 From: Oscar Campbell Date: Tue, 26 May 2015 16:28:44 +0200 Subject: [PATCH 0293/1263] Fix introduced erroneous use of "canonical" back to original wording. Fix faulty description of proc params behavior. Remove 'null' return type in example. --- doc/manual/procs.txt | 7 ++++--- doc/manual/trmacros.txt | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/doc/manual/procs.txt b/doc/manual/procs.txt index fb2c7a108..38e343686 100644 --- a/doc/manual/procs.txt +++ b/doc/manual/procs.txt @@ -25,15 +25,16 @@ A parameter may be declared with a default value which is used if the caller does not provide a value for the argument. .. code-block:: nim - # b is optional, 47 is its default value - proc foo(a, b: int = 47): int + # b is optional with 47 as its default value + proc foo(a: int, b: int = 47): int Parameters can be declared mutable and so allow the proc to modify those arguments, by using the type modifier `var`. .. code-block:: nim # "returning" a value to the caller through the 2nd argument - proc foo(inp: int, outp: var int): void = + # Notice that the function uses no actual return value at all (ie void) + proc foo(inp: int, outp: var int) = outp = inp + 47 If the proc declaration has no body, it is a `forward`:idx: declaration. If the diff --git a/doc/manual/trmacros.txt b/doc/manual/trmacros.txt index de98e3a46..5ff24a36a 100644 --- a/doc/manual/trmacros.txt +++ b/doc/manual/trmacros.txt @@ -54,7 +54,7 @@ blindly: .. code-block:: nim template mulIsCommutative{`*`(a, b)}(a, b: int): int = b*a -What optimizers really need to do is a *canonization*: +What optimizers really need to do is a *canonicalization*: .. code-block:: nim template canonMul{`*`(a, b)}(a: int{lit}, b: int): int = b*a From c02be0fe00eae464a44f9ddeb948e44fb43a8ddc Mon Sep 17 00:00:00 2001 From: Bruce Doan Date: Wed, 27 May 2015 00:18:15 +0700 Subject: [PATCH 0294/1263] Allow TR, TH, TD tags inside THEAD and TFOOT --- lib/pure/htmlparser.nim | 98 ++++++++++++++++++++--------------------- 1 file changed, 49 insertions(+), 49 deletions(-) diff --git a/lib/pure/htmlparser.nim b/lib/pure/htmlparser.nim index 9719181b8..658e4186d 100644 --- a/lib/pure/htmlparser.nim +++ b/lib/pure/htmlparser.nim @@ -9,7 +9,7 @@ ## This module parses an HTML document and creates its XML tree representation. ## It is supposed to handle the *wild* HTML the real world uses. -## +## ## It can be used to parse a wild HTML document and output it as valid XHTML ## document (well, if you are lucky): ## @@ -19,7 +19,7 @@ ## ## Every tag in the resulting tree is in lower case. ## -## **Note:** The resulting ``PXmlNode`` already uses the ``clientData`` field, +## **Note:** The resulting ``PXmlNode`` already uses the ``clientData`` field, ## so it cannot be used by clients of this library. ## ## Example: Transforming hyperlinks @@ -181,24 +181,24 @@ type const tagToStr* = [ - "a", "abbr", "acronym", "address", "applet", "area", "article", + "a", "abbr", "acronym", "address", "applet", "area", "article", "aside", "audio", - "b", "base", "basefont", "bdi", "bdo", "big", "blockquote", "body", - "br", "button", "canvas", "caption", "center", "cite", "code", + "b", "base", "basefont", "bdi", "bdo", "big", "blockquote", "body", + "br", "button", "canvas", "caption", "center", "cite", "code", "col", "colgroup", "command", - "datalist", "dd", "del", "details", "dfn", "dialog", "div", - "dir", "dl", "dt", "em", "embed", "fieldset", + "datalist", "dd", "del", "details", "dfn", "dialog", "div", + "dir", "dl", "dt", "em", "embed", "fieldset", "figcaption", "figure", "font", "footer", - "form", "frame", "frameset", "h1", "h2", "h3", - "h4", "h5", "h6", "head", "header", "hgroup", "html", "hr", - "i", "iframe", "img", "input", "ins", "isindex", + "form", "frame", "frameset", "h1", "h2", "h3", + "h4", "h5", "h6", "head", "header", "hgroup", "html", "hr", + "i", "iframe", "img", "input", "ins", "isindex", "kbd", "keygen", "label", "legend", "li", "link", "map", "mark", - "menu", "meta", "meter", "nav", "nobr", "noframes", "noscript", - "object", "ol", - "optgroup", "option", "output", "p", "param", "pre", "progress", "q", - "rp", "rt", "ruby", "s", "samp", "script", "section", "select", "small", - "source", "span", "strike", "strong", "style", - "sub", "summary", "sup", "table", + "menu", "meta", "meter", "nav", "nobr", "noframes", "noscript", + "object", "ol", + "optgroup", "option", "output", "p", "param", "pre", "progress", "q", + "rp", "rt", "ruby", "s", "samp", "script", "section", "select", "small", + "source", "span", "strike", "strong", "style", + "sub", "summary", "sup", "table", "tbody", "td", "textarea", "tfoot", "th", "thead", "time", "title", "tr", "track", "tt", "u", "ul", "var", "video", "wbr"] InlineTags* = {tagA, tagAbbr, tagAcronym, tagApplet, tagB, tagBasefont, @@ -206,17 +206,17 @@ const tagEm, tagFont, tagI, tagImg, tagIns, tagInput, tagIframe, tagKbd, tagLabel, tagMap, tagObject, tagQ, tagSamp, tagScript, tagSelect, tagSmall, tagSpan, tagStrong, tagSub, tagSup, tagTextarea, tagTt, - tagVar, tagApplet, tagBasefont, tagFont, tagIframe, tagU, tagS, + tagVar, tagApplet, tagBasefont, tagFont, tagIframe, tagU, tagS, tagStrike, tagWbr} - BlockTags* = {tagAddress, tagBlockquote, tagCenter, tagDel, tagDir, tagDiv, - tagDl, tagFieldset, tagForm, tagH1, tagH2, tagH3, tagH4, - tagH5, tagH6, tagHr, tagIns, tagIsindex, tagMenu, tagNoframes, tagNoscript, - tagOl, tagP, tagPre, tagTable, tagUl, tagCenter, tagDir, tagIsindex, + BlockTags* = {tagAddress, tagBlockquote, tagCenter, tagDel, tagDir, tagDiv, + tagDl, tagFieldset, tagForm, tagH1, tagH2, tagH3, tagH4, + tagH5, tagH6, tagHr, tagIns, tagIsindex, tagMenu, tagNoframes, tagNoscript, + tagOl, tagP, tagPre, tagTable, tagUl, tagCenter, tagDir, tagIsindex, tagMenu, tagNoframes} - SingleTags* = {tagArea, tagBase, tagBasefont, + SingleTags* = {tagArea, tagBase, tagBasefont, tagBr, tagCol, tagFrame, tagHr, tagImg, tagIsindex, tagLink, tagMeta, tagParam, tagWbr} - + Entities = [ ("nbsp", 0x00A0), ("iexcl", 0x00A1), ("cent", 0x00A2), ("pound", 0x00A3), ("curren", 0x00A4), ("yen", 0x00A5), ("brvbar", 0x00A6), ("sect", 0x00A7), @@ -225,13 +225,13 @@ const ("deg", 0x00B0), ("plusmn", 0x00B1), ("sup2", 0x00B2), ("sup3", 0x00B3), ("acute", 0x00B4), ("micro", 0x00B5), ("para", 0x00B6), ("middot", 0x00B7), ("cedil", 0x00B8), ("sup1", 0x00B9), ("ordm", 0x00BA), ("raquo", 0x00BB), - ("frac14", 0x00BC), ("frac12", 0x00BD), ("frac34", 0x00BE), + ("frac14", 0x00BC), ("frac12", 0x00BD), ("frac34", 0x00BE), ("iquest", 0x00BF), ("Agrave", 0x00C0), ("Aacute", 0x00C1), ("Acirc", 0x00C2), ("Atilde", 0x00C3), ("Auml", 0x00C4), ("Aring", 0x00C5), ("AElig", 0x00C6), ("Ccedil", 0x00C7), ("Egrave", 0x00C8), ("Eacute", 0x00C9), ("Ecirc", 0x00CA), ("Euml", 0x00CB), ("Igrave", 0x00CC), ("Iacute", 0x00CD), ("Icirc", 0x00CE), ("Iuml", 0x00CF), ("ETH", 0x00D0), - ("Ntilde", 0x00D1), ("Ograve", 0x00D2), ("Oacute", 0x00D3), + ("Ntilde", 0x00D1), ("Ograve", 0x00D2), ("Oacute", 0x00D3), ("Ocirc", 0x00D4), ("Otilde", 0x00D5), ("Ouml", 0x00D6), ("times", 0x00D7), ("Oslash", 0x00D8), ("Ugrave", 0x00D9), ("Uacute", 0x00DA), ("Ucirc", 0x00DB), ("Uuml", 0x00DC), ("Yacute", 0x00DD), ("THORN", 0x00DE), @@ -263,7 +263,7 @@ const ("zwnj", 0x200C), ("zwj", 0x200D), ("lrm", 0x200E), ("rlm", 0x200F), ("ndash", 0x2013), ("mdash", 0x2014), ("lsquo", 0x2018), ("rsquo", 0x2019), ("sbquo", 0x201A), ("ldquo", 0x201C), ("rdquo", 0x201D), ("bdquo", 0x201E), - ("dagger", 0x2020), ("Dagger", 0x2021), ("bull", 0x2022), + ("dagger", 0x2020), ("Dagger", 0x2021), ("bull", 0x2022), ("hellip", 0x2026), ("permil", 0x2030), ("prime", 0x2032), ("Prime", 0x2033), ("lsaquo", 0x2039), ("rsaquo", 0x203A), ("oline", 0x203E), ("frasl", 0x2044), ("euro", 0x20AC), @@ -422,7 +422,7 @@ proc toHtmlTag(s: string): THtmlTag = of "wbr": tagWbr else: tagUnknown -proc htmlTag*(n: XmlNode): THtmlTag = +proc htmlTag*(n: XmlNode): THtmlTag = ## gets `n`'s tag as a ``THtmlTag``. if n.clientData == 0: n.clientData = toHtmlTag(n.tag).ord @@ -434,7 +434,7 @@ proc htmlTag*(s: string): THtmlTag = let s = if allLower(s): s else: s.toLower result = toHtmlTag(s) -proc entityToUtf8*(entity: string): string = +proc entityToUtf8*(entity: string): string = ## converts an HTML entity name like ``Ü`` to its UTF-8 equivalent. ## "" is returned if the entity name is unknown. The HTML parser ## already converts entities to UTF-8. @@ -442,7 +442,7 @@ proc entityToUtf8*(entity: string): string = if name == entity: return toUTF8(Rune(val)) result = "" -proc addNode(father, son: XmlNode) = +proc addNode(father, son: XmlNode) = if son != nil: add(father, son) proc parse(x: var XmlParser, errors: var seq[string]): XmlNode @@ -452,9 +452,9 @@ proc expected(x: var XmlParser, n: XmlNode): string = template elemName(x: expr): expr = rawData(x) -proc untilElementEnd(x: var XmlParser, result: XmlNode, +proc untilElementEnd(x: var XmlParser, result: XmlNode, errors: var seq[string]) = - # we parsed e.g. ``
`` and don't really expect a ``
``: + # we parsed e.g. ``
`` and don't really expect a ``
``: if result.htmlTag in SingleTags: if x.kind != xmlElementEnd or cmpIgnoreCase(x.elemName, result.tag) != 0: return @@ -468,7 +468,7 @@ proc untilElementEnd(x: var XmlParser, result: XmlNode, tagOption}: errors.add(expected(x, result)) break - of tagTd, tagTh, tagTfoot, tagThead: + of tagTd, tagTh: if htmlTag(x.elemName) in {tagTr, tagTd, tagTh, tagTfoot, tagThead}: errors.add(expected(x, result)) break @@ -482,11 +482,11 @@ proc untilElementEnd(x: var XmlParser, result: XmlNode, break else: discard result.addNode(parse(x, errors)) - of xmlElementEnd: - if cmpIgnoreCase(x.elemName, result.tag) == 0: + of xmlElementEnd: + if cmpIgnoreCase(x.elemName, result.tag) == 0: next(x) else: - #echo "5; expected: ", result.htmltag, " ", x.elemName + #echo "5; expected: ", result.htmltag, " ", x.elemName errors.add(expected(x, result)) # do not skip it here! break @@ -498,7 +498,7 @@ proc untilElementEnd(x: var XmlParser, result: XmlNode, proc parse(x: var XmlParser, errors: var seq[string]): XmlNode = case x.kind - of xmlComment: + of xmlComment: result = newComment(x.rawData) next(x) of xmlCharData, xmlWhitespace: @@ -516,11 +516,11 @@ proc parse(x: var XmlParser, errors: var seq[string]): XmlNode = untilElementEnd(x, result, errors) of xmlElementEnd: errors.add(errorMsg(x, "unexpected ending tag: " & x.elemName)) - of xmlElementOpen: + of xmlElementOpen: result = newElement(x.elemName.toLower) next(x) result.attrs = newStringTable() - while true: + while true: case x.kind of xmlAttribute: result.attrs[x.rawData] = x.rawData2 @@ -540,7 +540,7 @@ proc parse(x: var XmlParser, errors: var seq[string]): XmlNode = of xmlAttribute, xmlElementClose: errors.add(errorMsg(x, " expected")) next(x) - of xmlCData: + of xmlCData: result = newCData(x.rawData) next(x) of xmlEntity: @@ -549,8 +549,8 @@ proc parse(x: var XmlParser, errors: var seq[string]): XmlNode = next(x) of xmlEof: discard -proc parseHtml*(s: Stream, filename: string, - errors: var seq[string]): XmlNode = +proc parseHtml*(s: Stream, filename: string, + errors: var seq[string]): XmlNode = ## parses the XML from stream `s` and returns a ``PXmlNode``. Every ## occurred parsing error is added to the `errors` sequence. var x: XmlParser @@ -558,7 +558,7 @@ proc parseHtml*(s: Stream, filename: string, next(x) # skip the DOCTYPE: if x.kind == xmlSpecial: next(x) - + result = newElement("document") result.addNode(parse(x, errors)) #if x.kind != xmlEof: @@ -573,22 +573,22 @@ proc parseHtml*(s: Stream, filename: string, if result.len == 1: result = result[0] -proc parseHtml*(s: Stream): XmlNode = +proc parseHtml*(s: Stream): XmlNode = ## parses the XTML from stream `s` and returns a ``PXmlNode``. All parsing ## errors are ignored. var errors: seq[string] = @[] result = parseHtml(s, "unknown_html_doc", errors) -proc loadHtml*(path: string, errors: var seq[string]): XmlNode = - ## Loads and parses HTML from file specified by ``path``, and returns +proc loadHtml*(path: string, errors: var seq[string]): XmlNode = + ## Loads and parses HTML from file specified by ``path``, and returns ## a ``PXmlNode``. Every occurred parsing error is added to ## the `errors` sequence. var s = newFileStream(path, fmRead) if s == nil: raise newException(IOError, "Unable to read file: " & path) result = parseHtml(s, path, errors) -proc loadHtml*(path: string): XmlNode = - ## Loads and parses HTML from file specified by ``path``, and returns +proc loadHtml*(path: string): XmlNode = + ## Loads and parses HTML from file specified by ``path``, and returns ## a ``PXmlNode``. All parsing errors are ignored. var errors: seq[string] = @[] result = loadHtml(path, errors) @@ -596,10 +596,10 @@ proc loadHtml*(path: string): XmlNode = when not defined(testing) and isMainModule: import os - var errors: seq[string] = @[] + var errors: seq[string] = @[] var x = loadHtml(paramStr(1), errors) for e in items(errors): echo e - + var f: File if open(f, "test.txt", fmWrite): f.write($x) From 0479831fb07f4a8daf6ce7d5f8eef7a0a320a04d Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Tue, 26 May 2015 16:48:17 -0400 Subject: [PATCH 0295/1263] Rename optionals module to options --- lib/pure/{optionals.nim => options.nim} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename lib/pure/{optionals.nim => options.nim} (100%) diff --git a/lib/pure/optionals.nim b/lib/pure/options.nim similarity index 100% rename from lib/pure/optionals.nim rename to lib/pure/options.nim From 9576bc087d20e8e5cacb9cd92c635d3f9efaf0a7 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Tue, 26 May 2015 18:18:11 -0400 Subject: [PATCH 0296/1263] Change to options module --- src/nre.nim | 24 +++++++++++------------- test/captures.nim | 10 +++++----- test/find.nim | 2 +- test/match.nim | 8 ++++---- test/misc.nim | 2 +- test/optional_nonstrict.nim | 3 +++ 6 files changed, 25 insertions(+), 24 deletions(-) create mode 100644 test/optional_nonstrict.nim diff --git a/src/nre.nim b/src/nre.nim index f96820b2c..2706398ee 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -5,7 +5,7 @@ import unsigned from future import lc, `[]` from strutils import toLower, `%` from math import ceil -import optional_t +import options from unicode import runeLenAt @@ -115,9 +115,7 @@ type RegexMatch* = object ## Usually seen as Option[RegexMatch], it represents the result of an - ## execution. On failure, it is ``None[RegexMatch]``, but if you want - ## automated derefrence, import ``optional_t.nonstrict``. The available - ## fields are as follows: + ## execution. On failure, it is none, on success, it is some. ## ## ``pattern: Regex`` ## the pattern that is being matched @@ -235,15 +233,15 @@ proc `[]`*(pattern: CaptureBounds, i: int): Option[Slice[int]] = let pattern = RegexMatch(pattern) if pattern.pcreMatchBounds[i + 1].a != -1: let bounds = pattern.pcreMatchBounds[i + 1] - return Some(int(bounds.a) .. int(bounds.b-1)) + return some(int(bounds.a) .. int(bounds.b-1)) else: - return None[Slice[int]]() + return none(Slice[int]) proc `[]`*(pattern: Captures, i: int): string = let pattern = RegexMatch(pattern) let bounds = pattern.captureBounds[i] - if bounds: + if bounds.isSome: let bounds = bounds.get return pattern.str.substr(bounds.a, bounds.b) else: @@ -275,7 +273,7 @@ proc toTable*(pattern: Captures, default: string = nil): Table[string, string] = result = initTable[string, string]() toTableImpl(nextVal == nil) -proc toTable*(pattern: CaptureBounds, default = None[Slice[int]]()): +proc toTable*(pattern: CaptureBounds, default = none(Slice[int])): Table[string, Option[Slice[int]]] = result = initTable[string, Option[Slice[int]]]() toTableImpl(nextVal.isNone) @@ -288,13 +286,13 @@ template itemsImpl(cond: bool): stmt {.immediate, dirty.} = else: yield nextVal -iterator items*(pattern: CaptureBounds, default = None[Slice[int]]()): Option[Slice[int]] = +iterator items*(pattern: CaptureBounds, default = none(Slice[int])): Option[Slice[int]] = itemsImpl(nextVal.isNone) iterator items*(pattern: Captures, default: string = nil): string = itemsImpl(nextVal == nil) -proc toSeq*(pattern: CaptureBounds, default = None[Slice[int]]()): seq[Option[Slice[int]]] = +proc toSeq*(pattern: CaptureBounds, default = none(Slice[int])): seq[Option[Slice[int]]] = accumulateResult(pattern.items(default)) proc toSeq*(pattern: Captures, default: string = nil): seq[string] = @@ -454,11 +452,11 @@ proc matchImpl(str: string, pattern: Regex, start, endpos: int, flags: int): Opt cast[ptr cint](addr myResult.pcreMatchBounds[0]), cint(vecsize)) if execRet >= 0: - return Some(myResult) + return some(myResult) case execRet: of pcre.ERROR_NOMATCH: - return None[RegexMatch]() + return none(RegexMatch) of pcre.ERROR_NULL: raise newException(AccessViolationError, "Expected non-null parameters") of pcre.ERROR_BADOPTION: @@ -497,7 +495,7 @@ iterator findIter*(str: string, pattern: Regex, start = 0, endpos = int.high): R while true: var flags = 0 - if match and + if match.isSome and match.get.matchBounds.a > match.get.matchBounds.b: # 0-len match flags = pcre.NOTEMPTY_ATSTART diff --git a/test/captures.nim b/test/captures.nim index 24ba021f5..4f3f15444 100644 --- a/test/captures.nim +++ b/test/captures.nim @@ -1,4 +1,4 @@ -import unittest, optional_t.nonstrict +import unittest, optional_nonstrict include nre suite "captures": @@ -31,8 +31,8 @@ suite "captures": test "named capture bounds": let ex1 = "foo".find(re("(?foo)(?bar)?")) - check(ex1.captureBounds["foo"] == Some(0..2)) - check(ex1.captureBounds["bar"] == None[Slice[int]]()) + check(ex1.captureBounds["foo"] == some(0..2)) + check(ex1.captureBounds["bar"] == none(Slice[int])) test "capture count": let ex1 = re("(?foo)(?bar)?") @@ -42,7 +42,7 @@ suite "captures": test "named capture table": let ex1 = "foo".find(re("(?foo)(?bar)?")) check(ex1.captures.toTable == {"foo" : "foo", "bar" : nil}.toTable()) - check(ex1.captureBounds.toTable == {"foo" : Some(0..2), "bar" : None[Slice[int]]()}.toTable()) + check(ex1.captureBounds.toTable == {"foo" : some(0..2), "bar" : none(Slice[int])}.toTable()) check(ex1.captures.toTable("") == {"foo" : "foo", "bar" : ""}.toTable()) let ex2 = "foobar".find(re("(?foo)(?bar)?")) @@ -51,7 +51,7 @@ suite "captures": test "capture sequence": let ex1 = "foo".find(re("(?foo)(?bar)?")) check(ex1.captures.toSeq == @["foo", nil]) - check(ex1.captureBounds.toSeq == @[Some(0..2), None[Slice[int]]()]) + check(ex1.captureBounds.toSeq == @[some(0..2), none(Slice[int])]) check(ex1.captures.toSeq("") == @["foo", ""]) let ex2 = "foobar".find(re("(?foo)(?bar)?")) diff --git a/test/find.nim b/test/find.nim index 90acaf4e1..05bfb848a 100644 --- a/test/find.nim +++ b/test/find.nim @@ -1,4 +1,4 @@ -import unittest, sequtils, nre, optional_t.nonstrict +import unittest, sequtils, nre, optional_nonstrict suite "find": test "find text": diff --git a/test/match.nim b/test/match.nim index 16fb931c0..38ee5214b 100644 --- a/test/match.nim +++ b/test/match.nim @@ -1,10 +1,10 @@ -include nre, unittest, optional_t.nonstrict +include nre, unittest, optional_nonstrict suite "match": test "upper bound must be inclusive": - check("abc".match(re"abc", endpos = -1) == None[RegexMatch]()) - check("abc".match(re"abc", endpos = 1) == None[RegexMatch]()) - check("abc".match(re"abc", endpos = 2) != None[RegexMatch]()) + check("abc".match(re"abc", endpos = -1) == none(RegexMatch)) + check("abc".match(re"abc", endpos = 1) == none(RegexMatch)) + check("abc".match(re"abc", endpos = 2) != none(RegexMatch)) test "match examples": check("abc".match(re"(\w)").captures[0] == "a") diff --git a/test/misc.nim b/test/misc.nim index f110c3f1e..f4a88b639 100644 --- a/test/misc.nim +++ b/test/misc.nim @@ -1,4 +1,4 @@ -import unittest, nre, strutils, optional_t.nonstrict +import unittest, nre, strutils, optional_nonstrict suite "Misc tests": test "unicode": diff --git a/test/optional_nonstrict.nim b/test/optional_nonstrict.nim new file mode 100644 index 000000000..d13f4fab7 --- /dev/null +++ b/test/optional_nonstrict.nim @@ -0,0 +1,3 @@ +import options +converter option2val*[T](val: Option[T]): T = + return val.get() From c9616897f0e0d932c75b61ed96124d8cbac35076 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Tue, 26 May 2015 18:29:44 -0400 Subject: [PATCH 0297/1263] Don't inspect typedescs --- lib/pure/unittest.nim | 13 +++++++------ tests/stdlib/tunittest.nim | 5 +++++ 2 files changed, 12 insertions(+), 6 deletions(-) create mode 100644 tests/stdlib/tunittest.nim diff --git a/lib/pure/unittest.nim b/lib/pure/unittest.nim index 3bf4724b9..092b1fba2 100644 --- a/lib/pure/unittest.nim +++ b/lib/pure/unittest.nim @@ -157,12 +157,13 @@ macro check*(conditions: stmt): stmt {.immediate.} = # Ident !"v" # IntLit 2 paramAst = exp[i][1] - argsAsgns.add getAst(asgn(arg, paramAst)) - argsPrintOuts.add getAst(print(argStr, arg)) - if exp[i].kind != nnkExprEqExpr: - exp[i] = arg - else: - exp[i][1] = arg + if exp[i].typekind notin {ntyTypeDesc}: + argsAsgns.add getAst(asgn(arg, paramAst)) + argsPrintOuts.add getAst(print(argStr, arg)) + if exp[i].kind != nnkExprEqExpr: + exp[i] = arg + else: + exp[i][1] = arg case checked.kind of nnkCallKinds: diff --git a/tests/stdlib/tunittest.nim b/tests/stdlib/tunittest.nim new file mode 100644 index 000000000..3726eaa9e --- /dev/null +++ b/tests/stdlib/tunittest.nim @@ -0,0 +1,5 @@ +import unittest +import options +test "unittest typedescs": + check(none(int) == none(int)) + check(none(int) != some(1)) From 3daef85d6ee73c7ef3c89c5ca0738698bcdbfbfa Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Tue, 26 May 2015 18:32:10 -0400 Subject: [PATCH 0298/1263] Fix #964, fix #1384 Doesn't actually fix those bugs, but they can no longer be reproduced. Test cases have been added. --- tests/stdlib/tunittest.nim | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/tests/stdlib/tunittest.nim b/tests/stdlib/tunittest.nim index 3726eaa9e..b23b3cdab 100644 --- a/tests/stdlib/tunittest.nim +++ b/tests/stdlib/tunittest.nim @@ -1,4 +1,20 @@ import unittest + + +proc doThings(spuds: var int): int = + spuds = 24 + return 99 +test "#964": + var spuds = 0 + check doThings(spuds) == 99 + check spuds == 24 + + +from strutils import toUpper +test "#1384": + check(@["hello", "world"].map(toUpper) == @["HELLO", "WORLD"]) + + import options test "unittest typedescs": check(none(int) == none(int)) From 0527e1f9fe00642207d78213f7d1436f8aa5ef0d Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Tue, 26 May 2015 19:14:04 -0400 Subject: [PATCH 0299/1263] Rearrange nre files --- lib/impure/{nre/src => }/nre.nim | 4 +- lib/impure/nre/LICENCE | 19 -- lib/impure/nre/README.rst | 258 ------------------ lib/impure/nre/circle.yml | 39 --- lib/impure/nre/nre.nimble | 11 - lib/impure/nre/{src => }/private/pcre.h | 0 lib/impure/nre/{src => }/private/pcre.nim | 2 +- .../nre/{src => }/private/pcre_src/config.h | 0 .../nre/{src => }/private/pcre_src/pcre.h | 0 .../private/pcre_src/pcre_byte_order.c | 0 .../private/pcre_src/pcre_chartables.c | 0 .../{src => }/private/pcre_src/pcre_compile.c | 0 .../{src => }/private/pcre_src/pcre_config.c | 0 .../private/pcre_src/pcre_dfa_exec.c | 0 .../{src => }/private/pcre_src/pcre_exec.c | 0 .../private/pcre_src/pcre_fullinfo.c | 0 .../nre/{src => }/private/pcre_src/pcre_get.c | 0 .../{src => }/private/pcre_src/pcre_globals.c | 0 .../private/pcre_src/pcre_internal.h | 0 .../private/pcre_src/pcre_jit_compile.c | 0 .../private/pcre_src/pcre_maketables.c | 0 .../{src => }/private/pcre_src/pcre_newline.c | 0 .../private/pcre_src/pcre_ord2utf8.c | 0 .../private/pcre_src/pcre_refcount.c | 0 .../private/pcre_src/pcre_string_utils.c | 0 .../{src => }/private/pcre_src/pcre_study.c | 0 .../{src => }/private/pcre_src/pcre_tables.c | 0 .../nre/{src => }/private/pcre_src/pcre_ucd.c | 0 .../private/pcre_src/pcre_valid_utf8.c | 0 .../{src => }/private/pcre_src/pcre_version.c | 0 .../{src => }/private/pcre_src/pcre_xclass.c | 0 .../nre/{src => }/private/pcre_src/ucp.h | 0 lib/impure/nre/{src => }/private/util.nim | 0 lib/impure/nre/runtests.sh | 3 - lib/impure/nre/test/testall.nim | 9 - lib/impure/nre/web/logo.png | Bin 41667 -> 0 bytes lib/impure/nre/web/logo.svg | 1 - .../test => tests/stdlib/nre}/captures.nim | 0 .../nre/test => tests/stdlib/nre}/escape.nim | 0 .../nre/test => tests/stdlib/nre}/find.nim | 0 .../nre/test => tests/stdlib/nre}/init.nim | 0 .../nre/test => tests/stdlib/nre}/match.nim | 0 .../nre/test => tests/stdlib/nre}/misc.nim | 0 .../stdlib/nre}/optional_nonstrict.nim | 0 .../nre/test => tests/stdlib/nre}/replace.nim | 0 .../nre/test => tests/stdlib/nre}/split.nim | 0 tests/stdlib/tnre.nim | 9 + 47 files changed, 12 insertions(+), 343 deletions(-) rename lib/impure/{nre/src => }/nre.nim (99%) delete mode 100644 lib/impure/nre/LICENCE delete mode 100644 lib/impure/nre/README.rst delete mode 100644 lib/impure/nre/circle.yml delete mode 100644 lib/impure/nre/nre.nimble rename lib/impure/nre/{src => }/private/pcre.h (100%) rename lib/impure/nre/{src => }/private/pcre.nim (99%) rename lib/impure/nre/{src => }/private/pcre_src/config.h (100%) rename lib/impure/nre/{src => }/private/pcre_src/pcre.h (100%) rename lib/impure/nre/{src => }/private/pcre_src/pcre_byte_order.c (100%) rename lib/impure/nre/{src => }/private/pcre_src/pcre_chartables.c (100%) rename lib/impure/nre/{src => }/private/pcre_src/pcre_compile.c (100%) rename lib/impure/nre/{src => }/private/pcre_src/pcre_config.c (100%) rename lib/impure/nre/{src => }/private/pcre_src/pcre_dfa_exec.c (100%) rename lib/impure/nre/{src => }/private/pcre_src/pcre_exec.c (100%) rename lib/impure/nre/{src => }/private/pcre_src/pcre_fullinfo.c (100%) rename lib/impure/nre/{src => }/private/pcre_src/pcre_get.c (100%) rename lib/impure/nre/{src => }/private/pcre_src/pcre_globals.c (100%) rename lib/impure/nre/{src => }/private/pcre_src/pcre_internal.h (100%) rename lib/impure/nre/{src => }/private/pcre_src/pcre_jit_compile.c (100%) rename lib/impure/nre/{src => }/private/pcre_src/pcre_maketables.c (100%) rename lib/impure/nre/{src => }/private/pcre_src/pcre_newline.c (100%) rename lib/impure/nre/{src => }/private/pcre_src/pcre_ord2utf8.c (100%) rename lib/impure/nre/{src => }/private/pcre_src/pcre_refcount.c (100%) rename lib/impure/nre/{src => }/private/pcre_src/pcre_string_utils.c (100%) rename lib/impure/nre/{src => }/private/pcre_src/pcre_study.c (100%) rename lib/impure/nre/{src => }/private/pcre_src/pcre_tables.c (100%) rename lib/impure/nre/{src => }/private/pcre_src/pcre_ucd.c (100%) rename lib/impure/nre/{src => }/private/pcre_src/pcre_valid_utf8.c (100%) rename lib/impure/nre/{src => }/private/pcre_src/pcre_version.c (100%) rename lib/impure/nre/{src => }/private/pcre_src/pcre_xclass.c (100%) rename lib/impure/nre/{src => }/private/pcre_src/ucp.h (100%) rename lib/impure/nre/{src => }/private/util.nim (100%) delete mode 100755 lib/impure/nre/runtests.sh delete mode 100644 lib/impure/nre/test/testall.nim delete mode 100644 lib/impure/nre/web/logo.png delete mode 100644 lib/impure/nre/web/logo.svg rename {lib/impure/nre/test => tests/stdlib/nre}/captures.nim (100%) rename {lib/impure/nre/test => tests/stdlib/nre}/escape.nim (100%) rename {lib/impure/nre/test => tests/stdlib/nre}/find.nim (100%) rename {lib/impure/nre/test => tests/stdlib/nre}/init.nim (100%) rename {lib/impure/nre/test => tests/stdlib/nre}/match.nim (100%) rename {lib/impure/nre/test => tests/stdlib/nre}/misc.nim (100%) rename {lib/impure/nre/test => tests/stdlib/nre}/optional_nonstrict.nim (100%) rename {lib/impure/nre/test => tests/stdlib/nre}/replace.nim (100%) rename {lib/impure/nre/test => tests/stdlib/nre}/split.nim (100%) create mode 100644 tests/stdlib/tnre.nim diff --git a/lib/impure/nre/src/nre.nim b/lib/impure/nre.nim similarity index 99% rename from lib/impure/nre/src/nre.nim rename to lib/impure/nre.nim index 2706398ee..09b855213 100644 --- a/lib/impure/nre/src/nre.nim +++ b/lib/impure/nre.nim @@ -1,5 +1,5 @@ -import private.pcre as pcre -import private.util +import nre.private.pcre as pcre +import nre.private.util import tables import unsigned from future import lc, `[]` diff --git a/lib/impure/nre/LICENCE b/lib/impure/nre/LICENCE deleted file mode 100644 index 561f818ac..000000000 --- a/lib/impure/nre/LICENCE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2015 Flaviu Tamas - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/lib/impure/nre/README.rst b/lib/impure/nre/README.rst deleted file mode 100644 index c767038db..000000000 --- a/lib/impure/nre/README.rst +++ /dev/null @@ -1,258 +0,0 @@ -What is NRE? -============ - -A regular expression library for Nim using PCRE to do the hard work. - -Why? ----- - -The `re.nim `__ module that -`Nim `__ provides in its standard library is -inadequate: - -- It provides only a limited number of captures, while the underling - library (PCRE) allows an unlimited number. - -- Instead of having one proc that returns both the bounds and - substring, it has one for the bounds and another for the substring. - -- If the splitting regex is empty (``""``), then it returns the input - string instead of following `Perl `__, - `Javascript `__, and - `Java `__'s precedent of returning a list - of each character (``"123".split(re"") == @["1", "2", "3"]``). - - -Other Notes ------------ - -By default, NRE compiles it’s own PCRE. If this is undesirable, pass -``-d:pcreDynlib`` to use whatever dynamic library is available on the -system. This may have unexpected consequences if the dynamic library -doesn’t have certain features enabled. -Types ------ - -``type Regex* = ref object`` -~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Represents the pattern that things are matched against, constructed with -``re(string)``. Examples: ``re"foo"``, ``re(r"(*ANYCRLF)(?x)foo # -comment".`` - -``pattern: string`` - the string that was used to create the pattern. - -``captureCount: int`` - the number of captures that the pattern has. - -``captureNameId: Table[string, int]`` - a table from the capture names to their numeric id. - - -Options -....... - -The following options may appear anywhere in the pattern, and they affect -the rest of it. - -- ``(?i)`` - case insensitive -- ``(?m)`` - multi-line: ``^`` and ``$`` match the beginning and end of - lines, not of the subject string -- ``(?s)`` - ``.`` also matches newline (*dotall*) -- ``(?U)`` - expressions are not greedy by default. ``?`` can be added - to a qualifier to make it greedy -- ``(?x)`` - whitespace and comments (``#``) are ignored (*extended*) -- ``(?X)`` - character escapes without special meaning (``\w`` vs. - ``\a``) are errors (*extra*) - -One or a combination of these options may appear only at the beginning -of the pattern: - -- ``(*UTF8)`` - treat both the pattern and subject as UTF-8 -- ``(*UCP)`` - Unicode character properties; ``\w`` matches ``я`` -- ``(*U)`` - a combination of the two options above -- ``(*FIRSTLINE*)`` - fails if there is not a match on the first line -- ``(*NO_AUTO_CAPTURE)`` - turn off auto-capture for groups; - ``(?...)`` can be used to capture -- ``(*CR)`` - newlines are separated by ``\r`` -- ``(*LF)`` - newlines are separated by ``\n`` (UNIX default) -- ``(*CRLF)`` - newlines are separated by ``\r\n`` (Windows default) -- ``(*ANYCRLF)`` - newlines are separated by any of the above -- ``(*ANY)`` - newlines are separated by any of the above and Unicode - newlines: - - single characters VT (vertical tab, U+000B), FF (form feed, U+000C), - NEL (next line, U+0085), LS (line separator, U+2028), and PS - (paragraph separator, U+2029). For the 8-bit library, the last two - are recognized only in UTF-8 mode. - — man pcre - -- ``(*JAVASCRIPT_COMPAT)`` - JavaScript compatibility -- ``(*NO_STUDY)`` - turn off studying; study is enabled by default - -For more details on the leading option groups, see the `Option -Setting `__ -and the `Newline -Convention `__ -sections of the `PCRE syntax -manual `__. - - -``type RegexMatch* = object`` -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Usually seen as Option[RegexMatch], it represents the result of an -execution. On failure, it is ``None[RegexMatch]``, but if you want -automated derefrence, import ``optional_t.nonstrict``. The available -fields are as follows: - -``pattern: Regex`` - the pattern that is being matched - -``str: string`` - the string that was matched against - -``captures[]: string`` - the string value of whatever was captured at that id. If the value - is invalid, then behavior is undefined. If the id is ``-1``, then - the whole match is returned. If the given capture was not matched, - ``nil`` is returned. - - - ``"abc".match(re"(\w)").captures[0] == "a"`` - - ``"abc".match(re"(?\w)").captures["letter"] == "a"`` - - ``"abc".match(re"(\w)\w").captures[-1] == "ab"`` - -``captureBounds[]: Option[Slice[int]]`` - gets the bounds of the given capture according to the same rules as - the above. If the capture is not filled, then ``None`` is returned. - The bounds are both inclusive. - - - ``"abc".match(re"(\w)").captureBounds[0] == 0 .. 0`` - - ``"abc".match(re"").captureBounds[-1] == 0 .. -1`` - - ``"abc".match(re"abc").captureBounds[-1] == 0 .. 2`` - -``match: string`` - the full text of the match. - -``matchBounds: Slice[int]`` - the bounds of the match, as in ``captureBounds[]`` - -``(captureBounds|captures).toTable`` - returns a table with each named capture as a key. - -``(captureBounds|captures).toSeq`` - returns all the captures by their number. - -``$: string`` - same as ``match`` - - -``type RegexInternalError* = ref object of RegexException`` -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Internal error in the module, this probably means that there is a bug - - -``type InvalidUnicodeError* = ref object of RegexException`` -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Thrown when matching fails due to invalid unicode in strings - - -``type SyntaxError* = ref object of RegexException`` -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Thrown when there is a syntax error in the -regular expression string passed in - - -``type StudyError* = ref object of RegexException`` -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Thrown when studying the regular expression failes -for whatever reason. The message contains the error -code. - - -Operations ----------- - -``proc match*(str: string, pattern: Regex, start = 0, endpos = int.high): Option[RegexMatch]`` -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Like ```find(...)`` <#proc-find>`__, but anchored to the start of the -string. This means that ``"foo".match(re"f") == true``, but -``"foo".match(re"o") == false``. - - -``iterator findIter*(str: string, pattern: Regex, start = 0, endpos = int.high): RegexMatch`` -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Works the same as ```find(...)`` <#proc-find>`__, but finds every -non-overlapping match. ``"2222".find(re"22")`` is ``"22", "22"``, not -``"22", "22", "22"``. - -Arguments are the same as ```find(...)`` <#proc-find>`__ - -Variants: - -- ``proc findAll(...)`` returns a ``seq[string]`` - - -``proc find*(str: string, pattern: Regex, start = 0, endpos = int.high): Option[RegexMatch]`` -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Finds the given pattern in the string between the end and start -positions. - -``start`` - The start point at which to start matching. ``|abc`` is ``0``; - ``a|bc`` is ``1`` - -``endpos`` - The maximum index for a match; ``int.high`` means the end of the - string, otherwise it’s an inclusive upper bound. - - -``proc split*(str: string, pattern: Regex, maxSplit = -1, start = 0): seq[string]`` -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Splits the string with the given regex. This works according to the -rules that Perl and Javascript use: - -- If the match is zero-width, then the string is still split: - ``"123".split(r"") == @["1", "2", "3"]``. - -- If the pattern has a capture in it, it is added after the string - split: ``"12".split(re"(\d)") == @["", "1", "", "2", ""]``. - -- If ``maxsplit != -1``, then the string will only be split - ``maxsplit - 1`` times. This means that there will be ``maxsplit`` - strings in the output seq. - ``"1.2.3".split(re"\.", maxsplit = 2) == @["1", "2.3"]`` - -``start`` behaves the same as in ```find(...)`` <#proc-find>`__. - - -``proc replace*(str: string, pattern: Regex, subproc: proc (match: RegexMatch): string): string`` -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Replaces each match of Regex in the string with ``sub``, which should -never be or return ``nil``. - -If ``sub`` is a ``proc (RegexMatch): string``, then it is executed with -each match and the return value is the replacement value. - -If ``sub`` is a ``proc (string): string``, then it is executed with the -full text of the match and and the return value is the replacement -value. - -If ``sub`` is a string, the syntax is as follows: - -- ``$$`` - literal ``$`` -- ``$123`` - capture number ``123`` -- ``$foo`` - named capture ``foo`` -- ``${foo}`` - same as above -- ``$1$#`` - first and second captures -- ``$#`` - first capture -- ``$0`` - full match - -If a given capture is missing, a ``ValueError`` exception is thrown. - - -``proc escapeRe*(str: string): string`` -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Escapes the string so it doesn’t match any special characters. -Incompatible with the Extra flag (``X``). - - diff --git a/lib/impure/nre/circle.yml b/lib/impure/nre/circle.yml deleted file mode 100644 index b6105af65..000000000 --- a/lib/impure/nre/circle.yml +++ /dev/null @@ -1,39 +0,0 @@ -dependencies: - pre: - - | - if [ ! -x ~/nim/bin/nim ]; then - sudo apt-get install gcc - git clone -b devel --depth 1 git://github.com/araq/nim ~/nim/ - git clone -b devel --depth 1 git://github.com/nim-lang/csources ~/nim/csources/ - cd ~/nim/csources; sh build.sh; cd .. - rm -rf csources - bin/nim c koch - ./koch boot -d:release - ln -fs ~/nim/bin/nim ~/bin/nim - else - cd ~/nim - git fetch origin - if ! git merge FETCH_HEAD | grep "Already up-to-date"; then - bin/nim c koch - ./koch boot -d:release - fi - fi - - | - if [ ! -x ~/.nimble/bin/nimble ]; then - git clone --depth 1 git://github.com/nim-lang/nimble ~/nimble/ - cd ~/nimble/ - nim c src/nimble.nim - ./src/nimble install - ln -fs ~/.nimble/bin/nimble ~/bin/nimble - fi - - nimble update - - nimble build - - cache_directories: - - "~/bin/" - - "~/nim/" - - "~/.nimble/" - -test: - override: - - ./runtests.sh diff --git a/lib/impure/nre/nre.nimble b/lib/impure/nre/nre.nimble deleted file mode 100644 index b007ff617..000000000 --- a/lib/impure/nre/nre.nimble +++ /dev/null @@ -1,11 +0,0 @@ -[Package] -name = "nre" -author = "Flaviu Tamas" -version = "0.6.1" -description = "Yet another PCRE library" -license = "MIT" -srcDir = "src" - -[Deps] -Requires: "nim >= 0.10.0" -Requires: "optional_t >= 1.2.0" diff --git a/lib/impure/nre/src/private/pcre.h b/lib/impure/nre/private/pcre.h similarity index 100% rename from lib/impure/nre/src/private/pcre.h rename to lib/impure/nre/private/pcre.h diff --git a/lib/impure/nre/src/private/pcre.nim b/lib/impure/nre/private/pcre.nim similarity index 99% rename from lib/impure/nre/src/private/pcre.nim rename to lib/impure/nre/private/pcre.nim index 3d619d268..744721d6f 100644 --- a/lib/impure/nre/src/private/pcre.nim +++ b/lib/impure/nre/private/pcre.nim @@ -1,4 +1,4 @@ -when defined(pcreDynlib): +when not defined(pcreStaticlib): const pcreHeader = "" when not defined(pcreDll): when hostOS == "windows": diff --git a/lib/impure/nre/src/private/pcre_src/config.h b/lib/impure/nre/private/pcre_src/config.h similarity index 100% rename from lib/impure/nre/src/private/pcre_src/config.h rename to lib/impure/nre/private/pcre_src/config.h diff --git a/lib/impure/nre/src/private/pcre_src/pcre.h b/lib/impure/nre/private/pcre_src/pcre.h similarity index 100% rename from lib/impure/nre/src/private/pcre_src/pcre.h rename to lib/impure/nre/private/pcre_src/pcre.h diff --git a/lib/impure/nre/src/private/pcre_src/pcre_byte_order.c b/lib/impure/nre/private/pcre_src/pcre_byte_order.c similarity index 100% rename from lib/impure/nre/src/private/pcre_src/pcre_byte_order.c rename to lib/impure/nre/private/pcre_src/pcre_byte_order.c diff --git a/lib/impure/nre/src/private/pcre_src/pcre_chartables.c b/lib/impure/nre/private/pcre_src/pcre_chartables.c similarity index 100% rename from lib/impure/nre/src/private/pcre_src/pcre_chartables.c rename to lib/impure/nre/private/pcre_src/pcre_chartables.c diff --git a/lib/impure/nre/src/private/pcre_src/pcre_compile.c b/lib/impure/nre/private/pcre_src/pcre_compile.c similarity index 100% rename from lib/impure/nre/src/private/pcre_src/pcre_compile.c rename to lib/impure/nre/private/pcre_src/pcre_compile.c diff --git a/lib/impure/nre/src/private/pcre_src/pcre_config.c b/lib/impure/nre/private/pcre_src/pcre_config.c similarity index 100% rename from lib/impure/nre/src/private/pcre_src/pcre_config.c rename to lib/impure/nre/private/pcre_src/pcre_config.c diff --git a/lib/impure/nre/src/private/pcre_src/pcre_dfa_exec.c b/lib/impure/nre/private/pcre_src/pcre_dfa_exec.c similarity index 100% rename from lib/impure/nre/src/private/pcre_src/pcre_dfa_exec.c rename to lib/impure/nre/private/pcre_src/pcre_dfa_exec.c diff --git a/lib/impure/nre/src/private/pcre_src/pcre_exec.c b/lib/impure/nre/private/pcre_src/pcre_exec.c similarity index 100% rename from lib/impure/nre/src/private/pcre_src/pcre_exec.c rename to lib/impure/nre/private/pcre_src/pcre_exec.c diff --git a/lib/impure/nre/src/private/pcre_src/pcre_fullinfo.c b/lib/impure/nre/private/pcre_src/pcre_fullinfo.c similarity index 100% rename from lib/impure/nre/src/private/pcre_src/pcre_fullinfo.c rename to lib/impure/nre/private/pcre_src/pcre_fullinfo.c diff --git a/lib/impure/nre/src/private/pcre_src/pcre_get.c b/lib/impure/nre/private/pcre_src/pcre_get.c similarity index 100% rename from lib/impure/nre/src/private/pcre_src/pcre_get.c rename to lib/impure/nre/private/pcre_src/pcre_get.c diff --git a/lib/impure/nre/src/private/pcre_src/pcre_globals.c b/lib/impure/nre/private/pcre_src/pcre_globals.c similarity index 100% rename from lib/impure/nre/src/private/pcre_src/pcre_globals.c rename to lib/impure/nre/private/pcre_src/pcre_globals.c diff --git a/lib/impure/nre/src/private/pcre_src/pcre_internal.h b/lib/impure/nre/private/pcre_src/pcre_internal.h similarity index 100% rename from lib/impure/nre/src/private/pcre_src/pcre_internal.h rename to lib/impure/nre/private/pcre_src/pcre_internal.h diff --git a/lib/impure/nre/src/private/pcre_src/pcre_jit_compile.c b/lib/impure/nre/private/pcre_src/pcre_jit_compile.c similarity index 100% rename from lib/impure/nre/src/private/pcre_src/pcre_jit_compile.c rename to lib/impure/nre/private/pcre_src/pcre_jit_compile.c diff --git a/lib/impure/nre/src/private/pcre_src/pcre_maketables.c b/lib/impure/nre/private/pcre_src/pcre_maketables.c similarity index 100% rename from lib/impure/nre/src/private/pcre_src/pcre_maketables.c rename to lib/impure/nre/private/pcre_src/pcre_maketables.c diff --git a/lib/impure/nre/src/private/pcre_src/pcre_newline.c b/lib/impure/nre/private/pcre_src/pcre_newline.c similarity index 100% rename from lib/impure/nre/src/private/pcre_src/pcre_newline.c rename to lib/impure/nre/private/pcre_src/pcre_newline.c diff --git a/lib/impure/nre/src/private/pcre_src/pcre_ord2utf8.c b/lib/impure/nre/private/pcre_src/pcre_ord2utf8.c similarity index 100% rename from lib/impure/nre/src/private/pcre_src/pcre_ord2utf8.c rename to lib/impure/nre/private/pcre_src/pcre_ord2utf8.c diff --git a/lib/impure/nre/src/private/pcre_src/pcre_refcount.c b/lib/impure/nre/private/pcre_src/pcre_refcount.c similarity index 100% rename from lib/impure/nre/src/private/pcre_src/pcre_refcount.c rename to lib/impure/nre/private/pcre_src/pcre_refcount.c diff --git a/lib/impure/nre/src/private/pcre_src/pcre_string_utils.c b/lib/impure/nre/private/pcre_src/pcre_string_utils.c similarity index 100% rename from lib/impure/nre/src/private/pcre_src/pcre_string_utils.c rename to lib/impure/nre/private/pcre_src/pcre_string_utils.c diff --git a/lib/impure/nre/src/private/pcre_src/pcre_study.c b/lib/impure/nre/private/pcre_src/pcre_study.c similarity index 100% rename from lib/impure/nre/src/private/pcre_src/pcre_study.c rename to lib/impure/nre/private/pcre_src/pcre_study.c diff --git a/lib/impure/nre/src/private/pcre_src/pcre_tables.c b/lib/impure/nre/private/pcre_src/pcre_tables.c similarity index 100% rename from lib/impure/nre/src/private/pcre_src/pcre_tables.c rename to lib/impure/nre/private/pcre_src/pcre_tables.c diff --git a/lib/impure/nre/src/private/pcre_src/pcre_ucd.c b/lib/impure/nre/private/pcre_src/pcre_ucd.c similarity index 100% rename from lib/impure/nre/src/private/pcre_src/pcre_ucd.c rename to lib/impure/nre/private/pcre_src/pcre_ucd.c diff --git a/lib/impure/nre/src/private/pcre_src/pcre_valid_utf8.c b/lib/impure/nre/private/pcre_src/pcre_valid_utf8.c similarity index 100% rename from lib/impure/nre/src/private/pcre_src/pcre_valid_utf8.c rename to lib/impure/nre/private/pcre_src/pcre_valid_utf8.c diff --git a/lib/impure/nre/src/private/pcre_src/pcre_version.c b/lib/impure/nre/private/pcre_src/pcre_version.c similarity index 100% rename from lib/impure/nre/src/private/pcre_src/pcre_version.c rename to lib/impure/nre/private/pcre_src/pcre_version.c diff --git a/lib/impure/nre/src/private/pcre_src/pcre_xclass.c b/lib/impure/nre/private/pcre_src/pcre_xclass.c similarity index 100% rename from lib/impure/nre/src/private/pcre_src/pcre_xclass.c rename to lib/impure/nre/private/pcre_src/pcre_xclass.c diff --git a/lib/impure/nre/src/private/pcre_src/ucp.h b/lib/impure/nre/private/pcre_src/ucp.h similarity index 100% rename from lib/impure/nre/src/private/pcre_src/ucp.h rename to lib/impure/nre/private/pcre_src/ucp.h diff --git a/lib/impure/nre/src/private/util.nim b/lib/impure/nre/private/util.nim similarity index 100% rename from lib/impure/nre/src/private/util.nim rename to lib/impure/nre/private/util.nim diff --git a/lib/impure/nre/runtests.sh b/lib/impure/nre/runtests.sh deleted file mode 100755 index 51dbcaf35..000000000 --- a/lib/impure/nre/runtests.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/sh -nim c --path:src -r --verbosity:0 --hints:off --linedir:on --debuginfo \ - --stacktrace:on --linetrace:on "$@" ./test/testall.nim diff --git a/lib/impure/nre/test/testall.nim b/lib/impure/nre/test/testall.nim deleted file mode 100644 index f7fe8892a..000000000 --- a/lib/impure/nre/test/testall.nim +++ /dev/null @@ -1,9 +0,0 @@ -import nre -import init -import captures -import find -import split -import match -import replace -import escape -import misc diff --git a/lib/impure/nre/web/logo.png b/lib/impure/nre/web/logo.png deleted file mode 100644 index ca41ec7b7261e2f8e4ae3675bf17591717b589b6..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 41667 zcmeEui96J7^!K!&hq7c#wrts#$kx~@VvxO%H8IwZiODh~*-P2?eJe}Wh+&XqC(3RN z*|JX7!C2mVdU}4>?>~62>%HE&u9iXH`@YXP_vd`h=bR~APe=U%`tj{QEmuYu4%i^xfR3(sEXQ(_fi&|zxL`fN@3 zz_$_DH;;k-XU_b*CPcetVt2y6i$Jl{r~xqhnRIAhH{8HeiPa|Fb3)TjFR+yJ&o2J` z?f?6gWQYHo(R}qM^nd&@?O?aNeV_Vpdp{P1jC;|sU5^wmA*Y3`5t zjba<0*OxF*&6_SawT$;8Of4{^he$jbMEf{}8bAKjgH#s`>vNj?3SuYg?Z4si{P`vC z?fJT(T7`gke3XHncgvxAmvN8JD0upxm%rKnM+gYy|0+0fW6u2R3u?Z?v3W1?uc0Bd)>`SvqTo;hrVx*)boFjLSmT~H$X(d#~UNSF>p=LRr>7@f-`}XI*L*eZy6j$pn zkZk(AGvaT`l32IAGVY! zK%)FcURb>Uu)kqmG>rVdajEBPVFLqBdOm;e1HylBOVtKm{bV91Vz_kCSlp*h-hh>W zrGVsf&r4>5e^syee*GXyI{<}*zw^HWHAwXuGa0wDVM&aH$GwJ|%cMN1Ga0taWtq>R zaHFx6WM;uG@Y~GT{`ma0NfRwXTIGU2)dCwk z@Ji>SzxkOh7A%+29wL)oEnN|C9QYJBndZUgox!zMIbT+ABe5Z6*}SqSpwv0y$EtjV z%lL3r@q(MB!NBl5ng;TsuhS9bhuli|f?-Kd4*Yt&>VBjmW2qdc^@HEzeaftbXM3mV zxLx<4nAz3$3mPZr^58+~?1+p5cROPcF}_aK7_{j44^Nx@>h%zJ&&_8kz?kmO_`Fa5 zOCGe-q&mV|nW1%W@fo)~Jci?099Fu{SC?{3`D|1>97RzTF)Mq+)+&uZ z2{S`B>!pI`#b2#Dp!mGAJl*OGOQBM7h^Jv!^eV-e*Se{7Nxx9iL;I{J9~2nai>Qn} z`=aiSJ#m_!d@L-qxK1NDr;rbrP#oJ|0@Tdv;Zbit-A4B2g6oZ1p6|*NNL@WP4MJ~Y z9ig+XnB4N0LY338q47{U20XC)VEy#-TjSBI?|gms=IN0IH_Rraj!J{Z_84$?+l4_8 z^LwC%)|N1J{pXuJ^n18@q#nJVV2GkU(A$0^c_&P&EaW7xHjywHRxsq*`tGhI<*6${1*_p2X63!PeYLVf`IM^XP> zc)E5~mv9d|Oz25onMLd9)@kSCGi;)tE*05_T6u46@l5n*TFIc+<~@b)XBsJ0O(2;e zuRxQV1 zL|1@$0_6W)A*;?$Y1q-NQB&OuZYac8yGIz`hQ{1a$g_+mY!73Du&DZjE?%XE2Ju5D58!~-%t_P_rc)62r#ebam!xKb9);$-C$ zadz>(c*99ZL3}Za07)_@1=r+{tuGT$$um``T5TE9{W>X|O>AoVl(RF&nj+@+j>|k9 z>;wYQbNKJ^;fKZq9(zTl>Lp43UAA*C(#-cZvU?Lf;p7E=mGhhET&BK#*VB6AK9aZR zPsWaZr^@o}X3Wez6aD?AGg#&eGIJ-mQC76E9KLZhay_jvVeL7o6!@2}gY>5Ib$->E z9oh8Q(59aSWA=NZhIco8SC$ws{(I@Y@nlc>N66I|vEO?eb<+<@I zz@fg%@b6|EClcL`fA<;Lm*SZ~z=wbNQ?WoGd`=+8vVirD9vzKEzsH!l&w)ekw|)q9 z{X~ifj2VQXEZdy>fQG`=ck$@V%2c$cd<{g58$6ul#BX{R=j-C|-32EK&Q2ff_HW7( zxQX0R4j5!Va{ka)Z~g;G6=kU-=4X7e)$~1M-R&4MaSg@6?nU z6@Do{{hViK3sabgmHPcN{(KRmGC#8q*q0fhz!!e_uzLdkjxyfPPZogoD`p)NuvZXd zx9-z4P5Lqan#{yo+YG6x<58U&EsUG=NKv^MjT>~&2VVG3jB4P zXws#|u^C6wlV{(YcTJl`gZkWB;V;co`DZkJ`NKYZ5yh!dryY!EdZo;7U%R7-SX-Vc zEd`67?Y5TTI2sJhv}h8?`sU!7v`gZ;jSfE%HdZ)U$FENysX%OR*!=5)=iDQy>_Wua zDD(%;PCnC%^)Kx##5Qx+)ypR0M!(OY$y6k^;h|l}>&>N{4!VT?4eX209rfmOUo+av ze7*MK!EFGCi=z0OXc#I$G#+mTLZ>D&*^`&iWb^=&7;&o&_%pr+*dg%4dqc@A@AimC zwb*a*EG}E%ab2HWRztBgO(*$#eN2A>r2Rj77h$9$PxK(N8zXH$#d=Ay0E9g*on0po z>_WT!Y9YTLS=HArbJ9%iW>2ktdx{hN%|luZ+>A4%qzP^h1j0u37vlsBtXB5s?VyI~ zktk%=?*jmjO_ToZzLH}0U|S5s>qf}l#EF0n^wAjIdO_yg#k!|EBT)SQbn*MX2YMJ+vB>O7(le${uK9Ru}~O5VawPo&H|X8yo3_H_{7%)8;njzkH?v)GYydxP z6vsky6~E&WI`WLeCh-px@=DS{6^~)l zpnp5@82;5a;8Ml6JkB`)M=kAtp+jx15a41ZbO;rLkJ@0Wa4+IBKo?67SNlHPe`Nu9 z+FB`fd?D^vlQ2zNWobo0_I>FKuXpUdc%jRrWbjzGrglx2@Nowos_8`bBGARJtG0d} zJ!dGIShk5hZEaI>`Psu6saA2TIdtyZE|DAN>|*#*D&t*HK=>4>I{6mgvJ0=&yKVuG z*7g=i_;9Xmkda9%w8tD=I*b>u`HhsG{M_4hs%pmYtZaU%Nx8SIj%+D<3C!*fi;T^n$(r|k1Tn?? z%pj9`#q7H#3+Pkv7u;Dv_D0+ttIKP6y!d&OB^~(jAMd-ry3QMcf1X?~UxDoVU^KD{ z>KtdCx)^!g*mVAzKl*=dGKiJ2{+=bx#G zq@@_kcpjxXCnz9&=Kmp59_>+e*>8&oWIhS#vg2s5w_byh$n7|&CK_%bU)7osGyE4j z8LOHGF1^>;b3G-YbVKS4BW}fK8pV?Mdf%1B&5&E#mnpvXgL0kCZZW@c-}1Tl5)+Kt z;Xl5LmzW+d2TSi$?St@ZfZGy#0K-Jcf~=zur*)kv=TVMar|XghYA0uN*zLNy(=5gp zZ2IeeSy*ja8OsbOy?KKcKzQoMCz9S@*WK-rZEc2X1^}36VO{47^;!K}DyScyZ z$vh(B>km^iOT=>sHU)q49^zlSQFf4L5yRo_;h;4!dplJZ8@+5|P;!PF)PoDkH}Kwz zRys|)?SEq9e>QuHVBlxpy_{XD)+oEb?a*37kj)4nyx3$>#F$arfxypbO4(TF#0{Ms z!U*R}P-Y5=MLXE1A~pOIiP(WA_*T4Uq1!h0^z2p*#ZZLn&Sxy(Pm_vqT8AF@PR84Gsoj(UBvKtVv7RI@&3yQd7+t0G?di<-Kl`H& z{tIEJMb;{_PnP|+m($Egk=+&V&b5(?ms((!f%PJOe%=R_fJ~-UqXUr!&H12C2}2a& zXWqmK;3N}6Suq<@KvjJR}s}ke>+uNq=u`eJygc3zS?HE&ro=g<2M%6X}^8c2(2=t zNQK09iUQCWPh`(nM$ejv2xacCGTS%caglZ!GtwVtB7ShzG#pLoR-5mx)w|n;;xlsN zJ(43>eK~xq@YIm@bt0C=GQ(?35^PEc9vuzJ%F=`OVM4%B`i?yl_U-4E9Hzd;!kNj% z6UPN&lb7WVjPON7@+W#pV}97447NB&5#3+kCXu=}92f&>VST6XIkz-cG_Ix`M6n?8P zPjR50l)zP4t&Tr$J7bOm3#c;1svL%q{m%pe0Lor3H9ty}`f%jqT;dps&)|_xdM%5} z-O8vXt^>O~Q~aCG&b{L#DENDECw|z)KDlng6mB*0?D)+TsTM%hz6w2Xzqct~U`15k z>Mm%SM$bFQ)qN9fEEeCzo|^szKuu_!)r24eti#RQonh7ZE2Al6W1Y27Z6y*u6qq}7 z@jdH)_tMDmT(7hip3+QU4ZWz*kfz|?m3y0YagVeSxl4ah@T{IaJnQFvG`rg-*of2T zd2GPw<}TjSq-yUTPIOk#X=c*Cz`~Q5e2-u07ud+Erl;rw#Y2x`;3xHUv;|Fr^wQux z3^eNg-A@g~*dRktQ{6+P>4H~h!?apcm7zrEW0WX>mR-xwKlm*Zzqepo@xJ(_?;_JK7DKGH};kzFWq^#;cd5xu$ zzH1M+9wre7KO{s>fxqzH8RtmXa)$@i{_TqejVtOqGevoLCabR76|0K{7AV9u7rO0^ zZy}MPh|VxzD+na~zq`8#3U9G4P_iP~!n^cLar|atO%+$o^%;my--IG%(}5*k9l9{L-7y_P1@`*7W;CuhGu3}bSLjy7D}2J0eVnKp`XsH0 zj6htMOIy5ClUb{bH3pmtq^keUIyXF3DE`D?8t+fjSvew&S>liEHbeW>?paG7ZTt`p z0E}jA7Co<_pj7S6*Nr;UV&qaRc>PWh;i&Tm@=ydGody;<_#GFSVPZaY@CqMQVQVhq z^{D@m@SlF#?=$~4yH0J4ek&Lw4mR?G%YD(U7`julRm8lujh!)66G+&%?VeZO4?UxN z^6O6tzUWTMCwCQf({^SAnaO-iJ*+DQYlaxQZVzPZUT=zzXP9a}ar7n@HBAL<#hqEg zc#}|H%LeBN>ita92Lr=PBxXH-$6)5m^4fQl%om-MDfVQ2X2KZ6+UDB7?Ku^dN!jvs zKima%8<^U}cYKL5q7ff;C5fYy6Z2uC!Hks1)n8yPe%<1M_SH@08z-7xUjdJ`yjEI3 z8)H}I)-YXQS|J#OF?%5fJp4YPJK&)0NSQdQCpPd4y||N>h8-mS$k!4ccLj;&N|Geh z*Qx$wW9rSG%e%()p3EVvyNogd!uRTLm+9Q|-tfk|#P5y#d+X15hO##^-ssfrox-u- z^teBC*r+88FWtp%+=&sh@B}5C76_gWVPF%nQVaj~v3pyQHt5tV4iP_im4^K~-{dms z9JtEIH7;fB)6lpkt&n`KZTVlQL7G+rX0&k^+`jN4AGgZa-V5yl`Rm03kD-`G3)FN>t-76J%TtQ-Q&>O=F z%AUElzoaw+2w65}vBX3oI16d(O0_;SuHY<2j6&V!SoeiB40K8Z33p#eiGC~v&hj?n z^0-F=K7>b~T?oH_BPV|V*vTSt)2Ksw+3^dkOg zRO^WoW;H{6mDpKw4Xp1E%AH=KCw_+GO;{bEH}c?k36eVka0 zl^-$w)I|53#}0lWW<2hsLFtFSZx~KEHcsx>DBltn?9FDK<#bBO^-g{}of)l+-7!YK}5rR?5rnLR}P9V?O`BtJF)eBCh{-~u))|K@@D-*=9 zMtxzq$FJZ49}4#c!GMm?6G7bm-ercFs#_)i?f4yHQ=Fe5j_*9L`0ZaF3)vfxK+RC& zF0|$Nj~}LEST$i;7{OalB&w2QbP}pvw%0mibYiY&Ka_a(^}ksFdR6#v@j!NPP}GH( zVY$T^`u$M|uat94waH-2KyBI4R`nB~FkM(z@)%W&<=bkr{fGJ3+;+>w$!R%7rmJDe zLz*eYhZ3LDf{yn;){-ecR6ZE5xSbnBRpv{iEaQYczw*q%y|n@GkZ;{$;v$(Flcx8! z>hwI%E`N@HAL*QcMcSVrnr6{=*-`zadmV9+0QFC6-_g+l66={JtS(4Mc)X0o zb`t0kR+QM>UnCof#Ctoq9{~xDIsxdaYe&vHM|$783PCvy`YM1PvLz&^^DZeIEm+^m zEleYa6~5-6&`KG*414p2L-)p_4<$QA9HkT$?8fc={*OTv^pq6}4>dxM6#_~hs|-#B zMd@zsufIu_*1BOfD4*NzG2e8b0@nJg;wSBim>s-d%g12Qu&c>`RoIpd0*ToMsH=k4 z=Kyf^SZ+}t$KE#Ab?{wA;YRfasPr1fkliMr2F%EKQpeBD%AeA$C?;UeY(-VQ)&>3}Uix+GT~;80Oxl%5@vLv1s!1GDPBG4Ij-9{9Vs} zkbmVOg&vIbMBII7SDZ_0&|zWHI2R2)7%?X~ji=5Q+jz#A8Pn+62FHmu+iv~%J#2`Q zZHOK=`JS*8Cx#($;12d-6rYk%gYtZ={p(;lM~^!6Y$j#Ed@ z(BLC3=S7mDPXls$q!sQ}o0q9s-!0#+)CYO~#1m-a_MZ;>B?1|0^cKcL5ThK^m&{EA z#zWLYWGv<0vj4M8Tb^-w%I9hjrOLw{pvZU?++c3p$lPwXT_=g11gw5hU&)Op_@JN_ ztH}ff+IMTp8JEWW{`3m7-fFt)we&1#QVtF}roQlzZAwlTTzW7cO26RKm#pC#<9bQ) zM(-*Ua1IBuuOiL#pGy}0{ss7`pjEFvPhylDgA`P2pQ_(jpedf}H|w2Do)IDC2AK(j z4y}>k$?>QAgJH>7z7U{c&e{U0-c@r|@yD)eU`1ZTT5|HhS1u4~9kvfltM+Clh{NV9 zz#kNYD1_`6q^{|oju=^z2q<+dVm#|qGGo)Nl-9^FV%jAuto;GgS`_{@aw{JCIMFis zx9h3x&VUaJ;tC7k7X00Pfv^$M`J{U-({pq+czY3s4}d5{#;`e>j&mH5cxb0GpJVBm9kq zk4h{;V`gVT^B^Q|4ZiCrRlLc5_7%TWv1FBU+;&7BYunq?)Hd+Nlreziaocfux{+ML zxf|o(KKI6q_pVy?lnf#0Az2+IZ}1OR(KGI#Go>gc`k-H8>WM_MSc&Oo7(S|XEWw3l zdy7_pkJKn$?@`GLa80rpZm19)zWxjSNb=K%jl)7v+5mPq3c9%6zLK{C*>iyKpC5cP z7}ne)CQ%j2tH`@_8mD;b`t3nu-bN>Qrfk)f$Ly!sq@|p%RW(IdYYjHRQf6z<-FyhA zlR{7RSjKI?%+rNAZKd6#EaE$g-VAcX$yUYsQJjLjC{u=BoJd_(Y(ci0+^Sqfv-Y6| z!Suza9M`t5%X;2#0F`((7vl-U5QFvvdRd zq`ahC4bN)c4gtJF;2b%lW>Rvx8=OYNM|DuMU%t&cB2Qd%+z}q&3crTC**qXoMc=#1 z+J)mfA%nfnh^3{?Eq3z<|U&X(J z9womO0W``Q5Ek#dfaa66WZn8lvMRP`l>_!hlk$g>y;_dWAWrjvGu$OQuvw}q8Sa&v zCmQ2#bx~{k=3v?Vk-eNeYz#)I#!G-9c3TWq+`Gyph3-MpLascsq};2aaVxUC^owex zZK1N>(DJ%zA26!rLn1}i6`)Hj?z_sReHU7+NVygG@oP%RLc&Lv-@s-lV?44~ zunBBtX%MuS*Xfd_(<)!(u%L8 z80c5YG_C6j%9W2&@YGpxkMFKJvvu;F@%0DQ>l~0mhWFQ#UQHSJb{T>Tl@Lp%c>UAE zY*J08ckt=mJ?@@WO&BX5O6Q^((<{!{ZQmG~GT(PXJ z|JvTReEDXj!C)kO7YV;V10{z{kF?%qU9h)suSJJuS?_#g9l)g*z&Ehkt{f=yJk>MRZ2D-Ag0y$$uT5_*U)dVkA z%rR;)%|PbvU@v@^N@}*x_Sqx2Vb7{>3`gwKN<7Ee)?dq)14QnRoU4DAryN^7&?81* zKLhz~kL~Dd&N!4!MwjfyeFRfU18UOUmhXW$@gWK;I4&Q zdsH;M5eg_g4CQluayuhAoqx$2X2n$O%n&IbvrY=~l3wI_NLD!*mg!i3N;r*Uf0WGP z>{s^(7;+iZMCO3RNbYsc7D!zWm~mr2(PsqISQ4wwEKSJ+Z(gj?JNUfZHUVNC&O9W7 zWs8~jLpEIHXZCk@R|FP?JpZRH>lU44)jl9*+k_Y)#YOEqTYRN5Rki!nEpygz(HM^C zZFX=G5wx`MVHdda+wFIGb{JoG?Wz33;aevoJ)bd;AdujV-_s%VRbtFLAhN28bk1+@ zo^4yN9G@581M$rtT2o$hTH+LF|D`5-jWxUW%JPhVD*Yp(C-nendiHzHPT*xGQ%>B+ z4kRdm1RkFkVqlR%>kT@=w19fy;n{_|Ky1g{)*J6}$==M|S|qyOlt?n|=u!G`xO|!O zA}|J(rupUQ zC7j{}vUNs8(9Lcl6k=j9P&0sRZP_jGT>z6of$Sduz_z`)8O&`1m({2@p44Y&;DTAn zRB@)5CgU%~aY&(61`T5t4oF)W>+DkI#|XY}K~R4k$&VRM8uP$$fwp06NB(EDVGDLQ zTU2I#J}fv5@Xy*TzXK-Rg-0x4-hq^8H?XJTQqCk}-eXw5+DIZF_S%H}IDN%oLfIB{ zpniY*x(`}o5S1msz0SQ_zk9+5Q;uWUN(;hy1?BnnzIrSt;o7r$14ams9Jpi$ZxUW| zgxMdsw!BOhUV=&aX5wif&0n59b@<-!s+-)a!`o5K%vwAvF$Pi0Onz{5IQN?=;ehr%8zjz2vNka{&wE#Dj;9} z_)NFn-XF9o{uGt@;WvXJQdRF`I1-+gE;6tsYw==j;H%h>M>Zh45u@_NVUjq--+=JJ ze6$Dg`>r=zP!INpd`|n`qKCL|0~enL`QnGeQ8DNv#NnelZCqWPtc~ye>N#IsU>>ri z)+{%cG&-?5cbX_KT~=aOizh!E|G7DAL4v&}W2295r(UuKflAL^j^ow!g4d|-^I`fo zu`hBxf;W+$J(xwJB9ezR>a_;dQMFet^{g7e`n7JfBB>hcGzJmynjgq>km)_rFx*tn z@9W_BrY1@}<;;Cr0})+yfv5m`3$cUAj@@Jo^tnNW;uy#1V@_U2(>9m;M(5rFm3W?74!Z^~WBPRl!|ld9<9DMz^}n-wR|G+Ondg;nTge! z2C;aKXR=y@LFa`bDjU9DbMZA-aQei8<=E4{GYt&s7K#D7$!d21%-KEiqgmv6{-jbC zOFzo>aZ}I5U8lsm8A;(U3bf2Pjb1>nC?;ap7oz-O2%isSOxUA71z|&rhNA)%JFPfB+-MFi`b;S} zH*RBCbFhA?`-73ab!M4L#ZuS#vtDY!2^ylsf@i<=I2dNt1pMkfuglro-MzhTUWZR`sbpT{N-D@YfjVl0+& z9UDf9tlbyhf@Ti}m_`Y{>Tv7(e>6fpN-!T0$Zq8DTKd{MS{16ULJB9nmd;=RV9r}W zL4at|1W}%P2xp90fBOX+lRt0OyJ`d$y(&cv%LAl?w5Y|tXn@XU+6!yv=xy3oN{F5x zkjnDF+!n}GCOV~QTb1~b&R-47Y7^QEen>V=FcsuH3oQWRb_5o*VDEO>389d$@} z%5LyXWAGMERDe>ntE{BFgA{Tdin5iD;W}bK>(#qOX$Q7}#v$8njhH`Z4}}WT>;bzU z?1_nKo@#eA+f>P_^-5<<9h?R0mnxaZgTc(xANjs#7!gEpU@#|ZTjJexa&mGWUbFr) zlIm(tcvrxyQ?Qt1(Zp>-7#(OrclW>rnqp4hrj)yE7;j}7$S4QN(s0pSy|7A#69hT(=a{0{1211KhK|Lv&BP@_`iE`NwNj<%y&P!X^z}v-O3KH-n6Qox;kjMks z>Pf&1gy)lE{lN9QNZfMLQ7&WX^h$Q$gj7bZ^tn0x!%-I5n2iySfqno znfA)BKMj2+!87~`z`m`FxQui;{$%&*NlBW=0?3(?3~6EK^TxpO zTq_>Yiy^gJTl^5nCFAo#&urlVB1^h{$SiA&4P4kyy*YD0RAoJZVe}|m{}Nora6g{m zl0oxE64w%wROCJg^H-vv$<)`QLek)R#8Wv&p$Ggy;2x9j9%XtZZ+h~e9{^>o&E-mS z5aq`i%^K9X@&pHqEON#?>oQuF-iS}Q?JbBw^Z^Zh9B9OCP6CPNR$=1{J!?2q%r>ses#%zv1-8Q1D6$kk!cI&_s2{z4 z4=#WVY>VcGPVCc~&0^}fdhwL8yM1*^I4*(nQqFPPcX90M*=B>}unFGBoG2hhcr8xq zpJchf;}3SGZxwH5;_WqWSQxa*NmESy+B{VLK6lArRA`B1o`QZ@{e^4<8S1HYbBLMf~Lx{&ypXt5R-3dZMK9QyDJG zW61Vw(BnEyJS2-~(GX)Cy%`*$vGW{H{;CuZ$V)YPS64g&8sxdvN+-3>4pt(;+s+WV@A|yDBr$U)Ox^si``%ss@!Kd_+^zcjKfOo!4P8VJ(18thm zVlY|Fdb2^PK6!EFcXEqAV>s9pEzP)(d|*{5Y6z1b1E8lx@1{_bY5 z;?ny43O-tJQvQ6O5vS=S)1XZxg4|9n&v>ww&qBa43bEdwhIq4o*+7nAaq`sSq;VR8 zU+Y2kp~cc{eSMHR9qeQodYayOd+XQ?2yvA7uhc70~=$B<_sSKJJ3bU_IY!Z*&;*4A>&s3w;R68m1zpbE_Nn|S5lh_qYLyrKujhE971 z?(cx9bwS((xrTSaXKGXK>cYcDK!%WTy<{YihKHrhLvIZ>#!Lx1rXbd5`|8x&5#faJ zpJ~1=@&p)cix+ioUsNapYX*u}99@#$&C$(ltNq9Xe&}KXILerO?FiyK-IKn@o_$C0 z2-m>PiO-W)1%F$WQN!VnV_c&dcCa34KVyy!2kZLkV$%^;;$LT80y~hWBTkAAoqG!7 zan$)qD37Nqpu`=EvQ@XPMZJ4t#7tbVfH_9}Am5#>P{uNkE?%Rx1@q>YK{aW}UUaUf zS5vM!N$oV@+U1_Fse@wO(jW~;i0u{RKzdf`W2WY>wFm|T;?FNm+V$00$t^~BIE~AX z%%l;kH;EA^p_{}U=Bj=ob@P`?*v*+E4*G+5tJl`Rxl(;~i3&ArvWt^Wi<9U$9Qnc> zm}x)Et)oYX_sHDf8t(C11ApnTvA#MQ`NfP)_UqAUh$kQl;yF$Bnquk|_}PVHx7nqH zx7bfZVzHQ~Zr0+zb;5r<-E(a&yZc7w?C$IU_@KoC-u{#udF6(Ro47H(n0OZ=C>EBi zb_SVyUq`G#xu+wR}}u-D>OL_x4k_|K_hS&kNA+6u;tnJ*uBr9?68Iw7azBk_EZiR{WJw1 z_9!lPn+Hafj>z=r^E{vy;$55sVI~}-W8lvhZd0vyzV*~|Bv9I#EvM5t9-mufKa3ri ztW0S3R{+CsfhdkMHxoRPvs_MmG(OIBHDgQP;26FzGV(h57Nw8;al<8}q-Q5wo$c(e zX*3_KrlF_gjeD3kX}aYJFY>tQ#_tk1Fz30Mz87dDDNU5wj5M_i)#gh%Nh#iIT zJbk7Jau2Ulf5YsJPc9 z0a&~E;I#78gZWyoee?G;0u336b<0KbteQZHDns6*Abiv#ca=eCI>MNNc%N&wS0354 zIT3Xj8(}>W9i$qMJN*JrfHVgkEn$lCz{j}&vCP>_2B4*J@12Mt7);v$LP2Txk$K$d zCMV^8+CqzBs9r|B=Aj{9z~$TUP-z4p$NCw+=sOKdP! zpxNe^=bg+#Ppb*?Es67{FQu8SK*?j0)p(Co46N~KEUhOR4}eL7@o%#{`r6b(e~Lvj zjOHiP%&@@%rlF@HS93+f8v_-?tr&&yrT-Y`p^($E(l3k8Ko!7*9^>fH&F5K^n-P?B zR1}*!sKWx#IeW`lIJN3tMf${}-erI-7uI6HM^jPOm1{i5K7DoAn7-KU^2NB^9et_d zT~PUKrsaJHc3nxE*OGd^B6*U2-4o1e1%J2d( zX8P%|+$m5JJk-nHD@}L`K+Y1!b@N*N_K_Li(GO&|{=39&E*zb}B1itX7u z7h_Z$^Yky}cc!r2KpKDW?Z>}~E*W@-F03y^XDr@FO`UM5jvyD9ENa*HGZsZOcayMn zxW4; qt9?1QsvWY!@fx<(q;^tqTk?(hpe+gMNTY6%{f2UXCazEN0h08_NFH=f3U zqT;Ks6vh8x_Q_ESWwjj1YP3+tL9)`%hj=l28RxBvh1FJFNY00sb(@%&8*Op*zkSY9 zZegU6Vh(AKoDVAL45#GgMhmI;PAvi{ZEso&u5eFvt`V$iU*X}@|GG6GG|Xk7Z!ilG z!q?+m*7sqmuG>=qCeU+NcPO|$>b%0pAGK*4Ni1#;W-#>qGh@$>_Z=HJdH|YiufMKTt`7eG>82 zTE7*pk#FAo>XJQY{kUTl1*F+9nh44bDIx9=Z@h9oJ1=zuVV2vYF-)O2J^!ZL2sI=& zs$=5>*S;hdTQide)%sZh@zYbaTxvXd;q~_ZY~x9G*x{?N^N#lN!OrQ3vSCoptXcc+ zyIcL@iG@0*%LTx_l6U$`Y8W)8p+O~M&Q--eFVzIC$(L=m5Gty?>=OE1)b$tH;bq@d zP=3)~;PTK0FfjhKQ&qKGX>2lvYNS2G(}Z`Jsqy~k8+@Mmof?9O>fC6XCw>f?&QC)G zhWTl#R*swM%&^ea_4uA-flbXfHtDKb^0iZOCA4K5oq<%;Hpz?@rau%KyCR+81-mND zG8F&o(g3i>qmS3B@XpOS^#h+%!ZgP7lityusk`!M_r`^hHI63$5q}2d-11YfGO&(z zWNIM1iRj?}h`2t@y*T+`jaK53wyGt*5m&%|*6`plUELk%7eN>1Xk%Y|sd!d<2Eo6W zEkK#=Tc70XMChVrA;^diuqvnqb!e;64Pc32_pqlFUXheM4_j7=m&*mV^>2ai$Q^KT zQ0mK+@vk6h`zbJ>)OI)zs7W{|MPnFG~YuaNgoS*I#!qA|9G zV=Gb|@q$7SskiQZtJ^6lG^W;3fg9y6K0dQin=}4vU>Nqwlz`BvtWdiaC5n#YxFET0PGy!tum7mxT1< zqz&D^;u_ocQGT#%Vs%ipF#af=dsB=1XMC>qd=u%~+=qKF?w@Xj?s8RLAF|&)V91FW zBS>585AyXeF&61#SEElqyUA6QBqnrzxV=~BE%3mGihfIt^6pfCE>u-`W6D@{?)JF6 zP78?4>f0*4>Wu^tnt_G~^mLuhp-Hz)RsH*XPfEPrdM!4dM1&m%dPNDE|4c*QB%QwK zmXQo`+W$#q`|2$@)jkdJ>%J%_Oa?oZmWb==3z~9hdd4Dcqp)Bbqid+`R(F%EW^gNX zsMN^NO5kZ>USapQCqED9eng~wmL5Nq^^>c@D$mikuP&Z@Gj&|PU}Iv6*gMYUo<=y% z<=(uv#%8#8VGRQLRurK>v>HTYT=K7?nxQp~TNUH8$SF#HB;;Fs29BF}E}g(H^g}@C z%Pqm86pYTJhn+6hK#KixMvW|$gCUyW80zq(N!+XbNo1ILDLdq@>{V`AAAGM;+?RlZ zGH#olhb{aKgv?>;z{F=wVQfFBuZ7FXE#7ws1=dECC=Jsc2)qZFr1ParNBr_oU*OVw z(5o@YPT<@~1C<~HG5zo0KBmx=`WLqS)1}|Ltr{HuZC&3O#0>|CKq&!kx2>tfk3rRv z_@gu2n`FShCW~oiIqawJ?)c-6bk=B-G7zpoVUs24k0=S@9eAhEW-V`gsOp^Y7t5Ps zTwb_-2(1~hC&&$;OJ(#9b&ISc<{H=3tu^Dkss0AAs zt?e!x?17`|fTM0&;ExuoZ&y>{k1Xl-X~03V-hJbs?%K%Juuem)+i`D-kzC4yKRUHW zE0?d#6kS+-JI%H!l|QBVS!V&Q((~xS`3WO$@wlYGcGG>JKHzE zzt^yq%gMbF-uiK%!3*R7S}O*|)l2lzRwL8{AxdTJ)|VL=$6HTU8pRz*rz{>loNO>t zJywIB)mf{1lzyxSZRedT1fQyX(CLm{kJ{?H0{sB)>u_pEYNHN4of=t|J_sh&pY-$Z zQoaFS-+Sb)+8#KbHTL2v1XAAr^Mw}r;4Q(w$tz4|+mlYvDKzObU!VNt_0lyuy8RNb zb7?6E*W|Eh7?oHMyU%2SkmxNzy)e29ZGCz*M^cS!*6CW(JL~-pVerW$ zPBk*t<1lP_kqGCBd$Jd#C)LdxU%FQGl^5i(QMT7jTB^suhj4%#pP!cj1f8h zT@r=cm{QJS&*?>3sfJYF)}9ergCsF~%42dbZ~XS5Gc9Gexfrn2DDD{ATym5gW(0!C zIu^0+vPKJ`MOrq*~gu>kkp6thd0Qs3MCo8 zzO|*U{7RiqiNwlF^o_m|n8#0zrxP$&xvd8Jt_4edJY#Knh$bAftkF7*5W^1A&1q4-4hB9o+L!x$b6gQdff%d=!GiIj$758r>=Dr6IZjeOhCS-Q%1h>VaUMI2oXJzZgLYaZd?ZA^T4Ci7M8j;NLYR&4iNAbuS?I zPBT3vA4{1Z8~_eKN*-GGx)&w#qwm|fZgoqb^b-Yyervb zQ2yhXZ$O#Xx$CPVs$a&bL+sV&tUlhJ-uA|GGDK4V%o_n&JDuLi~;70&OwIfUR00Ga)x{kCmUyx`1ojNz=VO3d!xm{WbP6j zs1Jo17`OdyK_QkunbshN(|e)APmEMCCG4j!_y&cgWwZa}4Fw0SzHP08GF2u2csuR+ zEGK08y0)s9`cHfF!PU>QmPI@osp;?ZB81?$#plxdSDd|aK0BDKj`Tf$e<7GYvRdl8 z(yv-DHMB9dW`#!p?{@WwZ`;S7`b@L)Zq z-1OPA42)ns6OM2qnT{Kf|7{Sov*99Nz5nmG6ER)6QhWt;dRbqL-n^}j`m5fXWY3F zBYTGSO82G$7932Lh1G}r#zt5WG^hc?I6I8Y>gp#%s+U+YBC{K_2Ul8f4g4*FBX4tW9~$)?b5#MBjT&hLMB z4QF=$E=HHi(-G1d-cx&rqu$+Y{@Yl)Q*JTO#&?~d^QbtHeJ3QW2z!xfPVe!vquhLZ ztK|@e*$FYs z*r{$Age=*Y5ZU)_?1k)OCwtb(HnI-J@;l>xKmY&ZaUb1B@|gGgbzbK@&-0w~e7#0F zV^N(e|(7e9Kq( zr%ss!_-5RLJbW)ESjSxv^27R5x~KS7Qv<7oTMn0=${lW&*8{H~ymVPq;{tNDkKwhs zG;e)&R{;te`SLYJ=+8*Koe@78ZS)l?3kZN8lDOCSjBcWBP??0(m#Ljw=*!5U4hAH$ zf=F-}q3R6WMx3|4{9b;X?}V_cFMiu>dueTyb9i|xH%CHPZoy7{uH4Oa?nIO?D%;hH za#+^&F6G_e^n}Co!-0#ftP0^N2vKW;ys~blFZBwlg$k%arMGC1Yhr$_i1X$82qUnr?sCfET$~W@JaPv}==1PouxK(r9`CA!LQMBz;$(4V zB#Ccz0|yZ2{V&IQ9}{`9R9HL8S-EDVcW$fEWjg)KtAyN~f7Pl`Y_1QUR8s{MXnxc`9(@U#x$`B{={AMD_e5 zb+fF&f`gy`VU-`T-M(86-2gUUxx)(dKf`5Zdl+8*1-O5ez9+>Rn{cN|Uv=!6TgF5- z!!A{roWfE0xj(z2SSn|U_JdXkY+jt?*SBB#kDk$Wt^Us2ULx0MoiBG-c*KgIteX{c zP}s55_59O%8T?O~eS_RnjVAz=2L9NRWSd*Kfj5^RvEmy(LCJ7kK+HqffGqt5a0Fgd zpH(2BwpdJcY-aiOVQ!h#LJC)AKxS{#RSworx5)EA#-J$GQy z4R{OS^iS%`?Q4tiMY)=&>Z3xPw3KV)bisY#k?I&9vr61jZsMrRB3k{a?0DAcCuK5{ zf4IdxJmv%Q3-Y5cO{ke<^%>C`4iqW<*3y=sMA!w)XR!h`)IopLBlg*wPr3bu(TAJm zKq{vnRah7Pbe(6hVutR-hRSJ{t6}6W2G6s(j`KAO0|(kUMyQF%JQY+uh86W+p&)Vg zgs-{q$UJWTOTKMLH8d}F+Zcy2k6YUl?)^^e?(^byB<;LgFp;5l-plG!|M5L2Vvg<^ zP8nNw>pb!0=JtK7)eqny?(T)bsQS2{zvZIA9n!X(@1a18f#UjSb#4u72-;i;?t;HeU4K44|R%2YC2{Y#^Xb{v=-e^ISq53|GDD z3lDytDYBrGI6!;&fjPtct|qy69#ZQybL$#(ZJjOc_`sZ;Ne}Lw^|qbOykZZ@kJXk_ z4W$J$iQIQ47ID>)NsS{sWmn|&lA)%A|F@QbWh6 zLfe~_={>wWCVndFDb$8lY6VlJwgQLyD9O5)_?iu))4!C&T{Y7@AUQoC+0Wv#DEP9= z|60-u^_hOPp^DXnp@EtK&4C`nBvavT;#DnO*Q;EiYC7KjkyzFOKE2ehuBoAY#McB; zy1~5*EoLM$xk~l9b|L}~02C?@ul*xKN&OMGw2!9KEfm6}b{u`!-_1-m)aTfh7|d&m zOee!%2-`<&Pzc(8R3D7rTj=o8%Um1Ccc9dE^;M*j#xrAXKQ->C^A5hHea2gSv+~%* zUAcFcK4|a!-Z-|v;h6jRSz(c_k+OE^=&N6&@5yPsZf5J7#DniRO&_bb+u9fmrp0g7 z+AVN=H59mPe2K<*B3`KLVIHaDxh?fRw7Lh@6~y*3c>a(eMdP)<#2B7};_m}xHyj^Q zh`Gtfk5nkUi@2rT?HBO9O(KSK3+FGJyMEuwDD#J9oWGs=!q#}Zw1$Pr-`e`?8+88e z2ov6^Qyrb^i(F8;_CJ-h&%(aPt|jKyKasVWezV4t1J73)x+Us0P;$TJ9024yP5^_P zeDoIuRPBXJmkYiEvs2D_2%@%Hx#8^&Mk%>>gFm>uheh9!q_yE7a{K^(;LO;qXdtTJ zStYg(m=!t9)Rh&8D4Gfg2$dG+_)+(G2X!O|@&Ui0h?+^;l%n;I^nZX$c@5wFeU-)E zy?Q3iyFr&$ia;XbwQX>b1rmE%k#p}e6kOv8CKV|sMXOT&)a2HS9q+C;q-v^B47MO6 z=_ajh9c2p_yxgtz>o?u!exasJ5gowc&7}?IFbh*N@zHa`uJ70u3oy|_bClbVhIoCB zwHlb4UN~2SJ{+AjJmQj{_IZJUot3%1vr~FEKIP9XgZjg* z?yZEPbmvu$%sz(NMIk!0rLf5m-o*$8bXWd-Ie0=CG#;ecih9 z_Y4JbhYnOw182sGOq*#-qSsPRfxi6ItGFMQe9^n5>& zF~4MEyM4H?+cg|2JT@QWXWYYlDm)nN zneZ1vv|$VV?qx9F<(ES9&vn<VfbW5s~H=?!7-|Gn)P$ zW^ZCX)l>wqQnWK;471>$p*%PuesZO)bHhZGIDkG3J?y)x|Hz2p?*~B5&e6euxN&g- z!3Ud!FncuoNBR3L?cZMr^?I^u0~PV9!V&>RVT?1US)u{FS}I2mGz+!GnOCMjV6(dJ zCp%0*sqpdPmD2mJ&D%nSuG}y%o=-@*x(7*}8M;KJEwZlF9#VR!>eJw{!U}Rw1S4*} z6%ZaelC_Ci!D;x{?fab^a@#4nY;p7K5>SWt3Av@31(%@Q<%ws95Qe$u-Z!n&w? z&09+w!InS<#h_GE=;c%R-ws07ZiJO_{Z$uGm`9(Sy!?xBV47RkVC325%K|u}ZPnk1 z6DhvKbgSp&|Nh{Wv};l|?V3uxs^gQ^Xi{aZ7O&r#f5N(+?bMZO0 zke&f_G~5v5koOMvb@LoTdTaOeVOm{VH?d!223BPQz?!vWDrXM4P=_QtT^qrz z@rty;+$VQx>86Fh8}<(|EZ}`zDAk`uO&>CHe)Wmk?fil(r%o)7^vQimi#eEk5B4xa zSzRKH6Je1tjIy_cX062EC*oR%=Dm-}TN-lex+(}-pXlL>)KkCex_Z~BB>dpB;_DUq zFErC|U$Op=&(bT<+i*JlF&>b7-UtwQg)IECN*Pt}n!;Ym2$Uat!_D4+Jr5o#VpuuM z&;|SH)#H7P+ny*l@XzOQ=#B6-TI@emkb9?nlIM_rPyKSMYlX>~qx8@oJZ0j0EZ#AH z5qF+Js4>%H^4IU_6Ts=FvX=O=U34giRUDvKfDJ8ShoA)i*};w`RLKgC!l4O7*`>=Z zvX*7Y1EO?5J93_@Z}2Q2sxeXp2NAb8{vC-Le(-aimdCwE(7O%ypP5B;^corjCUPrR zqYwXDEzhEEf31=&O4445pHX}DPui-x#jkY@5B;Sm>n`Fc9JefXa1AB~UtKdLe8;WFASu%jXsgItHkunRNcMZTVh z`3A)1*TtzA(#^D(cqZLiH{*@3HkljeP}8Oc3bvF^?hn$=Z{g!v!R`R0Ex8gR5PpaS zFGKF}n%P`N&x^_R9e;VU9L+@~>!Drq^>TRb_eHr)*1FCrV8tp@^fmRVI}EkoKW&Oo za2KVHz~ttIfPmoEYBgteH<3x4&a!5+?fA%MR=Yg^g20O4>OXTZ@X-H3Lr=j%-$S?V zf^*cL9XQ~5MxO>*=U?6a0%Mu@fFM9AY-6bAkY4z_#a3Jr`R=E=Ui`lplhMUn(b1#1 zTmLK^_jCSILX8}(FV5;BGO@AfDQwqtERH<;a9MglGxDERMRnLA5qVXE-NF`zQ-~9Z zDJQw%XUcxG2URbl-#zN~IVPw&ghT31T=FgLbg(?c%;HH{@~^xiZmOO38MY&Ea@a(z;uzBvIJ(kV7 zkoWTBTSbK-Hqx7x`{!?W1+?Xqqiz^%fVm!+e$3Pf(xW_H;P6YMUfqd+JBso%U32tM zzQ%i`pA^0PM7xbU3mmPdo!X=zh{La0pGWAE3u_Pdi{(PUQ5=>2Kt zFjZ6+mlYGJTXJ{8;ckt*>>(hd)!I&`qfZ!r7^l6#->>V#(41G8E9HcPg=sEtP{U3e z&uIBr;CQTMLB6O~=fz7opawac2>AtL1I?#%y)b^jAD{v5!Ba0N2iz{`8k_DW&o@b* z%SQD9+9f@vVZ%Y1!I+CvVFU|tL9Oz4oeRS~WuU+_62>jP8M(K%P_g{nGfjfrXBwQEIX~*BSRGm1J~+R89pSC z4FJ>g=8j`xY6B5*wyCdF^IWQaShjt-m>O#e)6$3i-@z4b&9h=WC445-4+l=v-`Z}j zj;Y#i4QwS@n0Dk5N-+I;TwBXj#=d*K@T8E_{}+n1+Li+TO9umTXW69@7g{@)?r06_ zDC|8RpP?i?lDam48S5O{5`3PW=`^fdXLpSbpDv;NRswLR;J9BGF+&k4oO?@Ij zPo1QH=HUKX*y zH}lsX{Z97Ay_5N)5qv(ibc}4cie(i>*QGuic9%(kg`1f8(@%o;t~=KEcwm3|ayzD! z%sp}7PQI~Ho`;!;38XkHl|Fb@MN4F2ssJGc`5DlhLbRU?5;AaBP37q6VXf#hVGYP? z6&Oid+Yh=zFp?18m{`YB2S)PQ;ka0G!Zk2|l)d!*l`{qAx;%>jINh551-@kWk znUVGAJY1)|7+lFX52>XV%k;{u%Kms%AZk5yL?Q0)i=u01zwOfnc9X$PAYptY?Wbtl zP+{10{$5;o7*7RF^B}&aw~`pZvHRnFS~f`(BRZ}$%r;ueUuJg;C2!=IaOX`Tx2KcC z%9}azfU0DxQHL2vN zpXA@ztFzYMa&uLv76Hx)7*u}mW`fRe)A_GO+=HhB#>H|h|sMJHWhi-(9i?|Utox?M@ zIdn23{>eS>aiIZYbCo+NeM>Rq@Bx4rPi)=3Gni&9UdTX~GPA@|M&4x;sQOlpQ@gXD zQ&*bUE|f8Be+y!-jE|Xc(k(|jwdp>9(Z&9E1iY}!pm;wwNO;qHA<;O_wT)DOL3C{v zzRTY1h~wVw?5|7dOoU!KaNEO-tXOS|zCpc1ob7EZgFKhLwC*>iZA76_7gg(p*RklV zf!}S;Y2_X;shGVa-=of-mfTz!nT1}n|0m7c@yv2 z%oBb`koGWU87(FiIo`d!o4xc{hsw1#IzS$k)>3OKu}m%S85T$@L^D%X;E3IhuVoY3f}U$%<( zz6FVob~61Wyf@~l3re*=H1nQ~@j#0%E+KI%c2~o7YL8*a9djXYW|aQxl~vVQD6ba+ z2O0(d7ne8V%Pvj?)e+J4uW$*5CBlK+&%@`r$PXru5zgx@{C&O0^<(Pv8^yvaftkBq zx!k)i(pja@X!m5QF)n%|?yjM6(FcWy&EvrFmpVGdOW-Wd+afsH7cK(Lq9E-1nP>cv z5MahNz%A@H$R-%VLY#Z%FzTVX{e%0^DaTe0zAMzU)Wa#k4u|{mutz@Y(E1FoJgk04 zjdHqekZ36yQuwDWN9!D!$`{4hGja-Q(k{AvZr|3K_aXoemg0coA|l(mHJ>67qN=L< zDS~tJ{A0%22)Fw-sVV1|?`Rr4NYgN0X!Q2Ynv+^YaX)k2vFd#YNHW#XyC$Wnf|Lg$ zn-I59vAsl(u_Sj8Ur#HP8O^xSdrZ&q?XBELK5knRx!p7`4cg_L=I#?G5C|nB=RO{2 z`^CX5Sf@O5v%Q=|2HkPdqDkl#- z@30Ya9$vW8MPFo2x`ojh#Vm1~JQomnz0a|2;tA?~b^MVg8!u6GtpgUYQ z7@6yRtPQ36bfZ6ewES183gzOm7ipz1@3zHwj}FO=y7;u5G?6_!P+%&fH)sFEZMgfd z?nY7q@S#&1qgt*z8fDA`!vW294w8|^OZUfZbt)?BqjKX)ZpxEy6m|AnncVxa zXN-lbxe>LGfBZqeOJh`GWr@W(kou{+*eT)dmGm+q6)SdMsb#8787#HD{T?M#zCFxc zmbw?|r6$DGI@K1(_(V^{r2_J}U(M)0?LN+@2(z?xvvm=zuQ6Z}`QQ!)Eni)aLG?Yi z*1pHBEg~@?3hEpC#f8DTFAZcHUAU!47RVRV&C+1%;sS*T9f>q{;mdfAQ9;+odp8&> z()XqqrJwyIjK_~>GCLUNI%BlvcONPj9MSlR9u0 zeF5er^pdwwKR;?pxf<^E=xuKQ8eYsTO6S7xjJ??s7A{#2^*=8?74qhx`l6Xh@(f%& z=lu!x;c1Ke(qY8sqdv&aL||8lg7+^!UN7_1^1ZD(=A<009Sc1&u*E^7UH!=Ht-h|Q zg9`OEYSuR|PaRXesPXre&9rRO>$mfw>95zheiXzW=6pv+%i9`a>&76LW28RC_ooFy zL*!@UiQg{9q-5!-l=Z1>hEW`k@w?uYCZbYtMaIMj^MH+%jps$0PRbXVzwDC(P48CP zHDJ@XAIzU-iDd~yK}(I#=^m}e^`IBJ$UlXQfFnz|-*X--!TOt|or?w00G|1C4AgyZ z7UBbTcX|Wq++|L+EmaD>c;YvU-@T>xg$8%gvDzPt>}{5i(40szas2Dv51=6egm_ZW z*Q`at#+-6=AMs6pGhM_Oqd?`Z2z~JI*YdEG&8sQYtHU3({XPSSN0|5mUHcrPxplqb z5e*9@q(O3rJy1Md6M{V=nl)<)<7hGcT5o5iy6YfOPqUoMBeK3ru`ar+L05Fv^yWpmA6T9+V!-JRo z3%l;>`&cr%K37(IdAhCT%a`*=m|CHxuXMe%KUcX2@eAWq8j(8)P0#O3jNlN@a4<0b z%UUumLTBTL0!yM#|BDAg4SDAepTQdMw(NM6uUhSuU+S;WK+z}n1~+i-{0b^|$I7L7 z{9wQIBQYq|`3Qi=Z*MgXDJaJe8xGzEkKdZObYtv|T)LA;psP%@&-3DpRnU z8K)CHAF(#>4mvxjt$5jv2m4(;n1q8*_++rKutM_(+8BK?zf+E!>gMroaqIK1<-7O& zPO^AlwwdX-)F-YzFLR9^q~Y$FrXFlxgW8x|Cs@;d74sHXm4EURwP2;-3LjA~NQ*L| zr?nAT79{lN>q`DH)&6eN+649DesB09q-rq?qY4-aX(>n3sDRPBg6TUAnNscP`V`CB;1Q$;Z5);sZ-{B)V!{%@#km=L%rU66^7NsXC&+tT2-BfK~8 zWHW!gwXTi*sIN3;2{V1C^I{rkSU{_T@N`Vr-w~=@tuMZdVL93l<`;~8tXkCFPfkKw=ipV!&*lgln!iCF$tFC%W>x8`NZGglx| z_|_rfV!+OHLZ2H>$oI{JL8GGTKMO$|R9dJBw!?hSlXcPU3ECgVuC&n(;zib#-)DNj zTLW|Sv0*a0uL{I0EWS{@muY*(e#?+Z6yn~Rn_Ao|7N=-CD~R34gf!oLP>P;Xl4kQ* zPzl|g?;|-!cA(YCG0kx}sl3}h`yO#)KS+jknKaWl$0gaLF%K5qbWngn;W6ZYhZDX( zdv?7H;m-!`bWlo3f$CInLa-uCW+^R8X;4rLV z_3PZSRcD^GD5^IcKHDS&7~e~S)B$)BK^s+zQA6hGqGLN?h=MTrD%>HN3_TiV)rf>U z$AR~ORYQFx5GGlCf$8r0OKZi_nj?GdK;uiDO{e~B(gwy^B~3?Cy{~{6d?%~Yl1mZN zP`xEbn&0GI?g*#k(WnO7FQ;Jbk#FjpLDP8>akWWdEH&}E~^r=+e->KP0`j|y7AEZ@qHiw<3pu!yRM^8 zXss}dR>#(wwT=;!a^=L(3oc#-BH$!2357VoxfC3XHcF&bl~-K=3|qK%pee2>XsvHo zv-YNcuHZt?U7%tIfjcg{uvJdS+NoDiAU6rS=9H}X5zmZwQ<|Ml+wTisv+7?bV)!aS-$1DFUjuoGjZjF?sX=l_z>y~^4z z7?PnV2zjF*@a0DaxCVCFYlQX(m#}o%My$6faadQkIm<43Jr+RdRjNx!y^9ld2ix%5?vcUgWGGOeQ~17;~lvRAv~isWK5JpiOmAmj9;P z$oldahF+DRf*N#vSY~9aW6~HLMiPJN=0xguIe4_(giFD=$p5@ZsBP*a6aX7u7!VYJ zzj+BMZsz6a&m5@X)6iG&7B-^4kuKsI2o;3KVJP4%W)yloxj*NQ`nCMO9TK!Zin(MQ z^_(ufT0GtGj&MUBJt+?gj<8|z+=U^x!f%B&Yv0v`W!j0jQZS}wun z6{IQlHszUHON+8%dH2Zd=l;1a7U<1gtstJ)a*-qbFxBfIENL<^3G2oRaX-r`EU@W` zo$Yu6jxWconp6xsCyFt7ySniPO^Q!S9l4v{<;!3-|IEou$vJQ{_1fTNI<|jhuCLsz zlI@UN0$E!$tBAN5#J2Mz+FMLV&rwG5QP6TcGpk}BsWT5+m#CXh5%rvDC!#83q`hx~ z6N!x1HvX7z`sUaF=`C`(VP&tJ;|X&cY!^fKd*^`Od(karps+zizhO6`^J8x&x zkAk?1d7sGVHK4$}T+yg~@ng04TwA9i)$*-Efk-sGU>vRBp{eoV&l0*?Wss#zKBqB_ zTLPIxf$L>8uc8y)nAgCuhBZl^ia)fZxsU{{dDI(wH`TndFEMp*5(`xU4SJK=9>a$q zzFyqVQcS)69woZ8>>nO;V@A#pPy||oEok*?v_k@_HF7~7PIh z7Np-T40PRB;yLP?BAZ1aIldZjgws;hwv68Qzkr-k9A-hlLGrKmJD^cDM&*vhiFPR} zC_3HCK@CdiDL7jbJfnb(6c_=lc7*_59zl8n_qvbz#CAd_x(nB=?LM?9K&ICb?tl3^U7dsYmRhE;_xYq2X?_2XCRy zqy$9qUzT9c)kcTGASi8`tRl)kau>4{hs_uhj_HAxcN(J;W*#( z2wmEE1krMo=1Jv0D?nih8qASj(I^!V%p$@gSW@BKM7c{^y&{)Ldsgga?q|R2P_X}+ zL9^GWGDpDPpQVf}625Cj7}GGVI+|AOR39y;1n$erFUX|q!&^&f%c)>yct_B0E73j) zYU1z;t}9(wdf4|__}eylWpArEA;CqIbAjG5t6AV|2NCRTAwTtJ-%vsG zV_-PMRa4rBy*jn%_P{@kC1cZpq#Z_c$@Y@Njmp7g9akztM?r*<7;_M*TMnmal$43H zN|XK)wgcA?pRGV>5D}S@bGhQrXPR%eOVK{;DnZ49E*zbW-}e9SlSDe{DIjNU;z^P= zH8b^WU{2ccO{*MQLPkHM;~XP+4?-v`b9 zNsz6<=Ko8PITaWHXoUWX-)4kS3gYv%eK`iUF#+q}$dPs;yOW3rl3O^Ilz3J5hj|DY6|-mq0E>f|tmAOG~tmsRj6F+RrxNhK8wqpHG#v&AZTJY3I5N zL2{Er*{A?hP*ziD0KVePOsJ{wc9o++R^srdL}~ds!*t*%W^$#YlRGf8{Etg0eshr( zK73Q$CKYUTss>rUHm*=!kEun|M8qe7tOLP1Uf;hhm2qg1N2Iq;ct zNTzbl7@`Ra?NlrcZax>%!b#tGFAnR;ug#CFqRpxh(E|j|^cJBF>vWFmgs3W=m;4LY zs1y$qlZbwbAfll3YZFz8g{4zSvs9qipo(^~r2YB+&YoD@NkrNe!zrlk7)+MdengGP z5pH+|3mMq`yZd_fWB7>u|j%~iUzVsy>yaL&IICqu`{pe7jT zaD4XgL?68ZD8Wsf(%L4eEQsei7Xk-$C5>i(((#RF&kU8^r7=4*X`0VS9ES1-z54)F zFS-jksc0Xr3zaypv+7XL8;rQ(&tiQSTB_wwT4N-W*u#IN4 z5hS=Y)K1MnKNS~7UcwvBXEH?7(o@WBteLU%w|`-0&BW_x4LQrw=?3m|D;he4ct-KZPG& zl-5U+`<)nq^=CGI+g(c&Ccs1h;n_=@vUwhX)40gxe?Z3e$A(DIfP-ZSgz#FPe-BOi zH5IXZJHP&9L4uc0S<9}Q&Fr&Aq9(!&&KZWdmlse#{KlvC>3PYpcb7lSgHF>t$fVk3 z?*tP8j{b<|A(xd%(FEH-=){y=fo5d$kr`XSc1d-1O%&57rG@dA#&C{Tk(C9;z_ghY z!vY7Q-MSLWtcy?d7TduB82)T{NvHi+jiBCTS{nE#x#J3Q6i1AS=RAa!BrOvO^w0yi zg|Zzt(s5pT3`vOjK}fmFcB%t-*EbNA#&+bCJll`TEgbF43C+rUARV}=KIHHT^6laA z1WPG#DE??mpp`NRlLnV6O>|{S%*5%Z4NG}c4`lO5mVF3=oYs z*Hl1A+BA_=!He50j*L4UD@LWb>eip-^%X_5H(7&T<_!q>I$;@gsj;RmrwD2Lv0J(y zyC{##NaKZ*UvpH^aGOc9Io)d+($G25kZi-!o9}VHe_v!pJbDF zk=_z`=UC~-GG=)xC-L;zb5gjd{pAFr$(7z#!hP_2^r&7?e!yA^#ArFUkV=cwW%y5 zY{qrX&j&o8KA{AbS&lbqfP$-KtEIDk<#sZN!vDXO1yS6!(IY&_cx>pAmnQ>VVlZLm zblvu9RWEm#HWAsQ0$5F&pZ`$@gC^G`pq7hAVE2GZd2nt$w*h|5MvitDU=#t;1 zS(v!}j68|Ci_?(=2|O)`KyW3Kv2RQnnlYn~Ebdewm-_}J&lTK9lkMRa49-KCX2~!t zaVHIblOL(a9C#&!=Kvx((Ehbvu;z9F#5{WZ?V_KIYdqM~p1RSy2J^Rc2zuH$hn4p~ z1l5^O<(jLk%Gr6o&wM8tp}U5=zi&~uebjUF;6Z}8zT_e z7q^-E1(9*50x`4)pR>2M&IAc(Q79#HXpI|3QT{3Y)bKGjsh`4wC`j<&EMM`1$v2?w z^qZk`$^3u=$@`4Te0jvnZu@WiH8`vP5Z@p#H|a$rh!oW5Pe)@EqA`0q=yjh4d9)G1 z?gFCvctswji(H@(IrL42E0k>r@ZSRDZQ5Mclfwwfi$P zA38Qlp)CNZRjH%|IL--AUZ-(GPsv{uqj3B$F~;ycoW}`3k=*4_f5Z8p!O3WTl!;A#rw(y!p6fki7&<5~+fkUKQ5D9=veUGvB#-1q;!DRJG zQlf|iI`rgGrp*&fjhE~HLbSXFD2{E1?w<4~!>A*36RsmI2ZVLGt}Ilb;Q?X}8KP8~ zL!M7pBA|IGc<&R4bRQFvS2+CL;E786yos>JZs*G3F;p&xE|Ma-_eh%B73-mFiHC`V zJ`}0)0@4dT30DL}*a;x2Ib0klPAF($!G{}xFtqsiC=PPU(?1m*f+X7D7EmtO-g|aU znoVS!9TEAfqciqmK-hZZ&dY^|Ms$!fH!}92MrI#syviwXWSI*N+UB=>zr(Z{g1(xsERs<~ z@9b`Be@vY1pJCd<|9zJP4__W2ue7onBR+rH-sxB@w*r|%C-K^+TiP%Z@a3Y#Fk)bz z%S^wf?C$wA=s|~8iR9ZL9)qF4B_P%Rz9Wo9E5O|WbJ5fkjI|g3=0zkoQ(*e1!~=-a z0{5|>`k+?htk`=t(|?6-ZbI=%_+eN%hsQVs=VLhEJ>ueCKbuG+K0R(A7W|*al(^Lr zR3G|v>)3u#=dxd0+=PMAC;WCk)?f0~JG?6pXSmzwyJYcm)T1E@Qm6#U8cT#8@)7hT z9dh{qlV*0*afJRi%Q7LyTX1QCzsi#m%4LuRt`2v2iTnTi?jo$-PHtB*e-VW+W05`Q z;kvW)&MF(aNHMVb^~x(A832z`k_`g?(*ht0XfsVjOZMogKpS9UJn3?i!g5Ao7&0A^ zz#fA+JEh1gNeTtCkfW)3`%eE6@A@3=u8c0V?>d0UAkaEu2}TrMSi4ik>O2dWW3v01K^~3+qDL+wK`s_? z_cgx!DHqS5{4b($GU%wtkb-hhlnCE(LZgv&!v)GT@uGO`KPOLJ)n_$iwV5Bm zO~{2BYZk5d_Gap)m8Qp1y;{%SeJOA>HJ02v=RjNx8IrHxA+P5Sr)_nw_~M!EC>$?# zn3i_KvQiT+k^R|hEdR9POT?2z(_<0BJ_#I5_4jHUnQWcW(QHg4G+KiwgfOYR;;iB^ z-Ww=??+1IKxzjSSW}+>o3j1QEroLEs|Qr&nFd#AV)ZaNB+_;vhc>! zBgX@H#$^BhJnyzWgHde&vzUEsD<5_?WCZfJACQtitSf7b{fc4YTQ?!7``Tz$Ic z(+Enp>ZjL%L!5|wRi1NoaW*?mh3poCeUsKsf=QQ@Dh$a^%8wCQRT;|^`o^dN-9VRAt$ymJO1tgdI%#t_$=V>M_wTC?>KUm~CIGLJ}FJ@Gv zxj2Pm!>|5q;X*hnEJjd9Ww%=D{O(T;31%BnyZM3UIFNt)6m7~r*Biz@B!_CO?6|4uV%__WT5>Y)WGjhUOtE7} zoveH=*%g;ZN>2I5D>y4Vi{a?1Uy4M`CdrO&CFu=38njg-hwi8fJq%t9ciE+2;Ok-J z#qJ&kHXqVyD5o0DChX7hlthlWx20EVQp=1&ypquFa_Ob)T2Nd0zTWRzt|O-VMb=q-%5)v(QgY9-kpw{e0iy`xEJH@{_BqjXhe^zJ#1r>vo%1w-ara93?D=& zGV(bHuuEmRjlH$xD~b**o9cNPG33^AqHOWz0w<=;*t&v#?FQczud2spe)u z!nJMIwp&%n^roy&TT4EwYIhlEU3u=z3%h_opSg^vE(lcHx{odwMkcSRwjrv=#EXY? zq|4@hE>4jh1_G>0<6qwC zE^V$iade34fV1!-qCsj~Wq1i$WGr#`FT~{96--;z*Zl4xaa_HnQ>B>w_~^^MX=4H^ za^{CLF3xrFw@BC|ykgR&S(-i9!S?Zecy(vH7hRejc~ic7W7$O>3v5M-n(I{!r zB7<+-HkD&LZ9Uiw;;`M-%W};dHpk1CENMHTON8&dO^yiZte^q8D-y2!{HWrRs#aCv z(!)tWt=IDae(&v_7R`>+K8K<_wJB1-CSqvjZy6(DV!+H z63vB^&_UWQ4CypOmlt31$(FAjy;u9e?am>DgriN23y}xspCxT$8wRM27Fx zGgk&IFc(N#eTSF0h~(&}N63Fx3+bG~C|3yL>UW(>OQ%)?UJ}NJU1k%l2wDtDsoj@k ziWbr}h#`S@(6tdU@_YI@#zaRl!)F5TDNgiVO7Tk#LB?VGdf_`BC0XG$lm%H|U3X_$!g`2k>1o|~v1 z(KP(mr1+=VPkg+(5>#(*He&4PbrJzn>R-0#Gt$MKeOfSonN^x@qB0l0!cu1YXaAh# zpmNsN9~n-SuI>tp?{VvTuk`k9Ct~UT2fph1_QRQP373?8@uS{&*$?>2mIp10DCBq? za(u6m^RMb%&7T9}*e8o;^>)T%%RDZExgyOJu^s>@9&29ISm(*U>58!^dM)Y?JMo3= zj(deu!Kf;?r5Zzaq7C{oi7a{26w9?UoG%s7A6<4Z+`UNUgm4vv4XB;nCtK5{LT|!1 zGfi;Grmutx63Xm;LTpqxEgrNab8C6@W~I9MVkjIIQwgGLmIuRJlkiB~F+_Fxb@0Bk zyh-YQ_`Uo~K65|CORjcjx9Og~DVaNy!N(^Sv$i>m>j^Db&qh_c zb(9(ouv+WDjivR9Remk##HW=m_QQGgykcDWxnlOKFKT( zIkmjvPjX;dS_krk$5-L;ea6bjstTqhVJ2I*hcjeY0f&^^RMzYuDb{7;E7qN)@mO&s z@u)5>J16Ze`rA}^d`=>5f@f4LHi7T9Z6comnar#S;Bq1T9uN`l!E(kSTT2#a0(9CP z#s$*{!pJSd2UE?~=??dBzuc#(#u#I!<#T7=nRbN>hIQ%*RPfRW6ke3DQ}b zSs3+;zvtG*QX3L&WGW#7Y$7pDJL!XA3^(RhY$Atx+yKLrJzj2aikJ?}oX$2fupHg; z5LrYn#vW!!J)L?cHGuI$cRih0H#XWH@Engf6Kv|KwCgK!5|kcfDf_P%E0#kCH~5ODe$ZlmR#!8Ho$=6UH6oLzFJsa9JJWFuawMkGhn)$6oYv-{o2tx{-~k7t@?M2U;FMXcQS*Y@~2Lu926P%;hJa zaax+-Olo=slm}p}r#B(#Ie$~(!_>lorv>VR3Yk6Y32Iitg-=lrt$K)RNdr$T(y^Zg z(xs>TEi_WC?8;Rw&sr&}-(&A-0vA4O*?qZ3v|p+tJVQ~G_sT?SZ>6P$-d^n1@9I}> zt|LZ~7H!m+a2Z-U5kDfdLwc9#W(af-u^vYA>^uBP&(Yf4OnpFgb;~85Il7?L^WNL0 ze2}YU8?WnPt_)Ut2-sqlx2~473*QP`xv|7K>a1rNTK)?jGa97xm>POhtnylADW%d( z_{qKL;ua?ZbK?9Vi)2C;qesP%4n z)cd)K1)jAf|FNxS6d;?v#Y$wI((G#;anw1K_J}AcBr1&iyDDAvw{sBJALOl+$^JYY zH!4ismO}ie25Gs7<8LS&!l%?8;_lVP$f<6B#c#BRWz{*QOZ;7k-%v)o3L#~p)Xp^y z9lT{?YM(W0S>!ddgaogZErvtY2aL6G(dLx(gIQ6C<7*&(%00>W@aZS3>(> zy@K2U1>ocgz_)c-0%i3pjY@K)Xf9>ZBYqVog%l-)$edzo<{2-=Z|F{6&>f^_S}JB* z@@2XvoMi9xaAxttX~ae@ZVe7TosE(A5XZ?2t#zA8tH~d0zPu8<^=rG>RS@8EbDv&P z7|NHZH0WV?4;#c`p!V=Fe^Oggh>$=2G0(Um(~{z}fUbG~eo?*_{!8UgGUiVjRpfV* zOezq@up_#|dfY_LHLv@_X<|tEwNqjAwk$hfRfWMv-49L~ScSq?5;~3laWc zcVau;=K1r8VyNr9Mx*WO+r3z|ciME4ic*IJ5tAKHECyFze-qzRkWU@ogKus7&=Z9E zb#-G7zoACPhxG@c5dMf!AG}^0=hAiDG=t|`;N+_4?MukrfP_n|^0hrowpM8Eb4*r} zgC^dmnN)uG-u=j}7w{#-LNgr^&hp#`ntW{9m>L?r89kxoC(t}xGuEM-_Q6&EkB z7OtfBFp6g!{<4&C$r(A`%4DmA);_~@<$7}Kg{TQW`JTlWDfl(( zvD=j?UTIn)BlEG$>u!4CC5=(ks~OqJ*kb~F2SBkpBIj_{1nhh<@OojF=qC8X#5@YHeRnt#K7a3R{&4+>&_ z$X<1<`?_aGRjRr+lCm~Q9&5iOr@HrPmwtDu+n;67t{CxA-a~;hy=V39hH?);;0f5? zU!Gq=u;|*>|7%1nZ^R|O%jX$y!H4?^`zy-T{=hr(B4d5~_qW;EGD<5Zk;h1n(O=S?+sc>5$vy0}r`78>NBdP3|6$upEgqWbeGRw5 z(NfFy5ERdHwU{MY6`f0RwaZ~y#!R-|SG0#UU+4{v;GgYvuC=I0TPyM_8NWQ}xnpNn zzr0X&!*O#h?o8>9j-j804VjBUnQ%!-ci5$uEqhjaqLJoRxhW205pG?_1=BKxgcZ$DM8iA{N@UCb3{+9)7XDv#*Z$PhmB-U%SAOV&bx=_t;NXsc zh=NdFG14w#wTK9cmhgyM#_}dWln@|1v?5}Kt(u@bU1<;^2?Yru1PnfEKwbhNJdzNL zB?uumypmJ{WWP!KFYL^EXEKw?H4U;0%luQlh~M!B9$KA++RjEme**O$BS?BmAHCbokoSQKUb8C?RBG0@VH z$oT3tnMJ3P_#l0+{!3(Al=!A-gPq&*Ryk(nh_dFM;q336)mp4iTin@AOt4+vcdmxjVnA+=p?eE9F7)v9no}4)aS9u)*jN9cVAiy(q421E z>wc~ZYf?HTI*Tym$Vd0y;jX8tUrxC_UZYL9Rd)lOewA2NXuQx#Ac-9@uZL|TA|ls+ zwtzAzQ(3_8k@4y&TbP<{)2w%DSmC4bi^k2_uecOrS~W$I|`}2%VNf& zDSm^;I2}d~oBYwvlGghdSJx2p$LqZyF!1RPbO{#NWImJ^SZih;C3}?l%pYsN(Lbg= zlrgQx0tq=#Hep7BjF+ZGxrsqg6P@KS`=n3u9sT3xZx7TU znIyfxOyxuhC2HZ(Gkc>Sb@4-rLfRSHK6}%|2 zt=WC^Vd`i2JH+`(yX=Q~esBKM6k}2B{z6A2{j3KOICr6vxWD6~As-nczIK<<2Crj$ zIEprl0i_R85W@)90shz^R+o)uzdy}@$`)whzvaf(q{}7vL$gBLDr4|syB3J)V@>6Q z^FDGyvQ^INIH)tz66agIk{;=EC#%@ID{JApfp>E6NI^2NPn1g~h%|8MX703J$vWhv zXAl<3Cbi1_O73jm)fb)}$sNIp9w{{-AehC9$1it%PKlAR?;r50;F;c$7CB5edp~I4 zB@Q?$Y^-u~78TFTs&vOMDje0qMQfG&t5eAKOuxZ03=6@oEE$5wE#LNA2>m>hVE{`@ zRrvwAuL@t7sSJWzep5_IZfpB`8&*AZg)9Dy!wL~2Gt?&!g61L~Yc8?OJz7fls3n12 zKgI+Kn$Zb9G|EMRaFK}@>$>8Cj(7b0oiU^FirwiBmS2T#s%rZ=Yn0Nc3IiT)hUz+Q z;A!BZw?Wz9Mhf^T$zx0V4?kB9j-_kXQdaBVRF#cikkCM27%UL`Z3%YY6fRFZ*h=|z zWcGp$PxDjpc|UGB6b%UY-wjM`ps;OaZl1=K?I36O-!d;3Eig;^2c;f{qN%BnG_7qo zWesMe1SiO15gS;c*bQ(ULhK*3Q2C9Bv)=mr!i;-myL)}dwZi4EUQ}apqLbc^Q`Acv zTY`T}me>Mz?uJyTeu$y5I)QM;$Z5QX(157k)THa_wm{&rHZQ^6E55#qos^)4Fwm)= z0v^6}cUdNzYbdmHX0A43`HJs#`zjyF?}pqCL3TqU`u=FdZ;*)I)3FI6{N$tWD2JcN z)=Vx7pUd-SL3v$z6B%6iVF#<3d=Y?s6AT~9)_RkI4R~1$9-&CTXTBHp?b=M ziGjg)87CYdLLXf*Mrg{o0cs4qjo_+(7@&sZHE>A7qDP9A{>&O5@^wp;2| z2_68wO~eK7h~Pt6c|Ud$t48kXg89n zS#Z{C-kTFi);|<~Tui>F;_S=WNiuC@cAl=U9&XCkIih(W9*RC2rW58X(qfoUEz5>Jbve~fm_zg0wS9sb`0TRt2ttr{(go?u2VmVq zh7!j$5D8w>g#0$9fChf=-9+hmztUbTJJ;<&{HZ6?`$kau4Cs8HRTypESm%nX9NEqs z=#i$n%wxV9n@N8C%E{kRP319w(ZnO$@+Q7bRY-;sbOSki?QE_Wj(=k{Pfl5wm?;Nt zYHRQf?B_nYEv~Mfzbufoq^$ajvT1Nt0mm7adtxkAQ5q`e(qS{0TYuyh)ZaI6hIl+u z%=qM>X1U~sXS{RJiA2lslVaDl^J&`G$9K52Y;!gzzC`=M{VPqJu^5XMjq+e^(i063 z&@5Exlhy z0u@0`k@B010VWuavKPk4HGGe?G*$=0*L!h)S_Lv{?Vp{2pFf;G z$Mv8M{Qx|6Z*tHpUT{gj(VI)fqD%Rlb{$=~~bZ!fX;3)mOn tFMmCD_)E|=Kgdz}5IyPtug!A3=}}bK-p`*?E*Ko~nE#2xtbd-n^j|IzyD$I% diff --git a/lib/impure/nre/web/logo.svg b/lib/impure/nre/web/logo.svg deleted file mode 100644 index 41d142b2a..000000000 --- a/lib/impure/nre/web/logo.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/lib/impure/nre/test/captures.nim b/tests/stdlib/nre/captures.nim similarity index 100% rename from lib/impure/nre/test/captures.nim rename to tests/stdlib/nre/captures.nim diff --git a/lib/impure/nre/test/escape.nim b/tests/stdlib/nre/escape.nim similarity index 100% rename from lib/impure/nre/test/escape.nim rename to tests/stdlib/nre/escape.nim diff --git a/lib/impure/nre/test/find.nim b/tests/stdlib/nre/find.nim similarity index 100% rename from lib/impure/nre/test/find.nim rename to tests/stdlib/nre/find.nim diff --git a/lib/impure/nre/test/init.nim b/tests/stdlib/nre/init.nim similarity index 100% rename from lib/impure/nre/test/init.nim rename to tests/stdlib/nre/init.nim diff --git a/lib/impure/nre/test/match.nim b/tests/stdlib/nre/match.nim similarity index 100% rename from lib/impure/nre/test/match.nim rename to tests/stdlib/nre/match.nim diff --git a/lib/impure/nre/test/misc.nim b/tests/stdlib/nre/misc.nim similarity index 100% rename from lib/impure/nre/test/misc.nim rename to tests/stdlib/nre/misc.nim diff --git a/lib/impure/nre/test/optional_nonstrict.nim b/tests/stdlib/nre/optional_nonstrict.nim similarity index 100% rename from lib/impure/nre/test/optional_nonstrict.nim rename to tests/stdlib/nre/optional_nonstrict.nim diff --git a/lib/impure/nre/test/replace.nim b/tests/stdlib/nre/replace.nim similarity index 100% rename from lib/impure/nre/test/replace.nim rename to tests/stdlib/nre/replace.nim diff --git a/lib/impure/nre/test/split.nim b/tests/stdlib/nre/split.nim similarity index 100% rename from lib/impure/nre/test/split.nim rename to tests/stdlib/nre/split.nim diff --git a/tests/stdlib/tnre.nim b/tests/stdlib/tnre.nim new file mode 100644 index 000000000..85792b81e --- /dev/null +++ b/tests/stdlib/tnre.nim @@ -0,0 +1,9 @@ +import nre +import nre.init +import nre.captures +import nre.find +import nre.split +import nre.match +import nre.replace +import nre.escape +import nre.misc From 42db40813cbb19a02f205a3d575423efd4f0b2a8 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Tue, 26 May 2015 19:18:34 -0400 Subject: [PATCH 0300/1263] Clarify nre licencing --- lib/impure/nre.nim | 53 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/lib/impure/nre.nim b/lib/impure/nre.nim index 09b855213..4b8a14b9a 100644 --- a/lib/impure/nre.nim +++ b/lib/impure/nre.nim @@ -1,3 +1,12 @@ +# +# Nim's Runtime Library +# (c) Copyright 2015 Nim Contributers +# +# See the file "copying.txt", included in this +# distribution, for details about the copyright. +# + + import nre.private.pcre as pcre import nre.private.util import tables @@ -33,6 +42,50 @@ from unicode import runeLenAt ## `Java `__'s precedent of returning a list ## of each character (``"123".split(re"") == @["1", "2", "3"]``). ## +## Licencing +## --------- +## +## PCRE has some additional terms that you must comply with if you use this module.:: +## +## > Copyright (c) 1997-2001 University of Cambridge +## > +## > Permission is granted to anyone to use this software for any purpose on any +## > computer system, and to redistribute it freely, subject to the following +## > restrictions: +## > +## > 1. This software is distributed in the hope that it will be useful, +## > but WITHOUT ANY WARRANTY; without even the implied warranty of +## > MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +## > +## > 2. The origin of this software must not be misrepresented, either by +## > explicit claim or by omission. In practice, this means that if you use +## > PCRE in software that you distribute to others, commercially or +## > otherwise, you must put a sentence like this +## > +## > Regular expression support is provided by the PCRE library package, +## > which is open source software, written by Philip Hazel, and copyright +## > by the University of Cambridge, England. +## > +## > somewhere reasonably visible in your documentation and in any relevant +## > files or online help data or similar. A reference to the ftp site for +## > the source, that is, to +## > +## > ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/ +## > +## > should also be given in the documentation. However, this condition is not +## > intended to apply to whole chains of software. If package A includes PCRE, +## > it must acknowledge it, but if package B is software that includes package +## > A, the condition is not imposed on package B (unless it uses PCRE +## > independently). +## > +## > 3. Altered versions must be plainly marked as such, and must not be +## > misrepresented as being the original software. +## > +## > 4. If PCRE is embedded in any software that is released under the GNU +## > General Purpose Licence (GPL), or Lesser General Purpose Licence (LGPL), +## > then the terms of that licence shall supersede any condition above with +## > which it is incompatible. +## ## ## Other Notes ## ----------- From 075a5e844069979f1fc3782839e9e2cc62c61ad5 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Tue, 26 May 2015 19:20:00 -0400 Subject: [PATCH 0301/1263] Disable static building of PCRE --- lib/impure/nre.nim | 9 - lib/impure/nre/private/pcre.h | 630 - lib/impure/nre/private/pcre.nim | 47 +- lib/impure/nre/private/pcre_src/config.h | 349 - lib/impure/nre/private/pcre_src/pcre.h | 677 - .../nre/private/pcre_src/pcre_byte_order.c | 319 - .../nre/private/pcre_src/pcre_chartables.c | 198 - .../nre/private/pcre_src/pcre_compile.c | 9515 -------------- lib/impure/nre/private/pcre_src/pcre_config.c | 190 - .../nre/private/pcre_src/pcre_dfa_exec.c | 3673 ------ lib/impure/nre/private/pcre_src/pcre_exec.c | 7160 ----------- .../nre/private/pcre_src/pcre_fullinfo.c | 245 - lib/impure/nre/private/pcre_src/pcre_get.c | 662 - .../nre/private/pcre_src/pcre_globals.c | 86 - .../nre/private/pcre_src/pcre_internal.h | 2781 ---- .../nre/private/pcre_src/pcre_jit_compile.c | 10704 ---------------- .../nre/private/pcre_src/pcre_maketables.c | 156 - .../nre/private/pcre_src/pcre_newline.c | 210 - .../nre/private/pcre_src/pcre_ord2utf8.c | 94 - .../nre/private/pcre_src/pcre_refcount.c | 92 - .../nre/private/pcre_src/pcre_string_utils.c | 211 - lib/impure/nre/private/pcre_src/pcre_study.c | 1643 --- lib/impure/nre/private/pcre_src/pcre_tables.c | 727 -- lib/impure/nre/private/pcre_src/pcre_ucd.c | 3630 ------ .../nre/private/pcre_src/pcre_valid_utf8.c | 301 - .../nre/private/pcre_src/pcre_version.c | 98 - lib/impure/nre/private/pcre_src/pcre_xclass.c | 268 - lib/impure/nre/private/pcre_src/ucp.h | 224 - 28 files changed, 10 insertions(+), 44889 deletions(-) delete mode 100644 lib/impure/nre/private/pcre.h delete mode 100644 lib/impure/nre/private/pcre_src/config.h delete mode 100644 lib/impure/nre/private/pcre_src/pcre.h delete mode 100644 lib/impure/nre/private/pcre_src/pcre_byte_order.c delete mode 100644 lib/impure/nre/private/pcre_src/pcre_chartables.c delete mode 100644 lib/impure/nre/private/pcre_src/pcre_compile.c delete mode 100644 lib/impure/nre/private/pcre_src/pcre_config.c delete mode 100644 lib/impure/nre/private/pcre_src/pcre_dfa_exec.c delete mode 100644 lib/impure/nre/private/pcre_src/pcre_exec.c delete mode 100644 lib/impure/nre/private/pcre_src/pcre_fullinfo.c delete mode 100644 lib/impure/nre/private/pcre_src/pcre_get.c delete mode 100644 lib/impure/nre/private/pcre_src/pcre_globals.c delete mode 100644 lib/impure/nre/private/pcre_src/pcre_internal.h delete mode 100644 lib/impure/nre/private/pcre_src/pcre_jit_compile.c delete mode 100644 lib/impure/nre/private/pcre_src/pcre_maketables.c delete mode 100644 lib/impure/nre/private/pcre_src/pcre_newline.c delete mode 100644 lib/impure/nre/private/pcre_src/pcre_ord2utf8.c delete mode 100644 lib/impure/nre/private/pcre_src/pcre_refcount.c delete mode 100644 lib/impure/nre/private/pcre_src/pcre_string_utils.c delete mode 100644 lib/impure/nre/private/pcre_src/pcre_study.c delete mode 100644 lib/impure/nre/private/pcre_src/pcre_tables.c delete mode 100644 lib/impure/nre/private/pcre_src/pcre_ucd.c delete mode 100644 lib/impure/nre/private/pcre_src/pcre_valid_utf8.c delete mode 100644 lib/impure/nre/private/pcre_src/pcre_version.c delete mode 100644 lib/impure/nre/private/pcre_src/pcre_xclass.c delete mode 100644 lib/impure/nre/private/pcre_src/ucp.h diff --git a/lib/impure/nre.nim b/lib/impure/nre.nim index 4b8a14b9a..a351fd8d3 100644 --- a/lib/impure/nre.nim +++ b/lib/impure/nre.nim @@ -85,15 +85,6 @@ from unicode import runeLenAt ## > General Purpose Licence (GPL), or Lesser General Purpose Licence (LGPL), ## > then the terms of that licence shall supersede any condition above with ## > which it is incompatible. -## -## -## Other Notes -## ----------- -## -## By default, NRE compiles it’s own PCRE. If this is undesirable, pass -## ``-d:pcreDynlib`` to use whatever dynamic library is available on the -## system. This may have unexpected consequences if the dynamic library -## doesn’t have certain features enabled. # Type definitions {{{ diff --git a/lib/impure/nre/private/pcre.h b/lib/impure/nre/private/pcre.h deleted file mode 100644 index b2d9c05e5..000000000 --- a/lib/impure/nre/private/pcre.h +++ /dev/null @@ -1,630 +0,0 @@ -#ifdef C2NIM -#def PCRE_EXP_DECL extern -#prefix PCRE_ -#mangle "'pcre'{[0-9]*}_{.*}" "$2$1" -#header "pcre.h" -#cdecl -#endif - -/************************************************* -* Perl-Compatible Regular Expressions * -*************************************************/ - -/* This is the public header file for the PCRE library, to be #included by -applications that call the PCRE functions. - - Copyright (c) 1997-2014 University of Cambridge - ------------------------------------------------------------------------------ -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - * Neither the name of the University of Cambridge nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ -*/ - -/* The current PCRE version information. */ - -#define PCRE_MAJOR 8 -#define PCRE_MINOR 36 -#define PCRE_PRERELEASE -#define PCRE_DATE 2014-09-26 - -/* When an application links to a PCRE DLL in Windows, the symbols that are -imported have to be identified as such. When building PCRE, the appropriate -export setting is defined in pcre_internal.h, which includes this file. So we -don't change existing definitions of PCRE_EXP_DECL and PCRECPP_EXP_DECL. */ - - -/* By default, we use the standard "extern" declarations. */ - - -/* Have to include stdlib.h in order to ensure that size_t is defined; -it is needed here for malloc. */ - -#include - -/* Allow for C++ users */ - -/* Public options. Some are compile-time only, some are run-time only, and some -are both. Most of the compile-time options are saved with the compiled regex so -that they can be inspected during studying (and therefore JIT compiling). Note -that pcre_study() has its own set of options. Originally, all the options -defined here used distinct bits. However, almost all the bits in a 32-bit word -are now used, so in order to conserve them, option bits that were previously -only recognized at matching time (i.e. by pcre_exec() or pcre_dfa_exec()) may -also be used for compile-time options that affect only compiling and are not -relevant for studying or JIT compiling. - -Some options for pcre_compile() change its behaviour but do not affect the -behaviour of the execution functions. Other options are passed through to the -execution functions and affect their behaviour, with or without affecting the -behaviour of pcre_compile(). - -Options that can be passed to pcre_compile() are tagged Cx below, with these -variants: - -C1 Affects compile only -C2 Does not affect compile; affects exec, dfa_exec -C3 Affects compile, exec, dfa_exec -C4 Affects compile, exec, dfa_exec, study -C5 Affects compile, exec, study - -Options that can be set for pcre_exec() and/or pcre_dfa_exec() are flagged with -E and D, respectively. They take precedence over C3, C4, and C5 settings passed -from pcre_compile(). Those that are compatible with JIT execution are flagged -with J. */ - -#define PCRE_CASELESS 0x00000001 /* C1 */ -#define PCRE_MULTILINE 0x00000002 /* C1 */ -#define PCRE_DOTALL 0x00000004 /* C1 */ -#define PCRE_EXTENDED 0x00000008 /* C1 */ -#define PCRE_ANCHORED 0x00000010 /* C4 E D */ -#define PCRE_DOLLAR_ENDONLY 0x00000020 /* C2 */ -#define PCRE_EXTRA 0x00000040 /* C1 */ -#define PCRE_NOTBOL 0x00000080 /* E D J */ -#define PCRE_NOTEOL 0x00000100 /* E D J */ -#define PCRE_UNGREEDY 0x00000200 /* C1 */ -#define PCRE_NOTEMPTY 0x00000400 /* E D J */ -#define PCRE_UTF8 0x00000800 /* C4 ) */ -#define PCRE_UTF16 0x00000800 /* C4 ) Synonyms */ -#define PCRE_UTF32 0x00000800 /* C4 ) */ -#define PCRE_NO_AUTO_CAPTURE 0x00001000 /* C1 */ -#define PCRE_NO_UTF8_CHECK 0x00002000 /* C1 E D J ) */ -#define PCRE_NO_UTF16_CHECK 0x00002000 /* C1 E D J ) Synonyms */ -#define PCRE_NO_UTF32_CHECK 0x00002000 /* C1 E D J ) */ -#define PCRE_AUTO_CALLOUT 0x00004000 /* C1 */ -#define PCRE_PARTIAL_SOFT 0x00008000 /* E D J ) Synonyms */ -#define PCRE_PARTIAL 0x00008000 /* E D J ) */ - -/* This pair use the same bit. */ -#define PCRE_NEVER_UTF 0x00010000 /* C1 ) Overlaid */ -#define PCRE_DFA_SHORTEST 0x00010000 /* D ) Overlaid */ - -/* This pair use the same bit. */ -#define PCRE_NO_AUTO_POSSESS 0x00020000 /* C1 ) Overlaid */ -#define PCRE_DFA_RESTART 0x00020000 /* D ) Overlaid */ - -#define PCRE_FIRSTLINE 0x00040000 /* C3 */ -#define PCRE_DUPNAMES 0x00080000 /* C1 */ -#define PCRE_NEWLINE_CR 0x00100000 /* C3 E D */ -#define PCRE_NEWLINE_LF 0x00200000 /* C3 E D */ -#define PCRE_NEWLINE_CRLF 0x00300000 /* C3 E D */ -#define PCRE_NEWLINE_ANY 0x00400000 /* C3 E D */ -#define PCRE_NEWLINE_ANYCRLF 0x00500000 /* C3 E D */ -#define PCRE_BSR_ANYCRLF 0x00800000 /* C3 E D */ -#define PCRE_BSR_UNICODE 0x01000000 /* C3 E D */ -#define PCRE_JAVASCRIPT_COMPAT 0x02000000 /* C5 */ -#define PCRE_NO_START_OPTIMIZE 0x04000000 /* C2 E D ) Synonyms */ -#define PCRE_NO_START_OPTIMISE 0x04000000 /* C2 E D ) */ -#define PCRE_PARTIAL_HARD 0x08000000 /* E D J */ -#define PCRE_NOTEMPTY_ATSTART 0x10000000 /* E D J */ -#define PCRE_UCP 0x20000000 /* C3 */ - -/* Exec-time and get/set-time error codes */ - -#define PCRE_ERROR_NOMATCH (-1) -#define PCRE_ERROR_NULL (-2) -#define PCRE_ERROR_BADOPTION (-3) -#define PCRE_ERROR_BADMAGIC (-4) -#define PCRE_ERROR_UNKNOWN_OPCODE (-5) -#define PCRE_ERROR_UNKNOWN_NODE (-5) /* For backward compatibility */ -#define PCRE_ERROR_NOMEMORY (-6) -#define PCRE_ERROR_NOSUBSTRING (-7) -#define PCRE_ERROR_MATCHLIMIT (-8) -#define PCRE_ERROR_CALLOUT (-9) /* Never used by PCRE itself */ -#define PCRE_ERROR_BADUTF8 (-10) /* Same for 8/16/32 */ -#define PCRE_ERROR_BADUTF16 (-10) /* Same for 8/16/32 */ -#define PCRE_ERROR_BADUTF32 (-10) /* Same for 8/16/32 */ -#define PCRE_ERROR_BADUTF8_OFFSET (-11) /* Same for 8/16 */ -#define PCRE_ERROR_BADUTF16_OFFSET (-11) /* Same for 8/16 */ -#define PCRE_ERROR_PARTIAL (-12) -#define PCRE_ERROR_BADPARTIAL (-13) -#define PCRE_ERROR_INTERNAL (-14) -#define PCRE_ERROR_BADCOUNT (-15) -#define PCRE_ERROR_DFA_UITEM (-16) -#define PCRE_ERROR_DFA_UCOND (-17) -#define PCRE_ERROR_DFA_UMLIMIT (-18) -#define PCRE_ERROR_DFA_WSSIZE (-19) -#define PCRE_ERROR_DFA_RECURSE (-20) -#define PCRE_ERROR_RECURSIONLIMIT (-21) -#define PCRE_ERROR_NULLWSLIMIT (-22) /* No longer actually used */ -#define PCRE_ERROR_BADNEWLINE (-23) -#define PCRE_ERROR_BADOFFSET (-24) -#define PCRE_ERROR_SHORTUTF8 (-25) -#define PCRE_ERROR_SHORTUTF16 (-25) /* Same for 8/16 */ -#define PCRE_ERROR_RECURSELOOP (-26) -#define PCRE_ERROR_JIT_STACKLIMIT (-27) -#define PCRE_ERROR_BADMODE (-28) -#define PCRE_ERROR_BADENDIANNESS (-29) -#define PCRE_ERROR_DFA_BADRESTART (-30) -#define PCRE_ERROR_JIT_BADOPTION (-31) -#define PCRE_ERROR_BADLENGTH (-32) -#define PCRE_ERROR_UNSET (-33) - -/* Specific error codes for UTF-8 validity checks */ - -#define PCRE_UTF8_ERR0 0 -#define PCRE_UTF8_ERR1 1 -#define PCRE_UTF8_ERR2 2 -#define PCRE_UTF8_ERR3 3 -#define PCRE_UTF8_ERR4 4 -#define PCRE_UTF8_ERR5 5 -#define PCRE_UTF8_ERR6 6 -#define PCRE_UTF8_ERR7 7 -#define PCRE_UTF8_ERR8 8 -#define PCRE_UTF8_ERR9 9 -#define PCRE_UTF8_ERR10 10 -#define PCRE_UTF8_ERR11 11 -#define PCRE_UTF8_ERR12 12 -#define PCRE_UTF8_ERR13 13 -#define PCRE_UTF8_ERR14 14 -#define PCRE_UTF8_ERR15 15 -#define PCRE_UTF8_ERR16 16 -#define PCRE_UTF8_ERR17 17 -#define PCRE_UTF8_ERR18 18 -#define PCRE_UTF8_ERR19 19 -#define PCRE_UTF8_ERR20 20 -#define PCRE_UTF8_ERR21 21 -#define PCRE_UTF8_ERR22 22 /* Unused (was non-character) */ - -/* Specific error codes for UTF-16 validity checks */ - -#define PCRE_UTF16_ERR0 0 -#define PCRE_UTF16_ERR1 1 -#define PCRE_UTF16_ERR2 2 -#define PCRE_UTF16_ERR3 3 -#define PCRE_UTF16_ERR4 4 /* Unused (was non-character) */ - -/* Specific error codes for UTF-32 validity checks */ - -#define PCRE_UTF32_ERR0 0 -#define PCRE_UTF32_ERR1 1 -#define PCRE_UTF32_ERR2 2 /* Unused (was non-character) */ -#define PCRE_UTF32_ERR3 3 - -/* Request types for pcre_fullinfo() */ - -#define PCRE_INFO_OPTIONS 0 -#define PCRE_INFO_SIZE 1 -#define PCRE_INFO_CAPTURECOUNT 2 -#define PCRE_INFO_BACKREFMAX 3 -#define PCRE_INFO_FIRSTBYTE 4 -#define PCRE_INFO_FIRSTCHAR 4 /* For backwards compatibility */ -#define PCRE_INFO_FIRSTTABLE 5 -#define PCRE_INFO_LASTLITERAL 6 -#define PCRE_INFO_NAMEENTRYSIZE 7 -#define PCRE_INFO_NAMECOUNT 8 -#define PCRE_INFO_NAMETABLE 9 -#define PCRE_INFO_STUDYSIZE 10 -#define PCRE_INFO_DEFAULT_TABLES 11 -#define PCRE_INFO_OKPARTIAL 12 -#define PCRE_INFO_JCHANGED 13 -#define PCRE_INFO_HASCRORLF 14 -#define PCRE_INFO_MINLENGTH 15 -#define PCRE_INFO_JIT 16 -#define PCRE_INFO_JITSIZE 17 -#define PCRE_INFO_MAXLOOKBEHIND 18 -#define PCRE_INFO_FIRSTCHARACTER 19 -#define PCRE_INFO_FIRSTCHARACTERFLAGS 20 -#define PCRE_INFO_REQUIREDCHAR 21 -#define PCRE_INFO_REQUIREDCHARFLAGS 22 -#define PCRE_INFO_MATCHLIMIT 23 -#define PCRE_INFO_RECURSIONLIMIT 24 -#define PCRE_INFO_MATCH_EMPTY 25 - -/* Request types for pcre_config(). Do not re-arrange, in order to remain -compatible. */ - -#define PCRE_CONFIG_UTF8 0 -#define PCRE_CONFIG_NEWLINE 1 -#define PCRE_CONFIG_LINK_SIZE 2 -#define PCRE_CONFIG_POSIX_MALLOC_THRESHOLD 3 -#define PCRE_CONFIG_MATCH_LIMIT 4 -#define PCRE_CONFIG_STACKRECURSE 5 -#define PCRE_CONFIG_UNICODE_PROPERTIES 6 -#define PCRE_CONFIG_MATCH_LIMIT_RECURSION 7 -#define PCRE_CONFIG_BSR 8 -#define PCRE_CONFIG_JIT 9 -#define PCRE_CONFIG_UTF16 10 -#define PCRE_CONFIG_JITTARGET 11 -#define PCRE_CONFIG_UTF32 12 -#define PCRE_CONFIG_PARENS_LIMIT 13 - -/* Request types for pcre_study(). Do not re-arrange, in order to remain -compatible. */ - -#define PCRE_STUDY_JIT_COMPILE 0x0001 -#define PCRE_STUDY_JIT_PARTIAL_SOFT_COMPILE 0x0002 -#define PCRE_STUDY_JIT_PARTIAL_HARD_COMPILE 0x0004 -#define PCRE_STUDY_EXTRA_NEEDED 0x0008 - -/* Bit flags for the pcre[16|32]_extra structure. Do not re-arrange or redefine -these bits, just add new ones on the end, in order to remain compatible. */ - -#define PCRE_EXTRA_STUDY_DATA 0x0001 -#define PCRE_EXTRA_MATCH_LIMIT 0x0002 -#define PCRE_EXTRA_CALLOUT_DATA 0x0004 -#define PCRE_EXTRA_TABLES 0x0008 -#define PCRE_EXTRA_MATCH_LIMIT_RECURSION 0x0010 -#define PCRE_EXTRA_MARK 0x0020 -#define PCRE_EXTRA_EXECUTABLE_JIT 0x0040 - -/* Types */ - -struct real_pcre; /* declaration; the definition is private */ -typedef struct real_pcre pcre; - -struct real_pcre16; /* declaration; the definition is private */ -typedef struct real_pcre16 pcre16; - -struct real_pcre32; /* declaration; the definition is private */ -typedef struct real_pcre32 pcre32; - -struct real_pcre_jit_stack; /* declaration; the definition is private */ -typedef struct real_pcre_jit_stack pcre_jit_stack; - -struct real_pcre16_jit_stack; /* declaration; the definition is private */ -typedef struct real_pcre16_jit_stack pcre16_jit_stack; - -struct real_pcre32_jit_stack; /* declaration; the definition is private */ -typedef struct real_pcre32_jit_stack pcre32_jit_stack; - -/* If PCRE is compiled with 16 bit character support, PCRE_UCHAR16 must contain -a 16 bit wide signed data type. Otherwise it can be a dummy data type since -pcre16 functions are not implemented. There is a check for this in pcre_internal.h. */ -typedef unsigned short PCRE_UCHAR16; -typedef const PCRE_UCHAR16 *PCRE_SPTR16; - -/* If PCRE is compiled with 32 bit character support, PCRE_UCHAR32 must contain -a 32 bit wide signed data type. Otherwise it can be a dummy data type since -pcre32 functions are not implemented. There is a check for this in pcre_internal.h. */ -typedef unsigned int PCRE_UCHAR32; -typedef const PCRE_UCHAR32 *PCRE_SPTR32; - -/* When PCRE is compiled as a C++ library, the subject pointer type can be -replaced with a custom type. For conventional use, the public interface is a -const char *. */ -typedef const char *PCRE_SPTR; - -/* The structure for passing additional data to pcre_exec(). This is defined in -such as way as to be extensible. Always add new fields at the end, in order to -remain compatible. */ - -typedef struct pcre_extra { - unsigned long int flags; /* Bits for which fields are set */ - void *study_data; /* Opaque data from pcre_study() */ - unsigned long int match_limit; /* Maximum number of calls to match() */ - void *callout_data; /* Data passed back in callouts */ - const unsigned char *tables; /* Pointer to character tables */ - unsigned long int match_limit_recursion; /* Max recursive calls to match() */ - unsigned char **mark; /* For passing back a mark pointer */ - void *executable_jit; /* Contains a pointer to a compiled jit code */ -} pcre_extra; - -/* Same structure as above, but with 16 bit char pointers. */ - -typedef struct pcre16_extra { - unsigned long int flags; /* Bits for which fields are set */ - void *study_data; /* Opaque data from pcre_study() */ - unsigned long int match_limit; /* Maximum number of calls to match() */ - void *callout_data; /* Data passed back in callouts */ - const unsigned char *tables; /* Pointer to character tables */ - unsigned long int match_limit_recursion; /* Max recursive calls to match() */ - PCRE_UCHAR16 **mark; /* For passing back a mark pointer */ - void *executable_jit; /* Contains a pointer to a compiled jit code */ -} pcre16_extra; - -/* Same structure as above, but with 32 bit char pointers. */ - -typedef struct pcre32_extra { - unsigned long int flags; /* Bits for which fields are set */ - void *study_data; /* Opaque data from pcre_study() */ - unsigned long int match_limit; /* Maximum number of calls to match() */ - void *callout_data; /* Data passed back in callouts */ - const unsigned char *tables; /* Pointer to character tables */ - unsigned long int match_limit_recursion; /* Max recursive calls to match() */ - PCRE_UCHAR32 **mark; /* For passing back a mark pointer */ - void *executable_jit; /* Contains a pointer to a compiled jit code */ -} pcre32_extra; - -/* The structure for passing out data via the pcre_callout_function. We use a -structure so that new fields can be added on the end in future versions, -without changing the API of the function, thereby allowing old clients to work -without modification. */ - -typedef struct pcre_callout_block { - int version; /* Identifies version of block */ - /* ------------------------ Version 0 ------------------------------- */ - int callout_number; /* Number compiled into pattern */ - int *offset_vector; /* The offset vector */ - PCRE_SPTR subject; /* The subject being matched */ - int subject_length; /* The length of the subject */ - int start_match; /* Offset to start of this match attempt */ - int current_position; /* Where we currently are in the subject */ - int capture_top; /* Max current capture */ - int capture_last; /* Most recently closed capture */ - void *callout_data; /* Data passed in with the call */ - /* ------------------- Added for Version 1 -------------------------- */ - int pattern_position; /* Offset to next item in the pattern */ - int next_item_length; /* Length of next item in the pattern */ - /* ------------------- Added for Version 2 -------------------------- */ - const unsigned char *mark; /* Pointer to current mark or NULL */ - /* ------------------------------------------------------------------ */ -} pcre_callout_block; - -/* Same structure as above, but with 16 bit char pointers. */ - -typedef struct pcre16_callout_block { - int version; /* Identifies version of block */ - /* ------------------------ Version 0 ------------------------------- */ - int callout_number; /* Number compiled into pattern */ - int *offset_vector; /* The offset vector */ - PCRE_SPTR16 subject; /* The subject being matched */ - int subject_length; /* The length of the subject */ - int start_match; /* Offset to start of this match attempt */ - int current_position; /* Where we currently are in the subject */ - int capture_top; /* Max current capture */ - int capture_last; /* Most recently closed capture */ - void *callout_data; /* Data passed in with the call */ - /* ------------------- Added for Version 1 -------------------------- */ - int pattern_position; /* Offset to next item in the pattern */ - int next_item_length; /* Length of next item in the pattern */ - /* ------------------- Added for Version 2 -------------------------- */ - const PCRE_UCHAR16 *mark; /* Pointer to current mark or NULL */ - /* ------------------------------------------------------------------ */ -} pcre16_callout_block; - -/* Same structure as above, but with 32 bit char pointers. */ - -typedef struct pcre32_callout_block { - int version; /* Identifies version of block */ - /* ------------------------ Version 0 ------------------------------- */ - int callout_number; /* Number compiled into pattern */ - int *offset_vector; /* The offset vector */ - PCRE_SPTR32 subject; /* The subject being matched */ - int subject_length; /* The length of the subject */ - int start_match; /* Offset to start of this match attempt */ - int current_position; /* Where we currently are in the subject */ - int capture_top; /* Max current capture */ - int capture_last; /* Most recently closed capture */ - void *callout_data; /* Data passed in with the call */ - /* ------------------- Added for Version 1 -------------------------- */ - int pattern_position; /* Offset to next item in the pattern */ - int next_item_length; /* Length of next item in the pattern */ - /* ------------------- Added for Version 2 -------------------------- */ - const PCRE_UCHAR32 *mark; /* Pointer to current mark or NULL */ - /* ------------------------------------------------------------------ */ -} pcre32_callout_block; - -/* Indirection for store get and free functions. These can be set to -alternative malloc/free functions if required. Special ones are used in the -non-recursive case for "frames". There is also an optional callout function -that is triggered by the (?) regex item. For Virtual Pascal, these definitions -have to take another form. */ - -#ifndef VPCOMPAT -PCRE_EXP_DECL void *(*pcre_malloc)(size_t); -PCRE_EXP_DECL void (*pcre_free)(void *); -PCRE_EXP_DECL void *(*pcre_stack_malloc)(size_t); -PCRE_EXP_DECL void (*pcre_stack_free)(void *); -PCRE_EXP_DECL int (*pcre_callout)(pcre_callout_block *); -PCRE_EXP_DECL int (*pcre_stack_guard)(void); - -PCRE_EXP_DECL void *(*pcre16_malloc)(size_t); -PCRE_EXP_DECL void (*pcre16_free)(void *); -PCRE_EXP_DECL void *(*pcre16_stack_malloc)(size_t); -PCRE_EXP_DECL void (*pcre16_stack_free)(void *); -PCRE_EXP_DECL int (*pcre16_callout)(pcre16_callout_block *); -PCRE_EXP_DECL int (*pcre16_stack_guard)(void); - -PCRE_EXP_DECL void *(*pcre32_malloc)(size_t); -PCRE_EXP_DECL void (*pcre32_free)(void *); -PCRE_EXP_DECL void *(*pcre32_stack_malloc)(size_t); -PCRE_EXP_DECL void (*pcre32_stack_free)(void *); -PCRE_EXP_DECL int (*pcre32_callout)(pcre32_callout_block *); -PCRE_EXP_DECL int (*pcre32_stack_guard)(void); -#else /* VPCOMPAT */ -PCRE_EXP_DECL void *pcre_malloc(size_t); -PCRE_EXP_DECL void pcre_free(void *); -PCRE_EXP_DECL void *pcre_stack_malloc(size_t); -PCRE_EXP_DECL void pcre_stack_free(void *); -PCRE_EXP_DECL int pcre_callout(pcre_callout_block *); -PCRE_EXP_DECL int pcre_stack_guard(void); - -PCRE_EXP_DECL void *pcre16_malloc(size_t); -PCRE_EXP_DECL void pcre16_free(void *); -PCRE_EXP_DECL void *pcre16_stack_malloc(size_t); -PCRE_EXP_DECL void pcre16_stack_free(void *); -PCRE_EXP_DECL int pcre16_callout(pcre16_callout_block *); -PCRE_EXP_DECL int pcre16_stack_guard(void); - -PCRE_EXP_DECL void *pcre32_malloc(size_t); -PCRE_EXP_DECL void pcre32_free(void *); -PCRE_EXP_DECL void *pcre32_stack_malloc(size_t); -PCRE_EXP_DECL void pcre32_stack_free(void *); -PCRE_EXP_DECL int pcre32_callout(pcre32_callout_block *); -PCRE_EXP_DECL int pcre32_stack_guard(void); -#endif /* VPCOMPAT */ - -/* User defined callback which provides a stack just before the match starts. */ - -typedef pcre_jit_stack *(*pcre_jit_callback)(void *); -typedef pcre16_jit_stack *(*pcre16_jit_callback)(void *); -typedef pcre32_jit_stack *(*pcre32_jit_callback)(void *); - -/* Exported PCRE functions */ - -PCRE_EXP_DECL pcre *pcre_compile(const char *, int, const char **, int *, - const unsigned char *); -PCRE_EXP_DECL pcre16 *pcre16_compile(PCRE_SPTR16, int, const char **, int *, - const unsigned char *); -PCRE_EXP_DECL pcre32 *pcre32_compile(PCRE_SPTR32, int, const char **, int *, - const unsigned char *); -PCRE_EXP_DECL pcre *pcre_compile2(const char *, int, int *, const char **, - int *, const unsigned char *); -PCRE_EXP_DECL pcre16 *pcre16_compile2(PCRE_SPTR16, int, int *, const char **, - int *, const unsigned char *); -PCRE_EXP_DECL pcre32 *pcre32_compile2(PCRE_SPTR32, int, int *, const char **, - int *, const unsigned char *); -PCRE_EXP_DECL int pcre_config(int, void *); -PCRE_EXP_DECL int pcre16_config(int, void *); -PCRE_EXP_DECL int pcre32_config(int, void *); -PCRE_EXP_DECL int pcre_copy_named_substring(const pcre *, const char *, - int *, int, const char *, char *, int); -PCRE_EXP_DECL int pcre16_copy_named_substring(const pcre16 *, PCRE_SPTR16, - int *, int, PCRE_SPTR16, PCRE_UCHAR16 *, int); -PCRE_EXP_DECL int pcre32_copy_named_substring(const pcre32 *, PCRE_SPTR32, - int *, int, PCRE_SPTR32, PCRE_UCHAR32 *, int); -PCRE_EXP_DECL int pcre_copy_substring(const char *, int *, int, int, - char *, int); -PCRE_EXP_DECL int pcre16_copy_substring(PCRE_SPTR16, int *, int, int, - PCRE_UCHAR16 *, int); -PCRE_EXP_DECL int pcre32_copy_substring(PCRE_SPTR32, int *, int, int, - PCRE_UCHAR32 *, int); -PCRE_EXP_DECL int pcre_dfa_exec(const pcre *, const pcre_extra *, - const char *, int, int, int, int *, int , int *, int); -PCRE_EXP_DECL int pcre16_dfa_exec(const pcre16 *, const pcre16_extra *, - PCRE_SPTR16, int, int, int, int *, int , int *, int); -PCRE_EXP_DECL int pcre32_dfa_exec(const pcre32 *, const pcre32_extra *, - PCRE_SPTR32, int, int, int, int *, int , int *, int); -PCRE_EXP_DECL int pcre_exec(const pcre *, const pcre_extra *, PCRE_SPTR, - int, int, int, int *, int); -PCRE_EXP_DECL int pcre16_exec(const pcre16 *, const pcre16_extra *, - PCRE_SPTR16, int, int, int, int *, int); -PCRE_EXP_DECL int pcre32_exec(const pcre32 *, const pcre32_extra *, - PCRE_SPTR32, int, int, int, int *, int); -PCRE_EXP_DECL int pcre_jit_exec(const pcre *, const pcre_extra *, - PCRE_SPTR, int, int, int, int *, int, - pcre_jit_stack *); -PCRE_EXP_DECL int pcre16_jit_exec(const pcre16 *, const pcre16_extra *, - PCRE_SPTR16, int, int, int, int *, int, - pcre16_jit_stack *); -PCRE_EXP_DECL int pcre32_jit_exec(const pcre32 *, const pcre32_extra *, - PCRE_SPTR32, int, int, int, int *, int, - pcre32_jit_stack *); -PCRE_EXP_DECL void pcre_free_substring(const char *); -PCRE_EXP_DECL void pcre16_free_substring(PCRE_SPTR16); -PCRE_EXP_DECL void pcre32_free_substring(PCRE_SPTR32); -PCRE_EXP_DECL void pcre_free_substring_list(const char **); -PCRE_EXP_DECL void pcre16_free_substring_list(PCRE_SPTR16 *); -PCRE_EXP_DECL void pcre32_free_substring_list(PCRE_SPTR32 *); -PCRE_EXP_DECL int pcre_fullinfo(const pcre *, const pcre_extra *, int, - void *); -PCRE_EXP_DECL int pcre16_fullinfo(const pcre16 *, const pcre16_extra *, int, - void *); -PCRE_EXP_DECL int pcre32_fullinfo(const pcre32 *, const pcre32_extra *, int, - void *); -PCRE_EXP_DECL int pcre_get_named_substring(const pcre *, const char *, - int *, int, const char *, const char **); -PCRE_EXP_DECL int pcre16_get_named_substring(const pcre16 *, PCRE_SPTR16, - int *, int, PCRE_SPTR16, PCRE_SPTR16 *); -PCRE_EXP_DECL int pcre32_get_named_substring(const pcre32 *, PCRE_SPTR32, - int *, int, PCRE_SPTR32, PCRE_SPTR32 *); -PCRE_EXP_DECL int pcre_get_stringnumber(const pcre *, const char *); -PCRE_EXP_DECL int pcre16_get_stringnumber(const pcre16 *, PCRE_SPTR16); -PCRE_EXP_DECL int pcre32_get_stringnumber(const pcre32 *, PCRE_SPTR32); -PCRE_EXP_DECL int pcre_get_stringtable_entries(const pcre *, const char *, - char **, char **); -PCRE_EXP_DECL int pcre16_get_stringtable_entries(const pcre16 *, PCRE_SPTR16, - PCRE_UCHAR16 **, PCRE_UCHAR16 **); -PCRE_EXP_DECL int pcre32_get_stringtable_entries(const pcre32 *, PCRE_SPTR32, - PCRE_UCHAR32 **, PCRE_UCHAR32 **); -PCRE_EXP_DECL int pcre_get_substring(const char *, int *, int, int, - const char **); -PCRE_EXP_DECL int pcre16_get_substring(PCRE_SPTR16, int *, int, int, - PCRE_SPTR16 *); -PCRE_EXP_DECL int pcre32_get_substring(PCRE_SPTR32, int *, int, int, - PCRE_SPTR32 *); -PCRE_EXP_DECL int pcre_get_substring_list(const char *, int *, int, - const char ***); -PCRE_EXP_DECL int pcre16_get_substring_list(PCRE_SPTR16, int *, int, - PCRE_SPTR16 **); -PCRE_EXP_DECL int pcre32_get_substring_list(PCRE_SPTR32, int *, int, - PCRE_SPTR32 **); -PCRE_EXP_DECL const unsigned char *pcre_maketables(void); -PCRE_EXP_DECL const unsigned char *pcre16_maketables(void); -PCRE_EXP_DECL const unsigned char *pcre32_maketables(void); -PCRE_EXP_DECL int pcre_refcount(pcre *, int); -PCRE_EXP_DECL int pcre16_refcount(pcre16 *, int); -PCRE_EXP_DECL int pcre32_refcount(pcre32 *, int); -PCRE_EXP_DECL pcre_extra *pcre_study(const pcre *, int, const char **); -PCRE_EXP_DECL pcre16_extra *pcre16_study(const pcre16 *, int, const char **); -PCRE_EXP_DECL pcre32_extra *pcre32_study(const pcre32 *, int, const char **); -PCRE_EXP_DECL void pcre_free_study(pcre_extra *); -PCRE_EXP_DECL void pcre16_free_study(pcre16_extra *); -PCRE_EXP_DECL void pcre32_free_study(pcre32_extra *); -PCRE_EXP_DECL const char *pcre_version(void); -PCRE_EXP_DECL const char *pcre16_version(void); -PCRE_EXP_DECL const char *pcre32_version(void); - -/* Utility functions for byte order swaps. */ -PCRE_EXP_DECL int pcre_pattern_to_host_byte_order(pcre *, pcre_extra *, - const unsigned char *); -PCRE_EXP_DECL int pcre16_pattern_to_host_byte_order(pcre16 *, pcre16_extra *, - const unsigned char *); -PCRE_EXP_DECL int pcre32_pattern_to_host_byte_order(pcre32 *, pcre32_extra *, - const unsigned char *); -PCRE_EXP_DECL int pcre16_utf16_to_host_byte_order(PCRE_UCHAR16 *, - PCRE_SPTR16, int, int *, int); -PCRE_EXP_DECL int pcre32_utf32_to_host_byte_order(PCRE_UCHAR32 *, - PCRE_SPTR32, int, int *, int); - -/* JIT compiler related functions. */ - -PCRE_EXP_DECL pcre_jit_stack *pcre_jit_stack_alloc(int, int); -PCRE_EXP_DECL pcre16_jit_stack *pcre16_jit_stack_alloc(int, int); -PCRE_EXP_DECL pcre32_jit_stack *pcre32_jit_stack_alloc(int, int); -PCRE_EXP_DECL void pcre_jit_stack_free(pcre_jit_stack *); -PCRE_EXP_DECL void pcre16_jit_stack_free(pcre16_jit_stack *); -PCRE_EXP_DECL void pcre32_jit_stack_free(pcre32_jit_stack *); -PCRE_EXP_DECL void pcre_assign_jit_stack(pcre_extra *, - pcre_jit_callback, void *); -PCRE_EXP_DECL void pcre16_assign_jit_stack(pcre16_extra *, - pcre16_jit_callback, void *); -PCRE_EXP_DECL void pcre32_assign_jit_stack(pcre32_extra *, - pcre32_jit_callback, void *); -PCRE_EXP_DECL void pcre_jit_free_unused_memory(void); -PCRE_EXP_DECL void pcre16_jit_free_unused_memory(void); -PCRE_EXP_DECL void pcre32_jit_free_unused_memory(void); diff --git a/lib/impure/nre/private/pcre.nim b/lib/impure/nre/private/pcre.nim index 744721d6f..83b0d5f79 100644 --- a/lib/impure/nre/private/pcre.nim +++ b/lib/impure/nre/private/pcre.nim @@ -1,42 +1,15 @@ -when not defined(pcreStaticlib): - const pcreHeader = "" - when not defined(pcreDll): - when hostOS == "windows": - const pcreDll = "pcre.dll" - elif hostOS == "macosx": - const pcreDll = "libpcre(.3|.1|).dylib" - else: - const pcreDll = "libpcre.so(.3|.1|)" - {.pragma: pcreImport, dynlib: pcreDll.} +const pcreHeader = "" +when not defined(pcreDll): + when hostOS == "windows": + const pcreDll = "pcre.dll" + elif hostOS == "macosx": + const pcreDll = "libpcre(.3|.1|).dylib" else: - {.pragma: pcreImport, header: pcreHeader.} - {.deadCodeElim: on.} # Don't error unless unsupported features are used + const pcreDll = "libpcre.so(.3|.1|)" + {.pragma: pcreImport, dynlib: pcreDll.} else: - {. passC: "-DHAVE_CONFIG_H", passC: "-I private/pcre_src", - passL: "-I private/pcre_src" .} - {. compile: "private/pcre_src/pcre_byte_order.c" .} - {. compile: "private/pcre_src/pcre_compile.c" .} - {. compile: "private/pcre_src/pcre_config.c" .} - {. compile: "private/pcre_src/pcre_dfa_exec.c" .} - {. compile: "private/pcre_src/pcre_exec.c" .} - {. compile: "private/pcre_src/pcre_fullinfo.c" .} - {. compile: "private/pcre_src/pcre_get.c" .} - {. compile: "private/pcre_src/pcre_globals.c" .} - {. compile: "private/pcre_src/pcre_jit_compile.c" .} - {. compile: "private/pcre_src/pcre_maketables.c" .} - {. compile: "private/pcre_src/pcre_newline.c" .} - {. compile: "private/pcre_src/pcre_ord2utf8.c" .} - {. compile: "private/pcre_src/pcre_refcount.c" .} - {. compile: "private/pcre_src/pcre_string_utils.c" .} - {. compile: "private/pcre_src/pcre_study.c" .} - {. compile: "private/pcre_src/pcre_tables.c" .} - {. compile: "private/pcre_src/pcre_ucd.c" .} - {. compile: "private/pcre_src/pcre_valid_utf8.c" .} - {. compile: "private/pcre_src/pcre_version.c" .} - {. compile: "private/pcre_src/pcre_xclass.c" .} - {. compile: "private/pcre_src/pcre_chartables.c" .} - - {.pragma: pcreImport.} + {.pragma: pcreImport, header: pcreHeader.} +{.deadCodeElim: on.} # Don't error unless unsupported features are used #************************************************ # Perl-Compatible Regular Expressions * diff --git a/lib/impure/nre/private/pcre_src/config.h b/lib/impure/nre/private/pcre_src/config.h deleted file mode 100644 index 55c8a27c2..000000000 --- a/lib/impure/nre/private/pcre_src/config.h +++ /dev/null @@ -1,349 +0,0 @@ -/* config.h. Generated from config.h.in by configure. */ -/* config.h.in. Generated from configure.ac by autoheader. */ - - -/* PCRE is written in Standard C, but there are a few non-standard things it -can cope with, allowing it to run on SunOS4 and other "close to standard" -systems. - -In environments that support the GNU autotools, config.h.in is converted into -config.h by the "configure" script. In environments that use CMake, -config-cmake.in is converted into config.h. If you are going to build PCRE "by -hand" without using "configure" or CMake, you should copy the distributed -config.h.generic to config.h, and edit the macro definitions to be the way you -need them. You must then add -DHAVE_CONFIG_H to all of your compile commands, -so that config.h is included at the start of every source. - -Alternatively, you can avoid editing by using -D on the compiler command line -to set the macro values. In this case, you do not have to set -DHAVE_CONFIG_H, -but if you do, default values will be taken from config.h for non-boolean -macros that are not defined on the command line. - -Boolean macros such as HAVE_STDLIB_H and SUPPORT_PCRE8 should either be defined -(conventionally to 1) for TRUE, and not defined at all for FALSE. All such -macros are listed as a commented #undef in config.h.generic. Macros such as -MATCH_LIMIT, whose actual value is relevant, have defaults defined, but are -surrounded by #ifndef/#endif lines so that the value can be overridden by -D. - -PCRE uses memmove() if HAVE_MEMMOVE is defined; otherwise it uses bcopy() if -HAVE_BCOPY is defined. If your system has neither bcopy() nor memmove(), make -sure both macros are undefined; an emulation function will then be used. */ - -/* By default, the \R escape sequence matches any Unicode line ending - character or sequence of characters. If BSR_ANYCRLF is defined (to any - value), this is changed so that backslash-R matches only CR, LF, or CRLF. - The build-time default can be overridden by the user of PCRE at runtime. */ -/* #undef BSR_ANYCRLF */ - -/* If you are compiling for a system that uses EBCDIC instead of ASCII - character codes, define this macro to any value. You must also edit the - NEWLINE macro below to set a suitable EBCDIC newline, commonly 21 (0x15). - On systems that can use "configure" or CMake to set EBCDIC, NEWLINE is - automatically adjusted. When EBCDIC is set, PCRE assumes that all input - strings are in EBCDIC. If you do not define this macro, PCRE will assume - input strings are ASCII or UTF-8/16/32 Unicode. It is not possible to build - a version of PCRE that supports both EBCDIC and UTF-8/16/32. */ -/* #undef EBCDIC */ - -/* In an EBCDIC environment, define this macro to any value to arrange for the - NL character to be 0x25 instead of the default 0x15. NL plays the role that - LF does in an ASCII/Unicode environment. The value must also be set in the - NEWLINE macro below. On systems that can use "configure" or CMake to set - EBCDIC_NL25, the adjustment of NEWLINE is automatic. */ -/* #undef EBCDIC_NL25 */ - -/* Define to 1 if you have the `bcopy' function. */ -#define HAVE_BCOPY 1 - -/* Define to 1 if you have the header file. */ -/* #undef HAVE_BITS_TYPE_TRAITS_H */ - -/* Define to 1 if you have the header file. */ -#define HAVE_BZLIB_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_DIRENT_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_DLFCN_H 1 - -/* Define to 1 if you have the header file. */ -/* #undef HAVE_EDITLINE_READLINE_H */ - -/* Define to 1 if you have the header file. */ -/* #undef HAVE_EDIT_READLINE_READLINE_H */ - -/* Define to 1 if you have the header file. */ -#define HAVE_INTTYPES_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_LIMITS_H 1 - -/* Define to 1 if the system has the type `long long'. */ -/* #undef HAVE_LONG_LONG */ - -/* Define to 1 if you have the `memmove' function. */ -#define HAVE_MEMMOVE 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_MEMORY_H 1 - -/* Define if you have POSIX threads libraries and header files. */ -/* #undef HAVE_PTHREAD */ - -/* Have PTHREAD_PRIO_INHERIT. */ -/* #undef HAVE_PTHREAD_PRIO_INHERIT */ - -/* Define to 1 if you have the header file. */ -/* #undef HAVE_READLINE_HISTORY_H */ - -/* Define to 1 if you have the header file. */ -/* #undef HAVE_READLINE_READLINE_H */ - -/* Define to 1 if you have the header file. */ -#define HAVE_STDINT_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_STDLIB_H 1 - -/* Define to 1 if you have the `strerror' function. */ -#define HAVE_STRERROR 1 - -/* Define to 1 if you have the header file. */ -/* #undef HAVE_STRING */ - -/* Define to 1 if you have the header file. */ -#define HAVE_STRINGS_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_STRING_H 1 - -/* Define to 1 if you have `strtoimax'. */ -/* #undef HAVE_STRTOIMAX */ - -/* Define to 1 if you have `strtoll'. */ -/* #undef HAVE_STRTOLL */ - -/* Define to 1 if you have `strtoq'. */ -/* #undef HAVE_STRTOQ */ - -/* Define to 1 if you have the header file. */ -#define HAVE_SYS_STAT_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_SYS_TYPES_H 1 - -/* Define to 1 if you have the header file. */ -/* #undef HAVE_TYPE_TRAITS_H */ - -/* Define to 1 if you have the header file. */ -#define HAVE_UNISTD_H 1 - -/* Define to 1 if the system has the type `unsigned long long'. */ -/* #undef HAVE_UNSIGNED_LONG_LONG */ - -/* Define to 1 if the compiler supports simple visibility declarations. */ -#define HAVE_VISIBILITY 1 - -/* Define to 1 if you have the header file. */ -/* #undef HAVE_WINDOWS_H */ - -/* Define to 1 if you have the header file. */ -#define HAVE_ZLIB_H 1 - -/* Define to 1 if you have `_strtoi64'. */ -/* #undef HAVE__STRTOI64 */ - -/* The value of LINK_SIZE determines the number of bytes used to store links - as offsets within the compiled regex. The default is 2, which allows for - compiled patterns up to 64K long. This covers the vast majority of cases. - However, PCRE can also be compiled to use 3 or 4 bytes instead. This allows - for longer patterns in extreme cases. */ -#define LINK_SIZE 2 - -/* Define to the sub-directory in which libtool stores uninstalled libraries. - */ -#define LT_OBJDIR ".libs/" - -/* The value of MATCH_LIMIT determines the default number of times the - internal match() function can be called during a single execution of - pcre_exec(). There is a runtime interface for setting a different limit. - The limit exists in order to catch runaway regular expressions that take - for ever to determine that they do not match. The default is set very large - so that it does not accidentally catch legitimate cases. */ -#define MATCH_LIMIT 10000000 - -/* The above limit applies to all calls of match(), whether or not they - increase the recursion depth. In some environments it is desirable to limit - the depth of recursive calls of match() more strictly, in order to restrict - the maximum amount of stack (or heap, if NO_RECURSE is defined) that is - used. The value of MATCH_LIMIT_RECURSION applies only to recursive calls of - match(). To have any useful effect, it must be less than the value of - MATCH_LIMIT. The default is to use the same value as MATCH_LIMIT. There is - a runtime method for setting a different limit. */ -#define MATCH_LIMIT_RECURSION MATCH_LIMIT - -/* This limit is parameterized just in case anybody ever wants to change it. - Care must be taken if it is increased, because it guards against integer - overflow caused by enormously large patterns. */ -#define MAX_NAME_COUNT 10000 - -/* This limit is parameterized just in case anybody ever wants to change it. - Care must be taken if it is increased, because it guards against integer - overflow caused by enormously large patterns. */ -#define MAX_NAME_SIZE 32 - -/* The value of NEWLINE determines the default newline character sequence. - PCRE client programs can override this by selecting other values at run - time. In ASCII environments, the value can be 10 (LF), 13 (CR), or 3338 - (CRLF); in EBCDIC environments the value can be 21 or 37 (LF), 13 (CR), or - 3349 or 3365 (CRLF) because there are two alternative codepoints (0x15 and - 0x25) that are used as the NL line terminator that is equivalent to ASCII - LF. In both ASCII and EBCDIC environments the value can also be -1 (ANY), - or -2 (ANYCRLF). */ -#define NEWLINE -2 - -/* PCRE uses recursive function calls to handle backtracking while matching. - This can sometimes be a problem on systems that have stacks of limited - size. Define NO_RECURSE to any value to get a version that doesn't use - recursion in the match() function; instead it creates its own stack by - steam using pcre_recurse_malloc() to obtain memory from the heap. For more - detail, see the comments and other stuff just above the match() function. - */ -/* #undef NO_RECURSE */ - -/* Name of package */ -#define PACKAGE "pcre" - -/* Define to the address where bug reports for this package should be sent. */ -#define PACKAGE_BUGREPORT "" - -/* Define to the full name of this package. */ -#define PACKAGE_NAME "PCRE" - -/* Define to the full name and version of this package. */ -#define PACKAGE_STRING "PCRE 8.36" - -/* Define to the one symbol short name of this package. */ -#define PACKAGE_TARNAME "pcre" - -/* Define to the home page for this package. */ -#define PACKAGE_URL "" - -/* Define to the version of this package. */ -#define PACKAGE_VERSION "8.36" - -/* The value of PARENS_NEST_LIMIT specifies the maximum depth of nested - parentheses (of any kind) in a pattern. This limits the amount of system - stack that is used while compiling a pattern. */ -#define PARENS_NEST_LIMIT 250 - -/* to make a symbol visible */ -#define PCRECPP_EXP_DECL extern __attribute__ ((visibility ("default"))) - -/* to make a symbol visible */ -#define PCRECPP_EXP_DEFN __attribute__ ((visibility ("default"))) - -/* The value of PCREGREP_BUFSIZE determines the size of buffer used by - pcregrep to hold parts of the file it is searching. This is also the - minimum value. The actual amount of memory used by pcregrep is three times - this number, because it allows for the buffering of "before" and "after" - lines. */ -#define PCREGREP_BUFSIZE 20480 - -/* to make a symbol visible */ -#define PCREPOSIX_EXP_DECL extern __attribute__ ((visibility ("default"))) - -/* to make a symbol visible */ -#define PCREPOSIX_EXP_DEFN extern __attribute__ ((visibility ("default"))) - -/* to make a symbol visible */ -#define PCRE_EXP_DATA_DEFN __attribute__ ((visibility ("default"))) - -/* to make a symbol visible */ -#define PCRE_EXP_DECL extern __attribute__ ((visibility ("default"))) - - -/* If you are compiling for a system other than a Unix-like system or - Win32, and it needs some magic to be inserted before the definition - of a function that is exported by the library, define this macro to - contain the relevant magic. If you do not define this macro, a suitable - __declspec value is used for Windows systems; in other environments - "extern" is used for a C compiler and "extern C" for a C++ compiler. - This macro apears at the start of every exported function that is part - of the external API. It does not appear on functions that are "external" - in the C sense, but which are internal to the library. */ -#define PCRE_EXP_DEFN __attribute__ ((visibility ("default"))) - -/* Define to any value if linking statically (TODO: make nice with Libtool) */ -/* #undef PCRE_STATIC */ - -/* When calling PCRE via the POSIX interface, additional working storage is - required for holding the pointers to capturing substrings because PCRE - requires three integers per substring, whereas the POSIX interface provides - only two. If the number of expected substrings is small, the wrapper - function uses space on the stack, because this is faster than using - malloc() for each call. The threshold above which the stack is no longer - used is defined by POSIX_MALLOC_THRESHOLD. */ -#define POSIX_MALLOC_THRESHOLD 10 - -/* Define to necessary symbol if this constant uses a non-standard name on - your system. */ -/* #undef PTHREAD_CREATE_JOINABLE */ - -/* Define to 1 if you have the ANSI C header files. */ -#define STDC_HEADERS 1 - -/* Define to any value to enable support for Just-In-Time compiling. */ -/* #undef SUPPORT_JIT */ - -/* Define to any value to allow pcregrep to be linked with libbz2, so that it - is able to handle .bz2 files. */ -/* #undef SUPPORT_LIBBZ2 */ - -/* Define to any value to allow pcretest to be linked with libedit. */ -/* #undef SUPPORT_LIBEDIT */ - -/* Define to any value to allow pcretest to be linked with libreadline. */ -/* #undef SUPPORT_LIBREADLINE */ - -/* Define to any value to allow pcregrep to be linked with libz, so that it is - able to handle .gz files. */ -/* #undef SUPPORT_LIBZ */ - -/* Define to any value to enable the 16 bit PCRE library. */ -/* #undef SUPPORT_PCRE16 */ - -/* Define to any value to enable the 32 bit PCRE library. */ -/* #undef SUPPORT_PCRE32 */ - -/* Define to any value to enable the 8 bit PCRE library. */ -#define SUPPORT_PCRE8 /**/ - -/* Define to any value to enable JIT support in pcregrep. */ -/* #undef SUPPORT_PCREGREP_JIT */ - -/* Define to any value to enable support for Unicode properties. */ -#define SUPPORT_UCP - -/* Define to any value to enable support for the UTF-8/16/32 Unicode encoding. - This will work even in an EBCDIC environment, but it is incompatible with - the EBCDIC macro. That is, PCRE can support *either* EBCDIC code *or* - ASCII/UTF-8/16/32, but not both at once. */ -#define SUPPORT_UTF - -/* Define to any value for valgrind support to find invalid memory reads. */ -/* #undef SUPPORT_VALGRIND */ - -/* Version number of package */ -#define VERSION "8.36" - -/* Define to empty if `const' does not conform to ANSI C. */ -/* #undef const */ - -/* Define to the type of a signed integer type of width exactly 64 bits if - such a type exists and the standard includes do not define it. */ -/* #undef int64_t */ - -/* Define to `unsigned int' if does not define. */ -/* #undef size_t */ diff --git a/lib/impure/nre/private/pcre_src/pcre.h b/lib/impure/nre/private/pcre_src/pcre.h deleted file mode 100644 index 9216d55b0..000000000 --- a/lib/impure/nre/private/pcre_src/pcre.h +++ /dev/null @@ -1,677 +0,0 @@ -/************************************************* -* Perl-Compatible Regular Expressions * -*************************************************/ - -/* This is the public header file for the PCRE library, to be #included by -applications that call the PCRE functions. - - Copyright (c) 1997-2014 University of Cambridge - ------------------------------------------------------------------------------ -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - * Neither the name of the University of Cambridge nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ -*/ - -#ifndef _PCRE_H -#define _PCRE_H - -/* The current PCRE version information. */ - -#define PCRE_MAJOR 8 -#define PCRE_MINOR 36 -#define PCRE_PRERELEASE -#define PCRE_DATE 2014-09-26 - -/* When an application links to a PCRE DLL in Windows, the symbols that are -imported have to be identified as such. When building PCRE, the appropriate -export setting is defined in pcre_internal.h, which includes this file. So we -don't change existing definitions of PCRE_EXP_DECL and PCRECPP_EXP_DECL. */ - -#if defined(_WIN32) && !defined(PCRE_STATIC) -# ifndef PCRE_EXP_DECL -# define PCRE_EXP_DECL extern __declspec(dllimport) -# endif -# ifdef __cplusplus -# ifndef PCRECPP_EXP_DECL -# define PCRECPP_EXP_DECL extern __declspec(dllimport) -# endif -# ifndef PCRECPP_EXP_DEFN -# define PCRECPP_EXP_DEFN __declspec(dllimport) -# endif -# endif -#endif - -/* By default, we use the standard "extern" declarations. */ - -#ifndef PCRE_EXP_DECL -# ifdef __cplusplus -# define PCRE_EXP_DECL extern "C" -# else -# define PCRE_EXP_DECL extern -# endif -#endif - -#ifdef __cplusplus -# ifndef PCRECPP_EXP_DECL -# define PCRECPP_EXP_DECL extern -# endif -# ifndef PCRECPP_EXP_DEFN -# define PCRECPP_EXP_DEFN -# endif -#endif - -/* Have to include stdlib.h in order to ensure that size_t is defined; -it is needed here for malloc. */ - -#include - -/* Allow for C++ users */ - -#ifdef __cplusplus -extern "C" { -#endif - -/* Public options. Some are compile-time only, some are run-time only, and some -are both. Most of the compile-time options are saved with the compiled regex so -that they can be inspected during studying (and therefore JIT compiling). Note -that pcre_study() has its own set of options. Originally, all the options -defined here used distinct bits. However, almost all the bits in a 32-bit word -are now used, so in order to conserve them, option bits that were previously -only recognized at matching time (i.e. by pcre_exec() or pcre_dfa_exec()) may -also be used for compile-time options that affect only compiling and are not -relevant for studying or JIT compiling. - -Some options for pcre_compile() change its behaviour but do not affect the -behaviour of the execution functions. Other options are passed through to the -execution functions and affect their behaviour, with or without affecting the -behaviour of pcre_compile(). - -Options that can be passed to pcre_compile() are tagged Cx below, with these -variants: - -C1 Affects compile only -C2 Does not affect compile; affects exec, dfa_exec -C3 Affects compile, exec, dfa_exec -C4 Affects compile, exec, dfa_exec, study -C5 Affects compile, exec, study - -Options that can be set for pcre_exec() and/or pcre_dfa_exec() are flagged with -E and D, respectively. They take precedence over C3, C4, and C5 settings passed -from pcre_compile(). Those that are compatible with JIT execution are flagged -with J. */ - -#define PCRE_CASELESS 0x00000001 /* C1 */ -#define PCRE_MULTILINE 0x00000002 /* C1 */ -#define PCRE_DOTALL 0x00000004 /* C1 */ -#define PCRE_EXTENDED 0x00000008 /* C1 */ -#define PCRE_ANCHORED 0x00000010 /* C4 E D */ -#define PCRE_DOLLAR_ENDONLY 0x00000020 /* C2 */ -#define PCRE_EXTRA 0x00000040 /* C1 */ -#define PCRE_NOTBOL 0x00000080 /* E D J */ -#define PCRE_NOTEOL 0x00000100 /* E D J */ -#define PCRE_UNGREEDY 0x00000200 /* C1 */ -#define PCRE_NOTEMPTY 0x00000400 /* E D J */ -#define PCRE_UTF8 0x00000800 /* C4 ) */ -#define PCRE_UTF16 0x00000800 /* C4 ) Synonyms */ -#define PCRE_UTF32 0x00000800 /* C4 ) */ -#define PCRE_NO_AUTO_CAPTURE 0x00001000 /* C1 */ -#define PCRE_NO_UTF8_CHECK 0x00002000 /* C1 E D J ) */ -#define PCRE_NO_UTF16_CHECK 0x00002000 /* C1 E D J ) Synonyms */ -#define PCRE_NO_UTF32_CHECK 0x00002000 /* C1 E D J ) */ -#define PCRE_AUTO_CALLOUT 0x00004000 /* C1 */ -#define PCRE_PARTIAL_SOFT 0x00008000 /* E D J ) Synonyms */ -#define PCRE_PARTIAL 0x00008000 /* E D J ) */ - -/* This pair use the same bit. */ -#define PCRE_NEVER_UTF 0x00010000 /* C1 ) Overlaid */ -#define PCRE_DFA_SHORTEST 0x00010000 /* D ) Overlaid */ - -/* This pair use the same bit. */ -#define PCRE_NO_AUTO_POSSESS 0x00020000 /* C1 ) Overlaid */ -#define PCRE_DFA_RESTART 0x00020000 /* D ) Overlaid */ - -#define PCRE_FIRSTLINE 0x00040000 /* C3 */ -#define PCRE_DUPNAMES 0x00080000 /* C1 */ -#define PCRE_NEWLINE_CR 0x00100000 /* C3 E D */ -#define PCRE_NEWLINE_LF 0x00200000 /* C3 E D */ -#define PCRE_NEWLINE_CRLF 0x00300000 /* C3 E D */ -#define PCRE_NEWLINE_ANY 0x00400000 /* C3 E D */ -#define PCRE_NEWLINE_ANYCRLF 0x00500000 /* C3 E D */ -#define PCRE_BSR_ANYCRLF 0x00800000 /* C3 E D */ -#define PCRE_BSR_UNICODE 0x01000000 /* C3 E D */ -#define PCRE_JAVASCRIPT_COMPAT 0x02000000 /* C5 */ -#define PCRE_NO_START_OPTIMIZE 0x04000000 /* C2 E D ) Synonyms */ -#define PCRE_NO_START_OPTIMISE 0x04000000 /* C2 E D ) */ -#define PCRE_PARTIAL_HARD 0x08000000 /* E D J */ -#define PCRE_NOTEMPTY_ATSTART 0x10000000 /* E D J */ -#define PCRE_UCP 0x20000000 /* C3 */ - -/* Exec-time and get/set-time error codes */ - -#define PCRE_ERROR_NOMATCH (-1) -#define PCRE_ERROR_NULL (-2) -#define PCRE_ERROR_BADOPTION (-3) -#define PCRE_ERROR_BADMAGIC (-4) -#define PCRE_ERROR_UNKNOWN_OPCODE (-5) -#define PCRE_ERROR_UNKNOWN_NODE (-5) /* For backward compatibility */ -#define PCRE_ERROR_NOMEMORY (-6) -#define PCRE_ERROR_NOSUBSTRING (-7) -#define PCRE_ERROR_MATCHLIMIT (-8) -#define PCRE_ERROR_CALLOUT (-9) /* Never used by PCRE itself */ -#define PCRE_ERROR_BADUTF8 (-10) /* Same for 8/16/32 */ -#define PCRE_ERROR_BADUTF16 (-10) /* Same for 8/16/32 */ -#define PCRE_ERROR_BADUTF32 (-10) /* Same for 8/16/32 */ -#define PCRE_ERROR_BADUTF8_OFFSET (-11) /* Same for 8/16 */ -#define PCRE_ERROR_BADUTF16_OFFSET (-11) /* Same for 8/16 */ -#define PCRE_ERROR_PARTIAL (-12) -#define PCRE_ERROR_BADPARTIAL (-13) -#define PCRE_ERROR_INTERNAL (-14) -#define PCRE_ERROR_BADCOUNT (-15) -#define PCRE_ERROR_DFA_UITEM (-16) -#define PCRE_ERROR_DFA_UCOND (-17) -#define PCRE_ERROR_DFA_UMLIMIT (-18) -#define PCRE_ERROR_DFA_WSSIZE (-19) -#define PCRE_ERROR_DFA_RECURSE (-20) -#define PCRE_ERROR_RECURSIONLIMIT (-21) -#define PCRE_ERROR_NULLWSLIMIT (-22) /* No longer actually used */ -#define PCRE_ERROR_BADNEWLINE (-23) -#define PCRE_ERROR_BADOFFSET (-24) -#define PCRE_ERROR_SHORTUTF8 (-25) -#define PCRE_ERROR_SHORTUTF16 (-25) /* Same for 8/16 */ -#define PCRE_ERROR_RECURSELOOP (-26) -#define PCRE_ERROR_JIT_STACKLIMIT (-27) -#define PCRE_ERROR_BADMODE (-28) -#define PCRE_ERROR_BADENDIANNESS (-29) -#define PCRE_ERROR_DFA_BADRESTART (-30) -#define PCRE_ERROR_JIT_BADOPTION (-31) -#define PCRE_ERROR_BADLENGTH (-32) -#define PCRE_ERROR_UNSET (-33) - -/* Specific error codes for UTF-8 validity checks */ - -#define PCRE_UTF8_ERR0 0 -#define PCRE_UTF8_ERR1 1 -#define PCRE_UTF8_ERR2 2 -#define PCRE_UTF8_ERR3 3 -#define PCRE_UTF8_ERR4 4 -#define PCRE_UTF8_ERR5 5 -#define PCRE_UTF8_ERR6 6 -#define PCRE_UTF8_ERR7 7 -#define PCRE_UTF8_ERR8 8 -#define PCRE_UTF8_ERR9 9 -#define PCRE_UTF8_ERR10 10 -#define PCRE_UTF8_ERR11 11 -#define PCRE_UTF8_ERR12 12 -#define PCRE_UTF8_ERR13 13 -#define PCRE_UTF8_ERR14 14 -#define PCRE_UTF8_ERR15 15 -#define PCRE_UTF8_ERR16 16 -#define PCRE_UTF8_ERR17 17 -#define PCRE_UTF8_ERR18 18 -#define PCRE_UTF8_ERR19 19 -#define PCRE_UTF8_ERR20 20 -#define PCRE_UTF8_ERR21 21 -#define PCRE_UTF8_ERR22 22 /* Unused (was non-character) */ - -/* Specific error codes for UTF-16 validity checks */ - -#define PCRE_UTF16_ERR0 0 -#define PCRE_UTF16_ERR1 1 -#define PCRE_UTF16_ERR2 2 -#define PCRE_UTF16_ERR3 3 -#define PCRE_UTF16_ERR4 4 /* Unused (was non-character) */ - -/* Specific error codes for UTF-32 validity checks */ - -#define PCRE_UTF32_ERR0 0 -#define PCRE_UTF32_ERR1 1 -#define PCRE_UTF32_ERR2 2 /* Unused (was non-character) */ -#define PCRE_UTF32_ERR3 3 - -/* Request types for pcre_fullinfo() */ - -#define PCRE_INFO_OPTIONS 0 -#define PCRE_INFO_SIZE 1 -#define PCRE_INFO_CAPTURECOUNT 2 -#define PCRE_INFO_BACKREFMAX 3 -#define PCRE_INFO_FIRSTBYTE 4 -#define PCRE_INFO_FIRSTCHAR 4 /* For backwards compatibility */ -#define PCRE_INFO_FIRSTTABLE 5 -#define PCRE_INFO_LASTLITERAL 6 -#define PCRE_INFO_NAMEENTRYSIZE 7 -#define PCRE_INFO_NAMECOUNT 8 -#define PCRE_INFO_NAMETABLE 9 -#define PCRE_INFO_STUDYSIZE 10 -#define PCRE_INFO_DEFAULT_TABLES 11 -#define PCRE_INFO_OKPARTIAL 12 -#define PCRE_INFO_JCHANGED 13 -#define PCRE_INFO_HASCRORLF 14 -#define PCRE_INFO_MINLENGTH 15 -#define PCRE_INFO_JIT 16 -#define PCRE_INFO_JITSIZE 17 -#define PCRE_INFO_MAXLOOKBEHIND 18 -#define PCRE_INFO_FIRSTCHARACTER 19 -#define PCRE_INFO_FIRSTCHARACTERFLAGS 20 -#define PCRE_INFO_REQUIREDCHAR 21 -#define PCRE_INFO_REQUIREDCHARFLAGS 22 -#define PCRE_INFO_MATCHLIMIT 23 -#define PCRE_INFO_RECURSIONLIMIT 24 -#define PCRE_INFO_MATCH_EMPTY 25 - -/* Request types for pcre_config(). Do not re-arrange, in order to remain -compatible. */ - -#define PCRE_CONFIG_UTF8 0 -#define PCRE_CONFIG_NEWLINE 1 -#define PCRE_CONFIG_LINK_SIZE 2 -#define PCRE_CONFIG_POSIX_MALLOC_THRESHOLD 3 -#define PCRE_CONFIG_MATCH_LIMIT 4 -#define PCRE_CONFIG_STACKRECURSE 5 -#define PCRE_CONFIG_UNICODE_PROPERTIES 6 -#define PCRE_CONFIG_MATCH_LIMIT_RECURSION 7 -#define PCRE_CONFIG_BSR 8 -#define PCRE_CONFIG_JIT 9 -#define PCRE_CONFIG_UTF16 10 -#define PCRE_CONFIG_JITTARGET 11 -#define PCRE_CONFIG_UTF32 12 -#define PCRE_CONFIG_PARENS_LIMIT 13 - -/* Request types for pcre_study(). Do not re-arrange, in order to remain -compatible. */ - -#define PCRE_STUDY_JIT_COMPILE 0x0001 -#define PCRE_STUDY_JIT_PARTIAL_SOFT_COMPILE 0x0002 -#define PCRE_STUDY_JIT_PARTIAL_HARD_COMPILE 0x0004 -#define PCRE_STUDY_EXTRA_NEEDED 0x0008 - -/* Bit flags for the pcre[16|32]_extra structure. Do not re-arrange or redefine -these bits, just add new ones on the end, in order to remain compatible. */ - -#define PCRE_EXTRA_STUDY_DATA 0x0001 -#define PCRE_EXTRA_MATCH_LIMIT 0x0002 -#define PCRE_EXTRA_CALLOUT_DATA 0x0004 -#define PCRE_EXTRA_TABLES 0x0008 -#define PCRE_EXTRA_MATCH_LIMIT_RECURSION 0x0010 -#define PCRE_EXTRA_MARK 0x0020 -#define PCRE_EXTRA_EXECUTABLE_JIT 0x0040 - -/* Types */ - -struct real_pcre; /* declaration; the definition is private */ -typedef struct real_pcre pcre; - -struct real_pcre16; /* declaration; the definition is private */ -typedef struct real_pcre16 pcre16; - -struct real_pcre32; /* declaration; the definition is private */ -typedef struct real_pcre32 pcre32; - -struct real_pcre_jit_stack; /* declaration; the definition is private */ -typedef struct real_pcre_jit_stack pcre_jit_stack; - -struct real_pcre16_jit_stack; /* declaration; the definition is private */ -typedef struct real_pcre16_jit_stack pcre16_jit_stack; - -struct real_pcre32_jit_stack; /* declaration; the definition is private */ -typedef struct real_pcre32_jit_stack pcre32_jit_stack; - -/* If PCRE is compiled with 16 bit character support, PCRE_UCHAR16 must contain -a 16 bit wide signed data type. Otherwise it can be a dummy data type since -pcre16 functions are not implemented. There is a check for this in pcre_internal.h. */ -#ifndef PCRE_UCHAR16 -#define PCRE_UCHAR16 unsigned short -#endif - -#ifndef PCRE_SPTR16 -#define PCRE_SPTR16 const PCRE_UCHAR16 * -#endif - -/* If PCRE is compiled with 32 bit character support, PCRE_UCHAR32 must contain -a 32 bit wide signed data type. Otherwise it can be a dummy data type since -pcre32 functions are not implemented. There is a check for this in pcre_internal.h. */ -#ifndef PCRE_UCHAR32 -#define PCRE_UCHAR32 unsigned int -#endif - -#ifndef PCRE_SPTR32 -#define PCRE_SPTR32 const PCRE_UCHAR32 * -#endif - -/* When PCRE is compiled as a C++ library, the subject pointer type can be -replaced with a custom type. For conventional use, the public interface is a -const char *. */ - -#ifndef PCRE_SPTR -#define PCRE_SPTR const char * -#endif - -/* The structure for passing additional data to pcre_exec(). This is defined in -such as way as to be extensible. Always add new fields at the end, in order to -remain compatible. */ - -typedef struct pcre_extra { - unsigned long int flags; /* Bits for which fields are set */ - void *study_data; /* Opaque data from pcre_study() */ - unsigned long int match_limit; /* Maximum number of calls to match() */ - void *callout_data; /* Data passed back in callouts */ - const unsigned char *tables; /* Pointer to character tables */ - unsigned long int match_limit_recursion; /* Max recursive calls to match() */ - unsigned char **mark; /* For passing back a mark pointer */ - void *executable_jit; /* Contains a pointer to a compiled jit code */ -} pcre_extra; - -/* Same structure as above, but with 16 bit char pointers. */ - -typedef struct pcre16_extra { - unsigned long int flags; /* Bits for which fields are set */ - void *study_data; /* Opaque data from pcre_study() */ - unsigned long int match_limit; /* Maximum number of calls to match() */ - void *callout_data; /* Data passed back in callouts */ - const unsigned char *tables; /* Pointer to character tables */ - unsigned long int match_limit_recursion; /* Max recursive calls to match() */ - PCRE_UCHAR16 **mark; /* For passing back a mark pointer */ - void *executable_jit; /* Contains a pointer to a compiled jit code */ -} pcre16_extra; - -/* Same structure as above, but with 32 bit char pointers. */ - -typedef struct pcre32_extra { - unsigned long int flags; /* Bits for which fields are set */ - void *study_data; /* Opaque data from pcre_study() */ - unsigned long int match_limit; /* Maximum number of calls to match() */ - void *callout_data; /* Data passed back in callouts */ - const unsigned char *tables; /* Pointer to character tables */ - unsigned long int match_limit_recursion; /* Max recursive calls to match() */ - PCRE_UCHAR32 **mark; /* For passing back a mark pointer */ - void *executable_jit; /* Contains a pointer to a compiled jit code */ -} pcre32_extra; - -/* The structure for passing out data via the pcre_callout_function. We use a -structure so that new fields can be added on the end in future versions, -without changing the API of the function, thereby allowing old clients to work -without modification. */ - -typedef struct pcre_callout_block { - int version; /* Identifies version of block */ - /* ------------------------ Version 0 ------------------------------- */ - int callout_number; /* Number compiled into pattern */ - int *offset_vector; /* The offset vector */ - PCRE_SPTR subject; /* The subject being matched */ - int subject_length; /* The length of the subject */ - int start_match; /* Offset to start of this match attempt */ - int current_position; /* Where we currently are in the subject */ - int capture_top; /* Max current capture */ - int capture_last; /* Most recently closed capture */ - void *callout_data; /* Data passed in with the call */ - /* ------------------- Added for Version 1 -------------------------- */ - int pattern_position; /* Offset to next item in the pattern */ - int next_item_length; /* Length of next item in the pattern */ - /* ------------------- Added for Version 2 -------------------------- */ - const unsigned char *mark; /* Pointer to current mark or NULL */ - /* ------------------------------------------------------------------ */ -} pcre_callout_block; - -/* Same structure as above, but with 16 bit char pointers. */ - -typedef struct pcre16_callout_block { - int version; /* Identifies version of block */ - /* ------------------------ Version 0 ------------------------------- */ - int callout_number; /* Number compiled into pattern */ - int *offset_vector; /* The offset vector */ - PCRE_SPTR16 subject; /* The subject being matched */ - int subject_length; /* The length of the subject */ - int start_match; /* Offset to start of this match attempt */ - int current_position; /* Where we currently are in the subject */ - int capture_top; /* Max current capture */ - int capture_last; /* Most recently closed capture */ - void *callout_data; /* Data passed in with the call */ - /* ------------------- Added for Version 1 -------------------------- */ - int pattern_position; /* Offset to next item in the pattern */ - int next_item_length; /* Length of next item in the pattern */ - /* ------------------- Added for Version 2 -------------------------- */ - const PCRE_UCHAR16 *mark; /* Pointer to current mark or NULL */ - /* ------------------------------------------------------------------ */ -} pcre16_callout_block; - -/* Same structure as above, but with 32 bit char pointers. */ - -typedef struct pcre32_callout_block { - int version; /* Identifies version of block */ - /* ------------------------ Version 0 ------------------------------- */ - int callout_number; /* Number compiled into pattern */ - int *offset_vector; /* The offset vector */ - PCRE_SPTR32 subject; /* The subject being matched */ - int subject_length; /* The length of the subject */ - int start_match; /* Offset to start of this match attempt */ - int current_position; /* Where we currently are in the subject */ - int capture_top; /* Max current capture */ - int capture_last; /* Most recently closed capture */ - void *callout_data; /* Data passed in with the call */ - /* ------------------- Added for Version 1 -------------------------- */ - int pattern_position; /* Offset to next item in the pattern */ - int next_item_length; /* Length of next item in the pattern */ - /* ------------------- Added for Version 2 -------------------------- */ - const PCRE_UCHAR32 *mark; /* Pointer to current mark or NULL */ - /* ------------------------------------------------------------------ */ -} pcre32_callout_block; - -/* Indirection for store get and free functions. These can be set to -alternative malloc/free functions if required. Special ones are used in the -non-recursive case for "frames". There is also an optional callout function -that is triggered by the (?) regex item. For Virtual Pascal, these definitions -have to take another form. */ - -#ifndef VPCOMPAT -PCRE_EXP_DECL void *(*pcre_malloc)(size_t); -PCRE_EXP_DECL void (*pcre_free)(void *); -PCRE_EXP_DECL void *(*pcre_stack_malloc)(size_t); -PCRE_EXP_DECL void (*pcre_stack_free)(void *); -PCRE_EXP_DECL int (*pcre_callout)(pcre_callout_block *); -PCRE_EXP_DECL int (*pcre_stack_guard)(void); - -PCRE_EXP_DECL void *(*pcre16_malloc)(size_t); -PCRE_EXP_DECL void (*pcre16_free)(void *); -PCRE_EXP_DECL void *(*pcre16_stack_malloc)(size_t); -PCRE_EXP_DECL void (*pcre16_stack_free)(void *); -PCRE_EXP_DECL int (*pcre16_callout)(pcre16_callout_block *); -PCRE_EXP_DECL int (*pcre16_stack_guard)(void); - -PCRE_EXP_DECL void *(*pcre32_malloc)(size_t); -PCRE_EXP_DECL void (*pcre32_free)(void *); -PCRE_EXP_DECL void *(*pcre32_stack_malloc)(size_t); -PCRE_EXP_DECL void (*pcre32_stack_free)(void *); -PCRE_EXP_DECL int (*pcre32_callout)(pcre32_callout_block *); -PCRE_EXP_DECL int (*pcre32_stack_guard)(void); -#else /* VPCOMPAT */ -PCRE_EXP_DECL void *pcre_malloc(size_t); -PCRE_EXP_DECL void pcre_free(void *); -PCRE_EXP_DECL void *pcre_stack_malloc(size_t); -PCRE_EXP_DECL void pcre_stack_free(void *); -PCRE_EXP_DECL int pcre_callout(pcre_callout_block *); -PCRE_EXP_DECL int pcre_stack_guard(void); - -PCRE_EXP_DECL void *pcre16_malloc(size_t); -PCRE_EXP_DECL void pcre16_free(void *); -PCRE_EXP_DECL void *pcre16_stack_malloc(size_t); -PCRE_EXP_DECL void pcre16_stack_free(void *); -PCRE_EXP_DECL int pcre16_callout(pcre16_callout_block *); -PCRE_EXP_DECL int pcre16_stack_guard(void); - -PCRE_EXP_DECL void *pcre32_malloc(size_t); -PCRE_EXP_DECL void pcre32_free(void *); -PCRE_EXP_DECL void *pcre32_stack_malloc(size_t); -PCRE_EXP_DECL void pcre32_stack_free(void *); -PCRE_EXP_DECL int pcre32_callout(pcre32_callout_block *); -PCRE_EXP_DECL int pcre32_stack_guard(void); -#endif /* VPCOMPAT */ - -/* User defined callback which provides a stack just before the match starts. */ - -typedef pcre_jit_stack *(*pcre_jit_callback)(void *); -typedef pcre16_jit_stack *(*pcre16_jit_callback)(void *); -typedef pcre32_jit_stack *(*pcre32_jit_callback)(void *); - -/* Exported PCRE functions */ - -PCRE_EXP_DECL pcre *pcre_compile(const char *, int, const char **, int *, - const unsigned char *); -PCRE_EXP_DECL pcre16 *pcre16_compile(PCRE_SPTR16, int, const char **, int *, - const unsigned char *); -PCRE_EXP_DECL pcre32 *pcre32_compile(PCRE_SPTR32, int, const char **, int *, - const unsigned char *); -PCRE_EXP_DECL pcre *pcre_compile2(const char *, int, int *, const char **, - int *, const unsigned char *); -PCRE_EXP_DECL pcre16 *pcre16_compile2(PCRE_SPTR16, int, int *, const char **, - int *, const unsigned char *); -PCRE_EXP_DECL pcre32 *pcre32_compile2(PCRE_SPTR32, int, int *, const char **, - int *, const unsigned char *); -PCRE_EXP_DECL int pcre_config(int, void *); -PCRE_EXP_DECL int pcre16_config(int, void *); -PCRE_EXP_DECL int pcre32_config(int, void *); -PCRE_EXP_DECL int pcre_copy_named_substring(const pcre *, const char *, - int *, int, const char *, char *, int); -PCRE_EXP_DECL int pcre16_copy_named_substring(const pcre16 *, PCRE_SPTR16, - int *, int, PCRE_SPTR16, PCRE_UCHAR16 *, int); -PCRE_EXP_DECL int pcre32_copy_named_substring(const pcre32 *, PCRE_SPTR32, - int *, int, PCRE_SPTR32, PCRE_UCHAR32 *, int); -PCRE_EXP_DECL int pcre_copy_substring(const char *, int *, int, int, - char *, int); -PCRE_EXP_DECL int pcre16_copy_substring(PCRE_SPTR16, int *, int, int, - PCRE_UCHAR16 *, int); -PCRE_EXP_DECL int pcre32_copy_substring(PCRE_SPTR32, int *, int, int, - PCRE_UCHAR32 *, int); -PCRE_EXP_DECL int pcre_dfa_exec(const pcre *, const pcre_extra *, - const char *, int, int, int, int *, int , int *, int); -PCRE_EXP_DECL int pcre16_dfa_exec(const pcre16 *, const pcre16_extra *, - PCRE_SPTR16, int, int, int, int *, int , int *, int); -PCRE_EXP_DECL int pcre32_dfa_exec(const pcre32 *, const pcre32_extra *, - PCRE_SPTR32, int, int, int, int *, int , int *, int); -PCRE_EXP_DECL int pcre_exec(const pcre *, const pcre_extra *, PCRE_SPTR, - int, int, int, int *, int); -PCRE_EXP_DECL int pcre16_exec(const pcre16 *, const pcre16_extra *, - PCRE_SPTR16, int, int, int, int *, int); -PCRE_EXP_DECL int pcre32_exec(const pcre32 *, const pcre32_extra *, - PCRE_SPTR32, int, int, int, int *, int); -PCRE_EXP_DECL int pcre_jit_exec(const pcre *, const pcre_extra *, - PCRE_SPTR, int, int, int, int *, int, - pcre_jit_stack *); -PCRE_EXP_DECL int pcre16_jit_exec(const pcre16 *, const pcre16_extra *, - PCRE_SPTR16, int, int, int, int *, int, - pcre16_jit_stack *); -PCRE_EXP_DECL int pcre32_jit_exec(const pcre32 *, const pcre32_extra *, - PCRE_SPTR32, int, int, int, int *, int, - pcre32_jit_stack *); -PCRE_EXP_DECL void pcre_free_substring(const char *); -PCRE_EXP_DECL void pcre16_free_substring(PCRE_SPTR16); -PCRE_EXP_DECL void pcre32_free_substring(PCRE_SPTR32); -PCRE_EXP_DECL void pcre_free_substring_list(const char **); -PCRE_EXP_DECL void pcre16_free_substring_list(PCRE_SPTR16 *); -PCRE_EXP_DECL void pcre32_free_substring_list(PCRE_SPTR32 *); -PCRE_EXP_DECL int pcre_fullinfo(const pcre *, const pcre_extra *, int, - void *); -PCRE_EXP_DECL int pcre16_fullinfo(const pcre16 *, const pcre16_extra *, int, - void *); -PCRE_EXP_DECL int pcre32_fullinfo(const pcre32 *, const pcre32_extra *, int, - void *); -PCRE_EXP_DECL int pcre_get_named_substring(const pcre *, const char *, - int *, int, const char *, const char **); -PCRE_EXP_DECL int pcre16_get_named_substring(const pcre16 *, PCRE_SPTR16, - int *, int, PCRE_SPTR16, PCRE_SPTR16 *); -PCRE_EXP_DECL int pcre32_get_named_substring(const pcre32 *, PCRE_SPTR32, - int *, int, PCRE_SPTR32, PCRE_SPTR32 *); -PCRE_EXP_DECL int pcre_get_stringnumber(const pcre *, const char *); -PCRE_EXP_DECL int pcre16_get_stringnumber(const pcre16 *, PCRE_SPTR16); -PCRE_EXP_DECL int pcre32_get_stringnumber(const pcre32 *, PCRE_SPTR32); -PCRE_EXP_DECL int pcre_get_stringtable_entries(const pcre *, const char *, - char **, char **); -PCRE_EXP_DECL int pcre16_get_stringtable_entries(const pcre16 *, PCRE_SPTR16, - PCRE_UCHAR16 **, PCRE_UCHAR16 **); -PCRE_EXP_DECL int pcre32_get_stringtable_entries(const pcre32 *, PCRE_SPTR32, - PCRE_UCHAR32 **, PCRE_UCHAR32 **); -PCRE_EXP_DECL int pcre_get_substring(const char *, int *, int, int, - const char **); -PCRE_EXP_DECL int pcre16_get_substring(PCRE_SPTR16, int *, int, int, - PCRE_SPTR16 *); -PCRE_EXP_DECL int pcre32_get_substring(PCRE_SPTR32, int *, int, int, - PCRE_SPTR32 *); -PCRE_EXP_DECL int pcre_get_substring_list(const char *, int *, int, - const char ***); -PCRE_EXP_DECL int pcre16_get_substring_list(PCRE_SPTR16, int *, int, - PCRE_SPTR16 **); -PCRE_EXP_DECL int pcre32_get_substring_list(PCRE_SPTR32, int *, int, - PCRE_SPTR32 **); -PCRE_EXP_DECL const unsigned char *pcre_maketables(void); -PCRE_EXP_DECL const unsigned char *pcre16_maketables(void); -PCRE_EXP_DECL const unsigned char *pcre32_maketables(void); -PCRE_EXP_DECL int pcre_refcount(pcre *, int); -PCRE_EXP_DECL int pcre16_refcount(pcre16 *, int); -PCRE_EXP_DECL int pcre32_refcount(pcre32 *, int); -PCRE_EXP_DECL pcre_extra *pcre_study(const pcre *, int, const char **); -PCRE_EXP_DECL pcre16_extra *pcre16_study(const pcre16 *, int, const char **); -PCRE_EXP_DECL pcre32_extra *pcre32_study(const pcre32 *, int, const char **); -PCRE_EXP_DECL void pcre_free_study(pcre_extra *); -PCRE_EXP_DECL void pcre16_free_study(pcre16_extra *); -PCRE_EXP_DECL void pcre32_free_study(pcre32_extra *); -PCRE_EXP_DECL const char *pcre_version(void); -PCRE_EXP_DECL const char *pcre16_version(void); -PCRE_EXP_DECL const char *pcre32_version(void); - -/* Utility functions for byte order swaps. */ -PCRE_EXP_DECL int pcre_pattern_to_host_byte_order(pcre *, pcre_extra *, - const unsigned char *); -PCRE_EXP_DECL int pcre16_pattern_to_host_byte_order(pcre16 *, pcre16_extra *, - const unsigned char *); -PCRE_EXP_DECL int pcre32_pattern_to_host_byte_order(pcre32 *, pcre32_extra *, - const unsigned char *); -PCRE_EXP_DECL int pcre16_utf16_to_host_byte_order(PCRE_UCHAR16 *, - PCRE_SPTR16, int, int *, int); -PCRE_EXP_DECL int pcre32_utf32_to_host_byte_order(PCRE_UCHAR32 *, - PCRE_SPTR32, int, int *, int); - -/* JIT compiler related functions. */ - -PCRE_EXP_DECL pcre_jit_stack *pcre_jit_stack_alloc(int, int); -PCRE_EXP_DECL pcre16_jit_stack *pcre16_jit_stack_alloc(int, int); -PCRE_EXP_DECL pcre32_jit_stack *pcre32_jit_stack_alloc(int, int); -PCRE_EXP_DECL void pcre_jit_stack_free(pcre_jit_stack *); -PCRE_EXP_DECL void pcre16_jit_stack_free(pcre16_jit_stack *); -PCRE_EXP_DECL void pcre32_jit_stack_free(pcre32_jit_stack *); -PCRE_EXP_DECL void pcre_assign_jit_stack(pcre_extra *, - pcre_jit_callback, void *); -PCRE_EXP_DECL void pcre16_assign_jit_stack(pcre16_extra *, - pcre16_jit_callback, void *); -PCRE_EXP_DECL void pcre32_assign_jit_stack(pcre32_extra *, - pcre32_jit_callback, void *); -PCRE_EXP_DECL void pcre_jit_free_unused_memory(void); -PCRE_EXP_DECL void pcre16_jit_free_unused_memory(void); -PCRE_EXP_DECL void pcre32_jit_free_unused_memory(void); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif /* End of pcre.h */ diff --git a/lib/impure/nre/private/pcre_src/pcre_byte_order.c b/lib/impure/nre/private/pcre_src/pcre_byte_order.c deleted file mode 100644 index cf5f12b04..000000000 --- a/lib/impure/nre/private/pcre_src/pcre_byte_order.c +++ /dev/null @@ -1,319 +0,0 @@ -/************************************************* -* Perl-Compatible Regular Expressions * -*************************************************/ - -/* PCRE is a library of functions to support regular expressions whose syntax -and semantics are as close as possible to those of the Perl 5 language. - - Written by Philip Hazel - Copyright (c) 1997-2014 University of Cambridge - ------------------------------------------------------------------------------ -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - * Neither the name of the University of Cambridge nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ -*/ - - -/* This module contains an internal function that tests a compiled pattern to -see if it was compiled with the opposite endianness. If so, it uses an -auxiliary local function to flip the appropriate bytes. */ - - -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - -#include "pcre_internal.h" - - -/************************************************* -* Swap byte functions * -*************************************************/ - -/* The following functions swap the bytes of a pcre_uint16 -and pcre_uint32 value. - -Arguments: - value any number - -Returns: the byte swapped value -*/ - -static pcre_uint32 -swap_uint32(pcre_uint32 value) -{ -return ((value & 0x000000ff) << 24) | - ((value & 0x0000ff00) << 8) | - ((value & 0x00ff0000) >> 8) | - (value >> 24); -} - -static pcre_uint16 -swap_uint16(pcre_uint16 value) -{ -return (value >> 8) | (value << 8); -} - - -/************************************************* -* Test for a byte-flipped compiled regex * -*************************************************/ - -/* This function swaps the bytes of a compiled pattern usually -loaded form the disk. It also sets the tables pointer, which -is likely an invalid pointer after reload. - -Arguments: - argument_re points to the compiled expression - extra_data points to extra data or is NULL - tables points to the character tables or NULL - -Returns: 0 if the swap is successful, negative on error -*/ - -#if defined COMPILE_PCRE8 -PCRE_EXP_DECL int pcre_pattern_to_host_byte_order(pcre *argument_re, - pcre_extra *extra_data, const unsigned char *tables) -#elif defined COMPILE_PCRE16 -PCRE_EXP_DECL int pcre16_pattern_to_host_byte_order(pcre16 *argument_re, - pcre16_extra *extra_data, const unsigned char *tables) -#elif defined COMPILE_PCRE32 -PCRE_EXP_DECL int pcre32_pattern_to_host_byte_order(pcre32 *argument_re, - pcre32_extra *extra_data, const unsigned char *tables) -#endif -{ -REAL_PCRE *re = (REAL_PCRE *)argument_re; -pcre_study_data *study; -#ifndef COMPILE_PCRE8 -pcre_uchar *ptr; -int length; -#if defined SUPPORT_UTF && defined COMPILE_PCRE16 -BOOL utf; -BOOL utf16_char; -#endif /* SUPPORT_UTF && COMPILE_PCRE16 */ -#endif /* !COMPILE_PCRE8 */ - -if (re == NULL) return PCRE_ERROR_NULL; -if (re->magic_number == MAGIC_NUMBER) - { - if ((re->flags & PCRE_MODE) == 0) return PCRE_ERROR_BADMODE; - re->tables = tables; - return 0; - } - -if (re->magic_number != REVERSED_MAGIC_NUMBER) return PCRE_ERROR_BADMAGIC; -if ((swap_uint32(re->flags) & PCRE_MODE) == 0) return PCRE_ERROR_BADMODE; - -re->magic_number = MAGIC_NUMBER; -re->size = swap_uint32(re->size); -re->options = swap_uint32(re->options); -re->flags = swap_uint32(re->flags); -re->limit_match = swap_uint32(re->limit_match); -re->limit_recursion = swap_uint32(re->limit_recursion); - -#if defined COMPILE_PCRE8 || defined COMPILE_PCRE16 -re->first_char = swap_uint16(re->first_char); -re->req_char = swap_uint16(re->req_char); -#elif defined COMPILE_PCRE32 -re->first_char = swap_uint32(re->first_char); -re->req_char = swap_uint32(re->req_char); -#endif - -re->max_lookbehind = swap_uint16(re->max_lookbehind); -re->top_bracket = swap_uint16(re->top_bracket); -re->top_backref = swap_uint16(re->top_backref); -re->name_table_offset = swap_uint16(re->name_table_offset); -re->name_entry_size = swap_uint16(re->name_entry_size); -re->name_count = swap_uint16(re->name_count); -re->ref_count = swap_uint16(re->ref_count); -re->tables = tables; - -if (extra_data != NULL && (extra_data->flags & PCRE_EXTRA_STUDY_DATA) != 0) - { - study = (pcre_study_data *)extra_data->study_data; - study->size = swap_uint32(study->size); - study->flags = swap_uint32(study->flags); - study->minlength = swap_uint32(study->minlength); - } - -#ifndef COMPILE_PCRE8 -ptr = (pcre_uchar *)re + re->name_table_offset; -length = re->name_count * re->name_entry_size; -#if defined SUPPORT_UTF && defined COMPILE_PCRE16 -utf = (re->options & PCRE_UTF16) != 0; -utf16_char = FALSE; -#endif /* SUPPORT_UTF && COMPILE_PCRE16 */ - -while(TRUE) - { - /* Swap previous characters. */ - while (length-- > 0) - { -#if defined COMPILE_PCRE16 - *ptr = swap_uint16(*ptr); -#elif defined COMPILE_PCRE32 - *ptr = swap_uint32(*ptr); -#endif - ptr++; - } -#if defined SUPPORT_UTF && defined COMPILE_PCRE16 - if (utf16_char) - { - if (HAS_EXTRALEN(ptr[-1])) - { - /* We know that there is only one extra character in UTF-16. */ - *ptr = swap_uint16(*ptr); - ptr++; - } - } - utf16_char = FALSE; -#endif /* SUPPORT_UTF */ - - /* Get next opcode. */ - length = 0; -#if defined COMPILE_PCRE16 - *ptr = swap_uint16(*ptr); -#elif defined COMPILE_PCRE32 - *ptr = swap_uint32(*ptr); -#endif - switch (*ptr) - { - case OP_END: - return 0; - -#if defined SUPPORT_UTF && defined COMPILE_PCRE16 - case OP_CHAR: - case OP_CHARI: - case OP_NOT: - case OP_NOTI: - case OP_STAR: - case OP_MINSTAR: - case OP_PLUS: - case OP_MINPLUS: - case OP_QUERY: - case OP_MINQUERY: - case OP_UPTO: - case OP_MINUPTO: - case OP_EXACT: - case OP_POSSTAR: - case OP_POSPLUS: - case OP_POSQUERY: - case OP_POSUPTO: - case OP_STARI: - case OP_MINSTARI: - case OP_PLUSI: - case OP_MINPLUSI: - case OP_QUERYI: - case OP_MINQUERYI: - case OP_UPTOI: - case OP_MINUPTOI: - case OP_EXACTI: - case OP_POSSTARI: - case OP_POSPLUSI: - case OP_POSQUERYI: - case OP_POSUPTOI: - case OP_NOTSTAR: - case OP_NOTMINSTAR: - case OP_NOTPLUS: - case OP_NOTMINPLUS: - case OP_NOTQUERY: - case OP_NOTMINQUERY: - case OP_NOTUPTO: - case OP_NOTMINUPTO: - case OP_NOTEXACT: - case OP_NOTPOSSTAR: - case OP_NOTPOSPLUS: - case OP_NOTPOSQUERY: - case OP_NOTPOSUPTO: - case OP_NOTSTARI: - case OP_NOTMINSTARI: - case OP_NOTPLUSI: - case OP_NOTMINPLUSI: - case OP_NOTQUERYI: - case OP_NOTMINQUERYI: - case OP_NOTUPTOI: - case OP_NOTMINUPTOI: - case OP_NOTEXACTI: - case OP_NOTPOSSTARI: - case OP_NOTPOSPLUSI: - case OP_NOTPOSQUERYI: - case OP_NOTPOSUPTOI: - if (utf) utf16_char = TRUE; -#endif - /* Fall through. */ - - default: - length = PRIV(OP_lengths)[*ptr] - 1; - break; - - case OP_CLASS: - case OP_NCLASS: - /* Skip the character bit map. */ - ptr += 32/sizeof(pcre_uchar); - length = 0; - break; - - case OP_XCLASS: - /* Reverse the size of the XCLASS instance. */ - ptr++; -#if defined COMPILE_PCRE16 - *ptr = swap_uint16(*ptr); -#elif defined COMPILE_PCRE32 - *ptr = swap_uint32(*ptr); -#endif -#ifndef COMPILE_PCRE32 - if (LINK_SIZE > 1) - { - /* LINK_SIZE can be 1 or 2 in 16 bit mode. */ - ptr++; - *ptr = swap_uint16(*ptr); - } -#endif - ptr++; - length = (GET(ptr, -LINK_SIZE)) - (1 + LINK_SIZE + 1); -#if defined COMPILE_PCRE16 - *ptr = swap_uint16(*ptr); -#elif defined COMPILE_PCRE32 - *ptr = swap_uint32(*ptr); -#endif - if ((*ptr & XCL_MAP) != 0) - { - /* Skip the character bit map. */ - ptr += 32/sizeof(pcre_uchar); - length -= 32/sizeof(pcre_uchar); - } - break; - } - ptr++; - } -/* Control should never reach here in 16/32 bit mode. */ -#else /* In 8-bit mode, the pattern does not need to be processed. */ -return 0; -#endif /* !COMPILE_PCRE8 */ -} - -/* End of pcre_byte_order.c */ diff --git a/lib/impure/nre/private/pcre_src/pcre_chartables.c b/lib/impure/nre/private/pcre_src/pcre_chartables.c deleted file mode 100644 index 1e20ec29d..000000000 --- a/lib/impure/nre/private/pcre_src/pcre_chartables.c +++ /dev/null @@ -1,198 +0,0 @@ -/************************************************* -* Perl-Compatible Regular Expressions * -*************************************************/ - -/* This file contains character tables that are used when no external tables -are passed to PCRE by the application that calls it. The tables are used only -for characters whose code values are less than 256. - -This is a default version of the tables that assumes ASCII encoding. A program -called dftables (which is distributed with PCRE) can be used to build -alternative versions of this file. This is necessary if you are running in an -EBCDIC environment, or if you want to default to a different encoding, for -example ISO-8859-1. When dftables is run, it creates these tables in the -current locale. If PCRE is configured with --enable-rebuild-chartables, this -happens automatically. - -The following #includes are present because without them gcc 4.x may remove the -array definition from the final binary if PCRE is built into a static library -and dead code stripping is activated. This leads to link errors. Pulling in the -header ensures that the array gets flagged as "someone outside this compilation -unit might reference this" and so it will always be supplied to the linker. */ - -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - -#include "pcre_internal.h" - -const pcre_uint8 PRIV(default_tables)[] = { - -/* This table is a lower casing table. */ - - 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, - -/* This table is a case flipping table. */ - - 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, 65, 66, 67, 68, 69, 70, 71, - 72, 73, 74, 75, 76, 77, 78, 79, - 80, 81, 82, 83, 84, 85, 86, 87, - 88, 89, 90,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, - -/* This table contains bit maps for various character classes. Each map is 32 -bytes long and the bits run from the least significant end of each byte. The -classes that have their own maps are: space, xdigit, digit, upper, lower, word, -graph, print, punct, and cntrl. Other classes are built from combinations. */ - - 0x00,0x3e,0x00,0x00,0x01,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - - 0x00,0x00,0x00,0x00,0x00,0x00,0xff,0x03, - 0x7e,0x00,0x00,0x00,0x7e,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - - 0x00,0x00,0x00,0x00,0x00,0x00,0xff,0x03, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0xfe,0xff,0xff,0x07,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0xfe,0xff,0xff,0x07, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - - 0x00,0x00,0x00,0x00,0x00,0x00,0xff,0x03, - 0xfe,0xff,0xff,0x87,0xfe,0xff,0xff,0x07, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - - 0x00,0x00,0x00,0x00,0xfe,0xff,0xff,0xff, - 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x7f, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - - 0x00,0x00,0x00,0x00,0xff,0xff,0xff,0xff, - 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x7f, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - - 0x00,0x00,0x00,0x00,0xfe,0xff,0x00,0xfc, - 0x01,0x00,0x00,0xf8,0x01,0x00,0x00,0x78, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - - 0xff,0xff,0xff,0xff,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - -/* This table identifies various classes of character by individual bits: - 0x01 white space character - 0x02 letter - 0x04 decimal digit - 0x08 hexadecimal digit - 0x10 alphanumeric or '_' - 0x80 regular expression metacharacter or binary zero -*/ - - 0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 0- 7 */ - 0x00,0x01,0x01,0x01,0x01,0x01,0x00,0x00, /* 8- 15 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 16- 23 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 24- 31 */ - 0x01,0x00,0x00,0x00,0x80,0x00,0x00,0x00, /* - ' */ - 0x80,0x80,0x80,0x80,0x00,0x00,0x80,0x00, /* ( - / */ - 0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c, /* 0 - 7 */ - 0x1c,0x1c,0x00,0x00,0x00,0x00,0x00,0x80, /* 8 - ? */ - 0x00,0x1a,0x1a,0x1a,0x1a,0x1a,0x1a,0x12, /* @ - G */ - 0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /* H - O */ - 0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /* P - W */ - 0x12,0x12,0x12,0x80,0x80,0x00,0x80,0x10, /* X - _ */ - 0x00,0x1a,0x1a,0x1a,0x1a,0x1a,0x1a,0x12, /* ` - g */ - 0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /* h - o */ - 0x12,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /* p - w */ - 0x12,0x12,0x12,0x80,0x80,0x00,0x00,0x00, /* x -127 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 128-135 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 136-143 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 144-151 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 152-159 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 160-167 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 168-175 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 176-183 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 184-191 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 192-199 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 200-207 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 208-215 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 216-223 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 224-231 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 232-239 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 240-247 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};/* 248-255 */ - -/* End of pcre_chartables.c */ diff --git a/lib/impure/nre/private/pcre_src/pcre_compile.c b/lib/impure/nre/private/pcre_src/pcre_compile.c deleted file mode 100644 index efc0b21fd..000000000 --- a/lib/impure/nre/private/pcre_src/pcre_compile.c +++ /dev/null @@ -1,9515 +0,0 @@ -/************************************************* -* Perl-Compatible Regular Expressions * -*************************************************/ - -/* PCRE is a library of functions to support regular expressions whose syntax -and semantics are as close as possible to those of the Perl 5 language. - - Written by Philip Hazel - Copyright (c) 1997-2014 University of Cambridge - ------------------------------------------------------------------------------ -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - * Neither the name of the University of Cambridge nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ -*/ - - -/* This module contains the external function pcre_compile(), along with -supporting internal functions that are not used by other modules. */ - - -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - -#define NLBLOCK cd /* Block containing newline information */ -#define PSSTART start_pattern /* Field containing pattern start */ -#define PSEND end_pattern /* Field containing pattern end */ - -#include "pcre_internal.h" - - -/* When PCRE_DEBUG is defined, we need the pcre(16|32)_printint() function, which -is also used by pcretest. PCRE_DEBUG is not defined when building a production -library. We do not need to select pcre16_printint.c specially, because the -COMPILE_PCREx macro will already be appropriately set. */ - -#ifdef PCRE_DEBUG -/* pcre_printint.c should not include any headers */ -#define PCRE_INCLUDED -#include "pcre_printint.c" -#undef PCRE_INCLUDED -#endif - - -/* Macro for setting individual bits in class bitmaps. */ - -#define SETBIT(a,b) a[(b)/8] |= (1 << ((b)&7)) - -/* Maximum length value to check against when making sure that the integer that -holds the compiled pattern length does not overflow. We make it a bit less than -INT_MAX to allow for adding in group terminating bytes, so that we don't have -to check them every time. */ - -#define OFLOW_MAX (INT_MAX - 20) - -/* Definitions to allow mutual recursion */ - -static int - add_list_to_class(pcre_uint8 *, pcre_uchar **, int, compile_data *, - const pcre_uint32 *, unsigned int); - -static BOOL - compile_regex(int, pcre_uchar **, const pcre_uchar **, int *, BOOL, BOOL, int, int, - pcre_uint32 *, pcre_int32 *, pcre_uint32 *, pcre_int32 *, branch_chain *, - compile_data *, int *); - - - -/************************************************* -* Code parameters and static tables * -*************************************************/ - -/* This value specifies the size of stack workspace that is used during the -first pre-compile phase that determines how much memory is required. The regex -is partly compiled into this space, but the compiled parts are discarded as -soon as they can be, so that hopefully there will never be an overrun. The code -does, however, check for an overrun. The largest amount I've seen used is 218, -so this number is very generous. - -The same workspace is used during the second, actual compile phase for -remembering forward references to groups so that they can be filled in at the -end. Each entry in this list occupies LINK_SIZE bytes, so even when LINK_SIZE -is 4 there is plenty of room for most patterns. However, the memory can get -filled up by repetitions of forward references, for example patterns like -/(?1){0,1999}(b)/, and one user did hit the limit. The code has been changed so -that the workspace is expanded using malloc() in this situation. The value -below is therefore a minimum, and we put a maximum on it for safety. The -minimum is now also defined in terms of LINK_SIZE so that the use of malloc() -kicks in at the same number of forward references in all cases. */ - -#define COMPILE_WORK_SIZE (2048*LINK_SIZE) -#define COMPILE_WORK_SIZE_MAX (100*COMPILE_WORK_SIZE) - -/* This value determines the size of the initial vector that is used for -remembering named groups during the pre-compile. It is allocated on the stack, -but if it is too small, it is expanded using malloc(), in a similar way to the -workspace. The value is the number of slots in the list. */ - -#define NAMED_GROUP_LIST_SIZE 20 - -/* The overrun tests check for a slightly smaller size so that they detect the -overrun before it actually does run off the end of the data block. */ - -#define WORK_SIZE_SAFETY_MARGIN (100) - -/* Private flags added to firstchar and reqchar. */ - -#define REQ_CASELESS (1 << 0) /* Indicates caselessness */ -#define REQ_VARY (1 << 1) /* Reqchar followed non-literal item */ -/* Negative values for the firstchar and reqchar flags */ -#define REQ_UNSET (-2) -#define REQ_NONE (-1) - -/* Repeated character flags. */ - -#define UTF_LENGTH 0x10000000l /* The char contains its length. */ - -/* Table for handling escaped characters in the range '0'-'z'. Positive returns -are simple data values; negative values are for special things like \d and so -on. Zero means further processing is needed (for things like \x), or the escape -is invalid. */ - -#ifndef EBCDIC - -/* This is the "normal" table for ASCII systems or for EBCDIC systems running -in UTF-8 mode. */ - -static const short int escapes[] = { - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - CHAR_COLON, CHAR_SEMICOLON, - CHAR_LESS_THAN_SIGN, CHAR_EQUALS_SIGN, - CHAR_GREATER_THAN_SIGN, CHAR_QUESTION_MARK, - CHAR_COMMERCIAL_AT, -ESC_A, - -ESC_B, -ESC_C, - -ESC_D, -ESC_E, - 0, -ESC_G, - -ESC_H, 0, - 0, -ESC_K, - 0, 0, - -ESC_N, 0, - -ESC_P, -ESC_Q, - -ESC_R, -ESC_S, - 0, 0, - -ESC_V, -ESC_W, - -ESC_X, 0, - -ESC_Z, CHAR_LEFT_SQUARE_BRACKET, - CHAR_BACKSLASH, CHAR_RIGHT_SQUARE_BRACKET, - CHAR_CIRCUMFLEX_ACCENT, CHAR_UNDERSCORE, - CHAR_GRAVE_ACCENT, 7, - -ESC_b, 0, - -ESC_d, ESC_e, - ESC_f, 0, - -ESC_h, 0, - 0, -ESC_k, - 0, 0, - ESC_n, 0, - -ESC_p, 0, - ESC_r, -ESC_s, - ESC_tee, 0, - -ESC_v, -ESC_w, - 0, 0, - -ESC_z -}; - -#else - -/* This is the "abnormal" table for EBCDIC systems without UTF-8 support. */ - -static const short int escapes[] = { -/* 48 */ 0, 0, 0, '.', '<', '(', '+', '|', -/* 50 */ '&', 0, 0, 0, 0, 0, 0, 0, -/* 58 */ 0, 0, '!', '$', '*', ')', ';', '~', -/* 60 */ '-', '/', 0, 0, 0, 0, 0, 0, -/* 68 */ 0, 0, '|', ',', '%', '_', '>', '?', -/* 70 */ 0, 0, 0, 0, 0, 0, 0, 0, -/* 78 */ 0, '`', ':', '#', '@', '\'', '=', '"', -/* 80 */ 0, 7, -ESC_b, 0, -ESC_d, ESC_e, ESC_f, 0, -/* 88 */-ESC_h, 0, 0, '{', 0, 0, 0, 0, -/* 90 */ 0, 0, -ESC_k, 'l', 0, ESC_n, 0, -ESC_p, -/* 98 */ 0, ESC_r, 0, '}', 0, 0, 0, 0, -/* A0 */ 0, '~', -ESC_s, ESC_tee, 0,-ESC_v, -ESC_w, 0, -/* A8 */ 0,-ESC_z, 0, 0, 0, '[', 0, 0, -/* B0 */ 0, 0, 0, 0, 0, 0, 0, 0, -/* B8 */ 0, 0, 0, 0, 0, ']', '=', '-', -/* C0 */ '{',-ESC_A, -ESC_B, -ESC_C, -ESC_D,-ESC_E, 0, -ESC_G, -/* C8 */-ESC_H, 0, 0, 0, 0, 0, 0, 0, -/* D0 */ '}', 0, -ESC_K, 0, 0,-ESC_N, 0, -ESC_P, -/* D8 */-ESC_Q,-ESC_R, 0, 0, 0, 0, 0, 0, -/* E0 */ '\\', 0, -ESC_S, 0, 0,-ESC_V, -ESC_W, -ESC_X, -/* E8 */ 0,-ESC_Z, 0, 0, 0, 0, 0, 0, -/* F0 */ 0, 0, 0, 0, 0, 0, 0, 0, -/* F8 */ 0, 0, 0, 0, 0, 0, 0, 0 -}; -#endif - - -/* Table of special "verbs" like (*PRUNE). This is a short table, so it is -searched linearly. Put all the names into a single string, in order to reduce -the number of relocations when a shared library is dynamically linked. The -string is built from string macros so that it works in UTF-8 mode on EBCDIC -platforms. */ - -typedef struct verbitem { - int len; /* Length of verb name */ - int op; /* Op when no arg, or -1 if arg mandatory */ - int op_arg; /* Op when arg present, or -1 if not allowed */ -} verbitem; - -static const char verbnames[] = - "\0" /* Empty name is a shorthand for MARK */ - STRING_MARK0 - STRING_ACCEPT0 - STRING_COMMIT0 - STRING_F0 - STRING_FAIL0 - STRING_PRUNE0 - STRING_SKIP0 - STRING_THEN; - -static const verbitem verbs[] = { - { 0, -1, OP_MARK }, - { 4, -1, OP_MARK }, - { 6, OP_ACCEPT, -1 }, - { 6, OP_COMMIT, -1 }, - { 1, OP_FAIL, -1 }, - { 4, OP_FAIL, -1 }, - { 5, OP_PRUNE, OP_PRUNE_ARG }, - { 4, OP_SKIP, OP_SKIP_ARG }, - { 4, OP_THEN, OP_THEN_ARG } -}; - -static const int verbcount = sizeof(verbs)/sizeof(verbitem); - - -/* Substitutes for [[:<:]] and [[:>:]], which mean start and end of word in -another regex library. */ - -static const pcre_uchar sub_start_of_word[] = { - CHAR_BACKSLASH, CHAR_b, CHAR_LEFT_PARENTHESIS, CHAR_QUESTION_MARK, - CHAR_EQUALS_SIGN, CHAR_BACKSLASH, CHAR_w, CHAR_RIGHT_PARENTHESIS, '\0' }; - -static const pcre_uchar sub_end_of_word[] = { - CHAR_BACKSLASH, CHAR_b, CHAR_LEFT_PARENTHESIS, CHAR_QUESTION_MARK, - CHAR_LESS_THAN_SIGN, CHAR_EQUALS_SIGN, CHAR_BACKSLASH, CHAR_w, - CHAR_RIGHT_PARENTHESIS, '\0' }; - - -/* Tables of names of POSIX character classes and their lengths. The names are -now all in a single string, to reduce the number of relocations when a shared -library is dynamically loaded. The list of lengths is terminated by a zero -length entry. The first three must be alpha, lower, upper, as this is assumed -for handling case independence. The indices for graph, print, and punct are -needed, so identify them. */ - -static const char posix_names[] = - STRING_alpha0 STRING_lower0 STRING_upper0 STRING_alnum0 - STRING_ascii0 STRING_blank0 STRING_cntrl0 STRING_digit0 - STRING_graph0 STRING_print0 STRING_punct0 STRING_space0 - STRING_word0 STRING_xdigit; - -static const pcre_uint8 posix_name_lengths[] = { - 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 4, 6, 0 }; - -#define PC_GRAPH 8 -#define PC_PRINT 9 -#define PC_PUNCT 10 - - -/* Table of class bit maps for each POSIX class. Each class is formed from a -base map, with an optional addition or removal of another map. Then, for some -classes, there is some additional tweaking: for [:blank:] the vertical space -characters are removed, and for [:alpha:] and [:alnum:] the underscore -character is removed. The triples in the table consist of the base map offset, -second map offset or -1 if no second map, and a non-negative value for map -addition or a negative value for map subtraction (if there are two maps). The -absolute value of the third field has these meanings: 0 => no tweaking, 1 => -remove vertical space characters, 2 => remove underscore. */ - -static const int posix_class_maps[] = { - cbit_word, cbit_digit, -2, /* alpha */ - cbit_lower, -1, 0, /* lower */ - cbit_upper, -1, 0, /* upper */ - cbit_word, -1, 2, /* alnum - word without underscore */ - cbit_print, cbit_cntrl, 0, /* ascii */ - cbit_space, -1, 1, /* blank - a GNU extension */ - cbit_cntrl, -1, 0, /* cntrl */ - cbit_digit, -1, 0, /* digit */ - cbit_graph, -1, 0, /* graph */ - cbit_print, -1, 0, /* print */ - cbit_punct, -1, 0, /* punct */ - cbit_space, -1, 0, /* space */ - cbit_word, -1, 0, /* word - a Perl extension */ - cbit_xdigit,-1, 0 /* xdigit */ -}; - -/* Table of substitutes for \d etc when PCRE_UCP is set. They are replaced by -Unicode property escapes. */ - -#ifdef SUPPORT_UCP -static const pcre_uchar string_PNd[] = { - CHAR_BACKSLASH, CHAR_P, CHAR_LEFT_CURLY_BRACKET, - CHAR_N, CHAR_d, CHAR_RIGHT_CURLY_BRACKET, '\0' }; -static const pcre_uchar string_pNd[] = { - CHAR_BACKSLASH, CHAR_p, CHAR_LEFT_CURLY_BRACKET, - CHAR_N, CHAR_d, CHAR_RIGHT_CURLY_BRACKET, '\0' }; -static const pcre_uchar string_PXsp[] = { - CHAR_BACKSLASH, CHAR_P, CHAR_LEFT_CURLY_BRACKET, - CHAR_X, CHAR_s, CHAR_p, CHAR_RIGHT_CURLY_BRACKET, '\0' }; -static const pcre_uchar string_pXsp[] = { - CHAR_BACKSLASH, CHAR_p, CHAR_LEFT_CURLY_BRACKET, - CHAR_X, CHAR_s, CHAR_p, CHAR_RIGHT_CURLY_BRACKET, '\0' }; -static const pcre_uchar string_PXwd[] = { - CHAR_BACKSLASH, CHAR_P, CHAR_LEFT_CURLY_BRACKET, - CHAR_X, CHAR_w, CHAR_d, CHAR_RIGHT_CURLY_BRACKET, '\0' }; -static const pcre_uchar string_pXwd[] = { - CHAR_BACKSLASH, CHAR_p, CHAR_LEFT_CURLY_BRACKET, - CHAR_X, CHAR_w, CHAR_d, CHAR_RIGHT_CURLY_BRACKET, '\0' }; - -static const pcre_uchar *substitutes[] = { - string_PNd, /* \D */ - string_pNd, /* \d */ - string_PXsp, /* \S */ /* Xsp is Perl space, but from 8.34, Perl */ - string_pXsp, /* \s */ /* space and POSIX space are the same. */ - string_PXwd, /* \W */ - string_pXwd /* \w */ -}; - -/* The POSIX class substitutes must be in the order of the POSIX class names, -defined above, and there are both positive and negative cases. NULL means no -general substitute of a Unicode property escape (\p or \P). However, for some -POSIX classes (e.g. graph, print, punct) a special property code is compiled -directly. */ - -static const pcre_uchar string_pL[] = { - CHAR_BACKSLASH, CHAR_p, CHAR_LEFT_CURLY_BRACKET, - CHAR_L, CHAR_RIGHT_CURLY_BRACKET, '\0' }; -static const pcre_uchar string_pLl[] = { - CHAR_BACKSLASH, CHAR_p, CHAR_LEFT_CURLY_BRACKET, - CHAR_L, CHAR_l, CHAR_RIGHT_CURLY_BRACKET, '\0' }; -static const pcre_uchar string_pLu[] = { - CHAR_BACKSLASH, CHAR_p, CHAR_LEFT_CURLY_BRACKET, - CHAR_L, CHAR_u, CHAR_RIGHT_CURLY_BRACKET, '\0' }; -static const pcre_uchar string_pXan[] = { - CHAR_BACKSLASH, CHAR_p, CHAR_LEFT_CURLY_BRACKET, - CHAR_X, CHAR_a, CHAR_n, CHAR_RIGHT_CURLY_BRACKET, '\0' }; -static const pcre_uchar string_h[] = { - CHAR_BACKSLASH, CHAR_h, '\0' }; -static const pcre_uchar string_pXps[] = { - CHAR_BACKSLASH, CHAR_p, CHAR_LEFT_CURLY_BRACKET, - CHAR_X, CHAR_p, CHAR_s, CHAR_RIGHT_CURLY_BRACKET, '\0' }; -static const pcre_uchar string_PL[] = { - CHAR_BACKSLASH, CHAR_P, CHAR_LEFT_CURLY_BRACKET, - CHAR_L, CHAR_RIGHT_CURLY_BRACKET, '\0' }; -static const pcre_uchar string_PLl[] = { - CHAR_BACKSLASH, CHAR_P, CHAR_LEFT_CURLY_BRACKET, - CHAR_L, CHAR_l, CHAR_RIGHT_CURLY_BRACKET, '\0' }; -static const pcre_uchar string_PLu[] = { - CHAR_BACKSLASH, CHAR_P, CHAR_LEFT_CURLY_BRACKET, - CHAR_L, CHAR_u, CHAR_RIGHT_CURLY_BRACKET, '\0' }; -static const pcre_uchar string_PXan[] = { - CHAR_BACKSLASH, CHAR_P, CHAR_LEFT_CURLY_BRACKET, - CHAR_X, CHAR_a, CHAR_n, CHAR_RIGHT_CURLY_BRACKET, '\0' }; -static const pcre_uchar string_H[] = { - CHAR_BACKSLASH, CHAR_H, '\0' }; -static const pcre_uchar string_PXps[] = { - CHAR_BACKSLASH, CHAR_P, CHAR_LEFT_CURLY_BRACKET, - CHAR_X, CHAR_p, CHAR_s, CHAR_RIGHT_CURLY_BRACKET, '\0' }; - -static const pcre_uchar *posix_substitutes[] = { - string_pL, /* alpha */ - string_pLl, /* lower */ - string_pLu, /* upper */ - string_pXan, /* alnum */ - NULL, /* ascii */ - string_h, /* blank */ - NULL, /* cntrl */ - string_pNd, /* digit */ - NULL, /* graph */ - NULL, /* print */ - NULL, /* punct */ - string_pXps, /* space */ /* Xps is POSIX space, but from 8.34 */ - string_pXwd, /* word */ /* Perl and POSIX space are the same */ - NULL, /* xdigit */ - /* Negated cases */ - string_PL, /* ^alpha */ - string_PLl, /* ^lower */ - string_PLu, /* ^upper */ - string_PXan, /* ^alnum */ - NULL, /* ^ascii */ - string_H, /* ^blank */ - NULL, /* ^cntrl */ - string_PNd, /* ^digit */ - NULL, /* ^graph */ - NULL, /* ^print */ - NULL, /* ^punct */ - string_PXps, /* ^space */ /* Xps is POSIX space, but from 8.34 */ - string_PXwd, /* ^word */ /* Perl and POSIX space are the same */ - NULL /* ^xdigit */ -}; -#define POSIX_SUBSIZE (sizeof(posix_substitutes) / sizeof(pcre_uchar *)) -#endif - -#define STRING(a) # a -#define XSTRING(s) STRING(s) - -/* The texts of compile-time error messages. These are "char *" because they -are passed to the outside world. Do not ever re-use any error number, because -they are documented. Always add a new error instead. Messages marked DEAD below -are no longer used. This used to be a table of strings, but in order to reduce -the number of relocations needed when a shared library is loaded dynamically, -it is now one long string. We cannot use a table of offsets, because the -lengths of inserts such as XSTRING(MAX_NAME_SIZE) are not known. Instead, we -simply count through to the one we want - this isn't a performance issue -because these strings are used only when there is a compilation error. - -Each substring ends with \0 to insert a null character. This includes the final -substring, so that the whole string ends with \0\0, which can be detected when -counting through. */ - -static const char error_texts[] = - "no error\0" - "\\ at end of pattern\0" - "\\c at end of pattern\0" - "unrecognized character follows \\\0" - "numbers out of order in {} quantifier\0" - /* 5 */ - "number too big in {} quantifier\0" - "missing terminating ] for character class\0" - "invalid escape sequence in character class\0" - "range out of order in character class\0" - "nothing to repeat\0" - /* 10 */ - "operand of unlimited repeat could match the empty string\0" /** DEAD **/ - "internal error: unexpected repeat\0" - "unrecognized character after (? or (?-\0" - "POSIX named classes are supported only within a class\0" - "missing )\0" - /* 15 */ - "reference to non-existent subpattern\0" - "erroffset passed as NULL\0" - "unknown option bit(s) set\0" - "missing ) after comment\0" - "parentheses nested too deeply\0" /** DEAD **/ - /* 20 */ - "regular expression is too large\0" - "failed to get memory\0" - "unmatched parentheses\0" - "internal error: code overflow\0" - "unrecognized character after (?<\0" - /* 25 */ - "lookbehind assertion is not fixed length\0" - "malformed number or name after (?(\0" - "conditional group contains more than two branches\0" - "assertion expected after (?(\0" - "(?R or (?[+-]digits must be followed by )\0" - /* 30 */ - "unknown POSIX class name\0" - "POSIX collating elements are not supported\0" - "this version of PCRE is compiled without UTF support\0" - "spare error\0" /** DEAD **/ - "character value in \\x{} or \\o{} is too large\0" - /* 35 */ - "invalid condition (?(0)\0" - "\\C not allowed in lookbehind assertion\0" - "PCRE does not support \\L, \\l, \\N{name}, \\U, or \\u\0" - "number after (?C is > 255\0" - "closing ) for (?C expected\0" - /* 40 */ - "recursive call could loop indefinitely\0" - "unrecognized character after (?P\0" - "syntax error in subpattern name (missing terminator)\0" - "two named subpatterns have the same name\0" - "invalid UTF-8 string\0" - /* 45 */ - "support for \\P, \\p, and \\X has not been compiled\0" - "malformed \\P or \\p sequence\0" - "unknown property name after \\P or \\p\0" - "subpattern name is too long (maximum " XSTRING(MAX_NAME_SIZE) " characters)\0" - "too many named subpatterns (maximum " XSTRING(MAX_NAME_COUNT) ")\0" - /* 50 */ - "repeated subpattern is too long\0" /** DEAD **/ - "octal value is greater than \\377 in 8-bit non-UTF-8 mode\0" - "internal error: overran compiling workspace\0" - "internal error: previously-checked referenced subpattern not found\0" - "DEFINE group contains more than one branch\0" - /* 55 */ - "repeating a DEFINE group is not allowed\0" /** DEAD **/ - "inconsistent NEWLINE options\0" - "\\g is not followed by a braced, angle-bracketed, or quoted name/number or by a plain number\0" - "a numbered reference must not be zero\0" - "an argument is not allowed for (*ACCEPT), (*FAIL), or (*COMMIT)\0" - /* 60 */ - "(*VERB) not recognized or malformed\0" - "number is too big\0" - "subpattern name expected\0" - "digit expected after (?+\0" - "] is an invalid data character in JavaScript compatibility mode\0" - /* 65 */ - "different names for subpatterns of the same number are not allowed\0" - "(*MARK) must have an argument\0" - "this version of PCRE is not compiled with Unicode property support\0" - "\\c must be followed by an ASCII character\0" - "\\k is not followed by a braced, angle-bracketed, or quoted name\0" - /* 70 */ - "internal error: unknown opcode in find_fixedlength()\0" - "\\N is not supported in a class\0" - "too many forward references\0" - "disallowed Unicode code point (>= 0xd800 && <= 0xdfff)\0" - "invalid UTF-16 string\0" - /* 75 */ - "name is too long in (*MARK), (*PRUNE), (*SKIP), or (*THEN)\0" - "character value in \\u.... sequence is too large\0" - "invalid UTF-32 string\0" - "setting UTF is disabled by the application\0" - "non-hex character in \\x{} (closing brace missing?)\0" - /* 80 */ - "non-octal character in \\o{} (closing brace missing?)\0" - "missing opening brace after \\o\0" - "parentheses are too deeply nested\0" - "invalid range in character class\0" - "group name must start with a non-digit\0" - /* 85 */ - "parentheses are too deeply nested (stack check)\0" - "digits missing in \\x{} or \\o{}\0" - ; - -/* Table to identify digits and hex digits. This is used when compiling -patterns. Note that the tables in chartables are dependent on the locale, and -may mark arbitrary characters as digits - but the PCRE compiling code expects -to handle only 0-9, a-z, and A-Z as digits when compiling. That is why we have -a private table here. It costs 256 bytes, but it is a lot faster than doing -character value tests (at least in some simple cases I timed), and in some -applications one wants PCRE to compile efficiently as well as match -efficiently. - -For convenience, we use the same bit definitions as in chartables: - - 0x04 decimal digit - 0x08 hexadecimal digit - -Then we can use ctype_digit and ctype_xdigit in the code. */ - -/* Using a simple comparison for decimal numbers rather than a memory read -is much faster, and the resulting code is simpler (the compiler turns it -into a subtraction and unsigned comparison). */ - -#define IS_DIGIT(x) ((x) >= CHAR_0 && (x) <= CHAR_9) - -#ifndef EBCDIC - -/* This is the "normal" case, for ASCII systems, and EBCDIC systems running in -UTF-8 mode. */ - -static const pcre_uint8 digitab[] = - { - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 0- 7 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 8- 15 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 16- 23 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 24- 31 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* - ' */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* ( - / */ - 0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c, /* 0 - 7 */ - 0x0c,0x0c,0x00,0x00,0x00,0x00,0x00,0x00, /* 8 - ? */ - 0x00,0x08,0x08,0x08,0x08,0x08,0x08,0x00, /* @ - G */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* H - O */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* P - W */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* X - _ */ - 0x00,0x08,0x08,0x08,0x08,0x08,0x08,0x00, /* ` - g */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* h - o */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* p - w */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* x -127 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 128-135 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 136-143 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 144-151 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 152-159 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 160-167 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 168-175 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 176-183 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 184-191 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 192-199 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 200-207 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 208-215 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 216-223 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 224-231 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 232-239 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 240-247 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};/* 248-255 */ - -#else - -/* This is the "abnormal" case, for EBCDIC systems not running in UTF-8 mode. */ - -static const pcre_uint8 digitab[] = - { - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 0- 7 0 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 8- 15 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 16- 23 10 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 24- 31 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 32- 39 20 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 40- 47 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 48- 55 30 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 56- 63 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* - 71 40 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 72- | */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* & - 87 50 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 88- 95 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* - -103 60 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 104- ? */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 112-119 70 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 120- " */ - 0x00,0x08,0x08,0x08,0x08,0x08,0x08,0x00, /* 128- g 80 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* h -143 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 144- p 90 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* q -159 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 160- x A0 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* y -175 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* ^ -183 B0 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 184-191 */ - 0x00,0x08,0x08,0x08,0x08,0x08,0x08,0x00, /* { - G C0 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* H -207 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* } - P D0 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* Q -223 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* \ - X E0 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* Y -239 */ - 0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c, /* 0 - 7 F0 */ - 0x0c,0x0c,0x00,0x00,0x00,0x00,0x00,0x00};/* 8 -255 */ - -static const pcre_uint8 ebcdic_chartab[] = { /* chartable partial dup */ - 0x80,0x00,0x00,0x00,0x00,0x01,0x00,0x00, /* 0- 7 */ - 0x00,0x00,0x00,0x00,0x01,0x01,0x00,0x00, /* 8- 15 */ - 0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00, /* 16- 23 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 24- 31 */ - 0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00, /* 32- 39 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 40- 47 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 48- 55 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 56- 63 */ - 0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* - 71 */ - 0x00,0x00,0x00,0x80,0x00,0x80,0x80,0x80, /* 72- | */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* & - 87 */ - 0x00,0x00,0x00,0x80,0x80,0x80,0x00,0x00, /* 88- 95 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* - -103 */ - 0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x80, /* 104- ? */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 112-119 */ - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 120- " */ - 0x00,0x1a,0x1a,0x1a,0x1a,0x1a,0x1a,0x12, /* 128- g */ - 0x12,0x12,0x00,0x00,0x00,0x00,0x00,0x00, /* h -143 */ - 0x00,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /* 144- p */ - 0x12,0x12,0x00,0x00,0x00,0x00,0x00,0x00, /* q -159 */ - 0x00,0x00,0x12,0x12,0x12,0x12,0x12,0x12, /* 160- x */ - 0x12,0x12,0x00,0x00,0x00,0x00,0x00,0x00, /* y -175 */ - 0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* ^ -183 */ - 0x00,0x00,0x80,0x00,0x00,0x00,0x00,0x00, /* 184-191 */ - 0x80,0x1a,0x1a,0x1a,0x1a,0x1a,0x1a,0x12, /* { - G */ - 0x12,0x12,0x00,0x00,0x00,0x00,0x00,0x00, /* H -207 */ - 0x00,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /* } - P */ - 0x12,0x12,0x00,0x00,0x00,0x00,0x00,0x00, /* Q -223 */ - 0x00,0x00,0x12,0x12,0x12,0x12,0x12,0x12, /* \ - X */ - 0x12,0x12,0x00,0x00,0x00,0x00,0x00,0x00, /* Y -239 */ - 0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c, /* 0 - 7 */ - 0x1c,0x1c,0x00,0x00,0x00,0x00,0x00,0x00};/* 8 -255 */ -#endif - - -/* This table is used to check whether auto-possessification is possible -between adjacent character-type opcodes. The left-hand (repeated) opcode is -used to select the row, and the right-hand opcode is use to select the column. -A value of 1 means that auto-possessification is OK. For example, the second -value in the first row means that \D+\d can be turned into \D++\d. - -The Unicode property types (\P and \p) have to be present to fill out the table -because of what their opcode values are, but the table values should always be -zero because property types are handled separately in the code. The last four -columns apply to items that cannot be repeated, so there is no need to have -rows for them. Note that OP_DIGIT etc. are generated only when PCRE_UCP is -*not* set. When it is set, \d etc. are converted into OP_(NOT_)PROP codes. */ - -#define APTROWS (LAST_AUTOTAB_LEFT_OP - FIRST_AUTOTAB_OP + 1) -#define APTCOLS (LAST_AUTOTAB_RIGHT_OP - FIRST_AUTOTAB_OP + 1) - -static const pcre_uint8 autoposstab[APTROWS][APTCOLS] = { -/* \D \d \S \s \W \w . .+ \C \P \p \R \H \h \V \v \X \Z \z $ $M */ - { 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 }, /* \D */ - { 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1 }, /* \d */ - { 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1 }, /* \S */ - { 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 }, /* \s */ - { 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 }, /* \W */ - { 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1 }, /* \w */ - { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0 }, /* . */ - { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 }, /* .+ */ - { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 }, /* \C */ - { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* \P */ - { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* \p */ - { 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0 }, /* \R */ - { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0 }, /* \H */ - { 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0 }, /* \h */ - { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0 }, /* \V */ - { 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0 }, /* \v */ - { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 } /* \X */ -}; - - -/* This table is used to check whether auto-possessification is possible -between adjacent Unicode property opcodes (OP_PROP and OP_NOTPROP). The -left-hand (repeated) opcode is used to select the row, and the right-hand -opcode is used to select the column. The values are as follows: - - 0 Always return FALSE (never auto-possessify) - 1 Character groups are distinct (possessify if both are OP_PROP) - 2 Check character categories in the same group (general or particular) - 3 TRUE if the two opcodes are not the same (PROP vs NOTPROP) - - 4 Check left general category vs right particular category - 5 Check right general category vs left particular category - - 6 Left alphanum vs right general category - 7 Left space vs right general category - 8 Left word vs right general category - - 9 Right alphanum vs left general category - 10 Right space vs left general category - 11 Right word vs left general category - - 12 Left alphanum vs right particular category - 13 Left space vs right particular category - 14 Left word vs right particular category - - 15 Right alphanum vs left particular category - 16 Right space vs left particular category - 17 Right word vs left particular category -*/ - -static const pcre_uint8 propposstab[PT_TABSIZE][PT_TABSIZE] = { -/* ANY LAMP GC PC SC ALNUM SPACE PXSPACE WORD CLIST UCNC */ - { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* PT_ANY */ - { 0, 3, 0, 0, 0, 3, 1, 1, 0, 0, 0 }, /* PT_LAMP */ - { 0, 0, 2, 4, 0, 9, 10, 10, 11, 0, 0 }, /* PT_GC */ - { 0, 0, 5, 2, 0, 15, 16, 16, 17, 0, 0 }, /* PT_PC */ - { 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0 }, /* PT_SC */ - { 0, 3, 6, 12, 0, 3, 1, 1, 0, 0, 0 }, /* PT_ALNUM */ - { 0, 1, 7, 13, 0, 1, 3, 3, 1, 0, 0 }, /* PT_SPACE */ - { 0, 1, 7, 13, 0, 1, 3, 3, 1, 0, 0 }, /* PT_PXSPACE */ - { 0, 0, 8, 14, 0, 0, 1, 1, 3, 0, 0 }, /* PT_WORD */ - { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* PT_CLIST */ - { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3 } /* PT_UCNC */ -}; - -/* This table is used to check whether auto-possessification is possible -between adjacent Unicode property opcodes (OP_PROP and OP_NOTPROP) when one -specifies a general category and the other specifies a particular category. The -row is selected by the general category and the column by the particular -category. The value is 1 if the particular category is not part of the general -category. */ - -static const pcre_uint8 catposstab[7][30] = { -/* Cc Cf Cn Co Cs Ll Lm Lo Lt Lu Mc Me Mn Nd Nl No Pc Pd Pe Pf Pi Po Ps Sc Sk Sm So Zl Zp Zs */ - { 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, /* C */ - { 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, /* L */ - { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, /* M */ - { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, /* N */ - { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1 }, /* P */ - { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1 }, /* S */ - { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0 } /* Z */ -}; - -/* This table is used when checking ALNUM, (PX)SPACE, SPACE, and WORD against -a general or particular category. The properties in each row are those -that apply to the character set in question. Duplication means that a little -unnecessary work is done when checking, but this keeps things much simpler -because they can all use the same code. For more details see the comment where -this table is used. - -Note: SPACE and PXSPACE used to be different because Perl excluded VT from -"space", but from Perl 5.18 it's included, so both categories are treated the -same here. */ - -static const pcre_uint8 posspropstab[3][4] = { - { ucp_L, ucp_N, ucp_N, ucp_Nl }, /* ALNUM, 3rd and 4th values redundant */ - { ucp_Z, ucp_Z, ucp_C, ucp_Cc }, /* SPACE and PXSPACE, 2nd value redundant */ - { ucp_L, ucp_N, ucp_P, ucp_Po } /* WORD */ -}; - -/* This table is used when converting repeating opcodes into possessified -versions as a result of an explicit possessive quantifier such as ++. A zero -value means there is no possessified version - in those cases the item in -question must be wrapped in ONCE brackets. The table is truncated at OP_CALLOUT -because all relevant opcodes are less than that. */ - -static const pcre_uint8 opcode_possessify[] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0 - 15 */ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 16 - 31 */ - - 0, /* NOTI */ - OP_POSSTAR, 0, /* STAR, MINSTAR */ - OP_POSPLUS, 0, /* PLUS, MINPLUS */ - OP_POSQUERY, 0, /* QUERY, MINQUERY */ - OP_POSUPTO, 0, /* UPTO, MINUPTO */ - 0, /* EXACT */ - 0, 0, 0, 0, /* POS{STAR,PLUS,QUERY,UPTO} */ - - OP_POSSTARI, 0, /* STARI, MINSTARI */ - OP_POSPLUSI, 0, /* PLUSI, MINPLUSI */ - OP_POSQUERYI, 0, /* QUERYI, MINQUERYI */ - OP_POSUPTOI, 0, /* UPTOI, MINUPTOI */ - 0, /* EXACTI */ - 0, 0, 0, 0, /* POS{STARI,PLUSI,QUERYI,UPTOI} */ - - OP_NOTPOSSTAR, 0, /* NOTSTAR, NOTMINSTAR */ - OP_NOTPOSPLUS, 0, /* NOTPLUS, NOTMINPLUS */ - OP_NOTPOSQUERY, 0, /* NOTQUERY, NOTMINQUERY */ - OP_NOTPOSUPTO, 0, /* NOTUPTO, NOTMINUPTO */ - 0, /* NOTEXACT */ - 0, 0, 0, 0, /* NOTPOS{STAR,PLUS,QUERY,UPTO} */ - - OP_NOTPOSSTARI, 0, /* NOTSTARI, NOTMINSTARI */ - OP_NOTPOSPLUSI, 0, /* NOTPLUSI, NOTMINPLUSI */ - OP_NOTPOSQUERYI, 0, /* NOTQUERYI, NOTMINQUERYI */ - OP_NOTPOSUPTOI, 0, /* NOTUPTOI, NOTMINUPTOI */ - 0, /* NOTEXACTI */ - 0, 0, 0, 0, /* NOTPOS{STARI,PLUSI,QUERYI,UPTOI} */ - - OP_TYPEPOSSTAR, 0, /* TYPESTAR, TYPEMINSTAR */ - OP_TYPEPOSPLUS, 0, /* TYPEPLUS, TYPEMINPLUS */ - OP_TYPEPOSQUERY, 0, /* TYPEQUERY, TYPEMINQUERY */ - OP_TYPEPOSUPTO, 0, /* TYPEUPTO, TYPEMINUPTO */ - 0, /* TYPEEXACT */ - 0, 0, 0, 0, /* TYPEPOS{STAR,PLUS,QUERY,UPTO} */ - - OP_CRPOSSTAR, 0, /* CRSTAR, CRMINSTAR */ - OP_CRPOSPLUS, 0, /* CRPLUS, CRMINPLUS */ - OP_CRPOSQUERY, 0, /* CRQUERY, CRMINQUERY */ - OP_CRPOSRANGE, 0, /* CRRANGE, CRMINRANGE */ - 0, 0, 0, 0, /* CRPOS{STAR,PLUS,QUERY,RANGE} */ - - 0, 0, 0, /* CLASS, NCLASS, XCLASS */ - 0, 0, /* REF, REFI */ - 0, 0, /* DNREF, DNREFI */ - 0, 0 /* RECURSE, CALLOUT */ -}; - - - -/************************************************* -* Find an error text * -*************************************************/ - -/* The error texts are now all in one long string, to save on relocations. As -some of the text is of unknown length, we can't use a table of offsets. -Instead, just count through the strings. This is not a performance issue -because it happens only when there has been a compilation error. - -Argument: the error number -Returns: pointer to the error string -*/ - -static const char * -find_error_text(int n) -{ -const char *s = error_texts; -for (; n > 0; n--) - { - while (*s++ != CHAR_NULL) {}; - if (*s == CHAR_NULL) return "Error text not found (please report)"; - } -return s; -} - - - -/************************************************* -* Expand the workspace * -*************************************************/ - -/* This function is called during the second compiling phase, if the number of -forward references fills the existing workspace, which is originally a block on -the stack. A larger block is obtained from malloc() unless the ultimate limit -has been reached or the increase will be rather small. - -Argument: pointer to the compile data block -Returns: 0 if all went well, else an error number -*/ - -static int -expand_workspace(compile_data *cd) -{ -pcre_uchar *newspace; -int newsize = cd->workspace_size * 2; - -if (newsize > COMPILE_WORK_SIZE_MAX) newsize = COMPILE_WORK_SIZE_MAX; -if (cd->workspace_size >= COMPILE_WORK_SIZE_MAX || - newsize - cd->workspace_size < WORK_SIZE_SAFETY_MARGIN) - return ERR72; - -newspace = (PUBL(malloc))(IN_UCHARS(newsize)); -if (newspace == NULL) return ERR21; -memcpy(newspace, cd->start_workspace, cd->workspace_size * sizeof(pcre_uchar)); -cd->hwm = (pcre_uchar *)newspace + (cd->hwm - cd->start_workspace); -if (cd->workspace_size > COMPILE_WORK_SIZE) - (PUBL(free))((void *)cd->start_workspace); -cd->start_workspace = newspace; -cd->workspace_size = newsize; -return 0; -} - - - -/************************************************* -* Check for counted repeat * -*************************************************/ - -/* This function is called when a '{' is encountered in a place where it might -start a quantifier. It looks ahead to see if it really is a quantifier or not. -It is only a quantifier if it is one of the forms {ddd} {ddd,} or {ddd,ddd} -where the ddds are digits. - -Arguments: - p pointer to the first char after '{' - -Returns: TRUE or FALSE -*/ - -static BOOL -is_counted_repeat(const pcre_uchar *p) -{ -if (!IS_DIGIT(*p)) return FALSE; -p++; -while (IS_DIGIT(*p)) p++; -if (*p == CHAR_RIGHT_CURLY_BRACKET) return TRUE; - -if (*p++ != CHAR_COMMA) return FALSE; -if (*p == CHAR_RIGHT_CURLY_BRACKET) return TRUE; - -if (!IS_DIGIT(*p)) return FALSE; -p++; -while (IS_DIGIT(*p)) p++; - -return (*p == CHAR_RIGHT_CURLY_BRACKET); -} - - - -/************************************************* -* Handle escapes * -*************************************************/ - -/* This function is called when a \ has been encountered. It either returns a -positive value for a simple escape such as \n, or 0 for a data character which -will be placed in chptr. A backreference to group n is returned as negative n. -When UTF-8 is enabled, a positive value greater than 255 may be returned in -chptr. On entry, ptr is pointing at the \. On exit, it is on the final -character of the escape sequence. - -Arguments: - ptrptr points to the pattern position pointer - chptr points to a returned data character - errorcodeptr points to the errorcode variable - bracount number of previous extracting brackets - options the options bits - isclass TRUE if inside a character class - -Returns: zero => a data character - positive => a special escape sequence - negative => a back reference - on error, errorcodeptr is set -*/ - -static int -check_escape(const pcre_uchar **ptrptr, pcre_uint32 *chptr, int *errorcodeptr, - int bracount, int options, BOOL isclass) -{ -/* PCRE_UTF16 has the same value as PCRE_UTF8. */ -BOOL utf = (options & PCRE_UTF8) != 0; -const pcre_uchar *ptr = *ptrptr + 1; -pcre_uint32 c; -int escape = 0; -int i; - -GETCHARINCTEST(c, ptr); /* Get character value, increment pointer */ -ptr--; /* Set pointer back to the last byte */ - -/* If backslash is at the end of the pattern, it's an error. */ - -if (c == CHAR_NULL) *errorcodeptr = ERR1; - -/* Non-alphanumerics are literals. For digits or letters, do an initial lookup -in a table. A non-zero result is something that can be returned immediately. -Otherwise further processing may be required. */ - -#ifndef EBCDIC /* ASCII/UTF-8 coding */ -/* Not alphanumeric */ -else if (c < CHAR_0 || c > CHAR_z) {} -else if ((i = escapes[c - CHAR_0]) != 0) - { if (i > 0) c = (pcre_uint32)i; else escape = -i; } - -#else /* EBCDIC coding */ -/* Not alphanumeric */ -else if (c < CHAR_a || (!MAX_255(c) || (ebcdic_chartab[c] & 0x0E) == 0)) {} -else if ((i = escapes[c - 0x48]) != 0) { if (i > 0) c = (pcre_uint32)i; else escape = -i; } -#endif - -/* Escapes that need further processing, or are illegal. */ - -else - { - const pcre_uchar *oldptr; - BOOL braced, negated, overflow; - int s; - - switch (c) - { - /* A number of Perl escapes are not handled by PCRE. We give an explicit - error. */ - - case CHAR_l: - case CHAR_L: - *errorcodeptr = ERR37; - break; - - case CHAR_u: - if ((options & PCRE_JAVASCRIPT_COMPAT) != 0) - { - /* In JavaScript, \u must be followed by four hexadecimal numbers. - Otherwise it is a lowercase u letter. */ - if (MAX_255(ptr[1]) && (digitab[ptr[1]] & ctype_xdigit) != 0 - && MAX_255(ptr[2]) && (digitab[ptr[2]] & ctype_xdigit) != 0 - && MAX_255(ptr[3]) && (digitab[ptr[3]] & ctype_xdigit) != 0 - && MAX_255(ptr[4]) && (digitab[ptr[4]] & ctype_xdigit) != 0) - { - c = 0; - for (i = 0; i < 4; ++i) - { - register pcre_uint32 cc = *(++ptr); -#ifndef EBCDIC /* ASCII/UTF-8 coding */ - if (cc >= CHAR_a) cc -= 32; /* Convert to upper case */ - c = (c << 4) + cc - ((cc < CHAR_A)? CHAR_0 : (CHAR_A - 10)); -#else /* EBCDIC coding */ - if (cc >= CHAR_a && cc <= CHAR_z) cc += 64; /* Convert to upper case */ - c = (c << 4) + cc - ((cc >= CHAR_0)? CHAR_0 : (CHAR_A - 10)); -#endif - } - -#if defined COMPILE_PCRE8 - if (c > (utf ? 0x10ffffU : 0xffU)) -#elif defined COMPILE_PCRE16 - if (c > (utf ? 0x10ffffU : 0xffffU)) -#elif defined COMPILE_PCRE32 - if (utf && c > 0x10ffffU) -#endif - { - *errorcodeptr = ERR76; - } - else if (utf && c >= 0xd800 && c <= 0xdfff) *errorcodeptr = ERR73; - } - } - else - *errorcodeptr = ERR37; - break; - - case CHAR_U: - /* In JavaScript, \U is an uppercase U letter. */ - if ((options & PCRE_JAVASCRIPT_COMPAT) == 0) *errorcodeptr = ERR37; - break; - - /* In a character class, \g is just a literal "g". Outside a character - class, \g must be followed by one of a number of specific things: - - (1) A number, either plain or braced. If positive, it is an absolute - backreference. If negative, it is a relative backreference. This is a Perl - 5.10 feature. - - (2) Perl 5.10 also supports \g{name} as a reference to a named group. This - is part of Perl's movement towards a unified syntax for back references. As - this is synonymous with \k{name}, we fudge it up by pretending it really - was \k. - - (3) For Oniguruma compatibility we also support \g followed by a name or a - number either in angle brackets or in single quotes. However, these are - (possibly recursive) subroutine calls, _not_ backreferences. Just return - the ESC_g code (cf \k). */ - - case CHAR_g: - if (isclass) break; - if (ptr[1] == CHAR_LESS_THAN_SIGN || ptr[1] == CHAR_APOSTROPHE) - { - escape = ESC_g; - break; - } - - /* Handle the Perl-compatible cases */ - - if (ptr[1] == CHAR_LEFT_CURLY_BRACKET) - { - const pcre_uchar *p; - for (p = ptr+2; *p != CHAR_NULL && *p != CHAR_RIGHT_CURLY_BRACKET; p++) - if (*p != CHAR_MINUS && !IS_DIGIT(*p)) break; - if (*p != CHAR_NULL && *p != CHAR_RIGHT_CURLY_BRACKET) - { - escape = ESC_k; - break; - } - braced = TRUE; - ptr++; - } - else braced = FALSE; - - if (ptr[1] == CHAR_MINUS) - { - negated = TRUE; - ptr++; - } - else negated = FALSE; - - /* The integer range is limited by the machine's int representation. */ - s = 0; - overflow = FALSE; - while (IS_DIGIT(ptr[1])) - { - if (s > INT_MAX / 10 - 1) /* Integer overflow */ - { - overflow = TRUE; - break; - } - s = s * 10 + (int)(*(++ptr) - CHAR_0); - } - if (overflow) /* Integer overflow */ - { - while (IS_DIGIT(ptr[1])) - ptr++; - *errorcodeptr = ERR61; - break; - } - - if (braced && *(++ptr) != CHAR_RIGHT_CURLY_BRACKET) - { - *errorcodeptr = ERR57; - break; - } - - if (s == 0) - { - *errorcodeptr = ERR58; - break; - } - - if (negated) - { - if (s > bracount) - { - *errorcodeptr = ERR15; - break; - } - s = bracount - (s - 1); - } - - escape = -s; - break; - - /* The handling of escape sequences consisting of a string of digits - starting with one that is not zero is not straightforward. Perl has changed - over the years. Nowadays \g{} for backreferences and \o{} for octal are - recommended to avoid the ambiguities in the old syntax. - - Outside a character class, the digits are read as a decimal number. If the - number is less than 8 (used to be 10), or if there are that many previous - extracting left brackets, then it is a back reference. Otherwise, up to - three octal digits are read to form an escaped byte. Thus \123 is likely to - be octal 123 (cf \0123, which is octal 012 followed by the literal 3). If - the octal value is greater than 377, the least significant 8 bits are - taken. \8 and \9 are treated as the literal characters 8 and 9. - - Inside a character class, \ followed by a digit is always either a literal - 8 or 9 or an octal number. */ - - case CHAR_1: case CHAR_2: case CHAR_3: case CHAR_4: case CHAR_5: - case CHAR_6: case CHAR_7: case CHAR_8: case CHAR_9: - - if (!isclass) - { - oldptr = ptr; - /* The integer range is limited by the machine's int representation. */ - s = (int)(c -CHAR_0); - overflow = FALSE; - while (IS_DIGIT(ptr[1])) - { - if (s > INT_MAX / 10 - 1) /* Integer overflow */ - { - overflow = TRUE; - break; - } - s = s * 10 + (int)(*(++ptr) - CHAR_0); - } - if (overflow) /* Integer overflow */ - { - while (IS_DIGIT(ptr[1])) - ptr++; - *errorcodeptr = ERR61; - break; - } - if (s < 8 || s <= bracount) /* Check for back reference */ - { - escape = -s; - break; - } - ptr = oldptr; /* Put the pointer back and fall through */ - } - - /* Handle a digit following \ when the number is not a back reference. If - the first digit is 8 or 9, Perl used to generate a binary zero byte and - then treat the digit as a following literal. At least by Perl 5.18 this - changed so as not to insert the binary zero. */ - - if ((c = *ptr) >= CHAR_8) break; - - /* Fall through with a digit less than 8 */ - - /* \0 always starts an octal number, but we may drop through to here with a - larger first octal digit. The original code used just to take the least - significant 8 bits of octal numbers (I think this is what early Perls used - to do). Nowadays we allow for larger numbers in UTF-8 mode and 16-bit mode, - but no more than 3 octal digits. */ - - case CHAR_0: - c -= CHAR_0; - while(i++ < 2 && ptr[1] >= CHAR_0 && ptr[1] <= CHAR_7) - c = c * 8 + *(++ptr) - CHAR_0; -#ifdef COMPILE_PCRE8 - if (!utf && c > 0xff) *errorcodeptr = ERR51; -#endif - break; - - /* \o is a relatively new Perl feature, supporting a more general way of - specifying character codes in octal. The only supported form is \o{ddd}. */ - - case CHAR_o: - if (ptr[1] != CHAR_LEFT_CURLY_BRACKET) *errorcodeptr = ERR81; else - if (ptr[2] == CHAR_RIGHT_CURLY_BRACKET) *errorcodeptr = ERR86; else - { - ptr += 2; - c = 0; - overflow = FALSE; - while (*ptr >= CHAR_0 && *ptr <= CHAR_7) - { - register pcre_uint32 cc = *ptr++; - if (c == 0 && cc == CHAR_0) continue; /* Leading zeroes */ -#ifdef COMPILE_PCRE32 - if (c >= 0x20000000l) { overflow = TRUE; break; } -#endif - c = (c << 3) + cc - CHAR_0 ; -#if defined COMPILE_PCRE8 - if (c > (utf ? 0x10ffffU : 0xffU)) { overflow = TRUE; break; } -#elif defined COMPILE_PCRE16 - if (c > (utf ? 0x10ffffU : 0xffffU)) { overflow = TRUE; break; } -#elif defined COMPILE_PCRE32 - if (utf && c > 0x10ffffU) { overflow = TRUE; break; } -#endif - } - if (overflow) - { - while (*ptr >= CHAR_0 && *ptr <= CHAR_7) ptr++; - *errorcodeptr = ERR34; - } - else if (*ptr == CHAR_RIGHT_CURLY_BRACKET) - { - if (utf && c >= 0xd800 && c <= 0xdfff) *errorcodeptr = ERR73; - } - else *errorcodeptr = ERR80; - } - break; - - /* \x is complicated. In JavaScript, \x must be followed by two hexadecimal - numbers. Otherwise it is a lowercase x letter. */ - - case CHAR_x: - if ((options & PCRE_JAVASCRIPT_COMPAT) != 0) - { - if (MAX_255(ptr[1]) && (digitab[ptr[1]] & ctype_xdigit) != 0 - && MAX_255(ptr[2]) && (digitab[ptr[2]] & ctype_xdigit) != 0) - { - c = 0; - for (i = 0; i < 2; ++i) - { - register pcre_uint32 cc = *(++ptr); -#ifndef EBCDIC /* ASCII/UTF-8 coding */ - if (cc >= CHAR_a) cc -= 32; /* Convert to upper case */ - c = (c << 4) + cc - ((cc < CHAR_A)? CHAR_0 : (CHAR_A - 10)); -#else /* EBCDIC coding */ - if (cc >= CHAR_a && cc <= CHAR_z) cc += 64; /* Convert to upper case */ - c = (c << 4) + cc - ((cc >= CHAR_0)? CHAR_0 : (CHAR_A - 10)); -#endif - } - } - } /* End JavaScript handling */ - - /* Handle \x in Perl's style. \x{ddd} is a character number which can be - greater than 0xff in utf or non-8bit mode, but only if the ddd are hex - digits. If not, { used to be treated as a data character. However, Perl - seems to read hex digits up to the first non-such, and ignore the rest, so - that, for example \x{zz} matches a binary zero. This seems crazy, so PCRE - now gives an error. */ - - else - { - if (ptr[1] == CHAR_LEFT_CURLY_BRACKET) - { - ptr += 2; - if (*ptr == CHAR_RIGHT_CURLY_BRACKET) - { - *errorcodeptr = ERR86; - break; - } - c = 0; - overflow = FALSE; - while (MAX_255(*ptr) && (digitab[*ptr] & ctype_xdigit) != 0) - { - register pcre_uint32 cc = *ptr++; - if (c == 0 && cc == CHAR_0) continue; /* Leading zeroes */ - -#ifdef COMPILE_PCRE32 - if (c >= 0x10000000l) { overflow = TRUE; break; } -#endif - -#ifndef EBCDIC /* ASCII/UTF-8 coding */ - if (cc >= CHAR_a) cc -= 32; /* Convert to upper case */ - c = (c << 4) + cc - ((cc < CHAR_A)? CHAR_0 : (CHAR_A - 10)); -#else /* EBCDIC coding */ - if (cc >= CHAR_a && cc <= CHAR_z) cc += 64; /* Convert to upper case */ - c = (c << 4) + cc - ((cc >= CHAR_0)? CHAR_0 : (CHAR_A - 10)); -#endif - -#if defined COMPILE_PCRE8 - if (c > (utf ? 0x10ffffU : 0xffU)) { overflow = TRUE; break; } -#elif defined COMPILE_PCRE16 - if (c > (utf ? 0x10ffffU : 0xffffU)) { overflow = TRUE; break; } -#elif defined COMPILE_PCRE32 - if (utf && c > 0x10ffffU) { overflow = TRUE; break; } -#endif - } - - if (overflow) - { - while (MAX_255(*ptr) && (digitab[*ptr] & ctype_xdigit) != 0) ptr++; - *errorcodeptr = ERR34; - } - - else if (*ptr == CHAR_RIGHT_CURLY_BRACKET) - { - if (utf && c >= 0xd800 && c <= 0xdfff) *errorcodeptr = ERR73; - } - - /* If the sequence of hex digits does not end with '}', give an error. - We used just to recognize this construct and fall through to the normal - \x handling, but nowadays Perl gives an error, which seems much more - sensible, so we do too. */ - - else *errorcodeptr = ERR79; - } /* End of \x{} processing */ - - /* Read a single-byte hex-defined char (up to two hex digits after \x) */ - - else - { - c = 0; - while (i++ < 2 && MAX_255(ptr[1]) && (digitab[ptr[1]] & ctype_xdigit) != 0) - { - pcre_uint32 cc; /* Some compilers don't like */ - cc = *(++ptr); /* ++ in initializers */ -#ifndef EBCDIC /* ASCII/UTF-8 coding */ - if (cc >= CHAR_a) cc -= 32; /* Convert to upper case */ - c = c * 16 + cc - ((cc < CHAR_A)? CHAR_0 : (CHAR_A - 10)); -#else /* EBCDIC coding */ - if (cc <= CHAR_z) cc += 64; /* Convert to upper case */ - c = c * 16 + cc - ((cc >= CHAR_0)? CHAR_0 : (CHAR_A - 10)); -#endif - } - } /* End of \xdd handling */ - } /* End of Perl-style \x handling */ - break; - - /* For \c, a following letter is upper-cased; then the 0x40 bit is flipped. - An error is given if the byte following \c is not an ASCII character. This - coding is ASCII-specific, but then the whole concept of \cx is - ASCII-specific. (However, an EBCDIC equivalent has now been added.) */ - - case CHAR_c: - c = *(++ptr); - if (c == CHAR_NULL) - { - *errorcodeptr = ERR2; - break; - } -#ifndef EBCDIC /* ASCII/UTF-8 coding */ - if (c > 127) /* Excludes all non-ASCII in either mode */ - { - *errorcodeptr = ERR68; - break; - } - if (c >= CHAR_a && c <= CHAR_z) c -= 32; - c ^= 0x40; -#else /* EBCDIC coding */ - if (c >= CHAR_a && c <= CHAR_z) c += 64; - c ^= 0xC0; -#endif - break; - - /* PCRE_EXTRA enables extensions to Perl in the matter of escapes. Any - other alphanumeric following \ is an error if PCRE_EXTRA was set; - otherwise, for Perl compatibility, it is a literal. This code looks a bit - odd, but there used to be some cases other than the default, and there may - be again in future, so I haven't "optimized" it. */ - - default: - if ((options & PCRE_EXTRA) != 0) switch(c) - { - default: - *errorcodeptr = ERR3; - break; - } - break; - } - } - -/* Perl supports \N{name} for character names, as well as plain \N for "not -newline". PCRE does not support \N{name}. However, it does support -quantification such as \N{2,3}. */ - -if (escape == ESC_N && ptr[1] == CHAR_LEFT_CURLY_BRACKET && - !is_counted_repeat(ptr+2)) - *errorcodeptr = ERR37; - -/* If PCRE_UCP is set, we change the values for \d etc. */ - -if ((options & PCRE_UCP) != 0 && escape >= ESC_D && escape <= ESC_w) - escape += (ESC_DU - ESC_D); - -/* Set the pointer to the final character before returning. */ - -*ptrptr = ptr; -*chptr = c; -return escape; -} - - - -#ifdef SUPPORT_UCP -/************************************************* -* Handle \P and \p * -*************************************************/ - -/* This function is called after \P or \p has been encountered, provided that -PCRE is compiled with support for Unicode properties. On entry, ptrptr is -pointing at the P or p. On exit, it is pointing at the final character of the -escape sequence. - -Argument: - ptrptr points to the pattern position pointer - negptr points to a boolean that is set TRUE for negation else FALSE - ptypeptr points to an unsigned int that is set to the type value - pdataptr points to an unsigned int that is set to the detailed property value - errorcodeptr points to the error code variable - -Returns: TRUE if the type value was found, or FALSE for an invalid type -*/ - -static BOOL -get_ucp(const pcre_uchar **ptrptr, BOOL *negptr, unsigned int *ptypeptr, - unsigned int *pdataptr, int *errorcodeptr) -{ -pcre_uchar c; -int i, bot, top; -const pcre_uchar *ptr = *ptrptr; -pcre_uchar name[32]; - -c = *(++ptr); -if (c == CHAR_NULL) goto ERROR_RETURN; - -*negptr = FALSE; - -/* \P or \p can be followed by a name in {}, optionally preceded by ^ for -negation. */ - -if (c == CHAR_LEFT_CURLY_BRACKET) - { - if (ptr[1] == CHAR_CIRCUMFLEX_ACCENT) - { - *negptr = TRUE; - ptr++; - } - for (i = 0; i < (int)(sizeof(name) / sizeof(pcre_uchar)) - 1; i++) - { - c = *(++ptr); - if (c == CHAR_NULL) goto ERROR_RETURN; - if (c == CHAR_RIGHT_CURLY_BRACKET) break; - name[i] = c; - } - if (c != CHAR_RIGHT_CURLY_BRACKET) goto ERROR_RETURN; - name[i] = 0; - } - -/* Otherwise there is just one following character */ - -else - { - name[0] = c; - name[1] = 0; - } - -*ptrptr = ptr; - -/* Search for a recognized property name using binary chop */ - -bot = 0; -top = PRIV(utt_size); - -while (bot < top) - { - int r; - i = (bot + top) >> 1; - r = STRCMP_UC_C8(name, PRIV(utt_names) + PRIV(utt)[i].name_offset); - if (r == 0) - { - *ptypeptr = PRIV(utt)[i].type; - *pdataptr = PRIV(utt)[i].value; - return TRUE; - } - if (r > 0) bot = i + 1; else top = i; - } - -*errorcodeptr = ERR47; -*ptrptr = ptr; -return FALSE; - -ERROR_RETURN: -*errorcodeptr = ERR46; -*ptrptr = ptr; -return FALSE; -} -#endif - - - -/************************************************* -* Read repeat counts * -*************************************************/ - -/* Read an item of the form {n,m} and return the values. This is called only -after is_counted_repeat() has confirmed that a repeat-count quantifier exists, -so the syntax is guaranteed to be correct, but we need to check the values. - -Arguments: - p pointer to first char after '{' - minp pointer to int for min - maxp pointer to int for max - returned as -1 if no max - errorcodeptr points to error code variable - -Returns: pointer to '}' on success; - current ptr on error, with errorcodeptr set non-zero -*/ - -static const pcre_uchar * -read_repeat_counts(const pcre_uchar *p, int *minp, int *maxp, int *errorcodeptr) -{ -int min = 0; -int max = -1; - -while (IS_DIGIT(*p)) - { - min = min * 10 + (int)(*p++ - CHAR_0); - if (min > 65535) - { - *errorcodeptr = ERR5; - return p; - } - } - -if (*p == CHAR_RIGHT_CURLY_BRACKET) max = min; else - { - if (*(++p) != CHAR_RIGHT_CURLY_BRACKET) - { - max = 0; - while(IS_DIGIT(*p)) - { - max = max * 10 + (int)(*p++ - CHAR_0); - if (max > 65535) - { - *errorcodeptr = ERR5; - return p; - } - } - if (max < min) - { - *errorcodeptr = ERR4; - return p; - } - } - } - -*minp = min; -*maxp = max; -return p; -} - - - -/************************************************* -* Find first significant op code * -*************************************************/ - -/* This is called by several functions that scan a compiled expression looking -for a fixed first character, or an anchoring op code etc. It skips over things -that do not influence this. For some calls, it makes sense to skip negative -forward and all backward assertions, and also the \b assertion; for others it -does not. - -Arguments: - code pointer to the start of the group - skipassert TRUE if certain assertions are to be skipped - -Returns: pointer to the first significant opcode -*/ - -static const pcre_uchar* -first_significant_code(const pcre_uchar *code, BOOL skipassert) -{ -for (;;) - { - switch ((int)*code) - { - case OP_ASSERT_NOT: - case OP_ASSERTBACK: - case OP_ASSERTBACK_NOT: - if (!skipassert) return code; - do code += GET(code, 1); while (*code == OP_ALT); - code += PRIV(OP_lengths)[*code]; - break; - - case OP_WORD_BOUNDARY: - case OP_NOT_WORD_BOUNDARY: - if (!skipassert) return code; - /* Fall through */ - - case OP_CALLOUT: - case OP_CREF: - case OP_DNCREF: - case OP_RREF: - case OP_DNRREF: - case OP_DEF: - code += PRIV(OP_lengths)[*code]; - break; - - default: - return code; - } - } -/* Control never reaches here */ -} - - - -/************************************************* -* Find the fixed length of a branch * -*************************************************/ - -/* Scan a branch and compute the fixed length of subject that will match it, -if the length is fixed. This is needed for dealing with backward assertions. -In UTF8 mode, the result is in characters rather than bytes. The branch is -temporarily terminated with OP_END when this function is called. - -This function is called when a backward assertion is encountered, so that if it -fails, the error message can point to the correct place in the pattern. -However, we cannot do this when the assertion contains subroutine calls, -because they can be forward references. We solve this by remembering this case -and doing the check at the end; a flag specifies which mode we are running in. - -Arguments: - code points to the start of the pattern (the bracket) - utf TRUE in UTF-8 / UTF-16 / UTF-32 mode - atend TRUE if called when the pattern is complete - cd the "compile data" structure - -Returns: the fixed length, - or -1 if there is no fixed length, - or -2 if \C was encountered (in UTF-8 mode only) - or -3 if an OP_RECURSE item was encountered and atend is FALSE - or -4 if an unknown opcode was encountered (internal error) -*/ - -static int -find_fixedlength(pcre_uchar *code, BOOL utf, BOOL atend, compile_data *cd) -{ -int length = -1; - -register int branchlength = 0; -register pcre_uchar *cc = code + 1 + LINK_SIZE; - -/* Scan along the opcodes for this branch. If we get to the end of the -branch, check the length against that of the other branches. */ - -for (;;) - { - int d; - pcre_uchar *ce, *cs; - register pcre_uchar op = *cc; - - switch (op) - { - /* We only need to continue for OP_CBRA (normal capturing bracket) and - OP_BRA (normal non-capturing bracket) because the other variants of these - opcodes are all concerned with unlimited repeated groups, which of course - are not of fixed length. */ - - case OP_CBRA: - case OP_BRA: - case OP_ONCE: - case OP_ONCE_NC: - case OP_COND: - d = find_fixedlength(cc + ((op == OP_CBRA)? IMM2_SIZE : 0), utf, atend, cd); - if (d < 0) return d; - branchlength += d; - do cc += GET(cc, 1); while (*cc == OP_ALT); - cc += 1 + LINK_SIZE; - break; - - /* Reached end of a branch; if it's a ket it is the end of a nested call. - If it's ALT it is an alternation in a nested call. An ACCEPT is effectively - an ALT. If it is END it's the end of the outer call. All can be handled by - the same code. Note that we must not include the OP_KETRxxx opcodes here, - because they all imply an unlimited repeat. */ - - case OP_ALT: - case OP_KET: - case OP_END: - case OP_ACCEPT: - case OP_ASSERT_ACCEPT: - if (length < 0) length = branchlength; - else if (length != branchlength) return -1; - if (*cc != OP_ALT) return length; - cc += 1 + LINK_SIZE; - branchlength = 0; - break; - - /* A true recursion implies not fixed length, but a subroutine call may - be OK. If the subroutine is a forward reference, we can't deal with - it until the end of the pattern, so return -3. */ - - case OP_RECURSE: - if (!atend) return -3; - cs = ce = (pcre_uchar *)cd->start_code + GET(cc, 1); /* Start subpattern */ - do ce += GET(ce, 1); while (*ce == OP_ALT); /* End subpattern */ - if (cc > cs && cc < ce) return -1; /* Recursion */ - d = find_fixedlength(cs + IMM2_SIZE, utf, atend, cd); - if (d < 0) return d; - branchlength += d; - cc += 1 + LINK_SIZE; - break; - - /* Skip over assertive subpatterns */ - - case OP_ASSERT: - case OP_ASSERT_NOT: - case OP_ASSERTBACK: - case OP_ASSERTBACK_NOT: - do cc += GET(cc, 1); while (*cc == OP_ALT); - cc += PRIV(OP_lengths)[*cc]; - break; - - /* Skip over things that don't match chars */ - - case OP_MARK: - case OP_PRUNE_ARG: - case OP_SKIP_ARG: - case OP_THEN_ARG: - cc += cc[1] + PRIV(OP_lengths)[*cc]; - break; - - case OP_CALLOUT: - case OP_CIRC: - case OP_CIRCM: - case OP_CLOSE: - case OP_COMMIT: - case OP_CREF: - case OP_DEF: - case OP_DNCREF: - case OP_DNRREF: - case OP_DOLL: - case OP_DOLLM: - case OP_EOD: - case OP_EODN: - case OP_FAIL: - case OP_NOT_WORD_BOUNDARY: - case OP_PRUNE: - case OP_REVERSE: - case OP_RREF: - case OP_SET_SOM: - case OP_SKIP: - case OP_SOD: - case OP_SOM: - case OP_THEN: - case OP_WORD_BOUNDARY: - cc += PRIV(OP_lengths)[*cc]; - break; - - /* Handle literal characters */ - - case OP_CHAR: - case OP_CHARI: - case OP_NOT: - case OP_NOTI: - branchlength++; - cc += 2; -#ifdef SUPPORT_UTF - if (utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]); -#endif - break; - - /* Handle exact repetitions. The count is already in characters, but we - need to skip over a multibyte character in UTF8 mode. */ - - case OP_EXACT: - case OP_EXACTI: - case OP_NOTEXACT: - case OP_NOTEXACTI: - branchlength += (int)GET2(cc,1); - cc += 2 + IMM2_SIZE; -#ifdef SUPPORT_UTF - if (utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]); -#endif - break; - - case OP_TYPEEXACT: - branchlength += GET2(cc,1); - if (cc[1 + IMM2_SIZE] == OP_PROP || cc[1 + IMM2_SIZE] == OP_NOTPROP) - cc += 2; - cc += 1 + IMM2_SIZE + 1; - break; - - /* Handle single-char matchers */ - - case OP_PROP: - case OP_NOTPROP: - cc += 2; - /* Fall through */ - - case OP_HSPACE: - case OP_VSPACE: - case OP_NOT_HSPACE: - case OP_NOT_VSPACE: - case OP_NOT_DIGIT: - case OP_DIGIT: - case OP_NOT_WHITESPACE: - case OP_WHITESPACE: - case OP_NOT_WORDCHAR: - case OP_WORDCHAR: - case OP_ANY: - case OP_ALLANY: - branchlength++; - cc++; - break; - - /* The single-byte matcher isn't allowed. This only happens in UTF-8 mode; - otherwise \C is coded as OP_ALLANY. */ - - case OP_ANYBYTE: - return -2; - - /* Check a class for variable quantification */ - - case OP_CLASS: - case OP_NCLASS: -#if defined SUPPORT_UTF || defined COMPILE_PCRE16 || defined COMPILE_PCRE32 - case OP_XCLASS: - /* The original code caused an unsigned overflow in 64 bit systems, - so now we use a conditional statement. */ - if (op == OP_XCLASS) - cc += GET(cc, 1); - else - cc += PRIV(OP_lengths)[OP_CLASS]; -#else - cc += PRIV(OP_lengths)[OP_CLASS]; -#endif - - switch (*cc) - { - case OP_CRSTAR: - case OP_CRMINSTAR: - case OP_CRPLUS: - case OP_CRMINPLUS: - case OP_CRQUERY: - case OP_CRMINQUERY: - case OP_CRPOSSTAR: - case OP_CRPOSPLUS: - case OP_CRPOSQUERY: - return -1; - - case OP_CRRANGE: - case OP_CRMINRANGE: - case OP_CRPOSRANGE: - if (GET2(cc,1) != GET2(cc,1+IMM2_SIZE)) return -1; - branchlength += (int)GET2(cc,1); - cc += 1 + 2 * IMM2_SIZE; - break; - - default: - branchlength++; - } - break; - - /* Anything else is variable length */ - - case OP_ANYNL: - case OP_BRAMINZERO: - case OP_BRAPOS: - case OP_BRAPOSZERO: - case OP_BRAZERO: - case OP_CBRAPOS: - case OP_EXTUNI: - case OP_KETRMAX: - case OP_KETRMIN: - case OP_KETRPOS: - case OP_MINPLUS: - case OP_MINPLUSI: - case OP_MINQUERY: - case OP_MINQUERYI: - case OP_MINSTAR: - case OP_MINSTARI: - case OP_MINUPTO: - case OP_MINUPTOI: - case OP_NOTMINPLUS: - case OP_NOTMINPLUSI: - case OP_NOTMINQUERY: - case OP_NOTMINQUERYI: - case OP_NOTMINSTAR: - case OP_NOTMINSTARI: - case OP_NOTMINUPTO: - case OP_NOTMINUPTOI: - case OP_NOTPLUS: - case OP_NOTPLUSI: - case OP_NOTPOSPLUS: - case OP_NOTPOSPLUSI: - case OP_NOTPOSQUERY: - case OP_NOTPOSQUERYI: - case OP_NOTPOSSTAR: - case OP_NOTPOSSTARI: - case OP_NOTPOSUPTO: - case OP_NOTPOSUPTOI: - case OP_NOTQUERY: - case OP_NOTQUERYI: - case OP_NOTSTAR: - case OP_NOTSTARI: - case OP_NOTUPTO: - case OP_NOTUPTOI: - case OP_PLUS: - case OP_PLUSI: - case OP_POSPLUS: - case OP_POSPLUSI: - case OP_POSQUERY: - case OP_POSQUERYI: - case OP_POSSTAR: - case OP_POSSTARI: - case OP_POSUPTO: - case OP_POSUPTOI: - case OP_QUERY: - case OP_QUERYI: - case OP_REF: - case OP_REFI: - case OP_DNREF: - case OP_DNREFI: - case OP_SBRA: - case OP_SBRAPOS: - case OP_SCBRA: - case OP_SCBRAPOS: - case OP_SCOND: - case OP_SKIPZERO: - case OP_STAR: - case OP_STARI: - case OP_TYPEMINPLUS: - case OP_TYPEMINQUERY: - case OP_TYPEMINSTAR: - case OP_TYPEMINUPTO: - case OP_TYPEPLUS: - case OP_TYPEPOSPLUS: - case OP_TYPEPOSQUERY: - case OP_TYPEPOSSTAR: - case OP_TYPEPOSUPTO: - case OP_TYPEQUERY: - case OP_TYPESTAR: - case OP_TYPEUPTO: - case OP_UPTO: - case OP_UPTOI: - return -1; - - /* Catch unrecognized opcodes so that when new ones are added they - are not forgotten, as has happened in the past. */ - - default: - return -4; - } - } -/* Control never gets here */ -} - - - -/************************************************* -* Scan compiled regex for specific bracket * -*************************************************/ - -/* This little function scans through a compiled pattern until it finds a -capturing bracket with the given number, or, if the number is negative, an -instance of OP_REVERSE for a lookbehind. The function is global in the C sense -so that it can be called from pcre_study() when finding the minimum matching -length. - -Arguments: - code points to start of expression - utf TRUE in UTF-8 / UTF-16 / UTF-32 mode - number the required bracket number or negative to find a lookbehind - -Returns: pointer to the opcode for the bracket, or NULL if not found -*/ - -const pcre_uchar * -PRIV(find_bracket)(const pcre_uchar *code, BOOL utf, int number) -{ -for (;;) - { - register pcre_uchar c = *code; - - if (c == OP_END) return NULL; - - /* XCLASS is used for classes that cannot be represented just by a bit - map. This includes negated single high-valued characters. The length in - the table is zero; the actual length is stored in the compiled code. */ - - if (c == OP_XCLASS) code += GET(code, 1); - - /* Handle recursion */ - - else if (c == OP_REVERSE) - { - if (number < 0) return (pcre_uchar *)code; - code += PRIV(OP_lengths)[c]; - } - - /* Handle capturing bracket */ - - else if (c == OP_CBRA || c == OP_SCBRA || - c == OP_CBRAPOS || c == OP_SCBRAPOS) - { - int n = (int)GET2(code, 1+LINK_SIZE); - if (n == number) return (pcre_uchar *)code; - code += PRIV(OP_lengths)[c]; - } - - /* Otherwise, we can get the item's length from the table, except that for - repeated character types, we have to test for \p and \P, which have an extra - two bytes of parameters, and for MARK/PRUNE/SKIP/THEN with an argument, we - must add in its length. */ - - else - { - switch(c) - { - case OP_TYPESTAR: - case OP_TYPEMINSTAR: - case OP_TYPEPLUS: - case OP_TYPEMINPLUS: - case OP_TYPEQUERY: - case OP_TYPEMINQUERY: - case OP_TYPEPOSSTAR: - case OP_TYPEPOSPLUS: - case OP_TYPEPOSQUERY: - if (code[1] == OP_PROP || code[1] == OP_NOTPROP) code += 2; - break; - - case OP_TYPEUPTO: - case OP_TYPEMINUPTO: - case OP_TYPEEXACT: - case OP_TYPEPOSUPTO: - if (code[1 + IMM2_SIZE] == OP_PROP || code[1 + IMM2_SIZE] == OP_NOTPROP) - code += 2; - break; - - case OP_MARK: - case OP_PRUNE_ARG: - case OP_SKIP_ARG: - case OP_THEN_ARG: - code += code[1]; - break; - } - - /* Add in the fixed length from the table */ - - code += PRIV(OP_lengths)[c]; - - /* In UTF-8 mode, opcodes that are followed by a character may be followed by - a multi-byte character. The length in the table is a minimum, so we have to - arrange to skip the extra bytes. */ - -#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 - if (utf) switch(c) - { - case OP_CHAR: - case OP_CHARI: - case OP_EXACT: - case OP_EXACTI: - case OP_UPTO: - case OP_UPTOI: - case OP_MINUPTO: - case OP_MINUPTOI: - case OP_POSUPTO: - case OP_POSUPTOI: - case OP_STAR: - case OP_STARI: - case OP_MINSTAR: - case OP_MINSTARI: - case OP_POSSTAR: - case OP_POSSTARI: - case OP_PLUS: - case OP_PLUSI: - case OP_MINPLUS: - case OP_MINPLUSI: - case OP_POSPLUS: - case OP_POSPLUSI: - case OP_QUERY: - case OP_QUERYI: - case OP_MINQUERY: - case OP_MINQUERYI: - case OP_POSQUERY: - case OP_POSQUERYI: - if (HAS_EXTRALEN(code[-1])) code += GET_EXTRALEN(code[-1]); - break; - } -#else - (void)(utf); /* Keep compiler happy by referencing function argument */ -#endif - } - } -} - - - -/************************************************* -* Scan compiled regex for recursion reference * -*************************************************/ - -/* This little function scans through a compiled pattern until it finds an -instance of OP_RECURSE. - -Arguments: - code points to start of expression - utf TRUE in UTF-8 / UTF-16 / UTF-32 mode - -Returns: pointer to the opcode for OP_RECURSE, or NULL if not found -*/ - -static const pcre_uchar * -find_recurse(const pcre_uchar *code, BOOL utf) -{ -for (;;) - { - register pcre_uchar c = *code; - if (c == OP_END) return NULL; - if (c == OP_RECURSE) return code; - - /* XCLASS is used for classes that cannot be represented just by a bit - map. This includes negated single high-valued characters. The length in - the table is zero; the actual length is stored in the compiled code. */ - - if (c == OP_XCLASS) code += GET(code, 1); - - /* Otherwise, we can get the item's length from the table, except that for - repeated character types, we have to test for \p and \P, which have an extra - two bytes of parameters, and for MARK/PRUNE/SKIP/THEN with an argument, we - must add in its length. */ - - else - { - switch(c) - { - case OP_TYPESTAR: - case OP_TYPEMINSTAR: - case OP_TYPEPLUS: - case OP_TYPEMINPLUS: - case OP_TYPEQUERY: - case OP_TYPEMINQUERY: - case OP_TYPEPOSSTAR: - case OP_TYPEPOSPLUS: - case OP_TYPEPOSQUERY: - if (code[1] == OP_PROP || code[1] == OP_NOTPROP) code += 2; - break; - - case OP_TYPEPOSUPTO: - case OP_TYPEUPTO: - case OP_TYPEMINUPTO: - case OP_TYPEEXACT: - if (code[1 + IMM2_SIZE] == OP_PROP || code[1 + IMM2_SIZE] == OP_NOTPROP) - code += 2; - break; - - case OP_MARK: - case OP_PRUNE_ARG: - case OP_SKIP_ARG: - case OP_THEN_ARG: - code += code[1]; - break; - } - - /* Add in the fixed length from the table */ - - code += PRIV(OP_lengths)[c]; - - /* In UTF-8 mode, opcodes that are followed by a character may be followed - by a multi-byte character. The length in the table is a minimum, so we have - to arrange to skip the extra bytes. */ - -#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 - if (utf) switch(c) - { - case OP_CHAR: - case OP_CHARI: - case OP_NOT: - case OP_NOTI: - case OP_EXACT: - case OP_EXACTI: - case OP_NOTEXACT: - case OP_NOTEXACTI: - case OP_UPTO: - case OP_UPTOI: - case OP_NOTUPTO: - case OP_NOTUPTOI: - case OP_MINUPTO: - case OP_MINUPTOI: - case OP_NOTMINUPTO: - case OP_NOTMINUPTOI: - case OP_POSUPTO: - case OP_POSUPTOI: - case OP_NOTPOSUPTO: - case OP_NOTPOSUPTOI: - case OP_STAR: - case OP_STARI: - case OP_NOTSTAR: - case OP_NOTSTARI: - case OP_MINSTAR: - case OP_MINSTARI: - case OP_NOTMINSTAR: - case OP_NOTMINSTARI: - case OP_POSSTAR: - case OP_POSSTARI: - case OP_NOTPOSSTAR: - case OP_NOTPOSSTARI: - case OP_PLUS: - case OP_PLUSI: - case OP_NOTPLUS: - case OP_NOTPLUSI: - case OP_MINPLUS: - case OP_MINPLUSI: - case OP_NOTMINPLUS: - case OP_NOTMINPLUSI: - case OP_POSPLUS: - case OP_POSPLUSI: - case OP_NOTPOSPLUS: - case OP_NOTPOSPLUSI: - case OP_QUERY: - case OP_QUERYI: - case OP_NOTQUERY: - case OP_NOTQUERYI: - case OP_MINQUERY: - case OP_MINQUERYI: - case OP_NOTMINQUERY: - case OP_NOTMINQUERYI: - case OP_POSQUERY: - case OP_POSQUERYI: - case OP_NOTPOSQUERY: - case OP_NOTPOSQUERYI: - if (HAS_EXTRALEN(code[-1])) code += GET_EXTRALEN(code[-1]); - break; - } -#else - (void)(utf); /* Keep compiler happy by referencing function argument */ -#endif - } - } -} - - - -/************************************************* -* Scan compiled branch for non-emptiness * -*************************************************/ - -/* This function scans through a branch of a compiled pattern to see whether it -can match the empty string or not. It is called from could_be_empty() -below and from compile_branch() when checking for an unlimited repeat of a -group that can match nothing. Note that first_significant_code() skips over -backward and negative forward assertions when its final argument is TRUE. If we -hit an unclosed bracket, we return "empty" - this means we've struck an inner -bracket whose current branch will already have been scanned. - -Arguments: - code points to start of search - endcode points to where to stop - utf TRUE if in UTF-8 / UTF-16 / UTF-32 mode - cd contains pointers to tables etc. - recurses chain of recurse_check to catch mutual recursion - -Returns: TRUE if what is matched could be empty -*/ - -typedef struct recurse_check { - struct recurse_check *prev; - const pcre_uchar *group; -} recurse_check; - -static BOOL -could_be_empty_branch(const pcre_uchar *code, const pcre_uchar *endcode, - BOOL utf, compile_data *cd, recurse_check *recurses) -{ -register pcre_uchar c; -recurse_check this_recurse; - -for (code = first_significant_code(code + PRIV(OP_lengths)[*code], TRUE); - code < endcode; - code = first_significant_code(code + PRIV(OP_lengths)[c], TRUE)) - { - const pcre_uchar *ccode; - - c = *code; - - /* Skip over forward assertions; the other assertions are skipped by - first_significant_code() with a TRUE final argument. */ - - if (c == OP_ASSERT) - { - do code += GET(code, 1); while (*code == OP_ALT); - c = *code; - continue; - } - - /* For a recursion/subroutine call, if its end has been reached, which - implies a backward reference subroutine call, we can scan it. If it's a - forward reference subroutine call, we can't. To detect forward reference - we have to scan up the list that is kept in the workspace. This function is - called only when doing the real compile, not during the pre-compile that - measures the size of the compiled pattern. */ - - if (c == OP_RECURSE) - { - const pcre_uchar *scode = cd->start_code + GET(code, 1); - const pcre_uchar *endgroup = scode; - BOOL empty_branch; - - /* Test for forward reference or uncompleted reference. This is disabled - when called to scan a completed pattern by setting cd->start_workspace to - NULL. */ - - if (cd->start_workspace != NULL) - { - const pcre_uchar *tcode; - for (tcode = cd->start_workspace; tcode < cd->hwm; tcode += LINK_SIZE) - if ((int)GET(tcode, 0) == (int)(code + 1 - cd->start_code)) return TRUE; - if (GET(scode, 1) == 0) return TRUE; /* Unclosed */ - } - - /* If the reference is to a completed group, we need to detect whether this - is a recursive call, as otherwise there will be an infinite loop. If it is - a recursion, just skip over it. Simple recursions are easily detected. For - mutual recursions we keep a chain on the stack. */ - - do endgroup += GET(endgroup, 1); while (*endgroup == OP_ALT); - if (code >= scode && code <= endgroup) continue; /* Simple recursion */ - else - { - recurse_check *r = recurses; - for (r = recurses; r != NULL; r = r->prev) - if (r->group == scode) break; - if (r != NULL) continue; /* Mutual recursion */ - } - - /* Completed reference; scan the referenced group, remembering it on the - stack chain to detect mutual recursions. */ - - empty_branch = FALSE; - this_recurse.prev = recurses; - this_recurse.group = scode; - - do - { - if (could_be_empty_branch(scode, endcode, utf, cd, &this_recurse)) - { - empty_branch = TRUE; - break; - } - scode += GET(scode, 1); - } - while (*scode == OP_ALT); - - if (!empty_branch) return FALSE; /* All branches are non-empty */ - continue; - } - - /* Groups with zero repeats can of course be empty; skip them. */ - - if (c == OP_BRAZERO || c == OP_BRAMINZERO || c == OP_SKIPZERO || - c == OP_BRAPOSZERO) - { - code += PRIV(OP_lengths)[c]; - do code += GET(code, 1); while (*code == OP_ALT); - c = *code; - continue; - } - - /* A nested group that is already marked as "could be empty" can just be - skipped. */ - - if (c == OP_SBRA || c == OP_SBRAPOS || - c == OP_SCBRA || c == OP_SCBRAPOS) - { - do code += GET(code, 1); while (*code == OP_ALT); - c = *code; - continue; - } - - /* For other groups, scan the branches. */ - - if (c == OP_BRA || c == OP_BRAPOS || - c == OP_CBRA || c == OP_CBRAPOS || - c == OP_ONCE || c == OP_ONCE_NC || - c == OP_COND) - { - BOOL empty_branch; - if (GET(code, 1) == 0) return TRUE; /* Hit unclosed bracket */ - - /* If a conditional group has only one branch, there is a second, implied, - empty branch, so just skip over the conditional, because it could be empty. - Otherwise, scan the individual branches of the group. */ - - if (c == OP_COND && code[GET(code, 1)] != OP_ALT) - code += GET(code, 1); - else - { - empty_branch = FALSE; - do - { - if (!empty_branch && could_be_empty_branch(code, endcode, utf, cd, NULL)) - empty_branch = TRUE; - code += GET(code, 1); - } - while (*code == OP_ALT); - if (!empty_branch) return FALSE; /* All branches are non-empty */ - } - - c = *code; - continue; - } - - /* Handle the other opcodes */ - - switch (c) - { - /* Check for quantifiers after a class. XCLASS is used for classes that - cannot be represented just by a bit map. This includes negated single - high-valued characters. The length in PRIV(OP_lengths)[] is zero; the - actual length is stored in the compiled code, so we must update "code" - here. */ - -#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 - case OP_XCLASS: - ccode = code += GET(code, 1); - goto CHECK_CLASS_REPEAT; -#endif - - case OP_CLASS: - case OP_NCLASS: - ccode = code + PRIV(OP_lengths)[OP_CLASS]; - -#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 - CHECK_CLASS_REPEAT: -#endif - - switch (*ccode) - { - case OP_CRSTAR: /* These could be empty; continue */ - case OP_CRMINSTAR: - case OP_CRQUERY: - case OP_CRMINQUERY: - case OP_CRPOSSTAR: - case OP_CRPOSQUERY: - break; - - default: /* Non-repeat => class must match */ - case OP_CRPLUS: /* These repeats aren't empty */ - case OP_CRMINPLUS: - case OP_CRPOSPLUS: - return FALSE; - - case OP_CRRANGE: - case OP_CRMINRANGE: - case OP_CRPOSRANGE: - if (GET2(ccode, 1) > 0) return FALSE; /* Minimum > 0 */ - break; - } - break; - - /* Opcodes that must match a character */ - - case OP_ANY: - case OP_ALLANY: - case OP_ANYBYTE: - - case OP_PROP: - case OP_NOTPROP: - case OP_ANYNL: - - case OP_NOT_HSPACE: - case OP_HSPACE: - case OP_NOT_VSPACE: - case OP_VSPACE: - case OP_EXTUNI: - - case OP_NOT_DIGIT: - case OP_DIGIT: - case OP_NOT_WHITESPACE: - case OP_WHITESPACE: - case OP_NOT_WORDCHAR: - case OP_WORDCHAR: - - case OP_CHAR: - case OP_CHARI: - case OP_NOT: - case OP_NOTI: - - case OP_PLUS: - case OP_PLUSI: - case OP_MINPLUS: - case OP_MINPLUSI: - - case OP_NOTPLUS: - case OP_NOTPLUSI: - case OP_NOTMINPLUS: - case OP_NOTMINPLUSI: - - case OP_POSPLUS: - case OP_POSPLUSI: - case OP_NOTPOSPLUS: - case OP_NOTPOSPLUSI: - - case OP_EXACT: - case OP_EXACTI: - case OP_NOTEXACT: - case OP_NOTEXACTI: - - case OP_TYPEPLUS: - case OP_TYPEMINPLUS: - case OP_TYPEPOSPLUS: - case OP_TYPEEXACT: - - return FALSE; - - /* These are going to continue, as they may be empty, but we have to - fudge the length for the \p and \P cases. */ - - case OP_TYPESTAR: - case OP_TYPEMINSTAR: - case OP_TYPEPOSSTAR: - case OP_TYPEQUERY: - case OP_TYPEMINQUERY: - case OP_TYPEPOSQUERY: - if (code[1] == OP_PROP || code[1] == OP_NOTPROP) code += 2; - break; - - /* Same for these */ - - case OP_TYPEUPTO: - case OP_TYPEMINUPTO: - case OP_TYPEPOSUPTO: - if (code[1 + IMM2_SIZE] == OP_PROP || code[1 + IMM2_SIZE] == OP_NOTPROP) - code += 2; - break; - - /* End of branch */ - - case OP_KET: - case OP_KETRMAX: - case OP_KETRMIN: - case OP_KETRPOS: - case OP_ALT: - return TRUE; - - /* In UTF-8 mode, STAR, MINSTAR, POSSTAR, QUERY, MINQUERY, POSQUERY, UPTO, - MINUPTO, and POSUPTO and their caseless and negative versions may be - followed by a multibyte character. */ - -#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 - case OP_STAR: - case OP_STARI: - case OP_NOTSTAR: - case OP_NOTSTARI: - - case OP_MINSTAR: - case OP_MINSTARI: - case OP_NOTMINSTAR: - case OP_NOTMINSTARI: - - case OP_POSSTAR: - case OP_POSSTARI: - case OP_NOTPOSSTAR: - case OP_NOTPOSSTARI: - - case OP_QUERY: - case OP_QUERYI: - case OP_NOTQUERY: - case OP_NOTQUERYI: - - case OP_MINQUERY: - case OP_MINQUERYI: - case OP_NOTMINQUERY: - case OP_NOTMINQUERYI: - - case OP_POSQUERY: - case OP_POSQUERYI: - case OP_NOTPOSQUERY: - case OP_NOTPOSQUERYI: - - if (utf && HAS_EXTRALEN(code[1])) code += GET_EXTRALEN(code[1]); - break; - - case OP_UPTO: - case OP_UPTOI: - case OP_NOTUPTO: - case OP_NOTUPTOI: - - case OP_MINUPTO: - case OP_MINUPTOI: - case OP_NOTMINUPTO: - case OP_NOTMINUPTOI: - - case OP_POSUPTO: - case OP_POSUPTOI: - case OP_NOTPOSUPTO: - case OP_NOTPOSUPTOI: - - if (utf && HAS_EXTRALEN(code[1 + IMM2_SIZE])) code += GET_EXTRALEN(code[1 + IMM2_SIZE]); - break; -#endif - - /* MARK, and PRUNE/SKIP/THEN with an argument must skip over the argument - string. */ - - case OP_MARK: - case OP_PRUNE_ARG: - case OP_SKIP_ARG: - case OP_THEN_ARG: - code += code[1]; - break; - - /* None of the remaining opcodes are required to match a character. */ - - default: - break; - } - } - -return TRUE; -} - - - -/************************************************* -* Scan compiled regex for non-emptiness * -*************************************************/ - -/* This function is called to check for left recursive calls. We want to check -the current branch of the current pattern to see if it could match the empty -string. If it could, we must look outwards for branches at other levels, -stopping when we pass beyond the bracket which is the subject of the recursion. -This function is called only during the real compile, not during the -pre-compile. - -Arguments: - code points to start of the recursion - endcode points to where to stop (current RECURSE item) - bcptr points to the chain of current (unclosed) branch starts - utf TRUE if in UTF-8 / UTF-16 / UTF-32 mode - cd pointers to tables etc - -Returns: TRUE if what is matched could be empty -*/ - -static BOOL -could_be_empty(const pcre_uchar *code, const pcre_uchar *endcode, - branch_chain *bcptr, BOOL utf, compile_data *cd) -{ -while (bcptr != NULL && bcptr->current_branch >= code) - { - if (!could_be_empty_branch(bcptr->current_branch, endcode, utf, cd, NULL)) - return FALSE; - bcptr = bcptr->outer; - } -return TRUE; -} - - - -/************************************************* -* Base opcode of repeated opcodes * -*************************************************/ - -/* Returns the base opcode for repeated single character type opcodes. If the -opcode is not a repeated character type, it returns with the original value. - -Arguments: c opcode -Returns: base opcode for the type -*/ - -static pcre_uchar -get_repeat_base(pcre_uchar c) -{ -return (c > OP_TYPEPOSUPTO)? c : - (c >= OP_TYPESTAR)? OP_TYPESTAR : - (c >= OP_NOTSTARI)? OP_NOTSTARI : - (c >= OP_NOTSTAR)? OP_NOTSTAR : - (c >= OP_STARI)? OP_STARI : - OP_STAR; -} - - - -#ifdef SUPPORT_UCP -/************************************************* -* Check a character and a property * -*************************************************/ - -/* This function is called by check_auto_possessive() when a property item -is adjacent to a fixed character. - -Arguments: - c the character - ptype the property type - pdata the data for the type - negated TRUE if it's a negated property (\P or \p{^) - -Returns: TRUE if auto-possessifying is OK -*/ - -static BOOL -check_char_prop(pcre_uint32 c, unsigned int ptype, unsigned int pdata, - BOOL negated) -{ -const pcre_uint32 *p; -const ucd_record *prop = GET_UCD(c); - -switch(ptype) - { - case PT_LAMP: - return (prop->chartype == ucp_Lu || - prop->chartype == ucp_Ll || - prop->chartype == ucp_Lt) == negated; - - case PT_GC: - return (pdata == PRIV(ucp_gentype)[prop->chartype]) == negated; - - case PT_PC: - return (pdata == prop->chartype) == negated; - - case PT_SC: - return (pdata == prop->script) == negated; - - /* These are specials */ - - case PT_ALNUM: - return (PRIV(ucp_gentype)[prop->chartype] == ucp_L || - PRIV(ucp_gentype)[prop->chartype] == ucp_N) == negated; - - /* Perl space used to exclude VT, but from Perl 5.18 it is included, which - means that Perl space and POSIX space are now identical. PCRE was changed - at release 8.34. */ - - case PT_SPACE: /* Perl space */ - case PT_PXSPACE: /* POSIX space */ - switch(c) - { - HSPACE_CASES: - VSPACE_CASES: - return negated; - - default: - return (PRIV(ucp_gentype)[prop->chartype] == ucp_Z) == negated; - } - break; /* Control never reaches here */ - - case PT_WORD: - return (PRIV(ucp_gentype)[prop->chartype] == ucp_L || - PRIV(ucp_gentype)[prop->chartype] == ucp_N || - c == CHAR_UNDERSCORE) == negated; - - case PT_CLIST: - p = PRIV(ucd_caseless_sets) + prop->caseset; - for (;;) - { - if (c < *p) return !negated; - if (c == *p++) return negated; - } - break; /* Control never reaches here */ - } - -return FALSE; -} -#endif /* SUPPORT_UCP */ - - - -/************************************************* -* Fill the character property list * -*************************************************/ - -/* Checks whether the code points to an opcode that can take part in auto- -possessification, and if so, fills a list with its properties. - -Arguments: - code points to start of expression - utf TRUE if in UTF-8 / UTF-16 / UTF-32 mode - fcc points to case-flipping table - list points to output list - list[0] will be filled with the opcode - list[1] will be non-zero if this opcode - can match an empty character string - list[2..7] depends on the opcode - -Returns: points to the start of the next opcode if *code is accepted - NULL if *code is not accepted -*/ - -static const pcre_uchar * -get_chr_property_list(const pcre_uchar *code, BOOL utf, - const pcre_uint8 *fcc, pcre_uint32 *list) -{ -pcre_uchar c = *code; -pcre_uchar base; -const pcre_uchar *end; -pcre_uint32 chr; - -#ifdef SUPPORT_UCP -pcre_uint32 *clist_dest; -const pcre_uint32 *clist_src; -#else -utf = utf; /* Suppress "unused parameter" compiler warning */ -#endif - -list[0] = c; -list[1] = FALSE; -code++; - -if (c >= OP_STAR && c <= OP_TYPEPOSUPTO) - { - base = get_repeat_base(c); - c -= (base - OP_STAR); - - if (c == OP_UPTO || c == OP_MINUPTO || c == OP_EXACT || c == OP_POSUPTO) - code += IMM2_SIZE; - - list[1] = (c != OP_PLUS && c != OP_MINPLUS && c != OP_EXACT && c != OP_POSPLUS); - - switch(base) - { - case OP_STAR: - list[0] = OP_CHAR; - break; - - case OP_STARI: - list[0] = OP_CHARI; - break; - - case OP_NOTSTAR: - list[0] = OP_NOT; - break; - - case OP_NOTSTARI: - list[0] = OP_NOTI; - break; - - case OP_TYPESTAR: - list[0] = *code; - code++; - break; - } - c = list[0]; - } - -switch(c) - { - case OP_NOT_DIGIT: - case OP_DIGIT: - case OP_NOT_WHITESPACE: - case OP_WHITESPACE: - case OP_NOT_WORDCHAR: - case OP_WORDCHAR: - case OP_ANY: - case OP_ALLANY: - case OP_ANYNL: - case OP_NOT_HSPACE: - case OP_HSPACE: - case OP_NOT_VSPACE: - case OP_VSPACE: - case OP_EXTUNI: - case OP_EODN: - case OP_EOD: - case OP_DOLL: - case OP_DOLLM: - return code; - - case OP_CHAR: - case OP_NOT: - GETCHARINCTEST(chr, code); - list[2] = chr; - list[3] = NOTACHAR; - return code; - - case OP_CHARI: - case OP_NOTI: - list[0] = (c == OP_CHARI) ? OP_CHAR : OP_NOT; - GETCHARINCTEST(chr, code); - list[2] = chr; - -#ifdef SUPPORT_UCP - if (chr < 128 || (chr < 256 && !utf)) - list[3] = fcc[chr]; - else - list[3] = UCD_OTHERCASE(chr); -#elif defined SUPPORT_UTF || !defined COMPILE_PCRE8 - list[3] = (chr < 256) ? fcc[chr] : chr; -#else - list[3] = fcc[chr]; -#endif - - /* The othercase might be the same value. */ - - if (chr == list[3]) - list[3] = NOTACHAR; - else - list[4] = NOTACHAR; - return code; - -#ifdef SUPPORT_UCP - case OP_PROP: - case OP_NOTPROP: - if (code[0] != PT_CLIST) - { - list[2] = code[0]; - list[3] = code[1]; - return code + 2; - } - - /* Convert only if we have enough space. */ - - clist_src = PRIV(ucd_caseless_sets) + code[1]; - clist_dest = list + 2; - code += 2; - - do { - if (clist_dest >= list + 8) - { - /* Early return if there is not enough space. This should never - happen, since all clists are shorter than 5 character now. */ - list[2] = code[0]; - list[3] = code[1]; - return code; - } - *clist_dest++ = *clist_src; - } - while(*clist_src++ != NOTACHAR); - - /* All characters are stored. The terminating NOTACHAR - is copied form the clist itself. */ - - list[0] = (c == OP_PROP) ? OP_CHAR : OP_NOT; - return code; -#endif - - case OP_NCLASS: - case OP_CLASS: -#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 - case OP_XCLASS: - if (c == OP_XCLASS) - end = code + GET(code, 0) - 1; - else -#endif - end = code + 32 / sizeof(pcre_uchar); - - switch(*end) - { - case OP_CRSTAR: - case OP_CRMINSTAR: - case OP_CRQUERY: - case OP_CRMINQUERY: - case OP_CRPOSSTAR: - case OP_CRPOSQUERY: - list[1] = TRUE; - end++; - break; - - case OP_CRPLUS: - case OP_CRMINPLUS: - case OP_CRPOSPLUS: - end++; - break; - - case OP_CRRANGE: - case OP_CRMINRANGE: - case OP_CRPOSRANGE: - list[1] = (GET2(end, 1) == 0); - end += 1 + 2 * IMM2_SIZE; - break; - } - list[2] = (pcre_uint32)(end - code); - return end; - } -return NULL; /* Opcode not accepted */ -} - - - -/************************************************* -* Scan further character sets for match * -*************************************************/ - -/* Checks whether the base and the current opcode have a common character, in -which case the base cannot be possessified. - -Arguments: - code points to the byte code - utf TRUE in UTF-8 / UTF-16 / UTF-32 mode - cd static compile data - base_list the data list of the base opcode - -Returns: TRUE if the auto-possessification is possible -*/ - -static BOOL -compare_opcodes(const pcre_uchar *code, BOOL utf, const compile_data *cd, - const pcre_uint32 *base_list, const pcre_uchar *base_end) -{ -pcre_uchar c; -pcre_uint32 list[8]; -const pcre_uint32 *chr_ptr; -const pcre_uint32 *ochr_ptr; -const pcre_uint32 *list_ptr; -const pcre_uchar *next_code; -#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 -const pcre_uchar *xclass_flags; -#endif -const pcre_uint8 *class_bitset; -const pcre_uint8 *set1, *set2, *set_end; -pcre_uint32 chr; -BOOL accepted, invert_bits; -BOOL entered_a_group = FALSE; - -/* Note: the base_list[1] contains whether the current opcode has greedy -(represented by a non-zero value) quantifier. This is a different from -other character type lists, which stores here that the character iterator -matches to an empty string (also represented by a non-zero value). */ - -for(;;) - { - /* All operations move the code pointer forward. - Therefore infinite recursions are not possible. */ - - c = *code; - - /* Skip over callouts */ - - if (c == OP_CALLOUT) - { - code += PRIV(OP_lengths)[c]; - continue; - } - - if (c == OP_ALT) - { - do code += GET(code, 1); while (*code == OP_ALT); - c = *code; - } - - switch(c) - { - case OP_END: - case OP_KETRPOS: - /* TRUE only in greedy case. The non-greedy case could be replaced by - an OP_EXACT, but it is probably not worth it. (And note that OP_EXACT - uses more memory, which we cannot get at this stage.) */ - - return base_list[1] != 0; - - case OP_KET: - /* If the bracket is capturing, and referenced by an OP_RECURSE, or - it is an atomic sub-pattern (assert, once, etc.) the non-greedy case - cannot be converted to a possessive form. */ - - if (base_list[1] == 0) return FALSE; - - switch(*(code - GET(code, 1))) - { - case OP_ASSERT: - case OP_ASSERT_NOT: - case OP_ASSERTBACK: - case OP_ASSERTBACK_NOT: - case OP_ONCE: - case OP_ONCE_NC: - /* Atomic sub-patterns and assertions can always auto-possessify their - last iterator. However, if the group was entered as a result of checking - a previous iterator, this is not possible. */ - - return !entered_a_group; - } - - code += PRIV(OP_lengths)[c]; - continue; - - case OP_ONCE: - case OP_ONCE_NC: - case OP_BRA: - case OP_CBRA: - next_code = code + GET(code, 1); - code += PRIV(OP_lengths)[c]; - - while (*next_code == OP_ALT) - { - if (!compare_opcodes(code, utf, cd, base_list, base_end)) return FALSE; - code = next_code + 1 + LINK_SIZE; - next_code += GET(next_code, 1); - } - - entered_a_group = TRUE; - continue; - - case OP_BRAZERO: - case OP_BRAMINZERO: - - next_code = code + 1; - if (*next_code != OP_BRA && *next_code != OP_CBRA - && *next_code != OP_ONCE && *next_code != OP_ONCE_NC) return FALSE; - - do next_code += GET(next_code, 1); while (*next_code == OP_ALT); - - /* The bracket content will be checked by the - OP_BRA/OP_CBRA case above. */ - next_code += 1 + LINK_SIZE; - if (!compare_opcodes(next_code, utf, cd, base_list, base_end)) - return FALSE; - - code += PRIV(OP_lengths)[c]; - continue; - - default: - break; - } - - /* Check for a supported opcode, and load its properties. */ - - code = get_chr_property_list(code, utf, cd->fcc, list); - if (code == NULL) return FALSE; /* Unsupported */ - - /* If either opcode is a small character list, set pointers for comparing - characters from that list with another list, or with a property. */ - - if (base_list[0] == OP_CHAR) - { - chr_ptr = base_list + 2; - list_ptr = list; - } - else if (list[0] == OP_CHAR) - { - chr_ptr = list + 2; - list_ptr = base_list; - } - - /* Character bitsets can also be compared to certain opcodes. */ - - else if (base_list[0] == OP_CLASS || list[0] == OP_CLASS -#ifdef COMPILE_PCRE8 - /* In 8 bit, non-UTF mode, OP_CLASS and OP_NCLASS are the same. */ - || (!utf && (base_list[0] == OP_NCLASS || list[0] == OP_NCLASS)) -#endif - ) - { -#ifdef COMPILE_PCRE8 - if (base_list[0] == OP_CLASS || (!utf && base_list[0] == OP_NCLASS)) -#else - if (base_list[0] == OP_CLASS) -#endif - { - set1 = (pcre_uint8 *)(base_end - base_list[2]); - list_ptr = list; - } - else - { - set1 = (pcre_uint8 *)(code - list[2]); - list_ptr = base_list; - } - - invert_bits = FALSE; - switch(list_ptr[0]) - { - case OP_CLASS: - case OP_NCLASS: - set2 = (pcre_uint8 *) - ((list_ptr == list ? code : base_end) - list_ptr[2]); - break; - -#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 - case OP_XCLASS: - xclass_flags = (list_ptr == list ? code : base_end) - list_ptr[2] + LINK_SIZE; - if ((*xclass_flags & XCL_HASPROP) != 0) return FALSE; - if ((*xclass_flags & XCL_MAP) == 0) - { - /* No bits are set for characters < 256. */ - if (list[1] == 0) return TRUE; - /* Might be an empty repeat. */ - continue; - } - set2 = (pcre_uint8 *)(xclass_flags + 1); - break; -#endif - - case OP_NOT_DIGIT: - invert_bits = TRUE; - /* Fall through */ - case OP_DIGIT: - set2 = (pcre_uint8 *)(cd->cbits + cbit_digit); - break; - - case OP_NOT_WHITESPACE: - invert_bits = TRUE; - /* Fall through */ - case OP_WHITESPACE: - set2 = (pcre_uint8 *)(cd->cbits + cbit_space); - break; - - case OP_NOT_WORDCHAR: - invert_bits = TRUE; - /* Fall through */ - case OP_WORDCHAR: - set2 = (pcre_uint8 *)(cd->cbits + cbit_word); - break; - - default: - return FALSE; - } - - /* Because the sets are unaligned, we need - to perform byte comparison here. */ - set_end = set1 + 32; - if (invert_bits) - { - do - { - if ((*set1++ & ~(*set2++)) != 0) return FALSE; - } - while (set1 < set_end); - } - else - { - do - { - if ((*set1++ & *set2++) != 0) return FALSE; - } - while (set1 < set_end); - } - - if (list[1] == 0) return TRUE; - /* Might be an empty repeat. */ - continue; - } - - /* Some property combinations also acceptable. Unicode property opcodes are - processed specially; the rest can be handled with a lookup table. */ - - else - { - pcre_uint32 leftop, rightop; - - leftop = base_list[0]; - rightop = list[0]; - -#ifdef SUPPORT_UCP - accepted = FALSE; /* Always set in non-unicode case. */ - if (leftop == OP_PROP || leftop == OP_NOTPROP) - { - if (rightop == OP_EOD) - accepted = TRUE; - else if (rightop == OP_PROP || rightop == OP_NOTPROP) - { - int n; - const pcre_uint8 *p; - BOOL same = leftop == rightop; - BOOL lisprop = leftop == OP_PROP; - BOOL risprop = rightop == OP_PROP; - BOOL bothprop = lisprop && risprop; - - /* There's a table that specifies how each combination is to be - processed: - 0 Always return FALSE (never auto-possessify) - 1 Character groups are distinct (possessify if both are OP_PROP) - 2 Check character categories in the same group (general or particular) - 3 Return TRUE if the two opcodes are not the same - ... see comments below - */ - - n = propposstab[base_list[2]][list[2]]; - switch(n) - { - case 0: break; - case 1: accepted = bothprop; break; - case 2: accepted = (base_list[3] == list[3]) != same; break; - case 3: accepted = !same; break; - - case 4: /* Left general category, right particular category */ - accepted = risprop && catposstab[base_list[3]][list[3]] == same; - break; - - case 5: /* Right general category, left particular category */ - accepted = lisprop && catposstab[list[3]][base_list[3]] == same; - break; - - /* This code is logically tricky. Think hard before fiddling with it. - The posspropstab table has four entries per row. Each row relates to - one of PCRE's special properties such as ALNUM or SPACE or WORD. - Only WORD actually needs all four entries, but using repeats for the - others means they can all use the same code below. - - The first two entries in each row are Unicode general categories, and - apply always, because all the characters they include are part of the - PCRE character set. The third and fourth entries are a general and a - particular category, respectively, that include one or more relevant - characters. One or the other is used, depending on whether the check - is for a general or a particular category. However, in both cases the - category contains more characters than the specials that are defined - for the property being tested against. Therefore, it cannot be used - in a NOTPROP case. - - Example: the row for WORD contains ucp_L, ucp_N, ucp_P, ucp_Po. - Underscore is covered by ucp_P or ucp_Po. */ - - case 6: /* Left alphanum vs right general category */ - case 7: /* Left space vs right general category */ - case 8: /* Left word vs right general category */ - p = posspropstab[n-6]; - accepted = risprop && lisprop == - (list[3] != p[0] && - list[3] != p[1] && - (list[3] != p[2] || !lisprop)); - break; - - case 9: /* Right alphanum vs left general category */ - case 10: /* Right space vs left general category */ - case 11: /* Right word vs left general category */ - p = posspropstab[n-9]; - accepted = lisprop && risprop == - (base_list[3] != p[0] && - base_list[3] != p[1] && - (base_list[3] != p[2] || !risprop)); - break; - - case 12: /* Left alphanum vs right particular category */ - case 13: /* Left space vs right particular category */ - case 14: /* Left word vs right particular category */ - p = posspropstab[n-12]; - accepted = risprop && lisprop == - (catposstab[p[0]][list[3]] && - catposstab[p[1]][list[3]] && - (list[3] != p[3] || !lisprop)); - break; - - case 15: /* Right alphanum vs left particular category */ - case 16: /* Right space vs left particular category */ - case 17: /* Right word vs left particular category */ - p = posspropstab[n-15]; - accepted = lisprop && risprop == - (catposstab[p[0]][base_list[3]] && - catposstab[p[1]][base_list[3]] && - (base_list[3] != p[3] || !risprop)); - break; - } - } - } - - else -#endif /* SUPPORT_UCP */ - - accepted = leftop >= FIRST_AUTOTAB_OP && leftop <= LAST_AUTOTAB_LEFT_OP && - rightop >= FIRST_AUTOTAB_OP && rightop <= LAST_AUTOTAB_RIGHT_OP && - autoposstab[leftop - FIRST_AUTOTAB_OP][rightop - FIRST_AUTOTAB_OP]; - - if (!accepted) return FALSE; - - if (list[1] == 0) return TRUE; - /* Might be an empty repeat. */ - continue; - } - - /* Control reaches here only if one of the items is a small character list. - All characters are checked against the other side. */ - - do - { - chr = *chr_ptr; - - switch(list_ptr[0]) - { - case OP_CHAR: - ochr_ptr = list_ptr + 2; - do - { - if (chr == *ochr_ptr) return FALSE; - ochr_ptr++; - } - while(*ochr_ptr != NOTACHAR); - break; - - case OP_NOT: - ochr_ptr = list_ptr + 2; - do - { - if (chr == *ochr_ptr) - break; - ochr_ptr++; - } - while(*ochr_ptr != NOTACHAR); - if (*ochr_ptr == NOTACHAR) return FALSE; /* Not found */ - break; - - /* Note that OP_DIGIT etc. are generated only when PCRE_UCP is *not* - set. When it is set, \d etc. are converted into OP_(NOT_)PROP codes. */ - - case OP_DIGIT: - if (chr < 256 && (cd->ctypes[chr] & ctype_digit) != 0) return FALSE; - break; - - case OP_NOT_DIGIT: - if (chr > 255 || (cd->ctypes[chr] & ctype_digit) == 0) return FALSE; - break; - - case OP_WHITESPACE: - if (chr < 256 && (cd->ctypes[chr] & ctype_space) != 0) return FALSE; - break; - - case OP_NOT_WHITESPACE: - if (chr > 255 || (cd->ctypes[chr] & ctype_space) == 0) return FALSE; - break; - - case OP_WORDCHAR: - if (chr < 255 && (cd->ctypes[chr] & ctype_word) != 0) return FALSE; - break; - - case OP_NOT_WORDCHAR: - if (chr > 255 || (cd->ctypes[chr] & ctype_word) == 0) return FALSE; - break; - - case OP_HSPACE: - switch(chr) - { - HSPACE_CASES: return FALSE; - default: break; - } - break; - - case OP_NOT_HSPACE: - switch(chr) - { - HSPACE_CASES: break; - default: return FALSE; - } - break; - - case OP_ANYNL: - case OP_VSPACE: - switch(chr) - { - VSPACE_CASES: return FALSE; - default: break; - } - break; - - case OP_NOT_VSPACE: - switch(chr) - { - VSPACE_CASES: break; - default: return FALSE; - } - break; - - case OP_DOLL: - case OP_EODN: - switch (chr) - { - case CHAR_CR: - case CHAR_LF: - case CHAR_VT: - case CHAR_FF: - case CHAR_NEL: -#ifndef EBCDIC - case 0x2028: - case 0x2029: -#endif /* Not EBCDIC */ - return FALSE; - } - break; - - case OP_EOD: /* Can always possessify before \z */ - break; - -#ifdef SUPPORT_UCP - case OP_PROP: - case OP_NOTPROP: - if (!check_char_prop(chr, list_ptr[2], list_ptr[3], - list_ptr[0] == OP_NOTPROP)) - return FALSE; - break; -#endif - - case OP_NCLASS: - if (chr > 255) return FALSE; - /* Fall through */ - - case OP_CLASS: - if (chr > 255) break; - class_bitset = (pcre_uint8 *) - ((list_ptr == list ? code : base_end) - list_ptr[2]); - if ((class_bitset[chr >> 3] & (1 << (chr & 7))) != 0) return FALSE; - break; - -#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 - case OP_XCLASS: - if (PRIV(xclass)(chr, (list_ptr == list ? code : base_end) - - list_ptr[2] + LINK_SIZE, utf)) return FALSE; - break; -#endif - - default: - return FALSE; - } - - chr_ptr++; - } - while(*chr_ptr != NOTACHAR); - - /* At least one character must be matched from this opcode. */ - - if (list[1] == 0) return TRUE; - } - -/* Control never reaches here. There used to be a fail-save return FALSE; here, -but some compilers complain about an unreachable statement. */ - -} - - - -/************************************************* -* Scan compiled regex for auto-possession * -*************************************************/ - -/* Replaces single character iterations with their possessive alternatives -if appropriate. This function modifies the compiled opcode! - -Arguments: - code points to start of the byte code - utf TRUE in UTF-8 / UTF-16 / UTF-32 mode - cd static compile data - -Returns: nothing -*/ - -static void -auto_possessify(pcre_uchar *code, BOOL utf, const compile_data *cd) -{ -register pcre_uchar c; -const pcre_uchar *end; -pcre_uchar *repeat_opcode; -pcre_uint32 list[8]; - -for (;;) - { - c = *code; - - if (c >= OP_STAR && c <= OP_TYPEPOSUPTO) - { - c -= get_repeat_base(c) - OP_STAR; - end = (c <= OP_MINUPTO) ? - get_chr_property_list(code, utf, cd->fcc, list) : NULL; - list[1] = c == OP_STAR || c == OP_PLUS || c == OP_QUERY || c == OP_UPTO; - - if (end != NULL && compare_opcodes(end, utf, cd, list, end)) - { - switch(c) - { - case OP_STAR: - *code += OP_POSSTAR - OP_STAR; - break; - - case OP_MINSTAR: - *code += OP_POSSTAR - OP_MINSTAR; - break; - - case OP_PLUS: - *code += OP_POSPLUS - OP_PLUS; - break; - - case OP_MINPLUS: - *code += OP_POSPLUS - OP_MINPLUS; - break; - - case OP_QUERY: - *code += OP_POSQUERY - OP_QUERY; - break; - - case OP_MINQUERY: - *code += OP_POSQUERY - OP_MINQUERY; - break; - - case OP_UPTO: - *code += OP_POSUPTO - OP_UPTO; - break; - - case OP_MINUPTO: - *code += OP_POSUPTO - OP_MINUPTO; - break; - } - } - c = *code; - } - else if (c == OP_CLASS || c == OP_NCLASS || c == OP_XCLASS) - { -#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 - if (c == OP_XCLASS) - repeat_opcode = code + GET(code, 1); - else -#endif - repeat_opcode = code + 1 + (32 / sizeof(pcre_uchar)); - - c = *repeat_opcode; - if (c >= OP_CRSTAR && c <= OP_CRMINRANGE) - { - /* end must not be NULL. */ - end = get_chr_property_list(code, utf, cd->fcc, list); - - list[1] = (c & 1) == 0; - - if (compare_opcodes(end, utf, cd, list, end)) - { - switch (c) - { - case OP_CRSTAR: - case OP_CRMINSTAR: - *repeat_opcode = OP_CRPOSSTAR; - break; - - case OP_CRPLUS: - case OP_CRMINPLUS: - *repeat_opcode = OP_CRPOSPLUS; - break; - - case OP_CRQUERY: - case OP_CRMINQUERY: - *repeat_opcode = OP_CRPOSQUERY; - break; - - case OP_CRRANGE: - case OP_CRMINRANGE: - *repeat_opcode = OP_CRPOSRANGE; - break; - } - } - } - c = *code; - } - - switch(c) - { - case OP_END: - return; - - case OP_TYPESTAR: - case OP_TYPEMINSTAR: - case OP_TYPEPLUS: - case OP_TYPEMINPLUS: - case OP_TYPEQUERY: - case OP_TYPEMINQUERY: - case OP_TYPEPOSSTAR: - case OP_TYPEPOSPLUS: - case OP_TYPEPOSQUERY: - if (code[1] == OP_PROP || code[1] == OP_NOTPROP) code += 2; - break; - - case OP_TYPEUPTO: - case OP_TYPEMINUPTO: - case OP_TYPEEXACT: - case OP_TYPEPOSUPTO: - if (code[1 + IMM2_SIZE] == OP_PROP || code[1 + IMM2_SIZE] == OP_NOTPROP) - code += 2; - break; - -#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 - case OP_XCLASS: - code += GET(code, 1); - break; -#endif - - case OP_MARK: - case OP_PRUNE_ARG: - case OP_SKIP_ARG: - case OP_THEN_ARG: - code += code[1]; - break; - } - - /* Add in the fixed length from the table */ - - code += PRIV(OP_lengths)[c]; - - /* In UTF-8 mode, opcodes that are followed by a character may be followed by - a multi-byte character. The length in the table is a minimum, so we have to - arrange to skip the extra bytes. */ - -#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 - if (utf) switch(c) - { - case OP_CHAR: - case OP_CHARI: - case OP_NOT: - case OP_NOTI: - case OP_STAR: - case OP_MINSTAR: - case OP_PLUS: - case OP_MINPLUS: - case OP_QUERY: - case OP_MINQUERY: - case OP_UPTO: - case OP_MINUPTO: - case OP_EXACT: - case OP_POSSTAR: - case OP_POSPLUS: - case OP_POSQUERY: - case OP_POSUPTO: - case OP_STARI: - case OP_MINSTARI: - case OP_PLUSI: - case OP_MINPLUSI: - case OP_QUERYI: - case OP_MINQUERYI: - case OP_UPTOI: - case OP_MINUPTOI: - case OP_EXACTI: - case OP_POSSTARI: - case OP_POSPLUSI: - case OP_POSQUERYI: - case OP_POSUPTOI: - case OP_NOTSTAR: - case OP_NOTMINSTAR: - case OP_NOTPLUS: - case OP_NOTMINPLUS: - case OP_NOTQUERY: - case OP_NOTMINQUERY: - case OP_NOTUPTO: - case OP_NOTMINUPTO: - case OP_NOTEXACT: - case OP_NOTPOSSTAR: - case OP_NOTPOSPLUS: - case OP_NOTPOSQUERY: - case OP_NOTPOSUPTO: - case OP_NOTSTARI: - case OP_NOTMINSTARI: - case OP_NOTPLUSI: - case OP_NOTMINPLUSI: - case OP_NOTQUERYI: - case OP_NOTMINQUERYI: - case OP_NOTUPTOI: - case OP_NOTMINUPTOI: - case OP_NOTEXACTI: - case OP_NOTPOSSTARI: - case OP_NOTPOSPLUSI: - case OP_NOTPOSQUERYI: - case OP_NOTPOSUPTOI: - if (HAS_EXTRALEN(code[-1])) code += GET_EXTRALEN(code[-1]); - break; - } -#else - (void)(utf); /* Keep compiler happy by referencing function argument */ -#endif - } -} - - - -/************************************************* -* Check for POSIX class syntax * -*************************************************/ - -/* This function is called when the sequence "[:" or "[." or "[=" is -encountered in a character class. It checks whether this is followed by a -sequence of characters terminated by a matching ":]" or ".]" or "=]". If we -reach an unescaped ']' without the special preceding character, return FALSE. - -Originally, this function only recognized a sequence of letters between the -terminators, but it seems that Perl recognizes any sequence of characters, -though of course unknown POSIX names are subsequently rejected. Perl gives an -"Unknown POSIX class" error for [:f\oo:] for example, where previously PCRE -didn't consider this to be a POSIX class. Likewise for [:1234:]. - -The problem in trying to be exactly like Perl is in the handling of escapes. We -have to be sure that [abc[:x\]pqr] is *not* treated as containing a POSIX -class, but [abc[:x\]pqr:]] is (so that an error can be generated). The code -below handles the special case of \], but does not try to do any other escape -processing. This makes it different from Perl for cases such as [:l\ower:] -where Perl recognizes it as the POSIX class "lower" but PCRE does not recognize -"l\ower". This is a lesser evil than not diagnosing bad classes when Perl does, -I think. - -A user pointed out that PCRE was rejecting [:a[:digit:]] whereas Perl was not. -It seems that the appearance of a nested POSIX class supersedes an apparent -external class. For example, [:a[:digit:]b:] matches "a", "b", ":", or -a digit. - -In Perl, unescaped square brackets may also appear as part of class names. For -example, [:a[:abc]b:] gives unknown POSIX class "[:abc]b:]". However, for -[:a[:abc]b][b:] it gives unknown POSIX class "[:abc]b][b:]", which does not -seem right at all. PCRE does not allow closing square brackets in POSIX class -names. - -Arguments: - ptr pointer to the initial [ - endptr where to return the end pointer - -Returns: TRUE or FALSE -*/ - -static BOOL -check_posix_syntax(const pcre_uchar *ptr, const pcre_uchar **endptr) -{ -pcre_uchar terminator; /* Don't combine these lines; the Solaris cc */ -terminator = *(++ptr); /* compiler warns about "non-constant" initializer. */ -for (++ptr; *ptr != CHAR_NULL; ptr++) - { - if (*ptr == CHAR_BACKSLASH && ptr[1] == CHAR_RIGHT_SQUARE_BRACKET) - ptr++; - else if (*ptr == CHAR_RIGHT_SQUARE_BRACKET) return FALSE; - else - { - if (*ptr == terminator && ptr[1] == CHAR_RIGHT_SQUARE_BRACKET) - { - *endptr = ptr; - return TRUE; - } - if (*ptr == CHAR_LEFT_SQUARE_BRACKET && - (ptr[1] == CHAR_COLON || ptr[1] == CHAR_DOT || - ptr[1] == CHAR_EQUALS_SIGN) && - check_posix_syntax(ptr, endptr)) - return FALSE; - } - } -return FALSE; -} - - - - -/************************************************* -* Check POSIX class name * -*************************************************/ - -/* This function is called to check the name given in a POSIX-style class entry -such as [:alnum:]. - -Arguments: - ptr points to the first letter - len the length of the name - -Returns: a value representing the name, or -1 if unknown -*/ - -static int -check_posix_name(const pcre_uchar *ptr, int len) -{ -const char *pn = posix_names; -register int yield = 0; -while (posix_name_lengths[yield] != 0) - { - if (len == posix_name_lengths[yield] && - STRNCMP_UC_C8(ptr, pn, (unsigned int)len) == 0) return yield; - pn += posix_name_lengths[yield] + 1; - yield++; - } -return -1; -} - - -/************************************************* -* Adjust OP_RECURSE items in repeated group * -*************************************************/ - -/* OP_RECURSE items contain an offset from the start of the regex to the group -that is referenced. This means that groups can be replicated for fixed -repetition simply by copying (because the recursion is allowed to refer to -earlier groups that are outside the current group). However, when a group is -optional (i.e. the minimum quantifier is zero), OP_BRAZERO or OP_SKIPZERO is -inserted before it, after it has been compiled. This means that any OP_RECURSE -items within it that refer to the group itself or any contained groups have to -have their offsets adjusted. That one of the jobs of this function. Before it -is called, the partially compiled regex must be temporarily terminated with -OP_END. - -This function has been extended with the possibility of forward references for -recursions and subroutine calls. It must also check the list of such references -for the group we are dealing with. If it finds that one of the recursions in -the current group is on this list, it adjusts the offset in the list, not the -value in the reference (which is a group number). - -Arguments: - group points to the start of the group - adjust the amount by which the group is to be moved - utf TRUE in UTF-8 / UTF-16 / UTF-32 mode - cd contains pointers to tables etc. - save_hwm the hwm forward reference pointer at the start of the group - -Returns: nothing -*/ - -static void -adjust_recurse(pcre_uchar *group, int adjust, BOOL utf, compile_data *cd, - pcre_uchar *save_hwm) -{ -pcre_uchar *ptr = group; - -while ((ptr = (pcre_uchar *)find_recurse(ptr, utf)) != NULL) - { - int offset; - pcre_uchar *hc; - - /* See if this recursion is on the forward reference list. If so, adjust the - reference. */ - - for (hc = save_hwm; hc < cd->hwm; hc += LINK_SIZE) - { - offset = (int)GET(hc, 0); - if (cd->start_code + offset == ptr + 1) - { - PUT(hc, 0, offset + adjust); - break; - } - } - - /* Otherwise, adjust the recursion offset if it's after the start of this - group. */ - - if (hc >= cd->hwm) - { - offset = (int)GET(ptr, 1); - if (cd->start_code + offset >= group) PUT(ptr, 1, offset + adjust); - } - - ptr += 1 + LINK_SIZE; - } -} - - - -/************************************************* -* Insert an automatic callout point * -*************************************************/ - -/* This function is called when the PCRE_AUTO_CALLOUT option is set, to insert -callout points before each pattern item. - -Arguments: - code current code pointer - ptr current pattern pointer - cd pointers to tables etc - -Returns: new code pointer -*/ - -static pcre_uchar * -auto_callout(pcre_uchar *code, const pcre_uchar *ptr, compile_data *cd) -{ -*code++ = OP_CALLOUT; -*code++ = 255; -PUT(code, 0, (int)(ptr - cd->start_pattern)); /* Pattern offset */ -PUT(code, LINK_SIZE, 0); /* Default length */ -return code + 2 * LINK_SIZE; -} - - - -/************************************************* -* Complete a callout item * -*************************************************/ - -/* A callout item contains the length of the next item in the pattern, which -we can't fill in till after we have reached the relevant point. This is used -for both automatic and manual callouts. - -Arguments: - previous_callout points to previous callout item - ptr current pattern pointer - cd pointers to tables etc - -Returns: nothing -*/ - -static void -complete_callout(pcre_uchar *previous_callout, const pcre_uchar *ptr, compile_data *cd) -{ -int length = (int)(ptr - cd->start_pattern - GET(previous_callout, 2)); -PUT(previous_callout, 2 + LINK_SIZE, length); -} - - - -#ifdef SUPPORT_UCP -/************************************************* -* Get othercase range * -*************************************************/ - -/* This function is passed the start and end of a class range, in UTF-8 mode -with UCP support. It searches up the characters, looking for ranges of -characters in the "other" case. Each call returns the next one, updating the -start address. A character with multiple other cases is returned on its own -with a special return value. - -Arguments: - cptr points to starting character value; updated - d end value - ocptr where to put start of othercase range - odptr where to put end of othercase range - -Yield: -1 when no more - 0 when a range is returned - >0 the CASESET offset for char with multiple other cases - in this case, ocptr contains the original -*/ - -static int -get_othercase_range(pcre_uint32 *cptr, pcre_uint32 d, pcre_uint32 *ocptr, - pcre_uint32 *odptr) -{ -pcre_uint32 c, othercase, next; -unsigned int co; - -/* Find the first character that has an other case. If it has multiple other -cases, return its case offset value. */ - -for (c = *cptr; c <= d; c++) - { - if ((co = UCD_CASESET(c)) != 0) - { - *ocptr = c++; /* Character that has the set */ - *cptr = c; /* Rest of input range */ - return (int)co; - } - if ((othercase = UCD_OTHERCASE(c)) != c) break; - } - -if (c > d) return -1; /* Reached end of range */ - -/* Found a character that has a single other case. Search for the end of the -range, which is either the end of the input range, or a character that has zero -or more than one other cases. */ - -*ocptr = othercase; -next = othercase + 1; - -for (++c; c <= d; c++) - { - if ((co = UCD_CASESET(c)) != 0 || UCD_OTHERCASE(c) != next) break; - next++; - } - -*odptr = next - 1; /* End of othercase range */ -*cptr = c; /* Rest of input range */ -return 0; -} -#endif /* SUPPORT_UCP */ - - - -/************************************************* -* Add a character or range to a class * -*************************************************/ - -/* This function packages up the logic of adding a character or range of -characters to a class. The character values in the arguments will be within the -valid values for the current mode (8-bit, 16-bit, UTF, etc). This function is -mutually recursive with the function immediately below. - -Arguments: - classbits the bit map for characters < 256 - uchardptr points to the pointer for extra data - options the options word - cd contains pointers to tables etc. - start start of range character - end end of range character - -Returns: the number of < 256 characters added - the pointer to extra data is updated -*/ - -static int -add_to_class(pcre_uint8 *classbits, pcre_uchar **uchardptr, int options, - compile_data *cd, pcre_uint32 start, pcre_uint32 end) -{ -pcre_uint32 c; -pcre_uint32 classbits_end = (end <= 0xff ? end : 0xff); -int n8 = 0; - -/* If caseless matching is required, scan the range and process alternate -cases. In Unicode, there are 8-bit characters that have alternate cases that -are greater than 255 and vice-versa. Sometimes we can just extend the original -range. */ - -if ((options & PCRE_CASELESS) != 0) - { -#ifdef SUPPORT_UCP - if ((options & PCRE_UTF8) != 0) - { - int rc; - pcre_uint32 oc, od; - - options &= ~PCRE_CASELESS; /* Remove for recursive calls */ - c = start; - - while ((rc = get_othercase_range(&c, end, &oc, &od)) >= 0) - { - /* Handle a single character that has more than one other case. */ - - if (rc > 0) n8 += add_list_to_class(classbits, uchardptr, options, cd, - PRIV(ucd_caseless_sets) + rc, oc); - - /* Do nothing if the other case range is within the original range. */ - - else if (oc >= start && od <= end) continue; - - /* Extend the original range if there is overlap, noting that if oc < c, we - can't have od > end because a subrange is always shorter than the basic - range. Otherwise, use a recursive call to add the additional range. */ - - else if (oc < start && od >= start - 1) start = oc; /* Extend downwards */ - else if (od > end && oc <= end + 1) end = od; /* Extend upwards */ - else n8 += add_to_class(classbits, uchardptr, options, cd, oc, od); - } - } - else -#endif /* SUPPORT_UCP */ - - /* Not UTF-mode, or no UCP */ - - for (c = start; c <= classbits_end; c++) - { - SETBIT(classbits, cd->fcc[c]); - n8++; - } - } - -/* Now handle the original range. Adjust the final value according to the bit -length - this means that the same lists of (e.g.) horizontal spaces can be used -in all cases. */ - -#if defined COMPILE_PCRE8 -#ifdef SUPPORT_UTF - if ((options & PCRE_UTF8) == 0) -#endif - if (end > 0xff) end = 0xff; - -#elif defined COMPILE_PCRE16 -#ifdef SUPPORT_UTF - if ((options & PCRE_UTF16) == 0) -#endif - if (end > 0xffff) end = 0xffff; - -#endif /* COMPILE_PCRE[8|16] */ - -/* Use the bitmap for characters < 256. Otherwise use extra data.*/ - -for (c = start; c <= classbits_end; c++) - { - /* Regardless of start, c will always be <= 255. */ - SETBIT(classbits, c); - n8++; - } - -#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 -if (start <= 0xff) start = 0xff + 1; - -if (end >= start) - { - pcre_uchar *uchardata = *uchardptr; -#ifdef SUPPORT_UTF - if ((options & PCRE_UTF8) != 0) /* All UTFs use the same flag bit */ - { - if (start < end) - { - *uchardata++ = XCL_RANGE; - uchardata += PRIV(ord2utf)(start, uchardata); - uchardata += PRIV(ord2utf)(end, uchardata); - } - else if (start == end) - { - *uchardata++ = XCL_SINGLE; - uchardata += PRIV(ord2utf)(start, uchardata); - } - } - else -#endif /* SUPPORT_UTF */ - - /* Without UTF support, character values are constrained by the bit length, - and can only be > 256 for 16-bit and 32-bit libraries. */ - -#ifdef COMPILE_PCRE8 - {} -#else - if (start < end) - { - *uchardata++ = XCL_RANGE; - *uchardata++ = start; - *uchardata++ = end; - } - else if (start == end) - { - *uchardata++ = XCL_SINGLE; - *uchardata++ = start; - } -#endif - - *uchardptr = uchardata; /* Updata extra data pointer */ - } -#endif /* SUPPORT_UTF || !COMPILE_PCRE8 */ - -return n8; /* Number of 8-bit characters */ -} - - - - -/************************************************* -* Add a list of characters to a class * -*************************************************/ - -/* This function is used for adding a list of case-equivalent characters to a -class, and also for adding a list of horizontal or vertical whitespace. If the -list is in order (which it should be), ranges of characters are detected and -handled appropriately. This function is mutually recursive with the function -above. - -Arguments: - classbits the bit map for characters < 256 - uchardptr points to the pointer for extra data - options the options word - cd contains pointers to tables etc. - p points to row of 32-bit values, terminated by NOTACHAR - except character to omit; this is used when adding lists of - case-equivalent characters to avoid including the one we - already know about - -Returns: the number of < 256 characters added - the pointer to extra data is updated -*/ - -static int -add_list_to_class(pcre_uint8 *classbits, pcre_uchar **uchardptr, int options, - compile_data *cd, const pcre_uint32 *p, unsigned int except) -{ -int n8 = 0; -while (p[0] < NOTACHAR) - { - int n = 0; - if (p[0] != except) - { - while(p[n+1] == p[0] + n + 1) n++; - n8 += add_to_class(classbits, uchardptr, options, cd, p[0], p[n]); - } - p += n + 1; - } -return n8; -} - - - -/************************************************* -* Add characters not in a list to a class * -*************************************************/ - -/* This function is used for adding the complement of a list of horizontal or -vertical whitespace to a class. The list must be in order. - -Arguments: - classbits the bit map for characters < 256 - uchardptr points to the pointer for extra data - options the options word - cd contains pointers to tables etc. - p points to row of 32-bit values, terminated by NOTACHAR - -Returns: the number of < 256 characters added - the pointer to extra data is updated -*/ - -static int -add_not_list_to_class(pcre_uint8 *classbits, pcre_uchar **uchardptr, - int options, compile_data *cd, const pcre_uint32 *p) -{ -BOOL utf = (options & PCRE_UTF8) != 0; -int n8 = 0; -if (p[0] > 0) - n8 += add_to_class(classbits, uchardptr, options, cd, 0, p[0] - 1); -while (p[0] < NOTACHAR) - { - while (p[1] == p[0] + 1) p++; - n8 += add_to_class(classbits, uchardptr, options, cd, p[0] + 1, - (p[1] == NOTACHAR) ? (utf ? 0x10ffffu : 0xffffffffu) : p[1] - 1); - p++; - } -return n8; -} - - - -/************************************************* -* Compile one branch * -*************************************************/ - -/* Scan the pattern, compiling it into the a vector. If the options are -changed during the branch, the pointer is used to change the external options -bits. This function is used during the pre-compile phase when we are trying -to find out the amount of memory needed, as well as during the real compile -phase. The value of lengthptr distinguishes the two phases. - -Arguments: - optionsptr pointer to the option bits - codeptr points to the pointer to the current code point - ptrptr points to the current pattern pointer - errorcodeptr points to error code variable - firstcharptr place to put the first required character - firstcharflagsptr place to put the first character flags, or a negative number - reqcharptr place to put the last required character - reqcharflagsptr place to put the last required character flags, or a negative number - bcptr points to current branch chain - cond_depth conditional nesting depth - cd contains pointers to tables etc. - lengthptr NULL during the real compile phase - points to length accumulator during pre-compile phase - -Returns: TRUE on success - FALSE, with *errorcodeptr set non-zero on error -*/ - -static BOOL -compile_branch(int *optionsptr, pcre_uchar **codeptr, - const pcre_uchar **ptrptr, int *errorcodeptr, - pcre_uint32 *firstcharptr, pcre_int32 *firstcharflagsptr, - pcre_uint32 *reqcharptr, pcre_int32 *reqcharflagsptr, - branch_chain *bcptr, int cond_depth, - compile_data *cd, int *lengthptr) -{ -int repeat_type, op_type; -int repeat_min = 0, repeat_max = 0; /* To please picky compilers */ -int bravalue = 0; -int greedy_default, greedy_non_default; -pcre_uint32 firstchar, reqchar; -pcre_int32 firstcharflags, reqcharflags; -pcre_uint32 zeroreqchar, zerofirstchar; -pcre_int32 zeroreqcharflags, zerofirstcharflags; -pcre_int32 req_caseopt, reqvary, tempreqvary; -int options = *optionsptr; /* May change dynamically */ -int after_manual_callout = 0; -int length_prevgroup = 0; -register pcre_uint32 c; -int escape; -register pcre_uchar *code = *codeptr; -pcre_uchar *last_code = code; -pcre_uchar *orig_code = code; -pcre_uchar *tempcode; -BOOL inescq = FALSE; -BOOL groupsetfirstchar = FALSE; -const pcre_uchar *ptr = *ptrptr; -const pcre_uchar *tempptr; -const pcre_uchar *nestptr = NULL; -pcre_uchar *previous = NULL; -pcre_uchar *previous_callout = NULL; -pcre_uchar *save_hwm = NULL; -pcre_uint8 classbits[32]; - -/* We can fish out the UTF-8 setting once and for all into a BOOL, but we -must not do this for other options (e.g. PCRE_EXTENDED) because they may change -dynamically as we process the pattern. */ - -#ifdef SUPPORT_UTF -/* PCRE_UTF[16|32] have the same value as PCRE_UTF8. */ -BOOL utf = (options & PCRE_UTF8) != 0; -#ifndef COMPILE_PCRE32 -pcre_uchar utf_chars[6]; -#endif -#else -BOOL utf = FALSE; -#endif - -/* Helper variables for OP_XCLASS opcode (for characters > 255). We define -class_uchardata always so that it can be passed to add_to_class() always, -though it will not be used in non-UTF 8-bit cases. This avoids having to supply -alternative calls for the different cases. */ - -pcre_uchar *class_uchardata; -#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 -BOOL xclass; -pcre_uchar *class_uchardata_base; -#endif - -#ifdef PCRE_DEBUG -if (lengthptr != NULL) DPRINTF((">> start branch\n")); -#endif - -/* Set up the default and non-default settings for greediness */ - -greedy_default = ((options & PCRE_UNGREEDY) != 0); -greedy_non_default = greedy_default ^ 1; - -/* Initialize no first byte, no required byte. REQ_UNSET means "no char -matching encountered yet". It gets changed to REQ_NONE if we hit something that -matches a non-fixed char first char; reqchar just remains unset if we never -find one. - -When we hit a repeat whose minimum is zero, we may have to adjust these values -to take the zero repeat into account. This is implemented by setting them to -zerofirstbyte and zeroreqchar when such a repeat is encountered. The individual -item types that can be repeated set these backoff variables appropriately. */ - -firstchar = reqchar = zerofirstchar = zeroreqchar = 0; -firstcharflags = reqcharflags = zerofirstcharflags = zeroreqcharflags = REQ_UNSET; - -/* The variable req_caseopt contains either the REQ_CASELESS value -or zero, according to the current setting of the caseless flag. The -REQ_CASELESS leaves the lower 28 bit empty. It is added into the -firstchar or reqchar variables to record the case status of the -value. This is used only for ASCII characters. */ - -req_caseopt = ((options & PCRE_CASELESS) != 0)? REQ_CASELESS:0; - -/* Switch on next character until the end of the branch */ - -for (;; ptr++) - { - BOOL negate_class; - BOOL should_flip_negation; - BOOL possessive_quantifier; - BOOL is_quantifier; - BOOL is_recurse; - BOOL reset_bracount; - int class_has_8bitchar; - int class_one_char; -#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 - BOOL xclass_has_prop; -#endif - int newoptions; - int recno; - int refsign; - int skipbytes; - pcre_uint32 subreqchar, subfirstchar; - pcre_int32 subreqcharflags, subfirstcharflags; - int terminator; - unsigned int mclength; - unsigned int tempbracount; - pcre_uint32 ec; - pcre_uchar mcbuffer[8]; - - /* Get next character in the pattern */ - - c = *ptr; - - /* If we are at the end of a nested substitution, revert to the outer level - string. Nesting only happens one level deep. */ - - if (c == CHAR_NULL && nestptr != NULL) - { - ptr = nestptr; - nestptr = NULL; - c = *ptr; - } - - /* If we are in the pre-compile phase, accumulate the length used for the - previous cycle of this loop. */ - - if (lengthptr != NULL) - { -#ifdef PCRE_DEBUG - if (code > cd->hwm) cd->hwm = code; /* High water info */ -#endif - if (code > cd->start_workspace + cd->workspace_size - - WORK_SIZE_SAFETY_MARGIN) /* Check for overrun */ - { - *errorcodeptr = ERR52; - goto FAILED; - } - - /* There is at least one situation where code goes backwards: this is the - case of a zero quantifier after a class (e.g. [ab]{0}). At compile time, - the class is simply eliminated. However, it is created first, so we have to - allow memory for it. Therefore, don't ever reduce the length at this point. - */ - - if (code < last_code) code = last_code; - - /* Paranoid check for integer overflow */ - - if (OFLOW_MAX - *lengthptr < code - last_code) - { - *errorcodeptr = ERR20; - goto FAILED; - } - - *lengthptr += (int)(code - last_code); - DPRINTF(("length=%d added %d c=%c (0x%x)\n", *lengthptr, - (int)(code - last_code), c, c)); - - /* If "previous" is set and it is not at the start of the work space, move - it back to there, in order to avoid filling up the work space. Otherwise, - if "previous" is NULL, reset the current code pointer to the start. */ - - if (previous != NULL) - { - if (previous > orig_code) - { - memmove(orig_code, previous, IN_UCHARS(code - previous)); - code -= previous - orig_code; - previous = orig_code; - } - } - else code = orig_code; - - /* Remember where this code item starts so we can pick up the length - next time round. */ - - last_code = code; - } - - /* In the real compile phase, just check the workspace used by the forward - reference list. */ - - else if (cd->hwm > cd->start_workspace + cd->workspace_size - - WORK_SIZE_SAFETY_MARGIN) - { - *errorcodeptr = ERR52; - goto FAILED; - } - - /* If in \Q...\E, check for the end; if not, we have a literal */ - - if (inescq && c != CHAR_NULL) - { - if (c == CHAR_BACKSLASH && ptr[1] == CHAR_E) - { - inescq = FALSE; - ptr++; - continue; - } - else - { - if (previous_callout != NULL) - { - if (lengthptr == NULL) /* Don't attempt in pre-compile phase */ - complete_callout(previous_callout, ptr, cd); - previous_callout = NULL; - } - if ((options & PCRE_AUTO_CALLOUT) != 0) - { - previous_callout = code; - code = auto_callout(code, ptr, cd); - } - goto NORMAL_CHAR; - } - /* Control does not reach here. */ - } - - /* In extended mode, skip white space and comments. We need a loop in order - to check for more white space and more comments after a comment. */ - - if ((options & PCRE_EXTENDED) != 0) - { - for (;;) - { - while (MAX_255(c) && (cd->ctypes[c] & ctype_space) != 0) c = *(++ptr); - if (c != CHAR_NUMBER_SIGN) break; - ptr++; - while (*ptr != CHAR_NULL) - { - if (IS_NEWLINE(ptr)) /* For non-fixed-length newline cases, */ - { /* IS_NEWLINE sets cd->nllen. */ - ptr += cd->nllen; - break; - } - ptr++; -#ifdef SUPPORT_UTF - if (utf) FORWARDCHAR(ptr); -#endif - } - c = *ptr; /* Either NULL or the char after a newline */ - } - } - - /* See if the next thing is a quantifier. */ - - is_quantifier = - c == CHAR_ASTERISK || c == CHAR_PLUS || c == CHAR_QUESTION_MARK || - (c == CHAR_LEFT_CURLY_BRACKET && is_counted_repeat(ptr+1)); - - /* Fill in length of a previous callout, except when the next thing is a - quantifier or when processing a property substitution string in UCP mode. */ - - if (!is_quantifier && previous_callout != NULL && nestptr == NULL && - after_manual_callout-- <= 0) - { - if (lengthptr == NULL) /* Don't attempt in pre-compile phase */ - complete_callout(previous_callout, ptr, cd); - previous_callout = NULL; - } - - /* Create auto callout, except for quantifiers, or while processing property - strings that are substituted for \w etc in UCP mode. */ - - if ((options & PCRE_AUTO_CALLOUT) != 0 && !is_quantifier && nestptr == NULL) - { - previous_callout = code; - code = auto_callout(code, ptr, cd); - } - - /* Process the next pattern item. */ - - switch(c) - { - /* ===================================================================*/ - case CHAR_NULL: /* The branch terminates at string end */ - case CHAR_VERTICAL_LINE: /* or | or ) */ - case CHAR_RIGHT_PARENTHESIS: - *firstcharptr = firstchar; - *firstcharflagsptr = firstcharflags; - *reqcharptr = reqchar; - *reqcharflagsptr = reqcharflags; - *codeptr = code; - *ptrptr = ptr; - if (lengthptr != NULL) - { - if (OFLOW_MAX - *lengthptr < code - last_code) - { - *errorcodeptr = ERR20; - goto FAILED; - } - *lengthptr += (int)(code - last_code); /* To include callout length */ - DPRINTF((">> end branch\n")); - } - return TRUE; - - - /* ===================================================================*/ - /* Handle single-character metacharacters. In multiline mode, ^ disables - the setting of any following char as a first character. */ - - case CHAR_CIRCUMFLEX_ACCENT: - previous = NULL; - if ((options & PCRE_MULTILINE) != 0) - { - if (firstcharflags == REQ_UNSET) - zerofirstcharflags = firstcharflags = REQ_NONE; - *code++ = OP_CIRCM; - } - else *code++ = OP_CIRC; - break; - - case CHAR_DOLLAR_SIGN: - previous = NULL; - *code++ = ((options & PCRE_MULTILINE) != 0)? OP_DOLLM : OP_DOLL; - break; - - /* There can never be a first char if '.' is first, whatever happens about - repeats. The value of reqchar doesn't change either. */ - - case CHAR_DOT: - if (firstcharflags == REQ_UNSET) firstcharflags = REQ_NONE; - zerofirstchar = firstchar; - zerofirstcharflags = firstcharflags; - zeroreqchar = reqchar; - zeroreqcharflags = reqcharflags; - previous = code; - *code++ = ((options & PCRE_DOTALL) != 0)? OP_ALLANY: OP_ANY; - break; - - - /* ===================================================================*/ - /* Character classes. If the included characters are all < 256, we build a - 32-byte bitmap of the permitted characters, except in the special case - where there is only one such character. For negated classes, we build the - map as usual, then invert it at the end. However, we use a different opcode - so that data characters > 255 can be handled correctly. - - If the class contains characters outside the 0-255 range, a different - opcode is compiled. It may optionally have a bit map for characters < 256, - but those above are are explicitly listed afterwards. A flag byte tells - whether the bitmap is present, and whether this is a negated class or not. - - In JavaScript compatibility mode, an isolated ']' causes an error. In - default (Perl) mode, it is treated as a data character. */ - - case CHAR_RIGHT_SQUARE_BRACKET: - if ((cd->external_options & PCRE_JAVASCRIPT_COMPAT) != 0) - { - *errorcodeptr = ERR64; - goto FAILED; - } - goto NORMAL_CHAR; - - /* In another (POSIX) regex library, the ugly syntax [[:<:]] and [[:>:]] is - used for "start of word" and "end of word". As these are otherwise illegal - sequences, we don't break anything by recognizing them. They are replaced - by \b(?=\w) and \b(?<=\w) respectively. Sequences like [a[:<:]] are - erroneous and are handled by the normal code below. */ - - case CHAR_LEFT_SQUARE_BRACKET: - if (STRNCMP_UC_C8(ptr+1, STRING_WEIRD_STARTWORD, 6) == 0) - { - nestptr = ptr + 7; - ptr = sub_start_of_word - 1; - continue; - } - - if (STRNCMP_UC_C8(ptr+1, STRING_WEIRD_ENDWORD, 6) == 0) - { - nestptr = ptr + 7; - ptr = sub_end_of_word - 1; - continue; - } - - /* Handle a real character class. */ - - previous = code; - - /* PCRE supports POSIX class stuff inside a class. Perl gives an error if - they are encountered at the top level, so we'll do that too. */ - - if ((ptr[1] == CHAR_COLON || ptr[1] == CHAR_DOT || - ptr[1] == CHAR_EQUALS_SIGN) && - check_posix_syntax(ptr, &tempptr)) - { - *errorcodeptr = (ptr[1] == CHAR_COLON)? ERR13 : ERR31; - goto FAILED; - } - - /* If the first character is '^', set the negation flag and skip it. Also, - if the first few characters (either before or after ^) are \Q\E or \E we - skip them too. This makes for compatibility with Perl. */ - - negate_class = FALSE; - for (;;) - { - c = *(++ptr); - if (c == CHAR_BACKSLASH) - { - if (ptr[1] == CHAR_E) - ptr++; - else if (STRNCMP_UC_C8(ptr + 1, STR_Q STR_BACKSLASH STR_E, 3) == 0) - ptr += 3; - else - break; - } - else if (!negate_class && c == CHAR_CIRCUMFLEX_ACCENT) - negate_class = TRUE; - else break; - } - - /* Empty classes are allowed in JavaScript compatibility mode. Otherwise, - an initial ']' is taken as a data character -- the code below handles - that. In JS mode, [] must always fail, so generate OP_FAIL, whereas - [^] must match any character, so generate OP_ALLANY. */ - - if (c == CHAR_RIGHT_SQUARE_BRACKET && - (cd->external_options & PCRE_JAVASCRIPT_COMPAT) != 0) - { - *code++ = negate_class? OP_ALLANY : OP_FAIL; - if (firstcharflags == REQ_UNSET) firstcharflags = REQ_NONE; - zerofirstchar = firstchar; - zerofirstcharflags = firstcharflags; - break; - } - - /* If a class contains a negative special such as \S, we need to flip the - negation flag at the end, so that support for characters > 255 works - correctly (they are all included in the class). */ - - should_flip_negation = FALSE; - - /* Extended class (xclass) will be used when characters > 255 - might match. */ - -#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 - xclass = FALSE; - class_uchardata = code + LINK_SIZE + 2; /* For XCLASS items */ - class_uchardata_base = class_uchardata; /* Save the start */ -#endif - - /* For optimization purposes, we track some properties of the class: - class_has_8bitchar will be non-zero if the class contains at least one < - 256 character; class_one_char will be 1 if the class contains just one - character; xclass_has_prop will be TRUE if unicode property checks - are present in the class. */ - - class_has_8bitchar = 0; - class_one_char = 0; -#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 - xclass_has_prop = FALSE; -#endif - - /* Initialize the 32-char bit map to all zeros. We build the map in a - temporary bit of memory, in case the class contains fewer than two - 8-bit characters because in that case the compiled code doesn't use the bit - map. */ - - memset(classbits, 0, 32 * sizeof(pcre_uint8)); - - /* Process characters until ] is reached. By writing this as a "do" it - means that an initial ] is taken as a data character. At the start of the - loop, c contains the first byte of the character. */ - - if (c != CHAR_NULL) do - { - const pcre_uchar *oldptr; - -#ifdef SUPPORT_UTF - if (utf && HAS_EXTRALEN(c)) - { /* Braces are required because the */ - GETCHARLEN(c, ptr, ptr); /* macro generates multiple statements */ - } -#endif - -#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 - /* In the pre-compile phase, accumulate the length of any extra - data and reset the pointer. This is so that very large classes that - contain a zillion > 255 characters no longer overwrite the work space - (which is on the stack). We have to remember that there was XCLASS data, - however. */ - - if (lengthptr != NULL && class_uchardata > class_uchardata_base) - { - xclass = TRUE; - *lengthptr += (int)(class_uchardata - class_uchardata_base); - class_uchardata = class_uchardata_base; - } -#endif - - /* Inside \Q...\E everything is literal except \E */ - - if (inescq) - { - if (c == CHAR_BACKSLASH && ptr[1] == CHAR_E) /* If we are at \E */ - { - inescq = FALSE; /* Reset literal state */ - ptr++; /* Skip the 'E' */ - continue; /* Carry on with next */ - } - goto CHECK_RANGE; /* Could be range if \E follows */ - } - - /* Handle POSIX class names. Perl allows a negation extension of the - form [:^name:]. A square bracket that doesn't match the syntax is - treated as a literal. We also recognize the POSIX constructions - [.ch.] and [=ch=] ("collating elements") and fault them, as Perl - 5.6 and 5.8 do. */ - - if (c == CHAR_LEFT_SQUARE_BRACKET && - (ptr[1] == CHAR_COLON || ptr[1] == CHAR_DOT || - ptr[1] == CHAR_EQUALS_SIGN) && check_posix_syntax(ptr, &tempptr)) - { - BOOL local_negate = FALSE; - int posix_class, taboffset, tabopt; - register const pcre_uint8 *cbits = cd->cbits; - pcre_uint8 pbits[32]; - - if (ptr[1] != CHAR_COLON) - { - *errorcodeptr = ERR31; - goto FAILED; - } - - ptr += 2; - if (*ptr == CHAR_CIRCUMFLEX_ACCENT) - { - local_negate = TRUE; - should_flip_negation = TRUE; /* Note negative special */ - ptr++; - } - - posix_class = check_posix_name(ptr, (int)(tempptr - ptr)); - if (posix_class < 0) - { - *errorcodeptr = ERR30; - goto FAILED; - } - - /* If matching is caseless, upper and lower are converted to - alpha. This relies on the fact that the class table starts with - alpha, lower, upper as the first 3 entries. */ - - if ((options & PCRE_CASELESS) != 0 && posix_class <= 2) - posix_class = 0; - - /* When PCRE_UCP is set, some of the POSIX classes are converted to - different escape sequences that use Unicode properties \p or \P. Others - that are not available via \p or \P generate XCL_PROP/XCL_NOTPROP - directly. */ - -#ifdef SUPPORT_UCP - if ((options & PCRE_UCP) != 0) - { - unsigned int ptype = 0; - int pc = posix_class + ((local_negate)? POSIX_SUBSIZE/2 : 0); - - /* The posix_substitutes table specifies which POSIX classes can be - converted to \p or \P items. */ - - if (posix_substitutes[pc] != NULL) - { - nestptr = tempptr + 1; - ptr = posix_substitutes[pc] - 1; - continue; - } - - /* There are three other classes that generate special property calls - that are recognized only in an XCLASS. */ - - else switch(posix_class) - { - case PC_GRAPH: - ptype = PT_PXGRAPH; - /* Fall through */ - case PC_PRINT: - if (ptype == 0) ptype = PT_PXPRINT; - /* Fall through */ - case PC_PUNCT: - if (ptype == 0) ptype = PT_PXPUNCT; - *class_uchardata++ = local_negate? XCL_NOTPROP : XCL_PROP; - *class_uchardata++ = ptype; - *class_uchardata++ = 0; - xclass_has_prop = TRUE; - ptr = tempptr + 1; - continue; - - /* For all other POSIX classes, no special action is taken in UCP - mode. Fall through to the non_UCP case. */ - - default: - break; - } - } -#endif - /* In the non-UCP case, or when UCP makes no difference, we build the - bit map for the POSIX class in a chunk of local store because we may be - adding and subtracting from it, and we don't want to subtract bits that - may be in the main map already. At the end we or the result into the - bit map that is being built. */ - - posix_class *= 3; - - /* Copy in the first table (always present) */ - - memcpy(pbits, cbits + posix_class_maps[posix_class], - 32 * sizeof(pcre_uint8)); - - /* If there is a second table, add or remove it as required. */ - - taboffset = posix_class_maps[posix_class + 1]; - tabopt = posix_class_maps[posix_class + 2]; - - if (taboffset >= 0) - { - if (tabopt >= 0) - for (c = 0; c < 32; c++) pbits[c] |= cbits[c + taboffset]; - else - for (c = 0; c < 32; c++) pbits[c] &= ~cbits[c + taboffset]; - } - - /* Now see if we need to remove any special characters. An option - value of 1 removes vertical space and 2 removes underscore. */ - - if (tabopt < 0) tabopt = -tabopt; - if (tabopt == 1) pbits[1] &= ~0x3c; - else if (tabopt == 2) pbits[11] &= 0x7f; - - /* Add the POSIX table or its complement into the main table that is - being built and we are done. */ - - if (local_negate) - for (c = 0; c < 32; c++) classbits[c] |= ~pbits[c]; - else - for (c = 0; c < 32; c++) classbits[c] |= pbits[c]; - - ptr = tempptr + 1; - /* Every class contains at least one < 256 character. */ - class_has_8bitchar = 1; - /* Every class contains at least two characters. */ - class_one_char = 2; - continue; /* End of POSIX syntax handling */ - } - - /* Backslash may introduce a single character, or it may introduce one - of the specials, which just set a flag. The sequence \b is a special - case. Inside a class (and only there) it is treated as backspace. We - assume that other escapes have more than one character in them, so - speculatively set both class_has_8bitchar and class_one_char bigger - than one. Unrecognized escapes fall through and are either treated - as literal characters (by default), or are faulted if - PCRE_EXTRA is set. */ - - if (c == CHAR_BACKSLASH) - { - escape = check_escape(&ptr, &ec, errorcodeptr, cd->bracount, options, - TRUE); - if (*errorcodeptr != 0) goto FAILED; - if (escape == 0) c = ec; - else if (escape == ESC_b) c = CHAR_BS; /* \b is backspace in a class */ - else if (escape == ESC_N) /* \N is not supported in a class */ - { - *errorcodeptr = ERR71; - goto FAILED; - } - else if (escape == ESC_Q) /* Handle start of quoted string */ - { - if (ptr[1] == CHAR_BACKSLASH && ptr[2] == CHAR_E) - { - ptr += 2; /* avoid empty string */ - } - else inescq = TRUE; - continue; - } - else if (escape == ESC_E) continue; /* Ignore orphan \E */ - - else - { - register const pcre_uint8 *cbits = cd->cbits; - /* Every class contains at least two < 256 characters. */ - class_has_8bitchar++; - /* Every class contains at least two characters. */ - class_one_char += 2; - - switch (escape) - { -#ifdef SUPPORT_UCP - case ESC_du: /* These are the values given for \d etc */ - case ESC_DU: /* when PCRE_UCP is set. We replace the */ - case ESC_wu: /* escape sequence with an appropriate \p */ - case ESC_WU: /* or \P to test Unicode properties instead */ - case ESC_su: /* of the default ASCII testing. */ - case ESC_SU: - nestptr = ptr; - ptr = substitutes[escape - ESC_DU] - 1; /* Just before substitute */ - class_has_8bitchar--; /* Undo! */ - continue; -#endif - case ESC_d: - for (c = 0; c < 32; c++) classbits[c] |= cbits[c+cbit_digit]; - continue; - - case ESC_D: - should_flip_negation = TRUE; - for (c = 0; c < 32; c++) classbits[c] |= ~cbits[c+cbit_digit]; - continue; - - case ESC_w: - for (c = 0; c < 32; c++) classbits[c] |= cbits[c+cbit_word]; - continue; - - case ESC_W: - should_flip_negation = TRUE; - for (c = 0; c < 32; c++) classbits[c] |= ~cbits[c+cbit_word]; - continue; - - /* Perl 5.004 onwards omitted VT from \s, but restored it at Perl - 5.18. Before PCRE 8.34, we had to preserve the VT bit if it was - previously set by something earlier in the character class. - Luckily, the value of CHAR_VT is 0x0b in both ASCII and EBCDIC, so - we could just adjust the appropriate bit. From PCRE 8.34 we no - longer treat \s and \S specially. */ - - case ESC_s: - for (c = 0; c < 32; c++) classbits[c] |= cbits[c+cbit_space]; - continue; - - case ESC_S: - should_flip_negation = TRUE; - for (c = 0; c < 32; c++) classbits[c] |= ~cbits[c+cbit_space]; - continue; - - /* The rest apply in both UCP and non-UCP cases. */ - - case ESC_h: - (void)add_list_to_class(classbits, &class_uchardata, options, cd, - PRIV(hspace_list), NOTACHAR); - continue; - - case ESC_H: - (void)add_not_list_to_class(classbits, &class_uchardata, options, - cd, PRIV(hspace_list)); - continue; - - case ESC_v: - (void)add_list_to_class(classbits, &class_uchardata, options, cd, - PRIV(vspace_list), NOTACHAR); - continue; - - case ESC_V: - (void)add_not_list_to_class(classbits, &class_uchardata, options, - cd, PRIV(vspace_list)); - continue; - -#ifdef SUPPORT_UCP - case ESC_p: - case ESC_P: - { - BOOL negated; - unsigned int ptype = 0, pdata = 0; - if (!get_ucp(&ptr, &negated, &ptype, &pdata, errorcodeptr)) - goto FAILED; - *class_uchardata++ = ((escape == ESC_p) != negated)? - XCL_PROP : XCL_NOTPROP; - *class_uchardata++ = ptype; - *class_uchardata++ = pdata; - xclass_has_prop = TRUE; - class_has_8bitchar--; /* Undo! */ - continue; - } -#endif - /* Unrecognized escapes are faulted if PCRE is running in its - strict mode. By default, for compatibility with Perl, they are - treated as literals. */ - - default: - if ((options & PCRE_EXTRA) != 0) - { - *errorcodeptr = ERR7; - goto FAILED; - } - class_has_8bitchar--; /* Undo the speculative increase. */ - class_one_char -= 2; /* Undo the speculative increase. */ - c = *ptr; /* Get the final character and fall through */ - break; - } - } - - /* Fall through if the escape just defined a single character (c >= 0). - This may be greater than 256. */ - - escape = 0; - - } /* End of backslash handling */ - - /* A character may be followed by '-' to form a range. However, Perl does - not permit ']' to be the end of the range. A '-' character at the end is - treated as a literal. Perl ignores orphaned \E sequences entirely. The - code for handling \Q and \E is messy. */ - - CHECK_RANGE: - while (ptr[1] == CHAR_BACKSLASH && ptr[2] == CHAR_E) - { - inescq = FALSE; - ptr += 2; - } - oldptr = ptr; - - /* Remember if \r or \n were explicitly used */ - - if (c == CHAR_CR || c == CHAR_NL) cd->external_flags |= PCRE_HASCRORLF; - - /* Check for range */ - - if (!inescq && ptr[1] == CHAR_MINUS) - { - pcre_uint32 d; - ptr += 2; - while (*ptr == CHAR_BACKSLASH && ptr[1] == CHAR_E) ptr += 2; - - /* If we hit \Q (not followed by \E) at this point, go into escaped - mode. */ - - while (*ptr == CHAR_BACKSLASH && ptr[1] == CHAR_Q) - { - ptr += 2; - if (*ptr == CHAR_BACKSLASH && ptr[1] == CHAR_E) - { ptr += 2; continue; } - inescq = TRUE; - break; - } - - /* Minus (hyphen) at the end of a class is treated as a literal, so put - back the pointer and jump to handle the character that preceded it. */ - - if (*ptr == CHAR_NULL || (!inescq && *ptr == CHAR_RIGHT_SQUARE_BRACKET)) - { - ptr = oldptr; - goto CLASS_SINGLE_CHARACTER; - } - - /* Otherwise, we have a potential range; pick up the next character */ - -#ifdef SUPPORT_UTF - if (utf) - { /* Braces are required because the */ - GETCHARLEN(d, ptr, ptr); /* macro generates multiple statements */ - } - else -#endif - d = *ptr; /* Not UTF-8 mode */ - - /* The second part of a range can be a single-character escape - sequence, but not any of the other escapes. Perl treats a hyphen as a - literal in such circumstances. However, in Perl's warning mode, a - warning is given, so PCRE now faults it as it is almost certainly a - mistake on the user's part. */ - - if (!inescq) - { - if (d == CHAR_BACKSLASH) - { - int descape; - descape = check_escape(&ptr, &d, errorcodeptr, cd->bracount, options, TRUE); - if (*errorcodeptr != 0) goto FAILED; - - /* 0 means a character was put into d; \b is backspace; any other - special causes an error. */ - - if (descape != 0) - { - if (descape == ESC_b) d = CHAR_BS; else - { - *errorcodeptr = ERR83; - goto FAILED; - } - } - } - - /* A hyphen followed by a POSIX class is treated in the same way. */ - - else if (d == CHAR_LEFT_SQUARE_BRACKET && - (ptr[1] == CHAR_COLON || ptr[1] == CHAR_DOT || - ptr[1] == CHAR_EQUALS_SIGN) && - check_posix_syntax(ptr, &tempptr)) - { - *errorcodeptr = ERR83; - goto FAILED; - } - } - - /* Check that the two values are in the correct order. Optimize - one-character ranges. */ - - if (d < c) - { - *errorcodeptr = ERR8; - goto FAILED; - } - if (d == c) goto CLASS_SINGLE_CHARACTER; /* A few lines below */ - - /* We have found a character range, so single character optimizations - cannot be done anymore. Any value greater than 1 indicates that there - is more than one character. */ - - class_one_char = 2; - - /* Remember an explicit \r or \n, and add the range to the class. */ - - if (d == CHAR_CR || d == CHAR_NL) cd->external_flags |= PCRE_HASCRORLF; - - class_has_8bitchar += - add_to_class(classbits, &class_uchardata, options, cd, c, d); - - continue; /* Go get the next char in the class */ - } - - /* Handle a single character - we can get here for a normal non-escape - char, or after \ that introduces a single character or for an apparent - range that isn't. Only the value 1 matters for class_one_char, so don't - increase it if it is already 2 or more ... just in case there's a class - with a zillion characters in it. */ - - CLASS_SINGLE_CHARACTER: - if (class_one_char < 2) class_one_char++; - - /* If class_one_char is 1, we have the first single character in the - class, and there have been no prior ranges, or XCLASS items generated by - escapes. If this is the final character in the class, we can optimize by - turning the item into a 1-character OP_CHAR[I] if it's positive, or - OP_NOT[I] if it's negative. In the positive case, it can cause firstchar - to be set. Otherwise, there can be no first char if this item is first, - whatever repeat count may follow. In the case of reqchar, save the - previous value for reinstating. */ - - if (!inescq && class_one_char == 1 && ptr[1] == CHAR_RIGHT_SQUARE_BRACKET) - { - ptr++; - zeroreqchar = reqchar; - zeroreqcharflags = reqcharflags; - - if (negate_class) - { -#ifdef SUPPORT_UCP - int d; -#endif - if (firstcharflags == REQ_UNSET) firstcharflags = REQ_NONE; - zerofirstchar = firstchar; - zerofirstcharflags = firstcharflags; - - /* For caseless UTF-8 mode when UCP support is available, check - whether this character has more than one other case. If so, generate - a special OP_NOTPROP item instead of OP_NOTI. */ - -#ifdef SUPPORT_UCP - if (utf && (options & PCRE_CASELESS) != 0 && - (d = UCD_CASESET(c)) != 0) - { - *code++ = OP_NOTPROP; - *code++ = PT_CLIST; - *code++ = d; - } - else -#endif - /* Char has only one other case, or UCP not available */ - - { - *code++ = ((options & PCRE_CASELESS) != 0)? OP_NOTI: OP_NOT; -#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 - if (utf && c > MAX_VALUE_FOR_SINGLE_CHAR) - code += PRIV(ord2utf)(c, code); - else -#endif - *code++ = c; - } - - /* We are finished with this character class */ - - goto END_CLASS; - } - - /* For a single, positive character, get the value into mcbuffer, and - then we can handle this with the normal one-character code. */ - -#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 - if (utf && c > MAX_VALUE_FOR_SINGLE_CHAR) - mclength = PRIV(ord2utf)(c, mcbuffer); - else -#endif - { - mcbuffer[0] = c; - mclength = 1; - } - goto ONE_CHAR; - } /* End of 1-char optimization */ - - /* There is more than one character in the class, or an XCLASS item - has been generated. Add this character to the class. */ - - class_has_8bitchar += - add_to_class(classbits, &class_uchardata, options, cd, c, c); - } - - /* Loop until ']' reached. This "while" is the end of the "do" far above. - If we are at the end of an internal nested string, revert to the outer - string. */ - - while (((c = *(++ptr)) != CHAR_NULL || - (nestptr != NULL && - (ptr = nestptr, nestptr = NULL, c = *(++ptr)) != CHAR_NULL)) && - (c != CHAR_RIGHT_SQUARE_BRACKET || inescq)); - - /* Check for missing terminating ']' */ - - if (c == CHAR_NULL) - { - *errorcodeptr = ERR6; - goto FAILED; - } - - /* We will need an XCLASS if data has been placed in class_uchardata. In - the second phase this is a sufficient test. However, in the pre-compile - phase, class_uchardata gets emptied to prevent workspace overflow, so it - only if the very last character in the class needs XCLASS will it contain - anything at this point. For this reason, xclass gets set TRUE above when - uchar_classdata is emptied, and that's why this code is the way it is here - instead of just doing a test on class_uchardata below. */ - -#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 - if (class_uchardata > class_uchardata_base) xclass = TRUE; -#endif - - /* If this is the first thing in the branch, there can be no first char - setting, whatever the repeat count. Any reqchar setting must remain - unchanged after any kind of repeat. */ - - if (firstcharflags == REQ_UNSET) firstcharflags = REQ_NONE; - zerofirstchar = firstchar; - zerofirstcharflags = firstcharflags; - zeroreqchar = reqchar; - zeroreqcharflags = reqcharflags; - - /* If there are characters with values > 255, we have to compile an - extended class, with its own opcode, unless there was a negated special - such as \S in the class, and PCRE_UCP is not set, because in that case all - characters > 255 are in the class, so any that were explicitly given as - well can be ignored. If (when there are explicit characters > 255 that must - be listed) there are no characters < 256, we can omit the bitmap in the - actual compiled code. */ - -#ifdef SUPPORT_UTF - if (xclass && (!should_flip_negation || (options & PCRE_UCP) != 0)) -#elif !defined COMPILE_PCRE8 - if (xclass && !should_flip_negation) -#endif -#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 - { - *class_uchardata++ = XCL_END; /* Marks the end of extra data */ - *code++ = OP_XCLASS; - code += LINK_SIZE; - *code = negate_class? XCL_NOT:0; - if (xclass_has_prop) *code |= XCL_HASPROP; - - /* If the map is required, move up the extra data to make room for it; - otherwise just move the code pointer to the end of the extra data. */ - - if (class_has_8bitchar > 0) - { - *code++ |= XCL_MAP; - memmove(code + (32 / sizeof(pcre_uchar)), code, - IN_UCHARS(class_uchardata - code)); - if (negate_class && !xclass_has_prop) - for (c = 0; c < 32; c++) classbits[c] = ~classbits[c]; - memcpy(code, classbits, 32); - code = class_uchardata + (32 / sizeof(pcre_uchar)); - } - else code = class_uchardata; - - /* Now fill in the complete length of the item */ - - PUT(previous, 1, (int)(code - previous)); - break; /* End of class handling */ - } -#endif - - /* If there are no characters > 255, or they are all to be included or - excluded, set the opcode to OP_CLASS or OP_NCLASS, depending on whether the - whole class was negated and whether there were negative specials such as \S - (non-UCP) in the class. Then copy the 32-byte map into the code vector, - negating it if necessary. */ - - *code++ = (negate_class == should_flip_negation) ? OP_CLASS : OP_NCLASS; - if (lengthptr == NULL) /* Save time in the pre-compile phase */ - { - if (negate_class) - for (c = 0; c < 32; c++) classbits[c] = ~classbits[c]; - memcpy(code, classbits, 32); - } - code += 32 / sizeof(pcre_uchar); - - END_CLASS: - break; - - - /* ===================================================================*/ - /* Various kinds of repeat; '{' is not necessarily a quantifier, but this - has been tested above. */ - - case CHAR_LEFT_CURLY_BRACKET: - if (!is_quantifier) goto NORMAL_CHAR; - ptr = read_repeat_counts(ptr+1, &repeat_min, &repeat_max, errorcodeptr); - if (*errorcodeptr != 0) goto FAILED; - goto REPEAT; - - case CHAR_ASTERISK: - repeat_min = 0; - repeat_max = -1; - goto REPEAT; - - case CHAR_PLUS: - repeat_min = 1; - repeat_max = -1; - goto REPEAT; - - case CHAR_QUESTION_MARK: - repeat_min = 0; - repeat_max = 1; - - REPEAT: - if (previous == NULL) - { - *errorcodeptr = ERR9; - goto FAILED; - } - - if (repeat_min == 0) - { - firstchar = zerofirstchar; /* Adjust for zero repeat */ - firstcharflags = zerofirstcharflags; - reqchar = zeroreqchar; /* Ditto */ - reqcharflags = zeroreqcharflags; - } - - /* Remember whether this is a variable length repeat */ - - reqvary = (repeat_min == repeat_max)? 0 : REQ_VARY; - - op_type = 0; /* Default single-char op codes */ - possessive_quantifier = FALSE; /* Default not possessive quantifier */ - - /* Save start of previous item, in case we have to move it up in order to - insert something before it. */ - - tempcode = previous; - - /* Before checking for a possessive quantifier, we must skip over - whitespace and comments in extended mode because Perl allows white space at - this point. */ - - if ((options & PCRE_EXTENDED) != 0) - { - const pcre_uchar *p = ptr + 1; - for (;;) - { - while (MAX_255(*p) && (cd->ctypes[*p] & ctype_space) != 0) p++; - if (*p != CHAR_NUMBER_SIGN) break; - p++; - while (*p != CHAR_NULL) - { - if (IS_NEWLINE(p)) /* For non-fixed-length newline cases, */ - { /* IS_NEWLINE sets cd->nllen. */ - p += cd->nllen; - break; - } - p++; -#ifdef SUPPORT_UTF - if (utf) FORWARDCHAR(p); -#endif - } /* Loop for comment characters */ - } /* Loop for multiple comments */ - ptr = p - 1; /* Character before the next significant one. */ - } - - /* If the next character is '+', we have a possessive quantifier. This - implies greediness, whatever the setting of the PCRE_UNGREEDY option. - If the next character is '?' this is a minimizing repeat, by default, - but if PCRE_UNGREEDY is set, it works the other way round. We change the - repeat type to the non-default. */ - - if (ptr[1] == CHAR_PLUS) - { - repeat_type = 0; /* Force greedy */ - possessive_quantifier = TRUE; - ptr++; - } - else if (ptr[1] == CHAR_QUESTION_MARK) - { - repeat_type = greedy_non_default; - ptr++; - } - else repeat_type = greedy_default; - - /* If previous was a recursion call, wrap it in atomic brackets so that - previous becomes the atomic group. All recursions were so wrapped in the - past, but it no longer happens for non-repeated recursions. In fact, the - repeated ones could be re-implemented independently so as not to need this, - but for the moment we rely on the code for repeating groups. */ - - if (*previous == OP_RECURSE) - { - memmove(previous + 1 + LINK_SIZE, previous, IN_UCHARS(1 + LINK_SIZE)); - *previous = OP_ONCE; - PUT(previous, 1, 2 + 2*LINK_SIZE); - previous[2 + 2*LINK_SIZE] = OP_KET; - PUT(previous, 3 + 2*LINK_SIZE, 2 + 2*LINK_SIZE); - code += 2 + 2 * LINK_SIZE; - length_prevgroup = 3 + 3*LINK_SIZE; - - /* When actually compiling, we need to check whether this was a forward - reference, and if so, adjust the offset. */ - - if (lengthptr == NULL && cd->hwm >= cd->start_workspace + LINK_SIZE) - { - int offset = GET(cd->hwm, -LINK_SIZE); - if (offset == previous + 1 - cd->start_code) - PUT(cd->hwm, -LINK_SIZE, offset + 1 + LINK_SIZE); - } - } - - /* Now handle repetition for the different types of item. */ - - /* If previous was a character or negated character match, abolish the item - and generate a repeat item instead. If a char item has a minimum of more - than one, ensure that it is set in reqchar - it might not be if a sequence - such as x{3} is the first thing in a branch because the x will have gone - into firstchar instead. */ - - if (*previous == OP_CHAR || *previous == OP_CHARI - || *previous == OP_NOT || *previous == OP_NOTI) - { - switch (*previous) - { - default: /* Make compiler happy. */ - case OP_CHAR: op_type = OP_STAR - OP_STAR; break; - case OP_CHARI: op_type = OP_STARI - OP_STAR; break; - case OP_NOT: op_type = OP_NOTSTAR - OP_STAR; break; - case OP_NOTI: op_type = OP_NOTSTARI - OP_STAR; break; - } - - /* Deal with UTF characters that take up more than one character. It's - easier to write this out separately than try to macrify it. Use c to - hold the length of the character in bytes, plus UTF_LENGTH to flag that - it's a length rather than a small character. */ - -#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 - if (utf && NOT_FIRSTCHAR(code[-1])) - { - pcre_uchar *lastchar = code - 1; - BACKCHAR(lastchar); - c = (int)(code - lastchar); /* Length of UTF-8 character */ - memcpy(utf_chars, lastchar, IN_UCHARS(c)); /* Save the char */ - c |= UTF_LENGTH; /* Flag c as a length */ - } - else -#endif /* SUPPORT_UTF */ - - /* Handle the case of a single charater - either with no UTF support, or - with UTF disabled, or for a single character UTF character. */ - { - c = code[-1]; - if (*previous <= OP_CHARI && repeat_min > 1) - { - reqchar = c; - reqcharflags = req_caseopt | cd->req_varyopt; - } - } - - goto OUTPUT_SINGLE_REPEAT; /* Code shared with single character types */ - } - - /* If previous was a character type match (\d or similar), abolish it and - create a suitable repeat item. The code is shared with single-character - repeats by setting op_type to add a suitable offset into repeat_type. Note - the the Unicode property types will be present only when SUPPORT_UCP is - defined, but we don't wrap the little bits of code here because it just - makes it horribly messy. */ - - else if (*previous < OP_EODN) - { - pcre_uchar *oldcode; - int prop_type, prop_value; - op_type = OP_TYPESTAR - OP_STAR; /* Use type opcodes */ - c = *previous; - - OUTPUT_SINGLE_REPEAT: - if (*previous == OP_PROP || *previous == OP_NOTPROP) - { - prop_type = previous[1]; - prop_value = previous[2]; - } - else prop_type = prop_value = -1; - - oldcode = code; - code = previous; /* Usually overwrite previous item */ - - /* If the maximum is zero then the minimum must also be zero; Perl allows - this case, so we do too - by simply omitting the item altogether. */ - - if (repeat_max == 0) goto END_REPEAT; - - /* Combine the op_type with the repeat_type */ - - repeat_type += op_type; - - /* A minimum of zero is handled either as the special case * or ?, or as - an UPTO, with the maximum given. */ - - if (repeat_min == 0) - { - if (repeat_max == -1) *code++ = OP_STAR + repeat_type; - else if (repeat_max == 1) *code++ = OP_QUERY + repeat_type; - else - { - *code++ = OP_UPTO + repeat_type; - PUT2INC(code, 0, repeat_max); - } - } - - /* A repeat minimum of 1 is optimized into some special cases. If the - maximum is unlimited, we use OP_PLUS. Otherwise, the original item is - left in place and, if the maximum is greater than 1, we use OP_UPTO with - one less than the maximum. */ - - else if (repeat_min == 1) - { - if (repeat_max == -1) - *code++ = OP_PLUS + repeat_type; - else - { - code = oldcode; /* leave previous item in place */ - if (repeat_max == 1) goto END_REPEAT; - *code++ = OP_UPTO + repeat_type; - PUT2INC(code, 0, repeat_max - 1); - } - } - - /* The case {n,n} is just an EXACT, while the general case {n,m} is - handled as an EXACT followed by an UPTO. */ - - else - { - *code++ = OP_EXACT + op_type; /* NB EXACT doesn't have repeat_type */ - PUT2INC(code, 0, repeat_min); - - /* If the maximum is unlimited, insert an OP_STAR. Before doing so, - we have to insert the character for the previous code. For a repeated - Unicode property match, there are two extra bytes that define the - required property. In UTF-8 mode, long characters have their length in - c, with the UTF_LENGTH bit as a flag. */ - - if (repeat_max < 0) - { -#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 - if (utf && (c & UTF_LENGTH) != 0) - { - memcpy(code, utf_chars, IN_UCHARS(c & 7)); - code += c & 7; - } - else -#endif - { - *code++ = c; - if (prop_type >= 0) - { - *code++ = prop_type; - *code++ = prop_value; - } - } - *code++ = OP_STAR + repeat_type; - } - - /* Else insert an UPTO if the max is greater than the min, again - preceded by the character, for the previously inserted code. If the - UPTO is just for 1 instance, we can use QUERY instead. */ - - else if (repeat_max != repeat_min) - { -#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 - if (utf && (c & UTF_LENGTH) != 0) - { - memcpy(code, utf_chars, IN_UCHARS(c & 7)); - code += c & 7; - } - else -#endif - *code++ = c; - if (prop_type >= 0) - { - *code++ = prop_type; - *code++ = prop_value; - } - repeat_max -= repeat_min; - - if (repeat_max == 1) - { - *code++ = OP_QUERY + repeat_type; - } - else - { - *code++ = OP_UPTO + repeat_type; - PUT2INC(code, 0, repeat_max); - } - } - } - - /* The character or character type itself comes last in all cases. */ - -#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 - if (utf && (c & UTF_LENGTH) != 0) - { - memcpy(code, utf_chars, IN_UCHARS(c & 7)); - code += c & 7; - } - else -#endif - *code++ = c; - - /* For a repeated Unicode property match, there are two extra bytes that - define the required property. */ - -#ifdef SUPPORT_UCP - if (prop_type >= 0) - { - *code++ = prop_type; - *code++ = prop_value; - } -#endif - } - - /* If previous was a character class or a back reference, we put the repeat - stuff after it, but just skip the item if the repeat was {0,0}. */ - - else if (*previous == OP_CLASS || *previous == OP_NCLASS || -#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 - *previous == OP_XCLASS || -#endif - *previous == OP_REF || *previous == OP_REFI || - *previous == OP_DNREF || *previous == OP_DNREFI) - { - if (repeat_max == 0) - { - code = previous; - goto END_REPEAT; - } - - if (repeat_min == 0 && repeat_max == -1) - *code++ = OP_CRSTAR + repeat_type; - else if (repeat_min == 1 && repeat_max == -1) - *code++ = OP_CRPLUS + repeat_type; - else if (repeat_min == 0 && repeat_max == 1) - *code++ = OP_CRQUERY + repeat_type; - else - { - *code++ = OP_CRRANGE + repeat_type; - PUT2INC(code, 0, repeat_min); - if (repeat_max == -1) repeat_max = 0; /* 2-byte encoding for max */ - PUT2INC(code, 0, repeat_max); - } - } - - /* If previous was a bracket group, we may have to replicate it in certain - cases. Note that at this point we can encounter only the "basic" bracket - opcodes such as BRA and CBRA, as this is the place where they get converted - into the more special varieties such as BRAPOS and SBRA. A test for >= - OP_ASSERT and <= OP_COND includes ASSERT, ASSERT_NOT, ASSERTBACK, - ASSERTBACK_NOT, ONCE, ONCE_NC, BRA, BRAPOS, CBRA, CBRAPOS, and COND. - Originally, PCRE did not allow repetition of assertions, but now it does, - for Perl compatibility. */ - - else if (*previous >= OP_ASSERT && *previous <= OP_COND) - { - register int i; - int len = (int)(code - previous); - pcre_uchar *bralink = NULL; - pcre_uchar *brazeroptr = NULL; - - /* Repeating a DEFINE group is pointless, but Perl allows the syntax, so - we just ignore the repeat. */ - - if (*previous == OP_COND && previous[LINK_SIZE+1] == OP_DEF) - goto END_REPEAT; - - /* There is no sense in actually repeating assertions. The only potential - use of repetition is in cases when the assertion is optional. Therefore, - if the minimum is greater than zero, just ignore the repeat. If the - maximum is not zero or one, set it to 1. */ - - if (*previous < OP_ONCE) /* Assertion */ - { - if (repeat_min > 0) goto END_REPEAT; - if (repeat_max < 0 || repeat_max > 1) repeat_max = 1; - } - - /* The case of a zero minimum is special because of the need to stick - OP_BRAZERO in front of it, and because the group appears once in the - data, whereas in other cases it appears the minimum number of times. For - this reason, it is simplest to treat this case separately, as otherwise - the code gets far too messy. There are several special subcases when the - minimum is zero. */ - - if (repeat_min == 0) - { - /* If the maximum is also zero, we used to just omit the group from the - output altogether, like this: - - ** if (repeat_max == 0) - ** { - ** code = previous; - ** goto END_REPEAT; - ** } - - However, that fails when a group or a subgroup within it is referenced - as a subroutine from elsewhere in the pattern, so now we stick in - OP_SKIPZERO in front of it so that it is skipped on execution. As we - don't have a list of which groups are referenced, we cannot do this - selectively. - - If the maximum is 1 or unlimited, we just have to stick in the BRAZERO - and do no more at this point. However, we do need to adjust any - OP_RECURSE calls inside the group that refer to the group itself or any - internal or forward referenced group, because the offset is from the - start of the whole regex. Temporarily terminate the pattern while doing - this. */ - - if (repeat_max <= 1) /* Covers 0, 1, and unlimited */ - { - *code = OP_END; - adjust_recurse(previous, 1, utf, cd, save_hwm); - memmove(previous + 1, previous, IN_UCHARS(len)); - code++; - if (repeat_max == 0) - { - *previous++ = OP_SKIPZERO; - goto END_REPEAT; - } - brazeroptr = previous; /* Save for possessive optimizing */ - *previous++ = OP_BRAZERO + repeat_type; - } - - /* If the maximum is greater than 1 and limited, we have to replicate - in a nested fashion, sticking OP_BRAZERO before each set of brackets. - The first one has to be handled carefully because it's the original - copy, which has to be moved up. The remainder can be handled by code - that is common with the non-zero minimum case below. We have to - adjust the value or repeat_max, since one less copy is required. Once - again, we may have to adjust any OP_RECURSE calls inside the group. */ - - else - { - int offset; - *code = OP_END; - adjust_recurse(previous, 2 + LINK_SIZE, utf, cd, save_hwm); - memmove(previous + 2 + LINK_SIZE, previous, IN_UCHARS(len)); - code += 2 + LINK_SIZE; - *previous++ = OP_BRAZERO + repeat_type; - *previous++ = OP_BRA; - - /* We chain together the bracket offset fields that have to be - filled in later when the ends of the brackets are reached. */ - - offset = (bralink == NULL)? 0 : (int)(previous - bralink); - bralink = previous; - PUTINC(previous, 0, offset); - } - - repeat_max--; - } - - /* If the minimum is greater than zero, replicate the group as many - times as necessary, and adjust the maximum to the number of subsequent - copies that we need. If we set a first char from the group, and didn't - set a required char, copy the latter from the former. If there are any - forward reference subroutine calls in the group, there will be entries on - the workspace list; replicate these with an appropriate increment. */ - - else - { - if (repeat_min > 1) - { - /* In the pre-compile phase, we don't actually do the replication. We - just adjust the length as if we had. Do some paranoid checks for - potential integer overflow. The INT64_OR_DOUBLE type is a 64-bit - integer type when available, otherwise double. */ - - if (lengthptr != NULL) - { - int delta = (repeat_min - 1)*length_prevgroup; - if ((INT64_OR_DOUBLE)(repeat_min - 1)* - (INT64_OR_DOUBLE)length_prevgroup > - (INT64_OR_DOUBLE)INT_MAX || - OFLOW_MAX - *lengthptr < delta) - { - *errorcodeptr = ERR20; - goto FAILED; - } - *lengthptr += delta; - } - - /* This is compiling for real. If there is a set first byte for - the group, and we have not yet set a "required byte", set it. Make - sure there is enough workspace for copying forward references before - doing the copy. */ - - else - { - if (groupsetfirstchar && reqcharflags < 0) - { - reqchar = firstchar; - reqcharflags = firstcharflags; - } - - for (i = 1; i < repeat_min; i++) - { - pcre_uchar *hc; - pcre_uchar *this_hwm = cd->hwm; - memcpy(code, previous, IN_UCHARS(len)); - - while (cd->hwm > cd->start_workspace + cd->workspace_size - - WORK_SIZE_SAFETY_MARGIN - (this_hwm - save_hwm)) - { - size_t save_offset = save_hwm - cd->start_workspace; - size_t this_offset = this_hwm - cd->start_workspace; - *errorcodeptr = expand_workspace(cd); - if (*errorcodeptr != 0) goto FAILED; - save_hwm = (pcre_uchar *)cd->start_workspace + save_offset; - this_hwm = (pcre_uchar *)cd->start_workspace + this_offset; - } - - for (hc = save_hwm; hc < this_hwm; hc += LINK_SIZE) - { - PUT(cd->hwm, 0, GET(hc, 0) + len); - cd->hwm += LINK_SIZE; - } - save_hwm = this_hwm; - code += len; - } - } - } - - if (repeat_max > 0) repeat_max -= repeat_min; - } - - /* This code is common to both the zero and non-zero minimum cases. If - the maximum is limited, it replicates the group in a nested fashion, - remembering the bracket starts on a stack. In the case of a zero minimum, - the first one was set up above. In all cases the repeat_max now specifies - the number of additional copies needed. Again, we must remember to - replicate entries on the forward reference list. */ - - if (repeat_max >= 0) - { - /* In the pre-compile phase, we don't actually do the replication. We - just adjust the length as if we had. For each repetition we must add 1 - to the length for BRAZERO and for all but the last repetition we must - add 2 + 2*LINKSIZE to allow for the nesting that occurs. Do some - paranoid checks to avoid integer overflow. The INT64_OR_DOUBLE type is - a 64-bit integer type when available, otherwise double. */ - - if (lengthptr != NULL && repeat_max > 0) - { - int delta = repeat_max * (length_prevgroup + 1 + 2 + 2*LINK_SIZE) - - 2 - 2*LINK_SIZE; /* Last one doesn't nest */ - if ((INT64_OR_DOUBLE)repeat_max * - (INT64_OR_DOUBLE)(length_prevgroup + 1 + 2 + 2*LINK_SIZE) - > (INT64_OR_DOUBLE)INT_MAX || - OFLOW_MAX - *lengthptr < delta) - { - *errorcodeptr = ERR20; - goto FAILED; - } - *lengthptr += delta; - } - - /* This is compiling for real */ - - else for (i = repeat_max - 1; i >= 0; i--) - { - pcre_uchar *hc; - pcre_uchar *this_hwm = cd->hwm; - - *code++ = OP_BRAZERO + repeat_type; - - /* All but the final copy start a new nesting, maintaining the - chain of brackets outstanding. */ - - if (i != 0) - { - int offset; - *code++ = OP_BRA; - offset = (bralink == NULL)? 0 : (int)(code - bralink); - bralink = code; - PUTINC(code, 0, offset); - } - - memcpy(code, previous, IN_UCHARS(len)); - - /* Ensure there is enough workspace for forward references before - copying them. */ - - while (cd->hwm > cd->start_workspace + cd->workspace_size - - WORK_SIZE_SAFETY_MARGIN - (this_hwm - save_hwm)) - { - size_t save_offset = save_hwm - cd->start_workspace; - size_t this_offset = this_hwm - cd->start_workspace; - *errorcodeptr = expand_workspace(cd); - if (*errorcodeptr != 0) goto FAILED; - save_hwm = (pcre_uchar *)cd->start_workspace + save_offset; - this_hwm = (pcre_uchar *)cd->start_workspace + this_offset; - } - - for (hc = save_hwm; hc < this_hwm; hc += LINK_SIZE) - { - PUT(cd->hwm, 0, GET(hc, 0) + len + ((i != 0)? 2+LINK_SIZE : 1)); - cd->hwm += LINK_SIZE; - } - save_hwm = this_hwm; - code += len; - } - - /* Now chain through the pending brackets, and fill in their length - fields (which are holding the chain links pro tem). */ - - while (bralink != NULL) - { - int oldlinkoffset; - int offset = (int)(code - bralink + 1); - pcre_uchar *bra = code - offset; - oldlinkoffset = GET(bra, 1); - bralink = (oldlinkoffset == 0)? NULL : bralink - oldlinkoffset; - *code++ = OP_KET; - PUTINC(code, 0, offset); - PUT(bra, 1, offset); - } - } - - /* If the maximum is unlimited, set a repeater in the final copy. For - ONCE brackets, that's all we need to do. However, possessively repeated - ONCE brackets can be converted into non-capturing brackets, as the - behaviour of (?:xx)++ is the same as (?>xx)++ and this saves having to - deal with possessive ONCEs specially. - - Otherwise, when we are doing the actual compile phase, check to see - whether this group is one that could match an empty string. If so, - convert the initial operator to the S form (e.g. OP_BRA -> OP_SBRA) so - that runtime checking can be done. [This check is also applied to ONCE - groups at runtime, but in a different way.] - - Then, if the quantifier was possessive and the bracket is not a - conditional, we convert the BRA code to the POS form, and the KET code to - KETRPOS. (It turns out to be convenient at runtime to detect this kind of - subpattern at both the start and at the end.) The use of special opcodes - makes it possible to reduce greatly the stack usage in pcre_exec(). If - the group is preceded by OP_BRAZERO, convert this to OP_BRAPOSZERO. - - Then, if the minimum number of matches is 1 or 0, cancel the possessive - flag so that the default action below, of wrapping everything inside - atomic brackets, does not happen. When the minimum is greater than 1, - there will be earlier copies of the group, and so we still have to wrap - the whole thing. */ - - else - { - pcre_uchar *ketcode = code - 1 - LINK_SIZE; - pcre_uchar *bracode = ketcode - GET(ketcode, 1); - - /* Convert possessive ONCE brackets to non-capturing */ - - if ((*bracode == OP_ONCE || *bracode == OP_ONCE_NC) && - possessive_quantifier) *bracode = OP_BRA; - - /* For non-possessive ONCE brackets, all we need to do is to - set the KET. */ - - if (*bracode == OP_ONCE || *bracode == OP_ONCE_NC) - *ketcode = OP_KETRMAX + repeat_type; - - /* Handle non-ONCE brackets and possessive ONCEs (which have been - converted to non-capturing above). */ - - else - { - /* In the compile phase, check for empty string matching. */ - - if (lengthptr == NULL) - { - pcre_uchar *scode = bracode; - do - { - if (could_be_empty_branch(scode, ketcode, utf, cd, NULL)) - { - *bracode += OP_SBRA - OP_BRA; - break; - } - scode += GET(scode, 1); - } - while (*scode == OP_ALT); - } - - /* Handle possessive quantifiers. */ - - if (possessive_quantifier) - { - /* For COND brackets, we wrap the whole thing in a possessively - repeated non-capturing bracket, because we have not invented POS - versions of the COND opcodes. Because we are moving code along, we - must ensure that any pending recursive references are updated. */ - - if (*bracode == OP_COND || *bracode == OP_SCOND) - { - int nlen = (int)(code - bracode); - *code = OP_END; - adjust_recurse(bracode, 1 + LINK_SIZE, utf, cd, save_hwm); - memmove(bracode + 1 + LINK_SIZE, bracode, IN_UCHARS(nlen)); - code += 1 + LINK_SIZE; - nlen += 1 + LINK_SIZE; - *bracode = OP_BRAPOS; - *code++ = OP_KETRPOS; - PUTINC(code, 0, nlen); - PUT(bracode, 1, nlen); - } - - /* For non-COND brackets, we modify the BRA code and use KETRPOS. */ - - else - { - *bracode += 1; /* Switch to xxxPOS opcodes */ - *ketcode = OP_KETRPOS; - } - - /* If the minimum is zero, mark it as possessive, then unset the - possessive flag when the minimum is 0 or 1. */ - - if (brazeroptr != NULL) *brazeroptr = OP_BRAPOSZERO; - if (repeat_min < 2) possessive_quantifier = FALSE; - } - - /* Non-possessive quantifier */ - - else *ketcode = OP_KETRMAX + repeat_type; - } - } - } - - /* If previous is OP_FAIL, it was generated by an empty class [] in - JavaScript mode. The other ways in which OP_FAIL can be generated, that is - by (*FAIL) or (?!) set previous to NULL, which gives a "nothing to repeat" - error above. We can just ignore the repeat in JS case. */ - - else if (*previous == OP_FAIL) goto END_REPEAT; - - /* Else there's some kind of shambles */ - - else - { - *errorcodeptr = ERR11; - goto FAILED; - } - - /* If the character following a repeat is '+', possessive_quantifier is - TRUE. For some opcodes, there are special alternative opcodes for this - case. For anything else, we wrap the entire repeated item inside OP_ONCE - brackets. Logically, the '+' notation is just syntactic sugar, taken from - Sun's Java package, but the special opcodes can optimize it. - - Some (but not all) possessively repeated subpatterns have already been - completely handled in the code just above. For them, possessive_quantifier - is always FALSE at this stage. Note that the repeated item starts at - tempcode, not at previous, which might be the first part of a string whose - (former) last char we repeated. */ - - if (possessive_quantifier) - { - int len; - - /* Possessifying an EXACT quantifier has no effect, so we can ignore it. - However, QUERY, STAR, or UPTO may follow (for quantifiers such as {5,6}, - {5,}, or {5,10}). We skip over an EXACT item; if the length of what - remains is greater than zero, there's a further opcode that can be - handled. If not, do nothing, leaving the EXACT alone. */ - - switch(*tempcode) - { - case OP_TYPEEXACT: - tempcode += PRIV(OP_lengths)[*tempcode] + - ((tempcode[1 + IMM2_SIZE] == OP_PROP - || tempcode[1 + IMM2_SIZE] == OP_NOTPROP)? 2 : 0); - break; - - /* CHAR opcodes are used for exacts whose count is 1. */ - - case OP_CHAR: - case OP_CHARI: - case OP_NOT: - case OP_NOTI: - case OP_EXACT: - case OP_EXACTI: - case OP_NOTEXACT: - case OP_NOTEXACTI: - tempcode += PRIV(OP_lengths)[*tempcode]; -#ifdef SUPPORT_UTF - if (utf && HAS_EXTRALEN(tempcode[-1])) - tempcode += GET_EXTRALEN(tempcode[-1]); -#endif - break; - - /* For the class opcodes, the repeat operator appears at the end; - adjust tempcode to point to it. */ - - case OP_CLASS: - case OP_NCLASS: - tempcode += 1 + 32/sizeof(pcre_uchar); - break; - -#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 - case OP_XCLASS: - tempcode += GET(tempcode, 1); - break; -#endif - } - - /* If tempcode is equal to code (which points to the end of the repeated - item), it means we have skipped an EXACT item but there is no following - QUERY, STAR, or UPTO; the value of len will be 0, and we do nothing. In - all other cases, tempcode will be pointing to the repeat opcode, and will - be less than code, so the value of len will be greater than 0. */ - - len = (int)(code - tempcode); - if (len > 0) - { - unsigned int repcode = *tempcode; - - /* There is a table for possessifying opcodes, all of which are less - than OP_CALLOUT. A zero entry means there is no possessified version. - */ - - if (repcode < OP_CALLOUT && opcode_possessify[repcode] > 0) - *tempcode = opcode_possessify[repcode]; - - /* For opcode without a special possessified version, wrap the item in - ONCE brackets. Because we are moving code along, we must ensure that any - pending recursive references are updated. */ - - else - { - *code = OP_END; - adjust_recurse(tempcode, 1 + LINK_SIZE, utf, cd, save_hwm); - memmove(tempcode + 1 + LINK_SIZE, tempcode, IN_UCHARS(len)); - code += 1 + LINK_SIZE; - len += 1 + LINK_SIZE; - tempcode[0] = OP_ONCE; - *code++ = OP_KET; - PUTINC(code, 0, len); - PUT(tempcode, 1, len); - } - } - -#ifdef NEVER - if (len > 0) switch (*tempcode) - { - case OP_STAR: *tempcode = OP_POSSTAR; break; - case OP_PLUS: *tempcode = OP_POSPLUS; break; - case OP_QUERY: *tempcode = OP_POSQUERY; break; - case OP_UPTO: *tempcode = OP_POSUPTO; break; - - case OP_STARI: *tempcode = OP_POSSTARI; break; - case OP_PLUSI: *tempcode = OP_POSPLUSI; break; - case OP_QUERYI: *tempcode = OP_POSQUERYI; break; - case OP_UPTOI: *tempcode = OP_POSUPTOI; break; - - case OP_NOTSTAR: *tempcode = OP_NOTPOSSTAR; break; - case OP_NOTPLUS: *tempcode = OP_NOTPOSPLUS; break; - case OP_NOTQUERY: *tempcode = OP_NOTPOSQUERY; break; - case OP_NOTUPTO: *tempcode = OP_NOTPOSUPTO; break; - - case OP_NOTSTARI: *tempcode = OP_NOTPOSSTARI; break; - case OP_NOTPLUSI: *tempcode = OP_NOTPOSPLUSI; break; - case OP_NOTQUERYI: *tempcode = OP_NOTPOSQUERYI; break; - case OP_NOTUPTOI: *tempcode = OP_NOTPOSUPTOI; break; - - case OP_TYPESTAR: *tempcode = OP_TYPEPOSSTAR; break; - case OP_TYPEPLUS: *tempcode = OP_TYPEPOSPLUS; break; - case OP_TYPEQUERY: *tempcode = OP_TYPEPOSQUERY; break; - case OP_TYPEUPTO: *tempcode = OP_TYPEPOSUPTO; break; - - case OP_CRSTAR: *tempcode = OP_CRPOSSTAR; break; - case OP_CRPLUS: *tempcode = OP_CRPOSPLUS; break; - case OP_CRQUERY: *tempcode = OP_CRPOSQUERY; break; - case OP_CRRANGE: *tempcode = OP_CRPOSRANGE; break; - - /* Because we are moving code along, we must ensure that any - pending recursive references are updated. */ - - default: - *code = OP_END; - adjust_recurse(tempcode, 1 + LINK_SIZE, utf, cd, save_hwm); - memmove(tempcode + 1 + LINK_SIZE, tempcode, IN_UCHARS(len)); - code += 1 + LINK_SIZE; - len += 1 + LINK_SIZE; - tempcode[0] = OP_ONCE; - *code++ = OP_KET; - PUTINC(code, 0, len); - PUT(tempcode, 1, len); - break; - } -#endif - } - - /* In all case we no longer have a previous item. We also set the - "follows varying string" flag for subsequently encountered reqchars if - it isn't already set and we have just passed a varying length item. */ - - END_REPEAT: - previous = NULL; - cd->req_varyopt |= reqvary; - break; - - - /* ===================================================================*/ - /* Start of nested parenthesized sub-expression, or comment or lookahead or - lookbehind or option setting or condition or all the other extended - parenthesis forms. */ - - case CHAR_LEFT_PARENTHESIS: - newoptions = options; - skipbytes = 0; - bravalue = OP_CBRA; - save_hwm = cd->hwm; - reset_bracount = FALSE; - - /* First deal with various "verbs" that can be introduced by '*'. */ - - ptr++; - if (ptr[0] == CHAR_ASTERISK && (ptr[1] == ':' - || (MAX_255(ptr[1]) && ((cd->ctypes[ptr[1]] & ctype_letter) != 0)))) - { - int i, namelen; - int arglen = 0; - const char *vn = verbnames; - const pcre_uchar *name = ptr + 1; - const pcre_uchar *arg = NULL; - previous = NULL; - ptr++; - while (MAX_255(*ptr) && (cd->ctypes[*ptr] & ctype_letter) != 0) ptr++; - namelen = (int)(ptr - name); - - /* It appears that Perl allows any characters whatsoever, other than - a closing parenthesis, to appear in arguments, so we no longer insist on - letters, digits, and underscores. */ - - if (*ptr == CHAR_COLON) - { - arg = ++ptr; - while (*ptr != CHAR_NULL && *ptr != CHAR_RIGHT_PARENTHESIS) ptr++; - arglen = (int)(ptr - arg); - if ((unsigned int)arglen > MAX_MARK) - { - *errorcodeptr = ERR75; - goto FAILED; - } - } - - if (*ptr != CHAR_RIGHT_PARENTHESIS) - { - *errorcodeptr = ERR60; - goto FAILED; - } - - /* Scan the table of verb names */ - - for (i = 0; i < verbcount; i++) - { - if (namelen == verbs[i].len && - STRNCMP_UC_C8(name, vn, namelen) == 0) - { - int setverb; - - /* Check for open captures before ACCEPT and convert it to - ASSERT_ACCEPT if in an assertion. */ - - if (verbs[i].op == OP_ACCEPT) - { - open_capitem *oc; - if (arglen != 0) - { - *errorcodeptr = ERR59; - goto FAILED; - } - cd->had_accept = TRUE; - for (oc = cd->open_caps; oc != NULL; oc = oc->next) - { - *code++ = OP_CLOSE; - PUT2INC(code, 0, oc->number); - } - setverb = *code++ = - (cd->assert_depth > 0)? OP_ASSERT_ACCEPT : OP_ACCEPT; - - /* Do not set firstchar after *ACCEPT */ - if (firstcharflags == REQ_UNSET) firstcharflags = REQ_NONE; - } - - /* Handle other cases with/without an argument */ - - else if (arglen == 0) - { - if (verbs[i].op < 0) /* Argument is mandatory */ - { - *errorcodeptr = ERR66; - goto FAILED; - } - setverb = *code++ = verbs[i].op; - } - - else - { - if (verbs[i].op_arg < 0) /* Argument is forbidden */ - { - *errorcodeptr = ERR59; - goto FAILED; - } - setverb = *code++ = verbs[i].op_arg; - *code++ = arglen; - memcpy(code, arg, IN_UCHARS(arglen)); - code += arglen; - *code++ = 0; - } - - switch (setverb) - { - case OP_THEN: - case OP_THEN_ARG: - cd->external_flags |= PCRE_HASTHEN; - break; - - case OP_PRUNE: - case OP_PRUNE_ARG: - case OP_SKIP: - case OP_SKIP_ARG: - cd->had_pruneorskip = TRUE; - break; - } - - break; /* Found verb, exit loop */ - } - - vn += verbs[i].len + 1; - } - - if (i < verbcount) continue; /* Successfully handled a verb */ - *errorcodeptr = ERR60; /* Verb not recognized */ - goto FAILED; - } - - /* Deal with the extended parentheses; all are introduced by '?', and the - appearance of any of them means that this is not a capturing group. */ - - else if (*ptr == CHAR_QUESTION_MARK) - { - int i, set, unset, namelen; - int *optset; - const pcre_uchar *name; - pcre_uchar *slot; - - switch (*(++ptr)) - { - case CHAR_NUMBER_SIGN: /* Comment; skip to ket */ - ptr++; - while (*ptr != CHAR_NULL && *ptr != CHAR_RIGHT_PARENTHESIS) ptr++; - if (*ptr == CHAR_NULL) - { - *errorcodeptr = ERR18; - goto FAILED; - } - continue; - - - /* ------------------------------------------------------------ */ - case CHAR_VERTICAL_LINE: /* Reset capture count for each branch */ - reset_bracount = TRUE; - /* Fall through */ - - /* ------------------------------------------------------------ */ - case CHAR_COLON: /* Non-capturing bracket */ - bravalue = OP_BRA; - ptr++; - break; - - - /* ------------------------------------------------------------ */ - case CHAR_LEFT_PARENTHESIS: - bravalue = OP_COND; /* Conditional group */ - tempptr = ptr; - - /* A condition can be an assertion, a number (referring to a numbered - group's having been set), a name (referring to a named group), or 'R', - referring to recursion. R and R&name are also permitted for - recursion tests. - - There are ways of testing a named group: (?(name)) is used by Python; - Perl 5.10 onwards uses (?() or (?('name')). - - There is one unfortunate ambiguity, caused by history. 'R' can be the - recursive thing or the name 'R' (and similarly for 'R' followed by - digits). We look for a name first; if not found, we try the other case. - - For compatibility with auto-callouts, we allow a callout to be - specified before a condition that is an assertion. First, check for the - syntax of a callout; if found, adjust the temporary pointer that is - used to check for an assertion condition. That's all that is needed! */ - - if (ptr[1] == CHAR_QUESTION_MARK && ptr[2] == CHAR_C) - { - for (i = 3;; i++) if (!IS_DIGIT(ptr[i])) break; - if (ptr[i] == CHAR_RIGHT_PARENTHESIS) - tempptr += i + 1; - } - - /* For conditions that are assertions, check the syntax, and then exit - the switch. This will take control down to where bracketed groups, - including assertions, are processed. */ - - if (tempptr[1] == CHAR_QUESTION_MARK && - (tempptr[2] == CHAR_EQUALS_SIGN || - tempptr[2] == CHAR_EXCLAMATION_MARK || - tempptr[2] == CHAR_LESS_THAN_SIGN)) - break; - - /* Other conditions use OP_CREF/OP_DNCREF/OP_RREF/OP_DNRREF, and all - need to skip at least 1+IMM2_SIZE bytes at the start of the group. */ - - code[1+LINK_SIZE] = OP_CREF; - skipbytes = 1+IMM2_SIZE; - refsign = -1; /* => not a number */ - namelen = -1; /* => not a name; must set to avoid warning */ - name = NULL; /* Always set to avoid warning */ - recno = 0; /* Always set to avoid warning */ - - /* Check for a test for recursion in a named group. */ - - ptr++; - if (*ptr == CHAR_R && ptr[1] == CHAR_AMPERSAND) - { - terminator = -1; - ptr += 2; - code[1+LINK_SIZE] = OP_RREF; /* Change the type of test */ - } - - /* Check for a test for a named group's having been set, using the Perl - syntax (?() or (?('name'), and also allow for the original PCRE - syntax of (?(name) or for (?(+n), (?(-n), and just (?(n). */ - - else if (*ptr == CHAR_LESS_THAN_SIGN) - { - terminator = CHAR_GREATER_THAN_SIGN; - ptr++; - } - else if (*ptr == CHAR_APOSTROPHE) - { - terminator = CHAR_APOSTROPHE; - ptr++; - } - else - { - terminator = CHAR_NULL; - if (*ptr == CHAR_MINUS || *ptr == CHAR_PLUS) refsign = *ptr++; - else if (IS_DIGIT(*ptr)) refsign = 0; - } - - /* Handle a number */ - - if (refsign >= 0) - { - while (IS_DIGIT(*ptr)) - { - recno = recno * 10 + (int)(*ptr - CHAR_0); - ptr++; - } - } - - /* Otherwise we expect to read a name; anything else is an error. When - a name is one of a number of duplicates, a different opcode is used and - it needs more memory. Unfortunately we cannot tell whether a name is a - duplicate in the first pass, so we have to allow for more memory. */ - - else - { - if (IS_DIGIT(*ptr)) - { - *errorcodeptr = ERR84; - goto FAILED; - } - if (!MAX_255(*ptr) || (cd->ctypes[*ptr] & ctype_word) == 0) - { - *errorcodeptr = ERR28; /* Assertion expected */ - goto FAILED; - } - name = ptr++; - while (MAX_255(*ptr) && (cd->ctypes[*ptr] & ctype_word) != 0) - { - ptr++; - } - namelen = (int)(ptr - name); - if (lengthptr != NULL && (options & PCRE_DUPNAMES) != 0) - *lengthptr += IMM2_SIZE; - } - - /* Check the terminator */ - - if ((terminator > 0 && *ptr++ != (pcre_uchar)terminator) || - *ptr++ != CHAR_RIGHT_PARENTHESIS) - { - ptr--; /* Error offset */ - *errorcodeptr = ERR26; /* Malformed number or name */ - goto FAILED; - } - - /* Do no further checking in the pre-compile phase. */ - - if (lengthptr != NULL) break; - - /* In the real compile we do the work of looking for the actual - reference. If refsign is not negative, it means we have a number in - recno. */ - - if (refsign >= 0) - { - if (recno <= 0) - { - *errorcodeptr = ERR35; - goto FAILED; - } - if (refsign != 0) recno = (refsign == CHAR_MINUS)? - cd->bracount - recno + 1 : recno + cd->bracount; - if (recno <= 0 || recno > cd->final_bracount) - { - *errorcodeptr = ERR15; - goto FAILED; - } - PUT2(code, 2+LINK_SIZE, recno); - break; - } - - /* Otherwise look for the name. */ - - slot = cd->name_table; - for (i = 0; i < cd->names_found; i++) - { - if (STRNCMP_UC_UC(name, slot+IMM2_SIZE, namelen) == 0) break; - slot += cd->name_entry_size; - } - - /* Found the named subpattern. If the name is duplicated, add one to - the opcode to change CREF/RREF into DNCREF/DNRREF and insert - appropriate data values. Otherwise, just insert the unique subpattern - number. */ - - if (i < cd->names_found) - { - int offset = i++; - int count = 1; - recno = GET2(slot, 0); /* Number from first found */ - for (; i < cd->names_found; i++) - { - slot += cd->name_entry_size; - if (STRNCMP_UC_UC(name, slot+IMM2_SIZE, namelen) != 0 || - (slot+IMM2_SIZE)[namelen] != 0) break; - count++; - } - - if (count > 1) - { - PUT2(code, 2+LINK_SIZE, offset); - PUT2(code, 2+LINK_SIZE+IMM2_SIZE, count); - skipbytes += IMM2_SIZE; - code[1+LINK_SIZE]++; - } - else /* Not a duplicated name */ - { - PUT2(code, 2+LINK_SIZE, recno); - } - } - - /* If terminator == CHAR_NULL it means that the name followed directly - after the opening parenthesis [e.g. (?(abc)...] and in this case there - are some further alternatives to try. For the cases where terminator != - CHAR_NULL [things like (?(... or (?('name')... or (?(R&name)... ] - we have now checked all the possibilities, so give an error. */ - - else if (terminator != CHAR_NULL) - { - *errorcodeptr = ERR15; - goto FAILED; - } - - /* Check for (?(R) for recursion. Allow digits after R to specify a - specific group number. */ - - else if (*name == CHAR_R) - { - recno = 0; - for (i = 1; i < namelen; i++) - { - if (!IS_DIGIT(name[i])) - { - *errorcodeptr = ERR15; - goto FAILED; - } - recno = recno * 10 + name[i] - CHAR_0; - } - if (recno == 0) recno = RREF_ANY; - code[1+LINK_SIZE] = OP_RREF; /* Change test type */ - PUT2(code, 2+LINK_SIZE, recno); - } - - /* Similarly, check for the (?(DEFINE) "condition", which is always - false. */ - - else if (namelen == 6 && STRNCMP_UC_C8(name, STRING_DEFINE, 6) == 0) - { - code[1+LINK_SIZE] = OP_DEF; - skipbytes = 1; - } - - /* Reference to an unidentified subpattern. */ - - else - { - *errorcodeptr = ERR15; - goto FAILED; - } - break; - - - /* ------------------------------------------------------------ */ - case CHAR_EQUALS_SIGN: /* Positive lookahead */ - bravalue = OP_ASSERT; - cd->assert_depth += 1; - ptr++; - break; - - /* Optimize (?!) to (*FAIL) unless it is quantified - which is a weird - thing to do, but Perl allows all assertions to be quantified, and when - they contain capturing parentheses there may be a potential use for - this feature. Not that that applies to a quantified (?!) but we allow - it for uniformity. */ - - /* ------------------------------------------------------------ */ - case CHAR_EXCLAMATION_MARK: /* Negative lookahead */ - ptr++; - if (*ptr == CHAR_RIGHT_PARENTHESIS && ptr[1] != CHAR_ASTERISK && - ptr[1] != CHAR_PLUS && ptr[1] != CHAR_QUESTION_MARK && - (ptr[1] != CHAR_LEFT_CURLY_BRACKET || !is_counted_repeat(ptr+2))) - { - *code++ = OP_FAIL; - previous = NULL; - continue; - } - bravalue = OP_ASSERT_NOT; - cd->assert_depth += 1; - break; - - - /* ------------------------------------------------------------ */ - case CHAR_LESS_THAN_SIGN: /* Lookbehind or named define */ - switch (ptr[1]) - { - case CHAR_EQUALS_SIGN: /* Positive lookbehind */ - bravalue = OP_ASSERTBACK; - cd->assert_depth += 1; - ptr += 2; - break; - - case CHAR_EXCLAMATION_MARK: /* Negative lookbehind */ - bravalue = OP_ASSERTBACK_NOT; - cd->assert_depth += 1; - ptr += 2; - break; - - default: /* Could be name define, else bad */ - if (MAX_255(ptr[1]) && (cd->ctypes[ptr[1]] & ctype_word) != 0) - goto DEFINE_NAME; - ptr++; /* Correct offset for error */ - *errorcodeptr = ERR24; - goto FAILED; - } - break; - - - /* ------------------------------------------------------------ */ - case CHAR_GREATER_THAN_SIGN: /* One-time brackets */ - bravalue = OP_ONCE; - ptr++; - break; - - - /* ------------------------------------------------------------ */ - case CHAR_C: /* Callout - may be followed by digits; */ - previous_callout = code; /* Save for later completion */ - after_manual_callout = 1; /* Skip one item before completing */ - *code++ = OP_CALLOUT; - { - int n = 0; - ptr++; - while(IS_DIGIT(*ptr)) - n = n * 10 + *ptr++ - CHAR_0; - if (*ptr != CHAR_RIGHT_PARENTHESIS) - { - *errorcodeptr = ERR39; - goto FAILED; - } - if (n > 255) - { - *errorcodeptr = ERR38; - goto FAILED; - } - *code++ = n; - PUT(code, 0, (int)(ptr - cd->start_pattern + 1)); /* Pattern offset */ - PUT(code, LINK_SIZE, 0); /* Default length */ - code += 2 * LINK_SIZE; - } - previous = NULL; - continue; - - - /* ------------------------------------------------------------ */ - case CHAR_P: /* Python-style named subpattern handling */ - if (*(++ptr) == CHAR_EQUALS_SIGN || - *ptr == CHAR_GREATER_THAN_SIGN) /* Reference or recursion */ - { - is_recurse = *ptr == CHAR_GREATER_THAN_SIGN; - terminator = CHAR_RIGHT_PARENTHESIS; - goto NAMED_REF_OR_RECURSE; - } - else if (*ptr != CHAR_LESS_THAN_SIGN) /* Test for Python-style defn */ - { - *errorcodeptr = ERR41; - goto FAILED; - } - /* Fall through to handle (?P< as (?< is handled */ - - - /* ------------------------------------------------------------ */ - DEFINE_NAME: /* Come here from (?< handling */ - case CHAR_APOSTROPHE: - terminator = (*ptr == CHAR_LESS_THAN_SIGN)? - CHAR_GREATER_THAN_SIGN : CHAR_APOSTROPHE; - name = ++ptr; - if (IS_DIGIT(*ptr)) - { - *errorcodeptr = ERR84; /* Group name must start with non-digit */ - goto FAILED; - } - while (MAX_255(*ptr) && (cd->ctypes[*ptr] & ctype_word) != 0) ptr++; - namelen = (int)(ptr - name); - - /* In the pre-compile phase, do a syntax check, remember the longest - name, and then remember the group in a vector, expanding it if - necessary. Duplicates for the same number are skipped; other duplicates - are checked for validity. In the actual compile, there is nothing to - do. */ - - if (lengthptr != NULL) - { - named_group *ng; - pcre_uint32 number = cd->bracount + 1; - - if (*ptr != (pcre_uchar)terminator) - { - *errorcodeptr = ERR42; - goto FAILED; - } - - if (cd->names_found >= MAX_NAME_COUNT) - { - *errorcodeptr = ERR49; - goto FAILED; - } - - if (namelen + IMM2_SIZE + 1 > cd->name_entry_size) - { - cd->name_entry_size = namelen + IMM2_SIZE + 1; - if (namelen > MAX_NAME_SIZE) - { - *errorcodeptr = ERR48; - goto FAILED; - } - } - - /* Scan the list to check for duplicates. For duplicate names, if the - number is the same, break the loop, which causes the name to be - discarded; otherwise, if DUPNAMES is not set, give an error. - If it is set, allow the name with a different number, but continue - scanning in case this is a duplicate with the same number. For - non-duplicate names, give an error if the number is duplicated. */ - - ng = cd->named_groups; - for (i = 0; i < cd->names_found; i++, ng++) - { - if (namelen == ng->length && - STRNCMP_UC_UC(name, ng->name, namelen) == 0) - { - if (ng->number == number) break; - if ((options & PCRE_DUPNAMES) == 0) - { - *errorcodeptr = ERR43; - goto FAILED; - } - cd->dupnames = TRUE; /* Duplicate names exist */ - } - else if (ng->number == number) - { - *errorcodeptr = ERR65; - goto FAILED; - } - } - - if (i >= cd->names_found) /* Not a duplicate with same number */ - { - /* Increase the list size if necessary */ - - if (cd->names_found >= cd->named_group_list_size) - { - int newsize = cd->named_group_list_size * 2; - named_group *newspace = (PUBL(malloc)) - (newsize * sizeof(named_group)); - - if (newspace == NULL) - { - *errorcodeptr = ERR21; - goto FAILED; - } - - memcpy(newspace, cd->named_groups, - cd->named_group_list_size * sizeof(named_group)); - if (cd->named_group_list_size > NAMED_GROUP_LIST_SIZE) - (PUBL(free))((void *)cd->named_groups); - cd->named_groups = newspace; - cd->named_group_list_size = newsize; - } - - cd->named_groups[cd->names_found].name = name; - cd->named_groups[cd->names_found].length = namelen; - cd->named_groups[cd->names_found].number = number; - cd->names_found++; - } - } - - ptr++; /* Move past > or ' in both passes. */ - goto NUMBERED_GROUP; - - - /* ------------------------------------------------------------ */ - case CHAR_AMPERSAND: /* Perl recursion/subroutine syntax */ - terminator = CHAR_RIGHT_PARENTHESIS; - is_recurse = TRUE; - /* Fall through */ - - /* We come here from the Python syntax above that handles both - references (?P=name) and recursion (?P>name), as well as falling - through from the Perl recursion syntax (?&name). We also come here from - the Perl \k or \k'name' back reference syntax and the \k{name} - .NET syntax, and the Oniguruma \g<...> and \g'...' subroutine syntax. */ - - NAMED_REF_OR_RECURSE: - name = ++ptr; - if (IS_DIGIT(*ptr)) - { - *errorcodeptr = ERR84; /* Group name must start with non-digit */ - goto FAILED; - } - while (MAX_255(*ptr) && (cd->ctypes[*ptr] & ctype_word) != 0) ptr++; - namelen = (int)(ptr - name); - - /* In the pre-compile phase, do a syntax check. We used to just set - a dummy reference number, because it was not used in the first pass. - However, with the change of recursive back references to be atomic, - we have to look for the number so that this state can be identified, as - otherwise the incorrect length is computed. If it's not a backwards - reference, the dummy number will do. */ - - if (lengthptr != NULL) - { - named_group *ng; - - if (namelen == 0) - { - *errorcodeptr = ERR62; - goto FAILED; - } - if (*ptr != (pcre_uchar)terminator) - { - *errorcodeptr = ERR42; - goto FAILED; - } - if (namelen > MAX_NAME_SIZE) - { - *errorcodeptr = ERR48; - goto FAILED; - } - - /* The name table does not exist in the first pass; instead we must - scan the list of names encountered so far in order to get the - number. If the name is not found, set the value to 0 for a forward - reference. */ - - ng = cd->named_groups; - for (i = 0; i < cd->names_found; i++, ng++) - { - if (namelen == ng->length && - STRNCMP_UC_UC(name, ng->name, namelen) == 0) - break; - } - recno = (i < cd->names_found)? ng->number : 0; - - /* Count named back references. */ - - if (!is_recurse) cd->namedrefcount++; - - /* If duplicate names are permitted, we have to allow for a named - reference to a duplicated name (this cannot be determined until the - second pass). This needs an extra 16-bit data item. */ - - if ((options & PCRE_DUPNAMES) != 0) *lengthptr += IMM2_SIZE; - } - - /* In the real compile, search the name table. We check the name - first, and then check that we have reached the end of the name in the - table. That way, if the name is longer than any in the table, the - comparison will fail without reading beyond the table entry. */ - - else - { - slot = cd->name_table; - for (i = 0; i < cd->names_found; i++) - { - if (STRNCMP_UC_UC(name, slot+IMM2_SIZE, namelen) == 0 && - slot[IMM2_SIZE+namelen] == 0) - break; - slot += cd->name_entry_size; - } - - if (i < cd->names_found) - { - recno = GET2(slot, 0); - } - else - { - *errorcodeptr = ERR15; - goto FAILED; - } - } - - /* In both phases, for recursions, we can now go to the code than - handles numerical recursion. */ - - if (is_recurse) goto HANDLE_RECURSION; - - /* In the second pass we must see if the name is duplicated. If so, we - generate a different opcode. */ - - if (lengthptr == NULL && cd->dupnames) - { - int count = 1; - unsigned int index = i; - pcre_uchar *cslot = slot + cd->name_entry_size; - - for (i++; i < cd->names_found; i++) - { - if (STRCMP_UC_UC(slot + IMM2_SIZE, cslot + IMM2_SIZE) != 0) break; - - - count++; - cslot += cd->name_entry_size; - } - - if (count > 1) - { - if (firstcharflags == REQ_UNSET) firstcharflags = REQ_NONE; - previous = code; - *code++ = ((options & PCRE_CASELESS) != 0)? OP_DNREFI : OP_DNREF; - PUT2INC(code, 0, index); - PUT2INC(code, 0, count); - - /* Process each potentially referenced group. */ - - for (; slot < cslot; slot += cd->name_entry_size) - { - open_capitem *oc; - recno = GET2(slot, 0); - cd->backref_map |= (recno < 32)? (1 << recno) : 1; - if (recno > cd->top_backref) cd->top_backref = recno; - - /* Check to see if this back reference is recursive, that it, it - is inside the group that it references. A flag is set so that the - group can be made atomic. */ - - for (oc = cd->open_caps; oc != NULL; oc = oc->next) - { - if (oc->number == recno) - { - oc->flag = TRUE; - break; - } - } - } - - continue; /* End of back ref handling */ - } - } - - /* First pass, or a non-duplicated name. */ - - goto HANDLE_REFERENCE; - - - /* ------------------------------------------------------------ */ - case CHAR_R: /* Recursion */ - ptr++; /* Same as (?0) */ - /* Fall through */ - - - /* ------------------------------------------------------------ */ - case CHAR_MINUS: case CHAR_PLUS: /* Recursion or subroutine */ - case CHAR_0: case CHAR_1: case CHAR_2: case CHAR_3: case CHAR_4: - case CHAR_5: case CHAR_6: case CHAR_7: case CHAR_8: case CHAR_9: - { - const pcre_uchar *called; - terminator = CHAR_RIGHT_PARENTHESIS; - - /* Come here from the \g<...> and \g'...' code (Oniguruma - compatibility). However, the syntax has been checked to ensure that - the ... are a (signed) number, so that neither ERR63 nor ERR29 will - be called on this path, nor with the jump to OTHER_CHAR_AFTER_QUERY - ever be taken. */ - - HANDLE_NUMERICAL_RECURSION: - - if ((refsign = *ptr) == CHAR_PLUS) - { - ptr++; - if (!IS_DIGIT(*ptr)) - { - *errorcodeptr = ERR63; - goto FAILED; - } - } - else if (refsign == CHAR_MINUS) - { - if (!IS_DIGIT(ptr[1])) - goto OTHER_CHAR_AFTER_QUERY; - ptr++; - } - - recno = 0; - while(IS_DIGIT(*ptr)) - recno = recno * 10 + *ptr++ - CHAR_0; - - if (*ptr != (pcre_uchar)terminator) - { - *errorcodeptr = ERR29; - goto FAILED; - } - - if (refsign == CHAR_MINUS) - { - if (recno == 0) - { - *errorcodeptr = ERR58; - goto FAILED; - } - recno = cd->bracount - recno + 1; - if (recno <= 0) - { - *errorcodeptr = ERR15; - goto FAILED; - } - } - else if (refsign == CHAR_PLUS) - { - if (recno == 0) - { - *errorcodeptr = ERR58; - goto FAILED; - } - recno += cd->bracount; - } - - /* Come here from code above that handles a named recursion */ - - HANDLE_RECURSION: - - previous = code; - called = cd->start_code; - - /* When we are actually compiling, find the bracket that is being - referenced. Temporarily end the regex in case it doesn't exist before - this point. If we end up with a forward reference, first check that - the bracket does occur later so we can give the error (and position) - now. Then remember this forward reference in the workspace so it can - be filled in at the end. */ - - if (lengthptr == NULL) - { - *code = OP_END; - if (recno != 0) - called = PRIV(find_bracket)(cd->start_code, utf, recno); - - /* Forward reference */ - - if (called == NULL) - { - if (recno > cd->final_bracount) - { - *errorcodeptr = ERR15; - goto FAILED; - } - - /* Fudge the value of "called" so that when it is inserted as an - offset below, what it actually inserted is the reference number - of the group. Then remember the forward reference. */ - - called = cd->start_code + recno; - if (cd->hwm >= cd->start_workspace + cd->workspace_size - - WORK_SIZE_SAFETY_MARGIN) - { - *errorcodeptr = expand_workspace(cd); - if (*errorcodeptr != 0) goto FAILED; - } - PUTINC(cd->hwm, 0, (int)(code + 1 - cd->start_code)); - } - - /* If not a forward reference, and the subpattern is still open, - this is a recursive call. We check to see if this is a left - recursion that could loop for ever, and diagnose that case. We - must not, however, do this check if we are in a conditional - subpattern because the condition might be testing for recursion in - a pattern such as /(?(R)a+|(?R)b)/, which is perfectly valid. - Forever loops are also detected at runtime, so those that occur in - conditional subpatterns will be picked up then. */ - - else if (GET(called, 1) == 0 && cond_depth <= 0 && - could_be_empty(called, code, bcptr, utf, cd)) - { - *errorcodeptr = ERR40; - goto FAILED; - } - } - - /* Insert the recursion/subroutine item. It does not have a set first - character (relevant if it is repeated, because it will then be - wrapped with ONCE brackets). */ - - *code = OP_RECURSE; - PUT(code, 1, (int)(called - cd->start_code)); - code += 1 + LINK_SIZE; - groupsetfirstchar = FALSE; - } - - /* Can't determine a first byte now */ - - if (firstcharflags == REQ_UNSET) firstcharflags = REQ_NONE; - continue; - - - /* ------------------------------------------------------------ */ - default: /* Other characters: check option setting */ - OTHER_CHAR_AFTER_QUERY: - set = unset = 0; - optset = &set; - - while (*ptr != CHAR_RIGHT_PARENTHESIS && *ptr != CHAR_COLON) - { - switch (*ptr++) - { - case CHAR_MINUS: optset = &unset; break; - - case CHAR_J: /* Record that it changed in the external options */ - *optset |= PCRE_DUPNAMES; - cd->external_flags |= PCRE_JCHANGED; - break; - - case CHAR_i: *optset |= PCRE_CASELESS; break; - case CHAR_m: *optset |= PCRE_MULTILINE; break; - case CHAR_s: *optset |= PCRE_DOTALL; break; - case CHAR_x: *optset |= PCRE_EXTENDED; break; - case CHAR_U: *optset |= PCRE_UNGREEDY; break; - case CHAR_X: *optset |= PCRE_EXTRA; break; - - default: *errorcodeptr = ERR12; - ptr--; /* Correct the offset */ - goto FAILED; - } - } - - /* Set up the changed option bits, but don't change anything yet. */ - - newoptions = (options | set) & (~unset); - - /* If the options ended with ')' this is not the start of a nested - group with option changes, so the options change at this level. If this - item is right at the start of the pattern, the options can be - abstracted and made external in the pre-compile phase, and ignored in - the compile phase. This can be helpful when matching -- for instance in - caseless checking of required bytes. - - If the code pointer is not (cd->start_code + 1 + LINK_SIZE), we are - definitely *not* at the start of the pattern because something has been - compiled. In the pre-compile phase, however, the code pointer can have - that value after the start, because it gets reset as code is discarded - during the pre-compile. However, this can happen only at top level - if - we are within parentheses, the starting BRA will still be present. At - any parenthesis level, the length value can be used to test if anything - has been compiled at that level. Thus, a test for both these conditions - is necessary to ensure we correctly detect the start of the pattern in - both phases. - - If we are not at the pattern start, reset the greedy defaults and the - case value for firstchar and reqchar. */ - - if (*ptr == CHAR_RIGHT_PARENTHESIS) - { - if (code == cd->start_code + 1 + LINK_SIZE && - (lengthptr == NULL || *lengthptr == 2 + 2*LINK_SIZE)) - { - cd->external_options = newoptions; - } - else - { - greedy_default = ((newoptions & PCRE_UNGREEDY) != 0); - greedy_non_default = greedy_default ^ 1; - req_caseopt = ((newoptions & PCRE_CASELESS) != 0)? REQ_CASELESS:0; - } - - /* Change options at this level, and pass them back for use - in subsequent branches. */ - - *optionsptr = options = newoptions; - previous = NULL; /* This item can't be repeated */ - continue; /* It is complete */ - } - - /* If the options ended with ':' we are heading into a nested group - with possible change of options. Such groups are non-capturing and are - not assertions of any kind. All we need to do is skip over the ':'; - the newoptions value is handled below. */ - - bravalue = OP_BRA; - ptr++; - } /* End of switch for character following (? */ - } /* End of (? handling */ - - /* Opening parenthesis not followed by '*' or '?'. If PCRE_NO_AUTO_CAPTURE - is set, all unadorned brackets become non-capturing and behave like (?:...) - brackets. */ - - else if ((options & PCRE_NO_AUTO_CAPTURE) != 0) - { - bravalue = OP_BRA; - } - - /* Else we have a capturing group. */ - - else - { - NUMBERED_GROUP: - cd->bracount += 1; - PUT2(code, 1+LINK_SIZE, cd->bracount); - skipbytes = IMM2_SIZE; - } - - /* Process nested bracketed regex. First check for parentheses nested too - deeply. */ - - if ((cd->parens_depth += 1) > PARENS_NEST_LIMIT) - { - *errorcodeptr = ERR82; - goto FAILED; - } - - /* Assertions used not to be repeatable, but this was changed for Perl - compatibility, so all kinds can now be repeated. We copy code into a - non-register variable (tempcode) in order to be able to pass its address - because some compilers complain otherwise. */ - - previous = code; /* For handling repetition */ - *code = bravalue; - tempcode = code; - tempreqvary = cd->req_varyopt; /* Save value before bracket */ - tempbracount = cd->bracount; /* Save value before bracket */ - length_prevgroup = 0; /* Initialize for pre-compile phase */ - - if (!compile_regex( - newoptions, /* The complete new option state */ - &tempcode, /* Where to put code (updated) */ - &ptr, /* Input pointer (updated) */ - errorcodeptr, /* Where to put an error message */ - (bravalue == OP_ASSERTBACK || - bravalue == OP_ASSERTBACK_NOT), /* TRUE if back assert */ - reset_bracount, /* True if (?| group */ - skipbytes, /* Skip over bracket number */ - cond_depth + - ((bravalue == OP_COND)?1:0), /* Depth of condition subpatterns */ - &subfirstchar, /* For possible first char */ - &subfirstcharflags, - &subreqchar, /* For possible last char */ - &subreqcharflags, - bcptr, /* Current branch chain */ - cd, /* Tables block */ - (lengthptr == NULL)? NULL : /* Actual compile phase */ - &length_prevgroup /* Pre-compile phase */ - )) - goto FAILED; - - cd->parens_depth -= 1; - - /* If this was an atomic group and there are no capturing groups within it, - generate OP_ONCE_NC instead of OP_ONCE. */ - - if (bravalue == OP_ONCE && cd->bracount <= tempbracount) - *code = OP_ONCE_NC; - - if (bravalue >= OP_ASSERT && bravalue <= OP_ASSERTBACK_NOT) - cd->assert_depth -= 1; - - /* At the end of compiling, code is still pointing to the start of the - group, while tempcode has been updated to point past the end of the group. - The pattern pointer (ptr) is on the bracket. - - If this is a conditional bracket, check that there are no more than - two branches in the group, or just one if it's a DEFINE group. We do this - in the real compile phase, not in the pre-pass, where the whole group may - not be available. */ - - if (bravalue == OP_COND && lengthptr == NULL) - { - pcre_uchar *tc = code; - int condcount = 0; - - do { - condcount++; - tc += GET(tc,1); - } - while (*tc != OP_KET); - - /* A DEFINE group is never obeyed inline (the "condition" is always - false). It must have only one branch. */ - - if (code[LINK_SIZE+1] == OP_DEF) - { - if (condcount > 1) - { - *errorcodeptr = ERR54; - goto FAILED; - } - bravalue = OP_DEF; /* Just a flag to suppress char handling below */ - } - - /* A "normal" conditional group. If there is just one branch, we must not - make use of its firstchar or reqchar, because this is equivalent to an - empty second branch. */ - - else - { - if (condcount > 2) - { - *errorcodeptr = ERR27; - goto FAILED; - } - if (condcount == 1) subfirstcharflags = subreqcharflags = REQ_NONE; - } - } - - /* Error if hit end of pattern */ - - if (*ptr != CHAR_RIGHT_PARENTHESIS) - { - *errorcodeptr = ERR14; - goto FAILED; - } - - /* In the pre-compile phase, update the length by the length of the group, - less the brackets at either end. Then reduce the compiled code to just a - set of non-capturing brackets so that it doesn't use much memory if it is - duplicated by a quantifier.*/ - - if (lengthptr != NULL) - { - if (OFLOW_MAX - *lengthptr < length_prevgroup - 2 - 2*LINK_SIZE) - { - *errorcodeptr = ERR20; - goto FAILED; - } - *lengthptr += length_prevgroup - 2 - 2*LINK_SIZE; - code++; /* This already contains bravalue */ - PUTINC(code, 0, 1 + LINK_SIZE); - *code++ = OP_KET; - PUTINC(code, 0, 1 + LINK_SIZE); - break; /* No need to waste time with special character handling */ - } - - /* Otherwise update the main code pointer to the end of the group. */ - - code = tempcode; - - /* For a DEFINE group, required and first character settings are not - relevant. */ - - if (bravalue == OP_DEF) break; - - /* Handle updating of the required and first characters for other types of - group. Update for normal brackets of all kinds, and conditions with two - branches (see code above). If the bracket is followed by a quantifier with - zero repeat, we have to back off. Hence the definition of zeroreqchar and - zerofirstchar outside the main loop so that they can be accessed for the - back off. */ - - zeroreqchar = reqchar; - zeroreqcharflags = reqcharflags; - zerofirstchar = firstchar; - zerofirstcharflags = firstcharflags; - groupsetfirstchar = FALSE; - - if (bravalue >= OP_ONCE) - { - /* If we have not yet set a firstchar in this branch, take it from the - subpattern, remembering that it was set here so that a repeat of more - than one can replicate it as reqchar if necessary. If the subpattern has - no firstchar, set "none" for the whole branch. In both cases, a zero - repeat forces firstchar to "none". */ - - if (firstcharflags == REQ_UNSET) - { - if (subfirstcharflags >= 0) - { - firstchar = subfirstchar; - firstcharflags = subfirstcharflags; - groupsetfirstchar = TRUE; - } - else firstcharflags = REQ_NONE; - zerofirstcharflags = REQ_NONE; - } - - /* If firstchar was previously set, convert the subpattern's firstchar - into reqchar if there wasn't one, using the vary flag that was in - existence beforehand. */ - - else if (subfirstcharflags >= 0 && subreqcharflags < 0) - { - subreqchar = subfirstchar; - subreqcharflags = subfirstcharflags | tempreqvary; - } - - /* If the subpattern set a required byte (or set a first byte that isn't - really the first byte - see above), set it. */ - - if (subreqcharflags >= 0) - { - reqchar = subreqchar; - reqcharflags = subreqcharflags; - } - } - - /* For a forward assertion, we take the reqchar, if set. This can be - helpful if the pattern that follows the assertion doesn't set a different - char. For example, it's useful for /(?=abcde).+/. We can't set firstchar - for an assertion, however because it leads to incorrect effect for patterns - such as /(?=a)a.+/ when the "real" "a" would then become a reqchar instead - of a firstchar. This is overcome by a scan at the end if there's no - firstchar, looking for an asserted first char. */ - - else if (bravalue == OP_ASSERT && subreqcharflags >= 0) - { - reqchar = subreqchar; - reqcharflags = subreqcharflags; - } - break; /* End of processing '(' */ - - - /* ===================================================================*/ - /* Handle metasequences introduced by \. For ones like \d, the ESC_ values - are arranged to be the negation of the corresponding OP_values in the - default case when PCRE_UCP is not set. For the back references, the values - are negative the reference number. Only back references and those types - that consume a character may be repeated. We can test for values between - ESC_b and ESC_Z for the latter; this may have to change if any new ones are - ever created. */ - - case CHAR_BACKSLASH: - tempptr = ptr; - escape = check_escape(&ptr, &ec, errorcodeptr, cd->bracount, options, FALSE); - if (*errorcodeptr != 0) goto FAILED; - - if (escape == 0) /* The escape coded a single character */ - c = ec; - else - { - if (escape == ESC_Q) /* Handle start of quoted string */ - { - if (ptr[1] == CHAR_BACKSLASH && ptr[2] == CHAR_E) - ptr += 2; /* avoid empty string */ - else inescq = TRUE; - continue; - } - - if (escape == ESC_E) continue; /* Perl ignores an orphan \E */ - - /* For metasequences that actually match a character, we disable the - setting of a first character if it hasn't already been set. */ - - if (firstcharflags == REQ_UNSET && escape > ESC_b && escape < ESC_Z) - firstcharflags = REQ_NONE; - - /* Set values to reset to if this is followed by a zero repeat. */ - - zerofirstchar = firstchar; - zerofirstcharflags = firstcharflags; - zeroreqchar = reqchar; - zeroreqcharflags = reqcharflags; - - /* \g or \g'name' is a subroutine call by name and \g or \g'n' - is a subroutine call by number (Oniguruma syntax). In fact, the value - ESC_g is returned only for these cases. So we don't need to check for < - or ' if the value is ESC_g. For the Perl syntax \g{n} the value is - -n, and for the Perl syntax \g{name} the result is ESC_k (as - that is a synonym for a named back reference). */ - - if (escape == ESC_g) - { - const pcre_uchar *p; - pcre_uint32 cf; - - save_hwm = cd->hwm; /* Normally this is set when '(' is read */ - terminator = (*(++ptr) == CHAR_LESS_THAN_SIGN)? - CHAR_GREATER_THAN_SIGN : CHAR_APOSTROPHE; - - /* These two statements stop the compiler for warning about possibly - unset variables caused by the jump to HANDLE_NUMERICAL_RECURSION. In - fact, because we do the check for a number below, the paths that - would actually be in error are never taken. */ - - skipbytes = 0; - reset_bracount = FALSE; - - /* If it's not a signed or unsigned number, treat it as a name. */ - - cf = ptr[1]; - if (cf != CHAR_PLUS && cf != CHAR_MINUS && !IS_DIGIT(cf)) - { - is_recurse = TRUE; - goto NAMED_REF_OR_RECURSE; - } - - /* Signed or unsigned number (cf = ptr[1]) is known to be plus or minus - or a digit. */ - - p = ptr + 2; - while (IS_DIGIT(*p)) p++; - if (*p != (pcre_uchar)terminator) - { - *errorcodeptr = ERR57; - break; - } - ptr++; - goto HANDLE_NUMERICAL_RECURSION; - } - - /* \k or \k'name' is a back reference by name (Perl syntax). - We also support \k{name} (.NET syntax). */ - - if (escape == ESC_k) - { - if ((ptr[1] != CHAR_LESS_THAN_SIGN && - ptr[1] != CHAR_APOSTROPHE && ptr[1] != CHAR_LEFT_CURLY_BRACKET)) - { - *errorcodeptr = ERR69; - break; - } - is_recurse = FALSE; - terminator = (*(++ptr) == CHAR_LESS_THAN_SIGN)? - CHAR_GREATER_THAN_SIGN : (*ptr == CHAR_APOSTROPHE)? - CHAR_APOSTROPHE : CHAR_RIGHT_CURLY_BRACKET; - goto NAMED_REF_OR_RECURSE; - } - - /* Back references are handled specially; must disable firstchar if - not set to cope with cases like (?=(\w+))\1: which would otherwise set - ':' later. */ - - if (escape < 0) - { - open_capitem *oc; - recno = -escape; - - /* Come here from named backref handling when the reference is to a - single group (i.e. not to a duplicated name. */ - - HANDLE_REFERENCE: - if (firstcharflags == REQ_UNSET) firstcharflags = REQ_NONE; - previous = code; - *code++ = ((options & PCRE_CASELESS) != 0)? OP_REFI : OP_REF; - PUT2INC(code, 0, recno); - cd->backref_map |= (recno < 32)? (1 << recno) : 1; - if (recno > cd->top_backref) cd->top_backref = recno; - - /* Check to see if this back reference is recursive, that it, it - is inside the group that it references. A flag is set so that the - group can be made atomic. */ - - for (oc = cd->open_caps; oc != NULL; oc = oc->next) - { - if (oc->number == recno) - { - oc->flag = TRUE; - break; - } - } - } - - /* So are Unicode property matches, if supported. */ - -#ifdef SUPPORT_UCP - else if (escape == ESC_P || escape == ESC_p) - { - BOOL negated; - unsigned int ptype = 0, pdata = 0; - if (!get_ucp(&ptr, &negated, &ptype, &pdata, errorcodeptr)) - goto FAILED; - previous = code; - *code++ = ((escape == ESC_p) != negated)? OP_PROP : OP_NOTPROP; - *code++ = ptype; - *code++ = pdata; - } -#else - - /* If Unicode properties are not supported, \X, \P, and \p are not - allowed. */ - - else if (escape == ESC_X || escape == ESC_P || escape == ESC_p) - { - *errorcodeptr = ERR45; - goto FAILED; - } -#endif - - /* For the rest (including \X when Unicode properties are supported), we - can obtain the OP value by negating the escape value in the default - situation when PCRE_UCP is not set. When it *is* set, we substitute - Unicode property tests. Note that \b and \B do a one-character - lookbehind, and \A also behaves as if it does. */ - - else - { - if ((escape == ESC_b || escape == ESC_B || escape == ESC_A) && - cd->max_lookbehind == 0) - cd->max_lookbehind = 1; -#ifdef SUPPORT_UCP - if (escape >= ESC_DU && escape <= ESC_wu) - { - nestptr = ptr + 1; /* Where to resume */ - ptr = substitutes[escape - ESC_DU] - 1; /* Just before substitute */ - } - else -#endif - /* In non-UTF-8 mode, we turn \C into OP_ALLANY instead of OP_ANYBYTE - so that it works in DFA mode and in lookbehinds. */ - - { - previous = (escape > ESC_b && escape < ESC_Z)? code : NULL; - *code++ = (!utf && escape == ESC_C)? OP_ALLANY : escape; - } - } - continue; - } - - /* We have a data character whose value is in c. In UTF-8 mode it may have - a value > 127. We set its representation in the length/buffer, and then - handle it as a data character. */ - -#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 - if (utf && c > MAX_VALUE_FOR_SINGLE_CHAR) - mclength = PRIV(ord2utf)(c, mcbuffer); - else -#endif - - { - mcbuffer[0] = c; - mclength = 1; - } - goto ONE_CHAR; - - - /* ===================================================================*/ - /* Handle a literal character. It is guaranteed not to be whitespace or # - when the extended flag is set. If we are in a UTF mode, it may be a - multi-unit literal character. */ - - default: - NORMAL_CHAR: - mclength = 1; - mcbuffer[0] = c; - -#ifdef SUPPORT_UTF - if (utf && HAS_EXTRALEN(c)) - ACROSSCHAR(TRUE, ptr[1], mcbuffer[mclength++] = *(++ptr)); -#endif - - /* At this point we have the character's bytes in mcbuffer, and the length - in mclength. When not in UTF-8 mode, the length is always 1. */ - - ONE_CHAR: - previous = code; - - /* For caseless UTF-8 mode when UCP support is available, check whether - this character has more than one other case. If so, generate a special - OP_PROP item instead of OP_CHARI. */ - -#ifdef SUPPORT_UCP - if (utf && (options & PCRE_CASELESS) != 0) - { - GETCHAR(c, mcbuffer); - if ((c = UCD_CASESET(c)) != 0) - { - *code++ = OP_PROP; - *code++ = PT_CLIST; - *code++ = c; - if (firstcharflags == REQ_UNSET) - firstcharflags = zerofirstcharflags = REQ_NONE; - break; - } - } -#endif - - /* Caseful matches, or not one of the multicase characters. */ - - *code++ = ((options & PCRE_CASELESS) != 0)? OP_CHARI : OP_CHAR; - for (c = 0; c < mclength; c++) *code++ = mcbuffer[c]; - - /* Remember if \r or \n were seen */ - - if (mcbuffer[0] == CHAR_CR || mcbuffer[0] == CHAR_NL) - cd->external_flags |= PCRE_HASCRORLF; - - /* Set the first and required bytes appropriately. If no previous first - byte, set it from this character, but revert to none on a zero repeat. - Otherwise, leave the firstchar value alone, and don't change it on a zero - repeat. */ - - if (firstcharflags == REQ_UNSET) - { - zerofirstcharflags = REQ_NONE; - zeroreqchar = reqchar; - zeroreqcharflags = reqcharflags; - - /* If the character is more than one byte long, we can set firstchar - only if it is not to be matched caselessly. */ - - if (mclength == 1 || req_caseopt == 0) - { - firstchar = mcbuffer[0] | req_caseopt; - firstchar = mcbuffer[0]; - firstcharflags = req_caseopt; - - if (mclength != 1) - { - reqchar = code[-1]; - reqcharflags = cd->req_varyopt; - } - } - else firstcharflags = reqcharflags = REQ_NONE; - } - - /* firstchar was previously set; we can set reqchar only if the length is - 1 or the matching is caseful. */ - - else - { - zerofirstchar = firstchar; - zerofirstcharflags = firstcharflags; - zeroreqchar = reqchar; - zeroreqcharflags = reqcharflags; - if (mclength == 1 || req_caseopt == 0) - { - reqchar = code[-1]; - reqcharflags = req_caseopt | cd->req_varyopt; - } - } - - break; /* End of literal character handling */ - } - } /* end of big loop */ - - -/* Control never reaches here by falling through, only by a goto for all the -error states. Pass back the position in the pattern so that it can be displayed -to the user for diagnosing the error. */ - -FAILED: -*ptrptr = ptr; -return FALSE; -} - - - -/************************************************* -* Compile sequence of alternatives * -*************************************************/ - -/* On entry, ptr is pointing past the bracket character, but on return it -points to the closing bracket, or vertical bar, or end of string. The code -variable is pointing at the byte into which the BRA operator has been stored. -This function is used during the pre-compile phase when we are trying to find -out the amount of memory needed, as well as during the real compile phase. The -value of lengthptr distinguishes the two phases. - -Arguments: - options option bits, including any changes for this subpattern - codeptr -> the address of the current code pointer - ptrptr -> the address of the current pattern pointer - errorcodeptr -> pointer to error code variable - lookbehind TRUE if this is a lookbehind assertion - reset_bracount TRUE to reset the count for each branch - skipbytes skip this many bytes at start (for brackets and OP_COND) - cond_depth depth of nesting for conditional subpatterns - firstcharptr place to put the first required character - firstcharflagsptr place to put the first character flags, or a negative number - reqcharptr place to put the last required character - reqcharflagsptr place to put the last required character flags, or a negative number - bcptr pointer to the chain of currently open branches - cd points to the data block with tables pointers etc. - lengthptr NULL during the real compile phase - points to length accumulator during pre-compile phase - -Returns: TRUE on success -*/ - -static BOOL -compile_regex(int options, pcre_uchar **codeptr, const pcre_uchar **ptrptr, - int *errorcodeptr, BOOL lookbehind, BOOL reset_bracount, int skipbytes, - int cond_depth, - pcre_uint32 *firstcharptr, pcre_int32 *firstcharflagsptr, - pcre_uint32 *reqcharptr, pcre_int32 *reqcharflagsptr, - branch_chain *bcptr, compile_data *cd, int *lengthptr) -{ -const pcre_uchar *ptr = *ptrptr; -pcre_uchar *code = *codeptr; -pcre_uchar *last_branch = code; -pcre_uchar *start_bracket = code; -pcre_uchar *reverse_count = NULL; -open_capitem capitem; -int capnumber = 0; -pcre_uint32 firstchar, reqchar; -pcre_int32 firstcharflags, reqcharflags; -pcre_uint32 branchfirstchar, branchreqchar; -pcre_int32 branchfirstcharflags, branchreqcharflags; -int length; -unsigned int orig_bracount; -unsigned int max_bracount; -branch_chain bc; - -/* If set, call the external function that checks for stack availability. */ - -if (PUBL(stack_guard) != NULL && PUBL(stack_guard)()) - { - *errorcodeptr= ERR85; - return FALSE; - } - -/* Miscellaneous initialization */ - -bc.outer = bcptr; -bc.current_branch = code; - -firstchar = reqchar = 0; -firstcharflags = reqcharflags = REQ_UNSET; - -/* Accumulate the length for use in the pre-compile phase. Start with the -length of the BRA and KET and any extra bytes that are required at the -beginning. We accumulate in a local variable to save frequent testing of -lenthptr for NULL. We cannot do this by looking at the value of code at the -start and end of each alternative, because compiled items are discarded during -the pre-compile phase so that the work space is not exceeded. */ - -length = 2 + 2*LINK_SIZE + skipbytes; - -/* WARNING: If the above line is changed for any reason, you must also change -the code that abstracts option settings at the start of the pattern and makes -them global. It tests the value of length for (2 + 2*LINK_SIZE) in the -pre-compile phase to find out whether anything has yet been compiled or not. */ - -/* If this is a capturing subpattern, add to the chain of open capturing items -so that we can detect them if (*ACCEPT) is encountered. This is also used to -detect groups that contain recursive back references to themselves. Note that -only OP_CBRA need be tested here; changing this opcode to one of its variants, -e.g. OP_SCBRAPOS, happens later, after the group has been compiled. */ - -if (*code == OP_CBRA) - { - capnumber = GET2(code, 1 + LINK_SIZE); - capitem.number = capnumber; - capitem.next = cd->open_caps; - capitem.flag = FALSE; - cd->open_caps = &capitem; - } - -/* Offset is set zero to mark that this bracket is still open */ - -PUT(code, 1, 0); -code += 1 + LINK_SIZE + skipbytes; - -/* Loop for each alternative branch */ - -orig_bracount = max_bracount = cd->bracount; -for (;;) - { - /* For a (?| group, reset the capturing bracket count so that each branch - uses the same numbers. */ - - if (reset_bracount) cd->bracount = orig_bracount; - - /* Set up dummy OP_REVERSE if lookbehind assertion */ - - if (lookbehind) - { - *code++ = OP_REVERSE; - reverse_count = code; - PUTINC(code, 0, 0); - length += 1 + LINK_SIZE; - } - - /* Now compile the branch; in the pre-compile phase its length gets added - into the length. */ - - if (!compile_branch(&options, &code, &ptr, errorcodeptr, &branchfirstchar, - &branchfirstcharflags, &branchreqchar, &branchreqcharflags, &bc, - cond_depth, cd, (lengthptr == NULL)? NULL : &length)) - { - *ptrptr = ptr; - return FALSE; - } - - /* Keep the highest bracket count in case (?| was used and some branch - has fewer than the rest. */ - - if (cd->bracount > max_bracount) max_bracount = cd->bracount; - - /* In the real compile phase, there is some post-processing to be done. */ - - if (lengthptr == NULL) - { - /* If this is the first branch, the firstchar and reqchar values for the - branch become the values for the regex. */ - - if (*last_branch != OP_ALT) - { - firstchar = branchfirstchar; - firstcharflags = branchfirstcharflags; - reqchar = branchreqchar; - reqcharflags = branchreqcharflags; - } - - /* If this is not the first branch, the first char and reqchar have to - match the values from all the previous branches, except that if the - previous value for reqchar didn't have REQ_VARY set, it can still match, - and we set REQ_VARY for the regex. */ - - else - { - /* If we previously had a firstchar, but it doesn't match the new branch, - we have to abandon the firstchar for the regex, but if there was - previously no reqchar, it takes on the value of the old firstchar. */ - - if (firstcharflags >= 0 && - (firstcharflags != branchfirstcharflags || firstchar != branchfirstchar)) - { - if (reqcharflags < 0) - { - reqchar = firstchar; - reqcharflags = firstcharflags; - } - firstcharflags = REQ_NONE; - } - - /* If we (now or from before) have no firstchar, a firstchar from the - branch becomes a reqchar if there isn't a branch reqchar. */ - - if (firstcharflags < 0 && branchfirstcharflags >= 0 && branchreqcharflags < 0) - { - branchreqchar = branchfirstchar; - branchreqcharflags = branchfirstcharflags; - } - - /* Now ensure that the reqchars match */ - - if (((reqcharflags & ~REQ_VARY) != (branchreqcharflags & ~REQ_VARY)) || - reqchar != branchreqchar) - reqcharflags = REQ_NONE; - else - { - reqchar = branchreqchar; - reqcharflags |= branchreqcharflags; /* To "or" REQ_VARY */ - } - } - - /* If lookbehind, check that this branch matches a fixed-length string, and - put the length into the OP_REVERSE item. Temporarily mark the end of the - branch with OP_END. If the branch contains OP_RECURSE, the result is -3 - because there may be forward references that we can't check here. Set a - flag to cause another lookbehind check at the end. Why not do it all at the - end? Because common, erroneous checks are picked up here and the offset of - the problem can be shown. */ - - if (lookbehind) - { - int fixed_length; - *code = OP_END; - fixed_length = find_fixedlength(last_branch, (options & PCRE_UTF8) != 0, - FALSE, cd); - DPRINTF(("fixed length = %d\n", fixed_length)); - if (fixed_length == -3) - { - cd->check_lookbehind = TRUE; - } - else if (fixed_length < 0) - { - *errorcodeptr = (fixed_length == -2)? ERR36 : - (fixed_length == -4)? ERR70: ERR25; - *ptrptr = ptr; - return FALSE; - } - else - { - if (fixed_length > cd->max_lookbehind) - cd->max_lookbehind = fixed_length; - PUT(reverse_count, 0, fixed_length); - } - } - } - - /* Reached end of expression, either ')' or end of pattern. In the real - compile phase, go back through the alternative branches and reverse the chain - of offsets, with the field in the BRA item now becoming an offset to the - first alternative. If there are no alternatives, it points to the end of the - group. The length in the terminating ket is always the length of the whole - bracketed item. Return leaving the pointer at the terminating char. */ - - if (*ptr != CHAR_VERTICAL_LINE) - { - if (lengthptr == NULL) - { - int branch_length = (int)(code - last_branch); - do - { - int prev_length = GET(last_branch, 1); - PUT(last_branch, 1, branch_length); - branch_length = prev_length; - last_branch -= branch_length; - } - while (branch_length > 0); - } - - /* Fill in the ket */ - - *code = OP_KET; - PUT(code, 1, (int)(code - start_bracket)); - code += 1 + LINK_SIZE; - - /* If it was a capturing subpattern, check to see if it contained any - recursive back references. If so, we must wrap it in atomic brackets. - Because we are moving code along, we must ensure that any pending recursive - references are updated. In any event, remove the block from the chain. */ - - if (capnumber > 0) - { - if (cd->open_caps->flag) - { - *code = OP_END; - adjust_recurse(start_bracket, 1 + LINK_SIZE, - (options & PCRE_UTF8) != 0, cd, cd->hwm); - memmove(start_bracket + 1 + LINK_SIZE, start_bracket, - IN_UCHARS(code - start_bracket)); - *start_bracket = OP_ONCE; - code += 1 + LINK_SIZE; - PUT(start_bracket, 1, (int)(code - start_bracket)); - *code = OP_KET; - PUT(code, 1, (int)(code - start_bracket)); - code += 1 + LINK_SIZE; - length += 2 + 2*LINK_SIZE; - } - cd->open_caps = cd->open_caps->next; - } - - /* Retain the highest bracket number, in case resetting was used. */ - - cd->bracount = max_bracount; - - /* Set values to pass back */ - - *codeptr = code; - *ptrptr = ptr; - *firstcharptr = firstchar; - *firstcharflagsptr = firstcharflags; - *reqcharptr = reqchar; - *reqcharflagsptr = reqcharflags; - if (lengthptr != NULL) - { - if (OFLOW_MAX - *lengthptr < length) - { - *errorcodeptr = ERR20; - return FALSE; - } - *lengthptr += length; - } - return TRUE; - } - - /* Another branch follows. In the pre-compile phase, we can move the code - pointer back to where it was for the start of the first branch. (That is, - pretend that each branch is the only one.) - - In the real compile phase, insert an ALT node. Its length field points back - to the previous branch while the bracket remains open. At the end the chain - is reversed. It's done like this so that the start of the bracket has a - zero offset until it is closed, making it possible to detect recursion. */ - - if (lengthptr != NULL) - { - code = *codeptr + 1 + LINK_SIZE + skipbytes; - length += 1 + LINK_SIZE; - } - else - { - *code = OP_ALT; - PUT(code, 1, (int)(code - last_branch)); - bc.current_branch = last_branch = code; - code += 1 + LINK_SIZE; - } - - ptr++; - } -/* Control never reaches here */ -} - - - - -/************************************************* -* Check for anchored expression * -*************************************************/ - -/* Try to find out if this is an anchored regular expression. Consider each -alternative branch. If they all start with OP_SOD or OP_CIRC, or with a bracket -all of whose alternatives start with OP_SOD or OP_CIRC (recurse ad lib), then -it's anchored. However, if this is a multiline pattern, then only OP_SOD will -be found, because ^ generates OP_CIRCM in that mode. - -We can also consider a regex to be anchored if OP_SOM starts all its branches. -This is the code for \G, which means "match at start of match position, taking -into account the match offset". - -A branch is also implicitly anchored if it starts with .* and DOTALL is set, -because that will try the rest of the pattern at all possible matching points, -so there is no point trying again.... er .... - -.... except when the .* appears inside capturing parentheses, and there is a -subsequent back reference to those parentheses. We haven't enough information -to catch that case precisely. - -At first, the best we could do was to detect when .* was in capturing brackets -and the highest back reference was greater than or equal to that level. -However, by keeping a bitmap of the first 31 back references, we can catch some -of the more common cases more precisely. - -... A second exception is when the .* appears inside an atomic group, because -this prevents the number of characters it matches from being adjusted. - -Arguments: - code points to start of expression (the bracket) - bracket_map a bitmap of which brackets we are inside while testing; this - handles up to substring 31; after that we just have to take - the less precise approach - cd points to the compile data block - atomcount atomic group level - -Returns: TRUE or FALSE -*/ - -static BOOL -is_anchored(register const pcre_uchar *code, unsigned int bracket_map, - compile_data *cd, int atomcount) -{ -do { - const pcre_uchar *scode = first_significant_code( - code + PRIV(OP_lengths)[*code], FALSE); - register int op = *scode; - - /* Non-capturing brackets */ - - if (op == OP_BRA || op == OP_BRAPOS || - op == OP_SBRA || op == OP_SBRAPOS) - { - if (!is_anchored(scode, bracket_map, cd, atomcount)) return FALSE; - } - - /* Capturing brackets */ - - else if (op == OP_CBRA || op == OP_CBRAPOS || - op == OP_SCBRA || op == OP_SCBRAPOS) - { - int n = GET2(scode, 1+LINK_SIZE); - int new_map = bracket_map | ((n < 32)? (1 << n) : 1); - if (!is_anchored(scode, new_map, cd, atomcount)) return FALSE; - } - - /* Positive forward assertions and conditions */ - - else if (op == OP_ASSERT || op == OP_COND) - { - if (!is_anchored(scode, bracket_map, cd, atomcount)) return FALSE; - } - - /* Atomic groups */ - - else if (op == OP_ONCE || op == OP_ONCE_NC) - { - if (!is_anchored(scode, bracket_map, cd, atomcount + 1)) - return FALSE; - } - - /* .* is not anchored unless DOTALL is set (which generates OP_ALLANY) and - it isn't in brackets that are or may be referenced or inside an atomic - group. */ - - else if ((op == OP_TYPESTAR || op == OP_TYPEMINSTAR || - op == OP_TYPEPOSSTAR)) - { - if (scode[1] != OP_ALLANY || (bracket_map & cd->backref_map) != 0 || - atomcount > 0 || cd->had_pruneorskip) - return FALSE; - } - - /* Check for explicit anchoring */ - - else if (op != OP_SOD && op != OP_SOM && op != OP_CIRC) return FALSE; - - code += GET(code, 1); - } -while (*code == OP_ALT); /* Loop for each alternative */ -return TRUE; -} - - - -/************************************************* -* Check for starting with ^ or .* * -*************************************************/ - -/* This is called to find out if every branch starts with ^ or .* so that -"first char" processing can be done to speed things up in multiline -matching and for non-DOTALL patterns that start with .* (which must start at -the beginning or after \n). As in the case of is_anchored() (see above), we -have to take account of back references to capturing brackets that contain .* -because in that case we can't make the assumption. Also, the appearance of .* -inside atomic brackets or in a pattern that contains *PRUNE or *SKIP does not -count, because once again the assumption no longer holds. - -Arguments: - code points to start of expression (the bracket) - bracket_map a bitmap of which brackets we are inside while testing; this - handles up to substring 31; after that we just have to take - the less precise approach - cd points to the compile data - atomcount atomic group level - -Returns: TRUE or FALSE -*/ - -static BOOL -is_startline(const pcre_uchar *code, unsigned int bracket_map, - compile_data *cd, int atomcount) -{ -do { - const pcre_uchar *scode = first_significant_code( - code + PRIV(OP_lengths)[*code], FALSE); - register int op = *scode; - - /* If we are at the start of a conditional assertion group, *both* the - conditional assertion *and* what follows the condition must satisfy the test - for start of line. Other kinds of condition fail. Note that there may be an - auto-callout at the start of a condition. */ - - if (op == OP_COND) - { - scode += 1 + LINK_SIZE; - if (*scode == OP_CALLOUT) scode += PRIV(OP_lengths)[OP_CALLOUT]; - switch (*scode) - { - case OP_CREF: - case OP_DNCREF: - case OP_RREF: - case OP_DNRREF: - case OP_DEF: - return FALSE; - - default: /* Assertion */ - if (!is_startline(scode, bracket_map, cd, atomcount)) return FALSE; - do scode += GET(scode, 1); while (*scode == OP_ALT); - scode += 1 + LINK_SIZE; - break; - } - scode = first_significant_code(scode, FALSE); - op = *scode; - } - - /* Non-capturing brackets */ - - if (op == OP_BRA || op == OP_BRAPOS || - op == OP_SBRA || op == OP_SBRAPOS) - { - if (!is_startline(scode, bracket_map, cd, atomcount)) return FALSE; - } - - /* Capturing brackets */ - - else if (op == OP_CBRA || op == OP_CBRAPOS || - op == OP_SCBRA || op == OP_SCBRAPOS) - { - int n = GET2(scode, 1+LINK_SIZE); - int new_map = bracket_map | ((n < 32)? (1 << n) : 1); - if (!is_startline(scode, new_map, cd, atomcount)) return FALSE; - } - - /* Positive forward assertions */ - - else if (op == OP_ASSERT) - { - if (!is_startline(scode, bracket_map, cd, atomcount)) return FALSE; - } - - /* Atomic brackets */ - - else if (op == OP_ONCE || op == OP_ONCE_NC) - { - if (!is_startline(scode, bracket_map, cd, atomcount + 1)) return FALSE; - } - - /* .* means "start at start or after \n" if it isn't in atomic brackets or - brackets that may be referenced, as long as the pattern does not contain - *PRUNE or *SKIP, because these break the feature. Consider, for example, - /.*?a(*PRUNE)b/ with the subject "aab", which matches "ab", i.e. not at the - start of a line. */ - - else if (op == OP_TYPESTAR || op == OP_TYPEMINSTAR || op == OP_TYPEPOSSTAR) - { - if (scode[1] != OP_ANY || (bracket_map & cd->backref_map) != 0 || - atomcount > 0 || cd->had_pruneorskip) - return FALSE; - } - - /* Check for explicit circumflex; anything else gives a FALSE result. Note - in particular that this includes atomic brackets OP_ONCE and OP_ONCE_NC - because the number of characters matched by .* cannot be adjusted inside - them. */ - - else if (op != OP_CIRC && op != OP_CIRCM) return FALSE; - - /* Move on to the next alternative */ - - code += GET(code, 1); - } -while (*code == OP_ALT); /* Loop for each alternative */ -return TRUE; -} - - - -/************************************************* -* Check for asserted fixed first char * -*************************************************/ - -/* During compilation, the "first char" settings from forward assertions are -discarded, because they can cause conflicts with actual literals that follow. -However, if we end up without a first char setting for an unanchored pattern, -it is worth scanning the regex to see if there is an initial asserted first -char. If all branches start with the same asserted char, or with a -non-conditional bracket all of whose alternatives start with the same asserted -char (recurse ad lib), then we return that char, with the flags set to zero or -REQ_CASELESS; otherwise return zero with REQ_NONE in the flags. - -Arguments: - code points to start of expression (the bracket) - flags points to the first char flags, or to REQ_NONE - inassert TRUE if in an assertion - -Returns: the fixed first char, or 0 with REQ_NONE in flags -*/ - -static pcre_uint32 -find_firstassertedchar(const pcre_uchar *code, pcre_int32 *flags, - BOOL inassert) -{ -register pcre_uint32 c = 0; -int cflags = REQ_NONE; - -*flags = REQ_NONE; -do { - pcre_uint32 d; - int dflags; - int xl = (*code == OP_CBRA || *code == OP_SCBRA || - *code == OP_CBRAPOS || *code == OP_SCBRAPOS)? IMM2_SIZE:0; - const pcre_uchar *scode = first_significant_code(code + 1+LINK_SIZE + xl, - TRUE); - register pcre_uchar op = *scode; - - switch(op) - { - default: - return 0; - - case OP_BRA: - case OP_BRAPOS: - case OP_CBRA: - case OP_SCBRA: - case OP_CBRAPOS: - case OP_SCBRAPOS: - case OP_ASSERT: - case OP_ONCE: - case OP_ONCE_NC: - d = find_firstassertedchar(scode, &dflags, op == OP_ASSERT); - if (dflags < 0) - return 0; - if (cflags < 0) { c = d; cflags = dflags; } else if (c != d || cflags != dflags) return 0; - break; - - case OP_EXACT: - scode += IMM2_SIZE; - /* Fall through */ - - case OP_CHAR: - case OP_PLUS: - case OP_MINPLUS: - case OP_POSPLUS: - if (!inassert) return 0; - if (cflags < 0) { c = scode[1]; cflags = 0; } - else if (c != scode[1]) return 0; - break; - - case OP_EXACTI: - scode += IMM2_SIZE; - /* Fall through */ - - case OP_CHARI: - case OP_PLUSI: - case OP_MINPLUSI: - case OP_POSPLUSI: - if (!inassert) return 0; - if (cflags < 0) { c = scode[1]; cflags = REQ_CASELESS; } - else if (c != scode[1]) return 0; - break; - } - - code += GET(code, 1); - } -while (*code == OP_ALT); - -*flags = cflags; -return c; -} - - - -/************************************************* -* Add an entry to the name/number table * -*************************************************/ - -/* This function is called between compiling passes to add an entry to the -name/number table, maintaining alphabetical order. Checking for permitted -and forbidden duplicates has already been done. - -Arguments: - cd the compile data block - name the name to add - length the length of the name - groupno the group number - -Returns: nothing -*/ - -static void -add_name(compile_data *cd, const pcre_uchar *name, int length, - unsigned int groupno) -{ -int i; -pcre_uchar *slot = cd->name_table; - -for (i = 0; i < cd->names_found; i++) - { - int crc = memcmp(name, slot+IMM2_SIZE, IN_UCHARS(length)); - if (crc == 0 && slot[IMM2_SIZE+length] != 0) - crc = -1; /* Current name is a substring */ - - /* Make space in the table and break the loop for an earlier name. For a - duplicate or later name, carry on. We do this for duplicates so that in the - simple case (when ?(| is not used) they are in order of their numbers. In all - cases they are in the order in which they appear in the pattern. */ - - if (crc < 0) - { - memmove(slot + cd->name_entry_size, slot, - IN_UCHARS((cd->names_found - i) * cd->name_entry_size)); - break; - } - - /* Continue the loop for a later or duplicate name */ - - slot += cd->name_entry_size; - } - -PUT2(slot, 0, groupno); -memcpy(slot + IMM2_SIZE, name, IN_UCHARS(length)); -slot[IMM2_SIZE + length] = 0; -cd->names_found++; -} - - - -/************************************************* -* Compile a Regular Expression * -*************************************************/ - -/* This function takes a string and returns a pointer to a block of store -holding a compiled version of the expression. The original API for this -function had no error code return variable; it is retained for backwards -compatibility. The new function is given a new name. - -Arguments: - pattern the regular expression - options various option bits - errorcodeptr pointer to error code variable (pcre_compile2() only) - can be NULL if you don't want a code value - errorptr pointer to pointer to error text - erroroffset ptr offset in pattern where error was detected - tables pointer to character tables or NULL - -Returns: pointer to compiled data block, or NULL on error, - with errorptr and erroroffset set -*/ - -#if defined COMPILE_PCRE8 -PCRE_EXP_DEFN pcre * PCRE_CALL_CONVENTION -pcre_compile(const char *pattern, int options, const char **errorptr, - int *erroroffset, const unsigned char *tables) -#elif defined COMPILE_PCRE16 -PCRE_EXP_DEFN pcre16 * PCRE_CALL_CONVENTION -pcre16_compile(PCRE_SPTR16 pattern, int options, const char **errorptr, - int *erroroffset, const unsigned char *tables) -#elif defined COMPILE_PCRE32 -PCRE_EXP_DEFN pcre32 * PCRE_CALL_CONVENTION -pcre32_compile(PCRE_SPTR32 pattern, int options, const char **errorptr, - int *erroroffset, const unsigned char *tables) -#endif -{ -#if defined COMPILE_PCRE8 -return pcre_compile2(pattern, options, NULL, errorptr, erroroffset, tables); -#elif defined COMPILE_PCRE16 -return pcre16_compile2(pattern, options, NULL, errorptr, erroroffset, tables); -#elif defined COMPILE_PCRE32 -return pcre32_compile2(pattern, options, NULL, errorptr, erroroffset, tables); -#endif -} - - -#if defined COMPILE_PCRE8 -PCRE_EXP_DEFN pcre * PCRE_CALL_CONVENTION -pcre_compile2(const char *pattern, int options, int *errorcodeptr, - const char **errorptr, int *erroroffset, const unsigned char *tables) -#elif defined COMPILE_PCRE16 -PCRE_EXP_DEFN pcre16 * PCRE_CALL_CONVENTION -pcre16_compile2(PCRE_SPTR16 pattern, int options, int *errorcodeptr, - const char **errorptr, int *erroroffset, const unsigned char *tables) -#elif defined COMPILE_PCRE32 -PCRE_EXP_DEFN pcre32 * PCRE_CALL_CONVENTION -pcre32_compile2(PCRE_SPTR32 pattern, int options, int *errorcodeptr, - const char **errorptr, int *erroroffset, const unsigned char *tables) -#endif -{ -REAL_PCRE *re; -int length = 1; /* For final END opcode */ -pcre_int32 firstcharflags, reqcharflags; -pcre_uint32 firstchar, reqchar; -pcre_uint32 limit_match = PCRE_UINT32_MAX; -pcre_uint32 limit_recursion = PCRE_UINT32_MAX; -int newline; -int errorcode = 0; -int skipatstart = 0; -BOOL utf; -BOOL never_utf = FALSE; -size_t size; -pcre_uchar *code; -const pcre_uchar *codestart; -const pcre_uchar *ptr; -compile_data compile_block; -compile_data *cd = &compile_block; - -/* This space is used for "compiling" into during the first phase, when we are -computing the amount of memory that is needed. Compiled items are thrown away -as soon as possible, so that a fairly large buffer should be sufficient for -this purpose. The same space is used in the second phase for remembering where -to fill in forward references to subpatterns. That may overflow, in which case -new memory is obtained from malloc(). */ - -pcre_uchar cworkspace[COMPILE_WORK_SIZE]; - -/* This vector is used for remembering name groups during the pre-compile. In a -similar way to cworkspace, it can be expanded using malloc() if necessary. */ - -named_group named_groups[NAMED_GROUP_LIST_SIZE]; - -/* Set this early so that early errors get offset 0. */ - -ptr = (const pcre_uchar *)pattern; - -/* We can't pass back an error message if errorptr is NULL; I guess the best we -can do is just return NULL, but we can set a code value if there is a code -pointer. */ - -if (errorptr == NULL) - { - if (errorcodeptr != NULL) *errorcodeptr = 99; - return NULL; - } - -*errorptr = NULL; -if (errorcodeptr != NULL) *errorcodeptr = ERR0; - -/* However, we can give a message for this error */ - -if (erroroffset == NULL) - { - errorcode = ERR16; - goto PCRE_EARLY_ERROR_RETURN2; - } - -*erroroffset = 0; - -/* Set up pointers to the individual character tables */ - -if (tables == NULL) tables = PRIV(default_tables); -cd->lcc = tables + lcc_offset; -cd->fcc = tables + fcc_offset; -cd->cbits = tables + cbits_offset; -cd->ctypes = tables + ctypes_offset; - -/* Check that all undefined public option bits are zero */ - -if ((options & ~PUBLIC_COMPILE_OPTIONS) != 0) - { - errorcode = ERR17; - goto PCRE_EARLY_ERROR_RETURN; - } - -/* If PCRE_NEVER_UTF is set, remember it. */ - -if ((options & PCRE_NEVER_UTF) != 0) never_utf = TRUE; - -/* Check for global one-time settings at the start of the pattern, and remember -the offset for later. */ - -cd->external_flags = 0; /* Initialize here for LIMIT_MATCH/RECURSION */ - -while (ptr[skipatstart] == CHAR_LEFT_PARENTHESIS && - ptr[skipatstart+1] == CHAR_ASTERISK) - { - int newnl = 0; - int newbsr = 0; - -/* For completeness and backward compatibility, (*UTFn) is supported in the -relevant libraries, but (*UTF) is generic and always supported. Note that -PCRE_UTF8 == PCRE_UTF16 == PCRE_UTF32. */ - -#ifdef COMPILE_PCRE8 - if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_UTF8_RIGHTPAR, 5) == 0) - { skipatstart += 7; options |= PCRE_UTF8; continue; } -#endif -#ifdef COMPILE_PCRE16 - if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_UTF16_RIGHTPAR, 6) == 0) - { skipatstart += 8; options |= PCRE_UTF16; continue; } -#endif -#ifdef COMPILE_PCRE32 - if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_UTF32_RIGHTPAR, 6) == 0) - { skipatstart += 8; options |= PCRE_UTF32; continue; } -#endif - - else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_UTF_RIGHTPAR, 4) == 0) - { skipatstart += 6; options |= PCRE_UTF8; continue; } - else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_UCP_RIGHTPAR, 4) == 0) - { skipatstart += 6; options |= PCRE_UCP; continue; } - else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_NO_AUTO_POSSESS_RIGHTPAR, 16) == 0) - { skipatstart += 18; options |= PCRE_NO_AUTO_POSSESS; continue; } - else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_NO_START_OPT_RIGHTPAR, 13) == 0) - { skipatstart += 15; options |= PCRE_NO_START_OPTIMIZE; continue; } - - else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_LIMIT_MATCH_EQ, 12) == 0) - { - pcre_uint32 c = 0; - int p = skipatstart + 14; - while (isdigit(ptr[p])) - { - if (c > PCRE_UINT32_MAX / 10 - 1) break; /* Integer overflow */ - c = c*10 + ptr[p++] - CHAR_0; - } - if (ptr[p++] != CHAR_RIGHT_PARENTHESIS) break; - if (c < limit_match) - { - limit_match = c; - cd->external_flags |= PCRE_MLSET; - } - skipatstart = p; - continue; - } - - else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_LIMIT_RECURSION_EQ, 16) == 0) - { - pcre_uint32 c = 0; - int p = skipatstart + 18; - while (isdigit(ptr[p])) - { - if (c > PCRE_UINT32_MAX / 10 - 1) break; /* Integer overflow check */ - c = c*10 + ptr[p++] - CHAR_0; - } - if (ptr[p++] != CHAR_RIGHT_PARENTHESIS) break; - if (c < limit_recursion) - { - limit_recursion = c; - cd->external_flags |= PCRE_RLSET; - } - skipatstart = p; - continue; - } - - if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_CR_RIGHTPAR, 3) == 0) - { skipatstart += 5; newnl = PCRE_NEWLINE_CR; } - else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_LF_RIGHTPAR, 3) == 0) - { skipatstart += 5; newnl = PCRE_NEWLINE_LF; } - else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_CRLF_RIGHTPAR, 5) == 0) - { skipatstart += 7; newnl = PCRE_NEWLINE_CR + PCRE_NEWLINE_LF; } - else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_ANY_RIGHTPAR, 4) == 0) - { skipatstart += 6; newnl = PCRE_NEWLINE_ANY; } - else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_ANYCRLF_RIGHTPAR, 8) == 0) - { skipatstart += 10; newnl = PCRE_NEWLINE_ANYCRLF; } - - else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_BSR_ANYCRLF_RIGHTPAR, 12) == 0) - { skipatstart += 14; newbsr = PCRE_BSR_ANYCRLF; } - else if (STRNCMP_UC_C8(ptr+skipatstart+2, STRING_BSR_UNICODE_RIGHTPAR, 12) == 0) - { skipatstart += 14; newbsr = PCRE_BSR_UNICODE; } - - if (newnl != 0) - options = (options & ~PCRE_NEWLINE_BITS) | newnl; - else if (newbsr != 0) - options = (options & ~(PCRE_BSR_ANYCRLF|PCRE_BSR_UNICODE)) | newbsr; - else break; - } - -/* PCRE_UTF(16|32) have the same value as PCRE_UTF8. */ -utf = (options & PCRE_UTF8) != 0; -if (utf && never_utf) - { - errorcode = ERR78; - goto PCRE_EARLY_ERROR_RETURN2; - } - -/* Can't support UTF unless PCRE has been compiled to include the code. The -return of an error code from PRIV(valid_utf)() is a new feature, introduced in -release 8.13. It is passed back from pcre_[dfa_]exec(), but at the moment is -not used here. */ - -#ifdef SUPPORT_UTF -if (utf && (options & PCRE_NO_UTF8_CHECK) == 0 && - (errorcode = PRIV(valid_utf)((PCRE_PUCHAR)pattern, -1, erroroffset)) != 0) - { -#if defined COMPILE_PCRE8 - errorcode = ERR44; -#elif defined COMPILE_PCRE16 - errorcode = ERR74; -#elif defined COMPILE_PCRE32 - errorcode = ERR77; -#endif - goto PCRE_EARLY_ERROR_RETURN2; - } -#else -if (utf) - { - errorcode = ERR32; - goto PCRE_EARLY_ERROR_RETURN; - } -#endif - -/* Can't support UCP unless PCRE has been compiled to include the code. */ - -#ifndef SUPPORT_UCP -if ((options & PCRE_UCP) != 0) - { - errorcode = ERR67; - goto PCRE_EARLY_ERROR_RETURN; - } -#endif - -/* Check validity of \R options. */ - -if ((options & (PCRE_BSR_ANYCRLF|PCRE_BSR_UNICODE)) == - (PCRE_BSR_ANYCRLF|PCRE_BSR_UNICODE)) - { - errorcode = ERR56; - goto PCRE_EARLY_ERROR_RETURN; - } - -/* Handle different types of newline. The three bits give seven cases. The -current code allows for fixed one- or two-byte sequences, plus "any" and -"anycrlf". */ - -switch (options & PCRE_NEWLINE_BITS) - { - case 0: newline = NEWLINE; break; /* Build-time default */ - case PCRE_NEWLINE_CR: newline = CHAR_CR; break; - case PCRE_NEWLINE_LF: newline = CHAR_NL; break; - case PCRE_NEWLINE_CR+ - PCRE_NEWLINE_LF: newline = (CHAR_CR << 8) | CHAR_NL; break; - case PCRE_NEWLINE_ANY: newline = -1; break; - case PCRE_NEWLINE_ANYCRLF: newline = -2; break; - default: errorcode = ERR56; goto PCRE_EARLY_ERROR_RETURN; - } - -if (newline == -2) - { - cd->nltype = NLTYPE_ANYCRLF; - } -else if (newline < 0) - { - cd->nltype = NLTYPE_ANY; - } -else - { - cd->nltype = NLTYPE_FIXED; - if (newline > 255) - { - cd->nllen = 2; - cd->nl[0] = (newline >> 8) & 255; - cd->nl[1] = newline & 255; - } - else - { - cd->nllen = 1; - cd->nl[0] = newline; - } - } - -/* Maximum back reference and backref bitmap. The bitmap records up to 31 back -references to help in deciding whether (.*) can be treated as anchored or not. -*/ - -cd->top_backref = 0; -cd->backref_map = 0; - -/* Reflect pattern for debugging output */ - -DPRINTF(("------------------------------------------------------------------\n")); -#ifdef PCRE_DEBUG -print_puchar(stdout, (PCRE_PUCHAR)pattern); -#endif -DPRINTF(("\n")); - -/* Pretend to compile the pattern while actually just accumulating the length -of memory required. This behaviour is triggered by passing a non-NULL final -argument to compile_regex(). We pass a block of workspace (cworkspace) for it -to compile parts of the pattern into; the compiled code is discarded when it is -no longer needed, so hopefully this workspace will never overflow, though there -is a test for its doing so. */ - -cd->bracount = cd->final_bracount = 0; -cd->names_found = 0; -cd->name_entry_size = 0; -cd->name_table = NULL; -cd->dupnames = FALSE; -cd->namedrefcount = 0; -cd->start_code = cworkspace; -cd->hwm = cworkspace; -cd->start_workspace = cworkspace; -cd->workspace_size = COMPILE_WORK_SIZE; -cd->named_groups = named_groups; -cd->named_group_list_size = NAMED_GROUP_LIST_SIZE; -cd->start_pattern = (const pcre_uchar *)pattern; -cd->end_pattern = (const pcre_uchar *)(pattern + STRLEN_UC((const pcre_uchar *)pattern)); -cd->req_varyopt = 0; -cd->parens_depth = 0; -cd->assert_depth = 0; -cd->max_lookbehind = 0; -cd->external_options = options; -cd->open_caps = NULL; - -/* Now do the pre-compile. On error, errorcode will be set non-zero, so we -don't need to look at the result of the function here. The initial options have -been put into the cd block so that they can be changed if an option setting is -found within the regex right at the beginning. Bringing initial option settings -outside can help speed up starting point checks. */ - -ptr += skipatstart; -code = cworkspace; -*code = OP_BRA; - -(void)compile_regex(cd->external_options, &code, &ptr, &errorcode, FALSE, - FALSE, 0, 0, &firstchar, &firstcharflags, &reqchar, &reqcharflags, NULL, - cd, &length); -if (errorcode != 0) goto PCRE_EARLY_ERROR_RETURN; - -DPRINTF(("end pre-compile: length=%d workspace=%d\n", length, - (int)(cd->hwm - cworkspace))); - -if (length > MAX_PATTERN_SIZE) - { - errorcode = ERR20; - goto PCRE_EARLY_ERROR_RETURN; - } - -/* If there are groups with duplicate names and there are also references by -name, we must allow for the possibility of named references to duplicated -groups. These require an extra data item each. */ - -if (cd->dupnames && cd->namedrefcount > 0) - length += cd->namedrefcount * IMM2_SIZE * sizeof(pcre_uchar); - -/* Compute the size of the data block for storing the compiled pattern. Integer -overflow should no longer be possible because nowadays we limit the maximum -value of cd->names_found and cd->name_entry_size. */ - -size = sizeof(REAL_PCRE) + - (length + cd->names_found * cd->name_entry_size) * sizeof(pcre_uchar); - -/* Get the memory. */ - -re = (REAL_PCRE *)(PUBL(malloc))(size); -if (re == NULL) - { - errorcode = ERR21; - goto PCRE_EARLY_ERROR_RETURN; - } - -/* Put in the magic number, and save the sizes, initial options, internal -flags, and character table pointer. NULL is used for the default character -tables. The nullpad field is at the end; it's there to help in the case when a -regex compiled on a system with 4-byte pointers is run on another with 8-byte -pointers. */ - -re->magic_number = MAGIC_NUMBER; -re->size = (int)size; -re->options = cd->external_options; -re->flags = cd->external_flags; -re->limit_match = limit_match; -re->limit_recursion = limit_recursion; -re->first_char = 0; -re->req_char = 0; -re->name_table_offset = sizeof(REAL_PCRE) / sizeof(pcre_uchar); -re->name_entry_size = cd->name_entry_size; -re->name_count = cd->names_found; -re->ref_count = 0; -re->tables = (tables == PRIV(default_tables))? NULL : tables; -re->nullpad = NULL; -#ifdef COMPILE_PCRE32 -re->dummy = 0; -#else -re->dummy1 = re->dummy2 = re->dummy3 = 0; -#endif - -/* The starting points of the name/number translation table and of the code are -passed around in the compile data block. The start/end pattern and initial -options are already set from the pre-compile phase, as is the name_entry_size -field. Reset the bracket count and the names_found field. Also reset the hwm -field; this time it's used for remembering forward references to subpatterns. -*/ - -cd->final_bracount = cd->bracount; /* Save for checking forward references */ -cd->parens_depth = 0; -cd->assert_depth = 0; -cd->bracount = 0; -cd->max_lookbehind = 0; -cd->name_table = (pcre_uchar *)re + re->name_table_offset; -codestart = cd->name_table + re->name_entry_size * re->name_count; -cd->start_code = codestart; -cd->hwm = (pcre_uchar *)(cd->start_workspace); -cd->req_varyopt = 0; -cd->had_accept = FALSE; -cd->had_pruneorskip = FALSE; -cd->check_lookbehind = FALSE; -cd->open_caps = NULL; - -/* If any named groups were found, create the name/number table from the list -created in the first pass. */ - -if (cd->names_found > 0) - { - int i = cd->names_found; - named_group *ng = cd->named_groups; - cd->names_found = 0; - for (; i > 0; i--, ng++) - add_name(cd, ng->name, ng->length, ng->number); - if (cd->named_group_list_size > NAMED_GROUP_LIST_SIZE) - (PUBL(free))((void *)cd->named_groups); - } - -/* Set up a starting, non-extracting bracket, then compile the expression. On -error, errorcode will be set non-zero, so we don't need to look at the result -of the function here. */ - -ptr = (const pcre_uchar *)pattern + skipatstart; -code = (pcre_uchar *)codestart; -*code = OP_BRA; -(void)compile_regex(re->options, &code, &ptr, &errorcode, FALSE, FALSE, 0, 0, - &firstchar, &firstcharflags, &reqchar, &reqcharflags, NULL, cd, NULL); -re->top_bracket = cd->bracount; -re->top_backref = cd->top_backref; -re->max_lookbehind = cd->max_lookbehind; -re->flags = cd->external_flags | PCRE_MODE; - -if (cd->had_accept) - { - reqchar = 0; /* Must disable after (*ACCEPT) */ - reqcharflags = REQ_NONE; - } - -/* If not reached end of pattern on success, there's an excess bracket. */ - -if (errorcode == 0 && *ptr != CHAR_NULL) errorcode = ERR22; - -/* Fill in the terminating state and check for disastrous overflow, but -if debugging, leave the test till after things are printed out. */ - -*code++ = OP_END; - -#ifndef PCRE_DEBUG -if (code - codestart > length) errorcode = ERR23; -#endif - -#ifdef SUPPORT_VALGRIND -/* If the estimated length exceeds the really used length, mark the extra -allocated memory as unaddressable, so that any out-of-bound reads can be -detected. */ -VALGRIND_MAKE_MEM_NOACCESS(code, (length - (code - codestart)) * sizeof(pcre_uchar)); -#endif - -/* Fill in any forward references that are required. There may be repeated -references; optimize for them, as searching a large regex takes time. */ - -if (cd->hwm > cd->start_workspace) - { - int prev_recno = -1; - const pcre_uchar *groupptr = NULL; - while (errorcode == 0 && cd->hwm > cd->start_workspace) - { - int offset, recno; - cd->hwm -= LINK_SIZE; - offset = GET(cd->hwm, 0); - recno = GET(codestart, offset); - if (recno != prev_recno) - { - groupptr = PRIV(find_bracket)(codestart, utf, recno); - prev_recno = recno; - } - if (groupptr == NULL) errorcode = ERR53; - else PUT(((pcre_uchar *)codestart), offset, (int)(groupptr - codestart)); - } - } - -/* If the workspace had to be expanded, free the new memory. Set the pointer to -NULL to indicate that forward references have been filled in. */ - -if (cd->workspace_size > COMPILE_WORK_SIZE) - (PUBL(free))((void *)cd->start_workspace); -cd->start_workspace = NULL; - -/* Give an error if there's back reference to a non-existent capturing -subpattern. */ - -if (errorcode == 0 && re->top_backref > re->top_bracket) errorcode = ERR15; - -/* Unless disabled, check whether any single character iterators can be -auto-possessified. The function overwrites the appropriate opcode values, so -the type of the pointer must be cast. NOTE: the intermediate variable "temp" is -used in this code because at least one compiler gives a warning about loss of -"const" attribute if the cast (pcre_uchar *)codestart is used directly in the -function call. */ - -if ((options & PCRE_NO_AUTO_POSSESS) == 0) - { - pcre_uchar *temp = (pcre_uchar *)codestart; - auto_possessify(temp, utf, cd); - } - -/* If there were any lookbehind assertions that contained OP_RECURSE -(recursions or subroutine calls), a flag is set for them to be checked here, -because they may contain forward references. Actual recursions cannot be fixed -length, but subroutine calls can. It is done like this so that those without -OP_RECURSE that are not fixed length get a diagnosic with a useful offset. The -exceptional ones forgo this. We scan the pattern to check that they are fixed -length, and set their lengths. */ - -if (cd->check_lookbehind) - { - pcre_uchar *cc = (pcre_uchar *)codestart; - - /* Loop, searching for OP_REVERSE items, and process those that do not have - their length set. (Actually, it will also re-process any that have a length - of zero, but that is a pathological case, and it does no harm.) When we find - one, we temporarily terminate the branch it is in while we scan it. */ - - for (cc = (pcre_uchar *)PRIV(find_bracket)(codestart, utf, -1); - cc != NULL; - cc = (pcre_uchar *)PRIV(find_bracket)(cc, utf, -1)) - { - if (GET(cc, 1) == 0) - { - int fixed_length; - pcre_uchar *be = cc - 1 - LINK_SIZE + GET(cc, -LINK_SIZE); - int end_op = *be; - *be = OP_END; - fixed_length = find_fixedlength(cc, (re->options & PCRE_UTF8) != 0, TRUE, - cd); - *be = end_op; - DPRINTF(("fixed length = %d\n", fixed_length)); - if (fixed_length < 0) - { - errorcode = (fixed_length == -2)? ERR36 : - (fixed_length == -4)? ERR70 : ERR25; - break; - } - if (fixed_length > cd->max_lookbehind) cd->max_lookbehind = fixed_length; - PUT(cc, 1, fixed_length); - } - cc += 1 + LINK_SIZE; - } - } - -/* Failed to compile, or error while post-processing */ - -if (errorcode != 0) - { - (PUBL(free))(re); - PCRE_EARLY_ERROR_RETURN: - *erroroffset = (int)(ptr - (const pcre_uchar *)pattern); - PCRE_EARLY_ERROR_RETURN2: - *errorptr = find_error_text(errorcode); - if (errorcodeptr != NULL) *errorcodeptr = errorcode; - return NULL; - } - -/* If the anchored option was not passed, set the flag if we can determine that -the pattern is anchored by virtue of ^ characters or \A or anything else, such -as starting with non-atomic .* when DOTALL is set and there are no occurrences -of *PRUNE or *SKIP. - -Otherwise, if we know what the first byte has to be, save it, because that -speeds up unanchored matches no end. If not, see if we can set the -PCRE_STARTLINE flag. This is helpful for multiline matches when all branches -start with ^. and also when all branches start with non-atomic .* for -non-DOTALL matches when *PRUNE and SKIP are not present. */ - -if ((re->options & PCRE_ANCHORED) == 0) - { - if (is_anchored(codestart, 0, cd, 0)) re->options |= PCRE_ANCHORED; - else - { - if (firstcharflags < 0) - firstchar = find_firstassertedchar(codestart, &firstcharflags, FALSE); - if (firstcharflags >= 0) /* Remove caseless flag for non-caseable chars */ - { -#if defined COMPILE_PCRE8 - re->first_char = firstchar & 0xff; -#elif defined COMPILE_PCRE16 - re->first_char = firstchar & 0xffff; -#elif defined COMPILE_PCRE32 - re->first_char = firstchar; -#endif - if ((firstcharflags & REQ_CASELESS) != 0) - { -#if defined SUPPORT_UCP && !(defined COMPILE_PCRE8) - /* We ignore non-ASCII first chars in 8 bit mode. */ - if (utf) - { - if (re->first_char < 128) - { - if (cd->fcc[re->first_char] != re->first_char) - re->flags |= PCRE_FCH_CASELESS; - } - else if (UCD_OTHERCASE(re->first_char) != re->first_char) - re->flags |= PCRE_FCH_CASELESS; - } - else -#endif - if (MAX_255(re->first_char) - && cd->fcc[re->first_char] != re->first_char) - re->flags |= PCRE_FCH_CASELESS; - } - - re->flags |= PCRE_FIRSTSET; - } - - else if (is_startline(codestart, 0, cd, 0)) re->flags |= PCRE_STARTLINE; - } - } - -/* For an anchored pattern, we use the "required byte" only if it follows a -variable length item in the regex. Remove the caseless flag for non-caseable -bytes. */ - -if (reqcharflags >= 0 && - ((re->options & PCRE_ANCHORED) == 0 || (reqcharflags & REQ_VARY) != 0)) - { -#if defined COMPILE_PCRE8 - re->req_char = reqchar & 0xff; -#elif defined COMPILE_PCRE16 - re->req_char = reqchar & 0xffff; -#elif defined COMPILE_PCRE32 - re->req_char = reqchar; -#endif - if ((reqcharflags & REQ_CASELESS) != 0) - { -#if defined SUPPORT_UCP && !(defined COMPILE_PCRE8) - /* We ignore non-ASCII first chars in 8 bit mode. */ - if (utf) - { - if (re->req_char < 128) - { - if (cd->fcc[re->req_char] != re->req_char) - re->flags |= PCRE_RCH_CASELESS; - } - else if (UCD_OTHERCASE(re->req_char) != re->req_char) - re->flags |= PCRE_RCH_CASELESS; - } - else -#endif - if (MAX_255(re->req_char) && cd->fcc[re->req_char] != re->req_char) - re->flags |= PCRE_RCH_CASELESS; - } - - re->flags |= PCRE_REQCHSET; - } - -/* Print out the compiled data if debugging is enabled. This is never the -case when building a production library. */ - -#ifdef PCRE_DEBUG -printf("Length = %d top_bracket = %d top_backref = %d\n", - length, re->top_bracket, re->top_backref); - -printf("Options=%08x\n", re->options); - -if ((re->flags & PCRE_FIRSTSET) != 0) - { - pcre_uchar ch = re->first_char; - const char *caseless = - ((re->flags & PCRE_FCH_CASELESS) == 0)? "" : " (caseless)"; - if (PRINTABLE(ch)) printf("First char = %c%s\n", ch, caseless); - else printf("First char = \\x%02x%s\n", ch, caseless); - } - -if ((re->flags & PCRE_REQCHSET) != 0) - { - pcre_uchar ch = re->req_char; - const char *caseless = - ((re->flags & PCRE_RCH_CASELESS) == 0)? "" : " (caseless)"; - if (PRINTABLE(ch)) printf("Req char = %c%s\n", ch, caseless); - else printf("Req char = \\x%02x%s\n", ch, caseless); - } - -#if defined COMPILE_PCRE8 -pcre_printint((pcre *)re, stdout, TRUE); -#elif defined COMPILE_PCRE16 -pcre16_printint((pcre *)re, stdout, TRUE); -#elif defined COMPILE_PCRE32 -pcre32_printint((pcre *)re, stdout, TRUE); -#endif - -/* This check is done here in the debugging case so that the code that -was compiled can be seen. */ - -if (code - codestart > length) - { - (PUBL(free))(re); - *errorptr = find_error_text(ERR23); - *erroroffset = ptr - (pcre_uchar *)pattern; - if (errorcodeptr != NULL) *errorcodeptr = ERR23; - return NULL; - } -#endif /* PCRE_DEBUG */ - -/* Check for a pattern than can match an empty string, so that this information -can be provided to applications. */ - -do - { - if (could_be_empty_branch(codestart, code, utf, cd, NULL)) - { - re->flags |= PCRE_MATCH_EMPTY; - break; - } - codestart += GET(codestart, 1); - } -while (*codestart == OP_ALT); - -#if defined COMPILE_PCRE8 -return (pcre *)re; -#elif defined COMPILE_PCRE16 -return (pcre16 *)re; -#elif defined COMPILE_PCRE32 -return (pcre32 *)re; -#endif -} - -/* End of pcre_compile.c */ - diff --git a/lib/impure/nre/private/pcre_src/pcre_config.c b/lib/impure/nre/private/pcre_src/pcre_config.c deleted file mode 100644 index 1cbdd9c96..000000000 --- a/lib/impure/nre/private/pcre_src/pcre_config.c +++ /dev/null @@ -1,190 +0,0 @@ -/************************************************* -* Perl-Compatible Regular Expressions * -*************************************************/ - -/* PCRE is a library of functions to support regular expressions whose syntax -and semantics are as close as possible to those of the Perl 5 language. - - Written by Philip Hazel - Copyright (c) 1997-2012 University of Cambridge - ------------------------------------------------------------------------------ -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - * Neither the name of the University of Cambridge nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ -*/ - - -/* This module contains the external function pcre_config(). */ - - -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - -/* Keep the original link size. */ -static int real_link_size = LINK_SIZE; - -#include "pcre_internal.h" - - -/************************************************* -* Return info about what features are configured * -*************************************************/ - -/* This function has an extensible interface so that additional items can be -added compatibly. - -Arguments: - what what information is required - where where to put the information - -Returns: 0 if data returned, negative on error -*/ - -#if defined COMPILE_PCRE8 -PCRE_EXP_DEFN int PCRE_CALL_CONVENTION -pcre_config(int what, void *where) -#elif defined COMPILE_PCRE16 -PCRE_EXP_DEFN int PCRE_CALL_CONVENTION -pcre16_config(int what, void *where) -#elif defined COMPILE_PCRE32 -PCRE_EXP_DEFN int PCRE_CALL_CONVENTION -pcre32_config(int what, void *where) -#endif -{ -switch (what) - { - case PCRE_CONFIG_UTF8: -#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 - *((int *)where) = 0; - return PCRE_ERROR_BADOPTION; -#else -#if defined SUPPORT_UTF - *((int *)where) = 1; -#else - *((int *)where) = 0; -#endif - break; -#endif - - case PCRE_CONFIG_UTF16: -#if defined COMPILE_PCRE8 || defined COMPILE_PCRE32 - *((int *)where) = 0; - return PCRE_ERROR_BADOPTION; -#else -#if defined SUPPORT_UTF - *((int *)where) = 1; -#else - *((int *)where) = 0; -#endif - break; -#endif - - case PCRE_CONFIG_UTF32: -#if defined COMPILE_PCRE8 || defined COMPILE_PCRE16 - *((int *)where) = 0; - return PCRE_ERROR_BADOPTION; -#else -#if defined SUPPORT_UTF - *((int *)where) = 1; -#else - *((int *)where) = 0; -#endif - break; -#endif - - case PCRE_CONFIG_UNICODE_PROPERTIES: -#ifdef SUPPORT_UCP - *((int *)where) = 1; -#else - *((int *)where) = 0; -#endif - break; - - case PCRE_CONFIG_JIT: -#ifdef SUPPORT_JIT - *((int *)where) = 1; -#else - *((int *)where) = 0; -#endif - break; - - case PCRE_CONFIG_JITTARGET: -#ifdef SUPPORT_JIT - *((const char **)where) = PRIV(jit_get_target)(); -#else - *((const char **)where) = NULL; -#endif - break; - - case PCRE_CONFIG_NEWLINE: - *((int *)where) = NEWLINE; - break; - - case PCRE_CONFIG_BSR: -#ifdef BSR_ANYCRLF - *((int *)where) = 1; -#else - *((int *)where) = 0; -#endif - break; - - case PCRE_CONFIG_LINK_SIZE: - *((int *)where) = real_link_size; - break; - - case PCRE_CONFIG_POSIX_MALLOC_THRESHOLD: - *((int *)where) = POSIX_MALLOC_THRESHOLD; - break; - - case PCRE_CONFIG_PARENS_LIMIT: - *((unsigned long int *)where) = PARENS_NEST_LIMIT; - break; - - case PCRE_CONFIG_MATCH_LIMIT: - *((unsigned long int *)where) = MATCH_LIMIT; - break; - - case PCRE_CONFIG_MATCH_LIMIT_RECURSION: - *((unsigned long int *)where) = MATCH_LIMIT_RECURSION; - break; - - case PCRE_CONFIG_STACKRECURSE: -#ifdef NO_RECURSE - *((int *)where) = 0; -#else - *((int *)where) = 1; -#endif - break; - - default: return PCRE_ERROR_BADOPTION; - } - -return 0; -} - -/* End of pcre_config.c */ diff --git a/lib/impure/nre/private/pcre_src/pcre_dfa_exec.c b/lib/impure/nre/private/pcre_src/pcre_dfa_exec.c deleted file mode 100644 index 87f4aef9a..000000000 --- a/lib/impure/nre/private/pcre_src/pcre_dfa_exec.c +++ /dev/null @@ -1,3673 +0,0 @@ -/************************************************* -* Perl-Compatible Regular Expressions * -*************************************************/ - -/* PCRE is a library of functions to support regular expressions whose syntax -and semantics are as close as possible to those of the Perl 5 language (but see -below for why this module is different). - - Written by Philip Hazel - Copyright (c) 1997-2014 University of Cambridge - ------------------------------------------------------------------------------ -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - * Neither the name of the University of Cambridge nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ -*/ - -/* This module contains the external function pcre_dfa_exec(), which is an -alternative matching function that uses a sort of DFA algorithm (not a true -FSM). This is NOT Perl-compatible, but it has advantages in certain -applications. */ - - -/* NOTE ABOUT PERFORMANCE: A user of this function sent some code that improved -the performance of his patterns greatly. I could not use it as it stood, as it -was not thread safe, and made assumptions about pattern sizes. Also, it caused -test 7 to loop, and test 9 to crash with a segfault. - -The issue is the check for duplicate states, which is done by a simple linear -search up the state list. (Grep for "duplicate" below to find the code.) For -many patterns, there will never be many states active at one time, so a simple -linear search is fine. In patterns that have many active states, it might be a -bottleneck. The suggested code used an indexing scheme to remember which states -had previously been used for each character, and avoided the linear search when -it knew there was no chance of a duplicate. This was implemented when adding -states to the state lists. - -I wrote some thread-safe, not-limited code to try something similar at the time -of checking for duplicates (instead of when adding states), using index vectors -on the stack. It did give a 13% improvement with one specially constructed -pattern for certain subject strings, but on other strings and on many of the -simpler patterns in the test suite it did worse. The major problem, I think, -was the extra time to initialize the index. This had to be done for each call -of internal_dfa_exec(). (The supplied patch used a static vector, initialized -only once - I suspect this was the cause of the problems with the tests.) - -Overall, I concluded that the gains in some cases did not outweigh the losses -in others, so I abandoned this code. */ - - - -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - -#define NLBLOCK md /* Block containing newline information */ -#define PSSTART start_subject /* Field containing processed string start */ -#define PSEND end_subject /* Field containing processed string end */ - -#include "pcre_internal.h" - - -/* For use to indent debugging output */ - -#define SP " " - - -/************************************************* -* Code parameters and static tables * -*************************************************/ - -/* These are offsets that are used to turn the OP_TYPESTAR and friends opcodes -into others, under special conditions. A gap of 20 between the blocks should be -enough. The resulting opcodes don't have to be less than 256 because they are -never stored, so we push them well clear of the normal opcodes. */ - -#define OP_PROP_EXTRA 300 -#define OP_EXTUNI_EXTRA 320 -#define OP_ANYNL_EXTRA 340 -#define OP_HSPACE_EXTRA 360 -#define OP_VSPACE_EXTRA 380 - - -/* This table identifies those opcodes that are followed immediately by a -character that is to be tested in some way. This makes it possible to -centralize the loading of these characters. In the case of Type * etc, the -"character" is the opcode for \D, \d, \S, \s, \W, or \w, which will always be a -small value. Non-zero values in the table are the offsets from the opcode where -the character is to be found. ***NOTE*** If the start of this table is -modified, the three tables that follow must also be modified. */ - -static const pcre_uint8 coptable[] = { - 0, /* End */ - 0, 0, 0, 0, 0, /* \A, \G, \K, \B, \b */ - 0, 0, 0, 0, 0, 0, /* \D, \d, \S, \s, \W, \w */ - 0, 0, 0, /* Any, AllAny, Anybyte */ - 0, 0, /* \P, \p */ - 0, 0, 0, 0, 0, /* \R, \H, \h, \V, \v */ - 0, /* \X */ - 0, 0, 0, 0, 0, 0, /* \Z, \z, $, $M, ^, ^M */ - 1, /* Char */ - 1, /* Chari */ - 1, /* not */ - 1, /* noti */ - /* Positive single-char repeats */ - 1, 1, 1, 1, 1, 1, /* *, *?, +, +?, ?, ?? */ - 1+IMM2_SIZE, 1+IMM2_SIZE, /* upto, minupto */ - 1+IMM2_SIZE, /* exact */ - 1, 1, 1, 1+IMM2_SIZE, /* *+, ++, ?+, upto+ */ - 1, 1, 1, 1, 1, 1, /* *I, *?I, +I, +?I, ?I, ??I */ - 1+IMM2_SIZE, 1+IMM2_SIZE, /* upto I, minupto I */ - 1+IMM2_SIZE, /* exact I */ - 1, 1, 1, 1+IMM2_SIZE, /* *+I, ++I, ?+I, upto+I */ - /* Negative single-char repeats - only for chars < 256 */ - 1, 1, 1, 1, 1, 1, /* NOT *, *?, +, +?, ?, ?? */ - 1+IMM2_SIZE, 1+IMM2_SIZE, /* NOT upto, minupto */ - 1+IMM2_SIZE, /* NOT exact */ - 1, 1, 1, 1+IMM2_SIZE, /* NOT *+, ++, ?+, upto+ */ - 1, 1, 1, 1, 1, 1, /* NOT *I, *?I, +I, +?I, ?I, ??I */ - 1+IMM2_SIZE, 1+IMM2_SIZE, /* NOT upto I, minupto I */ - 1+IMM2_SIZE, /* NOT exact I */ - 1, 1, 1, 1+IMM2_SIZE, /* NOT *+I, ++I, ?+I, upto+I */ - /* Positive type repeats */ - 1, 1, 1, 1, 1, 1, /* Type *, *?, +, +?, ?, ?? */ - 1+IMM2_SIZE, 1+IMM2_SIZE, /* Type upto, minupto */ - 1+IMM2_SIZE, /* Type exact */ - 1, 1, 1, 1+IMM2_SIZE, /* Type *+, ++, ?+, upto+ */ - /* Character class & ref repeats */ - 0, 0, 0, 0, 0, 0, /* *, *?, +, +?, ?, ?? */ - 0, 0, /* CRRANGE, CRMINRANGE */ - 0, 0, 0, 0, /* Possessive *+, ++, ?+, CRPOSRANGE */ - 0, /* CLASS */ - 0, /* NCLASS */ - 0, /* XCLASS - variable length */ - 0, /* REF */ - 0, /* REFI */ - 0, /* DNREF */ - 0, /* DNREFI */ - 0, /* RECURSE */ - 0, /* CALLOUT */ - 0, /* Alt */ - 0, /* Ket */ - 0, /* KetRmax */ - 0, /* KetRmin */ - 0, /* KetRpos */ - 0, /* Reverse */ - 0, /* Assert */ - 0, /* Assert not */ - 0, /* Assert behind */ - 0, /* Assert behind not */ - 0, 0, /* ONCE, ONCE_NC */ - 0, 0, 0, 0, 0, /* BRA, BRAPOS, CBRA, CBRAPOS, COND */ - 0, 0, 0, 0, 0, /* SBRA, SBRAPOS, SCBRA, SCBRAPOS, SCOND */ - 0, 0, /* CREF, DNCREF */ - 0, 0, /* RREF, DNRREF */ - 0, /* DEF */ - 0, 0, 0, /* BRAZERO, BRAMINZERO, BRAPOSZERO */ - 0, 0, 0, /* MARK, PRUNE, PRUNE_ARG */ - 0, 0, 0, 0, /* SKIP, SKIP_ARG, THEN, THEN_ARG */ - 0, 0, 0, 0, /* COMMIT, FAIL, ACCEPT, ASSERT_ACCEPT */ - 0, 0 /* CLOSE, SKIPZERO */ -}; - -/* This table identifies those opcodes that inspect a character. It is used to -remember the fact that a character could have been inspected when the end of -the subject is reached. ***NOTE*** If the start of this table is modified, the -two tables that follow must also be modified. */ - -static const pcre_uint8 poptable[] = { - 0, /* End */ - 0, 0, 0, 1, 1, /* \A, \G, \K, \B, \b */ - 1, 1, 1, 1, 1, 1, /* \D, \d, \S, \s, \W, \w */ - 1, 1, 1, /* Any, AllAny, Anybyte */ - 1, 1, /* \P, \p */ - 1, 1, 1, 1, 1, /* \R, \H, \h, \V, \v */ - 1, /* \X */ - 0, 0, 0, 0, 0, 0, /* \Z, \z, $, $M, ^, ^M */ - 1, /* Char */ - 1, /* Chari */ - 1, /* not */ - 1, /* noti */ - /* Positive single-char repeats */ - 1, 1, 1, 1, 1, 1, /* *, *?, +, +?, ?, ?? */ - 1, 1, 1, /* upto, minupto, exact */ - 1, 1, 1, 1, /* *+, ++, ?+, upto+ */ - 1, 1, 1, 1, 1, 1, /* *I, *?I, +I, +?I, ?I, ??I */ - 1, 1, 1, /* upto I, minupto I, exact I */ - 1, 1, 1, 1, /* *+I, ++I, ?+I, upto+I */ - /* Negative single-char repeats - only for chars < 256 */ - 1, 1, 1, 1, 1, 1, /* NOT *, *?, +, +?, ?, ?? */ - 1, 1, 1, /* NOT upto, minupto, exact */ - 1, 1, 1, 1, /* NOT *+, ++, ?+, upto+ */ - 1, 1, 1, 1, 1, 1, /* NOT *I, *?I, +I, +?I, ?I, ??I */ - 1, 1, 1, /* NOT upto I, minupto I, exact I */ - 1, 1, 1, 1, /* NOT *+I, ++I, ?+I, upto+I */ - /* Positive type repeats */ - 1, 1, 1, 1, 1, 1, /* Type *, *?, +, +?, ?, ?? */ - 1, 1, 1, /* Type upto, minupto, exact */ - 1, 1, 1, 1, /* Type *+, ++, ?+, upto+ */ - /* Character class & ref repeats */ - 1, 1, 1, 1, 1, 1, /* *, *?, +, +?, ?, ?? */ - 1, 1, /* CRRANGE, CRMINRANGE */ - 1, 1, 1, 1, /* Possessive *+, ++, ?+, CRPOSRANGE */ - 1, /* CLASS */ - 1, /* NCLASS */ - 1, /* XCLASS - variable length */ - 0, /* REF */ - 0, /* REFI */ - 0, /* DNREF */ - 0, /* DNREFI */ - 0, /* RECURSE */ - 0, /* CALLOUT */ - 0, /* Alt */ - 0, /* Ket */ - 0, /* KetRmax */ - 0, /* KetRmin */ - 0, /* KetRpos */ - 0, /* Reverse */ - 0, /* Assert */ - 0, /* Assert not */ - 0, /* Assert behind */ - 0, /* Assert behind not */ - 0, 0, /* ONCE, ONCE_NC */ - 0, 0, 0, 0, 0, /* BRA, BRAPOS, CBRA, CBRAPOS, COND */ - 0, 0, 0, 0, 0, /* SBRA, SBRAPOS, SCBRA, SCBRAPOS, SCOND */ - 0, 0, /* CREF, DNCREF */ - 0, 0, /* RREF, DNRREF */ - 0, /* DEF */ - 0, 0, 0, /* BRAZERO, BRAMINZERO, BRAPOSZERO */ - 0, 0, 0, /* MARK, PRUNE, PRUNE_ARG */ - 0, 0, 0, 0, /* SKIP, SKIP_ARG, THEN, THEN_ARG */ - 0, 0, 0, 0, /* COMMIT, FAIL, ACCEPT, ASSERT_ACCEPT */ - 0, 0 /* CLOSE, SKIPZERO */ -}; - -/* These 2 tables allow for compact code for testing for \D, \d, \S, \s, \W, -and \w */ - -static const pcre_uint8 toptable1[] = { - 0, 0, 0, 0, 0, 0, - ctype_digit, ctype_digit, - ctype_space, ctype_space, - ctype_word, ctype_word, - 0, 0 /* OP_ANY, OP_ALLANY */ -}; - -static const pcre_uint8 toptable2[] = { - 0, 0, 0, 0, 0, 0, - ctype_digit, 0, - ctype_space, 0, - ctype_word, 0, - 1, 1 /* OP_ANY, OP_ALLANY */ -}; - - -/* Structure for holding data about a particular state, which is in effect the -current data for an active path through the match tree. It must consist -entirely of ints because the working vector we are passed, and which we put -these structures in, is a vector of ints. */ - -typedef struct stateblock { - int offset; /* Offset to opcode */ - int count; /* Count for repeats */ - int data; /* Some use extra data */ -} stateblock; - -#define INTS_PER_STATEBLOCK (int)(sizeof(stateblock)/sizeof(int)) - - -#ifdef PCRE_DEBUG -/************************************************* -* Print character string * -*************************************************/ - -/* Character string printing function for debugging. - -Arguments: - p points to string - length number of bytes - f where to print - -Returns: nothing -*/ - -static void -pchars(const pcre_uchar *p, int length, FILE *f) -{ -pcre_uint32 c; -while (length-- > 0) - { - if (isprint(c = *(p++))) - fprintf(f, "%c", c); - else - fprintf(f, "\\x{%02x}", c); - } -} -#endif - - - -/************************************************* -* Execute a Regular Expression - DFA engine * -*************************************************/ - -/* This internal function applies a compiled pattern to a subject string, -starting at a given point, using a DFA engine. This function is called from the -external one, possibly multiple times if the pattern is not anchored. The -function calls itself recursively for some kinds of subpattern. - -Arguments: - md the match_data block with fixed information - this_start_code the opening bracket of this subexpression's code - current_subject where we currently are in the subject string - start_offset start offset in the subject string - offsets vector to contain the matching string offsets - offsetcount size of same - workspace vector of workspace - wscount size of same - rlevel function call recursion level - -Returns: > 0 => number of match offset pairs placed in offsets - = 0 => offsets overflowed; longest matches are present - -1 => failed to match - < -1 => some kind of unexpected problem - -The following macros are used for adding states to the two state vectors (one -for the current character, one for the following character). */ - -#define ADD_ACTIVE(x,y) \ - if (active_count++ < wscount) \ - { \ - next_active_state->offset = (x); \ - next_active_state->count = (y); \ - next_active_state++; \ - DPRINTF(("%.*sADD_ACTIVE(%d,%d)\n", rlevel*2-2, SP, (x), (y))); \ - } \ - else return PCRE_ERROR_DFA_WSSIZE - -#define ADD_ACTIVE_DATA(x,y,z) \ - if (active_count++ < wscount) \ - { \ - next_active_state->offset = (x); \ - next_active_state->count = (y); \ - next_active_state->data = (z); \ - next_active_state++; \ - DPRINTF(("%.*sADD_ACTIVE_DATA(%d,%d,%d)\n", rlevel*2-2, SP, (x), (y), (z))); \ - } \ - else return PCRE_ERROR_DFA_WSSIZE - -#define ADD_NEW(x,y) \ - if (new_count++ < wscount) \ - { \ - next_new_state->offset = (x); \ - next_new_state->count = (y); \ - next_new_state++; \ - DPRINTF(("%.*sADD_NEW(%d,%d)\n", rlevel*2-2, SP, (x), (y))); \ - } \ - else return PCRE_ERROR_DFA_WSSIZE - -#define ADD_NEW_DATA(x,y,z) \ - if (new_count++ < wscount) \ - { \ - next_new_state->offset = (x); \ - next_new_state->count = (y); \ - next_new_state->data = (z); \ - next_new_state++; \ - DPRINTF(("%.*sADD_NEW_DATA(%d,%d,%d) line %d\n", rlevel*2-2, SP, \ - (x), (y), (z), __LINE__)); \ - } \ - else return PCRE_ERROR_DFA_WSSIZE - -/* And now, here is the code */ - -static int -internal_dfa_exec( - dfa_match_data *md, - const pcre_uchar *this_start_code, - const pcre_uchar *current_subject, - int start_offset, - int *offsets, - int offsetcount, - int *workspace, - int wscount, - int rlevel) -{ -stateblock *active_states, *new_states, *temp_states; -stateblock *next_active_state, *next_new_state; - -const pcre_uint8 *ctypes, *lcc, *fcc; -const pcre_uchar *ptr; -const pcre_uchar *end_code, *first_op; - -dfa_recursion_info new_recursive; - -int active_count, new_count, match_count; - -/* Some fields in the md block are frequently referenced, so we load them into -independent variables in the hope that this will perform better. */ - -const pcre_uchar *start_subject = md->start_subject; -const pcre_uchar *end_subject = md->end_subject; -const pcre_uchar *start_code = md->start_code; - -#ifdef SUPPORT_UTF -BOOL utf = (md->poptions & PCRE_UTF8) != 0; -#else -BOOL utf = FALSE; -#endif - -BOOL reset_could_continue = FALSE; - -rlevel++; -offsetcount &= (-2); - -wscount -= 2; -wscount = (wscount - (wscount % (INTS_PER_STATEBLOCK * 2))) / - (2 * INTS_PER_STATEBLOCK); - -DPRINTF(("\n%.*s---------------------\n" - "%.*sCall to internal_dfa_exec f=%d\n", - rlevel*2-2, SP, rlevel*2-2, SP, rlevel)); - -ctypes = md->tables + ctypes_offset; -lcc = md->tables + lcc_offset; -fcc = md->tables + fcc_offset; - -match_count = PCRE_ERROR_NOMATCH; /* A negative number */ - -active_states = (stateblock *)(workspace + 2); -next_new_state = new_states = active_states + wscount; -new_count = 0; - -first_op = this_start_code + 1 + LINK_SIZE + - ((*this_start_code == OP_CBRA || *this_start_code == OP_SCBRA || - *this_start_code == OP_CBRAPOS || *this_start_code == OP_SCBRAPOS) - ? IMM2_SIZE:0); - -/* The first thing in any (sub) pattern is a bracket of some sort. Push all -the alternative states onto the list, and find out where the end is. This -makes is possible to use this function recursively, when we want to stop at a -matching internal ket rather than at the end. - -If the first opcode in the first alternative is OP_REVERSE, we are dealing with -a backward assertion. In that case, we have to find out the maximum amount to -move back, and set up each alternative appropriately. */ - -if (*first_op == OP_REVERSE) - { - int max_back = 0; - int gone_back; - - end_code = this_start_code; - do - { - int back = GET(end_code, 2+LINK_SIZE); - if (back > max_back) max_back = back; - end_code += GET(end_code, 1); - } - while (*end_code == OP_ALT); - - /* If we can't go back the amount required for the longest lookbehind - pattern, go back as far as we can; some alternatives may still be viable. */ - -#ifdef SUPPORT_UTF - /* In character mode we have to step back character by character */ - - if (utf) - { - for (gone_back = 0; gone_back < max_back; gone_back++) - { - if (current_subject <= start_subject) break; - current_subject--; - ACROSSCHAR(current_subject > start_subject, *current_subject, current_subject--); - } - } - else -#endif - - /* In byte-mode we can do this quickly. */ - - { - gone_back = (current_subject - max_back < start_subject)? - (int)(current_subject - start_subject) : max_back; - current_subject -= gone_back; - } - - /* Save the earliest consulted character */ - - if (current_subject < md->start_used_ptr) - md->start_used_ptr = current_subject; - - /* Now we can process the individual branches. */ - - end_code = this_start_code; - do - { - int back = GET(end_code, 2+LINK_SIZE); - if (back <= gone_back) - { - int bstate = (int)(end_code - start_code + 2 + 2*LINK_SIZE); - ADD_NEW_DATA(-bstate, 0, gone_back - back); - } - end_code += GET(end_code, 1); - } - while (*end_code == OP_ALT); - } - -/* This is the code for a "normal" subpattern (not a backward assertion). The -start of a whole pattern is always one of these. If we are at the top level, -we may be asked to restart matching from the same point that we reached for a -previous partial match. We still have to scan through the top-level branches to -find the end state. */ - -else - { - end_code = this_start_code; - - /* Restarting */ - - if (rlevel == 1 && (md->moptions & PCRE_DFA_RESTART) != 0) - { - do { end_code += GET(end_code, 1); } while (*end_code == OP_ALT); - new_count = workspace[1]; - if (!workspace[0]) - memcpy(new_states, active_states, new_count * sizeof(stateblock)); - } - - /* Not restarting */ - - else - { - int length = 1 + LINK_SIZE + - ((*this_start_code == OP_CBRA || *this_start_code == OP_SCBRA || - *this_start_code == OP_CBRAPOS || *this_start_code == OP_SCBRAPOS) - ? IMM2_SIZE:0); - do - { - ADD_NEW((int)(end_code - start_code + length), 0); - end_code += GET(end_code, 1); - length = 1 + LINK_SIZE; - } - while (*end_code == OP_ALT); - } - } - -workspace[0] = 0; /* Bit indicating which vector is current */ - -DPRINTF(("%.*sEnd state = %d\n", rlevel*2-2, SP, (int)(end_code - start_code))); - -/* Loop for scanning the subject */ - -ptr = current_subject; -for (;;) - { - int i, j; - int clen, dlen; - pcre_uint32 c, d; - int forced_fail = 0; - BOOL partial_newline = FALSE; - BOOL could_continue = reset_could_continue; - reset_could_continue = FALSE; - - /* Make the new state list into the active state list and empty the - new state list. */ - - temp_states = active_states; - active_states = new_states; - new_states = temp_states; - active_count = new_count; - new_count = 0; - - workspace[0] ^= 1; /* Remember for the restarting feature */ - workspace[1] = active_count; - -#ifdef PCRE_DEBUG - printf("%.*sNext character: rest of subject = \"", rlevel*2-2, SP); - pchars(ptr, STRLEN_UC(ptr), stdout); - printf("\"\n"); - - printf("%.*sActive states: ", rlevel*2-2, SP); - for (i = 0; i < active_count; i++) - printf("%d/%d ", active_states[i].offset, active_states[i].count); - printf("\n"); -#endif - - /* Set the pointers for adding new states */ - - next_active_state = active_states + active_count; - next_new_state = new_states; - - /* Load the current character from the subject outside the loop, as many - different states may want to look at it, and we assume that at least one - will. */ - - if (ptr < end_subject) - { - clen = 1; /* Number of data items in the character */ -#ifdef SUPPORT_UTF - GETCHARLENTEST(c, ptr, clen); -#else - c = *ptr; -#endif /* SUPPORT_UTF */ - } - else - { - clen = 0; /* This indicates the end of the subject */ - c = NOTACHAR; /* This value should never actually be used */ - } - - /* Scan up the active states and act on each one. The result of an action - may be to add more states to the currently active list (e.g. on hitting a - parenthesis) or it may be to put states on the new list, for considering - when we move the character pointer on. */ - - for (i = 0; i < active_count; i++) - { - stateblock *current_state = active_states + i; - BOOL caseless = FALSE; - const pcre_uchar *code; - int state_offset = current_state->offset; - int codevalue, rrc; - int count; - -#ifdef PCRE_DEBUG - printf ("%.*sProcessing state %d c=", rlevel*2-2, SP, state_offset); - if (clen == 0) printf("EOL\n"); - else if (c > 32 && c < 127) printf("'%c'\n", c); - else printf("0x%02x\n", c); -#endif - - /* A negative offset is a special case meaning "hold off going to this - (negated) state until the number of characters in the data field have - been skipped". If the could_continue flag was passed over from a previous - state, arrange for it to passed on. */ - - if (state_offset < 0) - { - if (current_state->data > 0) - { - DPRINTF(("%.*sSkipping this character\n", rlevel*2-2, SP)); - ADD_NEW_DATA(state_offset, current_state->count, - current_state->data - 1); - if (could_continue) reset_could_continue = TRUE; - continue; - } - else - { - current_state->offset = state_offset = -state_offset; - } - } - - /* Check for a duplicate state with the same count, and skip if found. - See the note at the head of this module about the possibility of improving - performance here. */ - - for (j = 0; j < i; j++) - { - if (active_states[j].offset == state_offset && - active_states[j].count == current_state->count) - { - DPRINTF(("%.*sDuplicate state: skipped\n", rlevel*2-2, SP)); - goto NEXT_ACTIVE_STATE; - } - } - - /* The state offset is the offset to the opcode */ - - code = start_code + state_offset; - codevalue = *code; - - /* If this opcode inspects a character, but we are at the end of the - subject, remember the fact for use when testing for a partial match. */ - - if (clen == 0 && poptable[codevalue] != 0) - could_continue = TRUE; - - /* If this opcode is followed by an inline character, load it. It is - tempting to test for the presence of a subject character here, but that - is wrong, because sometimes zero repetitions of the subject are - permitted. - - We also use this mechanism for opcodes such as OP_TYPEPLUS that take an - argument that is not a data character - but is always one byte long because - the values are small. We have to take special action to deal with \P, \p, - \H, \h, \V, \v and \X in this case. To keep the other cases fast, convert - these ones to new opcodes. */ - - if (coptable[codevalue] > 0) - { - dlen = 1; -#ifdef SUPPORT_UTF - if (utf) { GETCHARLEN(d, (code + coptable[codevalue]), dlen); } else -#endif /* SUPPORT_UTF */ - d = code[coptable[codevalue]]; - if (codevalue >= OP_TYPESTAR) - { - switch(d) - { - case OP_ANYBYTE: return PCRE_ERROR_DFA_UITEM; - case OP_NOTPROP: - case OP_PROP: codevalue += OP_PROP_EXTRA; break; - case OP_ANYNL: codevalue += OP_ANYNL_EXTRA; break; - case OP_EXTUNI: codevalue += OP_EXTUNI_EXTRA; break; - case OP_NOT_HSPACE: - case OP_HSPACE: codevalue += OP_HSPACE_EXTRA; break; - case OP_NOT_VSPACE: - case OP_VSPACE: codevalue += OP_VSPACE_EXTRA; break; - default: break; - } - } - } - else - { - dlen = 0; /* Not strictly necessary, but compilers moan */ - d = NOTACHAR; /* if these variables are not set. */ - } - - - /* Now process the individual opcodes */ - - switch (codevalue) - { -/* ========================================================================== */ - /* These cases are never obeyed. This is a fudge that causes a compile- - time error if the vectors coptable or poptable, which are indexed by - opcode, are not the correct length. It seems to be the only way to do - such a check at compile time, as the sizeof() operator does not work - in the C preprocessor. */ - - case OP_TABLE_LENGTH: - case OP_TABLE_LENGTH + - ((sizeof(coptable) == OP_TABLE_LENGTH) && - (sizeof(poptable) == OP_TABLE_LENGTH)): - break; - -/* ========================================================================== */ - /* Reached a closing bracket. If not at the end of the pattern, carry - on with the next opcode. For repeating opcodes, also add the repeat - state. Note that KETRPOS will always be encountered at the end of the - subpattern, because the possessive subpattern repeats are always handled - using recursive calls. Thus, it never adds any new states. - - At the end of the (sub)pattern, unless we have an empty string and - PCRE_NOTEMPTY is set, or PCRE_NOTEMPTY_ATSTART is set and we are at the - start of the subject, save the match data, shifting up all previous - matches so we always have the longest first. */ - - case OP_KET: - case OP_KETRMIN: - case OP_KETRMAX: - case OP_KETRPOS: - if (code != end_code) - { - ADD_ACTIVE(state_offset + 1 + LINK_SIZE, 0); - if (codevalue != OP_KET) - { - ADD_ACTIVE(state_offset - GET(code, 1), 0); - } - } - else - { - if (ptr > current_subject || - ((md->moptions & PCRE_NOTEMPTY) == 0 && - ((md->moptions & PCRE_NOTEMPTY_ATSTART) == 0 || - current_subject > start_subject + md->start_offset))) - { - if (match_count < 0) match_count = (offsetcount >= 2)? 1 : 0; - else if (match_count > 0 && ++match_count * 2 > offsetcount) - match_count = 0; - count = ((match_count == 0)? offsetcount : match_count * 2) - 2; - if (count > 0) memmove(offsets + 2, offsets, count * sizeof(int)); - if (offsetcount >= 2) - { - offsets[0] = (int)(current_subject - start_subject); - offsets[1] = (int)(ptr - start_subject); - DPRINTF(("%.*sSet matched string = \"%.*s\"\n", rlevel*2-2, SP, - offsets[1] - offsets[0], (char *)current_subject)); - } - if ((md->moptions & PCRE_DFA_SHORTEST) != 0) - { - DPRINTF(("%.*sEnd of internal_dfa_exec %d: returning %d\n" - "%.*s---------------------\n\n", rlevel*2-2, SP, rlevel, - match_count, rlevel*2-2, SP)); - return match_count; - } - } - } - break; - -/* ========================================================================== */ - /* These opcodes add to the current list of states without looking - at the current character. */ - - /*-----------------------------------------------------------------*/ - case OP_ALT: - do { code += GET(code, 1); } while (*code == OP_ALT); - ADD_ACTIVE((int)(code - start_code), 0); - break; - - /*-----------------------------------------------------------------*/ - case OP_BRA: - case OP_SBRA: - do - { - ADD_ACTIVE((int)(code - start_code + 1 + LINK_SIZE), 0); - code += GET(code, 1); - } - while (*code == OP_ALT); - break; - - /*-----------------------------------------------------------------*/ - case OP_CBRA: - case OP_SCBRA: - ADD_ACTIVE((int)(code - start_code + 1 + LINK_SIZE + IMM2_SIZE), 0); - code += GET(code, 1); - while (*code == OP_ALT) - { - ADD_ACTIVE((int)(code - start_code + 1 + LINK_SIZE), 0); - code += GET(code, 1); - } - break; - - /*-----------------------------------------------------------------*/ - case OP_BRAZERO: - case OP_BRAMINZERO: - ADD_ACTIVE(state_offset + 1, 0); - code += 1 + GET(code, 2); - while (*code == OP_ALT) code += GET(code, 1); - ADD_ACTIVE((int)(code - start_code + 1 + LINK_SIZE), 0); - break; - - /*-----------------------------------------------------------------*/ - case OP_SKIPZERO: - code += 1 + GET(code, 2); - while (*code == OP_ALT) code += GET(code, 1); - ADD_ACTIVE((int)(code - start_code + 1 + LINK_SIZE), 0); - break; - - /*-----------------------------------------------------------------*/ - case OP_CIRC: - if (ptr == start_subject && (md->moptions & PCRE_NOTBOL) == 0) - { ADD_ACTIVE(state_offset + 1, 0); } - break; - - /*-----------------------------------------------------------------*/ - case OP_CIRCM: - if ((ptr == start_subject && (md->moptions & PCRE_NOTBOL) == 0) || - (ptr != end_subject && WAS_NEWLINE(ptr))) - { ADD_ACTIVE(state_offset + 1, 0); } - break; - - /*-----------------------------------------------------------------*/ - case OP_EOD: - if (ptr >= end_subject) - { - if ((md->moptions & PCRE_PARTIAL_HARD) != 0) - could_continue = TRUE; - else { ADD_ACTIVE(state_offset + 1, 0); } - } - break; - - /*-----------------------------------------------------------------*/ - case OP_SOD: - if (ptr == start_subject) { ADD_ACTIVE(state_offset + 1, 0); } - break; - - /*-----------------------------------------------------------------*/ - case OP_SOM: - if (ptr == start_subject + start_offset) { ADD_ACTIVE(state_offset + 1, 0); } - break; - - -/* ========================================================================== */ - /* These opcodes inspect the next subject character, and sometimes - the previous one as well, but do not have an argument. The variable - clen contains the length of the current character and is zero if we are - at the end of the subject. */ - - /*-----------------------------------------------------------------*/ - case OP_ANY: - if (clen > 0 && !IS_NEWLINE(ptr)) - { - if (ptr + 1 >= md->end_subject && - (md->moptions & (PCRE_PARTIAL_HARD)) != 0 && - NLBLOCK->nltype == NLTYPE_FIXED && - NLBLOCK->nllen == 2 && - c == NLBLOCK->nl[0]) - { - could_continue = partial_newline = TRUE; - } - else - { - ADD_NEW(state_offset + 1, 0); - } - } - break; - - /*-----------------------------------------------------------------*/ - case OP_ALLANY: - if (clen > 0) - { ADD_NEW(state_offset + 1, 0); } - break; - - /*-----------------------------------------------------------------*/ - case OP_EODN: - if (clen == 0 && (md->moptions & PCRE_PARTIAL_HARD) != 0) - could_continue = TRUE; - else if (clen == 0 || (IS_NEWLINE(ptr) && ptr == end_subject - md->nllen)) - { ADD_ACTIVE(state_offset + 1, 0); } - break; - - /*-----------------------------------------------------------------*/ - case OP_DOLL: - if ((md->moptions & PCRE_NOTEOL) == 0) - { - if (clen == 0 && (md->moptions & PCRE_PARTIAL_HARD) != 0) - could_continue = TRUE; - else if (clen == 0 || - ((md->poptions & PCRE_DOLLAR_ENDONLY) == 0 && IS_NEWLINE(ptr) && - (ptr == end_subject - md->nllen) - )) - { ADD_ACTIVE(state_offset + 1, 0); } - else if (ptr + 1 >= md->end_subject && - (md->moptions & (PCRE_PARTIAL_HARD|PCRE_PARTIAL_SOFT)) != 0 && - NLBLOCK->nltype == NLTYPE_FIXED && - NLBLOCK->nllen == 2 && - c == NLBLOCK->nl[0]) - { - if ((md->moptions & PCRE_PARTIAL_HARD) != 0) - { - reset_could_continue = TRUE; - ADD_NEW_DATA(-(state_offset + 1), 0, 1); - } - else could_continue = partial_newline = TRUE; - } - } - break; - - /*-----------------------------------------------------------------*/ - case OP_DOLLM: - if ((md->moptions & PCRE_NOTEOL) == 0) - { - if (clen == 0 && (md->moptions & PCRE_PARTIAL_HARD) != 0) - could_continue = TRUE; - else if (clen == 0 || - ((md->poptions & PCRE_DOLLAR_ENDONLY) == 0 && IS_NEWLINE(ptr))) - { ADD_ACTIVE(state_offset + 1, 0); } - else if (ptr + 1 >= md->end_subject && - (md->moptions & (PCRE_PARTIAL_HARD|PCRE_PARTIAL_SOFT)) != 0 && - NLBLOCK->nltype == NLTYPE_FIXED && - NLBLOCK->nllen == 2 && - c == NLBLOCK->nl[0]) - { - if ((md->moptions & PCRE_PARTIAL_HARD) != 0) - { - reset_could_continue = TRUE; - ADD_NEW_DATA(-(state_offset + 1), 0, 1); - } - else could_continue = partial_newline = TRUE; - } - } - else if (IS_NEWLINE(ptr)) - { ADD_ACTIVE(state_offset + 1, 0); } - break; - - /*-----------------------------------------------------------------*/ - - case OP_DIGIT: - case OP_WHITESPACE: - case OP_WORDCHAR: - if (clen > 0 && c < 256 && - ((ctypes[c] & toptable1[codevalue]) ^ toptable2[codevalue]) != 0) - { ADD_NEW(state_offset + 1, 0); } - break; - - /*-----------------------------------------------------------------*/ - case OP_NOT_DIGIT: - case OP_NOT_WHITESPACE: - case OP_NOT_WORDCHAR: - if (clen > 0 && (c >= 256 || - ((ctypes[c] & toptable1[codevalue]) ^ toptable2[codevalue]) != 0)) - { ADD_NEW(state_offset + 1, 0); } - break; - - /*-----------------------------------------------------------------*/ - case OP_WORD_BOUNDARY: - case OP_NOT_WORD_BOUNDARY: - { - int left_word, right_word; - - if (ptr > start_subject) - { - const pcre_uchar *temp = ptr - 1; - if (temp < md->start_used_ptr) md->start_used_ptr = temp; -#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 - if (utf) { BACKCHAR(temp); } -#endif - GETCHARTEST(d, temp); -#ifdef SUPPORT_UCP - if ((md->poptions & PCRE_UCP) != 0) - { - if (d == '_') left_word = TRUE; else - { - int cat = UCD_CATEGORY(d); - left_word = (cat == ucp_L || cat == ucp_N); - } - } - else -#endif - left_word = d < 256 && (ctypes[d] & ctype_word) != 0; - } - else left_word = FALSE; - - if (clen > 0) - { -#ifdef SUPPORT_UCP - if ((md->poptions & PCRE_UCP) != 0) - { - if (c == '_') right_word = TRUE; else - { - int cat = UCD_CATEGORY(c); - right_word = (cat == ucp_L || cat == ucp_N); - } - } - else -#endif - right_word = c < 256 && (ctypes[c] & ctype_word) != 0; - } - else right_word = FALSE; - - if ((left_word == right_word) == (codevalue == OP_NOT_WORD_BOUNDARY)) - { ADD_ACTIVE(state_offset + 1, 0); } - } - break; - - - /*-----------------------------------------------------------------*/ - /* Check the next character by Unicode property. We will get here only - if the support is in the binary; otherwise a compile-time error occurs. - */ - -#ifdef SUPPORT_UCP - case OP_PROP: - case OP_NOTPROP: - if (clen > 0) - { - BOOL OK; - const pcre_uint32 *cp; - const ucd_record * prop = GET_UCD(c); - switch(code[1]) - { - case PT_ANY: - OK = TRUE; - break; - - case PT_LAMP: - OK = prop->chartype == ucp_Lu || prop->chartype == ucp_Ll || - prop->chartype == ucp_Lt; - break; - - case PT_GC: - OK = PRIV(ucp_gentype)[prop->chartype] == code[2]; - break; - - case PT_PC: - OK = prop->chartype == code[2]; - break; - - case PT_SC: - OK = prop->script == code[2]; - break; - - /* These are specials for combination cases. */ - - case PT_ALNUM: - OK = PRIV(ucp_gentype)[prop->chartype] == ucp_L || - PRIV(ucp_gentype)[prop->chartype] == ucp_N; - break; - - /* Perl space used to exclude VT, but from Perl 5.18 it is included, - which means that Perl space and POSIX space are now identical. PCRE - was changed at release 8.34. */ - - case PT_SPACE: /* Perl space */ - case PT_PXSPACE: /* POSIX space */ - switch(c) - { - HSPACE_CASES: - VSPACE_CASES: - OK = TRUE; - break; - - default: - OK = PRIV(ucp_gentype)[prop->chartype] == ucp_Z; - break; - } - break; - - case PT_WORD: - OK = PRIV(ucp_gentype)[prop->chartype] == ucp_L || - PRIV(ucp_gentype)[prop->chartype] == ucp_N || - c == CHAR_UNDERSCORE; - break; - - case PT_CLIST: - cp = PRIV(ucd_caseless_sets) + code[2]; - for (;;) - { - if (c < *cp) { OK = FALSE; break; } - if (c == *cp++) { OK = TRUE; break; } - } - break; - - case PT_UCNC: - OK = c == CHAR_DOLLAR_SIGN || c == CHAR_COMMERCIAL_AT || - c == CHAR_GRAVE_ACCENT || (c >= 0xa0 && c <= 0xd7ff) || - c >= 0xe000; - break; - - /* Should never occur, but keep compilers from grumbling. */ - - default: - OK = codevalue != OP_PROP; - break; - } - - if (OK == (codevalue == OP_PROP)) { ADD_NEW(state_offset + 3, 0); } - } - break; -#endif - - - -/* ========================================================================== */ - /* These opcodes likewise inspect the subject character, but have an - argument that is not a data character. It is one of these opcodes: - OP_ANY, OP_ALLANY, OP_DIGIT, OP_NOT_DIGIT, OP_WHITESPACE, OP_NOT_SPACE, - OP_WORDCHAR, OP_NOT_WORDCHAR. The value is loaded into d. */ - - case OP_TYPEPLUS: - case OP_TYPEMINPLUS: - case OP_TYPEPOSPLUS: - count = current_state->count; /* Already matched */ - if (count > 0) { ADD_ACTIVE(state_offset + 2, 0); } - if (clen > 0) - { - if (d == OP_ANY && ptr + 1 >= md->end_subject && - (md->moptions & (PCRE_PARTIAL_HARD)) != 0 && - NLBLOCK->nltype == NLTYPE_FIXED && - NLBLOCK->nllen == 2 && - c == NLBLOCK->nl[0]) - { - could_continue = partial_newline = TRUE; - } - else if ((c >= 256 && d != OP_DIGIT && d != OP_WHITESPACE && d != OP_WORDCHAR) || - (c < 256 && - (d != OP_ANY || !IS_NEWLINE(ptr)) && - ((ctypes[c] & toptable1[d]) ^ toptable2[d]) != 0)) - { - if (count > 0 && codevalue == OP_TYPEPOSPLUS) - { - active_count--; /* Remove non-match possibility */ - next_active_state--; - } - count++; - ADD_NEW(state_offset, count); - } - } - break; - - /*-----------------------------------------------------------------*/ - case OP_TYPEQUERY: - case OP_TYPEMINQUERY: - case OP_TYPEPOSQUERY: - ADD_ACTIVE(state_offset + 2, 0); - if (clen > 0) - { - if (d == OP_ANY && ptr + 1 >= md->end_subject && - (md->moptions & (PCRE_PARTIAL_HARD)) != 0 && - NLBLOCK->nltype == NLTYPE_FIXED && - NLBLOCK->nllen == 2 && - c == NLBLOCK->nl[0]) - { - could_continue = partial_newline = TRUE; - } - else if ((c >= 256 && d != OP_DIGIT && d != OP_WHITESPACE && d != OP_WORDCHAR) || - (c < 256 && - (d != OP_ANY || !IS_NEWLINE(ptr)) && - ((ctypes[c] & toptable1[d]) ^ toptable2[d]) != 0)) - { - if (codevalue == OP_TYPEPOSQUERY) - { - active_count--; /* Remove non-match possibility */ - next_active_state--; - } - ADD_NEW(state_offset + 2, 0); - } - } - break; - - /*-----------------------------------------------------------------*/ - case OP_TYPESTAR: - case OP_TYPEMINSTAR: - case OP_TYPEPOSSTAR: - ADD_ACTIVE(state_offset + 2, 0); - if (clen > 0) - { - if (d == OP_ANY && ptr + 1 >= md->end_subject && - (md->moptions & (PCRE_PARTIAL_HARD)) != 0 && - NLBLOCK->nltype == NLTYPE_FIXED && - NLBLOCK->nllen == 2 && - c == NLBLOCK->nl[0]) - { - could_continue = partial_newline = TRUE; - } - else if ((c >= 256 && d != OP_DIGIT && d != OP_WHITESPACE && d != OP_WORDCHAR) || - (c < 256 && - (d != OP_ANY || !IS_NEWLINE(ptr)) && - ((ctypes[c] & toptable1[d]) ^ toptable2[d]) != 0)) - { - if (codevalue == OP_TYPEPOSSTAR) - { - active_count--; /* Remove non-match possibility */ - next_active_state--; - } - ADD_NEW(state_offset, 0); - } - } - break; - - /*-----------------------------------------------------------------*/ - case OP_TYPEEXACT: - count = current_state->count; /* Number already matched */ - if (clen > 0) - { - if (d == OP_ANY && ptr + 1 >= md->end_subject && - (md->moptions & (PCRE_PARTIAL_HARD)) != 0 && - NLBLOCK->nltype == NLTYPE_FIXED && - NLBLOCK->nllen == 2 && - c == NLBLOCK->nl[0]) - { - could_continue = partial_newline = TRUE; - } - else if ((c >= 256 && d != OP_DIGIT && d != OP_WHITESPACE && d != OP_WORDCHAR) || - (c < 256 && - (d != OP_ANY || !IS_NEWLINE(ptr)) && - ((ctypes[c] & toptable1[d]) ^ toptable2[d]) != 0)) - { - if (++count >= (int)GET2(code, 1)) - { ADD_NEW(state_offset + 1 + IMM2_SIZE + 1, 0); } - else - { ADD_NEW(state_offset, count); } - } - } - break; - - /*-----------------------------------------------------------------*/ - case OP_TYPEUPTO: - case OP_TYPEMINUPTO: - case OP_TYPEPOSUPTO: - ADD_ACTIVE(state_offset + 2 + IMM2_SIZE, 0); - count = current_state->count; /* Number already matched */ - if (clen > 0) - { - if (d == OP_ANY && ptr + 1 >= md->end_subject && - (md->moptions & (PCRE_PARTIAL_HARD)) != 0 && - NLBLOCK->nltype == NLTYPE_FIXED && - NLBLOCK->nllen == 2 && - c == NLBLOCK->nl[0]) - { - could_continue = partial_newline = TRUE; - } - else if ((c >= 256 && d != OP_DIGIT && d != OP_WHITESPACE && d != OP_WORDCHAR) || - (c < 256 && - (d != OP_ANY || !IS_NEWLINE(ptr)) && - ((ctypes[c] & toptable1[d]) ^ toptable2[d]) != 0)) - { - if (codevalue == OP_TYPEPOSUPTO) - { - active_count--; /* Remove non-match possibility */ - next_active_state--; - } - if (++count >= (int)GET2(code, 1)) - { ADD_NEW(state_offset + 2 + IMM2_SIZE, 0); } - else - { ADD_NEW(state_offset, count); } - } - } - break; - -/* ========================================================================== */ - /* These are virtual opcodes that are used when something like - OP_TYPEPLUS has OP_PROP, OP_NOTPROP, OP_ANYNL, or OP_EXTUNI as its - argument. It keeps the code above fast for the other cases. The argument - is in the d variable. */ - -#ifdef SUPPORT_UCP - case OP_PROP_EXTRA + OP_TYPEPLUS: - case OP_PROP_EXTRA + OP_TYPEMINPLUS: - case OP_PROP_EXTRA + OP_TYPEPOSPLUS: - count = current_state->count; /* Already matched */ - if (count > 0) { ADD_ACTIVE(state_offset + 4, 0); } - if (clen > 0) - { - BOOL OK; - const pcre_uint32 *cp; - const ucd_record * prop = GET_UCD(c); - switch(code[2]) - { - case PT_ANY: - OK = TRUE; - break; - - case PT_LAMP: - OK = prop->chartype == ucp_Lu || prop->chartype == ucp_Ll || - prop->chartype == ucp_Lt; - break; - - case PT_GC: - OK = PRIV(ucp_gentype)[prop->chartype] == code[3]; - break; - - case PT_PC: - OK = prop->chartype == code[3]; - break; - - case PT_SC: - OK = prop->script == code[3]; - break; - - /* These are specials for combination cases. */ - - case PT_ALNUM: - OK = PRIV(ucp_gentype)[prop->chartype] == ucp_L || - PRIV(ucp_gentype)[prop->chartype] == ucp_N; - break; - - /* Perl space used to exclude VT, but from Perl 5.18 it is included, - which means that Perl space and POSIX space are now identical. PCRE - was changed at release 8.34. */ - - case PT_SPACE: /* Perl space */ - case PT_PXSPACE: /* POSIX space */ - switch(c) - { - HSPACE_CASES: - VSPACE_CASES: - OK = TRUE; - break; - - default: - OK = PRIV(ucp_gentype)[prop->chartype] == ucp_Z; - break; - } - break; - - case PT_WORD: - OK = PRIV(ucp_gentype)[prop->chartype] == ucp_L || - PRIV(ucp_gentype)[prop->chartype] == ucp_N || - c == CHAR_UNDERSCORE; - break; - - case PT_CLIST: - cp = PRIV(ucd_caseless_sets) + code[3]; - for (;;) - { - if (c < *cp) { OK = FALSE; break; } - if (c == *cp++) { OK = TRUE; break; } - } - break; - - case PT_UCNC: - OK = c == CHAR_DOLLAR_SIGN || c == CHAR_COMMERCIAL_AT || - c == CHAR_GRAVE_ACCENT || (c >= 0xa0 && c <= 0xd7ff) || - c >= 0xe000; - break; - - /* Should never occur, but keep compilers from grumbling. */ - - default: - OK = codevalue != OP_PROP; - break; - } - - if (OK == (d == OP_PROP)) - { - if (count > 0 && codevalue == OP_PROP_EXTRA + OP_TYPEPOSPLUS) - { - active_count--; /* Remove non-match possibility */ - next_active_state--; - } - count++; - ADD_NEW(state_offset, count); - } - } - break; - - /*-----------------------------------------------------------------*/ - case OP_EXTUNI_EXTRA + OP_TYPEPLUS: - case OP_EXTUNI_EXTRA + OP_TYPEMINPLUS: - case OP_EXTUNI_EXTRA + OP_TYPEPOSPLUS: - count = current_state->count; /* Already matched */ - if (count > 0) { ADD_ACTIVE(state_offset + 2, 0); } - if (clen > 0) - { - int lgb, rgb; - const pcre_uchar *nptr = ptr + clen; - int ncount = 0; - if (count > 0 && codevalue == OP_EXTUNI_EXTRA + OP_TYPEPOSPLUS) - { - active_count--; /* Remove non-match possibility */ - next_active_state--; - } - lgb = UCD_GRAPHBREAK(c); - while (nptr < end_subject) - { - dlen = 1; - if (!utf) d = *nptr; else { GETCHARLEN(d, nptr, dlen); } - rgb = UCD_GRAPHBREAK(d); - if ((PRIV(ucp_gbtable)[lgb] & (1 << rgb)) == 0) break; - ncount++; - lgb = rgb; - nptr += dlen; - } - count++; - ADD_NEW_DATA(-state_offset, count, ncount); - } - break; -#endif - - /*-----------------------------------------------------------------*/ - case OP_ANYNL_EXTRA + OP_TYPEPLUS: - case OP_ANYNL_EXTRA + OP_TYPEMINPLUS: - case OP_ANYNL_EXTRA + OP_TYPEPOSPLUS: - count = current_state->count; /* Already matched */ - if (count > 0) { ADD_ACTIVE(state_offset + 2, 0); } - if (clen > 0) - { - int ncount = 0; - switch (c) - { - case CHAR_VT: - case CHAR_FF: - case CHAR_NEL: -#ifndef EBCDIC - case 0x2028: - case 0x2029: -#endif /* Not EBCDIC */ - if ((md->moptions & PCRE_BSR_ANYCRLF) != 0) break; - goto ANYNL01; - - case CHAR_CR: - if (ptr + 1 < end_subject && UCHAR21TEST(ptr + 1) == CHAR_LF) ncount = 1; - /* Fall through */ - - ANYNL01: - case CHAR_LF: - if (count > 0 && codevalue == OP_ANYNL_EXTRA + OP_TYPEPOSPLUS) - { - active_count--; /* Remove non-match possibility */ - next_active_state--; - } - count++; - ADD_NEW_DATA(-state_offset, count, ncount); - break; - - default: - break; - } - } - break; - - /*-----------------------------------------------------------------*/ - case OP_VSPACE_EXTRA + OP_TYPEPLUS: - case OP_VSPACE_EXTRA + OP_TYPEMINPLUS: - case OP_VSPACE_EXTRA + OP_TYPEPOSPLUS: - count = current_state->count; /* Already matched */ - if (count > 0) { ADD_ACTIVE(state_offset + 2, 0); } - if (clen > 0) - { - BOOL OK; - switch (c) - { - VSPACE_CASES: - OK = TRUE; - break; - - default: - OK = FALSE; - break; - } - - if (OK == (d == OP_VSPACE)) - { - if (count > 0 && codevalue == OP_VSPACE_EXTRA + OP_TYPEPOSPLUS) - { - active_count--; /* Remove non-match possibility */ - next_active_state--; - } - count++; - ADD_NEW_DATA(-state_offset, count, 0); - } - } - break; - - /*-----------------------------------------------------------------*/ - case OP_HSPACE_EXTRA + OP_TYPEPLUS: - case OP_HSPACE_EXTRA + OP_TYPEMINPLUS: - case OP_HSPACE_EXTRA + OP_TYPEPOSPLUS: - count = current_state->count; /* Already matched */ - if (count > 0) { ADD_ACTIVE(state_offset + 2, 0); } - if (clen > 0) - { - BOOL OK; - switch (c) - { - HSPACE_CASES: - OK = TRUE; - break; - - default: - OK = FALSE; - break; - } - - if (OK == (d == OP_HSPACE)) - { - if (count > 0 && codevalue == OP_HSPACE_EXTRA + OP_TYPEPOSPLUS) - { - active_count--; /* Remove non-match possibility */ - next_active_state--; - } - count++; - ADD_NEW_DATA(-state_offset, count, 0); - } - } - break; - - /*-----------------------------------------------------------------*/ -#ifdef SUPPORT_UCP - case OP_PROP_EXTRA + OP_TYPEQUERY: - case OP_PROP_EXTRA + OP_TYPEMINQUERY: - case OP_PROP_EXTRA + OP_TYPEPOSQUERY: - count = 4; - goto QS1; - - case OP_PROP_EXTRA + OP_TYPESTAR: - case OP_PROP_EXTRA + OP_TYPEMINSTAR: - case OP_PROP_EXTRA + OP_TYPEPOSSTAR: - count = 0; - - QS1: - - ADD_ACTIVE(state_offset + 4, 0); - if (clen > 0) - { - BOOL OK; - const pcre_uint32 *cp; - const ucd_record * prop = GET_UCD(c); - switch(code[2]) - { - case PT_ANY: - OK = TRUE; - break; - - case PT_LAMP: - OK = prop->chartype == ucp_Lu || prop->chartype == ucp_Ll || - prop->chartype == ucp_Lt; - break; - - case PT_GC: - OK = PRIV(ucp_gentype)[prop->chartype] == code[3]; - break; - - case PT_PC: - OK = prop->chartype == code[3]; - break; - - case PT_SC: - OK = prop->script == code[3]; - break; - - /* These are specials for combination cases. */ - - case PT_ALNUM: - OK = PRIV(ucp_gentype)[prop->chartype] == ucp_L || - PRIV(ucp_gentype)[prop->chartype] == ucp_N; - break; - - /* Perl space used to exclude VT, but from Perl 5.18 it is included, - which means that Perl space and POSIX space are now identical. PCRE - was changed at release 8.34. */ - - case PT_SPACE: /* Perl space */ - case PT_PXSPACE: /* POSIX space */ - switch(c) - { - HSPACE_CASES: - VSPACE_CASES: - OK = TRUE; - break; - - default: - OK = PRIV(ucp_gentype)[prop->chartype] == ucp_Z; - break; - } - break; - - case PT_WORD: - OK = PRIV(ucp_gentype)[prop->chartype] == ucp_L || - PRIV(ucp_gentype)[prop->chartype] == ucp_N || - c == CHAR_UNDERSCORE; - break; - - case PT_CLIST: - cp = PRIV(ucd_caseless_sets) + code[3]; - for (;;) - { - if (c < *cp) { OK = FALSE; break; } - if (c == *cp++) { OK = TRUE; break; } - } - break; - - case PT_UCNC: - OK = c == CHAR_DOLLAR_SIGN || c == CHAR_COMMERCIAL_AT || - c == CHAR_GRAVE_ACCENT || (c >= 0xa0 && c <= 0xd7ff) || - c >= 0xe000; - break; - - /* Should never occur, but keep compilers from grumbling. */ - - default: - OK = codevalue != OP_PROP; - break; - } - - if (OK == (d == OP_PROP)) - { - if (codevalue == OP_PROP_EXTRA + OP_TYPEPOSSTAR || - codevalue == OP_PROP_EXTRA + OP_TYPEPOSQUERY) - { - active_count--; /* Remove non-match possibility */ - next_active_state--; - } - ADD_NEW(state_offset + count, 0); - } - } - break; - - /*-----------------------------------------------------------------*/ - case OP_EXTUNI_EXTRA + OP_TYPEQUERY: - case OP_EXTUNI_EXTRA + OP_TYPEMINQUERY: - case OP_EXTUNI_EXTRA + OP_TYPEPOSQUERY: - count = 2; - goto QS2; - - case OP_EXTUNI_EXTRA + OP_TYPESTAR: - case OP_EXTUNI_EXTRA + OP_TYPEMINSTAR: - case OP_EXTUNI_EXTRA + OP_TYPEPOSSTAR: - count = 0; - - QS2: - - ADD_ACTIVE(state_offset + 2, 0); - if (clen > 0) - { - int lgb, rgb; - const pcre_uchar *nptr = ptr + clen; - int ncount = 0; - if (codevalue == OP_EXTUNI_EXTRA + OP_TYPEPOSSTAR || - codevalue == OP_EXTUNI_EXTRA + OP_TYPEPOSQUERY) - { - active_count--; /* Remove non-match possibility */ - next_active_state--; - } - lgb = UCD_GRAPHBREAK(c); - while (nptr < end_subject) - { - dlen = 1; - if (!utf) d = *nptr; else { GETCHARLEN(d, nptr, dlen); } - rgb = UCD_GRAPHBREAK(d); - if ((PRIV(ucp_gbtable)[lgb] & (1 << rgb)) == 0) break; - ncount++; - lgb = rgb; - nptr += dlen; - } - ADD_NEW_DATA(-(state_offset + count), 0, ncount); - } - break; -#endif - - /*-----------------------------------------------------------------*/ - case OP_ANYNL_EXTRA + OP_TYPEQUERY: - case OP_ANYNL_EXTRA + OP_TYPEMINQUERY: - case OP_ANYNL_EXTRA + OP_TYPEPOSQUERY: - count = 2; - goto QS3; - - case OP_ANYNL_EXTRA + OP_TYPESTAR: - case OP_ANYNL_EXTRA + OP_TYPEMINSTAR: - case OP_ANYNL_EXTRA + OP_TYPEPOSSTAR: - count = 0; - - QS3: - ADD_ACTIVE(state_offset + 2, 0); - if (clen > 0) - { - int ncount = 0; - switch (c) - { - case CHAR_VT: - case CHAR_FF: - case CHAR_NEL: -#ifndef EBCDIC - case 0x2028: - case 0x2029: -#endif /* Not EBCDIC */ - if ((md->moptions & PCRE_BSR_ANYCRLF) != 0) break; - goto ANYNL02; - - case CHAR_CR: - if (ptr + 1 < end_subject && UCHAR21TEST(ptr + 1) == CHAR_LF) ncount = 1; - /* Fall through */ - - ANYNL02: - case CHAR_LF: - if (codevalue == OP_ANYNL_EXTRA + OP_TYPEPOSSTAR || - codevalue == OP_ANYNL_EXTRA + OP_TYPEPOSQUERY) - { - active_count--; /* Remove non-match possibility */ - next_active_state--; - } - ADD_NEW_DATA(-(state_offset + (int)count), 0, ncount); - break; - - default: - break; - } - } - break; - - /*-----------------------------------------------------------------*/ - case OP_VSPACE_EXTRA + OP_TYPEQUERY: - case OP_VSPACE_EXTRA + OP_TYPEMINQUERY: - case OP_VSPACE_EXTRA + OP_TYPEPOSQUERY: - count = 2; - goto QS4; - - case OP_VSPACE_EXTRA + OP_TYPESTAR: - case OP_VSPACE_EXTRA + OP_TYPEMINSTAR: - case OP_VSPACE_EXTRA + OP_TYPEPOSSTAR: - count = 0; - - QS4: - ADD_ACTIVE(state_offset + 2, 0); - if (clen > 0) - { - BOOL OK; - switch (c) - { - VSPACE_CASES: - OK = TRUE; - break; - - default: - OK = FALSE; - break; - } - if (OK == (d == OP_VSPACE)) - { - if (codevalue == OP_VSPACE_EXTRA + OP_TYPEPOSSTAR || - codevalue == OP_VSPACE_EXTRA + OP_TYPEPOSQUERY) - { - active_count--; /* Remove non-match possibility */ - next_active_state--; - } - ADD_NEW_DATA(-(state_offset + (int)count), 0, 0); - } - } - break; - - /*-----------------------------------------------------------------*/ - case OP_HSPACE_EXTRA + OP_TYPEQUERY: - case OP_HSPACE_EXTRA + OP_TYPEMINQUERY: - case OP_HSPACE_EXTRA + OP_TYPEPOSQUERY: - count = 2; - goto QS5; - - case OP_HSPACE_EXTRA + OP_TYPESTAR: - case OP_HSPACE_EXTRA + OP_TYPEMINSTAR: - case OP_HSPACE_EXTRA + OP_TYPEPOSSTAR: - count = 0; - - QS5: - ADD_ACTIVE(state_offset + 2, 0); - if (clen > 0) - { - BOOL OK; - switch (c) - { - HSPACE_CASES: - OK = TRUE; - break; - - default: - OK = FALSE; - break; - } - - if (OK == (d == OP_HSPACE)) - { - if (codevalue == OP_HSPACE_EXTRA + OP_TYPEPOSSTAR || - codevalue == OP_HSPACE_EXTRA + OP_TYPEPOSQUERY) - { - active_count--; /* Remove non-match possibility */ - next_active_state--; - } - ADD_NEW_DATA(-(state_offset + (int)count), 0, 0); - } - } - break; - - /*-----------------------------------------------------------------*/ -#ifdef SUPPORT_UCP - case OP_PROP_EXTRA + OP_TYPEEXACT: - case OP_PROP_EXTRA + OP_TYPEUPTO: - case OP_PROP_EXTRA + OP_TYPEMINUPTO: - case OP_PROP_EXTRA + OP_TYPEPOSUPTO: - if (codevalue != OP_PROP_EXTRA + OP_TYPEEXACT) - { ADD_ACTIVE(state_offset + 1 + IMM2_SIZE + 3, 0); } - count = current_state->count; /* Number already matched */ - if (clen > 0) - { - BOOL OK; - const pcre_uint32 *cp; - const ucd_record * prop = GET_UCD(c); - switch(code[1 + IMM2_SIZE + 1]) - { - case PT_ANY: - OK = TRUE; - break; - - case PT_LAMP: - OK = prop->chartype == ucp_Lu || prop->chartype == ucp_Ll || - prop->chartype == ucp_Lt; - break; - - case PT_GC: - OK = PRIV(ucp_gentype)[prop->chartype] == code[1 + IMM2_SIZE + 2]; - break; - - case PT_PC: - OK = prop->chartype == code[1 + IMM2_SIZE + 2]; - break; - - case PT_SC: - OK = prop->script == code[1 + IMM2_SIZE + 2]; - break; - - /* These are specials for combination cases. */ - - case PT_ALNUM: - OK = PRIV(ucp_gentype)[prop->chartype] == ucp_L || - PRIV(ucp_gentype)[prop->chartype] == ucp_N; - break; - - /* Perl space used to exclude VT, but from Perl 5.18 it is included, - which means that Perl space and POSIX space are now identical. PCRE - was changed at release 8.34. */ - - case PT_SPACE: /* Perl space */ - case PT_PXSPACE: /* POSIX space */ - switch(c) - { - HSPACE_CASES: - VSPACE_CASES: - OK = TRUE; - break; - - default: - OK = PRIV(ucp_gentype)[prop->chartype] == ucp_Z; - break; - } - break; - - case PT_WORD: - OK = PRIV(ucp_gentype)[prop->chartype] == ucp_L || - PRIV(ucp_gentype)[prop->chartype] == ucp_N || - c == CHAR_UNDERSCORE; - break; - - case PT_CLIST: - cp = PRIV(ucd_caseless_sets) + code[1 + IMM2_SIZE + 2]; - for (;;) - { - if (c < *cp) { OK = FALSE; break; } - if (c == *cp++) { OK = TRUE; break; } - } - break; - - case PT_UCNC: - OK = c == CHAR_DOLLAR_SIGN || c == CHAR_COMMERCIAL_AT || - c == CHAR_GRAVE_ACCENT || (c >= 0xa0 && c <= 0xd7ff) || - c >= 0xe000; - break; - - /* Should never occur, but keep compilers from grumbling. */ - - default: - OK = codevalue != OP_PROP; - break; - } - - if (OK == (d == OP_PROP)) - { - if (codevalue == OP_PROP_EXTRA + OP_TYPEPOSUPTO) - { - active_count--; /* Remove non-match possibility */ - next_active_state--; - } - if (++count >= (int)GET2(code, 1)) - { ADD_NEW(state_offset + 1 + IMM2_SIZE + 3, 0); } - else - { ADD_NEW(state_offset, count); } - } - } - break; - - /*-----------------------------------------------------------------*/ - case OP_EXTUNI_EXTRA + OP_TYPEEXACT: - case OP_EXTUNI_EXTRA + OP_TYPEUPTO: - case OP_EXTUNI_EXTRA + OP_TYPEMINUPTO: - case OP_EXTUNI_EXTRA + OP_TYPEPOSUPTO: - if (codevalue != OP_EXTUNI_EXTRA + OP_TYPEEXACT) - { ADD_ACTIVE(state_offset + 2 + IMM2_SIZE, 0); } - count = current_state->count; /* Number already matched */ - if (clen > 0) - { - int lgb, rgb; - const pcre_uchar *nptr = ptr + clen; - int ncount = 0; - if (codevalue == OP_EXTUNI_EXTRA + OP_TYPEPOSUPTO) - { - active_count--; /* Remove non-match possibility */ - next_active_state--; - } - lgb = UCD_GRAPHBREAK(c); - while (nptr < end_subject) - { - dlen = 1; - if (!utf) d = *nptr; else { GETCHARLEN(d, nptr, dlen); } - rgb = UCD_GRAPHBREAK(d); - if ((PRIV(ucp_gbtable)[lgb] & (1 << rgb)) == 0) break; - ncount++; - lgb = rgb; - nptr += dlen; - } - if (nptr >= end_subject && (md->moptions & PCRE_PARTIAL_HARD) != 0) - reset_could_continue = TRUE; - if (++count >= (int)GET2(code, 1)) - { ADD_NEW_DATA(-(state_offset + 2 + IMM2_SIZE), 0, ncount); } - else - { ADD_NEW_DATA(-state_offset, count, ncount); } - } - break; -#endif - - /*-----------------------------------------------------------------*/ - case OP_ANYNL_EXTRA + OP_TYPEEXACT: - case OP_ANYNL_EXTRA + OP_TYPEUPTO: - case OP_ANYNL_EXTRA + OP_TYPEMINUPTO: - case OP_ANYNL_EXTRA + OP_TYPEPOSUPTO: - if (codevalue != OP_ANYNL_EXTRA + OP_TYPEEXACT) - { ADD_ACTIVE(state_offset + 2 + IMM2_SIZE, 0); } - count = current_state->count; /* Number already matched */ - if (clen > 0) - { - int ncount = 0; - switch (c) - { - case CHAR_VT: - case CHAR_FF: - case CHAR_NEL: -#ifndef EBCDIC - case 0x2028: - case 0x2029: -#endif /* Not EBCDIC */ - if ((md->moptions & PCRE_BSR_ANYCRLF) != 0) break; - goto ANYNL03; - - case CHAR_CR: - if (ptr + 1 < end_subject && UCHAR21TEST(ptr + 1) == CHAR_LF) ncount = 1; - /* Fall through */ - - ANYNL03: - case CHAR_LF: - if (codevalue == OP_ANYNL_EXTRA + OP_TYPEPOSUPTO) - { - active_count--; /* Remove non-match possibility */ - next_active_state--; - } - if (++count >= (int)GET2(code, 1)) - { ADD_NEW_DATA(-(state_offset + 2 + IMM2_SIZE), 0, ncount); } - else - { ADD_NEW_DATA(-state_offset, count, ncount); } - break; - - default: - break; - } - } - break; - - /*-----------------------------------------------------------------*/ - case OP_VSPACE_EXTRA + OP_TYPEEXACT: - case OP_VSPACE_EXTRA + OP_TYPEUPTO: - case OP_VSPACE_EXTRA + OP_TYPEMINUPTO: - case OP_VSPACE_EXTRA + OP_TYPEPOSUPTO: - if (codevalue != OP_VSPACE_EXTRA + OP_TYPEEXACT) - { ADD_ACTIVE(state_offset + 2 + IMM2_SIZE, 0); } - count = current_state->count; /* Number already matched */ - if (clen > 0) - { - BOOL OK; - switch (c) - { - VSPACE_CASES: - OK = TRUE; - break; - - default: - OK = FALSE; - } - - if (OK == (d == OP_VSPACE)) - { - if (codevalue == OP_VSPACE_EXTRA + OP_TYPEPOSUPTO) - { - active_count--; /* Remove non-match possibility */ - next_active_state--; - } - if (++count >= (int)GET2(code, 1)) - { ADD_NEW_DATA(-(state_offset + 2 + IMM2_SIZE), 0, 0); } - else - { ADD_NEW_DATA(-state_offset, count, 0); } - } - } - break; - - /*-----------------------------------------------------------------*/ - case OP_HSPACE_EXTRA + OP_TYPEEXACT: - case OP_HSPACE_EXTRA + OP_TYPEUPTO: - case OP_HSPACE_EXTRA + OP_TYPEMINUPTO: - case OP_HSPACE_EXTRA + OP_TYPEPOSUPTO: - if (codevalue != OP_HSPACE_EXTRA + OP_TYPEEXACT) - { ADD_ACTIVE(state_offset + 2 + IMM2_SIZE, 0); } - count = current_state->count; /* Number already matched */ - if (clen > 0) - { - BOOL OK; - switch (c) - { - HSPACE_CASES: - OK = TRUE; - break; - - default: - OK = FALSE; - break; - } - - if (OK == (d == OP_HSPACE)) - { - if (codevalue == OP_HSPACE_EXTRA + OP_TYPEPOSUPTO) - { - active_count--; /* Remove non-match possibility */ - next_active_state--; - } - if (++count >= (int)GET2(code, 1)) - { ADD_NEW_DATA(-(state_offset + 2 + IMM2_SIZE), 0, 0); } - else - { ADD_NEW_DATA(-state_offset, count, 0); } - } - } - break; - -/* ========================================================================== */ - /* These opcodes are followed by a character that is usually compared - to the current subject character; it is loaded into d. We still get - here even if there is no subject character, because in some cases zero - repetitions are permitted. */ - - /*-----------------------------------------------------------------*/ - case OP_CHAR: - if (clen > 0 && c == d) { ADD_NEW(state_offset + dlen + 1, 0); } - break; - - /*-----------------------------------------------------------------*/ - case OP_CHARI: - if (clen == 0) break; - -#ifdef SUPPORT_UTF - if (utf) - { - if (c == d) { ADD_NEW(state_offset + dlen + 1, 0); } else - { - unsigned int othercase; - if (c < 128) - othercase = fcc[c]; - else - /* If we have Unicode property support, we can use it to test the - other case of the character. */ -#ifdef SUPPORT_UCP - othercase = UCD_OTHERCASE(c); -#else - othercase = NOTACHAR; -#endif - - if (d == othercase) { ADD_NEW(state_offset + dlen + 1, 0); } - } - } - else -#endif /* SUPPORT_UTF */ - /* Not UTF mode */ - { - if (TABLE_GET(c, lcc, c) == TABLE_GET(d, lcc, d)) - { ADD_NEW(state_offset + 2, 0); } - } - break; - - -#ifdef SUPPORT_UCP - /*-----------------------------------------------------------------*/ - /* This is a tricky one because it can match more than one character. - Find out how many characters to skip, and then set up a negative state - to wait for them to pass before continuing. */ - - case OP_EXTUNI: - if (clen > 0) - { - int lgb, rgb; - const pcre_uchar *nptr = ptr + clen; - int ncount = 0; - lgb = UCD_GRAPHBREAK(c); - while (nptr < end_subject) - { - dlen = 1; - if (!utf) d = *nptr; else { GETCHARLEN(d, nptr, dlen); } - rgb = UCD_GRAPHBREAK(d); - if ((PRIV(ucp_gbtable)[lgb] & (1 << rgb)) == 0) break; - ncount++; - lgb = rgb; - nptr += dlen; - } - if (nptr >= end_subject && (md->moptions & PCRE_PARTIAL_HARD) != 0) - reset_could_continue = TRUE; - ADD_NEW_DATA(-(state_offset + 1), 0, ncount); - } - break; -#endif - - /*-----------------------------------------------------------------*/ - /* This is a tricky like EXTUNI because it too can match more than one - character (when CR is followed by LF). In this case, set up a negative - state to wait for one character to pass before continuing. */ - - case OP_ANYNL: - if (clen > 0) switch(c) - { - case CHAR_VT: - case CHAR_FF: - case CHAR_NEL: -#ifndef EBCDIC - case 0x2028: - case 0x2029: -#endif /* Not EBCDIC */ - if ((md->moptions & PCRE_BSR_ANYCRLF) != 0) break; - - case CHAR_LF: - ADD_NEW(state_offset + 1, 0); - break; - - case CHAR_CR: - if (ptr + 1 >= end_subject) - { - ADD_NEW(state_offset + 1, 0); - if ((md->moptions & PCRE_PARTIAL_HARD) != 0) - reset_could_continue = TRUE; - } - else if (UCHAR21TEST(ptr + 1) == CHAR_LF) - { - ADD_NEW_DATA(-(state_offset + 1), 0, 1); - } - else - { - ADD_NEW(state_offset + 1, 0); - } - break; - } - break; - - /*-----------------------------------------------------------------*/ - case OP_NOT_VSPACE: - if (clen > 0) switch(c) - { - VSPACE_CASES: - break; - - default: - ADD_NEW(state_offset + 1, 0); - break; - } - break; - - /*-----------------------------------------------------------------*/ - case OP_VSPACE: - if (clen > 0) switch(c) - { - VSPACE_CASES: - ADD_NEW(state_offset + 1, 0); - break; - - default: - break; - } - break; - - /*-----------------------------------------------------------------*/ - case OP_NOT_HSPACE: - if (clen > 0) switch(c) - { - HSPACE_CASES: - break; - - default: - ADD_NEW(state_offset + 1, 0); - break; - } - break; - - /*-----------------------------------------------------------------*/ - case OP_HSPACE: - if (clen > 0) switch(c) - { - HSPACE_CASES: - ADD_NEW(state_offset + 1, 0); - break; - - default: - break; - } - break; - - /*-----------------------------------------------------------------*/ - /* Match a negated single character casefully. */ - - case OP_NOT: - if (clen > 0 && c != d) { ADD_NEW(state_offset + dlen + 1, 0); } - break; - - /*-----------------------------------------------------------------*/ - /* Match a negated single character caselessly. */ - - case OP_NOTI: - if (clen > 0) - { - unsigned int otherd; -#ifdef SUPPORT_UTF - if (utf && d >= 128) - { -#ifdef SUPPORT_UCP - otherd = UCD_OTHERCASE(d); -#endif /* SUPPORT_UCP */ - } - else -#endif /* SUPPORT_UTF */ - otherd = TABLE_GET(d, fcc, d); - if (c != d && c != otherd) - { ADD_NEW(state_offset + dlen + 1, 0); } - } - break; - - /*-----------------------------------------------------------------*/ - case OP_PLUSI: - case OP_MINPLUSI: - case OP_POSPLUSI: - case OP_NOTPLUSI: - case OP_NOTMINPLUSI: - case OP_NOTPOSPLUSI: - caseless = TRUE; - codevalue -= OP_STARI - OP_STAR; - - /* Fall through */ - case OP_PLUS: - case OP_MINPLUS: - case OP_POSPLUS: - case OP_NOTPLUS: - case OP_NOTMINPLUS: - case OP_NOTPOSPLUS: - count = current_state->count; /* Already matched */ - if (count > 0) { ADD_ACTIVE(state_offset + dlen + 1, 0); } - if (clen > 0) - { - pcre_uint32 otherd = NOTACHAR; - if (caseless) - { -#ifdef SUPPORT_UTF - if (utf && d >= 128) - { -#ifdef SUPPORT_UCP - otherd = UCD_OTHERCASE(d); -#endif /* SUPPORT_UCP */ - } - else -#endif /* SUPPORT_UTF */ - otherd = TABLE_GET(d, fcc, d); - } - if ((c == d || c == otherd) == (codevalue < OP_NOTSTAR)) - { - if (count > 0 && - (codevalue == OP_POSPLUS || codevalue == OP_NOTPOSPLUS)) - { - active_count--; /* Remove non-match possibility */ - next_active_state--; - } - count++; - ADD_NEW(state_offset, count); - } - } - break; - - /*-----------------------------------------------------------------*/ - case OP_QUERYI: - case OP_MINQUERYI: - case OP_POSQUERYI: - case OP_NOTQUERYI: - case OP_NOTMINQUERYI: - case OP_NOTPOSQUERYI: - caseless = TRUE; - codevalue -= OP_STARI - OP_STAR; - /* Fall through */ - case OP_QUERY: - case OP_MINQUERY: - case OP_POSQUERY: - case OP_NOTQUERY: - case OP_NOTMINQUERY: - case OP_NOTPOSQUERY: - ADD_ACTIVE(state_offset + dlen + 1, 0); - if (clen > 0) - { - pcre_uint32 otherd = NOTACHAR; - if (caseless) - { -#ifdef SUPPORT_UTF - if (utf && d >= 128) - { -#ifdef SUPPORT_UCP - otherd = UCD_OTHERCASE(d); -#endif /* SUPPORT_UCP */ - } - else -#endif /* SUPPORT_UTF */ - otherd = TABLE_GET(d, fcc, d); - } - if ((c == d || c == otherd) == (codevalue < OP_NOTSTAR)) - { - if (codevalue == OP_POSQUERY || codevalue == OP_NOTPOSQUERY) - { - active_count--; /* Remove non-match possibility */ - next_active_state--; - } - ADD_NEW(state_offset + dlen + 1, 0); - } - } - break; - - /*-----------------------------------------------------------------*/ - case OP_STARI: - case OP_MINSTARI: - case OP_POSSTARI: - case OP_NOTSTARI: - case OP_NOTMINSTARI: - case OP_NOTPOSSTARI: - caseless = TRUE; - codevalue -= OP_STARI - OP_STAR; - /* Fall through */ - case OP_STAR: - case OP_MINSTAR: - case OP_POSSTAR: - case OP_NOTSTAR: - case OP_NOTMINSTAR: - case OP_NOTPOSSTAR: - ADD_ACTIVE(state_offset + dlen + 1, 0); - if (clen > 0) - { - pcre_uint32 otherd = NOTACHAR; - if (caseless) - { -#ifdef SUPPORT_UTF - if (utf && d >= 128) - { -#ifdef SUPPORT_UCP - otherd = UCD_OTHERCASE(d); -#endif /* SUPPORT_UCP */ - } - else -#endif /* SUPPORT_UTF */ - otherd = TABLE_GET(d, fcc, d); - } - if ((c == d || c == otherd) == (codevalue < OP_NOTSTAR)) - { - if (codevalue == OP_POSSTAR || codevalue == OP_NOTPOSSTAR) - { - active_count--; /* Remove non-match possibility */ - next_active_state--; - } - ADD_NEW(state_offset, 0); - } - } - break; - - /*-----------------------------------------------------------------*/ - case OP_EXACTI: - case OP_NOTEXACTI: - caseless = TRUE; - codevalue -= OP_STARI - OP_STAR; - /* Fall through */ - case OP_EXACT: - case OP_NOTEXACT: - count = current_state->count; /* Number already matched */ - if (clen > 0) - { - pcre_uint32 otherd = NOTACHAR; - if (caseless) - { -#ifdef SUPPORT_UTF - if (utf && d >= 128) - { -#ifdef SUPPORT_UCP - otherd = UCD_OTHERCASE(d); -#endif /* SUPPORT_UCP */ - } - else -#endif /* SUPPORT_UTF */ - otherd = TABLE_GET(d, fcc, d); - } - if ((c == d || c == otherd) == (codevalue < OP_NOTSTAR)) - { - if (++count >= (int)GET2(code, 1)) - { ADD_NEW(state_offset + dlen + 1 + IMM2_SIZE, 0); } - else - { ADD_NEW(state_offset, count); } - } - } - break; - - /*-----------------------------------------------------------------*/ - case OP_UPTOI: - case OP_MINUPTOI: - case OP_POSUPTOI: - case OP_NOTUPTOI: - case OP_NOTMINUPTOI: - case OP_NOTPOSUPTOI: - caseless = TRUE; - codevalue -= OP_STARI - OP_STAR; - /* Fall through */ - case OP_UPTO: - case OP_MINUPTO: - case OP_POSUPTO: - case OP_NOTUPTO: - case OP_NOTMINUPTO: - case OP_NOTPOSUPTO: - ADD_ACTIVE(state_offset + dlen + 1 + IMM2_SIZE, 0); - count = current_state->count; /* Number already matched */ - if (clen > 0) - { - pcre_uint32 otherd = NOTACHAR; - if (caseless) - { -#ifdef SUPPORT_UTF - if (utf && d >= 128) - { -#ifdef SUPPORT_UCP - otherd = UCD_OTHERCASE(d); -#endif /* SUPPORT_UCP */ - } - else -#endif /* SUPPORT_UTF */ - otherd = TABLE_GET(d, fcc, d); - } - if ((c == d || c == otherd) == (codevalue < OP_NOTSTAR)) - { - if (codevalue == OP_POSUPTO || codevalue == OP_NOTPOSUPTO) - { - active_count--; /* Remove non-match possibility */ - next_active_state--; - } - if (++count >= (int)GET2(code, 1)) - { ADD_NEW(state_offset + dlen + 1 + IMM2_SIZE, 0); } - else - { ADD_NEW(state_offset, count); } - } - } - break; - - -/* ========================================================================== */ - /* These are the class-handling opcodes */ - - case OP_CLASS: - case OP_NCLASS: - case OP_XCLASS: - { - BOOL isinclass = FALSE; - int next_state_offset; - const pcre_uchar *ecode; - - /* For a simple class, there is always just a 32-byte table, and we - can set isinclass from it. */ - - if (codevalue != OP_XCLASS) - { - ecode = code + 1 + (32 / sizeof(pcre_uchar)); - if (clen > 0) - { - isinclass = (c > 255)? (codevalue == OP_NCLASS) : - ((((pcre_uint8 *)(code + 1))[c/8] & (1 << (c&7))) != 0); - } - } - - /* An extended class may have a table or a list of single characters, - ranges, or both, and it may be positive or negative. There's a - function that sorts all this out. */ - - else - { - ecode = code + GET(code, 1); - if (clen > 0) isinclass = PRIV(xclass)(c, code + 1 + LINK_SIZE, utf); - } - - /* At this point, isinclass is set for all kinds of class, and ecode - points to the byte after the end of the class. If there is a - quantifier, this is where it will be. */ - - next_state_offset = (int)(ecode - start_code); - - switch (*ecode) - { - case OP_CRSTAR: - case OP_CRMINSTAR: - case OP_CRPOSSTAR: - ADD_ACTIVE(next_state_offset + 1, 0); - if (isinclass) - { - if (*ecode == OP_CRPOSSTAR) - { - active_count--; /* Remove non-match possibility */ - next_active_state--; - } - ADD_NEW(state_offset, 0); - } - break; - - case OP_CRPLUS: - case OP_CRMINPLUS: - case OP_CRPOSPLUS: - count = current_state->count; /* Already matched */ - if (count > 0) { ADD_ACTIVE(next_state_offset + 1, 0); } - if (isinclass) - { - if (count > 0 && *ecode == OP_CRPOSPLUS) - { - active_count--; /* Remove non-match possibility */ - next_active_state--; - } - count++; - ADD_NEW(state_offset, count); - } - break; - - case OP_CRQUERY: - case OP_CRMINQUERY: - case OP_CRPOSQUERY: - ADD_ACTIVE(next_state_offset + 1, 0); - if (isinclass) - { - if (*ecode == OP_CRPOSQUERY) - { - active_count--; /* Remove non-match possibility */ - next_active_state--; - } - ADD_NEW(next_state_offset + 1, 0); - } - break; - - case OP_CRRANGE: - case OP_CRMINRANGE: - case OP_CRPOSRANGE: - count = current_state->count; /* Already matched */ - if (count >= (int)GET2(ecode, 1)) - { ADD_ACTIVE(next_state_offset + 1 + 2 * IMM2_SIZE, 0); } - if (isinclass) - { - int max = (int)GET2(ecode, 1 + IMM2_SIZE); - if (*ecode == OP_CRPOSRANGE) - { - active_count--; /* Remove non-match possibility */ - next_active_state--; - } - if (++count >= max && max != 0) /* Max 0 => no limit */ - { ADD_NEW(next_state_offset + 1 + 2 * IMM2_SIZE, 0); } - else - { ADD_NEW(state_offset, count); } - } - break; - - default: - if (isinclass) { ADD_NEW(next_state_offset, 0); } - break; - } - } - break; - -/* ========================================================================== */ - /* These are the opcodes for fancy brackets of various kinds. We have - to use recursion in order to handle them. The "always failing" assertion - (?!) is optimised to OP_FAIL when compiling, so we have to support that, - though the other "backtracking verbs" are not supported. */ - - case OP_FAIL: - forced_fail++; /* Count FAILs for multiple states */ - break; - - case OP_ASSERT: - case OP_ASSERT_NOT: - case OP_ASSERTBACK: - case OP_ASSERTBACK_NOT: - { - int rc; - int local_offsets[2]; - int local_workspace[1000]; - const pcre_uchar *endasscode = code + GET(code, 1); - - while (*endasscode == OP_ALT) endasscode += GET(endasscode, 1); - - rc = internal_dfa_exec( - md, /* static match data */ - code, /* this subexpression's code */ - ptr, /* where we currently are */ - (int)(ptr - start_subject), /* start offset */ - local_offsets, /* offset vector */ - sizeof(local_offsets)/sizeof(int), /* size of same */ - local_workspace, /* workspace vector */ - sizeof(local_workspace)/sizeof(int), /* size of same */ - rlevel); /* function recursion level */ - - if (rc == PCRE_ERROR_DFA_UITEM) return rc; - if ((rc >= 0) == (codevalue == OP_ASSERT || codevalue == OP_ASSERTBACK)) - { ADD_ACTIVE((int)(endasscode + LINK_SIZE + 1 - start_code), 0); } - } - break; - - /*-----------------------------------------------------------------*/ - case OP_COND: - case OP_SCOND: - { - int local_offsets[1000]; - int local_workspace[1000]; - int codelink = GET(code, 1); - int condcode; - - /* Because of the way auto-callout works during compile, a callout item - is inserted between OP_COND and an assertion condition. This does not - happen for the other conditions. */ - - if (code[LINK_SIZE+1] == OP_CALLOUT) - { - rrc = 0; - if (PUBL(callout) != NULL) - { - PUBL(callout_block) cb; - cb.version = 1; /* Version 1 of the callout block */ - cb.callout_number = code[LINK_SIZE+2]; - cb.offset_vector = offsets; -#if defined COMPILE_PCRE8 - cb.subject = (PCRE_SPTR)start_subject; -#elif defined COMPILE_PCRE16 - cb.subject = (PCRE_SPTR16)start_subject; -#elif defined COMPILE_PCRE32 - cb.subject = (PCRE_SPTR32)start_subject; -#endif - cb.subject_length = (int)(end_subject - start_subject); - cb.start_match = (int)(current_subject - start_subject); - cb.current_position = (int)(ptr - start_subject); - cb.pattern_position = GET(code, LINK_SIZE + 3); - cb.next_item_length = GET(code, 3 + 2*LINK_SIZE); - cb.capture_top = 1; - cb.capture_last = -1; - cb.callout_data = md->callout_data; - cb.mark = NULL; /* No (*MARK) support */ - if ((rrc = (*PUBL(callout))(&cb)) < 0) return rrc; /* Abandon */ - } - if (rrc > 0) break; /* Fail this thread */ - code += PRIV(OP_lengths)[OP_CALLOUT]; /* Skip callout data */ - } - - condcode = code[LINK_SIZE+1]; - - /* Back reference conditions and duplicate named recursion conditions - are not supported */ - - if (condcode == OP_CREF || condcode == OP_DNCREF || - condcode == OP_DNRREF) - return PCRE_ERROR_DFA_UCOND; - - /* The DEFINE condition is always false */ - - if (condcode == OP_DEF) - { ADD_ACTIVE(state_offset + codelink + LINK_SIZE + 1, 0); } - - /* The only supported version of OP_RREF is for the value RREF_ANY, - which means "test if in any recursion". We can't test for specifically - recursed groups. */ - - else if (condcode == OP_RREF) - { - int value = GET2(code, LINK_SIZE + 2); - if (value != RREF_ANY) return PCRE_ERROR_DFA_UCOND; - if (md->recursive != NULL) - { ADD_ACTIVE(state_offset + LINK_SIZE + 2 + IMM2_SIZE, 0); } - else { ADD_ACTIVE(state_offset + codelink + LINK_SIZE + 1, 0); } - } - - /* Otherwise, the condition is an assertion */ - - else - { - int rc; - const pcre_uchar *asscode = code + LINK_SIZE + 1; - const pcre_uchar *endasscode = asscode + GET(asscode, 1); - - while (*endasscode == OP_ALT) endasscode += GET(endasscode, 1); - - rc = internal_dfa_exec( - md, /* fixed match data */ - asscode, /* this subexpression's code */ - ptr, /* where we currently are */ - (int)(ptr - start_subject), /* start offset */ - local_offsets, /* offset vector */ - sizeof(local_offsets)/sizeof(int), /* size of same */ - local_workspace, /* workspace vector */ - sizeof(local_workspace)/sizeof(int), /* size of same */ - rlevel); /* function recursion level */ - - if (rc == PCRE_ERROR_DFA_UITEM) return rc; - if ((rc >= 0) == - (condcode == OP_ASSERT || condcode == OP_ASSERTBACK)) - { ADD_ACTIVE((int)(endasscode + LINK_SIZE + 1 - start_code), 0); } - else - { ADD_ACTIVE(state_offset + codelink + LINK_SIZE + 1, 0); } - } - } - break; - - /*-----------------------------------------------------------------*/ - case OP_RECURSE: - { - dfa_recursion_info *ri; - int local_offsets[1000]; - int local_workspace[1000]; - const pcre_uchar *callpat = start_code + GET(code, 1); - int recno = (callpat == md->start_code)? 0 : - GET2(callpat, 1 + LINK_SIZE); - int rc; - - DPRINTF(("%.*sStarting regex recursion\n", rlevel*2-2, SP)); - - /* Check for repeating a recursion without advancing the subject - pointer. This should catch convoluted mutual recursions. (Some simple - cases are caught at compile time.) */ - - for (ri = md->recursive; ri != NULL; ri = ri->prevrec) - if (recno == ri->group_num && ptr == ri->subject_position) - return PCRE_ERROR_RECURSELOOP; - - /* Remember this recursion and where we started it so as to - catch infinite loops. */ - - new_recursive.group_num = recno; - new_recursive.subject_position = ptr; - new_recursive.prevrec = md->recursive; - md->recursive = &new_recursive; - - rc = internal_dfa_exec( - md, /* fixed match data */ - callpat, /* this subexpression's code */ - ptr, /* where we currently are */ - (int)(ptr - start_subject), /* start offset */ - local_offsets, /* offset vector */ - sizeof(local_offsets)/sizeof(int), /* size of same */ - local_workspace, /* workspace vector */ - sizeof(local_workspace)/sizeof(int), /* size of same */ - rlevel); /* function recursion level */ - - md->recursive = new_recursive.prevrec; /* Done this recursion */ - - DPRINTF(("%.*sReturn from regex recursion: rc=%d\n", rlevel*2-2, SP, - rc)); - - /* Ran out of internal offsets */ - - if (rc == 0) return PCRE_ERROR_DFA_RECURSE; - - /* For each successful matched substring, set up the next state with a - count of characters to skip before trying it. Note that the count is in - characters, not bytes. */ - - if (rc > 0) - { - for (rc = rc*2 - 2; rc >= 0; rc -= 2) - { - int charcount = local_offsets[rc+1] - local_offsets[rc]; -#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 - if (utf) - { - const pcre_uchar *p = start_subject + local_offsets[rc]; - const pcre_uchar *pp = start_subject + local_offsets[rc+1]; - while (p < pp) if (NOT_FIRSTCHAR(*p++)) charcount--; - } -#endif - if (charcount > 0) - { - ADD_NEW_DATA(-(state_offset + LINK_SIZE + 1), 0, (charcount - 1)); - } - else - { - ADD_ACTIVE(state_offset + LINK_SIZE + 1, 0); - } - } - } - else if (rc != PCRE_ERROR_NOMATCH) return rc; - } - break; - - /*-----------------------------------------------------------------*/ - case OP_BRAPOS: - case OP_SBRAPOS: - case OP_CBRAPOS: - case OP_SCBRAPOS: - case OP_BRAPOSZERO: - { - int charcount, matched_count; - const pcre_uchar *local_ptr = ptr; - BOOL allow_zero; - - if (codevalue == OP_BRAPOSZERO) - { - allow_zero = TRUE; - codevalue = *(++code); /* Codevalue will be one of above BRAs */ - } - else allow_zero = FALSE; - - /* Loop to match the subpattern as many times as possible as if it were - a complete pattern. */ - - for (matched_count = 0;; matched_count++) - { - int local_offsets[2]; - int local_workspace[1000]; - - int rc = internal_dfa_exec( - md, /* fixed match data */ - code, /* this subexpression's code */ - local_ptr, /* where we currently are */ - (int)(ptr - start_subject), /* start offset */ - local_offsets, /* offset vector */ - sizeof(local_offsets)/sizeof(int), /* size of same */ - local_workspace, /* workspace vector */ - sizeof(local_workspace)/sizeof(int), /* size of same */ - rlevel); /* function recursion level */ - - /* Failed to match */ - - if (rc < 0) - { - if (rc != PCRE_ERROR_NOMATCH) return rc; - break; - } - - /* Matched: break the loop if zero characters matched. */ - - charcount = local_offsets[1] - local_offsets[0]; - if (charcount == 0) break; - local_ptr += charcount; /* Advance temporary position ptr */ - } - - /* At this point we have matched the subpattern matched_count - times, and local_ptr is pointing to the character after the end of the - last match. */ - - if (matched_count > 0 || allow_zero) - { - const pcre_uchar *end_subpattern = code; - int next_state_offset; - - do { end_subpattern += GET(end_subpattern, 1); } - while (*end_subpattern == OP_ALT); - next_state_offset = - (int)(end_subpattern - start_code + LINK_SIZE + 1); - - /* Optimization: if there are no more active states, and there - are no new states yet set up, then skip over the subject string - right here, to save looping. Otherwise, set up the new state to swing - into action when the end of the matched substring is reached. */ - - if (i + 1 >= active_count && new_count == 0) - { - ptr = local_ptr; - clen = 0; - ADD_NEW(next_state_offset, 0); - } - else - { - const pcre_uchar *p = ptr; - const pcre_uchar *pp = local_ptr; - charcount = (int)(pp - p); -#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 - if (utf) while (p < pp) if (NOT_FIRSTCHAR(*p++)) charcount--; -#endif - ADD_NEW_DATA(-next_state_offset, 0, (charcount - 1)); - } - } - } - break; - - /*-----------------------------------------------------------------*/ - case OP_ONCE: - case OP_ONCE_NC: - { - int local_offsets[2]; - int local_workspace[1000]; - - int rc = internal_dfa_exec( - md, /* fixed match data */ - code, /* this subexpression's code */ - ptr, /* where we currently are */ - (int)(ptr - start_subject), /* start offset */ - local_offsets, /* offset vector */ - sizeof(local_offsets)/sizeof(int), /* size of same */ - local_workspace, /* workspace vector */ - sizeof(local_workspace)/sizeof(int), /* size of same */ - rlevel); /* function recursion level */ - - if (rc >= 0) - { - const pcre_uchar *end_subpattern = code; - int charcount = local_offsets[1] - local_offsets[0]; - int next_state_offset, repeat_state_offset; - - do { end_subpattern += GET(end_subpattern, 1); } - while (*end_subpattern == OP_ALT); - next_state_offset = - (int)(end_subpattern - start_code + LINK_SIZE + 1); - - /* If the end of this subpattern is KETRMAX or KETRMIN, we must - arrange for the repeat state also to be added to the relevant list. - Calculate the offset, or set -1 for no repeat. */ - - repeat_state_offset = (*end_subpattern == OP_KETRMAX || - *end_subpattern == OP_KETRMIN)? - (int)(end_subpattern - start_code - GET(end_subpattern, 1)) : -1; - - /* If we have matched an empty string, add the next state at the - current character pointer. This is important so that the duplicate - checking kicks in, which is what breaks infinite loops that match an - empty string. */ - - if (charcount == 0) - { - ADD_ACTIVE(next_state_offset, 0); - } - - /* Optimization: if there are no more active states, and there - are no new states yet set up, then skip over the subject string - right here, to save looping. Otherwise, set up the new state to swing - into action when the end of the matched substring is reached. */ - - else if (i + 1 >= active_count && new_count == 0) - { - ptr += charcount; - clen = 0; - ADD_NEW(next_state_offset, 0); - - /* If we are adding a repeat state at the new character position, - we must fudge things so that it is the only current state. - Otherwise, it might be a duplicate of one we processed before, and - that would cause it to be skipped. */ - - if (repeat_state_offset >= 0) - { - next_active_state = active_states; - active_count = 0; - i = -1; - ADD_ACTIVE(repeat_state_offset, 0); - } - } - else - { -#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 - if (utf) - { - const pcre_uchar *p = start_subject + local_offsets[0]; - const pcre_uchar *pp = start_subject + local_offsets[1]; - while (p < pp) if (NOT_FIRSTCHAR(*p++)) charcount--; - } -#endif - ADD_NEW_DATA(-next_state_offset, 0, (charcount - 1)); - if (repeat_state_offset >= 0) - { ADD_NEW_DATA(-repeat_state_offset, 0, (charcount - 1)); } - } - } - else if (rc != PCRE_ERROR_NOMATCH) return rc; - } - break; - - -/* ========================================================================== */ - /* Handle callouts */ - - case OP_CALLOUT: - rrc = 0; - if (PUBL(callout) != NULL) - { - PUBL(callout_block) cb; - cb.version = 1; /* Version 1 of the callout block */ - cb.callout_number = code[1]; - cb.offset_vector = offsets; -#if defined COMPILE_PCRE8 - cb.subject = (PCRE_SPTR)start_subject; -#elif defined COMPILE_PCRE16 - cb.subject = (PCRE_SPTR16)start_subject; -#elif defined COMPILE_PCRE32 - cb.subject = (PCRE_SPTR32)start_subject; -#endif - cb.subject_length = (int)(end_subject - start_subject); - cb.start_match = (int)(current_subject - start_subject); - cb.current_position = (int)(ptr - start_subject); - cb.pattern_position = GET(code, 2); - cb.next_item_length = GET(code, 2 + LINK_SIZE); - cb.capture_top = 1; - cb.capture_last = -1; - cb.callout_data = md->callout_data; - cb.mark = NULL; /* No (*MARK) support */ - if ((rrc = (*PUBL(callout))(&cb)) < 0) return rrc; /* Abandon */ - } - if (rrc == 0) - { ADD_ACTIVE(state_offset + PRIV(OP_lengths)[OP_CALLOUT], 0); } - break; - - -/* ========================================================================== */ - default: /* Unsupported opcode */ - return PCRE_ERROR_DFA_UITEM; - } - - NEXT_ACTIVE_STATE: continue; - - } /* End of loop scanning active states */ - - /* We have finished the processing at the current subject character. If no - new states have been set for the next character, we have found all the - matches that we are going to find. If we are at the top level and partial - matching has been requested, check for appropriate conditions. - - The "forced_ fail" variable counts the number of (*F) encountered for the - character. If it is equal to the original active_count (saved in - workspace[1]) it means that (*F) was found on every active state. In this - case we don't want to give a partial match. - - The "could_continue" variable is true if a state could have continued but - for the fact that the end of the subject was reached. */ - - if (new_count <= 0) - { - if (rlevel == 1 && /* Top level, and */ - could_continue && /* Some could go on, and */ - forced_fail != workspace[1] && /* Not all forced fail & */ - ( /* either... */ - (md->moptions & PCRE_PARTIAL_HARD) != 0 /* Hard partial */ - || /* or... */ - ((md->moptions & PCRE_PARTIAL_SOFT) != 0 && /* Soft partial and */ - match_count < 0) /* no matches */ - ) && /* And... */ - ( - partial_newline || /* Either partial NL */ - ( /* or ... */ - ptr >= end_subject && /* End of subject and */ - ptr > md->start_used_ptr) /* Inspected non-empty string */ - ) - ) - match_count = PCRE_ERROR_PARTIAL; - DPRINTF(("%.*sEnd of internal_dfa_exec %d: returning %d\n" - "%.*s---------------------\n\n", rlevel*2-2, SP, rlevel, match_count, - rlevel*2-2, SP)); - break; /* In effect, "return", but see the comment below */ - } - - /* One or more states are active for the next character. */ - - ptr += clen; /* Advance to next subject character */ - } /* Loop to move along the subject string */ - -/* Control gets here from "break" a few lines above. We do it this way because -if we use "return" above, we have compiler trouble. Some compilers warn if -there's nothing here because they think the function doesn't return a value. On -the other hand, if we put a dummy statement here, some more clever compilers -complain that it can't be reached. Sigh. */ - -return match_count; -} - - - - -/************************************************* -* Execute a Regular Expression - DFA engine * -*************************************************/ - -/* This external function applies a compiled re to a subject string using a DFA -engine. This function calls the internal function multiple times if the pattern -is not anchored. - -Arguments: - argument_re points to the compiled expression - extra_data points to extra data or is NULL - subject points to the subject string - length length of subject string (may contain binary zeros) - start_offset where to start in the subject string - options option bits - offsets vector of match offsets - offsetcount size of same - workspace workspace vector - wscount size of same - -Returns: > 0 => number of match offset pairs placed in offsets - = 0 => offsets overflowed; longest matches are present - -1 => failed to match - < -1 => some kind of unexpected problem -*/ - -#if defined COMPILE_PCRE8 -PCRE_EXP_DEFN int PCRE_CALL_CONVENTION -pcre_dfa_exec(const pcre *argument_re, const pcre_extra *extra_data, - const char *subject, int length, int start_offset, int options, int *offsets, - int offsetcount, int *workspace, int wscount) -#elif defined COMPILE_PCRE16 -PCRE_EXP_DEFN int PCRE_CALL_CONVENTION -pcre16_dfa_exec(const pcre16 *argument_re, const pcre16_extra *extra_data, - PCRE_SPTR16 subject, int length, int start_offset, int options, int *offsets, - int offsetcount, int *workspace, int wscount) -#elif defined COMPILE_PCRE32 -PCRE_EXP_DEFN int PCRE_CALL_CONVENTION -pcre32_dfa_exec(const pcre32 *argument_re, const pcre32_extra *extra_data, - PCRE_SPTR32 subject, int length, int start_offset, int options, int *offsets, - int offsetcount, int *workspace, int wscount) -#endif -{ -REAL_PCRE *re = (REAL_PCRE *)argument_re; -dfa_match_data match_block; -dfa_match_data *md = &match_block; -BOOL utf, anchored, startline, firstline; -const pcre_uchar *current_subject, *end_subject; -const pcre_study_data *study = NULL; - -const pcre_uchar *req_char_ptr; -const pcre_uint8 *start_bits = NULL; -BOOL has_first_char = FALSE; -BOOL has_req_char = FALSE; -pcre_uchar first_char = 0; -pcre_uchar first_char2 = 0; -pcre_uchar req_char = 0; -pcre_uchar req_char2 = 0; -int newline; - -/* Plausibility checks */ - -if ((options & ~PUBLIC_DFA_EXEC_OPTIONS) != 0) return PCRE_ERROR_BADOPTION; -if (re == NULL || subject == NULL || workspace == NULL || - (offsets == NULL && offsetcount > 0)) return PCRE_ERROR_NULL; -if (offsetcount < 0) return PCRE_ERROR_BADCOUNT; -if (wscount < 20) return PCRE_ERROR_DFA_WSSIZE; -if (length < 0) return PCRE_ERROR_BADLENGTH; -if (start_offset < 0 || start_offset > length) return PCRE_ERROR_BADOFFSET; - -/* Check that the first field in the block is the magic number. If it is not, -return with PCRE_ERROR_BADMAGIC. However, if the magic number is equal to -REVERSED_MAGIC_NUMBER we return with PCRE_ERROR_BADENDIANNESS, which -means that the pattern is likely compiled with different endianness. */ - -if (re->magic_number != MAGIC_NUMBER) - return re->magic_number == REVERSED_MAGIC_NUMBER? - PCRE_ERROR_BADENDIANNESS:PCRE_ERROR_BADMAGIC; -if ((re->flags & PCRE_MODE) == 0) return PCRE_ERROR_BADMODE; - -/* If restarting after a partial match, do some sanity checks on the contents -of the workspace. */ - -if ((options & PCRE_DFA_RESTART) != 0) - { - if ((workspace[0] & (-2)) != 0 || workspace[1] < 1 || - workspace[1] > (wscount - 2)/INTS_PER_STATEBLOCK) - return PCRE_ERROR_DFA_BADRESTART; - } - -/* Set up study, callout, and table data */ - -md->tables = re->tables; -md->callout_data = NULL; - -if (extra_data != NULL) - { - unsigned long int flags = extra_data->flags; - if ((flags & PCRE_EXTRA_STUDY_DATA) != 0) - study = (const pcre_study_data *)extra_data->study_data; - if ((flags & PCRE_EXTRA_MATCH_LIMIT) != 0) return PCRE_ERROR_DFA_UMLIMIT; - if ((flags & PCRE_EXTRA_MATCH_LIMIT_RECURSION) != 0) - return PCRE_ERROR_DFA_UMLIMIT; - if ((flags & PCRE_EXTRA_CALLOUT_DATA) != 0) - md->callout_data = extra_data->callout_data; - if ((flags & PCRE_EXTRA_TABLES) != 0) - md->tables = extra_data->tables; - } - -/* Set some local values */ - -current_subject = (const pcre_uchar *)subject + start_offset; -end_subject = (const pcre_uchar *)subject + length; -req_char_ptr = current_subject - 1; - -#ifdef SUPPORT_UTF -/* PCRE_UTF(16|32) have the same value as PCRE_UTF8. */ -utf = (re->options & PCRE_UTF8) != 0; -#else -utf = FALSE; -#endif - -anchored = (options & (PCRE_ANCHORED|PCRE_DFA_RESTART)) != 0 || - (re->options & PCRE_ANCHORED) != 0; - -/* The remaining fixed data for passing around. */ - -md->start_code = (const pcre_uchar *)argument_re + - re->name_table_offset + re->name_count * re->name_entry_size; -md->start_subject = (const pcre_uchar *)subject; -md->end_subject = end_subject; -md->start_offset = start_offset; -md->moptions = options; -md->poptions = re->options; - -/* If the BSR option is not set at match time, copy what was set -at compile time. */ - -if ((md->moptions & (PCRE_BSR_ANYCRLF|PCRE_BSR_UNICODE)) == 0) - { - if ((re->options & (PCRE_BSR_ANYCRLF|PCRE_BSR_UNICODE)) != 0) - md->moptions |= re->options & (PCRE_BSR_ANYCRLF|PCRE_BSR_UNICODE); -#ifdef BSR_ANYCRLF - else md->moptions |= PCRE_BSR_ANYCRLF; -#endif - } - -/* Handle different types of newline. The three bits give eight cases. If -nothing is set at run time, whatever was used at compile time applies. */ - -switch ((((options & PCRE_NEWLINE_BITS) == 0)? re->options : (pcre_uint32)options) & - PCRE_NEWLINE_BITS) - { - case 0: newline = NEWLINE; break; /* Compile-time default */ - case PCRE_NEWLINE_CR: newline = CHAR_CR; break; - case PCRE_NEWLINE_LF: newline = CHAR_NL; break; - case PCRE_NEWLINE_CR+ - PCRE_NEWLINE_LF: newline = (CHAR_CR << 8) | CHAR_NL; break; - case PCRE_NEWLINE_ANY: newline = -1; break; - case PCRE_NEWLINE_ANYCRLF: newline = -2; break; - default: return PCRE_ERROR_BADNEWLINE; - } - -if (newline == -2) - { - md->nltype = NLTYPE_ANYCRLF; - } -else if (newline < 0) - { - md->nltype = NLTYPE_ANY; - } -else - { - md->nltype = NLTYPE_FIXED; - if (newline > 255) - { - md->nllen = 2; - md->nl[0] = (newline >> 8) & 255; - md->nl[1] = newline & 255; - } - else - { - md->nllen = 1; - md->nl[0] = newline; - } - } - -/* Check a UTF-8 string if required. Unfortunately there's no way of passing -back the character offset. */ - -#ifdef SUPPORT_UTF -if (utf && (options & PCRE_NO_UTF8_CHECK) == 0) - { - int erroroffset; - int errorcode = PRIV(valid_utf)((pcre_uchar *)subject, length, &erroroffset); - if (errorcode != 0) - { - if (offsetcount >= 2) - { - offsets[0] = erroroffset; - offsets[1] = errorcode; - } -#if defined COMPILE_PCRE8 - return (errorcode <= PCRE_UTF8_ERR5 && (options & PCRE_PARTIAL_HARD) != 0) ? - PCRE_ERROR_SHORTUTF8 : PCRE_ERROR_BADUTF8; -#elif defined COMPILE_PCRE16 - return (errorcode <= PCRE_UTF16_ERR1 && (options & PCRE_PARTIAL_HARD) != 0) ? - PCRE_ERROR_SHORTUTF16 : PCRE_ERROR_BADUTF16; -#elif defined COMPILE_PCRE32 - return PCRE_ERROR_BADUTF32; -#endif - } -#if defined COMPILE_PCRE8 || defined COMPILE_PCRE16 - if (start_offset > 0 && start_offset < length && - NOT_FIRSTCHAR(((PCRE_PUCHAR)subject)[start_offset])) - return PCRE_ERROR_BADUTF8_OFFSET; -#endif - } -#endif - -/* If the exec call supplied NULL for tables, use the inbuilt ones. This -is a feature that makes it possible to save compiled regex and re-use them -in other programs later. */ - -if (md->tables == NULL) md->tables = PRIV(default_tables); - -/* The "must be at the start of a line" flags are used in a loop when finding -where to start. */ - -startline = (re->flags & PCRE_STARTLINE) != 0; -firstline = (re->options & PCRE_FIRSTLINE) != 0; - -/* Set up the first character to match, if available. The first_byte value is -never set for an anchored regular expression, but the anchoring may be forced -at run time, so we have to test for anchoring. The first char may be unset for -an unanchored pattern, of course. If there's no first char and the pattern was -studied, there may be a bitmap of possible first characters. */ - -if (!anchored) - { - if ((re->flags & PCRE_FIRSTSET) != 0) - { - has_first_char = TRUE; - first_char = first_char2 = (pcre_uchar)(re->first_char); - if ((re->flags & PCRE_FCH_CASELESS) != 0) - { - first_char2 = TABLE_GET(first_char, md->tables + fcc_offset, first_char); -#if defined SUPPORT_UCP && !(defined COMPILE_PCRE8) - if (utf && first_char > 127) - first_char2 = UCD_OTHERCASE(first_char); -#endif - } - } - else - { - if (!startline && study != NULL && - (study->flags & PCRE_STUDY_MAPPED) != 0) - start_bits = study->start_bits; - } - } - -/* For anchored or unanchored matches, there may be a "last known required -character" set. */ - -if ((re->flags & PCRE_REQCHSET) != 0) - { - has_req_char = TRUE; - req_char = req_char2 = (pcre_uchar)(re->req_char); - if ((re->flags & PCRE_RCH_CASELESS) != 0) - { - req_char2 = TABLE_GET(req_char, md->tables + fcc_offset, req_char); -#if defined SUPPORT_UCP && !(defined COMPILE_PCRE8) - if (utf && req_char > 127) - req_char2 = UCD_OTHERCASE(req_char); -#endif - } - } - -/* Call the main matching function, looping for a non-anchored regex after a -failed match. If not restarting, perform certain optimizations at the start of -a match. */ - -for (;;) - { - int rc; - - if ((options & PCRE_DFA_RESTART) == 0) - { - const pcre_uchar *save_end_subject = end_subject; - - /* If firstline is TRUE, the start of the match is constrained to the first - line of a multiline string. Implement this by temporarily adjusting - end_subject so that we stop scanning at a newline. If the match fails at - the newline, later code breaks this loop. */ - - if (firstline) - { - PCRE_PUCHAR t = current_subject; -#ifdef SUPPORT_UTF - if (utf) - { - while (t < md->end_subject && !IS_NEWLINE(t)) - { - t++; - ACROSSCHAR(t < end_subject, *t, t++); - } - } - else -#endif - while (t < md->end_subject && !IS_NEWLINE(t)) t++; - end_subject = t; - } - - /* There are some optimizations that avoid running the match if a known - starting point is not found. However, there is an option that disables - these, for testing and for ensuring that all callouts do actually occur. - The option can be set in the regex by (*NO_START_OPT) or passed in - match-time options. */ - - if (((options | re->options) & PCRE_NO_START_OPTIMIZE) == 0) - { - /* Advance to a known first pcre_uchar (i.e. data item) */ - - if (has_first_char) - { - if (first_char != first_char2) - { - pcre_uchar csc; - while (current_subject < end_subject && - (csc = UCHAR21TEST(current_subject)) != first_char && csc != first_char2) - current_subject++; - } - else - while (current_subject < end_subject && - UCHAR21TEST(current_subject) != first_char) - current_subject++; - } - - /* Or to just after a linebreak for a multiline match if possible */ - - else if (startline) - { - if (current_subject > md->start_subject + start_offset) - { -#ifdef SUPPORT_UTF - if (utf) - { - while (current_subject < end_subject && - !WAS_NEWLINE(current_subject)) - { - current_subject++; - ACROSSCHAR(current_subject < end_subject, *current_subject, - current_subject++); - } - } - else -#endif - while (current_subject < end_subject && !WAS_NEWLINE(current_subject)) - current_subject++; - - /* If we have just passed a CR and the newline option is ANY or - ANYCRLF, and we are now at a LF, advance the match position by one - more character. */ - - if (UCHAR21TEST(current_subject - 1) == CHAR_CR && - (md->nltype == NLTYPE_ANY || md->nltype == NLTYPE_ANYCRLF) && - current_subject < end_subject && - UCHAR21TEST(current_subject) == CHAR_NL) - current_subject++; - } - } - - /* Advance to a non-unique first pcre_uchar after study */ - - else if (start_bits != NULL) - { - while (current_subject < end_subject) - { - register pcre_uint32 c = UCHAR21TEST(current_subject); -#ifndef COMPILE_PCRE8 - if (c > 255) c = 255; -#endif - if ((start_bits[c/8] & (1 << (c&7))) != 0) break; - current_subject++; - } - } - } - - /* Restore fudged end_subject */ - - end_subject = save_end_subject; - - /* The following two optimizations are disabled for partial matching or if - disabling is explicitly requested (and of course, by the test above, this - code is not obeyed when restarting after a partial match). */ - - if (((options | re->options) & PCRE_NO_START_OPTIMIZE) == 0 && - (options & (PCRE_PARTIAL_HARD|PCRE_PARTIAL_SOFT)) == 0) - { - /* If the pattern was studied, a minimum subject length may be set. This - is a lower bound; no actual string of that length may actually match the - pattern. Although the value is, strictly, in characters, we treat it as - in pcre_uchar units to avoid spending too much time in this optimization. - */ - - if (study != NULL && (study->flags & PCRE_STUDY_MINLEN) != 0 && - (pcre_uint32)(end_subject - current_subject) < study->minlength) - return PCRE_ERROR_NOMATCH; - - /* If req_char is set, we know that that pcre_uchar must appear in the - subject for the match to succeed. If the first pcre_uchar is set, - req_char must be later in the subject; otherwise the test starts at the - match point. This optimization can save a huge amount of work in patterns - with nested unlimited repeats that aren't going to match. Writing - separate code for cased/caseless versions makes it go faster, as does - using an autoincrement and backing off on a match. - - HOWEVER: when the subject string is very, very long, searching to its end - can take a long time, and give bad performance on quite ordinary - patterns. This showed up when somebody was matching /^C/ on a 32-megabyte - string... so we don't do this when the string is sufficiently long. */ - - if (has_req_char && end_subject - current_subject < REQ_BYTE_MAX) - { - register PCRE_PUCHAR p = current_subject + (has_first_char? 1:0); - - /* We don't need to repeat the search if we haven't yet reached the - place we found it at last time. */ - - if (p > req_char_ptr) - { - if (req_char != req_char2) - { - while (p < end_subject) - { - register pcre_uint32 pp = UCHAR21INCTEST(p); - if (pp == req_char || pp == req_char2) { p--; break; } - } - } - else - { - while (p < end_subject) - { - if (UCHAR21INCTEST(p) == req_char) { p--; break; } - } - } - - /* If we can't find the required pcre_uchar, break the matching loop, - which will cause a return or PCRE_ERROR_NOMATCH. */ - - if (p >= end_subject) break; - - /* If we have found the required pcre_uchar, save the point where we - found it, so that we don't search again next time round the loop if - the start hasn't passed this point yet. */ - - req_char_ptr = p; - } - } - } - } /* End of optimizations that are done when not restarting */ - - /* OK, now we can do the business */ - - md->start_used_ptr = current_subject; - md->recursive = NULL; - - rc = internal_dfa_exec( - md, /* fixed match data */ - md->start_code, /* this subexpression's code */ - current_subject, /* where we currently are */ - start_offset, /* start offset in subject */ - offsets, /* offset vector */ - offsetcount, /* size of same */ - workspace, /* workspace vector */ - wscount, /* size of same */ - 0); /* function recurse level */ - - /* Anything other than "no match" means we are done, always; otherwise, carry - on only if not anchored. */ - - if (rc != PCRE_ERROR_NOMATCH || anchored) - { - if (rc == PCRE_ERROR_PARTIAL && offsetcount >= 2) - { - offsets[0] = (int)(md->start_used_ptr - (PCRE_PUCHAR)subject); - offsets[1] = (int)(end_subject - (PCRE_PUCHAR)subject); - if (offsetcount > 2) - offsets[2] = (int)(current_subject - (PCRE_PUCHAR)subject); - } - return rc; - } - - /* Advance to the next subject character unless we are at the end of a line - and firstline is set. */ - - if (firstline && IS_NEWLINE(current_subject)) break; - current_subject++; -#ifdef SUPPORT_UTF - if (utf) - { - ACROSSCHAR(current_subject < end_subject, *current_subject, - current_subject++); - } -#endif - if (current_subject > end_subject) break; - - /* If we have just passed a CR and we are now at a LF, and the pattern does - not contain any explicit matches for \r or \n, and the newline option is CRLF - or ANY or ANYCRLF, advance the match position by one more character. */ - - if (UCHAR21TEST(current_subject - 1) == CHAR_CR && - current_subject < end_subject && - UCHAR21TEST(current_subject) == CHAR_NL && - (re->flags & PCRE_HASCRORLF) == 0 && - (md->nltype == NLTYPE_ANY || - md->nltype == NLTYPE_ANYCRLF || - md->nllen == 2)) - current_subject++; - - } /* "Bumpalong" loop */ - -return PCRE_ERROR_NOMATCH; -} - -/* End of pcre_dfa_exec.c */ diff --git a/lib/impure/nre/private/pcre_src/pcre_exec.c b/lib/impure/nre/private/pcre_src/pcre_exec.c deleted file mode 100644 index 654eb9e27..000000000 --- a/lib/impure/nre/private/pcre_src/pcre_exec.c +++ /dev/null @@ -1,7160 +0,0 @@ -/************************************************* -* Perl-Compatible Regular Expressions * -*************************************************/ - -/* PCRE is a library of functions to support regular expressions whose syntax -and semantics are as close as possible to those of the Perl 5 language. - - Written by Philip Hazel - Copyright (c) 1997-2014 University of Cambridge - ------------------------------------------------------------------------------ -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - * Neither the name of the University of Cambridge nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ -*/ - -/* This module contains pcre_exec(), the externally visible function that does -pattern matching using an NFA algorithm, trying to mimic Perl as closely as -possible. There are also some static supporting functions. */ - -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - -#define NLBLOCK md /* Block containing newline information */ -#define PSSTART start_subject /* Field containing processed string start */ -#define PSEND end_subject /* Field containing processed string end */ - -#include "pcre_internal.h" - -/* Undefine some potentially clashing cpp symbols */ - -#undef min -#undef max - -/* The md->capture_last field uses the lower 16 bits for the last captured -substring (which can never be greater than 65535) and a bit in the top half -to mean "capture vector overflowed". This odd way of doing things was -implemented when it was realized that preserving and restoring the overflow bit -whenever the last capture number was saved/restored made for a neater -interface, and doing it this way saved on (a) another variable, which would -have increased the stack frame size (a big NO-NO in PCRE) and (b) another -separate set of save/restore instructions. The following defines are used in -implementing this. */ - -#define CAPLMASK 0x0000ffff /* The bits used for last_capture */ -#define OVFLMASK 0xffff0000 /* The bits used for the overflow flag */ -#define OVFLBIT 0x00010000 /* The bit that is set for overflow */ - -/* Values for setting in md->match_function_type to indicate two special types -of call to match(). We do it this way to save on using another stack variable, -as stack usage is to be discouraged. */ - -#define MATCH_CONDASSERT 1 /* Called to check a condition assertion */ -#define MATCH_CBEGROUP 2 /* Could-be-empty unlimited repeat group */ - -/* Non-error returns from the match() function. Error returns are externally -defined PCRE_ERROR_xxx codes, which are all negative. */ - -#define MATCH_MATCH 1 -#define MATCH_NOMATCH 0 - -/* Special internal returns from the match() function. Make them sufficiently -negative to avoid the external error codes. */ - -#define MATCH_ACCEPT (-999) -#define MATCH_KETRPOS (-998) -#define MATCH_ONCE (-997) -/* The next 5 must be kept together and in sequence so that a test that checks -for any one of them can use a range. */ -#define MATCH_COMMIT (-996) -#define MATCH_PRUNE (-995) -#define MATCH_SKIP (-994) -#define MATCH_SKIP_ARG (-993) -#define MATCH_THEN (-992) -#define MATCH_BACKTRACK_MAX MATCH_THEN -#define MATCH_BACKTRACK_MIN MATCH_COMMIT - -/* Maximum number of ints of offset to save on the stack for recursive calls. -If the offset vector is bigger, malloc is used. This should be a multiple of 3, -because the offset vector is always a multiple of 3 long. */ - -#define REC_STACK_SAVE_MAX 30 - -/* Min and max values for the common repeats; for the maxima, 0 => infinity */ - -static const char rep_min[] = { 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, }; -static const char rep_max[] = { 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, }; - -#ifdef PCRE_DEBUG -/************************************************* -* Debugging function to print chars * -*************************************************/ - -/* Print a sequence of chars in printable format, stopping at the end of the -subject if the requested. - -Arguments: - p points to characters - length number to print - is_subject TRUE if printing from within md->start_subject - md pointer to matching data block, if is_subject is TRUE - -Returns: nothing -*/ - -static void -pchars(const pcre_uchar *p, int length, BOOL is_subject, match_data *md) -{ -pcre_uint32 c; -BOOL utf = md->utf; -if (is_subject && length > md->end_subject - p) length = md->end_subject - p; -while (length-- > 0) - if (isprint(c = UCHAR21INCTEST(p))) printf("%c", (char)c); else printf("\\x{%02x}", c); -} -#endif - - - -/************************************************* -* Match a back-reference * -*************************************************/ - -/* Normally, if a back reference hasn't been set, the length that is passed is -negative, so the match always fails. However, in JavaScript compatibility mode, -the length passed is zero. Note that in caseless UTF-8 mode, the number of -subject bytes matched may be different to the number of reference bytes. - -Arguments: - offset index into the offset vector - eptr pointer into the subject - length length of reference to be matched (number of bytes) - md points to match data block - caseless TRUE if caseless - -Returns: >= 0 the number of subject bytes matched - -1 no match - -2 partial match; always given if at end subject -*/ - -static int -match_ref(int offset, register PCRE_PUCHAR eptr, int length, match_data *md, - BOOL caseless) -{ -PCRE_PUCHAR eptr_start = eptr; -register PCRE_PUCHAR p = md->start_subject + md->offset_vector[offset]; -#if defined SUPPORT_UTF && defined SUPPORT_UCP -BOOL utf = md->utf; -#endif - -#ifdef PCRE_DEBUG -if (eptr >= md->end_subject) - printf("matching subject "); -else - { - printf("matching subject "); - pchars(eptr, length, TRUE, md); - } -printf(" against backref "); -pchars(p, length, FALSE, md); -printf("\n"); -#endif - -/* Always fail if reference not set (and not JavaScript compatible - in that -case the length is passed as zero). */ - -if (length < 0) return -1; - -/* Separate the caseless case for speed. In UTF-8 mode we can only do this -properly if Unicode properties are supported. Otherwise, we can check only -ASCII characters. */ - -if (caseless) - { -#if defined SUPPORT_UTF && defined SUPPORT_UCP - if (utf) - { - /* Match characters up to the end of the reference. NOTE: the number of - data units matched may differ, because in UTF-8 there are some characters - whose upper and lower case versions code have different numbers of bytes. - For example, U+023A (2 bytes in UTF-8) is the upper case version of U+2C65 - (3 bytes in UTF-8); a sequence of 3 of the former uses 6 bytes, as does a - sequence of two of the latter. It is important, therefore, to check the - length along the reference, not along the subject (earlier code did this - wrong). */ - - PCRE_PUCHAR endptr = p + length; - while (p < endptr) - { - pcre_uint32 c, d; - const ucd_record *ur; - if (eptr >= md->end_subject) return -2; /* Partial match */ - GETCHARINC(c, eptr); - GETCHARINC(d, p); - ur = GET_UCD(d); - if (c != d && c != d + ur->other_case) - { - const pcre_uint32 *pp = PRIV(ucd_caseless_sets) + ur->caseset; - for (;;) - { - if (c < *pp) return -1; - if (c == *pp++) break; - } - } - } - } - else -#endif - - /* The same code works when not in UTF-8 mode and in UTF-8 mode when there - is no UCP support. */ - { - while (length-- > 0) - { - pcre_uint32 cc, cp; - if (eptr >= md->end_subject) return -2; /* Partial match */ - cc = UCHAR21TEST(eptr); - cp = UCHAR21TEST(p); - if (TABLE_GET(cp, md->lcc, cp) != TABLE_GET(cc, md->lcc, cc)) return -1; - p++; - eptr++; - } - } - } - -/* In the caseful case, we can just compare the bytes, whether or not we -are in UTF-8 mode. */ - -else - { - while (length-- > 0) - { - if (eptr >= md->end_subject) return -2; /* Partial match */ - if (UCHAR21INCTEST(p) != UCHAR21INCTEST(eptr)) return -1; - } - } - -return (int)(eptr - eptr_start); -} - - - -/*************************************************************************** -**************************************************************************** - RECURSION IN THE match() FUNCTION - -The match() function is highly recursive, though not every recursive call -increases the recursive depth. Nevertheless, some regular expressions can cause -it to recurse to a great depth. I was writing for Unix, so I just let it call -itself recursively. This uses the stack for saving everything that has to be -saved for a recursive call. On Unix, the stack can be large, and this works -fine. - -It turns out that on some non-Unix-like systems there are problems with -programs that use a lot of stack. (This despite the fact that every last chip -has oodles of memory these days, and techniques for extending the stack have -been known for decades.) So.... - -There is a fudge, triggered by defining NO_RECURSE, which avoids recursive -calls by keeping local variables that need to be preserved in blocks of memory -obtained from malloc() instead instead of on the stack. Macros are used to -achieve this so that the actual code doesn't look very different to what it -always used to. - -The original heap-recursive code used longjmp(). However, it seems that this -can be very slow on some operating systems. Following a suggestion from Stan -Switzer, the use of longjmp() has been abolished, at the cost of having to -provide a unique number for each call to RMATCH. There is no way of generating -a sequence of numbers at compile time in C. I have given them names, to make -them stand out more clearly. - -Crude tests on x86 Linux show a small speedup of around 5-8%. However, on -FreeBSD, avoiding longjmp() more than halves the time taken to run the standard -tests. Furthermore, not using longjmp() means that local dynamic variables -don't have indeterminate values; this has meant that the frame size can be -reduced because the result can be "passed back" by straight setting of the -variable instead of being passed in the frame. -**************************************************************************** -***************************************************************************/ - -/* Numbers for RMATCH calls. When this list is changed, the code at HEAP_RETURN -below must be updated in sync. */ - -enum { RM1=1, RM2, RM3, RM4, RM5, RM6, RM7, RM8, RM9, RM10, - RM11, RM12, RM13, RM14, RM15, RM16, RM17, RM18, RM19, RM20, - RM21, RM22, RM23, RM24, RM25, RM26, RM27, RM28, RM29, RM30, - RM31, RM32, RM33, RM34, RM35, RM36, RM37, RM38, RM39, RM40, - RM41, RM42, RM43, RM44, RM45, RM46, RM47, RM48, RM49, RM50, - RM51, RM52, RM53, RM54, RM55, RM56, RM57, RM58, RM59, RM60, - RM61, RM62, RM63, RM64, RM65, RM66, RM67 }; - -/* These versions of the macros use the stack, as normal. There are debugging -versions and production versions. Note that the "rw" argument of RMATCH isn't -actually used in this definition. */ - -#ifndef NO_RECURSE -#define REGISTER register - -#ifdef PCRE_DEBUG -#define RMATCH(ra,rb,rc,rd,re,rw) \ - { \ - printf("match() called in line %d\n", __LINE__); \ - rrc = match(ra,rb,mstart,rc,rd,re,rdepth+1); \ - printf("to line %d\n", __LINE__); \ - } -#define RRETURN(ra) \ - { \ - printf("match() returned %d from line %d\n", ra, __LINE__); \ - return ra; \ - } -#else -#define RMATCH(ra,rb,rc,rd,re,rw) \ - rrc = match(ra,rb,mstart,rc,rd,re,rdepth+1) -#define RRETURN(ra) return ra -#endif - -#else - - -/* These versions of the macros manage a private stack on the heap. Note that -the "rd" argument of RMATCH isn't actually used in this definition. It's the md -argument of match(), which never changes. */ - -#define REGISTER - -#define RMATCH(ra,rb,rc,rd,re,rw)\ - {\ - heapframe *newframe = frame->Xnextframe;\ - if (newframe == NULL)\ - {\ - newframe = (heapframe *)(PUBL(stack_malloc))(sizeof(heapframe));\ - if (newframe == NULL) RRETURN(PCRE_ERROR_NOMEMORY);\ - newframe->Xnextframe = NULL;\ - frame->Xnextframe = newframe;\ - }\ - frame->Xwhere = rw;\ - newframe->Xeptr = ra;\ - newframe->Xecode = rb;\ - newframe->Xmstart = mstart;\ - newframe->Xoffset_top = rc;\ - newframe->Xeptrb = re;\ - newframe->Xrdepth = frame->Xrdepth + 1;\ - newframe->Xprevframe = frame;\ - frame = newframe;\ - DPRINTF(("restarting from line %d\n", __LINE__));\ - goto HEAP_RECURSE;\ - L_##rw:\ - DPRINTF(("jumped back to line %d\n", __LINE__));\ - } - -#define RRETURN(ra)\ - {\ - heapframe *oldframe = frame;\ - frame = oldframe->Xprevframe;\ - if (frame != NULL)\ - {\ - rrc = ra;\ - goto HEAP_RETURN;\ - }\ - return ra;\ - } - - -/* Structure for remembering the local variables in a private frame */ - -typedef struct heapframe { - struct heapframe *Xprevframe; - struct heapframe *Xnextframe; - - /* Function arguments that may change */ - - PCRE_PUCHAR Xeptr; - const pcre_uchar *Xecode; - PCRE_PUCHAR Xmstart; - int Xoffset_top; - eptrblock *Xeptrb; - unsigned int Xrdepth; - - /* Function local variables */ - - PCRE_PUCHAR Xcallpat; -#ifdef SUPPORT_UTF - PCRE_PUCHAR Xcharptr; -#endif - PCRE_PUCHAR Xdata; - PCRE_PUCHAR Xnext; - PCRE_PUCHAR Xpp; - PCRE_PUCHAR Xprev; - PCRE_PUCHAR Xsaved_eptr; - - recursion_info Xnew_recursive; - - BOOL Xcur_is_word; - BOOL Xcondition; - BOOL Xprev_is_word; - -#ifdef SUPPORT_UCP - int Xprop_type; - unsigned int Xprop_value; - int Xprop_fail_result; - int Xoclength; - pcre_uchar Xocchars[6]; -#endif - - int Xcodelink; - int Xctype; - unsigned int Xfc; - int Xfi; - int Xlength; - int Xmax; - int Xmin; - unsigned int Xnumber; - int Xoffset; - unsigned int Xop; - pcre_int32 Xsave_capture_last; - int Xsave_offset1, Xsave_offset2, Xsave_offset3; - int Xstacksave[REC_STACK_SAVE_MAX]; - - eptrblock Xnewptrb; - - /* Where to jump back to */ - - int Xwhere; - -} heapframe; - -#endif - - -/*************************************************************************** -***************************************************************************/ - - - -/************************************************* -* Match from current position * -*************************************************/ - -/* This function is called recursively in many circumstances. Whenever it -returns a negative (error) response, the outer incarnation must also return the -same response. */ - -/* These macros pack up tests that are used for partial matching, and which -appear several times in the code. We set the "hit end" flag if the pointer is -at the end of the subject and also past the start of the subject (i.e. -something has been matched). For hard partial matching, we then return -immediately. The second one is used when we already know we are past the end of -the subject. */ - -#define CHECK_PARTIAL()\ - if (md->partial != 0 && eptr >= md->end_subject && \ - eptr > md->start_used_ptr) \ - { \ - md->hitend = TRUE; \ - if (md->partial > 1) RRETURN(PCRE_ERROR_PARTIAL); \ - } - -#define SCHECK_PARTIAL()\ - if (md->partial != 0 && eptr > md->start_used_ptr) \ - { \ - md->hitend = TRUE; \ - if (md->partial > 1) RRETURN(PCRE_ERROR_PARTIAL); \ - } - - -/* Performance note: It might be tempting to extract commonly used fields from -the md structure (e.g. utf, end_subject) into individual variables to improve -performance. Tests using gcc on a SPARC disproved this; in the first case, it -made performance worse. - -Arguments: - eptr pointer to current character in subject - ecode pointer to current position in compiled code - mstart pointer to the current match start position (can be modified - by encountering \K) - offset_top current top pointer - md pointer to "static" info for the match - eptrb pointer to chain of blocks containing eptr at start of - brackets - for testing for empty matches - rdepth the recursion depth - -Returns: MATCH_MATCH if matched ) these values are >= 0 - MATCH_NOMATCH if failed to match ) - a negative MATCH_xxx value for PRUNE, SKIP, etc - a negative PCRE_ERROR_xxx value if aborted by an error condition - (e.g. stopped by repeated call or recursion limit) -*/ - -static int -match(REGISTER PCRE_PUCHAR eptr, REGISTER const pcre_uchar *ecode, - PCRE_PUCHAR mstart, int offset_top, match_data *md, eptrblock *eptrb, - unsigned int rdepth) -{ -/* These variables do not need to be preserved over recursion in this function, -so they can be ordinary variables in all cases. Mark some of them with -"register" because they are used a lot in loops. */ - -register int rrc; /* Returns from recursive calls */ -register int i; /* Used for loops not involving calls to RMATCH() */ -register pcre_uint32 c; /* Character values not kept over RMATCH() calls */ -register BOOL utf; /* Local copy of UTF flag for speed */ - -BOOL minimize, possessive; /* Quantifier options */ -BOOL caseless; -int condcode; - -/* When recursion is not being used, all "local" variables that have to be -preserved over calls to RMATCH() are part of a "frame". We set up the top-level -frame on the stack here; subsequent instantiations are obtained from the heap -whenever RMATCH() does a "recursion". See the macro definitions above. Putting -the top-level on the stack rather than malloc-ing them all gives a performance -boost in many cases where there is not much "recursion". */ - -#ifdef NO_RECURSE -heapframe *frame = (heapframe *)md->match_frames_base; - -/* Copy in the original argument variables */ - -frame->Xeptr = eptr; -frame->Xecode = ecode; -frame->Xmstart = mstart; -frame->Xoffset_top = offset_top; -frame->Xeptrb = eptrb; -frame->Xrdepth = rdepth; - -/* This is where control jumps back to to effect "recursion" */ - -HEAP_RECURSE: - -/* Macros make the argument variables come from the current frame */ - -#define eptr frame->Xeptr -#define ecode frame->Xecode -#define mstart frame->Xmstart -#define offset_top frame->Xoffset_top -#define eptrb frame->Xeptrb -#define rdepth frame->Xrdepth - -/* Ditto for the local variables */ - -#ifdef SUPPORT_UTF -#define charptr frame->Xcharptr -#endif -#define callpat frame->Xcallpat -#define codelink frame->Xcodelink -#define data frame->Xdata -#define next frame->Xnext -#define pp frame->Xpp -#define prev frame->Xprev -#define saved_eptr frame->Xsaved_eptr - -#define new_recursive frame->Xnew_recursive - -#define cur_is_word frame->Xcur_is_word -#define condition frame->Xcondition -#define prev_is_word frame->Xprev_is_word - -#ifdef SUPPORT_UCP -#define prop_type frame->Xprop_type -#define prop_value frame->Xprop_value -#define prop_fail_result frame->Xprop_fail_result -#define oclength frame->Xoclength -#define occhars frame->Xocchars -#endif - -#define ctype frame->Xctype -#define fc frame->Xfc -#define fi frame->Xfi -#define length frame->Xlength -#define max frame->Xmax -#define min frame->Xmin -#define number frame->Xnumber -#define offset frame->Xoffset -#define op frame->Xop -#define save_capture_last frame->Xsave_capture_last -#define save_offset1 frame->Xsave_offset1 -#define save_offset2 frame->Xsave_offset2 -#define save_offset3 frame->Xsave_offset3 -#define stacksave frame->Xstacksave - -#define newptrb frame->Xnewptrb - -/* When recursion is being used, local variables are allocated on the stack and -get preserved during recursion in the normal way. In this environment, fi and -i, and fc and c, can be the same variables. */ - -#else /* NO_RECURSE not defined */ -#define fi i -#define fc c - -/* Many of the following variables are used only in small blocks of the code. -My normal style of coding would have declared them within each of those blocks. -However, in order to accommodate the version of this code that uses an external -"stack" implemented on the heap, it is easier to declare them all here, so the -declarations can be cut out in a block. The only declarations within blocks -below are for variables that do not have to be preserved over a recursive call -to RMATCH(). */ - -#ifdef SUPPORT_UTF -const pcre_uchar *charptr; -#endif -const pcre_uchar *callpat; -const pcre_uchar *data; -const pcre_uchar *next; -PCRE_PUCHAR pp; -const pcre_uchar *prev; -PCRE_PUCHAR saved_eptr; - -recursion_info new_recursive; - -BOOL cur_is_word; -BOOL condition; -BOOL prev_is_word; - -#ifdef SUPPORT_UCP -int prop_type; -unsigned int prop_value; -int prop_fail_result; -int oclength; -pcre_uchar occhars[6]; -#endif - -int codelink; -int ctype; -int length; -int max; -int min; -unsigned int number; -int offset; -unsigned int op; -pcre_int32 save_capture_last; -int save_offset1, save_offset2, save_offset3; -int stacksave[REC_STACK_SAVE_MAX]; - -eptrblock newptrb; - -/* There is a special fudge for calling match() in a way that causes it to -measure the size of its basic stack frame when the stack is being used for -recursion. The second argument (ecode) being NULL triggers this behaviour. It -cannot normally ever be NULL. The return is the negated value of the frame -size. */ - -if (ecode == NULL) - { - if (rdepth == 0) - return match((PCRE_PUCHAR)&rdepth, NULL, NULL, 0, NULL, NULL, 1); - else - { - int len = (char *)&rdepth - (char *)eptr; - return (len > 0)? -len : len; - } - } -#endif /* NO_RECURSE */ - -/* To save space on the stack and in the heap frame, I have doubled up on some -of the local variables that are used only in localised parts of the code, but -still need to be preserved over recursive calls of match(). These macros define -the alternative names that are used. */ - -#define allow_zero cur_is_word -#define cbegroup condition -#define code_offset codelink -#define condassert condition -#define matched_once prev_is_word -#define foc number -#define save_mark data - -/* These statements are here to stop the compiler complaining about unitialized -variables. */ - -#ifdef SUPPORT_UCP -prop_value = 0; -prop_fail_result = 0; -#endif - - -/* This label is used for tail recursion, which is used in a few cases even -when NO_RECURSE is not defined, in order to reduce the amount of stack that is -used. Thanks to Ian Taylor for noticing this possibility and sending the -original patch. */ - -TAIL_RECURSE: - -/* OK, now we can get on with the real code of the function. Recursive calls -are specified by the macro RMATCH and RRETURN is used to return. When -NO_RECURSE is *not* defined, these just turn into a recursive call to match() -and a "return", respectively (possibly with some debugging if PCRE_DEBUG is -defined). However, RMATCH isn't like a function call because it's quite a -complicated macro. It has to be used in one particular way. This shouldn't, -however, impact performance when true recursion is being used. */ - -#ifdef SUPPORT_UTF -utf = md->utf; /* Local copy of the flag */ -#else -utf = FALSE; -#endif - -/* First check that we haven't called match() too many times, or that we -haven't exceeded the recursive call limit. */ - -if (md->match_call_count++ >= md->match_limit) RRETURN(PCRE_ERROR_MATCHLIMIT); -if (rdepth >= md->match_limit_recursion) RRETURN(PCRE_ERROR_RECURSIONLIMIT); - -/* At the start of a group with an unlimited repeat that may match an empty -string, the variable md->match_function_type is set to MATCH_CBEGROUP. It is -done this way to save having to use another function argument, which would take -up space on the stack. See also MATCH_CONDASSERT below. - -When MATCH_CBEGROUP is set, add the current subject pointer to the chain of -such remembered pointers, to be checked when we hit the closing ket, in order -to break infinite loops that match no characters. When match() is called in -other circumstances, don't add to the chain. The MATCH_CBEGROUP feature must -NOT be used with tail recursion, because the memory block that is used is on -the stack, so a new one may be required for each match(). */ - -if (md->match_function_type == MATCH_CBEGROUP) - { - newptrb.epb_saved_eptr = eptr; - newptrb.epb_prev = eptrb; - eptrb = &newptrb; - md->match_function_type = 0; - } - -/* Now start processing the opcodes. */ - -for (;;) - { - minimize = possessive = FALSE; - op = *ecode; - - switch(op) - { - case OP_MARK: - md->nomatch_mark = ecode + 2; - md->mark = NULL; /* In case previously set by assertion */ - RMATCH(eptr, ecode + PRIV(OP_lengths)[*ecode] + ecode[1], offset_top, md, - eptrb, RM55); - if ((rrc == MATCH_MATCH || rrc == MATCH_ACCEPT) && - md->mark == NULL) md->mark = ecode + 2; - - /* A return of MATCH_SKIP_ARG means that matching failed at SKIP with an - argument, and we must check whether that argument matches this MARK's - argument. It is passed back in md->start_match_ptr (an overloading of that - variable). If it does match, we reset that variable to the current subject - position and return MATCH_SKIP. Otherwise, pass back the return code - unaltered. */ - - else if (rrc == MATCH_SKIP_ARG && - STRCMP_UC_UC_TEST(ecode + 2, md->start_match_ptr) == 0) - { - md->start_match_ptr = eptr; - RRETURN(MATCH_SKIP); - } - RRETURN(rrc); - - case OP_FAIL: - RRETURN(MATCH_NOMATCH); - - case OP_COMMIT: - RMATCH(eptr, ecode + PRIV(OP_lengths)[*ecode], offset_top, md, - eptrb, RM52); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - RRETURN(MATCH_COMMIT); - - case OP_PRUNE: - RMATCH(eptr, ecode + PRIV(OP_lengths)[*ecode], offset_top, md, - eptrb, RM51); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - RRETURN(MATCH_PRUNE); - - case OP_PRUNE_ARG: - md->nomatch_mark = ecode + 2; - md->mark = NULL; /* In case previously set by assertion */ - RMATCH(eptr, ecode + PRIV(OP_lengths)[*ecode] + ecode[1], offset_top, md, - eptrb, RM56); - if ((rrc == MATCH_MATCH || rrc == MATCH_ACCEPT) && - md->mark == NULL) md->mark = ecode + 2; - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - RRETURN(MATCH_PRUNE); - - case OP_SKIP: - RMATCH(eptr, ecode + PRIV(OP_lengths)[*ecode], offset_top, md, - eptrb, RM53); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - md->start_match_ptr = eptr; /* Pass back current position */ - RRETURN(MATCH_SKIP); - - /* Note that, for Perl compatibility, SKIP with an argument does NOT set - nomatch_mark. When a pattern match ends with a SKIP_ARG for which there was - not a matching mark, we have to re-run the match, ignoring the SKIP_ARG - that failed and any that precede it (either they also failed, or were not - triggered). To do this, we maintain a count of executed SKIP_ARGs. If a - SKIP_ARG gets to top level, the match is re-run with md->ignore_skip_arg - set to the count of the one that failed. */ - - case OP_SKIP_ARG: - md->skip_arg_count++; - if (md->skip_arg_count <= md->ignore_skip_arg) - { - ecode += PRIV(OP_lengths)[*ecode] + ecode[1]; - break; - } - RMATCH(eptr, ecode + PRIV(OP_lengths)[*ecode] + ecode[1], offset_top, md, - eptrb, RM57); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - - /* Pass back the current skip name by overloading md->start_match_ptr and - returning the special MATCH_SKIP_ARG return code. This will either be - caught by a matching MARK, or get to the top, where it causes a rematch - with md->ignore_skip_arg set to the value of md->skip_arg_count. */ - - md->start_match_ptr = ecode + 2; - RRETURN(MATCH_SKIP_ARG); - - /* For THEN (and THEN_ARG) we pass back the address of the opcode, so that - the branch in which it occurs can be determined. Overload the start of - match pointer to do this. */ - - case OP_THEN: - RMATCH(eptr, ecode + PRIV(OP_lengths)[*ecode], offset_top, md, - eptrb, RM54); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - md->start_match_ptr = ecode; - RRETURN(MATCH_THEN); - - case OP_THEN_ARG: - md->nomatch_mark = ecode + 2; - md->mark = NULL; /* In case previously set by assertion */ - RMATCH(eptr, ecode + PRIV(OP_lengths)[*ecode] + ecode[1], offset_top, - md, eptrb, RM58); - if ((rrc == MATCH_MATCH || rrc == MATCH_ACCEPT) && - md->mark == NULL) md->mark = ecode + 2; - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - md->start_match_ptr = ecode; - RRETURN(MATCH_THEN); - - /* Handle an atomic group that does not contain any capturing parentheses. - This can be handled like an assertion. Prior to 8.13, all atomic groups - were handled this way. In 8.13, the code was changed as below for ONCE, so - that backups pass through the group and thereby reset captured values. - However, this uses a lot more stack, so in 8.20, atomic groups that do not - contain any captures generate OP_ONCE_NC, which can be handled in the old, - less stack intensive way. - - Check the alternative branches in turn - the matching won't pass the KET - for this kind of subpattern. If any one branch matches, we carry on as at - the end of a normal bracket, leaving the subject pointer, but resetting - the start-of-match value in case it was changed by \K. */ - - case OP_ONCE_NC: - prev = ecode; - saved_eptr = eptr; - save_mark = md->mark; - do - { - RMATCH(eptr, ecode + 1 + LINK_SIZE, offset_top, md, eptrb, RM64); - if (rrc == MATCH_MATCH) /* Note: _not_ MATCH_ACCEPT */ - { - mstart = md->start_match_ptr; - break; - } - if (rrc == MATCH_THEN) - { - next = ecode + GET(ecode,1); - if (md->start_match_ptr < next && - (*ecode == OP_ALT || *next == OP_ALT)) - rrc = MATCH_NOMATCH; - } - - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - ecode += GET(ecode,1); - md->mark = save_mark; - } - while (*ecode == OP_ALT); - - /* If hit the end of the group (which could be repeated), fail */ - - if (*ecode != OP_ONCE_NC && *ecode != OP_ALT) RRETURN(MATCH_NOMATCH); - - /* Continue as from after the group, updating the offsets high water - mark, since extracts may have been taken. */ - - do ecode += GET(ecode, 1); while (*ecode == OP_ALT); - - offset_top = md->end_offset_top; - eptr = md->end_match_ptr; - - /* For a non-repeating ket, just continue at this level. This also - happens for a repeating ket if no characters were matched in the group. - This is the forcible breaking of infinite loops as implemented in Perl - 5.005. */ - - if (*ecode == OP_KET || eptr == saved_eptr) - { - ecode += 1+LINK_SIZE; - break; - } - - /* The repeating kets try the rest of the pattern or restart from the - preceding bracket, in the appropriate order. The second "call" of match() - uses tail recursion, to avoid using another stack frame. */ - - if (*ecode == OP_KETRMIN) - { - RMATCH(eptr, ecode + 1 + LINK_SIZE, offset_top, md, eptrb, RM65); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - ecode = prev; - goto TAIL_RECURSE; - } - else /* OP_KETRMAX */ - { - RMATCH(eptr, prev, offset_top, md, eptrb, RM66); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - ecode += 1 + LINK_SIZE; - goto TAIL_RECURSE; - } - /* Control never gets here */ - - /* Handle a capturing bracket, other than those that are possessive with an - unlimited repeat. If there is space in the offset vector, save the current - subject position in the working slot at the top of the vector. We mustn't - change the current values of the data slot, because they may be set from a - previous iteration of this group, and be referred to by a reference inside - the group. A failure to match might occur after the group has succeeded, - if something later on doesn't match. For this reason, we need to restore - the working value and also the values of the final offsets, in case they - were set by a previous iteration of the same bracket. - - If there isn't enough space in the offset vector, treat this as if it were - a non-capturing bracket. Don't worry about setting the flag for the error - case here; that is handled in the code for KET. */ - - case OP_CBRA: - case OP_SCBRA: - number = GET2(ecode, 1+LINK_SIZE); - offset = number << 1; - -#ifdef PCRE_DEBUG - printf("start bracket %d\n", number); - printf("subject="); - pchars(eptr, 16, TRUE, md); - printf("\n"); -#endif - - if (offset < md->offset_max) - { - save_offset1 = md->offset_vector[offset]; - save_offset2 = md->offset_vector[offset+1]; - save_offset3 = md->offset_vector[md->offset_end - number]; - save_capture_last = md->capture_last; - save_mark = md->mark; - - DPRINTF(("saving %d %d %d\n", save_offset1, save_offset2, save_offset3)); - md->offset_vector[md->offset_end - number] = - (int)(eptr - md->start_subject); - - for (;;) - { - if (op >= OP_SBRA) md->match_function_type = MATCH_CBEGROUP; - RMATCH(eptr, ecode + PRIV(OP_lengths)[*ecode], offset_top, md, - eptrb, RM1); - if (rrc == MATCH_ONCE) break; /* Backing up through an atomic group */ - - /* If we backed up to a THEN, check whether it is within the current - branch by comparing the address of the THEN that is passed back with - the end of the branch. If it is within the current branch, and the - branch is one of two or more alternatives (it either starts or ends - with OP_ALT), we have reached the limit of THEN's action, so convert - the return code to NOMATCH, which will cause normal backtracking to - happen from now on. Otherwise, THEN is passed back to an outer - alternative. This implements Perl's treatment of parenthesized groups, - where a group not containing | does not affect the current alternative, - that is, (X) is NOT the same as (X|(*F)). */ - - if (rrc == MATCH_THEN) - { - next = ecode + GET(ecode,1); - if (md->start_match_ptr < next && - (*ecode == OP_ALT || *next == OP_ALT)) - rrc = MATCH_NOMATCH; - } - - /* Anything other than NOMATCH is passed back. */ - - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - md->capture_last = save_capture_last; - ecode += GET(ecode, 1); - md->mark = save_mark; - if (*ecode != OP_ALT) break; - } - - DPRINTF(("bracket %d failed\n", number)); - md->offset_vector[offset] = save_offset1; - md->offset_vector[offset+1] = save_offset2; - md->offset_vector[md->offset_end - number] = save_offset3; - - /* At this point, rrc will be one of MATCH_ONCE or MATCH_NOMATCH. */ - - RRETURN(rrc); - } - - /* FALL THROUGH ... Insufficient room for saving captured contents. Treat - as a non-capturing bracket. */ - - /* VVVVVVVVVVVVVVVVVVVVVVVVV */ - /* VVVVVVVVVVVVVVVVVVVVVVVVV */ - - DPRINTF(("insufficient capture room: treat as non-capturing\n")); - - /* VVVVVVVVVVVVVVVVVVVVVVVVV */ - /* VVVVVVVVVVVVVVVVVVVVVVVVV */ - - /* Non-capturing or atomic group, except for possessive with unlimited - repeat and ONCE group with no captures. Loop for all the alternatives. - - When we get to the final alternative within the brackets, we used to return - the result of a recursive call to match() whatever happened so it was - possible to reduce stack usage by turning this into a tail recursion, - except in the case of a possibly empty group. However, now that there is - the possiblity of (*THEN) occurring in the final alternative, this - optimization is no longer always possible. - - We can optimize if we know there are no (*THEN)s in the pattern; at present - this is the best that can be done. - - MATCH_ONCE is returned when the end of an atomic group is successfully - reached, but subsequent matching fails. It passes back up the tree (causing - captured values to be reset) until the original atomic group level is - reached. This is tested by comparing md->once_target with the start of the - group. At this point, the return is converted into MATCH_NOMATCH so that - previous backup points can be taken. */ - - case OP_ONCE: - case OP_BRA: - case OP_SBRA: - DPRINTF(("start non-capturing bracket\n")); - - for (;;) - { - if (op >= OP_SBRA || op == OP_ONCE) - md->match_function_type = MATCH_CBEGROUP; - - /* If this is not a possibly empty group, and there are no (*THEN)s in - the pattern, and this is the final alternative, optimize as described - above. */ - - else if (!md->hasthen && ecode[GET(ecode, 1)] != OP_ALT) - { - ecode += PRIV(OP_lengths)[*ecode]; - goto TAIL_RECURSE; - } - - /* In all other cases, we have to make another call to match(). */ - - save_mark = md->mark; - save_capture_last = md->capture_last; - RMATCH(eptr, ecode + PRIV(OP_lengths)[*ecode], offset_top, md, eptrb, - RM2); - - /* See comment in the code for capturing groups above about handling - THEN. */ - - if (rrc == MATCH_THEN) - { - next = ecode + GET(ecode,1); - if (md->start_match_ptr < next && - (*ecode == OP_ALT || *next == OP_ALT)) - rrc = MATCH_NOMATCH; - } - - if (rrc != MATCH_NOMATCH) - { - if (rrc == MATCH_ONCE) - { - const pcre_uchar *scode = ecode; - if (*scode != OP_ONCE) /* If not at start, find it */ - { - while (*scode == OP_ALT) scode += GET(scode, 1); - scode -= GET(scode, 1); - } - if (md->once_target == scode) rrc = MATCH_NOMATCH; - } - RRETURN(rrc); - } - ecode += GET(ecode, 1); - md->mark = save_mark; - if (*ecode != OP_ALT) break; - md->capture_last = save_capture_last; - } - - RRETURN(MATCH_NOMATCH); - - /* Handle possessive capturing brackets with an unlimited repeat. We come - here from BRAZERO with allow_zero set TRUE. The offset_vector values are - handled similarly to the normal case above. However, the matching is - different. The end of these brackets will always be OP_KETRPOS, which - returns MATCH_KETRPOS without going further in the pattern. By this means - we can handle the group by iteration rather than recursion, thereby - reducing the amount of stack needed. */ - - case OP_CBRAPOS: - case OP_SCBRAPOS: - allow_zero = FALSE; - - POSSESSIVE_CAPTURE: - number = GET2(ecode, 1+LINK_SIZE); - offset = number << 1; - -#ifdef PCRE_DEBUG - printf("start possessive bracket %d\n", number); - printf("subject="); - pchars(eptr, 16, TRUE, md); - printf("\n"); -#endif - - if (offset < md->offset_max) - { - matched_once = FALSE; - code_offset = (int)(ecode - md->start_code); - - save_offset1 = md->offset_vector[offset]; - save_offset2 = md->offset_vector[offset+1]; - save_offset3 = md->offset_vector[md->offset_end - number]; - save_capture_last = md->capture_last; - - DPRINTF(("saving %d %d %d\n", save_offset1, save_offset2, save_offset3)); - - /* Each time round the loop, save the current subject position for use - when the group matches. For MATCH_MATCH, the group has matched, so we - restart it with a new subject starting position, remembering that we had - at least one match. For MATCH_NOMATCH, carry on with the alternatives, as - usual. If we haven't matched any alternatives in any iteration, check to - see if a previous iteration matched. If so, the group has matched; - continue from afterwards. Otherwise it has failed; restore the previous - capture values before returning NOMATCH. */ - - for (;;) - { - md->offset_vector[md->offset_end - number] = - (int)(eptr - md->start_subject); - if (op >= OP_SBRA) md->match_function_type = MATCH_CBEGROUP; - RMATCH(eptr, ecode + PRIV(OP_lengths)[*ecode], offset_top, md, - eptrb, RM63); - if (rrc == MATCH_KETRPOS) - { - offset_top = md->end_offset_top; - ecode = md->start_code + code_offset; - save_capture_last = md->capture_last; - matched_once = TRUE; - mstart = md->start_match_ptr; /* In case \K changed it */ - if (eptr == md->end_match_ptr) /* Matched an empty string */ - { - do ecode += GET(ecode, 1); while (*ecode == OP_ALT); - break; - } - eptr = md->end_match_ptr; - continue; - } - - /* See comment in the code for capturing groups above about handling - THEN. */ - - if (rrc == MATCH_THEN) - { - next = ecode + GET(ecode,1); - if (md->start_match_ptr < next && - (*ecode == OP_ALT || *next == OP_ALT)) - rrc = MATCH_NOMATCH; - } - - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - md->capture_last = save_capture_last; - ecode += GET(ecode, 1); - if (*ecode != OP_ALT) break; - } - - if (!matched_once) - { - md->offset_vector[offset] = save_offset1; - md->offset_vector[offset+1] = save_offset2; - md->offset_vector[md->offset_end - number] = save_offset3; - } - - if (allow_zero || matched_once) - { - ecode += 1 + LINK_SIZE; - break; - } - - RRETURN(MATCH_NOMATCH); - } - - /* FALL THROUGH ... Insufficient room for saving captured contents. Treat - as a non-capturing bracket. */ - - /* VVVVVVVVVVVVVVVVVVVVVVVVV */ - /* VVVVVVVVVVVVVVVVVVVVVVVVV */ - - DPRINTF(("insufficient capture room: treat as non-capturing\n")); - - /* VVVVVVVVVVVVVVVVVVVVVVVVV */ - /* VVVVVVVVVVVVVVVVVVVVVVVVV */ - - /* Non-capturing possessive bracket with unlimited repeat. We come here - from BRAZERO with allow_zero = TRUE. The code is similar to the above, - without the capturing complication. It is written out separately for speed - and cleanliness. */ - - case OP_BRAPOS: - case OP_SBRAPOS: - allow_zero = FALSE; - - POSSESSIVE_NON_CAPTURE: - matched_once = FALSE; - code_offset = (int)(ecode - md->start_code); - save_capture_last = md->capture_last; - - for (;;) - { - if (op >= OP_SBRA) md->match_function_type = MATCH_CBEGROUP; - RMATCH(eptr, ecode + PRIV(OP_lengths)[*ecode], offset_top, md, - eptrb, RM48); - if (rrc == MATCH_KETRPOS) - { - offset_top = md->end_offset_top; - ecode = md->start_code + code_offset; - matched_once = TRUE; - mstart = md->start_match_ptr; /* In case \K reset it */ - if (eptr == md->end_match_ptr) /* Matched an empty string */ - { - do ecode += GET(ecode, 1); while (*ecode == OP_ALT); - break; - } - eptr = md->end_match_ptr; - continue; - } - - /* See comment in the code for capturing groups above about handling - THEN. */ - - if (rrc == MATCH_THEN) - { - next = ecode + GET(ecode,1); - if (md->start_match_ptr < next && - (*ecode == OP_ALT || *next == OP_ALT)) - rrc = MATCH_NOMATCH; - } - - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - ecode += GET(ecode, 1); - if (*ecode != OP_ALT) break; - md->capture_last = save_capture_last; - } - - if (matched_once || allow_zero) - { - ecode += 1 + LINK_SIZE; - break; - } - RRETURN(MATCH_NOMATCH); - - /* Control never reaches here. */ - - /* Conditional group: compilation checked that there are no more than two - branches. If the condition is false, skipping the first branch takes us - past the end of the item if there is only one branch, but that's exactly - what we want. */ - - case OP_COND: - case OP_SCOND: - - /* The variable codelink will be added to ecode when the condition is - false, to get to the second branch. Setting it to the offset to the ALT - or KET, then incrementing ecode achieves this effect. We now have ecode - pointing to the condition or callout. */ - - codelink = GET(ecode, 1); /* Offset to the second branch */ - ecode += 1 + LINK_SIZE; /* From this opcode */ - - /* Because of the way auto-callout works during compile, a callout item is - inserted between OP_COND and an assertion condition. */ - - if (*ecode == OP_CALLOUT) - { - if (PUBL(callout) != NULL) - { - PUBL(callout_block) cb; - cb.version = 2; /* Version 1 of the callout block */ - cb.callout_number = ecode[1]; - cb.offset_vector = md->offset_vector; -#if defined COMPILE_PCRE8 - cb.subject = (PCRE_SPTR)md->start_subject; -#elif defined COMPILE_PCRE16 - cb.subject = (PCRE_SPTR16)md->start_subject; -#elif defined COMPILE_PCRE32 - cb.subject = (PCRE_SPTR32)md->start_subject; -#endif - cb.subject_length = (int)(md->end_subject - md->start_subject); - cb.start_match = (int)(mstart - md->start_subject); - cb.current_position = (int)(eptr - md->start_subject); - cb.pattern_position = GET(ecode, 2); - cb.next_item_length = GET(ecode, 2 + LINK_SIZE); - cb.capture_top = offset_top/2; - cb.capture_last = md->capture_last & CAPLMASK; - /* Internal change requires this for API compatibility. */ - if (cb.capture_last == 0) cb.capture_last = -1; - cb.callout_data = md->callout_data; - cb.mark = md->nomatch_mark; - if ((rrc = (*PUBL(callout))(&cb)) > 0) RRETURN(MATCH_NOMATCH); - if (rrc < 0) RRETURN(rrc); - } - - /* Advance ecode past the callout, so it now points to the condition. We - must adjust codelink so that the value of ecode+codelink is unchanged. */ - - ecode += PRIV(OP_lengths)[OP_CALLOUT]; - codelink -= PRIV(OP_lengths)[OP_CALLOUT]; - } - - /* Test the various possible conditions */ - - condition = FALSE; - switch(condcode = *ecode) - { - case OP_RREF: /* Numbered group recursion test */ - if (md->recursive != NULL) /* Not recursing => FALSE */ - { - unsigned int recno = GET2(ecode, 1); /* Recursion group number*/ - condition = (recno == RREF_ANY || recno == md->recursive->group_num); - } - break; - - case OP_DNRREF: /* Duplicate named group recursion test */ - if (md->recursive != NULL) - { - int count = GET2(ecode, 1 + IMM2_SIZE); - pcre_uchar *slot = md->name_table + GET2(ecode, 1) * md->name_entry_size; - while (count-- > 0) - { - unsigned int recno = GET2(slot, 0); - condition = recno == md->recursive->group_num; - if (condition) break; - slot += md->name_entry_size; - } - } - break; - - case OP_CREF: /* Numbered group used test */ - offset = GET2(ecode, 1) << 1; /* Doubled ref number */ - condition = offset < offset_top && md->offset_vector[offset] >= 0; - break; - - case OP_DNCREF: /* Duplicate named group used test */ - { - int count = GET2(ecode, 1 + IMM2_SIZE); - pcre_uchar *slot = md->name_table + GET2(ecode, 1) * md->name_entry_size; - while (count-- > 0) - { - offset = GET2(slot, 0) << 1; - condition = offset < offset_top && md->offset_vector[offset] >= 0; - if (condition) break; - slot += md->name_entry_size; - } - } - break; - - case OP_DEF: /* DEFINE - always false */ - break; - - /* The condition is an assertion. Call match() to evaluate it - setting - md->match_function_type to MATCH_CONDASSERT causes it to stop at the end - of an assertion. */ - - default: - md->match_function_type = MATCH_CONDASSERT; - RMATCH(eptr, ecode, offset_top, md, NULL, RM3); - if (rrc == MATCH_MATCH) - { - if (md->end_offset_top > offset_top) - offset_top = md->end_offset_top; /* Captures may have happened */ - condition = TRUE; - - /* Advance ecode past the assertion to the start of the first branch, - but adjust it so that the general choosing code below works. */ - - ecode += GET(ecode, 1); - while (*ecode == OP_ALT) ecode += GET(ecode, 1); - ecode += 1 + LINK_SIZE - PRIV(OP_lengths)[condcode]; - } - - /* PCRE doesn't allow the effect of (*THEN) to escape beyond an - assertion; it is therefore treated as NOMATCH. Any other return is an - error. */ - - else if (rrc != MATCH_NOMATCH && rrc != MATCH_THEN) - { - RRETURN(rrc); /* Need braces because of following else */ - } - break; - } - - /* Choose branch according to the condition */ - - ecode += condition? PRIV(OP_lengths)[condcode] : codelink; - - /* We are now at the branch that is to be obeyed. As there is only one, we - can use tail recursion to avoid using another stack frame, except when - there is unlimited repeat of a possibly empty group. In the latter case, a - recursive call to match() is always required, unless the second alternative - doesn't exist, in which case we can just plough on. Note that, for - compatibility with Perl, the | in a conditional group is NOT treated as - creating two alternatives. If a THEN is encountered in the branch, it - propagates out to the enclosing alternative (unless nested in a deeper set - of alternatives, of course). */ - - if (condition || ecode[-(1+LINK_SIZE)] == OP_ALT) - { - if (op != OP_SCOND) - { - goto TAIL_RECURSE; - } - - md->match_function_type = MATCH_CBEGROUP; - RMATCH(eptr, ecode, offset_top, md, eptrb, RM49); - RRETURN(rrc); - } - - /* Condition false & no alternative; continue after the group. */ - - else - { - } - break; - - - /* Before OP_ACCEPT there may be any number of OP_CLOSE opcodes, - to close any currently open capturing brackets. */ - - case OP_CLOSE: - number = GET2(ecode, 1); /* Must be less than 65536 */ - offset = number << 1; - -#ifdef PCRE_DEBUG - printf("end bracket %d at *ACCEPT", number); - printf("\n"); -#endif - - md->capture_last = (md->capture_last & OVFLMASK) | number; - if (offset >= md->offset_max) md->capture_last |= OVFLBIT; else - { - md->offset_vector[offset] = - md->offset_vector[md->offset_end - number]; - md->offset_vector[offset+1] = (int)(eptr - md->start_subject); - if (offset_top <= offset) offset_top = offset + 2; - } - ecode += 1 + IMM2_SIZE; - break; - - - /* End of the pattern, either real or forced. */ - - case OP_END: - case OP_ACCEPT: - case OP_ASSERT_ACCEPT: - - /* If we have matched an empty string, fail if not in an assertion and not - in a recursion if either PCRE_NOTEMPTY is set, or if PCRE_NOTEMPTY_ATSTART - is set and we have matched at the start of the subject. In both cases, - backtracking will then try other alternatives, if any. */ - - if (eptr == mstart && op != OP_ASSERT_ACCEPT && - md->recursive == NULL && - (md->notempty || - (md->notempty_atstart && - mstart == md->start_subject + md->start_offset))) - RRETURN(MATCH_NOMATCH); - - /* Otherwise, we have a match. */ - - md->end_match_ptr = eptr; /* Record where we ended */ - md->end_offset_top = offset_top; /* and how many extracts were taken */ - md->start_match_ptr = mstart; /* and the start (\K can modify) */ - - /* For some reason, the macros don't work properly if an expression is - given as the argument to RRETURN when the heap is in use. */ - - rrc = (op == OP_END)? MATCH_MATCH : MATCH_ACCEPT; - RRETURN(rrc); - - /* Assertion brackets. Check the alternative branches in turn - the - matching won't pass the KET for an assertion. If any one branch matches, - the assertion is true. Lookbehind assertions have an OP_REVERSE item at the - start of each branch to move the current point backwards, so the code at - this level is identical to the lookahead case. When the assertion is part - of a condition, we want to return immediately afterwards. The caller of - this incarnation of the match() function will have set MATCH_CONDASSERT in - md->match_function type, and one of these opcodes will be the first opcode - that is processed. We use a local variable that is preserved over calls to - match() to remember this case. */ - - case OP_ASSERT: - case OP_ASSERTBACK: - save_mark = md->mark; - if (md->match_function_type == MATCH_CONDASSERT) - { - condassert = TRUE; - md->match_function_type = 0; - } - else condassert = FALSE; - - /* Loop for each branch */ - - do - { - RMATCH(eptr, ecode + 1 + LINK_SIZE, offset_top, md, NULL, RM4); - - /* A match means that the assertion is true; break out of the loop - that matches its alternatives. */ - - if (rrc == MATCH_MATCH || rrc == MATCH_ACCEPT) - { - mstart = md->start_match_ptr; /* In case \K reset it */ - break; - } - - /* If not matched, restore the previous mark setting. */ - - md->mark = save_mark; - - /* See comment in the code for capturing groups above about handling - THEN. */ - - if (rrc == MATCH_THEN) - { - next = ecode + GET(ecode,1); - if (md->start_match_ptr < next && - (*ecode == OP_ALT || *next == OP_ALT)) - rrc = MATCH_NOMATCH; - } - - /* Anything other than NOMATCH causes the entire assertion to fail, - passing back the return code. This includes COMMIT, SKIP, PRUNE and an - uncaptured THEN, which means they take their normal effect. This - consistent approach does not always have exactly the same effect as in - Perl. */ - - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - ecode += GET(ecode, 1); - } - while (*ecode == OP_ALT); /* Continue for next alternative */ - - /* If we have tried all the alternative branches, the assertion has - failed. If not, we broke out after a match. */ - - if (*ecode == OP_KET) RRETURN(MATCH_NOMATCH); - - /* If checking an assertion for a condition, return MATCH_MATCH. */ - - if (condassert) RRETURN(MATCH_MATCH); - - /* Continue from after a successful assertion, updating the offsets high - water mark, since extracts may have been taken during the assertion. */ - - do ecode += GET(ecode,1); while (*ecode == OP_ALT); - ecode += 1 + LINK_SIZE; - offset_top = md->end_offset_top; - continue; - - /* Negative assertion: all branches must fail to match for the assertion to - succeed. */ - - case OP_ASSERT_NOT: - case OP_ASSERTBACK_NOT: - save_mark = md->mark; - if (md->match_function_type == MATCH_CONDASSERT) - { - condassert = TRUE; - md->match_function_type = 0; - } - else condassert = FALSE; - - /* Loop for each alternative branch. */ - - do - { - RMATCH(eptr, ecode + 1 + LINK_SIZE, offset_top, md, NULL, RM5); - md->mark = save_mark; /* Always restore the mark setting */ - - switch(rrc) - { - case MATCH_MATCH: /* A successful match means */ - case MATCH_ACCEPT: /* the assertion has failed. */ - RRETURN(MATCH_NOMATCH); - - case MATCH_NOMATCH: /* Carry on with next branch */ - break; - - /* See comment in the code for capturing groups above about handling - THEN. */ - - case MATCH_THEN: - next = ecode + GET(ecode,1); - if (md->start_match_ptr < next && - (*ecode == OP_ALT || *next == OP_ALT)) - { - rrc = MATCH_NOMATCH; - break; - } - /* Otherwise fall through. */ - - /* COMMIT, SKIP, PRUNE, and an uncaptured THEN cause the whole - assertion to fail to match, without considering any more alternatives. - Failing to match means the assertion is true. This is a consistent - approach, but does not always have the same effect as in Perl. */ - - case MATCH_COMMIT: - case MATCH_SKIP: - case MATCH_SKIP_ARG: - case MATCH_PRUNE: - do ecode += GET(ecode,1); while (*ecode == OP_ALT); - goto NEG_ASSERT_TRUE; /* Break out of alternation loop */ - - /* Anything else is an error */ - - default: - RRETURN(rrc); - } - - /* Continue with next branch */ - - ecode += GET(ecode,1); - } - while (*ecode == OP_ALT); - - /* All branches in the assertion failed to match. */ - - NEG_ASSERT_TRUE: - if (condassert) RRETURN(MATCH_MATCH); /* Condition assertion */ - ecode += 1 + LINK_SIZE; /* Continue with current branch */ - continue; - - /* Move the subject pointer back. This occurs only at the start of - each branch of a lookbehind assertion. If we are too close to the start to - move back, this match function fails. When working with UTF-8 we move - back a number of characters, not bytes. */ - - case OP_REVERSE: -#ifdef SUPPORT_UTF - if (utf) - { - i = GET(ecode, 1); - while (i-- > 0) - { - eptr--; - if (eptr < md->start_subject) RRETURN(MATCH_NOMATCH); - BACKCHAR(eptr); - } - } - else -#endif - - /* No UTF-8 support, or not in UTF-8 mode: count is byte count */ - - { - eptr -= GET(ecode, 1); - if (eptr < md->start_subject) RRETURN(MATCH_NOMATCH); - } - - /* Save the earliest consulted character, then skip to next op code */ - - if (eptr < md->start_used_ptr) md->start_used_ptr = eptr; - ecode += 1 + LINK_SIZE; - break; - - /* The callout item calls an external function, if one is provided, passing - details of the match so far. This is mainly for debugging, though the - function is able to force a failure. */ - - case OP_CALLOUT: - if (PUBL(callout) != NULL) - { - PUBL(callout_block) cb; - cb.version = 2; /* Version 1 of the callout block */ - cb.callout_number = ecode[1]; - cb.offset_vector = md->offset_vector; -#if defined COMPILE_PCRE8 - cb.subject = (PCRE_SPTR)md->start_subject; -#elif defined COMPILE_PCRE16 - cb.subject = (PCRE_SPTR16)md->start_subject; -#elif defined COMPILE_PCRE32 - cb.subject = (PCRE_SPTR32)md->start_subject; -#endif - cb.subject_length = (int)(md->end_subject - md->start_subject); - cb.start_match = (int)(mstart - md->start_subject); - cb.current_position = (int)(eptr - md->start_subject); - cb.pattern_position = GET(ecode, 2); - cb.next_item_length = GET(ecode, 2 + LINK_SIZE); - cb.capture_top = offset_top/2; - cb.capture_last = md->capture_last & CAPLMASK; - /* Internal change requires this for API compatibility. */ - if (cb.capture_last == 0) cb.capture_last = -1; - cb.callout_data = md->callout_data; - cb.mark = md->nomatch_mark; - if ((rrc = (*PUBL(callout))(&cb)) > 0) RRETURN(MATCH_NOMATCH); - if (rrc < 0) RRETURN(rrc); - } - ecode += 2 + 2*LINK_SIZE; - break; - - /* Recursion either matches the current regex, or some subexpression. The - offset data is the offset to the starting bracket from the start of the - whole pattern. (This is so that it works from duplicated subpatterns.) - - The state of the capturing groups is preserved over recursion, and - re-instated afterwards. We don't know how many are started and not yet - finished (offset_top records the completed total) so we just have to save - all the potential data. There may be up to 65535 such values, which is too - large to put on the stack, but using malloc for small numbers seems - expensive. As a compromise, the stack is used when there are no more than - REC_STACK_SAVE_MAX values to store; otherwise malloc is used. - - There are also other values that have to be saved. We use a chained - sequence of blocks that actually live on the stack. Thanks to Robin Houston - for the original version of this logic. It has, however, been hacked around - a lot, so he is not to blame for the current way it works. */ - - case OP_RECURSE: - { - recursion_info *ri; - unsigned int recno; - - callpat = md->start_code + GET(ecode, 1); - recno = (callpat == md->start_code)? 0 : - GET2(callpat, 1 + LINK_SIZE); - - /* Check for repeating a recursion without advancing the subject pointer. - This should catch convoluted mutual recursions. (Some simple cases are - caught at compile time.) */ - - for (ri = md->recursive; ri != NULL; ri = ri->prevrec) - if (recno == ri->group_num && eptr == ri->subject_position) - RRETURN(PCRE_ERROR_RECURSELOOP); - - /* Add to "recursing stack" */ - - new_recursive.group_num = recno; - new_recursive.saved_capture_last = md->capture_last; - new_recursive.subject_position = eptr; - new_recursive.prevrec = md->recursive; - md->recursive = &new_recursive; - - /* Where to continue from afterwards */ - - ecode += 1 + LINK_SIZE; - - /* Now save the offset data */ - - new_recursive.saved_max = md->offset_end; - if (new_recursive.saved_max <= REC_STACK_SAVE_MAX) - new_recursive.offset_save = stacksave; - else - { - new_recursive.offset_save = - (int *)(PUBL(malloc))(new_recursive.saved_max * sizeof(int)); - if (new_recursive.offset_save == NULL) RRETURN(PCRE_ERROR_NOMEMORY); - } - memcpy(new_recursive.offset_save, md->offset_vector, - new_recursive.saved_max * sizeof(int)); - - /* OK, now we can do the recursion. After processing each alternative, - restore the offset data and the last captured value. If there were nested - recursions, md->recursive might be changed, so reset it before looping. - */ - - DPRINTF(("Recursing into group %d\n", new_recursive.group_num)); - cbegroup = (*callpat >= OP_SBRA); - do - { - if (cbegroup) md->match_function_type = MATCH_CBEGROUP; - RMATCH(eptr, callpat + PRIV(OP_lengths)[*callpat], offset_top, - md, eptrb, RM6); - memcpy(md->offset_vector, new_recursive.offset_save, - new_recursive.saved_max * sizeof(int)); - md->capture_last = new_recursive.saved_capture_last; - md->recursive = new_recursive.prevrec; - if (rrc == MATCH_MATCH || rrc == MATCH_ACCEPT) - { - DPRINTF(("Recursion matched\n")); - if (new_recursive.offset_save != stacksave) - (PUBL(free))(new_recursive.offset_save); - - /* Set where we got to in the subject, and reset the start in case - it was changed by \K. This *is* propagated back out of a recursion, - for Perl compatibility. */ - - eptr = md->end_match_ptr; - mstart = md->start_match_ptr; - goto RECURSION_MATCHED; /* Exit loop; end processing */ - } - - /* PCRE does not allow THEN, SKIP, PRUNE or COMMIT to escape beyond a - recursion; they cause a NOMATCH for the entire recursion. These codes - are defined in a range that can be tested for. */ - - if (rrc >= MATCH_BACKTRACK_MIN && rrc <= MATCH_BACKTRACK_MAX) - RRETURN(MATCH_NOMATCH); - - /* Any return code other than NOMATCH is an error. */ - - if (rrc != MATCH_NOMATCH) - { - DPRINTF(("Recursion gave error %d\n", rrc)); - if (new_recursive.offset_save != stacksave) - (PUBL(free))(new_recursive.offset_save); - RRETURN(rrc); - } - - md->recursive = &new_recursive; - callpat += GET(callpat, 1); - } - while (*callpat == OP_ALT); - - DPRINTF(("Recursion didn't match\n")); - md->recursive = new_recursive.prevrec; - if (new_recursive.offset_save != stacksave) - (PUBL(free))(new_recursive.offset_save); - RRETURN(MATCH_NOMATCH); - } - - RECURSION_MATCHED: - break; - - /* An alternation is the end of a branch; scan along to find the end of the - bracketed group and go to there. */ - - case OP_ALT: - do ecode += GET(ecode,1); while (*ecode == OP_ALT); - break; - - /* BRAZERO, BRAMINZERO and SKIPZERO occur just before a bracket group, - indicating that it may occur zero times. It may repeat infinitely, or not - at all - i.e. it could be ()* or ()? or even (){0} in the pattern. Brackets - with fixed upper repeat limits are compiled as a number of copies, with the - optional ones preceded by BRAZERO or BRAMINZERO. */ - - case OP_BRAZERO: - next = ecode + 1; - RMATCH(eptr, next, offset_top, md, eptrb, RM10); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - do next += GET(next, 1); while (*next == OP_ALT); - ecode = next + 1 + LINK_SIZE; - break; - - case OP_BRAMINZERO: - next = ecode + 1; - do next += GET(next, 1); while (*next == OP_ALT); - RMATCH(eptr, next + 1+LINK_SIZE, offset_top, md, eptrb, RM11); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - ecode++; - break; - - case OP_SKIPZERO: - next = ecode+1; - do next += GET(next,1); while (*next == OP_ALT); - ecode = next + 1 + LINK_SIZE; - break; - - /* BRAPOSZERO occurs before a possessive bracket group. Don't do anything - here; just jump to the group, with allow_zero set TRUE. */ - - case OP_BRAPOSZERO: - op = *(++ecode); - allow_zero = TRUE; - if (op == OP_CBRAPOS || op == OP_SCBRAPOS) goto POSSESSIVE_CAPTURE; - goto POSSESSIVE_NON_CAPTURE; - - /* End of a group, repeated or non-repeating. */ - - case OP_KET: - case OP_KETRMIN: - case OP_KETRMAX: - case OP_KETRPOS: - prev = ecode - GET(ecode, 1); - - /* If this was a group that remembered the subject start, in order to break - infinite repeats of empty string matches, retrieve the subject start from - the chain. Otherwise, set it NULL. */ - - if (*prev >= OP_SBRA || *prev == OP_ONCE) - { - saved_eptr = eptrb->epb_saved_eptr; /* Value at start of group */ - eptrb = eptrb->epb_prev; /* Backup to previous group */ - } - else saved_eptr = NULL; - - /* If we are at the end of an assertion group or a non-capturing atomic - group, stop matching and return MATCH_MATCH, but record the current high - water mark for use by positive assertions. We also need to record the match - start in case it was changed by \K. */ - - if ((*prev >= OP_ASSERT && *prev <= OP_ASSERTBACK_NOT) || - *prev == OP_ONCE_NC) - { - md->end_match_ptr = eptr; /* For ONCE_NC */ - md->end_offset_top = offset_top; - md->start_match_ptr = mstart; - RRETURN(MATCH_MATCH); /* Sets md->mark */ - } - - /* For capturing groups we have to check the group number back at the start - and if necessary complete handling an extraction by setting the offsets and - bumping the high water mark. Whole-pattern recursion is coded as a recurse - into group 0, so it won't be picked up here. Instead, we catch it when the - OP_END is reached. Other recursion is handled here. We just have to record - the current subject position and start match pointer and give a MATCH - return. */ - - if (*prev == OP_CBRA || *prev == OP_SCBRA || - *prev == OP_CBRAPOS || *prev == OP_SCBRAPOS) - { - number = GET2(prev, 1+LINK_SIZE); - offset = number << 1; - -#ifdef PCRE_DEBUG - printf("end bracket %d", number); - printf("\n"); -#endif - - /* Handle a recursively called group. */ - - if (md->recursive != NULL && md->recursive->group_num == number) - { - md->end_match_ptr = eptr; - md->start_match_ptr = mstart; - RRETURN(MATCH_MATCH); - } - - /* Deal with capturing */ - - md->capture_last = (md->capture_last & OVFLMASK) | number; - if (offset >= md->offset_max) md->capture_last |= OVFLBIT; else - { - /* If offset is greater than offset_top, it means that we are - "skipping" a capturing group, and that group's offsets must be marked - unset. In earlier versions of PCRE, all the offsets were unset at the - start of matching, but this doesn't work because atomic groups and - assertions can cause a value to be set that should later be unset. - Example: matching /(?>(a))b|(a)c/ against "ac". This sets group 1 as - part of the atomic group, but this is not on the final matching path, - so must be unset when 2 is set. (If there is no group 2, there is no - problem, because offset_top will then be 2, indicating no capture.) */ - - if (offset > offset_top) - { - register int *iptr = md->offset_vector + offset_top; - register int *iend = md->offset_vector + offset; - while (iptr < iend) *iptr++ = -1; - } - - /* Now make the extraction */ - - md->offset_vector[offset] = - md->offset_vector[md->offset_end - number]; - md->offset_vector[offset+1] = (int)(eptr - md->start_subject); - if (offset_top <= offset) offset_top = offset + 2; - } - } - - /* OP_KETRPOS is a possessive repeating ket. Remember the current position, - and return the MATCH_KETRPOS. This makes it possible to do the repeats one - at a time from the outer level, thus saving stack. This must precede the - empty string test - in this case that test is done at the outer level. */ - - if (*ecode == OP_KETRPOS) - { - md->start_match_ptr = mstart; /* In case \K reset it */ - md->end_match_ptr = eptr; - md->end_offset_top = offset_top; - RRETURN(MATCH_KETRPOS); - } - - /* For an ordinary non-repeating ket, just continue at this level. This - also happens for a repeating ket if no characters were matched in the - group. This is the forcible breaking of infinite loops as implemented in - Perl 5.005. For a non-repeating atomic group that includes captures, - establish a backup point by processing the rest of the pattern at a lower - level. If this results in a NOMATCH return, pass MATCH_ONCE back to the - original OP_ONCE level, thereby bypassing intermediate backup points, but - resetting any captures that happened along the way. */ - - if (*ecode == OP_KET || eptr == saved_eptr) - { - if (*prev == OP_ONCE) - { - RMATCH(eptr, ecode + 1 + LINK_SIZE, offset_top, md, eptrb, RM12); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - md->once_target = prev; /* Level at which to change to MATCH_NOMATCH */ - RRETURN(MATCH_ONCE); - } - ecode += 1 + LINK_SIZE; /* Carry on at this level */ - break; - } - - /* The normal repeating kets try the rest of the pattern or restart from - the preceding bracket, in the appropriate order. In the second case, we can - use tail recursion to avoid using another stack frame, unless we have an - an atomic group or an unlimited repeat of a group that can match an empty - string. */ - - if (*ecode == OP_KETRMIN) - { - RMATCH(eptr, ecode + 1 + LINK_SIZE, offset_top, md, eptrb, RM7); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (*prev == OP_ONCE) - { - RMATCH(eptr, prev, offset_top, md, eptrb, RM8); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - md->once_target = prev; /* Level at which to change to MATCH_NOMATCH */ - RRETURN(MATCH_ONCE); - } - if (*prev >= OP_SBRA) /* Could match an empty string */ - { - RMATCH(eptr, prev, offset_top, md, eptrb, RM50); - RRETURN(rrc); - } - ecode = prev; - goto TAIL_RECURSE; - } - else /* OP_KETRMAX */ - { - RMATCH(eptr, prev, offset_top, md, eptrb, RM13); - if (rrc == MATCH_ONCE && md->once_target == prev) rrc = MATCH_NOMATCH; - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (*prev == OP_ONCE) - { - RMATCH(eptr, ecode + 1 + LINK_SIZE, offset_top, md, eptrb, RM9); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - md->once_target = prev; - RRETURN(MATCH_ONCE); - } - ecode += 1 + LINK_SIZE; - goto TAIL_RECURSE; - } - /* Control never gets here */ - - /* Not multiline mode: start of subject assertion, unless notbol. */ - - case OP_CIRC: - if (md->notbol && eptr == md->start_subject) RRETURN(MATCH_NOMATCH); - - /* Start of subject assertion */ - - case OP_SOD: - if (eptr != md->start_subject) RRETURN(MATCH_NOMATCH); - ecode++; - break; - - /* Multiline mode: start of subject unless notbol, or after any newline. */ - - case OP_CIRCM: - if (md->notbol && eptr == md->start_subject) RRETURN(MATCH_NOMATCH); - if (eptr != md->start_subject && - (eptr == md->end_subject || !WAS_NEWLINE(eptr))) - RRETURN(MATCH_NOMATCH); - ecode++; - break; - - /* Start of match assertion */ - - case OP_SOM: - if (eptr != md->start_subject + md->start_offset) RRETURN(MATCH_NOMATCH); - ecode++; - break; - - /* Reset the start of match point */ - - case OP_SET_SOM: - mstart = eptr; - ecode++; - break; - - /* Multiline mode: assert before any newline, or before end of subject - unless noteol is set. */ - - case OP_DOLLM: - if (eptr < md->end_subject) - { - if (!IS_NEWLINE(eptr)) - { - if (md->partial != 0 && - eptr + 1 >= md->end_subject && - NLBLOCK->nltype == NLTYPE_FIXED && - NLBLOCK->nllen == 2 && - UCHAR21TEST(eptr) == NLBLOCK->nl[0]) - { - md->hitend = TRUE; - if (md->partial > 1) RRETURN(PCRE_ERROR_PARTIAL); - } - RRETURN(MATCH_NOMATCH); - } - } - else - { - if (md->noteol) RRETURN(MATCH_NOMATCH); - SCHECK_PARTIAL(); - } - ecode++; - break; - - /* Not multiline mode: assert before a terminating newline or before end of - subject unless noteol is set. */ - - case OP_DOLL: - if (md->noteol) RRETURN(MATCH_NOMATCH); - if (!md->endonly) goto ASSERT_NL_OR_EOS; - - /* ... else fall through for endonly */ - - /* End of subject assertion (\z) */ - - case OP_EOD: - if (eptr < md->end_subject) RRETURN(MATCH_NOMATCH); - SCHECK_PARTIAL(); - ecode++; - break; - - /* End of subject or ending \n assertion (\Z) */ - - case OP_EODN: - ASSERT_NL_OR_EOS: - if (eptr < md->end_subject && - (!IS_NEWLINE(eptr) || eptr != md->end_subject - md->nllen)) - { - if (md->partial != 0 && - eptr + 1 >= md->end_subject && - NLBLOCK->nltype == NLTYPE_FIXED && - NLBLOCK->nllen == 2 && - UCHAR21TEST(eptr) == NLBLOCK->nl[0]) - { - md->hitend = TRUE; - if (md->partial > 1) RRETURN(PCRE_ERROR_PARTIAL); - } - RRETURN(MATCH_NOMATCH); - } - - /* Either at end of string or \n before end. */ - - SCHECK_PARTIAL(); - ecode++; - break; - - /* Word boundary assertions */ - - case OP_NOT_WORD_BOUNDARY: - case OP_WORD_BOUNDARY: - { - - /* Find out if the previous and current characters are "word" characters. - It takes a bit more work in UTF-8 mode. Characters > 255 are assumed to - be "non-word" characters. Remember the earliest consulted character for - partial matching. */ - -#ifdef SUPPORT_UTF - if (utf) - { - /* Get status of previous character */ - - if (eptr == md->start_subject) prev_is_word = FALSE; else - { - PCRE_PUCHAR lastptr = eptr - 1; - BACKCHAR(lastptr); - if (lastptr < md->start_used_ptr) md->start_used_ptr = lastptr; - GETCHAR(c, lastptr); -#ifdef SUPPORT_UCP - if (md->use_ucp) - { - if (c == '_') prev_is_word = TRUE; else - { - int cat = UCD_CATEGORY(c); - prev_is_word = (cat == ucp_L || cat == ucp_N); - } - } - else -#endif - prev_is_word = c < 256 && (md->ctypes[c] & ctype_word) != 0; - } - - /* Get status of next character */ - - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - cur_is_word = FALSE; - } - else - { - GETCHAR(c, eptr); -#ifdef SUPPORT_UCP - if (md->use_ucp) - { - if (c == '_') cur_is_word = TRUE; else - { - int cat = UCD_CATEGORY(c); - cur_is_word = (cat == ucp_L || cat == ucp_N); - } - } - else -#endif - cur_is_word = c < 256 && (md->ctypes[c] & ctype_word) != 0; - } - } - else -#endif - - /* Not in UTF-8 mode, but we may still have PCRE_UCP set, and for - consistency with the behaviour of \w we do use it in this case. */ - - { - /* Get status of previous character */ - - if (eptr == md->start_subject) prev_is_word = FALSE; else - { - if (eptr <= md->start_used_ptr) md->start_used_ptr = eptr - 1; -#ifdef SUPPORT_UCP - if (md->use_ucp) - { - c = eptr[-1]; - if (c == '_') prev_is_word = TRUE; else - { - int cat = UCD_CATEGORY(c); - prev_is_word = (cat == ucp_L || cat == ucp_N); - } - } - else -#endif - prev_is_word = MAX_255(eptr[-1]) - && ((md->ctypes[eptr[-1]] & ctype_word) != 0); - } - - /* Get status of next character */ - - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - cur_is_word = FALSE; - } - else -#ifdef SUPPORT_UCP - if (md->use_ucp) - { - c = *eptr; - if (c == '_') cur_is_word = TRUE; else - { - int cat = UCD_CATEGORY(c); - cur_is_word = (cat == ucp_L || cat == ucp_N); - } - } - else -#endif - cur_is_word = MAX_255(*eptr) - && ((md->ctypes[*eptr] & ctype_word) != 0); - } - - /* Now see if the situation is what we want */ - - if ((*ecode++ == OP_WORD_BOUNDARY)? - cur_is_word == prev_is_word : cur_is_word != prev_is_word) - RRETURN(MATCH_NOMATCH); - } - break; - - /* Match any single character type except newline; have to take care with - CRLF newlines and partial matching. */ - - case OP_ANY: - if (IS_NEWLINE(eptr)) RRETURN(MATCH_NOMATCH); - if (md->partial != 0 && - eptr + 1 >= md->end_subject && - NLBLOCK->nltype == NLTYPE_FIXED && - NLBLOCK->nllen == 2 && - UCHAR21TEST(eptr) == NLBLOCK->nl[0]) - { - md->hitend = TRUE; - if (md->partial > 1) RRETURN(PCRE_ERROR_PARTIAL); - } - - /* Fall through */ - - /* Match any single character whatsoever. */ - - case OP_ALLANY: - if (eptr >= md->end_subject) /* DO NOT merge the eptr++ here; it must */ - { /* not be updated before SCHECK_PARTIAL. */ - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - eptr++; -#ifdef SUPPORT_UTF - if (utf) ACROSSCHAR(eptr < md->end_subject, *eptr, eptr++); -#endif - ecode++; - break; - - /* Match a single byte, even in UTF-8 mode. This opcode really does match - any byte, even newline, independent of the setting of PCRE_DOTALL. */ - - case OP_ANYBYTE: - if (eptr >= md->end_subject) /* DO NOT merge the eptr++ here; it must */ - { /* not be updated before SCHECK_PARTIAL. */ - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - eptr++; - ecode++; - break; - - case OP_NOT_DIGIT: - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINCTEST(c, eptr); - if ( -#if defined SUPPORT_UTF || !(defined COMPILE_PCRE8) - c < 256 && -#endif - (md->ctypes[c] & ctype_digit) != 0 - ) - RRETURN(MATCH_NOMATCH); - ecode++; - break; - - case OP_DIGIT: - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINCTEST(c, eptr); - if ( -#if defined SUPPORT_UTF || !(defined COMPILE_PCRE8) - c > 255 || -#endif - (md->ctypes[c] & ctype_digit) == 0 - ) - RRETURN(MATCH_NOMATCH); - ecode++; - break; - - case OP_NOT_WHITESPACE: - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINCTEST(c, eptr); - if ( -#if defined SUPPORT_UTF || !(defined COMPILE_PCRE8) - c < 256 && -#endif - (md->ctypes[c] & ctype_space) != 0 - ) - RRETURN(MATCH_NOMATCH); - ecode++; - break; - - case OP_WHITESPACE: - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINCTEST(c, eptr); - if ( -#if defined SUPPORT_UTF || !(defined COMPILE_PCRE8) - c > 255 || -#endif - (md->ctypes[c] & ctype_space) == 0 - ) - RRETURN(MATCH_NOMATCH); - ecode++; - break; - - case OP_NOT_WORDCHAR: - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINCTEST(c, eptr); - if ( -#if defined SUPPORT_UTF || !(defined COMPILE_PCRE8) - c < 256 && -#endif - (md->ctypes[c] & ctype_word) != 0 - ) - RRETURN(MATCH_NOMATCH); - ecode++; - break; - - case OP_WORDCHAR: - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINCTEST(c, eptr); - if ( -#if defined SUPPORT_UTF || !(defined COMPILE_PCRE8) - c > 255 || -#endif - (md->ctypes[c] & ctype_word) == 0 - ) - RRETURN(MATCH_NOMATCH); - ecode++; - break; - - case OP_ANYNL: - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINCTEST(c, eptr); - switch(c) - { - default: RRETURN(MATCH_NOMATCH); - - case CHAR_CR: - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - } - else if (UCHAR21TEST(eptr) == CHAR_LF) eptr++; - break; - - case CHAR_LF: - break; - - case CHAR_VT: - case CHAR_FF: - case CHAR_NEL: -#ifndef EBCDIC - case 0x2028: - case 0x2029: -#endif /* Not EBCDIC */ - if (md->bsr_anycrlf) RRETURN(MATCH_NOMATCH); - break; - } - ecode++; - break; - - case OP_NOT_HSPACE: - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINCTEST(c, eptr); - switch(c) - { - HSPACE_CASES: RRETURN(MATCH_NOMATCH); /* Byte and multibyte cases */ - default: break; - } - ecode++; - break; - - case OP_HSPACE: - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINCTEST(c, eptr); - switch(c) - { - HSPACE_CASES: break; /* Byte and multibyte cases */ - default: RRETURN(MATCH_NOMATCH); - } - ecode++; - break; - - case OP_NOT_VSPACE: - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINCTEST(c, eptr); - switch(c) - { - VSPACE_CASES: RRETURN(MATCH_NOMATCH); - default: break; - } - ecode++; - break; - - case OP_VSPACE: - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINCTEST(c, eptr); - switch(c) - { - VSPACE_CASES: break; - default: RRETURN(MATCH_NOMATCH); - } - ecode++; - break; - -#ifdef SUPPORT_UCP - /* Check the next character by Unicode property. We will get here only - if the support is in the binary; otherwise a compile-time error occurs. */ - - case OP_PROP: - case OP_NOTPROP: - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINCTEST(c, eptr); - { - const pcre_uint32 *cp; - const ucd_record *prop = GET_UCD(c); - - switch(ecode[1]) - { - case PT_ANY: - if (op == OP_NOTPROP) RRETURN(MATCH_NOMATCH); - break; - - case PT_LAMP: - if ((prop->chartype == ucp_Lu || - prop->chartype == ucp_Ll || - prop->chartype == ucp_Lt) == (op == OP_NOTPROP)) - RRETURN(MATCH_NOMATCH); - break; - - case PT_GC: - if ((ecode[2] != PRIV(ucp_gentype)[prop->chartype]) == (op == OP_PROP)) - RRETURN(MATCH_NOMATCH); - break; - - case PT_PC: - if ((ecode[2] != prop->chartype) == (op == OP_PROP)) - RRETURN(MATCH_NOMATCH); - break; - - case PT_SC: - if ((ecode[2] != prop->script) == (op == OP_PROP)) - RRETURN(MATCH_NOMATCH); - break; - - /* These are specials */ - - case PT_ALNUM: - if ((PRIV(ucp_gentype)[prop->chartype] == ucp_L || - PRIV(ucp_gentype)[prop->chartype] == ucp_N) == (op == OP_NOTPROP)) - RRETURN(MATCH_NOMATCH); - break; - - /* Perl space used to exclude VT, but from Perl 5.18 it is included, - which means that Perl space and POSIX space are now identical. PCRE - was changed at release 8.34. */ - - case PT_SPACE: /* Perl space */ - case PT_PXSPACE: /* POSIX space */ - switch(c) - { - HSPACE_CASES: - VSPACE_CASES: - if (op == OP_NOTPROP) RRETURN(MATCH_NOMATCH); - break; - - default: - if ((PRIV(ucp_gentype)[prop->chartype] == ucp_Z) == - (op == OP_NOTPROP)) RRETURN(MATCH_NOMATCH); - break; - } - break; - - case PT_WORD: - if ((PRIV(ucp_gentype)[prop->chartype] == ucp_L || - PRIV(ucp_gentype)[prop->chartype] == ucp_N || - c == CHAR_UNDERSCORE) == (op == OP_NOTPROP)) - RRETURN(MATCH_NOMATCH); - break; - - case PT_CLIST: - cp = PRIV(ucd_caseless_sets) + ecode[2]; - for (;;) - { - if (c < *cp) - { if (op == OP_PROP) { RRETURN(MATCH_NOMATCH); } else break; } - if (c == *cp++) - { if (op == OP_PROP) break; else { RRETURN(MATCH_NOMATCH); } } - } - break; - - case PT_UCNC: - if ((c == CHAR_DOLLAR_SIGN || c == CHAR_COMMERCIAL_AT || - c == CHAR_GRAVE_ACCENT || (c >= 0xa0 && c <= 0xd7ff) || - c >= 0xe000) == (op == OP_NOTPROP)) - RRETURN(MATCH_NOMATCH); - break; - - /* This should never occur */ - - default: - RRETURN(PCRE_ERROR_INTERNAL); - } - - ecode += 3; - } - break; - - /* Match an extended Unicode sequence. We will get here only if the support - is in the binary; otherwise a compile-time error occurs. */ - - case OP_EXTUNI: - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - else - { - int lgb, rgb; - GETCHARINCTEST(c, eptr); - lgb = UCD_GRAPHBREAK(c); - while (eptr < md->end_subject) - { - int len = 1; - if (!utf) c = *eptr; else { GETCHARLEN(c, eptr, len); } - rgb = UCD_GRAPHBREAK(c); - if ((PRIV(ucp_gbtable)[lgb] & (1 << rgb)) == 0) break; - lgb = rgb; - eptr += len; - } - } - CHECK_PARTIAL(); - ecode++; - break; -#endif /* SUPPORT_UCP */ - - - /* Match a back reference, possibly repeatedly. Look past the end of the - item to see if there is repeat information following. The code is similar - to that for character classes, but repeated for efficiency. Then obey - similar code to character type repeats - written out again for speed. - However, if the referenced string is the empty string, always treat - it as matched, any number of times (otherwise there could be infinite - loops). If the reference is unset, there are two possibilities: - - (a) In the default, Perl-compatible state, set the length negative; - this ensures that every attempt at a match fails. We can't just fail - here, because of the possibility of quantifiers with zero minima. - - (b) If the JavaScript compatibility flag is set, set the length to zero - so that the back reference matches an empty string. - - Otherwise, set the length to the length of what was matched by the - referenced subpattern. - - The OP_REF and OP_REFI opcodes are used for a reference to a numbered group - or to a non-duplicated named group. For a duplicated named group, OP_DNREF - and OP_DNREFI are used. In this case we must scan the list of groups to - which the name refers, and use the first one that is set. */ - - case OP_DNREF: - case OP_DNREFI: - caseless = op == OP_DNREFI; - { - int count = GET2(ecode, 1+IMM2_SIZE); - pcre_uchar *slot = md->name_table + GET2(ecode, 1) * md->name_entry_size; - ecode += 1 + 2*IMM2_SIZE; - - /* Setting the default length first and initializing 'offset' avoids - compiler warnings in the REF_REPEAT code. */ - - length = (md->jscript_compat)? 0 : -1; - offset = 0; - - while (count-- > 0) - { - offset = GET2(slot, 0) << 1; - if (offset < offset_top && md->offset_vector[offset] >= 0) - { - length = md->offset_vector[offset+1] - md->offset_vector[offset]; - break; - } - slot += md->name_entry_size; - } - } - goto REF_REPEAT; - - case OP_REF: - case OP_REFI: - caseless = op == OP_REFI; - offset = GET2(ecode, 1) << 1; /* Doubled ref number */ - ecode += 1 + IMM2_SIZE; - if (offset >= offset_top || md->offset_vector[offset] < 0) - length = (md->jscript_compat)? 0 : -1; - else - length = md->offset_vector[offset+1] - md->offset_vector[offset]; - - /* Set up for repetition, or handle the non-repeated case */ - - REF_REPEAT: - switch (*ecode) - { - case OP_CRSTAR: - case OP_CRMINSTAR: - case OP_CRPLUS: - case OP_CRMINPLUS: - case OP_CRQUERY: - case OP_CRMINQUERY: - c = *ecode++ - OP_CRSTAR; - minimize = (c & 1) != 0; - min = rep_min[c]; /* Pick up values from tables; */ - max = rep_max[c]; /* zero for max => infinity */ - if (max == 0) max = INT_MAX; - break; - - case OP_CRRANGE: - case OP_CRMINRANGE: - minimize = (*ecode == OP_CRMINRANGE); - min = GET2(ecode, 1); - max = GET2(ecode, 1 + IMM2_SIZE); - if (max == 0) max = INT_MAX; - ecode += 1 + 2 * IMM2_SIZE; - break; - - default: /* No repeat follows */ - if ((length = match_ref(offset, eptr, length, md, caseless)) < 0) - { - if (length == -2) eptr = md->end_subject; /* Partial match */ - CHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - eptr += length; - continue; /* With the main loop */ - } - - /* Handle repeated back references. If the length of the reference is - zero, just continue with the main loop. If the length is negative, it - means the reference is unset in non-Java-compatible mode. If the minimum is - zero, we can continue at the same level without recursion. For any other - minimum, carrying on will result in NOMATCH. */ - - if (length == 0) continue; - if (length < 0 && min == 0) continue; - - /* First, ensure the minimum number of matches are present. We get back - the length of the reference string explicitly rather than passing the - address of eptr, so that eptr can be a register variable. */ - - for (i = 1; i <= min; i++) - { - int slength; - if ((slength = match_ref(offset, eptr, length, md, caseless)) < 0) - { - if (slength == -2) eptr = md->end_subject; /* Partial match */ - CHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - eptr += slength; - } - - /* If min = max, continue at the same level without recursion. - They are not both allowed to be zero. */ - - if (min == max) continue; - - /* If minimizing, keep trying and advancing the pointer */ - - if (minimize) - { - for (fi = min;; fi++) - { - int slength; - RMATCH(eptr, ecode, offset_top, md, eptrb, RM14); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (fi >= max) RRETURN(MATCH_NOMATCH); - if ((slength = match_ref(offset, eptr, length, md, caseless)) < 0) - { - if (slength == -2) eptr = md->end_subject; /* Partial match */ - CHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - eptr += slength; - } - /* Control never gets here */ - } - - /* If maximizing, find the longest string and work backwards */ - - else - { - pp = eptr; - for (i = min; i < max; i++) - { - int slength; - if ((slength = match_ref(offset, eptr, length, md, caseless)) < 0) - { - /* Can't use CHECK_PARTIAL because we don't want to update eptr in - the soft partial matching case. */ - - if (slength == -2 && md->partial != 0 && - md->end_subject > md->start_used_ptr) - { - md->hitend = TRUE; - if (md->partial > 1) RRETURN(PCRE_ERROR_PARTIAL); - } - break; - } - eptr += slength; - } - - while (eptr >= pp) - { - RMATCH(eptr, ecode, offset_top, md, eptrb, RM15); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - eptr -= length; - } - RRETURN(MATCH_NOMATCH); - } - /* Control never gets here */ - - /* Match a bit-mapped character class, possibly repeatedly. This op code is - used when all the characters in the class have values in the range 0-255, - and either the matching is caseful, or the characters are in the range - 0-127 when UTF-8 processing is enabled. The only difference between - OP_CLASS and OP_NCLASS occurs when a data character outside the range is - encountered. - - First, look past the end of the item to see if there is repeat information - following. Then obey similar code to character type repeats - written out - again for speed. */ - - case OP_NCLASS: - case OP_CLASS: - { - /* The data variable is saved across frames, so the byte map needs to - be stored there. */ -#define BYTE_MAP ((pcre_uint8 *)data) - data = ecode + 1; /* Save for matching */ - ecode += 1 + (32 / sizeof(pcre_uchar)); /* Advance past the item */ - - switch (*ecode) - { - case OP_CRSTAR: - case OP_CRMINSTAR: - case OP_CRPLUS: - case OP_CRMINPLUS: - case OP_CRQUERY: - case OP_CRMINQUERY: - case OP_CRPOSSTAR: - case OP_CRPOSPLUS: - case OP_CRPOSQUERY: - c = *ecode++ - OP_CRSTAR; - if (c < OP_CRPOSSTAR - OP_CRSTAR) minimize = (c & 1) != 0; - else possessive = TRUE; - min = rep_min[c]; /* Pick up values from tables; */ - max = rep_max[c]; /* zero for max => infinity */ - if (max == 0) max = INT_MAX; - break; - - case OP_CRRANGE: - case OP_CRMINRANGE: - case OP_CRPOSRANGE: - minimize = (*ecode == OP_CRMINRANGE); - possessive = (*ecode == OP_CRPOSRANGE); - min = GET2(ecode, 1); - max = GET2(ecode, 1 + IMM2_SIZE); - if (max == 0) max = INT_MAX; - ecode += 1 + 2 * IMM2_SIZE; - break; - - default: /* No repeat follows */ - min = max = 1; - break; - } - - /* First, ensure the minimum number of matches are present. */ - -#ifdef SUPPORT_UTF - if (utf) - { - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINC(c, eptr); - if (c > 255) - { - if (op == OP_CLASS) RRETURN(MATCH_NOMATCH); - } - else - if ((BYTE_MAP[c/8] & (1 << (c&7))) == 0) RRETURN(MATCH_NOMATCH); - } - } - else -#endif - /* Not UTF mode */ - { - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - c = *eptr++; -#ifndef COMPILE_PCRE8 - if (c > 255) - { - if (op == OP_CLASS) RRETURN(MATCH_NOMATCH); - } - else -#endif - if ((BYTE_MAP[c/8] & (1 << (c&7))) == 0) RRETURN(MATCH_NOMATCH); - } - } - - /* If max == min we can continue with the main loop without the - need to recurse. */ - - if (min == max) continue; - - /* If minimizing, keep testing the rest of the expression and advancing - the pointer while it matches the class. */ - - if (minimize) - { -#ifdef SUPPORT_UTF - if (utf) - { - for (fi = min;; fi++) - { - RMATCH(eptr, ecode, offset_top, md, eptrb, RM16); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (fi >= max) RRETURN(MATCH_NOMATCH); - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINC(c, eptr); - if (c > 255) - { - if (op == OP_CLASS) RRETURN(MATCH_NOMATCH); - } - else - if ((BYTE_MAP[c/8] & (1 << (c&7))) == 0) RRETURN(MATCH_NOMATCH); - } - } - else -#endif - /* Not UTF mode */ - { - for (fi = min;; fi++) - { - RMATCH(eptr, ecode, offset_top, md, eptrb, RM17); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (fi >= max) RRETURN(MATCH_NOMATCH); - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - c = *eptr++; -#ifndef COMPILE_PCRE8 - if (c > 255) - { - if (op == OP_CLASS) RRETURN(MATCH_NOMATCH); - } - else -#endif - if ((BYTE_MAP[c/8] & (1 << (c&7))) == 0) RRETURN(MATCH_NOMATCH); - } - } - /* Control never gets here */ - } - - /* If maximizing, find the longest possible run, then work backwards. */ - - else - { - pp = eptr; - -#ifdef SUPPORT_UTF - if (utf) - { - for (i = min; i < max; i++) - { - int len = 1; - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - break; - } - GETCHARLEN(c, eptr, len); - if (c > 255) - { - if (op == OP_CLASS) break; - } - else - if ((BYTE_MAP[c/8] & (1 << (c&7))) == 0) break; - eptr += len; - } - - if (possessive) continue; /* No backtracking */ - - for (;;) - { - RMATCH(eptr, ecode, offset_top, md, eptrb, RM18); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (eptr-- == pp) break; /* Stop if tried at original pos */ - BACKCHAR(eptr); - } - } - else -#endif - /* Not UTF mode */ - { - for (i = min; i < max; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - break; - } - c = *eptr; -#ifndef COMPILE_PCRE8 - if (c > 255) - { - if (op == OP_CLASS) break; - } - else -#endif - if ((BYTE_MAP[c/8] & (1 << (c&7))) == 0) break; - eptr++; - } - - if (possessive) continue; /* No backtracking */ - - while (eptr >= pp) - { - RMATCH(eptr, ecode, offset_top, md, eptrb, RM19); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - eptr--; - } - } - - RRETURN(MATCH_NOMATCH); - } -#undef BYTE_MAP - } - /* Control never gets here */ - - - /* Match an extended character class. In the 8-bit library, this opcode is - encountered only when UTF-8 mode mode is supported. In the 16-bit and - 32-bit libraries, codepoints greater than 255 may be encountered even when - UTF is not supported. */ - -#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 - case OP_XCLASS: - { - data = ecode + 1 + LINK_SIZE; /* Save for matching */ - ecode += GET(ecode, 1); /* Advance past the item */ - - switch (*ecode) - { - case OP_CRSTAR: - case OP_CRMINSTAR: - case OP_CRPLUS: - case OP_CRMINPLUS: - case OP_CRQUERY: - case OP_CRMINQUERY: - case OP_CRPOSSTAR: - case OP_CRPOSPLUS: - case OP_CRPOSQUERY: - c = *ecode++ - OP_CRSTAR; - if (c < OP_CRPOSSTAR - OP_CRSTAR) minimize = (c & 1) != 0; - else possessive = TRUE; - min = rep_min[c]; /* Pick up values from tables; */ - max = rep_max[c]; /* zero for max => infinity */ - if (max == 0) max = INT_MAX; - break; - - case OP_CRRANGE: - case OP_CRMINRANGE: - case OP_CRPOSRANGE: - minimize = (*ecode == OP_CRMINRANGE); - possessive = (*ecode == OP_CRPOSRANGE); - min = GET2(ecode, 1); - max = GET2(ecode, 1 + IMM2_SIZE); - if (max == 0) max = INT_MAX; - ecode += 1 + 2 * IMM2_SIZE; - break; - - default: /* No repeat follows */ - min = max = 1; - break; - } - - /* First, ensure the minimum number of matches are present. */ - - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINCTEST(c, eptr); - if (!PRIV(xclass)(c, data, utf)) RRETURN(MATCH_NOMATCH); - } - - /* If max == min we can continue with the main loop without the - need to recurse. */ - - if (min == max) continue; - - /* If minimizing, keep testing the rest of the expression and advancing - the pointer while it matches the class. */ - - if (minimize) - { - for (fi = min;; fi++) - { - RMATCH(eptr, ecode, offset_top, md, eptrb, RM20); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (fi >= max) RRETURN(MATCH_NOMATCH); - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINCTEST(c, eptr); - if (!PRIV(xclass)(c, data, utf)) RRETURN(MATCH_NOMATCH); - } - /* Control never gets here */ - } - - /* If maximizing, find the longest possible run, then work backwards. */ - - else - { - pp = eptr; - for (i = min; i < max; i++) - { - int len = 1; - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - break; - } -#ifdef SUPPORT_UTF - GETCHARLENTEST(c, eptr, len); -#else - c = *eptr; -#endif - if (!PRIV(xclass)(c, data, utf)) break; - eptr += len; - } - - if (possessive) continue; /* No backtracking */ - - for(;;) - { - RMATCH(eptr, ecode, offset_top, md, eptrb, RM21); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (eptr-- == pp) break; /* Stop if tried at original pos */ -#ifdef SUPPORT_UTF - if (utf) BACKCHAR(eptr); -#endif - } - RRETURN(MATCH_NOMATCH); - } - - /* Control never gets here */ - } -#endif /* End of XCLASS */ - - /* Match a single character, casefully */ - - case OP_CHAR: -#ifdef SUPPORT_UTF - if (utf) - { - length = 1; - ecode++; - GETCHARLEN(fc, ecode, length); - if (length > md->end_subject - eptr) - { - CHECK_PARTIAL(); /* Not SCHECK_PARTIAL() */ - RRETURN(MATCH_NOMATCH); - } - while (length-- > 0) if (*ecode++ != UCHAR21INC(eptr)) RRETURN(MATCH_NOMATCH); - } - else -#endif - /* Not UTF mode */ - { - if (md->end_subject - eptr < 1) - { - SCHECK_PARTIAL(); /* This one can use SCHECK_PARTIAL() */ - RRETURN(MATCH_NOMATCH); - } - if (ecode[1] != *eptr++) RRETURN(MATCH_NOMATCH); - ecode += 2; - } - break; - - /* Match a single character, caselessly. If we are at the end of the - subject, give up immediately. */ - - case OP_CHARI: - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - -#ifdef SUPPORT_UTF - if (utf) - { - length = 1; - ecode++; - GETCHARLEN(fc, ecode, length); - - /* If the pattern character's value is < 128, we have only one byte, and - we know that its other case must also be one byte long, so we can use the - fast lookup table. We know that there is at least one byte left in the - subject. */ - - if (fc < 128) - { - pcre_uint32 cc = UCHAR21(eptr); - if (md->lcc[fc] != TABLE_GET(cc, md->lcc, cc)) RRETURN(MATCH_NOMATCH); - ecode++; - eptr++; - } - - /* Otherwise we must pick up the subject character. Note that we cannot - use the value of "length" to check for sufficient bytes left, because the - other case of the character may have more or fewer bytes. */ - - else - { - pcre_uint32 dc; - GETCHARINC(dc, eptr); - ecode += length; - - /* If we have Unicode property support, we can use it to test the other - case of the character, if there is one. */ - - if (fc != dc) - { -#ifdef SUPPORT_UCP - if (dc != UCD_OTHERCASE(fc)) -#endif - RRETURN(MATCH_NOMATCH); - } - } - } - else -#endif /* SUPPORT_UTF */ - - /* Not UTF mode */ - { - if (TABLE_GET(ecode[1], md->lcc, ecode[1]) - != TABLE_GET(*eptr, md->lcc, *eptr)) RRETURN(MATCH_NOMATCH); - eptr++; - ecode += 2; - } - break; - - /* Match a single character repeatedly. */ - - case OP_EXACT: - case OP_EXACTI: - min = max = GET2(ecode, 1); - ecode += 1 + IMM2_SIZE; - goto REPEATCHAR; - - case OP_POSUPTO: - case OP_POSUPTOI: - possessive = TRUE; - /* Fall through */ - - case OP_UPTO: - case OP_UPTOI: - case OP_MINUPTO: - case OP_MINUPTOI: - min = 0; - max = GET2(ecode, 1); - minimize = *ecode == OP_MINUPTO || *ecode == OP_MINUPTOI; - ecode += 1 + IMM2_SIZE; - goto REPEATCHAR; - - case OP_POSSTAR: - case OP_POSSTARI: - possessive = TRUE; - min = 0; - max = INT_MAX; - ecode++; - goto REPEATCHAR; - - case OP_POSPLUS: - case OP_POSPLUSI: - possessive = TRUE; - min = 1; - max = INT_MAX; - ecode++; - goto REPEATCHAR; - - case OP_POSQUERY: - case OP_POSQUERYI: - possessive = TRUE; - min = 0; - max = 1; - ecode++; - goto REPEATCHAR; - - case OP_STAR: - case OP_STARI: - case OP_MINSTAR: - case OP_MINSTARI: - case OP_PLUS: - case OP_PLUSI: - case OP_MINPLUS: - case OP_MINPLUSI: - case OP_QUERY: - case OP_QUERYI: - case OP_MINQUERY: - case OP_MINQUERYI: - c = *ecode++ - ((op < OP_STARI)? OP_STAR : OP_STARI); - minimize = (c & 1) != 0; - min = rep_min[c]; /* Pick up values from tables; */ - max = rep_max[c]; /* zero for max => infinity */ - if (max == 0) max = INT_MAX; - - /* Common code for all repeated single-character matches. We first check - for the minimum number of characters. If the minimum equals the maximum, we - are done. Otherwise, if minimizing, check the rest of the pattern for a - match; if there isn't one, advance up to the maximum, one character at a - time. - - If maximizing, advance up to the maximum number of matching characters, - until eptr is past the end of the maximum run. If possessive, we are - then done (no backing up). Otherwise, match at this position; anything - other than no match is immediately returned. For nomatch, back up one - character, unless we are matching \R and the last thing matched was - \r\n, in which case, back up two bytes. When we reach the first optional - character position, we can save stack by doing a tail recurse. - - The various UTF/non-UTF and caseful/caseless cases are handled separately, - for speed. */ - - REPEATCHAR: -#ifdef SUPPORT_UTF - if (utf) - { - length = 1; - charptr = ecode; - GETCHARLEN(fc, ecode, length); - ecode += length; - - /* Handle multibyte character matching specially here. There is - support for caseless matching if UCP support is present. */ - - if (length > 1) - { -#ifdef SUPPORT_UCP - pcre_uint32 othercase; - if (op >= OP_STARI && /* Caseless */ - (othercase = UCD_OTHERCASE(fc)) != fc) - oclength = PRIV(ord2utf)(othercase, occhars); - else oclength = 0; -#endif /* SUPPORT_UCP */ - - for (i = 1; i <= min; i++) - { - if (eptr <= md->end_subject - length && - memcmp(eptr, charptr, IN_UCHARS(length)) == 0) eptr += length; -#ifdef SUPPORT_UCP - else if (oclength > 0 && - eptr <= md->end_subject - oclength && - memcmp(eptr, occhars, IN_UCHARS(oclength)) == 0) eptr += oclength; -#endif /* SUPPORT_UCP */ - else - { - CHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - } - - if (min == max) continue; - - if (minimize) - { - for (fi = min;; fi++) - { - RMATCH(eptr, ecode, offset_top, md, eptrb, RM22); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (fi >= max) RRETURN(MATCH_NOMATCH); - if (eptr <= md->end_subject - length && - memcmp(eptr, charptr, IN_UCHARS(length)) == 0) eptr += length; -#ifdef SUPPORT_UCP - else if (oclength > 0 && - eptr <= md->end_subject - oclength && - memcmp(eptr, occhars, IN_UCHARS(oclength)) == 0) eptr += oclength; -#endif /* SUPPORT_UCP */ - else - { - CHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - } - /* Control never gets here */ - } - - else /* Maximize */ - { - pp = eptr; - for (i = min; i < max; i++) - { - if (eptr <= md->end_subject - length && - memcmp(eptr, charptr, IN_UCHARS(length)) == 0) eptr += length; -#ifdef SUPPORT_UCP - else if (oclength > 0 && - eptr <= md->end_subject - oclength && - memcmp(eptr, occhars, IN_UCHARS(oclength)) == 0) eptr += oclength; -#endif /* SUPPORT_UCP */ - else - { - CHECK_PARTIAL(); - break; - } - } - - if (possessive) continue; /* No backtracking */ - for(;;) - { - if (eptr == pp) goto TAIL_RECURSE; - RMATCH(eptr, ecode, offset_top, md, eptrb, RM23); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); -#ifdef SUPPORT_UCP - eptr--; - BACKCHAR(eptr); -#else /* without SUPPORT_UCP */ - eptr -= length; -#endif /* SUPPORT_UCP */ - } - } - /* Control never gets here */ - } - - /* If the length of a UTF-8 character is 1, we fall through here, and - obey the code as for non-UTF-8 characters below, though in this case the - value of fc will always be < 128. */ - } - else -#endif /* SUPPORT_UTF */ - /* When not in UTF-8 mode, load a single-byte character. */ - fc = *ecode++; - - /* The value of fc at this point is always one character, though we may - or may not be in UTF mode. The code is duplicated for the caseless and - caseful cases, for speed, since matching characters is likely to be quite - common. First, ensure the minimum number of matches are present. If min = - max, continue at the same level without recursing. Otherwise, if - minimizing, keep trying the rest of the expression and advancing one - matching character if failing, up to the maximum. Alternatively, if - maximizing, find the maximum number of characters and work backwards. */ - - DPRINTF(("matching %c{%d,%d} against subject %.*s\n", fc, min, max, - max, (char *)eptr)); - - if (op >= OP_STARI) /* Caseless */ - { -#ifdef COMPILE_PCRE8 - /* fc must be < 128 if UTF is enabled. */ - foc = md->fcc[fc]; -#else -#ifdef SUPPORT_UTF -#ifdef SUPPORT_UCP - if (utf && fc > 127) - foc = UCD_OTHERCASE(fc); -#else - if (utf && fc > 127) - foc = fc; -#endif /* SUPPORT_UCP */ - else -#endif /* SUPPORT_UTF */ - foc = TABLE_GET(fc, md->fcc, fc); -#endif /* COMPILE_PCRE8 */ - - for (i = 1; i <= min; i++) - { - pcre_uint32 cc; /* Faster than pcre_uchar */ - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - cc = UCHAR21TEST(eptr); - if (fc != cc && foc != cc) RRETURN(MATCH_NOMATCH); - eptr++; - } - if (min == max) continue; - if (minimize) - { - for (fi = min;; fi++) - { - pcre_uint32 cc; /* Faster than pcre_uchar */ - RMATCH(eptr, ecode, offset_top, md, eptrb, RM24); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (fi >= max) RRETURN(MATCH_NOMATCH); - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - cc = UCHAR21TEST(eptr); - if (fc != cc && foc != cc) RRETURN(MATCH_NOMATCH); - eptr++; - } - /* Control never gets here */ - } - else /* Maximize */ - { - pp = eptr; - for (i = min; i < max; i++) - { - pcre_uint32 cc; /* Faster than pcre_uchar */ - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - break; - } - cc = UCHAR21TEST(eptr); - if (fc != cc && foc != cc) break; - eptr++; - } - if (possessive) continue; /* No backtracking */ - for (;;) - { - if (eptr == pp) goto TAIL_RECURSE; - RMATCH(eptr, ecode, offset_top, md, eptrb, RM25); - eptr--; - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - } - /* Control never gets here */ - } - } - - /* Caseful comparisons (includes all multi-byte characters) */ - - else - { - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - if (fc != UCHAR21INCTEST(eptr)) RRETURN(MATCH_NOMATCH); - } - - if (min == max) continue; - - if (minimize) - { - for (fi = min;; fi++) - { - RMATCH(eptr, ecode, offset_top, md, eptrb, RM26); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (fi >= max) RRETURN(MATCH_NOMATCH); - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - if (fc != UCHAR21INCTEST(eptr)) RRETURN(MATCH_NOMATCH); - } - /* Control never gets here */ - } - else /* Maximize */ - { - pp = eptr; - for (i = min; i < max; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - break; - } - if (fc != UCHAR21TEST(eptr)) break; - eptr++; - } - if (possessive) continue; /* No backtracking */ - for (;;) - { - if (eptr == pp) goto TAIL_RECURSE; - RMATCH(eptr, ecode, offset_top, md, eptrb, RM27); - eptr--; - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - } - /* Control never gets here */ - } - } - /* Control never gets here */ - - /* Match a negated single one-byte character. The character we are - checking can be multibyte. */ - - case OP_NOT: - case OP_NOTI: - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } -#ifdef SUPPORT_UTF - if (utf) - { - register pcre_uint32 ch, och; - - ecode++; - GETCHARINC(ch, ecode); - GETCHARINC(c, eptr); - - if (op == OP_NOT) - { - if (ch == c) RRETURN(MATCH_NOMATCH); - } - else - { -#ifdef SUPPORT_UCP - if (ch > 127) - och = UCD_OTHERCASE(ch); -#else - if (ch > 127) - och = ch; -#endif /* SUPPORT_UCP */ - else - och = TABLE_GET(ch, md->fcc, ch); - if (ch == c || och == c) RRETURN(MATCH_NOMATCH); - } - } - else -#endif - { - register pcre_uint32 ch = ecode[1]; - c = *eptr++; - if (ch == c || (op == OP_NOTI && TABLE_GET(ch, md->fcc, ch) == c)) - RRETURN(MATCH_NOMATCH); - ecode += 2; - } - break; - - /* Match a negated single one-byte character repeatedly. This is almost a - repeat of the code for a repeated single character, but I haven't found a - nice way of commoning these up that doesn't require a test of the - positive/negative option for each character match. Maybe that wouldn't add - very much to the time taken, but character matching *is* what this is all - about... */ - - case OP_NOTEXACT: - case OP_NOTEXACTI: - min = max = GET2(ecode, 1); - ecode += 1 + IMM2_SIZE; - goto REPEATNOTCHAR; - - case OP_NOTUPTO: - case OP_NOTUPTOI: - case OP_NOTMINUPTO: - case OP_NOTMINUPTOI: - min = 0; - max = GET2(ecode, 1); - minimize = *ecode == OP_NOTMINUPTO || *ecode == OP_NOTMINUPTOI; - ecode += 1 + IMM2_SIZE; - goto REPEATNOTCHAR; - - case OP_NOTPOSSTAR: - case OP_NOTPOSSTARI: - possessive = TRUE; - min = 0; - max = INT_MAX; - ecode++; - goto REPEATNOTCHAR; - - case OP_NOTPOSPLUS: - case OP_NOTPOSPLUSI: - possessive = TRUE; - min = 1; - max = INT_MAX; - ecode++; - goto REPEATNOTCHAR; - - case OP_NOTPOSQUERY: - case OP_NOTPOSQUERYI: - possessive = TRUE; - min = 0; - max = 1; - ecode++; - goto REPEATNOTCHAR; - - case OP_NOTPOSUPTO: - case OP_NOTPOSUPTOI: - possessive = TRUE; - min = 0; - max = GET2(ecode, 1); - ecode += 1 + IMM2_SIZE; - goto REPEATNOTCHAR; - - case OP_NOTSTAR: - case OP_NOTSTARI: - case OP_NOTMINSTAR: - case OP_NOTMINSTARI: - case OP_NOTPLUS: - case OP_NOTPLUSI: - case OP_NOTMINPLUS: - case OP_NOTMINPLUSI: - case OP_NOTQUERY: - case OP_NOTQUERYI: - case OP_NOTMINQUERY: - case OP_NOTMINQUERYI: - c = *ecode++ - ((op >= OP_NOTSTARI)? OP_NOTSTARI: OP_NOTSTAR); - minimize = (c & 1) != 0; - min = rep_min[c]; /* Pick up values from tables; */ - max = rep_max[c]; /* zero for max => infinity */ - if (max == 0) max = INT_MAX; - - /* Common code for all repeated single-byte matches. */ - - REPEATNOTCHAR: - GETCHARINCTEST(fc, ecode); - - /* The code is duplicated for the caseless and caseful cases, for speed, - since matching characters is likely to be quite common. First, ensure the - minimum number of matches are present. If min = max, continue at the same - level without recursing. Otherwise, if minimizing, keep trying the rest of - the expression and advancing one matching character if failing, up to the - maximum. Alternatively, if maximizing, find the maximum number of - characters and work backwards. */ - - DPRINTF(("negative matching %c{%d,%d} against subject %.*s\n", fc, min, max, - max, (char *)eptr)); - - if (op >= OP_NOTSTARI) /* Caseless */ - { -#ifdef SUPPORT_UTF -#ifdef SUPPORT_UCP - if (utf && fc > 127) - foc = UCD_OTHERCASE(fc); -#else - if (utf && fc > 127) - foc = fc; -#endif /* SUPPORT_UCP */ - else -#endif /* SUPPORT_UTF */ - foc = TABLE_GET(fc, md->fcc, fc); - -#ifdef SUPPORT_UTF - if (utf) - { - register pcre_uint32 d; - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINC(d, eptr); - if (fc == d || (unsigned int)foc == d) RRETURN(MATCH_NOMATCH); - } - } - else -#endif /* SUPPORT_UTF */ - /* Not UTF mode */ - { - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - if (fc == *eptr || foc == *eptr) RRETURN(MATCH_NOMATCH); - eptr++; - } - } - - if (min == max) continue; - - if (minimize) - { -#ifdef SUPPORT_UTF - if (utf) - { - register pcre_uint32 d; - for (fi = min;; fi++) - { - RMATCH(eptr, ecode, offset_top, md, eptrb, RM28); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (fi >= max) RRETURN(MATCH_NOMATCH); - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINC(d, eptr); - if (fc == d || (unsigned int)foc == d) RRETURN(MATCH_NOMATCH); - } - } - else -#endif /*SUPPORT_UTF */ - /* Not UTF mode */ - { - for (fi = min;; fi++) - { - RMATCH(eptr, ecode, offset_top, md, eptrb, RM29); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (fi >= max) RRETURN(MATCH_NOMATCH); - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - if (fc == *eptr || foc == *eptr) RRETURN(MATCH_NOMATCH); - eptr++; - } - } - /* Control never gets here */ - } - - /* Maximize case */ - - else - { - pp = eptr; - -#ifdef SUPPORT_UTF - if (utf) - { - register pcre_uint32 d; - for (i = min; i < max; i++) - { - int len = 1; - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - break; - } - GETCHARLEN(d, eptr, len); - if (fc == d || (unsigned int)foc == d) break; - eptr += len; - } - if (possessive) continue; /* No backtracking */ - for(;;) - { - if (eptr == pp) goto TAIL_RECURSE; - RMATCH(eptr, ecode, offset_top, md, eptrb, RM30); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - eptr--; - BACKCHAR(eptr); - } - } - else -#endif /* SUPPORT_UTF */ - /* Not UTF mode */ - { - for (i = min; i < max; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - break; - } - if (fc == *eptr || foc == *eptr) break; - eptr++; - } - if (possessive) continue; /* No backtracking */ - for (;;) - { - if (eptr == pp) goto TAIL_RECURSE; - RMATCH(eptr, ecode, offset_top, md, eptrb, RM31); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - eptr--; - } - } - /* Control never gets here */ - } - } - - /* Caseful comparisons */ - - else - { -#ifdef SUPPORT_UTF - if (utf) - { - register pcre_uint32 d; - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINC(d, eptr); - if (fc == d) RRETURN(MATCH_NOMATCH); - } - } - else -#endif - /* Not UTF mode */ - { - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - if (fc == *eptr++) RRETURN(MATCH_NOMATCH); - } - } - - if (min == max) continue; - - if (minimize) - { -#ifdef SUPPORT_UTF - if (utf) - { - register pcre_uint32 d; - for (fi = min;; fi++) - { - RMATCH(eptr, ecode, offset_top, md, eptrb, RM32); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (fi >= max) RRETURN(MATCH_NOMATCH); - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINC(d, eptr); - if (fc == d) RRETURN(MATCH_NOMATCH); - } - } - else -#endif - /* Not UTF mode */ - { - for (fi = min;; fi++) - { - RMATCH(eptr, ecode, offset_top, md, eptrb, RM33); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (fi >= max) RRETURN(MATCH_NOMATCH); - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - if (fc == *eptr++) RRETURN(MATCH_NOMATCH); - } - } - /* Control never gets here */ - } - - /* Maximize case */ - - else - { - pp = eptr; - -#ifdef SUPPORT_UTF - if (utf) - { - register pcre_uint32 d; - for (i = min; i < max; i++) - { - int len = 1; - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - break; - } - GETCHARLEN(d, eptr, len); - if (fc == d) break; - eptr += len; - } - if (possessive) continue; /* No backtracking */ - for(;;) - { - if (eptr == pp) goto TAIL_RECURSE; - RMATCH(eptr, ecode, offset_top, md, eptrb, RM34); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - eptr--; - BACKCHAR(eptr); - } - } - else -#endif - /* Not UTF mode */ - { - for (i = min; i < max; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - break; - } - if (fc == *eptr) break; - eptr++; - } - if (possessive) continue; /* No backtracking */ - for (;;) - { - if (eptr == pp) goto TAIL_RECURSE; - RMATCH(eptr, ecode, offset_top, md, eptrb, RM35); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - eptr--; - } - } - /* Control never gets here */ - } - } - /* Control never gets here */ - - /* Match a single character type repeatedly; several different opcodes - share code. This is very similar to the code for single characters, but we - repeat it in the interests of efficiency. */ - - case OP_TYPEEXACT: - min = max = GET2(ecode, 1); - minimize = TRUE; - ecode += 1 + IMM2_SIZE; - goto REPEATTYPE; - - case OP_TYPEUPTO: - case OP_TYPEMINUPTO: - min = 0; - max = GET2(ecode, 1); - minimize = *ecode == OP_TYPEMINUPTO; - ecode += 1 + IMM2_SIZE; - goto REPEATTYPE; - - case OP_TYPEPOSSTAR: - possessive = TRUE; - min = 0; - max = INT_MAX; - ecode++; - goto REPEATTYPE; - - case OP_TYPEPOSPLUS: - possessive = TRUE; - min = 1; - max = INT_MAX; - ecode++; - goto REPEATTYPE; - - case OP_TYPEPOSQUERY: - possessive = TRUE; - min = 0; - max = 1; - ecode++; - goto REPEATTYPE; - - case OP_TYPEPOSUPTO: - possessive = TRUE; - min = 0; - max = GET2(ecode, 1); - ecode += 1 + IMM2_SIZE; - goto REPEATTYPE; - - case OP_TYPESTAR: - case OP_TYPEMINSTAR: - case OP_TYPEPLUS: - case OP_TYPEMINPLUS: - case OP_TYPEQUERY: - case OP_TYPEMINQUERY: - c = *ecode++ - OP_TYPESTAR; - minimize = (c & 1) != 0; - min = rep_min[c]; /* Pick up values from tables; */ - max = rep_max[c]; /* zero for max => infinity */ - if (max == 0) max = INT_MAX; - - /* Common code for all repeated single character type matches. Note that - in UTF-8 mode, '.' matches a character of any length, but for the other - character types, the valid characters are all one-byte long. */ - - REPEATTYPE: - ctype = *ecode++; /* Code for the character type */ - -#ifdef SUPPORT_UCP - if (ctype == OP_PROP || ctype == OP_NOTPROP) - { - prop_fail_result = ctype == OP_NOTPROP; - prop_type = *ecode++; - prop_value = *ecode++; - } - else prop_type = -1; -#endif - - /* First, ensure the minimum number of matches are present. Use inline - code for maximizing the speed, and do the type test once at the start - (i.e. keep it out of the loop). Separate the UTF-8 code completely as that - is tidier. Also separate the UCP code, which can be the same for both UTF-8 - and single-bytes. */ - - if (min > 0) - { -#ifdef SUPPORT_UCP - if (prop_type >= 0) - { - switch(prop_type) - { - case PT_ANY: - if (prop_fail_result) RRETURN(MATCH_NOMATCH); - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINCTEST(c, eptr); - } - break; - - case PT_LAMP: - for (i = 1; i <= min; i++) - { - int chartype; - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINCTEST(c, eptr); - chartype = UCD_CHARTYPE(c); - if ((chartype == ucp_Lu || - chartype == ucp_Ll || - chartype == ucp_Lt) == prop_fail_result) - RRETURN(MATCH_NOMATCH); - } - break; - - case PT_GC: - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINCTEST(c, eptr); - if ((UCD_CATEGORY(c) == prop_value) == prop_fail_result) - RRETURN(MATCH_NOMATCH); - } - break; - - case PT_PC: - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINCTEST(c, eptr); - if ((UCD_CHARTYPE(c) == prop_value) == prop_fail_result) - RRETURN(MATCH_NOMATCH); - } - break; - - case PT_SC: - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINCTEST(c, eptr); - if ((UCD_SCRIPT(c) == prop_value) == prop_fail_result) - RRETURN(MATCH_NOMATCH); - } - break; - - case PT_ALNUM: - for (i = 1; i <= min; i++) - { - int category; - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINCTEST(c, eptr); - category = UCD_CATEGORY(c); - if ((category == ucp_L || category == ucp_N) == prop_fail_result) - RRETURN(MATCH_NOMATCH); - } - break; - - /* Perl space used to exclude VT, but from Perl 5.18 it is included, - which means that Perl space and POSIX space are now identical. PCRE - was changed at release 8.34. */ - - case PT_SPACE: /* Perl space */ - case PT_PXSPACE: /* POSIX space */ - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINCTEST(c, eptr); - switch(c) - { - HSPACE_CASES: - VSPACE_CASES: - if (prop_fail_result) RRETURN(MATCH_NOMATCH); - break; - - default: - if ((UCD_CATEGORY(c) == ucp_Z) == prop_fail_result) - RRETURN(MATCH_NOMATCH); - break; - } - } - break; - - case PT_WORD: - for (i = 1; i <= min; i++) - { - int category; - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINCTEST(c, eptr); - category = UCD_CATEGORY(c); - if ((category == ucp_L || category == ucp_N || c == CHAR_UNDERSCORE) - == prop_fail_result) - RRETURN(MATCH_NOMATCH); - } - break; - - case PT_CLIST: - for (i = 1; i <= min; i++) - { - const pcre_uint32 *cp; - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINCTEST(c, eptr); - cp = PRIV(ucd_caseless_sets) + prop_value; - for (;;) - { - if (c < *cp) - { if (prop_fail_result) break; else { RRETURN(MATCH_NOMATCH); } } - if (c == *cp++) - { if (prop_fail_result) { RRETURN(MATCH_NOMATCH); } else break; } - } - } - break; - - case PT_UCNC: - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINCTEST(c, eptr); - if ((c == CHAR_DOLLAR_SIGN || c == CHAR_COMMERCIAL_AT || - c == CHAR_GRAVE_ACCENT || (c >= 0xa0 && c <= 0xd7ff) || - c >= 0xe000) == prop_fail_result) - RRETURN(MATCH_NOMATCH); - } - break; - - /* This should not occur */ - - default: - RRETURN(PCRE_ERROR_INTERNAL); - } - } - - /* Match extended Unicode sequences. We will get here only if the - support is in the binary; otherwise a compile-time error occurs. */ - - else if (ctype == OP_EXTUNI) - { - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - else - { - int lgb, rgb; - GETCHARINCTEST(c, eptr); - lgb = UCD_GRAPHBREAK(c); - while (eptr < md->end_subject) - { - int len = 1; - if (!utf) c = *eptr; else { GETCHARLEN(c, eptr, len); } - rgb = UCD_GRAPHBREAK(c); - if ((PRIV(ucp_gbtable)[lgb] & (1 << rgb)) == 0) break; - lgb = rgb; - eptr += len; - } - } - CHECK_PARTIAL(); - } - } - - else -#endif /* SUPPORT_UCP */ - -/* Handle all other cases when the coding is UTF-8 */ - -#ifdef SUPPORT_UTF - if (utf) switch(ctype) - { - case OP_ANY: - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - if (IS_NEWLINE(eptr)) RRETURN(MATCH_NOMATCH); - if (md->partial != 0 && - eptr + 1 >= md->end_subject && - NLBLOCK->nltype == NLTYPE_FIXED && - NLBLOCK->nllen == 2 && - UCHAR21(eptr) == NLBLOCK->nl[0]) - { - md->hitend = TRUE; - if (md->partial > 1) RRETURN(PCRE_ERROR_PARTIAL); - } - eptr++; - ACROSSCHAR(eptr < md->end_subject, *eptr, eptr++); - } - break; - - case OP_ALLANY: - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - eptr++; - ACROSSCHAR(eptr < md->end_subject, *eptr, eptr++); - } - break; - - case OP_ANYBYTE: - if (eptr > md->end_subject - min) RRETURN(MATCH_NOMATCH); - eptr += min; - break; - - case OP_ANYNL: - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINC(c, eptr); - switch(c) - { - default: RRETURN(MATCH_NOMATCH); - - case CHAR_CR: - if (eptr < md->end_subject && UCHAR21(eptr) == CHAR_LF) eptr++; - break; - - case CHAR_LF: - break; - - case CHAR_VT: - case CHAR_FF: - case CHAR_NEL: -#ifndef EBCDIC - case 0x2028: - case 0x2029: -#endif /* Not EBCDIC */ - if (md->bsr_anycrlf) RRETURN(MATCH_NOMATCH); - break; - } - } - break; - - case OP_NOT_HSPACE: - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINC(c, eptr); - switch(c) - { - HSPACE_CASES: RRETURN(MATCH_NOMATCH); /* Byte and multibyte cases */ - default: break; - } - } - break; - - case OP_HSPACE: - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINC(c, eptr); - switch(c) - { - HSPACE_CASES: break; /* Byte and multibyte cases */ - default: RRETURN(MATCH_NOMATCH); - } - } - break; - - case OP_NOT_VSPACE: - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINC(c, eptr); - switch(c) - { - VSPACE_CASES: RRETURN(MATCH_NOMATCH); - default: break; - } - } - break; - - case OP_VSPACE: - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINC(c, eptr); - switch(c) - { - VSPACE_CASES: break; - default: RRETURN(MATCH_NOMATCH); - } - } - break; - - case OP_NOT_DIGIT: - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINC(c, eptr); - if (c < 128 && (md->ctypes[c] & ctype_digit) != 0) - RRETURN(MATCH_NOMATCH); - } - break; - - case OP_DIGIT: - for (i = 1; i <= min; i++) - { - pcre_uint32 cc; - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - cc = UCHAR21(eptr); - if (cc >= 128 || (md->ctypes[cc] & ctype_digit) == 0) - RRETURN(MATCH_NOMATCH); - eptr++; - /* No need to skip more bytes - we know it's a 1-byte character */ - } - break; - - case OP_NOT_WHITESPACE: - for (i = 1; i <= min; i++) - { - pcre_uint32 cc; - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - cc = UCHAR21(eptr); - if (cc < 128 && (md->ctypes[cc] & ctype_space) != 0) - RRETURN(MATCH_NOMATCH); - eptr++; - ACROSSCHAR(eptr < md->end_subject, *eptr, eptr++); - } - break; - - case OP_WHITESPACE: - for (i = 1; i <= min; i++) - { - pcre_uint32 cc; - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - cc = UCHAR21(eptr); - if (cc >= 128 || (md->ctypes[cc] & ctype_space) == 0) - RRETURN(MATCH_NOMATCH); - eptr++; - /* No need to skip more bytes - we know it's a 1-byte character */ - } - break; - - case OP_NOT_WORDCHAR: - for (i = 1; i <= min; i++) - { - pcre_uint32 cc; - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - cc = UCHAR21(eptr); - if (cc < 128 && (md->ctypes[cc] & ctype_word) != 0) - RRETURN(MATCH_NOMATCH); - eptr++; - ACROSSCHAR(eptr < md->end_subject, *eptr, eptr++); - } - break; - - case OP_WORDCHAR: - for (i = 1; i <= min; i++) - { - pcre_uint32 cc; - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - cc = UCHAR21(eptr); - if (cc >= 128 || (md->ctypes[cc] & ctype_word) == 0) - RRETURN(MATCH_NOMATCH); - eptr++; - /* No need to skip more bytes - we know it's a 1-byte character */ - } - break; - - default: - RRETURN(PCRE_ERROR_INTERNAL); - } /* End switch(ctype) */ - - else -#endif /* SUPPORT_UTF */ - - /* Code for the non-UTF-8 case for minimum matching of operators other - than OP_PROP and OP_NOTPROP. */ - - switch(ctype) - { - case OP_ANY: - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - if (IS_NEWLINE(eptr)) RRETURN(MATCH_NOMATCH); - if (md->partial != 0 && - eptr + 1 >= md->end_subject && - NLBLOCK->nltype == NLTYPE_FIXED && - NLBLOCK->nllen == 2 && - *eptr == NLBLOCK->nl[0]) - { - md->hitend = TRUE; - if (md->partial > 1) RRETURN(PCRE_ERROR_PARTIAL); - } - eptr++; - } - break; - - case OP_ALLANY: - if (eptr > md->end_subject - min) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - eptr += min; - break; - - case OP_ANYBYTE: - if (eptr > md->end_subject - min) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - eptr += min; - break; - - case OP_ANYNL: - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - switch(*eptr++) - { - default: RRETURN(MATCH_NOMATCH); - - case CHAR_CR: - if (eptr < md->end_subject && *eptr == CHAR_LF) eptr++; - break; - - case CHAR_LF: - break; - - case CHAR_VT: - case CHAR_FF: - case CHAR_NEL: -#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 - case 0x2028: - case 0x2029: -#endif - if (md->bsr_anycrlf) RRETURN(MATCH_NOMATCH); - break; - } - } - break; - - case OP_NOT_HSPACE: - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - switch(*eptr++) - { - default: break; - HSPACE_BYTE_CASES: -#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 - HSPACE_MULTIBYTE_CASES: -#endif - RRETURN(MATCH_NOMATCH); - } - } - break; - - case OP_HSPACE: - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - switch(*eptr++) - { - default: RRETURN(MATCH_NOMATCH); - HSPACE_BYTE_CASES: -#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 - HSPACE_MULTIBYTE_CASES: -#endif - break; - } - } - break; - - case OP_NOT_VSPACE: - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - switch(*eptr++) - { - VSPACE_BYTE_CASES: -#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 - VSPACE_MULTIBYTE_CASES: -#endif - RRETURN(MATCH_NOMATCH); - default: break; - } - } - break; - - case OP_VSPACE: - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - switch(*eptr++) - { - default: RRETURN(MATCH_NOMATCH); - VSPACE_BYTE_CASES: -#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 - VSPACE_MULTIBYTE_CASES: -#endif - break; - } - } - break; - - case OP_NOT_DIGIT: - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - if (MAX_255(*eptr) && (md->ctypes[*eptr] & ctype_digit) != 0) - RRETURN(MATCH_NOMATCH); - eptr++; - } - break; - - case OP_DIGIT: - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - if (!MAX_255(*eptr) || (md->ctypes[*eptr] & ctype_digit) == 0) - RRETURN(MATCH_NOMATCH); - eptr++; - } - break; - - case OP_NOT_WHITESPACE: - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - if (MAX_255(*eptr) && (md->ctypes[*eptr] & ctype_space) != 0) - RRETURN(MATCH_NOMATCH); - eptr++; - } - break; - - case OP_WHITESPACE: - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - if (!MAX_255(*eptr) || (md->ctypes[*eptr] & ctype_space) == 0) - RRETURN(MATCH_NOMATCH); - eptr++; - } - break; - - case OP_NOT_WORDCHAR: - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - if (MAX_255(*eptr) && (md->ctypes[*eptr] & ctype_word) != 0) - RRETURN(MATCH_NOMATCH); - eptr++; - } - break; - - case OP_WORDCHAR: - for (i = 1; i <= min; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - if (!MAX_255(*eptr) || (md->ctypes[*eptr] & ctype_word) == 0) - RRETURN(MATCH_NOMATCH); - eptr++; - } - break; - - default: - RRETURN(PCRE_ERROR_INTERNAL); - } - } - - /* If min = max, continue at the same level without recursing */ - - if (min == max) continue; - - /* If minimizing, we have to test the rest of the pattern before each - subsequent match. Again, separate the UTF-8 case for speed, and also - separate the UCP cases. */ - - if (minimize) - { -#ifdef SUPPORT_UCP - if (prop_type >= 0) - { - switch(prop_type) - { - case PT_ANY: - for (fi = min;; fi++) - { - RMATCH(eptr, ecode, offset_top, md, eptrb, RM36); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (fi >= max) RRETURN(MATCH_NOMATCH); - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINCTEST(c, eptr); - if (prop_fail_result) RRETURN(MATCH_NOMATCH); - } - /* Control never gets here */ - - case PT_LAMP: - for (fi = min;; fi++) - { - int chartype; - RMATCH(eptr, ecode, offset_top, md, eptrb, RM37); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (fi >= max) RRETURN(MATCH_NOMATCH); - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINCTEST(c, eptr); - chartype = UCD_CHARTYPE(c); - if ((chartype == ucp_Lu || - chartype == ucp_Ll || - chartype == ucp_Lt) == prop_fail_result) - RRETURN(MATCH_NOMATCH); - } - /* Control never gets here */ - - case PT_GC: - for (fi = min;; fi++) - { - RMATCH(eptr, ecode, offset_top, md, eptrb, RM38); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (fi >= max) RRETURN(MATCH_NOMATCH); - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINCTEST(c, eptr); - if ((UCD_CATEGORY(c) == prop_value) == prop_fail_result) - RRETURN(MATCH_NOMATCH); - } - /* Control never gets here */ - - case PT_PC: - for (fi = min;; fi++) - { - RMATCH(eptr, ecode, offset_top, md, eptrb, RM39); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (fi >= max) RRETURN(MATCH_NOMATCH); - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINCTEST(c, eptr); - if ((UCD_CHARTYPE(c) == prop_value) == prop_fail_result) - RRETURN(MATCH_NOMATCH); - } - /* Control never gets here */ - - case PT_SC: - for (fi = min;; fi++) - { - RMATCH(eptr, ecode, offset_top, md, eptrb, RM40); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (fi >= max) RRETURN(MATCH_NOMATCH); - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINCTEST(c, eptr); - if ((UCD_SCRIPT(c) == prop_value) == prop_fail_result) - RRETURN(MATCH_NOMATCH); - } - /* Control never gets here */ - - case PT_ALNUM: - for (fi = min;; fi++) - { - int category; - RMATCH(eptr, ecode, offset_top, md, eptrb, RM59); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (fi >= max) RRETURN(MATCH_NOMATCH); - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINCTEST(c, eptr); - category = UCD_CATEGORY(c); - if ((category == ucp_L || category == ucp_N) == prop_fail_result) - RRETURN(MATCH_NOMATCH); - } - /* Control never gets here */ - - /* Perl space used to exclude VT, but from Perl 5.18 it is included, - which means that Perl space and POSIX space are now identical. PCRE - was changed at release 8.34. */ - - case PT_SPACE: /* Perl space */ - case PT_PXSPACE: /* POSIX space */ - for (fi = min;; fi++) - { - RMATCH(eptr, ecode, offset_top, md, eptrb, RM61); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (fi >= max) RRETURN(MATCH_NOMATCH); - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINCTEST(c, eptr); - switch(c) - { - HSPACE_CASES: - VSPACE_CASES: - if (prop_fail_result) RRETURN(MATCH_NOMATCH); - break; - - default: - if ((UCD_CATEGORY(c) == ucp_Z) == prop_fail_result) - RRETURN(MATCH_NOMATCH); - break; - } - } - /* Control never gets here */ - - case PT_WORD: - for (fi = min;; fi++) - { - int category; - RMATCH(eptr, ecode, offset_top, md, eptrb, RM62); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (fi >= max) RRETURN(MATCH_NOMATCH); - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINCTEST(c, eptr); - category = UCD_CATEGORY(c); - if ((category == ucp_L || - category == ucp_N || - c == CHAR_UNDERSCORE) - == prop_fail_result) - RRETURN(MATCH_NOMATCH); - } - /* Control never gets here */ - - case PT_CLIST: - for (fi = min;; fi++) - { - const pcre_uint32 *cp; - RMATCH(eptr, ecode, offset_top, md, eptrb, RM67); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (fi >= max) RRETURN(MATCH_NOMATCH); - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINCTEST(c, eptr); - cp = PRIV(ucd_caseless_sets) + prop_value; - for (;;) - { - if (c < *cp) - { if (prop_fail_result) break; else { RRETURN(MATCH_NOMATCH); } } - if (c == *cp++) - { if (prop_fail_result) { RRETURN(MATCH_NOMATCH); } else break; } - } - } - /* Control never gets here */ - - case PT_UCNC: - for (fi = min;; fi++) - { - RMATCH(eptr, ecode, offset_top, md, eptrb, RM60); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (fi >= max) RRETURN(MATCH_NOMATCH); - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - GETCHARINCTEST(c, eptr); - if ((c == CHAR_DOLLAR_SIGN || c == CHAR_COMMERCIAL_AT || - c == CHAR_GRAVE_ACCENT || (c >= 0xa0 && c <= 0xd7ff) || - c >= 0xe000) == prop_fail_result) - RRETURN(MATCH_NOMATCH); - } - /* Control never gets here */ - - /* This should never occur */ - default: - RRETURN(PCRE_ERROR_INTERNAL); - } - } - - /* Match extended Unicode sequences. We will get here only if the - support is in the binary; otherwise a compile-time error occurs. */ - - else if (ctype == OP_EXTUNI) - { - for (fi = min;; fi++) - { - RMATCH(eptr, ecode, offset_top, md, eptrb, RM41); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (fi >= max) RRETURN(MATCH_NOMATCH); - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - else - { - int lgb, rgb; - GETCHARINCTEST(c, eptr); - lgb = UCD_GRAPHBREAK(c); - while (eptr < md->end_subject) - { - int len = 1; - if (!utf) c = *eptr; else { GETCHARLEN(c, eptr, len); } - rgb = UCD_GRAPHBREAK(c); - if ((PRIV(ucp_gbtable)[lgb] & (1 << rgb)) == 0) break; - lgb = rgb; - eptr += len; - } - } - CHECK_PARTIAL(); - } - } - else -#endif /* SUPPORT_UCP */ - -#ifdef SUPPORT_UTF - if (utf) - { - for (fi = min;; fi++) - { - RMATCH(eptr, ecode, offset_top, md, eptrb, RM42); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (fi >= max) RRETURN(MATCH_NOMATCH); - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - if (ctype == OP_ANY && IS_NEWLINE(eptr)) - RRETURN(MATCH_NOMATCH); - GETCHARINC(c, eptr); - switch(ctype) - { - case OP_ANY: /* This is the non-NL case */ - if (md->partial != 0 && /* Take care with CRLF partial */ - eptr >= md->end_subject && - NLBLOCK->nltype == NLTYPE_FIXED && - NLBLOCK->nllen == 2 && - c == NLBLOCK->nl[0]) - { - md->hitend = TRUE; - if (md->partial > 1) RRETURN(PCRE_ERROR_PARTIAL); - } - break; - - case OP_ALLANY: - case OP_ANYBYTE: - break; - - case OP_ANYNL: - switch(c) - { - default: RRETURN(MATCH_NOMATCH); - case CHAR_CR: - if (eptr < md->end_subject && UCHAR21(eptr) == CHAR_LF) eptr++; - break; - - case CHAR_LF: - break; - - case CHAR_VT: - case CHAR_FF: - case CHAR_NEL: -#ifndef EBCDIC - case 0x2028: - case 0x2029: -#endif /* Not EBCDIC */ - if (md->bsr_anycrlf) RRETURN(MATCH_NOMATCH); - break; - } - break; - - case OP_NOT_HSPACE: - switch(c) - { - HSPACE_CASES: RRETURN(MATCH_NOMATCH); - default: break; - } - break; - - case OP_HSPACE: - switch(c) - { - HSPACE_CASES: break; - default: RRETURN(MATCH_NOMATCH); - } - break; - - case OP_NOT_VSPACE: - switch(c) - { - VSPACE_CASES: RRETURN(MATCH_NOMATCH); - default: break; - } - break; - - case OP_VSPACE: - switch(c) - { - VSPACE_CASES: break; - default: RRETURN(MATCH_NOMATCH); - } - break; - - case OP_NOT_DIGIT: - if (c < 256 && (md->ctypes[c] & ctype_digit) != 0) - RRETURN(MATCH_NOMATCH); - break; - - case OP_DIGIT: - if (c >= 256 || (md->ctypes[c] & ctype_digit) == 0) - RRETURN(MATCH_NOMATCH); - break; - - case OP_NOT_WHITESPACE: - if (c < 256 && (md->ctypes[c] & ctype_space) != 0) - RRETURN(MATCH_NOMATCH); - break; - - case OP_WHITESPACE: - if (c >= 256 || (md->ctypes[c] & ctype_space) == 0) - RRETURN(MATCH_NOMATCH); - break; - - case OP_NOT_WORDCHAR: - if (c < 256 && (md->ctypes[c] & ctype_word) != 0) - RRETURN(MATCH_NOMATCH); - break; - - case OP_WORDCHAR: - if (c >= 256 || (md->ctypes[c] & ctype_word) == 0) - RRETURN(MATCH_NOMATCH); - break; - - default: - RRETURN(PCRE_ERROR_INTERNAL); - } - } - } - else -#endif - /* Not UTF mode */ - { - for (fi = min;; fi++) - { - RMATCH(eptr, ecode, offset_top, md, eptrb, RM43); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - if (fi >= max) RRETURN(MATCH_NOMATCH); - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - RRETURN(MATCH_NOMATCH); - } - if (ctype == OP_ANY && IS_NEWLINE(eptr)) - RRETURN(MATCH_NOMATCH); - c = *eptr++; - switch(ctype) - { - case OP_ANY: /* This is the non-NL case */ - if (md->partial != 0 && /* Take care with CRLF partial */ - eptr >= md->end_subject && - NLBLOCK->nltype == NLTYPE_FIXED && - NLBLOCK->nllen == 2 && - c == NLBLOCK->nl[0]) - { - md->hitend = TRUE; - if (md->partial > 1) RRETURN(PCRE_ERROR_PARTIAL); - } - break; - - case OP_ALLANY: - case OP_ANYBYTE: - break; - - case OP_ANYNL: - switch(c) - { - default: RRETURN(MATCH_NOMATCH); - case CHAR_CR: - if (eptr < md->end_subject && *eptr == CHAR_LF) eptr++; - break; - - case CHAR_LF: - break; - - case CHAR_VT: - case CHAR_FF: - case CHAR_NEL: -#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 - case 0x2028: - case 0x2029: -#endif - if (md->bsr_anycrlf) RRETURN(MATCH_NOMATCH); - break; - } - break; - - case OP_NOT_HSPACE: - switch(c) - { - default: break; - HSPACE_BYTE_CASES: -#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 - HSPACE_MULTIBYTE_CASES: -#endif - RRETURN(MATCH_NOMATCH); - } - break; - - case OP_HSPACE: - switch(c) - { - default: RRETURN(MATCH_NOMATCH); - HSPACE_BYTE_CASES: -#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 - HSPACE_MULTIBYTE_CASES: -#endif - break; - } - break; - - case OP_NOT_VSPACE: - switch(c) - { - default: break; - VSPACE_BYTE_CASES: -#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 - VSPACE_MULTIBYTE_CASES: -#endif - RRETURN(MATCH_NOMATCH); - } - break; - - case OP_VSPACE: - switch(c) - { - default: RRETURN(MATCH_NOMATCH); - VSPACE_BYTE_CASES: -#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 - VSPACE_MULTIBYTE_CASES: -#endif - break; - } - break; - - case OP_NOT_DIGIT: - if (MAX_255(c) && (md->ctypes[c] & ctype_digit) != 0) RRETURN(MATCH_NOMATCH); - break; - - case OP_DIGIT: - if (!MAX_255(c) || (md->ctypes[c] & ctype_digit) == 0) RRETURN(MATCH_NOMATCH); - break; - - case OP_NOT_WHITESPACE: - if (MAX_255(c) && (md->ctypes[c] & ctype_space) != 0) RRETURN(MATCH_NOMATCH); - break; - - case OP_WHITESPACE: - if (!MAX_255(c) || (md->ctypes[c] & ctype_space) == 0) RRETURN(MATCH_NOMATCH); - break; - - case OP_NOT_WORDCHAR: - if (MAX_255(c) && (md->ctypes[c] & ctype_word) != 0) RRETURN(MATCH_NOMATCH); - break; - - case OP_WORDCHAR: - if (!MAX_255(c) || (md->ctypes[c] & ctype_word) == 0) RRETURN(MATCH_NOMATCH); - break; - - default: - RRETURN(PCRE_ERROR_INTERNAL); - } - } - } - /* Control never gets here */ - } - - /* If maximizing, it is worth using inline code for speed, doing the type - test once at the start (i.e. keep it out of the loop). Again, keep the - UTF-8 and UCP stuff separate. */ - - else - { - pp = eptr; /* Remember where we started */ - -#ifdef SUPPORT_UCP - if (prop_type >= 0) - { - switch(prop_type) - { - case PT_ANY: - for (i = min; i < max; i++) - { - int len = 1; - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - break; - } - GETCHARLENTEST(c, eptr, len); - if (prop_fail_result) break; - eptr+= len; - } - break; - - case PT_LAMP: - for (i = min; i < max; i++) - { - int chartype; - int len = 1; - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - break; - } - GETCHARLENTEST(c, eptr, len); - chartype = UCD_CHARTYPE(c); - if ((chartype == ucp_Lu || - chartype == ucp_Ll || - chartype == ucp_Lt) == prop_fail_result) - break; - eptr+= len; - } - break; - - case PT_GC: - for (i = min; i < max; i++) - { - int len = 1; - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - break; - } - GETCHARLENTEST(c, eptr, len); - if ((UCD_CATEGORY(c) == prop_value) == prop_fail_result) break; - eptr+= len; - } - break; - - case PT_PC: - for (i = min; i < max; i++) - { - int len = 1; - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - break; - } - GETCHARLENTEST(c, eptr, len); - if ((UCD_CHARTYPE(c) == prop_value) == prop_fail_result) break; - eptr+= len; - } - break; - - case PT_SC: - for (i = min; i < max; i++) - { - int len = 1; - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - break; - } - GETCHARLENTEST(c, eptr, len); - if ((UCD_SCRIPT(c) == prop_value) == prop_fail_result) break; - eptr+= len; - } - break; - - case PT_ALNUM: - for (i = min; i < max; i++) - { - int category; - int len = 1; - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - break; - } - GETCHARLENTEST(c, eptr, len); - category = UCD_CATEGORY(c); - if ((category == ucp_L || category == ucp_N) == prop_fail_result) - break; - eptr+= len; - } - break; - - /* Perl space used to exclude VT, but from Perl 5.18 it is included, - which means that Perl space and POSIX space are now identical. PCRE - was changed at release 8.34. */ - - case PT_SPACE: /* Perl space */ - case PT_PXSPACE: /* POSIX space */ - for (i = min; i < max; i++) - { - int len = 1; - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - break; - } - GETCHARLENTEST(c, eptr, len); - switch(c) - { - HSPACE_CASES: - VSPACE_CASES: - if (prop_fail_result) goto ENDLOOP99; /* Break the loop */ - break; - - default: - if ((UCD_CATEGORY(c) == ucp_Z) == prop_fail_result) - goto ENDLOOP99; /* Break the loop */ - break; - } - eptr+= len; - } - ENDLOOP99: - break; - - case PT_WORD: - for (i = min; i < max; i++) - { - int category; - int len = 1; - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - break; - } - GETCHARLENTEST(c, eptr, len); - category = UCD_CATEGORY(c); - if ((category == ucp_L || category == ucp_N || - c == CHAR_UNDERSCORE) == prop_fail_result) - break; - eptr+= len; - } - break; - - case PT_CLIST: - for (i = min; i < max; i++) - { - const pcre_uint32 *cp; - int len = 1; - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - break; - } - GETCHARLENTEST(c, eptr, len); - cp = PRIV(ucd_caseless_sets) + prop_value; - for (;;) - { - if (c < *cp) - { if (prop_fail_result) break; else goto GOT_MAX; } - if (c == *cp++) - { if (prop_fail_result) goto GOT_MAX; else break; } - } - eptr += len; - } - GOT_MAX: - break; - - case PT_UCNC: - for (i = min; i < max; i++) - { - int len = 1; - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - break; - } - GETCHARLENTEST(c, eptr, len); - if ((c == CHAR_DOLLAR_SIGN || c == CHAR_COMMERCIAL_AT || - c == CHAR_GRAVE_ACCENT || (c >= 0xa0 && c <= 0xd7ff) || - c >= 0xe000) == prop_fail_result) - break; - eptr += len; - } - break; - - default: - RRETURN(PCRE_ERROR_INTERNAL); - } - - /* eptr is now past the end of the maximum run */ - - if (possessive) continue; /* No backtracking */ - for(;;) - { - if (eptr == pp) goto TAIL_RECURSE; - RMATCH(eptr, ecode, offset_top, md, eptrb, RM44); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - eptr--; - if (utf) BACKCHAR(eptr); - } - } - - /* Match extended Unicode grapheme clusters. We will get here only if the - support is in the binary; otherwise a compile-time error occurs. */ - - else if (ctype == OP_EXTUNI) - { - for (i = min; i < max; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - break; - } - else - { - int lgb, rgb; - GETCHARINCTEST(c, eptr); - lgb = UCD_GRAPHBREAK(c); - while (eptr < md->end_subject) - { - int len = 1; - if (!utf) c = *eptr; else { GETCHARLEN(c, eptr, len); } - rgb = UCD_GRAPHBREAK(c); - if ((PRIV(ucp_gbtable)[lgb] & (1 << rgb)) == 0) break; - lgb = rgb; - eptr += len; - } - } - CHECK_PARTIAL(); - } - - /* eptr is now past the end of the maximum run */ - - if (possessive) continue; /* No backtracking */ - - for(;;) - { - int lgb, rgb; - PCRE_PUCHAR fptr; - - if (eptr == pp) goto TAIL_RECURSE; /* At start of char run */ - RMATCH(eptr, ecode, offset_top, md, eptrb, RM45); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - - /* Backtracking over an extended grapheme cluster involves inspecting - the previous two characters (if present) to see if a break is - permitted between them. */ - - eptr--; - if (!utf) c = *eptr; else - { - BACKCHAR(eptr); - GETCHAR(c, eptr); - } - rgb = UCD_GRAPHBREAK(c); - - for (;;) - { - if (eptr == pp) goto TAIL_RECURSE; /* At start of char run */ - fptr = eptr - 1; - if (!utf) c = *fptr; else - { - BACKCHAR(fptr); - GETCHAR(c, fptr); - } - lgb = UCD_GRAPHBREAK(c); - if ((PRIV(ucp_gbtable)[lgb] & (1 << rgb)) == 0) break; - eptr = fptr; - rgb = lgb; - } - } - } - - else -#endif /* SUPPORT_UCP */ - -#ifdef SUPPORT_UTF - if (utf) - { - switch(ctype) - { - case OP_ANY: - for (i = min; i < max; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - break; - } - if (IS_NEWLINE(eptr)) break; - if (md->partial != 0 && /* Take care with CRLF partial */ - eptr + 1 >= md->end_subject && - NLBLOCK->nltype == NLTYPE_FIXED && - NLBLOCK->nllen == 2 && - UCHAR21(eptr) == NLBLOCK->nl[0]) - { - md->hitend = TRUE; - if (md->partial > 1) RRETURN(PCRE_ERROR_PARTIAL); - } - eptr++; - ACROSSCHAR(eptr < md->end_subject, *eptr, eptr++); - } - break; - - case OP_ALLANY: - if (max < INT_MAX) - { - for (i = min; i < max; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - break; - } - eptr++; - ACROSSCHAR(eptr < md->end_subject, *eptr, eptr++); - } - } - else - { - eptr = md->end_subject; /* Unlimited UTF-8 repeat */ - SCHECK_PARTIAL(); - } - break; - - /* The byte case is the same as non-UTF8 */ - - case OP_ANYBYTE: - c = max - min; - if (c > (unsigned int)(md->end_subject - eptr)) - { - eptr = md->end_subject; - SCHECK_PARTIAL(); - } - else eptr += c; - break; - - case OP_ANYNL: - for (i = min; i < max; i++) - { - int len = 1; - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - break; - } - GETCHARLEN(c, eptr, len); - if (c == CHAR_CR) - { - if (++eptr >= md->end_subject) break; - if (UCHAR21(eptr) == CHAR_LF) eptr++; - } - else - { - if (c != CHAR_LF && - (md->bsr_anycrlf || - (c != CHAR_VT && c != CHAR_FF && c != CHAR_NEL -#ifndef EBCDIC - && c != 0x2028 && c != 0x2029 -#endif /* Not EBCDIC */ - ))) - break; - eptr += len; - } - } - break; - - case OP_NOT_HSPACE: - case OP_HSPACE: - for (i = min; i < max; i++) - { - BOOL gotspace; - int len = 1; - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - break; - } - GETCHARLEN(c, eptr, len); - switch(c) - { - HSPACE_CASES: gotspace = TRUE; break; - default: gotspace = FALSE; break; - } - if (gotspace == (ctype == OP_NOT_HSPACE)) break; - eptr += len; - } - break; - - case OP_NOT_VSPACE: - case OP_VSPACE: - for (i = min; i < max; i++) - { - BOOL gotspace; - int len = 1; - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - break; - } - GETCHARLEN(c, eptr, len); - switch(c) - { - VSPACE_CASES: gotspace = TRUE; break; - default: gotspace = FALSE; break; - } - if (gotspace == (ctype == OP_NOT_VSPACE)) break; - eptr += len; - } - break; - - case OP_NOT_DIGIT: - for (i = min; i < max; i++) - { - int len = 1; - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - break; - } - GETCHARLEN(c, eptr, len); - if (c < 256 && (md->ctypes[c] & ctype_digit) != 0) break; - eptr+= len; - } - break; - - case OP_DIGIT: - for (i = min; i < max; i++) - { - int len = 1; - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - break; - } - GETCHARLEN(c, eptr, len); - if (c >= 256 ||(md->ctypes[c] & ctype_digit) == 0) break; - eptr+= len; - } - break; - - case OP_NOT_WHITESPACE: - for (i = min; i < max; i++) - { - int len = 1; - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - break; - } - GETCHARLEN(c, eptr, len); - if (c < 256 && (md->ctypes[c] & ctype_space) != 0) break; - eptr+= len; - } - break; - - case OP_WHITESPACE: - for (i = min; i < max; i++) - { - int len = 1; - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - break; - } - GETCHARLEN(c, eptr, len); - if (c >= 256 ||(md->ctypes[c] & ctype_space) == 0) break; - eptr+= len; - } - break; - - case OP_NOT_WORDCHAR: - for (i = min; i < max; i++) - { - int len = 1; - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - break; - } - GETCHARLEN(c, eptr, len); - if (c < 256 && (md->ctypes[c] & ctype_word) != 0) break; - eptr+= len; - } - break; - - case OP_WORDCHAR: - for (i = min; i < max; i++) - { - int len = 1; - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - break; - } - GETCHARLEN(c, eptr, len); - if (c >= 256 || (md->ctypes[c] & ctype_word) == 0) break; - eptr+= len; - } - break; - - default: - RRETURN(PCRE_ERROR_INTERNAL); - } - - if (possessive) continue; /* No backtracking */ - for(;;) - { - if (eptr == pp) goto TAIL_RECURSE; - RMATCH(eptr, ecode, offset_top, md, eptrb, RM46); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - eptr--; - BACKCHAR(eptr); - if (ctype == OP_ANYNL && eptr > pp && UCHAR21(eptr) == CHAR_NL && - UCHAR21(eptr - 1) == CHAR_CR) eptr--; - } - } - else -#endif /* SUPPORT_UTF */ - /* Not UTF mode */ - { - switch(ctype) - { - case OP_ANY: - for (i = min; i < max; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - break; - } - if (IS_NEWLINE(eptr)) break; - if (md->partial != 0 && /* Take care with CRLF partial */ - eptr + 1 >= md->end_subject && - NLBLOCK->nltype == NLTYPE_FIXED && - NLBLOCK->nllen == 2 && - *eptr == NLBLOCK->nl[0]) - { - md->hitend = TRUE; - if (md->partial > 1) RRETURN(PCRE_ERROR_PARTIAL); - } - eptr++; - } - break; - - case OP_ALLANY: - case OP_ANYBYTE: - c = max - min; - if (c > (unsigned int)(md->end_subject - eptr)) - { - eptr = md->end_subject; - SCHECK_PARTIAL(); - } - else eptr += c; - break; - - case OP_ANYNL: - for (i = min; i < max; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - break; - } - c = *eptr; - if (c == CHAR_CR) - { - if (++eptr >= md->end_subject) break; - if (*eptr == CHAR_LF) eptr++; - } - else - { - if (c != CHAR_LF && (md->bsr_anycrlf || - (c != CHAR_VT && c != CHAR_FF && c != CHAR_NEL -#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 - && c != 0x2028 && c != 0x2029 -#endif - ))) break; - eptr++; - } - } - break; - - case OP_NOT_HSPACE: - for (i = min; i < max; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - break; - } - switch(*eptr) - { - default: eptr++; break; - HSPACE_BYTE_CASES: -#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 - HSPACE_MULTIBYTE_CASES: -#endif - goto ENDLOOP00; - } - } - ENDLOOP00: - break; - - case OP_HSPACE: - for (i = min; i < max; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - break; - } - switch(*eptr) - { - default: goto ENDLOOP01; - HSPACE_BYTE_CASES: -#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 - HSPACE_MULTIBYTE_CASES: -#endif - eptr++; break; - } - } - ENDLOOP01: - break; - - case OP_NOT_VSPACE: - for (i = min; i < max; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - break; - } - switch(*eptr) - { - default: eptr++; break; - VSPACE_BYTE_CASES: -#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 - VSPACE_MULTIBYTE_CASES: -#endif - goto ENDLOOP02; - } - } - ENDLOOP02: - break; - - case OP_VSPACE: - for (i = min; i < max; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - break; - } - switch(*eptr) - { - default: goto ENDLOOP03; - VSPACE_BYTE_CASES: -#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 - VSPACE_MULTIBYTE_CASES: -#endif - eptr++; break; - } - } - ENDLOOP03: - break; - - case OP_NOT_DIGIT: - for (i = min; i < max; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - break; - } - if (MAX_255(*eptr) && (md->ctypes[*eptr] & ctype_digit) != 0) break; - eptr++; - } - break; - - case OP_DIGIT: - for (i = min; i < max; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - break; - } - if (!MAX_255(*eptr) || (md->ctypes[*eptr] & ctype_digit) == 0) break; - eptr++; - } - break; - - case OP_NOT_WHITESPACE: - for (i = min; i < max; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - break; - } - if (MAX_255(*eptr) && (md->ctypes[*eptr] & ctype_space) != 0) break; - eptr++; - } - break; - - case OP_WHITESPACE: - for (i = min; i < max; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - break; - } - if (!MAX_255(*eptr) || (md->ctypes[*eptr] & ctype_space) == 0) break; - eptr++; - } - break; - - case OP_NOT_WORDCHAR: - for (i = min; i < max; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - break; - } - if (MAX_255(*eptr) && (md->ctypes[*eptr] & ctype_word) != 0) break; - eptr++; - } - break; - - case OP_WORDCHAR: - for (i = min; i < max; i++) - { - if (eptr >= md->end_subject) - { - SCHECK_PARTIAL(); - break; - } - if (!MAX_255(*eptr) || (md->ctypes[*eptr] & ctype_word) == 0) break; - eptr++; - } - break; - - default: - RRETURN(PCRE_ERROR_INTERNAL); - } - - if (possessive) continue; /* No backtracking */ - for (;;) - { - if (eptr == pp) goto TAIL_RECURSE; - RMATCH(eptr, ecode, offset_top, md, eptrb, RM47); - if (rrc != MATCH_NOMATCH) RRETURN(rrc); - eptr--; - if (ctype == OP_ANYNL && eptr > pp && *eptr == CHAR_LF && - eptr[-1] == CHAR_CR) eptr--; - } - } - - /* Control never gets here */ - } - - /* There's been some horrible disaster. Arrival here can only mean there is - something seriously wrong in the code above or the OP_xxx definitions. */ - - default: - DPRINTF(("Unknown opcode %d\n", *ecode)); - RRETURN(PCRE_ERROR_UNKNOWN_OPCODE); - } - - /* Do not stick any code in here without much thought; it is assumed - that "continue" in the code above comes out to here to repeat the main - loop. */ - - } /* End of main loop */ -/* Control never reaches here */ - - -/* When compiling to use the heap rather than the stack for recursive calls to -match(), the RRETURN() macro jumps here. The number that is saved in -frame->Xwhere indicates which label we actually want to return to. */ - -#ifdef NO_RECURSE -#define LBL(val) case val: goto L_RM##val; -HEAP_RETURN: -switch (frame->Xwhere) - { - LBL( 1) LBL( 2) LBL( 3) LBL( 4) LBL( 5) LBL( 6) LBL( 7) LBL( 8) - LBL( 9) LBL(10) LBL(11) LBL(12) LBL(13) LBL(14) LBL(15) LBL(17) - LBL(19) LBL(24) LBL(25) LBL(26) LBL(27) LBL(29) LBL(31) LBL(33) - LBL(35) LBL(43) LBL(47) LBL(48) LBL(49) LBL(50) LBL(51) LBL(52) - LBL(53) LBL(54) LBL(55) LBL(56) LBL(57) LBL(58) LBL(63) LBL(64) - LBL(65) LBL(66) -#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 - LBL(20) LBL(21) -#endif -#ifdef SUPPORT_UTF - LBL(16) LBL(18) - LBL(22) LBL(23) LBL(28) LBL(30) - LBL(32) LBL(34) LBL(42) LBL(46) -#ifdef SUPPORT_UCP - LBL(36) LBL(37) LBL(38) LBL(39) LBL(40) LBL(41) LBL(44) LBL(45) - LBL(59) LBL(60) LBL(61) LBL(62) LBL(67) -#endif /* SUPPORT_UCP */ -#endif /* SUPPORT_UTF */ - default: - DPRINTF(("jump error in pcre match: label %d non-existent\n", frame->Xwhere)); - return PCRE_ERROR_INTERNAL; - } -#undef LBL -#endif /* NO_RECURSE */ -} - - -/*************************************************************************** -**************************************************************************** - RECURSION IN THE match() FUNCTION - -Undefine all the macros that were defined above to handle this. */ - -#ifdef NO_RECURSE -#undef eptr -#undef ecode -#undef mstart -#undef offset_top -#undef eptrb -#undef flags - -#undef callpat -#undef charptr -#undef data -#undef next -#undef pp -#undef prev -#undef saved_eptr - -#undef new_recursive - -#undef cur_is_word -#undef condition -#undef prev_is_word - -#undef ctype -#undef length -#undef max -#undef min -#undef number -#undef offset -#undef op -#undef save_capture_last -#undef save_offset1 -#undef save_offset2 -#undef save_offset3 -#undef stacksave - -#undef newptrb - -#endif - -/* These two are defined as macros in both cases */ - -#undef fc -#undef fi - -/*************************************************************************** -***************************************************************************/ - - -#ifdef NO_RECURSE -/************************************************* -* Release allocated heap frames * -*************************************************/ - -/* This function releases all the allocated frames. The base frame is on the -machine stack, and so must not be freed. - -Argument: the address of the base frame -Returns: nothing -*/ - -static void -release_match_heapframes (heapframe *frame_base) -{ -heapframe *nextframe = frame_base->Xnextframe; -while (nextframe != NULL) - { - heapframe *oldframe = nextframe; - nextframe = nextframe->Xnextframe; - (PUBL(stack_free))(oldframe); - } -} -#endif - - -/************************************************* -* Execute a Regular Expression * -*************************************************/ - -/* This function applies a compiled re to a subject string and picks out -portions of the string if it matches. Two elements in the vector are set for -each substring: the offsets to the start and end of the substring. - -Arguments: - argument_re points to the compiled expression - extra_data points to extra data or is NULL - subject points to the subject string - length length of subject string (may contain binary zeros) - start_offset where to start in the subject string - options option bits - offsets points to a vector of ints to be filled in with offsets - offsetcount the number of elements in the vector - -Returns: > 0 => success; value is the number of elements filled in - = 0 => success, but offsets is not big enough - -1 => failed to match - < -1 => some kind of unexpected problem -*/ - -#if defined COMPILE_PCRE8 -PCRE_EXP_DEFN int PCRE_CALL_CONVENTION -pcre_exec(const pcre *argument_re, const pcre_extra *extra_data, - PCRE_SPTR subject, int length, int start_offset, int options, int *offsets, - int offsetcount) -#elif defined COMPILE_PCRE16 -PCRE_EXP_DEFN int PCRE_CALL_CONVENTION -pcre16_exec(const pcre16 *argument_re, const pcre16_extra *extra_data, - PCRE_SPTR16 subject, int length, int start_offset, int options, int *offsets, - int offsetcount) -#elif defined COMPILE_PCRE32 -PCRE_EXP_DEFN int PCRE_CALL_CONVENTION -pcre32_exec(const pcre32 *argument_re, const pcre32_extra *extra_data, - PCRE_SPTR32 subject, int length, int start_offset, int options, int *offsets, - int offsetcount) -#endif -{ -int rc, ocount, arg_offset_max; -int newline; -BOOL using_temporary_offsets = FALSE; -BOOL anchored; -BOOL startline; -BOOL firstline; -BOOL utf; -BOOL has_first_char = FALSE; -BOOL has_req_char = FALSE; -pcre_uchar first_char = 0; -pcre_uchar first_char2 = 0; -pcre_uchar req_char = 0; -pcre_uchar req_char2 = 0; -match_data match_block; -match_data *md = &match_block; -const pcre_uint8 *tables; -const pcre_uint8 *start_bits = NULL; -PCRE_PUCHAR start_match = (PCRE_PUCHAR)subject + start_offset; -PCRE_PUCHAR end_subject; -PCRE_PUCHAR start_partial = NULL; -PCRE_PUCHAR match_partial = NULL; -PCRE_PUCHAR req_char_ptr = start_match - 1; - -const pcre_study_data *study; -const REAL_PCRE *re = (const REAL_PCRE *)argument_re; - -#ifdef NO_RECURSE -heapframe frame_zero; -frame_zero.Xprevframe = NULL; /* Marks the top level */ -frame_zero.Xnextframe = NULL; /* None are allocated yet */ -md->match_frames_base = &frame_zero; -#endif - -/* Check for the special magic call that measures the size of the stack used -per recursive call of match(). Without the funny casting for sizeof, a Windows -compiler gave this error: "unary minus operator applied to unsigned type, -result still unsigned". Hopefully the cast fixes that. */ - -if (re == NULL && extra_data == NULL && subject == NULL && length == -999 && - start_offset == -999) -#ifdef NO_RECURSE - return -((int)sizeof(heapframe)); -#else - return match(NULL, NULL, NULL, 0, NULL, NULL, 0); -#endif - -/* Plausibility checks */ - -if ((options & ~PUBLIC_EXEC_OPTIONS) != 0) return PCRE_ERROR_BADOPTION; -if (re == NULL || subject == NULL || (offsets == NULL && offsetcount > 0)) - return PCRE_ERROR_NULL; -if (offsetcount < 0) return PCRE_ERROR_BADCOUNT; -if (length < 0) return PCRE_ERROR_BADLENGTH; -if (start_offset < 0 || start_offset > length) return PCRE_ERROR_BADOFFSET; - -/* Check that the first field in the block is the magic number. If it is not, -return with PCRE_ERROR_BADMAGIC. However, if the magic number is equal to -REVERSED_MAGIC_NUMBER we return with PCRE_ERROR_BADENDIANNESS, which -means that the pattern is likely compiled with different endianness. */ - -if (re->magic_number != MAGIC_NUMBER) - return re->magic_number == REVERSED_MAGIC_NUMBER? - PCRE_ERROR_BADENDIANNESS:PCRE_ERROR_BADMAGIC; -if ((re->flags & PCRE_MODE) == 0) return PCRE_ERROR_BADMODE; - -/* These two settings are used in the code for checking a UTF-8 string that -follows immediately afterwards. Other values in the md block are used only -during "normal" pcre_exec() processing, not when the JIT support is in use, -so they are set up later. */ - -/* PCRE_UTF16 has the same value as PCRE_UTF8. */ -utf = md->utf = (re->options & PCRE_UTF8) != 0; -md->partial = ((options & PCRE_PARTIAL_HARD) != 0)? 2 : - ((options & PCRE_PARTIAL_SOFT) != 0)? 1 : 0; - -/* Check a UTF-8 string if required. Pass back the character offset and error -code for an invalid string if a results vector is available. */ - -#ifdef SUPPORT_UTF -if (utf && (options & PCRE_NO_UTF8_CHECK) == 0) - { - int erroroffset; - int errorcode = PRIV(valid_utf)((PCRE_PUCHAR)subject, length, &erroroffset); - if (errorcode != 0) - { - if (offsetcount >= 2) - { - offsets[0] = erroroffset; - offsets[1] = errorcode; - } -#if defined COMPILE_PCRE8 - return (errorcode <= PCRE_UTF8_ERR5 && md->partial > 1)? - PCRE_ERROR_SHORTUTF8 : PCRE_ERROR_BADUTF8; -#elif defined COMPILE_PCRE16 - return (errorcode <= PCRE_UTF16_ERR1 && md->partial > 1)? - PCRE_ERROR_SHORTUTF16 : PCRE_ERROR_BADUTF16; -#elif defined COMPILE_PCRE32 - return PCRE_ERROR_BADUTF32; -#endif - } -#if defined COMPILE_PCRE8 || defined COMPILE_PCRE16 - /* Check that a start_offset points to the start of a UTF character. */ - if (start_offset > 0 && start_offset < length && - NOT_FIRSTCHAR(((PCRE_PUCHAR)subject)[start_offset])) - return PCRE_ERROR_BADUTF8_OFFSET; -#endif - } -#endif - -/* If the pattern was successfully studied with JIT support, run the JIT -executable instead of the rest of this function. Most options must be set at -compile time for the JIT code to be usable. Fallback to the normal code path if -an unsupported flag is set. */ - -#ifdef SUPPORT_JIT -if (extra_data != NULL - && (extra_data->flags & (PCRE_EXTRA_EXECUTABLE_JIT | - PCRE_EXTRA_TABLES)) == PCRE_EXTRA_EXECUTABLE_JIT - && extra_data->executable_jit != NULL - && (options & ~PUBLIC_JIT_EXEC_OPTIONS) == 0) - { - rc = PRIV(jit_exec)(extra_data, (const pcre_uchar *)subject, length, - start_offset, options, offsets, offsetcount); - - /* PCRE_ERROR_NULL means that the selected normal or partial matching - mode is not compiled. In this case we simply fallback to interpreter. */ - - if (rc != PCRE_ERROR_JIT_BADOPTION) return rc; - } -#endif - -/* Carry on with non-JIT matching. This information is for finding all the -numbers associated with a given name, for condition testing. */ - -md->name_table = (pcre_uchar *)re + re->name_table_offset; -md->name_count = re->name_count; -md->name_entry_size = re->name_entry_size; - -/* Fish out the optional data from the extra_data structure, first setting -the default values. */ - -study = NULL; -md->match_limit = MATCH_LIMIT; -md->match_limit_recursion = MATCH_LIMIT_RECURSION; -md->callout_data = NULL; - -/* The table pointer is always in native byte order. */ - -tables = re->tables; - -/* The two limit values override the defaults, whatever their value. */ - -if (extra_data != NULL) - { - unsigned long int flags = extra_data->flags; - if ((flags & PCRE_EXTRA_STUDY_DATA) != 0) - study = (const pcre_study_data *)extra_data->study_data; - if ((flags & PCRE_EXTRA_MATCH_LIMIT) != 0) - md->match_limit = extra_data->match_limit; - if ((flags & PCRE_EXTRA_MATCH_LIMIT_RECURSION) != 0) - md->match_limit_recursion = extra_data->match_limit_recursion; - if ((flags & PCRE_EXTRA_CALLOUT_DATA) != 0) - md->callout_data = extra_data->callout_data; - if ((flags & PCRE_EXTRA_TABLES) != 0) tables = extra_data->tables; - } - -/* Limits in the regex override only if they are smaller. */ - -if ((re->flags & PCRE_MLSET) != 0 && re->limit_match < md->match_limit) - md->match_limit = re->limit_match; - -if ((re->flags & PCRE_RLSET) != 0 && - re->limit_recursion < md->match_limit_recursion) - md->match_limit_recursion = re->limit_recursion; - -/* If the exec call supplied NULL for tables, use the inbuilt ones. This -is a feature that makes it possible to save compiled regex and re-use them -in other programs later. */ - -if (tables == NULL) tables = PRIV(default_tables); - -/* Set up other data */ - -anchored = ((re->options | options) & PCRE_ANCHORED) != 0; -startline = (re->flags & PCRE_STARTLINE) != 0; -firstline = (re->options & PCRE_FIRSTLINE) != 0; - -/* The code starts after the real_pcre block and the capture name table. */ - -md->start_code = (const pcre_uchar *)re + re->name_table_offset + - re->name_count * re->name_entry_size; - -md->start_subject = (PCRE_PUCHAR)subject; -md->start_offset = start_offset; -md->end_subject = md->start_subject + length; -end_subject = md->end_subject; - -md->endonly = (re->options & PCRE_DOLLAR_ENDONLY) != 0; -md->use_ucp = (re->options & PCRE_UCP) != 0; -md->jscript_compat = (re->options & PCRE_JAVASCRIPT_COMPAT) != 0; -md->ignore_skip_arg = 0; - -/* Some options are unpacked into BOOL variables in the hope that testing -them will be faster than individual option bits. */ - -md->notbol = (options & PCRE_NOTBOL) != 0; -md->noteol = (options & PCRE_NOTEOL) != 0; -md->notempty = (options & PCRE_NOTEMPTY) != 0; -md->notempty_atstart = (options & PCRE_NOTEMPTY_ATSTART) != 0; - -md->hitend = FALSE; -md->mark = md->nomatch_mark = NULL; /* In case never set */ - -md->recursive = NULL; /* No recursion at top level */ -md->hasthen = (re->flags & PCRE_HASTHEN) != 0; - -md->lcc = tables + lcc_offset; -md->fcc = tables + fcc_offset; -md->ctypes = tables + ctypes_offset; - -/* Handle different \R options. */ - -switch (options & (PCRE_BSR_ANYCRLF|PCRE_BSR_UNICODE)) - { - case 0: - if ((re->options & (PCRE_BSR_ANYCRLF|PCRE_BSR_UNICODE)) != 0) - md->bsr_anycrlf = (re->options & PCRE_BSR_ANYCRLF) != 0; - else -#ifdef BSR_ANYCRLF - md->bsr_anycrlf = TRUE; -#else - md->bsr_anycrlf = FALSE; -#endif - break; - - case PCRE_BSR_ANYCRLF: - md->bsr_anycrlf = TRUE; - break; - - case PCRE_BSR_UNICODE: - md->bsr_anycrlf = FALSE; - break; - - default: return PCRE_ERROR_BADNEWLINE; - } - -/* Handle different types of newline. The three bits give eight cases. If -nothing is set at run time, whatever was used at compile time applies. */ - -switch ((((options & PCRE_NEWLINE_BITS) == 0)? re->options : - (pcre_uint32)options) & PCRE_NEWLINE_BITS) - { - case 0: newline = NEWLINE; break; /* Compile-time default */ - case PCRE_NEWLINE_CR: newline = CHAR_CR; break; - case PCRE_NEWLINE_LF: newline = CHAR_NL; break; - case PCRE_NEWLINE_CR+ - PCRE_NEWLINE_LF: newline = (CHAR_CR << 8) | CHAR_NL; break; - case PCRE_NEWLINE_ANY: newline = -1; break; - case PCRE_NEWLINE_ANYCRLF: newline = -2; break; - default: return PCRE_ERROR_BADNEWLINE; - } - -if (newline == -2) - { - md->nltype = NLTYPE_ANYCRLF; - } -else if (newline < 0) - { - md->nltype = NLTYPE_ANY; - } -else - { - md->nltype = NLTYPE_FIXED; - if (newline > 255) - { - md->nllen = 2; - md->nl[0] = (newline >> 8) & 255; - md->nl[1] = newline & 255; - } - else - { - md->nllen = 1; - md->nl[0] = newline; - } - } - -/* Partial matching was originally supported only for a restricted set of -regexes; from release 8.00 there are no restrictions, but the bits are still -defined (though never set). So there's no harm in leaving this code. */ - -if (md->partial && (re->flags & PCRE_NOPARTIAL) != 0) - return PCRE_ERROR_BADPARTIAL; - -/* If the expression has got more back references than the offsets supplied can -hold, we get a temporary chunk of working store to use during the matching. -Otherwise, we can use the vector supplied, rounding down its size to a multiple -of 3. */ - -ocount = offsetcount - (offsetcount % 3); -arg_offset_max = (2*ocount)/3; - -if (re->top_backref > 0 && re->top_backref >= ocount/3) - { - ocount = re->top_backref * 3 + 3; - md->offset_vector = (int *)(PUBL(malloc))(ocount * sizeof(int)); - if (md->offset_vector == NULL) return PCRE_ERROR_NOMEMORY; - using_temporary_offsets = TRUE; - DPRINTF(("Got memory to hold back references\n")); - } -else md->offset_vector = offsets; -md->offset_end = ocount; -md->offset_max = (2*ocount)/3; -md->capture_last = 0; - -/* Reset the working variable associated with each extraction. These should -never be used unless previously set, but they get saved and restored, and so we -initialize them to avoid reading uninitialized locations. Also, unset the -offsets for the matched string. This is really just for tidiness with callouts, -in case they inspect these fields. */ - -if (md->offset_vector != NULL) - { - register int *iptr = md->offset_vector + ocount; - register int *iend = iptr - re->top_bracket; - if (iend < md->offset_vector + 2) iend = md->offset_vector + 2; - while (--iptr >= iend) *iptr = -1; - md->offset_vector[0] = md->offset_vector[1] = -1; - } - -/* Set up the first character to match, if available. The first_char value is -never set for an anchored regular expression, but the anchoring may be forced -at run time, so we have to test for anchoring. The first char may be unset for -an unanchored pattern, of course. If there's no first char and the pattern was -studied, there may be a bitmap of possible first characters. */ - -if (!anchored) - { - if ((re->flags & PCRE_FIRSTSET) != 0) - { - has_first_char = TRUE; - first_char = first_char2 = (pcre_uchar)(re->first_char); - if ((re->flags & PCRE_FCH_CASELESS) != 0) - { - first_char2 = TABLE_GET(first_char, md->fcc, first_char); -#if defined SUPPORT_UCP && !(defined COMPILE_PCRE8) - if (utf && first_char > 127) - first_char2 = UCD_OTHERCASE(first_char); -#endif - } - } - else - if (!startline && study != NULL && - (study->flags & PCRE_STUDY_MAPPED) != 0) - start_bits = study->start_bits; - } - -/* For anchored or unanchored matches, there may be a "last known required -character" set. */ - -if ((re->flags & PCRE_REQCHSET) != 0) - { - has_req_char = TRUE; - req_char = req_char2 = (pcre_uchar)(re->req_char); - if ((re->flags & PCRE_RCH_CASELESS) != 0) - { - req_char2 = TABLE_GET(req_char, md->fcc, req_char); -#if defined SUPPORT_UCP && !(defined COMPILE_PCRE8) - if (utf && req_char > 127) - req_char2 = UCD_OTHERCASE(req_char); -#endif - } - } - - -/* ==========================================================================*/ - -/* Loop for handling unanchored repeated matching attempts; for anchored regexs -the loop runs just once. */ - -for(;;) - { - PCRE_PUCHAR save_end_subject = end_subject; - PCRE_PUCHAR new_start_match; - - /* If firstline is TRUE, the start of the match is constrained to the first - line of a multiline string. That is, the match must be before or at the first - newline. Implement this by temporarily adjusting end_subject so that we stop - scanning at a newline. If the match fails at the newline, later code breaks - this loop. */ - - if (firstline) - { - PCRE_PUCHAR t = start_match; -#ifdef SUPPORT_UTF - if (utf) - { - while (t < md->end_subject && !IS_NEWLINE(t)) - { - t++; - ACROSSCHAR(t < end_subject, *t, t++); - } - } - else -#endif - while (t < md->end_subject && !IS_NEWLINE(t)) t++; - end_subject = t; - } - - /* There are some optimizations that avoid running the match if a known - starting point is not found, or if a known later character is not present. - However, there is an option that disables these, for testing and for ensuring - that all callouts do actually occur. The option can be set in the regex by - (*NO_START_OPT) or passed in match-time options. */ - - if (((options | re->options) & PCRE_NO_START_OPTIMIZE) == 0) - { - /* Advance to a unique first char if there is one. */ - - if (has_first_char) - { - pcre_uchar smc; - - if (first_char != first_char2) - while (start_match < end_subject && - (smc = UCHAR21TEST(start_match)) != first_char && smc != first_char2) - start_match++; - else - while (start_match < end_subject && UCHAR21TEST(start_match) != first_char) - start_match++; - } - - /* Or to just after a linebreak for a multiline match */ - - else if (startline) - { - if (start_match > md->start_subject + start_offset) - { -#ifdef SUPPORT_UTF - if (utf) - { - while (start_match < end_subject && !WAS_NEWLINE(start_match)) - { - start_match++; - ACROSSCHAR(start_match < end_subject, *start_match, - start_match++); - } - } - else -#endif - while (start_match < end_subject && !WAS_NEWLINE(start_match)) - start_match++; - - /* If we have just passed a CR and the newline option is ANY or ANYCRLF, - and we are now at a LF, advance the match position by one more character. - */ - - if (start_match[-1] == CHAR_CR && - (md->nltype == NLTYPE_ANY || md->nltype == NLTYPE_ANYCRLF) && - start_match < end_subject && - UCHAR21TEST(start_match) == CHAR_NL) - start_match++; - } - } - - /* Or to a non-unique first byte after study */ - - else if (start_bits != NULL) - { - while (start_match < end_subject) - { - register pcre_uint32 c = UCHAR21TEST(start_match); -#ifndef COMPILE_PCRE8 - if (c > 255) c = 255; -#endif - if ((start_bits[c/8] & (1 << (c&7))) != 0) break; - start_match++; - } - } - } /* Starting optimizations */ - - /* Restore fudged end_subject */ - - end_subject = save_end_subject; - - /* The following two optimizations are disabled for partial matching or if - disabling is explicitly requested. */ - - if (((options | re->options) & PCRE_NO_START_OPTIMIZE) == 0 && !md->partial) - { - /* If the pattern was studied, a minimum subject length may be set. This is - a lower bound; no actual string of that length may actually match the - pattern. Although the value is, strictly, in characters, we treat it as - bytes to avoid spending too much time in this optimization. */ - - if (study != NULL && (study->flags & PCRE_STUDY_MINLEN) != 0 && - (pcre_uint32)(end_subject - start_match) < study->minlength) - { - rc = MATCH_NOMATCH; - break; - } - - /* If req_char is set, we know that that character must appear in the - subject for the match to succeed. If the first character is set, req_char - must be later in the subject; otherwise the test starts at the match point. - This optimization can save a huge amount of backtracking in patterns with - nested unlimited repeats that aren't going to match. Writing separate code - for cased/caseless versions makes it go faster, as does using an - autoincrement and backing off on a match. - - HOWEVER: when the subject string is very, very long, searching to its end - can take a long time, and give bad performance on quite ordinary patterns. - This showed up when somebody was matching something like /^\d+C/ on a - 32-megabyte string... so we don't do this when the string is sufficiently - long. */ - - if (has_req_char && end_subject - start_match < REQ_BYTE_MAX) - { - register PCRE_PUCHAR p = start_match + (has_first_char? 1:0); - - /* We don't need to repeat the search if we haven't yet reached the - place we found it at last time. */ - - if (p > req_char_ptr) - { - if (req_char != req_char2) - { - while (p < end_subject) - { - register pcre_uint32 pp = UCHAR21INCTEST(p); - if (pp == req_char || pp == req_char2) { p--; break; } - } - } - else - { - while (p < end_subject) - { - if (UCHAR21INCTEST(p) == req_char) { p--; break; } - } - } - - /* If we can't find the required character, break the matching loop, - forcing a match failure. */ - - if (p >= end_subject) - { - rc = MATCH_NOMATCH; - break; - } - - /* If we have found the required character, save the point where we - found it, so that we don't search again next time round the loop if - the start hasn't passed this character yet. */ - - req_char_ptr = p; - } - } - } - -#ifdef PCRE_DEBUG /* Sigh. Some compilers never learn. */ - printf(">>>> Match against: "); - pchars(start_match, end_subject - start_match, TRUE, md); - printf("\n"); -#endif - - /* OK, we can now run the match. If "hitend" is set afterwards, remember the - first starting point for which a partial match was found. */ - - md->start_match_ptr = start_match; - md->start_used_ptr = start_match; - md->match_call_count = 0; - md->match_function_type = 0; - md->end_offset_top = 0; - md->skip_arg_count = 0; - rc = match(start_match, md->start_code, start_match, 2, md, NULL, 0); - if (md->hitend && start_partial == NULL) - { - start_partial = md->start_used_ptr; - match_partial = start_match; - } - - switch(rc) - { - /* If MATCH_SKIP_ARG reaches this level it means that a MARK that matched - the SKIP's arg was not found. In this circumstance, Perl ignores the SKIP - entirely. The only way we can do that is to re-do the match at the same - point, with a flag to force SKIP with an argument to be ignored. Just - treating this case as NOMATCH does not work because it does not check other - alternatives in patterns such as A(*SKIP:A)B|AC when the subject is AC. */ - - case MATCH_SKIP_ARG: - new_start_match = start_match; - md->ignore_skip_arg = md->skip_arg_count; - break; - - /* SKIP passes back the next starting point explicitly, but if it is no - greater than the match we have just done, treat it as NOMATCH. */ - - case MATCH_SKIP: - if (md->start_match_ptr > start_match) - { - new_start_match = md->start_match_ptr; - break; - } - /* Fall through */ - - /* NOMATCH and PRUNE advance by one character. THEN at this level acts - exactly like PRUNE. Unset ignore SKIP-with-argument. */ - - case MATCH_NOMATCH: - case MATCH_PRUNE: - case MATCH_THEN: - md->ignore_skip_arg = 0; - new_start_match = start_match + 1; -#ifdef SUPPORT_UTF - if (utf) - ACROSSCHAR(new_start_match < end_subject, *new_start_match, - new_start_match++); -#endif - break; - - /* COMMIT disables the bumpalong, but otherwise behaves as NOMATCH. */ - - case MATCH_COMMIT: - rc = MATCH_NOMATCH; - goto ENDLOOP; - - /* Any other return is either a match, or some kind of error. */ - - default: - goto ENDLOOP; - } - - /* Control reaches here for the various types of "no match at this point" - result. Reset the code to MATCH_NOMATCH for subsequent checking. */ - - rc = MATCH_NOMATCH; - - /* If PCRE_FIRSTLINE is set, the match must happen before or at the first - newline in the subject (though it may continue over the newline). Therefore, - if we have just failed to match, starting at a newline, do not continue. */ - - if (firstline && IS_NEWLINE(start_match)) break; - - /* Advance to new matching position */ - - start_match = new_start_match; - - /* Break the loop if the pattern is anchored or if we have passed the end of - the subject. */ - - if (anchored || start_match > end_subject) break; - - /* If we have just passed a CR and we are now at a LF, and the pattern does - not contain any explicit matches for \r or \n, and the newline option is CRLF - or ANY or ANYCRLF, advance the match position by one more character. In - normal matching start_match will aways be greater than the first position at - this stage, but a failed *SKIP can cause a return at the same point, which is - why the first test exists. */ - - if (start_match > (PCRE_PUCHAR)subject + start_offset && - start_match[-1] == CHAR_CR && - start_match < end_subject && - *start_match == CHAR_NL && - (re->flags & PCRE_HASCRORLF) == 0 && - (md->nltype == NLTYPE_ANY || - md->nltype == NLTYPE_ANYCRLF || - md->nllen == 2)) - start_match++; - - md->mark = NULL; /* Reset for start of next match attempt */ - } /* End of for(;;) "bumpalong" loop */ - -/* ==========================================================================*/ - -/* We reach here when rc is not MATCH_NOMATCH, or if one of the stopping -conditions is true: - -(1) The pattern is anchored or the match was failed by (*COMMIT); - -(2) We are past the end of the subject; - -(3) PCRE_FIRSTLINE is set and we have failed to match at a newline, because - this option requests that a match occur at or before the first newline in - the subject. - -When we have a match and the offset vector is big enough to deal with any -backreferences, captured substring offsets will already be set up. In the case -where we had to get some local store to hold offsets for backreference -processing, copy those that we can. In this case there need not be overflow if -certain parts of the pattern were not used, even though there are more -capturing parentheses than vector slots. */ - -ENDLOOP: - -if (rc == MATCH_MATCH || rc == MATCH_ACCEPT) - { - if (using_temporary_offsets) - { - if (arg_offset_max >= 4) - { - memcpy(offsets + 2, md->offset_vector + 2, - (arg_offset_max - 2) * sizeof(int)); - DPRINTF(("Copied offsets from temporary memory\n")); - } - if (md->end_offset_top > arg_offset_max) md->capture_last |= OVFLBIT; - DPRINTF(("Freeing temporary memory\n")); - (PUBL(free))(md->offset_vector); - } - - /* Set the return code to the number of captured strings, or 0 if there were - too many to fit into the vector. */ - - rc = ((md->capture_last & OVFLBIT) != 0 && - md->end_offset_top >= arg_offset_max)? - 0 : md->end_offset_top/2; - - /* If there is space in the offset vector, set any unused pairs at the end of - the pattern to -1 for backwards compatibility. It is documented that this - happens. In earlier versions, the whole set of potential capturing offsets - was set to -1 each time round the loop, but this is handled differently now. - "Gaps" are set to -1 dynamically instead (this fixes a bug). Thus, it is only - those at the end that need unsetting here. We can't just unset them all at - the start of the whole thing because they may get set in one branch that is - not the final matching branch. */ - - if (md->end_offset_top/2 <= re->top_bracket && offsets != NULL) - { - register int *iptr, *iend; - int resetcount = 2 + re->top_bracket * 2; - if (resetcount > offsetcount) resetcount = offsetcount; - iptr = offsets + md->end_offset_top; - iend = offsets + resetcount; - while (iptr < iend) *iptr++ = -1; - } - - /* If there is space, set up the whole thing as substring 0. The value of - md->start_match_ptr might be modified if \K was encountered on the success - matching path. */ - - if (offsetcount < 2) rc = 0; else - { - offsets[0] = (int)(md->start_match_ptr - md->start_subject); - offsets[1] = (int)(md->end_match_ptr - md->start_subject); - } - - /* Return MARK data if requested */ - - if (extra_data != NULL && (extra_data->flags & PCRE_EXTRA_MARK) != 0) - *(extra_data->mark) = (pcre_uchar *)md->mark; - DPRINTF((">>>> returning %d\n", rc)); -#ifdef NO_RECURSE - release_match_heapframes(&frame_zero); -#endif - return rc; - } - -/* Control gets here if there has been an error, or if the overall match -attempt has failed at all permitted starting positions. */ - -if (using_temporary_offsets) - { - DPRINTF(("Freeing temporary memory\n")); - (PUBL(free))(md->offset_vector); - } - -/* For anything other than nomatch or partial match, just return the code. */ - -if (rc != MATCH_NOMATCH && rc != PCRE_ERROR_PARTIAL) - { - DPRINTF((">>>> error: returning %d\n", rc)); -#ifdef NO_RECURSE - release_match_heapframes(&frame_zero); -#endif - return rc; - } - -/* Handle partial matches - disable any mark data */ - -if (match_partial != NULL) - { - DPRINTF((">>>> returning PCRE_ERROR_PARTIAL\n")); - md->mark = NULL; - if (offsetcount > 1) - { - offsets[0] = (int)(start_partial - (PCRE_PUCHAR)subject); - offsets[1] = (int)(end_subject - (PCRE_PUCHAR)subject); - if (offsetcount > 2) - offsets[2] = (int)(match_partial - (PCRE_PUCHAR)subject); - } - rc = PCRE_ERROR_PARTIAL; - } - -/* This is the classic nomatch case */ - -else - { - DPRINTF((">>>> returning PCRE_ERROR_NOMATCH\n")); - rc = PCRE_ERROR_NOMATCH; - } - -/* Return the MARK data if it has been requested. */ - -if (extra_data != NULL && (extra_data->flags & PCRE_EXTRA_MARK) != 0) - *(extra_data->mark) = (pcre_uchar *)md->nomatch_mark; -#ifdef NO_RECURSE - release_match_heapframes(&frame_zero); -#endif -return rc; -} - -/* End of pcre_exec.c */ diff --git a/lib/impure/nre/private/pcre_src/pcre_fullinfo.c b/lib/impure/nre/private/pcre_src/pcre_fullinfo.c deleted file mode 100644 index a6c2ece6c..000000000 --- a/lib/impure/nre/private/pcre_src/pcre_fullinfo.c +++ /dev/null @@ -1,245 +0,0 @@ -/************************************************* -* Perl-Compatible Regular Expressions * -*************************************************/ - -/* PCRE is a library of functions to support regular expressions whose syntax -and semantics are as close as possible to those of the Perl 5 language. - - Written by Philip Hazel - Copyright (c) 1997-2013 University of Cambridge - ------------------------------------------------------------------------------ -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - * Neither the name of the University of Cambridge nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ -*/ - - -/* This module contains the external function pcre_fullinfo(), which returns -information about a compiled pattern. */ - - -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - -#include "pcre_internal.h" - - -/************************************************* -* Return info about compiled pattern * -*************************************************/ - -/* This is a newer "info" function which has an extensible interface so -that additional items can be added compatibly. - -Arguments: - argument_re points to compiled code - extra_data points extra data, or NULL - what what information is required - where where to put the information - -Returns: 0 if data returned, negative on error -*/ - -#if defined COMPILE_PCRE8 -PCRE_EXP_DEFN int PCRE_CALL_CONVENTION -pcre_fullinfo(const pcre *argument_re, const pcre_extra *extra_data, - int what, void *where) -#elif defined COMPILE_PCRE16 -PCRE_EXP_DEFN int PCRE_CALL_CONVENTION -pcre16_fullinfo(const pcre16 *argument_re, const pcre16_extra *extra_data, - int what, void *where) -#elif defined COMPILE_PCRE32 -PCRE_EXP_DEFN int PCRE_CALL_CONVENTION -pcre32_fullinfo(const pcre32 *argument_re, const pcre32_extra *extra_data, - int what, void *where) -#endif -{ -const REAL_PCRE *re = (const REAL_PCRE *)argument_re; -const pcre_study_data *study = NULL; - -if (re == NULL || where == NULL) return PCRE_ERROR_NULL; - -if (extra_data != NULL && (extra_data->flags & PCRE_EXTRA_STUDY_DATA) != 0) - study = (const pcre_study_data *)extra_data->study_data; - -/* Check that the first field in the block is the magic number. If it is not, -return with PCRE_ERROR_BADMAGIC. However, if the magic number is equal to -REVERSED_MAGIC_NUMBER we return with PCRE_ERROR_BADENDIANNESS, which -means that the pattern is likely compiled with different endianness. */ - -if (re->magic_number != MAGIC_NUMBER) - return re->magic_number == REVERSED_MAGIC_NUMBER? - PCRE_ERROR_BADENDIANNESS:PCRE_ERROR_BADMAGIC; - -/* Check that this pattern was compiled in the correct bit mode */ - -if ((re->flags & PCRE_MODE) == 0) return PCRE_ERROR_BADMODE; - -switch (what) - { - case PCRE_INFO_OPTIONS: - *((unsigned long int *)where) = re->options & PUBLIC_COMPILE_OPTIONS; - break; - - case PCRE_INFO_SIZE: - *((size_t *)where) = re->size; - break; - - case PCRE_INFO_STUDYSIZE: - *((size_t *)where) = (study == NULL)? 0 : study->size; - break; - - case PCRE_INFO_JITSIZE: -#ifdef SUPPORT_JIT - *((size_t *)where) = - (extra_data != NULL && - (extra_data->flags & PCRE_EXTRA_EXECUTABLE_JIT) != 0 && - extra_data->executable_jit != NULL)? - PRIV(jit_get_size)(extra_data->executable_jit) : 0; -#else - *((size_t *)where) = 0; -#endif - break; - - case PCRE_INFO_CAPTURECOUNT: - *((int *)where) = re->top_bracket; - break; - - case PCRE_INFO_BACKREFMAX: - *((int *)where) = re->top_backref; - break; - - case PCRE_INFO_FIRSTBYTE: - *((int *)where) = - ((re->flags & PCRE_FIRSTSET) != 0)? (int)re->first_char : - ((re->flags & PCRE_STARTLINE) != 0)? -1 : -2; - break; - - case PCRE_INFO_FIRSTCHARACTER: - *((pcre_uint32 *)where) = - (re->flags & PCRE_FIRSTSET) != 0 ? re->first_char : 0; - break; - - case PCRE_INFO_FIRSTCHARACTERFLAGS: - *((int *)where) = - ((re->flags & PCRE_FIRSTSET) != 0) ? 1 : - ((re->flags & PCRE_STARTLINE) != 0) ? 2 : 0; - break; - - /* Make sure we pass back the pointer to the bit vector in the external - block, not the internal copy (with flipped integer fields). */ - - case PCRE_INFO_FIRSTTABLE: - *((const pcre_uint8 **)where) = - (study != NULL && (study->flags & PCRE_STUDY_MAPPED) != 0)? - ((const pcre_study_data *)extra_data->study_data)->start_bits : NULL; - break; - - case PCRE_INFO_MINLENGTH: - *((int *)where) = - (study != NULL && (study->flags & PCRE_STUDY_MINLEN) != 0)? - (int)(study->minlength) : -1; - break; - - case PCRE_INFO_JIT: - *((int *)where) = extra_data != NULL && - (extra_data->flags & PCRE_EXTRA_EXECUTABLE_JIT) != 0 && - extra_data->executable_jit != NULL; - break; - - case PCRE_INFO_LASTLITERAL: - *((int *)where) = - ((re->flags & PCRE_REQCHSET) != 0)? (int)re->req_char : -1; - break; - - case PCRE_INFO_REQUIREDCHAR: - *((pcre_uint32 *)where) = - ((re->flags & PCRE_REQCHSET) != 0) ? re->req_char : 0; - break; - - case PCRE_INFO_REQUIREDCHARFLAGS: - *((int *)where) = - ((re->flags & PCRE_REQCHSET) != 0); - break; - - case PCRE_INFO_NAMEENTRYSIZE: - *((int *)where) = re->name_entry_size; - break; - - case PCRE_INFO_NAMECOUNT: - *((int *)where) = re->name_count; - break; - - case PCRE_INFO_NAMETABLE: - *((const pcre_uchar **)where) = (const pcre_uchar *)re + re->name_table_offset; - break; - - case PCRE_INFO_DEFAULT_TABLES: - *((const pcre_uint8 **)where) = (const pcre_uint8 *)(PRIV(default_tables)); - break; - - /* From release 8.00 this will always return TRUE because NOPARTIAL is - no longer ever set (the restrictions have been removed). */ - - case PCRE_INFO_OKPARTIAL: - *((int *)where) = (re->flags & PCRE_NOPARTIAL) == 0; - break; - - case PCRE_INFO_JCHANGED: - *((int *)where) = (re->flags & PCRE_JCHANGED) != 0; - break; - - case PCRE_INFO_HASCRORLF: - *((int *)where) = (re->flags & PCRE_HASCRORLF) != 0; - break; - - case PCRE_INFO_MAXLOOKBEHIND: - *((int *)where) = re->max_lookbehind; - break; - - case PCRE_INFO_MATCHLIMIT: - if ((re->flags & PCRE_MLSET) == 0) return PCRE_ERROR_UNSET; - *((pcre_uint32 *)where) = re->limit_match; - break; - - case PCRE_INFO_RECURSIONLIMIT: - if ((re->flags & PCRE_RLSET) == 0) return PCRE_ERROR_UNSET; - *((pcre_uint32 *)where) = re->limit_recursion; - break; - - case PCRE_INFO_MATCH_EMPTY: - *((int *)where) = (re->flags & PCRE_MATCH_EMPTY) != 0; - break; - - default: return PCRE_ERROR_BADOPTION; - } - -return 0; -} - -/* End of pcre_fullinfo.c */ diff --git a/lib/impure/nre/private/pcre_src/pcre_get.c b/lib/impure/nre/private/pcre_src/pcre_get.c deleted file mode 100644 index 8094b34bb..000000000 --- a/lib/impure/nre/private/pcre_src/pcre_get.c +++ /dev/null @@ -1,662 +0,0 @@ -/************************************************* -* Perl-Compatible Regular Expressions * -*************************************************/ - -/* PCRE is a library of functions to support regular expressions whose syntax -and semantics are as close as possible to those of the Perl 5 language. - - Written by Philip Hazel - Copyright (c) 1997-2012 University of Cambridge - ------------------------------------------------------------------------------ -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - * Neither the name of the University of Cambridge nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ -*/ - - -/* This module contains some convenience functions for extracting substrings -from the subject string after a regex match has succeeded. The original idea -for these functions came from Scott Wimer. */ - - -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - -#include "pcre_internal.h" - - -/************************************************* -* Find number for named string * -*************************************************/ - -/* This function is used by the get_first_set() function below, as well -as being generally available. It assumes that names are unique. - -Arguments: - code the compiled regex - stringname the name whose number is required - -Returns: the number of the named parentheses, or a negative number - (PCRE_ERROR_NOSUBSTRING) if not found -*/ - -#if defined COMPILE_PCRE8 -PCRE_EXP_DEFN int PCRE_CALL_CONVENTION -pcre_get_stringnumber(const pcre *code, const char *stringname) -#elif defined COMPILE_PCRE16 -PCRE_EXP_DEFN int PCRE_CALL_CONVENTION -pcre16_get_stringnumber(const pcre16 *code, PCRE_SPTR16 stringname) -#elif defined COMPILE_PCRE32 -PCRE_EXP_DEFN int PCRE_CALL_CONVENTION -pcre32_get_stringnumber(const pcre32 *code, PCRE_SPTR32 stringname) -#endif -{ -int rc; -int entrysize; -int top, bot; -pcre_uchar *nametable; - -#ifdef COMPILE_PCRE8 -if ((rc = pcre_fullinfo(code, NULL, PCRE_INFO_NAMECOUNT, &top)) != 0) - return rc; -if (top <= 0) return PCRE_ERROR_NOSUBSTRING; - -if ((rc = pcre_fullinfo(code, NULL, PCRE_INFO_NAMEENTRYSIZE, &entrysize)) != 0) - return rc; -if ((rc = pcre_fullinfo(code, NULL, PCRE_INFO_NAMETABLE, &nametable)) != 0) - return rc; -#endif -#ifdef COMPILE_PCRE16 -if ((rc = pcre16_fullinfo(code, NULL, PCRE_INFO_NAMECOUNT, &top)) != 0) - return rc; -if (top <= 0) return PCRE_ERROR_NOSUBSTRING; - -if ((rc = pcre16_fullinfo(code, NULL, PCRE_INFO_NAMEENTRYSIZE, &entrysize)) != 0) - return rc; -if ((rc = pcre16_fullinfo(code, NULL, PCRE_INFO_NAMETABLE, &nametable)) != 0) - return rc; -#endif -#ifdef COMPILE_PCRE32 -if ((rc = pcre32_fullinfo(code, NULL, PCRE_INFO_NAMECOUNT, &top)) != 0) - return rc; -if (top <= 0) return PCRE_ERROR_NOSUBSTRING; - -if ((rc = pcre32_fullinfo(code, NULL, PCRE_INFO_NAMEENTRYSIZE, &entrysize)) != 0) - return rc; -if ((rc = pcre32_fullinfo(code, NULL, PCRE_INFO_NAMETABLE, &nametable)) != 0) - return rc; -#endif - -bot = 0; -while (top > bot) - { - int mid = (top + bot) / 2; - pcre_uchar *entry = nametable + entrysize*mid; - int c = STRCMP_UC_UC((pcre_uchar *)stringname, - (pcre_uchar *)(entry + IMM2_SIZE)); - if (c == 0) return GET2(entry, 0); - if (c > 0) bot = mid + 1; else top = mid; - } - -return PCRE_ERROR_NOSUBSTRING; -} - - - -/************************************************* -* Find (multiple) entries for named string * -*************************************************/ - -/* This is used by the get_first_set() function below, as well as being -generally available. It is used when duplicated names are permitted. - -Arguments: - code the compiled regex - stringname the name whose entries required - firstptr where to put the pointer to the first entry - lastptr where to put the pointer to the last entry - -Returns: the length of each entry, or a negative number - (PCRE_ERROR_NOSUBSTRING) if not found -*/ - -#if defined COMPILE_PCRE8 -PCRE_EXP_DEFN int PCRE_CALL_CONVENTION -pcre_get_stringtable_entries(const pcre *code, const char *stringname, - char **firstptr, char **lastptr) -#elif defined COMPILE_PCRE16 -PCRE_EXP_DEFN int PCRE_CALL_CONVENTION -pcre16_get_stringtable_entries(const pcre16 *code, PCRE_SPTR16 stringname, - PCRE_UCHAR16 **firstptr, PCRE_UCHAR16 **lastptr) -#elif defined COMPILE_PCRE32 -PCRE_EXP_DEFN int PCRE_CALL_CONVENTION -pcre32_get_stringtable_entries(const pcre32 *code, PCRE_SPTR32 stringname, - PCRE_UCHAR32 **firstptr, PCRE_UCHAR32 **lastptr) -#endif -{ -int rc; -int entrysize; -int top, bot; -pcre_uchar *nametable, *lastentry; - -#ifdef COMPILE_PCRE8 -if ((rc = pcre_fullinfo(code, NULL, PCRE_INFO_NAMECOUNT, &top)) != 0) - return rc; -if (top <= 0) return PCRE_ERROR_NOSUBSTRING; - -if ((rc = pcre_fullinfo(code, NULL, PCRE_INFO_NAMEENTRYSIZE, &entrysize)) != 0) - return rc; -if ((rc = pcre_fullinfo(code, NULL, PCRE_INFO_NAMETABLE, &nametable)) != 0) - return rc; -#endif -#ifdef COMPILE_PCRE16 -if ((rc = pcre16_fullinfo(code, NULL, PCRE_INFO_NAMECOUNT, &top)) != 0) - return rc; -if (top <= 0) return PCRE_ERROR_NOSUBSTRING; - -if ((rc = pcre16_fullinfo(code, NULL, PCRE_INFO_NAMEENTRYSIZE, &entrysize)) != 0) - return rc; -if ((rc = pcre16_fullinfo(code, NULL, PCRE_INFO_NAMETABLE, &nametable)) != 0) - return rc; -#endif -#ifdef COMPILE_PCRE32 -if ((rc = pcre32_fullinfo(code, NULL, PCRE_INFO_NAMECOUNT, &top)) != 0) - return rc; -if (top <= 0) return PCRE_ERROR_NOSUBSTRING; - -if ((rc = pcre32_fullinfo(code, NULL, PCRE_INFO_NAMEENTRYSIZE, &entrysize)) != 0) - return rc; -if ((rc = pcre32_fullinfo(code, NULL, PCRE_INFO_NAMETABLE, &nametable)) != 0) - return rc; -#endif - -lastentry = nametable + entrysize * (top - 1); -bot = 0; -while (top > bot) - { - int mid = (top + bot) / 2; - pcre_uchar *entry = nametable + entrysize*mid; - int c = STRCMP_UC_UC((pcre_uchar *)stringname, - (pcre_uchar *)(entry + IMM2_SIZE)); - if (c == 0) - { - pcre_uchar *first = entry; - pcre_uchar *last = entry; - while (first > nametable) - { - if (STRCMP_UC_UC((pcre_uchar *)stringname, - (pcre_uchar *)(first - entrysize + IMM2_SIZE)) != 0) break; - first -= entrysize; - } - while (last < lastentry) - { - if (STRCMP_UC_UC((pcre_uchar *)stringname, - (pcre_uchar *)(last + entrysize + IMM2_SIZE)) != 0) break; - last += entrysize; - } -#if defined COMPILE_PCRE8 - *firstptr = (char *)first; - *lastptr = (char *)last; -#elif defined COMPILE_PCRE16 - *firstptr = (PCRE_UCHAR16 *)first; - *lastptr = (PCRE_UCHAR16 *)last; -#elif defined COMPILE_PCRE32 - *firstptr = (PCRE_UCHAR32 *)first; - *lastptr = (PCRE_UCHAR32 *)last; -#endif - return entrysize; - } - if (c > 0) bot = mid + 1; else top = mid; - } - -return PCRE_ERROR_NOSUBSTRING; -} - - - -/************************************************* -* Find first set of multiple named strings * -*************************************************/ - -/* This function allows for duplicate names in the table of named substrings. -It returns the number of the first one that was set in a pattern match. - -Arguments: - code the compiled regex - stringname the name of the capturing substring - ovector the vector of matched substrings - -Returns: the number of the first that is set, - or the number of the last one if none are set, - or a negative number on error -*/ - -#if defined COMPILE_PCRE8 -static int -get_first_set(const pcre *code, const char *stringname, int *ovector) -#elif defined COMPILE_PCRE16 -static int -get_first_set(const pcre16 *code, PCRE_SPTR16 stringname, int *ovector) -#elif defined COMPILE_PCRE32 -static int -get_first_set(const pcre32 *code, PCRE_SPTR32 stringname, int *ovector) -#endif -{ -const REAL_PCRE *re = (const REAL_PCRE *)code; -int entrysize; -pcre_uchar *entry; -#if defined COMPILE_PCRE8 -char *first, *last; -#elif defined COMPILE_PCRE16 -PCRE_UCHAR16 *first, *last; -#elif defined COMPILE_PCRE32 -PCRE_UCHAR32 *first, *last; -#endif - -#if defined COMPILE_PCRE8 -if ((re->options & PCRE_DUPNAMES) == 0 && (re->flags & PCRE_JCHANGED) == 0) - return pcre_get_stringnumber(code, stringname); -entrysize = pcre_get_stringtable_entries(code, stringname, &first, &last); -#elif defined COMPILE_PCRE16 -if ((re->options & PCRE_DUPNAMES) == 0 && (re->flags & PCRE_JCHANGED) == 0) - return pcre16_get_stringnumber(code, stringname); -entrysize = pcre16_get_stringtable_entries(code, stringname, &first, &last); -#elif defined COMPILE_PCRE32 -if ((re->options & PCRE_DUPNAMES) == 0 && (re->flags & PCRE_JCHANGED) == 0) - return pcre32_get_stringnumber(code, stringname); -entrysize = pcre32_get_stringtable_entries(code, stringname, &first, &last); -#endif -if (entrysize <= 0) return entrysize; -for (entry = (pcre_uchar *)first; entry <= (pcre_uchar *)last; entry += entrysize) - { - int n = GET2(entry, 0); - if (ovector[n*2] >= 0) return n; - } -return GET2(entry, 0); -} - - - - -/************************************************* -* Copy captured string to given buffer * -*************************************************/ - -/* This function copies a single captured substring into a given buffer. -Note that we use memcpy() rather than strncpy() in case there are binary zeros -in the string. - -Arguments: - subject the subject string that was matched - ovector pointer to the offsets table - stringcount the number of substrings that were captured - (i.e. the yield of the pcre_exec call, unless - that was zero, in which case it should be 1/3 - of the offset table size) - stringnumber the number of the required substring - buffer where to put the substring - size the size of the buffer - -Returns: if successful: - the length of the copied string, not including the zero - that is put on the end; can be zero - if not successful: - PCRE_ERROR_NOMEMORY (-6) buffer too small - PCRE_ERROR_NOSUBSTRING (-7) no such captured substring -*/ - -#if defined COMPILE_PCRE8 -PCRE_EXP_DEFN int PCRE_CALL_CONVENTION -pcre_copy_substring(const char *subject, int *ovector, int stringcount, - int stringnumber, char *buffer, int size) -#elif defined COMPILE_PCRE16 -PCRE_EXP_DEFN int PCRE_CALL_CONVENTION -pcre16_copy_substring(PCRE_SPTR16 subject, int *ovector, int stringcount, - int stringnumber, PCRE_UCHAR16 *buffer, int size) -#elif defined COMPILE_PCRE32 -PCRE_EXP_DEFN int PCRE_CALL_CONVENTION -pcre32_copy_substring(PCRE_SPTR32 subject, int *ovector, int stringcount, - int stringnumber, PCRE_UCHAR32 *buffer, int size) -#endif -{ -int yield; -if (stringnumber < 0 || stringnumber >= stringcount) - return PCRE_ERROR_NOSUBSTRING; -stringnumber *= 2; -yield = ovector[stringnumber+1] - ovector[stringnumber]; -if (size < yield + 1) return PCRE_ERROR_NOMEMORY; -memcpy(buffer, subject + ovector[stringnumber], IN_UCHARS(yield)); -buffer[yield] = 0; -return yield; -} - - - -/************************************************* -* Copy named captured string to given buffer * -*************************************************/ - -/* This function copies a single captured substring into a given buffer, -identifying it by name. If the regex permits duplicate names, the first -substring that is set is chosen. - -Arguments: - code the compiled regex - subject the subject string that was matched - ovector pointer to the offsets table - stringcount the number of substrings that were captured - (i.e. the yield of the pcre_exec call, unless - that was zero, in which case it should be 1/3 - of the offset table size) - stringname the name of the required substring - buffer where to put the substring - size the size of the buffer - -Returns: if successful: - the length of the copied string, not including the zero - that is put on the end; can be zero - if not successful: - PCRE_ERROR_NOMEMORY (-6) buffer too small - PCRE_ERROR_NOSUBSTRING (-7) no such captured substring -*/ - -#if defined COMPILE_PCRE8 -PCRE_EXP_DEFN int PCRE_CALL_CONVENTION -pcre_copy_named_substring(const pcre *code, const char *subject, - int *ovector, int stringcount, const char *stringname, - char *buffer, int size) -#elif defined COMPILE_PCRE16 -PCRE_EXP_DEFN int PCRE_CALL_CONVENTION -pcre16_copy_named_substring(const pcre16 *code, PCRE_SPTR16 subject, - int *ovector, int stringcount, PCRE_SPTR16 stringname, - PCRE_UCHAR16 *buffer, int size) -#elif defined COMPILE_PCRE32 -PCRE_EXP_DEFN int PCRE_CALL_CONVENTION -pcre32_copy_named_substring(const pcre32 *code, PCRE_SPTR32 subject, - int *ovector, int stringcount, PCRE_SPTR32 stringname, - PCRE_UCHAR32 *buffer, int size) -#endif -{ -int n = get_first_set(code, stringname, ovector); -if (n <= 0) return n; -#if defined COMPILE_PCRE8 -return pcre_copy_substring(subject, ovector, stringcount, n, buffer, size); -#elif defined COMPILE_PCRE16 -return pcre16_copy_substring(subject, ovector, stringcount, n, buffer, size); -#elif defined COMPILE_PCRE32 -return pcre32_copy_substring(subject, ovector, stringcount, n, buffer, size); -#endif -} - - - -/************************************************* -* Copy all captured strings to new store * -*************************************************/ - -/* This function gets one chunk of store and builds a list of pointers and all -of the captured substrings in it. A NULL pointer is put on the end of the list. - -Arguments: - subject the subject string that was matched - ovector pointer to the offsets table - stringcount the number of substrings that were captured - (i.e. the yield of the pcre_exec call, unless - that was zero, in which case it should be 1/3 - of the offset table size) - listptr set to point to the list of pointers - -Returns: if successful: 0 - if not successful: - PCRE_ERROR_NOMEMORY (-6) failed to get store -*/ - -#if defined COMPILE_PCRE8 -PCRE_EXP_DEFN int PCRE_CALL_CONVENTION -pcre_get_substring_list(const char *subject, int *ovector, int stringcount, - const char ***listptr) -#elif defined COMPILE_PCRE16 -PCRE_EXP_DEFN int PCRE_CALL_CONVENTION -pcre16_get_substring_list(PCRE_SPTR16 subject, int *ovector, int stringcount, - PCRE_SPTR16 **listptr) -#elif defined COMPILE_PCRE32 -PCRE_EXP_DEFN int PCRE_CALL_CONVENTION -pcre32_get_substring_list(PCRE_SPTR32 subject, int *ovector, int stringcount, - PCRE_SPTR32 **listptr) -#endif -{ -int i; -int size = sizeof(pcre_uchar *); -int double_count = stringcount * 2; -pcre_uchar **stringlist; -pcre_uchar *p; - -for (i = 0; i < double_count; i += 2) - size += sizeof(pcre_uchar *) + IN_UCHARS(ovector[i+1] - ovector[i] + 1); - -stringlist = (pcre_uchar **)(PUBL(malloc))(size); -if (stringlist == NULL) return PCRE_ERROR_NOMEMORY; - -#if defined COMPILE_PCRE8 -*listptr = (const char **)stringlist; -#elif defined COMPILE_PCRE16 -*listptr = (PCRE_SPTR16 *)stringlist; -#elif defined COMPILE_PCRE32 -*listptr = (PCRE_SPTR32 *)stringlist; -#endif -p = (pcre_uchar *)(stringlist + stringcount + 1); - -for (i = 0; i < double_count; i += 2) - { - int len = ovector[i+1] - ovector[i]; - memcpy(p, subject + ovector[i], IN_UCHARS(len)); - *stringlist++ = p; - p += len; - *p++ = 0; - } - -*stringlist = NULL; -return 0; -} - - - -/************************************************* -* Free store obtained by get_substring_list * -*************************************************/ - -/* This function exists for the benefit of people calling PCRE from non-C -programs that can call its functions, but not free() or (PUBL(free))() -directly. - -Argument: the result of a previous pcre_get_substring_list() -Returns: nothing -*/ - -#if defined COMPILE_PCRE8 -PCRE_EXP_DEFN void PCRE_CALL_CONVENTION -pcre_free_substring_list(const char **pointer) -#elif defined COMPILE_PCRE16 -PCRE_EXP_DEFN void PCRE_CALL_CONVENTION -pcre16_free_substring_list(PCRE_SPTR16 *pointer) -#elif defined COMPILE_PCRE32 -PCRE_EXP_DEFN void PCRE_CALL_CONVENTION -pcre32_free_substring_list(PCRE_SPTR32 *pointer) -#endif -{ -(PUBL(free))((void *)pointer); -} - - - -/************************************************* -* Copy captured string to new store * -*************************************************/ - -/* This function copies a single captured substring into a piece of new -store - -Arguments: - subject the subject string that was matched - ovector pointer to the offsets table - stringcount the number of substrings that were captured - (i.e. the yield of the pcre_exec call, unless - that was zero, in which case it should be 1/3 - of the offset table size) - stringnumber the number of the required substring - stringptr where to put a pointer to the substring - -Returns: if successful: - the length of the string, not including the zero that - is put on the end; can be zero - if not successful: - PCRE_ERROR_NOMEMORY (-6) failed to get store - PCRE_ERROR_NOSUBSTRING (-7) substring not present -*/ - -#if defined COMPILE_PCRE8 -PCRE_EXP_DEFN int PCRE_CALL_CONVENTION -pcre_get_substring(const char *subject, int *ovector, int stringcount, - int stringnumber, const char **stringptr) -#elif defined COMPILE_PCRE16 -PCRE_EXP_DEFN int PCRE_CALL_CONVENTION -pcre16_get_substring(PCRE_SPTR16 subject, int *ovector, int stringcount, - int stringnumber, PCRE_SPTR16 *stringptr) -#elif defined COMPILE_PCRE32 -PCRE_EXP_DEFN int PCRE_CALL_CONVENTION -pcre32_get_substring(PCRE_SPTR32 subject, int *ovector, int stringcount, - int stringnumber, PCRE_SPTR32 *stringptr) -#endif -{ -int yield; -pcre_uchar *substring; -if (stringnumber < 0 || stringnumber >= stringcount) - return PCRE_ERROR_NOSUBSTRING; -stringnumber *= 2; -yield = ovector[stringnumber+1] - ovector[stringnumber]; -substring = (pcre_uchar *)(PUBL(malloc))(IN_UCHARS(yield + 1)); -if (substring == NULL) return PCRE_ERROR_NOMEMORY; -memcpy(substring, subject + ovector[stringnumber], IN_UCHARS(yield)); -substring[yield] = 0; -#if defined COMPILE_PCRE8 -*stringptr = (const char *)substring; -#elif defined COMPILE_PCRE16 -*stringptr = (PCRE_SPTR16)substring; -#elif defined COMPILE_PCRE32 -*stringptr = (PCRE_SPTR32)substring; -#endif -return yield; -} - - - -/************************************************* -* Copy named captured string to new store * -*************************************************/ - -/* This function copies a single captured substring, identified by name, into -new store. If the regex permits duplicate names, the first substring that is -set is chosen. - -Arguments: - code the compiled regex - subject the subject string that was matched - ovector pointer to the offsets table - stringcount the number of substrings that were captured - (i.e. the yield of the pcre_exec call, unless - that was zero, in which case it should be 1/3 - of the offset table size) - stringname the name of the required substring - stringptr where to put the pointer - -Returns: if successful: - the length of the copied string, not including the zero - that is put on the end; can be zero - if not successful: - PCRE_ERROR_NOMEMORY (-6) couldn't get memory - PCRE_ERROR_NOSUBSTRING (-7) no such captured substring -*/ - -#if defined COMPILE_PCRE8 -PCRE_EXP_DEFN int PCRE_CALL_CONVENTION -pcre_get_named_substring(const pcre *code, const char *subject, - int *ovector, int stringcount, const char *stringname, - const char **stringptr) -#elif defined COMPILE_PCRE16 -PCRE_EXP_DEFN int PCRE_CALL_CONVENTION -pcre16_get_named_substring(const pcre16 *code, PCRE_SPTR16 subject, - int *ovector, int stringcount, PCRE_SPTR16 stringname, - PCRE_SPTR16 *stringptr) -#elif defined COMPILE_PCRE32 -PCRE_EXP_DEFN int PCRE_CALL_CONVENTION -pcre32_get_named_substring(const pcre32 *code, PCRE_SPTR32 subject, - int *ovector, int stringcount, PCRE_SPTR32 stringname, - PCRE_SPTR32 *stringptr) -#endif -{ -int n = get_first_set(code, stringname, ovector); -if (n <= 0) return n; -#if defined COMPILE_PCRE8 -return pcre_get_substring(subject, ovector, stringcount, n, stringptr); -#elif defined COMPILE_PCRE16 -return pcre16_get_substring(subject, ovector, stringcount, n, stringptr); -#elif defined COMPILE_PCRE32 -return pcre32_get_substring(subject, ovector, stringcount, n, stringptr); -#endif -} - - - - -/************************************************* -* Free store obtained by get_substring * -*************************************************/ - -/* This function exists for the benefit of people calling PCRE from non-C -programs that can call its functions, but not free() or (PUBL(free))() -directly. - -Argument: the result of a previous pcre_get_substring() -Returns: nothing -*/ - -#if defined COMPILE_PCRE8 -PCRE_EXP_DEFN void PCRE_CALL_CONVENTION -pcre_free_substring(const char *pointer) -#elif defined COMPILE_PCRE16 -PCRE_EXP_DEFN void PCRE_CALL_CONVENTION -pcre16_free_substring(PCRE_SPTR16 pointer) -#elif defined COMPILE_PCRE32 -PCRE_EXP_DEFN void PCRE_CALL_CONVENTION -pcre32_free_substring(PCRE_SPTR32 pointer) -#endif -{ -(PUBL(free))((void *)pointer); -} - -/* End of pcre_get.c */ diff --git a/lib/impure/nre/private/pcre_src/pcre_globals.c b/lib/impure/nre/private/pcre_src/pcre_globals.c deleted file mode 100644 index 0f106aa90..000000000 --- a/lib/impure/nre/private/pcre_src/pcre_globals.c +++ /dev/null @@ -1,86 +0,0 @@ -/************************************************* -* Perl-Compatible Regular Expressions * -*************************************************/ - -/* PCRE is a library of functions to support regular expressions whose syntax -and semantics are as close as possible to those of the Perl 5 language. - - Written by Philip Hazel - Copyright (c) 1997-2014 University of Cambridge - ------------------------------------------------------------------------------ -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - * Neither the name of the University of Cambridge nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ -*/ - - -/* This module contains global variables that are exported by the PCRE library. -PCRE is thread-clean and doesn't use any global variables in the normal sense. -However, it calls memory allocation and freeing functions via the four -indirections below, and it can optionally do callouts, using the fifth -indirection. These values can be changed by the caller, but are shared between -all threads. - -For MS Visual Studio and Symbian OS, there are problems in initializing these -variables to non-local functions. In these cases, therefore, an indirection via -a local function is used. - -Also, when compiling for Virtual Pascal, things are done differently, and -global variables are not used. */ - -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - -#include "pcre_internal.h" - -#if defined _MSC_VER || defined __SYMBIAN32__ -static void* LocalPcreMalloc(size_t aSize) - { - return malloc(aSize); - } -static void LocalPcreFree(void* aPtr) - { - free(aPtr); - } -PCRE_EXP_DATA_DEFN void *(*PUBL(malloc))(size_t) = LocalPcreMalloc; -PCRE_EXP_DATA_DEFN void (*PUBL(free))(void *) = LocalPcreFree; -PCRE_EXP_DATA_DEFN void *(*PUBL(stack_malloc))(size_t) = LocalPcreMalloc; -PCRE_EXP_DATA_DEFN void (*PUBL(stack_free))(void *) = LocalPcreFree; -PCRE_EXP_DATA_DEFN int (*PUBL(callout))(PUBL(callout_block) *) = NULL; -PCRE_EXP_DATA_DEFN int (*PUBL(stack_guard))(void) = NULL; - -#elif !defined VPCOMPAT -PCRE_EXP_DATA_DEFN void *(*PUBL(malloc))(size_t) = malloc; -PCRE_EXP_DATA_DEFN void (*PUBL(free))(void *) = free; -PCRE_EXP_DATA_DEFN void *(*PUBL(stack_malloc))(size_t) = malloc; -PCRE_EXP_DATA_DEFN void (*PUBL(stack_free))(void *) = free; -PCRE_EXP_DATA_DEFN int (*PUBL(callout))(PUBL(callout_block) *) = NULL; -PCRE_EXP_DATA_DEFN int (*PUBL(stack_guard))(void) = NULL; -#endif - -/* End of pcre_globals.c */ diff --git a/lib/impure/nre/private/pcre_src/pcre_internal.h b/lib/impure/nre/private/pcre_src/pcre_internal.h deleted file mode 100644 index 02d3ab17c..000000000 --- a/lib/impure/nre/private/pcre_src/pcre_internal.h +++ /dev/null @@ -1,2781 +0,0 @@ -/************************************************* -* Perl-Compatible Regular Expressions * -*************************************************/ - - -/* PCRE is a library of functions to support regular expressions whose syntax -and semantics are as close as possible to those of the Perl 5 language. - - Written by Philip Hazel - Copyright (c) 1997-2014 University of Cambridge - ------------------------------------------------------------------------------ -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - * Neither the name of the University of Cambridge nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ -*/ - -/* This header contains definitions that are shared between the different -modules, but which are not relevant to the exported API. This includes some -functions whose names all begin with "_pcre_", "_pcre16_" or "_pcre32_" -depending on the PRIV macro. */ - -#ifndef PCRE_INTERNAL_H -#define PCRE_INTERNAL_H - -/* Define PCRE_DEBUG to get debugging output on stdout. */ - -#if 0 -#define PCRE_DEBUG -#endif - -/* PCRE is compiled as an 8 bit library if it is not requested otherwise. */ - -#if !defined COMPILE_PCRE16 && !defined COMPILE_PCRE32 -#define COMPILE_PCRE8 -#endif - -/* If SUPPORT_UCP is defined, SUPPORT_UTF must also be defined. The -"configure" script ensures this, but not everybody uses "configure". */ - -#if defined SUPPORT_UCP && !(defined SUPPORT_UTF) -#define SUPPORT_UTF 1 -#endif - -/* We define SUPPORT_UTF if SUPPORT_UTF8 is enabled for compatibility -reasons with existing code. */ - -#if defined SUPPORT_UTF8 && !(defined SUPPORT_UTF) -#define SUPPORT_UTF 1 -#endif - -/* Fixme: SUPPORT_UTF8 should be eventually disappear from the code. -Until then we define it if SUPPORT_UTF is defined. */ - -#if defined SUPPORT_UTF && !(defined SUPPORT_UTF8) -#define SUPPORT_UTF8 1 -#endif - -/* We do not support both EBCDIC and UTF-8/16/32 at the same time. The "configure" -script prevents both being selected, but not everybody uses "configure". */ - -#if defined EBCDIC && defined SUPPORT_UTF -#error The use of both EBCDIC and SUPPORT_UTF is not supported. -#endif - -/* Use a macro for debugging printing, 'cause that eliminates the use of #ifdef -inline, and there are *still* stupid compilers about that don't like indented -pre-processor statements, or at least there were when I first wrote this. After -all, it had only been about 10 years then... - -It turns out that the Mac Debugging.h header also defines the macro DPRINTF, so -be absolutely sure we get our version. */ - -#undef DPRINTF -#ifdef PCRE_DEBUG -#define DPRINTF(p) printf p -#else -#define DPRINTF(p) /* Nothing */ -#endif - - -/* Standard C headers plus the external interface definition. The only time -setjmp and stdarg are used is when NO_RECURSE is set. */ - -#include -#include -#include -#include -#include -#include - -/* Valgrind (memcheck) support */ - -#ifdef SUPPORT_VALGRIND -#include -#endif - -/* When compiling a DLL for Windows, the exported symbols have to be declared -using some MS magic. I found some useful information on this web page: -http://msdn2.microsoft.com/en-us/library/y4h7bcy6(VS.80).aspx. According to the -information there, using __declspec(dllexport) without "extern" we have a -definition; with "extern" we have a declaration. The settings here override the -setting in pcre.h (which is included below); it defines only PCRE_EXP_DECL, -which is all that is needed for applications (they just import the symbols). We -use: - - PCRE_EXP_DECL for declarations - PCRE_EXP_DEFN for definitions of exported functions - PCRE_EXP_DATA_DEFN for definitions of exported variables - -The reason for the two DEFN macros is that in non-Windows environments, one -does not want to have "extern" before variable definitions because it leads to -compiler warnings. So we distinguish between functions and variables. In -Windows, the two should always be the same. - -The reason for wrapping this in #ifndef PCRE_EXP_DECL is so that pcretest, -which is an application, but needs to import this file in order to "peek" at -internals, can #include pcre.h first to get an application's-eye view. - -In principle, people compiling for non-Windows, non-Unix-like (i.e. uncommon, -special-purpose environments) might want to stick other stuff in front of -exported symbols. That's why, in the non-Windows case, we set PCRE_EXP_DEFN and -PCRE_EXP_DATA_DEFN only if they are not already set. */ - -#ifndef PCRE_EXP_DECL -# ifdef _WIN32 -# ifndef PCRE_STATIC -# define PCRE_EXP_DECL extern __declspec(dllexport) -# define PCRE_EXP_DEFN __declspec(dllexport) -# define PCRE_EXP_DATA_DEFN __declspec(dllexport) -# else -# define PCRE_EXP_DECL extern -# define PCRE_EXP_DEFN -# define PCRE_EXP_DATA_DEFN -# endif -# else -# ifdef __cplusplus -# define PCRE_EXP_DECL extern "C" -# else -# define PCRE_EXP_DECL extern -# endif -# ifndef PCRE_EXP_DEFN -# define PCRE_EXP_DEFN PCRE_EXP_DECL -# endif -# ifndef PCRE_EXP_DATA_DEFN -# define PCRE_EXP_DATA_DEFN -# endif -# endif -#endif - -/* When compiling with the MSVC compiler, it is sometimes necessary to include -a "calling convention" before exported function names. (This is secondhand -information; I know nothing about MSVC myself). For example, something like - - void __cdecl function(....) - -might be needed. In order so make this easy, all the exported functions have -PCRE_CALL_CONVENTION just before their names. It is rarely needed; if not -set, we ensure here that it has no effect. */ - -#ifndef PCRE_CALL_CONVENTION -#define PCRE_CALL_CONVENTION -#endif - -/* We need to have types that specify unsigned 8, 16 and 32-bit integers. We -cannot determine these outside the compilation (e.g. by running a program as -part of "configure") because PCRE is often cross-compiled for use on other -systems. Instead we make use of the maximum sizes that are available at -preprocessor time in standard C environments. */ - -typedef unsigned char pcre_uint8; - -#if USHRT_MAX == 65535 -typedef unsigned short pcre_uint16; -typedef short pcre_int16; -#define PCRE_UINT16_MAX USHRT_MAX -#define PCRE_INT16_MAX SHRT_MAX -#elif UINT_MAX == 65535 -typedef unsigned int pcre_uint16; -typedef int pcre_int16; -#define PCRE_UINT16_MAX UINT_MAX -#define PCRE_INT16_MAX INT_MAX -#else -#error Cannot determine a type for 16-bit integers -#endif - -#if UINT_MAX == 4294967295U -typedef unsigned int pcre_uint32; -typedef int pcre_int32; -#define PCRE_UINT32_MAX UINT_MAX -#define PCRE_INT32_MAX INT_MAX -#elif ULONG_MAX == 4294967295UL -typedef unsigned long int pcre_uint32; -typedef long int pcre_int32; -#define PCRE_UINT32_MAX ULONG_MAX -#define PCRE_INT32_MAX LONG_MAX -#else -#error Cannot determine a type for 32-bit integers -#endif - -/* When checking for integer overflow in pcre_compile(), we need to handle -large integers. If a 64-bit integer type is available, we can use that. -Otherwise we have to cast to double, which of course requires floating point -arithmetic. Handle this by defining a macro for the appropriate type. If -stdint.h is available, include it; it may define INT64_MAX. Systems that do not -have stdint.h (e.g. Solaris) may have inttypes.h. The macro int64_t may be set -by "configure". */ - -#if defined HAVE_STDINT_H -#include -#elif defined HAVE_INTTYPES_H -#include -#endif - -#if defined INT64_MAX || defined int64_t -#define INT64_OR_DOUBLE int64_t -#else -#define INT64_OR_DOUBLE double -#endif - -/* All character handling must be done as unsigned characters. Otherwise there -are problems with top-bit-set characters and functions such as isspace(). -However, we leave the interface to the outside world as char * or short *, -because that should make things easier for callers. This character type is -called pcre_uchar. - -The IN_UCHARS macro multiply its argument with the byte size of the current -pcre_uchar type. Useful for memcpy and such operations, whose require the -byte size of their input/output buffers. - -The MAX_255 macro checks whether its pcre_uchar input is less than 256. - -The TABLE_GET macro is designed for accessing elements of tables whose contain -exactly 256 items. When the character is able to contain more than 256 -items, some check is needed before accessing these tables. -*/ - -#if defined COMPILE_PCRE8 - -typedef unsigned char pcre_uchar; -#define IN_UCHARS(x) (x) -#define MAX_255(c) 1 -#define TABLE_GET(c, table, default) ((table)[c]) - -#elif defined COMPILE_PCRE16 - -#if USHRT_MAX != 65535 -/* This is a warning message. Change PCRE_UCHAR16 to a 16 bit data type in -pcre.h(.in) and disable (comment out) this message. */ -#error Warning: PCRE_UCHAR16 is not a 16 bit data type. -#endif - -typedef pcre_uint16 pcre_uchar; -#define UCHAR_SHIFT (1) -#define IN_UCHARS(x) ((x) << UCHAR_SHIFT) -#define MAX_255(c) ((c) <= 255u) -#define TABLE_GET(c, table, default) (MAX_255(c)? ((table)[c]):(default)) - -#elif defined COMPILE_PCRE32 - -typedef pcre_uint32 pcre_uchar; -#define UCHAR_SHIFT (2) -#define IN_UCHARS(x) ((x) << UCHAR_SHIFT) -#define MAX_255(c) ((c) <= 255u) -#define TABLE_GET(c, table, default) (MAX_255(c)? ((table)[c]):(default)) - -#else -#error Unsupported compiling mode -#endif /* COMPILE_PCRE[8|16|32] */ - -/* This is an unsigned int value that no character can ever have. UTF-8 -characters only go up to 0x7fffffff (though Unicode doesn't go beyond -0x0010ffff). */ - -#define NOTACHAR 0xffffffff - -/* PCRE is able to support several different kinds of newline (CR, LF, CRLF, -"any" and "anycrlf" at present). The following macros are used to package up -testing for newlines. NLBLOCK, PSSTART, and PSEND are defined in the various -modules to indicate in which datablock the parameters exist, and what the -start/end of string field names are. */ - -#define NLTYPE_FIXED 0 /* Newline is a fixed length string */ -#define NLTYPE_ANY 1 /* Newline is any Unicode line ending */ -#define NLTYPE_ANYCRLF 2 /* Newline is CR, LF, or CRLF */ - -/* This macro checks for a newline at the given position */ - -#define IS_NEWLINE(p) \ - ((NLBLOCK->nltype != NLTYPE_FIXED)? \ - ((p) < NLBLOCK->PSEND && \ - PRIV(is_newline)((p), NLBLOCK->nltype, NLBLOCK->PSEND, \ - &(NLBLOCK->nllen), utf)) \ - : \ - ((p) <= NLBLOCK->PSEND - NLBLOCK->nllen && \ - UCHAR21TEST(p) == NLBLOCK->nl[0] && \ - (NLBLOCK->nllen == 1 || UCHAR21TEST(p+1) == NLBLOCK->nl[1]) \ - ) \ - ) - -/* This macro checks for a newline immediately preceding the given position */ - -#define WAS_NEWLINE(p) \ - ((NLBLOCK->nltype != NLTYPE_FIXED)? \ - ((p) > NLBLOCK->PSSTART && \ - PRIV(was_newline)((p), NLBLOCK->nltype, NLBLOCK->PSSTART, \ - &(NLBLOCK->nllen), utf)) \ - : \ - ((p) >= NLBLOCK->PSSTART + NLBLOCK->nllen && \ - UCHAR21TEST(p - NLBLOCK->nllen) == NLBLOCK->nl[0] && \ - (NLBLOCK->nllen == 1 || UCHAR21TEST(p - NLBLOCK->nllen + 1) == NLBLOCK->nl[1]) \ - ) \ - ) - -/* When PCRE is compiled as a C++ library, the subject pointer can be replaced -with a custom type. This makes it possible, for example, to allow pcre_exec() -to process subject strings that are discontinuous by using a smart pointer -class. It must always be possible to inspect all of the subject string in -pcre_exec() because of the way it backtracks. Two macros are required in the -normal case, for sign-unspecified and unsigned char pointers. The former is -used for the external interface and appears in pcre.h, which is why its name -must begin with PCRE_. */ - -#ifdef CUSTOM_SUBJECT_PTR -#define PCRE_PUCHAR CUSTOM_SUBJECT_PTR -#else -#define PCRE_PUCHAR const pcre_uchar * -#endif - -/* Include the public PCRE header and the definitions of UCP character property -values. */ - -#include "pcre.h" -#include "ucp.h" - -#ifdef COMPILE_PCRE32 -/* Assert that the public PCRE_UCHAR32 is a 32-bit type */ -typedef int __assert_pcre_uchar32_size[sizeof(PCRE_UCHAR32) == 4 ? 1 : -1]; -#endif - -/* When compiling for use with the Virtual Pascal compiler, these functions -need to have their names changed. PCRE must be compiled with the -DVPCOMPAT -option on the command line. */ - -#ifdef VPCOMPAT -#define strlen(s) _strlen(s) -#define strncmp(s1,s2,m) _strncmp(s1,s2,m) -#define memcmp(s,c,n) _memcmp(s,c,n) -#define memcpy(d,s,n) _memcpy(d,s,n) -#define memmove(d,s,n) _memmove(d,s,n) -#define memset(s,c,n) _memset(s,c,n) -#else /* VPCOMPAT */ - -/* To cope with SunOS4 and other systems that lack memmove() but have bcopy(), -define a macro for memmove() if HAVE_MEMMOVE is false, provided that HAVE_BCOPY -is set. Otherwise, include an emulating function for those systems that have -neither (there some non-Unix environments where this is the case). */ - -#ifndef HAVE_MEMMOVE -#undef memmove /* some systems may have a macro */ -#ifdef HAVE_BCOPY -#define memmove(a, b, c) bcopy(b, a, c) -#else /* HAVE_BCOPY */ -static void * -pcre_memmove(void *d, const void *s, size_t n) -{ -size_t i; -unsigned char *dest = (unsigned char *)d; -const unsigned char *src = (const unsigned char *)s; -if (dest > src) - { - dest += n; - src += n; - for (i = 0; i < n; ++i) *(--dest) = *(--src); - return (void *)dest; - } -else - { - for (i = 0; i < n; ++i) *dest++ = *src++; - return (void *)(dest - n); - } -} -#define memmove(a, b, c) pcre_memmove(a, b, c) -#endif /* not HAVE_BCOPY */ -#endif /* not HAVE_MEMMOVE */ -#endif /* not VPCOMPAT */ - - -/* PCRE keeps offsets in its compiled code as 2-byte quantities (always stored -in big-endian order) by default. These are used, for example, to link from the -start of a subpattern to its alternatives and its end. The use of 2 bytes per -offset limits the size of the compiled regex to around 64K, which is big enough -for almost everybody. However, I received a request for an even bigger limit. -For this reason, and also to make the code easier to maintain, the storing and -loading of offsets from the byte string is now handled by the macros that are -defined here. - -The macros are controlled by the value of LINK_SIZE. This defaults to 2 in -the config.h file, but can be overridden by using -D on the command line. This -is automated on Unix systems via the "configure" command. */ - -#if defined COMPILE_PCRE8 - -#if LINK_SIZE == 2 - -#define PUT(a,n,d) \ - (a[n] = (d) >> 8), \ - (a[(n)+1] = (d) & 255) - -#define GET(a,n) \ - (((a)[n] << 8) | (a)[(n)+1]) - -#define MAX_PATTERN_SIZE (1 << 16) - - -#elif LINK_SIZE == 3 - -#define PUT(a,n,d) \ - (a[n] = (d) >> 16), \ - (a[(n)+1] = (d) >> 8), \ - (a[(n)+2] = (d) & 255) - -#define GET(a,n) \ - (((a)[n] << 16) | ((a)[(n)+1] << 8) | (a)[(n)+2]) - -#define MAX_PATTERN_SIZE (1 << 24) - - -#elif LINK_SIZE == 4 - -#define PUT(a,n,d) \ - (a[n] = (d) >> 24), \ - (a[(n)+1] = (d) >> 16), \ - (a[(n)+2] = (d) >> 8), \ - (a[(n)+3] = (d) & 255) - -#define GET(a,n) \ - (((a)[n] << 24) | ((a)[(n)+1] << 16) | ((a)[(n)+2] << 8) | (a)[(n)+3]) - -/* Keep it positive */ -#define MAX_PATTERN_SIZE (1 << 30) - -#else -#error LINK_SIZE must be either 2, 3, or 4 -#endif - -#elif defined COMPILE_PCRE16 - -#if LINK_SIZE == 2 - -/* Redefine LINK_SIZE as a multiple of sizeof(pcre_uchar) */ -#undef LINK_SIZE -#define LINK_SIZE 1 - -#define PUT(a,n,d) \ - (a[n] = (d)) - -#define GET(a,n) \ - (a[n]) - -#define MAX_PATTERN_SIZE (1 << 16) - -#elif LINK_SIZE == 3 || LINK_SIZE == 4 - -/* Redefine LINK_SIZE as a multiple of sizeof(pcre_uchar) */ -#undef LINK_SIZE -#define LINK_SIZE 2 - -#define PUT(a,n,d) \ - (a[n] = (d) >> 16), \ - (a[(n)+1] = (d) & 65535) - -#define GET(a,n) \ - (((a)[n] << 16) | (a)[(n)+1]) - -/* Keep it positive */ -#define MAX_PATTERN_SIZE (1 << 30) - -#else -#error LINK_SIZE must be either 2, 3, or 4 -#endif - -#elif defined COMPILE_PCRE32 - -/* Only supported LINK_SIZE is 4 */ -/* Redefine LINK_SIZE as a multiple of sizeof(pcre_uchar) */ -#undef LINK_SIZE -#define LINK_SIZE 1 - -#define PUT(a,n,d) \ - (a[n] = (d)) - -#define GET(a,n) \ - (a[n]) - -/* Keep it positive */ -#define MAX_PATTERN_SIZE (1 << 30) - -#else -#error Unsupported compiling mode -#endif /* COMPILE_PCRE[8|16|32] */ - -/* Convenience macro defined in terms of the others */ - -#define PUTINC(a,n,d) PUT(a,n,d), a += LINK_SIZE - - -/* PCRE uses some other 2-byte quantities that do not change when the size of -offsets changes. There are used for repeat counts and for other things such as -capturing parenthesis numbers in back references. */ - -#if defined COMPILE_PCRE8 - -#define IMM2_SIZE 2 - -#define PUT2(a,n,d) \ - a[n] = (d) >> 8; \ - a[(n)+1] = (d) & 255 - -/* For reasons that I do not understand, the expression in this GET2 macro is -treated by gcc as a signed expression, even when a is declared as unsigned. It -seems that any kind of arithmetic results in a signed value. */ - -#define GET2(a,n) \ - (unsigned int)(((a)[n] << 8) | (a)[(n)+1]) - -#elif defined COMPILE_PCRE16 - -#define IMM2_SIZE 1 - -#define PUT2(a,n,d) \ - a[n] = d - -#define GET2(a,n) \ - a[n] - -#elif defined COMPILE_PCRE32 - -#define IMM2_SIZE 1 - -#define PUT2(a,n,d) \ - a[n] = d - -#define GET2(a,n) \ - a[n] - -#else -#error Unsupported compiling mode -#endif /* COMPILE_PCRE[8|16|32] */ - -#define PUT2INC(a,n,d) PUT2(a,n,d), a += IMM2_SIZE - -/* The maximum length of a MARK name is currently one data unit; it may be -changed in future to be a fixed number of bytes or to depend on LINK_SIZE. */ - -#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 -#define MAX_MARK ((1u << 16) - 1) -#else -#define MAX_MARK ((1u << 8) - 1) -#endif - -/* There is a proposed future special "UTF-21" mode, in which only the lowest -21 bits of a 32-bit character are interpreted as UTF, with the remaining 11 -high-order bits available to the application for other uses. In preparation for -the future implementation of this mode, there are macros that load a data item -and, if in this special mode, mask it to 21 bits. These macros all have names -starting with UCHAR21. In all other modes, including the normal 32-bit -library, the macros all have the same simple definitions. When the new mode is -implemented, it is expected that these definitions will be varied appropriately -using #ifdef when compiling the library that supports the special mode. */ - -#define UCHAR21(eptr) (*(eptr)) -#define UCHAR21TEST(eptr) (*(eptr)) -#define UCHAR21INC(eptr) (*(eptr)++) -#define UCHAR21INCTEST(eptr) (*(eptr)++) - -/* When UTF encoding is being used, a character is no longer just a single -byte in 8-bit mode or a single short in 16-bit mode. The macros for character -handling generate simple sequences when used in the basic mode, and more -complicated ones for UTF characters. GETCHARLENTEST and other macros are not -used when UTF is not supported. To make sure they can never even appear when -UTF support is omitted, we don't even define them. */ - -#ifndef SUPPORT_UTF - -/* #define MAX_VALUE_FOR_SINGLE_CHAR */ -/* #define HAS_EXTRALEN(c) */ -/* #define GET_EXTRALEN(c) */ -/* #define NOT_FIRSTCHAR(c) */ -#define GETCHAR(c, eptr) c = *eptr; -#define GETCHARTEST(c, eptr) c = *eptr; -#define GETCHARINC(c, eptr) c = *eptr++; -#define GETCHARINCTEST(c, eptr) c = *eptr++; -#define GETCHARLEN(c, eptr, len) c = *eptr; -/* #define GETCHARLENTEST(c, eptr, len) */ -/* #define BACKCHAR(eptr) */ -/* #define FORWARDCHAR(eptr) */ -/* #define ACROSSCHAR(condition, eptr, action) */ - -#else /* SUPPORT_UTF */ - -/* Tests whether the code point needs extra characters to decode. */ - -#define HASUTF8EXTRALEN(c) ((c) >= 0xc0) - -/* Base macro to pick up the remaining bytes of a UTF-8 character, not -advancing the pointer. */ - -#define GETUTF8(c, eptr) \ - { \ - if ((c & 0x20) == 0) \ - c = ((c & 0x1f) << 6) | (eptr[1] & 0x3f); \ - else if ((c & 0x10) == 0) \ - c = ((c & 0x0f) << 12) | ((eptr[1] & 0x3f) << 6) | (eptr[2] & 0x3f); \ - else if ((c & 0x08) == 0) \ - c = ((c & 0x07) << 18) | ((eptr[1] & 0x3f) << 12) | \ - ((eptr[2] & 0x3f) << 6) | (eptr[3] & 0x3f); \ - else if ((c & 0x04) == 0) \ - c = ((c & 0x03) << 24) | ((eptr[1] & 0x3f) << 18) | \ - ((eptr[2] & 0x3f) << 12) | ((eptr[3] & 0x3f) << 6) | \ - (eptr[4] & 0x3f); \ - else \ - c = ((c & 0x01) << 30) | ((eptr[1] & 0x3f) << 24) | \ - ((eptr[2] & 0x3f) << 18) | ((eptr[3] & 0x3f) << 12) | \ - ((eptr[4] & 0x3f) << 6) | (eptr[5] & 0x3f); \ - } - -/* Base macro to pick up the remaining bytes of a UTF-8 character, advancing -the pointer. */ - -#define GETUTF8INC(c, eptr) \ - { \ - if ((c & 0x20) == 0) \ - c = ((c & 0x1f) << 6) | (*eptr++ & 0x3f); \ - else if ((c & 0x10) == 0) \ - { \ - c = ((c & 0x0f) << 12) | ((*eptr & 0x3f) << 6) | (eptr[1] & 0x3f); \ - eptr += 2; \ - } \ - else if ((c & 0x08) == 0) \ - { \ - c = ((c & 0x07) << 18) | ((*eptr & 0x3f) << 12) | \ - ((eptr[1] & 0x3f) << 6) | (eptr[2] & 0x3f); \ - eptr += 3; \ - } \ - else if ((c & 0x04) == 0) \ - { \ - c = ((c & 0x03) << 24) | ((*eptr & 0x3f) << 18) | \ - ((eptr[1] & 0x3f) << 12) | ((eptr[2] & 0x3f) << 6) | \ - (eptr[3] & 0x3f); \ - eptr += 4; \ - } \ - else \ - { \ - c = ((c & 0x01) << 30) | ((*eptr & 0x3f) << 24) | \ - ((eptr[1] & 0x3f) << 18) | ((eptr[2] & 0x3f) << 12) | \ - ((eptr[3] & 0x3f) << 6) | (eptr[4] & 0x3f); \ - eptr += 5; \ - } \ - } - -#if defined COMPILE_PCRE8 - -/* These macros were originally written in the form of loops that used data -from the tables whose names start with PRIV(utf8_table). They were rewritten by -a user so as not to use loops, because in some environments this gives a -significant performance advantage, and it seems never to do any harm. */ - -/* Tells the biggest code point which can be encoded as a single character. */ - -#define MAX_VALUE_FOR_SINGLE_CHAR 127 - -/* Tests whether the code point needs extra characters to decode. */ - -#define HAS_EXTRALEN(c) ((c) >= 0xc0) - -/* Returns with the additional number of characters if IS_MULTICHAR(c) is TRUE. -Otherwise it has an undefined behaviour. */ - -#define GET_EXTRALEN(c) (PRIV(utf8_table4)[(c) & 0x3f]) - -/* Returns TRUE, if the given character is not the first character -of a UTF sequence. */ - -#define NOT_FIRSTCHAR(c) (((c) & 0xc0) == 0x80) - -/* Get the next UTF-8 character, not advancing the pointer. This is called when -we know we are in UTF-8 mode. */ - -#define GETCHAR(c, eptr) \ - c = *eptr; \ - if (c >= 0xc0) GETUTF8(c, eptr); - -/* Get the next UTF-8 character, testing for UTF-8 mode, and not advancing the -pointer. */ - -#define GETCHARTEST(c, eptr) \ - c = *eptr; \ - if (utf && c >= 0xc0) GETUTF8(c, eptr); - -/* Get the next UTF-8 character, advancing the pointer. This is called when we -know we are in UTF-8 mode. */ - -#define GETCHARINC(c, eptr) \ - c = *eptr++; \ - if (c >= 0xc0) GETUTF8INC(c, eptr); - -/* Get the next character, testing for UTF-8 mode, and advancing the pointer. -This is called when we don't know if we are in UTF-8 mode. */ - -#define GETCHARINCTEST(c, eptr) \ - c = *eptr++; \ - if (utf && c >= 0xc0) GETUTF8INC(c, eptr); - -/* Base macro to pick up the remaining bytes of a UTF-8 character, not -advancing the pointer, incrementing the length. */ - -#define GETUTF8LEN(c, eptr, len) \ - { \ - if ((c & 0x20) == 0) \ - { \ - c = ((c & 0x1f) << 6) | (eptr[1] & 0x3f); \ - len++; \ - } \ - else if ((c & 0x10) == 0) \ - { \ - c = ((c & 0x0f) << 12) | ((eptr[1] & 0x3f) << 6) | (eptr[2] & 0x3f); \ - len += 2; \ - } \ - else if ((c & 0x08) == 0) \ - {\ - c = ((c & 0x07) << 18) | ((eptr[1] & 0x3f) << 12) | \ - ((eptr[2] & 0x3f) << 6) | (eptr[3] & 0x3f); \ - len += 3; \ - } \ - else if ((c & 0x04) == 0) \ - { \ - c = ((c & 0x03) << 24) | ((eptr[1] & 0x3f) << 18) | \ - ((eptr[2] & 0x3f) << 12) | ((eptr[3] & 0x3f) << 6) | \ - (eptr[4] & 0x3f); \ - len += 4; \ - } \ - else \ - {\ - c = ((c & 0x01) << 30) | ((eptr[1] & 0x3f) << 24) | \ - ((eptr[2] & 0x3f) << 18) | ((eptr[3] & 0x3f) << 12) | \ - ((eptr[4] & 0x3f) << 6) | (eptr[5] & 0x3f); \ - len += 5; \ - } \ - } - -/* Get the next UTF-8 character, not advancing the pointer, incrementing length -if there are extra bytes. This is called when we know we are in UTF-8 mode. */ - -#define GETCHARLEN(c, eptr, len) \ - c = *eptr; \ - if (c >= 0xc0) GETUTF8LEN(c, eptr, len); - -/* Get the next UTF-8 character, testing for UTF-8 mode, not advancing the -pointer, incrementing length if there are extra bytes. This is called when we -do not know if we are in UTF-8 mode. */ - -#define GETCHARLENTEST(c, eptr, len) \ - c = *eptr; \ - if (utf && c >= 0xc0) GETUTF8LEN(c, eptr, len); - -/* If the pointer is not at the start of a character, move it back until -it is. This is called only in UTF-8 mode - we don't put a test within the macro -because almost all calls are already within a block of UTF-8 only code. */ - -#define BACKCHAR(eptr) while((*eptr & 0xc0) == 0x80) eptr-- - -/* Same as above, just in the other direction. */ -#define FORWARDCHAR(eptr) while((*eptr & 0xc0) == 0x80) eptr++ - -/* Same as above, but it allows a fully customizable form. */ -#define ACROSSCHAR(condition, eptr, action) \ - while((condition) && ((eptr) & 0xc0) == 0x80) action - -#elif defined COMPILE_PCRE16 - -/* Tells the biggest code point which can be encoded as a single character. */ - -#define MAX_VALUE_FOR_SINGLE_CHAR 65535 - -/* Tests whether the code point needs extra characters to decode. */ - -#define HAS_EXTRALEN(c) (((c) & 0xfc00) == 0xd800) - -/* Returns with the additional number of characters if IS_MULTICHAR(c) is TRUE. -Otherwise it has an undefined behaviour. */ - -#define GET_EXTRALEN(c) 1 - -/* Returns TRUE, if the given character is not the first character -of a UTF sequence. */ - -#define NOT_FIRSTCHAR(c) (((c) & 0xfc00) == 0xdc00) - -/* Base macro to pick up the low surrogate of a UTF-16 character, not -advancing the pointer. */ - -#define GETUTF16(c, eptr) \ - { c = (((c & 0x3ff) << 10) | (eptr[1] & 0x3ff)) + 0x10000; } - -/* Get the next UTF-16 character, not advancing the pointer. This is called when -we know we are in UTF-16 mode. */ - -#define GETCHAR(c, eptr) \ - c = *eptr; \ - if ((c & 0xfc00) == 0xd800) GETUTF16(c, eptr); - -/* Get the next UTF-16 character, testing for UTF-16 mode, and not advancing the -pointer. */ - -#define GETCHARTEST(c, eptr) \ - c = *eptr; \ - if (utf && (c & 0xfc00) == 0xd800) GETUTF16(c, eptr); - -/* Base macro to pick up the low surrogate of a UTF-16 character, advancing -the pointer. */ - -#define GETUTF16INC(c, eptr) \ - { c = (((c & 0x3ff) << 10) | (*eptr++ & 0x3ff)) + 0x10000; } - -/* Get the next UTF-16 character, advancing the pointer. This is called when we -know we are in UTF-16 mode. */ - -#define GETCHARINC(c, eptr) \ - c = *eptr++; \ - if ((c & 0xfc00) == 0xd800) GETUTF16INC(c, eptr); - -/* Get the next character, testing for UTF-16 mode, and advancing the pointer. -This is called when we don't know if we are in UTF-16 mode. */ - -#define GETCHARINCTEST(c, eptr) \ - c = *eptr++; \ - if (utf && (c & 0xfc00) == 0xd800) GETUTF16INC(c, eptr); - -/* Base macro to pick up the low surrogate of a UTF-16 character, not -advancing the pointer, incrementing the length. */ - -#define GETUTF16LEN(c, eptr, len) \ - { c = (((c & 0x3ff) << 10) | (eptr[1] & 0x3ff)) + 0x10000; len++; } - -/* Get the next UTF-16 character, not advancing the pointer, incrementing -length if there is a low surrogate. This is called when we know we are in -UTF-16 mode. */ - -#define GETCHARLEN(c, eptr, len) \ - c = *eptr; \ - if ((c & 0xfc00) == 0xd800) GETUTF16LEN(c, eptr, len); - -/* Get the next UTF-816character, testing for UTF-16 mode, not advancing the -pointer, incrementing length if there is a low surrogate. This is called when -we do not know if we are in UTF-16 mode. */ - -#define GETCHARLENTEST(c, eptr, len) \ - c = *eptr; \ - if (utf && (c & 0xfc00) == 0xd800) GETUTF16LEN(c, eptr, len); - -/* If the pointer is not at the start of a character, move it back until -it is. This is called only in UTF-16 mode - we don't put a test within the -macro because almost all calls are already within a block of UTF-16 only -code. */ - -#define BACKCHAR(eptr) if ((*eptr & 0xfc00) == 0xdc00) eptr-- - -/* Same as above, just in the other direction. */ -#define FORWARDCHAR(eptr) if ((*eptr & 0xfc00) == 0xdc00) eptr++ - -/* Same as above, but it allows a fully customizable form. */ -#define ACROSSCHAR(condition, eptr, action) \ - if ((condition) && ((eptr) & 0xfc00) == 0xdc00) action - -#elif defined COMPILE_PCRE32 - -/* These are trivial for the 32-bit library, since all UTF-32 characters fit -into one pcre_uchar unit. */ -#define MAX_VALUE_FOR_SINGLE_CHAR (0x10ffffu) -#define HAS_EXTRALEN(c) (0) -#define GET_EXTRALEN(c) (0) -#define NOT_FIRSTCHAR(c) (0) - -/* Get the next UTF-32 character, not advancing the pointer. This is called when -we know we are in UTF-32 mode. */ - -#define GETCHAR(c, eptr) \ - c = *(eptr); - -/* Get the next UTF-32 character, testing for UTF-32 mode, and not advancing the -pointer. */ - -#define GETCHARTEST(c, eptr) \ - c = *(eptr); - -/* Get the next UTF-32 character, advancing the pointer. This is called when we -know we are in UTF-32 mode. */ - -#define GETCHARINC(c, eptr) \ - c = *((eptr)++); - -/* Get the next character, testing for UTF-32 mode, and advancing the pointer. -This is called when we don't know if we are in UTF-32 mode. */ - -#define GETCHARINCTEST(c, eptr) \ - c = *((eptr)++); - -/* Get the next UTF-32 character, not advancing the pointer, not incrementing -length (since all UTF-32 is of length 1). This is called when we know we are in -UTF-32 mode. */ - -#define GETCHARLEN(c, eptr, len) \ - GETCHAR(c, eptr) - -/* Get the next UTF-32character, testing for UTF-32 mode, not advancing the -pointer, not incrementing the length (since all UTF-32 is of length 1). -This is called when we do not know if we are in UTF-32 mode. */ - -#define GETCHARLENTEST(c, eptr, len) \ - GETCHARTEST(c, eptr) - -/* If the pointer is not at the start of a character, move it back until -it is. This is called only in UTF-32 mode - we don't put a test within the -macro because almost all calls are already within a block of UTF-32 only -code. -These are all no-ops since all UTF-32 characters fit into one pcre_uchar. */ - -#define BACKCHAR(eptr) do { } while (0) - -/* Same as above, just in the other direction. */ -#define FORWARDCHAR(eptr) do { } while (0) - -/* Same as above, but it allows a fully customizable form. */ -#define ACROSSCHAR(condition, eptr, action) do { } while (0) - -#else -#error Unsupported compiling mode -#endif /* COMPILE_PCRE[8|16|32] */ - -#endif /* SUPPORT_UTF */ - -/* Tests for Unicode horizontal and vertical whitespace characters must check a -number of different values. Using a switch statement for this generates the -fastest code (no loop, no memory access), and there are several places in the -interpreter code where this happens. In order to ensure that all the case lists -remain in step, we use macros so that there is only one place where the lists -are defined. - -These values are also required as lists in pcre_compile.c when processing \h, -\H, \v and \V in a character class. The lists are defined in pcre_tables.c, but -macros that define the values are here so that all the definitions are -together. The lists must be in ascending character order, terminated by -NOTACHAR (which is 0xffffffff). - -Any changes should ensure that the various macros are kept in step with each -other. NOTE: The values also appear in pcre_jit_compile.c. */ - -/* ------ ASCII/Unicode environments ------ */ - -#ifndef EBCDIC - -#define HSPACE_LIST \ - CHAR_HT, CHAR_SPACE, 0xa0, \ - 0x1680, 0x180e, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, \ - 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202f, 0x205f, 0x3000, \ - NOTACHAR - -#define HSPACE_MULTIBYTE_CASES \ - case 0x1680: /* OGHAM SPACE MARK */ \ - case 0x180e: /* MONGOLIAN VOWEL SEPARATOR */ \ - case 0x2000: /* EN QUAD */ \ - case 0x2001: /* EM QUAD */ \ - case 0x2002: /* EN SPACE */ \ - case 0x2003: /* EM SPACE */ \ - case 0x2004: /* THREE-PER-EM SPACE */ \ - case 0x2005: /* FOUR-PER-EM SPACE */ \ - case 0x2006: /* SIX-PER-EM SPACE */ \ - case 0x2007: /* FIGURE SPACE */ \ - case 0x2008: /* PUNCTUATION SPACE */ \ - case 0x2009: /* THIN SPACE */ \ - case 0x200A: /* HAIR SPACE */ \ - case 0x202f: /* NARROW NO-BREAK SPACE */ \ - case 0x205f: /* MEDIUM MATHEMATICAL SPACE */ \ - case 0x3000 /* IDEOGRAPHIC SPACE */ - -#define HSPACE_BYTE_CASES \ - case CHAR_HT: \ - case CHAR_SPACE: \ - case 0xa0 /* NBSP */ - -#define HSPACE_CASES \ - HSPACE_BYTE_CASES: \ - HSPACE_MULTIBYTE_CASES - -#define VSPACE_LIST \ - CHAR_LF, CHAR_VT, CHAR_FF, CHAR_CR, CHAR_NEL, 0x2028, 0x2029, NOTACHAR - -#define VSPACE_MULTIBYTE_CASES \ - case 0x2028: /* LINE SEPARATOR */ \ - case 0x2029 /* PARAGRAPH SEPARATOR */ - -#define VSPACE_BYTE_CASES \ - case CHAR_LF: \ - case CHAR_VT: \ - case CHAR_FF: \ - case CHAR_CR: \ - case CHAR_NEL - -#define VSPACE_CASES \ - VSPACE_BYTE_CASES: \ - VSPACE_MULTIBYTE_CASES - -/* ------ EBCDIC environments ------ */ - -#else -#define HSPACE_LIST CHAR_HT, CHAR_SPACE - -#define HSPACE_BYTE_CASES \ - case CHAR_HT: \ - case CHAR_SPACE - -#define HSPACE_CASES HSPACE_BYTE_CASES - -#ifdef EBCDIC_NL25 -#define VSPACE_LIST \ - CHAR_VT, CHAR_FF, CHAR_CR, CHAR_NEL, CHAR_LF, NOTACHAR -#else -#define VSPACE_LIST \ - CHAR_VT, CHAR_FF, CHAR_CR, CHAR_LF, CHAR_NEL, NOTACHAR -#endif - -#define VSPACE_BYTE_CASES \ - case CHAR_LF: \ - case CHAR_VT: \ - case CHAR_FF: \ - case CHAR_CR: \ - case CHAR_NEL - -#define VSPACE_CASES VSPACE_BYTE_CASES -#endif /* EBCDIC */ - -/* ------ End of whitespace macros ------ */ - - - -/* Private flags containing information about the compiled regex. They used to -live at the top end of the options word, but that got almost full, so they were -moved to a 16-bit flags word - which got almost full, so now they are in a -32-bit flags word. From release 8.00, PCRE_NOPARTIAL is unused, as the -restrictions on partial matching have been lifted. It remains for backwards -compatibility. */ - -#define PCRE_MODE8 0x00000001 /* compiled in 8 bit mode */ -#define PCRE_MODE16 0x00000002 /* compiled in 16 bit mode */ -#define PCRE_MODE32 0x00000004 /* compiled in 32 bit mode */ -#define PCRE_FIRSTSET 0x00000010 /* first_char is set */ -#define PCRE_FCH_CASELESS 0x00000020 /* caseless first char */ -#define PCRE_REQCHSET 0x00000040 /* req_byte is set */ -#define PCRE_RCH_CASELESS 0x00000080 /* caseless requested char */ -#define PCRE_STARTLINE 0x00000100 /* start after \n for multiline */ -#define PCRE_NOPARTIAL 0x00000200 /* can't use partial with this regex */ -#define PCRE_JCHANGED 0x00000400 /* j option used in regex */ -#define PCRE_HASCRORLF 0x00000800 /* explicit \r or \n in pattern */ -#define PCRE_HASTHEN 0x00001000 /* pattern contains (*THEN) */ -#define PCRE_MLSET 0x00002000 /* match limit set by regex */ -#define PCRE_RLSET 0x00004000 /* recursion limit set by regex */ -#define PCRE_MATCH_EMPTY 0x00008000 /* pattern can match empty string */ - -#if defined COMPILE_PCRE8 -#define PCRE_MODE PCRE_MODE8 -#elif defined COMPILE_PCRE16 -#define PCRE_MODE PCRE_MODE16 -#elif defined COMPILE_PCRE32 -#define PCRE_MODE PCRE_MODE32 -#endif -#define PCRE_MODE_MASK (PCRE_MODE8 | PCRE_MODE16 | PCRE_MODE32) - -/* Flags for the "extra" block produced by pcre_study(). */ - -#define PCRE_STUDY_MAPPED 0x0001 /* a map of starting chars exists */ -#define PCRE_STUDY_MINLEN 0x0002 /* a minimum length field exists */ - -/* Masks for identifying the public options that are permitted at compile -time, run time, or study time, respectively. */ - -#define PCRE_NEWLINE_BITS (PCRE_NEWLINE_CR|PCRE_NEWLINE_LF|PCRE_NEWLINE_ANY| \ - PCRE_NEWLINE_ANYCRLF) - -#define PUBLIC_COMPILE_OPTIONS \ - (PCRE_CASELESS|PCRE_EXTENDED|PCRE_ANCHORED|PCRE_MULTILINE| \ - PCRE_DOTALL|PCRE_DOLLAR_ENDONLY|PCRE_EXTRA|PCRE_UNGREEDY|PCRE_UTF8| \ - PCRE_NO_AUTO_CAPTURE|PCRE_NO_AUTO_POSSESS| \ - PCRE_NO_UTF8_CHECK|PCRE_AUTO_CALLOUT|PCRE_FIRSTLINE| \ - PCRE_DUPNAMES|PCRE_NEWLINE_BITS|PCRE_BSR_ANYCRLF|PCRE_BSR_UNICODE| \ - PCRE_JAVASCRIPT_COMPAT|PCRE_UCP|PCRE_NO_START_OPTIMIZE|PCRE_NEVER_UTF) - -#define PUBLIC_EXEC_OPTIONS \ - (PCRE_ANCHORED|PCRE_NOTBOL|PCRE_NOTEOL|PCRE_NOTEMPTY|PCRE_NOTEMPTY_ATSTART| \ - PCRE_NO_UTF8_CHECK|PCRE_PARTIAL_HARD|PCRE_PARTIAL_SOFT|PCRE_NEWLINE_BITS| \ - PCRE_BSR_ANYCRLF|PCRE_BSR_UNICODE|PCRE_NO_START_OPTIMIZE) - -#define PUBLIC_DFA_EXEC_OPTIONS \ - (PCRE_ANCHORED|PCRE_NOTBOL|PCRE_NOTEOL|PCRE_NOTEMPTY|PCRE_NOTEMPTY_ATSTART| \ - PCRE_NO_UTF8_CHECK|PCRE_PARTIAL_HARD|PCRE_PARTIAL_SOFT|PCRE_DFA_SHORTEST| \ - PCRE_DFA_RESTART|PCRE_NEWLINE_BITS|PCRE_BSR_ANYCRLF|PCRE_BSR_UNICODE| \ - PCRE_NO_START_OPTIMIZE) - -#define PUBLIC_STUDY_OPTIONS \ - (PCRE_STUDY_JIT_COMPILE|PCRE_STUDY_JIT_PARTIAL_SOFT_COMPILE| \ - PCRE_STUDY_JIT_PARTIAL_HARD_COMPILE|PCRE_STUDY_EXTRA_NEEDED) - -#define PUBLIC_JIT_EXEC_OPTIONS \ - (PCRE_NO_UTF8_CHECK|PCRE_NOTBOL|PCRE_NOTEOL|PCRE_NOTEMPTY|\ - PCRE_NOTEMPTY_ATSTART|PCRE_PARTIAL_SOFT|PCRE_PARTIAL_HARD) - -/* Magic number to provide a small check against being handed junk. */ - -#define MAGIC_NUMBER 0x50435245UL /* 'PCRE' */ - -/* This variable is used to detect a loaded regular expression -in different endianness. */ - -#define REVERSED_MAGIC_NUMBER 0x45524350UL /* 'ERCP' */ - -/* The maximum remaining length of subject we are prepared to search for a -req_byte match. */ - -#define REQ_BYTE_MAX 1000 - -/* Miscellaneous definitions. The #ifndef is to pacify compiler warnings in -environments where these macros are defined elsewhere. Unfortunately, there -is no way to do the same for the typedef. */ - -typedef int BOOL; - -#ifndef FALSE -#define FALSE 0 -#define TRUE 1 -#endif - -/* If PCRE is to support UTF-8 on EBCDIC platforms, we cannot use normal -character constants like '*' because the compiler would emit their EBCDIC code, -which is different from their ASCII/UTF-8 code. Instead we define macros for -the characters so that they always use the ASCII/UTF-8 code when UTF-8 support -is enabled. When UTF-8 support is not enabled, the definitions use character -literals. Both character and string versions of each character are needed, and -there are some longer strings as well. - -This means that, on EBCDIC platforms, the PCRE library can handle either -EBCDIC, or UTF-8, but not both. To support both in the same compiled library -would need different lookups depending on whether PCRE_UTF8 was set or not. -This would make it impossible to use characters in switch/case statements, -which would reduce performance. For a theoretical use (which nobody has asked -for) in a minority area (EBCDIC platforms), this is not sensible. Any -application that did need both could compile two versions of the library, using -macros to give the functions distinct names. */ - -#ifndef SUPPORT_UTF - -/* UTF-8 support is not enabled; use the platform-dependent character literals -so that PCRE works in both ASCII and EBCDIC environments, but only in non-UTF -mode. Newline characters are problematic in EBCDIC. Though it has CR and LF -characters, a common practice has been to use its NL (0x15) character as the -line terminator in C-like processing environments. However, sometimes the LF -(0x25) character is used instead, according to this Unicode document: - -http://unicode.org/standard/reports/tr13/tr13-5.html - -PCRE defaults EBCDIC NL to 0x15, but has a build-time option to select 0x25 -instead. Whichever is *not* chosen is defined as NEL. - -In both ASCII and EBCDIC environments, CHAR_NL and CHAR_LF are synonyms for the -same code point. */ - -#ifdef EBCDIC - -#ifndef EBCDIC_NL25 -#define CHAR_NL '\x15' -#define CHAR_NEL '\x25' -#define STR_NL "\x15" -#define STR_NEL "\x25" -#else -#define CHAR_NL '\x25' -#define CHAR_NEL '\x15' -#define STR_NL "\x25" -#define STR_NEL "\x15" -#endif - -#define CHAR_LF CHAR_NL -#define STR_LF STR_NL - -#define CHAR_ESC '\047' -#define CHAR_DEL '\007' -#define STR_ESC "\047" -#define STR_DEL "\007" - -#else /* Not EBCDIC */ - -/* In ASCII/Unicode, linefeed is '\n' and we equate this to NL for -compatibility. NEL is the Unicode newline character; make sure it is -a positive value. */ - -#define CHAR_LF '\n' -#define CHAR_NL CHAR_LF -#define CHAR_NEL ((unsigned char)'\x85') -#define CHAR_ESC '\033' -#define CHAR_DEL '\177' - -#define STR_LF "\n" -#define STR_NL STR_LF -#define STR_NEL "\x85" -#define STR_ESC "\033" -#define STR_DEL "\177" - -#endif /* EBCDIC */ - -/* The remaining definitions work in both environments. */ - -#define CHAR_NULL '\0' -#define CHAR_HT '\t' -#define CHAR_VT '\v' -#define CHAR_FF '\f' -#define CHAR_CR '\r' -#define CHAR_BS '\b' -#define CHAR_BEL '\a' - -#define CHAR_SPACE ' ' -#define CHAR_EXCLAMATION_MARK '!' -#define CHAR_QUOTATION_MARK '"' -#define CHAR_NUMBER_SIGN '#' -#define CHAR_DOLLAR_SIGN '$' -#define CHAR_PERCENT_SIGN '%' -#define CHAR_AMPERSAND '&' -#define CHAR_APOSTROPHE '\'' -#define CHAR_LEFT_PARENTHESIS '(' -#define CHAR_RIGHT_PARENTHESIS ')' -#define CHAR_ASTERISK '*' -#define CHAR_PLUS '+' -#define CHAR_COMMA ',' -#define CHAR_MINUS '-' -#define CHAR_DOT '.' -#define CHAR_SLASH '/' -#define CHAR_0 '0' -#define CHAR_1 '1' -#define CHAR_2 '2' -#define CHAR_3 '3' -#define CHAR_4 '4' -#define CHAR_5 '5' -#define CHAR_6 '6' -#define CHAR_7 '7' -#define CHAR_8 '8' -#define CHAR_9 '9' -#define CHAR_COLON ':' -#define CHAR_SEMICOLON ';' -#define CHAR_LESS_THAN_SIGN '<' -#define CHAR_EQUALS_SIGN '=' -#define CHAR_GREATER_THAN_SIGN '>' -#define CHAR_QUESTION_MARK '?' -#define CHAR_COMMERCIAL_AT '@' -#define CHAR_A 'A' -#define CHAR_B 'B' -#define CHAR_C 'C' -#define CHAR_D 'D' -#define CHAR_E 'E' -#define CHAR_F 'F' -#define CHAR_G 'G' -#define CHAR_H 'H' -#define CHAR_I 'I' -#define CHAR_J 'J' -#define CHAR_K 'K' -#define CHAR_L 'L' -#define CHAR_M 'M' -#define CHAR_N 'N' -#define CHAR_O 'O' -#define CHAR_P 'P' -#define CHAR_Q 'Q' -#define CHAR_R 'R' -#define CHAR_S 'S' -#define CHAR_T 'T' -#define CHAR_U 'U' -#define CHAR_V 'V' -#define CHAR_W 'W' -#define CHAR_X 'X' -#define CHAR_Y 'Y' -#define CHAR_Z 'Z' -#define CHAR_LEFT_SQUARE_BRACKET '[' -#define CHAR_BACKSLASH '\\' -#define CHAR_RIGHT_SQUARE_BRACKET ']' -#define CHAR_CIRCUMFLEX_ACCENT '^' -#define CHAR_UNDERSCORE '_' -#define CHAR_GRAVE_ACCENT '`' -#define CHAR_a 'a' -#define CHAR_b 'b' -#define CHAR_c 'c' -#define CHAR_d 'd' -#define CHAR_e 'e' -#define CHAR_f 'f' -#define CHAR_g 'g' -#define CHAR_h 'h' -#define CHAR_i 'i' -#define CHAR_j 'j' -#define CHAR_k 'k' -#define CHAR_l 'l' -#define CHAR_m 'm' -#define CHAR_n 'n' -#define CHAR_o 'o' -#define CHAR_p 'p' -#define CHAR_q 'q' -#define CHAR_r 'r' -#define CHAR_s 's' -#define CHAR_t 't' -#define CHAR_u 'u' -#define CHAR_v 'v' -#define CHAR_w 'w' -#define CHAR_x 'x' -#define CHAR_y 'y' -#define CHAR_z 'z' -#define CHAR_LEFT_CURLY_BRACKET '{' -#define CHAR_VERTICAL_LINE '|' -#define CHAR_RIGHT_CURLY_BRACKET '}' -#define CHAR_TILDE '~' - -#define STR_HT "\t" -#define STR_VT "\v" -#define STR_FF "\f" -#define STR_CR "\r" -#define STR_BS "\b" -#define STR_BEL "\a" - -#define STR_SPACE " " -#define STR_EXCLAMATION_MARK "!" -#define STR_QUOTATION_MARK "\"" -#define STR_NUMBER_SIGN "#" -#define STR_DOLLAR_SIGN "$" -#define STR_PERCENT_SIGN "%" -#define STR_AMPERSAND "&" -#define STR_APOSTROPHE "'" -#define STR_LEFT_PARENTHESIS "(" -#define STR_RIGHT_PARENTHESIS ")" -#define STR_ASTERISK "*" -#define STR_PLUS "+" -#define STR_COMMA "," -#define STR_MINUS "-" -#define STR_DOT "." -#define STR_SLASH "/" -#define STR_0 "0" -#define STR_1 "1" -#define STR_2 "2" -#define STR_3 "3" -#define STR_4 "4" -#define STR_5 "5" -#define STR_6 "6" -#define STR_7 "7" -#define STR_8 "8" -#define STR_9 "9" -#define STR_COLON ":" -#define STR_SEMICOLON ";" -#define STR_LESS_THAN_SIGN "<" -#define STR_EQUALS_SIGN "=" -#define STR_GREATER_THAN_SIGN ">" -#define STR_QUESTION_MARK "?" -#define STR_COMMERCIAL_AT "@" -#define STR_A "A" -#define STR_B "B" -#define STR_C "C" -#define STR_D "D" -#define STR_E "E" -#define STR_F "F" -#define STR_G "G" -#define STR_H "H" -#define STR_I "I" -#define STR_J "J" -#define STR_K "K" -#define STR_L "L" -#define STR_M "M" -#define STR_N "N" -#define STR_O "O" -#define STR_P "P" -#define STR_Q "Q" -#define STR_R "R" -#define STR_S "S" -#define STR_T "T" -#define STR_U "U" -#define STR_V "V" -#define STR_W "W" -#define STR_X "X" -#define STR_Y "Y" -#define STR_Z "Z" -#define STR_LEFT_SQUARE_BRACKET "[" -#define STR_BACKSLASH "\\" -#define STR_RIGHT_SQUARE_BRACKET "]" -#define STR_CIRCUMFLEX_ACCENT "^" -#define STR_UNDERSCORE "_" -#define STR_GRAVE_ACCENT "`" -#define STR_a "a" -#define STR_b "b" -#define STR_c "c" -#define STR_d "d" -#define STR_e "e" -#define STR_f "f" -#define STR_g "g" -#define STR_h "h" -#define STR_i "i" -#define STR_j "j" -#define STR_k "k" -#define STR_l "l" -#define STR_m "m" -#define STR_n "n" -#define STR_o "o" -#define STR_p "p" -#define STR_q "q" -#define STR_r "r" -#define STR_s "s" -#define STR_t "t" -#define STR_u "u" -#define STR_v "v" -#define STR_w "w" -#define STR_x "x" -#define STR_y "y" -#define STR_z "z" -#define STR_LEFT_CURLY_BRACKET "{" -#define STR_VERTICAL_LINE "|" -#define STR_RIGHT_CURLY_BRACKET "}" -#define STR_TILDE "~" - -#define STRING_ACCEPT0 "ACCEPT\0" -#define STRING_COMMIT0 "COMMIT\0" -#define STRING_F0 "F\0" -#define STRING_FAIL0 "FAIL\0" -#define STRING_MARK0 "MARK\0" -#define STRING_PRUNE0 "PRUNE\0" -#define STRING_SKIP0 "SKIP\0" -#define STRING_THEN "THEN" - -#define STRING_alpha0 "alpha\0" -#define STRING_lower0 "lower\0" -#define STRING_upper0 "upper\0" -#define STRING_alnum0 "alnum\0" -#define STRING_ascii0 "ascii\0" -#define STRING_blank0 "blank\0" -#define STRING_cntrl0 "cntrl\0" -#define STRING_digit0 "digit\0" -#define STRING_graph0 "graph\0" -#define STRING_print0 "print\0" -#define STRING_punct0 "punct\0" -#define STRING_space0 "space\0" -#define STRING_word0 "word\0" -#define STRING_xdigit "xdigit" - -#define STRING_DEFINE "DEFINE" -#define STRING_WEIRD_STARTWORD "[:<:]]" -#define STRING_WEIRD_ENDWORD "[:>:]]" - -#define STRING_CR_RIGHTPAR "CR)" -#define STRING_LF_RIGHTPAR "LF)" -#define STRING_CRLF_RIGHTPAR "CRLF)" -#define STRING_ANY_RIGHTPAR "ANY)" -#define STRING_ANYCRLF_RIGHTPAR "ANYCRLF)" -#define STRING_BSR_ANYCRLF_RIGHTPAR "BSR_ANYCRLF)" -#define STRING_BSR_UNICODE_RIGHTPAR "BSR_UNICODE)" -#define STRING_UTF8_RIGHTPAR "UTF8)" -#define STRING_UTF16_RIGHTPAR "UTF16)" -#define STRING_UTF32_RIGHTPAR "UTF32)" -#define STRING_UTF_RIGHTPAR "UTF)" -#define STRING_UCP_RIGHTPAR "UCP)" -#define STRING_NO_AUTO_POSSESS_RIGHTPAR "NO_AUTO_POSSESS)" -#define STRING_NO_START_OPT_RIGHTPAR "NO_START_OPT)" -#define STRING_LIMIT_MATCH_EQ "LIMIT_MATCH=" -#define STRING_LIMIT_RECURSION_EQ "LIMIT_RECURSION=" - -#else /* SUPPORT_UTF */ - -/* UTF-8 support is enabled; always use UTF-8 (=ASCII) character codes. This -works in both modes non-EBCDIC platforms, and on EBCDIC platforms in UTF-8 mode -only. */ - -#define CHAR_HT '\011' -#define CHAR_VT '\013' -#define CHAR_FF '\014' -#define CHAR_CR '\015' -#define CHAR_LF '\012' -#define CHAR_NL CHAR_LF -#define CHAR_NEL ((unsigned char)'\x85') -#define CHAR_BS '\010' -#define CHAR_BEL '\007' -#define CHAR_ESC '\033' -#define CHAR_DEL '\177' - -#define CHAR_NULL '\0' -#define CHAR_SPACE '\040' -#define CHAR_EXCLAMATION_MARK '\041' -#define CHAR_QUOTATION_MARK '\042' -#define CHAR_NUMBER_SIGN '\043' -#define CHAR_DOLLAR_SIGN '\044' -#define CHAR_PERCENT_SIGN '\045' -#define CHAR_AMPERSAND '\046' -#define CHAR_APOSTROPHE '\047' -#define CHAR_LEFT_PARENTHESIS '\050' -#define CHAR_RIGHT_PARENTHESIS '\051' -#define CHAR_ASTERISK '\052' -#define CHAR_PLUS '\053' -#define CHAR_COMMA '\054' -#define CHAR_MINUS '\055' -#define CHAR_DOT '\056' -#define CHAR_SLASH '\057' -#define CHAR_0 '\060' -#define CHAR_1 '\061' -#define CHAR_2 '\062' -#define CHAR_3 '\063' -#define CHAR_4 '\064' -#define CHAR_5 '\065' -#define CHAR_6 '\066' -#define CHAR_7 '\067' -#define CHAR_8 '\070' -#define CHAR_9 '\071' -#define CHAR_COLON '\072' -#define CHAR_SEMICOLON '\073' -#define CHAR_LESS_THAN_SIGN '\074' -#define CHAR_EQUALS_SIGN '\075' -#define CHAR_GREATER_THAN_SIGN '\076' -#define CHAR_QUESTION_MARK '\077' -#define CHAR_COMMERCIAL_AT '\100' -#define CHAR_A '\101' -#define CHAR_B '\102' -#define CHAR_C '\103' -#define CHAR_D '\104' -#define CHAR_E '\105' -#define CHAR_F '\106' -#define CHAR_G '\107' -#define CHAR_H '\110' -#define CHAR_I '\111' -#define CHAR_J '\112' -#define CHAR_K '\113' -#define CHAR_L '\114' -#define CHAR_M '\115' -#define CHAR_N '\116' -#define CHAR_O '\117' -#define CHAR_P '\120' -#define CHAR_Q '\121' -#define CHAR_R '\122' -#define CHAR_S '\123' -#define CHAR_T '\124' -#define CHAR_U '\125' -#define CHAR_V '\126' -#define CHAR_W '\127' -#define CHAR_X '\130' -#define CHAR_Y '\131' -#define CHAR_Z '\132' -#define CHAR_LEFT_SQUARE_BRACKET '\133' -#define CHAR_BACKSLASH '\134' -#define CHAR_RIGHT_SQUARE_BRACKET '\135' -#define CHAR_CIRCUMFLEX_ACCENT '\136' -#define CHAR_UNDERSCORE '\137' -#define CHAR_GRAVE_ACCENT '\140' -#define CHAR_a '\141' -#define CHAR_b '\142' -#define CHAR_c '\143' -#define CHAR_d '\144' -#define CHAR_e '\145' -#define CHAR_f '\146' -#define CHAR_g '\147' -#define CHAR_h '\150' -#define CHAR_i '\151' -#define CHAR_j '\152' -#define CHAR_k '\153' -#define CHAR_l '\154' -#define CHAR_m '\155' -#define CHAR_n '\156' -#define CHAR_o '\157' -#define CHAR_p '\160' -#define CHAR_q '\161' -#define CHAR_r '\162' -#define CHAR_s '\163' -#define CHAR_t '\164' -#define CHAR_u '\165' -#define CHAR_v '\166' -#define CHAR_w '\167' -#define CHAR_x '\170' -#define CHAR_y '\171' -#define CHAR_z '\172' -#define CHAR_LEFT_CURLY_BRACKET '\173' -#define CHAR_VERTICAL_LINE '\174' -#define CHAR_RIGHT_CURLY_BRACKET '\175' -#define CHAR_TILDE '\176' - -#define STR_HT "\011" -#define STR_VT "\013" -#define STR_FF "\014" -#define STR_CR "\015" -#define STR_NL "\012" -#define STR_BS "\010" -#define STR_BEL "\007" -#define STR_ESC "\033" -#define STR_DEL "\177" - -#define STR_SPACE "\040" -#define STR_EXCLAMATION_MARK "\041" -#define STR_QUOTATION_MARK "\042" -#define STR_NUMBER_SIGN "\043" -#define STR_DOLLAR_SIGN "\044" -#define STR_PERCENT_SIGN "\045" -#define STR_AMPERSAND "\046" -#define STR_APOSTROPHE "\047" -#define STR_LEFT_PARENTHESIS "\050" -#define STR_RIGHT_PARENTHESIS "\051" -#define STR_ASTERISK "\052" -#define STR_PLUS "\053" -#define STR_COMMA "\054" -#define STR_MINUS "\055" -#define STR_DOT "\056" -#define STR_SLASH "\057" -#define STR_0 "\060" -#define STR_1 "\061" -#define STR_2 "\062" -#define STR_3 "\063" -#define STR_4 "\064" -#define STR_5 "\065" -#define STR_6 "\066" -#define STR_7 "\067" -#define STR_8 "\070" -#define STR_9 "\071" -#define STR_COLON "\072" -#define STR_SEMICOLON "\073" -#define STR_LESS_THAN_SIGN "\074" -#define STR_EQUALS_SIGN "\075" -#define STR_GREATER_THAN_SIGN "\076" -#define STR_QUESTION_MARK "\077" -#define STR_COMMERCIAL_AT "\100" -#define STR_A "\101" -#define STR_B "\102" -#define STR_C "\103" -#define STR_D "\104" -#define STR_E "\105" -#define STR_F "\106" -#define STR_G "\107" -#define STR_H "\110" -#define STR_I "\111" -#define STR_J "\112" -#define STR_K "\113" -#define STR_L "\114" -#define STR_M "\115" -#define STR_N "\116" -#define STR_O "\117" -#define STR_P "\120" -#define STR_Q "\121" -#define STR_R "\122" -#define STR_S "\123" -#define STR_T "\124" -#define STR_U "\125" -#define STR_V "\126" -#define STR_W "\127" -#define STR_X "\130" -#define STR_Y "\131" -#define STR_Z "\132" -#define STR_LEFT_SQUARE_BRACKET "\133" -#define STR_BACKSLASH "\134" -#define STR_RIGHT_SQUARE_BRACKET "\135" -#define STR_CIRCUMFLEX_ACCENT "\136" -#define STR_UNDERSCORE "\137" -#define STR_GRAVE_ACCENT "\140" -#define STR_a "\141" -#define STR_b "\142" -#define STR_c "\143" -#define STR_d "\144" -#define STR_e "\145" -#define STR_f "\146" -#define STR_g "\147" -#define STR_h "\150" -#define STR_i "\151" -#define STR_j "\152" -#define STR_k "\153" -#define STR_l "\154" -#define STR_m "\155" -#define STR_n "\156" -#define STR_o "\157" -#define STR_p "\160" -#define STR_q "\161" -#define STR_r "\162" -#define STR_s "\163" -#define STR_t "\164" -#define STR_u "\165" -#define STR_v "\166" -#define STR_w "\167" -#define STR_x "\170" -#define STR_y "\171" -#define STR_z "\172" -#define STR_LEFT_CURLY_BRACKET "\173" -#define STR_VERTICAL_LINE "\174" -#define STR_RIGHT_CURLY_BRACKET "\175" -#define STR_TILDE "\176" - -#define STRING_ACCEPT0 STR_A STR_C STR_C STR_E STR_P STR_T "\0" -#define STRING_COMMIT0 STR_C STR_O STR_M STR_M STR_I STR_T "\0" -#define STRING_F0 STR_F "\0" -#define STRING_FAIL0 STR_F STR_A STR_I STR_L "\0" -#define STRING_MARK0 STR_M STR_A STR_R STR_K "\0" -#define STRING_PRUNE0 STR_P STR_R STR_U STR_N STR_E "\0" -#define STRING_SKIP0 STR_S STR_K STR_I STR_P "\0" -#define STRING_THEN STR_T STR_H STR_E STR_N - -#define STRING_alpha0 STR_a STR_l STR_p STR_h STR_a "\0" -#define STRING_lower0 STR_l STR_o STR_w STR_e STR_r "\0" -#define STRING_upper0 STR_u STR_p STR_p STR_e STR_r "\0" -#define STRING_alnum0 STR_a STR_l STR_n STR_u STR_m "\0" -#define STRING_ascii0 STR_a STR_s STR_c STR_i STR_i "\0" -#define STRING_blank0 STR_b STR_l STR_a STR_n STR_k "\0" -#define STRING_cntrl0 STR_c STR_n STR_t STR_r STR_l "\0" -#define STRING_digit0 STR_d STR_i STR_g STR_i STR_t "\0" -#define STRING_graph0 STR_g STR_r STR_a STR_p STR_h "\0" -#define STRING_print0 STR_p STR_r STR_i STR_n STR_t "\0" -#define STRING_punct0 STR_p STR_u STR_n STR_c STR_t "\0" -#define STRING_space0 STR_s STR_p STR_a STR_c STR_e "\0" -#define STRING_word0 STR_w STR_o STR_r STR_d "\0" -#define STRING_xdigit STR_x STR_d STR_i STR_g STR_i STR_t - -#define STRING_DEFINE STR_D STR_E STR_F STR_I STR_N STR_E -#define STRING_WEIRD_STARTWORD STR_LEFT_SQUARE_BRACKET STR_COLON STR_LESS_THAN_SIGN STR_COLON STR_RIGHT_SQUARE_BRACKET STR_RIGHT_SQUARE_BRACKET -#define STRING_WEIRD_ENDWORD STR_LEFT_SQUARE_BRACKET STR_COLON STR_GREATER_THAN_SIGN STR_COLON STR_RIGHT_SQUARE_BRACKET STR_RIGHT_SQUARE_BRACKET - -#define STRING_CR_RIGHTPAR STR_C STR_R STR_RIGHT_PARENTHESIS -#define STRING_LF_RIGHTPAR STR_L STR_F STR_RIGHT_PARENTHESIS -#define STRING_CRLF_RIGHTPAR STR_C STR_R STR_L STR_F STR_RIGHT_PARENTHESIS -#define STRING_ANY_RIGHTPAR STR_A STR_N STR_Y STR_RIGHT_PARENTHESIS -#define STRING_ANYCRLF_RIGHTPAR STR_A STR_N STR_Y STR_C STR_R STR_L STR_F STR_RIGHT_PARENTHESIS -#define STRING_BSR_ANYCRLF_RIGHTPAR STR_B STR_S STR_R STR_UNDERSCORE STR_A STR_N STR_Y STR_C STR_R STR_L STR_F STR_RIGHT_PARENTHESIS -#define STRING_BSR_UNICODE_RIGHTPAR STR_B STR_S STR_R STR_UNDERSCORE STR_U STR_N STR_I STR_C STR_O STR_D STR_E STR_RIGHT_PARENTHESIS -#define STRING_UTF8_RIGHTPAR STR_U STR_T STR_F STR_8 STR_RIGHT_PARENTHESIS -#define STRING_UTF16_RIGHTPAR STR_U STR_T STR_F STR_1 STR_6 STR_RIGHT_PARENTHESIS -#define STRING_UTF32_RIGHTPAR STR_U STR_T STR_F STR_3 STR_2 STR_RIGHT_PARENTHESIS -#define STRING_UTF_RIGHTPAR STR_U STR_T STR_F STR_RIGHT_PARENTHESIS -#define STRING_UCP_RIGHTPAR STR_U STR_C STR_P STR_RIGHT_PARENTHESIS -#define STRING_NO_AUTO_POSSESS_RIGHTPAR STR_N STR_O STR_UNDERSCORE STR_A STR_U STR_T STR_O STR_UNDERSCORE STR_P STR_O STR_S STR_S STR_E STR_S STR_S STR_RIGHT_PARENTHESIS -#define STRING_NO_START_OPT_RIGHTPAR STR_N STR_O STR_UNDERSCORE STR_S STR_T STR_A STR_R STR_T STR_UNDERSCORE STR_O STR_P STR_T STR_RIGHT_PARENTHESIS -#define STRING_LIMIT_MATCH_EQ STR_L STR_I STR_M STR_I STR_T STR_UNDERSCORE STR_M STR_A STR_T STR_C STR_H STR_EQUALS_SIGN -#define STRING_LIMIT_RECURSION_EQ STR_L STR_I STR_M STR_I STR_T STR_UNDERSCORE STR_R STR_E STR_C STR_U STR_R STR_S STR_I STR_O STR_N STR_EQUALS_SIGN - -#endif /* SUPPORT_UTF */ - -/* Escape items that are just an encoding of a particular data value. */ - -#ifndef ESC_e -#define ESC_e CHAR_ESC -#endif - -#ifndef ESC_f -#define ESC_f CHAR_FF -#endif - -#ifndef ESC_n -#define ESC_n CHAR_LF -#endif - -#ifndef ESC_r -#define ESC_r CHAR_CR -#endif - -/* We can't officially use ESC_t because it is a POSIX reserved identifier -(presumably because of all the others like size_t). */ - -#ifndef ESC_tee -#define ESC_tee CHAR_HT -#endif - -/* Codes for different types of Unicode property */ - -#define PT_ANY 0 /* Any property - matches all chars */ -#define PT_LAMP 1 /* L& - the union of Lu, Ll, Lt */ -#define PT_GC 2 /* Specified general characteristic (e.g. L) */ -#define PT_PC 3 /* Specified particular characteristic (e.g. Lu) */ -#define PT_SC 4 /* Script (e.g. Han) */ -#define PT_ALNUM 5 /* Alphanumeric - the union of L and N */ -#define PT_SPACE 6 /* Perl space - Z plus 9,10,12,13 */ -#define PT_PXSPACE 7 /* POSIX space - Z plus 9,10,11,12,13 */ -#define PT_WORD 8 /* Word - L plus N plus underscore */ -#define PT_CLIST 9 /* Pseudo-property: match character list */ -#define PT_UCNC 10 /* Universal Character nameable character */ -#define PT_TABSIZE 11 /* Size of square table for autopossessify tests */ - -/* The following special properties are used only in XCLASS items, when POSIX -classes are specified and PCRE_UCP is set - in other words, for Unicode -handling of these classes. They are not available via the \p or \P escapes like -those in the above list, and so they do not take part in the autopossessifying -table. */ - -#define PT_PXGRAPH 11 /* [:graph:] - characters that mark the paper */ -#define PT_PXPRINT 12 /* [:print:] - [:graph:] plus non-control spaces */ -#define PT_PXPUNCT 13 /* [:punct:] - punctuation characters */ - -/* Flag bits and data types for the extended class (OP_XCLASS) for classes that -contain characters with values greater than 255. */ - -#define XCL_NOT 0x01 /* Flag: this is a negative class */ -#define XCL_MAP 0x02 /* Flag: a 32-byte map is present */ -#define XCL_HASPROP 0x04 /* Flag: property checks are present. */ - -#define XCL_END 0 /* Marks end of individual items */ -#define XCL_SINGLE 1 /* Single item (one multibyte char) follows */ -#define XCL_RANGE 2 /* A range (two multibyte chars) follows */ -#define XCL_PROP 3 /* Unicode property (2-byte property code follows) */ -#define XCL_NOTPROP 4 /* Unicode inverted property (ditto) */ - -/* These are escaped items that aren't just an encoding of a particular data -value such as \n. They must have non-zero values, as check_escape() returns 0 -for a data character. Also, they must appear in the same order as in the -opcode definitions below, up to ESC_z. There's a dummy for OP_ALLANY because it -corresponds to "." in DOTALL mode rather than an escape sequence. It is also -used for [^] in JavaScript compatibility mode, and for \C in non-utf mode. In -non-DOTALL mode, "." behaves like \N. - -The special values ESC_DU, ESC_du, etc. are used instead of ESC_D, ESC_d, etc. -when PCRE_UCP is set and replacement of \d etc by \p sequences is required. -They must be contiguous, and remain in order so that the replacements can be -looked up from a table. - -Negative numbers are used to encode a backreference (\1, \2, \3, etc.) in -check_escape(). There are two tests in the code for an escape -greater than ESC_b and less than ESC_Z to detect the types that may be -repeated. These are the types that consume characters. If any new escapes are -put in between that don't consume a character, that code will have to change. -*/ - -enum { ESC_A = 1, ESC_G, ESC_K, ESC_B, ESC_b, ESC_D, ESC_d, ESC_S, ESC_s, - ESC_W, ESC_w, ESC_N, ESC_dum, ESC_C, ESC_P, ESC_p, ESC_R, ESC_H, - ESC_h, ESC_V, ESC_v, ESC_X, ESC_Z, ESC_z, - ESC_E, ESC_Q, ESC_g, ESC_k, - ESC_DU, ESC_du, ESC_SU, ESC_su, ESC_WU, ESC_wu }; - - -/********************** Opcode definitions ******************/ - -/****** NOTE NOTE NOTE ****** - -Starting from 1 (i.e. after OP_END), the values up to OP_EOD must correspond in -order to the list of escapes immediately above. Furthermore, values up to -OP_DOLLM must not be changed without adjusting the table called autoposstab in -pcre_compile.c - -Whenever this list is updated, the two macro definitions that follow must be -updated to match. The possessification table called "opcode_possessify" in -pcre_compile.c must also be updated, and also the tables called "coptable" -and "poptable" in pcre_dfa_exec.c. - -****** NOTE NOTE NOTE ******/ - - -/* The values between FIRST_AUTOTAB_OP and LAST_AUTOTAB_RIGHT_OP, inclusive, -are used in a table for deciding whether a repeated character type can be -auto-possessified. */ - -#define FIRST_AUTOTAB_OP OP_NOT_DIGIT -#define LAST_AUTOTAB_LEFT_OP OP_EXTUNI -#define LAST_AUTOTAB_RIGHT_OP OP_DOLLM - -enum { - OP_END, /* 0 End of pattern */ - - /* Values corresponding to backslashed metacharacters */ - - OP_SOD, /* 1 Start of data: \A */ - OP_SOM, /* 2 Start of match (subject + offset): \G */ - OP_SET_SOM, /* 3 Set start of match (\K) */ - OP_NOT_WORD_BOUNDARY, /* 4 \B */ - OP_WORD_BOUNDARY, /* 5 \b */ - OP_NOT_DIGIT, /* 6 \D */ - OP_DIGIT, /* 7 \d */ - OP_NOT_WHITESPACE, /* 8 \S */ - OP_WHITESPACE, /* 9 \s */ - OP_NOT_WORDCHAR, /* 10 \W */ - OP_WORDCHAR, /* 11 \w */ - - OP_ANY, /* 12 Match any character except newline (\N) */ - OP_ALLANY, /* 13 Match any character */ - OP_ANYBYTE, /* 14 Match any byte (\C); different to OP_ANY for UTF-8 */ - OP_NOTPROP, /* 15 \P (not Unicode property) */ - OP_PROP, /* 16 \p (Unicode property) */ - OP_ANYNL, /* 17 \R (any newline sequence) */ - OP_NOT_HSPACE, /* 18 \H (not horizontal whitespace) */ - OP_HSPACE, /* 19 \h (horizontal whitespace) */ - OP_NOT_VSPACE, /* 20 \V (not vertical whitespace) */ - OP_VSPACE, /* 21 \v (vertical whitespace) */ - OP_EXTUNI, /* 22 \X (extended Unicode sequence */ - OP_EODN, /* 23 End of data or \n at end of data (\Z) */ - OP_EOD, /* 24 End of data (\z) */ - - /* Line end assertions */ - - OP_DOLL, /* 25 End of line - not multiline */ - OP_DOLLM, /* 26 End of line - multiline */ - OP_CIRC, /* 27 Start of line - not multiline */ - OP_CIRCM, /* 28 Start of line - multiline */ - - /* Single characters; caseful must precede the caseless ones */ - - OP_CHAR, /* 29 Match one character, casefully */ - OP_CHARI, /* 30 Match one character, caselessly */ - OP_NOT, /* 31 Match one character, not the given one, casefully */ - OP_NOTI, /* 32 Match one character, not the given one, caselessly */ - - /* The following sets of 13 opcodes must always be kept in step because - the offset from the first one is used to generate the others. */ - - /* Repeated characters; caseful must precede the caseless ones */ - - OP_STAR, /* 33 The maximizing and minimizing versions of */ - OP_MINSTAR, /* 34 these six opcodes must come in pairs, with */ - OP_PLUS, /* 35 the minimizing one second. */ - OP_MINPLUS, /* 36 */ - OP_QUERY, /* 37 */ - OP_MINQUERY, /* 38 */ - - OP_UPTO, /* 39 From 0 to n matches of one character, caseful*/ - OP_MINUPTO, /* 40 */ - OP_EXACT, /* 41 Exactly n matches */ - - OP_POSSTAR, /* 42 Possessified star, caseful */ - OP_POSPLUS, /* 43 Possessified plus, caseful */ - OP_POSQUERY, /* 44 Posesssified query, caseful */ - OP_POSUPTO, /* 45 Possessified upto, caseful */ - - /* Repeated characters; caseless must follow the caseful ones */ - - OP_STARI, /* 46 */ - OP_MINSTARI, /* 47 */ - OP_PLUSI, /* 48 */ - OP_MINPLUSI, /* 49 */ - OP_QUERYI, /* 50 */ - OP_MINQUERYI, /* 51 */ - - OP_UPTOI, /* 52 From 0 to n matches of one character, caseless */ - OP_MINUPTOI, /* 53 */ - OP_EXACTI, /* 54 */ - - OP_POSSTARI, /* 55 Possessified star, caseless */ - OP_POSPLUSI, /* 56 Possessified plus, caseless */ - OP_POSQUERYI, /* 57 Posesssified query, caseless */ - OP_POSUPTOI, /* 58 Possessified upto, caseless */ - - /* The negated ones must follow the non-negated ones, and match them */ - /* Negated repeated character, caseful; must precede the caseless ones */ - - OP_NOTSTAR, /* 59 The maximizing and minimizing versions of */ - OP_NOTMINSTAR, /* 60 these six opcodes must come in pairs, with */ - OP_NOTPLUS, /* 61 the minimizing one second. They must be in */ - OP_NOTMINPLUS, /* 62 exactly the same order as those above. */ - OP_NOTQUERY, /* 63 */ - OP_NOTMINQUERY, /* 64 */ - - OP_NOTUPTO, /* 65 From 0 to n matches, caseful */ - OP_NOTMINUPTO, /* 66 */ - OP_NOTEXACT, /* 67 Exactly n matches */ - - OP_NOTPOSSTAR, /* 68 Possessified versions, caseful */ - OP_NOTPOSPLUS, /* 69 */ - OP_NOTPOSQUERY, /* 70 */ - OP_NOTPOSUPTO, /* 71 */ - - /* Negated repeated character, caseless; must follow the caseful ones */ - - OP_NOTSTARI, /* 72 */ - OP_NOTMINSTARI, /* 73 */ - OP_NOTPLUSI, /* 74 */ - OP_NOTMINPLUSI, /* 75 */ - OP_NOTQUERYI, /* 76 */ - OP_NOTMINQUERYI, /* 77 */ - - OP_NOTUPTOI, /* 78 From 0 to n matches, caseless */ - OP_NOTMINUPTOI, /* 79 */ - OP_NOTEXACTI, /* 80 Exactly n matches */ - - OP_NOTPOSSTARI, /* 81 Possessified versions, caseless */ - OP_NOTPOSPLUSI, /* 82 */ - OP_NOTPOSQUERYI, /* 83 */ - OP_NOTPOSUPTOI, /* 84 */ - - /* Character types */ - - OP_TYPESTAR, /* 85 The maximizing and minimizing versions of */ - OP_TYPEMINSTAR, /* 86 these six opcodes must come in pairs, with */ - OP_TYPEPLUS, /* 87 the minimizing one second. These codes must */ - OP_TYPEMINPLUS, /* 88 be in exactly the same order as those above. */ - OP_TYPEQUERY, /* 89 */ - OP_TYPEMINQUERY, /* 90 */ - - OP_TYPEUPTO, /* 91 From 0 to n matches */ - OP_TYPEMINUPTO, /* 92 */ - OP_TYPEEXACT, /* 93 Exactly n matches */ - - OP_TYPEPOSSTAR, /* 94 Possessified versions */ - OP_TYPEPOSPLUS, /* 95 */ - OP_TYPEPOSQUERY, /* 96 */ - OP_TYPEPOSUPTO, /* 97 */ - - /* These are used for character classes and back references; only the - first six are the same as the sets above. */ - - OP_CRSTAR, /* 98 The maximizing and minimizing versions of */ - OP_CRMINSTAR, /* 99 all these opcodes must come in pairs, with */ - OP_CRPLUS, /* 100 the minimizing one second. These codes must */ - OP_CRMINPLUS, /* 101 be in exactly the same order as those above. */ - OP_CRQUERY, /* 102 */ - OP_CRMINQUERY, /* 103 */ - - OP_CRRANGE, /* 104 These are different to the three sets above. */ - OP_CRMINRANGE, /* 105 */ - - OP_CRPOSSTAR, /* 106 Possessified versions */ - OP_CRPOSPLUS, /* 107 */ - OP_CRPOSQUERY, /* 108 */ - OP_CRPOSRANGE, /* 109 */ - - /* End of quantifier opcodes */ - - OP_CLASS, /* 110 Match a character class, chars < 256 only */ - OP_NCLASS, /* 111 Same, but the bitmap was created from a negative - class - the difference is relevant only when a - character > 255 is encountered. */ - OP_XCLASS, /* 112 Extended class for handling > 255 chars within the - class. This does both positive and negative. */ - OP_REF, /* 113 Match a back reference, casefully */ - OP_REFI, /* 114 Match a back reference, caselessly */ - OP_DNREF, /* 115 Match a duplicate name backref, casefully */ - OP_DNREFI, /* 116 Match a duplicate name backref, caselessly */ - OP_RECURSE, /* 117 Match a numbered subpattern (possibly recursive) */ - OP_CALLOUT, /* 118 Call out to external function if provided */ - - OP_ALT, /* 119 Start of alternation */ - OP_KET, /* 120 End of group that doesn't have an unbounded repeat */ - OP_KETRMAX, /* 121 These two must remain together and in this */ - OP_KETRMIN, /* 122 order. They are for groups the repeat for ever. */ - OP_KETRPOS, /* 123 Possessive unlimited repeat. */ - - /* The assertions must come before BRA, CBRA, ONCE, and COND, and the four - asserts must remain in order. */ - - OP_REVERSE, /* 124 Move pointer back - used in lookbehind assertions */ - OP_ASSERT, /* 125 Positive lookahead */ - OP_ASSERT_NOT, /* 126 Negative lookahead */ - OP_ASSERTBACK, /* 127 Positive lookbehind */ - OP_ASSERTBACK_NOT, /* 128 Negative lookbehind */ - - /* ONCE, ONCE_NC, BRA, BRAPOS, CBRA, CBRAPOS, and COND must come immediately - after the assertions, with ONCE first, as there's a test for >= ONCE for a - subpattern that isn't an assertion. The POS versions must immediately follow - the non-POS versions in each case. */ - - OP_ONCE, /* 129 Atomic group, contains captures */ - OP_ONCE_NC, /* 130 Atomic group containing no captures */ - OP_BRA, /* 131 Start of non-capturing bracket */ - OP_BRAPOS, /* 132 Ditto, with unlimited, possessive repeat */ - OP_CBRA, /* 133 Start of capturing bracket */ - OP_CBRAPOS, /* 134 Ditto, with unlimited, possessive repeat */ - OP_COND, /* 135 Conditional group */ - - /* These five must follow the previous five, in the same order. There's a - check for >= SBRA to distinguish the two sets. */ - - OP_SBRA, /* 136 Start of non-capturing bracket, check empty */ - OP_SBRAPOS, /* 137 Ditto, with unlimited, possessive repeat */ - OP_SCBRA, /* 138 Start of capturing bracket, check empty */ - OP_SCBRAPOS, /* 139 Ditto, with unlimited, possessive repeat */ - OP_SCOND, /* 140 Conditional group, check empty */ - - /* The next two pairs must (respectively) be kept together. */ - - OP_CREF, /* 141 Used to hold a capture number as condition */ - OP_DNCREF, /* 142 Used to point to duplicate names as a condition */ - OP_RREF, /* 143 Used to hold a recursion number as condition */ - OP_DNRREF, /* 144 Used to point to duplicate names as a condition */ - OP_DEF, /* 145 The DEFINE condition */ - - OP_BRAZERO, /* 146 These two must remain together and in this */ - OP_BRAMINZERO, /* 147 order. */ - OP_BRAPOSZERO, /* 148 */ - - /* These are backtracking control verbs */ - - OP_MARK, /* 149 always has an argument */ - OP_PRUNE, /* 150 */ - OP_PRUNE_ARG, /* 151 same, but with argument */ - OP_SKIP, /* 152 */ - OP_SKIP_ARG, /* 153 same, but with argument */ - OP_THEN, /* 154 */ - OP_THEN_ARG, /* 155 same, but with argument */ - OP_COMMIT, /* 156 */ - - /* These are forced failure and success verbs */ - - OP_FAIL, /* 157 */ - OP_ACCEPT, /* 158 */ - OP_ASSERT_ACCEPT, /* 159 Used inside assertions */ - OP_CLOSE, /* 160 Used before OP_ACCEPT to close open captures */ - - /* This is used to skip a subpattern with a {0} quantifier */ - - OP_SKIPZERO, /* 161 */ - - /* This is not an opcode, but is used to check that tables indexed by opcode - are the correct length, in order to catch updating errors - there have been - some in the past. */ - - OP_TABLE_LENGTH -}; - -/* *** NOTE NOTE NOTE *** Whenever the list above is updated, the two macro -definitions that follow must also be updated to match. There are also tables -called "opcode_possessify" in pcre_compile.c and "coptable" and "poptable" in -pcre_dfa_exec.c that must be updated. */ - - -/* This macro defines textual names for all the opcodes. These are used only -for debugging, and some of them are only partial names. The macro is referenced -only in pcre_printint.c, which fills out the full names in many cases (and in -some cases doesn't actually use these names at all). */ - -#define OP_NAME_LIST \ - "End", "\\A", "\\G", "\\K", "\\B", "\\b", "\\D", "\\d", \ - "\\S", "\\s", "\\W", "\\w", "Any", "AllAny", "Anybyte", \ - "notprop", "prop", "\\R", "\\H", "\\h", "\\V", "\\v", \ - "extuni", "\\Z", "\\z", \ - "$", "$", "^", "^", "char", "chari", "not", "noti", \ - "*", "*?", "+", "+?", "?", "??", \ - "{", "{", "{", \ - "*+","++", "?+", "{", \ - "*", "*?", "+", "+?", "?", "??", \ - "{", "{", "{", \ - "*+","++", "?+", "{", \ - "*", "*?", "+", "+?", "?", "??", \ - "{", "{", "{", \ - "*+","++", "?+", "{", \ - "*", "*?", "+", "+?", "?", "??", \ - "{", "{", "{", \ - "*+","++", "?+", "{", \ - "*", "*?", "+", "+?", "?", "??", "{", "{", "{", \ - "*+","++", "?+", "{", \ - "*", "*?", "+", "+?", "?", "??", "{", "{", \ - "*+","++", "?+", "{", \ - "class", "nclass", "xclass", "Ref", "Refi", "DnRef", "DnRefi", \ - "Recurse", "Callout", \ - "Alt", "Ket", "KetRmax", "KetRmin", "KetRpos", \ - "Reverse", "Assert", "Assert not", "AssertB", "AssertB not", \ - "Once", "Once_NC", \ - "Bra", "BraPos", "CBra", "CBraPos", \ - "Cond", \ - "SBra", "SBraPos", "SCBra", "SCBraPos", \ - "SCond", \ - "Cond ref", "Cond dnref", "Cond rec", "Cond dnrec", "Cond def", \ - "Brazero", "Braminzero", "Braposzero", \ - "*MARK", "*PRUNE", "*PRUNE", "*SKIP", "*SKIP", \ - "*THEN", "*THEN", "*COMMIT", "*FAIL", \ - "*ACCEPT", "*ASSERT_ACCEPT", \ - "Close", "Skip zero" - - -/* This macro defines the length of fixed length operations in the compiled -regex. The lengths are used when searching for specific things, and also in the -debugging printing of a compiled regex. We use a macro so that it can be -defined close to the definitions of the opcodes themselves. - -As things have been extended, some of these are no longer fixed lenths, but are -minima instead. For example, the length of a single-character repeat may vary -in UTF-8 mode. The code that uses this table must know about such things. */ - -#define OP_LENGTHS \ - 1, /* End */ \ - 1, 1, 1, 1, 1, /* \A, \G, \K, \B, \b */ \ - 1, 1, 1, 1, 1, 1, /* \D, \d, \S, \s, \W, \w */ \ - 1, 1, 1, /* Any, AllAny, Anybyte */ \ - 3, 3, /* \P, \p */ \ - 1, 1, 1, 1, 1, /* \R, \H, \h, \V, \v */ \ - 1, /* \X */ \ - 1, 1, 1, 1, 1, 1, /* \Z, \z, $, $M ^, ^M */ \ - 2, /* Char - the minimum length */ \ - 2, /* Chari - the minimum length */ \ - 2, /* not */ \ - 2, /* noti */ \ - /* Positive single-char repeats ** These are */ \ - 2, 2, 2, 2, 2, 2, /* *, *?, +, +?, ?, ?? ** minima in */ \ - 2+IMM2_SIZE, 2+IMM2_SIZE, /* upto, minupto ** mode */ \ - 2+IMM2_SIZE, /* exact */ \ - 2, 2, 2, 2+IMM2_SIZE, /* *+, ++, ?+, upto+ */ \ - 2, 2, 2, 2, 2, 2, /* *I, *?I, +I, +?I, ?I, ??I ** UTF-8 */ \ - 2+IMM2_SIZE, 2+IMM2_SIZE, /* upto I, minupto I */ \ - 2+IMM2_SIZE, /* exact I */ \ - 2, 2, 2, 2+IMM2_SIZE, /* *+I, ++I, ?+I, upto+I */ \ - /* Negative single-char repeats - only for chars < 256 */ \ - 2, 2, 2, 2, 2, 2, /* NOT *, *?, +, +?, ?, ?? */ \ - 2+IMM2_SIZE, 2+IMM2_SIZE, /* NOT upto, minupto */ \ - 2+IMM2_SIZE, /* NOT exact */ \ - 2, 2, 2, 2+IMM2_SIZE, /* Possessive NOT *, +, ?, upto */ \ - 2, 2, 2, 2, 2, 2, /* NOT *I, *?I, +I, +?I, ?I, ??I */ \ - 2+IMM2_SIZE, 2+IMM2_SIZE, /* NOT upto I, minupto I */ \ - 2+IMM2_SIZE, /* NOT exact I */ \ - 2, 2, 2, 2+IMM2_SIZE, /* Possessive NOT *I, +I, ?I, upto I */ \ - /* Positive type repeats */ \ - 2, 2, 2, 2, 2, 2, /* Type *, *?, +, +?, ?, ?? */ \ - 2+IMM2_SIZE, 2+IMM2_SIZE, /* Type upto, minupto */ \ - 2+IMM2_SIZE, /* Type exact */ \ - 2, 2, 2, 2+IMM2_SIZE, /* Possessive *+, ++, ?+, upto+ */ \ - /* Character class & ref repeats */ \ - 1, 1, 1, 1, 1, 1, /* *, *?, +, +?, ?, ?? */ \ - 1+2*IMM2_SIZE, 1+2*IMM2_SIZE, /* CRRANGE, CRMINRANGE */ \ - 1, 1, 1, 1+2*IMM2_SIZE, /* Possessive *+, ++, ?+, CRPOSRANGE */ \ - 1+(32/sizeof(pcre_uchar)), /* CLASS */ \ - 1+(32/sizeof(pcre_uchar)), /* NCLASS */ \ - 0, /* XCLASS - variable length */ \ - 1+IMM2_SIZE, /* REF */ \ - 1+IMM2_SIZE, /* REFI */ \ - 1+2*IMM2_SIZE, /* DNREF */ \ - 1+2*IMM2_SIZE, /* DNREFI */ \ - 1+LINK_SIZE, /* RECURSE */ \ - 2+2*LINK_SIZE, /* CALLOUT */ \ - 1+LINK_SIZE, /* Alt */ \ - 1+LINK_SIZE, /* Ket */ \ - 1+LINK_SIZE, /* KetRmax */ \ - 1+LINK_SIZE, /* KetRmin */ \ - 1+LINK_SIZE, /* KetRpos */ \ - 1+LINK_SIZE, /* Reverse */ \ - 1+LINK_SIZE, /* Assert */ \ - 1+LINK_SIZE, /* Assert not */ \ - 1+LINK_SIZE, /* Assert behind */ \ - 1+LINK_SIZE, /* Assert behind not */ \ - 1+LINK_SIZE, /* ONCE */ \ - 1+LINK_SIZE, /* ONCE_NC */ \ - 1+LINK_SIZE, /* BRA */ \ - 1+LINK_SIZE, /* BRAPOS */ \ - 1+LINK_SIZE+IMM2_SIZE, /* CBRA */ \ - 1+LINK_SIZE+IMM2_SIZE, /* CBRAPOS */ \ - 1+LINK_SIZE, /* COND */ \ - 1+LINK_SIZE, /* SBRA */ \ - 1+LINK_SIZE, /* SBRAPOS */ \ - 1+LINK_SIZE+IMM2_SIZE, /* SCBRA */ \ - 1+LINK_SIZE+IMM2_SIZE, /* SCBRAPOS */ \ - 1+LINK_SIZE, /* SCOND */ \ - 1+IMM2_SIZE, 1+2*IMM2_SIZE, /* CREF, DNCREF */ \ - 1+IMM2_SIZE, 1+2*IMM2_SIZE, /* RREF, DNRREF */ \ - 1, /* DEF */ \ - 1, 1, 1, /* BRAZERO, BRAMINZERO, BRAPOSZERO */ \ - 3, 1, 3, /* MARK, PRUNE, PRUNE_ARG */ \ - 1, 3, /* SKIP, SKIP_ARG */ \ - 1, 3, /* THEN, THEN_ARG */ \ - 1, 1, 1, 1, /* COMMIT, FAIL, ACCEPT, ASSERT_ACCEPT */ \ - 1+IMM2_SIZE, 1 /* CLOSE, SKIPZERO */ - -/* A magic value for OP_RREF to indicate the "any recursion" condition. */ - -#define RREF_ANY 0xffff - -/* Compile time error code numbers. They are given names so that they can more -easily be tracked. When a new number is added, the table called eint in -pcreposix.c must be updated. */ - -enum { ERR0, ERR1, ERR2, ERR3, ERR4, ERR5, ERR6, ERR7, ERR8, ERR9, - ERR10, ERR11, ERR12, ERR13, ERR14, ERR15, ERR16, ERR17, ERR18, ERR19, - ERR20, ERR21, ERR22, ERR23, ERR24, ERR25, ERR26, ERR27, ERR28, ERR29, - ERR30, ERR31, ERR32, ERR33, ERR34, ERR35, ERR36, ERR37, ERR38, ERR39, - ERR40, ERR41, ERR42, ERR43, ERR44, ERR45, ERR46, ERR47, ERR48, ERR49, - ERR50, ERR51, ERR52, ERR53, ERR54, ERR55, ERR56, ERR57, ERR58, ERR59, - ERR60, ERR61, ERR62, ERR63, ERR64, ERR65, ERR66, ERR67, ERR68, ERR69, - ERR70, ERR71, ERR72, ERR73, ERR74, ERR75, ERR76, ERR77, ERR78, ERR79, - ERR80, ERR81, ERR82, ERR83, ERR84, ERR85, ERR86, ERRCOUNT }; - -/* JIT compiling modes. The function list is indexed by them. */ - -enum { JIT_COMPILE, JIT_PARTIAL_SOFT_COMPILE, JIT_PARTIAL_HARD_COMPILE, - JIT_NUMBER_OF_COMPILE_MODES }; - -/* The real format of the start of the pcre block; the index of names and the -code vector run on as long as necessary after the end. We store an explicit -offset to the name table so that if a regex is compiled on one host, saved, and -then run on another where the size of pointers is different, all might still -be well. - -The size of the structure must be a multiple of 8 bytes. For the case of -compiled-on-4 and run-on-8, we include an extra pointer that is always NULL so -that there are an even number of pointers which therefore are a multiple of 8 -bytes. - -It is necessary to fork the struct for the 32 bit library, since it needs to -use pcre_uint32 for first_char and req_char. We can't put an ifdef inside the -typedef because pcretest needs access to the struct of the 8-, 16- and 32-bit -variants. - -*** WARNING *** -When new fields are added to these structures, remember to adjust the code in -pcre_byte_order.c that is concerned with swapping the byte order of the fields -when a compiled regex is reloaded on a host with different endianness. -*** WARNING *** -There is also similar byte-flipping code in pcretest.c, which is used for -testing the byte-flipping features. It must also be kept in step. -*** WARNING *** -*/ - -typedef struct real_pcre8_or_16 { - pcre_uint32 magic_number; - pcre_uint32 size; /* Total that was malloced */ - pcre_uint32 options; /* Public options */ - pcre_uint32 flags; /* Private flags */ - pcre_uint32 limit_match; /* Limit set from regex */ - pcre_uint32 limit_recursion; /* Limit set from regex */ - pcre_uint16 first_char; /* Starting character */ - pcre_uint16 req_char; /* This character must be seen */ - pcre_uint16 max_lookbehind; /* Longest lookbehind (characters) */ - pcre_uint16 top_bracket; /* Highest numbered group */ - pcre_uint16 top_backref; /* Highest numbered back reference */ - pcre_uint16 name_table_offset; /* Offset to name table that follows */ - pcre_uint16 name_entry_size; /* Size of any name items */ - pcre_uint16 name_count; /* Number of name items */ - pcre_uint16 ref_count; /* Reference count */ - pcre_uint16 dummy1; /* To ensure size is a multiple of 8 */ - pcre_uint16 dummy2; /* To ensure size is a multiple of 8 */ - pcre_uint16 dummy3; /* To ensure size is a multiple of 8 */ - const pcre_uint8 *tables; /* Pointer to tables or NULL for std */ - void *nullpad; /* NULL padding */ -} real_pcre8_or_16; - -typedef struct real_pcre8_or_16 real_pcre; -typedef struct real_pcre8_or_16 real_pcre16; - -typedef struct real_pcre32 { - pcre_uint32 magic_number; - pcre_uint32 size; /* Total that was malloced */ - pcre_uint32 options; /* Public options */ - pcre_uint32 flags; /* Private flags */ - pcre_uint32 limit_match; /* Limit set from regex */ - pcre_uint32 limit_recursion; /* Limit set from regex */ - pcre_uint32 first_char; /* Starting character */ - pcre_uint32 req_char; /* This character must be seen */ - pcre_uint16 max_lookbehind; /* Longest lookbehind (characters) */ - pcre_uint16 top_bracket; /* Highest numbered group */ - pcre_uint16 top_backref; /* Highest numbered back reference */ - pcre_uint16 name_table_offset; /* Offset to name table that follows */ - pcre_uint16 name_entry_size; /* Size of any name items */ - pcre_uint16 name_count; /* Number of name items */ - pcre_uint16 ref_count; /* Reference count */ - pcre_uint16 dummy; /* To ensure size is a multiple of 8 */ - const pcre_uint8 *tables; /* Pointer to tables or NULL for std */ - void *nullpad; /* NULL padding */ -} real_pcre32; - -#if defined COMPILE_PCRE8 -#define REAL_PCRE real_pcre -#elif defined COMPILE_PCRE16 -#define REAL_PCRE real_pcre16 -#elif defined COMPILE_PCRE32 -#define REAL_PCRE real_pcre32 -#endif - -/* Assert that the size of REAL_PCRE is divisible by 8 */ -typedef int __assert_real_pcre_size_divisible_8[(sizeof(REAL_PCRE) % 8) == 0 ? 1 : -1]; - -/* Needed in pcretest to access some fields in the real_pcre* structures - * directly. They're unified for 8/16/32 bits since the structs only differ - * after these fields; if that ever changes, need to fork those defines into - * 8/16 and 32 bit versions. */ -#define REAL_PCRE_MAGIC(re) (((REAL_PCRE*)re)->magic_number) -#define REAL_PCRE_SIZE(re) (((REAL_PCRE*)re)->size) -#define REAL_PCRE_OPTIONS(re) (((REAL_PCRE*)re)->options) -#define REAL_PCRE_FLAGS(re) (((REAL_PCRE*)re)->flags) - -/* The format of the block used to store data from pcre_study(). The same -remark (see NOTE above) about extending this structure applies. */ - -typedef struct pcre_study_data { - pcre_uint32 size; /* Total that was malloced */ - pcre_uint32 flags; /* Private flags */ - pcre_uint8 start_bits[32]; /* Starting char bits */ - pcre_uint32 minlength; /* Minimum subject length */ -} pcre_study_data; - -/* Structure for building a chain of open capturing subpatterns during -compiling, so that instructions to close them can be compiled when (*ACCEPT) is -encountered. This is also used to identify subpatterns that contain recursive -back references to themselves, so that they can be made atomic. */ - -typedef struct open_capitem { - struct open_capitem *next; /* Chain link */ - pcre_uint16 number; /* Capture number */ - pcre_uint16 flag; /* Set TRUE if recursive back ref */ -} open_capitem; - -/* Structure for building a list of named groups during the first pass of -compiling. */ - -typedef struct named_group { - const pcre_uchar *name; /* Points to the name in the pattern */ - int length; /* Length of the name */ - pcre_uint32 number; /* Group number */ -} named_group; - -/* Structure for passing "static" information around between the functions -doing the compiling, so that they are thread-safe. */ - -typedef struct compile_data { - const pcre_uint8 *lcc; /* Points to lower casing table */ - const pcre_uint8 *fcc; /* Points to case-flipping table */ - const pcre_uint8 *cbits; /* Points to character type table */ - const pcre_uint8 *ctypes; /* Points to table of type maps */ - const pcre_uchar *start_workspace;/* The start of working space */ - const pcre_uchar *start_code; /* The start of the compiled code */ - const pcre_uchar *start_pattern; /* The start of the pattern */ - const pcre_uchar *end_pattern; /* The end of the pattern */ - pcre_uchar *hwm; /* High watermark of workspace */ - open_capitem *open_caps; /* Chain of open capture items */ - named_group *named_groups; /* Points to vector in pre-compile */ - pcre_uchar *name_table; /* The name/number table */ - int names_found; /* Number of entries so far */ - int name_entry_size; /* Size of each entry */ - int named_group_list_size; /* Number of entries in the list */ - int workspace_size; /* Size of workspace */ - unsigned int bracount; /* Count of capturing parens as we compile */ - int final_bracount; /* Saved value after first pass */ - int max_lookbehind; /* Maximum lookbehind (characters) */ - int top_backref; /* Maximum back reference */ - unsigned int backref_map; /* Bitmap of low back refs */ - unsigned int namedrefcount; /* Number of backreferences by name */ - int parens_depth; /* Depth of nested parentheses */ - int assert_depth; /* Depth of nested assertions */ - pcre_uint32 external_options; /* External (initial) options */ - pcre_uint32 external_flags; /* External flag bits to be set */ - int req_varyopt; /* "After variable item" flag for reqbyte */ - BOOL had_accept; /* (*ACCEPT) encountered */ - BOOL had_pruneorskip; /* (*PRUNE) or (*SKIP) encountered */ - BOOL check_lookbehind; /* Lookbehinds need later checking */ - BOOL dupnames; /* Duplicate names exist */ - int nltype; /* Newline type */ - int nllen; /* Newline string length */ - pcre_uchar nl[4]; /* Newline string when fixed length */ -} compile_data; - -/* Structure for maintaining a chain of pointers to the currently incomplete -branches, for testing for left recursion while compiling. */ - -typedef struct branch_chain { - struct branch_chain *outer; - pcre_uchar *current_branch; -} branch_chain; - -/* Structure for items in a linked list that represents an explicit recursive -call within the pattern; used by pcre_exec(). */ - -typedef struct recursion_info { - struct recursion_info *prevrec; /* Previous recursion record (or NULL) */ - unsigned int group_num; /* Number of group that was called */ - int *offset_save; /* Pointer to start of saved offsets */ - int saved_max; /* Number of saved offsets */ - int saved_capture_last; /* Last capture number */ - PCRE_PUCHAR subject_position; /* Position at start of recursion */ -} recursion_info; - -/* A similar structure for pcre_dfa_exec(). */ - -typedef struct dfa_recursion_info { - struct dfa_recursion_info *prevrec; - int group_num; - PCRE_PUCHAR subject_position; -} dfa_recursion_info; - -/* Structure for building a chain of data for holding the values of the subject -pointer at the start of each subpattern, so as to detect when an empty string -has been matched by a subpattern - to break infinite loops; used by -pcre_exec(). */ - -typedef struct eptrblock { - struct eptrblock *epb_prev; - PCRE_PUCHAR epb_saved_eptr; -} eptrblock; - - -/* Structure for passing "static" information around between the functions -doing traditional NFA matching, so that they are thread-safe. */ - -typedef struct match_data { - unsigned long int match_call_count; /* As it says */ - unsigned long int match_limit; /* As it says */ - unsigned long int match_limit_recursion; /* As it says */ - int *offset_vector; /* Offset vector */ - int offset_end; /* One past the end */ - int offset_max; /* The maximum usable for return data */ - int nltype; /* Newline type */ - int nllen; /* Newline string length */ - int name_count; /* Number of names in name table */ - int name_entry_size; /* Size of entry in names table */ - unsigned int skip_arg_count; /* For counting SKIP_ARGs */ - unsigned int ignore_skip_arg; /* For re-run when SKIP arg name not found */ - pcre_uchar *name_table; /* Table of names */ - pcre_uchar nl[4]; /* Newline string when fixed */ - const pcre_uint8 *lcc; /* Points to lower casing table */ - const pcre_uint8 *fcc; /* Points to case-flipping table */ - const pcre_uint8 *ctypes; /* Points to table of type maps */ - BOOL notbol; /* NOTBOL flag */ - BOOL noteol; /* NOTEOL flag */ - BOOL utf; /* UTF-8 / UTF-16 flag */ - BOOL jscript_compat; /* JAVASCRIPT_COMPAT flag */ - BOOL use_ucp; /* PCRE_UCP flag */ - BOOL endonly; /* Dollar not before final \n */ - BOOL notempty; /* Empty string match not wanted */ - BOOL notempty_atstart; /* Empty string match at start not wanted */ - BOOL hitend; /* Hit the end of the subject at some point */ - BOOL bsr_anycrlf; /* \R is just any CRLF, not full Unicode */ - BOOL hasthen; /* Pattern contains (*THEN) */ - const pcre_uchar *start_code; /* For use when recursing */ - PCRE_PUCHAR start_subject; /* Start of the subject string */ - PCRE_PUCHAR end_subject; /* End of the subject string */ - PCRE_PUCHAR start_match_ptr; /* Start of matched string */ - PCRE_PUCHAR end_match_ptr; /* Subject position at end match */ - PCRE_PUCHAR start_used_ptr; /* Earliest consulted character */ - int partial; /* PARTIAL options */ - int end_offset_top; /* Highwater mark at end of match */ - pcre_int32 capture_last; /* Most recent capture number + overflow flag */ - int start_offset; /* The start offset value */ - int match_function_type; /* Set for certain special calls of MATCH() */ - eptrblock *eptrchain; /* Chain of eptrblocks for tail recursions */ - int eptrn; /* Next free eptrblock */ - recursion_info *recursive; /* Linked list of recursion data */ - void *callout_data; /* To pass back to callouts */ - const pcre_uchar *mark; /* Mark pointer to pass back on success */ - const pcre_uchar *nomatch_mark;/* Mark pointer to pass back on failure */ - const pcre_uchar *once_target; /* Where to back up to for atomic groups */ -#ifdef NO_RECURSE - void *match_frames_base; /* For remembering malloc'd frames */ -#endif -} match_data; - -/* A similar structure is used for the same purpose by the DFA matching -functions. */ - -typedef struct dfa_match_data { - const pcre_uchar *start_code; /* Start of the compiled pattern */ - const pcre_uchar *start_subject ; /* Start of the subject string */ - const pcre_uchar *end_subject; /* End of subject string */ - const pcre_uchar *start_used_ptr; /* Earliest consulted character */ - const pcre_uint8 *tables; /* Character tables */ - int start_offset; /* The start offset value */ - int moptions; /* Match options */ - int poptions; /* Pattern options */ - int nltype; /* Newline type */ - int nllen; /* Newline string length */ - pcre_uchar nl[4]; /* Newline string when fixed */ - void *callout_data; /* To pass back to callouts */ - dfa_recursion_info *recursive; /* Linked list of recursion data */ -} dfa_match_data; - -/* Bit definitions for entries in the pcre_ctypes table. */ - -#define ctype_space 0x01 -#define ctype_letter 0x02 -#define ctype_digit 0x04 -#define ctype_xdigit 0x08 -#define ctype_word 0x10 /* alphanumeric or '_' */ -#define ctype_meta 0x80 /* regexp meta char or zero (end pattern) */ - -/* Offsets for the bitmap tables in pcre_cbits. Each table contains a set -of bits for a class map. Some classes are built by combining these tables. */ - -#define cbit_space 0 /* [:space:] or \s */ -#define cbit_xdigit 32 /* [:xdigit:] */ -#define cbit_digit 64 /* [:digit:] or \d */ -#define cbit_upper 96 /* [:upper:] */ -#define cbit_lower 128 /* [:lower:] */ -#define cbit_word 160 /* [:word:] or \w */ -#define cbit_graph 192 /* [:graph:] */ -#define cbit_print 224 /* [:print:] */ -#define cbit_punct 256 /* [:punct:] */ -#define cbit_cntrl 288 /* [:cntrl:] */ -#define cbit_length 320 /* Length of the cbits table */ - -/* Offsets of the various tables from the base tables pointer, and -total length. */ - -#define lcc_offset 0 -#define fcc_offset 256 -#define cbits_offset 512 -#define ctypes_offset (cbits_offset + cbit_length) -#define tables_length (ctypes_offset + 256) - -/* Internal function and data prefixes. */ - -#if defined COMPILE_PCRE8 -#ifndef PUBL -#define PUBL(name) pcre_##name -#endif -#ifndef PRIV -#define PRIV(name) _pcre_##name -#endif -#elif defined COMPILE_PCRE16 -#ifndef PUBL -#define PUBL(name) pcre16_##name -#endif -#ifndef PRIV -#define PRIV(name) _pcre16_##name -#endif -#elif defined COMPILE_PCRE32 -#ifndef PUBL -#define PUBL(name) pcre32_##name -#endif -#ifndef PRIV -#define PRIV(name) _pcre32_##name -#endif -#else -#error Unsupported compiling mode -#endif /* COMPILE_PCRE[8|16|32] */ - -/* Layout of the UCP type table that translates property names into types and -codes. Each entry used to point directly to a name, but to reduce the number of -relocations in shared libraries, it now has an offset into a single string -instead. */ - -typedef struct { - pcre_uint16 name_offset; - pcre_uint16 type; - pcre_uint16 value; -} ucp_type_table; - - -/* Internal shared data tables. These are tables that are used by more than one -of the exported public functions. They have to be "external" in the C sense, -but are not part of the PCRE public API. The data for these tables is in the -pcre_tables.c module. */ - -#ifdef COMPILE_PCRE8 -extern const int PRIV(utf8_table1)[]; -extern const int PRIV(utf8_table1_size); -extern const int PRIV(utf8_table2)[]; -extern const int PRIV(utf8_table3)[]; -extern const pcre_uint8 PRIV(utf8_table4)[]; -#endif /* COMPILE_PCRE8 */ - -extern const char PRIV(utt_names)[]; -extern const ucp_type_table PRIV(utt)[]; -extern const int PRIV(utt_size); - -extern const pcre_uint8 PRIV(OP_lengths)[]; -extern const pcre_uint8 PRIV(default_tables)[]; - -extern const pcre_uint32 PRIV(hspace_list)[]; -extern const pcre_uint32 PRIV(vspace_list)[]; - - -/* Internal shared functions. These are functions that are used by more than -one of the exported public functions. They have to be "external" in the C -sense, but are not part of the PCRE public API. */ - -/* String comparison functions. */ -#if defined COMPILE_PCRE8 - -#define STRCMP_UC_UC(str1, str2) \ - strcmp((char *)(str1), (char *)(str2)) -#define STRCMP_UC_C8(str1, str2) \ - strcmp((char *)(str1), (str2)) -#define STRNCMP_UC_UC(str1, str2, num) \ - strncmp((char *)(str1), (char *)(str2), (num)) -#define STRNCMP_UC_C8(str1, str2, num) \ - strncmp((char *)(str1), (str2), (num)) -#define STRLEN_UC(str) strlen((const char *)str) - -#elif defined COMPILE_PCRE16 || defined COMPILE_PCRE32 - -extern int PRIV(strcmp_uc_uc)(const pcre_uchar *, - const pcre_uchar *); -extern int PRIV(strcmp_uc_c8)(const pcre_uchar *, - const char *); -extern int PRIV(strncmp_uc_uc)(const pcre_uchar *, - const pcre_uchar *, unsigned int num); -extern int PRIV(strncmp_uc_c8)(const pcre_uchar *, - const char *, unsigned int num); -extern unsigned int PRIV(strlen_uc)(const pcre_uchar *str); - -#define STRCMP_UC_UC(str1, str2) \ - PRIV(strcmp_uc_uc)((str1), (str2)) -#define STRCMP_UC_C8(str1, str2) \ - PRIV(strcmp_uc_c8)((str1), (str2)) -#define STRNCMP_UC_UC(str1, str2, num) \ - PRIV(strncmp_uc_uc)((str1), (str2), (num)) -#define STRNCMP_UC_C8(str1, str2, num) \ - PRIV(strncmp_uc_c8)((str1), (str2), (num)) -#define STRLEN_UC(str) PRIV(strlen_uc)(str) - -#endif /* COMPILE_PCRE[8|16|32] */ - -#if defined COMPILE_PCRE8 || defined COMPILE_PCRE16 - -#define STRCMP_UC_UC_TEST(str1, str2) STRCMP_UC_UC(str1, str2) -#define STRCMP_UC_C8_TEST(str1, str2) STRCMP_UC_C8(str1, str2) - -#elif defined COMPILE_PCRE32 - -extern int PRIV(strcmp_uc_uc_utf)(const pcre_uchar *, - const pcre_uchar *); -extern int PRIV(strcmp_uc_c8_utf)(const pcre_uchar *, - const char *); - -#define STRCMP_UC_UC_TEST(str1, str2) \ - (utf ? PRIV(strcmp_uc_uc_utf)((str1), (str2)) : PRIV(strcmp_uc_uc)((str1), (str2))) -#define STRCMP_UC_C8_TEST(str1, str2) \ - (utf ? PRIV(strcmp_uc_c8_utf)((str1), (str2)) : PRIV(strcmp_uc_c8)((str1), (str2))) - -#endif /* COMPILE_PCRE[8|16|32] */ - -extern const pcre_uchar *PRIV(find_bracket)(const pcre_uchar *, BOOL, int); -extern BOOL PRIV(is_newline)(PCRE_PUCHAR, int, PCRE_PUCHAR, - int *, BOOL); -extern unsigned int PRIV(ord2utf)(pcre_uint32, pcre_uchar *); -extern int PRIV(valid_utf)(PCRE_PUCHAR, int, int *); -extern BOOL PRIV(was_newline)(PCRE_PUCHAR, int, PCRE_PUCHAR, - int *, BOOL); -extern BOOL PRIV(xclass)(pcre_uint32, const pcre_uchar *, BOOL); - -#ifdef SUPPORT_JIT -extern void PRIV(jit_compile)(const REAL_PCRE *, - PUBL(extra) *, int); -extern int PRIV(jit_exec)(const PUBL(extra) *, - const pcre_uchar *, int, int, int, int *, int); -extern void PRIV(jit_free)(void *); -extern int PRIV(jit_get_size)(void *); -extern const char* PRIV(jit_get_target)(void); -#endif - -/* Unicode character database (UCD) */ - -typedef struct { - pcre_uint8 script; /* ucp_Arabic, etc. */ - pcre_uint8 chartype; /* ucp_Cc, etc. (general categories) */ - pcre_uint8 gbprop; /* ucp_gbControl, etc. (grapheme break property) */ - pcre_uint8 caseset; /* offset to multichar other cases or zero */ - pcre_int32 other_case; /* offset to other case, or zero if none */ -} ucd_record; - -extern const pcre_uint32 PRIV(ucd_caseless_sets)[]; -extern const ucd_record PRIV(ucd_records)[]; -extern const pcre_uint8 PRIV(ucd_stage1)[]; -extern const pcre_uint16 PRIV(ucd_stage2)[]; -extern const pcre_uint32 PRIV(ucp_gentype)[]; -extern const pcre_uint32 PRIV(ucp_gbtable)[]; -#ifdef SUPPORT_JIT -extern const int PRIV(ucp_typerange)[]; -#endif - -#ifdef SUPPORT_UCP -/* UCD access macros */ - -#define UCD_BLOCK_SIZE 128 -#define GET_UCD(ch) (PRIV(ucd_records) + \ - PRIV(ucd_stage2)[PRIV(ucd_stage1)[(int)(ch) / UCD_BLOCK_SIZE] * \ - UCD_BLOCK_SIZE + (int)(ch) % UCD_BLOCK_SIZE]) - -#define UCD_CHARTYPE(ch) GET_UCD(ch)->chartype -#define UCD_SCRIPT(ch) GET_UCD(ch)->script -#define UCD_CATEGORY(ch) PRIV(ucp_gentype)[UCD_CHARTYPE(ch)] -#define UCD_GRAPHBREAK(ch) GET_UCD(ch)->gbprop -#define UCD_CASESET(ch) GET_UCD(ch)->caseset -#define UCD_OTHERCASE(ch) ((pcre_uint32)((int)ch + (int)(GET_UCD(ch)->other_case))) - -#endif /* SUPPORT_UCP */ - -#endif - -/* End of pcre_internal.h */ diff --git a/lib/impure/nre/private/pcre_src/pcre_jit_compile.c b/lib/impure/nre/private/pcre_src/pcre_jit_compile.c deleted file mode 100644 index 256e3a45b..000000000 --- a/lib/impure/nre/private/pcre_src/pcre_jit_compile.c +++ /dev/null @@ -1,10704 +0,0 @@ -/************************************************* -* Perl-Compatible Regular Expressions * -*************************************************/ - -/* PCRE is a library of functions to support regular expressions whose syntax -and semantics are as close as possible to those of the Perl 5 language. - - Written by Philip Hazel - Copyright (c) 1997-2013 University of Cambridge - - The machine code generator part (this module) was written by Zoltan Herczeg - Copyright (c) 2010-2013 - ------------------------------------------------------------------------------ -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - * Neither the name of the University of Cambridge nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ -*/ - -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - -#include "pcre_internal.h" - -#if defined SUPPORT_JIT - -/* All-in-one: Since we use the JIT compiler only from here, -we just include it. This way we don't need to touch the build -system files. */ - -#define SLJIT_MALLOC(size) (PUBL(malloc))(size) -#define SLJIT_FREE(ptr) (PUBL(free))(ptr) -#define SLJIT_CONFIG_AUTO 1 -#define SLJIT_CONFIG_STATIC 1 -#define SLJIT_VERBOSE 0 -#define SLJIT_DEBUG 0 - -#include "sljit/sljitLir.c" - -#if defined SLJIT_CONFIG_UNSUPPORTED && SLJIT_CONFIG_UNSUPPORTED -#error Unsupported architecture -#endif - -/* Defines for debugging purposes. */ - -/* 1 - Use unoptimized capturing brackets. - 2 - Enable capture_last_ptr (includes option 1). */ -/* #define DEBUG_FORCE_UNOPTIMIZED_CBRAS 2 */ - -/* 1 - Always have a control head. */ -/* #define DEBUG_FORCE_CONTROL_HEAD 1 */ - -/* Allocate memory for the regex stack on the real machine stack. -Fast, but limited size. */ -#define MACHINE_STACK_SIZE 32768 - -/* Growth rate for stack allocated by the OS. Should be the multiply -of page size. */ -#define STACK_GROWTH_RATE 8192 - -/* Enable to check that the allocation could destroy temporaries. */ -#if defined SLJIT_DEBUG && SLJIT_DEBUG -#define DESTROY_REGISTERS 1 -#endif - -/* -Short summary about the backtracking mechanism empolyed by the jit code generator: - -The code generator follows the recursive nature of the PERL compatible regular -expressions. The basic blocks of regular expressions are condition checkers -whose execute different commands depending on the result of the condition check. -The relationship between the operators can be horizontal (concatenation) and -vertical (sub-expression) (See struct backtrack_common for more details). - - 'ab' - 'a' and 'b' regexps are concatenated - 'a+' - 'a' is the sub-expression of the '+' operator - -The condition checkers are boolean (true/false) checkers. Machine code is generated -for the checker itself and for the actions depending on the result of the checker. -The 'true' case is called as the matching path (expected path), and the other is called as -the 'backtrack' path. Branch instructions are expesive for all CPUs, so we avoid taken -branches on the matching path. - - Greedy star operator (*) : - Matching path: match happens. - Backtrack path: match failed. - Non-greedy star operator (*?) : - Matching path: no need to perform a match. - Backtrack path: match is required. - -The following example shows how the code generated for a capturing bracket -with two alternatives. Let A, B, C, D are arbirary regular expressions, and -we have the following regular expression: - - A(B|C)D - -The generated code will be the following: - - A matching path - '(' matching path (pushing arguments to the stack) - B matching path - ')' matching path (pushing arguments to the stack) - D matching path - return with successful match - - D backtrack path - ')' backtrack path (If we arrived from "C" jump to the backtrack of "C") - B backtrack path - C expected path - jump to D matching path - C backtrack path - A backtrack path - - Notice, that the order of backtrack code paths are the opposite of the fast - code paths. In this way the topmost value on the stack is always belong - to the current backtrack code path. The backtrack path must check - whether there is a next alternative. If so, it needs to jump back to - the matching path eventually. Otherwise it needs to clear out its own stack - frame and continue the execution on the backtrack code paths. -*/ - -/* -Saved stack frames: - -Atomic blocks and asserts require reloading the values of private data -when the backtrack mechanism performed. Because of OP_RECURSE, the data -are not necessarly known in compile time, thus we need a dynamic restore -mechanism. - -The stack frames are stored in a chain list, and have the following format: -([ capturing bracket offset ][ start value ][ end value ])+ ... [ 0 ] [ previous head ] - -Thus we can restore the private data to a particular point in the stack. -*/ - -typedef struct jit_arguments { - /* Pointers first. */ - struct sljit_stack *stack; - const pcre_uchar *str; - const pcre_uchar *begin; - const pcre_uchar *end; - int *offsets; - pcre_uchar *uchar_ptr; - pcre_uchar *mark_ptr; - void *callout_data; - /* Everything else after. */ - pcre_uint32 limit_match; - int real_offset_count; - int offset_count; - pcre_uint8 notbol; - pcre_uint8 noteol; - pcre_uint8 notempty; - pcre_uint8 notempty_atstart; -} jit_arguments; - -typedef struct executable_functions { - void *executable_funcs[JIT_NUMBER_OF_COMPILE_MODES]; - sljit_uw *read_only_data[JIT_NUMBER_OF_COMPILE_MODES]; - sljit_uw executable_sizes[JIT_NUMBER_OF_COMPILE_MODES]; - PUBL(jit_callback) callback; - void *userdata; - pcre_uint32 top_bracket; - pcre_uint32 limit_match; -} executable_functions; - -typedef struct jump_list { - struct sljit_jump *jump; - struct jump_list *next; -} jump_list; - -typedef struct stub_list { - struct sljit_jump *start; - struct sljit_label *quit; - struct stub_list *next; -} stub_list; - -typedef struct label_addr_list { - struct sljit_label *label; - sljit_uw *update_addr; - struct label_addr_list *next; -} label_addr_list; - -enum frame_types { - no_frame = -1, - no_stack = -2 -}; - -enum control_types { - type_mark = 0, - type_then_trap = 1 -}; - -typedef int (SLJIT_CALL *jit_function)(jit_arguments *args); - -/* The following structure is the key data type for the recursive -code generator. It is allocated by compile_matchingpath, and contains -the arguments for compile_backtrackingpath. Must be the first member -of its descendants. */ -typedef struct backtrack_common { - /* Concatenation stack. */ - struct backtrack_common *prev; - jump_list *nextbacktracks; - /* Internal stack (for component operators). */ - struct backtrack_common *top; - jump_list *topbacktracks; - /* Opcode pointer. */ - pcre_uchar *cc; -} backtrack_common; - -typedef struct assert_backtrack { - backtrack_common common; - jump_list *condfailed; - /* Less than 0 if a frame is not needed. */ - int framesize; - /* Points to our private memory word on the stack. */ - int private_data_ptr; - /* For iterators. */ - struct sljit_label *matchingpath; -} assert_backtrack; - -typedef struct bracket_backtrack { - backtrack_common common; - /* Where to coninue if an alternative is successfully matched. */ - struct sljit_label *alternative_matchingpath; - /* For rmin and rmax iterators. */ - struct sljit_label *recursive_matchingpath; - /* For greedy ? operator. */ - struct sljit_label *zero_matchingpath; - /* Contains the branches of a failed condition. */ - union { - /* Both for OP_COND, OP_SCOND. */ - jump_list *condfailed; - assert_backtrack *assert; - /* For OP_ONCE. Less than 0 if not needed. */ - int framesize; - } u; - /* Points to our private memory word on the stack. */ - int private_data_ptr; -} bracket_backtrack; - -typedef struct bracketpos_backtrack { - backtrack_common common; - /* Points to our private memory word on the stack. */ - int private_data_ptr; - /* Reverting stack is needed. */ - int framesize; - /* Allocated stack size. */ - int stacksize; -} bracketpos_backtrack; - -typedef struct braminzero_backtrack { - backtrack_common common; - struct sljit_label *matchingpath; -} braminzero_backtrack; - -typedef struct iterator_backtrack { - backtrack_common common; - /* Next iteration. */ - struct sljit_label *matchingpath; -} iterator_backtrack; - -typedef struct recurse_entry { - struct recurse_entry *next; - /* Contains the function entry. */ - struct sljit_label *entry; - /* Collects the calls until the function is not created. */ - jump_list *calls; - /* Points to the starting opcode. */ - sljit_sw start; -} recurse_entry; - -typedef struct recurse_backtrack { - backtrack_common common; - BOOL inlined_pattern; -} recurse_backtrack; - -#define OP_THEN_TRAP OP_TABLE_LENGTH - -typedef struct then_trap_backtrack { - backtrack_common common; - /* If then_trap is not NULL, this structure contains the real - then_trap for the backtracking path. */ - struct then_trap_backtrack *then_trap; - /* Points to the starting opcode. */ - sljit_sw start; - /* Exit point for the then opcodes of this alternative. */ - jump_list *quit; - /* Frame size of the current alternative. */ - int framesize; -} then_trap_backtrack; - -#define MAX_RANGE_SIZE 4 - -typedef struct compiler_common { - /* The sljit ceneric compiler. */ - struct sljit_compiler *compiler; - /* First byte code. */ - pcre_uchar *start; - /* Maps private data offset to each opcode. */ - sljit_si *private_data_ptrs; - /* This read-only data is available during runtime. */ - sljit_uw *read_only_data; - /* The total size of the read-only data. */ - sljit_uw read_only_data_size; - /* The next free entry of the read_only_data. */ - sljit_uw *read_only_data_ptr; - /* Tells whether the capturing bracket is optimized. */ - pcre_uint8 *optimized_cbracket; - /* Tells whether the starting offset is a target of then. */ - pcre_uint8 *then_offsets; - /* Current position where a THEN must jump. */ - then_trap_backtrack *then_trap; - /* Starting offset of private data for capturing brackets. */ - int cbra_ptr; - /* Output vector starting point. Must be divisible by 2. */ - int ovector_start; - /* Last known position of the requested byte. */ - int req_char_ptr; - /* Head of the last recursion. */ - int recursive_head_ptr; - /* First inspected character for partial matching. */ - int start_used_ptr; - /* Starting pointer for partial soft matches. */ - int hit_start; - /* End pointer of the first line. */ - int first_line_end; - /* Points to the marked string. */ - int mark_ptr; - /* Recursive control verb management chain. */ - int control_head_ptr; - /* Points to the last matched capture block index. */ - int capture_last_ptr; - /* Points to the starting position of the current match. */ - int start_ptr; - - /* Flipped and lower case tables. */ - const pcre_uint8 *fcc; - sljit_sw lcc; - /* Mode can be PCRE_STUDY_JIT_COMPILE and others. */ - int mode; - /* TRUE, when minlength is greater than 0. */ - BOOL might_be_empty; - /* \K is found in the pattern. */ - BOOL has_set_som; - /* (*SKIP:arg) is found in the pattern. */ - BOOL has_skip_arg; - /* (*THEN) is found in the pattern. */ - BOOL has_then; - /* Needs to know the start position anytime. */ - BOOL needs_start_ptr; - /* Currently in recurse or negative assert. */ - BOOL local_exit; - /* Currently in a positive assert. */ - BOOL positive_assert; - /* Newline control. */ - int nltype; - pcre_uint32 nlmax; - pcre_uint32 nlmin; - int newline; - int bsr_nltype; - pcre_uint32 bsr_nlmax; - pcre_uint32 bsr_nlmin; - /* Dollar endonly. */ - int endonly; - /* Tables. */ - sljit_sw ctypes; - /* Named capturing brackets. */ - pcre_uchar *name_table; - sljit_sw name_count; - sljit_sw name_entry_size; - - /* Labels and jump lists. */ - struct sljit_label *partialmatchlabel; - struct sljit_label *quit_label; - struct sljit_label *forced_quit_label; - struct sljit_label *accept_label; - struct sljit_label *ff_newline_shortcut; - stub_list *stubs; - label_addr_list *label_addrs; - recurse_entry *entries; - recurse_entry *currententry; - jump_list *partialmatch; - jump_list *quit; - jump_list *positive_assert_quit; - jump_list *forced_quit; - jump_list *accept; - jump_list *calllimit; - jump_list *stackalloc; - jump_list *revertframes; - jump_list *wordboundary; - jump_list *anynewline; - jump_list *hspace; - jump_list *vspace; - jump_list *casefulcmp; - jump_list *caselesscmp; - jump_list *reset_match; - BOOL jscript_compat; -#ifdef SUPPORT_UTF - BOOL utf; -#ifdef SUPPORT_UCP - BOOL use_ucp; -#endif -#ifdef COMPILE_PCRE8 - jump_list *utfreadchar; - jump_list *utfreadchar16; - jump_list *utfreadtype8; -#endif -#endif /* SUPPORT_UTF */ -#ifdef SUPPORT_UCP - jump_list *getucd; -#endif -} compiler_common; - -/* For byte_sequence_compare. */ - -typedef struct compare_context { - int length; - int sourcereg; -#if defined SLJIT_UNALIGNED && SLJIT_UNALIGNED - int ucharptr; - union { - sljit_si asint; - sljit_uh asushort; -#if defined COMPILE_PCRE8 - sljit_ub asbyte; - sljit_ub asuchars[4]; -#elif defined COMPILE_PCRE16 - sljit_uh asuchars[2]; -#elif defined COMPILE_PCRE32 - sljit_ui asuchars[1]; -#endif - } c; - union { - sljit_si asint; - sljit_uh asushort; -#if defined COMPILE_PCRE8 - sljit_ub asbyte; - sljit_ub asuchars[4]; -#elif defined COMPILE_PCRE16 - sljit_uh asuchars[2]; -#elif defined COMPILE_PCRE32 - sljit_ui asuchars[1]; -#endif - } oc; -#endif -} compare_context; - -/* Undefine sljit macros. */ -#undef CMP - -/* Used for accessing the elements of the stack. */ -#define STACK(i) ((-(i) - 1) * (int)sizeof(sljit_sw)) - -#define TMP1 SLJIT_R0 -#define TMP2 SLJIT_R2 -#define TMP3 SLJIT_R3 -#define STR_PTR SLJIT_S0 -#define STR_END SLJIT_S1 -#define STACK_TOP SLJIT_R1 -#define STACK_LIMIT SLJIT_S2 -#define COUNT_MATCH SLJIT_S3 -#define ARGUMENTS SLJIT_S4 -#define RETURN_ADDR SLJIT_R4 - -/* Local space layout. */ -/* These two locals can be used by the current opcode. */ -#define LOCALS0 (0 * sizeof(sljit_sw)) -#define LOCALS1 (1 * sizeof(sljit_sw)) -/* Two local variables for possessive quantifiers (char1 cannot use them). */ -#define POSSESSIVE0 (2 * sizeof(sljit_sw)) -#define POSSESSIVE1 (3 * sizeof(sljit_sw)) -/* Max limit of recursions. */ -#define LIMIT_MATCH (4 * sizeof(sljit_sw)) -/* The output vector is stored on the stack, and contains pointers -to characters. The vector data is divided into two groups: the first -group contains the start / end character pointers, and the second is -the start pointers when the end of the capturing group has not yet reached. */ -#define OVECTOR_START (common->ovector_start) -#define OVECTOR(i) (OVECTOR_START + (i) * (sljit_sw)sizeof(sljit_sw)) -#define OVECTOR_PRIV(i) (common->cbra_ptr + (i) * (sljit_sw)sizeof(sljit_sw)) -#define PRIVATE_DATA(cc) (common->private_data_ptrs[(cc) - common->start]) - -#if defined COMPILE_PCRE8 -#define MOV_UCHAR SLJIT_MOV_UB -#define MOVU_UCHAR SLJIT_MOVU_UB -#elif defined COMPILE_PCRE16 -#define MOV_UCHAR SLJIT_MOV_UH -#define MOVU_UCHAR SLJIT_MOVU_UH -#elif defined COMPILE_PCRE32 -#define MOV_UCHAR SLJIT_MOV_UI -#define MOVU_UCHAR SLJIT_MOVU_UI -#else -#error Unsupported compiling mode -#endif - -/* Shortcuts. */ -#define DEFINE_COMPILER \ - struct sljit_compiler *compiler = common->compiler -#define OP1(op, dst, dstw, src, srcw) \ - sljit_emit_op1(compiler, (op), (dst), (dstw), (src), (srcw)) -#define OP2(op, dst, dstw, src1, src1w, src2, src2w) \ - sljit_emit_op2(compiler, (op), (dst), (dstw), (src1), (src1w), (src2), (src2w)) -#define LABEL() \ - sljit_emit_label(compiler) -#define JUMP(type) \ - sljit_emit_jump(compiler, (type)) -#define JUMPTO(type, label) \ - sljit_set_label(sljit_emit_jump(compiler, (type)), (label)) -#define JUMPHERE(jump) \ - sljit_set_label((jump), sljit_emit_label(compiler)) -#define SET_LABEL(jump, label) \ - sljit_set_label((jump), (label)) -#define CMP(type, src1, src1w, src2, src2w) \ - sljit_emit_cmp(compiler, (type), (src1), (src1w), (src2), (src2w)) -#define CMPTO(type, src1, src1w, src2, src2w, label) \ - sljit_set_label(sljit_emit_cmp(compiler, (type), (src1), (src1w), (src2), (src2w)), (label)) -#define OP_FLAGS(op, dst, dstw, src, srcw, type) \ - sljit_emit_op_flags(compiler, (op), (dst), (dstw), (src), (srcw), (type)) -#define GET_LOCAL_BASE(dst, dstw, offset) \ - sljit_get_local_base(compiler, (dst), (dstw), (offset)) - -#define READ_CHAR_MAX 0x7fffffff - -static pcre_uchar* bracketend(pcre_uchar* cc) -{ -SLJIT_ASSERT((*cc >= OP_ASSERT && *cc <= OP_ASSERTBACK_NOT) || (*cc >= OP_ONCE && *cc <= OP_SCOND)); -do cc += GET(cc, 1); while (*cc == OP_ALT); -SLJIT_ASSERT(*cc >= OP_KET && *cc <= OP_KETRPOS); -cc += 1 + LINK_SIZE; -return cc; -} - -static int no_alternatives(pcre_uchar* cc) -{ -int count = 0; -SLJIT_ASSERT((*cc >= OP_ASSERT && *cc <= OP_ASSERTBACK_NOT) || (*cc >= OP_ONCE && *cc <= OP_SCOND)); -do - { - cc += GET(cc, 1); - count++; - } -while (*cc == OP_ALT); -SLJIT_ASSERT(*cc >= OP_KET && *cc <= OP_KETRPOS); -return count; -} - -static int ones_in_half_byte[16] = { - /* 0 */ 0, 1, 1, 2, /* 4 */ 1, 2, 2, 3, - /* 8 */ 1, 2, 2, 3, /* 12 */ 2, 3, 3, 4 -}; - -/* Functions whose might need modification for all new supported opcodes: - next_opcode - check_opcode_types - set_private_data_ptrs - get_framesize - init_frame - get_private_data_copy_length - copy_private_data - compile_matchingpath - compile_backtrackingpath -*/ - -static pcre_uchar *next_opcode(compiler_common *common, pcre_uchar *cc) -{ -SLJIT_UNUSED_ARG(common); -switch(*cc) - { - case OP_SOD: - case OP_SOM: - case OP_SET_SOM: - case OP_NOT_WORD_BOUNDARY: - case OP_WORD_BOUNDARY: - case OP_NOT_DIGIT: - case OP_DIGIT: - case OP_NOT_WHITESPACE: - case OP_WHITESPACE: - case OP_NOT_WORDCHAR: - case OP_WORDCHAR: - case OP_ANY: - case OP_ALLANY: - case OP_NOTPROP: - case OP_PROP: - case OP_ANYNL: - case OP_NOT_HSPACE: - case OP_HSPACE: - case OP_NOT_VSPACE: - case OP_VSPACE: - case OP_EXTUNI: - case OP_EODN: - case OP_EOD: - case OP_CIRC: - case OP_CIRCM: - case OP_DOLL: - case OP_DOLLM: - case OP_CRSTAR: - case OP_CRMINSTAR: - case OP_CRPLUS: - case OP_CRMINPLUS: - case OP_CRQUERY: - case OP_CRMINQUERY: - case OP_CRRANGE: - case OP_CRMINRANGE: - case OP_CRPOSSTAR: - case OP_CRPOSPLUS: - case OP_CRPOSQUERY: - case OP_CRPOSRANGE: - case OP_CLASS: - case OP_NCLASS: - case OP_REF: - case OP_REFI: - case OP_DNREF: - case OP_DNREFI: - case OP_RECURSE: - case OP_CALLOUT: - case OP_ALT: - case OP_KET: - case OP_KETRMAX: - case OP_KETRMIN: - case OP_KETRPOS: - case OP_REVERSE: - case OP_ASSERT: - case OP_ASSERT_NOT: - case OP_ASSERTBACK: - case OP_ASSERTBACK_NOT: - case OP_ONCE: - case OP_ONCE_NC: - case OP_BRA: - case OP_BRAPOS: - case OP_CBRA: - case OP_CBRAPOS: - case OP_COND: - case OP_SBRA: - case OP_SBRAPOS: - case OP_SCBRA: - case OP_SCBRAPOS: - case OP_SCOND: - case OP_CREF: - case OP_DNCREF: - case OP_RREF: - case OP_DNRREF: - case OP_DEF: - case OP_BRAZERO: - case OP_BRAMINZERO: - case OP_BRAPOSZERO: - case OP_PRUNE: - case OP_SKIP: - case OP_THEN: - case OP_COMMIT: - case OP_FAIL: - case OP_ACCEPT: - case OP_ASSERT_ACCEPT: - case OP_CLOSE: - case OP_SKIPZERO: - return cc + PRIV(OP_lengths)[*cc]; - - case OP_CHAR: - case OP_CHARI: - case OP_NOT: - case OP_NOTI: - case OP_STAR: - case OP_MINSTAR: - case OP_PLUS: - case OP_MINPLUS: - case OP_QUERY: - case OP_MINQUERY: - case OP_UPTO: - case OP_MINUPTO: - case OP_EXACT: - case OP_POSSTAR: - case OP_POSPLUS: - case OP_POSQUERY: - case OP_POSUPTO: - case OP_STARI: - case OP_MINSTARI: - case OP_PLUSI: - case OP_MINPLUSI: - case OP_QUERYI: - case OP_MINQUERYI: - case OP_UPTOI: - case OP_MINUPTOI: - case OP_EXACTI: - case OP_POSSTARI: - case OP_POSPLUSI: - case OP_POSQUERYI: - case OP_POSUPTOI: - case OP_NOTSTAR: - case OP_NOTMINSTAR: - case OP_NOTPLUS: - case OP_NOTMINPLUS: - case OP_NOTQUERY: - case OP_NOTMINQUERY: - case OP_NOTUPTO: - case OP_NOTMINUPTO: - case OP_NOTEXACT: - case OP_NOTPOSSTAR: - case OP_NOTPOSPLUS: - case OP_NOTPOSQUERY: - case OP_NOTPOSUPTO: - case OP_NOTSTARI: - case OP_NOTMINSTARI: - case OP_NOTPLUSI: - case OP_NOTMINPLUSI: - case OP_NOTQUERYI: - case OP_NOTMINQUERYI: - case OP_NOTUPTOI: - case OP_NOTMINUPTOI: - case OP_NOTEXACTI: - case OP_NOTPOSSTARI: - case OP_NOTPOSPLUSI: - case OP_NOTPOSQUERYI: - case OP_NOTPOSUPTOI: - cc += PRIV(OP_lengths)[*cc]; -#ifdef SUPPORT_UTF - if (common->utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]); -#endif - return cc; - - /* Special cases. */ - case OP_TYPESTAR: - case OP_TYPEMINSTAR: - case OP_TYPEPLUS: - case OP_TYPEMINPLUS: - case OP_TYPEQUERY: - case OP_TYPEMINQUERY: - case OP_TYPEUPTO: - case OP_TYPEMINUPTO: - case OP_TYPEEXACT: - case OP_TYPEPOSSTAR: - case OP_TYPEPOSPLUS: - case OP_TYPEPOSQUERY: - case OP_TYPEPOSUPTO: - return cc + PRIV(OP_lengths)[*cc] - 1; - - case OP_ANYBYTE: -#ifdef SUPPORT_UTF - if (common->utf) return NULL; -#endif - return cc + 1; - -#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 - case OP_XCLASS: - return cc + GET(cc, 1); -#endif - - case OP_MARK: - case OP_PRUNE_ARG: - case OP_SKIP_ARG: - case OP_THEN_ARG: - return cc + 1 + 2 + cc[1]; - - default: - /* All opcodes are supported now! */ - SLJIT_ASSERT_STOP(); - return NULL; - } -} - -static BOOL check_opcode_types(compiler_common *common, pcre_uchar *cc, pcre_uchar *ccend) -{ -int count; -pcre_uchar *slot; - -/* Calculate important variables (like stack size) and checks whether all opcodes are supported. */ -while (cc < ccend) - { - switch(*cc) - { - case OP_SET_SOM: - common->has_set_som = TRUE; - common->might_be_empty = TRUE; - cc += 1; - break; - - case OP_REF: - case OP_REFI: - common->optimized_cbracket[GET2(cc, 1)] = 0; - cc += 1 + IMM2_SIZE; - break; - - case OP_BRA: - case OP_CBRA: - case OP_SBRA: - case OP_SCBRA: - count = no_alternatives(cc); - if (count > 4) - common->read_only_data_size += count * sizeof(sljit_uw); - cc += 1 + LINK_SIZE + (*cc == OP_CBRA || *cc == OP_SCBRA ? IMM2_SIZE : 0); - break; - - case OP_CBRAPOS: - case OP_SCBRAPOS: - common->optimized_cbracket[GET2(cc, 1 + LINK_SIZE)] = 0; - cc += 1 + LINK_SIZE + IMM2_SIZE; - break; - - case OP_COND: - case OP_SCOND: - /* Only AUTO_CALLOUT can insert this opcode. We do - not intend to support this case. */ - if (cc[1 + LINK_SIZE] == OP_CALLOUT) - return FALSE; - cc += 1 + LINK_SIZE; - break; - - case OP_CREF: - common->optimized_cbracket[GET2(cc, 1)] = 0; - cc += 1 + IMM2_SIZE; - break; - - case OP_DNREF: - case OP_DNREFI: - case OP_DNCREF: - count = GET2(cc, 1 + IMM2_SIZE); - slot = common->name_table + GET2(cc, 1) * common->name_entry_size; - while (count-- > 0) - { - common->optimized_cbracket[GET2(slot, 0)] = 0; - slot += common->name_entry_size; - } - cc += 1 + 2 * IMM2_SIZE; - break; - - case OP_RECURSE: - /* Set its value only once. */ - if (common->recursive_head_ptr == 0) - { - common->recursive_head_ptr = common->ovector_start; - common->ovector_start += sizeof(sljit_sw); - } - cc += 1 + LINK_SIZE; - break; - - case OP_CALLOUT: - if (common->capture_last_ptr == 0) - { - common->capture_last_ptr = common->ovector_start; - common->ovector_start += sizeof(sljit_sw); - } - cc += 2 + 2 * LINK_SIZE; - break; - - case OP_THEN_ARG: - common->has_then = TRUE; - common->control_head_ptr = 1; - /* Fall through. */ - - case OP_PRUNE_ARG: - common->needs_start_ptr = TRUE; - /* Fall through. */ - - case OP_MARK: - if (common->mark_ptr == 0) - { - common->mark_ptr = common->ovector_start; - common->ovector_start += sizeof(sljit_sw); - } - cc += 1 + 2 + cc[1]; - break; - - case OP_THEN: - common->has_then = TRUE; - common->control_head_ptr = 1; - /* Fall through. */ - - case OP_PRUNE: - case OP_SKIP: - common->needs_start_ptr = TRUE; - cc += 1; - break; - - case OP_SKIP_ARG: - common->control_head_ptr = 1; - common->has_skip_arg = TRUE; - cc += 1 + 2 + cc[1]; - break; - - default: - cc = next_opcode(common, cc); - if (cc == NULL) - return FALSE; - break; - } - } -return TRUE; -} - -static int get_class_iterator_size(pcre_uchar *cc) -{ -switch(*cc) - { - case OP_CRSTAR: - case OP_CRPLUS: - return 2; - - case OP_CRMINSTAR: - case OP_CRMINPLUS: - case OP_CRQUERY: - case OP_CRMINQUERY: - return 1; - - case OP_CRRANGE: - case OP_CRMINRANGE: - if (GET2(cc, 1) == GET2(cc, 1 + IMM2_SIZE)) - return 0; - return 2; - - default: - return 0; - } -} - -static BOOL detect_repeat(compiler_common *common, pcre_uchar *begin) -{ -pcre_uchar *end = bracketend(begin); -pcre_uchar *next; -pcre_uchar *next_end; -pcre_uchar *max_end; -pcre_uchar type; -sljit_sw length = end - begin; -int min, max, i; - -/* Detect fixed iterations first. */ -if (end[-(1 + LINK_SIZE)] != OP_KET) - return FALSE; - -/* Already detected repeat. */ -if (common->private_data_ptrs[end - common->start - LINK_SIZE] != 0) - return TRUE; - -next = end; -min = 1; -while (1) - { - if (*next != *begin) - break; - next_end = bracketend(next); - if (next_end - next != length || memcmp(begin, next, IN_UCHARS(length)) != 0) - break; - next = next_end; - min++; - } - -if (min == 2) - return FALSE; - -max = 0; -max_end = next; -if (*next == OP_BRAZERO || *next == OP_BRAMINZERO) - { - type = *next; - while (1) - { - if (next[0] != type || next[1] != OP_BRA || next[2 + LINK_SIZE] != *begin) - break; - next_end = bracketend(next + 2 + LINK_SIZE); - if (next_end - next != (length + 2 + LINK_SIZE) || memcmp(begin, next + 2 + LINK_SIZE, IN_UCHARS(length)) != 0) - break; - next = next_end; - max++; - } - - if (next[0] == type && next[1] == *begin && max >= 1) - { - next_end = bracketend(next + 1); - if (next_end - next == (length + 1) && memcmp(begin, next + 1, IN_UCHARS(length)) == 0) - { - for (i = 0; i < max; i++, next_end += 1 + LINK_SIZE) - if (*next_end != OP_KET) - break; - - if (i == max) - { - common->private_data_ptrs[max_end - common->start - LINK_SIZE] = next_end - max_end; - common->private_data_ptrs[max_end - common->start - LINK_SIZE + 1] = (type == OP_BRAZERO) ? OP_UPTO : OP_MINUPTO; - /* +2 the original and the last. */ - common->private_data_ptrs[max_end - common->start - LINK_SIZE + 2] = max + 2; - if (min == 1) - return TRUE; - min--; - max_end -= (1 + LINK_SIZE) + GET(max_end, -LINK_SIZE); - } - } - } - } - -if (min >= 3) - { - common->private_data_ptrs[end - common->start - LINK_SIZE] = max_end - end; - common->private_data_ptrs[end - common->start - LINK_SIZE + 1] = OP_EXACT; - common->private_data_ptrs[end - common->start - LINK_SIZE + 2] = min; - return TRUE; - } - -return FALSE; -} - -#define CASE_ITERATOR_PRIVATE_DATA_1 \ - case OP_MINSTAR: \ - case OP_MINPLUS: \ - case OP_QUERY: \ - case OP_MINQUERY: \ - case OP_MINSTARI: \ - case OP_MINPLUSI: \ - case OP_QUERYI: \ - case OP_MINQUERYI: \ - case OP_NOTMINSTAR: \ - case OP_NOTMINPLUS: \ - case OP_NOTQUERY: \ - case OP_NOTMINQUERY: \ - case OP_NOTMINSTARI: \ - case OP_NOTMINPLUSI: \ - case OP_NOTQUERYI: \ - case OP_NOTMINQUERYI: - -#define CASE_ITERATOR_PRIVATE_DATA_2A \ - case OP_STAR: \ - case OP_PLUS: \ - case OP_STARI: \ - case OP_PLUSI: \ - case OP_NOTSTAR: \ - case OP_NOTPLUS: \ - case OP_NOTSTARI: \ - case OP_NOTPLUSI: - -#define CASE_ITERATOR_PRIVATE_DATA_2B \ - case OP_UPTO: \ - case OP_MINUPTO: \ - case OP_UPTOI: \ - case OP_MINUPTOI: \ - case OP_NOTUPTO: \ - case OP_NOTMINUPTO: \ - case OP_NOTUPTOI: \ - case OP_NOTMINUPTOI: - -#define CASE_ITERATOR_TYPE_PRIVATE_DATA_1 \ - case OP_TYPEMINSTAR: \ - case OP_TYPEMINPLUS: \ - case OP_TYPEQUERY: \ - case OP_TYPEMINQUERY: - -#define CASE_ITERATOR_TYPE_PRIVATE_DATA_2A \ - case OP_TYPESTAR: \ - case OP_TYPEPLUS: - -#define CASE_ITERATOR_TYPE_PRIVATE_DATA_2B \ - case OP_TYPEUPTO: \ - case OP_TYPEMINUPTO: - -static void set_private_data_ptrs(compiler_common *common, int *private_data_start, pcre_uchar *ccend) -{ -pcre_uchar *cc = common->start; -pcre_uchar *alternative; -pcre_uchar *end = NULL; -int private_data_ptr = *private_data_start; -int space, size, bracketlen; - -while (cc < ccend) - { - space = 0; - size = 0; - bracketlen = 0; - if (private_data_ptr > SLJIT_MAX_LOCAL_SIZE) - return; - - if (*cc == OP_ONCE || *cc == OP_ONCE_NC || *cc == OP_BRA || *cc == OP_CBRA || *cc == OP_COND) - if (detect_repeat(common, cc)) - { - /* These brackets are converted to repeats, so no global - based single character repeat is allowed. */ - if (cc >= end) - end = bracketend(cc); - } - - switch(*cc) - { - case OP_KET: - if (common->private_data_ptrs[cc + 1 - common->start] != 0) - { - common->private_data_ptrs[cc - common->start] = private_data_ptr; - private_data_ptr += sizeof(sljit_sw); - cc += common->private_data_ptrs[cc + 1 - common->start]; - } - cc += 1 + LINK_SIZE; - break; - - case OP_ASSERT: - case OP_ASSERT_NOT: - case OP_ASSERTBACK: - case OP_ASSERTBACK_NOT: - case OP_ONCE: - case OP_ONCE_NC: - case OP_BRAPOS: - case OP_SBRA: - case OP_SBRAPOS: - case OP_SCOND: - common->private_data_ptrs[cc - common->start] = private_data_ptr; - private_data_ptr += sizeof(sljit_sw); - bracketlen = 1 + LINK_SIZE; - break; - - case OP_CBRAPOS: - case OP_SCBRAPOS: - common->private_data_ptrs[cc - common->start] = private_data_ptr; - private_data_ptr += sizeof(sljit_sw); - bracketlen = 1 + LINK_SIZE + IMM2_SIZE; - break; - - case OP_COND: - /* Might be a hidden SCOND. */ - alternative = cc + GET(cc, 1); - if (*alternative == OP_KETRMAX || *alternative == OP_KETRMIN) - { - common->private_data_ptrs[cc - common->start] = private_data_ptr; - private_data_ptr += sizeof(sljit_sw); - } - bracketlen = 1 + LINK_SIZE; - break; - - case OP_BRA: - bracketlen = 1 + LINK_SIZE; - break; - - case OP_CBRA: - case OP_SCBRA: - bracketlen = 1 + LINK_SIZE + IMM2_SIZE; - break; - - CASE_ITERATOR_PRIVATE_DATA_1 - space = 1; - size = -2; - break; - - CASE_ITERATOR_PRIVATE_DATA_2A - space = 2; - size = -2; - break; - - CASE_ITERATOR_PRIVATE_DATA_2B - space = 2; - size = -(2 + IMM2_SIZE); - break; - - CASE_ITERATOR_TYPE_PRIVATE_DATA_1 - space = 1; - size = 1; - break; - - CASE_ITERATOR_TYPE_PRIVATE_DATA_2A - if (cc[1] != OP_ANYNL && cc[1] != OP_EXTUNI) - space = 2; - size = 1; - break; - - CASE_ITERATOR_TYPE_PRIVATE_DATA_2B - if (cc[1 + IMM2_SIZE] != OP_ANYNL && cc[1 + IMM2_SIZE] != OP_EXTUNI) - space = 2; - size = 1 + IMM2_SIZE; - break; - - case OP_CLASS: - case OP_NCLASS: - size += 1 + 32 / sizeof(pcre_uchar); - space = get_class_iterator_size(cc + size); - break; - -#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 - case OP_XCLASS: - size = GET(cc, 1); - space = get_class_iterator_size(cc + size); - break; -#endif - - default: - cc = next_opcode(common, cc); - SLJIT_ASSERT(cc != NULL); - break; - } - - /* Character iterators, which are not inside a repeated bracket, - gets a private slot instead of allocating it on the stack. */ - if (space > 0 && cc >= end) - { - common->private_data_ptrs[cc - common->start] = private_data_ptr; - private_data_ptr += sizeof(sljit_sw) * space; - } - - if (size != 0) - { - if (size < 0) - { - cc += -size; -#ifdef SUPPORT_UTF - if (common->utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]); -#endif - } - else - cc += size; - } - - if (bracketlen > 0) - { - if (cc >= end) - { - end = bracketend(cc); - if (end[-1 - LINK_SIZE] == OP_KET) - end = NULL; - } - cc += bracketlen; - } - } -*private_data_start = private_data_ptr; -} - -/* Returns with a frame_types (always < 0) if no need for frame. */ -static int get_framesize(compiler_common *common, pcre_uchar *cc, pcre_uchar *ccend, BOOL recursive, BOOL* needs_control_head) -{ -int length = 0; -int possessive = 0; -BOOL stack_restore = FALSE; -BOOL setsom_found = recursive; -BOOL setmark_found = recursive; -/* The last capture is a local variable even for recursions. */ -BOOL capture_last_found = FALSE; - -#if defined DEBUG_FORCE_CONTROL_HEAD && DEBUG_FORCE_CONTROL_HEAD -SLJIT_ASSERT(common->control_head_ptr != 0); -*needs_control_head = TRUE; -#else -*needs_control_head = FALSE; -#endif - -if (ccend == NULL) - { - ccend = bracketend(cc) - (1 + LINK_SIZE); - if (!recursive && (*cc == OP_CBRAPOS || *cc == OP_SCBRAPOS)) - { - possessive = length = (common->capture_last_ptr != 0) ? 5 : 3; - /* This is correct regardless of common->capture_last_ptr. */ - capture_last_found = TRUE; - } - cc = next_opcode(common, cc); - } - -SLJIT_ASSERT(cc != NULL); -while (cc < ccend) - switch(*cc) - { - case OP_SET_SOM: - SLJIT_ASSERT(common->has_set_som); - stack_restore = TRUE; - if (!setsom_found) - { - length += 2; - setsom_found = TRUE; - } - cc += 1; - break; - - case OP_MARK: - case OP_PRUNE_ARG: - case OP_THEN_ARG: - SLJIT_ASSERT(common->mark_ptr != 0); - stack_restore = TRUE; - if (!setmark_found) - { - length += 2; - setmark_found = TRUE; - } - if (common->control_head_ptr != 0) - *needs_control_head = TRUE; - cc += 1 + 2 + cc[1]; - break; - - case OP_RECURSE: - stack_restore = TRUE; - if (common->has_set_som && !setsom_found) - { - length += 2; - setsom_found = TRUE; - } - if (common->mark_ptr != 0 && !setmark_found) - { - length += 2; - setmark_found = TRUE; - } - if (common->capture_last_ptr != 0 && !capture_last_found) - { - length += 2; - capture_last_found = TRUE; - } - cc += 1 + LINK_SIZE; - break; - - case OP_CBRA: - case OP_CBRAPOS: - case OP_SCBRA: - case OP_SCBRAPOS: - stack_restore = TRUE; - if (common->capture_last_ptr != 0 && !capture_last_found) - { - length += 2; - capture_last_found = TRUE; - } - length += 3; - cc += 1 + LINK_SIZE + IMM2_SIZE; - break; - - default: - stack_restore = TRUE; - /* Fall through. */ - - case OP_NOT_WORD_BOUNDARY: - case OP_WORD_BOUNDARY: - case OP_NOT_DIGIT: - case OP_DIGIT: - case OP_NOT_WHITESPACE: - case OP_WHITESPACE: - case OP_NOT_WORDCHAR: - case OP_WORDCHAR: - case OP_ANY: - case OP_ALLANY: - case OP_ANYBYTE: - case OP_NOTPROP: - case OP_PROP: - case OP_ANYNL: - case OP_NOT_HSPACE: - case OP_HSPACE: - case OP_NOT_VSPACE: - case OP_VSPACE: - case OP_EXTUNI: - case OP_EODN: - case OP_EOD: - case OP_CIRC: - case OP_CIRCM: - case OP_DOLL: - case OP_DOLLM: - case OP_CHAR: - case OP_CHARI: - case OP_NOT: - case OP_NOTI: - - case OP_EXACT: - case OP_POSSTAR: - case OP_POSPLUS: - case OP_POSQUERY: - case OP_POSUPTO: - - case OP_EXACTI: - case OP_POSSTARI: - case OP_POSPLUSI: - case OP_POSQUERYI: - case OP_POSUPTOI: - - case OP_NOTEXACT: - case OP_NOTPOSSTAR: - case OP_NOTPOSPLUS: - case OP_NOTPOSQUERY: - case OP_NOTPOSUPTO: - - case OP_NOTEXACTI: - case OP_NOTPOSSTARI: - case OP_NOTPOSPLUSI: - case OP_NOTPOSQUERYI: - case OP_NOTPOSUPTOI: - - case OP_TYPEEXACT: - case OP_TYPEPOSSTAR: - case OP_TYPEPOSPLUS: - case OP_TYPEPOSQUERY: - case OP_TYPEPOSUPTO: - - case OP_CLASS: - case OP_NCLASS: - case OP_XCLASS: - - cc = next_opcode(common, cc); - SLJIT_ASSERT(cc != NULL); - break; - } - -/* Possessive quantifiers can use a special case. */ -if (SLJIT_UNLIKELY(possessive == length)) - return stack_restore ? no_frame : no_stack; - -if (length > 0) - return length + 1; -return stack_restore ? no_frame : no_stack; -} - -static void init_frame(compiler_common *common, pcre_uchar *cc, pcre_uchar *ccend, int stackpos, int stacktop, BOOL recursive) -{ -DEFINE_COMPILER; -BOOL setsom_found = recursive; -BOOL setmark_found = recursive; -/* The last capture is a local variable even for recursions. */ -BOOL capture_last_found = FALSE; -int offset; - -/* >= 1 + shortest item size (2) */ -SLJIT_UNUSED_ARG(stacktop); -SLJIT_ASSERT(stackpos >= stacktop + 2); - -stackpos = STACK(stackpos); -if (ccend == NULL) - { - ccend = bracketend(cc) - (1 + LINK_SIZE); - if (recursive || (*cc != OP_CBRAPOS && *cc != OP_SCBRAPOS)) - cc = next_opcode(common, cc); - } - -SLJIT_ASSERT(cc != NULL); -while (cc < ccend) - switch(*cc) - { - case OP_SET_SOM: - SLJIT_ASSERT(common->has_set_som); - if (!setsom_found) - { - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(0)); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, SLJIT_IMM, -OVECTOR(0)); - stackpos += (int)sizeof(sljit_sw); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, TMP1, 0); - stackpos += (int)sizeof(sljit_sw); - setsom_found = TRUE; - } - cc += 1; - break; - - case OP_MARK: - case OP_PRUNE_ARG: - case OP_THEN_ARG: - SLJIT_ASSERT(common->mark_ptr != 0); - if (!setmark_found) - { - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->mark_ptr); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, SLJIT_IMM, -common->mark_ptr); - stackpos += (int)sizeof(sljit_sw); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, TMP1, 0); - stackpos += (int)sizeof(sljit_sw); - setmark_found = TRUE; - } - cc += 1 + 2 + cc[1]; - break; - - case OP_RECURSE: - if (common->has_set_som && !setsom_found) - { - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(0)); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, SLJIT_IMM, -OVECTOR(0)); - stackpos += (int)sizeof(sljit_sw); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, TMP1, 0); - stackpos += (int)sizeof(sljit_sw); - setsom_found = TRUE; - } - if (common->mark_ptr != 0 && !setmark_found) - { - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->mark_ptr); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, SLJIT_IMM, -common->mark_ptr); - stackpos += (int)sizeof(sljit_sw); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, TMP1, 0); - stackpos += (int)sizeof(sljit_sw); - setmark_found = TRUE; - } - if (common->capture_last_ptr != 0 && !capture_last_found) - { - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->capture_last_ptr); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, SLJIT_IMM, -common->capture_last_ptr); - stackpos += (int)sizeof(sljit_sw); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, TMP1, 0); - stackpos += (int)sizeof(sljit_sw); - capture_last_found = TRUE; - } - cc += 1 + LINK_SIZE; - break; - - case OP_CBRA: - case OP_CBRAPOS: - case OP_SCBRA: - case OP_SCBRAPOS: - if (common->capture_last_ptr != 0 && !capture_last_found) - { - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->capture_last_ptr); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, SLJIT_IMM, -common->capture_last_ptr); - stackpos += (int)sizeof(sljit_sw); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, TMP1, 0); - stackpos += (int)sizeof(sljit_sw); - capture_last_found = TRUE; - } - offset = (GET2(cc, 1 + LINK_SIZE)) << 1; - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, SLJIT_IMM, OVECTOR(offset)); - stackpos += (int)sizeof(sljit_sw); - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset)); - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1)); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, TMP1, 0); - stackpos += (int)sizeof(sljit_sw); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, TMP2, 0); - stackpos += (int)sizeof(sljit_sw); - - cc += 1 + LINK_SIZE + IMM2_SIZE; - break; - - default: - cc = next_opcode(common, cc); - SLJIT_ASSERT(cc != NULL); - break; - } - -OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackpos, SLJIT_IMM, 0); -SLJIT_ASSERT(stackpos == STACK(stacktop)); -} - -static SLJIT_INLINE int get_private_data_copy_length(compiler_common *common, pcre_uchar *cc, pcre_uchar *ccend, BOOL needs_control_head) -{ -int private_data_length = needs_control_head ? 3 : 2; -int size; -pcre_uchar *alternative; -/* Calculate the sum of the private machine words. */ -while (cc < ccend) - { - size = 0; - switch(*cc) - { - case OP_KET: - if (PRIVATE_DATA(cc) != 0) - private_data_length++; - cc += 1 + LINK_SIZE; - break; - - case OP_ASSERT: - case OP_ASSERT_NOT: - case OP_ASSERTBACK: - case OP_ASSERTBACK_NOT: - case OP_ONCE: - case OP_ONCE_NC: - case OP_BRAPOS: - case OP_SBRA: - case OP_SBRAPOS: - case OP_SCOND: - private_data_length++; - cc += 1 + LINK_SIZE; - break; - - case OP_CBRA: - case OP_SCBRA: - if (common->optimized_cbracket[GET2(cc, 1 + LINK_SIZE)] == 0) - private_data_length++; - cc += 1 + LINK_SIZE + IMM2_SIZE; - break; - - case OP_CBRAPOS: - case OP_SCBRAPOS: - private_data_length += 2; - cc += 1 + LINK_SIZE + IMM2_SIZE; - break; - - case OP_COND: - /* Might be a hidden SCOND. */ - alternative = cc + GET(cc, 1); - if (*alternative == OP_KETRMAX || *alternative == OP_KETRMIN) - private_data_length++; - cc += 1 + LINK_SIZE; - break; - - CASE_ITERATOR_PRIVATE_DATA_1 - if (PRIVATE_DATA(cc)) - private_data_length++; - cc += 2; -#ifdef SUPPORT_UTF - if (common->utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]); -#endif - break; - - CASE_ITERATOR_PRIVATE_DATA_2A - if (PRIVATE_DATA(cc)) - private_data_length += 2; - cc += 2; -#ifdef SUPPORT_UTF - if (common->utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]); -#endif - break; - - CASE_ITERATOR_PRIVATE_DATA_2B - if (PRIVATE_DATA(cc)) - private_data_length += 2; - cc += 2 + IMM2_SIZE; -#ifdef SUPPORT_UTF - if (common->utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]); -#endif - break; - - CASE_ITERATOR_TYPE_PRIVATE_DATA_1 - if (PRIVATE_DATA(cc)) - private_data_length++; - cc += 1; - break; - - CASE_ITERATOR_TYPE_PRIVATE_DATA_2A - if (PRIVATE_DATA(cc)) - private_data_length += 2; - cc += 1; - break; - - CASE_ITERATOR_TYPE_PRIVATE_DATA_2B - if (PRIVATE_DATA(cc)) - private_data_length += 2; - cc += 1 + IMM2_SIZE; - break; - - case OP_CLASS: - case OP_NCLASS: -#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 - case OP_XCLASS: - size = (*cc == OP_XCLASS) ? GET(cc, 1) : 1 + 32 / (int)sizeof(pcre_uchar); -#else - size = 1 + 32 / (int)sizeof(pcre_uchar); -#endif - if (PRIVATE_DATA(cc)) - private_data_length += get_class_iterator_size(cc + size); - cc += size; - break; - - default: - cc = next_opcode(common, cc); - SLJIT_ASSERT(cc != NULL); - break; - } - } -SLJIT_ASSERT(cc == ccend); -return private_data_length; -} - -static void copy_private_data(compiler_common *common, pcre_uchar *cc, pcre_uchar *ccend, - BOOL save, int stackptr, int stacktop, BOOL needs_control_head) -{ -DEFINE_COMPILER; -int srcw[2]; -int count, size; -BOOL tmp1next = TRUE; -BOOL tmp1empty = TRUE; -BOOL tmp2empty = TRUE; -pcre_uchar *alternative; -enum { - start, - loop, - end -} status; - -status = save ? start : loop; -stackptr = STACK(stackptr - 2); -stacktop = STACK(stacktop - 1); - -if (!save) - { - stackptr += (needs_control_head ? 2 : 1) * sizeof(sljit_sw); - if (stackptr < stacktop) - { - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), stackptr); - stackptr += sizeof(sljit_sw); - tmp1empty = FALSE; - } - if (stackptr < stacktop) - { - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), stackptr); - stackptr += sizeof(sljit_sw); - tmp2empty = FALSE; - } - /* The tmp1next must be TRUE in either way. */ - } - -do - { - count = 0; - switch(status) - { - case start: - SLJIT_ASSERT(save && common->recursive_head_ptr != 0); - count = 1; - srcw[0] = common->recursive_head_ptr; - if (needs_control_head) - { - SLJIT_ASSERT(common->control_head_ptr != 0); - count = 2; - srcw[1] = common->control_head_ptr; - } - status = loop; - break; - - case loop: - if (cc >= ccend) - { - status = end; - break; - } - - switch(*cc) - { - case OP_KET: - if (PRIVATE_DATA(cc) != 0) - { - count = 1; - srcw[0] = PRIVATE_DATA(cc); - } - cc += 1 + LINK_SIZE; - break; - - case OP_ASSERT: - case OP_ASSERT_NOT: - case OP_ASSERTBACK: - case OP_ASSERTBACK_NOT: - case OP_ONCE: - case OP_ONCE_NC: - case OP_BRAPOS: - case OP_SBRA: - case OP_SBRAPOS: - case OP_SCOND: - count = 1; - srcw[0] = PRIVATE_DATA(cc); - SLJIT_ASSERT(srcw[0] != 0); - cc += 1 + LINK_SIZE; - break; - - case OP_CBRA: - case OP_SCBRA: - if (common->optimized_cbracket[GET2(cc, 1 + LINK_SIZE)] == 0) - { - count = 1; - srcw[0] = OVECTOR_PRIV(GET2(cc, 1 + LINK_SIZE)); - } - cc += 1 + LINK_SIZE + IMM2_SIZE; - break; - - case OP_CBRAPOS: - case OP_SCBRAPOS: - count = 2; - srcw[0] = PRIVATE_DATA(cc); - srcw[1] = OVECTOR_PRIV(GET2(cc, 1 + LINK_SIZE)); - SLJIT_ASSERT(srcw[0] != 0 && srcw[1] != 0); - cc += 1 + LINK_SIZE + IMM2_SIZE; - break; - - case OP_COND: - /* Might be a hidden SCOND. */ - alternative = cc + GET(cc, 1); - if (*alternative == OP_KETRMAX || *alternative == OP_KETRMIN) - { - count = 1; - srcw[0] = PRIVATE_DATA(cc); - SLJIT_ASSERT(srcw[0] != 0); - } - cc += 1 + LINK_SIZE; - break; - - CASE_ITERATOR_PRIVATE_DATA_1 - if (PRIVATE_DATA(cc)) - { - count = 1; - srcw[0] = PRIVATE_DATA(cc); - } - cc += 2; -#ifdef SUPPORT_UTF - if (common->utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]); -#endif - break; - - CASE_ITERATOR_PRIVATE_DATA_2A - if (PRIVATE_DATA(cc)) - { - count = 2; - srcw[0] = PRIVATE_DATA(cc); - srcw[1] = PRIVATE_DATA(cc) + sizeof(sljit_sw); - } - cc += 2; -#ifdef SUPPORT_UTF - if (common->utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]); -#endif - break; - - CASE_ITERATOR_PRIVATE_DATA_2B - if (PRIVATE_DATA(cc)) - { - count = 2; - srcw[0] = PRIVATE_DATA(cc); - srcw[1] = PRIVATE_DATA(cc) + sizeof(sljit_sw); - } - cc += 2 + IMM2_SIZE; -#ifdef SUPPORT_UTF - if (common->utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]); -#endif - break; - - CASE_ITERATOR_TYPE_PRIVATE_DATA_1 - if (PRIVATE_DATA(cc)) - { - count = 1; - srcw[0] = PRIVATE_DATA(cc); - } - cc += 1; - break; - - CASE_ITERATOR_TYPE_PRIVATE_DATA_2A - if (PRIVATE_DATA(cc)) - { - count = 2; - srcw[0] = PRIVATE_DATA(cc); - srcw[1] = srcw[0] + sizeof(sljit_sw); - } - cc += 1; - break; - - CASE_ITERATOR_TYPE_PRIVATE_DATA_2B - if (PRIVATE_DATA(cc)) - { - count = 2; - srcw[0] = PRIVATE_DATA(cc); - srcw[1] = srcw[0] + sizeof(sljit_sw); - } - cc += 1 + IMM2_SIZE; - break; - - case OP_CLASS: - case OP_NCLASS: -#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 - case OP_XCLASS: - size = (*cc == OP_XCLASS) ? GET(cc, 1) : 1 + 32 / (int)sizeof(pcre_uchar); -#else - size = 1 + 32 / (int)sizeof(pcre_uchar); -#endif - if (PRIVATE_DATA(cc)) - switch(get_class_iterator_size(cc + size)) - { - case 1: - count = 1; - srcw[0] = PRIVATE_DATA(cc); - break; - - case 2: - count = 2; - srcw[0] = PRIVATE_DATA(cc); - srcw[1] = srcw[0] + sizeof(sljit_sw); - break; - - default: - SLJIT_ASSERT_STOP(); - break; - } - cc += size; - break; - - default: - cc = next_opcode(common, cc); - SLJIT_ASSERT(cc != NULL); - break; - } - break; - - case end: - SLJIT_ASSERT_STOP(); - break; - } - - while (count > 0) - { - count--; - if (save) - { - if (tmp1next) - { - if (!tmp1empty) - { - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackptr, TMP1, 0); - stackptr += sizeof(sljit_sw); - } - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), srcw[count]); - tmp1empty = FALSE; - tmp1next = FALSE; - } - else - { - if (!tmp2empty) - { - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackptr, TMP2, 0); - stackptr += sizeof(sljit_sw); - } - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), srcw[count]); - tmp2empty = FALSE; - tmp1next = TRUE; - } - } - else - { - if (tmp1next) - { - SLJIT_ASSERT(!tmp1empty); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), srcw[count], TMP1, 0); - tmp1empty = stackptr >= stacktop; - if (!tmp1empty) - { - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), stackptr); - stackptr += sizeof(sljit_sw); - } - tmp1next = FALSE; - } - else - { - SLJIT_ASSERT(!tmp2empty); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), srcw[count], TMP2, 0); - tmp2empty = stackptr >= stacktop; - if (!tmp2empty) - { - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), stackptr); - stackptr += sizeof(sljit_sw); - } - tmp1next = TRUE; - } - } - } - } -while (status != end); - -if (save) - { - if (tmp1next) - { - if (!tmp1empty) - { - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackptr, TMP1, 0); - stackptr += sizeof(sljit_sw); - } - if (!tmp2empty) - { - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackptr, TMP2, 0); - stackptr += sizeof(sljit_sw); - } - } - else - { - if (!tmp2empty) - { - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackptr, TMP2, 0); - stackptr += sizeof(sljit_sw); - } - if (!tmp1empty) - { - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), stackptr, TMP1, 0); - stackptr += sizeof(sljit_sw); - } - } - } -SLJIT_ASSERT(cc == ccend && stackptr == stacktop && (save || (tmp1empty && tmp2empty))); -} - -static SLJIT_INLINE pcre_uchar *set_then_offsets(compiler_common *common, pcre_uchar *cc, pcre_uint8 *current_offset) -{ -pcre_uchar *end = bracketend(cc); -BOOL has_alternatives = cc[GET(cc, 1)] == OP_ALT; - -/* Assert captures then. */ -if (*cc >= OP_ASSERT && *cc <= OP_ASSERTBACK_NOT) - current_offset = NULL; -/* Conditional block does not. */ -if (*cc == OP_COND || *cc == OP_SCOND) - has_alternatives = FALSE; - -cc = next_opcode(common, cc); -if (has_alternatives) - current_offset = common->then_offsets + (cc - common->start); - -while (cc < end) - { - if ((*cc >= OP_ASSERT && *cc <= OP_ASSERTBACK_NOT) || (*cc >= OP_ONCE && *cc <= OP_SCOND)) - cc = set_then_offsets(common, cc, current_offset); - else - { - if (*cc == OP_ALT && has_alternatives) - current_offset = common->then_offsets + (cc + 1 + LINK_SIZE - common->start); - if (*cc >= OP_THEN && *cc <= OP_THEN_ARG && current_offset != NULL) - *current_offset = 1; - cc = next_opcode(common, cc); - } - } - -return end; -} - -#undef CASE_ITERATOR_PRIVATE_DATA_1 -#undef CASE_ITERATOR_PRIVATE_DATA_2A -#undef CASE_ITERATOR_PRIVATE_DATA_2B -#undef CASE_ITERATOR_TYPE_PRIVATE_DATA_1 -#undef CASE_ITERATOR_TYPE_PRIVATE_DATA_2A -#undef CASE_ITERATOR_TYPE_PRIVATE_DATA_2B - -static SLJIT_INLINE BOOL is_powerof2(unsigned int value) -{ -return (value & (value - 1)) == 0; -} - -static SLJIT_INLINE void set_jumps(jump_list *list, struct sljit_label *label) -{ -while (list) - { - /* sljit_set_label is clever enough to do nothing - if either the jump or the label is NULL. */ - SET_LABEL(list->jump, label); - list = list->next; - } -} - -static SLJIT_INLINE void add_jump(struct sljit_compiler *compiler, jump_list **list, struct sljit_jump* jump) -{ -jump_list *list_item = sljit_alloc_memory(compiler, sizeof(jump_list)); -if (list_item) - { - list_item->next = *list; - list_item->jump = jump; - *list = list_item; - } -} - -static void add_stub(compiler_common *common, struct sljit_jump *start) -{ -DEFINE_COMPILER; -stub_list* list_item = sljit_alloc_memory(compiler, sizeof(stub_list)); - -if (list_item) - { - list_item->start = start; - list_item->quit = LABEL(); - list_item->next = common->stubs; - common->stubs = list_item; - } -} - -static void flush_stubs(compiler_common *common) -{ -DEFINE_COMPILER; -stub_list* list_item = common->stubs; - -while (list_item) - { - JUMPHERE(list_item->start); - add_jump(compiler, &common->stackalloc, JUMP(SLJIT_FAST_CALL)); - JUMPTO(SLJIT_JUMP, list_item->quit); - list_item = list_item->next; - } -common->stubs = NULL; -} - -static void add_label_addr(compiler_common *common, sljit_uw *update_addr) -{ -DEFINE_COMPILER; -label_addr_list *label_addr; - -label_addr = sljit_alloc_memory(compiler, sizeof(label_addr_list)); -if (label_addr == NULL) - return; -label_addr->label = LABEL(); -label_addr->update_addr = update_addr; -label_addr->next = common->label_addrs; -common->label_addrs = label_addr; -} - -static SLJIT_INLINE void count_match(compiler_common *common) -{ -DEFINE_COMPILER; - -OP2(SLJIT_SUB | SLJIT_SET_E, COUNT_MATCH, 0, COUNT_MATCH, 0, SLJIT_IMM, 1); -add_jump(compiler, &common->calllimit, JUMP(SLJIT_C_ZERO)); -} - -static SLJIT_INLINE void allocate_stack(compiler_common *common, int size) -{ -/* May destroy all locals and registers except TMP2. */ -DEFINE_COMPILER; - -OP2(SLJIT_ADD, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, size * sizeof(sljit_sw)); -#ifdef DESTROY_REGISTERS -OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, 12345); -OP1(SLJIT_MOV, TMP3, 0, TMP1, 0); -OP1(SLJIT_MOV, RETURN_ADDR, 0, TMP1, 0); -OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS0, TMP1, 0); -OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS1, TMP1, 0); -#endif -add_stub(common, CMP(SLJIT_C_GREATER, STACK_TOP, 0, STACK_LIMIT, 0)); -} - -static SLJIT_INLINE void free_stack(compiler_common *common, int size) -{ -DEFINE_COMPILER; -OP2(SLJIT_SUB, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, size * sizeof(sljit_sw)); -} - -static SLJIT_INLINE void reset_ovector(compiler_common *common, int length) -{ -DEFINE_COMPILER; -struct sljit_label *loop; -int i; - -/* At this point we can freely use all temporary registers. */ -SLJIT_ASSERT(length > 1); -/* TMP1 returns with begin - 1. */ -OP2(SLJIT_SUB, SLJIT_R0, 0, SLJIT_MEM1(SLJIT_S0), SLJIT_OFFSETOF(jit_arguments, begin), SLJIT_IMM, IN_UCHARS(1)); -if (length < 8) - { - for (i = 1; i < length; i++) - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(i), SLJIT_R0, 0); - } -else - { - GET_LOCAL_BASE(SLJIT_R1, 0, OVECTOR_START); - OP1(SLJIT_MOV, SLJIT_R2, 0, SLJIT_IMM, length - 1); - loop = LABEL(); - OP1(SLJIT_MOVU, SLJIT_MEM1(SLJIT_R1), sizeof(sljit_sw), SLJIT_R0, 0); - OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_R2, 0, SLJIT_R2, 0, SLJIT_IMM, 1); - JUMPTO(SLJIT_C_NOT_ZERO, loop); - } -} - -static SLJIT_INLINE void do_reset_match(compiler_common *common, int length) -{ -DEFINE_COMPILER; -struct sljit_label *loop; -int i; - -SLJIT_ASSERT(length > 1); -/* OVECTOR(1) contains the "string begin - 1" constant. */ -if (length > 2) - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(1)); -if (length < 8) - { - for (i = 2; i < length; i++) - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(i), TMP1, 0); - } -else - { - GET_LOCAL_BASE(TMP2, 0, OVECTOR_START + sizeof(sljit_sw)); - OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_IMM, length - 2); - loop = LABEL(); - OP1(SLJIT_MOVU, SLJIT_MEM1(TMP2), sizeof(sljit_sw), TMP1, 0); - OP2(SLJIT_SUB | SLJIT_SET_E, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, 1); - JUMPTO(SLJIT_C_NOT_ZERO, loop); - } - -OP1(SLJIT_MOV, STACK_TOP, 0, ARGUMENTS, 0); -if (common->mark_ptr != 0) - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->mark_ptr, SLJIT_IMM, 0); -if (common->control_head_ptr != 0) - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, SLJIT_IMM, 0); -OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(STACK_TOP), SLJIT_OFFSETOF(jit_arguments, stack)); -OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->start_ptr); -OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(STACK_TOP), SLJIT_OFFSETOF(struct sljit_stack, base)); -} - -static sljit_sw SLJIT_CALL do_search_mark(sljit_sw *current, const pcre_uchar *skip_arg) -{ -while (current != NULL) - { - switch (current[-2]) - { - case type_then_trap: - break; - - case type_mark: - if (STRCMP_UC_UC(skip_arg, (pcre_uchar *)current[-3]) == 0) - return current[-4]; - break; - - default: - SLJIT_ASSERT_STOP(); - break; - } - current = (sljit_sw*)current[-1]; - } -return -1; -} - -static SLJIT_INLINE void copy_ovector(compiler_common *common, int topbracket) -{ -DEFINE_COMPILER; -struct sljit_label *loop; -struct sljit_jump *early_quit; - -/* At this point we can freely use all registers. */ -OP1(SLJIT_MOV, SLJIT_S2, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(1)); -OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(1), STR_PTR, 0); - -OP1(SLJIT_MOV, SLJIT_R0, 0, ARGUMENTS, 0); -if (common->mark_ptr != 0) - OP1(SLJIT_MOV, SLJIT_R2, 0, SLJIT_MEM1(SLJIT_SP), common->mark_ptr); -OP1(SLJIT_MOV_SI, SLJIT_R1, 0, SLJIT_MEM1(SLJIT_R0), SLJIT_OFFSETOF(jit_arguments, offset_count)); -if (common->mark_ptr != 0) - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_R0), SLJIT_OFFSETOF(jit_arguments, mark_ptr), SLJIT_R2, 0); -OP2(SLJIT_SUB, SLJIT_R2, 0, SLJIT_MEM1(SLJIT_R0), SLJIT_OFFSETOF(jit_arguments, offsets), SLJIT_IMM, sizeof(int)); -OP1(SLJIT_MOV, SLJIT_R0, 0, SLJIT_MEM1(SLJIT_R0), SLJIT_OFFSETOF(jit_arguments, begin)); -GET_LOCAL_BASE(SLJIT_S0, 0, OVECTOR_START); -/* Unlikely, but possible */ -early_quit = CMP(SLJIT_C_EQUAL, SLJIT_R1, 0, SLJIT_IMM, 0); -loop = LABEL(); -OP2(SLJIT_SUB, SLJIT_S1, 0, SLJIT_MEM1(SLJIT_S0), 0, SLJIT_R0, 0); -OP2(SLJIT_ADD, SLJIT_S0, 0, SLJIT_S0, 0, SLJIT_IMM, sizeof(sljit_sw)); -/* Copy the integer value to the output buffer */ -#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 -OP2(SLJIT_ASHR, SLJIT_S1, 0, SLJIT_S1, 0, SLJIT_IMM, UCHAR_SHIFT); -#endif -OP1(SLJIT_MOVU_SI, SLJIT_MEM1(SLJIT_R2), sizeof(int), SLJIT_S1, 0); -OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_R1, 0, SLJIT_R1, 0, SLJIT_IMM, 1); -JUMPTO(SLJIT_C_NOT_ZERO, loop); -JUMPHERE(early_quit); - -/* Calculate the return value, which is the maximum ovector value. */ -if (topbracket > 1) - { - GET_LOCAL_BASE(SLJIT_R0, 0, OVECTOR_START + topbracket * 2 * sizeof(sljit_sw)); - OP1(SLJIT_MOV, SLJIT_R1, 0, SLJIT_IMM, topbracket + 1); - - /* OVECTOR(0) is never equal to SLJIT_S2. */ - loop = LABEL(); - OP1(SLJIT_MOVU, SLJIT_R2, 0, SLJIT_MEM1(SLJIT_R0), -(2 * (sljit_sw)sizeof(sljit_sw))); - OP2(SLJIT_SUB, SLJIT_R1, 0, SLJIT_R1, 0, SLJIT_IMM, 1); - CMPTO(SLJIT_C_EQUAL, SLJIT_R2, 0, SLJIT_S2, 0, loop); - OP1(SLJIT_MOV, SLJIT_RETURN_REG, 0, SLJIT_R1, 0); - } -else - OP1(SLJIT_MOV, SLJIT_RETURN_REG, 0, SLJIT_IMM, 1); -} - -static SLJIT_INLINE void return_with_partial_match(compiler_common *common, struct sljit_label *quit) -{ -DEFINE_COMPILER; -struct sljit_jump *jump; - -SLJIT_COMPILE_ASSERT(STR_END == SLJIT_S1, str_end_must_be_saved_reg2); -SLJIT_ASSERT(common->start_used_ptr != 0 && common->start_ptr != 0 - && (common->mode == JIT_PARTIAL_SOFT_COMPILE ? common->hit_start != 0 : common->hit_start == 0)); - -OP1(SLJIT_MOV, SLJIT_R1, 0, ARGUMENTS, 0); -OP1(SLJIT_MOV, SLJIT_RETURN_REG, 0, SLJIT_IMM, PCRE_ERROR_PARTIAL); -OP1(SLJIT_MOV_SI, SLJIT_R2, 0, SLJIT_MEM1(SLJIT_R1), SLJIT_OFFSETOF(jit_arguments, real_offset_count)); -CMPTO(SLJIT_C_SIG_LESS, SLJIT_R2, 0, SLJIT_IMM, 2, quit); - -/* Store match begin and end. */ -OP1(SLJIT_MOV, SLJIT_S0, 0, SLJIT_MEM1(SLJIT_R1), SLJIT_OFFSETOF(jit_arguments, begin)); -OP1(SLJIT_MOV, SLJIT_R1, 0, SLJIT_MEM1(SLJIT_R1), SLJIT_OFFSETOF(jit_arguments, offsets)); - -jump = CMP(SLJIT_C_SIG_LESS, SLJIT_R2, 0, SLJIT_IMM, 3); -OP2(SLJIT_SUB, SLJIT_R2, 0, SLJIT_MEM1(SLJIT_SP), common->mode == JIT_PARTIAL_HARD_COMPILE ? common->start_ptr : (common->hit_start + (int)sizeof(sljit_sw)), SLJIT_S0, 0); -#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 -OP2(SLJIT_ASHR, SLJIT_R2, 0, SLJIT_R2, 0, SLJIT_IMM, UCHAR_SHIFT); -#endif -OP1(SLJIT_MOV_SI, SLJIT_MEM1(SLJIT_R1), 2 * sizeof(int), SLJIT_R2, 0); -JUMPHERE(jump); - -OP1(SLJIT_MOV, SLJIT_R2, 0, SLJIT_MEM1(SLJIT_SP), common->mode == JIT_PARTIAL_HARD_COMPILE ? common->start_used_ptr : common->hit_start); -OP2(SLJIT_SUB, SLJIT_S1, 0, STR_END, 0, SLJIT_S0, 0); -#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 -OP2(SLJIT_ASHR, SLJIT_S1, 0, SLJIT_S1, 0, SLJIT_IMM, UCHAR_SHIFT); -#endif -OP1(SLJIT_MOV_SI, SLJIT_MEM1(SLJIT_R1), sizeof(int), SLJIT_S1, 0); - -OP2(SLJIT_SUB, SLJIT_R2, 0, SLJIT_R2, 0, SLJIT_S0, 0); -#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 -OP2(SLJIT_ASHR, SLJIT_R2, 0, SLJIT_R2, 0, SLJIT_IMM, UCHAR_SHIFT); -#endif -OP1(SLJIT_MOV_SI, SLJIT_MEM1(SLJIT_R1), 0, SLJIT_R2, 0); - -JUMPTO(SLJIT_JUMP, quit); -} - -static SLJIT_INLINE void check_start_used_ptr(compiler_common *common) -{ -/* May destroy TMP1. */ -DEFINE_COMPILER; -struct sljit_jump *jump; - -if (common->mode == JIT_PARTIAL_SOFT_COMPILE) - { - /* The value of -1 must be kept for start_used_ptr! */ - OP2(SLJIT_ADD, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->start_used_ptr, SLJIT_IMM, 1); - /* Jumps if start_used_ptr < STR_PTR, or start_used_ptr == -1. Although overwriting - is not necessary if start_used_ptr == STR_PTR, it does not hurt as well. */ - jump = CMP(SLJIT_C_LESS_EQUAL, TMP1, 0, STR_PTR, 0); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->start_used_ptr, STR_PTR, 0); - JUMPHERE(jump); - } -else if (common->mode == JIT_PARTIAL_HARD_COMPILE) - { - jump = CMP(SLJIT_C_LESS_EQUAL, SLJIT_MEM1(SLJIT_SP), common->start_used_ptr, STR_PTR, 0); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->start_used_ptr, STR_PTR, 0); - JUMPHERE(jump); - } -} - -static SLJIT_INLINE BOOL char_has_othercase(compiler_common *common, pcre_uchar* cc) -{ -/* Detects if the character has an othercase. */ -unsigned int c; - -#ifdef SUPPORT_UTF -if (common->utf) - { - GETCHAR(c, cc); - if (c > 127) - { -#ifdef SUPPORT_UCP - return c != UCD_OTHERCASE(c); -#else - return FALSE; -#endif - } -#ifndef COMPILE_PCRE8 - return common->fcc[c] != c; -#endif - } -else -#endif - c = *cc; -return MAX_255(c) ? common->fcc[c] != c : FALSE; -} - -static SLJIT_INLINE unsigned int char_othercase(compiler_common *common, unsigned int c) -{ -/* Returns with the othercase. */ -#ifdef SUPPORT_UTF -if (common->utf && c > 127) - { -#ifdef SUPPORT_UCP - return UCD_OTHERCASE(c); -#else - return c; -#endif - } -#endif -return TABLE_GET(c, common->fcc, c); -} - -static unsigned int char_get_othercase_bit(compiler_common *common, pcre_uchar* cc) -{ -/* Detects if the character and its othercase has only 1 bit difference. */ -unsigned int c, oc, bit; -#if defined SUPPORT_UTF && defined COMPILE_PCRE8 -int n; -#endif - -#ifdef SUPPORT_UTF -if (common->utf) - { - GETCHAR(c, cc); - if (c <= 127) - oc = common->fcc[c]; - else - { -#ifdef SUPPORT_UCP - oc = UCD_OTHERCASE(c); -#else - oc = c; -#endif - } - } -else - { - c = *cc; - oc = TABLE_GET(c, common->fcc, c); - } -#else -c = *cc; -oc = TABLE_GET(c, common->fcc, c); -#endif - -SLJIT_ASSERT(c != oc); - -bit = c ^ oc; -/* Optimized for English alphabet. */ -if (c <= 127 && bit == 0x20) - return (0 << 8) | 0x20; - -/* Since c != oc, they must have at least 1 bit difference. */ -if (!is_powerof2(bit)) - return 0; - -#if defined COMPILE_PCRE8 - -#ifdef SUPPORT_UTF -if (common->utf && c > 127) - { - n = GET_EXTRALEN(*cc); - while ((bit & 0x3f) == 0) - { - n--; - bit >>= 6; - } - return (n << 8) | bit; - } -#endif /* SUPPORT_UTF */ -return (0 << 8) | bit; - -#elif defined COMPILE_PCRE16 || defined COMPILE_PCRE32 - -#ifdef SUPPORT_UTF -if (common->utf && c > 65535) - { - if (bit >= (1 << 10)) - bit >>= 10; - else - return (bit < 256) ? ((2 << 8) | bit) : ((3 << 8) | (bit >> 8)); - } -#endif /* SUPPORT_UTF */ -return (bit < 256) ? ((0 << 8) | bit) : ((1 << 8) | (bit >> 8)); - -#endif /* COMPILE_PCRE[8|16|32] */ -} - -static void check_partial(compiler_common *common, BOOL force) -{ -/* Checks whether a partial matching is occurred. Does not modify registers. */ -DEFINE_COMPILER; -struct sljit_jump *jump = NULL; - -SLJIT_ASSERT(!force || common->mode != JIT_COMPILE); - -if (common->mode == JIT_COMPILE) - return; - -if (!force) - jump = CMP(SLJIT_C_GREATER_EQUAL, SLJIT_MEM1(SLJIT_SP), common->start_used_ptr, STR_PTR, 0); -else if (common->mode == JIT_PARTIAL_SOFT_COMPILE) - jump = CMP(SLJIT_C_EQUAL, SLJIT_MEM1(SLJIT_SP), common->start_used_ptr, SLJIT_IMM, -1); - -if (common->mode == JIT_PARTIAL_SOFT_COMPILE) - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->hit_start, SLJIT_IMM, 0); -else - { - if (common->partialmatchlabel != NULL) - JUMPTO(SLJIT_JUMP, common->partialmatchlabel); - else - add_jump(compiler, &common->partialmatch, JUMP(SLJIT_JUMP)); - } - -if (jump != NULL) - JUMPHERE(jump); -} - -static void check_str_end(compiler_common *common, jump_list **end_reached) -{ -/* Does not affect registers. Usually used in a tight spot. */ -DEFINE_COMPILER; -struct sljit_jump *jump; - -if (common->mode == JIT_COMPILE) - { - add_jump(compiler, end_reached, CMP(SLJIT_C_GREATER_EQUAL, STR_PTR, 0, STR_END, 0)); - return; - } - -jump = CMP(SLJIT_C_LESS, STR_PTR, 0, STR_END, 0); -if (common->mode == JIT_PARTIAL_SOFT_COMPILE) - { - add_jump(compiler, end_reached, CMP(SLJIT_C_GREATER_EQUAL, SLJIT_MEM1(SLJIT_SP), common->start_used_ptr, STR_PTR, 0)); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->hit_start, SLJIT_IMM, 0); - add_jump(compiler, end_reached, JUMP(SLJIT_JUMP)); - } -else - { - add_jump(compiler, end_reached, CMP(SLJIT_C_GREATER_EQUAL, SLJIT_MEM1(SLJIT_SP), common->start_used_ptr, STR_PTR, 0)); - if (common->partialmatchlabel != NULL) - JUMPTO(SLJIT_JUMP, common->partialmatchlabel); - else - add_jump(compiler, &common->partialmatch, JUMP(SLJIT_JUMP)); - } -JUMPHERE(jump); -} - -static void detect_partial_match(compiler_common *common, jump_list **backtracks) -{ -DEFINE_COMPILER; -struct sljit_jump *jump; - -if (common->mode == JIT_COMPILE) - { - add_jump(compiler, backtracks, CMP(SLJIT_C_GREATER_EQUAL, STR_PTR, 0, STR_END, 0)); - return; - } - -/* Partial matching mode. */ -jump = CMP(SLJIT_C_LESS, STR_PTR, 0, STR_END, 0); -add_jump(compiler, backtracks, CMP(SLJIT_C_GREATER_EQUAL, SLJIT_MEM1(SLJIT_SP), common->start_used_ptr, STR_PTR, 0)); -if (common->mode == JIT_PARTIAL_SOFT_COMPILE) - { - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->hit_start, SLJIT_IMM, 0); - add_jump(compiler, backtracks, JUMP(SLJIT_JUMP)); - } -else - { - if (common->partialmatchlabel != NULL) - JUMPTO(SLJIT_JUMP, common->partialmatchlabel); - else - add_jump(compiler, &common->partialmatch, JUMP(SLJIT_JUMP)); - } -JUMPHERE(jump); -} - -static void peek_char(compiler_common *common, pcre_uint32 max) -{ -/* Reads the character into TMP1, keeps STR_PTR. -Does not check STR_END. TMP2 Destroyed. */ -DEFINE_COMPILER; -#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 -struct sljit_jump *jump; -#endif - -SLJIT_UNUSED_ARG(max); - -OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), 0); -#if defined SUPPORT_UTF && defined COMPILE_PCRE8 -if (common->utf) - { - if (max < 128) return; - - jump = CMP(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, 0xc0); - OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); - add_jump(compiler, &common->utfreadchar, JUMP(SLJIT_FAST_CALL)); - OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, TMP2, 0); - JUMPHERE(jump); - } -#endif /* SUPPORT_UTF && !COMPILE_PCRE32 */ - -#if defined SUPPORT_UTF && defined COMPILE_PCRE16 -if (common->utf) - { - if (max < 0xd800) return; - - OP2(SLJIT_SUB, TMP2, 0, TMP1, 0, SLJIT_IMM, 0xd800); - jump = CMP(SLJIT_C_GREATER, TMP2, 0, SLJIT_IMM, 0xdc00 - 0xd800 - 1); - /* TMP2 contains the high surrogate. */ - OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); - OP2(SLJIT_ADD, TMP2, 0, TMP2, 0, SLJIT_IMM, 0x40); - OP2(SLJIT_SHL, TMP2, 0, TMP2, 0, SLJIT_IMM, 10); - OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x3ff); - OP2(SLJIT_OR, TMP1, 0, TMP1, 0, TMP2, 0); - JUMPHERE(jump); - } -#endif -} - -#if defined SUPPORT_UTF && defined COMPILE_PCRE8 - -static BOOL is_char7_bitset(const pcre_uint8 *bitset, BOOL nclass) -{ -/* Tells whether the character codes below 128 are enough -to determine a match. */ -const pcre_uint8 value = nclass ? 0xff : 0; -const pcre_uint8* end = bitset + 32; - -bitset += 16; -do - { - if (*bitset++ != value) - return FALSE; - } -while (bitset < end); -return TRUE; -} - -static void read_char7_type(compiler_common *common, BOOL full_read) -{ -/* Reads the precise character type of a character into TMP1, if the character -is less than 128. Otherwise it returns with zero. Does not check STR_END. The -full_read argument tells whether characters above max are accepted or not. */ -DEFINE_COMPILER; -struct sljit_jump *jump; - -SLJIT_ASSERT(common->utf); - -OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), 0); -OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); - -OP1(SLJIT_MOV_UB, TMP1, 0, SLJIT_MEM1(TMP2), common->ctypes); - -if (full_read) - { - jump = CMP(SLJIT_C_LESS, TMP2, 0, SLJIT_IMM, 0xc0); - OP1(SLJIT_MOV_UB, TMP2, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(utf8_table4) - 0xc0); - OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP2, 0); - JUMPHERE(jump); - } -} - -#endif /* SUPPORT_UTF && COMPILE_PCRE8 */ - -static void read_char_range(compiler_common *common, pcre_uint32 min, pcre_uint32 max, BOOL update_str_ptr) -{ -/* Reads the precise value of a character into TMP1, if the character is -between min and max (c >= min && c <= max). Otherwise it returns with a value -outside the range. Does not check STR_END. */ -DEFINE_COMPILER; -#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 -struct sljit_jump *jump; -#endif -#if defined SUPPORT_UTF && defined COMPILE_PCRE8 -struct sljit_jump *jump2; -#endif - -SLJIT_UNUSED_ARG(update_str_ptr); -SLJIT_UNUSED_ARG(min); -SLJIT_UNUSED_ARG(max); -SLJIT_ASSERT(min <= max); - -OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); -OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); - -#if defined SUPPORT_UTF && defined COMPILE_PCRE8 -if (common->utf) - { - if (max < 128 && !update_str_ptr) return; - - jump = CMP(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, 0xc0); - if (min >= 0x10000) - { - OP2(SLJIT_SUB, TMP2, 0, TMP1, 0, SLJIT_IMM, 0xf0); - if (update_str_ptr) - OP1(SLJIT_MOV_UB, RETURN_ADDR, 0, SLJIT_MEM1(TMP1), (sljit_sw)PRIV(utf8_table4) - 0xc0); - OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); - jump2 = CMP(SLJIT_C_GREATER, TMP2, 0, SLJIT_IMM, 0x7); - OP2(SLJIT_SHL, TMP2, 0, TMP2, 0, SLJIT_IMM, 6); - OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x3f); - OP2(SLJIT_OR, TMP1, 0, TMP1, 0, TMP2, 0); - OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(1)); - OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 6); - OP2(SLJIT_AND, TMP2, 0, TMP2, 0, SLJIT_IMM, 0x3f); - OP2(SLJIT_OR, TMP1, 0, TMP1, 0, TMP2, 0); - OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(2)); - if (!update_str_ptr) - OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(3)); - OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 6); - OP2(SLJIT_AND, TMP2, 0, TMP2, 0, SLJIT_IMM, 0x3f); - OP2(SLJIT_OR, TMP1, 0, TMP1, 0, TMP2, 0); - JUMPHERE(jump2); - if (update_str_ptr) - OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, RETURN_ADDR, 0); - } - else if (min >= 0x800 && max <= 0xffff) - { - OP2(SLJIT_SUB, TMP2, 0, TMP1, 0, SLJIT_IMM, 0xe0); - if (update_str_ptr) - OP1(SLJIT_MOV_UB, RETURN_ADDR, 0, SLJIT_MEM1(TMP1), (sljit_sw)PRIV(utf8_table4) - 0xc0); - OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); - jump2 = CMP(SLJIT_C_GREATER, TMP2, 0, SLJIT_IMM, 0xf); - OP2(SLJIT_SHL, TMP2, 0, TMP2, 0, SLJIT_IMM, 6); - OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x3f); - OP2(SLJIT_OR, TMP1, 0, TMP1, 0, TMP2, 0); - OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(1)); - if (!update_str_ptr) - OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(2)); - OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 6); - OP2(SLJIT_AND, TMP2, 0, TMP2, 0, SLJIT_IMM, 0x3f); - OP2(SLJIT_OR, TMP1, 0, TMP1, 0, TMP2, 0); - JUMPHERE(jump2); - if (update_str_ptr) - OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, RETURN_ADDR, 0); - } - else if (max >= 0x800) - add_jump(compiler, (max < 0x10000) ? &common->utfreadchar16 : &common->utfreadchar, JUMP(SLJIT_FAST_CALL)); - else if (max < 128) - { - OP1(SLJIT_MOV_UB, TMP2, 0, SLJIT_MEM1(TMP1), (sljit_sw)PRIV(utf8_table4) - 0xc0); - OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP2, 0); - } - else - { - OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); - if (!update_str_ptr) - OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); - else - OP1(SLJIT_MOV_UB, RETURN_ADDR, 0, SLJIT_MEM1(TMP1), (sljit_sw)PRIV(utf8_table4) - 0xc0); - OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x3f); - OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 6); - OP2(SLJIT_AND, TMP2, 0, TMP2, 0, SLJIT_IMM, 0x3f); - OP2(SLJIT_OR, TMP1, 0, TMP1, 0, TMP2, 0); - if (update_str_ptr) - OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, RETURN_ADDR, 0); - } - JUMPHERE(jump); - } -#endif - -#if defined SUPPORT_UTF && defined COMPILE_PCRE16 -if (common->utf) - { - if (max >= 0x10000) - { - OP2(SLJIT_SUB, TMP2, 0, TMP1, 0, SLJIT_IMM, 0xd800); - jump = CMP(SLJIT_C_GREATER, TMP2, 0, SLJIT_IMM, 0xdc00 - 0xd800 - 1); - /* TMP2 contains the high surrogate. */ - OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); - OP2(SLJIT_ADD, TMP2, 0, TMP2, 0, SLJIT_IMM, 0x40); - OP2(SLJIT_SHL, TMP2, 0, TMP2, 0, SLJIT_IMM, 10); - OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); - OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x3ff); - OP2(SLJIT_OR, TMP1, 0, TMP1, 0, TMP2, 0); - JUMPHERE(jump); - return; - } - - if (max < 0xd800 && !update_str_ptr) return; - - /* Skip low surrogate if necessary. */ - OP2(SLJIT_SUB, TMP2, 0, TMP1, 0, SLJIT_IMM, 0xd800); - jump = CMP(SLJIT_C_GREATER, TMP2, 0, SLJIT_IMM, 0xdc00 - 0xd800 - 1); - if (update_str_ptr) - OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); - if (max >= 0xd800) - OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, 0x10000); - JUMPHERE(jump); - } -#endif -} - -static SLJIT_INLINE void read_char(compiler_common *common) -{ -read_char_range(common, 0, READ_CHAR_MAX, TRUE); -} - -static void read_char8_type(compiler_common *common, BOOL update_str_ptr) -{ -/* Reads the character type into TMP1, updates STR_PTR. Does not check STR_END. */ -DEFINE_COMPILER; -#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 -struct sljit_jump *jump; -#endif -#if defined SUPPORT_UTF && defined COMPILE_PCRE8 -struct sljit_jump *jump2; -#endif - -SLJIT_UNUSED_ARG(update_str_ptr); - -OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), 0); -OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); - -#if defined SUPPORT_UTF && defined COMPILE_PCRE8 -if (common->utf) - { - /* This can be an extra read in some situations, but hopefully - it is needed in most cases. */ - OP1(SLJIT_MOV_UB, TMP1, 0, SLJIT_MEM1(TMP2), common->ctypes); - jump = CMP(SLJIT_C_LESS, TMP2, 0, SLJIT_IMM, 0xc0); - if (!update_str_ptr) - { - OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); - OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); - OP2(SLJIT_AND, TMP2, 0, TMP2, 0, SLJIT_IMM, 0x3f); - OP2(SLJIT_SHL, TMP2, 0, TMP2, 0, SLJIT_IMM, 6); - OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x3f); - OP2(SLJIT_OR, TMP2, 0, TMP2, 0, TMP1, 0); - OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, 0); - jump2 = CMP(SLJIT_C_GREATER, TMP2, 0, SLJIT_IMM, 255); - OP1(SLJIT_MOV_UB, TMP1, 0, SLJIT_MEM1(TMP2), common->ctypes); - JUMPHERE(jump2); - } - else - add_jump(compiler, &common->utfreadtype8, JUMP(SLJIT_FAST_CALL)); - JUMPHERE(jump); - return; - } -#endif /* SUPPORT_UTF && COMPILE_PCRE8 */ - -#if !defined COMPILE_PCRE8 -/* The ctypes array contains only 256 values. */ -OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, 0); -jump = CMP(SLJIT_C_GREATER, TMP2, 0, SLJIT_IMM, 255); -#endif -OP1(SLJIT_MOV_UB, TMP1, 0, SLJIT_MEM1(TMP2), common->ctypes); -#if !defined COMPILE_PCRE8 -JUMPHERE(jump); -#endif - -#if defined SUPPORT_UTF && defined COMPILE_PCRE16 -if (common->utf && update_str_ptr) - { - /* Skip low surrogate if necessary. */ - OP2(SLJIT_SUB, TMP2, 0, TMP2, 0, SLJIT_IMM, 0xd800); - jump = CMP(SLJIT_C_GREATER, TMP2, 0, SLJIT_IMM, 0xdc00 - 0xd800 - 1); - OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); - JUMPHERE(jump); - } -#endif /* SUPPORT_UTF && COMPILE_PCRE16 */ -} - -static void skip_char_back(compiler_common *common) -{ -/* Goes one character back. Affects STR_PTR and TMP1. Does not check begin. */ -DEFINE_COMPILER; -#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 -#if defined COMPILE_PCRE8 -struct sljit_label *label; - -if (common->utf) - { - label = LABEL(); - OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), -IN_UCHARS(1)); - OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); - OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0xc0); - CMPTO(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, 0x80, label); - return; - } -#elif defined COMPILE_PCRE16 -if (common->utf) - { - OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), -IN_UCHARS(1)); - OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); - /* Skip low surrogate if necessary. */ - OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0xfc00); - OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0xdc00); - OP_FLAGS(SLJIT_MOV, TMP1, 0, SLJIT_UNUSED, 0, SLJIT_C_EQUAL); - OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 1); - OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, TMP1, 0); - return; - } -#endif /* COMPILE_PCRE[8|16] */ -#endif /* SUPPORT_UTF && !COMPILE_PCRE32 */ -OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); -} - -static void check_newlinechar(compiler_common *common, int nltype, jump_list **backtracks, BOOL jumpifmatch) -{ -/* Character comes in TMP1. Checks if it is a newline. TMP2 may be destroyed. */ -DEFINE_COMPILER; -struct sljit_jump *jump; - -if (nltype == NLTYPE_ANY) - { - add_jump(compiler, &common->anynewline, JUMP(SLJIT_FAST_CALL)); - add_jump(compiler, backtracks, JUMP(jumpifmatch ? SLJIT_C_NOT_ZERO : SLJIT_C_ZERO)); - } -else if (nltype == NLTYPE_ANYCRLF) - { - if (jumpifmatch) - { - add_jump(compiler, backtracks, CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, CHAR_CR)); - add_jump(compiler, backtracks, CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, CHAR_NL)); - } - else - { - jump = CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, CHAR_CR); - add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, CHAR_NL)); - JUMPHERE(jump); - } - } -else - { - SLJIT_ASSERT(nltype == NLTYPE_FIXED && common->newline < 256); - add_jump(compiler, backtracks, CMP(jumpifmatch ? SLJIT_C_EQUAL : SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, common->newline)); - } -} - -#ifdef SUPPORT_UTF - -#if defined COMPILE_PCRE8 -static void do_utfreadchar(compiler_common *common) -{ -/* Fast decoding a UTF-8 character. TMP1 contains the first byte -of the character (>= 0xc0). Return char value in TMP1, length in TMP2. */ -DEFINE_COMPILER; -struct sljit_jump *jump; - -sljit_emit_fast_enter(compiler, RETURN_ADDR, 0); -OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); -OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x3f); -OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 6); -OP2(SLJIT_AND, TMP2, 0, TMP2, 0, SLJIT_IMM, 0x3f); -OP2(SLJIT_OR, TMP1, 0, TMP1, 0, TMP2, 0); - -/* Searching for the first zero. */ -OP2(SLJIT_AND | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x800); -jump = JUMP(SLJIT_C_NOT_ZERO); -/* Two byte sequence. */ -OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); -OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, IN_UCHARS(2)); -sljit_emit_fast_return(compiler, RETURN_ADDR, 0); - -JUMPHERE(jump); -OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(1)); -OP2(SLJIT_XOR, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x800); -OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 6); -OP2(SLJIT_AND, TMP2, 0, TMP2, 0, SLJIT_IMM, 0x3f); -OP2(SLJIT_OR, TMP1, 0, TMP1, 0, TMP2, 0); - -OP2(SLJIT_AND | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x10000); -jump = JUMP(SLJIT_C_NOT_ZERO); -/* Three byte sequence. */ -OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(2)); -OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, IN_UCHARS(3)); -sljit_emit_fast_return(compiler, RETURN_ADDR, 0); - -/* Four byte sequence. */ -JUMPHERE(jump); -OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(2)); -OP2(SLJIT_XOR, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x10000); -OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 6); -OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(3)); -OP2(SLJIT_AND, TMP2, 0, TMP2, 0, SLJIT_IMM, 0x3f); -OP2(SLJIT_OR, TMP1, 0, TMP1, 0, TMP2, 0); -OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, IN_UCHARS(4)); -sljit_emit_fast_return(compiler, RETURN_ADDR, 0); -} - -static void do_utfreadchar16(compiler_common *common) -{ -/* Fast decoding a UTF-8 character. TMP1 contains the first byte -of the character (>= 0xc0). Return value in TMP1. */ -DEFINE_COMPILER; -struct sljit_jump *jump; - -sljit_emit_fast_enter(compiler, RETURN_ADDR, 0); -OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); -OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x3f); -OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 6); -OP2(SLJIT_AND, TMP2, 0, TMP2, 0, SLJIT_IMM, 0x3f); -OP2(SLJIT_OR, TMP1, 0, TMP1, 0, TMP2, 0); - -/* Searching for the first zero. */ -OP2(SLJIT_AND | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x800); -jump = JUMP(SLJIT_C_NOT_ZERO); -/* Two byte sequence. */ -OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); -sljit_emit_fast_return(compiler, RETURN_ADDR, 0); - -JUMPHERE(jump); -OP2(SLJIT_AND | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x400); -OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_UNUSED, 0, SLJIT_C_NOT_ZERO); -/* This code runs only in 8 bit mode. No need to shift the value. */ -OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP2, 0); -OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(1)); -OP2(SLJIT_XOR, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x800); -OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 6); -OP2(SLJIT_AND, TMP2, 0, TMP2, 0, SLJIT_IMM, 0x3f); -OP2(SLJIT_OR, TMP1, 0, TMP1, 0, TMP2, 0); -/* Three byte sequence. */ -OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(2)); -sljit_emit_fast_return(compiler, RETURN_ADDR, 0); -} - -static void do_utfreadtype8(compiler_common *common) -{ -/* Fast decoding a UTF-8 character type. TMP2 contains the first byte -of the character (>= 0xc0). Return value in TMP1. */ -DEFINE_COMPILER; -struct sljit_jump *jump; -struct sljit_jump *compare; - -sljit_emit_fast_enter(compiler, RETURN_ADDR, 0); - -OP2(SLJIT_AND | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP2, 0, SLJIT_IMM, 0x20); -jump = JUMP(SLJIT_C_NOT_ZERO); -/* Two byte sequence. */ -OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); -OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); -OP2(SLJIT_AND, TMP2, 0, TMP2, 0, SLJIT_IMM, 0x1f); -/* The upper 5 bits are known at this point. */ -compare = CMP(SLJIT_C_GREATER, TMP2, 0, SLJIT_IMM, 0x3); -OP2(SLJIT_SHL, TMP2, 0, TMP2, 0, SLJIT_IMM, 6); -OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x3f); -OP2(SLJIT_OR, TMP2, 0, TMP2, 0, TMP1, 0); -OP1(SLJIT_MOV_UB, TMP1, 0, SLJIT_MEM1(TMP2), common->ctypes); -sljit_emit_fast_return(compiler, RETURN_ADDR, 0); - -JUMPHERE(compare); -OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, 0); -sljit_emit_fast_return(compiler, RETURN_ADDR, 0); - -/* We only have types for characters less than 256. */ -JUMPHERE(jump); -OP1(SLJIT_MOV_UB, TMP2, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(utf8_table4) - 0xc0); -OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, 0); -OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP2, 0); -sljit_emit_fast_return(compiler, RETURN_ADDR, 0); -} - -#endif /* COMPILE_PCRE8 */ - -#endif /* SUPPORT_UTF */ - -#ifdef SUPPORT_UCP - -/* UCD_BLOCK_SIZE must be 128 (see the assert below). */ -#define UCD_BLOCK_MASK 127 -#define UCD_BLOCK_SHIFT 7 - -static void do_getucd(compiler_common *common) -{ -/* Search the UCD record for the character comes in TMP1. -Returns chartype in TMP1 and UCD offset in TMP2. */ -DEFINE_COMPILER; - -SLJIT_ASSERT(UCD_BLOCK_SIZE == 128 && sizeof(ucd_record) == 8); - -sljit_emit_fast_enter(compiler, RETURN_ADDR, 0); -OP2(SLJIT_LSHR, TMP2, 0, TMP1, 0, SLJIT_IMM, UCD_BLOCK_SHIFT); -OP1(SLJIT_MOV_UB, TMP2, 0, SLJIT_MEM1(TMP2), (sljit_sw)PRIV(ucd_stage1)); -OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, UCD_BLOCK_MASK); -OP2(SLJIT_SHL, TMP2, 0, TMP2, 0, SLJIT_IMM, UCD_BLOCK_SHIFT); -OP2(SLJIT_ADD, TMP1, 0, TMP1, 0, TMP2, 0); -OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, (sljit_sw)PRIV(ucd_stage2)); -OP1(SLJIT_MOV_UH, TMP2, 0, SLJIT_MEM2(TMP2, TMP1), 1); -OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, chartype)); -OP1(SLJIT_MOV_UB, TMP1, 0, SLJIT_MEM2(TMP1, TMP2), 3); -sljit_emit_fast_return(compiler, RETURN_ADDR, 0); -} -#endif - -static SLJIT_INLINE struct sljit_label *mainloop_entry(compiler_common *common, BOOL hascrorlf, BOOL firstline) -{ -DEFINE_COMPILER; -struct sljit_label *mainloop; -struct sljit_label *newlinelabel = NULL; -struct sljit_jump *start; -struct sljit_jump *end = NULL; -struct sljit_jump *nl = NULL; -#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 -struct sljit_jump *singlechar; -#endif -jump_list *newline = NULL; -BOOL newlinecheck = FALSE; -BOOL readuchar = FALSE; - -if (!(hascrorlf || firstline) && (common->nltype == NLTYPE_ANY || - common->nltype == NLTYPE_ANYCRLF || common->newline > 255)) - newlinecheck = TRUE; - -if (firstline) - { - /* Search for the end of the first line. */ - SLJIT_ASSERT(common->first_line_end != 0); - OP1(SLJIT_MOV, TMP3, 0, STR_PTR, 0); - - if (common->nltype == NLTYPE_FIXED && common->newline > 255) - { - mainloop = LABEL(); - OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); - end = CMP(SLJIT_C_GREATER_EQUAL, STR_PTR, 0, STR_END, 0); - OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(-1)); - OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); - CMPTO(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, (common->newline >> 8) & 0xff, mainloop); - CMPTO(SLJIT_C_NOT_EQUAL, TMP2, 0, SLJIT_IMM, common->newline & 0xff, mainloop); - JUMPHERE(end); - OP2(SLJIT_SUB, SLJIT_MEM1(SLJIT_SP), common->first_line_end, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); - } - else - { - end = CMP(SLJIT_C_GREATER_EQUAL, STR_PTR, 0, STR_END, 0); - mainloop = LABEL(); - /* Continual stores does not cause data dependency. */ - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->first_line_end, STR_PTR, 0); - read_char_range(common, common->nlmin, common->nlmax, TRUE); - check_newlinechar(common, common->nltype, &newline, TRUE); - CMPTO(SLJIT_C_LESS, STR_PTR, 0, STR_END, 0, mainloop); - JUMPHERE(end); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->first_line_end, STR_PTR, 0); - set_jumps(newline, LABEL()); - } - - OP1(SLJIT_MOV, STR_PTR, 0, TMP3, 0); - } - -start = JUMP(SLJIT_JUMP); - -if (newlinecheck) - { - newlinelabel = LABEL(); - OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); - end = CMP(SLJIT_C_GREATER_EQUAL, STR_PTR, 0, STR_END, 0); - OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), 0); - OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, common->newline & 0xff); - OP_FLAGS(SLJIT_MOV, TMP1, 0, SLJIT_UNUSED, 0, SLJIT_C_EQUAL); -#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 - OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, UCHAR_SHIFT); -#endif - OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP1, 0); - nl = JUMP(SLJIT_JUMP); - } - -mainloop = LABEL(); - -/* Increasing the STR_PTR here requires one less jump in the most common case. */ -#ifdef SUPPORT_UTF -if (common->utf) readuchar = TRUE; -#endif -if (newlinecheck) readuchar = TRUE; - -if (readuchar) - OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), 0); - -if (newlinecheck) - CMPTO(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, (common->newline >> 8) & 0xff, newlinelabel); - -OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); -#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 -#if defined COMPILE_PCRE8 -if (common->utf) - { - singlechar = CMP(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, 0xc0); - OP1(SLJIT_MOV_UB, TMP1, 0, SLJIT_MEM1(TMP1), (sljit_sw)PRIV(utf8_table4) - 0xc0); - OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP1, 0); - JUMPHERE(singlechar); - } -#elif defined COMPILE_PCRE16 -if (common->utf) - { - singlechar = CMP(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, 0xd800); - OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0xfc00); - OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0xd800); - OP_FLAGS(SLJIT_MOV, TMP1, 0, SLJIT_UNUSED, 0, SLJIT_C_EQUAL); - OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 1); - OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP1, 0); - JUMPHERE(singlechar); - } -#endif /* COMPILE_PCRE[8|16] */ -#endif /* SUPPORT_UTF && !COMPILE_PCRE32 */ -JUMPHERE(start); - -if (newlinecheck) - { - JUMPHERE(end); - JUMPHERE(nl); - } - -return mainloop; -} - -#define MAX_N_CHARS 16 -#define MAX_N_BYTES 8 - -static SLJIT_INLINE void add_prefix_byte(pcre_uint8 byte, pcre_uint8 *bytes) -{ -pcre_uint8 len = bytes[0]; -int i; - -if (len == 255) - return; - -if (len == 0) - { - bytes[0] = 1; - bytes[1] = byte; - return; - } - -for (i = len; i > 0; i--) - if (bytes[i] == byte) - return; - -if (len >= MAX_N_BYTES - 1) - { - bytes[0] = 255; - return; - } - -len++; -bytes[len] = byte; -bytes[0] = len; -} - -static int scan_prefix(compiler_common *common, pcre_uchar *cc, pcre_uint32 *chars, pcre_uint8 *bytes, int max_chars) -{ -/* Recursive function, which scans prefix literals. */ -BOOL last, any, caseless; -int len, repeat, len_save, consumed = 0; -pcre_uint32 chr, mask; -pcre_uchar *alternative, *cc_save, *oc; -#if defined SUPPORT_UTF && defined COMPILE_PCRE8 -pcre_uchar othercase[8]; -#elif defined SUPPORT_UTF && defined COMPILE_PCRE16 -pcre_uchar othercase[2]; -#else -pcre_uchar othercase[1]; -#endif - -repeat = 1; -while (TRUE) - { - last = TRUE; - any = FALSE; - caseless = FALSE; - switch (*cc) - { - case OP_CHARI: - caseless = TRUE; - case OP_CHAR: - last = FALSE; - cc++; - break; - - case OP_SOD: - case OP_SOM: - case OP_SET_SOM: - case OP_NOT_WORD_BOUNDARY: - case OP_WORD_BOUNDARY: - case OP_EODN: - case OP_EOD: - case OP_CIRC: - case OP_CIRCM: - case OP_DOLL: - case OP_DOLLM: - /* Zero width assertions. */ - cc++; - continue; - - case OP_ASSERT: - case OP_ASSERT_NOT: - case OP_ASSERTBACK: - case OP_ASSERTBACK_NOT: - cc = bracketend(cc); - continue; - - case OP_PLUSI: - case OP_MINPLUSI: - case OP_POSPLUSI: - caseless = TRUE; - case OP_PLUS: - case OP_MINPLUS: - case OP_POSPLUS: - cc++; - break; - - case OP_EXACTI: - caseless = TRUE; - case OP_EXACT: - repeat = GET2(cc, 1); - last = FALSE; - cc += 1 + IMM2_SIZE; - break; - - case OP_QUERYI: - case OP_MINQUERYI: - case OP_POSQUERYI: - caseless = TRUE; - case OP_QUERY: - case OP_MINQUERY: - case OP_POSQUERY: - len = 1; - cc++; -#ifdef SUPPORT_UTF - if (common->utf && HAS_EXTRALEN(*cc)) len += GET_EXTRALEN(*cc); -#endif - max_chars = scan_prefix(common, cc + len, chars, bytes, max_chars); - if (max_chars == 0) - return consumed; - last = FALSE; - break; - - case OP_KET: - cc += 1 + LINK_SIZE; - continue; - - case OP_ALT: - cc += GET(cc, 1); - continue; - - case OP_ONCE: - case OP_ONCE_NC: - case OP_BRA: - case OP_BRAPOS: - case OP_CBRA: - case OP_CBRAPOS: - alternative = cc + GET(cc, 1); - while (*alternative == OP_ALT) - { - max_chars = scan_prefix(common, alternative + 1 + LINK_SIZE, chars, bytes, max_chars); - if (max_chars == 0) - return consumed; - alternative += GET(alternative, 1); - } - - if (*cc == OP_CBRA || *cc == OP_CBRAPOS) - cc += IMM2_SIZE; - cc += 1 + LINK_SIZE; - continue; - - case OP_CLASS: -#if defined SUPPORT_UTF && defined COMPILE_PCRE8 - if (common->utf && !is_char7_bitset((const pcre_uint8 *)(cc + 1), FALSE)) return consumed; -#endif - any = TRUE; - cc += 1 + 32 / sizeof(pcre_uchar); - break; - - case OP_NCLASS: -#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 - if (common->utf) return consumed; -#endif - any = TRUE; - cc += 1 + 32 / sizeof(pcre_uchar); - break; - -#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 - case OP_XCLASS: -#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 - if (common->utf) return consumed; -#endif - any = TRUE; - cc += GET(cc, 1); - break; -#endif - - case OP_DIGIT: -#if defined SUPPORT_UTF && defined COMPILE_PCRE8 - if (common->utf && !is_char7_bitset((const pcre_uint8 *)common->ctypes - cbit_length + cbit_digit, FALSE)) - return consumed; -#endif - any = TRUE; - cc++; - break; - - case OP_WHITESPACE: -#if defined SUPPORT_UTF && defined COMPILE_PCRE8 - if (common->utf && !is_char7_bitset((const pcre_uint8 *)common->ctypes - cbit_length + cbit_space, FALSE)) - return consumed; -#endif - any = TRUE; - cc++; - break; - - case OP_WORDCHAR: -#if defined SUPPORT_UTF && defined COMPILE_PCRE8 - if (common->utf && !is_char7_bitset((const pcre_uint8 *)common->ctypes - cbit_length + cbit_word, FALSE)) - return consumed; -#endif - any = TRUE; - cc++; - break; - - case OP_NOT: - case OP_NOTI: - cc++; - /* Fall through. */ - case OP_NOT_DIGIT: - case OP_NOT_WHITESPACE: - case OP_NOT_WORDCHAR: - case OP_ANY: - case OP_ALLANY: -#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 - if (common->utf) return consumed; -#endif - any = TRUE; - cc++; - break; - -#ifdef SUPPORT_UCP - case OP_NOTPROP: - case OP_PROP: -#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 - if (common->utf) return consumed; -#endif - any = TRUE; - cc += 1 + 2; - break; -#endif - - case OP_TYPEEXACT: - repeat = GET2(cc, 1); - cc += 1 + IMM2_SIZE; - continue; - - case OP_NOTEXACT: - case OP_NOTEXACTI: -#if defined SUPPORT_UTF && !defined COMPILE_PCRE32 - if (common->utf) return consumed; -#endif - any = TRUE; - repeat = GET2(cc, 1); - cc += 1 + IMM2_SIZE + 1; - break; - - default: - return consumed; - } - - if (any) - { -#if defined COMPILE_PCRE8 - mask = 0xff; -#elif defined COMPILE_PCRE16 - mask = 0xffff; -#elif defined COMPILE_PCRE32 - mask = 0xffffffff; -#else - SLJIT_ASSERT_STOP(); -#endif - - do - { - chars[0] = mask; - chars[1] = mask; - bytes[0] = 255; - - consumed++; - if (--max_chars == 0) - return consumed; - chars += 2; - bytes += MAX_N_BYTES; - } - while (--repeat > 0); - - repeat = 1; - continue; - } - - len = 1; -#ifdef SUPPORT_UTF - if (common->utf && HAS_EXTRALEN(*cc)) len += GET_EXTRALEN(*cc); -#endif - - if (caseless && char_has_othercase(common, cc)) - { -#ifdef SUPPORT_UTF - if (common->utf) - { - GETCHAR(chr, cc); - if ((int)PRIV(ord2utf)(char_othercase(common, chr), othercase) != len) - return consumed; - } - else -#endif - { - chr = *cc; - othercase[0] = TABLE_GET(chr, common->fcc, chr); - } - } - else - caseless = FALSE; - - len_save = len; - cc_save = cc; - while (TRUE) - { - oc = othercase; - do - { - chr = *cc; -#ifdef COMPILE_PCRE32 - if (SLJIT_UNLIKELY(chr == NOTACHAR)) - return consumed; -#endif - add_prefix_byte((pcre_uint8)chr, bytes); - - mask = 0; - if (caseless) - { - add_prefix_byte((pcre_uint8)*oc, bytes); - mask = *cc ^ *oc; - chr |= mask; - } - -#ifdef COMPILE_PCRE32 - if (chars[0] == NOTACHAR && chars[1] == 0) -#else - if (chars[0] == NOTACHAR) -#endif - { - chars[0] = chr; - chars[1] = mask; - } - else - { - mask |= chars[0] ^ chr; - chr |= mask; - chars[0] = chr; - chars[1] |= mask; - } - - len--; - consumed++; - if (--max_chars == 0) - return consumed; - chars += 2; - bytes += MAX_N_BYTES; - cc++; - oc++; - } - while (len > 0); - - if (--repeat == 0) - break; - - len = len_save; - cc = cc_save; - } - - repeat = 1; - if (last) - return consumed; - } -} - -static SLJIT_INLINE BOOL fast_forward_first_n_chars(compiler_common *common, BOOL firstline) -{ -DEFINE_COMPILER; -struct sljit_label *start; -struct sljit_jump *quit; -pcre_uint32 chars[MAX_N_CHARS * 2]; -pcre_uint8 bytes[MAX_N_CHARS * MAX_N_BYTES]; -pcre_uint8 ones[MAX_N_CHARS]; -int offsets[3]; -pcre_uint32 mask; -pcre_uint8 *byte_set, *byte_set_end; -int i, max, from; -int range_right = -1, range_len = 3 - 1; -sljit_ub *update_table = NULL; -BOOL in_range; - -/* This is even TRUE, if both are NULL. */ -SLJIT_ASSERT(common->read_only_data_ptr == common->read_only_data); - -for (i = 0; i < MAX_N_CHARS; i++) - { - chars[i << 1] = NOTACHAR; - chars[(i << 1) + 1] = 0; - bytes[i * MAX_N_BYTES] = 0; - } - -max = scan_prefix(common, common->start, chars, bytes, MAX_N_CHARS); - -if (max <= 1) - return FALSE; - -for (i = 0; i < max; i++) - { - mask = chars[(i << 1) + 1]; - ones[i] = ones_in_half_byte[mask & 0xf]; - mask >>= 4; - while (mask != 0) - { - ones[i] += ones_in_half_byte[mask & 0xf]; - mask >>= 4; - } - } - -in_range = FALSE; -from = 0; /* Prevent compiler "uninitialized" warning */ -for (i = 0; i <= max; i++) - { - if (in_range && (i - from) > range_len && (bytes[(i - 1) * MAX_N_BYTES] <= 4)) - { - range_len = i - from; - range_right = i - 1; - } - - if (i < max && bytes[i * MAX_N_BYTES] < 255) - { - if (!in_range) - { - in_range = TRUE; - from = i; - } - } - else if (in_range) - in_range = FALSE; - } - -if (range_right >= 0) - { - /* Since no data is consumed (see the assert in the beginning - of this function), this space can be reallocated. */ - if (common->read_only_data) - SLJIT_FREE(common->read_only_data); - - common->read_only_data_size += 256; - common->read_only_data = (sljit_uw *)SLJIT_MALLOC(common->read_only_data_size); - if (common->read_only_data == NULL) - return TRUE; - - update_table = (sljit_ub *)common->read_only_data; - common->read_only_data_ptr = (sljit_uw *)(update_table + 256); - memset(update_table, IN_UCHARS(range_len), 256); - - for (i = 0; i < range_len; i++) - { - byte_set = bytes + ((range_right - i) * MAX_N_BYTES); - SLJIT_ASSERT(byte_set[0] > 0 && byte_set[0] < 255); - byte_set_end = byte_set + byte_set[0]; - byte_set++; - while (byte_set <= byte_set_end) - { - if (update_table[*byte_set] > IN_UCHARS(i)) - update_table[*byte_set] = IN_UCHARS(i); - byte_set++; - } - } - } - -offsets[0] = -1; -/* Scan forward. */ -for (i = 0; i < max; i++) - if (ones[i] <= 2) { - offsets[0] = i; - break; - } - -if (offsets[0] < 0 && range_right < 0) - return FALSE; - -if (offsets[0] >= 0) - { - /* Scan backward. */ - offsets[1] = -1; - for (i = max - 1; i > offsets[0]; i--) - if (ones[i] <= 2 && i != range_right) - { - offsets[1] = i; - break; - } - - /* This case is handled better by fast_forward_first_char. */ - if (offsets[1] == -1 && offsets[0] == 0 && range_right < 0) - return FALSE; - - offsets[2] = -1; - /* We only search for a middle character if there is no range check. */ - if (offsets[1] >= 0 && range_right == -1) - { - /* Scan from middle. */ - for (i = (offsets[0] + offsets[1]) / 2 + 1; i < offsets[1]; i++) - if (ones[i] <= 2) - { - offsets[2] = i; - break; - } - - if (offsets[2] == -1) - { - for (i = (offsets[0] + offsets[1]) / 2; i > offsets[0]; i--) - if (ones[i] <= 2) - { - offsets[2] = i; - break; - } - } - } - - SLJIT_ASSERT(offsets[1] == -1 || (offsets[0] < offsets[1])); - SLJIT_ASSERT(offsets[2] == -1 || (offsets[0] < offsets[2] && offsets[1] > offsets[2])); - - chars[0] = chars[offsets[0] << 1]; - chars[1] = chars[(offsets[0] << 1) + 1]; - if (offsets[2] >= 0) - { - chars[2] = chars[offsets[2] << 1]; - chars[3] = chars[(offsets[2] << 1) + 1]; - } - if (offsets[1] >= 0) - { - chars[4] = chars[offsets[1] << 1]; - chars[5] = chars[(offsets[1] << 1) + 1]; - } - } - -max -= 1; -if (firstline) - { - SLJIT_ASSERT(common->first_line_end != 0); - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->first_line_end); - OP1(SLJIT_MOV, TMP3, 0, STR_END, 0); - OP2(SLJIT_SUB, STR_END, 0, STR_END, 0, SLJIT_IMM, IN_UCHARS(max)); - quit = CMP(SLJIT_C_LESS_EQUAL, STR_END, 0, TMP1, 0); - OP1(SLJIT_MOV, STR_END, 0, TMP1, 0); - JUMPHERE(quit); - } -else - OP2(SLJIT_SUB, STR_END, 0, STR_END, 0, SLJIT_IMM, IN_UCHARS(max)); - -#if !(defined SLJIT_CONFIG_X86_32 && SLJIT_CONFIG_X86_32) -if (range_right >= 0) - OP1(SLJIT_MOV, RETURN_ADDR, 0, SLJIT_IMM, (sljit_sw)update_table); -#endif - -start = LABEL(); -quit = CMP(SLJIT_C_GREATER_EQUAL, STR_PTR, 0, STR_END, 0); - -SLJIT_ASSERT(range_right >= 0 || offsets[0] >= 0); - -if (range_right >= 0) - { -#if defined COMPILE_PCRE8 || (defined SLJIT_LITTLE_ENDIAN && SLJIT_LITTLE_ENDIAN) - OP1(SLJIT_MOV_UB, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(range_right)); -#else - OP1(SLJIT_MOV_UB, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(range_right + 1) - 1); -#endif - -#if !(defined SLJIT_CONFIG_X86_32 && SLJIT_CONFIG_X86_32) - OP1(SLJIT_MOV_UB, TMP1, 0, SLJIT_MEM2(RETURN_ADDR, TMP1), 0); -#else - OP1(SLJIT_MOV_UB, TMP1, 0, SLJIT_MEM1(TMP1), (sljit_sw)update_table); -#endif - OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP1, 0); - CMPTO(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, 0, start); - } - -if (offsets[0] >= 0) - { - OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(offsets[0])); - if (offsets[1] >= 0) - OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(offsets[1])); - OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); - - if (chars[1] != 0) - OP2(SLJIT_OR, TMP1, 0, TMP1, 0, SLJIT_IMM, chars[1]); - CMPTO(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, chars[0], start); - if (offsets[2] >= 0) - OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(offsets[2] - 1)); - - if (offsets[1] >= 0) - { - if (chars[5] != 0) - OP2(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_IMM, chars[5]); - CMPTO(SLJIT_C_NOT_EQUAL, TMP2, 0, SLJIT_IMM, chars[4], start); - } - - if (offsets[2] >= 0) - { - if (chars[3] != 0) - OP2(SLJIT_OR, TMP1, 0, TMP1, 0, SLJIT_IMM, chars[3]); - CMPTO(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, chars[2], start); - } - OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); - } - -JUMPHERE(quit); - -if (firstline) - { - if (range_right >= 0) - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->first_line_end); - OP1(SLJIT_MOV, STR_END, 0, TMP3, 0); - if (range_right >= 0) - { - quit = CMP(SLJIT_C_LESS_EQUAL, STR_PTR, 0, TMP1, 0); - OP1(SLJIT_MOV, STR_PTR, 0, TMP1, 0); - JUMPHERE(quit); - } - } -else - OP2(SLJIT_ADD, STR_END, 0, STR_END, 0, SLJIT_IMM, IN_UCHARS(max)); -return TRUE; -} - -#undef MAX_N_CHARS -#undef MAX_N_BYTES - -static SLJIT_INLINE void fast_forward_first_char(compiler_common *common, pcre_uchar first_char, BOOL caseless, BOOL firstline) -{ -DEFINE_COMPILER; -struct sljit_label *start; -struct sljit_jump *quit; -struct sljit_jump *found; -pcre_uchar oc, bit; - -if (firstline) - { - SLJIT_ASSERT(common->first_line_end != 0); - OP1(SLJIT_MOV, TMP3, 0, STR_END, 0); - OP1(SLJIT_MOV, STR_END, 0, SLJIT_MEM1(SLJIT_SP), common->first_line_end); - } - -start = LABEL(); -quit = CMP(SLJIT_C_GREATER_EQUAL, STR_PTR, 0, STR_END, 0); -OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), 0); - -oc = first_char; -if (caseless) - { - oc = TABLE_GET(first_char, common->fcc, first_char); -#if defined SUPPORT_UCP && !(defined COMPILE_PCRE8) - if (first_char > 127 && common->utf) - oc = UCD_OTHERCASE(first_char); -#endif - } -if (first_char == oc) - found = CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, first_char); -else - { - bit = first_char ^ oc; - if (is_powerof2(bit)) - { - OP2(SLJIT_OR, TMP2, 0, TMP1, 0, SLJIT_IMM, bit); - found = CMP(SLJIT_C_EQUAL, TMP2, 0, SLJIT_IMM, first_char | bit); - } - else - { - OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, first_char); - OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_UNUSED, 0, SLJIT_C_EQUAL); - OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, oc); - OP_FLAGS(SLJIT_OR | SLJIT_SET_E, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); - found = JUMP(SLJIT_C_NOT_ZERO); - } - } - -OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); -JUMPTO(SLJIT_JUMP, start); -JUMPHERE(found); -JUMPHERE(quit); - -if (firstline) - OP1(SLJIT_MOV, STR_END, 0, TMP3, 0); -} - -static SLJIT_INLINE void fast_forward_newline(compiler_common *common, BOOL firstline) -{ -DEFINE_COMPILER; -struct sljit_label *loop; -struct sljit_jump *lastchar; -struct sljit_jump *firstchar; -struct sljit_jump *quit; -struct sljit_jump *foundcr = NULL; -struct sljit_jump *notfoundnl; -jump_list *newline = NULL; - -if (firstline) - { - SLJIT_ASSERT(common->first_line_end != 0); - OP1(SLJIT_MOV, TMP3, 0, STR_END, 0); - OP1(SLJIT_MOV, STR_END, 0, SLJIT_MEM1(SLJIT_SP), common->first_line_end); - } - -if (common->nltype == NLTYPE_FIXED && common->newline > 255) - { - lastchar = CMP(SLJIT_C_GREATER_EQUAL, STR_PTR, 0, STR_END, 0); - OP1(SLJIT_MOV, TMP1, 0, ARGUMENTS, 0); - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, str)); - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, begin)); - firstchar = CMP(SLJIT_C_LESS_EQUAL, STR_PTR, 0, TMP2, 0); - - OP2(SLJIT_ADD, TMP1, 0, TMP1, 0, SLJIT_IMM, IN_UCHARS(2)); - OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, STR_PTR, 0, TMP1, 0); - OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_UNUSED, 0, SLJIT_C_GREATER_EQUAL); -#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 - OP2(SLJIT_SHL, TMP2, 0, TMP2, 0, SLJIT_IMM, UCHAR_SHIFT); -#endif - OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, TMP2, 0); - - loop = LABEL(); - OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); - quit = CMP(SLJIT_C_GREATER_EQUAL, STR_PTR, 0, STR_END, 0); - OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(-2)); - OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(-1)); - CMPTO(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, (common->newline >> 8) & 0xff, loop); - CMPTO(SLJIT_C_NOT_EQUAL, TMP2, 0, SLJIT_IMM, common->newline & 0xff, loop); - - JUMPHERE(quit); - JUMPHERE(firstchar); - JUMPHERE(lastchar); - - if (firstline) - OP1(SLJIT_MOV, STR_END, 0, TMP3, 0); - return; - } - -OP1(SLJIT_MOV, TMP1, 0, ARGUMENTS, 0); -OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, str)); -firstchar = CMP(SLJIT_C_LESS_EQUAL, STR_PTR, 0, TMP2, 0); -skip_char_back(common); - -loop = LABEL(); -common->ff_newline_shortcut = loop; - -read_char_range(common, common->nlmin, common->nlmax, TRUE); -lastchar = CMP(SLJIT_C_GREATER_EQUAL, STR_PTR, 0, STR_END, 0); -if (common->nltype == NLTYPE_ANY || common->nltype == NLTYPE_ANYCRLF) - foundcr = CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, CHAR_CR); -check_newlinechar(common, common->nltype, &newline, FALSE); -set_jumps(newline, loop); - -if (common->nltype == NLTYPE_ANY || common->nltype == NLTYPE_ANYCRLF) - { - quit = JUMP(SLJIT_JUMP); - JUMPHERE(foundcr); - notfoundnl = CMP(SLJIT_C_GREATER_EQUAL, STR_PTR, 0, STR_END, 0); - OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), 0); - OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, CHAR_NL); - OP_FLAGS(SLJIT_MOV, TMP1, 0, SLJIT_UNUSED, 0, SLJIT_C_EQUAL); -#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 - OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, UCHAR_SHIFT); -#endif - OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP1, 0); - JUMPHERE(notfoundnl); - JUMPHERE(quit); - } -JUMPHERE(lastchar); -JUMPHERE(firstchar); - -if (firstline) - OP1(SLJIT_MOV, STR_END, 0, TMP3, 0); -} - -static BOOL check_class_ranges(compiler_common *common, const pcre_uint8 *bits, BOOL nclass, BOOL invert, jump_list **backtracks); - -static SLJIT_INLINE void fast_forward_start_bits(compiler_common *common, pcre_uint8 *start_bits, BOOL firstline) -{ -DEFINE_COMPILER; -struct sljit_label *start; -struct sljit_jump *quit; -struct sljit_jump *found = NULL; -jump_list *matches = NULL; -#ifndef COMPILE_PCRE8 -struct sljit_jump *jump; -#endif - -if (firstline) - { - SLJIT_ASSERT(common->first_line_end != 0); - OP1(SLJIT_MOV, RETURN_ADDR, 0, STR_END, 0); - OP1(SLJIT_MOV, STR_END, 0, SLJIT_MEM1(SLJIT_SP), common->first_line_end); - } - -start = LABEL(); -quit = CMP(SLJIT_C_GREATER_EQUAL, STR_PTR, 0, STR_END, 0); -OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), 0); -#ifdef SUPPORT_UTF -if (common->utf) - OP1(SLJIT_MOV, TMP3, 0, TMP1, 0); -#endif - -if (!check_class_ranges(common, start_bits, (start_bits[31] & 0x80) != 0, TRUE, &matches)) - { -#ifndef COMPILE_PCRE8 - jump = CMP(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, 255); - OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, 255); - JUMPHERE(jump); -#endif - OP2(SLJIT_AND, TMP2, 0, TMP1, 0, SLJIT_IMM, 0x7); - OP2(SLJIT_LSHR, TMP1, 0, TMP1, 0, SLJIT_IMM, 3); - OP1(SLJIT_MOV_UB, TMP1, 0, SLJIT_MEM1(TMP1), (sljit_sw)start_bits); - OP2(SLJIT_SHL, TMP2, 0, SLJIT_IMM, 1, TMP2, 0); - OP2(SLJIT_AND | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, TMP2, 0); - found = JUMP(SLJIT_C_NOT_ZERO); - } - -#ifdef SUPPORT_UTF -if (common->utf) - OP1(SLJIT_MOV, TMP1, 0, TMP3, 0); -#endif -OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); -#ifdef SUPPORT_UTF -#if defined COMPILE_PCRE8 -if (common->utf) - { - CMPTO(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, 0xc0, start); - OP1(SLJIT_MOV_UB, TMP1, 0, SLJIT_MEM1(TMP1), (sljit_sw)PRIV(utf8_table4) - 0xc0); - OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP1, 0); - } -#elif defined COMPILE_PCRE16 -if (common->utf) - { - CMPTO(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, 0xd800, start); - OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0xfc00); - OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0xd800); - OP_FLAGS(SLJIT_MOV, TMP1, 0, SLJIT_UNUSED, 0, SLJIT_C_EQUAL); - OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 1); - OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP1, 0); - } -#endif /* COMPILE_PCRE[8|16] */ -#endif /* SUPPORT_UTF */ -JUMPTO(SLJIT_JUMP, start); -if (found != NULL) - JUMPHERE(found); -if (matches != NULL) - set_jumps(matches, LABEL()); -JUMPHERE(quit); - -if (firstline) - OP1(SLJIT_MOV, STR_END, 0, RETURN_ADDR, 0); -} - -static SLJIT_INLINE struct sljit_jump *search_requested_char(compiler_common *common, pcre_uchar req_char, BOOL caseless, BOOL has_firstchar) -{ -DEFINE_COMPILER; -struct sljit_label *loop; -struct sljit_jump *toolong; -struct sljit_jump *alreadyfound; -struct sljit_jump *found; -struct sljit_jump *foundoc = NULL; -struct sljit_jump *notfound; -pcre_uint32 oc, bit; - -SLJIT_ASSERT(common->req_char_ptr != 0); -OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), common->req_char_ptr); -OP2(SLJIT_ADD, TMP1, 0, STR_PTR, 0, SLJIT_IMM, REQ_BYTE_MAX); -toolong = CMP(SLJIT_C_LESS, TMP1, 0, STR_END, 0); -alreadyfound = CMP(SLJIT_C_LESS, STR_PTR, 0, TMP2, 0); - -if (has_firstchar) - OP2(SLJIT_ADD, TMP1, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); -else - OP1(SLJIT_MOV, TMP1, 0, STR_PTR, 0); - -loop = LABEL(); -notfound = CMP(SLJIT_C_GREATER_EQUAL, TMP1, 0, STR_END, 0); - -OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(TMP1), 0); -oc = req_char; -if (caseless) - { - oc = TABLE_GET(req_char, common->fcc, req_char); -#if defined SUPPORT_UCP && !(defined COMPILE_PCRE8) - if (req_char > 127 && common->utf) - oc = UCD_OTHERCASE(req_char); -#endif - } -if (req_char == oc) - found = CMP(SLJIT_C_EQUAL, TMP2, 0, SLJIT_IMM, req_char); -else - { - bit = req_char ^ oc; - if (is_powerof2(bit)) - { - OP2(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_IMM, bit); - found = CMP(SLJIT_C_EQUAL, TMP2, 0, SLJIT_IMM, req_char | bit); - } - else - { - found = CMP(SLJIT_C_EQUAL, TMP2, 0, SLJIT_IMM, req_char); - foundoc = CMP(SLJIT_C_EQUAL, TMP2, 0, SLJIT_IMM, oc); - } - } -OP2(SLJIT_ADD, TMP1, 0, TMP1, 0, SLJIT_IMM, IN_UCHARS(1)); -JUMPTO(SLJIT_JUMP, loop); - -JUMPHERE(found); -if (foundoc) - JUMPHERE(foundoc); -OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->req_char_ptr, TMP1, 0); -JUMPHERE(alreadyfound); -JUMPHERE(toolong); -return notfound; -} - -static void do_revertframes(compiler_common *common) -{ -DEFINE_COMPILER; -struct sljit_jump *jump; -struct sljit_label *mainloop; - -sljit_emit_fast_enter(compiler, RETURN_ADDR, 0); -OP1(SLJIT_MOV, TMP1, 0, STACK_TOP, 0); -GET_LOCAL_BASE(TMP3, 0, 0); - -/* Drop frames until we reach STACK_TOP. */ -mainloop = LABEL(); -OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(TMP1), 0); -OP2(SLJIT_SUB | SLJIT_SET_S, SLJIT_UNUSED, 0, TMP2, 0, SLJIT_IMM, 0); -jump = JUMP(SLJIT_C_SIG_LESS_EQUAL); - -OP2(SLJIT_ADD, TMP2, 0, TMP2, 0, TMP3, 0); -OP1(SLJIT_MOV, SLJIT_MEM1(TMP2), 0, SLJIT_MEM1(TMP1), sizeof(sljit_sw)); -OP1(SLJIT_MOV, SLJIT_MEM1(TMP2), sizeof(sljit_sw), SLJIT_MEM1(TMP1), 2 * sizeof(sljit_sw)); -OP2(SLJIT_ADD, TMP1, 0, TMP1, 0, SLJIT_IMM, 3 * sizeof(sljit_sw)); -JUMPTO(SLJIT_JUMP, mainloop); - -JUMPHERE(jump); -jump = JUMP(SLJIT_C_SIG_LESS); -/* End of dropping frames. */ -sljit_emit_fast_return(compiler, RETURN_ADDR, 0); - -JUMPHERE(jump); -OP1(SLJIT_NEG, TMP2, 0, TMP2, 0); -OP2(SLJIT_ADD, TMP2, 0, TMP2, 0, TMP3, 0); -OP1(SLJIT_MOV, SLJIT_MEM1(TMP2), 0, SLJIT_MEM1(TMP1), sizeof(sljit_sw)); -OP2(SLJIT_ADD, TMP1, 0, TMP1, 0, SLJIT_IMM, 2 * sizeof(sljit_sw)); -JUMPTO(SLJIT_JUMP, mainloop); -} - -static void check_wordboundary(compiler_common *common) -{ -DEFINE_COMPILER; -struct sljit_jump *skipread; -jump_list *skipread_list = NULL; -#if !(defined COMPILE_PCRE8) || defined SUPPORT_UTF -struct sljit_jump *jump; -#endif - -SLJIT_COMPILE_ASSERT(ctype_word == 0x10, ctype_word_must_be_16); - -sljit_emit_fast_enter(compiler, SLJIT_MEM1(SLJIT_SP), LOCALS0); -/* Get type of the previous char, and put it to LOCALS1. */ -OP1(SLJIT_MOV, TMP1, 0, ARGUMENTS, 0); -OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, begin)); -OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS1, SLJIT_IMM, 0); -skipread = CMP(SLJIT_C_LESS_EQUAL, STR_PTR, 0, TMP1, 0); -skip_char_back(common); -check_start_used_ptr(common); -read_char(common); - -/* Testing char type. */ -#ifdef SUPPORT_UCP -if (common->use_ucp) - { - OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, 1); - jump = CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, CHAR_UNDERSCORE); - add_jump(compiler, &common->getucd, JUMP(SLJIT_FAST_CALL)); - OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, ucp_Ll); - OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, ucp_Lu - ucp_Ll); - OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_UNUSED, 0, SLJIT_C_LESS_EQUAL); - OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, ucp_Nd - ucp_Ll); - OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, ucp_No - ucp_Nd); - OP_FLAGS(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_C_LESS_EQUAL); - JUMPHERE(jump); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS1, TMP2, 0); - } -else -#endif - { -#ifndef COMPILE_PCRE8 - jump = CMP(SLJIT_C_GREATER, TMP1, 0, SLJIT_IMM, 255); -#elif defined SUPPORT_UTF - /* Here LOCALS1 has already been zeroed. */ - jump = NULL; - if (common->utf) - jump = CMP(SLJIT_C_GREATER, TMP1, 0, SLJIT_IMM, 255); -#endif /* COMPILE_PCRE8 */ - OP1(SLJIT_MOV_UB, TMP1, 0, SLJIT_MEM1(TMP1), common->ctypes); - OP2(SLJIT_LSHR, TMP1, 0, TMP1, 0, SLJIT_IMM, 4 /* ctype_word */); - OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 1); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS1, TMP1, 0); -#ifndef COMPILE_PCRE8 - JUMPHERE(jump); -#elif defined SUPPORT_UTF - if (jump != NULL) - JUMPHERE(jump); -#endif /* COMPILE_PCRE8 */ - } -JUMPHERE(skipread); - -OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, 0); -check_str_end(common, &skipread_list); -peek_char(common, READ_CHAR_MAX); - -/* Testing char type. This is a code duplication. */ -#ifdef SUPPORT_UCP -if (common->use_ucp) - { - OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, 1); - jump = CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, CHAR_UNDERSCORE); - add_jump(compiler, &common->getucd, JUMP(SLJIT_FAST_CALL)); - OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, ucp_Ll); - OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, ucp_Lu - ucp_Ll); - OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_UNUSED, 0, SLJIT_C_LESS_EQUAL); - OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, ucp_Nd - ucp_Ll); - OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, ucp_No - ucp_Nd); - OP_FLAGS(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_C_LESS_EQUAL); - JUMPHERE(jump); - } -else -#endif - { -#ifndef COMPILE_PCRE8 - /* TMP2 may be destroyed by peek_char. */ - OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, 0); - jump = CMP(SLJIT_C_GREATER, TMP1, 0, SLJIT_IMM, 255); -#elif defined SUPPORT_UTF - OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, 0); - jump = NULL; - if (common->utf) - jump = CMP(SLJIT_C_GREATER, TMP1, 0, SLJIT_IMM, 255); -#endif - OP1(SLJIT_MOV_UB, TMP2, 0, SLJIT_MEM1(TMP1), common->ctypes); - OP2(SLJIT_LSHR, TMP2, 0, TMP2, 0, SLJIT_IMM, 4 /* ctype_word */); - OP2(SLJIT_AND, TMP2, 0, TMP2, 0, SLJIT_IMM, 1); -#ifndef COMPILE_PCRE8 - JUMPHERE(jump); -#elif defined SUPPORT_UTF - if (jump != NULL) - JUMPHERE(jump); -#endif /* COMPILE_PCRE8 */ - } -set_jumps(skipread_list, LABEL()); - -OP2(SLJIT_XOR | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP2, 0, SLJIT_MEM1(SLJIT_SP), LOCALS1); -sljit_emit_fast_return(compiler, SLJIT_MEM1(SLJIT_SP), LOCALS0); -} - -static BOOL check_class_ranges(compiler_common *common, const pcre_uint8 *bits, BOOL nclass, BOOL invert, jump_list **backtracks) -{ -DEFINE_COMPILER; -int ranges[MAX_RANGE_SIZE]; -pcre_uint8 bit, cbit, all; -int i, byte, length = 0; - -bit = bits[0] & 0x1; -/* All bits will be zero or one (since bit is zero or one). */ -all = -bit; - -for (i = 0; i < 256; ) - { - byte = i >> 3; - if ((i & 0x7) == 0 && bits[byte] == all) - i += 8; - else - { - cbit = (bits[byte] >> (i & 0x7)) & 0x1; - if (cbit != bit) - { - if (length >= MAX_RANGE_SIZE) - return FALSE; - ranges[length] = i; - length++; - bit = cbit; - all = -cbit; - } - i++; - } - } - -if (((bit == 0) && nclass) || ((bit == 1) && !nclass)) - { - if (length >= MAX_RANGE_SIZE) - return FALSE; - ranges[length] = 256; - length++; - } - -if (length < 0 || length > 4) - return FALSE; - -bit = bits[0] & 0x1; -if (invert) bit ^= 0x1; - -/* No character is accepted. */ -if (length == 0 && bit == 0) - add_jump(compiler, backtracks, JUMP(SLJIT_JUMP)); - -switch(length) - { - case 0: - /* When bit != 0, all characters are accepted. */ - return TRUE; - - case 1: - add_jump(compiler, backtracks, CMP(bit == 0 ? SLJIT_C_LESS : SLJIT_C_GREATER_EQUAL, TMP1, 0, SLJIT_IMM, ranges[0])); - return TRUE; - - case 2: - if (ranges[0] + 1 != ranges[1]) - { - OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, ranges[0]); - add_jump(compiler, backtracks, CMP(bit != 0 ? SLJIT_C_LESS : SLJIT_C_GREATER_EQUAL, TMP1, 0, SLJIT_IMM, ranges[1] - ranges[0])); - } - else - add_jump(compiler, backtracks, CMP(bit != 0 ? SLJIT_C_EQUAL : SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, ranges[0])); - return TRUE; - - case 3: - if (bit != 0) - { - add_jump(compiler, backtracks, CMP(SLJIT_C_GREATER_EQUAL, TMP1, 0, SLJIT_IMM, ranges[2])); - if (ranges[0] + 1 != ranges[1]) - { - OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, ranges[0]); - add_jump(compiler, backtracks, CMP(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, ranges[1] - ranges[0])); - } - else - add_jump(compiler, backtracks, CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, ranges[0])); - return TRUE; - } - - add_jump(compiler, backtracks, CMP(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, ranges[0])); - if (ranges[1] + 1 != ranges[2]) - { - OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, ranges[1]); - add_jump(compiler, backtracks, CMP(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, ranges[2] - ranges[1])); - } - else - add_jump(compiler, backtracks, CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, ranges[1])); - return TRUE; - - case 4: - if ((ranges[1] - ranges[0]) == (ranges[3] - ranges[2]) - && (ranges[0] | (ranges[2] - ranges[0])) == ranges[2] - && is_powerof2(ranges[2] - ranges[0])) - { - OP2(SLJIT_OR, TMP1, 0, TMP1, 0, SLJIT_IMM, ranges[2] - ranges[0]); - if (ranges[2] + 1 != ranges[3]) - { - OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, ranges[2]); - add_jump(compiler, backtracks, CMP(bit != 0 ? SLJIT_C_LESS : SLJIT_C_GREATER_EQUAL, TMP1, 0, SLJIT_IMM, ranges[3] - ranges[2])); - } - else - add_jump(compiler, backtracks, CMP(bit != 0 ? SLJIT_C_EQUAL : SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, ranges[2])); - return TRUE; - } - - if (bit != 0) - { - i = 0; - if (ranges[0] + 1 != ranges[1]) - { - OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, ranges[0]); - add_jump(compiler, backtracks, CMP(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, ranges[1] - ranges[0])); - i = ranges[0]; - } - else - add_jump(compiler, backtracks, CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, ranges[0])); - - if (ranges[2] + 1 != ranges[3]) - { - OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, ranges[2] - i); - add_jump(compiler, backtracks, CMP(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, ranges[3] - ranges[2])); - } - else - add_jump(compiler, backtracks, CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, ranges[2] - i)); - return TRUE; - } - - OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, ranges[0]); - add_jump(compiler, backtracks, CMP(SLJIT_C_GREATER_EQUAL, TMP1, 0, SLJIT_IMM, ranges[3] - ranges[0])); - if (ranges[1] + 1 != ranges[2]) - { - OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, ranges[1] - ranges[0]); - add_jump(compiler, backtracks, CMP(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, ranges[2] - ranges[1])); - } - else - add_jump(compiler, backtracks, CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, ranges[1] - ranges[0])); - return TRUE; - - default: - SLJIT_ASSERT_STOP(); - return FALSE; - } -} - -static void check_anynewline(compiler_common *common) -{ -/* Check whether TMP1 contains a newline character. TMP2 destroyed. */ -DEFINE_COMPILER; - -sljit_emit_fast_enter(compiler, RETURN_ADDR, 0); - -OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x0a); -OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x0d - 0x0a); -OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_UNUSED, 0, SLJIT_C_LESS_EQUAL); -OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x85 - 0x0a); -#if defined SUPPORT_UTF || defined COMPILE_PCRE16 || defined COMPILE_PCRE32 -#ifdef COMPILE_PCRE8 -if (common->utf) - { -#endif - OP_FLAGS(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); - OP2(SLJIT_OR, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x1); - OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x2029 - 0x0a); -#ifdef COMPILE_PCRE8 - } -#endif -#endif /* SUPPORT_UTF || COMPILE_PCRE16 || COMPILE_PCRE32 */ -OP_FLAGS(SLJIT_OR | SLJIT_SET_E, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); -sljit_emit_fast_return(compiler, RETURN_ADDR, 0); -} - -static void check_hspace(compiler_common *common) -{ -/* Check whether TMP1 contains a newline character. TMP2 destroyed. */ -DEFINE_COMPILER; - -sljit_emit_fast_enter(compiler, RETURN_ADDR, 0); - -OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x09); -OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_UNUSED, 0, SLJIT_C_EQUAL); -OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x20); -OP_FLAGS(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); -OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0xa0); -#if defined SUPPORT_UTF || defined COMPILE_PCRE16 || defined COMPILE_PCRE32 -#ifdef COMPILE_PCRE8 -if (common->utf) - { -#endif - OP_FLAGS(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); - OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x1680); - OP_FLAGS(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); - OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x180e); - OP_FLAGS(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); - OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x2000); - OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x200A - 0x2000); - OP_FLAGS(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_C_LESS_EQUAL); - OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x202f - 0x2000); - OP_FLAGS(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); - OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x205f - 0x2000); - OP_FLAGS(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); - OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x3000 - 0x2000); -#ifdef COMPILE_PCRE8 - } -#endif -#endif /* SUPPORT_UTF || COMPILE_PCRE16 || COMPILE_PCRE32 */ -OP_FLAGS(SLJIT_OR | SLJIT_SET_E, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); - -sljit_emit_fast_return(compiler, RETURN_ADDR, 0); -} - -static void check_vspace(compiler_common *common) -{ -/* Check whether TMP1 contains a newline character. TMP2 destroyed. */ -DEFINE_COMPILER; - -sljit_emit_fast_enter(compiler, RETURN_ADDR, 0); - -OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x0a); -OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x0d - 0x0a); -OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_UNUSED, 0, SLJIT_C_LESS_EQUAL); -OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x85 - 0x0a); -#if defined SUPPORT_UTF || defined COMPILE_PCRE16 || defined COMPILE_PCRE32 -#ifdef COMPILE_PCRE8 -if (common->utf) - { -#endif - OP_FLAGS(SLJIT_OR | SLJIT_SET_E, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); - OP2(SLJIT_OR, TMP1, 0, TMP1, 0, SLJIT_IMM, 0x1); - OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x2029 - 0x0a); -#ifdef COMPILE_PCRE8 - } -#endif -#endif /* SUPPORT_UTF || COMPILE_PCRE16 || COMPILE_PCRE32 */ -OP_FLAGS(SLJIT_OR | SLJIT_SET_E, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); - -sljit_emit_fast_return(compiler, RETURN_ADDR, 0); -} - -#define CHAR1 STR_END -#define CHAR2 STACK_TOP - -static void do_casefulcmp(compiler_common *common) -{ -DEFINE_COMPILER; -struct sljit_jump *jump; -struct sljit_label *label; - -sljit_emit_fast_enter(compiler, RETURN_ADDR, 0); -OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, TMP2, 0); -OP1(SLJIT_MOV, TMP3, 0, CHAR1, 0); -OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS0, CHAR2, 0); -OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, IN_UCHARS(1)); -OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); - -label = LABEL(); -OP1(MOVU_UCHAR, CHAR1, 0, SLJIT_MEM1(TMP1), IN_UCHARS(1)); -OP1(MOVU_UCHAR, CHAR2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(1)); -jump = CMP(SLJIT_C_NOT_EQUAL, CHAR1, 0, CHAR2, 0); -OP2(SLJIT_SUB | SLJIT_SET_E, TMP2, 0, TMP2, 0, SLJIT_IMM, IN_UCHARS(1)); -JUMPTO(SLJIT_C_NOT_ZERO, label); - -JUMPHERE(jump); -OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); -OP1(SLJIT_MOV, CHAR1, 0, TMP3, 0); -OP1(SLJIT_MOV, CHAR2, 0, SLJIT_MEM1(SLJIT_SP), LOCALS0); -sljit_emit_fast_return(compiler, RETURN_ADDR, 0); -} - -#define LCC_TABLE STACK_LIMIT - -static void do_caselesscmp(compiler_common *common) -{ -DEFINE_COMPILER; -struct sljit_jump *jump; -struct sljit_label *label; - -sljit_emit_fast_enter(compiler, RETURN_ADDR, 0); -OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, TMP2, 0); - -OP1(SLJIT_MOV, TMP3, 0, LCC_TABLE, 0); -OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS0, CHAR1, 0); -OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS1, CHAR2, 0); -OP1(SLJIT_MOV, LCC_TABLE, 0, SLJIT_IMM, common->lcc); -OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, IN_UCHARS(1)); -OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); - -label = LABEL(); -OP1(MOVU_UCHAR, CHAR1, 0, SLJIT_MEM1(TMP1), IN_UCHARS(1)); -OP1(MOVU_UCHAR, CHAR2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(1)); -#ifndef COMPILE_PCRE8 -jump = CMP(SLJIT_C_GREATER, CHAR1, 0, SLJIT_IMM, 255); -#endif -OP1(SLJIT_MOV_UB, CHAR1, 0, SLJIT_MEM2(LCC_TABLE, CHAR1), 0); -#ifndef COMPILE_PCRE8 -JUMPHERE(jump); -jump = CMP(SLJIT_C_GREATER, CHAR2, 0, SLJIT_IMM, 255); -#endif -OP1(SLJIT_MOV_UB, CHAR2, 0, SLJIT_MEM2(LCC_TABLE, CHAR2), 0); -#ifndef COMPILE_PCRE8 -JUMPHERE(jump); -#endif -jump = CMP(SLJIT_C_NOT_EQUAL, CHAR1, 0, CHAR2, 0); -OP2(SLJIT_SUB | SLJIT_SET_E, TMP2, 0, TMP2, 0, SLJIT_IMM, IN_UCHARS(1)); -JUMPTO(SLJIT_C_NOT_ZERO, label); - -JUMPHERE(jump); -OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); -OP1(SLJIT_MOV, LCC_TABLE, 0, TMP3, 0); -OP1(SLJIT_MOV, CHAR1, 0, SLJIT_MEM1(SLJIT_SP), LOCALS0); -OP1(SLJIT_MOV, CHAR2, 0, SLJIT_MEM1(SLJIT_SP), LOCALS1); -sljit_emit_fast_return(compiler, RETURN_ADDR, 0); -} - -#undef LCC_TABLE -#undef CHAR1 -#undef CHAR2 - -#if defined SUPPORT_UTF && defined SUPPORT_UCP - -static const pcre_uchar * SLJIT_CALL do_utf_caselesscmp(pcre_uchar *src1, jit_arguments *args, pcre_uchar *end1) -{ -/* This function would be ineffective to do in JIT level. */ -pcre_uint32 c1, c2; -const pcre_uchar *src2 = args->uchar_ptr; -const pcre_uchar *end2 = args->end; -const ucd_record *ur; -const pcre_uint32 *pp; - -while (src1 < end1) - { - if (src2 >= end2) - return (pcre_uchar*)1; - GETCHARINC(c1, src1); - GETCHARINC(c2, src2); - ur = GET_UCD(c2); - if (c1 != c2 && c1 != c2 + ur->other_case) - { - pp = PRIV(ucd_caseless_sets) + ur->caseset; - for (;;) - { - if (c1 < *pp) return NULL; - if (c1 == *pp++) break; - } - } - } -return src2; -} - -#endif /* SUPPORT_UTF && SUPPORT_UCP */ - -static pcre_uchar *byte_sequence_compare(compiler_common *common, BOOL caseless, pcre_uchar *cc, - compare_context* context, jump_list **backtracks) -{ -DEFINE_COMPILER; -unsigned int othercasebit = 0; -pcre_uchar *othercasechar = NULL; -#ifdef SUPPORT_UTF -int utflength; -#endif - -if (caseless && char_has_othercase(common, cc)) - { - othercasebit = char_get_othercase_bit(common, cc); - SLJIT_ASSERT(othercasebit); - /* Extracting bit difference info. */ -#if defined COMPILE_PCRE8 - othercasechar = cc + (othercasebit >> 8); - othercasebit &= 0xff; -#elif defined COMPILE_PCRE16 || defined COMPILE_PCRE32 - /* Note that this code only handles characters in the BMP. If there - ever are characters outside the BMP whose othercase differs in only one - bit from itself (there currently are none), this code will need to be - revised for COMPILE_PCRE32. */ - othercasechar = cc + (othercasebit >> 9); - if ((othercasebit & 0x100) != 0) - othercasebit = (othercasebit & 0xff) << 8; - else - othercasebit &= 0xff; -#endif /* COMPILE_PCRE[8|16|32] */ - } - -if (context->sourcereg == -1) - { -#if defined COMPILE_PCRE8 -#if defined SLJIT_UNALIGNED && SLJIT_UNALIGNED - if (context->length >= 4) - OP1(SLJIT_MOV_SI, TMP1, 0, SLJIT_MEM1(STR_PTR), -context->length); - else if (context->length >= 2) - OP1(SLJIT_MOV_UH, TMP1, 0, SLJIT_MEM1(STR_PTR), -context->length); - else -#endif - OP1(SLJIT_MOV_UB, TMP1, 0, SLJIT_MEM1(STR_PTR), -context->length); -#elif defined COMPILE_PCRE16 -#if defined SLJIT_UNALIGNED && SLJIT_UNALIGNED - if (context->length >= 4) - OP1(SLJIT_MOV_SI, TMP1, 0, SLJIT_MEM1(STR_PTR), -context->length); - else -#endif - OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), -context->length); -#elif defined COMPILE_PCRE32 - OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), -context->length); -#endif /* COMPILE_PCRE[8|16|32] */ - context->sourcereg = TMP2; - } - -#ifdef SUPPORT_UTF -utflength = 1; -if (common->utf && HAS_EXTRALEN(*cc)) - utflength += GET_EXTRALEN(*cc); - -do - { -#endif - - context->length -= IN_UCHARS(1); -#if (defined SLJIT_UNALIGNED && SLJIT_UNALIGNED) && (defined COMPILE_PCRE8 || defined COMPILE_PCRE16) - - /* Unaligned read is supported. */ - if (othercasebit != 0 && othercasechar == cc) - { - context->c.asuchars[context->ucharptr] = *cc | othercasebit; - context->oc.asuchars[context->ucharptr] = othercasebit; - } - else - { - context->c.asuchars[context->ucharptr] = *cc; - context->oc.asuchars[context->ucharptr] = 0; - } - context->ucharptr++; - -#if defined COMPILE_PCRE8 - if (context->ucharptr >= 4 || context->length == 0 || (context->ucharptr == 2 && context->length == 1)) -#else - if (context->ucharptr >= 2 || context->length == 0) -#endif - { - if (context->length >= 4) - OP1(SLJIT_MOV_SI, context->sourcereg, 0, SLJIT_MEM1(STR_PTR), -context->length); - else if (context->length >= 2) - OP1(SLJIT_MOV_UH, context->sourcereg, 0, SLJIT_MEM1(STR_PTR), -context->length); -#if defined COMPILE_PCRE8 - else if (context->length >= 1) - OP1(SLJIT_MOV_UB, context->sourcereg, 0, SLJIT_MEM1(STR_PTR), -context->length); -#endif /* COMPILE_PCRE8 */ - context->sourcereg = context->sourcereg == TMP1 ? TMP2 : TMP1; - - switch(context->ucharptr) - { - case 4 / sizeof(pcre_uchar): - if (context->oc.asint != 0) - OP2(SLJIT_OR, context->sourcereg, 0, context->sourcereg, 0, SLJIT_IMM, context->oc.asint); - add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, context->sourcereg, 0, SLJIT_IMM, context->c.asint | context->oc.asint)); - break; - - case 2 / sizeof(pcre_uchar): - if (context->oc.asushort != 0) - OP2(SLJIT_OR, context->sourcereg, 0, context->sourcereg, 0, SLJIT_IMM, context->oc.asushort); - add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, context->sourcereg, 0, SLJIT_IMM, context->c.asushort | context->oc.asushort)); - break; - -#ifdef COMPILE_PCRE8 - case 1: - if (context->oc.asbyte != 0) - OP2(SLJIT_OR, context->sourcereg, 0, context->sourcereg, 0, SLJIT_IMM, context->oc.asbyte); - add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, context->sourcereg, 0, SLJIT_IMM, context->c.asbyte | context->oc.asbyte)); - break; -#endif - - default: - SLJIT_ASSERT_STOP(); - break; - } - context->ucharptr = 0; - } - -#else - - /* Unaligned read is unsupported or in 32 bit mode. */ - if (context->length >= 1) - OP1(MOV_UCHAR, context->sourcereg, 0, SLJIT_MEM1(STR_PTR), -context->length); - - context->sourcereg = context->sourcereg == TMP1 ? TMP2 : TMP1; - - if (othercasebit != 0 && othercasechar == cc) - { - OP2(SLJIT_OR, context->sourcereg, 0, context->sourcereg, 0, SLJIT_IMM, othercasebit); - add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, context->sourcereg, 0, SLJIT_IMM, *cc | othercasebit)); - } - else - add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, context->sourcereg, 0, SLJIT_IMM, *cc)); - -#endif - - cc++; -#ifdef SUPPORT_UTF - utflength--; - } -while (utflength > 0); -#endif - -return cc; -} - -#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 - -#define SET_TYPE_OFFSET(value) \ - if ((value) != typeoffset) \ - { \ - if ((value) < typeoffset) \ - OP2(SLJIT_ADD, typereg, 0, typereg, 0, SLJIT_IMM, typeoffset - (value)); \ - else \ - OP2(SLJIT_SUB, typereg, 0, typereg, 0, SLJIT_IMM, (value) - typeoffset); \ - } \ - typeoffset = (value); - -#define SET_CHAR_OFFSET(value) \ - if ((value) != charoffset) \ - { \ - if ((value) < charoffset) \ - OP2(SLJIT_ADD, TMP1, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)(charoffset - (value))); \ - else \ - OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)((value) - charoffset)); \ - } \ - charoffset = (value); - -static void compile_xclass_matchingpath(compiler_common *common, pcre_uchar *cc, jump_list **backtracks) -{ -DEFINE_COMPILER; -jump_list *found = NULL; -jump_list **list = (cc[0] & XCL_NOT) == 0 ? &found : backtracks; -sljit_uw c, charoffset, max = 256, min = READ_CHAR_MAX; -struct sljit_jump *jump = NULL; -pcre_uchar *ccbegin; -int compares, invertcmp, numberofcmps; -#if defined SUPPORT_UTF && (defined COMPILE_PCRE8 || defined COMPILE_PCRE16) -BOOL utf = common->utf; -#endif - -#ifdef SUPPORT_UCP -BOOL needstype = FALSE, needsscript = FALSE, needschar = FALSE; -BOOL charsaved = FALSE; -int typereg = TMP1, scriptreg = TMP1; -const pcre_uint32 *other_cases; -sljit_uw typeoffset; -#endif - -/* Scanning the necessary info. */ -cc++; -ccbegin = cc; -compares = 0; -if (cc[-1] & XCL_MAP) - { - min = 0; - cc += 32 / sizeof(pcre_uchar); - } - -while (*cc != XCL_END) - { - compares++; - if (*cc == XCL_SINGLE) - { - cc ++; - GETCHARINCTEST(c, cc); - if (c > max) max = c; - if (c < min) min = c; -#ifdef SUPPORT_UCP - needschar = TRUE; -#endif - } - else if (*cc == XCL_RANGE) - { - cc ++; - GETCHARINCTEST(c, cc); - if (c < min) min = c; - GETCHARINCTEST(c, cc); - if (c > max) max = c; -#ifdef SUPPORT_UCP - needschar = TRUE; -#endif - } -#ifdef SUPPORT_UCP - else - { - SLJIT_ASSERT(*cc == XCL_PROP || *cc == XCL_NOTPROP); - cc++; - if (*cc == PT_CLIST) - { - other_cases = PRIV(ucd_caseless_sets) + cc[1]; - while (*other_cases != NOTACHAR) - { - if (*other_cases > max) max = *other_cases; - if (*other_cases < min) min = *other_cases; - other_cases++; - } - } - else - { - max = READ_CHAR_MAX; - min = 0; - } - - switch(*cc) - { - case PT_ANY: - break; - - case PT_LAMP: - case PT_GC: - case PT_PC: - case PT_ALNUM: - needstype = TRUE; - break; - - case PT_SC: - needsscript = TRUE; - break; - - case PT_SPACE: - case PT_PXSPACE: - case PT_WORD: - case PT_PXGRAPH: - case PT_PXPRINT: - case PT_PXPUNCT: - needstype = TRUE; - needschar = TRUE; - break; - - case PT_CLIST: - case PT_UCNC: - needschar = TRUE; - break; - - default: - SLJIT_ASSERT_STOP(); - break; - } - cc += 2; - } -#endif - } - -/* We are not necessary in utf mode even in 8 bit mode. */ -cc = ccbegin; -detect_partial_match(common, backtracks); -read_char_range(common, min, max, (cc[-1] & XCL_NOT) != 0); - -if ((cc[-1] & XCL_HASPROP) == 0) - { - if ((cc[-1] & XCL_MAP) != 0) - { - jump = CMP(SLJIT_C_GREATER, TMP1, 0, SLJIT_IMM, 255); - if (!check_class_ranges(common, (const pcre_uint8 *)cc, (((const pcre_uint8 *)cc)[31] & 0x80) != 0, TRUE, &found)) - { - OP2(SLJIT_AND, TMP2, 0, TMP1, 0, SLJIT_IMM, 0x7); - OP2(SLJIT_LSHR, TMP1, 0, TMP1, 0, SLJIT_IMM, 3); - OP1(SLJIT_MOV_UB, TMP1, 0, SLJIT_MEM1(TMP1), (sljit_sw)cc); - OP2(SLJIT_SHL, TMP2, 0, SLJIT_IMM, 1, TMP2, 0); - OP2(SLJIT_AND | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, TMP2, 0); - add_jump(compiler, &found, JUMP(SLJIT_C_NOT_ZERO)); - } - - add_jump(compiler, backtracks, JUMP(SLJIT_JUMP)); - JUMPHERE(jump); - - cc += 32 / sizeof(pcre_uchar); - } - else - { - OP2(SLJIT_SUB, TMP2, 0, TMP1, 0, SLJIT_IMM, min); - add_jump(compiler, (cc[-1] & XCL_NOT) == 0 ? backtracks : &found, CMP(SLJIT_C_GREATER, TMP2, 0, SLJIT_IMM, max - min)); - } - } -else if ((cc[-1] & XCL_MAP) != 0) - { - OP1(SLJIT_MOV, TMP3, 0, TMP1, 0); -#ifdef SUPPORT_UCP - charsaved = TRUE; -#endif - if (!check_class_ranges(common, (const pcre_uint8 *)cc, FALSE, TRUE, list)) - { -#ifdef COMPILE_PCRE8 - SLJIT_ASSERT(common->utf); -#endif - jump = CMP(SLJIT_C_GREATER, TMP1, 0, SLJIT_IMM, 255); - - OP2(SLJIT_AND, TMP2, 0, TMP1, 0, SLJIT_IMM, 0x7); - OP2(SLJIT_LSHR, TMP1, 0, TMP1, 0, SLJIT_IMM, 3); - OP1(SLJIT_MOV_UB, TMP1, 0, SLJIT_MEM1(TMP1), (sljit_sw)cc); - OP2(SLJIT_SHL, TMP2, 0, SLJIT_IMM, 1, TMP2, 0); - OP2(SLJIT_AND | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, TMP2, 0); - add_jump(compiler, list, JUMP(SLJIT_C_NOT_ZERO)); - - JUMPHERE(jump); - } - - OP1(SLJIT_MOV, TMP1, 0, TMP3, 0); - cc += 32 / sizeof(pcre_uchar); - } - -#ifdef SUPPORT_UCP -/* Simple register allocation. TMP1 is preferred if possible. */ -if (needstype || needsscript) - { - if (needschar && !charsaved) - OP1(SLJIT_MOV, TMP3, 0, TMP1, 0); - add_jump(compiler, &common->getucd, JUMP(SLJIT_FAST_CALL)); - if (needschar) - { - if (needstype) - { - OP1(SLJIT_MOV, RETURN_ADDR, 0, TMP1, 0); - typereg = RETURN_ADDR; - } - - if (needsscript) - scriptreg = TMP3; - OP1(SLJIT_MOV, TMP1, 0, TMP3, 0); - } - else if (needstype && needsscript) - scriptreg = TMP3; - /* In all other cases only one of them was specified, and that can goes to TMP1. */ - - if (needsscript) - { - if (scriptreg == TMP1) - { - OP1(SLJIT_MOV, scriptreg, 0, SLJIT_IMM, (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, script)); - OP1(SLJIT_MOV_UB, scriptreg, 0, SLJIT_MEM2(scriptreg, TMP2), 3); - } - else - { - OP2(SLJIT_SHL, TMP2, 0, TMP2, 0, SLJIT_IMM, 3); - OP2(SLJIT_ADD, TMP2, 0, TMP2, 0, SLJIT_IMM, (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, script)); - OP1(SLJIT_MOV_UB, scriptreg, 0, SLJIT_MEM1(TMP2), 0); - } - } - } -#endif - -/* Generating code. */ -charoffset = 0; -numberofcmps = 0; -#ifdef SUPPORT_UCP -typeoffset = 0; -#endif - -while (*cc != XCL_END) - { - compares--; - invertcmp = (compares == 0 && list != backtracks); - jump = NULL; - - if (*cc == XCL_SINGLE) - { - cc ++; - GETCHARINCTEST(c, cc); - - if (numberofcmps < 3 && (*cc == XCL_SINGLE || *cc == XCL_RANGE)) - { - OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset)); - OP_FLAGS(numberofcmps == 0 ? SLJIT_MOV : SLJIT_OR, TMP2, 0, numberofcmps == 0 ? SLJIT_UNUSED : TMP2, 0, SLJIT_C_EQUAL); - numberofcmps++; - } - else if (numberofcmps > 0) - { - OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset)); - OP_FLAGS(SLJIT_OR | SLJIT_SET_E, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); - jump = JUMP(SLJIT_C_NOT_ZERO ^ invertcmp); - numberofcmps = 0; - } - else - { - jump = CMP(SLJIT_C_EQUAL ^ invertcmp, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset)); - numberofcmps = 0; - } - } - else if (*cc == XCL_RANGE) - { - cc ++; - GETCHARINCTEST(c, cc); - SET_CHAR_OFFSET(c); - GETCHARINCTEST(c, cc); - - if (numberofcmps < 3 && (*cc == XCL_SINGLE || *cc == XCL_RANGE)) - { - OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset)); - OP_FLAGS(numberofcmps == 0 ? SLJIT_MOV : SLJIT_OR, TMP2, 0, numberofcmps == 0 ? SLJIT_UNUSED : TMP2, 0, SLJIT_C_LESS_EQUAL); - numberofcmps++; - } - else if (numberofcmps > 0) - { - OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset)); - OP_FLAGS(SLJIT_OR | SLJIT_SET_E, TMP2, 0, TMP2, 0, SLJIT_C_LESS_EQUAL); - jump = JUMP(SLJIT_C_NOT_ZERO ^ invertcmp); - numberofcmps = 0; - } - else - { - jump = CMP(SLJIT_C_LESS_EQUAL ^ invertcmp, TMP1, 0, SLJIT_IMM, (sljit_sw)(c - charoffset)); - numberofcmps = 0; - } - } -#ifdef SUPPORT_UCP - else - { - if (*cc == XCL_NOTPROP) - invertcmp ^= 0x1; - cc++; - switch(*cc) - { - case PT_ANY: - if (list != backtracks) - { - if ((cc[-1] == XCL_NOTPROP && compares > 0) || (cc[-1] == XCL_PROP && compares == 0)) - continue; - } - else if (cc[-1] == XCL_NOTPROP) - continue; - jump = JUMP(SLJIT_JUMP); - break; - - case PT_LAMP: - OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, typereg, 0, SLJIT_IMM, ucp_Lu - typeoffset); - OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_UNUSED, 0, SLJIT_C_EQUAL); - OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, typereg, 0, SLJIT_IMM, ucp_Ll - typeoffset); - OP_FLAGS(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); - OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, typereg, 0, SLJIT_IMM, ucp_Lt - typeoffset); - OP_FLAGS(SLJIT_OR | SLJIT_SET_E, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); - jump = JUMP(SLJIT_C_NOT_ZERO ^ invertcmp); - break; - - case PT_GC: - c = PRIV(ucp_typerange)[(int)cc[1] * 2]; - SET_TYPE_OFFSET(c); - jump = CMP(SLJIT_C_LESS_EQUAL ^ invertcmp, typereg, 0, SLJIT_IMM, PRIV(ucp_typerange)[(int)cc[1] * 2 + 1] - c); - break; - - case PT_PC: - jump = CMP(SLJIT_C_EQUAL ^ invertcmp, typereg, 0, SLJIT_IMM, (int)cc[1] - typeoffset); - break; - - case PT_SC: - jump = CMP(SLJIT_C_EQUAL ^ invertcmp, scriptreg, 0, SLJIT_IMM, (int)cc[1]); - break; - - case PT_SPACE: - case PT_PXSPACE: - SET_CHAR_OFFSET(9); - OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0xd - 0x9); - OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_UNUSED, 0, SLJIT_C_LESS_EQUAL); - - OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x85 - 0x9); - OP_FLAGS(SLJIT_OR | SLJIT_SET_E, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); - - OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x180e - 0x9); - OP_FLAGS(SLJIT_OR | SLJIT_SET_E, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); - - SET_TYPE_OFFSET(ucp_Zl); - OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, typereg, 0, SLJIT_IMM, ucp_Zs - ucp_Zl); - OP_FLAGS(SLJIT_OR | SLJIT_SET_E, TMP2, 0, TMP2, 0, SLJIT_C_LESS_EQUAL); - jump = JUMP(SLJIT_C_NOT_ZERO ^ invertcmp); - break; - - case PT_WORD: - OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)(CHAR_UNDERSCORE - charoffset)); - OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_UNUSED, 0, SLJIT_C_EQUAL); - /* Fall through. */ - - case PT_ALNUM: - SET_TYPE_OFFSET(ucp_Ll); - OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, typereg, 0, SLJIT_IMM, ucp_Lu - ucp_Ll); - OP_FLAGS((*cc == PT_ALNUM) ? SLJIT_MOV : SLJIT_OR, TMP2, 0, (*cc == PT_ALNUM) ? SLJIT_UNUSED : TMP2, 0, SLJIT_C_LESS_EQUAL); - SET_TYPE_OFFSET(ucp_Nd); - OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, typereg, 0, SLJIT_IMM, ucp_No - ucp_Nd); - OP_FLAGS(SLJIT_OR | SLJIT_SET_E, TMP2, 0, TMP2, 0, SLJIT_C_LESS_EQUAL); - jump = JUMP(SLJIT_C_NOT_ZERO ^ invertcmp); - break; - - case PT_CLIST: - other_cases = PRIV(ucd_caseless_sets) + cc[1]; - - /* At least three characters are required. - Otherwise this case would be handled by the normal code path. */ - SLJIT_ASSERT(other_cases[0] != NOTACHAR && other_cases[1] != NOTACHAR && other_cases[2] != NOTACHAR); - SLJIT_ASSERT(other_cases[0] < other_cases[1] && other_cases[1] < other_cases[2]); - - /* Optimizing character pairs, if their difference is power of 2. */ - if (is_powerof2(other_cases[1] ^ other_cases[0])) - { - if (charoffset == 0) - OP2(SLJIT_OR, TMP2, 0, TMP1, 0, SLJIT_IMM, other_cases[1] ^ other_cases[0]); - else - { - OP2(SLJIT_ADD, TMP2, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)charoffset); - OP2(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_IMM, other_cases[1] ^ other_cases[0]); - } - OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP2, 0, SLJIT_IMM, other_cases[1]); - OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_UNUSED, 0, SLJIT_C_EQUAL); - other_cases += 2; - } - else if (is_powerof2(other_cases[2] ^ other_cases[1])) - { - if (charoffset == 0) - OP2(SLJIT_OR, TMP2, 0, TMP1, 0, SLJIT_IMM, other_cases[2] ^ other_cases[1]); - else - { - OP2(SLJIT_ADD, TMP2, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)charoffset); - OP2(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_IMM, other_cases[1] ^ other_cases[0]); - } - OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP2, 0, SLJIT_IMM, other_cases[2]); - OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_UNUSED, 0, SLJIT_C_EQUAL); - - OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)(other_cases[0] - charoffset)); - OP_FLAGS(SLJIT_OR | ((other_cases[3] == NOTACHAR) ? SLJIT_SET_E : 0), TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); - - other_cases += 3; - } - else - { - OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)(*other_cases++ - charoffset)); - OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_UNUSED, 0, SLJIT_C_EQUAL); - } - - while (*other_cases != NOTACHAR) - { - OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)(*other_cases++ - charoffset)); - OP_FLAGS(SLJIT_OR | ((*other_cases == NOTACHAR) ? SLJIT_SET_E : 0), TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); - } - jump = JUMP(SLJIT_C_NOT_ZERO ^ invertcmp); - break; - - case PT_UCNC: - OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)(CHAR_DOLLAR_SIGN - charoffset)); - OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_UNUSED, 0, SLJIT_C_EQUAL); - OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)(CHAR_COMMERCIAL_AT - charoffset)); - OP_FLAGS(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); - OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)(CHAR_GRAVE_ACCENT - charoffset)); - OP_FLAGS(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); - - SET_CHAR_OFFSET(0xa0); - OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, (sljit_sw)(0xd7ff - charoffset)); - OP_FLAGS(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_C_LESS_EQUAL); - SET_CHAR_OFFSET(0); - OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0xe000 - 0); - OP_FLAGS(SLJIT_OR | SLJIT_SET_E, TMP2, 0, TMP2, 0, SLJIT_C_GREATER_EQUAL); - jump = JUMP(SLJIT_C_NOT_ZERO ^ invertcmp); - break; - - case PT_PXGRAPH: - /* C and Z groups are the farthest two groups. */ - SET_TYPE_OFFSET(ucp_Ll); - OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, typereg, 0, SLJIT_IMM, ucp_So - ucp_Ll); - OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_UNUSED, 0, SLJIT_C_GREATER); - - jump = CMP(SLJIT_C_NOT_EQUAL, typereg, 0, SLJIT_IMM, ucp_Cf - ucp_Ll); - - /* In case of ucp_Cf, we overwrite the result. */ - SET_CHAR_OFFSET(0x2066); - OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x2069 - 0x2066); - OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_UNUSED, 0, SLJIT_C_LESS_EQUAL); - - OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x061c - 0x2066); - OP_FLAGS(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); - - OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x180e - 0x2066); - OP_FLAGS(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); - - JUMPHERE(jump); - jump = CMP(SLJIT_C_ZERO ^ invertcmp, TMP2, 0, SLJIT_IMM, 0); - break; - - case PT_PXPRINT: - /* C and Z groups are the farthest two groups. */ - SET_TYPE_OFFSET(ucp_Ll); - OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, typereg, 0, SLJIT_IMM, ucp_So - ucp_Ll); - OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_UNUSED, 0, SLJIT_C_GREATER); - - OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, typereg, 0, SLJIT_IMM, ucp_Zs - ucp_Ll); - OP_FLAGS(SLJIT_AND, TMP2, 0, TMP2, 0, SLJIT_C_NOT_EQUAL); - - jump = CMP(SLJIT_C_NOT_EQUAL, typereg, 0, SLJIT_IMM, ucp_Cf - ucp_Ll); - - /* In case of ucp_Cf, we overwrite the result. */ - SET_CHAR_OFFSET(0x2066); - OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x2069 - 0x2066); - OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_UNUSED, 0, SLJIT_C_LESS_EQUAL); - - OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0x061c - 0x2066); - OP_FLAGS(SLJIT_OR, TMP2, 0, TMP2, 0, SLJIT_C_EQUAL); - - JUMPHERE(jump); - jump = CMP(SLJIT_C_ZERO ^ invertcmp, TMP2, 0, SLJIT_IMM, 0); - break; - - case PT_PXPUNCT: - SET_TYPE_OFFSET(ucp_Sc); - OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, typereg, 0, SLJIT_IMM, ucp_So - ucp_Sc); - OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_UNUSED, 0, SLJIT_C_LESS_EQUAL); - - SET_CHAR_OFFSET(0); - OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0xff); - OP_FLAGS(SLJIT_AND, TMP2, 0, TMP2, 0, SLJIT_C_LESS_EQUAL); - - SET_TYPE_OFFSET(ucp_Pc); - OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, typereg, 0, SLJIT_IMM, ucp_Ps - ucp_Pc); - OP_FLAGS(SLJIT_OR | SLJIT_SET_E, TMP2, 0, TMP2, 0, SLJIT_C_LESS_EQUAL); - jump = JUMP(SLJIT_C_NOT_ZERO ^ invertcmp); - break; - } - cc += 2; - } -#endif - - if (jump != NULL) - add_jump(compiler, compares > 0 ? list : backtracks, jump); - } - -if (found != NULL) - set_jumps(found, LABEL()); -} - -#undef SET_TYPE_OFFSET -#undef SET_CHAR_OFFSET - -#endif - -static pcre_uchar *compile_char1_matchingpath(compiler_common *common, pcre_uchar type, pcre_uchar *cc, jump_list **backtracks) -{ -DEFINE_COMPILER; -int length; -unsigned int c, oc, bit; -compare_context context; -struct sljit_jump *jump[4]; -jump_list *end_list; -#ifdef SUPPORT_UTF -struct sljit_label *label; -#ifdef SUPPORT_UCP -pcre_uchar propdata[5]; -#endif -#endif /* SUPPORT_UTF */ - -switch(type) - { - case OP_SOD: - OP1(SLJIT_MOV, TMP1, 0, ARGUMENTS, 0); - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, begin)); - add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, STR_PTR, 0, TMP1, 0)); - return cc; - - case OP_SOM: - OP1(SLJIT_MOV, TMP1, 0, ARGUMENTS, 0); - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, str)); - add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, STR_PTR, 0, TMP1, 0)); - return cc; - - case OP_NOT_WORD_BOUNDARY: - case OP_WORD_BOUNDARY: - add_jump(compiler, &common->wordboundary, JUMP(SLJIT_FAST_CALL)); - add_jump(compiler, backtracks, JUMP(type == OP_NOT_WORD_BOUNDARY ? SLJIT_C_NOT_ZERO : SLJIT_C_ZERO)); - return cc; - - case OP_NOT_DIGIT: - case OP_DIGIT: - /* Digits are usually 0-9, so it is worth to optimize them. */ - detect_partial_match(common, backtracks); -#if defined SUPPORT_UTF && defined COMPILE_PCRE8 - if (common->utf && is_char7_bitset((const pcre_uint8*)common->ctypes - cbit_length + cbit_digit, FALSE)) - read_char7_type(common, type == OP_NOT_DIGIT); - else -#endif - read_char8_type(common, type == OP_NOT_DIGIT); - /* Flip the starting bit in the negative case. */ - OP2(SLJIT_AND | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, ctype_digit); - add_jump(compiler, backtracks, JUMP(type == OP_DIGIT ? SLJIT_C_ZERO : SLJIT_C_NOT_ZERO)); - return cc; - - case OP_NOT_WHITESPACE: - case OP_WHITESPACE: - detect_partial_match(common, backtracks); -#if defined SUPPORT_UTF && defined COMPILE_PCRE8 - if (common->utf && is_char7_bitset((const pcre_uint8*)common->ctypes - cbit_length + cbit_space, FALSE)) - read_char7_type(common, type == OP_NOT_WHITESPACE); - else -#endif - read_char8_type(common, type == OP_NOT_WHITESPACE); - OP2(SLJIT_AND | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, ctype_space); - add_jump(compiler, backtracks, JUMP(type == OP_WHITESPACE ? SLJIT_C_ZERO : SLJIT_C_NOT_ZERO)); - return cc; - - case OP_NOT_WORDCHAR: - case OP_WORDCHAR: - detect_partial_match(common, backtracks); -#if defined SUPPORT_UTF && defined COMPILE_PCRE8 - if (common->utf && is_char7_bitset((const pcre_uint8*)common->ctypes - cbit_length + cbit_word, FALSE)) - read_char7_type(common, type == OP_NOT_WORDCHAR); - else -#endif - read_char8_type(common, type == OP_NOT_WORDCHAR); - OP2(SLJIT_AND | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, ctype_word); - add_jump(compiler, backtracks, JUMP(type == OP_WORDCHAR ? SLJIT_C_ZERO : SLJIT_C_NOT_ZERO)); - return cc; - - case OP_ANY: - detect_partial_match(common, backtracks); - read_char_range(common, common->nlmin, common->nlmax, TRUE); - if (common->nltype == NLTYPE_FIXED && common->newline > 255) - { - jump[0] = CMP(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, (common->newline >> 8) & 0xff); - end_list = NULL; - if (common->mode != JIT_PARTIAL_HARD_COMPILE) - add_jump(compiler, &end_list, CMP(SLJIT_C_GREATER_EQUAL, STR_PTR, 0, STR_END, 0)); - else - check_str_end(common, &end_list); - - OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), 0); - add_jump(compiler, backtracks, CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, common->newline & 0xff)); - set_jumps(end_list, LABEL()); - JUMPHERE(jump[0]); - } - else - check_newlinechar(common, common->nltype, backtracks, TRUE); - return cc; - - case OP_ALLANY: - detect_partial_match(common, backtracks); -#ifdef SUPPORT_UTF - if (common->utf) - { - OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), 0); - OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); -#if defined COMPILE_PCRE8 || defined COMPILE_PCRE16 -#if defined COMPILE_PCRE8 - jump[0] = CMP(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, 0xc0); - OP1(SLJIT_MOV_UB, TMP1, 0, SLJIT_MEM1(TMP1), (sljit_sw)PRIV(utf8_table4) - 0xc0); - OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP1, 0); -#elif defined COMPILE_PCRE16 - jump[0] = CMP(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, 0xd800); - OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0xfc00); - OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, 0xd800); - OP_FLAGS(SLJIT_MOV, TMP1, 0, SLJIT_UNUSED, 0, SLJIT_C_EQUAL); - OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, 1); - OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP1, 0); -#endif - JUMPHERE(jump[0]); -#endif /* COMPILE_PCRE[8|16] */ - return cc; - } -#endif - OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); - return cc; - - case OP_ANYBYTE: - detect_partial_match(common, backtracks); - OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); - return cc; - -#ifdef SUPPORT_UTF -#ifdef SUPPORT_UCP - case OP_NOTPROP: - case OP_PROP: - propdata[0] = XCL_HASPROP; - propdata[1] = type == OP_NOTPROP ? XCL_NOTPROP : XCL_PROP; - propdata[2] = cc[0]; - propdata[3] = cc[1]; - propdata[4] = XCL_END; - compile_xclass_matchingpath(common, propdata, backtracks); - return cc + 2; -#endif -#endif - - case OP_ANYNL: - detect_partial_match(common, backtracks); - read_char_range(common, common->bsr_nlmin, common->bsr_nlmax, FALSE); - jump[0] = CMP(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, CHAR_CR); - /* We don't need to handle soft partial matching case. */ - end_list = NULL; - if (common->mode != JIT_PARTIAL_HARD_COMPILE) - add_jump(compiler, &end_list, CMP(SLJIT_C_GREATER_EQUAL, STR_PTR, 0, STR_END, 0)); - else - check_str_end(common, &end_list); - OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), 0); - jump[1] = CMP(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, CHAR_NL); - OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); - jump[2] = JUMP(SLJIT_JUMP); - JUMPHERE(jump[0]); - check_newlinechar(common, common->bsr_nltype, backtracks, FALSE); - set_jumps(end_list, LABEL()); - JUMPHERE(jump[1]); - JUMPHERE(jump[2]); - return cc; - - case OP_NOT_HSPACE: - case OP_HSPACE: - detect_partial_match(common, backtracks); - read_char_range(common, 0x9, 0x3000, type == OP_NOT_HSPACE); - add_jump(compiler, &common->hspace, JUMP(SLJIT_FAST_CALL)); - add_jump(compiler, backtracks, JUMP(type == OP_NOT_HSPACE ? SLJIT_C_NOT_ZERO : SLJIT_C_ZERO)); - return cc; - - case OP_NOT_VSPACE: - case OP_VSPACE: - detect_partial_match(common, backtracks); - read_char_range(common, 0xa, 0x2029, type == OP_NOT_VSPACE); - add_jump(compiler, &common->vspace, JUMP(SLJIT_FAST_CALL)); - add_jump(compiler, backtracks, JUMP(type == OP_NOT_VSPACE ? SLJIT_C_NOT_ZERO : SLJIT_C_ZERO)); - return cc; - -#ifdef SUPPORT_UCP - case OP_EXTUNI: - detect_partial_match(common, backtracks); - read_char(common); - add_jump(compiler, &common->getucd, JUMP(SLJIT_FAST_CALL)); - OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, gbprop)); - /* Optimize register allocation: use a real register. */ - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS0, STACK_TOP, 0); - OP1(SLJIT_MOV_UB, STACK_TOP, 0, SLJIT_MEM2(TMP1, TMP2), 3); - - label = LABEL(); - jump[0] = CMP(SLJIT_C_GREATER_EQUAL, STR_PTR, 0, STR_END, 0); - OP1(SLJIT_MOV, TMP3, 0, STR_PTR, 0); - read_char(common); - add_jump(compiler, &common->getucd, JUMP(SLJIT_FAST_CALL)); - OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, (sljit_sw)PRIV(ucd_records) + SLJIT_OFFSETOF(ucd_record, gbprop)); - OP1(SLJIT_MOV_UB, TMP2, 0, SLJIT_MEM2(TMP1, TMP2), 3); - - OP2(SLJIT_SHL, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, 2); - OP1(SLJIT_MOV_UI, TMP1, 0, SLJIT_MEM1(STACK_TOP), (sljit_sw)PRIV(ucp_gbtable)); - OP1(SLJIT_MOV, STACK_TOP, 0, TMP2, 0); - OP2(SLJIT_SHL, TMP2, 0, SLJIT_IMM, 1, TMP2, 0); - OP2(SLJIT_AND | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, TMP2, 0); - JUMPTO(SLJIT_C_NOT_ZERO, label); - - OP1(SLJIT_MOV, STR_PTR, 0, TMP3, 0); - JUMPHERE(jump[0]); - OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), LOCALS0); - - if (common->mode == JIT_PARTIAL_HARD_COMPILE) - { - jump[0] = CMP(SLJIT_C_LESS, STR_PTR, 0, STR_END, 0); - /* Since we successfully read a char above, partial matching must occure. */ - check_partial(common, TRUE); - JUMPHERE(jump[0]); - } - return cc; -#endif - - case OP_EODN: - /* Requires rather complex checks. */ - jump[0] = CMP(SLJIT_C_GREATER_EQUAL, STR_PTR, 0, STR_END, 0); - if (common->nltype == NLTYPE_FIXED && common->newline > 255) - { - OP2(SLJIT_ADD, TMP2, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(2)); - OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); - if (common->mode == JIT_COMPILE) - add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, TMP2, 0, STR_END, 0)); - else - { - jump[1] = CMP(SLJIT_C_EQUAL, TMP2, 0, STR_END, 0); - OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, TMP2, 0, STR_END, 0); - OP_FLAGS(SLJIT_MOV, TMP2, 0, SLJIT_UNUSED, 0, SLJIT_C_LESS); - OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, SLJIT_IMM, (common->newline >> 8) & 0xff); - OP_FLAGS(SLJIT_OR | SLJIT_SET_E, TMP2, 0, TMP2, 0, SLJIT_C_NOT_EQUAL); - add_jump(compiler, backtracks, JUMP(SLJIT_C_NOT_EQUAL)); - check_partial(common, TRUE); - add_jump(compiler, backtracks, JUMP(SLJIT_JUMP)); - JUMPHERE(jump[1]); - } - OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(1)); - add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, (common->newline >> 8) & 0xff)); - add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, TMP2, 0, SLJIT_IMM, common->newline & 0xff)); - } - else if (common->nltype == NLTYPE_FIXED) - { - OP2(SLJIT_ADD, TMP2, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); - OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); - add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, TMP2, 0, STR_END, 0)); - add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, common->newline)); - } - else - { - OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); - jump[1] = CMP(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, CHAR_CR); - OP2(SLJIT_ADD, TMP2, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(2)); - OP2(SLJIT_SUB | SLJIT_SET_U, SLJIT_UNUSED, 0, TMP2, 0, STR_END, 0); - jump[2] = JUMP(SLJIT_C_GREATER); - add_jump(compiler, backtracks, JUMP(SLJIT_C_LESS)); - /* Equal. */ - OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(1)); - jump[3] = CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, CHAR_NL); - add_jump(compiler, backtracks, JUMP(SLJIT_JUMP)); - - JUMPHERE(jump[1]); - if (common->nltype == NLTYPE_ANYCRLF) - { - OP2(SLJIT_ADD, TMP2, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); - add_jump(compiler, backtracks, CMP(SLJIT_C_LESS, TMP2, 0, STR_END, 0)); - add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, CHAR_NL)); - } - else - { - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS1, STR_PTR, 0); - read_char_range(common, common->nlmin, common->nlmax, TRUE); - add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, STR_PTR, 0, STR_END, 0)); - add_jump(compiler, &common->anynewline, JUMP(SLJIT_FAST_CALL)); - add_jump(compiler, backtracks, JUMP(SLJIT_C_ZERO)); - OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(SLJIT_SP), LOCALS1); - } - JUMPHERE(jump[2]); - JUMPHERE(jump[3]); - } - JUMPHERE(jump[0]); - check_partial(common, FALSE); - return cc; - - case OP_EOD: - add_jump(compiler, backtracks, CMP(SLJIT_C_LESS, STR_PTR, 0, STR_END, 0)); - check_partial(common, FALSE); - return cc; - - case OP_CIRC: - OP1(SLJIT_MOV, TMP2, 0, ARGUMENTS, 0); - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(TMP2), SLJIT_OFFSETOF(jit_arguments, begin)); - add_jump(compiler, backtracks, CMP(SLJIT_C_GREATER, STR_PTR, 0, TMP1, 0)); - OP1(SLJIT_MOV_UB, TMP2, 0, SLJIT_MEM1(TMP2), SLJIT_OFFSETOF(jit_arguments, notbol)); - add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, TMP2, 0, SLJIT_IMM, 0)); - return cc; - - case OP_CIRCM: - OP1(SLJIT_MOV, TMP2, 0, ARGUMENTS, 0); - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(TMP2), SLJIT_OFFSETOF(jit_arguments, begin)); - jump[1] = CMP(SLJIT_C_GREATER, STR_PTR, 0, TMP1, 0); - OP1(SLJIT_MOV_UB, TMP2, 0, SLJIT_MEM1(TMP2), SLJIT_OFFSETOF(jit_arguments, notbol)); - add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, TMP2, 0, SLJIT_IMM, 0)); - jump[0] = JUMP(SLJIT_JUMP); - JUMPHERE(jump[1]); - - add_jump(compiler, backtracks, CMP(SLJIT_C_GREATER_EQUAL, STR_PTR, 0, STR_END, 0)); - if (common->nltype == NLTYPE_FIXED && common->newline > 255) - { - OP2(SLJIT_SUB, TMP2, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(2)); - add_jump(compiler, backtracks, CMP(SLJIT_C_LESS, TMP2, 0, TMP1, 0)); - OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(-2)); - OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(-1)); - add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, (common->newline >> 8) & 0xff)); - add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, TMP2, 0, SLJIT_IMM, common->newline & 0xff)); - } - else - { - skip_char_back(common); - read_char_range(common, common->nlmin, common->nlmax, TRUE); - check_newlinechar(common, common->nltype, backtracks, FALSE); - } - JUMPHERE(jump[0]); - return cc; - - case OP_DOLL: - OP1(SLJIT_MOV, TMP2, 0, ARGUMENTS, 0); - OP1(SLJIT_MOV_UB, TMP2, 0, SLJIT_MEM1(TMP2), SLJIT_OFFSETOF(jit_arguments, noteol)); - add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, TMP2, 0, SLJIT_IMM, 0)); - - if (!common->endonly) - compile_char1_matchingpath(common, OP_EODN, cc, backtracks); - else - { - add_jump(compiler, backtracks, CMP(SLJIT_C_LESS, STR_PTR, 0, STR_END, 0)); - check_partial(common, FALSE); - } - return cc; - - case OP_DOLLM: - jump[1] = CMP(SLJIT_C_LESS, STR_PTR, 0, STR_END, 0); - OP1(SLJIT_MOV, TMP2, 0, ARGUMENTS, 0); - OP1(SLJIT_MOV_UB, TMP2, 0, SLJIT_MEM1(TMP2), SLJIT_OFFSETOF(jit_arguments, noteol)); - add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, TMP2, 0, SLJIT_IMM, 0)); - check_partial(common, FALSE); - jump[0] = JUMP(SLJIT_JUMP); - JUMPHERE(jump[1]); - - if (common->nltype == NLTYPE_FIXED && common->newline > 255) - { - OP2(SLJIT_ADD, TMP2, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(2)); - OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(0)); - if (common->mode == JIT_COMPILE) - add_jump(compiler, backtracks, CMP(SLJIT_C_GREATER, TMP2, 0, STR_END, 0)); - else - { - jump[1] = CMP(SLJIT_C_LESS_EQUAL, TMP2, 0, STR_END, 0); - /* STR_PTR = STR_END - IN_UCHARS(1) */ - add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, (common->newline >> 8) & 0xff)); - check_partial(common, TRUE); - add_jump(compiler, backtracks, JUMP(SLJIT_JUMP)); - JUMPHERE(jump[1]); - } - - OP1(MOV_UCHAR, TMP2, 0, SLJIT_MEM1(STR_PTR), IN_UCHARS(1)); - add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, (common->newline >> 8) & 0xff)); - add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, TMP2, 0, SLJIT_IMM, common->newline & 0xff)); - } - else - { - peek_char(common, common->nlmax); - check_newlinechar(common, common->nltype, backtracks, FALSE); - } - JUMPHERE(jump[0]); - return cc; - - case OP_CHAR: - case OP_CHARI: - length = 1; -#ifdef SUPPORT_UTF - if (common->utf && HAS_EXTRALEN(*cc)) length += GET_EXTRALEN(*cc); -#endif - if (common->mode == JIT_COMPILE && (type == OP_CHAR || !char_has_othercase(common, cc) || char_get_othercase_bit(common, cc) != 0)) - { - OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(length)); - add_jump(compiler, backtracks, CMP(SLJIT_C_GREATER, STR_PTR, 0, STR_END, 0)); - - context.length = IN_UCHARS(length); - context.sourcereg = -1; -#if defined SLJIT_UNALIGNED && SLJIT_UNALIGNED - context.ucharptr = 0; -#endif - return byte_sequence_compare(common, type == OP_CHARI, cc, &context, backtracks); - } - - detect_partial_match(common, backtracks); -#ifdef SUPPORT_UTF - if (common->utf) - { - GETCHAR(c, cc); - } - else -#endif - c = *cc; - - if (type == OP_CHAR || !char_has_othercase(common, cc)) - { - read_char_range(common, c, c, FALSE); - add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, c)); - return cc + length; - } - oc = char_othercase(common, c); - read_char_range(common, c < oc ? c : oc, c > oc ? c : oc, FALSE); - bit = c ^ oc; - if (is_powerof2(bit)) - { - OP2(SLJIT_OR, TMP1, 0, TMP1, 0, SLJIT_IMM, bit); - add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, c | bit)); - return cc + length; - } - jump[0] = CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, c); - add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, oc)); - JUMPHERE(jump[0]); - return cc + length; - - case OP_NOT: - case OP_NOTI: - detect_partial_match(common, backtracks); - length = 1; -#ifdef SUPPORT_UTF - if (common->utf) - { -#ifdef COMPILE_PCRE8 - c = *cc; - if (c < 128) - { - OP1(SLJIT_MOV_UB, TMP1, 0, SLJIT_MEM1(STR_PTR), 0); - if (type == OP_NOT || !char_has_othercase(common, cc)) - add_jump(compiler, backtracks, CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, c)); - else - { - /* Since UTF8 code page is fixed, we know that c is in [a-z] or [A-Z] range. */ - OP2(SLJIT_OR, TMP2, 0, TMP1, 0, SLJIT_IMM, 0x20); - add_jump(compiler, backtracks, CMP(SLJIT_C_EQUAL, TMP2, 0, SLJIT_IMM, c | 0x20)); - } - /* Skip the variable-length character. */ - OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1)); - jump[0] = CMP(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, 0xc0); - OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(TMP1), (sljit_sw)PRIV(utf8_table4) - 0xc0); - OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP1, 0); - JUMPHERE(jump[0]); - return cc + 1; - } - else -#endif /* COMPILE_PCRE8 */ - { - GETCHARLEN(c, cc, length); - } - } - else -#endif /* SUPPORT_UTF */ - c = *cc; - - if (type == OP_NOT || !char_has_othercase(common, cc)) - { - read_char_range(common, c, c, TRUE); - add_jump(compiler, backtracks, CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, c)); - } - else - { - oc = char_othercase(common, c); - read_char_range(common, c < oc ? c : oc, c > oc ? c : oc, TRUE); - bit = c ^ oc; - if (is_powerof2(bit)) - { - OP2(SLJIT_OR, TMP1, 0, TMP1, 0, SLJIT_IMM, bit); - add_jump(compiler, backtracks, CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, c | bit)); - } - else - { - add_jump(compiler, backtracks, CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, c)); - add_jump(compiler, backtracks, CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, oc)); - } - } - return cc + length; - - case OP_CLASS: - case OP_NCLASS: - detect_partial_match(common, backtracks); - -#if defined SUPPORT_UTF && defined COMPILE_PCRE8 - bit = (common->utf && is_char7_bitset((const pcre_uint8 *)cc, type == OP_NCLASS)) ? 127 : 255; - read_char_range(common, 0, bit, type == OP_NCLASS); -#else - read_char_range(common, 0, 255, type == OP_NCLASS); -#endif - - if (check_class_ranges(common, (const pcre_uint8 *)cc, type == OP_NCLASS, FALSE, backtracks)) - return cc + 32 / sizeof(pcre_uchar); - -#if defined SUPPORT_UTF && defined COMPILE_PCRE8 - jump[0] = NULL; - if (common->utf) - { - jump[0] = CMP(SLJIT_C_GREATER, TMP1, 0, SLJIT_IMM, bit); - if (type == OP_CLASS) - { - add_jump(compiler, backtracks, jump[0]); - jump[0] = NULL; - } - } -#elif !defined COMPILE_PCRE8 - jump[0] = CMP(SLJIT_C_GREATER, TMP1, 0, SLJIT_IMM, 255); - if (type == OP_CLASS) - { - add_jump(compiler, backtracks, jump[0]); - jump[0] = NULL; - } -#endif /* SUPPORT_UTF && COMPILE_PCRE8 */ - - OP2(SLJIT_AND, TMP2, 0, TMP1, 0, SLJIT_IMM, 0x7); - OP2(SLJIT_LSHR, TMP1, 0, TMP1, 0, SLJIT_IMM, 3); - OP1(SLJIT_MOV_UB, TMP1, 0, SLJIT_MEM1(TMP1), (sljit_sw)cc); - OP2(SLJIT_SHL, TMP2, 0, SLJIT_IMM, 1, TMP2, 0); - OP2(SLJIT_AND | SLJIT_SET_E, SLJIT_UNUSED, 0, TMP1, 0, TMP2, 0); - add_jump(compiler, backtracks, JUMP(SLJIT_C_ZERO)); - -#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 - if (jump[0] != NULL) - JUMPHERE(jump[0]); -#endif - - return cc + 32 / sizeof(pcre_uchar); - -#if defined SUPPORT_UTF || defined COMPILE_PCRE16 || defined COMPILE_PCRE32 - case OP_XCLASS: - compile_xclass_matchingpath(common, cc + LINK_SIZE, backtracks); - return cc + GET(cc, 0) - 1; -#endif - - case OP_REVERSE: - length = GET(cc, 0); - if (length == 0) - return cc + LINK_SIZE; - OP1(SLJIT_MOV, TMP1, 0, ARGUMENTS, 0); -#ifdef SUPPORT_UTF - if (common->utf) - { - OP1(SLJIT_MOV, TMP3, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, begin)); - OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, length); - label = LABEL(); - add_jump(compiler, backtracks, CMP(SLJIT_C_LESS_EQUAL, STR_PTR, 0, TMP3, 0)); - skip_char_back(common); - OP2(SLJIT_SUB | SLJIT_SET_E, TMP2, 0, TMP2, 0, SLJIT_IMM, 1); - JUMPTO(SLJIT_C_NOT_ZERO, label); - } - else -#endif - { - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, begin)); - OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(length)); - add_jump(compiler, backtracks, CMP(SLJIT_C_LESS, STR_PTR, 0, TMP1, 0)); - } - check_start_used_ptr(common); - return cc + LINK_SIZE; - } -SLJIT_ASSERT_STOP(); -return cc; -} - -static SLJIT_INLINE pcre_uchar *compile_charn_matchingpath(compiler_common *common, pcre_uchar *cc, pcre_uchar *ccend, jump_list **backtracks) -{ -/* This function consumes at least one input character. */ -/* To decrease the number of length checks, we try to concatenate the fixed length character sequences. */ -DEFINE_COMPILER; -pcre_uchar *ccbegin = cc; -compare_context context; -int size; - -context.length = 0; -do - { - if (cc >= ccend) - break; - - if (*cc == OP_CHAR) - { - size = 1; -#ifdef SUPPORT_UTF - if (common->utf && HAS_EXTRALEN(cc[1])) - size += GET_EXTRALEN(cc[1]); -#endif - } - else if (*cc == OP_CHARI) - { - size = 1; -#ifdef SUPPORT_UTF - if (common->utf) - { - if (char_has_othercase(common, cc + 1) && char_get_othercase_bit(common, cc + 1) == 0) - size = 0; - else if (HAS_EXTRALEN(cc[1])) - size += GET_EXTRALEN(cc[1]); - } - else -#endif - if (char_has_othercase(common, cc + 1) && char_get_othercase_bit(common, cc + 1) == 0) - size = 0; - } - else - size = 0; - - cc += 1 + size; - context.length += IN_UCHARS(size); - } -while (size > 0 && context.length <= 128); - -cc = ccbegin; -if (context.length > 0) - { - /* We have a fixed-length byte sequence. */ - OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, context.length); - add_jump(compiler, backtracks, CMP(SLJIT_C_GREATER, STR_PTR, 0, STR_END, 0)); - - context.sourcereg = -1; -#if defined SLJIT_UNALIGNED && SLJIT_UNALIGNED - context.ucharptr = 0; -#endif - do cc = byte_sequence_compare(common, *cc == OP_CHARI, cc + 1, &context, backtracks); while (context.length > 0); - return cc; - } - -/* A non-fixed length character will be checked if length == 0. */ -return compile_char1_matchingpath(common, *cc, cc + 1, backtracks); -} - -/* Forward definitions. */ -static void compile_matchingpath(compiler_common *, pcre_uchar *, pcre_uchar *, backtrack_common *); -static void compile_backtrackingpath(compiler_common *, struct backtrack_common *); - -#define PUSH_BACKTRACK(size, ccstart, error) \ - do \ - { \ - backtrack = sljit_alloc_memory(compiler, (size)); \ - if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) \ - return error; \ - memset(backtrack, 0, size); \ - backtrack->prev = parent->top; \ - backtrack->cc = (ccstart); \ - parent->top = backtrack; \ - } \ - while (0) - -#define PUSH_BACKTRACK_NOVALUE(size, ccstart) \ - do \ - { \ - backtrack = sljit_alloc_memory(compiler, (size)); \ - if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) \ - return; \ - memset(backtrack, 0, size); \ - backtrack->prev = parent->top; \ - backtrack->cc = (ccstart); \ - parent->top = backtrack; \ - } \ - while (0) - -#define BACKTRACK_AS(type) ((type *)backtrack) - -static void compile_dnref_search(compiler_common *common, pcre_uchar *cc, jump_list **backtracks) -{ -/* The OVECTOR offset goes to TMP2. */ -DEFINE_COMPILER; -int count = GET2(cc, 1 + IMM2_SIZE); -pcre_uchar *slot = common->name_table + GET2(cc, 1) * common->name_entry_size; -unsigned int offset; -jump_list *found = NULL; - -SLJIT_ASSERT(*cc == OP_DNREF || *cc == OP_DNREFI); - -OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(1)); - -count--; -while (count-- > 0) - { - offset = GET2(slot, 0) << 1; - GET_LOCAL_BASE(TMP2, 0, OVECTOR(offset)); - add_jump(compiler, &found, CMP(SLJIT_C_NOT_EQUAL, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset), TMP1, 0)); - slot += common->name_entry_size; - } - -offset = GET2(slot, 0) << 1; -GET_LOCAL_BASE(TMP2, 0, OVECTOR(offset)); -if (backtracks != NULL && !common->jscript_compat) - add_jump(compiler, backtracks, CMP(SLJIT_C_EQUAL, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset), TMP1, 0)); - -set_jumps(found, LABEL()); -} - -static void compile_ref_matchingpath(compiler_common *common, pcre_uchar *cc, jump_list **backtracks, BOOL withchecks, BOOL emptyfail) -{ -DEFINE_COMPILER; -BOOL ref = (*cc == OP_REF || *cc == OP_REFI); -int offset = 0; -struct sljit_jump *jump = NULL; -struct sljit_jump *partial; -struct sljit_jump *nopartial; - -if (ref) - { - offset = GET2(cc, 1) << 1; - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset)); - /* OVECTOR(1) contains the "string begin - 1" constant. */ - if (withchecks && !common->jscript_compat) - add_jump(compiler, backtracks, CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(1))); - } -else - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(TMP2), 0); - -#if defined SUPPORT_UTF && defined SUPPORT_UCP -if (common->utf && *cc == OP_REFI) - { - SLJIT_ASSERT(TMP1 == SLJIT_R0 && STACK_TOP == SLJIT_R1 && TMP2 == SLJIT_R2); - if (ref) - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1)); - else - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(TMP2), sizeof(sljit_sw)); - - if (withchecks) - jump = CMP(SLJIT_C_EQUAL, TMP1, 0, TMP2, 0); - - /* Needed to save important temporary registers. */ - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS0, STACK_TOP, 0); - OP1(SLJIT_MOV, SLJIT_R1, 0, ARGUMENTS, 0); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_R1), SLJIT_OFFSETOF(jit_arguments, uchar_ptr), STR_PTR, 0); - sljit_emit_ijump(compiler, SLJIT_CALL3, SLJIT_IMM, SLJIT_FUNC_OFFSET(do_utf_caselesscmp)); - OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), LOCALS0); - if (common->mode == JIT_COMPILE) - add_jump(compiler, backtracks, CMP(SLJIT_C_LESS_EQUAL, SLJIT_RETURN_REG, 0, SLJIT_IMM, 1)); - else - { - add_jump(compiler, backtracks, CMP(SLJIT_C_EQUAL, SLJIT_RETURN_REG, 0, SLJIT_IMM, 0)); - nopartial = CMP(SLJIT_C_NOT_EQUAL, SLJIT_RETURN_REG, 0, SLJIT_IMM, 1); - check_partial(common, FALSE); - add_jump(compiler, backtracks, JUMP(SLJIT_JUMP)); - JUMPHERE(nopartial); - } - OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_RETURN_REG, 0); - } -else -#endif /* SUPPORT_UTF && SUPPORT_UCP */ - { - if (ref) - OP2(SLJIT_SUB | SLJIT_SET_E, TMP2, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1), TMP1, 0); - else - OP2(SLJIT_SUB | SLJIT_SET_E, TMP2, 0, SLJIT_MEM1(TMP2), sizeof(sljit_sw), TMP1, 0); - - if (withchecks) - jump = JUMP(SLJIT_C_ZERO); - - OP2(SLJIT_ADD, STR_PTR, 0, STR_PTR, 0, TMP2, 0); - partial = CMP(SLJIT_C_GREATER, STR_PTR, 0, STR_END, 0); - if (common->mode == JIT_COMPILE) - add_jump(compiler, backtracks, partial); - - add_jump(compiler, *cc == OP_REF ? &common->casefulcmp : &common->caselesscmp, JUMP(SLJIT_FAST_CALL)); - add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, TMP2, 0, SLJIT_IMM, 0)); - - if (common->mode != JIT_COMPILE) - { - nopartial = JUMP(SLJIT_JUMP); - JUMPHERE(partial); - /* TMP2 -= STR_END - STR_PTR */ - OP2(SLJIT_SUB, TMP2, 0, TMP2, 0, STR_PTR, 0); - OP2(SLJIT_ADD, TMP2, 0, TMP2, 0, STR_END, 0); - partial = CMP(SLJIT_C_EQUAL, TMP2, 0, SLJIT_IMM, 0); - OP1(SLJIT_MOV, STR_PTR, 0, STR_END, 0); - add_jump(compiler, *cc == OP_REF ? &common->casefulcmp : &common->caselesscmp, JUMP(SLJIT_FAST_CALL)); - add_jump(compiler, backtracks, CMP(SLJIT_C_NOT_EQUAL, TMP2, 0, SLJIT_IMM, 0)); - JUMPHERE(partial); - check_partial(common, FALSE); - add_jump(compiler, backtracks, JUMP(SLJIT_JUMP)); - JUMPHERE(nopartial); - } - } - -if (jump != NULL) - { - if (emptyfail) - add_jump(compiler, backtracks, jump); - else - JUMPHERE(jump); - } -} - -static SLJIT_INLINE pcre_uchar *compile_ref_iterator_matchingpath(compiler_common *common, pcre_uchar *cc, backtrack_common *parent) -{ -DEFINE_COMPILER; -BOOL ref = (*cc == OP_REF || *cc == OP_REFI); -backtrack_common *backtrack; -pcre_uchar type; -int offset = 0; -struct sljit_label *label; -struct sljit_jump *zerolength; -struct sljit_jump *jump = NULL; -pcre_uchar *ccbegin = cc; -int min = 0, max = 0; -BOOL minimize; - -PUSH_BACKTRACK(sizeof(iterator_backtrack), cc, NULL); - -if (ref) - offset = GET2(cc, 1) << 1; -else - cc += IMM2_SIZE; -type = cc[1 + IMM2_SIZE]; - -SLJIT_COMPILE_ASSERT((OP_CRSTAR & 0x1) == 0, crstar_opcode_must_be_even); -minimize = (type & 0x1) != 0; -switch(type) - { - case OP_CRSTAR: - case OP_CRMINSTAR: - min = 0; - max = 0; - cc += 1 + IMM2_SIZE + 1; - break; - case OP_CRPLUS: - case OP_CRMINPLUS: - min = 1; - max = 0; - cc += 1 + IMM2_SIZE + 1; - break; - case OP_CRQUERY: - case OP_CRMINQUERY: - min = 0; - max = 1; - cc += 1 + IMM2_SIZE + 1; - break; - case OP_CRRANGE: - case OP_CRMINRANGE: - min = GET2(cc, 1 + IMM2_SIZE + 1); - max = GET2(cc, 1 + IMM2_SIZE + 1 + IMM2_SIZE); - cc += 1 + IMM2_SIZE + 1 + 2 * IMM2_SIZE; - break; - default: - SLJIT_ASSERT_STOP(); - break; - } - -if (!minimize) - { - if (min == 0) - { - allocate_stack(common, 2); - if (ref) - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset)); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(1), SLJIT_IMM, 0); - /* Temporary release of STR_PTR. */ - OP2(SLJIT_SUB, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, sizeof(sljit_sw)); - /* Handles both invalid and empty cases. Since the minimum repeat, - is zero the invalid case is basically the same as an empty case. */ - if (ref) - zerolength = CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1)); - else - { - compile_dnref_search(common, ccbegin, NULL); - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(TMP2), 0); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), POSSESSIVE1, TMP2, 0); - zerolength = CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_MEM1(TMP2), sizeof(sljit_sw)); - } - /* Restore if not zero length. */ - OP2(SLJIT_ADD, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, sizeof(sljit_sw)); - } - else - { - allocate_stack(common, 1); - if (ref) - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset)); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); - if (ref) - { - add_jump(compiler, &backtrack->topbacktracks, CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(1))); - zerolength = CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1)); - } - else - { - compile_dnref_search(common, ccbegin, &backtrack->topbacktracks); - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(TMP2), 0); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), POSSESSIVE1, TMP2, 0); - zerolength = CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_MEM1(TMP2), sizeof(sljit_sw)); - } - } - - if (min > 1 || max > 1) - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), POSSESSIVE0, SLJIT_IMM, 0); - - label = LABEL(); - if (!ref) - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), POSSESSIVE1); - compile_ref_matchingpath(common, ccbegin, &backtrack->topbacktracks, FALSE, FALSE); - - if (min > 1 || max > 1) - { - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), POSSESSIVE0); - OP2(SLJIT_ADD, TMP1, 0, TMP1, 0, SLJIT_IMM, 1); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), POSSESSIVE0, TMP1, 0); - if (min > 1) - CMPTO(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, min, label); - if (max > 1) - { - jump = CMP(SLJIT_C_GREATER_EQUAL, TMP1, 0, SLJIT_IMM, max); - allocate_stack(common, 1); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); - JUMPTO(SLJIT_JUMP, label); - JUMPHERE(jump); - } - } - - if (max == 0) - { - /* Includes min > 1 case as well. */ - allocate_stack(common, 1); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); - JUMPTO(SLJIT_JUMP, label); - } - - JUMPHERE(zerolength); - BACKTRACK_AS(iterator_backtrack)->matchingpath = LABEL(); - - count_match(common); - return cc; - } - -allocate_stack(common, ref ? 2 : 3); -if (ref) - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset)); -OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); -if (type != OP_CRMINSTAR) - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(1), SLJIT_IMM, 0); - -if (min == 0) - { - /* Handles both invalid and empty cases. Since the minimum repeat, - is zero the invalid case is basically the same as an empty case. */ - if (ref) - zerolength = CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1)); - else - { - compile_dnref_search(common, ccbegin, NULL); - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(TMP2), 0); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(2), TMP2, 0); - zerolength = CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_MEM1(TMP2), sizeof(sljit_sw)); - } - /* Length is non-zero, we can match real repeats. */ - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); - jump = JUMP(SLJIT_JUMP); - } -else - { - if (ref) - { - add_jump(compiler, &backtrack->topbacktracks, CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(1))); - zerolength = CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1)); - } - else - { - compile_dnref_search(common, ccbegin, &backtrack->topbacktracks); - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(TMP2), 0); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(2), TMP2, 0); - zerolength = CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_MEM1(TMP2), sizeof(sljit_sw)); - } - } - -BACKTRACK_AS(iterator_backtrack)->matchingpath = LABEL(); -if (max > 0) - add_jump(compiler, &backtrack->topbacktracks, CMP(SLJIT_C_GREATER_EQUAL, SLJIT_MEM1(STACK_TOP), STACK(1), SLJIT_IMM, max)); - -if (!ref) - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), STACK(2)); -compile_ref_matchingpath(common, ccbegin, &backtrack->topbacktracks, TRUE, TRUE); -OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); - -if (min > 1) - { - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(1)); - OP2(SLJIT_ADD, TMP1, 0, TMP1, 0, SLJIT_IMM, 1); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(1), TMP1, 0); - CMPTO(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, min, BACKTRACK_AS(iterator_backtrack)->matchingpath); - } -else if (max > 0) - OP2(SLJIT_ADD, SLJIT_MEM1(STACK_TOP), STACK(1), SLJIT_MEM1(STACK_TOP), STACK(1), SLJIT_IMM, 1); - -if (jump != NULL) - JUMPHERE(jump); -JUMPHERE(zerolength); - -count_match(common); -return cc; -} - -static SLJIT_INLINE pcre_uchar *compile_recurse_matchingpath(compiler_common *common, pcre_uchar *cc, backtrack_common *parent) -{ -DEFINE_COMPILER; -backtrack_common *backtrack; -recurse_entry *entry = common->entries; -recurse_entry *prev = NULL; -sljit_sw start = GET(cc, 1); -pcre_uchar *start_cc; -BOOL needs_control_head; - -PUSH_BACKTRACK(sizeof(recurse_backtrack), cc, NULL); - -/* Inlining simple patterns. */ -if (get_framesize(common, common->start + start, NULL, TRUE, &needs_control_head) == no_stack) - { - start_cc = common->start + start; - compile_matchingpath(common, next_opcode(common, start_cc), bracketend(start_cc) - (1 + LINK_SIZE), backtrack); - BACKTRACK_AS(recurse_backtrack)->inlined_pattern = TRUE; - return cc + 1 + LINK_SIZE; - } - -while (entry != NULL) - { - if (entry->start == start) - break; - prev = entry; - entry = entry->next; - } - -if (entry == NULL) - { - entry = sljit_alloc_memory(compiler, sizeof(recurse_entry)); - if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) - return NULL; - entry->next = NULL; - entry->entry = NULL; - entry->calls = NULL; - entry->start = start; - - if (prev != NULL) - prev->next = entry; - else - common->entries = entry; - } - -if (common->has_set_som && common->mark_ptr != 0) - { - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(0)); - allocate_stack(common, 2); - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->mark_ptr); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), TMP2, 0); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(1), TMP1, 0); - } -else if (common->has_set_som || common->mark_ptr != 0) - { - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), common->has_set_som ? (int)(OVECTOR(0)) : common->mark_ptr); - allocate_stack(common, 1); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), TMP2, 0); - } - -if (entry->entry == NULL) - add_jump(compiler, &entry->calls, JUMP(SLJIT_FAST_CALL)); -else - JUMPTO(SLJIT_FAST_CALL, entry->entry); -/* Leave if the match is failed. */ -add_jump(compiler, &backtrack->topbacktracks, CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, 0)); -return cc + 1 + LINK_SIZE; -} - -static int SLJIT_CALL do_callout(struct jit_arguments* arguments, PUBL(callout_block) *callout_block, pcre_uchar **jit_ovector) -{ -const pcre_uchar *begin = arguments->begin; -int *offset_vector = arguments->offsets; -int offset_count = arguments->offset_count; -int i; - -if (PUBL(callout) == NULL) - return 0; - -callout_block->version = 2; -callout_block->callout_data = arguments->callout_data; - -/* Offsets in subject. */ -callout_block->subject_length = arguments->end - arguments->begin; -callout_block->start_match = (pcre_uchar*)callout_block->subject - arguments->begin; -callout_block->current_position = (pcre_uchar*)callout_block->offset_vector - arguments->begin; -#if defined COMPILE_PCRE8 -callout_block->subject = (PCRE_SPTR)begin; -#elif defined COMPILE_PCRE16 -callout_block->subject = (PCRE_SPTR16)begin; -#elif defined COMPILE_PCRE32 -callout_block->subject = (PCRE_SPTR32)begin; -#endif - -/* Convert and copy the JIT offset vector to the offset_vector array. */ -callout_block->capture_top = 0; -callout_block->offset_vector = offset_vector; -for (i = 2; i < offset_count; i += 2) - { - offset_vector[i] = jit_ovector[i] - begin; - offset_vector[i + 1] = jit_ovector[i + 1] - begin; - if (jit_ovector[i] >= begin) - callout_block->capture_top = i; - } - -callout_block->capture_top = (callout_block->capture_top >> 1) + 1; -if (offset_count > 0) - offset_vector[0] = -1; -if (offset_count > 1) - offset_vector[1] = -1; -return (*PUBL(callout))(callout_block); -} - -/* Aligning to 8 byte. */ -#define CALLOUT_ARG_SIZE \ - (((int)sizeof(PUBL(callout_block)) + 7) & ~7) - -#define CALLOUT_ARG_OFFSET(arg) \ - (-CALLOUT_ARG_SIZE + SLJIT_OFFSETOF(PUBL(callout_block), arg)) - -static SLJIT_INLINE pcre_uchar *compile_callout_matchingpath(compiler_common *common, pcre_uchar *cc, backtrack_common *parent) -{ -DEFINE_COMPILER; -backtrack_common *backtrack; - -PUSH_BACKTRACK(sizeof(backtrack_common), cc, NULL); - -allocate_stack(common, CALLOUT_ARG_SIZE / sizeof(sljit_sw)); - -OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), common->capture_last_ptr); -OP1(SLJIT_MOV, TMP1, 0, ARGUMENTS, 0); -SLJIT_ASSERT(common->capture_last_ptr != 0); -OP1(SLJIT_MOV_SI, SLJIT_MEM1(STACK_TOP), CALLOUT_ARG_OFFSET(callout_number), SLJIT_IMM, cc[1]); -OP1(SLJIT_MOV_SI, SLJIT_MEM1(STACK_TOP), CALLOUT_ARG_OFFSET(capture_last), TMP2, 0); - -/* These pointer sized fields temporarly stores internal variables. */ -OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(0)); -OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), CALLOUT_ARG_OFFSET(offset_vector), STR_PTR, 0); -OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), CALLOUT_ARG_OFFSET(subject), TMP2, 0); - -if (common->mark_ptr != 0) - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, mark_ptr)); -OP1(SLJIT_MOV_SI, SLJIT_MEM1(STACK_TOP), CALLOUT_ARG_OFFSET(pattern_position), SLJIT_IMM, GET(cc, 2)); -OP1(SLJIT_MOV_SI, SLJIT_MEM1(STACK_TOP), CALLOUT_ARG_OFFSET(next_item_length), SLJIT_IMM, GET(cc, 2 + LINK_SIZE)); -OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), CALLOUT_ARG_OFFSET(mark), (common->mark_ptr != 0) ? TMP2 : SLJIT_IMM, 0); - -/* Needed to save important temporary registers. */ -OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS0, STACK_TOP, 0); -OP2(SLJIT_SUB, SLJIT_R1, 0, STACK_TOP, 0, SLJIT_IMM, CALLOUT_ARG_SIZE); -GET_LOCAL_BASE(SLJIT_R2, 0, OVECTOR_START); -sljit_emit_ijump(compiler, SLJIT_CALL3, SLJIT_IMM, SLJIT_FUNC_OFFSET(do_callout)); -OP1(SLJIT_MOV_SI, SLJIT_RETURN_REG, 0, SLJIT_RETURN_REG, 0); -OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), LOCALS0); -free_stack(common, CALLOUT_ARG_SIZE / sizeof(sljit_sw)); - -/* Check return value. */ -OP2(SLJIT_SUB | SLJIT_SET_S, SLJIT_UNUSED, 0, SLJIT_RETURN_REG, 0, SLJIT_IMM, 0); -add_jump(compiler, &backtrack->topbacktracks, JUMP(SLJIT_C_SIG_GREATER)); -if (common->forced_quit_label == NULL) - add_jump(compiler, &common->forced_quit, JUMP(SLJIT_C_SIG_LESS)); -else - JUMPTO(SLJIT_C_SIG_LESS, common->forced_quit_label); -return cc + 2 + 2 * LINK_SIZE; -} - -#undef CALLOUT_ARG_SIZE -#undef CALLOUT_ARG_OFFSET - -static pcre_uchar *compile_assert_matchingpath(compiler_common *common, pcre_uchar *cc, assert_backtrack *backtrack, BOOL conditional) -{ -DEFINE_COMPILER; -int framesize; -int extrasize; -BOOL needs_control_head; -int private_data_ptr; -backtrack_common altbacktrack; -pcre_uchar *ccbegin; -pcre_uchar opcode; -pcre_uchar bra = OP_BRA; -jump_list *tmp = NULL; -jump_list **target = (conditional) ? &backtrack->condfailed : &backtrack->common.topbacktracks; -jump_list **found; -/* Saving previous accept variables. */ -BOOL save_local_exit = common->local_exit; -BOOL save_positive_assert = common->positive_assert; -then_trap_backtrack *save_then_trap = common->then_trap; -struct sljit_label *save_quit_label = common->quit_label; -struct sljit_label *save_accept_label = common->accept_label; -jump_list *save_quit = common->quit; -jump_list *save_positive_assert_quit = common->positive_assert_quit; -jump_list *save_accept = common->accept; -struct sljit_jump *jump; -struct sljit_jump *brajump = NULL; - -/* Assert captures then. */ -common->then_trap = NULL; - -if (*cc == OP_BRAZERO || *cc == OP_BRAMINZERO) - { - SLJIT_ASSERT(!conditional); - bra = *cc; - cc++; - } -private_data_ptr = PRIVATE_DATA(cc); -SLJIT_ASSERT(private_data_ptr != 0); -framesize = get_framesize(common, cc, NULL, FALSE, &needs_control_head); -backtrack->framesize = framesize; -backtrack->private_data_ptr = private_data_ptr; -opcode = *cc; -SLJIT_ASSERT(opcode >= OP_ASSERT && opcode <= OP_ASSERTBACK_NOT); -found = (opcode == OP_ASSERT || opcode == OP_ASSERTBACK) ? &tmp : target; -ccbegin = cc; -cc += GET(cc, 1); - -if (bra == OP_BRAMINZERO) - { - /* This is a braminzero backtrack path. */ - OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); - free_stack(common, 1); - brajump = CMP(SLJIT_C_EQUAL, STR_PTR, 0, SLJIT_IMM, 0); - } - -if (framesize < 0) - { - extrasize = needs_control_head ? 2 : 1; - if (framesize == no_frame) - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, STACK_TOP, 0); - allocate_stack(common, extrasize); - if (needs_control_head) - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); - if (needs_control_head) - { - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, SLJIT_IMM, 0); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(1), TMP1, 0); - } - } -else - { - extrasize = needs_control_head ? 3 : 2; - allocate_stack(common, framesize + extrasize); - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); - OP2(SLJIT_SUB, TMP2, 0, STACK_TOP, 0, SLJIT_IMM, (framesize + extrasize) * sizeof(sljit_sw)); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, TMP2, 0); - if (needs_control_head) - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); - if (needs_control_head) - { - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(2), TMP1, 0); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(1), TMP2, 0); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, SLJIT_IMM, 0); - } - else - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(1), TMP1, 0); - init_frame(common, ccbegin, NULL, framesize + extrasize - 1, extrasize, FALSE); - } - -memset(&altbacktrack, 0, sizeof(backtrack_common)); -if (opcode == OP_ASSERT_NOT || opcode == OP_ASSERTBACK_NOT) - { - /* Negative assert is stronger than positive assert. */ - common->local_exit = TRUE; - common->quit_label = NULL; - common->quit = NULL; - common->positive_assert = FALSE; - } -else - common->positive_assert = TRUE; -common->positive_assert_quit = NULL; - -while (1) - { - common->accept_label = NULL; - common->accept = NULL; - altbacktrack.top = NULL; - altbacktrack.topbacktracks = NULL; - - if (*ccbegin == OP_ALT) - OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); - - altbacktrack.cc = ccbegin; - compile_matchingpath(common, ccbegin + 1 + LINK_SIZE, cc, &altbacktrack); - if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) - { - if (opcode == OP_ASSERT_NOT || opcode == OP_ASSERTBACK_NOT) - { - common->local_exit = save_local_exit; - common->quit_label = save_quit_label; - common->quit = save_quit; - } - common->positive_assert = save_positive_assert; - common->then_trap = save_then_trap; - common->accept_label = save_accept_label; - common->positive_assert_quit = save_positive_assert_quit; - common->accept = save_accept; - return NULL; - } - common->accept_label = LABEL(); - if (common->accept != NULL) - set_jumps(common->accept, common->accept_label); - - /* Reset stack. */ - if (framesize < 0) - { - if (framesize == no_frame) - OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); - else - free_stack(common, extrasize); - if (needs_control_head) - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, SLJIT_MEM1(STACK_TOP), 0); - } - else - { - if ((opcode != OP_ASSERT_NOT && opcode != OP_ASSERTBACK_NOT) || conditional) - { - /* We don't need to keep the STR_PTR, only the previous private_data_ptr. */ - OP2(SLJIT_ADD, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr, SLJIT_IMM, (framesize + 1) * sizeof(sljit_sw)); - if (needs_control_head) - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, SLJIT_MEM1(STACK_TOP), 0); - } - else - { - OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); - if (needs_control_head) - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, SLJIT_MEM1(STACK_TOP), (framesize + 1) * sizeof(sljit_sw)); - add_jump(compiler, &common->revertframes, JUMP(SLJIT_FAST_CALL)); - } - } - - if (opcode == OP_ASSERT_NOT || opcode == OP_ASSERTBACK_NOT) - { - /* We know that STR_PTR was stored on the top of the stack. */ - if (conditional) - OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), needs_control_head ? sizeof(sljit_sw) : 0); - else if (bra == OP_BRAZERO) - { - if (framesize < 0) - OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), (extrasize - 1) * sizeof(sljit_sw)); - else - { - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), framesize * sizeof(sljit_sw)); - OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), (framesize + extrasize - 1) * sizeof(sljit_sw)); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, TMP1, 0); - } - OP2(SLJIT_ADD, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, sizeof(sljit_sw)); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); - } - else if (framesize >= 0) - { - /* For OP_BRA and OP_BRAMINZERO. */ - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, SLJIT_MEM1(STACK_TOP), framesize * sizeof(sljit_sw)); - } - } - add_jump(compiler, found, JUMP(SLJIT_JUMP)); - - compile_backtrackingpath(common, altbacktrack.top); - if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) - { - if (opcode == OP_ASSERT_NOT || opcode == OP_ASSERTBACK_NOT) - { - common->local_exit = save_local_exit; - common->quit_label = save_quit_label; - common->quit = save_quit; - } - common->positive_assert = save_positive_assert; - common->then_trap = save_then_trap; - common->accept_label = save_accept_label; - common->positive_assert_quit = save_positive_assert_quit; - common->accept = save_accept; - return NULL; - } - set_jumps(altbacktrack.topbacktracks, LABEL()); - - if (*cc != OP_ALT) - break; - - ccbegin = cc; - cc += GET(cc, 1); - } - -if (opcode == OP_ASSERT_NOT || opcode == OP_ASSERTBACK_NOT) - { - SLJIT_ASSERT(common->positive_assert_quit == NULL); - /* Makes the check less complicated below. */ - common->positive_assert_quit = common->quit; - } - -/* None of them matched. */ -if (common->positive_assert_quit != NULL) - { - jump = JUMP(SLJIT_JUMP); - set_jumps(common->positive_assert_quit, LABEL()); - SLJIT_ASSERT(framesize != no_stack); - if (framesize < 0) - OP2(SLJIT_ADD, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr, SLJIT_IMM, extrasize * sizeof(sljit_sw)); - else - { - OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); - add_jump(compiler, &common->revertframes, JUMP(SLJIT_FAST_CALL)); - OP2(SLJIT_ADD, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, (framesize + extrasize) * sizeof(sljit_sw)); - } - JUMPHERE(jump); - } - -if (needs_control_head) - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, SLJIT_MEM1(STACK_TOP), STACK(1)); - -if (opcode == OP_ASSERT || opcode == OP_ASSERTBACK) - { - /* Assert is failed. */ - if (conditional || bra == OP_BRAZERO) - OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); - - if (framesize < 0) - { - /* The topmost item should be 0. */ - if (bra == OP_BRAZERO) - { - if (extrasize == 2) - free_stack(common, 1); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); - } - else - free_stack(common, extrasize); - } - else - { - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(extrasize - 1)); - /* The topmost item should be 0. */ - if (bra == OP_BRAZERO) - { - free_stack(common, framesize + extrasize - 1); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); - } - else - free_stack(common, framesize + extrasize); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, TMP1, 0); - } - jump = JUMP(SLJIT_JUMP); - if (bra != OP_BRAZERO) - add_jump(compiler, target, jump); - - /* Assert is successful. */ - set_jumps(tmp, LABEL()); - if (framesize < 0) - { - /* We know that STR_PTR was stored on the top of the stack. */ - OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), (extrasize - 1) * sizeof(sljit_sw)); - /* Keep the STR_PTR on the top of the stack. */ - if (bra == OP_BRAZERO) - { - OP2(SLJIT_ADD, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, sizeof(sljit_sw)); - if (extrasize == 2) - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); - } - else if (bra == OP_BRAMINZERO) - { - OP2(SLJIT_ADD, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, sizeof(sljit_sw)); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); - } - } - else - { - if (bra == OP_BRA) - { - /* We don't need to keep the STR_PTR, only the previous private_data_ptr. */ - OP2(SLJIT_ADD, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr, SLJIT_IMM, (framesize + 1) * sizeof(sljit_sw)); - OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), (extrasize - 2) * sizeof(sljit_sw)); - } - else - { - /* We don't need to keep the STR_PTR, only the previous private_data_ptr. */ - OP2(SLJIT_ADD, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr, SLJIT_IMM, (framesize + 2) * sizeof(sljit_sw)); - if (extrasize == 2) - { - OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); - if (bra == OP_BRAMINZERO) - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); - } - else - { - OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), 0); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), bra == OP_BRAZERO ? STR_PTR : SLJIT_IMM, 0); - } - } - } - - if (bra == OP_BRAZERO) - { - backtrack->matchingpath = LABEL(); - SET_LABEL(jump, backtrack->matchingpath); - } - else if (bra == OP_BRAMINZERO) - { - JUMPTO(SLJIT_JUMP, backtrack->matchingpath); - JUMPHERE(brajump); - if (framesize >= 0) - { - OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); - add_jump(compiler, &common->revertframes, JUMP(SLJIT_FAST_CALL)); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, SLJIT_MEM1(STACK_TOP), framesize * sizeof(sljit_sw)); - } - set_jumps(backtrack->common.topbacktracks, LABEL()); - } - } -else - { - /* AssertNot is successful. */ - if (framesize < 0) - { - OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); - if (bra != OP_BRA) - { - if (extrasize == 2) - free_stack(common, 1); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); - } - else - free_stack(common, extrasize); - } - else - { - OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(extrasize - 1)); - /* The topmost item should be 0. */ - if (bra != OP_BRA) - { - free_stack(common, framesize + extrasize - 1); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); - } - else - free_stack(common, framesize + extrasize); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, TMP1, 0); - } - - if (bra == OP_BRAZERO) - backtrack->matchingpath = LABEL(); - else if (bra == OP_BRAMINZERO) - { - JUMPTO(SLJIT_JUMP, backtrack->matchingpath); - JUMPHERE(brajump); - } - - if (bra != OP_BRA) - { - SLJIT_ASSERT(found == &backtrack->common.topbacktracks); - set_jumps(backtrack->common.topbacktracks, LABEL()); - backtrack->common.topbacktracks = NULL; - } - } - -if (opcode == OP_ASSERT_NOT || opcode == OP_ASSERTBACK_NOT) - { - common->local_exit = save_local_exit; - common->quit_label = save_quit_label; - common->quit = save_quit; - } -common->positive_assert = save_positive_assert; -common->then_trap = save_then_trap; -common->accept_label = save_accept_label; -common->positive_assert_quit = save_positive_assert_quit; -common->accept = save_accept; -return cc + 1 + LINK_SIZE; -} - -static SLJIT_INLINE void match_once_common(compiler_common *common, pcre_uchar ket, int framesize, int private_data_ptr, BOOL has_alternatives, BOOL needs_control_head) -{ -DEFINE_COMPILER; -int stacksize; - -if (framesize < 0) - { - if (framesize == no_frame) - OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); - else - { - stacksize = needs_control_head ? 1 : 0; - if (ket != OP_KET || has_alternatives) - stacksize++; - free_stack(common, stacksize); - } - - if (needs_control_head) - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), (ket != OP_KET || has_alternatives) ? sizeof(sljit_sw) : 0); - - /* TMP2 which is set here used by OP_KETRMAX below. */ - if (ket == OP_KETRMAX) - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), 0); - else if (ket == OP_KETRMIN) - { - /* Move the STR_PTR to the private_data_ptr. */ - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, SLJIT_MEM1(STACK_TOP), 0); - } - } -else - { - stacksize = (ket != OP_KET || has_alternatives) ? 2 : 1; - OP2(SLJIT_ADD, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr, SLJIT_IMM, (framesize + stacksize) * sizeof(sljit_sw)); - if (needs_control_head) - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), 0); - - if (ket == OP_KETRMAX) - { - /* TMP2 which is set here used by OP_KETRMAX below. */ - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); - } - } -if (needs_control_head) - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, TMP1, 0); -} - -static SLJIT_INLINE int match_capture_common(compiler_common *common, int stacksize, int offset, int private_data_ptr) -{ -DEFINE_COMPILER; - -if (common->capture_last_ptr != 0) - { - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->capture_last_ptr); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->capture_last_ptr, SLJIT_IMM, offset >> 1); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), TMP1, 0); - stacksize++; - } -if (common->optimized_cbracket[offset >> 1] == 0) - { - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset)); - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1)); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), TMP1, 0); - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize + 1), TMP2, 0); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1), STR_PTR, 0); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset), TMP1, 0); - stacksize += 2; - } -return stacksize; -} - -/* - Handling bracketed expressions is probably the most complex part. - - Stack layout naming characters: - S - Push the current STR_PTR - 0 - Push a 0 (NULL) - A - Push the current STR_PTR. Needed for restoring the STR_PTR - before the next alternative. Not pushed if there are no alternatives. - M - Any values pushed by the current alternative. Can be empty, or anything. - C - Push the previous OVECTOR(i), OVECTOR(i+1) and OVECTOR_PRIV(i) to the stack. - L - Push the previous local (pointed by localptr) to the stack - () - opional values stored on the stack - ()* - optonal, can be stored multiple times - - The following list shows the regular expression templates, their PCRE byte codes - and stack layout supported by pcre-sljit. - - (?:) OP_BRA | OP_KET A M - () OP_CBRA | OP_KET C M - (?:)+ OP_BRA | OP_KETRMAX 0 A M S ( A M S )* - OP_SBRA | OP_KETRMAX 0 L M S ( L M S )* - (?:)+? OP_BRA | OP_KETRMIN 0 A M S ( A M S )* - OP_SBRA | OP_KETRMIN 0 L M S ( L M S )* - ()+ OP_CBRA | OP_KETRMAX 0 C M S ( C M S )* - OP_SCBRA | OP_KETRMAX 0 C M S ( C M S )* - ()+? OP_CBRA | OP_KETRMIN 0 C M S ( C M S )* - OP_SCBRA | OP_KETRMIN 0 C M S ( C M S )* - (?:)? OP_BRAZERO | OP_BRA | OP_KET S ( A M 0 ) - (?:)?? OP_BRAMINZERO | OP_BRA | OP_KET S ( A M 0 ) - ()? OP_BRAZERO | OP_CBRA | OP_KET S ( C M 0 ) - ()?? OP_BRAMINZERO | OP_CBRA | OP_KET S ( C M 0 ) - (?:)* OP_BRAZERO | OP_BRA | OP_KETRMAX S 0 ( A M S )* - OP_BRAZERO | OP_SBRA | OP_KETRMAX S 0 ( L M S )* - (?:)*? OP_BRAMINZERO | OP_BRA | OP_KETRMIN S 0 ( A M S )* - OP_BRAMINZERO | OP_SBRA | OP_KETRMIN S 0 ( L M S )* - ()* OP_BRAZERO | OP_CBRA | OP_KETRMAX S 0 ( C M S )* - OP_BRAZERO | OP_SCBRA | OP_KETRMAX S 0 ( C M S )* - ()*? OP_BRAMINZERO | OP_CBRA | OP_KETRMIN S 0 ( C M S )* - OP_BRAMINZERO | OP_SCBRA | OP_KETRMIN S 0 ( C M S )* - - - Stack layout naming characters: - A - Push the alternative index (starting from 0) on the stack. - Not pushed if there is no alternatives. - M - Any values pushed by the current alternative. Can be empty, or anything. - - The next list shows the possible content of a bracket: - (|) OP_*BRA | OP_ALT ... M A - (?()|) OP_*COND | OP_ALT M A - (?>|) OP_ONCE | OP_ALT ... [stack trace] M A - (?>|) OP_ONCE_NC | OP_ALT ... [stack trace] M A - Or nothing, if trace is unnecessary -*/ - -static pcre_uchar *compile_bracket_matchingpath(compiler_common *common, pcre_uchar *cc, backtrack_common *parent) -{ -DEFINE_COMPILER; -backtrack_common *backtrack; -pcre_uchar opcode; -int private_data_ptr = 0; -int offset = 0; -int i, stacksize; -int repeat_ptr = 0, repeat_length = 0; -int repeat_type = 0, repeat_count = 0; -pcre_uchar *ccbegin; -pcre_uchar *matchingpath; -pcre_uchar *slot; -pcre_uchar bra = OP_BRA; -pcre_uchar ket; -assert_backtrack *assert; -BOOL has_alternatives; -BOOL needs_control_head = FALSE; -struct sljit_jump *jump; -struct sljit_jump *skip; -struct sljit_label *rmax_label = NULL; -struct sljit_jump *braminzero = NULL; - -PUSH_BACKTRACK(sizeof(bracket_backtrack), cc, NULL); - -if (*cc == OP_BRAZERO || *cc == OP_BRAMINZERO) - { - bra = *cc; - cc++; - opcode = *cc; - } - -opcode = *cc; -ccbegin = cc; -matchingpath = bracketend(cc) - 1 - LINK_SIZE; -ket = *matchingpath; -if (ket == OP_KET && PRIVATE_DATA(matchingpath) != 0) - { - repeat_ptr = PRIVATE_DATA(matchingpath); - repeat_length = PRIVATE_DATA(matchingpath + 1); - repeat_type = PRIVATE_DATA(matchingpath + 2); - repeat_count = PRIVATE_DATA(matchingpath + 3); - SLJIT_ASSERT(repeat_length != 0 && repeat_type != 0 && repeat_count != 0); - if (repeat_type == OP_UPTO) - ket = OP_KETRMAX; - if (repeat_type == OP_MINUPTO) - ket = OP_KETRMIN; - } - -if ((opcode == OP_COND || opcode == OP_SCOND) && cc[1 + LINK_SIZE] == OP_DEF) - { - /* Drop this bracket_backtrack. */ - parent->top = backtrack->prev; - return matchingpath + 1 + LINK_SIZE + repeat_length; - } - -matchingpath = ccbegin + 1 + LINK_SIZE; -SLJIT_ASSERT(ket == OP_KET || ket == OP_KETRMAX || ket == OP_KETRMIN); -SLJIT_ASSERT(!((bra == OP_BRAZERO && ket == OP_KETRMIN) || (bra == OP_BRAMINZERO && ket == OP_KETRMAX))); -cc += GET(cc, 1); - -has_alternatives = *cc == OP_ALT; -if (SLJIT_UNLIKELY(opcode == OP_COND || opcode == OP_SCOND)) - has_alternatives = (*matchingpath == OP_RREF || *matchingpath == OP_DNRREF) ? FALSE : TRUE; - -if (SLJIT_UNLIKELY(opcode == OP_COND) && (*cc == OP_KETRMAX || *cc == OP_KETRMIN)) - opcode = OP_SCOND; -if (SLJIT_UNLIKELY(opcode == OP_ONCE_NC)) - opcode = OP_ONCE; - -if (opcode == OP_CBRA || opcode == OP_SCBRA) - { - /* Capturing brackets has a pre-allocated space. */ - offset = GET2(ccbegin, 1 + LINK_SIZE); - if (common->optimized_cbracket[offset] == 0) - { - private_data_ptr = OVECTOR_PRIV(offset); - offset <<= 1; - } - else - { - offset <<= 1; - private_data_ptr = OVECTOR(offset); - } - BACKTRACK_AS(bracket_backtrack)->private_data_ptr = private_data_ptr; - matchingpath += IMM2_SIZE; - } -else if (opcode == OP_ONCE || opcode == OP_SBRA || opcode == OP_SCOND) - { - /* Other brackets simply allocate the next entry. */ - private_data_ptr = PRIVATE_DATA(ccbegin); - SLJIT_ASSERT(private_data_ptr != 0); - BACKTRACK_AS(bracket_backtrack)->private_data_ptr = private_data_ptr; - if (opcode == OP_ONCE) - BACKTRACK_AS(bracket_backtrack)->u.framesize = get_framesize(common, ccbegin, NULL, FALSE, &needs_control_head); - } - -/* Instructions before the first alternative. */ -stacksize = 0; -if (ket == OP_KETRMAX || (ket == OP_KETRMIN && bra != OP_BRAMINZERO)) - stacksize++; -if (bra == OP_BRAZERO) - stacksize++; - -if (stacksize > 0) - allocate_stack(common, stacksize); - -stacksize = 0; -if (ket == OP_KETRMAX || (ket == OP_KETRMIN && bra != OP_BRAMINZERO)) - { - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), SLJIT_IMM, 0); - stacksize++; - } - -if (bra == OP_BRAZERO) - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), STR_PTR, 0); - -if (bra == OP_BRAMINZERO) - { - /* This is a backtrack path! (Since the try-path of OP_BRAMINZERO matches to the empty string) */ - OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); - if (ket != OP_KETRMIN) - { - free_stack(common, 1); - braminzero = CMP(SLJIT_C_EQUAL, STR_PTR, 0, SLJIT_IMM, 0); - } - else - { - if (opcode == OP_ONCE || opcode >= OP_SBRA) - { - jump = CMP(SLJIT_C_NOT_EQUAL, STR_PTR, 0, SLJIT_IMM, 0); - OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(1)); - /* Nothing stored during the first run. */ - skip = JUMP(SLJIT_JUMP); - JUMPHERE(jump); - /* Checking zero-length iteration. */ - if (opcode != OP_ONCE || BACKTRACK_AS(bracket_backtrack)->u.framesize < 0) - { - /* When we come from outside, private_data_ptr contains the previous STR_PTR. */ - braminzero = CMP(SLJIT_C_EQUAL, STR_PTR, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); - } - else - { - /* Except when the whole stack frame must be saved. */ - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); - braminzero = CMP(SLJIT_C_EQUAL, STR_PTR, 0, SLJIT_MEM1(TMP1), (BACKTRACK_AS(bracket_backtrack)->u.framesize + 1) * sizeof(sljit_sw)); - } - JUMPHERE(skip); - } - else - { - jump = CMP(SLJIT_C_NOT_EQUAL, STR_PTR, 0, SLJIT_IMM, 0); - OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(1)); - JUMPHERE(jump); - } - } - } - -if (repeat_type != 0) - { - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), repeat_ptr, SLJIT_IMM, repeat_count); - if (repeat_type == OP_EXACT) - rmax_label = LABEL(); - } - -if (ket == OP_KETRMIN) - BACKTRACK_AS(bracket_backtrack)->recursive_matchingpath = LABEL(); - -if (ket == OP_KETRMAX) - { - rmax_label = LABEL(); - if (has_alternatives && opcode != OP_ONCE && opcode < OP_SBRA && repeat_type == 0) - BACKTRACK_AS(bracket_backtrack)->alternative_matchingpath = rmax_label; - } - -/* Handling capturing brackets and alternatives. */ -if (opcode == OP_ONCE) - { - stacksize = 0; - if (needs_control_head) - { - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr); - stacksize++; - } - - if (BACKTRACK_AS(bracket_backtrack)->u.framesize < 0) - { - /* Neither capturing brackets nor recursions are found in the block. */ - if (ket == OP_KETRMIN) - { - stacksize += 2; - if (!needs_control_head) - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); - } - else - { - if (BACKTRACK_AS(bracket_backtrack)->u.framesize == no_frame) - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, STACK_TOP, 0); - if (ket == OP_KETRMAX || has_alternatives) - stacksize++; - } - - if (stacksize > 0) - allocate_stack(common, stacksize); - - stacksize = 0; - if (needs_control_head) - { - stacksize++; - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), TMP2, 0); - } - - if (ket == OP_KETRMIN) - { - if (needs_control_head) - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), STR_PTR, 0); - if (BACKTRACK_AS(bracket_backtrack)->u.framesize == no_frame) - OP2(SLJIT_SUB, SLJIT_MEM1(SLJIT_SP), private_data_ptr, STACK_TOP, 0, SLJIT_IMM, needs_control_head ? (2 * sizeof(sljit_sw)) : sizeof(sljit_sw)); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize + 1), TMP2, 0); - } - else if (ket == OP_KETRMAX || has_alternatives) - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), STR_PTR, 0); - } - else - { - if (ket != OP_KET || has_alternatives) - stacksize++; - - stacksize += BACKTRACK_AS(bracket_backtrack)->u.framesize + 1; - allocate_stack(common, stacksize); - - if (needs_control_head) - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), TMP2, 0); - - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); - OP2(SLJIT_SUB, TMP2, 0, STACK_TOP, 0, SLJIT_IMM, stacksize * sizeof(sljit_sw)); - - stacksize = needs_control_head ? 1 : 0; - if (ket != OP_KET || has_alternatives) - { - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), STR_PTR, 0); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, TMP2, 0); - stacksize++; - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), TMP1, 0); - } - else - { - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, TMP2, 0); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), TMP1, 0); - } - init_frame(common, ccbegin, NULL, BACKTRACK_AS(bracket_backtrack)->u.framesize + stacksize, stacksize + 1, FALSE); - } - } -else if (opcode == OP_CBRA || opcode == OP_SCBRA) - { - /* Saving the previous values. */ - if (common->optimized_cbracket[offset >> 1] != 0) - { - SLJIT_ASSERT(private_data_ptr == OVECTOR(offset)); - allocate_stack(common, 2); - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr + sizeof(sljit_sw)); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, STR_PTR, 0); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), TMP1, 0); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(1), TMP2, 0); - } - else - { - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); - allocate_stack(common, 1); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, STR_PTR, 0); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), TMP2, 0); - } - } -else if (opcode == OP_SBRA || opcode == OP_SCOND) - { - /* Saving the previous value. */ - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); - allocate_stack(common, 1); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, STR_PTR, 0); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), TMP2, 0); - } -else if (has_alternatives) - { - /* Pushing the starting string pointer. */ - allocate_stack(common, 1); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); - } - -/* Generating code for the first alternative. */ -if (opcode == OP_COND || opcode == OP_SCOND) - { - if (*matchingpath == OP_CREF) - { - SLJIT_ASSERT(has_alternatives); - add_jump(compiler, &(BACKTRACK_AS(bracket_backtrack)->u.condfailed), - CMP(SLJIT_C_EQUAL, SLJIT_MEM1(SLJIT_SP), OVECTOR(GET2(matchingpath, 1) << 1), SLJIT_MEM1(SLJIT_SP), OVECTOR(1))); - matchingpath += 1 + IMM2_SIZE; - } - else if (*matchingpath == OP_DNCREF) - { - SLJIT_ASSERT(has_alternatives); - - i = GET2(matchingpath, 1 + IMM2_SIZE); - slot = common->name_table + GET2(matchingpath, 1) * common->name_entry_size; - OP1(SLJIT_MOV, TMP3, 0, STR_PTR, 0); - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(1)); - OP2(SLJIT_SUB | SLJIT_SET_E, TMP2, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(GET2(slot, 0) << 1), TMP1, 0); - slot += common->name_entry_size; - i--; - while (i-- > 0) - { - OP2(SLJIT_SUB, STR_PTR, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(GET2(slot, 0) << 1), TMP1, 0); - OP2(SLJIT_OR | SLJIT_SET_E, TMP2, 0, TMP2, 0, STR_PTR, 0); - slot += common->name_entry_size; - } - OP1(SLJIT_MOV, STR_PTR, 0, TMP3, 0); - add_jump(compiler, &(BACKTRACK_AS(bracket_backtrack)->u.condfailed), JUMP(SLJIT_C_ZERO)); - matchingpath += 1 + 2 * IMM2_SIZE; - } - else if (*matchingpath == OP_RREF || *matchingpath == OP_DNRREF) - { - /* Never has other case. */ - BACKTRACK_AS(bracket_backtrack)->u.condfailed = NULL; - SLJIT_ASSERT(!has_alternatives); - - if (*matchingpath == OP_RREF) - { - stacksize = GET2(matchingpath, 1); - if (common->currententry == NULL) - stacksize = 0; - else if (stacksize == RREF_ANY) - stacksize = 1; - else if (common->currententry->start == 0) - stacksize = stacksize == 0; - else - stacksize = stacksize == (int)GET2(common->start, common->currententry->start + 1 + LINK_SIZE); - - if (stacksize != 0) - matchingpath += 1 + IMM2_SIZE; - } - else - { - if (common->currententry == NULL || common->currententry->start == 0) - stacksize = 0; - else - { - stacksize = GET2(matchingpath, 1 + IMM2_SIZE); - slot = common->name_table + GET2(matchingpath, 1) * common->name_entry_size; - i = (int)GET2(common->start, common->currententry->start + 1 + LINK_SIZE); - while (stacksize > 0) - { - if ((int)GET2(slot, 0) == i) - break; - slot += common->name_entry_size; - stacksize--; - } - } - - if (stacksize != 0) - matchingpath += 1 + 2 * IMM2_SIZE; - } - - /* The stacksize == 0 is a common "else" case. */ - if (stacksize == 0) - { - if (*cc == OP_ALT) - { - matchingpath = cc + 1 + LINK_SIZE; - cc += GET(cc, 1); - } - else - matchingpath = cc; - } - } - else - { - SLJIT_ASSERT(has_alternatives && *matchingpath >= OP_ASSERT && *matchingpath <= OP_ASSERTBACK_NOT); - /* Similar code as PUSH_BACKTRACK macro. */ - assert = sljit_alloc_memory(compiler, sizeof(assert_backtrack)); - if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) - return NULL; - memset(assert, 0, sizeof(assert_backtrack)); - assert->common.cc = matchingpath; - BACKTRACK_AS(bracket_backtrack)->u.assert = assert; - matchingpath = compile_assert_matchingpath(common, matchingpath, assert, TRUE); - } - } - -compile_matchingpath(common, matchingpath, cc, backtrack); -if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) - return NULL; - -if (opcode == OP_ONCE) - match_once_common(common, ket, BACKTRACK_AS(bracket_backtrack)->u.framesize, private_data_ptr, has_alternatives, needs_control_head); - -stacksize = 0; -if (repeat_type == OP_MINUPTO) - { - /* We need to preserve the counter. TMP2 will be used below. */ - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), repeat_ptr); - stacksize++; - } -if (ket != OP_KET || bra != OP_BRA) - stacksize++; -if (offset != 0) - { - if (common->capture_last_ptr != 0) - stacksize++; - if (common->optimized_cbracket[offset >> 1] == 0) - stacksize += 2; - } -if (has_alternatives && opcode != OP_ONCE) - stacksize++; - -if (stacksize > 0) - allocate_stack(common, stacksize); - -stacksize = 0; -if (repeat_type == OP_MINUPTO) - { - /* TMP2 was set above. */ - OP2(SLJIT_SUB, SLJIT_MEM1(STACK_TOP), STACK(stacksize), TMP2, 0, SLJIT_IMM, 1); - stacksize++; - } - -if (ket != OP_KET || bra != OP_BRA) - { - if (ket != OP_KET) - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), STR_PTR, 0); - else - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), SLJIT_IMM, 0); - stacksize++; - } - -if (offset != 0) - stacksize = match_capture_common(common, stacksize, offset, private_data_ptr); - -if (has_alternatives) - { - if (opcode != OP_ONCE) - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), SLJIT_IMM, 0); - if (ket != OP_KETRMAX) - BACKTRACK_AS(bracket_backtrack)->alternative_matchingpath = LABEL(); - } - -/* Must be after the matchingpath label. */ -if (offset != 0 && common->optimized_cbracket[offset >> 1] != 0) - { - SLJIT_ASSERT(private_data_ptr == OVECTOR(offset + 0)); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1), STR_PTR, 0); - } - -if (ket == OP_KETRMAX) - { - if (repeat_type != 0) - { - if (has_alternatives) - BACKTRACK_AS(bracket_backtrack)->alternative_matchingpath = LABEL(); - OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_MEM1(SLJIT_SP), repeat_ptr, SLJIT_MEM1(SLJIT_SP), repeat_ptr, SLJIT_IMM, 1); - JUMPTO(SLJIT_C_NOT_ZERO, rmax_label); - /* Drop STR_PTR for greedy plus quantifier. */ - if (opcode != OP_ONCE) - free_stack(common, 1); - } - else if (opcode == OP_ONCE || opcode >= OP_SBRA) - { - if (has_alternatives) - BACKTRACK_AS(bracket_backtrack)->alternative_matchingpath = LABEL(); - /* Checking zero-length iteration. */ - if (opcode != OP_ONCE) - { - CMPTO(SLJIT_C_NOT_EQUAL, SLJIT_MEM1(SLJIT_SP), private_data_ptr, STR_PTR, 0, rmax_label); - /* Drop STR_PTR for greedy plus quantifier. */ - if (bra != OP_BRAZERO) - free_stack(common, 1); - } - else - /* TMP2 must contain the starting STR_PTR. */ - CMPTO(SLJIT_C_NOT_EQUAL, TMP2, 0, STR_PTR, 0, rmax_label); - } - else - JUMPTO(SLJIT_JUMP, rmax_label); - BACKTRACK_AS(bracket_backtrack)->recursive_matchingpath = LABEL(); - } - -if (repeat_type == OP_EXACT) - { - count_match(common); - OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_MEM1(SLJIT_SP), repeat_ptr, SLJIT_MEM1(SLJIT_SP), repeat_ptr, SLJIT_IMM, 1); - JUMPTO(SLJIT_C_NOT_ZERO, rmax_label); - } -else if (repeat_type == OP_UPTO) - { - /* We need to preserve the counter. */ - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), repeat_ptr); - allocate_stack(common, 1); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), TMP2, 0); - } - -if (bra == OP_BRAZERO) - BACKTRACK_AS(bracket_backtrack)->zero_matchingpath = LABEL(); - -if (bra == OP_BRAMINZERO) - { - /* This is a backtrack path! (From the viewpoint of OP_BRAMINZERO) */ - JUMPTO(SLJIT_JUMP, ((braminzero_backtrack *)parent)->matchingpath); - if (braminzero != NULL) - { - JUMPHERE(braminzero); - /* We need to release the end pointer to perform the - backtrack for the zero-length iteration. When - framesize is < 0, OP_ONCE will do the release itself. */ - if (opcode == OP_ONCE && BACKTRACK_AS(bracket_backtrack)->u.framesize >= 0) - { - OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); - add_jump(compiler, &common->revertframes, JUMP(SLJIT_FAST_CALL)); - } - else if (ket == OP_KETRMIN && opcode != OP_ONCE) - free_stack(common, 1); - } - /* Continue to the normal backtrack. */ - } - -if ((ket != OP_KET && bra != OP_BRAMINZERO) || bra == OP_BRAZERO) - count_match(common); - -/* Skip the other alternatives. */ -while (*cc == OP_ALT) - cc += GET(cc, 1); -cc += 1 + LINK_SIZE; - -/* Temporarily encoding the needs_control_head in framesize. */ -if (opcode == OP_ONCE) - BACKTRACK_AS(bracket_backtrack)->u.framesize = (BACKTRACK_AS(bracket_backtrack)->u.framesize << 1) | (needs_control_head ? 1 : 0); -return cc + repeat_length; -} - -static pcre_uchar *compile_bracketpos_matchingpath(compiler_common *common, pcre_uchar *cc, backtrack_common *parent) -{ -DEFINE_COMPILER; -backtrack_common *backtrack; -pcre_uchar opcode; -int private_data_ptr; -int cbraprivptr = 0; -BOOL needs_control_head; -int framesize; -int stacksize; -int offset = 0; -BOOL zero = FALSE; -pcre_uchar *ccbegin = NULL; -int stack; /* Also contains the offset of control head. */ -struct sljit_label *loop = NULL; -struct jump_list *emptymatch = NULL; - -PUSH_BACKTRACK(sizeof(bracketpos_backtrack), cc, NULL); -if (*cc == OP_BRAPOSZERO) - { - zero = TRUE; - cc++; - } - -opcode = *cc; -private_data_ptr = PRIVATE_DATA(cc); -SLJIT_ASSERT(private_data_ptr != 0); -BACKTRACK_AS(bracketpos_backtrack)->private_data_ptr = private_data_ptr; -switch(opcode) - { - case OP_BRAPOS: - case OP_SBRAPOS: - ccbegin = cc + 1 + LINK_SIZE; - break; - - case OP_CBRAPOS: - case OP_SCBRAPOS: - offset = GET2(cc, 1 + LINK_SIZE); - /* This case cannot be optimized in the same was as - normal capturing brackets. */ - SLJIT_ASSERT(common->optimized_cbracket[offset] == 0); - cbraprivptr = OVECTOR_PRIV(offset); - offset <<= 1; - ccbegin = cc + 1 + LINK_SIZE + IMM2_SIZE; - break; - - default: - SLJIT_ASSERT_STOP(); - break; - } - -framesize = get_framesize(common, cc, NULL, FALSE, &needs_control_head); -BACKTRACK_AS(bracketpos_backtrack)->framesize = framesize; -if (framesize < 0) - { - if (offset != 0) - { - stacksize = 2; - if (common->capture_last_ptr != 0) - stacksize++; - } - else - stacksize = 1; - - if (needs_control_head) - stacksize++; - if (!zero) - stacksize++; - - BACKTRACK_AS(bracketpos_backtrack)->stacksize = stacksize; - allocate_stack(common, stacksize); - if (framesize == no_frame) - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, STACK_TOP, 0); - - stack = 0; - if (offset != 0) - { - stack = 2; - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset)); - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1)); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), TMP1, 0); - if (common->capture_last_ptr != 0) - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->capture_last_ptr); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(1), TMP2, 0); - if (needs_control_head) - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr); - if (common->capture_last_ptr != 0) - { - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(2), TMP1, 0); - stack = 3; - } - } - else - { - if (needs_control_head) - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); - stack = 1; - } - - if (needs_control_head) - stack++; - if (!zero) - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stack), SLJIT_IMM, 1); - if (needs_control_head) - { - stack--; - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stack), TMP2, 0); - } - } -else - { - stacksize = framesize + 1; - if (!zero) - stacksize++; - if (needs_control_head) - stacksize++; - if (offset == 0) - stacksize++; - BACKTRACK_AS(bracketpos_backtrack)->stacksize = stacksize; - - allocate_stack(common, stacksize); - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); - if (needs_control_head) - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr); - OP2(SLJIT_SUB, SLJIT_MEM1(SLJIT_SP), private_data_ptr, STACK_TOP, 0, SLJIT_IMM, -STACK(stacksize - 1)); - - stack = 0; - if (!zero) - { - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 1); - stack = 1; - } - if (needs_control_head) - { - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stack), TMP2, 0); - stack++; - } - if (offset == 0) - { - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stack), STR_PTR, 0); - stack++; - } - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stack), TMP1, 0); - init_frame(common, cc, NULL, stacksize - 1, stacksize - framesize, FALSE); - stack -= 1 + (offset == 0); - } - -if (offset != 0) - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), cbraprivptr, STR_PTR, 0); - -loop = LABEL(); -while (*cc != OP_KETRPOS) - { - backtrack->top = NULL; - backtrack->topbacktracks = NULL; - cc += GET(cc, 1); - - compile_matchingpath(common, ccbegin, cc, backtrack); - if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) - return NULL; - - if (framesize < 0) - { - if (framesize == no_frame) - OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); - - if (offset != 0) - { - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), cbraprivptr); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1), STR_PTR, 0); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), cbraprivptr, STR_PTR, 0); - if (common->capture_last_ptr != 0) - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->capture_last_ptr, SLJIT_IMM, offset >> 1); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset), TMP1, 0); - } - else - { - if (opcode == OP_SBRAPOS) - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); - } - - if (opcode == OP_SBRAPOS || opcode == OP_SCBRAPOS) - add_jump(compiler, &emptymatch, CMP(SLJIT_C_EQUAL, TMP1, 0, STR_PTR, 0)); - - if (!zero) - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize - 1), SLJIT_IMM, 0); - } - else - { - if (offset != 0) - { - OP2(SLJIT_ADD, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr, SLJIT_IMM, stacksize * sizeof(sljit_sw)); - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), cbraprivptr); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1), STR_PTR, 0); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), cbraprivptr, STR_PTR, 0); - if (common->capture_last_ptr != 0) - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->capture_last_ptr, SLJIT_IMM, offset >> 1); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset), TMP1, 0); - } - else - { - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); - OP2(SLJIT_ADD, STACK_TOP, 0, TMP2, 0, SLJIT_IMM, stacksize * sizeof(sljit_sw)); - if (opcode == OP_SBRAPOS) - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(TMP2), (framesize + 1) * sizeof(sljit_sw)); - OP1(SLJIT_MOV, SLJIT_MEM1(TMP2), (framesize + 1) * sizeof(sljit_sw), STR_PTR, 0); - } - - if (opcode == OP_SBRAPOS || opcode == OP_SCBRAPOS) - add_jump(compiler, &emptymatch, CMP(SLJIT_C_EQUAL, TMP1, 0, STR_PTR, 0)); - - if (!zero) - { - if (framesize < 0) - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize - 1), SLJIT_IMM, 0); - else - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); - } - } - - if (needs_control_head) - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, SLJIT_MEM1(STACK_TOP), STACK(stack)); - - JUMPTO(SLJIT_JUMP, loop); - flush_stubs(common); - - compile_backtrackingpath(common, backtrack->top); - if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) - return NULL; - set_jumps(backtrack->topbacktracks, LABEL()); - - if (framesize < 0) - { - if (offset != 0) - OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(SLJIT_SP), cbraprivptr); - else - OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); - } - else - { - if (offset != 0) - { - /* Last alternative. */ - if (*cc == OP_KETRPOS) - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); - OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(SLJIT_SP), cbraprivptr); - } - else - { - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); - OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(TMP2), (framesize + 1) * sizeof(sljit_sw)); - } - } - - if (*cc == OP_KETRPOS) - break; - ccbegin = cc + 1 + LINK_SIZE; - } - -/* We don't have to restore the control head in case of a failed match. */ - -backtrack->topbacktracks = NULL; -if (!zero) - { - if (framesize < 0) - add_jump(compiler, &backtrack->topbacktracks, CMP(SLJIT_C_NOT_EQUAL, SLJIT_MEM1(STACK_TOP), STACK(stacksize - 1), SLJIT_IMM, 0)); - else /* TMP2 is set to [private_data_ptr] above. */ - add_jump(compiler, &backtrack->topbacktracks, CMP(SLJIT_C_NOT_EQUAL, SLJIT_MEM1(TMP2), (stacksize - 1) * sizeof(sljit_sw), SLJIT_IMM, 0)); - } - -/* None of them matched. */ -set_jumps(emptymatch, LABEL()); -count_match(common); -return cc + 1 + LINK_SIZE; -} - -static SLJIT_INLINE pcre_uchar *get_iterator_parameters(compiler_common *common, pcre_uchar *cc, pcre_uchar *opcode, pcre_uchar *type, int *max, int *min, pcre_uchar **end) -{ -int class_len; - -*opcode = *cc; -if (*opcode >= OP_STAR && *opcode <= OP_POSUPTO) - { - cc++; - *type = OP_CHAR; - } -else if (*opcode >= OP_STARI && *opcode <= OP_POSUPTOI) - { - cc++; - *type = OP_CHARI; - *opcode -= OP_STARI - OP_STAR; - } -else if (*opcode >= OP_NOTSTAR && *opcode <= OP_NOTPOSUPTO) - { - cc++; - *type = OP_NOT; - *opcode -= OP_NOTSTAR - OP_STAR; - } -else if (*opcode >= OP_NOTSTARI && *opcode <= OP_NOTPOSUPTOI) - { - cc++; - *type = OP_NOTI; - *opcode -= OP_NOTSTARI - OP_STAR; - } -else if (*opcode >= OP_TYPESTAR && *opcode <= OP_TYPEPOSUPTO) - { - cc++; - *opcode -= OP_TYPESTAR - OP_STAR; - *type = 0; - } -else - { - SLJIT_ASSERT(*opcode == OP_CLASS || *opcode == OP_NCLASS || *opcode == OP_XCLASS); - *type = *opcode; - cc++; - class_len = (*type < OP_XCLASS) ? (int)(1 + (32 / sizeof(pcre_uchar))) : GET(cc, 0); - *opcode = cc[class_len - 1]; - if (*opcode >= OP_CRSTAR && *opcode <= OP_CRMINQUERY) - { - *opcode -= OP_CRSTAR - OP_STAR; - if (end != NULL) - *end = cc + class_len; - } - else if (*opcode >= OP_CRPOSSTAR && *opcode <= OP_CRPOSQUERY) - { - *opcode -= OP_CRPOSSTAR - OP_POSSTAR; - if (end != NULL) - *end = cc + class_len; - } - else - { - SLJIT_ASSERT(*opcode == OP_CRRANGE || *opcode == OP_CRMINRANGE || *opcode == OP_CRPOSRANGE); - *max = GET2(cc, (class_len + IMM2_SIZE)); - *min = GET2(cc, class_len); - - if (*min == 0) - { - SLJIT_ASSERT(*max != 0); - *opcode = (*opcode == OP_CRRANGE) ? OP_UPTO : (*opcode == OP_CRMINRANGE ? OP_MINUPTO : OP_POSUPTO); - } - if (*max == *min) - *opcode = OP_EXACT; - - if (end != NULL) - *end = cc + class_len + 2 * IMM2_SIZE; - } - return cc; - } - -if (*opcode == OP_UPTO || *opcode == OP_MINUPTO || *opcode == OP_EXACT || *opcode == OP_POSUPTO) - { - *max = GET2(cc, 0); - cc += IMM2_SIZE; - } - -if (*type == 0) - { - *type = *cc; - if (end != NULL) - *end = next_opcode(common, cc); - cc++; - return cc; - } - -if (end != NULL) - { - *end = cc + 1; -#ifdef SUPPORT_UTF - if (common->utf && HAS_EXTRALEN(*cc)) *end += GET_EXTRALEN(*cc); -#endif - } -return cc; -} - -static pcre_uchar *compile_iterator_matchingpath(compiler_common *common, pcre_uchar *cc, backtrack_common *parent) -{ -DEFINE_COMPILER; -backtrack_common *backtrack; -pcre_uchar opcode; -pcre_uchar type; -int max = -1, min = -1; -pcre_uchar* end; -jump_list *nomatch = NULL; -struct sljit_jump *jump = NULL; -struct sljit_label *label; -int private_data_ptr = PRIVATE_DATA(cc); -int base = (private_data_ptr == 0) ? SLJIT_MEM1(STACK_TOP) : SLJIT_MEM1(SLJIT_SP); -int offset0 = (private_data_ptr == 0) ? STACK(0) : private_data_ptr; -int offset1 = (private_data_ptr == 0) ? STACK(1) : private_data_ptr + (int)sizeof(sljit_sw); -int tmp_base, tmp_offset; - -PUSH_BACKTRACK(sizeof(iterator_backtrack), cc, NULL); - -cc = get_iterator_parameters(common, cc, &opcode, &type, &max, &min, &end); - -switch(type) - { - case OP_NOT_DIGIT: - case OP_DIGIT: - case OP_NOT_WHITESPACE: - case OP_WHITESPACE: - case OP_NOT_WORDCHAR: - case OP_WORDCHAR: - case OP_ANY: - case OP_ALLANY: - case OP_ANYBYTE: - case OP_ANYNL: - case OP_NOT_HSPACE: - case OP_HSPACE: - case OP_NOT_VSPACE: - case OP_VSPACE: - case OP_CHAR: - case OP_CHARI: - case OP_NOT: - case OP_NOTI: - case OP_CLASS: - case OP_NCLASS: - tmp_base = TMP3; - tmp_offset = 0; - break; - - default: - SLJIT_ASSERT_STOP(); - /* Fall through. */ - - case OP_EXTUNI: - case OP_XCLASS: - case OP_NOTPROP: - case OP_PROP: - tmp_base = SLJIT_MEM1(SLJIT_SP); - tmp_offset = POSSESSIVE0; - break; - } - -switch(opcode) - { - case OP_STAR: - case OP_PLUS: - case OP_UPTO: - case OP_CRRANGE: - if (type == OP_ANYNL || type == OP_EXTUNI) - { - SLJIT_ASSERT(private_data_ptr == 0); - if (opcode == OP_STAR || opcode == OP_UPTO) - { - allocate_stack(common, 2); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(1), SLJIT_IMM, 0); - } - else - { - allocate_stack(common, 1); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); - } - - if (opcode == OP_UPTO || opcode == OP_CRRANGE) - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), POSSESSIVE0, SLJIT_IMM, 0); - - label = LABEL(); - compile_char1_matchingpath(common, type, cc, &backtrack->topbacktracks); - if (opcode == OP_UPTO || opcode == OP_CRRANGE) - { - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), POSSESSIVE0); - OP2(SLJIT_ADD, TMP1, 0, TMP1, 0, SLJIT_IMM, 1); - if (opcode == OP_CRRANGE && min > 0) - CMPTO(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, min, label); - if (opcode == OP_UPTO || (opcode == OP_CRRANGE && max > 0)) - jump = CMP(SLJIT_C_GREATER_EQUAL, TMP1, 0, SLJIT_IMM, max); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), POSSESSIVE0, TMP1, 0); - } - - /* We cannot use TMP3 because of this allocate_stack. */ - allocate_stack(common, 1); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); - JUMPTO(SLJIT_JUMP, label); - if (jump != NULL) - JUMPHERE(jump); - } - else - { - if (opcode == OP_PLUS) - compile_char1_matchingpath(common, type, cc, &backtrack->topbacktracks); - if (private_data_ptr == 0) - allocate_stack(common, 2); - OP1(SLJIT_MOV, base, offset0, STR_PTR, 0); - if (opcode <= OP_PLUS) - OP1(SLJIT_MOV, base, offset1, STR_PTR, 0); - else - OP1(SLJIT_MOV, base, offset1, SLJIT_IMM, 1); - label = LABEL(); - compile_char1_matchingpath(common, type, cc, &nomatch); - OP1(SLJIT_MOV, base, offset0, STR_PTR, 0); - if (opcode <= OP_PLUS) - JUMPTO(SLJIT_JUMP, label); - else if (opcode == OP_CRRANGE && max == 0) - { - OP2(SLJIT_ADD, base, offset1, base, offset1, SLJIT_IMM, 1); - JUMPTO(SLJIT_JUMP, label); - } - else - { - OP1(SLJIT_MOV, TMP1, 0, base, offset1); - OP2(SLJIT_ADD, TMP1, 0, TMP1, 0, SLJIT_IMM, 1); - OP1(SLJIT_MOV, base, offset1, TMP1, 0); - CMPTO(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, max + 1, label); - } - set_jumps(nomatch, LABEL()); - if (opcode == OP_CRRANGE) - add_jump(compiler, &backtrack->topbacktracks, CMP(SLJIT_C_LESS, base, offset1, SLJIT_IMM, min + 1)); - OP1(SLJIT_MOV, STR_PTR, 0, base, offset0); - } - BACKTRACK_AS(iterator_backtrack)->matchingpath = LABEL(); - break; - - case OP_MINSTAR: - case OP_MINPLUS: - if (opcode == OP_MINPLUS) - compile_char1_matchingpath(common, type, cc, &backtrack->topbacktracks); - if (private_data_ptr == 0) - allocate_stack(common, 1); - OP1(SLJIT_MOV, base, offset0, STR_PTR, 0); - BACKTRACK_AS(iterator_backtrack)->matchingpath = LABEL(); - break; - - case OP_MINUPTO: - case OP_CRMINRANGE: - if (private_data_ptr == 0) - allocate_stack(common, 2); - OP1(SLJIT_MOV, base, offset0, STR_PTR, 0); - OP1(SLJIT_MOV, base, offset1, SLJIT_IMM, 1); - if (opcode == OP_CRMINRANGE) - add_jump(compiler, &backtrack->topbacktracks, JUMP(SLJIT_JUMP)); - BACKTRACK_AS(iterator_backtrack)->matchingpath = LABEL(); - break; - - case OP_QUERY: - case OP_MINQUERY: - if (private_data_ptr == 0) - allocate_stack(common, 1); - OP1(SLJIT_MOV, base, offset0, STR_PTR, 0); - if (opcode == OP_QUERY) - compile_char1_matchingpath(common, type, cc, &backtrack->topbacktracks); - BACKTRACK_AS(iterator_backtrack)->matchingpath = LABEL(); - break; - - case OP_EXACT: - OP1(SLJIT_MOV, tmp_base, tmp_offset, SLJIT_IMM, max); - label = LABEL(); - compile_char1_matchingpath(common, type, cc, &backtrack->topbacktracks); - OP2(SLJIT_SUB | SLJIT_SET_E, tmp_base, tmp_offset, tmp_base, tmp_offset, SLJIT_IMM, 1); - JUMPTO(SLJIT_C_NOT_ZERO, label); - break; - - case OP_POSSTAR: - case OP_POSPLUS: - case OP_POSUPTO: - if (opcode == OP_POSPLUS) - compile_char1_matchingpath(common, type, cc, &backtrack->topbacktracks); - if (opcode == OP_POSUPTO) - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), POSSESSIVE1, SLJIT_IMM, max); - OP1(SLJIT_MOV, tmp_base, tmp_offset, STR_PTR, 0); - label = LABEL(); - compile_char1_matchingpath(common, type, cc, &nomatch); - OP1(SLJIT_MOV, tmp_base, tmp_offset, STR_PTR, 0); - if (opcode != OP_POSUPTO) - JUMPTO(SLJIT_JUMP, label); - else - { - OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_MEM1(SLJIT_SP), POSSESSIVE1, SLJIT_MEM1(SLJIT_SP), POSSESSIVE1, SLJIT_IMM, 1); - JUMPTO(SLJIT_C_NOT_ZERO, label); - } - set_jumps(nomatch, LABEL()); - OP1(SLJIT_MOV, STR_PTR, 0, tmp_base, tmp_offset); - break; - - case OP_POSQUERY: - OP1(SLJIT_MOV, tmp_base, tmp_offset, STR_PTR, 0); - compile_char1_matchingpath(common, type, cc, &nomatch); - OP1(SLJIT_MOV, tmp_base, tmp_offset, STR_PTR, 0); - set_jumps(nomatch, LABEL()); - OP1(SLJIT_MOV, STR_PTR, 0, tmp_base, tmp_offset); - break; - - case OP_CRPOSRANGE: - /* Combination of OP_EXACT and OP_POSSTAR or OP_POSUPTO */ - OP1(SLJIT_MOV, tmp_base, tmp_offset, SLJIT_IMM, min); - label = LABEL(); - compile_char1_matchingpath(common, type, cc, &backtrack->topbacktracks); - OP2(SLJIT_SUB | SLJIT_SET_E, tmp_base, tmp_offset, tmp_base, tmp_offset, SLJIT_IMM, 1); - JUMPTO(SLJIT_C_NOT_ZERO, label); - - if (max != 0) - { - SLJIT_ASSERT(max - min > 0); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), POSSESSIVE1, SLJIT_IMM, max - min); - } - OP1(SLJIT_MOV, tmp_base, tmp_offset, STR_PTR, 0); - label = LABEL(); - compile_char1_matchingpath(common, type, cc, &nomatch); - OP1(SLJIT_MOV, tmp_base, tmp_offset, STR_PTR, 0); - if (max == 0) - JUMPTO(SLJIT_JUMP, label); - else - { - OP2(SLJIT_SUB | SLJIT_SET_E, SLJIT_MEM1(SLJIT_SP), POSSESSIVE1, SLJIT_MEM1(SLJIT_SP), POSSESSIVE1, SLJIT_IMM, 1); - JUMPTO(SLJIT_C_NOT_ZERO, label); - } - set_jumps(nomatch, LABEL()); - OP1(SLJIT_MOV, STR_PTR, 0, tmp_base, tmp_offset); - break; - - default: - SLJIT_ASSERT_STOP(); - break; - } - -count_match(common); -return end; -} - -static SLJIT_INLINE pcre_uchar *compile_fail_accept_matchingpath(compiler_common *common, pcre_uchar *cc, backtrack_common *parent) -{ -DEFINE_COMPILER; -backtrack_common *backtrack; - -PUSH_BACKTRACK(sizeof(backtrack_common), cc, NULL); - -if (*cc == OP_FAIL) - { - add_jump(compiler, &backtrack->topbacktracks, JUMP(SLJIT_JUMP)); - return cc + 1; - } - -if (*cc == OP_ASSERT_ACCEPT || common->currententry != NULL || !common->might_be_empty) - { - /* No need to check notempty conditions. */ - if (common->accept_label == NULL) - add_jump(compiler, &common->accept, JUMP(SLJIT_JUMP)); - else - JUMPTO(SLJIT_JUMP, common->accept_label); - return cc + 1; - } - -if (common->accept_label == NULL) - add_jump(compiler, &common->accept, CMP(SLJIT_C_NOT_EQUAL, STR_PTR, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(0))); -else - CMPTO(SLJIT_C_NOT_EQUAL, STR_PTR, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(0), common->accept_label); -OP1(SLJIT_MOV, TMP1, 0, ARGUMENTS, 0); -OP1(SLJIT_MOV_UB, TMP2, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, notempty)); -add_jump(compiler, &backtrack->topbacktracks, CMP(SLJIT_C_NOT_EQUAL, TMP2, 0, SLJIT_IMM, 0)); -OP1(SLJIT_MOV_UB, TMP2, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, notempty_atstart)); -if (common->accept_label == NULL) - add_jump(compiler, &common->accept, CMP(SLJIT_C_EQUAL, TMP2, 0, SLJIT_IMM, 0)); -else - CMPTO(SLJIT_C_EQUAL, TMP2, 0, SLJIT_IMM, 0, common->accept_label); -OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, str)); -if (common->accept_label == NULL) - add_jump(compiler, &common->accept, CMP(SLJIT_C_NOT_EQUAL, TMP2, 0, STR_PTR, 0)); -else - CMPTO(SLJIT_C_NOT_EQUAL, TMP2, 0, STR_PTR, 0, common->accept_label); -add_jump(compiler, &backtrack->topbacktracks, JUMP(SLJIT_JUMP)); -return cc + 1; -} - -static SLJIT_INLINE pcre_uchar *compile_close_matchingpath(compiler_common *common, pcre_uchar *cc) -{ -DEFINE_COMPILER; -int offset = GET2(cc, 1); -BOOL optimized_cbracket = common->optimized_cbracket[offset] != 0; - -/* Data will be discarded anyway... */ -if (common->currententry != NULL) - return cc + 1 + IMM2_SIZE; - -if (!optimized_cbracket) - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR_PRIV(offset)); -offset <<= 1; -OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1), STR_PTR, 0); -if (!optimized_cbracket) - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset), TMP1, 0); -return cc + 1 + IMM2_SIZE; -} - -static SLJIT_INLINE pcre_uchar *compile_control_verb_matchingpath(compiler_common *common, pcre_uchar *cc, backtrack_common *parent) -{ -DEFINE_COMPILER; -backtrack_common *backtrack; -pcre_uchar opcode = *cc; -pcre_uchar *ccend = cc + 1; - -if (opcode == OP_PRUNE_ARG || opcode == OP_SKIP_ARG || opcode == OP_THEN_ARG) - ccend += 2 + cc[1]; - -PUSH_BACKTRACK(sizeof(backtrack_common), cc, NULL); - -if (opcode == OP_SKIP) - { - allocate_stack(common, 1); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); - return ccend; - } - -if (opcode == OP_PRUNE_ARG || opcode == OP_THEN_ARG) - { - OP1(SLJIT_MOV, TMP1, 0, ARGUMENTS, 0); - OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, (sljit_sw)(cc + 2)); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->mark_ptr, TMP2, 0); - OP1(SLJIT_MOV, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, mark_ptr), TMP2, 0); - } - -return ccend; -} - -static pcre_uchar then_trap_opcode[1] = { OP_THEN_TRAP }; - -static SLJIT_INLINE void compile_then_trap_matchingpath(compiler_common *common, pcre_uchar *cc, pcre_uchar *ccend, backtrack_common *parent) -{ -DEFINE_COMPILER; -backtrack_common *backtrack; -BOOL needs_control_head; -int size; - -PUSH_BACKTRACK_NOVALUE(sizeof(then_trap_backtrack), cc); -common->then_trap = BACKTRACK_AS(then_trap_backtrack); -BACKTRACK_AS(then_trap_backtrack)->common.cc = then_trap_opcode; -BACKTRACK_AS(then_trap_backtrack)->start = (sljit_sw)(cc - common->start); -BACKTRACK_AS(then_trap_backtrack)->framesize = get_framesize(common, cc, ccend, FALSE, &needs_control_head); - -size = BACKTRACK_AS(then_trap_backtrack)->framesize; -size = 3 + (size < 0 ? 0 : size); - -OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr); -allocate_stack(common, size); -if (size > 3) - OP2(SLJIT_SUB, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, STACK_TOP, 0, SLJIT_IMM, (size - 3) * sizeof(sljit_sw)); -else - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, STACK_TOP, 0); -OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(size - 1), SLJIT_IMM, BACKTRACK_AS(then_trap_backtrack)->start); -OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(size - 2), SLJIT_IMM, type_then_trap); -OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(size - 3), TMP2, 0); - -size = BACKTRACK_AS(then_trap_backtrack)->framesize; -if (size >= 0) - init_frame(common, cc, ccend, size - 1, 0, FALSE); -} - -static void compile_matchingpath(compiler_common *common, pcre_uchar *cc, pcre_uchar *ccend, backtrack_common *parent) -{ -DEFINE_COMPILER; -backtrack_common *backtrack; -BOOL has_then_trap = FALSE; -then_trap_backtrack *save_then_trap = NULL; - -SLJIT_ASSERT(*ccend == OP_END || (*ccend >= OP_ALT && *ccend <= OP_KETRPOS)); - -if (common->has_then && common->then_offsets[cc - common->start] != 0) - { - SLJIT_ASSERT(*ccend != OP_END && common->control_head_ptr != 0); - has_then_trap = TRUE; - save_then_trap = common->then_trap; - /* Tail item on backtrack. */ - compile_then_trap_matchingpath(common, cc, ccend, parent); - } - -while (cc < ccend) - { - switch(*cc) - { - case OP_SOD: - case OP_SOM: - case OP_NOT_WORD_BOUNDARY: - case OP_WORD_BOUNDARY: - case OP_NOT_DIGIT: - case OP_DIGIT: - case OP_NOT_WHITESPACE: - case OP_WHITESPACE: - case OP_NOT_WORDCHAR: - case OP_WORDCHAR: - case OP_ANY: - case OP_ALLANY: - case OP_ANYBYTE: - case OP_NOTPROP: - case OP_PROP: - case OP_ANYNL: - case OP_NOT_HSPACE: - case OP_HSPACE: - case OP_NOT_VSPACE: - case OP_VSPACE: - case OP_EXTUNI: - case OP_EODN: - case OP_EOD: - case OP_CIRC: - case OP_CIRCM: - case OP_DOLL: - case OP_DOLLM: - case OP_NOT: - case OP_NOTI: - case OP_REVERSE: - cc = compile_char1_matchingpath(common, *cc, cc + 1, parent->top != NULL ? &parent->top->nextbacktracks : &parent->topbacktracks); - break; - - case OP_SET_SOM: - PUSH_BACKTRACK_NOVALUE(sizeof(backtrack_common), cc); - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(0)); - allocate_stack(common, 1); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(0), STR_PTR, 0); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), TMP2, 0); - cc++; - break; - - case OP_CHAR: - case OP_CHARI: - if (common->mode == JIT_COMPILE) - cc = compile_charn_matchingpath(common, cc, ccend, parent->top != NULL ? &parent->top->nextbacktracks : &parent->topbacktracks); - else - cc = compile_char1_matchingpath(common, *cc, cc + 1, parent->top != NULL ? &parent->top->nextbacktracks : &parent->topbacktracks); - break; - - case OP_STAR: - case OP_MINSTAR: - case OP_PLUS: - case OP_MINPLUS: - case OP_QUERY: - case OP_MINQUERY: - case OP_UPTO: - case OP_MINUPTO: - case OP_EXACT: - case OP_POSSTAR: - case OP_POSPLUS: - case OP_POSQUERY: - case OP_POSUPTO: - case OP_STARI: - case OP_MINSTARI: - case OP_PLUSI: - case OP_MINPLUSI: - case OP_QUERYI: - case OP_MINQUERYI: - case OP_UPTOI: - case OP_MINUPTOI: - case OP_EXACTI: - case OP_POSSTARI: - case OP_POSPLUSI: - case OP_POSQUERYI: - case OP_POSUPTOI: - case OP_NOTSTAR: - case OP_NOTMINSTAR: - case OP_NOTPLUS: - case OP_NOTMINPLUS: - case OP_NOTQUERY: - case OP_NOTMINQUERY: - case OP_NOTUPTO: - case OP_NOTMINUPTO: - case OP_NOTEXACT: - case OP_NOTPOSSTAR: - case OP_NOTPOSPLUS: - case OP_NOTPOSQUERY: - case OP_NOTPOSUPTO: - case OP_NOTSTARI: - case OP_NOTMINSTARI: - case OP_NOTPLUSI: - case OP_NOTMINPLUSI: - case OP_NOTQUERYI: - case OP_NOTMINQUERYI: - case OP_NOTUPTOI: - case OP_NOTMINUPTOI: - case OP_NOTEXACTI: - case OP_NOTPOSSTARI: - case OP_NOTPOSPLUSI: - case OP_NOTPOSQUERYI: - case OP_NOTPOSUPTOI: - case OP_TYPESTAR: - case OP_TYPEMINSTAR: - case OP_TYPEPLUS: - case OP_TYPEMINPLUS: - case OP_TYPEQUERY: - case OP_TYPEMINQUERY: - case OP_TYPEUPTO: - case OP_TYPEMINUPTO: - case OP_TYPEEXACT: - case OP_TYPEPOSSTAR: - case OP_TYPEPOSPLUS: - case OP_TYPEPOSQUERY: - case OP_TYPEPOSUPTO: - cc = compile_iterator_matchingpath(common, cc, parent); - break; - - case OP_CLASS: - case OP_NCLASS: - if (cc[1 + (32 / sizeof(pcre_uchar))] >= OP_CRSTAR && cc[1 + (32 / sizeof(pcre_uchar))] <= OP_CRPOSRANGE) - cc = compile_iterator_matchingpath(common, cc, parent); - else - cc = compile_char1_matchingpath(common, *cc, cc + 1, parent->top != NULL ? &parent->top->nextbacktracks : &parent->topbacktracks); - break; - -#if defined SUPPORT_UTF || defined COMPILE_PCRE16 || defined COMPILE_PCRE32 - case OP_XCLASS: - if (*(cc + GET(cc, 1)) >= OP_CRSTAR && *(cc + GET(cc, 1)) <= OP_CRPOSRANGE) - cc = compile_iterator_matchingpath(common, cc, parent); - else - cc = compile_char1_matchingpath(common, *cc, cc + 1, parent->top != NULL ? &parent->top->nextbacktracks : &parent->topbacktracks); - break; -#endif - - case OP_REF: - case OP_REFI: - if (cc[1 + IMM2_SIZE] >= OP_CRSTAR && cc[1 + IMM2_SIZE] <= OP_CRPOSRANGE) - cc = compile_ref_iterator_matchingpath(common, cc, parent); - else - { - compile_ref_matchingpath(common, cc, parent->top != NULL ? &parent->top->nextbacktracks : &parent->topbacktracks, TRUE, FALSE); - cc += 1 + IMM2_SIZE; - } - break; - - case OP_DNREF: - case OP_DNREFI: - if (cc[1 + 2 * IMM2_SIZE] >= OP_CRSTAR && cc[1 + 2 * IMM2_SIZE] <= OP_CRPOSRANGE) - cc = compile_ref_iterator_matchingpath(common, cc, parent); - else - { - compile_dnref_search(common, cc, parent->top != NULL ? &parent->top->nextbacktracks : &parent->topbacktracks); - compile_ref_matchingpath(common, cc, parent->top != NULL ? &parent->top->nextbacktracks : &parent->topbacktracks, TRUE, FALSE); - cc += 1 + 2 * IMM2_SIZE; - } - break; - - case OP_RECURSE: - cc = compile_recurse_matchingpath(common, cc, parent); - break; - - case OP_CALLOUT: - cc = compile_callout_matchingpath(common, cc, parent); - break; - - case OP_ASSERT: - case OP_ASSERT_NOT: - case OP_ASSERTBACK: - case OP_ASSERTBACK_NOT: - PUSH_BACKTRACK_NOVALUE(sizeof(assert_backtrack), cc); - cc = compile_assert_matchingpath(common, cc, BACKTRACK_AS(assert_backtrack), FALSE); - break; - - case OP_BRAMINZERO: - PUSH_BACKTRACK_NOVALUE(sizeof(braminzero_backtrack), cc); - cc = bracketend(cc + 1); - if (*(cc - 1 - LINK_SIZE) != OP_KETRMIN) - { - allocate_stack(common, 1); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); - } - else - { - allocate_stack(common, 2); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(1), STR_PTR, 0); - } - BACKTRACK_AS(braminzero_backtrack)->matchingpath = LABEL(); - if (cc[1] > OP_ASSERTBACK_NOT) - count_match(common); - break; - - case OP_ONCE: - case OP_ONCE_NC: - case OP_BRA: - case OP_CBRA: - case OP_COND: - case OP_SBRA: - case OP_SCBRA: - case OP_SCOND: - cc = compile_bracket_matchingpath(common, cc, parent); - break; - - case OP_BRAZERO: - if (cc[1] > OP_ASSERTBACK_NOT) - cc = compile_bracket_matchingpath(common, cc, parent); - else - { - PUSH_BACKTRACK_NOVALUE(sizeof(assert_backtrack), cc); - cc = compile_assert_matchingpath(common, cc, BACKTRACK_AS(assert_backtrack), FALSE); - } - break; - - case OP_BRAPOS: - case OP_CBRAPOS: - case OP_SBRAPOS: - case OP_SCBRAPOS: - case OP_BRAPOSZERO: - cc = compile_bracketpos_matchingpath(common, cc, parent); - break; - - case OP_MARK: - PUSH_BACKTRACK_NOVALUE(sizeof(backtrack_common), cc); - SLJIT_ASSERT(common->mark_ptr != 0); - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), common->mark_ptr); - allocate_stack(common, common->has_skip_arg ? 5 : 1); - OP1(SLJIT_MOV, TMP1, 0, ARGUMENTS, 0); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(common->has_skip_arg ? 4 : 0), TMP2, 0); - OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, (sljit_sw)(cc + 2)); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->mark_ptr, TMP2, 0); - OP1(SLJIT_MOV, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, mark_ptr), TMP2, 0); - if (common->has_skip_arg) - { - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, STACK_TOP, 0); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(1), SLJIT_IMM, type_mark); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(2), SLJIT_IMM, (sljit_sw)(cc + 2)); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(3), STR_PTR, 0); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), TMP1, 0); - } - cc += 1 + 2 + cc[1]; - break; - - case OP_PRUNE: - case OP_PRUNE_ARG: - case OP_SKIP: - case OP_SKIP_ARG: - case OP_THEN: - case OP_THEN_ARG: - case OP_COMMIT: - cc = compile_control_verb_matchingpath(common, cc, parent); - break; - - case OP_FAIL: - case OP_ACCEPT: - case OP_ASSERT_ACCEPT: - cc = compile_fail_accept_matchingpath(common, cc, parent); - break; - - case OP_CLOSE: - cc = compile_close_matchingpath(common, cc); - break; - - case OP_SKIPZERO: - cc = bracketend(cc + 1); - break; - - default: - SLJIT_ASSERT_STOP(); - return; - } - if (cc == NULL) - return; - } - -if (has_then_trap) - { - /* Head item on backtrack. */ - PUSH_BACKTRACK_NOVALUE(sizeof(then_trap_backtrack), cc); - BACKTRACK_AS(then_trap_backtrack)->common.cc = then_trap_opcode; - BACKTRACK_AS(then_trap_backtrack)->then_trap = common->then_trap; - common->then_trap = save_then_trap; - } -SLJIT_ASSERT(cc == ccend); -} - -#undef PUSH_BACKTRACK -#undef PUSH_BACKTRACK_NOVALUE -#undef BACKTRACK_AS - -#define COMPILE_BACKTRACKINGPATH(current) \ - do \ - { \ - compile_backtrackingpath(common, (current)); \ - if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) \ - return; \ - } \ - while (0) - -#define CURRENT_AS(type) ((type *)current) - -static void compile_iterator_backtrackingpath(compiler_common *common, struct backtrack_common *current) -{ -DEFINE_COMPILER; -pcre_uchar *cc = current->cc; -pcre_uchar opcode; -pcre_uchar type; -int max = -1, min = -1; -struct sljit_label *label = NULL; -struct sljit_jump *jump = NULL; -jump_list *jumplist = NULL; -int private_data_ptr = PRIVATE_DATA(cc); -int base = (private_data_ptr == 0) ? SLJIT_MEM1(STACK_TOP) : SLJIT_MEM1(SLJIT_SP); -int offset0 = (private_data_ptr == 0) ? STACK(0) : private_data_ptr; -int offset1 = (private_data_ptr == 0) ? STACK(1) : private_data_ptr + (int)sizeof(sljit_sw); - -cc = get_iterator_parameters(common, cc, &opcode, &type, &max, &min, NULL); - -switch(opcode) - { - case OP_STAR: - case OP_PLUS: - case OP_UPTO: - case OP_CRRANGE: - if (type == OP_ANYNL || type == OP_EXTUNI) - { - SLJIT_ASSERT(private_data_ptr == 0); - set_jumps(current->topbacktracks, LABEL()); - OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); - free_stack(common, 1); - CMPTO(SLJIT_C_NOT_EQUAL, STR_PTR, 0, SLJIT_IMM, 0, CURRENT_AS(iterator_backtrack)->matchingpath); - } - else - { - if (opcode == OP_UPTO) - min = 0; - if (opcode <= OP_PLUS) - { - OP1(SLJIT_MOV, STR_PTR, 0, base, offset0); - jump = CMP(SLJIT_C_LESS_EQUAL, STR_PTR, 0, base, offset1); - } - else - { - OP1(SLJIT_MOV, TMP1, 0, base, offset1); - OP1(SLJIT_MOV, STR_PTR, 0, base, offset0); - jump = CMP(SLJIT_C_LESS_EQUAL, TMP1, 0, SLJIT_IMM, min + 1); - OP2(SLJIT_SUB, base, offset1, TMP1, 0, SLJIT_IMM, 1); - } - skip_char_back(common); - OP1(SLJIT_MOV, base, offset0, STR_PTR, 0); - JUMPTO(SLJIT_JUMP, CURRENT_AS(iterator_backtrack)->matchingpath); - if (opcode == OP_CRRANGE) - set_jumps(current->topbacktracks, LABEL()); - JUMPHERE(jump); - if (private_data_ptr == 0) - free_stack(common, 2); - if (opcode == OP_PLUS) - set_jumps(current->topbacktracks, LABEL()); - } - break; - - case OP_MINSTAR: - case OP_MINPLUS: - OP1(SLJIT_MOV, STR_PTR, 0, base, offset0); - compile_char1_matchingpath(common, type, cc, &jumplist); - OP1(SLJIT_MOV, base, offset0, STR_PTR, 0); - JUMPTO(SLJIT_JUMP, CURRENT_AS(iterator_backtrack)->matchingpath); - set_jumps(jumplist, LABEL()); - if (private_data_ptr == 0) - free_stack(common, 1); - if (opcode == OP_MINPLUS) - set_jumps(current->topbacktracks, LABEL()); - break; - - case OP_MINUPTO: - case OP_CRMINRANGE: - if (opcode == OP_CRMINRANGE) - { - label = LABEL(); - set_jumps(current->topbacktracks, label); - } - OP1(SLJIT_MOV, STR_PTR, 0, base, offset0); - compile_char1_matchingpath(common, type, cc, &jumplist); - - OP1(SLJIT_MOV, TMP1, 0, base, offset1); - OP1(SLJIT_MOV, base, offset0, STR_PTR, 0); - OP2(SLJIT_ADD, TMP1, 0, TMP1, 0, SLJIT_IMM, 1); - OP1(SLJIT_MOV, base, offset1, TMP1, 0); - - if (opcode == OP_CRMINRANGE) - CMPTO(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, min + 1, label); - - if (opcode == OP_CRMINRANGE && max == 0) - JUMPTO(SLJIT_JUMP, CURRENT_AS(iterator_backtrack)->matchingpath); - else - CMPTO(SLJIT_C_LESS, TMP1, 0, SLJIT_IMM, max + 2, CURRENT_AS(iterator_backtrack)->matchingpath); - - set_jumps(jumplist, LABEL()); - if (private_data_ptr == 0) - free_stack(common, 2); - break; - - case OP_QUERY: - OP1(SLJIT_MOV, STR_PTR, 0, base, offset0); - OP1(SLJIT_MOV, base, offset0, SLJIT_IMM, 0); - CMPTO(SLJIT_C_NOT_EQUAL, STR_PTR, 0, SLJIT_IMM, 0, CURRENT_AS(iterator_backtrack)->matchingpath); - jump = JUMP(SLJIT_JUMP); - set_jumps(current->topbacktracks, LABEL()); - OP1(SLJIT_MOV, STR_PTR, 0, base, offset0); - OP1(SLJIT_MOV, base, offset0, SLJIT_IMM, 0); - JUMPTO(SLJIT_JUMP, CURRENT_AS(iterator_backtrack)->matchingpath); - JUMPHERE(jump); - if (private_data_ptr == 0) - free_stack(common, 1); - break; - - case OP_MINQUERY: - OP1(SLJIT_MOV, STR_PTR, 0, base, offset0); - OP1(SLJIT_MOV, base, offset0, SLJIT_IMM, 0); - jump = CMP(SLJIT_C_EQUAL, STR_PTR, 0, SLJIT_IMM, 0); - compile_char1_matchingpath(common, type, cc, &jumplist); - JUMPTO(SLJIT_JUMP, CURRENT_AS(iterator_backtrack)->matchingpath); - set_jumps(jumplist, LABEL()); - JUMPHERE(jump); - if (private_data_ptr == 0) - free_stack(common, 1); - break; - - case OP_EXACT: - case OP_POSPLUS: - case OP_CRPOSRANGE: - set_jumps(current->topbacktracks, LABEL()); - break; - - case OP_POSSTAR: - case OP_POSQUERY: - case OP_POSUPTO: - break; - - default: - SLJIT_ASSERT_STOP(); - break; - } -} - -static SLJIT_INLINE void compile_ref_iterator_backtrackingpath(compiler_common *common, struct backtrack_common *current) -{ -DEFINE_COMPILER; -pcre_uchar *cc = current->cc; -BOOL ref = (*cc == OP_REF || *cc == OP_REFI); -pcre_uchar type; - -type = cc[ref ? 1 + IMM2_SIZE : 1 + 2 * IMM2_SIZE]; - -if ((type & 0x1) == 0) - { - /* Maximize case. */ - set_jumps(current->topbacktracks, LABEL()); - OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); - free_stack(common, 1); - CMPTO(SLJIT_C_NOT_EQUAL, STR_PTR, 0, SLJIT_IMM, 0, CURRENT_AS(iterator_backtrack)->matchingpath); - return; - } - -OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); -CMPTO(SLJIT_C_NOT_EQUAL, STR_PTR, 0, SLJIT_IMM, 0, CURRENT_AS(iterator_backtrack)->matchingpath); -set_jumps(current->topbacktracks, LABEL()); -free_stack(common, ref ? 2 : 3); -} - -static SLJIT_INLINE void compile_recurse_backtrackingpath(compiler_common *common, struct backtrack_common *current) -{ -DEFINE_COMPILER; - -if (CURRENT_AS(recurse_backtrack)->inlined_pattern) - compile_backtrackingpath(common, current->top); -set_jumps(current->topbacktracks, LABEL()); -if (CURRENT_AS(recurse_backtrack)->inlined_pattern) - return; - -if (common->has_set_som && common->mark_ptr != 0) - { - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(1)); - free_stack(common, 2); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(0), TMP2, 0); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->mark_ptr, TMP1, 0); - } -else if (common->has_set_som || common->mark_ptr != 0) - { - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); - free_stack(common, 1); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->has_set_som ? (int)(OVECTOR(0)) : common->mark_ptr, TMP2, 0); - } -} - -static void compile_assert_backtrackingpath(compiler_common *common, struct backtrack_common *current) -{ -DEFINE_COMPILER; -pcre_uchar *cc = current->cc; -pcre_uchar bra = OP_BRA; -struct sljit_jump *brajump = NULL; - -SLJIT_ASSERT(*cc != OP_BRAMINZERO); -if (*cc == OP_BRAZERO) - { - bra = *cc; - cc++; - } - -if (bra == OP_BRAZERO) - { - SLJIT_ASSERT(current->topbacktracks == NULL); - OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); - } - -if (CURRENT_AS(assert_backtrack)->framesize < 0) - { - set_jumps(current->topbacktracks, LABEL()); - - if (bra == OP_BRAZERO) - { - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); - CMPTO(SLJIT_C_NOT_EQUAL, STR_PTR, 0, SLJIT_IMM, 0, CURRENT_AS(assert_backtrack)->matchingpath); - free_stack(common, 1); - } - return; - } - -if (bra == OP_BRAZERO) - { - if (*cc == OP_ASSERT_NOT || *cc == OP_ASSERTBACK_NOT) - { - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); - CMPTO(SLJIT_C_NOT_EQUAL, STR_PTR, 0, SLJIT_IMM, 0, CURRENT_AS(assert_backtrack)->matchingpath); - free_stack(common, 1); - return; - } - free_stack(common, 1); - brajump = CMP(SLJIT_C_EQUAL, STR_PTR, 0, SLJIT_IMM, 0); - } - -if (*cc == OP_ASSERT || *cc == OP_ASSERTBACK) - { - OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), CURRENT_AS(assert_backtrack)->private_data_ptr); - add_jump(compiler, &common->revertframes, JUMP(SLJIT_FAST_CALL)); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), CURRENT_AS(assert_backtrack)->private_data_ptr, SLJIT_MEM1(STACK_TOP), CURRENT_AS(assert_backtrack)->framesize * sizeof(sljit_sw)); - - set_jumps(current->topbacktracks, LABEL()); - } -else - set_jumps(current->topbacktracks, LABEL()); - -if (bra == OP_BRAZERO) - { - /* We know there is enough place on the stack. */ - OP2(SLJIT_ADD, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, sizeof(sljit_sw)); - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), SLJIT_IMM, 0); - JUMPTO(SLJIT_JUMP, CURRENT_AS(assert_backtrack)->matchingpath); - JUMPHERE(brajump); - } -} - -static void compile_bracket_backtrackingpath(compiler_common *common, struct backtrack_common *current) -{ -DEFINE_COMPILER; -int opcode, stacksize, alt_count, alt_max; -int offset = 0; -int private_data_ptr = CURRENT_AS(bracket_backtrack)->private_data_ptr; -int repeat_ptr = 0, repeat_type = 0, repeat_count = 0; -pcre_uchar *cc = current->cc; -pcre_uchar *ccbegin; -pcre_uchar *ccprev; -pcre_uchar bra = OP_BRA; -pcre_uchar ket; -assert_backtrack *assert; -sljit_uw *next_update_addr = NULL; -BOOL has_alternatives; -BOOL needs_control_head = FALSE; -struct sljit_jump *brazero = NULL; -struct sljit_jump *alt1 = NULL; -struct sljit_jump *alt2 = NULL; -struct sljit_jump *once = NULL; -struct sljit_jump *cond = NULL; -struct sljit_label *rmin_label = NULL; -struct sljit_label *exact_label = NULL; - -if (*cc == OP_BRAZERO || *cc == OP_BRAMINZERO) - { - bra = *cc; - cc++; - } - -opcode = *cc; -ccbegin = bracketend(cc) - 1 - LINK_SIZE; -ket = *ccbegin; -if (ket == OP_KET && PRIVATE_DATA(ccbegin) != 0) - { - repeat_ptr = PRIVATE_DATA(ccbegin); - repeat_type = PRIVATE_DATA(ccbegin + 2); - repeat_count = PRIVATE_DATA(ccbegin + 3); - SLJIT_ASSERT(repeat_type != 0 && repeat_count != 0); - if (repeat_type == OP_UPTO) - ket = OP_KETRMAX; - if (repeat_type == OP_MINUPTO) - ket = OP_KETRMIN; - } -ccbegin = cc; -cc += GET(cc, 1); -has_alternatives = *cc == OP_ALT; -if (SLJIT_UNLIKELY(opcode == OP_COND) || SLJIT_UNLIKELY(opcode == OP_SCOND)) - has_alternatives = (ccbegin[1 + LINK_SIZE] >= OP_ASSERT && ccbegin[1 + LINK_SIZE] <= OP_ASSERTBACK_NOT) || CURRENT_AS(bracket_backtrack)->u.condfailed != NULL; -if (opcode == OP_CBRA || opcode == OP_SCBRA) - offset = (GET2(ccbegin, 1 + LINK_SIZE)) << 1; -if (SLJIT_UNLIKELY(opcode == OP_COND) && (*cc == OP_KETRMAX || *cc == OP_KETRMIN)) - opcode = OP_SCOND; -if (SLJIT_UNLIKELY(opcode == OP_ONCE_NC)) - opcode = OP_ONCE; - -alt_max = has_alternatives ? no_alternatives(ccbegin) : 0; - -/* Decoding the needs_control_head in framesize. */ -if (opcode == OP_ONCE) - { - needs_control_head = (CURRENT_AS(bracket_backtrack)->u.framesize & 0x1) != 0; - CURRENT_AS(bracket_backtrack)->u.framesize >>= 1; - } - -if (ket != OP_KET && repeat_type != 0) - { - /* TMP1 is used in OP_KETRMIN below. */ - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); - free_stack(common, 1); - if (repeat_type == OP_UPTO) - OP2(SLJIT_ADD, SLJIT_MEM1(SLJIT_SP), repeat_ptr, TMP1, 0, SLJIT_IMM, 1); - else - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), repeat_ptr, TMP1, 0); - } - -if (ket == OP_KETRMAX) - { - if (bra == OP_BRAZERO) - { - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); - free_stack(common, 1); - brazero = CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, 0); - } - } -else if (ket == OP_KETRMIN) - { - if (bra != OP_BRAMINZERO) - { - OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); - if (repeat_type != 0) - { - /* TMP1 was set a few lines above. */ - CMPTO(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, 0, CURRENT_AS(bracket_backtrack)->recursive_matchingpath); - /* Drop STR_PTR for non-greedy plus quantifier. */ - if (opcode != OP_ONCE) - free_stack(common, 1); - } - else if (opcode >= OP_SBRA || opcode == OP_ONCE) - { - /* Checking zero-length iteration. */ - if (opcode != OP_ONCE || CURRENT_AS(bracket_backtrack)->u.framesize < 0) - CMPTO(SLJIT_C_NOT_EQUAL, STR_PTR, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr, CURRENT_AS(bracket_backtrack)->recursive_matchingpath); - else - { - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); - CMPTO(SLJIT_C_NOT_EQUAL, STR_PTR, 0, SLJIT_MEM1(TMP1), (CURRENT_AS(bracket_backtrack)->u.framesize + 1) * sizeof(sljit_sw), CURRENT_AS(bracket_backtrack)->recursive_matchingpath); - } - /* Drop STR_PTR for non-greedy plus quantifier. */ - if (opcode != OP_ONCE) - free_stack(common, 1); - } - else - JUMPTO(SLJIT_JUMP, CURRENT_AS(bracket_backtrack)->recursive_matchingpath); - } - rmin_label = LABEL(); - if (repeat_type != 0) - OP2(SLJIT_ADD, SLJIT_MEM1(SLJIT_SP), repeat_ptr, SLJIT_MEM1(SLJIT_SP), repeat_ptr, SLJIT_IMM, 1); - } -else if (bra == OP_BRAZERO) - { - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); - free_stack(common, 1); - brazero = CMP(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, 0); - } -else if (repeat_type == OP_EXACT) - { - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), repeat_ptr, SLJIT_IMM, 1); - exact_label = LABEL(); - } - -if (offset != 0) - { - if (common->capture_last_ptr != 0) - { - SLJIT_ASSERT(common->optimized_cbracket[offset >> 1] == 0); - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), STACK(1)); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->capture_last_ptr, TMP1, 0); - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(2)); - free_stack(common, 3); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset), TMP2, 0); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1), TMP1, 0); - } - else if (common->optimized_cbracket[offset >> 1] == 0) - { - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), STACK(1)); - free_stack(common, 2); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset), TMP1, 0); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1), TMP2, 0); - } - } - -if (SLJIT_UNLIKELY(opcode == OP_ONCE)) - { - if (CURRENT_AS(bracket_backtrack)->u.framesize >= 0) - { - OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); - add_jump(compiler, &common->revertframes, JUMP(SLJIT_FAST_CALL)); - } - once = JUMP(SLJIT_JUMP); - } -else if (SLJIT_UNLIKELY(opcode == OP_COND) || SLJIT_UNLIKELY(opcode == OP_SCOND)) - { - if (has_alternatives) - { - /* Always exactly one alternative. */ - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); - free_stack(common, 1); - - alt_max = 2; - alt1 = CMP(SLJIT_C_EQUAL, TMP1, 0, SLJIT_IMM, sizeof(sljit_uw)); - } - } -else if (has_alternatives) - { - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); - free_stack(common, 1); - - if (alt_max > 4) - { - /* Table jump if alt_max is greater than 4. */ - next_update_addr = common->read_only_data_ptr; - common->read_only_data_ptr += alt_max; - sljit_emit_ijump(compiler, SLJIT_JUMP, SLJIT_MEM1(TMP1), (sljit_sw)next_update_addr); - add_label_addr(common, next_update_addr++); - } - else - { - if (alt_max == 4) - alt2 = CMP(SLJIT_C_GREATER_EQUAL, TMP1, 0, SLJIT_IMM, 2 * sizeof(sljit_uw)); - alt1 = CMP(SLJIT_C_GREATER_EQUAL, TMP1, 0, SLJIT_IMM, sizeof(sljit_uw)); - } - } - -COMPILE_BACKTRACKINGPATH(current->top); -if (current->topbacktracks) - set_jumps(current->topbacktracks, LABEL()); - -if (SLJIT_UNLIKELY(opcode == OP_COND) || SLJIT_UNLIKELY(opcode == OP_SCOND)) - { - /* Conditional block always has at most one alternative. */ - if (ccbegin[1 + LINK_SIZE] >= OP_ASSERT && ccbegin[1 + LINK_SIZE] <= OP_ASSERTBACK_NOT) - { - SLJIT_ASSERT(has_alternatives); - assert = CURRENT_AS(bracket_backtrack)->u.assert; - if (assert->framesize >= 0 && (ccbegin[1 + LINK_SIZE] == OP_ASSERT || ccbegin[1 + LINK_SIZE] == OP_ASSERTBACK)) - { - OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), assert->private_data_ptr); - add_jump(compiler, &common->revertframes, JUMP(SLJIT_FAST_CALL)); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), assert->private_data_ptr, SLJIT_MEM1(STACK_TOP), assert->framesize * sizeof(sljit_sw)); - } - cond = JUMP(SLJIT_JUMP); - set_jumps(CURRENT_AS(bracket_backtrack)->u.assert->condfailed, LABEL()); - } - else if (CURRENT_AS(bracket_backtrack)->u.condfailed != NULL) - { - SLJIT_ASSERT(has_alternatives); - cond = JUMP(SLJIT_JUMP); - set_jumps(CURRENT_AS(bracket_backtrack)->u.condfailed, LABEL()); - } - else - SLJIT_ASSERT(!has_alternatives); - } - -if (has_alternatives) - { - alt_count = sizeof(sljit_uw); - do - { - current->top = NULL; - current->topbacktracks = NULL; - current->nextbacktracks = NULL; - /* Conditional blocks always have an additional alternative, even if it is empty. */ - if (*cc == OP_ALT) - { - ccprev = cc + 1 + LINK_SIZE; - cc += GET(cc, 1); - if (opcode != OP_COND && opcode != OP_SCOND) - { - if (opcode != OP_ONCE) - { - if (private_data_ptr != 0) - OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(SLJIT_SP), private_data_ptr); - else - OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); - } - else - OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(needs_control_head ? 1 : 0)); - } - compile_matchingpath(common, ccprev, cc, current); - if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) - return; - } - - /* Instructions after the current alternative is successfully matched. */ - /* There is a similar code in compile_bracket_matchingpath. */ - if (opcode == OP_ONCE) - match_once_common(common, ket, CURRENT_AS(bracket_backtrack)->u.framesize, private_data_ptr, has_alternatives, needs_control_head); - - stacksize = 0; - if (repeat_type == OP_MINUPTO) - { - /* We need to preserve the counter. TMP2 will be used below. */ - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), repeat_ptr); - stacksize++; - } - if (ket != OP_KET || bra != OP_BRA) - stacksize++; - if (offset != 0) - { - if (common->capture_last_ptr != 0) - stacksize++; - if (common->optimized_cbracket[offset >> 1] == 0) - stacksize += 2; - } - if (opcode != OP_ONCE) - stacksize++; - - if (stacksize > 0) - allocate_stack(common, stacksize); - - stacksize = 0; - if (repeat_type == OP_MINUPTO) - { - /* TMP2 was set above. */ - OP2(SLJIT_SUB, SLJIT_MEM1(STACK_TOP), STACK(stacksize), TMP2, 0, SLJIT_IMM, 1); - stacksize++; - } - - if (ket != OP_KET || bra != OP_BRA) - { - if (ket != OP_KET) - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), STR_PTR, 0); - else - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), SLJIT_IMM, 0); - stacksize++; - } - - if (offset != 0) - stacksize = match_capture_common(common, stacksize, offset, private_data_ptr); - - if (opcode != OP_ONCE) - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(stacksize), SLJIT_IMM, alt_count); - - if (offset != 0 && ket == OP_KETRMAX && common->optimized_cbracket[offset >> 1] != 0) - { - /* If ket is not OP_KETRMAX, this code path is executed after the jump to alternative_matchingpath. */ - SLJIT_ASSERT(private_data_ptr == OVECTOR(offset + 0)); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1), STR_PTR, 0); - } - - JUMPTO(SLJIT_JUMP, CURRENT_AS(bracket_backtrack)->alternative_matchingpath); - - if (opcode != OP_ONCE) - { - if (alt_max > 4) - add_label_addr(common, next_update_addr++); - else - { - if (alt_count != 2 * sizeof(sljit_uw)) - { - JUMPHERE(alt1); - if (alt_max == 3 && alt_count == sizeof(sljit_uw)) - alt2 = CMP(SLJIT_C_GREATER_EQUAL, TMP1, 0, SLJIT_IMM, 2 * sizeof(sljit_uw)); - } - else - { - JUMPHERE(alt2); - if (alt_max == 4) - alt1 = CMP(SLJIT_C_GREATER_EQUAL, TMP1, 0, SLJIT_IMM, 3 * sizeof(sljit_uw)); - } - } - alt_count += sizeof(sljit_uw); - } - - COMPILE_BACKTRACKINGPATH(current->top); - if (current->topbacktracks) - set_jumps(current->topbacktracks, LABEL()); - SLJIT_ASSERT(!current->nextbacktracks); - } - while (*cc == OP_ALT); - - if (cond != NULL) - { - SLJIT_ASSERT(opcode == OP_COND || opcode == OP_SCOND); - assert = CURRENT_AS(bracket_backtrack)->u.assert; - if ((ccbegin[1 + LINK_SIZE] == OP_ASSERT_NOT || ccbegin[1 + LINK_SIZE] == OP_ASSERTBACK_NOT) && assert->framesize >= 0) - { - OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), assert->private_data_ptr); - add_jump(compiler, &common->revertframes, JUMP(SLJIT_FAST_CALL)); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), assert->private_data_ptr, SLJIT_MEM1(STACK_TOP), assert->framesize * sizeof(sljit_sw)); - } - JUMPHERE(cond); - } - - /* Free the STR_PTR. */ - if (private_data_ptr == 0) - free_stack(common, 1); - } - -if (offset != 0) - { - /* Using both tmp register is better for instruction scheduling. */ - if (common->optimized_cbracket[offset >> 1] != 0) - { - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), STACK(1)); - free_stack(common, 2); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset), TMP1, 0); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1), TMP2, 0); - } - else - { - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); - free_stack(common, 1); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, TMP1, 0); - } - } -else if (opcode == OP_SBRA || opcode == OP_SCOND) - { - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, SLJIT_MEM1(STACK_TOP), STACK(0)); - free_stack(common, 1); - } -else if (opcode == OP_ONCE) - { - cc = ccbegin + GET(ccbegin, 1); - stacksize = needs_control_head ? 1 : 0; - - if (CURRENT_AS(bracket_backtrack)->u.framesize >= 0) - { - /* Reset head and drop saved frame. */ - stacksize += CURRENT_AS(bracket_backtrack)->u.framesize + ((ket != OP_KET || *cc == OP_ALT) ? 2 : 1); - } - else if (ket == OP_KETRMAX || (*cc == OP_ALT && ket != OP_KETRMIN)) - { - /* The STR_PTR must be released. */ - stacksize++; - } - free_stack(common, stacksize); - - JUMPHERE(once); - /* Restore previous private_data_ptr */ - if (CURRENT_AS(bracket_backtrack)->u.framesize >= 0) - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, SLJIT_MEM1(STACK_TOP), CURRENT_AS(bracket_backtrack)->u.framesize * sizeof(sljit_sw)); - else if (ket == OP_KETRMIN) - { - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(1)); - /* See the comment below. */ - free_stack(common, 2); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), private_data_ptr, TMP1, 0); - } - } - -if (repeat_type == OP_EXACT) - { - OP2(SLJIT_ADD, TMP1, 0, SLJIT_MEM1(SLJIT_SP), repeat_ptr, SLJIT_IMM, 1); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), repeat_ptr, TMP1, 0); - CMPTO(SLJIT_C_LESS_EQUAL, TMP1, 0, SLJIT_IMM, repeat_count, exact_label); - } -else if (ket == OP_KETRMAX) - { - OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); - if (bra != OP_BRAZERO) - free_stack(common, 1); - - CMPTO(SLJIT_C_NOT_EQUAL, STR_PTR, 0, SLJIT_IMM, 0, CURRENT_AS(bracket_backtrack)->recursive_matchingpath); - if (bra == OP_BRAZERO) - { - OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(1)); - JUMPTO(SLJIT_JUMP, CURRENT_AS(bracket_backtrack)->zero_matchingpath); - JUMPHERE(brazero); - free_stack(common, 1); - } - } -else if (ket == OP_KETRMIN) - { - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); - - /* OP_ONCE removes everything in case of a backtrack, so we don't - need to explicitly release the STR_PTR. The extra release would - affect badly the free_stack(2) above. */ - if (opcode != OP_ONCE) - free_stack(common, 1); - CMPTO(SLJIT_C_NOT_EQUAL, TMP1, 0, SLJIT_IMM, 0, rmin_label); - if (opcode == OP_ONCE) - free_stack(common, bra == OP_BRAMINZERO ? 2 : 1); - else if (bra == OP_BRAMINZERO) - free_stack(common, 1); - } -else if (bra == OP_BRAZERO) - { - OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); - JUMPTO(SLJIT_JUMP, CURRENT_AS(bracket_backtrack)->zero_matchingpath); - JUMPHERE(brazero); - } -} - -static SLJIT_INLINE void compile_bracketpos_backtrackingpath(compiler_common *common, struct backtrack_common *current) -{ -DEFINE_COMPILER; -int offset; -struct sljit_jump *jump; - -if (CURRENT_AS(bracketpos_backtrack)->framesize < 0) - { - if (*current->cc == OP_CBRAPOS || *current->cc == OP_SCBRAPOS) - { - offset = (GET2(current->cc, 1 + LINK_SIZE)) << 1; - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), STACK(1)); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset), TMP1, 0); - if (common->capture_last_ptr != 0) - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(2)); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(offset + 1), TMP2, 0); - if (common->capture_last_ptr != 0) - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->capture_last_ptr, TMP1, 0); - } - set_jumps(current->topbacktracks, LABEL()); - free_stack(common, CURRENT_AS(bracketpos_backtrack)->stacksize); - return; - } - -OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), CURRENT_AS(bracketpos_backtrack)->private_data_ptr); -add_jump(compiler, &common->revertframes, JUMP(SLJIT_FAST_CALL)); - -if (current->topbacktracks) - { - jump = JUMP(SLJIT_JUMP); - set_jumps(current->topbacktracks, LABEL()); - /* Drop the stack frame. */ - free_stack(common, CURRENT_AS(bracketpos_backtrack)->stacksize); - JUMPHERE(jump); - } -OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), CURRENT_AS(bracketpos_backtrack)->private_data_ptr, SLJIT_MEM1(STACK_TOP), CURRENT_AS(bracketpos_backtrack)->framesize * sizeof(sljit_sw)); -} - -static SLJIT_INLINE void compile_braminzero_backtrackingpath(compiler_common *common, struct backtrack_common *current) -{ -assert_backtrack backtrack; - -current->top = NULL; -current->topbacktracks = NULL; -current->nextbacktracks = NULL; -if (current->cc[1] > OP_ASSERTBACK_NOT) - { - /* Manual call of compile_bracket_matchingpath and compile_bracket_backtrackingpath. */ - compile_bracket_matchingpath(common, current->cc, current); - compile_bracket_backtrackingpath(common, current->top); - } -else - { - memset(&backtrack, 0, sizeof(backtrack)); - backtrack.common.cc = current->cc; - backtrack.matchingpath = CURRENT_AS(braminzero_backtrack)->matchingpath; - /* Manual call of compile_assert_matchingpath. */ - compile_assert_matchingpath(common, current->cc, &backtrack, FALSE); - } -SLJIT_ASSERT(!current->nextbacktracks && !current->topbacktracks); -} - -static SLJIT_INLINE void compile_control_verb_backtrackingpath(compiler_common *common, struct backtrack_common *current) -{ -DEFINE_COMPILER; -pcre_uchar opcode = *current->cc; -struct sljit_label *loop; -struct sljit_jump *jump; - -if (opcode == OP_THEN || opcode == OP_THEN_ARG) - { - if (common->then_trap != NULL) - { - SLJIT_ASSERT(common->control_head_ptr != 0); - - OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr); - OP1(SLJIT_MOV, TMP1, 0, SLJIT_IMM, type_then_trap); - OP1(SLJIT_MOV, TMP2, 0, SLJIT_IMM, common->then_trap->start); - jump = JUMP(SLJIT_JUMP); - - loop = LABEL(); - OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(STACK_TOP), -(int)sizeof(sljit_sw)); - JUMPHERE(jump); - CMPTO(SLJIT_C_NOT_EQUAL, SLJIT_MEM1(STACK_TOP), -(int)(2 * sizeof(sljit_sw)), TMP1, 0, loop); - CMPTO(SLJIT_C_NOT_EQUAL, SLJIT_MEM1(STACK_TOP), -(int)(3 * sizeof(sljit_sw)), TMP2, 0, loop); - add_jump(compiler, &common->then_trap->quit, JUMP(SLJIT_JUMP)); - return; - } - else if (common->positive_assert) - { - add_jump(compiler, &common->positive_assert_quit, JUMP(SLJIT_JUMP)); - return; - } - } - -if (common->local_exit) - { - if (common->quit_label == NULL) - add_jump(compiler, &common->quit, JUMP(SLJIT_JUMP)); - else - JUMPTO(SLJIT_JUMP, common->quit_label); - return; - } - -if (opcode == OP_SKIP_ARG) - { - SLJIT_ASSERT(common->control_head_ptr != 0); - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS0, STACK_TOP, 0); - OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_IMM, (sljit_sw)(current->cc + 2)); - sljit_emit_ijump(compiler, SLJIT_CALL2, SLJIT_IMM, SLJIT_FUNC_OFFSET(do_search_mark)); - OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), LOCALS0); - - OP1(SLJIT_MOV, STR_PTR, 0, TMP1, 0); - add_jump(compiler, &common->reset_match, CMP(SLJIT_C_NOT_EQUAL, STR_PTR, 0, SLJIT_IMM, -1)); - return; - } - -if (opcode == OP_SKIP) - OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); -else - OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_IMM, 0); -add_jump(compiler, &common->reset_match, JUMP(SLJIT_JUMP)); -} - -static SLJIT_INLINE void compile_then_trap_backtrackingpath(compiler_common *common, struct backtrack_common *current) -{ -DEFINE_COMPILER; -struct sljit_jump *jump; -int size; - -if (CURRENT_AS(then_trap_backtrack)->then_trap) - { - common->then_trap = CURRENT_AS(then_trap_backtrack)->then_trap; - return; - } - -size = CURRENT_AS(then_trap_backtrack)->framesize; -size = 3 + (size < 0 ? 0 : size); - -OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(size - 3)); -free_stack(common, size); -jump = JUMP(SLJIT_JUMP); - -set_jumps(CURRENT_AS(then_trap_backtrack)->quit, LABEL()); -/* STACK_TOP is set by THEN. */ -if (CURRENT_AS(then_trap_backtrack)->framesize >= 0) - add_jump(compiler, &common->revertframes, JUMP(SLJIT_FAST_CALL)); -OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); -free_stack(common, 3); - -JUMPHERE(jump); -OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, TMP1, 0); -} - -static void compile_backtrackingpath(compiler_common *common, struct backtrack_common *current) -{ -DEFINE_COMPILER; -then_trap_backtrack *save_then_trap = common->then_trap; - -while (current) - { - if (current->nextbacktracks != NULL) - set_jumps(current->nextbacktracks, LABEL()); - switch(*current->cc) - { - case OP_SET_SOM: - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); - free_stack(common, 1); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(0), TMP1, 0); - break; - - case OP_STAR: - case OP_MINSTAR: - case OP_PLUS: - case OP_MINPLUS: - case OP_QUERY: - case OP_MINQUERY: - case OP_UPTO: - case OP_MINUPTO: - case OP_EXACT: - case OP_POSSTAR: - case OP_POSPLUS: - case OP_POSQUERY: - case OP_POSUPTO: - case OP_STARI: - case OP_MINSTARI: - case OP_PLUSI: - case OP_MINPLUSI: - case OP_QUERYI: - case OP_MINQUERYI: - case OP_UPTOI: - case OP_MINUPTOI: - case OP_EXACTI: - case OP_POSSTARI: - case OP_POSPLUSI: - case OP_POSQUERYI: - case OP_POSUPTOI: - case OP_NOTSTAR: - case OP_NOTMINSTAR: - case OP_NOTPLUS: - case OP_NOTMINPLUS: - case OP_NOTQUERY: - case OP_NOTMINQUERY: - case OP_NOTUPTO: - case OP_NOTMINUPTO: - case OP_NOTEXACT: - case OP_NOTPOSSTAR: - case OP_NOTPOSPLUS: - case OP_NOTPOSQUERY: - case OP_NOTPOSUPTO: - case OP_NOTSTARI: - case OP_NOTMINSTARI: - case OP_NOTPLUSI: - case OP_NOTMINPLUSI: - case OP_NOTQUERYI: - case OP_NOTMINQUERYI: - case OP_NOTUPTOI: - case OP_NOTMINUPTOI: - case OP_NOTEXACTI: - case OP_NOTPOSSTARI: - case OP_NOTPOSPLUSI: - case OP_NOTPOSQUERYI: - case OP_NOTPOSUPTOI: - case OP_TYPESTAR: - case OP_TYPEMINSTAR: - case OP_TYPEPLUS: - case OP_TYPEMINPLUS: - case OP_TYPEQUERY: - case OP_TYPEMINQUERY: - case OP_TYPEUPTO: - case OP_TYPEMINUPTO: - case OP_TYPEEXACT: - case OP_TYPEPOSSTAR: - case OP_TYPEPOSPLUS: - case OP_TYPEPOSQUERY: - case OP_TYPEPOSUPTO: - case OP_CLASS: - case OP_NCLASS: -#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 - case OP_XCLASS: -#endif - compile_iterator_backtrackingpath(common, current); - break; - - case OP_REF: - case OP_REFI: - case OP_DNREF: - case OP_DNREFI: - compile_ref_iterator_backtrackingpath(common, current); - break; - - case OP_RECURSE: - compile_recurse_backtrackingpath(common, current); - break; - - case OP_ASSERT: - case OP_ASSERT_NOT: - case OP_ASSERTBACK: - case OP_ASSERTBACK_NOT: - compile_assert_backtrackingpath(common, current); - break; - - case OP_ONCE: - case OP_ONCE_NC: - case OP_BRA: - case OP_CBRA: - case OP_COND: - case OP_SBRA: - case OP_SCBRA: - case OP_SCOND: - compile_bracket_backtrackingpath(common, current); - break; - - case OP_BRAZERO: - if (current->cc[1] > OP_ASSERTBACK_NOT) - compile_bracket_backtrackingpath(common, current); - else - compile_assert_backtrackingpath(common, current); - break; - - case OP_BRAPOS: - case OP_CBRAPOS: - case OP_SBRAPOS: - case OP_SCBRAPOS: - case OP_BRAPOSZERO: - compile_bracketpos_backtrackingpath(common, current); - break; - - case OP_BRAMINZERO: - compile_braminzero_backtrackingpath(common, current); - break; - - case OP_MARK: - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), STACK(common->has_skip_arg ? 4 : 0)); - if (common->has_skip_arg) - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); - free_stack(common, common->has_skip_arg ? 5 : 1); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->mark_ptr, TMP1, 0); - if (common->has_skip_arg) - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, TMP2, 0); - break; - - case OP_THEN: - case OP_THEN_ARG: - case OP_PRUNE: - case OP_PRUNE_ARG: - case OP_SKIP: - case OP_SKIP_ARG: - compile_control_verb_backtrackingpath(common, current); - break; - - case OP_COMMIT: - if (!common->local_exit) - OP1(SLJIT_MOV, SLJIT_RETURN_REG, 0, SLJIT_IMM, PCRE_ERROR_NOMATCH); - if (common->quit_label == NULL) - add_jump(compiler, &common->quit, JUMP(SLJIT_JUMP)); - else - JUMPTO(SLJIT_JUMP, common->quit_label); - break; - - case OP_CALLOUT: - case OP_FAIL: - case OP_ACCEPT: - case OP_ASSERT_ACCEPT: - set_jumps(current->topbacktracks, LABEL()); - break; - - case OP_THEN_TRAP: - /* A virtual opcode for then traps. */ - compile_then_trap_backtrackingpath(common, current); - break; - - default: - SLJIT_ASSERT_STOP(); - break; - } - current = current->prev; - } -common->then_trap = save_then_trap; -} - -static SLJIT_INLINE void compile_recurse(compiler_common *common) -{ -DEFINE_COMPILER; -pcre_uchar *cc = common->start + common->currententry->start; -pcre_uchar *ccbegin = cc + 1 + LINK_SIZE + (*cc == OP_BRA ? 0 : IMM2_SIZE); -pcre_uchar *ccend = bracketend(cc); -BOOL needs_control_head; -int framesize = get_framesize(common, cc, NULL, TRUE, &needs_control_head); -int private_data_size = get_private_data_copy_length(common, ccbegin, ccend, needs_control_head); -int alternativesize; -BOOL needs_frame; -backtrack_common altbacktrack; -struct sljit_jump *jump; - -/* Recurse captures then. */ -common->then_trap = NULL; - -SLJIT_ASSERT(*cc == OP_BRA || *cc == OP_CBRA || *cc == OP_CBRAPOS || *cc == OP_SCBRA || *cc == OP_SCBRAPOS); -needs_frame = framesize >= 0; -if (!needs_frame) - framesize = 0; -alternativesize = *(cc + GET(cc, 1)) == OP_ALT ? 1 : 0; - -SLJIT_ASSERT(common->currententry->entry == NULL && common->recursive_head_ptr != 0); -common->currententry->entry = LABEL(); -set_jumps(common->currententry->calls, common->currententry->entry); - -sljit_emit_fast_enter(compiler, TMP2, 0); -allocate_stack(common, private_data_size + framesize + alternativesize); -OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(private_data_size + framesize + alternativesize - 1), TMP2, 0); -copy_private_data(common, ccbegin, ccend, TRUE, private_data_size + framesize + alternativesize, framesize + alternativesize, needs_control_head); -if (needs_control_head) - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, SLJIT_IMM, 0); -OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->recursive_head_ptr, STACK_TOP, 0); -if (needs_frame) - init_frame(common, cc, NULL, framesize + alternativesize - 1, alternativesize, TRUE); - -if (alternativesize > 0) - OP1(SLJIT_MOV, SLJIT_MEM1(STACK_TOP), STACK(0), STR_PTR, 0); - -memset(&altbacktrack, 0, sizeof(backtrack_common)); -common->quit_label = NULL; -common->accept_label = NULL; -common->quit = NULL; -common->accept = NULL; -altbacktrack.cc = ccbegin; -cc += GET(cc, 1); -while (1) - { - altbacktrack.top = NULL; - altbacktrack.topbacktracks = NULL; - - if (altbacktrack.cc != ccbegin) - OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(STACK_TOP), STACK(0)); - - compile_matchingpath(common, altbacktrack.cc, cc, &altbacktrack); - if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) - return; - - add_jump(compiler, &common->accept, JUMP(SLJIT_JUMP)); - - compile_backtrackingpath(common, altbacktrack.top); - if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) - return; - set_jumps(altbacktrack.topbacktracks, LABEL()); - - if (*cc != OP_ALT) - break; - - altbacktrack.cc = cc + 1 + LINK_SIZE; - cc += GET(cc, 1); - } - -/* None of them matched. */ -OP1(SLJIT_MOV, TMP3, 0, SLJIT_IMM, 0); -jump = JUMP(SLJIT_JUMP); - -if (common->quit != NULL) - { - set_jumps(common->quit, LABEL()); - OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), common->recursive_head_ptr); - if (needs_frame) - { - OP2(SLJIT_SUB, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, (framesize + alternativesize) * sizeof(sljit_sw)); - add_jump(compiler, &common->revertframes, JUMP(SLJIT_FAST_CALL)); - OP2(SLJIT_ADD, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, (framesize + alternativesize) * sizeof(sljit_sw)); - } - OP1(SLJIT_MOV, TMP3, 0, SLJIT_IMM, 0); - common->quit = NULL; - add_jump(compiler, &common->quit, JUMP(SLJIT_JUMP)); - } - -set_jumps(common->accept, LABEL()); -OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(SLJIT_SP), common->recursive_head_ptr); -if (needs_frame) - { - OP2(SLJIT_SUB, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, (framesize + alternativesize) * sizeof(sljit_sw)); - add_jump(compiler, &common->revertframes, JUMP(SLJIT_FAST_CALL)); - OP2(SLJIT_ADD, STACK_TOP, 0, STACK_TOP, 0, SLJIT_IMM, (framesize + alternativesize) * sizeof(sljit_sw)); - } -OP1(SLJIT_MOV, TMP3, 0, SLJIT_IMM, 1); - -JUMPHERE(jump); -if (common->quit != NULL) - set_jumps(common->quit, LABEL()); -copy_private_data(common, ccbegin, ccend, FALSE, private_data_size + framesize + alternativesize, framesize + alternativesize, needs_control_head); -free_stack(common, private_data_size + framesize + alternativesize); -if (needs_control_head) - { - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(STACK_TOP), 2 * sizeof(sljit_sw)); - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), sizeof(sljit_sw)); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->recursive_head_ptr, TMP1, 0); - OP1(SLJIT_MOV, TMP1, 0, TMP3, 0); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, TMP2, 0); - } -else - { - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(STACK_TOP), sizeof(sljit_sw)); - OP1(SLJIT_MOV, TMP1, 0, TMP3, 0); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->recursive_head_ptr, TMP2, 0); - } -sljit_emit_fast_return(compiler, SLJIT_MEM1(STACK_TOP), 0); -} - -#undef COMPILE_BACKTRACKINGPATH -#undef CURRENT_AS - -void -PRIV(jit_compile)(const REAL_PCRE *re, PUBL(extra) *extra, int mode) -{ -struct sljit_compiler *compiler; -backtrack_common rootbacktrack; -compiler_common common_data; -compiler_common *common = &common_data; -const pcre_uint8 *tables = re->tables; -pcre_study_data *study; -int private_data_size; -pcre_uchar *ccend; -executable_functions *functions; -void *executable_func; -sljit_uw executable_size; -sljit_uw total_length; -label_addr_list *label_addr; -struct sljit_label *mainloop_label = NULL; -struct sljit_label *continue_match_label; -struct sljit_label *empty_match_found_label = NULL; -struct sljit_label *empty_match_backtrack_label = NULL; -struct sljit_label *reset_match_label; -struct sljit_label *quit_label; -struct sljit_jump *jump; -struct sljit_jump *minlength_check_failed = NULL; -struct sljit_jump *reqbyte_notfound = NULL; -struct sljit_jump *empty_match = NULL; - -SLJIT_ASSERT((extra->flags & PCRE_EXTRA_STUDY_DATA) != 0); -study = extra->study_data; - -if (!tables) - tables = PRIV(default_tables); - -memset(&rootbacktrack, 0, sizeof(backtrack_common)); -memset(common, 0, sizeof(compiler_common)); -rootbacktrack.cc = (pcre_uchar *)re + re->name_table_offset + re->name_count * re->name_entry_size; - -common->start = rootbacktrack.cc; -common->read_only_data = NULL; -common->read_only_data_size = 0; -common->read_only_data_ptr = NULL; -common->fcc = tables + fcc_offset; -common->lcc = (sljit_sw)(tables + lcc_offset); -common->mode = mode; -common->might_be_empty = study->minlength == 0; -common->nltype = NLTYPE_FIXED; -switch(re->options & PCRE_NEWLINE_BITS) - { - case 0: - /* Compile-time default */ - switch(NEWLINE) - { - case -1: common->newline = (CHAR_CR << 8) | CHAR_NL; common->nltype = NLTYPE_ANY; break; - case -2: common->newline = (CHAR_CR << 8) | CHAR_NL; common->nltype = NLTYPE_ANYCRLF; break; - default: common->newline = NEWLINE; break; - } - break; - case PCRE_NEWLINE_CR: common->newline = CHAR_CR; break; - case PCRE_NEWLINE_LF: common->newline = CHAR_NL; break; - case PCRE_NEWLINE_CR+ - PCRE_NEWLINE_LF: common->newline = (CHAR_CR << 8) | CHAR_NL; break; - case PCRE_NEWLINE_ANY: common->newline = (CHAR_CR << 8) | CHAR_NL; common->nltype = NLTYPE_ANY; break; - case PCRE_NEWLINE_ANYCRLF: common->newline = (CHAR_CR << 8) | CHAR_NL; common->nltype = NLTYPE_ANYCRLF; break; - default: return; - } -common->nlmax = READ_CHAR_MAX; -common->nlmin = 0; -if ((re->options & PCRE_BSR_ANYCRLF) != 0) - common->bsr_nltype = NLTYPE_ANYCRLF; -else if ((re->options & PCRE_BSR_UNICODE) != 0) - common->bsr_nltype = NLTYPE_ANY; -else - { -#ifdef BSR_ANYCRLF - common->bsr_nltype = NLTYPE_ANYCRLF; -#else - common->bsr_nltype = NLTYPE_ANY; -#endif - } -common->bsr_nlmax = READ_CHAR_MAX; -common->bsr_nlmin = 0; -common->endonly = (re->options & PCRE_DOLLAR_ENDONLY) != 0; -common->ctypes = (sljit_sw)(tables + ctypes_offset); -common->name_table = ((pcre_uchar *)re) + re->name_table_offset; -common->name_count = re->name_count; -common->name_entry_size = re->name_entry_size; -common->jscript_compat = (re->options & PCRE_JAVASCRIPT_COMPAT) != 0; -#ifdef SUPPORT_UTF -/* PCRE_UTF[16|32] have the same value as PCRE_UTF8. */ -common->utf = (re->options & PCRE_UTF8) != 0; -#ifdef SUPPORT_UCP -common->use_ucp = (re->options & PCRE_UCP) != 0; -#endif -if (common->utf) - { - if (common->nltype == NLTYPE_ANY) - common->nlmax = 0x2029; - else if (common->nltype == NLTYPE_ANYCRLF) - common->nlmax = (CHAR_CR > CHAR_NL) ? CHAR_CR : CHAR_NL; - else - { - /* We only care about the first newline character. */ - common->nlmax = common->newline & 0xff; - } - - if (common->nltype == NLTYPE_FIXED) - common->nlmin = common->newline & 0xff; - else - common->nlmin = (CHAR_CR < CHAR_NL) ? CHAR_CR : CHAR_NL; - - if (common->bsr_nltype == NLTYPE_ANY) - common->bsr_nlmax = 0x2029; - else - common->bsr_nlmax = (CHAR_CR > CHAR_NL) ? CHAR_CR : CHAR_NL; - common->bsr_nlmin = (CHAR_CR < CHAR_NL) ? CHAR_CR : CHAR_NL; - } -#endif /* SUPPORT_UTF */ -ccend = bracketend(common->start); - -/* Calculate the local space size on the stack. */ -common->ovector_start = LIMIT_MATCH + sizeof(sljit_sw); -common->optimized_cbracket = (pcre_uint8 *)SLJIT_MALLOC(re->top_bracket + 1); -if (!common->optimized_cbracket) - return; -#if defined DEBUG_FORCE_UNOPTIMIZED_CBRAS && DEBUG_FORCE_UNOPTIMIZED_CBRAS == 1 -memset(common->optimized_cbracket, 0, re->top_bracket + 1); -#else -memset(common->optimized_cbracket, 1, re->top_bracket + 1); -#endif - -SLJIT_ASSERT(*common->start == OP_BRA && ccend[-(1 + LINK_SIZE)] == OP_KET); -#if defined DEBUG_FORCE_UNOPTIMIZED_CBRAS && DEBUG_FORCE_UNOPTIMIZED_CBRAS == 2 -common->capture_last_ptr = common->ovector_start; -common->ovector_start += sizeof(sljit_sw); -#endif -if (!check_opcode_types(common, common->start, ccend)) - { - SLJIT_FREE(common->optimized_cbracket); - return; - } - -/* Checking flags and updating ovector_start. */ -if (mode == JIT_COMPILE && (re->flags & PCRE_REQCHSET) != 0 && (re->options & PCRE_NO_START_OPTIMIZE) == 0) - { - common->req_char_ptr = common->ovector_start; - common->ovector_start += sizeof(sljit_sw); - } -if (mode != JIT_COMPILE) - { - common->start_used_ptr = common->ovector_start; - common->ovector_start += sizeof(sljit_sw); - if (mode == JIT_PARTIAL_SOFT_COMPILE) - { - common->hit_start = common->ovector_start; - common->ovector_start += 2 * sizeof(sljit_sw); - } - else - { - SLJIT_ASSERT(mode == JIT_PARTIAL_HARD_COMPILE); - common->needs_start_ptr = TRUE; - } - } -if ((re->options & PCRE_FIRSTLINE) != 0) - { - common->first_line_end = common->ovector_start; - common->ovector_start += sizeof(sljit_sw); - } -#if defined DEBUG_FORCE_CONTROL_HEAD && DEBUG_FORCE_CONTROL_HEAD -common->control_head_ptr = 1; -#endif -if (common->control_head_ptr != 0) - { - common->control_head_ptr = common->ovector_start; - common->ovector_start += sizeof(sljit_sw); - } -if (common->needs_start_ptr && common->has_set_som) - { - /* Saving the real start pointer is necessary. */ - common->start_ptr = common->ovector_start; - common->ovector_start += sizeof(sljit_sw); - } -else - common->needs_start_ptr = FALSE; - -/* Aligning ovector to even number of sljit words. */ -if ((common->ovector_start & sizeof(sljit_sw)) != 0) - common->ovector_start += sizeof(sljit_sw); - -if (common->start_ptr == 0) - common->start_ptr = OVECTOR(0); - -/* Capturing brackets cannot be optimized if callouts are allowed. */ -if (common->capture_last_ptr != 0) - memset(common->optimized_cbracket, 0, re->top_bracket + 1); - -SLJIT_ASSERT(!(common->req_char_ptr != 0 && common->start_used_ptr != 0)); -common->cbra_ptr = OVECTOR_START + (re->top_bracket + 1) * 2 * sizeof(sljit_sw); - -total_length = ccend - common->start; -common->private_data_ptrs = (sljit_si *)SLJIT_MALLOC(total_length * (sizeof(sljit_si) + (common->has_then ? 1 : 0))); -if (!common->private_data_ptrs) - { - SLJIT_FREE(common->optimized_cbracket); - return; - } -memset(common->private_data_ptrs, 0, total_length * sizeof(sljit_si)); - -private_data_size = common->cbra_ptr + (re->top_bracket + 1) * sizeof(sljit_sw); -set_private_data_ptrs(common, &private_data_size, ccend); -if (private_data_size > SLJIT_MAX_LOCAL_SIZE) - { - SLJIT_FREE(common->private_data_ptrs); - SLJIT_FREE(common->optimized_cbracket); - return; - } - -if (common->has_then) - { - common->then_offsets = (pcre_uint8 *)(common->private_data_ptrs + total_length); - memset(common->then_offsets, 0, total_length); - set_then_offsets(common, common->start, NULL); - } - -if (common->read_only_data_size > 0) - { - common->read_only_data = (sljit_uw *)SLJIT_MALLOC(common->read_only_data_size); - if (common->read_only_data == NULL) - { - SLJIT_FREE(common->optimized_cbracket); - SLJIT_FREE(common->private_data_ptrs); - return; - } - common->read_only_data_ptr = common->read_only_data; - } - -compiler = sljit_create_compiler(); -if (!compiler) - { - SLJIT_FREE(common->optimized_cbracket); - SLJIT_FREE(common->private_data_ptrs); - if (common->read_only_data) - SLJIT_FREE(common->read_only_data); - return; - } -common->compiler = compiler; - -/* Main pcre_jit_exec entry. */ -sljit_emit_enter(compiler, 0, 1, 5, 5, 0, 0, private_data_size); - -/* Register init. */ -reset_ovector(common, (re->top_bracket + 1) * 2); -if (common->req_char_ptr != 0) - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->req_char_ptr, SLJIT_R0, 0); - -OP1(SLJIT_MOV, ARGUMENTS, 0, SLJIT_S0, 0); -OP1(SLJIT_MOV, TMP1, 0, SLJIT_S0, 0); -OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, str)); -OP1(SLJIT_MOV, STR_END, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, end)); -OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, stack)); -OP1(SLJIT_MOV_UI, TMP1, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, limit_match)); -OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(TMP2), SLJIT_OFFSETOF(struct sljit_stack, base)); -OP1(SLJIT_MOV, STACK_LIMIT, 0, SLJIT_MEM1(TMP2), SLJIT_OFFSETOF(struct sljit_stack, limit)); -OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LIMIT_MATCH, TMP1, 0); - -if (mode == JIT_PARTIAL_SOFT_COMPILE) - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->hit_start, SLJIT_IMM, -1); -if (common->mark_ptr != 0) - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->mark_ptr, SLJIT_IMM, 0); -if (common->control_head_ptr != 0) - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->control_head_ptr, SLJIT_IMM, 0); - -/* Main part of the matching */ -if ((re->options & PCRE_ANCHORED) == 0) - { - mainloop_label = mainloop_entry(common, (re->flags & PCRE_HASCRORLF) != 0, (re->options & PCRE_FIRSTLINE) != 0); - continue_match_label = LABEL(); - /* Forward search if possible. */ - if ((re->options & PCRE_NO_START_OPTIMIZE) == 0) - { - if (mode == JIT_COMPILE && fast_forward_first_n_chars(common, (re->options & PCRE_FIRSTLINE) != 0)) - { - /* If read_only_data is reallocated, we might have an allocation failure. */ - if (common->read_only_data_size > 0 && common->read_only_data == NULL) - { - sljit_free_compiler(compiler); - SLJIT_FREE(common->optimized_cbracket); - SLJIT_FREE(common->private_data_ptrs); - return; - } - } - else if ((re->flags & PCRE_FIRSTSET) != 0) - fast_forward_first_char(common, (pcre_uchar)re->first_char, (re->flags & PCRE_FCH_CASELESS) != 0, (re->options & PCRE_FIRSTLINE) != 0); - else if ((re->flags & PCRE_STARTLINE) != 0) - fast_forward_newline(common, (re->options & PCRE_FIRSTLINE) != 0); - else if ((re->flags & PCRE_STARTLINE) == 0 && study != NULL && (study->flags & PCRE_STUDY_MAPPED) != 0) - fast_forward_start_bits(common, study->start_bits, (re->options & PCRE_FIRSTLINE) != 0); - } - } -else - continue_match_label = LABEL(); - -if (mode == JIT_COMPILE && study->minlength > 0 && (re->options & PCRE_NO_START_OPTIMIZE) == 0) - { - OP1(SLJIT_MOV, SLJIT_RETURN_REG, 0, SLJIT_IMM, PCRE_ERROR_NOMATCH); - OP2(SLJIT_ADD, TMP2, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(study->minlength)); - minlength_check_failed = CMP(SLJIT_C_GREATER, TMP2, 0, STR_END, 0); - } -if (common->req_char_ptr != 0) - reqbyte_notfound = search_requested_char(common, (pcre_uchar)re->req_char, (re->flags & PCRE_RCH_CASELESS) != 0, (re->flags & PCRE_FIRSTSET) != 0); - -/* Store the current STR_PTR in OVECTOR(0). */ -OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), OVECTOR(0), STR_PTR, 0); -/* Copy the limit of allowed recursions. */ -OP1(SLJIT_MOV, COUNT_MATCH, 0, SLJIT_MEM1(SLJIT_SP), LIMIT_MATCH); -if (common->capture_last_ptr != 0) - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->capture_last_ptr, SLJIT_IMM, -1); - -if (common->needs_start_ptr) - { - SLJIT_ASSERT(common->start_ptr != OVECTOR(0)); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->start_ptr, STR_PTR, 0); - } -else - SLJIT_ASSERT(common->start_ptr == OVECTOR(0)); - -/* Copy the beginning of the string. */ -if (mode == JIT_PARTIAL_SOFT_COMPILE) - { - jump = CMP(SLJIT_C_NOT_EQUAL, SLJIT_MEM1(SLJIT_SP), common->hit_start, SLJIT_IMM, -1); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->start_used_ptr, STR_PTR, 0); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->hit_start + sizeof(sljit_sw), STR_PTR, 0); - JUMPHERE(jump); - } -else if (mode == JIT_PARTIAL_HARD_COMPILE) - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->start_used_ptr, STR_PTR, 0); - -compile_matchingpath(common, common->start, ccend, &rootbacktrack); -if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) - { - sljit_free_compiler(compiler); - SLJIT_FREE(common->optimized_cbracket); - SLJIT_FREE(common->private_data_ptrs); - if (common->read_only_data) - SLJIT_FREE(common->read_only_data); - return; - } - -if (common->might_be_empty) - { - empty_match = CMP(SLJIT_C_EQUAL, STR_PTR, 0, SLJIT_MEM1(SLJIT_SP), OVECTOR(0)); - empty_match_found_label = LABEL(); - } - -common->accept_label = LABEL(); -if (common->accept != NULL) - set_jumps(common->accept, common->accept_label); - -/* This means we have a match. Update the ovector. */ -copy_ovector(common, re->top_bracket + 1); -common->quit_label = common->forced_quit_label = LABEL(); -if (common->quit != NULL) - set_jumps(common->quit, common->quit_label); -if (common->forced_quit != NULL) - set_jumps(common->forced_quit, common->forced_quit_label); -if (minlength_check_failed != NULL) - SET_LABEL(minlength_check_failed, common->forced_quit_label); -sljit_emit_return(compiler, SLJIT_MOV, SLJIT_RETURN_REG, 0); - -if (mode != JIT_COMPILE) - { - common->partialmatchlabel = LABEL(); - set_jumps(common->partialmatch, common->partialmatchlabel); - return_with_partial_match(common, common->quit_label); - } - -if (common->might_be_empty) - empty_match_backtrack_label = LABEL(); -compile_backtrackingpath(common, rootbacktrack.top); -if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) - { - sljit_free_compiler(compiler); - SLJIT_FREE(common->optimized_cbracket); - SLJIT_FREE(common->private_data_ptrs); - if (common->read_only_data) - SLJIT_FREE(common->read_only_data); - return; - } - -SLJIT_ASSERT(rootbacktrack.prev == NULL); -reset_match_label = LABEL(); - -if (mode == JIT_PARTIAL_SOFT_COMPILE) - { - /* Update hit_start only in the first time. */ - jump = CMP(SLJIT_C_NOT_EQUAL, SLJIT_MEM1(SLJIT_SP), common->hit_start, SLJIT_IMM, 0); - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->start_used_ptr); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->start_used_ptr, SLJIT_IMM, -1); - OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), common->hit_start, TMP1, 0); - JUMPHERE(jump); - } - -/* Check we have remaining characters. */ -if ((re->options & PCRE_ANCHORED) == 0 && (re->options & PCRE_FIRSTLINE) != 0) - { - SLJIT_ASSERT(common->first_line_end != 0); - OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(SLJIT_SP), common->first_line_end); - } - -OP1(SLJIT_MOV, STR_PTR, 0, SLJIT_MEM1(SLJIT_SP), common->start_ptr); - -if ((re->options & PCRE_ANCHORED) == 0) - { - if (common->ff_newline_shortcut != NULL) - { - if ((re->options & PCRE_FIRSTLINE) == 0) - CMPTO(SLJIT_C_LESS, STR_PTR, 0, STR_END, 0, common->ff_newline_shortcut); - /* There cannot be more newlines here. */ - } - else - { - if ((re->options & PCRE_FIRSTLINE) == 0) - CMPTO(SLJIT_C_LESS, STR_PTR, 0, STR_END, 0, mainloop_label); - else - CMPTO(SLJIT_C_LESS, STR_PTR, 0, TMP1, 0, mainloop_label); - } - } - -/* No more remaining characters. */ -if (reqbyte_notfound != NULL) - JUMPHERE(reqbyte_notfound); - -if (mode == JIT_PARTIAL_SOFT_COMPILE) - CMPTO(SLJIT_C_NOT_EQUAL, SLJIT_MEM1(SLJIT_SP), common->hit_start, SLJIT_IMM, -1, common->partialmatchlabel); - -OP1(SLJIT_MOV, SLJIT_RETURN_REG, 0, SLJIT_IMM, PCRE_ERROR_NOMATCH); -JUMPTO(SLJIT_JUMP, common->quit_label); - -flush_stubs(common); - -if (common->might_be_empty) - { - JUMPHERE(empty_match); - OP1(SLJIT_MOV, TMP1, 0, ARGUMENTS, 0); - OP1(SLJIT_MOV_UB, TMP2, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, notempty)); - CMPTO(SLJIT_C_NOT_EQUAL, TMP2, 0, SLJIT_IMM, 0, empty_match_backtrack_label); - OP1(SLJIT_MOV_UB, TMP2, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, notempty_atstart)); - CMPTO(SLJIT_C_EQUAL, TMP2, 0, SLJIT_IMM, 0, empty_match_found_label); - OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, str)); - CMPTO(SLJIT_C_NOT_EQUAL, TMP2, 0, STR_PTR, 0, empty_match_found_label); - JUMPTO(SLJIT_JUMP, empty_match_backtrack_label); - } - -common->currententry = common->entries; -common->local_exit = TRUE; -quit_label = common->quit_label; -while (common->currententry != NULL) - { - /* Might add new entries. */ - compile_recurse(common); - if (SLJIT_UNLIKELY(sljit_get_compiler_error(compiler))) - { - sljit_free_compiler(compiler); - SLJIT_FREE(common->optimized_cbracket); - SLJIT_FREE(common->private_data_ptrs); - if (common->read_only_data) - SLJIT_FREE(common->read_only_data); - return; - } - flush_stubs(common); - common->currententry = common->currententry->next; - } -common->local_exit = FALSE; -common->quit_label = quit_label; - -/* Allocating stack, returns with PCRE_ERROR_JIT_STACKLIMIT if fails. */ -/* This is a (really) rare case. */ -set_jumps(common->stackalloc, LABEL()); -/* RETURN_ADDR is not a saved register. */ -sljit_emit_fast_enter(compiler, SLJIT_MEM1(SLJIT_SP), LOCALS0); -OP1(SLJIT_MOV, SLJIT_MEM1(SLJIT_SP), LOCALS1, TMP2, 0); -OP1(SLJIT_MOV, TMP1, 0, ARGUMENTS, 0); -OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, stack)); -OP1(SLJIT_MOV, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(struct sljit_stack, top), STACK_TOP, 0); -OP2(SLJIT_ADD, TMP2, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(struct sljit_stack, limit), SLJIT_IMM, STACK_GROWTH_RATE); - -sljit_emit_ijump(compiler, SLJIT_CALL2, SLJIT_IMM, SLJIT_FUNC_OFFSET(sljit_stack_resize)); -jump = CMP(SLJIT_C_NOT_EQUAL, SLJIT_RETURN_REG, 0, SLJIT_IMM, 0); -OP1(SLJIT_MOV, TMP1, 0, ARGUMENTS, 0); -OP1(SLJIT_MOV, TMP1, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(jit_arguments, stack)); -OP1(SLJIT_MOV, STACK_TOP, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(struct sljit_stack, top)); -OP1(SLJIT_MOV, STACK_LIMIT, 0, SLJIT_MEM1(TMP1), SLJIT_OFFSETOF(struct sljit_stack, limit)); -OP1(SLJIT_MOV, TMP2, 0, SLJIT_MEM1(SLJIT_SP), LOCALS1); -sljit_emit_fast_return(compiler, SLJIT_MEM1(SLJIT_SP), LOCALS0); - -/* Allocation failed. */ -JUMPHERE(jump); -/* We break the return address cache here, but this is a really rare case. */ -OP1(SLJIT_MOV, SLJIT_RETURN_REG, 0, SLJIT_IMM, PCRE_ERROR_JIT_STACKLIMIT); -JUMPTO(SLJIT_JUMP, common->quit_label); - -/* Call limit reached. */ -set_jumps(common->calllimit, LABEL()); -OP1(SLJIT_MOV, SLJIT_RETURN_REG, 0, SLJIT_IMM, PCRE_ERROR_MATCHLIMIT); -JUMPTO(SLJIT_JUMP, common->quit_label); - -if (common->revertframes != NULL) - { - set_jumps(common->revertframes, LABEL()); - do_revertframes(common); - } -if (common->wordboundary != NULL) - { - set_jumps(common->wordboundary, LABEL()); - check_wordboundary(common); - } -if (common->anynewline != NULL) - { - set_jumps(common->anynewline, LABEL()); - check_anynewline(common); - } -if (common->hspace != NULL) - { - set_jumps(common->hspace, LABEL()); - check_hspace(common); - } -if (common->vspace != NULL) - { - set_jumps(common->vspace, LABEL()); - check_vspace(common); - } -if (common->casefulcmp != NULL) - { - set_jumps(common->casefulcmp, LABEL()); - do_casefulcmp(common); - } -if (common->caselesscmp != NULL) - { - set_jumps(common->caselesscmp, LABEL()); - do_caselesscmp(common); - } -if (common->reset_match != NULL) - { - set_jumps(common->reset_match, LABEL()); - do_reset_match(common, (re->top_bracket + 1) * 2); - CMPTO(SLJIT_C_GREATER, STR_PTR, 0, TMP1, 0, continue_match_label); - OP1(SLJIT_MOV, STR_PTR, 0, TMP1, 0); - JUMPTO(SLJIT_JUMP, reset_match_label); - } -#ifdef SUPPORT_UTF -#ifdef COMPILE_PCRE8 -if (common->utfreadchar != NULL) - { - set_jumps(common->utfreadchar, LABEL()); - do_utfreadchar(common); - } -if (common->utfreadchar16 != NULL) - { - set_jumps(common->utfreadchar16, LABEL()); - do_utfreadchar16(common); - } -if (common->utfreadtype8 != NULL) - { - set_jumps(common->utfreadtype8, LABEL()); - do_utfreadtype8(common); - } -#endif /* COMPILE_PCRE8 */ -#endif /* SUPPORT_UTF */ -#ifdef SUPPORT_UCP -if (common->getucd != NULL) - { - set_jumps(common->getucd, LABEL()); - do_getucd(common); - } -#endif - -SLJIT_ASSERT(common->read_only_data + (common->read_only_data_size >> SLJIT_WORD_SHIFT) == common->read_only_data_ptr); -SLJIT_FREE(common->optimized_cbracket); -SLJIT_FREE(common->private_data_ptrs); - -executable_func = sljit_generate_code(compiler); -executable_size = sljit_get_generated_code_size(compiler); -label_addr = common->label_addrs; -while (label_addr != NULL) - { - *label_addr->update_addr = sljit_get_label_addr(label_addr->label); - label_addr = label_addr->next; - } -sljit_free_compiler(compiler); -if (executable_func == NULL) - { - if (common->read_only_data) - SLJIT_FREE(common->read_only_data); - return; - } - -/* Reuse the function descriptor if possible. */ -if ((extra->flags & PCRE_EXTRA_EXECUTABLE_JIT) != 0 && extra->executable_jit != NULL) - functions = (executable_functions *)extra->executable_jit; -else - { - /* Note: If your memory-checker has flagged the allocation below as a - * memory leak, it is probably because you either forgot to call - * pcre_free_study() (or pcre16_free_study()) on the pcre_extra (or - * pcre16_extra) object, or you called said function after having - * cleared the PCRE_EXTRA_EXECUTABLE_JIT bit from the "flags" field - * of the object. (The function will only free the JIT data if the - * bit remains set, as the bit indicates that the pointer to the data - * is valid.) - */ - functions = SLJIT_MALLOC(sizeof(executable_functions)); - if (functions == NULL) - { - /* This case is highly unlikely since we just recently - freed a lot of memory. Not impossible though. */ - sljit_free_code(executable_func); - if (common->read_only_data) - SLJIT_FREE(common->read_only_data); - return; - } - memset(functions, 0, sizeof(executable_functions)); - functions->top_bracket = (re->top_bracket + 1) * 2; - functions->limit_match = (re->flags & PCRE_MLSET) != 0 ? re->limit_match : 0; - extra->executable_jit = functions; - extra->flags |= PCRE_EXTRA_EXECUTABLE_JIT; - } - -functions->executable_funcs[mode] = executable_func; -functions->read_only_data[mode] = common->read_only_data; -functions->executable_sizes[mode] = executable_size; -} - -static int jit_machine_stack_exec(jit_arguments *arguments, void* executable_func) -{ -union { - void* executable_func; - jit_function call_executable_func; -} convert_executable_func; -pcre_uint8 local_space[MACHINE_STACK_SIZE]; -struct sljit_stack local_stack; - -local_stack.top = (sljit_sw)&local_space; -local_stack.base = local_stack.top; -local_stack.limit = local_stack.base + MACHINE_STACK_SIZE; -local_stack.max_limit = local_stack.limit; -arguments->stack = &local_stack; -convert_executable_func.executable_func = executable_func; -return convert_executable_func.call_executable_func(arguments); -} - -int -PRIV(jit_exec)(const PUBL(extra) *extra_data, const pcre_uchar *subject, - int length, int start_offset, int options, int *offsets, int offset_count) -{ -executable_functions *functions = (executable_functions *)extra_data->executable_jit; -union { - void* executable_func; - jit_function call_executable_func; -} convert_executable_func; -jit_arguments arguments; -int max_offset_count; -int retval; -int mode = JIT_COMPILE; - -if ((options & PCRE_PARTIAL_HARD) != 0) - mode = JIT_PARTIAL_HARD_COMPILE; -else if ((options & PCRE_PARTIAL_SOFT) != 0) - mode = JIT_PARTIAL_SOFT_COMPILE; - -if (functions->executable_funcs[mode] == NULL) - return PCRE_ERROR_JIT_BADOPTION; - -/* Sanity checks should be handled by pcre_exec. */ -arguments.str = subject + start_offset; -arguments.begin = subject; -arguments.end = subject + length; -arguments.mark_ptr = NULL; -/* JIT decreases this value less frequently than the interpreter. */ -arguments.limit_match = ((extra_data->flags & PCRE_EXTRA_MATCH_LIMIT) == 0) ? MATCH_LIMIT : (pcre_uint32)(extra_data->match_limit); -if (functions->limit_match != 0 && functions->limit_match < arguments.limit_match) - arguments.limit_match = functions->limit_match; -arguments.notbol = (options & PCRE_NOTBOL) != 0; -arguments.noteol = (options & PCRE_NOTEOL) != 0; -arguments.notempty = (options & PCRE_NOTEMPTY) != 0; -arguments.notempty_atstart = (options & PCRE_NOTEMPTY_ATSTART) != 0; -arguments.offsets = offsets; -arguments.callout_data = (extra_data->flags & PCRE_EXTRA_CALLOUT_DATA) != 0 ? extra_data->callout_data : NULL; -arguments.real_offset_count = offset_count; - -/* pcre_exec() rounds offset_count to a multiple of 3, and then uses only 2/3 of -the output vector for storing captured strings, with the remainder used as -workspace. We don't need the workspace here. For compatibility, we limit the -number of captured strings in the same way as pcre_exec(), so that the user -gets the same result with and without JIT. */ - -if (offset_count != 2) - offset_count = ((offset_count - (offset_count % 3)) * 2) / 3; -max_offset_count = functions->top_bracket; -if (offset_count > max_offset_count) - offset_count = max_offset_count; -arguments.offset_count = offset_count; - -if (functions->callback) - arguments.stack = (struct sljit_stack *)functions->callback(functions->userdata); -else - arguments.stack = (struct sljit_stack *)functions->userdata; - -if (arguments.stack == NULL) - retval = jit_machine_stack_exec(&arguments, functions->executable_funcs[mode]); -else - { - convert_executable_func.executable_func = functions->executable_funcs[mode]; - retval = convert_executable_func.call_executable_func(&arguments); - } - -if (retval * 2 > offset_count) - retval = 0; -if ((extra_data->flags & PCRE_EXTRA_MARK) != 0) - *(extra_data->mark) = arguments.mark_ptr; - -return retval; -} - -#if defined COMPILE_PCRE8 -PCRE_EXP_DEFN int PCRE_CALL_CONVENTION -pcre_jit_exec(const pcre *argument_re, const pcre_extra *extra_data, - PCRE_SPTR subject, int length, int start_offset, int options, - int *offsets, int offset_count, pcre_jit_stack *stack) -#elif defined COMPILE_PCRE16 -PCRE_EXP_DEFN int PCRE_CALL_CONVENTION -pcre16_jit_exec(const pcre16 *argument_re, const pcre16_extra *extra_data, - PCRE_SPTR16 subject, int length, int start_offset, int options, - int *offsets, int offset_count, pcre16_jit_stack *stack) -#elif defined COMPILE_PCRE32 -PCRE_EXP_DEFN int PCRE_CALL_CONVENTION -pcre32_jit_exec(const pcre32 *argument_re, const pcre32_extra *extra_data, - PCRE_SPTR32 subject, int length, int start_offset, int options, - int *offsets, int offset_count, pcre32_jit_stack *stack) -#endif -{ -pcre_uchar *subject_ptr = (pcre_uchar *)subject; -executable_functions *functions = (executable_functions *)extra_data->executable_jit; -union { - void* executable_func; - jit_function call_executable_func; -} convert_executable_func; -jit_arguments arguments; -int max_offset_count; -int retval; -int mode = JIT_COMPILE; - -SLJIT_UNUSED_ARG(argument_re); - -/* Plausibility checks */ -if ((options & ~PUBLIC_JIT_EXEC_OPTIONS) != 0) return PCRE_ERROR_JIT_BADOPTION; - -if ((options & PCRE_PARTIAL_HARD) != 0) - mode = JIT_PARTIAL_HARD_COMPILE; -else if ((options & PCRE_PARTIAL_SOFT) != 0) - mode = JIT_PARTIAL_SOFT_COMPILE; - -if (functions->executable_funcs[mode] == NULL) - return PCRE_ERROR_JIT_BADOPTION; - -/* Sanity checks should be handled by pcre_exec. */ -arguments.stack = (struct sljit_stack *)stack; -arguments.str = subject_ptr + start_offset; -arguments.begin = subject_ptr; -arguments.end = subject_ptr + length; -arguments.mark_ptr = NULL; -/* JIT decreases this value less frequently than the interpreter. */ -arguments.limit_match = ((extra_data->flags & PCRE_EXTRA_MATCH_LIMIT) == 0) ? MATCH_LIMIT : (pcre_uint32)(extra_data->match_limit); -if (functions->limit_match != 0 && functions->limit_match < arguments.limit_match) - arguments.limit_match = functions->limit_match; -arguments.notbol = (options & PCRE_NOTBOL) != 0; -arguments.noteol = (options & PCRE_NOTEOL) != 0; -arguments.notempty = (options & PCRE_NOTEMPTY) != 0; -arguments.notempty_atstart = (options & PCRE_NOTEMPTY_ATSTART) != 0; -arguments.offsets = offsets; -arguments.callout_data = (extra_data->flags & PCRE_EXTRA_CALLOUT_DATA) != 0 ? extra_data->callout_data : NULL; -arguments.real_offset_count = offset_count; - -/* pcre_exec() rounds offset_count to a multiple of 3, and then uses only 2/3 of -the output vector for storing captured strings, with the remainder used as -workspace. We don't need the workspace here. For compatibility, we limit the -number of captured strings in the same way as pcre_exec(), so that the user -gets the same result with and without JIT. */ - -if (offset_count != 2) - offset_count = ((offset_count - (offset_count % 3)) * 2) / 3; -max_offset_count = functions->top_bracket; -if (offset_count > max_offset_count) - offset_count = max_offset_count; -arguments.offset_count = offset_count; - -convert_executable_func.executable_func = functions->executable_funcs[mode]; -retval = convert_executable_func.call_executable_func(&arguments); - -if (retval * 2 > offset_count) - retval = 0; -if ((extra_data->flags & PCRE_EXTRA_MARK) != 0) - *(extra_data->mark) = arguments.mark_ptr; - -return retval; -} - -void -PRIV(jit_free)(void *executable_funcs) -{ -int i; -executable_functions *functions = (executable_functions *)executable_funcs; -for (i = 0; i < JIT_NUMBER_OF_COMPILE_MODES; i++) - { - if (functions->executable_funcs[i] != NULL) - sljit_free_code(functions->executable_funcs[i]); - if (functions->read_only_data[i] != NULL) - SLJIT_FREE(functions->read_only_data[i]); - } -SLJIT_FREE(functions); -} - -int -PRIV(jit_get_size)(void *executable_funcs) -{ -int i; -sljit_uw size = 0; -sljit_uw *executable_sizes = ((executable_functions *)executable_funcs)->executable_sizes; -for (i = 0; i < JIT_NUMBER_OF_COMPILE_MODES; i++) - size += executable_sizes[i]; -return (int)size; -} - -const char* -PRIV(jit_get_target)(void) -{ -return sljit_get_platform_name(); -} - -#if defined COMPILE_PCRE8 -PCRE_EXP_DECL pcre_jit_stack * -pcre_jit_stack_alloc(int startsize, int maxsize) -#elif defined COMPILE_PCRE16 -PCRE_EXP_DECL pcre16_jit_stack * -pcre16_jit_stack_alloc(int startsize, int maxsize) -#elif defined COMPILE_PCRE32 -PCRE_EXP_DECL pcre32_jit_stack * -pcre32_jit_stack_alloc(int startsize, int maxsize) -#endif -{ -if (startsize < 1 || maxsize < 1) - return NULL; -if (startsize > maxsize) - startsize = maxsize; -startsize = (startsize + STACK_GROWTH_RATE - 1) & ~(STACK_GROWTH_RATE - 1); -maxsize = (maxsize + STACK_GROWTH_RATE - 1) & ~(STACK_GROWTH_RATE - 1); -return (PUBL(jit_stack)*)sljit_allocate_stack(startsize, maxsize); -} - -#if defined COMPILE_PCRE8 -PCRE_EXP_DECL void -pcre_jit_stack_free(pcre_jit_stack *stack) -#elif defined COMPILE_PCRE16 -PCRE_EXP_DECL void -pcre16_jit_stack_free(pcre16_jit_stack *stack) -#elif defined COMPILE_PCRE32 -PCRE_EXP_DECL void -pcre32_jit_stack_free(pcre32_jit_stack *stack) -#endif -{ -sljit_free_stack((struct sljit_stack *)stack); -} - -#if defined COMPILE_PCRE8 -PCRE_EXP_DECL void -pcre_assign_jit_stack(pcre_extra *extra, pcre_jit_callback callback, void *userdata) -#elif defined COMPILE_PCRE16 -PCRE_EXP_DECL void -pcre16_assign_jit_stack(pcre16_extra *extra, pcre16_jit_callback callback, void *userdata) -#elif defined COMPILE_PCRE32 -PCRE_EXP_DECL void -pcre32_assign_jit_stack(pcre32_extra *extra, pcre32_jit_callback callback, void *userdata) -#endif -{ -executable_functions *functions; -if (extra != NULL && - (extra->flags & PCRE_EXTRA_EXECUTABLE_JIT) != 0 && - extra->executable_jit != NULL) - { - functions = (executable_functions *)extra->executable_jit; - functions->callback = callback; - functions->userdata = userdata; - } -} - -#if defined COMPILE_PCRE8 -PCRE_EXP_DECL void -pcre_jit_free_unused_memory(void) -#elif defined COMPILE_PCRE16 -PCRE_EXP_DECL void -pcre16_jit_free_unused_memory(void) -#elif defined COMPILE_PCRE32 -PCRE_EXP_DECL void -pcre32_jit_free_unused_memory(void) -#endif -{ -sljit_free_unused_memory_exec(); -} - -#else /* SUPPORT_JIT */ - -/* These are dummy functions to avoid linking errors when JIT support is not -being compiled. */ - -#if defined COMPILE_PCRE8 -PCRE_EXP_DECL pcre_jit_stack * -pcre_jit_stack_alloc(int startsize, int maxsize) -#elif defined COMPILE_PCRE16 -PCRE_EXP_DECL pcre16_jit_stack * -pcre16_jit_stack_alloc(int startsize, int maxsize) -#elif defined COMPILE_PCRE32 -PCRE_EXP_DECL pcre32_jit_stack * -pcre32_jit_stack_alloc(int startsize, int maxsize) -#endif -{ -(void)startsize; -(void)maxsize; -return NULL; -} - -#if defined COMPILE_PCRE8 -PCRE_EXP_DECL void -pcre_jit_stack_free(pcre_jit_stack *stack) -#elif defined COMPILE_PCRE16 -PCRE_EXP_DECL void -pcre16_jit_stack_free(pcre16_jit_stack *stack) -#elif defined COMPILE_PCRE32 -PCRE_EXP_DECL void -pcre32_jit_stack_free(pcre32_jit_stack *stack) -#endif -{ -(void)stack; -} - -#if defined COMPILE_PCRE8 -PCRE_EXP_DECL void -pcre_assign_jit_stack(pcre_extra *extra, pcre_jit_callback callback, void *userdata) -#elif defined COMPILE_PCRE16 -PCRE_EXP_DECL void -pcre16_assign_jit_stack(pcre16_extra *extra, pcre16_jit_callback callback, void *userdata) -#elif defined COMPILE_PCRE32 -PCRE_EXP_DECL void -pcre32_assign_jit_stack(pcre32_extra *extra, pcre32_jit_callback callback, void *userdata) -#endif -{ -(void)extra; -(void)callback; -(void)userdata; -} - -#if defined COMPILE_PCRE8 -PCRE_EXP_DECL void -pcre_jit_free_unused_memory(void) -#elif defined COMPILE_PCRE16 -PCRE_EXP_DECL void -pcre16_jit_free_unused_memory(void) -#elif defined COMPILE_PCRE32 -PCRE_EXP_DECL void -pcre32_jit_free_unused_memory(void) -#endif -{ -} - -#endif - -/* End of pcre_jit_compile.c */ diff --git a/lib/impure/nre/private/pcre_src/pcre_maketables.c b/lib/impure/nre/private/pcre_src/pcre_maketables.c deleted file mode 100644 index a44a6eaa9..000000000 --- a/lib/impure/nre/private/pcre_src/pcre_maketables.c +++ /dev/null @@ -1,156 +0,0 @@ -/************************************************* -* Perl-Compatible Regular Expressions * -*************************************************/ - -/* PCRE is a library of functions to support regular expressions whose syntax -and semantics are as close as possible to those of the Perl 5 language. - - Written by Philip Hazel - Copyright (c) 1997-2012 University of Cambridge - ------------------------------------------------------------------------------ -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - * Neither the name of the University of Cambridge nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ -*/ - - -/* This module contains the external function pcre_maketables(), which builds -character tables for PCRE in the current locale. The file is compiled on its -own as part of the PCRE library. However, it is also included in the -compilation of dftables.c, in which case the macro DFTABLES is defined. */ - - -#ifndef DFTABLES -# ifdef HAVE_CONFIG_H -# include "config.h" -# endif -# include "pcre_internal.h" -#endif - - -/************************************************* -* Create PCRE character tables * -*************************************************/ - -/* This function builds a set of character tables for use by PCRE and returns -a pointer to them. They are build using the ctype functions, and consequently -their contents will depend upon the current locale setting. When compiled as -part of the library, the store is obtained via PUBL(malloc)(), but when -compiled inside dftables, use malloc(). - -Arguments: none -Returns: pointer to the contiguous block of data -*/ - -#if defined COMPILE_PCRE8 -const unsigned char * -pcre_maketables(void) -#elif defined COMPILE_PCRE16 -const unsigned char * -pcre16_maketables(void) -#elif defined COMPILE_PCRE32 -const unsigned char * -pcre32_maketables(void) -#endif -{ -unsigned char *yield, *p; -int i; - -#ifndef DFTABLES -yield = (unsigned char*)(PUBL(malloc))(tables_length); -#else -yield = (unsigned char*)malloc(tables_length); -#endif - -if (yield == NULL) return NULL; -p = yield; - -/* First comes the lower casing table */ - -for (i = 0; i < 256; i++) *p++ = tolower(i); - -/* Next the case-flipping table */ - -for (i = 0; i < 256; i++) *p++ = islower(i)? toupper(i) : tolower(i); - -/* Then the character class tables. Don't try to be clever and save effort on -exclusive ones - in some locales things may be different. - -Note that the table for "space" includes everything "isspace" gives, including -VT in the default locale. This makes it work for the POSIX class [:space:]. -From release 8.34 is is also correct for Perl space, because Perl added VT at -release 5.18. - -Note also that it is possible for a character to be alnum or alpha without -being lower or upper, such as "male and female ordinals" (\xAA and \xBA) in the -fr_FR locale (at least under Debian Linux's locales as of 12/2005). So we must -test for alnum specially. */ - -memset(p, 0, cbit_length); -for (i = 0; i < 256; i++) - { - if (isdigit(i)) p[cbit_digit + i/8] |= 1 << (i&7); - if (isupper(i)) p[cbit_upper + i/8] |= 1 << (i&7); - if (islower(i)) p[cbit_lower + i/8] |= 1 << (i&7); - if (isalnum(i)) p[cbit_word + i/8] |= 1 << (i&7); - if (i == '_') p[cbit_word + i/8] |= 1 << (i&7); - if (isspace(i)) p[cbit_space + i/8] |= 1 << (i&7); - if (isxdigit(i))p[cbit_xdigit + i/8] |= 1 << (i&7); - if (isgraph(i)) p[cbit_graph + i/8] |= 1 << (i&7); - if (isprint(i)) p[cbit_print + i/8] |= 1 << (i&7); - if (ispunct(i)) p[cbit_punct + i/8] |= 1 << (i&7); - if (iscntrl(i)) p[cbit_cntrl + i/8] |= 1 << (i&7); - } -p += cbit_length; - -/* Finally, the character type table. In this, we used to exclude VT from the -white space chars, because Perl didn't recognize it as such for \s and for -comments within regexes. However, Perl changed at release 5.18, so PCRE changed -at release 8.34. */ - -for (i = 0; i < 256; i++) - { - int x = 0; - if (isspace(i)) x += ctype_space; - if (isalpha(i)) x += ctype_letter; - if (isdigit(i)) x += ctype_digit; - if (isxdigit(i)) x += ctype_xdigit; - if (isalnum(i) || i == '_') x += ctype_word; - - /* Note: strchr includes the terminating zero in the characters it considers. - In this instance, that is ok because we want binary zero to be flagged as a - meta-character, which in this sense is any character that terminates a run - of data characters. */ - - if (strchr("\\*+?{^.$|()[", i) != 0) x += ctype_meta; - *p++ = x; - } - -return yield; -} - -/* End of pcre_maketables.c */ diff --git a/lib/impure/nre/private/pcre_src/pcre_newline.c b/lib/impure/nre/private/pcre_src/pcre_newline.c deleted file mode 100644 index b8f5a4de1..000000000 --- a/lib/impure/nre/private/pcre_src/pcre_newline.c +++ /dev/null @@ -1,210 +0,0 @@ -/************************************************* -* Perl-Compatible Regular Expressions * -*************************************************/ - -/* PCRE is a library of functions to support regular expressions whose syntax -and semantics are as close as possible to those of the Perl 5 language. - - Written by Philip Hazel - Copyright (c) 1997-2012 University of Cambridge - ------------------------------------------------------------------------------ -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - * Neither the name of the University of Cambridge nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ -*/ - - -/* This module contains internal functions for testing newlines when more than -one kind of newline is to be recognized. When a newline is found, its length is -returned. In principle, we could implement several newline "types", each -referring to a different set of newline characters. At present, PCRE supports -only NLTYPE_FIXED, which gets handled without these functions, NLTYPE_ANYCRLF, -and NLTYPE_ANY. The full list of Unicode newline characters is taken from -http://unicode.org/unicode/reports/tr18/. */ - - -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - -#include "pcre_internal.h" - - - -/************************************************* -* Check for newline at given position * -*************************************************/ - -/* It is guaranteed that the initial value of ptr is less than the end of the -string that is being processed. - -Arguments: - ptr pointer to possible newline - type the newline type - endptr pointer to the end of the string - lenptr where to return the length - utf TRUE if in utf mode - -Returns: TRUE or FALSE -*/ - -BOOL -PRIV(is_newline)(PCRE_PUCHAR ptr, int type, PCRE_PUCHAR endptr, int *lenptr, - BOOL utf) -{ -pcre_uint32 c; -(void)utf; -#ifdef SUPPORT_UTF -if (utf) - { - GETCHAR(c, ptr); - } -else -#endif /* SUPPORT_UTF */ - c = *ptr; - -/* Note that this function is called only for ANY or ANYCRLF. */ - -if (type == NLTYPE_ANYCRLF) switch(c) - { - case CHAR_LF: *lenptr = 1; return TRUE; - case CHAR_CR: *lenptr = (ptr < endptr - 1 && ptr[1] == CHAR_LF)? 2 : 1; - return TRUE; - default: return FALSE; - } - -/* NLTYPE_ANY */ - -else switch(c) - { -#ifdef EBCDIC - case CHAR_NEL: -#endif - case CHAR_LF: - case CHAR_VT: - case CHAR_FF: *lenptr = 1; return TRUE; - - case CHAR_CR: - *lenptr = (ptr < endptr - 1 && ptr[1] == CHAR_LF)? 2 : 1; - return TRUE; - -#ifndef EBCDIC -#ifdef COMPILE_PCRE8 - case CHAR_NEL: *lenptr = utf? 2 : 1; return TRUE; - case 0x2028: /* LS */ - case 0x2029: *lenptr = 3; return TRUE; /* PS */ -#else /* COMPILE_PCRE16 || COMPILE_PCRE32 */ - case CHAR_NEL: - case 0x2028: /* LS */ - case 0x2029: *lenptr = 1; return TRUE; /* PS */ -#endif /* COMPILE_PCRE8 */ -#endif /* Not EBCDIC */ - - default: return FALSE; - } -} - - - -/************************************************* -* Check for newline at previous position * -*************************************************/ - -/* It is guaranteed that the initial value of ptr is greater than the start of -the string that is being processed. - -Arguments: - ptr pointer to possible newline - type the newline type - startptr pointer to the start of the string - lenptr where to return the length - utf TRUE if in utf mode - -Returns: TRUE or FALSE -*/ - -BOOL -PRIV(was_newline)(PCRE_PUCHAR ptr, int type, PCRE_PUCHAR startptr, int *lenptr, - BOOL utf) -{ -pcre_uint32 c; -(void)utf; -ptr--; -#ifdef SUPPORT_UTF -if (utf) - { - BACKCHAR(ptr); - GETCHAR(c, ptr); - } -else -#endif /* SUPPORT_UTF */ - c = *ptr; - -/* Note that this function is called only for ANY or ANYCRLF. */ - -if (type == NLTYPE_ANYCRLF) switch(c) - { - case CHAR_LF: - *lenptr = (ptr > startptr && ptr[-1] == CHAR_CR)? 2 : 1; - return TRUE; - - case CHAR_CR: *lenptr = 1; return TRUE; - default: return FALSE; - } - -/* NLTYPE_ANY */ - -else switch(c) - { - case CHAR_LF: - *lenptr = (ptr > startptr && ptr[-1] == CHAR_CR)? 2 : 1; - return TRUE; - -#ifdef EBCDIC - case CHAR_NEL: -#endif - case CHAR_VT: - case CHAR_FF: - case CHAR_CR: *lenptr = 1; return TRUE; - -#ifndef EBCDIC -#ifdef COMPILE_PCRE8 - case CHAR_NEL: *lenptr = utf? 2 : 1; return TRUE; - case 0x2028: /* LS */ - case 0x2029: *lenptr = 3; return TRUE; /* PS */ -#else /* COMPILE_PCRE16 || COMPILE_PCRE32 */ - case CHAR_NEL: - case 0x2028: /* LS */ - case 0x2029: *lenptr = 1; return TRUE; /* PS */ -#endif /* COMPILE_PCRE8 */ -#endif /* NotEBCDIC */ - - default: return FALSE; - } -} - -/* End of pcre_newline.c */ diff --git a/lib/impure/nre/private/pcre_src/pcre_ord2utf8.c b/lib/impure/nre/private/pcre_src/pcre_ord2utf8.c deleted file mode 100644 index 95f1beb96..000000000 --- a/lib/impure/nre/private/pcre_src/pcre_ord2utf8.c +++ /dev/null @@ -1,94 +0,0 @@ -/************************************************* -* Perl-Compatible Regular Expressions * -*************************************************/ - -/* PCRE is a library of functions to support regular expressions whose syntax -and semantics are as close as possible to those of the Perl 5 language. - - Written by Philip Hazel - Copyright (c) 1997-2012 University of Cambridge - ------------------------------------------------------------------------------ -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - * Neither the name of the University of Cambridge nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ -*/ - - -/* This file contains a private PCRE function that converts an ordinal -character value into a UTF8 string. */ - -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - -#define COMPILE_PCRE8 - -#include "pcre_internal.h" - -/************************************************* -* Convert character value to UTF-8 * -*************************************************/ - -/* This function takes an integer value in the range 0 - 0x10ffff -and encodes it as a UTF-8 character in 1 to 4 pcre_uchars. - -Arguments: - cvalue the character value - buffer pointer to buffer for result - at least 6 pcre_uchars long - -Returns: number of characters placed in the buffer -*/ - -unsigned -int -PRIV(ord2utf)(pcre_uint32 cvalue, pcre_uchar *buffer) -{ -#ifdef SUPPORT_UTF - -register int i, j; - -for (i = 0; i < PRIV(utf8_table1_size); i++) - if ((int)cvalue <= PRIV(utf8_table1)[i]) break; -buffer += i; -for (j = i; j > 0; j--) - { - *buffer-- = 0x80 | (cvalue & 0x3f); - cvalue >>= 6; - } -*buffer = PRIV(utf8_table2)[i] | cvalue; -return i + 1; - -#else - -(void)(cvalue); /* Keep compiler happy; this function won't ever be */ -(void)(buffer); /* called when SUPPORT_UTF is not defined. */ -return 0; - -#endif -} - -/* End of pcre_ord2utf8.c */ diff --git a/lib/impure/nre/private/pcre_src/pcre_refcount.c b/lib/impure/nre/private/pcre_src/pcre_refcount.c deleted file mode 100644 index 79efa90f2..000000000 --- a/lib/impure/nre/private/pcre_src/pcre_refcount.c +++ /dev/null @@ -1,92 +0,0 @@ -/************************************************* -* Perl-Compatible Regular Expressions * -*************************************************/ - -/* PCRE is a library of functions to support regular expressions whose syntax -and semantics are as close as possible to those of the Perl 5 language. - - Written by Philip Hazel - Copyright (c) 1997-2012 University of Cambridge - ------------------------------------------------------------------------------ -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - * Neither the name of the University of Cambridge nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ -*/ - - -/* This module contains the external function pcre_refcount(), which is an -auxiliary function that can be used to maintain a reference count in a compiled -pattern data block. This might be helpful in applications where the block is -shared by different users. */ - - -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - -#include "pcre_internal.h" - - -/************************************************* -* Maintain reference count * -*************************************************/ - -/* The reference count is a 16-bit field, initialized to zero. It is not -possible to transfer a non-zero count from one host to a different host that -has a different byte order - though I can't see why anyone in their right mind -would ever want to do that! - -Arguments: - argument_re points to compiled code - adjust value to add to the count - -Returns: the (possibly updated) count value (a non-negative number), or - a negative error number -*/ - -#if defined COMPILE_PCRE8 -PCRE_EXP_DEFN int PCRE_CALL_CONVENTION -pcre_refcount(pcre *argument_re, int adjust) -#elif defined COMPILE_PCRE16 -PCRE_EXP_DEFN int PCRE_CALL_CONVENTION -pcre16_refcount(pcre16 *argument_re, int adjust) -#elif defined COMPILE_PCRE32 -PCRE_EXP_DEFN int PCRE_CALL_CONVENTION -pcre32_refcount(pcre32 *argument_re, int adjust) -#endif -{ -REAL_PCRE *re = (REAL_PCRE *)argument_re; -if (re == NULL) return PCRE_ERROR_NULL; -if (re->magic_number != MAGIC_NUMBER) return PCRE_ERROR_BADMAGIC; -if ((re->flags & PCRE_MODE) == 0) return PCRE_ERROR_BADMODE; -re->ref_count = (-adjust > re->ref_count)? 0 : - (adjust + re->ref_count > 65535)? 65535 : - re->ref_count + adjust; -return re->ref_count; -} - -/* End of pcre_refcount.c */ diff --git a/lib/impure/nre/private/pcre_src/pcre_string_utils.c b/lib/impure/nre/private/pcre_src/pcre_string_utils.c deleted file mode 100644 index 25eacc850..000000000 --- a/lib/impure/nre/private/pcre_src/pcre_string_utils.c +++ /dev/null @@ -1,211 +0,0 @@ -/************************************************* -* Perl-Compatible Regular Expressions * -*************************************************/ - -/* PCRE is a library of functions to support regular expressions whose syntax -and semantics are as close as possible to those of the Perl 5 language. - - Written by Philip Hazel - Copyright (c) 1997-2014 University of Cambridge - ------------------------------------------------------------------------------ -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - * Neither the name of the University of Cambridge nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ -*/ - - -/* This module contains internal functions for comparing and finding the length -of strings for different data item sizes. */ - - -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - -#include "pcre_internal.h" - -#ifndef COMPILE_PCRE8 - -/************************************************* -* Compare string utilities * -*************************************************/ - -/* The following two functions compares two strings. Basically a strcmp -for non 8 bit characters. - -Arguments: - str1 first string - str2 second string - -Returns: 0 if both string are equal (like strcmp), 1 otherwise -*/ - -int -PRIV(strcmp_uc_uc)(const pcre_uchar *str1, const pcre_uchar *str2) -{ -pcre_uchar c1; -pcre_uchar c2; - -while (*str1 != '\0' || *str2 != '\0') - { - c1 = *str1++; - c2 = *str2++; - if (c1 != c2) - return ((c1 > c2) << 1) - 1; - } -/* Both length and characters must be equal. */ -return 0; -} - -#ifdef COMPILE_PCRE32 - -int -PRIV(strcmp_uc_uc_utf)(const pcre_uchar *str1, const pcre_uchar *str2) -{ -pcre_uchar c1; -pcre_uchar c2; - -while (*str1 != '\0' || *str2 != '\0') - { - c1 = UCHAR21INC(str1); - c2 = UCHAR21INC(str2); - if (c1 != c2) - return ((c1 > c2) << 1) - 1; - } -/* Both length and characters must be equal. */ -return 0; -} - -#endif /* COMPILE_PCRE32 */ - -int -PRIV(strcmp_uc_c8)(const pcre_uchar *str1, const char *str2) -{ -const pcre_uint8 *ustr2 = (pcre_uint8 *)str2; -pcre_uchar c1; -pcre_uchar c2; - -while (*str1 != '\0' || *ustr2 != '\0') - { - c1 = *str1++; - c2 = (pcre_uchar)*ustr2++; - if (c1 != c2) - return ((c1 > c2) << 1) - 1; - } -/* Both length and characters must be equal. */ -return 0; -} - -#ifdef COMPILE_PCRE32 - -int -PRIV(strcmp_uc_c8_utf)(const pcre_uchar *str1, const char *str2) -{ -const pcre_uint8 *ustr2 = (pcre_uint8 *)str2; -pcre_uchar c1; -pcre_uchar c2; - -while (*str1 != '\0' || *ustr2 != '\0') - { - c1 = UCHAR21INC(str1); - c2 = (pcre_uchar)*ustr2++; - if (c1 != c2) - return ((c1 > c2) << 1) - 1; - } -/* Both length and characters must be equal. */ -return 0; -} - -#endif /* COMPILE_PCRE32 */ - -/* The following two functions compares two, fixed length -strings. Basically an strncmp for non 8 bit characters. - -Arguments: - str1 first string - str2 second string - num size of the string - -Returns: 0 if both string are equal (like strcmp), 1 otherwise -*/ - -int -PRIV(strncmp_uc_uc)(const pcre_uchar *str1, const pcre_uchar *str2, unsigned int num) -{ -pcre_uchar c1; -pcre_uchar c2; - -while (num-- > 0) - { - c1 = *str1++; - c2 = *str2++; - if (c1 != c2) - return ((c1 > c2) << 1) - 1; - } -/* Both length and characters must be equal. */ -return 0; -} - -int -PRIV(strncmp_uc_c8)(const pcre_uchar *str1, const char *str2, unsigned int num) -{ -const pcre_uint8 *ustr2 = (pcre_uint8 *)str2; -pcre_uchar c1; -pcre_uchar c2; - -while (num-- > 0) - { - c1 = *str1++; - c2 = (pcre_uchar)*ustr2++; - if (c1 != c2) - return ((c1 > c2) << 1) - 1; - } -/* Both length and characters must be equal. */ -return 0; -} - -/* The following function returns with the length of -a zero terminated string. Basically an strlen for non 8 bit characters. - -Arguments: - str string - -Returns: length of the string -*/ - -unsigned int -PRIV(strlen_uc)(const pcre_uchar *str) -{ -unsigned int len = 0; -while (*str++ != 0) - len++; -return len; -} - -#endif /* !COMPILE_PCRE8 */ - -/* End of pcre_string_utils.c */ diff --git a/lib/impure/nre/private/pcre_src/pcre_study.c b/lib/impure/nre/private/pcre_src/pcre_study.c deleted file mode 100644 index f19d9fbb9..000000000 --- a/lib/impure/nre/private/pcre_src/pcre_study.c +++ /dev/null @@ -1,1643 +0,0 @@ -/************************************************* -* Perl-Compatible Regular Expressions * -*************************************************/ - -/* PCRE is a library of functions to support regular expressions whose syntax -and semantics are as close as possible to those of the Perl 5 language. - - Written by Philip Hazel - Copyright (c) 1997-2012 University of Cambridge - ------------------------------------------------------------------------------ -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - * Neither the name of the University of Cambridge nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ -*/ - - -/* This module contains the external function pcre_study(), along with local -supporting functions. */ - - -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - -#include "pcre_internal.h" - -#define SET_BIT(c) start_bits[c/8] |= (1 << (c&7)) - -/* Returns from set_start_bits() */ - -enum { SSB_FAIL, SSB_DONE, SSB_CONTINUE, SSB_UNKNOWN }; - - - -/************************************************* -* Find the minimum subject length for a group * -*************************************************/ - -/* Scan a parenthesized group and compute the minimum length of subject that -is needed to match it. This is a lower bound; it does not mean there is a -string of that length that matches. In UTF8 mode, the result is in characters -rather than bytes. - -Arguments: - re compiled pattern block - code pointer to start of group (the bracket) - startcode pointer to start of the whole pattern's code - options the compiling options - int RECURSE depth - -Returns: the minimum length - -1 if \C in UTF-8 mode or (*ACCEPT) was encountered - -2 internal error (missing capturing bracket) - -3 internal error (opcode not listed) -*/ - -static int -find_minlength(const REAL_PCRE *re, const pcre_uchar *code, - const pcre_uchar *startcode, int options, int recurse_depth) -{ -int length = -1; -/* PCRE_UTF16 has the same value as PCRE_UTF8. */ -BOOL utf = (options & PCRE_UTF8) != 0; -BOOL had_recurse = FALSE; -register int branchlength = 0; -register pcre_uchar *cc = (pcre_uchar *)code + 1 + LINK_SIZE; - -if (*code == OP_CBRA || *code == OP_SCBRA || - *code == OP_CBRAPOS || *code == OP_SCBRAPOS) cc += IMM2_SIZE; - -/* Scan along the opcodes for this branch. If we get to the end of the -branch, check the length against that of the other branches. */ - -for (;;) - { - int d, min; - pcre_uchar *cs, *ce; - register pcre_uchar op = *cc; - - switch (op) - { - case OP_COND: - case OP_SCOND: - - /* If there is only one branch in a condition, the implied branch has zero - length, so we don't add anything. This covers the DEFINE "condition" - automatically. */ - - cs = cc + GET(cc, 1); - if (*cs != OP_ALT) - { - cc = cs + 1 + LINK_SIZE; - break; - } - - /* Otherwise we can fall through and treat it the same as any other - subpattern. */ - - case OP_CBRA: - case OP_SCBRA: - case OP_BRA: - case OP_SBRA: - case OP_CBRAPOS: - case OP_SCBRAPOS: - case OP_BRAPOS: - case OP_SBRAPOS: - case OP_ONCE: - case OP_ONCE_NC: - d = find_minlength(re, cc, startcode, options, recurse_depth); - if (d < 0) return d; - branchlength += d; - do cc += GET(cc, 1); while (*cc == OP_ALT); - cc += 1 + LINK_SIZE; - break; - - /* ACCEPT makes things far too complicated; we have to give up. */ - - case OP_ACCEPT: - case OP_ASSERT_ACCEPT: - return -1; - - /* Reached end of a branch; if it's a ket it is the end of a nested - call. If it's ALT it is an alternation in a nested call. If it is END it's - the end of the outer call. All can be handled by the same code. If an - ACCEPT was previously encountered, use the length that was in force at that - time, and pass back the shortest ACCEPT length. */ - - case OP_ALT: - case OP_KET: - case OP_KETRMAX: - case OP_KETRMIN: - case OP_KETRPOS: - case OP_END: - if (length < 0 || (!had_recurse && branchlength < length)) - length = branchlength; - if (op != OP_ALT) return length; - cc += 1 + LINK_SIZE; - branchlength = 0; - had_recurse = FALSE; - break; - - /* Skip over assertive subpatterns */ - - case OP_ASSERT: - case OP_ASSERT_NOT: - case OP_ASSERTBACK: - case OP_ASSERTBACK_NOT: - do cc += GET(cc, 1); while (*cc == OP_ALT); - /* Fall through */ - - /* Skip over things that don't match chars */ - - case OP_REVERSE: - case OP_CREF: - case OP_DNCREF: - case OP_RREF: - case OP_DNRREF: - case OP_DEF: - case OP_CALLOUT: - case OP_SOD: - case OP_SOM: - case OP_EOD: - case OP_EODN: - case OP_CIRC: - case OP_CIRCM: - case OP_DOLL: - case OP_DOLLM: - case OP_NOT_WORD_BOUNDARY: - case OP_WORD_BOUNDARY: - cc += PRIV(OP_lengths)[*cc]; - break; - - /* Skip over a subpattern that has a {0} or {0,x} quantifier */ - - case OP_BRAZERO: - case OP_BRAMINZERO: - case OP_BRAPOSZERO: - case OP_SKIPZERO: - cc += PRIV(OP_lengths)[*cc]; - do cc += GET(cc, 1); while (*cc == OP_ALT); - cc += 1 + LINK_SIZE; - break; - - /* Handle literal characters and + repetitions */ - - case OP_CHAR: - case OP_CHARI: - case OP_NOT: - case OP_NOTI: - case OP_PLUS: - case OP_PLUSI: - case OP_MINPLUS: - case OP_MINPLUSI: - case OP_POSPLUS: - case OP_POSPLUSI: - case OP_NOTPLUS: - case OP_NOTPLUSI: - case OP_NOTMINPLUS: - case OP_NOTMINPLUSI: - case OP_NOTPOSPLUS: - case OP_NOTPOSPLUSI: - branchlength++; - cc += 2; -#ifdef SUPPORT_UTF - if (utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]); -#endif - break; - - case OP_TYPEPLUS: - case OP_TYPEMINPLUS: - case OP_TYPEPOSPLUS: - branchlength++; - cc += (cc[1] == OP_PROP || cc[1] == OP_NOTPROP)? 4 : 2; - break; - - /* Handle exact repetitions. The count is already in characters, but we - need to skip over a multibyte character in UTF8 mode. */ - - case OP_EXACT: - case OP_EXACTI: - case OP_NOTEXACT: - case OP_NOTEXACTI: - branchlength += GET2(cc,1); - cc += 2 + IMM2_SIZE; -#ifdef SUPPORT_UTF - if (utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]); -#endif - break; - - case OP_TYPEEXACT: - branchlength += GET2(cc,1); - cc += 2 + IMM2_SIZE + ((cc[1 + IMM2_SIZE] == OP_PROP - || cc[1 + IMM2_SIZE] == OP_NOTPROP)? 2 : 0); - break; - - /* Handle single-char non-literal matchers */ - - case OP_PROP: - case OP_NOTPROP: - cc += 2; - /* Fall through */ - - case OP_NOT_DIGIT: - case OP_DIGIT: - case OP_NOT_WHITESPACE: - case OP_WHITESPACE: - case OP_NOT_WORDCHAR: - case OP_WORDCHAR: - case OP_ANY: - case OP_ALLANY: - case OP_EXTUNI: - case OP_HSPACE: - case OP_NOT_HSPACE: - case OP_VSPACE: - case OP_NOT_VSPACE: - branchlength++; - cc++; - break; - - /* "Any newline" might match two characters, but it also might match just - one. */ - - case OP_ANYNL: - branchlength += 1; - cc++; - break; - - /* The single-byte matcher means we can't proceed in UTF-8 mode. (In - non-UTF-8 mode \C will actually be turned into OP_ALLANY, so won't ever - appear, but leave the code, just in case.) */ - - case OP_ANYBYTE: -#ifdef SUPPORT_UTF - if (utf) return -1; -#endif - branchlength++; - cc++; - break; - - /* For repeated character types, we have to test for \p and \P, which have - an extra two bytes of parameters. */ - - case OP_TYPESTAR: - case OP_TYPEMINSTAR: - case OP_TYPEQUERY: - case OP_TYPEMINQUERY: - case OP_TYPEPOSSTAR: - case OP_TYPEPOSQUERY: - if (cc[1] == OP_PROP || cc[1] == OP_NOTPROP) cc += 2; - cc += PRIV(OP_lengths)[op]; - break; - - case OP_TYPEUPTO: - case OP_TYPEMINUPTO: - case OP_TYPEPOSUPTO: - if (cc[1 + IMM2_SIZE] == OP_PROP - || cc[1 + IMM2_SIZE] == OP_NOTPROP) cc += 2; - cc += PRIV(OP_lengths)[op]; - break; - - /* Check a class for variable quantification */ - - case OP_CLASS: - case OP_NCLASS: -#if defined SUPPORT_UTF || defined COMPILE_PCRE16 || defined COMPILE_PCRE32 - case OP_XCLASS: - /* The original code caused an unsigned overflow in 64 bit systems, - so now we use a conditional statement. */ - if (op == OP_XCLASS) - cc += GET(cc, 1); - else - cc += PRIV(OP_lengths)[OP_CLASS]; -#else - cc += PRIV(OP_lengths)[OP_CLASS]; -#endif - - switch (*cc) - { - case OP_CRPLUS: - case OP_CRMINPLUS: - case OP_CRPOSPLUS: - branchlength++; - /* Fall through */ - - case OP_CRSTAR: - case OP_CRMINSTAR: - case OP_CRQUERY: - case OP_CRMINQUERY: - case OP_CRPOSSTAR: - case OP_CRPOSQUERY: - cc++; - break; - - case OP_CRRANGE: - case OP_CRMINRANGE: - case OP_CRPOSRANGE: - branchlength += GET2(cc,1); - cc += 1 + 2 * IMM2_SIZE; - break; - - default: - branchlength++; - break; - } - break; - - /* Backreferences and subroutine calls are treated in the same way: we find - the minimum length for the subpattern. A recursion, however, causes an - a flag to be set that causes the length of this branch to be ignored. The - logic is that a recursion can only make sense if there is another - alternation that stops the recursing. That will provide the minimum length - (when no recursion happens). A backreference within the group that it is - referencing behaves in the same way. - - If PCRE_JAVASCRIPT_COMPAT is set, a backreference to an unset bracket - matches an empty string (by default it causes a matching failure), so in - that case we must set the minimum length to zero. */ - - case OP_DNREF: /* Duplicate named pattern back reference */ - case OP_DNREFI: - if ((options & PCRE_JAVASCRIPT_COMPAT) == 0) - { - int count = GET2(cc, 1+IMM2_SIZE); - pcre_uchar *slot = (pcre_uchar *)re + - re->name_table_offset + GET2(cc, 1) * re->name_entry_size; - d = INT_MAX; - while (count-- > 0) - { - ce = cs = (pcre_uchar *)PRIV(find_bracket)(startcode, utf, GET2(slot, 0)); - if (cs == NULL) return -2; - do ce += GET(ce, 1); while (*ce == OP_ALT); - if (cc > cs && cc < ce) - { - d = 0; - had_recurse = TRUE; - break; - } - else - { - int dd = find_minlength(re, cs, startcode, options, recurse_depth); - if (dd < d) d = dd; - } - slot += re->name_entry_size; - } - } - else d = 0; - cc += 1 + 2*IMM2_SIZE; - goto REPEAT_BACK_REFERENCE; - - case OP_REF: /* Single back reference */ - case OP_REFI: - if ((options & PCRE_JAVASCRIPT_COMPAT) == 0) - { - ce = cs = (pcre_uchar *)PRIV(find_bracket)(startcode, utf, GET2(cc, 1)); - if (cs == NULL) return -2; - do ce += GET(ce, 1); while (*ce == OP_ALT); - if (cc > cs && cc < ce) - { - d = 0; - had_recurse = TRUE; - } - else - { - d = find_minlength(re, cs, startcode, options, recurse_depth); - } - } - else d = 0; - cc += 1 + IMM2_SIZE; - - /* Handle repeated back references */ - - REPEAT_BACK_REFERENCE: - switch (*cc) - { - case OP_CRSTAR: - case OP_CRMINSTAR: - case OP_CRQUERY: - case OP_CRMINQUERY: - case OP_CRPOSSTAR: - case OP_CRPOSQUERY: - min = 0; - cc++; - break; - - case OP_CRPLUS: - case OP_CRMINPLUS: - case OP_CRPOSPLUS: - min = 1; - cc++; - break; - - case OP_CRRANGE: - case OP_CRMINRANGE: - case OP_CRPOSRANGE: - min = GET2(cc, 1); - cc += 1 + 2 * IMM2_SIZE; - break; - - default: - min = 1; - break; - } - - branchlength += min * d; - break; - - /* We can easily detect direct recursion, but not mutual recursion. This is - caught by a recursion depth count. */ - - case OP_RECURSE: - cs = ce = (pcre_uchar *)startcode + GET(cc, 1); - do ce += GET(ce, 1); while (*ce == OP_ALT); - if ((cc > cs && cc < ce) || recurse_depth > 10) - had_recurse = TRUE; - else - { - branchlength += find_minlength(re, cs, startcode, options, - recurse_depth + 1); - } - cc += 1 + LINK_SIZE; - break; - - /* Anything else does not or need not match a character. We can get the - item's length from the table, but for those that can match zero occurrences - of a character, we must take special action for UTF-8 characters. As it - happens, the "NOT" versions of these opcodes are used at present only for - ASCII characters, so they could be omitted from this list. However, in - future that may change, so we include them here so as not to leave a - gotcha for a future maintainer. */ - - case OP_UPTO: - case OP_UPTOI: - case OP_NOTUPTO: - case OP_NOTUPTOI: - case OP_MINUPTO: - case OP_MINUPTOI: - case OP_NOTMINUPTO: - case OP_NOTMINUPTOI: - case OP_POSUPTO: - case OP_POSUPTOI: - case OP_NOTPOSUPTO: - case OP_NOTPOSUPTOI: - - case OP_STAR: - case OP_STARI: - case OP_NOTSTAR: - case OP_NOTSTARI: - case OP_MINSTAR: - case OP_MINSTARI: - case OP_NOTMINSTAR: - case OP_NOTMINSTARI: - case OP_POSSTAR: - case OP_POSSTARI: - case OP_NOTPOSSTAR: - case OP_NOTPOSSTARI: - - case OP_QUERY: - case OP_QUERYI: - case OP_NOTQUERY: - case OP_NOTQUERYI: - case OP_MINQUERY: - case OP_MINQUERYI: - case OP_NOTMINQUERY: - case OP_NOTMINQUERYI: - case OP_POSQUERY: - case OP_POSQUERYI: - case OP_NOTPOSQUERY: - case OP_NOTPOSQUERYI: - - cc += PRIV(OP_lengths)[op]; -#ifdef SUPPORT_UTF - if (utf && HAS_EXTRALEN(cc[-1])) cc += GET_EXTRALEN(cc[-1]); -#endif - break; - - /* Skip these, but we need to add in the name length. */ - - case OP_MARK: - case OP_PRUNE_ARG: - case OP_SKIP_ARG: - case OP_THEN_ARG: - cc += PRIV(OP_lengths)[op] + cc[1]; - break; - - /* The remaining opcodes are just skipped over. */ - - case OP_CLOSE: - case OP_COMMIT: - case OP_FAIL: - case OP_PRUNE: - case OP_SET_SOM: - case OP_SKIP: - case OP_THEN: - cc += PRIV(OP_lengths)[op]; - break; - - /* This should not occur: we list all opcodes explicitly so that when - new ones get added they are properly considered. */ - - default: - return -3; - } - } -/* Control never gets here */ -} - - - -/************************************************* -* Set a bit and maybe its alternate case * -*************************************************/ - -/* Given a character, set its first byte's bit in the table, and also the -corresponding bit for the other version of a letter if we are caseless. In -UTF-8 mode, for characters greater than 127, we can only do the caseless thing -when Unicode property support is available. - -Arguments: - start_bits points to the bit map - p points to the character - caseless the caseless flag - cd the block with char table pointers - utf TRUE for UTF-8 / UTF-16 / UTF-32 mode - -Returns: pointer after the character -*/ - -static const pcre_uchar * -set_table_bit(pcre_uint8 *start_bits, const pcre_uchar *p, BOOL caseless, - compile_data *cd, BOOL utf) -{ -pcre_uint32 c = *p; - -#ifdef COMPILE_PCRE8 -SET_BIT(c); - -#ifdef SUPPORT_UTF -if (utf && c > 127) - { - GETCHARINC(c, p); -#ifdef SUPPORT_UCP - if (caseless) - { - pcre_uchar buff[6]; - c = UCD_OTHERCASE(c); - (void)PRIV(ord2utf)(c, buff); - SET_BIT(buff[0]); - } -#endif /* Not SUPPORT_UCP */ - return p; - } -#else /* Not SUPPORT_UTF */ -(void)(utf); /* Stops warning for unused parameter */ -#endif /* SUPPORT_UTF */ - -/* Not UTF-8 mode, or character is less than 127. */ - -if (caseless && (cd->ctypes[c] & ctype_letter) != 0) SET_BIT(cd->fcc[c]); -return p + 1; -#endif /* COMPILE_PCRE8 */ - -#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 -if (c > 0xff) - { - c = 0xff; - caseless = FALSE; - } -SET_BIT(c); - -#ifdef SUPPORT_UTF -if (utf && c > 127) - { - GETCHARINC(c, p); -#ifdef SUPPORT_UCP - if (caseless) - { - c = UCD_OTHERCASE(c); - if (c > 0xff) - c = 0xff; - SET_BIT(c); - } -#endif /* SUPPORT_UCP */ - return p; - } -#else /* Not SUPPORT_UTF */ -(void)(utf); /* Stops warning for unused parameter */ -#endif /* SUPPORT_UTF */ - -if (caseless && (cd->ctypes[c] & ctype_letter) != 0) SET_BIT(cd->fcc[c]); -return p + 1; -#endif -} - - - -/************************************************* -* Set bits for a positive character type * -*************************************************/ - -/* This function sets starting bits for a character type. In UTF-8 mode, we can -only do a direct setting for bytes less than 128, as otherwise there can be -confusion with bytes in the middle of UTF-8 characters. In a "traditional" -environment, the tables will only recognize ASCII characters anyway, but in at -least one Windows environment, some higher bytes bits were set in the tables. -So we deal with that case by considering the UTF-8 encoding. - -Arguments: - start_bits the starting bitmap - cbit type the type of character wanted - table_limit 32 for non-UTF-8; 16 for UTF-8 - cd the block with char table pointers - -Returns: nothing -*/ - -static void -set_type_bits(pcre_uint8 *start_bits, int cbit_type, unsigned int table_limit, - compile_data *cd) -{ -register pcre_uint32 c; -for (c = 0; c < table_limit; c++) start_bits[c] |= cd->cbits[c+cbit_type]; -#if defined SUPPORT_UTF && defined COMPILE_PCRE8 -if (table_limit == 32) return; -for (c = 128; c < 256; c++) - { - if ((cd->cbits[c/8] & (1 << (c&7))) != 0) - { - pcre_uchar buff[6]; - (void)PRIV(ord2utf)(c, buff); - SET_BIT(buff[0]); - } - } -#endif -} - - -/************************************************* -* Set bits for a negative character type * -*************************************************/ - -/* This function sets starting bits for a negative character type such as \D. -In UTF-8 mode, we can only do a direct setting for bytes less than 128, as -otherwise there can be confusion with bytes in the middle of UTF-8 characters. -Unlike in the positive case, where we can set appropriate starting bits for -specific high-valued UTF-8 characters, in this case we have to set the bits for -all high-valued characters. The lowest is 0xc2, but we overkill by starting at -0xc0 (192) for simplicity. - -Arguments: - start_bits the starting bitmap - cbit type the type of character wanted - table_limit 32 for non-UTF-8; 16 for UTF-8 - cd the block with char table pointers - -Returns: nothing -*/ - -static void -set_nottype_bits(pcre_uint8 *start_bits, int cbit_type, unsigned int table_limit, - compile_data *cd) -{ -register pcre_uint32 c; -for (c = 0; c < table_limit; c++) start_bits[c] |= ~cd->cbits[c+cbit_type]; -#if defined SUPPORT_UTF && defined COMPILE_PCRE8 -if (table_limit != 32) for (c = 24; c < 32; c++) start_bits[c] = 0xff; -#endif -} - - - -/************************************************* -* Create bitmap of starting bytes * -*************************************************/ - -/* This function scans a compiled unanchored expression recursively and -attempts to build a bitmap of the set of possible starting bytes. As time goes -by, we may be able to get more clever at doing this. The SSB_CONTINUE return is -useful for parenthesized groups in patterns such as (a*)b where the group -provides some optional starting bytes but scanning must continue at the outer -level to find at least one mandatory byte. At the outermost level, this -function fails unless the result is SSB_DONE. - -Arguments: - code points to an expression - start_bits points to a 32-byte table, initialized to 0 - utf TRUE if in UTF-8 / UTF-16 / UTF-32 mode - cd the block with char table pointers - -Returns: SSB_FAIL => Failed to find any starting bytes - SSB_DONE => Found mandatory starting bytes - SSB_CONTINUE => Found optional starting bytes - SSB_UNKNOWN => Hit an unrecognized opcode -*/ - -static int -set_start_bits(const pcre_uchar *code, pcre_uint8 *start_bits, BOOL utf, - compile_data *cd) -{ -register pcre_uint32 c; -int yield = SSB_DONE; -#if defined SUPPORT_UTF && defined COMPILE_PCRE8 -int table_limit = utf? 16:32; -#else -int table_limit = 32; -#endif - -#if 0 -/* ========================================================================= */ -/* The following comment and code was inserted in January 1999. In May 2006, -when it was observed to cause compiler warnings about unused values, I took it -out again. If anybody is still using OS/2, they will have to put it back -manually. */ - -/* This next statement and the later reference to dummy are here in order to -trick the optimizer of the IBM C compiler for OS/2 into generating correct -code. Apparently IBM isn't going to fix the problem, and we would rather not -disable optimization (in this module it actually makes a big difference, and -the pcre module can use all the optimization it can get). */ - -volatile int dummy; -/* ========================================================================= */ -#endif - -do - { - BOOL try_next = TRUE; - const pcre_uchar *tcode = code + 1 + LINK_SIZE; - - if (*code == OP_CBRA || *code == OP_SCBRA || - *code == OP_CBRAPOS || *code == OP_SCBRAPOS) tcode += IMM2_SIZE; - - while (try_next) /* Loop for items in this branch */ - { - int rc; - - switch(*tcode) - { - /* If we reach something we don't understand, it means a new opcode has - been created that hasn't been added to this code. Hopefully this problem - will be discovered during testing. */ - - default: - return SSB_UNKNOWN; - - /* Fail for a valid opcode that implies no starting bits. */ - - case OP_ACCEPT: - case OP_ASSERT_ACCEPT: - case OP_ALLANY: - case OP_ANY: - case OP_ANYBYTE: - case OP_CIRC: - case OP_CIRCM: - case OP_CLOSE: - case OP_COMMIT: - case OP_COND: - case OP_CREF: - case OP_DEF: - case OP_DNCREF: - case OP_DNREF: - case OP_DNREFI: - case OP_DNRREF: - case OP_DOLL: - case OP_DOLLM: - case OP_END: - case OP_EOD: - case OP_EODN: - case OP_EXTUNI: - case OP_FAIL: - case OP_MARK: - case OP_NOT: - case OP_NOTEXACT: - case OP_NOTEXACTI: - case OP_NOTI: - case OP_NOTMINPLUS: - case OP_NOTMINPLUSI: - case OP_NOTMINQUERY: - case OP_NOTMINQUERYI: - case OP_NOTMINSTAR: - case OP_NOTMINSTARI: - case OP_NOTMINUPTO: - case OP_NOTMINUPTOI: - case OP_NOTPLUS: - case OP_NOTPLUSI: - case OP_NOTPOSPLUS: - case OP_NOTPOSPLUSI: - case OP_NOTPOSQUERY: - case OP_NOTPOSQUERYI: - case OP_NOTPOSSTAR: - case OP_NOTPOSSTARI: - case OP_NOTPOSUPTO: - case OP_NOTPOSUPTOI: - case OP_NOTPROP: - case OP_NOTQUERY: - case OP_NOTQUERYI: - case OP_NOTSTAR: - case OP_NOTSTARI: - case OP_NOTUPTO: - case OP_NOTUPTOI: - case OP_NOT_HSPACE: - case OP_NOT_VSPACE: - case OP_PRUNE: - case OP_PRUNE_ARG: - case OP_RECURSE: - case OP_REF: - case OP_REFI: - case OP_REVERSE: - case OP_RREF: - case OP_SCOND: - case OP_SET_SOM: - case OP_SKIP: - case OP_SKIP_ARG: - case OP_SOD: - case OP_SOM: - case OP_THEN: - case OP_THEN_ARG: - return SSB_FAIL; - - /* A "real" property test implies no starting bits, but the fake property - PT_CLIST identifies a list of characters. These lists are short, as they - are used for characters with more than one "other case", so there is no - point in recognizing them for OP_NOTPROP. */ - - case OP_PROP: - if (tcode[1] != PT_CLIST) return SSB_FAIL; - { - const pcre_uint32 *p = PRIV(ucd_caseless_sets) + tcode[2]; - while ((c = *p++) < NOTACHAR) - { -#if defined SUPPORT_UTF && defined COMPILE_PCRE8 - if (utf) - { - pcre_uchar buff[6]; - (void)PRIV(ord2utf)(c, buff); - c = buff[0]; - } -#endif - if (c > 0xff) SET_BIT(0xff); else SET_BIT(c); - } - } - try_next = FALSE; - break; - - /* We can ignore word boundary tests. */ - - case OP_WORD_BOUNDARY: - case OP_NOT_WORD_BOUNDARY: - tcode++; - break; - - /* If we hit a bracket or a positive lookahead assertion, recurse to set - bits from within the subpattern. If it can't find anything, we have to - give up. If it finds some mandatory character(s), we are done for this - branch. Otherwise, carry on scanning after the subpattern. */ - - case OP_BRA: - case OP_SBRA: - case OP_CBRA: - case OP_SCBRA: - case OP_BRAPOS: - case OP_SBRAPOS: - case OP_CBRAPOS: - case OP_SCBRAPOS: - case OP_ONCE: - case OP_ONCE_NC: - case OP_ASSERT: - rc = set_start_bits(tcode, start_bits, utf, cd); - if (rc == SSB_FAIL || rc == SSB_UNKNOWN) return rc; - if (rc == SSB_DONE) try_next = FALSE; else - { - do tcode += GET(tcode, 1); while (*tcode == OP_ALT); - tcode += 1 + LINK_SIZE; - } - break; - - /* If we hit ALT or KET, it means we haven't found anything mandatory in - this branch, though we might have found something optional. For ALT, we - continue with the next alternative, but we have to arrange that the final - result from subpattern is SSB_CONTINUE rather than SSB_DONE. For KET, - return SSB_CONTINUE: if this is the top level, that indicates failure, - but after a nested subpattern, it causes scanning to continue. */ - - case OP_ALT: - yield = SSB_CONTINUE; - try_next = FALSE; - break; - - case OP_KET: - case OP_KETRMAX: - case OP_KETRMIN: - case OP_KETRPOS: - return SSB_CONTINUE; - - /* Skip over callout */ - - case OP_CALLOUT: - tcode += 2 + 2*LINK_SIZE; - break; - - /* Skip over lookbehind and negative lookahead assertions */ - - case OP_ASSERT_NOT: - case OP_ASSERTBACK: - case OP_ASSERTBACK_NOT: - do tcode += GET(tcode, 1); while (*tcode == OP_ALT); - tcode += 1 + LINK_SIZE; - break; - - /* BRAZERO does the bracket, but carries on. */ - - case OP_BRAZERO: - case OP_BRAMINZERO: - case OP_BRAPOSZERO: - rc = set_start_bits(++tcode, start_bits, utf, cd); - if (rc == SSB_FAIL || rc == SSB_UNKNOWN) return rc; -/* ========================================================================= - See the comment at the head of this function concerning the next line, - which was an old fudge for the benefit of OS/2. - dummy = 1; - ========================================================================= */ - do tcode += GET(tcode,1); while (*tcode == OP_ALT); - tcode += 1 + LINK_SIZE; - break; - - /* SKIPZERO skips the bracket. */ - - case OP_SKIPZERO: - tcode++; - do tcode += GET(tcode,1); while (*tcode == OP_ALT); - tcode += 1 + LINK_SIZE; - break; - - /* Single-char * or ? sets the bit and tries the next item */ - - case OP_STAR: - case OP_MINSTAR: - case OP_POSSTAR: - case OP_QUERY: - case OP_MINQUERY: - case OP_POSQUERY: - tcode = set_table_bit(start_bits, tcode + 1, FALSE, cd, utf); - break; - - case OP_STARI: - case OP_MINSTARI: - case OP_POSSTARI: - case OP_QUERYI: - case OP_MINQUERYI: - case OP_POSQUERYI: - tcode = set_table_bit(start_bits, tcode + 1, TRUE, cd, utf); - break; - - /* Single-char upto sets the bit and tries the next */ - - case OP_UPTO: - case OP_MINUPTO: - case OP_POSUPTO: - tcode = set_table_bit(start_bits, tcode + 1 + IMM2_SIZE, FALSE, cd, utf); - break; - - case OP_UPTOI: - case OP_MINUPTOI: - case OP_POSUPTOI: - tcode = set_table_bit(start_bits, tcode + 1 + IMM2_SIZE, TRUE, cd, utf); - break; - - /* At least one single char sets the bit and stops */ - - case OP_EXACT: - tcode += IMM2_SIZE; - /* Fall through */ - case OP_CHAR: - case OP_PLUS: - case OP_MINPLUS: - case OP_POSPLUS: - (void)set_table_bit(start_bits, tcode + 1, FALSE, cd, utf); - try_next = FALSE; - break; - - case OP_EXACTI: - tcode += IMM2_SIZE; - /* Fall through */ - case OP_CHARI: - case OP_PLUSI: - case OP_MINPLUSI: - case OP_POSPLUSI: - (void)set_table_bit(start_bits, tcode + 1, TRUE, cd, utf); - try_next = FALSE; - break; - - /* Special spacing and line-terminating items. These recognize specific - lists of characters. The difference between VSPACE and ANYNL is that the - latter can match the two-character CRLF sequence, but that is not - relevant for finding the first character, so their code here is - identical. */ - - case OP_HSPACE: - SET_BIT(CHAR_HT); - SET_BIT(CHAR_SPACE); -#ifdef SUPPORT_UTF - if (utf) - { -#ifdef COMPILE_PCRE8 - SET_BIT(0xC2); /* For U+00A0 */ - SET_BIT(0xE1); /* For U+1680, U+180E */ - SET_BIT(0xE2); /* For U+2000 - U+200A, U+202F, U+205F */ - SET_BIT(0xE3); /* For U+3000 */ -#elif defined COMPILE_PCRE16 || defined COMPILE_PCRE32 - SET_BIT(0xA0); - SET_BIT(0xFF); /* For characters > 255 */ -#endif /* COMPILE_PCRE[8|16|32] */ - } - else -#endif /* SUPPORT_UTF */ - { -#ifndef EBCDIC - SET_BIT(0xA0); -#endif /* Not EBCDIC */ -#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 - SET_BIT(0xFF); /* For characters > 255 */ -#endif /* COMPILE_PCRE[16|32] */ - } - try_next = FALSE; - break; - - case OP_ANYNL: - case OP_VSPACE: - SET_BIT(CHAR_LF); - SET_BIT(CHAR_VT); - SET_BIT(CHAR_FF); - SET_BIT(CHAR_CR); -#ifdef SUPPORT_UTF - if (utf) - { -#ifdef COMPILE_PCRE8 - SET_BIT(0xC2); /* For U+0085 */ - SET_BIT(0xE2); /* For U+2028, U+2029 */ -#elif defined COMPILE_PCRE16 || defined COMPILE_PCRE32 - SET_BIT(CHAR_NEL); - SET_BIT(0xFF); /* For characters > 255 */ -#endif /* COMPILE_PCRE[8|16|32] */ - } - else -#endif /* SUPPORT_UTF */ - { - SET_BIT(CHAR_NEL); -#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 - SET_BIT(0xFF); /* For characters > 255 */ -#endif - } - try_next = FALSE; - break; - - /* Single character types set the bits and stop. Note that if PCRE_UCP - is set, we do not see these op codes because \d etc are converted to - properties. Therefore, these apply in the case when only characters less - than 256 are recognized to match the types. */ - - case OP_NOT_DIGIT: - set_nottype_bits(start_bits, cbit_digit, table_limit, cd); - try_next = FALSE; - break; - - case OP_DIGIT: - set_type_bits(start_bits, cbit_digit, table_limit, cd); - try_next = FALSE; - break; - - /* The cbit_space table has vertical tab as whitespace; we no longer - have to play fancy tricks because Perl added VT to its whitespace at - release 5.18. PCRE added it at release 8.34. */ - - case OP_NOT_WHITESPACE: - set_nottype_bits(start_bits, cbit_space, table_limit, cd); - try_next = FALSE; - break; - - case OP_WHITESPACE: - set_type_bits(start_bits, cbit_space, table_limit, cd); - try_next = FALSE; - break; - - case OP_NOT_WORDCHAR: - set_nottype_bits(start_bits, cbit_word, table_limit, cd); - try_next = FALSE; - break; - - case OP_WORDCHAR: - set_type_bits(start_bits, cbit_word, table_limit, cd); - try_next = FALSE; - break; - - /* One or more character type fudges the pointer and restarts, knowing - it will hit a single character type and stop there. */ - - case OP_TYPEPLUS: - case OP_TYPEMINPLUS: - case OP_TYPEPOSPLUS: - tcode++; - break; - - case OP_TYPEEXACT: - tcode += 1 + IMM2_SIZE; - break; - - /* Zero or more repeats of character types set the bits and then - try again. */ - - case OP_TYPEUPTO: - case OP_TYPEMINUPTO: - case OP_TYPEPOSUPTO: - tcode += IMM2_SIZE; /* Fall through */ - - case OP_TYPESTAR: - case OP_TYPEMINSTAR: - case OP_TYPEPOSSTAR: - case OP_TYPEQUERY: - case OP_TYPEMINQUERY: - case OP_TYPEPOSQUERY: - switch(tcode[1]) - { - default: - case OP_ANY: - case OP_ALLANY: - return SSB_FAIL; - - case OP_HSPACE: - SET_BIT(CHAR_HT); - SET_BIT(CHAR_SPACE); -#ifdef SUPPORT_UTF - if (utf) - { -#ifdef COMPILE_PCRE8 - SET_BIT(0xC2); /* For U+00A0 */ - SET_BIT(0xE1); /* For U+1680, U+180E */ - SET_BIT(0xE2); /* For U+2000 - U+200A, U+202F, U+205F */ - SET_BIT(0xE3); /* For U+3000 */ -#elif defined COMPILE_PCRE16 || defined COMPILE_PCRE32 - SET_BIT(0xA0); - SET_BIT(0xFF); /* For characters > 255 */ -#endif /* COMPILE_PCRE[8|16|32] */ - } - else -#endif /* SUPPORT_UTF */ -#ifndef EBCDIC - SET_BIT(0xA0); -#endif /* Not EBCDIC */ - break; - - case OP_ANYNL: - case OP_VSPACE: - SET_BIT(CHAR_LF); - SET_BIT(CHAR_VT); - SET_BIT(CHAR_FF); - SET_BIT(CHAR_CR); -#ifdef SUPPORT_UTF - if (utf) - { -#ifdef COMPILE_PCRE8 - SET_BIT(0xC2); /* For U+0085 */ - SET_BIT(0xE2); /* For U+2028, U+2029 */ -#elif defined COMPILE_PCRE16 || defined COMPILE_PCRE32 - SET_BIT(CHAR_NEL); - SET_BIT(0xFF); /* For characters > 255 */ -#endif /* COMPILE_PCRE16 */ - } - else -#endif /* SUPPORT_UTF */ - SET_BIT(CHAR_NEL); - break; - - case OP_NOT_DIGIT: - set_nottype_bits(start_bits, cbit_digit, table_limit, cd); - break; - - case OP_DIGIT: - set_type_bits(start_bits, cbit_digit, table_limit, cd); - break; - - /* The cbit_space table has vertical tab as whitespace; we no longer - have to play fancy tricks because Perl added VT to its whitespace at - release 5.18. PCRE added it at release 8.34. */ - - case OP_NOT_WHITESPACE: - set_nottype_bits(start_bits, cbit_space, table_limit, cd); - break; - - case OP_WHITESPACE: - set_type_bits(start_bits, cbit_space, table_limit, cd); - break; - - case OP_NOT_WORDCHAR: - set_nottype_bits(start_bits, cbit_word, table_limit, cd); - break; - - case OP_WORDCHAR: - set_type_bits(start_bits, cbit_word, table_limit, cd); - break; - } - - tcode += 2; - break; - - /* Character class where all the information is in a bit map: set the - bits and either carry on or not, according to the repeat count. If it was - a negative class, and we are operating with UTF-8 characters, any byte - with a value >= 0xc4 is a potentially valid starter because it starts a - character with a value > 255. */ - -#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 - case OP_XCLASS: - if ((tcode[1 + LINK_SIZE] & XCL_HASPROP) != 0) - return SSB_FAIL; - /* All bits are set. */ - if ((tcode[1 + LINK_SIZE] & XCL_MAP) == 0 && (tcode[1 + LINK_SIZE] & XCL_NOT) != 0) - return SSB_FAIL; -#endif - /* Fall through */ - - case OP_NCLASS: -#if defined SUPPORT_UTF && defined COMPILE_PCRE8 - if (utf) - { - start_bits[24] |= 0xf0; /* Bits for 0xc4 - 0xc8 */ - memset(start_bits+25, 0xff, 7); /* Bits for 0xc9 - 0xff */ - } -#endif -#if defined COMPILE_PCRE16 || defined COMPILE_PCRE32 - SET_BIT(0xFF); /* For characters > 255 */ -#endif - /* Fall through */ - - case OP_CLASS: - { - pcre_uint8 *map; -#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 - map = NULL; - if (*tcode == OP_XCLASS) - { - if ((tcode[1 + LINK_SIZE] & XCL_MAP) != 0) - map = (pcre_uint8 *)(tcode + 1 + LINK_SIZE + 1); - tcode += GET(tcode, 1); - } - else -#endif - { - tcode++; - map = (pcre_uint8 *)tcode; - tcode += 32 / sizeof(pcre_uchar); - } - - /* In UTF-8 mode, the bits in a bit map correspond to character - values, not to byte values. However, the bit map we are constructing is - for byte values. So we have to do a conversion for characters whose - value is > 127. In fact, there are only two possible starting bytes for - characters in the range 128 - 255. */ - -#if defined SUPPORT_UTF || !defined COMPILE_PCRE8 - if (map != NULL) -#endif - { -#if defined SUPPORT_UTF && defined COMPILE_PCRE8 - if (utf) - { - for (c = 0; c < 16; c++) start_bits[c] |= map[c]; - for (c = 128; c < 256; c++) - { - if ((map[c/8] && (1 << (c&7))) != 0) - { - int d = (c >> 6) | 0xc0; /* Set bit for this starter */ - start_bits[d/8] |= (1 << (d&7)); /* and then skip on to the */ - c = (c & 0xc0) + 0x40 - 1; /* next relevant character. */ - } - } - } - else -#endif - { - /* In non-UTF-8 mode, the two bit maps are completely compatible. */ - for (c = 0; c < 32; c++) start_bits[c] |= map[c]; - } - } - - /* Advance past the bit map, and act on what follows. For a zero - minimum repeat, continue; otherwise stop processing. */ - - switch (*tcode) - { - case OP_CRSTAR: - case OP_CRMINSTAR: - case OP_CRQUERY: - case OP_CRMINQUERY: - case OP_CRPOSSTAR: - case OP_CRPOSQUERY: - tcode++; - break; - - case OP_CRRANGE: - case OP_CRMINRANGE: - case OP_CRPOSRANGE: - if (GET2(tcode, 1) == 0) tcode += 1 + 2 * IMM2_SIZE; - else try_next = FALSE; - break; - - default: - try_next = FALSE; - break; - } - } - break; /* End of bitmap class handling */ - - } /* End of switch */ - } /* End of try_next loop */ - - code += GET(code, 1); /* Advance to next branch */ - } -while (*code == OP_ALT); -return yield; -} - - - - - -/************************************************* -* Study a compiled expression * -*************************************************/ - -/* This function is handed a compiled expression that it must study to produce -information that will speed up the matching. It returns a pcre[16]_extra block -which then gets handed back to pcre_exec(). - -Arguments: - re points to the compiled expression - options contains option bits - errorptr points to where to place error messages; - set NULL unless error - -Returns: pointer to a pcre[16]_extra block, with study_data filled in and - the appropriate flags set; - NULL on error or if no optimization possible -*/ - -#if defined COMPILE_PCRE8 -PCRE_EXP_DEFN pcre_extra * PCRE_CALL_CONVENTION -pcre_study(const pcre *external_re, int options, const char **errorptr) -#elif defined COMPILE_PCRE16 -PCRE_EXP_DEFN pcre16_extra * PCRE_CALL_CONVENTION -pcre16_study(const pcre16 *external_re, int options, const char **errorptr) -#elif defined COMPILE_PCRE32 -PCRE_EXP_DEFN pcre32_extra * PCRE_CALL_CONVENTION -pcre32_study(const pcre32 *external_re, int options, const char **errorptr) -#endif -{ -int min; -BOOL bits_set = FALSE; -pcre_uint8 start_bits[32]; -PUBL(extra) *extra = NULL; -pcre_study_data *study; -const pcre_uint8 *tables; -pcre_uchar *code; -compile_data compile_block; -const REAL_PCRE *re = (const REAL_PCRE *)external_re; - - -*errorptr = NULL; - -if (re == NULL || re->magic_number != MAGIC_NUMBER) - { - *errorptr = "argument is not a compiled regular expression"; - return NULL; - } - -if ((re->flags & PCRE_MODE) == 0) - { -#if defined COMPILE_PCRE8 - *errorptr = "argument not compiled in 8 bit mode"; -#elif defined COMPILE_PCRE16 - *errorptr = "argument not compiled in 16 bit mode"; -#elif defined COMPILE_PCRE32 - *errorptr = "argument not compiled in 32 bit mode"; -#endif - return NULL; - } - -if ((options & ~PUBLIC_STUDY_OPTIONS) != 0) - { - *errorptr = "unknown or incorrect option bit(s) set"; - return NULL; - } - -code = (pcre_uchar *)re + re->name_table_offset + - (re->name_count * re->name_entry_size); - -/* For an anchored pattern, or an unanchored pattern that has a first char, or -a multiline pattern that matches only at "line starts", there is no point in -seeking a list of starting bytes. */ - -if ((re->options & PCRE_ANCHORED) == 0 && - (re->flags & (PCRE_FIRSTSET|PCRE_STARTLINE)) == 0) - { - int rc; - - /* Set the character tables in the block that is passed around */ - - tables = re->tables; - -#if defined COMPILE_PCRE8 - if (tables == NULL) - (void)pcre_fullinfo(external_re, NULL, PCRE_INFO_DEFAULT_TABLES, - (void *)(&tables)); -#elif defined COMPILE_PCRE16 - if (tables == NULL) - (void)pcre16_fullinfo(external_re, NULL, PCRE_INFO_DEFAULT_TABLES, - (void *)(&tables)); -#elif defined COMPILE_PCRE32 - if (tables == NULL) - (void)pcre32_fullinfo(external_re, NULL, PCRE_INFO_DEFAULT_TABLES, - (void *)(&tables)); -#endif - - compile_block.lcc = tables + lcc_offset; - compile_block.fcc = tables + fcc_offset; - compile_block.cbits = tables + cbits_offset; - compile_block.ctypes = tables + ctypes_offset; - - /* See if we can find a fixed set of initial characters for the pattern. */ - - memset(start_bits, 0, 32 * sizeof(pcre_uint8)); - rc = set_start_bits(code, start_bits, (re->options & PCRE_UTF8) != 0, - &compile_block); - bits_set = rc == SSB_DONE; - if (rc == SSB_UNKNOWN) - { - *errorptr = "internal error: opcode not recognized"; - return NULL; - } - } - -/* Find the minimum length of subject string. */ - -switch(min = find_minlength(re, code, code, re->options, 0)) - { - case -2: *errorptr = "internal error: missing capturing bracket"; return NULL; - case -3: *errorptr = "internal error: opcode not recognized"; return NULL; - default: break; - } - -/* If a set of starting bytes has been identified, or if the minimum length is -greater than zero, or if JIT optimization has been requested, or if -PCRE_STUDY_EXTRA_NEEDED is set, get a pcre[16]_extra block and a -pcre_study_data block. The study data is put in the latter, which is pointed to -by the former, which may also get additional data set later by the calling -program. At the moment, the size of pcre_study_data is fixed. We nevertheless -save it in a field for returning via the pcre_fullinfo() function so that if it -becomes variable in the future, we don't have to change that code. */ - -if (bits_set || min > 0 || (options & ( -#ifdef SUPPORT_JIT - PCRE_STUDY_JIT_COMPILE | PCRE_STUDY_JIT_PARTIAL_SOFT_COMPILE | - PCRE_STUDY_JIT_PARTIAL_HARD_COMPILE | -#endif - PCRE_STUDY_EXTRA_NEEDED)) != 0) - { - extra = (PUBL(extra) *)(PUBL(malloc)) - (sizeof(PUBL(extra)) + sizeof(pcre_study_data)); - if (extra == NULL) - { - *errorptr = "failed to get memory"; - return NULL; - } - - study = (pcre_study_data *)((char *)extra + sizeof(PUBL(extra))); - extra->flags = PCRE_EXTRA_STUDY_DATA; - extra->study_data = study; - - study->size = sizeof(pcre_study_data); - study->flags = 0; - - /* Set the start bits always, to avoid unset memory errors if the - study data is written to a file, but set the flag only if any of the bits - are set, to save time looking when none are. */ - - if (bits_set) - { - study->flags |= PCRE_STUDY_MAPPED; - memcpy(study->start_bits, start_bits, sizeof(start_bits)); - } - else memset(study->start_bits, 0, 32 * sizeof(pcre_uint8)); - -#ifdef PCRE_DEBUG - if (bits_set) - { - pcre_uint8 *ptr = start_bits; - int i; - - printf("Start bits:\n"); - for (i = 0; i < 32; i++) - printf("%3d: %02x%s", i * 8, *ptr++, ((i + 1) & 0x7) != 0? " " : "\n"); - } -#endif - - /* Always set the minlength value in the block, because the JIT compiler - makes use of it. However, don't set the bit unless the length is greater than - zero - the interpretive pcre_exec() and pcre_dfa_exec() needn't waste time - checking the zero case. */ - - if (min > 0) - { - study->flags |= PCRE_STUDY_MINLEN; - study->minlength = min; - } - else study->minlength = 0; - - /* If JIT support was compiled and requested, attempt the JIT compilation. - If no starting bytes were found, and the minimum length is zero, and JIT - compilation fails, abandon the extra block and return NULL, unless - PCRE_STUDY_EXTRA_NEEDED is set. */ - -#ifdef SUPPORT_JIT - extra->executable_jit = NULL; - if ((options & PCRE_STUDY_JIT_COMPILE) != 0) - PRIV(jit_compile)(re, extra, JIT_COMPILE); - if ((options & PCRE_STUDY_JIT_PARTIAL_SOFT_COMPILE) != 0) - PRIV(jit_compile)(re, extra, JIT_PARTIAL_SOFT_COMPILE); - if ((options & PCRE_STUDY_JIT_PARTIAL_HARD_COMPILE) != 0) - PRIV(jit_compile)(re, extra, JIT_PARTIAL_HARD_COMPILE); - - if (study->flags == 0 && (extra->flags & PCRE_EXTRA_EXECUTABLE_JIT) == 0 && - (options & PCRE_STUDY_EXTRA_NEEDED) == 0) - { -#if defined COMPILE_PCRE8 - pcre_free_study(extra); -#elif defined COMPILE_PCRE16 - pcre16_free_study(extra); -#elif defined COMPILE_PCRE32 - pcre32_free_study(extra); -#endif - extra = NULL; - } -#endif - } - -return extra; -} - - -/************************************************* -* Free the study data * -*************************************************/ - -/* This function frees the memory that was obtained by pcre_study(). - -Argument: a pointer to the pcre[16]_extra block -Returns: nothing -*/ - -#if defined COMPILE_PCRE8 -PCRE_EXP_DEFN void -pcre_free_study(pcre_extra *extra) -#elif defined COMPILE_PCRE16 -PCRE_EXP_DEFN void -pcre16_free_study(pcre16_extra *extra) -#elif defined COMPILE_PCRE32 -PCRE_EXP_DEFN void -pcre32_free_study(pcre32_extra *extra) -#endif -{ -if (extra == NULL) - return; -#ifdef SUPPORT_JIT -if ((extra->flags & PCRE_EXTRA_EXECUTABLE_JIT) != 0 && - extra->executable_jit != NULL) - PRIV(jit_free)(extra->executable_jit); -#endif -PUBL(free)(extra); -} - -/* End of pcre_study.c */ diff --git a/lib/impure/nre/private/pcre_src/pcre_tables.c b/lib/impure/nre/private/pcre_src/pcre_tables.c deleted file mode 100644 index 4960af57c..000000000 --- a/lib/impure/nre/private/pcre_src/pcre_tables.c +++ /dev/null @@ -1,727 +0,0 @@ -/************************************************* -* Perl-Compatible Regular Expressions * -*************************************************/ - -/* PCRE is a library of functions to support regular expressions whose syntax -and semantics are as close as possible to those of the Perl 5 language. - - Written by Philip Hazel - Copyright (c) 1997-2012 University of Cambridge - ------------------------------------------------------------------------------ -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - * Neither the name of the University of Cambridge nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ -*/ - -#ifndef PCRE_INCLUDED - -/* This module contains some fixed tables that are used by more than one of the -PCRE code modules. The tables are also #included by the pcretest program, which -uses macros to change their names from _pcre_xxx to xxxx, thereby avoiding name -clashes with the library. */ - - -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - -#include "pcre_internal.h" - -#endif /* PCRE_INCLUDED */ - -/* Table of sizes for the fixed-length opcodes. It's defined in a macro so that -the definition is next to the definition of the opcodes in pcre_internal.h. */ - -const pcre_uint8 PRIV(OP_lengths)[] = { OP_LENGTHS }; - -/* Tables of horizontal and vertical whitespace characters, suitable for -adding to classes. */ - -const pcre_uint32 PRIV(hspace_list)[] = { HSPACE_LIST }; -const pcre_uint32 PRIV(vspace_list)[] = { VSPACE_LIST }; - - - -/************************************************* -* Tables for UTF-8 support * -*************************************************/ - -/* These are the breakpoints for different numbers of bytes in a UTF-8 -character. */ - -#if (defined SUPPORT_UTF && defined COMPILE_PCRE8) \ - || (defined PCRE_INCLUDED && (defined SUPPORT_PCRE16 || defined SUPPORT_PCRE32)) - -/* These tables are also required by pcretest in 16- or 32-bit mode. */ - -const int PRIV(utf8_table1)[] = - { 0x7f, 0x7ff, 0xffff, 0x1fffff, 0x3ffffff, 0x7fffffff}; - -const int PRIV(utf8_table1_size) = sizeof(PRIV(utf8_table1)) / sizeof(int); - -/* These are the indicator bits and the mask for the data bits to set in the -first byte of a character, indexed by the number of additional bytes. */ - -const int PRIV(utf8_table2)[] = { 0, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc}; -const int PRIV(utf8_table3)[] = { 0xff, 0x1f, 0x0f, 0x07, 0x03, 0x01}; - -/* Table of the number of extra bytes, indexed by the first byte masked with -0x3f. The highest number for a valid UTF-8 first byte is in fact 0x3d. */ - -const pcre_uint8 PRIV(utf8_table4)[] = { - 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, - 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, - 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, - 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5 }; - -#endif /* (SUPPORT_UTF && COMPILE_PCRE8) || (PCRE_INCLUDED && SUPPORT_PCRE[16|32])*/ - -#ifdef SUPPORT_UTF - -/* Table to translate from particular type value to the general value. */ - -const pcre_uint32 PRIV(ucp_gentype)[] = { - ucp_C, ucp_C, ucp_C, ucp_C, ucp_C, /* Cc, Cf, Cn, Co, Cs */ - ucp_L, ucp_L, ucp_L, ucp_L, ucp_L, /* Ll, Lu, Lm, Lo, Lt */ - ucp_M, ucp_M, ucp_M, /* Mc, Me, Mn */ - ucp_N, ucp_N, ucp_N, /* Nd, Nl, No */ - ucp_P, ucp_P, ucp_P, ucp_P, ucp_P, /* Pc, Pd, Pe, Pf, Pi */ - ucp_P, ucp_P, /* Ps, Po */ - ucp_S, ucp_S, ucp_S, ucp_S, /* Sc, Sk, Sm, So */ - ucp_Z, ucp_Z, ucp_Z /* Zl, Zp, Zs */ -}; - -/* This table encodes the rules for finding the end of an extended grapheme -cluster. Every code point has a grapheme break property which is one of the -ucp_gbXX values defined in ucp.h. The 2-dimensional table is indexed by the -properties of two adjacent code points. The left property selects a word from -the table, and the right property selects a bit from that word like this: - - ucp_gbtable[left-property] & (1 << right-property) - -The value is non-zero if a grapheme break is NOT permitted between the relevant -two code points. The breaking rules are as follows: - -1. Break at the start and end of text (pretty obviously). - -2. Do not break between a CR and LF; otherwise, break before and after - controls. - -3. Do not break Hangul syllable sequences, the rules for which are: - - L may be followed by L, V, LV or LVT - LV or V may be followed by V or T - LVT or T may be followed by T - -4. Do not break before extending characters. - -The next two rules are only for extended grapheme clusters (but that's what we -are implementing). - -5. Do not break before SpacingMarks. - -6. Do not break after Prepend characters. - -7. Otherwise, break everywhere. -*/ - -const pcre_uint32 PRIV(ucp_gbtable[]) = { - (1< 0x10ffff is not permitted -PCRE_UTF8_ERR14 3-byte character with value 0xd000-0xdfff is not permitted -PCRE_UTF8_ERR15 Overlong 2-byte sequence -PCRE_UTF8_ERR16 Overlong 3-byte sequence -PCRE_UTF8_ERR17 Overlong 4-byte sequence -PCRE_UTF8_ERR18 Overlong 5-byte sequence (won't ever occur) -PCRE_UTF8_ERR19 Overlong 6-byte sequence (won't ever occur) -PCRE_UTF8_ERR20 Isolated 0x80 byte (not within UTF-8 character) -PCRE_UTF8_ERR21 Byte with the illegal value 0xfe or 0xff -PCRE_UTF8_ERR22 Unused (was non-character) - -Arguments: - string points to the string - length length of string, or -1 if the string is zero-terminated - errp pointer to an error position offset variable - -Returns: = 0 if the string is a valid UTF-8 string - > 0 otherwise, setting the offset of the bad character -*/ - -int -PRIV(valid_utf)(PCRE_PUCHAR string, int length, int *erroroffset) -{ -#ifdef SUPPORT_UTF -register PCRE_PUCHAR p; - -if (length < 0) - { - for (p = string; *p != 0; p++); - length = (int)(p - string); - } - -for (p = string; length-- > 0; p++) - { - register pcre_uchar ab, c, d; - - c = *p; - if (c < 128) continue; /* ASCII character */ - - if (c < 0xc0) /* Isolated 10xx xxxx byte */ - { - *erroroffset = (int)(p - string); - return PCRE_UTF8_ERR20; - } - - if (c >= 0xfe) /* Invalid 0xfe or 0xff bytes */ - { - *erroroffset = (int)(p - string); - return PCRE_UTF8_ERR21; - } - - ab = PRIV(utf8_table4)[c & 0x3f]; /* Number of additional bytes */ - if (length < ab) - { - *erroroffset = (int)(p - string); /* Missing bytes */ - return ab - length; /* Codes ERR1 to ERR5 */ - } - length -= ab; /* Length remaining */ - - /* Check top bits in the second byte */ - - if (((d = *(++p)) & 0xc0) != 0x80) - { - *erroroffset = (int)(p - string) - 1; - return PCRE_UTF8_ERR6; - } - - /* For each length, check that the remaining bytes start with the 0x80 bit - set and not the 0x40 bit. Then check for an overlong sequence, and for the - excluded range 0xd800 to 0xdfff. */ - - switch (ab) - { - /* 2-byte character. No further bytes to check for 0x80. Check first byte - for for xx00 000x (overlong sequence). */ - - case 1: if ((c & 0x3e) == 0) - { - *erroroffset = (int)(p - string) - 1; - return PCRE_UTF8_ERR15; - } - break; - - /* 3-byte character. Check third byte for 0x80. Then check first 2 bytes - for 1110 0000, xx0x xxxx (overlong sequence) or - 1110 1101, 1010 xxxx (0xd800 - 0xdfff) */ - - case 2: - if ((*(++p) & 0xc0) != 0x80) /* Third byte */ - { - *erroroffset = (int)(p - string) - 2; - return PCRE_UTF8_ERR7; - } - if (c == 0xe0 && (d & 0x20) == 0) - { - *erroroffset = (int)(p - string) - 2; - return PCRE_UTF8_ERR16; - } - if (c == 0xed && d >= 0xa0) - { - *erroroffset = (int)(p - string) - 2; - return PCRE_UTF8_ERR14; - } - break; - - /* 4-byte character. Check 3rd and 4th bytes for 0x80. Then check first 2 - bytes for for 1111 0000, xx00 xxxx (overlong sequence), then check for a - character greater than 0x0010ffff (f4 8f bf bf) */ - - case 3: - if ((*(++p) & 0xc0) != 0x80) /* Third byte */ - { - *erroroffset = (int)(p - string) - 2; - return PCRE_UTF8_ERR7; - } - if ((*(++p) & 0xc0) != 0x80) /* Fourth byte */ - { - *erroroffset = (int)(p - string) - 3; - return PCRE_UTF8_ERR8; - } - if (c == 0xf0 && (d & 0x30) == 0) - { - *erroroffset = (int)(p - string) - 3; - return PCRE_UTF8_ERR17; - } - if (c > 0xf4 || (c == 0xf4 && d > 0x8f)) - { - *erroroffset = (int)(p - string) - 3; - return PCRE_UTF8_ERR13; - } - break; - - /* 5-byte and 6-byte characters are not allowed by RFC 3629, and will be - rejected by the length test below. However, we do the appropriate tests - here so that overlong sequences get diagnosed, and also in case there is - ever an option for handling these larger code points. */ - - /* 5-byte character. Check 3rd, 4th, and 5th bytes for 0x80. Then check for - 1111 1000, xx00 0xxx */ - - case 4: - if ((*(++p) & 0xc0) != 0x80) /* Third byte */ - { - *erroroffset = (int)(p - string) - 2; - return PCRE_UTF8_ERR7; - } - if ((*(++p) & 0xc0) != 0x80) /* Fourth byte */ - { - *erroroffset = (int)(p - string) - 3; - return PCRE_UTF8_ERR8; - } - if ((*(++p) & 0xc0) != 0x80) /* Fifth byte */ - { - *erroroffset = (int)(p - string) - 4; - return PCRE_UTF8_ERR9; - } - if (c == 0xf8 && (d & 0x38) == 0) - { - *erroroffset = (int)(p - string) - 4; - return PCRE_UTF8_ERR18; - } - break; - - /* 6-byte character. Check 3rd-6th bytes for 0x80. Then check for - 1111 1100, xx00 00xx. */ - - case 5: - if ((*(++p) & 0xc0) != 0x80) /* Third byte */ - { - *erroroffset = (int)(p - string) - 2; - return PCRE_UTF8_ERR7; - } - if ((*(++p) & 0xc0) != 0x80) /* Fourth byte */ - { - *erroroffset = (int)(p - string) - 3; - return PCRE_UTF8_ERR8; - } - if ((*(++p) & 0xc0) != 0x80) /* Fifth byte */ - { - *erroroffset = (int)(p - string) - 4; - return PCRE_UTF8_ERR9; - } - if ((*(++p) & 0xc0) != 0x80) /* Sixth byte */ - { - *erroroffset = (int)(p - string) - 5; - return PCRE_UTF8_ERR10; - } - if (c == 0xfc && (d & 0x3c) == 0) - { - *erroroffset = (int)(p - string) - 5; - return PCRE_UTF8_ERR19; - } - break; - } - - /* Character is valid under RFC 2279, but 4-byte and 5-byte characters are - excluded by RFC 3629. The pointer p is currently at the last byte of the - character. */ - - if (ab > 3) - { - *erroroffset = (int)(p - string) - ab; - return (ab == 4)? PCRE_UTF8_ERR11 : PCRE_UTF8_ERR12; - } - } - -#else /* Not SUPPORT_UTF */ -(void)(string); /* Keep picky compilers happy */ -(void)(length); -(void)(erroroffset); -#endif - -return PCRE_UTF8_ERR0; /* This indicates success */ -} - -/* End of pcre_valid_utf8.c */ diff --git a/lib/impure/nre/private/pcre_src/pcre_version.c b/lib/impure/nre/private/pcre_src/pcre_version.c deleted file mode 100644 index ae86ff28b..000000000 --- a/lib/impure/nre/private/pcre_src/pcre_version.c +++ /dev/null @@ -1,98 +0,0 @@ -/************************************************* -* Perl-Compatible Regular Expressions * -*************************************************/ - -/* PCRE is a library of functions to support regular expressions whose syntax -and semantics are as close as possible to those of the Perl 5 language. - - Written by Philip Hazel - Copyright (c) 1997-2012 University of Cambridge - ------------------------------------------------------------------------------ -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - * Neither the name of the University of Cambridge nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ -*/ - - -/* This module contains the external function pcre_version(), which returns a -string that identifies the PCRE version that is in use. */ - - -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - -#include "pcre_internal.h" - - -/************************************************* -* Return version string * -*************************************************/ - -/* These macros are the standard way of turning unquoted text into C strings. -They allow macros like PCRE_MAJOR to be defined without quotes, which is -convenient for user programs that want to test its value. */ - -#define STRING(a) # a -#define XSTRING(s) STRING(s) - -/* A problem turned up with PCRE_PRERELEASE, which is defined empty for -production releases. Originally, it was used naively in this code: - - return XSTRING(PCRE_MAJOR) - "." XSTRING(PCRE_MINOR) - XSTRING(PCRE_PRERELEASE) - " " XSTRING(PCRE_DATE); - -However, when PCRE_PRERELEASE is empty, this leads to an attempted expansion of -STRING(). The C standard states: "If (before argument substitution) any -argument consists of no preprocessing tokens, the behavior is undefined." It -turns out the gcc treats this case as a single empty string - which is what we -really want - but Visual C grumbles about the lack of an argument for the -macro. Unfortunately, both are within their rights. To cope with both ways of -handling this, I had resort to some messy hackery that does a test at run time. -I could find no way of detecting that a macro is defined as an empty string at -pre-processor time. This hack uses a standard trick for avoiding calling -the STRING macro with an empty argument when doing the test. */ - -#if defined COMPILE_PCRE8 -PCRE_EXP_DEFN const char * PCRE_CALL_CONVENTION -pcre_version(void) -#elif defined COMPILE_PCRE16 -PCRE_EXP_DEFN const char * PCRE_CALL_CONVENTION -pcre16_version(void) -#elif defined COMPILE_PCRE32 -PCRE_EXP_DEFN const char * PCRE_CALL_CONVENTION -pcre32_version(void) -#endif -{ -return (XSTRING(Z PCRE_PRERELEASE)[1] == 0)? - XSTRING(PCRE_MAJOR.PCRE_MINOR PCRE_DATE) : - XSTRING(PCRE_MAJOR.PCRE_MINOR) XSTRING(PCRE_PRERELEASE PCRE_DATE); -} - -/* End of pcre_version.c */ diff --git a/lib/impure/nre/private/pcre_src/pcre_xclass.c b/lib/impure/nre/private/pcre_src/pcre_xclass.c deleted file mode 100644 index c2b61f0f9..000000000 --- a/lib/impure/nre/private/pcre_src/pcre_xclass.c +++ /dev/null @@ -1,268 +0,0 @@ -/************************************************* -* Perl-Compatible Regular Expressions * -*************************************************/ - -/* PCRE is a library of functions to support regular expressions whose syntax -and semantics are as close as possible to those of the Perl 5 language. - - Written by Philip Hazel - Copyright (c) 1997-2013 University of Cambridge - ------------------------------------------------------------------------------ -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - * Neither the name of the University of Cambridge nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ -*/ - - -/* This module contains an internal function that is used to match an extended -class. It is used by both pcre_exec() and pcre_def_exec(). */ - - -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - -#include "pcre_internal.h" - - -/************************************************* -* Match character against an XCLASS * -*************************************************/ - -/* This function is called to match a character against an extended class that -might contain values > 255 and/or Unicode properties. - -Arguments: - c the character - data points to the flag byte of the XCLASS data - -Returns: TRUE if character matches, else FALSE -*/ - -BOOL -PRIV(xclass)(pcre_uint32 c, const pcre_uchar *data, BOOL utf) -{ -pcre_uchar t; -BOOL negated = (*data & XCL_NOT) != 0; - -(void)utf; -#ifdef COMPILE_PCRE8 -/* In 8 bit mode, this must always be TRUE. Help the compiler to know that. */ -utf = TRUE; -#endif - -/* Character values < 256 are matched against a bitmap, if one is present. If -not, we still carry on, because there may be ranges that start below 256 in the -additional data. */ - -if (c < 256) - { - if ((*data & XCL_HASPROP) == 0) - { - if ((*data & XCL_MAP) == 0) return negated; - return (((pcre_uint8 *)(data + 1))[c/8] & (1 << (c&7))) != 0; - } - if ((*data & XCL_MAP) != 0 && - (((pcre_uint8 *)(data + 1))[c/8] & (1 << (c&7))) != 0) - return !negated; /* char found */ - } - -/* First skip the bit map if present. Then match against the list of Unicode -properties or large chars or ranges that end with a large char. We won't ever -encounter XCL_PROP or XCL_NOTPROP when UCP support is not compiled. */ - -if ((*data++ & XCL_MAP) != 0) data += 32 / sizeof(pcre_uchar); - -while ((t = *data++) != XCL_END) - { - pcre_uint32 x, y; - if (t == XCL_SINGLE) - { -#ifdef SUPPORT_UTF - if (utf) - { - GETCHARINC(x, data); /* macro generates multiple statements */ - } - else -#endif - x = *data++; - if (c == x) return !negated; - } - else if (t == XCL_RANGE) - { -#ifdef SUPPORT_UTF - if (utf) - { - GETCHARINC(x, data); /* macro generates multiple statements */ - GETCHARINC(y, data); /* macro generates multiple statements */ - } - else -#endif - { - x = *data++; - y = *data++; - } - if (c >= x && c <= y) return !negated; - } - -#ifdef SUPPORT_UCP - else /* XCL_PROP & XCL_NOTPROP */ - { - const ucd_record *prop = GET_UCD(c); - BOOL isprop = t == XCL_PROP; - - switch(*data) - { - case PT_ANY: - if (isprop) return !negated; - break; - - case PT_LAMP: - if ((prop->chartype == ucp_Lu || prop->chartype == ucp_Ll || - prop->chartype == ucp_Lt) == isprop) return !negated; - break; - - case PT_GC: - if ((data[1] == PRIV(ucp_gentype)[prop->chartype]) == isprop) - return !negated; - break; - - case PT_PC: - if ((data[1] == prop->chartype) == isprop) return !negated; - break; - - case PT_SC: - if ((data[1] == prop->script) == isprop) return !negated; - break; - - case PT_ALNUM: - if ((PRIV(ucp_gentype)[prop->chartype] == ucp_L || - PRIV(ucp_gentype)[prop->chartype] == ucp_N) == isprop) - return !negated; - break; - - /* Perl space used to exclude VT, but from Perl 5.18 it is included, - which means that Perl space and POSIX space are now identical. PCRE - was changed at release 8.34. */ - - case PT_SPACE: /* Perl space */ - case PT_PXSPACE: /* POSIX space */ - switch(c) - { - HSPACE_CASES: - VSPACE_CASES: - if (isprop) return !negated; - break; - - default: - if ((PRIV(ucp_gentype)[prop->chartype] == ucp_Z) == isprop) - return !negated; - break; - } - break; - - case PT_WORD: - if ((PRIV(ucp_gentype)[prop->chartype] == ucp_L || - PRIV(ucp_gentype)[prop->chartype] == ucp_N || c == CHAR_UNDERSCORE) - == isprop) - return !negated; - break; - - case PT_UCNC: - if (c < 0xa0) - { - if ((c == CHAR_DOLLAR_SIGN || c == CHAR_COMMERCIAL_AT || - c == CHAR_GRAVE_ACCENT) == isprop) - return !negated; - } - else - { - if ((c < 0xd800 || c > 0xdfff) == isprop) - return !negated; - } - break; - - /* The following three properties can occur only in an XCLASS, as there - is no \p or \P coding for them. */ - - /* Graphic character. Implement this as not Z (space or separator) and - not C (other), except for Cf (format) with a few exceptions. This seems - to be what Perl does. The exceptional characters are: - - U+061C Arabic Letter Mark - U+180E Mongolian Vowel Separator - U+2066 - U+2069 Various "isolate"s - */ - - case PT_PXGRAPH: - if ((PRIV(ucp_gentype)[prop->chartype] != ucp_Z && - (PRIV(ucp_gentype)[prop->chartype] != ucp_C || - (prop->chartype == ucp_Cf && - c != 0x061c && c != 0x180e && (c < 0x2066 || c > 0x2069)) - )) == isprop) - return !negated; - break; - - /* Printable character: same as graphic, with the addition of Zs, i.e. - not Zl and not Zp, and U+180E. */ - - case PT_PXPRINT: - if ((prop->chartype != ucp_Zl && - prop->chartype != ucp_Zp && - (PRIV(ucp_gentype)[prop->chartype] != ucp_C || - (prop->chartype == ucp_Cf && - c != 0x061c && (c < 0x2066 || c > 0x2069)) - )) == isprop) - return !negated; - break; - - /* Punctuation: all Unicode punctuation, plus ASCII characters that - Unicode treats as symbols rather than punctuation, for Perl - compatibility (these are $+<=>^`|~). */ - - case PT_PXPUNCT: - if ((PRIV(ucp_gentype)[prop->chartype] == ucp_P || - (c < 256 && PRIV(ucp_gentype)[prop->chartype] == ucp_S)) == isprop) - return !negated; - break; - - /* This should never occur, but compilers may mutter if there is no - default. */ - - default: - return FALSE; - } - - data += 2; - } -#endif /* SUPPORT_UCP */ - } - -return negated; /* char did not match */ -} - -/* End of pcre_xclass.c */ diff --git a/lib/impure/nre/private/pcre_src/ucp.h b/lib/impure/nre/private/pcre_src/ucp.h deleted file mode 100644 index 2fa00296e..000000000 --- a/lib/impure/nre/private/pcre_src/ucp.h +++ /dev/null @@ -1,224 +0,0 @@ -/************************************************* -* Unicode Property Table handler * -*************************************************/ - -#ifndef _UCP_H -#define _UCP_H - -/* This file contains definitions of the property values that are returned by -the UCD access macros. New values that are added for new releases of Unicode -should always be at the end of each enum, for backwards compatibility. - -IMPORTANT: Note also that the specific numeric values of the enums have to be -the same as the values that are generated by the maint/MultiStage2.py script, -where the equivalent property descriptive names are listed in vectors. - -ALSO: The specific values of the first two enums are assumed for the table -called catposstab in pcre_compile.c. */ - -/* These are the general character categories. */ - -enum { - ucp_C, /* Other */ - ucp_L, /* Letter */ - ucp_M, /* Mark */ - ucp_N, /* Number */ - ucp_P, /* Punctuation */ - ucp_S, /* Symbol */ - ucp_Z /* Separator */ -}; - -/* These are the particular character categories. */ - -enum { - ucp_Cc, /* Control */ - ucp_Cf, /* Format */ - ucp_Cn, /* Unassigned */ - ucp_Co, /* Private use */ - ucp_Cs, /* Surrogate */ - ucp_Ll, /* Lower case letter */ - ucp_Lm, /* Modifier letter */ - ucp_Lo, /* Other letter */ - ucp_Lt, /* Title case letter */ - ucp_Lu, /* Upper case letter */ - ucp_Mc, /* Spacing mark */ - ucp_Me, /* Enclosing mark */ - ucp_Mn, /* Non-spacing mark */ - ucp_Nd, /* Decimal number */ - ucp_Nl, /* Letter number */ - ucp_No, /* Other number */ - ucp_Pc, /* Connector punctuation */ - ucp_Pd, /* Dash punctuation */ - ucp_Pe, /* Close punctuation */ - ucp_Pf, /* Final punctuation */ - ucp_Pi, /* Initial punctuation */ - ucp_Po, /* Other punctuation */ - ucp_Ps, /* Open punctuation */ - ucp_Sc, /* Currency symbol */ - ucp_Sk, /* Modifier symbol */ - ucp_Sm, /* Mathematical symbol */ - ucp_So, /* Other symbol */ - ucp_Zl, /* Line separator */ - ucp_Zp, /* Paragraph separator */ - ucp_Zs /* Space separator */ -}; - -/* These are grapheme break properties. Note that the code for processing them -assumes that the values are less than 16. If more values are added that take -the number to 16 or more, the code will have to be rewritten. */ - -enum { - ucp_gbCR, /* 0 */ - ucp_gbLF, /* 1 */ - ucp_gbControl, /* 2 */ - ucp_gbExtend, /* 3 */ - ucp_gbPrepend, /* 4 */ - ucp_gbSpacingMark, /* 5 */ - ucp_gbL, /* 6 Hangul syllable type L */ - ucp_gbV, /* 7 Hangul syllable type V */ - ucp_gbT, /* 8 Hangul syllable type T */ - ucp_gbLV, /* 9 Hangul syllable type LV */ - ucp_gbLVT, /* 10 Hangul syllable type LVT */ - ucp_gbRegionalIndicator, /* 11 */ - ucp_gbOther /* 12 */ -}; - -/* These are the script identifications. */ - -enum { - ucp_Arabic, - ucp_Armenian, - ucp_Bengali, - ucp_Bopomofo, - ucp_Braille, - ucp_Buginese, - ucp_Buhid, - ucp_Canadian_Aboriginal, - ucp_Cherokee, - ucp_Common, - ucp_Coptic, - ucp_Cypriot, - ucp_Cyrillic, - ucp_Deseret, - ucp_Devanagari, - ucp_Ethiopic, - ucp_Georgian, - ucp_Glagolitic, - ucp_Gothic, - ucp_Greek, - ucp_Gujarati, - ucp_Gurmukhi, - ucp_Han, - ucp_Hangul, - ucp_Hanunoo, - ucp_Hebrew, - ucp_Hiragana, - ucp_Inherited, - ucp_Kannada, - ucp_Katakana, - ucp_Kharoshthi, - ucp_Khmer, - ucp_Lao, - ucp_Latin, - ucp_Limbu, - ucp_Linear_B, - ucp_Malayalam, - ucp_Mongolian, - ucp_Myanmar, - ucp_New_Tai_Lue, - ucp_Ogham, - ucp_Old_Italic, - ucp_Old_Persian, - ucp_Oriya, - ucp_Osmanya, - ucp_Runic, - ucp_Shavian, - ucp_Sinhala, - ucp_Syloti_Nagri, - ucp_Syriac, - ucp_Tagalog, - ucp_Tagbanwa, - ucp_Tai_Le, - ucp_Tamil, - ucp_Telugu, - ucp_Thaana, - ucp_Thai, - ucp_Tibetan, - ucp_Tifinagh, - ucp_Ugaritic, - ucp_Yi, - /* New for Unicode 5.0: */ - ucp_Balinese, - ucp_Cuneiform, - ucp_Nko, - ucp_Phags_Pa, - ucp_Phoenician, - /* New for Unicode 5.1: */ - ucp_Carian, - ucp_Cham, - ucp_Kayah_Li, - ucp_Lepcha, - ucp_Lycian, - ucp_Lydian, - ucp_Ol_Chiki, - ucp_Rejang, - ucp_Saurashtra, - ucp_Sundanese, - ucp_Vai, - /* New for Unicode 5.2: */ - ucp_Avestan, - ucp_Bamum, - ucp_Egyptian_Hieroglyphs, - ucp_Imperial_Aramaic, - ucp_Inscriptional_Pahlavi, - ucp_Inscriptional_Parthian, - ucp_Javanese, - ucp_Kaithi, - ucp_Lisu, - ucp_Meetei_Mayek, - ucp_Old_South_Arabian, - ucp_Old_Turkic, - ucp_Samaritan, - ucp_Tai_Tham, - ucp_Tai_Viet, - /* New for Unicode 6.0.0: */ - ucp_Batak, - ucp_Brahmi, - ucp_Mandaic, - /* New for Unicode 6.1.0: */ - ucp_Chakma, - ucp_Meroitic_Cursive, - ucp_Meroitic_Hieroglyphs, - ucp_Miao, - ucp_Sharada, - ucp_Sora_Sompeng, - ucp_Takri, - /* New for Unicode 7.0.0: */ - ucp_Bassa_Vah, - ucp_Caucasian_Albanian, - ucp_Duployan, - ucp_Elbasan, - ucp_Grantha, - ucp_Khojki, - ucp_Khudawadi, - ucp_Linear_A, - ucp_Mahajani, - ucp_Manichaean, - ucp_Mende_Kikakui, - ucp_Modi, - ucp_Mro, - ucp_Nabataean, - ucp_Old_North_Arabian, - ucp_Old_Permic, - ucp_Pahawh_Hmong, - ucp_Palmyrene, - ucp_Psalter_Pahlavi, - ucp_Pau_Cin_Hau, - ucp_Siddham, - ucp_Tirhuta, - ucp_Warang_Citi -}; - -#endif - -/* End of ucp.h */ From b4843bc7c1187d5e5443f355925b71be30c88fba Mon Sep 17 00:00:00 2001 From: yglukhov Date: Wed, 27 May 2015 11:27:34 +0300 Subject: [PATCH 0302/1263] Enabled taddr and testobjs tests --- tests/js/taddr.nim | 8 +++++++- tests/js/testobjs.nim | 12 ++++++++---- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/tests/js/taddr.nim b/tests/js/taddr.nim index 6a60aa902..f9c89fbc3 100644 --- a/tests/js/taddr.nim +++ b/tests/js/taddr.nim @@ -1,3 +1,7 @@ +discard """ + action: run +""" + type T = object x: int s: string @@ -29,8 +33,10 @@ doAssert objDeref.x == 42 obj.s = "lorem ipsum dolor sit amet" var indexAddr = addr(obj.s[2]) -doAssert indexAddr[] == '4' +doAssert indexAddr[] == 'r' indexAddr[] = 'd' doAssert indexAddr[] == 'd' + +doAssert obj.s == "lodem ipsum dolor sit amet" diff --git a/tests/js/testobjs.nim b/tests/js/testobjs.nim index 4fb9a83dc..0166c0f38 100644 --- a/tests/js/testobjs.nim +++ b/tests/js/testobjs.nim @@ -1,3 +1,7 @@ +discard """ + action: run +""" + ## Tests javascript object generation type @@ -28,7 +32,7 @@ var recurse1 = Recurse[int](data: 1, next: recurse2) -assert(test.name == "Jorden") -assert(knight.age == 19) -assert(knight.item.price == 50) -assert(recurse1.next.next.data == 3) +doAssert test.name == "Jorden" +doAssert knight.age == 19 +doAssert knight.item.price == 50 +doAssert recurse1.next.next.data == 3 From eec76cfc6b4c21c7deeac051442d408b7dc9f589 Mon Sep 17 00:00:00 2001 From: yglukhov Date: Thu, 28 May 2015 10:23:09 +0300 Subject: [PATCH 0303/1263] Fixed renderer for asm node in JS --- compiler/renderer.nim | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/compiler/renderer.nim b/compiler/renderer.nim index ffdb60696..376c0d6f7 100644 --- a/compiler/renderer.nim +++ b/compiler/renderer.nim @@ -767,7 +767,8 @@ proc gasm(g: var TSrcGen, n: PNode) = putWithSpace(g, tkAsm, "asm") gsub(g, n.sons[0]) gcoms(g) - gsub(g, n.sons[1]) + if n.sons.len > 1: + gsub(g, n.sons[1]) proc gident(g: var TSrcGen, n: PNode) = if g.checkAnon and n.kind == nkSym and sfAnon in n.sym.flags: return From 94f54700c4bfcc04966e0ea011960c5432b29092 Mon Sep 17 00:00:00 2001 From: Araq Date: Thu, 28 May 2015 12:42:04 +0200 Subject: [PATCH 0304/1263] first implementation of pinnedSpawn --- compiler/lowerings.nim | 13 ++++--- compiler/semexprs.nim | 16 +++++---- compiler/sempass2.nim | 5 +-- lib/pure/concurrency/threadpool.nim | 56 ++++++++++++++++++++++++++--- 4 files changed, 73 insertions(+), 17 deletions(-) diff --git a/compiler/lowerings.nim b/compiler/lowerings.nim index b6b01d558..842bb01f6 100644 --- a/compiler/lowerings.nim +++ b/compiler/lowerings.nim @@ -167,7 +167,7 @@ proc genDeref*(n: PNode): PNode = result.add n proc callCodegenProc*(name: string, arg1: PNode; - arg2, arg3: PNode = nil): PNode = + arg2, arg3, optionalArgs: PNode = nil): PNode = result = newNodeI(nkCall, arg1.info) let sym = magicsys.getCompilerProc(name) if sym == nil: @@ -177,6 +177,9 @@ proc callCodegenProc*(name: string, arg1: PNode; result.add arg1 if arg2 != nil: result.add arg2 if arg3 != nil: result.add arg3 + if optionalArgs != nil: + for i in 1..optionalArgs.len-3: + result.add optionalArgs[i] result.typ = sym.typ.sons[0] proc callProc(a: PNode): PNode = @@ -483,7 +486,7 @@ proc wrapProcForSpawn*(owner: PSym; spawnExpr: PNode; retType: PType; barrier, dest: PNode = nil): PNode = # if 'barrier' != nil, then it is in a 'parallel' section and we # generate quite different code - let n = spawnExpr[1] + let n = spawnExpr[^2] let spawnKind = spawnResult(retType, barrier!=nil) case spawnKind of srVoid: @@ -569,7 +572,7 @@ proc wrapProcForSpawn*(owner: PSym; spawnExpr: PNode; retType: PType; fvField = newDotExpr(scratchObj, field) fvAsExpr = indirectAccess(castExpr, field, n.info) # create flowVar: - result.add newFastAsgnStmt(fvField, callProc(spawnExpr[2])) + result.add newFastAsgnStmt(fvField, callProc(spawnExpr[^1])) if barrier == nil: result.add callCodegenProc("nimFlowVarCreateSemaphore", fvField) @@ -584,7 +587,7 @@ proc wrapProcForSpawn*(owner: PSym; spawnExpr: PNode; retType: PType; let wrapper = createWrapperProc(fn, threadParam, argsParam, varSection, varInit, call, barrierAsExpr, fvAsExpr, spawnKind) - result.add callCodegenProc("nimSpawn", wrapper.newSymNode, - genAddrOf(scratchObj.newSymNode)) + result.add callCodegenProc("nimSpawn" & $spawnExpr.len, wrapper.newSymNode, + genAddrOf(scratchObj.newSymNode), nil, spawnExpr) if spawnKind == srFlowVar: result.add fvField diff --git a/compiler/semexprs.nim b/compiler/semexprs.nim index cd6ba3753..be1461c3c 100644 --- a/compiler/semexprs.nim +++ b/compiler/semexprs.nim @@ -1727,13 +1727,17 @@ proc semMagic(c: PContext, n: PNode, s: PSym, flags: TExprFlags): PNode = dec c.inParallelStmt of mSpawn: result = setMs(n, s) - result.sons[1] = semExpr(c, n.sons[1]) - if not result[1].typ.isEmptyType: - if spawnResult(result[1].typ, c.inParallelStmt > 0) == srFlowVar: - result.typ = createFlowVar(c, result[1].typ, n.info) + for i in 1 .. 0) == srFlowVar: + result.typ = createFlowVar(c, typ, n.info) else: - result.typ = result[1].typ - result.add instantiateCreateFlowVarCall(c, result[1].typ, n.info).newSymNode + result.typ = typ + result.add instantiateCreateFlowVarCall(c, typ, n.info).newSymNode + else: + result.add emptyNode of mProcCall: result = setMs(n, s) result.sons[1] = semExpr(c, n.sons[1]) diff --git a/compiler/sempass2.nim b/compiler/sempass2.nim index adf03be64..517c37b0f 100644 --- a/compiler/sempass2.nim +++ b/compiler/sempass2.nim @@ -237,9 +237,10 @@ proc useVar(a: PEffects, n: PNode) = message(n.info, warnUninit, s.name.s) # prevent superfluous warnings about the same variable: a.init.add s.id - if {sfGlobal, sfThread} * s.flags == {sfGlobal} and s.kind in {skVar, skLet}: + if {sfGlobal, sfThread} * s.flags != {} and s.kind in {skVar, skLet}: if s.guard != nil: guardGlobal(a, n, s.guard) - if (tfHasGCedMem in s.typ.flags or s.typ.isGCedMem): + if {sfGlobal, sfThread} * s.flags == {sfGlobal} and + (tfHasGCedMem in s.typ.flags or s.typ.isGCedMem): #if warnGcUnsafe in gNotes: warnAboutGcUnsafe(n) markGcUnsafe(a, s) diff --git a/lib/pure/concurrency/threadpool.nim b/lib/pure/concurrency/threadpool.nim index 9f1e53fb8..10117183a 100644 --- a/lib/pure/concurrency/threadpool.nim +++ b/lib/pure/concurrency/threadpool.nim @@ -267,6 +267,10 @@ proc nimArgsPassingDone(p: pointer) {.compilerProc.} = const MaxThreadPoolSize* = 256 ## maximal size of the thread pool. 256 threads ## should be good enough for anybody ;-) + MaxDistinguishedThread* = 32 ## maximal number of "distinguished" threads. + +type + ThreadId* = range[0..MaxDistinguishedThread-1] var currentPoolSize: int @@ -291,10 +295,24 @@ proc slave(w: ptr Worker) {.thread.} = w.shutdown = false atomicDec currentPoolSize +proc distinguishedSlave(w: ptr Worker) {.thread.} = + while true: + when declared(atomicStoreN): + atomicStoreN(addr(w.ready), true, ATOMIC_SEQ_CST) + else: + w.ready = true + await(w.taskArrived) + assert(not w.ready) + w.f(w, w.data) + if w.q.len != 0: w.cleanFlowVars + var workers: array[MaxThreadPoolSize, TThread[ptr Worker]] workersData: array[MaxThreadPoolSize, Worker] + distinguished: array[MaxDistinguishedThread, TThread[ptr Worker]] + distinguishedData: array[MaxDistinguishedThread, Worker] + proc setMinPoolSize*(size: range[1..MaxThreadPoolSize]) = ## sets the minimal thread pool size. The default value of this is 4. minPoolSize = size @@ -308,7 +326,7 @@ proc setMaxPoolSize*(size: range[1..MaxThreadPoolSize]) = let w = addr(workersData[i]) w.shutdown = true -proc activateThread(i: int) {.noinline.} = +proc activateWorkerThread(i: int) {.noinline.} = workersData[i].taskArrived = createSemaphore() workersData[i].taskStarted = createSemaphore() workersData[i].initialized = true @@ -316,10 +334,18 @@ proc activateThread(i: int) {.noinline.} = initLock(workersData[i].q.lock) createThread(workers[i], slave, addr(workersData[i])) +proc activateDistinguishedThread(i: int) {.noinline.} = + distinguishedData[i].taskArrived = createSemaphore() + distinguishedData[i].taskStarted = createSemaphore() + distinguishedData[i].initialized = true + distinguishedData[i].q.empty = createSemaphore() + initLock(distinguishedData[i].q.lock) + createThread(distinguished[i], distinguishedSlave, addr(distinguishedData[i])) + proc setup() = currentPoolSize = min(countProcessors(), MaxThreadPoolSize) readyWorker = addr(workersData[0]) - for i in 0.. Date: Thu, 28 May 2015 12:44:31 +0200 Subject: [PATCH 0305/1263] minor tut1 update --- doc/tut1.txt | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/doc/tut1.txt b/doc/tut1.txt index 58ace1dbe..fef4cb438 100644 --- a/doc/tut1.txt +++ b/doc/tut1.txt @@ -1325,11 +1325,11 @@ define operators which accept Slice objects to define ranges. b = "Slices are useless." echo a[7..12] # --> 'a prog' - b[11.. -2] = "useful" + b[11..^2] = "useful" echo b # --> 'Slices are useful.' -In the previous example slices are used to modify a part of a string, and even -a negative index is used. The slice's bounds can hold any value supported by +In the previous example slices are used to modify a part of a string. The +slice's bounds can hold any value supported by their type, but it is the proc using the slice object which defines what values are accepted. From c5a479d536eee243846282f3817ebb3916f6bcf4 Mon Sep 17 00:00:00 2001 From: Araq Date: Thu, 28 May 2015 12:44:58 +0200 Subject: [PATCH 0306/1263] minor manual update --- doc/manual/types.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/manual/types.txt b/doc/manual/types.txt index bdf51941d..1461b67b2 100644 --- a/doc/manual/types.txt +++ b/doc/manual/types.txt @@ -564,7 +564,7 @@ the ``of`` operator can be used to determine the object's type. .. code-block:: nim type - Person {.inheritable.} = object + Person = object of RootObj name*: string # the * means that `name` is accessible from other modules age: int # no * means that the field is hidden From 21ea8e6913fbfc16192ad3fd157e8e18e559219d Mon Sep 17 00:00:00 2001 From: Araq Date: Thu, 28 May 2015 12:49:08 +0200 Subject: [PATCH 0307/1263] some progress on making async multithreaded --- lib/pure/asyncdispatch.nim | 5 +- lib/pure/collections/sharedstrings.nim | 154 ++++++++++++++++++ lib/pure/collections/sharedtables.nim | 105 ++++++++++++ lib/pure/collections/tableimpl.nim | 132 +++++++++++++++ lib/pure/collections/tables.nim | 217 ++++++------------------- lib/pure/selectors.nim | 134 +++++++-------- 6 files changed, 504 insertions(+), 243 deletions(-) create mode 100644 lib/pure/collections/sharedstrings.nim create mode 100644 lib/pure/collections/sharedtables.nim create mode 100644 lib/pure/collections/tableimpl.nim diff --git a/lib/pure/asyncdispatch.nim b/lib/pure/asyncdispatch.nim index a4d7a1632..2a271b841 100644 --- a/lib/pure/asyncdispatch.nim +++ b/lib/pure/asyncdispatch.nim @@ -122,7 +122,6 @@ export Port, SocketFlag ## Limitations/Bugs ## ---------------- ## -## * ``except`` statement (without `try`) does not work inside async procedures. ## * The effect system (``raises: []``) does not work with async procedures. ## * Can't await in a ``except`` body @@ -929,7 +928,7 @@ else: result = newRawSocket(domain, typ, protocol).TAsyncFD result.SocketHandle.setBlocking(false) when defined(macosx): - result.SocketHandle.setSockOptInt(SOL_SOCKET, SO_NOSIGPIPE, 1) + result.SocketHandle.setSockOptInt(SOL_SOCKET, SO_NOSIGPIPE, 1) register(result) proc newAsyncRawSocket*(domain: Domain = AF_INET, @@ -938,7 +937,7 @@ else: result = newRawSocket(domain, typ, protocol).TAsyncFD result.SocketHandle.setBlocking(false) when defined(macosx): - result.SocketHandle.setSockOptInt(SOL_SOCKET, SO_NOSIGPIPE, 1) + result.SocketHandle.setSockOptInt(SOL_SOCKET, SO_NOSIGPIPE, 1) register(result) proc closeSocket*(sock: TAsyncFD) = diff --git a/lib/pure/collections/sharedstrings.nim b/lib/pure/collections/sharedstrings.nim new file mode 100644 index 000000000..10ab30767 --- /dev/null +++ b/lib/pure/collections/sharedstrings.nim @@ -0,0 +1,154 @@ +# +# +# Nim's Runtime Library +# (c) Copyright 2015 Andreas Rumpf +# +# See the file "copying.txt", included in this +# distribution, for details about the copyright. +# + +## Shared string support for Nim. + +const ArrayDummySize = when defined(cpu16): 10_000 else: 100_000_000 + +type + UncheckedCharArray {.unchecked.} = array[0..ArrayDummySize, char] + +type + Buffer = ptr object + refcount: int + capacity, realLen: int + data: UncheckedCharArray + + SharedString* = object ## A string that can be shared. Slicing is O(1). + buffer: Buffer + first, len: int + +proc decRef(b: Buffer) {.inline.} = + if atomicDec(b.refcount) <= 0: + deallocShared(b) + +proc incRef(b: Buffer) {.inline.} = + atomicInc(b.refcount) + +{.experimental.} + +proc `=destroy`*(s: SharedString) = + #echo "destroyed" + if not s.buffer.isNil: + decRef(s.buffer) + +when false: + proc `=`*(dest: var SharedString; src: SharedString) = + incRef(src.buffer) + if not dest.buffer.isNil: + decRef(dest.buffer) + dest.buffer = src.buffer + dest.first = src.first + dest.len = src.len + +proc len*(s: SharedString): int = s.len + +proc `[]`*(s: SharedString; i: Natural): char = + if i < s.len: result = s.buffer.data[i+s.first] + else: raise newException(IndexError, "index out of bounds") + +proc `[]=`*(s: var SharedString; i: Natural; value: char) = + if i < s.len: s.buffer.data[i+s.first] = value + else: raise newException(IndexError, "index out of bounds") + +proc `[]`*(s: SharedString; ab: Slice[int]): SharedString = + #incRef(src.buffer) + if ab.a < s.len: + result.buffer = s.buffer + result.first = ab.a + result.len = min(s.len, ab.b - ab.a + 1) + # else: produce empty string ;-) + +proc newBuffer(cap, len: int): Buffer = + assert cap >= len + result = cast[Buffer](allocShared0(sizeof(int)*3 + cap)) + result.refcount = 0 + result.capacity = cap + result.realLen = len + +proc newSharedString*(len: Natural): SharedString = + if len != 0: + # optimization: Don't have an underlying buffer when 'len == 0' + result.buffer = newBuffer(len, len) + result.first = 0 + result.len = len + +proc newSharedString*(s: string): SharedString = + let len = s.len + if len != 0: + # optimization: Don't have an underlying buffer when 'len == 0' + result.buffer = newBuffer(len, len) + copyMem(addr result.buffer.data[0], cstring(s), s.len) + result.first = 0 + result.len = len + +when declared(atomicLoadN): + template load(x): expr = atomicLoadN(addr x, ATOMIC_SEQ_CST) +else: + # XXX Fixme + template load(x): expr = x + +proc add*(s: var SharedString; t: cstring; len: Natural) = + if len == 0: return + let newLen = s.len + len + if s.buffer.isNil: + s.buffer = newBuffer(len, len) + copyMem(addr s.buffer.data[0], t, len) + s.len = len + elif newLen >= s.buffer.capacity or s.first != 0 or + s.len != s.buffer.realLen or load(s.buffer.refcount) > 1: + let oldBuf = s.buffer + s.buffer = newBuffer(max(s.buffer.capacity * 3 div 2, newLen), newLen) + copyMem(addr s.buffer.data[0], addr oldBuf.data[s.first], s.len) + copyMem(addr s.buffer.data[s.len], t, len) + decRef(oldBuf) + else: + copyMem(addr s.buffer.data[s.len], t, len) + s.buffer.realLen += len + s.len += len + +proc add*(s: var SharedString; t: string) = + s.add(t.cstring, t.len) + +proc rawData*(s: var SharedString): pointer = + if s.buffer.isNil: result = nil + else: result = addr s.buffer.data[s.first] + +proc add*(s: var SharedString; t: SharedString) = + if t.buffer.isNil: return + s.add(cast[cstring](addr s.buffer.data[s.first]), t.len) + +proc `$`*(s: SharedString): string = + result = newString(s.len) + if s.len > 0: + copyMem(addr result[0], addr s.buffer.data[s.first], s.len) + +proc `==`*(s: SharedString; t: string): bool = + if s.buffer.isNil: result = t.len == 0 + else: result = t.len == s.len and equalMem(addr s.buffer.data[s.first], + cstring(t), t.len) + +proc `==`*(s, t: SharedString): bool = + if s.buffer.isNil: result = t.len == 0 + else: result = t.len == s.len and equalMem(addr s.buffer.data[s.first], + addr t.buffer.data[t.first], t.len) + +iterator items*(s: SharedString): char = + let buf = s.buffer.data + let x = s.first + if buf != nil: + for i in 0..= 0 + if hasKey: result = t.data[index].val + if not hasKey: + when compiles($key): + raise newException(KeyError, "key not found: " & $key) + else: + raise newException(KeyError, "key not found") + +proc mgetOrPut*[A, B](t: var SharedTable[A, B], key: A, val: B): var B = + ## retrieves value at ``t[key]`` or puts ``val`` if not present, either way + ## returning a value which can be modified. **Note**: This is inherently + ## unsafe in the context of multi-threading since it returns a pointer + ## to ``B``. + withLock t: + mgetOrPutImpl(enlarge) + +proc hasKeyOrPut*[A, B](t: var SharedTable[A, B], key: A, val: B): bool = + ## returns true iff `key` is in the table, otherwise inserts `value`. + withLock t: + hasKeyOrPutImpl(enlarge) + +proc `[]=`*[A, B](t: var SharedTable[A, B], key: A, val: B) = + ## puts a (key, value)-pair into `t`. + withLock t: + putImpl(enlarge) + +proc add*[A, B](t: var SharedTable[A, B], key: A, val: B) = + ## puts a new (key, value)-pair into `t` even if ``t[key]`` already exists. + withLock t: + addImpl(enlarge) + +proc del*[A, B](t: var SharedTable[A, B], key: A) = + ## deletes `key` from hash table `t`. + withLock t: + delImpl() + +proc initSharedTable*[A, B](initialSize=64): SharedTable[A, B] = + ## creates a new hash table that is empty. + ## + ## `initialSize` needs to be a power of two. If you need to accept runtime + ## values for this you could use the ``nextPowerOfTwo`` proc from the + ## `math `_ module or the ``rightSize`` proc from this module. + assert isPowerOfTwo(initialSize) + result.counter = 0 + result.dataLen = initialSize + result.data = cast[KeyValuePairSeq[A, B]](allocShared0( + sizeof(KeyValuePair[A, B]) * initialSize)) + initLock result.lock + +proc deinitSharedTable*[A, B](t: var SharedTable[A, B]) = + deallocShared(t.data) + deinitLock t.lock diff --git a/lib/pure/collections/tableimpl.nim b/lib/pure/collections/tableimpl.nim new file mode 100644 index 000000000..5900864fb --- /dev/null +++ b/lib/pure/collections/tableimpl.nim @@ -0,0 +1,132 @@ +# +# +# Nim's Runtime Library +# (c) Copyright 2015 Andreas Rumpf +# +# See the file "copying.txt", included in this +# distribution, for details about the copyright. +# + +## An ``include`` file for the different table implementations. + +# hcode for real keys cannot be zero. hcode==0 signifies an empty slot. These +# two procs retain clarity of that encoding without the space cost of an enum. +proc isEmpty(hcode: THash): bool {.inline.} = + result = hcode == 0 + +proc isFilled(hcode: THash): bool {.inline.} = + result = hcode != 0 + +const + growthFactor = 2 + +proc mustRehash(length, counter: int): bool {.inline.} = + assert(length > counter) + result = (length * 2 < counter * 3) or (length - counter < 4) + +proc nextTry(h, maxHash: THash): THash {.inline.} = + result = (h + 1) and maxHash + +template rawGetKnownHCImpl() {.dirty.} = + var h: THash = hc and maxHash(t) # start with real hash value + while isFilled(t.data[h].hcode): + # Compare hc THEN key with boolean short circuit. This makes the common case + # zero ==key's for missing (e.g.inserts) and exactly one ==key for present. + # It does slow down succeeding lookups by one extra THash cmp&and..usually + # just a few clock cycles, generally worth it for any non-integer-like A. + if t.data[h].hcode == hc and t.data[h].key == key: + return h + h = nextTry(h, maxHash(t)) + result = -1 - h # < 0 => MISSING; insert idx = -1 - result + +template rawGetImpl() {.dirty.} = + hc = hash(key) + if hc == 0: # This almost never taken branch should be very predictable. + hc = 314159265 # Value doesn't matter; Any non-zero favorite is fine. + rawGetKnownHCImpl() + +template rawGetDeepImpl() {.dirty.} = # Search algo for unconditional add + hc = hash(key) + if hc == 0: + hc = 314159265 + var h: THash = hc and maxHash(t) + while isFilled(t.data[h].hcode): + h = nextTry(h, maxHash(t)) + result = h + +template rawInsertImpl() {.dirty.} = + data[h].key = key + data[h].val = val + data[h].hcode = hc + +proc rawGetKnownHC[X, A](t: X, key: A, hc: THash): int {.inline.} = + rawGetKnownHCImpl() + +proc rawGetDeep[X, A](t: X, key: A, hc: var THash): int {.inline.} = + rawGetDeepImpl() + +proc rawGet[X, A](t: X, key: A, hc: var THash): int {.inline.} = + rawGetImpl() + +proc rawInsert[X, A, B](t: var X, data: var KeyValuePairSeq[A, B], + key: A, val: B, hc: THash, h: THash) = + rawInsertImpl() + +template addImpl(enlarge) {.dirty, immediate.} = + if mustRehash(t.dataLen, t.counter): enlarge(t) + var hc: THash + var j = rawGetDeep(t, key, hc) + rawInsert(t, t.data, key, val, hc, j) + inc(t.counter) + +template maybeRehashPutImpl(enlarge) {.dirty, immediate.} = + if mustRehash(t.dataLen, t.counter): + enlarge(t) + index = rawGetKnownHC(t, key, hc) + index = -1 - index # important to transform for mgetOrPutImpl + rawInsert(t, t.data, key, val, hc, index) + inc(t.counter) + +template putImpl(enlarge) {.dirty, immediate.} = + var hc: THash + var index = rawGet(t, key, hc) + if index >= 0: t.data[index].val = val + else: maybeRehashPutImpl(enlarge) + +template mgetOrPutImpl(enlarge) {.dirty, immediate.} = + var hc: THash + var index = rawGet(t, key, hc) + if index < 0: + # not present: insert (flipping index) + maybeRehashPutImpl(enlarge) + # either way return modifiable val + result = t.data[index].val + +template hasKeyOrPutImpl(enlarge) {.dirty, immediate.} = + var hc: THash + var index = rawGet(t, key, hc) + if index < 0: + result = false + maybeRehashPutImpl(enlarge) + else: result = true + +template delImpl() {.dirty, immediate.} = + var hc: THash + var i = rawGet(t, key, hc) + let msk = maxHash(t) + if i >= 0: + t.data[i].hcode = 0 + dec(t.counter) + block outer: + while true: # KnuthV3 Algo6.4R adapted for i=i+1 instead of i=i-1 + var j = i # The correctness of this depends on (h+1) in nextTry, + var r = j # though may be adaptable to other simple sequences. + t.data[i].hcode = 0 # mark current EMPTY + while true: + i = (i + 1) and msk # increment mod table size + if isEmpty(t.data[i].hcode): # end of collision cluster; So all done + break outer + r = t.data[i].hcode and msk # "home" location of key@i + if not ((i >= r and r > j) or (r > j and j > i) or (j > i and i >= r)): + break + shallowCopy(t.data[j], t.data[i]) # data[j] will be marked EMPTY next loop diff --git a/lib/pure/collections/tables.nim b/lib/pure/collections/tables.nim index a9357ce67..c802d0221 100644 --- a/lib/pure/collections/tables.nim +++ b/lib/pure/collections/tables.nim @@ -68,65 +68,20 @@ import hashes, math -{.pragma: myShallow.} - type KeyValuePair[A, B] = tuple[hcode: THash, key: A, val: B] KeyValuePairSeq[A, B] = seq[KeyValuePair[A, B]] - Table* {.myShallow.}[A, B] = object ## generic hash table + Table*[A, B] = object ## generic hash table data: KeyValuePairSeq[A, B] counter: int TableRef*[A,B] = ref Table[A, B] {.deprecated: [TTable: Table, PTable: TableRef].} -when not defined(nimhygiene): - {.pragma: dirty.} +template maxHash(t): expr {.immediate.} = high(t.data) +template dataLen(t): expr = len(t.data) -# hcode for real keys cannot be zero. hcode==0 signifies an empty slot. These -# two procs retain clarity of that encoding without the space cost of an enum. -proc isEmpty(hcode: THash): bool {.inline.} = - result = hcode == 0 - -proc isFilled(hcode: THash): bool {.inline.} = - result = hcode != 0 - -proc len*[A, B](t: Table[A, B]): int = - ## returns the number of keys in `t`. - result = t.counter - -iterator pairs*[A, B](t: Table[A, B]): (A, B) = - ## iterates over any (key, value) pair in the table `t`. - for h in 0..high(t.data): - if isFilled(t.data[h].hcode): yield (t.data[h].key, t.data[h].val) - -iterator mpairs*[A, B](t: var Table[A, B]): (A, var B) = - ## iterates over any (key, value) pair in the table `t`. The values - ## can be modified. - for h in 0..high(t.data): - if isFilled(t.data[h].hcode): yield (t.data[h].key, t.data[h].val) - -iterator keys*[A, B](t: Table[A, B]): A = - ## iterates over any key in the table `t`. - for h in 0..high(t.data): - if isFilled(t.data[h].hcode): yield t.data[h].key - -iterator values*[A, B](t: Table[A, B]): B = - ## iterates over any value in the table `t`. - for h in 0..high(t.data): - if isFilled(t.data[h].hcode): yield t.data[h].val - -iterator mvalues*[A, B](t: var Table[A, B]): var B = - ## iterates over any value in the table `t`. The values can be modified. - for h in 0..high(t.data): - if isFilled(t.data[h].hcode): yield t.data[h].val - -const - growthFactor = 2 - -proc mustRehash(length, counter: int): bool {.inline.} = - assert(length > counter) - result = (length * 2 < counter * 3) or (length - counter < 4) +include tableimpl proc rightSize*(count: Natural): int {.inline.} = ## Return the value of `initialSize` to support `count` items. @@ -137,49 +92,9 @@ proc rightSize*(count: Natural): int {.inline.} = ## Internally, we want mustRehash(rightSize(x), x) == false. result = nextPowerOfTwo(count * 3 div 2 + 4) -proc nextTry(h, maxHash: THash): THash {.inline.} = - result = (h + 1) and maxHash - -template rawGetKnownHCImpl() {.dirty.} = - var h: THash = hc and high(t.data) # start with real hash value - while isFilled(t.data[h].hcode): - # Compare hc THEN key with boolean short circuit. This makes the common case - # zero ==key's for missing (e.g.inserts) and exactly one ==key for present. - # It does slow down succeeding lookups by one extra THash cmp&and..usually - # just a few clock cycles, generally worth it for any non-integer-like A. - if t.data[h].hcode == hc and t.data[h].key == key: - return h - h = nextTry(h, high(t.data)) - result = -1 - h # < 0 => MISSING; insert idx = -1 - result - -template rawGetImpl() {.dirty.} = - hc = hash(key) - if hc == 0: # This almost never taken branch should be very predictable. - hc = 314159265 # Value doesn't matter; Any non-zero favorite is fine. - rawGetKnownHCImpl() - -template rawGetDeepImpl() {.dirty.} = # Search algo for unconditional add - hc = hash(key) - if hc == 0: - hc = 314159265 - var h: THash = hc and high(t.data) - while isFilled(t.data[h].hcode): - h = nextTry(h, high(t.data)) - result = h - -template rawInsertImpl() {.dirty.} = - data[h].key = key - data[h].val = val - data[h].hcode = hc - -proc rawGetKnownHC[A, B](t: Table[A, B], key: A, hc: THash): int {.inline.} = - rawGetKnownHCImpl() - -proc rawGetDeep[A, B](t: Table[A, B], key: A, hc: var THash): int {.inline.} = - rawGetDeepImpl() - -proc rawGet[A, B](t: Table[A, B], key: A, hc: var THash): int {.inline.} = - rawGetImpl() +proc len*[A, B](t: Table[A, B]): int = + ## returns the number of keys in `t`. + result = t.counter proc `[]`*[A, B](t: Table[A, B], key: A): B = ## retrieves the value at ``t[key]``. If `key` is not in `t`, @@ -215,9 +130,35 @@ proc hasKey*[A, B](t: Table[A, B], key: A): bool = var hc: THash result = rawGet(t, key, hc) >= 0 -proc rawInsert[A, B](t: var Table[A, B], data: var KeyValuePairSeq[A, B], - key: A, val: B, hc: THash, h: THash) = - rawInsertImpl() +iterator pairs*[A, B](t: Table[A, B]): (A, B) = + ## iterates over any (key, value) pair in the table `t`. + for h in 0..high(t.data): + if isFilled(t.data[h].hcode): yield (t.data[h].key, t.data[h].val) + +iterator mpairs*[A, B](t: var Table[A, B]): (A, var B) = + ## iterates over any (key, value) pair in the table `t`. The values + ## can be modified. + for h in 0..high(t.data): + if isFilled(t.data[h].hcode): yield (t.data[h].key, t.data[h].val) + +iterator keys*[A, B](t: Table[A, B]): A = + ## iterates over any key in the table `t`. + for h in 0..high(t.data): + if isFilled(t.data[h].hcode): yield t.data[h].key + +iterator values*[A, B](t: Table[A, B]): B = + ## iterates over any value in the table `t`. + for h in 0..high(t.data): + if isFilled(t.data[h].hcode): yield t.data[h].val + +iterator mvalues*[A, B](t: var Table[A, B]): var B = + ## iterates over any value in the table `t`. The values can be modified. + for h in 0..high(t.data): + if isFilled(t.data[h].hcode): yield t.data[h].val + +proc del*[A, B](t: var Table[A, B], key: A) = + ## deletes `key` from hash table `t`. + delImpl() proc enlarge[A, B](t: var Table[A, B]) = var n: KeyValuePairSeq[A, B] @@ -228,81 +169,26 @@ proc enlarge[A, B](t: var Table[A, B]) = var j = -1 - rawGetKnownHC(t, n[i].key, n[i].hcode) rawInsert(t, t.data, n[i].key, n[i].val, n[i].hcode, j) -template addImpl() {.dirty.} = - if mustRehash(len(t.data), t.counter): enlarge(t) - var hc: THash - var j = rawGetDeep(t, key, hc) - rawInsert(t, t.data, key, val, hc, j) - inc(t.counter) - -template maybeRehashPutImpl() {.dirty.} = - if mustRehash(len(t.data), t.counter): - enlarge(t) - index = rawGetKnownHC(t, key, hc) - index = -1 - index # important to transform for mgetOrPutImpl - rawInsert(t, t.data, key, val, hc, index) - inc(t.counter) - -template putImpl() {.dirty.} = - var hc: THash - var index = rawGet(t, key, hc) - if index >= 0: t.data[index].val = val - else: maybeRehashPutImpl() - -template mgetOrPutImpl() {.dirty.} = - var hc: THash - var index = rawGet(t, key, hc) - if index < 0: maybeRehashPutImpl() # not present: insert (flipping index) - result = t.data[index].val # either way return modifiable val - -template hasKeyOrPutImpl() {.dirty.} = - var hc: THash - var index = rawGet(t, key, hc) - if index < 0: - result = false - maybeRehashPutImpl() - else: result = true - proc mgetOrPut*[A, B](t: var Table[A, B], key: A, val: B): var B = ## retrieves value at ``t[key]`` or puts ``val`` if not present, either way ## returning a value which can be modified. - mgetOrPutImpl() + mgetOrPutImpl(enlarge) proc hasKeyOrPut*[A, B](t: var Table[A, B], key: A, val: B): bool = ## returns true iff `key` is in the table, otherwise inserts `value`. - hasKeyOrPutImpl() + hasKeyOrPutImpl(enlarge) proc `[]=`*[A, B](t: var Table[A, B], key: A, val: B) = ## puts a (key, value)-pair into `t`. - putImpl() + putImpl(enlarge) proc add*[A, B](t: var Table[A, B], key: A, val: B) = ## puts a new (key, value)-pair into `t` even if ``t[key]`` already exists. - addImpl() + addImpl(enlarge) -template doWhile(a: expr, b: stmt): stmt = - while true: - b - if not a: break - -proc del*[A, B](t: var Table[A, B], key: A) = - ## deletes `key` from hash table `t`. - var hc: THash - var i = rawGet(t, key, hc) - let msk = high(t.data) - if i >= 0: - t.data[i].hcode = 0 - dec(t.counter) - while true: # KnuthV3 Algo6.4R adapted for i=i+1 instead of i=i-1 - var j = i # The correctness of this depends on (h+1) in nextTry, - var r = j # though may be adaptable to other simple sequences. - t.data[i].hcode = 0 # mark current EMPTY - doWhile ((i >= r and r > j) or (r > j and j > i) or (j > i and i >= r)): - i = (i + 1) and msk # increment mod table size - if isEmpty(t.data[i].hcode): # end of collision cluster; So all done - return - r = t.data[i].hcode and msk # "home" location of key@i - shallowCopy(t.data[j], t.data[i]) # data[j] will be marked EMPTY next loop +proc len*[A, B](t: TableRef[A, B]): int = + ## returns the number of keys in `t`. + result = t.counter proc initTable*[A, B](initialSize=64): Table[A, B] = ## creates a new hash table that is empty. @@ -356,10 +242,6 @@ proc indexBy*[A, B, C](collection: A, index: proc(x: B): C): Table[C, B] = for item in collection: result[index(item)] = item -proc len*[A, B](t: TableRef[A, B]): int = - ## returns the number of keys in `t`. - result = t.counter - iterator pairs*[A, B](t: TableRef[A, B]): (A, B) = ## iterates over any (key, value) pair in the table `t`. for h in 0..high(t.data): @@ -454,8 +336,7 @@ type OrderedKeyValuePair[A, B] = tuple[ hcode: THash, next: int, key: A, val: B] OrderedKeyValuePairSeq[A, B] = seq[OrderedKeyValuePair[A, B]] - OrderedTable* {. - myShallow.}[A, B] = object ## table that remembers insertion order + OrderedTable* [A, B] = object ## table that remembers insertion order data: OrderedKeyValuePairSeq[A, B] counter, first, last: int OrderedTableRef*[A, B] = ref OrderedTable[A, B] @@ -557,20 +438,20 @@ proc enlarge[A, B](t: var OrderedTable[A, B]) = proc `[]=`*[A, B](t: var OrderedTable[A, B], key: A, val: B) = ## puts a (key, value)-pair into `t`. - putImpl() + putImpl(enlarge) proc add*[A, B](t: var OrderedTable[A, B], key: A, val: B) = ## puts a new (key, value)-pair into `t` even if ``t[key]`` already exists. - addImpl() + addImpl(enlarge) proc mgetOrPut*[A, B](t: var OrderedTable[A, B], key: A, val: B): var B = ## retrieves value at ``t[key]`` or puts ``value`` if not present, either way ## returning a value which can be modified. - mgetOrPutImpl() + mgetOrPutImpl(enlarge) proc hasKeyOrPut*[A, B](t: var OrderedTable[A, B], key: A, val: B): bool = ## returns true iff `key` is in the table, otherwise inserts `value`. - hasKeyOrPutImpl() + hasKeyOrPutImpl(enlarge) proc initOrderedTable*[A, B](initialSize=64): OrderedTable[A, B] = ## creates a new ordered hash table that is empty. @@ -741,7 +622,7 @@ proc sort*[A, B](t: OrderedTableRef[A, B], # ------------------------------ count tables ------------------------------- type - CountTable* {.myShallow.}[ + CountTable* [ A] = object ## table that counts the number of each key data: seq[tuple[key: A, val: int]] counter: int diff --git a/lib/pure/selectors.nim b/lib/pure/selectors.nim index 6901ecf58..066d7dd52 100644 --- a/lib/pure/selectors.nim +++ b/lib/pure/selectors.nim @@ -11,11 +11,11 @@ import tables, os, unsigned, hashes -when defined(linux): +when defined(linux): import posix, epoll -elif defined(windows): +elif defined(windows): import winlean -else: +else: import posix proc hash*(x: SocketHandle): THash {.borrow.} @@ -25,22 +25,23 @@ type Event* = enum EvRead, EvWrite, EvError - SelectorKey* = ref object + SelectorKey* = object fd*: SocketHandle events*: set[Event] ## The events which ``fd`` listens for. - data*: RootRef ## User object. + data*: pointer ## User object. ReadyInfo* = tuple[key: SelectorKey, events: set[Event]] + + when defined(nimdoc): type Selector* = ref object ## An object which holds file descriptors to be checked for read/write ## status. - fds: Table[SocketHandle, SelectorKey] proc register*(s: Selector, fd: SocketHandle, events: set[Event], - data: RootRef): SelectorKey {.discardable.} = + data: pointer): SelectorKey {.discardable.} = ## Registers file descriptor ``fd`` to selector ``s`` with a set of TEvent ## ``events``. @@ -57,7 +58,7 @@ when defined(nimdoc): proc select*(s: Selector, timeout: int): seq[ReadyInfo] = ## The ``events`` field of the returned ``key`` contains the original events ## for which the ``fd`` was bound. This is contrary to the ``events`` field - ## of the ``TReadyInfo`` tuple which determines which events are ready + ## of the ``ReadyInfo`` tuple which determines which events are ready ## on the ``fd``. proc newSelector*(): Selector = @@ -72,11 +73,11 @@ when defined(nimdoc): elif defined(linux): type - Selector* = ref object + Selector* = object epollFD: cint events: array[64, epoll_event] - fds: Table[SocketHandle, SelectorKey] - + fds: SharedTable[SocketHandle, SelectorKey] + proc createEventStruct(events: set[Event], fd: SocketHandle): epoll_event = if EvRead in events: result.events = EPOLLIN @@ -84,21 +85,19 @@ elif defined(linux): result.events = result.events or EPOLLOUT result.events = result.events or EPOLLRDHUP result.data.fd = fd.cint - + proc register*(s: Selector, fd: SocketHandle, events: set[Event], - data: RootRef): SelectorKey {.discardable.} = + data: pointer) = var event = createEventStruct(events, fd) if events != {}: if epoll_ctl(s.epollFD, EPOLL_CTL_ADD, fd, addr(event)) != 0: raiseOSError(osLastError()) var key = SelectorKey(fd: fd, events: events, data: data) - + s.fds[fd] = key - result = key - - proc update*(s: Selector, fd: SocketHandle, - events: set[Event]): SelectorKey {.discardable.} = + + proc update*(s: var Selector, fd: SocketHandle, events: set[Event]) = if s.fds[fd].events != events: if events == {}: # This fd is idle -- it should not be registered to epoll. @@ -108,7 +107,7 @@ elif defined(linux): # are therefore constantly ready. (leading to 100% CPU usage). if epoll_ctl(s.epollFD, EPOLL_CTL_DEL, fd, nil) != 0: raiseOSError(osLastError()) - s.fds[fd].events = events + s.fds.mget(fd).events = events else: var event = createEventStruct(events, fd) if s.fds[fd].events == {}: @@ -119,22 +118,20 @@ elif defined(linux): else: if epoll_ctl(s.epollFD, EPOLL_CTL_MOD, fd, addr(event)) != 0: raiseOSError(osLastError()) - s.fds[fd].events = events - - result = s.fds[fd] - - proc unregister*(s: Selector, fd: SocketHandle): SelectorKey {.discardable.} = + s.fds.mget(fd).events = events + + proc unregister*(s: var Selector, fd: SocketHandle) = if epoll_ctl(s.epollFD, EPOLL_CTL_DEL, fd, nil) != 0: let err = osLastError() - if err.cint notin {ENOENT, EBADF}: # TODO: Why do we sometimes get an EBADF? Is this normal? + if err.cint notin {ENOENT, EBADF}: + # TODO: Why do we sometimes get an EBADF? Is this normal? raiseOSError(err) - result = s.fds[fd] s.fds.del(fd) - proc close*(s: Selector) = + proc close*(s: var Selector) = + deinitSharedTable(s.fds) if s.epollFD.close() != 0: raiseOSError(osLastError()) - dealloc(addr s.events) # TODO: Test this - + proc epollHasFd(s: Selector, fd: SocketHandle): bool = result = true var event = createEventStruct(s.fds[fd].events, fd) @@ -142,9 +139,9 @@ elif defined(linux): let err = osLastError() if err.cint in {ENOENT, EBADF}: return false - raiseOSError(osLastError()) - - proc select*(s: Selector, timeout: int): seq[ReadyInfo] = + raiseOSError(err) + + proc select*(s: var Selector, timeout: int): seq[ReadyInfo] = ## ## The ``events`` field of the returned ``key`` contains the original events ## for which the ``fd`` was bound. This is contrary to the ``events`` field @@ -156,11 +153,11 @@ elif defined(linux): let err = osLastError() if err.cint == EINTR: return @[] - raiseOSError(osLastError()) + raiseOSError(err) if evNum == 0: return @[] for i in 0 .. Date: Wed, 6 May 2015 09:20:50 +0200 Subject: [PATCH 0308/1263] development version is 0.11.3 --- lib/system.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/system.nim b/lib/system.nim index a4b053ca7..205a68685 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -1535,7 +1535,7 @@ const NimMinor*: int = 11 ## is the minor number of Nim's version. - NimPatch*: int = 2 + NimPatch*: int = 3 ## is the patch number of Nim's version. NimVersion*: string = $NimMajor & "." & $NimMinor & "." & $NimPatch From 2b0115eb5fdf616a2cf30ec620d5b4dff7bc8e14 Mon Sep 17 00:00:00 2001 From: Araq Date: Tue, 12 May 2015 14:45:50 +0200 Subject: [PATCH 0309/1263] prepare for unidecode Nimble package --- doc/lib.txt | 5 ----- 1 file changed, 5 deletions(-) diff --git a/doc/lib.txt b/doc/lib.txt index f43228151..fd5218b0a 100644 --- a/doc/lib.txt +++ b/doc/lib.txt @@ -123,11 +123,6 @@ String handling Ropes can represent very long strings efficiently; especially concatenation is done in O(1) instead of O(n). -* `unidecode `_ - This module provides Unicode to ASCII transliterations: - It finds the sequence of ASCII characters that is the closest approximation - to the Unicode string. - * `matchers `_ This module contains various string matchers for email addresses, etc. From 3c13508b25da810f5ffabc3d2f34180d51f19ecc Mon Sep 17 00:00:00 2001 From: Araq Date: Wed, 13 May 2015 12:17:11 +0200 Subject: [PATCH 0310/1263] terminal: doc improvments --- lib/pure/terminal.nim | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/lib/pure/terminal.nim b/lib/pure/terminal.nim index 29f700db5..7b4d548fe 100644 --- a/lib/pure/terminal.nim +++ b/lib/pure/terminal.nim @@ -364,7 +364,13 @@ macro styledEcho*(m: varargs[expr]): stmt = result.add(newCall(bindSym"write", bindSym"stdout", newStrLitNode("\n"))) result.add(newCall(bindSym"resetAttributes")) -when not defined(windows): +when defined(nimdoc): + proc getch*(): char = + ## Read a single character from the terminal, blocking until it is entered. + ## The character is not printed to the terminal. This is not available for + ## Windows. + discard +elif not defined(windows): proc getch*(): char = ## Read a single character from the terminal, blocking until it is entered. ## The character is not printed to the terminal. This is not available for From 543ec379755879af7fe543d7b4596a9646d60a92 Mon Sep 17 00:00:00 2001 From: Araq Date: Wed, 13 May 2015 12:19:08 +0200 Subject: [PATCH 0311/1263] get rid of deprecated effects --- lib/core/locks.nim | 24 ++++++------------------ 1 file changed, 6 insertions(+), 18 deletions(-) diff --git a/lib/core/locks.nim b/lib/core/locks.nim index 8a809fc84..92ae24a37 100644 --- a/lib/core/locks.nim +++ b/lib/core/locks.nim @@ -1,7 +1,7 @@ # # # Nim's Runtime Library -# (c) Copyright 2012 Andreas Rumpf +# (c) Copyright 2015 Andreas Rumpf # # See the file "copying.txt", included in this # distribution, for details about the copyright. @@ -15,18 +15,6 @@ type TLock* = TSysLock ## Nim lock; whether this is re-entrant ## or not is unspecified! TCond* = TSysCond ## Nim condition variable - - LockEffect* {.deprecated.} = object of RootEffect ## \ - ## effect that denotes that some lock operation - ## is performed. Deprecated, do not use anymore! - AquireEffect* {.deprecated.} = object of LockEffect ## \ - ## effect that denotes that some lock is - ## acquired. Deprecated, do not use anymore! - ReleaseEffect* {.deprecated.} = object of LockEffect ## \ - ## effect that denotes that some lock is - ## released. Deprecated, do not use anymore! -{.deprecated: [FLock: LockEffect, FAquireLock: AquireEffect, - FReleaseLock: ReleaseEffect].} proc initLock*(lock: var TLock) {.inline.} = ## Initializes the given lock. @@ -36,14 +24,14 @@ proc deinitLock*(lock: var TLock) {.inline.} = ## Frees the resources associated with the lock. deinitSys(lock) -proc tryAcquire*(lock: var TLock): bool = +proc tryAcquire*(lock: var TLock): bool = ## Tries to acquire the given lock. Returns `true` on success. result = tryAcquireSys(lock) proc acquire*(lock: var TLock) = ## Acquires the given lock. acquireSys(lock) - + proc release*(lock: var TLock) = ## Releases the given lock. releaseSys(lock) @@ -58,10 +46,10 @@ proc deinitCond*(cond: var TCond) {.inline.} = deinitSysCond(cond) proc wait*(cond: var TCond, lock: var TLock) {.inline.} = - ## waits on the condition variable `cond`. + ## waits on the condition variable `cond`. waitSysCond(cond, lock) - + proc signal*(cond: var TCond) {.inline.} = - ## sends a signal to the condition variable `cond`. + ## sends a signal to the condition variable `cond`. signalSysCond(cond) From 8d508162e88aff8b86b7320c1d84de129692a401 Mon Sep 17 00:00:00 2001 From: Araq Date: Thu, 28 May 2015 12:50:46 +0200 Subject: [PATCH 0312/1263] added missing test --- tests/js/trefbyvar.nim | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 tests/js/trefbyvar.nim diff --git a/tests/js/trefbyvar.nim b/tests/js/trefbyvar.nim new file mode 100644 index 000000000..68dd36543 --- /dev/null +++ b/tests/js/trefbyvar.nim @@ -0,0 +1,35 @@ +discard """ + output: '''0 +5 +0 +5''' +""" + +# bug #2476 + +type A = ref object + m: int + +proc f(a: var A) = + var b: A + b.new() + b.m = 5 + a = b + +var t: A +t.new() + +echo t.m +t.f() +echo t.m + +proc main = + # now test the same for locals + var t: A + t.new() + + echo t.m + t.f() + echo t.m + +main() From 2d2eca18b8c326f1e3ea9101d00b3370c8c5c290 Mon Sep 17 00:00:00 2001 From: Araq Date: Thu, 28 May 2015 12:59:40 +0200 Subject: [PATCH 0313/1263] bootstrap.sh: cannot keep exec bit on windows --- bootstrap.sh | 0 1 file changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 bootstrap.sh diff --git a/bootstrap.sh b/bootstrap.sh old mode 100755 new mode 100644 From e65ccfb8f5123988ce3a1c204fc72a98c76fce34 Mon Sep 17 00:00:00 2001 From: yglukhov Date: Thu, 28 May 2015 11:24:39 +0300 Subject: [PATCH 0314/1263] Removed formatting from logging. --- lib/pure/logging.nim | 52 +++++++++++++++++++------------------------- web/news.txt | 5 +++++ 2 files changed, 27 insertions(+), 30 deletions(-) diff --git a/lib/pure/logging.nim b/lib/pure/logging.nim index cc5340211..36bb5e92c 100644 --- a/lib/pure/logging.nim +++ b/lib/pure/logging.nim @@ -112,27 +112,22 @@ proc substituteLog(frmt: string): string = of "appname": result.add(app.splitFile.name) else: discard -method log*(logger: Logger, level: Level, - frmt: string, args: varargs[string, `$`]) {. +method log*(logger: Logger, level: Level, args: varargs[string, `$`]) {. raises: [Exception], tags: [TimeEffect, WriteIOEffect, ReadIOEffect].} = ## Override this method in custom loggers. Default implementation does ## nothing. discard -method log*(logger: ConsoleLogger, level: Level, - frmt: string, args: varargs[string, `$`]) = +method log*(logger: ConsoleLogger, level: Level, args: varargs[string, `$`]) = ## Logs to the console using ``logger`` only. if level >= logger.levelThreshold: - writeln(stdout, LevelNames[level], " ", substituteLog(logger.fmtStr), - frmt % args) + writeln(stdout, LevelNames[level], " ", substituteLog(logger.fmtStr), args) -method log*(logger: FileLogger, level: Level, - frmt: string, args: varargs[string, `$`]) = +method log*(logger: FileLogger, level: Level, args: varargs[string, `$`]) = ## Logs to a file using ``logger`` only. if level >= logger.levelThreshold: - writeln(logger.f, LevelNames[level], " ", - substituteLog(logger.fmtStr), frmt % args) + writeln(logger.f, LevelNames[level], " ", substituteLog(logger.fmtStr), args) proc defaultFilename*(): string = ## Returns the default filename for a logger. @@ -206,8 +201,7 @@ proc rotate(logger: RollingFileLogger) = moveFile(dir / (name & ext & srcSuff), dir / (name & ext & ExtSep & $(i+1))) -method log*(logger: RollingFileLogger, level: Level, - frmt: string, args: varargs[string, `$`]) = +method log*(logger: RollingFileLogger, level: Level, args: varargs[string, `$`]) = ## Logs to a file using rolling ``logger`` only. if level >= logger.levelThreshold: if logger.curLine >= logger.maxLines: @@ -217,7 +211,7 @@ method log*(logger: RollingFileLogger, level: Level, logger.curLine = 0 logger.f = open(logger.baseName, logger.baseMode) - writeln(logger.f, LevelNames[level], " ",substituteLog(logger.fmtStr), frmt % args) + writeln(logger.f, LevelNames[level], " ", substituteLog(logger.fmtStr), args) logger.curLine.inc # -------- @@ -225,39 +219,39 @@ method log*(logger: RollingFileLogger, level: Level, var level {.threadvar.}: Level ## global log filter var handlers {.threadvar.}: seq[Logger] ## handlers with their own log levels -proc logLoop(level: Level, frmt: string, args: varargs[string, `$`]) = +proc logLoop(level: Level, args: varargs[string, `$`]) = for logger in items(handlers): if level >= logger.levelThreshold: - log(logger, level, frmt, args) + log(logger, level, args) -template log*(level: Level, frmt: string, args: varargs[string, `$`]) = +template log*(level: Level, args: varargs[string, `$`]) = ## Logs a message to all registered handlers at the given level. bind logLoop bind `%` bind logging.level if level >= logging.level: - logLoop(level, frmt, args) + logLoop(level, args) -template debug*(frmt: string, args: varargs[string, `$`]) = +template debug*(args: varargs[string, `$`]) = ## Logs a debug message to all registered handlers. - log(lvlDebug, frmt, args) + log(lvlDebug, args) -template info*(frmt: string, args: varargs[string, `$`]) = +template info*(args: varargs[string, `$`]) = ## Logs an info message to all registered handlers. - log(lvlInfo, frmt, args) + log(lvlInfo, args) -template warn*(frmt: string, args: varargs[string, `$`]) = +template warn*(args: varargs[string, `$`]) = ## Logs a warning message to all registered handlers. - log(lvlWarn, frmt, args) + log(lvlWarn, args) -template error*(frmt: string, args: varargs[string, `$`]) = +template error*(args: varargs[string, `$`]) = ## Logs an error message to all registered handlers. - log(lvlError, frmt, args) + log(lvlError, args) -template fatal*(frmt: string, args: varargs[string, `$`]) = +template fatal*(args: varargs[string, `$`]) = ## Logs a fatal error message to all registered handlers. - log(lvlFatal, frmt, args) + log(lvlFatal, args) proc addHandler*(handler: Logger) = ## Adds ``handler`` to the list of handlers. @@ -286,6 +280,4 @@ when not defined(testing) and isMainModule: addHandler(fL) addHandler(rL) for i in 0 .. 25: - info("hello" & $i, []) - - + info("hello", i) diff --git a/web/news.txt b/web/news.txt index 22ea03157..6a82b3f26 100644 --- a/web/news.txt +++ b/web/news.txt @@ -14,6 +14,11 @@ News during object initialization or as a named parameter of ``initInterval()`` will need to be updated. + - ``std.logging`` functions no longer do formatting and semantically treat + their arguments just like ``echo`` does. Affected functions: ``log``, + ``debug``, ``info``, ``warn``, ``error``, ``fatal``. Custom subtypes of + ``Logger`` also need to be adjusted accordingly. + Language Additions ------------------ From 4fcf5adfe2460601bd97b13d3efb3a783ac50623 Mon Sep 17 00:00:00 2001 From: Stephan Diehl Date: Thu, 28 May 2015 15:25:09 +0200 Subject: [PATCH 0315/1263] fix for https://github.com/nim-lang/Aporia/issues/69 --- lib/pure/encodings.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/pure/encodings.nim b/lib/pure/encodings.nim index 2a6134615..78baec3de 100644 --- a/lib/pure/encodings.nim +++ b/lib/pure/encodings.nim @@ -262,7 +262,7 @@ else: else: const iconvDll = "(libc.so.6|libiconv.so)" - when defined(macosx) and defined(powerpc): + when defined(macosx): const prefix = "lib" else: const prefix = "" From c5f7d553e969bd90223570059c199c8459b16a54 Mon Sep 17 00:00:00 2001 From: yglukhov Date: Wed, 27 May 2015 16:48:10 +0300 Subject: [PATCH 0316/1263] Perform lambda lifting for compile-time stuff when targeting JS. Enable unittest test. --- compiler/lambdalifting.nim | 6 +++++- lib/pure/unittest.nim | 9 ++++----- tests/js/tunittests.nim | 5 +---- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/compiler/lambdalifting.nim b/compiler/lambdalifting.nim index c68bc352c..69b45c980 100644 --- a/compiler/lambdalifting.nim +++ b/compiler/lambdalifting.nim @@ -946,7 +946,11 @@ proc transformOuterProc(o: POuterContext, n: PNode; it: TIter): PNode = proc liftLambdas*(fn: PSym, body: PNode): PNode = # XXX gCmd == cmdCompileToJS does not suffice! The compiletime stuff needs # the transformation even when compiling to JS ... - if body.kind == nkEmpty or gCmd == cmdCompileToJS or + + # However we can do lifting for the stuff which is *only* compiletime. + let isCompileTime = sfCompileTime in fn.flags or fn.kind == skMacro + + if body.kind == nkEmpty or (gCmd == cmdCompileToJS and not isCompileTime) or fn.skipGenericOwner.kind != skModule: # ignore forward declaration: result = body diff --git a/lib/pure/unittest.nim b/lib/pure/unittest.nim index 092b1fba2..dbbd3cabc 100644 --- a/lib/pure/unittest.nim +++ b/lib/pure/unittest.nim @@ -99,8 +99,9 @@ template test*(name: expr, body: stmt): stmt {.immediate, dirty.} = body except: - checkpoint("Unhandled exception: " & getCurrentExceptionMsg()) - echo getCurrentException().getStackTrace() + when not defined(js): + checkpoint("Unhandled exception: " & getCurrentExceptionMsg()) + echo getCurrentException().getStackTrace() fail() finally: @@ -114,9 +115,7 @@ proc checkpoint*(msg: string) = template fail* = bind checkpoints for msg in items(checkpoints): - # this used to be 'echo' which now breaks due to a bug. XXX will revisit - # this issue later. - stdout.writeln msg + echo msg when not defined(ECMAScript): if abortOnError: quit(1) diff --git a/tests/js/tunittests.nim b/tests/js/tunittests.nim index 8a264a5e0..4b09c99a9 100644 --- a/tests/js/tunittests.nim +++ b/tests/js/tunittests.nim @@ -1,10 +1,7 @@ discard """ - disabled: "true" + output: '''[OK] >:)''' """ -# Unittest uses lambdalifting at compile-time which we disable for the JS -# codegen! So this cannot and will not work for quite some time. - import unittest suite "Bacon": From af07db28297e0d4d03a1c1e64da524b0119d62fe Mon Sep 17 00:00:00 2001 From: boopcat Date: Sat, 30 May 2015 11:01:15 +0000 Subject: [PATCH 0317/1263] Export newSocket(fd) from net.nim and standardize args in net/asyncnet Exporting newSocket(fd) mimics what asyncnet does and lets you pass in your own socket FD. newSocket*(fd) and newAsyncSocket*(fd) now both take "buffered" instead of "isBuff" and defaults to true to match the other constructors on both. --- lib/pure/asyncnet.nim | 6 +++--- lib/pure/net.nim | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/lib/pure/asyncnet.nim b/lib/pure/asyncnet.nim index aadbde824..e759f9788 100644 --- a/lib/pure/asyncnet.nim +++ b/lib/pure/asyncnet.nim @@ -91,13 +91,13 @@ type # TODO: Save AF, domain etc info and reuse it in procs which need it like connect. -proc newAsyncSocket*(fd: TAsyncFD, isBuff: bool): AsyncSocket = +proc newAsyncSocket*(fd: TAsyncFD, buffered = true): AsyncSocket = ## Creates a new ``AsyncSocket`` based on the supplied params. assert fd != osInvalidSocket.TAsyncFD new(result) result.fd = fd.SocketHandle - result.isBuffered = isBuff - if isBuff: + result.isBuffered = buffered + if buffered: result.currPos = 0 proc newAsyncSocket*(domain: Domain = AF_INET, typ: SockType = SOCK_STREAM, diff --git a/lib/pure/net.nim b/lib/pure/net.nim index cf37c271e..1990818e5 100644 --- a/lib/pure/net.nim +++ b/lib/pure/net.nim @@ -118,13 +118,13 @@ proc toOSFlags*(socketFlags: set[SocketFlag]): cint = result = result or MSG_PEEK of SocketFlag.SafeDisconn: continue -proc newSocket(fd: SocketHandle, isBuff: bool): Socket = +proc newSocket*(fd: SocketHandle, buffered = true): Socket = ## Creates a new socket as specified by the params. assert fd != osInvalidSocket new(result) result.fd = fd - result.isBuffered = isBuff - if isBuff: + result.isBuffered = buffered + if buffered: result.currPos = 0 proc newSocket*(domain, typ, protocol: cint, buffered = true): Socket = From 49b953533a05c984524daec359dbfb692a692eab Mon Sep 17 00:00:00 2001 From: Oscar Campbell Date: Sun, 31 May 2015 00:56:27 +0200 Subject: [PATCH 0318/1263] Fix #2523 - first commit. Needs some cleanup. --- compiler/lexer.nim | 302 ++++++++++++++++++++++++++++++--------------- 1 file changed, 204 insertions(+), 98 deletions(-) diff --git a/compiler/lexer.nim b/compiler/lexer.nim index 8080e0e8c..bdbaa79b1 100644 --- a/compiler/lexer.nim +++ b/compiler/lexer.nim @@ -240,12 +240,43 @@ proc matchUnderscoreChars(L: var TLexer, tok: var TToken, chars: set[char]) = break if buf[pos] == '_': if buf[pos+1] notin chars: - lexMessage(L, errInvalidToken, "_") + lexMessage(L, errInvalidToken, "_") # TODO/ozra - lift out for better msg break add(tok.literal, '_') inc(pos) L.bufpos = pos +# Used for getting human friendlier err messages. Also only used in getNumber +proc matchAllLiteralishForMessage(L: var TLexer, tok: var TToken, startpos: int) = + # Note: high(int32)): if result.tokType == tkIntLit: result.tokType = tkInt64Lit elif result.tokType in {tkInt8Lit, tkInt16Lit, tkInt32Lit}: - lexMessage(L, errNumberOutOfRange, result.literal) + lexLiteralNumberMessage(L, errNumberOutOfRange, startpos) elif result.tokType == tkInt8Lit and (result.iNumber < int8.low or result.iNumber > int8.high): - lexMessage(L, errNumberOutOfRange, result.literal) + lexLiteralNumberMessage(L, errNumberOutOfRange, startpos) elif result.tokType == tkInt16Lit and (result.iNumber < int16.low or result.iNumber > int16.high): - lexMessage(L, errNumberOutOfRange, result.literal) + lexLiteralNumberMessage(L, errNumberOutOfRange, startpos) + except ValueError: - lexMessage(L, errInvalidNumber, result.literal) + lexLiteralNumberMessage(L, errInvalidNumber, startpos) except OverflowError, RangeError: - lexMessage(L, errNumberOutOfRange, result.literal) - L.bufpos = endpos + lexLiteralNumberMessage(L, errNumberOutOfRange, startpos) + + L.bufpos = postPos proc handleHexChar(L: var TLexer, xi: var int) = case L.buf[L.bufpos] From 1b4db5a34caf301995b3c08eb9a1e3b75c54a9ba Mon Sep 17 00:00:00 2001 From: Oscar Campbell Date: Sun, 31 May 2015 01:31:06 +0200 Subject: [PATCH 0319/1263] Implement #2811 - Unicode en-dash (U+2013) as hump/snake alt. --- compiler/idents.nim | 4 +++- compiler/lexer.nim | 20 ++++++++++++++++---- lib/pure/hashes.nim | 12 ++++++++++-- 3 files changed, 29 insertions(+), 7 deletions(-) diff --git a/compiler/idents.nim b/compiler/idents.nim index 0cca18929..5216b109f 100644 --- a/compiler/idents.nim +++ b/compiler/idents.nim @@ -12,7 +12,7 @@ # id. This module is essential for the compiler's performance. import - hashes, strutils + hashes, strutils, etcpriv type TIdObj* = object of RootObj @@ -37,6 +37,8 @@ proc cmpIgnoreStyle(a, b: cstring, blen: int): int = while j < blen: while a[i] == '_': inc(i) while b[j] == '_': inc(j) + while isMagicIdentSeparatorRune(a, i): inc(i, magicIdentSeparatorRuneByteWidth) + while isMagicIdentSeparatorRune(b, j): inc(j, magicIdentSeparatorRuneByteWidth) # tolower inlined: var aa = a[i] var bb = b[j] diff --git a/compiler/lexer.nim b/compiler/lexer.nim index 8080e0e8c..c37b4deba 100644 --- a/compiler/lexer.nim +++ b/compiler/lexer.nim @@ -17,7 +17,7 @@ import hashes, options, msgs, strutils, platform, idents, nimlexbase, llstream, - wordrecg + wordrecg, etcpriv const MaxLineLength* = 80 # lines longer than this lead to a warning @@ -143,7 +143,8 @@ proc isNimIdentifier*(s: string): bool = while i < s.len: if s[i] == '_': inc(i) - if s[i] notin SymChars: return + elif isMagicIdentSeparatorRune(cstring s, i): + inc(i, magicIdentSeparatorRuneByteWidth) if s[i] notin SymChars: return inc(i) result = true @@ -632,16 +633,27 @@ proc getSymbol(L: var TLexer, tok: var TToken) = var c = buf[pos] case c of 'a'..'z', '0'..'9', '\x80'..'\xFF': - h = h !& ord(c) + if c == '\226' and + buf[pos+1] == '\128' and + buf[pos+2] == '\147': # It's a 'magic separator' en-dash Unicode + if buf[pos + magicIdentSeparatorRuneByteWidth] notin SymChars: + lexMessage(L, errInvalidToken, "·") + break + inc(pos, magicIdentSeparatorRuneByteWidth) + else: + h = h !& ord(c) + inc(pos) of 'A'..'Z': c = chr(ord(c) + (ord('a') - ord('A'))) # toLower() h = h !& ord(c) + inc(pos) of '_': if buf[pos+1] notin SymChars: lexMessage(L, errInvalidToken, "_") break + inc(pos) + else: break - inc(pos) h = !$h tok.ident = getIdent(addr(L.buf[L.bufpos]), pos - L.bufpos, h) L.bufpos = pos diff --git a/lib/pure/hashes.nim b/lib/pure/hashes.nim index 2ce8ac796..c6af8f918 100644 --- a/lib/pure/hashes.nim +++ b/lib/pure/hashes.nim @@ -38,7 +38,7 @@ ## result = !$h import - strutils + strutils, etcpriv type THash* = int ## a hash value; hash tables using these values should @@ -124,13 +124,21 @@ proc hash*(x: string): THash = proc hashIgnoreStyle*(x: string): THash = ## efficient hashing of strings; style is ignored var h: THash = 0 - for i in 0..x.len-1: + var i = 0 + let xLen = x.len + while i < xLen: var c = x[i] if c == '_': + inc(i) continue # skip _ + if isMagicIdentSeparatorRune(cstring(x), i): + inc(i, magicIdentSeparatorRuneByteWidth) + continue # skip '·' (unicode middle dot) if c in {'A'..'Z'}: c = chr(ord(c) + (ord('a') - ord('A'))) # toLower() h = h !& ord(c) + inc(i) + result = !$h proc hashIgnoreCase*(x: string): THash = From d35887e492613e646f4fcc04f8314cc897afe793 Mon Sep 17 00:00:00 2001 From: Oscar Campbell Date: Sun, 31 May 2015 01:32:50 +0200 Subject: [PATCH 0320/1263] Util funcs used by lib/hashes.nim and compiler/lexer.nim --- lib/pure/etcpriv.nim | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 lib/pure/etcpriv.nim diff --git a/lib/pure/etcpriv.nim b/lib/pure/etcpriv.nim new file mode 100644 index 000000000..e7a525e4d --- /dev/null +++ b/lib/pure/etcpriv.nim @@ -0,0 +1,23 @@ +# +# +# Nim's Runtime Library +# (c) Copyright 2015 Nim Authors +# +# See the file "copying.txt", included in this +# distribution, for details about the copyright. +# + +## This module contains utils that are less then easy to categorize and +## don't really warrant a specific module. They are private to compiler +## and stdlib usage, and should not be used outside of that - they may +## change or disappear at any time. + + +# Used by pure/hashes.nim, and the compiler parsing +const magicIdentSeparatorRuneByteWidth* = 3 + +# Used by pure/hashes.nim, and the compiler parsing +proc isMagicIdentSeparatorRune*(cs: cstring, i: int): bool {. inline } = + result = cs[i] == '\226' and + cs[i + 1] == '\128' and + cs[i + 2] == '\147' # en-dash # 145 = nb-hyphen From 6a43b0e81721919d864ce053e0c0c624ba8c0127 Mon Sep 17 00:00:00 2001 From: Oscar Campbell Date: Sun, 31 May 2015 02:55:06 +0200 Subject: [PATCH 0321/1263] Clean up to compiler style. Refine error-msg for illegal octal 'O' --- compiler/lexer.nim | 188 +++++++++++++++------------------------------ compiler/msgs.nim | 8 +- 2 files changed, 68 insertions(+), 128 deletions(-) diff --git a/compiler/lexer.nim b/compiler/lexer.nim index bdbaa79b1..e1615ac36 100644 --- a/compiler/lexer.nim +++ b/compiler/lexer.nim @@ -229,54 +229,6 @@ proc lexMessagePos(L: var TLexer, msg: TMsgKind, pos: int, arg = "") = var info = newLineInfo(L.fileIdx, L.lineNumber, pos - L.lineStart) L.dispMessage(info, msg, arg) -proc matchUnderscoreChars(L: var TLexer, tok: var TToken, chars: set[char]) = - var pos = L.bufpos # use registers for pos, buf - var buf = L.buf - while true: - if buf[pos] in chars: - add(tok.literal, buf[pos]) - inc(pos) - else: - break - if buf[pos] == '_': - if buf[pos+1] notin chars: - lexMessage(L, errInvalidToken, "_") # TODO/ozra - lift out for better msg - break - add(tok.literal, '_') - inc(pos) - L.bufpos = pos - -# Used for getting human friendlier err messages. Also only used in getNumber -proc matchAllLiteralishForMessage(L: var TLexer, tok: var TToken, startpos: int) = - # Note: high(int32)): if result.tokType == tkIntLit: result.tokType = tkInt64Lit elif result.tokType in {tkInt8Lit, tkInt16Lit, tkInt32Lit}: - lexLiteralNumberMessage(L, errNumberOutOfRange, startpos) + lexMessageLitNum(L, errNumberOutOfRange, startpos) elif result.tokType == tkInt8Lit and (result.iNumber < int8.low or result.iNumber > int8.high): - lexLiteralNumberMessage(L, errNumberOutOfRange, startpos) + lexMessageLitNum(L, errNumberOutOfRange, startpos) elif result.tokType == tkInt16Lit and (result.iNumber < int16.low or result.iNumber > int16.high): - lexLiteralNumberMessage(L, errNumberOutOfRange, startpos) - + lexMessageLitNum(L, errNumberOutOfRange, startpos) except ValueError: - lexLiteralNumberMessage(L, errInvalidNumber, startpos) + lexMessageLitNum(L, errInvalidNumber, startpos) except OverflowError, RangeError: - lexLiteralNumberMessage(L, errNumberOutOfRange, startpos) - + lexMessageLitNum(L, errNumberOutOfRange, startpos) L.bufpos = postPos proc handleHexChar(L: var TLexer, xi: var int) = diff --git a/compiler/msgs.nim b/compiler/msgs.nim index 041a181be..e97032db4 100644 --- a/compiler/msgs.nim +++ b/compiler/msgs.nim @@ -17,10 +17,9 @@ type errIntLiteralExpected, errInvalidCharacterConstant, errClosingTripleQuoteExpected, errClosingQuoteExpected, errTabulatorsAreNotAllowed, errInvalidToken, errLineTooLong, - errInvalidNumber, errNumberOutOfRange, errNnotAllowedInCharacter, - errClosingBracketExpected, errMissingFinalQuote, errIdentifierExpected, - errNewlineExpected, - errInvalidModuleName, + errInvalidNumber, errInvalidNumberOctalCode, errNumberOutOfRange, + errNnotAllowedInCharacter, errClosingBracketExpected, errMissingFinalQuote, + errIdentifierExpected, errNewlineExpected, errInvalidModuleName, errOperatorExpected, errTokenExpected, errStringAfterIncludeExpected, errRecursiveDependencyX, errOnOrOffExpected, errNoneSpeedOrSizeExpected, errInvalidPragma, errUnknownPragma, errInvalidDirectiveX, @@ -143,6 +142,7 @@ const errInvalidToken: "invalid token: $1", errLineTooLong: "line too long", errInvalidNumber: "$1 is not a valid number", + errInvalidNumberOctalCode: "$1 is not a valid number; did you mean octal? Then use one of '0o', '0c' or '0C'.", errNumberOutOfRange: "number $1 out of valid range", errNnotAllowedInCharacter: "\\n not allowed in character literal", errClosingBracketExpected: "closing ']' expected, but end of file reached", From 4a1e45e3f85c668185971627849e4420c72af767 Mon Sep 17 00:00:00 2001 From: Oscar Campbell Date: Sun, 31 May 2015 03:11:44 +0200 Subject: [PATCH 0322/1263] Remove forgotten debug echo statement. --- compiler/lexer.nim | 1 - 1 file changed, 1 deletion(-) diff --git a/compiler/lexer.nim b/compiler/lexer.nim index e1615ac36..bc4b46bc9 100644 --- a/compiler/lexer.nim +++ b/compiler/lexer.nim @@ -414,7 +414,6 @@ proc getNumber(L: var TLexer): TToken = # Is there still a literalish char awaiting? Then it's an error! if L.buf[postPos] in literalishCharsNoDot or (L.buf[postPos] == '.' and L.buf[postPos + 1] in {'0'..'9'}): - echo "likely literal error, additionally: '", L.buf[postPos], L.buf[postPos+1], L.buf[postPos+2], L.buf[postPos+3], "', ", postPos lexMessageLitNum(L, errInvalidNumber, startpos) # Third stage, extract actual number L.bufpos = startpos # restore position From 9fcd5252c79b982d90b5c17f81253c2951acac1f Mon Sep 17 00:00:00 2001 From: Oscar Campbell Date: Sun, 31 May 2015 03:59:31 +0200 Subject: [PATCH 0323/1263] Fix doc for #2523, regarding numeric literals. --- doc/manual/lexing.txt | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/doc/manual/lexing.txt b/doc/manual/lexing.txt index ab1cd632d..fab6da416 100644 --- a/doc/manual/lexing.txt +++ b/doc/manual/lexing.txt @@ -276,7 +276,7 @@ Numerical constants are of a single type and have the form:: bindigit = '0'..'1' HEX_LIT = '0' ('x' | 'X' ) hexdigit ( ['_'] hexdigit )* DEC_LIT = digit ( ['_'] digit )* - OCT_LIT = '0o' octdigit ( ['_'] octdigit )* + OCT_LIT = '0' ('o' | 'c' | 'C') octdigit ( ['_'] octdigit )* BIN_LIT = '0' ('b' | 'B' ) bindigit ( ['_'] bindigit )* INT_LIT = HEX_LIT @@ -297,15 +297,17 @@ Numerical constants are of a single type and have the form:: exponent = ('e' | 'E' ) ['+' | '-'] digit ( ['_'] digit )* FLOAT_LIT = digit (['_'] digit)* (('.' (['_'] digit)* [exponent]) |exponent) - FLOAT32_LIT = HEX_LIT '\'' ('f'|'F') '32' - | (FLOAT_LIT | DEC_LIT | OCT_LIT | BIN_LIT) ['\''] ('f'|'F') '32' - FLOAT64_LIT = HEX_LIT '\'' ('f'|'F') '64' - | (FLOAT_LIT | DEC_LIT | OCT_LIT | BIN_LIT) ['\''] ('f'|'F') '64' + FLOAT32_SUFFIX = ('f' | 'F') ['32'] + FLOAT32_LIT = HEX_LIT '\'' FLOAT32_SUFFIX + | (FLOAT_LIT | DEC_LIT | OCT_LIT | BIN_LIT) ['\''] FLOAT32_SUFFIX + FLOAT64_SUFFIX = ( ('f' | 'F') '64' ) | 'd' | 'D' + FLOAT64_LIT = HEX_LIT '\'' FLOAT64_SUFFIX + | (FLOAT_LIT | DEC_LIT | OCT_LIT | BIN_LIT) ['\''] FLOAT64_SUFFIX As can be seen in the productions, numerical constants can contain underscores for readability. Integer and floating point literals may be given in decimal (no -prefix), binary (prefix ``0b``), octal (prefix ``0o``) and hexadecimal +prefix), binary (prefix ``0b``), octal (prefix ``0o`` or ``0c``) and hexadecimal (prefix ``0x``) notation. There exists a literal for each numerical type that is @@ -331,8 +333,11 @@ The type suffixes are: ``'u16`` uint16 ``'u32`` uint32 ``'u64`` uint64 + ``'f`` float32 + ``'d`` float64 ``'f32`` float32 ``'f64`` float64 + ``'f128`` float128 ================= ========================= Floating point literals may also be in binary, octal or hexadecimal @@ -344,8 +349,8 @@ is approximately 1.72826e35 according to the IEEE floating point standard. Operators --------- -In Nim one can define his own operators. An operator is any -combination of the following characters:: +Nim allows user defined operators. An operator is any combination of the +following characters:: = + - * / < > @ $ ~ & % | @@ -355,7 +360,7 @@ These keywords are also operators: ``and or not xor shl shr div mod in notin is isnot of``. `=`:tok:, `:`:tok:, `::`:tok: are not available as general operators; they -are used for other notational purposes. +are used for other notational purposes. ``*:`` is as a special case the two tokens `*`:tok: and `:`:tok: (to support ``var v*: T``). From 50e96ad939c39c9d9e25b75803ed971fad49dc8f Mon Sep 17 00:00:00 2001 From: Stefan Talpalaru Date: Sun, 31 May 2015 19:07:44 +0200 Subject: [PATCH 0324/1263] the Go GC - initial implementation --- compiler/commands.nim | 7 +- compiler/options.nim | 2 +- doc/advopt.txt | 2 +- doc/koch.txt | 2 +- lib/core/typeinfo.nim | 4 +- lib/system.nim | 8 +- lib/system/mmdisp.nim | 194 ++++++++++++++++++++++++++++++++++++++++- lib/system/repr.nim | 2 +- lib/system/sysstr.nim | 2 +- lib/system/threads.nim | 6 +- 10 files changed, 213 insertions(+), 16 deletions(-) diff --git a/compiler/commands.nim b/compiler/commands.nim index d30d8326c..d0719a420 100644 --- a/compiler/commands.nim +++ b/compiler/commands.nim @@ -22,6 +22,7 @@ bootSwitch(usedNoCaas, defined(noCaas), "-d:noCaas") bootSwitch(usedBoehm, defined(boehmgc), "--gc:boehm") bootSwitch(usedMarkAndSweep, defined(gcmarkandsweep), "--gc:markAndSweep") bootSwitch(usedGenerational, defined(gcgenerational), "--gc:generational") +bootSwitch(usedGoGC, defined(gogc), "--gc:go") bootSwitch(usedNoGC, defined(nogc), "--gc:none") import @@ -86,7 +87,7 @@ proc writeVersionInfo(pass: TCmdLinePass) = msgWriteln("active boot switches:" & usedRelease & usedAvoidTimeMachine & usedTinyC & usedGnuReadline & usedNativeStacktrace & usedNoCaas & - usedFFI & usedBoehm & usedMarkAndSweep & usedGenerational & usedNoGC) + usedFFI & usedBoehm & usedMarkAndSweep & usedGenerational & usedGoGC & usedNoGC) msgQuit(0) var @@ -181,6 +182,7 @@ proc testCompileOptionArg*(switch, arg: string, info: TLineInfo): bool = of "v2": result = gSelectedGC == gcV2 of "markandsweep": result = gSelectedGC == gcMarkAndSweep of "generational": result = gSelectedGC == gcGenerational + of "go": result = gSelectedGC == gcGo of "none": result = gSelectedGC == gcNone else: localError(info, errNoneBoehmRefcExpectedButXFound, arg) of "opt": @@ -365,6 +367,9 @@ proc processSwitch(switch, arg: string, pass: TCmdLinePass, info: TLineInfo) = of "generational": gSelectedGC = gcGenerational defineSymbol("gcgenerational") + of "go": + gSelectedGC = gcGo + defineSymbol("gogc") of "none": gSelectedGC = gcNone defineSymbol("nogc") diff --git a/compiler/options.nim b/compiler/options.nim index b3060a180..b0e711a44 100644 --- a/compiler/options.nim +++ b/compiler/options.nim @@ -81,7 +81,7 @@ type # please make sure we have under 32 options cmdRun # run the project via TCC backend TStringSeq* = seq[string] TGCMode* = enum # the selected GC - gcNone, gcBoehm, gcMarkAndSweep, gcRefc, gcV2, gcGenerational + gcNone, gcBoehm, gcGo, gcMarkAndSweep, gcRefc, gcV2, gcGenerational IdeCmd* = enum ideNone, ideSug, ideCon, ideDef, ideUse diff --git a/doc/advopt.txt b/doc/advopt.txt index 195122cc7..a4f72e2d8 100644 --- a/doc/advopt.txt +++ b/doc/advopt.txt @@ -58,7 +58,7 @@ Advanced options: --skipUserCfg do not read the user's configuration file --skipParentCfg do not read the parent dirs' configuration files --skipProjCfg do not read the project's configuration file - --gc:refc|v2|markAndSweep|boehm|none + --gc:refc|v2|markAndSweep|boehm|go|none select the GC to use; default is 'refc' --index:on|off turn index file generation on|off --putenv:key=value set an environment variable diff --git a/doc/koch.txt b/doc/koch.txt index 7da137458..a58d386ea 100644 --- a/doc/koch.txt +++ b/doc/koch.txt @@ -71,7 +71,7 @@ options: are limited to pure Nim code at compilation time. Enabling this switch will allow macros to execute non-nim code at compilation time (eg. open a file and write to it). ---gc:refc|v2|markAndSweep|boehm|none +--gc:refc|v2|markAndSweep|boehm|go|none Selects which garbage collection strategy to use for the compiler and generated code. See the `Nim's Garbage Collector `_ documentation for more information. diff --git a/lib/core/typeinfo.nim b/lib/core/typeinfo.nim index c3ff66591..1a7e2d60f 100644 --- a/lib/core/typeinfo.nim +++ b/lib/core/typeinfo.nim @@ -67,11 +67,11 @@ type pbyteArray = ptr array[0.. 0xffff, int8] TGenericSeq {.importc.} = object - len, space: int + len, space, elemSize: int PGenSeq = ptr TGenericSeq const - GenericSeqSize = (2 * sizeof(int)) + GenericSeqSize = (3 * sizeof(int)) proc genericAssign(dest, src: pointer, mt: PNimType) {.importCompilerProc.} proc genericShallowAssign(dest, src: pointer, mt: PNimType) {. diff --git a/lib/system.nim b/lib/system.nim index 205a68685..b2f68b588 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -304,7 +304,7 @@ const ArrayDummySize = when defined(cpu16): 10_000 else: 100_000_000 when not defined(JS): type TGenericSeq {.compilerproc, pure, inheritable.} = object - len, reserved: int + len, reserved, elemSize: int PGenericSeq {.exportc.} = ptr TGenericSeq UncheckedCharArray {.unchecked.} = array[0..ArrayDummySize, char] # len and space without counting the terminating zero: @@ -1068,7 +1068,7 @@ proc compileOption*(option, arg: string): bool {. const hasThreadSupport = compileOption("threads") - hasSharedHeap = defined(boehmgc) # don't share heaps; every thread has its own + hasSharedHeap = defined(boehmgc) or defined(gogc) # don't share heaps; every thread has its own taintMode = compileOption("taintmode") when taintMode: @@ -2315,7 +2315,7 @@ when not defined(JS): #and not defined(NimrodVM): when not defined(NimrodVM) and hostOS != "standalone": proc initGC() - when not defined(boehmgc) and not defined(useMalloc): + when not defined(boehmgc) and not defined(useMalloc) and not defined(gogc): proc initAllocator() {.inline.} proc initStackBottom() {.inline, compilerproc.} = @@ -2649,7 +2649,7 @@ when not defined(JS): #and not defined(NimrodVM): include "system/sets" const - GenericSeqSize = (2 * sizeof(int)) + GenericSeqSize = (3 * sizeof(int)) proc getDiscriminant(aa: pointer, n: ptr TNimNode): int = sysAssert(n.kind == nkCase, "getDiscriminant: node != nkCase") diff --git a/lib/system/mmdisp.nim b/lib/system/mmdisp.nim index bdbb3a95a..377408f78 100644 --- a/lib/system/mmdisp.nim +++ b/lib/system/mmdisp.nim @@ -7,7 +7,7 @@ # distribution, for details about the copyright. # -# Nim high-level memory manager: It supports Boehm's GC, no GC and the +# Nim high-level memory manager: It supports Boehm's GC, Go's GC, no GC and the # native Nim GC. The native Nim GC is the default. #{.push checks:on, assertions:on.} @@ -148,6 +148,7 @@ when defined(boehmgc): proc GC_enableMarkAndSweep() = discard proc GC_disableMarkAndSweep() = discard proc GC_getStatistics(): string = return "" + proc setupForeignThreadGc*() = discard proc getOccupiedMem(): int = return boehmGetHeapSize()-boehmGetFreeBytes() proc getFreeMem(): int = return boehmGetFreeBytes() @@ -193,6 +194,195 @@ when defined(boehmgc): proc deallocOsPages() {.inline.} = discard include "system/cellsets" + +elif defined(gogc): + when defined(windows): + const goLib = "libgo.dll" + elif defined(macosx): + const goLib = "libgo.dylib" + else: + const goLib = "libgo.so" + + proc `div`[T: SomeUnsignedInt](x, y: T): T {.magic: "DivU", noSideEffect.} + proc `-`[T: SomeUnsignedInt](x, y: T): T {.magic: "SubU", noSideEffect.} + + proc roundup(x, v: int): int {.inline.} = + result = (x + (v-1)) and not (v-1) + + proc initGC() = discard + # runtime_setgcpercent is only available in GCC 5 + proc GC_disable() = discard + proc GC_enable() = discard + proc goRuntimeGC(force: int32) {.importc: "runtime_gc", dynlib: goLib.} + proc GC_fullCollect() = goRuntimeGC(2) + proc GC_setStrategy(strategy: GC_Strategy) = discard + proc GC_enableMarkAndSweep() = discard + proc GC_disableMarkAndSweep() = discard + + const + goNumSizeClasses = 67 + + type + cbool {.importc: "_Bool", nodecl.} = bool + + goMStats_inner_struct = object + size: uint32 + nmalloc: uint64 + nfree: uint64 + + goMStats = object + # General statistics. + alloc: uint64 # bytes allocated and still in use + total_alloc: uint64 # bytes allocated (even if freed) + sys: uint64 # bytes obtained from system (should be sum of xxx_sys below, no locking, approximate) + nlookup: uint64 # number of pointer lookups + nmalloc: uint64 # number of mallocs + nfree: uint64 # number of frees + # Statistics about malloc heap. + # protected by mheap.Lock + heap_alloc: uint64 # bytes allocated and still in use + heap_sys: uint64 # bytes obtained from system + heap_idle: uint64 # bytes in idle spans + heap_inuse: uint64 # bytes in non-idle spans + heap_released: uint64 # bytes released to the OS + heap_objects: uint64 # total number of allocated objects + # Statistics about allocation of low-level fixed-size structures. + # Protected by FixAlloc locks. + stacks_inuse: uint64 # bootstrap stacks + stacks_sys: uint64 + mspan_inuse: uint64 # MSpan structures + mspan_sys: uint64 + mcache_inuse: uint64 # MCache structures + mcache_sys: uint64 + buckhash_sys: uint64 # profiling bucket hash table + gc_sys: uint64 + other_sys: uint64 + # Statistics about garbage collector. + # Protected by mheap or stopping the world during GC. + next_gc: uint64 # next GC (in heap_alloc time) + last_gc: uint64 # last GC (in absolute time) + pause_total_ns: uint64 + pause_ns: array[256, uint64] + numgc: uint32 + enablegc: cbool + debuggc: cbool + # Statistics about allocation size classes. + by_size: array[goNumSizeClasses, goMStats_inner_struct] + + proc goRuntime_ReadMemStats(a2: ptr goMStats) {.cdecl, importc: "runtime_ReadMemStats", codegenDecl: "$1 $2$3 __asm__ (\"runtime.ReadMemStats\");\n$1 $2$3", dynlib: goLib.} + + proc GC_getStatistics(): string = + var mstats: goMStats + goRuntime_ReadMemStats(addr mstats) + result = "[GC] total allocated memory: " & $(mstats.total_alloc) & "\n" & + "[GC] total memory obtained from system: " & $(mstats.sys) & "\n" & + "[GC] occupied memory: " & $(mstats.alloc) & "\n" & + "[GC] number of pointer lookups: " & $(mstats.nlookup) & "\n" & + "[GC] number of mallocs: " & $(mstats.nmalloc) & "\n" & + "[GC] number of frees: " & $(mstats.nfree) & "\n" & + "[GC] heap objects: " & $(mstats.heap_objects) & "\n" & + "[GC] numgc: " & $(mstats.numgc) & "\n" & + "[GC] enablegc: " & $(mstats.enablegc) & "\n" & + "[GC] debuggc: " & $(mstats.debuggc) & "\n" & + "[GC] total pause time [ms]: " & $(mstats.pause_total_ns div 1000_000) + proc setupForeignThreadGc*() = discard + + proc getOccupiedMem(): int = + var mstats: goMStats + goRuntime_ReadMemStats(addr mstats) + result = int(mstats.alloc) + + proc getFreeMem(): int = + var mstats: goMStats + goRuntime_ReadMemStats(addr mstats) + result = int(mstats.sys - mstats.alloc) + + proc getTotalMem(): int = + var mstats: goMStats + goRuntime_ReadMemStats(addr mstats) + result = int(mstats.sys) + + proc setStackBottom(theStackBottom: pointer) = discard + + proc alloc(size: Natural): pointer = + result = cmalloc(size) + if result == nil: raiseOutOfMem() + + proc alloc0(size: Natural): pointer = + result = alloc(size) + zeroMem(result, size) + + proc realloc(p: pointer, newsize: Natural): pointer = + result = crealloc(p, newsize) + if result == nil: raiseOutOfMem() + + proc dealloc(p: pointer) = cfree(p) + + proc allocShared(size: Natural): pointer = + result = cmalloc(size) + if result == nil: raiseOutOfMem() + + proc allocShared0(size: Natural): pointer = + result = alloc(size) + zeroMem(result, size) + + proc reallocShared(p: pointer, newsize: Natural): pointer = + result = crealloc(p, newsize) + if result == nil: raiseOutOfMem() + + proc deallocShared(p: pointer) = cfree(p) + + when hasThreadSupport: + proc getFreeSharedMem(): int = discard + proc getTotalSharedMem(): int = discard + proc getOccupiedSharedMem(): int = discard + + const goFlagNoZero: uint32 = 1 shl 3 + proc goRuntimeMallocGC(size: uint, typ: uint, flag: uint32): pointer {.importc: "runtime_mallocgc", dynlib: goLib.} + proc goFree(v: pointer) {.importc: "__go_free", dynlib: goLib.} + + proc newObj(typ: PNimType, size: int): pointer {.compilerproc.} = + result = goRuntimeMallocGC(roundup(size, sizeof(pointer)).uint, 0.uint, 0.uint32) + + proc newObjNoInit(typ: PNimType, size: int): pointer = + result = goRuntimeMallocGC(roundup(size, sizeof(pointer)).uint, 0.uint, goFlagNoZero) + + proc newSeq(typ: PNimType, len: int): pointer {.compilerproc.} = + result = newObj(typ, len * typ.base.size + GenericSeqSize) + cast[PGenericSeq](result).len = len + cast[PGenericSeq](result).reserved = len + cast[PGenericSeq](result).elemSize = typ.base.size + + proc growObj(old: pointer, newsize: int): pointer = + # the Go GC doesn't have a realloc + var + oldsize = cast[PGenericSeq](old).len * cast[PGenericSeq](old).elemSize + GenericSeqSize + result = goRuntimeMallocGC(roundup(newsize, sizeof(pointer)).uint, 0.uint, goFlagNoZero) + copyMem(result, old, oldsize) + zeroMem(cast[pointer](cast[ByteAddress](result) +% oldsize), newsize - oldsize) + goFree(old) + + proc nimGCref(p: pointer) {.compilerproc, inline.} = discard + proc nimGCunref(p: pointer) {.compilerproc, inline.} = discard + + proc unsureAsgnRef(dest: PPointer, src: pointer) {.compilerproc, inline.} = + dest[] = src + proc asgnRef(dest: PPointer, src: pointer) {.compilerproc, inline.} = + dest[] = src + proc asgnRefNoCycle(dest: PPointer, src: pointer) {.compilerproc, inline.} = + dest[] = src + + type + TMemRegion = object {.final, pure.} + + proc alloc(r: var TMemRegion, size: int): pointer = + result = alloc(size) + proc alloc0(r: var TMemRegion, size: int): pointer = + result = alloc0(size) + proc dealloc(r: var TMemRegion, p: pointer) = dealloc(p) + proc deallocOsPages(r: var TMemRegion) {.inline.} = discard + proc deallocOsPages() {.inline.} = discard + elif defined(nogc) and defined(useMalloc): when not defined(useNimRtl): @@ -225,6 +415,7 @@ elif defined(nogc) and defined(useMalloc): proc GC_enableMarkAndSweep() = discard proc GC_disableMarkAndSweep() = discard proc GC_getStatistics(): string = return "" + proc setupForeignThreadGc*() = discard proc getOccupiedMem(): int = discard proc getFreeMem(): int = discard @@ -287,6 +478,7 @@ elif defined(nogc): proc GC_enableMarkAndSweep() = discard proc GC_disableMarkAndSweep() = discard proc GC_getStatistics(): string = return "" + proc setupForeignThreadGc*() = discard proc newObj(typ: PNimType, size: int): pointer {.compilerproc.} = diff --git a/lib/system/repr.nim b/lib/system/repr.nim index f1029ff6a..d03b11b56 100644 --- a/lib/system/repr.nim +++ b/lib/system/repr.nim @@ -204,7 +204,7 @@ when not defined(useNimRtl): cl: var TReprClosure) = # we know that p is not nil here: when declared(TCellSet): - when defined(boehmGC) or defined(nogc): + when defined(boehmGC) or defined(gogc) or defined(nogc): var cell = cast[PCell](p) else: var cell = usrToCell(p) diff --git a/lib/system/sysstr.nim b/lib/system/sysstr.nim index 5b4020c8c..d44552902 100644 --- a/lib/system/sysstr.nim +++ b/lib/system/sysstr.nim @@ -216,7 +216,7 @@ proc setLengthSeq(seq: PGenericSeq, elemSize, newLen: int): PGenericSeq {. elif newLen < result.len: # we need to decref here, otherwise the GC leaks! when not defined(boehmGC) and not defined(nogc) and - not defined(gcMarkAndSweep): + not defined(gcMarkAndSweep) and not defined(gogc): when compileOption("gc", "v2"): for i in newLen..result.len-1: let len0 = gch.tempStack.len diff --git a/lib/system/threads.nim b/lib/system/threads.nim index d8e011ecb..1b901ebfb 100644 --- a/lib/system/threads.nim +++ b/lib/system/threads.nim @@ -232,7 +232,7 @@ when not defined(useNimRtl): echo "too large thread local storage size requested" quit 1 - when hasSharedHeap and not defined(boehmgc) and not defined(nogc): + when hasSharedHeap and not defined(boehmgc) and not defined(gogc) and not defined(nogc): var threadList: PGcThread @@ -281,7 +281,7 @@ type TThreadId*[TArg] = ptr TThread[TArg] ## the current implementation uses ## a pointer as a thread ID. -when not defined(boehmgc) and not hasSharedHeap: +when not defined(boehmgc) and not hasSharedHeap and not defined(gogc): proc deallocOsPages() template threadProcWrapperBody(closure: expr) {.immediate.} = @@ -289,7 +289,7 @@ template threadProcWrapperBody(closure: expr) {.immediate.} = var t = cast[ptr TThread[TArg]](closure) when useStackMaskHack: var tls: TThreadLocalStorage - when not defined(boehmgc) and not defined(nogc) and not hasSharedHeap: + when not defined(boehmgc) and not defined(gogc) and not defined(nogc) and not hasSharedHeap: # init the GC for this thread: setStackBottom(addr(t)) initGC() From 3f78f754839a7a00df3944d3fcdbc33bc4430401 Mon Sep 17 00:00:00 2001 From: x2f Date: Sun, 31 May 2015 21:06:23 -0400 Subject: [PATCH 0325/1263] Expose bufSize parameter for file-based loggers newFileLogger and newRollingFileLogger have a new bufSize parameter that is used in open(). The default value -1 has the same behavior as before. Use 0 for unbuffered output to log file. --- lib/pure/logging.nim | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/lib/pure/logging.nim b/lib/pure/logging.nim index cc5340211..18e6cbdb1 100644 --- a/lib/pure/logging.nim +++ b/lib/pure/logging.nim @@ -82,6 +82,7 @@ type baseName: string # initial filename baseMode: FileMode # initial file mode logFiles: int # how many log files already created, e.g. basename.1, basename.2... + bufSize: int # size of output buffer (-1: automatic, 0: unbuffered, >0: fixed buffer size) {.deprecated: [TLevel: Level, PLogger: Logger, PConsoleLogger: ConsoleLogger, PFileLogger: FileLogger, PRollingFileLogger: RollingFileLogger].} @@ -148,11 +149,12 @@ proc newConsoleLogger*(levelThreshold = lvlAll, fmtStr = defaultFmtStr): Console proc newFileLogger*(filename = defaultFilename(), mode: FileMode = fmAppend, levelThreshold = lvlAll, - fmtStr = defaultFmtStr): FileLogger = + fmtStr = defaultFmtStr, + bufSize: int = -1): FileLogger = ## Creates a new file logger. This logger logs to a file. new(result) result.levelThreshold = levelThreshold - result.f = open(filename, mode) + result.f = open(filename, mode, bufSize = bufSize) result.fmtStr = fmtStr # ------ @@ -181,14 +183,16 @@ proc newRollingFileLogger*(filename = defaultFilename(), mode: FileMode = fmReadWrite, levelThreshold = lvlAll, fmtStr = defaultFmtStr, - maxLines = 1000): RollingFileLogger = + maxLines = 1000, + bufSize: int = -1): RollingFileLogger = ## Creates a new rolling file logger. Once a file reaches ``maxLines`` lines ## a new log file will be started and the old will be renamed. new(result) result.levelThreshold = levelThreshold result.fmtStr = fmtStr result.maxLines = maxLines - result.f = open(filename, mode) + result.bufSize = bufSize + result.f = open(filename, mode, bufSize=result.bufSize) result.curLine = 0 result.baseName = filename result.baseMode = mode @@ -215,7 +219,7 @@ method log*(logger: RollingFileLogger, level: Level, rotate(logger) logger.logFiles.inc logger.curLine = 0 - logger.f = open(logger.baseName, logger.baseMode) + logger.f = open(logger.baseName, logger.baseMode, bufSize = logger.bufSize) writeln(logger.f, LevelNames[level], " ",substituteLog(logger.fmtStr), frmt % args) logger.curLine.inc From f3b8a3cbbcee905eb6ed0b7268180b2d872eff7d Mon Sep 17 00:00:00 2001 From: Billingsly Wetherfordshire Date: Mon, 1 Jun 2015 06:04:22 -0500 Subject: [PATCH 0326/1263] made string compatible with openarray[char] --- compiler/sigmatch.nim | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/compiler/sigmatch.nim b/compiler/sigmatch.nim index 7ea2c3d6f..072890ddd 100644 --- a/compiler/sigmatch.nim +++ b/compiler/sigmatch.nim @@ -748,6 +748,11 @@ proc typeRel(c: var TCandidate, f, aOrig: PType, doBind = true): TTypeRelation = result = isConvertible elif typeRel(c, base(f), a.sons[0]) >= isGeneric: result = isConvertible + of tyString: + if f.sons[0].kind == tyChar: + result = isConvertible + elif f.sons[0].kind == tyGenericParam and typeRel(c, base(f), base(a)) >= isGeneric: + result = isConvertible else: discard of tySequence: case a.kind From 87c8d586b5955e8183b822016a3ebd2fcd0a821c Mon Sep 17 00:00:00 2001 From: Billingsly Wetherfordshire Date: Mon, 1 Jun 2015 07:37:36 -0500 Subject: [PATCH 0327/1263] string only matches for openarray not varargs --- compiler/sigmatch.nim | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/compiler/sigmatch.nim b/compiler/sigmatch.nim index 072890ddd..f506e3ff5 100644 --- a/compiler/sigmatch.nim +++ b/compiler/sigmatch.nim @@ -749,10 +749,11 @@ proc typeRel(c: var TCandidate, f, aOrig: PType, doBind = true): TTypeRelation = elif typeRel(c, base(f), a.sons[0]) >= isGeneric: result = isConvertible of tyString: - if f.sons[0].kind == tyChar: - result = isConvertible - elif f.sons[0].kind == tyGenericParam and typeRel(c, base(f), base(a)) >= isGeneric: - result = isConvertible + if f.kind == tyOpenArray: + if f.sons[0].kind == tyChar: + result = isConvertible + elif f.sons[0].kind == tyGenericParam and typeRel(c, base(f), base(a)) >= isGeneric: + result = isConvertible else: discard of tySequence: case a.kind From 80a13a408e39ca197f42398163ef7917a64d1aad Mon Sep 17 00:00:00 2001 From: fowlmouth Date: Mon, 1 Jun 2015 11:01:50 -0500 Subject: [PATCH 0328/1263] added a test --- tests/typerel/tstr_as_openarray.nim | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 tests/typerel/tstr_as_openarray.nim diff --git a/tests/typerel/tstr_as_openarray.nim b/tests/typerel/tstr_as_openarray.nim new file mode 100644 index 000000000..fc28d6c93 --- /dev/null +++ b/tests/typerel/tstr_as_openarray.nim @@ -0,0 +1,22 @@ +discard """ + output: '''success''' +""" +var s = "HI" + +proc x (zz: openarray[char]) = + discard + +x s + +proc z [T] (zz: openarray[T]) = + discard + +z s +z([s,s,s]) + +proc y [T] (arg: var openarray[T]) = + arg[0] = 'X' +y s +doAssert s == "XI" + +echo "success" From dd30bab480f59e4bb4ab8fad5aabd13c08aa1b11 Mon Sep 17 00:00:00 2001 From: Oscar Campbell Date: Mon, 1 Jun 2015 23:49:04 +0200 Subject: [PATCH 0329/1263] Restructure branching slighty. Fix error message. --- compiler/lexer.nim | 5 +++-- lib/pure/hashes.nim | 13 ++++++------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/compiler/lexer.nim b/compiler/lexer.nim index c37b4deba..eaabe05e2 100644 --- a/compiler/lexer.nim +++ b/compiler/lexer.nim @@ -140,7 +140,8 @@ proc isKeyword*(kind: TTokType): bool = proc isNimIdentifier*(s: string): bool = if s[0] in SymStartChars: var i = 1 - while i < s.len: + var sLen = s.len + while i < sLen: if s[i] == '_': inc(i) elif isMagicIdentSeparatorRune(cstring s, i): @@ -637,7 +638,7 @@ proc getSymbol(L: var TLexer, tok: var TToken) = buf[pos+1] == '\128' and buf[pos+2] == '\147': # It's a 'magic separator' en-dash Unicode if buf[pos + magicIdentSeparatorRuneByteWidth] notin SymChars: - lexMessage(L, errInvalidToken, "·") + lexMessage(L, errInvalidToken, "–") break inc(pos, magicIdentSeparatorRuneByteWidth) else: diff --git a/lib/pure/hashes.nim b/lib/pure/hashes.nim index c6af8f918..132264e4a 100644 --- a/lib/pure/hashes.nim +++ b/lib/pure/hashes.nim @@ -130,14 +130,13 @@ proc hashIgnoreStyle*(x: string): THash = var c = x[i] if c == '_': inc(i) - continue # skip _ - if isMagicIdentSeparatorRune(cstring(x), i): + elif isMagicIdentSeparatorRune(cstring(x), i): inc(i, magicIdentSeparatorRuneByteWidth) - continue # skip '·' (unicode middle dot) - if c in {'A'..'Z'}: - c = chr(ord(c) + (ord('a') - ord('A'))) # toLower() - h = h !& ord(c) - inc(i) + else: + if c in {'A'..'Z'}: + c = chr(ord(c) + (ord('a') - ord('A'))) # toLower() + h = h !& ord(c) + inc(i) result = !$h From 51d284ce84c87f4576acd77c8a2a89cef0291970 Mon Sep 17 00:00:00 2001 From: x2f Date: Mon, 1 Jun 2015 21:52:26 -0400 Subject: [PATCH 0330/1263] Documented bufSize param in logging.nim Documented bufSize param in logging.nim to complete the previous change that added a bufSize parameter to file based logger constructors. --- lib/pure/logging.nim | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/lib/pure/logging.nim b/lib/pure/logging.nim index 18e6cbdb1..75b40afea 100644 --- a/lib/pure/logging.nim +++ b/lib/pure/logging.nim @@ -82,7 +82,7 @@ type baseName: string # initial filename baseMode: FileMode # initial file mode logFiles: int # how many log files already created, e.g. basename.1, basename.2... - bufSize: int # size of output buffer (-1: automatic, 0: unbuffered, >0: fixed buffer size) + bufSize: int # size of output buffer (-1: use system defaults, 0: unbuffered, >0: fixed buffer size) {.deprecated: [TLevel: Level, PLogger: Logger, PConsoleLogger: ConsoleLogger, PFileLogger: FileLogger, PRollingFileLogger: RollingFileLogger].} @@ -152,6 +152,8 @@ proc newFileLogger*(filename = defaultFilename(), fmtStr = defaultFmtStr, bufSize: int = -1): FileLogger = ## Creates a new file logger. This logger logs to a file. + ## Use ``bufSize`` as size of the output buffer when writing the file + ## (-1: use system defaults, 0: unbuffered, >0: fixed buffer size). new(result) result.levelThreshold = levelThreshold result.f = open(filename, mode, bufSize = bufSize) @@ -187,6 +189,8 @@ proc newRollingFileLogger*(filename = defaultFilename(), bufSize: int = -1): RollingFileLogger = ## Creates a new rolling file logger. Once a file reaches ``maxLines`` lines ## a new log file will be started and the old will be renamed. + ## Use ``bufSize`` as size of the output buffer when writing the file + ## (-1: use system defaults, 0: unbuffered, >0: fixed buffer size). new(result) result.levelThreshold = levelThreshold result.fmtStr = fmtStr From 3312d49a489e50e5c5f2275f7c0e400208eb8a5d Mon Sep 17 00:00:00 2001 From: Araq Date: Tue, 2 Jun 2015 16:21:55 +0200 Subject: [PATCH 0331/1263] proper waiting for the pinned thread --- lib/pure/concurrency/threadpool.nim | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/lib/pure/concurrency/threadpool.nim b/lib/pure/concurrency/threadpool.nim index 10117183a..0059e3897 100644 --- a/lib/pure/concurrency/threadpool.nim +++ b/lib/pure/concurrency/threadpool.nim @@ -128,6 +128,7 @@ type initialized: bool # whether it has even been initialized shutdown: bool # the pool requests to shut down this worker thread q: ToFreeQueue + readyForTask: Semaphore proc await*(fv: FlowVarBase) = ## waits until the value for the flowVar arrives. Usually it is not necessary @@ -301,6 +302,7 @@ proc distinguishedSlave(w: ptr Worker) {.thread.} = atomicStoreN(addr(w.ready), true, ATOMIC_SEQ_CST) else: w.ready = true + signal(w.readyForTask) await(w.taskArrived) assert(not w.ready) w.f(w, w.data) @@ -340,6 +342,7 @@ proc activateDistinguishedThread(i: int) {.noinline.} = distinguishedData[i].initialized = true distinguishedData[i].q.empty = createSemaphore() initLock(distinguishedData[i].q.lock) + distinguishedData[i].readyForTask = createSemaphore() createThread(distinguished[i], distinguishedSlave, addr(distinguishedData[i])) proc setup() = @@ -429,11 +432,11 @@ proc nimSpawn4(fn: WorkerProc; data: pointer; id: ThreadId) {.compilerProc.} = acquire(distinguishedLock) if not distinguishedData[id].initialized: activateDistinguishedThread(id) + release(distinguishedLock) while true: if selectWorker(addr(distinguishedData[id]), fn, data): break - cpuRelax() - # XXX exponential backoff? - release(distinguishedLock) + await(distinguishedData[id].readyForTask) + proc sync*() = ## a simple barrier to wait for all spawn'ed tasks. If you need more elaborate From 79c92603f505c388d370c5ef0dd8890e4e17e4e0 Mon Sep 17 00:00:00 2001 From: Araq Date: Tue, 2 Jun 2015 16:32:41 +0200 Subject: [PATCH 0332/1263] FlowVar's ^ for refs is safe and convenient to use --- lib/pure/concurrency/threadpool.nim | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/lib/pure/concurrency/threadpool.nim b/lib/pure/concurrency/threadpool.nim index a431691ad..7080e16eb 100644 --- a/lib/pure/concurrency/threadpool.nim +++ b/lib/pure/concurrency/threadpool.nim @@ -221,11 +221,17 @@ proc awaitAndThen*[T](fv: FlowVar[T]; action: proc (x: T) {.closure.}) = action(fv.blob) finished(fv) -proc `^`*[T](fv: FlowVar[ref T]): foreign ptr T = +proc unsafeRead*[T](fv: FlowVar[ref T]): foreign ptr T = ## blocks until the value is available and then returns this value. await(fv) result = cast[foreign ptr T](fv.data) +proc `^`*[T](fv: FlowVar[ref T]): ref T = + ## blocks until the value is available and then returns this value. + await(fv) + let src = cast[ref T](fv.data) + deepCopy result, src + proc `^`*[T](fv: FlowVar[T]): T = ## blocks until the value is available and then returns this value. await(fv) From 13b57dbc2f686ba9beb410ad9fef848926de38c5 Mon Sep 17 00:00:00 2001 From: Adam Strzelecki Date: Tue, 2 Jun 2015 21:29:28 +0200 Subject: [PATCH 0333/1263] Introduce {.noRewrite.} expr pragma disabling TR Term rewriting macros/templates are currently greedy and they will rewrite as long as there is a match. So there was no way to ensure some rewrite happens only once, eg. when rewriting term to same term plus extra content. With new macro we can actually prevent further rewriting on marked expr or stmts, eg. with given example echo(...) will be rewritten just once: template pwnEcho{echo(x)}(x: expr) = {.noRewrite.}: echo("pwned!") echo "ab" --- compiler/ast.nim | 1 + compiler/patterns.nim | 4 +++- compiler/pragmas.nim | 4 +++- compiler/semstmts.nim | 2 ++ compiler/wordrecg.nim | 4 ++-- 5 files changed, 11 insertions(+), 4 deletions(-) diff --git a/compiler/ast.nim b/compiler/ast.nim index 64cb1b1bc..52ba93565 100644 --- a/compiler/ast.nim +++ b/compiler/ast.nim @@ -423,6 +423,7 @@ type # but unfortunately it has measurable impact for compilation # efficiency nfTransf, # node has been transformed + nfNoRewrite # node should not be transformed anymore nfSem # node has been checked for semantics nfLL # node has gone through lambda lifting nfDotField # the call can use a dot operator diff --git a/compiler/patterns.nim b/compiler/patterns.nim index 368b0b37b..3f8b05940 100644 --- a/compiler/patterns.nim +++ b/compiler/patterns.nim @@ -130,7 +130,9 @@ proc matchNested(c: PPatternContext, p, n: PNode, rpn: bool): bool = proc matches(c: PPatternContext, p, n: PNode): bool = # hidden conversions (?) - if isPatternParam(c, p): + if nfNoRewrite in n.flags: + result = false + elif isPatternParam(c, p): result = bindOrCheck(c, p.sym, n) elif n.kind == nkSym and p.kind == nkIdent: result = p.ident.id == n.sym.name.id diff --git a/compiler/pragmas.nim b/compiler/pragmas.nim index c048d78e9..6f37fe756 100644 --- a/compiler/pragmas.nim +++ b/compiler/pragmas.nim @@ -37,7 +37,7 @@ const wImportc, wExportc, wNodecl, wMagic, wDeprecated, wBorrow, wExtern, wImportCpp, wImportObjC, wError, wDiscardable, wGensym, wInject, wRaises, wTags, wLocks, wGcSafe} - exprPragmas* = {wLine, wLocks} + exprPragmas* = {wLine, wLocks, wNoRewrite} stmtPragmas* = {wChecks, wObjChecks, wFieldChecks, wRangechecks, wBoundchecks, wOverflowchecks, wNilchecks, wAssertions, wWarnings, wHints, wLinedir, wStacktrace, wLinetrace, wOptimization, wHint, wWarning, wError, @@ -859,6 +859,8 @@ proc singlePragma(c: PContext, sym: PSym, n: PNode, i: int, c.module.flags.incl sfExperimental else: localError(it.info, "'experimental' pragma only valid as toplevel statement") + of wNoRewrite: + noVal(it) else: invalidPragma(it) else: invalidPragma(it) else: processNote(c, it) diff --git a/compiler/semstmts.nim b/compiler/semstmts.nim index c355a5bf1..43cdca866 100644 --- a/compiler/semstmts.nim +++ b/compiler/semstmts.nim @@ -1268,6 +1268,8 @@ proc semPragmaBlock(c: PContext, n: PNode): PNode = of wLocks: result = n result.typ = n.sons[1].typ + of wNoRewrite: + incl(result.flags, nfNoRewrite) else: discard proc semStaticStmt(c: PContext, n: PNode): PNode = diff --git a/compiler/wordrecg.nim b/compiler/wordrecg.nim index 63fd995c4..deb12536f 100644 --- a/compiler/wordrecg.nim +++ b/compiler/wordrecg.nim @@ -55,7 +55,7 @@ type wFloatchecks, wNanChecks, wInfChecks, wAssertions, wPatterns, wWarnings, wHints, wOptimization, wRaises, wWrites, wReads, wSize, wEffects, wTags, - wDeadCodeElim, wSafecode, wNoForward, + wDeadCodeElim, wSafecode, wNoForward, wNoRewrite, wPragma, wCompileTime, wNoInit, wPassc, wPassl, wBorrow, wDiscardable, @@ -139,7 +139,7 @@ const "assertions", "patterns", "warnings", "hints", "optimization", "raises", "writes", "reads", "size", "effects", "tags", - "deadcodeelim", "safecode", "noforward", + "deadcodeelim", "safecode", "noforward", "norewrite", "pragma", "compiletime", "noinit", "passc", "passl", "borrow", "discardable", "fieldchecks", From 2f5ed17cfe21011dfba30dc10ea7f478c0d67d21 Mon Sep 17 00:00:00 2001 From: Adam Strzelecki Date: Tue, 2 Jun 2015 21:51:41 +0200 Subject: [PATCH 0334/1263] Parser: Properly represent parsePar in grammar --- compiler/parser.nim | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/compiler/parser.nim b/compiler/parser.nim index 0d2ba7cfc..18ef06e64 100644 --- a/compiler/parser.nim +++ b/compiler/parser.nim @@ -499,10 +499,12 @@ proc parsePar(p: var TParser): PNode = #| parKeyw = 'discard' | 'include' | 'if' | 'while' | 'case' | 'try' #| | 'finally' | 'except' | 'for' | 'block' | 'const' | 'let' #| | 'when' | 'var' | 'mixin' - #| par = '(' optInd (&parKeyw complexOrSimpleStmt ^+ ';' - #| | simpleExpr ('=' expr (';' complexOrSimpleStmt ^+ ';' )? )? - #| | (':' expr)? (',' (exprColonEqExpr comma?)*)? )? - #| optPar ')' + #| par = '(' optInd + #| ( &parKeyw complexOrSimpleStmt ^+ ';' + #| | ';' complexOrSimpleStmt ^+ ';' + #| | simpleExpr ( ('=' expr (';' complexOrSimpleStmt ^+ ';' )? ) + #| | (':' expr (',' exprColonEqExpr ^+ ',' )? ) ) ) + #| optPar ')' # # unfortunately it's ambiguous: (expr: expr) vs (exprStmt); however a # leading ';' could be used to enforce a 'stmt' context ... From b0db8126a52fd48352b0b2ce8c7d99e0c98083ef Mon Sep 17 00:00:00 2001 From: Adam Strzelecki Date: Tue, 2 Jun 2015 21:56:44 +0200 Subject: [PATCH 0335/1263] Parser: Inline expr pragmas with parenthesis Previously pragmas could be attached only to whole statements, this change allows attaching pragmas to inline statements, eg.: template rewriteAdd{a + b}(a: expr, b: expr): expr = ({.noRewrite.}: a + b) + 1 Code above will cause a + b to be rewritten once, because rewriteAdd attaches {.noRewrite.} to resulting a + b expr. --- compiler/parser.nim | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/compiler/parser.nim b/compiler/parser.nim index 18ef06e64..05b4df13d 100644 --- a/compiler/parser.nim +++ b/compiler/parser.nim @@ -64,6 +64,7 @@ proc setBaseFlags*(n: PNode, base: TNumericalBase) proc parseSymbol*(p: var TParser, allowNil = false): PNode proc parseTry(p: var TParser; isExpr: bool): PNode proc parseCase(p: var TParser): PNode +proc parseStmtPragma(p: var TParser): PNode # implementation proc getTok(p: var TParser) = @@ -502,6 +503,7 @@ proc parsePar(p: var TParser): PNode = #| par = '(' optInd #| ( &parKeyw complexOrSimpleStmt ^+ ';' #| | ';' complexOrSimpleStmt ^+ ';' + #| | pragmaStmt #| | simpleExpr ( ('=' expr (';' complexOrSimpleStmt ^+ ';' )? ) #| | (':' expr (',' exprColonEqExpr ^+ ',' )? ) ) ) #| optPar ')' @@ -523,6 +525,8 @@ proc parsePar(p: var TParser): PNode = getTok(p) optInd(p, result) semiStmtList(p, result) + elif p.tok.tokType == tkCurlyDotLe: + result.add(parseStmtPragma(p)) elif p.tok.tokType != tkParRi: var a = simpleExpr(p) if p.tok.tokType == tkEquals: From 44b0bf59d9538343178e52346991b527aeb53558 Mon Sep 17 00:00:00 2001 From: Oscar Campbell Date: Tue, 2 Jun 2015 22:22:27 +0200 Subject: [PATCH 0336/1263] Change const def to cleaner code per suggestion. --- compiler/lexer.nim | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/compiler/lexer.nim b/compiler/lexer.nim index bc4b46bc9..a60518323 100644 --- a/compiler/lexer.nim +++ b/compiler/lexer.nim @@ -266,8 +266,7 @@ proc getNumber(L: var TLexer): TToken = xi: BiggestInt const literalishChars = { 'A'..'F', 'a'..'f', '0'..'9', 'X', 'x', 'o', 'c', 'C', 'b', 'B', '_', '.', '\''} - const literalishCharsNoDot = { 'A'..'F', 'a'..'f', '0'..'9', 'X', 'x', 'o', - 'c', 'C', 'b', 'B', '_', '\''} + const literalishCharsNoDot = literalishChars - {'.'} proc matchUnderscoreChars(L: var TLexer, tok: var TToken, chars: set[char]) = var pos = L.bufpos # use registers for pos, buf From 860da53db50d515df54d24241529388d96eafc1a Mon Sep 17 00:00:00 2001 From: apense Date: Tue, 2 Jun 2015 17:11:03 -0400 Subject: [PATCH 0337/1263] Added slight explanation for count{down|up} The inclusivity of a..b (that it is from a <= n <= b) wasn't clear. --- lib/system.nim | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/system.nim b/lib/system.nim index 205a68685..fbb3cbfc7 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -1578,7 +1578,7 @@ else: type IntLikeForCount = int|int8|int16|int32|char|bool|uint8|uint16|enum iterator countdown*[T](a, b: T, step = 1): T {.inline.} = - ## Counts from ordinal value `a` down to `b` with the given + ## Counts from ordinal value `a` down to `b` (inclusive) with the given ## step count. `T` may be any ordinal type, `step` may only ## be positive. **Note**: This fails to count to ``low(int)`` if T = int for ## efficiency reasons. @@ -1606,7 +1606,7 @@ template countupImpl(incr: stmt) {.immediate, dirty.} = incr iterator countup*[S, T](a: S, b: T, step = 1): T {.inline.} = - ## Counts from ordinal value `a` up to `b` with the given + ## Counts from ordinal value `a` up to `b` (inclusive) with the given ## step count. `S`, `T` may be any ordinal type, `step` may only ## be positive. **Note**: This fails to count to ``high(int)`` if T = int for ## efficiency reasons. From 8beed9610640495185e8dce55ca1efe13a7705fd Mon Sep 17 00:00:00 2001 From: Ryan Gonzalez Date: Sun, 31 May 2015 18:05:34 -0500 Subject: [PATCH 0338/1263] Colors! --- compiler/commands.nim | 3 ++ compiler/extccomp.nim | 2 +- compiler/msgs.nim | 79 +++++++++++++++++++++++++++---------------- compiler/options.nim | 1 + 4 files changed, 55 insertions(+), 30 deletions(-) diff --git a/compiler/commands.nim b/compiler/commands.nim index d30d8326c..285d73e7a 100644 --- a/compiler/commands.nim +++ b/compiler/commands.nim @@ -532,6 +532,9 @@ proc processSwitch(switch, arg: string, pass: TCmdLinePass, info: TLineInfo) = of "genscript": expectNoArg(switch, arg, pass, info) incl(gGlobalOptions, optGenScript) + of "usecolors": + expectNoArg(switch, arg, pass, info) + incl(gGlobalOptions, optUseColors) of "lib": expectArg(switch, arg, pass, info) libpath = processPath(arg, notRelativeToProj=true) diff --git a/compiler/extccomp.nim b/compiler/extccomp.nim index 186a3884d..ea69f6c25 100644 --- a/compiler/extccomp.nim +++ b/compiler/extccomp.nim @@ -13,7 +13,7 @@ # nim files. import - lists, ropes, os, strutils, osproc, platform, condsyms, options, msgs, crc + lists, ropes, os, strutils, osproc, platform, condsyms, options, msgs, crc, terminal type TSystemCC* = enum diff --git a/compiler/msgs.nim b/compiler/msgs.nim index 041a181be..eb6707d65 100644 --- a/compiler/msgs.nim +++ b/compiler/msgs.nim @@ -8,7 +8,7 @@ # import - options, strutils, os, tables, ropes, platform + options, strutils, os, tables, ropes, platform, terminal type TMsgKind* = enum @@ -601,13 +601,13 @@ proc suggestQuit*() = # this format is understood by many text editors: it is the same that # Borland and Freepascal use const - PosErrorFormat* = "$1($2, $3) Error: $4" - PosWarningFormat* = "$1($2, $3) Warning: $4" - PosHintFormat* = "$1($2, $3) Hint: $4" - PosContextFormat = "$1($2, $3) Info: $4" - RawErrorFormat* = "Error: $1" - RawWarningFormat* = "Warning: $1" - RawHintFormat* = "Hint: $1" + PosErrorFormat* = "$1($2, $3) Error: " + PosWarningFormat* = "$1($2, $3) Warning: " + PosHintFormat* = "$1($2, $3) Hint: " + PosContextFormat = "$1($2, $3) Info: " + RawError* = "Error: " + RawWarning* = "Warning: " + RawHint* = "Hint: " proc getInfoContextLen*(): int = return msgContext.len proc setInfoContextLen*(L: int) = setLen(msgContext, L) @@ -682,17 +682,27 @@ proc outWriteln*(s: string) = ## Writes to stdout. Always. if eStdOut in errorOutputs: writeln(stdout, s) -proc msgWriteln*(s: string) = - ## Writes to stdout. If --stdout option is given, writes to stderr instead. +proc msgWriteln*(s: string, color: ForegroundColor = fgWhite, coloredText: string = "") = + ## Writes to stdout. If --stderr option is given, writes to stderr instead. #if gCmd == cmdIdeTools and optCDebug notin gGlobalOptions: return + var hasColor = optUseColors in gGlobalOptions if not isNil(writelnHook): - writelnHook(s) - elif optStdout in gGlobalOptions: - if eStdErr in errorOutputs: writeln(stderr, s) + writelnHook(coloredText & s) else: - if eStdOut in errorOutputs: writeln(stdout, s) + if optStdout in gGlobalOptions: + if eStdErr in errorOutputs: + if hasColor: setForegroundColor(color) + write(stderr, coloredText) + if hasColor: resetAttributes() + writeln(stderr, s) + else: + if eStdOut in errorOutputs: + if hasColor: setForegroundColor(color) + write(stdout, coloredText) + if hasColor: resetAttributes() + writeln(stdout, s) proc coordToStr(coord: int): string = if coord == -1: result = "???" @@ -714,7 +724,7 @@ proc handleError(msg: TMsgKind, eh: TErrorHandling, s: string) = if stackTraceAvailable() and isNil(writelnHook): writeStackTrace() else: - msgWriteln("No stack traceback available\nTo create a stacktrace, rerun compilation with ./koch temp " & options.command & " ") + msgWriteln("", fgRed, "No stack traceback available\nTo create a stacktrace, rerun compilation with ./koch temp " & options.command & " ") quit 1 if msg >= fatalMin and msg <= fatalMax: @@ -737,34 +747,39 @@ proc writeContext(lastinfo: TLineInfo) = for i in countup(0, len(msgContext) - 1): if msgContext[i] != lastinfo and msgContext[i] != info: msgWriteln(PosContextFormat % [toMsgFilename(msgContext[i]), - coordToStr(msgContext[i].line), - coordToStr(msgContext[i].col+1), - getMessageStr(errInstantiationFrom, "")]) + coordToStr(msgContext[i].line), + coordToStr(msgContext[i].col+1), + getMessageStr(errInstantiationFrom, "")]) info = msgContext[i] proc ignoreMsgBecauseOfIdeTools(msg: TMsgKind): bool = msg >= errGenerated and gCmd == cmdIdeTools and optIdeDebug notin gGlobalOptions proc rawMessage*(msg: TMsgKind, args: openArray[string]) = - var frmt: string + var + frmt: string + color: ForegroundColor case msg of errMin..errMax: writeContext(unknownLineInfo()) - frmt = RawErrorFormat + frmt = RawError + color = fgRed of warnMin..warnMax: if optWarns notin gOptions: return if msg notin gNotes: return writeContext(unknownLineInfo()) - frmt = RawWarningFormat + frmt = RawWarning inc(gWarnCounter) + color = fgYellow of hintMin..hintMax: if optHints notin gOptions: return if msg notin gNotes: return - frmt = RawHintFormat + frmt = RawHint inc(gHintCounter) - let s = `%`(frmt, `%`(msgKindToString(msg), args)) + color = fgGreen + let s = `%`(msgKindToString(msg), args) if not ignoreMsgBecauseOfIdeTools(msg): - msgWriteln(s) + msgWriteln(s, color, frmt) handleError(msg, doAbort, s) proc rawMessage*(msg: TMsgKind, arg: string) = @@ -785,8 +800,10 @@ proc formatMsg*(info: TLineInfo, msg: TMsgKind, arg: string): string = proc liMessage(info: TLineInfo, msg: TMsgKind, arg: string, eh: TErrorHandling) = - var frmt: string - var ignoreMsg = false + var + frmt: string + ignoreMsg = false + color: ForegroundColor case msg of errMin..errMax: writeContext(info) @@ -795,22 +812,26 @@ proc liMessage(info: TLineInfo, msg: TMsgKind, arg: string, # in the same file and line are produced: #ignoreMsg = lastError == info and eh != doAbort lastError = info + color = fgRed of warnMin..warnMax: ignoreMsg = optWarns notin gOptions or msg notin gNotes if not ignoreMsg: writeContext(info) frmt = PosWarningFormat inc(gWarnCounter) + color = fgYellow of hintMin..hintMax: ignoreMsg = optHints notin gOptions or msg notin gNotes frmt = PosHintFormat inc(gHintCounter) + color = fgGreen # NOTE: currently line info line numbers start with 1, # but column numbers start with 0, however most editors expect # first column to be 1, so we need to +1 here - let s = frmt % [toMsgFilename(info), coordToStr(info.line), - coordToStr(info.col+1), getMessageStr(msg, arg)] + let x = frmt % [toMsgFilename(info), coordToStr(info.line), + coordToStr(info.col+1)] + let s = getMessageStr(msg, arg) if not ignoreMsg and not ignoreMsgBecauseOfIdeTools(msg): - msgWriteln(s) + msgWriteln(s, color, x) if optPrintSurroundingSrc and msg in errMin..errMax: info.writeSurroundingSrc handleError(msg, eh, s) diff --git a/compiler/options.nim b/compiler/options.nim index b3060a180..48e2db0c7 100644 --- a/compiler/options.nim +++ b/compiler/options.nim @@ -54,6 +54,7 @@ type # please make sure we have under 32 options optSkipUserConfigFile, # skip the users's config file optSkipParentConfigFiles, # skip parent dir's config files optNoMain, # do not generate a "main" proc + optUseColors, # use colors for hints, warnings, and errors optThreads, # support for multi-threading optStdout, # output to stdout optThreadAnalysis, # thread analysis pass From bf9053315c75037a58230f8abc7f75ece636f806 Mon Sep 17 00:00:00 2001 From: Oscar Campbell Date: Wed, 3 Jun 2015 03:22:17 +0200 Subject: [PATCH 0339/1263] Ensure fresh compiler and local compiler + libs --- koch.nim | 3 +++ tests/testament/specs.nim | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/koch.nim b/koch.nim index fc292401a..83737d751 100644 --- a/koch.nim +++ b/koch.nim @@ -330,6 +330,9 @@ proc winRelease() = template `|`(a, b): expr = (if a.len > 0: a else: b) proc tests(args: string) = + # Since tests take a long time (on my machine) - lets make sure a stupid + # mistake - like forgetting to compile the compiler - isn't made... + exec "nim c --lib:./lib -d:release compiler/nim.nim" # we compile the tester with taintMode:on to have a basic # taint mode test :-) exec "nim cc --taintMode:on tests/testament/tester" diff --git a/tests/testament/specs.nim b/tests/testament/specs.nim index 9306bf025..a4b1b8283 100644 --- a/tests/testament/specs.nim +++ b/tests/testament/specs.nim @@ -10,7 +10,7 @@ import parseutils, strutils, os, osproc, streams, parsecfg const - cmdTemplate* = r"nim $target --hints:on -d:testing $options $file" + cmdTemplate* = r"./compiler/nim $target --lib:./lib --hints:on -d:testing $options $file" type TTestAction* = enum From 51fc903dbf26a30add2ec75bbdc01a403cb2d46c Mon Sep 17 00:00:00 2001 From: Oscar Campbell Date: Wed, 3 Jun 2015 13:08:28 +0200 Subject: [PATCH 0340/1263] Made pathing (hopefully) Windows friendly. --- koch.nim | 2 +- tests/testament/specs.nim | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/koch.nim b/koch.nim index 83737d751..8962acdc1 100644 --- a/koch.nim +++ b/koch.nim @@ -332,7 +332,7 @@ template `|`(a, b): expr = (if a.len > 0: a else: b) proc tests(args: string) = # Since tests take a long time (on my machine) - lets make sure a stupid # mistake - like forgetting to compile the compiler - isn't made... - exec "nim c --lib:./lib -d:release compiler/nim.nim" + exec "nim c --lib:lib -d:release compiler/nim.nim" # we compile the tester with taintMode:on to have a basic # taint mode test :-) exec "nim cc --taintMode:on tests/testament/tester" diff --git a/tests/testament/specs.nim b/tests/testament/specs.nim index a4b1b8283..99640f22c 100644 --- a/tests/testament/specs.nim +++ b/tests/testament/specs.nim @@ -10,7 +10,7 @@ import parseutils, strutils, os, osproc, streams, parsecfg const - cmdTemplate* = r"./compiler/nim $target --lib:./lib --hints:on -d:testing $options $file" + cmdTemplate* = r"compiler" / "nim $target --lib:lib --hints:on -d:testing $options $file" type TTestAction* = enum From a385b6736cc76b94658097fa7f7ae01beb4fba57 Mon Sep 17 00:00:00 2001 From: Dominik Picheta Date: Wed, 3 Jun 2015 18:48:55 +0100 Subject: [PATCH 0341/1263] Fix incorrect 400 reply in asynchttpserver Without the ``continue`` the user's callback will be called but the client would have already been replied to. --- lib/pure/asynchttpserver.nim | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/pure/asynchttpserver.nim b/lib/pure/asynchttpserver.nim index 279cedb5d..9e036443c 100644 --- a/lib/pure/asynchttpserver.nim +++ b/lib/pure/asynchttpserver.nim @@ -210,6 +210,7 @@ proc processClient(client: AsyncSocket, address: string, var contentLength = 0 if parseInt(request.headers["Content-Length"], contentLength) == 0: await request.respond(Http400, "Bad Request. Invalid Content-Length.") + continue else: request.body = await client.recv(contentLength) assert request.body.len == contentLength From 071ccf3d026b03135dbc1e413a5312ac296191ac Mon Sep 17 00:00:00 2001 From: Oscar Campbell Date: Thu, 4 Jun 2015 07:33:27 +0200 Subject: [PATCH 0342/1263] Add "safety compilation". Improved, fixed messages - node ext searcher also looks for "iojs" if no node(js?) found. - koch ensures the local work dir compiler is freshly compiled before executing the tests. - the tester can only run in the repo dir - now the compiler and libs used are also explicitly the local dirs - so no confusion from system wide pathing ("sufficiently sandboxed"). - fixed expectations in tmitems.nim test to match changes in json mod. - re-layouted the columns / row printing slightly, making test fails pop out more, and everything "normal" layed back. --- compiler/nodejs.nim | 2 + koch.nim | 6 +- tests/stdlib/tmitems.nim | 4 +- tests/testament/tester.nim | 146 +++++++++++++++++++++++-------------- 4 files changed, 100 insertions(+), 58 deletions(-) diff --git a/compiler/nodejs.nim b/compiler/nodejs.nim index e2b79df19..7f9f28aaf 100644 --- a/compiler/nodejs.nim +++ b/compiler/nodejs.nim @@ -4,3 +4,5 @@ proc findNodeJs*(): string = result = findExe("nodejs") if result == "": result = findExe("node") + if result == "": + result = findExe("iojs") diff --git a/koch.nim b/koch.nim index 8962acdc1..83f363b1a 100644 --- a/koch.nim +++ b/koch.nim @@ -330,12 +330,12 @@ proc winRelease() = template `|`(a, b): expr = (if a.len > 0: a else: b) proc tests(args: string) = - # Since tests take a long time (on my machine) - lets make sure a stupid - # mistake - like forgetting to compile the compiler - isn't made... - exec "nim c --lib:lib -d:release compiler/nim.nim" # we compile the tester with taintMode:on to have a basic # taint mode test :-) exec "nim cc --taintMode:on tests/testament/tester" + # Since tests take a long time (on my machine), and we want to defy Murhpys + # law - lets make sure the compiler really is freshly compiled! + exec "nim c --lib:lib -d:release --opt:speed compiler/nim.nim" let tester = quoteShell(getCurrentDir() / "tests/testament/tester".exe) let success = tryExec tester & " " & (args|"all") exec tester & " html" diff --git a/tests/stdlib/tmitems.nim b/tests/stdlib/tmitems.nim index 2c0a0392a..544ad0334 100644 --- a/tests/stdlib/tmitems.nim +++ b/tests/stdlib/tmitems.nim @@ -11,8 +11,8 @@ fpqeew [11, 12, 13] [11, 12, 13] [11, 12, 13] -{"key1": 11, "key2": 12, "key3": 13} -[11, 12, 13] +{"key1":11,"key2":12,"key3":13} +[11,12,13] diff --git a/tests/testament/tester.nim b/tests/testament/tester.nim index 62dafee80..ebfea591a 100644 --- a/tests/testament/tester.nim +++ b/tests/testament/tester.nim @@ -12,7 +12,7 @@ import parseutils, strutils, pegs, os, osproc, streams, parsecfg, json, marshal, backend, parseopt, specs, htmlgen, browsers, terminal, - algorithm, compiler/nodejs + algorithm, compiler/nodejs, re const resultsFile = "testresults.html" @@ -126,6 +126,9 @@ proc `$`(x: TResults): string = "Tests skipped: $2 / $3
\n") % [$x.passed, $x.skipped, $x.total] +proc leftAlign(s: string, count: Natural, padding = ' '): string = + s & repeat(padding, max(0, count - s.len)) + proc addResult(r: var TResults, test: TTest, expected, given: string, success: TResultEnum) = let name = test.name.extractFilename & test.options @@ -137,14 +140,19 @@ proc addResult(r: var TResults, test: TTest, expected = expected, given = given) r.data.addf("$#\t$#\t$#\t$#", name, expected, given, $success) - if success == reIgnored: - styledEcho styleBright, name, fgYellow, " [", $success, "]" - elif success != reSuccess: - styledEcho styleBright, name, fgRed, " [", $success, "]" - echo"Expected:" - styledEcho styleBright, expected - echo"Given:" - styledEcho styleBright, given + let alignedName = leftAlign(name, 72) # Make the total line length 78 chars + if success == reSuccess: + styledEcho fgCyan, alignedName, fgGreen, " [PASS]" + elif success == reIgnored: + styledEcho styleBright, fgCyan, alignedName, styleDim, fgYellow, " [SKIP]" + else: + styledEcho styleBright, fgCyan, alignedName, fgRed, " [FAIL]" + styledEcho styleBright, fgCyan, "Test \"", test.name, "\"", " in category \"", test.cat.string, "\"" + styledEcho styleBright, fgRed, "Failure: ", $success + styledEcho fgYellow, "Expected:" + styledEcho styleBright, expected, "\n" + styledEcho fgYellow, "Gotten:" + styledEcho styleBright, given, "\n" proc cmpMsgs(r: var TResults, expected, given: TSpec, test: TTest) = if strip(expected.msg) notin strip(given.msg): @@ -211,68 +219,100 @@ proc compilerOutputTests(test: TTest, given: var TSpec, expected: TSpec; if given.err == reSuccess: inc(r.passed) r.addResult(test, expectedmsg, givenmsg, given.err) +proc analyzeAndConsolidateOutput(s: string): string = + result = "" + let rows = s.splitLines + for i in 0 ..< rows.len: + if (let pos = find(rows[i], "Traceback (most recent call last)"); pos != -1): + result = substr(rows[i], pos) & "\n" + for i in i+1 ..< rows.len: + result.add rows[i] & "\n" + if not (rows[i] =~ re"^[^(]+\(\d+\)\s+"): + return + elif (let pos = find(rows[i], "SIGSEGV: Illegal storage access."); pos != -1): + result = substr(rows[i], pos) + return + proc testSpec(r: var TResults, test: TTest) = # major entry point for a single test let tname = test.name.addFileExt(".nim") inc(r.total) - styledEcho "Processing ", fgCyan, extractFilename(tname) var expected: TSpec if test.action != actionRunNoSpec: expected = parseSpec(tname) else: specDefaults expected expected.action = actionRunNoSpec + if expected.err == reIgnored: r.addResult(test, "", "", reIgnored) inc(r.skipped) - else: - case expected.action - of actionCompile: - var given = callCompiler(expected.cmd, test.name, - test.options & " --hint[Path]:off --hint[Processing]:off", test.target) - compilerOutputTests(test, given, expected, r) - of actionRun, actionRunNoSpec: - var given = callCompiler(expected.cmd, test.name, test.options, - test.target) - if given.err != reSuccess: - r.addResult(test, "", given.msg, given.err) - else: - var exeFile: string - if test.target == targetJS: - let (dir, file, ext) = splitFile(tname) - exeFile = dir / "nimcache" / file & ".js" - else: - exeFile = changeFileExt(tname, ExeExt) - if existsFile(exeFile): - let nodejs = findNodeJs() - if test.target == targetJS and nodejs == "": - r.addResult(test, expected.outp, "nodejs binary not in PATH", - reExeNotFound) - return - var (buf, exitCode) = execCmdEx( - (if test.target == targetJS: nodejs & " " else: "") & exeFile) - if exitCode != expected.exitCode: - r.addResult(test, "exitcode: " & $expected.exitCode, - "exitcode: " & $exitCode, reExitCodesDiffer) - else: - var bufB = strip(buf.string) - if expected.sortoutput: bufB = makeDeterministic(bufB) - if bufB != strip(expected.outp): - if not (expected.substr and expected.outp in bufB): - given.err = reOutputsDiffer - compilerOutputTests(test, given, expected, r) - else: - r.addResult(test, expected.outp, "executable not found", reExeNotFound) - of actionReject: - var given = callCompiler(expected.cmd, test.name, test.options, - test.target) - cmpMsgs(r, expected, given, test) + return + + case expected.action + of actionCompile: + var given = callCompiler(expected.cmd, test.name, + test.options & " --hint[Path]:off --hint[Processing]:off", test.target) + compilerOutputTests(test, given, expected, r) + of actionRun, actionRunNoSpec: + # In this branch of code "early return" pattern is clearer than deep + # nested conditionals - the empty rows in between to clarify the "danger" + var given = callCompiler(expected.cmd, test.name, test.options, + test.target) + + if given.err != reSuccess: + r.addResult(test, "", given.msg, given.err) + return + + let isJsTarget = test.target == targetJS + var exeFile: string + if isJsTarget: + let (dir, file, ext) = splitFile(tname) + exeFile = dir / "nimcache" / file & ".js" # *TODO* hardcoded "nimcache" + else: + exeFile = changeFileExt(tname, ExeExt) + + if not existsFile(exeFile): + r.addResult(test, expected.outp, "executable not found", reExeNotFound) + return + + let nodejs = if isJsTarget: findNodeJs() else: "" + if isJsTarget and nodejs == "": + r.addResult(test, expected.outp, "nodejs binary not in PATH", + reExeNotFound) + return + + let exeCmd = (if isJsTarget: nodejs & " " else: "") & exeFile + let (buf, exitCode) = execCmdEx(exeCmd) + let bufB = if expected.sortoutput: makeDeterministic(strip(buf.string)) + else: strip(buf.string) + + if exitCode != expected.exitCode: + r.addResult(test, "exitcode: " & $expected.exitCode, + "exitcode: " & $exitCode & "\n\nOutput:\n" & + analyzeAndConsolidateOutput(bufB), + reExitCodesDiffer) + return + + if bufB != strip(expected.outp): + if not (expected.substr and expected.outp in bufB): + given.err = reOutputsDiffer + r.addResult(test, expected.outp, bufB, reOutputsDiffer) + return + + compilerOutputTests(test, given, expected, r) + return + + of actionReject: + var given = callCompiler(expected.cmd, test.name, test.options, + test.target) + cmpMsgs(r, expected, given, test) + return proc testNoSpec(r: var TResults, test: TTest) = # does not extract the spec because the file is not supposed to have any let tname = test.name.addFileExt(".nim") inc(r.total) - styledEcho "Processing ", fgCyan, extractFilename(tname) let given = callCompiler(cmdTemplate, test.name, test.options, test.target) r.addResult(test, "", given.msg, given.err) if given.err == reSuccess: inc(r.passed) From e9a57e97061c69b73525bfef6bfb5165450ad630 Mon Sep 17 00:00:00 2001 From: yglukhov Date: Wed, 3 Jun 2015 16:15:54 +0300 Subject: [PATCH 0343/1263] Fixed codegen for DotDot magic --- compiler/jsgen.nim | 21 ++++++++++++++------- tests/js/testmagic.nim | 5 ++++- 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/compiler/jsgen.nim b/compiler/jsgen.nim index 0f6323abc..2fdf14b76 100644 --- a/compiler/jsgen.nim +++ b/compiler/jsgen.nim @@ -986,6 +986,15 @@ proc genAddr(p: PProc, n: PNode, r: var TCompRes) = else: internalError(n.sons[0].info, "expr(nkBracketExpr, " & $ty.kind & ')') else: internalError(n.sons[0].info, "genAddr") +proc genProcForSymIfNeeded(p: PProc, s: PSym) = + if not p.g.generatedSyms.containsOrIncl(s.id): + let newp = genProc(p, s) + var owner = p + while owner != nil and owner.prc != s.owner: + owner = owner.up + if owner != nil: add(owner.locals, newp) + else: add(p.g.code, newp) + proc genSym(p: PProc, n: PNode, r: var TCompRes) = var s = n.sym case s.kind @@ -1021,13 +1030,8 @@ proc genSym(p: PProc, n: PNode, r: var TCompRes) = discard elif sfForward in s.flags: p.g.forwarded.add(s) - elif not p.g.generatedSyms.containsOrIncl(s.id): - let newp = genProc(p, s) - var owner = p - while owner != nil and owner.prc != s.owner: - owner = owner.up - if owner != nil: add(owner.locals, newp) - else: add(p.g.code, newp) + else: + genProcForSymIfNeeded(p, s) else: if s.loc.r == nil: internalError(n.info, "symbol has no generated name: " & s.name.s) @@ -1394,6 +1398,9 @@ proc genMagic(p: PProc, n: PNode, r: var TCompRes) = of mCopyStrLast: ternaryExpr(p, n, r, "", "($1.slice($2, ($3)+1).concat(0))") of mNewString: unaryExpr(p, n, r, "mnewString", "mnewString($1)") of mNewStringOfCap: unaryExpr(p, n, r, "mnewString", "mnewString(0)") + of mDotDot: + genProcForSymIfNeeded(p, n.sons[0].sym) + genCall(p, n, r) else: genCall(p, n, r) #else internalError(e.info, 'genMagic: ' + magicToStr[op]); diff --git a/tests/js/testmagic.nim b/tests/js/testmagic.nim index 5f793ae05..8e06f1a9b 100644 --- a/tests/js/testmagic.nim +++ b/tests/js/testmagic.nim @@ -1,5 +1,7 @@ discard """ - output: '''true''' + output: '''true +123 +''' """ # This file tests some magic @@ -7,3 +9,4 @@ discard """ var foo = cstring("foo") var bar = cstring("foo") echo(foo == bar) +echo "01234"[1 .. ^2] From 9764ba933b08e9e04a145c922ab32bfa06cc7400 Mon Sep 17 00:00:00 2001 From: pdw Date: Sun, 24 May 2015 22:20:41 -0500 Subject: [PATCH 0344/1263] Dropped 'T' from types --- compiler/ast.nim | 2 +- compiler/astalgo.nim | 48 ++++++++++++++++++++++---------------------- compiler/docgen.nim | 6 +++--- compiler/idents.nim | 6 +++--- compiler/lexer.nim | 6 +++--- compiler/treetab.nim | 14 ++++++------- 6 files changed, 41 insertions(+), 41 deletions(-) diff --git a/compiler/ast.nim b/compiler/ast.nim index 64cb1b1bc..044f21341 100644 --- a/compiler/ast.nim +++ b/compiler/ast.nim @@ -842,7 +842,7 @@ type data*: TIdNodePairSeq TNodePair* = object - h*: THash # because it is expensive to compute! + h*: Hash # because it is expensive to compute! key*: PNode val*: int diff --git a/compiler/astalgo.nim b/compiler/astalgo.nim index 1707718d7..5980edb27 100644 --- a/compiler/astalgo.nim +++ b/compiler/astalgo.nim @@ -14,7 +14,7 @@ import ast, hashes, intsets, strutils, options, msgs, ropes, idents, rodutils -proc hashNode*(p: RootRef): THash +proc hashNode*(p: RootRef): Hash proc treeToYaml*(n: PNode, indent: int = 0, maxRecDepth: int = - 1): Rope # Convert a tree into its YAML representation; this is used by the # YAML code generator and it is invaluable for debugging purposes. @@ -49,7 +49,7 @@ proc strTableGet*(t: TStrTable, name: PIdent): PSym type TTabIter*{.final.} = object # consider all fields here private - h*: THash # current hash + h*: Hash # current hash proc initTabIter*(ti: var TTabIter, tab: TStrTable): PSym proc nextIter*(ti: var TTabIter, tab: TStrTable): PSym @@ -65,7 +65,7 @@ proc nextIter*(ti: var TTabIter, tab: TStrTable): PSym type TIdentIter*{.final.} = object # iterator over all syms with same identifier - h*: THash # current hash + h*: Hash # current hash name*: PIdent @@ -94,7 +94,7 @@ proc getSymFromList*(list: PNode, ident: PIdent, start: int = 0): PSym proc lookupInRecord*(n: PNode, field: PIdent): PSym proc getModule*(s: PSym): PSym proc mustRehash*(length, counter: int): bool -proc nextTry*(h, maxHash: THash): THash {.inline.} +proc nextTry*(h, maxHash: Hash): Hash {.inline.} # ------------- table[int, int] --------------------------------------------- const @@ -196,7 +196,7 @@ proc getSymFromList(list: PNode, ident: PIdent, start: int = 0): PSym = else: internalError(list.info, "getSymFromList") result = nil -proc hashNode(p: RootRef): THash = +proc hashNode(p: RootRef): Hash = result = hash(cast[pointer](p)) proc mustRehash(length, counter: int): bool = @@ -466,7 +466,7 @@ proc debug(n: PNode) = const EmptySeq = @[] -proc nextTry(h, maxHash: THash): THash = +proc nextTry(h, maxHash: Hash): Hash = result = ((5 * h) + 1) and maxHash # For any initial h in range(maxHash), repeating that maxHash times # generates each int in range(maxHash) exactly once (see any text on @@ -474,7 +474,7 @@ proc nextTry(h, maxHash: THash): THash = proc objectSetContains(t: TObjectSet, obj: RootRef): bool = # returns true whether n is in t - var h: THash = hashNode(obj) and high(t.data) # start with real hash value + var h: Hash = hashNode(obj) and high(t.data) # start with real hash value while t.data[h] != nil: if t.data[h] == obj: return true @@ -482,7 +482,7 @@ proc objectSetContains(t: TObjectSet, obj: RootRef): bool = result = false proc objectSetRawInsert(data: var TObjectSeq, obj: RootRef) = - var h: THash = hashNode(obj) and high(data) + var h: Hash = hashNode(obj) and high(data) while data[h] != nil: assert(data[h] != obj) h = nextTry(h, high(data)) @@ -503,7 +503,7 @@ proc objectSetIncl(t: var TObjectSet, obj: RootRef) = proc objectSetContainsOrIncl(t: var TObjectSet, obj: RootRef): bool = # returns true if obj is already in the string table: - var h: THash = hashNode(obj) and high(t.data) + var h: Hash = hashNode(obj) and high(t.data) while true: var it = t.data[h] if it == nil: break @@ -520,7 +520,7 @@ proc objectSetContainsOrIncl(t: var TObjectSet, obj: RootRef): bool = result = false proc tableRawGet(t: TTable, key: RootRef): int = - var h: THash = hashNode(key) and high(t.data) # start with real hash value + var h: Hash = hashNode(key) and high(t.data) # start with real hash value while t.data[h].key != nil: if t.data[h].key == key: return h @@ -529,7 +529,7 @@ proc tableRawGet(t: TTable, key: RootRef): int = proc tableSearch(t: TTable, key, closure: RootRef, comparator: TCmpProc): RootRef = - var h: THash = hashNode(key) and high(t.data) # start with real hash value + var h: Hash = hashNode(key) and high(t.data) # start with real hash value while t.data[h].key != nil: if t.data[h].key == key: if comparator(t.data[h].val, closure): @@ -544,7 +544,7 @@ proc tableGet(t: TTable, key: RootRef): RootRef = else: result = nil proc tableRawInsert(data: var TPairSeq, key, val: RootRef) = - var h: THash = hashNode(key) and high(data) + var h: Hash = hashNode(key) and high(data) while data[h].key != nil: assert(data[h].key != key) h = nextTry(h, high(data)) @@ -569,7 +569,7 @@ proc tablePut(t: var TTable, key, val: RootRef) = inc(t.counter) proc strTableContains(t: TStrTable, n: PSym): bool = - var h: THash = n.name.h and high(t.data) # start with real hash value + var h: Hash = n.name.h and high(t.data) # start with real hash value while t.data[h] != nil: if (t.data[h] == n): return true @@ -577,7 +577,7 @@ proc strTableContains(t: TStrTable, n: PSym): bool = result = false proc strTableRawInsert(data: var TSymSeq, n: PSym) = - var h: THash = n.name.h and high(data) + var h: Hash = n.name.h and high(data) if sfImmediate notin n.flags: # fast path: while data[h] != nil: @@ -606,7 +606,7 @@ proc strTableRawInsert(data: var TSymSeq, n: PSym) = proc symTabReplaceRaw(data: var TSymSeq, prevSym: PSym, newSym: PSym) = assert prevSym.name.h == newSym.name.h - var h: THash = prevSym.name.h and high(data) + var h: Hash = prevSym.name.h and high(data) while data[h] != nil: if data[h] == prevSym: data[h] = newSym @@ -640,7 +640,7 @@ proc strTableIncl*(t: var TStrTable, n: PSym): bool {.discardable.} = # It is essential that `n` is written nevertheless! # This way the newest redefinition is picked by the semantic analyses! assert n.name != nil - var h: THash = n.name.h and high(t.data) + var h: Hash = n.name.h and high(t.data) var replaceSlot = -1 while true: var it = t.data[h] @@ -666,7 +666,7 @@ proc strTableIncl*(t: var TStrTable, n: PSym): bool {.discardable.} = result = false proc strTableGet(t: TStrTable, name: PIdent): PSym = - var h: THash = name.h and high(t.data) + var h: Hash = name.h and high(t.data) while true: result = t.data[h] if result == nil: break @@ -694,7 +694,7 @@ proc nextIdentIter(ti: var TIdentIter, tab: TStrTable): PSym = proc nextIdentExcluding*(ti: var TIdentIter, tab: TStrTable, excluding: IntSet): PSym = - var h: THash = ti.h and high(tab.data) + var h: Hash = ti.h and high(tab.data) var start = h result = tab.data[h] while result != nil: @@ -743,7 +743,7 @@ proc hasEmptySlot(data: TIdPairSeq): bool = result = false proc idTableRawGet(t: TIdTable, key: int): int = - var h: THash + var h: Hash h = key and high(t.data) # start with real hash value while t.data[h].key != nil: if t.data[h].key.id == key: @@ -772,7 +772,7 @@ iterator pairs*(t: TIdTable): tuple[key: int, value: RootRef] = yield (t.data[i].key.id, t.data[i].val) proc idTableRawInsert(data: var TIdPairSeq, key: PIdObj, val: RootRef) = - var h: THash + var h: Hash h = key.id and high(data) while data[h].key != nil: assert(data[h].key.id != key.id) @@ -805,7 +805,7 @@ iterator idTablePairs*(t: TIdTable): tuple[key: PIdObj, val: RootRef] = if not isNil(t.data[i].key): yield (t.data[i].key, t.data[i].val) proc idNodeTableRawGet(t: TIdNodeTable, key: PIdObj): int = - var h: THash + var h: Hash h = key.id and high(t.data) # start with real hash value while t.data[h].key != nil: if t.data[h].key.id == key.id: @@ -824,7 +824,7 @@ proc idNodeTableGetLazy*(t: TIdNodeTable, key: PIdObj): PNode = result = idNodeTableGet(t, key) proc idNodeTableRawInsert(data: var TIdNodePairSeq, key: PIdObj, val: PNode) = - var h: THash + var h: Hash h = key.id and high(data) while data[h].key != nil: assert(data[h].key.id != key.id) @@ -863,7 +863,7 @@ proc initIITable(x: var TIITable) = for i in countup(0, StartSize - 1): x.data[i].key = InvalidKey proc iiTableRawGet(t: TIITable, key: int): int = - var h: THash + var h: Hash h = key and high(t.data) # start with real hash value while t.data[h].key != InvalidKey: if t.data[h].key == key: return h @@ -876,7 +876,7 @@ proc iiTableGet(t: TIITable, key: int): int = else: result = InvalidKey proc iiTableRawInsert(data: var TIIPairSeq, key, val: int) = - var h: THash + var h: Hash h = key and high(data) while data[h].key != InvalidKey: assert(data[h].key != key) diff --git a/compiler/docgen.nim b/compiler/docgen.nim index f8489d825..4b52b1c92 100644 --- a/compiler/docgen.nim +++ b/compiler/docgen.nim @@ -18,7 +18,7 @@ import type TSections = array[TSymKind, Rope] - TDocumentor = object of rstgen.TRstGenerator + TDocumentor = object of rstgen.RstGenerator modDesc: Rope # module description id: int # for generating IDs toc, section: TSections @@ -29,7 +29,7 @@ type PDoc* = ref TDocumentor ## Alias to type less. proc compilerMsgHandler(filename: string, line, col: int, - msgKind: rst.TMsgKind, arg: string) {.procvar.} = + msgKind: rst.MsgKind, arg: string) {.procvar.} = # translate msg kind: var k: msgs.TMsgKind case msgKind @@ -53,7 +53,7 @@ proc docgenFindFile(s: string): string {.procvar.} = proc parseRst(text, filename: string, line, column: int, hasToc: var bool, - rstOptions: TRstParseOptions): PRstNode = + rstOptions: RstParseOptions): PRstNode = result = rstParse(text, filename, line, column, hasToc, rstOptions, docgenFindFile, compilerMsgHandler) diff --git a/compiler/idents.nim b/compiler/idents.nim index 5216b109f..6986800cf 100644 --- a/compiler/idents.nim +++ b/compiler/idents.nim @@ -23,7 +23,7 @@ type TIdent*{.acyclic.} = object of TIdObj s*: string next*: PIdent # for hash-table chaining - h*: THash # hash value of s + h*: Hash # hash value of s var firstCharIsCS*: bool = true var buckets*: array[0..4096 * 2 - 1, PIdent] @@ -67,7 +67,7 @@ proc cmpExact(a, b: cstring, blen: int): int = var wordCounter = 1 -proc getIdent*(identifier: cstring, length: int, h: THash): PIdent = +proc getIdent*(identifier: cstring, length: int, h: Hash): PIdent = var idx = h and high(buckets) result = buckets[idx] var last: PIdent = nil @@ -101,7 +101,7 @@ proc getIdent*(identifier: string): PIdent = result = getIdent(cstring(identifier), len(identifier), hashIgnoreStyle(identifier)) -proc getIdent*(identifier: string, h: THash): PIdent = +proc getIdent*(identifier: string, h: Hash): PIdent = result = getIdent(cstring(identifier), len(identifier), h) proc identEq*(id: PIdent, name: string): bool = diff --git a/compiler/lexer.nim b/compiler/lexer.nim index a4efe2f22..6b38ee062 100644 --- a/compiler/lexer.nim +++ b/compiler/lexer.nim @@ -671,7 +671,7 @@ proc getCharacter(L: var TLexer, tok: var TToken) = inc(L.bufpos) # skip ' proc getSymbol(L: var TLexer, tok: var TToken) = - var h: THash = 0 + var h: Hash = 0 var pos = L.bufpos var buf = L.buf while true: @@ -709,7 +709,7 @@ proc getSymbol(L: var TLexer, tok: var TToken) = tok.tokType = TTokType(tok.ident.id + ord(tkSymbol)) proc endOperator(L: var TLexer, tok: var TToken, pos: int, - hash: THash) {.inline.} = + hash: Hash) {.inline.} = var h = !$hash tok.ident = getIdent(addr(L.buf[L.bufpos]), pos - L.bufpos, h) if (tok.ident.id < oprLow) or (tok.ident.id > oprHigh): tok.tokType = tkOpr @@ -719,7 +719,7 @@ proc endOperator(L: var TLexer, tok: var TToken, pos: int, proc getOperator(L: var TLexer, tok: var TToken) = var pos = L.bufpos var buf = L.buf - var h: THash = 0 + var h: Hash = 0 while true: var c = buf[pos] if c notin OpChars: break diff --git a/compiler/treetab.nim b/compiler/treetab.nim index 8d66d56c7..adfc7b2ce 100644 --- a/compiler/treetab.nim +++ b/compiler/treetab.nim @@ -12,7 +12,7 @@ import hashes, ast, astalgo, types -proc hashTree(n: PNode): THash = +proc hashTree(n: PNode): Hash = if n == nil: return result = ord(n.kind) case n.kind @@ -53,8 +53,8 @@ proc treesEquivalent(a, b: PNode): bool = result = true if result: result = sameTypeOrNil(a.typ, b.typ) -proc nodeTableRawGet(t: TNodeTable, k: THash, key: PNode): int = - var h: THash = k and high(t.data) +proc nodeTableRawGet(t: TNodeTable, k: Hash, key: PNode): int = + var h: Hash = k and high(t.data) while t.data[h].key != nil: if (t.data[h].h == k) and treesEquivalent(t.data[h].key, key): return h @@ -66,9 +66,9 @@ proc nodeTableGet*(t: TNodeTable, key: PNode): int = if index >= 0: result = t.data[index].val else: result = low(int) -proc nodeTableRawInsert(data: var TNodePairSeq, k: THash, key: PNode, +proc nodeTableRawInsert(data: var TNodePairSeq, k: Hash, key: PNode, val: int) = - var h: THash = k and high(data) + var h: Hash = k and high(data) while data[h].key != nil: h = nextTry(h, high(data)) assert(data[h].key == nil) data[h].h = k @@ -77,7 +77,7 @@ proc nodeTableRawInsert(data: var TNodePairSeq, k: THash, key: PNode, proc nodeTablePut*(t: var TNodeTable, key: PNode, val: int) = var n: TNodePairSeq - var k: THash = hashTree(key) + var k: Hash = hashTree(key) var index = nodeTableRawGet(t, k, key) if index >= 0: assert(t.data[index].key != nil) @@ -94,7 +94,7 @@ proc nodeTablePut*(t: var TNodeTable, key: PNode, val: int) = proc nodeTableTestOrSet*(t: var TNodeTable, key: PNode, val: int): int = var n: TNodePairSeq - var k: THash = hashTree(key) + var k: Hash = hashTree(key) var index = nodeTableRawGet(t, k, key) if index >= 0: assert(t.data[index].key != nil) From 6ca3504dfb1f9669d3b3cc0baf386656c4f34785 Mon Sep 17 00:00:00 2001 From: pdw Date: Sun, 24 May 2015 22:21:55 -0500 Subject: [PATCH 0345/1263] lib/core - Dropped 'T' from types --- lib/core/locks.nim | 26 ++++---- lib/core/typeinfo.nim | 139 +++++++++++++++++++++--------------------- 2 files changed, 84 insertions(+), 81 deletions(-) diff --git a/lib/core/locks.nim b/lib/core/locks.nim index 92ae24a37..12f289e74 100644 --- a/lib/core/locks.nim +++ b/lib/core/locks.nim @@ -12,44 +12,46 @@ include "system/syslocks" type - TLock* = TSysLock ## Nim lock; whether this is re-entrant + Lock* = SysLock ## Nim lock; whether this is re-entrant ## or not is unspecified! - TCond* = TSysCond ## Nim condition variable -proc initLock*(lock: var TLock) {.inline.} = + Cond* = SysCond ## Nim condition variable + +{.deprecated: [TLock: Lock, TCond: Cond].} + +proc initLock*(lock: var Lock) {.inline.} = ## Initializes the given lock. initSysLock(lock) -proc deinitLock*(lock: var TLock) {.inline.} = +proc deinitLock*(lock: var Lock) {.inline.} = ## Frees the resources associated with the lock. deinitSys(lock) -proc tryAcquire*(lock: var TLock): bool = +proc tryAcquire*(lock: var Lock): bool = ## Tries to acquire the given lock. Returns `true` on success. result = tryAcquireSys(lock) -proc acquire*(lock: var TLock) = +proc acquire*(lock: var Lock) = ## Acquires the given lock. acquireSys(lock) -proc release*(lock: var TLock) = +proc release*(lock: var Lock) = ## Releases the given lock. releaseSys(lock) -proc initCond*(cond: var TCond) {.inline.} = +proc initCond*(cond: var Cond) {.inline.} = ## Initializes the given condition variable. initSysCond(cond) -proc deinitCond*(cond: var TCond) {.inline.} = +proc deinitCond*(cond: var Cond) {.inline.} = ## Frees the resources associated with the lock. deinitSysCond(cond) -proc wait*(cond: var TCond, lock: var TLock) {.inline.} = +proc wait*(cond: var Cond, lock: var Lock) {.inline.} = ## waits on the condition variable `cond`. waitSysCond(cond, lock) -proc signal*(cond: var TCond) {.inline.} = +proc signal*(cond: var Cond) {.inline.} = ## sends a signal to the condition variable `cond`. signalSysCond(cond) - diff --git a/lib/core/typeinfo.nim b/lib/core/typeinfo.nim index c3ff66591..d7fa2ec9b 100644 --- a/lib/core/typeinfo.nim +++ b/lib/core/typeinfo.nim @@ -9,7 +9,7 @@ ## This module implements an interface to Nim's `runtime type information`:idx: ## (`RTTI`:idx:). -## Note that even though ``TAny`` and its operations hide the nasty low level +## Note that even though ``Any`` and its operations hide the nasty low level ## details from its clients, it remains inherently unsafe! ## ## See the `marshal `_ module for what this module allows you @@ -23,7 +23,7 @@ include "system/hti.nim" {.pop.} type - TAnyKind* = enum ## what kind of ``any`` it is + AnyKind* = enum ## what kind of ``any`` it is akNone = 0, ## invalid any akBool = 1, ## any represents a ``bool`` akChar = 2, ## any represents a ``char`` @@ -55,9 +55,9 @@ type akUInt32 = 43, ## any represents an unsigned int32 akUInt64 = 44, ## any represents an unsigned int64 - TAny* = object ## can represent any nim value; NOTE: the wrapped + Any* = object ## can represent any nim value; NOTE: the wrapped ## value can be modified with its wrapper! This means - ## that ``TAny`` keeps a non-traced pointer to its + ## that ``Any`` keeps a non-traced pointer to its ## wrapped value and **must not** live longer than ## its wrapped value. value: pointer @@ -69,6 +69,7 @@ type TGenericSeq {.importc.} = object len, space: int PGenSeq = ptr TGenericSeq +{.deprecated: [TAny: Any, TAnyKind: AnyKind].} const GenericSeqSize = (2 * sizeof(int)) @@ -103,58 +104,58 @@ proc selectBranch(aa: pointer, n: ptr TNimNode): ptr TNimNode = else: result = n.sons[n.len] -proc newAny(value: pointer, rawType: PNimType): TAny = +proc newAny(value: pointer, rawType: PNimType): Any = result.value = value result.rawType = rawType -when declared(system.TVarSlot): - proc toAny*(x: TVarSlot): TAny {.inline.} = - ## constructs a ``TAny`` object from a variable slot ``x``. +when declared(system.VarSlot): + proc toAny*(x: VarSlot): Any {.inline.} = + ## constructs a ``Any`` object from a variable slot ``x``. ## This captures `x`'s address, so `x` can be modified with its - ## ``TAny`` wrapper! The client needs to ensure that the wrapper + ## ``Any`` wrapper! The client needs to ensure that the wrapper ## **does not** live longer than `x`! ## This is provided for easier reflection capabilities of a debugger. result.value = x.address result.rawType = x.typ -proc toAny*[T](x: var T): TAny {.inline.} = - ## constructs a ``TAny`` object from `x`. This captures `x`'s address, so - ## `x` can be modified with its ``TAny`` wrapper! The client needs to ensure +proc toAny*[T](x: var T): Any {.inline.} = + ## constructs a ``Any`` object from `x`. This captures `x`'s address, so + ## `x` can be modified with its ``Any`` wrapper! The client needs to ensure ## that the wrapper **does not** live longer than `x`! result.value = addr(x) result.rawType = cast[PNimType](getTypeInfo(x)) -proc kind*(x: TAny): TAnyKind {.inline.} = +proc kind*(x: Any): AnyKind {.inline.} = ## get the type kind - result = TAnyKind(ord(x.rawType.kind)) + result = AnyKind(ord(x.rawType.kind)) -proc size*(x: TAny): int {.inline.} = +proc size*(x: Any): int {.inline.} = ## returns the size of `x`'s type. result = x.rawType.size -proc baseTypeKind*(x: TAny): TAnyKind {.inline.} = +proc baseTypeKind*(x: Any): AnyKind {.inline.} = ## get the base type's kind; ``akNone`` is returned if `x` has no base type. if x.rawType.base != nil: - result = TAnyKind(ord(x.rawType.base.kind)) + result = AnyKind(ord(x.rawType.base.kind)) -proc baseTypeSize*(x: TAny): int {.inline.} = +proc baseTypeSize*(x: Any): int {.inline.} = ## returns the size of `x`'s basetype. if x.rawType.base != nil: result = x.rawType.base.size -proc invokeNew*(x: TAny) = +proc invokeNew*(x: Any) = ## performs ``new(x)``. `x` needs to represent a ``ref``. assert x.rawType.kind == tyRef var z = newObj(x.rawType, x.rawType.base.size) genericAssign(x.value, addr(z), x.rawType) -proc invokeNewSeq*(x: TAny, len: int) = +proc invokeNewSeq*(x: Any, len: int) = ## performs ``newSeq(x, len)``. `x` needs to represent a ``seq``. assert x.rawType.kind == tySequence var z = newSeq(x.rawType, len) genericShallowAssign(x.value, addr(z), x.rawType) -proc extendSeq*(x: TAny) = +proc extendSeq*(x: Any) = ## performs ``setLen(x, x.len+1)``. `x` needs to represent a ``seq``. assert x.rawType.kind == tySequence var y = cast[ptr PGenSeq](x.value)[] @@ -164,7 +165,7 @@ proc extendSeq*(x: TAny) = cast[ppointer](x.value)[] = z #genericShallowAssign(x.value, addr(z), x.rawType) -proc setObjectRuntimeType*(x: TAny) = +proc setObjectRuntimeType*(x: Any) = ## this needs to be called to set `x`'s runtime object type field. assert x.rawType.kind == tyObject objectInit(x.value, x.rawType) @@ -173,7 +174,7 @@ proc skipRange(x: PNimType): PNimType {.inline.} = result = x if result.kind == tyRange: result = result.base -proc `[]`*(x: TAny, i: int): TAny = +proc `[]`*(x: Any, i: int): Any = ## accessor for an any `x` that represents an array or a sequence. case x.rawType.kind of tyArray: @@ -190,7 +191,7 @@ proc `[]`*(x: TAny, i: int): TAny = return newAny(s +!! (GenericSeqSize+i*bs), x.rawType.base) else: assert false -proc `[]=`*(x: TAny, i: int, y: TAny) = +proc `[]=`*(x: Any, i: int, y: Any) = ## accessor for an any `x` that represents an array or a sequence. case x.rawType.kind of tyArray: @@ -209,7 +210,7 @@ proc `[]=`*(x: TAny, i: int, y: TAny) = genericAssign(s +!! (GenericSeqSize+i*bs), y.value, y.rawType) else: assert false -proc len*(x: TAny): int = +proc len*(x: Any): int = ## len for an any `x` that represents an array or a sequence. case x.rawType.kind of tyArray: result = x.rawType.size div x.rawType.base.size @@ -217,20 +218,20 @@ proc len*(x: TAny): int = else: assert false -proc base*(x: TAny): TAny = - ## returns base TAny (useful for inherited object types). +proc base*(x: Any): Any = + ## returns base Any (useful for inherited object types). result.rawType = x.rawType.base result.value = x.value -proc isNil*(x: TAny): bool = +proc isNil*(x: Any): bool = ## `isNil` for an any `x` that represents a sequence, string, cstring, ## proc or some pointer type. assert x.rawType.kind in {tyString, tyCString, tyRef, tyPtr, tyPointer, tySequence, tyProc} result = isNil(cast[ppointer](x.value)[]) -proc getPointer*(x: TAny): pointer = +proc getPointer*(x: Any): pointer = ## retrieve the pointer value out of `x`. ``x`` needs to be of kind ## ``akString``, ``akCString``, ``akProc``, ``akRef``, ``akPtr``, ## ``akPointer``, ``akSequence``. @@ -238,7 +239,7 @@ proc getPointer*(x: TAny): pointer = tySequence, tyProc} result = cast[ppointer](x.value)[] -proc setPointer*(x: TAny, y: pointer) = +proc setPointer*(x: Any, y: pointer) = ## sets the pointer value of `x`. ``x`` needs to be of kind ## ``akString``, ``akCString``, ``akProc``, ``akRef``, ``akPtr``, ## ``akPointer``, ``akSequence``. @@ -247,7 +248,7 @@ proc setPointer*(x: TAny, y: pointer) = cast[ppointer](x.value)[] = y proc fieldsAux(p: pointer, n: ptr TNimNode, - ret: var seq[tuple[name: cstring, any: TAny]]) = + ret: var seq[tuple[name: cstring, any: Any]]) = case n.kind of nkNone: assert(false) of nkSlot: @@ -260,7 +261,7 @@ proc fieldsAux(p: pointer, n: ptr TNimNode, ret.add((n.name, newAny(p +!! n.offset, n.typ))) if m != nil: fieldsAux(p, m, ret) -iterator fields*(x: TAny): tuple[name: string, any: TAny] = +iterator fields*(x: Any): tuple[name: string, any: Any] = ## iterates over every active field of the any `x` that represents an object ## or a tuple. assert x.rawType.kind in {tyTuple, tyObject} @@ -269,7 +270,7 @@ iterator fields*(x: TAny): tuple[name: string, any: TAny] = # XXX BUG: does not work yet, however is questionable anyway when false: if x.rawType.kind == tyObject: t = cast[ptr PNimType](x.value)[] - var ret: seq[tuple[name: cstring, any: TAny]] = @[] + var ret: seq[tuple[name: cstring, any: Any]] = @[] if t.kind == tyObject: while true: fieldsAux(p, t.node, ret) @@ -314,7 +315,7 @@ proc getFieldNode(p: pointer, n: ptr TNimNode, var m = selectBranch(p, n) if m != nil: result = getFieldNode(p, m, name) -proc `[]=`*(x: TAny, fieldName: string, value: TAny) = +proc `[]=`*(x: Any, fieldName: string, value: Any) = ## sets a field of `x`; `x` represents an object or a tuple. var t = x.rawType # XXX BUG: does not work yet, however is questionable anyway @@ -328,7 +329,7 @@ proc `[]=`*(x: TAny, fieldName: string, value: TAny) = else: raise newException(ValueError, "invalid field name: " & fieldName) -proc `[]`*(x: TAny, fieldName: string): TAny = +proc `[]`*(x: Any, fieldName: string): Any = ## gets a field of `x`; `x` represents an object or a tuple. var t = x.rawType # XXX BUG: does not work yet, however is questionable anyway @@ -342,44 +343,44 @@ proc `[]`*(x: TAny, fieldName: string): TAny = else: raise newException(ValueError, "invalid field name: " & fieldName) -proc `[]`*(x: TAny): TAny = +proc `[]`*(x: Any): Any = ## dereference operation for the any `x` that represents a ptr or a ref. assert x.rawType.kind in {tyRef, tyPtr} result.value = cast[ppointer](x.value)[] result.rawType = x.rawType.base -proc `[]=`*(x, y: TAny) = +proc `[]=`*(x, y: Any) = ## dereference operation for the any `x` that represents a ptr or a ref. assert x.rawType.kind in {tyRef, tyPtr} assert y.rawType == x.rawType.base genericAssign(cast[ppointer](x.value)[], y.value, y.rawType) -proc getInt*(x: TAny): int = +proc getInt*(x: Any): int = ## retrieve the int value out of `x`. `x` needs to represent an int. assert skipRange(x.rawType).kind == tyInt result = cast[ptr int](x.value)[] -proc getInt8*(x: TAny): int8 = +proc getInt8*(x: Any): int8 = ## retrieve the int8 value out of `x`. `x` needs to represent an int8. assert skipRange(x.rawType).kind == tyInt8 result = cast[ptr int8](x.value)[] -proc getInt16*(x: TAny): int16 = +proc getInt16*(x: Any): int16 = ## retrieve the int16 value out of `x`. `x` needs to represent an int16. assert skipRange(x.rawType).kind == tyInt16 result = cast[ptr int16](x.value)[] -proc getInt32*(x: TAny): int32 = +proc getInt32*(x: Any): int32 = ## retrieve the int32 value out of `x`. `x` needs to represent an int32. assert skipRange(x.rawType).kind == tyInt32 result = cast[ptr int32](x.value)[] -proc getInt64*(x: TAny): int64 = +proc getInt64*(x: Any): int64 = ## retrieve the int64 value out of `x`. `x` needs to represent an int64. assert skipRange(x.rawType).kind == tyInt64 result = cast[ptr int64](x.value)[] -proc getBiggestInt*(x: TAny): BiggestInt = +proc getBiggestInt*(x: Any): BiggestInt = ## retrieve the integer value out of `x`. `x` needs to represent ## some integer, a bool, a char, an enum or a small enough bit set. ## The value might be sign-extended to ``BiggestInt``. @@ -405,7 +406,7 @@ proc getBiggestInt*(x: TAny): BiggestInt = of tyUInt32: result = BiggestInt(cast[ptr uint32](x.value)[]) else: assert false -proc setBiggestInt*(x: TAny, y: BiggestInt) = +proc setBiggestInt*(x: Any, y: BiggestInt) = ## sets the integer value of `x`. `x` needs to represent ## some integer, a bool, a char, an enum or a small enough bit set. var t = skipRange(x.rawType) @@ -430,36 +431,36 @@ proc setBiggestInt*(x: TAny, y: BiggestInt) = of tyUInt32: cast[ptr uint32](x.value)[] = uint32(y) else: assert false -proc getUInt*(x: TAny): uint = +proc getUInt*(x: Any): uint = ## retrieve the uint value out of `x`, `x` needs to represent an uint. assert skipRange(x.rawType).kind == tyUInt result = cast[ptr uint](x.value)[] -proc getUInt8*(x: TAny): uint8 = +proc getUInt8*(x: Any): uint8 = ## retrieve the uint8 value out of `x`, `x` needs to represent an ## uint8. assert skipRange(x.rawType).kind == tyUInt8 result = cast[ptr uint8](x.value)[] -proc getUInt16*(x: TAny): uint16 = +proc getUInt16*(x: Any): uint16 = ## retrieve the uint16 value out of `x`, `x` needs to represent an ## uint16. assert skipRange(x.rawType).kind == tyUInt16 result = cast[ptr uint16](x.value)[] -proc getUInt32*(x: TAny): uint32 = +proc getUInt32*(x: Any): uint32 = ## retrieve the uint32 value out of `x`, `x` needs to represent an ## uint32. assert skipRange(x.rawType).kind == tyUInt32 result = cast[ptr uint32](x.value)[] -proc getUInt64*(x: TAny): uint64 = +proc getUInt64*(x: Any): uint64 = ## retrieve the uint64 value out of `x`, `x` needs to represent an ## uint64. assert skipRange(x.rawType).kind == tyUInt64 result = cast[ptr uint64](x.value)[] -proc getBiggestUint*(x: TAny): uint64 = +proc getBiggestUint*(x: Any): uint64 = ## retrieve the unsigned integer value out of `x`. `x` needs to ## represent an unsigned integer. var t = skipRange(x.rawType) @@ -471,7 +472,7 @@ proc getBiggestUint*(x: TAny): uint64 = of tyUInt64: result = uint64(cast[ptr uint64](x.value)[]) else: assert false -proc setBiggestUint*(x: TAny; y: uint64) = +proc setBiggestUint*(x: Any; y: uint64) = ## sets the unsigned integer value of `c`. `c` needs to represent an ## unsigned integer. var t = skipRange(x.rawType) @@ -483,25 +484,25 @@ proc setBiggestUint*(x: TAny; y: uint64) = of tyUInt64: cast[ptr uint64](x.value)[] = uint64(y) else: assert false -proc getChar*(x: TAny): char = +proc getChar*(x: Any): char = ## retrieve the char value out of `x`. `x` needs to represent a char. var t = skipRange(x.rawType) assert t.kind == tyChar result = cast[ptr char](x.value)[] -proc getBool*(x: TAny): bool = +proc getBool*(x: Any): bool = ## retrieve the bool value out of `x`. `x` needs to represent a bool. var t = skipRange(x.rawType) assert t.kind == tyBool result = cast[ptr bool](x.value)[] -proc skipRange*(x: TAny): TAny = +proc skipRange*(x: Any): Any = ## skips the range information of `x`. assert x.rawType.kind == tyRange result.rawType = x.rawType.base result.value = x.value -proc getEnumOrdinal*(x: TAny, name: string): int = +proc getEnumOrdinal*(x: Any, name: string): int = ## gets the enum field ordinal from `name`. `x` needs to represent an enum ## but is only used to access the type information. In case of an error ## ``low(int)`` is returned. @@ -517,7 +518,7 @@ proc getEnumOrdinal*(x: TAny, name: string): int = return s[i].offset result = low(int) -proc getEnumField*(x: TAny, ordinalValue: int): string = +proc getEnumField*(x: Any, ordinalValue: int): string = ## gets the enum field name as a string. `x` needs to represent an enum ## but is only used to access the type information. The field name of ## `ordinalValue` is returned. @@ -535,26 +536,26 @@ proc getEnumField*(x: TAny, ordinalValue: int): string = if s[i].offset == e: return $s[i].name result = $e -proc getEnumField*(x: TAny): string = +proc getEnumField*(x: Any): string = ## gets the enum field name as a string. `x` needs to represent an enum. result = getEnumField(x, getBiggestInt(x).int) -proc getFloat*(x: TAny): float = +proc getFloat*(x: Any): float = ## retrieve the float value out of `x`. `x` needs to represent an float. assert skipRange(x.rawType).kind == tyFloat result = cast[ptr float](x.value)[] -proc getFloat32*(x: TAny): float32 = +proc getFloat32*(x: Any): float32 = ## retrieve the float32 value out of `x`. `x` needs to represent an float32. assert skipRange(x.rawType).kind == tyFloat32 result = cast[ptr float32](x.value)[] -proc getFloat64*(x: TAny): float64 = +proc getFloat64*(x: Any): float64 = ## retrieve the float64 value out of `x`. `x` needs to represent an float64. assert skipRange(x.rawType).kind == tyFloat64 result = cast[ptr float64](x.value)[] -proc getBiggestFloat*(x: TAny): BiggestFloat = +proc getBiggestFloat*(x: Any): BiggestFloat = ## retrieve the float value out of `x`. `x` needs to represent ## some float. The value is extended to ``BiggestFloat``. case skipRange(x.rawType).kind @@ -563,7 +564,7 @@ proc getBiggestFloat*(x: TAny): BiggestFloat = of tyFloat64: result = BiggestFloat(cast[ptr float64](x.value)[]) else: assert false -proc setBiggestFloat*(x: TAny, y: BiggestFloat) = +proc setBiggestFloat*(x: Any, y: BiggestFloat) = ## sets the float value of `x`. `x` needs to represent ## some float. case skipRange(x.rawType).kind @@ -572,29 +573,29 @@ proc setBiggestFloat*(x: TAny, y: BiggestFloat) = of tyFloat64: cast[ptr float64](x.value)[] = y else: assert false -proc getString*(x: TAny): string = +proc getString*(x: Any): string = ## retrieve the string value out of `x`. `x` needs to represent a string. assert x.rawType.kind == tyString if not isNil(cast[ptr pointer](x.value)[]): result = cast[ptr string](x.value)[] -proc setString*(x: TAny, y: string) = +proc setString*(x: Any, y: string) = ## sets the string value of `x`. `x` needs to represent a string. assert x.rawType.kind == tyString cast[ptr string](x.value)[] = y -proc getCString*(x: TAny): cstring = +proc getCString*(x: Any): cstring = ## retrieve the cstring value out of `x`. `x` needs to represent a cstring. assert x.rawType.kind == tyCString result = cast[ptr cstring](x.value)[] -proc assign*(x, y: TAny) = - ## copies the value of `y` to `x`. The assignment operator for ``TAny`` +proc assign*(x, y: Any) = + ## copies the value of `y` to `x`. The assignment operator for ``Any`` ## does NOT do this; it performs a shallow copy instead! assert y.rawType == x.rawType genericAssign(x.value, y.value, y.rawType) -iterator elements*(x: TAny): int = +iterator elements*(x: Any): int = ## iterates over every element of `x` that represents a Nim bitset. assert x.rawType.kind == tySet var typ = x.rawType @@ -616,7 +617,7 @@ iterator elements*(x: TAny): int = if (u and (1'i64 shl int64(i))) != 0'i64: yield i+typ.node.len -proc inclSetElement*(x: TAny, elem: int) = +proc inclSetElement*(x: Any, elem: int) = ## includes an element `elem` in `x`. `x` needs to represent a Nim bitset. assert x.rawType.kind == tySet var typ = x.rawType From ea03fc68862494b07242a06d45907be8823132d2 Mon Sep 17 00:00:00 2001 From: pdw Date: Sun, 24 May 2015 22:24:07 -0500 Subject: [PATCH 0346/1263] lib/impure - Dropped 'T' from types --- lib/impure/db_mysql.nim | 61 +++++++++++++------------- lib/impure/db_postgres.nim | 88 +++++++++++++++++++------------------- lib/impure/db_sqlite.nim | 61 +++++++++++++------------- lib/impure/graphics.nim | 58 +++++++++++++------------ lib/impure/rdstdin.nim | 2 +- lib/impure/ssl.nim | 13 +++--- lib/impure/zipfiles.nim | 39 +++++++++-------- 7 files changed, 165 insertions(+), 157 deletions(-) diff --git a/lib/impure/db_mysql.nim b/lib/impure/db_mysql.nim index b8180cd87..619c2a656 100644 --- a/lib/impure/db_mysql.nim +++ b/lib/impure/db_mysql.nim @@ -13,27 +13,28 @@ import strutils, mysql type - TDbConn* = PMySQL ## encapsulates a database connection - TRow* = seq[string] ## a row of a dataset. NULL database values will be + DbConn* = PMySQL ## encapsulates a database connection + Row* = seq[string] ## a row of a dataset. NULL database values will be ## transformed always to the empty string. EDb* = object of IOError ## exception that is raised if a database error occurs - TSqlQuery* = distinct string ## an SQL query string + SqlQuery* = distinct string ## an SQL query string FDb* = object of IOEffect ## effect that denotes a database operation FReadDb* = object of FDb ## effect that denotes a read operation FWriteDb* = object of FDb ## effect that denotes a write operation +{.deprecated: [TRow: Row, TSqlQuery: SqlQuery, TDbConn: DbConn].} -proc sql*(query: string): TSqlQuery {.noSideEffect, inline.} = - ## constructs a TSqlQuery from the string `query`. This is supposed to be +proc sql*(query: string): SqlQuery {.noSideEffect, inline.} = + ## constructs a SqlQuery from the string `query`. This is supposed to be ## used as a raw-string-literal modifier: ## ``sql"update user set counter = counter + 1"`` ## ## If assertions are turned off, it does nothing. If assertions are turned ## on, later versions will check the string for valid syntax. - result = TSqlQuery(query) + result = SqlQuery(query) -proc dbError(db: TDbConn) {.noreturn.} = +proc dbError(db: DbConn) {.noreturn.} = ## raises an EDb exception. var e: ref EDb new(e) @@ -48,7 +49,7 @@ proc dbError*(msg: string) {.noreturn.} = raise e when false: - proc dbQueryOpt*(db: TDbConn, query: string, args: varargs[string, `$`]) = + proc dbQueryOpt*(db: DbConn, query: string, args: varargs[string, `$`]) = var stmt = mysql_stmt_init(db) if stmt == nil: dbError(db) if mysql_stmt_prepare(stmt, query, len(query)) != 0: @@ -65,7 +66,7 @@ proc dbQuote*(s: string): string = else: add(result, c) add(result, '\'') -proc dbFormat(formatstr: TSqlQuery, args: varargs[string]): string = +proc dbFormat(formatstr: SqlQuery, args: varargs[string]): string = result = "" var a = 0 for c in items(string(formatstr)): @@ -78,23 +79,23 @@ proc dbFormat(formatstr: TSqlQuery, args: varargs[string]): string = else: add(result, c) -proc tryExec*(db: TDbConn, query: TSqlQuery, args: varargs[string, `$`]): bool {. +proc tryExec*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]): bool {. tags: [FReadDB, FWriteDb].} = ## tries to execute the query and returns true if successful, false otherwise. var q = dbFormat(query, args) return mysql.realQuery(db, q, q.len) == 0'i32 -proc rawExec(db: TDbConn, query: TSqlQuery, args: varargs[string, `$`]) = +proc rawExec(db: DbConn, query: SqlQuery, args: varargs[string, `$`]) = var q = dbFormat(query, args) if mysql.realQuery(db, q, q.len) != 0'i32: dbError(db) -proc exec*(db: TDbConn, query: TSqlQuery, args: varargs[string, `$`]) {. +proc exec*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]) {. tags: [FReadDB, FWriteDb].} = ## executes the query and raises EDB if not successful. var q = dbFormat(query, args) if mysql.realQuery(db, q, q.len) != 0'i32: dbError(db) -proc newRow(L: int): TRow = +proc newRow(L: int): Row = newSeq(result, L) for i in 0..L-1: result[i] = "" @@ -103,8 +104,8 @@ proc properFreeResult(sqlres: mysql.PRES, row: cstringArray) = while mysql.fetchRow(sqlres) != nil: discard mysql.freeResult(sqlres) -iterator fastRows*(db: TDbConn, query: TSqlQuery, - args: varargs[string, `$`]): TRow {.tags: [FReadDB].} = +iterator fastRows*(db: DbConn, query: SqlQuery, + args: varargs[string, `$`]): Row {.tags: [FReadDB].} = ## executes the query and iterates over the result dataset. This is very ## fast, but potenially dangerous: If the for-loop-body executes another ## query, the results can be undefined. For MySQL this is the case!. @@ -126,10 +127,10 @@ iterator fastRows*(db: TDbConn, query: TSqlQuery, yield result properFreeResult(sqlres, row) -proc getRow*(db: TDbConn, query: TSqlQuery, - args: varargs[string, `$`]): TRow {.tags: [FReadDB].} = +proc getRow*(db: DbConn, query: SqlQuery, + args: varargs[string, `$`]): Row {.tags: [FReadDB].} = ## retrieves a single row. If the query doesn't return any rows, this proc - ## will return a TRow with empty strings for each column. + ## will return a Row with empty strings for each column. rawExec(db, query, args) var sqlres = mysql.useResult(db) if sqlres != nil: @@ -145,8 +146,8 @@ proc getRow*(db: TDbConn, query: TSqlQuery, add(result[i], row[i]) properFreeResult(sqlres, row) -proc getAllRows*(db: TDbConn, query: TSqlQuery, - args: varargs[string, `$`]): seq[TRow] {.tags: [FReadDB].} = +proc getAllRows*(db: DbConn, query: SqlQuery, + args: varargs[string, `$`]): seq[Row] {.tags: [FReadDB].} = ## executes the query and returns the whole result dataset. result = @[] rawExec(db, query, args) @@ -168,12 +169,12 @@ proc getAllRows*(db: TDbConn, query: TSqlQuery, inc(j) mysql.freeResult(sqlres) -iterator rows*(db: TDbConn, query: TSqlQuery, - args: varargs[string, `$`]): TRow {.tags: [FReadDB].} = +iterator rows*(db: DbConn, query: SqlQuery, + args: varargs[string, `$`]): Row {.tags: [FReadDB].} = ## same as `fastRows`, but slower and safe. for r in items(getAllRows(db, query, args)): yield r -proc getValue*(db: TDbConn, query: TSqlQuery, +proc getValue*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]): string {.tags: [FReadDB].} = ## executes the query and returns the first column of the first row of the ## result dataset. Returns "" if the dataset contains no rows or the database @@ -183,7 +184,7 @@ proc getValue*(db: TDbConn, query: TSqlQuery, result = row[0] break -proc tryInsertId*(db: TDbConn, query: TSqlQuery, +proc tryInsertId*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]): int64 {.tags: [FWriteDb].} = ## executes the query (typically "INSERT") and returns the ## generated ID for the row or -1 in case of an error. @@ -193,14 +194,14 @@ proc tryInsertId*(db: TDbConn, query: TSqlQuery, else: result = mysql.insertId(db) -proc insertId*(db: TDbConn, query: TSqlQuery, +proc insertId*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]): int64 {.tags: [FWriteDb].} = ## executes the query (typically "INSERT") and returns the ## generated ID for the row. result = tryInsertID(db, query, args) if result < 0: dbError(db) -proc execAffectedRows*(db: TDbConn, query: TSqlQuery, +proc execAffectedRows*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]): int64 {. tags: [FReadDB, FWriteDb].} = ## runs the query (typically "UPDATE") and returns the @@ -208,11 +209,11 @@ proc execAffectedRows*(db: TDbConn, query: TSqlQuery, rawExec(db, query, args) result = mysql.affectedRows(db) -proc close*(db: TDbConn) {.tags: [FDb].} = +proc close*(db: DbConn) {.tags: [FDb].} = ## closes the database connection. if db != nil: mysql.close(db) -proc open*(connection, user, password, database: string): TDbConn {. +proc open*(connection, user, password, database: string): DbConn {. tags: [FDb].} = ## opens a database connection. Raises `EDb` if the connection could not ## be established. @@ -230,8 +231,8 @@ proc open*(connection, user, password, database: string): TDbConn {. db_mysql.close(result) dbError(errmsg) -proc setEncoding*(connection: TDbConn, encoding: string): bool {. +proc setEncoding*(connection: DbConn, encoding: string): bool {. tags: [FDb].} = ## sets the encoding of a database connection, returns true for ## success, false for failure. - result = mysql.set_character_set(connection, encoding) == 0 \ No newline at end of file + result = mysql.set_character_set(connection, encoding) == 0 diff --git a/lib/impure/db_postgres.nim b/lib/impure/db_postgres.nim index ffb8bbcda..774cb1510 100644 --- a/lib/impure/db_postgres.nim +++ b/lib/impure/db_postgres.nim @@ -13,28 +13,30 @@ import strutils, postgres type - TDbConn* = PPGconn ## encapsulates a database connection - TRow* = seq[string] ## a row of a dataset. NULL database values will be + DbConn* = PPGconn ## encapsulates a database connection + Row* = seq[string] ## a row of a dataset. NULL database values will be ## transformed always to the empty string. EDb* = object of IOError ## exception that is raised if a database error occurs - TSqlQuery* = distinct string ## an SQL query string - TSqlPrepared* = distinct string ## a identifier for the prepared queries + SqlQuery* = distinct string ## an SQL query string + SqlPrepared* = distinct string ## a identifier for the prepared queries FDb* = object of IOEffect ## effect that denotes a database operation FReadDb* = object of FDb ## effect that denotes a read operation FWriteDb* = object of FDb ## effect that denotes a write operation +{.deprecated: [TRow: Row, TSqlQuery: SqlQuery, TDbConn: DbConn, + TSqlPrepared: SqlPrepared].} -proc sql*(query: string): TSqlQuery {.noSideEffect, inline.} = - ## constructs a TSqlQuery from the string `query`. This is supposed to be +proc sql*(query: string): SqlQuery {.noSideEffect, inline.} = + ## constructs a SqlQuery from the string `query`. This is supposed to be ## used as a raw-string-literal modifier: ## ``sql"update user set counter = counter + 1"`` ## ## If assertions are turned off, it does nothing. If assertions are turned ## on, later versions will check the string for valid syntax. - result = TSqlQuery(query) + result = SqlQuery(query) -proc dbError*(db: TDbConn) {.noreturn.} = +proc dbError*(db: DbConn) {.noreturn.} = ## raises an EDb exception. var e: ref EDb new(e) @@ -56,7 +58,7 @@ proc dbQuote*(s: string): string = else: add(result, c) add(result, '\'') -proc dbFormat(formatstr: TSqlQuery, args: varargs[string]): string = +proc dbFormat(formatstr: SqlQuery, args: varargs[string]): string = result = "" var a = 0 for c in items(string(formatstr)): @@ -69,7 +71,7 @@ proc dbFormat(formatstr: TSqlQuery, args: varargs[string]): string = else: add(result, c) -proc tryExec*(db: TDbConn, query: TSqlQuery, +proc tryExec*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]): bool {.tags: [FReadDB, FWriteDb].} = ## tries to execute the query and returns true if successful, false otherwise. var arr = allocCStringArray(args) @@ -79,7 +81,7 @@ proc tryExec*(db: TDbConn, query: TSqlQuery, result = pqresultStatus(res) == PGRES_COMMAND_OK pqclear(res) -proc exec*(db: TDbConn, query: TSqlQuery, args: varargs[string, `$`]) {. +proc exec*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]) {. tags: [FReadDB, FWriteDb].} = ## executes the query and raises EDB if not successful. var arr = allocCStringArray(args) @@ -89,7 +91,7 @@ proc exec*(db: TDbConn, query: TSqlQuery, args: varargs[string, `$`]) {. if pqresultStatus(res) != PGRES_COMMAND_OK: dbError(db) pqclear(res) -proc exec*(db: TDbConn, stmtName: TSqlPrepared, +proc exec*(db: DbConn, stmtName: SqlPrepared, args: varargs[string]) {.tags: [FReadDB, FWriteDb].} = var arr = allocCStringArray(args) var res = pqexecPrepared(db, stmtName.string, int32(args.len), arr, @@ -98,11 +100,11 @@ proc exec*(db: TDbConn, stmtName: TSqlPrepared, if pqResultStatus(res) != PGRES_COMMAND_OK: dbError(db) pqclear(res) -proc newRow(L: int): TRow = +proc newRow(L: int): Row = newSeq(result, L) for i in 0..L-1: result[i] = "" -proc setupQuery(db: TDbConn, query: TSqlQuery, +proc setupQuery(db: DbConn, query: SqlQuery, args: varargs[string]): PPGresult = var arr = allocCStringArray(args) result = pqexecParams(db, query.string, int32(args.len), nil, arr, @@ -110,7 +112,7 @@ proc setupQuery(db: TDbConn, query: TSqlQuery, deallocCStringArray(arr) if pqResultStatus(result) != PGRES_TUPLES_OK: dbError(db) -proc setupQuery(db: TDbConn, stmtName: TSqlPrepared, +proc setupQuery(db: DbConn, stmtName: SqlPrepared, args: varargs[string]): PPGresult = var arr = allocCStringArray(args) result = pqexecPrepared(db, stmtName.string, int32(args.len), arr, @@ -118,13 +120,13 @@ proc setupQuery(db: TDbConn, stmtName: TSqlPrepared, deallocCStringArray(arr) if pqResultStatus(result) != PGRES_TUPLES_OK: dbError(db) -proc prepare*(db: TDbConn; stmtName: string, query: TSqlQuery; - nParams: int): TSqlPrepared = +proc prepare*(db: DbConn; stmtName: string, query: SqlQuery; + nParams: int): SqlPrepared = var res = pqprepare(db, stmtName, query.string, int32(nParams), nil) if pqResultStatus(res) != PGRES_COMMAND_OK: dbError(db) - return TSqlPrepared(stmtName) + return SqlPrepared(stmtName) -proc setRow(res: PPGresult, r: var TRow, line, cols: int32) = +proc setRow(res: PPGresult, r: var Row, line, cols: int32) = for col in 0..cols-1: setLen(r[col], 0) let x = pqgetvalue(res, line, col) @@ -133,8 +135,8 @@ proc setRow(res: PPGresult, r: var TRow, line, cols: int32) = else: add(r[col], x) -iterator fastRows*(db: TDbConn, query: TSqlQuery, - args: varargs[string, `$`]): TRow {.tags: [FReadDB].} = +iterator fastRows*(db: DbConn, query: SqlQuery, + args: varargs[string, `$`]): Row {.tags: [FReadDB].} = ## executes the query and iterates over the result dataset. This is very ## fast, but potenially dangerous: If the for-loop-body executes another ## query, the results can be undefined. For Postgres it is safe though. @@ -146,8 +148,8 @@ iterator fastRows*(db: TDbConn, query: TSqlQuery, yield result pqclear(res) -iterator fastRows*(db: TDbConn, stmtName: TSqlPrepared, - args: varargs[string, `$`]): TRow {.tags: [FReadDB].} = +iterator fastRows*(db: DbConn, stmtName: SqlPrepared, + args: varargs[string, `$`]): Row {.tags: [FReadDB].} = ## executes the prepared query and iterates over the result dataset. var res = setupQuery(db, stmtName, args) var L = pqNfields(res) @@ -157,44 +159,44 @@ iterator fastRows*(db: TDbConn, stmtName: TSqlPrepared, yield result pqClear(res) -proc getRow*(db: TDbConn, query: TSqlQuery, - args: varargs[string, `$`]): TRow {.tags: [FReadDB].} = +proc getRow*(db: DbConn, query: SqlQuery, + args: varargs[string, `$`]): Row {.tags: [FReadDB].} = ## retrieves a single row. If the query doesn't return any rows, this proc - ## will return a TRow with empty strings for each column. + ## will return a Row with empty strings for each column. var res = setupQuery(db, query, args) var L = pqnfields(res) result = newRow(L) setRow(res, result, 0, L) pqclear(res) -proc getRow*(db: TDbConn, stmtName: TSqlPrepared, - args: varargs[string, `$`]): TRow {.tags: [FReadDB].} = +proc getRow*(db: DbConn, stmtName: SqlPrepared, + args: varargs[string, `$`]): Row {.tags: [FReadDB].} = var res = setupQuery(db, stmtName, args) var L = pqNfields(res) result = newRow(L) setRow(res, result, 0, L) pqClear(res) -proc getAllRows*(db: TDbConn, query: TSqlQuery, - args: varargs[string, `$`]): seq[TRow] {.tags: [FReadDB].} = +proc getAllRows*(db: DbConn, query: SqlQuery, + args: varargs[string, `$`]): seq[Row] {.tags: [FReadDB].} = ## executes the query and returns the whole result dataset. result = @[] for r in fastRows(db, query, args): result.add(r) -proc getAllRows*(db: TDbConn, stmtName: TSqlPrepared, - args: varargs[string, `$`]): seq[TRow] {.tags: [FReadDB].} = +proc getAllRows*(db: DbConn, stmtName: SqlPrepared, + args: varargs[string, `$`]): seq[Row] {.tags: [FReadDB].} = ## executes the prepared query and returns the whole result dataset. result = @[] for r in fastRows(db, stmtName, args): result.add(r) -iterator rows*(db: TDbConn, query: TSqlQuery, - args: varargs[string, `$`]): TRow {.tags: [FReadDB].} = +iterator rows*(db: DbConn, query: SqlQuery, + args: varargs[string, `$`]): Row {.tags: [FReadDB].} = ## same as `fastRows`, but slower and safe. for r in items(getAllRows(db, query, args)): yield r -proc getValue*(db: TDbConn, query: TSqlQuery, +proc getValue*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]): string {.tags: [FReadDB].} = ## executes the query and returns the first column of the first row of the ## result dataset. Returns "" if the dataset contains no rows or the database @@ -202,20 +204,20 @@ proc getValue*(db: TDbConn, query: TSqlQuery, var x = pqgetvalue(setupQuery(db, query, args), 0, 0) result = if isNil(x): "" else: $x -proc tryInsertID*(db: TDbConn, query: TSqlQuery, +proc tryInsertID*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]): int64 {.tags: [FWriteDb].}= ## executes the query (typically "INSERT") and returns the ## generated ID for the row or -1 in case of an error. For Postgre this adds ## ``RETURNING id`` to the query, so it only works if your primary key is ## named ``id``. - var x = pqgetvalue(setupQuery(db, TSqlQuery(string(query) & " RETURNING id"), + var x = pqgetvalue(setupQuery(db, SqlQuery(string(query) & " RETURNING id"), args), 0, 0) if not isNil(x): result = parseBiggestInt($x) else: result = -1 -proc insertID*(db: TDbConn, query: TSqlQuery, +proc insertID*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]): int64 {.tags: [FWriteDb].} = ## executes the query (typically "INSERT") and returns the ## generated ID for the row. For Postgre this adds @@ -224,7 +226,7 @@ proc insertID*(db: TDbConn, query: TSqlQuery, result = tryInsertID(db, query, args) if result < 0: dbError(db) -proc execAffectedRows*(db: TDbConn, query: TSqlQuery, +proc execAffectedRows*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]): int64 {.tags: [ FReadDB, FWriteDb].} = ## executes the query (typically "UPDATE") and returns the @@ -235,11 +237,11 @@ proc execAffectedRows*(db: TDbConn, query: TSqlQuery, result = parseBiggestInt($pqcmdTuples(res)) pqclear(res) -proc close*(db: TDbConn) {.tags: [FDb].} = +proc close*(db: DbConn) {.tags: [FDb].} = ## closes the database connection. if db != nil: pqfinish(db) -proc open*(connection, user, password, database: string): TDbConn {. +proc open*(connection, user, password, database: string): DbConn {. tags: [FDb].} = ## opens a database connection. Raises `EDb` if the connection could not ## be established. @@ -261,8 +263,8 @@ proc open*(connection, user, password, database: string): TDbConn {. result = pqsetdbLogin(nil, nil, nil, nil, database, user, password) if pqStatus(result) != CONNECTION_OK: dbError(result) # result = nil -proc setEncoding*(connection: TDbConn, encoding: string): bool {. +proc setEncoding*(connection: DbConn, encoding: string): bool {. tags: [FDb].} = ## sets the encoding of a database connection, returns true for ## success, false for failure. - return pqsetClientEncoding(connection, encoding) == 0 \ No newline at end of file + return pqsetClientEncoding(connection, encoding) == 0 diff --git a/lib/impure/db_sqlite.nim b/lib/impure/db_sqlite.nim index 8536ab6f2..47e7c1900 100644 --- a/lib/impure/db_sqlite.nim +++ b/lib/impure/db_sqlite.nim @@ -13,27 +13,28 @@ import strutils, sqlite3 type - TDbConn* = PSqlite3 ## encapsulates a database connection - TRow* = seq[string] ## a row of a dataset. NULL database values will be + DbConn* = PSqlite3 ## encapsulates a database connection + Row* = seq[string] ## a row of a dataset. NULL database values will be ## transformed always to the empty string. EDb* = object of IOError ## exception that is raised if a database error occurs - TSqlQuery* = distinct string ## an SQL query string + SqlQuery* = distinct string ## an SQL query string FDb* = object of IOEffect ## effect that denotes a database operation FReadDb* = object of FDb ## effect that denotes a read operation FWriteDb* = object of FDb ## effect that denotes a write operation +{.deprecated: [TRow: Row, TSqlQuery: SqlQuery, TDbConn: DbConn].} -proc sql*(query: string): TSqlQuery {.noSideEffect, inline.} = - ## constructs a TSqlQuery from the string `query`. This is supposed to be +proc sql*(query: string): SqlQuery {.noSideEffect, inline.} = + ## constructs a SqlQuery from the string `query`. This is supposed to be ## used as a raw-string-literal modifier: ## ``sql"update user set counter = counter + 1"`` ## ## If assertions are turned off, it does nothing. If assertions are turned ## on, later versions will check the string for valid syntax. - result = TSqlQuery(query) + result = SqlQuery(query) -proc dbError(db: TDbConn) {.noreturn.} = +proc dbError(db: DbConn) {.noreturn.} = ## raises an EDb exception. var e: ref EDb new(e) @@ -55,7 +56,7 @@ proc dbQuote(s: string): string = else: add(result, c) add(result, '\'') -proc dbFormat(formatstr: TSqlQuery, args: varargs[string]): string = +proc dbFormat(formatstr: SqlQuery, args: varargs[string]): string = result = "" var a = 0 for c in items(string(formatstr)): @@ -65,7 +66,7 @@ proc dbFormat(formatstr: TSqlQuery, args: varargs[string]): string = else: add(result, c) -proc tryExec*(db: TDbConn, query: TSqlQuery, +proc tryExec*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]): bool {.tags: [FReadDb, FWriteDb].} = ## tries to execute the query and returns true if successful, false otherwise. var q = dbFormat(query, args) @@ -74,29 +75,29 @@ proc tryExec*(db: TDbConn, query: TSqlQuery, if step(stmt) == SQLITE_DONE: result = finalize(stmt) == SQLITE_OK -proc exec*(db: TDbConn, query: TSqlQuery, args: varargs[string, `$`]) {. +proc exec*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]) {. tags: [FReadDb, FWriteDb].} = ## executes the query and raises EDB if not successful. if not tryExec(db, query, args): dbError(db) -proc newRow(L: int): TRow = +proc newRow(L: int): Row = newSeq(result, L) for i in 0..L-1: result[i] = "" -proc setupQuery(db: TDbConn, query: TSqlQuery, +proc setupQuery(db: DbConn, query: SqlQuery, args: varargs[string]): Pstmt = var q = dbFormat(query, args) if prepare_v2(db, q, q.len.cint, result, nil) != SQLITE_OK: dbError(db) -proc setRow(stmt: Pstmt, r: var TRow, cols: cint) = +proc setRow(stmt: Pstmt, r: var Row, cols: cint) = for col in 0..cols-1: setLen(r[col], column_bytes(stmt, col)) # set capacity setLen(r[col], 0) let x = column_text(stmt, col) if not isNil(x): add(r[col], x) -iterator fastRows*(db: TDbConn, query: TSqlQuery, - args: varargs[string, `$`]): TRow {.tags: [FReadDb].} = +iterator fastRows*(db: DbConn, query: SqlQuery, + args: varargs[string, `$`]): Row {.tags: [FReadDb].} = ## executes the query and iterates over the result dataset. This is very ## fast, but potenially dangerous: If the for-loop-body executes another ## query, the results can be undefined. For Sqlite it is safe though. @@ -108,10 +109,10 @@ iterator fastRows*(db: TDbConn, query: TSqlQuery, yield result if finalize(stmt) != SQLITE_OK: dbError(db) -proc getRow*(db: TDbConn, query: TSqlQuery, - args: varargs[string, `$`]): TRow {.tags: [FReadDb].} = +proc getRow*(db: DbConn, query: SqlQuery, + args: varargs[string, `$`]): Row {.tags: [FReadDb].} = ## retrieves a single row. If the query doesn't return any rows, this proc - ## will return a TRow with empty strings for each column. + ## will return a Row with empty strings for each column. var stmt = setupQuery(db, query, args) var L = (column_count(stmt)) result = newRow(L) @@ -119,19 +120,19 @@ proc getRow*(db: TDbConn, query: TSqlQuery, setRow(stmt, result, L) if finalize(stmt) != SQLITE_OK: dbError(db) -proc getAllRows*(db: TDbConn, query: TSqlQuery, - args: varargs[string, `$`]): seq[TRow] {.tags: [FReadDb].} = +proc getAllRows*(db: DbConn, query: SqlQuery, + args: varargs[string, `$`]): seq[Row] {.tags: [FReadDb].} = ## executes the query and returns the whole result dataset. result = @[] for r in fastRows(db, query, args): result.add(r) -iterator rows*(db: TDbConn, query: TSqlQuery, - args: varargs[string, `$`]): TRow {.tags: [FReadDb].} = +iterator rows*(db: DbConn, query: SqlQuery, + args: varargs[string, `$`]): Row {.tags: [FReadDb].} = ## same as `FastRows`, but slower and safe. for r in fastRows(db, query, args): yield r -proc getValue*(db: TDbConn, query: TSqlQuery, +proc getValue*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]): string {.tags: [FReadDb].} = ## executes the query and returns the first column of the first row of the ## result dataset. Returns "" if the dataset contains no rows or the database @@ -148,7 +149,7 @@ proc getValue*(db: TDbConn, query: TSqlQuery, result = "" if finalize(stmt) != SQLITE_OK: dbError(db) -proc tryInsertID*(db: TDbConn, query: TSqlQuery, +proc tryInsertID*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]): int64 {.tags: [FWriteDb], raises: [].} = ## executes the query (typically "INSERT") and returns the @@ -162,7 +163,7 @@ proc tryInsertID*(db: TDbConn, query: TSqlQuery, if finalize(stmt) != SQLITE_OK: result = -1 -proc insertID*(db: TDbConn, query: TSqlQuery, +proc insertID*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]): int64 {.tags: [FWriteDb].} = ## executes the query (typically "INSERT") and returns the ## generated ID for the row. For Postgre this adds @@ -171,7 +172,7 @@ proc insertID*(db: TDbConn, query: TSqlQuery, result = tryInsertID(db, query, args) if result < 0: dbError(db) -proc execAffectedRows*(db: TDbConn, query: TSqlQuery, +proc execAffectedRows*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]): int64 {. tags: [FReadDb, FWriteDb].} = ## executes the query (typically "UPDATE") and returns the @@ -179,21 +180,21 @@ proc execAffectedRows*(db: TDbConn, query: TSqlQuery, exec(db, query, args) result = changes(db) -proc close*(db: TDbConn) {.tags: [FDb].} = +proc close*(db: DbConn) {.tags: [FDb].} = ## closes the database connection. if sqlite3.close(db) != SQLITE_OK: dbError(db) -proc open*(connection, user, password, database: string): TDbConn {. +proc open*(connection, user, password, database: string): DbConn {. tags: [FDb].} = ## opens a database connection. Raises `EDb` if the connection could not ## be established. Only the ``connection`` parameter is used for ``sqlite``. - var db: TDbConn + var db: DbConn if sqlite3.open(connection, db) == SQLITE_OK: result = db else: dbError(db) -proc setEncoding*(connection: TDbConn, encoding: string): bool {. +proc setEncoding*(connection: DbConn, encoding: string): bool {. tags: [FDb].} = ## sets the encoding of a database connection, returns true for ## success, false for failure. diff --git a/lib/impure/graphics.nim b/lib/impure/graphics.nim index 814c0ebe1..1b3d1d5b6 100644 --- a/lib/impure/graphics.nim +++ b/lib/impure/graphics.nim @@ -17,23 +17,24 @@ from sdl import PSurface # Bug from sdl_ttf import openFont, closeFont type - TRect* = tuple[x, y, width, height: int] - TPoint* = tuple[x, y: int] + Rect* = tuple[x, y, width, height: int] + Point* = tuple[x, y: int] - PSurface* = ref TSurface ## a surface to draw onto - TSurface* {.pure, final.} = object + PSurface* = ref Surface ## a surface to draw onto + Surface* {.pure, final.} = object w*, h*: Natural s*: sdl.PSurface EGraphics* = object of IOError - TFont {.pure, final.} = object + Font {.pure, final.} = object f: sdl_ttf.PFont - color: sdl.TColor - PFont* = ref TFont ## represents a font + color: sdl.Color + PFont* = ref Font ## represents a font +{.deprecated: [TSurface: Surface, TFont: Font, TRect: Rect, TPoint: Point].} -proc toSdlColor*(c: Color): sdl.TColor = - ## Convert colors.TColor to sdl.TColor +proc toSdlColor*(c: Color): sdl.Color = + ## Convert colors.Color to sdl.Color var x = c.extractRGB result.r = x.r and 0xff result.g = x.g and 0xff @@ -45,8 +46,8 @@ proc createSdlColor*(sur: PSurface, c: Color, alpha: int = 0): int32 = return sdl.mapRGBA(sur.s.format, x.r and 0xff, x.g and 0xff, x.b and 0xff, alpha and 0xff) -proc toSdlRect*(r: TRect): sdl.TRect = - ## Convert ``graphics.TRect`` to ``sdl.TRect``. +proc toSdlRect*(r: Rect): sdl.Rect = + ## Convert ``graphics.Rect`` to ``sdl.Rect``. result.x = int16(r.x) result.y = int16(r.y) result.w = uint16(r.width) @@ -103,8 +104,9 @@ proc writeToBMP*(sur: PSurface, filename: string) = raise newException(IOError, "cannot write: " & filename) type - TPixels = array[0..1000_000-1, int32] - PPixels = ptr TPixels + Pixels = array[0..1000_000-1, int32] + PPixels = ptr Pixels +{.deprecated: [TPixels: Pixels].} template setPix(video, pitch, x, y, col: expr): stmt = video[y * pitch + x] = int32(col) @@ -128,7 +130,7 @@ proc setPixel(sur: PSurface, x, y: Natural, col: colors.Color) {.inline.} = #pixs[y * (sur.s.pitch div colSize) + x] = int(col) setPix(pixs, sur.s.pitch.int div ColSize, x, y, col) -proc `[]`*(sur: PSurface, p: TPoint): Color = +proc `[]`*(sur: PSurface, p: Point): Color = ## get pixel at position `p`. No range checking is done! result = getPixel(sur, p.x, p.y) @@ -136,7 +138,7 @@ proc `[]`*(sur: PSurface, x, y: int): Color = ## get pixel at position ``(x, y)``. No range checking is done! result = getPixel(sur, x, y) -proc `[]=`*(sur: PSurface, p: TPoint, col: Color) = +proc `[]=`*(sur: PSurface, p: Point, col: Color) = ## set the pixel at position `p`. No range checking is done! setPixel(sur, p.x, p.y, col) @@ -144,10 +146,10 @@ proc `[]=`*(sur: PSurface, x, y: int, col: Color) = ## set the pixel at position ``(x, y)``. No range checking is done! setPixel(sur, x, y, col) -proc blit*(destSurf: PSurface, destRect: TRect, srcSurf: PSurface, - srcRect: TRect) = +proc blit*(destSurf: PSurface, destRect: Rect, srcSurf: PSurface, + srcRect: Rect) = ## Copies ``srcSurf`` into ``destSurf`` - var destTRect, srcTRect: sdl.TRect + var destTRect, srcTRect: sdl.Rect destTRect.x = int16(destRect.x) destTRect.y = int16(destRect.y) @@ -168,7 +170,7 @@ proc textBounds*(text: string, font = defaultFont): tuple[width, height: int] = result.width = int(w) result.height = int(h) -proc drawText*(sur: PSurface, p: TPoint, text: string, font = defaultFont) = +proc drawText*(sur: PSurface, p: Point, text: string, font = defaultFont) = ## Draws text with a transparent background, at location ``p`` with the given ## font. var textSur: PSurface # This surface will have the text drawn on it @@ -179,7 +181,7 @@ proc drawText*(sur: PSurface, p: TPoint, text: string, font = defaultFont) = # Merge the text surface with sur sur.blit((p.x, p.y, sur.w, sur.h), textSur, (0, 0, sur.w, sur.h)) -proc drawText*(sur: PSurface, p: TPoint, text: string, +proc drawText*(sur: PSurface, p: Point, text: string, bg: Color, font = defaultFont) = ## Draws text, at location ``p`` with font ``font``. ``bg`` ## is the background color. @@ -189,7 +191,7 @@ proc drawText*(sur: PSurface, p: TPoint, text: string, # Merge the text surface with sur sur.blit((p.x, p.y, sur.w, sur.h), textSur, (0, 0, sur.w, sur.h)) -proc drawCircle*(sur: PSurface, p: TPoint, r: Natural, color: Color) = +proc drawCircle*(sur: PSurface, p: Point, r: Natural, color: Color) = ## draws a circle with center `p` and radius `r` with the given color ## onto the surface `sur`. var video = cast[PPixels](sur.s.pixels) @@ -229,7 +231,7 @@ proc `>-<`(val: int, s: PSurface): int {.inline.} = proc `>|<`(val: int, s: PSurface): int {.inline.} = return if val < 0: 0 elif val >= s.h: s.h-1 else: val -proc drawLine*(sur: PSurface, p1, p2: TPoint, color: Color) = +proc drawLine*(sur: PSurface, p1, p2: Point, color: Color) = ## draws a line between the two points `p1` and `p2` with the given color ## onto the surface `sur`. var stepx, stepy: int = 0 @@ -291,7 +293,7 @@ proc drawVerLine*(sur: PSurface, x, y, h: Natural, color: Color) = for i in 0 .. min(sur.s.h-y, h)-1: setPix(video, pitch, x, y + i, color) -proc fillCircle*(s: PSurface, p: TPoint, r: Natural, color: Color) = +proc fillCircle*(s: PSurface, p: Point, r: Natural, color: Color) = ## draws a circle with center `p` and radius `r` with the given color ## onto the surface `sur` and fills it. var a = 1 - r @@ -319,7 +321,7 @@ proc fillCircle*(s: PSurface, p: TPoint, r: Natural, color: Color) = drawVerLine(s, x - py - 1, y - px, px, color) px = px + 1 -proc drawRect*(sur: PSurface, r: TRect, color: Color) = +proc drawRect*(sur: PSurface, r: Rect, color: Color) = ## draws a rectangle. var video = cast[PPixels](sur.s.pixels) var pitch = sur.s.pitch.int div ColSize @@ -337,7 +339,7 @@ proc drawRect*(sur: PSurface, r: TRect, color: Color) = setPix(video, pitch, r.x, r.y + i, color) setPix(video, pitch, r.x + minW - 1, r.y + i, color) # Draw right side -proc fillRect*(sur: PSurface, r: TRect, col: Color) = +proc fillRect*(sur: PSurface, r: Rect, col: Color) = ## Fills a rectangle using sdl's ``FillRect`` function. var rect = toSdlRect(r) if sdl.fillRect(sur.s, addr(rect), sur.createSdlColor(col)) == -1: @@ -424,7 +426,7 @@ template cround(x: expr): expr = ipart(x + 0.5) template fpart(x: expr): expr = x - ipart(x) template rfpart(x: expr): expr = 1.0 - fpart(x) -proc drawLineAA*(sur: PSurface, p1, p2: TPoint, color: Color) = +proc drawLineAA*(sur: PSurface, p1, p2: Point, color: Color) = ## Draws a anti-aliased line from ``p1`` to ``p2``, using Xiaolin Wu's ## line algorithm var (x1, x2, y1, y2) = (p1.x.toFloat(), p2.x.toFloat(), @@ -490,9 +492,9 @@ proc fillSurface*(sur: PSurface, color: Color) = template withEvents*(surf: PSurface, event: expr, actions: stmt): stmt {. immediate.} = ## Simple template which creates an event loop. ``Event`` is the name of the - ## variable containing the TEvent object. + ## variable containing the Event object. while true: - var event: sdl.TEvent + var event: sdl.Event if sdl.waitEvent(addr(event)) == 1: actions diff --git a/lib/impure/rdstdin.nim b/lib/impure/rdstdin.nim index f4d00979c..dfe3e22eb 100644 --- a/lib/impure/rdstdin.nim +++ b/lib/impure/rdstdin.nim @@ -135,7 +135,7 @@ else: var cur, old: Termios discard fd.tcgetattr(cur.addr) old = cur - cur.c_lflag = cur.c_lflag and not Tcflag(ECHO) + cur.c_lflag = cur.c_lflag and not Cflag(ECHO) discard fd.tcsetattr(TCSADRAIN, cur.addr) stdout.write prompt result = stdin.readLine(password) diff --git a/lib/impure/ssl.nim b/lib/impure/ssl.nim index d318a1979..079a2c3a2 100644 --- a/lib/impure/ssl.nim +++ b/lib/impure/ssl.nim @@ -15,11 +15,12 @@ import openssl, strutils, os type - TSecureSocket* = object + SecureSocket* = object ssl: SslPtr bio: BIO +{.deprecated: [TSecureSocket: SecureSocket].} -proc connect*(sock: var TSecureSocket, address: string, +proc connect*(sock: var SecureSocket, address: string, port: int): int = ## Connects to the specified `address` on the specified `port`. ## Returns the result of the certificate validation. @@ -52,7 +53,7 @@ proc connect*(sock: var TSecureSocket, address: string, result = SSL_get_verify_result(sock.ssl) -proc recvLine*(sock: TSecureSocket, line: var TaintedString): bool = +proc recvLine*(sock: SecureSocket, line: var TaintedString): bool = ## Acts in a similar fashion to the `recvLine` in the sockets module. ## Returns false when no data is available to be read. ## `Line` must be initialized and not nil! @@ -71,19 +72,19 @@ proc recvLine*(sock: TSecureSocket, line: var TaintedString): bool = add(line.string, c) -proc send*(sock: TSecureSocket, data: string) = +proc send*(sock: SecureSocket, data: string) = ## Writes `data` to the socket. if BIO_write(sock.bio, data, data.len.cint) <= 0: raiseOSError(osLastError()) -proc close*(sock: TSecureSocket) = +proc close*(sock: SecureSocket) = ## Closes the socket if BIO_free(sock.bio) <= 0: ERR_print_errors_fp(stderr) raiseOSError(osLastError()) when not defined(testing) and isMainModule: - var s: TSecureSocket + var s: SecureSocket echo connect(s, "smtp.gmail.com", 465) #var buffer: array[0..255, char] diff --git a/lib/impure/zipfiles.nim b/lib/impure/zipfiles.nim index b41ca1e4b..56483c586 100644 --- a/lib/impure/zipfiles.nim +++ b/lib/impure/zipfiles.nim @@ -13,18 +13,18 @@ import streams, libzip, times, os, strutils type - TZipArchive* = object of RootObj ## represents a zip archive + ZipArchive* = object of RootObj ## represents a zip archive mode: FileMode w: PZip +{.deprecated: [TZipArchive: ZipArchive].} - -proc zipError(z: var TZipArchive) = +proc zipError(z: var ZipArchive) = var e: ref IOError new(e) e.msg = $zip_strerror(z.w) raise e -proc open*(z: var TZipArchive, filename: string, mode: FileMode = fmRead): bool = +proc open*(z: var ZipArchive, filename: string, mode: FileMode = fmRead): bool = ## Opens a zip file for reading, writing or appending. All file modes are ## supported. Returns true iff successful, false otherwise. var err, flags: int32 @@ -38,11 +38,11 @@ proc open*(z: var TZipArchive, filename: string, mode: FileMode = fmRead): bool z.mode = mode result = z.w != nil -proc close*(z: var TZipArchive) = +proc close*(z: var ZipArchive) = ## Closes a zip file. zip_close(z.w) -proc createDir*(z: var TZipArchive, dir: string) = +proc createDir*(z: var ZipArchive, dir: string) = ## Creates a directory within the `z` archive. This does not fail if the ## directory already exists. Note that for adding a file like ## ``"path1/path2/filename"`` it is not necessary @@ -52,7 +52,7 @@ proc createDir*(z: var TZipArchive, dir: string) = discard zip_add_dir(z.w, dir) zip_error_clear(z.w) -proc addFile*(z: var TZipArchive, dest, src: string) = +proc addFile*(z: var ZipArchive, dest, src: string) = ## Adds the file `src` to the archive `z` with the name `dest`. `dest` ## may contain a path that will be created. assert(z.mode != fmRead) @@ -67,13 +67,13 @@ proc addFile*(z: var TZipArchive, dest, src: string) = zip_source_free(zipsrc) zipError(z) -proc addFile*(z: var TZipArchive, file: string) = +proc addFile*(z: var ZipArchive, file: string) = ## A shortcut for ``addFile(z, file, file)``, i.e. the name of the source is ## the name of the destination. addFile(z, file, file) proc mySourceCallback(state, data: pointer, len: int, - cmd: TZipSourceCmd): int {.cdecl.} = + cmd: ZipSourceCmd): int {.cdecl.} = var src = cast[Stream](state) case cmd of ZIP_SOURCE_OPEN: @@ -86,7 +86,7 @@ proc mySourceCallback(state, data: pointer, len: int, zip_stat_init(stat) stat.size = high(int32)-1 # we don't know the size stat.mtime = getTime() - result = sizeof(TZipStat) + result = sizeof(ZipStat) of ZIP_SOURCE_ERROR: var err = cast[ptr array[0..1, cint]](data) err[0] = ZIP_ER_INTERNAL @@ -95,7 +95,7 @@ proc mySourceCallback(state, data: pointer, len: int, of constZIP_SOURCE_FREE: GC_unref(src) else: assert(false) -proc addFile*(z: var TZipArchive, dest: string, src: Stream) = +proc addFile*(z: var ZipArchive, dest: string, src: Stream) = ## Adds a file named with `dest` to the archive `z`. `dest` ## may contain a path. The file's content is read from the `src` stream. assert(z.mode != fmRead) @@ -109,12 +109,13 @@ proc addFile*(z: var TZipArchive, dest: string, src: Stream) = # -------------- zip file stream --------------------------------------------- type - TZipFileStream = object of StreamObj + ZipFileStream = object of StreamObj f: PZipFile atEnd: bool PZipFileStream* = - ref TZipFileStream ## a reader stream of a file within a zip archive + ref ZipFileStream ## a reader stream of a file within a zip archive +{.deprecated: [TZipFileStream: ZipFileStream].} proc fsClose(s: Stream) = zip_fclose(PZipFileStream(s).f) proc fsAtEnd(s: Stream): bool = PZipFileStream(s).atEnd @@ -134,7 +135,7 @@ proc newZipFileStream(f: PZipFile): PZipFileStream = # ---------------------------------------------------------------------------- -proc getStream*(z: var TZipArchive, filename: string): PZipFileStream = +proc getStream*(z: var ZipArchive, filename: string): PZipFileStream = ## returns a stream that can be used to read the file named `filename` ## from the archive `z`. Returns nil in case of an error. ## The returned stream does not support the `setPosition`, `getPosition`, @@ -142,7 +143,7 @@ proc getStream*(z: var TZipArchive, filename: string): PZipFileStream = var x = zip_fopen(z.w, filename, 0'i32) if x != nil: result = newZipFileStream(x) -iterator walkFiles*(z: var TZipArchive): string = +iterator walkFiles*(z: var ZipArchive): string = ## walks over all files in the archive `z` and returns the filename ## (including the path). var i = 0'i32 @@ -152,7 +153,7 @@ iterator walkFiles*(z: var TZipArchive): string = inc(i) -proc extractFile*(z: var TZipArchive, srcFile: string, dest: Stream) = +proc extractFile*(z: var ZipArchive, srcFile: string, dest: Stream) = ## extracts a file from the zip archive `z` to the destination stream. var strm = getStream(z, srcFile) while true: @@ -162,13 +163,13 @@ proc extractFile*(z: var TZipArchive, srcFile: string, dest: Stream) = dest.flush() strm.close() -proc extractFile*(z: var TZipArchive, srcFile: string, dest: string) = +proc extractFile*(z: var ZipArchive, srcFile: string, dest: string) = ## extracts a file from the zip archive `z` to the destination filename. var file = newFileStream(dest, fmWrite) extractFile(z, srcFile, file) file.close() -proc extractAll*(z: var TZipArchive, dest: string) = +proc extractAll*(z: var ZipArchive, dest: string) = ## extracts all files from archive `z` to the destination directory. for file in walkFiles(z): if file.endsWith("/"): @@ -177,7 +178,7 @@ proc extractAll*(z: var TZipArchive, dest: string) = extractFile(z, file, dest / file) when not defined(testing) and isMainModule: - var zip: TZipArchive + var zip: ZipArchive if not zip.open("nim-0.11.0.zip"): raise newException(IOError, "opening zip failed") zip.extractAll("test") From 6e8e3fdd23e4e5452768540e01566f6b35ab1d0f Mon Sep 17 00:00:00 2001 From: pdw Date: Sun, 24 May 2015 22:24:52 -0500 Subject: [PATCH 0347/1263] lib/js - Dropped 'T' from types --- lib/js/dom.nim | 142 ++++++++++++++++++++++++++----------------------- 1 file changed, 74 insertions(+), 68 deletions(-) diff --git a/lib/js/dom.nim b/lib/js/dom.nim index b063fa838..bc870999b 100644 --- a/lib/js/dom.nim +++ b/lib/js/dom.nim @@ -14,56 +14,56 @@ when not defined(js) and not defined(Nimdoc): {.error: "This module only works on the JavaScript platform".} type - TEventHandlers* {.importc.} = object of RootObj - onabort*: proc (event: ref TEvent) {.nimcall.} - onblur*: proc (event: ref TEvent) {.nimcall.} - onchange*: proc (event: ref TEvent) {.nimcall.} - onclick*: proc (event: ref TEvent) {.nimcall.} - ondblclick*: proc (event: ref TEvent) {.nimcall.} - onerror*: proc (event: ref TEvent) {.nimcall.} - onfocus*: proc (event: ref TEvent) {.nimcall.} - onkeydown*: proc (event: ref TEvent) {.nimcall.} - onkeypress*: proc (event: ref TEvent) {.nimcall.} - onkeyup*: proc (event: ref TEvent) {.nimcall.} - onload*: proc (event: ref TEvent) {.nimcall.} - onmousedown*: proc (event: ref TEvent) {.nimcall.} - onmousemove*: proc (event: ref TEvent) {.nimcall.} - onmouseout*: proc (event: ref TEvent) {.nimcall.} - onmouseover*: proc (event: ref TEvent) {.nimcall.} - onmouseup*: proc (event: ref TEvent) {.nimcall.} - onreset*: proc (event: ref TEvent) {.nimcall.} - onselect*: proc (event: ref TEvent) {.nimcall.} - onsubmit*: proc (event: ref TEvent) {.nimcall.} - onunload*: proc (event: ref TEvent) {.nimcall.} + EventHandlers* {.importc.} = object of RootObj + onabort*: proc (event: ref Event) {.nimcall.} + onblur*: proc (event: ref Event) {.nimcall.} + onchange*: proc (event: ref Event) {.nimcall.} + onclick*: proc (event: ref Event) {.nimcall.} + ondblclick*: proc (event: ref Event) {.nimcall.} + onerror*: proc (event: ref Event) {.nimcall.} + onfocus*: proc (event: ref Event) {.nimcall.} + onkeydown*: proc (event: ref Event) {.nimcall.} + onkeypress*: proc (event: ref Event) {.nimcall.} + onkeyup*: proc (event: ref Event) {.nimcall.} + onload*: proc (event: ref Event) {.nimcall.} + onmousedown*: proc (event: ref Event) {.nimcall.} + onmousemove*: proc (event: ref Event) {.nimcall.} + onmouseout*: proc (event: ref Event) {.nimcall.} + onmouseover*: proc (event: ref Event) {.nimcall.} + onmouseup*: proc (event: ref Event) {.nimcall.} + onreset*: proc (event: ref Event) {.nimcall.} + onselect*: proc (event: ref Event) {.nimcall.} + onsubmit*: proc (event: ref Event) {.nimcall.} + onunload*: proc (event: ref Event) {.nimcall.} - addEventListener*: proc(ev: cstring, cb: proc(ev: ref TEvent), useCapture: bool = false) {.nimcall.} + addEventListener*: proc(ev: cstring, cb: proc(ev: ref Event), useCapture: bool = false) {.nimcall.} Window* = ref WindowObj - WindowObj {.importc.} = object of TEventHandlers + WindowObj {.importc.} = object of EventHandlers document*: Document - event*: ref TEvent - history*: ref THistory - location*: ref TLocation + event*: ref Event + history*: ref History + location*: ref Location closed*: bool defaultStatus*: cstring innerHeight*, innerWidth*: int - locationbar*: ref TLocationBar - menubar*: ref TMenuBar + locationbar*: ref LocationBar + menubar*: ref MenuBar name*: cstring outerHeight*, outerWidth*: int pageXOffset*, pageYOffset*: int - personalbar*: ref TPersonalBar - scrollbars*: ref TScrollBars - statusbar*: ref TStatusBar + personalbar*: ref PersonalBar + scrollbars*: ref ScrollBars + statusbar*: ref StatusBar status*: cstring - toolbar*: ref TToolBar + toolbar*: ref ToolBar alert*: proc (msg: cstring) {.nimcall.} back*: proc () {.nimcall.} blur*: proc () {.nimcall.} captureEvents*: proc (eventMask: int) {.nimcall.} - clearInterval*: proc (interval: ref TInterval) {.nimcall.} - clearTimeout*: proc (timeout: ref TTimeOut) {.nimcall.} + clearInterval*: proc (interval: ref Interval) {.nimcall.} + clearTimeout*: proc (timeout: ref TimeOut) {.nimcall.} close*: proc () {.nimcall.} confirm*: proc (msg: cstring): bool {.nimcall.} disableExternalCapture*: proc () {.nimcall.} @@ -72,7 +72,7 @@ type backwards = false) {.nimcall.} focus*: proc () {.nimcall.} forward*: proc () {.nimcall.} - handleEvent*: proc (e: ref TEvent) {.nimcall.} + handleEvent*: proc (e: ref Event) {.nimcall.} home*: proc () {.nimcall.} moveBy*: proc (x, y: int) {.nimcall.} moveTo*: proc (x, y: int) {.nimcall.} @@ -83,13 +83,13 @@ type releaseEvents*: proc (eventMask: int) {.nimcall.} resizeBy*: proc (x, y: int) {.nimcall.} resizeTo*: proc (x, y: int) {.nimcall.} - routeEvent*: proc (event: ref TEvent) {.nimcall.} + routeEvent*: proc (event: ref Event) {.nimcall.} scrollBy*: proc (x, y: int) {.nimcall.} scrollTo*: proc (x, y: int) {.nimcall.} - setInterval*: proc (code: cstring, pause: int): ref TInterval {.nimcall.} - setTimeout*: proc (code: cstring, pause: int): ref TTimeOut {.nimcall.} + setInterval*: proc (code: cstring, pause: int): ref Interval {.nimcall.} + setTimeout*: proc (code: cstring, pause: int): ref TimeOut {.nimcall.} stop*: proc () {.nimcall.} - frames*: seq[TFrame] + frames*: seq[FrameObj] Frame* = ref FrameObj FrameObj {.importc.} = object of WindowObj @@ -100,7 +100,7 @@ type contains*: proc (class: cstring):bool {.nimcall.} toggle*: proc (class: cstring) {.nimcall.} - TNodeType* = enum + NodeType* = enum ElementNode = 1, AttributeNode, TextNode, @@ -115,7 +115,7 @@ type NotationNode Node* = ref NodeObj - NodeObj {.importc.} = object of TEventHandlers + NodeObj {.importc.} = object of EventHandlers attributes*: seq[Node] childNodes*: seq[Node] children*: seq[Node] @@ -124,7 +124,7 @@ type lastChild*: Node nextSibling*: Node nodeName*: cstring - nodeType*: TNodeType + nodeType*: NodeType nodeValue*: cstring parentNode*: Node previousSibling*: Node @@ -146,7 +146,7 @@ type scrollIntoView*: proc () {.nimcall.} setAttribute*: proc (name, value: cstring) {.nimcall.} setAttributeNode*: proc (attr: Node) {.nimcall.} - style*: ref TStyle + style*: ref Style Document* = ref DocumentObj DocumentObj {.importc.} = object of NodeObj @@ -173,16 +173,16 @@ type getElementsByTagName*: proc (name: cstring): seq[Element] {.nimcall.} getElementsByClassName*: proc (name: cstring): seq[Element] {.nimcall.} getSelection*: proc (): cstring {.nimcall.} - handleEvent*: proc (event: ref TEvent) {.nimcall.} + handleEvent*: proc (event: ref Event) {.nimcall.} open*: proc () {.nimcall.} releaseEvents*: proc (eventMask: int) {.nimcall.} - routeEvent*: proc (event: ref TEvent) {.nimcall.} + routeEvent*: proc (event: ref Event) {.nimcall.} write*: proc (text: cstring) {.nimcall.} writeln*: proc (text: cstring) {.nimcall.} anchors*: seq[AnchorElement] forms*: seq[FormElement] images*: seq[ImageElement] - applets*: seq[ref TApplet] + applets*: seq[ref Applet] embeds*: seq[EmbedElement] links*: seq[LinkElement] @@ -199,7 +199,7 @@ type blur*: proc () {.nimcall.} click*: proc () {.nimcall.} focus*: proc () {.nimcall.} - handleEvent*: proc (event: ref TEvent) {.nimcall.} + handleEvent*: proc (event: ref Event) {.nimcall.} select*: proc () {.nimcall.} options*: seq[OptionElement] getElementsByTagName*: proc (name: cstring): seq[Element] {.nimcall.} @@ -228,7 +228,7 @@ type text*: cstring x*, y*: int - TApplet* {.importc.} = object of RootObj + Applet* {.importc.} = object of RootObj OptionElement* = ref OptionObj OptionObj {.importc.} = object of ElementObj @@ -260,7 +260,7 @@ type width*: int - TStyle* {.importc.} = object of RootObj + Style* {.importc.} = object of RootObj background*: cstring backgroundAttachment*: cstring backgroundColor*: cstring @@ -354,7 +354,7 @@ type removeAttribute*: proc (attr: cstring, caseSensitive=false) {.nimcall.} setAttribute*: proc (attr, value: cstring, caseSensitive=false) {.nimcall.} - TEvent* {.importc.} = object of RootObj + Event* {.importc.} = object of RootObj target*: Node altKey*, ctrlKey*, shiftKey*: bool button*: int @@ -393,7 +393,7 @@ type SUBMIT*: int UNLOAD*: int - TLocation* {.importc.} = object of RootObj + Location* {.importc.} = object of RootObj hash*: cstring host*: cstring hostname*: cstring @@ -405,13 +405,13 @@ type reload*: proc () {.nimcall.} replace*: proc (s: cstring) {.nimcall.} - THistory* {.importc.} = object of RootObj + History* {.importc.} = object of RootObj length*: int back*: proc () {.nimcall.} forward*: proc () {.nimcall.} go*: proc (pagesToJump: int) {.nimcall.} - TNavigator* {.importc.} = object of RootObj + Navigator* {.importc.} = object of RootObj appCodeName*: cstring appName*: cstring appVersion*: cstring @@ -420,28 +420,28 @@ type platform*: cstring userAgent*: cstring javaEnabled*: proc (): bool {.nimcall.} - mimeTypes*: seq[ref TMimeType] + mimeTypes*: seq[ref MimeType] - TPlugin* {.importc.} = object of RootObj + Plugin* {.importc.} = object of RootObj description*: cstring filename*: cstring name*: cstring - TMimeType* {.importc.} = object of RootObj + MimeType* {.importc.} = object of RootObj description*: cstring - enabledPlugin*: ref TPlugin + enabledPlugin*: ref Plugin suffixes*: seq[cstring] `type`*: cstring - TLocationBar* {.importc.} = object of RootObj + LocationBar* {.importc.} = object of RootObj visible*: bool - TMenuBar* = TLocationBar - TPersonalBar* = TLocationBar - TScrollBars* = TLocationBar - TToolBar* = TLocationBar - TStatusBar* = TLocationBar + MenuBar* = LocationBar + PersonalBar* = LocationBar + ScrollBars* = LocationBar + ToolBar* = LocationBar + StatusBar* = LocationBar - TScreen* {.importc.} = object of RootObj + Screen* {.importc.} = object of RootObj availHeight*: int availWidth*: int colorDepth*: int @@ -449,14 +449,20 @@ type pixelDepth*: int width*: int - TTimeOut* {.importc.} = object of RootObj - TInterval* {.importc.} = object of RootObj + TimeOut* {.importc.} = object of RootObj + Interval* {.importc.} = object of RootObj +{.deprecated: [TEventHandlers: EventHandlers, TEvent: Event, TNodeType: NodeType, + TInterval: Interval, TTimeOut: TimeOut, TStatusBar: StatusBar, + TMenuBar: MenuBar, TApplet: Applet, TLocation: Location, + THistory: History, TNavigator: Navigator, TPlugin: Plugin, + TMimeType: MimeType, TLocationBar: LocationBar, TPersonalBar: PersonalBar, + TScrollBars: ScrollBars, TToolBar: ToolBar, TScreen: Screen].} var window* {.importc, nodecl.}: Window document* {.importc, nodecl.}: Document - navigator* {.importc, nodecl.}: ref TNavigator - screen* {.importc, nodecl.}: ref TScreen + navigator* {.importc, nodecl.}: ref Navigator + screen* {.importc, nodecl.}: ref Screen proc decodeURI*(uri: cstring): cstring {.importc, nodecl.} proc encodeURI*(uri: cstring): cstring {.importc, nodecl.} From 76167905154502c94c726bc5349f9c5fd75e7b3b Mon Sep 17 00:00:00 2001 From: pdw Date: Sun, 24 May 2015 22:25:38 -0500 Subject: [PATCH 0348/1263] lib/packages/docutils - Dropped 'T' from types --- lib/packages/docutils/highlite.nim | 61 ++++--- lib/packages/docutils/rst.nim | 277 +++++++++++++++-------------- lib/packages/docutils/rstast.nim | 29 +-- lib/packages/docutils/rstgen.nim | 121 ++++++------- 4 files changed, 253 insertions(+), 235 deletions(-) diff --git a/lib/packages/docutils/highlite.nim b/lib/packages/docutils/highlite.nim index 9485f3912..640b8cd5a 100644 --- a/lib/packages/docutils/highlite.nim +++ b/lib/packages/docutils/highlite.nim @@ -15,7 +15,7 @@ import strutils type - TTokenClass* = enum + TokenClass* = enum gtEof, gtNone, gtWhitespace, gtDecNumber, gtBinNumber, gtHexNumber, gtOctNumber, gtFloatNumber, gtIdentifier, gtKeyword, gtStringLit, gtLongStringLit, gtCharLit, gtEscapeSequence, # escape sequence like \xff @@ -23,20 +23,22 @@ type gtTagStart, gtTagEnd, gtKey, gtValue, gtRawData, gtAssembler, gtPreprocessor, gtDirective, gtCommand, gtRule, gtHyperlink, gtLabel, gtReference, gtOther - TGeneralTokenizer* = object of RootObj - kind*: TTokenClass + GeneralTokenizer* = object of RootObj + kind*: TokenClass start*, length*: int buf: cstring pos: int - state: TTokenClass + state: TokenClass - TSourceLanguage* = enum + SourceLanguage* = enum langNone, langNim, langNimrod, langCpp, langCsharp, langC, langJava +{.deprecated: [TSourceLanguage: SourceLanguage, TTokenClass: TokenClass, + TGeneralTokenizer: GeneralTokenizer].} const - sourceLanguageToStr*: array[TSourceLanguage, string] = ["none", + sourceLanguageToStr*: array[SourceLanguage, string] = ["none", "Nim", "Nimrod", "C++", "C#", "C", "Java"] - tokenClassToStr*: array[TTokenClass, string] = ["Eof", "None", "Whitespace", + tokenClassToStr*: array[TokenClass, string] = ["Eof", "None", "Whitespace", "DecNumber", "BinNumber", "HexNumber", "OctNumber", "FloatNumber", "Identifier", "Keyword", "StringLit", "LongStringLit", "CharLit", "EscapeSequence", "Operator", "Punctuation", "Comment", "LongComment", @@ -58,29 +60,29 @@ const "template", "try", "tuple", "type", "using", "var", "when", "while", "with", "without", "xor", "yield"] -proc getSourceLanguage*(name: string): TSourceLanguage = - for i in countup(succ(low(TSourceLanguage)), high(TSourceLanguage)): +proc getSourceLanguage*(name: string): SourceLanguage = + for i in countup(succ(low(SourceLanguage)), high(SourceLanguage)): if cmpIgnoreStyle(name, sourceLanguageToStr[i]) == 0: return i result = langNone -proc initGeneralTokenizer*(g: var TGeneralTokenizer, buf: cstring) = +proc initGeneralTokenizer*(g: var GeneralTokenizer, buf: cstring) = g.buf = buf - g.kind = low(TTokenClass) + g.kind = low(TokenClass) g.start = 0 g.length = 0 - g.state = low(TTokenClass) + g.state = low(TokenClass) var pos = 0 # skip initial whitespace: while g.buf[pos] in {' ', '\x09'..'\x0D'}: inc(pos) g.pos = pos -proc initGeneralTokenizer*(g: var TGeneralTokenizer, buf: string) = +proc initGeneralTokenizer*(g: var GeneralTokenizer, buf: string) = initGeneralTokenizer(g, cstring(buf)) -proc deinitGeneralTokenizer*(g: var TGeneralTokenizer) = +proc deinitGeneralTokenizer*(g: var GeneralTokenizer) = discard -proc nimGetKeyword(id: string): TTokenClass = +proc nimGetKeyword(id: string): TokenClass = for k in nimKeywords: if cmpIgnoreStyle(id, k) == 0: return gtKeyword result = gtIdentifier @@ -92,7 +94,7 @@ proc nimGetKeyword(id: string): TTokenClass = else: result = gtIdentifier -proc nimNumberPostfix(g: var TGeneralTokenizer, position: int): int = +proc nimNumberPostfix(g: var GeneralTokenizer, position: int): int = var pos = position if g.buf[pos] == '\'': inc(pos) @@ -110,7 +112,7 @@ proc nimNumberPostfix(g: var TGeneralTokenizer, position: int): int = discard result = pos -proc nimNumber(g: var TGeneralTokenizer, position: int): int = +proc nimNumber(g: var GeneralTokenizer, position: int): int = const decChars = {'0'..'9', '_'} var pos = position g.kind = gtDecNumber @@ -130,7 +132,7 @@ const OpChars = {'+', '-', '*', '/', '\\', '<', '>', '!', '?', '^', '.', '|', '=', '%', '&', '$', '@', '~', ':', '\x80'..'\xFF'} -proc nimNextToken(g: var TGeneralTokenizer) = +proc nimNextToken(g: var GeneralTokenizer) = const hexChars = {'0'..'9', 'A'..'F', 'a'..'f', '_'} octChars = {'0'..'7', '_'} @@ -278,7 +280,7 @@ proc nimNextToken(g: var TGeneralTokenizer) = assert false, "nimNextToken: produced an empty token" g.pos = pos -proc generalNumber(g: var TGeneralTokenizer, position: int): int = +proc generalNumber(g: var GeneralTokenizer, position: int): int = const decChars = {'0'..'9'} var pos = position g.kind = gtDecNumber @@ -294,7 +296,7 @@ proc generalNumber(g: var TGeneralTokenizer, position: int): int = while g.buf[pos] in decChars: inc(pos) result = pos -proc generalStrLit(g: var TGeneralTokenizer, position: int): int = +proc generalStrLit(g: var GeneralTokenizer, position: int): int = const decChars = {'0'..'9'} hexChars = {'0'..'9', 'A'..'F', 'a'..'f'} @@ -355,12 +357,13 @@ proc isKeywordIgnoreCase(x: openArray[string], y: string): int = result = - 1 type - TTokenizerFlag = enum + TokenizerFlag = enum hasPreprocessor, hasNestedComments - TTokenizerFlags = set[TTokenizerFlag] + TokenizerFlags = set[TokenizerFlag] +{.deprecated: [TTokenizerFlag: TokenizerFlag, TTokenizerFlags: TokenizerFlags].} -proc clikeNextToken(g: var TGeneralTokenizer, keywords: openArray[string], - flags: TTokenizerFlags) = +proc clikeNextToken(g: var GeneralTokenizer, keywords: openArray[string], + flags: TokenizerFlags) = const hexChars = {'0'..'9', 'A'..'F', 'a'..'f'} octChars = {'0'..'7'} @@ -493,7 +496,7 @@ proc clikeNextToken(g: var TGeneralTokenizer, keywords: openArray[string], assert false, "clikeNextToken: produced an empty token" g.pos = pos -proc cNextToken(g: var TGeneralTokenizer) = +proc cNextToken(g: var GeneralTokenizer) = const keywords: array[0..36, string] = ["_Bool", "_Complex", "_Imaginary", "auto", "break", "case", "char", "const", "continue", "default", "do", "double", @@ -503,7 +506,7 @@ proc cNextToken(g: var TGeneralTokenizer) = "volatile", "while"] clikeNextToken(g, keywords, {hasPreprocessor}) -proc cppNextToken(g: var TGeneralTokenizer) = +proc cppNextToken(g: var GeneralTokenizer) = const keywords: array[0..47, string] = ["asm", "auto", "break", "case", "catch", "char", "class", "const", "continue", "default", "delete", "do", "double", @@ -514,7 +517,7 @@ proc cppNextToken(g: var TGeneralTokenizer) = "union", "unsigned", "virtual", "void", "volatile", "while"] clikeNextToken(g, keywords, {hasPreprocessor}) -proc csharpNextToken(g: var TGeneralTokenizer) = +proc csharpNextToken(g: var GeneralTokenizer) = const keywords: array[0..76, string] = ["abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked", "class", "const", "continue", @@ -529,7 +532,7 @@ proc csharpNextToken(g: var TGeneralTokenizer) = "virtual", "void", "volatile", "while"] clikeNextToken(g, keywords, {hasPreprocessor}) -proc javaNextToken(g: var TGeneralTokenizer) = +proc javaNextToken(g: var GeneralTokenizer) = const keywords: array[0..52, string] = ["abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "default", @@ -541,7 +544,7 @@ proc javaNextToken(g: var TGeneralTokenizer) = "try", "void", "volatile", "while"] clikeNextToken(g, keywords, {}) -proc getNextToken*(g: var TGeneralTokenizer, lang: TSourceLanguage) = +proc getNextToken*(g: var GeneralTokenizer, lang: SourceLanguage) = case lang of langNone: assert false of langNim, langNimrod: nimNextToken(g) diff --git a/lib/packages/docutils/rst.nim b/lib/packages/docutils/rst.nim index 2ee94ba13..ae3ed8feb 100644 --- a/lib/packages/docutils/rst.nim +++ b/lib/packages/docutils/rst.nim @@ -15,7 +15,7 @@ import os, strutils, rstast type - TRstParseOption* = enum ## options for the RST parser + RstParseOption* = enum ## options for the RST parser roSkipPounds, ## skip ``#`` at line beginning (documentation ## embedded in Nim comments) roSupportSmilies, ## make the RST parser support smilies like ``:)`` @@ -23,14 +23,14 @@ type ## it for sandboxing) roSupportMarkdown ## support additional features of markdown - TRstParseOptions* = set[TRstParseOption] + RstParseOptions* = set[RstParseOption] - TMsgClass* = enum + MsgClass* = enum mcHint = "Hint", mcWarning = "Warning", mcError = "Error" - TMsgKind* = enum ## the possible messages + MsgKind* = enum ## the possible messages meCannotOpenFile, meExpected, meGridTableNotImplemented, @@ -42,12 +42,14 @@ type mwUnsupportedLanguage, mwUnsupportedField - TMsgHandler* = proc (filename: string, line, col: int, msgKind: TMsgKind, + MsgHandler* = proc (filename: string, line, col: int, msgKind: MsgKind, arg: string) {.nimcall.} ## what to do in case of an error - TFindFileHandler* = proc (filename: string): string {.nimcall.} + FindFileHandler* = proc (filename: string): string {.nimcall.} +{.deprecated: [TRstParseOptions: RstParseOptions, TRstParseOption: RstParseOption, + TMsgKind: MsgKind].} const - messages: array [TMsgKind, string] = [ + messages: array [MsgKind, string] = [ meCannotOpenFile: "cannot open '$1'", meExpected: "'$1' expected", meGridTableNotImplemented: "grid table is not implemented", @@ -111,23 +113,24 @@ const } type - TTokType = enum + TokType = enum tkEof, tkIndent, tkWhite, tkWord, tkAdornment, tkPunct, tkOther - TToken = object # a RST token - kind*: TTokType # the type of the token + Token = object # a RST token + kind*: TokType # the type of the token ival*: int # the indentation or parsed integer value symbol*: string # the parsed symbol as string line*, col*: int # line and column of the token - TTokenSeq = seq[TToken] - TLexer = object of RootObj + TokenSeq = seq[Token] + Lexer = object of RootObj buf*: cstring bufpos*: int line*, col*, baseIndent*: int skipPounds*: bool +{.deprecated: [TTokType: TokType, TToken: Token, TTokenSeq: TokenSeq, + TLexer: Lexer].} - -proc getThing(L: var TLexer, tok: var TToken, s: set[char]) = +proc getThing(L: var Lexer, tok: var Token, s: set[char]) = tok.kind = tkWord tok.line = L.line tok.col = L.col @@ -139,7 +142,7 @@ proc getThing(L: var TLexer, tok: var TToken, s: set[char]) = inc(L.col, pos - L.bufpos) L.bufpos = pos -proc getAdornment(L: var TLexer, tok: var TToken) = +proc getAdornment(L: var Lexer, tok: var Token) = tok.kind = tkAdornment tok.line = L.line tok.col = L.col @@ -152,7 +155,7 @@ proc getAdornment(L: var TLexer, tok: var TToken) = inc(L.col, pos - L.bufpos) L.bufpos = pos -proc getIndentAux(L: var TLexer, start: int): int = +proc getIndentAux(L: var Lexer, start: int): int = var pos = start var buf = L.buf # skip the newline (but include it in the token!) @@ -181,7 +184,7 @@ proc getIndentAux(L: var TLexer, start: int): int = result = getIndentAux(L, pos) L.bufpos = pos # no need to set back buf -proc getIndent(L: var TLexer, tok: var TToken) = +proc getIndent(L: var Lexer, tok: var Token) = tok.col = 0 tok.kind = tkIndent # skip the newline (but include it in the token!) tok.ival = getIndentAux(L, L.bufpos) @@ -191,7 +194,7 @@ proc getIndent(L: var TLexer, tok: var TToken) = tok.ival = max(tok.ival - L.baseIndent, 0) tok.symbol = "\n" & spaces(tok.ival) -proc rawGetTok(L: var TLexer, tok: var TToken) = +proc rawGetTok(L: var Lexer, tok: var Token) = tok.symbol = "" tok.ival = 0 var c = L.buf[L.bufpos] @@ -222,8 +225,8 @@ proc rawGetTok(L: var TLexer, tok: var TToken) = inc(L.col) tok.col = max(tok.col - L.baseIndent, 0) -proc getTokens(buffer: string, skipPounds: bool, tokens: var TTokenSeq): int = - var L: TLexer +proc getTokens(buffer: string, skipPounds: bool, tokens: var TokenSeq): int = + var L: Lexer var length = len(tokens) L.buf = cstring(buffer) L.line = 0 # skip UTF-8 BOM @@ -253,31 +256,31 @@ proc getTokens(buffer: string, skipPounds: bool, tokens: var TTokenSeq): int = tokens[0].kind = tkIndent type - TLevelMap = array[char, int] - TSubstitution = object + LevelMap = array[char, int] + Substitution = object key*: string value*: PRstNode - TSharedState = object - options: TRstParseOptions # parsing options + SharedState = object + options: RstParseOptions # parsing options uLevel, oLevel: int # counters for the section levels - subs: seq[TSubstitution] # substitutions - refs: seq[TSubstitution] # references - underlineToLevel: TLevelMap # Saves for each possible title adornment + subs: seq[Substitution] # substitutions + refs: seq[Substitution] # references + underlineToLevel: LevelMap # Saves for each possible title adornment # character its level in the # current document. # This is for single underline adornments. - overlineToLevel: TLevelMap # Saves for each possible title adornment + overlineToLevel: LevelMap # Saves for each possible title adornment # character its level in the current # document. # This is for over-underline adornments. - msgHandler: TMsgHandler # How to handle errors. - findFile: TFindFileHandler # How to find files. + msgHandler: MsgHandler # How to handle errors. + findFile: FindFileHandler # How to find files. - PSharedState = ref TSharedState - TRstParser = object of RootObj + PSharedState = ref SharedState + RstParser = object of RootObj idx*: int - tok*: TTokenSeq + tok*: TokenSeq s*: PSharedState indentStack*: seq[int] filename*: string @@ -285,8 +288,12 @@ type hasToc*: bool EParseError* = object of ValueError +{.deprecated: [TLevelMap: LevelMap, TSubstitution: Substitution, + TSharedState: SharedState, TRstParser: RstParser, + TMsgHandler: MsgHandler, TFindFileHandler: FindFileHandler, + TMsgClass: MsgClass].} -proc whichMsgClass*(k: TMsgKind): TMsgClass = +proc whichMsgClass*(k: MsgKind): MsgClass = ## returns which message class `k` belongs to. case ($k)[1] of 'e', 'E': result = mcError @@ -294,7 +301,7 @@ proc whichMsgClass*(k: TMsgKind): TMsgClass = of 'h', 'H': result = mcHint else: assert false, "msgkind does not fit naming scheme" -proc defaultMsgHandler*(filename: string, line, col: int, msgkind: TMsgKind, +proc defaultMsgHandler*(filename: string, line, col: int, msgkind: MsgKind, arg: string) {.procvar.} = let mc = msgkind.whichMsgClass let a = messages[msgkind] % arg @@ -306,9 +313,9 @@ proc defaultFindFile*(filename: string): string {.procvar.} = if existsFile(filename): result = filename else: result = "" -proc newSharedState(options: TRstParseOptions, - findFile: TFindFileHandler, - msgHandler: TMsgHandler): PSharedState = +proc newSharedState(options: RstParseOptions, + findFile: FindFileHandler, + msgHandler: MsgHandler): PSharedState = new(result) result.subs = @[] result.refs = @[] @@ -316,34 +323,34 @@ proc newSharedState(options: TRstParseOptions, result.msgHandler = if not isNil(msgHandler): msgHandler else: defaultMsgHandler result.findFile = if not isNil(findFile): findFile else: defaultFindFile -proc rstMessage(p: TRstParser, msgKind: TMsgKind, arg: string) = +proc rstMessage(p: RstParser, msgKind: MsgKind, arg: string) = p.s.msgHandler(p.filename, p.line + p.tok[p.idx].line, p.col + p.tok[p.idx].col, msgKind, arg) -proc rstMessage(p: TRstParser, msgKind: TMsgKind, arg: string, line, col: int) = +proc rstMessage(p: RstParser, msgKind: MsgKind, arg: string, line, col: int) = p.s.msgHandler(p.filename, p.line + line, p.col + col, msgKind, arg) -proc rstMessage(p: TRstParser, msgKind: TMsgKind) = +proc rstMessage(p: RstParser, msgKind: MsgKind) = p.s.msgHandler(p.filename, p.line + p.tok[p.idx].line, p.col + p.tok[p.idx].col, msgKind, p.tok[p.idx].symbol) when false: - proc corrupt(p: TRstParser) = + proc corrupt(p: RstParser) = assert p.indentStack[0] == 0 for i in 1 .. high(p.indentStack): assert p.indentStack[i] < 1_000 -proc currInd(p: TRstParser): int = +proc currInd(p: RstParser): int = result = p.indentStack[high(p.indentStack)] -proc pushInd(p: var TRstParser, ind: int) = +proc pushInd(p: var RstParser, ind: int) = add(p.indentStack, ind) -proc popInd(p: var TRstParser) = +proc popInd(p: var RstParser) = if len(p.indentStack) > 1: setLen(p.indentStack, len(p.indentStack) - 1) -proc initParser(p: var TRstParser, sharedState: PSharedState) = +proc initParser(p: var RstParser, sharedState: PSharedState) = p.indentStack = @[0] p.tok = @[] p.idx = 0 @@ -393,7 +400,7 @@ proc rstnodeToRefname(n: PRstNode): string = var b = false rstnodeToRefnameAux(n, result, b) -proc findSub(p: var TRstParser, n: PRstNode): int = +proc findSub(p: var RstParser, n: PRstNode): int = var key = addNodes(n) # the spec says: if no exact match, try one without case distinction: for i in countup(0, high(p.s.subs)): @@ -404,7 +411,7 @@ proc findSub(p: var TRstParser, n: PRstNode): int = return i result = -1 -proc setSub(p: var TRstParser, key: string, value: PRstNode) = +proc setSub(p: var RstParser, key: string, value: PRstNode) = var length = len(p.s.subs) for i in countup(0, length - 1): if key == p.s.subs[i].key: @@ -414,7 +421,7 @@ proc setSub(p: var TRstParser, key: string, value: PRstNode) = p.s.subs[length].key = key p.s.subs[length].value = value -proc setRef(p: var TRstParser, key: string, value: PRstNode) = +proc setRef(p: var RstParser, key: string, value: PRstNode) = var length = len(p.s.refs) for i in countup(0, length - 1): if key == p.s.refs[i].key: @@ -427,15 +434,15 @@ proc setRef(p: var TRstParser, key: string, value: PRstNode) = p.s.refs[length].key = key p.s.refs[length].value = value -proc findRef(p: var TRstParser, key: string): PRstNode = +proc findRef(p: var RstParser, key: string): PRstNode = for i in countup(0, high(p.s.refs)): if key == p.s.refs[i].key: return p.s.refs[i].value -proc newLeaf(p: var TRstParser): PRstNode = +proc newLeaf(p: var RstParser): PRstNode = result = newRstNode(rnLeaf, p.tok[p.idx].symbol) -proc getReferenceName(p: var TRstParser, endStr: string): PRstNode = +proc getReferenceName(p: var RstParser, endStr: string): PRstNode = var res = newRstNode(rnInner) while true: case p.tok[p.idx].kind @@ -453,17 +460,17 @@ proc getReferenceName(p: var TRstParser, endStr: string): PRstNode = inc(p.idx) result = res -proc untilEol(p: var TRstParser): PRstNode = +proc untilEol(p: var RstParser): PRstNode = result = newRstNode(rnInner) while not (p.tok[p.idx].kind in {tkIndent, tkEof}): add(result, newLeaf(p)) inc(p.idx) -proc expect(p: var TRstParser, tok: string) = +proc expect(p: var RstParser, tok: string) = if p.tok[p.idx].symbol == tok: inc(p.idx) else: rstMessage(p, meExpected, tok) -proc isInlineMarkupEnd(p: TRstParser, markup: string): bool = +proc isInlineMarkupEnd(p: RstParser, markup: string): bool = result = p.tok[p.idx].symbol == markup if not result: return # Rule 3: @@ -480,7 +487,7 @@ proc isInlineMarkupEnd(p: TRstParser, markup: string): bool = if (markup != "``") and (p.tok[p.idx - 1].symbol == "\\"): result = false -proc isInlineMarkupStart(p: TRstParser, markup: string): bool = +proc isInlineMarkupStart(p: RstParser, markup: string): bool = var d: char result = p.tok[p.idx].symbol == markup if not result: @@ -507,7 +514,7 @@ proc isInlineMarkupStart(p: TRstParser, markup: string): bool = else: d = '\0' if d != '\0': result = p.tok[p.idx + 1].symbol[0] != d -proc match(p: TRstParser, start: int, expr: string): bool = +proc match(p: RstParser, start: int, expr: string): bool = # regular expressions are: # special char exact match # 'w' tkWord @@ -562,7 +569,7 @@ proc fixupEmbeddedRef(n, a, b: PRstNode) = for i in countup(0, sep - incr): add(a, n.sons[i]) for i in countup(sep + 1, len(n) - 2): add(b, n.sons[i]) -proc parsePostfix(p: var TRstParser, n: PRstNode): PRstNode = +proc parsePostfix(p: var RstParser, n: PRstNode): PRstNode = result = n if isInlineMarkupEnd(p, "_") or isInlineMarkupEnd(p, "__"): inc(p.idx) @@ -606,7 +613,7 @@ proc parsePostfix(p: var TRstParser, n: PRstNode): PRstNode = add(result, newRstNode(rnLeaf, p.tok[p.idx + 1].symbol)) inc(p.idx, 3) -proc matchVerbatim(p: TRstParser, start: int, expr: string): int = +proc matchVerbatim(p: RstParser, start: int, expr: string): int = result = start var j = 0 while j < expr.len and result < p.tok.len and @@ -615,7 +622,7 @@ proc matchVerbatim(p: TRstParser, start: int, expr: string): int = inc result if j < expr.len: result = 0 -proc parseSmiley(p: var TRstParser): PRstNode = +proc parseSmiley(p: var RstParser): PRstNode = if p.tok[p.idx].symbol[0] notin SmileyStartChars: return for key, val in items(Smilies): let m = matchVerbatim(p, p.idx, key) @@ -631,12 +638,12 @@ when false: '$', '(', ')', '~', '_', '?', '+', '-', '=', '\\', '.', '&', '\128'..'\255'} -proc isUrl(p: TRstParser, i: int): bool = +proc isUrl(p: RstParser, i: int): bool = result = (p.tok[i+1].symbol == ":") and (p.tok[i+2].symbol == "//") and (p.tok[i+3].kind == tkWord) and (p.tok[i].symbol in ["http", "https", "ftp", "telnet", "file"]) -proc parseUrl(p: var TRstParser, father: PRstNode) = +proc parseUrl(p: var RstParser, father: PRstNode) = #if p.tok[p.idx].symbol[strStart] == '<': if isUrl(p, p.idx): var n = newRstNode(rnStandaloneHyperlink) @@ -656,7 +663,7 @@ proc parseUrl(p: var TRstParser, father: PRstNode) = if p.tok[p.idx].symbol == "_": n = parsePostfix(p, n) add(father, n) -proc parseBackslash(p: var TRstParser, father: PRstNode) = +proc parseBackslash(p: var RstParser, father: PRstNode) = assert(p.tok[p.idx].kind == tkPunct) if p.tok[p.idx].symbol == "\\\\": add(father, newRstNode(rnLeaf, "\\")) @@ -671,7 +678,7 @@ proc parseBackslash(p: var TRstParser, father: PRstNode) = inc(p.idx) when false: - proc parseAdhoc(p: var TRstParser, father: PRstNode, verbatim: bool) = + proc parseAdhoc(p: var RstParser, father: PRstNode, verbatim: bool) = if not verbatim and isURL(p, p.idx): var n = newRstNode(rnStandaloneHyperlink) while true: @@ -694,7 +701,7 @@ when false: if p.tok[p.idx].symbol == "_": n = parsePostfix(p, n) add(father, n) -proc parseUntil(p: var TRstParser, father: PRstNode, postfix: string, +proc parseUntil(p: var RstParser, father: PRstNode, postfix: string, interpretBackslash: bool) = let line = p.tok[p.idx].line @@ -725,7 +732,7 @@ proc parseUntil(p: var TRstParser, father: PRstNode, postfix: string, inc(p.idx) else: rstMessage(p, meExpected, postfix, line, col) -proc parseMarkdownCodeblock(p: var TRstParser): PRstNode = +proc parseMarkdownCodeblock(p: var RstParser): PRstNode = var args = newRstNode(rnDirArg) if p.tok[p.idx].kind == tkWord: add(args, newLeaf(p)) @@ -755,7 +762,7 @@ proc parseMarkdownCodeblock(p: var TRstParser): PRstNode = add(result, nil) add(result, lb) -proc parseInline(p: var TRstParser, father: PRstNode) = +proc parseInline(p: var RstParser, father: PRstNode) = case p.tok[p.idx].kind of tkPunct: if isInlineMarkupStart(p, "***"): @@ -810,7 +817,7 @@ proc parseInline(p: var TRstParser, father: PRstNode) = inc(p.idx) else: discard -proc getDirective(p: var TRstParser): string = +proc getDirective(p: var RstParser): string = if p.tok[p.idx].kind == tkWhite and p.tok[p.idx+1].kind == tkWord: var j = p.idx inc(p.idx) @@ -830,7 +837,7 @@ proc getDirective(p: var TRstParser): string = else: result = "" -proc parseComment(p: var TRstParser): PRstNode = +proc parseComment(p: var RstParser): PRstNode = case p.tok[p.idx].kind of tkIndent, tkEof: if p.tok[p.idx].kind != tkEof and p.tok[p.idx + 1].kind == tkIndent: @@ -851,34 +858,35 @@ proc parseComment(p: var TRstParser): PRstNode = result = nil type - TDirKind = enum # must be ordered alphabetically! + DirKind = enum # must be ordered alphabetically! dkNone, dkAuthor, dkAuthors, dkCode, dkCodeBlock, dkContainer, dkContents, dkFigure, dkImage, dkInclude, dkIndex, dkRaw, dkTitle +{.deprecated: [TDirKind: DirKind].} const DirIds: array[0..12, string] = ["", "author", "authors", "code", "code-block", "container", "contents", "figure", "image", "include", "index", "raw", "title"] -proc getDirKind(s: string): TDirKind = +proc getDirKind(s: string): DirKind = let i = find(DirIds, s) - if i >= 0: result = TDirKind(i) + if i >= 0: result = DirKind(i) else: result = dkNone -proc parseLine(p: var TRstParser, father: PRstNode) = +proc parseLine(p: var RstParser, father: PRstNode) = while true: case p.tok[p.idx].kind of tkWhite, tkWord, tkOther, tkPunct: parseInline(p, father) else: break -proc parseUntilNewline(p: var TRstParser, father: PRstNode) = +proc parseUntilNewline(p: var RstParser, father: PRstNode) = while true: case p.tok[p.idx].kind of tkWhite, tkWord, tkAdornment, tkOther, tkPunct: parseInline(p, father) of tkEof, tkIndent: break -proc parseSection(p: var TRstParser, result: PRstNode) {.gcsafe.} -proc parseField(p: var TRstParser): PRstNode = +proc parseSection(p: var RstParser, result: PRstNode) {.gcsafe.} +proc parseField(p: var RstParser): PRstNode = ## Returns a parsed rnField node. ## ## rnField nodes have two children nodes, a rnFieldName and a rnFieldBody. @@ -897,7 +905,7 @@ proc parseField(p: var TRstParser): PRstNode = add(result, fieldname) add(result, fieldbody) -proc parseFields(p: var TRstParser): PRstNode = +proc parseFields(p: var RstParser): PRstNode = ## Parses fields for a section or directive block. ## ## This proc may return nil if the parsing doesn't find anything of value, @@ -947,8 +955,8 @@ proc getArgument(n: PRstNode): string = if n.sons[0] == nil: result = "" else: result = addNodes(n.sons[0]) -proc parseDotDot(p: var TRstParser): PRstNode {.gcsafe.} -proc parseLiteralBlock(p: var TRstParser): PRstNode = +proc parseDotDot(p: var RstParser): PRstNode {.gcsafe.} +proc parseLiteralBlock(p: var RstParser): PRstNode = result = newRstNode(rnLiteralBlock) var n = newRstNode(rnLeaf, "") if p.tok[p.idx].kind == tkIndent: @@ -974,13 +982,13 @@ proc parseLiteralBlock(p: var TRstParser): PRstNode = inc(p.idx) add(result, n) -proc getLevel(map: var TLevelMap, lvl: var int, c: char): int = +proc getLevel(map: var LevelMap, lvl: var int, c: char): int = if map[c] == 0: inc(lvl) map[c] = lvl result = map[c] -proc tokenAfterNewline(p: TRstParser): int = +proc tokenAfterNewline(p: RstParser): int = result = p.idx while true: case p.tok[result].kind @@ -991,28 +999,28 @@ proc tokenAfterNewline(p: TRstParser): int = break else: inc(result) -proc isLineBlock(p: TRstParser): bool = +proc isLineBlock(p: RstParser): bool = var j = tokenAfterNewline(p) result = (p.tok[p.idx].col == p.tok[j].col) and (p.tok[j].symbol == "|") or (p.tok[j].col > p.tok[p.idx].col) -proc predNL(p: TRstParser): bool = +proc predNL(p: RstParser): bool = result = true if p.idx > 0: result = p.tok[p.idx-1].kind == tkIndent and p.tok[p.idx-1].ival == currInd(p) -proc isDefList(p: TRstParser): bool = +proc isDefList(p: RstParser): bool = var j = tokenAfterNewline(p) result = (p.tok[p.idx].col < p.tok[j].col) and (p.tok[j].kind in {tkWord, tkOther, tkPunct}) and (p.tok[j - 2].symbol != "::") -proc isOptionList(p: TRstParser): bool = +proc isOptionList(p: RstParser): bool = result = match(p, p.idx, "-w") or match(p, p.idx, "--w") or match(p, p.idx, "/w") or match(p, p.idx, "//w") -proc whichSection(p: TRstParser): TRstNodeKind = +proc whichSection(p: RstParser): RstNodeKind = case p.tok[p.idx].kind of tkAdornment: if match(p, p.idx + 1, "ii"): result = rnTransition @@ -1053,7 +1061,7 @@ proc whichSection(p: TRstParser): TRstNodeKind = else: result = rnParagraph else: result = rnLeaf -proc parseLineBlock(p: var TRstParser): PRstNode = +proc parseLineBlock(p: var RstParser): PRstNode = result = nil if p.tok[p.idx + 1].kind == tkWhite: var col = p.tok[p.idx].col @@ -1072,7 +1080,7 @@ proc parseLineBlock(p: var TRstParser): PRstNode = break popInd(p) -proc parseParagraph(p: var TRstParser, result: PRstNode) = +proc parseParagraph(p: var RstParser, result: PRstNode) = while true: case p.tok[p.idx].kind of tkIndent: @@ -1103,7 +1111,7 @@ proc parseParagraph(p: var TRstParser, result: PRstNode) = parseInline(p, result) else: break -proc parseHeadline(p: var TRstParser): PRstNode = +proc parseHeadline(p: var RstParser): PRstNode = result = newRstNode(rnHeadline) parseUntilNewline(p, result) assert(p.tok[p.idx].kind == tkIndent) @@ -1113,12 +1121,13 @@ proc parseHeadline(p: var TRstParser): PRstNode = result.level = getLevel(p.s.underlineToLevel, p.s.uLevel, c) type - TIntSeq = seq[int] + IntSeq = seq[int] +{.deprecated: [TIntSeq: IntSeq].} -proc tokEnd(p: TRstParser): int = +proc tokEnd(p: RstParser): int = result = p.tok[p.idx].col + len(p.tok[p.idx].symbol) - 1 -proc getColumns(p: var TRstParser, cols: var TIntSeq) = +proc getColumns(p: var RstParser, cols: var IntSeq) = var L = 0 while true: inc(L) @@ -1133,15 +1142,15 @@ proc getColumns(p: var TRstParser, cols: var TIntSeq) = # last column has no limit: cols[L - 1] = 32000 -proc parseDoc(p: var TRstParser): PRstNode {.gcsafe.} +proc parseDoc(p: var RstParser): PRstNode {.gcsafe.} -proc parseSimpleTable(p: var TRstParser): PRstNode = +proc parseSimpleTable(p: var RstParser): PRstNode = var - cols: TIntSeq + cols: IntSeq row: seq[string] i, last, line: int c: char - q: TRstParser + q: RstParser a, b: PRstNode result = newRstNode(rnTable) cols = @[] @@ -1188,13 +1197,13 @@ proc parseSimpleTable(p: var TRstParser): PRstNode = add(a, b) add(result, a) -proc parseTransition(p: var TRstParser): PRstNode = +proc parseTransition(p: var RstParser): PRstNode = result = newRstNode(rnTransition) inc(p.idx) if p.tok[p.idx].kind == tkIndent: inc(p.idx) if p.tok[p.idx].kind == tkIndent: inc(p.idx) -proc parseOverline(p: var TRstParser): PRstNode = +proc parseOverline(p: var RstParser): PRstNode = var c = p.tok[p.idx].symbol[0] inc(p.idx, 2) result = newRstNode(rnOverline) @@ -1213,7 +1222,7 @@ proc parseOverline(p: var TRstParser): PRstNode = inc(p.idx) # XXX: check? if p.tok[p.idx].kind == tkIndent: inc(p.idx) -proc parseBulletList(p: var TRstParser): PRstNode = +proc parseBulletList(p: var RstParser): PRstNode = result = nil if p.tok[p.idx + 1].kind == tkWhite: var bullet = p.tok[p.idx].symbol @@ -1233,7 +1242,7 @@ proc parseBulletList(p: var TRstParser): PRstNode = break popInd(p) -proc parseOptionList(p: var TRstParser): PRstNode = +proc parseOptionList(p: var RstParser): PRstNode = result = newRstNode(rnOptionList) while true: if isOptionList(p): @@ -1262,7 +1271,7 @@ proc parseOptionList(p: var TRstParser): PRstNode = else: break -proc parseDefinitionList(p: var TRstParser): PRstNode = +proc parseDefinitionList(p: var RstParser): PRstNode = result = nil var j = tokenAfterNewline(p) - 1 if (j >= 1) and (p.tok[j].kind == tkIndent) and @@ -1298,7 +1307,7 @@ proc parseDefinitionList(p: var TRstParser): PRstNode = break if len(result) == 0: result = nil -proc parseEnumList(p: var TRstParser): PRstNode = +proc parseEnumList(p: var RstParser): PRstNode = const wildcards: array[0..2, string] = ["(e) ", "e) ", "e. "] wildpos: array[0..2, int] = [1, 0, 0] @@ -1328,11 +1337,11 @@ proc parseEnumList(p: var TRstParser): PRstNode = dec(p.idx, wildpos[w] + 3) result = nil -proc sonKind(father: PRstNode, i: int): TRstNodeKind = +proc sonKind(father: PRstNode, i: int): RstNodeKind = result = rnLeaf if i < len(father): result = father.sons[i].kind -proc parseSection(p: var TRstParser, result: PRstNode) = +proc parseSection(p: var RstParser, result: PRstNode) = while true: var leave = false assert(p.idx >= 0) @@ -1380,16 +1389,16 @@ proc parseSection(p: var TRstParser, result: PRstNode) = if sonKind(result, 0) == rnParagraph and sonKind(result, 1) != rnParagraph: result.sons[0].kind = rnInner -proc parseSectionWrapper(p: var TRstParser): PRstNode = +proc parseSectionWrapper(p: var RstParser): PRstNode = result = newRstNode(rnInner) parseSection(p, result) while (result.kind == rnInner) and (len(result) == 1): result = result.sons[0] -proc `$`(t: TToken): string = +proc `$`(t: Token): string = result = $t.kind & ' ' & (if isNil(t.symbol): "NIL" else: t.symbol) -proc parseDoc(p: var TRstParser): PRstNode = +proc parseDoc(p: var RstParser): PRstNode = result = parseSectionWrapper(p) if p.tok[p.idx].kind != tkEof: when false: @@ -1403,12 +1412,14 @@ proc parseDoc(p: var TRstParser): PRstNode = rstMessage(p, meGeneralParseError) type - TDirFlag = enum + DirFlag = enum hasArg, hasOptions, argIsFile, argIsWord - TDirFlags = set[TDirFlag] - TSectionParser = proc (p: var TRstParser): PRstNode {.nimcall.} + DirFlags = set[DirFlag] + SectionParser = proc (p: var RstParser): PRstNode {.nimcall.} +{.deprecated: [TDirFlag: DirFlag, TDirFlags: DirFlags, + TSectionParser: SectionParser].} -proc parseDirective(p: var TRstParser, flags: TDirFlags): PRstNode = +proc parseDirective(p: var RstParser, flags: DirFlags): PRstNode = ## Parses arguments and options for a directive block. ## ## A directive block will always have three sons: the arguments for the @@ -1446,11 +1457,11 @@ proc parseDirective(p: var TRstParser, flags: TDirFlags): PRstNode = options = parseFields(p) add(result, options) -proc indFollows(p: TRstParser): bool = +proc indFollows(p: RstParser): bool = result = p.tok[p.idx].kind == tkIndent and p.tok[p.idx].ival > currInd(p) -proc parseDirective(p: var TRstParser, flags: TDirFlags, - contentParser: TSectionParser): PRstNode = +proc parseDirective(p: var RstParser, flags: DirFlags, + contentParser: SectionParser): PRstNode = ## Returns a generic rnDirective tree. ## ## The children are rnDirArg, rnFieldList and rnLineBlock. Any might be nil. @@ -1463,13 +1474,13 @@ proc parseDirective(p: var TRstParser, flags: TDirFlags, else: add(result, nil) -proc parseDirBody(p: var TRstParser, contentParser: TSectionParser): PRstNode = +proc parseDirBody(p: var RstParser, contentParser: SectionParser): PRstNode = if indFollows(p): pushInd(p, p.tok[p.idx].ival) result = contentParser(p) popInd(p) -proc dirInclude(p: var TRstParser): PRstNode = +proc dirInclude(p: var RstParser): PRstNode = # #The following options are recognized: # @@ -1498,7 +1509,7 @@ proc dirInclude(p: var TRstParser): PRstNode = result = newRstNode(rnLiteralBlock) add(result, newRstNode(rnLeaf, readFile(path))) else: - var q: TRstParser + var q: RstParser initParser(q, p.s) q.filename = filename q.col += getTokens(readFile(path), false, q.tok) @@ -1507,7 +1518,7 @@ proc dirInclude(p: var TRstParser): PRstNode = # InternalError("Too many binary zeros in include file") result = parseDoc(q) -proc dirCodeBlock(p: var TRstParser, nimrodExtension = false): PRstNode = +proc dirCodeBlock(p: var RstParser, nimrodExtension = false): PRstNode = ## Parses a code block. ## ## Code blocks are rnDirective trees with a `kind` of rnCodeBlock. See the @@ -1548,35 +1559,35 @@ proc dirCodeBlock(p: var TRstParser, nimrodExtension = false): PRstNode = result.kind = rnCodeBlock -proc dirContainer(p: var TRstParser): PRstNode = +proc dirContainer(p: var RstParser): PRstNode = result = parseDirective(p, {hasArg}, parseSectionWrapper) assert(result.kind == rnDirective) assert(len(result) == 3) result.kind = rnContainer -proc dirImage(p: var TRstParser): PRstNode = +proc dirImage(p: var RstParser): PRstNode = result = parseDirective(p, {hasOptions, hasArg, argIsFile}, nil) result.kind = rnImage -proc dirFigure(p: var TRstParser): PRstNode = +proc dirFigure(p: var RstParser): PRstNode = result = parseDirective(p, {hasOptions, hasArg, argIsFile}, parseSectionWrapper) result.kind = rnFigure -proc dirTitle(p: var TRstParser): PRstNode = +proc dirTitle(p: var RstParser): PRstNode = result = parseDirective(p, {hasArg}, nil) result.kind = rnTitle -proc dirContents(p: var TRstParser): PRstNode = +proc dirContents(p: var RstParser): PRstNode = result = parseDirective(p, {hasArg}, nil) result.kind = rnContents -proc dirIndex(p: var TRstParser): PRstNode = +proc dirIndex(p: var RstParser): PRstNode = result = parseDirective(p, {}, parseSectionWrapper) result.kind = rnIndex -proc dirRawAux(p: var TRstParser, result: var PRstNode, kind: TRstNodeKind, - contentParser: TSectionParser) = +proc dirRawAux(p: var RstParser, result: var PRstNode, kind: RstNodeKind, + contentParser: SectionParser) = var filename = getFieldValue(result, "file") if filename.len > 0: var path = p.s.findFile(filename) @@ -1590,7 +1601,7 @@ proc dirRawAux(p: var TRstParser, result: var PRstNode, kind: TRstNodeKind, result.kind = kind add(result, parseDirBody(p, contentParser)) -proc dirRaw(p: var TRstParser): PRstNode = +proc dirRaw(p: var RstParser): PRstNode = # #The following options are recognized: # @@ -1610,7 +1621,7 @@ proc dirRaw(p: var TRstParser): PRstNode = else: dirRawAux(p, result, rnRaw, parseSectionWrapper) -proc parseDotDot(p: var TRstParser): PRstNode = +proc parseDotDot(p: var RstParser): PRstNode = result = nil var col = p.tok[p.idx].col inc(p.idx) @@ -1667,7 +1678,7 @@ proc parseDotDot(p: var TRstParser): PRstNode = else: result = parseComment(p) -proc resolveSubs(p: var TRstParser, n: PRstNode): PRstNode = +proc resolveSubs(p: var RstParser, n: PRstNode): PRstNode = result = n if n == nil: return case n.kind @@ -1696,10 +1707,10 @@ proc resolveSubs(p: var TRstParser, n: PRstNode): PRstNode = proc rstParse*(text, filename: string, line, column: int, hasToc: var bool, - options: TRstParseOptions, - findFile: TFindFileHandler = nil, - msgHandler: TMsgHandler = nil): PRstNode = - var p: TRstParser + options: RstParseOptions, + findFile: FindFileHandler = nil, + msgHandler: MsgHandler = nil): PRstNode = + var p: RstParser initParser(p, newSharedState(options, findFile, msgHandler)) p.filename = filename p.line = line diff --git a/lib/packages/docutils/rstast.nim b/lib/packages/docutils/rstast.nim index c3956ab8b..7be4470c1 100644 --- a/lib/packages/docutils/rstast.nim +++ b/lib/packages/docutils/rstast.nim @@ -12,7 +12,7 @@ import strutils, json type - TRstNodeKind* = enum ## the possible node kinds of an PRstNode + RstNodeKind* = enum ## the possible node kinds of an PRstNode rnInner, # an inner node or a root rnHeadline, # a headline rnOverline, # an over- and underlined headline @@ -62,24 +62,26 @@ type # leaf val - PRstNode* = ref TRstNode ## an RST node - TRstNodeSeq* = seq[PRstNode] - TRstNode* {.acyclic, final.} = object ## an RST node's description - kind*: TRstNodeKind ## the node's kind + PRstNode* = ref RstNode ## an RST node + RstNodeSeq* = seq[PRstNode] + RstNode* {.acyclic, final.} = object ## an RST node's description + kind*: RstNodeKind ## the node's kind text*: string ## valid for leafs in the AST; and the title of ## the document or the section level*: int ## valid for some node kinds - sons*: TRstNodeSeq ## the node's sons + sons*: RstNodeSeq ## the node's sons +{.deprecated: [TRstNodeKind: RstNodeKind, TRstNodeSeq: RstNodeSeq, + TRstNode: RstNode].} proc len*(n: PRstNode): int = result = len(n.sons) -proc newRstNode*(kind: TRstNodeKind): PRstNode = +proc newRstNode*(kind: RstNodeKind): PRstNode = new(result) result.sons = @[] result.kind = kind -proc newRstNode*(kind: TRstNodeKind, s: string): PRstNode = +proc newRstNode*(kind: RstNodeKind, s: string): PRstNode = result = newRstNode(kind) result.text = s @@ -94,18 +96,19 @@ proc addIfNotNil*(father, son: PRstNode) = type - TRenderContext {.pure.} = object + RenderContext {.pure.} = object indent: int verbatim: int +{.deprecated: [TRenderContext: RenderContext].} -proc renderRstToRst(d: var TRenderContext, n: PRstNode, +proc renderRstToRst(d: var RenderContext, n: PRstNode, result: var string) {.gcsafe.} -proc renderRstSons(d: var TRenderContext, n: PRstNode, result: var string) = +proc renderRstSons(d: var RenderContext, n: PRstNode, result: var string) = for i in countup(0, len(n) - 1): renderRstToRst(d, n.sons[i], result) -proc renderRstToRst(d: var TRenderContext, n: PRstNode, result: var string) = +proc renderRstToRst(d: var RenderContext, n: PRstNode, result: var string) = # this is needed for the index generation; it may also be useful for # debugging, but most code is already debugged... const @@ -284,7 +287,7 @@ proc renderRstToRst(d: var TRenderContext, n: PRstNode, result: var string) = proc renderRstToRst*(n: PRstNode, result: var string) = ## renders `n` into its string representation and appends to `result`. - var d: TRenderContext + var d: RenderContext renderRstToRst(d, n, result) proc renderRstToJsonNode(node: PRstNode): JsonNode = diff --git a/lib/packages/docutils/rstgen.nim b/lib/packages/docutils/rstgen.nim index 9e96d8a63..f9c8198f2 100644 --- a/lib/packages/docutils/rstgen.nim +++ b/lib/packages/docutils/rstgen.nim @@ -18,7 +18,7 @@ ## document you provide yourself, so it won't contain the usual ``
`` or ## ```` parts. ## -## You can also create a ``TRstGenerator`` structure and populate it with the +## You can also create a ``RstGenerator`` structure and populate it with the ## other lower level methods to finally build complete documents. This requires ## many options and tweaking, but you are not limited to snippets and can ## generate `LaTeX documents `_ too. @@ -31,29 +31,29 @@ const IndexExt* = ".idx" type - TOutputTarget* = enum ## which document type to generate + OutputTarget* = enum ## which document type to generate outHtml, # output is HTML outLatex # output is Latex - TTocEntry = object + TocEntry = object n*: PRstNode refname*, header*: string - TMetaEnum* = enum + MetaEnum* = enum metaNone, metaTitle, metaSubtitle, metaAuthor, metaVersion - TRstGenerator* = object of RootObj - target*: TOutputTarget + RstGenerator* = object of RootObj + target*: OutputTarget config*: StringTableRef splitAfter*: int # split too long entries in the TOC - tocPart*: seq[TTocEntry] + tocPart*: seq[TocEntry] hasToc*: bool theIndex: string # Contents of the index file to be dumped at the end. - options*: TRstParseOptions - findFile*: TFindFileHandler - msgHandler*: TMsgHandler + options*: RstParseOptions + findFile*: FindFileHandler + msgHandler*: MsgHandler filename*: string - meta*: array[TMetaEnum, string] + meta*: array[MetaEnum, string] currentSection: string ## \ ## Stores the empty string or the last headline/overline found in the rst ## document, so it can be used as a prettier name for term index generation. @@ -61,14 +61,15 @@ type ## Keeps count of same text index terms to generate different identifiers ## for hyperlinks. See renderIndexTerm proc for details. - PDoc = var TRstGenerator ## Alias to type less. + PDoc = var RstGenerator ## Alias to type less. CodeBlockParams = object ## Stores code block params. numberLines: bool ## True if the renderer has to show line numbers. startLine: int ## The starting line of the code block, by default 1. langStr: string ## Input string used to specify the language. - lang: TSourceLanguage ## Type of highlighting, by default none. - + lang: SourceLanguage ## Type of highlighting, by default none. +{.deprecated: [TRstGenerator: RstGenerator, TTocEntry: TocEntry, + TOutputTarget: OutputTarget, TMetaEnum: MetaEnum].} proc init(p: var CodeBlockParams) = ## Default initialisation of CodeBlockParams to sane values. @@ -76,14 +77,14 @@ proc init(p: var CodeBlockParams) = p.lang = langNone p.langStr = "" -proc initRstGenerator*(g: var TRstGenerator, target: TOutputTarget, +proc initRstGenerator*(g: var RstGenerator, target: OutputTarget, config: StringTableRef, filename: string, - options: TRstParseOptions, - findFile: TFindFileHandler=nil, - msgHandler: TMsgHandler=nil) = - ## Initializes a ``TRstGenerator``. + options: RstParseOptions, + findFile: FindFileHandler=nil, + msgHandler: MsgHandler=nil) = + ## Initializes a ``RstGenerator``. ## - ## You need to call this before using a ``TRstGenerator`` with any other + ## You need to call this before using a ``RstGenerator`` with any other ## procs in this module. Pass a non ``nil`` ``StringTableRef`` value as ## `config` with parameters used by the HTML output generator. If you don't ## know what to use, pass the results of the `defaultConfig() @@ -96,7 +97,7 @@ proc initRstGenerator*(g: var TRstGenerator, target: TOutputTarget, ## filename``. This default title can be overriden by the embedded rst, but ## it helps to prettify the generated index if no title is found. ## - ## The ``TRstParseOptions``, ``TFindFileHandler`` and ``TMsgHandler`` types + ## The ``RstParseOptions``, ``FindFileHandler`` and ``MsgHandler`` types ## are defined in the the `packages/docutils/rst module `_. ## ``options`` selects the behaviour of the rst parser. ## @@ -120,7 +121,7 @@ proc initRstGenerator*(g: var TRstGenerator, target: TOutputTarget, ## ## import packages/docutils/rstgen ## - ## var gen: TRstGenerator + ## var gen: RstGenerator ## gen.initRstGenerator(outHtml, defaultConfig(), "filename", {}) g.config = config g.target = target @@ -141,7 +142,7 @@ proc initRstGenerator*(g: var TRstGenerator, target: TOutputTarget, if s != "": g.splitAfter = parseInt(s) for i in low(g.meta)..high(g.meta): g.meta[i] = "" -proc writeIndexFile*(g: var TRstGenerator, outfile: string) = +proc writeIndexFile*(g: var RstGenerator, outfile: string) = ## Writes the current index buffer to the specified output file. ## ## You previously need to add entries to the index with the `setIndexTerm() @@ -183,7 +184,7 @@ proc addTexChar(dest: var string, c: char) = var splitter*: string = "" -proc escChar*(target: TOutputTarget, dest: var string, c: char) {.inline.} = +proc escChar*(target: OutputTarget, dest: var string, c: char) {.inline.} = case target of outHtml: addXmlChar(dest, c) of outLatex: addTexChar(dest, c) @@ -200,7 +201,7 @@ proc nextSplitPoint*(s: string, start: int): int = inc(result) dec(result) # last valid index -proc esc*(target: TOutputTarget, s: string, splitAfter = -1): string = +proc esc*(target: OutputTarget, s: string, splitAfter = -1): string = result = "" if splitAfter >= 0: var partLen = 0 @@ -217,16 +218,16 @@ proc esc*(target: TOutputTarget, s: string, splitAfter = -1): string = for i in countup(0, len(s) - 1): escChar(target, result, s[i]) -proc disp(target: TOutputTarget, xml, tex: string): string = +proc disp(target: OutputTarget, xml, tex: string): string = if target != outLatex: result = xml else: result = tex -proc dispF(target: TOutputTarget, xml, tex: string, +proc dispF(target: OutputTarget, xml, tex: string, args: varargs[string]): string = if target != outLatex: result = xml % args else: result = tex % args -proc dispA(target: TOutputTarget, dest: var string, +proc dispA(target: OutputTarget, dest: var string, xml, tex: string, args: varargs[string]) = if target != outLatex: addf(dest, xml, args) else: addf(dest, tex, args) @@ -234,10 +235,10 @@ proc dispA(target: TOutputTarget, dest: var string, proc `or`(x, y: string): string {.inline.} = result = if x.isNil: y else: x -proc renderRstToOut*(d: var TRstGenerator, n: PRstNode, result: var string) +proc renderRstToOut*(d: var RstGenerator, n: PRstNode, result: var string) ## Writes into ``result`` the rst ast ``n`` using the ``d`` configuration. ## - ## Before using this proc you need to initialise a ``TRstGenerator`` with + ## Before using this proc you need to initialise a ``RstGenerator`` with ## ``initRstGenerator`` and parse a rst file with ``rstParse`` from the ## `packages/docutils/rst module `_. Example: ## @@ -277,7 +278,7 @@ proc unquoteIndexColumn(text: string): string = ## Returns the unquoted version generated by ``quoteIndexColumn``. result = text.replace("\\t", "\t").replace("\\n", "\n").replace("\\\\", "\\") -proc setIndexTerm*(d: var TRstGenerator, id, term: string, +proc setIndexTerm*(d: var RstGenerator, id, term: string, linkTitle, linkDesc = "") = ## Adds a `term` to the index using the specified hyperlink identifier. ## @@ -351,30 +352,30 @@ proc renderIndexTerm*(d: PDoc, n: PRstNode, result: var string) = [id, term]) type - TIndexEntry = object + IndexEntry = object keyword: string link: string linkTitle: string ## If not nil, contains a prettier text for the href linkDesc: string ## If not nil, the title attribute of the final href - TIndexedDocs = Table[TIndexEntry, seq[TIndexEntry]] ## \ + IndexedDocs = Table[IndexEntry, seq[IndexEntry]] ## \ ## Contains the index sequences for doc types. ## - ## The key is a *fake* TIndexEntry which will contain the title of the + ## The key is a *fake* IndexEntry which will contain the title of the ## document in the `keyword` field and `link` will contain the html ## filename for the document. `linkTitle` and `linkDesc` will be nil. ## - ## The value indexed by this TIndexEntry is a sequence with the real index + ## The value indexed by this IndexEntry is a sequence with the real index ## entries found in the ``.idx`` file. +{.deprecated: [TIndexEntry: IndexEntry, TIndexedDocs: IndexedDocs].} - -proc cmp(a, b: TIndexEntry): int = - ## Sorts two ``TIndexEntry`` first by `keyword` field, then by `link`. +proc cmp(a, b: IndexEntry): int = + ## Sorts two ``IndexEntry`` first by `keyword` field, then by `link`. result = cmpIgnoreStyle(a.keyword, b.keyword) if result == 0: result = cmpIgnoreStyle(a.link, b.link) -proc hash(x: TIndexEntry): THash = +proc hash(x: IndexEntry): Hash = ## Returns the hash for the combined fields of the type. ## ## The hash is computed as the chained hash of the individual string hashes. @@ -385,7 +386,7 @@ proc hash(x: TIndexEntry): THash = result = result !& (x.linkDesc or "").hash result = !$result -proc `<-`(a: var TIndexEntry, b: TIndexEntry) = +proc `<-`(a: var IndexEntry, b: IndexEntry) = shallowCopy a.keyword, b.keyword shallowCopy a.link, b.link if b.linkTitle.isNil: a.linkTitle = nil @@ -393,7 +394,7 @@ proc `<-`(a: var TIndexEntry, b: TIndexEntry) = if b.linkDesc.isNil: a.linkDesc = nil else: shallowCopy a.linkDesc, b.linkDesc -proc sortIndex(a: var openArray[TIndexEntry]) = +proc sortIndex(a: var openArray[IndexEntry]) = # we use shellsort here; fast and simple let n = len(a) var h = 1 @@ -403,7 +404,7 @@ proc sortIndex(a: var openArray[TIndexEntry]) = while true: h = h div 3 for i in countup(h, n - 1): - var v: TIndexEntry + var v: IndexEntry v <- a[i] var j = i while cmp(a[j-h], v) >= 0: @@ -413,7 +414,7 @@ proc sortIndex(a: var openArray[TIndexEntry]) = a[j] <- v if h == 1: break -proc generateSymbolIndex(symbols: seq[TIndexEntry]): string = +proc generateSymbolIndex(symbols: seq[IndexEntry]): string = result = "" var i = 0 while i < symbols.len: @@ -466,7 +467,7 @@ proc indentToLevel(level: var int, newLevel: int): string = result = repeat("", level - newLevel) level = newLevel -proc generateDocumentationTOC(entries: seq[TIndexEntry]): string = +proc generateDocumentationTOC(entries: seq[IndexEntry]): string = ## Returns the sequence of index entries in an HTML hierarchical list. result = "" # Build a list of levels and extracted titles to make processing easier. @@ -507,12 +508,12 @@ proc generateDocumentationTOC(entries: seq[TIndexEntry]): string = assert(not titleRef.isNil, "Can't use this proc on an API index, docs always have a title entry") -proc generateDocumentationIndex(docs: TIndexedDocs): string = +proc generateDocumentationIndex(docs: IndexedDocs): string = ## Returns all the documentation TOCs in an HTML hierarchical list. result = "" # Sort the titles to generate their toc in alphabetical order. - var titles = toSeq(keys[TIndexEntry, seq[TIndexEntry]](docs)) + var titles = toSeq(keys[IndexEntry, seq[IndexEntry]](docs)) sort(titles, cmp) for title in titles: @@ -520,12 +521,12 @@ proc generateDocumentationIndex(docs: TIndexedDocs): string = result.add("\n") -proc generateDocumentationJumps(docs: TIndexedDocs): string = +proc generateDocumentationJumps(docs: IndexedDocs): string = ## Returns a plain list of hyperlinks to documentation TOCs in HTML. result = "Documents: " # Sort the titles to generate their toc in alphabetical order. - var titles = toSeq(keys[TIndexEntry, seq[TIndexEntry]](docs)) + var titles = toSeq(keys[IndexEntry, seq[IndexEntry]](docs)) sort(titles, cmp) var chunks: seq[string] = @[] @@ -545,14 +546,14 @@ proc generateModuleJumps(modules: seq[string]): string = result.add(chunks.join(", ") & ".
") proc readIndexDir(dir: string): - tuple[modules: seq[string], symbols: seq[TIndexEntry], docs: TIndexedDocs] = - ## Walks `dir` reading ``.idx`` files converting them in TIndexEntry items. + tuple[modules: seq[string], symbols: seq[IndexEntry], docs: IndexedDocs] = + ## Walks `dir` reading ``.idx`` files converting them in IndexEntry items. ## ## Returns the list of found module names, the list of free symbol entries ## and the different documentation indexes. The list of modules is sorted. ## See the documentation of ``mergeIndexes`` for details. result.modules = @[] - result.docs = initTable[TIndexEntry, seq[TIndexEntry]](32) + result.docs = initTable[IndexEntry, seq[IndexEntry]](32) newSeq(result.symbols, 15_000) setLen(result.symbols, 0) var L = 0 @@ -560,8 +561,8 @@ proc readIndexDir(dir: string): for kind, path in walkDir(dir): if kind == pcFile and path.endsWith(IndexExt): var - fileEntries: seq[TIndexEntry] - title: TIndexEntry + fileEntries: seq[IndexEntry] + title: IndexEntry F = 0 newSeq(fileEntries, 500) setLen(fileEntries, 0) @@ -662,7 +663,7 @@ proc mergeIndexes*(dir: string): string = proc stripTOCHTML(s: string): string = ## Ugly quick hack to remove HTML tags from TOC titles. ## - ## A TTocEntry.header field already contains rendered HTML tags. Instead of + ## A TocEntry.header field already contains rendered HTML tags. Instead of ## implementing a proper version of renderRstToOut() which recursively ## renders an rst tree to plain text, we simply remove text found between ## angled brackets. Given the limited possibilities of rst inside TOC titles @@ -728,12 +729,12 @@ proc renderOverline(d: PDoc, n: PRstNode, result: var string) = rstnodeToRefname(n), tmp, $chr(n.level - 1 + ord('A'))]) -proc renderTocEntry(d: PDoc, e: TTocEntry, result: var string) = +proc renderTocEntry(d: PDoc, e: TocEntry, result: var string) = dispA(d.target, result, "
  • $2
  • \n", "\\item\\label{$1_toc} $2\\ref{$1}\n", [e.refname, e.header]) -proc renderTocEntries*(d: var TRstGenerator, j: var int, lvl: int, +proc renderTocEntries*(d: var RstGenerator, j: var int, lvl: int, result: var string) = var tmp = "" while j <= high(d.tocPart): @@ -878,7 +879,7 @@ proc renderCodeBlock(d: PDoc, n: PRstNode, result: var string) = d.msgHandler(d.filename, 1, 0, mwUnsupportedLanguage, params.langStr) for letter in m.text: escChar(d.target, result, letter) else: - var g: TGeneralTokenizer + var g: GeneralTokenizer initGeneralTokenizer(g, m.text) while true: getNextToken(g, params.lang) @@ -1214,7 +1215,7 @@ $content # ---------- forum --------------------------------------------------------- -proc rstToHtml*(s: string, options: TRstParseOptions, +proc rstToHtml*(s: string, options: RstParseOptions, config: StringTableRef): string = ## Converts an input rst string into embeddable HTML. ## @@ -1233,7 +1234,7 @@ proc rstToHtml*(s: string, options: TRstParseOptions, ## # --> Hello world! ## ## If you need to allow the rst ``include`` directive or tweak the generated - ## output you have to create your own ``TRstGenerator`` with + ## output you have to create your own ``RstGenerator`` with ## ``initRstGenerator`` and related procs. proc myFindFile(filename: string): string = @@ -1241,7 +1242,7 @@ proc rstToHtml*(s: string, options: TRstParseOptions, result = "" const filen = "input" - var d: TRstGenerator + var d: RstGenerator initRstGenerator(d, outHtml, config, filen, options, myFindFile, rst.defaultMsgHandler) var dummyHasToc = false From 1c426c613c4310b7ecf9358160c07074da73d327 Mon Sep 17 00:00:00 2001 From: pdw Date: Sun, 24 May 2015 22:26:36 -0500 Subject: [PATCH 0349/1263] lib/posix - Dropped 'T' from types --- lib/posix/inotify.nim | 7 +- lib/posix/linux.nim | 4 +- lib/posix/posix.nim | 922 ++++++++++++++++++++++-------------------- lib/posix/termios.nim | 13 +- 4 files changed, 487 insertions(+), 459 deletions(-) diff --git a/lib/posix/inotify.nim b/lib/posix/inotify.nim index c6f0633ff..14cac4d72 100644 --- a/lib/posix/inotify.nim +++ b/lib/posix/inotify.nim @@ -12,14 +12,15 @@ # Get the platform-dependent flags. # Structure describing an inotify event. type - Tinotify_event*{.pure, final, importc: "struct inotify_event", + InotifyEvent*{.pure, final, importc: "struct inotify_event", header: "".} = object wd*{.importc: "wd".}: cint # Watch descriptor. mask*{.importc: "mask".}: uint32 # Watch mask. cookie*{.importc: "cookie".}: uint32 # Cookie to synchronize two events. len*{.importc: "len".}: uint32 # Length (including NULs) of name. name*{.importc: "name".}: char # Name. - +{.deprecated: [Tinotify_event: InotifyEvent].} + # Supported events suitable for MASK parameter of INOTIFY_ADD_WATCH. const IN_ACCESS* = 0x00000001 # File was accessed. @@ -69,4 +70,4 @@ proc inotify_add_watch*(fd: cint; name: cstring; mask: uint32): cint{. cdecl, importc: "inotify_add_watch", header: "".} # Remove the watch specified by WD from the inotify instance FD. proc inotify_rm_watch*(fd: cint; wd: cint): cint{.cdecl, - importc: "inotify_rm_watch", header: "".} \ No newline at end of file + importc: "inotify_rm_watch", header: "".} diff --git a/lib/posix/linux.nim b/lib/posix/linux.nim index be591e29a..05eab52bc 100644 --- a/lib/posix/linux.nim +++ b/lib/posix/linux.nim @@ -24,5 +24,5 @@ const # fn should be of type proc (a2: pointer): void {.cdecl.} proc clone*(fn: pointer; child_stack: pointer; flags: cint; - arg: pointer; ptid: ptr TPid; tls: pointer; - ctid: ptr TPid): cint {.importc, header: "".} + arg: pointer; ptid: ptr Pid; tls: pointer; + ctid: ptr Pid): cint {.importc, header: "".} diff --git a/lib/posix/posix.nim b/lib/posix/posix.nim index 0c7b84090..dba79cbf6 100644 --- a/lib/posix/posix.nim +++ b/lib/posix/posix.nim @@ -81,9 +81,10 @@ const DT_WHT* = 14 type - TDIR* {.importc: "DIR", header: "", + DIR* {.importc: "DIR", header: "", incompleteStruct.} = object ## A type representing a directory stream. +{.deprecated: [TDIR: DIR].} type SocketHandle* = distinct cint # The type used to represent socket descriptors @@ -91,47 +92,47 @@ type {.deprecated: [TSocketHandle: SocketHandle].} type - Tdirent* {.importc: "struct dirent", + Dirent* {.importc: "struct dirent", header: "", final, pure.} = object ## dirent_t struct - d_ino*: Tino ## File serial number. + d_ino*: Ino ## File serial number. when defined(linux) or defined(macosx) or defined(bsd): d_reclen*: cshort ## Length of this record. (not POSIX) d_type*: int8 ## Type of file; not supported by all filesystem types. ## (not POSIX) when defined(linux) or defined(bsd): - d_off*: TOff ## Not an offset. Value that ``telldir()`` would return. + d_off*: Off ## Not an offset. Value that ``telldir()`` would return. d_name*: array [0..255, char] ## Name of entry. Tflock* {.importc: "struct flock", final, pure, header: "".} = object ## flock type l_type*: cshort ## Type of lock; F_RDLCK, F_WRLCK, F_UNLCK. l_whence*: cshort ## Flag for starting offset. - l_start*: TOff ## Relative offset in bytes. - l_len*: TOff ## Size; if 0 then until EOF. - l_pid*: TPid ## Process ID of the process holding the lock; + l_start*: Off ## Relative offset in bytes. + l_len*: Off ## Size; if 0 then until EOF. + l_pid*: Pid ## Process ID of the process holding the lock; ## returned with F_GETLK. - TFTW* {.importc: "struct FTW", header: "", final, pure.} = object + FTW* {.importc: "struct FTW", header: "", final, pure.} = object base*: cint level*: cint - TGlob* {.importc: "glob_t", header: "", + Glob* {.importc: "glob_t", header: "", final, pure.} = object ## glob_t gl_pathc*: int ## Count of paths matched by pattern. gl_pathv*: cstringArray ## Pointer to a list of matched pathnames. gl_offs*: int ## Slots to reserve at the beginning of gl_pathv. - TGroup* {.importc: "struct group", header: "", + Group* {.importc: "struct group", header: "", final, pure.} = object ## struct group gr_name*: cstring ## The name of the group. - gr_gid*: TGid ## Numerical group ID. + gr_gid*: Gid ## Numerical group ID. gr_mem*: cstringArray ## Pointer to a null-terminated array of character ## pointers to member names. - Ticonv* {.importc: "iconv_t", header: "", final, pure.} = + Iconv* {.importc: "iconv_t", header: "", final, pure.} = object ## Identifies the conversion from one codeset to another. - Tlconv* {.importc: "struct lconv", header: "", final, + Lconv* {.importc: "struct lconv", header: "", final, pure.} = object currency_symbol*: cstring decimal_point*: cstring @@ -158,8 +159,8 @@ type p_sign_posn*: char thousands_sep*: cstring - TMqd* {.importc: "mqd_t", header: "", final, pure.} = object - TMqAttr* {.importc: "struct mq_attr", + Mqd* {.importc: "mqd_t", header: "", final, pure.} = object + MqAttr* {.importc: "struct mq_attr", header: "", final, pure.} = object ## message queue attribute mq_flags*: int ## Message queue flags. @@ -167,64 +168,64 @@ type mq_msgsize*: int ## Maximum message size. mq_curmsgs*: int ## Number of messages currently queued. - TPasswd* {.importc: "struct passwd", header: "", + Passwd* {.importc: "struct passwd", header: "", final, pure.} = object ## struct passwd pw_name*: cstring ## User's login name. - pw_uid*: Tuid ## Numerical user ID. - pw_gid*: TGid ## Numerical group ID. + pw_uid*: Uid ## Numerical user ID. + pw_gid*: Gid ## Numerical group ID. pw_dir*: cstring ## Initial working directory. pw_shell*: cstring ## Program to use as shell. - Tblkcnt* {.importc: "blkcnt_t", header: "".} = int + Blkcnt* {.importc: "blkcnt_t", header: "".} = int ## used for file block counts - Tblksize* {.importc: "blksize_t", header: "".} = int + Blksize* {.importc: "blksize_t", header: "".} = int ## used for block sizes - TClock* {.importc: "clock_t", header: "".} = int - TClockId* {.importc: "clockid_t", header: "".} = int - TDev* {.importc: "dev_t", header: "".} = int - Tfsblkcnt* {.importc: "fsblkcnt_t", header: "".} = int - Tfsfilcnt* {.importc: "fsfilcnt_t", header: "".} = int - TGid* {.importc: "gid_t", header: "".} = int - Tid* {.importc: "id_t", header: "".} = int - Tino* {.importc: "ino_t", header: "".} = int - TKey* {.importc: "key_t", header: "".} = int - TMode* {.importc: "mode_t", header: "".} = cint - TNlink* {.importc: "nlink_t", header: "".} = int - TOff* {.importc: "off_t", header: "".} = int64 - TPid* {.importc: "pid_t", header: "".} = int - Tpthread_attr* {.importc: "pthread_attr_t", header: "".} = int - Tpthread_barrier* {.importc: "pthread_barrier_t", + Clock* {.importc: "clock_t", header: "".} = int + ClockId* {.importc: "clockid_t", header: "".} = int + Dev* {.importc: "dev_t", header: "".} = int + Fsblkcnt* {.importc: "fsblkcnt_t", header: "".} = int + Fsfilcnt* {.importc: "fsfilcnt_t", header: "".} = int + Gid* {.importc: "gid_t", header: "".} = int + Id* {.importc: "id_t", header: "".} = int + Ino* {.importc: "ino_t", header: "".} = int + Key* {.importc: "key_t", header: "".} = int + Mode* {.importc: "mode_t", header: "".} = cint + Nlink* {.importc: "nlink_t", header: "".} = int + Off* {.importc: "off_t", header: "".} = int64 + Pid* {.importc: "pid_t", header: "".} = int + Pthread_attr* {.importc: "pthread_attr_t", header: "".} = int + Pthread_barrier* {.importc: "pthread_barrier_t", header: "".} = int - Tpthread_barrierattr* {.importc: "pthread_barrierattr_t", + Pthread_barrierattr* {.importc: "pthread_barrierattr_t", header: "".} = int - Tpthread_cond* {.importc: "pthread_cond_t", header: "".} = int - Tpthread_condattr* {.importc: "pthread_condattr_t", + Pthread_cond* {.importc: "pthread_cond_t", header: "".} = int + Pthread_condattr* {.importc: "pthread_condattr_t", header: "".} = int - Tpthread_key* {.importc: "pthread_key_t", header: "".} = int - Tpthread_mutex* {.importc: "pthread_mutex_t", header: "".} = int - Tpthread_mutexattr* {.importc: "pthread_mutexattr_t", + Pthread_key* {.importc: "pthread_key_t", header: "".} = int + Pthread_mutex* {.importc: "pthread_mutex_t", header: "".} = int + Pthread_mutexattr* {.importc: "pthread_mutexattr_t", header: "".} = int - Tpthread_once* {.importc: "pthread_once_t", header: "".} = int - Tpthread_rwlock* {.importc: "pthread_rwlock_t", + Pthread_once* {.importc: "pthread_once_t", header: "".} = int + Pthread_rwlock* {.importc: "pthread_rwlock_t", header: "".} = int - Tpthread_rwlockattr* {.importc: "pthread_rwlockattr_t", + Pthread_rwlockattr* {.importc: "pthread_rwlockattr_t", header: "".} = int - Tpthread_spinlock* {.importc: "pthread_spinlock_t", + Pthread_spinlock* {.importc: "pthread_spinlock_t", header: "".} = int - Tpthread* {.importc: "pthread_t", header: "".} = int - Tsuseconds* {.importc: "suseconds_t", header: "".} = int + Pthread* {.importc: "pthread_t", header: "".} = int + Suseconds* {.importc: "suseconds_t", header: "".} = int #Ttime* {.importc: "time_t", header: "".} = int - Ttimer* {.importc: "timer_t", header: "".} = int - Ttrace_attr* {.importc: "trace_attr_t", header: "".} = int - Ttrace_event_id* {.importc: "trace_event_id_t", + Timer* {.importc: "timer_t", header: "".} = int + Trace_attr* {.importc: "trace_attr_t", header: "".} = int + Trace_event_id* {.importc: "trace_event_id_t", header: "".} = int - Ttrace_event_set* {.importc: "trace_event_set_t", + Trace_event_set* {.importc: "trace_event_set_t", header: "".} = int - Ttrace_id* {.importc: "trace_id_t", header: "".} = int - Tuid* {.importc: "uid_t", header: "".} = int - Tuseconds* {.importc: "useconds_t", header: "".} = int + Trace_id* {.importc: "trace_id_t", header: "".} = int + Uid* {.importc: "uid_t", header: "".} = int + Useconds* {.importc: "useconds_t", header: "".} = int - Tutsname* {.importc: "struct utsname", + Utsname* {.importc: "struct utsname", header: "", final, pure.} = object ## struct utsname sysname*, ## Name of this implementation of the operating system. @@ -235,25 +236,25 @@ type machine*: array [0..255, char] ## Name of the hardware type on which the ## system is running. - TSem* {.importc: "sem_t", header: "", final, pure.} = object - Tipc_perm* {.importc: "struct ipc_perm", + Sem* {.importc: "sem_t", header: "", final, pure.} = object + Ipc_perm* {.importc: "struct ipc_perm", header: "", final, pure.} = object ## struct ipc_perm - uid*: Tuid ## Owner's user ID. - gid*: TGid ## Owner's group ID. - cuid*: Tuid ## Creator's user ID. - cgid*: TGid ## Creator's group ID. - mode*: TMode ## Read/write permission. + uid*: Uid ## Owner's user ID. + gid*: Gid ## Owner's group ID. + cuid*: Uid ## Creator's user ID. + cgid*: Gid ## Creator's group ID. + mode*: Mode ## Read/write permission. - TStat* {.importc: "struct stat", + Stat* {.importc: "struct stat", header: "", final, pure.} = object ## struct stat - st_dev*: TDev ## Device ID of device containing file. - st_ino*: Tino ## File serial number. - st_mode*: TMode ## Mode of file (see below). - st_nlink*: TNlink ## Number of hard links to the file. - st_uid*: Tuid ## User ID of file. - st_gid*: TGid ## Group ID of file. - st_rdev*: TDev ## Device ID (if file is character or block special). - st_size*: TOff ## For regular files, the file size in bytes. + st_dev*: Dev ## Device ID of device containing file. + st_ino*: Ino ## File serial number. + st_mode*: Mode ## Mode of file (see below). + st_nlink*: Nlink ## Number of hard links to the file. + st_uid*: Uid ## User ID of file. + st_gid*: Gid ## Group ID of file. + st_rdev*: Dev ## Device ID (if file is character or block special). + st_size*: Off ## For regular files, the file size in bytes. ## For symbolic links, the length in bytes of the ## pathname contained in the symbolic link. ## For a shared memory object, the length in bytes. @@ -263,34 +264,34 @@ type st_atime*: Time ## Time of last access. st_mtime*: Time ## Time of last data modification. st_ctime*: Time ## Time of last status change. - st_blksize*: Tblksize ## A file system-specific preferred I/O block size + st_blksize*: Blksize ## A file system-specific preferred I/O block size ## for this object. In some file system types, this ## may vary from file to file. - st_blocks*: Tblkcnt ## Number of blocks allocated for this object. + st_blocks*: Blkcnt ## Number of blocks allocated for this object. - TStatvfs* {.importc: "struct statvfs", header: "", + Statvfs* {.importc: "struct statvfs", header: "", final, pure.} = object ## struct statvfs f_bsize*: int ## File system block size. f_frsize*: int ## Fundamental file system block size. - f_blocks*: Tfsblkcnt ## Total number of blocks on file system + f_blocks*: Fsblkcnt ## Total number of blocks on file system ## in units of f_frsize. - f_bfree*: Tfsblkcnt ## Total number of free blocks. - f_bavail*: Tfsblkcnt ## Number of free blocks available to + f_bfree*: Fsblkcnt ## Total number of free blocks. + f_bavail*: Fsblkcnt ## Number of free blocks available to ## non-privileged process. - f_files*: Tfsfilcnt ## Total number of file serial numbers. - f_ffree*: Tfsfilcnt ## Total number of free file serial numbers. - f_favail*: Tfsfilcnt ## Number of file serial numbers available to + f_files*: Fsfilcnt ## Total number of file serial numbers. + f_ffree*: Fsfilcnt ## Total number of free file serial numbers. + f_favail*: Fsfilcnt ## Number of file serial numbers available to ## non-privileged process. f_fsid*: int ## File system ID. f_flag*: int ## Bit mask of f_flag values. f_namemax*: int ## Maximum filename length. - Tposix_typed_mem_info* {.importc: "struct posix_typed_mem_info", + Posix_typed_mem_info* {.importc: "struct posix_typed_mem_info", header: "", final, pure.} = object posix_tmi_length*: int - Ttm* {.importc: "struct tm", header: "", + Tm* {.importc: "struct tm", header: "", final, pure.} = object ## struct tm tm_sec*: cint ## Seconds [0,60]. tm_min*: cint ## Minutes [0,59]. @@ -301,79 +302,79 @@ type tm_wday*: cint ## Day of week [0,6] (Sunday =0). tm_yday*: cint ## Day of year [0,365]. tm_isdst*: cint ## Daylight Savings flag. - Ttimespec* {.importc: "struct timespec", + Timespec* {.importc: "struct timespec", header: "", final, pure.} = object ## struct timespec tv_sec*: Time ## Seconds. tv_nsec*: int ## Nanoseconds. - titimerspec* {.importc: "struct itimerspec", header: "", + Itimerspec* {.importc: "struct itimerspec", header: "", final, pure.} = object ## struct itimerspec - it_interval*: Ttimespec ## Timer period. - it_value*: Ttimespec ## Timer expiration. + it_interval*: Timespec ## Timer period. + it_value*: Timespec ## Timer expiration. - Tsig_atomic* {.importc: "sig_atomic_t", header: "".} = cint + Sig_atomic* {.importc: "sig_atomic_t", header: "".} = cint ## Possibly volatile-qualified integer type of an object that can be ## accessed as an atomic entity, even in the presence of asynchronous ## interrupts. - Tsigset* {.importc: "sigset_t", header: "", final, pure.} = object + Sigset* {.importc: "sigset_t", header: "", final, pure.} = object - TsigEvent* {.importc: "struct sigevent", + SigEvent* {.importc: "struct sigevent", header: "", final, pure.} = object ## struct sigevent sigev_notify*: cint ## Notification type. sigev_signo*: cint ## Signal number. - sigev_value*: TsigVal ## Signal value. - sigev_notify_function*: proc (x: TsigVal) {.noconv.} ## Notification func. - sigev_notify_attributes*: ptr Tpthread_attr ## Notification attributes. + sigev_value*: SigVal ## Signal value. + sigev_notify_function*: proc (x: SigVal) {.noconv.} ## Notification func. + sigev_notify_attributes*: ptr PthreadAttr ## Notification attributes. - TsigVal* {.importc: "union sigval", + SigVal* {.importc: "union sigval", header: "", final, pure.} = object ## struct sigval sival_ptr*: pointer ## pointer signal value; ## integer signal value not defined! - TSigaction* {.importc: "struct sigaction", + Sigaction* {.importc: "struct sigaction", header: "", final, pure.} = object ## struct sigaction sa_handler*: proc (x: cint) {.noconv.} ## Pointer to a signal-catching ## function or one of the macros ## SIG_IGN or SIG_DFL. - sa_mask*: Tsigset ## Set of signals to be blocked during execution of + sa_mask*: Sigset ## Set of signals to be blocked during execution of ## the signal handling function. sa_flags*: cint ## Special flags. - sa_sigaction*: proc (x: cint, y: var TsigInfo, z: pointer) {.noconv.} + sa_sigaction*: proc (x: cint, y: var SigInfo, z: pointer) {.noconv.} - TStack* {.importc: "stack_t", + Stack* {.importc: "stack_t", header: "", final, pure.} = object ## stack_t ss_sp*: pointer ## Stack base or pointer. ss_size*: int ## Stack size. ss_flags*: cint ## Flags. - TSigStack* {.importc: "struct sigstack", + SigStack* {.importc: "struct sigstack", header: "", final, pure.} = object ## struct sigstack ss_onstack*: cint ## Non-zero when signal stack is in use. ss_sp*: pointer ## Signal stack pointer. - TsigInfo* {.importc: "siginfo_t", + SigInfo* {.importc: "siginfo_t", header: "", final, pure.} = object ## siginfo_t si_signo*: cint ## Signal number. si_code*: cint ## Signal code. si_errno*: cint ## If non-zero, an errno value associated with ## this signal, as defined in . - si_pid*: TPid ## Sending process ID. - si_uid*: Tuid ## Real user ID of sending process. + si_pid*: Pid ## Sending process ID. + si_uid*: Uid ## Real user ID of sending process. si_addr*: pointer ## Address of faulting instruction. si_status*: cint ## Exit value or signal. si_band*: int ## Band event for SIGPOLL. - si_value*: TsigVal ## Signal value. + si_value*: SigVal ## Signal value. - Tnl_item* {.importc: "nl_item", header: "".} = cint - Tnl_catd* {.importc: "nl_catd", header: "".} = cint + Nl_item* {.importc: "nl_item", header: "".} = cint + Nl_catd* {.importc: "nl_catd", header: "".} = cint - Tsched_param* {.importc: "struct sched_param", + Sched_param* {.importc: "struct sched_param", header: "", final, pure.} = object ## struct sched_param sched_priority*: cint sched_ss_low_priority*: cint ## Low scheduling priority for ## sporadic server. - sched_ss_repl_period*: Ttimespec ## Replenishment period for + sched_ss_repl_period*: Timespec ## Replenishment period for ## sporadic server. - sched_ss_init_budget*: Ttimespec ## Initial budget for sporadic server. + sched_ss_init_budget*: Timespec ## Initial budget for sporadic server. sched_ss_max_repl*: cint ## Maximum pending replenishments for ## sporadic server. @@ -383,28 +384,52 @@ type tv_usec*: int ## Microseconds. TFdSet* {.importc: "fd_set", header: "", final, pure.} = object - Tmcontext* {.importc: "mcontext_t", header: "", + Mcontext* {.importc: "mcontext_t", header: "", final, pure.} = object - Tucontext* {.importc: "ucontext_t", header: "", + Ucontext* {.importc: "ucontext_t", header: "", final, pure.} = object ## ucontext_t - uc_link*: ptr Tucontext ## Pointer to the context that is resumed + uc_link*: ptr Ucontext ## Pointer to the context that is resumed ## when this context returns. - uc_sigmask*: Tsigset ## The set of signals that are blocked when this + uc_sigmask*: Sigset ## The set of signals that are blocked when this ## context is active. - uc_stack*: TStack ## The stack used by this context. - uc_mcontext*: Tmcontext ## A machine-specific representation of the saved + uc_stack*: Stack ## The stack used by this context. + uc_mcontext*: Mcontext ## A machine-specific representation of the saved ## context. - +{.deprecated: [TOff: Off, TPid: Pid, TGid: Gid, TMode: Mode, TDev: Dev, + TNlink: Nlink, TStack: Stack, TGroup: Group, TMqd: Mqd, + TPasswd: Passwd, TClock: Clock, TClockId: ClockId, TKey: Key, + TSem: Sem, Tpthread_attr: PthreadAttr, Ttimespec: Timespec, + Tdirent: Dirent, TFTW: FTW, TGlob: Glob, + # Tflock: Flock, # Naming conflict if we drop the `T` + Ticonv: Iconv, Tlconv: Lconv, TMqAttr: MqAttr, Tblkcnt: Blkcnt, + Tblksize: Blksize, Tfsblkcnt: Fsblkcnt, Tfsfilcnt: Fsfilcnt, + Tid: Id, Tino: Ino, Tpthread_barrier: Pthread_barrier, + Tpthread_barrierattr: Pthread_barrierattr, Tpthread_cond: Pthread_cond, + TPthread_condattr: Pthread_condattr, Tpthread_key: Pthread_key, + Tpthread_mutex: Pthread_mutex, Tpthread_mutexattr: Pthread_mutexattr, + Tpthread_once: Pthread_once, Tpthread_rwlock: Pthread_rwlock, + Tpthread_rwlockattr: Pthread_rwlockattr, Tpthread_spinlock: Pthread_spinlock, + Tpthread: Pthread, Tsuseconds: Suseconds, Ttimer: Timer, + Ttrace_attr: Trace_attr, Ttrace_event_id: Trace_event_id, + Ttrace_event_set: Trace_event_set, Ttrace_id: Trace_id, + Tuid: Uid, Tuseconds: Useconds, Tutsname: Utsname, Tipc_perm: Ipc_perm, + TStat: Stat, TStatvfs: Statvfs, Tposix_typed_mem_info: Posix_typed_mem_info, + Ttm: Tm, titimerspec: Itimerspec, Tsig_atomic: Sig_atomic, Tsigset: Sigset, + TsigEvent: SigEvent, TsigVal: SigVal, TSigaction: Sigaction, + TSigStack: SigStack, TsigInfo: SigInfo, Tnl_item: Nl_item, + Tnl_catd: Nl_catd, Tsched_param: Sched_param, + # TFdSet: FdSet, # Naming conflict if we drop the `T` + Tmcontext: Mcontext, Tucontext: Ucontext].} when hasAioH: type Taiocb* {.importc: "struct aiocb", header: "", final, pure.} = object ## struct aiocb aio_fildes*: cint ## File descriptor. - aio_offset*: TOff ## File offset. + aio_offset*: Off ## File offset. aio_buf*: pointer ## Location of buffer. aio_nbytes*: int ## Length of transfer. aio_reqprio*: cint ## Request priority offset. - aio_sigevent*: TsigEvent ## Signal number and value. + aio_sigevent*: SigEvent ## Signal number and value. aio_lio_opcode: cint ## Operation to be performed. when hasSpawnH: @@ -434,7 +459,7 @@ type if_name*: cstring ## Null-terminated name of the interface. - TIOVec* {.importc: "struct iovec", pure, final, + IOVec* {.importc: "struct iovec", pure, final, header: "".} = object ## struct iovec iov_base*: pointer ## Base address of a memory region for input or output. iov_len*: int ## The size of the memory pointed to by iov_base. @@ -443,7 +468,7 @@ type header: "".} = object ## struct msghdr msg_name*: pointer ## Optional address. msg_namelen*: Socklen ## Size of address. - msg_iov*: ptr TIOVec ## Scatter/gather array. + msg_iov*: ptr IOVec ## Scatter/gather array. msg_iovlen*: cint ## Members in msg_iov. msg_control*: pointer ## Ancillary data; see below. msg_controllen*: Socklen ## Ancillary data buffer len. @@ -461,37 +486,37 @@ type l_onoff*: cint ## Indicates whether linger option is enabled. l_linger*: cint ## Linger time, in seconds. - TInPort* = int16 ## unsigned! - TInAddrScalar* = int32 ## unsigned! + InPort* = int16 ## unsigned! + InAddrScalar* = int32 ## unsigned! - TInAddrT* {.importc: "in_addr_t", pure, final, + InAddrT* {.importc: "in_addr_t", pure, final, header: "".} = int32 ## unsigned! InAddr* {.importc: "struct in_addr", pure, final, header: "".} = object ## struct in_addr - s_addr*: TInAddrScalar + s_addr*: InAddrScalar Sockaddr_in* {.importc: "struct sockaddr_in", pure, final, header: "".} = object ## struct sockaddr_in sin_family*: TSa_Family ## AF_INET. - sin_port*: TInPort ## Port number. + sin_port*: InPort ## Port number. sin_addr*: InAddr ## IP address. - TIn6Addr* {.importc: "struct in6_addr", pure, final, + In6Addr* {.importc: "struct in6_addr", pure, final, header: "".} = object ## struct in6_addr s6_addr*: array [0..15, char] Tsockaddr_in6* {.importc: "struct sockaddr_in6", pure, final, header: "".} = object ## struct sockaddr_in6 sin6_family*: TSa_Family ## AF_INET6. - sin6_port*: TInPort ## Port number. + sin6_port*: InPort ## Port number. sin6_flowinfo*: int32 ## IPv6 traffic class and flow information. - sin6_addr*: TIn6Addr ## IPv6 address. + sin6_addr*: In6Addr ## IPv6 address. sin6_scope_id*: int32 ## Set of interfaces for a scope. Tipv6_mreq* {.importc: "struct ipv6_mreq", pure, final, header: "".} = object ## struct ipv6_mreq - ipv6mr_multiaddr*: TIn6Addr ## IPv6 multicast address. + ipv6mr_multiaddr*: In6Addr ## IPv6 multicast address. ipv6mr_interface*: cint ## Interface index. Hostent* {.importc: "struct hostent", pure, final, @@ -516,7 +541,7 @@ type n_addrtype*: cint ## The address type of the network. n_net*: int32 ## The network number, in host byte order. - TProtoent* {.importc: "struct protoent", pure, final, + Protoent* {.importc: "struct protoent", pure, final, header: "".} = object ## struct protoent p_name*: cstring ## Official name of the protocol. p_aliases*: cstringArray ## A pointer to an array of pointers to @@ -557,7 +582,8 @@ type {.deprecated: [TSockaddr_in: Sockaddr_in, TAddrinfo: AddrInfo, TSockAddr: SockAddr, TSockLen: SockLen, TTimeval: Timeval, Thostent: Hostent, TServent: Servent, - TInAddr: InAddr].} + TInAddr: InAddr, TIOVec: IOVec, TInPort: InPort, TInAddrT: InAddrT, + TIn6Addr: In6Addr, TInAddrScalar: InAddrScalar, TProtoent: Protoent].} var errno* {.importc, header: "".}: cint ## error variable @@ -1629,9 +1655,9 @@ var IPPROTO_UDP* {.importc, header: "".}: cint ## User datagram protocol. - INADDR_ANY* {.importc, header: "".}: TInAddrScalar + INADDR_ANY* {.importc, header: "".}: InAddrScalar ## IPv4 local host address. - INADDR_BROADCAST* {.importc, header: "".}: TInAddrScalar + INADDR_BROADCAST* {.importc, header: "".}: InAddrScalar ## IPv4 broadcast address. INET_ADDRSTRLEN* {.importc, header: "".}: cint @@ -1766,11 +1792,11 @@ when hasAioH: proc aio_fsync*(a1: cint, a2: ptr Taiocb): cint {.importc, header: "".} proc aio_read*(a1: ptr Taiocb): cint {.importc, header: "".} proc aio_return*(a1: ptr Taiocb): int {.importc, header: "".} - proc aio_suspend*(a1: ptr ptr Taiocb, a2: cint, a3: ptr Ttimespec): cint {. + proc aio_suspend*(a1: ptr ptr Taiocb, a2: cint, a3: ptr Timespec): cint {. importc, header: "".} proc aio_write*(a1: ptr Taiocb): cint {.importc, header: "".} proc lio_listio*(a1: cint, a2: ptr ptr Taiocb, a3: cint, - a4: ptr TsigEvent): cint {.importc, header: "".} + a4: ptr SigEvent): cint {.importc, header: "".} # arpa/inet.h proc htonl*(a1: int32): int32 {.importc, header: "".} @@ -1778,7 +1804,7 @@ proc htons*(a1: int16): int16 {.importc, header: "".} proc ntohl*(a1: int32): int32 {.importc, header: "".} proc ntohs*(a1: int16): int16 {.importc, header: "".} -proc inet_addr*(a1: cstring): TInAddrT {.importc, header: "".} +proc inet_addr*(a1: cstring): InAddrT {.importc, header: "".} proc inet_ntoa*(a1: InAddr): cstring {.importc, header: "".} proc inet_ntop*(a1: cint, a2: pointer, a3: cstring, a4: int32): cstring {. importc, header: "".} @@ -1786,21 +1812,21 @@ proc inet_pton*(a1: cint, a2: cstring, a3: pointer): cint {. importc, header: "".} var - in6addr_any* {.importc, header: "".}: TIn6Addr - in6addr_loopback* {.importc, header: "".}: TIn6Addr + in6addr_any* {.importc, header: "".}: In6Addr + in6addr_loopback* {.importc, header: "".}: In6Addr -proc IN6ADDR_ANY_INIT* (): TIn6Addr {.importc, header: "".} -proc IN6ADDR_LOOPBACK_INIT* (): TIn6Addr {.importc, header: "".} +proc IN6ADDR_ANY_INIT* (): In6Addr {.importc, header: "".} +proc IN6ADDR_LOOPBACK_INIT* (): In6Addr {.importc, header: "".} # dirent.h -proc closedir*(a1: ptr TDIR): cint {.importc, header: "".} -proc opendir*(a1: cstring): ptr TDIR {.importc, header: "".} -proc readdir*(a1: ptr TDIR): ptr Tdirent {.importc, header: "".} -proc readdir_r*(a1: ptr TDIR, a2: ptr Tdirent, a3: ptr ptr Tdirent): cint {. +proc closedir*(a1: ptr DIR): cint {.importc, header: "".} +proc opendir*(a1: cstring): ptr DIR {.importc, header: "".} +proc readdir*(a1: ptr DIR): ptr Dirent {.importc, header: "".} +proc readdir_r*(a1: ptr DIR, a2: ptr Dirent, a3: ptr ptr Dirent): cint {. importc, header: "".} -proc rewinddir*(a1: ptr TDIR) {.importc, header: "".} -proc seekdir*(a1: ptr TDIR, a2: int) {.importc, header: "".} -proc telldir*(a1: ptr TDIR): int {.importc, header: "".} +proc rewinddir*(a1: ptr DIR) {.importc, header: "".} +proc seekdir*(a1: ptr DIR, a2: int) {.importc, header: "".} +proc telldir*(a1: ptr DIR): int {.importc, header: "".} # dlfcn.h proc dlclose*(a1: pointer): cint {.importc, header: "".} @@ -1808,12 +1834,12 @@ proc dlerror*(): cstring {.importc, header: "".} proc dlopen*(a1: cstring, a2: cint): pointer {.importc, header: "".} proc dlsym*(a1: pointer, a2: cstring): pointer {.importc, header: "".} -proc creat*(a1: cstring, a2: TMode): cint {.importc, header: "".} +proc creat*(a1: cstring, a2: Mode): cint {.importc, header: "".} proc fcntl*(a1: cint | SocketHandle, a2: cint): cint {.varargs, importc, header: "".} proc open*(a1: cstring, a2: cint): cint {.varargs, importc, header: "".} -proc posix_fadvise*(a1: cint, a2, a3: TOff, a4: cint): cint {. +proc posix_fadvise*(a1: cint, a2, a3: Off, a4: cint): cint {. importc, header: "".} -proc posix_fallocate*(a1: cint, a2, a3: TOff): cint {. +proc posix_fallocate*(a1: cint, a2, a3: Off): cint {. importc, header: "".} when not defined(haiku) and not defined(OpenBSD): @@ -1822,248 +1848,248 @@ when not defined(haiku) and not defined(OpenBSD): proc fnmatch*(a1, a2: cstring, a3: cint): cint {.importc, header: "".} proc ftw*(a1: cstring, - a2: proc (x1: cstring, x2: ptr TStat, x3: cint): cint {.noconv.}, + a2: proc (x1: cstring, x2: ptr Stat, x3: cint): cint {.noconv.}, a3: cint): cint {.importc, header: "".} proc nftw*(a1: cstring, - a2: proc (x1: cstring, x2: ptr TStat, - x3: cint, x4: ptr TFTW): cint {.noconv.}, + a2: proc (x1: cstring, x2: ptr Stat, + x3: cint, x4: ptr FTW): cint {.noconv.}, a3: cint, a4: cint): cint {.importc, header: "".} proc glob*(a1: cstring, a2: cint, a3: proc (x1: cstring, x2: cint): cint {.noconv.}, - a4: ptr TGlob): cint {.importc, header: "".} -proc globfree*(a1: ptr TGlob) {.importc, header: "".} + a4: ptr Glob): cint {.importc, header: "".} +proc globfree*(a1: ptr Glob) {.importc, header: "".} -proc getgrgid*(a1: TGid): ptr TGroup {.importc, header: "".} -proc getgrnam*(a1: cstring): ptr TGroup {.importc, header: "".} -proc getgrgid_r*(a1: TGid, a2: ptr TGroup, a3: cstring, a4: int, - a5: ptr ptr TGroup): cint {.importc, header: "".} -proc getgrnam_r*(a1: cstring, a2: ptr TGroup, a3: cstring, - a4: int, a5: ptr ptr TGroup): cint {. +proc getgrgid*(a1: Gid): ptr Group {.importc, header: "".} +proc getgrnam*(a1: cstring): ptr Group {.importc, header: "".} +proc getgrgid_r*(a1: Gid, a2: ptr Group, a3: cstring, a4: int, + a5: ptr ptr Group): cint {.importc, header: "".} +proc getgrnam_r*(a1: cstring, a2: ptr Group, a3: cstring, + a4: int, a5: ptr ptr Group): cint {. importc, header: "".} -proc getgrent*(): ptr TGroup {.importc, header: "".} +proc getgrent*(): ptr Group {.importc, header: "".} proc endgrent*() {.importc, header: "".} proc setgrent*() {.importc, header: "".} -proc iconv_open*(a1, a2: cstring): Ticonv {.importc, header: "".} -proc iconv*(a1: Ticonv, a2: var cstring, a3: var int, a4: var cstring, +proc iconv_open*(a1, a2: cstring): Iconv {.importc, header: "".} +proc iconv*(a1: Iconv, a2: var cstring, a3: var int, a4: var cstring, a5: var int): int {.importc, header: "".} -proc iconv_close*(a1: Ticonv): cint {.importc, header: "".} +proc iconv_close*(a1: Iconv): cint {.importc, header: "".} -proc nl_langinfo*(a1: Tnl_item): cstring {.importc, header: "".} +proc nl_langinfo*(a1: Nl_item): cstring {.importc, header: "".} proc basename*(a1: cstring): cstring {.importc, header: "".} proc dirname*(a1: cstring): cstring {.importc, header: "".} -proc localeconv*(): ptr Tlconv {.importc, header: "".} +proc localeconv*(): ptr Lconv {.importc, header: "".} proc setlocale*(a1: cint, a2: cstring): cstring {. importc, header: "".} proc strfmon*(a1: cstring, a2: int, a3: cstring): int {.varargs, importc, header: "".} -proc mq_close*(a1: TMqd): cint {.importc, header: "".} -proc mq_getattr*(a1: TMqd, a2: ptr TMqAttr): cint {. +proc mq_close*(a1: Mqd): cint {.importc, header: "".} +proc mq_getattr*(a1: Mqd, a2: ptr MqAttr): cint {. importc, header: "".} -proc mq_notify*(a1: TMqd, a2: ptr TsigEvent): cint {. +proc mq_notify*(a1: Mqd, a2: ptr SigEvent): cint {. importc, header: "".} -proc mq_open*(a1: cstring, a2: cint): TMqd {. +proc mq_open*(a1: cstring, a2: cint): Mqd {. varargs, importc, header: "".} -proc mq_receive*(a1: TMqd, a2: cstring, a3: int, a4: var int): int {. +proc mq_receive*(a1: Mqd, a2: cstring, a3: int, a4: var int): int {. importc, header: "".} -proc mq_send*(a1: TMqd, a2: cstring, a3: int, a4: int): cint {. +proc mq_send*(a1: Mqd, a2: cstring, a3: int, a4: int): cint {. importc, header: "".} -proc mq_setattr*(a1: TMqd, a2, a3: ptr TMqAttr): cint {. +proc mq_setattr*(a1: Mqd, a2, a3: ptr MqAttr): cint {. importc, header: "".} -proc mq_timedreceive*(a1: TMqd, a2: cstring, a3: int, a4: int, - a5: ptr Ttimespec): int {.importc, header: "".} -proc mq_timedsend*(a1: TMqd, a2: cstring, a3: int, a4: int, - a5: ptr Ttimespec): cint {.importc, header: "".} +proc mq_timedreceive*(a1: Mqd, a2: cstring, a3: int, a4: int, + a5: ptr Timespec): int {.importc, header: "".} +proc mq_timedsend*(a1: Mqd, a2: cstring, a3: int, a4: int, + a5: ptr Timespec): cint {.importc, header: "".} proc mq_unlink*(a1: cstring): cint {.importc, header: "".} -proc getpwnam*(a1: cstring): ptr TPasswd {.importc, header: "".} -proc getpwuid*(a1: Tuid): ptr TPasswd {.importc, header: "".} -proc getpwnam_r*(a1: cstring, a2: ptr TPasswd, a3: cstring, a4: int, - a5: ptr ptr TPasswd): cint {.importc, header: "".} -proc getpwuid_r*(a1: Tuid, a2: ptr TPasswd, a3: cstring, - a4: int, a5: ptr ptr TPasswd): cint {.importc, header: "".} +proc getpwnam*(a1: cstring): ptr Passwd {.importc, header: "".} +proc getpwuid*(a1: Uid): ptr Passwd {.importc, header: "".} +proc getpwnam_r*(a1: cstring, a2: ptr Passwd, a3: cstring, a4: int, + a5: ptr ptr Passwd): cint {.importc, header: "".} +proc getpwuid_r*(a1: Uid, a2: ptr Passwd, a3: cstring, + a4: int, a5: ptr ptr Passwd): cint {.importc, header: "".} proc endpwent*() {.importc, header: "".} -proc getpwent*(): ptr TPasswd {.importc, header: "".} +proc getpwent*(): ptr Passwd {.importc, header: "".} proc setpwent*() {.importc, header: "".} -proc uname*(a1: var Tutsname): cint {.importc, header: "".} +proc uname*(a1: var Utsname): cint {.importc, header: "".} proc pthread_atfork*(a1, a2, a3: proc () {.noconv.}): cint {. importc, header: "".} -proc pthread_attr_destroy*(a1: ptr Tpthread_attr): cint {. +proc pthread_attr_destroy*(a1: ptr PthreadAttr): cint {. importc, header: "".} -proc pthread_attr_getdetachstate*(a1: ptr Tpthread_attr, a2: cint): cint {. +proc pthread_attr_getdetachstate*(a1: ptr PthreadAttr, a2: cint): cint {. importc, header: "".} -proc pthread_attr_getguardsize*(a1: ptr Tpthread_attr, a2: var cint): cint {. +proc pthread_attr_getguardsize*(a1: ptr PthreadAttr, a2: var cint): cint {. importc, header: "".} -proc pthread_attr_getinheritsched*(a1: ptr Tpthread_attr, +proc pthread_attr_getinheritsched*(a1: ptr PthreadAttr, a2: var cint): cint {.importc, header: "".} -proc pthread_attr_getschedparam*(a1: ptr Tpthread_attr, - a2: ptr Tsched_param): cint {.importc, header: "".} -proc pthread_attr_getschedpolicy*(a1: ptr Tpthread_attr, +proc pthread_attr_getschedparam*(a1: ptr PthreadAttr, + a2: ptr Sched_param): cint {.importc, header: "".} +proc pthread_attr_getschedpolicy*(a1: ptr PthreadAttr, a2: var cint): cint {.importc, header: "".} -proc pthread_attr_getscope*(a1: ptr Tpthread_attr, +proc pthread_attr_getscope*(a1: ptr PthreadAttr, a2: var cint): cint {.importc, header: "".} -proc pthread_attr_getstack*(a1: ptr Tpthread_attr, +proc pthread_attr_getstack*(a1: ptr PthreadAttr, a2: var pointer, a3: var int): cint {.importc, header: "".} -proc pthread_attr_getstackaddr*(a1: ptr Tpthread_attr, +proc pthread_attr_getstackaddr*(a1: ptr PthreadAttr, a2: var pointer): cint {.importc, header: "".} -proc pthread_attr_getstacksize*(a1: ptr Tpthread_attr, +proc pthread_attr_getstacksize*(a1: ptr PthreadAttr, a2: var int): cint {.importc, header: "".} -proc pthread_attr_init*(a1: ptr Tpthread_attr): cint {. +proc pthread_attr_init*(a1: ptr PthreadAttr): cint {. importc, header: "".} -proc pthread_attr_setdetachstate*(a1: ptr Tpthread_attr, a2: cint): cint {. +proc pthread_attr_setdetachstate*(a1: ptr PthreadAttr, a2: cint): cint {. importc, header: "".} -proc pthread_attr_setguardsize*(a1: ptr Tpthread_attr, a2: int): cint {. +proc pthread_attr_setguardsize*(a1: ptr PthreadAttr, a2: int): cint {. importc, header: "".} -proc pthread_attr_setinheritsched*(a1: ptr Tpthread_attr, a2: cint): cint {. +proc pthread_attr_setinheritsched*(a1: ptr PthreadAttr, a2: cint): cint {. importc, header: "".} -proc pthread_attr_setschedparam*(a1: ptr Tpthread_attr, - a2: ptr Tsched_param): cint {.importc, header: "".} -proc pthread_attr_setschedpolicy*(a1: ptr Tpthread_attr, a2: cint): cint {. +proc pthread_attr_setschedparam*(a1: ptr PthreadAttr, + a2: ptr Sched_param): cint {.importc, header: "".} +proc pthread_attr_setschedpolicy*(a1: ptr PthreadAttr, a2: cint): cint {. importc, header: "".} -proc pthread_attr_setscope*(a1: ptr Tpthread_attr, a2: cint): cint {.importc, +proc pthread_attr_setscope*(a1: ptr PthreadAttr, a2: cint): cint {.importc, header: "".} -proc pthread_attr_setstack*(a1: ptr Tpthread_attr, a2: pointer, a3: int): cint {. +proc pthread_attr_setstack*(a1: ptr PthreadAttr, a2: pointer, a3: int): cint {. importc, header: "".} -proc pthread_attr_setstackaddr*(a1: ptr Tpthread_attr, a2: pointer): cint {. +proc pthread_attr_setstackaddr*(a1: ptr PthreadAttr, a2: pointer): cint {. importc, header: "".} -proc pthread_attr_setstacksize*(a1: ptr Tpthread_attr, a2: int): cint {. +proc pthread_attr_setstacksize*(a1: ptr PthreadAttr, a2: int): cint {. importc, header: "".} -proc pthread_barrier_destroy*(a1: ptr Tpthread_barrier): cint {. +proc pthread_barrier_destroy*(a1: ptr Pthread_barrier): cint {. importc, header: "".} -proc pthread_barrier_init*(a1: ptr Tpthread_barrier, - a2: ptr Tpthread_barrierattr, a3: cint): cint {. +proc pthread_barrier_init*(a1: ptr Pthread_barrier, + a2: ptr Pthread_barrierattr, a3: cint): cint {. importc, header: "".} -proc pthread_barrier_wait*(a1: ptr Tpthread_barrier): cint {. +proc pthread_barrier_wait*(a1: ptr Pthread_barrier): cint {. importc, header: "".} -proc pthread_barrierattr_destroy*(a1: ptr Tpthread_barrierattr): cint {. +proc pthread_barrierattr_destroy*(a1: ptr Pthread_barrierattr): cint {. importc, header: "".} proc pthread_barrierattr_getpshared*( - a1: ptr Tpthread_barrierattr, a2: var cint): cint {. + a1: ptr Pthread_barrierattr, a2: var cint): cint {. importc, header: "".} -proc pthread_barrierattr_init*(a1: ptr Tpthread_barrierattr): cint {. +proc pthread_barrierattr_init*(a1: ptr Pthread_barrierattr): cint {. importc, header: "".} -proc pthread_barrierattr_setpshared*(a1: ptr Tpthread_barrierattr, +proc pthread_barrierattr_setpshared*(a1: ptr Pthread_barrierattr, a2: cint): cint {.importc, header: "".} -proc pthread_cancel*(a1: Tpthread): cint {.importc, header: "".} +proc pthread_cancel*(a1: Pthread): cint {.importc, header: "".} proc pthread_cleanup_push*(a1: proc (x: pointer) {.noconv.}, a2: pointer) {. importc, header: "".} proc pthread_cleanup_pop*(a1: cint) {.importc, header: "".} -proc pthread_cond_broadcast*(a1: ptr Tpthread_cond): cint {. +proc pthread_cond_broadcast*(a1: ptr Pthread_cond): cint {. importc, header: "".} -proc pthread_cond_destroy*(a1: ptr Tpthread_cond): cint {.importc, header: "".} -proc pthread_cond_init*(a1: ptr Tpthread_cond, - a2: ptr Tpthread_condattr): cint {.importc, header: "".} -proc pthread_cond_signal*(a1: ptr Tpthread_cond): cint {.importc, header: "".} -proc pthread_cond_timedwait*(a1: ptr Tpthread_cond, - a2: ptr Tpthread_mutex, a3: ptr Ttimespec): cint {.importc, header: "".} +proc pthread_cond_destroy*(a1: ptr Pthread_cond): cint {.importc, header: "".} +proc pthread_cond_init*(a1: ptr Pthread_cond, + a2: ptr Pthread_condattr): cint {.importc, header: "".} +proc pthread_cond_signal*(a1: ptr Pthread_cond): cint {.importc, header: "".} +proc pthread_cond_timedwait*(a1: ptr Pthread_cond, + a2: ptr Pthread_mutex, a3: ptr Timespec): cint {.importc, header: "".} -proc pthread_cond_wait*(a1: ptr Tpthread_cond, - a2: ptr Tpthread_mutex): cint {.importc, header: "".} -proc pthread_condattr_destroy*(a1: ptr Tpthread_condattr): cint {.importc, header: "".} -proc pthread_condattr_getclock*(a1: ptr Tpthread_condattr, - a2: var TClockId): cint {.importc, header: "".} -proc pthread_condattr_getpshared*(a1: ptr Tpthread_condattr, +proc pthread_cond_wait*(a1: ptr Pthread_cond, + a2: ptr Pthread_mutex): cint {.importc, header: "".} +proc pthread_condattr_destroy*(a1: ptr Pthread_condattr): cint {.importc, header: "".} +proc pthread_condattr_getclock*(a1: ptr Pthread_condattr, + a2: var ClockId): cint {.importc, header: "".} +proc pthread_condattr_getpshared*(a1: ptr Pthread_condattr, a2: var cint): cint {.importc, header: "".} -proc pthread_condattr_init*(a1: ptr Tpthread_condattr): cint {.importc, header: "".} -proc pthread_condattr_setclock*(a1: ptr Tpthread_condattr,a2: TClockId): cint {.importc, header: "".} -proc pthread_condattr_setpshared*(a1: ptr Tpthread_condattr, a2: cint): cint {.importc, header: "".} +proc pthread_condattr_init*(a1: ptr Pthread_condattr): cint {.importc, header: "".} +proc pthread_condattr_setclock*(a1: ptr Pthread_condattr,a2: ClockId): cint {.importc, header: "".} +proc pthread_condattr_setpshared*(a1: ptr Pthread_condattr, a2: cint): cint {.importc, header: "".} -proc pthread_create*(a1: ptr Tpthread, a2: ptr Tpthread_attr, +proc pthread_create*(a1: ptr Pthread, a2: ptr PthreadAttr, a3: proc (x: pointer): pointer {.noconv.}, a4: pointer): cint {.importc, header: "".} -proc pthread_detach*(a1: Tpthread): cint {.importc, header: "".} -proc pthread_equal*(a1, a2: Tpthread): cint {.importc, header: "".} +proc pthread_detach*(a1: Pthread): cint {.importc, header: "".} +proc pthread_equal*(a1, a2: Pthread): cint {.importc, header: "".} proc pthread_exit*(a1: pointer) {.importc, header: "".} proc pthread_getconcurrency*(): cint {.importc, header: "".} -proc pthread_getcpuclockid*(a1: Tpthread, a2: var TClockId): cint {.importc, header: "".} -proc pthread_getschedparam*(a1: Tpthread, a2: var cint, - a3: ptr Tsched_param): cint {.importc, header: "".} -proc pthread_getspecific*(a1: Tpthread_key): pointer {.importc, header: "".} -proc pthread_join*(a1: Tpthread, a2: ptr pointer): cint {.importc, header: "".} -proc pthread_key_create*(a1: ptr Tpthread_key, a2: proc (x: pointer) {.noconv.}): cint {.importc, header: "".} -proc pthread_key_delete*(a1: Tpthread_key): cint {.importc, header: "".} +proc pthread_getcpuclockid*(a1: Pthread, a2: var ClockId): cint {.importc, header: "".} +proc pthread_getschedparam*(a1: Pthread, a2: var cint, + a3: ptr Sched_param): cint {.importc, header: "".} +proc pthread_getspecific*(a1: Pthread_key): pointer {.importc, header: "".} +proc pthread_join*(a1: Pthread, a2: ptr pointer): cint {.importc, header: "".} +proc pthread_key_create*(a1: ptr Pthread_key, a2: proc (x: pointer) {.noconv.}): cint {.importc, header: "".} +proc pthread_key_delete*(a1: Pthread_key): cint {.importc, header: "".} -proc pthread_mutex_destroy*(a1: ptr Tpthread_mutex): cint {.importc, header: "".} -proc pthread_mutex_getprioceiling*(a1: ptr Tpthread_mutex, +proc pthread_mutex_destroy*(a1: ptr Pthread_mutex): cint {.importc, header: "".} +proc pthread_mutex_getprioceiling*(a1: ptr Pthread_mutex, a2: var cint): cint {.importc, header: "".} -proc pthread_mutex_init*(a1: ptr Tpthread_mutex, - a2: ptr Tpthread_mutexattr): cint {.importc, header: "".} -proc pthread_mutex_lock*(a1: ptr Tpthread_mutex): cint {.importc, header: "".} -proc pthread_mutex_setprioceiling*(a1: ptr Tpthread_mutex,a2: cint, +proc pthread_mutex_init*(a1: ptr Pthread_mutex, + a2: ptr Pthread_mutexattr): cint {.importc, header: "".} +proc pthread_mutex_lock*(a1: ptr Pthread_mutex): cint {.importc, header: "".} +proc pthread_mutex_setprioceiling*(a1: ptr Pthread_mutex,a2: cint, a3: var cint): cint {.importc, header: "".} -proc pthread_mutex_timedlock*(a1: ptr Tpthread_mutex, - a2: ptr Ttimespec): cint {.importc, header: "".} -proc pthread_mutex_trylock*(a1: ptr Tpthread_mutex): cint {.importc, header: "".} -proc pthread_mutex_unlock*(a1: ptr Tpthread_mutex): cint {.importc, header: "".} -proc pthread_mutexattr_destroy*(a1: ptr Tpthread_mutexattr): cint {.importc, header: "".} +proc pthread_mutex_timedlock*(a1: ptr Pthread_mutex, + a2: ptr Timespec): cint {.importc, header: "".} +proc pthread_mutex_trylock*(a1: ptr Pthread_mutex): cint {.importc, header: "".} +proc pthread_mutex_unlock*(a1: ptr Pthread_mutex): cint {.importc, header: "".} +proc pthread_mutexattr_destroy*(a1: ptr Pthread_mutexattr): cint {.importc, header: "".} proc pthread_mutexattr_getprioceiling*( - a1: ptr Tpthread_mutexattr, a2: var cint): cint {.importc, header: "".} -proc pthread_mutexattr_getprotocol*(a1: ptr Tpthread_mutexattr, + a1: ptr Pthread_mutexattr, a2: var cint): cint {.importc, header: "".} +proc pthread_mutexattr_getprotocol*(a1: ptr Pthread_mutexattr, a2: var cint): cint {.importc, header: "".} -proc pthread_mutexattr_getpshared*(a1: ptr Tpthread_mutexattr, +proc pthread_mutexattr_getpshared*(a1: ptr Pthread_mutexattr, a2: var cint): cint {.importc, header: "".} -proc pthread_mutexattr_gettype*(a1: ptr Tpthread_mutexattr, +proc pthread_mutexattr_gettype*(a1: ptr Pthread_mutexattr, a2: var cint): cint {.importc, header: "".} -proc pthread_mutexattr_init*(a1: ptr Tpthread_mutexattr): cint {.importc, header: "".} -proc pthread_mutexattr_setprioceiling*(a1: ptr Tpthread_mutexattr, a2: cint): cint {.importc, header: "".} -proc pthread_mutexattr_setprotocol*(a1: ptr Tpthread_mutexattr, a2: cint): cint {.importc, header: "".} -proc pthread_mutexattr_setpshared*(a1: ptr Tpthread_mutexattr, a2: cint): cint {.importc, header: "".} -proc pthread_mutexattr_settype*(a1: ptr Tpthread_mutexattr, a2: cint): cint {.importc, header: "".} +proc pthread_mutexattr_init*(a1: ptr Pthread_mutexattr): cint {.importc, header: "".} +proc pthread_mutexattr_setprioceiling*(a1: ptr Pthread_mutexattr, a2: cint): cint {.importc, header: "".} +proc pthread_mutexattr_setprotocol*(a1: ptr Pthread_mutexattr, a2: cint): cint {.importc, header: "".} +proc pthread_mutexattr_setpshared*(a1: ptr Pthread_mutexattr, a2: cint): cint {.importc, header: "".} +proc pthread_mutexattr_settype*(a1: ptr Pthread_mutexattr, a2: cint): cint {.importc, header: "".} -proc pthread_once*(a1: ptr Tpthread_once, a2: proc () {.noconv.}): cint {.importc, header: "".} +proc pthread_once*(a1: ptr Pthread_once, a2: proc () {.noconv.}): cint {.importc, header: "".} -proc pthread_rwlock_destroy*(a1: ptr Tpthread_rwlock): cint {.importc, header: "".} -proc pthread_rwlock_init*(a1: ptr Tpthread_rwlock, - a2: ptr Tpthread_rwlockattr): cint {.importc, header: "".} -proc pthread_rwlock_rdlock*(a1: ptr Tpthread_rwlock): cint {.importc, header: "".} -proc pthread_rwlock_timedrdlock*(a1: ptr Tpthread_rwlock, - a2: ptr Ttimespec): cint {.importc, header: "".} -proc pthread_rwlock_timedwrlock*(a1: ptr Tpthread_rwlock, - a2: ptr Ttimespec): cint {.importc, header: "".} +proc pthread_rwlock_destroy*(a1: ptr Pthread_rwlock): cint {.importc, header: "".} +proc pthread_rwlock_init*(a1: ptr Pthread_rwlock, + a2: ptr Pthread_rwlockattr): cint {.importc, header: "".} +proc pthread_rwlock_rdlock*(a1: ptr Pthread_rwlock): cint {.importc, header: "".} +proc pthread_rwlock_timedrdlock*(a1: ptr Pthread_rwlock, + a2: ptr Timespec): cint {.importc, header: "".} +proc pthread_rwlock_timedwrlock*(a1: ptr Pthread_rwlock, + a2: ptr Timespec): cint {.importc, header: "".} -proc pthread_rwlock_tryrdlock*(a1: ptr Tpthread_rwlock): cint {.importc, header: "".} -proc pthread_rwlock_trywrlock*(a1: ptr Tpthread_rwlock): cint {.importc, header: "".} -proc pthread_rwlock_unlock*(a1: ptr Tpthread_rwlock): cint {.importc, header: "".} -proc pthread_rwlock_wrlock*(a1: ptr Tpthread_rwlock): cint {.importc, header: "".} -proc pthread_rwlockattr_destroy*(a1: ptr Tpthread_rwlockattr): cint {.importc, header: "".} +proc pthread_rwlock_tryrdlock*(a1: ptr Pthread_rwlock): cint {.importc, header: "".} +proc pthread_rwlock_trywrlock*(a1: ptr Pthread_rwlock): cint {.importc, header: "".} +proc pthread_rwlock_unlock*(a1: ptr Pthread_rwlock): cint {.importc, header: "".} +proc pthread_rwlock_wrlock*(a1: ptr Pthread_rwlock): cint {.importc, header: "".} +proc pthread_rwlockattr_destroy*(a1: ptr Pthread_rwlockattr): cint {.importc, header: "".} proc pthread_rwlockattr_getpshared*( - a1: ptr Tpthread_rwlockattr, a2: var cint): cint {.importc, header: "".} -proc pthread_rwlockattr_init*(a1: ptr Tpthread_rwlockattr): cint {.importc, header: "".} -proc pthread_rwlockattr_setpshared*(a1: ptr Tpthread_rwlockattr, a2: cint): cint {.importc, header: "".} + a1: ptr Pthread_rwlockattr, a2: var cint): cint {.importc, header: "".} +proc pthread_rwlockattr_init*(a1: ptr Pthread_rwlockattr): cint {.importc, header: "".} +proc pthread_rwlockattr_setpshared*(a1: ptr Pthread_rwlockattr, a2: cint): cint {.importc, header: "".} -proc pthread_self*(): Tpthread {.importc, header: "".} +proc pthread_self*(): Pthread {.importc, header: "".} proc pthread_setcancelstate*(a1: cint, a2: var cint): cint {.importc, header: "".} proc pthread_setcanceltype*(a1: cint, a2: var cint): cint {.importc, header: "".} proc pthread_setconcurrency*(a1: cint): cint {.importc, header: "".} -proc pthread_setschedparam*(a1: Tpthread, a2: cint, - a3: ptr Tsched_param): cint {.importc, header: "".} +proc pthread_setschedparam*(a1: Pthread, a2: cint, + a3: ptr Sched_param): cint {.importc, header: "".} -proc pthread_setschedprio*(a1: Tpthread, a2: cint): cint {. +proc pthread_setschedprio*(a1: Pthread, a2: cint): cint {. importc, header: "".} -proc pthread_setspecific*(a1: Tpthread_key, a2: pointer): cint {. +proc pthread_setspecific*(a1: Pthread_key, a2: pointer): cint {. importc, header: "".} -proc pthread_spin_destroy*(a1: ptr Tpthread_spinlock): cint {. +proc pthread_spin_destroy*(a1: ptr Pthread_spinlock): cint {. importc, header: "".} -proc pthread_spin_init*(a1: ptr Tpthread_spinlock, a2: cint): cint {. +proc pthread_spin_init*(a1: ptr Pthread_spinlock, a2: cint): cint {. importc, header: "".} -proc pthread_spin_lock*(a1: ptr Tpthread_spinlock): cint {. +proc pthread_spin_lock*(a1: ptr Pthread_spinlock): cint {. importc, header: "".} -proc pthread_spin_trylock*(a1: ptr Tpthread_spinlock): cint{. +proc pthread_spin_trylock*(a1: ptr Pthread_spinlock): cint{. importc, header: "".} -proc pthread_spin_unlock*(a1: ptr Tpthread_spinlock): cint {. +proc pthread_spin_unlock*(a1: ptr Pthread_spinlock): cint {. importc, header: "".} proc pthread_testcancel*() {.importc, header: "".} @@ -2072,7 +2098,7 @@ proc exitnow*(code: int): void {.importc: "_exit", header: "".} proc access*(a1: cstring, a2: cint): cint {.importc, header: "".} proc alarm*(a1: cint): cint {.importc, header: "".} proc chdir*(a1: cstring): cint {.importc, header: "".} -proc chown*(a1: cstring, a2: Tuid, a3: TGid): cint {.importc, header: "".} +proc chown*(a1: cstring, a2: Uid, a3: Gid): cint {.importc, header: "".} proc close*(a1: cint | SocketHandle): cint {.importc, header: "".} proc confstr*(a1: cint, a2: cstring, a3: int): int {.importc, header: "".} proc crypt*(a1, a2: cstring): cstring {.importc, header: "".} @@ -2089,19 +2115,19 @@ proc execve*(a1: cstring, a2, a3: cstringArray): cint {. importc, header: "".} proc execvp*(a1: cstring, a2: cstringArray): cint {.importc, header: "".} proc execvpe*(a1: cstring, a2: cstringArray, a3: cstringArray): cint {.importc, header: "".} -proc fchown*(a1: cint, a2: Tuid, a3: TGid): cint {.importc, header: "".} +proc fchown*(a1: cint, a2: Uid, a3: Gid): cint {.importc, header: "".} proc fchdir*(a1: cint): cint {.importc, header: "".} proc fdatasync*(a1: cint): cint {.importc, header: "".} -proc fork*(): TPid {.importc, header: "".} +proc fork*(): Pid {.importc, header: "".} proc fpathconf*(a1, a2: cint): int {.importc, header: "".} proc fsync*(a1: cint): cint {.importc, header: "".} -proc ftruncate*(a1: cint, a2: TOff): cint {.importc, header: "".} +proc ftruncate*(a1: cint, a2: Off): cint {.importc, header: "".} proc getcwd*(a1: cstring, a2: int): cstring {.importc, header: "".} -proc getegid*(): TGid {.importc, header: "".} -proc geteuid*(): Tuid {.importc, header: "".} -proc getgid*(): TGid {.importc, header: "".} +proc getegid*(): Gid {.importc, header: "".} +proc geteuid*(): Uid {.importc, header: "".} +proc getgid*(): Gid {.importc, header: "".} -proc getgroups*(a1: cint, a2: ptr array[0..255, TGid]): cint {. +proc getgroups*(a1: cint, a2: ptr array[0..255, Gid]): cint {. importc, header: "".} proc gethostid*(): int {.importc, header: "".} proc gethostname*(a1: cstring, a2: int): cint {.importc, header: "".} @@ -2110,120 +2136,120 @@ proc getlogin_r*(a1: cstring, a2: int): cint {.importc, header: "".} proc getopt*(a1: cint, a2: cstringArray, a3: cstring): cint {. importc, header: "".} -proc getpgid*(a1: TPid): TPid {.importc, header: "".} -proc getpgrp*(): TPid {.importc, header: "".} -proc getpid*(): TPid {.importc, header: "".} -proc getppid*(): TPid {.importc, header: "".} -proc getsid*(a1: TPid): TPid {.importc, header: "".} -proc getuid*(): Tuid {.importc, header: "".} +proc getpgid*(a1: Pid): Pid {.importc, header: "".} +proc getpgrp*(): Pid {.importc, header: "".} +proc getpid*(): Pid {.importc, header: "".} +proc getppid*(): Pid {.importc, header: "".} +proc getsid*(a1: Pid): Pid {.importc, header: "".} +proc getuid*(): Uid {.importc, header: "".} proc getwd*(a1: cstring): cstring {.importc, header: "".} proc isatty*(a1: cint): cint {.importc, header: "".} -proc lchown*(a1: cstring, a2: Tuid, a3: TGid): cint {.importc, header: "".} +proc lchown*(a1: cstring, a2: Uid, a3: Gid): cint {.importc, header: "".} proc link*(a1, a2: cstring): cint {.importc, header: "".} -proc lockf*(a1, a2: cint, a3: TOff): cint {.importc, header: "".} -proc lseek*(a1: cint, a2: TOff, a3: cint): TOff {.importc, header: "".} +proc lockf*(a1, a2: cint, a3: Off): cint {.importc, header: "".} +proc lseek*(a1: cint, a2: Off, a3: cint): Off {.importc, header: "".} proc nice*(a1: cint): cint {.importc, header: "".} proc pathconf*(a1: cstring, a2: cint): int {.importc, header: "".} proc pause*(): cint {.importc, header: "".} proc pipe*(a: array[0..1, cint]): cint {.importc, header: "".} -proc pread*(a1: cint, a2: pointer, a3: int, a4: TOff): int {. +proc pread*(a1: cint, a2: pointer, a3: int, a4: Off): int {. importc, header: "".} -proc pwrite*(a1: cint, a2: pointer, a3: int, a4: TOff): int {. +proc pwrite*(a1: cint, a2: pointer, a3: int, a4: Off): int {. importc, header: "".} proc read*(a1: cint, a2: pointer, a3: int): int {.importc, header: "".} proc readlink*(a1, a2: cstring, a3: int): int {.importc, header: "".} proc rmdir*(a1: cstring): cint {.importc, header: "".} -proc setegid*(a1: TGid): cint {.importc, header: "".} -proc seteuid*(a1: Tuid): cint {.importc, header: "".} -proc setgid*(a1: TGid): cint {.importc, header: "".} +proc setegid*(a1: Gid): cint {.importc, header: "".} +proc seteuid*(a1: Uid): cint {.importc, header: "".} +proc setgid*(a1: Gid): cint {.importc, header: "".} -proc setpgid*(a1, a2: TPid): cint {.importc, header: "".} -proc setpgrp*(): TPid {.importc, header: "".} -proc setregid*(a1, a2: TGid): cint {.importc, header: "".} -proc setreuid*(a1, a2: Tuid): cint {.importc, header: "".} -proc setsid*(): TPid {.importc, header: "".} -proc setuid*(a1: Tuid): cint {.importc, header: "".} +proc setpgid*(a1, a2: Pid): cint {.importc, header: "".} +proc setpgrp*(): Pid {.importc, header: "".} +proc setregid*(a1, a2: Gid): cint {.importc, header: "".} +proc setreuid*(a1, a2: Uid): cint {.importc, header: "".} +proc setsid*(): Pid {.importc, header: "".} +proc setuid*(a1: Uid): cint {.importc, header: "".} proc sleep*(a1: cint): cint {.importc, header: "".} proc swab*(a1, a2: pointer, a3: int) {.importc, header: "".} proc symlink*(a1, a2: cstring): cint {.importc, header: "".} proc sync*() {.importc, header: "".} proc sysconf*(a1: cint): int {.importc, header: "".} -proc tcgetpgrp*(a1: cint): TPid {.importc, header: "".} -proc tcsetpgrp*(a1: cint, a2: TPid): cint {.importc, header: "".} -proc truncate*(a1: cstring, a2: TOff): cint {.importc, header: "".} +proc tcgetpgrp*(a1: cint): Pid {.importc, header: "".} +proc tcsetpgrp*(a1: cint, a2: Pid): cint {.importc, header: "".} +proc truncate*(a1: cstring, a2: Off): cint {.importc, header: "".} proc ttyname*(a1: cint): cstring {.importc, header: "".} proc ttyname_r*(a1: cint, a2: cstring, a3: int): cint {. importc, header: "".} -proc ualarm*(a1, a2: Tuseconds): Tuseconds {.importc, header: "".} +proc ualarm*(a1, a2: Useconds): Useconds {.importc, header: "".} proc unlink*(a1: cstring): cint {.importc, header: "".} -proc usleep*(a1: Tuseconds): cint {.importc, header: "".} -proc vfork*(): TPid {.importc, header: "".} +proc usleep*(a1: Useconds): cint {.importc, header: "".} +proc vfork*(): Pid {.importc, header: "".} proc write*(a1: cint, a2: pointer, a3: int): int {.importc, header: "".} -proc sem_close*(a1: ptr TSem): cint {.importc, header: "".} -proc sem_destroy*(a1: ptr TSem): cint {.importc, header: "".} -proc sem_getvalue*(a1: ptr TSem, a2: var cint): cint {. +proc sem_close*(a1: ptr Sem): cint {.importc, header: "".} +proc sem_destroy*(a1: ptr Sem): cint {.importc, header: "".} +proc sem_getvalue*(a1: ptr Sem, a2: var cint): cint {. importc, header: "".} -proc sem_init*(a1: ptr TSem, a2: cint, a3: cint): cint {. +proc sem_init*(a1: ptr Sem, a2: cint, a3: cint): cint {. importc, header: "".} -proc sem_open*(a1: cstring, a2: cint): ptr TSem {. +proc sem_open*(a1: cstring, a2: cint): ptr Sem {. varargs, importc, header: "".} -proc sem_post*(a1: ptr TSem): cint {.importc, header: "".} -proc sem_timedwait*(a1: ptr TSem, a2: ptr Ttimespec): cint {. +proc sem_post*(a1: ptr Sem): cint {.importc, header: "".} +proc sem_timedwait*(a1: ptr Sem, a2: ptr Timespec): cint {. importc, header: "".} -proc sem_trywait*(a1: ptr TSem): cint {.importc, header: "".} +proc sem_trywait*(a1: ptr Sem): cint {.importc, header: "".} proc sem_unlink*(a1: cstring): cint {.importc, header: "".} -proc sem_wait*(a1: ptr TSem): cint {.importc, header: "".} +proc sem_wait*(a1: ptr Sem): cint {.importc, header: "".} -proc ftok*(a1: cstring, a2: cint): TKey {.importc, header: "".} +proc ftok*(a1: cstring, a2: cint): Key {.importc, header: "".} -proc statvfs*(a1: cstring, a2: var TStatvfs): cint {. +proc statvfs*(a1: cstring, a2: var Statvfs): cint {. importc, header: "".} -proc fstatvfs*(a1: cint, a2: var TStatvfs): cint {. +proc fstatvfs*(a1: cint, a2: var Statvfs): cint {. importc, header: "".} -proc chmod*(a1: cstring, a2: TMode): cint {.importc, header: "".} -proc fchmod*(a1: cint, a2: TMode): cint {.importc, header: "".} -proc fstat*(a1: cint, a2: var TStat): cint {.importc, header: "".} -proc lstat*(a1: cstring, a2: var TStat): cint {.importc, header: "".} -proc mkdir*(a1: cstring, a2: TMode): cint {.importc, header: "".} -proc mkfifo*(a1: cstring, a2: TMode): cint {.importc, header: "".} -proc mknod*(a1: cstring, a2: TMode, a3: TDev): cint {. +proc chmod*(a1: cstring, a2: Mode): cint {.importc, header: "".} +proc fchmod*(a1: cint, a2: Mode): cint {.importc, header: "".} +proc fstat*(a1: cint, a2: var Stat): cint {.importc, header: "".} +proc lstat*(a1: cstring, a2: var Stat): cint {.importc, header: "".} +proc mkdir*(a1: cstring, a2: Mode): cint {.importc, header: "".} +proc mkfifo*(a1: cstring, a2: Mode): cint {.importc, header: "".} +proc mknod*(a1: cstring, a2: Mode, a3: Dev): cint {. importc, header: "".} -proc stat*(a1: cstring, a2: var TStat): cint {.importc, header: "".} -proc umask*(a1: TMode): TMode {.importc, header: "".} +proc stat*(a1: cstring, a2: var Stat): cint {.importc, header: "".} +proc umask*(a1: Mode): Mode {.importc, header: "".} -proc S_ISBLK*(m: TMode): bool {.importc, header: "".} +proc S_ISBLK*(m: Mode): bool {.importc, header: "".} ## Test for a block special file. -proc S_ISCHR*(m: TMode): bool {.importc, header: "".} +proc S_ISCHR*(m: Mode): bool {.importc, header: "".} ## Test for a character special file. -proc S_ISDIR*(m: TMode): bool {.importc, header: "".} +proc S_ISDIR*(m: Mode): bool {.importc, header: "".} ## Test for a directory. -proc S_ISFIFO*(m: TMode): bool {.importc, header: "".} +proc S_ISFIFO*(m: Mode): bool {.importc, header: "".} ## Test for a pipe or FIFO special file. -proc S_ISREG*(m: TMode): bool {.importc, header: "".} +proc S_ISREG*(m: Mode): bool {.importc, header: "".} ## Test for a regular file. -proc S_ISLNK*(m: TMode): bool {.importc, header: "".} +proc S_ISLNK*(m: Mode): bool {.importc, header: "".} ## Test for a symbolic link. -proc S_ISSOCK*(m: TMode): bool {.importc, header: "".} +proc S_ISSOCK*(m: Mode): bool {.importc, header: "".} ## Test for a socket. -proc S_TYPEISMQ*(buf: var TStat): bool {.importc, header: "".} +proc S_TYPEISMQ*(buf: var Stat): bool {.importc, header: "".} ## Test for a message queue. -proc S_TYPEISSEM*(buf: var TStat): bool {.importc, header: "".} +proc S_TYPEISSEM*(buf: var Stat): bool {.importc, header: "".} ## Test for a semaphore. -proc S_TYPEISSHM*(buf: var TStat): bool {.importc, header: "".} +proc S_TYPEISSHM*(buf: var Stat): bool {.importc, header: "".} ## Test for a shared memory object. -proc S_TYPEISTMO*(buf: var TStat): bool {.importc, header: "".} +proc S_TYPEISTMO*(buf: var Stat): bool {.importc, header: "".} ## Test macro for a typed memory object. proc mlock*(a1: pointer, a2: int): cint {.importc, header: "".} proc mlockall*(a1: cint): cint {.importc, header: "".} -proc mmap*(a1: pointer, a2: int, a3, a4, a5: cint, a6: TOff): pointer {. +proc mmap*(a1: pointer, a2: int, a3, a4, a5: cint, a6: Off): pointer {. importc, header: "".} proc mprotect*(a1: pointer, a2: int, a3: cint): cint {. importc, header: "".} @@ -2233,119 +2259,119 @@ proc munlockall*(): cint {.importc, header: "".} proc munmap*(a1: pointer, a2: int): cint {.importc, header: "".} proc posix_madvise*(a1: pointer, a2: int, a3: cint): cint {. importc, header: "".} -proc posix_mem_offset*(a1: pointer, a2: int, a3: var TOff, +proc posix_mem_offset*(a1: pointer, a2: int, a3: var Off, a4: var int, a5: var cint): cint {.importc, header: "".} proc posix_typed_mem_get_info*(a1: cint, - a2: var Tposix_typed_mem_info): cint {.importc, header: "".} + a2: var Posix_typed_mem_info): cint {.importc, header: "".} proc posix_typed_mem_open*(a1: cstring, a2, a3: cint): cint {. importc, header: "".} -proc shm_open*(a1: cstring, a2: cint, a3: TMode): cint {. +proc shm_open*(a1: cstring, a2: cint, a3: Mode): cint {. importc, header: "".} proc shm_unlink*(a1: cstring): cint {.importc, header: "".} -proc asctime*(a1: var Ttm): cstring{.importc, header: "".} +proc asctime*(a1: var Tm): cstring{.importc, header: "".} -proc asctime_r*(a1: var Ttm, a2: cstring): cstring {.importc, header: "".} -proc clock*(): TClock {.importc, header: "".} -proc clock_getcpuclockid*(a1: TPid, a2: var TClockId): cint {. +proc asctime_r*(a1: var Tm, a2: cstring): cstring {.importc, header: "".} +proc clock*(): Clock {.importc, header: "".} +proc clock_getcpuclockid*(a1: Pid, a2: var ClockId): cint {. importc, header: "".} -proc clock_getres*(a1: TClockId, a2: var Ttimespec): cint {. +proc clock_getres*(a1: ClockId, a2: var Timespec): cint {. importc, header: "".} -proc clock_gettime*(a1: TClockId, a2: var Ttimespec): cint {. +proc clock_gettime*(a1: ClockId, a2: var Timespec): cint {. importc, header: "".} -proc clock_nanosleep*(a1: TClockId, a2: cint, a3: var Ttimespec, - a4: var Ttimespec): cint {.importc, header: "".} -proc clock_settime*(a1: TClockId, a2: var Ttimespec): cint {. +proc clock_nanosleep*(a1: ClockId, a2: cint, a3: var Timespec, + a4: var Timespec): cint {.importc, header: "".} +proc clock_settime*(a1: ClockId, a2: var Timespec): cint {. importc, header: "".} proc ctime*(a1: var Time): cstring {.importc, header: "".} proc ctime_r*(a1: var Time, a2: cstring): cstring {.importc, header: "".} proc difftime*(a1, a2: Time): cdouble {.importc, header: "".} -proc getdate*(a1: cstring): ptr Ttm {.importc, header: "".} +proc getdate*(a1: cstring): ptr Tm {.importc, header: "".} -proc gmtime*(a1: var Time): ptr Ttm {.importc, header: "".} -proc gmtime_r*(a1: var Time, a2: var Ttm): ptr Ttm {.importc, header: "".} -proc localtime*(a1: var Time): ptr Ttm {.importc, header: "".} -proc localtime_r*(a1: var Time, a2: var Ttm): ptr Ttm {.importc, header: "".} -proc mktime*(a1: var Ttm): Time {.importc, header: "".} -proc timegm*(a1: var Ttm): Time {.importc, header: "".} -proc nanosleep*(a1, a2: var Ttimespec): cint {.importc, header: "".} +proc gmtime*(a1: var Time): ptr Tm {.importc, header: "".} +proc gmtime_r*(a1: var Time, a2: var Tm): ptr Tm {.importc, header: "".} +proc localtime*(a1: var Time): ptr Tm {.importc, header: "".} +proc localtime_r*(a1: var Time, a2: var Tm): ptr Tm {.importc, header: "".} +proc mktime*(a1: var Tm): Time {.importc, header: "".} +proc timegm*(a1: var Tm): Time {.importc, header: "".} +proc nanosleep*(a1, a2: var Timespec): cint {.importc, header: "".} proc strftime*(a1: cstring, a2: int, a3: cstring, - a4: var Ttm): int {.importc, header: "".} -proc strptime*(a1, a2: cstring, a3: var Ttm): cstring {.importc, header: "".} + a4: var Tm): int {.importc, header: "".} +proc strptime*(a1, a2: cstring, a3: var Tm): cstring {.importc, header: "".} proc time*(a1: var Time): Time {.importc, header: "".} -proc timer_create*(a1: var TClockId, a2: var TsigEvent, - a3: var Ttimer): cint {.importc, header: "".} -proc timer_delete*(a1: var Ttimer): cint {.importc, header: "".} -proc timer_gettime*(a1: Ttimer, a2: var titimerspec): cint {. +proc timer_create*(a1: var ClockId, a2: var SigEvent, + a3: var Timer): cint {.importc, header: "".} +proc timer_delete*(a1: var Timer): cint {.importc, header: "".} +proc timer_gettime*(a1: Timer, a2: var Itimerspec): cint {. importc, header: "".} -proc timer_getoverrun*(a1: Ttimer): cint {.importc, header: "".} -proc timer_settime*(a1: Ttimer, a2: cint, a3: var titimerspec, - a4: var titimerspec): cint {.importc, header: "".} +proc timer_getoverrun*(a1: Timer): cint {.importc, header: "".} +proc timer_settime*(a1: Timer, a2: cint, a3: var Itimerspec, + a4: var Itimerspec): cint {.importc, header: "".} proc tzset*() {.importc, header: "".} -proc wait*(a1: var cint): TPid {.importc, header: "".} -proc waitid*(a1: cint, a2: Tid, a3: var TsigInfo, a4: cint): cint {. +proc wait*(a1: var cint): Pid {.importc, header: "".} +proc waitid*(a1: cint, a2: Id, a3: var SigInfo, a4: cint): cint {. importc, header: "".} -proc waitpid*(a1: TPid, a2: var cint, a3: cint): TPid {. +proc waitpid*(a1: Pid, a2: var cint, a3: cint): Pid {. importc, header: "".} proc bsd_signal*(a1: cint, a2: proc (x: pointer) {.noconv.}) {. importc, header: "".} -proc kill*(a1: TPid, a2: cint): cint {.importc, header: "".} -proc killpg*(a1: TPid, a2: cint): cint {.importc, header: "".} -proc pthread_kill*(a1: Tpthread, a2: cint): cint {.importc, header: "".} -proc pthread_sigmask*(a1: cint, a2, a3: var Tsigset): cint {. +proc kill*(a1: Pid, a2: cint): cint {.importc, header: "".} +proc killpg*(a1: Pid, a2: cint): cint {.importc, header: "".} +proc pthread_kill*(a1: Pthread, a2: cint): cint {.importc, header: "".} +proc pthread_sigmask*(a1: cint, a2, a3: var Sigset): cint {. importc, header: "".} proc `raise`*(a1: cint): cint {.importc, header: "".} -proc sigaction*(a1: cint, a2, a3: var TSigaction): cint {. +proc sigaction*(a1: cint, a2, a3: var Sigaction): cint {. importc, header: "".} -proc sigaddset*(a1: var Tsigset, a2: cint): cint {.importc, header: "".} -proc sigaltstack*(a1, a2: var TStack): cint {.importc, header: "".} -proc sigdelset*(a1: var Tsigset, a2: cint): cint {.importc, header: "".} -proc sigemptyset*(a1: var Tsigset): cint {.importc, header: "".} -proc sigfillset*(a1: var Tsigset): cint {.importc, header: "".} +proc sigaddset*(a1: var Sigset, a2: cint): cint {.importc, header: "".} +proc sigaltstack*(a1, a2: var Stack): cint {.importc, header: "".} +proc sigdelset*(a1: var Sigset, a2: cint): cint {.importc, header: "".} +proc sigemptyset*(a1: var Sigset): cint {.importc, header: "".} +proc sigfillset*(a1: var Sigset): cint {.importc, header: "".} proc sighold*(a1: cint): cint {.importc, header: "".} proc sigignore*(a1: cint): cint {.importc, header: "".} proc siginterrupt*(a1, a2: cint): cint {.importc, header: "".} -proc sigismember*(a1: var Tsigset, a2: cint): cint {.importc, header: "".} +proc sigismember*(a1: var Sigset, a2: cint): cint {.importc, header: "".} proc signal*(a1: cint, a2: proc (x: cint) {.noconv.}) {. importc, header: "".} proc sigpause*(a1: cint): cint {.importc, header: "".} -proc sigpending*(a1: var Tsigset): cint {.importc, header: "".} -proc sigprocmask*(a1: cint, a2, a3: var Tsigset): cint {. +proc sigpending*(a1: var Sigset): cint {.importc, header: "".} +proc sigprocmask*(a1: cint, a2, a3: var Sigset): cint {. importc, header: "".} -proc sigqueue*(a1: TPid, a2: cint, a3: TsigVal): cint {. +proc sigqueue*(a1: Pid, a2: cint, a3: SigVal): cint {. importc, header: "".} proc sigrelse*(a1: cint): cint {.importc, header: "".} proc sigset*(a1: int, a2: proc (x: cint) {.noconv.}) {. importc, header: "".} -proc sigsuspend*(a1: var Tsigset): cint {.importc, header: "".} -proc sigtimedwait*(a1: var Tsigset, a2: var TsigInfo, - a3: var Ttimespec): cint {.importc, header: "".} -proc sigwait*(a1: var Tsigset, a2: var cint): cint {. +proc sigsuspend*(a1: var Sigset): cint {.importc, header: "".} +proc sigtimedwait*(a1: var Sigset, a2: var SigInfo, + a3: var Timespec): cint {.importc, header: "".} +proc sigwait*(a1: var Sigset, a2: var cint): cint {. importc, header: "".} -proc sigwaitinfo*(a1: var Tsigset, a2: var TsigInfo): cint {. +proc sigwaitinfo*(a1: var Sigset, a2: var SigInfo): cint {. importc, header: "".} -proc catclose*(a1: Tnl_catd): cint {.importc, header: "".} -proc catgets*(a1: Tnl_catd, a2, a3: cint, a4: cstring): cstring {. +proc catclose*(a1: Nl_catd): cint {.importc, header: "".} +proc catgets*(a1: Nl_catd, a2, a3: cint, a4: cstring): cstring {. importc, header: "".} -proc catopen*(a1: cstring, a2: cint): Tnl_catd {. +proc catopen*(a1: cstring, a2: cint): Nl_catd {. importc, header: "".} proc sched_get_priority_max*(a1: cint): cint {.importc, header: "".} proc sched_get_priority_min*(a1: cint): cint {.importc, header: "".} -proc sched_getparam*(a1: TPid, a2: var Tsched_param): cint {. +proc sched_getparam*(a1: Pid, a2: var Sched_param): cint {. importc, header: "".} -proc sched_getscheduler*(a1: TPid): cint {.importc, header: "".} -proc sched_rr_get_interval*(a1: TPid, a2: var Ttimespec): cint {. +proc sched_getscheduler*(a1: Pid): cint {.importc, header: "".} +proc sched_rr_get_interval*(a1: Pid, a2: var Timespec): cint {. importc, header: "".} -proc sched_setparam*(a1: TPid, a2: var Tsched_param): cint {. +proc sched_setparam*(a1: Pid, a2: var Sched_param): cint {. importc, header: "".} -proc sched_setscheduler*(a1: TPid, a2: cint, a3: var Tsched_param): cint {. +proc sched_setscheduler*(a1: Pid, a2: cint, a3: var Sched_param): cint {. importc, header: "".} proc sched_yield*(): cint {.importc, header: "".} @@ -2359,13 +2385,13 @@ proc FD_SET*(a1: cint | SocketHandle, a2: var TFdSet) {. importc: "FD_SET", header: "".} proc FD_ZERO*(a1: var TFdSet) {.importc, header: "".} -proc pselect*(a1: cint, a2, a3, a4: ptr TFdSet, a5: ptr Ttimespec, - a6: var Tsigset): cint {.importc, header: "".} +proc pselect*(a1: cint, a2, a3, a4: ptr TFdSet, a5: ptr Timespec, + a6: var Sigset): cint {.importc, header: "".} proc select*(a1: cint | SocketHandle, a2, a3, a4: ptr TFdSet, a5: ptr Timeval): cint {. importc, header: "".} when hasSpawnH: - proc posix_spawn*(a1: var TPid, a2: cstring, + proc posix_spawn*(a1: var Pid, a2: cstring, a3: var Tposix_spawn_file_actions, a4: var Tposix_spawnattr, a5, a6: cstringArray): cint {.importc, header: "".} @@ -2374,7 +2400,7 @@ when hasSpawnH: proc posix_spawn_file_actions_adddup2*(a1: var Tposix_spawn_file_actions, a2, a3: cint): cint {.importc, header: "".} proc posix_spawn_file_actions_addopen*(a1: var Tposix_spawn_file_actions, - a2: cint, a3: cstring, a4: cint, a5: TMode): cint {. + a2: cint, a3: cstring, a4: cint, a5: Mode): cint {. importc, header: "".} proc posix_spawn_file_actions_destroy*( a1: var Tposix_spawn_file_actions): cint {.importc, header: "".} @@ -2383,48 +2409,48 @@ when hasSpawnH: proc posix_spawnattr_destroy*(a1: var Tposix_spawnattr): cint {. importc, header: "".} proc posix_spawnattr_getsigdefault*(a1: var Tposix_spawnattr, - a2: var Tsigset): cint {.importc, header: "".} + a2: var Sigset): cint {.importc, header: "".} proc posix_spawnattr_getflags*(a1: var Tposix_spawnattr, a2: var cshort): cint {.importc, header: "".} proc posix_spawnattr_getpgroup*(a1: var Tposix_spawnattr, - a2: var TPid): cint {.importc, header: "".} + a2: var Pid): cint {.importc, header: "".} proc posix_spawnattr_getschedparam*(a1: var Tposix_spawnattr, - a2: var Tsched_param): cint {.importc, header: "".} + a2: var Sched_param): cint {.importc, header: "".} proc posix_spawnattr_getschedpolicy*(a1: var Tposix_spawnattr, a2: var cint): cint {.importc, header: "".} proc posix_spawnattr_getsigmask*(a1: var Tposix_spawnattr, - a2: var Tsigset): cint {.importc, header: "".} + a2: var Sigset): cint {.importc, header: "".} proc posix_spawnattr_init*(a1: var Tposix_spawnattr): cint {. importc, header: "".} proc posix_spawnattr_setsigdefault*(a1: var Tposix_spawnattr, - a2: var Tsigset): cint {.importc, header: "".} + a2: var Sigset): cint {.importc, header: "".} proc posix_spawnattr_setflags*(a1: var Tposix_spawnattr, a2: cint): cint {. importc, header: "".} - proc posix_spawnattr_setpgroup*(a1: var Tposix_spawnattr, a2: TPid): cint {. + proc posix_spawnattr_setpgroup*(a1: var Tposix_spawnattr, a2: Pid): cint {. importc, header: "".} proc posix_spawnattr_setschedparam*(a1: var Tposix_spawnattr, - a2: var Tsched_param): cint {.importc, header: "".} + a2: var Sched_param): cint {.importc, header: "".} proc posix_spawnattr_setschedpolicy*(a1: var Tposix_spawnattr, a2: cint): cint {. importc, header: "".} proc posix_spawnattr_setsigmask*(a1: var Tposix_spawnattr, - a2: var Tsigset): cint {.importc, header: "".} - proc posix_spawnp*(a1: var TPid, a2: cstring, + a2: var Sigset): cint {.importc, header: "".} + proc posix_spawnp*(a1: var Pid, a2: cstring, a3: var Tposix_spawn_file_actions, a4: var Tposix_spawnattr, a5, a6: cstringArray): cint {.importc, header: "".} -proc getcontext*(a1: var Tucontext): cint {.importc, header: "".} -proc makecontext*(a1: var Tucontext, a4: proc (){.noconv.}, a3: cint) {. +proc getcontext*(a1: var Ucontext): cint {.importc, header: "".} +proc makecontext*(a1: var Ucontext, a4: proc (){.noconv.}, a3: cint) {. varargs, importc, header: "".} -proc setcontext*(a1: var Tucontext): cint {.importc, header: "".} -proc swapcontext*(a1, a2: var Tucontext): cint {.importc, header: "".} +proc setcontext*(a1: var Ucontext): cint {.importc, header: "".} +proc swapcontext*(a1, a2: var Ucontext): cint {.importc, header: "".} -proc readv*(a1: cint, a2: ptr TIOVec, a3: cint): int {. +proc readv*(a1: cint, a2: ptr IOVec, a3: cint): int {. importc, header: "".} -proc writev*(a1: cint, a2: ptr TIOVec, a3: cint): int {. +proc writev*(a1: cint, a2: ptr IOVec, a3: cint): int {. importc, header: "".} proc CMSG_DATA*(cmsg: ptr Tcmsghdr): cstring {. @@ -2491,40 +2517,40 @@ proc if_indextoname*(a1: cint, a2: cstring): cstring {. proc if_nameindex*(): ptr Tif_nameindex {.importc, header: "".} proc if_freenameindex*(a1: ptr Tif_nameindex) {.importc, header: "".} -proc IN6_IS_ADDR_UNSPECIFIED* (a1: ptr TIn6Addr): cint {. +proc IN6_IS_ADDR_UNSPECIFIED* (a1: ptr In6Addr): cint {. importc, header: "".} ## Unspecified address. -proc IN6_IS_ADDR_LOOPBACK* (a1: ptr TIn6Addr): cint {. +proc IN6_IS_ADDR_LOOPBACK* (a1: ptr In6Addr): cint {. importc, header: "".} ## Loopback address. -proc IN6_IS_ADDR_MULTICAST* (a1: ptr TIn6Addr): cint {. +proc IN6_IS_ADDR_MULTICAST* (a1: ptr In6Addr): cint {. importc, header: "".} ## Multicast address. -proc IN6_IS_ADDR_LINKLOCAL* (a1: ptr TIn6Addr): cint {. +proc IN6_IS_ADDR_LINKLOCAL* (a1: ptr In6Addr): cint {. importc, header: "".} ## Unicast link-local address. -proc IN6_IS_ADDR_SITELOCAL* (a1: ptr TIn6Addr): cint {. +proc IN6_IS_ADDR_SITELOCAL* (a1: ptr In6Addr): cint {. importc, header: "".} ## Unicast site-local address. -proc IN6_IS_ADDR_V4MAPPED* (a1: ptr TIn6Addr): cint {. +proc IN6_IS_ADDR_V4MAPPED* (a1: ptr In6Addr): cint {. importc, header: "".} ## IPv4 mapped address. -proc IN6_IS_ADDR_V4COMPAT* (a1: ptr TIn6Addr): cint {. +proc IN6_IS_ADDR_V4COMPAT* (a1: ptr In6Addr): cint {. importc, header: "".} ## IPv4-compatible address. -proc IN6_IS_ADDR_MC_NODELOCAL* (a1: ptr TIn6Addr): cint {. +proc IN6_IS_ADDR_MC_NODELOCAL* (a1: ptr In6Addr): cint {. importc, header: "".} ## Multicast node-local address. -proc IN6_IS_ADDR_MC_LINKLOCAL* (a1: ptr TIn6Addr): cint {. +proc IN6_IS_ADDR_MC_LINKLOCAL* (a1: ptr In6Addr): cint {. importc, header: "".} ## Multicast link-local address. -proc IN6_IS_ADDR_MC_SITELOCAL* (a1: ptr TIn6Addr): cint {. +proc IN6_IS_ADDR_MC_SITELOCAL* (a1: ptr In6Addr): cint {. importc, header: "".} ## Multicast site-local address. -proc IN6_IS_ADDR_MC_ORGLOCAL* (a1: ptr TIn6Addr): cint {. +proc IN6_IS_ADDR_MC_ORGLOCAL* (a1: ptr In6Addr): cint {. importc, header: "".} ## Multicast organization-local address. -proc IN6_IS_ADDR_MC_GLOBAL* (a1: ptr TIn6Addr): cint {. +proc IN6_IS_ADDR_MC_GLOBAL* (a1: ptr In6Addr): cint {. importc, header: "".} ## Multicast global address. @@ -2552,9 +2578,9 @@ proc getnetbyaddr*(a1: int32, a2: cint): ptr Tnetent {.importc, header: "".} proc getnetent*(): ptr Tnetent {.importc, header: "".} -proc getprotobyname*(a1: cstring): ptr TProtoent {.importc, header: "".} -proc getprotobynumber*(a1: cint): ptr TProtoent {.importc, header: "".} -proc getprotoent*(): ptr TProtoent {.importc, header: "".} +proc getprotobyname*(a1: cstring): ptr Protoent {.importc, header: "".} +proc getprotobynumber*(a1: cint): ptr Protoent {.importc, header: "".} +proc getprotoent*(): ptr Protoent {.importc, header: "".} proc getservbyname*(a1, a2: cstring): ptr Servent {.importc, header: "".} proc getservbyport*(a1: cint, a2: cstring): ptr Servent {. diff --git a/lib/posix/termios.nim b/lib/posix/termios.nim index 710b2fa6b..44f029039 100644 --- a/lib/posix/termios.nim +++ b/lib/posix/termios.nim @@ -12,17 +12,18 @@ import posix type Speed* = cuint - Tcflag* = cuint + Cflag* = cuint +{.deprecated: [Tcflag: Cflag].} const NCCS* = 32 type Termios* {.importc: "struct termios", header: "".} = object - c_iflag*: Tcflag # input mode flags - c_oflag*: Tcflag # output mode flags - c_cflag*: Tcflag # control mode flags - c_lflag*: Tcflag # local mode flags + c_iflag*: Cflag # input mode flags + c_oflag*: Cflag # output mode flags + c_cflag*: Cflag # control mode flags + c_lflag*: Cflag # local mode flags c_line*: cuchar # line discipline c_cc*: array[NCCS, cuchar] # control characters @@ -258,4 +259,4 @@ proc tcFlow*(fd: cint; action: cint): cint {.importc: "tcflow", header: "".} # Get process group ID for session leader for controlling terminal FD. -proc tcGetSid*(fd: cint): TPid {.importc: "tcgetsid", header: "".} +proc tcGetSid*(fd: cint): Pid {.importc: "tcgetsid", header: "".} From 192ba3bbc0ae7f570c1277c9211d24eeea2cf48a Mon Sep 17 00:00:00 2001 From: pdw Date: Sun, 24 May 2015 22:30:19 -0500 Subject: [PATCH 0350/1263] lib/pure/a-c - Dropped 'T' from types --- lib/pure/actors.nim | 104 ++++++------- lib/pure/asyncdispatch.nim | 163 ++++++++++---------- lib/pure/asyncfile.nim | 34 ++--- lib/pure/asyncio.nim | 4 +- lib/pure/asyncnet.nim | 20 +-- lib/pure/basic2d.nim | 212 +++++++++++++------------- lib/pure/basic3d.nim | 202 ++++++++++++------------ lib/pure/collections/LockFreeHash.nim | 60 ++++---- lib/pure/collections/intsets.nim | 16 +- lib/pure/collections/sets.nim | 50 +++--- lib/pure/collections/tables.nim | 72 ++++----- lib/pure/concurrency/cpuload.nim | 2 +- lib/pure/concurrency/threadpool.nim | 8 +- 13 files changed, 477 insertions(+), 470 deletions(-) diff --git a/lib/pure/actors.nim b/lib/pure/actors.nim index 294c24741..da9037285 100644 --- a/lib/pure/actors.nim +++ b/lib/pure/actors.nim @@ -16,7 +16,7 @@ ## .. code-block:: nim ## ## var -## a: TActorPool[int, void] +## a: ActorPool[int, void] ## createActorPool(a) ## for i in 0 .. < 300: ## a.spawn(i, proc (x: int) {.thread.} = echo x) @@ -30,75 +30,76 @@ from os import sleep type - TTask*[TIn, TOut] = object{.pure, final.} ## a task - when TOut isnot void: - receiver*: ptr TChannel[TOut] ## the receiver channel of the response - action*: proc (x: TIn): TOut {.thread.} ## action to execute; + Task*[In, Out] = object{.pure, final.} ## a task + when Out isnot void: + receiver*: ptr Channel[Out] ## the receiver channel of the response + action*: proc (x: In): Out {.thread.} ## action to execute; ## sometimes useful shutDown*: bool ## set to tell an actor to shut-down - data*: TIn ## the data to process + data*: In ## the data to process - TActor[TIn, TOut] = object{.pure, final.} - i: TChannel[TTask[TIn, TOut]] - t: TThread[ptr TActor[TIn, TOut]] + Actor[In, Out] = object{.pure, final.} + i: Channel[Task[In, Out]] + t: TThread[ptr Actor[In, Out]] - PActor*[TIn, TOut] = ptr TActor[TIn, TOut] ## an actor - -proc spawn*[TIn, TOut](action: proc( - self: PActor[TIn, TOut]){.thread.}): PActor[TIn, TOut] = + PActor*[In, Out] = ptr Actor[In, Out] ## an actor +{.deprecated: [TTask: Task, TActor: Actor].} + +proc spawn*[In, Out](action: proc( + self: PActor[In, Out]){.thread.}): PActor[In, Out] = ## creates an actor; that is a thread with an inbox. The caller MUST call ## ``join`` because that also frees the actor's associated resources. - result = cast[PActor[TIn, TOut]](allocShared0(sizeof(result[]))) + result = cast[PActor[In, Out]](allocShared0(sizeof(result[]))) open(result.i) createThread(result.t, action, result) -proc inbox*[TIn, TOut](self: PActor[TIn, TOut]): ptr TChannel[TIn] = +proc inbox*[In, Out](self: PActor[In, Out]): ptr Channel[In] = ## gets a pointer to the associated inbox of the actor `self`. result = addr(self.i) -proc running*[TIn, TOut](a: PActor[TIn, TOut]): bool = +proc running*[In, Out](a: PActor[In, Out]): bool = ## returns true if the actor `a` is running. result = running(a.t) -proc ready*[TIn, TOut](a: PActor[TIn, TOut]): bool = +proc ready*[In, Out](a: PActor[In, Out]): bool = ## returns true if the actor `a` is ready to process new messages. result = ready(a.i) -proc join*[TIn, TOut](a: PActor[TIn, TOut]) = +proc join*[In, Out](a: PActor[In, Out]) = ## joins an actor. joinThread(a.t) close(a.i) deallocShared(a) -proc recv*[TIn, TOut](a: PActor[TIn, TOut]): TTask[TIn, TOut] = +proc recv*[In, Out](a: PActor[In, Out]): Task[In, Out] = ## receives a task from `a`'s inbox. result = recv(a.i) -proc send*[TIn, TOut, X, Y](receiver: PActor[TIn, TOut], msg: TIn, +proc send*[In, Out, X, Y](receiver: PActor[In, Out], msg: In, sender: PActor[X, Y]) = ## sends a message to `a`'s inbox. - var t: TTask[TIn, TOut] + var t: Task[In, Out] t.receiver = addr(sender.i) shallowCopy(t.data, msg) send(receiver.i, t) -proc send*[TIn, TOut](receiver: PActor[TIn, TOut], msg: TIn, - sender: ptr TChannel[TOut] = nil) = +proc send*[In, Out](receiver: PActor[In, Out], msg: In, + sender: ptr Channel[Out] = nil) = ## sends a message to `receiver`'s inbox. - var t: TTask[TIn, TOut] + var t: Task[In, Out] t.receiver = sender shallowCopy(t.data, msg) send(receiver.i, t) -proc sendShutdown*[TIn, TOut](receiver: PActor[TIn, TOut]) = +proc sendShutdown*[In, Out](receiver: PActor[In, Out]) = ## send a shutdown message to `receiver`. - var t: TTask[TIn, TOut] + var t: Task[In, Out] t.shutdown = true send(receiver.i, t) -proc reply*[TIn, TOut](t: TTask[TIn, TOut], m: TOut) = +proc reply*[In, Out](t: Task[In, Out], m: Out) = ## sends a message to io's output message box. - when TOut is void: + when Out is void: {.error: "you cannot reply to a void outbox".} assert t.receiver != nil send(t.receiver[], m) @@ -107,34 +108,35 @@ proc reply*[TIn, TOut](t: TTask[TIn, TOut], m: TOut) = # ----------------- actor pools ---------------------------------------------- type - TActorPool*[TIn, TOut] = object{.pure, final.} ## an actor pool - actors: seq[PActor[TIn, TOut]] - when TOut isnot void: - outputs: TChannel[TOut] + ActorPool*[In, Out] = object{.pure, final.} ## an actor pool + actors: seq[PActor[In, Out]] + when Out isnot void: + outputs: Channel[Out] +{.deprecated: [TActorPool: ActorPool].} -proc `^`*[T](f: ptr TChannel[T]): T = +proc `^`*[T](f: ptr Channel[T]): T = ## alias for 'recv'. result = recv(f[]) -proc poolWorker[TIn, TOut](self: PActor[TIn, TOut]) {.thread.} = +proc poolWorker[In, Out](self: PActor[In, Out]) {.thread.} = while true: var m = self.recv if m.shutDown: break - when TOut is void: + when Out is void: m.action(m.data) else: send(m.receiver[], m.action(m.data)) #self.reply() -proc createActorPool*[TIn, TOut](a: var TActorPool[TIn, TOut], poolSize = 4) = +proc createActorPool*[In, Out](a: var ActorPool[In, Out], poolSize = 4) = ## creates an actor pool. newSeq(a.actors, poolSize) - when TOut isnot void: + when Out isnot void: open(a.outputs) for i in 0 .. < a.actors.len: - a.actors[i] = spawn(poolWorker[TIn, TOut]) + a.actors[i] = spawn(poolWorker[In, Out]) -proc sync*[TIn, TOut](a: var TActorPool[TIn, TOut], polling=50) = +proc sync*[In, Out](a: var ActorPool[In, Out], polling=50) = ## waits for every actor of `a` to finish with its work. Currently this is ## implemented as polling every `polling` ms and has a slight chance ## of failing since we check for every actor to be in `ready` state and not @@ -157,18 +159,18 @@ proc sync*[TIn, TOut](a: var TActorPool[TIn, TOut], polling=50) = if allReadyCount > 1: break sleep(polling) -proc terminate*[TIn, TOut](a: var TActorPool[TIn, TOut]) = +proc terminate*[In, Out](a: var ActorPool[In, Out]) = ## terminates each actor in the actor pool `a` and frees the ## resources attached to `a`. - var t: TTask[TIn, TOut] + var t: Task[In, Out] t.shutdown = true for i in 0.. 0 @@ -148,7 +148,7 @@ proc read*(f: AsyncFile, size: int): Future[string] = ol.offsetHigh = DWord(f.offset shr 32) # According to MSDN we're supposed to pass nil to lpNumberOfBytesRead. - let ret = readFile(f.fd.THandle, buffer, size.int32, nil, + let ret = readFile(f.fd.Handle, buffer, size.int32, nil, cast[POVERLAPPED](ol)) if not ret.bool: let err = osLastError() @@ -161,7 +161,7 @@ proc read*(f: AsyncFile, size: int): Future[string] = else: # Request completed immediately. var bytesRead: DWord - let overlappedRes = getOverlappedResult(f.fd.THandle, + let overlappedRes = getOverlappedResult(f.fd.Handle, cast[POverlapped](ol)[], bytesRead, false.WinBool) if not overlappedRes.bool: let err = osLastError() @@ -179,7 +179,7 @@ proc read*(f: AsyncFile, size: int): Future[string] = else: var readBuffer = newString(size) - proc cb(fd: TAsyncFD): bool = + proc cb(fd: AsyncFD): bool = result = true let res = read(fd.cint, addr readBuffer[0], size.cint) if res < 0: @@ -251,8 +251,8 @@ proc write*(f: AsyncFile, data: string): Future[void] = var ol = PCustomOverlapped() GC_ref(ol) - ol.data = TCompletionData(fd: f.fd, cb: - proc (fd: TAsyncFD, bytesCount: DWord, errcode: OSErrorCode) = + ol.data = CompletionData(fd: f.fd, cb: + proc (fd: AsyncFD, bytesCount: DWord, errcode: OSErrorCode) = if not retFuture.finished: if errcode == OSErrorCode(-1): assert bytesCount == data.len.int32 @@ -268,7 +268,7 @@ proc write*(f: AsyncFile, data: string): Future[void] = ol.offsetHigh = DWord(f.offset shr 32) # According to MSDN we're supposed to pass nil to lpNumberOfBytesWritten. - let ret = writeFile(f.fd.THandle, buffer, data.len.int32, nil, + let ret = writeFile(f.fd.Handle, buffer, data.len.int32, nil, cast[POVERLAPPED](ol)) if not ret.bool: let err = osLastError() @@ -281,7 +281,7 @@ proc write*(f: AsyncFile, data: string): Future[void] = else: # Request completed immediately. var bytesWritten: DWord - let overlappedRes = getOverlappedResult(f.fd.THandle, + let overlappedRes = getOverlappedResult(f.fd.Handle, cast[POverlapped](ol)[], bytesWritten, false.WinBool) if not overlappedRes.bool: retFuture.fail(newException(OSError, osErrorMsg(osLastError()))) @@ -292,7 +292,7 @@ proc write*(f: AsyncFile, data: string): Future[void] = else: var written = 0 - proc cb(fd: TAsyncFD): bool = + proc cb(fd: AsyncFD): bool = result = true let remainderSize = data.len-written let res = write(fd.cint, addr copy[written], remainderSize.cint) @@ -317,7 +317,7 @@ proc write*(f: AsyncFile, data: string): Future[void] = proc close*(f: AsyncFile) = ## Closes the file specified. when defined(windows) or defined(nimdoc): - if not closeHandle(f.fd.THandle).bool: + if not closeHandle(f.fd.Handle).bool: raiseOSError(osLastError()) else: if close(f.fd.cint) == -1: diff --git a/lib/pure/asyncio.nim b/lib/pure/asyncio.nim index 6ae2c608b..5fd45b215 100644 --- a/lib/pure/asyncio.nim +++ b/lib/pure/asyncio.nim @@ -188,8 +188,8 @@ proc asyncSocket*(domain: Domain = AF_INET, typ: SockType = SOCK_STREAM, result.socket.setBlocking(false) proc toAsyncSocket*(sock: Socket, state: SocketStatus = SockConnected): AsyncSocket = - ## Wraps an already initialized ``TSocket`` into a AsyncSocket. - ## This is useful if you want to use an already connected TSocket as an + ## Wraps an already initialized ``Socket`` into a AsyncSocket. + ## This is useful if you want to use an already connected Socket as an ## asynchronous AsyncSocket in asyncio's event loop. ## ## ``state`` may be overriden, i.e. if ``sock`` is not connected it should be diff --git a/lib/pure/asyncnet.nim b/lib/pure/asyncnet.nim index aadbde824..d44e5d31f 100644 --- a/lib/pure/asyncnet.nim +++ b/lib/pure/asyncnet.nim @@ -91,9 +91,9 @@ type # TODO: Save AF, domain etc info and reuse it in procs which need it like connect. -proc newAsyncSocket*(fd: TAsyncFD, isBuff: bool): AsyncSocket = +proc newAsyncSocket*(fd: AsyncFD, isBuff: bool): AsyncSocket = ## Creates a new ``AsyncSocket`` based on the supplied params. - assert fd != osInvalidSocket.TAsyncFD + assert fd != osInvalidSocket.AsyncFD new(result) result.fd = fd.SocketHandle result.isBuffered = isBuff @@ -142,7 +142,7 @@ when defined(ssl): if read < 0: raiseSslError() data.setLen(read) - await socket.fd.TAsyncFd.send(data, flags) + await socket.fd.AsyncFd.send(data, flags) proc appeaseSsl(socket: AsyncSocket, flags: set[SocketFlag], sslError: cint) {.async.} = @@ -150,7 +150,7 @@ when defined(ssl): of SSL_ERROR_WANT_WRITE: await sendPendingSslData(socket, flags) of SSL_ERROR_WANT_READ: - var data = await recv(socket.fd.TAsyncFD, BufferSize, flags) + var data = await recv(socket.fd.AsyncFD, BufferSize, flags) let ret = bioWrite(socket.bioIn, addr data[0], data.len.cint) if ret < 0: raiseSSLError() @@ -175,7 +175,7 @@ proc connect*(socket: AsyncSocket, address: string, port: Port, ## ## Returns a ``Future`` which will complete when the connection succeeds ## or an error occurs. - await connect(socket.fd.TAsyncFD, address, port, af) + await connect(socket.fd.AsyncFD, address, port, af) if socket.isSsl: when defined(ssl): let flags = {SocketFlag.SafeDisconn} @@ -194,7 +194,7 @@ template readInto(buf: cstring, size: int, socket: AsyncSocket, sslRead(socket.sslHandle, buf, size.cint)) res = opResult else: - var recvIntoFut = recvInto(socket.fd.TAsyncFD, buf, size, flags) + var recvIntoFut = recvInto(socket.fd.AsyncFD, buf, size, flags) yield recvIntoFut # Not in SSL mode. res = recvIntoFut.read() @@ -271,7 +271,7 @@ proc send*(socket: AsyncSocket, data: string, sslWrite(socket.sslHandle, addr copy[0], copy.len.cint)) await sendPendingSslData(socket, flags) else: - await send(socket.fd.TAsyncFD, data, flags) + await send(socket.fd.AsyncFD, data, flags) proc acceptAddr*(socket: AsyncSocket, flags = {SocketFlag.SafeDisconn}): Future[tuple[address: string, client: AsyncSocket]] = @@ -279,9 +279,9 @@ proc acceptAddr*(socket: AsyncSocket, flags = {SocketFlag.SafeDisconn}): ## corresponding to that connection and the remote address of the client. ## The future will complete when the connection is successfully accepted. var retFuture = newFuture[tuple[address: string, client: AsyncSocket]]("asyncnet.acceptAddr") - var fut = acceptAddr(socket.fd.TAsyncFD, flags) + var fut = acceptAddr(socket.fd.AsyncFD, flags) fut.callback = - proc (future: Future[tuple[address: string, client: TAsyncFD]]) = + proc (future: Future[tuple[address: string, client: AsyncFD]]) = assert future.finished if future.failed: retFuture.fail(future.readError) @@ -445,7 +445,7 @@ proc bindAddr*(socket: AsyncSocket, port = Port(0), address = "") {. proc close*(socket: AsyncSocket) = ## Closes the socket. defer: - socket.fd.TAsyncFD.closeSocket() + socket.fd.AsyncFD.closeSocket() when defined(ssl): if socket.isSSL: let res = SslShutdown(socket.sslHandle) diff --git a/lib/pure/basic2d.nim b/lib/pure/basic2d.nim index a344cd053..d18e73c16 100644 --- a/lib/pure/basic2d.nim +++ b/lib/pure/basic2d.nim @@ -20,20 +20,20 @@ import strutils ## ## # Create a matrix which first rotates, then scales and at last translates ## -## var m:TMatrix2d=rotate(DEG90) & scale(2.0) & move(100.0,200.0) +## var m:Matrix2d=rotate(DEG90) & scale(2.0) & move(100.0,200.0) ## ## # Create a 2d point at (100,0) and a vector (5,2) ## -## var pt:TPoint2d=point2d(100.0,0.0) +## var pt:Point2d=point2d(100.0,0.0) ## -## var vec:TVector2d=vector2d(5.0,2.0) +## var vec:Vector2d=vector2d(5.0,2.0) ## ## ## pt &= m # transforms pt in place ## -## var pt2:TPoint2d=pt & m #concatenates pt with m and returns a new point +## var pt2:Point2d=pt & m #concatenates pt with m and returns a new point ## -## var vec2:TVector2d=vec & m #concatenates vec with m and returns a new vector +## var vec2:Vector2d=vec & m #concatenates vec with m and returns a new vector const @@ -57,46 +57,46 @@ const ## used internally by DegToRad and RadToDeg type - TMatrix2d* = object + Matrix2d* = object ## Implements a row major 2d matrix, which means ## transformations are applied the order they are concatenated. ## The rightmost column of the 3x3 matrix is left out since normally ## not used for geometric transformations in 2d. ax*,ay*,bx*,by*,tx*,ty*:float - TPoint2d* = object + Point2d* = object ## Implements a non-homegeneous 2d point stored as ## an `x` coordinate and an `y` coordinate. x*,y*:float - TVector2d* = object + Vector2d* = object ## Implements a 2d **direction vector** stored as ## an `x` coordinate and an `y` coordinate. Direction vector means, ## that when transforming a vector with a matrix, the translational ## part of the matrix is ignored. x*,y*:float - +{.deprecated: [TMatrix2d: Matrix2d, TPoint2d: Point2d, TVector2d: Vector2d].} # Some forward declarations... -proc matrix2d*(ax,ay,bx,by,tx,ty:float):TMatrix2d {.noInit.} +proc matrix2d*(ax,ay,bx,by,tx,ty:float):Matrix2d {.noInit.} ## Creates a new matrix. ## `ax`,`ay` is the local x axis ## `bx`,`by` is the local y axis ## `tx`,`ty` is the translation -proc vector2d*(x,y:float):TVector2d {.noInit,inline.} +proc vector2d*(x,y:float):Vector2d {.noInit,inline.} ## Returns a new vector (`x`,`y`) -proc point2d*(x,y:float):TPoint2d {.noInit,inline.} +proc point2d*(x,y:float):Point2d {.noInit,inline.} ## Returns a new point (`x`,`y`) let - IDMATRIX*:TMatrix2d=matrix2d(1.0,0.0,0.0,1.0,0.0,0.0) + IDMATRIX*:Matrix2d=matrix2d(1.0,0.0,0.0,1.0,0.0,0.0) ## Quick access to an identity matrix - ORIGO*:TPoint2d=point2d(0.0,0.0) + ORIGO*:Point2d=point2d(0.0,0.0) ## Quick acces to point (0,0) - XAXIS*:TVector2d=vector2d(1.0,0.0) + XAXIS*:Vector2d=vector2d(1.0,0.0) ## Quick acces to an 2d x-axis unit vector - YAXIS*:TVector2d=vector2d(0.0,1.0) + YAXIS*:Vector2d=vector2d(0.0,1.0) ## Quick acces to an 2d y-axis unit vector @@ -116,21 +116,21 @@ proc safeArccos(v:float):float= template makeBinOpVector(s:expr)= ## implements binary operators + , - , * and / for vectors - proc s*(a,b:TVector2d):TVector2d {.inline,noInit.} = vector2d(s(a.x,b.x),s(a.y,b.y)) - proc s*(a:TVector2d,b:float):TVector2d {.inline,noInit.} = vector2d(s(a.x,b),s(a.y,b)) - proc s*(a:float,b:TVector2d):TVector2d {.inline,noInit.} = vector2d(s(a,b.x),s(a,b.y)) + proc s*(a,b:Vector2d):Vector2d {.inline,noInit.} = vector2d(s(a.x,b.x),s(a.y,b.y)) + proc s*(a:Vector2d,b:float):Vector2d {.inline,noInit.} = vector2d(s(a.x,b),s(a.y,b)) + proc s*(a:float,b:Vector2d):Vector2d {.inline,noInit.} = vector2d(s(a,b.x),s(a,b.y)) template makeBinOpAssignVector(s:expr)= ## implements inplace binary operators += , -= , /= and *= for vectors - proc s*(a:var TVector2d,b:TVector2d) {.inline.} = s(a.x,b.x) ; s(a.y,b.y) - proc s*(a:var TVector2d,b:float) {.inline.} = s(a.x,b) ; s(a.y,b) + proc s*(a:var Vector2d,b:Vector2d) {.inline.} = s(a.x,b.x) ; s(a.y,b.y) + proc s*(a:var Vector2d,b:float) {.inline.} = s(a.x,b) ; s(a.y,b) # *************************************** -# TMatrix2d implementation +# Matrix2d implementation # *************************************** -proc setElements*(t:var TMatrix2d,ax,ay,bx,by,tx,ty:float) {.inline.}= +proc setElements*(t:var Matrix2d,ax,ay,bx,by,tx,ty:float) {.inline.}= ## Sets arbitrary elements in an existing matrix. t.ax=ax t.ay=ay @@ -139,10 +139,10 @@ proc setElements*(t:var TMatrix2d,ax,ay,bx,by,tx,ty:float) {.inline.}= t.tx=tx t.ty=ty -proc matrix2d*(ax,ay,bx,by,tx,ty:float):TMatrix2d = +proc matrix2d*(ax,ay,bx,by,tx,ty:float):Matrix2d = result.setElements(ax,ay,bx,by,tx,ty) -proc `&`*(a,b:TMatrix2d):TMatrix2d {.noInit.} = #concatenate matrices +proc `&`*(a,b:Matrix2d):Matrix2d {.noInit.} = #concatenate matrices ## Concatenates matrices returning a new matrix. # | a.AX a.AY 0 | | b.AX b.AY 0 | @@ -157,34 +157,34 @@ proc `&`*(a,b:TMatrix2d):TMatrix2d {.noInit.} = #concatenate matrices a.tx * b.ay + a.ty * b.by + b.ty) -proc scale*(s:float):TMatrix2d {.noInit.} = +proc scale*(s:float):Matrix2d {.noInit.} = ## Returns a new scale matrix. result.setElements(s,0,0,s,0,0) -proc scale*(s:float,org:TPoint2d):TMatrix2d {.noInit.} = +proc scale*(s:float,org:Point2d):Matrix2d {.noInit.} = ## Returns a new scale matrix using, `org` as scale origin. result.setElements(s,0,0,s,org.x-s*org.x,org.y-s*org.y) -proc stretch*(sx,sy:float):TMatrix2d {.noInit.} = +proc stretch*(sx,sy:float):Matrix2d {.noInit.} = ## Returns new a stretch matrix, which is a ## scale matrix with non uniform scale in x and y. result.setElements(sx,0,0,sy,0,0) -proc stretch*(sx,sy:float,org:TPoint2d):TMatrix2d {.noInit.} = +proc stretch*(sx,sy:float,org:Point2d):Matrix2d {.noInit.} = ## Returns a new stretch matrix, which is a ## scale matrix with non uniform scale in x and y. ## `org` is used as stretch origin. result.setElements(sx,0,0,sy,org.x-sx*org.x,org.y-sy*org.y) -proc move*(dx,dy:float):TMatrix2d {.noInit.} = +proc move*(dx,dy:float):Matrix2d {.noInit.} = ## Returns a new translation matrix. result.setElements(1,0,0,1,dx,dy) -proc move*(v:TVector2d):TMatrix2d {.noInit.} = +proc move*(v:Vector2d):Matrix2d {.noInit.} = ## Returns a new translation matrix from a vector. result.setElements(1,0,0,1,v.x,v.y) -proc rotate*(rad:float):TMatrix2d {.noInit.} = +proc rotate*(rad:float):Matrix2d {.noInit.} = ## Returns a new rotation matrix, which ## represents a rotation by `rad` radians let @@ -192,7 +192,7 @@ proc rotate*(rad:float):TMatrix2d {.noInit.} = c=cos(rad) result.setElements(c,s,-s,c,0,0) -proc rotate*(rad:float,org:TPoint2d):TMatrix2d {.noInit.} = +proc rotate*(rad:float,org:Point2d):Matrix2d {.noInit.} = ## Returns a new rotation matrix, which ## represents a rotation by `rad` radians around ## the origin `org` @@ -201,7 +201,7 @@ proc rotate*(rad:float,org:TPoint2d):TMatrix2d {.noInit.} = c=cos(rad) result.setElements(c,s,-s,c,org.x+s*org.y-c*org.x,org.y-c*org.y-s*org.x) -proc mirror*(v:TVector2d):TMatrix2d {.noInit.} = +proc mirror*(v:Vector2d):Matrix2d {.noInit.} = ## Returns a new mirror matrix, mirroring ## around the line that passes through origo and ## has the direction of `v` @@ -220,7 +220,7 @@ proc mirror*(v:TVector2d):TMatrix2d {.noInit.} = xy2,-sqd, 0.0,0.0) -proc mirror*(org:TPoint2d,v:TVector2d):TMatrix2d {.noInit.} = +proc mirror*(org:Point2d,v:Vector2d):Matrix2d {.noInit.} = ## Returns a new mirror matrix, mirroring ## around the line that passes through `org` and ## has the direction of `v` @@ -241,20 +241,20 @@ proc mirror*(org:TPoint2d,v:TVector2d):TMatrix2d {.noInit.} = -proc skew*(xskew,yskew:float):TMatrix2d {.noInit.} = +proc skew*(xskew,yskew:float):Matrix2d {.noInit.} = ## Returns a new skew matrix, which has its ## x axis rotated `xskew` radians from the local x axis, and ## y axis rotated `yskew` radians from the local y axis result.setElements(cos(yskew),sin(yskew),-sin(xskew),cos(xskew),0,0) -proc `$`* (t:TMatrix2d):string {.noInit.} = +proc `$`* (t:Matrix2d):string {.noInit.} = ## Returns a string representation of the matrix return rtos(t.ax) & "," & rtos(t.ay) & "," & rtos(t.bx) & "," & rtos(t.by) & "," & rtos(t.tx) & "," & rtos(t.ty) -proc isUniform*(t:TMatrix2d,tol=1.0e-6):bool= +proc isUniform*(t:Matrix2d,tol=1.0e-6):bool= ## Checks if the transform is uniform, that is ## perpendicular axes of equal length, which means (for example) ## it cannot transform a circle into an ellipse. @@ -268,18 +268,18 @@ proc isUniform*(t:TMatrix2d,tol=1.0e-6):bool= return true return false -proc determinant*(t:TMatrix2d):float= +proc determinant*(t:Matrix2d):float= ## Computes the determinant of the matrix. #NOTE: equivalent with perp.dot product for two 2d vectors return t.ax*t.by-t.bx*t.ay -proc isMirroring* (m:TMatrix2d):bool= +proc isMirroring* (m:Matrix2d):bool= ## Checks if the `m` is a mirroring matrix, ## which means it will reverse direction of a curve transformed with it return m.determinant<0.0 -proc inverse*(m:TMatrix2d):TMatrix2d {.noInit.} = +proc inverse*(m:Matrix2d):Matrix2d {.noInit.} = ## Returns a new matrix, which is the inverse of the matrix ## If the matrix is not invertible (determinant=0), an EDivByZero ## will be raised. @@ -293,7 +293,7 @@ proc inverse*(m:TMatrix2d):TMatrix2d {.noInit.} = (m.bx*m.ty-m.by*m.tx)/d, (m.ay*m.tx-m.ax*m.ty)/d) -proc equals*(m1:TMatrix2d,m2:TMatrix2d,tol=1.0e-6):bool= +proc equals*(m1:Matrix2d,m2:Matrix2d,tol=1.0e-6):bool= ## Checks if all elements of `m1`and `m2` is equal within ## a given tolerance `tol`. return @@ -304,17 +304,17 @@ proc equals*(m1:TMatrix2d,m2:TMatrix2d,tol=1.0e-6):bool= abs(m1.tx-m2.tx)<=tol and abs(m1.ty-m2.ty)<=tol -proc `=~`*(m1,m2:TMatrix2d):bool= +proc `=~`*(m1,m2:Matrix2d):bool= ## Checks if `m1`and `m2` is approximately equal, using a ## tolerance of 1e-6. equals(m1,m2) -proc isIdentity*(m:TMatrix2d,tol=1.0e-6):bool= +proc isIdentity*(m:Matrix2d,tol=1.0e-6):bool= ## Checks is a matrix is approximately an identity matrix, ## using `tol` as tolerance for each element. return equals(m,IDMATRIX,tol) -proc apply*(m:TMatrix2d,x,y:var float,translate=false)= +proc apply*(m:Matrix2d,x,y:var float,translate=false)= ## Applies transformation `m` onto `x`,`y`, optionally ## using the translation part of the matrix. if translate: # positional style transform @@ -329,29 +329,29 @@ proc apply*(m:TMatrix2d,x,y:var float,translate=false)= # *************************************** -# TVector2d implementation +# Vector2d implementation # *************************************** -proc vector2d*(x,y:float):TVector2d = #forward decl. +proc vector2d*(x,y:float):Vector2d = #forward decl. result.x=x result.y=y -proc polarVector2d*(ang:float,len:float):TVector2d {.noInit.} = +proc polarVector2d*(ang:float,len:float):Vector2d {.noInit.} = ## Returns a new vector with angle `ang` and magnitude `len` result.x=cos(ang)*len result.y=sin(ang)*len -proc slopeVector2d*(slope:float,len:float):TVector2d {.noInit.} = +proc slopeVector2d*(slope:float,len:float):Vector2d {.noInit.} = ## Returns a new vector having slope (dy/dx) given by ## `slope`, and a magnitude of `len` let ang=arctan(slope) result.x=cos(ang)*len result.y=sin(ang)*len -proc len*(v:TVector2d):float {.inline.}= +proc len*(v:Vector2d):float {.inline.}= ## Returns the length of the vector. sqrt(v.x*v.x+v.y*v.y) -proc `len=`*(v:var TVector2d,newlen:float) {.noInit.} = +proc `len=`*(v:var Vector2d,newlen:float) {.noInit.} = ## Sets the length of the vector, keeping its angle. let fac=newlen/v.len @@ -369,25 +369,25 @@ proc `len=`*(v:var TVector2d,newlen:float) {.noInit.} = v.x*=fac v.y*=fac -proc sqrLen*(v:TVector2d):float {.inline.}= +proc sqrLen*(v:Vector2d):float {.inline.}= ## Computes the squared length of the vector, which is ## faster than computing the absolute length. v.x*v.x+v.y*v.y -proc angle*(v:TVector2d):float= +proc angle*(v:Vector2d):float= ## Returns the angle of the vector. ## (The counter clockwise plane angle between posetive x axis and `v`) result=arctan2(v.y,v.x) if result<0.0: result+=DEG360 -proc `$` *(v:TVector2d):string= +proc `$` *(v:Vector2d):string= ## String representation of `v` result=rtos(v.x) result.add(",") result.add(rtos(v.y)) -proc `&` *(v:TVector2d,m:TMatrix2d):TVector2d {.noInit.} = +proc `&` *(v:Vector2d,m:Matrix2d):Vector2d {.noInit.} = ## Concatenate vector `v` with a transformation matrix. ## Transforming a vector ignores the translational part ## of the matrix. @@ -399,7 +399,7 @@ proc `&` *(v:TVector2d,m:TMatrix2d):TVector2d {.noInit.} = result.y=v.x*m.ay+v.y*m.by -proc `&=`*(v:var TVector2d,m:TMatrix2d) {.inline.}= +proc `&=`*(v:var Vector2d,m:Matrix2d) {.inline.}= ## Applies transformation `m` onto `v` in place. ## Transforming a vector ignores the translational part ## of the matrix. @@ -412,7 +412,7 @@ proc `&=`*(v:var TVector2d,m:TMatrix2d) {.inline.}= v.x=newx -proc tryNormalize*(v:var TVector2d):bool= +proc tryNormalize*(v:var Vector2d):bool= ## Modifies `v` to have a length of 1.0, keeping its angle. ## If `v` has zero length (and thus no angle), it is left unmodified and ## false is returned, otherwise true is returned. @@ -427,13 +427,13 @@ proc tryNormalize*(v:var TVector2d):bool= return true -proc normalize*(v:var TVector2d) {.inline.}= +proc normalize*(v:var Vector2d) {.inline.}= ## Modifies `v` to have a length of 1.0, keeping its angle. ## If `v` has zero length, an EDivByZero will be raised. if not tryNormalize(v): raise newException(DivByZeroError,"Cannot normalize zero length vector") -proc transformNorm*(v:var TVector2d,t:TMatrix2d)= +proc transformNorm*(v:var Vector2d,t:Matrix2d)= ## Applies a normal direction transformation `t` onto `v` in place. ## The resulting vector is *not* normalized. Transforming a vector ignores the ## translational part of the matrix. If the matrix is not invertible @@ -452,7 +452,7 @@ proc transformNorm*(v:var TVector2d,t:TMatrix2d)= v.y = (t.ax*v.y-t.bx*v.x)/d v.x = newx -proc transformInv*(v:var TVector2d,t:TMatrix2d)= +proc transformInv*(v:var Vector2d,t:Matrix2d)= ## Applies inverse of a transformation `t` to `v` in place. ## This is faster than creating an inverse matrix and apply() it. ## Transforming a vector ignores the translational part @@ -467,7 +467,7 @@ proc transformInv*(v:var TVector2d,t:TMatrix2d)= v.y = (t.ax*v.y-t.ay*v.x)/d v.x = newx -proc transformNormInv*(v:var TVector2d,t:TMatrix2d)= +proc transformNormInv*(v:var Vector2d,t:Matrix2d)= ## Applies an inverse normal direction transformation `t` onto `v` in place. ## This is faster than creating an inverse ## matrix and transformNorm(...) it. Transforming a vector ignores the @@ -484,25 +484,25 @@ proc transformNormInv*(v:var TVector2d,t:TMatrix2d)= v.y=t.by*v.y+t.bx*v.x v.x=newx -proc rotate90*(v:var TVector2d) {.inline.}= +proc rotate90*(v:var Vector2d) {.inline.}= ## Quickly rotates vector `v` 90 degrees counter clockwise, ## without using any trigonometrics. swap(v.x,v.y) v.x= -v.x -proc rotate180*(v:var TVector2d){.inline.}= +proc rotate180*(v:var Vector2d){.inline.}= ## Quickly rotates vector `v` 180 degrees counter clockwise, ## without using any trigonometrics. v.x= -v.x v.y= -v.y -proc rotate270*(v:var TVector2d) {.inline.}= +proc rotate270*(v:var Vector2d) {.inline.}= ## Quickly rotates vector `v` 270 degrees counter clockwise, ## without using any trigonometrics. swap(v.x,v.y) v.y= -v.y -proc rotate*(v:var TVector2d,rad:float) = +proc rotate*(v:var Vector2d,rad:float) = ## Rotates vector `v` `rad` radians in place. let s=sin(rad) @@ -511,18 +511,18 @@ proc rotate*(v:var TVector2d,rad:float) = v.y=c*v.y+s*v.x v.x=newx -proc scale*(v:var TVector2d,fac:float){.inline.}= +proc scale*(v:var Vector2d,fac:float){.inline.}= ## Scales vector `v` `rad` radians in place. v.x*=fac v.y*=fac -proc stretch*(v:var TVector2d,facx,facy:float){.inline.}= +proc stretch*(v:var Vector2d,facx,facy:float){.inline.}= ## Stretches vector `v` `facx` times horizontally, ## and `facy` times vertically. v.x*=facx v.y*=facy -proc mirror*(v:var TVector2d,mirrvec:TVector2d)= +proc mirror*(v:var Vector2d,mirrvec:Vector2d)= ## Mirrors vector `v` using `mirrvec` as mirror direction. let sqx=mirrvec.x*mirrvec.x @@ -539,7 +539,7 @@ proc mirror*(v:var TVector2d,mirrvec:TVector2d)= v.x=newx -proc `-` *(v:TVector2d):TVector2d= +proc `-` *(v:Vector2d):Vector2d= ## Negates a vector result.x= -v.x result.y= -v.y @@ -555,27 +555,27 @@ makeBinOpAssignVector(`*=`) makeBinOpAssignVector(`/=`) -proc dot*(v1,v2:TVector2d):float= +proc dot*(v1,v2:Vector2d):float= ## Computes the dot product of two vectors. ## Returns 0.0 if the vectors are perpendicular. return v1.x*v2.x+v1.y*v2.y -proc cross*(v1,v2:TVector2d):float= +proc cross*(v1,v2:Vector2d):float= ## Computes the cross product of two vectors, also called ## the 'perpendicular dot product' in 2d. Returns 0.0 if the vectors ## are parallel. return v1.x*v2.y-v1.y*v2.x -proc equals*(v1,v2:TVector2d,tol=1.0e-6):bool= +proc equals*(v1,v2:Vector2d,tol=1.0e-6):bool= ## Checks if two vectors approximately equals with a tolerance. return abs(v2.x-v1.x)<=tol and abs(v2.y-v1.y)<=tol -proc `=~` *(v1,v2:TVector2d):bool= +proc `=~` *(v1,v2:Vector2d):bool= ## Checks if two vectors approximately equals with a ## hardcoded tolerance 1e-6 equals(v1,v2) -proc angleTo*(v1,v2:TVector2d):float= +proc angleTo*(v1,v2:Vector2d):float= ## Returns the smallest of the two possible angles ## between `v1` and `v2` in radians. var @@ -585,7 +585,7 @@ proc angleTo*(v1,v2:TVector2d):float= return 0.0 # zero length vector has zero angle to any other vector return safeArccos(dot(nv1,nv2)) -proc angleCCW*(v1,v2:TVector2d):float= +proc angleCCW*(v1,v2:Vector2d):float= ## Returns the counter clockwise plane angle from `v1` to `v2`, ## in range 0 - 2*PI let a=v1.angleTo(v2) @@ -593,7 +593,7 @@ proc angleCCW*(v1,v2:TVector2d):float= return a return DEG360-a -proc angleCW*(v1,v2:TVector2d):float= +proc angleCW*(v1,v2:Vector2d):float= ## Returns the clockwise plane angle from `v1` to `v2`, ## in range 0 - 2*PI let a=v1.angleTo(v2) @@ -601,7 +601,7 @@ proc angleCW*(v1,v2:TVector2d):float= return a return DEG360-a -proc turnAngle*(v1,v2:TVector2d):float= +proc turnAngle*(v1,v2:Vector2d):float= ## Returns the amount v1 should be rotated (in radians) to equal v2, ## in range -PI to PI let a=v1.angleTo(v2) @@ -609,7 +609,7 @@ proc turnAngle*(v1,v2:TVector2d):float= return -a return a -proc bisect*(v1,v2:TVector2d):TVector2d {.noInit.}= +proc bisect*(v1,v2:Vector2d):Vector2d {.noInit.}= ## Computes the bisector between v1 and v2 as a normalized vector. ## If one of the input vectors has zero length, a normalized version ## of the other is returned. If both input vectors has zero length, @@ -645,24 +645,24 @@ proc bisect*(v1,v2:TVector2d):TVector2d {.noInit.}= # *************************************** -# TPoint2d implementation +# Point2d implementation # *************************************** -proc point2d*(x,y:float):TPoint2d = +proc point2d*(x,y:float):Point2d = result.x=x result.y=y -proc sqrDist*(a,b:TPoint2d):float= +proc sqrDist*(a,b:Point2d):float= ## Computes the squared distance between `a` and `b` let dx=b.x-a.x let dy=b.y-a.y result=dx*dx+dy*dy -proc dist*(a,b:TPoint2d):float {.inline.}= +proc dist*(a,b:Point2d):float {.inline.}= ## Computes the absolute distance between `a` and `b` result=sqrt(sqrDist(a,b)) -proc angle*(a,b:TPoint2d):float= +proc angle*(a,b:Point2d):float= ## Computes the angle of the vector `b`-`a` let dx=b.x-a.x let dy=b.y-a.y @@ -670,13 +670,13 @@ proc angle*(a,b:TPoint2d):float= if result<0: result += DEG360 -proc `$` *(p:TPoint2d):string= +proc `$` *(p:Point2d):string= ## String representation of `p` result=rtos(p.x) result.add(",") result.add(rtos(p.y)) -proc `&`*(p:TPoint2d,t:TMatrix2d):TPoint2d {.noInit,inline.} = +proc `&`*(p:Point2d,t:Matrix2d):Point2d {.noInit,inline.} = ## Concatenates a point `p` with a transform `t`, ## resulting in a new, transformed point. @@ -686,14 +686,14 @@ proc `&`*(p:TPoint2d,t:TMatrix2d):TPoint2d {.noInit,inline.} = result.x=p.x*t.ax+p.y*t.bx+t.tx result.y=p.x*t.ay+p.y*t.by+t.ty -proc `&=` *(p:var TPoint2d,t:TMatrix2d) {.inline.}= +proc `&=` *(p:var Point2d,t:Matrix2d) {.inline.}= ## Applies transformation `t` onto `p` in place. let newx=p.x*t.ax+p.y*t.bx+t.tx p.y=p.x*t.ay+p.y*t.by+t.ty p.x=newx -proc transformInv*(p:var TPoint2d,t:TMatrix2d){.inline.}= +proc transformInv*(p:var Point2d,t:Matrix2d){.inline.}= ## Applies the inverse of transformation `t` onto `p` in place. ## If the matrix is not invertable (determinant=0) , EDivByZero will ## be raised. @@ -710,48 +710,48 @@ proc transformInv*(p:var TPoint2d,t:TMatrix2d){.inline.}= p.x=newx -proc `+`*(p:TPoint2d,v:TVector2d):TPoint2d {.noInit,inline.} = +proc `+`*(p:Point2d,v:Vector2d):Point2d {.noInit,inline.} = ## Adds a vector `v` to a point `p`, resulting ## in a new point. result.x=p.x+v.x result.y=p.y+v.y -proc `+=`*(p:var TPoint2d,v:TVector2d) {.noInit,inline.} = +proc `+=`*(p:var Point2d,v:Vector2d) {.noInit,inline.} = ## Adds a vector `v` to a point `p` in place. p.x+=v.x p.y+=v.y -proc `-`*(p:TPoint2d,v:TVector2d):TPoint2d {.noInit,inline.} = +proc `-`*(p:Point2d,v:Vector2d):Point2d {.noInit,inline.} = ## Subtracts a vector `v` from a point `p`, resulting ## in a new point. result.x=p.x-v.x result.y=p.y-v.y -proc `-`*(p1,p2:TPoint2d):TVector2d {.noInit,inline.} = +proc `-`*(p1,p2:Point2d):Vector2d {.noInit,inline.} = ## Subtracts `p2`from `p1` resulting in a difference vector. result.x=p1.x-p2.x result.y=p1.y-p2.y -proc `-=`*(p:var TPoint2d,v:TVector2d) {.noInit,inline.} = +proc `-=`*(p:var Point2d,v:Vector2d) {.noInit,inline.} = ## Subtracts a vector `v` from a point `p` in place. p.x-=v.x p.y-=v.y -proc equals(p1,p2:TPoint2d,tol=1.0e-6):bool {.inline.}= +proc equals(p1,p2:Point2d,tol=1.0e-6):bool {.inline.}= ## Checks if two points approximately equals with a tolerance. return abs(p2.x-p1.x)<=tol and abs(p2.y-p1.y)<=tol -proc `=~`*(p1,p2:TPoint2d):bool {.inline.}= +proc `=~`*(p1,p2:Point2d):bool {.inline.}= ## Checks if two vectors approximately equals with a ## hardcoded tolerance 1e-6 equals(p1,p2) -proc polar*(p:TPoint2d,ang,dist:float):TPoint2d {.noInit.} = +proc polar*(p:Point2d,ang,dist:float):Point2d {.noInit.} = ## Returns a point with a given angle and distance away from `p` result.x=p.x+cos(ang)*dist result.y=p.y+sin(ang)*dist -proc rotate*(p:var TPoint2d,rad:float)= +proc rotate*(p:var Point2d,rad:float)= ## Rotates a point in place `rad` radians around origo. let c=cos(rad) @@ -760,7 +760,7 @@ proc rotate*(p:var TPoint2d,rad:float)= p.y=p.y*c+p.x*s p.x=newx -proc rotate*(p:var TPoint2d,rad:float,org:TPoint2d)= +proc rotate*(p:var Point2d,rad:float,org:Point2d)= ## Rotates a point in place `rad` radians using `org` as ## center of rotation. let @@ -770,50 +770,50 @@ proc rotate*(p:var TPoint2d,rad:float,org:TPoint2d)= p.y=(p.y - org.y) * c + (p.x - org.x) * s + org.y p.x=newx -proc scale*(p:var TPoint2d,fac:float) {.inline.}= +proc scale*(p:var Point2d,fac:float) {.inline.}= ## Scales a point in place `fac` times with world origo as origin. p.x*=fac p.y*=fac -proc scale*(p:var TPoint2d,fac:float,org:TPoint2d){.inline.}= +proc scale*(p:var Point2d,fac:float,org:Point2d){.inline.}= ## Scales the point in place `fac` times with `org` as origin. p.x=(p.x - org.x) * fac + org.x p.y=(p.y - org.y) * fac + org.y -proc stretch*(p:var TPoint2d,facx,facy:float){.inline.}= +proc stretch*(p:var Point2d,facx,facy:float){.inline.}= ## Scales a point in place non uniformly `facx` and `facy` times with ## world origo as origin. p.x*=facx p.y*=facy -proc stretch*(p:var TPoint2d,facx,facy:float,org:TPoint2d){.inline.}= +proc stretch*(p:var Point2d,facx,facy:float,org:Point2d){.inline.}= ## Scales the point in place non uniformly `facx` and `facy` times with ## `org` as origin. p.x=(p.x - org.x) * facx + org.x p.y=(p.y - org.y) * facy + org.y -proc move*(p:var TPoint2d,dx,dy:float){.inline.}= +proc move*(p:var Point2d,dx,dy:float){.inline.}= ## Translates a point `dx`, `dy` in place. p.x+=dx p.y+=dy -proc move*(p:var TPoint2d,v:TVector2d){.inline.}= +proc move*(p:var Point2d,v:Vector2d){.inline.}= ## Translates a point with vector `v` in place. p.x+=v.x p.y+=v.y -proc sgnArea*(a,b,c:TPoint2d):float= +proc sgnArea*(a,b,c:Point2d):float= ## Computes the signed area of the triangle thru points `a`,`b` and `c` ## result>0.0 for counter clockwise triangle ## result<0.0 for clockwise triangle ## This is commonly used to determinate side of a point with respect to a line. return ((b.x - c.x) * (b.y - a.y)-(b.y - c.y) * (b.x - a.x))*0.5 -proc area*(a,b,c:TPoint2d):float= +proc area*(a,b,c:Point2d):float= ## Computes the area of the triangle thru points `a`,`b` and `c` return abs(sgnArea(a,b,c)) -proc closestPoint*(p:TPoint2d,pts:varargs[TPoint2d]):TPoint2d= +proc closestPoint*(p:Point2d,pts:varargs[Point2d]):Point2d= ## Returns a point selected from `pts`, that has the closest ## euclidean distance to `p` assert(pts.len>0) # must have at least one point diff --git a/lib/pure/basic3d.nim b/lib/pure/basic3d.nim index 5a943dd05..b99357e3a 100644 --- a/lib/pure/basic3d.nim +++ b/lib/pure/basic3d.nim @@ -25,25 +25,25 @@ import times ## ## # Create a matrix which first rotates, then scales and at last translates ## -## var m:TMatrix3d=rotate(PI,vector3d(1,1,2.5)) & scale(2.0) & move(100.0,200.0,300.0) +## var m:Matrix3d=rotate(PI,vector3d(1,1,2.5)) & scale(2.0) & move(100.0,200.0,300.0) ## ## # Create a 3d point at (100,150,200) and a vector (5,2,3) ## -## var pt:TPoint3d=point3d(100.0,150.0,200.0) +## var pt:Point3d=point3d(100.0,150.0,200.0) ## -## var vec:TVector3d=vector3d(5.0,2.0,3.0) +## var vec:Vector3d=vector3d(5.0,2.0,3.0) ## ## ## pt &= m # transforms pt in place ## -## var pt2:TPoint3d=pt & m #concatenates pt with m and returns a new point +## var pt2:Point3d=pt & m #concatenates pt with m and returns a new point ## -## var vec2:TVector3d=vec & m #concatenates vec with m and returns a new vector +## var vec2:Vector3d=vec & m #concatenates vec with m and returns a new vector type - TMatrix3d* =object + Matrix3d* =object ## Implements a row major 3d matrix, which means ## transformations are applied the order they are concatenated. ## This matrix is stored as an 4x4 matrix: @@ -52,31 +52,31 @@ type ## [ cx cy cz cw ] ## [ tx ty tz tw ] ax*,ay*,az*,aw*, bx*,by*,bz*,bw*, cx*,cy*,cz*,cw*, tx*,ty*,tz*,tw*:float - TPoint3d* = object + Point3d* = object ## Implements a non-homegeneous 2d point stored as ## an `x` , `y` and `z` coordinate. x*,y*,z*:float - TVector3d* = object + Vector3d* = object ## Implements a 3d **direction vector** stored as ## an `x` , `y` and `z` coordinate. Direction vector means, ## that when transforming a vector with a matrix, the translational ## part of the matrix is ignored. x*,y*,z*:float - +{.deprecated: [TMatrix3d: Matrix3d, TPoint3d: Point3d, TVector3d: Vector3d].} # Some forward declarations -proc matrix3d*(ax,ay,az,aw,bx,by,bz,bw,cx,cy,cz,cw,tx,ty,tz,tw:float):TMatrix3d {.noInit.} +proc matrix3d*(ax,ay,az,aw,bx,by,bz,bw,cx,cy,cz,cw,tx,ty,tz,tw:float):Matrix3d {.noInit.} ## Creates a new 4x4 3d transformation matrix. ## `ax` , `ay` , `az` is the local x axis. ## `bx` , `by` , `bz` is the local y axis. ## `cx` , `cy` , `cz` is the local z axis. ## `tx` , `ty` , `tz` is the translation. -proc vector3d*(x,y,z:float):TVector3d {.noInit,inline.} +proc vector3d*(x,y,z:float):Vector3d {.noInit,inline.} ## Returns a new 3d vector (`x`,`y`,`z`) -proc point3d*(x,y,z:float):TPoint3d {.noInit,inline.} +proc point3d*(x,y,z:float):Point3d {.noInit,inline.} ## Returns a new 4d point (`x`,`y`,`z`) -proc tryNormalize*(v:var TVector3d):bool +proc tryNormalize*(v:var Vector3d):bool ## Modifies `v` to have a length of 1.0, keeping its angle. ## If `v` has zero length (and thus no angle), it is left unmodified and false is ## returned, otherwise true is returned. @@ -84,19 +84,19 @@ proc tryNormalize*(v:var TVector3d):bool let - IDMATRIX*:TMatrix3d=matrix3d( + IDMATRIX*:Matrix3d=matrix3d( 1.0,0.0,0.0,0.0, 0.0,1.0,0.0,0.0, 0.0,0.0,1.0,0.0, 0.0,0.0,0.0,1.0) ## Quick access to a 3d identity matrix - ORIGO*:TPoint3d=point3d(0.0,0.0,0.0) + ORIGO*:Point3d=point3d(0.0,0.0,0.0) ## Quick access to point (0,0) - XAXIS*:TVector3d=vector3d(1.0,0.0,0.0) + XAXIS*:Vector3d=vector3d(1.0,0.0,0.0) ## Quick access to an 3d x-axis unit vector - YAXIS*:TVector3d=vector3d(0.0,1.0,0.0) + YAXIS*:Vector3d=vector3d(0.0,1.0,0.0) ## Quick access to an 3d y-axis unit vector - ZAXIS*:TVector3d=vector3d(0.0,0.0,1.0) + ZAXIS*:Vector3d=vector3d(0.0,0.0,1.0) ## Quick access to an 3d z-axis unit vector @@ -116,27 +116,27 @@ proc safeArccos(v:float):float= template makeBinOpVector(s:expr)= ## implements binary operators + , - , * and / for vectors - proc s*(a,b:TVector3d):TVector3d {.inline,noInit.} = + proc s*(a,b:Vector3d):Vector3d {.inline,noInit.} = vector3d(s(a.x,b.x),s(a.y,b.y),s(a.z,b.z)) - proc s*(a:TVector3d,b:float):TVector3d {.inline,noInit.} = + proc s*(a:Vector3d,b:float):Vector3d {.inline,noInit.} = vector3d(s(a.x,b),s(a.y,b),s(a.z,b)) - proc s*(a:float,b:TVector3d):TVector3d {.inline,noInit.} = + proc s*(a:float,b:Vector3d):Vector3d {.inline,noInit.} = vector3d(s(a,b.x),s(a,b.y),s(a,b.z)) template makeBinOpAssignVector(s:expr)= ## implements inplace binary operators += , -= , /= and *= for vectors - proc s*(a:var TVector3d,b:TVector3d) {.inline.} = + proc s*(a:var Vector3d,b:Vector3d) {.inline.} = s(a.x,b.x) ; s(a.y,b.y) ; s(a.z,b.z) - proc s*(a:var TVector3d,b:float) {.inline.} = + proc s*(a:var Vector3d,b:float) {.inline.} = s(a.x,b) ; s(a.y,b) ; s(a.z,b) # *************************************** -# TMatrix3d implementation +# Matrix3d implementation # *************************************** -proc setElements*(t:var TMatrix3d,ax,ay,az,aw,bx,by,bz,bw,cx,cy,cz,cw,tx,ty,tz,tw:float) {.inline.}= +proc setElements*(t:var Matrix3d,ax,ay,az,aw,bx,by,bz,bw,cx,cy,cz,cw,tx,ty,tz,tw:float) {.inline.}= ## Sets arbitrary elements in an exisitng matrix. t.ax=ax t.ay=ay @@ -155,10 +155,10 @@ proc setElements*(t:var TMatrix3d,ax,ay,az,aw,bx,by,bz,bw,cx,cy,cz,cw,tx,ty,tz,t t.tz=tz t.tw=tw -proc matrix3d*(ax,ay,az,aw,bx,by,bz,bw,cx,cy,cz,cw,tx,ty,tz,tw:float):TMatrix3d = +proc matrix3d*(ax,ay,az,aw,bx,by,bz,bw,cx,cy,cz,cw,tx,ty,tz,tw:float):Matrix3d = result.setElements(ax,ay,az,aw,bx,by,bz,bw,cx,cy,cz,cw,tx,ty,tz,tw) -proc `&`*(a,b:TMatrix3d):TMatrix3d {.noinit.} = +proc `&`*(a,b:Matrix3d):Matrix3d {.noinit.} = ## Concatenates matrices returning a new matrix. result.setElements( a.aw*b.tx+a.az*b.cx+a.ay*b.bx+a.ax*b.ax, @@ -182,36 +182,36 @@ proc `&`*(a,b:TMatrix3d):TMatrix3d {.noinit.} = a.tw*b.tw+a.tz*b.cw+a.ty*b.bw+a.tx*b.aw) -proc scale*(s:float):TMatrix3d {.noInit.} = +proc scale*(s:float):Matrix3d {.noInit.} = ## Returns a new scaling matrix. result.setElements(s,0,0,0, 0,s,0,0, 0,0,s,0, 0,0,0,1) -proc scale*(s:float,org:TPoint3d):TMatrix3d {.noInit.} = +proc scale*(s:float,org:Point3d):Matrix3d {.noInit.} = ## Returns a new scaling matrix using, `org` as scale origin. result.setElements(s,0,0,0, 0,s,0,0, 0,0,s,0, org.x-s*org.x,org.y-s*org.y,org.z-s*org.z,1.0) -proc stretch*(sx,sy,sz:float):TMatrix3d {.noInit.} = +proc stretch*(sx,sy,sz:float):Matrix3d {.noInit.} = ## Returns new a stretch matrix, which is a ## scale matrix with non uniform scale in x,y and z. result.setElements(sx,0,0,0, 0,sy,0,0, 0,0,sz,0, 0,0,0,1) -proc stretch*(sx,sy,sz:float,org:TPoint3d):TMatrix3d {.noInit.} = +proc stretch*(sx,sy,sz:float,org:Point3d):Matrix3d {.noInit.} = ## Returns a new stretch matrix, which is a ## scale matrix with non uniform scale in x,y and z. ## `org` is used as stretch origin. result.setElements(sx,0,0,0, 0,sy,0,0, 0,0,sz,0, org.x-sx*org.x,org.y-sy*org.y,org.z-sz*org.z,1) -proc move*(dx,dy,dz:float):TMatrix3d {.noInit.} = +proc move*(dx,dy,dz:float):Matrix3d {.noInit.} = ## Returns a new translation matrix. result.setElements(1,0,0,0, 0,1,0,0, 0,0,1,0, dx,dy,dz,1) -proc move*(v:TVector3d):TMatrix3d {.noInit.} = +proc move*(v:Vector3d):Matrix3d {.noInit.} = ## Returns a new translation matrix from a vector. result.setElements(1,0,0,0, 0,1,0,0, 0,0,1,0, v.x,v.y,v.z,1) -proc rotate*(angle:float,axis:TVector3d):TMatrix3d {.noInit.}= +proc rotate*(angle:float,axis:Vector3d):Matrix3d {.noInit.}= ## Creates a rotation matrix that rotates `angle` radians over ## `axis`, which passes through origo. @@ -242,7 +242,7 @@ proc rotate*(angle:float,axis:TVector3d):TMatrix3d {.noInit.}= uwomc+vsi, vwomc-usi, w2+(1.0-w2)*cs, 0.0, 0.0,0.0,0.0,1.0) -proc rotate*(angle:float,org:TPoint3d,axis:TVector3d):TMatrix3d {.noInit.}= +proc rotate*(angle:float,org:Point3d,axis:Vector3d):Matrix3d {.noInit.}= ## Creates a rotation matrix that rotates `angle` radians over ## `axis`, which passes through `org`. @@ -282,7 +282,7 @@ proc rotate*(angle:float,org:TPoint3d,axis:TVector3d):TMatrix3d {.noInit.}= (c*(u2+v2)-w*(a*u+b*v))*omc+(a*v-b*u)*si,1.0) -proc rotateX*(angle:float):TMatrix3d {.noInit.}= +proc rotateX*(angle:float):Matrix3d {.noInit.}= ## Creates a matrix that rotates around the x-axis with `angle` radians, ## which is also called a 'roll' matrix. let @@ -294,7 +294,7 @@ proc rotateX*(angle:float):TMatrix3d {.noInit.}= 0,-s,c,0, 0,0,0,1) -proc rotateY*(angle:float):TMatrix3d {.noInit.}= +proc rotateY*(angle:float):Matrix3d {.noInit.}= ## Creates a matrix that rotates around the y-axis with `angle` radians, ## which is also called a 'pitch' matrix. let @@ -306,7 +306,7 @@ proc rotateY*(angle:float):TMatrix3d {.noInit.}= s,0,c,0, 0,0,0,1) -proc rotateZ*(angle:float):TMatrix3d {.noInit.}= +proc rotateZ*(angle:float):Matrix3d {.noInit.}= ## Creates a matrix that rotates around the z-axis with `angle` radians, ## which is also called a 'yaw' matrix. let @@ -318,7 +318,7 @@ proc rotateZ*(angle:float):TMatrix3d {.noInit.}= 0,0,1,0, 0,0,0,1) -proc isUniform*(m:TMatrix3d,tol=1.0e-6):bool= +proc isUniform*(m:Matrix3d,tol=1.0e-6):bool= ## Checks if the transform is uniform, that is ## perpendicular axes of equal length, which means (for example) ## it cannot transform a sphere into an ellipsoid. @@ -341,7 +341,7 @@ proc isUniform*(m:TMatrix3d,tol=1.0e-6):bool= -proc mirror*(planeperp:TVector3d):TMatrix3d {.noInit.}= +proc mirror*(planeperp:Vector3d):Matrix3d {.noInit.}= ## Creates a matrix that mirrors over the plane that has `planeperp` as normal, ## and passes through origo. `planeperp` does not need to be normalized. @@ -365,7 +365,7 @@ proc mirror*(planeperp:TVector3d):TMatrix3d {.noInit.}= 0,0,0,1) -proc mirror*(org:TPoint3d,planeperp:TVector3d):TMatrix3d {.noInit.}= +proc mirror*(org:Point3d,planeperp:Vector3d):Matrix3d {.noInit.}= ## Creates a matrix that mirrors over the plane that has `planeperp` as normal, ## and passes through `org`. `planeperp` does not need to be normalized. @@ -400,7 +400,7 @@ proc mirror*(org:TPoint3d,planeperp:TVector3d):TMatrix3d {.noInit.}= 2*(cc*tz+bc*ty+ac*tx) ,1) -proc determinant*(m:TMatrix3d):float= +proc determinant*(m:Matrix3d):float= ## Computes the determinant of matrix `m`. # This computation is gotten from ratsimp(optimize(determinant(m))) @@ -419,7 +419,7 @@ proc determinant*(m:TMatrix3d):float= (O3*m.az-O5*m.ay+O6*m.ax)*m.bw -proc inverse*(m:TMatrix3d):TMatrix3d {.noInit.}= +proc inverse*(m:Matrix3d):Matrix3d {.noInit.}= ## Computes the inverse of matrix `m`. If the matrix ## determinant is zero, thus not invertible, a EDivByZero ## will be raised. @@ -461,7 +461,7 @@ proc inverse*(m:TMatrix3d):TMatrix3d {.noInit.}= (-m.ax*O7+m.ay*O14-m.az*O18)/det , (m.ax*O10-m.ay*O16+m.az*O19)/det) -proc equals*(m1:TMatrix3d,m2:TMatrix3d,tol=1.0e-6):bool= +proc equals*(m1:Matrix3d,m2:Matrix3d,tol=1.0e-6):bool= ## Checks if all elements of `m1`and `m2` is equal within ## a given tolerance `tol`. return @@ -482,42 +482,42 @@ proc equals*(m1:TMatrix3d,m2:TMatrix3d,tol=1.0e-6):bool= abs(m1.tz-m2.tz)<=tol and abs(m1.tw-m2.tw)<=tol -proc `=~`*(m1,m2:TMatrix3d):bool= +proc `=~`*(m1,m2:Matrix3d):bool= ## Checks if `m1` and `m2` is approximately equal, using a ## tolerance of 1e-6. equals(m1,m2) -proc transpose*(m:TMatrix3d):TMatrix3d {.noInit.}= +proc transpose*(m:Matrix3d):Matrix3d {.noInit.}= ## Returns the transpose of `m` result.setElements(m.ax,m.bx,m.cx,m.tx,m.ay,m.by,m.cy,m.ty,m.az,m.bz,m.cz,m.tz,m.aw,m.bw,m.cw,m.tw) -proc getXAxis*(m:TMatrix3d):TVector3d {.noInit.}= +proc getXAxis*(m:Matrix3d):Vector3d {.noInit.}= ## Gets the local x axis of `m` result.x=m.ax result.y=m.ay result.z=m.az -proc getYAxis*(m:TMatrix3d):TVector3d {.noInit.}= +proc getYAxis*(m:Matrix3d):Vector3d {.noInit.}= ## Gets the local y axis of `m` result.x=m.bx result.y=m.by result.z=m.bz -proc getZAxis*(m:TMatrix3d):TVector3d {.noInit.}= +proc getZAxis*(m:Matrix3d):Vector3d {.noInit.}= ## Gets the local y axis of `m` result.x=m.cx result.y=m.cy result.z=m.cz -proc `$`*(m:TMatrix3d):string= +proc `$`*(m:Matrix3d):string= ## String representation of `m` return rtos(m.ax) & "," & rtos(m.ay) & "," & rtos(m.az) & "," & rtos(m.aw) & "\n" & rtos(m.bx) & "," & rtos(m.by) & "," & rtos(m.bz) & "," & rtos(m.bw) & "\n" & rtos(m.cx) & "," & rtos(m.cy) & "," & rtos(m.cz) & "," & rtos(m.cw) & "\n" & rtos(m.tx) & "," & rtos(m.ty) & "," & rtos(m.tz) & "," & rtos(m.tw) -proc apply*(m:TMatrix3d, x,y,z:var float, translate=false)= +proc apply*(m:Matrix3d, x,y,z:var float, translate=false)= ## Applies transformation `m` onto `x` , `y` , `z` , optionally ## using the translation part of the matrix. let @@ -535,18 +535,18 @@ proc apply*(m:TMatrix3d, x,y,z:var float, translate=false)= z+=m.tz # *************************************** -# TVector3d implementation +# Vector3d implementation # *************************************** -proc vector3d*(x,y,z:float):TVector3d= +proc vector3d*(x,y,z:float):Vector3d= result.x=x result.y=y result.z=z -proc len*(v:TVector3d):float= +proc len*(v:Vector3d):float= ## Returns the length of the vector `v`. sqrt(v.x*v.x+v.y*v.y+v.z*v.z) -proc `len=`*(v:var TVector3d,newlen:float) {.noInit.} = +proc `len=`*(v:var Vector3d,newlen:float) {.noInit.} = ## Sets the length of the vector, keeping its direction. ## If the vector has zero length before changing it's length, ## an arbitrary vector of the requested length is returned. @@ -571,12 +571,12 @@ proc `len=`*(v:var TVector3d,newlen:float) {.noInit.} = v.z*=fac -proc sqrLen*(v:TVector3d):float {.inline.}= +proc sqrLen*(v:Vector3d):float {.inline.}= ## Computes the squared length of the vector, which is ## faster than computing the absolute length. return v.x*v.x+v.y*v.y+v.z*v.z -proc `$` *(v:TVector3d):string= +proc `$` *(v:Vector3d):string= ## String representation of `v` result=rtos(v.x) result.add(",") @@ -584,7 +584,7 @@ proc `$` *(v:TVector3d):string= result.add(",") result.add(rtos(v.z)) -proc `&` *(v:TVector3d,m:TMatrix3d):TVector3d {.noInit.} = +proc `&` *(v:Vector3d,m:Matrix3d):Vector3d {.noInit.} = ## Concatenate vector `v` with a transformation matrix. ## Transforming a vector ignores the translational part ## of the matrix. @@ -601,7 +601,7 @@ proc `&` *(v:TVector3d,m:TMatrix3d):TVector3d {.noInit.} = result.x=newx -proc `&=` *(v:var TVector3d,m:TMatrix3d) {.noInit.} = +proc `&=` *(v:var Vector3d,m:Matrix3d) {.noInit.} = ## Applies transformation `m` onto `v` in place. ## Transforming a vector ignores the translational part ## of the matrix. @@ -618,7 +618,7 @@ proc `&=` *(v:var TVector3d,m:TMatrix3d) {.noInit.} = v.y=newy v.x=newx -proc transformNorm*(v:var TVector3d,m:TMatrix3d)= +proc transformNorm*(v:var Vector3d,m:Matrix3d)= ## Applies a normal direction transformation `m` onto `v` in place. ## The resulting vector is *not* normalized. Transforming a vector ignores the ## translational part of the matrix. If the matrix is not invertible @@ -631,7 +631,7 @@ proc transformNorm*(v:var TVector3d,m:TMatrix3d)= # (possibly by hardware) as well as having a consistent API with the 2d version. v&=transpose(inverse(m)) -proc transformInv*(v:var TVector3d,m:TMatrix3d)= +proc transformInv*(v:var Vector3d,m:Matrix3d)= ## Applies the inverse of `m` on vector `v`. Transforming a vector ignores ## the translational part of the matrix. Transforming a vector ignores the ## translational part of the matrix. @@ -642,7 +642,7 @@ proc transformInv*(v:var TVector3d,m:TMatrix3d)= # (possibly by hardware) as well as having a consistent API with the 2d version. v&=m.inverse -proc transformNormInv*(vec:var TVector3d,m:TMatrix3d)= +proc transformNormInv*(vec:var Vector3d,m:Matrix3d)= ## Applies an inverse normal direction transformation `m` onto `v` in place. ## This is faster than creating an inverse ## matrix and transformNorm(...) it. Transforming a vector ignores the @@ -651,7 +651,7 @@ proc transformNormInv*(vec:var TVector3d,m:TMatrix3d)= # see vector2d:s equivalent for a deeper look how/why this works vec&=m.transpose -proc tryNormalize*(v:var TVector3d):bool= +proc tryNormalize*(v:var Vector3d):bool= ## Modifies `v` to have a length of 1.0, keeping its angle. ## If `v` has zero length (and thus no angle), it is left unmodified and false is ## returned, otherwise true is returned. @@ -666,13 +666,13 @@ proc tryNormalize*(v:var TVector3d):bool= return true -proc normalize*(v:var TVector3d) {.inline.}= +proc normalize*(v:var Vector3d) {.inline.}= ## Modifies `v` to have a length of 1.0, keeping its angle. ## If `v` has zero length, an EDivByZero will be raised. if not tryNormalize(v): raise newException(DivByZeroError,"Cannot normalize zero length vector") -proc rotate*(vec:var TVector3d,angle:float,axis:TVector3d)= +proc rotate*(vec:var Vector3d,angle:float,axis:Vector3d)= ## Rotates `vec` in place, with `angle` radians over `axis`, which passes ## through origo. @@ -699,19 +699,19 @@ proc rotate*(vec:var TVector3d,angle:float,axis:TVector3d)= vec.y=v*uxyzomc+y*cs+(w*x-u*z)*si vec.z=w*uxyzomc+z*cs+(u*y-v*x)*si -proc scale*(v:var TVector3d,s:float)= +proc scale*(v:var Vector3d,s:float)= ## Scales the vector in place with factor `s` v.x*=s v.y*=s v.z*=s -proc stretch*(v:var TVector3d,sx,sy,sz:float)= +proc stretch*(v:var Vector3d,sx,sy,sz:float)= ## Scales the vector non uniformly with factors `sx` , `sy` , `sz` v.x*=sx v.y*=sy v.z*=sz -proc mirror*(v:var TVector3d,planeperp:TVector3d)= +proc mirror*(v:var Vector3d,planeperp:Vector3d)= ## Computes the mirrored vector of `v` over the plane ## that has `planeperp` as normal direction. ## `planeperp` does not need to be normalized. @@ -735,7 +735,7 @@ proc mirror*(v:var TVector3d,planeperp:TVector3d)= v.z= -2*(c*c*z+bc*y+ac*x)+z -proc `-` *(v:TVector3d):TVector3d= +proc `-` *(v:Vector3d):Vector3d= ## Negates a vector result.x= -v.x result.y= -v.y @@ -751,12 +751,12 @@ makeBinOpAssignVector(`-=`) makeBinOpAssignVector(`*=`) makeBinOpAssignVector(`/=`) -proc dot*(v1,v2:TVector3d):float {.inline.}= +proc dot*(v1,v2:Vector3d):float {.inline.}= ## Computes the dot product of two vectors. ## Returns 0.0 if the vectors are perpendicular. return v1.x*v2.x+v1.y*v2.y+v1.z*v2.z -proc cross*(v1,v2:TVector3d):TVector3d {.inline.}= +proc cross*(v1,v2:Vector3d):Vector3d {.inline.}= ## Computes the cross product of two vectors. ## The result is a vector which is perpendicular ## to the plane of `v1` and `v2`, which means @@ -766,16 +766,16 @@ proc cross*(v1,v2:TVector3d):TVector3d {.inline.}= result.y = (v1.z * v2.x) - (v2.z * v1.x) result.z = (v1.x * v2.y) - (v2.x * v1.y) -proc equals*(v1,v2:TVector3d,tol=1.0e-6):bool= +proc equals*(v1,v2:Vector3d,tol=1.0e-6):bool= ## Checks if two vectors approximately equals with a tolerance. return abs(v2.x-v1.x)<=tol and abs(v2.y-v1.y)<=tol and abs(v2.z-v1.z)<=tol -proc `=~` *(v1,v2:TVector3d):bool= +proc `=~` *(v1,v2:Vector3d):bool= ## Checks if two vectors approximately equals with a ## hardcoded tolerance 1e-6 equals(v1,v2) -proc angleTo*(v1,v2:TVector3d):float= +proc angleTo*(v1,v2:Vector3d):float= ## Returns the smallest angle between v1 and v2, ## which is in range 0-PI var @@ -785,13 +785,13 @@ proc angleTo*(v1,v2:TVector3d):float= return 0.0 # zero length vector has zero angle to any other vector return safeArccos(dot(nv1,nv2)) -proc arbitraryAxis*(norm:TVector3d):TMatrix3d {.noInit.}= +proc arbitraryAxis*(norm:Vector3d):Matrix3d {.noInit.}= ## Computes the rotation matrix that would transform ## world z vector into `norm`. The inverse of this matrix ## is useful to transform a planar 3d object to 2d space. ## This is the same algorithm used to interpret DXF and DWG files. const lim=1.0/64.0 - var ax,ay,az:TVector3d + var ax,ay,az:Vector3d if abs(norm.x) counter) result = (length * 2 < counter * 3) or (length - counter < 4) -proc nextTry(h, maxHash: THash): THash {.inline.} = +proc nextTry(h, maxHash: Hash): Hash {.inline.} = result = ((5 * h) + 1) and maxHash proc intSetGet(t: IntSet, key: int): PTrunk = @@ -59,7 +59,7 @@ proc intSetGet(t: IntSet, key: int): PTrunk = h = nextTry(h, t.max) result = nil -proc intSetRawInsert(t: IntSet, data: var TTrunkSeq, desc: PTrunk) = +proc intSetRawInsert(t: IntSet, data: var TrunkSeq, desc: PTrunk) = var h = desc.key and t.max while data[h] != nil: assert(data[h] != desc) @@ -68,7 +68,7 @@ proc intSetRawInsert(t: IntSet, data: var TTrunkSeq, desc: PTrunk) = data[h] = desc proc intSetEnlarge(t: var IntSet) = - var n: TTrunkSeq + var n: TrunkSeq var oldMax = t.max t.max = ((t.max + 1) * 2) - 1 newSeq(n, t.max + 1) diff --git a/lib/pure/collections/sets.nim b/lib/pure/collections/sets.nim index 280e0eeba..3d4de8fdc 100644 --- a/lib/pure/collections/sets.nim +++ b/lib/pure/collections/sets.nim @@ -29,7 +29,7 @@ when not defined(nimhygiene): # codes should never be needed, and this can pack more entries per cache-line. # Losing hcode entirely is also possible - if some element value is forbidden. type - KeyValuePair[A] = tuple[hcode: THash, key: A] + KeyValuePair[A] = tuple[hcode: Hash, key: A] KeyValuePairSeq[A] = seq[KeyValuePair[A]] HashSet* {.myShallow.}[A] = object ## \ ## A generic hash set. @@ -43,10 +43,10 @@ type # hcode for real keys cannot be zero. hcode==0 signifies an empty slot. These # two procs retain clarity of that encoding without the space cost of an enum. -proc isEmpty(hcode: THash): bool {.inline.} = +proc isEmpty(hcode: Hash): bool {.inline.} = result = hcode == 0 -proc isFilled(hcode: THash): bool {.inline.} = +proc isFilled(hcode: Hash): bool {.inline.} = result = hcode != 0 proc isValid*[A](s: HashSet[A]): bool = @@ -58,7 +58,7 @@ proc isValid*[A](s: HashSet[A]): bool = ## initialized. Example: ## ## .. code-block :: - ## proc savePreferences(options: TSet[string]) = + ## proc savePreferences(options: Set[string]) = ## assert options.isValid, "Pass an initialized set!" ## # Do stuff here, may crash in release builds! result = not s.data.isNil @@ -72,7 +72,7 @@ proc len*[A](s: HashSet[A]): int = ## ## .. code-block:: ## - ## var values: TSet[int] + ## var values: Set[int] ## assert(not values.isValid) ## assert values.len == 0 result = s.counter @@ -123,15 +123,15 @@ proc rightSize*(count: Natural): int {.inline.} = ## Internally, we want mustRehash(rightSize(x), x) == false. result = nextPowerOfTwo(count * 3 div 2 + 4) -proc nextTry(h, maxHash: THash): THash {.inline.} = +proc nextTry(h, maxHash: Hash): Hash {.inline.} = result = (h + 1) and maxHash template rawGetKnownHCImpl() {.dirty.} = - var h: THash = hc and high(s.data) # start with real hash value + var h: Hash = hc and high(s.data) # start with real hash value while isFilled(s.data[h].hcode): # Compare hc THEN key with boolean short circuit. This makes the common case # zero ==key's for missing (e.g.inserts) and exactly one ==key for present. - # It does slow down succeeding lookups by one extra THash cmp&and..usually + # It does slow down succeeding lookups by one extra Hash cmp&and..usually # just a few clock cycles, generally worth it for any non-integer-like A. if s.data[h].hcode == hc and s.data[h].key == key: # compare hc THEN key return h @@ -148,10 +148,10 @@ template rawInsertImpl() {.dirty.} = data[h].key = key data[h].hcode = hc -proc rawGetKnownHC[A](s: HashSet[A], key: A, hc: THash): int {.inline.} = +proc rawGetKnownHC[A](s: HashSet[A], key: A, hc: Hash): int {.inline.} = rawGetKnownHCImpl() -proc rawGet[A](s: HashSet[A], key: A, hc: var THash): int {.inline.} = +proc rawGet[A](s: HashSet[A], key: A, hc: var Hash): int {.inline.} = rawGetImpl() proc mget*[A](s: var HashSet[A], key: A): var A = @@ -160,7 +160,7 @@ proc mget*[A](s: var HashSet[A], key: A): var A = ## when one overloaded 'hash' and '==' but still needs reference semantics ## for sharing. assert s.isValid, "The set needs to be initialized." - var hc: THash + var hc: Hash var index = rawGet(s, key, hc) if index >= 0: result = s.data[index].key else: raise newException(KeyError, "key not found: " & $key) @@ -178,12 +178,12 @@ proc contains*[A](s: HashSet[A], key: A): bool = ## values.excl(2) ## assert(not values.contains(2)) assert s.isValid, "The set needs to be initialized." - var hc: THash + var hc: Hash var index = rawGet(s, key, hc) result = index >= 0 proc rawInsert[A](s: var HashSet[A], data: var KeyValuePairSeq[A], key: A, - hc: THash, h: THash) = + hc: Hash, h: Hash) = rawInsertImpl() proc enlarge[A](s: var HashSet[A]) = @@ -196,7 +196,7 @@ proc enlarge[A](s: var HashSet[A]) = rawInsert(s, s.data, n[i].key, n[i].hcode, j) template inclImpl() {.dirty.} = - var hc: THash + var hc: Hash var index = rawGet(s, key, hc) if index < 0: if mustRehash(len(s.data), s.counter): @@ -206,7 +206,7 @@ template inclImpl() {.dirty.} = inc(s.counter) template containsOrInclImpl() {.dirty.} = - var hc: THash + var hc: Hash var index = rawGet(s, key, hc) if index >= 0: result = true @@ -261,7 +261,7 @@ proc excl*[A](s: var HashSet[A], key: A) = ## s.excl(2) ## assert s.len == 3 assert s.isValid, "The set needs to be initialized." - var hc: THash + var hc: Hash var i = rawGet(s, key, hc) var msk = high(s.data) if i >= 0: @@ -323,7 +323,7 @@ proc init*[A](s: var HashSet[A], initialSize=64) = ## existing values and calling `excl() <#excl,TSet[A],A>`_ on them. Example: ## ## .. code-block :: - ## var a: TSet[int] + ## var a: Set[int] ## a.init(4) ## a.incl(2) ## a.init @@ -552,7 +552,7 @@ proc map*[A, B](data: HashSet[A], op: proc (x: A): B {.closure.}): HashSet[B] = type OrderedKeyValuePair[A] = tuple[ - hcode: THash, next: int, key: A] + hcode: Hash, next: int, key: A] OrderedKeyValuePairSeq[A] = seq[OrderedKeyValuePair[A]] OrderedSet* {.myShallow.}[A] = object ## \ ## A generic hash set that remembers insertion order. @@ -574,7 +574,7 @@ proc isValid*[A](s: OrderedSet[A]): bool = ## correctly initialized. Example: ## ## .. code-block:: - ## proc saveTarotCards(cards: TOrderedSet[int]) = + ## proc saveTarotCards(cards: OrderedSet[int]) = ## assert cards.isValid, "Pass an initialized set!" ## # Do stuff here, may crash in release builds! result = not s.data.isNil @@ -588,7 +588,7 @@ proc len*[A](s: OrderedSet[A]): int {.inline.} = ## ## .. code-block:: ## - ## var values: TOrderedSet[int] + ## var values: OrderedSet[int] ## assert(not values.isValid) ## assert values.len == 0 result = s.counter @@ -629,10 +629,10 @@ iterator items*[A](s: OrderedSet[A]): A = forAllOrderedPairs: yield s.data[h].key -proc rawGetKnownHC[A](s: OrderedSet[A], key: A, hc: THash): int {.inline.} = +proc rawGetKnownHC[A](s: OrderedSet[A], key: A, hc: Hash): int {.inline.} = rawGetKnownHCImpl() -proc rawGet[A](s: OrderedSet[A], key: A, hc: var THash): int {.inline.} = +proc rawGet[A](s: OrderedSet[A], key: A, hc: var Hash): int {.inline.} = rawGetImpl() proc contains*[A](s: OrderedSet[A], key: A): bool = @@ -646,12 +646,12 @@ proc contains*[A](s: OrderedSet[A], key: A): bool = ## values.incl(2) ## assert values.contains(2) assert s.isValid, "The set needs to be initialized." - var hc: THash + var hc: Hash var index = rawGet(s, key, hc) result = index >= 0 proc rawInsert[A](s: var OrderedSet[A], data: var OrderedKeyValuePairSeq[A], - key: A, hc: THash, h: THash) = + key: A, hc: Hash, h: Hash) = rawInsertImpl() data[h].next = -1 if s.first < 0: s.first = h @@ -729,7 +729,7 @@ proc init*[A](s: var OrderedSet[A], initialSize=64) = ## from an ordered hash set. Example: ## ## .. code-block :: - ## var a: TOrderedSet[int] + ## var a: OrderedSet[int] ## a.init(4) ## a.incl(2) ## a.init diff --git a/lib/pure/collections/tables.nim b/lib/pure/collections/tables.nim index 9496fa2fe..c44adfc82 100644 --- a/lib/pure/collections/tables.nim +++ b/lib/pure/collections/tables.nim @@ -24,13 +24,13 @@ ## ## Error: type mismatch: got (Person) ## but expected one of: -## hashes.hash(x: openarray[A]): THash -## hashes.hash(x: int): THash -## hashes.hash(x: float): THash +## hashes.hash(x: openarray[A]): Hash +## hashes.hash(x: int): Hash +## hashes.hash(x: float): Hash ## … ## ## What is happening here is that the types used for table keys require to have -## a ``hash()`` proc which will convert them to a `THash `_ +## a ``hash()`` proc which will convert them to a `Hash `_ ## value, and the compiler is listing all the hash functions it knows. ## Additionally there has to be a ``==`` operator that provides the same ## semantics as its corresponding ``hash`` proc. @@ -46,7 +46,7 @@ ## Person = object ## firstName, lastName: string ## -## proc hash(x: Person): THash = +## proc hash(x: Person): Hash = ## ## Piggyback on the already available string hash proc. ## ## ## ## Without this proc nothing works! @@ -71,7 +71,7 @@ import {.pragma: myShallow.} type - KeyValuePair[A, B] = tuple[hcode: THash, key: A, val: B] + KeyValuePair[A, B] = tuple[hcode: Hash, key: A, val: B] KeyValuePairSeq[A, B] = seq[KeyValuePair[A, B]] Table* {.myShallow.}[A, B] = object ## generic hash table data: KeyValuePairSeq[A, B] @@ -85,10 +85,10 @@ when not defined(nimhygiene): # hcode for real keys cannot be zero. hcode==0 signifies an empty slot. These # two procs retain clarity of that encoding without the space cost of an enum. -proc isEmpty(hcode: THash): bool {.inline.} = +proc isEmpty(hcode: Hash): bool {.inline.} = result = hcode == 0 -proc isFilled(hcode: THash): bool {.inline.} = +proc isFilled(hcode: Hash): bool {.inline.} = result = hcode != 0 proc len*[A, B](t: Table[A, B]): int = @@ -137,15 +137,15 @@ proc rightSize*(count: Natural): int {.inline.} = ## Internally, we want mustRehash(rightSize(x), x) == false. result = nextPowerOfTwo(count * 3 div 2 + 4) -proc nextTry(h, maxHash: THash): THash {.inline.} = +proc nextTry(h, maxHash: Hash): Hash {.inline.} = result = (h + 1) and maxHash template rawGetKnownHCImpl() {.dirty.} = - var h: THash = hc and high(t.data) # start with real hash value + var h: Hash = hc and high(t.data) # start with real hash value while isFilled(t.data[h].hcode): # Compare hc THEN key with boolean short circuit. This makes the common case # zero ==key's for missing (e.g.inserts) and exactly one ==key for present. - # It does slow down succeeding lookups by one extra THash cmp&and..usually + # It does slow down succeeding lookups by one extra Hash cmp&and..usually # just a few clock cycles, generally worth it for any non-integer-like A. if t.data[h].hcode == hc and t.data[h].key == key: return h @@ -162,7 +162,7 @@ template rawGetDeepImpl() {.dirty.} = # Search algo for unconditional add hc = hash(key) if hc == 0: hc = 314159265 - var h: THash = hc and high(t.data) + var h: Hash = hc and high(t.data) while isFilled(t.data[h].hcode): h = nextTry(h, high(t.data)) result = h @@ -172,13 +172,13 @@ template rawInsertImpl() {.dirty.} = data[h].val = val data[h].hcode = hc -proc rawGetKnownHC[A, B](t: Table[A, B], key: A, hc: THash): int {.inline.} = +proc rawGetKnownHC[A, B](t: Table[A, B], key: A, hc: Hash): int {.inline.} = rawGetKnownHCImpl() -proc rawGetDeep[A, B](t: Table[A, B], key: A, hc: var THash): int {.inline.} = +proc rawGetDeep[A, B](t: Table[A, B], key: A, hc: var Hash): int {.inline.} = rawGetDeepImpl() -proc rawGet[A, B](t: Table[A, B], key: A, hc: var THash): int {.inline.} = +proc rawGet[A, B](t: Table[A, B], key: A, hc: var Hash): int {.inline.} = rawGetImpl() proc `[]`*[A, B](t: Table[A, B], key: A): B = @@ -186,14 +186,14 @@ proc `[]`*[A, B](t: Table[A, B], key: A): B = ## default empty value for the type `B` is returned ## and no exception is raised. One can check with ``hasKey`` whether the key ## exists. - var hc: THash + var hc: Hash var index = rawGet(t, key, hc) if index >= 0: result = t.data[index].val proc mget*[A, B](t: var Table[A, B], key: A): var B = ## retrieves the value at ``t[key]``. The value can be modified. ## If `key` is not in `t`, the ``KeyError`` exception is raised. - var hc: THash + var hc: Hash var index = rawGet(t, key, hc) if index >= 0: result = t.data[index].val else: @@ -204,7 +204,7 @@ proc mget*[A, B](t: var Table[A, B], key: A): var B = iterator allValues*[A, B](t: Table[A, B]; key: A): B = ## iterates over any value in the table `t` that belongs to the given `key`. - var h: THash = hash(key) and high(t.data) + var h: Hash = hash(key) and high(t.data) while isFilled(t.data[h].hcode): if t.data[h].key == key: yield t.data[h].val @@ -212,7 +212,7 @@ iterator allValues*[A, B](t: Table[A, B]; key: A): B = proc hasKey*[A, B](t: Table[A, B], key: A): bool = ## returns true iff `key` is in the table `t`. - var hc: THash + var hc: Hash result = rawGet(t, key, hc) >= 0 proc contains*[A, B](t: Table[A, B], key: A): bool = @@ -220,7 +220,7 @@ proc contains*[A, B](t: Table[A, B], key: A): bool = return hasKey[A, B](t, key) proc rawInsert[A, B](t: var Table[A, B], data: var KeyValuePairSeq[A, B], - key: A, val: B, hc: THash, h: THash) = + key: A, val: B, hc: Hash, h: Hash) = rawInsertImpl() proc enlarge[A, B](t: var Table[A, B]) = @@ -234,7 +234,7 @@ proc enlarge[A, B](t: var Table[A, B]) = template addImpl() {.dirty.} = if mustRehash(len(t.data), t.counter): enlarge(t) - var hc: THash + var hc: Hash var j = rawGetDeep(t, key, hc) rawInsert(t, t.data, key, val, hc, j) inc(t.counter) @@ -248,19 +248,19 @@ template maybeRehashPutImpl() {.dirty.} = inc(t.counter) template putImpl() {.dirty.} = - var hc: THash + var hc: Hash var index = rawGet(t, key, hc) if index >= 0: t.data[index].val = val else: maybeRehashPutImpl() template mgetOrPutImpl() {.dirty.} = - var hc: THash + var hc: Hash var index = rawGet(t, key, hc) if index < 0: maybeRehashPutImpl() # not present: insert (flipping index) result = t.data[index].val # either way return modifiable val template hasKeyOrPutImpl() {.dirty.} = - var hc: THash + var hc: Hash var index = rawGet(t, key, hc) if index < 0: result = false @@ -291,7 +291,7 @@ template doWhile(a: expr, b: stmt): stmt = proc del*[A, B](t: var Table[A, B], key: A) = ## deletes `key` from hash table `t`. - var hc: THash + var hc: Hash var i = rawGet(t, key, hc) let msk = high(t.data) if i >= 0: @@ -460,7 +460,7 @@ proc newTableFrom*[A, B, C](collection: A, index: proc(x: B): C): TableRef[C, B] type OrderedKeyValuePair[A, B] = tuple[ - hcode: THash, next: int, key: A, val: B] + hcode: Hash, next: int, key: A, val: B] OrderedKeyValuePairSeq[A, B] = seq[OrderedKeyValuePair[A, B]] OrderedTable* {. myShallow.}[A, B] = object ## table that remembers insertion order @@ -509,13 +509,13 @@ iterator mvalues*[A, B](t: var OrderedTable[A, B]): var B = forAllOrderedPairs: yield t.data[h].val -proc rawGetKnownHC[A, B](t: OrderedTable[A, B], key: A, hc: THash): int = +proc rawGetKnownHC[A, B](t: OrderedTable[A, B], key: A, hc: Hash): int = rawGetKnownHCImpl() -proc rawGetDeep[A, B](t: OrderedTable[A, B], key: A, hc: var THash): int {.inline.} = +proc rawGetDeep[A, B](t: OrderedTable[A, B], key: A, hc: var Hash): int {.inline.} = rawGetDeepImpl() -proc rawGet[A, B](t: OrderedTable[A, B], key: A, hc: var THash): int = +proc rawGet[A, B](t: OrderedTable[A, B], key: A, hc: var Hash): int = rawGetImpl() proc `[]`*[A, B](t: OrderedTable[A, B], key: A): B = @@ -523,21 +523,21 @@ proc `[]`*[A, B](t: OrderedTable[A, B], key: A): B = ## default empty value for the type `B` is returned ## and no exception is raised. One can check with ``hasKey`` whether the key ## exists. - var hc: THash + var hc: Hash var index = rawGet(t, key, hc) if index >= 0: result = t.data[index].val proc mget*[A, B](t: var OrderedTable[A, B], key: A): var B = ## retrieves the value at ``t[key]``. The value can be modified. ## If `key` is not in `t`, the ``EInvalidKey`` exception is raised. - var hc: THash + var hc: Hash var index = rawGet(t, key, hc) if index >= 0: result = t.data[index].val else: raise newException(KeyError, "key not found: " & $key) proc hasKey*[A, B](t: OrderedTable[A, B], key: A): bool = ## returns true iff `key` is in the table `t`. - var hc: THash + var hc: Hash result = rawGet(t, key, hc) >= 0 proc contains*[A, B](t: OrderedTable[A, B], key: A): bool = @@ -546,7 +546,7 @@ proc contains*[A, B](t: OrderedTable[A, B], key: A): bool = proc rawInsert[A, B](t: var OrderedTable[A, B], data: var OrderedKeyValuePairSeq[A, B], - key: A, val: B, hc: THash, h: THash) = + key: A, val: B, hc: Hash, h: Hash) = rawInsertImpl() data[h].next = -1 if t.first < 0: t.first = h @@ -796,7 +796,7 @@ iterator mvalues*[A](t: CountTable[A]): var int = if t.data[h].val != 0: yield t.data[h].val proc rawGet[A](t: CountTable[A], key: A): int = - var h: THash = hash(key) and high(t.data) # start with real hash value + var h: Hash = hash(key) and high(t.data) # start with real hash value while t.data[h].val != 0: if t.data[h].key == key: return h h = nextTry(h, high(t.data)) @@ -826,7 +826,7 @@ proc contains*[A](t: CountTable[A], key: A): bool = proc rawInsert[A](t: CountTable[A], data: var seq[tuple[key: A, val: int]], key: A, val: int) = - var h: THash = hash(key) and high(data) + var h: Hash = hash(key) and high(data) while data[h].val != 0: h = nextTry(h, high(data)) data[h].key = key data[h].val = val @@ -1032,7 +1032,7 @@ when isMainModule: Person = object firstName, lastName: string - proc hash(x: Person): THash = + proc hash(x: Person): Hash = ## Piggyback on the already available string hash proc. ## ## Without this proc nothing works! diff --git a/lib/pure/concurrency/cpuload.nim b/lib/pure/concurrency/cpuload.nim index 7ce5e01b7..1f3f54056 100644 --- a/lib/pure/concurrency/cpuload.nim +++ b/lib/pure/concurrency/cpuload.nim @@ -34,7 +34,7 @@ proc advice*(s: var ThreadPoolState): ThreadPoolAdvice = sysIdle, sysKernel, sysUser, procCreation, procExit, procKernel, procUser: TFILETIME if getSystemTimes(sysIdle, sysKernel, sysUser) == 0 or - getProcessTimes(THandle(-1), procCreation, procExit, + getProcessTimes(Handle(-1), procCreation, procExit, procKernel, procUser) == 0: return doNothing if s.calls > 0: diff --git a/lib/pure/concurrency/threadpool.nim b/lib/pure/concurrency/threadpool.nim index 7080e16eb..749a2fa2d 100644 --- a/lib/pure/concurrency/threadpool.nim +++ b/lib/pure/concurrency/threadpool.nim @@ -18,8 +18,8 @@ import cpuinfo, cpuload, locks type Semaphore = object - c: TCond - L: TLock + c: Cond + L: Lock counter: int proc createSemaphore(): Semaphore = @@ -113,7 +113,7 @@ type ToFreeQueue = object len: int - lock: TLock + lock: Lock empty: Semaphore data: array[128, pointer] @@ -355,7 +355,7 @@ proc parallel*(body: stmt) {.magic: "Parallel".} var state: ThreadPoolState - stateLock: TLock + stateLock: Lock initLock stateLock From 6914244f3054a60b7f12622c8d5fbe5e880f7c56 Mon Sep 17 00:00:00 2001 From: pdw Date: Sun, 24 May 2015 22:33:34 -0500 Subject: [PATCH 0351/1263] lib/pure/e-o - Dropped 'T' from types --- lib/pure/encodings.nim | 5 ++-- lib/pure/gentabs.nim | 43 +++++++++++++++-------------- lib/pure/hashes.nim | 61 +++++++++++++++++++++-------------------- lib/pure/htmlparser.nim | 15 +++++----- lib/pure/httpserver.nim | 24 ++++++++-------- lib/pure/json.nim | 32 +++++++++++---------- lib/pure/lexbase.nim | 2 +- lib/pure/marshal.nim | 28 ++++++++++--------- lib/pure/memfiles.nim | 2 +- lib/pure/net.nim | 39 +++++++++++++------------- lib/pure/nimprof.nim | 48 ++++++++++++++++---------------- lib/pure/os.nim | 36 ++++++++++++------------ lib/pure/osproc.nim | 52 ++++++++++++++++++----------------- 13 files changed, 202 insertions(+), 185 deletions(-) diff --git a/lib/pure/encodings.nim b/lib/pure/encodings.nim index 78baec3de..e427b585d 100644 --- a/lib/pure/encodings.nim +++ b/lib/pure/encodings.nim @@ -211,12 +211,13 @@ when defined(windows): when false: # not needed yet: type - TCpInfo = object + CpInfo = object maxCharSize: int32 defaultChar: array[0..1, char] leadByte: array[0..12-1, char] + {.deprecated: [TCpInfo: CpInfo].} - proc getCPInfo(codePage: CodePage, lpCPInfo: var TCpInfo): int32 {. + proc getCPInfo(codePage: CodePage, lpCPInfo: var CpInfo): int32 {. stdcall, importc: "GetCPInfo", dynlib: "kernel32".} proc nameToCodePage(name: string): CodePage = diff --git a/lib/pure/gentabs.nim b/lib/pure/gentabs.nim index 84d0a44de..e6a05ec63 100644 --- a/lib/pure/gentabs.nim +++ b/lib/pure/gentabs.nim @@ -18,20 +18,22 @@ import os, hashes, strutils type - TGenTableMode* = enum ## describes the table's key matching mode + GenTableMode* = enum ## describes the table's key matching mode modeCaseSensitive, ## case sensitive matching of keys modeCaseInsensitive, ## case insensitive matching of keys modeStyleInsensitive ## style sensitive matching of keys - TGenKeyValuePair[T] = tuple[key: string, val: T] - TGenKeyValuePairSeq[T] = seq[TGenKeyValuePair[T]] - TGenTable*[T] = object of RootObj + GenKeyValuePair[T] = tuple[key: string, val: T] + GenKeyValuePairSeq[T] = seq[GenKeyValuePair[T]] + GenTable*[T] = object of RootObj counter: int - data: TGenKeyValuePairSeq[T] - mode: TGenTableMode + data: GenKeyValuePairSeq[T] + mode: GenTableMode - PGenTable*[T] = ref TGenTable[T] ## use this type to declare hash tables + PGenTable*[T] = ref GenTable[T] ## use this type to declare hash tables +{.deprecated: [TGenTableMode: GenTableMode, TGenKeyValuePair: GenKeyValuePair, + TGenKeyValuePairSeq: GenKeyValuePairSeq, TGenTable: GenTable].} const growthFactor = 2 @@ -48,7 +50,7 @@ iterator pairs*[T](tbl: PGenTable[T]): tuple[key: string, value: T] = if not isNil(tbl.data[h].key): yield (tbl.data[h].key, tbl.data[h].val) -proc myhash[T](tbl: PGenTable[T], key: string): THash = +proc myhash[T](tbl: PGenTable[T], key: string): Hash = case tbl.mode of modeCaseSensitive: result = hashes.hash(key) of modeCaseInsensitive: result = hashes.hashIgnoreCase(key) @@ -64,18 +66,18 @@ proc mustRehash(length, counter: int): bool = assert(length > counter) result = (length * 2 < counter * 3) or (length - counter < 4) -proc newGenTable*[T](mode: TGenTableMode): PGenTable[T] = +proc newGenTable*[T](mode: GenTableMode): PGenTable[T] = ## creates a new generic hash table that is empty. new(result) result.mode = mode result.counter = 0 newSeq(result.data, startSize) -proc nextTry(h, maxHash: THash): THash {.inline.} = +proc nextTry(h, maxHash: Hash): Hash {.inline.} = result = ((5 * h) + 1) and maxHash proc rawGet[T](tbl: PGenTable[T], key: string): int = - var h: THash + var h: Hash h = myhash(tbl, key) and high(tbl.data) # start with real hash value while not isNil(tbl.data[h].key): if myCmp(tbl, tbl.data[h].key, key): @@ -83,9 +85,9 @@ proc rawGet[T](tbl: PGenTable[T], key: string): int = h = nextTry(h, high(tbl.data)) result = - 1 -proc rawInsert[T](tbl: PGenTable[T], data: var TGenKeyValuePairSeq[T], +proc rawInsert[T](tbl: PGenTable[T], data: var GenKeyValuePairSeq[T], key: string, val: T) = - var h: THash + var h: Hash h = myhash(tbl, key) and high(data) while not isNil(data[h].key): h = nextTry(h, high(data)) @@ -93,7 +95,7 @@ proc rawInsert[T](tbl: PGenTable[T], data: var TGenKeyValuePairSeq[T], data[h].val = val proc enlarge[T](tbl: PGenTable[T]) = - var n: TGenKeyValuePairSeq[T] + var n: GenKeyValuePairSeq[T] newSeq(n, len(tbl.data) * growthFactor) for i in countup(0, high(tbl.data)): if not isNil(tbl.data[i].key): @@ -146,19 +148,20 @@ when isMainModule: # Verify a table of user-defined types # type - TMyType = tuple[first, second: string] # a pair of strings + MyType = tuple[first, second: string] # a pair of strings + {.deprecated: [TMyType: MyType].} - var y = newGenTable[TMyType](modeCaseInsensitive) # hash table where each - # value is TMyType tuple + var y = newGenTable[MyType](modeCaseInsensitive) # hash table where each + # value is MyType tuple - #var junk: TMyType = ("OK", "Here") + #var junk: MyType = ("OK", "Here") #echo junk.first, " ", junk.second y["Hello"] = ("Hello", "World") y["Goodbye"] = ("Goodbye", "Everyone") - #y["Hello"] = TMyType( ("Hello", "World") ) - #y["Goodbye"] = TMyType( ("Goodbye", "Everyone") ) + #y["Hello"] = MyType( ("Hello", "World") ) + #y["Goodbye"] = MyType( ("Goodbye", "Everyone") ) assert( not isNil(y["Hello"].first) ) assert( y["Hello"].first == "Hello" ) diff --git a/lib/pure/hashes.nim b/lib/pure/hashes.nim index 132264e4a..c303c7b4b 100644 --- a/lib/pure/hashes.nim +++ b/lib/pure/hashes.nim @@ -15,9 +15,9 @@ ## code: ## ## .. code-block:: Nim -## proc hash(x: Something): THash = -## ## Computes a THash from `x`. -## var h: THash = 0 +## proc hash(x: Something): Hash = +## ## Computes a Hash from `x`. +## var h: Hash = 0 ## # Iterate over parts of `x`. ## for xAtom in x: ## # Mix the atom with the partial hash. @@ -30,9 +30,9 @@ ## together the hash value of the individual fields: ## ## .. code-block:: Nim -## proc hash(x: Something): THash = -## ## Computes a THash from `x`. -## var h: THash = 0 +## proc hash(x: Something): Hash = +## ## Computes a Hash from `x`. +## var h: Hash = 0 ## h = h !& hash(x.foo) ## h = h !& hash(x.bar) ## result = !$h @@ -41,27 +41,28 @@ import strutils, etcpriv type - THash* = int ## a hash value; hash tables using these values should + Hash* = int ## a hash value; hash tables using these values should ## always have a size of a power of two and can use the ``and`` ## operator instead of ``mod`` for truncation of the hash value. +{.deprecated: [THash: Hash].} -proc `!&`*(h: THash, val: int): THash {.inline.} = +proc `!&`*(h: Hash, val: int): Hash {.inline.} = ## mixes a hash value `h` with `val` to produce a new hash value. This is ## only needed if you need to implement a hash proc for a new datatype. result = h +% val result = result +% result shl 10 result = result xor (result shr 6) -proc `!$`*(h: THash): THash {.inline.} = +proc `!$`*(h: Hash): Hash {.inline.} = ## finishes the computation of the hash value. This is ## only needed if you need to implement a hash proc for a new datatype. result = h +% h shl 3 result = result xor (result shr 11) result = result +% result shl 15 -proc hashData*(data: pointer, size: int): THash = +proc hashData*(data: pointer, size: int): Hash = ## hashes an array of bytes of size `size` - var h: THash = 0 + var h: Hash = 0 when defined(js): var p: cstring asm """`p` = `Data`;""" @@ -78,7 +79,7 @@ proc hashData*(data: pointer, size: int): THash = when defined(js): var objectID = 0 -proc hash*(x: pointer): THash {.inline.} = +proc hash*(x: pointer): Hash {.inline.} = ## efficient hashing of pointers when defined(js): asm """ @@ -92,38 +93,38 @@ proc hash*(x: pointer): THash {.inline.} = } """ else: - result = (cast[THash](x)) shr 3 # skip the alignment + result = (cast[Hash](x)) shr 3 # skip the alignment when not defined(booting): - proc hash*[T: proc](x: T): THash {.inline.} = + proc hash*[T: proc](x: T): Hash {.inline.} = ## efficient hashing of proc vars; closures are supported too. when T is "closure": result = hash(rawProc(x)) !& hash(rawEnv(x)) else: result = hash(pointer(x)) -proc hash*(x: int): THash {.inline.} = +proc hash*(x: int): Hash {.inline.} = ## efficient hashing of integers result = x -proc hash*(x: int64): THash {.inline.} = +proc hash*(x: int64): Hash {.inline.} = ## efficient hashing of integers result = toU32(x) -proc hash*(x: char): THash {.inline.} = +proc hash*(x: char): Hash {.inline.} = ## efficient hashing of characters result = ord(x) -proc hash*(x: string): THash = +proc hash*(x: string): Hash = ## efficient hashing of strings - var h: THash = 0 + var h: Hash = 0 for i in 0..x.len-1: h = h !& ord(x[i]) result = !$h -proc hashIgnoreStyle*(x: string): THash = +proc hashIgnoreStyle*(x: string): Hash = ## efficient hashing of strings; style is ignored - var h: THash = 0 + var h: Hash = 0 var i = 0 let xLen = x.len while i < xLen: @@ -140,9 +141,9 @@ proc hashIgnoreStyle*(x: string): THash = result = !$h -proc hashIgnoreCase*(x: string): THash = +proc hashIgnoreCase*(x: string): Hash = ## efficient hashing of strings; case is ignored - var h: THash = 0 + var h: Hash = 0 for i in 0..x.len-1: var c = x[i] if c in {'A'..'Z'}: @@ -150,28 +151,28 @@ proc hashIgnoreCase*(x: string): THash = h = h !& ord(c) result = !$h -proc hash*(x: float): THash {.inline.} = +proc hash*(x: float): Hash {.inline.} = var y = x + 1.0 - result = cast[ptr THash](addr(y))[] + result = cast[ptr Hash](addr(y))[] # Forward declarations before methods that hash containers. This allows # containers to contain other containers -proc hash*[A](x: openArray[A]): THash -proc hash*[A](x: set[A]): THash +proc hash*[A](x: openArray[A]): Hash +proc hash*[A](x: set[A]): Hash -proc hash*[T: tuple](x: T): THash = +proc hash*[T: tuple](x: T): Hash = ## efficient hashing of tuples. for f in fields(x): result = result !& hash(f) result = !$result -proc hash*[A](x: openArray[A]): THash = +proc hash*[A](x: openArray[A]): Hash = for it in items(x): result = result !& hash(it) result = !$result -proc hash*[A](x: set[A]): THash = +proc hash*[A](x: set[A]): Hash = for it in items(x): result = result !& hash(it) result = !$result diff --git a/lib/pure/htmlparser.nim b/lib/pure/htmlparser.nim index 9719181b8..a0e2ecd9b 100644 --- a/lib/pure/htmlparser.nim +++ b/lib/pure/htmlparser.nim @@ -52,7 +52,7 @@ import strutils, streams, parsexml, xmltree, unicode, strtabs type - THtmlTag* = enum ## list of all supported HTML tags; order will always be + HtmlTag* = enum ## list of all supported HTML tags; order will always be ## alphabetically tagUnknown, ## unknown HTML element tagA, ## the HTML ``a`` element @@ -178,6 +178,7 @@ type tagVar, ## the HTML ``var`` element tagVideo, ## the HTML ``video`` element tagWbr ## the HTML ``wbr`` element +{.deprecated: [THtmlTag: HtmlTag].} const tagToStr* = [ @@ -295,7 +296,7 @@ proc allLower(s: string): bool = if c < 'a' or c > 'z': return false return true -proc toHtmlTag(s: string): THtmlTag = +proc toHtmlTag(s: string): HtmlTag = case s of "a": tagA of "abbr": tagAbbr @@ -422,14 +423,14 @@ proc toHtmlTag(s: string): THtmlTag = of "wbr": tagWbr else: tagUnknown -proc htmlTag*(n: XmlNode): THtmlTag = - ## gets `n`'s tag as a ``THtmlTag``. +proc htmlTag*(n: XmlNode): HtmlTag = + ## gets `n`'s tag as a ``HtmlTag``. if n.clientData == 0: n.clientData = toHtmlTag(n.tag).ord - result = THtmlTag(n.clientData) + result = HtmlTag(n.clientData) -proc htmlTag*(s: string): THtmlTag = - ## converts `s` to a ``THtmlTag``. If `s` is no HTML tag, ``tagUnknown`` is +proc htmlTag*(s: string): HtmlTag = + ## converts `s` to a ``HtmlTag``. If `s` is no HTML tag, ``tagUnknown`` is ## returned. let s = if allLower(s): s else: s.toLower result = toHtmlTag(s) diff --git a/lib/pure/httpserver.nim b/lib/pure/httpserver.nim index dc76c9228..981891227 100644 --- a/lib/pure/httpserver.nim +++ b/lib/pure/httpserver.nim @@ -106,9 +106,10 @@ proc serveFile*(client: Socket, filename: string) = when false: # TODO: Fix this, or get rid of it. type - TRequestMethod = enum reqGet, reqPost + RequestMethod = enum reqGet, reqPost + {.deprecated: [TRequestMethod: RequestMethod].} - proc executeCgi(client: Socket, path, query: string, meth: TRequestMethod) = + proc executeCgi(client: Socket, path, query: string, meth: RequestMethod) = var env = newStringTable(modeCaseInsensitive) var contentLength = -1 case meth @@ -208,7 +209,7 @@ when false: executeCgi(client, path, query, meth) type - TServer* = object of RootObj ## contains the current server state + Server* = object of RootObj ## contains the current server state socket: Socket port: Port client*: Socket ## the socket to write the file data to @@ -218,11 +219,12 @@ type body*: string ## only set with POST requests ip*: string ## ip address of the requesting client - PAsyncHTTPServer* = ref TAsyncHTTPServer - TAsyncHTTPServer = object of TServer + PAsyncHTTPServer* = ref AsyncHTTPServer + AsyncHTTPServer = object of Server asyncSocket: AsyncSocket +{.deprecated: [TAsyncHTTPServer: AsyncHTTPServer, TServer: Server].} -proc open*(s: var TServer, port = Port(80), reuseAddr = false) = +proc open*(s: var Server, port = Port(80), reuseAddr = false) = ## creates a new server at port `port`. If ``port == 0`` a free port is ## acquired that can be accessed later by the ``port`` proc. s.socket = socket(AF_INET) @@ -243,11 +245,11 @@ proc open*(s: var TServer, port = Port(80), reuseAddr = false) = s.query = "" s.headers = {:}.newStringTable() -proc port*(s: var TServer): Port = +proc port*(s: var Server): Port = ## get the port number the server has acquired. result = s.port -proc next*(s: var TServer) = +proc next*(s: var Server) = ## proceed to the first/next request. var client: Socket new(client) @@ -354,7 +356,7 @@ proc next*(s: var TServer) = s.query = "" s.path = data.substr(i, last-1) -proc close*(s: TServer) = +proc close*(s: Server) = ## closes the server (and the socket the server uses). close(s.socket) @@ -362,7 +364,7 @@ proc run*(handleRequest: proc (client: Socket, path, query: string): bool {.closure.}, port = Port(80)) = ## encapsulates the server object and main loop - var s: TServer + var s: Server open(s, port, reuseAddr = true) #echo("httpserver running on port ", s.port) while true: @@ -517,7 +519,7 @@ proc close*(h: PAsyncHTTPServer) = when not defined(testing) and isMainModule: var counter = 0 - var s: TServer + var s: Server open(s, Port(0)) echo("httpserver running on port ", s.port) while true: diff --git a/lib/pure/json.nim b/lib/pure/json.nim index 0959bb221..49915b7e9 100644 --- a/lib/pure/json.nim +++ b/lib/pure/json.nim @@ -68,7 +68,7 @@ type jsonArrayStart, ## start of an array: the ``[`` token jsonArrayEnd ## start of an array: the ``]`` token - TTokKind = enum # must be synchronized with TJsonEventKind! + TokKind = enum # must be synchronized with TJsonEventKind! tkError, tkEof, tkString, @@ -103,14 +103,14 @@ type JsonParser* = object of BaseLexer ## the parser object. a: string - tok: TTokKind + tok: TokKind kind: JsonEventKind err: JsonError state: seq[ParserState] filename: string {.deprecated: [TJsonEventKind: JsonEventKind, TJsonError: JsonError, - TJsonParser: JsonParser].} + TJsonParser: JsonParser, TTokKind: TokKind].} const errorMessages: array [JsonError, string] = [ @@ -126,7 +126,7 @@ const "EOF expected", "expression expected" ] - tokToStr: array [TTokKind, string] = [ + tokToStr: array [TokKind, string] = [ "invalid token", "EOF", "string literal", @@ -203,7 +203,7 @@ proc handleHexChar(c: char, x: var int): bool = of 'A'..'F': x = (x shl 4) or (ord(c) - ord('A') + 10) else: result = false # error -proc parseString(my: var JsonParser): TTokKind = +proc parseString(my: var JsonParser): TokKind = result = tkString var pos = my.bufpos + 1 var buf = my.buf @@ -359,7 +359,7 @@ proc parseName(my: var JsonParser) = inc(pos) my.bufpos = pos -proc getTok(my: var JsonParser): TTokKind = +proc getTok(my: var JsonParser): TokKind = setLen(my.a, 0) skip(my) # skip whitespace, comments case my.buf[my.bufpos] @@ -734,7 +734,7 @@ proc `==`* (a,b: JsonNode): bool = of JObject: a.fields == b.fields -proc hash* (n:JsonNode): THash = +proc hash* (n:JsonNode): Hash = ## Compute the hash for a JSON node case n.kind of JArray: @@ -1016,7 +1016,7 @@ iterator mpairs*(node: var JsonNode): var tuple[key: string, val: JsonNode] = for keyVal in mitems(node.fields): yield keyVal -proc eat(p: var JsonParser, tok: TTokKind) = +proc eat(p: var JsonParser, tok: TokKind) = if p.tok == tok: discard getTok(p) else: raiseParseErr(p, tokToStr[tok]) @@ -1091,8 +1091,10 @@ when not defined(js): else: from math import `mod` type - TJSObject = object - proc parseNativeJson(x: cstring): TJSObject {.importc: "JSON.parse".} + JSObject = object + {.deprecated: [TJSObject: JSObject].} + + proc parseNativeJson(x: cstring): JSObject {.importc: "JSON.parse".} proc getVarType(x): JsonNodeKind = result = JNull @@ -1111,25 +1113,25 @@ else: of "[object String]": return JString else: assert false - proc len(x: TJSObject): int = + proc len(x: JSObject): int = assert x.getVarType == JArray asm """ return `x`.length; """ - proc `[]`(x: TJSObject, y: string): TJSObject = + proc `[]`(x: JSObject, y: string): JSObject = assert x.getVarType == JObject asm """ return `x`[`y`]; """ - proc `[]`(x: TJSObject, y: int): TJSObject = + proc `[]`(x: JSObject, y: int): JSObject = assert x.getVarType == JArray asm """ return `x`[`y`]; """ - proc convertObject(x: TJSObject): JsonNode = + proc convertObject(x: JSObject): JsonNode = case getVarType(x) of JArray: result = newJArray() @@ -1141,7 +1143,7 @@ else: if (`x`.hasOwnProperty(property)) { """ var nimProperty: cstring - var nimValue: TJSObject + var nimValue: JSObject asm "`nimProperty` = property; `nimValue` = `x`[property];" result[$nimProperty] = nimValue.convertObject() asm "}}" diff --git a/lib/pure/lexbase.nim b/lib/pure/lexbase.nim index 23a87d9f8..585ba87f5 100644 --- a/lib/pure/lexbase.nim +++ b/lib/pure/lexbase.nim @@ -39,7 +39,7 @@ type {.deprecated: [TBaseLexer: BaseLexer].} proc open*(L: var BaseLexer, input: Stream, bufLen: int = 8192) - ## inits the TBaseLexer with a stream to read from + ## inits the BaseLexer with a stream to read from proc close*(L: var BaseLexer) ## closes the base lexer. This closes `L`'s associated stream too. diff --git a/lib/pure/marshal.nim b/lib/pure/marshal.nim index e0092f314..49f049e46 100644 --- a/lib/pure/marshal.nim +++ b/lib/pure/marshal.nim @@ -17,13 +17,13 @@ ## .. code-block:: nim ## ## type -## TA = object -## TB = object of TA +## A = object +## B = object of A ## f: int ## ## var -## a: ref TA -## b: ref TB +## a: ref A +## b: ref B ## ## new(b) ## a = b @@ -36,7 +36,7 @@ import streams, typeinfo, json, intsets, tables proc ptrToInt(x: pointer): int {.inline.} = result = cast[int](x) # don't skip alignment -proc storeAny(s: Stream, a: TAny, stored: var IntSet) = +proc storeAny(s: Stream, a: Any, stored: var IntSet) = case a.kind of akNone: assert false of akBool: s.write($getBool(a)) @@ -96,7 +96,7 @@ proc storeAny(s: Stream, a: TAny, stored: var IntSet) = of akInt..akInt64, akUInt..akUInt64: s.write($getBiggestInt(a)) of akFloat..akFloat128: s.write($getBiggestFloat(a)) -proc loadAny(p: var JsonParser, a: TAny, t: var Table[BiggestInt, pointer]) = +proc loadAny(p: var JsonParser, a: Any, t: var Table[BiggestInt, pointer]) = case a.kind of akNone: assert false of akBool: @@ -222,7 +222,7 @@ proc loadAny(p: var JsonParser, a: TAny, t: var Table[BiggestInt, pointer]) = raiseParseErr(p, "float expected") of akRange: loadAny(p, a.skipRange, t) -proc loadAny(s: Stream, a: TAny, t: var Table[BiggestInt, pointer]) = +proc loadAny(s: Stream, a: Any, t: var Table[BiggestInt, pointer]) = var p: JsonParser open(p, s, "unknown file") next(p) @@ -278,10 +278,11 @@ when not defined(testing) and isMainModule: else: nil - PNode = ref TNode - TNode = object + PNode = ref Node + Node = object next, prev: PNode data: string + {.deprecated: [TNode: Node].} proc buildList(): PNode = new(result) @@ -317,14 +318,15 @@ when not defined(testing) and isMainModule: testit(test7) type - TA {.inheritable.} = object - TB = object of TA + A {.inheritable.} = object + B = object of A f: int var - a: ref TA - b: ref TB + a: ref A + b: ref B new(b) a = b echo($$a[]) # produces "{}", not "{f: 0}" + diff --git a/lib/pure/memfiles.nim b/lib/pure/memfiles.nim index d49dfae9f..76ff6a8e1 100644 --- a/lib/pure/memfiles.nim +++ b/lib/pure/memfiles.nim @@ -196,7 +196,7 @@ proc open*(filename: string, mode: FileMode = fmRead, if mappedSize != -1: result.size = mappedSize else: - var stat: TStat + var stat: Stat if fstat(result.handle, stat) != -1: # XXX: Hmm, this could be unsafe # Why is mmap taking int anyway? diff --git a/lib/pure/net.nim b/lib/pure/net.nim index cf37c271e..49ca12098 100644 --- a/lib/pure/net.nim +++ b/lib/pure/net.nim @@ -86,7 +86,7 @@ type IPv6, ## IPv6 address IPv4 ## IPv4 address - TIpAddress* = object ## stores an arbitrary IP address + IpAddress* = object ## stores an arbitrary IP address case family*: IpAddressFamily ## the type of the IP address (IPv4 or IPv6) of IpAddressFamily.IPv6: address_v6*: array[0..15, uint8] ## Contains the IP address in bytes in @@ -94,9 +94,10 @@ type of IpAddressFamily.IPv4: address_v4*: array[0..3, uint8] ## Contains the IP address in bytes in ## case of IPv4 +{.deprecated: [TIpAddress: IpAddress].} proc isIpAddress*(address_str: string): bool {.tags: [].} -proc parseIpAddress*(address_str: string): TIpAddress +proc parseIpAddress*(address_str: string): IpAddress proc isDisconnectionError*(flags: set[SocketFlag], lastError: OSErrorCode): bool = @@ -395,7 +396,7 @@ proc acceptAddr*(server: Socket, client: var Socket, address: var string, when false: #defined(ssl): proc acceptAddrSSL*(server: Socket, client: var Socket, - address: var string): TSSLAcceptResult {. + address: var string): SSLAcceptResult {. tags: [ReadIOEffect].} = ## This procedure should only be used for non-blocking **SSL** sockets. ## It will immediately return with one of the following values: @@ -992,39 +993,39 @@ proc isSsl*(socket: Socket): bool = proc getFd*(socket: Socket): SocketHandle = return socket.fd ## Returns the socket's file descriptor -proc IPv4_any*(): TIpAddress = +proc IPv4_any*(): IpAddress = ## Returns the IPv4 any address, which can be used to listen on all available ## network adapters - result = TIpAddress( + result = IpAddress( family: IpAddressFamily.IPv4, address_v4: [0'u8, 0, 0, 0]) -proc IPv4_loopback*(): TIpAddress = +proc IPv4_loopback*(): IpAddress = ## Returns the IPv4 loopback address (127.0.0.1) - result = TIpAddress( + result = IpAddress( family: IpAddressFamily.IPv4, address_v4: [127'u8, 0, 0, 1]) -proc IPv4_broadcast*(): TIpAddress = +proc IPv4_broadcast*(): IpAddress = ## Returns the IPv4 broadcast address (255.255.255.255) - result = TIpAddress( + result = IpAddress( family: IpAddressFamily.IPv4, address_v4: [255'u8, 255, 255, 255]) -proc IPv6_any*(): TIpAddress = +proc IPv6_any*(): IpAddress = ## Returns the IPv6 any address (::0), which can be used ## to listen on all available network adapters - result = TIpAddress( + result = IpAddress( family: IpAddressFamily.IPv6, address_v6: [0'u8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) -proc IPv6_loopback*(): TIpAddress = +proc IPv6_loopback*(): IpAddress = ## Returns the IPv6 loopback address (::1) - result = TIpAddress( + result = IpAddress( family: IpAddressFamily.IPv6, address_v6: [0'u8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]) -proc `==`*(lhs, rhs: TIpAddress): bool = +proc `==`*(lhs, rhs: IpAddress): bool = ## Compares two IpAddresses for Equality. Returns two if the addresses are equal if lhs.family != rhs.family: return false if lhs.family == IpAddressFamily.IPv4: @@ -1035,8 +1036,8 @@ proc `==`*(lhs, rhs: TIpAddress): bool = if lhs.address_v6[i] != rhs.address_v6[i]: return false return true -proc `$`*(address: TIpAddress): string = - ## Converts an TIpAddress into the textual representation +proc `$`*(address: IpAddress): string = + ## Converts an IpAddress into the textual representation result = "" case address.family of IpAddressFamily.IPv4: @@ -1095,7 +1096,7 @@ proc `$`*(address: TIpAddress): string = mask = mask shr 4 printedLastGroup = true -proc parseIPv4Address(address_str: string): TIpAddress = +proc parseIPv4Address(address_str: string): IpAddress = ## Parses IPv4 adresses ## Raises EInvalidValue on errors var @@ -1129,7 +1130,7 @@ proc parseIPv4Address(address_str: string): TIpAddress = raise newException(ValueError, "Invalid IP Address") result.address_v4[byteCount] = cast[uint8](currentByte) -proc parseIPv6Address(address_str: string): TIpAddress = +proc parseIPv6Address(address_str: string): IpAddress = ## Parses IPv6 adresses ## Raises EInvalidValue on errors result.family = IpAddressFamily.IPv6 @@ -1250,7 +1251,7 @@ proc parseIPv6Address(address_str: string): TIpAddress = raise newException(ValueError, "Invalid IP Address. The address consists of too many groups") -proc parseIpAddress(address_str: string): TIpAddress = +proc parseIpAddress(address_str: string): IpAddress = ## Parses an IP address ## Raises EInvalidValue on error if address_str == nil: diff --git a/lib/pure/nimprof.nim b/lib/pure/nimprof.nim index cce2a20ae..765d1e341 100644 --- a/lib/pure/nimprof.nim +++ b/lib/pure/nimprof.nim @@ -26,17 +26,19 @@ const withThreads = compileOption("threads") tickCountCorrection = 50_000 -when not declared(system.TStackTrace): - type TStackTrace = array [0..20, cstring] +when not declared(system.StackTrace): + type StackTrace = array [0..20, cstring] + {.deprecated: [TStackTrace: StackTrace].} # We use a simple hash table of bounded size to keep track of the stack traces: type - TProfileEntry = object + ProfileEntry = object total: int - st: TStackTrace - TProfileData = array [0..64*1024-1, ptr TProfileEntry] + st: StackTrace + ProfileData = array [0..64*1024-1, ptr ProfileEntry] +{.deprecated: [TProfileEntry: ProfileEntry, TProfileData: ProfileData].} -proc `==`(a, b: TStackTrace): bool = +proc `==`(a, b: StackTrace): bool = for i in 0 .. high(a): if a[i] != b[i]: return false result = true @@ -44,13 +46,13 @@ proc `==`(a, b: TStackTrace): bool = # XXX extract this data structure; it is generally useful ;-) # However a chain length of over 3000 is suspicious... var - profileData: TProfileData + profileData: ProfileData emptySlots = profileData.len * 3 div 2 maxChainLen = 0 totalCalls = 0 when not defined(memProfiler): - var interval: TNanos = 5_000_000 - tickCountCorrection # 5ms + var interval: Nanos = 5_000_000 - tickCountCorrection # 5ms proc setSamplingFrequency*(intervalInUs: int) = ## set this to change the sampling frequency. Default value is 5ms. @@ -62,11 +64,11 @@ when not defined(memProfiler): when withThreads: import locks var - profilingLock: TLock + profilingLock: Lock initLock profilingLock -proc hookAux(st: TStackTrace, costs: int) = +proc hookAux(st: StackTrace, costs: int) = # this is quite performance sensitive! when withThreads: acquire profilingLock inc totalCalls @@ -94,8 +96,8 @@ proc hookAux(st: TStackTrace, costs: int) = var chain = 0 while true: if profileData[h] == nil: - profileData[h] = cast[ptr TProfileEntry]( - allocShared0(sizeof(TProfileEntry))) + profileData[h] = cast[ptr ProfileEntry]( + allocShared0(sizeof(ProfileEntry))) profileData[h].total = costs profileData[h].st = st dec emptySlots @@ -115,7 +117,7 @@ when defined(memProfiler): var gTicker {.threadvar.}: int - proc hook(st: TStackTrace, size: int) {.nimcall.} = + proc hook(st: StackTrace, size: int) {.nimcall.} = if gTicker == 0: gTicker = -1 when defined(ignoreAllocationSize): @@ -127,26 +129,26 @@ when defined(memProfiler): else: var - t0 {.threadvar.}: TTicks + t0 {.threadvar.}: Ticks - proc hook(st: TStackTrace) {.nimcall.} = + proc hook(st: StackTrace) {.nimcall.} = if interval == 0: hookAux(st, 1) elif int64(t0) == 0 or getTicks() - t0 > interval: hookAux(st, 1) t0 = getTicks() -proc getTotal(x: ptr TProfileEntry): int = +proc getTotal(x: ptr ProfileEntry): int = result = if isNil(x): 0 else: x.total -proc cmpEntries(a, b: ptr TProfileEntry): int = +proc cmpEntries(a, b: ptr ProfileEntry): int = result = b.getTotal - a.getTotal proc `//`(a, b: int): string = result = format("$1/$2 = $3%", a, b, formatFloat(a / b * 100.0, ffDefault, 2)) proc writeProfile() {.noconv.} = - when declared(system.TStackTrace): + when declared(system.StackTrace): system.profilerHook = nil const filename = "profile_results.txt" echo "writing " & filename & "..." @@ -161,7 +163,7 @@ proc writeProfile() {.noconv.} = var perProc = initCountTable[string]() for i in 0..entries-1: var dups = initSet[string]() - for ii in 0..high(TStackTrace): + for ii in 0..high(StackTrace): let procname = profileData[i].st[ii] if isNil(procname): break let p = $procname @@ -176,7 +178,7 @@ proc writeProfile() {.noconv.} = writeln(f, "Entry: ", i+1, "/", entries, " Calls: ", profileData[i].total // totalCalls, " [sum: ", sum, "; ", sum // totalCalls, "]") - for ii in 0..high(TStackTrace): + for ii in 0..high(StackTrace): let procname = profileData[i].st[ii] if isNil(procname): break writeln(f, " ", procname, " ", perProc[$procname] // totalCalls) @@ -189,16 +191,16 @@ var disabled: int proc disableProfiling*() = - when declared(system.TStackTrace): + when declared(system.StackTrace): atomicDec disabled system.profilerHook = nil proc enableProfiling*() = - when declared(system.TStackTrace): + when declared(system.StackTrace): if atomicInc(disabled) >= 0: system.profilerHook = hook -when declared(system.TStackTrace): +when declared(system.StackTrace): system.profilerHook = hook addQuitProc(writeProfile) diff --git a/lib/pure/os.nim b/lib/pure/os.nim index 3a5bcbfa1..38ad9d6ec 100644 --- a/lib/pure/os.nim +++ b/lib/pure/os.nim @@ -359,7 +359,7 @@ when defined(windows): template wrapBinary(varname, winApiProc, arg, arg2: expr) {.immediate.} = var varname = winApiProc(newWideCString(arg), arg2) - proc findFirstFile(a: string, b: var TWIN32_FIND_DATA): THandle = + proc findFirstFile(a: string, b: var TWIN32_FIND_DATA): Handle = result = findFirstFileW(newWideCString(a), b) template findNextFile(a, b: expr): expr = findNextFileW(a, b) template getCommandLine(): expr = getCommandLineW() @@ -390,7 +390,7 @@ proc existsFile*(filename: string): bool {.rtl, extern: "nos$1", if a != -1'i32: result = (a and FILE_ATTRIBUTE_DIRECTORY) == 0'i32 else: - var res: TStat + var res: Stat return stat(filename, res) >= 0'i32 and S_ISREG(res.st_mode) proc existsDir*(dir: string): bool {.rtl, extern: "nos$1", tags: [ReadDirEffect].} = @@ -404,7 +404,7 @@ proc existsDir*(dir: string): bool {.rtl, extern: "nos$1", tags: [ReadDirEffect] if a != -1'i32: result = (a and FILE_ATTRIBUTE_DIRECTORY) != 0'i32 else: - var res: TStat + var res: Stat return stat(dir, res) >= 0'i32 and S_ISDIR(res.st_mode) proc symlinkExists*(link: string): bool {.rtl, extern: "nos$1", @@ -419,7 +419,7 @@ proc symlinkExists*(link: string): bool {.rtl, extern: "nos$1", if a != -1'i32: result = (a and FILE_ATTRIBUTE_REPARSE_POINT) != 0'i32 else: - var res: TStat + var res: Stat return lstat(link, res) >= 0'i32 and S_ISLNK(res.st_mode) proc fileExists*(filename: string): bool {.inline.} = @@ -433,7 +433,7 @@ proc dirExists*(dir: string): bool {.inline.} = proc getLastModificationTime*(file: string): Time {.rtl, extern: "nos$1".} = ## Returns the `file`'s last modification time. when defined(posix): - var res: TStat + var res: Stat if stat(file, res) < 0'i32: raiseOSError(osLastError()) return res.st_mtime else: @@ -446,7 +446,7 @@ proc getLastModificationTime*(file: string): Time {.rtl, extern: "nos$1".} = proc getLastAccessTime*(file: string): Time {.rtl, extern: "nos$1".} = ## Returns the `file`'s last read or write access time. when defined(posix): - var res: TStat + var res: Stat if stat(file, res) < 0'i32: raiseOSError(osLastError()) return res.st_atime else: @@ -461,7 +461,7 @@ proc getCreationTime*(file: string): Time {.rtl, extern: "nos$1".} = ## Note that under posix OS's, the returned time may actually be the time at ## which the file's attribute's were last modified. when defined(posix): - var res: TStat + var res: Stat if stat(file, res) < 0'i32: raiseOSError(osLastError()) return res.st_ctime else: @@ -794,7 +794,7 @@ proc isAbsolute*(path: string): bool {.rtl, noSideEffect, extern: "nos$1".} = result = path[0] == '/' when defined(Windows): - proc openHandle(path: string, followSymlink=true): THandle = + proc openHandle(path: string, followSymlink=true): Handle = var flags = FILE_FLAG_BACKUP_SEMANTICS or FILE_ATTRIBUTE_NORMAL if not followSymlink: flags = flags or FILE_FLAG_OPEN_REPARSE_POINT @@ -846,7 +846,7 @@ proc sameFile*(path1, path2: string): bool {.rtl, extern: "nos$1", if not success: raiseOSError(lastErr) else: - var a, b: TStat + var a, b: Stat if stat(path1, a) < 0'i32 or stat(path2, b) < 0'i32: raiseOSError(osLastError()) else: @@ -903,7 +903,7 @@ proc getFilePermissions*(filename: string): set[FilePermission] {. ## an error. On Windows, only the ``readonly`` flag is checked, every other ## permission is available in any case. when defined(posix): - var a: TStat + var a: Stat if stat(filename, a) < 0'i32: raiseOSError(osLastError()) result = {} if (a.st_mode and S_IRUSR) != 0'i32: result.incl(fpUserRead) @@ -1232,7 +1232,7 @@ iterator walkFiles*(pattern: string): string {.tags: [ReadDirEffect].} = findClose(res) else: # here we use glob var - f: TGlob + f: Glob res: int f.gl_offs = 0 f.gl_pathc = 0 @@ -1297,7 +1297,7 @@ iterator walkDir*(dir: string): tuple[kind: PathComponent, path: string] {. if x == nil: break var y = $x.d_name if y != "." and y != "..": - var s: TStat + var s: Stat y = dir / y var k = pcFile @@ -1842,7 +1842,7 @@ proc sleep*(milsecs: int) {.rtl, extern: "nos$1", tags: [TimeEffect].} = when defined(windows): winlean.sleep(int32(milsecs)) else: - var a, b: Ttimespec + var a, b: Timespec a.tv_sec = Time(milsecs div 1000) a.tv_nsec = (milsecs mod 1000) * 1000 * 1000 discard posix.nanosleep(a, b) @@ -1907,8 +1907,8 @@ when defined(Windows): FileId* = int64 else: type - DeviceId* = TDev - FileId* = Tino + DeviceId* = Dev + FileId* = Ino type FileInfo* = object @@ -1925,7 +1925,7 @@ type template rawToFormalFileInfo(rawInfo, formalInfo): expr = ## Transforms the native file info structure into the one nim uses. ## 'rawInfo' is either a 'TBY_HANDLE_FILE_INFORMATION' structure on Windows, - ## or a 'TStat' structure on posix + ## or a 'Stat' structure on posix when defined(Windows): template toTime(e): expr = winTimeToUnixTime(rdFileTime(e)) template merge(a, b): expr = a or (b shl 32) @@ -1996,7 +1996,7 @@ proc getFileInfo*(handle: FileHandle): FileInfo = raiseOSError(osLastError()) rawToFormalFileInfo(rawInfo, result) else: - var rawInfo: TStat + var rawInfo: Stat if fstat(handle, rawInfo) < 0'i32: raiseOSError(osLastError()) rawToFormalFileInfo(rawInfo, result) @@ -2031,7 +2031,7 @@ proc getFileInfo*(path: string, followSymlink = true): FileInfo = rawToFormalFileInfo(rawInfo, result) discard closeHandle(handle) else: - var rawInfo: TStat + var rawInfo: Stat if followSymlink: if stat(path, rawInfo) < 0'i32: raiseOSError(osLastError()) diff --git a/lib/pure/osproc.nim b/lib/pure/osproc.nim index dc6f21174..f4a0ae3a0 100644 --- a/lib/pure/osproc.nim +++ b/lib/pure/osproc.nim @@ -26,13 +26,13 @@ when defined(linux): type ProcessObj = object of RootObj when defined(windows): - fProcessHandle: THandle + fProcessHandle: Handle inHandle, outHandle, errHandle: FileHandle - id: THandle + id: Handle else: inHandle, outHandle, errHandle: FileHandle inStream, outStream, errStream: Stream - id: TPid + id: Pid exitCode: cint Process* = ref ProcessObj ## represents an operating system process @@ -334,10 +334,11 @@ when not defined(useNimRtl): when defined(Windows) and not defined(useNimRtl): # We need to implement a handle stream for Windows: type - PFileHandleStream = ref TFileHandleStream - TFileHandleStream = object of StreamObj - handle: THandle + PFileHandleStream = ref FileHandleStream + FileHandleStream = object of StreamObj + handle: Handle atTheEnd: bool + {.deprecated: [TFileHandleStream: FileHandleStream].} proc hsClose(s: Stream) = discard # nothing to do here proc hsAtEnd(s: Stream): bool = return PFileHandleStream(s).atTheEnd @@ -361,7 +362,7 @@ when defined(Windows) and not defined(useNimRtl): addr bytesWritten, nil) if a == 0: raiseOSError(osLastError()) - proc newFileHandleStream(handle: THandle): PFileHandleStream = + proc newFileHandleStream(handle: Handle): PFileHandleStream = new(result) result.handle = handle result.closeImpl = hsClose @@ -387,14 +388,14 @@ when defined(Windows) and not defined(useNimRtl): copyMem(addr(result[L]), cstring(x), x.len+1) # copy \0 inc(L, x.len+1) - #proc open_osfhandle(osh: THandle, mode: int): int {. + #proc open_osfhandle(osh: Handle, mode: int): int {. # importc: "_open_osfhandle", header: "".} #var # O_WRONLY {.importc: "_O_WRONLY", header: "".}: int # O_RDONLY {.importc: "_O_RDONLY", header: "".}: int - proc createPipeHandles(rdHandle, wrHandle: var THandle) = + proc createPipeHandles(rdHandle, wrHandle: var Handle) = var piInheritablePipe: TSECURITY_ATTRIBUTES piInheritablePipe.nLength = sizeof(TSECURITY_ATTRIBUTES).cint piInheritablePipe.lpSecurityDescriptor = nil @@ -402,7 +403,7 @@ when defined(Windows) and not defined(useNimRtl): if createPipe(rdHandle, wrHandle, piInheritablePipe, 1024) == 0'i32: raiseOSError(osLastError()) - proc fileClose(h: THandle) {.inline.} = + proc fileClose(h: Handle) {.inline.} = if h > 4: discard closeHandle(h) proc startProcess(command: string, @@ -414,7 +415,7 @@ when defined(Windows) and not defined(useNimRtl): si: TSTARTUPINFO procInfo: TPROCESS_INFORMATION success: int - hi, ho, he: THandle + hi, ho, he: Handle new(result) si.cb = sizeof(si).cint if poParentStreams notin options: @@ -527,7 +528,7 @@ when defined(Windows) and not defined(useNimRtl): var si: TSTARTUPINFO procInfo: TPROCESS_INFORMATION - process: THandle + process: Handle L: int32 si.cb = sizeof(si).cint si.hStdError = getStdHandle(STD_ERROR_HANDLE) @@ -595,7 +596,7 @@ elif not defined(useNimRtl): copyMem(result[i], addr(x[0]), x.len+1) inc(i) - type TStartProcessData = object + type StartProcessData = object sysCommand: cstring sysArgs: cstringArray sysEnv: cstringArray @@ -604,14 +605,15 @@ elif not defined(useNimRtl): optionPoUsePath: bool optionPoParentStreams: bool optionPoStdErrToStdOut: bool + {.deprecated: [TStartProcessData: StartProcessData].} when not defined(useFork): - proc startProcessAuxSpawn(data: TStartProcessData): TPid {. + proc startProcessAuxSpawn(data: StartProcessData): Pid {. tags: [ExecIOEffect, ReadEnvEffect], gcsafe.} - proc startProcessAuxFork(data: TStartProcessData): TPid {. + proc startProcessAuxFork(data: StartProcessData): Pid {. tags: [ExecIOEffect, ReadEnvEffect], gcsafe.} {.push stacktrace: off, profiler: off.} - proc startProcessAfterFork(data: ptr TStartProcessData) {. + proc startProcessAfterFork(data: ptr StartProcessData) {. tags: [ExecIOEffect, ReadEnvEffect], cdecl, gcsafe.} {.pop.} @@ -641,7 +643,7 @@ elif not defined(useNimRtl): for arg in args.items: sysArgsRaw.add arg - var pid: TPid + var pid: Pid var sysArgs = allocCStringArray(sysArgsRaw) defer: deallocCStringArray(sysArgs) @@ -653,7 +655,7 @@ elif not defined(useNimRtl): defer: deallocCStringArray(sysEnv) - var data: TStartProcessData + var data: StartProcessData data.sysCommand = sysCommand data.sysArgs = sysArgs data.sysEnv = sysEnv @@ -698,7 +700,7 @@ elif not defined(useNimRtl): discard close(pStdout[writeIdx]) when not defined(useFork): - proc startProcessAuxSpawn(data: TStartProcessData): TPid = + proc startProcessAuxSpawn(data: StartProcessData): Pid = var attr: Tposix_spawnattr var fops: Tposix_spawn_file_actions @@ -708,7 +710,7 @@ elif not defined(useNimRtl): chck posix_spawn_file_actions_init(fops) chck posix_spawnattr_init(attr) - var mask: Tsigset + var mask: Sigset chck sigemptyset(mask) chck posix_spawnattr_setsigmask(attr, mask) chck posix_spawnattr_setpgroup(attr, 0'i32) @@ -732,7 +734,7 @@ elif not defined(useNimRtl): # FIXME: chdir is global to process if data.workingDir.len > 0: setCurrentDir($data.workingDir) - var pid: TPid + var pid: Pid if data.optionPoUsePath: res = posix_spawnp(pid, data.sysCommand, fops, attr, data.sysArgs, data.sysEnv) @@ -744,14 +746,14 @@ elif not defined(useNimRtl): chck res return pid - proc startProcessAuxFork(data: TStartProcessData): TPid = + proc startProcessAuxFork(data: StartProcessData): Pid = if pipe(data.pErrorPipe) != 0: raiseOSError(osLastError()) defer: discard close(data.pErrorPipe[readIdx]) - var pid: TPid + var pid: Pid var dataCopy = data when defined(useClone): @@ -781,7 +783,7 @@ elif not defined(useNimRtl): return pid {.push stacktrace: off, profiler: off.} - proc startProcessFail(data: ptr TStartProcessData) = + proc startProcessFail(data: ptr StartProcessData) = var error: cint = errno discard write(data.pErrorPipe[writeIdx], addr error, sizeof(error)) exitnow(1) @@ -789,7 +791,7 @@ elif not defined(useNimRtl): when defined(macosx) or defined(freebsd): var environ {.importc.}: cstringArray - proc startProcessAfterFork(data: ptr TStartProcessData) = + proc startProcessAfterFork(data: ptr StartProcessData) = # Warning: no GC here! # Or anything that touches global structures - all called nim procs # must be marked with stackTrace:off. Inspect C code after making changes. From d18e18060ed25f12f1fd845b3900369c8f46fb44 Mon Sep 17 00:00:00 2001 From: pdw Date: Sun, 24 May 2015 22:34:41 -0500 Subject: [PATCH 0352/1263] lib/pure/p-t - Dropped 'T' from types --- lib/pure/parseopt.nim | 2 +- lib/pure/pegs.nim | 47 +++++++++++++++++++++-------------------- lib/pure/rationals.nim | 4 ++-- lib/pure/rawsockets.nim | 6 +++--- lib/pure/redis.nim | 16 +++++++------- lib/pure/selectors.nim | 4 ++-- lib/pure/sexp.nim | 15 +++++++------ lib/pure/sockets.nim | 9 ++++---- lib/pure/streams.nim | 2 +- lib/pure/strtabs.nim | 8 +++---- lib/pure/strutils.nim | 3 ++- lib/pure/subexes.nim | 31 ++++++++++++++------------- lib/pure/terminal.nim | 26 +++++++++++------------ 13 files changed, 89 insertions(+), 84 deletions(-) diff --git a/lib/pure/parseopt.nim b/lib/pure/parseopt.nim index 4c92a7cdf..e9d10b51a 100644 --- a/lib/pure/parseopt.nim +++ b/lib/pure/parseopt.nim @@ -133,7 +133,7 @@ proc cmdLineRest*(p: OptParser): TaintedString {.rtl, extern: "npo$1".} = when declared(initOptParser): iterator getopt*(): tuple[kind: CmdLineKind, key, val: TaintedString] = ## This is an convenience iterator for iterating over the command line. - ## This uses the TOptParser object. Example: + ## This uses the OptParser object. Example: ## ## .. code-block:: nim ## var diff --git a/lib/pure/pegs.nim b/lib/pure/pegs.nim index 39f0bfa95..ce837d9d1 100644 --- a/lib/pure/pegs.nim +++ b/lib/pure/pegs.nim @@ -74,8 +74,8 @@ type line: int ## line the symbol has been declared/used in col: int ## column the symbol has been declared/used in flags: set[NonTerminalFlag] ## the nonterminal's flags - rule: TNode ## the rule that the symbol refers to - TNode {.shallow.} = object + rule: Node ## the rule that the symbol refers to + Node {.shallow.} = object case kind: PegKind of pkEmpty..pkWhitespace: nil of pkTerminal, pkTerminalIgnoreCase, pkTerminalIgnoreStyle: term: string @@ -83,12 +83,12 @@ type of pkCharChoice, pkGreedyRepSet: charChoice: ref set[char] of pkNonTerminal: nt: NonTerminal of pkBackRef..pkBackRefIgnoreStyle: index: range[0..MaxSubpatterns] - else: sons: seq[TNode] + else: sons: seq[Node] NonTerminal* = ref NonTerminalObj - Peg* = TNode ## type that represents a PEG + Peg* = Node ## type that represents a PEG -{.deprecated: [TPeg: Peg].} +{.deprecated: [TPeg: Peg, TNode: Node].} proc term*(t: string): Peg {.nosideEffect, rtl, extern: "npegs$1Str".} = ## constructs a PEG from a terminal string @@ -1014,12 +1014,12 @@ proc split*(s: string, sep: Peg): seq[string] {. # ------------------- scanner ------------------------------------------------- type - TModifier = enum + Modifier = enum modNone, modVerbatim, modIgnoreCase, modIgnoreStyle - TTokKind = enum ## enumeration of all tokens + TokKind = enum ## enumeration of all tokens tkInvalid, ## invalid token tkEof, ## end of file reached tkAny, ## . @@ -1046,9 +1046,9 @@ type tkDollar, ## '$' tkHat ## '^' - TToken {.final.} = object ## a token - kind: TTokKind ## the type of the token - modifier: TModifier + Token {.final.} = object ## a token + kind: TokKind ## the type of the token + modifier: Modifier literal: string ## the parsed (string) literal charset: set[char] ## if kind == tkCharSet index: int ## if kind == tkBackref @@ -1060,9 +1060,10 @@ type lineStart: int ## index of last line start in buffer colOffset: int ## column to add filename: string +{.deprecated: [TTokKind: TokKind, TToken: Token, TModifier: Modifier].} const - tokKindToStr: array[TTokKind, string] = [ + tokKindToStr: array[TokKind, string] = [ "invalid", "[EOF]", ".", "_", "identifier", "string literal", "character set", "(", ")", "{", "}", "{@}", "<-", "/", "*", "+", "&", "!", "?", @@ -1114,7 +1115,7 @@ proc handleHexChar(c: var PegLexer, xi: var int) = inc(c.bufpos) else: discard -proc getEscapedChar(c: var PegLexer, tok: var TToken) = +proc getEscapedChar(c: var PegLexer, tok: var Token) = inc(c.bufpos) case c.buf[c.bufpos] of 'r', 'R', 'c', 'C': @@ -1185,7 +1186,7 @@ proc skip(c: var PegLexer) = break # EndOfFile also leaves the loop c.bufpos = pos -proc getString(c: var PegLexer, tok: var TToken) = +proc getString(c: var PegLexer, tok: var Token) = tok.kind = tkStringLit var pos = c.bufpos + 1 var buf = c.buf @@ -1207,7 +1208,7 @@ proc getString(c: var PegLexer, tok: var TToken) = inc(pos) c.bufpos = pos -proc getDollar(c: var PegLexer, tok: var TToken) = +proc getDollar(c: var PegLexer, tok: var Token) = var pos = c.bufpos + 1 var buf = c.buf if buf[pos] in {'0'..'9'}: @@ -1220,7 +1221,7 @@ proc getDollar(c: var PegLexer, tok: var TToken) = tok.kind = tkDollar c.bufpos = pos -proc getCharSet(c: var PegLexer, tok: var TToken) = +proc getCharSet(c: var PegLexer, tok: var Token) = tok.kind = tkCharSet tok.charset = {} var pos = c.bufpos + 1 @@ -1271,7 +1272,7 @@ proc getCharSet(c: var PegLexer, tok: var TToken) = c.bufpos = pos if caret: tok.charset = {'\1'..'\xFF'} - tok.charset -proc getSymbol(c: var PegLexer, tok: var TToken) = +proc getSymbol(c: var PegLexer, tok: var Token) = var pos = c.bufpos var buf = c.buf while true: @@ -1281,7 +1282,7 @@ proc getSymbol(c: var PegLexer, tok: var TToken) = c.bufpos = pos tok.kind = tkIdentifier -proc getBuiltin(c: var PegLexer, tok: var TToken) = +proc getBuiltin(c: var PegLexer, tok: var Token) = if c.buf[c.bufpos+1] in strutils.Letters: inc(c.bufpos) getSymbol(c, tok) @@ -1290,7 +1291,7 @@ proc getBuiltin(c: var PegLexer, tok: var TToken) = tok.kind = tkEscaped getEscapedChar(c, tok) # may set tok.kind to tkInvalid -proc getTok(c: var PegLexer, tok: var TToken) = +proc getTok(c: var PegLexer, tok: var Token) = tok.kind = tkInvalid tok.modifier = modNone setLen(tok.literal, 0) @@ -1408,9 +1409,9 @@ type EInvalidPeg* = object of ValueError ## raised if an invalid ## PEG has been detected PegParser = object of PegLexer ## the PEG parser object - tok: TToken + tok: Token nonterms: seq[NonTerminal] - modifier: TModifier + modifier: Modifier captures: int identIsVerbatim: bool skip: Peg @@ -1425,7 +1426,7 @@ proc getTok(p: var PegParser) = getTok(p, p.tok) if p.tok.kind == tkInvalid: pegError(p, "invalid token") -proc eat(p: var PegParser, kind: TTokKind) = +proc eat(p: var PegParser, kind: TokKind) = if p.tok.kind == kind: getTok(p) else: pegError(p, tokKindToStr[kind] & " expected") @@ -1439,13 +1440,13 @@ proc getNonTerminal(p: var PegParser, name: string): NonTerminal = result = newNonTerminal(name, getLine(p), getColumn(p)) add(p.nonterms, result) -proc modifiedTerm(s: string, m: TModifier): Peg = +proc modifiedTerm(s: string, m: Modifier): Peg = case m of modNone, modVerbatim: result = term(s) of modIgnoreCase: result = termIgnoreCase(s) of modIgnoreStyle: result = termIgnoreStyle(s) -proc modifiedBackref(s: int, m: TModifier): Peg = +proc modifiedBackref(s: int, m: Modifier): Peg = case m of modNone, modVerbatim: result = backref(s) of modIgnoreCase: result = backrefIgnoreCase(s) diff --git a/lib/pure/rationals.nim b/lib/pure/rationals.nim index 3b68a2381..8e1dbe464 100644 --- a/lib/pure/rationals.nim +++ b/lib/pure/rationals.nim @@ -206,13 +206,13 @@ proc abs*[T](x: Rational[T]): Rational[T] = result.num = abs x.num result.den = abs x.den -proc hash*[T](x: Rational[T]): THash = +proc hash*[T](x: Rational[T]): Hash = ## Computes hash for rational `x` # reduce first so that hash(x) == hash(y) for x == y var copy = x reduce(copy) - var h: THash = 0 + var h: Hash = 0 h = h !& hash(copy.num) h = h !& hash(copy.den) result = !$h diff --git a/lib/pure/rawsockets.nim b/lib/pure/rawsockets.nim index d08c5b769..6d656c983 100644 --- a/lib/pure/rawsockets.nim +++ b/lib/pure/rawsockets.nim @@ -106,13 +106,13 @@ proc `$`*(p: Port): string {.borrow.} ## returns the port number as a string proc toInt*(domain: Domain): cint - ## Converts the TDomain enum to a platform-dependent ``cint``. + ## Converts the Domain enum to a platform-dependent ``cint``. proc toInt*(typ: SockType): cint - ## Converts the TType enum to a platform-dependent ``cint``. + ## Converts the SockType enum to a platform-dependent ``cint``. proc toInt*(p: Protocol): cint - ## Converts the TProtocol enum to a platform-dependent ``cint``. + ## Converts the Protocol enum to a platform-dependent ``cint``. when not useWinVersion: proc toInt(domain: Domain): cint = diff --git a/lib/pure/redis.nim b/lib/pure/redis.nim index aa2e0f9bd..b738e4094 100644 --- a/lib/pure/redis.nim +++ b/lib/pure/redis.nim @@ -10,8 +10,8 @@ ## This module implements a redis client. It allows you to connect to a ## redis-server instance, send commands and receive replies. ## -## **Beware**: Most (if not all) functions that return a ``TRedisString`` may -## return ``redisNil``, and functions which return a ``TRedisList`` +## **Beware**: Most (if not all) functions that return a ``RedisString`` may +## return ``redisNil``, and functions which return a ``RedisList`` ## may return ``nil``. import sockets, os, strutils, parseutils @@ -843,27 +843,27 @@ proc pfmerge*(r: Redis, destination: string, sources: varargs[string]) = # TODO: pub/sub -- I don't think this will work synchronously. discard """ -proc psubscribe*(r: TRedis, pattern: openarray[string]): ???? = +proc psubscribe*(r: Redis, pattern: openarray[string]): ???? = ## Listen for messages published to channels matching the given patterns r.socket.send("PSUBSCRIBE $#\c\L" % pattern) return ??? -proc publish*(r: TRedis, channel: string, message: string): TRedisInteger = +proc publish*(r: Redis, channel: string, message: string): RedisInteger = ## Post a message to a channel r.socket.send("PUBLISH $# $#\c\L" % [channel, message]) return r.readInteger() -proc punsubscribe*(r: TRedis, [pattern: openarray[string], : string): ???? = +proc punsubscribe*(r: Redis, [pattern: openarray[string], : string): ???? = ## Stop listening for messages posted to channels matching the given patterns r.socket.send("PUNSUBSCRIBE $# $#\c\L" % [[pattern.join(), ]) return ??? -proc subscribe*(r: TRedis, channel: openarray[string]): ???? = +proc subscribe*(r: Redis, channel: openarray[string]): ???? = ## Listen for messages published to the given channels r.socket.send("SUBSCRIBE $#\c\L" % channel.join) return ??? -proc unsubscribe*(r: TRedis, [channel: openarray[string], : string): ???? = +proc unsubscribe*(r: Redis, [channel: openarray[string], : string): ???? = ## Stop listening for messages posted to the given channels r.socket.send("UNSUBSCRIBE $# $#\c\L" % [[channel.join(), ]) return ??? @@ -991,7 +991,7 @@ proc lastsave*(r: Redis): RedisInteger = return r.readInteger() discard """ -proc monitor*(r: TRedis) = +proc monitor*(r: Redis) = ## Listen for all requests received by the server in real time r.socket.send("MONITOR\c\L") raiseNoOK(r.readStatus(), r.pipeline.enabled) diff --git a/lib/pure/selectors.nim b/lib/pure/selectors.nim index 6901ecf58..e44b87051 100644 --- a/lib/pure/selectors.nim +++ b/lib/pure/selectors.nim @@ -18,7 +18,7 @@ elif defined(windows): else: import posix -proc hash*(x: SocketHandle): THash {.borrow.} +proc hash*(x: SocketHandle): Hash {.borrow.} proc `$`*(x: SocketHandle): string {.borrow.} type @@ -41,7 +41,7 @@ when defined(nimdoc): proc register*(s: Selector, fd: SocketHandle, events: set[Event], data: RootRef): SelectorKey {.discardable.} = - ## Registers file descriptor ``fd`` to selector ``s`` with a set of TEvent + ## Registers file descriptor ``fd`` to selector ``s`` with a set of Event ## ``events``. proc update*(s: Selector, fd: SocketHandle, diff --git a/lib/pure/sexp.nim b/lib/pure/sexp.nim index 3c9fbc150..be6188c9e 100644 --- a/lib/pure/sexp.nim +++ b/lib/pure/sexp.nim @@ -23,7 +23,7 @@ type sexpListStart, ## start of a list: the ``(`` token sexpListEnd, ## end of a list: the ``)`` token - TTokKind = enum # must be synchronized with SexpEventKind! + TokKind = enum # must be synchronized with SexpEventKind! tkError, tkEof, tkString, @@ -45,9 +45,10 @@ type SexpParser* = object of BaseLexer ## the parser object. a: string - tok: TTokKind + tok: TokKind kind: SexpEventKind err: SexpError +{.deprecated: [TTokKind: TokKind].} const errorMessages: array [SexpError, string] = [ @@ -57,7 +58,7 @@ const "'\"' or \"'\" expected", "EOF expected", ] - tokToStr: array [TTokKind, string] = [ + tokToStr: array [TokKind, string] = [ "invalid token", "EOF", "string literal", @@ -119,7 +120,7 @@ proc handleHexChar(c: char, x: var int): bool = of 'A'..'F': x = (x shl 4) or (ord(c) - ord('A') + 10) else: result = false # error -proc parseString(my: var SexpParser): TTokKind = +proc parseString(my: var SexpParser): TokKind = result = tkString var pos = my.bufpos + 1 var buf = my.buf @@ -217,7 +218,7 @@ proc parseSymbol(my: var SexpParser) = inc(pos) my.bufpos = pos -proc getTok(my: var SexpParser): TTokKind = +proc getTok(my: var SexpParser): TokKind = setLen(my.a, 0) case my.buf[my.bufpos] of '-', '0'..'9': # numbers that start with a . are not parsed @@ -466,7 +467,7 @@ proc `==`* (a,b: SexpNode): bool = of SCons: a.car == b.car and a.cdr == b.cdr -proc hash* (n:SexpNode): THash = +proc hash* (n:SexpNode): Hash = ## Compute the hash for a SEXP node case n.kind of SList: @@ -620,7 +621,7 @@ iterator mitems*(node: var SexpNode): var SexpNode = for i in mitems(node.elems): yield i -proc eat(p: var SexpParser, tok: TTokKind) = +proc eat(p: var SexpParser, tok: TokKind) = if p.tok == tok: discard getTok(p) else: raiseParseErr(p, tokToStr[tok]) diff --git a/lib/pure/sockets.nim b/lib/pure/sockets.nim index 64e2cdcd3..a10255e5b 100644 --- a/lib/pure/sockets.nim +++ b/lib/pure/sockets.nim @@ -75,7 +75,7 @@ const BufferSize*: int = 4000 ## size of a buffered socket's buffer type - TSocketImpl = object ## socket type + SocketImpl = object ## socket type fd: SocketHandle case isBuffered: bool # determines whether this socket is buffered. of true: @@ -94,7 +94,7 @@ type of false: nil nonblocking: bool - Socket* = ref TSocketImpl + Socket* = ref SocketImpl Port* = distinct uint16 ## port type @@ -146,8 +146,9 @@ type {.deprecated: [TSocket: Socket, TType: SockType, TPort: Port, TDomain: Domain, TProtocol: Protocol, TServent: Servent, THostent: Hostent, - TSOBool: SOBool, TRecvLineResult: RecvLineResult, - TReadLineResult: ReadLineResult, ETimeout: TimeoutError].} + TSOBool: SOBool, TRecvLineResult: RecvLineResult, + TReadLineResult: ReadLineResult, ETimeout: TimeoutError, + TSocketImpl: SocketImpl].} when defined(booting): let invalidSocket*: Socket = nil ## invalid socket diff --git a/lib/pure/streams.nim b/lib/pure/streams.nim index c85a09bad..e6004b5d0 100644 --- a/lib/pure/streams.nim +++ b/lib/pure/streams.nim @@ -327,7 +327,7 @@ proc newStringStream*(s: string = ""): StringStream = when not defined(js): type - FileStream* = ref FileStreamObj ## a stream that encapsulates a `TFile` + FileStream* = ref FileStreamObj ## a stream that encapsulates a `File` FileStreamObj* = object of Stream f: File {.deprecated: [PFileStream: FileStream, TFileStream: FileStreamObj].} diff --git a/lib/pure/strtabs.nim b/lib/pure/strtabs.nim index 7fdd994f2..86f81aa43 100644 --- a/lib/pure/strtabs.nim +++ b/lib/pure/strtabs.nim @@ -74,7 +74,7 @@ const growthFactor = 2 startSize = 64 -proc myhash(t: StringTableRef, key: string): THash = +proc myhash(t: StringTableRef, key: string): Hash = case t.mode of modeCaseSensitive: result = hashes.hash(key) of modeCaseInsensitive: result = hashes.hashIgnoreCase(key) @@ -90,11 +90,11 @@ proc mustRehash(length, counter: int): bool = assert(length > counter) result = (length * 2 < counter * 3) or (length - counter < 4) -proc nextTry(h, maxHash: THash): THash {.inline.} = +proc nextTry(h, maxHash: Hash): Hash {.inline.} = result = ((5 * h) + 1) and maxHash proc rawGet(t: StringTableRef, key: string): int = - var h: THash = myhash(t, key) and high(t.data) # start with real hash value + var h: Hash = myhash(t, key) and high(t.data) # start with real hash value while not isNil(t.data[h].key): if myCmp(t, t.data[h].key, key): return h @@ -122,7 +122,7 @@ proc hasKey*(t: StringTableRef, key: string): bool {.rtl, extern: "nst$1".} = result = rawGet(t, key) >= 0 proc rawInsert(t: StringTableRef, data: var KeyValuePairSeq, key, val: string) = - var h: THash = myhash(t, key) and high(data) + var h: Hash = myhash(t, key) and high(data) while not isNil(data[h].key): h = nextTry(h, high(data)) data[h].key = key diff --git a/lib/pure/strutils.nim b/lib/pure/strutils.nim index eb4be719a..317da9a0a 100644 --- a/lib/pure/strutils.nim +++ b/lib/pure/strutils.nim @@ -23,7 +23,8 @@ import parseutils include "system/inclrtl" type - TCharSet* {.deprecated.} = set[char] # for compatibility with Nim + CharSet* {.deprecated.} = set[char] # for compatibility with Nim +{.deprecated: [TCharSet: CharSet].} const Whitespace* = {' ', '\t', '\v', '\r', '\l', '\f'} diff --git a/lib/pure/subexes.nim b/lib/pure/subexes.nim index d213c99e6..46824645d 100644 --- a/lib/pure/subexes.nim +++ b/lib/pure/subexes.nim @@ -37,13 +37,14 @@ proc raiseInvalidFormat(msg: string) {.noinline.} = raise newException(SubexError, "invalid format string: " & msg) type - TFormatParser = object {.pure, final.} + FormatParser = object {.pure, final.} when defined(js): f: string # we rely on the '\0' terminator # which JS's native string doesn't have else: f: cstring num, i, lineLen: int +{.deprecated: [TFormatParser: FormatParser].} template call(x: stmt) {.immediate.} = p.i = i @@ -57,7 +58,7 @@ template callNoLineLenTracking(x: stmt) {.immediate.} = i = p.i p.lineLen = oldLineLen -proc getFormatArg(p: var TFormatParser, a: openArray[string]): int = +proc getFormatArg(p: var FormatParser, a: openArray[string]): int = const PatternChars = {'a'..'z', 'A'..'Z', '0'..'9', '\128'..'\255', '_'} var i = p.i var f = p.f @@ -90,22 +91,22 @@ proc getFormatArg(p: var TFormatParser, a: openArray[string]): int = if result >=% a.len: raiseInvalidFormat("index out of bounds: " & $result) p.i = i -proc scanDollar(p: var TFormatParser, a: openarray[string], s: var string) {. +proc scanDollar(p: var FormatParser, a: openarray[string], s: var string) {. noSideEffect.} -proc emitChar(p: var TFormatParser, x: var string, ch: char) {.inline.} = +proc emitChar(p: var FormatParser, x: var string, ch: char) {.inline.} = x.add(ch) if ch == '\L': p.lineLen = 0 else: inc p.lineLen -proc emitStrLinear(p: var TFormatParser, x: var string, y: string) {.inline.} = +proc emitStrLinear(p: var FormatParser, x: var string, y: string) {.inline.} = for ch in items(y): emitChar(p, x, ch) -proc emitStr(p: var TFormatParser, x: var string, y: string) {.inline.} = +proc emitStr(p: var FormatParser, x: var string, y: string) {.inline.} = x.add(y) inc p.lineLen, y.len -proc scanQuote(p: var TFormatParser, x: var string, toAdd: bool) = +proc scanQuote(p: var FormatParser, x: var string, toAdd: bool) = var i = p.i+1 var f = p.f while true: @@ -120,7 +121,7 @@ proc scanQuote(p: var TFormatParser, x: var string, toAdd: bool) = inc i p.i = i -proc scanBranch(p: var TFormatParser, a: openArray[string], +proc scanBranch(p: var FormatParser, a: openArray[string], x: var string, choice: int) = var i = p.i var f = p.f @@ -167,7 +168,7 @@ proc scanBranch(p: var TFormatParser, a: openArray[string], i = last p.i = i+1 -proc scanSlice(p: var TFormatParser, a: openarray[string]): tuple[x, y: int] = +proc scanSlice(p: var FormatParser, a: openarray[string]): tuple[x, y: int] = var slice = false var i = p.i var f = p.f @@ -193,7 +194,7 @@ proc scanSlice(p: var TFormatParser, a: openarray[string]): tuple[x, y: int] = inc i p.i = i -proc scanDollar(p: var TFormatParser, a: openarray[string], s: var string) = +proc scanDollar(p: var FormatParser, a: openarray[string], s: var string) = var i = p.i var f = p.f case f[i] @@ -312,7 +313,7 @@ proc subex*(s: string): Subex = proc addf*(s: var string, formatstr: Subex, a: varargs[string, `$`]) {. noSideEffect, rtl, extern: "nfrmtAddf".} = ## The same as ``add(s, formatstr % a)``, but more efficient. - var p: TFormatParser + var p: FormatParser p.f = formatstr.string var i = 0 while i < len(formatstr.string): @@ -386,10 +387,10 @@ when isMainModule: longishA, longish)""" - assert "type TMyEnum* = enum\n $', '2i'\n '{..}" % ["fieldA", + assert "type MyEnum* = enum\n $', '2i'\n '{..}" % ["fieldA", "fieldB", "FiledClkad", "fieldD", "fieldE", "longishFieldName"] == strutils.unindent """ - type TMyEnum* = enum + type MyEnum* = enum fieldA, fieldB, FiledClkad, fieldD, fieldE, longishFieldName""" @@ -400,11 +401,11 @@ when isMainModule: doAssert subex"$['''|'|''''|']']#" % "0" == "'|" - assert subex("type\n TEnum = enum\n $', '40c'\n '{..}") % [ + assert subex("type\n Enum = enum\n $', '40c'\n '{..}") % [ "fieldNameA", "fieldNameB", "fieldNameC", "fieldNameD"] == strutils.unindent """ type - TEnum = enum + Enum = enum fieldNameA, fieldNameB, fieldNameC, fieldNameD""" diff --git a/lib/pure/terminal.nim b/lib/pure/terminal.nim index 7b4d548fe..1e9c40f06 100644 --- a/lib/pure/terminal.nim +++ b/lib/pure/terminal.nim @@ -20,7 +20,7 @@ when defined(windows): import windows, os var - conHandle: THandle + conHandle: Handle # = createFile("CONOUT$", GENERIC_WRITE, 0, nil, OPEN_ALWAYS, 0, 0) block: @@ -30,13 +30,13 @@ when defined(windows): raiseOSError(osLastError()) proc getCursorPos(): tuple [x,y: int] = - var c: TCONSOLESCREENBUFFERINFO + var c: CONSOLESCREENBUFFERINFO if GetConsoleScreenBufferInfo(conHandle, addr(c)) == 0: raiseOSError(osLastError()) return (int(c.dwCursorPosition.X), int(c.dwCursorPosition.Y)) proc getAttributes(): int16 = - var c: TCONSOLESCREENBUFFERINFO + var c: CONSOLESCREENBUFFERINFO # workaround Windows bugs: try several times if GetConsoleScreenBufferInfo(conHandle, addr(c)) != 0: return c.wAttributes @@ -51,11 +51,11 @@ else: proc setRaw(fd: FileHandle, time: cint = TCSAFLUSH) = var mode: Termios discard fd.tcgetattr(addr mode) - mode.c_iflag = mode.c_iflag and not Tcflag(BRKINT or ICRNL or INPCK or + mode.c_iflag = mode.c_iflag and not Cflag(BRKINT or ICRNL or INPCK or ISTRIP or IXON) - mode.c_oflag = mode.c_oflag and not Tcflag(OPOST) - mode.c_cflag = (mode.c_cflag and not Tcflag(CSIZE or PARENB)) or CS8 - mode.c_lflag = mode.c_lflag and not Tcflag(ECHO or ICANON or IEXTEN or ISIG) + mode.c_oflag = mode.c_oflag and not Cflag(OPOST) + mode.c_cflag = (mode.c_cflag and not Cflag(CSIZE or PARENB)) or CS8 + mode.c_lflag = mode.c_lflag and not Cflag(ECHO or ICANON or IEXTEN or ISIG) mode.c_cc[VMIN] = 1.cuchar mode.c_cc[VTIME] = 0.cuchar discard fd.tcsetattr(time, addr mode) @@ -64,7 +64,7 @@ proc setCursorPos*(x, y: int) = ## sets the terminal's cursor to the (x,y) position. (0,0) is the ## upper left of the screen. when defined(windows): - var c: TCOORD + var c: COORD c.X = int16(x) c.Y = int16(y) if SetConsoleCursorPosition(conHandle, c) == 0: raiseOSError(osLastError()) @@ -75,7 +75,7 @@ proc setCursorXPos*(x: int) = ## sets the terminal's cursor to the x position. The y position is ## not changed. when defined(windows): - var scrbuf: TCONSOLESCREENBUFFERINFO + var scrbuf: CONSOLESCREENBUFFERINFO var hStdout = conHandle if GetConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0: raiseOSError(osLastError()) @@ -91,7 +91,7 @@ when defined(windows): ## sets the terminal's cursor to the y position. The x position is ## not changed. **Warning**: This is not supported on UNIX! when defined(windows): - var scrbuf: TCONSOLESCREENBUFFERINFO + var scrbuf: CONSOLESCREENBUFFERINFO var hStdout = conHandle if GetConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0: raiseOSError(osLastError()) @@ -172,7 +172,7 @@ else: proc eraseLine* = ## Erases the entire current line. when defined(windows): - var scrbuf: TCONSOLESCREENBUFFERINFO + var scrbuf: CONSOLESCREENBUFFERINFO var numwrote: DWORD var hStdout = conHandle if GetConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0: @@ -196,9 +196,9 @@ proc eraseLine* = proc eraseScreen* = ## Erases the screen with the background colour and moves the cursor to home. when defined(windows): - var scrbuf: TCONSOLESCREENBUFFERINFO + var scrbuf: CONSOLESCREENBUFFERINFO var numwrote: DWORD - var origin: TCOORD # is inititalized to 0, 0 + var origin: COORD # is inititalized to 0, 0 var hStdout = conHandle if GetConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0: From ff5b446dfc32f2121799f1a8b90c913ceb52401f Mon Sep 17 00:00:00 2001 From: pdw Date: Sun, 24 May 2015 22:37:01 -0500 Subject: [PATCH 0353/1263] lib/system/a-e - Dropped 'T' from types --- lib/system.nim | 20 +++-- lib/system/alloc.nim | 184 ++++++++++++++++++++-------------------- lib/system/atomics.nim | 43 +++++----- lib/system/avltree.nim | 4 +- lib/system/cellsets.nim | 57 +++++++------ lib/system/cgprocs.nim | 11 +-- lib/system/channels.nim | 38 +++++---- lib/system/debugger.nim | 54 ++++++------ lib/system/dyncalls.nim | 36 ++++---- lib/system/endb.nim | 70 +++++++-------- lib/system/excpt.nim | 5 +- 11 files changed, 270 insertions(+), 252 deletions(-) diff --git a/lib/system.nim b/lib/system.nim index fbb3cbfc7..90587f306 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -249,7 +249,7 @@ when defined(nimNewShared): guarded* {.magic: "Guarded".} # comparison operators: -proc `==` *[TEnum: enum](x, y: TEnum): bool {.magic: "EqEnum", noSideEffect.} +proc `==` *[Enum: enum](x, y: Enum): bool {.magic: "EqEnum", noSideEffect.} proc `==` *(x, y: pointer): bool {.magic: "EqRef", noSideEffect.} proc `==` *(x, y: string): bool {.magic: "EqStr", noSideEffect.} proc `==` *(x, y: cstring): bool {.magic: "EqCString", noSideEffect.} @@ -260,7 +260,7 @@ proc `==` *[T](x, y: ref T): bool {.magic: "EqRef", noSideEffect.} proc `==` *[T](x, y: ptr T): bool {.magic: "EqRef", noSideEffect.} proc `==` *[T: proc](x, y: T): bool {.magic: "EqProc", noSideEffect.} -proc `<=` *[TEnum: enum](x, y: TEnum): bool {.magic: "LeEnum", noSideEffect.} +proc `<=` *[Enum: enum](x, y: Enum): bool {.magic: "LeEnum", noSideEffect.} proc `<=` *(x, y: string): bool {.magic: "LeStr", noSideEffect.} proc `<=` *(x, y: char): bool {.magic: "LeCh", noSideEffect.} proc `<=` *[T](x, y: set[T]): bool {.magic: "LeSet", noSideEffect.} @@ -268,7 +268,7 @@ proc `<=` *(x, y: bool): bool {.magic: "LeB", noSideEffect.} proc `<=` *[T](x, y: ref T): bool {.magic: "LePtr", noSideEffect.} proc `<=` *(x, y: pointer): bool {.magic: "LePtr", noSideEffect.} -proc `<` *[TEnum: enum](x, y: TEnum): bool {.magic: "LtEnum", noSideEffect.} +proc `<` *[Enum: enum](x, y: Enum): bool {.magic: "LtEnum", noSideEffect.} proc `<` *(x, y: string): bool {.magic: "LtStr", noSideEffect.} proc `<` *(x, y: char): bool {.magic: "LtCh", noSideEffect.} proc `<` *[T](x, y: set[T]): bool {.magic: "LtSet", noSideEffect.} @@ -332,7 +332,7 @@ type RootObj* {.exportc: "TNimObject", inheritable.} = object ## the root of Nim's object hierarchy. Objects should - ## inherit from TObject or one of its descendants. However, + ## inherit from RootObj or one of its descendants. However, ## objects that have no ancestor are allowed. RootRef* = ref RootObj ## reference to RootObj @@ -1505,7 +1505,7 @@ proc `$` *(x: string): string {.magic: "StrToStr", noSideEffect.} ## as it is. This operator is useful for generic code, so ## that ``$expr`` also works if ``expr`` is already a string. -proc `$` *[TEnum: enum](x: TEnum): string {.magic: "EnumToStr", noSideEffect.} +proc `$` *[Enum: enum](x: Enum): string {.magic: "EnumToStr", noSideEffect.} ## The stringify operator for an enumeration argument. This works for ## any enumeration type thanks to compiler magic. If ## a ``$`` operator for a concrete enumeration is provided, this is @@ -2213,6 +2213,7 @@ type filename*: cstring ## filename of the proc that is currently executing len*: int16 ## length of the inspectable slots calldepth*: int16 ## used for max call depth checking +#{.deprecated: [TFrame: Frame].} when defined(JS): proc add*(x: var string, y: cstring) {.asmNoStackFrame.} = @@ -2414,7 +2415,7 @@ when not defined(JS): #and not defined(NimrodVM): proc open*(f: var File, filehandle: FileHandle, mode: FileMode = fmRead): bool {.tags: [], benign.} - ## Creates a ``TFile`` from a `filehandle` with given `mode`. + ## Creates a ``File`` from a `filehandle` with given `mode`. ## ## Default mode is readonly. Returns true iff the file could be opened. @@ -2604,6 +2605,8 @@ when not defined(JS): #and not defined(NimrodVM): context: C_JmpBuf hasRaiseAction: bool raiseAction: proc (e: ref Exception): bool {.closure.} + SafePoint = TSafePoint +# {.deprecated: [TSafePoint: SafePoint].} when declared(initAllocator): initAllocator() @@ -3054,9 +3057,10 @@ proc raiseAssert*(msg: string) {.noinline.} = proc failedAssertImpl*(msg: string) {.raises: [], tags: [].} = # trick the compiler to not list ``AssertionError`` when called # by ``assert``. - type THide = proc (msg: string) {.noinline, raises: [], noSideEffect, + type Hide = proc (msg: string) {.noinline, raises: [], noSideEffect, tags: [].} - THide(raiseAssert)(msg) + {.deprecated: [THide: Hide].} + Hide(raiseAssert)(msg) template assert*(cond: bool, msg = "") = ## Raises ``AssertionError`` with `msg` if `cond` is false. Note diff --git a/lib/system/alloc.nim b/lib/system/alloc.nim index ad3419808..76232499e 100644 --- a/lib/system/alloc.nim +++ b/lib/system/alloc.nim @@ -98,46 +98,49 @@ const SmallChunkSize = PageSize type - PTrunk = ptr TTrunk - TTrunk {.final.} = object + PTrunk = ptr Trunk + Trunk {.final.} = object next: PTrunk # all nodes are connected with this pointer key: int # start address at bit 0 bits: array[0..IntsPerTrunk-1, int] # a bit vector - TTrunkBuckets = array[0..255, PTrunk] - TIntSet {.final.} = object - data: TTrunkBuckets + TrunkBuckets = array[0..255, PTrunk] + IntSet {.final.} = object + data: TrunkBuckets +{.deprecated: [TIntSet: IntSet, TTrunk: Trunk, TTrunkBuckets: TrunkBuckets].} type - TAlignType = BiggestFloat - TFreeCell {.final, pure.} = object - next: ptr TFreeCell # next free cell in chunk (overlaid with refcount) + AlignType = BiggestFloat + FreeCell {.final, pure.} = object + next: ptr FreeCell # next free cell in chunk (overlaid with refcount) zeroField: int # 0 means cell is not used (overlaid with typ field) # 1 means cell is manually managed pointer # otherwise a PNimType is stored in there - PChunk = ptr TBaseChunk - PBigChunk = ptr TBigChunk - PSmallChunk = ptr TSmallChunk - TBaseChunk {.pure, inheritable.} = object + PChunk = ptr BaseChunk + PBigChunk = ptr BigChunk + PSmallChunk = ptr SmallChunk + BaseChunk {.pure, inheritable.} = object prevSize: int # size of previous chunk; for coalescing size: int # if < PageSize it is a small chunk used: bool # later will be optimized into prevSize... - TSmallChunk = object of TBaseChunk + SmallChunk = object of BaseChunk next, prev: PSmallChunk # chunks of the same size - freeList: ptr TFreeCell + freeList: ptr FreeCell free: int # how many bytes remain acc: int # accumulator for small object allocation - data: TAlignType # start of usable memory + data: AlignType # start of usable memory - TBigChunk = object of TBaseChunk # not necessarily > PageSize! + BigChunk = object of BaseChunk # not necessarily > PageSize! next, prev: PBigChunk # chunks of the same (or bigger) size align: int - data: TAlignType # start of usable memory + data: AlignType # start of usable memory +{.deprecated: [TAlignType: AlignType, TFreeCell: FreeCell, TBaseChunk: BaseChunk, + TBigChunk: BigChunk, TSmallChunk: SmallChunk].} -template smallChunkOverhead(): expr = sizeof(TSmallChunk)-sizeof(TAlignType) -template bigChunkOverhead(): expr = sizeof(TBigChunk)-sizeof(TAlignType) +template smallChunkOverhead(): expr = sizeof(SmallChunk)-sizeof(AlignType) +template bigChunkOverhead(): expr = sizeof(BigChunk)-sizeof(AlignType) proc roundup(x, v: int): int {.inline.} = result = (x + (v-1)) and not (v-1) @@ -156,31 +159,32 @@ sysAssert(roundup(65, 8) == 72, "roundup broken 2") # to the OS), a fixed size array can be used. type - PLLChunk = ptr TLLChunk - TLLChunk {.pure.} = object ## *low-level* chunk + PLLChunk = ptr LLChunk + LLChunk {.pure.} = object ## *low-level* chunk size: int # remaining size acc: int # accumulator next: PLLChunk # next low-level chunk; only needed for dealloc - PAvlNode = ptr TAvlNode - TAvlNode {.pure, final.} = object + PAvlNode = ptr AvlNode + AvlNode {.pure, final.} = object link: array[0..1, PAvlNode] # Left (0) and right (1) links key, upperBound: int level: int - TMemRegion {.final, pure.} = object + MemRegion {.final, pure.} = object minLargeObj, maxLargeObj: int freeSmallChunks: array[0..SmallChunkSize div MemAlign-1, PSmallChunk] llmem: PLLChunk currMem, maxMem, freeMem: int # memory sizes (allocated from OS) lastSize: int # needed for the case that OS gives us pages linearly freeChunksList: PBigChunk # XXX make this a datastructure with O(1) access - chunkStarts: TIntSet + chunkStarts: IntSet root, deleted, last, freeAvlNodes: PAvlNode +{.deprecated: [TLLChunk: LLChunk, TAvlNode: AvlNode, TMemRegion: MemRegion].} # shared: var - bottomData: TAvlNode + bottomData: AvlNode bottom: PAvlNode {.push stack_trace: off.} @@ -191,44 +195,44 @@ proc initAllocator() = bottom.link[1] = bottom {.pop.} -proc incCurrMem(a: var TMemRegion, bytes: int) {.inline.} = +proc incCurrMem(a: var MemRegion, bytes: int) {.inline.} = inc(a.currMem, bytes) -proc decCurrMem(a: var TMemRegion, bytes: int) {.inline.} = +proc decCurrMem(a: var MemRegion, bytes: int) {.inline.} = a.maxMem = max(a.maxMem, a.currMem) dec(a.currMem, bytes) -proc getMaxMem(a: var TMemRegion): int = +proc getMaxMem(a: var MemRegion): int = # Since we update maxPagesCount only when freeing pages, # maxPagesCount may not be up to date. Thus we use the # maximum of these both values here: result = max(a.currMem, a.maxMem) -proc llAlloc(a: var TMemRegion, size: int): pointer = +proc llAlloc(a: var MemRegion, size: int): pointer = # *low-level* alloc for the memory managers data structures. Deallocation # is done at he end of the allocator's life time. if a.llmem == nil or size > a.llmem.size: - # the requested size is ``roundup(size+sizeof(TLLChunk), PageSize)``, but + # the requested size is ``roundup(size+sizeof(LLChunk), PageSize)``, but # since we know ``size`` is a (small) constant, we know the requested size # is one page: - sysAssert roundup(size+sizeof(TLLChunk), PageSize) == PageSize, "roundup 6" + sysAssert roundup(size+sizeof(LLChunk), PageSize) == PageSize, "roundup 6" var old = a.llmem # can be nil and is correct with nil a.llmem = cast[PLLChunk](osAllocPages(PageSize)) incCurrMem(a, PageSize) - a.llmem.size = PageSize - sizeof(TLLChunk) - a.llmem.acc = sizeof(TLLChunk) + a.llmem.size = PageSize - sizeof(LLChunk) + a.llmem.acc = sizeof(LLChunk) a.llmem.next = old result = cast[pointer](cast[ByteAddress](a.llmem) + a.llmem.acc) dec(a.llmem.size, size) inc(a.llmem.acc, size) zeroMem(result, size) -proc allocAvlNode(a: var TMemRegion, key, upperBound: int): PAvlNode = +proc allocAvlNode(a: var MemRegion, key, upperBound: int): PAvlNode = if a.freeAvlNodes != nil: result = a.freeAvlNodes a.freeAvlNodes = a.freeAvlNodes.link[0] else: - result = cast[PAvlNode](llAlloc(a, sizeof(TAvlNode))) + result = cast[PAvlNode](llAlloc(a, sizeof(AvlNode))) result.key = key result.upperBound = upperBound result.link[0] = bottom @@ -238,13 +242,13 @@ proc allocAvlNode(a: var TMemRegion, key, upperBound: int): PAvlNode = sysAssert(bottom.link[0] == bottom, "bottom link[0]") sysAssert(bottom.link[1] == bottom, "bottom link[1]") -proc deallocAvlNode(a: var TMemRegion, n: PAvlNode) {.inline.} = +proc deallocAvlNode(a: var MemRegion, n: PAvlNode) {.inline.} = n.link[0] = a.freeAvlNodes a.freeAvlNodes = n include "system/avltree" -proc llDeallocAll(a: var TMemRegion) = +proc llDeallocAll(a: var MemRegion) = var it = a.llmem while it != nil: # we know each block in the list has the size of 1 page: @@ -252,14 +256,14 @@ proc llDeallocAll(a: var TMemRegion) = osDeallocPages(it, PageSize) it = next -proc intSetGet(t: TIntSet, key: int): PTrunk = +proc intSetGet(t: IntSet, key: int): PTrunk = var it = t.data[key and high(t.data)] while it != nil: if it.key == key: return it it = it.next result = nil -proc intSetPut(a: var TMemRegion, t: var TIntSet, key: int): PTrunk = +proc intSetPut(a: var MemRegion, t: var IntSet, key: int): PTrunk = result = intSetGet(t, key) if result == nil: result = cast[PTrunk](llAlloc(a, sizeof(result[]))) @@ -267,7 +271,7 @@ proc intSetPut(a: var TMemRegion, t: var TIntSet, key: int): PTrunk = t.data[key and high(t.data)] = result result.key = key -proc contains(s: TIntSet, key: int): bool = +proc contains(s: IntSet, key: int): bool = var t = intSetGet(s, key shr TrunkShift) if t != nil: var u = key and TrunkMask @@ -275,19 +279,19 @@ proc contains(s: TIntSet, key: int): bool = else: result = false -proc incl(a: var TMemRegion, s: var TIntSet, key: int) = +proc incl(a: var MemRegion, s: var IntSet, key: int) = var t = intSetPut(a, s, key shr TrunkShift) var u = key and TrunkMask t.bits[u shr IntShift] = t.bits[u shr IntShift] or (1 shl (u and IntMask)) -proc excl(s: var TIntSet, key: int) = +proc excl(s: var IntSet, key: int) = var t = intSetGet(s, key shr TrunkShift) if t != nil: var u = key and TrunkMask t.bits[u shr IntShift] = t.bits[u shr IntShift] and not (1 shl (u and IntMask)) -iterator elements(t: TIntSet): int {.inline.} = +iterator elements(t: IntSet): int {.inline.} = # while traversing it is forbidden to change the set! for h in 0..high(t.data): var r = t.data[h] @@ -311,7 +315,7 @@ proc isSmallChunk(c: PChunk): bool {.inline.} = proc chunkUnused(c: PChunk): bool {.inline.} = result = not c.used -iterator allObjects(m: TMemRegion): pointer {.inline.} = +iterator allObjects(m: MemRegion): pointer {.inline.} = for s in elements(m.chunkStarts): # we need to check here again as it could have been modified: if s in m.chunkStarts: @@ -331,7 +335,7 @@ iterator allObjects(m: TMemRegion): pointer {.inline.} = yield addr(c.data) proc isCell(p: pointer): bool {.inline.} = - result = cast[ptr TFreeCell](p).zeroField >% 1 + result = cast[ptr FreeCell](p).zeroField >% 1 # ------------- chunk management ---------------------------------------------- proc pageIndex(c: PChunk): int {.inline.} = @@ -344,7 +348,7 @@ proc pageAddr(p: pointer): PChunk {.inline.} = result = cast[PChunk](cast[ByteAddress](p) and not PageMask) #sysAssert(Contains(allocator.chunkStarts, pageIndex(result))) -proc requestOsChunks(a: var TMemRegion, size: int): PBigChunk = +proc requestOsChunks(a: var MemRegion, size: int): PBigChunk = incCurrMem(a, size) inc(a.freeMem, size) result = cast[PBigChunk](osAllocPages(size)) @@ -373,7 +377,7 @@ proc requestOsChunks(a: var TMemRegion, size: int): PBigChunk = result.prevSize = 0 # unknown a.lastSize = size # for next request -proc freeOsChunks(a: var TMemRegion, p: pointer, size: int) = +proc freeOsChunks(a: var MemRegion, p: pointer, size: int) = # update next.prevSize: var c = cast[PChunk](p) var nxt = cast[ByteAddress](p) +% c.size @@ -387,7 +391,7 @@ proc freeOsChunks(a: var TMemRegion, p: pointer, size: int) = dec(a.freeMem, size) #c_fprintf(c_stdout, "[Alloc] back to OS: %ld\n", size) -proc isAccessible(a: TMemRegion, p: pointer): bool {.inline.} = +proc isAccessible(a: MemRegion, p: pointer): bool {.inline.} = result = contains(a.chunkStarts, pageIndex(p)) proc contains[T](list, x: T): bool = @@ -396,7 +400,7 @@ proc contains[T](list, x: T): bool = if it == x: return true it = it.next -proc writeFreeList(a: TMemRegion) = +proc writeFreeList(a: MemRegion) = var it = a.freeChunksList c_fprintf(c_stdout, "freeChunksList: %p\n", it) while it != nil: @@ -427,14 +431,14 @@ proc listRemove[T](head: var T, c: T) {.inline.} = c.next = nil c.prev = nil -proc updatePrevSize(a: var TMemRegion, c: PBigChunk, +proc updatePrevSize(a: var MemRegion, c: PBigChunk, prevSize: int) {.inline.} = var ri = cast[PChunk](cast[ByteAddress](c) +% c.size) sysAssert((cast[ByteAddress](ri) and PageMask) == 0, "updatePrevSize") if isAccessible(a, ri): ri.prevSize = prevSize -proc freeBigChunk(a: var TMemRegion, c: PBigChunk) = +proc freeBigChunk(a: var MemRegion, c: PBigChunk) = var c = c sysAssert(c.size >= PageSize, "freeBigChunk") inc(a.freeMem, c.size) @@ -467,7 +471,7 @@ proc freeBigChunk(a: var TMemRegion, c: PBigChunk) = else: freeOsChunks(a, c, c.size) -proc splitChunk(a: var TMemRegion, c: PBigChunk, size: int) = +proc splitChunk(a: var MemRegion, c: PBigChunk, size: int) = var rest = cast[PBigChunk](cast[ByteAddress](c) +% size) sysAssert(rest notin a.freeChunksList, "splitChunk") rest.size = c.size - size @@ -480,7 +484,7 @@ proc splitChunk(a: var TMemRegion, c: PBigChunk, size: int) = incl(a, a.chunkStarts, pageIndex(rest)) listAdd(a.freeChunksList, rest) -proc getBigChunk(a: var TMemRegion, size: int): PBigChunk = +proc getBigChunk(a: var MemRegion, size: int): PBigChunk = # use first fit for now: sysAssert((size and PageMask) == 0, "getBigChunk 1") sysAssert(size > 0, "getBigChunk 2") @@ -507,16 +511,16 @@ proc getBigChunk(a: var TMemRegion, size: int): PBigChunk = incl(a, a.chunkStarts, pageIndex(result)) dec(a.freeMem, size) -proc getSmallChunk(a: var TMemRegion): PSmallChunk = +proc getSmallChunk(a: var MemRegion): PSmallChunk = var res = getBigChunk(a, PageSize) sysAssert res.prev == nil, "getSmallChunk 1" sysAssert res.next == nil, "getSmallChunk 2" result = cast[PSmallChunk](res) # ----------------------------------------------------------------------------- -proc isAllocatedPtr(a: TMemRegion, p: pointer): bool {.benign.} +proc isAllocatedPtr(a: MemRegion, p: pointer): bool {.benign.} -proc allocInv(a: TMemRegion): bool = +proc allocInv(a: MemRegion): bool = ## checks some (not all yet) invariants of the allocator's data structures. for s in low(a.freeSmallChunks)..high(a.freeSmallChunks): var c = a.freeSmallChunks[s] @@ -537,10 +541,10 @@ proc allocInv(a: TMemRegion): bool = c = c.next result = true -proc rawAlloc(a: var TMemRegion, requestedSize: int): pointer = +proc rawAlloc(a: var MemRegion, requestedSize: int): pointer = sysAssert(allocInv(a), "rawAlloc: begin") sysAssert(roundup(65, 8) == 72, "rawAlloc: roundup broken") - sysAssert(requestedSize >= sizeof(TFreeCell), "rawAlloc: requested size too small") + sysAssert(requestedSize >= sizeof(FreeCell), "rawAlloc: requested size too small") var size = roundup(requestedSize, MemAlign) sysAssert(size >= requestedSize, "insufficient allocated size!") #c_fprintf(c_stdout, "alloc; size: %ld; %ld\n", requestedSize, size) @@ -601,11 +605,11 @@ proc rawAlloc(a: var TMemRegion, requestedSize: int): pointer = sysAssert(allocInv(a), "rawAlloc: end") when logAlloc: cprintf("rawAlloc: %ld %p\n", requestedSize, result) -proc rawAlloc0(a: var TMemRegion, requestedSize: int): pointer = +proc rawAlloc0(a: var MemRegion, requestedSize: int): pointer = result = rawAlloc(a, requestedSize) zeroMem(result, requestedSize) -proc rawDealloc(a: var TMemRegion, p: pointer) = +proc rawDealloc(a: var MemRegion, p: pointer) = #sysAssert(isAllocatedPtr(a, p), "rawDealloc: no allocated pointer") sysAssert(allocInv(a), "rawDealloc: begin") var c = pageAddr(p) @@ -615,7 +619,7 @@ proc rawDealloc(a: var TMemRegion, p: pointer) = var s = c.size sysAssert(((cast[ByteAddress](p) and PageMask) - smallChunkOverhead()) %% s == 0, "rawDealloc 3") - var f = cast[ptr TFreeCell](p) + var f = cast[ptr FreeCell](p) #echo("setting to nil: ", $cast[TAddress](addr(f.zeroField))) sysAssert(f.zeroField != 0, "rawDealloc 1") f.zeroField = 0 @@ -623,8 +627,8 @@ proc rawDealloc(a: var TMemRegion, p: pointer) = c.freeList = f when overwriteFree: # set to 0xff to check for usage after free bugs: - c_memset(cast[pointer](cast[int](p) +% sizeof(TFreeCell)), -1'i32, - s -% sizeof(TFreeCell)) + c_memset(cast[pointer](cast[int](p) +% sizeof(FreeCell)), -1'i32, + s -% sizeof(FreeCell)) # check if it is not in the freeSmallChunks[s] list: if c.free < s: # add it to the freeSmallChunks[s] array: @@ -649,7 +653,7 @@ proc rawDealloc(a: var TMemRegion, p: pointer) = sysAssert(allocInv(a), "rawDealloc: end") when logAlloc: cprintf("rawDealloc: %p\n", p) -proc isAllocatedPtr(a: TMemRegion, p: pointer): bool = +proc isAllocatedPtr(a: MemRegion, p: pointer): bool = if isAccessible(a, p): var c = pageAddr(p) if not chunkUnused(c): @@ -658,16 +662,16 @@ proc isAllocatedPtr(a: TMemRegion, p: pointer): bool = var offset = (cast[ByteAddress](p) and (PageSize-1)) -% smallChunkOverhead() result = (c.acc >% offset) and (offset %% c.size == 0) and - (cast[ptr TFreeCell](p).zeroField >% 1) + (cast[ptr FreeCell](p).zeroField >% 1) else: var c = cast[PBigChunk](c) - result = p == addr(c.data) and cast[ptr TFreeCell](p).zeroField >% 1 + result = p == addr(c.data) and cast[ptr FreeCell](p).zeroField >% 1 -proc prepareForInteriorPointerChecking(a: var TMemRegion) {.inline.} = +proc prepareForInteriorPointerChecking(a: var MemRegion) {.inline.} = a.minLargeObj = lowGauge(a.root) a.maxLargeObj = highGauge(a.root) -proc interiorAllocatedPtr(a: TMemRegion, p: pointer): pointer = +proc interiorAllocatedPtr(a: MemRegion, p: pointer): pointer = if isAccessible(a, p): var c = pageAddr(p) if not chunkUnused(c): @@ -678,7 +682,7 @@ proc interiorAllocatedPtr(a: TMemRegion, p: pointer): pointer = if c.acc >% offset: sysAssert(cast[ByteAddress](addr(c.data)) +% offset == cast[ByteAddress](p), "offset is not what you think it is") - var d = cast[ptr TFreeCell](cast[ByteAddress](addr(c.data)) +% + var d = cast[ptr FreeCell](cast[ByteAddress](addr(c.data)) +% offset -% (offset %% c.size)) if d.zeroField >% 1: result = d @@ -686,7 +690,7 @@ proc interiorAllocatedPtr(a: TMemRegion, p: pointer): pointer = else: var c = cast[PBigChunk](c) var d = addr(c.data) - if p >= d and cast[ptr TFreeCell](d).zeroField >% 1: + if p >= d and cast[ptr FreeCell](d).zeroField >% 1: result = d sysAssert isAllocatedPtr(a, result), " result wrong pointer!" else: @@ -699,38 +703,38 @@ proc interiorAllocatedPtr(a: TMemRegion, p: pointer): pointer = var k = cast[pointer](avlNode.key) var c = cast[PBigChunk](pageAddr(k)) sysAssert(addr(c.data) == k, " k is not the same as addr(c.data)!") - if cast[ptr TFreeCell](k).zeroField >% 1: + if cast[ptr FreeCell](k).zeroField >% 1: result = k sysAssert isAllocatedPtr(a, result), " result wrong pointer!" proc ptrSize(p: pointer): int = - var x = cast[pointer](cast[ByteAddress](p) -% sizeof(TFreeCell)) + var x = cast[pointer](cast[ByteAddress](p) -% sizeof(FreeCell)) var c = pageAddr(p) sysAssert(not chunkUnused(c), "ptrSize") - result = c.size -% sizeof(TFreeCell) + result = c.size -% sizeof(FreeCell) if not isSmallChunk(c): dec result, bigChunkOverhead() -proc alloc(allocator: var TMemRegion, size: Natural): pointer = - result = rawAlloc(allocator, size+sizeof(TFreeCell)) - cast[ptr TFreeCell](result).zeroField = 1 # mark it as used +proc alloc(allocator: var MemRegion, size: Natural): pointer = + result = rawAlloc(allocator, size+sizeof(FreeCell)) + cast[ptr FreeCell](result).zeroField = 1 # mark it as used sysAssert(not isAllocatedPtr(allocator, result), "alloc") - result = cast[pointer](cast[ByteAddress](result) +% sizeof(TFreeCell)) + result = cast[pointer](cast[ByteAddress](result) +% sizeof(FreeCell)) -proc alloc0(allocator: var TMemRegion, size: Natural): pointer = +proc alloc0(allocator: var MemRegion, size: Natural): pointer = result = alloc(allocator, size) zeroMem(result, size) -proc dealloc(allocator: var TMemRegion, p: pointer) = +proc dealloc(allocator: var MemRegion, p: pointer) = sysAssert(p != nil, "dealloc 0") - var x = cast[pointer](cast[ByteAddress](p) -% sizeof(TFreeCell)) + var x = cast[pointer](cast[ByteAddress](p) -% sizeof(FreeCell)) sysAssert(x != nil, "dealloc 1") sysAssert(isAccessible(allocator, x), "is not accessible") - sysAssert(cast[ptr TFreeCell](x).zeroField == 1, "dealloc 2") + sysAssert(cast[ptr FreeCell](x).zeroField == 1, "dealloc 2") rawDealloc(allocator, x) sysAssert(not isAllocatedPtr(allocator, x), "dealloc 3") -proc realloc(allocator: var TMemRegion, p: pointer, newsize: Natural): pointer = +proc realloc(allocator: var MemRegion, p: pointer, newsize: Natural): pointer = if newsize > 0: result = alloc0(allocator, newsize) if p != nil: @@ -739,7 +743,7 @@ proc realloc(allocator: var TMemRegion, p: pointer, newsize: Natural): pointer = elif p != nil: dealloc(allocator, p) -proc deallocOsPages(a: var TMemRegion) = +proc deallocOsPages(a: var MemRegion) = # we free every 'ordinarily' allocated page by iterating over the page bits: for p in elements(a.chunkStarts): var page = cast[PChunk](p shl PageShift) @@ -756,9 +760,9 @@ proc deallocOsPages(a: var TMemRegion) = # And then we free the pages that are in use for the page bits: llDeallocAll(a) -proc getFreeMem(a: TMemRegion): int {.inline.} = result = a.freeMem -proc getTotalMem(a: TMemRegion): int {.inline.} = result = a.currMem -proc getOccupiedMem(a: TMemRegion): int {.inline.} = +proc getFreeMem(a: MemRegion): int {.inline.} = result = a.freeMem +proc getTotalMem(a: MemRegion): int {.inline.} = result = a.currMem +proc getOccupiedMem(a: MemRegion): int {.inline.} = result = a.currMem - a.freeMem # ---------------------- thread memory region ------------------------------- @@ -769,7 +773,7 @@ template instantiateForRegion(allocator: expr) = result = interiorAllocatedPtr(allocator, p) proc isAllocatedPtr*(p: pointer): bool = - let p = cast[pointer](cast[ByteAddress](p)-%ByteAddress(sizeof(TCell))) + let p = cast[pointer](cast[ByteAddress](p)-%ByteAddress(sizeof(Cell))) result = isAllocatedPtr(allocator, p) proc deallocOsPages = deallocOsPages(allocator) @@ -803,8 +807,8 @@ template instantiateForRegion(allocator: expr) = # -------------------- shared heap region ---------------------------------- when hasThreadSupport: - var sharedHeap: TMemRegion - var heapLock: TSysLock + var sharedHeap: MemRegion + var heapLock: SysLock initSysLock(heapLock) proc allocShared(size: Natural): pointer = diff --git a/lib/system/atomics.nim b/lib/system/atomics.nim index c97d2fc7f..0b16b63bf 100644 --- a/lib/system/atomics.nim +++ b/lib/system/atomics.nim @@ -37,39 +37,40 @@ when someGcc and hasThreadSupport: ## and release stores in all threads. type - TAtomType* = SomeNumber|pointer|ptr|char|bool + AtomType* = SomeNumber|pointer|ptr|char|bool ## Type Class representing valid types for use with atomic procs + {.deprecated: [TAtomType: AtomType].} - proc atomicLoadN*[T: TAtomType](p: ptr T, mem: AtomMemModel): T {. + proc atomicLoadN*[T: AtomType](p: ptr T, mem: AtomMemModel): T {. importc: "__atomic_load_n", nodecl.} ## This proc implements an atomic load operation. It returns the contents at p. ## ATOMIC_RELAXED, ATOMIC_SEQ_CST, ATOMIC_ACQUIRE, ATOMIC_CONSUME. - proc atomicLoad*[T: TAtomType](p, ret: ptr T, mem: AtomMemModel) {. + proc atomicLoad*[T: AtomType](p, ret: ptr T, mem: AtomMemModel) {. importc: "__atomic_load", nodecl.} ## This is the generic version of an atomic load. It returns the contents at p in ret. - proc atomicStoreN*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel) {. + proc atomicStoreN*[T: AtomType](p: ptr T, val: T, mem: AtomMemModel) {. importc: "__atomic_store_n", nodecl.} ## This proc implements an atomic store operation. It writes val at p. ## ATOMIC_RELAXED, ATOMIC_SEQ_CST, and ATOMIC_RELEASE. - proc atomicStore*[T: TAtomType](p, val: ptr T, mem: AtomMemModel) {. + proc atomicStore*[T: AtomType](p, val: ptr T, mem: AtomMemModel) {. importc: "__atomic_store", nodecl.} ## This is the generic version of an atomic store. It stores the value of val at p - proc atomicExchangeN*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {. + proc atomicExchangeN*[T: AtomType](p: ptr T, val: T, mem: AtomMemModel): T {. importc: "__atomic_exchange_n", nodecl.} ## This proc implements an atomic exchange operation. It writes val at p, ## and returns the previous contents at p. ## ATOMIC_RELAXED, ATOMIC_SEQ_CST, ATOMIC_ACQUIRE, ATOMIC_RELEASE, ATOMIC_ACQ_REL - proc atomicExchange*[T: TAtomType](p, val, ret: ptr T, mem: AtomMemModel) {. + proc atomicExchange*[T: AtomType](p, val, ret: ptr T, mem: AtomMemModel) {. importc: "__atomic_exchange", nodecl.} ## This is the generic version of an atomic exchange. It stores the contents at val at p. ## The original value at p is copied into ret. - proc atomicCompareExchangeN*[T: TAtomType](p, expected: ptr T, desired: T, + proc atomicCompareExchangeN*[T: AtomType](p, expected: ptr T, desired: T, weak: bool, success_memmodel: AtomMemModel, failure_memmodel: AtomMemModel): bool {. importc: "__atomic_compare_exchange_n ", nodecl.} ## This proc implements an atomic compare and exchange operation. This compares the @@ -85,7 +86,7 @@ when someGcc and hasThreadSupport: ## cannot be __ATOMIC_RELEASE nor __ATOMIC_ACQ_REL. It also cannot be a stronger model ## than that specified by success_memmodel. - proc atomicCompareExchange*[T: TAtomType](p, expected, desired: ptr T, + proc atomicCompareExchange*[T: AtomType](p, expected, desired: ptr T, weak: bool, success_memmodel: AtomMemModel, failure_memmodel: AtomMemModel): bool {. importc: "__atomic_compare_exchange", nodecl.} ## This proc implements the generic version of atomic_compare_exchange. @@ -93,31 +94,31 @@ when someGcc and hasThreadSupport: ## value is also a pointer. ## Perform the operation return the new value, all memory models are valid - proc atomicAddFetch*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {. + proc atomicAddFetch*[T: AtomType](p: ptr T, val: T, mem: AtomMemModel): T {. importc: "__atomic_add_fetch", nodecl.} - proc atomicSubFetch*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {. + proc atomicSubFetch*[T: AtomType](p: ptr T, val: T, mem: AtomMemModel): T {. importc: "__atomic_sub_fetch", nodecl.} - proc atomicOrFetch*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {. + proc atomicOrFetch*[T: AtomType](p: ptr T, val: T, mem: AtomMemModel): T {. importc: "__atomic_or_fetch ", nodecl.} - proc atomicAndFetch*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {. + proc atomicAndFetch*[T: AtomType](p: ptr T, val: T, mem: AtomMemModel): T {. importc: "__atomic_and_fetch", nodecl.} - proc atomicXorFetch*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {. + proc atomicXorFetch*[T: AtomType](p: ptr T, val: T, mem: AtomMemModel): T {. importc: "__atomic_xor_fetch", nodecl.} - proc atomicNandFetch*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {. + proc atomicNandFetch*[T: AtomType](p: ptr T, val: T, mem: AtomMemModel): T {. importc: "__atomic_nand_fetch ", nodecl.} ## Perform the operation return the old value, all memory models are valid - proc atomicFetchAdd*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {. + proc atomicFetchAdd*[T: AtomType](p: ptr T, val: T, mem: AtomMemModel): T {. importc: "__atomic_fetch_add", nodecl.} - proc atomicFetchSub*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {. + proc atomicFetchSub*[T: AtomType](p: ptr T, val: T, mem: AtomMemModel): T {. importc: "__atomic_fetch_sub", nodecl.} - proc atomicFetchOr*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {. + proc atomicFetchOr*[T: AtomType](p: ptr T, val: T, mem: AtomMemModel): T {. importc: "__atomic_fetch_or", nodecl.} - proc atomicFetchAnd*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {. + proc atomicFetchAnd*[T: AtomType](p: ptr T, val: T, mem: AtomMemModel): T {. importc: "__atomic_fetch_and", nodecl.} - proc atomicFetchXor*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {. + proc atomicFetchXor*[T: AtomType](p: ptr T, val: T, mem: AtomMemModel): T {. importc: "__atomic_fetch_xor", nodecl.} - proc atomicFetchNand*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {. + proc atomicFetchNand*[T: AtomType](p: ptr T, val: T, mem: AtomMemModel): T {. importc: "__atomic_fetch_nand", nodecl.} proc atomicTestAndSet*(p: pointer, mem: AtomMemModel): bool {. diff --git a/lib/system/avltree.nim b/lib/system/avltree.nim index 292097062..5ee37d3eb 100644 --- a/lib/system/avltree.nim +++ b/lib/system/avltree.nim @@ -51,7 +51,7 @@ proc split(t: var PAvlNode) = t.link[0] = temp inc t.level -proc add(a: var TMemRegion, t: var PAvlNode, key, upperBound: int) {.benign.} = +proc add(a: var MemRegion, t: var PAvlNode, key, upperBound: int) {.benign.} = if t == bottom: t = allocAvlNode(a, key, upperBound) else: @@ -64,7 +64,7 @@ proc add(a: var TMemRegion, t: var PAvlNode, key, upperBound: int) {.benign.} = skew(t) split(t) -proc del(a: var TMemRegion, t: var PAvlNode, x: int) {.benign.} = +proc del(a: var MemRegion, t: var PAvlNode, x: int) {.benign.} = if t == bottom: return a.last = t if x <% t.key: diff --git a/lib/system/cellsets.nim b/lib/system/cellsets.nim index 0e3a01eba..93c49483b 100644 --- a/lib/system/cellsets.nim +++ b/lib/system/cellsets.nim @@ -10,10 +10,10 @@ # Efficient set of pointers for the GC (and repr) type - TRefCount = int + RefCount = int - TCell {.pure.} = object - refcount: TRefCount # the refcount and some flags + Cell {.pure.} = object + refcount: RefCount # the refcount and some flags typ: PNimType when trackAllocationSource: filename: cstring @@ -21,34 +21,35 @@ type when useCellIds: id: int - PCell = ptr TCell + PCell = ptr Cell - PPageDesc = ptr TPageDesc - TBitIndex = range[0..UnitsPerPage-1] - TPageDesc {.final, pure.} = object + PPageDesc = ptr PageDesc + BitIndex = range[0..UnitsPerPage-1] + PageDesc {.final, pure.} = object next: PPageDesc # all nodes are connected with this pointer key: ByteAddress # start address at bit 0 - bits: array[TBitIndex, int] # a bit vector + bits: array[BitIndex, int] # a bit vector PPageDescArray = ptr array[0..1000_000, PPageDesc] - TCellSet {.final, pure.} = object + CellSet {.final, pure.} = object counter, max: int head: PPageDesc data: PPageDescArray PCellArray = ptr array[0..100_000_000, PCell] - TCellSeq {.final, pure.} = object + CellSeq {.final, pure.} = object len, cap: int d: PCellArray - +{.deprecated: [TCell: Cell, TBitIndex: BitIndex, TPageDesc: PageDesc, + TRefCount: RefCount, TCellSet: CellSet, TCellSeq: CellSeq].} # ------------------- cell seq handling --------------------------------------- -proc contains(s: TCellSeq, c: PCell): bool {.inline.} = +proc contains(s: CellSeq, c: PCell): bool {.inline.} = for i in 0 .. s.len-1: if s.d[i] == c: return true return false -proc add(s: var TCellSeq, c: PCell) {.inline.} = +proc add(s: var CellSeq, c: PCell) {.inline.} = if s.len >= s.cap: s.cap = s.cap * 3 div 2 var d = cast[PCellArray](alloc(s.cap * sizeof(PCell))) @@ -59,12 +60,12 @@ proc add(s: var TCellSeq, c: PCell) {.inline.} = s.d[s.len] = c inc(s.len) -proc init(s: var TCellSeq, cap: int = 1024) = +proc init(s: var CellSeq, cap: int = 1024) = s.len = 0 s.cap = cap s.d = cast[PCellArray](alloc0(cap * sizeof(PCell))) -proc deinit(s: var TCellSeq) = +proc deinit(s: var CellSeq) = dealloc(s.d) s.d = nil s.len = 0 @@ -75,13 +76,13 @@ proc deinit(s: var TCellSeq) = const InitCellSetSize = 1024 # must be a power of two! -proc init(s: var TCellSet) = +proc init(s: var CellSet) = s.data = cast[PPageDescArray](alloc0(InitCellSetSize * sizeof(PPageDesc))) s.max = InitCellSetSize-1 s.counter = 0 s.head = nil -proc deinit(s: var TCellSet) = +proc deinit(s: var CellSet) = var it = s.head while it != nil: var n = it.next @@ -98,14 +99,14 @@ proc nextTry(h, maxHash: int): int {.inline.} = # generates each int in range(maxHash) exactly once (see any text on # random-number generation for proof). -proc cellSetGet(t: TCellSet, key: ByteAddress): PPageDesc = +proc cellSetGet(t: CellSet, key: ByteAddress): PPageDesc = var h = cast[int](key) and t.max while t.data[h] != nil: if t.data[h].key == key: return t.data[h] h = nextTry(h, t.max) return nil -proc cellSetRawInsert(t: TCellSet, data: PPageDescArray, desc: PPageDesc) = +proc cellSetRawInsert(t: CellSet, data: PPageDescArray, desc: PPageDesc) = var h = cast[int](desc.key) and t.max while data[h] != nil: sysAssert(data[h] != desc, "CellSetRawInsert 1") @@ -113,7 +114,7 @@ proc cellSetRawInsert(t: TCellSet, data: PPageDescArray, desc: PPageDesc) = sysAssert(data[h] == nil, "CellSetRawInsert 2") data[h] = desc -proc cellSetEnlarge(t: var TCellSet) = +proc cellSetEnlarge(t: var CellSet) = var oldMax = t.max t.max = ((t.max+1)*2)-1 var n = cast[PPageDescArray](alloc0((t.max + 1) * sizeof(PPageDesc))) @@ -123,7 +124,7 @@ proc cellSetEnlarge(t: var TCellSet) = dealloc(t.data) t.data = n -proc cellSetPut(t: var TCellSet, key: ByteAddress): PPageDesc = +proc cellSetPut(t: var CellSet, key: ByteAddress): PPageDesc = var h = cast[int](key) and t.max while true: var x = t.data[h] @@ -138,7 +139,7 @@ proc cellSetPut(t: var TCellSet, key: ByteAddress): PPageDesc = while t.data[h] != nil: h = nextTry(h, t.max) sysAssert(t.data[h] == nil, "CellSetPut") # the new page descriptor goes into result - result = cast[PPageDesc](alloc0(sizeof(TPageDesc))) + result = cast[PPageDesc](alloc0(sizeof(PageDesc))) result.next = t.head result.key = key t.head = result @@ -146,7 +147,7 @@ proc cellSetPut(t: var TCellSet, key: ByteAddress): PPageDesc = # ---------- slightly higher level procs -------------------------------------- -proc contains(s: TCellSet, cell: PCell): bool = +proc contains(s: CellSet, cell: PCell): bool = var u = cast[ByteAddress](cell) var t = cellSetGet(s, u shr PageShift) if t != nil: @@ -155,13 +156,13 @@ proc contains(s: TCellSet, cell: PCell): bool = else: result = false -proc incl(s: var TCellSet, cell: PCell) {.noinline.} = +proc incl(s: var CellSet, cell: PCell) {.noinline.} = var u = cast[ByteAddress](cell) var t = cellSetPut(s, u shr PageShift) u = (u %% PageSize) /% MemAlign t.bits[u shr IntShift] = t.bits[u shr IntShift] or (1 shl (u and IntMask)) -proc excl(s: var TCellSet, cell: PCell) = +proc excl(s: var CellSet, cell: PCell) = var u = cast[ByteAddress](cell) var t = cellSetGet(s, u shr PageShift) if t != nil: @@ -169,7 +170,7 @@ proc excl(s: var TCellSet, cell: PCell) = t.bits[u shr IntShift] = (t.bits[u shr IntShift] and not (1 shl (u and IntMask))) -proc containsOrIncl(s: var TCellSet, cell: PCell): bool = +proc containsOrIncl(s: var CellSet, cell: PCell): bool = var u = cast[ByteAddress](cell) var t = cellSetGet(s, u shr PageShift) if t != nil: @@ -182,7 +183,7 @@ proc containsOrIncl(s: var TCellSet, cell: PCell): bool = incl(s, cell) result = false -iterator elements(t: TCellSet): PCell {.inline.} = +iterator elements(t: CellSet): PCell {.inline.} = # while traversing it is forbidden to add pointers to the tree! var r = t.head while r != nil: @@ -200,7 +201,7 @@ iterator elements(t: TCellSet): PCell {.inline.} = inc(i) r = r.next -iterator elementsExcept(t, s: TCellSet): PCell {.inline.} = +iterator elementsExcept(t, s: CellSet): PCell {.inline.} = var r = t.head while r != nil: let ss = cellSetGet(s, r.key) diff --git a/lib/system/cgprocs.nim b/lib/system/cgprocs.nim index f3acc81f2..6cd2ef08c 100644 --- a/lib/system/cgprocs.nim +++ b/lib/system/cgprocs.nim @@ -12,12 +12,13 @@ proc addChar(s: NimString, c: char): NimString {.compilerProc, benign.} type - TLibHandle = pointer # private type - TProcAddr = pointer # library loading and loading of procs: + LibHandle = pointer # private type + ProcAddr = pointer # library loading and loading of procs: +{.deprecated: [TLibHandle: LibHandle, TProcAddr: ProcAddr].} -proc nimLoadLibrary(path: string): TLibHandle {.compilerproc.} -proc nimUnloadLibrary(lib: TLibHandle) {.compilerproc.} -proc nimGetProcAddr(lib: TLibHandle, name: cstring): TProcAddr {.compilerproc.} +proc nimLoadLibrary(path: string): LibHandle {.compilerproc.} +proc nimUnloadLibrary(lib: LibHandle) {.compilerproc.} +proc nimGetProcAddr(lib: LibHandle, name: cstring): ProcAddr {.compilerproc.} proc nimLoadLibraryError(path: string) {.compilerproc, noinline.} diff --git a/lib/system/channels.nim b/lib/system/channels.nim index ebd30c353..6739fb83e 100644 --- a/lib/system/channels.nim +++ b/lib/system/channels.nim @@ -19,18 +19,20 @@ when not declared(NimString): type pbytes = ptr array[0.. 0xffff, byte] - TRawChannel {.pure, final.} = object ## msg queue for a thread + RawChannel {.pure, final.} = object ## msg queue for a thread rd, wr, count, mask: int data: pbytes - lock: TSysLock - cond: TSysCond + lock: SysLock + cond: SysCond elemType: PNimType ready: bool - region: TMemRegion - PRawChannel = ptr TRawChannel - TLoadStoreMode = enum mStore, mLoad - TChannel* {.gcsafe.}[TMsg] = TRawChannel ## a channel for thread communication - + region: MemRegion + PRawChannel = ptr RawChannel + LoadStoreMode = enum mStore, mLoad + Channel* {.gcsafe.}[TMsg] = RawChannel ## a channel for thread communication +{.deprecated: [TRawChannel: RawChannel, TLoadStoreMode: LoadStoreMode, + TChannel: Channel].} + const ChannelDeadMask = -2 proc initRawChannel(p: pointer) = @@ -49,9 +51,9 @@ proc deinitRawChannel(p: pointer) = deinitSysCond(c.cond) proc storeAux(dest, src: pointer, mt: PNimType, t: PRawChannel, - mode: TLoadStoreMode) {.benign.} + mode: LoadStoreMode) {.benign.} proc storeAux(dest, src: pointer, n: ptr TNimNode, t: PRawChannel, - mode: TLoadStoreMode) {.benign.} = + mode: LoadStoreMode) {.benign.} = var d = cast[ByteAddress](dest) s = cast[ByteAddress](src) @@ -68,7 +70,7 @@ proc storeAux(dest, src: pointer, n: ptr TNimNode, t: PRawChannel, of nkNone: sysAssert(false, "storeAux") proc storeAux(dest, src: pointer, mt: PNimType, t: PRawChannel, - mode: TLoadStoreMode) = + mode: LoadStoreMode) = var d = cast[ByteAddress](dest) s = cast[ByteAddress](src) @@ -202,7 +204,7 @@ template sendImpl(q: expr) {.immediate.} = releaseSys(q.lock) signalSysCond(q.cond) -proc send*[TMsg](c: var TChannel[TMsg], msg: TMsg) = +proc send*[TMsg](c: var Channel[TMsg], msg: TMsg) = ## sends a message to a thread. `msg` is deeply copied. var q = cast[PRawChannel](addr(c)) sendImpl(q) @@ -218,7 +220,7 @@ proc llRecv(q: PRawChannel, res: pointer, typ: PNimType) = sysFatal(ValueError, "cannot receive message of wrong type") rawRecv(q, res, typ) -proc recv*[TMsg](c: var TChannel[TMsg]): TMsg = +proc recv*[TMsg](c: var Channel[TMsg]): TMsg = ## receives a message from the channel `c`. This blocks until ## a message has arrived! You may use ``peek`` to avoid the blocking. var q = cast[PRawChannel](addr(c)) @@ -226,7 +228,7 @@ proc recv*[TMsg](c: var TChannel[TMsg]): TMsg = llRecv(q, addr(result), cast[PNimType](getTypeInfo(result))) releaseSys(q.lock) -proc tryRecv*[TMsg](c: var TChannel[TMsg]): tuple[dataAvailable: bool, +proc tryRecv*[TMsg](c: var Channel[TMsg]): tuple[dataAvailable: bool, msg: TMsg] = ## try to receives a message from the channel `c` if available. Otherwise ## it returns ``(false, default(msg))``. @@ -238,7 +240,7 @@ proc tryRecv*[TMsg](c: var TChannel[TMsg]): tuple[dataAvailable: bool, result.dataAvailable = true releaseSys(q.lock) -proc peek*[TMsg](c: var TChannel[TMsg]): int = +proc peek*[TMsg](c: var Channel[TMsg]): int = ## returns the current number of messages in the channel `c`. Returns -1 ## if the channel has been closed. **Note**: This is dangerous to use ## as it encourages races. It's much better to use ``tryRecv`` instead. @@ -249,15 +251,15 @@ proc peek*[TMsg](c: var TChannel[TMsg]): int = else: result = -1 -proc open*[TMsg](c: var TChannel[TMsg]) = +proc open*[TMsg](c: var Channel[TMsg]) = ## opens a channel `c` for inter thread communication. initRawChannel(addr(c)) -proc close*[TMsg](c: var TChannel[TMsg]) = +proc close*[TMsg](c: var Channel[TMsg]) = ## closes a channel `c` and frees its associated resources. deinitRawChannel(addr(c)) -proc ready*[TMsg](c: var TChannel[TMsg]): bool = +proc ready*[TMsg](c: var Channel[TMsg]): bool = ## returns true iff some thread is waiting on the channel `c` for ## new messages. var q = cast[PRawChannel](addr(c)) diff --git a/lib/system/debugger.nim b/lib/system/debugger.nim index 7b5169344..63ccd770b 100644 --- a/lib/system/debugger.nim +++ b/lib/system/debugger.nim @@ -10,22 +10,23 @@ ## This file implements basic features for any debugger. type - TVarSlot* {.compilerproc, final.} = object ## a slot in a frame + VarSlot* {.compilerproc, final.} = object ## a slot in a frame address*: pointer ## the variable's address typ*: PNimType ## the variable's type name*: cstring ## the variable's name; for globals this is "module.name" - PExtendedFrame = ptr TExtendedFrame - TExtendedFrame = object # If the debugger is enabled the compiler + PExtendedFrame = ptr ExtendedFrame + ExtendedFrame = object # If the debugger is enabled the compiler # provides an extended frame. Of course # only slots that are # needed are allocated and not 10_000, # except for the global data description. - f: TFrame - slots: array[0..10_000, TVarSlot] + f: Frame + slots: array[0..10_000, VarSlot] +{.deprecated: [TVarSlot: VarSlot, TExtendedFrame: ExtendedFrame].} var - dbgGlobalData: TExtendedFrame # this reserves much space, but + dbgGlobalData: ExtendedFrame # this reserves much space, but # for now it is the most practical way proc dbgRegisterGlobal(name: cstring, address: pointer, @@ -39,7 +40,7 @@ proc dbgRegisterGlobal(name: cstring, address: pointer, dbgGlobalData.slots[i].address = address inc(dbgGlobalData.f.len) -proc getLocal*(frame: PFrame; slot: int): TVarSlot {.inline.} = +proc getLocal*(frame: PFrame; slot: int): VarSlot {.inline.} = ## retrieves the meta data for the local variable at `slot`. CAUTION: An ## invalid `slot` value causes a corruption! result = cast[PExtendedFrame](frame).slots[slot] @@ -48,7 +49,7 @@ proc getGlobalLen*(): int {.inline.} = ## gets the number of registered globals. result = dbgGlobalData.f.len -proc getGlobal*(slot: int): TVarSlot {.inline.} = +proc getGlobal*(slot: int): VarSlot {.inline.} = ## retrieves the meta data for the global variable at `slot`. CAUTION: An ## invalid `slot` value causes a corruption! result = dbgGlobalData.slots[slot] @@ -56,13 +57,13 @@ proc getGlobal*(slot: int): TVarSlot {.inline.} = # ------------------- breakpoint support ------------------------------------ type - TBreakpoint* = object ## represents a break point + Breakpoint* = object ## represents a break point low*, high*: int ## range from low to high; if disabled ## both low and high are set to their negative values filename*: cstring ## the filename of the breakpoint var - dbgBP: array[0..127, TBreakpoint] # breakpoints + dbgBP: array[0..127, Breakpoint] # breakpoints dbgBPlen: int dbgBPbloom: int64 # we use a bloom filter to speed up breakpoint checking @@ -131,16 +132,16 @@ proc canonFilename*(filename: cstring): cstring = if fileMatches(result, filename): return result result = nil -iterator listBreakpoints*(): ptr TBreakpoint = +iterator listBreakpoints*(): ptr Breakpoint = ## lists all breakpoints. for i in 0..dbgBPlen-1: yield addr(dbgBP[i]) -proc isActive*(b: ptr TBreakpoint): bool = b.low > 0 -proc flip*(b: ptr TBreakpoint) = +proc isActive*(b: ptr Breakpoint): bool = b.low > 0 +proc flip*(b: ptr Breakpoint) = ## enables or disables 'b' depending on its current state. b.low = -b.low; b.high = -b.high -proc checkBreakpoints*(filename: cstring, line: int): ptr TBreakpoint = +proc checkBreakpoints*(filename: cstring, line: int): ptr Breakpoint = ## in which breakpoint (if any) we are. if (dbgBPbloom and line) != line: return nil for b in listBreakpoints(): @@ -149,29 +150,30 @@ proc checkBreakpoints*(filename: cstring, line: int): ptr TBreakpoint = # ------------------- watchpoint support ------------------------------------ type - THash = int - TWatchpoint {.pure, final.} = object + Hash = int + Watchpoint {.pure, final.} = object name: cstring address: pointer typ: PNimType - oldValue: THash + oldValue: Hash +{.deprecated: [THash: Hash, TWatchpoint: Watchpoint].} var - watchpoints: array [0..99, TWatchpoint] + watchpoints: array [0..99, Watchpoint] watchpointsLen: int -proc `!&`(h: THash, val: int): THash {.inline.} = +proc `!&`(h: Hash, val: int): Hash {.inline.} = result = h +% val result = result +% result shl 10 result = result xor (result shr 6) -proc `!$`(h: THash): THash {.inline.} = +proc `!$`(h: Hash): Hash {.inline.} = result = h +% h shl 3 result = result xor (result shr 11) result = result +% result shl 15 -proc hash(data: pointer, size: int): THash = - var h: THash = 0 +proc hash(data: pointer, size: int): Hash = + var h: Hash = 0 var p = cast[cstring](data) var i = 0 var s = size @@ -181,14 +183,14 @@ proc hash(data: pointer, size: int): THash = dec(s) result = !$h -proc hashGcHeader(data: pointer): THash = +proc hashGcHeader(data: pointer): Hash = const headerSize = sizeof(int)*2 result = hash(cast[pointer](cast[int](data) -% headerSize), headerSize) proc genericHashAux(dest: pointer, mt: PNimType, shallow: bool, - h: THash): THash + h: Hash): Hash proc genericHashAux(dest: pointer, n: ptr TNimNode, shallow: bool, - h: THash): THash = + h: Hash): Hash = var d = cast[ByteAddress](dest) case n.kind of nkSlot: @@ -204,7 +206,7 @@ proc genericHashAux(dest: pointer, n: ptr TNimNode, shallow: bool, of nkNone: sysAssert(false, "genericHashAux") proc genericHashAux(dest: pointer, mt: PNimType, shallow: bool, - h: THash): THash = + h: Hash): Hash = sysAssert(mt != nil, "genericHashAux 2") case mt.kind of tyString: diff --git a/lib/system/dyncalls.nim b/lib/system/dyncalls.nim index 44f7b67c3..8ef583482 100644 --- a/lib/system/dyncalls.nim +++ b/lib/system/dyncalls.nim @@ -15,7 +15,7 @@ {.push stack_trace: off.} const - NilLibHandle: TLibHandle = nil + NilLibHandle: LibHandle = nil proc rawWrite(f: File, s: string) = # we cannot throw an exception here! @@ -55,22 +55,22 @@ when defined(posix): var RTLD_NOW {.importc: "RTLD_NOW", header: "".}: int - proc dlclose(lib: TLibHandle) {.importc, header: "".} - proc dlopen(path: cstring, mode: int): TLibHandle {. + proc dlclose(lib: LibHandle) {.importc, header: "".} + proc dlopen(path: cstring, mode: int): LibHandle {. importc, header: "".} - proc dlsym(lib: TLibHandle, name: cstring): TProcAddr {. + proc dlsym(lib: LibHandle, name: cstring): ProcAddr {. importc, header: "".} proc dlerror(): cstring {.importc, header: "".} - proc nimUnloadLibrary(lib: TLibHandle) = + proc nimUnloadLibrary(lib: LibHandle) = dlclose(lib) - proc nimLoadLibrary(path: string): TLibHandle = + proc nimLoadLibrary(path: string): LibHandle = result = dlopen(path, RTLD_NOW) #c_fprintf(c_stdout, "%s\n", dlerror()) - proc nimGetProcAddr(lib: TLibHandle, name: cstring): TProcAddr = + proc nimGetProcAddr(lib: LibHandle, name: cstring): ProcAddr = result = dlsym(lib, name) if result == nil: procAddrError(name) @@ -84,12 +84,12 @@ elif defined(windows) or defined(dos): type THINSTANCE {.importc: "HINSTANCE".} = object x: pointer - proc getProcAddress(lib: THINSTANCE, name: cstring): TProcAddr {. + proc getProcAddress(lib: THINSTANCE, name: cstring): ProcAddr {. importcpp: "(void*)GetProcAddress(@)", header: "", stdcall.} else: type THINSTANCE {.importc: "HINSTANCE".} = pointer - proc getProcAddress(lib: THINSTANCE, name: cstring): TProcAddr {. + proc getProcAddress(lib: THINSTANCE, name: cstring): ProcAddr {. importc: "GetProcAddress", header: "", stdcall.} proc freeLibrary(lib: THINSTANCE) {. @@ -97,13 +97,13 @@ elif defined(windows) or defined(dos): proc winLoadLibrary(path: cstring): THINSTANCE {. importc: "LoadLibraryA", header: "", stdcall.} - proc nimUnloadLibrary(lib: TLibHandle) = + proc nimUnloadLibrary(lib: LibHandle) = freeLibrary(cast[THINSTANCE](lib)) - proc nimLoadLibrary(path: string): TLibHandle = - result = cast[TLibHandle](winLoadLibrary(path)) + proc nimLoadLibrary(path: string): LibHandle = + result = cast[LibHandle](winLoadLibrary(path)) - proc nimGetProcAddr(lib: TLibHandle, name: cstring): TProcAddr = + proc nimGetProcAddr(lib: LibHandle, name: cstring): ProcAddr = result = getProcAddress(cast[THINSTANCE](lib), name) if result == nil: procAddrError(name) @@ -115,13 +115,13 @@ elif defined(mac): # {.error: "no implementation for dyncalls yet".} - proc nimUnloadLibrary(lib: TLibHandle) = + proc nimUnloadLibrary(lib: LibHandle) = NSUnLinkModule(NSModule(lib), NSUNLINKMODULE_OPTION_RESET_LAZY_REFERENCES) var dyld_present {.importc: "_dyld_present", header: "".}: int - proc nimLoadLibrary(path: string): TLibHandle = + proc nimLoadLibrary(path: string): LibHandle = var img: NSObjectFileImage ret: NSObjectFileImageReturnCode @@ -134,13 +134,13 @@ elif defined(mac): modul = NSLinkModule(img, path, NSLINKMODULE_OPTION_PRIVATE or NSLINKMODULE_OPTION_RETURN_ON_ERROR) NSDestroyObjectFileImage(img) - result = TLibHandle(modul) + result = LibHandle(modul) - proc nimGetProcAddr(lib: TLibHandle, name: cstring): TProcAddr = + proc nimGetProcAddr(lib: LibHandle, name: cstring): ProcAddr = var nss: NSSymbol nss = NSLookupSymbolInModule(NSModule(lib), name) - result = TProcAddr(NSAddressOfSymbol(nss)) + result = ProcAddr(NSAddressOfSymbol(nss)) if result == nil: ProcAddrError(name) else: diff --git a/lib/system/endb.nim b/lib/system/endb.nim index 003698421..ef2664796 100644 --- a/lib/system/endb.nim +++ b/lib/system/endb.nim @@ -20,63 +20,65 @@ const EndbEnd = "***\n" type - TStaticStr = object + StaticStr = object len: int data: array[0..100, char] - TBreakpointFilename = object - b: ptr TBreakpoint - filename: TStaticStr + BreakpointFilename = object + b: ptr Breakpoint + filename: StaticStr - TDbgState = enum + DbgState = enum dbOff, # debugger is turned off dbStepInto, # debugger is in tracing mode dbStepOver, dbSkipCurrent, dbQuiting, # debugger wants to quit dbBreakpoints # debugger is only interested in breakpoints +{.deprecated: [TStaticStr: StaticStr, TBreakpointFilename: BreakpointFilename, + TDbgState: DbgState].} var - dbgUser: TStaticStr # buffer for user input; first command is ``step_into`` + dbgUser: StaticStr # buffer for user input; first command is ``step_into`` # needs to be global cause we store the last command # in it - dbgState: TDbgState # state of debugger + dbgState: DbgState # state of debugger dbgSkipToFrame: PFrame # frame to be skipped to maxDisplayRecDepth: int = 5 # do not display too much data! - brkPoints: array[0..127, TBreakpointFilename] + brkPoints: array[0..127, BreakpointFilename] -proc setLen(s: var TStaticStr, newLen=0) = +proc setLen(s: var StaticStr, newLen=0) = s.len = newLen s.data[newLen] = '\0' -proc add(s: var TStaticStr, c: char) = +proc add(s: var StaticStr, c: char) = if s.len < high(s.data)-1: s.data[s.len] = c s.data[s.len+1] = '\0' inc s.len -proc add(s: var TStaticStr, c: cstring) = +proc add(s: var StaticStr, c: cstring) = var i = 0 while c[i] != '\0': add s, c[i] inc i -proc assign(s: var TStaticStr, c: cstring) = +proc assign(s: var StaticStr, c: cstring) = setLen(s) add s, c -proc `==`(a, b: TStaticStr): bool = +proc `==`(a, b: StaticStr): bool = if a.len == b.len: for i in 0 .. a.len-1: if a.data[i] != b.data[i]: return false return true -proc `==`(a: TStaticStr, b: cstring): bool = +proc `==`(a: StaticStr, b: cstring): bool = result = c_strcmp(a.data, b) == 0 -proc write(f: TFile, s: TStaticStr) = +proc write(f: File, s: StaticStr) = write(f, cstring(s.data)) proc listBreakPoints() = @@ -95,14 +97,14 @@ proc listBreakPoints() = write(stdout, "\n") write(stdout, EndbEnd) -proc openAppend(filename: cstring): TFile = +proc openAppend(filename: cstring): File = var p: pointer = fopen(filename, "ab") if p != nil: - result = cast[TFile](p) + result = cast[File](p) write(result, "----------------------------------------\n") proc dbgRepr(p: pointer, typ: PNimType): string = - var cl: TReprClosure + var cl: ReprClosure initReprClosure(cl) cl.recDepth = maxDisplayRecDepth # locks for the GC turned out to be a bad idea... @@ -112,12 +114,12 @@ proc dbgRepr(p: pointer, typ: PNimType): string = # dec(recGcLock) deinitReprClosure(cl) -proc writeVariable(stream: TFile, slot: TVarSlot) = +proc writeVariable(stream: File, slot: VarSlot) = write(stream, slot.name) write(stream, " = ") writeln(stream, dbgRepr(slot.address, slot.typ)) -proc listFrame(stream: TFile, f: PFrame) = +proc listFrame(stream: File, f: PFrame) = write(stream, EndbBeg) write(stream, "| Frame (") write(stream, f.len) @@ -126,7 +128,7 @@ proc listFrame(stream: TFile, f: PFrame) = writeln(stream, getLocal(f, i).name) write(stream, EndbEnd) -proc listLocals(stream: TFile, f: PFrame) = +proc listLocals(stream: File, f: PFrame) = write(stream, EndbBeg) write(stream, "| Frame (") write(stream, f.len) @@ -135,7 +137,7 @@ proc listLocals(stream: TFile, f: PFrame) = writeVariable(stream, getLocal(f, i)) write(stream, EndbEnd) -proc listGlobals(stream: TFile) = +proc listGlobals(stream: File) = write(stream, EndbBeg) write(stream, "| Globals:\n") for i in 0 .. getGlobalLen()-1: @@ -172,7 +174,7 @@ proc dbgShowExecutionPoint() = write(stdout, framePtr.procname) write(stdout, " ***\n") -proc scanAndAppendWord(src: cstring, a: var TStaticStr, start: int): int = +proc scanAndAppendWord(src: cstring, a: var StaticStr, start: int): int = result = start # skip whitespace: while src[result] in {'\t', ' '}: inc(result) @@ -184,11 +186,11 @@ proc scanAndAppendWord(src: cstring, a: var TStaticStr, start: int): int = else: break inc(result) -proc scanWord(src: cstring, a: var TStaticStr, start: int): int = +proc scanWord(src: cstring, a: var StaticStr, start: int): int = setlen(a) result = scanAndAppendWord(src, a, start) -proc scanFilename(src: cstring, a: var TStaticStr, start: int): int = +proc scanFilename(src: cstring, a: var StaticStr, start: int): int = result = start setLen a while src[result] in {'\t', ' '}: inc(result) @@ -250,8 +252,8 @@ proc hasExt(s: cstring): bool = if s[i] == '.': return true inc i -proc parseBreakpoint(s: cstring, start: int): TBreakpoint = - var dbgTemp: TStaticStr +proc parseBreakpoint(s: cstring, start: int): Breakpoint = + var dbgTemp: StaticStr var i = scanNumber(s, result.low, start) if result.low == 0: result.low = framePtr.line i = scanNumber(s, result.high, i) @@ -279,11 +281,11 @@ proc breakpointToggle(s: cstring, start: int) = if not b.isNil: b.flip else: debugOut("[Warning] unknown breakpoint ") -proc dbgEvaluate(stream: TFile, s: cstring, start: int, f: PFrame) = - var dbgTemp: TStaticStr +proc dbgEvaluate(stream: File, s: cstring, start: int, f: PFrame) = + var dbgTemp: StaticStr var i = scanWord(s, dbgTemp, start) while s[i] in {' ', '\t'}: inc(i) - var v: TVarSlot + var v: VarSlot if s[i] == '.': inc(i) add(dbgTemp, '.') @@ -299,7 +301,7 @@ proc dbgEvaluate(stream: TFile, s: cstring, start: int, f: PFrame) = writeVariable(stream, v) proc dbgOut(s: cstring, start: int, currFrame: PFrame) = - var dbgTemp: TStaticStr + var dbgTemp: StaticStr var i = scanFilename(s, dbgTemp, start) if dbgTemp.len == 0: invalidCommand() @@ -312,7 +314,7 @@ proc dbgOut(s: cstring, start: int, currFrame: PFrame) = close(stream) proc dbgStackFrame(s: cstring, start: int, currFrame: PFrame) = - var dbgTemp: TStaticStr + var dbgTemp: StaticStr var i = scanFilename(s, dbgTemp, start) if dbgTemp.len == 0: # just write it to stdout: @@ -325,7 +327,7 @@ proc dbgStackFrame(s: cstring, start: int, currFrame: PFrame) = listFrame(stream, currFrame) close(stream) -proc readLine(f: TFile, line: var TStaticStr): bool = +proc readLine(f: File, line: var StaticStr): bool = while true: var c = fgetc(f) if c < 0'i32: @@ -358,7 +360,7 @@ proc commandPrompt() = again = true dbgFramePtr = framePtr # for going down and up the stack dbgDown = 0 # how often we did go down - dbgTemp: TStaticStr + dbgTemp: StaticStr while again: write(stdout, "*** endb| >>") diff --git a/lib/system/excpt.nim b/lib/system/excpt.nim index 189d52f57..f157f428c 100644 --- a/lib/system/excpt.nim +++ b/lib/system/excpt.nim @@ -365,5 +365,6 @@ when not defined(noSignalHandler): proc setControlCHook(hook: proc () {.noconv.} not nil) = # ugly cast, but should work on all architectures: - type TSignalHandler = proc (sig: cint) {.noconv, benign.} - c_signal(SIGINT, cast[TSignalHandler](hook)) + type SignalHandler = proc (sig: cint) {.noconv, benign.} + {.deprecated: [TSignalHandler: SignalHandler].} + c_signal(SIGINT, cast[SignalHandler](hook)) From 2ca90a20a117ba14f6610cf57e6a233d3081b9d5 Mon Sep 17 00:00:00 2001 From: pdw Date: Sun, 24 May 2015 22:37:46 -0500 Subject: [PATCH 0354/1263] lib/system/g-w - Dropped 'T' from types --- lib/system/gc.nim | 138 ++++++++++++++++++------------------ lib/system/gc2.nim | 151 +++++++++++++++++++++------------------- lib/system/gc_ms.nim | 95 ++++++++++++------------- lib/system/jssys.nim | 67 +++++++++--------- lib/system/mmdisp.nim | 31 +++++---- lib/system/profiler.nim | 22 +++--- lib/system/repr.nim | 37 +++++----- lib/system/sets.nim | 5 +- lib/system/syslocks.nim | 60 ++++++++-------- lib/system/sysspawn.nim | 4 +- lib/system/threads.nim | 140 +++++++++++++++++++------------------ lib/system/timers.nim | 57 ++++++++------- lib/system/widestrs.nim | 15 ++-- 13 files changed, 426 insertions(+), 396 deletions(-) diff --git a/lib/system/gc.nim b/lib/system/gc.nim index e0d1006d9..ae8bb724f 100644 --- a/lib/system/gc.nim +++ b/lib/system/gc.nim @@ -45,17 +45,17 @@ const rcShift = 3 # shift by rcShift to get the reference counter colorMask = 0b011 type - TWalkOp = enum + WalkOp = enum waMarkGlobal, # part of the backup/debug mark&sweep waMarkPrecise, # part of the backup/debug mark&sweep waZctDecRef, waPush, waCycleDecRef, waMarkGray, waScan, waScanBlack, waCollectWhite #, waDebug - TFinalizer {.compilerproc.} = proc (self: pointer) {.nimcall, benign.} + Finalizer {.compilerproc.} = proc (self: pointer) {.nimcall, benign.} # A ref type can have a finalizer that is called before the object's # storage is freed. - TGcStat {.final, pure.} = object + GcStat {.final, pure.} = object stackScans: int # number of performed stack scans (for statistics) cycleCollections: int # number of performed full collections maxThreshold: int # max threshold that has been set @@ -64,35 +64,36 @@ type cycleTableSize: int # max entries in cycle table maxPause: int64 # max measured GC pause in nanoseconds - TGcHeap {.final, pure.} = object # this contains the zero count and + GcHeap {.final, pure.} = object # this contains the zero count and # non-zero count table stackBottom: pointer cycleThreshold: int when useCellIds: idGenerator: int - zct: TCellSeq # the zero count table - decStack: TCellSeq # cells in the stack that are to decref again - cycleRoots: TCellSet - tempStack: TCellSeq # temporary stack for recursion elimination + zct: CellSeq # the zero count table + decStack: CellSeq # cells in the stack that are to decref again + cycleRoots: CellSet + tempStack: CellSeq # temporary stack for recursion elimination recGcLock: int # prevent recursion via finalizers; no thread lock when withRealTime: - maxPause: TNanos # max allowed pause in nanoseconds; active if > 0 - region: TMemRegion # garbage collected region - stat: TGcStat + maxPause: Nanos # max allowed pause in nanoseconds; active if > 0 + region: MemRegion # garbage collected region + stat: GcStat when useMarkForDebug or useBackupGc: - marked: TCellSet - + marked: CellSet +{.deprecated: [TWalkOp: WalkOp, TFinalizer: Finalizer, TGcHeap: GcHeap, + TGcStat: GcStat].} var - gch {.rtlThreadVar.}: TGcHeap + gch {.rtlThreadVar.}: GcHeap when not defined(useNimRtl): instantiateForRegion(gch.region) -template acquire(gch: TGcHeap) = +template acquire(gch: GcHeap) = when hasThreadSupport and hasSharedHeap: acquireSys(HeapLock) -template release(gch: TGcHeap) = +template release(gch: GcHeap) = when hasThreadSupport and hasSharedHeap: releaseSys(HeapLock) @@ -104,18 +105,18 @@ template gcAssert(cond: bool, msg: string) = writeStackTrace() quit 1 -proc addZCT(s: var TCellSeq, c: PCell) {.noinline.} = +proc addZCT(s: var CellSeq, c: PCell) {.noinline.} = if (c.refcount and ZctFlag) == 0: c.refcount = c.refcount or ZctFlag add(s, c) proc cellToUsr(cell: PCell): pointer {.inline.} = # convert object (=pointer to refcount) to pointer to userdata - result = cast[pointer](cast[ByteAddress](cell)+%ByteAddress(sizeof(TCell))) + result = cast[pointer](cast[ByteAddress](cell)+%ByteAddress(sizeof(Cell))) proc usrToCell(usr: pointer): PCell {.inline.} = # convert pointer to userdata to object (=pointer to refcount) - result = cast[PCell](cast[ByteAddress](usr)-%ByteAddress(sizeof(TCell))) + result = cast[PCell](cast[ByteAddress](usr)-%ByteAddress(sizeof(Cell))) proc canBeCycleRoot(c: PCell): bool {.inline.} = result = ntfAcyclic notin c.typ.flags @@ -152,11 +153,11 @@ template gcTrace(cell, state: expr): stmt {.immediate.} = when traceGC: traceCell(cell, state) # forward declarations: -proc collectCT(gch: var TGcHeap) {.benign.} +proc collectCT(gch: var GcHeap) {.benign.} proc isOnStack*(p: pointer): bool {.noinline, benign.} -proc forAllChildren(cell: PCell, op: TWalkOp) {.benign.} -proc doOperation(p: pointer, op: TWalkOp) {.benign.} -proc forAllChildrenAux(dest: pointer, mt: PNimType, op: TWalkOp) {.benign.} +proc forAllChildren(cell: PCell, op: WalkOp) {.benign.} +proc doOperation(p: pointer, op: WalkOp) {.benign.} +proc forAllChildrenAux(dest: pointer, mt: PNimType, op: WalkOp) {.benign.} # we need the prototype here for debugging purposes when hasThreadSupport and hasSharedHeap: @@ -178,7 +179,7 @@ proc prepareDealloc(cell: PCell) = # prevend recursive entering here by a lock. # XXX: we should set the cell's children to nil! inc(gch.recGcLock) - (cast[TFinalizer](cell.typ.finalizer))(cellToUsr(cell)) + (cast[Finalizer](cell.typ.finalizer))(cellToUsr(cell)) dec(gch.recGcLock) proc rtlAddCycleRoot(c: PCell) {.rtl, inl.} = @@ -276,7 +277,7 @@ proc unsureAsgnRef(dest: PPointer, src: pointer) {.compilerProc.} = proc initGC() = when not defined(useNimRtl): when traceGC: - for i in low(TCellState)..high(TCellState): init(states[i]) + for i in low(CellState)..high(CellState): init(states[i]) gch.cycleThreshold = InitialCycleThreshold gch.stat.stackScans = 0 gch.stat.cycleCollections = 0 @@ -308,12 +309,13 @@ proc setupForeignThreadGc*() = when useMarkForDebug or useBackupGc: type - TGlobalMarkerProc = proc () {.nimcall, benign.} + GlobalMarkerProc = proc () {.nimcall, benign.} + {.deprecated: [TGlobalMarkerProc: GlobalMarkerProc].} var globalMarkersLen: int - globalMarkers: array[0.. 7_000, TGlobalMarkerProc] + globalMarkers: array[0.. 7_000, GlobalMarkerProc] - proc nimRegisterGlobalMarker(markerProc: TGlobalMarkerProc) {.compilerProc.} = + proc nimRegisterGlobalMarker(markerProc: GlobalMarkerProc) {.compilerProc.} = if globalMarkersLen <= high(globalMarkers): globalMarkers[globalMarkersLen] = markerProc inc globalMarkersLen @@ -321,11 +323,11 @@ when useMarkForDebug or useBackupGc: echo "[GC] cannot register global variable; too many global variables" quit 1 -proc cellsetReset(s: var TCellSet) = +proc cellsetReset(s: var CellSet) = deinit(s) init(s) -proc forAllSlotsAux(dest: pointer, n: ptr TNimNode, op: TWalkOp) {.benign.} = +proc forAllSlotsAux(dest: pointer, n: ptr TNimNode, op: WalkOp) {.benign.} = var d = cast[ByteAddress](dest) case n.kind of nkSlot: forAllChildrenAux(cast[pointer](d +% n.offset), n.typ, op) @@ -345,7 +347,7 @@ proc forAllSlotsAux(dest: pointer, n: ptr TNimNode, op: TWalkOp) {.benign.} = if m != nil: forAllSlotsAux(dest, m, op) of nkNone: sysAssert(false, "forAllSlotsAux") -proc forAllChildrenAux(dest: pointer, mt: PNimType, op: TWalkOp) = +proc forAllChildrenAux(dest: pointer, mt: PNimType, op: WalkOp) = var d = cast[ByteAddress](dest) if dest == nil: return # nothing to do if ntfNoRefs notin mt.flags: @@ -359,7 +361,7 @@ proc forAllChildrenAux(dest: pointer, mt: PNimType, op: TWalkOp) = forAllChildrenAux(cast[pointer](d +% i *% mt.base.size), mt.base, op) else: discard -proc forAllChildren(cell: PCell, op: TWalkOp) = +proc forAllChildren(cell: PCell, op: WalkOp) = gcAssert(cell != nil, "forAllChildren: 1") gcAssert(isAllocatedPtr(gch.region, cell), "forAllChildren: 2") gcAssert(cell.typ != nil, "forAllChildren: 3") @@ -380,7 +382,7 @@ proc forAllChildren(cell: PCell, op: TWalkOp) = GenericSeqSize), cell.typ.base, op) else: discard -proc addNewObjToZCT(res: PCell, gch: var TGcHeap) {.inline.} = +proc addNewObjToZCT(res: PCell, gch: var GcHeap) {.inline.} = # we check the last 8 entries (cache line) for a slot that could be reused. # In 63% of all cases we succeed here! But we have to optimize the heck # out of this small linear search so that ``newObj`` is not slowed down. @@ -431,13 +433,13 @@ proc gcInvariant*() = markForDebug(gch) {.pop.} -proc rawNewObj(typ: PNimType, size: int, gch: var TGcHeap): pointer = +proc rawNewObj(typ: PNimType, size: int, gch: var GcHeap): pointer = # generates a new object and sets its reference counter to 0 sysAssert(allocInv(gch.region), "rawNewObj begin") acquire(gch) gcAssert(typ.kind in {tyRef, tyString, tySequence}, "newObj: 1") collectCT(gch) - var res = cast[PCell](rawAlloc(gch.region, size + sizeof(TCell))) + var res = cast[PCell](rawAlloc(gch.region, size + sizeof(Cell))) gcAssert((cast[ByteAddress](res) and (MemAlign-1)) == 0, "newObj: 2") # now it is buffered in the ZCT res.typ = typ @@ -486,7 +488,7 @@ proc newObjRC1(typ: PNimType, size: int): pointer {.compilerRtl.} = collectCT(gch) sysAssert(allocInv(gch.region), "newObjRC1 after collectCT") - var res = cast[PCell](rawAlloc(gch.region, size + sizeof(TCell))) + var res = cast[PCell](rawAlloc(gch.region, size + sizeof(Cell))) sysAssert(allocInv(gch.region), "newObjRC1 after rawAlloc") sysAssert((cast[ByteAddress](res) and (MemAlign-1)) == 0, "newObj: 2") # now it is buffered in the ZCT @@ -515,7 +517,7 @@ proc newSeqRC1(typ: PNimType, len: int): pointer {.compilerRtl.} = cast[PGenericSeq](result).reserved = len when defined(memProfiler): nimProfile(size) -proc growObj(old: pointer, newsize: int, gch: var TGcHeap): pointer = +proc growObj(old: pointer, newsize: int, gch: var GcHeap): pointer = acquire(gch) collectCT(gch) var ol = usrToCell(old) @@ -523,13 +525,13 @@ proc growObj(old: pointer, newsize: int, gch: var TGcHeap): pointer = gcAssert(ol.typ.kind in {tyString, tySequence}, "growObj: 2") sysAssert(allocInv(gch.region), "growObj begin") - var res = cast[PCell](rawAlloc(gch.region, newsize + sizeof(TCell))) + var res = cast[PCell](rawAlloc(gch.region, newsize + sizeof(Cell))) var elemSize = 1 if ol.typ.kind != tyString: elemSize = ol.typ.base.size var oldsize = cast[PGenericSeq](old).len*elemSize + GenericSeqSize - copyMem(res, ol, oldsize + sizeof(TCell)) - zeroMem(cast[pointer](cast[ByteAddress](res)+% oldsize +% sizeof(TCell)), + copyMem(res, ol, oldsize + sizeof(Cell)) + zeroMem(cast[pointer](cast[ByteAddress](res)+% oldsize +% sizeof(Cell)), newsize-oldsize) sysAssert((cast[ByteAddress](res) and (MemAlign-1)) == 0, "growObj: 3") # This can be wrong for intermediate temps that are nevertheless on the @@ -564,7 +566,7 @@ proc growObj(old: pointer, newsize: int, gch: var TGcHeap): pointer = decRef(ol) else: sysAssert(ol.typ != nil, "growObj: 5") - zeroMem(ol, sizeof(TCell)) + zeroMem(ol, sizeof(Cell)) release(gch) when useCellIds: inc gch.idGenerator @@ -580,7 +582,7 @@ proc growObj(old: pointer, newsize: int): pointer {.rtl.} = # ---------------- cycle collector ------------------------------------------- -proc freeCyclicCell(gch: var TGcHeap, c: PCell) = +proc freeCyclicCell(gch: var GcHeap, c: PCell) = prepareDealloc(c) gcTrace(c, csCycFreed) when logGC: writeCell("cycle collector dealloc cell", c) @@ -589,7 +591,7 @@ proc freeCyclicCell(gch: var TGcHeap, c: PCell) = rawDealloc(gch.region, c) else: gcAssert(c.typ != nil, "freeCyclicCell") - zeroMem(c, sizeof(TCell)) + zeroMem(c, sizeof(Cell)) proc markGray(s: PCell) = if s.color != rcGray: @@ -620,7 +622,7 @@ proc collectWhite(s: PCell) = forAllChildren(s, waCollectWhite) freeCyclicCell(gch, s) -proc markRoots(gch: var TGcHeap) = +proc markRoots(gch: var GcHeap) = var tabSize = 0 for s in elements(gch.cycleRoots): #writeCell("markRoot", s) @@ -635,7 +637,7 @@ proc markRoots(gch: var TGcHeap) = gch.stat.cycleTableSize = max(gch.stat.cycleTableSize, tabSize) when useBackupGc: - proc sweep(gch: var TGcHeap) = + proc sweep(gch: var GcHeap) = for x in allObjects(gch.region): if isCell(x): # cast to PCell is correct here: @@ -643,7 +645,7 @@ when useBackupGc: if c notin gch.marked: freeCyclicCell(gch, c) when useMarkForDebug or useBackupGc: - proc markS(gch: var TGcHeap, c: PCell) = + proc markS(gch: var GcHeap, c: PCell) = incl(gch.marked, c) gcAssert gch.tempStack.len == 0, "stack not empty!" forAllChildren(c, waMarkPrecise) @@ -653,10 +655,10 @@ when useMarkForDebug or useBackupGc: if not containsOrIncl(gch.marked, d): forAllChildren(d, waMarkPrecise) - proc markGlobals(gch: var TGcHeap) = + proc markGlobals(gch: var GcHeap) = for i in 0 .. < globalMarkersLen: globalMarkers[i]() - proc stackMarkS(gch: var TGcHeap, p: pointer) {.inline.} = + proc stackMarkS(gch: var GcHeap, p: pointer) {.inline.} = # the addresses are not as cells on the stack, so turn them to cells: var cell = usrToCell(p) var c = cast[TAddress](cell) @@ -688,7 +690,7 @@ when logGC: forAllChildren(s, waDebug) c_fprintf(c_stdout, "}\n") -proc doOperation(p: pointer, op: TWalkOp) = +proc doOperation(p: pointer, op: WalkOp) = if p == nil: return var c: PCell = usrToCell(p) gcAssert(c != nil, "doOperation: 1") @@ -733,19 +735,19 @@ proc doOperation(p: pointer, op: TWalkOp) = #of waDebug: debugGraph(c) proc nimGCvisit(d: pointer, op: int) {.compilerRtl.} = - doOperation(d, TWalkOp(op)) + doOperation(d, WalkOp(op)) -proc collectZCT(gch: var TGcHeap): bool {.benign.} +proc collectZCT(gch: var GcHeap): bool {.benign.} when useMarkForDebug or useBackupGc: - proc markStackAndRegistersForSweep(gch: var TGcHeap) {.noinline, cdecl, + proc markStackAndRegistersForSweep(gch: var GcHeap) {.noinline, cdecl, benign.} -proc collectRoots(gch: var TGcHeap) = +proc collectRoots(gch: var GcHeap) = for s in elements(gch.cycleRoots): collectWhite(s) -proc collectCycles(gch: var TGcHeap) = +proc collectCycles(gch: var GcHeap) = # ensure the ZCT 'color' is not used: while gch.zct.len > 0: discard collectZCT(gch) when useBackupGc: @@ -778,7 +780,7 @@ proc collectCycles(gch: var TGcHeap) = if cycleRootsLen != 0: cfprintf(cstdout, "cycle roots: %ld\n", cycleRootsLen) -proc gcMark(gch: var TGcHeap, p: pointer) {.inline.} = +proc gcMark(gch: var GcHeap, p: pointer) {.inline.} = # the addresses are not as cells on the stack, so turn them to cells: sysAssert(allocInv(gch.region), "gcMark begin") var cell = usrToCell(p) @@ -798,7 +800,7 @@ proc gcMark(gch: var TGcHeap, p: pointer) {.inline.} = add(gch.decStack, cell) sysAssert(allocInv(gch.region), "gcMark end") -proc markThreadStacks(gch: var TGcHeap) = +proc markThreadStacks(gch: var GcHeap) = when hasThreadSupport and hasSharedHeap: {.error: "not fully implemented".} var it = threadList @@ -887,7 +889,7 @@ elif stackIncreases: var jmpbufSize {.importc: "sizeof(jmp_buf)", nodecl.}: int - # a little hack to get the size of a TJmpBuf in the generated C code + # a little hack to get the size of a JmpBuf in the generated C code # in a platform independent way template forEachStackSlot(gch, gcMark: expr) {.immediate, dirty.} = @@ -947,18 +949,18 @@ else: gcMark(gch, cast[PPointer](sp)[]) sp = sp +% sizeof(pointer) -proc markStackAndRegisters(gch: var TGcHeap) {.noinline, cdecl.} = +proc markStackAndRegisters(gch: var GcHeap) {.noinline, cdecl.} = forEachStackSlot(gch, gcMark) when useMarkForDebug or useBackupGc: - proc markStackAndRegistersForSweep(gch: var TGcHeap) = + proc markStackAndRegistersForSweep(gch: var GcHeap) = forEachStackSlot(gch, stackMarkS) # ---------------------------------------------------------------------------- # end of non-portable code # ---------------------------------------------------------------------------- -proc collectZCT(gch: var TGcHeap): bool = +proc collectZCT(gch: var GcHeap): bool = # Note: Freeing may add child objects to the ZCT! So essentially we do # deep freeing, which is bad for incremental operation. In order to # avoid a deep stack, we move objects to keep the ZCT small. @@ -968,7 +970,7 @@ proc collectZCT(gch: var TGcHeap): bool = when withRealTime: var steps = workPackage - var t0: TTicks + var t0: Ticks if gch.maxPause > 0: t0 = getticks() while L[] > 0: var c = gch.zct.d[0] @@ -1001,7 +1003,7 @@ proc collectZCT(gch: var TGcHeap): bool = rawDealloc(gch.region, c) else: sysAssert(c.typ != nil, "collectZCT 2") - zeroMem(c, sizeof(TCell)) + zeroMem(c, sizeof(Cell)) when withRealTime: if steps == 0: steps = workPackage @@ -1014,7 +1016,7 @@ proc collectZCT(gch: var TGcHeap): bool = return false result = true -proc unmarkStackAndRegisters(gch: var TGcHeap) = +proc unmarkStackAndRegisters(gch: var GcHeap) = var d = gch.decStack.d for i in 0..gch.decStack.len-1: sysAssert isAllocatedPtr(gch.region, d[i]), "unmarkStackAndRegisters" @@ -1026,7 +1028,7 @@ proc unmarkStackAndRegisters(gch: var TGcHeap) = #sysAssert c.typ != nil, "unmarkStackAndRegisters 2" gch.decStack.len = 0 -proc collectCTBody(gch: var TGcHeap) = +proc collectCTBody(gch: var GcHeap) = when withRealTime: let t0 = getticks() sysAssert(allocInv(gch.region), "collectCT: begin") @@ -1058,11 +1060,11 @@ proc collectCTBody(gch: var TGcHeap) = c_fprintf(c_stdout, "[GC] missed deadline: %ld\n", duration) when useMarkForDebug or useBackupGc: - proc markForDebug(gch: var TGcHeap) = + proc markForDebug(gch: var GcHeap) = markStackAndRegistersForSweep(gch) markGlobals(gch) -proc collectCT(gch: var TGcHeap) = +proc collectCT(gch: var GcHeap) = # stackMarkCosts prevents some pathological behaviour: Stack marking # becomes more expensive with large stacks and large stacks mean that # cells with RC=0 are more likely to be kept alive by the stack. @@ -1077,13 +1079,13 @@ proc collectCT(gch: var TGcHeap) = collectCTBody(gch) when withRealTime: - proc toNano(x: int): TNanos {.inline.} = + proc toNano(x: int): Nanos {.inline.} = result = x * 1000 proc GC_setMaxPause*(MaxPauseInUs: int) = gch.maxPause = MaxPauseInUs.toNano - proc GC_step(gch: var TGcHeap, us: int, strongAdvice: bool) = + proc GC_step(gch: var GcHeap, us: int, strongAdvice: bool) = acquire(gch) gch.maxPause = us.toNano if (gch.zct.len >= ZctThreshold or (cycleGC and diff --git a/lib/system/gc2.nim b/lib/system/gc2.nim index 4e3dee51c..015e08c9e 100644 --- a/lib/system/gc2.nim +++ b/lib/system/gc2.nim @@ -54,7 +54,7 @@ const # was replaced by a resize operation. # see growObj for details - rcColorMask = TRefCount(0b00111) + rcColorMask = RefCount(0b00111) rcZct = 0b01000 # already added to ZCT rcInCycleRoots = 0b10000 # already buffered as cycle candidate @@ -97,14 +97,14 @@ const CollectCyclesStats = false type - TWalkOp = enum + WalkOp = enum waPush - TFinalizer {.compilerproc.} = proc (self: pointer) {.nimcall.} + Finalizer {.compilerproc.} = proc (self: pointer) {.nimcall.} # A ref type can have a finalizer that is called before the object's # storage is freed. - TGcStat {.final, pure.} = object + GcStat {.final, pure.} = object stackScans: int # number of performed stack scans (for statistics) cycleCollections: int # number of performed full collections maxThreshold: int # max threshold that has been set @@ -113,16 +113,16 @@ type cycleTableSize: int # max entries in cycle table maxPause: int64 # max measured GC pause in nanoseconds - TGcHeap {.final, pure.} = object # this contains the zero count and + GcHeap {.final, pure.} = object # this contains the zero count and # non-zero count table stackBottom: pointer stackTop: pointer cycleThreshold: int - zct: TCellSeq # the zero count table - decStack: TCellSeq # cells in the stack that are to decref again - cycleRoots: TCellSeq - tempStack: TCellSeq # temporary stack for recursion elimination - freeStack: TCellSeq # objects ready to be freed + zct: CellSeq # the zero count table + decStack: CellSeq # cells in the stack that are to decref again + cycleRoots: CellSeq + tempStack: CellSeq # temporary stack for recursion elimination + freeStack: CellSeq # objects ready to be freed recGcLock: int # prevent recursion via finalizers; no thread lock cycleRootsTrimIdx: int # Trimming is a light-weight collection of the # cycle roots table that uses a cheap linear scan @@ -132,21 +132,22 @@ type # This index indicates the start of the range of # such new objects within the table. when withRealTime: - maxPause: TNanos # max allowed pause in nanoseconds; active if > 0 - region: TMemRegion # garbage collected region - stat: TGcStat - + maxPause: Nanos # max allowed pause in nanoseconds; active if > 0 + region: MemRegion # garbage collected region + stat: GcStat +{.deprecated: [TWalkOp: WalkOp, TFinalizer: Finalizer, TGcStat: GcStat, + TGcHeap: GcHeap].} var - gch* {.rtlThreadVar.}: TGcHeap + gch* {.rtlThreadVar.}: GcHeap when not defined(useNimRtl): instantiateForRegion(gch.region) -template acquire(gch: TGcHeap) = +template acquire(gch: GcHeap) = when hasThreadSupport and hasSharedHeap: AcquireSys(HeapLock) -template release(gch: TGcHeap) = +template release(gch: GcHeap) = when hasThreadSupport and hasSharedHeap: releaseSys(HeapLock) @@ -169,7 +170,7 @@ template isDead(c: Pcell): expr = c.isBitUp(rcReallyDead) # also covers rcRetiredBuffer template clearBit(c: PCell, bit): expr = - c.refcount = c.refcount and (not TRefCount(bit)) + c.refcount = c.refcount and (not RefCount(bit)) when debugGC: var gcCollectionIdx = 0 @@ -206,7 +207,7 @@ when debugGC: c_fprintf(c_stdout, "[GC] %s: %p %d rc=%ld\n", msg, c, kind, c.refcount shr rcShift) -proc addZCT(zct: var TCellSeq, c: PCell) {.noinline.} = +proc addZCT(zct: var CellSeq, c: PCell) {.noinline.} = if c.isBitDown(rcZct): c.setBit rcZct zct.add c @@ -221,7 +222,7 @@ template setStackTop(gch) = var stackTop {.volatile.}: pointer gch.stackTop = addr(stackTop) -template addCycleRoot(cycleRoots: var TCellSeq, c: PCell) = +template addCycleRoot(cycleRoots: var CellSeq, c: PCell) = if c.color != rcCycleCandidate: c.setColor rcCycleCandidate @@ -233,11 +234,11 @@ template addCycleRoot(cycleRoots: var TCellSeq, c: PCell) = proc cellToUsr(cell: PCell): pointer {.inline.} = # convert object (=pointer to refcount) to pointer to userdata - result = cast[pointer](cast[ByteAddress](cell)+%ByteAddress(sizeof(TCell))) + result = cast[pointer](cast[ByteAddress](cell)+%ByteAddress(sizeof(Cell))) proc usrToCell*(usr: pointer): PCell {.inline.} = # convert pointer to userdata to object (=pointer to refcount) - result = cast[PCell](cast[ByteAddress](usr)-%ByteAddress(sizeof(TCell))) + result = cast[PCell](cast[ByteAddress](usr)-%ByteAddress(sizeof(Cell))) proc canbeCycleRoot(c: PCell): bool {.inline.} = result = ntfAcyclic notin c.typ.flags @@ -254,11 +255,11 @@ when BitsPerPage mod (sizeof(int)*8) != 0: {.error: "(BitsPerPage mod BitsPerUnit) should be zero!".} # forward declarations: -proc collectCT(gch: var TGcHeap) +proc collectCT(gch: var GcHeap) proc isOnStack*(p: pointer): bool {.noinline.} -proc forAllChildren(cell: PCell, op: TWalkOp) -proc doOperation(p: pointer, op: TWalkOp) -proc forAllChildrenAux(dest: pointer, mt: PNimType, op: TWalkOp) +proc forAllChildren(cell: PCell, op: WalkOp) +proc doOperation(p: pointer, op: WalkOp) +proc forAllChildrenAux(dest: pointer, mt: PNimType, op: WalkOp) # we need the prototype here for debugging purposes proc prepareDealloc(cell: PCell) = @@ -269,18 +270,19 @@ proc prepareDealloc(cell: PCell) = # prevend recursive entering here by a lock. # XXX: we should set the cell's children to nil! inc(gch.recGcLock) - (cast[TFinalizer](cell.typ.finalizer))(cellToUsr(cell)) + (cast[Finalizer](cell.typ.finalizer))(cellToUsr(cell)) dec(gch.recGcLock) when traceGC: # traceGC is a special switch to enable extensive debugging type - TCellState = enum + CellState = enum csAllocated, csFreed + {.deprecated: [TCellState: CellState].} var - states: array[TCellState, TCellSet] + states: array[CellState, CellSet] - proc traceCell(c: PCell, state: TCellState) = + proc traceCell(c: PCell, state: CellState) = case state of csAllocated: if c in states[csAllocated]: @@ -300,7 +302,7 @@ when traceGC: incl(states[state], c) proc computeCellWeight(c: PCell): int = - var x: TCellSet + var x: CellSet x.init let startLen = gch.tempStack.len @@ -363,30 +365,32 @@ proc rtlAddZCT(c: PCell) {.rtl, inl.} = WithHeapLock: addZCT(gch.zct, c) type - TCyclicMode = enum + CyclicMode = enum Cyclic, Acyclic, MaybeCyclic - TReleaseType = enum + ReleaseType = enum AddToZTC FreeImmediately - THeapType = enum + HeapType = enum LocalHeap SharedHeap +{.deprecated: [TCyclicMode: CyclicMode, TReleaseType: ReleaseType, + THeapType: HeapType].} -template `++` (rc: TRefCount, heapType: THeapType): stmt = +template `++` (rc: RefCount, heapType: HeapType): stmt = when heapType == SharedHeap: discard atomicInc(rc, rcIncrement) else: inc rc, rcIncrement -template `--`(rc: TRefCount): expr = +template `--`(rc: RefCount): expr = dec rc, rcIncrement rc <% rcIncrement -template `--` (rc: TRefCount, heapType: THeapType): expr = +template `--` (rc: RefCount, heapType: HeapType): expr = (when heapType == SharedHeap: atomicDec(rc, rcIncrement) <% rcIncrement else: --rc) template doDecRef(cc: PCell, @@ -479,7 +483,7 @@ when hasThreadSupport and hasSharedHeap: proc initGC() = when not defined(useNimRtl): when traceGC: - for i in low(TCellState)..high(TCellState): init(states[i]) + for i in low(CellState)..high(CellState): init(states[i]) gch.cycleThreshold = InitialCycleThreshold gch.stat.stackScans = 0 gch.stat.cycleCollections = 0 @@ -494,7 +498,7 @@ proc initGC() = init(gch.cycleRoots) init(gch.decStack) -proc forAllSlotsAux(dest: pointer, n: ptr TNimNode, op: TWalkOp) = +proc forAllSlotsAux(dest: pointer, n: ptr TNimNode, op: WalkOp) = var d = cast[ByteAddress](dest) case n.kind of nkSlot: forAllChildrenAux(cast[pointer](d +% n.offset), n.typ, op) @@ -514,7 +518,7 @@ proc forAllSlotsAux(dest: pointer, n: ptr TNimNode, op: TWalkOp) = if m != nil: forAllSlotsAux(dest, m, op) of nkNone: sysAssert(false, "forAllSlotsAux") -proc forAllChildrenAux(dest: pointer, mt: PNimType, op: TWalkOp) = +proc forAllChildrenAux(dest: pointer, mt: PNimType, op: WalkOp) = var d = cast[ByteAddress](dest) if dest == nil: return # nothing to do if ntfNoRefs notin mt.flags: @@ -528,7 +532,7 @@ proc forAllChildrenAux(dest: pointer, mt: PNimType, op: TWalkOp) = forAllChildrenAux(cast[pointer](d +% i *% mt.base.size), mt.base, op) else: discard -proc forAllChildren(cell: PCell, op: TWalkOp) = +proc forAllChildren(cell: PCell, op: WalkOp) = sysAssert(cell != nil, "forAllChildren: 1") sysAssert(cell.typ != nil, "forAllChildren: 2") sysAssert cell.typ.kind in {tyRef, tySequence, tyString}, "forAllChildren: 3" @@ -549,7 +553,7 @@ proc forAllChildren(cell: PCell, op: TWalkOp) = cell.typ.base, op) else: discard -proc addNewObjToZCT(res: PCell, gch: var TGcHeap) {.inline.} = +proc addNewObjToZCT(res: PCell, gch: var GcHeap) {.inline.} = # we check the last 8 entries (cache line) for a slot that could be reused. # In 63% of all cases we succeed here! But we have to optimize the heck # out of this small linear search so that ``newObj`` is not slowed down. @@ -593,7 +597,7 @@ proc addNewObjToZCT(res: PCell, gch: var TGcHeap) {.inline.} = return add(gch.zct, res) -proc rawNewObj(typ: PNimType, size: int, gch: var TGcHeap, rc1 = false): pointer = +proc rawNewObj(typ: PNimType, size: int, gch: var GcHeap, rc1 = false): pointer = # generates a new object and sets its reference counter to 0 acquire(gch) sysAssert(allocInv(gch.region), "rawNewObj begin") @@ -602,7 +606,7 @@ proc rawNewObj(typ: PNimType, size: int, gch: var TGcHeap, rc1 = false): pointer collectCT(gch) sysAssert(allocInv(gch.region), "rawNewObj after collect") - var res = cast[PCell](rawAlloc(gch.region, size + sizeof(TCell))) + var res = cast[PCell](rawAlloc(gch.region, size + sizeof(Cell))) sysAssert(allocInv(gch.region), "rawNewObj after rawAlloc") sysAssert((cast[ByteAddress](res) and (MemAlign-1)) == 0, "newObj: 2") @@ -638,20 +642,20 @@ proc rawNewObj(typ: PNimType, size: int, gch: var TGcHeap, rc1 = false): pointer {.pop.} -proc freeCell(gch: var TGcHeap, c: PCell) = +proc freeCell(gch: var GcHeap, c: PCell) = # prepareDealloc(c) gcTrace(c, csFreed) when reallyDealloc: rawDealloc(gch.region, c) else: sysAssert(c.typ != nil, "collectCycles") - zeroMem(c, sizeof(TCell)) + zeroMem(c, sizeof(Cell)) -template eraseAt(cells: var TCellSeq, at: int): stmt = +template eraseAt(cells: var CellSeq, at: int): stmt = cells.d[at] = cells.d[cells.len - 1] dec cells.len -template trimAt(roots: var TCellSeq, at: int): stmt = +template trimAt(roots: var CellSeq, at: int): stmt = # This will remove a cycle root candidate during trimming. # a candidate is removed either because it received a refup and # it's no longer a candidate or because it received further refdowns @@ -696,7 +700,7 @@ proc newSeqRC1(typ: PNimType, len: int): pointer {.compilerRtl.} = cast[PGenericSeq](result).len = len cast[PGenericSeq](result).reserved = len -proc growObj(old: pointer, newsize: int, gch: var TGcHeap): pointer = +proc growObj(old: pointer, newsize: int, gch: var GcHeap): pointer = acquire(gch) collectCT(gch) var ol = usrToCell(old) @@ -704,7 +708,7 @@ proc growObj(old: pointer, newsize: int, gch: var TGcHeap): pointer = sysAssert(ol.typ.kind in {tyString, tySequence}, "growObj: 2") sysAssert(allocInv(gch.region), "growObj begin") - var res = cast[PCell](rawAlloc(gch.region, newsize + sizeof(TCell))) + var res = cast[PCell](rawAlloc(gch.region, newsize + sizeof(Cell))) var elemSize = if ol.typ.kind != tyString: ol.typ.base.size else: 1 @@ -713,8 +717,8 @@ proc growObj(old: pointer, newsize: int, gch: var TGcHeap): pointer = # XXX: This should happen outside # call user-defined move code # call user-defined default constructor - copyMem(res, ol, oldsize + sizeof(TCell)) - zeroMem(cast[pointer](cast[ByteAddress](res)+% oldsize +% sizeof(TCell)), + copyMem(res, ol, oldsize + sizeof(Cell)) + zeroMem(cast[pointer](cast[ByteAddress](res)+% oldsize +% sizeof(Cell)), newsize-oldsize) sysAssert((cast[ByteAddress](res) and (MemAlign-1)) == 0, "growObj: 3") @@ -778,26 +782,27 @@ proc growObj(old: pointer, newsize: int): pointer {.rtl.} = # ---------------- cycle collector ------------------------------------------- -proc doOperation(p: pointer, op: TWalkOp) = +proc doOperation(p: pointer, op: WalkOp) = if p == nil: return var c: PCell = usrToCell(p) sysAssert(c != nil, "doOperation: 1") gch.tempStack.add c proc nimGCvisit(d: pointer, op: int) {.compilerRtl.} = - doOperation(d, TWalkOp(op)) + doOperation(d, WalkOp(op)) type - TRecursionType = enum + RecursionType = enum FromChildren, FromRoot +{.deprecated: [TRecursionType: RecursionType].} -proc collectZCT(gch: var TGcHeap): bool +proc collectZCT(gch: var GcHeap): bool -template pseudoRecursion(typ: TRecursionType, body: stmt): stmt = +template pseudoRecursion(typ: RecursionType, body: stmt): stmt = discard -proc trimCycleRoots(gch: var TGcHeap, startIdx = gch.cycleRootsTrimIdx) = +proc trimCycleRoots(gch: var GcHeap, startIdx = gch.cycleRootsTrimIdx) = var i = startIdx while i < gch.cycleRoots.len: if gch.cycleRoots.d[i].color != rcCycleCandidate: @@ -808,7 +813,7 @@ proc trimCycleRoots(gch: var TGcHeap, startIdx = gch.cycleRootsTrimIdx) = gch.cycleRootsTrimIdx = gch.cycleRoots.len # we now use a much simpler and non-recursive algorithm for cycle removal -proc collectCycles(gch: var TGcHeap) = +proc collectCycles(gch: var GcHeap) = if gch.cycleRoots.len == 0: return gch.stat.cycleTableSize = max(gch.stat.cycleTableSize, gch.cycleRoots.len) @@ -990,7 +995,7 @@ var gcDebugging* = false var seqdbg* : proc (s: PGenericSeq) {.cdecl.} -proc gcMark(gch: var TGcHeap, p: pointer) {.inline.} = +proc gcMark(gch: var GcHeap, p: pointer) {.inline.} = # the addresses are not as cells on the stack, so turn them to cells: sysAssert(allocInv(gch.region), "gcMark begin") var cell = usrToCell(p) @@ -1025,7 +1030,7 @@ proc gcMark(gch: var TGcHeap, p: pointer) {.inline.} = add(gch.decStack, cell) sysAssert(allocInv(gch.region), "gcMark end") -proc markThreadStacks(gch: var TGcHeap) = +proc markThreadStacks(gch: var GcHeap) = when hasThreadSupport and hasSharedHeap: {.error: "not fully implemented".} var it = threadList @@ -1074,7 +1079,7 @@ proc stackSize(): int {.noinline.} = var jmpbufSize {.importc: "sizeof(jmp_buf)", nodecl.}: int - # a little hack to get the size of a TJmpBuf in the generated C code + # a little hack to get the size of a JmpBuf in the generated C code # in a platform independent way when defined(sparc): # For SPARC architecture. @@ -1086,7 +1091,7 @@ when defined(sparc): # For SPARC architecture. var x = cast[ByteAddress](p) result = a <=% x and x <=% b - proc markStackAndRegisters(gch: var TGcHeap) {.noinline, cdecl.} = + proc markStackAndRegisters(gch: var GcHeap) {.noinline, cdecl.} = when defined(sparcv9): asm """"flushw \n" """ else: @@ -1117,7 +1122,7 @@ elif stackIncreases: var x = cast[ByteAddress](p) result = a <=% x and x <=% b - proc markStackAndRegisters(gch: var TGcHeap) {.noinline, cdecl.} = + proc markStackAndRegisters(gch: var GcHeap) {.noinline, cdecl.} = var registers: C_JmpBuf if c_setjmp(registers) == 0'i32: # To fill the C stack with registers. var max = cast[ByteAddress](gch.stackBottom) @@ -1140,7 +1145,7 @@ else: var x = cast[ByteAddress](p) result = a <=% x and x <=% b - proc markStackAndRegisters(gch: var TGcHeap) {.noinline, cdecl.} = + proc markStackAndRegisters(gch: var GcHeap) {.noinline, cdecl.} = # We use a jmp_buf buffer that is in the C stack. # Used to traverse the stack and registers assuming # that 'setjmp' will save registers in the C stack. @@ -1181,7 +1186,7 @@ else: # end of non-portable code # ---------------------------------------------------------------------------- -proc releaseCell(gch: var TGcHeap, cell: PCell) = +proc releaseCell(gch: var GcHeap, cell: PCell) = if cell.color != rcReallyDead: prepareDealloc(cell) cell.setColor rcReallyDead @@ -1210,13 +1215,13 @@ proc releaseCell(gch: var TGcHeap, cell: PCell) = # recursion). # We can ignore it now as the ZCT cleaner will reach it soon. -proc collectZCT(gch: var TGcHeap): bool = +proc collectZCT(gch: var GcHeap): bool = const workPackage = 100 var L = addr(gch.zct.len) when withRealtime: var steps = workPackage - var t0: TTicks + var t0: Ticks if gch.maxPause > 0: t0 = getticks() while L[] > 0: @@ -1257,7 +1262,7 @@ proc collectZCT(gch: var TGcHeap): bool = #deInit(gch.zct) #init(gch.zct) -proc unmarkStackAndRegisters(gch: var TGcHeap) = +proc unmarkStackAndRegisters(gch: var GcHeap) = var d = gch.decStack.d for i in 0 .. 0 and duration > gch.maxPause: c_fprintf(c_stdout, "[GC] missed deadline: %ld\n", duration) -proc collectCT(gch: var TGcHeap) = +proc collectCT(gch: var GcHeap) = if (gch.zct.len >= ZctThreshold or (cycleGC and getOccupiedMem(gch.region)>=gch.cycleThreshold) or alwaysGC) and gch.recGcLock == 0: collectCTBody(gch) when withRealtime: - proc toNano(x: int): TNanos {.inline.} = + proc toNano(x: int): Nanos {.inline.} = result = x * 1000 proc GC_setMaxPause*(MaxPauseInUs: int) = gch.maxPause = MaxPauseInUs.toNano - proc GC_step(gch: var TGcHeap, us: int, strongAdvice: bool) = + proc GC_step(gch: var GcHeap, us: int, strongAdvice: bool) = acquire(gch) gch.maxPause = us.toNano if (gch.zct.len >= ZctThreshold or (cycleGC and diff --git a/lib/system/gc_ms.nim b/lib/system/gc_ms.nim index a0699f46a..aab28eba2 100644 --- a/lib/system/gc_ms.nim +++ b/lib/system/gc_ms.nim @@ -26,49 +26,50 @@ when defined(memProfiler): proc nimProfile(requestedSize: int) type - TWalkOp = enum + WalkOp = enum waMarkGlobal, # we need to mark conservatively for global marker procs # as these may refer to a global var and not to a thread # local waMarkPrecise # fast precise marking - TFinalizer {.compilerproc.} = proc (self: pointer) {.nimcall, benign.} + Finalizer {.compilerproc.} = proc (self: pointer) {.nimcall, benign.} # A ref type can have a finalizer that is called before the object's # storage is freed. - TGlobalMarkerProc = proc () {.nimcall, benign.} + GlobalMarkerProc = proc () {.nimcall, benign.} - TGcStat = object + GcStat = object collections: int # number of performed full collections maxThreshold: int # max threshold that has been set maxStackSize: int # max stack size freedObjects: int # max entries in cycle table - TGcHeap = object # this contains the zero count and + GcHeap = object # this contains the zero count and # non-zero count table stackBottom: pointer cycleThreshold: int when useCellIds: idGenerator: int when withBitvectors: - allocated, marked: TCellSet - tempStack: TCellSeq # temporary stack for recursion elimination + allocated, marked: CellSet + tempStack: CellSeq # temporary stack for recursion elimination recGcLock: int # prevent recursion via finalizers; no thread lock - region: TMemRegion # garbage collected region - stat: TGcStat - additionalRoots: TCellSeq # dummy roots for GC_ref/unref - + region: MemRegion # garbage collected region + stat: GcStat + additionalRoots: CellSeq # dummy roots for GC_ref/unref +{.deprecated: [TWalkOp: WalkOp, TFinalizer: Finalizer, TGcStat: GcStat, + TGlobalMarkerProc: GlobalMarkerProc, TGcHeap, GcHeap].} var - gch {.rtlThreadVar.}: TGcHeap + gch {.rtlThreadVar.}: GcHeap when not defined(useNimRtl): instantiateForRegion(gch.region) -template acquire(gch: TGcHeap) = +template acquire(gch: GcHeap) = when hasThreadSupport and hasSharedHeap: acquireSys(HeapLock) -template release(gch: TGcHeap) = +template release(gch: GcHeap) = when hasThreadSupport and hasSharedHeap: releaseSys(HeapLock) @@ -80,11 +81,11 @@ template gcAssert(cond: bool, msg: string) = proc cellToUsr(cell: PCell): pointer {.inline.} = # convert object (=pointer to refcount) to pointer to userdata - result = cast[pointer](cast[ByteAddress](cell)+%ByteAddress(sizeof(TCell))) + result = cast[pointer](cast[ByteAddress](cell)+%ByteAddress(sizeof(Cell))) proc usrToCell(usr: pointer): PCell {.inline.} = # convert pointer to userdata to object (=pointer to refcount) - result = cast[PCell](cast[ByteAddress](usr)-%ByteAddress(sizeof(TCell))) + result = cast[PCell](cast[ByteAddress](usr)-%ByteAddress(sizeof(Cell))) proc canbeCycleRoot(c: PCell): bool {.inline.} = result = ntfAcyclic notin c.typ.flags @@ -101,9 +102,9 @@ proc internRefcount(p: pointer): int {.exportc: "getRefcount".} = var globalMarkersLen: int - globalMarkers: array[0.. 7_000, TGlobalMarkerProc] + globalMarkers: array[0.. 7_000, GlobalMarkerProc] -proc nimRegisterGlobalMarker(markerProc: TGlobalMarkerProc) {.compilerProc.} = +proc nimRegisterGlobalMarker(markerProc: GlobalMarkerProc) {.compilerProc.} = if globalMarkersLen <= high(globalMarkers): globalMarkers[globalMarkersLen] = markerProc inc globalMarkersLen @@ -116,11 +117,11 @@ when BitsPerPage mod (sizeof(int)*8) != 0: {.error: "(BitsPerPage mod BitsPerUnit) should be zero!".} # forward declarations: -proc collectCT(gch: var TGcHeap) {.benign.} +proc collectCT(gch: var GcHeap) {.benign.} proc isOnStack*(p: pointer): bool {.noinline, benign.} -proc forAllChildren(cell: PCell, op: TWalkOp) {.benign.} -proc doOperation(p: pointer, op: TWalkOp) {.benign.} -proc forAllChildrenAux(dest: pointer, mt: PNimType, op: TWalkOp) {.benign.} +proc forAllChildren(cell: PCell, op: WalkOp) {.benign.} +proc doOperation(p: pointer, op: WalkOp) {.benign.} +proc forAllChildrenAux(dest: pointer, mt: PNimType, op: WalkOp) {.benign.} # we need the prototype here for debugging purposes proc prepareDealloc(cell: PCell) = @@ -131,7 +132,7 @@ proc prepareDealloc(cell: PCell) = # prevend recursive entering here by a lock. # XXX: we should set the cell's children to nil! inc(gch.recGcLock) - (cast[TFinalizer](cell.typ.finalizer))(cellToUsr(cell)) + (cast[Finalizer](cell.typ.finalizer))(cellToUsr(cell)) dec(gch.recGcLock) proc nimGCref(p: pointer) {.compilerProc.} = @@ -182,7 +183,7 @@ proc setupForeignThreadGc*() = setStackBottom(addr(stackTop)) initGC() -proc forAllSlotsAux(dest: pointer, n: ptr TNimNode, op: TWalkOp) {.benign.} = +proc forAllSlotsAux(dest: pointer, n: ptr TNimNode, op: WalkOp) {.benign.} = var d = cast[ByteAddress](dest) case n.kind of nkSlot: forAllChildrenAux(cast[pointer](d +% n.offset), n.typ, op) @@ -194,7 +195,7 @@ proc forAllSlotsAux(dest: pointer, n: ptr TNimNode, op: TWalkOp) {.benign.} = if m != nil: forAllSlotsAux(dest, m, op) of nkNone: sysAssert(false, "forAllSlotsAux") -proc forAllChildrenAux(dest: pointer, mt: PNimType, op: TWalkOp) = +proc forAllChildrenAux(dest: pointer, mt: PNimType, op: WalkOp) = var d = cast[ByteAddress](dest) if dest == nil: return # nothing to do if ntfNoRefs notin mt.flags: @@ -208,7 +209,7 @@ proc forAllChildrenAux(dest: pointer, mt: PNimType, op: TWalkOp) = forAllChildrenAux(cast[pointer](d +% i *% mt.base.size), mt.base, op) else: discard -proc forAllChildren(cell: PCell, op: TWalkOp) = +proc forAllChildren(cell: PCell, op: WalkOp) = gcAssert(cell != nil, "forAllChildren: 1") gcAssert(cell.typ != nil, "forAllChildren: 2") gcAssert cell.typ.kind in {tyRef, tySequence, tyString}, "forAllChildren: 3" @@ -228,12 +229,12 @@ proc forAllChildren(cell: PCell, op: TWalkOp) = GenericSeqSize), cell.typ.base, op) else: discard -proc rawNewObj(typ: PNimType, size: int, gch: var TGcHeap): pointer = +proc rawNewObj(typ: PNimType, size: int, gch: var GcHeap): pointer = # generates a new object and sets its reference counter to 0 acquire(gch) gcAssert(typ.kind in {tyRef, tyString, tySequence}, "newObj: 1") collectCT(gch) - var res = cast[PCell](rawAlloc(gch.region, size + sizeof(TCell))) + var res = cast[PCell](rawAlloc(gch.region, size + sizeof(Cell))) gcAssert((cast[ByteAddress](res) and (MemAlign-1)) == 0, "newObj: 2") # now it is buffered in the ZCT res.typ = typ @@ -285,20 +286,20 @@ proc newSeqRC1(typ: PNimType, len: int): pointer {.compilerRtl.} = cast[PGenericSeq](result).reserved = len when defined(memProfiler): nimProfile(size) -proc growObj(old: pointer, newsize: int, gch: var TGcHeap): pointer = +proc growObj(old: pointer, newsize: int, gch: var GcHeap): pointer = acquire(gch) collectCT(gch) var ol = usrToCell(old) sysAssert(ol.typ != nil, "growObj: 1") gcAssert(ol.typ.kind in {tyString, tySequence}, "growObj: 2") - var res = cast[PCell](rawAlloc(gch.region, newsize + sizeof(TCell))) + var res = cast[PCell](rawAlloc(gch.region, newsize + sizeof(Cell))) var elemSize = 1 if ol.typ.kind != tyString: elemSize = ol.typ.base.size var oldsize = cast[PGenericSeq](old).len*elemSize + GenericSeqSize - copyMem(res, ol, oldsize + sizeof(TCell)) - zeroMem(cast[pointer](cast[ByteAddress](res)+% oldsize +% sizeof(TCell)), + copyMem(res, ol, oldsize + sizeof(Cell)) + zeroMem(cast[pointer](cast[ByteAddress](res)+% oldsize +% sizeof(Cell)), newsize-oldsize) sysAssert((cast[ByteAddress](res) and (MemAlign-1)) == 0, "growObj: 3") when false: @@ -306,7 +307,7 @@ proc growObj(old: pointer, newsize: int, gch: var TGcHeap): pointer = when withBitvectors: excl(gch.allocated, ol) when reallyDealloc: rawDealloc(gch.region, ol) else: - zeroMem(ol, sizeof(TCell)) + zeroMem(ol, sizeof(Cell)) when withBitvectors: incl(gch.allocated, res) when useCellIds: inc gch.idGenerator @@ -322,7 +323,7 @@ proc growObj(old: pointer, newsize: int): pointer {.rtl.} = # ----------------- collector ----------------------------------------------- -proc mark(gch: var TGcHeap, c: PCell) = +proc mark(gch: var GcHeap, c: PCell) = when withBitvectors: incl(gch.marked, c) gcAssert gch.tempStack.len == 0, "stack not empty!" @@ -344,7 +345,7 @@ proc mark(gch: var TGcHeap, c: PCell) = d.refCount = rcBlack forAllChildren(d, waMarkPrecise) -proc doOperation(p: pointer, op: TWalkOp) = +proc doOperation(p: pointer, op: WalkOp) = if p == nil: return var c: PCell = usrToCell(p) gcAssert(c != nil, "doOperation: 1") @@ -359,17 +360,17 @@ proc doOperation(p: pointer, op: TWalkOp) = of waMarkPrecise: add(gch.tempStack, c) proc nimGCvisit(d: pointer, op: int) {.compilerRtl.} = - doOperation(d, TWalkOp(op)) + doOperation(d, WalkOp(op)) -proc freeCyclicCell(gch: var TGcHeap, c: PCell) = +proc freeCyclicCell(gch: var GcHeap, c: PCell) = inc gch.stat.freedObjects prepareDealloc(c) when reallyDealloc: rawDealloc(gch.region, c) else: gcAssert(c.typ != nil, "freeCyclicCell") - zeroMem(c, sizeof(TCell)) + zeroMem(c, sizeof(Cell)) -proc sweep(gch: var TGcHeap) = +proc sweep(gch: var GcHeap) = when withBitvectors: for c in gch.allocated.elementsExcept(gch.marked): gch.allocated.excl(c) @@ -391,12 +392,12 @@ when false: writeStackTrace() quit 1 -proc markGlobals(gch: var TGcHeap) = +proc markGlobals(gch: var GcHeap) = for i in 0 .. < globalMarkersLen: globalMarkers[i]() let d = gch.additionalRoots.d for i in 0 .. < gch.additionalRoots.len: mark(gch, d[i]) -proc gcMark(gch: var TGcHeap, p: pointer) {.inline.} = +proc gcMark(gch: var GcHeap, p: pointer) {.inline.} = # the addresses are not as cells on the stack, so turn them to cells: var cell = usrToCell(p) var c = cast[ByteAddress](cell) @@ -446,7 +447,7 @@ when defined(sparc): # For SPARC architecture. var x = cast[ByteAddress](p) result = a <=% x and x <=% b - proc markStackAndRegisters(gch: var TGcHeap) {.noinline, cdecl.} = + proc markStackAndRegisters(gch: var GcHeap) {.noinline, cdecl.} = when defined(sparcv9): asm """"flushw \n" """ else: @@ -479,10 +480,10 @@ elif stackIncreases: var jmpbufSize {.importc: "sizeof(jmp_buf)", nodecl.}: int - # a little hack to get the size of a TJmpBuf in the generated C code + # a little hack to get the size of a JmpBuf in the generated C code # in a platform independent way - proc markStackAndRegisters(gch: var TGcHeap) {.noinline, cdecl.} = + proc markStackAndRegisters(gch: var GcHeap) {.noinline, cdecl.} = var registers: C_JmpBuf if c_setjmp(registers) == 0'i32: # To fill the C stack with registers. var max = cast[ByteAddress](gch.stackBottom) @@ -505,7 +506,7 @@ else: var x = cast[ByteAddress](p) result = a <=% x and x <=% b - proc markStackAndRegisters(gch: var TGcHeap) {.noinline, cdecl.} = + proc markStackAndRegisters(gch: var GcHeap) {.noinline, cdecl.} = # We use a jmp_buf buffer that is in the C stack. # Used to traverse the stack and registers assuming # that 'setjmp' will save registers in the C stack. @@ -543,7 +544,7 @@ else: # end of non-portable code # ---------------------------------------------------------------------------- -proc collectCTBody(gch: var TGcHeap) = +proc collectCTBody(gch: var GcHeap) = gch.stat.maxStackSize = max(gch.stat.maxStackSize, stackSize()) prepareForInteriorPointerChecking(gch.region) markStackAndRegisters(gch) @@ -558,7 +559,7 @@ proc collectCTBody(gch: var TGcHeap) = gch.stat.maxThreshold = max(gch.stat.maxThreshold, gch.cycleThreshold) sysAssert(allocInv(gch.region), "collectCT: end") -proc collectCT(gch: var TGcHeap) = +proc collectCT(gch: var GcHeap) = if getOccupiedMem(gch.region) >= gch.cycleThreshold and gch.recGcLock == 0: collectCTBody(gch) diff --git a/lib/system/jssys.nim b/lib/system/jssys.nim index 3b55f62ca..4a26e1e08 100644 --- a/lib/system/jssys.nim +++ b/lib/system/jssys.nim @@ -15,13 +15,13 @@ else: proc log*(s: cstring) {.importc: "console.log", varargs, nodecl.} type - PSafePoint = ptr TSafePoint - TSafePoint {.compilerproc, final.} = object + PSafePoint = ptr SafePoint + SafePoint {.compilerproc, final.} = object prev: PSafePoint # points to next safe point exc: ref Exception - PCallFrame = ptr TCallFrame - TCallFrame {.importc, nodecl, final.} = object + PCallFrame = ptr CallFrame + CallFrame {.importc, nodecl, final.} = object prev: PCallFrame procname: cstring line: int # current line number @@ -33,6 +33,7 @@ type lineNumber {.importc.}: int message {.importc.}: cstring stack {.importc.}: cstring +{.deprecated: [TSafePoint: SafePoint, TCallFrame: CallFrame].} var framePtr {.importc, nodecl, volatile.}: PCallFrame @@ -60,12 +61,13 @@ proc getCurrentExceptionMsg*(): string = proc auxWriteStackTrace(f: PCallFrame): string = type - TTempFrame = tuple[procname: cstring, line: int] + TempFrame = tuple[procname: cstring, line: int] + {.deprecated: [TTempFrame: TempFrame].} var it = f i = 0 total = 0 - tempFrames: array [0..63, TTempFrame] + tempFrames: array [0..63, TempFrame] while it != nil and i <= high(tempFrames): tempFrames[i].procname = it.procname tempFrames[i].line = it.line @@ -260,17 +262,17 @@ proc eqStrings(a, b: string): bool {.asmNoStackFrame, compilerProc.} = """ type - TDocument {.importc.} = object of RootObj + Document {.importc.} = object of RootObj write: proc (text: cstring) {.nimcall.} writeln: proc (text: cstring) {.nimcall.} - createAttribute: proc (identifier: cstring): ref TNode {.nimcall.} - createElement: proc (identifier: cstring): ref TNode {.nimcall.} - createTextNode: proc (identifier: cstring): ref TNode {.nimcall.} - getElementById: proc (id: cstring): ref TNode {.nimcall.} - getElementsByName: proc (name: cstring): seq[ref TNode] {.nimcall.} - getElementsByTagName: proc (name: cstring): seq[ref TNode] {.nimcall.} + createAttribute: proc (identifier: cstring): ref Node {.nimcall.} + createElement: proc (identifier: cstring): ref Node {.nimcall.} + createTextNode: proc (identifier: cstring): ref Node {.nimcall.} + getElementById: proc (id: cstring): ref Node {.nimcall.} + getElementsByName: proc (name: cstring): seq[ref Node] {.nimcall.} + getElementsByTagName: proc (name: cstring): seq[ref Node] {.nimcall.} - TNodeType* = enum + NodeType* = enum ElementNode = 1, AttributeNode, TextNode, @@ -283,35 +285,36 @@ type DocumentTypeNode, DocumentFragmentNode, NotationNode - TNode* {.importc.} = object of RootObj - attributes*: seq[ref TNode] - childNodes*: seq[ref TNode] + Node* {.importc.} = object of RootObj + attributes*: seq[ref Node] + childNodes*: seq[ref Node] data*: cstring - firstChild*: ref TNode - lastChild*: ref TNode - nextSibling*: ref TNode + firstChild*: ref Node + lastChild*: ref Node + nextSibling*: ref Node nodeName*: cstring - nodeType*: TNodeType + nodeType*: NodeType nodeValue*: cstring - parentNode*: ref TNode - previousSibling*: ref TNode - appendChild*: proc (child: ref TNode) {.nimcall.} + parentNode*: ref Node + previousSibling*: ref Node + appendChild*: proc (child: ref Node) {.nimcall.} appendData*: proc (data: cstring) {.nimcall.} cloneNode*: proc (copyContent: bool) {.nimcall.} deleteData*: proc (start, len: int) {.nimcall.} getAttribute*: proc (attr: cstring): cstring {.nimcall.} - getAttributeNode*: proc (attr: cstring): ref TNode {.nimcall.} - getElementsByTagName*: proc (): seq[ref TNode] {.nimcall.} + getAttributeNode*: proc (attr: cstring): ref Node {.nimcall.} + getElementsByTagName*: proc (): seq[ref Node] {.nimcall.} hasChildNodes*: proc (): bool {.nimcall.} - insertBefore*: proc (newNode, before: ref TNode) {.nimcall.} + insertBefore*: proc (newNode, before: ref Node) {.nimcall.} insertData*: proc (position: int, data: cstring) {.nimcall.} removeAttribute*: proc (attr: cstring) {.nimcall.} - removeAttributeNode*: proc (attr: ref TNode) {.nimcall.} - removeChild*: proc (child: ref TNode) {.nimcall.} - replaceChild*: proc (newNode, oldNode: ref TNode) {.nimcall.} + removeAttributeNode*: proc (attr: ref Node) {.nimcall.} + removeChild*: proc (child: ref Node) {.nimcall.} + replaceChild*: proc (newNode, oldNode: ref Node) {.nimcall.} replaceData*: proc (start, len: int, text: cstring) {.nimcall.} setAttribute*: proc (name, value: cstring) {.nimcall.} - setAttributeNode*: proc (attr: ref TNode) {.nimcall.} + setAttributeNode*: proc (attr: ref Node) {.nimcall.} +{.deprecated: [TNode: Node, TNodeType: NodeType, TDocument: Document].} when defined(kwin): proc rawEcho {.compilerproc, asmNoStackFrame.} = @@ -337,7 +340,7 @@ elif defined(nodejs): else: var - document {.importc, nodecl.}: ref TDocument + document {.importc, nodecl.}: ref Document proc ewriteln(x: cstring) = var node = document.getElementsByTagName("body")[0] diff --git a/lib/system/mmdisp.nim b/lib/system/mmdisp.nim index bdbb3a95a..86d834ceb 100644 --- a/lib/system/mmdisp.nim +++ b/lib/system/mmdisp.nim @@ -34,9 +34,10 @@ const type PPointer = ptr pointer - TByteArray = array[0..1000_0000, byte] - PByte = ptr TByteArray + ByteArray = array[0..1000_0000, byte] + PByte = ptr ByteArray PString = ptr string +{.deprecated: [TByteArray: ByteArray].} # Page size of the system; in most cases 4096 bytes. For exotic OS or # CPU this needs to be changed: @@ -180,16 +181,17 @@ when defined(boehmgc): dest[] = src type - TMemRegion = object {.final, pure.} + MemRegion = object {.final, pure.} + {.deprecated: [TMemRegion: MemRegion].} - proc alloc(r: var TMemRegion, size: int): pointer = + proc alloc(r: var MemRegion, size: int): pointer = result = boehmAlloc(size) if result == nil: raiseOutOfMem() - proc alloc0(r: var TMemRegion, size: int): pointer = + proc alloc0(r: var MemRegion, size: int): pointer = result = alloc(size) zeroMem(result, size) - proc dealloc(r: var TMemRegion, p: pointer) = boehmDealloc(p) - proc deallocOsPages(r: var TMemRegion) {.inline.} = discard + proc dealloc(r: var MemRegion, p: pointer) = boehmDealloc(p) + proc deallocOsPages(r: var MemRegion) {.inline.} = discard proc deallocOsPages() {.inline.} = discard include "system/cellsets" @@ -257,14 +259,15 @@ elif defined(nogc) and defined(useMalloc): dest[] = src type - TMemRegion = object {.final, pure.} + MemRegion = object {.final, pure.} + {.deprecated: [TMemRegion: MemRegion].} - proc alloc(r: var TMemRegion, size: int): pointer = + proc alloc(r: var MemRegion, size: int): pointer = result = alloc(size) - proc alloc0(r: var TMemRegion, size: int): pointer = + proc alloc0(r: var MemRegion, size: int): pointer = result = alloc0(size) - proc dealloc(r: var TMemRegion, p: pointer) = dealloc(p) - proc deallocOsPages(r: var TMemRegion) {.inline.} = discard + proc dealloc(r: var MemRegion, p: pointer) = dealloc(p) + proc deallocOsPages(r: var MemRegion) {.inline.} = discard proc deallocOsPages() {.inline.} = discard elif defined(nogc): @@ -313,7 +316,7 @@ elif defined(nogc): proc asgnRefNoCycle(dest: PPointer, src: pointer) {.compilerproc, inline.} = dest[] = src - var allocator {.rtlThreadVar.}: TMemRegion + var allocator {.rtlThreadVar.}: MemRegion instantiateForRegion(allocator) include "system/cellsets" @@ -323,7 +326,7 @@ else: include "system/cellsets" when not leakDetector: - sysAssert(sizeof(TCell) == sizeof(TFreeCell), "sizeof TFreeCell") + sysAssert(sizeof(Cell) == sizeof(FreeCell), "sizeof FreeCell") when compileOption("gc", "v2"): include "system/gc2" elif defined(gcMarkAndSweep): diff --git a/lib/system/profiler.nim b/lib/system/profiler.nim index 6d6863caa..c93456fb3 100644 --- a/lib/system/profiler.nim +++ b/lib/system/profiler.nim @@ -19,10 +19,11 @@ const MaxTraceLen = 20 # tracking the last 20 calls is enough type - TStackTrace* = array [0..MaxTraceLen-1, cstring] - TProfilerHook* = proc (st: TStackTrace) {.nimcall.} + StackTrace* = array [0..MaxTraceLen-1, cstring] + ProfilerHook* = proc (st: StackTrace) {.nimcall.} +{.deprecated: [TStackTrace: StackTrace, TProfilerHook: ProfilerHook].} -proc captureStackTrace(f: PFrame, st: var TStackTrace) = +proc captureStackTrace(f: PFrame, st: var StackTrace) = const firstCalls = 5 var @@ -51,14 +52,15 @@ proc captureStackTrace(f: PFrame, st: var TStackTrace) = when defined(memProfiler): type - TMemProfilerHook* = proc (st: TStackTrace, requestedSize: int) {.nimcall, benign.} + MemProfilerHook* = proc (st: StackTrace, requestedSize: int) {.nimcall, benign.} + {.deprecated: [TMemProfilerHook: MemProfilerHook].} var - profilerHook*: TMemProfilerHook + profilerHook*: MemProfilerHook ## set this variable to provide a procedure that implements a profiler in ## user space. See the `nimprof` module for a reference implementation. - proc callProfilerHook(hook: TMemProfilerHook, requestedSize: int) = - var st: TStackTrace + proc callProfilerHook(hook: MemProfilerHook, requestedSize: int) = + var st: StackTrace captureStackTrace(framePtr, st) hook(st, requestedSize) @@ -70,15 +72,15 @@ else: SamplingInterval = 50_000 # set this to change the default sampling interval var - profilerHook*: TProfilerHook + profilerHook*: ProfilerHook ## set this variable to provide a procedure that implements a profiler in ## user space. See the `nimprof` module for a reference implementation. gTicker {.threadvar.}: int - proc callProfilerHook(hook: TProfilerHook) {.noinline.} = + proc callProfilerHook(hook: ProfilerHook) {.noinline.} = # 'noinline' so that 'nimProfile' does not perform the stack allocation # in the common case. - var st: TStackTrace + var st: StackTrace captureStackTrace(framePtr, st) hook(st) diff --git a/lib/system/repr.nim b/lib/system/repr.nim index f1029ff6a..f3b69954a 100644 --- a/lib/system/repr.nim +++ b/lib/system/repr.nim @@ -121,38 +121,39 @@ proc reprSet(p: pointer, typ: PNimType): string {.compilerRtl.} = reprSetAux(result, p, typ) type - TReprClosure {.final.} = object # we cannot use a global variable here + ReprClosure {.final.} = object # we cannot use a global variable here # as this wouldn't be thread-safe - when declared(TCellSet): - marked: TCellSet + when declared(CellSet): + marked: CellSet recdepth: int # do not recurse endlessly indent: int # indentation +{.deprecated: [TReprClosure: ReprClosure].} when not defined(useNimRtl): - proc initReprClosure(cl: var TReprClosure) = + proc initReprClosure(cl: var ReprClosure) = # Important: cellsets does not lock the heap when doing allocations! We # have to do it here ... when hasThreadSupport and hasSharedHeap and declared(heapLock): AcquireSys(HeapLock) - when declared(TCellSet): + when declared(CellSet): init(cl.marked) cl.recdepth = -1 # default is to display everything! cl.indent = 0 - proc deinitReprClosure(cl: var TReprClosure) = - when declared(TCellSet): deinit(cl.marked) + proc deinitReprClosure(cl: var ReprClosure) = + when declared(CellSet): deinit(cl.marked) when hasThreadSupport and hasSharedHeap and declared(heapLock): ReleaseSys(HeapLock) - proc reprBreak(result: var string, cl: TReprClosure) = + proc reprBreak(result: var string, cl: ReprClosure) = add result, "\n" for i in 0..cl.indent-1: add result, ' ' proc reprAux(result: var string, p: pointer, typ: PNimType, - cl: var TReprClosure) {.benign.} + cl: var ReprClosure) {.benign.} proc reprArray(result: var string, p: pointer, typ: PNimType, - cl: var TReprClosure) = + cl: var ReprClosure) = add result, "[" var bs = typ.base.size for i in 0..typ.size div bs - 1: @@ -161,7 +162,7 @@ when not defined(useNimRtl): add result, "]" proc reprSequence(result: var string, p: pointer, typ: PNimType, - cl: var TReprClosure) = + cl: var ReprClosure) = if p == nil: add result, "nil" return @@ -174,7 +175,7 @@ when not defined(useNimRtl): add result, "]" proc reprRecordAux(result: var string, p: pointer, n: ptr TNimNode, - cl: var TReprClosure) {.benign.} = + cl: var ReprClosure) {.benign.} = case n.kind of nkNone: sysAssert(false, "reprRecordAux") of nkSlot: @@ -191,7 +192,7 @@ when not defined(useNimRtl): if m != nil: reprRecordAux(result, p, m, cl) proc reprRecord(result: var string, p: pointer, typ: PNimType, - cl: var TReprClosure) = + cl: var ReprClosure) = add result, "[" let oldLen = result.len reprRecordAux(result, p, typ.node, cl) @@ -201,9 +202,9 @@ when not defined(useNimRtl): add result, "]" proc reprRef(result: var string, p: pointer, typ: PNimType, - cl: var TReprClosure) = + cl: var ReprClosure) = # we know that p is not nil here: - when declared(TCellSet): + when declared(CellSet): when defined(boehmGC) or defined(nogc): var cell = cast[PCell](p) else: @@ -216,7 +217,7 @@ when not defined(useNimRtl): reprAux(result, p, typ.base, cl) proc reprAux(result: var string, p: pointer, typ: PNimType, - cl: var TReprClosure) = + cl: var ReprClosure) = if cl.recdepth == 0: add result, "..." return @@ -261,7 +262,7 @@ when not defined(useNimRtl): proc reprOpenArray(p: pointer, length: int, elemtyp: PNimType): string {. compilerRtl.} = var - cl: TReprClosure + cl: ReprClosure initReprClosure(cl) result = "[" var bs = elemtyp.size @@ -274,7 +275,7 @@ proc reprOpenArray(p: pointer, length: int, elemtyp: PNimType): string {. when not defined(useNimRtl): proc reprAny(p: pointer, typ: PNimType): string = var - cl: TReprClosure + cl: ReprClosure initReprClosure(cl) result = "" if typ.kind in {tyObject, tyTuple, tyArray, tyArrayConstr, tySet}: diff --git a/lib/system/sets.nim b/lib/system/sets.nim index 626d43c33..22d6d57c0 100644 --- a/lib/system/sets.nim +++ b/lib/system/sets.nim @@ -10,7 +10,8 @@ # set handling type - TNimSet = array [0..4*2048-1, uint8] + NimSet = array [0..4*2048-1, uint8] +{.deprecated: [TNimSet: NimSet].} proc countBits32(n: int32): int {.compilerproc.} = var v = n @@ -22,7 +23,7 @@ proc countBits64(n: int64): int {.compilerproc.} = result = countBits32(toU32(n and 0xffff'i64)) + countBits32(toU32(n shr 16'i64)) -proc cardSet(s: TNimSet, len: int): int {.compilerproc.} = +proc cardSet(s: NimSet, len: int): int {.compilerproc.} = result = 0 for i in countup(0, len-1): inc(result, countBits32(int32(s[i]))) diff --git a/lib/system/syslocks.nim b/lib/system/syslocks.nim index 8b38f34f3..ec8c26275 100644 --- a/lib/system/syslocks.nim +++ b/lib/system/syslocks.nim @@ -11,8 +11,8 @@ when defined(Windows): type - THandle = int - TSysLock {.final, pure.} = object # CRITICAL_SECTION in WinApi + Handle = int + SysLock {.final, pure.} = object # CRITICAL_SECTION in WinApi DebugInfo: pointer LockCount: int32 RecursionCount: int32 @@ -20,85 +20,87 @@ when defined(Windows): LockSemaphore: int Reserved: int32 - TSysCond = THandle + SysCond = Handle + + {.deprecated: [THandle: Handle, TSysLock: SysLock, TSysCond: SysCond].} - proc initSysLock(L: var TSysLock) {.stdcall, noSideEffect, + proc initSysLock(L: var SysLock) {.stdcall, noSideEffect, dynlib: "kernel32", importc: "InitializeCriticalSection".} ## Initializes the lock `L`. - proc tryAcquireSysAux(L: var TSysLock): int32 {.stdcall, noSideEffect, + proc tryAcquireSysAux(L: var SysLock): int32 {.stdcall, noSideEffect, dynlib: "kernel32", importc: "TryEnterCriticalSection".} ## Tries to acquire the lock `L`. - proc tryAcquireSys(L: var TSysLock): bool {.inline.} = + proc tryAcquireSys(L: var SysLock): bool {.inline.} = result = tryAcquireSysAux(L) != 0'i32 - proc acquireSys(L: var TSysLock) {.stdcall, noSideEffect, + proc acquireSys(L: var SysLock) {.stdcall, noSideEffect, dynlib: "kernel32", importc: "EnterCriticalSection".} ## Acquires the lock `L`. - proc releaseSys(L: var TSysLock) {.stdcall, noSideEffect, + proc releaseSys(L: var SysLock) {.stdcall, noSideEffect, dynlib: "kernel32", importc: "LeaveCriticalSection".} ## Releases the lock `L`. - proc deinitSys(L: var TSysLock) {.stdcall, noSideEffect, + proc deinitSys(L: var SysLock) {.stdcall, noSideEffect, dynlib: "kernel32", importc: "DeleteCriticalSection".} proc createEvent(lpEventAttributes: pointer, bManualReset, bInitialState: int32, - lpName: cstring): TSysCond {.stdcall, noSideEffect, + lpName: cstring): SysCond {.stdcall, noSideEffect, dynlib: "kernel32", importc: "CreateEventA".} - proc closeHandle(hObject: THandle) {.stdcall, noSideEffect, + proc closeHandle(hObject: Handle) {.stdcall, noSideEffect, dynlib: "kernel32", importc: "CloseHandle".} - proc waitForSingleObject(hHandle: THandle, dwMilliseconds: int32): int32 {. + proc waitForSingleObject(hHandle: Handle, dwMilliseconds: int32): int32 {. stdcall, dynlib: "kernel32", importc: "WaitForSingleObject", noSideEffect.} - proc signalSysCond(hEvent: TSysCond) {.stdcall, noSideEffect, + proc signalSysCond(hEvent: SysCond) {.stdcall, noSideEffect, dynlib: "kernel32", importc: "SetEvent".} - proc initSysCond(cond: var TSysCond) {.inline.} = + proc initSysCond(cond: var SysCond) {.inline.} = cond = createEvent(nil, 0'i32, 0'i32, nil) - proc deinitSysCond(cond: var TSysCond) {.inline.} = + proc deinitSysCond(cond: var SysCond) {.inline.} = closeHandle(cond) - proc waitSysCond(cond: var TSysCond, lock: var TSysLock) = + proc waitSysCond(cond: var SysCond, lock: var SysLock) = releaseSys(lock) discard waitForSingleObject(cond, -1'i32) acquireSys(lock) - proc waitSysCondWindows(cond: var TSysCond) = + proc waitSysCondWindows(cond: var SysCond) = discard waitForSingleObject(cond, -1'i32) else: type - TSysLock {.importc: "pthread_mutex_t", pure, final, + SysLock {.importc: "pthread_mutex_t", pure, final, header: "".} = object - TSysCond {.importc: "pthread_cond_t", pure, final, + SysCond {.importc: "pthread_cond_t", pure, final, header: "".} = object - proc initSysLock(L: var TSysLock, attr: pointer = nil) {. + proc initSysLock(L: var SysLock, attr: pointer = nil) {. importc: "pthread_mutex_init", header: "", noSideEffect.} - proc acquireSys(L: var TSysLock) {.noSideEffect, + proc acquireSys(L: var SysLock) {.noSideEffect, importc: "pthread_mutex_lock", header: "".} - proc tryAcquireSysAux(L: var TSysLock): cint {.noSideEffect, + proc tryAcquireSysAux(L: var SysLock): cint {.noSideEffect, importc: "pthread_mutex_trylock", header: "".} - proc tryAcquireSys(L: var TSysLock): bool {.inline.} = + proc tryAcquireSys(L: var SysLock): bool {.inline.} = result = tryAcquireSysAux(L) == 0'i32 - proc releaseSys(L: var TSysLock) {.noSideEffect, + proc releaseSys(L: var SysLock) {.noSideEffect, importc: "pthread_mutex_unlock", header: "".} - proc deinitSys(L: var TSysLock) {.noSideEffect, + proc deinitSys(L: var SysLock) {.noSideEffect, importc: "pthread_mutex_destroy", header: "".} - proc initSysCond(cond: var TSysCond, cond_attr: pointer = nil) {. + proc initSysCond(cond: var SysCond, cond_attr: pointer = nil) {. importc: "pthread_cond_init", header: "", noSideEffect.} - proc waitSysCond(cond: var TSysCond, lock: var TSysLock) {. + proc waitSysCond(cond: var SysCond, lock: var SysLock) {. importc: "pthread_cond_wait", header: "", noSideEffect.} - proc signalSysCond(cond: var TSysCond) {. + proc signalSysCond(cond: var SysCond) {. importc: "pthread_cond_signal", header: "", noSideEffect.} - proc deinitSysCond(cond: var TSysCond) {.noSideEffect, + proc deinitSysCond(cond: var SysCond) {.noSideEffect, importc: "pthread_cond_destroy", header: "".} diff --git a/lib/system/sysspawn.nim b/lib/system/sysspawn.nim index 6f45f1509..5f8f2b2c5 100644 --- a/lib/system/sysspawn.nim +++ b/lib/system/sysspawn.nim @@ -19,9 +19,9 @@ when not declared(NimString): type CondVar = object - c: TSysCond + c: SysCond when defined(posix): - stupidLock: TSysLock + stupidLock: SysLock counter: int proc createCondVar(): CondVar = diff --git a/lib/system/threads.nim b/lib/system/threads.nim index d8e011ecb..865271a50 100644 --- a/lib/system/threads.nim +++ b/lib/system/threads.nim @@ -24,8 +24,8 @@ ## import locks ## ## var -## thr: array [0..4, TThread[tuple[a,b: int]]] -## L: TLock +## thr: array [0..4, Thread[tuple[a,b: int]]] +## L: Lock ## ## proc threadFunc(interval: tuple[a,b: int]) {.thread.} = ## for i in interval.a..interval.b: @@ -51,40 +51,41 @@ const when defined(windows): type - TSysThread = THandle - TWinThreadProc = proc (x: pointer): int32 {.stdcall.} + SysThread = Handle + WinThreadProc = proc (x: pointer): int32 {.stdcall.} + {.deprecated: [TSysThread: SysThread, TWinThreadProc: WinThreadProc].} proc createThread(lpThreadAttributes: pointer, dwStackSize: int32, - lpStartAddress: TWinThreadProc, + lpStartAddress: WinThreadProc, lpParameter: pointer, dwCreationFlags: int32, - lpThreadId: var int32): TSysThread {. + lpThreadId: var int32): SysThread {. stdcall, dynlib: "kernel32", importc: "CreateThread".} - proc winSuspendThread(hThread: TSysThread): int32 {. + proc winSuspendThread(hThread: SysThread): int32 {. stdcall, dynlib: "kernel32", importc: "SuspendThread".} - proc winResumeThread(hThread: TSysThread): int32 {. + proc winResumeThread(hThread: SysThread): int32 {. stdcall, dynlib: "kernel32", importc: "ResumeThread".} proc waitForMultipleObjects(nCount: int32, - lpHandles: ptr TSysThread, + lpHandles: ptr SysThread, bWaitAll: int32, dwMilliseconds: int32): int32 {. stdcall, dynlib: "kernel32", importc: "WaitForMultipleObjects".} - proc terminateThread(hThread: TSysThread, dwExitCode: int32): int32 {. + proc terminateThread(hThread: SysThread, dwExitCode: int32): int32 {. stdcall, dynlib: "kernel32", importc: "TerminateThread".} type - TThreadVarSlot = distinct int32 + ThreadVarSlot = distinct int32 when true: - proc threadVarAlloc(): TThreadVarSlot {. + proc threadVarAlloc(): ThreadVarSlot {. importc: "TlsAlloc", stdcall, header: "".} - proc threadVarSetValue(dwTlsIndex: TThreadVarSlot, lpTlsValue: pointer) {. + proc threadVarSetValue(dwTlsIndex: ThreadVarSlot, lpTlsValue: pointer) {. importc: "TlsSetValue", stdcall, header: "".} - proc tlsGetValue(dwTlsIndex: TThreadVarSlot): pointer {. + proc tlsGetValue(dwTlsIndex: ThreadVarSlot): pointer {. importc: "TlsGetValue", stdcall, header: "".} proc getLastError(): uint32 {. @@ -92,16 +93,16 @@ when defined(windows): proc setLastError(x: uint32) {. importc: "SetLastError", stdcall, header: "".} - proc threadVarGetValue(dwTlsIndex: TThreadVarSlot): pointer = + proc threadVarGetValue(dwTlsIndex: ThreadVarSlot): pointer = let realLastError = getLastError() result = tlsGetValue(dwTlsIndex) setLastError(realLastError) else: - proc threadVarAlloc(): TThreadVarSlot {. + proc threadVarAlloc(): ThreadVarSlot {. importc: "TlsAlloc", stdcall, dynlib: "kernel32".} - proc threadVarSetValue(dwTlsIndex: TThreadVarSlot, lpTlsValue: pointer) {. + proc threadVarSetValue(dwTlsIndex: ThreadVarSlot, lpTlsValue: pointer) {. importc: "TlsSetValue", stdcall, dynlib: "kernel32".} - proc threadVarGetValue(dwTlsIndex: TThreadVarSlot): pointer {. + proc threadVarGetValue(dwTlsIndex: ThreadVarSlot): pointer {. importc: "TlsGetValue", stdcall, dynlib: "kernel32".} else: @@ -111,55 +112,58 @@ else: {.passC: "-pthread".} type - TSysThread {.importc: "pthread_t", header: "", + SysThread {.importc: "pthread_t", header: "", final, pure.} = object - Tpthread_attr {.importc: "pthread_attr_t", + Pthread_attr {.importc: "pthread_attr_t", header: "", final, pure.} = object - Ttimespec {.importc: "struct timespec", + Timespec {.importc: "struct timespec", header: "", final, pure.} = object tv_sec: int tv_nsec: int + {.deprecated: [TSysThread: SysThread, Tpthread_attr: PThreadAttr, + Ttimespec: Timespec].} - proc pthread_attr_init(a1: var TPthread_attr) {. + proc pthread_attr_init(a1: var PthreadAttr) {. importc, header: "".} - proc pthread_attr_setstacksize(a1: var TPthread_attr, a2: int) {. + proc pthread_attr_setstacksize(a1: var PthreadAttr, a2: int) {. importc, header: "".} - proc pthread_create(a1: var TSysThread, a2: var TPthread_attr, + proc pthread_create(a1: var SysThread, a2: var PthreadAttr, a3: proc (x: pointer): pointer {.noconv.}, a4: pointer): cint {.importc: "pthread_create", header: "".} - proc pthread_join(a1: TSysThread, a2: ptr pointer): cint {. + proc pthread_join(a1: SysThread, a2: ptr pointer): cint {. importc, header: "".} - proc pthread_cancel(a1: TSysThread): cint {. + proc pthread_cancel(a1: SysThread): cint {. importc: "pthread_cancel", header: "".} type - TThreadVarSlot {.importc: "pthread_key_t", pure, final, + ThreadVarSlot {.importc: "pthread_key_t", pure, final, header: "".} = object + {.deprecated: [TThreadVarSlot: ThreadVarSlot].} - proc pthread_getspecific(a1: TThreadVarSlot): pointer {. + proc pthread_getspecific(a1: ThreadVarSlot): pointer {. importc: "pthread_getspecific", header: "".} - proc pthread_key_create(a1: ptr TThreadVarSlot, + proc pthread_key_create(a1: ptr ThreadVarSlot, destruct: proc (x: pointer) {.noconv.}): int32 {. importc: "pthread_key_create", header: "".} - proc pthread_key_delete(a1: TThreadVarSlot): int32 {. + proc pthread_key_delete(a1: ThreadVarSlot): int32 {. importc: "pthread_key_delete", header: "".} - proc pthread_setspecific(a1: TThreadVarSlot, a2: pointer): int32 {. + proc pthread_setspecific(a1: ThreadVarSlot, a2: pointer): int32 {. importc: "pthread_setspecific", header: "".} - proc threadVarAlloc(): TThreadVarSlot {.inline.} = + proc threadVarAlloc(): ThreadVarSlot {.inline.} = discard pthread_key_create(addr(result), nil) - proc threadVarSetValue(s: TThreadVarSlot, value: pointer) {.inline.} = + proc threadVarSetValue(s: ThreadVarSlot, value: pointer) {.inline.} = discard pthread_setspecific(s, value) - proc threadVarGetValue(s: TThreadVarSlot): pointer {.inline.} = + proc threadVarGetValue(s: ThreadVarSlot): pointer {.inline.} = result = pthread_getspecific(s) when useStackMaskHack: - proc pthread_attr_setstack(attr: var TPthread_attr, stackaddr: pointer, + proc pthread_attr_setstack(attr: var PthreadAttr, stackaddr: pointer, size: int): cint {. importc: "pthread_attr_setstack", header: "".} @@ -175,13 +179,13 @@ when emulatedThreadVars: # allocations are needed. Currently less than 7K are used on a 64bit machine. # We use ``float`` for proper alignment: type - TThreadLocalStorage = array [0..1_000, float] + ThreadLocalStorage = array [0..1_000, float] - PGcThread = ptr TGcThread - TGcThread {.pure, inheritable.} = object - sys: TSysThread + PGcThread = ptr GcThread + GcThread {.pure, inheritable.} = object + sys: SysThread when emulatedThreadVars and not useStackMaskHack: - tls: TThreadLocalStorage + tls: ThreadLocalStorage else: nil when hasSharedHeap: @@ -190,15 +194,16 @@ type stackSize: int else: nil +{.deprecated: [TThreadLocalStorage: ThreadLocalStorage, TGcThread: GcThread].} # XXX it'd be more efficient to not use a global variable for the # thread storage slot, but to rely on the implementation to assign slot X # for us... ;-) -var globalsSlot: TThreadVarSlot +var globalsSlot: ThreadVarSlot when not defined(useNimRtl): when not useStackMaskHack: - var mainThread: TGcThread + var mainThread: GcThread proc initThreadVarsEmulation() {.compilerProc, inline.} = when not defined(useNimRtl): @@ -206,7 +211,7 @@ proc initThreadVarsEmulation() {.compilerProc, inline.} = when declared(mainThread): threadVarSetValue(globalsSlot, addr(mainThread)) -#const globalsSlot = TThreadVarSlot(0) +#const globalsSlot = ThreadVarSlot(0) #sysAssert checkSlot.int == globalsSlot.int when emulatedThreadVars: @@ -228,7 +233,7 @@ when not defined(useNimRtl): initGC() when emulatedThreadVars: - if nimThreadVarsSize() > sizeof(TThreadLocalStorage): + if nimThreadVarsSize() > sizeof(ThreadLocalStorage): echo "too large thread local storage size requested" quit 1 @@ -269,26 +274,27 @@ when not defined(useNimRtl): # use ``stdcall`` since it is mapped to ``noconv`` on UNIX anyway. type - TThread* {.pure, final.}[TArg] = - object of TGcThread ## Nim thread. A thread is a heavy object (~14K) + Thread* {.pure, final.}[TArg] = + object of GcThread ## Nim thread. A thread is a heavy object (~14K) ## that **must not** be part of a message! Use - ## a ``TThreadId`` for that. + ## a ``ThreadId`` for that. when TArg is void: dataFn: proc () {.nimcall, gcsafe.} else: dataFn: proc (m: TArg) {.nimcall, gcsafe.} data: TArg - TThreadId*[TArg] = ptr TThread[TArg] ## the current implementation uses + ThreadId*[TArg] = ptr Thread[TArg] ## the current implementation uses ## a pointer as a thread ID. +{.deprecated: [TThread: Thread, TThreadId: ThreadId].} when not defined(boehmgc) and not hasSharedHeap: proc deallocOsPages() template threadProcWrapperBody(closure: expr) {.immediate.} = when declared(globalsSlot): threadVarSetValue(globalsSlot, closure) - var t = cast[ptr TThread[TArg]](closure) + var t = cast[ptr Thread[TArg]](closure) when useStackMaskHack: - var tls: TThreadLocalStorage + var tls: ThreadLocalStorage when not defined(boehmgc) and not defined(nogc) and not hasSharedHeap: # init the GC for this thread: setStackBottom(addr(t)) @@ -319,35 +325,35 @@ else: threadProcWrapperBody(closure) {.pop.} -proc running*[TArg](t: TThread[TArg]): bool {.inline.} = +proc running*[TArg](t: Thread[TArg]): bool {.inline.} = ## returns true if `t` is running. result = t.dataFn != nil when hostOS == "windows": - proc joinThread*[TArg](t: TThread[TArg]) {.inline.} = + proc joinThread*[TArg](t: Thread[TArg]) {.inline.} = ## waits for the thread `t` to finish. discard waitForSingleObject(t.sys, -1'i32) - proc joinThreads*[TArg](t: varargs[TThread[TArg]]) = + proc joinThreads*[TArg](t: varargs[Thread[TArg]]) = ## waits for every thread in `t` to finish. - var a: array[0..255, TSysThread] + var a: array[0..255, SysThread] sysAssert a.len >= t.len, "a.len >= t.len" for i in 0..t.high: a[i] = t[i].sys discard waitForMultipleObjects(t.len.int32, - cast[ptr TSysThread](addr(a)), 1, -1) + cast[ptr SysThread](addr(a)), 1, -1) else: - proc joinThread*[TArg](t: TThread[TArg]) {.inline.} = + proc joinThread*[TArg](t: Thread[TArg]) {.inline.} = ## waits for the thread `t` to finish. discard pthread_join(t.sys, nil) - proc joinThreads*[TArg](t: varargs[TThread[TArg]]) = + proc joinThreads*[TArg](t: varargs[Thread[TArg]]) = ## waits for every thread in `t` to finish. for i in 0..t.high: joinThread(t[i]) when false: # XXX a thread should really release its heap here somehow: - proc destroyThread*[TArg](t: var TThread[TArg]) = + proc destroyThread*[TArg](t: var Thread[TArg]) = ## forces the thread `t` to terminate. This is potentially dangerous if ## you don't have full control over `t` and its acquired resources. when hostOS == "windows": @@ -358,7 +364,7 @@ when false: t.dataFn = nil when hostOS == "windows": - proc createThread*[TArg](t: var TThread[TArg], + proc createThread*[TArg](t: var Thread[TArg], tp: proc (arg: TArg) {.thread.}, param: TArg) = ## creates a new thread `t` and starts its execution. Entry point is the @@ -373,7 +379,7 @@ when hostOS == "windows": if t.sys <= 0: raise newException(ResourceExhaustedError, "cannot create thread") else: - proc createThread*[TArg](t: var TThread[TArg], + proc createThread*[TArg](t: var Thread[TArg], tp: proc (arg: TArg) {.thread.}, param: TArg) = ## creates a new thread `t` and starts its execution. Entry point is the @@ -382,29 +388,29 @@ else: when TArg isnot void: t.data = param t.dataFn = tp when hasSharedHeap: t.stackSize = ThreadStackSize - var a {.noinit.}: Tpthread_attr + var a {.noinit.}: PthreadAttr pthread_attr_init(a) pthread_attr_setstacksize(a, ThreadStackSize) if pthread_create(t.sys, a, threadProcWrapper[TArg], addr(t)) != 0: raise newException(ResourceExhaustedError, "cannot create thread") -proc threadId*[TArg](t: var TThread[TArg]): TThreadId[TArg] {.inline.} = +proc threadId*[TArg](t: var Thread[TArg]): ThreadId[TArg] {.inline.} = ## returns the thread ID of `t`. result = addr(t) -proc myThreadId*[TArg](): TThreadId[TArg] = +proc myThreadId*[TArg](): ThreadId[TArg] = ## returns the thread ID of the thread that calls this proc. This is unsafe ## because the type ``TArg`` is not checked for consistency! - result = cast[TThreadId[TArg]](threadVarGetValue(globalsSlot)) + result = cast[ThreadId[TArg]](threadVarGetValue(globalsSlot)) when false: - proc mainThreadId*[TArg](): TThreadId[TArg] = + proc mainThreadId*[TArg](): ThreadId[TArg] = ## returns the thread ID of the main thread. - result = cast[TThreadId[TArg]](addr(mainThread)) + result = cast[ThreadId[TArg]](addr(mainThread)) when useStackMaskHack: proc runMain(tp: proc () {.thread.}) {.compilerproc.} = - var mainThread: TThread[pointer] + var mainThread: Thread[pointer] createThread(mainThread, tp) joinThread(mainThread) diff --git a/lib/system/timers.nim b/lib/system/timers.nim index e5de791ac..74748c541 100644 --- a/lib/system/timers.nim +++ b/lib/system/timers.nim @@ -11,83 +11,86 @@ ## ``_ type - TTicks = distinct int64 - TNanos = int64 + Ticks = distinct int64 + Nanos = int64 +{.deprecated: [TTicks: Ticks, TNanos: Nanos].} when defined(windows): - proc QueryPerformanceCounter(res: var TTicks) {. + proc QueryPerformanceCounter(res: var Ticks) {. importc: "QueryPerformanceCounter", stdcall, dynlib: "kernel32".} proc QueryPerformanceFrequency(res: var int64) {. importc: "QueryPerformanceFrequency", stdcall, dynlib: "kernel32".} - proc getTicks(): TTicks {.inline.} = + proc getTicks(): Ticks {.inline.} = QueryPerformanceCounter(result) - proc `-`(a, b: TTicks): TNanos = + proc `-`(a, b: Ticks): Nanos = var frequency: int64 QueryPerformanceFrequency(frequency) var performanceCounterRate = 1e+9'f64 / float64(frequency) - result = TNanos(float64(a.int64 - b.int64) * performanceCounterRate) + result = Nanos(float64(a.int64 - b.int64) * performanceCounterRate) elif defined(macosx): type - TMachTimebaseInfoData {.pure, final, + MachTimebaseInfoData {.pure, final, importc: "mach_timebase_info_data_t", header: "".} = object numer, denom: int32 + {.deprecated: [TMachTimebaseInfoData: MachTimebaseInfoData].} proc mach_absolute_time(): int64 {.importc, header: "".} - proc mach_timebase_info(info: var TMachTimebaseInfoData) {.importc, + proc mach_timebase_info(info: var MachTimebaseInfoData) {.importc, header: "".} - proc getTicks(): TTicks {.inline.} = - result = TTicks(mach_absolute_time()) + proc getTicks(): Ticks {.inline.} = + result = Ticks(mach_absolute_time()) - var timeBaseInfo: TMachTimebaseInfoData + var timeBaseInfo: MachTimebaseInfoData mach_timebase_info(timeBaseInfo) - proc `-`(a, b: TTicks): TNanos = + proc `-`(a, b: Ticks): Nanos = result = (a.int64 - b.int64) * timeBaseInfo.numer div timeBaseInfo.denom elif defined(posixRealtime): type - TClockid {.importc: "clockid_t", header: "", final.} = object + Clockid {.importc: "clockid_t", header: "", final.} = object - TTimeSpec {.importc: "struct timespec", header: "", + TimeSpec {.importc: "struct timespec", header: "", final, pure.} = object ## struct timespec tv_sec: int ## Seconds. tv_nsec: int ## Nanoseconds. + {.deprecated: [TClockid: Clickid, TTimeSpec: TimeSpec].} var - CLOCK_REALTIME {.importc: "CLOCK_REALTIME", header: "".}: TClockid + CLOCK_REALTIME {.importc: "CLOCK_REALTIME", header: "".}: Clockid - proc clock_gettime(clkId: TClockid, tp: var TTimespec) {. + proc clock_gettime(clkId: Clockid, tp: var Timespec) {. importc: "clock_gettime", header: "".} - proc getTicks(): TTicks = - var t: TTimespec + proc getTicks(): Ticks = + var t: Timespec clock_gettime(CLOCK_REALTIME, t) - result = TTicks(int64(t.tv_sec) * 1000000000'i64 + int64(t.tv_nsec)) + result = Ticks(int64(t.tv_sec) * 1000000000'i64 + int64(t.tv_nsec)) - proc `-`(a, b: TTicks): TNanos {.borrow.} + proc `-`(a, b: Ticks): Nanos {.borrow.} else: # fallback Posix implementation: type - Ttimeval {.importc: "struct timeval", header: "", + Timeval {.importc: "struct timeval", header: "", final, pure.} = object ## struct timeval tv_sec: int ## Seconds. tv_usec: int ## Microseconds. - - proc posix_gettimeofday(tp: var Ttimeval, unused: pointer = nil) {. + {.deprecated: [Ttimeval: Timeval].} + proc posix_gettimeofday(tp: var Timeval, unused: pointer = nil) {. importc: "gettimeofday", header: "".} - proc getTicks(): TTicks = - var t: Ttimeval + proc getTicks(): Ticks = + var t: Timeval posix_gettimeofday(t) - result = TTicks(int64(t.tv_sec) * 1000_000_000'i64 + + result = Ticks(int64(t.tv_sec) * 1000_000_000'i64 + int64(t.tv_usec) * 1000'i64) - proc `-`(a, b: TTicks): TNanos {.borrow.} + proc `-`(a, b: Ticks): Nanos {.borrow.} diff --git a/lib/system/widestrs.nim b/lib/system/widestrs.nim index 1e8bc6791..e7b7f3972 100644 --- a/lib/system/widestrs.nim +++ b/lib/system/widestrs.nim @@ -14,8 +14,9 @@ when not declared(NimString): {.error: "You must not import this module explicitly".} type - TUtf16Char* = distinct int16 - WideCString* = ref array[0.. 1_000_000, TUtf16Char] + Utf16Char* = distinct int16 + WideCString* = ref array[0.. 1_000_000, Utf16Char] +{.deprecated: [TUtf16Char: Utf16Char].} proc len*(w: WideCString): int = ## returns the length of a widestring. This traverses the whole string to @@ -23,7 +24,7 @@ proc len*(w: WideCString): int = while int16(w[result]) != 0'i16: inc result const - UNI_REPLACEMENT_CHAR = TUtf16Char(0xFFFD'i16) + UNI_REPLACEMENT_CHAR = Utf16Char(0xFFFD'i16) UNI_MAX_BMP = 0x0000FFFF UNI_MAX_UTF16 = 0x0010FFFF UNI_MAX_UTF32 = 0x7FFFFFFF @@ -89,16 +90,16 @@ proc newWideCString*(source: cstring, L: int): WideCString = if ch >=% UNI_SUR_HIGH_START and ch <=% UNI_SUR_LOW_END: result[d] = UNI_REPLACEMENT_CHAR else: - result[d] = TUtf16Char(toU16(ch)) + result[d] = Utf16Char(toU16(ch)) elif ch >% UNI_MAX_UTF16: result[d] = UNI_REPLACEMENT_CHAR else: let ch = ch -% halfBase - result[d] = TUtf16Char(toU16((ch shr halfShift) +% UNI_SUR_HIGH_START)) + result[d] = Utf16Char(toU16((ch shr halfShift) +% UNI_SUR_HIGH_START)) inc d - result[d] = TUtf16Char(toU16((ch and halfMask) +% UNI_SUR_LOW_START)) + result[d] = Utf16Char(toU16((ch and halfMask) +% UNI_SUR_LOW_START)) inc d - result[d] = TUtf16Char(0'i16) + result[d] = Utf16Char(0'i16) proc newWideCString*(s: cstring): WideCString = if s.isNil: return nil From 9e771ca707207bbcafc8359fa2ce8a2780adc399 Mon Sep 17 00:00:00 2001 From: pdw Date: Sun, 24 May 2015 22:38:43 -0500 Subject: [PATCH 0355/1263] lib/windows - Dropped 'T' from types --- lib/windows/mmsystem.nim | 46 +- lib/windows/nb30.nim | 44 +- lib/windows/shellapi.nim | 72 +- lib/windows/shfolder.nim | 18 +- lib/windows/windows.nim | 1766 ++++++++++++++------------------------ lib/windows/winlean.nim | 199 ++--- 6 files changed, 847 insertions(+), 1298 deletions(-) diff --git a/lib/windows/mmsystem.nim b/lib/windows/mmsystem.nim index 45613d8e2..9bc6a873f 100644 --- a/lib/windows/mmsystem.nim +++ b/lib/windows/mmsystem.nim @@ -29,12 +29,12 @@ import type MMRESULT* = uint32 MMVERSION* = uint32 - HWAVEOUT* = THandle + HWAVEOUT* = Handle LPHWAVEOUT* = ptr HWAVEOUT - HWAVEIN* = THandle + HWAVEIN* = Handle LPHWAVEIN* = ptr HWAVEOUT - HWAVE* = THandle - LPHWAVE* = ptr THandle + HWAVE* = Handle + LPHWAVE* = ptr Handle LPUINT* = ptr uint32 const @@ -151,7 +151,7 @@ const CALLBACK_FUNCTION* = 0x00030000 type - HDRVR* = THandle + HDRVR* = Handle const DRV_LOAD* = 1 @@ -178,7 +178,7 @@ const DRV_MCI_LAST* = (DRV_RESERVED + 0x00000FFF) type - PDRVCALLBACK* = proc (hdrvr: THandle, uMsg: uint32, dwUser, dw1, dw2: DWORD){. + PDRVCALLBACK* = proc (hdrvr: Handle, uMsg: uint32, dwUser, dw1, dw2: DWORD){. stdcall.} proc sndPlaySoundA*(Name: LPCSTR, flags: uint32): bool{.stdcall, @@ -991,7 +991,6 @@ type NPMMTIME* = ptr MMTIME LPMMTIME* = ptr MMTIME PWAVEHDR* = ptr WAVEHDR - TMMTime* = MMTIME WAVEHDR* {.final.} = object lpData*: cstring dwBufferLength*: DWORD @@ -1002,7 +1001,6 @@ type lpNext*: PWAVEHDR reserved*: DWORD - TWAVEHDR* = WAVEHDR NPWAVEHDR* = ptr WAVEHDR LPWAVEHDR* = ptr WAVEHDR WAVEOUTCAPSA* {.final.} = object @@ -1015,7 +1013,6 @@ type wReserved1*: int16 dwSupport*: DWORD - TWAVEOUTCAPSA* = WAVEOUTCAPSA PWAVEOUTCAPSA* = ptr WAVEOUTCAPSA NPWAVEOUTCAPSA* = ptr WAVEOUTCAPSA LPWAVEOUTCAPSA* = ptr WAVEOUTCAPSA @@ -1032,7 +1029,8 @@ type PWAVEOUTCAPSW* = ptr WAVEOUTCAPSW NPWAVEOUTCAPSW* = ptr WAVEOUTCAPSW LPWAVEOUTCAPSW* = ptr WAVEOUTCAPSW - TWAVEOUTCAPSW* = WAVEOUTCAPSW +{.deprecated: [Twavehdr: Wavehdr, Tmmtime: Mmtime, Twaveoutcapsa: Waveoutcapsa, + Twaveoutcapsw: Waveoutcapsw].} when defined(UNICODE): type @@ -1127,10 +1125,10 @@ type LPWAVEFORMATEX* = ptr WAVEFORMATEX LPCWAVEFORMATEX* = ptr WAVEFORMATEX TWAVEFORMATEX* = WAVEFORMATEX - HMIDI* = THandle - HMIDIIN* = THandle - HMIDIOUT* = THandle - HMIDISTRM* = THandle + HMIDI* = Handle + HMIDIIN* = Handle + HMIDIOUT* = Handle + HMIDISTRM* = Handle LPHMIDI* = ptr HMIDI LPHMIDIIN* = ptr HMIDIIN LPHMIDIOUT* = ptr HMIDIOUT @@ -1299,9 +1297,9 @@ else: LPAUXCAPS* = LPAUXCAPSA type TAUXCAPS* = AUXCAPS - HMIXEROBJ* = THandle + HMIXEROBJ* = Handle LPHMIXEROBJ* = ptr HMIXEROBJ - HMIXER* = THandle + HMIXER* = Handle LPHMIXER* = ptr HMIXER proc mixerGetNumDevs*(): uint32{.stdcall, dynlib: "winmm.dll", @@ -1647,7 +1645,7 @@ type TJOYINFOEX* = JOYINFOEX FOURCC* = DWORD HPSTR* = cstring - HMMIO* = THandle + HMMIO* = Handle LPMMIOPROC* = proc (x1: LPSTR, x2: uint32, x3, x4: LPARAM): LRESULT{.stdcall.} TMMIOPROC* = LPMMIOPROC MMIOINFO* {.final.} = object @@ -2096,14 +2094,14 @@ else: type MCI_ANIM_RECT_PARMS* {.final.} = object dwCallback*: DWORD - rc*: TRECT + rc*: RECT PMCI_ANIM_RECT_PARMS* = ptr MCI_ANIM_RECT_PARMS LPMCI_ANIM_RECT_PARMS* = ptr MCI_ANIM_RECT_PARMS TMCI_ANIM_RECT_PARMS* = MCI_ANIM_RECT_PARMS MCI_ANIM_UPDATE_PARMS* {.final.} = object dwCallback*: DWORD - rc*: TRECT + rc*: RECT hDC*: HDC PMCI_ANIM_UPDATE_PARMS* = ptr MCI_ANIM_UPDATE_PARMS @@ -2179,7 +2177,7 @@ type TMCI_OVLY_WINDOW_PARMS* = MCI_OVLY_WINDOW_PARMSW MCI_OVLY_RECT_PARMS* {.final.} = object dwCallback*: DWORD - rc*: TRECT + rc*: RECT PMCI_OVLY_RECT_PARMS* = ptr MCI_OVLY_RECT_PARMS LPMCI_OVLY_RECT_PARMS* = ptr MCI_OVLY_RECT_PARMS @@ -2187,7 +2185,7 @@ type MCI_OVLY_SAVE_PARMSA* {.final.} = object dwCallback*: DWORD lpfilename*: LPCSTR - rc*: TRECT + rc*: RECT PMCI_OVLY_SAVE_PARMSA* = ptr MCI_OVLY_SAVE_PARMSA LPMCI_OVLY_SAVE_PARMSA* = ptr MCI_OVLY_SAVE_PARMSA @@ -2195,7 +2193,7 @@ type MCI_OVLY_SAVE_PARMSW* {.final.} = object dwCallback*: DWORD lpfilename*: LPCWSTR - rc*: TRECT + rc*: RECT PMCI_OVLY_SAVE_PARMSW* = ptr MCI_OVLY_SAVE_PARMSW LPMCI_OVLY_SAVE_PARMSW* = ptr MCI_OVLY_SAVE_PARMSW @@ -2216,7 +2214,7 @@ type MCI_OVLY_LOAD_PARMSA* {.final.} = object dwCallback*: DWORD lpfilename*: LPCSTR - rc*: TRECT + rc*: RECT PMCI_OVLY_LOAD_PARMSA* = ptr MCI_OVLY_LOAD_PARMSA LPMCI_OVLY_LOAD_PARMSA* = ptr MCI_OVLY_LOAD_PARMSA @@ -2224,7 +2222,7 @@ type MCI_OVLY_LOAD_PARMSW* {.final.} = object dwCallback*: DWORD lpfilename*: LPCWSTR - rc*: TRECT + rc*: RECT PMCI_OVLY_LOAD_PARMSW* = ptr MCI_OVLY_LOAD_PARMSW LPMCI_OVLY_LOAD_PARMSW* = ptr MCI_OVLY_LOAD_PARMSW diff --git a/lib/windows/nb30.nim b/lib/windows/nb30.nim index 2e0c679ae..820e0b7a3 100644 --- a/lib/windows/nb30.nim +++ b/lib/windows/nb30.nim @@ -20,9 +20,9 @@ const MAX_LANA* = 254 # lana's in range 0 to MAX_LANA inclusive type # Network Control Block - PNCB* = ptr TNCB - TNCBPostProc* = proc (P: PNCB) {.stdcall.} - TNCB* {.final.} = object # Structure returned to the NCB command NCBASTAT is ADAPTER_STATUS followed + PNCB* = ptr NCB + NCBPostProc* = proc (P: PNCB) {.stdcall.} + NCB* {.final.} = object # Structure returned to the NCB command NCBASTAT is ADAPTER_STATUS followed # by an array of NAME_BUFFER structures. ncb_command*: char # command code ncb_retcode*: char # return code @@ -34,17 +34,17 @@ type # Network Control Block ncb_name*: array[0..NCBNAMSZ - 1, char] # our blank-padded netname ncb_rto*: char # rcv timeout/retry count ncb_sto*: char # send timeout/sys timeout - ncb_post*: TNCBPostProc # POST routine address + ncb_post*: NCBPostProc # POST routine address ncb_lana_num*: char # lana (adapter) number ncb_cmd_cplt*: char # 0xff => commmand pending ncb_reserve*: array[0..9, char] # reserved, used by BIOS - ncb_event*: THandle # HANDLE to Win32 event which + ncb_event*: Handle # HANDLE to Win32 event which # will be set to the signalled # state when an ASYNCH command # completes - PAdapterStatus* = ptr TAdapterStatus - TAdapterStatus* {.final.} = object + PAdapterStatus* = ptr AdapterStatus + AdapterStatus* {.final.} = object adapter_address*: array[0..5, char] rev_major*: char reserved0*: char @@ -73,11 +73,13 @@ type # Network Control Block max_sess_pkt_size*: int16 name_count*: int16 - PNameBuffer* = ptr TNameBuffer - TNameBuffer* {.final.} = object + PNameBuffer* = ptr NameBuffer + NameBuffer* {.final.} = object name*: array[0..NCBNAMSZ - 1, char] name_num*: char name_flags*: char +{.deprecated: [TNCB: NCB, TNCBPostProc: NCBPostProc, + TAdapterStatus: AdapterStatus, TNameBuffer: NameBuffer].} const # values for name_flags bits. @@ -94,21 +96,22 @@ type # Structure returned to the NCB command NCBSSTAT is SESSION_HEADER followed # by an array of SESSION_BUFFER structures. If the NCB_NAME starts with an # asterisk then an array of these structures is returned containing the # status for all names. - PSessionHeader* = ptr TSessionHeader - TSessionHeader* {.final.} = object + PSessionHeader* = ptr SessionHeader + SessionHeader* {.final.} = object sess_name*: char num_sess*: char rcv_dg_outstanding*: char rcv_any_outstanding*: char - PSessionBuffer* = ptr TSessionBuffer - TSessionBuffer* {.final.} = object + PSessionBuffer* = ptr SessionBuffer + SessionBuffer* {.final.} = object lsn*: char state*: char local_name*: array[0..NCBNAMSZ - 1, char] remote_name*: array[0..NCBNAMSZ - 1, char] rcvs_outstanding*: char sends_outstanding*: char +{.deprecated: [TSessionHeader: SessionHeader, TSessionBuffer: SessionBuffer].} const # Values for state @@ -128,14 +131,14 @@ type # Structure returned to the NCB command NCBENUM. len*: char # Number of valid entries in lana[] lana*: array[0..MAX_LANA, char] - PFindNameHeader* = ptr TFindNameHeader - TFindNameHeader* {.final.} = object + PFindNameHeader* = ptr FindNameHeader + FindNameHeader* {.final.} = object node_count*: int16 reserved*: char unique_group*: char - PFindNameBuffer* = ptr TFindNameBuffer - TFindNameBuffer* {.final.} = object # Structure provided with NCBACTION. The purpose of NCBACTION is to provide + PFindNameBuffer* = ptr FindNameBuffer + FindNameBuffer* {.final.} = object # Structure provided with NCBACTION. The purpose of NCBACTION is to provide # transport specific extensions to netbios. len*: char access_control*: char @@ -144,12 +147,13 @@ type # Structure returned to the NCB command NCBENUM. source_addr*: array[0..5, char] routing_info*: array[0..17, char] - PActionHeader* = ptr TActionHeader - TActionHeader* {.final.} = object + PActionHeader* = ptr ActionHeader + ActionHeader* {.final.} = object transport_id*: int32 action_code*: int16 reserved*: int16 - +{.deprecated: [TFindNameHeader: FindNameHeader, TFindNameBuffer: FindNameBuffer, + TActionHeader: ActionHeader].} const # Values for transport_id ALL_TRANSPORTS* = "M\0\0\0" diff --git a/lib/windows/shellapi.nim b/lib/windows/shellapi.nim index 079257680..0f8bc5ea3 100644 --- a/lib/windows/shellapi.nim +++ b/lib/windows/shellapi.nim @@ -31,7 +31,7 @@ import windows type - HDROP* = THandle + HDROP* = Handle UINT_PTR* = ptr uint32 DWORD_PTR* = ptr DWORD PHICON* = ptr HICON @@ -57,8 +57,8 @@ type hStdError*: HANDLE LPSTARTUPINFOW* = ptr STARTUPINFOW - TSTARTUPINFOW* = STARTUPINFOW PSTARTUPINFOW* = ptr STARTUPINFOW #unicode +{.deprecated: [TSTARTUPINFOW: STARTUPINFOW].} proc DragQueryFileA*(arg1: HDROP, arg2: uint32, arg3: LPSTR, arg4: uint32): uint32{. stdcall, dynlib: "shell32.dll", importc: "DragQueryFileA".} @@ -132,7 +132,6 @@ type # init with sizeof(DRAGINFO) lpFileList*: LPSTR grfKeyState*: DWORD - TDRAGINFOA* = DRAGINFOA LPDRAGINFOA* = ptr DRAGINFOA # init with sizeof(DRAGINFO) DRAGINFOW* {.final.} = object uSize*: uint32 @@ -141,19 +140,19 @@ type # init with sizeof(DRAGINFO) lpFileList*: LPWSTR grfKeyState*: DWORD - TDRAGINFOW* = DRAGINFOW LPDRAGINFOW* = ptr DRAGINFOW +{.deprecated: [TDRAGINFOA: DRAGINFOA, TDRAGINFOW: DRAGINFOW].} when defined(UNICODE): type DRAGINFO* = DRAGINFOW - TDRAGINFO* = DRAGINFOW LPDRAGINFO* = LPDRAGINFOW + {.deprecated: [TDRAGINFO: DRAGINFOW].} else: type DRAGINFO* = DRAGINFOA - TDRAGINFO* = DRAGINFOW LPDRAGINFO* = LPDRAGINFOA + {.deprecated: [TDRAGINFO: DRAGINFOW].} const ABM_NEW* = 0x00000000 ABM_REMOVE* = 0x00000001 @@ -189,8 +188,8 @@ type rc*: RECT lParam*: LPARAM # message specific - TAPPBARDATA* = AppBarData PAPPBARDATA* = ptr AppBarData +{.deprecated: [TAPPBARDATA: AppBarData].} proc SHAppBarMessage*(dwMessage: DWORD, pData: APPBARDATA): UINT_PTR{.stdcall, dynlib: "shell32.dll", importc: "SHAppBarMessage".} @@ -299,7 +298,6 @@ type hNameMappings*: LPVOID lpszProgressTitle*: LPCSTR # only used if FOF_SIMPLEPROGRESS - TSHFILEOPSTRUCTA* = SHFILEOPSTRUCTA LPSHFILEOPSTRUCTA* = ptr SHFILEOPSTRUCTA SHFILEOPSTRUCTW* {.final.} = object hwnd*: HWND @@ -311,19 +309,21 @@ type hNameMappings*: LPVOID lpszProgressTitle*: LPCWSTR - TSHFILEOPSTRUCTW* = SHFILEOPSTRUCTW LPSHFILEOPSTRUCTW* = ptr SHFILEOPSTRUCTW +{.deprecated: [TSHFILEOPSTRUCTA: SHFILEOPSTRUCTA, + TSHFILEOPSTRUCTW: SHFILEOPSTRUCTW].} when defined(UNICODE): type SHFILEOPSTRUCT* = SHFILEOPSTRUCTW - TSHFILEOPSTRUCT* = SHFILEOPSTRUCTW LPSHFILEOPSTRUCT* = LPSHFILEOPSTRUCTW + {.deprecated: [TSHFILEOPSTRUCT: SHFILEOPSTRUCTW].} else: type SHFILEOPSTRUCT* = SHFILEOPSTRUCTA - TSHFILEOPSTRUCT* = SHFILEOPSTRUCTA LPSHFILEOPSTRUCT* = LPSHFILEOPSTRUCTA + {.deprecated: [TSHFILEOPSTRUCT: SHFILEOPSTRUCTA].} + proc SHFileOperationA*(lpFileOp: LPSHFILEOPSTRUCTA): int32{.stdcall, dynlib: "shell32.dll", importc: "SHFileOperationA".} proc SHFileOperationW*(lpFileOp: LPSHFILEOPSTRUCTW): int32{.stdcall, @@ -332,7 +332,7 @@ proc SHFileOperation*(lpFileOp: LPSHFILEOPSTRUCTA): int32{.stdcall, dynlib: "shell32.dll", importc: "SHFileOperationA".} proc SHFileOperation*(lpFileOp: LPSHFILEOPSTRUCTW): int32{.stdcall, dynlib: "shell32.dll", importc: "SHFileOperationW".} -proc SHFreeNameMappings*(hNameMappings: THandle){.stdcall, +proc SHFreeNameMappings*(hNameMappings: Handle){.stdcall, dynlib: "shell32.dll", importc: "SHFreeNameMappings".} type SHNAMEMAPPINGA* {.final.} = object @@ -341,7 +341,6 @@ type cchOldPath*: int32 cchNewPath*: int32 - TSHNAMEMAPPINGA* = SHNAMEMAPPINGA LPSHNAMEMAPPINGA* = ptr SHNAMEMAPPINGA SHNAMEMAPPINGW* {.final.} = object pszOldPath*: LPWSTR @@ -349,19 +348,20 @@ type cchOldPath*: int32 cchNewPath*: int32 - TSHNAMEMAPPINGW* = SHNAMEMAPPINGW LPSHNAMEMAPPINGW* = ptr SHNAMEMAPPINGW +{.deprecated: [TSHNAMEMAPPINGA: SHNAMEMAPPINGA, + TSHNAMEMAPPINGW: SHNAMEMAPPINGW].} when not(defined(UNICODE)): type SHNAMEMAPPING* = SHNAMEMAPPINGW - TSHNAMEMAPPING* = SHNAMEMAPPINGW LPSHNAMEMAPPING* = LPSHNAMEMAPPINGW + {.deprecated: [TSHNAMEMAPPING: SHNAMEMAPPINGW].} else: type SHNAMEMAPPING* = SHNAMEMAPPINGA - TSHNAMEMAPPING* = SHNAMEMAPPINGA LPSHNAMEMAPPING* = LPSHNAMEMAPPINGA + {.deprecated: [TSHNAMEMAPPING: SHNAMEMAPPINGA].} # # End Shell File Operations # @@ -424,7 +424,6 @@ type hMonitor*: HANDLE # also: hIcon hProcess*: HANDLE - TSHELLEXECUTEINFOA* = SHELLEXECUTEINFOA LPSHELLEXECUTEINFOA* = ptr SHELLEXECUTEINFOA SHELLEXECUTEINFOW* {.final.} = object cbSize*: DWORD @@ -443,19 +442,21 @@ type hMonitor*: HANDLE # also: hIcon hProcess*: HANDLE - TSHELLEXECUTEINFOW* = SHELLEXECUTEINFOW LPSHELLEXECUTEINFOW* = ptr SHELLEXECUTEINFOW +{.deprecated: [TSHELLEXECUTEINFOA: SHELLEXECUTEINFOA, + TSHELLEXECUTEINFOW: SHELLEXECUTEINFOW].} when defined(UNICODE): type SHELLEXECUTEINFO* = SHELLEXECUTEINFOW - TSHELLEXECUTEINFO* = SHELLEXECUTEINFOW LPSHELLEXECUTEINFO* = LPSHELLEXECUTEINFOW + {.deprecated: [TSHELLEXECUTEINFO: SHELLEXECUTEINFOW].} else: type SHELLEXECUTEINFO* = SHELLEXECUTEINFOA - TSHELLEXECUTEINFO* = SHELLEXECUTEINFOA LPSHELLEXECUTEINFO* = LPSHELLEXECUTEINFOA + {.deprecated: [TSHELLEXECUTEINFO: SHELLEXECUTEINFOA].} + proc ShellExecuteExA*(lpExecInfo: LPSHELLEXECUTEINFOA): bool{.stdcall, dynlib: "shell32.dll", importc: "ShellExecuteExA".} proc ShellExecuteExW*(lpExecInfo: LPSHELLEXECUTEINFOW): bool{.stdcall, @@ -492,8 +493,8 @@ type lpStartupInfo*: LPSTARTUPINFOW lpProcessInformation*: LPPROCESS_INFORMATION - TSHCREATEPROCESSINFOW* = SHCREATEPROCESSINFOW PSHCREATEPROCESSINFOW* = ptr SHCREATEPROCESSINFOW +{.deprecated: [TSHCREATEPROCESSINFOW: SHCREATEPROCESSINFOW].} proc SHCreateProcessAsUserW*(pscpi: PSHCREATEPROCESSINFOW): bool{.stdcall, dynlib: "shell32.dll", importc: "SHCreateProcessAsUserW".} @@ -510,8 +511,8 @@ type i64Size*: int64 i64NumItems*: int64 - TSHQUERYRBINFO* = SHQUERYRBINFO LPSHQUERYRBINFO* = ptr SHQUERYRBINFO # flags for SHEmptyRecycleBin +{.deprecated: [TSHQUERYRBINFO: SHQUERYRBINFO].} const SHERB_NOCONFIRMATION* = 0x00000001 @@ -555,9 +556,8 @@ type uTimeout*: uint32 # also: uVersion szInfoTitle*: array[0..63, char] dwInfoFlags*: DWORD - guidItem*: TGUID + guidItem*: GUID - TNOTIFYICONDATAA* = NOTIFYICONDATAA PNOTIFYICONDATAA* = ptr NOTIFYICONDATAA NOTIFYICONDATAW* {.final.} = object cbSize*: DWORD @@ -573,21 +573,22 @@ type uTimeout*: uint32 # also uVersion : UINT szInfoTitle*: array[0..63, char] dwInfoFlags*: DWORD - guidItem*: TGUID + guidItem*: GUID - TNOTIFYICONDATAW* = NOTIFYICONDATAW PNOTIFYICONDATAW* = ptr NOTIFYICONDATAW +{.deprecated: [TNOTIFYICONDATAA: NOTIFYICONDATAA, + TNOTIFYICONDATAW: NOTIFYICONDATAW].} when defined(UNICODE): type NOTIFYICONDATA* = NOTIFYICONDATAW - TNOTIFYICONDATA* = NOTIFYICONDATAW PNOTIFYICONDATA* = PNOTIFYICONDATAW + {.deprecated: [TNOTIFYICONDATA: NOTIFYICONDATAW].} else: type NOTIFYICONDATA* = NOTIFYICONDATAA - TNOTIFYICONDATA* = NOTIFYICONDATAA PNOTIFYICONDATA* = PNOTIFYICONDATAA + {.deprecated: [TNOTIFYICONDATA: NOTIFYICONDATAA].} const NIN_SELECT* = WM_USER + 0 NINF_KEY* = 0x00000001 @@ -655,7 +656,6 @@ type szDisplayName*: array[0..(MAX_PATH) - 1, char] # out: display name (or path) szTypeName*: array[0..79, char] # out: type name - TSHFILEINFOA* = SHFILEINFOA PSHFILEINFOA* = ptr SHFILEINFOA SHFILEINFOW* {.final.} = object hIcon*: HICON # out: icon @@ -664,19 +664,19 @@ type szDisplayName*: array[0..(MAX_PATH) - 1, Wchar] # out: display name (or path) szTypeName*: array[0..79, Wchar] # out: type name - TSHFILEINFOW* = SHFILEINFOW PSHFILEINFOW* = ptr SHFILEINFOW +{.deprecated: [TSHFILEINFOA: SHFILEINFOA, TSHFILEINFOW: SHFILEINFOW].} when defined(UNICODE): type SHFILEINFO* = SHFILEINFOW - TSHFILEINFO* = SHFILEINFOW pFILEINFO* = SHFILEINFOW + {.deprecated: [TSHFILEINFO: SHFILEINFOW].} else: type SHFILEINFO* = SHFILEINFOA - TSHFILEINFO* = SHFILEINFOA pFILEINFO* = SHFILEINFOA + {.deprecated: [TSHFILEINFO: SHFILEINFOA].} # NOTE: This is also in shlwapi.h. Please keep in synch. const @@ -710,16 +710,16 @@ proc SHGetFileInfo*(pszPath: LPCSTR, dwFileAttributes: DWORD, psfi: PSHFILEINFOA, cbFileInfo, UFlags: uint32): DWORD{. stdcall, dynlib: "shell32.dll", importc: "SHGetFileInfoA".} proc SHGetFileInfoA*(pszPath: LPCSTR, dwFileAttributes: DWORD, - psfi: var TSHFILEINFOA, cbFileInfo, UFlags: uint32): DWORD{. + psfi: var SHFILEINFOA, cbFileInfo, UFlags: uint32): DWORD{. stdcall, dynlib: "shell32.dll", importc: "SHGetFileInfoA".} proc SHGetFileInfoW*(pszPath: LPCWSTR, dwFileAttributes: DWORD, - psfi: var TSHFILEINFOW, cbFileInfo, UFlags: uint32): DWORD{. + psfi: var SHFILEINFOW, cbFileInfo, UFlags: uint32): DWORD{. stdcall, dynlib: "shell32.dll", importc: "SHGetFileInfoW".} proc SHGetFileInfo*(pszPath: LPCSTR, dwFileAttributes: DWORD, - psfi: var TSHFILEINFOA, cbFileInfo, UFlags: uint32): DWORD{. + psfi: var SHFILEINFOA, cbFileInfo, UFlags: uint32): DWORD{. stdcall, dynlib: "shell32.dll", importc: "SHGetFileInfoA".} proc SHGetFileInfo*(pszPath: LPCWSTR, dwFileAttributes: DWORD, - psfi: var TSHFILEINFOW, cbFileInfo, UFlags: uint32): DWORD{. + psfi: var SHFILEINFOW, cbFileInfo, UFlags: uint32): DWORD{. stdcall, dynlib: "shell32.dll", importc: "SHGetFileInfoW".} proc SHGetDiskFreeSpaceExA*(pszDirectoryName: LPCSTR, pulFreeBytesAvailableToCaller: PULARGE_INTEGER, diff --git a/lib/windows/shfolder.nim b/lib/windows/shfolder.nim index 886d757eb..99cdf6cf5 100644 --- a/lib/windows/shfolder.nim +++ b/lib/windows/shfolder.nim @@ -72,22 +72,22 @@ const CSIDL_FLAG_CREATE* = 0x00008000 # (force creation of requested folder if it doesn't exist yet) # Original entry points -proc SHGetFolderPathA*(Ahwnd: HWND, Csidl: int, Token: THandle, Flags: DWord, +proc SHGetFolderPathA*(Ahwnd: HWND, Csidl: int, Token: Handle, Flags: DWord, Path: cstring): HRESULT{.stdcall, dynlib: LibName, importc: "SHGetFolderPathA".} -proc SHGetFolderPathW*(Ahwnd: HWND, Csidl: int, Token: THandle, Flags: DWord, +proc SHGetFolderPathW*(Ahwnd: HWND, Csidl: int, Token: Handle, Flags: DWord, Path: cstring): HRESULT{.stdcall, dynlib: LibName, importc: "SHGetFolderPathW".} -proc SHGetFolderPath*(Ahwnd: HWND, Csidl: int, Token: THandle, Flags: DWord, +proc SHGetFolderPath*(Ahwnd: HWND, Csidl: int, Token: Handle, Flags: DWord, Path: cstring): HRESULT{.stdcall, dynlib: LibName, importc: "SHGetFolderPathA".} type - PFNSHGetFolderPathA* = proc (Ahwnd: HWND, Csidl: int, Token: THandle, + PFNSHGetFolderPathA* = proc (Ahwnd: HWND, Csidl: int, Token: Handle, Flags: DWord, Path: cstring): HRESULT{.stdcall.} - PFNSHGetFolderPathW* = proc (Ahwnd: HWND, Csidl: int, Token: THandle, + PFNSHGetFolderPathW* = proc (Ahwnd: HWND, Csidl: int, Token: Handle, Flags: DWord, Path: cstring): HRESULT{.stdcall.} PFNSHGetFolderPath* = PFNSHGetFolderPathA - TSHGetFolderPathA* = PFNSHGetFolderPathA - TSHGetFolderPathW* = PFNSHGetFolderPathW - TSHGetFolderPath* = TSHGetFolderPathA - + +{.deprecated: [TSHGetFolderPathA: PFNSHGetFolderPathA, + TSHGetFolderPathW: PFNSHGetFolderPathW, + TSHGetFolderPath: SHGetFolderPathA].} diff --git a/lib/windows/windows.nim b/lib/windows/windows.nim index 02c87132a..49b82a4ba 100644 --- a/lib/windows/windows.nim +++ b/lib/windows/windows.nim @@ -98,9 +98,8 @@ type # WinDef.h -- Basic Windows Type Definitions LRESULT* = LONG_PTR ATOM* = int16 - TAtom* = ATOM HANDLE* = int - THandle* = HANDLE +# Handle* = HANDLE PHANDLE* = ptr HANDLE LPHANDLE* = ptr HANDLE HWND* = HANDLE @@ -150,11 +149,8 @@ type # WinDef.h -- Basic Windows Type Definitions y*: LONG PPOINTL* = ptr POINTL - TPOINT* = POINT - TPOINTL* = POINTL - RECT* {.final, pure.} = object - TopLeft*, BottomRight*: TPoint + TopLeft*, BottomRight*: Point PRECT* = ptr RECT LPRECT* = ptr RECT @@ -179,19 +175,14 @@ type # WinDef.h -- Basic Windows Type Definitions y*: SHORT PPOINTS* = ptr POINTS - TRECT* = RECT - TRECTL* = RECTL - TSIZE* = SIZE - TSIZEL* = SIZE - TPOINTS* = POINTS - FILETIME* {.final, pure.} = object dwLowDateTime*: DWORD dwHighDateTime*: DWORD PFILETIME* = ptr FILETIME LPFILETIME* = ptr FILETIME - - TFILETIME* = FILETIME +{.deprecated: [THandle: Handle, TAtom: ATOM, TFILETIME: FILETIME, TRECT: RECT, + TRECTL: RECTL, TSIZE: SIZE, TSIZEL: SIZE, TPOINTS: POINTS, + TPOINT: POINT, TPOINTL: POINTL].} const MAX_PATH* = 260 @@ -238,7 +229,6 @@ type CALTYPE* = int CALID* = int CCHAR* = char - TCOLORREF* = COLORREF WINT* = int32 PINTEGER* = ptr int32 PBOOL* = ptr WINBOOL @@ -269,6 +259,7 @@ type LCTYPE* = DWORD LP* = ptr int16 LPBOOL* = ptr WINBOOL +{.deprecated: [TCOLORREF: COLORREF].} when defined(winUnicode): type @@ -316,14 +307,16 @@ type when defined(winUnicode): type - TBYTE* = uint16 - TCHAR* = widechar + BYTE* = uint16 + CHAR* = widechar BCHAR* = int16 + {.deprecated: [TBYTE: BYTE, TCHAR: CHAR].} else: type - TBYTE* = uint8 - TCHAR* = char + BYTE* = uint8 + CHAR* = char BCHAR* = int8 + {.deprecated: [TBYTE: BYTE, TCHAR: CHAR].} type WCHAR* = WideChar PLPSTR* = ptr LPSTR @@ -367,7 +360,7 @@ type TokenUser = 1, TokenGroups, TokenPrivileges, TokenOwner, TokenPrimaryGroup, TokenDefaultDacl, TokenSource, TokenType, TokenImpersonationLevel, TokenStatistics - TTOKEN_TYPE* = enum + TTOKEN_TYPE* = enum # Name conflict if we drop the `T` TokenPrimary = 1, TokenImpersonation MakeIntResourceA* = cstring MakeIntResourceW* = PWideChar @@ -405,8 +398,7 @@ type WNDPROC* = proc (para1: HWND, para2: WINUINT, para3: WPARAM, para4: LPARAM): LRESULT{. stdcall.} FARPROC* = pointer - TFarProc* = FARPROC - TProc* = pointer + Proc* = pointer ENUMRESTYPEPROC* = proc (para1: HANDLE, para2: LPTSTR, para3: LONG): WINBOOL{. stdcall.} ENUMRESNAMEPROC* = proc (para1: HANDLE, para2: LPCTSTR, para3: LPTSTR, @@ -431,7 +423,7 @@ type stdcall.} ENUMOBJECTSPROC* = proc (para1: LPVOID, para2: LPARAM){.stdcall.} LINEDDAPROC* = proc (para1: int32, para2: int32, para3: LPARAM){.stdcall.} - TABORTPROC* = proc (para1: HDC, para2: int32): WINBOOL{.stdcall.} + ABORTPROC* = proc (para1: HDC, para2: int32): WINBOOL{.stdcall.} LPPAGEPAINTHOOK* = proc (para1: HWND, para2: WINUINT, para3: WPARAM, para4: LPARAM): WINUINT{.stdcall.} LPPAGESETUPHOOK* = proc (para1: HWND, para2: WINUINT, para3: WPARAM, @@ -454,6 +446,7 @@ type stdcall.} PFNPROCESSPOLICIES* = proc (para1: HWND, para2: LPCTSTR, para3: LPCTSTR, para4: LPCTSTR, para5: DWORD): WINBOOL{.stdcall.} +{.deprecated: [TFarProc: FARPROC, TProc: Proc, TABORTPROC: ABORTPROC].} const SE_CREATE_TOKEN_NAME* = "SeCreateTokenPrivilege" @@ -5385,9 +5378,10 @@ const # TV_INSERTSTRUCT structure type - TTREEITEM* {.final, pure.} = object - HTREEITEM* = ptr TTREEITEM - PTREEITEM* = ptr TTREEITEM + TREEITEM* {.final, pure.} = object + HTREEITEM* = ptr TREEITEM + PTREEITEM* = ptr TREEITEM +{.deprecated: [TTREEITEM: TREEITEM].} const TVI_ROOT* = cast[HTREEITEM](0xFFFF0000) @@ -6870,32 +6864,31 @@ type # va_list is just a dummy record # MvdV: Nevertheless it should be a pointer type, not a record va_list* = cstring - TABC* {.final, pure.} = object + ABC* {.final, pure.} = object abcA*: int32 abcB*: WINUINT abcC*: int32 - LPABC* = ptr TABC - PABC* = ptr TABC - TABCFLOAT* {.final, pure.} = object + LPABC* = ptr ABC + PABC* = ptr ABC + ABCFLOAT* {.final, pure.} = object abcfA*: float32 abcfB*: float32 abcfC*: float32 - LPABCFLOAT* = ptr TABCFLOAT - PABCFLOAT* = ptr TABCFLOAT + LPABCFLOAT* = ptr ABCFLOAT + PABCFLOAT* = ptr ABCFLOAT - TACCEL* {.final, pure.} = object + ACCEL* {.final, pure.} = object fVirt*: int8 key*: int16 cmd*: int16 - LPACCEL* = ptr TACCEL - PACCEL* = ptr TACCEL + LPACCEL* = ptr ACCEL + PACCEL* = ptr ACCEL ACE_HEADER* {.final, pure.} = object AceType*: int8 AceFlags*: int8 AceSize*: int16 - TACE_HEADER* = ACE_HEADER PACE_HEADER* = ptr ACE_HEADER ACCESS_MASK* = DWORD REGSAM* = ACCESS_MASK @@ -6904,20 +6897,17 @@ type Mask*: ACCESS_MASK SidStart*: DWORD - TACCESS_ALLOWED_ACE* = ACCESS_ALLOWED_ACE PACCESS_ALLOWED_ACE* = ptr ACCESS_ALLOWED_ACE ACCESS_DENIED_ACE* {.final, pure.} = object Header*: ACE_HEADER Mask*: ACCESS_MASK SidStart*: DWORD - TACCESS_DENIED_ACE* = ACCESS_DENIED_ACE ACCESSTIMEOUT* {.final, pure.} = object cbSize*: WINUINT dwFlags*: DWORD iTimeOutMSec*: DWORD - TACCESSTIMEOUT* = ACCESSTIMEOUT PACCESSTIMEOUT* = ptr ACCESSTIMEOUT ACL* {.final, pure.} = object AclRevision*: int8 @@ -6927,12 +6917,11 @@ type Sbz2*: int16 PACL* = ptr ACL - TACL* = ACL - TACL_REVISION_INFORMATION* {.final, pure.} = object + TACL_REVISION_INFORMATION* {.final, pure.} = object # Name conflit if we drop the `T` AclRevision*: DWORD PACLREVISIONINFORMATION* = ptr TACL_REVISION_INFORMATION - TACL_SIZE_INFORMATION* {.final, pure.} = object + TACL_SIZE_INFORMATION* {.final, pure.} = object # Name conflict if we drop the `T` AceCount*: DWORD AclBytesInUse*: DWORD AclBytesFree*: DWORD @@ -6942,7 +6931,6 @@ type action_code*: USHORT reserved*: USHORT - TACTIONHEADER* = ACTION_HEADER PACTIONHEADER* = ptr ACTION_HEADER ADAPTER_STATUS* {.final, pure.} = object adapter_address*: array[0..5, UCHAR] @@ -6973,20 +6961,17 @@ type max_sess_pkt_size*: int16 name_count*: int16 - TADAPTERSTATUS* = ADAPTER_STATUS PADAPTERSTATUS* = ptr ADAPTER_STATUS ADDJOB_INFO_1* {.final, pure.} = object Path*: LPTSTR JobId*: DWORD - TADDJOB_INFO_1* = ADDJOB_INFO_1 PADDJOB_INFO_1* = ptr ADDJOB_INFO_1 ANIMATIONINFO* {.final, pure.} = object cbSize*: WINUINT iMinAnimate*: int32 LPANIMATIONINFO* = ptr ANIMATIONINFO - TANIMATIONINFO* = ANIMATIONINFO PANIMATIONINFO* = ptr ANIMATIONINFO APPBARDATA* {.final, pure.} = object @@ -6997,7 +6982,6 @@ type rc*: RECT lParam*: LPARAM - TAppBarData* = APPBARDATA PAppBarData* = ptr APPBARDATA BITMAP* {.final, pure.} = object bmType*: LONG @@ -7011,7 +6995,6 @@ type PBITMAP* = ptr BITMAP NPBITMAP* = ptr BITMAP LPBITMAP* = ptr BITMAP - TBITMAP* = BITMAP BITMAPCOREHEADER* {.final, pure.} = object bcSize*: DWORD bcWidth*: int16 @@ -7019,14 +7002,12 @@ type bcPlanes*: int16 bcBitCount*: int16 - TBITMAPCOREHEADER* = BITMAPCOREHEADER PBITMAPCOREHEADER* = ptr BITMAPCOREHEADER RGBTRIPLE* {.final, pure.} = object rgbtBlue*: int8 rgbtGreen*: int8 rgbtRed*: int8 - TRGBTRIPLE* = RGBTRIPLE PRGBTRIPLE* = ptr RGBTRIPLE BITMAPCOREINFO* {.final, pure.} = object bmciHeader*: BITMAPCOREHEADER @@ -7034,7 +7015,7 @@ type PBITMAPCOREINFO* = ptr BITMAPCOREINFO LPBITMAPCOREINFO* = ptr BITMAPCOREINFO - TBITMAPCOREINFO* = BITMAPCOREINFO # error +# TBITMAPCOREINFO* = BITMAPCOREINFO # error # WORD bfReserved1; # WORD bfReserved2; # in declarator_list @@ -7052,7 +7033,6 @@ type biClrImportant*: DWORD LPBITMAPINFOHEADER* = ptr BITMAPINFOHEADER - TBITMAPINFOHEADER* = BITMAPINFOHEADER PBITMAPINFOHEADER* = ptr BITMAPINFOHEADER RGBQUAD* {.final, pure.} = object rgbBlue*: int8 @@ -7060,7 +7040,6 @@ type rgbRed*: int8 rgbReserved*: int8 - TRGBQUAD* = RGBQUAD PRGBQUAD* = ptr RGBQUAD BITMAPINFO* {.final, pure.} = object bmiHeader*: BITMAPINFOHEADER @@ -7068,7 +7047,6 @@ type LPBITMAPINFO* = ptr BITMAPINFO PBITMAPINFO* = ptr BITMAPINFO - TBITMAPINFO* = BITMAPINFO FXPT2DOT30* = int32 LPFXPT2DOT30* = ptr FXPT2DOT30 TPFXPT2DOT30* = FXPT2DOT30 @@ -7079,7 +7057,6 @@ type ciexyzZ*: FXPT2DOT30 LPCIEXYZ* = ptr CIEXYZ - TPCIEXYZ* = CIEXYZ PCIEXYZ* = ptr CIEXYZ CIEXYZTRIPLE* {.final, pure.} = object ciexyzRed*: CIEXYZ @@ -7087,7 +7064,6 @@ type ciexyzBlue*: CIEXYZ LPCIEXYZTRIPLE* = ptr CIEXYZTRIPLE - TCIEXYZTRIPLE* = CIEXYZTRIPLE PCIEXYZTRIPLE* = ptr CIEXYZTRIPLE BITMAPV4HEADER* {.final, pure.} = object bV4Size*: DWORD @@ -7112,7 +7088,6 @@ type bV4GammaBlue*: DWORD LPBITMAPV4HEADER* = ptr BITMAPV4HEADER - TBITMAPV4HEADER* = BITMAPV4HEADER PBITMAPV4HEADER* = ptr BITMAPV4HEADER BITMAPFILEHEADER* {.final, pure.} = object bfType*: int16 @@ -7125,7 +7100,6 @@ type cbSize*: ULONG pBlobData*: ptr int8 - TBLOB* = BLOB PBLOB* = ptr BLOB SHITEMID* {.final, pure.} = object cb*: USHORT @@ -7133,14 +7107,12 @@ type LPSHITEMID* = ptr SHITEMID LPCSHITEMID* = ptr SHITEMID - TSHITEMID* = SHITEMID PSHITEMID* = ptr SHITEMID ITEMIDLIST* {.final, pure.} = object mkid*: SHITEMID LPITEMIDLIST* = ptr ITEMIDLIST LPCITEMIDLIST* = ptr ITEMIDLIST - TITEMIDLIST* = ITEMIDLIST PITEMIDLIST* = ptr ITEMIDLIST BROWSEINFO* {.final, pure.} = object hwndOwner*: HWND @@ -7153,7 +7125,6 @@ type iImage*: int32 LPBROWSEINFO* = ptr BROWSEINFO - Tbrowseinfo* = BROWSEINFO PBROWSEINFO* = ptr BROWSEINFO BY_HANDLE_FILE_INFORMATION* {.final, pure.} = object @@ -7169,22 +7140,19 @@ type nFileIndexLow*: DWORD LPBY_HANDLE_FILE_INFORMATION* = ptr BY_HANDLE_FILE_INFORMATION - TBYHANDLEFILEINFORMATION* = BY_HANDLE_FILE_INFORMATION PBYHANDLEFILEINFORMATION* = ptr BY_HANDLE_FILE_INFORMATION FIXED* {.final, pure.} = object fract*: int16 value*: SHORT - TFIXED* = FIXED PFIXED* = ptr FIXED POINTFX* {.final, pure.} = object x*: FIXED y*: FIXED - TPOINTFX* = POINTFX PPOINTFX* = ptr POINTFX - TSmallPoint* {.final, pure.} = object + SmallPoint* {.final, pure.} = object X*, Y*: SHORT CANDIDATEFORM* {.final, pure.} = object @@ -7194,7 +7162,6 @@ type rcArea*: RECT LPCANDIDATEFORM* = ptr CANDIDATEFORM - TCANDIDATEFORM* = CANDIDATEFORM PCANDIDATEFORM* = ptr CANDIDATEFORM CANDIDATELIST* {.final, pure.} = object dwSize*: DWORD @@ -7206,7 +7173,6 @@ type dwOffset*: array[0..0, DWORD] LPCANDIDATELIST* = ptr CANDIDATELIST - TCANDIDATELIST* = CANDIDATELIST PCANDIDATELIST* = ptr CANDIDATELIST CREATESTRUCT* {.final, pure.} = object lpCreateParams*: LPVOID @@ -7223,25 +7189,21 @@ type dwExStyle*: DWORD LPCREATESTRUCT* = ptr CREATESTRUCT - TCREATESTRUCT* = CREATESTRUCT PCREATESTRUCT* = ptr CREATESTRUCT CBT_CREATEWND* {.final, pure.} = object lpcs*: LPCREATESTRUCT hwndInsertAfter*: HWND - TCBT_CREATEWND* = CBT_CREATEWND PCBT_CREATEWND* = ptr CBT_CREATEWND CBTACTIVATESTRUCT* {.final, pure.} = object fMouse*: WINBOOL hWndActive*: HWND - TCBTACTIVATESTRUCT* = CBTACTIVATESTRUCT PCBTACTIVATESTRUCT* = ptr CBTACTIVATESTRUCT CHAR_INFO* {.final, pure.} = object UnicodeChar*: WCHAR Attributes*: int16 # other union part: AsciiChar : CHAR - TCHAR_INFO* = CHAR_INFO PCHAR_INFO* = ptr CHAR_INFO CHARFORMAT* {.final, pure.} = object cbSize*: WINUINT @@ -7252,28 +7214,24 @@ type crTextColor*: COLORREF bCharSet*: int8 bPitchAndFamily*: int8 - szFaceName*: array[0..(LF_FACESIZE) - 1, TCHAR] + szFaceName*: array[0..(LF_FACESIZE) - 1, CHAR] - Tcharformat* = CHARFORMAT Pcharformat* = ptr CHARFORMAT CHARRANGE* {.final, pure.} = object cpMin*: LONG cpMax*: LONG - Tcharrange* = CHARRANGE Pcharrange* = ptr CHARRANGE CHARSET* {.final, pure.} = object aflBlock*: array[0..2, DWORD] flLang*: DWORD - TCHARSET* = CHARSET PCHARSET* = ptr CHARSET FONTSIGNATURE* {.final, pure.} = object fsUsb*: array[0..3, DWORD] fsCsb*: array[0..1, DWORD] LPFONTSIGNATURE* = ptr FONTSIGNATURE - TFONTSIGNATURE* = FONTSIGNATURE PFONTSIGNATURE* = ptr FONTSIGNATURE CHARSETINFO* {.final, pure.} = object ciCharset*: WINUINT @@ -7281,7 +7239,6 @@ type fs*: FONTSIGNATURE LPCHARSETINFO* = ptr CHARSETINFO - TCHARSETINFO* = CHARSETINFO PCHARSETINFO* = ptr CHARSETINFO #CHOOSECOLOR = record confilcts with function ChooseColor TCHOOSECOLOR* {.final, pure.} = object @@ -7311,11 +7268,9 @@ type lfClipPrecision*: int8 lfQuality*: int8 lfPitchAndFamily*: int8 - lfFaceName*: array[0..(LF_FACESIZE) - 1, TCHAR] + lfFaceName*: array[0..(LF_FACESIZE) - 1, CHAR] LPLOGFONT* = ptr LOGFONT - TLOGFONT* = LOGFONT - TLOGFONTA* = LOGFONT PLOGFONT* = ptr LOGFONT PLOGFONTA* = PLOGFONT LOGFONTW* {.final, pure.} = object @@ -7336,9 +7291,8 @@ type LPLOGFONTW* = ptr LOGFONTW NPLOGFONTW* = ptr LOGFONTW - TLogFontW* = LOGFONTW - PLogFontW* = ptr TLogFontW - TCHOOSEFONT* {.final, pure.} = object + PLogFontW* = ptr LogFontW + TCHOOSEFONT* {.final, pure.} = object # Name conflict if we drop the `T` lStructSize*: DWORD hwndOwner*: HWND hDC*: HDC @@ -7363,14 +7317,12 @@ type aoffset*: array[0..0, WINUINT] LPIDA* = ptr CIDA - TIDA* = CIDA PIDA* = ptr CIDA CLIENTCREATESTRUCT* {.final, pure.} = object hWindowMenu*: HANDLE idFirstChild*: WINUINT LPCLIENTCREATESTRUCT* = ptr CLIENTCREATESTRUCT - TCLIENTCREATESTRUCT* = CLIENTCREATESTRUCT PCLIENTCREATESTRUCT* = ptr CLIENTCREATESTRUCT CMINVOKECOMMANDINFO* {.final, pure.} = object cbSize*: DWORD @@ -7384,7 +7336,6 @@ type hIcon*: HANDLE LPCMINVOKECOMMANDINFO* = ptr CMINVOKECOMMANDINFO - TCMInvokeCommandInfo* = CMINVOKECOMMANDINFO PCMInvokeCommandInfo* = ptr CMINVOKECOMMANDINFO COLORADJUSTMENT* {.final, pure.} = object caSize*: int16 @@ -7401,14 +7352,12 @@ type caRedGreenTint*: SHORT LPCOLORADJUSTMENT* = ptr COLORADJUSTMENT - TCOLORADJUSTMENT* = COLORADJUSTMENT PCOLORADJUSTMENT* = ptr COLORADJUSTMENT COLORMAP* {.final, pure.} = object `from`*: COLORREF `to`*: COLORREF # XXX! LPCOLORMAP* = ptr COLORMAP - TCOLORMAP* = COLORMAP PCOLORMAP* = ptr COLORMAP DCB* {.final, pure.} = object DCBlength*: DWORD @@ -7428,8 +7377,28 @@ type wReserved1*: int16 LPDCB* = ptr DCB - TDCB* = DCB PDCB* = ptr DCB +{.deprecated: [TABC: ABC, TABCFLOAT: ABCFLOAT, TACCEL: ACCEL, TACE_HEADER: ACE_HEADER, + TACCESS_ALLOWED_ACE: ACCESS_ALLOWED_ACE, TACCESS_DENIED_ACE: ACCESS_DENIED_ACE, + TACCESSTIMEOUT: ACCESSTIMEOUT, TACL: ACL, TACTIONHEADER: ACTION_HEADER, + TADAPTERSTATUS: ADAPTER_STATUS, TADDJOB_INFO_1: ADDJOB_INFO_1, + TANIMATIONINFO: ANIMATIONINFO, TAppBarData: APPBARDATA, TBITMAP: BITMAP, + TBITMAPCOREHEADER: BITMAPCOREHEADER, TRGBTRIPLE: RGBTRIPLE, + TBITMAPCOREINFO: BITMAPCOREINFO, TBITMAPINFOHEADER: BITMAPINFOHEADER, + TRGBQUAD: RGBQUAD, TBITMAPINFO: BITMAPINFO, TPCIEXYZ: CIEXYZ, + TCIEXYZTRIPLE: CIEXYZTRIPLE, TBITMAPV4HEADER: BITMAPV4HEADER, TBLOB: BLOB, + TSHITEMID: SHITEMID, TITEMIDLIST: ITEMIDLIST, Tbrowseinfo: BROWSEINFO, + TBYHANDLEFILEINFORMATION: BY_HANDLE_FILE_INFORMATION, TFIXED: FIXED, + TPOINTFX: POINTFX, TSmallPoint: SmallPoint, TCANDIDATEFORM: CANDIDATEFORM, + TCANDIDATELIST: CANDIDATELIST, TCREATESTRUCT: CREATESTRUCT, + TCBT_CREATEWND: CBT_CREATEWND, TCBTACTIVATESTRUCT: CBTACTIVATESTRUCT, + TCHAR_INFO: CHAR_INFO, Tcharformat: CHARFORMAT, Tcharrange: CHARRANGE, + TCHARSET: CHARSET, TFONTSIGNATURE: FONTSIGNATURE, TCHARSETINFO: CHARSETINFO, + TLOGFONT: LOGFONT, TLOGFONTA: LOGFONT, TLogFontW: LOGFONTW, + TIDA: CIDA, TCLIENTCREATESTRUCT: CLIENTCREATESTRUCT, + TCMInvokeCommandInfo: CMINVOKECOMMANDINFO, TCOLORADJUSTMENT: COLORADJUSTMENT, + TCOLORMAP: COLORMAP, TDCB: DCB +].} const bm_DCB_fBinary* = 1 @@ -7501,7 +7470,6 @@ type wcProviderData*: array[0..0, WCHAR] LPCOMMCONFIG* = ptr COMMCONFIG - TCOMMCONFIG* = COMMCONFIG PCOMMCONFIG* = ptr COMMCONFIG COMMPROP* {.final, pure.} = object wPacketLength*: int16 @@ -7524,7 +7492,6 @@ type wcProvChar*: array[0..0, WCHAR] LPCOMMPROP* = ptr COMMPROP - TCOMMPROP* = COMMPROP PCOMMPROP* = ptr COMMPROP COMMTIMEOUTS* {.final, pure.} = object ReadIntervalTimeout*: DWORD @@ -7534,7 +7501,6 @@ type WriteTotalTimeoutConstant*: DWORD LPCOMMTIMEOUTS* = ptr COMMTIMEOUTS - TCOMMTIMEOUTS* = COMMTIMEOUTS PCOMMTIMEOUTS* = ptr COMMTIMEOUTS COMPAREITEMSTRUCT* {.final, pure.} = object CtlType*: WINUINT @@ -7545,14 +7511,12 @@ type itemID2*: WINUINT itemData2*: ULONG_PTR - TCOMPAREITEMSTRUCT* = COMPAREITEMSTRUCT PCOMPAREITEMSTRUCT* = ptr COMPAREITEMSTRUCT COMPCOLOR* {.final, pure.} = object crText*: COLORREF crBackground*: COLORREF dwEffects*: DWORD - TCOMPCOLOR* = COMPCOLOR PCOMPCOLOR* = ptr COMPCOLOR COMPOSITIONFORM* {.final, pure.} = object dwStyle*: DWORD @@ -7560,18 +7524,19 @@ type rcArea*: RECT LPCOMPOSITIONFORM* = ptr COMPOSITIONFORM - TCOMPOSITIONFORM* = COMPOSITIONFORM - PCOMPOSITIONFORM* = ptr COMPOSITIONFORM # TComStatFlags = set of (fCtsHold, fDsrHold, fRlsdHold , fXoffHold , + PCOMPOSITIONFORM* = ptr COMPOSITIONFORM # ComStatFlags = set of (fCtsHold, fDsrHold, fRlsdHold , fXoffHold , # fXoffSent , fEof , fTxim , fReserved); COMSTAT* {.final, pure.} = object - flag0*: DWORD # can't use tcomstatflags, set packing issues + flag0*: DWORD # can't use comstatflags, set packing issues # and conflicts with macro's cbInQue*: DWORD cbOutQue*: DWORD LPCOMSTAT* = ptr COMSTAT - TCOMSTAT* = COMSTAT PCOMSTAT* = ptr COMSTAT +{.deprecated: [TCOMSTAT: COMSTAT, TCOMPOSITIONFORM: COMPOSITIONFORM, + TCOMPCOLOR: COMPCOLOR, TCOMPAREITEMSTRUCT: COMPAREITEMSTRUCT, + TCOMMTIMEOUTS: COMMTIMEOUTS, TCOMMPROP: COMMPROP, TCOMMCONFIG: COMMCONFIG].} const bm_COMSTAT_fCtsHold* = 0x00000001 @@ -7614,13 +7579,10 @@ type bVisible*: WINBOOL PCONSOLE_CURSOR_INFO* = ptr CONSOLE_CURSOR_INFO - TCONSOLECURSORINFO* = CONSOLE_CURSOR_INFO - TCURSORINFO* = CONSOLE_CURSOR_INFO COORD* {.final, pure.} = object X*: SHORT Y*: SHORT - TCOORD* = COORD PCOORD* = ptr COORD SMALL_RECT* {.final, pure.} = object Left*: SHORT @@ -7628,7 +7590,6 @@ type Right*: SHORT Bottom*: SHORT - TSMALL_RECT* = SMALL_RECT PSMALL_RECT* = ptr SMALL_RECT CONSOLE_SCREEN_BUFFER_INFO* {.final, pure.} = object dwSize*: COORD @@ -7638,7 +7599,10 @@ type dwMaximumWindowSize*: COORD PCONSOLE_SCREEN_BUFFER_INFO* = ptr CONSOLE_SCREEN_BUFFER_INFO - TCONSOLESCREENBUFFERINFO* = CONSOLE_SCREEN_BUFFER_INFO + +{.deprecated: [TCONSOLECURSORINFO: CONSOLE_CURSOR_INFO, + TCURSORINFO: CONSOLE_CURSOR_INFO, TCOORD: COORD, TSMALL_RECT: SMALL_RECT, + TCONSOLESCREENBUFFERINFO: CONSOLE_SCREEN_BUFFER_INFO].} when defined(i386): type @@ -7653,7 +7617,6 @@ when defined(i386): RegisterArea*: array[0..79, int8] Cr0NpxState*: DWORD - TFLOATINGSAVEAREA* = FLOATING_SAVE_AREA PFLOATINGSAVEAREA* = ptr FLOATING_SAVE_AREA CONTEXT* {.final, pure.} = object ContextFlags*: DWORD @@ -7680,6 +7643,7 @@ when defined(i386): EFlags*: DWORD Esp*: DWORD SegSs*: DWORD + {.deprecated: [TFLOATINGSAVEAREA: FLOATING_SAVE_AREA].} elif defined(x86_64): # @@ -7690,8 +7654,7 @@ elif defined(x86_64): Low*: ULONGLONG High*: LONGLONG - TM128A* = M128A - PM128A* = TM128A #typedef struct _XMM_SAVE_AREA32 { + PM128A* = M128A #typedef struct _XMM_SAVE_AREA32 { XMM_SAVE_AREA32* {.final, pure.} = object ControlWord*: int16 StatusWord*: int16 @@ -7710,8 +7673,9 @@ elif defined(x86_64): XmmRegisters*: array[0..16, M128A] Reserved4*: array[0..95, int8] - TXmmSaveArea* = XMM_SAVE_AREA32 - PXmmSaveArea* = ptr TXmmSaveArea + PXmmSaveArea* = ptr XmmSaveArea32 + {.deprecated: [TM128A: M128A, TXmmSaveArea: XMM_SAVE_AREA32].} + type CONTEXT* {.final, pure.} = object P1Home*: DWORD64 @@ -7891,20 +7855,19 @@ else: type LPCONTEXT* = ptr CONTEXT - TCONTEXT* = CONTEXT PCONTEXT* = ptr CONTEXT +{.deprecated: [TCONTEXT: CONTEXT].} type LIST_ENTRY* {.final, pure.} = object Flink*: ptr LIST_ENTRY Blink*: ptr LIST_ENTRY - TLISTENTRY* = LIST_ENTRY PLISTENTRY* = ptr LIST_ENTRY CRITICAL_SECTION_DEBUG* {.final, pure.} = object `type`*: int16 CreatorBackTraceIndex*: int16 - CriticalSection*: ptr TCRITICAL_SECTION + CriticalSection*: ptr TRTL_CRITICAL_SECTION ProcessLocksList*: LIST_ENTRY EntryCount*: DWORD ContentionCount*: DWORD @@ -7923,8 +7886,6 @@ type LPCRITICAL_SECTION_DEBUG* = ptr CRITICAL_SECTION_DEBUG PCRITICAL_SECTION_DEBUG* = ptr CRITICAL_SECTION_DEBUG - TCRITICALSECTIONDEBUG* = CRITICAL_SECTION_DEBUG - TCRITICAL_SECTION* = TRTLCriticalSection PCRITICAL_SECTION* = PRTLCriticalSection LPCRITICAL_SECTION* = PRTLCriticalSection SECURITY_QUALITY_OF_SERVICE* {.final, pure.} = object @@ -7934,7 +7895,6 @@ type EffectiveOnly*: bool PSECURITY_QUALITY_OF_SERVICE* = ptr SECURITY_QUALITY_OF_SERVICE - TSECURITYQUALITYOFSERVICE* = SECURITY_QUALITY_OF_SERVICE CONVCONTEXT* {.final, pure.} = object cb*: WINUINT wFlags*: WINUINT @@ -7944,7 +7904,6 @@ type dwSecurity*: DWORD qos*: SECURITY_QUALITY_OF_SERVICE - TCONVCONTEXT* = CONVCONTEXT PCONVCONTEXT* = ptr CONVCONTEXT CONVINFO* {.final, pure.} = object cb*: DWORD @@ -7964,14 +7923,12 @@ type hwnd*: HWND hwndPartner*: HWND - TCONVINFO* = CONVINFO PCONVINFO* = ptr CONVINFO COPYDATASTRUCT* {.final, pure.} = object dwData*: DWORD cbData*: DWORD lpData*: PVOID - TCOPYDATASTRUCT* = COPYDATASTRUCT PCOPYDATASTRUCT* = ptr COPYDATASTRUCT CPINFO* {.final, pure.} = object MaxCharSize*: WINUINT @@ -7979,7 +7936,6 @@ type LeadByte*: array[0..(MAX_LEADBYTES) - 1, int8] LPCPINFO* = ptr CPINFO - Tcpinfo* = CPINFO Pcpinfo* = ptr CPINFO CPLINFO* {.final, pure.} = object idIcon*: int32 @@ -7987,7 +7943,6 @@ type idInfo*: int32 lData*: LONG - TCPLINFO* = CPLINFO PCPLINFO* = ptr CPLINFO CREATE_PROCESS_DEBUG_INFO* {.final, pure.} = object hFile*: HANDLE @@ -8001,14 +7956,12 @@ type lpImageName*: LPVOID fUnicode*: int16 - TCREATEPROCESSDEBUGINFO* = CREATE_PROCESS_DEBUG_INFO PCREATEPROCESSDEBUGINFO* = ptr CREATE_PROCESS_DEBUG_INFO CREATE_THREAD_DEBUG_INFO* {.final, pure.} = object hThread*: HANDLE lpThreadLocalBase*: LPVOID lpStartAddress*: LPTHREAD_START_ROUTINE - - TCREATETHREADDEBUGINFO* = CREATE_THREAD_DEBUG_INFO + PCREATETHREADDEBUGINFO* = ptr CREATE_THREAD_DEBUG_INFO CURRENCYFMT* {.final, pure.} = object @@ -8021,7 +7974,6 @@ type PositiveOrder*: WINUINT lpCurrencySymbol*: LPTSTR - Tcurrencyfmt* = CURRENCYFMT Pcurrencyfmt* = ptr CURRENCYFMT CURSORSHAPE* {.final, pure.} = object xHotSpot*: int32 @@ -8033,7 +7985,6 @@ type BitsPixel*: int8 LPCURSORSHAPE* = ptr CURSORSHAPE - TCURSORSHAPE* = CURSORSHAPE PCURSORSHAPE* = ptr CURSORSHAPE CWPRETSTRUCT* {.final, pure.} = object lResult*: LRESULT @@ -8042,7 +7993,6 @@ type message*: DWORD hwnd*: HWND - TCWPRETSTRUCT* = CWPRETSTRUCT PCWPRETSTRUCT* = ptr CWPRETSTRUCT CWPSTRUCT* {.final, pure.} = object lParam*: LPARAM @@ -8050,18 +8000,24 @@ type message*: WINUINT hwnd*: HWND - TCWPSTRUCT* = CWPSTRUCT PCWPSTRUCT* = ptr CWPSTRUCT DATATYPES_INFO_1* {.final, pure.} = object pName*: LPTSTR - TDATATYPESINFO1* = DATATYPES_INFO_1 PDATATYPESINFO1* = ptr DATATYPES_INFO_1 DDEACK* {.final, pure.} = object flag0*: int16 - TDDEACK* = DDEACK PDDEACK* = ptr DDEACK +{.deprecated: [TLISTENTRY: LIST_ENTRY, TDATATYPESINFO1: DATATYPES_INFO_1, + TCWPSTRUCT: CWPSTRUCT, TCWPRETSTRUCT: CWPRETSTRUCT, TCURSORSHAPE: CURSORSHAPE, + Tcurrencyfmt: CURRENCYFMT, TCREATETHREADDEBUGINFO: CREATE_THREAD_DEBUG_INFO, + TCREATEPROCESSDEBUGINFO: CREATE_PROCESS_DEBUG_INFO, TCPLINFO: CPLINFO, + Tcpinfo: CPINFO, TCOPYDATASTRUCT: COPYDATASTRUCT, TCONVINFO: CONVINFO, + TCONVCONTEXT: CONVCONTEXT, TSECURITYQUALITYOFSERVICE: SECURITY_QUALITY_OF_SERVICE, + TCRITICAL_SECTION: TRTLCriticalSection, TCRITICALSECTIONDEBUG: CRITICAL_SECTION_DEBUG, + TDDEACK: DDEACK +].} const bm_DDEACK_bAppReturnCode* = 0x000000FF'i16 @@ -8086,8 +8042,8 @@ type flag0*: int16 cfFormat*: SHORT - TDDEADVISE* = DDEADVISE PDDEADVISE* = ptr DDEADVISE +{.deprecated: [TDDEADVISE: DDEADVISE].} const bm_DDEADVISE_reserved* = 0x00003FFF'i16 @@ -8138,8 +8094,8 @@ type flag0*: int16 cfFormat*: SHORT - TDDELN* = DDELN PDDELN* = ptr DDELN +{.deprecated: [TDDELN: DDELN].} const bm_DDELN_unused* = 0x00001FFF'i16 @@ -8166,15 +8122,14 @@ type cbData*: DWORD Data*: array[0..7, DWORD] - TDDEMLMSGHOOKDATA* = DDEML_MSG_HOOK_DATA PDDEMLMSGHOOKDATA* = ptr DDEML_MSG_HOOK_DATA DDEPOKE* {.final, pure.} = object flag0*: int16 cfFormat*: SHORT Value*: array[0..0, int8] - TDDEPOKE* = DDEPOKE PDDEPOKE* = ptr DDEPOKE +{.deprecated: [TDDEMLMSGHOOKDATA: DDEML_MSG_HOOK_DATA, TDDEPOKE: DDEPOKE].} const bm_DDEPOKE_unused* = 0x00001FFF'i16 @@ -8196,8 +8151,8 @@ type cfFormat*: SHORT rgb*: array[0..0, int8] - TDDEUP* = DDEUP PDDEUP* = ptr DDEUP +{.deprecated: [TDDEUP: DDEUP].} const bm_DDEUP_unused* = 0x00000FFF'i16 @@ -8232,13 +8187,11 @@ type ULONG_PTR] PEXCEPTION_RECORD* = ptr EXCEPTION_RECORD - TEXCEPTIONRECORD* = EXCEPTION_RECORD EXCEPTION_DEBUG_INFO* {.final, pure.} = object ExceptionRecord*: EXCEPTION_RECORD dwFirstChance*: DWORD PEXCEPTION_DEBUG_INFO* = ptr EXCEPTION_DEBUG_INFO - TEXCEPTIONDEBUGINFO* = EXCEPTION_DEBUG_INFO EXCEPTION_RECORD32* {.final, pure.} = object ExceptionCode*: DWORD ExceptionFlags*: DWORD @@ -8248,13 +8201,11 @@ type ExceptionInformation*: array[0..(EXCEPTION_MAXIMUM_PARAMETERS) - 1, DWORD] PEXCEPTION_RECORD32* = ptr EXCEPTION_RECORD32 - TExceptionRecord32* = EXCEPTION_RECORD32 EXCEPTION_DEBUG_INFO32* {.final, pure.} = object ExceptionRecord*: EXCEPTION_RECORD32 dwFirstChance*: DWORD PEXCEPTION_DEBUG_INFO32* = ptr EXCEPTION_DEBUG_INFO32 - TExceptionDebugInfo32* = EXCEPTION_DEBUG_INFO32 EXCEPTION_RECORD64* {.final, pure.} = object ExceptionCode*: DWORD ExceptionFlags*: DWORD @@ -8265,22 +8216,18 @@ type ExceptionInformation*: array[0..(EXCEPTION_MAXIMUM_PARAMETERS) - 1, DWORD64] PEXCEPTION_RECORD64* = ptr EXCEPTION_RECORD64 - TExceptionRecord64* = EXCEPTION_RECORD64 EXCEPTION_DEBUG_INFO64* {.final, pure.} = object ExceptionRecord*: EXCEPTION_RECORD64 dwFirstChance*: DWORD PEXCEPTION_DEBUG_INFO64* = ptr EXCEPTION_DEBUG_INFO64 - TExceptionDebugInfo64* = EXCEPTION_DEBUG_INFO64 EXIT_PROCESS_DEBUG_INFO* {.final, pure.} = object dwExitCode*: DWORD - TEXITPROCESSDEBUGINFO* = EXIT_PROCESS_DEBUG_INFO PEXITPROCESSDEBUGINFO* = ptr EXIT_PROCESS_DEBUG_INFO EXIT_THREAD_DEBUG_INFO* {.final, pure.} = object dwExitCode*: DWORD - TEXITTHREADDEBUGINFO* = EXIT_THREAD_DEBUG_INFO PEXITTHREADDEBUGINFO* = ptr EXIT_THREAD_DEBUG_INFO LOAD_DLL_DEBUG_INFO* {.final, pure.} = object hFile*: HANDLE @@ -8290,25 +8237,21 @@ type lpImageName*: LPVOID fUnicode*: int16 - TLOADDLLDEBUGINFO* = LOAD_DLL_DEBUG_INFO PLOADDLLDEBUGINFO* = ptr LOAD_DLL_DEBUG_INFO UNLOAD_DLL_DEBUG_INFO* {.final, pure.} = object lpBaseOfDll*: LPVOID - TUNLOADDLLDEBUGINFO* = UNLOAD_DLL_DEBUG_INFO PUNLOADDLLDEBUGINFO* = ptr UNLOAD_DLL_DEBUG_INFO OUTPUT_DEBUG_STRING_INFO* {.final, pure.} = object lpDebugStringData*: LPSTR fUnicode*: int16 nDebugStringLength*: int16 - TOUTPUTDEBUGSTRINGINFO* = OUTPUT_DEBUG_STRING_INFO POUTPUTDEBUGSTRINGINFO* = ptr OUTPUT_DEBUG_STRING_INFO RIP_INFO* {.final, pure.} = object dwError*: DWORD dwType*: DWORD - TRIPINFO* = RIP_INFO PRIPINFO* = ptr RIP_INFO DEBUG_EVENT* {.final, pure.} = object dwDebugEventCode*: DWORD @@ -8317,7 +8260,6 @@ type data*: array[0..15, DWORD] LPDEBUG_EVENT* = ptr DEBUG_EVENT - TDEBUGEVENT* = DEBUG_EVENT PDEBUGEVENT* = ptr DEBUG_EVENT DEBUGHOOKINFO* {.final, pure.} = object idThread*: DWORD @@ -8326,7 +8268,6 @@ type wParam*: WPARAM code*: int32 - TDEBUGHOOKINFO* = DEBUGHOOKINFO PDEBUGHOOKINFO* = ptr DEBUGHOOKINFO DELETEITEMSTRUCT* {.final, pure.} = object CtlType*: WINUINT @@ -8335,7 +8276,6 @@ type hwndItem*: HWND itemData*: ULONG_PTR - TDELETEITEMSTRUCT* = DELETEITEMSTRUCT PDELETEITEMSTRUCT* = ptr DELETEITEMSTRUCT DEV_BROADCAST_HDR* {.final, pure.} = object dbch_size*: ULONG @@ -8343,7 +8283,6 @@ type dbch_reserved*: ULONG PDEV_BROADCAST_HDR* = ptr DEV_BROADCAST_HDR - TDEVBROADCASTHDR* = DEV_BROADCAST_HDR DEV_BROADCAST_OEM* {.final, pure.} = object dbco_size*: ULONG dbco_devicetype*: ULONG @@ -8352,7 +8291,6 @@ type dbco_suppfunc*: ULONG PDEV_BROADCAST_OEM* = ptr DEV_BROADCAST_OEM - TDEVBROADCASTOEM* = DEV_BROADCAST_OEM DEV_BROADCAST_PORT* {.final, pure.} = object dbcp_size*: ULONG dbcp_devicetype*: ULONG @@ -8360,13 +8298,11 @@ type dbcp_name*: array[0..0, char] PDEV_BROADCAST_PORT* = ptr DEV_BROADCAST_PORT - TDEVBROADCASTPORT* = DEV_BROADCAST_PORT DEV_BROADCAST_USERDEFINED* {.final, pure.} = object dbud_dbh*: DEV_BROADCAST_HDR dbud_szName*: array[0..0, char] dbud_rgbUserDefined*: array[0..0, int8] - TDEVBROADCASTUSERDEFINED* = DEV_BROADCAST_USERDEFINED PDEVBROADCASTUSERDEFINED* = ptr DEV_BROADCAST_USERDEFINED DEV_BROADCAST_VOLUME* {.final, pure.} = object dbcv_size*: ULONG @@ -8376,7 +8312,6 @@ type dbcv_flags*: USHORT PDEV_BROADCAST_VOLUME* = ptr DEV_BROADCAST_VOLUME - TDEVBROADCASTVOLUME* = DEV_BROADCAST_VOLUME DEVMODE* {.final, pure.} = object dmDeviceName*: array[0..(CCHDEVICENAME) - 1, BCHAR] dmSpecVersion*: int16 @@ -8416,11 +8351,8 @@ type LPDEVMODE* = ptr DEVMODE Devicemode* = DEVMODE - TDevicemode* = DEVMODE - TDevicemodeA* = DEVMODE PDeviceModeA* = LPDEVMODE PDeviceMode* = LPDEVMODE - TDEVMODE* = DEVMODE PDEVMODE* = LPDEVMODE DEVMODEW* {.final, pure.} = object dmDeviceName*: array[0..CCHDEVICENAME - 1, WCHAR] @@ -8460,9 +8392,7 @@ type LPDEVMODEW* = ptr DEVMODEW DevicemodeW* = DEVMODEW - TDeviceModeW* = DEVMODEW PDeviceModeW* = LPDEVMODEW - TDEVMODEW* = DEVMODEW PDEVMODEW* = LPDEVMODEW DEVNAMES* {.final, pure.} = object wDriverOffset*: int16 @@ -8471,7 +8401,6 @@ type wDefault*: int16 LPDEVNAMES* = ptr DEVNAMES - TDEVNAMES* = DEVNAMES PDEVNAMES* = ptr DEVNAMES DIBSECTION* {.final, pure.} = object dsBm*: BITMAP @@ -8480,7 +8409,6 @@ type dshSection*: HANDLE dsOffset*: DWORD - TDIBSECTION* = DIBSECTION PDIBSECTION* = ptr DIBSECTION # # LARGE_INTEGER = record # case byte of @@ -8497,9 +8425,7 @@ type LARGE_INTEGER* = int64 ULARGE_INTEGER* = int64 PLARGE_INTEGER* = ptr LARGE_INTEGER - TLargeInteger* = int64 PULARGE_INTEGER* = ptr ULARGE_INTEGER - TULargeInteger* = int64 DISK_GEOMETRY* {.final, pure.} = object Cylinders*: LARGE_INTEGER MediaType*: MEDIA_TYPE @@ -8507,7 +8433,6 @@ type SectorsPerTrack*: DWORD BytesPerSector*: DWORD - TDISKGEOMETRY* = DISK_GEOMETRY PDISKGEOMETRY* = ptr DISK_GEOMETRY DISK_PERFORMANCE* {.final, pure.} = object BytesRead*: LARGE_INTEGER @@ -8518,7 +8443,6 @@ type WriteCount*: DWORD QueueDepth*: DWORD - TDISKPERFORMANCE* = DISK_PERFORMANCE PDISKPERFORMANCE* = ptr DISK_PERFORMANCE DLGITEMTEMPLATE* {.final, pure.} = object style*: DWORD @@ -8530,7 +8454,6 @@ type id*: int16 LPDLGITEMTEMPLATE* = ptr DLGITEMTEMPLATE - TDLGITEMTEMPLATE* = DLGITEMTEMPLATE PDLGITEMTEMPLATE* = ptr DLGITEMTEMPLATE DLGTEMPLATE* {.final, pure.} = object style*: DWORD @@ -8543,14 +8466,12 @@ type LPDLGTEMPLATE* = ptr DLGTEMPLATE LPCDLGTEMPLATE* = ptr DLGTEMPLATE - TDLGTEMPLATE* = DLGTEMPLATE PDLGTEMPLATE* = ptr DLGTEMPLATE DOC_INFO_1* {.final, pure.} = object pDocName*: LPTSTR pOutputFile*: LPTSTR pDatatype*: LPTSTR - TDOCINFO1* = DOC_INFO_1 PDOCINFO1* = ptr DOC_INFO_1 DOC_INFO_2* {.final, pure.} = object pDocName*: LPTSTR @@ -8559,7 +8480,6 @@ type dwMode*: DWORD JobId*: DWORD - TDOCINFO2* = DOC_INFO_2 PDOCINFO2* = ptr DOC_INFO_2 DOCINFO* {.final, pure.} = object cbSize*: int32 @@ -8568,8 +8488,6 @@ type lpszDatatype*: LPCTSTR fwType*: DWORD - TDOCINFO* = DOCINFO - TDOCINFOA* = DOCINFO PDOCINFO* = ptr DOCINFO DRAGLISTINFO* {.final, pure.} = object uNotification*: WINUINT @@ -8577,7 +8495,6 @@ type ptCursor*: POINT LPDRAGLISTINFO* = ptr DRAGLISTINFO - TDRAGLISTINFO* = DRAGLISTINFO PDRAGLISTINFO* = ptr DRAGLISTINFO DRAWITEMSTRUCT* {.final, pure.} = object CtlType*: WINUINT @@ -8591,7 +8508,6 @@ type itemData*: ULONG_PTR LPDRAWITEMSTRUCT* = ptr DRAWITEMSTRUCT - TDRAWITEMSTRUCT* = DRAWITEMSTRUCT PDRAWITEMSTRUCT* = ptr DRAWITEMSTRUCT DRAWTEXTPARAMS* {.final, pure.} = object cbSize*: WINUINT @@ -8601,7 +8517,6 @@ type uiLengthDrawn*: WINUINT LPDRAWTEXTPARAMS* = ptr DRAWTEXTPARAMS - TDRAWTEXTPARAMS* = DRAWTEXTPARAMS PDRAWTEXTPARAMS* = ptr DRAWTEXTPARAMS PARTITION_INFORMATION* {.final, pure.} = object PartitionType*: int8 @@ -8612,19 +8527,16 @@ type PartitionLength*: LARGE_INTEGER HiddenSectors*: LARGE_INTEGER - TPARTITIONINFORMATION* = PARTITION_INFORMATION PPARTITIONINFORMATION* = ptr PARTITION_INFORMATION DRIVE_LAYOUT_INFORMATION* {.final, pure.} = object PartitionCount*: DWORD Signature*: DWORD PartitionEntry*: array[0..0, PARTITION_INFORMATION] - TDRIVELAYOUTINFORMATION* = DRIVE_LAYOUT_INFORMATION PDRIVELAYOUTINFORMATION* = ptr DRIVE_LAYOUT_INFORMATION DRIVER_INFO_1* {.final, pure.} = object pName*: LPTSTR - TDRIVERINFO1* = DRIVER_INFO_1 PDRIVERINFO1* = ptr DRIVER_INFO_1 DRIVER_INFO_2* {.final, pure.} = object cVersion*: DWORD @@ -8634,7 +8546,6 @@ type pDataFile*: LPTSTR pConfigFile*: LPTSTR - TDRIVERINFO2* = DRIVER_INFO_2 PDRIVERINFO2* = ptr DRIVER_INFO_2 DRIVER_INFO_3* {.final, pure.} = object cVersion*: DWORD @@ -8648,20 +8559,17 @@ type pMonitorName*: LPTSTR pDefaultDataType*: LPTSTR - TDRIVERINFO3* = DRIVER_INFO_3 PDRIVERINFO3* = ptr DRIVER_INFO_3 EDITSTREAM* {.final, pure.} = object dwCookie*: DWORD dwError*: DWORD pfnCallback*: EDITSTREAMCALLBACK - Teditstream* = EDITSTREAM Peditstream* = ptr EDITSTREAM EMR* {.final, pure.} = object iType*: DWORD nSize*: DWORD - TEMR* = EMR PEMR* = ptr EMR EMRANGLEARC* {.final, pure.} = object emr*: EMR @@ -8670,7 +8578,6 @@ type eStartAngle*: float32 eSweepAngle*: float32 - TEMRANGLEARC* = EMRANGLEARC PEMRANGLEARC* = ptr EMRANGLEARC EMRARC* {.final, pure.} = object emr*: EMR @@ -8678,16 +8585,12 @@ type ptlStart*: POINTL ptlEnd*: POINTL - TEMRARC* = EMRARC PEMRARC* = ptr EMRARC EMRARCTO* = EMRARC - TEMRARCTO* = EMRARC PEMRARCTO* = ptr EMRARC EMRCHORD* = EMRARC - TEMRCHORD* = EMRARC PEMRCHORD* = ptr EMRARC EMRPIE* = EMRARC - TEMRPIE* = EMRARC PEMRPIE* = ptr EMRARC XFORM* {.final, pure.} = object eM11*: float32 @@ -8698,7 +8601,6 @@ type eDy*: float32 LPXFORM* = ptr XFORM - TXFORM* = XFORM PXFORM* = ptr XFORM EMRBITBLT* {.final, pure.} = object emr*: EMR @@ -8717,21 +8619,18 @@ type offBitsSrc*: DWORD cbBitsSrc*: DWORD - TEMRBITBLT* = EMRBITBLT PEMRBITBLT* = ptr EMRBITBLT LOGBRUSH* {.final, pure.} = object lbStyle*: WINUINT lbColor*: COLORREF lbHatch*: LONG - TLOGBRUSH* = LOGBRUSH PLOGBRUSH* = ptr LOGBRUSH EMRCREATEBRUSHINDIRECT* {.final, pure.} = object emr*: EMR ihBrush*: DWORD lb*: LOGBRUSH - TEMRCREATEBRUSHINDIRECT* = EMRCREATEBRUSHINDIRECT PEMRCREATEBRUSHINDIRECT* = ptr EMRCREATEBRUSHINDIRECT LCSCSTYPE* = LONG LCSGAMUTMATCH* = LONG @@ -8745,18 +8644,15 @@ type lcsGammaRed*: DWORD lcsGammaGreen*: DWORD lcsGammaBlue*: DWORD - lcsFilename*: array[0..(MAX_PATH) - 1, TCHAR] + lcsFilename*: array[0..(MAX_PATH) - 1, CHAR] LPLOGCOLORSPACE* = ptr LOGCOLORSPACE - TLOGCOLORSPACE* = LOGCOLORSPACE - TLOGCOLORSPACEA* = LOGCOLORSPACE PLOGCOLORSPACE* = ptr LOGCOLORSPACE EMRCREATECOLORSPACE* {.final, pure.} = object emr*: EMR ihCS*: DWORD lcs*: LOGCOLORSPACE - TEMRCREATECOLORSPACE* = EMRCREATECOLORSPACE PEMRCREATECOLORSPACE* = ptr EMRCREATECOLORSPACE EMRCREATEDIBPATTERNBRUSHPT* {.final, pure.} = object emr*: EMR @@ -8767,7 +8663,6 @@ type offBits*: DWORD cbBits*: DWORD - TEMRCREATEDIBPATTERNBRUSHPT* = EMRCREATEDIBPATTERNBRUSHPT PEMRCREATEDIBPATTERNBRUSHPT* = EMRCREATEDIBPATTERNBRUSHPT EMRCREATEMONOBRUSH* {.final, pure.} = object emr*: EMR @@ -8778,7 +8673,6 @@ type offBits*: DWORD cbBits*: DWORD - TEMRCREATEMONOBRUSH* = EMRCREATEMONOBRUSH PEMRCREATEMONOBRUSH* = ptr EMRCREATEMONOBRUSH PALETTEENTRY* {.final, pure.} = object peRed*: int8 @@ -8787,7 +8681,6 @@ type peFlags*: int8 LPPALETTEENTRY* = ptr PALETTEENTRY - TPALETTEENTRY* = PALETTEENTRY PPALETTEENTRY* = ptr PALETTEENTRY LOGPALETTE* {.final, pure.} = object palVersion*: int16 @@ -8796,37 +8689,31 @@ type LPLOGPALETTE* = ptr LOGPALETTE NPLOGPALETTE* = ptr LOGPALETTE - TLOGPALETTE* = LOGPALETTE PLOGPALETTE* = ptr LOGPALETTE EMRCREATEPALETTE* {.final, pure.} = object emr*: EMR ihPal*: DWORD lgpl*: LOGPALETTE - TEMRCREATEPALETTE* = EMRCREATEPALETTE PEMRCREATEPALETTE* = ptr EMRCREATEPALETTE LOGPEN* {.final, pure.} = object lopnStyle*: WINUINT lopnWidth*: POINT lopnColor*: COLORREF - TLOGPEN* = LOGPEN PLOGPEN* = ptr LOGPEN EMRCREATEPEN* {.final, pure.} = object emr*: EMR ihPen*: DWORD lopn*: LOGPEN - TEMRCREATEPEN* = EMRCREATEPEN PEMRCREATEPEN* = ptr EMRCREATEPEN EMRELLIPSE* {.final, pure.} = object emr*: EMR rclBox*: RECTL - TEMRELLIPSE* = EMRELLIPSE PEMRELLIPSE* = ptr EMRELLIPSE EMRRECTANGLE* = EMRELLIPSE - TEMRRECTANGLE* = EMRELLIPSE PEMRRECTANGLE* = ptr EMRELLIPSE EMREOF* {.final, pure.} = object emr*: EMR @@ -8834,16 +8721,13 @@ type offPalEntries*: DWORD nSizeLast*: DWORD - TEMREOF* = EMREOF PEMREOF* = ptr EMREOF EMREXCLUDECLIPRECT* {.final, pure.} = object emr*: EMR rclClip*: RECTL - TEMREXCLUDECLIPRECT* = EMREXCLUDECLIPRECT PEMREXCLUDECLIPRECT* = ptr EMREXCLUDECLIPRECT EMRINTERSECTCLIPRECT* = EMREXCLUDECLIPRECT - TEMRINTERSECTCLIPRECT* = EMREXCLUDECLIPRECT PEMRINTERSECTCLIPRECT* = ptr EMREXCLUDECLIPRECT PANOSE* {.final, pure.} = object bFamilyType*: int8 @@ -8857,7 +8741,6 @@ type bMidline*: int8 bXHeight*: int8 - TPANOSE* = PANOSE PPANOSE* = ptr PANOSE EXTLOGFONT* {.final, pure.} = object elfLogFont*: LOGFONT @@ -8871,14 +8754,12 @@ type elfCulture*: DWORD elfPanose*: PANOSE - TEXTLOGFONT* = EXTLOGFONT PEXTLOGFONT* = ptr EXTLOGFONT EMREXTCREATEFONTINDIRECTW* {.final, pure.} = object emr*: EMR ihFont*: DWORD elfw*: EXTLOGFONT - TEMREXTCREATEFONTINDIRECTW* = EMREXTCREATEFONTINDIRECTW PEMREXTCREATEFONTINDIRECTW* = ptr EMREXTCREATEFONTINDIRECTW EXTLOGPEN* {.final, pure.} = object elpPenStyle*: WINUINT @@ -8889,7 +8770,6 @@ type elpNumEntries*: DWORD elpStyleEntry*: array[0..0, DWORD] - TEXTLOGPEN* = EXTLOGPEN PEXTLOGPEN* = ptr EXTLOGPEN EMREXTCREATEPEN* {.final, pure.} = object emr*: EMR @@ -8900,7 +8780,6 @@ type cbBits*: DWORD elp*: EXTLOGPEN - TEMREXTCREATEPEN* = EMREXTCREATEPEN PEMREXTCREATEPEN* = ptr EMREXTCREATEPEN EMREXTFLOODFILL* {.final, pure.} = object emr*: EMR @@ -8908,7 +8787,6 @@ type crColor*: COLORREF iMode*: DWORD - TEMREXTFLOODFILL* = EMREXTFLOODFILL PEMREXTFLOODFILL* = ptr EMREXTFLOODFILL EMREXTSELECTCLIPRGN* {.final, pure.} = object emr*: EMR @@ -8916,7 +8794,6 @@ type iMode*: DWORD RgnData*: array[0..0, int8] - TEMREXTSELECTCLIPRGN* = EMREXTSELECTCLIPRGN PEMREXTSELECTCLIPRGN* = ptr EMREXTSELECTCLIPRGN EMRTEXT* {.final, pure.} = object ptlReference*: POINTL @@ -8926,7 +8803,6 @@ type rcl*: RECTL offDx*: DWORD - TEMRTEXT* = EMRTEXT PEMRTEXT* = ptr EMRTEXT EMREXTTEXTOUTA* {.final, pure.} = object emr*: EMR @@ -8936,22 +8812,17 @@ type eyScale*: float32 emrtext*: EMRTEXT - TEMREXTTEXTOUTA* = EMREXTTEXTOUTA PEMREXTTEXTOUTA* = ptr EMREXTTEXTOUTA EMREXTTEXTOUTW* = EMREXTTEXTOUTA - TEMREXTTEXTOUTW* = EMREXTTEXTOUTA PEMREXTTEXTOUTW* = ptr EMREXTTEXTOUTA EMRFILLPATH* {.final, pure.} = object emr*: EMR rclBounds*: RECTL - TEMRFILLPATH* = EMRFILLPATH PEMRFILLPATH* = ptr EMRFILLPATH EMRSTROKEANDFILLPATH* = EMRFILLPATH - TEMRSTROKEANDFILLPATH* = EMRFILLPATH PEMRSTROKEANDFILLPATH* = ptr EMRFILLPATH EMRSTROKEPATH* = EMRFILLPATH - TEMRSTROKEPATH* = EMRFILLPATH PEMRSTROKEPATH* = ptr EMRFILLPATH EMRFILLRGN* {.final, pure.} = object emr*: EMR @@ -8960,7 +8831,6 @@ type ihBrush*: DWORD RgnData*: array[0..0, int8] - TEMRFILLRGN* = EMRFILLRGN PEMRFILLRGN* = ptr EMRFILLRGN EMRFORMAT* {.final, pure.} = object dSignature*: DWORD @@ -8968,7 +8838,6 @@ type cbData*: DWORD offData*: DWORD - TEMRFORMAT* = EMRFORMAT PEMRFORMAT* = ptr EMRFORMAT EMRFRAMERGN* {.final, pure.} = object @@ -8979,14 +8848,12 @@ type szlStroke*: SIZEL RgnData*: array[0..0, int8] - TEMRFRAMERGN* = EMRFRAMERGN PEMRFRAMERGN* = ptr EMRFRAMERGN EMRGDICOMMENT* {.final, pure.} = object emr*: EMR cbData*: DWORD Data*: array[0..0, int8] - TEMRGDICOMMENT* = EMRGDICOMMENT PEMRGDICOMMENT* = ptr EMRGDICOMMENT EMRINVERTRGN* {.final, pure.} = object emr*: EMR @@ -8994,19 +8861,15 @@ type cbRgnData*: DWORD RgnData*: array[0..0, int8] - TEMRINVERTRGN* = EMRINVERTRGN PEMRINVERTRGN* = ptr EMRINVERTRGN EMRPAINTRGN* = EMRINVERTRGN - TEMRPAINTRGN* = EMRINVERTRGN PEMRPAINTRGN* = ptr EMRINVERTRGN EMRLINETO* {.final, pure.} = object emr*: EMR ptl*: POINTL - TEMRLINETO* = EMRLINETO PEMRLINETO* = ptr EMRLINETO EMRMOVETOEX* = EMRLINETO - TEMRMOVETOEX* = EMRLINETO PEMRMOVETOEX* = ptr EMRLINETO EMRMASKBLT* {.final, pure.} = object emr*: EMR @@ -9033,20 +8896,17 @@ type offBitsMask*: DWORD cbBitsMask*: DWORD - TEMRMASKBLT* = EMRMASKBLT PEMRMASKBLT* = ptr EMRMASKBLT EMRMODIFYWORLDTRANSFORM* {.final, pure.} = object emr*: EMR xform*: XFORM iMode*: DWORD - TEMRMODIFYWORLDTRANSFORM* = EMRMODIFYWORLDTRANSFORM PEMRMODIFYWORLDTRANSFORM* = EMRMODIFYWORLDTRANSFORM EMROFFSETCLIPRGN* {.final, pure.} = object emr*: EMR ptlOffset*: POINTL - TEMROFFSETCLIPRGN* = EMROFFSETCLIPRGN PEMROFFSETCLIPRGN* = ptr EMROFFSETCLIPRGN EMRPLGBLT* {.final, pure.} = object emr*: EMR @@ -9071,7 +8931,6 @@ type offBitsMask*: DWORD cbBitsMask*: DWORD - TEMRPLGBLT* = EMRPLGBLT PEMRPLGBLT* = ptr EMRPLGBLT EMRPOLYDRAW* {.final, pure.} = object emr*: EMR @@ -9080,7 +8939,6 @@ type aptl*: array[0..0, POINTL] abTypes*: array[0..0, int8] - TEMRPOLYDRAW* = EMRPOLYDRAW PEMRPOLYDRAW* = ptr EMRPOLYDRAW EMRPOLYDRAW16* {.final, pure.} = object emr*: EMR @@ -9089,7 +8947,6 @@ type apts*: array[0..0, POINTS] abTypes*: array[0..0, int8] - TEMRPOLYDRAW16* = EMRPOLYDRAW16 PEMRPOLYDRAW16* = ptr EMRPOLYDRAW16 EMRPOLYLINE* {.final, pure.} = object emr*: EMR @@ -9097,19 +8954,14 @@ type cptl*: DWORD aptl*: array[0..0, POINTL] - TEMRPOLYLINE* = EMRPOLYLINE PEMRPOLYLINE* = ptr EMRPOLYLINE EMRPOLYBEZIER* = EMRPOLYLINE - TEMRPOLYBEZIER* = EMRPOLYLINE PEMRPOLYBEZIER* = ptr EMRPOLYLINE EMRPOLYGON* = EMRPOLYLINE - TEMRPOLYGON* = EMRPOLYLINE PEMRPOLYGON* = ptr EMRPOLYLINE EMRPOLYBEZIERTO* = EMRPOLYLINE - TEMRPOLYBEZIERTO* = EMRPOLYLINE PEMRPOLYBEZIERTO* = ptr EMRPOLYLINE EMRPOLYLINETO* = EMRPOLYLINE - TEMRPOLYLINETO* = EMRPOLYLINE PEMRPOLYLINETO* = ptr EMRPOLYLINE EMRPOLYLINE16* {.final, pure.} = object emr*: EMR @@ -9117,19 +8969,14 @@ type cpts*: DWORD apts*: array[0..0, POINTL] - TEMRPOLYLINE16* = EMRPOLYLINE16 PEMRPOLYLINE16* = ptr EMRPOLYLINE16 EMRPOLYBEZIER16* = EMRPOLYLINE16 - TEMRPOLYBEZIER16* = EMRPOLYLINE16 PEMRPOLYBEZIER16* = ptr EMRPOLYLINE16 EMRPOLYGON16* = EMRPOLYLINE16 - TEMRPOLYGON16* = EMRPOLYLINE16 PEMRPOLYGON16* = ptr EMRPOLYLINE16 EMRPOLYBEZIERTO16* = EMRPOLYLINE16 - TEMRPOLYBEZIERTO16* = EMRPOLYLINE16 PEMRPOLYBEZIERTO16* = ptr EMRPOLYLINE16 EMRPOLYLINETO16* = EMRPOLYLINE16 - TEMRPOLYLINETO16* = EMRPOLYLINE16 PEMRPOLYLINETO16* = ptr EMRPOLYLINE16 EMRPOLYPOLYLINE* {.final, pure.} = object emr*: EMR @@ -9139,10 +8986,8 @@ type aPolyCounts*: array[0..0, DWORD] aptl*: array[0..0, POINTL] - TEMRPOLYPOLYLINE* = EMRPOLYPOLYLINE PEMRPOLYPOLYLINE* = ptr EMRPOLYPOLYLINE EMRPOLYPOLYGON* = EMRPOLYPOLYLINE - TEMRPOLYPOLYGON* = EMRPOLYPOLYLINE PEMRPOLYPOLYGON* = ptr EMRPOLYPOLYLINE EMRPOLYPOLYLINE16* {.final, pure.} = object emr*: EMR @@ -9152,10 +8997,8 @@ type aPolyCounts*: array[0..0, DWORD] apts*: array[0..0, POINTS] - TEMRPOLYPOLYLINE16* = EMRPOLYPOLYLINE16 PEMRPOLYPOLYLINE16* = ptr EMRPOLYPOLYLINE16 EMRPOLYPOLYGON16* = EMRPOLYPOLYLINE16 - TEMRPOLYPOLYGON16* = EMRPOLYPOLYLINE16 PEMRPOLYPOLYGON16* = ptr EMRPOLYPOLYLINE16 EMRPOLYTEXTOUTA* {.final, pure.} = object emr*: EMR @@ -9166,30 +9009,25 @@ type cStrings*: LONG aemrtext*: array[0..0, EMRTEXT] - TEMRPOLYTEXTOUTA* = EMRPOLYTEXTOUTA PEMRPOLYTEXTOUTA* = ptr EMRPOLYTEXTOUTA EMRPOLYTEXTOUTW* = EMRPOLYTEXTOUTA - TEMRPOLYTEXTOUTW* = EMRPOLYTEXTOUTA PEMRPOLYTEXTOUTW* = ptr EMRPOLYTEXTOUTA EMRRESIZEPALETTE* {.final, pure.} = object emr*: EMR ihPal*: DWORD cEntries*: DWORD - TEMRRESIZEPALETTE* = EMRRESIZEPALETTE PEMRRESIZEPALETTE* = ptr EMRRESIZEPALETTE EMRRESTOREDC* {.final, pure.} = object emr*: EMR iRelative*: LONG - TEMRRESTOREDC* = EMRRESTOREDC PEMRRESTOREDC* = ptr EMRRESTOREDC EMRROUNDRECT* {.final, pure.} = object emr*: EMR rclBox*: RECTL szlCorner*: SIZEL - TEMRROUNDRECT* = EMRROUNDRECT PEMRROUNDRECT* = ptr EMRROUNDRECT EMRSCALEVIEWPORTEXTEX* {.final, pure.} = object emr*: EMR @@ -9198,56 +9036,45 @@ type yNum*: LONG yDenom*: LONG - TEMRSCALEVIEWPORTEXTEX* = EMRSCALEVIEWPORTEXTEX PEMRSCALEVIEWPORTEXTEX* = ptr EMRSCALEVIEWPORTEXTEX EMRSCALEWINDOWEXTEX* = EMRSCALEVIEWPORTEXTEX - TEMRSCALEWINDOWEXTEX* = EMRSCALEVIEWPORTEXTEX PEMRSCALEWINDOWEXTEX* = ptr EMRSCALEVIEWPORTEXTEX EMRSELECTCOLORSPACE* {.final, pure.} = object emr*: EMR ihCS*: DWORD - TEMRSELECTCOLORSPACE* = EMRSELECTCOLORSPACE PEMRSELECTCOLORSPACE* = ptr EMRSELECTCOLORSPACE EMRDELETECOLORSPACE* = EMRSELECTCOLORSPACE - TEMRDELETECOLORSPACE* = EMRSELECTCOLORSPACE PEMRDELETECOLORSPACE* = ptr EMRSELECTCOLORSPACE EMRSELECTOBJECT* {.final, pure.} = object emr*: EMR ihObject*: DWORD - TEMRSELECTOBJECT* = EMRSELECTOBJECT PEMRSELECTOBJECT* = ptr EMRSELECTOBJECT EMRDELETEOBJECT* = EMRSELECTOBJECT - TEMRDELETEOBJECT* = EMRSELECTOBJECT PEMRDELETEOBJECT* = ptr EMRSELECTOBJECT EMRSELECTPALETTE* {.final, pure.} = object emr*: EMR ihPal*: DWORD - TEMRSELECTPALETTE* = EMRSELECTPALETTE PEMRSELECTPALETTE* = ptr EMRSELECTPALETTE EMRSETARCDIRECTION* {.final, pure.} = object emr*: EMR iArcDirection*: DWORD - TEMRSETARCDIRECTION* = EMRSETARCDIRECTION PEMRSETARCDIRECTION* = ptr EMRSETARCDIRECTION EMRSETBKCOLOR* {.final, pure.} = object emr*: EMR crColor*: COLORREF - TEMRSETBKCOLOR* = EMRSETBKCOLOR PEMRSETBKCOLOR* = ptr EMRSETBKCOLOR EMRSETTEXTCOLOR* = EMRSETBKCOLOR - TEMRSETTEXTCOLOR* = EMRSETBKCOLOR PEMRSETTEXTCOLOR* = ptr EMRSETBKCOLOR EMRSETCOLORADJUSTMENT* {.final, pure.} = object emr*: EMR ColorAdjustment*: COLORADJUSTMENT - TEMRSETCOLORADJUSTMENT* = EMRSETCOLORADJUSTMENT PEMRSETCOLORADJUSTMENT* = ptr EMRSETCOLORADJUSTMENT EMRSETDIBITSTODEVICE* {.final, pure.} = object emr*: EMR @@ -9266,19 +9093,16 @@ type iStartScan*: DWORD cScans*: DWORD - TEMRSETDIBITSTODEVICE* = EMRSETDIBITSTODEVICE PEMRSETDIBITSTODEVICE* = ptr EMRSETDIBITSTODEVICE EMRSETMAPPERFLAGS* {.final, pure.} = object emr*: EMR dwFlags*: DWORD - TEMRSETMAPPERFLAGS* = EMRSETMAPPERFLAGS PEMRSETMAPPERFLAGS* = ptr EMRSETMAPPERFLAGS EMRSETMITERLIMIT* {.final, pure.} = object emr*: EMR eMiterLimit*: float32 - TEMRSETMITERLIMIT* = EMRSETMITERLIMIT PEMRSETMITERLIMIT* = ptr EMRSETMITERLIMIT EMRSETPALETTEENTRIES* {.final, pure.} = object emr*: EMR @@ -9287,41 +9111,33 @@ type cEntries*: DWORD aPalEntries*: array[0..0, PALETTEENTRY] - TEMRSETPALETTEENTRIES* = EMRSETPALETTEENTRIES PEMRSETPALETTEENTRIES* = ptr EMRSETPALETTEENTRIES EMRSETPIXELV* {.final, pure.} = object emr*: EMR ptlPixel*: POINTL crColor*: COLORREF - TEMRSETPIXELV* = EMRSETPIXELV PEMRSETPIXELV* = ptr EMRSETPIXELV EMRSETVIEWPORTEXTEX* {.final, pure.} = object emr*: EMR szlExtent*: SIZEL - TEMRSETVIEWPORTEXTEX* = EMRSETVIEWPORTEXTEX PEMRSETVIEWPORTEXTEX* = ptr EMRSETVIEWPORTEXTEX EMRSETWINDOWEXTEX* = EMRSETVIEWPORTEXTEX - TEMRSETWINDOWEXTEX* = EMRSETVIEWPORTEXTEX PEMRSETWINDOWEXTEX* = ptr EMRSETVIEWPORTEXTEX EMRSETVIEWPORTORGEX* {.final, pure.} = object emr*: EMR ptlOrigin*: POINTL - TEMRSETVIEWPORTORGEX* = EMRSETVIEWPORTORGEX PEMRSETVIEWPORTORGEX* = ptr EMRSETVIEWPORTORGEX EMRSETWINDOWORGEX* = EMRSETVIEWPORTORGEX - TEMRSETWINDOWORGEX* = EMRSETVIEWPORTORGEX PEMRSETWINDOWORGEX* = ptr EMRSETVIEWPORTORGEX EMRSETBRUSHORGEX* = EMRSETVIEWPORTORGEX - TEMRSETBRUSHORGEX* = EMRSETVIEWPORTORGEX PEMRSETBRUSHORGEX* = ptr EMRSETVIEWPORTORGEX EMRSETWORLDTRANSFORM* {.final, pure.} = object emr*: EMR xform*: XFORM - TEMRSETWORLDTRANSFORM* = EMRSETWORLDTRANSFORM PEMRSETWORLDTRANSFORM* = ptr EMRSETWORLDTRANSFORM EMRSTRETCHBLT* {.final, pure.} = object emr*: EMR @@ -9343,7 +9159,6 @@ type cxSrc*: LONG cySrc*: LONG - TEMRSTRETCHBLT* = EMRSTRETCHBLT PEMRSTRETCHBLT* = ptr EMRSTRETCHBLT EMRSTRETCHDIBITS* {.final, pure.} = object emr*: EMR @@ -9363,99 +9178,79 @@ type cxDest*: LONG cyDest*: LONG - TEMRSTRETCHDIBITS* = EMRSTRETCHDIBITS PEMRSTRETCHDIBITS* = ptr EMRSTRETCHDIBITS EMRABORTPATH* {.final, pure.} = object emr*: EMR - TEMRABORTPATH* = EMRABORTPATH PEMRABORTPATH* = ptr EMRABORTPATH - TABORTPATH* = EMRABORTPATH EMRBEGINPATH* = EMRABORTPATH - TEMRBEGINPATH* = EMRABORTPATH PEMRBEGINPATH* = ptr EMRABORTPATH EMRENDPATH* = EMRABORTPATH - TEMRENDPATH* = EMRABORTPATH PEMRENDPATH* = ptr EMRABORTPATH EMRCLOSEFIGURE* = EMRABORTPATH - TEMRCLOSEFIGURE* = EMRABORTPATH PEMRCLOSEFIGURE* = ptr EMRABORTPATH EMRFLATTENPATH* = EMRABORTPATH - TEMRFLATTENPATH* = EMRABORTPATH PEMRFLATTENPATH* = ptr EMRABORTPATH EMRWIDENPATH* = EMRABORTPATH - TEMRWIDENPATH* = EMRABORTPATH PEMRWIDENPATH* = ptr EMRABORTPATH EMRSETMETARGN* = EMRABORTPATH - TEMRSETMETARGN* = EMRABORTPATH PEMRSETMETARGN* = ptr EMRABORTPATH EMRSAVEDC* = EMRABORTPATH - TEMRSAVEDC* = EMRABORTPATH PEMRSAVEDC* = ptr EMRABORTPATH EMRREALIZEPALETTE* = EMRABORTPATH - TEMRREALIZEPALETTE* = EMRABORTPATH PEMRREALIZEPALETTE* = ptr EMRABORTPATH EMRSELECTCLIPPATH* {.final, pure.} = object emr*: EMR iMode*: DWORD - TEMRSELECTCLIPPATH* = EMRSELECTCLIPPATH PEMRSELECTCLIPPATH* = ptr EMRSELECTCLIPPATH EMRSETBKMODE* = EMRSELECTCLIPPATH - TEMRSETBKMODE* = EMRSELECTCLIPPATH PEMRSETBKMODE* = ptr EMRSELECTCLIPPATH EMRSETMAPMODE* = EMRSELECTCLIPPATH - TEMRSETMAPMODE* = EMRSELECTCLIPPATH PEMRSETMAPMODE* = ptr EMRSELECTCLIPPATH EMRSETPOLYFILLMODE* = EMRSELECTCLIPPATH - TEMRSETPOLYFILLMODE* = EMRSELECTCLIPPATH PEMRSETPOLYFILLMODE* = ptr EMRSELECTCLIPPATH EMRSETROP2* = EMRSELECTCLIPPATH - TEMRSETROP2* = EMRSELECTCLIPPATH PEMRSETROP2* = ptr EMRSELECTCLIPPATH EMRSETSTRETCHBLTMODE* = EMRSELECTCLIPPATH - TEMRSETSTRETCHBLTMODE* = EMRSELECTCLIPPATH PEMRSETSTRETCHBLTMODE* = ptr EMRSELECTCLIPPATH EMRSETTEXTALIGN* = EMRSELECTCLIPPATH - TEMRSETTEXTALIGN* = EMRSELECTCLIPPATH PEMRSETTEXTALIGN* = ptr EMRSELECTCLIPPATH EMRENABLEICM* = EMRSELECTCLIPPATH - TEMRENABLEICM* = EMRSELECTCLIPPATH PEMRENABLEICM* = ptr EMRSELECTCLIPPATH NMHDR* {.final, pure.} = object hwndFrom*: HWND idFrom*: WINUINT code*: WINUINT - TNMHDR* = NMHDR PNMHDR* = ptr NMHDR - TENCORRECTTEXT* {.final, pure.} = object + TENCORRECTTEXT* {.final, pure.} = object # Name conflict if we drop the `T` nmhdr*: NMHDR chrg*: CHARRANGE seltyp*: int16 Pencorrecttext* = ptr TENCORRECTTEXT - TENDROPFILES* {.final, pure.} = object + TENDROPFILES* {.final, pure.} = object # Name conflict if we drop the `T` nmhdr*: NMHDR hDrop*: HANDLE cp*: LONG fProtected*: WINBOOL Pendropfiles* = ptr TENDROPFILES - TENSAVECLIPBOARD* {.final, pure.} = object + TENSAVECLIPBOARD* {.final, pure.} = object # Name conflict if we drop the `T` nmhdr*: NMHDR cObjectCount*: LONG cch*: LONG PENSAVECLIPBOARD* = ptr TENSAVECLIPBOARD - TENOLEOPFAILED* {.final, pure.} = object + TENOLEOPFAILED* {.final, pure.} = object # Name conflict if we drop the `T` nmhdr*: NMHDR iob*: LONG lOper*: LONG hr*: HRESULT PENOLEOPFAILED* = ptr TENOLEOPFAILED - TENHMETAHEADER* {.final, pure.} = object + ENHMETAHEADER* {.final, pure.} = object iType*: DWORD nSize*: DWORD rclBounds*: RECTL @@ -9472,16 +9267,16 @@ type szlDevice*: SIZEL szlMillimeters*: SIZEL - LPENHMETAHEADER* = ptr TENHMETAHEADER - PENHMETAHEADER* = ptr TENHMETAHEADER - TENHMETARECORD* {.final, pure.} = object + LPENHMETAHEADER* = ptr ENHMETAHEADER + PENHMETAHEADER* = ptr ENHMETAHEADER + ENHMETARECORD* {.final, pure.} = object iType*: DWORD nSize*: DWORD dParm*: array[0..0, DWORD] - LPENHMETARECORD* = ptr TENHMETARECORD - PENHMETARECORD* = ptr TENHMETARECORD - TENPROTECTED* {.final, pure.} = object + LPENHMETARECORD* = ptr ENHMETARECORD + PENHMETARECORD* = ptr ENHMETARECORD + TENPROTECTED* {.final, pure.} = object # Name conflict if we drop the `T` nmhdr*: NMHDR msg*: WINUINT wParam*: WPARAM @@ -9499,7 +9294,6 @@ type dwWaitHint*: DWORD LPSERVICE_STATUS* = ptr SERVICE_STATUS - TSERVICESTATUS* = SERVICE_STATUS PSERVICESTATUS* = ptr SERVICE_STATUS ENUM_SERVICE_STATUS* {.final, pure.} = object lpServiceName*: LPTSTR @@ -9507,14 +9301,12 @@ type ServiceStatus*: SERVICE_STATUS LPENUM_SERVICE_STATUS* = ptr ENUM_SERVICE_STATUS - TENUMSERVICESTATUS* = ENUM_SERVICE_STATUS PENUMSERVICESTATUS* = ptr ENUM_SERVICE_STATUS ENUMLOGFONT* {.final, pure.} = object elfLogFont*: LOGFONT elfFullName*: array[0..(LF_FULLFACESIZE) - 1, BCHAR] elfStyle*: array[0..(LF_FACESIZE) - 1, BCHAR] - TENUMLOGFONT* = ENUMLOGFONT PENUMLOGFONT* = ptr ENUMLOGFONT ENUMLOGFONTEX* {.final, pure.} = object elfLogFont*: LOGFONT @@ -9522,7 +9314,6 @@ type elfStyle*: array[0..(LF_FACESIZE) - 1, BCHAR] elfScript*: array[0..(LF_FACESIZE) - 1, BCHAR] - TENUMLOGFONTEX* = ENUMLOGFONTEX PENUMLOGFONTEX* = ptr ENUMLOGFONTEX EVENTLOGRECORD* {.final, pure.} = object @@ -9543,7 +9334,6 @@ type DataLength*: DWORD DataOffset*: DWORD - TEVENTLOGRECORD* = EVENTLOGRECORD PEVENTLOGRECORD* = ptr EVENTLOGRECORD EVENTMSG* {.final, pure.} = object message*: WINUINT @@ -9552,7 +9342,6 @@ type time*: DWORD hwnd*: HWND - TEVENTMSG* = EVENTMSG PEVENTMSG* = ptr EVENTMSG EXCEPTION_POINTERS* {.final, pure.} = object ExceptionRecord*: PEXCEPTION_RECORD @@ -9560,14 +9349,12 @@ type LPEXCEPTION_POINTERS* = ptr EXCEPTION_POINTERS PEXCEPTION_POINTERS* = ptr EXCEPTION_POINTERS - TEXCEPTIONPOINTERS* = EXCEPTION_POINTERS EXT_BUTTON* {.final, pure.} = object idCommand*: int16 idsHelp*: int16 fsStyle*: int16 LPEXT_BUTTON* = ptr EXT_BUTTON - TEXTBUTTON* = EXT_BUTTON PEXTBUTTON* = ptr EXT_BUTTON FILTERKEYS* {.final, pure.} = object cbSize*: WINUINT @@ -9577,7 +9364,6 @@ type iRepeatMSec*: DWORD iBounceMSec*: DWORD - TFILTERKEYS* = FILTERKEYS PFILTERKEYS* = ptr FILTERKEYS FIND_NAME_BUFFER* {.final, pure.} = object len*: UCHAR @@ -9587,14 +9373,12 @@ type source_addr*: array[0..5, UCHAR] routing_info*: array[0..17, UCHAR] - TFINDNAMEBUFFER* = FIND_NAME_BUFFER PFINDNAMEBUFFER* = ptr FIND_NAME_BUFFER FIND_NAME_HEADER* {.final, pure.} = object node_count*: int16 reserved*: UCHAR unique_group*: UCHAR - TFINDNAMEHEADER* = FIND_NAME_HEADER PFINDNAMEHEADER* = ptr FIND_NAME_HEADER FINDREPLACE* {.final, pure.} = object lStructSize*: DWORD @@ -9610,7 +9394,6 @@ type lpTemplateName*: LPCTSTR LPFINDREPLACE* = ptr FINDREPLACE - TFINDREPLACE* = FINDREPLACE PFINDREPLACE* = ptr FINDREPLACE #FINDTEXT = record conflicts with FindText function TFINDTEXT* {.final, pure.} = object @@ -9623,32 +9406,28 @@ type lpstrText*: LPSTR chrgText*: CHARRANGE - Tfindtextex* = FINDTEXTEX Pfindtextex* = ptr FINDTEXTEX FMS_GETDRIVEINFO* {.final, pure.} = object dwTotalSpace*: DWORD dwFreeSpace*: DWORD - szPath*: array[0..259, TCHAR] - szVolume*: array[0..13, TCHAR] - szShare*: array[0..127, TCHAR] + szPath*: array[0..259, CHAR] + szVolume*: array[0..13, CHAR] + szShare*: array[0..127, CHAR] - TFMSGETDRIVEINFO* = FMS_GETDRIVEINFO PFMSGETDRIVEINFO* = ptr FMS_GETDRIVEINFO FMS_GETFILESEL* {.final, pure.} = object ftTime*: FILETIME dwSize*: DWORD bAttr*: int8 - szName*: array[0..259, TCHAR] + szName*: array[0..259, CHAR] - TFMSGETFILESEL* = FMS_GETFILESEL PFMSGETFILESEL* = ptr FMS_GETFILESEL FMS_LOAD* {.final, pure.} = object dwSize*: DWORD - szMenuName*: array[0..(MENU_TEXT_LEN) - 1, TCHAR] + szMenuName*: array[0..(MENU_TEXT_LEN) - 1, CHAR] hMenu*: HMENU wMenuDelta*: WINUINT - TFMSLOAD* = FMS_LOAD PFMSLOAD* = ptr FMS_LOAD FMS_TOOLBARLOAD* {.final, pure.} = object dwSize*: DWORD @@ -9658,12 +9437,10 @@ type idBitmap*: int16 hBitmap*: HBITMAP - TFMSTOOLBARLOAD* = FMS_TOOLBARLOAD PFMSTOOLBARLOAD* = ptr FMS_TOOLBARLOAD FOCUS_EVENT_RECORD* {.final, pure.} = object bSetFocus*: WINBOOL - TFOCUSEVENTRECORD* = FOCUS_EVENT_RECORD PFOCUSEVENTRECORD* = ptr FOCUS_EVENT_RECORD FORM_INFO_1* {.final, pure.} = object Flags*: DWORD @@ -9671,7 +9448,6 @@ type Size*: SIZEL ImageableArea*: RECTL - TFORMINFO1* = FORM_INFO_1 PFORMINFO1* = ptr FORM_INFO_1 FORMAT_PARAMETERS* {.final, pure.} = object MediaType*: MEDIA_TYPE @@ -9680,7 +9456,6 @@ type StartHeadNumber*: DWORD EndHeadNumber*: DWORD - TFORMATPARAMETERS* = FORMAT_PARAMETERS PFORMATPARAMETERS* = ptr FORMAT_PARAMETERS FORMATRANGE* {.final, pure.} = object hdc*: HDC @@ -9689,7 +9464,6 @@ type rcPage*: RECT chrg*: CHARRANGE - Tformatrange* = FORMATRANGE Pformatrange* = ptr FORMATRANGE GCP_RESULTS* {.final, pure.} = object lStructSize*: DWORD @@ -9703,7 +9477,6 @@ type nMaxFit*: WINUINT LPGCP_RESULTS* = ptr GCP_RESULTS - TGCPRESULTS* = GCP_RESULTS PGCPRESULTS* = ptr GCP_RESULTS GENERIC_MAPPING* {.final, pure.} = object GenericRead*: ACCESS_MASK @@ -9712,7 +9485,6 @@ type GenericAll*: ACCESS_MASK PGENERIC_MAPPING* = ptr GENERIC_MAPPING - TGENERICMAPPING* = GENERIC_MAPPING GLYPHMETRICS* {.final, pure.} = object gmBlackBoxX*: WINUINT gmBlackBoxY*: WINUINT @@ -9721,19 +9493,16 @@ type gmCellIncY*: SHORT LPGLYPHMETRICS* = ptr GLYPHMETRICS - TGLYPHMETRICS* = GLYPHMETRICS PGLYPHMETRICS* = ptr GLYPHMETRICS HANDLETABLE* {.final, pure.} = object objectHandle*: array[0..0, HGDIOBJ] - THANDLETABLE* = HANDLETABLE LPHANDLETABLE* = ptr HANDLETABLE HD_HITTESTINFO* {.final, pure.} = object pt*: POINT flags*: WINUINT iItem*: int32 - THDHITTESTINFO* = HD_HITTESTINFO PHDHITTESTINFO* = ptr HD_HITTESTINFO HD_ITEM* {.final, pure.} = object mask*: WINUINT @@ -9744,7 +9513,6 @@ type fmt*: int32 lParam*: LPARAM - THDITEM* = HD_ITEM PHDITEM* = ptr HD_ITEM WINDOWPOS* {.final, pure.} = object hwnd*: HWND @@ -9756,13 +9524,11 @@ type flags*: WINUINT LPWINDOWPOS* = ptr WINDOWPOS - TWINDOWPOS* = WINDOWPOS PWINDOWPOS* = ptr WINDOWPOS HD_LAYOUT* {.final, pure.} = object prc*: ptr RECT pwpos*: ptr WINDOWPOS - THDLAYOUT* = HD_LAYOUT PHDLAYOUT* = ptr HD_LAYOUT HD_NOTIFY* {.final, pure.} = object hdr*: NMHDR @@ -9770,7 +9536,6 @@ type iButton*: int32 pitem*: ptr HD_ITEM - THDNOTIFY* = HD_NOTIFY PHDNOTIFY* = ptr HD_NOTIFY HELPINFO* {.final, pure.} = object cbSize*: WINUINT @@ -9781,7 +9546,6 @@ type MousePos*: POINT LPHELPINFO* = ptr HELPINFO - THELPINFO* = HELPINFO PHELPINFO* = ptr HELPINFO HELPWININFO* {.final, pure.} = object wStructSize*: int32 @@ -9790,9 +9554,8 @@ type dx*: int32 dy*: int32 wMax*: int32 - rgchMember*: array[0..1, TCHAR] + rgchMember*: array[0..1, CHAR] - THELPWININFO* = HELPWININFO PHELPWININFO* = ptr HELPWININFO HIGHCONTRAST* {.final, pure.} = object cbSize*: WINUINT @@ -9800,13 +9563,11 @@ type lpszDefaultScheme*: LPTSTR LPHIGHCONTRAST* = ptr HIGHCONTRAST - THIGHCONTRAST* = HIGHCONTRAST PHIGHCONTRAST* = ptr HIGHCONTRAST HSZPAIR* {.final, pure.} = object hszSvc*: HSZ hszTopic*: HSZ - THSZPAIR* = HSZPAIR PHSZPAIR* = ptr HSZPAIR ICONINFO* {.final, pure.} = object fIcon*: WINBOOL @@ -9815,7 +9576,6 @@ type hbmMask*: HBITMAP hbmColor*: HBITMAP - TICONINFO* = ICONINFO PICONINFO* = ptr ICONINFO ICONMETRICS* {.final, pure.} = object cbSize*: WINUINT @@ -9825,7 +9585,6 @@ type lfFont*: LOGFONT LPICONMETRICS* = ptr ICONMETRICS - TICONMETRICS* = ICONMETRICS PICONMETRICS* = ptr ICONMETRICS IMAGEINFO* {.final, pure.} = object hbmImage*: HBITMAP @@ -9834,7 +9593,6 @@ type Unused2*: int32 rcImage*: RECT - TIMAGEINFO* = IMAGEINFO PIMAGEINFO* = ptr IMAGEINFO KEY_EVENT_RECORD* {.final, pure.} = object bKeyDown*: WINBOOL @@ -9844,7 +9602,6 @@ type UnicodeChar*: WCHAR dwControlKeyState*: DWORD # other union part: AsciiChar: CHAR - TKEYEVENTRECORD* = KEY_EVENT_RECORD PKEYEVENTRECORD* = ptr KEY_EVENT_RECORD MOUSE_EVENT_RECORD* {.final, pure.} = object dwMousePosition*: COORD @@ -9852,25 +9609,21 @@ type dwControlKeyState*: DWORD dwEventFlags*: DWORD - TMOUSEEVENTRECORD* = MOUSE_EVENT_RECORD PMOUSEEVENTRECORD* = ptr MOUSE_EVENT_RECORD WINDOW_BUFFER_SIZE_RECORD* {.final, pure.} = object dwSize*: COORD - TWINDOWBUFFERSIZERECORD* = WINDOW_BUFFER_SIZE_RECORD PWINDOWBUFFERSIZERECORD* = ptr WINDOW_BUFFER_SIZE_RECORD MENU_EVENT_RECORD* {.final, pure.} = object dwCommandId*: WINUINT PMENU_EVENT_RECORD* = ptr MENU_EVENT_RECORD - TMENUEVENTRECORD* = MENU_EVENT_RECORD INPUT_RECORD* {.final, pure.} = object EventType*: int16 Reserved*: int16 event*: array[0..5, DWORD] PINPUT_RECORD* = ptr INPUT_RECORD - TINPUTRECORD* = INPUT_RECORD SYSTEMTIME* {.final, pure.} = object wYear*: int16 wMonth*: int16 @@ -9882,7 +9635,6 @@ type wMilliseconds*: int16 LPSYSTEMTIME* = ptr SYSTEMTIME - TSYSTEMTIME* = SYSTEMTIME PSYSTEMTIME* = ptr SYSTEMTIME JOB_INFO_1* {.final, pure.} = object JobId*: DWORD @@ -9899,25 +9651,21 @@ type PagesPrinted*: DWORD Submitted*: SYSTEMTIME - TJOBINFO1* = JOB_INFO_1 PJOBINFO1* = ptr JOB_INFO_1 SID_IDENTIFIER_AUTHORITY* {.final, pure.} = object Value*: array[0..5, int8] LPSID_IDENTIFIER_AUTHORITY* = ptr SID_IDENTIFIER_AUTHORITY PSID_IDENTIFIER_AUTHORITY* = ptr SID_IDENTIFIER_AUTHORITY - TSIDIDENTIFIERAUTHORITY* = SID_IDENTIFIER_AUTHORITY SID* {.final, pure.} = object Revision*: int8 SubAuthorityCount*: int8 IdentifierAuthority*: SID_IDENTIFIER_AUTHORITY SubAuthority*: array[0..(ANYSIZE_ARRAY) - 1, DWORD] - TSID* = SID PSID* = ptr SID SECURITY_DESCRIPTOR_CONTROL* = int16 PSECURITY_DESCRIPTOR_CONTROL* = ptr SECURITY_DESCRIPTOR_CONTROL - TSECURITYDESCRIPTORCONTROL* = SECURITY_DESCRIPTOR_CONTROL SECURITY_DESCRIPTOR* {.final, pure.} = object Revision*: int8 Sbz1*: int8 @@ -9928,7 +9676,6 @@ type Dacl*: PACL PSECURITY_DESCRIPTOR* = ptr SECURITY_DESCRIPTOR - TSECURITYDESCRIPTOR* = SECURITY_DESCRIPTOR JOB_INFO_2* {.final, pure.} = object JobId*: DWORD pPrinterName*: LPTSTR @@ -9954,7 +9701,6 @@ type Time*: DWORD PagesPrinted*: DWORD - TJOBINFO2* = JOB_INFO_2 PJOBINFO2* = ptr JOB_INFO_2 KERNINGPAIR* {.final, pure.} = object wFirst*: int16 @@ -9968,7 +9714,6 @@ type len*: UCHAR lana*: array[0..(MAX_LANA) - 1, UCHAR] - TLANAENUM* = LANA_ENUM PLANAENUM* = ptr LANA_ENUM LDT_ENTRY* {.final, pure.} = object LimitLow*: int16 @@ -9980,7 +9725,16 @@ type LPLDT_ENTRY* = ptr LDT_ENTRY PLDT_ENTRY* = ptr LDT_ENTRY - TLDTENTRY* = LDT_ENTRY + +{.deprecated: [TEXCEPTIONRECORD: EXCEPTION_RECORD, TEXCEPTIONDEBUGINFO: EXCEPTION_DEBUG_INFO, TExceptionRecord32: EXCEPTION_RECORD32, TExceptionDebugInfo32: EXCEPTION_DEBUG_INFO32, TExceptionRecord64: EXCEPTION_RECORD64, TExceptionDebugInfo64: EXCEPTION_DEBUG_INFO64, TEXITPROCESSDEBUGINFO: EXIT_PROCESS_DEBUG_INFO, TEXITTHREADDEBUGINFO: EXIT_THREAD_DEBUG_INFO, TLOADDLLDEBUGINFO: LOAD_DLL_DEBUG_INFO, TUNLOADDLLDEBUGINFO: UNLOAD_DLL_DEBUG_INFO, TOUTPUTDEBUGSTRINGINFO: OUTPUT_DEBUG_STRING_INFO, TRIPINFO: RIP_INFO, TDEBUGEVENT: DEBUG_EVENT, TDEBUGHOOKINFO: DEBUGHOOKINFO, TDELETEITEMSTRUCT: DELETEITEMSTRUCT, TDEVBROADCASTHDR: DEV_BROADCAST_HDR, TDEVBROADCASTOEM: DEV_BROADCAST_OEM, TDEVBROADCASTPORT: DEV_BROADCAST_PORT, TDEVBROADCASTUSERDEFINED: DEV_BROADCAST_USERDEFINED, TDEVBROADCASTVOLUME: DEV_BROADCAST_VOLUME, TDevicemode: DEVMODE, TDevicemodeA: DEVMODE, TDEVMODE: DEVMODE, TDEVNAMES: DEVNAMES, TDEVMODEW: DEVMODEW, TDeviceModeW: DEVMODEW, TDIBSECTION: DIBSECTION, TLargeInteger: LargeInteger, TULargeInteger: ULargeInteger, TDISKPERFORMANCE: DISK_PERFORMANCE, TDISKGEOMETRY: DISK_GEOMETRY, TDOCINFO1: DOC_INFO_1, TDLGTEMPLATE: DLGTEMPLATE, TDLGITEMTEMPLATE: DLGITEMTEMPLATE, TDRAWTEXTPARAMS: DRAWTEXTPARAMS, TDRAWITEMSTRUCT: DRAWITEMSTRUCT, TDRAGLISTINFO: DRAGLISTINFO, TDOCINFO: DOCINFO, TDOCINFOA: DOCINFO, TDOCINFO2: DOC_INFO_2, TPARTITIONINFORMATION: PARTITION_INFORMATION, TDRIVELAYOUTINFORMATION: DRIVE_LAYOUT_INFORMATION, TEMRARC: EMRARC, TEMRANGLEARC: EMRANGLEARC, TEMR: EMR, Teditstream: EDITSTREAM, TDRIVERINFO3: DRIVER_INFO_3, TDRIVERINFO2: DRIVER_INFO_2, TDRIVERINFO1: DRIVER_INFO_1, TEMREXTCREATEFONTINDIRECTW: EMREXTCREATEFONTINDIRECTW].} + +{.deprecated: [TEXTLOGFONT: EXTLOGFONT, TPANOSE: PANOSE, TEMRINTERSECTCLIPRECT: EMREXCLUDECLIPRECT, TEMREXCLUDECLIPRECT: EMREXCLUDECLIPRECT, TEMREOF: EMREOF, TEMRRECTANGLE: EMRELLIPSE, TEMRELLIPSE: EMRELLIPSE, TEMRCREATEPEN: EMRCREATEPEN, TLOGPEN: LOGPEN, TEMRCREATEPALETTE: EMRCREATEPALETTE, TLOGPALETTE: LOGPALETTE, TPALETTEENTRY: PALETTEENTRY, TEMRCREATEMONOBRUSH: EMRCREATEMONOBRUSH, TEMRCREATEDIBPATTERNBRUSHPT: EMRCREATEDIBPATTERNBRUSHPT, TEMRCREATECOLORSPACE: EMRCREATECOLORSPACE, TLOGCOLORSPACE: LOGCOLORSPACE, TLOGCOLORSPACEA: LOGCOLORSPACE, TEMRCREATEBRUSHINDIRECT: EMRCREATEBRUSHINDIRECT, TLOGBRUSH: LOGBRUSH, TEMRBITBLT: EMRBITBLT, TXFORM: XFORM, TEMRPIE: EMRARC, TEMRCHORD: EMRARC, TEMRARCTO: EMRARC, TSERVICESTATUS: SERVICE_STATUS, TENUMSERVICESTATUS: ENUM_SERVICE_STATUS, TENUMLOGFONT: ENUMLOGFONT, TENUMLOGFONTEX: ENUMLOGFONTEX, TEVENTLOGRECORD: EVENTLOGRECORD, TEVENTMSG: EVENTMSG, TEXCEPTIONPOINTERS: EXCEPTION_POINTERS, TEXTBUTTON: EXT_BUTTON, TFILTERKEYS: FILTERKEYS, TFINDNAMEBUFFER: FIND_NAME_BUFFER, TFINDNAMEHEADER: FIND_NAME_HEADER, TFINDREPLACE: FINDREPLACE, Tfindtextex: FINDTEXTEX, TFMSGETDRIVEINFO: FMS_GETDRIVEINFO, TFMSGETFILESEL: FMS_GETFILESEL, TFMSLOAD: FMS_LOAD, TFMSTOOLBARLOAD: FMS_TOOLBARLOAD, TFOCUSEVENTRECORD: FOCUS_EVENT_RECORD, TFORMINFO1: FORM_INFO_1, TFORMATPARAMETERS: FORMAT_PARAMETERS, Tformatrange: FORMATRANGE, TGCPRESULTS: GCP_RESULTS, TGENERICMAPPING: GENERIC_MAPPING, TGLYPHMETRICS: GLYPHMETRICS, THANDLETABLE: HANDLETABLE, THDHITTESTINFO: HD_HITTESTINFO, THDITEM: HD_ITEM, TWINDOWPOS: WINDOWPOS, THDLAYOUT: HD_LAYOUT, THDNOTIFY: HD_NOTIFY, THELPINFO: HELPINFO, THELPWININFO: HELPWININFO, THIGHCONTRAST: HIGHCONTRAST, THSZPAIR: HSZPAIR, TICONINFO: ICONINFO, TICONMETRICS: ICONMETRICS, TIMAGEINFO: IMAGEINFO, TKEYEVENTRECORD: KEY_EVENT_RECORD, TMOUSEEVENTRECORD: MOUSE_EVENT_RECORD, TWINDOWBUFFERSIZERECORD: WINDOW_BUFFER_SIZE_RECORD, TMENUEVENTRECORD: MENU_EVENT_RECORD, TINPUTRECORD: INPUT_RECORD, TSYSTEMTIME: SYSTEMTIME, TJOBINFO1: JOB_INFO_1].} + +{.deprecated: [TSIDIDENTIFIERAUTHORITY: SID_IDENTIFIER_AUTHORITY, TSID: SID, TSECURITYDESCRIPTORCONTROL: SECURITY_DESCRIPTOR_CONTROL, TSECURITYDESCRIPTOR: SECURITY_DESCRIPTOR, TJOBINFO2: JOB_INFO_2, TLANAENUM: LANA_ENUM, TLDTENTRY: LDT_ENTRY, TEMRPOLYPOLYGON: EMRPOLYPOLYLINE, TEMRPOLYPOLYLINE: EMRPOLYPOLYLINE, TEMRPOLYLINETO16: EMRPOLYLINE16, TEMRPOLYBEZIERTO16: EMRPOLYLINE16, TEMRPOLYGON16: EMRPOLYLINE16, TEMRPOLYBEZIER16: EMRPOLYLINE16, TEMRPOLYLINE16: EMRPOLYLINE16, TEMRPOLYLINETO: EMRPOLYLINE, TEMRPOLYBEZIERTO: EMRPOLYLINE, TEMRPOLYGON: EMRPOLYLINE, TEMRPOLYBEZIER: EMRPOLYLINE, TEMRPOLYLINE: EMRPOLYLINE, TEMRPOLYDRAW16: EMRPOLYDRAW16, TEMRPOLYDRAW: EMRPOLYDRAW, TEMRPLGBLT: EMRPLGBLT, TEMROFFSETCLIPRGN: EMROFFSETCLIPRGN, TEMRMODIFYWORLDTRANSFORM: EMRMODIFYWORLDTRANSFORM, TEMRMASKBLT: EMRMASKBLT, TEMRMOVETOEX: EMRLINETO, TEMRLINETO: EMRLINETO, TEMRPAINTRGN: EMRINVERTRGN, TEMRINVERTRGN: EMRINVERTRGN, TEMRGDICOMMENT: EMRGDICOMMENT, TEMRFRAMERGN: EMRFRAMERGN, TEMRFORMAT: EMRFORMAT, TEMRFILLRGN: EMRFILLRGN, TEMRSTROKEPATH: EMRFILLPATH, TEMRSTROKEANDFILLPATH: EMRFILLPATH, TEMRFILLPATH: EMRFILLPATH, TEMREXTTEXTOUTW: EMREXTTEXTOUTA, TEMREXTTEXTOUTA: EMREXTTEXTOUTA, TEMRTEXT: EMRTEXT, TEMREXTSELECTCLIPRGN: EMREXTSELECTCLIPRGN, TEMREXTFLOODFILL: EMREXTFLOODFILL, TEMREXTCREATEPEN: EMREXTCREATEPEN, TEXTLOGPEN: EXTLOGPEN, TNMHDR: NMHDR, TEMRENABLEICM: EMRSELECTCLIPPATH, TEMRSETTEXTALIGN: EMRSELECTCLIPPATH, TEMRSETSTRETCHBLTMODE: EMRSELECTCLIPPATH, TEMRSETROP2: EMRSELECTCLIPPATH, TEMRSETPOLYFILLMODE: EMRSELECTCLIPPATH, TEMRSETMAPMODE: EMRSELECTCLIPPATH, TEMRSETBKMODE: EMRSELECTCLIPPATH, TEMRSELECTCLIPPATH: EMRSELECTCLIPPATH, TEMRREALIZEPALETTE: EMRABORTPATH, TEMRSAVEDC: EMRABORTPATH, TEMRSETMETARGN: EMRABORTPATH, TEMRWIDENPATH: EMRABORTPATH].} + +{.deprecated: [TEMRFLATTENPATH: EMRABORTPATH, TEMRCLOSEFIGURE: EMRABORTPATH, TEMRENDPATH: EMRABORTPATH, TEMRBEGINPATH: EMRABORTPATH, TABORTPATH: EMRABORTPATH, TEMRABORTPATH: EMRABORTPATH, TEMRSTRETCHDIBITS: EMRSTRETCHDIBITS, TEMRSTRETCHBLT: EMRSTRETCHBLT, TEMRSETWORLDTRANSFORM: EMRSETWORLDTRANSFORM, TEMRSETBRUSHORGEX: EMRSETVIEWPORTORGEX, TEMRSETWINDOWORGEX: EMRSETVIEWPORTORGEX, TEMRSETVIEWPORTORGEX: EMRSETVIEWPORTORGEX, TEMRSETWINDOWEXTEX: EMRSETVIEWPORTEXTEX, TEMRSETVIEWPORTEXTEX: EMRSETVIEWPORTEXTEX, TEMRSETPIXELV: EMRSETPIXELV, TEMRSETPALETTEENTRIES: EMRSETPALETTEENTRIES, TEMRSETMITERLIMIT: EMRSETMITERLIMIT, TEMRSETMAPPERFLAGS: EMRSETMAPPERFLAGS, TEMRSETDIBITSTODEVICE: EMRSETDIBITSTODEVICE, TEMRSETCOLORADJUSTMENT: EMRSETCOLORADJUSTMENT, TEMRSETTEXTCOLOR: EMRSETBKCOLOR, TEMRSETBKCOLOR: EMRSETBKCOLOR, TEMRSETARCDIRECTION: EMRSETARCDIRECTION, TEMRSELECTPALETTE: EMRSELECTPALETTE, TEMRDELETEOBJECT: EMRSELECTOBJECT, TEMRSELECTOBJECT: EMRSELECTOBJECT, TEMRDELETECOLORSPACE: EMRSELECTCOLORSPACE, TEMRSELECTCOLORSPACE: EMRSELECTCOLORSPACE, TEMRSCALEWINDOWEXTEX: EMRSCALEVIEWPORTEXTEX, TEMRSCALEVIEWPORTEXTEX: EMRSCALEVIEWPORTEXTEX, TEMRROUNDRECT: EMRROUNDRECT, TEMRRESTOREDC: EMRRESTOREDC, TEMRRESIZEPALETTE: EMRRESIZEPALETTE, TEMRPOLYTEXTOUTW: EMRPOLYTEXTOUTA, TEMRPOLYTEXTOUTA: EMRPOLYTEXTOUTA, TEMRPOLYPOLYGON16: EMRPOLYPOLYLINE16, TEMRPOLYPOLYLINE16: EMRPOLYPOLYLINE16, TENHMETAHEADER: ENHMETAHEADER, TENHMETARECORD: ENHMETARECORD].} + + const bm_LDT_ENTRY_BaseMid* = 0x000000FF @@ -10010,34 +9764,27 @@ type lsCsbDefault*: array[0..1, DWORD] lsCsbSupported*: array[0..1, DWORD] - TLOCALESIGNATURE* = LOCALESIGNATURE PLOCALESIGNATURE* = ptr LOCALESIGNATURE LOCALGROUP_MEMBERS_INFO_0* {.final, pure.} = object lgrmi0_sid*: PSID - TLOCALGROUPMEMBERSINFO0* = LOCALGROUP_MEMBERS_INFO_0 PLOCALGROUPMEMBERSINFO0* = ptr LOCALGROUP_MEMBERS_INFO_0 LOCALGROUP_MEMBERS_INFO_3* {.final, pure.} = object lgrmi3_domainandname*: LPWSTR - TLOCALGROUPMEMBERSINFO3* = LOCALGROUP_MEMBERS_INFO_3 PLOCALGROUPMEMBERSINFO3* = ptr LOCALGROUP_MEMBERS_INFO_3 FXPT16DOT16* = int32 LPFXPT16DOT16* = ptr FXPT16DOT16 - TFXPT16DOT16* = FXPT16DOT16 PFXPT16DOT16* = ptr FXPT16DOT16 - LUID* = TlargeInteger - TLUID* = LUID + LUID* = LargeInteger PLUID* = ptr LUID LUID_AND_ATTRIBUTES* {.final, pure.} = object Luid*: LUID Attributes*: DWORD - TLUIDANDATTRIBUTES* = LUID_AND_ATTRIBUTES PLUIDANDATTRIBUTES* = ptr LUID_AND_ATTRIBUTES LUID_AND_ATTRIBUTES_ARRAY* = array[0..(ANYSIZE_ARRAY) - 1, LUID_AND_ATTRIBUTES] PLUID_AND_ATTRIBUTES_ARRAY* = ptr LUID_AND_ATTRIBUTES_ARRAY - TLUIDANDATTRIBUTESARRAY* = LUID_AND_ATTRIBUTES_ARRAY LV_COLUMN* {.final, pure.} = object mask*: WINUINT fmt*: int32 @@ -10046,7 +9793,6 @@ type cchTextMax*: int32 iSubItem*: int32 - TLVCOLUMN* = LV_COLUMN PLVCOLUMN* = ptr LV_COLUMN LV_ITEM* {.final, pure.} = object mask*: WINUINT @@ -10059,13 +9805,11 @@ type iImage*: int32 lParam*: LPARAM - TLVITEM* = LV_ITEM PLVITEM* = ptr LV_ITEM LV_DISPINFO* {.final, pure.} = object hdr*: NMHDR item*: LV_ITEM - TLVDISPINFO* = LV_DISPINFO PLVDISPINFO* = ptr LV_DISPINFO LV_FINDINFO* {.final, pure.} = object flags*: WINUINT @@ -10074,21 +9818,18 @@ type pt*: POINT vkDirection*: WINUINT - TLVFINDINFO* = LV_FINDINFO PLVFINDINFO* = ptr LV_FINDINFO LV_HITTESTINFO* {.final, pure.} = object pt*: POINT flags*: WINUINT iItem*: int32 - TLVHITTESTINFO* = LV_HITTESTINFO PLVHITTESTINFO* = ptr LV_HITTESTINFO LV_KEYDOWN* {.final, pure.} = object hdr*: NMHDR wVKey*: int16 flags*: WINUINT - TLVKEYDOWN* = LV_KEYDOWN PLVKEYDOWN* = ptr LV_KEYDOWN MAT2* {.final, pure.} = object eM11*: FIXED @@ -10096,7 +9837,6 @@ type eM21*: FIXED eM22*: FIXED - TMAT2* = MAT2 PMAT2* = ptr MAT2 MDICREATESTRUCT* {.final, pure.} = object szClass*: LPCTSTR @@ -10110,7 +9850,6 @@ type lParam*: LPARAM LPMDICREATESTRUCT* = ptr MDICREATESTRUCT - TMDICREATESTRUCT* = MDICREATESTRUCT PMDICREATESTRUCT* = ptr MDICREATESTRUCT MEASUREITEMSTRUCT* {.final, pure.} = object CtlType*: WINUINT @@ -10121,7 +9860,6 @@ type itemData*: ULONG_PTR LPMEASUREITEMSTRUCT* = ptr MEASUREITEMSTRUCT - TMEASUREITEMSTRUCT* = MEASUREITEMSTRUCT PMEASUREITEMSTRUCT* = ptr MEASUREITEMSTRUCT MEMORY_BASIC_INFORMATION* {.final, pure.} = object BaseAddress*: PVOID @@ -10133,7 +9871,6 @@ type `type`*: DWORD PMEMORY_BASIC_INFORMATION* = ptr MEMORY_BASIC_INFORMATION - TMEMORYBASICINFORMATION* = MEMORY_BASIC_INFORMATION MEMORYSTATUS* {.final, pure.} = object dwLength*: DWORD dwMemoryLoad*: DWORD @@ -10144,21 +9881,19 @@ type dwTotalVirtual*: int dwAvailVirtual*: int - TGUID* {.final, pure.} = object + GUID* {.final, pure.} = object D1*: int32 D2*: int16 D3*: int16 D4*: array [0..7, int8] LPMEMORYSTATUS* = ptr MEMORYSTATUS - TMEMORYSTATUS* = MEMORYSTATUS PMEMORYSTATUS* = ptr MEMORYSTATUS MENUEX_TEMPLATE_HEADER* {.final, pure.} = object wVersion*: int16 wOffset*: int16 dwHelpId*: DWORD - TMENUXTEMPLATEHEADER* = MENUEX_TEMPLATE_HEADER PMENUXTEMPLATEHEADER* = ptr MENUEX_TEMPLATE_HEADER MENUEX_TEMPLATE_ITEM* {.final, pure.} = object dwType*: DWORD @@ -10168,7 +9903,6 @@ type szText*: array[0..0, WCHAR] dwHelpId*: DWORD - TMENUEXTEMPLATEITEM* = MENUEX_TEMPLATE_ITEM PMENUEXTEMPLATEITEM* = ptr MENUEX_TEMPLATE_ITEM MENUINFO* {.final, pure.} = object cbSize*: DWORD @@ -10181,7 +9915,6 @@ type LPMENUINFO* = ptr MENUINFO LPCMENUINFO* = ptr MENUINFO - TMENUINFO* = MENUINFO PMENUINFO* = ptr MENUINFO MENUITEMINFO* {.final, pure.} = object cbSize*: WINUINT @@ -10199,25 +9932,20 @@ type LPMENUITEMINFO* = ptr MENUITEMINFO LPCMENUITEMINFO* = ptr MENUITEMINFO - TMENUITEMINFO* = MENUITEMINFO - TMENUITEMINFOA* = MENUITEMINFO PMENUITEMINFO* = ptr MENUITEMINFO MENUITEMTEMPLATE* {.final, pure.} = object mtOption*: int16 mtID*: int16 mtString*: array[0..0, WCHAR] - TMENUITEMTEMPLATE* = MENUITEMTEMPLATE PMENUITEMTEMPLATE* = ptr MENUITEMTEMPLATE MENUITEMTEMPLATEHEADER* {.final, pure.} = object versionNumber*: int16 offset*: int16 - TMENUITEMTEMPLATEHEADER* = MENUITEMTEMPLATEHEADER PMENUITEMTEMPLATEHEADER* = ptr MENUITEMTEMPLATEHEADER MENUTEMPLATE* {.final, pure.} = object LPMENUTEMPLATE* = ptr MENUTEMPLATE - TMENUTEMPLATE* = MENUTEMPLATE PMENUTEMPLATE* = ptr MENUTEMPLATE METAFILEPICT* {.final, pure.} = object mm*: LONG @@ -10226,7 +9954,6 @@ type hMF*: HMETAFILE LPMETAFILEPICT* = ptr METAFILEPICT - TMETAFILEPICT* = METAFILEPICT PMETAFILEPICT* = ptr METAFILEPICT METAHEADER* {.final, pure.} = object mtType*: int16 @@ -10237,7 +9964,6 @@ type mtMaxRecord*: DWORD mtNoParameters*: int16 - TMETAHEADER* = METAHEADER PMETAHEADER* = ptr METAHEADER METARECORD* {.final, pure.} = object rdSize*: DWORD @@ -10245,7 +9971,6 @@ type rdParm*: array[0..0, int16] LPMETARECORD* = ptr METARECORD - TMETARECORD* = METARECORD PMETARECORD* = ptr METARECORD MINIMIZEDMETRICS* {.final, pure.} = object cbSize*: WINUINT @@ -10255,7 +9980,6 @@ type iArrange*: int32 LPMINIMIZEDMETRICS* = ptr MINIMIZEDMETRICS - TMINIMIZEDMETRICS* = MINIMIZEDMETRICS PMINIMIZEDMETRICS* = ptr MINIMIZEDMETRICS MINMAXINFO* {.final, pure.} = object ptReserved*: POINT @@ -10264,7 +9988,6 @@ type ptMinTrackSize*: POINT ptMaxTrackSize*: POINT - TMINMAXINFO* = MINMAXINFO PMINMAXINFO* = ptr MINMAXINFO MODEMDEVCAPS* {.final, pure.} = object dwActualSize*: DWORD @@ -10289,7 +10012,6 @@ type abVariablePortion*: array[0..0, int8] LPMODEMDEVCAPS* = ptr MODEMDEVCAPS - TMODEMDEVCAPS* = MODEMDEVCAPS PMODEMDEVCAPS* = ptr MODEMDEVCAPS MODEMSETTINGS* {.final, pure.} = object dwActualSize*: DWORD @@ -10306,7 +10028,6 @@ type abVariablePortion*: array[0..0, int8] LPMODEMSETTINGS* = ptr MODEMSETTINGS - TMODEMSETTINGS* = MODEMSETTINGS PMODEMSETTINGS* = ptr MODEMSETTINGS MONCBSTRUCT* {.final, pure.} = object cb*: WINUINT @@ -10325,7 +10046,6 @@ type cbData*: DWORD Data*: array[0..7, DWORD] - TMONCBSTRUCT* = MONCBSTRUCT PMONCBSTRUCT* = ptr MONCBSTRUCT MONCONVSTRUCT* {.final, pure.} = object cb*: WINUINT @@ -10337,7 +10057,6 @@ type hConvClient*: HCONV hConvServer*: HCONV - TMONCONVSTRUCT* = MONCONVSTRUCT PMONCONVSTRUCT* = ptr MONCONVSTRUCT MONERRSTRUCT* {.final, pure.} = object cb*: WINUINT @@ -10345,7 +10064,6 @@ type dwTime*: DWORD hTask*: HANDLE - TMONERRSTRUCT* = MONERRSTRUCT PMONERRSTRUCT* = ptr MONERRSTRUCT MONHSZSTRUCT* {.final, pure.} = object cb*: WINUINT @@ -10353,21 +10071,18 @@ type dwTime*: DWORD hsz*: HSZ hTask*: HANDLE - str*: array[0..0, TCHAR] + str*: array[0..0, CHAR] - TMONHSZSTRUCT* = MONHSZSTRUCT PMONHSZSTRUCT* = ptr MONHSZSTRUCT MONITOR_INFO_1* {.final, pure.} = object pName*: LPTSTR - TMONITORINFO1* = MONITOR_INFO_1 PMONITORINFO1* = ptr MONITOR_INFO_1 MONITOR_INFO_2* {.final, pure.} = object pName*: LPTSTR pEnvironment*: LPTSTR pDLLName*: LPTSTR - TMONITORINFO2* = MONITOR_INFO_2 PMONITORINFO2* = ptr MONITOR_INFO_2 MONLINKSTRUCT* {.final, pure.} = object cb*: WINUINT @@ -10383,7 +10098,6 @@ type hConvServer*: HCONV hConvClient*: HCONV - TMONLINKSTRUCT* = MONLINKSTRUCT PMONLINKSTRUCT* = ptr MONLINKSTRUCT MONMSGSTRUCT* {.final, pure.} = object cb*: WINUINT @@ -10395,7 +10109,6 @@ type lParam*: LPARAM dmhd*: DDEML_MSG_HOOK_DATA - TMONMSGSTRUCT* = MONMSGSTRUCT PMONMSGSTRUCT* = ptr MONMSGSTRUCT MOUSEHOOKSTRUCT* {.final, pure.} = object pt*: POINT @@ -10404,7 +10117,6 @@ type dwExtraInfo*: DWORD LPMOUSEHOOKSTRUCT* = ptr MOUSEHOOKSTRUCT - TMOUSEHOOKSTRUCT* = MOUSEHOOKSTRUCT PMOUSEHOOKSTRUCT* = ptr MOUSEHOOKSTRUCT MOUSEKEYS* {.final, pure.} = object cbSize*: DWORD @@ -10415,7 +10127,6 @@ type dwReserved1*: DWORD dwReserved2*: DWORD - TMOUSEKEYS* = MOUSEKEYS PMOUSEKEYS* = ptr MOUSEKEYS MSGBOXCALLBACK* = proc (lpHelpInfo: LPHELPINFO){.stdcall.} TMSGBOXCALLBACK* = MSGBOXCALLBACK @@ -10432,8 +10143,6 @@ type dwLanguageId*: DWORD LPMSGBOXPARAMS* = ptr MSGBOXPARAMS - TMSGBOXPARAMS* = MSGBOXPARAMS - TMSGBOXPARAMSA* = MSGBOXPARAMS PMSGBOXPARAMS* = ptr MSGBOXPARAMS MSGFILTER* {.final, pure.} = object nmhdr*: NMHDR @@ -10441,21 +10150,18 @@ type wParam*: WPARAM lParam*: LPARAM - Tmsgfilter* = MSGFILTER Pmsgfilter* = ptr MSGFILTER MULTIKEYHELP* {.final, pure.} = object mkSize*: DWORD - mkKeylist*: TCHAR - szKeyphrase*: array[0..0, TCHAR] + mkKeylist*: CHAR + szKeyphrase*: array[0..0, CHAR] - TMULTIKEYHELP* = MULTIKEYHELP PMULTIKEYHELP* = ptr MULTIKEYHELP NAME_BUFFER* {.final, pure.} = object name*: array[0..(NCBNAMSZ) - 1, UCHAR] name_num*: UCHAR name_flags*: UCHAR - TNAMEBUFFER* = NAME_BUFFER PNAMEBUFFER* = ptr NAME_BUFFER p_NCB* = ptr NCB NCB* {.final, pure.} = object @@ -10475,7 +10181,6 @@ type ncb_reserve*: array[0..9, UCHAR] ncb_event*: HANDLE - TNCB* = NCB NCCALCSIZE_PARAMS* {.final, pure.} = object rgrc*: array[0..2, RECT] lppos*: PWINDOWPOS @@ -10495,7 +10200,6 @@ type cNumItems*: LONG lpszItemList*: LPTSTR - TNDDESHAREINFO* = NDDESHAREINFO PNDDESHAREINFO* = ptr NDDESHAREINFO NETRESOURCE* {.final, pure.} = object dwScope*: DWORD @@ -10508,8 +10212,6 @@ type lpProvider*: LPTSTR LPNETRESOURCE* = ptr NETRESOURCE - TNETRESOURCE* = NETRESOURCE - TNETRESOURCEA* = NETRESOURCE PNETRESOURCE* = ptr NETRESOURCE PNETRESOURCEA* = ptr NETRESOURCE NEWCPLINFO* {.final, pure.} = object @@ -10518,11 +10220,10 @@ type dwHelpContext*: DWORD lData*: LONG hIcon*: HICON - szName*: array[0..31, TCHAR] - szInfo*: array[0..63, TCHAR] - szHelpFile*: array[0..127, TCHAR] + szName*: array[0..31, CHAR] + szInfo*: array[0..63, CHAR] + szHelpFile*: array[0..127, CHAR] - TNEWCPLINFO* = NEWCPLINFO PNEWCPLINFO* = ptr NEWCPLINFO NEWTEXTMETRIC* {.final, pure.} = object tmHeight*: LONG @@ -10550,13 +10251,11 @@ type ntmCellHeight*: WINUINT ntmAvgWidth*: WINUINT - TNEWTEXTMETRIC* = NEWTEXTMETRIC PNEWTEXTMETRIC* = ptr NEWTEXTMETRIC NEWTEXTMETRICEX* {.final, pure.} = object ntmentm*: NEWTEXTMETRIC ntmeFontSignature*: FONTSIGNATURE - TNEWTEXTMETRICEX* = NEWTEXTMETRICEX PNEWTEXTMETRICEX* = ptr NEWTEXTMETRICEX NM_LISTVIEW* {.final, pure.} = object hdr*: NMHDR @@ -10568,7 +10267,6 @@ type ptAction*: POINT lParam*: LPARAM - TNMLISTVIEW* = NM_LISTVIEW PNMLISTVIEW* = ptr NM_LISTVIEW TV_ITEM* {.final, pure.} = object mask*: WINUINT @@ -10583,7 +10281,6 @@ type lParam*: LPARAM LPTV_ITEM* = ptr TV_ITEM - TTVITEM* = TV_ITEM PTVITEM* = ptr TV_ITEM NM_TREEVIEW* {.final, pure.} = object hdr*: NMHDR @@ -10593,14 +10290,12 @@ type ptDrag*: POINT LPNM_TREEVIEW* = ptr NM_TREEVIEW - TNMTREEVIEW* = NM_TREEVIEW PNMTREEVIEW* = ptr NM_TREEVIEW NM_UPDOWNW* {.final, pure.} = object hdr*: NMHDR iPos*: int32 iDelta*: int32 - TNMUPDOWN* = NM_UPDOWNW PNMUPDOWN* = ptr NM_UPDOWNW NONCLIENTMETRICS* {.final, pure.} = object cbSize*: WINUINT @@ -10620,7 +10315,6 @@ type lfMessageFont*: LOGFONT LPNONCLIENTMETRICS* = ptr NONCLIENTMETRICS - TNONCLIENTMETRICS* = NONCLIENTMETRICS PNONCLIENTMETRICS* = ptr NONCLIENTMETRICS SERVICE_ADDRESS* {.final, pure.} = object dwAddressType*: DWORD @@ -10630,20 +10324,17 @@ type lpAddress*: ptr int8 lpPrincipal*: ptr int8 - TSERVICEADDRESS* = SERVICE_ADDRESS PSERVICEADDRESS* = ptr SERVICE_ADDRESS SERVICE_ADDRESSES* {.final, pure.} = object dwAddressCount*: DWORD Addresses*: array[0..0, SERVICE_ADDRESS] LPSERVICE_ADDRESSES* = ptr SERVICE_ADDRESSES - TSERVICEADDRESSES* = SERVICE_ADDRESSES PSERVICEADDRESSES* = ptr SERVICE_ADDRESSES - LPGUID* = ptr TGUID - PGUID* = ptr TGUID - CLSID* = TGUID + LPGUID* = ptr GUID + PGUID* = ptr GUID + CLSID* = GUID LPCLSID* = ptr CLSID - TCLSID* = CLSID PCLSID* = ptr CLSID SERVICE_INFO* {.final, pure.} = object lpServiceType*: LPGUID @@ -10657,13 +10348,11 @@ type lpServiceAddress*: LPSERVICE_ADDRESSES ServiceSpecificInfo*: BLOB - TSERVICEINFO* = SERVICE_INFO PSERVICEINFO* = ptr SERVICE_INFO NS_SERVICE_INFO* {.final, pure.} = object dwNameSpace*: DWORD ServiceInfo*: SERVICE_INFO - TNSSERVICEINFO* = NS_SERVICE_INFO PNSSERVICEINFO* = ptr NS_SERVICE_INFO NUMBERFMT* {.final, pure.} = object NumDigits*: WINUINT @@ -10673,7 +10362,6 @@ type lpThousandSep*: LPTSTR NegativeOrder*: WINUINT - Tnumberfmt* = NUMBERFMT Pnumberfmt* = ptr NUMBERFMT OFSTRUCT* {.final, pure.} = object cBytes*: int8 @@ -10684,7 +10372,6 @@ type szPathName*: array[0..(OFS_MAXPATHNAME) - 1, char] LPOFSTRUCT* = ptr OFSTRUCT - TOFSTRUCT* = OFSTRUCT POFSTRUCT* = ptr OFSTRUCT OPENFILENAME_NT4* {.final, pure.} = object lStructSize*: DWORD @@ -10709,9 +10396,8 @@ type lpTemplateName*: LPCTSTR LPOPENFILENAME_NT4* = ptr OPENFILENAME_NT4 - TOPENFILENAME_NT4* = OPENFILENAME_NT4 POPENFILENAME_NT4* = ptr OPENFILENAME_NT4 - TOPENFILENAME* {.final, pure.} = object + OPENFILENAME* {.final, pure.} = object lStructSize*: DWORD hwndOwner*: HWND hInstance*: HINST @@ -10736,17 +10422,16 @@ type dwreserved*: DWORD FlagsEx*: DWORD - LPOPENFILENAME* = ptr TOPENFILENAME - POPENFILENAME* = ptr TOPENFILENAME - OFN* = TOPENFILENAME - POFN* = ptr TOPENFILENAME + LPOPENFILENAME* = ptr OPENFILENAME + POPENFILENAME* = ptr OPENFILENAME + OFN* = OPENFILENAME + POFN* = ptr OPENFILENAME OFNOTIFY* {.final, pure.} = object hdr*: NMHDR lpOFN*: LPOPENFILENAME pszFile*: LPTSTR LPOFNOTIFY* = ptr OFNOTIFY - TOFNOTIFY* = OFNOTIFY POFNOTIFY* = ptr OFNOTIFY OSVERSIONINFO* {.final, pure.} = object dwOSVersionInfoSize*: DWORD @@ -10754,10 +10439,9 @@ type dwMinorVersion*: DWORD dwBuildNumber*: DWORD dwPlatformId*: DWORD - szCSDVersion*: array[0..127, TCHAR] + szCSDVersion*: array[0..127, CHAR] LPOSVERSIONINFO* = ptr OSVERSIONINFO - TOSVERSIONINFO* = OSVERSIONINFO POSVERSIONINFO* = ptr OSVERSIONINFO OSVERSIONINFOW* {.final, pure.} = object dwOSVersionInfoSize*: DWORD @@ -10768,7 +10452,6 @@ type szCSDVersion*: array[0..127, WCHAR] LPOSVERSIONINFOW* = ptr OSVERSIONINFOW - TOSVERSIONINFOW* = OSVERSIONINFOW POSVERSIONINFOW* = ptr OSVERSIONINFOW TEXTMETRIC* {.final, pure.} = object tmHeight*: LONG @@ -10793,7 +10476,6 @@ type tmCharSet*: int8 LPTEXTMETRIC* = ptr TEXTMETRIC - TTEXTMETRIC* = TEXTMETRIC PTEXTMETRIC* = ptr TEXTMETRIC TEXTMETRICW* {.final, pure.} = object tmHeight*: LONG @@ -10818,7 +10500,6 @@ type tmCharSet*: int8 LPTEXTMETRICW* = ptr TEXTMETRICW - TTEXTMETRICW* = TEXTMETRICW PTEXTMETRICW* = ptr TEXTMETRICW OUTLINETEXTMETRIC* {.final, pure.} = object otmSize*: WINUINT @@ -10855,7 +10536,6 @@ type otmpFullName*: PSTR LPOUTLINETEXTMETRIC* = ptr OUTLINETEXTMETRIC - TOUTLINETEXTMETRIC* = OUTLINETEXTMETRIC POUTLINETEXTMETRIC* = ptr OUTLINETEXTMETRIC OVERLAPPED* {.final, pure.} = object Internal*: DWORD @@ -10865,7 +10545,6 @@ type hEvent*: HANDLE LPOVERLAPPED* = ptr OVERLAPPED - TOVERLAPPED* = OVERLAPPED POVERLAPPED* = ptr OVERLAPPED #PAGESETUPDLG = record conflicts with function PageSetupDlg TPAGESETUPDLG* {.final, pure.} = object @@ -10886,7 +10565,6 @@ type LPPAGESETUPDLG* = ptr TPAGESETUPDLG PPAGESETUPDLG* = ptr TPAGESETUPDLG - TPSD* = TPAGESETUPDLG PPSD* = ptr TPAGESETUPDLG PAINTSTRUCT* {.final, pure.} = object hdc*: HDC @@ -10897,7 +10575,6 @@ type rgbReserved*: array[0..31, int8] LPPAINTSTRUCT* = ptr PAINTSTRUCT - TPAINTSTRUCT* = PAINTSTRUCT PPAINTSTRUCT* = ptr PAINTSTRUCT PARAFORMAT* {.final, pure.} = object cbSize*: WINUINT @@ -10911,12 +10588,10 @@ type cTabCount*: SHORT rgxTabs*: array[0..(MAX_TAB_STOPS) - 1, LONG] - Tparaformat* = PARAFORMAT Pparaformat* = ptr PARAFORMAT PERF_COUNTER_BLOCK* {.final, pure.} = object ByteLength*: DWORD - TPERFCOUNTERBLOCK* = PERF_COUNTER_BLOCK PPERFCOUNTERBLOCK* = ptr PERF_COUNTER_BLOCK PERF_COUNTER_DEFINITION* {.final, pure.} = object ByteLength*: DWORD @@ -10930,7 +10605,6 @@ type CounterSize*: DWORD CounterOffset*: DWORD - TPERFCOUNTERDEFINITION* = PERF_COUNTER_DEFINITION PPERFCOUNTERDEFINITION* = ptr PERF_COUNTER_DEFINITION PERF_DATA_BLOCK* {.final, pure.} = object Signature*: array[0..3, WCHAR] @@ -10948,7 +10622,6 @@ type SystemNameLength*: DWORD SystemNameOffset*: DWORD - TPERFDATABLOCK* = PERF_DATA_BLOCK PPERFDATABLOCK* = ptr PERF_DATA_BLOCK PERF_INSTANCE_DEFINITION* {.final, pure.} = object ByteLength*: DWORD @@ -10958,7 +10631,6 @@ type NameOffset*: DWORD NameLength*: DWORD - TPERFINSTANCEDEFINITION* = PERF_INSTANCE_DEFINITION PPERFINSTANCEDEFINITION* = PERF_INSTANCE_DEFINITION PERF_OBJECT_TYPE* {.final, pure.} = object TotalByteLength*: DWORD @@ -10976,7 +10648,6 @@ type PerfTime*: LARGE_INTEGER PerfFreq*: LARGE_INTEGER - TPERFOBJECTTYPE* = PERF_OBJECT_TYPE PPERFOBJECTTYPE* = ptr PERF_OBJECT_TYPE POLYTEXT* {.final, pure.} = object x*: int32 @@ -10987,12 +10658,10 @@ type rcl*: RECT pdx*: ptr int32 - TPOLYTEXT* = POLYTEXT PPOLYTEXT* = ptr POLYTEXT PORT_INFO_1* {.final, pure.} = object pName*: LPTSTR - TPORTINFO1* = PORT_INFO_1 PPORTINFO1* = ptr PORT_INFO_1 PORT_INFO_2* {.final, pure.} = object pPortName*: LPSTR @@ -11001,12 +10670,10 @@ type fPortType*: DWORD Reserved*: DWORD - TPORTINFO2* = PORT_INFO_2 PPORTINFO2* = ptr PORT_INFO_2 PREVENT_MEDIA_REMOVAL* {.final, pure.} = object PreventMediaRemoval*: bool - TPREVENTMEDIAREMOVAL* = PREVENT_MEDIA_REMOVAL PPREVENTMEDIAREMOVAL* = ptr PREVENT_MEDIA_REMOVAL #PRINTDLG = record conflicts with PrintDlg function TPRINTDLG* {.final, pure.} = object @@ -11032,14 +10699,12 @@ type LPPRINTDLG* = ptr TPRINTDLG PPRINTDLG* = ptr TPRINTDLG - TPD* = TPRINTDLG PPD* = ptr TPRINTDLG PRINTER_DEFAULTS* {.final, pure.} = object pDatatype*: LPTSTR pDevMode*: LPDEVMODE DesiredAccess*: ACCESS_MASK - TPRINTERDEFAULTS* = PRINTER_DEFAULTS PPRINTERDEFAULTS* = ptr PRINTER_DEFAULTS PRINTER_INFO_1* {.final, pure.} = object Flags*: DWORD @@ -11049,7 +10714,6 @@ type LPPRINTER_INFO_1* = ptr PRINTER_INFO_1 PPRINTER_INFO_1* = ptr PRINTER_INFO_1 - TPRINTERINFO1* = PRINTER_INFO_1 PRINTER_INFO_2* {.final, pure.} = object pServerName*: LPTSTR pPrinterName*: LPTSTR @@ -11073,19 +10737,16 @@ type cJobs*: DWORD AveragePPM*: DWORD - TPRINTERINFO2* = PRINTER_INFO_2 PPRINTERINFO2* = ptr PRINTER_INFO_2 PRINTER_INFO_3* {.final, pure.} = object pSecurityDescriptor*: PSECURITY_DESCRIPTOR - TPRINTERINFO3* = PRINTER_INFO_3 PPRINTERINFO3* = ptr PRINTER_INFO_3 PRINTER_INFO_4* {.final, pure.} = object pPrinterName*: LPTSTR pServerName*: LPTSTR Attributes*: DWORD - TPRINTERINFO4* = PRINTER_INFO_4 PPRINTERINFO4* = ptr PRINTER_INFO_4 PRINTER_INFO_5* {.final, pure.} = object pPrinterName*: LPTSTR @@ -11094,7 +10755,6 @@ type DeviceNotSelectedTimeout*: DWORD TransmissionRetryTimeout*: DWORD - TPRINTERINFO5* = PRINTER_INFO_5 PPRINTERINFO5* = ptr PRINTER_INFO_5 PRINTER_NOTIFY_INFO_DATA* {.final, pure.} = object `type`*: int16 @@ -11104,7 +10764,6 @@ type cbBuf*: DWORD pBuf*: LPVOID - TPRINTERNOTIFYINFODATA* = PRINTER_NOTIFY_INFO_DATA PPRINTERNOTIFYINFODATA* = ptr PRINTER_NOTIFY_INFO_DATA PRINTER_NOTIFY_INFO* {.final, pure.} = object Version*: DWORD @@ -11112,7 +10771,6 @@ type Count*: DWORD aData*: array[0..0, PRINTER_NOTIFY_INFO_DATA] - TPRINTERNOTIFYINFO* = PRINTER_NOTIFY_INFO PPRINTERNOTIFYINFO* = ptr PRINTER_NOTIFY_INFO PRINTER_NOTIFY_OPTIONS_TYPE* {.final, pure.} = object `type`*: int16 @@ -11123,19 +10781,16 @@ type pFields*: PWORD PPRINTER_NOTIFY_OPTIONS_TYPE* = ptr PRINTER_NOTIFY_OPTIONS_TYPE - TPRINTERNOTIFYOPTIONSTYPE* = PRINTER_NOTIFY_OPTIONS_TYPE PRINTER_NOTIFY_OPTIONS* {.final, pure.} = object Version*: DWORD Flags*: DWORD Count*: DWORD pTypes*: PPRINTER_NOTIFY_OPTIONS_TYPE - TPRINTERNOTIFYOPTIONS* = PRINTER_NOTIFY_OPTIONS PPRINTERNOTIFYOPTIONS* = ptr PRINTER_NOTIFY_OPTIONS PRINTPROCESSOR_INFO_1* {.final, pure.} = object pName*: LPTSTR - TPRINTPROCESSORINFO1* = PRINTPROCESSOR_INFO_1 PPRINTPROCESSORINFO1* = ptr PRINTPROCESSOR_INFO_1 PRIVILEGE_SET* {.final, pure.} = object PrivilegeCount*: DWORD @@ -11144,7 +10799,6 @@ type LPPRIVILEGE_SET* = ptr PRIVILEGE_SET PPRIVILEGE_SET* = ptr PRIVILEGE_SET - TPRIVILEGESET* = PRIVILEGE_SET PROCESS_HEAPENTRY* {.final, pure.} = object lpData*: PVOID cbData*: DWORD @@ -11158,7 +10812,6 @@ type hMem*: HANDLE LPPROCESS_HEAP_ENTRY* = ptr PROCESS_HEAPENTRY - TPROCESSHEAPENTRY* = PROCESS_HEAPENTRY PPROCESSHEAPENTRY* = ptr PROCESS_HEAPENTRY PROCESS_INFORMATION* {.final, pure.} = object hProcess*: HANDLE @@ -11167,11 +10820,9 @@ type dwThreadId*: DWORD LPPROCESS_INFORMATION* = ptr PROCESS_INFORMATION - TPROCESSINFORMATION* = PROCESS_INFORMATION PPROCESSINFORMATION* = ptr PROCESS_INFORMATION LPFNPSPCALLBACK* = proc (para1: HWND, para2: WINUINT, para3: LPVOID): WINUINT{. stdcall.} - TFNPSPCALLBACK* = LPFNPSPCALLBACK PROPSHEETPAGE* {.final, pure.} = object dwSize*: DWORD dwFlags*: DWORD @@ -11185,7 +10836,6 @@ type LPPROPSHEETPAGE* = ptr PROPSHEETPAGE LPCPROPSHEETPAGE* = ptr PROPSHEETPAGE - TPROPSHEETPAGE* = PROPSHEETPAGE PPROPSHEETPAGE* = ptr PROPSHEETPAGE emptyrecord* {.final, pure.} = object lpemptyrecord* = ptr emptyrecord @@ -11207,15 +10857,12 @@ type LPPROPSHEETHEADER* = ptr PROPSHEETHEADER LPCPROPSHEETHEADER* = ptr PROPSHEETHEADER - TPROPSHEETHEADER* = PROPSHEETHEADER PPROPSHEETHEADER* = ptr PROPSHEETHEADER # PropertySheet callbacks LPFNADDPROPSHEETPAGE* = proc (para1: HPROPSHEETPAGE, para2: LPARAM): WINBOOL{. stdcall.} - TFNADDPROPSHEETPAGE* = LPFNADDPROPSHEETPAGE LPFNADDPROPSHEETPAGES* = proc (para1: LPVOID, para2: LPFNADDPROPSHEETPAGE, para3: LPARAM): WINBOOL{.stdcall.} - TFNADDPROPSHEETPAGES* = LPFNADDPROPSHEETPAGES PROTOCOL_INFO* {.final, pure.} = object dwServiceFlags*: DWORD iAddressFamily*: WINT @@ -11226,29 +10873,25 @@ type dwMessageSize*: DWORD lpProtocol*: LPTSTR - TPROTOCOLINFO* = PROTOCOL_INFO PPROTOCOLINFO* = ptr PROTOCOL_INFO PROVIDOR_INFO_1* {.final, pure.} = object pName*: LPTSTR pEnvironment*: LPTSTR pDLLName*: LPTSTR - TPROVIDORINFO1* = PROVIDOR_INFO_1 PPROVIDORINFO1* = ptr PROVIDOR_INFO_1 PSHNOTIFY* {.final, pure.} = object hdr*: NMHDR lParam*: LPARAM LPPSHNOTIFY* = ptr PSHNOTIFY - TPSHNOTIFY* = PSHNOTIFY PPSHNOTIFY* = ptr PSHNOTIFY PUNCTUATION* {.final, pure.} = object iSize*: WINUINT szPunctuation*: LPSTR - Tpunctuation* = PUNCTUATION Ppunctuation* = ptr PUNCTUATION - TQUERY_SERVICE_CONFIG* {.final, pure.} = object + TQUERY_SERVICE_CONFIG* {.final, pure.} = object # Name conflict if we drop the `T` dwServiceType*: DWORD dwStartType*: DWORD dwErrorControl*: DWORD @@ -11261,7 +10904,7 @@ type LPQUERY_SERVICE_CONFIG* = ptr TQUERY_SERVICE_CONFIG PQUERYSERVICECONFIG* = ptr TQUERY_SERVICE_CONFIG - TQUERY_SERVICE_LOCK_STATUS* {.final, pure.} = object + TQUERY_SERVICE_LOCK_STATUS* {.final, pure.} = object # Name conflict if we drop the `T` fIsLocked*: DWORD lpLockOwner*: LPTSTR dwLockDuration*: DWORD @@ -11271,28 +10914,25 @@ type RASAMB* {.final, pure.} = object dwSize*: DWORD dwError*: DWORD - szNetBiosError*: array[0..(NETBIOS_NAME_LEN + 1) - 1, TCHAR] + szNetBiosError*: array[0..(NETBIOS_NAME_LEN + 1) - 1, CHAR] bLana*: int8 - TRASAMB* = RASAMB PRASAMB* = ptr RASAMB RASCONN* {.final, pure.} = object dwSize*: DWORD hrasconn*: HRASCONN - szEntryName*: array[0..(RAS_MaxEntryName + 1) - 1, TCHAR] + szEntryName*: array[0..(RAS_MaxEntryName + 1) - 1, CHAR] szDeviceType*: array[0..(RAS_MaxDeviceType + 1) - 1, char] szDeviceName*: array[0..(RAS_MaxDeviceName + 1) - 1, char] - TRASCONN* = RASCONN PRASCONN* = ptr RASCONN RASCONNSTATUS* {.final, pure.} = object dwSize*: DWORD rasconnstate*: RASCONNSTATE dwError*: DWORD - szDeviceType*: array[0..(RAS_MaxDeviceType + 1) - 1, TCHAR] - szDeviceName*: array[0..(RAS_MaxDeviceName + 1) - 1, TCHAR] + szDeviceType*: array[0..(RAS_MaxDeviceType + 1) - 1, CHAR] + szDeviceName*: array[0..(RAS_MaxDeviceName + 1) - 1, CHAR] - TRASCONNSTATUS* = RASCONNSTATUS PRASCONNSTATUS* = ptr RASCONNSTATUS RASDIALEXTENSIONS* {.final, pure.} = object dwSize*: DWORD @@ -11300,48 +10940,42 @@ type hwndParent*: HWND reserved*: DWORD - TRASDIALEXTENSIONS* = RASDIALEXTENSIONS PRASDIALEXTENSIONS* = ptr RASDIALEXTENSIONS RASDIALPARAMS* {.final, pure.} = object dwSize*: DWORD - szEntryName*: array[0..(RAS_MaxEntryName + 1) - 1, TCHAR] - szPhoneNumber*: array[0..(RAS_MaxPhoneNumber + 1) - 1, TCHAR] - szCallbackNumber*: array[0..(RAS_MaxCallbackNumber + 1) - 1, TCHAR] - szUserName*: array[0..(UNLEN + 1) - 1, TCHAR] - szPassword*: array[0..(PWLEN + 1) - 1, TCHAR] - szDomain*: array[0..(DNLEN + 1) - 1, TCHAR] + szEntryName*: array[0..(RAS_MaxEntryName + 1) - 1, CHAR] + szPhoneNumber*: array[0..(RAS_MaxPhoneNumber + 1) - 1, CHAR] + szCallbackNumber*: array[0..(RAS_MaxCallbackNumber + 1) - 1, CHAR] + szUserName*: array[0..(UNLEN + 1) - 1, CHAR] + szPassword*: array[0..(PWLEN + 1) - 1, CHAR] + szDomain*: array[0..(DNLEN + 1) - 1, CHAR] - TRASDIALPARAMS* = RASDIALPARAMS PRASDIALPARAMS* = ptr RASDIALPARAMS RASENTRYNAME* {.final, pure.} = object dwSize*: DWORD - szEntryName*: array[0..(RAS_MaxEntryName + 1) - 1, TCHAR] + szEntryName*: array[0..(RAS_MaxEntryName + 1) - 1, CHAR] - TRASENTRYNAME* = RASENTRYNAME PRASENTRYNAME* = ptr RASENTRYNAME RASPPPIP* {.final, pure.} = object dwSize*: DWORD dwError*: DWORD - szIpAddress*: array[0..(RAS_MaxIpAddress + 1) - 1, TCHAR] + szIpAddress*: array[0..(RAS_MaxIpAddress + 1) - 1, CHAR] - TRASPPPIP* = RASPPPIP PRASPPPIP* = ptr RASPPPIP RASPPPIPX* {.final, pure.} = object dwSize*: DWORD dwError*: DWORD - szIpxAddress*: array[0..(RAS_MaxIpxAddress + 1) - 1, TCHAR] + szIpxAddress*: array[0..(RAS_MaxIpxAddress + 1) - 1, CHAR] - TRASPPPIPX* = RASPPPIPX PRASPPPIPX* = ptr RASPPPIPX RASPPPNBF* {.final, pure.} = object dwSize*: DWORD dwError*: DWORD dwNetBiosError*: DWORD - szNetBiosError*: array[0..(NETBIOS_NAME_LEN + 1) - 1, TCHAR] - szWorkstationName*: array[0..(NETBIOS_NAME_LEN + 1) - 1, TCHAR] + szNetBiosError*: array[0..(NETBIOS_NAME_LEN + 1) - 1, CHAR] + szWorkstationName*: array[0..(NETBIOS_NAME_LEN + 1) - 1, CHAR] bLana*: int8 - TRASPPPNBF* = RASPPPNBF PRASPPPNBF* = ptr RASPPPNBF RASTERIZER_STATUS* {.final, pure.} = object nSize*: SHORT @@ -11349,34 +10983,29 @@ type nLanguageID*: SHORT LPRASTERIZER_STATUS* = ptr RASTERIZER_STATUS - TRASTERIZERSTATUS* = RASTERIZER_STATUS PRASTERIZERSTATUS* = ptr RASTERIZER_STATUS REASSIGN_BLOCKS* {.final, pure.} = object Reserved*: int16 Count*: int16 BlockNumber*: array[0..0, DWORD] - TREASSIGNBLOCKS* = REASSIGN_BLOCKS PREASSIGNBLOCKS* = ptr REASSIGN_BLOCKS REMOTE_NAME_INFO* {.final, pure.} = object lpUniversalName*: LPTSTR lpConnectionName*: LPTSTR lpRemainingPath*: LPTSTR - TREMOTENAMEINFO* = REMOTE_NAME_INFO PREMOTENAMEINFO* = ptr REMOTE_NAME_INFO REPASTESPECIAL* {.final, pure.} = object dwAspect*: DWORD dwParam*: DWORD - Trepastespecial* = REPASTESPECIAL Prepastespecial* = ptr REPASTESPECIAL REQRESIZE* {.final, pure.} = object nmhdr*: NMHDR rc*: RECT - Treqresize* = REQRESIZE Preqresize* = ptr REQRESIZE RGNDATAHEADER* {.final, pure.} = object dwSize*: DWORD @@ -11385,14 +11014,12 @@ type nRgnSize*: DWORD rcBound*: RECT - TRGNDATAHEADER* = RGNDATAHEADER PRGNDATAHEADER* = ptr RGNDATAHEADER RGNDATA* {.final, pure.} = object rdh*: RGNDATAHEADER Buffer*: array[0..0, char] LPRGNDATA* = ptr RGNDATA - TRGNDATA* = RGNDATA PRGNDATA* = ptr RGNDATA SCROLLINFO* {.final, pure.} = object cbSize*: WINUINT @@ -11405,7 +11032,6 @@ type LPSCROLLINFO* = ptr SCROLLINFO LPCSCROLLINFO* = ptr SCROLLINFO - TSCROLLINFO* = SCROLLINFO PSCROLLINFO* = ptr SCROLLINFO SECURITY_ATTRIBUTES* {.final, pure.} = object nLength*: DWORD @@ -11413,17 +11039,14 @@ type bInheritHandle*: WINBOOL LPSECURITY_ATTRIBUTES* = ptr SECURITY_ATTRIBUTES - TSECURITYATTRIBUTES* = SECURITY_ATTRIBUTES PSECURITYATTRIBUTES* = ptr SECURITY_ATTRIBUTES SECURITY_INFORMATION* = DWORD PSECURITY_INFORMATION* = ptr SECURITY_INFORMATION - TSECURITYINFORMATION* = SECURITY_INFORMATION SELCHANGE* {.final, pure.} = object nmhdr*: NMHDR chrg*: CHARRANGE seltyp*: int16 - Tselchange* = SELCHANGE Pselchange* = ptr SELCHANGE SERIALKEYS* {.final, pure.} = object cbSize*: DWORD @@ -11434,14 +11057,12 @@ type iPortState*: DWORD LPSERIALKEYS* = ptr SERIALKEYS - TSERIALKEYS* = SERIALKEYS PSERIALKEYS* = ptr SERIALKEYS SERVICE_TABLE_ENTRY* {.final, pure.} = object lpServiceName*: LPTSTR lpServiceProc*: LPSERVICE_MAIN_FUNCTION LPSERVICE_TABLE_ENTRY* = ptr SERVICE_TABLE_ENTRY - TSERVICETABLEENTRY* = SERVICE_TABLE_ENTRY PSERVICETABLEENTRY* = ptr SERVICE_TABLE_ENTRY SERVICE_TYPE_VALUE_ABS* {.final, pure.} = object dwNameSpace*: DWORD @@ -11450,14 +11071,12 @@ type lpValueName*: LPTSTR lpValue*: PVOID - TSERVICETYPEVALUEABS* = SERVICE_TYPE_VALUE_ABS PSERVICETYPEVALUEABS* = ptr SERVICE_TYPE_VALUE_ABS SERVICE_TYPE_INFO_ABS* {.final, pure.} = object lpTypeName*: LPTSTR dwValueCount*: DWORD Values*: array[0..0, SERVICE_TYPE_VALUE_ABS] - TSERVICETYPEINFOABS* = SERVICE_TYPE_INFO_ABS PSERVICETYPEINFOABS* = ptr SERVICE_TYPE_INFO_ABS SESSION_BUFFER* {.final, pure.} = object lsn*: UCHAR @@ -11467,7 +11086,6 @@ type rcvs_outstanding*: UCHAR sends_outstanding*: UCHAR - TSESSIONBUFFER* = SESSION_BUFFER PSESSIONBUFFER* = ptr SESSION_BUFFER SESSION_HEADER* {.final, pure.} = object sess_name*: UCHAR @@ -11475,16 +11093,13 @@ type rcv_dg_outstanding*: UCHAR rcv_any_outstanding*: UCHAR - TSESSIONHEADER* = SESSION_HEADER PSESSIONHEADER* = ptr SESSION_HEADER SET_PARTITION_INFORMATION* {.final, pure.} = object PartitionType*: int8 - TSETPARTITIONINFORMATION* = SET_PARTITION_INFORMATION PSETPARTITIONINFORMATION* = ptr SET_PARTITION_INFORMATION SHCONTF* = enum SHCONTF_FOLDERS = 32, SHCONTF_NONFOLDERS = 64, SHCONTF_INCLUDEHIDDEN = 128 - TSHCONTF* = SHCONTF SHFILEINFO* {.final, pure.} = object hIcon*: HICON iIcon*: int32 @@ -11492,10 +11107,8 @@ type szDisplayName*: array[0..(MAX_PATH) - 1, char] szTypeName*: array[0..79, char] - TSHFILEINFO* = SHFILEINFO PSHFILEINFO* = ptr SHFILEINFO FILEOP_FLAGS* = int16 - TFILEOPFLAGS* = FILEOP_FLAGS PFILEOPFLAGS* = ptr FILEOP_FLAGS SHFILEOPSTRUCT* {.final, pure.} = object hwnd*: HWND @@ -11508,11 +11121,9 @@ type lpszProgressTitle*: LPCSTR LPSHFILEOPSTRUCT* = ptr SHFILEOPSTRUCT - TSHFILEOPSTRUCT* = SHFILEOPSTRUCT PSHFILEOPSTRUCT* = ptr SHFILEOPSTRUCT SHGNO* = enum SHGDN_NORMAL = 0, SHGDN_INFOLDER = 1, SHGDN_FORPARSING = 0x00008000 - TSHGDN* = SHGNO SHNAMEMAPPING* {.final, pure.} = object pszOldPath*: LPSTR pszNewPath*: LPSTR @@ -11520,21 +11131,17 @@ type cchNewPath*: int32 LPSHNAMEMAPPING* = ptr SHNAMEMAPPING - TSHNAMEMAPPING* = SHNAMEMAPPING PSHNAMEMAPPING* = ptr SHNAMEMAPPING SID_AND_ATTRIBUTES* {.final, pure.} = object Sid*: PSID Attributes*: DWORD - TSIDANDATTRIBUTES* = SID_AND_ATTRIBUTES PSIDANDATTRIBUTES* = ptr SID_AND_ATTRIBUTES SID_AND_ATTRIBUTES_ARRAY* = array[0..(ANYSIZE_ARRAY) - 1, SID_AND_ATTRIBUTES] PSID_AND_ATTRIBUTES_ARRAY* = ptr SID_AND_ATTRIBUTES_ARRAY - TSIDANDATTRIBUTESARRAY* = SID_AND_ATTRIBUTES_ARRAY SINGLE_LIST_ENTRY* {.final, pure.} = object Next*: ptr SINGLE_LIST_ENTRY - TSINGLELISTENTRY* = SINGLE_LIST_ENTRY PSINGLELISTENTRY* = ptr SINGLE_LIST_ENTRY SOUNDSENTRY* {.final, pure.} = object cbSize*: WINUINT @@ -11551,7 +11158,6 @@ type iWindowsEffectOrdinal*: DWORD LPSOUNDSENTRY* = ptr SOUNDSENTRY - TSOUNDSENTRY* = SOUNDSENTRY PSOUNDSENTRY* = ptr SOUNDSENTRY STARTUPINFO* {.final, pure.} = object cb*: DWORD @@ -11574,42 +11180,36 @@ type hStdError*: HANDLE LPSTARTUPINFO* = ptr STARTUPINFO - TSTARTUPINFO* = STARTUPINFO PSTARTUPINFO* = ptr STARTUPINFO STICKYKEYS* {.final, pure.} = object cbSize*: DWORD dwFlags*: DWORD LPSTICKYKEYS* = ptr STICKYKEYS - TSTICKYKEYS* = STICKYKEYS PSTICKYKEYS* = ptr STICKYKEYS STRRET* {.final, pure.} = object uType*: WINUINT cStr*: array[0..(MAX_PATH) - 1, char] LPSTRRET* = ptr STRRET - TSTRRET* = STRRET PSTRRET* = ptr STRRET STYLEBUF* {.final, pure.} = object dwStyle*: DWORD szDescription*: array[0..31, char] LPSTYLEBUF* = ptr STYLEBUF - TSTYLEBUF* = STYLEBUF PSTYLEBUF* = ptr STYLEBUF STYLESTRUCT* {.final, pure.} = object styleOld*: DWORD styleNew*: DWORD LPSTYLESTRUCT* = ptr STYLESTRUCT - TSTYLESTRUCT* = STYLESTRUCT PSTYLESTRUCT* = ptr STYLESTRUCT SYSTEM_AUDIT_ACE* {.final, pure.} = object Header*: ACE_HEADER Mask*: ACCESS_MASK SidStart*: DWORD - TSYSTEMAUDITACE* = SYSTEM_AUDIT_ACE PSYSTEMAUDITACE* = ptr SYSTEM_AUDIT_ACE SYSTEM_INFO* {.final, pure.} = object dwOemId*: DWORD @@ -11624,7 +11224,6 @@ type wProcessorRevision*: int16 LPSYSTEM_INFO* = ptr SYSTEM_INFO - TSYSTEMINFO* = SYSTEM_INFO PSYSTEMINFO* = ptr SYSTEM_INFO SYSTEM_POWER_STATUS* {.final, pure.} = object ACLineStatus*: int8 @@ -11634,13 +11233,11 @@ type BatteryLifeTime*: DWORD BatteryFullLifeTime*: DWORD - TSYSTEMPOWERSTATUS* = SYSTEM_POWER_STATUS PSYSTEMPOWERSTATUS* = ptr SYSTEM_POWER_STATUS LPSYSTEM_POWER_STATUS* = ptr emptyrecord TAPE_ERASE* {.final, pure.} = object `type`*: ULONG - TTAPEERASE* = TAPE_ERASE PTAPEERASE* = ptr TAPE_ERASE TAPE_GET_DRIVE_PARAMETERS* {.final, pure.} = object ECC*: bool @@ -11655,7 +11252,6 @@ type FeaturesHigh*: ULONG EOTWarningZoneSize*: ULONG - TTAPEGETDRIVEPARAMETERS* = TAPE_GET_DRIVE_PARAMETERS PTAPEGETDRIVEPARAMETERS* = ptr TAPE_GET_DRIVE_PARAMETERS TAPE_GET_MEDIA_PARAMETERS* {.final, pure.} = object Capacity*: LARGE_INTEGER @@ -11664,7 +11260,6 @@ type PartitionCount*: DWORD WriteProtected*: bool - TTAPEGETMEDIAPARAMETERS* = TAPE_GET_MEDIA_PARAMETERS PTAPEGETMEDIAPARAMETERS* = ptr TAPE_GET_MEDIA_PARAMETERS TAPE_GET_POSITION* {.final, pure.} = object `type`*: ULONG @@ -11672,12 +11267,10 @@ type OffsetLow*: ULONG OffsetHigh*: ULONG - TTAPEGETPOSITION* = TAPE_GET_POSITION PTAPEGETPOSITION* = ptr TAPE_GET_POSITION TAPE_PREPARE* {.final, pure.} = object Operation*: ULONG - TTAPEPREPARE* = TAPE_PREPARE PTAPEPREPARE* = ptr TAPE_PREPARE TAPE_SET_DRIVE_PARAMETERS* {.final, pure.} = object ECC*: bool @@ -11686,12 +11279,10 @@ type ReportSetmarks*: bool EOTWarningZoneSize*: ULONG - TTAPESETDRIVEPARAMETERS* = TAPE_SET_DRIVE_PARAMETERS PTAPESETDRIVEPARAMETERS* = ptr TAPE_SET_DRIVE_PARAMETERS TAPE_SET_MEDIA_PARAMETERS* {.final, pure.} = object BlockSize*: ULONG - TTAPESETMEDIAPARAMETERS* = TAPE_SET_MEDIA_PARAMETERS PTAPESETMEDIAPARAMETERS* = ptr TAPE_SET_MEDIA_PARAMETERS TAPE_SET_POSITION* {.final, pure.} = object `Method`*: ULONG @@ -11699,15 +11290,13 @@ type OffsetLow*: ULONG OffsetHigh*: ULONG - TTAPESETPOSITION* = TAPE_SET_POSITION PTAPESETPOSITION* = ptr TAPE_SET_POSITION TAPE_WRITE_MARKS* {.final, pure.} = object `type`*: ULONG Count*: ULONG - TTAPEWRITEMARKS* = TAPE_WRITE_MARKS PTAPEWRITEMARKS* = ptr TAPE_WRITE_MARKS - TTBADDBITMAP* {.final, pure.} = object + TTBADDBITMAP* {.final, pure.} = object # Name conflict if we drop the `T` hInst*: HINST nID*: WINUINT @@ -11723,7 +11312,6 @@ type LPTBBUTTON* = ptr TBBUTTON LPCTBBUTTON* = ptr TBBUTTON - TTBBUTTON* = TBBUTTON PTBBUTTON* = ptr TBBUTTON TBNOTIFY* {.final, pure.} = object hdr*: NMHDR @@ -11733,20 +11321,17 @@ type pszText*: LPTSTR LPTBNOTIFY* = ptr TBNOTIFY - TTBNOTIFY* = TBNOTIFY PTBNOTIFY* = ptr TBNOTIFY TBSAVEPARAMS* {.final, pure.} = object hkr*: HKEY pszSubKey*: LPCTSTR pszValueName*: LPCTSTR - TTBSAVEPARAMS* = TBSAVEPARAMS PTBSAVEPARAMS* = ptr TBSAVEPARAMS TC_HITTESTINFO* {.final, pure.} = object pt*: POINT flags*: WINUINT - TTCHITTESTINFO* = TC_HITTESTINFO PTCHITTESTINFO* = ptr TC_HITTESTINFO TC_ITEM* {.final, pure.} = object mask*: WINUINT @@ -11757,7 +11342,6 @@ type iImage*: int32 lParam*: LPARAM - TTCITEM* = TC_ITEM PTCITEM* = ptr TC_ITEM TC_ITEMHEADER* {.final, pure.} = object mask*: WINUINT @@ -11767,20 +11351,17 @@ type cchTextMax*: int32 iImage*: int32 - TTCITEMHEADER* = TC_ITEMHEADER PTCITEMHEADER* = ptr TC_ITEMHEADER TC_KEYDOWN* {.final, pure.} = object hdr*: NMHDR wVKey*: int16 flags*: WINUINT - TTCKEYDOWN* = TC_KEYDOWN PTCKEYDOWN* = ptr TC_KEYDOWN TEXTRANGE* {.final, pure.} = object chrg*: CHARRANGE lpstrText*: LPSTR - Ttextrange* = TEXTRANGE Ptextrange* = ptr TEXTRANGE TIME_ZONE_INFORMATION* {.final, pure.} = object Bias*: LONG @@ -11792,15 +11373,13 @@ type DaylightBias*: LONG LPTIME_ZONE_INFORMATION* = ptr TIME_ZONE_INFORMATION - TTIMEZONEINFORMATION* = TIME_ZONE_INFORMATION PTIMEZONEINFORMATION* = ptr TIME_ZONE_INFORMATION TOGGLEKEYS* {.final, pure.} = object cbSize*: DWORD dwFlags*: DWORD - TTOGGLEKEYS* = TOGGLEKEYS PTOGGLEKEYS* = ptr TOGGLEKEYS - TTOKEN_SOURCE* {.final, pure.} = object + TTOKEN_SOURCE* {.final, pure.} = object # Name confict if we drop the `T` SourceName*: array[0..7, char] SourceIdentifier*: LUID @@ -11811,33 +11390,32 @@ type ModifiedId*: LUID TokenSource*: TTOKEN_SOURCE - TTOKENCONTROL* = TOKEN_CONTROL PTOKENCONTROL* = ptr TOKEN_CONTROL TTOKEN_DEFAULT_DACL* {.final, pure.} = object DefaultDacl*: PACL - PTOKENDEFAULTDACL* = ptr TTOKEN_DEFAULT_DACL - TTOKEN_GROUPS* {.final, pure.} = object + PTOKENDEFAULTDACL* = ptr TTOKEN_DEFAULT_DACL # Name conflict if we drop the `T` + TTOKEN_GROUPS* {.final, pure.} = object # Name conflict if we drop the `T` GroupCount*: DWORD Groups*: array[0..(ANYSIZE_ARRAY) - 1, SID_AND_ATTRIBUTES] LPTOKEN_GROUPS* = ptr TTOKEN_GROUPS PTOKENGROUPS* = ptr TTOKEN_GROUPS - TTOKEN_OWNER* {.final, pure.} = object + TTOKEN_OWNER* {.final, pure.} = object # Name conflict if we drop the `T` Owner*: PSID PTOKENOWNER* = ptr TTOKEN_OWNER TTOKEN_PRIMARY_GROUP* {.final, pure.} = object PrimaryGroup*: PSID - PTOKENPRIMARYGROUP* = ptr TTOKEN_PRIMARY_GROUP - TTOKEN_PRIVILEGES* {.final, pure.} = object + PTOKENPRIMARYGROUP* = ptr TTOKEN_PRIMARY_GROUP # Name conflict if we drop the `T` + TTOKEN_PRIVILEGES* {.final, pure.} = object # Name conflict if we drop the `T` PrivilegeCount*: DWORD Privileges*: array[0..(ANYSIZE_ARRAY) - 1, LUID_AND_ATTRIBUTES] PTOKEN_PRIVILEGES* = ptr TTOKEN_PRIVILEGES LPTOKEN_PRIVILEGES* = ptr TTOKEN_PRIVILEGES - TTOKEN_STATISTICS* {.final, pure.} = object + TTOKEN_STATISTICS* {.final, pure.} = object # Name conflict if we drop the `T` TokenId*: LUID AuthenticationId*: LUID ExpirationTime*: LARGE_INTEGER @@ -11850,7 +11428,7 @@ type ModifiedId*: LUID PTOKENSTATISTICS* = ptr TTOKEN_STATISTICS - TTOKEN_USER* {.final, pure.} = object + TTOKEN_USER* {.final, pure.} = object # Name conflict if we drop the `T` User*: SID_AND_ATTRIBUTES PTOKENUSER* = ptr TTOKEN_USER @@ -11864,7 +11442,6 @@ type lpszText*: LPTSTR LPTOOLINFO* = ptr TOOLINFO - TTOOLINFO* = TOOLINFO PTOOLINFO* = ptr TOOLINFO TOOLTIPTEXT* {.final, pure.} = object hdr*: NMHDR @@ -11874,14 +11451,12 @@ type uFlags*: WINUINT LPTOOLTIPTEXT* = ptr TOOLTIPTEXT - TTOOLTIPTEXT* = TOOLTIPTEXT PTOOLTIPTEXT* = ptr TOOLTIPTEXT TPMPARAMS* {.final, pure.} = object cbSize*: WINUINT rcExclude*: RECT LPTPMPARAMS* = ptr TPMPARAMS - TTPMPARAMS* = TPMPARAMS PTPMPARAMS* = ptr TPMPARAMS TRANSMIT_FILE_BUFFERS* {.final, pure.} = object Head*: PVOID @@ -11889,7 +11464,6 @@ type Tail*: PVOID TailLength*: DWORD - TTRANSMITFILEBUFFERS* = TRANSMIT_FILE_BUFFERS PTRANSMITFILEBUFFERS* = ptr TRANSMIT_FILE_BUFFERS TTHITTESTINFO* {.final, pure.} = object hwnd*: HWND @@ -11897,7 +11471,6 @@ type ti*: TOOLINFO LPHITTESTINFO* = ptr TTHITTESTINFO - TTTHITTESTINFO* = TTHITTESTINFO PTTHITTESTINFO* = ptr TTHITTESTINFO TTPOLYCURVE* {.final, pure.} = object wType*: int16 @@ -11905,7 +11478,6 @@ type apfx*: array[0..0, POINTFX] LPTTPOLYCURVE* = ptr TTPOLYCURVE - TTTPOLYCURVE* = TTPOLYCURVE PTTPOLYCURVE* = ptr TTPOLYCURVE TTPOLYGONHEADER* {.final, pure.} = object cb*: DWORD @@ -11913,13 +11485,11 @@ type pfxStart*: POINTFX LPTTPOLYGONHEADER* = ptr TTPOLYGONHEADER - TTTPOLYGONHEADER* = TTPOLYGONHEADER PTTPOLYGONHEADER* = ptr TTPOLYGONHEADER TV_DISPINFO* {.final, pure.} = object hdr*: NMHDR item*: TV_ITEM - TTVDISPINFO* = TV_DISPINFO PTVDISPINFO* = ptr TV_DISPINFO TV_HITTESTINFO* {.final, pure.} = object pt*: POINT @@ -11927,7 +11497,6 @@ type hItem*: HTREEITEM LPTV_HITTESTINFO* = ptr TV_HITTESTINFO - TTVHITTESTINFO* = TV_HITTESTINFO PTVHITTESTINFO* = ptr TV_HITTESTINFO TV_INSERTSTRUCT* {.final, pure.} = object hParent*: HTREEITEM @@ -11935,14 +11504,12 @@ type item*: TV_ITEM LPTV_INSERTSTRUCT* = ptr TV_INSERTSTRUCT - TTVINSERTSTRUCT* = TV_INSERTSTRUCT PTVINSERTSTRUCT* = ptr TV_INSERTSTRUCT TV_KEYDOWN* {.final, pure.} = object hdr*: NMHDR wVKey*: int16 flags*: WINUINT - TTVKEYDOWN* = TV_KEYDOWN PTVKEYDOWN* = ptr TV_KEYDOWN TV_SORTCB* {.final, pure.} = object hParent*: HTREEITEM @@ -11950,25 +11517,21 @@ type lParam*: LPARAM LPTV_SORTCB* = ptr TV_SORTCB - TTVSORTCB* = TV_SORTCB PTVSORTCB* = ptr TV_SORTCB UDACCEL* {.final, pure.} = object nSec*: WINUINT nInc*: WINUINT - TUDACCEL* = UDACCEL PUDACCEL* = ptr UDACCEL UNIVERSAL_NAME_INFO* {.final, pure.} = object lpUniversalName*: LPTSTR - TUNIVERSALNAMEINFO* = UNIVERSAL_NAME_INFO PUNIVERSALNAMEINFO* = ptr UNIVERSAL_NAME_INFO USEROBJECTFLAGS* {.final, pure.} = object fInherit*: WINBOOL fReserved*: WINBOOL dwFlags*: DWORD - TUSEROBJECTFLAGS* = USEROBJECTFLAGS PUSEROBJECTFLAGS* = ptr USEROBJECTFLAGS VALENT* {.final, pure.} = object ve_valuename*: LPTSTR @@ -11976,16 +11539,13 @@ type ve_valueptr*: DWORD ve_type*: DWORD - TVALENT* = VALENT PVALENT* = ptr VALENT value_ent* = VALENT - Tvalue_ent* = VALENT Pvalue_ent* = ptr VALENT VERIFY_INFORMATION* {.final, pure.} = object StartingOffset*: LARGE_INTEGER len*: DWORD - TVERIFYINFORMATION* = VERIFY_INFORMATION PVERIFYINFORMATION* = ptr VERIFY_INFORMATION VS_FIXEDFILEINFO* {.final, pure.} = object dwSignature*: DWORD @@ -12002,7 +11562,6 @@ type dwFileDateMS*: DWORD dwFileDateLS*: DWORD - TVSFIXEDFILEINFO* = VS_FIXEDFILEINFO PVSFIXEDFILEINFO* = ptr VS_FIXEDFILEINFO WIN32_FIND_DATA* {.final, pure.} = object dwFileAttributes*: DWORD @@ -12013,13 +11572,11 @@ type nFileSizeLow*: DWORD dwReserved0*: DWORD dwReserved1*: DWORD - cFileName*: array[0..(MAX_PATH) - 1, TCHAR] - cAlternateFileName*: array[0..13, TCHAR] + cFileName*: array[0..(MAX_PATH) - 1, CHAR] + cAlternateFileName*: array[0..13, CHAR] LPWIN32_FIND_DATA* = ptr WIN32_FIND_DATA PWIN32_FIND_DATA* = ptr WIN32_FIND_DATA - TWIN32FINDDATA* = WIN32_FIND_DATA - TWIN32FINDDATAA* = WIN32_FIND_DATA WIN32_FIND_DATAW* {.final, pure.} = object dwFileAttributes*: DWORD ftCreationTime*: FILETIME @@ -12034,7 +11591,6 @@ type LPWIN32_FIND_DATAW* = ptr WIN32_FIND_DATAW PWIN32_FIND_DATAW* = ptr WIN32_FIND_DATAW - TWIN32FINDDATAW* = WIN32_FIND_DATAW WIN32_STREAM_ID* {.final, pure.} = object dwStreamId*: DWORD dwStreamAttributes*: DWORD @@ -12042,7 +11598,6 @@ type dwStreamNameSize*: DWORD cStreamName*: ptr WCHAR - TWIN32STREAMID* = WIN32_STREAM_ID PWIN32STREAMID* = ptr WIN32_STREAM_ID WINDOWPLACEMENT* {.final, pure.} = object len*: WINUINT @@ -12052,7 +11607,6 @@ type ptMaxPosition*: POINT rcNormalPosition*: RECT - TWINDOWPLACEMENT* = WINDOWPLACEMENT PWINDOWPLACEMENT* = ptr WINDOWPLACEMENT WNDCLASS* {.final, pure.} = object style*: WINUINT @@ -12067,8 +11621,6 @@ type lpszClassName*: LPCTSTR LPWNDCLASS* = ptr WNDCLASS - TWNDCLASS* = WNDCLASS - TWNDCLASSA* = WNDCLASS PWNDCLASS* = ptr WNDCLASS WNDCLASSW* {.final, pure.} = object style*: WINUINT @@ -12083,7 +11635,6 @@ type lpszClassName*: LPCWSTR LPWNDCLASSW* = ptr WNDCLASSW - TWNDCLASSW* = WNDCLASSW PWNDCLASSW* = ptr WNDCLASSW WNDCLASSEX* {.final, pure.} = object cbSize*: WINUINT @@ -12100,8 +11651,6 @@ type hIconSm*: HANDLE LPWNDCLASSEX* = ptr WNDCLASSEX - TWNDCLASSEX* = WNDCLASSEX - TWNDCLASSEXA* = WNDCLASSEX PWNDCLASSEX* = ptr WNDCLASSEX WNDCLASSEXW* {.final, pure.} = object cbSize*: WINUINT @@ -12118,7 +11667,6 @@ type hIconSm*: HANDLE LPWNDCLASSEXW* = ptr WNDCLASSEXW - TWNDCLASSEXW* = WNDCLASSEXW PWNDCLASSEXW* = ptr WNDCLASSEXW CONNECTDLGSTRUCT* {.final, pure.} = object cbStructure*: DWORD @@ -12128,7 +11676,6 @@ type dwDevNum*: DWORD LPCONNECTDLGSTRUCT* = ptr CONNECTDLGSTRUCT - TCONNECTDLGSTRUCT* = CONNECTDLGSTRUCT PCONNECTDLGSTRUCT* = ptr CONNECTDLGSTRUCT DISCDLGSTRUCT* {.final, pure.} = object cbStructure*: DWORD @@ -12138,8 +11685,6 @@ type dwFlags*: DWORD LPDISCDLGSTRUCT* = ptr DISCDLGSTRUCT - TDISCDLGSTRUCT* = DISCDLGSTRUCT - TDISCDLGSTRUCTA* = DISCDLGSTRUCT PDISCDLGSTRUCT* = ptr DISCDLGSTRUCT NETINFOSTRUCT* {.final, pure.} = object cbStructure*: DWORD @@ -12152,7 +11697,6 @@ type dwDrives*: DWORD LPNETINFOSTRUCT* = ptr NETINFOSTRUCT - TNETINFOSTRUCT* = NETINFOSTRUCT PNETINFOSTRUCT* = ptr NETINFOSTRUCT NETCONNECTINFOSTRUCT* {.final, pure.} = object cbStructure*: DWORD @@ -12162,11 +11706,10 @@ type dwOptDataSize*: DWORD LPNETCONNECTINFOSTRUCT* = ptr NETCONNECTINFOSTRUCT - TNETCONNECTINFOSTRUCT* = NETCONNECTINFOSTRUCT PNETCONNECTINFOSTRUCT* = ptr NETCONNECTINFOSTRUCT ENUMMETAFILEPROC* = proc (para1: HDC, para2: HANDLETABLE, para3: METARECORD, para4: int32, para5: LPARAM): int32{.stdcall.} - ENHMETAFILEPROC* = proc (para1: HDC, para2: HANDLETABLE, para3: TENHMETARECORD, + ENHMETAFILEPROC* = proc (para1: HDC, para2: HANDLETABLE, para3: ENHMETARECORD, para4: int32, para5: LPARAM): int32{.stdcall.} ENUMFONTSPROC* = proc (para1: LPLOGFONT, para2: LPTEXTMETRIC, para3: DWORD, para4: LPARAM): int32{.stdcall.} @@ -12181,7 +11724,6 @@ type x*: float32 y*: float32 - TPOINTFLOAT* = POINTFLOAT PPOINTFLOAT* = ptr POINTFLOAT GLYPHMETRICSFLOAT* {.final, pure.} = object gmfBlackBoxX*: float32 @@ -12191,7 +11733,6 @@ type gmfCellIncY*: float32 LPGLYPHMETRICSFLOAT* = ptr GLYPHMETRICSFLOAT - TGLYPHMETRICSFLOAT* = GLYPHMETRICSFLOAT PGLYPHMETRICSFLOAT* = ptr GLYPHMETRICSFLOAT LAYERPLANEDESCRIPTOR* {.final, pure.} = object nSize*: int16 @@ -12220,7 +11761,6 @@ type crTransparent*: COLORREF LPLAYERPLANEDESCRIPTOR* = ptr LAYERPLANEDESCRIPTOR - TLAYERPLANEDESCRIPTOR* = LAYERPLANEDESCRIPTOR PLAYERPLANEDESCRIPTOR* = ptr LAYERPLANEDESCRIPTOR PIXELFORMATDESCRIPTOR* {.final, pure.} = object nSize*: int16 @@ -12251,7 +11791,6 @@ type dwDamageMask*: DWORD LPPIXELFORMATDESCRIPTOR* = ptr PIXELFORMATDESCRIPTOR - TPIXELFORMATDESCRIPTOR* = PIXELFORMATDESCRIPTOR PPIXELFORMATDESCRIPTOR* = ptr PIXELFORMATDESCRIPTOR USER_INFO_2* {.final, pure.} = object usri2_name*: LPWSTR @@ -12281,13 +11820,11 @@ type PUSER_INFO_2* = ptr USER_INFO_2 LPUSER_INFO_2* = ptr USER_INFO_2 - TUSERINFO2* = USER_INFO_2 USER_INFO_0* {.final, pure.} = object usri0_name*: LPWSTR PUSER_INFO_0* = ptr USER_INFO_0 LPUSER_INFO_0* = ptr USER_INFO_0 - TUSERINFO0* = USER_INFO_0 USER_INFO_3* {.final, pure.} = object usri3_name*: LPWSTR usri3_password*: LPWSTR @@ -12321,7 +11858,6 @@ type PUSER_INFO_3* = ptr USER_INFO_3 LPUSER_INFO_3* = ptr USER_INFO_3 - TUSERINFO3* = USER_INFO_3 GROUP_INFO_2* {.final, pure.} = object grpi2_name*: LPWSTR grpi2_comment*: LPWSTR @@ -12329,13 +11865,11 @@ type grpi2_attributes*: DWORD PGROUP_INFO_2* = ptr GROUP_INFO_2 - TGROUPINFO2* = GROUP_INFO_2 LOCALGROUP_INFO_0* {.final, pure.} = object lgrpi0_name*: LPWSTR PLOCALGROUP_INFO_0* = ptr LOCALGROUP_INFO_0 LPLOCALGROUP_INFO_0* = ptr LOCALGROUP_INFO_0 - TLOCALGROUPINFO0* = LOCALGROUP_INFO_0 IMAGE_DOS_HEADER* {.final, pure.} = object e_magic*: int16 e_cblp*: int16 @@ -12358,7 +11892,6 @@ type e_lfanew*: LONG PIMAGE_DOS_HEADER* = ptr IMAGE_DOS_HEADER - TIMAGEDOSHEADER* = IMAGE_DOS_HEADER NOTIFYICONDATAA* {.final, pure.} = object cbSize*: DWORD Wnd*: HWND @@ -12378,15 +11911,22 @@ type hIcon*: HICON szTip*: array[0..63, int16] - TNotifyIconDataA* = NOTIFYICONDATAA - TNotifyIconDataW* = NOTIFYICONDATAW - TNotifyIconData* = TNotifyIconDataA - PNotifyIconDataA* = ptr TNotifyIconDataA - PNotifyIconDataW* = ptr TNotifyIconDataW + PNotifyIconDataA* = ptr NotifyIconDataA + PNotifyIconDataW* = ptr NotifyIconDataW PNotifyIconData* = PNotifyIconDataA - TWOHandleArray* = array[0..MAXIMUM_WAIT_OBJECTS - 1, HANDLE] - PWOHandleArray* = ptr TWOHandleArray + WOHandleArray* = array[0..MAXIMUM_WAIT_OBJECTS - 1, HANDLE] + PWOHandleArray* = ptr WOHandleArray MMRESULT* = int32 +{.deprecated: [TPRINTERNOTIFYINFO: PRINTER_NOTIFY_INFO, TPRINTERNOTIFYINFODATA: PRINTER_NOTIFY_INFO_DATA, TPRINTERINFO5: PRINTER_INFO_5, TPRINTERINFO4: PRINTER_INFO_4, TPRINTERINFO3: PRINTER_INFO_3, TPRINTERINFO2: PRINTER_INFO_2, TPRINTERINFO1: PRINTER_INFO_1, TPRINTERDEFAULTS: PRINTER_DEFAULTS, TPD: TPRINTDLG, TPREVENTMEDIAREMOVAL: PREVENT_MEDIA_REMOVAL, TPORTINFO2: PORT_INFO_2, TPORTINFO1: PORT_INFO_1, TPOLYTEXT: POLYTEXT, TPERFOBJECTTYPE: PERF_OBJECT_TYPE, TPERFINSTANCEDEFINITION: PERF_INSTANCE_DEFINITION, TPERFDATABLOCK: PERF_DATA_BLOCK, TPERFCOUNTERDEFINITION: PERF_COUNTER_DEFINITION, TPERFCOUNTERBLOCK: PERF_COUNTER_BLOCK, Tparaformat: PARAFORMAT, TPAINTSTRUCT: PAINTSTRUCT, TPSD: TPAGESETUPDLG, TOVERLAPPED: OVERLAPPED, TOUTLINETEXTMETRIC: OUTLINETEXTMETRIC, TTEXTMETRICW: TEXTMETRICW, TTEXTMETRIC: TEXTMETRIC, TOSVERSIONINFOW: OSVERSIONINFOW, TOSVERSIONINFO: OSVERSIONINFO, TOFNOTIFY: OFNOTIFY, TOPENFILENAME_NT4: OPENFILENAME_NT4, TOFSTRUCT: OFSTRUCT, Tnumberfmt: NUMBERFMT, TNSSERVICEINFO: NS_SERVICE_INFO, TSERVICEINFO: SERVICE_INFO, TCLSID: CLSID, TSERVICEADDRESSES: SERVICE_ADDRESSES, TSERVICEADDRESS: SERVICE_ADDRESS, TNONCLIENTMETRICS: NONCLIENTMETRICS, TNMUPDOWN: NM_UPDOWNW, TNMTREEVIEW: NM_TREEVIEW, TTVITEM: TV_ITEM, TNMLISTVIEW: NM_LISTVIEW, TNEWTEXTMETRICEX: NEWTEXTMETRICEX, TNEWTEXTMETRIC: NEWTEXTMETRIC].} + +{.deprecated: [TNEWCPLINFO: NEWCPLINFO, TNETRESOURCE: NETRESOURCE, TNETRESOURCEA: NETRESOURCE, TNDDESHAREINFO: NDDESHAREINFO, TNCB: NCB, TNAMEBUFFER: NAME_BUFFER, TMULTIKEYHELP: MULTIKEYHELP, Tmsgfilter: MSGFILTER, TMSGBOXPARAMS: MSGBOXPARAMS, TMSGBOXPARAMSA: MSGBOXPARAMS, TMOUSEKEYS: MOUSEKEYS, TMOUSEHOOKSTRUCT: MOUSEHOOKSTRUCT, TMONMSGSTRUCT: MONMSGSTRUCT, TMONLINKSTRUCT: MONLINKSTRUCT, TMONITORINFO2: MONITOR_INFO_2, TMONITORINFO1: MONITOR_INFO_1, TMONHSZSTRUCT: MONHSZSTRUCT, TMONERRSTRUCT: MONERRSTRUCT, TMONCONVSTRUCT: MONCONVSTRUCT, TMONCBSTRUCT: MONCBSTRUCT, TMODEMSETTINGS: MODEMSETTINGS, TMODEMDEVCAPS: MODEMDEVCAPS, TMINMAXINFO: MINMAXINFO, TMINIMIZEDMETRICS: MINIMIZEDMETRICS, TMETARECORD: METARECORD, TMETAHEADER: METAHEADER, TMETAFILEPICT: METAFILEPICT, TMENUTEMPLATE: MENUTEMPLATE, TMENUITEMTEMPLATEHEADER: MENUITEMTEMPLATEHEADER, TMENUITEMTEMPLATE: MENUITEMTEMPLATE, TMENUITEMINFOA: MENUITEMINFO, TMENUITEMINFO: MENUITEMINFO, TMENUINFO: MENUINFO, TMENUEXTEMPLATEITEM: MENUEX_TEMPLATE_ITEM, TMENUXTEMPLATEHEADER: MENUEX_TEMPLATE_HEADER, TMEMORYSTATUS: MEMORYSTATUS, TMEMORYBASICINFORMATION: MEMORY_BASIC_INFORMATION, TMEASUREITEMSTRUCT: MEASUREITEMSTRUCT, TMDICREATESTRUCT: MDICREATESTRUCT, TMAT2: MAT2, TLVKEYDOWN: LV_KEYDOWN, TLVHITTESTINFO: LV_HITTESTINFO, TLVFINDINFO: LV_FINDINFO, TLVDISPINFO: LV_DISPINFO, TLVITEM: LV_ITEM, TLVCOLUMN: LV_COLUMN, TLUIDANDATTRIBUTESARRAY: LUID_AND_ATTRIBUTES_ARRAY, TLUIDANDATTRIBUTES: LUID_AND_ATTRIBUTES, TLUID: LUID, TFXPT16DOT16: FXPT16DOT16, TLOCALGROUPMEMBERSINFO3: LOCALGROUP_MEMBERS_INFO_3, TLOCALGROUPMEMBERSINFO0: LOCALGROUP_MEMBERS_INFO_0, TLOCALESIGNATURE: LOCALESIGNATURE, TGUID: GUID, TOPENFILENAME: OPENFILENAME].} + +{.deprecated: [TTOGGLEKEYS: TOGGLEKEYS, TTIMEZONEINFORMATION: TIME_ZONE_INFORMATION, Ttextrange: TEXTRANGE, TTCKEYDOWN: TC_KEYDOWN, TTCITEMHEADER: TC_ITEMHEADER, TTCITEM: TC_ITEM, TTCHITTESTINFO: TC_HITTESTINFO, TTBSAVEPARAMS: TBSAVEPARAMS, TTBNOTIFY: TBNOTIFY, TTBBUTTON: TBBUTTON, TTAPEWRITEMARKS: TAPE_WRITE_MARKS, TTAPESETPOSITION: TAPE_SET_POSITION, TTAPESETMEDIAPARAMETERS: TAPE_SET_MEDIA_PARAMETERS, TTAPESETDRIVEPARAMETERS: TAPE_SET_DRIVE_PARAMETERS, TTAPEPREPARE: TAPE_PREPARE, TTAPEGETPOSITION: TAPE_GET_POSITION, TTAPEGETMEDIAPARAMETERS: TAPE_GET_MEDIA_PARAMETERS, TTAPEGETDRIVEPARAMETERS: TAPE_GET_DRIVE_PARAMETERS, TTAPEERASE: TAPE_ERASE, TSYSTEMPOWERSTATUS: SYSTEM_POWER_STATUS, TSYSTEMINFO: SYSTEM_INFO, TSYSTEMAUDITACE: SYSTEM_AUDIT_ACE, TSTYLESTRUCT: STYLESTRUCT, TSTYLEBUF: STYLEBUF, TSTRRET: STRRET, TSTICKYKEYS: STICKYKEYS, TSTARTUPINFO: STARTUPINFO, TSOUNDSENTRY: SOUNDSENTRY, TSINGLELISTENTRY: SINGLE_LIST_ENTRY, TSIDANDATTRIBUTESARRAY: SID_AND_ATTRIBUTES_ARRAY, TSIDANDATTRIBUTES: SID_AND_ATTRIBUTES, TSHNAMEMAPPING: SHNAMEMAPPING, TSHGDN: SHGNO, TSHFILEOPSTRUCT: SHFILEOPSTRUCT, TFILEOPFLAGS: FILEOP_FLAGS, TSHFILEINFO: SHFILEINFO, TSHCONTF: SHCONTF, TSETPARTITIONINFORMATION: SET_PARTITION_INFORMATION, TSESSIONHEADER: SESSION_HEADER].} + +{.deprecated: [TSESSIONBUFFER: SESSION_BUFFER, TSERVICETYPEINFOABS: SERVICE_TYPE_INFO_ABS, TSERVICETYPEVALUEABS: SERVICE_TYPE_VALUE_ABS, TSERVICETABLEENTRY: SERVICE_TABLE_ENTRY, TSERIALKEYS: SERIALKEYS, Tselchange: SELCHANGE, TSECURITYINFORMATION: SECURITY_INFORMATION, TSECURITYATTRIBUTES: SECURITY_ATTRIBUTES, TSCROLLINFO: SCROLLINFO, TRGNDATA: RGNDATA, TRGNDATAHEADER: RGNDATAHEADER, Treqresize: REQRESIZE, Trepastespecial: REPASTESPECIAL, TREMOTENAMEINFO: REMOTE_NAME_INFO, TREASSIGNBLOCKS: REASSIGN_BLOCKS, TRASTERIZERSTATUS: RASTERIZER_STATUS, TRASPPPNBF: RASPPPNBF, TRASPPPIPX: RASPPPIPX, TRASPPPIP: RASPPPIP, TRASENTRYNAME: RASENTRYNAME, TRASDIALPARAMS: RASDIALPARAMS, TRASDIALEXTENSIONS: RASDIALEXTENSIONS, TRASCONNSTATUS: RASCONNSTATUS, TRASCONN: RASCONN, TRASAMB: RASAMB, Tpunctuation: PUNCTUATION, TPSHNOTIFY: PSHNOTIFY, TPROVIDORINFO1: PROVIDOR_INFO_1, TPROTOCOLINFO: PROTOCOL_INFO, TFNADDPROPSHEETPAGES: LPFNADDPROPSHEETPAGES, TFNADDPROPSHEETPAGE: LPFNADDPROPSHEETPAGE, TPROPSHEETHEADER: PROPSHEETHEADER, TPROPSHEETPAGE: PROPSHEETPAGE, TFNPSPCALLBACK: LPFNPSPCALLBACK, TPROCESSINFORMATION: PROCESS_INFORMATION, TPROCESSHEAPENTRY: PROCESS_HEAPENTRY, TPRIVILEGESET: PRIVILEGE_SET, TPRINTPROCESSORINFO1: PRINTPROCESSOR_INFO_1, TPRINTERNOTIFYOPTIONS: PRINTER_NOTIFY_OPTIONS, TPRINTERNOTIFYOPTIONSTYPE: PRINTER_NOTIFY_OPTIONS_TYPE].} + +{.deprecated: [TNotifyIconDataA: NOTIFYICONDATAA, TNotifyIconDataW: NOTIFYICONDATAW, TNotifyIconData: NotifyIconDataA, TIMAGEDOSHEADER: IMAGE_DOS_HEADER, TLOCALGROUPINFO0: LOCALGROUP_INFO_0, TGROUPINFO2: GROUP_INFO_2, TUSERINFO3: USER_INFO_3, TUSERINFO0: USER_INFO_0, TUSERINFO2: USER_INFO_2, TPIXELFORMATDESCRIPTOR: PIXELFORMATDESCRIPTOR, TLAYERPLANEDESCRIPTOR: LAYERPLANEDESCRIPTOR, TGLYPHMETRICSFLOAT: GLYPHMETRICSFLOAT, TPOINTFLOAT: POINTFLOAT, TNETCONNECTINFOSTRUCT: NETCONNECTINFOSTRUCT, TNETINFOSTRUCT: NETINFOSTRUCT, TDISCDLGSTRUCT: DISCDLGSTRUCT, TDISCDLGSTRUCTA: DISCDLGSTRUCT, TCONNECTDLGSTRUCT: CONNECTDLGSTRUCT, TWNDCLASSEXW: WNDCLASSEXW, TWNDCLASSEX: WNDCLASSEX, TWNDCLASSEXA: WNDCLASSEX, TWNDCLASSW: WNDCLASSW, TWNDCLASS: WNDCLASS, TWNDCLASSA: WNDCLASS, TWINDOWPLACEMENT: WINDOWPLACEMENT, TWIN32STREAMID: WIN32_STREAM_ID, TWIN32FINDDATAW: WIN32_FIND_DATAW, TWIN32FINDDATAA: WIN32_FIND_DATA, TWIN32FINDDATA: WIN32_FIND_DATA, TVSFIXEDFILEINFO: VS_FIXEDFILEINFO, TVERIFYINFORMATION: VERIFY_INFORMATION, Tvalue_ent: VALENT, TVALENT: VALENT, TUSEROBJECTFLAGS: USEROBJECTFLAGS, TUNIVERSALNAMEINFO: UNIVERSAL_NAME_INFO, TUDACCEL: UDACCEL, TTVSORTCB: TV_SORTCB, TTVKEYDOWN: TV_KEYDOWN, TTVINSERTSTRUCT: TV_INSERTSTRUCT, TTVHITTESTINFO: TV_HITTESTINFO, TTVDISPINFO: TV_DISPINFO, TTTPOLYGONHEADER: TTPOLYGONHEADER, TTTPOLYCURVE: TTPOLYCURVE, TTTHITTESTINFO: TTHITTESTINFO, TTRANSMITFILEBUFFERS: TRANSMIT_FILE_BUFFERS, TTPMPARAMS: TPMPARAMS, TTOOLTIPTEXT: TOOLTIPTEXT, TTOOLINFO: TOOLINFO, TTOKENCONTROL: TOKEN_CONTROL, TWOHandleArray: WOHandleArray].} + type PWaveFormatEx* = ptr TWaveFormatEx @@ -13643,13 +13183,13 @@ type TWMNCHitTest* {.final, pure.} = object Msg*: WINUINT Unused*: int32 - Pos*: TSmallPoint + Pos*: SmallPoint Result*: LRESULT TWMMouse* {.final, pure.} = object Msg*: WINUINT Keys*: int32 - Pos*: TSmallPoint + Pos*: SmallPoint Result*: LRESULT TWMLButtonDblClk* = TWMMouse @@ -13662,7 +13202,7 @@ type Msg*: WINUINT Keys*: int16 WheelDelta*: int16 - Pos*: TSmallPoint + Pos*: SmallPoint Result*: LRESULT TWMNCHitMessage* {.final, pure.} = object @@ -13718,7 +13258,7 @@ type TWMContextMenu* {.final, pure.} = object Msg*: WINUINT hWnd*: HWND - Pos*: TSmallPoint + Pos*: SmallPoint Result*: LRESULT TWMNCCalcSize* {.final, pure.} = object @@ -13776,7 +13316,7 @@ type TWMMove* {.final, pure.} = object Msg*: WINUINT Unused*: int - Pos*: TSmallPoint + Pos*: SmallPoint Result*: LRESULT TWMWindowPosMsg* {.final, pure.} = object @@ -13915,7 +13455,7 @@ type TWMSizeClipboard* {.final, pure.} = object Msg*: WINUINT Viewer*: HWND - RC*: THandle + RC*: Handle Result*: LRESULT TWMSpoolerStatus* {.final, pure.} = object @@ -13950,7 +13490,7 @@ type TWMTimer* {.final, pure.} = object Msg*: WINUINT TimerID*: LPARAM - TimerProc*: TFarProc + TimerProc*: FarProc Result*: LRESULT TWMUndo* = TWMNoParams @@ -13970,7 +13510,7 @@ type TWMDropFiles* {.final, pure.} = object Msg*: WINUINT - Drop*: THANDLE + Drop*: HANDLE Unused*: LPARAM Result*: LRESULT @@ -18673,7 +18213,7 @@ proc ExitProcess*(uExitCode: WINUINT){.stdcall, dynlib: "kernel32", importc: "ExitProcess".} proc TerminateProcess*(hProcess: HANDLE, uExitCode: WINUINT): WINBOOL{.stdcall, dynlib: "kernel32", importc: "TerminateProcess".} -proc SetProcessAffinityMask*(hProcess: THandle, dwProcessAffinityMask: DWORD): WINBOOL{. +proc SetProcessAffinityMask*(hProcess: Handle, dwProcessAffinityMask: DWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "SetProcessAffinityMask".} proc GetExitCodeProcess*(hProcess: HANDLE, lpExitCode: LPDWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "GetExitCodeProcess".} @@ -20215,7 +19755,7 @@ proc GetWinMetaFileBits*(para1: HENHMETAFILE, para2: WINUINT, para3: LPBYTE, proc PlayEnhMetaFile*(para1: HDC, para2: HENHMETAFILE, para3: RECT): WINBOOL{. stdcall, dynlib: "gdi32", importc: "PlayEnhMetaFile".} proc PlayEnhMetaFileRecord*(para1: HDC, para2: LPHANDLETABLE, - para3: var TENHMETARECORD, para4: WINUINT): WINBOOL{. + para3: var ENHMETARECORD, para4: WINUINT): WINBOOL{. stdcall, dynlib: "gdi32", importc: "PlayEnhMetaFileRecord".} proc SetEnhMetaFileBits*(para1: WINUINT, para2: var int8): HENHMETAFILE{.stdcall, dynlib: "gdi32", importc: "SetEnhMetaFileBits".} @@ -20255,7 +19795,7 @@ proc StartPage*(para1: HDC): int32{.stdcall, dynlib: "gdi32", importc: "StartPage".} proc EndPage*(para1: HDC): int32{.stdcall, dynlib: "gdi32", importc: "EndPage".} proc AbortDoc*(para1: HDC): int32{.stdcall, dynlib: "gdi32", importc: "AbortDoc".} -proc SetAbortProc*(para1: HDC, para2: TABORTPROC): int32{.stdcall, +proc SetAbortProc*(para1: HDC, para2: ABORTPROC): int32{.stdcall, dynlib: "gdi32", importc: "SetAbortProc".} proc ArcTo*(para1: HDC, para2: int32, para3: int32, para4: int32, para5: int32, para6: int32, para7: int32, para8: int32, para9: int32): WINBOOL{. @@ -20732,7 +20272,7 @@ proc wglDescribeLayerPlane*(para1: HDC, para2: int32, para3: int32, para4: WINUI proc wglGetLayerPaletteEntries*(para1: HDC, para2: int32, para3: int32, para4: int32, para5: var COLORREF): int32{. stdcall, dynlib: "opengl32", importc: "wglGetLayerPaletteEntries".} -proc wglGetProcAddress*(para1: LPCSTR): TProc{.stdcall, dynlib: "opengl32", +proc wglGetProcAddress*(para1: LPCSTR): Proc{.stdcall, dynlib: "opengl32", importc: "wglGetProcAddress".} proc wglRealizeLayerPalette*(para1: HDC, para2: int32, para3: WINBOOL): WINBOOL{. stdcall, dynlib: "opengl32", importc: "wglRealizeLayerPalette".} @@ -20923,7 +20463,7 @@ proc SetLayeredWindowAttributes*(hwnd: HWND, crKey: COLORREF, bAlpha: int8, dynlib: "user32", importc: "SetLayeredWindowAttributes".} type PIID* = PGUID - TIID* = TGUID + TIID* = GUID TFNDlgProc* = FARPROC TFNThreadStartRoutine* = FARPROC TFNTimerAPCRoutine* = FARPROC @@ -20956,7 +20496,7 @@ type TMaxLogPalette* {.final, pure.} = object palVersion*: int16 palNumEntries*: int16 - palPalEntry*: array[int8, TPaletteEntry] + palPalEntry*: array[int8, PaletteEntry] PMaxLogPalette* = ptr TMaxLogPalette POSVersionInfoA* = POSVERSIONINFO @@ -21082,60 +20622,60 @@ proc SetCriticalSectionSpinCount*(CriticalSection: var TRTLCriticalSection, proc TryEnterCriticalSection*(CriticalSection: var TRTLCriticalSection): WINBOOL{. stdcall, dynlib: "kernel32", importc: "TryEnterCriticalSection".} proc ControlService*(hService: SC_HANDLE, dwControl: DWORD, - ServiceStatus: var TSERVICESTATUS): WINBOOL{.stdcall, + ServiceStatus: var SERVICESTATUS): WINBOOL{.stdcall, dynlib: "advapi32", importc: "ControlService".} proc QueryServiceStatus*(hService: SC_HANDLE, - lpServiceStatus: var TSERVICESTATUS): WINBOOL{.stdcall, + lpServiceStatus: var SERVICESTATUS): WINBOOL{.stdcall, dynlib: "advapi32", importc: "QueryServiceStatus".} proc SetServiceStatus*(hServiceStatus: SERVICE_STATUS_HANDLE, - ServiceStatus: TSERVICESTATUS): WINBOOL{.stdcall, + ServiceStatus: SERVICESTATUS): WINBOOL{.stdcall, dynlib: "advapi32", importc: "SetServiceStatus".} -proc AdjustTokenPrivileges*(TokenHandle: THandle, DisableAllPrivileges: WINBOOL, +proc AdjustTokenPrivileges*(TokenHandle: Handle, DisableAllPrivileges: WINBOOL, NewState: TTokenPrivileges, BufferLength: DWORD, PreviousState: var TTokenPrivileges, ReturnLength: var DWORD): WINBOOL{.stdcall, dynlib: "advapi32", importc: "AdjustTokenPrivileges".} -proc AdjustWindowRect*(lpRect: var TRect, dwStyle: DWORD, bMenu: WINBOOL): WINBOOL{. +proc AdjustWindowRect*(lpRect: var Rect, dwStyle: DWORD, bMenu: WINBOOL): WINBOOL{. stdcall, dynlib: "user32", importc: "AdjustWindowRect".} -proc AdjustWindowRectEx*(lpRect: var TRect, dwStyle: DWORD, bMenu: WINBOOL, +proc AdjustWindowRectEx*(lpRect: var Rect, dwStyle: DWORD, bMenu: WINBOOL, dwExStyle: DWORD): WINBOOL{.stdcall, dynlib: "user32", importc: "AdjustWindowRectEx".} -proc AllocateAndInitializeSid*(pIdentifierAuthority: TSIDIdentifierAuthority, +proc AllocateAndInitializeSid*(pIdentifierAuthority: SIDIdentifierAuthority, nSubAuthorityCount: int8, nSubAuthority0, nSubAuthority1: DWORD, nSubAuthority2, nSubAuthority3, nSubAuthority4: DWORD, nSubAuthority5, nSubAuthority6, nSubAuthority7: DWORD, pSid: var pointer): WINBOOL{.stdcall, dynlib: "advapi32", importc: "AllocateAndInitializeSid".} -proc AllocateLocallyUniqueId*(Luid: var TLargeInteger): WINBOOL{.stdcall, +proc AllocateLocallyUniqueId*(Luid: var LargeInteger): WINBOOL{.stdcall, dynlib: "advapi32", importc: "AllocateLocallyUniqueId".} -proc BackupRead*(hFile: THandle, lpBuffer: PByte, nNumberOfBytesToRead: DWORD, +proc BackupRead*(hFile: Handle, lpBuffer: PByte, nNumberOfBytesToRead: DWORD, lpNumberOfBytesRead: var DWORD, bAbort: WINBOOL, bProcessSecurity: WINBOOL, lpContext: var pointer): WINBOOL{. stdcall, dynlib: "kernel32", importc: "BackupRead".} -proc BackupSeek*(hFile: THandle, dwLowBytesToSeek, dwHighBytesToSeek: DWORD, +proc BackupSeek*(hFile: Handle, dwLowBytesToSeek, dwHighBytesToSeek: DWORD, lpdwLowByteSeeked, lpdwHighByteSeeked: var DWORD, lpContext: pointer): WINBOOL{.stdcall, dynlib: "kernel32", importc: "BackupSeek".} -proc BackupWrite*(hFile: THandle, lpBuffer: PByte, nNumberOfBytesToWrite: DWORD, +proc BackupWrite*(hFile: Handle, lpBuffer: PByte, nNumberOfBytesToWrite: DWORD, lpNumberOfBytesWritten: var DWORD, bAbort, bProcessSecurity: WINBOOL, lpContext: var pointer): WINBOOL{. stdcall, dynlib: "kernel32", importc: "BackupWrite".} -proc BeginPaint*(wnd: HWND, lpPaint: var TPaintStruct): HDC{.stdcall, +proc BeginPaint*(wnd: HWND, lpPaint: var PaintStruct): HDC{.stdcall, dynlib: "user32", importc: "BeginPaint".} -proc BuildCommDCB*(lpDef: cstring, lpDCB: var TDCB): WINBOOL{.stdcall, +proc BuildCommDCB*(lpDef: cstring, lpDCB: var DCB): WINBOOL{.stdcall, dynlib: "kernel32", importc: "BuildCommDCBA".} -proc BuildCommDCBA*(lpDef: LPCSTR, lpDCB: var TDCB): WINBOOL{.stdcall, +proc BuildCommDCBA*(lpDef: LPCSTR, lpDCB: var DCB): WINBOOL{.stdcall, dynlib: "kernel32", importc: "BuildCommDCBA".} -proc BuildCommDCBAndTimeouts*(lpDef: cstring, lpDCB: var TDCB, - lpCommTimeouts: var TCommTimeouts): WINBOOL{. +proc BuildCommDCBAndTimeouts*(lpDef: cstring, lpDCB: var DCB, + lpCommTimeouts: var CommTimeouts): WINBOOL{. stdcall, dynlib: "kernel32", importc: "BuildCommDCBAndTimeoutsA".} -proc BuildCommDCBAndTimeoutsA*(lpDef: LPCSTR, lpDCB: var TDCB, - lpCommTimeouts: var TCommTimeouts): WINBOOL{. +proc BuildCommDCBAndTimeoutsA*(lpDef: LPCSTR, lpDCB: var DCB, + lpCommTimeouts: var CommTimeouts): WINBOOL{. stdcall, dynlib: "kernel32", importc: "BuildCommDCBAndTimeoutsA".} -proc BuildCommDCBAndTimeoutsW*(lpDef: LPWSTR, lpDCB: var TDCB, - lpCommTimeouts: var TCommTimeouts): WINBOOL{. +proc BuildCommDCBAndTimeoutsW*(lpDef: LPWSTR, lpDCB: var DCB, + lpCommTimeouts: var CommTimeouts): WINBOOL{. stdcall, dynlib: "kernel32", importc: "BuildCommDCBAndTimeoutsW".} -proc BuildCommDCBW*(lpDef: LPWSTR, lpDCB: var TDCB): WINBOOL{.stdcall, +proc BuildCommDCBW*(lpDef: LPWSTR, lpDCB: var DCB): WINBOOL{.stdcall, dynlib: "kernel32", importc: "BuildCommDCBW".} proc CallMsgFilter*(lpMsg: var TMsg, nCode: int): WINBOOL{.stdcall, dynlib: "user32", importc: "CallMsgFilterA".} @@ -21158,45 +20698,45 @@ proc CallNamedPipeW*(lpNamedPipeName: LPWSTR, lpInBuffer: pointer, nOutBufferSize: DWORD, lpBytesRead: var DWORD, nTimeOut: DWORD): WINBOOL{.stdcall, dynlib: "kernel32", importc: "CallNamedPipeW".} -proc CoRegisterClassObject*(para1: TCLSID, para2: pointer, para3: DWORD, +proc CoRegisterClassObject*(para1: CLSID, para2: pointer, para3: DWORD, para4: DWORD, out_para5: DWORD): HRESULT{.stdcall, dynlib: "ole32.dll", importc: "CoRegisterClassObject".} -proc ChangeDisplaySettings*(lpDevMode: var TDeviceMode, dwFlags: DWORD): int32{. +proc ChangeDisplaySettings*(lpDevMode: var DevMode, dwFlags: DWORD): int32{. stdcall, dynlib: "user32", importc: "ChangeDisplaySettingsA".} -proc ChangeDisplaySettingsA*(lpDevMode: var TDeviceModeA, dwFlags: DWORD): int32{. +proc ChangeDisplaySettingsA*(lpDevMode: var DevMode, dwFlags: DWORD): int32{. stdcall, dynlib: "user32", importc: "ChangeDisplaySettingsA".} proc ChangeDisplaySettingsEx*(lpszDeviceName: cstring, - lpDevMode: var TDeviceMode, wnd: HWND, + lpDevMode: var DevMode, wnd: HWND, dwFlags: DWORD, lParam: pointer): int32{.stdcall, dynlib: "user32", importc: "ChangeDisplaySettingsExA".} proc ChangeDisplaySettingsExA*(lpszDeviceName: LPCSTR, - lpDevMode: var TDeviceModeA, wnd: HWND, + lpDevMode: var DevMode, wnd: HWND, dwFlags: DWORD, lParam: pointer): int32{.stdcall, dynlib: "user32", importc: "ChangeDisplaySettingsExA".} proc ChangeDisplaySettingsExW*(lpszDeviceName: LPWSTR, - lpDevMode: var TDeviceModeW, wnd: HWND, + lpDevMode: var DevModeW, wnd: HWND, dwFlags: DWORD, lParam: pointer): int32{.stdcall, dynlib: "user32", importc: "ChangeDisplaySettingsExW".} -proc ChangeDisplaySettingsW*(lpDevMode: var TDeviceModeW, dwFlags: DWORD): int32{. +proc ChangeDisplaySettingsW*(lpDevMode: var DevModeW, dwFlags: DWORD): int32{. stdcall, dynlib: "user32", importc: "ChangeDisplaySettingsW".} #function CheckColorsInGamut(DC: HDC; var RGBQuads, Results; Count: DWORD): WINBOOL; stdcall; external 'gdi32' name 'CheckColorsInGamut'; proc ChoosePixelFormat*(para1: HDC, para2: var PIXELFORMATDESCRIPTOR): int32{. stdcall, dynlib: "gdi32", importc: "ChoosePixelFormat".} -proc ClearCommError*(hFile: THandle, lpErrors: var DWORD, lpStat: PComStat): WINBOOL{. +proc ClearCommError*(hFile: Handle, lpErrors: var DWORD, lpStat: PComStat): WINBOOL{. stdcall, dynlib: "kernel32", importc: "ClearCommError".} -proc ClientToScreen*(wnd: HWND, lpPoint: var TPoint): WINBOOL{.stdcall, +proc ClientToScreen*(wnd: HWND, lpPoint: var Point): WINBOOL{.stdcall, dynlib: "user32", importc: "ClientToScreen".} proc ClipCursor*(lpRect: var RECT): WINBOOL{.stdcall, dynlib: "user32", importc: "ClipCursor".} - #function CombineTransform(var p1: TXForm; const p2, p3: TXForm): WINBOOL; stdcall; external 'gdi32' name 'CombineTransform'; -proc CommConfigDialog*(lpszName: cstring, wnd: HWND, lpCC: var TCommConfig): WINBOOL{. + #function CombineTransform(var p1: XForm; const p2, p3: XForm): WINBOOL; stdcall; external 'gdi32' name 'CombineTransform'; +proc CommConfigDialog*(lpszName: cstring, wnd: HWND, lpCC: var CommConfig): WINBOOL{. stdcall, dynlib: "kernel32", importc: "CommConfigDialogA".} -proc CommConfigDialogA*(lpszName: LPCSTR, wnd: HWND, lpCC: var TCommConfig): WINBOOL{. +proc CommConfigDialogA*(lpszName: LPCSTR, wnd: HWND, lpCC: var CommConfig): WINBOOL{. stdcall, dynlib: "kernel32", importc: "CommConfigDialogA".} -proc CommConfigDialogW*(lpszName: LPWSTR, wnd: HWND, lpCC: var TCommConfig): WINBOOL{. +proc CommConfigDialogW*(lpszName: LPWSTR, wnd: HWND, lpCC: var CommConfig): WINBOOL{. stdcall, dynlib: "kernel32", importc: "CommConfigDialogW".} - #function CompareFileTime(const lpFileTime1, lpFileTime2: TFileTime): Longint; stdcall; external 'kernel32' name 'CompareFileTime'; - #function ConvertToAutoInheritPrivateObjectSecurity(ParentDescriptor, CurrentSecurityDescriptor: PSecurityDescriptor; var NewDescriptor: PSecurityDescriptor; ObjectType: PGUID; IsDirectoryObject: WINBOOL; const GenericMapping: TGenericMapping): WINBOOL; + #function CompareFileTime(const lpFileTime1, lpFileTime2: FileTime): Longint; stdcall; external 'kernel32' name 'CompareFileTime'; + #function ConvertToAutoInheritPrivateObjectSecurity(ParentDescriptor, CurrentSecurityDescriptor: PSecurityDescriptor; var NewDescriptor: PSecurityDescriptor; ObjectType: PGUID; IsDirectoryObject: WINBOOL; const GenericMapping: GenericMapping): WINBOOL; # stdcall; external 'advapi32' name 'ConvertToAutoInheritPrivateObjectSecurity'; proc CopyAcceleratorTable*(hAccelSrc: HACCEL, lpAccelDst: pointer, cAccelEntries: int): int{.stdcall, dynlib: "user32", @@ -21207,7 +20747,7 @@ proc CopyAcceleratorTableA*(hAccelSrc: HACCEL, lpAccelDst: pointer, proc CopyAcceleratorTableW*(hAccelSrc: HACCEL, lpAccelDst: pointer, cAccelEntries: int): int{.stdcall, dynlib: "user32", importc: "CopyAcceleratorTableW".} -proc CopyRect*(lprcDst: var TRect, lprcSrc: TRect): WINBOOL{.stdcall, +proc CopyRect*(lprcDst: var Rect, lprcSrc: Rect): WINBOOL{.stdcall, dynlib: "user32", importc: "CopyRect".} proc CreateAcceleratorTable*(Accel: pointer, Count: int): HACCEL{.stdcall, dynlib: "user32", importc: "CreateAcceleratorTableA".} @@ -21215,105 +20755,105 @@ proc CreateAcceleratorTableA*(Accel: pointer, Count: int): HACCEL{.stdcall, dynlib: "user32", importc: "CreateAcceleratorTableA".} proc CreateAcceleratorTableW*(Accel: pointer, Count: int): HACCEL{.stdcall, dynlib: "user32", importc: "CreateAcceleratorTableW".} - #function CreateBitmapIndirect(const p1: TBitmap): HBITMAP; stdcall; external 'gdi32' name 'CreateBitmapIndirect'; - #function CreateBrushIndirect(const p1: TLogBrush): HBRUSH; stdcall; external 'gdi32' name 'CreateBrushIndirect'; -proc CreateColorSpace*(ColorSpace: var TLogColorSpace): HCOLORSPACE{.stdcall, + #function CreateBitmapIndirect(const p1: Bitmap): HBITMAP; stdcall; external 'gdi32' name 'CreateBitmapIndirect'; + #function CreateBrushIndirect(const p1: LogBrush): HBRUSH; stdcall; external 'gdi32' name 'CreateBrushIndirect'; +proc CreateColorSpace*(ColorSpace: var LogColorSpace): HCOLORSPACE{.stdcall, dynlib: "gdi32", importc: "CreateColorSpaceA".} -proc CreateColorSpaceA*(ColorSpace: var TLogColorSpaceA): HCOLORSPACE{.stdcall, +proc CreateColorSpaceA*(ColorSpace: var LogColorSpace): HCOLORSPACE{.stdcall, dynlib: "gdi32", importc: "CreateColorSpaceA".} - #function CreateColorSpaceW(var ColorSpace: TLogColorSpaceW): HCOLORSPACE; stdcall; external 'gdi32' name 'CreateColorSpaceW'; -proc CreateDialogIndirectParam*(hInstance: HINST, lpTemplate: TDlgTemplate, + #function CreateColorSpaceW(var ColorSpace: LogColorSpaceW): HCOLORSPACE; stdcall; external 'gdi32' name 'CreateColorSpaceW'; +proc CreateDialogIndirectParam*(hInstance: HINST, lpTemplate: DlgTemplate, hWndParent: HWND, lpDialogFunc: TFNDlgProc, dwInitParam: LPARAM): HWND{.stdcall, dynlib: "user32", importc: "CreateDialogIndirectParamA".} - #function CreateDialogIndirectParamA(hInstance: HINST; const lpTemplate: TDlgTemplate; hWndParent: HWND; lpDialogFunc: TFNDlgProc; dwInitParam: LPARAM): HWND; stdcall; external 'user32' name 'CreateDialogIndirectParamA'; - #function CreateDialogIndirectParamW(hInstance: HINST; const lpTemplate: TDlgTemplate; hWndParent: HWND; lpDialogFunc: TFNDlgProc; dwInitParam: LPARAM): HWND; stdcall; external 'user32' name 'CreateDialogIndirectParamW'; - #function CreateDIBitmap(DC: HDC; var InfoHeader: TBitmapInfoHeader; dwUsage: DWORD; InitBits: PChar; var InitInfo: TBitmapInfo; wUsage: WINUINT): HBITMAP; stdcall; external 'gdi32' name 'CreateDIBitmap'; + #function CreateDialogIndirectParamA(hInstance: HINST; const lpTemplate: DlgTemplate; hWndParent: HWND; lpDialogFunc: TFNDlgProc; dwInitParam: LPARAM): HWND; stdcall; external 'user32' name 'CreateDialogIndirectParamA'; + #function CreateDialogIndirectParamW(hInstance: HINST; const lpTemplate: DlgTemplate; hWndParent: HWND; lpDialogFunc: TFNDlgProc; dwInitParam: LPARAM): HWND; stdcall; external 'user32' name 'CreateDialogIndirectParamW'; + #function CreateDIBitmap(DC: HDC; var InfoHeader: BitmapInfoHeader; dwUsage: DWORD; InitBits: PChar; var InitInfo: BitmapInfo; wUsage: WINUINT): HBITMAP; stdcall; external 'gdi32' name 'CreateDIBitmap'; #function CreateDIBPatternBrushPt(const p1: pointer; p2: WINUINT): HBRUSH; stdcall; external 'gdi32' name 'CreateDIBPatternBrushPt'; - #function CreateDIBSection(DC: HDC; const p2: TBitmapInfo; p3: WINUINT; var p4: pointer; p5: THandle; p6: DWORD): HBITMAP; stdcall; external 'gdi32' name 'CreateDIBSection'; - #function CreateEllipticRgnIndirect(const p1: TRect): HRGN; stdcall; external 'gdi32' name 'CreateEllipticRgnIndirect'; - #function CreateFontIndirect(const p1: TLogFont): HFONT;stdcall; external 'gdi32' name 'CreateFontIndirectA'; - #function CreateFontIndirectA(const p1: TLogFontA): HFONT; stdcall; external 'gdi32' name 'CreateFontIndirectA'; + #function CreateDIBSection(DC: HDC; const p2: BitmapInfo; p3: WINUINT; var p4: pointer; p5: Handle; p6: DWORD): HBITMAP; stdcall; external 'gdi32' name 'CreateDIBSection'; + #function CreateEllipticRgnIndirect(const p1: Rect): HRGN; stdcall; external 'gdi32' name 'CreateEllipticRgnIndirect'; + #function CreateFontIndirect(const p1: LogFont): HFONT;stdcall; external 'gdi32' name 'CreateFontIndirectA'; + #function CreateFontIndirectA(const p1: LogFont): HFONT; stdcall; external 'gdi32' name 'CreateFontIndirectA'; #function CreateFontIndirectEx(const p1: PEnumLogFontExDV): HFONT;stdcall; external 'gdi32' name 'CreateFontIndirectExA'; #function CreateFontIndirectExA(const p1: PEnumLogFontExDVA): HFONT;stdcall; external 'gdi32' name 'CreateFontIndirectExA'; #function CreateFontIndirectExW(const p1: PEnumLogFontExDVW): HFONT;stdcall; external 'gdi32' name 'CreateFontIndirectExW'; - #function CreateFontIndirectW(const p1: TLogFontW): HFONT; stdcall; external 'gdi32' name 'CreateFontIndirectW'; -proc CreateIconIndirect*(piconinfo: var TIconInfo): HICON{.stdcall, + #function CreateFontIndirectW(const p1: LogFontW): HFONT; stdcall; external 'gdi32' name 'CreateFontIndirectW'; +proc CreateIconIndirect*(piconinfo: var IconInfo): HICON{.stdcall, dynlib: "user32", importc: "CreateIconIndirect".} - #function CreatePalette(const LogPalette: TLogPalette): HPalette; stdcall; external 'gdi32' name 'CreatePalette'; - #function CreatePenIndirect(const LogPen: TLogPen): HPEN; stdcall; external 'gdi32' name 'CreatePenIndirect'; -proc CreatePipe*(hReadPipe, hWritePipe: var THandle, + #function CreatePalette(const LogPalette: LogPalette): HPalette; stdcall; external 'gdi32' name 'CreatePalette'; + #function CreatePenIndirect(const LogPen: LogPen): HPEN; stdcall; external 'gdi32' name 'CreatePenIndirect'; +proc CreatePipe*(hReadPipe, hWritePipe: var Handle, lpPipeAttributes: PSecurityAttributes, nSize: DWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "CreatePipe".} proc CreatePolygonRgn*(Points: pointer, Count, FillMode: int): HRGN{.stdcall, dynlib: "gdi32", importc: "CreatePolygonRgn".} proc CreatePolyPolygonRgn*(pPtStructs: pointer, pIntArray: pointer, p3, p4: int): HRGN{. stdcall, dynlib: "gdi32", importc: "CreatePolyPolygonRgn".} - #function CreatePrivateObjectSecurity(ParentDescriptor, CreatorDescriptor: PSecurityDescriptor; var NewDescriptor: PSecurityDescriptor; IsDirectoryObject: WINBOOL; Token: THandle; const GenericMapping: TGenericMapping): WINBOOL; + #function CreatePrivateObjectSecurity(ParentDescriptor, CreatorDescriptor: PSecurityDescriptor; var NewDescriptor: PSecurityDescriptor; IsDirectoryObject: WINBOOL; Token: Handle; const GenericMapping: GenericMapping): WINBOOL; # stdcall; external 'advapi32' name 'CreatePrivateObjectSecurity'; - #function CreatePrivateObjectSecurityEx(ParentDescriptor, CreatorDescriptor: PSecurityDescriptor; var NewDescriptor: PSecurityDescriptor; ObjectType: PGUID; IsContainerObject: WINBOOL; AutoInheritFlags: ULONG; Token: THandle; - # const GenericMapping: TGenericMapping): WINBOOL;stdcall; external 'advapi32' name 'CreatePrivateObjectSecurityEx'; + #function CreatePrivateObjectSecurityEx(ParentDescriptor, CreatorDescriptor: PSecurityDescriptor; var NewDescriptor: PSecurityDescriptor; ObjectType: PGUID; IsContainerObject: WINBOOL; AutoInheritFlags: ULONG; Token: Handle; + # const GenericMapping: GenericMapping): WINBOOL;stdcall; external 'advapi32' name 'CreatePrivateObjectSecurityEx'; proc CreateProcess*(lpApplicationName: cstring, lpCommandLine: cstring, lpProcessAttributes, lpThreadAttributes: PSecurityAttributes, bInheritHandles: WINBOOL, dwCreationFlags: DWORD, lpEnvironment: pointer, lpCurrentDirectory: cstring, - lpStartupInfo: TStartupInfo, - lpProcessInformation: var TProcessInformation): WINBOOL{. + lpStartupInfo: StartupInfo, + lpProcessInformation: var ProcessInformation): WINBOOL{. stdcall, dynlib: "kernel32", importc: "CreateProcessA".} proc CreateProcessA*(lpApplicationName: LPCSTR, lpCommandLine: LPCSTR, lpProcessAttributes, lpThreadAttributes: PSecurityAttributes, bInheritHandles: WINBOOL, dwCreationFlags: DWORD, lpEnvironment: pointer, lpCurrentDirectory: LPCSTR, - lpStartupInfo: TStartupInfo, - lpProcessInformation: var TProcessInformation): WINBOOL{. + lpStartupInfo: StartupInfo, + lpProcessInformation: var ProcessInformation): WINBOOL{. stdcall, dynlib: "kernel32", importc: "CreateProcessA".} - #function CreateProcessAsUser(hToken: THandle; lpApplicationName: PChar; lpCommandLine: PChar; lpProcessAttributes: PSecurityAttributes; lpThreadAttributes: PSecurityAttributes; bInheritHandles: WINBOOL; dwCreationFlags: DWORD; - # lpEnvironment: pointer; lpCurrentDirectory: PChar; const lpStartupInfo: TStartupInfo; var lpProcessInformation: TProcessInformation): WINBOOL;stdcall; external 'advapi32' name 'CreateProcessAsUserA'; - #function CreateProcessAsUserA(hToken: THandle; lpApplicationName: LPCSTR; lpCommandLine: LPCSTR; lpProcessAttributes: PSecurityAttributes; lpThreadAttributes: PSecurityAttributes; bInheritHandles: WINBOOL; dwCreationFlags: DWORD; - # lpEnvironment: pointer; lpCurrentDirectory: LPCSTR; const lpStartupInfo: TStartupInfo; var lpProcessInformation: TProcessInformation): WINBOOL; stdcall; external 'advapi32' name 'CreateProcessAsUserA'; - #function CreateProcessAsUserW(hToken: THandle; lpApplicationName: LPWSTR; lpCommandLine: LPWSTR; lpProcessAttributes: PSecurityAttributes; lpThreadAttributes: PSecurityAttributes; bInheritHandles: WINBOOL; dwCreationFlags: DWORD; - # lpEnvironment: pointer; lpCurrentDirectory: LPWSTR; const lpStartupInfo: TStartupInfo; var lpProcessInformation: TProcessInformation): WINBOOL; stdcall; external 'advapi32' name 'CreateProcessAsUserW'; + #function CreateProcessAsUser(hToken: Handle; lpApplicationName: PChar; lpCommandLine: PChar; lpProcessAttributes: PSecurityAttributes; lpThreadAttributes: PSecurityAttributes; bInheritHandles: WINBOOL; dwCreationFlags: DWORD; + # lpEnvironment: pointer; lpCurrentDirectory: PChar; const lpStartupInfo: StartupInfo; var lpProcessInformation: ProcessInformation): WINBOOL;stdcall; external 'advapi32' name 'CreateProcessAsUserA'; + #function CreateProcessAsUserA(hToken: Handle; lpApplicationName: LPCSTR; lpCommandLine: LPCSTR; lpProcessAttributes: PSecurityAttributes; lpThreadAttributes: PSecurityAttributes; bInheritHandles: WINBOOL; dwCreationFlags: DWORD; + # lpEnvironment: pointer; lpCurrentDirectory: LPCSTR; const lpStartupInfo: StartupInfo; var lpProcessInformation: ProcessInformation): WINBOOL; stdcall; external 'advapi32' name 'CreateProcessAsUserA'; + #function CreateProcessAsUserW(hToken: Handle; lpApplicationName: LPWSTR; lpCommandLine: LPWSTR; lpProcessAttributes: PSecurityAttributes; lpThreadAttributes: PSecurityAttributes; bInheritHandles: WINBOOL; dwCreationFlags: DWORD; + # lpEnvironment: pointer; lpCurrentDirectory: LPWSTR; const lpStartupInfo: StartupInfo; var lpProcessInformation: ProcessInformation): WINBOOL; stdcall; external 'advapi32' name 'CreateProcessAsUserW'; proc CreateProcessW*(lpApplicationName: LPWSTR, lpCommandLine: LPWSTR, lpProcessAttributes, lpThreadAttributes: PSecurityAttributes, bInheritHandles: WINBOOL, dwCreationFlags: DWORD, lpEnvironment: pointer, lpCurrentDirectory: LPWSTR, - lpStartupInfo: TStartupInfo, - lpProcessInformation: var TProcessInformation): WINBOOL{. + lpStartupInfo: StartupInfo, + lpProcessInformation: var ProcessInformation): WINBOOL{. stdcall, dynlib: "kernel32", importc: "CreateProcessW".} - #function CreateRectRgnIndirect(const p1: TRect): HRGN; stdcall; external 'gdi32' name 'CreateRectRgnIndirect'; -proc CreateRemoteThread*(hProcess: THandle, lpThreadAttributes: pointer, + #function CreateRectRgnIndirect(const p1: Rect): HRGN; stdcall; external 'gdi32' name 'CreateRectRgnIndirect'; +proc CreateRemoteThread*(hProcess: Handle, lpThreadAttributes: pointer, dwStackSize: DWORD, lpStartAddress: TFNThreadStartRoutine, lpParameter: pointer, dwCreationFlags: DWORD, - lpThreadId: var DWORD): THandle{.stdcall, + lpThreadId: var DWORD): Handle{.stdcall, dynlib: "kernel32", importc: "CreateRemoteThread".} proc CreateThread*(lpThreadAttributes: pointer, dwStackSize: DWORD, lpStartAddress: TFNThreadStartRoutine, lpParameter: pointer, - dwCreationFlags: DWORD, lpThreadId: var DWORD): THandle{. + dwCreationFlags: DWORD, lpThreadId: var DWORD): Handle{. stdcall, dynlib: "kernel32", importc: "CreateThread".} proc DdeSetQualityOfService*(hWndClient: HWnd, - pqosNew: TSecurityQualityOfService, + pqosNew: SecurityQualityOfService, pqosPrev: PSecurityQualityOfService): WINBOOL{. stdcall, dynlib: "user32", importc: "DdeSetQualityOfService".} - #function DeleteAce(var pAcl: TACL; dwAceIndex: DWORD): WINBOOL; stdcall; external 'advapi32' name 'DeleteAce'; + #function DeleteAce(var pAcl: ACL; dwAceIndex: DWORD): WINBOOL; stdcall; external 'advapi32' name 'DeleteAce'; proc DescribePixelFormat*(DC: HDC, p2: int, p3: WINUINT, - p4: var TPixelFormatDescriptor): WINBOOL{.stdcall, + p4: var PixelFormatDescriptor): WINBOOL{.stdcall, dynlib: "gdi32", importc: "DescribePixelFormat".} #function DestroyPrivateObjectSecurity(var ObjectDescriptor: PSecurityDescriptor): WINBOOL; stdcall; external 'advapi32' name 'DestroyPrivateObjectSecurity'; -proc DeviceIoControl*(hDevice: THandle, dwIoControlCode: DWORD, +proc DeviceIoControl*(hDevice: Handle, dwIoControlCode: DWORD, lpInBuffer: pointer, nInBufferSize: DWORD, lpOutBuffer: pointer, nOutBufferSize: DWORD, lpBytesReturned: var DWORD, lpOverlapped: POverlapped): WINBOOL{. stdcall, dynlib: "kernel32", importc: "DeviceIoControl".} -proc DialogBoxIndirectParam*(hInstance: HINST, lpDialogTemplate: TDlgTemplate, +proc DialogBoxIndirectParam*(hInstance: HINST, lpDialogTemplate: DlgTemplate, hWndParent: HWND, lpDialogFunc: TFNDlgProc, dwInitParam: LPARAM): int{.stdcall, dynlib: "user32", importc: "DialogBoxIndirectParamA".} -proc DialogBoxIndirectParamA*(hInstance: HINST, lpDialogTemplate: TDlgTemplate, +proc DialogBoxIndirectParamA*(hInstance: HINST, lpDialogTemplate: DlgTemplate, hWndParent: HWND, lpDialogFunc: TFNDlgProc, dwInitParam: LPARAM): int{.stdcall, dynlib: "user32", importc: "DialogBoxIndirectParamA".} -proc DialogBoxIndirectParamW*(hInstance: HINST, lpDialogTemplate: TDlgTemplate, +proc DialogBoxIndirectParamW*(hInstance: HINST, lpDialogTemplate: DlgTemplate, hWndParent: HWND, lpDialogFunc: TFNDlgProc, dwInitParam: LPARAM): int{.stdcall, dynlib: "user32", importc: "DialogBoxIndirectParamW".} @@ -21323,109 +20863,109 @@ proc DispatchMessageA*(lpMsg: TMsg): int32{.stdcall, dynlib: "user32", importc: "DispatchMessageA".} proc DispatchMessageW*(lpMsg: TMsg): int32{.stdcall, dynlib: "user32", importc: "DispatchMessageW".} -proc DosDateTimeToFileTime*(wFatDate, wFatTime: int16, lpFileTime: var TFileTime): WINBOOL{. +proc DosDateTimeToFileTime*(wFatDate, wFatTime: int16, lpFileTime: var FileTime): WINBOOL{. stdcall, dynlib: "kernel32", importc: "DosDateTimeToFileTime".} proc DPtoLP*(DC: HDC, Points: pointer, Count: int): WINBOOL{.stdcall, dynlib: "gdi32", importc: "DPtoLP".} - # function DrawAnimatedRects(wnd: HWND; idAni: Integer; const lprcFrom, lprcTo: TRect): WINBOOL; stdcall; external 'user32' name 'DrawAnimatedRects'; - #function DrawCaption(p1: HWND; p2: HDC; const p3: TRect; p4: WINUINT): WINBOOL; stdcall; external 'user32' name 'DrawCaption'; -proc DrawEdge*(hdc: HDC, qrc: var TRect, edge: WINUINT, grfFlags: WINUINT): WINBOOL{. + # function DrawAnimatedRects(wnd: HWND; idAni: Integer; const lprcFrom, lprcTo: Rect): WINBOOL; stdcall; external 'user32' name 'DrawAnimatedRects'; + #function DrawCaption(p1: HWND; p2: HDC; const p3: Rect; p4: WINUINT): WINBOOL; stdcall; external 'user32' name 'DrawCaption'; +proc DrawEdge*(hdc: HDC, qrc: var Rect, edge: WINUINT, grfFlags: WINUINT): WINBOOL{. stdcall, dynlib: "user32", importc: "DrawEdge".} - #function DrawFocusRect(hDC: HDC; const lprc: TRect): WINBOOL; stdcall; external 'user32' name 'DrawFocusRect'; -proc DrawFrameControl*(DC: HDC, Rect: TRect, uType, uState: WINUINT): WINBOOL{. + #function DrawFocusRect(hDC: HDC; const lprc: Rect): WINBOOL; stdcall; external 'user32' name 'DrawFocusRect'; +proc DrawFrameControl*(DC: HDC, Rect: Rect, uType, uState: WINUINT): WINBOOL{. stdcall, dynlib: "user32", importc: "DrawFrameControl".} -proc DrawText*(hDC: HDC, lpString: cstring, nCount: int, lpRect: var TRect, +proc DrawText*(hDC: HDC, lpString: cstring, nCount: int, lpRect: var Rect, uFormat: WINUINT): int{.stdcall, dynlib: "user32", importc: "DrawTextA".} -proc DrawTextA*(hDC: HDC, lpString: LPCSTR, nCount: int, lpRect: var TRect, +proc DrawTextA*(hDC: HDC, lpString: LPCSTR, nCount: int, lpRect: var Rect, uFormat: WINUINT): int{.stdcall, dynlib: "user32", importc: "DrawTextA".} -proc DrawTextEx*(DC: HDC, lpchText: cstring, cchText: int, p4: var TRect, +proc DrawTextEx*(DC: HDC, lpchText: cstring, cchText: int, p4: var Rect, dwDTFormat: WINUINT, DTParams: PDrawTextParams): int{.stdcall, dynlib: "user32", importc: "DrawTextExA".} -proc DrawTextExA*(DC: HDC, lpchText: LPCSTR, cchText: int, p4: var TRect, +proc DrawTextExA*(DC: HDC, lpchText: LPCSTR, cchText: int, p4: var Rect, dwDTFormat: WINUINT, DTParams: PDrawTextParams): int{.stdcall, dynlib: "user32", importc: "DrawTextExA".} -proc DrawTextExW*(DC: HDC, lpchText: LPWSTR, cchText: int, p4: var TRect, +proc DrawTextExW*(DC: HDC, lpchText: LPWSTR, cchText: int, p4: var Rect, dwDTFormat: WINUINT, DTParams: PDrawTextParams): int{.stdcall, dynlib: "user32", importc: "DrawTextExW".} -proc DrawTextW*(hDC: HDC, lpString: LPWSTR, nCount: int, lpRect: var TRect, +proc DrawTextW*(hDC: HDC, lpString: LPWSTR, nCount: int, lpRect: var Rect, uFormat: WINUINT): int{.stdcall, dynlib: "user32", importc: "DrawTextW".} - #function DuplicateTokenEx(hExistingToken: THandle; dwDesiredAccess: DWORD; lpTokenAttributes: PSecurityAttributes; ImpersonationLevel: TSecurityImpersonationLevel; TokenType: TTokenType; var phNewToken: THandle): WINBOOL; + #function DuplicateTokenEx(hExistingToken: Handle; dwDesiredAccess: DWORD; lpTokenAttributes: PSecurityAttributes; ImpersonationLevel: TSecurityImpersonationLevel; TokenType: TTokenType; var phNewToken: Handle): WINBOOL; # stdcall; external 'advapi32' name 'DuplicateTokenEx'; -proc EndPaint*(wnd: HWND, lpPaint: TPaintStruct): WINBOOL{.stdcall, +proc EndPaint*(wnd: HWND, lpPaint: PaintStruct): WINBOOL{.stdcall, dynlib: "user32", importc: "EndPaint".} #function EnumDisplayDevices(Unused: pointer; iDevNum: DWORD; var lpDisplayDevice: TDisplayDevice; dwFlags: DWORD): WINBOOL;stdcall; external 'user32' name 'EnumDisplayDevicesA'; #function EnumDisplayDevicesA(Unused: pointer; iDevNum: DWORD; var lpDisplayDevice: TDisplayDeviceA; dwFlags: DWORD): WINBOOL;stdcall; external 'user32' name 'EnumDisplayDevicesA'; #function EnumDisplayDevicesW(Unused: pointer; iDevNum: DWORD; var lpDisplayDevice: TDisplayDeviceW; dwFlags: DWORD): WINBOOL;stdcall; external 'user32' name 'EnumDisplayDevicesW'; proc EnumDisplaySettings*(lpszDeviceName: cstring, iModeNum: DWORD, - lpDevMode: var TDeviceMode): WINBOOL{.stdcall, + lpDevMode: var DevMode): WINBOOL{.stdcall, dynlib: "user32", importc: "EnumDisplaySettingsA".} proc EnumDisplaySettingsA*(lpszDeviceName: LPCSTR, iModeNum: DWORD, - lpDevMode: var TDeviceModeA): WINBOOL{.stdcall, + lpDevMode: var DevMode): WINBOOL{.stdcall, dynlib: "user32", importc: "EnumDisplaySettingsA".} proc EnumDisplaySettingsW*(lpszDeviceName: LPWSTR, iModeNum: DWORD, - lpDevMode: var TDeviceModeW): WINBOOL{.stdcall, + lpDevMode: var DevModeW): WINBOOL{.stdcall, dynlib: "user32", importc: "EnumDisplaySettingsW".} - #function EnumEnhMetaFile(DC: HDC; p2: HENHMETAFILE; p3: TFNEnhMFEnumProc; p4: pointer; const p5: TRect): WINBOOL; stdcall; external 'gdi32' name 'EnumEnhMetaFile'; - #function EnumFontFamiliesEx(DC: HDC; var p2: TLogFont; p3: TFNFontEnumProc; p4: LPARAM; p5: DWORD): WINBOOL;stdcall; external 'gdi32' name 'EnumFontFamiliesExA'; - #function EnumFontFamiliesExA(DC: HDC; var p2: TLogFontA; p3: TFNFontEnumProcA; p4: LPARAM; p5: DWORD): WINBOOL; stdcall; external 'gdi32' name 'EnumFontFamiliesExA'; - #function EnumFontFamiliesExW(DC: HDC; var p2: TLogFontW; p3: TFNFontEnumProcW; p4: LPARAM; p5: DWORD): WINBOOL; stdcall; external 'gdi32' name 'EnumFontFamiliesExW'; - #function EqualRect(const lprc1, lprc2: TRect): WINBOOL; stdcall; external 'user32' name 'EqualRect'; -proc ExtCreatePen*(PenStyle, Width: DWORD, Brush: TLogBrush, StyleCount: DWORD, + #function EnumEnhMetaFile(DC: HDC; p2: HENHMETAFILE; p3: TFNEnhMFEnumProc; p4: pointer; const p5: Rect): WINBOOL; stdcall; external 'gdi32' name 'EnumEnhMetaFile'; + #function EnumFontFamiliesEx(DC: HDC; var p2: LogFont; p3: TFNFontEnumProc; p4: LPARAM; p5: DWORD): WINBOOL;stdcall; external 'gdi32' name 'EnumFontFamiliesExA'; + #function EnumFontFamiliesExA(DC: HDC; var p2: LogFont; p3: TFNFontEnumProcA; p4: LPARAM; p5: DWORD): WINBOOL; stdcall; external 'gdi32' name 'EnumFontFamiliesExA'; + #function EnumFontFamiliesExW(DC: HDC; var p2: LogFontW; p3: TFNFontEnumProcW; p4: LPARAM; p5: DWORD): WINBOOL; stdcall; external 'gdi32' name 'EnumFontFamiliesExW'; + #function EqualRect(const lprc1, lprc2: Rect): WINBOOL; stdcall; external 'user32' name 'EqualRect'; +proc ExtCreatePen*(PenStyle, Width: DWORD, Brush: LogBrush, StyleCount: DWORD, Style: pointer): HPEN{.stdcall, dynlib: "gdi32", importc: "ExtCreatePen".} -proc ExtCreateRegion*(p1: PXForm, p2: DWORD, p3: TRgnData): HRGN{.stdcall, +proc ExtCreateRegion*(p1: PXForm, p2: DWORD, p3: RgnData): HRGN{.stdcall, dynlib: "gdi32", importc: "ExtCreateRegion".} # function ExtEscape(DC: HDC; p2, p3: Integer; const p4: LPCSTR; p5: Integer; p6: LPSTR): Integer; stdcall; external 'gdi32' name 'ExtEscape'; -proc FileTimeToDosDateTime*(lpFileTime: TFileTime, +proc FileTimeToDosDateTime*(lpFileTime: FileTime, lpFatDate, lpFatTime: var int16): WINBOOL{.stdcall, dynlib: "kernel32", importc: "FileTimeToDosDateTime".} -proc FileTimeToLocalFileTime*(lpFileTime: TFileTime, - lpLocalFileTime: var TFileTime): WINBOOL{.stdcall, +proc FileTimeToLocalFileTime*(lpFileTime: FileTime, + lpLocalFileTime: var FileTime): WINBOOL{.stdcall, dynlib: "kernel32", importc: "FileTimeToLocalFileTime".} -proc FileTimeToSystemTime*(lpFileTime: TFileTime, lpSystemTime: var TSystemTime): WINBOOL{. +proc FileTimeToSystemTime*(lpFileTime: FileTime, lpSystemTime: var SystemTime): WINBOOL{. stdcall, dynlib: "kernel32", importc: "FileTimeToSystemTime".} -proc FillConsoleOutputAttribute*(hConsoleOutput: THandle, wAttribute: int16, - nLength: DWORD, dwWriteCoord: TCoord, +proc FillConsoleOutputAttribute*(hConsoleOutput: Handle, wAttribute: int16, + nLength: DWORD, dwWriteCoord: Coord, lpNumberOfAttrsWritten: var DWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "FillConsoleOutputAttribute".} -proc FillConsoleOutputCharacter*(hConsoleOutput: THandle, cCharacter: char, - nLength: DWORD, dwWriteCoord: TCoord, +proc FillConsoleOutputCharacter*(hConsoleOutput: Handle, cCharacter: char, + nLength: DWORD, dwWriteCoord: Coord, lpNumberOfCharsWritten: var DWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "FillConsoleOutputCharacterA".} -proc FillConsoleOutputCharacterA*(hConsoleOutput: THandle, cCharacter: char, - nLength: DWORD, dwWriteCoord: TCoord, +proc FillConsoleOutputCharacterA*(hConsoleOutput: Handle, cCharacter: char, + nLength: DWORD, dwWriteCoord: Coord, lpNumberOfCharsWritten: var DWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "FillConsoleOutputCharacterA".} -proc FillConsoleOutputCharacterW*(hConsoleOutput: THandle, cCharacter: WideChar, - nLength: DWORD, dwWriteCoord: TCoord, +proc FillConsoleOutputCharacterW*(hConsoleOutput: Handle, cCharacter: WideChar, + nLength: DWORD, dwWriteCoord: Coord, lpNumberOfCharsWritten: var DWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "FillConsoleOutputCharacterW".} - #function FillRect(hDC: HDC; const lprc: TRect; hbr: HBRUSH): Integer; stdcall; external 'user32' name 'FillRect'; -proc FindFirstFile*(lpFileName: cstring, lpFindFileData: var TWIN32FindData): THandle{. + #function FillRect(hDC: HDC; const lprc: Rect; hbr: HBRUSH): Integer; stdcall; external 'user32' name 'FillRect'; +proc FindFirstFile*(lpFileName: cstring, lpFindFileData: var WIN32FindData): Handle{. stdcall, dynlib: "kernel32", importc: "FindFirstFileA".} -proc FindFirstFileA*(lpFileName: LPCSTR, lpFindFileData: var TWIN32FindDataA): THandle{. +proc FindFirstFileA*(lpFileName: LPCSTR, lpFindFileData: var WIN32FindData): Handle{. stdcall, dynlib: "kernel32", importc: "FindFirstFileA".} -proc FindFirstFileW*(lpFileName: LPWSTR, lpFindFileData: var TWIN32FindDataW): THandle{. +proc FindFirstFileW*(lpFileName: LPWSTR, lpFindFileData: var WIN32FindDataW): Handle{. stdcall, dynlib: "kernel32", importc: "FindFirstFileW".} - #function FindFirstFreeAce(var pAcl: TACL; var pAce: pointer): WINBOOL; stdcall; external 'advapi32' name 'FindFirstFreeAce'; -proc FindNextFile*(hFindFile: THandle, lpFindFileData: var TWIN32FindData): WINBOOL{. + #function FindFirstFreeAce(var pAcl: ACL; var pAce: pointer): WINBOOL; stdcall; external 'advapi32' name 'FindFirstFreeAce'; +proc FindNextFile*(hFindFile: Handle, lpFindFileData: var WIN32FindData): WINBOOL{. stdcall, dynlib: "kernel32", importc: "FindNextFileA".} -proc FindNextFileA*(hFindFile: THandle, lpFindFileData: var TWIN32FindDataA): WINBOOL{. +proc FindNextFileA*(hFindFile: Handle, lpFindFileData: var WIN32FindData): WINBOOL{. stdcall, dynlib: "kernel32", importc: "FindNextFileA".} -proc FindNextFileW*(hFindFile: THandle, lpFindFileData: var TWIN32FindDataW): WINBOOL{. +proc FindNextFileW*(hFindFile: Handle, lpFindFileData: var WIN32FindDataW): WINBOOL{. stdcall, dynlib: "kernel32", importc: "FindNextFileW".} - #function FlushInstructionCache(hProcess: THandle; const lpBaseAddress: pointer; dwSize: DWORD): WINBOOL; stdcall; external 'kernel32' name 'FlushInstructionCache'; + #function FlushInstructionCache(hProcess: Handle; const lpBaseAddress: pointer; dwSize: DWORD): WINBOOL; stdcall; external 'kernel32' name 'FlushInstructionCache'; #function FlushViewOfFile(const lpBaseAddress: pointer; dwNumberOfBytesToFlush: DWORD): WINBOOL; stdcall; external 'kernel32' name 'FlushViewOfFile'; - #function FrameRect(hDC: HDC; const lprc: TRect; hbr: HBRUSH): Integer; stdcall; external 'user32' name 'FrameRect'; - #function GetAce(const pAcl: TACL; dwAceIndex: DWORD; var pAce: pointer): WINBOOL; stdcall; external 'advapi32' name 'GetAce'; - #function GetAclInformation(const pAcl: TACL; pAclInformation: pointer; nAclInformationLength: DWORD; dwAclInformationClass: TAclInformationClass): WINBOOL; stdcall; external 'advapi32' name 'GetAclInformation'; + #function FrameRect(hDC: HDC; const lprc: Rect; hbr: HBRUSH): Integer; stdcall; external 'user32' name 'FrameRect'; + #function GetAce(const pAcl: ACL; dwAceIndex: DWORD; var pAce: pointer): WINBOOL; stdcall; external 'advapi32' name 'GetAce'; + #function GetAclInformation(const pAcl: ACL; pAclInformation: pointer; nAclInformationLength: DWORD; dwAclInformationClass: AclInformationClass): WINBOOL; stdcall; external 'advapi32' name 'GetAclInformation'; #function GetAltTabInfo(wnd: HWND; iItem: Integer; var pati: TAltTabInfo; pszItemText: PChar; cchItemText: WINUINT): WINBOOL;stdcall; external 'user32' name 'GetAltTabInfoA'; #function GetAltTabInfoA(wnd: HWND; iItem: Integer; var pati: TAltTabInfo; pszItemText: LPCSTR; cchItemText: WINUINT): WINBOOL;stdcall; external 'user32' name 'GetAltTabInfoA'; #function GetAltTabInfoW(wnd: HWND; iItem: Integer; var pati: TAltTabInfo; pszItemText: LPWSTR; cchItemText: WINUINT): WINBOOL;stdcall; external 'user32' name 'GetAltTabInfoW'; -proc GetAspectRatioFilterEx*(DC: HDC, p2: var TSize): WINBOOL{.stdcall, +proc GetAspectRatioFilterEx*(DC: HDC, p2: var Size): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetAspectRatioFilterEx".} proc GetBinaryType*(lpApplicationName: cstring, lpBinaryType: var DWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "GetBinaryTypeA".} @@ -21433,13 +20973,13 @@ proc GetBinaryTypeA*(lpApplicationName: LPCSTR, lpBinaryType: var DWORD): WINBOO stdcall, dynlib: "kernel32", importc: "GetBinaryTypeA".} proc GetBinaryTypeW*(lpApplicationName: LPWSTR, lpBinaryType: var DWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "GetBinaryTypeW".} -proc GetBitmapDimensionEx*(p1: HBITMAP, p2: var TSize): WINBOOL{.stdcall, +proc GetBitmapDimensionEx*(p1: HBITMAP, p2: var Size): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetBitmapDimensionEx".} -proc GetBoundsRect*(DC: HDC, p2: var TRect, p3: WINUINT): WINUINT{.stdcall, +proc GetBoundsRect*(DC: HDC, p2: var Rect, p3: WINUINT): WINUINT{.stdcall, dynlib: "gdi32", importc: "GetBoundsRect".} -proc GetBrushOrgEx*(DC: HDC, p2: var TPoint): WINBOOL{.stdcall, dynlib: "gdi32", +proc GetBrushOrgEx*(DC: HDC, p2: var Point): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetBrushOrgEx".} -proc GetCaretPos*(lpPoint: var TPoint): WINBOOL{.stdcall, dynlib: "user32", +proc GetCaretPos*(lpPoint: var Point): WINBOOL{.stdcall, dynlib: "user32", importc: "GetCaretPos".} proc GetCharABCWidths*(DC: HDC, p2, p3: WINUINT, ABCStructs: pointer): WINBOOL{. stdcall, dynlib: "gdi32", importc: "GetCharABCWidthsA".} @@ -21455,13 +20995,13 @@ proc GetCharABCWidthsFloatW*(DC: HDC, p2, p3: WINUINT, ABCFloatSturcts: pointer) proc GetCharABCWidthsW*(DC: HDC, p2, p3: WINUINT, ABCStructs: pointer): WINBOOL{. stdcall, dynlib: "gdi32", importc: "GetCharABCWidthsW".} proc GetCharacterPlacement*(DC: HDC, p2: cstring, p3, p4: WINBOOL, - p5: var TGCPResults, p6: DWORD): DWORD{.stdcall, + p5: var GCPResults, p6: DWORD): DWORD{.stdcall, dynlib: "gdi32", importc: "GetCharacterPlacementA".} proc GetCharacterPlacementA*(DC: HDC, p2: LPCSTR, p3, p4: WINBOOL, - p5: var TGCPResults, p6: DWORD): DWORD{.stdcall, + p5: var GCPResults, p6: DWORD): DWORD{.stdcall, dynlib: "gdi32", importc: "GetCharacterPlacementA".} proc GetCharacterPlacementW*(DC: HDC, p2: LPWSTR, p3, p4: WINBOOL, - p5: var TGCPResults, p6: DWORD): DWORD{.stdcall, + p5: var GCPResults, p6: DWORD): DWORD{.stdcall, dynlib: "gdi32", importc: "GetCharacterPlacementW".} proc GetCharWidth*(DC: HDC, p2, p3: WINUINT, Widths: pointer): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetCharWidthA".} @@ -21483,37 +21023,37 @@ proc GetCharWidthFloatW*(DC: HDC, p2, p3: WINUINT, Widths: pointer): WINBOOL{. proc GetCharWidthW*(DC: HDC, p2, p3: WINUINT, Widths: pointer): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetCharWidthW".} proc GetClassInfo*(hInstance: HINST, lpClassName: cstring, - lpWndClass: var TWndClass): WINBOOL{.stdcall, + lpWndClass: var WndClass): WINBOOL{.stdcall, dynlib: "user32", importc: "GetClassInfoA".} proc GetClassInfoA*(hInstance: HINST, lpClassName: LPCSTR, - lpWndClass: var TWndClassA): WINBOOL{.stdcall, + lpWndClass: var WndClass): WINBOOL{.stdcall, dynlib: "user32", importc: "GetClassInfoA".} proc GetClassInfoEx*(Instance: HINST, Classname: cstring, - WndClass: var TWndClassEx): WINBOOL{.stdcall, + WndClass: var WndClassEx): WINBOOL{.stdcall, dynlib: "user32", importc: "GetClassInfoExA".} - #function GetClassInfoExA(Instance: HINST; Classname: LPCSTR; var WndClass: TWndClassExA): WINBOOL; stdcall; external 'user32' name 'GetClassInfoExA'; - #function GetClassInfoExW(Instance: HINST; Classname: LPWSTR; var WndClass: TWndClassExW): WINBOOL; stdcall; external 'user32' name 'GetClassInfoExW'; - #function GetClassInfoW(hInstance: HINST; lpClassName: LPWSTR; var lpWndClass: TWndClassW): WINBOOL; stdcall; external 'user32' name 'GetClassInfoW'; -proc GetClientRect*(wnd: HWND, lpRect: var TRect): WINBOOL{.stdcall, + #function GetClassInfoExA(Instance: HINST; Classname: LPCSTR; var WndClass: WndClassEx): WINBOOL; stdcall; external 'user32' name 'GetClassInfoExA'; + #function GetClassInfoExW(Instance: HINST; Classname: LPWSTR; var WndClass: WndClassExW): WINBOOL; stdcall; external 'user32' name 'GetClassInfoExW'; + #function GetClassInfoW(hInstance: HINST; lpClassName: LPWSTR; var lpWndClass: WndClassW): WINBOOL; stdcall; external 'user32' name 'GetClassInfoW'; +proc GetClientRect*(wnd: HWND, lpRect: var Rect): WINBOOL{.stdcall, dynlib: "user32", importc: "GetClientRect".} -proc GetClipBox*(DC: HDC, Rect: var TRect): int{.stdcall, dynlib: "gdi32", +proc GetClipBox*(DC: HDC, Rect: var Rect): int{.stdcall, dynlib: "gdi32", importc: "GetClipBox".} -proc GetClipCursor*(lpRect: var TRect): WINBOOL{.stdcall, dynlib: "user32", +proc GetClipCursor*(lpRect: var Rect): WINBOOL{.stdcall, dynlib: "user32", importc: "GetClipCursor".} -proc GetColorAdjustment*(DC: HDC, p2: var TColorAdjustment): WINBOOL{.stdcall, +proc GetColorAdjustment*(DC: HDC, p2: var ColorAdjustment): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetColorAdjustment".} -proc GetCommConfig*(hCommDev: THandle, lpCC: var TCommConfig, +proc GetCommConfig*(hCommDev: Handle, lpCC: var CommConfig, lpdwSize: var DWORD): WINBOOL{.stdcall, dynlib: "kernel32", importc: "GetCommConfig".} -proc GetCommMask*(hFile: THandle, lpEvtMask: var DWORD): WINBOOL{.stdcall, +proc GetCommMask*(hFile: Handle, lpEvtMask: var DWORD): WINBOOL{.stdcall, dynlib: "kernel32", importc: "GetCommMask".} -proc GetCommModemStatus*(hFile: THandle, lpModemStat: var DWORD): WINBOOL{. +proc GetCommModemStatus*(hFile: Handle, lpModemStat: var DWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "GetCommModemStatus".} -proc GetCommProperties*(hFile: THandle, lpCommProp: var TCommProp): WINBOOL{. +proc GetCommProperties*(hFile: Handle, lpCommProp: var CommProp): WINBOOL{. stdcall, dynlib: "kernel32", importc: "GetCommProperties".} -proc GetCommState*(hFile: THandle, lpDCB: var TDCB): WINBOOL{.stdcall, +proc GetCommState*(hFile: Handle, lpDCB: var DCB): WINBOOL{.stdcall, dynlib: "kernel32", importc: "GetCommState".} -proc GetCommTimeouts*(hFile: THandle, lpCommTimeouts: var TCommTimeouts): WINBOOL{. +proc GetCommTimeouts*(hFile: Handle, lpCommTimeouts: var CommTimeouts): WINBOOL{. stdcall, dynlib: "kernel32", importc: "GetCommTimeouts".} proc GetComputerName*(lpBuffer: cstring, nSize: var DWORD): WINBOOL{.stdcall, dynlib: "kernel32", importc: "GetComputerNameA".} @@ -21521,38 +21061,38 @@ proc GetComputerNameA*(lpBuffer: LPCSTR, nSize: var DWORD): WINBOOL{.stdcall, dynlib: "kernel32", importc: "GetComputerNameA".} proc GetComputerNameW*(lpBuffer: LPWSTR, nSize: var DWORD): WINBOOL{.stdcall, dynlib: "kernel32", importc: "GetComputerNameW".} -proc GetConsoleCursorInfo*(hConsoleOutput: THandle, - lpConsoleCursorInfo: var TConsoleCursorInfo): WINBOOL{. +proc GetConsoleCursorInfo*(hConsoleOutput: Handle, + lpConsoleCursorInfo: var ConsoleCursorInfo): WINBOOL{. stdcall, dynlib: "kernel32", importc: "GetConsoleCursorInfo".} -proc GetConsoleMode*(hConsoleHandle: THandle, lpMode: var DWORD): WINBOOL{. +proc GetConsoleMode*(hConsoleHandle: Handle, lpMode: var DWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "GetConsoleMode".} -proc GetConsoleScreenBufferInfo*(hConsoleOutput: THandle, - lpConsoleScreenBufferInfo: var TConsoleScreenBufferInfo): WINBOOL{.stdcall, +proc GetConsoleScreenBufferInfo*(hConsoleOutput: Handle, + lpConsoleScreenBufferInfo: var ConsoleScreenBufferInfo): WINBOOL{.stdcall, dynlib: "kernel32", importc: "GetConsoleScreenBufferInfo".} -proc GetCPInfo*(CodePage: WINUINT, lpCPInfo: var TCPInfo): WINBOOL{.stdcall, +proc GetCPInfo*(CodePage: WINUINT, lpCPInfo: var CPInfo): WINBOOL{.stdcall, dynlib: "kernel32", importc: "GetCPInfo".} #function GetCurrentHwProfile(var lpHwProfileInfo: THWProfileInfo): WINBOOL;stdcall; external 'advapi32' name 'GetCurrentHwProfileA'; #function GetCurrentHwProfileA(var lpHwProfileInfo: THWProfileInfoA): WINBOOL;stdcall; external 'advapi32' name 'GetCurrentHwProfileA'; #function GetCurrentHwProfileW(var lpHwProfileInfo: THWProfileInfoW): WINBOOL;stdcall; external 'advapi32' name 'GetCurrentHwProfileW'; -proc GetCursorInfo*(pci: var TCursorInfo): WINBOOL{.stdcall, dynlib: "user32", +proc GetCursorInfo*(pci: var ConsoleCursorInfo): WINBOOL{.stdcall, dynlib: "user32", importc: "GetCursorInfo".} -proc GetCursorPos*(lpPoint: var TPoint): WINBOOL{.stdcall, dynlib: "user32", +proc GetCursorPos*(lpPoint: var Point): WINBOOL{.stdcall, dynlib: "user32", importc: "GetCursorPos".} -proc GetDCOrgEx*(DC: HDC, Origin: var TPoint): WINBOOL{.stdcall, +proc GetDCOrgEx*(DC: HDC, Origin: var Point): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetDCOrgEx".} -proc GetDefaultCommConfig*(lpszName: cstring, lpCC: var TCommConfig, +proc GetDefaultCommConfig*(lpszName: cstring, lpCC: var CommConfig, lpdwSize: var DWORD): WINBOOL{.stdcall, dynlib: "kernel32", importc: "GetDefaultCommConfigA".} -proc GetDefaultCommConfigA*(lpszName: LPCSTR, lpCC: var TCommConfig, +proc GetDefaultCommConfigA*(lpszName: LPCSTR, lpCC: var CommConfig, lpdwSize: var DWORD): WINBOOL{.stdcall, dynlib: "kernel32", importc: "GetDefaultCommConfigA".} -proc GetDefaultCommConfigW*(lpszName: LPWSTR, lpCC: var TCommConfig, +proc GetDefaultCommConfigW*(lpszName: LPWSTR, lpCC: var CommConfig, lpdwSize: var DWORD): WINBOOL{.stdcall, dynlib: "kernel32", importc: "GetDefaultCommConfigW".} proc GetDIBColorTable*(DC: HDC, p2, p3: WINUINT, RGBQuadStructs: pointer): WINUINT{. stdcall, dynlib: "gdi32", importc: "GetDIBColorTable".} proc GetDIBits*(DC: HDC, Bitmap: HBitmap, StartScan, NumScans: WINUINT, - Bits: pointer, BitInfo: var TBitmapInfo, Usage: WINUINT): int{. + Bits: pointer, BitInfo: var BitmapInfo, Usage: WINUINT): int{. stdcall, dynlib: "gdi32", importc: "GetDIBits".} proc GetDiskFreeSpace*(lpRootPathName: cstring, lpSectorsPerCluster, lpBytesPerSector, lpNumberOfFreeClusters, lpTotalNumberOfClusters: var DWORD): WINBOOL{. @@ -21561,15 +21101,15 @@ proc GetDiskFreeSpaceA*(lpRootPathName: LPCSTR, lpSectorsPerCluster, lpBytesPerSector, lpNumberOfFreeClusters, lpTotalNumberOfClusters: var DWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "GetDiskFreeSpaceA".} proc GetDiskFreeSpaceEx*(lpDirectoryName: cstring, lpFreeBytesAvailableToCaller, - lpTotalNumberOfBytes: var TLargeInteger, + lpTotalNumberOfBytes: var LargeInteger, lpTotalNumberOfFreeBytes: PLargeInteger): WINBOOL{. stdcall, dynlib: "kernel32", importc: "GetDiskFreeSpaceExA".} proc GetDiskFreeSpaceExA*(lpDirectoryName: LPCSTR, lpFreeBytesAvailableToCaller, - lpTotalNumberOfBytes: var TLargeInteger, + lpTotalNumberOfBytes: var LargeInteger, lpTotalNumberOfFreeBytes: PLargeInteger): WINBOOL{. stdcall, dynlib: "kernel32", importc: "GetDiskFreeSpaceExA".} proc GetDiskFreeSpaceExW*(lpDirectoryName: LPWSTR, lpFreeBytesAvailableToCaller, - lpTotalNumberOfBytes: var TLargeInteger, + lpTotalNumberOfBytes: var LargeInteger, lpTotalNumberOfFreeBytes: PLargeInteger): WINBOOL{. stdcall, dynlib: "kernel32", importc: "GetDiskFreeSpaceExW".} proc GetDiskFreeSpaceW*(lpRootPathName: LPWSTR, lpSectorsPerCluster, @@ -21584,12 +21124,12 @@ proc GetDiskFreeSpaceExA*(lpDirectoryName: LPCSTR, lpFreeBytesAvailableToCaller, proc GetDiskFreeSpaceExW*(lpDirectoryName: LPWSTR, lpFreeBytesAvailableToCaller, lpTotalNumberOfBytes: PLargeInteger, lpTotalNumberOfFreeBytes: PLargeInteger): WINBOOL{. stdcall, dynlib: "kernel32", importc: "GetDiskFreeSpaceExW".} - #function GetEnhMetaFilePixelFormat(p1: HENHMETAFILE; p2: Cardinal; var p3: TPixelFormatDescriptor): WINUINT;stdcall; external 'gdi32' name 'GetEnhMetaFilePixelFormat'; -proc GetExitCodeProcess*(hProcess: THandle, lpExitCode: var DWORD): WINBOOL{. + #function GetEnhMetaFilePixelFormat(p1: HENHMETAFILE; p2: Cardinal; var p3: PixelFormatDescriptor): WINUINT;stdcall; external 'gdi32' name 'GetEnhMetaFilePixelFormat'; +proc GetExitCodeProcess*(hProcess: Handle, lpExitCode: var DWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "GetExitCodeProcess".} -proc GetExitCodeThread*(hThread: THandle, lpExitCode: var DWORD): WINBOOL{. +proc GetExitCodeThread*(hThread: Handle, lpExitCode: var DWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "GetExitCodeThread".} -proc GetFileInformationByHandle*(hFile: THandle, lpFileInformation: var TByHandleFileInformation): WINBOOL{. +proc GetFileInformationByHandle*(hFile: Handle, lpFileInformation: var ByHandleFileInformation): WINBOOL{. stdcall, dynlib: "kernel32", importc: "GetFileInformationByHandle".} #function GetFileSecurity(lpFileName: PChar; RequestedInformation: SECURITY_INFORMATION; pSecurityDescriptor: PSecurityDescriptor; nLength: DWORD; var lpnLengthNeeded: DWORD): WINBOOL;stdcall; external 'advapi32' name 'GetFileSecurityA'; #function GetFileSecurityA(lpFileName: LPCSTR; RequestedInformation: SECURITY_INFORMATION; pSecurityDescriptor: PSecurityDescriptor; nLength: DWORD; var lpnLengthNeeded: DWORD): WINBOOL; stdcall; external 'advapi32' name 'GetFileSecurityA'; @@ -21604,24 +21144,24 @@ proc GetFileVersionInfoSizeW*(lptstrFilename: LPWSTR, lpdwHandle: var DWORD): DW # function GetFullPathName(lpFileName: PChar; nBufferLength: DWORD; lpBuffer: PChar; var lpFilePart: PChar): DWORD;stdcall; external 'kernel32' name 'GetFullPathNameA'; # function GetFullPathNameA(lpFileName: LPCSTR; nBufferLength: DWORD; lpBuffer: LPCSTR; var lpFilePart: LPCSTR): DWORD; stdcall; external 'kernel32' name 'GetFullPathNameA'; # function GetFullPathNameW(lpFileName: LPWSTR; nBufferLength: DWORD; lpBuffer: LPWSTR; var lpFilePart: LPWSTR): DWORD; stdcall; external 'kernel32' name 'GetFullPathNameW'; -proc GetGlyphOutline*(DC: HDC, p2, p3: WINUINT, p4: TGlyphMetrics, p5: DWORD, - p6: pointer, p7: TMat2): DWORD{.stdcall, dynlib: "gdi32", +proc GetGlyphOutline*(DC: HDC, p2, p3: WINUINT, p4: GlyphMetrics, p5: DWORD, + p6: pointer, p7: Mat2): DWORD{.stdcall, dynlib: "gdi32", importc: "GetGlyphOutlineA".} -proc GetGlyphOutlineA*(DC: HDC, p2, p3: WINUINT, p4: TGlyphMetrics, p5: DWORD, - p6: pointer, p7: TMat2): DWORD{.stdcall, dynlib: "gdi32", +proc GetGlyphOutlineA*(DC: HDC, p2, p3: WINUINT, p4: GlyphMetrics, p5: DWORD, + p6: pointer, p7: Mat2): DWORD{.stdcall, dynlib: "gdi32", importc: "GetGlyphOutlineA".} -proc GetGlyphOutlineW*(DC: HDC, p2, p3: WINUINT, p4: TGlyphMetrics, p5: DWORD, - p6: pointer, p7: TMat2): DWORD{.stdcall, dynlib: "gdi32", +proc GetGlyphOutlineW*(DC: HDC, p2, p3: WINUINT, p4: GlyphMetrics, p5: DWORD, + p6: pointer, p7: Mat2): DWORD{.stdcall, dynlib: "gdi32", importc: "GetGlyphOutlineW".} #function GetGUIThreadInfo(idThread: DWORD; var pgui: TGUIThreadinfo): WINBOOL;stdcall; external 'user32' name 'GetGUIThreadInfo'; -proc GetHandleInformation*(hObject: THandle, lpdwFlags: var DWORD): WINBOOL{. +proc GetHandleInformation*(hObject: Handle, lpdwFlags: var DWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "GetHandleInformation".} #function GetICMProfile(DC: HDC; var Size: DWORD; Name: PChar): WINBOOL;stdcall; external 'gdi32' name 'GetICMProfileA'; #function GetICMProfileA(DC: HDC; var Size: DWORD; Name: LPCSTR): WINBOOL; stdcall; external 'gdi32' name 'GetICMProfileA'; #function GetICMProfileW(DC: HDC; var Size: DWORD; Name: LPWSTR): WINBOOL; stdcall; external 'gdi32' name 'GetICMProfileW'; -proc GetIconInfo*(icon: HICON, piconinfo: var TIconInfo): WINBOOL{.stdcall, +proc GetIconInfo*(icon: HICON, piconinfo: var IconInfo): WINBOOL{.stdcall, dynlib: "user32", importc: "GetIconInfo".} - #function GetKernelObjectSecurity(Handle: THandle; RequestedInformation: SECURITY_INFORMATION; pSecurityDescriptor: PSecurityDescriptor; nLength: DWORD; var lpnLengthNeeded: DWORD): WINBOOL; stdcall; external 'advapi32' name 'GetKernelObjectSecurity'; + #function GetKernelObjectSecurity(Handle: Handle; RequestedInformation: SECURITY_INFORMATION; pSecurityDescriptor: PSecurityDescriptor; nLength: DWORD; var lpnLengthNeeded: DWORD): WINBOOL; stdcall; external 'advapi32' name 'GetKernelObjectSecurity'; proc GetKerningPairs*(DC: HDC, Count: DWORD, KerningPairs: pointer): DWORD{. stdcall, dynlib: "gdi32", importc: "GetKerningPairs".} proc GetKeyboardLayoutList*(nBuff: int, List: pointer): WINUINT{.stdcall, @@ -21638,25 +21178,25 @@ proc SetSystemTime*(lpSystemTime: var SYSTEMTIME): WINBOOL{.stdcall, dynlib: "kernel32", importc: "SetSystemTime".} proc SetLocalTime*(lpSystemTime: var SYSTEMTIME): WINBOOL{.stdcall, dynlib: "kernel32", importc: "SetLocalTime".} -proc GetLogColorSpace*(p1: HCOLORSPACE, ColorSpace: var TLogColorSpace, +proc GetLogColorSpace*(p1: HCOLORSPACE, ColorSpace: var LogColorSpace, Size: DWORD): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetLogColorSpaceA".} -proc GetLogColorSpaceA*(p1: HCOLORSPACE, ColorSpace: var TLogColorSpaceA, +proc GetLogColorSpaceA*(p1: HCOLORSPACE, ColorSpace: var LogColorSpace, Size: DWORD): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetLogColorSpaceA".} - #function GetLogColorSpaceW(p1: HCOLORSPACE; var ColorSpace: TLogColorSpaceW; Size: DWORD): WINBOOL; stdcall; external 'gdi32' name 'GetLogColorSpaceW'; -proc GetMailslotInfo*(hMailslot: THandle, lpMaxMessageSize: pointer, + #function GetLogColorSpaceW(p1: HCOLORSPACE; var ColorSpace: LogColorSpaceW; Size: DWORD): WINBOOL; stdcall; external 'gdi32' name 'GetLogColorSpaceW'; +proc GetMailslotInfo*(hMailslot: Handle, lpMaxMessageSize: pointer, lpNextSize: var DWORD, lpMessageCount, lpReadTimeout: pointer): WINBOOL{.stdcall, dynlib: "kernel32", importc: "GetMailslotInfo".} #function GetMenuBarInfo(hend: HWND; idObject, idItem: Longint; var pmbi: TMenuBarInfo): WINBOOL;stdcall; external 'user32' name 'GetMenuBarInfo'; #function GetMenuInfo(menu: HMENU; var lpmi: TMenuInfo): WINBOOL;stdcall; external 'user32' name 'GetMenuInfo'; -proc GetMenuItemInfo*(p1: HMENU, p2: WINUINT, p3: WINBOOL, p4: var TMenuItemInfo): WINBOOL{. +proc GetMenuItemInfo*(p1: HMENU, p2: WINUINT, p3: WINBOOL, p4: var MenuItemInfo): WINBOOL{. stdcall, dynlib: "user32", importc: "GetMenuItemInfoA".} -proc GetMenuItemInfoA*(p1: HMENU, p2: WINUINT, p3: WINBOOL, p4: var TMenuItemInfoA): WINBOOL{. +proc GetMenuItemInfoA*(p1: HMENU, p2: WINUINT, p3: WINBOOL, p4: var MenuItemInfo): WINBOOL{. stdcall, dynlib: "user32", importc: "GetMenuItemInfoA".} - #function GetMenuItemInfoW(p1: HMENU; p2: WINUINT; p3: WINBOOL; var p4: TMenuItemInfoW): WINBOOL; stdcall; external 'user32' name 'GetMenuItemInfoW'; -proc GetMenuItemRect*(wnd: HWND, menu: HMENU, uItem: WINUINT, lprcItem: var TRect): WINBOOL{. + #function GetMenuItemInfoW(p1: HMENU; p2: WINUINT; p3: WINBOOL; var p4: MenuItemInfoW): WINBOOL; stdcall; external 'user32' name 'GetMenuItemInfoW'; +proc GetMenuItemRect*(wnd: HWND, menu: HMENU, uItem: WINUINT, lprcItem: var Rect): WINBOOL{. stdcall, dynlib: "user32", importc: "GetMenuItemRect".} proc GetMessage*(lpMsg: var TMsg, wnd: HWND, wMsgFilterMin, wMsgFilterMax: WINUINT): WINBOOL{. stdcall, dynlib: "user32", importc: "GetMessageA".} @@ -21669,17 +21209,17 @@ proc GetMessageW*(lpMsg: var TMsg, wnd: HWND, proc GetMiterLimit*(DC: HDC, Limit: var float32): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetMiterLimit".} #function GetMouseMovePoints(cbSize: WINUINT; var lppt, lpptBuf: TMouseMovePoint; nBufPoints: Integer; resolution: DWORD): Integer;stdcall; external 'user32' name 'GetMouseMovePoints'; -proc GetNamedPipeInfo*(hNamedPipe: THandle, lpFlags: var DWORD, +proc GetNamedPipeInfo*(hNamedPipe: Handle, lpFlags: var DWORD, lpOutBufferSize, lpInBufferSize, lpMaxInstances: pointer): WINBOOL{. stdcall, dynlib: "kernel32", importc: "GetNamedPipeInfo".} -proc GetNumberOfConsoleInputEvents*(hConsoleInput: THandle, +proc GetNumberOfConsoleInputEvents*(hConsoleInput: Handle, lpNumberOfEvents: var DWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "GetNumberOfConsoleInputEvents".} proc GetNumberOfConsoleMouseButtons*(lpNumberOfMouseButtons: var DWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "GetNumberOfConsoleMouseButtons".} - #function GetNumberOfEventLogRecords(hEventLog: THandle; var NumberOfRecords: DWORD): WINBOOL; stdcall; external 'advapi32' name 'GetNumberOfEventLogRecords'; - #function GetOldestEventLogRecord(hEventLog: THandle; var OldestRecord: DWORD): WINBOOL; stdcall; external 'advapi32' name 'GetOldestEventLogRecord'; -proc GetOverlappedResult*(hFile: THandle, lpOverlapped: TOverlapped, + #function GetNumberOfEventLogRecords(hEventLog: Handle; var NumberOfRecords: DWORD): WINBOOL; stdcall; external 'advapi32' name 'GetNumberOfEventLogRecords'; + #function GetOldestEventLogRecord(hEventLog: Handle; var OldestRecord: DWORD): WINBOOL; stdcall; external 'advapi32' name 'GetOldestEventLogRecord'; +proc GetOverlappedResult*(hFile: Handle, lpOverlapped: Overlapped, lpNumberOfBytesTransferred: var DWORD, bWait: WINBOOL): WINBOOL{. stdcall, dynlib: "kernel32", importc: "GetOverlappedResult".} proc GetPaletteEntries*(Palette: HPALETTE, StartIndex, NumEntries: WINUINT, @@ -21709,32 +21249,32 @@ proc GetPrivateProfileStructW*(lpszSection, lpszKey: LPCWSTR, lpStruct: LPVOID, proc GetPrivateProfileStruct*(lpszSection, lpszKey: LPCTSTR, lpStruct: LPVOID, uSizeStruct: WINUINT, szFile: LPCTSTR): WINBOOL{. stdcall, dynlib: "kernel32", importc: "GetPrivateProfileStructA".} -proc GetProcessAffinityMask*(hProcess: THandle, lpProcessAffinityMask, +proc GetProcessAffinityMask*(hProcess: Handle, lpProcessAffinityMask, lpSystemAffinityMask: var DWORD): WINBOOL{.stdcall, dynlib: "kernel32", importc: "GetProcessAffinityMask".} -proc GetProcessHeaps*(NumberOfHeaps: DWORD, ProcessHeaps: var THandle): DWORD{. +proc GetProcessHeaps*(NumberOfHeaps: DWORD, ProcessHeaps: var Handle): DWORD{. stdcall, dynlib: "kernel32", importc: "GetProcessHeaps".} -proc GetProcessPriorityBoost*(hThread: THandle, +proc GetProcessPriorityBoost*(hThread: Handle, DisablePriorityBoost: var WINBOOL): WINBOOL{. stdcall, dynlib: "kernel32", importc: "GetProcessPriorityBoost".} proc GetProcessShutdownParameters*(lpdwLevel, lpdwFlags: var DWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "GetProcessShutdownParameters".} -proc GetProcessTimes*(hProcess: THandle, lpCreationTime, lpExitTime, - lpKernelTime, lpUserTime: var TFileTime): WINBOOL{.stdcall, +proc GetProcessTimes*(hProcess: Handle, lpCreationTime, lpExitTime, + lpKernelTime, lpUserTime: var FileTime): WINBOOL{.stdcall, dynlib: "kernel32", importc: "GetProcessTimes".} -proc GetProcessWorkingSetSize*(hProcess: THandle, lpMinimumWorkingSetSize, +proc GetProcessWorkingSetSize*(hProcess: Handle, lpMinimumWorkingSetSize, lpMaximumWorkingSetSize: var DWORD): WINBOOL{.stdcall, dynlib: "kernel32", importc: "GetProcessWorkingSetSize".} -proc GetQueuedCompletionStatus*(CompletionPort: THandle, +proc GetQueuedCompletionStatus*(CompletionPort: Handle, lpNumberOfBytesTransferred, lpCompletionKey: var DWORD, lpOverlapped: var POverlapped, dwMilliseconds: DWORD): WINBOOL{.stdcall, dynlib: "kernel32", importc: "GetQueuedCompletionStatus".} -proc GetRasterizerCaps*(p1: var TRasterizerStatus, p2: WINUINT): WINBOOL{.stdcall, +proc GetRasterizerCaps*(p1: var RasterizerStatus, p2: WINUINT): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetRasterizerCaps".} -proc GetRgnBox*(RGN: HRGN, p2: var TRect): int{.stdcall, dynlib: "gdi32", +proc GetRgnBox*(RGN: HRGN, p2: var Rect): int{.stdcall, dynlib: "gdi32", importc: "GetRgnBox".} -proc GetScrollInfo*(wnd: HWND, BarFlag: int, ScrollInfo: var TScrollInfo): WINBOOL{. +proc GetScrollInfo*(wnd: HWND, BarFlag: int, ScrollInfo: var ScrollInfo): WINBOOL{. stdcall, dynlib: "user32", importc: "GetScrollInfo".} proc GetScrollRange*(wnd: HWND, nBar: int, lpMinPos, lpMaxPos: var int): WINBOOL{. stdcall, dynlib: "user32", importc: "GetScrollRange".} @@ -21743,7 +21283,7 @@ proc GetScrollRange*(wnd: HWND, nBar: int, lpMinPos, lpMaxPos: var int): WINBOOL #function GetSecurityDescriptorGroup(pSecurityDescriptor: PSecurityDescriptor; var pGroup: PSID; var lpbGroupDefaulted: WINBOOL): WINBOOL; stdcall; external 'advapi32' name 'GetSecurityDescriptorGroup'; #function GetSecurityDescriptorOwner(pSecurityDescriptor: PSecurityDescriptor; var pOwner: PSID; var lpbOwnerDefaulted: WINBOOL): WINBOOL; stdcall; external 'advapi32' name 'GetSecurityDescriptorOwner'; #function GetSecurityDescriptorSacl(pSecurityDescriptor: PSecurityDescriptor; var lpbSaclPresent: WINBOOL; var pSacl: PACL; var lpbSaclDefaulted: WINBOOL): WINBOOL; stdcall; external 'advapi32' name 'GetSecurityDescriptorSacl'; -proc GetStartupInfo*(lpStartupInfo: var TSTARTUPINFO){.stdcall, +proc GetStartupInfo*(lpStartupInfo: var STARTUPINFO){.stdcall, dynlib: "kernel32", importc: "GetStartupInfoA".} proc GetStringTypeA*(Locale: LCID, dwInfoType: DWORD, lpSrcStr: LPCSTR, cchSrc: WINBOOL, lpCharType: var int16): WINBOOL{.stdcall, @@ -21763,12 +21303,12 @@ proc GetStringTypeW*(dwInfoType: DWORD, lpSrcStr: WCHAR, cchSrc: WINBOOL, proc GetSystemPaletteEntries*(DC: HDC, StartIndex, NumEntries: WINUINT, PaletteEntries: pointer): WINUINT{.stdcall, dynlib: "gdi32", importc: "GetSystemPaletteEntries".} -proc GetSystemPowerStatus*(lpSystemPowerStatus: var TSystemPowerStatus): WINBOOL{. +proc GetSystemPowerStatus*(lpSystemPowerStatus: var SystemPowerStatus): WINBOOL{. stdcall, dynlib: "kernel32", importc: "GetSystemPowerStatus".} proc GetSystemTimeAdjustment*(lpTimeAdjustment, lpTimeIncrement: var DWORD, lpTimeAdjustmentDisabled: var WINBOOL): WINBOOL{. stdcall, dynlib: "kernel32", importc: "GetSystemTimeAdjustment".} -proc GetSystemTimeAsFileTime*(lpSystemTimeAsFileTime: var TFILETIME){.stdcall, +proc GetSystemTimeAsFileTime*(lpSystemTimeAsFileTime: var FILETIME){.stdcall, dynlib: "kernel32", importc: "GetSystemTimeAsFileTime".} proc GetTabbedTextExtent*(hDC: HDC, lpString: cstring, nCount, nTabPositions: int, @@ -21782,55 +21322,55 @@ proc GetTabbedTextExtentW*(hDC: HDC, lpString: LPWSTR, nCount, nTabPositions: int, lpnTabStopPositions: pointer): DWORD{.stdcall, dynlib: "user32", importc: "GetTabbedTextExtentW".} -proc GetTapeParameters*(hDevice: THandle, dwOperation: DWORD, +proc GetTapeParameters*(hDevice: Handle, dwOperation: DWORD, lpdwSize: var DWORD, lpTapeInformation: pointer): DWORD{. stdcall, dynlib: "kernel32", importc: "GetTapeParameters".} -proc GetTapePosition*(hDevice: THandle, dwPositionType: DWORD, +proc GetTapePosition*(hDevice: Handle, dwPositionType: DWORD, lpdwPartition, lpdwOffsetLow: var DWORD, lpdwOffsetHigh: pointer): DWORD{.stdcall, dynlib: "kernel32", importc: "GetTapePosition".} proc GetTextExtentExPoint*(DC: HDC, p2: cstring, p3, p4: int, p5, p6: PInteger, - p7: var TSize): WINBOOL{.stdcall, dynlib: "gdi32", + p7: var Size): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetTextExtentExPointA".} proc GetTextExtentExPointA*(DC: HDC, p2: LPCSTR, p3, p4: int, p5, p6: PInteger, - p7: var TSize): WINBOOL{.stdcall, dynlib: "gdi32", + p7: var Size): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetTextExtentExPointA".} - #function GetTextExtentExPointI(DC: HDC; p2: PWORD; p3, p4: Integer; p5, p6: PINT; var p7: TSize): WINBOOL;stdcall; external 'gdi32' name 'GetTextExtentExPointI'; + #function GetTextExtentExPointI(DC: HDC; p2: PWORD; p3, p4: Integer; p5, p6: PINT; var p7: Size): WINBOOL;stdcall; external 'gdi32' name 'GetTextExtentExPointI'; proc GetTextExtentExPointW*(DC: HDC, p2: LPWSTR, p3, p4: int, p5, p6: PInteger, - p7: var TSize): WINBOOL{.stdcall, dynlib: "gdi32", + p7: var Size): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetTextExtentExPointW".} -proc GetTextExtentPoint*(DC: HDC, Str: cstring, Count: int, Size: var TSize): WINBOOL{. +proc GetTextExtentPoint*(DC: HDC, Str: cstring, Count: int, Size: var Size): WINBOOL{. stdcall, dynlib: "gdi32", importc: "GetTextExtentPointA".} -proc GetTextExtentPoint32*(DC: HDC, Str: cstring, Count: int, Size: var TSize): WINBOOL{. +proc GetTextExtentPoint32*(DC: HDC, Str: cstring, Count: int, Size: var Size): WINBOOL{. stdcall, dynlib: "gdi32", importc: "GetTextExtentPoint32A".} -proc GetTextExtentPoint32A*(DC: HDC, Str: LPCSTR, Count: int, Size: var TSize): WINBOOL{. +proc GetTextExtentPoint32A*(DC: HDC, Str: LPCSTR, Count: int, Size: var Size): WINBOOL{. stdcall, dynlib: "gdi32", importc: "GetTextExtentPoint32A".} -proc GetTextExtentPoint32W*(DC: HDC, Str: LPWSTR, Count: int, Size: var TSize): WINBOOL{. +proc GetTextExtentPoint32W*(DC: HDC, Str: LPWSTR, Count: int, Size: var Size): WINBOOL{. stdcall, dynlib: "gdi32", importc: "GetTextExtentPoint32W".} -proc GetTextExtentPointA*(DC: HDC, Str: LPCSTR, Count: int, Size: var TSize): WINBOOL{. +proc GetTextExtentPointA*(DC: HDC, Str: LPCSTR, Count: int, Size: var Size): WINBOOL{. stdcall, dynlib: "gdi32", importc: "GetTextExtentPointA".} - #function GetTextExtentPointI(DC: HDC; p2: PWORD; p3: Integer; var p4: TSize): WINBOOL;stdcall; external 'gdi32' name 'GetTextExtentPointI'; -proc GetTextExtentPointW*(DC: HDC, Str: LPWSTR, Count: int, Size: var TSize): WINBOOL{. + #function GetTextExtentPointI(DC: HDC; p2: PWORD; p3: Integer; var p4: Size): WINBOOL;stdcall; external 'gdi32' name 'GetTextExtentPointI'; +proc GetTextExtentPointW*(DC: HDC, Str: LPWSTR, Count: int, Size: var Size): WINBOOL{. stdcall, dynlib: "gdi32", importc: "GetTextExtentPointW".} -proc GetTextMetrics*(DC: HDC, TM: var TTextMetric): WINBOOL{.stdcall, +proc GetTextMetrics*(DC: HDC, TM: var TextMetric): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetTextMetricsA".} - #function GetTextMetricsA(DC: HDC; var TM: TTextMetricA): WINBOOL; stdcall; external 'gdi32' name 'GetTextMetricsA'; - #function GetTextMetricsW(DC: HDC; var TM: TTextMetricW): WINBOOL; stdcall; external 'gdi32' name 'GetTextMetricsW'; -proc GetThreadContext*(hThread: THandle, lpContext: var TContext): WINBOOL{. + #function GetTextMetricsA(DC: HDC; var TM: TextMetricA): WINBOOL; stdcall; external 'gdi32' name 'GetTextMetricsA'; + #function GetTextMetricsW(DC: HDC; var TM: TextMetricW): WINBOOL; stdcall; external 'gdi32' name 'GetTextMetricsW'; +proc GetThreadContext*(hThread: Handle, lpContext: var Context): WINBOOL{. stdcall, dynlib: "kernel32", importc: "GetThreadContext".} -proc GetThreadPriorityBoost*(hThread: THandle, DisablePriorityBoost: var WINBOOL): WINBOOL{. +proc GetThreadPriorityBoost*(hThread: Handle, DisablePriorityBoost: var WINBOOL): WINBOOL{. stdcall, dynlib: "kernel32", importc: "GetThreadPriorityBoost".} -proc GetThreadSelectorEntry*(hThread: THandle, dwSelector: DWORD, - lpSelectorEntry: var TLDTEntry): WINBOOL{.stdcall, +proc GetThreadSelectorEntry*(hThread: Handle, dwSelector: DWORD, + lpSelectorEntry: var LDTEntry): WINBOOL{.stdcall, dynlib: "kernel32", importc: "GetThreadSelectorEntry".} -proc GetThreadTimes*(hThread: THandle, lpCreationTime, lpExitTime, lpKernelTime, - lpUserTime: var TFileTime): WINBOOL{. +proc GetThreadTimes*(hThread: Handle, lpCreationTime, lpExitTime, lpKernelTime, + lpUserTime: var FileTime): WINBOOL{. stdcall, dynlib: "kernel32", importc: "GetThreadTimes".} -proc GetTimeZoneInformation*(lpTimeZoneInformation: var TTimeZoneInformation): DWORD{. +proc GetTimeZoneInformation*(lpTimeZoneInformation: var TimeZoneInformation): DWORD{. stdcall, dynlib: "kernel32", importc: "GetTimeZoneInformation".} #function GetTitleBarInfo(wnd: HWND; var pti: TTitleBarInfo): WINBOOL;stdcall; external 'user32' name 'GetTitleBarInfo'; - #function GetTokenInformation(TokenHandle: THandle; TokenInformationClass: TTokenInformationClass; TokenInformation: pointer; TokenInformationLength: DWORD; var ReturnLength: DWORD): WINBOOL; stdcall; external 'advapi32' name 'GetTokenInformation'; -proc GetUpdateRect*(wnd: HWND, lpRect: var TRect, bErase: WINBOOL): WINBOOL{. + #function GetTokenInformation(TokenHandle: Handle; TokenInformationClass: TokenInformationClass; TokenInformation: pointer; TokenInformationLength: DWORD; var ReturnLength: DWORD): WINBOOL; stdcall; external 'advapi32' name 'GetTokenInformation'; +proc GetUpdateRect*(wnd: HWND, lpRect: var Rect, bErase: WINBOOL): WINBOOL{. stdcall, dynlib: "user32", importc: "GetUpdateRect".} proc GetUserName*(lpBuffer: cstring, nSize: var DWORD): WINBOOL{.stdcall, dynlib: "advapi32", importc: "GetUserNameA".} @@ -21838,28 +21378,28 @@ proc GetUserNameA*(lpBuffer: LPCSTR, nSize: var DWORD): WINBOOL{.stdcall, dynlib: "advapi32", importc: "GetUserNameA".} proc GetUserNameW*(lpBuffer: LPWSTR, nSize: var DWORD): WINBOOL{.stdcall, dynlib: "advapi32", importc: "GetUserNameW".} -proc GetUserObjectInformation*(hObj: THandle, nIndex: int, pvInfo: pointer, +proc GetUserObjectInformation*(hObj: Handle, nIndex: int, pvInfo: pointer, nLength: DWORD, lpnLengthNeeded: var DWORD): WINBOOL{. stdcall, dynlib: "user32", importc: "GetUserObjectInformationA".} -proc GetUserObjectInformationA*(hObj: THandle, nIndex: int, pvInfo: pointer, +proc GetUserObjectInformationA*(hObj: Handle, nIndex: int, pvInfo: pointer, nLength: DWORD, lpnLengthNeeded: var DWORD): WINBOOL{. stdcall, dynlib: "user32", importc: "GetUserObjectInformationA".} -proc GetUserObjectInformationW*(hObj: THandle, nIndex: int, pvInfo: pointer, +proc GetUserObjectInformationW*(hObj: Handle, nIndex: int, pvInfo: pointer, nLength: DWORD, lpnLengthNeeded: var DWORD): WINBOOL{. stdcall, dynlib: "user32", importc: "GetUserObjectInformationW".} -proc GetUserObjectSecurity*(hObj: THandle, pSIRequested: var DWORD, +proc GetUserObjectSecurity*(hObj: Handle, pSIRequested: var DWORD, pSID: PSecurityDescriptor, nLength: DWORD, lpnLengthNeeded: var DWORD): WINBOOL{.stdcall, dynlib: "user32", importc: "GetUserObjectSecurity".} -proc GetVersionEx*(lpVersionInformation: var TOSVersionInfo): WINBOOL{.stdcall, +proc GetVersionEx*(lpVersionInformation: var OSVersionInfo): WINBOOL{.stdcall, dynlib: "kernel32", importc: "GetVersionExA".} -proc GetVersionExA*(lpVersionInformation: var TOSVersionInfo): WINBOOL{.stdcall, +proc GetVersionExA*(lpVersionInformation: var OSVersionInfo): WINBOOL{.stdcall, dynlib: "kernel32", importc: "GetVersionExA".} -proc GetVersionExW*(lpVersionInformation: var TOSVersionInfoW): WINBOOL{. +proc GetVersionExW*(lpVersionInformation: var OSVersionInfoW): WINBOOL{. stdcall, dynlib: "kernel32", importc: "GetVersionExW".} -proc GetViewportExtEx*(DC: HDC, Size: var TSize): WINBOOL{.stdcall, +proc GetViewportExtEx*(DC: HDC, Size: var Size): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetViewportExtEx".} -proc GetViewportOrgEx*(DC: HDC, Point: var TPoint): WINBOOL{.stdcall, +proc GetViewportOrgEx*(DC: HDC, Point: var Point): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetViewportOrgEx".} proc GetVolumeInformation*(lpRootPathName: cstring, lpVolumeNameBuffer: cstring, nVolumeNameSize: DWORD, lpVolumeSerialNumber: PDWORD, @@ -21881,59 +21421,59 @@ proc GetVolumeInformationW*(lpRootPathName: LPWSTR, lpVolumeNameBuffer: LPWSTR, lpFileSystemNameBuffer: LPWSTR, nFileSystemNameSize: DWORD): WINBOOL{.stdcall, dynlib: "kernel32", importc: "GetVolumeInformationW".} -proc GetWindowExtEx*(DC: HDC, Size: var TSize): WINBOOL{.stdcall, +proc GetWindowExtEx*(DC: HDC, Size: var Size): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetWindowExtEx".} #function GetWindowInfo(wnd: HWND; var pwi: TWindowInfo): WINBOOL;stdcall; external 'user32' name 'GetWindowInfo'; -proc GetWindowOrgEx*(DC: HDC, Point: var TPoint): WINBOOL{.stdcall, +proc GetWindowOrgEx*(DC: HDC, Point: var Point): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetWindowOrgEx".} -proc GetWindowRect*(wnd: HWND, lpRect: var TRect): WINBOOL{.stdcall, +proc GetWindowRect*(wnd: HWND, lpRect: var Rect): WINBOOL{.stdcall, dynlib: "user32", importc: "GetWindowRect".} -proc GetWorldTransform*(DC: HDC, p2: var TXForm): WINBOOL{.stdcall, +proc GetWorldTransform*(DC: HDC, p2: var XForm): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetWorldTransform".} #function GradientFill(DC: HDC; var p2: TTriVertex; p3: ULONG; p4: pointer; p5, p6: ULONG): WINBOOL;stdcall; external 'gdi32' name 'GradientFill'; proc GlobalMemoryStatus*(Buffer: var MEMORYSTATUS){.stdcall, dynlib: "kernel32", importc: "GlobalMemoryStatus".} -proc HeapWalk*(hHeap: THandle, lpEntry: var TProcessHeapEntry): WINBOOL{. +proc HeapWalk*(hHeap: Handle, lpEntry: var ProcessHeapEntry): WINBOOL{. stdcall, dynlib: "kernel32", importc: "HeapWalk".} proc ImageList_GetDragImage*(ppt: var POINT, pptHotspot: var POINT): HIMAGELIST{. stdcall, dynlib: "comctl32", importc: "ImageList_GetDragImage".} -proc InflateRect*(lprc: var TRect, dx, dy: int): WINBOOL{.stdcall, +proc InflateRect*(lprc: var Rect, dx, dy: int): WINBOOL{.stdcall, dynlib: "user32", importc: "InflateRect".} -proc InitializeAcl*(pAcl: var TACL, nAclLength, dwAclRevision: DWORD): WINBOOL{. +proc InitializeAcl*(pAcl: var ACL, nAclLength, dwAclRevision: DWORD): WINBOOL{. stdcall, dynlib: "advapi32", importc: "InitializeAcl".} -proc InitializeSid*(Sid: pointer, pIdentifierAuthority: TSIDIdentifierAuthority, +proc InitializeSid*(Sid: pointer, pIdentifierAuthority: SIDIdentifierAuthority, nSubAuthorityCount: int8): WINBOOL{.stdcall, dynlib: "advapi32", importc: "InitializeSid".} -proc InsertMenuItemA*(p1: HMENU, p2: WINUINT, p3: WINBOOL, p4: TMenuItemInfoA): WINBOOL{. +proc InsertMenuItemA*(p1: HMENU, p2: WINUINT, p3: WINBOOL, p4: MenuItemInfo): WINBOOL{. stdcall, dynlib: "user32", importc: "InsertMenuItemA".} - #function InsertMenuItemW(p1: HMENU; p2: WINUINT; p3: WINBOOL; const p4: TMenuItemInfoW): WINBOOL; stdcall; external 'user32' name 'InsertMenuItemW'; -proc IntersectRect*(lprcDst: var TRect, lprcSrc1, lprcSrc2: TRect): WINBOOL{. + #function InsertMenuItemW(p1: HMENU; p2: WINUINT; p3: WINBOOL; const p4: MenuItemInfoW): WINBOOL; stdcall; external 'user32' name 'InsertMenuItemW'; +proc IntersectRect*(lprcDst: var Rect, lprcSrc1, lprcSrc2: Rect): WINBOOL{. stdcall, dynlib: "user32", importc: "IntersectRect".} - #function InvertRect(hDC: HDC; const lprc: TRect): WINBOOL; stdcall; external 'user32' name 'InvertRect'; + #function InvertRect(hDC: HDC; const lprc: Rect): WINBOOL; stdcall; external 'user32' name 'InvertRect'; proc IsDialogMessage*(hDlg: HWND, lpMsg: var TMsg): WINBOOL{.stdcall, dynlib: "user32", importc: "IsDialogMessageA".} proc IsDialogMessageA*(hDlg: HWND, lpMsg: var TMsg): WINBOOL{.stdcall, dynlib: "user32", importc: "IsDialogMessageA".} proc IsDialogMessageW*(hDlg: HWND, lpMsg: var TMsg): WINBOOL{.stdcall, dynlib: "user32", importc: "IsDialogMessageW".} - #function IsRectEmpty(const lprc: TRect): WINBOOL; stdcall; external 'user32' name 'IsRectEmpty'; -proc IsValidAcl*(pAcl: TACL): WINBOOL{.stdcall, dynlib: "advapi32", + #function IsRectEmpty(const lprc: Rect): WINBOOL; stdcall; external 'user32' name 'IsRectEmpty'; +proc IsValidAcl*(pAcl: ACL): WINBOOL{.stdcall, dynlib: "advapi32", importc: "IsValidAcl".} -proc LocalFileTimeToFileTime*(lpLocalFileTime: TFileTime, - lpFileTime: var TFileTime): WINBOOL{.stdcall, +proc LocalFileTimeToFileTime*(lpLocalFileTime: FileTime, + lpFileTime: var FileTime): WINBOOL{.stdcall, dynlib: "kernel32", importc: "LocalFileTimeToFileTime".} -proc LockFileEx*(hFile: THandle, dwFlags, dwReserved: DWORD, +proc LockFileEx*(hFile: Handle, dwFlags, dwReserved: DWORD, nNumberOfBytesToLockLow, nNumberOfBytesToLockHigh: DWORD, - lpOverlapped: TOverlapped): WINBOOL{.stdcall, + lpOverlapped: Overlapped): WINBOOL{.stdcall, dynlib: "kernel32", importc: "LockFileEx".} proc LogonUser*(lpszUsername, lpszDomain, lpszPassword: cstring, - dwLogonType, dwLogonProvider: DWORD, phToken: var THandle): WINBOOL{. + dwLogonType, dwLogonProvider: DWORD, phToken: var Handle): WINBOOL{. stdcall, dynlib: "advapi32", importc: "LogonUserA".} proc LogonUserA*(lpszUsername, lpszDomain, lpszPassword: LPCSTR, - dwLogonType, dwLogonProvider: DWORD, phToken: var THandle): WINBOOL{. + dwLogonType, dwLogonProvider: DWORD, phToken: var Handle): WINBOOL{. stdcall, dynlib: "advapi32", importc: "LogonUserA".} proc LogonUserW*(lpszUsername, lpszDomain, lpszPassword: LPWSTR, - dwLogonType, dwLogonProvider: DWORD, phToken: var THandle): WINBOOL{. + dwLogonType, dwLogonProvider: DWORD, phToken: var Handle): WINBOOL{. stdcall, dynlib: "advapi32", importc: "LogonUserW".} proc LookupAccountName*(lpSystemName, lpAccountName: cstring, Sid: PSID, cbSid: var DWORD, ReferencedDomainName: cstring, @@ -21977,30 +21517,30 @@ proc LookupPrivilegeDisplayNameW*(lpSystemName, lpName: LPCSTR, lpDisplayName: LPWSTR, cbDisplayName, lpLanguageId: var DWORD): WINBOOL{. stdcall, dynlib: "advapi32", importc: "LookupPrivilegeDisplayNameW".} -proc LookupPrivilegeName*(lpSystemName: cstring, lpLuid: var TLargeInteger, +proc LookupPrivilegeName*(lpSystemName: cstring, lpLuid: var LargeInteger, lpName: cstring, cbName: var DWORD): WINBOOL{.stdcall, dynlib: "advapi32", importc: "LookupPrivilegeNameA".} -proc LookupPrivilegeNameA*(lpSystemName: LPCSTR, lpLuid: var TLargeInteger, +proc LookupPrivilegeNameA*(lpSystemName: LPCSTR, lpLuid: var LargeInteger, lpName: LPCSTR, cbName: var DWORD): WINBOOL{.stdcall, dynlib: "advapi32", importc: "LookupPrivilegeNameA".} -proc LookupPrivilegeNameW*(lpSystemName: LPWSTR, lpLuid: var TLargeInteger, +proc LookupPrivilegeNameW*(lpSystemName: LPWSTR, lpLuid: var LargeInteger, lpName: LPWSTR, cbName: var DWORD): WINBOOL{.stdcall, dynlib: "advapi32", importc: "LookupPrivilegeNameW".} proc LookupPrivilegeValue*(lpSystemName, lpName: cstring, - lpLuid: var TLargeInteger): WINBOOL{.stdcall, + lpLuid: var LargeInteger): WINBOOL{.stdcall, dynlib: "advapi32", importc: "LookupPrivilegeValueA".} proc LookupPrivilegeValueA*(lpSystemName, lpName: LPCSTR, - lpLuid: var TLargeInteger): WINBOOL{.stdcall, + lpLuid: var LargeInteger): WINBOOL{.stdcall, dynlib: "advapi32", importc: "LookupPrivilegeValueA".} proc LookupPrivilegeValueW*(lpSystemName, lpName: LPWSTR, - lpLuid: var TLargeInteger): WINBOOL{.stdcall, + lpLuid: var LargeInteger): WINBOOL{.stdcall, dynlib: "advapi32", importc: "LookupPrivilegeValueW".} proc LPtoDP*(DC: HDC, Points: pointer, Count: int): WINBOOL{.stdcall, dynlib: "gdi32", importc: "LPtoDP".} proc MakeAbsoluteSD*(pSelfRelativeSecurityDescriptor: PSecurityDescriptor, pAbsoluteSecurityDescriptor: PSecurityDescriptor, lpdwAbsoluteSecurityDescriptorSi: var DWORD, - pDacl: var TACL, lpdwDaclSize: var DWORD, pSacl: var TACL, + pDacl: var ACL, lpdwDaclSize: var DWORD, pSacl: var ACL, lpdwSaclSize: var DWORD, pOwner: PSID, lpdwOwnerSize: var DWORD, pPrimaryGroup: pointer, @@ -22010,16 +21550,16 @@ proc MakeSelfRelativeSD*(pAbsoluteSecurityDescriptor: PSecurityDescriptor, pSelfRelativeSecurityDescriptor: PSecurityDescriptor, lpdwBufferLength: var DWORD): WINBOOL{.stdcall, dynlib: "advapi32", importc: "MakeSelfRelativeSD".} -proc MapDialogRect*(hDlg: HWND, lpRect: var TRect): WINBOOL{.stdcall, +proc MapDialogRect*(hDlg: HWND, lpRect: var Rect): WINBOOL{.stdcall, dynlib: "user32", importc: "MapDialogRect".} proc MapWindowPoints*(hWndFrom, hWndTo: HWND, lpPoints: pointer, cPoints: WINUINT): int{. stdcall, dynlib: "user32", importc: "MapWindowPoints".} -proc MessageBoxIndirect*(MsgBoxParams: TMsgBoxParams): WINBOOL{.stdcall, +proc MessageBoxIndirect*(MsgBoxParams: MsgBoxParams): WINBOOL{.stdcall, dynlib: "user32", importc: "MessageBoxIndirectA".} -proc MessageBoxIndirectA*(MsgBoxParams: TMsgBoxParamsA): WINBOOL{.stdcall, +proc MessageBoxIndirectA*(MsgBoxParams: MsgBoxParams): WINBOOL{.stdcall, dynlib: "user32", importc: "MessageBoxIndirectA".} - #function MessageBoxIndirectW(const MsgBoxParams: TMsgBoxParamsW): WINBOOL; stdcall; external 'user32' name 'MessageBoxIndirectW'; - #function ModifyWorldTransform(DC: HDC; const p2: TXForm; p3: DWORD): WINBOOL; stdcall; external 'gdi32' name 'ModifyWorldTransform'; + #function MessageBoxIndirectW(const MsgBoxParams: MsgBoxParamsW): WINBOOL; stdcall; external 'user32' name 'MessageBoxIndirectW'; + #function ModifyWorldTransform(DC: HDC; const p2: XForm; p3: DWORD): WINBOOL; stdcall; external 'gdi32' name 'ModifyWorldTransform'; proc MsgWaitForMultipleObjects*(nCount: DWORD, pHandles: pointer, fWaitAll: WINBOOL, dwMilliseconds, dwWakeMask: DWORD): DWORD{. @@ -22031,66 +21571,66 @@ proc MsgWaitForMultipleObjectsEx*(nCount: DWORD, pHandles: pointer, proc ObjectOpenAuditAlarm*(SubsystemName: cstring, HandleId: pointer, ObjectTypeName: cstring, ObjectName: cstring, pSecurityDescriptor: PSecurityDescriptor, - ClientToken: THandle, + ClientToken: Handle, DesiredAccess, GrantedAccess: DWORD, - Privileges: var TPrivilegeSet, + Privileges: var PrivilegeSet, ObjectCreation, AccessGranted: WINBOOL, GenerateOnClose: var WINBOOL): WINBOOL{.stdcall, dynlib: "advapi32", importc: "ObjectOpenAuditAlarmA".} proc ObjectOpenAuditAlarmA*(SubsystemName: LPCSTR, HandleId: pointer, ObjectTypeName: LPCSTR, ObjectName: LPCSTR, pSecurityDescriptor: PSecurityDescriptor, - ClientToken: THandle, + ClientToken: Handle, DesiredAccess, GrantedAccess: DWORD, - Privileges: var TPrivilegeSet, + Privileges: var PrivilegeSet, ObjectCreation, AccessGranted: WINBOOL, GenerateOnClose: var WINBOOL): WINBOOL{.stdcall, dynlib: "advapi32", importc: "ObjectOpenAuditAlarmA".} proc ObjectOpenAuditAlarmW*(SubsystemName: LPWSTR, HandleId: pointer, ObjectTypeName: LPWSTR, ObjectName: LPWSTR, pSecurityDescriptor: PSecurityDescriptor, - ClientToken: THandle, + ClientToken: Handle, DesiredAccess, GrantedAccess: DWORD, - Privileges: var TPrivilegeSet, + Privileges: var PrivilegeSet, ObjectCreation, AccessGranted: WINBOOL, GenerateOnClose: var WINBOOL): WINBOOL{.stdcall, dynlib: "advapi32", importc: "ObjectOpenAuditAlarmW".} proc ObjectPrivilegeAuditAlarm*(SubsystemName: cstring, HandleId: pointer, - ClientToken: THandle, DesiredAccess: DWORD, - Privileges: var TPrivilegeSet, + ClientToken: Handle, DesiredAccess: DWORD, + Privileges: var PrivilegeSet, AccessGranted: WINBOOL): WINBOOL{.stdcall, dynlib: "advapi32", importc: "ObjectPrivilegeAuditAlarmA".} proc ObjectPrivilegeAuditAlarmA*(SubsystemName: LPCSTR, HandleId: pointer, - ClientToken: THandle, DesiredAccess: DWORD, - Privileges: var TPrivilegeSet, + ClientToken: Handle, DesiredAccess: DWORD, + Privileges: var PrivilegeSet, AccessGranted: WINBOOL): WINBOOL{.stdcall, dynlib: "advapi32", importc: "ObjectPrivilegeAuditAlarmA".} proc ObjectPrivilegeAuditAlarmW*(SubsystemName: LPWSTR, HandleId: pointer, - ClientToken: THandle, DesiredAccess: DWORD, - Privileges: var TPrivilegeSet, + ClientToken: Handle, DesiredAccess: DWORD, + Privileges: var PrivilegeSet, AccessGranted: WINBOOL): WINBOOL{.stdcall, dynlib: "advapi32", importc: "ObjectPrivilegeAuditAlarmW".} -proc OffsetRect*(lprc: var TRect, dx, dy: int): WINBOOL{.stdcall, +proc OffsetRect*(lprc: var Rect, dx, dy: int): WINBOOL{.stdcall, dynlib: "user32", importc: "OffsetRect".} proc OffsetViewportOrgEx*(DC: HDC, X, Y: int, Points: pointer): WINBOOL{. stdcall, dynlib: "gdi32", importc: "OffsetViewportOrgEx".} proc OffsetWindowOrgEx*(DC: HDC, X, Y: int, Points: pointer): WINBOOL{.stdcall, dynlib: "gdi32", importc: "OffsetWindowOrgEx".} -proc OpenFile*(lpFileName: LPCSTR, lpReOpenBuff: var TOFStruct, uStyle: WINUINT): HFILE{. +proc OpenFile*(lpFileName: LPCSTR, lpReOpenBuff: var OFStruct, uStyle: WINUINT): HFILE{. stdcall, dynlib: "kernel32", importc: "OpenFile".} -proc OpenProcessToken*(ProcessHandle: THandle, DesiredAccess: DWORD, - TokenHandle: var THandle): WINBOOL{.stdcall, +proc OpenProcessToken*(ProcessHandle: Handle, DesiredAccess: DWORD, + TokenHandle: var Handle): WINBOOL{.stdcall, dynlib: "advapi32", importc: "OpenProcessToken".} -proc OpenThreadToken*(ThreadHandle: THandle, DesiredAccess: DWORD, - OpenAsSelf: WINBOOL, TokenHandle: var THandle): WINBOOL{. +proc OpenThreadToken*(ThreadHandle: Handle, DesiredAccess: DWORD, + OpenAsSelf: WINBOOL, TokenHandle: var Handle): WINBOOL{. stdcall, dynlib: "advapi32", importc: "OpenThreadToken".} -proc PeekConsoleInput*(hConsoleInput: THandle, lpBuffer: var TInputRecord, +proc PeekConsoleInput*(hConsoleInput: Handle, lpBuffer: var InputRecord, nLength: DWORD, lpNumberOfEventsRead: var DWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "PeekConsoleInputA".} -proc PeekConsoleInputA*(hConsoleInput: THandle, lpBuffer: var TInputRecord, +proc PeekConsoleInputA*(hConsoleInput: Handle, lpBuffer: var InputRecord, nLength: DWORD, lpNumberOfEventsRead: var DWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "PeekConsoleInputA".} -proc PeekConsoleInputW*(hConsoleInput: THandle, lpBuffer: var TInputRecord, +proc PeekConsoleInputW*(hConsoleInput: Handle, lpBuffer: var InputRecord, nLength: DWORD, lpNumberOfEventsRead: var DWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "PeekConsoleInputW".} proc PeekMessage*(lpMsg: var TMsg, wnd: HWND, @@ -22102,11 +21642,11 @@ proc PeekMessageA*(lpMsg: var TMsg, wnd: HWND, proc PeekMessageW*(lpMsg: var TMsg, wnd: HWND, wMsgFilterMin, wMsgFilterMax, wRemoveMsg: WINUINT): WINBOOL{. stdcall, dynlib: "user32", importc: "PeekMessageW".} - #function PlayEnhMetaFile(DC: HDC; p2: HENHMETAFILE; const p3: TRect): WINBOOL; stdcall; external 'gdi32' name 'PlayEnhMetaFile'; -proc PlayEnhMetaFileRecord*(DC: HDC, p2: var THandleTable, p3: TEnhMetaRecord, + #function PlayEnhMetaFile(DC: HDC; p2: HENHMETAFILE; const p3: Rect): WINBOOL; stdcall; external 'gdi32' name 'PlayEnhMetaFile'; +proc PlayEnhMetaFileRecord*(DC: HDC, p2: var HandleTable, p3: EnhMetaRecord, p4: WINUINT): WINBOOL{.stdcall, dynlib: "gdi32", importc: "PlayEnhMetaFileRecord".} -proc PlayMetaFileRecord*(DC: HDC, p2: THandleTable, p3: TMetaRecord, p4: WINUINT): WINBOOL{. +proc PlayMetaFileRecord*(DC: HDC, p2: HandleTable, p3: MetaRecord, p4: WINUINT): WINBOOL{. stdcall, dynlib: "gdi32", importc: "PlayMetaFileRecord".} proc PlgBlt*(DC: HDC, PointsArray: pointer, p3: HDC, p4, p5, p6, p7: int, p8: HBITMAP, p9, p10: int): WINBOOL{.stdcall, dynlib: "gdi32", @@ -22133,28 +21673,28 @@ proc PolyTextOutA*(DC: HDC, PolyTextArray: pointer, Strings: int): WINBOOL{. stdcall, dynlib: "gdi32", importc: "PolyTextOutA".} proc PolyTextOutW*(DC: HDC, PolyTextArray: pointer, Strings: int): WINBOOL{. stdcall, dynlib: "gdi32", importc: "PolyTextOutW".} -proc PrivilegeCheck*(ClientToken: THandle, RequiredPrivileges: TPrivilegeSet, +proc PrivilegeCheck*(ClientToken: Handle, RequiredPrivileges: PrivilegeSet, pfResult: var WINBOOL): WINBOOL{.stdcall, dynlib: "advapi32", importc: "PrivilegeCheck".} proc PrivilegedServiceAuditAlarm*(SubsystemName, ServiceName: cstring, - ClientToken: THandle, - Privileges: var TPrivilegeSet, + ClientToken: Handle, + Privileges: var PrivilegeSet, AccessGranted: WINBOOL): WINBOOL{.stdcall, dynlib: "advapi32", importc: "PrivilegedServiceAuditAlarmA".} proc PrivilegedServiceAuditAlarmA*(SubsystemName, ServiceName: LPCSTR, - ClientToken: THandle, - Privileges: var TPrivilegeSet, + ClientToken: Handle, + Privileges: var PrivilegeSet, AccessGranted: WINBOOL): WINBOOL{.stdcall, dynlib: "advapi32", importc: "PrivilegedServiceAuditAlarmA".} proc PrivilegedServiceAuditAlarmW*(SubsystemName, ServiceName: LPWSTR, - ClientToken: THandle, - Privileges: var TPrivilegeSet, + ClientToken: Handle, + Privileges: var PrivilegeSet, AccessGranted: WINBOOL): WINBOOL{.stdcall, dynlib: "advapi32", importc: "PrivilegedServiceAuditAlarmW".} - #function PtInRect(const lprc: TRect; pt: TPoint): WINBOOL; stdcall; external 'user32' name 'PtInRect'; -proc QueryPerformanceCounter*(lpPerformanceCount: var TLargeInteger): WINBOOL{. + #function PtInRect(const lprc: Rect; pt: Point): WINBOOL; stdcall; external 'user32' name 'PtInRect'; +proc QueryPerformanceCounter*(lpPerformanceCount: var LargeInteger): WINBOOL{. stdcall, dynlib: "kernel32", importc: "QueryPerformanceCounter".} -proc QueryPerformanceFrequency*(lpFrequency: var TLargeInteger): WINBOOL{. +proc QueryPerformanceFrequency*(lpFrequency: var LargeInteger): WINBOOL{. stdcall, dynlib: "kernel32", importc: "QueryPerformanceFrequency".} #function QueryRecoveryAgents(p1: PChar; var p2: pointer; var p3: TRecoveryAgentInformation): DWORD;stdcall; external 'kernel32' name 'QueryRecoveryAgentsA'; #function QueryRecoveryAgentsA(p1: LPCSTR; var p2: pointer; var p3: TRecoveryAgentInformationA): DWORD;stdcall; external 'kernel32' name 'QueryRecoveryAgentsA'; @@ -22164,76 +21704,76 @@ proc RaiseException*(dwExceptionCode: DWORD, dwExceptionFlags: DWORD, stdcall, dynlib: "kernel32", importc: "RaiseException".} proc UnhandledExceptionFilter*(ExceptionInfo: var emptyrecord): LONG{.stdcall, dynlib: "kernel32", importc: "UnhandledExceptionFilter".} -proc ReadConsole*(hConsoleInput: THandle, lpBuffer: pointer, +proc ReadConsole*(hConsoleInput: Handle, lpBuffer: pointer, nNumberOfCharsToRead: DWORD, lpNumberOfCharsRead: var DWORD, lpReserved: pointer): WINBOOL{.stdcall, dynlib: "kernel32", importc: "ReadConsoleA".} -proc ReadConsoleA*(hConsoleInput: THandle, lpBuffer: pointer, +proc ReadConsoleA*(hConsoleInput: Handle, lpBuffer: pointer, nNumberOfCharsToRead: DWORD, lpNumberOfCharsRead: var DWORD, lpReserved: pointer): WINBOOL{.stdcall, dynlib: "kernel32", importc: "ReadConsoleA".} -proc ReadConsoleInput*(hConsoleInput: THandle, lpBuffer: var TInputRecord, +proc ReadConsoleInput*(hConsoleInput: Handle, lpBuffer: var InputRecord, nLength: DWORD, lpNumberOfEventsRead: var DWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "ReadConsoleInputA".} -proc ReadConsoleInputA*(hConsoleInput: THandle, lpBuffer: var TInputRecord, +proc ReadConsoleInputA*(hConsoleInput: Handle, lpBuffer: var InputRecord, nLength: DWORD, lpNumberOfEventsRead: var DWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "ReadConsoleInputA".} -proc ReadConsoleInputW*(hConsoleInput: THandle, lpBuffer: var TInputRecord, +proc ReadConsoleInputW*(hConsoleInput: Handle, lpBuffer: var InputRecord, nLength: DWORD, lpNumberOfEventsRead: var DWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "ReadConsoleInputW".} -proc ReadConsoleOutput*(hConsoleOutput: THandle, lpBuffer: pointer, - dwBufferSize, dwBufferCoord: TCoord, - lpReadRegion: var TSmallRect): WINBOOL{.stdcall, +proc ReadConsoleOutput*(hConsoleOutput: Handle, lpBuffer: pointer, + dwBufferSize, dwBufferCoord: Coord, + lpReadRegion: var SmallRect): WINBOOL{.stdcall, dynlib: "kernel32", importc: "ReadConsoleOutputA".} -proc ReadConsoleOutputA*(hConsoleOutput: THandle, lpBuffer: pointer, - dwBufferSize, dwBufferCoord: TCoord, - lpReadRegion: var TSmallRect): WINBOOL{.stdcall, +proc ReadConsoleOutputA*(hConsoleOutput: Handle, lpBuffer: pointer, + dwBufferSize, dwBufferCoord: Coord, + lpReadRegion: var SmallRect): WINBOOL{.stdcall, dynlib: "kernel32", importc: "ReadConsoleOutputA".} -proc ReadConsoleOutputAttribute*(hConsoleOutput: THandle, lpAttribute: pointer, - nLength: DWORD, dwReadCoord: TCoord, +proc ReadConsoleOutputAttribute*(hConsoleOutput: Handle, lpAttribute: pointer, + nLength: DWORD, dwReadCoord: Coord, lpNumberOfAttrsRead: var DWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "ReadConsoleOutputAttribute".} -proc ReadConsoleOutputCharacter*(hConsoleOutput: THandle, lpCharacter: LPCSTR, - nLength: DWORD, dwReadCoord: TCoord, +proc ReadConsoleOutputCharacter*(hConsoleOutput: Handle, lpCharacter: LPCSTR, + nLength: DWORD, dwReadCoord: Coord, lpNumberOfCharsRead: var DWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "ReadConsoleOutputCharacterA".} -proc ReadConsoleOutputCharacterA*(hConsoleOutput: THandle, lpCharacter: LPCSTR, - nLength: DWORD, dwReadCoord: TCoord, +proc ReadConsoleOutputCharacterA*(hConsoleOutput: Handle, lpCharacter: LPCSTR, + nLength: DWORD, dwReadCoord: Coord, lpNumberOfCharsRead: var DWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "ReadConsoleOutputCharacterA".} -proc ReadConsoleOutputCharacterW*(hConsoleOutput: THandle, lpCharacter: LPCSTR, - nLength: DWORD, dwReadCoord: TCoord, +proc ReadConsoleOutputCharacterW*(hConsoleOutput: Handle, lpCharacter: LPCSTR, + nLength: DWORD, dwReadCoord: Coord, lpNumberOfCharsRead: var DWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "ReadConsoleOutputCharacterW".} -proc ReadConsoleOutputW*(hConsoleOutput: THandle, lpBuffer: pointer, - dwBufferSize, dwBufferCoord: TCoord, - lpReadRegion: var TSmallRect): WINBOOL{.stdcall, +proc ReadConsoleOutputW*(hConsoleOutput: Handle, lpBuffer: pointer, + dwBufferSize, dwBufferCoord: Coord, + lpReadRegion: var SmallRect): WINBOOL{.stdcall, dynlib: "kernel32", importc: "ReadConsoleOutputW".} -proc ReadConsoleW*(hConsoleInput: THandle, lpBuffer: pointer, +proc ReadConsoleW*(hConsoleInput: Handle, lpBuffer: pointer, nNumberOfCharsToRead: DWORD, lpNumberOfCharsRead: var DWORD, lpReserved: pointer): WINBOOL{.stdcall, dynlib: "kernel32", importc: "ReadConsoleW".} -proc ReadEventLog*(hEventLog: THandle, dwReadFlags, dwRecordOffset: DWORD, +proc ReadEventLog*(hEventLog: Handle, dwReadFlags, dwRecordOffset: DWORD, lpBuffer: pointer, nNumberOfBytesToRead: DWORD, pnBytesRead, pnMinNumberOfBytesNeeded: var DWORD): WINBOOL{. stdcall, dynlib: "advapi32", importc: "ReadEventLogA".} -proc ReadEventLogA*(hEventLog: THandle, dwReadFlags, dwRecordOffset: DWORD, +proc ReadEventLogA*(hEventLog: Handle, dwReadFlags, dwRecordOffset: DWORD, lpBuffer: pointer, nNumberOfBytesToRead: DWORD, pnBytesRead, pnMinNumberOfBytesNeeded: var DWORD): WINBOOL{. stdcall, dynlib: "advapi32", importc: "ReadEventLogA".} -proc ReadEventLogW*(hEventLog: THandle, dwReadFlags, dwRecordOffset: DWORD, +proc ReadEventLogW*(hEventLog: Handle, dwReadFlags, dwRecordOffset: DWORD, lpBuffer: pointer, nNumberOfBytesToRead: DWORD, pnBytesRead, pnMinNumberOfBytesNeeded: var DWORD): WINBOOL{. stdcall, dynlib: "advapi32", importc: "ReadEventLogW".} -proc ReadFile*(hFile: THandle, Buffer: pointer, nNumberOfBytesToRead: DWORD, +proc ReadFile*(hFile: Handle, Buffer: pointer, nNumberOfBytesToRead: DWORD, lpNumberOfBytesRead: var DWORD, lpOverlapped: POverlapped): WINBOOL{. stdcall, dynlib: "kernel32", importc: "ReadFile".} -proc ReadProcessMemory*(hProcess: THandle, lpBaseAddress: pointer, +proc ReadProcessMemory*(hProcess: Handle, lpBaseAddress: pointer, lpBuffer: pointer, nSize: DWORD, lpNumberOfBytesRead: var DWORD): WINBOOL{.stdcall, dynlib: "kernel32", importc: "ReadProcessMemory".} - #function RectInRegion(RGN: HRGN; const p2: TRect): WINBOOL; stdcall; external 'gdi32' name 'RectInRegion'; - #function RectVisible(DC: HDC; const Rect: TRect): WINBOOL; stdcall; external 'gdi32' name 'RectVisible'; + #function RectInRegion(RGN: HRGN; const p2: Rect): WINBOOL; stdcall; external 'gdi32' name 'RectInRegion'; + #function RectVisible(DC: HDC; const Rect: Rect): WINBOOL; stdcall; external 'gdi32' name 'RectVisible'; proc RegConnectRegistry*(lpMachineName: cstring, key: HKEY, phkResult: var HKEY): int32{. stdcall, dynlib: "advapi32", importc: "RegConnectRegistryA".} proc RegConnectRegistryA*(lpMachineName: LPCSTR, key: HKEY, phkResult: var HKEY): int32{. @@ -22298,17 +21838,17 @@ proc RegSetValueExA*(key: HKEY, lpValueName: LPCSTR, Reserved: DWORD, proc RegSetValueExW*(key: HKEY, lpValueName: LPCWSTR, Reserved: DWORD, dwType: DWORD, lpData: pointer, cbData: DWORD): LONG{. stdcall, dynlib: "advapi32", importc: "RegSetValueExW".} -proc RegisterClass*(lpWndClass: TWndClass): ATOM{.stdcall, dynlib: "user32", +proc RegisterClass*(lpWndClass: WndClass): ATOM{.stdcall, dynlib: "user32", importc: "RegisterClassA".} -proc RegisterClassA*(lpWndClass: TWndClassA): ATOM{.stdcall, dynlib: "user32", +proc RegisterClassA*(lpWndClass: WndClass): ATOM{.stdcall, dynlib: "user32", importc: "RegisterClassA".} -proc RegisterClassEx*(WndClass: TWndClassEx): ATOM{.stdcall, dynlib: "user32", +proc RegisterClassEx*(WndClass: WndClassEx): ATOM{.stdcall, dynlib: "user32", importc: "RegisterClassExA".} -proc RegisterClassExA*(WndClass: TWndClassExA): ATOM{.stdcall, dynlib: "user32", +proc RegisterClassExA*(WndClass: WndClassEx): ATOM{.stdcall, dynlib: "user32", importc: "RegisterClassExA".} -proc RegisterClassExW*(WndClass: TWndClassExW): ATOM{.stdcall, dynlib: "user32", +proc RegisterClassExW*(WndClass: WndClassExW): ATOM{.stdcall, dynlib: "user32", importc: "RegisterClassExW".} -proc RegisterClassW*(lpWndClass: TWndClassW): ATOM{.stdcall, dynlib: "user32", +proc RegisterClassW*(lpWndClass: WndClassW): ATOM{.stdcall, dynlib: "user32", importc: "RegisterClassW".} proc RegOpenKey*(key: HKEY, lpSubKey: cstring, phkResult: var HKEY): int32{. stdcall, dynlib: "advapi32", importc: "RegOpenKeyA".} @@ -22343,30 +21883,30 @@ proc RegQueryValueA*(key: HKEY, lpSubKey: LPCSTR, lpValue: LPCSTR, proc RegQueryValueW*(key: HKEY, lpSubKey: LPWSTR, lpValue: LPWSTR, lpcbValue: var int32): int32{.stdcall, dynlib: "advapi32", importc: "RegQueryValueW".} -proc ResetDC*(DC: HDC, p2: TDeviceMode): HDC{.stdcall, dynlib: "gdi32", +proc ResetDC*(DC: HDC, p2: DevMode): HDC{.stdcall, dynlib: "gdi32", importc: "ResetDCA".} -proc ResetDCA*(DC: HDC, p2: TDeviceModeA): HDC{.stdcall, dynlib: "gdi32", +proc ResetDCA*(DC: HDC, p2: DevMode): HDC{.stdcall, dynlib: "gdi32", importc: "ResetDCA".} - #function ResetDCW(DC: HDC; const p2: TDeviceModeW): HDC; stdcall; external 'gdi32' name 'ResetDCW'; -proc ScreenToClient*(wnd: HWND, lpPoint: var TPoint): WINBOOL{.stdcall, + #function ResetDCW(DC: HDC; const p2: DevModeW): HDC; stdcall; external 'gdi32' name 'ResetDCW'; +proc ScreenToClient*(wnd: HWND, lpPoint: var Point): WINBOOL{.stdcall, dynlib: "user32", importc: "ScreenToClient".} -proc ScrollConsoleScreenBuffer*(hConsoleOutput: THandle, - lpScrollRectangle: TSmallRect, - lpClipRectangle: TSmallRect, - dwDestinationOrigin: TCoord, - lpFill: var TCharInfo): WINBOOL{.stdcall, +proc ScrollConsoleScreenBuffer*(hConsoleOutput: Handle, + lpScrollRectangle: SmallRect, + lpClipRectangle: SmallRect, + dwDestinationOrigin: Coord, + lpFill: var CharInfo): WINBOOL{.stdcall, dynlib: "kernel32", importc: "ScrollConsoleScreenBufferA".} -proc ScrollConsoleScreenBufferA*(hConsoleOutput: THandle, - lpScrollRectangle: TSmallRect, - lpClipRectangle: TSmallRect, - dwDestinationOrigin: TCoord, - lpFill: var TCharInfo): WINBOOL{.stdcall, +proc ScrollConsoleScreenBufferA*(hConsoleOutput: Handle, + lpScrollRectangle: SmallRect, + lpClipRectangle: SmallRect, + dwDestinationOrigin: Coord, + lpFill: var CharInfo): WINBOOL{.stdcall, dynlib: "kernel32", importc: "ScrollConsoleScreenBufferA".} -proc ScrollConsoleScreenBufferW*(hConsoleOutput: THandle, - lpScrollRectangle: TSmallRect, - lpClipRectangle: TSmallRect, - dwDestinationOrigin: TCoord, - lpFill: var TCharInfo): WINBOOL{.stdcall, +proc ScrollConsoleScreenBufferW*(hConsoleOutput: Handle, + lpScrollRectangle: SmallRect, + lpClipRectangle: SmallRect, + dwDestinationOrigin: Coord, + lpFill: var CharInfo): WINBOOL{.stdcall, dynlib: "kernel32", importc: "ScrollConsoleScreenBufferW".} proc ScrollWindow*(wnd: HWND, XAmount: int32, YAmount: int32, rect: LPRECT, lpClipRect: LPRECT): WINBOOL{.stdcall, dynlib: "user32", @@ -22375,7 +21915,7 @@ proc ScrollWindowEx*(wnd: HWND, dx: int32, dy: int32, prcScroll: LPRECT, prcClip: LPRECT, hrgnUpdate: HRGN, prcUpdate: LPRECT, flags: WINUINT): int32{.stdcall, dynlib: "user32", importc: "ScrollWindowEx".} - #function ScrollDC(DC: HDC; DX, DY: Integer; var Scroll, Clip: TRect; Rgn: HRGN; Update: PRect): WINBOOL; stdcall; external 'user32' name 'ScrollDC'; + #function ScrollDC(DC: HDC; DX, DY: Integer; var Scroll, Clip: Rect; Rgn: HRGN; Update: PRect): WINBOOL; stdcall; external 'user32' name 'ScrollDC'; #function SearchPath(lpPath, lpFileName, lpExtension: PChar; nBufferLength: DWORD; lpBuffer: PChar; var lpFilePart: PChar): DWORD;stdcall; external 'kernel32' name 'SearchPathA'; #function SearchPathA(lpPath, lpFileName, lpExtension: LPCSTR; nBufferLength: DWORD; lpBuffer: LPCSTR; var lpFilePart: LPCSTR): DWORD; stdcall; external 'kernel32' name 'SearchPathA'; #function SearchPathW(lpPath, lpFileName, lpExtension: LPWSTR; nBufferLength: DWORD; lpBuffer: LPWSTR; var lpFilePart: LPWSTR): DWORD; stdcall; external 'kernel32' name 'SearchPathW'; @@ -22389,84 +21929,84 @@ proc SendMessageTimeoutA*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM, proc SendMessageTimeoutW*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM, fuFlags, uTimeout: WINUINT, lpdwResult: var DWORD): LRESULT{. stdcall, dynlib: "user32", importc: "SendMessageTimeoutW".} - #function SetAclInformation(var pAcl: TACL; pAclInformation: pointer; nAclInformationLength: DWORD; dwAclInformationClass: TAclInformationClass): WINBOOL; stdcall; external 'advapi32' name 'SetAclInformation'; - #function SetColorAdjustment(DC: HDC; const p2: TColorAdjustment): WINBOOL; stdcall; external 'gdi32' name 'SetColorAdjustment'; -proc SetCommConfig*(hCommDev: THandle, lpCC: TCommConfig, dwSize: DWORD): WINBOOL{. + #function SetAclInformation(var pAcl: ACL; pAclInformation: pointer; nAclInformationLength: DWORD; dwAclInformationClass: AclInformationClass): WINBOOL; stdcall; external 'advapi32' name 'SetAclInformation'; + #function SetColorAdjustment(DC: HDC; const p2: ColorAdjustment): WINBOOL; stdcall; external 'gdi32' name 'SetColorAdjustment'; +proc SetCommConfig*(hCommDev: Handle, lpCC: CommConfig, dwSize: DWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "SetCommConfig".} -proc SetCommState*(hFile: THandle, lpDCB: TDCB): WINBOOL{.stdcall, +proc SetCommState*(hFile: Handle, lpDCB: DCB): WINBOOL{.stdcall, dynlib: "kernel32", importc: "SetCommState".} -proc SetCommTimeouts*(hFile: THandle, lpCommTimeouts: TCommTimeouts): WINBOOL{. +proc SetCommTimeouts*(hFile: Handle, lpCommTimeouts: CommTimeouts): WINBOOL{. stdcall, dynlib: "kernel32", importc: "SetCommTimeouts".} -proc SetConsoleCursorInfo*(hConsoleOutput: THandle, - lpConsoleCursorInfo: TConsoleCursorInfo): WINBOOL{. +proc SetConsoleCursorInfo*(hConsoleOutput: Handle, + lpConsoleCursorInfo: ConsoleCursorInfo): WINBOOL{. stdcall, dynlib: "kernel32", importc: "SetConsoleCursorInfo".} - #function SetConsoleWindowInfo(hConsoleOutput: THandle; bAbsolute: WINBOOL; const lpConsoleWindow: TSmallRect): WINBOOL; stdcall; external 'kernel32' name 'SetConsoleWindowInfo'; + #function SetConsoleWindowInfo(hConsoleOutput: Handle; bAbsolute: WINBOOL; const lpConsoleWindow: SmallRect): WINBOOL; stdcall; external 'kernel32' name 'SetConsoleWindowInfo'; proc SetDIBColorTable*(DC: HDC, p2, p3: WINUINT, RGBQuadSTructs: pointer): WINUINT{. stdcall, dynlib: "gdi32", importc: "SetDIBColorTable".} proc SetDIBits*(DC: HDC, Bitmap: HBITMAP, StartScan, NumScans: WINUINT, - Bits: pointer, BitsInfo: var TBitmapInfo, Usage: WINUINT): int{. + Bits: pointer, BitsInfo: var BitmapInfo, Usage: WINUINT): int{. stdcall, dynlib: "gdi32", importc: "SetDIBits".} - #function SetDIBitsToDevice(DC: HDC; DestX, DestY: Integer; Width, Height: DWORD; SrcX, SrcY: Integer; nStartScan, NumScans: WINUINT; Bits: pointer; var BitsInfo: TBitmapInfo; Usage: WINUINT): Integer; stdcall; external 'gdi32' name 'SetDIBitsToDevice'; + #function SetDIBitsToDevice(DC: HDC; DestX, DestY: Integer; Width, Height: DWORD; SrcX, SrcY: Integer; nStartScan, NumScans: WINUINT; Bits: pointer; var BitsInfo: BitmapInfo; Usage: WINUINT): Integer; stdcall; external 'gdi32' name 'SetDIBitsToDevice'; proc SetEnhMetaFileBits*(para1: WINUINT, para2: pointer): HENHMETAFILE{.stdcall, dynlib: "gdi32", importc: "SetEnhMetaFileBits".} proc SetFileTime*(hFile: HANDLE, lpCreationTime: var FILETIME, lpLastAccessTime: var FILETIME, lpLastWriteTime: var FILETIME): WINBOOL{. stdcall, dynlib: "kernel32", importc: "SetFileTime".} #function SetKeyboardState(var KeyState: TKeyboardState): WINBOOL; stdcall; external 'user32' name 'SetKeyboardState'; - #function SetLocalTime(const lpSystemTime: TSystemTime): WINBOOL; stdcall; external 'kernel32' name 'SetLocalTime'; + #function SetLocalTime(const lpSystemTime: SystemTime): WINBOOL; stdcall; external 'kernel32' name 'SetLocalTime'; #function SetMenuInfo(menu: HMENU; const lpcmi: TMenuInfo): WINBOOL;stdcall; external 'user32' name 'SetMenuInfo'; -proc SetMenuItemInfo*(p1: HMENU, p2: WINUINT, p3: WINBOOL, p4: TMenuItemInfo): WINBOOL{. +proc SetMenuItemInfo*(p1: HMENU, p2: WINUINT, p3: WINBOOL, p4: MenuItemInfo): WINBOOL{. stdcall, dynlib: "user32", importc: "SetMenuItemInfoA".} -proc SetMenuItemInfoA*(p1: HMENU, p2: WINUINT, p3: WINBOOL, p4: TMenuItemInfoA): WINBOOL{. +proc SetMenuItemInfoA*(p1: HMENU, p2: WINUINT, p3: WINBOOL, p4: MenuItemInfo): WINBOOL{. stdcall, dynlib: "user32", importc: "SetMenuItemInfoA".} - #function SetMenuItemInfoW(p1: HMENU; p2: WINUINT; p3: WINBOOL; const p4: TMenuItemInfoW): WINBOOL; stdcall; external 'user32' name 'SetMenuItemInfoW'; + #function SetMenuItemInfoW(p1: HMENU; p2: WINUINT; p3: WINBOOL; const p4: MenuItemInfoW): WINBOOL; stdcall; external 'user32' name 'SetMenuItemInfoW'; proc SetMetaFileBitsEx*(p1: WINUINT, p2: cstring): HMETAFILE{.stdcall, dynlib: "gdi32", importc: "SetMetaFileBitsEx".} -proc SetNamedPipeHandleState*(hNamedPipe: THandle, lpMode: var DWORD, +proc SetNamedPipeHandleState*(hNamedPipe: Handle, lpMode: var DWORD, lpMaxCollectionCount, lpCollectDataTimeout: pointer): WINBOOL{.stdcall, dynlib: "kernel32", importc: "SetNamedPipeHandleState".} proc SetPaletteEntries*(Palette: HPALETTE, StartIndex, NumEntries: WINUINT, PaletteEntries: pointer): WINUINT{.stdcall, dynlib: "gdi32", importc: "SetPaletteEntries".} - #function SetPrivateObjectSecurity(SecurityInformation: SECURITY_INFORMATION; ModificationDescriptor: PSecurityDescriptor; var ObjectsSecurityDescriptor: PSecurityDescriptor; const GenericMapping: TGenericMapping; Token: THandle): WINBOOL; + #function SetPrivateObjectSecurity(SecurityInformation: SECURITY_INFORMATION; ModificationDescriptor: PSecurityDescriptor; var ObjectsSecurityDescriptor: PSecurityDescriptor; const GenericMapping: GenericMapping; Token: Handle): WINBOOL; # stdcall; external 'advapi32' name 'SetPrivateObjectSecurity'; #function SetPrivateObjectSecurityEx(SecurityInformation: SECURITY_INFORMATION; ModificationDescriptor: PSecurityDescriptor; var ObjectsSecurityDescriptor: PSecurityDescriptor; AutoInheritFlags: ULONG; - # const GenericMapping: TGenericMapping; Token: THandle): WINBOOL;stdcall; external 'advapi32' name 'SetPrivateObjectSecurityEx'; -proc SetRect*(lprc: var TRect, xLeft, yTop, xRight, yBottom: int): WINBOOL{. + # const GenericMapping: GenericMapping; Token: Handle): WINBOOL;stdcall; external 'advapi32' name 'SetPrivateObjectSecurityEx'; +proc SetRect*(lprc: var Rect, xLeft, yTop, xRight, yBottom: int): WINBOOL{. stdcall, dynlib: "user32", importc: "SetRect".} -proc SetRectEmpty*(lprc: var TRect): WINBOOL{.stdcall, dynlib: "user32", +proc SetRectEmpty*(lprc: var Rect): WINBOOL{.stdcall, dynlib: "user32", importc: "SetRectEmpty".} -proc SetScrollInfo*(wnd: HWND, BarFlag: int, ScrollInfo: TScrollInfo, +proc SetScrollInfo*(wnd: HWND, BarFlag: int, ScrollInfo: ScrollInfo, Redraw: WINBOOL): int{.stdcall, dynlib: "user32", importc: "SetScrollInfo".} proc SetSysColors*(cElements: int, lpaElements: pointer, lpaRgbValues: pointer): WINBOOL{. stdcall, dynlib: "user32", importc: "SetSysColors".} - #function SetSystemTime(const lpSystemTime: TSystemTime): WINBOOL; stdcall; external 'kernel32' name 'SetSystemTime'; -proc SetThreadContext*(hThread: THandle, lpContext: TContext): WINBOOL{.stdcall, + #function SetSystemTime(const lpSystemTime: SystemTime): WINBOOL; stdcall; external 'kernel32' name 'SetSystemTime'; +proc SetThreadContext*(hThread: Handle, lpContext: Context): WINBOOL{.stdcall, dynlib: "kernel32", importc: "SetThreadContext".} - #function SetTimeZoneInformation(const lpTimeZoneInformation: TTimeZoneInformation): WINBOOL; stdcall; external 'kernel32' name 'SetTimeZoneInformation'; -proc SetUserObjectSecurity*(hObj: THandle, pSIRequested: var DWORD, + #function SetTimeZoneInformation(const lpTimeZoneInformation: TimeZoneInformation): WINBOOL; stdcall; external 'kernel32' name 'SetTimeZoneInformation'; +proc SetUserObjectSecurity*(hObj: Handle, pSIRequested: var DWORD, pSID: PSecurityDescriptor): WINBOOL{.stdcall, dynlib: "user32", importc: "SetUserObjectSecurity".} -proc SetWaitableTimer*(hTimer: THandle, lpDueTime: var TLargeInteger, +proc SetWaitableTimer*(hTimer: Handle, lpDueTime: var LargeInteger, lPeriod: int32, pfnCompletionRoutine: TFNTimerAPCRoutine, lpArgToCompletionRoutine: pointer, fResume: WINBOOL): WINBOOL{. stdcall, dynlib: "kernel32", importc: "SetWaitableTimer".} -proc SetWinMetaFileBits*(p1: WINUINT, p2: cstring, p3: HDC, p4: TMetaFilePict): HENHMETAFILE{. +proc SetWinMetaFileBits*(p1: WINUINT, p2: cstring, p3: HDC, p4: MetaFilePict): HENHMETAFILE{. stdcall, dynlib: "gdi32", importc: "SetWinMetaFileBits".} - #function SetWorldTransform(DC: HDC; const p2: TXForm): WINBOOL; stdcall; external 'gdi32' name 'SetWorldTransform'; -proc StartDoc*(DC: HDC, p2: TDocInfo): int{.stdcall, dynlib: "gdi32", + #function SetWorldTransform(DC: HDC; const p2: XForm): WINBOOL; stdcall; external 'gdi32' name 'SetWorldTransform'; +proc StartDoc*(DC: HDC, p2: DocInfo): int{.stdcall, dynlib: "gdi32", importc: "StartDocA".} -proc StartDocA*(DC: HDC, p2: TDocInfoA): int{.stdcall, dynlib: "gdi32", +proc StartDocA*(DC: HDC, p2: DocInfo): int{.stdcall, dynlib: "gdi32", importc: "StartDocA".} - #function StartDocW(DC: HDC; const p2: TDocInfoW): Integer; stdcall; external 'gdi32' name 'StartDocW'; - #function StretchDIBits(DC: HDC; DestX, DestY, DestWidth, DestHegiht, SrcX, SrcY, SrcWidth, SrcHeight: Integer; Bits: pointer; var BitsInfo: TBitmapInfo; Usage: WINUINT; Rop: DWORD): Integer; stdcall; external 'gdi32' name 'StretchDIBits'; -proc SubtractRect*(lprcDst: var TRect, lprcSrc1, lprcSrc2: TRect): WINBOOL{. + #function StartDocW(DC: HDC; const p2: DocInfoW): Integer; stdcall; external 'gdi32' name 'StartDocW'; + #function StretchDIBits(DC: HDC; DestX, DestY, DestWidth, DestHegiht, SrcX, SrcY, SrcWidth, SrcHeight: Integer; Bits: pointer; var BitsInfo: BitmapInfo; Usage: WINUINT; Rop: DWORD): Integer; stdcall; external 'gdi32' name 'StretchDIBits'; +proc SubtractRect*(lprcDst: var Rect, lprcSrc1, lprcSrc2: Rect): WINBOOL{. stdcall, dynlib: "user32", importc: "SubtractRect".} -proc SystemTimeToFileTime*(lpSystemTime: TSystemTime, lpFileTime: var TFileTime): WINBOOL{. +proc SystemTimeToFileTime*(lpSystemTime: SystemTime, lpFileTime: var FileTime): WINBOOL{. stdcall, dynlib: "kernel32", importc: "SystemTimeToFileTime".} proc SystemTimeToTzSpecificLocalTime*(lpTimeZoneInformation: PTimeZoneInformation, - lpUniversalTime, lpLocalTime: var TSystemTime): WINBOOL{.stdcall, + lpUniversalTime, lpLocalTime: var SystemTime): WINBOOL{.stdcall, dynlib: "kernel32", importc: "SystemTimeToTzSpecificLocalTime".} proc TabbedTextOut*(hDC: HDC, X, Y: int, lpString: cstring, nCount, nTabPositions: int, lpnTabStopPositions: pointer, @@ -22491,7 +22031,7 @@ proc TrackMouseEvent*(lpEventTrack: PTrackMouseEvent): WINBOOL{.stdcall, proc TrackPopupMenu*(menu: HMENU, uFlags: WINUINT, x: int32, y: int32, nReserved: int32, wnd: HWND, prcRect: PRect): WINBOOL{. stdcall, dynlib: "user32", importc: "TrackPopupMenu".} -proc TransactNamedPipe*(hNamedPipe: THandle, lpInBuffer: pointer, +proc TransactNamedPipe*(hNamedPipe: Handle, lpInBuffer: pointer, nInBufferSize: DWORD, lpOutBuffer: pointer, nOutBufferSize: DWORD, lpBytesRead: var DWORD, lpOverlapped: POverlapped): WINBOOL{.stdcall, @@ -22502,7 +22042,7 @@ proc TranslateAcceleratorA*(wnd: HWND, hAccTable: HACCEL, lpMsg: var TMsg): int{ stdcall, dynlib: "user32", importc: "TranslateAcceleratorA".} proc TranslateAcceleratorW*(wnd: HWND, hAccTable: HACCEL, lpMsg: var TMsg): int{. stdcall, dynlib: "user32", importc: "TranslateAcceleratorW".} -proc TranslateCharsetInfo*(lpSrc: var DWORD, lpCs: var TCharsetInfo, +proc TranslateCharsetInfo*(lpSrc: var DWORD, lpCs: var CharsetInfo, dwFlags: DWORD): WINBOOL{.stdcall, dynlib: "gdi32", importc: "TranslateCharsetInfo".} proc TranslateMDISysAccel*(hWndClient: HWND, lpMsg: TMsg): WINBOOL{.stdcall, @@ -22510,12 +22050,12 @@ proc TranslateMDISysAccel*(hWndClient: HWND, lpMsg: TMsg): WINBOOL{.stdcall, proc TranslateMessage*(lpMsg: TMsg): WINBOOL{.stdcall, dynlib: "user32", importc: "TranslateMessage".} #function TransparentDIBits(DC: HDC; p2, p3, p4, p5: Integer; const p6: pointer; const p7: PBitmapInfo; p8: WINUINT; p9, p10, p11, p12: Integer; p13: WINUINT): WINBOOL;stdcall; external 'gdi32' name 'TransparentDIBits'; -proc UnhandledExceptionFilter*(ExceptionInfo: TExceptionpointers): int32{. +proc UnhandledExceptionFilter*(ExceptionInfo: Exceptionpointers): int32{. stdcall, dynlib: "kernel32", importc: "UnhandledExceptionFilter".} -proc UnionRect*(lprcDst: var TRect, lprcSrc1, lprcSrc2: TRect): WINBOOL{. +proc UnionRect*(lprcDst: var Rect, lprcSrc1, lprcSrc2: Rect): WINBOOL{. stdcall, dynlib: "user32", importc: "UnionRect".} -proc UnlockFileEx*(hFile: THandle, dwReserved, nNumberOfBytesToUnlockLow: DWORD, - nNumberOfBytesToUnlockHigh: DWORD, lpOverlapped: TOverlapped): WINBOOL{. +proc UnlockFileEx*(hFile: Handle, dwReserved, nNumberOfBytesToUnlockLow: DWORD, + nNumberOfBytesToUnlockHigh: DWORD, lpOverlapped: Overlapped): WINBOOL{. stdcall, dynlib: "kernel32", importc: "UnlockFileEx".} proc VerFindFile*(uFlags: DWORD, szFileName, szWinDir, szAppDir, szCurDir: cstring, @@ -22553,19 +22093,19 @@ proc VerQueryValueA*(pBlock: pointer, lpSubBlock: LPCSTR, proc VerQueryValueW*(pBlock: pointer, lpSubBlock: LPWSTR, lplpBuffer: var pointer, puLen: var WINUINT): WINBOOL{. stdcall, dynlib: "version", importc: "VerQueryValueW".} -proc VirtualQuery*(lpAddress: pointer, lpBuffer: var TMemoryBasicInformation, +proc VirtualQuery*(lpAddress: pointer, lpBuffer: var MemoryBasicInformation, dwLength: DWORD): DWORD{.stdcall, dynlib: "kernel32", importc: "VirtualQuery".} -proc VirtualQueryEx*(hProcess: THandle, lpAddress: pointer, - lpBuffer: var TMemoryBasicInformation, dwLength: DWORD): DWORD{. +proc VirtualQueryEx*(hProcess: Handle, lpAddress: pointer, + lpBuffer: var MemoryBasicInformation, dwLength: DWORD): DWORD{. stdcall, dynlib: "kernel32", importc: "VirtualQueryEx".} -proc WaitCommEvent*(hFile: THandle, lpEvtMask: var DWORD, +proc WaitCommEvent*(hFile: Handle, lpEvtMask: var DWORD, lpOverlapped: POverlapped): WINBOOL{.stdcall, dynlib: "kernel32", importc: "WaitCommEvent".} -proc WaitForDebugEvent*(lpDebugEvent: var TDebugEvent, dwMilliseconds: DWORD): WINBOOL{. +proc WaitForDebugEvent*(lpDebugEvent: var DebugEvent, dwMilliseconds: DWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "WaitForDebugEvent".} proc wglDescribeLayerPlane*(p1: HDC, p2, p3: int, p4: int, - p5: var TLayerPlaneDescriptor): WINBOOL{.stdcall, + p5: var LayerPlaneDescriptor): WINBOOL{.stdcall, dynlib: "opengl32", importc: "wglDescribeLayerPlane".} proc wglGetLayerPaletteEntries*(p1: HDC, p2, p3, p4: int, pcr: pointer): int{. stdcall, dynlib: "opengl32", importc: "wglGetLayerPaletteEntries".} @@ -22573,38 +22113,38 @@ proc wglSetLayerPaletteEntries*(p1: HDC, p2, p3, p4: int, pcr: pointer): int{. stdcall, dynlib: "opengl32", importc: "wglSetLayerPaletteEntries".} #function wglSwapMultipleBuffers(p1: WINUINT; const p2: PWGLSwap): DWORD;stdcall; external 'opengl32' name 'wglSwapMultipleBuffers'; #function WinSubmitCertificate(var lpCertificate: TWinCertificate): WINBOOL;stdcall; external 'imaghlp' name 'WinSubmitCertificate'; - #function WinVerifyTrust(wnd: HWND; const ActionID: TGUID; ActionData: pointer): Longint;stdcall; external 'imaghlp' name 'WinVerifyTrust'; -proc WNetAddConnection2*(lpNetResource: var TNetResource, + #function WinVerifyTrust(wnd: HWND; const ActionID: GUID; ActionData: pointer): Longint;stdcall; external 'imaghlp' name 'WinVerifyTrust'; +proc WNetAddConnection2*(lpNetResource: var NetResource, lpPassword, lpUserName: cstring, dwFlags: DWORD): DWORD{. stdcall, dynlib: "mpr", importc: "WNetAddConnection2A".} -proc WNetAddConnection2A*(lpNetResource: var TNetResourceA, +proc WNetAddConnection2A*(lpNetResource: var NetResource, lpPassword, lpUserName: LPCSTR, dwFlags: DWORD): DWORD{. stdcall, dynlib: "mpr", importc: "WNetAddConnection2A".} - #function WNetAddConnection2W(var lpNetResource: TNetResourceW; lpPassword, lpUserName: LPWSTR; dwFlags: DWORD): DWORD; stdcall; external 'mpr' name 'WNetAddConnection2W'; -proc WNetAddConnection3*(hwndOwner: HWND, lpNetResource: var TNetResource, + #function WNetAddConnection2W(var lpNetResource: NetResourceW; lpPassword, lpUserName: LPWSTR; dwFlags: DWORD): DWORD; stdcall; external 'mpr' name 'WNetAddConnection2W'; +proc WNetAddConnection3*(hwndOwner: HWND, lpNetResource: var NetResource, lpPassword, lpUserName: cstring, dwFlags: DWORD): DWORD{. stdcall, dynlib: "mpr", importc: "WNetAddConnection3A".} -proc WNetAddConnection3A*(hwndOwner: HWND, lpNetResource: var TNetResourceA, +proc WNetAddConnection3A*(hwndOwner: HWND, lpNetResource: var NetResource, lpPassword, lpUserName: LPCSTR, dwFlags: DWORD): DWORD{. stdcall, dynlib: "mpr", importc: "WNetAddConnection3A".} - #function WNetAddConnection3W(hwndOwner: HWND; var lpNetResource: TNetResourceW; lpPassword, lpUserName: LPWSTR; dwFlags: DWORD): DWORD; stdcall; external 'mpr' name 'WNetAddConnection3W'; -proc WNetConnectionDialog1*(lpConnDlgStruct: var TConnectDlgStruct): DWORD{. + #function WNetAddConnection3W(hwndOwner: HWND; var lpNetResource: NetResourceW; lpPassword, lpUserName: LPWSTR; dwFlags: DWORD): DWORD; stdcall; external 'mpr' name 'WNetAddConnection3W'; +proc WNetConnectionDialog1*(lpConnDlgStruct: var ConnectDlgStruct): DWORD{. stdcall, dynlib: "mpr", importc: "WNetConnectionDialog1A".} -proc WNetConnectionDialog1A*(lpConnDlgStruct: var TConnectDlgStruct): DWORD{. +proc WNetConnectionDialog1A*(lpConnDlgStruct: var ConnectDlgStruct): DWORD{. stdcall, dynlib: "mpr", importc: "WNetConnectionDialog1A".} - #function WNetConnectionDialog1W(var lpConnDlgStruct: TConnectDlgStruct): DWORD; stdcall; external 'mpr' name 'WNetConnectionDialog1W'; -proc WNetDisconnectDialog1*(lpConnDlgStruct: var TDiscDlgStruct): DWORD{. + #function WNetConnectionDialog1W(var lpConnDlgStruct: ConnectDlgStruct): DWORD; stdcall; external 'mpr' name 'WNetConnectionDialog1W'; +proc WNetDisconnectDialog1*(lpConnDlgStruct: var DiscDlgStruct): DWORD{. stdcall, dynlib: "mpr", importc: "WNetDisconnectDialog1A".} -proc WNetDisconnectDialog1A*(lpConnDlgStruct: var TDiscDlgStructA): DWORD{. +proc WNetDisconnectDialog1A*(lpConnDlgStruct: var DiscDlgStruct): DWORD{. stdcall, dynlib: "mpr", importc: "WNetDisconnectDialog1A".} - #function WNetDisconnectDialog1W(var lpConnDlgStruct: TDiscDlgStructW): DWORD; stdcall; external 'mpr' name 'WNetDisconnectDialog1W'; -proc WNetEnumResource*(hEnum: THandle, lpcCount: var DWORD, lpBuffer: pointer, + #function WNetDisconnectDialog1W(var lpConnDlgStruct: DiscDlgStructW): DWORD; stdcall; external 'mpr' name 'WNetDisconnectDialog1W'; +proc WNetEnumResource*(hEnum: Handle, lpcCount: var DWORD, lpBuffer: pointer, lpBufferSize: var DWORD): DWORD{.stdcall, dynlib: "mpr", importc: "WNetEnumResourceA".} -proc WNetEnumResourceA*(hEnum: THandle, lpcCount: var DWORD, lpBuffer: pointer, +proc WNetEnumResourceA*(hEnum: Handle, lpcCount: var DWORD, lpBuffer: pointer, lpBufferSize: var DWORD): DWORD{.stdcall, dynlib: "mpr", importc: "WNetEnumResourceA".} -proc WNetEnumResourceW*(hEnum: THandle, lpcCount: var DWORD, lpBuffer: pointer, +proc WNetEnumResourceW*(hEnum: Handle, lpcCount: var DWORD, lpBuffer: pointer, lpBufferSize: var DWORD): DWORD{.stdcall, dynlib: "mpr", importc: "WNetEnumResourceW".} proc WNetGetConnection*(lpLocalName: cstring, lpRemoteName: cstring, @@ -22629,13 +22169,13 @@ proc WNetGetLastErrorW*(lpError: var DWORD, lpErrorBuf: LPWSTR, nNameBufSize: DWORD): DWORD{.stdcall, dynlib: "mpr", importc: "WNetGetLastErrorW".} proc WNetGetNetworkInformation*(lpProvider: cstring, - lpNetInfoStruct: var TNetInfoStruct): DWORD{. + lpNetInfoStruct: var NetInfoStruct): DWORD{. stdcall, dynlib: "mpr", importc: "WNetGetNetworkInformationA".} proc WNetGetNetworkInformationA*(lpProvider: LPCSTR, - lpNetInfoStruct: var TNetInfoStruct): DWORD{. + lpNetInfoStruct: var NetInfoStruct): DWORD{. stdcall, dynlib: "mpr", importc: "WNetGetNetworkInformationA".} proc WNetGetNetworkInformationW*(lpProvider: LPWSTR, - lpNetInfoStruct: var TNetInfoStruct): DWORD{. + lpNetInfoStruct: var NetInfoStruct): DWORD{. stdcall, dynlib: "mpr", importc: "WNetGetNetworkInformationW".} proc WNetGetProviderName*(dwNetType: DWORD, lpProviderName: cstring, lpBufferSize: var DWORD): DWORD{.stdcall, @@ -22669,77 +22209,77 @@ proc WNetGetUserA*(lpName: LPCSTR, lpUserName: LPCSTR, lpnLength: var DWORD): DW proc WNetGetUserW*(lpName: LPWSTR, lpUserName: LPWSTR, lpnLength: var DWORD): DWORD{. stdcall, dynlib: "mpr", importc: "WNetGetUserW".} proc WNetOpenEnum*(dwScope, dwType, dwUsage: DWORD, lpNetResource: PNetResource, - lphEnum: var THandle): DWORD{.stdcall, dynlib: "mpr", + lphEnum: var Handle): DWORD{.stdcall, dynlib: "mpr", importc: "WNetOpenEnumA".} proc WNetOpenEnumA*(dwScope, dwType, dwUsage: DWORD, - lpNetResource: PNetResourceA, lphEnum: var THandle): DWORD{. + lpNetResource: PNetResourceA, lphEnum: var Handle): DWORD{. stdcall, dynlib: "mpr", importc: "WNetOpenEnumA".} - #function WNetOpenEnumW(dwScope, dwType, dwUsage: DWORD; lpNetResource: PNetResourceW; var lphEnum: THandle): DWORD; stdcall; external 'mpr' name 'WNetOpenEnumW'; -proc WNetUseConnection*(hwndOwner: HWND, lpNetResource: var TNetResource, + #function WNetOpenEnumW(dwScope, dwType, dwUsage: DWORD; lpNetResource: PNetResourceW; var lphEnum: Handle): DWORD; stdcall; external 'mpr' name 'WNetOpenEnumW'; +proc WNetUseConnection*(hwndOwner: HWND, lpNetResource: var NetResource, lpUserID: cstring, lpPassword: cstring, dwFlags: DWORD, lpAccessName: cstring, lpBufferSize: var DWORD, lpResult: var DWORD): DWORD{.stdcall, dynlib: "mpr", importc: "WNetUseConnectionA".} -proc WNetUseConnectionA*(hwndOwner: HWND, lpNetResource: var TNetResourceA, +proc WNetUseConnectionA*(hwndOwner: HWND, lpNetResource: var NetResource, lpUserID: LPCSTR, lpPassword: LPCSTR, dwFlags: DWORD, lpAccessName: LPCSTR, lpBufferSize: var DWORD, lpResult: var DWORD): DWORD{.stdcall, dynlib: "mpr", importc: "WNetUseConnectionA".} - #function WNetUseConnectionW(hwndOwner: HWND; var lpNetResource: TNetResourceW; lpUserID: LPWSTR; lpPassword: LPWSTR; dwFlags: DWORD; lpAccessName: LPWSTR; var lpBufferSize: DWORD; var lpResult: DWORD): DWORD; stdcall; external 'mpr' name 'WNetUseConnectionW'; -proc WriteConsole*(hConsoleOutput: THandle, lpBuffer: pointer, + #function WNetUseConnectionW(hwndOwner: HWND; var lpNetResource: NetResourceW; lpUserID: LPWSTR; lpPassword: LPWSTR; dwFlags: DWORD; lpAccessName: LPWSTR; var lpBufferSize: DWORD; var lpResult: DWORD): DWORD; stdcall; external 'mpr' name 'WNetUseConnectionW'; +proc WriteConsole*(hConsoleOutput: Handle, lpBuffer: pointer, nNumberOfCharsToWrite: DWORD, lpNumberOfCharsWritten: var DWORD, lpReserved: pointer): WINBOOL{. stdcall, dynlib: "kernel32", importc: "WriteConsoleA".} -proc WriteConsoleA*(hConsoleOutput: THandle, lpBuffer: pointer, +proc WriteConsoleA*(hConsoleOutput: Handle, lpBuffer: pointer, nNumberOfCharsToWrite: DWORD, lpNumberOfCharsWritten: var DWORD, lpReserved: pointer): WINBOOL{. stdcall, dynlib: "kernel32", importc: "WriteConsoleA".} -proc WriteConsoleInput*(hConsoleInput: THandle, lpBuffer: TInputRecord, +proc WriteConsoleInput*(hConsoleInput: Handle, lpBuffer: InputRecord, nLength: DWORD, lpNumberOfEventsWritten: var DWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "WriteConsoleInputA".} -proc WriteConsoleInputA*(hConsoleInput: THandle, lpBuffer: TInputRecord, +proc WriteConsoleInputA*(hConsoleInput: Handle, lpBuffer: InputRecord, nLength: DWORD, lpNumberOfEventsWritten: var DWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "WriteConsoleInputA".} -proc WriteConsoleInputW*(hConsoleInput: THandle, lpBuffer: TInputRecord, +proc WriteConsoleInputW*(hConsoleInput: Handle, lpBuffer: InputRecord, nLength: DWORD, lpNumberOfEventsWritten: var DWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "WriteConsoleInputW".} -proc WriteConsoleOutput*(hConsoleOutput: THandle, lpBuffer: pointer, - dwBufferSize, dwBufferCoord: TCoord, - lpWriteRegion: var TSmallRect): WINBOOL{.stdcall, +proc WriteConsoleOutput*(hConsoleOutput: Handle, lpBuffer: pointer, + dwBufferSize, dwBufferCoord: Coord, + lpWriteRegion: var SmallRect): WINBOOL{.stdcall, dynlib: "kernel32", importc: "WriteConsoleOutputA".} -proc WriteConsoleOutputA*(hConsoleOutput: THandle, lpBuffer: pointer, - dwBufferSize, dwBufferCoord: TCoord, - lpWriteRegion: var TSmallRect): WINBOOL{.stdcall, +proc WriteConsoleOutputA*(hConsoleOutput: Handle, lpBuffer: pointer, + dwBufferSize, dwBufferCoord: Coord, + lpWriteRegion: var SmallRect): WINBOOL{.stdcall, dynlib: "kernel32", importc: "WriteConsoleOutputA".} -proc WriteConsoleOutputAttribute*(hConsoleOutput: THandle, lpAttribute: pointer, - nLength: DWORD, dwWriteCoord: TCoord, +proc WriteConsoleOutputAttribute*(hConsoleOutput: Handle, lpAttribute: pointer, + nLength: DWORD, dwWriteCoord: Coord, lpNumberOfAttrsWritten: var DWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "WriteConsoleOutputAttribute".} -proc WriteConsoleOutputCharacter*(hConsoleOutput: THandle, lpCharacter: cstring, - nLength: DWORD, dwWriteCoord: TCoord, +proc WriteConsoleOutputCharacter*(hConsoleOutput: Handle, lpCharacter: cstring, + nLength: DWORD, dwWriteCoord: Coord, lpNumberOfCharsWritten: var DWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "WriteConsoleOutputCharacterA".} -proc WriteConsoleOutputCharacterA*(hConsoleOutput: THandle, lpCharacter: LPCSTR, - nLength: DWORD, dwWriteCoord: TCoord, +proc WriteConsoleOutputCharacterA*(hConsoleOutput: Handle, lpCharacter: LPCSTR, + nLength: DWORD, dwWriteCoord: Coord, lpNumberOfCharsWritten: var DWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "WriteConsoleOutputCharacterA".} -proc WriteConsoleOutputCharacterW*(hConsoleOutput: THandle, lpCharacter: LPWSTR, - nLength: DWORD, dwWriteCoord: TCoord, +proc WriteConsoleOutputCharacterW*(hConsoleOutput: Handle, lpCharacter: LPWSTR, + nLength: DWORD, dwWriteCoord: Coord, lpNumberOfCharsWritten: var DWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "WriteConsoleOutputCharacterW".} -proc WriteConsoleOutputW*(hConsoleOutput: THandle, lpBuffer: pointer, - dwBufferSize, dwBufferCoord: TCoord, - lpWriteRegion: var TSmallRect): WINBOOL{.stdcall, +proc WriteConsoleOutputW*(hConsoleOutput: Handle, lpBuffer: pointer, + dwBufferSize, dwBufferCoord: Coord, + lpWriteRegion: var SmallRect): WINBOOL{.stdcall, dynlib: "kernel32", importc: "WriteConsoleOutputW".} -proc WriteConsoleW*(hConsoleOutput: THandle, lpBuffer: pointer, +proc WriteConsoleW*(hConsoleOutput: Handle, lpBuffer: pointer, nNumberOfCharsToWrite: DWORD, lpNumberOfCharsWritten: var DWORD, lpReserved: pointer): WINBOOL{. stdcall, dynlib: "kernel32", importc: "WriteConsoleW".} -proc WriteFile*(hFile: THandle, Buffer: pointer, nNumberOfBytesToWrite: DWORD, +proc WriteFile*(hFile: Handle, Buffer: pointer, nNumberOfBytesToWrite: DWORD, lpNumberOfBytesWritten: var DWORD, lpOverlapped: POverlapped): WINBOOL{. stdcall, dynlib: "kernel32", importc: "WriteFile".} -proc WriteFileEx*(hFile: THandle, lpBuffer: pointer, - nNumberOfBytesToWrite: DWORD, lpOverlapped: TOverlapped, +proc WriteFileEx*(hFile: Handle, lpBuffer: pointer, + nNumberOfBytesToWrite: DWORD, lpOverlapped: Overlapped, lpCompletionRoutine: FARPROC): WINBOOL{.stdcall, dynlib: "kernel32", importc: "WriteFileEx".} proc WritePrivateProfileStructA*(lpszSection, lpszKey: LPCSTR, lpStruct: LPVOID, @@ -22752,7 +22292,7 @@ proc WritePrivateProfileStructW*(lpszSection, lpszKey: LPCWSTR, proc WritePrivateProfileStruct*(lpszSection, lpszKey: LPCTSTR, lpStruct: LPVOID, uSizeStruct: WINUINT, szFile: LPCTSTR): WINBOOL{. stdcall, dynlib: "kernel32", importc: "WritePrivateProfileStructA".} -proc WriteProcessMemory*(hProcess: THandle, lpBaseAddress: pointer, +proc WriteProcessMemory*(hProcess: Handle, lpBaseAddress: pointer, lpBuffer: pointer, nSize: DWORD, lpNumberOfBytesWritten: var DWORD): WINBOOL{.stdcall, dynlib: "kernel32", importc: "WriteProcessMemory".} diff --git a/lib/windows/winlean.nim b/lib/windows/winlean.nim index 57b79c7de..596507ebe 100644 --- a/lib/windows/winlean.nim +++ b/lib/windows/winlean.nim @@ -16,7 +16,7 @@ const useWinUnicode* = not defined(useWinAnsi) type - THandle* = int + Handle* = int LONG* = int32 ULONG* = int PULONG* = ptr int @@ -24,15 +24,15 @@ type DWORD* = int32 PDWORD* = ptr DWORD LPINT* = ptr int32 - HDC* = THandle - HGLRC* = THandle + HDC* = Handle + HGLRC* = Handle - TSECURITY_ATTRIBUTES* {.final, pure.} = object + SECURITY_ATTRIBUTES* {.final, pure.} = object nLength*: int32 lpSecurityDescriptor*: pointer bInheritHandle*: WINBOOL - TSTARTUPINFO* {.final, pure.} = object + STARTUPINFO* {.final, pure.} = object cb*: int32 lpReserved*: cstring lpDesktop*: cstring @@ -48,25 +48,25 @@ type wShowWindow*: int16 cbReserved2*: int16 lpReserved2*: pointer - hStdInput*: THandle - hStdOutput*: THandle - hStdError*: THandle + hStdInput*: Handle + hStdOutput*: Handle + hStdError*: Handle - TPROCESS_INFORMATION* {.final, pure.} = object - hProcess*: THandle - hThread*: THandle + PROCESS_INFORMATION* {.final, pure.} = object + hProcess*: Handle + hThread*: Handle dwProcessId*: int32 dwThreadId*: int32 - TFILETIME* {.final, pure.} = object ## CANNOT BE int64 BECAUSE OF ALIGNMENT + FILETIME* {.final, pure.} = object ## CANNOT BE int64 BECAUSE OF ALIGNMENT dwLowDateTime*: DWORD dwHighDateTime*: DWORD - TBY_HANDLE_FILE_INFORMATION* {.final, pure.} = object + BY_HANDLE_FILE_INFORMATION* {.final, pure.} = object dwFileAttributes*: DWORD - ftCreationTime*: TFILETIME - ftLastAccessTime*: TFILETIME - ftLastWriteTime*: TFILETIME + ftCreationTime*: FILETIME + ftLastAccessTime*: FILETIME + ftLastWriteTime*: FILETIME dwVolumeSerialNumber*: DWORD nFileSizeHigh*: DWORD nFileSizeLow*: DWORD @@ -74,10 +74,16 @@ type nFileIndexHigh*: DWORD nFileIndexLow*: DWORD +{.deprecated: [THandle: Handle, TSECURITY_ATTRIBUTES: SECURITY_ATTRIBUTES, + TSTARTUPINFO: STARTUPINFO, TPROCESS_INFORMATION: PROCESS_INFORMATION, + TFILETIME: FILETIME, TBY_HANDLE_FILE_INFORMATION: BY_HANDLE_FILE_INFORMATION].} + when useWinUnicode: - type TWinChar* = TUtf16Char + type WinChar* = Utf16Char + {.deprecated: [TWinChar: WinChar].} else: - type TWinChar* = char + type WinChar* = char + {.deprecated: [TWinChar: WinChar].} const STARTF_USESHOWWINDOW* = 1'i32 @@ -98,67 +104,67 @@ const DETACHED_PROCESS* = 8'i32 SW_SHOWNORMAL* = 1'i32 - INVALID_HANDLE_VALUE* = THandle(-1) + INVALID_HANDLE_VALUE* = Handle(-1) CREATE_UNICODE_ENVIRONMENT* = 1024'i32 -proc closeHandle*(hObject: THandle): WINBOOL {.stdcall, dynlib: "kernel32", +proc closeHandle*(hObject: Handle): WINBOOL {.stdcall, dynlib: "kernel32", importc: "CloseHandle".} -proc readFile*(hFile: THandle, Buffer: pointer, nNumberOfBytesToRead: int32, +proc readFile*(hFile: Handle, Buffer: pointer, nNumberOfBytesToRead: int32, lpNumberOfBytesRead: ptr int32, lpOverlapped: pointer): WINBOOL{. stdcall, dynlib: "kernel32", importc: "ReadFile".} -proc writeFile*(hFile: THandle, Buffer: pointer, nNumberOfBytesToWrite: int32, +proc writeFile*(hFile: Handle, Buffer: pointer, nNumberOfBytesToWrite: int32, lpNumberOfBytesWritten: ptr int32, lpOverlapped: pointer): WINBOOL{. stdcall, dynlib: "kernel32", importc: "WriteFile".} -proc createPipe*(hReadPipe, hWritePipe: var THandle, - lpPipeAttributes: var TSECURITY_ATTRIBUTES, +proc createPipe*(hReadPipe, hWritePipe: var Handle, + lpPipeAttributes: var SECURITY_ATTRIBUTES, nSize: int32): WINBOOL{. stdcall, dynlib: "kernel32", importc: "CreatePipe".} when useWinUnicode: proc createProcessW*(lpApplicationName, lpCommandLine: WideCString, - lpProcessAttributes: ptr TSECURITY_ATTRIBUTES, - lpThreadAttributes: ptr TSECURITY_ATTRIBUTES, + lpProcessAttributes: ptr SECURITY_ATTRIBUTES, + lpThreadAttributes: ptr SECURITY_ATTRIBUTES, bInheritHandles: WINBOOL, dwCreationFlags: int32, lpEnvironment, lpCurrentDirectory: WideCString, - lpStartupInfo: var TSTARTUPINFO, - lpProcessInformation: var TPROCESS_INFORMATION): WINBOOL{. + lpStartupInfo: var STARTUPINFO, + lpProcessInformation: var PROCESS_INFORMATION): WINBOOL{. stdcall, dynlib: "kernel32", importc: "CreateProcessW".} else: proc createProcessA*(lpApplicationName, lpCommandLine: cstring, - lpProcessAttributes: ptr TSECURITY_ATTRIBUTES, - lpThreadAttributes: ptr TSECURITY_ATTRIBUTES, + lpProcessAttributes: ptr SECURITY_ATTRIBUTES, + lpThreadAttributes: ptr SECURITY_ATTRIBUTES, bInheritHandles: WINBOOL, dwCreationFlags: int32, lpEnvironment: pointer, lpCurrentDirectory: cstring, - lpStartupInfo: var TSTARTUPINFO, - lpProcessInformation: var TPROCESS_INFORMATION): WINBOOL{. + lpStartupInfo: var STARTUPINFO, + lpProcessInformation: var PROCESS_INFORMATION): WINBOOL{. stdcall, dynlib: "kernel32", importc: "CreateProcessA".} -proc suspendThread*(hThread: THandle): int32 {.stdcall, dynlib: "kernel32", +proc suspendThread*(hThread: Handle): int32 {.stdcall, dynlib: "kernel32", importc: "SuspendThread".} -proc resumeThread*(hThread: THandle): int32 {.stdcall, dynlib: "kernel32", +proc resumeThread*(hThread: Handle): int32 {.stdcall, dynlib: "kernel32", importc: "ResumeThread".} -proc waitForSingleObject*(hHandle: THandle, dwMilliseconds: int32): int32 {. +proc waitForSingleObject*(hHandle: Handle, dwMilliseconds: int32): int32 {. stdcall, dynlib: "kernel32", importc: "WaitForSingleObject".} -proc terminateProcess*(hProcess: THandle, uExitCode: int): WINBOOL {.stdcall, +proc terminateProcess*(hProcess: Handle, uExitCode: int): WINBOOL {.stdcall, dynlib: "kernel32", importc: "TerminateProcess".} -proc getExitCodeProcess*(hProcess: THandle, lpExitCode: var int32): WINBOOL {. +proc getExitCodeProcess*(hProcess: Handle, lpExitCode: var int32): WINBOOL {. stdcall, dynlib: "kernel32", importc: "GetExitCodeProcess".} -proc getStdHandle*(nStdHandle: int32): THandle {.stdcall, dynlib: "kernel32", +proc getStdHandle*(nStdHandle: int32): Handle {.stdcall, dynlib: "kernel32", importc: "GetStdHandle".} -proc setStdHandle*(nStdHandle: int32, hHandle: THandle): WINBOOL {.stdcall, +proc setStdHandle*(nStdHandle: int32, hHandle: Handle): WINBOOL {.stdcall, dynlib: "kernel32", importc: "SetStdHandle".} -proc flushFileBuffers*(hFile: THandle): WINBOOL {.stdcall, dynlib: "kernel32", +proc flushFileBuffers*(hFile: Handle): WINBOOL {.stdcall, dynlib: "kernel32", importc: "FlushFileBuffers".} proc getLastError*(): int32 {.importc: "GetLastError", @@ -193,7 +199,7 @@ when useWinUnicode: proc setEnvironmentVariableW*(lpName, lpValue: WideCString): int32 {. stdcall, dynlib: "kernel32", importc: "SetEnvironmentVariableW".} - proc getModuleFileNameW*(handle: THandle, buf: WideCString, + proc getModuleFileNameW*(handle: Handle, buf: WideCString, size: int32): int32 {.importc: "GetModuleFileNameW", dynlib: "kernel32", stdcall.} else: @@ -208,7 +214,7 @@ else: proc setEnvironmentVariableA*(lpName, lpValue: cstring): int32 {. stdcall, dynlib: "kernel32", importc: "SetEnvironmentVariableA".} - proc getModuleFileNameA*(handle: THandle, buf: cstring, size: int32): int32 {. + proc getModuleFileNameA*(handle: Handle, buf: cstring, size: int32): int32 {. importc: "GetModuleFileNameA", dynlib: "kernel32", stdcall.} when useWinUnicode: @@ -239,34 +245,35 @@ const MAX_PATH* = 260 type - TWIN32_FIND_DATA* {.pure.} = object + WIN32_FIND_DATA* {.pure.} = object dwFileAttributes*: int32 - ftCreationTime*: TFILETIME - ftLastAccessTime*: TFILETIME - ftLastWriteTime*: TFILETIME + ftCreationTime*: FILETIME + ftLastAccessTime*: FILETIME + ftLastWriteTime*: FILETIME nFileSizeHigh*: int32 nFileSizeLow*: int32 dwReserved0: int32 dwReserved1: int32 - cFileName*: array[0..(MAX_PATH) - 1, TWinChar] - cAlternateFileName*: array[0..13, TWinChar] + cFileName*: array[0..(MAX_PATH) - 1, WinChar] + cAlternateFileName*: array[0..13, WinChar] +{.deprecated: [TWIN32_FIND_DATA: WIN32_FIND_DATA].} when useWinUnicode: proc findFirstFileW*(lpFileName: WideCString, - lpFindFileData: var TWIN32_FIND_DATA): THandle {. + lpFindFileData: var WIN32_FIND_DATA): Handle {. stdcall, dynlib: "kernel32", importc: "FindFirstFileW".} - proc findNextFileW*(hFindFile: THandle, - lpFindFileData: var TWIN32_FIND_DATA): int32 {. + proc findNextFileW*(hFindFile: Handle, + lpFindFileData: var WIN32_FIND_DATA): int32 {. stdcall, dynlib: "kernel32", importc: "FindNextFileW".} else: proc findFirstFileA*(lpFileName: cstring, - lpFindFileData: var TWIN32_FIND_DATA): THANDLE {. + lpFindFileData: var WIN32_FIND_DATA): THANDLE {. stdcall, dynlib: "kernel32", importc: "FindFirstFileA".} proc findNextFileA*(hFindFile: THANDLE, - lpFindFileData: var TWIN32_FIND_DATA): int32 {. + lpFindFileData: var WIN32_FIND_DATA): int32 {. stdcall, dynlib: "kernel32", importc: "FindNextFileA".} -proc findClose*(hFindFile: THandle) {.stdcall, dynlib: "kernel32", +proc findClose*(hFindFile: Handle) {.stdcall, dynlib: "kernel32", importc: "FindClose".} when useWinUnicode: @@ -326,32 +333,32 @@ else: proc getCommandLineA*(): cstring {. importc: "GetCommandLineA", stdcall, dynlib: "kernel32".} -proc rdFileTime*(f: TFILETIME): int64 = +proc rdFileTime*(f: FILETIME): int64 = result = ze64(f.dwLowDateTime) or (ze64(f.dwHighDateTime) shl 32) -proc rdFileSize*(f: TWIN32_FIND_DATA): int64 = +proc rdFileSize*(f: WIN32_FIND_DATA): int64 = result = ze64(f.nFileSizeLow) or (ze64(f.nFileSizeHigh) shl 32) -proc getSystemTimeAsFileTime*(lpSystemTimeAsFileTime: var TFILETIME) {. +proc getSystemTimeAsFileTime*(lpSystemTimeAsFileTime: var FILETIME) {. importc: "GetSystemTimeAsFileTime", dynlib: "kernel32", stdcall.} proc sleep*(dwMilliseconds: int32){.stdcall, dynlib: "kernel32", importc: "Sleep".} when useWinUnicode: - proc shellExecuteW*(HWND: THandle, lpOperation, lpFile, + proc shellExecuteW*(HWND: Handle, lpOperation, lpFile, lpParameters, lpDirectory: WideCString, - nShowCmd: int32): THandle{. + nShowCmd: int32): Handle{. stdcall, dynlib: "shell32.dll", importc: "ShellExecuteW".} else: - proc shellExecuteA*(HWND: THandle, lpOperation, lpFile, + proc shellExecuteA*(HWND: Handle, lpOperation, lpFile, lpParameters, lpDirectory: cstring, - nShowCmd: int32): THandle{. + nShowCmd: int32): Handle{. stdcall, dynlib: "shell32.dll", importc: "ShellExecuteA".} -proc getFileInformationByHandle*(hFile: THandle, - lpFileInformation: ptr TBY_HANDLE_FILE_INFORMATION): WINBOOL{. +proc getFileInformationByHandle*(hFile: Handle, + lpFileInformation: ptr BY_HANDLE_FILE_INFORMATION): WINBOOL{. stdcall, dynlib: "kernel32", importc: "GetFileInformationByHandle".} const @@ -374,7 +381,6 @@ proc wsaGetLastError*(): cint {.importc: "WSAGetLastError", dynlib: ws2dll.} type SocketHandle* = distinct int - {.deprecated: [TSocketHandle: SocketHandle].} type @@ -433,7 +439,7 @@ type h_length*: int16 h_addr_list*: cstringArray - TFdSet* = object + FdSet* = object fd_count*: cint # unsigned fd_array*: array[0..FD_SETSIZE-1, SocketHandle] @@ -451,12 +457,11 @@ type ai_next*: ptr AddrInfo ## Pointer to next in list. SockLen* = cuint - {.deprecated: [TSockaddr_in: Sockaddr_in, TAddrinfo: AddrInfo, TSockAddr: SockAddr, TSockLen: SockLen, TTimeval: Timeval, TWSADATA: WSADATA, Thostent: Hostent, TServent: Servent, TInAddr: InAddr, Tin6_addr: In6_addr, Tsockaddr_in6: Sockaddr_in6, - Tsockaddr_in6_old: Sockaddr_in6_old].} + Tsockaddr_in6_old: Sockaddr_in6_old, TFdSet: FdSet].} var @@ -520,7 +525,7 @@ proc recv*(s: SocketHandle, buf: pointer, len, flags: cint): cint {. proc recvfrom*(s: SocketHandle, buf: cstring, len, flags: cint, fromm: ptr SockAddr, fromlen: ptr SockLen): cint {. stdcall, importc: "recvfrom", dynlib: ws2dll.} -proc select*(nfds: cint, readfds, writefds, exceptfds: ptr TFdSet, +proc select*(nfds: cint, readfds, writefds, exceptfds: ptr FdSet, timeout: ptr Timeval): cint {. stdcall, importc: "select", dynlib: ws2dll.} proc send*(s: SocketHandle, buf: pointer, len, flags: cint): cint {. @@ -540,18 +545,18 @@ proc getnameinfo*(a1: ptr SockAddr, a2: SockLen, proc inet_addr*(cp: cstring): int32 {. stdcall, importc: "inet_addr", dynlib: ws2dll.} -proc WSAFDIsSet(s: SocketHandle, set: var TFdSet): bool {. +proc WSAFDIsSet(s: SocketHandle, set: var FdSet): bool {. stdcall, importc: "__WSAFDIsSet", dynlib: ws2dll, noSideEffect.} -proc FD_ISSET*(socket: SocketHandle, set: var TFdSet): cint = +proc FD_ISSET*(socket: SocketHandle, set: var FdSet): cint = result = if WSAFDIsSet(socket, set): 1'i32 else: 0'i32 -proc FD_SET*(socket: SocketHandle, s: var TFdSet) = +proc FD_SET*(socket: SocketHandle, s: var FdSet) = if s.fd_count < FD_SETSIZE: s.fd_array[int(s.fd_count)] = socket inc(s.fd_count) -proc FD_ZERO*(s: var TFdSet) = +proc FD_ZERO*(s: var FdSet) = s.fd_count = 0 proc wsaStartup*(wVersionRequired: int16, WSData: ptr WSAData): cint {. @@ -571,8 +576,9 @@ const MAXIMUM_WAIT_OBJECTS* = 0x00000040 type - TWOHandleArray* = array[0..MAXIMUM_WAIT_OBJECTS - 1, THandle] - PWOHandleArray* = ptr TWOHandleArray + WOHandleArray* = array[0..MAXIMUM_WAIT_OBJECTS - 1, Handle] + PWOHandleArray* = ptr WOHandleArray +{.deprecated: [TWOHandleArray: WOHandleArray].} proc waitForMultipleObjects*(nCount: DWORD, lpHandles: PWOHandleArray, bWaitAll: WINBOOL, dwMilliseconds: DWORD): DWORD{. @@ -613,7 +619,7 @@ when useWinUnicode: proc createFileW*(lpFileName: WideCString, dwDesiredAccess, dwShareMode: DWORD, lpSecurityAttributes: pointer, dwCreationDisposition, dwFlagsAndAttributes: DWORD, - hTemplateFile: THandle): THandle {. + hTemplateFile: Handle): Handle {. stdcall, dynlib: "kernel32", importc: "CreateFileW".} proc deleteFileW*(pathName: WideCString): int32 {. importc: "DeleteFileW", dynlib: "kernel32", stdcall.} @@ -626,28 +632,28 @@ else: proc deleteFileA*(pathName: cstring): int32 {. importc: "DeleteFileA", dynlib: "kernel32", stdcall.} -proc setEndOfFile*(hFile: THandle): WINBOOL {.stdcall, dynlib: "kernel32", +proc setEndOfFile*(hFile: Handle): WINBOOL {.stdcall, dynlib: "kernel32", importc: "SetEndOfFile".} -proc setFilePointer*(hFile: THandle, lDistanceToMove: LONG, +proc setFilePointer*(hFile: Handle, lDistanceToMove: LONG, lpDistanceToMoveHigh: ptr LONG, dwMoveMethod: DWORD): DWORD {. stdcall, dynlib: "kernel32", importc: "SetFilePointer".} -proc getFileSize*(hFile: THandle, lpFileSizeHigh: ptr DWORD): DWORD{.stdcall, +proc getFileSize*(hFile: Handle, lpFileSizeHigh: ptr DWORD): DWORD{.stdcall, dynlib: "kernel32", importc: "GetFileSize".} -proc mapViewOfFileEx*(hFileMappingObject: THandle, dwDesiredAccess: DWORD, +proc mapViewOfFileEx*(hFileMappingObject: Handle, dwDesiredAccess: DWORD, dwFileOffsetHigh, dwFileOffsetLow: DWORD, dwNumberOfBytesToMap: DWORD, lpBaseAddress: pointer): pointer{. stdcall, dynlib: "kernel32", importc: "MapViewOfFileEx".} -proc createFileMappingW*(hFile: THandle, +proc createFileMappingW*(hFile: Handle, lpFileMappingAttributes: pointer, flProtect, dwMaximumSizeHigh: DWORD, dwMaximumSizeLow: DWORD, - lpName: pointer): THandle {. + lpName: pointer): Handle {. stdcall, dynlib: "kernel32", importc: "CreateFileMappingW".} when not useWinUnicode: @@ -661,23 +667,24 @@ proc unmapViewOfFile*(lpBaseAddress: pointer): WINBOOL {.stdcall, dynlib: "kernel32", importc: "UnmapViewOfFile".} type - TOVERLAPPED* {.pure, inheritable.} = object + OVERLAPPED* {.pure, inheritable.} = object internal*: PULONG internalHigh*: PULONG offset*: DWORD offsetHigh*: DWORD - hEvent*: THandle + hEvent*: Handle - POVERLAPPED* = ptr TOVERLAPPED + POVERLAPPED* = ptr OVERLAPPED POVERLAPPED_COMPLETION_ROUTINE* = proc (para1: DWORD, para2: DWORD, para3: POVERLAPPED){.stdcall.} - TGUID* {.final, pure.} = object + GUID* {.final, pure.} = object D1*: int32 D2*: int16 D3*: int16 D4*: array [0..7, int8] +{.deprecated: [TOVERLAPPED: OVERLAPPED, TGUID: GUID].} const ERROR_IO_PENDING* = 997 # a.k.a WSA_IO_PENDING @@ -689,18 +696,18 @@ const WSAETIMEDOUT* = 10060 ERROR_NETNAME_DELETED* = 64 -proc createIoCompletionPort*(FileHandle: THandle, ExistingCompletionPort: THandle, +proc createIoCompletionPort*(FileHandle: Handle, ExistingCompletionPort: Handle, CompletionKey: DWORD, - NumberOfConcurrentThreads: DWORD): THandle{.stdcall, + NumberOfConcurrentThreads: DWORD): Handle{.stdcall, dynlib: "kernel32", importc: "CreateIoCompletionPort".} -proc getQueuedCompletionStatus*(CompletionPort: THandle, +proc getQueuedCompletionStatus*(CompletionPort: Handle, lpNumberOfBytesTransferred: PDWORD, lpCompletionKey: PULONG, lpOverlapped: ptr POVERLAPPED, dwMilliseconds: DWORD): WINBOOL{.stdcall, dynlib: "kernel32", importc: "GetQueuedCompletionStatus".} -proc getOverlappedResult*(hFile: THandle, lpOverlapped: TOVERLAPPED, +proc getOverlappedResult*(hFile: Handle, lpOverlapped: OVERLAPPED, lpNumberOfBytesTransferred: var DWORD, bWait: WINBOOL): WINBOOL{. stdcall, dynlib: "kernel32", importc: "GetOverlappedResult".} @@ -717,11 +724,11 @@ const SO_UPDATE_ACCEPT_CONTEXT* = 0x700B var - WSAID_CONNECTEX*: TGUID = TGUID(D1: 0x25a207b9, D2: 0xddf3'i16, D3: 0x4660, D4: [ + WSAID_CONNECTEX*: GUID = GUID(D1: 0x25a207b9, D2: 0xddf3'i16, D3: 0x4660, D4: [ 0x8e'i8, 0xe9'i8, 0x76'i8, 0xe5'i8, 0x8c'i8, 0x74'i8, 0x06'i8, 0x3e'i8]) - WSAID_ACCEPTEX*: TGUID = TGUID(D1: 0xb5367df1'i32, D2: 0xcbac'i16, D3: 0x11cf, D4: [ + WSAID_ACCEPTEX*: GUID = GUID(D1: 0xb5367df1'i32, D2: 0xcbac'i16, D3: 0x11cf, D4: [ 0x95'i8, 0xca'i8, 0x00'i8, 0x80'i8, 0x5f'i8, 0x48'i8, 0xa1'i8, 0x92'i8]) - WSAID_GETACCEPTEXSOCKADDRS*: TGUID = TGUID(D1: 0xb5367df2'i32, D2: 0xcbac'i16, D3: 0x11cf, D4: [ + WSAID_GETACCEPTEXSOCKADDRS*: GUID = GUID(D1: 0xb5367df2'i32, D2: 0xcbac'i16, D3: 0x11cf, D4: [ 0x95'i8, 0xca'i8, 0x00'i8, 0x80'i8, 0x5f'i8, 0x48'i8, 0xa1'i8, 0x92'i8]) proc WSAIoctl*(s: SocketHandle, dwIoControlCode: DWORD, lpvInBuffer: pointer, @@ -745,13 +752,13 @@ proc WSASend*(s: SocketHandle, buf: ptr TWSABuf, bufCount: DWORD, completionProc: POVERLAPPED_COMPLETION_ROUTINE): cint {. stdcall, importc: "WSASend", dynlib: "Ws2_32.dll".} -proc get_osfhandle*(fd:FileHandle): THandle {. +proc get_osfhandle*(fd:FileHandle): Handle {. importc: "_get_osfhandle", header:"".} proc getSystemTimes*(lpIdleTime, lpKernelTime, - lpUserTime: var TFILETIME): WINBOOL {.stdcall, + lpUserTime: var FILETIME): WINBOOL {.stdcall, dynlib: "kernel32", importc: "GetSystemTimes".} -proc getProcessTimes*(hProcess: THandle; lpCreationTime, lpExitTime, - lpKernelTime, lpUserTime: var TFILETIME): WINBOOL {.stdcall, +proc getProcessTimes*(hProcess: Handle; lpCreationTime, lpExitTime, + lpKernelTime, lpUserTime: var FILETIME): WINBOOL {.stdcall, dynlib: "kernel32", importc: "GetProcessTimes".} From b2bc5440aa9748b0c7cf05688071cf012442e6ef Mon Sep 17 00:00:00 2001 From: pdw Date: Sun, 24 May 2015 22:43:13 -0500 Subject: [PATCH 0356/1263] lib/wrappers/c-r - Dropped 'T' from types --- lib/wrappers/claro.nim | 814 ++++++++++++++------------- lib/wrappers/expat.nim | 218 +++---- lib/wrappers/joyent_http_parser.nim | 33 +- lib/wrappers/libcurl.nim | 252 +++++---- lib/wrappers/libffi/libffi.nim | 71 +-- lib/wrappers/libsvm.nim | 61 +- lib/wrappers/libuv.nim | 206 ++++--- lib/wrappers/mysql.nim | 286 +++++----- lib/wrappers/odbcsql.nim | 199 +++---- lib/wrappers/pdcurses.nim | 456 +++++++-------- lib/wrappers/postgres.nim | 51 +- lib/wrappers/readline/history.nim | 36 +- lib/wrappers/readline/readline.nim | 55 +- lib/wrappers/readline/rltypedefs.nim | 29 +- 14 files changed, 1458 insertions(+), 1309 deletions(-) diff --git a/lib/wrappers/claro.nim b/lib/wrappers/claro.nim index 0fb0882bf..41956c28a 100644 --- a/lib/wrappers/claro.nim +++ b/lib/wrappers/claro.nim @@ -35,61 +35,62 @@ else: import cairo type - TNode* {.pure.} = object - next*: ptr TNode - prev*: ptr TNode # pointer to real structure + Node* {.pure.} = object + next*: ptr Node + prev*: ptr Node # pointer to real structure data*: pointer - TList* {.pure.} = object - head*: ptr TNode - tail*: ptr TNode + List* {.pure.} = object + head*: ptr Node + tail*: ptr Node count*: int32 - +{.deprecated: [TNode: Node, TList: List].} proc list_init*(){.cdecl, importc: "list_init", dynlib: clarodll.} -proc list_create*(list: ptr TList){.cdecl, importc: "list_create", +proc list_create*(list: ptr List){.cdecl, importc: "list_create", dynlib: clarodll.} -proc node_create*(): ptr TNode{.cdecl, importc: "node_create", +proc node_create*(): ptr Node{.cdecl, importc: "node_create", dynlib: clarodll.} -proc node_free*(n: ptr TNode){.cdecl, importc: "node_free", dynlib: clarodll.} -proc node_add*(data: pointer, n: ptr TNode, L: ptr TList){.cdecl, +proc node_free*(n: ptr Node){.cdecl, importc: "node_free", dynlib: clarodll.} +proc node_add*(data: pointer, n: ptr Node, L: ptr List){.cdecl, importc: "node_add", dynlib: clarodll.} -proc node_prepend*(data: pointer, n: ptr TNode, L: ptr TList){.cdecl, +proc node_prepend*(data: pointer, n: ptr Node, L: ptr List){.cdecl, importc: "node_prepend", dynlib: clarodll.} -proc node_del*(n: ptr TNode, L: ptr TList){.cdecl, importc: "node_del", +proc node_del*(n: ptr Node, L: ptr List){.cdecl, importc: "node_del", dynlib: clarodll.} -proc node_find*(data: pointer, L: ptr TList): ptr TNode{.cdecl, +proc node_find*(data: pointer, L: ptr List): ptr Node{.cdecl, importc: "node_find", dynlib: clarodll.} -proc node_move*(n: ptr TNode, oldlist: ptr TList, newlist: ptr TList){. +proc node_move*(n: ptr Node, oldlist: ptr List, newlist: ptr List){. cdecl, importc: "node_move", dynlib: clarodll.} type - TClaroObj*{.pure, inheritable.} = object + ClaroObj*{.pure, inheritable.} = object typ*: array[0..64 - 1, char] destroy_pending*: cint - event_handlers*: TList - children*: TList - parent*: ptr TClaroObj + event_handlers*: List + children*: List + parent*: ptr ClaroObj appdata*: pointer # !! this is for APPLICATION USE ONLY !! - TEvent*{.pure.} = object - obj*: ptr TClaroObj # the object which this event was sent to + Event*{.pure.} = object + obj*: ptr ClaroObj # the object which this event was sent to name*: array[0..64 - 1, char] handled*: cint arg_num*: cint # number of arguments format*: array[0..16 - 1, char] # format of the arguments sent arglist*: ptr pointer # list of args, as per format. - TEventFunc* = proc (obj: ptr TClaroObj, event: ptr TEvent){.cdecl.} - TEventIfaceFunc* = proc (obj: ptr TClaroObj, event: ptr TEvent, + EventFunc* = proc (obj: ptr ClaroObj, event: ptr Event){.cdecl.} + EventIfaceFunc* = proc (obj: ptr ClaroObj, event: ptr Event, data: pointer){.cdecl.} - TEventHandler*{.pure.} = object + EventHandler*{.pure.} = object typ*: array[0..32 - 1, char] data*: pointer - fun*: TEventFunc # the function that handles this event - + fun*: EventFunc # the function that handles this event +{.deprecated: [TEvent: Event, TEventFunc: EventFunc, TClaroObj: ClaroObj, + TEventIfaceFunc: EventIfaceFunc, TEventHandler: EventHandler].} -# #define event_handler(n) void n ( TClaroObj *object, event_t *event ) +# #define event_handler(n) void n ( ClaroObj *object, event_t *event ) #CLVEXP list_t object_list; proc object_init*(){.cdecl, importc: "object_init", dynlib: clarodll.} @@ -99,36 +100,36 @@ proc object_override_next_size*(size: cint){.cdecl, ## Overrides the size of next object to be created, providing the ## size is more than is requested by default. ## - ## `size` specifies the full size, which is greater than both TClaroObj + ## `size` specifies the full size, which is greater than both ClaroObj ## and the size that will be requested automatically. -proc event_get_arg_ptr*(e: ptr TEvent, arg: cint): pointer{.cdecl, +proc event_get_arg_ptr*(e: ptr Event, arg: cint): pointer{.cdecl, importc: "event_get_arg_ptr", dynlib: clarodll.} -proc event_get_arg_double*(e: ptr TEvent, arg: cint): cdouble{.cdecl, +proc event_get_arg_double*(e: ptr Event, arg: cint): cdouble{.cdecl, importc: "event_get_arg_double", dynlib: clarodll.} -proc event_get_arg_int*(e: ptr TEvent, arg: cint): cint{.cdecl, +proc event_get_arg_int*(e: ptr Event, arg: cint): cint{.cdecl, importc: "event_get_arg_int", dynlib: clarodll.} -proc object_create*(parent: ptr TClaroObj, size: int32, - typ: cstring): ptr TClaroObj{. +proc object_create*(parent: ptr ClaroObj, size: int32, + typ: cstring): ptr ClaroObj{. cdecl, importc: "object_create", dynlib: clarodll.} -proc object_destroy*(obj: ptr TClaroObj){.cdecl, importc: "object_destroy", +proc object_destroy*(obj: ptr ClaroObj){.cdecl, importc: "object_destroy", dynlib: clarodll.} -proc object_set_parent*(obj: ptr TClaroObj, parent: ptr TClaroObj){.cdecl, +proc object_set_parent*(obj: ptr ClaroObj, parent: ptr ClaroObj){.cdecl, importc: "object_set_parent", dynlib: clarodll.} -##define object_cmptype(o,t) (!strcmp(((TClaroObj *)o)->type,t)) +##define object_cmptype(o,t) (!strcmp(((ClaroObj *)o)->type,t)) # event functions -proc object_addhandler*(obj: ptr TClaroObj, event: cstring, - fun: TEventFunc){.cdecl, +proc object_addhandler*(obj: ptr ClaroObj, event: cstring, + fun: EventFunc){.cdecl, importc: "object_addhandler", dynlib: clarodll.} -proc object_addhandler_interface*(obj: ptr TClaroObj, event: cstring, - fun: TEventFunc, data: pointer){.cdecl, +proc object_addhandler_interface*(obj: ptr ClaroObj, event: cstring, + fun: EventFunc, data: pointer){.cdecl, importc: "object_addhandler_interface", dynlib: clarodll.} -proc event_send*(obj: ptr TClaroObj, event: cstring, fmt: cstring): cint{. +proc event_send*(obj: ptr ClaroObj, event: cstring, fmt: cstring): cint{. varargs, cdecl, importc: "event_send", dynlib: clarodll.} -proc event_get_name*(event: ptr TEvent): cstring{.cdecl, +proc event_get_name*(event: ptr Event): cstring{.cdecl, importc: "event_get_name", dynlib: clarodll.} proc claro_base_init(){.cdecl, importc: "claro_base_init", dynlib: clarodll.} proc claro_loop*(){.cdecl, importc: "claro_loop", dynlib: clarodll.} @@ -143,19 +144,19 @@ const cWidgetCustomDraw* = (1 shl 25) type - TBounds*{.pure.} = object + Bounds*{.pure.} = object x*: cint y*: cint w*: cint h*: cint - owner*: ptr TClaroObj - + owner*: ptr ClaroObj +{.deprecated: [TBounds: Bounds].} const cSizeRequestChanged* = 1 type - TFont*{.pure.} = object + Font*{.pure.} = object used*: cint face*: cstring size*: cint @@ -164,30 +165,31 @@ type decoration*: cint native*: pointer - TColor*{.pure.} = object + Color*{.pure.} = object used*: cint r*: cfloat g*: cfloat b*: cfloat a*: cfloat - TWidget* {.pure.} = object of TClaroObj - size_req*: ptr TBounds - size*: TBounds - size_ct*: TBounds + Widget* {.pure.} = object of ClaroObj + size_req*: ptr Bounds + size*: Bounds + size_ct*: Bounds supports_alpha*: cint size_flags*: cint flags*: cint visible*: cint notify_flags*: cint - font*: TFont + font*: Font native*: pointer # native widget ndata*: pointer # additional native data container*: pointer # native widget container (if not ->native) naddress*: array[0..3, pointer] # addressed for something # we override or need to remember - -proc clipboard_set_text*(w: ptr TWidget, text: cstring): cint{.cdecl, +{.deprecated: [TFont: Font, TColor: Color, TWidget: Widget].} + +proc clipboard_set_text*(w: ptr Widget, text: cstring): cint{.cdecl, importc: "clipboard_set_text", dynlib: clarodll.} ## Sets the (text) clipboard to the specified text value. ## @@ -207,7 +209,7 @@ const cFontDecorationUnderline* = 1 -proc widget_set_font*(widget: ptr TClaroObj, face: cstring, size: cint, +proc widget_set_font*(widget: ptr ClaroObj, face: cstring, size: cint, weight: cint, slant: cint, decoration: cint){.cdecl, importc: "widget_set_font", dynlib: clarodll.} ## Sets the font details of the specified widget. @@ -219,7 +221,7 @@ proc widget_set_font*(widget: ptr TClaroObj, face: cstring, size: cint, ## `slant` The sland of the font ## `decoration` The decoration of the font -proc widget_font_string_width*(widget: ptr TClaroObj, text: cstring, +proc widget_font_string_width*(widget: ptr ClaroObj, text: cstring, chars: cint): cint {. cdecl, importc: "widget_font_string_width", dynlib: clarodll.} ## Calculates the pixel width of the text in the widget's font. @@ -230,16 +232,16 @@ const CLARO_APPLICATION* = "claro.graphics" type - TImage* {.pure.} = object of TClaroObj + Image* {.pure.} = object of ClaroObj width*: cint height*: cint native*: pointer native2*: pointer native3*: pointer icon*: pointer +{.deprecated: [TImage: Image].} - -proc image_load*(parent: ptr TClaroObj, file: cstring): ptr TImage{.cdecl, +proc image_load*(parent: ptr ClaroObj, file: cstring): ptr Image{.cdecl, importc: "image_load", dynlib: clarodll.} ## Loads an image from a file and returns a new image object. ## @@ -249,8 +251,8 @@ proc image_load*(parent: ptr TClaroObj, file: cstring): ptr TImage{.cdecl, ## ## `Parent` object (usually the application's main window), can be nil. -proc image_load_inline_png*(parent: ptr TClaroObj, data: cstring, - len: cint): ptr TImage{.cdecl, +proc image_load_inline_png*(parent: ptr ClaroObj, data: cstring, + len: cint): ptr Image{.cdecl, importc: "image_load_inline_png", dynlib: clarodll.} ## Loads an image from inline data and returns a new image object. ## `Parent` object (usually the application's main window), can be nil. @@ -262,10 +264,11 @@ when true: else: # status icons are not supported on all platforms yet: type - TStatusIcon* {.pure.} = object of TClaroObj - icon*: ptr TImage + StatusIcon* {.pure.} = object of ClaroObj + icon*: ptr Image native*: pointer native2*: pointer + {.deprecated: [TStatusIcon: StatusIcon].} #* # \brief Creates a status icon @@ -277,8 +280,8 @@ else: # \return New status_icon_t object # - proc status_icon_create*(parent: ptr TClaroObj, icon: ptr TImage, - flags: cint): ptr TStatusIcon {. + proc status_icon_create*(parent: ptr ClaroObj, icon: ptr Image, + flags: cint): ptr StatusIcon {. cdecl, importc: "status_icon_create", dynlib: clarodll.} #* @@ -288,7 +291,7 @@ else: # \param image The image object for the icon # - proc status_icon_set_icon*(status: ptr TStatusIcon, icon: ptr TImage){.cdecl, + proc status_icon_set_icon*(status: ptr StatusIcon, icon: ptr Image){.cdecl, importc: "status_icon_set_icon", dynlib: clarodll.} #* @@ -298,7 +301,7 @@ else: # \param menu The menu object for the popup menu # - proc status_icon_set_menu*(status: ptr TStatusIcon, menu: ptr TClaroObj){.cdecl, + proc status_icon_set_menu*(status: ptr StatusIcon, menu: ptr ClaroObj){.cdecl, importc: "status_icon_set_menu", dynlib: clarodll.} #* # \brief sets the status icon's visibility @@ -307,7 +310,7 @@ else: # \param visible whether the status icon is visible or not # - proc status_icon_set_visible*(status: ptr TStatusIcon, visible: cint){.cdecl, + proc status_icon_set_visible*(status: ptr StatusIcon, visible: cint){.cdecl, importc: "status_icon_set_visible", dynlib: clarodll.} #* # \brief sets the status icon's tooltip @@ -316,7 +319,7 @@ else: # \param tooltip Tooltip string # - proc status_icon_set_tooltip*(status: ptr TStatusIcon, tooltip: cstring){.cdecl, + proc status_icon_set_tooltip*(status: ptr StatusIcon, tooltip: cstring){.cdecl, importc: "status_icon_set_tooltip", dynlib: clarodll.} #* @@ -325,7 +328,7 @@ else: # \param widget A widget # -proc widget_show*(widget: ptr TWidget){.cdecl, importc: "widget_show", +proc widget_show*(widget: ptr Widget){.cdecl, importc: "widget_show", dynlib: clarodll.} #* # \brief Makes the specified widget invisible. @@ -333,7 +336,7 @@ proc widget_show*(widget: ptr TWidget){.cdecl, importc: "widget_show", # \param widget A widget # -proc widget_hide*(widget: ptr TWidget){.cdecl, importc: "widget_hide", +proc widget_hide*(widget: ptr Widget){.cdecl, importc: "widget_hide", dynlib: clarodll.} #* # \brief Enables the widget, allowing focus @@ -341,7 +344,7 @@ proc widget_hide*(widget: ptr TWidget){.cdecl, importc: "widget_hide", # \param widget A widget # -proc widget_enable*(widget: ptr TWidget){.cdecl, importc: "widget_enable", +proc widget_enable*(widget: ptr Widget){.cdecl, importc: "widget_enable", dynlib: clarodll.} #* # \brief Disables the widget @@ -351,7 +354,7 @@ proc widget_enable*(widget: ptr TWidget){.cdecl, importc: "widget_enable", # \param widget A widget # -proc widget_disable*(widget: ptr TWidget){.cdecl, importc: "widget_disable", +proc widget_disable*(widget: ptr Widget){.cdecl, importc: "widget_disable", dynlib: clarodll.} #* # \brief Give focus to the specified widget @@ -359,7 +362,7 @@ proc widget_disable*(widget: ptr TWidget){.cdecl, importc: "widget_disable", # \param widget A widget # -proc widget_focus*(widget: ptr TWidget){.cdecl, importc: "widget_focus", +proc widget_focus*(widget: ptr Widget){.cdecl, importc: "widget_focus", dynlib: clarodll.} #* # \brief Closes a widget @@ -372,7 +375,7 @@ proc widget_focus*(widget: ptr TWidget){.cdecl, importc: "widget_focus", # \param widget A widget # -proc widget_close*(widget: ptr TWidget){.cdecl, importc: "widget_close", +proc widget_close*(widget: ptr Widget){.cdecl, importc: "widget_close", dynlib: clarodll.} #* # \brief Retrieve the screen offset of the specified widget. @@ -384,7 +387,7 @@ proc widget_close*(widget: ptr TWidget){.cdecl, importc: "widget_close", # \param dy Pointer to the location to place the Y position. # -proc widget_screen_offset*(widget: ptr TWidget, dx: ptr cint, dy: ptr cint){. +proc widget_screen_offset*(widget: ptr Widget, dx: ptr cint, dy: ptr cint){. cdecl, importc: "widget_screen_offset", dynlib: clarodll.} #* # \brief Sets the additional notify events that should be sent. @@ -397,16 +400,17 @@ proc widget_screen_offset*(widget: ptr TWidget, dx: ptr cint, dy: ptr cint){. # \param flags Any number of cWidgetNotify flags ORed together. # -proc widget_set_notify*(widget: ptr TWidget, flags: cint){.cdecl, +proc widget_set_notify*(widget: ptr Widget, flags: cint){.cdecl, importc: "widget_set_notify", dynlib: clarodll.} type - TCursorType* {.size: sizeof(cint).} = enum + CursorType* {.size: sizeof(cint).} = enum cCursorNormal = 0, cCursorTextEdit = 1, cCursorWait = 2, cCursorPoint = 3 +{.deprecated: [TCursorType: CursorType].} #* # \brief Sets the mouse cursor for the widget @@ -415,7 +419,7 @@ type # \param cursor A valid cCursor* value # -proc widget_set_cursor*(widget: ptr TWidget, cursor: TCursorType){.cdecl, +proc widget_set_cursor*(widget: ptr Widget, cursor: CursorType){.cdecl, importc: "widget_set_cursor", dynlib: clarodll.} #* @@ -426,7 +430,7 @@ proc widget_set_cursor*(widget: ptr TWidget, cursor: TCursorType){.cdecl, # \return The keycode of the key pressed. # -proc widget_get_notify_key*(widget: ptr TWidget, event: ptr TEvent): cint{. +proc widget_get_notify_key*(widget: ptr Widget, event: ptr Event): cint{. cdecl, importc: "widget_get_notify_key", dynlib: clarodll.} #* @@ -443,7 +447,7 @@ proc widget_get_notify_key*(widget: ptr TWidget, event: ptr TEvent): cint{. # \param h The new height # -proc bounds_set*(bounds: ptr TBounds, x: cint, y: cint, w: cint, h: cint){. +proc bounds_set*(bounds: ptr Bounds, x: cint, y: cint, w: cint, h: cint){. cdecl, importc: "bounds_set", dynlib: clarodll.} #* # \brief Create a new bounds object @@ -457,13 +461,13 @@ proc bounds_set*(bounds: ptr TBounds, x: cint, y: cint, w: cint, h: cint){. # \return A new bounds_t structure # -proc new_bounds*(x: cint, y: cint, w: cint, h: cint): ptr TBounds{.cdecl, +proc new_bounds*(x: cint, y: cint, w: cint, h: cint): ptr Bounds{.cdecl, importc: "new_bounds", dynlib: clarodll.} -proc get_req_bounds*(widget: ptr TWidget): ptr TBounds{.cdecl, +proc get_req_bounds*(widget: ptr Widget): ptr Bounds{.cdecl, importc: "get_req_bounds", dynlib: clarodll.} var - noBoundsVar: TBounds # set to all zero which is correct + noBoundsVar: Bounds # set to all zero which is correct template noBounds*: expr = (addr(bind noBoundsVar)) @@ -473,7 +477,7 @@ template noBounds*: expr = (addr(bind noBoundsVar)) # \param widget A widget # -proc widget_pre_init*(widget: ptr TWidget){.cdecl, importc: "widget_pre_init", +proc widget_pre_init*(widget: ptr Widget){.cdecl, importc: "widget_pre_init", dynlib: clarodll.} #* \internal # \brief Internal post-inititalisation hook @@ -481,7 +485,7 @@ proc widget_pre_init*(widget: ptr TWidget){.cdecl, importc: "widget_pre_init", # \param widget A widget # -proc widget_post_init*(widget: ptr TWidget){.cdecl, +proc widget_post_init*(widget: ptr Widget){.cdecl, importc: "widget_post_init", dynlib: clarodll.} #* \internal # \brief Internal resize event handler @@ -490,7 +494,7 @@ proc widget_post_init*(widget: ptr TWidget){.cdecl, # \param event An event resource # -proc widget_resized_handle*(obj: ptr TWidget, event: ptr TEvent){.cdecl, +proc widget_resized_handle*(obj: ptr Widget, event: ptr Event){.cdecl, importc: "widget_resized_handle", dynlib: clarodll.} # CLVEXP bounds_t no_bounds; #* \internal @@ -507,11 +511,12 @@ proc widget_resized_handle*(obj: ptr TWidget, event: ptr TEvent){.cdecl, # type - TcgraphicsCreateFunction* = proc (widget: ptr TWidget) {.cdecl.} + CgraphicsCreateFunction* = proc (widget: ptr Widget) {.cdecl.} +{.deprecated: [TcgraphicsCreateFunction: CgraphicsCreateFunction].} -proc newdefault*(parent: ptr TWidget, widget_size: int, - widget_name: cstring, size_req: ptr TBounds, flags: cint, - creator: TcgraphicsCreateFunction): ptr TWidget{.cdecl, +proc newdefault*(parent: ptr Widget, widget_size: int, + widget_name: cstring, size_req: ptr Bounds, flags: cint, + creator: CgraphicsCreateFunction): ptr Widget{.cdecl, importc: "default_widget_create", dynlib: clarodll.} #* \internal # \brief Retrieves the native container of the widget's children @@ -520,7 +525,7 @@ proc newdefault*(parent: ptr TWidget, widget_size: int, # \return A pointer to the native widget that will hold w's children # -proc widget_get_container*(widget: ptr TWidget): pointer{.cdecl, +proc widget_get_container*(widget: ptr Widget): pointer{.cdecl, importc: "widget_get_container", dynlib: clarodll.} #* \internal # \brief Sets the content size of the widget. @@ -531,7 +536,7 @@ proc widget_get_container*(widget: ptr TWidget): pointer{.cdecl, # \param event Whether to send a content_size event # -proc widget_set_content_size*(widget: ptr TWidget, w: cint, h: cint, +proc widget_set_content_size*(widget: ptr Widget, w: cint, h: cint, event: cint){.cdecl, importc: "widget_set_content_size", dynlib: clarodll.} #* \internal @@ -543,7 +548,7 @@ proc widget_set_content_size*(widget: ptr TWidget, w: cint, h: cint, # \param event Whether to send a resize event # -proc widget_set_size*(widget: ptr TWidget, w: cint, h: cint, event: cint){. +proc widget_set_size*(widget: ptr Widget, w: cint, h: cint, event: cint){. cdecl, importc: "widget_set_size", dynlib: clarodll.} #* \internal # \brief Sets the position of the widget's content area. @@ -554,7 +559,7 @@ proc widget_set_size*(widget: ptr TWidget, w: cint, h: cint, event: cint){. # \param event Whether to send a content_move event # -proc widget_set_content_position*(widget: ptr TWidget, x: cint, y: cint, +proc widget_set_content_position*(widget: ptr Widget, x: cint, y: cint, event: cint){.cdecl, importc: "widget_set_content_position", dynlib: clarodll.} #* \internal @@ -566,7 +571,7 @@ proc widget_set_content_position*(widget: ptr TWidget, x: cint, y: cint, # \param event Whether to send a moved event # -proc widget_set_position*(widget: ptr TWidget, x: cint, y: cint, event: cint){. +proc widget_set_position*(widget: ptr Widget, x: cint, y: cint, event: cint){. cdecl, importc: "widget_set_position", dynlib: clarodll.} #* \internal # \brief Sends a destroy event to the specified widget. @@ -576,13 +581,13 @@ proc widget_set_position*(widget: ptr TWidget, x: cint, y: cint, event: cint){. # \param widget A widget # -proc widget_destroy*(widget: ptr TWidget){.cdecl, importc: "widget_destroy", +proc widget_destroy*(widget: ptr Widget){.cdecl, importc: "widget_destroy", dynlib: clarodll.} type - TOpenglWidget* {.pure.} = object of TWidget + OpenglWidget* {.pure.} = object of Widget gldata*: pointer - +{.deprecated: [TOpenglWidget: OpenglWidget].} # functions #* @@ -594,8 +599,8 @@ type # \return A new OpenGL widget object. # -proc newopengl*(parent: ptr TClaroObj, bounds: ptr TBounds, - flags: cint): ptr TOpenglWidget {. +proc newopengl*(parent: ptr ClaroObj, bounds: ptr Bounds, + flags: cint): ptr OpenglWidget {. cdecl, importc: "opengl_widget_create", dynlib: clarodll.} #* # \brief Flips the front and back buffers @@ -603,7 +608,7 @@ proc newopengl*(parent: ptr TClaroObj, bounds: ptr TBounds, # \param widget A valid OpenGL widget object # -proc opengl_flip*(widget: ptr TOpenglWidget) {.cdecl, importc: "opengl_flip", +proc opengl_flip*(widget: ptr OpenglWidget) {.cdecl, importc: "opengl_flip", dynlib: clarodll.} #* # \brief Activates this OpenGL widget's context @@ -611,13 +616,13 @@ proc opengl_flip*(widget: ptr TOpenglWidget) {.cdecl, importc: "opengl_flip", # \param widget A valid OpenGL widget object # -proc opengl_activate*(widget: ptr TOpenglWidget) {. +proc opengl_activate*(widget: ptr OpenglWidget) {. cdecl, importc: "opengl_activate", dynlib: clarodll.} type - TButton* {.pure.} = object of TWidget + Button* {.pure.} = object of Widget text*: array[0..256-1, char] - +{.deprecated: [TButton: Button].} # functions #* @@ -629,8 +634,8 @@ type # \return A new Button widget object. # -proc newbutton*(parent: ptr TClaroObj, bounds: ptr TBounds, - flags: cint): ptr TButton {. +proc newbutton*(parent: ptr ClaroObj, bounds: ptr Bounds, + flags: cint): ptr Button {. cdecl, importc: "button_widget_create", dynlib: clarodll.} #* # \brief Creates a Button widget with a label @@ -642,9 +647,9 @@ proc newbutton*(parent: ptr TClaroObj, bounds: ptr TBounds, # \return A new Button widget object. # -proc newbutton*(parent: ptr TClaroObj, - bounds: ptr TBounds, flags: cint, - label: cstring): ptr TButton{.cdecl, +proc newbutton*(parent: ptr ClaroObj, + bounds: ptr Bounds, flags: cint, + label: cstring): ptr Button{.cdecl, importc: "button_widget_create_with_label", dynlib: clarodll.} #* # \brief Changes the label of the button @@ -653,7 +658,7 @@ proc newbutton*(parent: ptr TClaroObj, # \param label The new label for the button # -proc button_set_text*(obj: ptr TButton, label: cstring){.cdecl, +proc button_set_text*(obj: ptr Button, label: cstring){.cdecl, importc: "button_set_label", dynlib: clarodll.} #* @@ -666,7 +671,7 @@ proc button_set_text*(obj: ptr TButton, label: cstring){.cdecl, # \param image The new image for the button # -proc button_set_image*(obj: ptr TButton, image: ptr TImage){.cdecl, +proc button_set_image*(obj: ptr Button, image: ptr Image){.cdecl, importc: "button_set_image", dynlib: clarodll.} const @@ -680,7 +685,7 @@ const # END OLD type - TCanvas*{.pure.} = object of TWidget + Canvas*{.pure.} = object of Widget surface*: cairo.PSurface cr*: cairo.PContext surfdata*: pointer @@ -697,6 +702,7 @@ type charsize*: array[0..256 - 1, cairo.TTextExtents] csz_loaded*: cint fontsize*: cint +{.deprecated: [TCanvas: Canvas].} # functions #* @@ -708,8 +714,8 @@ type # \return A new Canvas widget object. # -proc newcanvas*(parent: ptr TClaroObj, bounds: ptr TBounds, - flags: cint): ptr TCanvas{. +proc newcanvas*(parent: ptr ClaroObj, bounds: ptr Bounds, + flags: cint): ptr Canvas{. cdecl, importc: "canvas_widget_create", dynlib: clarodll.} #* # \brief Invalidates and redraws a canvas widget @@ -717,7 +723,7 @@ proc newcanvas*(parent: ptr TClaroObj, bounds: ptr TBounds, # \param widget A valid Canvas widget object. # -proc canvas_redraw*(widget: ptr TCanvas){.cdecl, importc: "canvas_redraw", +proc canvas_redraw*(widget: ptr Canvas){.cdecl, importc: "canvas_redraw", dynlib: clarodll.} # claro text functions #* @@ -730,7 +736,7 @@ proc canvas_redraw*(widget: ptr TCanvas){.cdecl, importc: "canvas_redraw", # \param a Alpha component (0.0 - 1.0) # -proc canvas_set_text_color*(widget: ptr TCanvas, r: cdouble, g: cdouble, +proc canvas_set_text_color*(widget: ptr Canvas, r: cdouble, g: cdouble, b: cdouble, a: cdouble){.cdecl, importc: "canvas_set_text_color", dynlib: clarodll.} #* @@ -743,7 +749,7 @@ proc canvas_set_text_color*(widget: ptr TCanvas, r: cdouble, g: cdouble, # \param a Alpha component (0.0 - 1.0) # -proc canvas_set_text_bgcolor*(widget: ptr TCanvas, r: cdouble, g: cdouble, +proc canvas_set_text_bgcolor*(widget: ptr Canvas, r: cdouble, g: cdouble, b: cdouble, a: cdouble){.cdecl, importc: "canvas_set_text_bgcolor", dynlib: clarodll.} #* @@ -757,7 +763,7 @@ proc canvas_set_text_bgcolor*(widget: ptr TCanvas, r: cdouble, g: cdouble, # \param decoration Font decorations # -proc canvas_set_text_font*(widget: ptr TCanvas, face: cstring, size: cint, +proc canvas_set_text_font*(widget: ptr Canvas, face: cstring, size: cint, weight: cint, slant: cint, decoration: cint){.cdecl, importc: "canvas_set_text_font", dynlib: clarodll.} #* @@ -769,7 +775,7 @@ proc canvas_set_text_font*(widget: ptr TCanvas, face: cstring, size: cint, # \return Width of the text in pixels # -proc canvas_text_width*(widget: ptr TCanvas, text: cstring, len: cint): cint{. +proc canvas_text_width*(widget: ptr Canvas, text: cstring, len: cint): cint{. cdecl, importc: "canvas_text_width", dynlib: clarodll.} #* # \brief Calculates the width of the specified text's bounding box @@ -780,7 +786,7 @@ proc canvas_text_width*(widget: ptr TCanvas, text: cstring, len: cint): cint{. # \return Width of the text's bounding box in pixels # -proc canvas_text_box_width*(widget: ptr TCanvas, text: cstring, +proc canvas_text_box_width*(widget: ptr Canvas, text: cstring, len: cint): cint{. cdecl, importc: "canvas_text_box_width", dynlib: clarodll.} #* @@ -793,7 +799,7 @@ proc canvas_text_box_width*(widget: ptr TCanvas, text: cstring, # \return The number of characters of text that will fit in width pixels. # -proc canvas_text_display_count*(widget: ptr TCanvas, text: cstring, +proc canvas_text_display_count*(widget: ptr Canvas, text: cstring, width: cint): cint{.cdecl, importc: "canvas_text_display_count", dynlib: clarodll.} #* @@ -806,7 +812,7 @@ proc canvas_text_display_count*(widget: ptr TCanvas, text: cstring, # \param len The number of characters of text to calulcate # -proc canvas_show_text*(widget: ptr TCanvas, x: cint, y: cint, text: cstring, +proc canvas_show_text*(widget: ptr Canvas, x: cint, y: cint, text: cstring, len: cint){.cdecl, importc: "canvas_show_text", dynlib: clarodll.} #* @@ -823,7 +829,7 @@ proc canvas_show_text*(widget: ptr TCanvas, x: cint, y: cint, text: cstring, # \param a Alpha component (0.0 - 1.0) # -proc canvas_fill_rect*(widget: ptr TCanvas, x: cint, y: cint, w: cint, +proc canvas_fill_rect*(widget: ptr Canvas, x: cint, y: cint, w: cint, h: cint, r, g, b, a: cdouble){. cdecl, importc: "canvas_fill_rect", dynlib: clarodll.} #* @@ -835,7 +841,7 @@ proc canvas_fill_rect*(widget: ptr TCanvas, x: cint, y: cint, w: cint, # \param y The Y position at which the image will be drawn # -proc canvas_draw_image*(widget: ptr TCanvas, image: ptr TImage, x: cint, +proc canvas_draw_image*(widget: ptr Canvas, image: ptr Image, x: cint, y: cint){.cdecl, importc: "canvas_draw_image", dynlib: clarodll.} # claro "extensions" of cairo @@ -843,25 +849,25 @@ proc canvas_draw_image*(widget: ptr TCanvas, image: ptr TImage, x: cint, # \brief Internal claro extension of cairo text functions # -proc canvas_cairo_buffered_text_width*(widget: ptr TCanvas, +proc canvas_cairo_buffered_text_width*(widget: ptr Canvas, text: cstring, len: cint): cint{.cdecl, importc: "canvas_cairo_buffered_text_width", dynlib: clarodll.} #* \internal # \brief Internal claro extension of cairo text functions # -proc canvas_cairo_buffered_text_display_count*(widget: ptr TCanvas, +proc canvas_cairo_buffered_text_display_count*(widget: ptr Canvas, text: cstring, width: cint): cint{.cdecl, importc: "canvas_cairo_buffered_text_display_count", dynlib: clarodll.} -proc canvas_get_cairo_context*(widget: ptr TCanvas): cairo.PContext {.cdecl, +proc canvas_get_cairo_context*(widget: ptr Canvas): cairo.PContext {.cdecl, importc: "canvas_get_cairo_context", dynlib: clarodll.} type - TCheckBox*{.pure.} = object of TWidget + CheckBox*{.pure.} = object of Widget text*: array[0..256-1, char] checked*: cint - +{.deprecated: [TCheckBox: CheckBox].} #* # \brief Creates a Checkbox widget # @@ -871,8 +877,8 @@ type # \return A new Checkbox widget object. # -proc newcheckbox*(parent: ptr TClaroObj, bounds: ptr TBounds, - flags: cint): ptr TCheckBox{. +proc newcheckbox*(parent: ptr ClaroObj, bounds: ptr Bounds, + flags: cint): ptr CheckBox{. cdecl, importc: "checkbox_widget_create", dynlib: clarodll.} #* # \brief Creates a Checkbox widget with a label @@ -884,9 +890,9 @@ proc newcheckbox*(parent: ptr TClaroObj, bounds: ptr TBounds, # \return A new Checkbox widget object. # -proc newcheckbox*(parent: ptr TClaroObj, - bounds: ptr TBounds, flags: cint, - label: cstring): ptr TCheckBox {.cdecl, +proc newcheckbox*(parent: ptr ClaroObj, + bounds: ptr Bounds, flags: cint, + label: cstring): ptr CheckBox {.cdecl, importc: "checkbox_widget_create_with_label", dynlib: clarodll.} #* # \brief Sets a new label for the Checkbox widget @@ -895,7 +901,7 @@ proc newcheckbox*(parent: ptr TClaroObj, # \param label The new label for the checkbox # -proc checkbox_set_text*(obj: ptr TCheckBox, label: cstring){.cdecl, +proc checkbox_set_text*(obj: ptr CheckBox, label: cstring){.cdecl, importc: "checkbox_set_label", dynlib: clarodll.} #* # \brief Retrieves the checkbox's check state @@ -904,7 +910,7 @@ proc checkbox_set_text*(obj: ptr TCheckBox, label: cstring){.cdecl, # \return 1 if the checkbox is checked, otherwise 0 # -proc checkbox_checked*(obj: ptr TCheckBox): cint{.cdecl, +proc checkbox_checked*(obj: ptr CheckBox): cint{.cdecl, importc: "checkbox_get_checked", dynlib: clarodll.} #* # \brief Sets the checkbox's checked state @@ -913,7 +919,7 @@ proc checkbox_checked*(obj: ptr TCheckBox): cint{.cdecl, # \param checked 1 if the checkbox should become checked, otherwise 0 # -proc checkbox_set_checked*(obj: ptr TCheckBox, checked: cint){.cdecl, +proc checkbox_set_checked*(obj: ptr CheckBox, checked: cint){.cdecl, importc: "checkbox_set_checked", dynlib: clarodll.} @@ -922,31 +928,31 @@ proc checkbox_set_checked*(obj: ptr TCheckBox, checked: cint){.cdecl, # type - TListItem*{.pure.} = object of TClaroObj + ListItem*{.pure.} = object of ClaroObj row*: cint native*: pointer nativeid*: int - menu*: ptr TClaroObj + menu*: ptr ClaroObj enabled*: cint data*: ptr pointer - ListItemChildren*: TList - ListItemParent*: ptr TList - parent_item*: ptr TListItem # drawing related info, not always required - text_color*: TColor - sel_text_color*: TColor - back_color*: TColor - sel_back_color*: TColor - font*: TFont + ListItemChildren*: List + ListItemParent*: ptr List + parent_item*: ptr ListItem # drawing related info, not always required + text_color*: Color + sel_text_color*: Color + back_color*: Color + sel_back_color*: Color + font*: Font - TListWidget* {.pure.} = object of TWidget ## List widget, base for + ListWidget* {.pure.} = object of Widget ## List widget, base for ## widgets containing items columns*: cint coltypes*: ptr cint - items*: TList - - TCombo*{.pure.} = object of TListWidget - selected*: ptr TListItem + items*: List + Combo*{.pure.} = object of ListWidget + selected*: ptr ListItem +{.deprecated: [TListItem: ListItem, TListWidget: ListWidget, TCombo: Combo].} # functions #* @@ -958,8 +964,8 @@ type # \return A new Combo widget object. # -proc newcombo*(parent: ptr TClaroObj, bounds: ptr TBounds, - flags: cint): ptr TCombo{. +proc newcombo*(parent: ptr ClaroObj, bounds: ptr Bounds, + flags: cint): ptr Combo{. cdecl, importc: "combo_widget_create", dynlib: clarodll.} #* # \brief Append a row to a Combo widget @@ -969,7 +975,7 @@ proc newcombo*(parent: ptr TClaroObj, bounds: ptr TBounds, # \return A new list item. # -proc combo_append_row*(combo: ptr TCombo, text: cstring): ptr TListItem {. +proc combo_append_row*(combo: ptr Combo, text: cstring): ptr ListItem {. cdecl, importc: "combo_append_row", dynlib: clarodll.} #* # \brief Insert a row at the specified position into a Combo widget @@ -980,8 +986,8 @@ proc combo_append_row*(combo: ptr TCombo, text: cstring): ptr TListItem {. # \return A new list item. # -proc combo_insert_row*(combo: ptr TCombo, pos: cint, - text: cstring): ptr TListItem {. +proc combo_insert_row*(combo: ptr Combo, pos: cint, + text: cstring): ptr ListItem {. cdecl, importc: "combo_insert_row", dynlib: clarodll.} #* # \brief Move a row in a Combo widget @@ -991,7 +997,7 @@ proc combo_insert_row*(combo: ptr TCombo, pos: cint, # \param row New position to place this item # -proc combo_move_row*(combo: ptr TCombo, item: ptr TListItem, row: cint){. +proc combo_move_row*(combo: ptr Combo, item: ptr ListItem, row: cint){. cdecl, importc: "combo_move_row", dynlib: clarodll.} #* # \brief Remove a row from a Combo widget @@ -1000,7 +1006,7 @@ proc combo_move_row*(combo: ptr TCombo, item: ptr TListItem, row: cint){. # \param item A valid list item # -proc combo_remove_row*(combo: ptr TCombo, item: ptr TListItem){.cdecl, +proc combo_remove_row*(combo: ptr Combo, item: ptr ListItem){.cdecl, importc: "combo_remove_row", dynlib: clarodll.} #* # \brief Returns the currently selected Combo item @@ -1009,7 +1015,7 @@ proc combo_remove_row*(combo: ptr TCombo, item: ptr TListItem){.cdecl, # \return The currently selected Combo item, or NULL if no item is selected. # -proc combo_get_selected*(obj: ptr TCombo): ptr TListItem{.cdecl, +proc combo_get_selected*(obj: ptr Combo): ptr ListItem{.cdecl, importc: "combo_get_selected", dynlib: clarodll.} #* # \brief Returns the number of rows in a Combo widget @@ -1018,7 +1024,7 @@ proc combo_get_selected*(obj: ptr TCombo): ptr TListItem{.cdecl, # \return Number of rows # -proc combo_get_rows*(obj: ptr TCombo): cint{.cdecl, +proc combo_get_rows*(obj: ptr Combo): cint{.cdecl, importc: "combo_get_rows", dynlib: clarodll.} #* # \brief Selects a row in a Combo widget @@ -1027,7 +1033,7 @@ proc combo_get_rows*(obj: ptr TCombo): cint{.cdecl, # \param item A valid list item # -proc combo_select_item*(obj: ptr TCombo, item: ptr TListItem){.cdecl, +proc combo_select_item*(obj: ptr Combo, item: ptr ListItem){.cdecl, importc: "combo_select_item", dynlib: clarodll.} #* # \brief Removes all entries from a Combo widget @@ -1035,11 +1041,12 @@ proc combo_select_item*(obj: ptr TCombo, item: ptr TListItem){.cdecl, # \param obj A valid Combo widget object. # -proc combo_clear*(obj: ptr TCombo){.cdecl, importc: "combo_clear", +proc combo_clear*(obj: ptr Combo){.cdecl, importc: "combo_clear", dynlib: clarodll.} type - TContainerWidget* {.pure.} = object of TWidget + ContainerWidget* {.pure.} = object of Widget +{.deprecated: [TContainerWidget: ContainerWidget].} # functions @@ -1052,14 +1059,14 @@ type # \return A new Container widget object. # -proc newcontainer*(parent: ptr TClaroObj, bounds: ptr TBounds, - flags: cint): ptr TContainerWidget{. +proc newcontainer*(parent: ptr ClaroObj, bounds: ptr Bounds, + flags: cint): ptr ContainerWidget{. cdecl, importc: "container_widget_create", dynlib: clarodll.} -proc newdialog*(parent: ptr TClaroObj, bounds: ptr TBounds, format: cstring, - flags: cint): ptr TClaroObj{.cdecl, +proc newdialog*(parent: ptr ClaroObj, bounds: ptr Bounds, format: cstring, + flags: cint): ptr ClaroObj{.cdecl, importc: "dialog_widget_create", dynlib: clarodll.} -proc dialog_set_text*(obj: ptr TClaroObj, text: cstring){.cdecl, +proc dialog_set_text*(obj: ptr ClaroObj, text: cstring){.cdecl, importc: "dialog_set_text", dynlib: clarodll.} proc dialog_set_default_icon*(typ: cstring, file: cstring){.cdecl, importc: "dialog_set_default_icon", dynlib: clarodll.} @@ -1075,8 +1082,9 @@ proc dialog_other*(format: cstring, text: cstring, default_icon: cstring): cint{ cdecl, importc: "dialog_other", dynlib: clarodll.} type - TFontDialog* {.pure.} = object of TWidget - selected*: TFont + FontDialog* {.pure.} = object of Widget + selected*: Font +{.deprecated: [TFontDialog: FontDialog].} # functions #* @@ -1087,7 +1095,7 @@ type # \return A new Font Selection widget object. # -proc newFontDialog*(parent: ptr TClaroObj, flags: cint): ptr TFontDialog {. +proc newFontDialog*(parent: ptr ClaroObj, flags: cint): ptr FontDialog {. cdecl, importc: "font_dialog_widget_create", dynlib: clarodll.} #* # \brief Changes the selected font @@ -1096,7 +1104,7 @@ proc newFontDialog*(parent: ptr TClaroObj, flags: cint): ptr TFontDialog {. # \param font The name of the font # -proc font_dialog_set_font*(obj: ptr TFontDialog, face: cstring, size: cint, +proc font_dialog_set_font*(obj: ptr FontDialog, face: cstring, size: cint, weight: cint, slant: cint, decoration: cint){.cdecl, importc: "font_dialog_set_font", dynlib: clarodll.} #* @@ -1106,13 +1114,13 @@ proc font_dialog_set_font*(obj: ptr TFontDialog, face: cstring, size: cint, # \return A font_t structure containing information about the selected font. # -proc font_dialog_get_font*(obj: ptr TFontDialog): ptr TFont{.cdecl, +proc font_dialog_get_font*(obj: ptr FontDialog): ptr Font{.cdecl, importc: "font_dialog_get_font", dynlib: clarodll.} type - TFrame* {.pure.} = object of TWidget + Frame* {.pure.} = object of Widget text*: array[0..256-1, char] - +{.deprecated: [TFrame: Frame].} #* # \brief Creates a Frame widget @@ -1123,8 +1131,8 @@ type # \return A new Frame widget object. # -proc newframe*(parent: ptr TClaroObj, bounds: ptr TBounds, - flags: cint): ptr TFrame{. +proc newframe*(parent: ptr ClaroObj, bounds: ptr Bounds, + flags: cint): ptr Frame{. cdecl, importc: "frame_widget_create", dynlib: clarodll.} #* # \brief Creates a Frame widget with a label @@ -1136,8 +1144,8 @@ proc newframe*(parent: ptr TClaroObj, bounds: ptr TBounds, # \return A new Frame widget object. # -proc newframe*(parent: ptr TClaroObj, bounds: ptr TBounds, flags: cint, - label: cstring): ptr TFrame {.cdecl, +proc newframe*(parent: ptr ClaroObj, bounds: ptr Bounds, flags: cint, + label: cstring): ptr Frame {.cdecl, importc: "frame_widget_create_with_label", dynlib: clarodll.} #* # \brief Creates a Container widget @@ -1148,13 +1156,13 @@ proc newframe*(parent: ptr TClaroObj, bounds: ptr TBounds, flags: cint, # \return A new Container widget object. # -proc frame_set_text*(frame: ptr TFrame, label: cstring){.cdecl, +proc frame_set_text*(frame: ptr Frame, label: cstring){.cdecl, importc: "frame_set_label", dynlib: clarodll.} type - TImageWidget* {.pure.} = object of TWidget - src*: ptr TImage - + ImageWidget* {.pure.} = object of Widget + src*: ptr Image +{.deprecated: [TImageWidget: ImageWidget].} #* # \brief Creates an Image widget @@ -1165,8 +1173,8 @@ type # \return A new Image widget object. # -proc newimageWidget*(parent: ptr TClaroObj, bounds: ptr TBounds, - flags: cint): ptr TImageWidget{. +proc newimageWidget*(parent: ptr ClaroObj, bounds: ptr Bounds, + flags: cint): ptr ImageWidget{. cdecl, importc: "image_widget_create", dynlib: clarodll.} #* # \brief Creates an Image widget with an image @@ -1178,9 +1186,9 @@ proc newimageWidget*(parent: ptr TClaroObj, bounds: ptr TBounds, # \return A new Image widget object. # -proc newimageWidget*(parent: ptr TClaroObj, - bounds: ptr TBounds, flags: cint, - image: ptr TImage): ptr TImageWidget{.cdecl, +proc newimageWidget*(parent: ptr ClaroObj, + bounds: ptr Bounds, flags: cint, + image: ptr Image): ptr ImageWidget{.cdecl, importc: "image_widget_create_with_image", dynlib: clarodll.} #* # \brief Sets the image object of the image widget @@ -1189,16 +1197,17 @@ proc newimageWidget*(parent: ptr TClaroObj, # \param src The source image object # -proc image_set_image*(image: ptr TImageWidget, src: ptr TImage){.cdecl, +proc image_set_image*(image: ptr ImageWidget, src: ptr Image){.cdecl, importc: "image_set_image", dynlib: clarodll.} type - TLabel*{.pure.} = object of TWidget + Label*{.pure.} = object of Widget text*: array[0..256-1, char] - TcLabelJustify* = enum + CLabelJustify* = enum cLabelLeft = 0x00000001, cLabelRight = 0x00000002, cLabelCenter = 0x00000004, cLabelFill = 0x00000008 +{.deprecated: [TLabel: Label, TcLabelJustify: CLabelJustify].} #* # \brief Creates a Label widget @@ -1209,8 +1218,8 @@ type # \return A new Label widget object. # -proc newlabel*(parent: ptr TClaroObj, bounds: ptr TBounds, - flags: cint): ptr TLabel{. +proc newlabel*(parent: ptr ClaroObj, bounds: ptr Bounds, + flags: cint): ptr Label{. cdecl, importc: "label_widget_create", dynlib: clarodll.} #* # \brief Creates a Label widget @@ -1221,9 +1230,9 @@ proc newlabel*(parent: ptr TClaroObj, bounds: ptr TBounds, # \return A new Label widget object. # -proc newLabel*(parent: ptr TClaroObj, - bounds: ptr TBounds, flags: cint, - text: cstring): ptr TLabel{.cdecl, +proc newLabel*(parent: ptr ClaroObj, + bounds: ptr Bounds, flags: cint, + text: cstring): ptr Label{.cdecl, importc: "label_widget_create_with_text", dynlib: clarodll.} #* # \brief Sets the text of a label widget @@ -1232,7 +1241,7 @@ proc newLabel*(parent: ptr TClaroObj, # \param text The text this label widget will show # -proc label_set_text*(obj: ptr TLabel, text: cstring){.cdecl, +proc label_set_text*(obj: ptr Label, text: cstring){.cdecl, importc: "label_set_text", dynlib: clarodll.} #* @@ -1242,7 +1251,7 @@ proc label_set_text*(obj: ptr TLabel, text: cstring){.cdecl, # \param text The justification (see cLabelJustify enum) # -proc label_set_justify*(obj: ptr TLabel, flags: cint){.cdecl, +proc label_set_justify*(obj: ptr Label, flags: cint){.cdecl, importc: "label_set_justify", dynlib: clarodll.} const @@ -1262,7 +1271,7 @@ const # types of the columns. # -proc list_widget_init_ptr*(obj: ptr TListWidget, col_num: cint, +proc list_widget_init_ptr*(obj: ptr ListWidget, col_num: cint, cols: ptr cint) {.cdecl, importc: "list_widget_init_ptr", dynlib: clarodll.} #* @@ -1273,7 +1282,7 @@ proc list_widget_init_ptr*(obj: ptr TListWidget, col_num: cint, # \param argpi A pointer to a va_list to parse # -#proc list_widget_init_vaptr*(obj: ptr TClaroObj, col_num: cunsignedint, +#proc list_widget_init_vaptr*(obj: ptr ClaroObj, col_num: cunsignedint, # argpi: va_list){.cdecl, # importc: "list_widget_init_vaptr", dynlib: clarodll.} @@ -1282,7 +1291,7 @@ proc list_widget_init_ptr*(obj: ptr TListWidget, col_num: cint, # it's own arguments, and a pointer to the first variable argument. # -proc list_widget_init*(obj: ptr TListWidget, col_num: cint){.varargs, +proc list_widget_init*(obj: ptr ListWidget, col_num: cint){.varargs, cdecl, importc: "list_widget_init", dynlib: clarodll.} #* # \brief Inserts a row to a list under parent at the position specified. @@ -1302,16 +1311,16 @@ proc list_widget_init*(obj: ptr TListWidget, col_num: cint){.varargs, # a pointer to the first variable argument. # -proc list_widget_row_append*(list: ptr TListWidget, - parent: ptr TListItem): ptr TListItem{. +proc list_widget_row_append*(list: ptr ListWidget, + parent: ptr ListItem): ptr ListItem{. varargs, cdecl, importc: "list_widget_row_append", dynlib: clarodll.} #* # Shortcut function, calls list_widget_row_insert_ptr with # it's own arguments, and a pointer to the first variable argument. # -proc list_widget_row_insert*(list: ptr TListWidget, parent: ptr TListItem, - pos: cint): ptr TListItem {.varargs, cdecl, +proc list_widget_row_insert*(list: ptr ListWidget, parent: ptr ListItem, + pos: cint): ptr ListItem {.varargs, cdecl, importc: "list_widget_row_insert", dynlib: clarodll.} #* # \brief Removes a row from a list @@ -1320,7 +1329,7 @@ proc list_widget_row_insert*(list: ptr TListWidget, parent: ptr TListItem, # \param item The item to remove # -proc list_widget_row_remove*(list: ptr TListWidget, item: ptr TListItem){. +proc list_widget_row_remove*(list: ptr ListWidget, item: ptr ListItem){. cdecl, importc: "list_widget_row_remove", dynlib: clarodll.} #* # \brief Moves a row to a new position in the list @@ -1331,7 +1340,7 @@ proc list_widget_row_remove*(list: ptr TListWidget, item: ptr TListItem){. # position will result in no change. # -proc list_widget_row_move*(list: ptr TListWidget, item: ptr TListItem, +proc list_widget_row_move*(list: ptr ListWidget, item: ptr ListItem, row: cint){.cdecl, importc: "list_widget_row_move", dynlib: clarodll.} #* @@ -1342,8 +1351,8 @@ proc list_widget_row_move*(list: ptr TListWidget, item: ptr TListItem, # \param row Row index of item to return # -proc list_widget_get_row*(list: ptr TListWidget, parent: ptr TListItem, - row: cint): ptr TListItem{.cdecl, +proc list_widget_get_row*(list: ptr ListWidget, parent: ptr ListItem, + row: cint): ptr ListItem{.cdecl, importc: "list_widget_get_row", dynlib: clarodll.} #* # \brief Edit items of a row in the list. @@ -1365,7 +1374,7 @@ proc list_widget_get_row*(list: ptr TListWidget, parent: ptr TListItem, # Don't forget the -1. # -proc list_widget_edit_row*(list: ptr TListWidget, item: ptr TListItem){. +proc list_widget_edit_row*(list: ptr ListWidget, item: ptr ListItem){. varargs, cdecl, importc: "list_widget_edit_row", dynlib: clarodll.} #* # \brief Set the text color of an item. @@ -1379,7 +1388,7 @@ proc list_widget_edit_row*(list: ptr TListWidget, item: ptr TListItem){. # should be 1.0) # -proc list_item_set_text_color*(item: ptr TListItem, r: cfloat, g: cfloat, +proc list_item_set_text_color*(item: ptr ListItem, r: cfloat, g: cfloat, b: cfloat, a: cfloat){.cdecl, importc: "list_item_set_text_color", dynlib: clarodll.} #* @@ -1394,7 +1403,7 @@ proc list_item_set_text_color*(item: ptr TListItem, r: cfloat, g: cfloat, # should be 1.0) # -proc list_item_set_text_bgcolor*(item: ptr TListItem, r: cfloat, g: cfloat, +proc list_item_set_text_bgcolor*(item: ptr ListItem, r: cfloat, g: cfloat, b: cfloat, a: cfloat){.cdecl, importc: "list_item_set_text_bgcolor", dynlib: clarodll.} #* @@ -1409,7 +1418,7 @@ proc list_item_set_text_bgcolor*(item: ptr TListItem, r: cfloat, g: cfloat, # should be 1.0) # -proc list_item_set_sel_text_color*(item: ptr TListItem, r: cfloat, g: cfloat, +proc list_item_set_sel_text_color*(item: ptr ListItem, r: cfloat, g: cfloat, b: cfloat, a: cfloat){.cdecl, importc: "list_item_set_sel_text_color", dynlib: clarodll.} #* @@ -1424,7 +1433,7 @@ proc list_item_set_sel_text_color*(item: ptr TListItem, r: cfloat, g: cfloat, # should be 1.0) # -proc list_item_set_sel_text_bgcolor*(item: ptr TListItem, r: cfloat, +proc list_item_set_sel_text_bgcolor*(item: ptr ListItem, r: cfloat, g: cfloat, b: cfloat, a: cfloat){.cdecl, importc: "list_item_set_sel_text_bgcolor", dynlib: clarodll.} #* @@ -1436,13 +1445,14 @@ proc list_item_set_sel_text_bgcolor*(item: ptr TListItem, r: cfloat, # \param decoration Font decorations # -proc list_item_set_font_extra*(item: ptr TListItem, weight: cint, +proc list_item_set_font_extra*(item: ptr ListItem, weight: cint, slant: cint, decoration: cint){.cdecl, importc: "list_item_set_font_extra", dynlib: clarodll.} type - TListbox* {.pure.} = object of TListWidget - selected*: ptr TListItem + Listbox* {.pure.} = object of ListWidget + selected*: ptr ListItem +{.deprecated: [TListbox: Listbox].} # functions #* @@ -1454,8 +1464,8 @@ type # \return A new ListBox widget object. # -proc newlistbox*(parent: ptr TClaroObj, bounds: ptr TBounds, - flags: cint): ptr TListbox{. +proc newlistbox*(parent: ptr ClaroObj, bounds: ptr Bounds, + flags: cint): ptr Listbox{. cdecl, importc: "listbox_widget_create", dynlib: clarodll.} #* # \brief Insert a row at the specified position into a ListBox widget @@ -1466,8 +1476,8 @@ proc newlistbox*(parent: ptr TClaroObj, bounds: ptr TBounds, # \return A new list item. # -proc listbox_insert_row*(listbox: ptr TListbox, pos: cint, - text: cstring): ptr TListItem{. +proc listbox_insert_row*(listbox: ptr Listbox, pos: cint, + text: cstring): ptr ListItem{. cdecl, importc: "listbox_insert_row", dynlib: clarodll.} #* # \brief Append a row to a ListBox widget @@ -1477,7 +1487,7 @@ proc listbox_insert_row*(listbox: ptr TListbox, pos: cint, # \return A new list item. # -proc listbox_append_row*(listbox: ptr TListbox, text: cstring): ptr TListItem{. +proc listbox_append_row*(listbox: ptr Listbox, text: cstring): ptr ListItem{. cdecl, importc: "listbox_append_row", dynlib: clarodll.} #* # \brief Move a row in a ListBox widget @@ -1487,7 +1497,7 @@ proc listbox_append_row*(listbox: ptr TListbox, text: cstring): ptr TListItem{. # \param row New position to place this item # -proc listbox_move_row*(listbox: ptr TListbox, item: ptr TListItem, row: cint){. +proc listbox_move_row*(listbox: ptr Listbox, item: ptr ListItem, row: cint){. cdecl, importc: "listbox_move_row", dynlib: clarodll.} #* # \brief Remove a row from a ListBox widget @@ -1496,7 +1506,7 @@ proc listbox_move_row*(listbox: ptr TListbox, item: ptr TListItem, row: cint){. # \param item A valid list item # -proc listbox_remove_row*(listbox: ptr TListbox, item: ptr TListItem){.cdecl, +proc listbox_remove_row*(listbox: ptr Listbox, item: ptr ListItem){.cdecl, importc: "listbox_remove_row", dynlib: clarodll.} #* # \brief Returns the currently selected ListBox item @@ -1505,7 +1515,7 @@ proc listbox_remove_row*(listbox: ptr TListbox, item: ptr TListItem){.cdecl, # \return The currently selected ListBox item, or NULL if no item is selected. # -proc listbox_get_selected*(obj: ptr TListbox): ptr TListItem{.cdecl, +proc listbox_get_selected*(obj: ptr Listbox): ptr ListItem{.cdecl, importc: "listbox_get_selected", dynlib: clarodll.} #* # \brief Returns the number of rows in a ListBox widget @@ -1514,7 +1524,7 @@ proc listbox_get_selected*(obj: ptr TListbox): ptr TListItem{.cdecl, # \return Number of rows # -proc listbox_get_rows*(obj: ptr TListbox): cint{.cdecl, +proc listbox_get_rows*(obj: ptr Listbox): cint{.cdecl, importc: "listbox_get_rows", dynlib: clarodll.} #* # \brief Selects a row in a ListBox widget @@ -1523,7 +1533,7 @@ proc listbox_get_rows*(obj: ptr TListbox): cint{.cdecl, # \param item A valid list item # -proc listbox_select_item*(obj: ptr TListbox, item: ptr TListItem){.cdecl, +proc listbox_select_item*(obj: ptr Listbox, item: ptr ListItem){.cdecl, importc: "listbox_select_item", dynlib: clarodll.} const @@ -1538,11 +1548,11 @@ const cListViewRowCheckBoxes* = 1 type - TListview* {.pure.} = object of TListWidget + Listview* {.pure.} = object of ListWidget titles*: cstringArray nativep*: pointer - selected*: ptr TListItem - + selected*: ptr ListItem +{.deprecated: [TListview: Listview].} # functions #* @@ -1557,8 +1567,8 @@ type # \return A new ListView widget object. # -proc newlistview*(parent: ptr TClaroObj, bounds: ptr TBounds, columns: cint, - flags: cint): ptr TListview {.varargs, cdecl, +proc newlistview*(parent: ptr ClaroObj, bounds: ptr Bounds, columns: cint, + flags: cint): ptr Listview {.varargs, cdecl, importc: "listview_widget_create", dynlib: clarodll.} #* # \brief Append a row to a ListView widget @@ -1568,7 +1578,7 @@ proc newlistview*(parent: ptr TClaroObj, bounds: ptr TBounds, columns: cint, # \return A new list item. # -proc listview_append_row*(listview: ptr TListview): ptr TListItem{.varargs, +proc listview_append_row*(listview: ptr Listview): ptr ListItem{.varargs, cdecl, importc: "listview_append_row", dynlib: clarodll.} #* # \brief Insert a row at the specified position into a ListView widget @@ -1579,7 +1589,7 @@ proc listview_append_row*(listview: ptr TListview): ptr TListItem{.varargs, # \return A new list item. # -proc listview_insert_row*(listview: ptr TListview, pos: cint): ptr TListItem{. +proc listview_insert_row*(listview: ptr Listview, pos: cint): ptr ListItem{. varargs, cdecl, importc: "listview_insert_row", dynlib: clarodll.} #* # \brief Move a row in a ListView widget @@ -1589,7 +1599,7 @@ proc listview_insert_row*(listview: ptr TListview, pos: cint): ptr TListItem{. # \param row New position to place this item # -proc listview_move_row*(listview: ptr TListview, item: ptr TListItem, +proc listview_move_row*(listview: ptr Listview, item: ptr ListItem, row: cint){.cdecl, importc: "listview_move_row", dynlib: clarodll.} #* @@ -1599,7 +1609,7 @@ proc listview_move_row*(listview: ptr TListview, item: ptr TListItem, # \param item A valid list item # -proc listview_remove_row*(listview: ptr TListview, item: ptr TListItem){. +proc listview_remove_row*(listview: ptr Listview, item: ptr ListItem){. cdecl, importc: "listview_remove_row", dynlib: clarodll.} #* # \brief Returns the currently selected ListView item @@ -1608,7 +1618,7 @@ proc listview_remove_row*(listview: ptr TListview, item: ptr TListItem){. # \return The currently selected ListView item, or NULL if no item is selected. # -proc listview_get_selected*(obj: ptr TListview): ptr TListItem{.cdecl, +proc listview_get_selected*(obj: ptr Listview): ptr ListItem{.cdecl, importc: "listview_get_selected", dynlib: clarodll.} #* # \brief Returns the number of rows in a ListView widget @@ -1617,7 +1627,7 @@ proc listview_get_selected*(obj: ptr TListview): ptr TListItem{.cdecl, # \return Number of rows # -proc listview_get_rows*(obj: ptr TListview): cint{.cdecl, +proc listview_get_rows*(obj: ptr Listview): cint{.cdecl, importc: "listview_get_rows", dynlib: clarodll.} #* # \brief Selects a row in a ListView widget @@ -1626,15 +1636,15 @@ proc listview_get_rows*(obj: ptr TListview): cint{.cdecl, # \param item A valid list item # -proc listview_select_item*(obj: ptr TListview, item: ptr TListItem){.cdecl, +proc listview_select_item*(obj: ptr Listview, item: ptr ListItem){.cdecl, importc: "listview_select_item", dynlib: clarodll.} const cMenuPopupAtCursor* = 1 type - TMenu* {.pure.} = object of TListWidget - + Menu* {.pure.} = object of ListWidget +{.deprecated: [TMenu: Menu].} #* # \brief Creates a Menu widget @@ -1644,7 +1654,7 @@ type # \return A new Menu widget object. # -proc newmenu*(parent: ptr TClaroObj, flags: cint): ptr TMenu {.cdecl, +proc newmenu*(parent: ptr ClaroObj, flags: cint): ptr Menu {.cdecl, importc: "menu_widget_create", dynlib: clarodll.} #* # \brief Append a row to a Menu widget @@ -1656,8 +1666,8 @@ proc newmenu*(parent: ptr TClaroObj, flags: cint): ptr TMenu {.cdecl, # \return A new list item. # -proc menu_append_item*(menu: ptr TMenu, parent: ptr TListItem, - image: ptr TImage, title: cstring): ptr TListItem{. +proc menu_append_item*(menu: ptr Menu, parent: ptr ListItem, + image: ptr Image, title: cstring): ptr ListItem{. cdecl, importc: "menu_append_item", dynlib: clarodll.} #* # \brief Insert a row into a Menu widget @@ -1670,8 +1680,8 @@ proc menu_append_item*(menu: ptr TMenu, parent: ptr TListItem, # \return A new list item. # -proc menu_insert_item*(menu: ptr TMenu, parent: ptr TListItem, pos: cint, - image: ptr TImage, title: cstring): ptr TListItem{. +proc menu_insert_item*(menu: ptr Menu, parent: ptr ListItem, pos: cint, + image: ptr Image, title: cstring): ptr ListItem{. cdecl, importc: "menu_insert_item", dynlib: clarodll.} #* # \brief Append a separator to a Menu widget @@ -1681,8 +1691,8 @@ proc menu_insert_item*(menu: ptr TMenu, parent: ptr TListItem, pos: cint, # \return A new list item. # -proc menu_append_separator*(menu: ptr TMenu, - parent: ptr TListItem): ptr TListItem{. +proc menu_append_separator*(menu: ptr Menu, + parent: ptr ListItem): ptr ListItem{. cdecl, importc: "menu_append_separator", dynlib: clarodll.} #* # \brief Insert a separator into a Menu widget @@ -1693,8 +1703,8 @@ proc menu_append_separator*(menu: ptr TMenu, # \return A new list item. # -proc menu_insert_separator*(menu: ptr TMenu, parent: ptr TListItem, - pos: cint): ptr TListItem{.cdecl, +proc menu_insert_separator*(menu: ptr Menu, parent: ptr ListItem, + pos: cint): ptr ListItem{.cdecl, importc: "menu_insert_separator", dynlib: clarodll.} #* # \brief Move a row in a Menu widget @@ -1704,7 +1714,7 @@ proc menu_insert_separator*(menu: ptr TMenu, parent: ptr TListItem, # \param row New position to place this item # -proc menu_move_item*(menu: ptr TMenu, item: ptr TListItem, row: cint){. +proc menu_move_item*(menu: ptr Menu, item: ptr ListItem, row: cint){. cdecl, importc: "menu_move_item", dynlib: clarodll.} #* # \brief Remove a row from a Menu widget @@ -1713,7 +1723,7 @@ proc menu_move_item*(menu: ptr TMenu, item: ptr TListItem, row: cint){. # \param item A valid list item # -proc menu_remove_item*(menu: ptr TMenu, item: ptr TListItem){.cdecl, +proc menu_remove_item*(menu: ptr Menu, item: ptr ListItem){.cdecl, importc: "menu_remove_item", dynlib: clarodll.} #* # \brief Returns the number of rows in a Menu widget @@ -1724,7 +1734,7 @@ proc menu_remove_item*(menu: ptr TMenu, item: ptr TListItem){.cdecl, # \return Number of rows # -proc menu_item_count*(obj: ptr TMenu, parent: ptr TListItem): cint{. +proc menu_item_count*(obj: ptr Menu, parent: ptr ListItem): cint{. cdecl, importc: "menu_item_count", dynlib: clarodll.} #* # \brief Disables a menu item (no focus and greyed out) @@ -1733,7 +1743,7 @@ proc menu_item_count*(obj: ptr TMenu, parent: ptr TListItem): cint{. # \param item A valid list item # -proc menu_disable_item*(menu: ptr TMenu, item: ptr TListItem){.cdecl, +proc menu_disable_item*(menu: ptr Menu, item: ptr ListItem){.cdecl, importc: "menu_disable_item", dynlib: clarodll.} #* # \brief Enables a menu item (allows focus and not greyed out) @@ -1742,7 +1752,7 @@ proc menu_disable_item*(menu: ptr TMenu, item: ptr TListItem){.cdecl, # \param item A valid list item # -proc menu_enable_item*(menu: ptr TMenu, item: ptr TListItem){.cdecl, +proc menu_enable_item*(menu: ptr Menu, item: ptr ListItem){.cdecl, importc: "menu_enable_item", dynlib: clarodll.} #* # \brief Pops up the menu at the position specified @@ -1753,7 +1763,7 @@ proc menu_enable_item*(menu: ptr TMenu, item: ptr TListItem){.cdecl, # \param flags Flags # -proc menu_popup*(menu: ptr TMenu, x: cint, y: cint, flags: cint){.cdecl, +proc menu_popup*(menu: ptr Menu, x: cint, y: cint, flags: cint){.cdecl, importc: "menu_popup", dynlib: clarodll.} # # Menu modifiers @@ -1764,8 +1774,8 @@ const cModifierCommand* = 1 shl 1 type - TMenubar* {.pure.} = object of TListWidget - + Menubar* {.pure.} = object of ListWidget +{.deprecated: [TMenubar: Menubar].} #* # \brief Creates a MenuBar widget # @@ -1774,7 +1784,7 @@ type # \return A new MenuBar widget object. # -proc newmenubar*(parent: ptr TClaroObj, flags: cint): ptr TMenubar {.cdecl, +proc newmenubar*(parent: ptr ClaroObj, flags: cint): ptr Menubar {.cdecl, importc: "menubar_widget_create", dynlib: clarodll.} #* # \brief Add a key binding to a menu items @@ -1785,7 +1795,7 @@ proc newmenubar*(parent: ptr TClaroObj, flags: cint): ptr TMenubar {.cdecl, # \param modifier The modifier key, or 0. # -proc menubar_add_key_binding*(menubar: ptr TMenubar, item: ptr TListItem, +proc menubar_add_key_binding*(menubar: ptr Menubar, item: ptr ListItem, utf8_key: cstring, modifier: cint){.cdecl, importc: "menubar_add_key_binding", dynlib: clarodll.} #* @@ -1798,8 +1808,8 @@ proc menubar_add_key_binding*(menubar: ptr TMenubar, item: ptr TListItem, # \return A new list item. # -proc menubar_append_item*(menubar: ptr TMenubar, parent: ptr TListItem, - image: ptr TImage, title: cstring): ptr TListItem{. +proc menubar_append_item*(menubar: ptr Menubar, parent: ptr ListItem, + image: ptr Image, title: cstring): ptr ListItem{. cdecl, importc: "menubar_append_item", dynlib: clarodll.} #* # \brief Insert a row into a MenuBar widget @@ -1812,9 +1822,9 @@ proc menubar_append_item*(menubar: ptr TMenubar, parent: ptr TListItem, # \return A new list item. # -proc menubar_insert_item*(menubar: ptr TMenubar, parent: ptr TListItem, - pos: cint, image: ptr TImage, - title: cstring): ptr TListItem{. +proc menubar_insert_item*(menubar: ptr Menubar, parent: ptr ListItem, + pos: cint, image: ptr Image, + title: cstring): ptr ListItem{. cdecl, importc: "menubar_insert_item", dynlib: clarodll.} #* # \brief Append a separator to a MenuBar widget @@ -1824,8 +1834,8 @@ proc menubar_insert_item*(menubar: ptr TMenubar, parent: ptr TListItem, # \return A new list item. # -proc menubar_append_separator*(menubar: ptr TMenubar, - parent: ptr TListItem): ptr TListItem{. +proc menubar_append_separator*(menubar: ptr Menubar, + parent: ptr ListItem): ptr ListItem{. cdecl, importc: "menubar_append_separator", dynlib: clarodll.} #* # \brief Insert a separator into a MenuBar widget @@ -1836,8 +1846,8 @@ proc menubar_append_separator*(menubar: ptr TMenubar, # \return A new list item. # -proc menubar_insert_separator*(menubar: ptr TMenubar, parent: ptr TListItem, - pos: cint): ptr TListItem{.cdecl, +proc menubar_insert_separator*(menubar: ptr Menubar, parent: ptr ListItem, + pos: cint): ptr ListItem{.cdecl, importc: "menubar_insert_separator", dynlib: clarodll.} #* # \brief Move a row in a MenuBar widget @@ -1847,7 +1857,7 @@ proc menubar_insert_separator*(menubar: ptr TMenubar, parent: ptr TListItem, # \param row New position to place this item # -proc menubar_move_item*(menubar: ptr TMenubar, item: ptr TListItem, +proc menubar_move_item*(menubar: ptr Menubar, item: ptr ListItem, row: cint){.cdecl, importc: "menubar_move_item", dynlib: clarodll.} #* @@ -1857,7 +1867,7 @@ proc menubar_move_item*(menubar: ptr TMenubar, item: ptr TListItem, # \param item A valid list item # -proc menubar_remove_item*(menubar: ptr TMenubar, item: ptr TListItem) {. +proc menubar_remove_item*(menubar: ptr Menubar, item: ptr ListItem) {. cdecl, importc: "menubar_remove_item", dynlib: clarodll.} #* # \brief Returns the number of rows in a MenuBar widget @@ -1868,7 +1878,7 @@ proc menubar_remove_item*(menubar: ptr TMenubar, item: ptr TListItem) {. # \return Number of rows # -proc menubar_item_count*(obj: ptr TMenubar, parent: ptr TListItem): cint{. +proc menubar_item_count*(obj: ptr Menubar, parent: ptr ListItem): cint{. cdecl, importc: "menubar_item_count", dynlib: clarodll.} #* # \brief Disables a menu item (no focus and greyed out) @@ -1877,7 +1887,7 @@ proc menubar_item_count*(obj: ptr TMenubar, parent: ptr TListItem): cint{. # \param item A valid list item # -proc menubar_disable_item*(menubar: ptr TMenubar, item: ptr TListItem){. +proc menubar_disable_item*(menubar: ptr Menubar, item: ptr ListItem){. cdecl, importc: "menubar_disable_item", dynlib: clarodll.} #* # \brief Enables a menu item (allows focus and not greyed out) @@ -1886,15 +1896,16 @@ proc menubar_disable_item*(menubar: ptr TMenubar, item: ptr TListItem){. # \param item A valid list item # -proc menubar_enable_item*(menubar: ptr TMenubar, item: ptr TListItem){. +proc menubar_enable_item*(menubar: ptr Menubar, item: ptr ListItem){. cdecl, importc: "menubar_enable_item", dynlib: clarodll.} type - TProgress* {.pure.} = object of TWidget + Progress* {.pure.} = object of Widget - TcProgressStyle* = enum + CProgressStyle* = enum cProgressLeftRight = 0x00000000, cProgressRightLeft = 0x00000001, cProgressTopBottom = 0x00000002, cProgressBottomTop = 0x00000004 +{.deprecated: [TProgress: Progress, TcProgressStyle: CProgressStyle].} #* # \brief Creates a Progress widget @@ -1905,8 +1916,8 @@ type # \return A new Progress widget object. # -proc newprogress*(parent: ptr TClaroObj, bounds: ptr TBounds, - flags: cint): ptr TProgress {. +proc newprogress*(parent: ptr ClaroObj, bounds: ptr Bounds, + flags: cint): ptr Progress {. cdecl, importc: "progress_widget_create", dynlib: clarodll.} #* # \brief Sets the value of a progress widget @@ -1915,7 +1926,7 @@ proc newprogress*(parent: ptr TClaroObj, bounds: ptr TBounds, # \param percentage Progress value # -proc progress_set_level*(progress: ptr TProgress, percentage: cdouble){.cdecl, +proc progress_set_level*(progress: ptr Progress, percentage: cdouble){.cdecl, importc: "progress_set_level", dynlib: clarodll.} #* # \brief Sets the orientation of a progress widget @@ -1924,19 +1935,19 @@ proc progress_set_level*(progress: ptr TProgress, percentage: cdouble){.cdecl, # \param flags One of the cProgressStyle values # -proc progress_set_orientation*(progress: ptr TProgress, flags: cint){.cdecl, +proc progress_set_orientation*(progress: ptr Progress, flags: cint){.cdecl, importc: "progress_set_orientation", dynlib: clarodll.} type - TRadioGroup* {.pure.} = object of TClaroObj - buttons*: TList - selected*: ptr TClaroObj + RadioGroup* {.pure.} = object of ClaroObj + buttons*: List + selected*: ptr ClaroObj ndata*: pointer - TRadioButton* {.pure.} = object of TWidget + RadioButton* {.pure.} = object of Widget text*: array[0..256-1, char] - group*: ptr TRadioGroup - + group*: ptr RadioGroup +{.deprecated: [TRadioGroup: RadioGroup, TRadioButton: RadioButton].} #* # \brief Creates a Radio Group widget @@ -1946,7 +1957,7 @@ type # \return A new Radio Group widget object. # -proc newRadiogroup*(parent: ptr TClaroObj, flags: cint): ptr TRadioGroup {. +proc newRadiogroup*(parent: ptr ClaroObj, flags: cint): ptr RadioGroup {. cdecl, importc: "radiogroup_create", dynlib: clarodll.} #* # \brief Creates a Radio Button widget @@ -1959,9 +1970,9 @@ proc newRadiogroup*(parent: ptr TClaroObj, flags: cint): ptr TRadioGroup {. # \return A new Radio Button widget object. # -proc newradiobutton*(parent: ptr TClaroObj, group: ptr TRadioGroup, - bounds: ptr TBounds, label: cstring, - flags: cint): ptr TRadioButton{. +proc newradiobutton*(parent: ptr ClaroObj, group: ptr RadioGroup, + bounds: ptr Bounds, label: cstring, + flags: cint): ptr RadioButton{. cdecl, importc: "radiobutton_widget_create", dynlib: clarodll.} #* # \brief Set the label of a Radio Button @@ -1970,7 +1981,7 @@ proc newradiobutton*(parent: ptr TClaroObj, group: ptr TRadioGroup, # \param label The new label for the Radio Button # -proc radiobutton_set_text*(obj: ptr TRadioButton, label: cstring){.cdecl, +proc radiobutton_set_text*(obj: ptr RadioButton, label: cstring){.cdecl, importc: "radiobutton_set_label", dynlib: clarodll.} #* # \brief Set the group of a Radio Button @@ -1979,18 +1990,18 @@ proc radiobutton_set_text*(obj: ptr TRadioButton, label: cstring){.cdecl, # \param group A valid Radio Group widget object # -proc radiobutton_set_group*(rbutton: ptr TRadioButton, group: ptr TRadioGroup){. +proc radiobutton_set_group*(rbutton: ptr RadioButton, group: ptr RadioGroup){. cdecl, importc: "radiobutton_set_group", dynlib: clarodll.} const CLARO_SCROLLBAR_MAXIMUM* = 256 type - TScrollbar* {.pure.} = object of TWidget + Scrollbar* {.pure.} = object of Widget min*: cint max*: cint pagesize*: cint - +{.deprecated: [TScrollbar: Scrollbar].} const cScrollbarHorizontal* = 0 @@ -2006,8 +2017,8 @@ const # \return A new ScrollBar widget object. # -proc newscrollbar*(parent: ptr TClaroObj, bounds: ptr TBounds, - flags: cint): ptr TScrollbar{. +proc newscrollbar*(parent: ptr ClaroObj, bounds: ptr Bounds, + flags: cint): ptr Scrollbar{. cdecl, importc: "scrollbar_widget_create", dynlib: clarodll.} #* # \brief Returns the width that scrollbars should be on this platform @@ -2026,7 +2037,7 @@ proc scrollbar_get_sys_width*(): cint{.cdecl, # \param max The maximum value # -proc scrollbar_set_range*(w: ptr TScrollbar, min: cint, max: cint){.cdecl, +proc scrollbar_set_range*(w: ptr Scrollbar, min: cint, max: cint){.cdecl, importc: "scrollbar_set_range", dynlib: clarodll.} #* # \brief Sets the position of a ScrollBar widget @@ -2035,7 +2046,7 @@ proc scrollbar_set_range*(w: ptr TScrollbar, min: cint, max: cint){.cdecl, # \param pos The new position # -proc scrollbar_set_pos*(w: ptr TScrollbar, pos: cint){.cdecl, +proc scrollbar_set_pos*(w: ptr Scrollbar, pos: cint){.cdecl, importc: "scrollbar_set_pos", dynlib: clarodll.} #* # \brief Gets the position of a ScrollBar widget @@ -2044,7 +2055,7 @@ proc scrollbar_set_pos*(w: ptr TScrollbar, pos: cint){.cdecl, # \return The current position # -proc scrollbar_get_pos*(w: ptr TScrollbar): cint{.cdecl, +proc scrollbar_get_pos*(w: ptr Scrollbar): cint{.cdecl, importc: "scrollbar_get_pos", dynlib: clarodll.} #* # \brief Sets the page size of a ScrollBar widget @@ -2053,20 +2064,21 @@ proc scrollbar_get_pos*(w: ptr TScrollbar): cint{.cdecl, # \param pagesize The size of a page (the number of units visible at one time) # -proc scrollbar_set_pagesize*(w: ptr TScrollbar, pagesize: cint){.cdecl, +proc scrollbar_set_pagesize*(w: ptr Scrollbar, pagesize: cint){.cdecl, importc: "scrollbar_set_pagesize", dynlib: clarodll.} type - TcSplitterChildren* = enum + CSplitterChildren* = enum cSplitterFirst = 0, cSplitterSecond = 1 - TSplitterChild* {.pure.} = object + SplitterChild* {.pure.} = object flex*: cint size*: cint - w*: ptr TWidget - - TSplitter* {.pure.} = object of TWidget - pair*: array[0..1, TSplitterChild] + w*: ptr Widget + Splitter* {.pure.} = object of Widget + pair*: array[0..1, SplitterChild] +{.deprecated: [TcSplitterChildren: CSplitterChildren, TSplitter: Splitter, + TSplitterChild: SplitterChild].} const cSplitterHorizontal* = 0 @@ -2082,8 +2094,8 @@ const # \return A new Splitter widget object. # -proc newsplitter*(parent: ptr TClaroObj, bounds: ptr TBounds, - flags: cint): ptr TSplitter{. +proc newsplitter*(parent: ptr ClaroObj, bounds: ptr Bounds, + flags: cint): ptr Splitter{. cdecl, importc: "splitter_widget_create", dynlib: clarodll.} #* # \brief Sets the sizing information of a child @@ -2095,13 +2107,14 @@ proc newsplitter*(parent: ptr TClaroObj, bounds: ptr TBounds, # \param size The size of this child # -proc splitter_set_info*(splitter: ptr TSplitter, child: cint, flex: cint, +proc splitter_set_info*(splitter: ptr Splitter, child: cint, flex: cint, size: cint){.cdecl, importc: "splitter_set_info", dynlib: clarodll.} type - TStatusbar* {.pure.} = object of TWidget + Statusbar* {.pure.} = object of Widget text*: array[0..256 - 1, char] +{.deprecated: [TStatusbar: Statusbar].} #* @@ -2112,7 +2125,7 @@ type # \return A new StatusBar widget object. # -proc newstatusbar*(parent: ptr TClaroObj, flags: cint): ptr TStatusbar {.cdecl, +proc newstatusbar*(parent: ptr ClaroObj, flags: cint): ptr Statusbar {.cdecl, importc: "statusbar_widget_create", dynlib: clarodll.} #* # \brief Sets the text of a statusbar @@ -2121,7 +2134,7 @@ proc newstatusbar*(parent: ptr TClaroObj, flags: cint): ptr TStatusbar {.cdecl, # \param text The new text # -proc statusbar_set_text*(obj: ptr TStatusbar, text: cstring){.cdecl, +proc statusbar_set_text*(obj: ptr Statusbar, text: cstring){.cdecl, importc: "statusbar_set_text", dynlib: clarodll.} #* # \brief obtains a stock image @@ -2130,7 +2143,7 @@ proc statusbar_set_text*(obj: ptr TStatusbar, text: cstring){.cdecl, # \return The Image object. # -proc stock_get_image*(stock_id: cstring): ptr TImage{.cdecl, +proc stock_get_image*(stock_id: cstring): ptr Image{.cdecl, importc: "stock_get_image", dynlib: clarodll.} #* # \brief adds a stock id image @@ -2140,15 +2153,16 @@ proc stock_get_image*(stock_id: cstring): ptr TImage{.cdecl, # \return The Image object. # -proc stock_add_image*(stock_id: cstring, img: ptr TImage){.cdecl, +proc stock_add_image*(stock_id: cstring, img: ptr Image){.cdecl, importc: "stock_add_image", dynlib: clarodll.} const CLARO_TEXTAREA_MAXIMUM = (1024 * 1024) type - TTextArea* {.pure.} = object of TWidget + TextArea* {.pure.} = object of Widget text*: array[0..CLARO_TEXTAREA_MAXIMUM - 1, char] +{.deprecated: [TTextArea: TextArea].} #* @@ -2160,8 +2174,8 @@ type # \return A new TextArea widget object. # -proc newtextarea*(parent: ptr TClaroObj, bounds: ptr TBounds, - flags: cint): ptr TTextArea{. +proc newtextarea*(parent: ptr ClaroObj, bounds: ptr Bounds, + flags: cint): ptr TextArea{. cdecl, importc: "textarea_widget_create", dynlib: clarodll.} #* # \brief Sets the text of a textarea @@ -2170,7 +2184,7 @@ proc newtextarea*(parent: ptr TClaroObj, bounds: ptr TBounds, # \param text The new text # -proc textarea_set_text*(obj: ptr TTextArea, text: cstring){.cdecl, +proc textarea_set_text*(obj: ptr TextArea, text: cstring){.cdecl, importc: "textarea_set_text", dynlib: clarodll.} #* # \brief Retrieve the text of a textarea @@ -2179,16 +2193,16 @@ proc textarea_set_text*(obj: ptr TTextArea, text: cstring){.cdecl, # \return Pointer to an internal reference of the text. Should not be changed. # -proc textarea_get_text*(obj: ptr TTextArea): cstring{.cdecl, +proc textarea_get_text*(obj: ptr TextArea): cstring{.cdecl, importc: "textarea_get_text", dynlib: clarodll.} const CLARO_TEXTBOX_MAXIMUM = 8192 type - TTextBox* {.pure.} = object of TWidget + TextBox* {.pure.} = object of Widget text*: array[0..CLARO_TEXTBOX_MAXIMUM-1, char] - +{.deprecated: [TTextBox: TextBox].} const cTextBoxTypePassword* = 1 @@ -2203,8 +2217,8 @@ const # \return A new TextBox widget object. # -proc newtextbox*(parent: ptr TClaroObj, bounds: ptr TBounds, - flags: cint): ptr TTextBox{. +proc newtextbox*(parent: ptr ClaroObj, bounds: ptr Bounds, + flags: cint): ptr TextBox{. cdecl, importc: "textbox_widget_create", dynlib: clarodll.} #* # \brief Sets the text of a textbox @@ -2213,7 +2227,7 @@ proc newtextbox*(parent: ptr TClaroObj, bounds: ptr TBounds, # \param text The new text # -proc textbox_set_text*(obj: ptr TTextBox, text: cstring){.cdecl, +proc textbox_set_text*(obj: ptr TextBox, text: cstring){.cdecl, importc: "textbox_set_text", dynlib: clarodll.} #* # \brief Retrieve the text of a textbox @@ -2222,7 +2236,7 @@ proc textbox_set_text*(obj: ptr TTextBox, text: cstring){.cdecl, # \return Pointer to an internal reference of the text. Should not be changed. # -proc textbox_get_text*(obj: ptr TTextBox): cstring{.cdecl, +proc textbox_get_text*(obj: ptr TextBox): cstring{.cdecl, importc: "textbox_get_text", dynlib: clarodll.} #* # \brief Retrieve the cursor position inside a textbox @@ -2231,7 +2245,7 @@ proc textbox_get_text*(obj: ptr TTextBox): cstring{.cdecl, # \return Cursor position inside TextBox # -proc textbox_get_pos*(obj: ptr TTextBox): cint{.cdecl, +proc textbox_get_pos*(obj: ptr TextBox): cint{.cdecl, importc: "textbox_get_pos", dynlib: clarodll.} #* # \brief Sets the cursor position inside a textbox @@ -2240,7 +2254,7 @@ proc textbox_get_pos*(obj: ptr TTextBox): cint{.cdecl, # \param pos New cursor position inside TextBox # -proc textbox_set_pos*(obj: ptr TTextBox, pos: cint){.cdecl, +proc textbox_set_pos*(obj: ptr TextBox, pos: cint){.cdecl, importc: "textbox_set_pos", dynlib: clarodll.} const @@ -2250,8 +2264,8 @@ const cToolbarAutoSizeButtons* = 4 type - TToolbar* {.pure.} = object of TListWidget - + Toolbar* {.pure.} = object of ListWidget +{.deprecated: [TToolbar: Toolbar].} #* # \brief Creates a ToolBar widget # @@ -2260,7 +2274,7 @@ type # \return A new ToolBar widget object. # -proc newtoolbar*(parent: ptr TClaroObj, flags: cint): ptr TToolbar{.cdecl, +proc newtoolbar*(parent: ptr ClaroObj, flags: cint): ptr Toolbar{.cdecl, importc: "toolbar_widget_create", dynlib: clarodll.} #* # \brief Append a row to a ToolBar widget @@ -2272,8 +2286,8 @@ proc newtoolbar*(parent: ptr TClaroObj, flags: cint): ptr TToolbar{.cdecl, # \return A new list item. # -proc toolbar_append_icon*(toolbar: ptr TToolbar, image: ptr TImage, - title: cstring, tooltip: cstring): ptr TListItem{. +proc toolbar_append_icon*(toolbar: ptr Toolbar, image: ptr Image, + title: cstring, tooltip: cstring): ptr ListItem{. cdecl, importc: "toolbar_append_icon", dynlib: clarodll.} #* # \brief Insert a row into a ToolBar widget @@ -2286,9 +2300,9 @@ proc toolbar_append_icon*(toolbar: ptr TToolbar, image: ptr TImage, # \return A new list item. # -proc toolbar_insert_icon*(toolbar: ptr TToolbar, pos: cint, - image: ptr TImage, title: cstring, - tooltip: cstring): ptr TListItem{. +proc toolbar_insert_icon*(toolbar: ptr Toolbar, pos: cint, + image: ptr Image, title: cstring, + tooltip: cstring): ptr ListItem{. cdecl, importc: "toolbar_insert_icon", dynlib: clarodll.} #* # \brief Append a separator to a ToolBar widget @@ -2297,7 +2311,7 @@ proc toolbar_insert_icon*(toolbar: ptr TToolbar, pos: cint, # \return A new list item. # -proc toolbar_append_separator*(toolbar: ptr TToolbar): ptr TListItem{.cdecl, +proc toolbar_append_separator*(toolbar: ptr Toolbar): ptr ListItem{.cdecl, importc: "toolbar_append_separator", dynlib: clarodll.} #* # \brief Insert a separator into a ToolBar widget @@ -2307,8 +2321,8 @@ proc toolbar_append_separator*(toolbar: ptr TToolbar): ptr TListItem{.cdecl, # \return A new list item. # -proc toolbar_insert_separator*(toolbar: ptr TToolbar, - pos: cint): ptr TListItem {. +proc toolbar_insert_separator*(toolbar: ptr Toolbar, + pos: cint): ptr ListItem {. cdecl, importc: "toolbar_insert_separator", dynlib: clarodll.} #* # \brief Assign a menu widget to an item. @@ -2321,8 +2335,8 @@ proc toolbar_insert_separator*(toolbar: ptr TToolbar, # \param menu Menu widget object, or NULL to remove a menu. # -proc toolbar_set_item_menu*(toolbar: ptr TToolbar, item: ptr TListItem, - menu: ptr TMenu){.cdecl, +proc toolbar_set_item_menu*(toolbar: ptr Toolbar, item: ptr ListItem, + menu: ptr Menu){.cdecl, importc: "toolbar_set_item_menu", dynlib: clarodll.} #* # \brief Move a row in a ToolBar widget @@ -2332,7 +2346,7 @@ proc toolbar_set_item_menu*(toolbar: ptr TToolbar, item: ptr TListItem, # \param row New position to place this item # -proc toolbar_move_icon*(toolbar: ptr TToolbar, item: ptr TListItem, +proc toolbar_move_icon*(toolbar: ptr Toolbar, item: ptr ListItem, row: cint){.cdecl, importc: "toolbar_move_icon", dynlib: clarodll.} #* @@ -2342,7 +2356,7 @@ proc toolbar_move_icon*(toolbar: ptr TToolbar, item: ptr TListItem, # \param item A valid list item # -proc toolbar_remove_icon*(toolbar: ptr TToolbar, item: ptr TListItem){. +proc toolbar_remove_icon*(toolbar: ptr Toolbar, item: ptr ListItem){. cdecl, importc: "toolbar_remove_icon", dynlib: clarodll.} #* # \brief Returns the number of rows in a ToolBar widget @@ -2351,16 +2365,16 @@ proc toolbar_remove_icon*(toolbar: ptr TToolbar, item: ptr TListItem){. # \return Number of rows # -proc toolbar_item_count*(obj: ptr TToolbar): cint{.cdecl, +proc toolbar_item_count*(obj: ptr Toolbar): cint{.cdecl, importc: "toolbar_item_count", dynlib: clarodll.} #* # \brief TreeView widget # type - TTreeview* {.pure.} = object of TListWidget - selected*: ptr TListItem - + Treeview* {.pure.} = object of ListWidget + selected*: ptr ListItem +{.deprecated: [TTreeview: Treeview].} # functions #* @@ -2372,8 +2386,8 @@ type # \return A new TreeView widget object. # -proc newtreeview*(parent: ptr TClaroObj, bounds: ptr TBounds, - flags: cint): ptr TTreeview{. +proc newtreeview*(parent: ptr ClaroObj, bounds: ptr Bounds, + flags: cint): ptr Treeview{. cdecl, importc: "treeview_widget_create", dynlib: clarodll.} #* # \brief Append a row to a TreeView @@ -2385,8 +2399,8 @@ proc newtreeview*(parent: ptr TClaroObj, bounds: ptr TBounds, # \return A new list item. # -proc treeview_append_row*(treeview: ptr TTreeview, parent: ptr TListItem, - image: ptr TImage, title: cstring): ptr TListItem{. +proc treeview_append_row*(treeview: ptr Treeview, parent: ptr ListItem, + image: ptr Image, title: cstring): ptr ListItem{. cdecl, importc: "treeview_append_row", dynlib: clarodll.} #* # \brief Insert a row at the specified position into a TreeView @@ -2399,9 +2413,9 @@ proc treeview_append_row*(treeview: ptr TTreeview, parent: ptr TListItem, # \return A new list item. # -proc treeview_insert_row*(treeview: ptr TTreeview, parent: ptr TListItem, - pos: cint, image: ptr TImage, - title: cstring): ptr TListItem{. +proc treeview_insert_row*(treeview: ptr Treeview, parent: ptr ListItem, + pos: cint, image: ptr Image, + title: cstring): ptr ListItem{. cdecl, importc: "treeview_insert_row", dynlib: clarodll.} #* # \brief Move a row in a TreeView @@ -2411,7 +2425,7 @@ proc treeview_insert_row*(treeview: ptr TTreeview, parent: ptr TListItem, # \param row New position to place this item # -proc treeview_move_row*(treeview: ptr TTreeview, item: ptr TListItem, +proc treeview_move_row*(treeview: ptr Treeview, item: ptr ListItem, row: cint){.cdecl, importc: "treeview_move_row", dynlib: clarodll.} #* @@ -2421,7 +2435,7 @@ proc treeview_move_row*(treeview: ptr TTreeview, item: ptr TListItem, # \param item A valid list item # -proc treeview_remove_row*(treeview: ptr TTreeview, item: ptr TListItem){. +proc treeview_remove_row*(treeview: ptr Treeview, item: ptr ListItem){. cdecl, importc: "treeview_remove_row", dynlib: clarodll.} #* # \brief Expand a row in a TreeView @@ -2430,7 +2444,7 @@ proc treeview_remove_row*(treeview: ptr TTreeview, item: ptr TListItem){. # \param item A valid list item # -proc treeview_expand*(treeview: ptr TTreeview, item: ptr TListItem){.cdecl, +proc treeview_expand*(treeview: ptr Treeview, item: ptr ListItem){.cdecl, importc: "treeview_expand", dynlib: clarodll.} #* # \brief Collapse a row in a TreeView @@ -2439,7 +2453,7 @@ proc treeview_expand*(treeview: ptr TTreeview, item: ptr TListItem){.cdecl, # \param item A valid list item # -proc treeview_collapse*(treeview: ptr TTreeview, item: ptr TListItem){.cdecl, +proc treeview_collapse*(treeview: ptr Treeview, item: ptr ListItem){.cdecl, importc: "treeview_collapse", dynlib: clarodll.} #* # \brief Returns the currently selected TreeView item @@ -2448,7 +2462,7 @@ proc treeview_collapse*(treeview: ptr TTreeview, item: ptr TListItem){.cdecl, # \return The currently selected TreeView item, or NULL if no item is selected. # -proc treeview_get_selected*(obj: ptr TTreeview): ptr TListItem{.cdecl, +proc treeview_get_selected*(obj: ptr Treeview): ptr ListItem{.cdecl, importc: "treeview_get_selected", dynlib: clarodll.} #* # \brief Returns the number of rows in a TreeView @@ -2459,7 +2473,7 @@ proc treeview_get_selected*(obj: ptr TTreeview): ptr TListItem{.cdecl, # \return Number of rows # -proc treeview_get_rows*(obj: ptr TTreeview, parent: ptr TListItem): cint{. +proc treeview_get_rows*(obj: ptr Treeview, parent: ptr ListItem): cint{. cdecl, importc: "treeview_get_rows", dynlib: clarodll.} #* # \brief Selects a row in a TreeView @@ -2468,7 +2482,7 @@ proc treeview_get_rows*(obj: ptr TTreeview, parent: ptr TListItem): cint{. # \param item A valid list item # -proc treeview_select_item*(obj: ptr TTreeview, item: ptr TListItem){.cdecl, +proc treeview_select_item*(obj: ptr Treeview, item: ptr ListItem){.cdecl, importc: "treeview_select_item", dynlib: clarodll.} const @@ -2477,15 +2491,15 @@ const cWindowNoResizing* = 4 type - TWindow* {.pure.} = object of TWidget + Window* {.pure.} = object of Widget title*: array[0..512 - 1, char] - icon*: ptr TImage - menubar*: ptr TWidget - workspace*: ptr TWidget + icon*: ptr Image + menubar*: ptr Widget + workspace*: ptr Widget exsp_tools*: cint exsp_status*: cint exsp_init*: cint - +{.deprecated: [TWindow: Window].} const cWindowFixedSize* = 1 @@ -2500,8 +2514,8 @@ const # \return A new Window widget object. # -proc newwindow*(parent: ptr TClaroObj, bounds: ptr TBounds, - flags: cint): ptr TWindow {. +proc newwindow*(parent: ptr ClaroObj, bounds: ptr Bounds, + flags: cint): ptr Window {. cdecl, importc: "window_widget_create", dynlib: clarodll.} #* # \brief Sets a Window's title @@ -2510,7 +2524,7 @@ proc newwindow*(parent: ptr TClaroObj, bounds: ptr TBounds, # \param title The new title for the window # -proc window_set_title*(w: ptr TWindow, title: cstring){.cdecl, +proc window_set_title*(w: ptr Window, title: cstring){.cdecl, importc: "window_set_title", dynlib: clarodll.} #* # \brief Makes a window visible @@ -2518,7 +2532,7 @@ proc window_set_title*(w: ptr TWindow, title: cstring){.cdecl, # \param w A valid Window widget object # -proc window_show*(w: ptr TWindow){.cdecl, importc: "window_show", +proc window_show*(w: ptr Window){.cdecl, importc: "window_show", dynlib: clarodll.} #* # \brief Makes a window invisible @@ -2526,7 +2540,7 @@ proc window_show*(w: ptr TWindow){.cdecl, importc: "window_show", # \param w A valid Window widget object # -proc window_hide*(w: ptr TWindow){.cdecl, importc: "window_hide", +proc window_hide*(w: ptr Window){.cdecl, importc: "window_hide", dynlib: clarodll.} #* # \brief Gives focus to a window @@ -2534,7 +2548,7 @@ proc window_hide*(w: ptr TWindow){.cdecl, importc: "window_hide", # \param w A valid Window widget object # -proc window_focus*(w: ptr TWindow){.cdecl, importc: "window_focus", +proc window_focus*(w: ptr Window){.cdecl, importc: "window_focus", dynlib: clarodll.} #* # \brief Maximises a window @@ -2542,7 +2556,7 @@ proc window_focus*(w: ptr TWindow){.cdecl, importc: "window_focus", # \param w A valid Window widget object # -proc window_maximize*(w: ptr TWindow){.cdecl, importc: "window_maximise", +proc window_maximize*(w: ptr Window){.cdecl, importc: "window_maximise", dynlib: clarodll.} #* # \brief Minimises a window @@ -2550,7 +2564,7 @@ proc window_maximize*(w: ptr TWindow){.cdecl, importc: "window_maximise", # \param w A valid Window widget object # -proc window_minimize*(w: ptr TWindow){.cdecl, importc: "window_minimise", +proc window_minimize*(w: ptr Window){.cdecl, importc: "window_minimise", dynlib: clarodll.} #* # \brief Restores a window @@ -2558,7 +2572,7 @@ proc window_minimize*(w: ptr TWindow){.cdecl, importc: "window_minimise", # \param w A valid Window widget object # -proc window_restore*(w: ptr TWindow){.cdecl, importc: "window_restore", +proc window_restore*(w: ptr Window){.cdecl, importc: "window_restore", dynlib: clarodll.} #* # \brief Sets a window's icon @@ -2567,7 +2581,7 @@ proc window_restore*(w: ptr TWindow){.cdecl, importc: "window_restore", # \param icon A valid Image object # -proc window_set_icon*(w: ptr TWindow, icon: ptr TImage){.cdecl, +proc window_set_icon*(w: ptr Window, icon: ptr Image){.cdecl, importc: "window_set_icon", dynlib: clarodll.} const @@ -2575,13 +2589,13 @@ const cWorkspaceTileVertically* = 1 type - TWorkspace*{.pure.} = object of TWidget + Workspace*{.pure.} = object of Widget - TWorkspaceWindow*{.pure.} = object of TWidget - icon*: ptr TImage + WorkspaceWindow*{.pure.} = object of Widget + icon*: ptr Image title*: array[0..512 - 1, char] - workspace*: ptr TWorkspace - + workspace*: ptr Workspace +{.deprecated: [TWorkspace: Workspace, TWorkspaceWindow: WorkspaceWindow].} # functions (workspace) #* @@ -2593,8 +2607,8 @@ type # \return A new Workspace widget object. # -proc newworkspace*(parent: ptr TClaroObj, bounds: ptr TBounds, - flags: cint): ptr TWorkspace{. +proc newworkspace*(parent: ptr ClaroObj, bounds: ptr Bounds, + flags: cint): ptr Workspace{. cdecl, importc: "workspace_widget_create", dynlib: clarodll.} #* # \brief Sets the active (visible) workspace child @@ -2603,7 +2617,7 @@ proc newworkspace*(parent: ptr TClaroObj, bounds: ptr TBounds, # \param child A valid workspace window widget # -proc workspace_set_active*(workspace: ptr TWorkspace, child: ptr TClaroObj){. +proc workspace_set_active*(workspace: ptr Workspace, child: ptr ClaroObj){. cdecl, importc: "workspace_set_active", dynlib: clarodll.} #* # \brief Returns the active (visible) workspace child @@ -2612,7 +2626,7 @@ proc workspace_set_active*(workspace: ptr TWorkspace, child: ptr TClaroObj){. # \return The active workspace window widget # -proc workspace_get_active*(workspace: ptr TWorkspace): ptr TWorkspace{.cdecl, +proc workspace_get_active*(workspace: ptr Workspace): ptr Workspace{.cdecl, importc: "workspace_get_active", dynlib: clarodll.} #* # \brief Cascades all workspace windows @@ -2620,7 +2634,7 @@ proc workspace_get_active*(workspace: ptr TWorkspace): ptr TWorkspace{.cdecl, # \param workspace A valid workspace widget # -proc workspace_cascade*(workspace: ptr TWorkspace){.cdecl, +proc workspace_cascade*(workspace: ptr Workspace){.cdecl, importc: "workspace_cascade", dynlib: clarodll.} #* # \brief Tiles all workspace windows @@ -2629,7 +2643,7 @@ proc workspace_cascade*(workspace: ptr TWorkspace){.cdecl, # \param dir The direction to tile child widgets # -proc workspace_tile*(workspace: ptr TWorkspace, dir: cint){.cdecl, +proc workspace_tile*(workspace: ptr Workspace, dir: cint){.cdecl, importc: "workspace_tile", dynlib: clarodll.} # functions (workspace_window) #* @@ -2641,9 +2655,9 @@ proc workspace_tile*(workspace: ptr TWorkspace, dir: cint){.cdecl, # \return A new Workspace widget object. # -proc newWorkspaceWindow*(parent: ptr TClaroObj, - bounds: ptr TBounds, - flags: cint): ptr TWorkspaceWindow{. +proc newWorkspaceWindow*(parent: ptr ClaroObj, + bounds: ptr Bounds, + flags: cint): ptr WorkspaceWindow{. cdecl, importc: "workspace_window_widget_create", dynlib: clarodll.} #* # \brief Sets the title of a Workspace Window widget @@ -2652,7 +2666,7 @@ proc newWorkspaceWindow*(parent: ptr TClaroObj, # \param title The new title for the widget # -proc workspace_window_set_title*(window: ptr TWorkspaceWindow, +proc workspace_window_set_title*(window: ptr WorkspaceWindow, title: cstring){.cdecl, importc: "workspace_window_set_title", dynlib: clarodll.} #* @@ -2661,7 +2675,7 @@ proc workspace_window_set_title*(window: ptr TWorkspaceWindow, # \param window A valid Workspace Window widget # -proc workspace_window_show*(window: ptr TWorkspaceWindow){.cdecl, +proc workspace_window_show*(window: ptr WorkspaceWindow){.cdecl, importc: "workspace_window_show", dynlib: clarodll.} #* # \brief Makes a Workspace Window widget invisible @@ -2669,7 +2683,7 @@ proc workspace_window_show*(window: ptr TWorkspaceWindow){.cdecl, # \param window A valid Workspace Window widget # -proc workspace_window_hide*(window: ptr TWorkspaceWindow){.cdecl, +proc workspace_window_hide*(window: ptr WorkspaceWindow){.cdecl, importc: "workspace_window_hide", dynlib: clarodll.} #* # \brief Restores a Workspace Window widget @@ -2677,7 +2691,7 @@ proc workspace_window_hide*(window: ptr TWorkspaceWindow){.cdecl, # \param window A valid Workspace Window widget # -proc workspace_window_restore*(window: ptr TWorkspaceWindow){.cdecl, +proc workspace_window_restore*(window: ptr WorkspaceWindow){.cdecl, importc: "workspace_window_restore", dynlib: clarodll.} # American spelling @@ -2687,7 +2701,7 @@ proc workspace_window_restore*(window: ptr TWorkspaceWindow){.cdecl, # \param window A valid Workspace Window widget # -proc workspace_window_minimize*(window: ptr TWorkspaceWindow){.cdecl, +proc workspace_window_minimize*(window: ptr WorkspaceWindow){.cdecl, importc: "workspace_window_minimise", dynlib: clarodll.} #* # \brief Maxmimises a Workspace Window widget @@ -2695,7 +2709,7 @@ proc workspace_window_minimize*(window: ptr TWorkspaceWindow){.cdecl, # \param window A valid Workspace Window widget # -proc workspace_window_maximize*(window: ptr TWorkspaceWindow){.cdecl, +proc workspace_window_maximize*(window: ptr WorkspaceWindow){.cdecl, importc: "workspace_window_maximise", dynlib: clarodll.} #* # \brief Sets the icon of a Workspace Window widget @@ -2704,7 +2718,7 @@ proc workspace_window_maximize*(window: ptr TWorkspaceWindow){.cdecl, # \param icon A valid Image object. # -proc workspace_window_set_icon*(w: ptr TWorkspaceWindow, icon: ptr TImage){. +proc workspace_window_set_icon*(w: ptr WorkspaceWindow, icon: ptr Image){. cdecl, importc: "workspace_window_set_icon", dynlib: clarodll.} claro_base_init() @@ -2720,9 +2734,9 @@ when not defined(testing) and isMainModule: var b = newButton(w, new_bounds(40, 45, 150, -1), 0, "Push my button!") - proc push_my_button(obj: ptr TClaroObj, event: ptr TEvent) {.cdecl.} = + proc push_my_button(obj: ptr ClaroObj, event: ptr Event) {.cdecl.} = textbox_set_text(t, "You pushed my button!") - var button = cast[ptr TButton](obj) + var button = cast[ptr Button](obj) button_set_text(button, "Ouch!") object_addhandler(b, "pushed", push_my_button) diff --git a/lib/wrappers/expat.nim b/lib/wrappers/expat.nim index a3d888201..e1897e2b4 100644 --- a/lib/wrappers/expat.nim +++ b/lib/wrappers/expat.nim @@ -13,9 +13,9 @@ when not defined(expatDll): const expatDll = "libexpat.so(.1|)" type - TParserStruct{.pure, final.} = object + ParserStruct{.pure, final.} = object - PParser* = ptr TParserStruct + PParser* = ptr ParserStruct # The XML_Status enum gives the possible return values for several # API functions. The preprocessor #defines are included so this @@ -30,11 +30,12 @@ type # Otherwise, the #define hackery is quite ugly and would have been # dropped. # +{.deprecated: [TParserStruct: ParserStruct].} type - TStatus*{.size: sizeof(cint).} = enum + Status*{.size: sizeof(cint).} = enum STATUS_ERROR = 0, STATUS_OK = 1, STATUS_SUSPENDED = 2 - TError*{.size: sizeof(cint).} = enum + Error*{.size: sizeof(cint).} = enum ERROR_NONE, ERROR_NO_MEMORY, ERROR_SYNTAX, ERROR_NO_ELEMENTS, ERROR_INVALID_TOKEN, ERROR_UNCLOSED_TOKEN, ERROR_PARTIAL_CHAR, ERROR_TAG_MISMATCH, ERROR_DUPLICATE_ATTRIBUTE, @@ -52,10 +53,12 @@ type ERROR_ABORTED, ERROR_FINISHED, ERROR_SUSPEND_PE, ERROR_RESERVED_PREFIX_XML, ERROR_RESERVED_PREFIX_XMLNS, ERROR_RESERVED_NAMESPACE_URI - TContent_Type*{.size: sizeof(cint).} = enum + ContentType*{.size: sizeof(cint).} = enum CTYPE_EMPTY = 1, CTYPE_ANY, CTYPE_MIXED, CTYPE_NAME, CTYPE_CHOICE, CTYPE_SEQ - TContent_Quant*{.size: sizeof(cint).} = enum + ContentQuant*{.size: sizeof(cint).} = enum CQUANT_NONE, CQUANT_OPT, CQUANT_REP, CQUANT_PLUS +{.deprecated: [TStatus: Status, TError: Error, TContent_Type: ContentType, + TContent_Quant: ContentQuant].} # If type == XML_CTYPE_EMPTY or XML_CTYPE_ANY, then quant will be # XML_CQUANT_NONE, and the other fields will be zero or NULL. @@ -76,13 +79,13 @@ type # type - TContent*{.pure, final.} = object - typ*: TContentType - quant*: TContentQuant + Content*{.pure, final.} = object + typ*: ContentType + quant*: ContentQuant name*: cstring numchildren*: cint - children*: ptr TContent - + children*: ptr Content +{.deprecated: [TContent: Content].} # This is called for an element declaration. See above for # description of the model argument. It's the caller's responsibility @@ -90,10 +93,11 @@ type # type - TElementDeclHandler* = proc (userData: pointer, name: cstring, - model: ptr TContent){.cdecl.} + ElementDeclHandler* = proc (userData: pointer, name: cstring, + model: ptr Content){.cdecl.} +{.deprecated: [TElementDeclHandler: ElementDeclHandler].} -proc setElementDeclHandler*(parser: PParser, eldecl: TElementDeclHandler){. +proc setElementDeclHandler*(parser: PParser, eldecl: ElementDeclHandler){. cdecl, importc: "XML_SetElementDeclHandler", dynlib: expatDll.} # The Attlist declaration handler is called for *each* attribute. So # a single Attlist declaration with multiple attributes declared will @@ -105,11 +109,12 @@ proc setElementDeclHandler*(parser: PParser, eldecl: TElementDeclHandler){. # type - TAttlistDeclHandler* = proc (userData: pointer, elname: cstring, + AttlistDeclHandler* = proc (userData: pointer, elname: cstring, attname: cstring, attType: cstring, dflt: cstring, isrequired: cint){.cdecl.} +{.deprecated: [TAttlistDeclHandler: AttlistDeclHandler].} -proc setAttlistDeclHandler*(parser: PParser, attdecl: TAttlistDeclHandler){. +proc setAttlistDeclHandler*(parser: PParser, attdecl: AttlistDeclHandler){. cdecl, importc: "XML_SetAttlistDeclHandler", dynlib: expatDll.} # The XML declaration handler is called for *both* XML declarations # and text declarations. The way to distinguish is that the version @@ -121,17 +126,18 @@ proc setAttlistDeclHandler*(parser: PParser, attdecl: TAttlistDeclHandler){. # type - TXmlDeclHandler* = proc (userData: pointer, version: cstring, + XmlDeclHandler* = proc (userData: pointer, version: cstring, encoding: cstring, standalone: cint){.cdecl.} +{.deprecated: [TXmlDeclHandler: XmlDeclHandler].} -proc setXmlDeclHandler*(parser: PParser, xmldecl: TXmlDeclHandler){.cdecl, +proc setXmlDeclHandler*(parser: PParser, xmldecl: XmlDeclHandler){.cdecl, importc: "XML_SetXmlDeclHandler", dynlib: expatDll.} type - TMemory_Handling_Suite*{.pure, final.} = object + Memory_Handling_Suite*{.pure, final.} = object mallocFcn*: proc (size: int): pointer{.cdecl.} reallocFcn*: proc (p: pointer, size: int): pointer{.cdecl.} freeFcn*: proc (p: pointer){.cdecl.} - +{.deprecated: [TMemory_Handling_Suite: MemoryHandlingSuite].} # Constructs a new parser; encoding is the encoding specified by the # external protocol or NULL if there is none specified. @@ -183,29 +189,33 @@ proc parserReset*(parser: PParser, encoding: cstring): bool{.cdecl, # type - TStartElementHandler* = proc (userData: pointer, name: cstring, + StartElementHandler* = proc (userData: pointer, name: cstring, atts: cstringArray){.cdecl.} - TEndElementHandler* = proc (userData: pointer, name: cstring){.cdecl.} - + EndElementHandler* = proc (userData: pointer, name: cstring){.cdecl.} +{.deprecated: [TStartElementHandler: StartElementHandler, + TEndElementHandler: EndElementHandler].} # s is not 0 terminated. type - TCharacterDataHandler* = proc (userData: pointer, s: cstring, len: cint){. + CharacterDataHandler* = proc (userData: pointer, s: cstring, len: cint){. cdecl.} - +{.deprecated: [TCharacterDataHandler: CharacterDataHandler].} # target and data are 0 terminated type - TProcessingInstructionHandler* = proc (userData: pointer, target: cstring, + ProcessingInstructionHandler* = proc (userData: pointer, target: cstring, data: cstring){.cdecl.} +{.deprecated: [TProcessingInstructionHandler: ProcessingInstructionHandler].} # data is 0 terminated type - TCommentHandler* = proc (userData: pointer, data: cstring){.cdecl.} - TStartCdataSectionHandler* = proc (userData: pointer){.cdecl.} - TEndCdataSectionHandler* = proc (userData: pointer){.cdecl.} - + CommentHandler* = proc (userData: pointer, data: cstring){.cdecl.} + StartCdataSectionHandler* = proc (userData: pointer){.cdecl.} + EndCdataSectionHandler* = proc (userData: pointer){.cdecl.} +{.deprecated: [TCommentHandler: CommentHandler, + TStartCdataSectionHandler: StartCdataSectionHandler, + TEndCdataSectionHandler: EndCdataSectionHandler].} # This is called for any characters in the XML document for which # there is no applicable handler. This includes both characters that # are part of markup which is of a kind that is not reported @@ -221,16 +231,17 @@ type # type - TDefaultHandler* = proc (userData: pointer, s: cstring, len: cint){.cdecl.} - + DefaultHandler* = proc (userData: pointer, s: cstring, len: cint){.cdecl.} +{.deprecated: [TDefaultHandler: DefaultHandler].} # This is called for the start of the DOCTYPE declaration, before # any DTD or internal subset is parsed. # type - TStartDoctypeDeclHandler* = proc (userData: pointer, doctypeName: cstring, + StartDoctypeDeclHandler* = proc (userData: pointer, doctypeName: cstring, sysid: cstring, pubid: cstring, hasInternalSubset: cint){.cdecl.} +{.deprecated: [TStartDoctypeDeclHandler: StartDoctypeDeclHandler].} # This is called for the start of the DOCTYPE declaration when the # closing > is encountered, but after processing any external @@ -238,7 +249,8 @@ type # type - TEndDoctypeDeclHandler* = proc (userData: pointer){.cdecl.} + EndDoctypeDeclHandler* = proc (userData: pointer){.cdecl.} +{.deprecated: [TEndDoctypeDeclHandler: EndDoctypeDeclHandler].} # This is called for entity declarations. The is_parameter_entity # argument will be non-zero if the entity is a parameter entity, zero @@ -260,13 +272,14 @@ type # type - TEntityDeclHandler* = proc (userData: pointer, entityName: cstring, + EntityDeclHandler* = proc (userData: pointer, entityName: cstring, isParameterEntity: cint, value: cstring, valueLength: cint, base: cstring, systemId: cstring, publicId: cstring, notationName: cstring){.cdecl.} +{.deprecated: [TEntityDeclHandler: EntityDeclHandler].} -proc setEntityDeclHandler*(parser: PParser, handler: TEntityDeclHandler){.cdecl, +proc setEntityDeclHandler*(parser: PParser, handler: EntityDeclHandler){.cdecl, importc: "XML_SetEntityDeclHandler", dynlib: expatDll.} # OBSOLETE -- OBSOLETE -- OBSOLETE # This handler has been superceded by the EntityDeclHandler above. @@ -279,10 +292,11 @@ proc setEntityDeclHandler*(parser: PParser, handler: TEntityDeclHandler){.cdecl, # type - TUnparsedEntityDeclHandler* = proc (userData: pointer, entityName: cstring, + UnparsedEntityDeclHandler* = proc (userData: pointer, entityName: cstring, base: cstring, systemId: cstring, publicId, notationName: cstring){. cdecl.} +{.deprecated: [TUnparsedEntityDeclHandler: UnparsedEntityDeclHandler].} # This is called for a declaration of notation. The base argument is # whatever was set by XML_SetBase. The notationName will never be @@ -290,9 +304,10 @@ type # type - TNotationDeclHandler* = proc (userData: pointer, notationName: cstring, + NotationDeclHandler* = proc (userData: pointer, notationName: cstring, base: cstring, systemId: cstring, publicId: cstring){.cdecl.} +{.deprecated: [TNotationDeclHandler: NotationDeclHandler].} # When namespace processing is enabled, these are called once for # each namespace declaration. The call to the start and end element @@ -302,10 +317,11 @@ type # type - TStartNamespaceDeclHandler* = proc (userData: pointer, prefix: cstring, + StartNamespaceDeclHandler* = proc (userData: pointer, prefix: cstring, uri: cstring){.cdecl.} - TEndNamespaceDeclHandler* = proc (userData: pointer, prefix: cstring){.cdecl.} - + EndNamespaceDeclHandler* = proc (userData: pointer, prefix: cstring){.cdecl.} +{.deprecated: [TStartNamespaceDeclHandler: StartNamespaceDeclHandler, + TEndNamespaceDeclHandler: EndNamespaceDeclHandler].} # This is called if the document is not standalone, that is, it has an # external subset or a reference to a parameter entity, but does not # have standalone="yes". If this handler returns XML_STATUS_ERROR, @@ -317,7 +333,8 @@ type # type - TNotStandaloneHandler* = proc (userData: pointer): cint{.cdecl.} + NotStandaloneHandler* = proc (userData: pointer): cint{.cdecl.} +{.deprecated: [TNotStandaloneHandler: NotStandaloneHandler].} # This is called for a reference to an external parsed general # entity. The referenced entity is not automatically parsed. The @@ -355,10 +372,10 @@ type # type - TExternalEntityRefHandler* = proc (parser: PParser, context: cstring, + ExternalEntityRefHandler* = proc (parser: PParser, context: cstring, base: cstring, systemId: cstring, publicId: cstring): cint{.cdecl.} - +{.deprecated: [TExternalEntityRefHandler: ExternalEntityRefHandler].} # This is called in two situations: # 1) An entity reference is encountered for which no declaration # has been read *and* this is not an error. @@ -371,8 +388,9 @@ type # type - TSkippedEntityHandler* = proc (userData: pointer, entityName: cstring, + SkippedEntityHandler* = proc (userData: pointer, entityName: cstring, isParameterEntity: cint){.cdecl.} +{.deprecated: [TSkippedEntityHandler: SkippedEntityHandler].} # This structure is filled in by the XML_UnknownEncodingHandler to # provide information to the parser about encodings that are unknown @@ -428,11 +446,12 @@ type # type - TEncoding*{.pure, final.} = object + Encoding*{.pure, final.} = object map*: array[0..256 - 1, cint] data*: pointer convert*: proc (data: pointer, s: cstring): cint{.cdecl.} release*: proc (data: pointer){.cdecl.} +{.deprecated: [TEncoding: Encoding].} # This is called for an encoding that is unknown to the parser. @@ -452,74 +471,75 @@ type # type - TUnknownEncodingHandler* = proc (encodingHandlerData: pointer, name: cstring, - info: ptr TEncoding): cint{.cdecl.} + UnknownEncodingHandler* = proc (encodingHandlerData: pointer, name: cstring, + info: ptr Encoding): cint{.cdecl.} +{.deprecated: [TUnknownEncodingHandler: UnknownEncodingHandler].} -proc setElementHandler*(parser: PParser, start: TStartElementHandler, - endHandler: TEndElementHandler){.cdecl, +proc setElementHandler*(parser: PParser, start: StartElementHandler, + endHandler: EndElementHandler){.cdecl, importc: "XML_SetElementHandler", dynlib: expatDll.} -proc setStartElementHandler*(parser: PParser, handler: TStartElementHandler){. +proc setStartElementHandler*(parser: PParser, handler: StartElementHandler){. cdecl, importc: "XML_SetStartElementHandler", dynlib: expatDll.} -proc setEndElementHandler*(parser: PParser, handler: TEndElementHandler){.cdecl, +proc setEndElementHandler*(parser: PParser, handler: EndElementHandler){.cdecl, importc: "XML_SetEndElementHandler", dynlib: expatDll.} -proc setCharacterDataHandler*(parser: PParser, handler: TCharacterDataHandler){. +proc setCharacterDataHandler*(parser: PParser, handler: CharacterDataHandler){. cdecl, importc: "XML_SetCharacterDataHandler", dynlib: expatDll.} proc setProcessingInstructionHandler*(parser: PParser, - handler: TProcessingInstructionHandler){. + handler: ProcessingInstructionHandler){. cdecl, importc: "XML_SetProcessingInstructionHandler", dynlib: expatDll.} -proc setCommentHandler*(parser: PParser, handler: TCommentHandler){.cdecl, +proc setCommentHandler*(parser: PParser, handler: CommentHandler){.cdecl, importc: "XML_SetCommentHandler", dynlib: expatDll.} -proc setCdataSectionHandler*(parser: PParser, start: TStartCdataSectionHandler, - endHandler: TEndCdataSectionHandler){.cdecl, +proc setCdataSectionHandler*(parser: PParser, start: StartCdataSectionHandler, + endHandler: EndCdataSectionHandler){.cdecl, importc: "XML_SetCdataSectionHandler", dynlib: expatDll.} proc setStartCdataSectionHandler*(parser: PParser, - start: TStartCdataSectionHandler){.cdecl, + start: StartCdataSectionHandler){.cdecl, importc: "XML_SetStartCdataSectionHandler", dynlib: expatDll.} proc setEndCdataSectionHandler*(parser: PParser, - endHandler: TEndCdataSectionHandler){.cdecl, + endHandler: EndCdataSectionHandler){.cdecl, importc: "XML_SetEndCdataSectionHandler", dynlib: expatDll.} # This sets the default handler and also inhibits expansion of # internal entities. These entity references will be passed to the # default handler, or to the skipped entity handler, if one is set. # -proc setDefaultHandler*(parser: PParser, handler: TDefaultHandler){.cdecl, +proc setDefaultHandler*(parser: PParser, handler: DefaultHandler){.cdecl, importc: "XML_SetDefaultHandler", dynlib: expatDll.} # This sets the default handler but does not inhibit expansion of # internal entities. The entity reference will not be passed to the # default handler. # -proc setDefaultHandlerExpand*(parser: PParser, handler: TDefaultHandler){.cdecl, +proc setDefaultHandlerExpand*(parser: PParser, handler: DefaultHandler){.cdecl, importc: "XML_SetDefaultHandlerExpand", dynlib: expatDll.} -proc setDoctypeDeclHandler*(parser: PParser, start: TStartDoctypeDeclHandler, - endHandler: TEndDoctypeDeclHandler){.cdecl, +proc setDoctypeDeclHandler*(parser: PParser, start: StartDoctypeDeclHandler, + endHandler: EndDoctypeDeclHandler){.cdecl, importc: "XML_SetDoctypeDeclHandler", dynlib: expatDll.} proc setStartDoctypeDeclHandler*(parser: PParser, - start: TStartDoctypeDeclHandler){.cdecl, + start: StartDoctypeDeclHandler){.cdecl, importc: "XML_SetStartDoctypeDeclHandler", dynlib: expatDll.} proc setEndDoctypeDeclHandler*(parser: PParser, - endHandler: TEndDoctypeDeclHandler){.cdecl, + endHandler: EndDoctypeDeclHandler){.cdecl, importc: "XML_SetEndDoctypeDeclHandler", dynlib: expatDll.} proc setUnparsedEntityDeclHandler*(parser: PParser, - handler: TUnparsedEntityDeclHandler){.cdecl, + handler: UnparsedEntityDeclHandler){.cdecl, importc: "XML_SetUnparsedEntityDeclHandler", dynlib: expatDll.} -proc setNotationDeclHandler*(parser: PParser, handler: TNotationDeclHandler){. +proc setNotationDeclHandler*(parser: PParser, handler: NotationDeclHandler){. cdecl, importc: "XML_SetNotationDeclHandler", dynlib: expatDll.} proc setNamespaceDeclHandler*(parser: PParser, - start: TStartNamespaceDeclHandler, - endHandler: TEndNamespaceDeclHandler){.cdecl, + start: StartNamespaceDeclHandler, + endHandler: EndNamespaceDeclHandler){.cdecl, importc: "XML_SetNamespaceDeclHandler", dynlib: expatDll.} proc setStartNamespaceDeclHandler*(parser: PParser, - start: TStartNamespaceDeclHandler){.cdecl, + start: StartNamespaceDeclHandler){.cdecl, importc: "XML_SetStartNamespaceDeclHandler", dynlib: expatDll.} proc setEndNamespaceDeclHandler*(parser: PParser, - endHandler: TEndNamespaceDeclHandler){.cdecl, + endHandler: EndNamespaceDeclHandler){.cdecl, importc: "XML_SetEndNamespaceDeclHandler", dynlib: expatDll.} -proc setNotStandaloneHandler*(parser: PParser, handler: TNotStandaloneHandler){. +proc setNotStandaloneHandler*(parser: PParser, handler: NotStandaloneHandler){. cdecl, importc: "XML_SetNotStandaloneHandler", dynlib: expatDll.} proc setExternalEntityRefHandler*(parser: PParser, - handler: TExternalEntityRefHandler){.cdecl, + handler: ExternalEntityRefHandler){.cdecl, importc: "XML_SetExternalEntityRefHandler", dynlib: expatDll.} # If a non-NULL value for arg is specified here, then it will be # passed as the first argument to the external entity ref handler @@ -528,10 +548,10 @@ proc setExternalEntityRefHandler*(parser: PParser, proc setExternalEntityRefHandlerArg*(parser: PParser, arg: pointer){.cdecl, importc: "XML_SetExternalEntityRefHandlerArg", dynlib: expatDll.} -proc setSkippedEntityHandler*(parser: PParser, handler: TSkippedEntityHandler){. +proc setSkippedEntityHandler*(parser: PParser, handler: SkippedEntityHandler){. cdecl, importc: "XML_SetSkippedEntityHandler", dynlib: expatDll.} proc setUnknownEncodingHandler*(parser: PParser, - handler: TUnknownEncodingHandler, + handler: UnknownEncodingHandler, encodingHandlerData: pointer){.cdecl, importc: "XML_SetUnknownEncodingHandler", dynlib: expatDll.} # This can be called within a handler for a start element, end @@ -573,7 +593,7 @@ template getUserData*(parser: expr): expr = # has no effect and returns XML_STATUS_ERROR. # -proc setEncoding*(parser: PParser, encoding: cstring): TStatus{.cdecl, +proc setEncoding*(parser: PParser, encoding: cstring): Status{.cdecl, importc: "XML_SetEncoding", dynlib: expatDll.} # If this function is called, then the parser will be passed as the # first argument to callbacks instead of userData. The userData will @@ -601,7 +621,7 @@ proc useParserAsHandlerArg*(parser: PParser){.cdecl, # XML_ERROR_FEATURE_REQUIRES_XML_DTD. # -proc useForeignDTD*(parser: PParser, useDTD: bool): TError{.cdecl, +proc useForeignDTD*(parser: PParser, useDTD: bool): Error{.cdecl, importc: "XML_UseForeignDTD", dynlib: expatDll.} # Sets the base to be used for resolving relative URIs in system # identifiers in declarations. Resolving relative identifiers is @@ -612,7 +632,7 @@ proc useForeignDTD*(parser: PParser, useDTD: bool): TError{.cdecl, # XML_STATUS_OK otherwise. # -proc setBase*(parser: PParser, base: cstring): TStatus{.cdecl, +proc setBase*(parser: PParser, base: cstring): Status{.cdecl, importc: "XML_SetBase", dynlib: expatDll.} proc getBase*(parser: PParser): cstring{.cdecl, importc: "XML_GetBase", dynlib: expatDll.} @@ -643,11 +663,11 @@ proc getIdAttributeIndex*(parser: PParser): cint{.cdecl, # values. # -proc parse*(parser: PParser, s: cstring, len: cint, isFinal: cint): TStatus{. +proc parse*(parser: PParser, s: cstring, len: cint, isFinal: cint): Status{. cdecl, importc: "XML_Parse", dynlib: expatDll.} proc getBuffer*(parser: PParser, len: cint): pointer{.cdecl, importc: "XML_GetBuffer", dynlib: expatDll.} -proc parseBuffer*(parser: PParser, len: cint, isFinal: cint): TStatus{.cdecl, +proc parseBuffer*(parser: PParser, len: cint, isFinal: cint): Status{.cdecl, importc: "XML_ParseBuffer", dynlib: expatDll.} # Stops parsing, causing XML_Parse() or XML_ParseBuffer() to return. # Must be called from within a call-back handler, except when aborting @@ -681,7 +701,7 @@ proc parseBuffer*(parser: PParser, len: cint, isFinal: cint): TStatus{.cdecl, # When suspended, parsing can be resumed by calling XML_ResumeParser(). # -proc stopParser*(parser: PParser, resumable: bool): TStatus{.cdecl, +proc stopParser*(parser: PParser, resumable: bool): Status{.cdecl, importc: "XML_StopParser", dynlib: expatDll.} # Resumes parsing after it has been suspended with XML_StopParser(). # Must not be called from within a handler call-back. Returns same @@ -696,15 +716,16 @@ proc stopParser*(parser: PParser, resumable: bool): TStatus{.cdecl, # application to call XML_ResumeParser() on it at the appropriate moment. # -proc resumeParser*(parser: PParser): TStatus{.cdecl, +proc resumeParser*(parser: PParser): Status{.cdecl, importc: "XML_ResumeParser", dynlib: expatDll.} type TParsing* = enum INITIALIZED, PARSING, FINISHED, SUSPENDED - TParsingStatus*{.pure, final.} = object + ParsingStatus*{.pure, final.} = object parsing*: TParsing finalBuffer*: bool - +{.deprecated: [#TParsing: Parsing, # Naming conflict if we drop the `T` + TParsingStatus: ParsingStatus].} # Returns status of parser with respect to being initialized, parsing, # finished, or suspended and processing the final buffer. @@ -712,7 +733,7 @@ type # XXX with XML_FINISHED_OK or XML_FINISHED_ERROR replacing XML_FINISHED # -proc getParsingStatus*(parser: PParser, status: ptr TParsingStatus){.cdecl, +proc getParsingStatus*(parser: PParser, status: ptr ParsingStatus){.cdecl, importc: "XML_GetParsingStatus", dynlib: expatDll.} # Creates an XML_Parser object that can parse an external general # entity; context is a '\0'-terminated string specifying the parse @@ -735,9 +756,10 @@ proc externalEntityParserCreate*(parser: PParser, context: cstring, encoding: cstring): PParser{.cdecl, importc: "XML_ExternalEntityParserCreate", dynlib: expatDll.} type - TParamEntityParsing* = enum + ParamEntityParsing* = enum PARAM_ENTITY_PARSING_NEVER, PARAM_ENTITY_PARSING_UNLESS_STANDALONE, PARAM_ENTITY_PARSING_ALWAYS +{.deprecated: [TParamEntityParsing: ParamEntityParsing].} # Controls parsing of parameter entities (including the external DTD # subset). If parsing of parameter entities is enabled, then @@ -763,13 +785,13 @@ type # XML_ParseBuffer, then it has no effect and will always return 0. # -proc setParamEntityParsing*(parser: PParser, parsing: TParamEntityParsing): cint{. +proc setParamEntityParsing*(parser: PParser, parsing: ParamEntityParsing): cint{. cdecl, importc: "XML_SetParamEntityParsing", dynlib: expatDll.} # If XML_Parse or XML_ParseBuffer have returned XML_STATUS_ERROR, then # XML_GetErrorCode returns information about the error. # -proc getErrorCode*(parser: PParser): TError{.cdecl, importc: "XML_GetErrorCode", +proc getErrorCode*(parser: PParser): Error{.cdecl, importc: "XML_GetErrorCode", dynlib: expatDll.} # These functions return information about the current parse # location. They may be called from any callback called to report @@ -815,7 +837,7 @@ proc getInputContext*(parser: PParser, offset: ptr cint, size: ptr cint): cstrin cdecl, importc: "XML_GetInputContext", dynlib: expatDll.} # Frees the content model passed to the element declaration handler -proc freeContentModel*(parser: PParser, model: ptr TContent){.cdecl, +proc freeContentModel*(parser: PParser, model: ptr Content){.cdecl, importc: "XML_FreeContentModel", dynlib: expatDll.} # Exposing the memory handling functions used in Expat @@ -831,39 +853,39 @@ proc parserFree*(parser: PParser){.cdecl, importc: "XML_ParserFree", dynlib: expatDll.} # Returns a string describing the error. -proc errorString*(code: TError): cstring{.cdecl, importc: "XML_ErrorString", +proc errorString*(code: Error): cstring{.cdecl, importc: "XML_ErrorString", dynlib: expatDll.} # Return a string containing the version number of this expat proc expatVersion*(): cstring{.cdecl, importc: "XML_ExpatVersion", dynlib: expatDll.} type - TExpat_Version*{.pure, final.} = object + Expat_Version*{.pure, final.} = object major*: cint minor*: cint micro*: cint - +{.deprecated: [TExpat_Version: ExpatVersion].} # Return an XML_Expat_Version structure containing numeric version # number information for this version of expat. # -proc expatVersionInfo*(): TExpatVersion{.cdecl, +proc expatVersionInfo*(): ExpatVersion{.cdecl, importc: "XML_ExpatVersionInfo", dynlib: expatDll.} # Added in Expat 1.95.5. type - TFeatureEnum* = enum + FeatureEnum* = enum FEATURE_END = 0, FEATURE_UNICODE, FEATURE_UNICODE_WCHAR_T, FEATURE_DTD, FEATURE_CONTEXT_BYTES, FEATURE_MIN_SIZE, FEATURE_SIZEOF_XML_CHAR, FEATURE_SIZEOF_XML_LCHAR, FEATURE_NS, FEATURE_LARGE_SIZE # Additional features must be added to the end of this enum. - TFeature*{.pure, final.} = object - feature*: TFeatureEnum + Feature*{.pure, final.} = object + feature*: FeatureEnum name*: cstring value*: int +{.deprecated: [TFeatureEnum: FeatureEnum, TFeature: Feature].} - -proc getFeatureList*(): ptr TFeature{.cdecl, importc: "XML_GetFeatureList", +proc getFeatureList*(): ptr Feature{.cdecl, importc: "XML_GetFeatureList", dynlib: expatDll.} # Expat follows the GNU/Linux convention of odd number minor version for # beta/development releases and even number minor version for stable diff --git a/lib/wrappers/joyent_http_parser.nim b/lib/wrappers/joyent_http_parser.nim index a008da43e..2fed392b9 100644 --- a/lib/wrappers/joyent_http_parser.nim +++ b/lib/wrappers/joyent_http_parser.nim @@ -1,20 +1,20 @@ type csize = int - HttpDataProc* = proc (a2: ptr THttpParser, at: cstring, length: csize): cint {.cdecl.} - HttpProc* = proc (a2: ptr THttpParser): cint {.cdecl.} + HttpDataProc* = proc (a2: ptr HttpParser, at: cstring, length: csize): cint {.cdecl.} + HttpProc* = proc (a2: ptr HttpParser): cint {.cdecl.} - THttpMethod* = enum + HttpMethod* = enum HTTP_DELETE = 0, HTTP_GET, HTTP_HEAD, HTTP_POST, HTTP_PUT, HTTP_CONNECT, HTTP_OPTIONS, HTTP_TRACE, HTTP_COPY, HTTP_LOCK, HTTP_MKCOL, HTTP_MOVE, HTTP_PROPFIND, HTTP_PROPPATCH, HTTP_UNLOCK, HTTP_REPORT, HTTP_MKACTIVITY, HTTP_CHECKOUT, HTTP_MERGE, HTTP_MSEARCH, HTTP_NOTIFY, HTTP_SUBSCRIBE, HTTP_UNSUBSCRIBE, HTTP_PATCH - THttpParserType* = enum + HttpParserType* = enum HTTP_REQUEST, HTTP_RESPONSE, HTTP_BOTH - TParserFlag* = enum + ParserFlag* = enum F_CHUNKED = 1 shl 0, F_CONNECTION_KEEP_ALIVE = 1 shl 1, F_CONNECTION_CLOSE = 1 shl 2, @@ -22,7 +22,7 @@ type F_UPGRADE = 1 shl 4, F_SKIPBODY = 1 shl 5 - THttpErrNo* = enum + HttpErrNo* = enum HPE_OK, HPE_CB_message_begin, HPE_CB_path, HPE_CB_query_string, HPE_CB_url, HPE_CB_fragment, HPE_CB_header_field, HPE_CB_header_value, HPE_CB_headers_complete, HPE_CB_body, HPE_CB_message_complete, @@ -34,7 +34,7 @@ type HPE_INVALID_CHUNK_SIZE, HPE_INVALID_CONSTANT, HPE_INVALID_INTERNAL_STATE, HPE_STRICT, HPE_UNKNOWN - THttpParser*{.pure, final, importc: "http_parser", header: "http_parser.h".} = object + HttpParser*{.pure, final, importc: "http_parser", header: "http_parser.h".} = object typ {.importc: "type".}: char flags {.importc: "flags".}: char state*{.importc: "state".}: char @@ -50,7 +50,7 @@ type upgrade {.importc: "upgrade".}: bool data*{.importc: "data".}: pointer - THttpParserSettings*{.pure, final, importc: "http_parser_settings", header: "http_parser.h".} = object + HttpParserSettings*{.pure, final, importc: "http_parser_settings", header: "http_parser.h".} = object on_message_begin*{.importc: "on_message_begin".}: HttpProc on_url*{.importc: "on_url".}: HttpDataProc on_header_field*{.importc: "on_header_field".}: HttpDataProc @@ -58,24 +58,27 @@ type on_headers_complete*{.importc: "on_headers_complete".}: HttpProc on_body*{.importc: "on_body".}: HttpDataProc on_message_complete*{.importc: "on_message_complete".}: HttpProc +{.deprecated: [THttpMethod: HttpMethod, THttpParserType: HttpParserType, + TParserFlag: ParserFlag, THttpErrNo: HttpErrNo, + THttpParser: HttpParser, THttpParserSettings: HttpParserSettings].} -proc http_parser_init*(parser: var THttpParser, typ: THttpParserType){. +proc http_parser_init*(parser: var HttpParser, typ: HttpParserType){. importc: "http_parser_init", header: "http_parser.h".} -proc http_parser_execute*(parser: var THttpParser, - settings: var THttpParserSettings, data: cstring, +proc http_parser_execute*(parser: var HttpParser, + settings: var HttpParserSettings, data: cstring, len: csize): csize {. importc: "http_parser_execute", header: "http_parser.h".} -proc http_should_keep_alive*(parser: var THttpParser): cint{. +proc http_should_keep_alive*(parser: var HttpParser): cint{. importc: "http_should_keep_alive", header: "http_parser.h".} -proc http_method_str*(m: THttpMethod): cstring{. +proc http_method_str*(m: HttpMethod): cstring{. importc: "http_method_str", header: "http_parser.h".} -proc http_errno_name*(err: THttpErrNo): cstring{. +proc http_errno_name*(err: HttpErrNo): cstring{. importc: "http_errno_name", header: "http_parser.h".} -proc http_errno_description*(err: THttpErrNo): cstring{. +proc http_errno_description*(err: HttpErrNo): cstring{. importc: "http_errno_description", header: "http_parser.h".} diff --git a/lib/wrappers/libcurl.nim b/lib/wrappers/libcurl.nim index 8c962f6cb..924879e75 100644 --- a/lib/wrappers/libcurl.nim +++ b/lib/wrappers/libcurl.nim @@ -31,47 +31,47 @@ elif defined(unix): const libname = "libcurl.so.4" type - Pcalloc_callback* = ptr Tcalloc_callback - Pclosepolicy* = ptr Tclosepolicy - Pforms* = ptr Tforms - Pftpauth* = ptr Tftpauth - Pftpmethod* = ptr Tftpmethod - Pftpssl* = ptr Tftpssl - PHTTP_VERSION* = ptr THTTP_VERSION - Phttppost* = ptr Thttppost + Pcalloc_callback* = ptr Calloc_callback + Pclosepolicy* = ptr Closepolicy + Pforms* = ptr Forms + Pftpauth* = ptr Ftpauth + Pftpmethod* = ptr Ftpmethod + Pftpssl* = ptr Ftpssl + PHTTP_VERSION* = ptr HTTP_VERSION + Phttppost* = ptr Httppost PPcurl_httppost* = ptr Phttppost - Pinfotype* = ptr Tinfotype - Plock_access* = ptr Tlock_access - Plock_data* = ptr Tlock_data - Pmalloc_callback* = ptr Tmalloc_callback - PNETRC_OPTION* = ptr TNETRC_OPTION - Pproxytype* = ptr Tproxytype - Prealloc_callback* = ptr Trealloc_callback - Pslist* = ptr Tslist - Psocket* = ptr Tsocket - PSSL_VERSION* = ptr TSSL_VERSION - Pstrdup_callback* = ptr Tstrdup_callback - PTIMECOND* = ptr TTIMECOND - Pversion_info_data* = ptr Tversion_info_data - Pcode* = ptr Tcode - PFORMcode* = ptr TFORMcode - Pformoption* = ptr Tformoption - PINFO* = ptr TINFO - Piocmd* = ptr Tiocmd - Pioerr* = ptr Tioerr - PM* = ptr TM - PMcode* = ptr TMcode - PMoption* = ptr TMoption - PMSG* = ptr TMSG - Poption* = ptr Toption - PSH* = ptr TSH - PSHcode* = ptr TSHcode - PSHoption* = ptr TSHoption - Pversion* = ptr Tversion + Pinfotype* = ptr Infotype + Plock_access* = ptr Lock_access + Plock_data* = ptr Lock_data + Pmalloc_callback* = ptr Malloc_callback + PNETRC_OPTION* = ptr NETRC_OPTION + Pproxytype* = ptr Proxytype + Prealloc_callback* = ptr Realloc_callback + Pslist* = ptr Slist + Psocket* = ptr Socket + PSSL_VERSION* = ptr SSL_VERSION + Pstrdup_callback* = ptr Strdup_callback + PTIMECOND* = ptr TIMECOND + Pversion_info_data* = ptr Version_info_data + Pcode* = ptr Code + PFORMcode* = ptr FORMcode + Pformoption* = ptr Formoption + PINFO* = ptr INFO + Piocmd* = ptr Iocmd + Pioerr* = ptr Ioerr + PM* = ptr M + PMcode* = ptr Mcode + PMoption* = ptr Moption + PMSG* = ptr MSG + Poption* = ptr Option + PSH* = ptr SH + PSHcode* = ptr SHcode + PSHoption* = ptr SHoption + Pversion* = ptr Version Pfd_set* = pointer - PCurl* = ptr TCurl - TCurl* = pointer - Thttppost*{.final, pure.} = object + PCurl* = ptr Curl + Curl* = pointer + Httppost*{.final, pure.} = object next*: Phttppost name*: cstring namelength*: int32 @@ -85,32 +85,32 @@ type flags*: int32 showfilename*: cstring - Tprogress_callback* = proc (clientp: pointer, dltotal: float64, + Progress_callback* = proc (clientp: pointer, dltotal: float64, dlnow: float64, ultotal: float64, ulnow: float64): int32 {.cdecl.} - Twrite_callback* = proc (buffer: cstring, size: int, nitems: int, + Write_callback* = proc (buffer: cstring, size: int, nitems: int, outstream: pointer): int{.cdecl.} - Tread_callback* = proc (buffer: cstring, size: int, nitems: int, + Read_callback* = proc (buffer: cstring, size: int, nitems: int, instream: pointer): int{.cdecl.} - Tpasswd_callback* = proc (clientp: pointer, prompt: cstring, buffer: cstring, + Passwd_callback* = proc (clientp: pointer, prompt: cstring, buffer: cstring, buflen: int32): int32{.cdecl.} - Tioerr* = enum + Ioerr* = enum IOE_OK, IOE_UNKNOWNCMD, IOE_FAILRESTART, IOE_LAST - Tiocmd* = enum + Iocmd* = enum IOCMD_NOP, IOCMD_RESTARTREAD, IOCMD_LAST - Tioctl_callback* = proc (handle: PCurl, cmd: int32, clientp: pointer): Tioerr{. + Ioctl_callback* = proc (handle: PCurl, cmd: int32, clientp: pointer): Ioerr{. cdecl.} - Tmalloc_callback* = proc (size: int): pointer{.cdecl.} - Tfree_callback* = proc (p: pointer){.cdecl.} - Trealloc_callback* = proc (p: pointer, size: int): pointer{.cdecl.} - Tstrdup_callback* = proc (str: cstring): cstring{.cdecl.} - Tcalloc_callback* = proc (nmemb: int, size: int): pointer{.noconv.} - Tinfotype* = enum + Malloc_callback* = proc (size: int): pointer{.cdecl.} + Free_callback* = proc (p: pointer){.cdecl.} + Realloc_callback* = proc (p: pointer, size: int): pointer{.cdecl.} + Strdup_callback* = proc (str: cstring): cstring{.cdecl.} + Calloc_callback* = proc (nmemb: int, size: int): pointer{.noconv.} + Infotype* = enum INFO_TEXT = 0, INFO_HEADER_IN, INFO_HEADER_OUT, INFO_DATA_IN, INFO_DATA_OUT, INFO_SSL_DATA_IN, INFO_SSL_DATA_OUT, INFO_END - Tdebug_callback* = proc (handle: PCurl, theType: Tinfotype, data: cstring, + Debug_callback* = proc (handle: PCurl, theType: Infotype, data: cstring, size: int, userptr: pointer): int32{.cdecl.} - Tcode* = enum + Code* = enum E_OK = 0, E_UNSUPPORTED_PROTOCOL, E_FAILED_INIT, E_URL_MALFORMAT, E_URL_MALFORMAT_USER, E_COULDNT_RESOLVE_PROXY, E_COULDNT_RESOLVE_HOST, E_COULDNT_CONNECT, E_FTP_WEIRD_SERVER_REPLY, E_FTP_ACCESS_DENIED, @@ -135,18 +135,18 @@ type E_LOGIN_DENIED, E_TFTP_NOTFOUND, E_TFTP_PERM, E_TFTP_DISKFULL, E_TFTP_ILLEGAL, E_TFTP_UNKNOWNID, E_TFTP_EXISTS, E_TFTP_NOSUCHUSER, E_CONV_FAILED, E_CONV_REQD, LAST - Tconv_callback* = proc (buffer: cstring, len: int): Tcode{.cdecl.} - Tssl_ctx_callback* = proc (curl: PCurl, ssl_ctx, userptr: pointer): Tcode{.cdecl.} - Tproxytype* = enum + Conv_callback* = proc (buffer: cstring, len: int): Code{.cdecl.} + Ssl_ctx_callback* = proc (curl: PCurl, ssl_ctx, userptr: pointer): Code{.cdecl.} + Proxytype* = enum PROXY_HTTP = 0, PROXY_SOCKS4 = 4, PROXY_SOCKS5 = 5 - Tftpssl* = enum + Ftpssl* = enum FTPSSL_NONE, FTPSSL_TRY, FTPSSL_CONTROL, FTPSSL_ALL, FTPSSL_LAST - Tftpauth* = enum + Ftpauth* = enum FTPAUTH_DEFAULT, FTPAUTH_SSL, FTPAUTH_TLS, FTPAUTH_LAST - Tftpmethod* = enum + Ftpmethod* = enum FTPMETHOD_DEFAULT, FTPMETHOD_MULTICWD, FTPMETHOD_NOCWD, FTPMETHOD_SINGLECWD, FTPMETHOD_LAST - Toption* = enum + Option* = enum OPT_PORT = 0 + 3, OPT_TIMEOUT = 0 + 13, OPT_INFILESIZE = 0 + 14, OPT_LOW_SPEED_LIMIT = 0 + 19, OPT_LOW_SPEED_TIME = 0 + 20, OPT_RESUME_FROM = 0 + 21, OPT_CRLF = 0 + 27, OPT_SSLVERSION = 0 + 32, @@ -211,37 +211,37 @@ type OPT_MAXFILESIZE_LARGE = 30000 + 117, OPT_POSTFIELDSIZE_LARGE = 30000 + 120, OPT_MAX_SEND_SPEED_LARGE = 30000 + 145, OPT_MAX_RECV_SPEED_LARGE = 30000 + 146 - THTTP_VERSION* = enum + HTTP_VERSION* = enum HTTP_VERSION_NONE, HTTP_VERSION_1_0, HTTP_VERSION_1_1, HTTP_VERSION_LAST - TNETRC_OPTION* = enum + NETRC_OPTION* = enum NETRC_IGNORED, NETRC_OPTIONAL, NETRC_REQUIRED, NETRC_LAST - TSSL_VERSION* = enum + SSL_VERSION* = enum SSLVERSION_DEFAULT, SSLVERSION_TLSv1, SSLVERSION_SSLv2, SSLVERSION_SSLv3, SSLVERSION_LAST - TTIMECOND* = enum + TIMECOND* = enum TIMECOND_NONE, TIMECOND_IFMODSINCE, TIMECOND_IFUNMODSINCE, TIMECOND_LASTMOD, TIMECOND_LAST - Tformoption* = enum + Formoption* = enum FORM_NOTHING, FORM_COPYNAME, FORM_PTRNAME, FORM_NAMELENGTH, FORM_COPYCONTENTS, FORM_PTRCONTENTS, FORM_CONTENTSLENGTH, FORM_FILECONTENT, FORM_ARRAY, FORM_OBSOLETE, FORM_FILE, FORM_BUFFER, FORM_BUFFERPTR, FORM_BUFFERLENGTH, FORM_CONTENTTYPE, FORM_CONTENTHEADER, FORM_FILENAME, FORM_END, FORM_OBSOLETE2, FORM_LASTENTRY - Tforms*{.pure, final.} = object - option*: Tformoption + Forms*{.pure, final.} = object + option*: Formoption value*: cstring - TFORMcode* = enum + FORMcode* = enum FORMADD_OK, FORMADD_MEMORY, FORMADD_OPTION_TWICE, FORMADD_NULL, FORMADD_UNKNOWN_OPTION, FORMADD_INCOMPLETE, FORMADD_ILLEGAL_ARRAY, FORMADD_DISABLED, FORMADD_LAST - Tformget_callback* = proc (arg: pointer, buf: cstring, length: int): int{. + Formget_callback* = proc (arg: pointer, buf: cstring, length: int): int{. cdecl.} - Tslist*{.pure, final.} = object + Slist*{.pure, final.} = object data*: cstring next*: Pslist - TINFO* = enum + INFO* = enum INFO_NONE = 0, INFO_LASTONE = 30, INFO_EFFECTIVE_URL = 0x00100000 + 1, INFO_CONTENT_TYPE = 0x00100000 + 18, INFO_PRIVATE = 0x00100000 + 21, INFO_FTP_ENTRY_PATH = 0x00100000 + 30, INFO_RESPONSE_CODE = 0x00200000 + 2, @@ -261,31 +261,31 @@ type INFO_STARTTRANSFER_TIME = 0x00300000 + 17, INFO_REDIRECT_TIME = 0x00300000 + 19, INFO_SSL_ENGINES = 0x00400000 + 27, INFO_COOKIELIST = 0x00400000 + 28 - Tclosepolicy* = enum + Closepolicy* = enum CLOSEPOLICY_NONE, CLOSEPOLICY_OLDEST, CLOSEPOLICY_LEAST_RECENTLY_USED, CLOSEPOLICY_LEAST_TRAFFIC, CLOSEPOLICY_SLOWEST, CLOSEPOLICY_CALLBACK, CLOSEPOLICY_LAST - Tlock_data* = enum + Lock_data* = enum LOCK_DATA_NONE = 0, LOCK_DATA_SHARE, LOCK_DATA_COOKIE, LOCK_DATA_DNS, LOCK_DATA_SSL_SESSION, LOCK_DATA_CONNECT, LOCK_DATA_LAST - Tlock_access* = enum + Lock_access* = enum LOCK_ACCESS_NONE = 0, LOCK_ACCESS_SHARED = 1, LOCK_ACCESS_SINGLE = 2, LOCK_ACCESS_LAST - Tlock_function* = proc (handle: PCurl, data: Tlock_data, - locktype: Tlock_access, + Lock_function* = proc (handle: PCurl, data: Lock_data, + locktype: Lock_access, userptr: pointer){.cdecl.} - Tunlock_function* = proc (handle: PCurl, data: Tlock_data, userptr: pointer){. + Unlock_function* = proc (handle: PCurl, data: Lock_data, userptr: pointer){. cdecl.} - TSH* = pointer - TSHcode* = enum + SH* = pointer + SHcode* = enum SHE_OK, SHE_BAD_OPTION, SHE_IN_USE, SHE_INVALID, SHE_NOMEM, SHE_LAST - TSHoption* = enum + SHoption* = enum SHOPT_NONE, SHOPT_SHARE, SHOPT_UNSHARE, SHOPT_LOCKFUNC, SHOPT_UNLOCKFUNC, SHOPT_USERDATA, SHOPT_LAST - Tversion* = enum + Version* = enum VERSION_FIRST, VERSION_SECOND, VERSION_THIRD, VERSION_LAST - Tversion_info_data*{.pure, final.} = object - age*: Tversion + Version_info_data*{.pure, final.} = object + age*: Version version*: cstring version_num*: int32 host*: cstring @@ -299,15 +299,15 @@ type libidn*: cstring iconv_ver_num*: int32 - TM* = pointer - Tsocket* = int32 - TMcode* = enum + M* = pointer + Socket* = int32 + Mcode* = enum M_CALL_MULTI_PERFORM = - 1, M_OK = 0, M_BAD_HANDLE, M_BAD_EASY_HANDLE, M_OUT_OF_MEMORY, M_INTERNAL_ERROR, M_BAD_SOCKET, M_UNKNOWN_OPTION, M_LAST - TMSGEnum* = enum + MSGEnum* = enum MSG_NONE, MSG_DONE, MSG_LAST - TMsg*{.pure, final.} = object - msg*: TMSGEnum + Msg*{.pure, final.} = object + msg*: MSGEnum easy_handle*: PCurl whatever*: pointer #data : record # case longint of @@ -315,11 +315,29 @@ type # 1 : ( result : CURLcode ); # end; - Tsocket_callback* = proc (easy: PCurl, s: Tsocket, what: int32, + Socket_callback* = proc (easy: PCurl, s: Socket, what: int32, userp, socketp: pointer): int32{.cdecl.} - TMoption* = enum + Moption* = enum MOPT_SOCKETDATA = 10000 + 2, MOPT_LASTENTRY = 10000 + 3, MOPT_SOCKETFUNCTION = 20000 + 1 +{.deprecated: [TMsg: Msg, TCurl: Curl, Thttppost: Httppost, + Tprogress_callback: Progress_callback, Twrite_callback: Write_callback, + Tread_callback: Read_callback, Tpasswd_callback: Passwd_callback, Tioerr: Ioerr, + Tiocmd: Iocmd, Tioctl_callback: Ioctl_callback, Tmalloc_callback: Malloc_callback, + Tfree_callback: Free_callback, Trealloc_callback: Realloc_callback, + Tstrdup_callback: Strdup_callback, Tcalloc_callback: Calloc_callback, + Tinfotype: Infotype, Tdebug_callback: Debug_callback, Tcode: Code, + Tconv_callback: Conv_callback, Tssl_ctx_callback: Ssl_ctx_callback, + Tproxytype: Proxytype, Tftpssl: Ftpssl, Tftpauth: Ftpauth, Tftpmethod: Ftpmethod, + Toption: Option, THTTP_VERSION: HTTP_VERSION, TNETRC_OPTION: NETRC_OPTION, + TSSL_VERSION: SSL_VERSION, TTIMECOND: TIMECOND, Tformoption: Formoption, + Tforms: Forms, TFORMcode: FORMcode, Tformget_callback: Formget_callback, + Tslist: Slist, TINFO: INFO, Tclosepolicy: Closepolicy, Tlock_data: Lock_data, + Tlock_access: Lock_access, Tlock_function: Lock_function, + Tunlock_function: Unlock_function, TSH: Sh, TSHcode: SHcode, TSHoption: SHoption, + Tversion: Version, Tversion_info_data: Version_info_data, TM: M, Tsocket: Socket, + TMcode: Mcode, TMSGEnum: MsGEnum, Tsocket_callback: Socket_callback, + TMoption: Moption].} const OPT_SSLKEYPASSWD* = OPT_SSLCERTPASSWD @@ -413,9 +431,9 @@ proc strequal*(s1, s2: cstring): int32{.cdecl, dynlib: libname, importc: "curl_strequal".} proc strnequal*(s1, s2: cstring, n: int): int32{.cdecl, dynlib: libname, importc: "curl_strnequal".} -proc formadd*(httppost, last_post: PPcurl_httppost): TFORMcode{.cdecl, varargs, +proc formadd*(httppost, last_post: PPcurl_httppost): FORMcode{.cdecl, varargs, dynlib: libname, importc: "curl_formadd".} -proc formget*(form: Phttppost, arg: pointer, append: Tformget_callback): int32{. +proc formget*(form: Phttppost, arg: pointer, append: Formget_callback): int32{. cdecl, dynlib: libname, importc: "curl_formget".} proc formfree*(form: Phttppost){.cdecl, dynlib: libname, importc: "curl_formfree".} @@ -431,11 +449,11 @@ proc easy_unescape*(handle: PCurl, str: cstring, len: int32, outlength: var int3 proc unescape*(str: cstring, len: int32): cstring{.cdecl, dynlib: libname, importc: "curl_unescape".} proc free*(p: pointer){.cdecl, dynlib: libname, importc: "curl_free".} -proc global_init*(flags: int32): Tcode{.cdecl, dynlib: libname, +proc global_init*(flags: int32): Code{.cdecl, dynlib: libname, importc: "curl_global_init".} -proc global_init_mem*(flags: int32, m: Tmalloc_callback, f: Tfree_callback, - r: Trealloc_callback, s: Tstrdup_callback, - c: Tcalloc_callback): Tcode{.cdecl, dynlib: libname, +proc global_init_mem*(flags: int32, m: Malloc_callback, f: Free_callback, + r: Realloc_callback, s: Strdup_callback, + c: Calloc_callback): Code{.cdecl, dynlib: libname, importc: "curl_global_init_mem".} proc global_cleanup*(){.cdecl, dynlib: libname, importc: "curl_global_cleanup".} proc slist_append*(slist: Pslist, p: cstring): Pslist{.cdecl, dynlib: libname, @@ -445,50 +463,50 @@ proc slist_free_all*(para1: Pslist){.cdecl, dynlib: libname, proc getdate*(p: cstring, unused: ptr Time): Time{.cdecl, dynlib: libname, importc: "curl_getdate".} proc share_init*(): PSH{.cdecl, dynlib: libname, importc: "curl_share_init".} -proc share_setopt*(para1: PSH, option: TSHoption): TSHcode{.cdecl, varargs, +proc share_setopt*(para1: PSH, option: SHoption): SHcode{.cdecl, varargs, dynlib: libname, importc: "curl_share_setopt".} -proc share_cleanup*(para1: PSH): TSHcode{.cdecl, dynlib: libname, +proc share_cleanup*(para1: PSH): SHcode{.cdecl, dynlib: libname, importc: "curl_share_cleanup".} -proc version_info*(para1: Tversion): Pversion_info_data{.cdecl, dynlib: libname, +proc version_info*(para1: Version): Pversion_info_data{.cdecl, dynlib: libname, importc: "curl_version_info".} -proc easy_strerror*(para1: Tcode): cstring{.cdecl, dynlib: libname, +proc easy_strerror*(para1: Code): cstring{.cdecl, dynlib: libname, importc: "curl_easy_strerror".} -proc share_strerror*(para1: TSHcode): cstring{.cdecl, dynlib: libname, +proc share_strerror*(para1: SHcode): cstring{.cdecl, dynlib: libname, importc: "curl_share_strerror".} proc easy_init*(): PCurl{.cdecl, dynlib: libname, importc: "curl_easy_init".} -proc easy_setopt*(curl: PCurl, option: Toption): Tcode{.cdecl, varargs, dynlib: libname, +proc easy_setopt*(curl: PCurl, option: Option): Code{.cdecl, varargs, dynlib: libname, importc: "curl_easy_setopt".} -proc easy_perform*(curl: PCurl): Tcode{.cdecl, dynlib: libname, +proc easy_perform*(curl: PCurl): Code{.cdecl, dynlib: libname, importc: "curl_easy_perform".} proc easy_cleanup*(curl: PCurl){.cdecl, dynlib: libname, importc: "curl_easy_cleanup".} -proc easy_getinfo*(curl: PCurl, info: TINFO): Tcode{.cdecl, varargs, dynlib: libname, +proc easy_getinfo*(curl: PCurl, info: INFO): Code{.cdecl, varargs, dynlib: libname, importc: "curl_easy_getinfo".} proc easy_duphandle*(curl: PCurl): PCurl{.cdecl, dynlib: libname, importc: "curl_easy_duphandle".} proc easy_reset*(curl: PCurl){.cdecl, dynlib: libname, importc: "curl_easy_reset".} proc multi_init*(): PM{.cdecl, dynlib: libname, importc: "curl_multi_init".} -proc multi_add_handle*(multi_handle: PM, handle: PCurl): TMcode{.cdecl, +proc multi_add_handle*(multi_handle: PM, handle: PCurl): Mcode{.cdecl, dynlib: libname, importc: "curl_multi_add_handle".} -proc multi_remove_handle*(multi_handle: PM, handle: PCurl): TMcode{.cdecl, +proc multi_remove_handle*(multi_handle: PM, handle: PCurl): Mcode{.cdecl, dynlib: libname, importc: "curl_multi_remove_handle".} proc multi_fdset*(multi_handle: PM, read_fd_set: Pfd_set, write_fd_set: Pfd_set, - exc_fd_set: Pfd_set, max_fd: var int32): TMcode{.cdecl, + exc_fd_set: Pfd_set, max_fd: var int32): Mcode{.cdecl, dynlib: libname, importc: "curl_multi_fdset".} -proc multi_perform*(multi_handle: PM, running_handles: var int32): TMcode{. +proc multi_perform*(multi_handle: PM, running_handles: var int32): Mcode{. cdecl, dynlib: libname, importc: "curl_multi_perform".} -proc multi_cleanup*(multi_handle: PM): TMcode{.cdecl, dynlib: libname, +proc multi_cleanup*(multi_handle: PM): Mcode{.cdecl, dynlib: libname, importc: "curl_multi_cleanup".} proc multi_info_read*(multi_handle: PM, msgs_in_queue: var int32): PMsg{.cdecl, dynlib: libname, importc: "curl_multi_info_read".} -proc multi_strerror*(para1: TMcode): cstring{.cdecl, dynlib: libname, +proc multi_strerror*(para1: Mcode): cstring{.cdecl, dynlib: libname, importc: "curl_multi_strerror".} -proc multi_socket*(multi_handle: PM, s: Tsocket, running_handles: var int32): TMcode{. +proc multi_socket*(multi_handle: PM, s: Socket, running_handles: var int32): Mcode{. cdecl, dynlib: libname, importc: "curl_multi_socket".} -proc multi_socket_all*(multi_handle: PM, running_handles: var int32): TMcode{. +proc multi_socket_all*(multi_handle: PM, running_handles: var int32): Mcode{. cdecl, dynlib: libname, importc: "curl_multi_socket_all".} -proc multi_timeout*(multi_handle: PM, milliseconds: var int32): TMcode{.cdecl, +proc multi_timeout*(multi_handle: PM, milliseconds: var int32): Mcode{.cdecl, dynlib: libname, importc: "curl_multi_timeout".} -proc multi_setopt*(multi_handle: PM, option: TMoption): TMcode{.cdecl, varargs, +proc multi_setopt*(multi_handle: PM, option: Moption): Mcode{.cdecl, varargs, dynlib: libname, importc: "curl_multi_setopt".} -proc multi_assign*(multi_handle: PM, sockfd: Tsocket, sockp: pointer): TMcode{. +proc multi_assign*(multi_handle: PM, sockfd: Socket, sockp: pointer): Mcode{. cdecl, dynlib: libname, importc: "curl_multi_assign".} diff --git a/lib/wrappers/libffi/libffi.nim b/lib/wrappers/libffi/libffi.nim index 1b6130103..d7e11a20c 100644 --- a/lib/wrappers/libffi/libffi.nim +++ b/lib/wrappers/libffi/libffi.nim @@ -58,8 +58,9 @@ else: {.pragma: mylib, dynlib: "libffi.so".} type - TArg* = int - TSArg* = int + Arg* = int + SArg* = int +{deprecated: [TArg: Arg, TSArg: SArg].} when defined(windows) and defined(x86): type @@ -105,67 +106,71 @@ const tkSMALL_STRUCT_4B* = (tkLAST + 3) type - TType* = object + Type* = object size*: int alignment*: uint16 typ*: uint16 - elements*: ptr ptr TType + elements*: ptr ptr Type +{.deprecated: [TType: Type].} var - type_void* {.importc: "ffi_type_void", mylib.}: TType - type_uint8* {.importc: "ffi_type_uint8", mylib.}: TType - type_sint8* {.importc: "ffi_type_sint8", mylib.}: TType - type_uint16* {.importc: "ffi_type_uint16", mylib.}: TType - type_sint16* {.importc: "ffi_type_sint16", mylib.}: TType - type_uint32* {.importc: "ffi_type_uint32", mylib.}: TType - type_sint32* {.importc: "ffi_type_sint32", mylib.}: TType - type_uint64* {.importc: "ffi_type_uint64", mylib.}: TType - type_sint64* {.importc: "ffi_type_sint64", mylib.}: TType - type_float* {.importc: "ffi_type_float", mylib.}: TType - type_double* {.importc: "ffi_type_double", mylib.}: TType - type_pointer* {.importc: "ffi_type_pointer", mylib.}: TType - type_longdouble* {.importc: "ffi_type_longdouble", mylib.}: TType + type_void* {.importc: "ffi_type_void", mylib.}: Type + type_uint8* {.importc: "ffi_type_uint8", mylib.}: Type + type_sint8* {.importc: "ffi_type_sint8", mylib.}: Type + type_uint16* {.importc: "ffi_type_uint16", mylib.}: Type + type_sint16* {.importc: "ffi_type_sint16", mylib.}: Type + type_uint32* {.importc: "ffi_type_uint32", mylib.}: Type + type_sint32* {.importc: "ffi_type_sint32", mylib.}: Type + type_uint64* {.importc: "ffi_type_uint64", mylib.}: Type + type_sint64* {.importc: "ffi_type_sint64", mylib.}: Type + type_float* {.importc: "ffi_type_float", mylib.}: Type + type_double* {.importc: "ffi_type_double", mylib.}: Type + type_pointer* {.importc: "ffi_type_pointer", mylib.}: Type + type_longdouble* {.importc: "ffi_type_longdouble", mylib.}: Type type - Tstatus* {.size: sizeof(cint).} = enum + Status* {.size: sizeof(cint).} = enum OK, BAD_TYPEDEF, BAD_ABI - TTypeKind* = cuint + TypeKind* = cuint TCif* {.pure, final.} = object abi*: TABI nargs*: cuint - arg_types*: ptr ptr TType - rtype*: ptr TType + arg_types*: ptr ptr Type + rtype*: ptr Type bytes*: cuint flags*: cuint +{.deprecated: [Tstatus: Status].} type - TRaw* = object - sint*: TSArg + Raw* = object + sint*: SArg +{.deprecated: [TRaw: Raw].} proc raw_call*(cif: var Tcif; fn: proc () {.cdecl.}; rvalue: pointer; - avalue: ptr TRaw) {.cdecl, importc: "ffi_raw_call", mylib.} -proc ptrarray_to_raw*(cif: var Tcif; args: ptr pointer; raw: ptr TRaw) {.cdecl, + avalue: ptr Raw) {.cdecl, importc: "ffi_raw_call", mylib.} +proc ptrarray_to_raw*(cif: var Tcif; args: ptr pointer; raw: ptr Raw) {.cdecl, importc: "ffi_ptrarray_to_raw", mylib.} -proc raw_to_ptrarray*(cif: var Tcif; raw: ptr TRaw; args: ptr pointer) {.cdecl, +proc raw_to_ptrarray*(cif: var Tcif; raw: ptr Raw; args: ptr pointer) {.cdecl, importc: "ffi_raw_to_ptrarray", mylib.} proc raw_size*(cif: var Tcif): int {.cdecl, importc: "ffi_raw_size", mylib.} -proc prep_cif*(cif: var Tcif; abi: TABI; nargs: cuint; rtype: ptr TType; - atypes: ptr ptr TType): TStatus {.cdecl, importc: "ffi_prep_cif", +proc prep_cif*(cif: var Tcif; abi: TABI; nargs: cuint; rtype: ptr Type; + atypes: ptr ptr Type): Status {.cdecl, importc: "ffi_prep_cif", mylib.} proc call*(cif: var Tcif; fn: proc () {.cdecl.}; rvalue: pointer; avalue: ptr pointer) {.cdecl, importc: "ffi_call", mylib.} # the same with an easier interface: type - TParamList* = array[0..100, ptr TType] - TArgList* = array[0..100, pointer] + ParamList* = array[0..100, ptr Type] + ArgList* = array[0..100, pointer] +{.deprecated: [TParamList: ParamList, TArgList: ArgList].} -proc prep_cif*(cif: var Tcif; abi: TABI; nargs: cuint; rtype: ptr TType; - atypes: TParamList): TStatus {.cdecl, importc: "ffi_prep_cif", +proc prep_cif*(cif: var Tcif; abi: TABI; nargs: cuint; rtype: ptr Type; + atypes: ParamList): Status {.cdecl, importc: "ffi_prep_cif", mylib.} proc call*(cif: var Tcif; fn, rvalue: pointer; - avalue: TArgList) {.cdecl, importc: "ffi_call", mylib.} + avalue: ArgList) {.cdecl, importc: "ffi_call", mylib.} # Useful for eliminating compiler warnings ##define FFI_FN(f) ((void (*)(void))f) diff --git a/lib/wrappers/libsvm.nim b/lib/wrappers/libsvm.nim index 00d5ac73c..8cc314412 100644 --- a/lib/wrappers/libsvm.nim +++ b/lib/wrappers/libsvm.nim @@ -21,24 +21,24 @@ else: const svmdll* = "libsvm.so" type - Tnode*{.pure, final.} = object + Node*{.pure, final.} = object index*: cint value*: cdouble - Tproblem*{.pure, final.} = object + Problem*{.pure, final.} = object L*: cint y*: ptr cdouble - x*: ptr ptr Tnode + x*: ptr ptr Node - Ttype*{.size: sizeof(cint).} = enum + Type*{.size: sizeof(cint).} = enum C_SVC, NU_SVC, ONE_CLASS, EPSILON_SVR, NU_SVR - TKernelType*{.size: sizeof(cint).} = enum + KernelType*{.size: sizeof(cint).} = enum LINEAR, POLY, RBF, SIGMOID, PRECOMPUTED - Tparameter*{.pure, final.} = object - typ*: TType - kernelType*: TKernelType + Parameter*{.pure, final.} = object + typ*: Type + kernelType*: KernelType degree*: cint # for poly gamma*: cdouble # for poly/rbf/sigmoid coef0*: cdouble # for poly/sigmoid @@ -53,18 +53,19 @@ type p*: cdouble # for EPSILON_SVR shrinking*: cint # use the shrinking heuristics probability*: cint # do probability estimates - +{.deprecated: [Tnode: Node, Tproblem: Problem, Ttype: Type, + TKernelType: KernelType, Tparameter: Parameter].} # # svm_model # type - TModel*{.pure, final.} = object - param*: Tparameter # parameter + Model*{.pure, final.} = object + param*: Parameter # parameter nr_class*: cint # number of classes, = 2 in regression/one class svm L*: cint # total #SV - SV*: ptr ptr Tnode # SVs (SV[l]) + SV*: ptr ptr Node # SVs (SV[l]) sv_coef*: ptr ptr cdouble # coefficients for SVs in decision functions (sv_coef[k-1][l]) rho*: ptr cdouble # constants in decision functions (rho[k*(k-1)/2]) probA*: ptr cdouble # pariwise probability information @@ -74,42 +75,42 @@ type # nSV[0] + nSV[1] + ... + nSV[k-1] = l # XXX free_sv*: cint # 1 if svm_model is created by svm_load_model - # 0 if svm_model is created by svm_train - + # 0 if svm_model is created by svm_train +{.deprecated: [TModel: Model].} -proc train*(prob: ptr Tproblem, param: ptr Tparameter): ptr Tmodel{.cdecl, +proc train*(prob: ptr Problem, param: ptr Parameter): ptr Model{.cdecl, importc: "svm_train", dynlib: svmdll.} -proc cross_validation*(prob: ptr Tproblem, param: ptr Tparameter, nr_fold: cint, +proc cross_validation*(prob: ptr Problem, param: ptr Parameter, nr_fold: cint, target: ptr cdouble){.cdecl, importc: "svm_cross_validation", dynlib: svmdll.} -proc save_model*(model_file_name: cstring, model: ptr Tmodel): cint{.cdecl, +proc save_model*(model_file_name: cstring, model: ptr Model): cint{.cdecl, importc: "svm_save_model", dynlib: svmdll.} -proc load_model*(model_file_name: cstring): ptr Tmodel{.cdecl, +proc load_model*(model_file_name: cstring): ptr Model{.cdecl, importc: "svm_load_model", dynlib: svmdll.} -proc get_svm_type*(model: ptr Tmodel): cint{.cdecl, importc: "svm_get_svm_type", +proc get_svm_type*(model: ptr Model): cint{.cdecl, importc: "svm_get_svm_type", dynlib: svmdll.} -proc get_nr_class*(model: ptr Tmodel): cint{.cdecl, importc: "svm_get_nr_class", +proc get_nr_class*(model: ptr Model): cint{.cdecl, importc: "svm_get_nr_class", dynlib: svmdll.} -proc get_labels*(model: ptr Tmodel, label: ptr cint){.cdecl, +proc get_labels*(model: ptr Model, label: ptr cint){.cdecl, importc: "svm_get_labels", dynlib: svmdll.} -proc get_svr_probability*(model: ptr Tmodel): cdouble{.cdecl, +proc get_svr_probability*(model: ptr Model): cdouble{.cdecl, importc: "svm_get_svr_probability", dynlib: svmdll.} -proc predict_values*(model: ptr Tmodel, x: ptr Tnode, dec_values: ptr cdouble): cdouble{. +proc predict_values*(model: ptr Model, x: ptr Node, dec_values: ptr cdouble): cdouble{. cdecl, importc: "svm_predict_values", dynlib: svmdll.} -proc predict*(model: ptr Tmodel, x: ptr Tnode): cdouble{.cdecl, +proc predict*(model: ptr Model, x: ptr Node): cdouble{.cdecl, importc: "svm_predict", dynlib: svmdll.} -proc predict_probability*(model: ptr Tmodel, x: ptr Tnode, +proc predict_probability*(model: ptr Model, x: ptr Node, prob_estimates: ptr cdouble): cdouble{.cdecl, importc: "svm_predict_probability", dynlib: svmdll.} -proc free_model_content*(model_ptr: ptr Tmodel){.cdecl, +proc free_model_content*(model_ptr: ptr Model){.cdecl, importc: "svm_free_model_content", dynlib: svmdll.} -proc free_and_destroy_model*(model_ptr_ptr: ptr ptr Tmodel){.cdecl, +proc free_and_destroy_model*(model_ptr_ptr: ptr ptr Model){.cdecl, importc: "svm_free_and_destroy_model", dynlib: svmdll.} -proc destroy_param*(param: ptr Tparameter){.cdecl, importc: "svm_destroy_param", +proc destroy_param*(param: ptr Parameter){.cdecl, importc: "svm_destroy_param", dynlib: svmdll.} -proc check_parameter*(prob: ptr Tproblem, param: ptr Tparameter): cstring{. +proc check_parameter*(prob: ptr Problem, param: ptr Parameter): cstring{. cdecl, importc: "svm_check_parameter", dynlib: svmdll.} -proc check_probability_model*(model: ptr Tmodel): cint{.cdecl, +proc check_probability_model*(model: ptr Model): cint{.cdecl, importc: "svm_check_probability_model", dynlib: svmdll.} proc set_print_string_function*(print_func: proc (arg: cstring) {.cdecl.}){. diff --git a/lib/wrappers/libuv.nim b/lib/wrappers/libuv.nim index a52ae0f63..0cb14fb2b 100644 --- a/lib/wrappers/libuv.nim +++ b/lib/wrappers/libuv.nim @@ -10,15 +10,15 @@ else: import posix type - TPort* = distinct int16 ## port type + Port* = distinct int16 ## port type cssize = int coff = int csize = int - AllocProc* = proc (handle: PHandle, suggested_size: csize): TBuf {.cdecl.} - ReadProc* = proc (stream: PStream, nread: cssize, buf: TBuf) {.cdecl.} - ReadProc2* = proc (stream: PPipe, nread: cssize, buf: TBuf, pending: THandleType) {.cdecl.} + AllocProc* = proc (handle: PHandle, suggested_size: csize): Buf {.cdecl.} + ReadProc* = proc (stream: PStream, nread: cssize, buf: Buf) {.cdecl.} + ReadProc2* = proc (stream: PPipe, nread: cssize, buf: Buf, pending: HandleType) {.cdecl.} WriteProc* = proc (req: PWrite, status: cint) {.cdecl.} ConnectProc* = proc (req: PConnect, status: cint) {.cdecl.} ShutdownProc* = proc (req: PShutdown, status: cint) {.cdecl.} @@ -41,7 +41,7 @@ type FsEventProc* = proc (handle: PFsEvent, filename: cstring, events: cint, status: cint) - TErrorCode* {.size: sizeof(cint).} = enum + ErrorCode* {.size: sizeof(cint).} = enum UNKNOWN = - 1, OK = 0, EOF, EACCESS, EAGAIN, EADDRINUSE, EADDRNOTAVAIL, EAFNOSUPPORT, EALREADY, EBADF, EBUSY, ECONNABORTED, ECONNREFUSED, ECONNRESET, EDESTADDRREQ, EFAULT, EHOSTUNREACH, EINTR, EINVAL, EISCONN, @@ -50,11 +50,11 @@ type EPROTONOSUPPORT, EPROTOTYPE, ETIMEDOUT, ECHARSET, EAIFAMNOSUPPORT, EAINONAME, EAISERVICE, EAISOCKTYPE, ESHUTDOWN, EEXIST - THandleType* {.size: sizeof(cint).} = enum + HandleType* {.size: sizeof(cint).} = enum UNKNOWN_HANDLE = 0, TCP, UDP, NAMED_PIPE, TTY, FILE, TIMER, PREPARE, CHECK, IDLE, ASYNC, ARES_TASK, ARES_EVENT, PROCESS, FS_EVENT - TReqType* {.size: sizeof(cint).} = enum + ReqType* {.size: sizeof(cint).} = enum rUNKNOWN_REQ = 0, rCONNECT, rACCEPT, @@ -68,57 +68,57 @@ type rGETADDRINFO, rREQ_TYPE_PRIVATE - TErr* {.pure, final, importc: "uv_err_t", header: "uv.h".} = object - code* {.importc: "code".}: TErrorCode + Err* {.pure, final, importc: "uv_err_t", header: "uv.h".} = object + code* {.importc: "code".}: ErrorCode sys_errno* {.importc: "sys_errno_".}: cint - TFsEventType* = enum + FsEventType* = enum evRENAME = 1, evCHANGE = 2 TFsEvent* {.pure, final, importc: "uv_fs_event_t", header: "uv.h".} = object loop* {.importc: "loop".}: PLoop - typ* {.importc: "type".}: THandleType + typ* {.importc: "type".}: HandleType close_cb* {.importc: "close_cb".}: CloseProc data* {.importc: "data".}: pointer filename {.importc: "filename".}: cstring PFsEvent* = ptr TFsEvent - TFsEvents* {.pure, final, importc: "uv_fs_event_t", header: "uv.h".} = object + FsEvents* {.pure, final, importc: "uv_fs_event_t", header: "uv.h".} = object loop* {.importc: "loop".}: PLoop - typ* {.importc: "type".}: THandleType + typ* {.importc: "type".}: HandleType close_cb* {.importc: "close_cb".}: CloseProc data* {.importc: "data".}: pointer filename* {.importc: "filename".}: cstring - TBuf* {.pure, final, importc: "uv_buf_t", header: "uv.h"} = object + Buf* {.pure, final, importc: "uv_buf_t", header: "uv.h"} = object base* {.importc: "base".}: cstring len* {.importc: "len".}: csize - TAnyHandle* {.pure, final, importc: "uv_any_handle", header: "uv.h".} = object + AnyHandle* {.pure, final, importc: "uv_any_handle", header: "uv.h".} = object tcp* {.importc: "tcp".}: TTcp - pipe* {.importc: "pipe".}: TPipe + pipe* {.importc: "pipe".}: Pipe prepare* {.importc: "prepare".}: TPrepare check* {.importc: "check".}: TCheck idle* {.importc: "idle".}: TIdle async* {.importc: "async".}: TAsync timer* {.importc: "timer".}: TTimer - getaddrinfo* {.importc: "getaddrinfo".}: TGetaddrinfo - fs_event* {.importc: "fs_event".}: TFsEvents + getaddrinfo* {.importc: "getaddrinfo".}: Getaddrinfo + fs_event* {.importc: "fs_event".}: FsEvents - TAnyReq* {.pure, final, importc: "uv_any_req", header: "uv.h".} = object - req* {.importc: "req".}: TReq - write* {.importc: "write".}: TWrite - connect* {.importc: "connect".}: TConnect - shutdown* {.importc: "shutdown".}: TShutdown - fs_req* {.importc: "fs_req".}: Tfs - work_req* {.importc: "work_req".}: TWork + AnyReq* {.pure, final, importc: "uv_any_req", header: "uv.h".} = object + req* {.importc: "req".}: Req + write* {.importc: "write".}: Write + connect* {.importc: "connect".}: Connect + shutdown* {.importc: "shutdown".}: Shutdown + fs_req* {.importc: "fs_req".}: Fs + work_req* {.importc: "work_req".}: Work ## better import this uint64 = int64 - TCounters* {.pure, final, importc: "uv_counters_t", header: "uv.h".} = object + Counters* {.pure, final, importc: "uv_counters_t", header: "uv.h".} = object eio_init* {.importc: "eio_init".}: uint64 req_init* {.importc: "req_init".}: uint64 handle_init* {.importc: "handle_init".}: uint64 @@ -135,36 +135,36 @@ type process_init* {.importc: "process_init".}: uint64 fs_event_init* {.importc: "fs_event_init".}: uint64 - TLoop* {.pure, final, importc: "uv_loop_t", header: "uv.h".} = object + Loop* {.pure, final, importc: "uv_loop_t", header: "uv.h".} = object # ares_handles_* {.importc: "uv_ares_handles_".}: pointer # XXX: This seems to be a private field? eio_want_poll_notifier* {.importc: "uv_eio_want_poll_notifier".}: TAsync eio_done_poll_notifier* {.importc: "uv_eio_done_poll_notifier".}: TAsync eio_poller* {.importc: "uv_eio_poller".}: TIdle - counters* {.importc: "counters".}: TCounters - last_err* {.importc: "last_err".}: TErr + counters* {.importc: "counters".}: Counters + last_err* {.importc: "last_err".}: Err data* {.importc: "data".}: pointer - PLoop* = ptr TLoop + PLoop* = ptr Loop - TShutdown* {.pure, final, importc: "uv_shutdown_t", header: "uv.h".} = object - typ* {.importc: "type".}: TReqType + Shutdown* {.pure, final, importc: "uv_shutdown_t", header: "uv.h".} = object + typ* {.importc: "type".}: ReqType data* {.importc: "data".}: pointer handle* {.importc: "handle".}: PStream cb* {.importc: "cb".}: ShutdownProc - PShutdown* = ptr TShutdown + PShutdown* = ptr Shutdown - THandle* {.pure, final, importc: "uv_handle_t", header: "uv.h".} = object + Handle* {.pure, final, importc: "uv_handle_t", header: "uv.h".} = object loop* {.importc: "loop".}: PLoop - typ* {.importc: "type".}: THandleType + typ* {.importc: "type".}: HandleType close_cb* {.importc: "close_cb".}: CloseProc data* {.importc: "data".}: pointer - PHandle* = ptr THandle + PHandle* = ptr Handle - TStream* {.pure, final, importc: "uv_stream_t", header: "uv.h".} = object + Stream* {.pure, final, importc: "uv_stream_t", header: "uv.h".} = object loop* {.importc: "loop".}: PLoop - typ* {.importc: "type".}: THandleType + typ* {.importc: "type".}: HandleType alloc_cb* {.importc: "alloc_cb".}: AllocProc read_cb* {.importc: "read_cb".}: ReadProc read2_cb* {.importc: "read2_cb".}: ReadProc2 @@ -172,20 +172,20 @@ type data* {.importc: "data".}: pointer write_queue_size* {.importc: "write_queue_size".}: csize - PStream* = ptr TStream + PStream* = ptr Stream - TWrite* {.pure, final, importc: "uv_write_t", header: "uv.h".} = object - typ* {.importc: "type".}: TReqType + Write* {.pure, final, importc: "uv_write_t", header: "uv.h".} = object + typ* {.importc: "type".}: ReqType data* {.importc: "data".}: pointer cb* {.importc: "cb".}: WriteProc send_handle* {.importc: "send_handle".}: PStream handle* {.importc: "handle".}: PStream - PWrite* = ptr TWrite + PWrite* = ptr Write TTcp* {.pure, final, importc: "uv_tcp_t", header: "uv.h".} = object loop* {.importc: "loop".}: PLoop - typ* {.importc: "type".}: THandleType + typ* {.importc: "type".}: HandleType alloc_cb* {.importc: "alloc_cb".}: AllocProc read_cb* {.importc: "read_cb".}: ReadProc read2_cb* {.importc: "read2_cb".}: ReadProc2 @@ -195,42 +195,42 @@ type PTcp* = ptr TTcp - TConnect* {.pure, final, importc: "uv_connect_t", header: "uv.h".} = object - typ* {.importc: "type".}: TReqType + Connect* {.pure, final, importc: "uv_connect_t", header: "uv.h".} = object + typ* {.importc: "type".}: ReqType data* {.importc: "data".}: pointer cb* {.importc: "cb".}: ConnectProc handle* {.importc: "handle".}: PStream - PConnect* = ptr TConnect + PConnect* = ptr Connect - TUdpFlags* = enum + UdpFlags* = enum UDP_IPV6ONLY = 1, UDP_PARTIAL = 2 ## XXX: better import this cunsigned = int UdpSendProc* = proc (req: PUdpSend, status: cint) - UdpRecvProc* = proc (handle: PUdp, nread: cssize, buf: TBuf, adr: ptr SockAddr, flags: cunsigned) + UdpRecvProc* = proc (handle: PUdp, nread: cssize, buf: Buf, adr: ptr SockAddr, flags: cunsigned) TUdp* {.pure, final, importc: "uv_udp_t", header: "uv.h".} = object loop* {.importc: "loop".}: PLoop - typ* {.importc: "type".}: THandleType + typ* {.importc: "type".}: HandleType close_cb* {.importc: "close_cb".}: CloseProc data* {.importc: "data".}: pointer PUdp* = ptr TUdp - TUdpSend* {.pure, final, importc: "uv_udp_send_t", header: "uv.h".} = object - typ* {.importc: "type".}: TReqType + UdpSend* {.pure, final, importc: "uv_udp_send_t", header: "uv.h".} = object + typ* {.importc: "type".}: ReqType data* {.importc: "data".}: pointer handle* {.importc: "handle".}: PUdp cb* {.importc: "cb".}: UdpSendProc - PUdpSend* = ptr TUdpSend + PUdpSend* = ptr UdpSend tTTy* {.pure, final, importc: "uv_tty_t", header: "uv.h".} = object loop* {.importc: "loop".}: PLoop - typ* {.importc: "type".}: THandleType + typ* {.importc: "type".}: HandleType alloc_cb* {.importc: "alloc_cb".}: AllocProc read_cb* {.importc: "read_cb".}: ReadProc read2_cb* {.importc: "read2_cb".}: ReadProc2 @@ -240,9 +240,9 @@ type pTTy* = ptr tTTy - TPipe* {.pure, final, importc: "uv_pipe_t", header: "uv.h".} = object + Pipe* {.pure, final, importc: "uv_pipe_t", header: "uv.h".} = object loop* {.importc: "loop".}: PLoop - typ* {.importc: "type".}: THandleType + typ* {.importc: "type".}: HandleType alloc_cb* {.importc: "alloc_cb".}: AllocProc read_cb* {.importc: "read_cb".}: ReadProc read2_cb* {.importc: "read2_cb".}: ReadProc2 @@ -251,11 +251,11 @@ type write_queue_size* {.importc: "write_queue_size".}: csize ipc {.importc: "ipc".}: int - PPipe* = ptr TPipe + PPipe* = ptr Pipe TPrepare* {.pure, final, importc: "uv_prepare_t", header: "uv.h".} = object loop* {.importc: "loop".}: PLoop - typ* {.importc: "type".}: THandleType + typ* {.importc: "type".}: HandleType close_cb* {.importc: "close_cb".}: CloseProc data* {.importc: "data".}: pointer @@ -263,7 +263,7 @@ type TCheck* {.pure, final, importc: "uv_check_t", header: "uv.h".} = object loop* {.importc: "loop".}: PLoop - typ* {.importc: "type".}: THandleType + typ* {.importc: "type".}: HandleType close_cb* {.importc: "close_cb".}: CloseProc data* {.importc: "data".}: pointer @@ -271,7 +271,7 @@ type TIdle* {.pure, final, importc: "uv_idle_t", header: "uv.h".} = object loop* {.importc: "loop".}: PLoop - typ* {.importc: "type".}: THandleType + typ* {.importc: "type".}: HandleType close_cb* {.importc: "close_cb".}: CloseProc data* {.importc: "data".}: pointer @@ -279,7 +279,7 @@ type TAsync* {.pure, final, importc: "uv_async_t", header: "uv.h".} = object loop* {.importc: "loop".}: PLoop - typ* {.importc: "type".}: THandleType + typ* {.importc: "type".}: HandleType close_cb* {.importc: "close_cb".}: CloseProc data* {.importc: "data".}: pointer @@ -287,20 +287,20 @@ type TTimer* {.pure, final, importc: "uv_timer_t", header: "uv.h".} = object loop* {.importc: "loop".}: PLoop - typ* {.importc: "type".}: THandleType + typ* {.importc: "type".}: HandleType close_cb* {.importc: "close_cb".}: CloseProc data* {.importc: "data".}: pointer PTimer* = ptr TTimer - TGetAddrInfo* {.pure, final, importc: "uv_getaddrinfo_t", header: "uv.h".} = object - typ* {.importc: "type".}: TReqType + GetAddrInfo* {.pure, final, importc: "uv_getaddrinfo_t", header: "uv.h".} = object + typ* {.importc: "type".}: ReqType data* {.importc: "data".}: pointer loop* {.importc: "loop".}: PLoop - PGetAddrInfo* = ptr TGetAddrInfo + PGetAddrInfo* = ptr GetAddrInfo - TProcessOptions* {.pure, final, importc: "uv_process_options_t", header: "uv.h".} = object + ProcessOptions* {.pure, final, importc: "uv_process_options_t", header: "uv.h".} = object exit_cb* {.importc: "exit_cb".}: ExitProc file* {.importc: "file".}: cstring args* {.importc: "args".}: cstringArray @@ -311,11 +311,11 @@ type stdout_stream* {.importc: "stdout_stream".}: PPipe stderr_stream* {.importc: "stderr_stream".}: PPipe - PProcessOptions* = ptr TProcessOptions + PProcessOptions* = ptr ProcessOptions TProcess* {.pure, final, importc: "uv_process_t", header: "uv.h".} = object loop* {.importc: "loop".}: PLoop - typ* {.importc: "type".}: THandleType + typ* {.importc: "type".}: HandleType close_cb* {.importc: "close_cb".}: CloseProc data* {.importc: "data".}: pointer exit_cb* {.importc: "exit_cb".}: ExitProc @@ -323,47 +323,47 @@ type PProcess* = ptr TProcess - TWork* {.pure, final, importc: "uv_work_t", header: "uv.h".} = object - typ* {.importc: "type".}: TReqType + Work* {.pure, final, importc: "uv_work_t", header: "uv.h".} = object + typ* {.importc: "type".}: ReqType data* {.importc: "data".}: pointer loop* {.importc: "loop".}: PLoop work_cb* {.importc: "work_cb".}: WorkProc after_work_cb* {.importc: "after_work_cb".}: AfterWorkProc - PWork* = ptr TWork + PWork* = ptr Work - TFsType* {.size: sizeof(cint).} = enum + FsType* {.size: sizeof(cint).} = enum FS_UNKNOWN = - 1, FS_CUSTOM, FS_OPEN, FS_CLOSE, FS_READ, FS_WRITE, FS_SENDFILE, FS_STAT, FS_LSTAT, FS_FSTAT, FS_FTRUNCATE, FS_UTIME, FS_FUTIME, FS_CHMOD, FS_FCHMOD, FS_FSYNC, FS_FDATASYNC, FS_UNLINK, FS_RMDIR, FS_MKDIR, FS_RENAME, FS_READDIR, FS_LINK, FS_SYMLINK, FS_READLINK, FS_CHOWN, FS_FCHOWN - TFS* {.pure, final, importc: "uv_fs_t", header: "uv.h".} = object - typ* {.importc: "type".}: TReqType + FS* {.pure, final, importc: "uv_fs_t", header: "uv.h".} = object + typ* {.importc: "type".}: ReqType data* {.importc: "data".}: pointer loop* {.importc: "loop".}: PLoop - fs_type* {.importc: "fs_type".}: TFsType + fs_type* {.importc: "fs_type".}: FsType cb* {.importc: "cb".}: FsProc result* {.importc: "result".}: cssize fsPtr* {.importc: "ptr".}: pointer path* {.importc: "path".}: cstring errorno* {.importc: "errorno".}: cint - PFS* = ptr TFS + PFS* = ptr FS - TReq* {.pure, final, importc: "uv_req_t", header: "uv.h".} = object - typ* {.importc: "type".}: TReqType + Req* {.pure, final, importc: "uv_req_t", header: "uv.h".} = object + typ* {.importc: "type".}: ReqType data* {.importc: "data".}: pointer - PReq* = ptr TReq + PReq* = ptr Req - TAresOptions* {.pure, final, importc: "ares_options", header: "uv.h".} = object + AresOptions* {.pure, final, importc: "ares_options", header: "uv.h".} = object flags* {.importc: "flags".}: int timeout* {.importc: "timeout".}: int tries* {.importc: "tries".}: int ndots* {.importc: "ndots".}: int - udp_port* {.importc: "udp_port".}: TPort - tcp_port* {.importc: "tcp_port".}: TPort + udp_port* {.importc: "udp_port".}: Port + tcp_port* {.importc: "tcp_port".}: Port socket_send_buffer_size* {.importc: "socket_send_buffer_size".}: int socket_recv_buffer_size* {.importc: "socket_receive_buffer_size".}: int servers* {.importc: "servers".}: ptr InAddr @@ -378,8 +378,30 @@ type #struct apattern *sortlist; #int nsort; - PAresOptions* = ptr TAresOptions + PAresOptions* = ptr AresOptions PAresChannel* = pointer +{.deprecated: [THandle: Handle, THandleType: HandleType, TAnyHandle: AnyHandle, + TAnyReq: AnyReq, TPort: Port, TErrorCode: ErrorCode, TReqType: ReqType, + TErr: Err, TFsEventType: FsEventType, + # TFsEvent: FsEvent, # Name conflict if we drop `T` + TFsEvents: FsEvents, TBuf: Buf, TCounters: Counters, TLoop: Loop, + TShutdown: Shutdown, TStream: Stream, TWrite: Write, + # TTcp: Tcp, # Name conflict if we drop `T` + TConnect: Connect, + TUdpFlags: UdpFlags, + # TUdp: Udp, # Name conflict if we drop `T` + TUdpSend: UdpSend, + # tTTy: TTy, # Name conflict if we drop `T` + TPipe: Pipe, + # TPrepare: Prepare, # Name conflict if we drop `T` + # TCheck: Check, # Name conflict if we drop `T` + # TIdle: Idle, # Name conflict if we drop `T` + # TAsync: Async, # Name conflict if we drop `T` + # TTimer: Timer, # Name conflict if we drop `T` + TGetAddrInfo: GetAddrInfo, TProcessOptions: ProcessOptions, + # TProcess: Process, # Name conflict if we drop `T` + TWork: Work, + TFsType: FsType, TFS: FS, TReq: Req, TAresOptions: AresOptions].} proc loop_new*(): PLoop{. importc: "uv_loop_new", header: "uv.h".} @@ -405,13 +427,13 @@ proc update_time*(a2: PLoop){. proc now*(a2: PLoop): int64{. importc: "uv_now", header: "uv.h".} -proc last_error*(a2: PLoop): TErr{. +proc last_error*(a2: PLoop): Err{. importc: "uv_last_error", header: "uv.h".} -proc strerror*(err: TErr): cstring{. +proc strerror*(err: Err): cstring{. importc: "uv_strerror", header: "uv.h".} -proc err_name*(err: TErr): cstring{. +proc err_name*(err: Err): cstring{. importc: "uv_err_name", header: "uv.h".} proc shutdown*(req: PShutdown, handle: PStream, cb: ShutdownProc): cint{. @@ -423,7 +445,7 @@ proc is_active*(handle: PHandle): cint{. proc close*(handle: PHandle, close_cb: CloseProc){. importc: "uv_close", header: "uv.h".} -proc buf_init*(base: cstring, len: csize): TBuf{. +proc buf_init*(base: cstring, len: csize): Buf{. importc: "uv_buf_init", header: "uv.h".} proc listen*(stream: PStream, backlog: cint, cb: ConnectionProc): cint{. @@ -441,10 +463,10 @@ proc read_start*(a2: PStream, alloc_cb: AllocProc, read_cb: ReadProc2): cint{. proc read_stop*(a2: PStream): cint{. importc: "uv_read_stop", header: "uv.h".} -proc write*(req: PWrite, handle: PStream, bufs: ptr TBuf, bufcnt: cint, cb: WriteProc): cint{. +proc write*(req: PWrite, handle: PStream, bufs: ptr Buf, bufcnt: cint, cb: WriteProc): cint{. importc: "uv_write", header: "uv.h".} -proc write*(req: PWrite, handle: PStream, bufs: ptr TBuf, bufcnt: cint, send_handle: PStream, cb: WriteProc): cint{. +proc write*(req: PWrite, handle: PStream, bufs: ptr Buf, bufcnt: cint, send_handle: PStream, cb: WriteProc): cint{. importc: "uv_write2", header: "uv.h".} proc tcp_init*(a2: PLoop, handle: PTcp): cint{. @@ -480,10 +502,10 @@ proc udp_bind6*(handle: PUdp, adr: TSockAddrIn6, flags: cunsigned): cint{. proc udp_getsockname*(handle: PUdp, name: ptr SockAddr, namelen: var cint): cint{. importc: "uv_udp_getsockname", header: "uv.h".} -proc udp_send*(req: PUdpSend, handle: PUdp, bufs: ptr TBuf, bufcnt: cint, adr: SockAddrIn, send_cb: UdpSendProc): cint{. +proc udp_send*(req: PUdpSend, handle: PUdp, bufs: ptr Buf, bufcnt: cint, adr: SockAddrIn, send_cb: UdpSendProc): cint{. importc: "uv_udp_send", header: "uv.h".} -proc udp_send6*(req: PUdpSend, handle: PUdp, bufs: ptr TBuf, bufcnt: cint, adr: TSockAddrIn6, send_cb: UdpSendProc): cint{. +proc udp_send6*(req: PUdpSend, handle: PUdp, bufs: ptr Buf, bufcnt: cint, adr: TSockAddrIn6, send_cb: UdpSendProc): cint{. importc: "uv_udp_send6", header: "uv.h".} proc udp_recv_start*(handle: PUdp, alloc_cb: AllocProc, recv_cb: UdpRecvProc): cint{. @@ -504,7 +526,7 @@ proc tty_get_winsize*(a2: pTTy, width: var cint, height: var cint): cint{. proc tty_reset_mode*() {. importc: "uv_tty_reset_mode", header: "uv.h".} -proc guess_handle*(file: File): THandleType{. +proc guess_handle*(file: File): HandleType{. importc: "uv_guess_handle", header: "uv.h".} proc pipe_init*(a2: PLoop, handle: PPipe, ipc: int): cint{. @@ -582,7 +604,7 @@ proc getaddrinfo*(a2: PLoop, handle: PGetAddrInfo,getaddrinfo_cb: GetAddrInfoPro proc freeaddrinfo*(ai: ptr AddrInfo){. importc: "uv_freeaddrinfo", header: "uv.h".} -proc spawn*(a2: PLoop, a3: PProcess, options: TProcessOptions): cint{. +proc spawn*(a2: PLoop, a3: PProcess, options: ProcessOptions): cint{. importc: "uv_spawn", header: "uv.h".} proc process_kill*(a2: PProcess, signum: cint): cint{. diff --git a/lib/wrappers/mysql.nim b/lib/wrappers/mysql.nim index 937a8952a..73b82b5c6 100644 --- a/lib/wrappers/mysql.nim +++ b/lib/wrappers/mysql.nim @@ -51,7 +51,7 @@ const SERVICENAME* = "MySQL" type - Tenum_server_command* = enum + Enum_server_command* = enum COM_SLEEP, COM_QUIT, COM_INIT_DB, COM_QUERY, COM_FIELD_LIST, COM_CREATE_DB, COM_DROP_DB, COM_REFRESH, COM_SHUTDOWN, COM_STATISTICS, COM_PROCESS_INFO, COM_CONNECT, COM_PROCESS_KILL, COM_DEBUG, COM_PING, COM_TIME, @@ -59,6 +59,7 @@ type COM_CONNECT_OUT, COM_REGISTER_SLAVE, COM_STMT_PREPARE, COM_STMT_EXECUTE, COM_STMT_SEND_LONG_DATA, COM_STMT_CLOSE, COM_STMT_RESET, COM_SET_OPTION, COM_STMT_FETCH, COM_END +{.deprecated: [Tenum_server_command: Enum_server_command].} const SCRAMBLE_LENGTH* = 20 # Length of random string sent by server on handshake; @@ -150,8 +151,8 @@ const MAX_BLOB_WIDTH* = 8192 # Default width for blob type - Pst_net* = ptr Tst_net - Tst_net*{.final.} = object + Pst_net* = ptr St_net + St_net*{.final.} = object vio*: PVio buff*: cstring buff_end*: cstring @@ -191,14 +192,15 @@ type report_error*: my_bool # We should report error (we have unreported error) return_errno*: my_bool - TNET* = Tst_net - PNET* = ptr TNET + NET* = St_net + PNET* = ptr NET +{.deprecated: [Tst_net: St_net, TNET: NET].} const packet_error* = - 1 type - Tenum_field_types* = enum # For backward compatibility + Enum_field_types* = enum # For backward compatibility TYPE_DECIMAL, TYPE_TINY, TYPE_SHORT, TYPE_LONG, TYPE_FLOAT, TYPE_DOUBLE, TYPE_NULL, TYPE_TIMESTAMP, TYPE_LONGLONG, TYPE_INT24, TYPE_DATE, TYPE_TIME, TYPE_DATETIME, TYPE_YEAR, TYPE_NEWDATE, TYPE_VARCHAR, TYPE_BIT, @@ -206,6 +208,7 @@ type TYPE_TINY_BLOB = 249, TYPE_MEDIUM_BLOB = 250, TYPE_LONG_BLOB = 251, TYPE_BLOB = 252, TYPE_VAR_STRING = 253, TYPE_STRING = 254, TYPE_GEOMETRY = 255 +{.deprecated: [Tenum_field_types: Enum_field_types].} const CLIENT_MULTI_QUERIES* = CLIENT_MULTI_STATEMENTS @@ -244,16 +247,19 @@ const SHUTDOWN_KILLABLE_UPDATE* = chr(1 shl 3) type - Tenum_shutdown_level* = enum + Enum_shutdown_level* = enum SHUTDOWN_DEFAULT = 0, SHUTDOWN_WAIT_CONNECTIONS = 1, SHUTDOWN_WAIT_TRANSACTIONS = 2, SHUTDOWN_WAIT_UPDATES = 8, SHUTDOWN_WAIT_ALL_BUFFERS = 16, SHUTDOWN_WAIT_CRITICAL_BUFFERS = 17, KILL_QUERY = 254, KILL_CONNECTION = 255 - Tenum_cursor_type* = enum # options for mysql_set_option + Enum_cursor_type* = enum # options for mysql_set_option CURSOR_TYPE_NO_CURSOR = 0, CURSOR_TYPE_READ_ONLY = 1, CURSOR_TYPE_FOR_UPDATE = 2, CURSOR_TYPE_SCROLLABLE = 4 - Tenum_mysql_set_option* = enum + Enum_mysql_set_option* = enum OPTION_MULTI_STATEMENTS_ON, OPTION_MULTI_STATEMENTS_OFF +{.deprecated: [Tenum_shutdown_level: Enum_shutdown_level, + Tenum_cursor_type: Enum_cursor_type, + Tenum_mysql_set_option: Enum_mysql_set_option].} proc my_net_init*(net: PNET, vio: PVio): my_bool{.cdecl, dynlib: lib, importc: "my_net_init".} @@ -275,24 +281,25 @@ proc my_net_read*(net: PNET): int{.cdecl, dynlib: lib, importc: "my_net_read".} # The following function is not meant for normal usage # Currently it's used internally by manager.c type - Psockaddr* = ptr Tsockaddr - Tsockaddr*{.final.} = object # undefined structure + Psockaddr* = ptr Sockaddr + Sockaddr*{.final.} = object # undefined structure +{.deprecated: [Tsockaddr: Sockaddr].} proc my_connect*(s: my_socket, name: Psockaddr, namelen: cuint, timeout: cuint): cint{. cdecl, dynlib: lib, importc: "my_connect".} type - Prand_struct* = ptr Trand_struct - Trand_struct*{.final.} = object # The following is for user defined functions + Prand_struct* = ptr Rand_struct + Rand_struct*{.final.} = object # The following is for user defined functions seed1*: int seed2*: int max_value*: int max_value_dbl*: cdouble - TItem_result* = enum + Item_result* = enum STRING_RESULT, REAL_RESULT, INT_RESULT, ROW_RESULT, DECIMAL_RESULT - PItem_result* = ptr TItem_result - Pst_udf_args* = ptr Tst_udf_args - Tst_udf_args*{.final.} = object + PItem_result* = ptr Item_result + Pst_udf_args* = ptr St_udf_args + St_udf_args*{.final.} = object arg_count*: cuint # Number of arguments arg_type*: PItem_result # Pointer to item_results args*: cstringArray # Pointer to item_results @@ -301,18 +308,21 @@ type attributes*: cstringArray # Pointer to attribute name attribute_lengths*: ptr int # Length of attribute arguments - TUDF_ARGS* = Tst_udf_args - PUDF_ARGS* = ptr TUDF_ARGS # This holds information about the result - Pst_udf_init* = ptr Tst_udf_init - Tst_udf_init*{.final.} = object + UDF_ARGS* = St_udf_args + PUDF_ARGS* = ptr UDF_ARGS # This holds information about the result + Pst_udf_init* = ptr St_udf_init + St_udf_init*{.final.} = object maybe_null*: my_bool # 1 if function can return NULL decimals*: cuint # for real functions max_length*: int # For string functions theptr*: cstring # free pointer for function data const_item*: my_bool # free pointer for function data - TUDF_INIT* = Tst_udf_init - PUDF_INIT* = ptr TUDF_INIT # Constants when using compression + UDF_INIT* = St_udf_init + PUDF_INIT* = ptr UDF_INIT # Constants when using compression +{.deprecated: [Trand_stuct: Rand_struct, TItem_result: Item_result, + Tst_udf_args: St_udf_args, TUDF_ARGS: UDF_ARGS, + Tst_udf_init: St_udf_init, TUDF_INIT: UDF_INIT].} const NET_HEADER_SIZE* = 4 # standard header size @@ -386,8 +396,8 @@ const CLIENT_NET_WRITE_TIMEOUT* = 365 * 24 * 3600 # Timeout on write type - Pst_mysql_field* = ptr Tst_mysql_field - Tst_mysql_field*{.final.} = object + Pst_mysql_field* = ptr St_mysql_field + St_mysql_field*{.final.} = object name*: cstring # Name of column org_name*: cstring # Original column name, if an alias table*: cstring # Table of column if column was a field @@ -407,19 +417,21 @@ type flags*: cuint # Div flags decimals*: cuint # Number of decimals in field charsetnr*: cuint # Character set - ftype*: Tenum_field_types # Type of field. See mysql_com.h for types + ftype*: Enum_field_types # Type of field. See mysql_com.h for types - TFIELD* = Tst_mysql_field - PFIELD* = ptr TFIELD - PROW* = ptr TROW # return data as array of strings - TROW* = cstringArray - PFIELD_OFFSET* = ptr TFIELD_OFFSET # offset to current field - TFIELD_OFFSET* = cuint + FIELD* = St_mysql_field + PFIELD* = ptr FIELD + PROW* = ptr ROW # return data as array of strings + ROW* = cstringArray + PFIELD_OFFSET* = ptr FIELD_OFFSET # offset to current field + FIELD_OFFSET* = cuint +{.deprecated: [Tst_mysql_field: St_mysql_field, TFIELD: FIELD, TROW: ROW, + TFIELD_OFFSET: FIELD_OFFSET].} proc IS_PRI_KEY*(n: int32): bool proc IS_NOT_NULL*(n: int32): bool proc IS_BLOB*(n: int32): bool -proc IS_NUM*(t: Tenum_field_types): bool +proc IS_NUM*(t: Enum_field_types): bool proc INTERNAL_NUM_FIELD*(f: Pst_mysql_field): bool proc IS_NUM_FIELD*(f: Pst_mysql_field): bool type @@ -430,32 +442,34 @@ const COUNT_ERROR* = not (my_ulonglong(0)) type - Pst_mysql_rows* = ptr Tst_mysql_rows - Tst_mysql_rows*{.final.} = object + Pst_mysql_rows* = ptr St_mysql_rows + St_mysql_rows*{.final.} = object next*: Pst_mysql_rows # list of rows - data*: TROW + data*: ROW len*: int - TROWS* = Tst_mysql_rows - PROWS* = ptr TROWS - PROW_OFFSET* = ptr TROW_OFFSET # offset to current row - TROW_OFFSET* = TROWS + ROWS* = St_mysql_rows + PROWS* = ptr ROWS + PROW_OFFSET* = ptr ROW_OFFSET # offset to current row + ROW_OFFSET* = ROWS +{.deprecated: [Tst_mysql_rows: St_mysql_rows, TROWS: ROWS, + TROW_OFFSET: ROW_OFFSET].} const ALLOC_MAX_BLOCK_TO_DROP* = 4096 ALLOC_MAX_BLOCK_USAGE_BEFORE_DROP* = 10 # struct for once_alloc (block) type - Pst_used_mem* = ptr Tst_used_mem - Tst_used_mem*{.final.} = object + Pst_used_mem* = ptr St_used_mem + St_used_mem*{.final.} = object next*: Pst_used_mem # Next block in use left*: cuint # memory left in block size*: cuint # size of block - TUSED_MEM* = Tst_used_mem - PUSED_MEM* = ptr TUSED_MEM - Pst_mem_root* = ptr Tst_mem_root - Tst_mem_root*{.final.} = object + USED_MEM* = St_used_mem + PUSED_MEM* = ptr USED_MEM + Pst_mem_root* = ptr St_mem_root + St_mem_root*{.final.} = object free*: PUSED_MEM # blocks with free memory in it used*: PUSED_MEM # blocks almost without free memory pre_alloc*: PUSED_MEM # preallocated block @@ -467,27 +481,30 @@ type first_block_usage*: cuint error_handler*: proc (){.cdecl.} - TMEM_ROOT* = Tst_mem_root - PMEM_ROOT* = ptr TMEM_ROOT # ------------ Stop of declaration in "my_alloc.h" ---------------------- + MEM_ROOT* = St_mem_root + PMEM_ROOT* = ptr MEM_ROOT # ------------ Stop of declaration in "my_alloc.h" ---------------------- +{.deprecated: [Tst_used_mem: St_used_mem, TUSED_MEM: USED_MEM, + Tst_mem_root: St_mem_root, TMEM_ROOT: MEM_ROOT].} type - Pst_mysql_data* = ptr Tst_mysql_data - Tst_mysql_data*{.final.} = object + Pst_mysql_data* = ptr St_mysql_data + St_mysql_data*{.final.} = object rows*: my_ulonglong fields*: cuint data*: PROWS - alloc*: TMEM_ROOT + alloc*: MEM_ROOT prev_ptr*: ptr PROWS - TDATA* = Tst_mysql_data - PDATA* = ptr TDATA - Toption* = enum + DATA* = St_mysql_data + PDATA* = ptr DATA + Option* = enum OPT_CONNECT_TIMEOUT, OPT_COMPRESS, OPT_NAMED_PIPE, INIT_COMMAND, READ_DEFAULT_FILE, READ_DEFAULT_GROUP, SET_CHARSET_DIR, SET_CHARSET_NAME, OPT_LOCAL_INFILE, OPT_PROTOCOL, SHARED_MEMORY_BASE_NAME, OPT_READ_TIMEOUT, OPT_WRITE_TIMEOUT, OPT_USE_RESULT, OPT_USE_REMOTE_CONNECTION, OPT_USE_EMBEDDED_CONNECTION, OPT_GUESS_CONNECTION, SET_CLIENT_IP, SECURE_AUTH, REPORT_DATA_TRUNCATION, OPT_RECONNECT +{.deprecated: [Tst_mysql_data: St_mysql_data, TDATA: DATA, Toption: Option].} const MAX_MYSQL_MANAGER_ERR* = 256 @@ -499,17 +516,17 @@ const MANAGER_INTERNAL_ERR* = 500 type - Tst_dynamic_array*{.final.} = object + St_dynamic_array*{.final.} = object buffer*: cstring elements*: cuint max_element*: cuint alloc_increment*: cuint size_of_element*: cuint - TDYNAMIC_ARRAY* = Tst_dynamic_array - Pst_dynamic_array* = ptr Tst_dynamic_array - Pst_mysql_options* = ptr Tst_mysql_options - Tst_mysql_options*{.final.} = object + DYNAMIC_ARRAY* = St_dynamic_array + Pst_dynamic_array* = ptr St_dynamic_array + Pst_mysql_options* = ptr St_mysql_options + St_mysql_options*{.final.} = object connect_timeout*: cuint read_timeout*: cuint write_timeout*: cuint @@ -543,7 +560,7 @@ type # a read that is replication-aware no_master_reads*: my_bool separate_thread*: my_bool - methods_to_use*: Toption + methods_to_use*: Option client_ip*: cstring secure_auth*: my_bool # Refuse client connecting to server if it uses old (pre-4.1.1) protocol report_data_truncation*: my_bool # 0 - never report, 1 - always report (default) @@ -555,16 +572,16 @@ type local_infile_error*: proc (para1: pointer, para2: cstring, para3: cuint): cint local_infile_userdata*: pointer - Tstatus* = enum + Status* = enum STATUS_READY, STATUS_GET_RESULT, STATUS_USE_RESULT - Tprotocol_type* = enum # There are three types of queries - the ones that have to go to + Protocol_type* = enum # There are three types of queries - the ones that have to go to # the master, the ones that go to a slave, and the administrative # type which must happen on the pivot connectioin PROTOCOL_DEFAULT, PROTOCOL_TCP, PROTOCOL_SOCKET, PROTOCOL_PIPE, PROTOCOL_MEMORY - Trpl_type* = enum + Rpl_type* = enum RPL_MASTER, RPL_SLAVE, RPL_ADMIN - Tcharset_info_st*{.final.} = object + Charset_info_st*{.final.} = object number*: cuint primary_number*: cuint binary_number*: cuint @@ -592,10 +609,10 @@ type cset*: pointer # was ^MY_CHARSET_HANDLER coll*: pointer # was ^MY_COLLATION_HANDLER; - TCHARSET_INFO* = Tcharset_info_st - Pcharset_info_st* = ptr Tcharset_info_st - Pcharacter_set* = ptr Tcharacter_set - Tcharacter_set*{.final.} = object + CHARSET_INFO* = Charset_info_st + Pcharset_info_st* = ptr Charset_info_st + Pcharacter_set* = ptr Character_set + Character_set*{.final.} = object number*: cuint state*: cuint csname*: cstring @@ -605,12 +622,12 @@ type mbminlen*: cuint mbmaxlen*: cuint - TMY_CHARSET_INFO* = Tcharacter_set - PMY_CHARSET_INFO* = ptr TMY_CHARSET_INFO - Pst_mysql_methods* = ptr Tst_mysql_methods - Pst_mysql* = ptr Tst_mysql - Tst_mysql*{.final.} = object - net*: TNET # Communication parameters + MY_CHARSET_INFO* = Character_set + PMY_CHARSET_INFO* = ptr MY_CHARSET_INFO + Pst_mysql_methods* = ptr St_mysql_methods + Pst_mysql* = ptr St_mysql + St_mysql*{.final.} = object + net*: NET # Communication parameters connector_fd*: gptr # ConnectorFd for SSL host*: cstring user*: cstring @@ -622,7 +639,7 @@ type db*: cstring charset*: Pcharset_info_st fields*: PFIELD - field_alloc*: TMEM_ROOT + field_alloc*: MEM_ROOT affected_rows*: my_ulonglong insert_id*: my_ulonglong # id if insert on table with NEXTNR extra_info*: my_ulonglong # Used by mysqlshow, not used by mysql 5.0 and up @@ -636,8 +653,8 @@ type server_status*: cuint server_language*: cuint warning_count*: cuint - options*: Tst_mysql_options - status*: Tstatus + options*: St_mysql_options + status*: Status free_me*: my_bool # If free in mysql_close reconnect*: my_bool # set to 1 if automatic reconnect scramble*: array[0..(SCRAMBLE_LENGTH + 1) - 1, char] # session-wide random string @@ -655,37 +672,37 @@ type # from mysql_stmt_close if close had to cancel result set of this object. unbuffered_fetch_owner*: Pmy_bool - TMySQL* = Tst_mysql - PMySQL* = ptr TMySQL - Pst_mysql_res* = ptr Tst_mysql_res - Tst_mysql_res*{.final.} = object + MySQL* = St_mysql + PMySQL* = ptr MySQL + Pst_mysql_res* = ptr St_mysql_res + St_mysql_res*{.final.} = object row_count*: my_ulonglong fields*: PFIELD data*: PDATA data_cursor*: PROWS lengths*: ptr int # column lengths of current row handle*: PMySQL # for unbuffered reads - field_alloc*: TMEM_ROOT + field_alloc*: MEM_ROOT field_count*: cuint current_field*: cuint - row*: TROW # If unbuffered read - current_row*: TROW # buffer to current row + row*: ROW # If unbuffered read + current_row*: ROW # buffer to current row eof*: my_bool # Used by mysql_fetch_row unbuffered_fetch_cancelled*: my_bool # mysql_stmt_close() had to cancel this result methods*: Pst_mysql_methods - TRES* = Tst_mysql_res - PRES* = ptr TRES - Pst_mysql_stmt* = ptr Tst_mysql_stmt - PSTMT* = ptr TSTMT - Tst_mysql_methods*{.final.} = object + RES* = St_mysql_res + PRES* = ptr RES + Pst_mysql_stmt* = ptr St_mysql_stmt + PSTMT* = ptr STMT + St_mysql_methods*{.final.} = object read_query_result*: proc (MySQL: PMySQL): my_bool{.cdecl.} - advanced_command*: proc (MySQL: PMySQL, command: Tenum_server_command, header: cstring, + advanced_command*: proc (MySQL: PMySQL, command: Enum_server_command, header: cstring, header_length: int, arg: cstring, arg_length: int, skip_check: my_bool): my_bool read_rows*: proc (MySQL: PMySQL, fields: PFIELD, fields_count: cuint): PDATA use_result*: proc (MySQL: PMySQL): PRES - fetch_lengths*: proc (fto: ptr int, column: TROW, field_count: cuint) + fetch_lengths*: proc (fto: ptr int, column: ROW, field_count: cuint) flush_use_result*: proc (MySQL: PMySQL) list_fields*: proc (MySQL: PMySQL): PFIELD read_prepare_result*: proc (MySQL: PMySQL, stmt: PSTMT): my_bool @@ -698,11 +715,11 @@ type read_change_user_result*: proc (MySQL: PMySQL, buff: cstring, passwd: cstring): cint read_rowsfrom_cursor*: proc (stmt: PSTMT): cint - TMETHODS* = Tst_mysql_methods - PMETHODS* = ptr TMETHODS - Pst_mysql_manager* = ptr Tst_mysql_manager - Tst_mysql_manager*{.final.} = object - net*: TNET + METHODS* = St_mysql_methods + PMETHODS* = ptr METHODS + Pst_mysql_manager* = ptr St_mysql_manager + St_mysql_manager*{.final.} = object + net*: NET host*: cstring user*: cstring passwd*: cstring @@ -717,24 +734,24 @@ type net_buf_size*: cint last_error*: array[0..(MAX_MYSQL_MANAGER_ERR) - 1, char] - TMANAGER* = Tst_mysql_manager - PMANAGER* = ptr TMANAGER - Pst_mysql_parameters* = ptr Tst_mysql_parameters - Tst_mysql_parameters*{.final.} = object + MANAGER* = St_mysql_manager + PMANAGER* = ptr MANAGER + Pst_mysql_parameters* = ptr St_mysql_parameters + St_mysql_parameters*{.final.} = object p_max_allowed_packet*: ptr int p_net_buffer_length*: ptr int - TPARAMETERS* = Tst_mysql_parameters - PPARAMETERS* = ptr TPARAMETERS - Tenum_mysql_stmt_state* = enum + PARAMETERS* = St_mysql_parameters + PPARAMETERS* = ptr PARAMETERS + Enum_mysql_stmt_state* = enum STMT_INIT_DONE = 1, STMT_PREPARE_DONE, STMT_EXECUTE_DONE, STMT_FETCH_DONE - Pst_mysql_bind* = ptr Tst_mysql_bind - Tst_mysql_bind*{.final.} = object + Pst_mysql_bind* = ptr St_mysql_bind + St_mysql_bind*{.final.} = object len*: int # output length pointer is_null*: Pmy_bool # Pointer to null indicator buffer*: pointer # buffer to get/put data error*: PMy_bool # set this if you want to track data truncations happened during fetch - buffer_type*: Tenum_field_types # buffer type + buffer_type*: Enum_field_types # buffer type buffer_length*: int # buffer length, must be set for str/binary # Following are for internal use. Set by mysql_stmt_bind_param row_ptr*: ptr byte # for the current data position @@ -750,15 +767,15 @@ type fetch_result*: proc (para1: Pst_mysql_bind, para2: PFIELD, row: PPbyte) skip_result*: proc (para1: Pst_mysql_bind, para2: PFIELD, row: PPbyte) - TBIND* = Tst_mysql_bind - PBIND* = ptr TBIND # statement handler - Tst_mysql_stmt*{.final.} = object - mem_root*: TMEM_ROOT # root allocations + BIND* = St_mysql_bind + PBIND* = ptr BIND # statement handler + St_mysql_stmt*{.final.} = object + mem_root*: MEM_ROOT # root allocations mysql*: PMySQL # connection handle params*: PBIND # input parameters `bind`*: PBIND # input parameters fields*: PFIELD # result set metadata - result*: TDATA # cached result set + result*: DATA # cached result set data_cursor*: PROWS # current row in cached result affected_rows*: my_ulonglong # copy of mysql->affected_rows after statement execution insert_id*: my_ulonglong @@ -771,7 +788,7 @@ type last_errno*: cuint # error code param_count*: cuint # input parameter count field_count*: cuint # number of columns in result set - state*: Tenum_mysql_stmt_state # statement state + state*: Enum_mysql_stmt_state # statement state last_error*: array[0..(ERRMSG_SIZE) - 1, char] # error message sqlstate*: array[0..(SQLSTATE_LENGTH + 1) - 1, char] send_types_to_server*: my_bool # Types of input parameters should be sent to server @@ -780,10 +797,23 @@ type unbuffered_fetch_cancelled*: my_bool update_max_length*: my_bool - TSTMT* = Tst_mysql_stmt + STMT* = St_mysql_stmt - Tenum_stmt_attr_type* = enum + Enum_stmt_attr_type* = enum STMT_ATTR_UPDATE_MAX_LENGTH, STMT_ATTR_CURSOR_TYPE, STMT_ATTR_PREFETCH_ROWS +{.deprecated: [Tst_dynamic_array: St_dynamic_array, Tst_mysql_options: St_mysql_options, + TDYNAMIC_ARRAY: DYNAMIC_ARRAY, Tprotocol_type: Protocol_type, + Trpl_type: Rpl_type, Tcharset_info_st: Charset_info_st, + TCHARSET_INFO: CHARSET_INFO, Tcharacter_set: Character_set, + TMY_CHARSET_INFO: MY_CHARSET_INFO, Tst_mysql: St_mysql, + Tst_mysql_methods: St_mysql_methods, TMySql: MySql, + Tst_mysql_res: St_mysql_res, TMETHODS: METHODS, TRES: RES, + Tst_mysql_manager: St_mysql_manager, TMANAGER: MANAGER, + Tst_mysql_parameters: St_mysql_parameters, TPARAMETERS: PARAMETERS, + Tenum_mysql_stmt_state: Enum_mysql_stmt_state, + Tst_mysql_bind: St_mysql_bind, TBIND: BIND, Tst_mysql_stmt: St_mysql_stmt, + TSTMT: STMT, Tenum_stmt_attr_type: Enum_stmt_attr_type, + Tstatus: Status].} proc server_init*(argc: cint, argv: cstringArray, groups: cstringArray): cint{. cdecl, dynlib: lib, importc: "mysql_server_init".} @@ -817,9 +847,9 @@ proc fetch_field_direct*(res: PRES, fieldnr: cuint): PFIELD{.stdcall, dynlib: lib, importc: "mysql_fetch_field_direct".} proc fetch_fields*(res: PRES): PFIELD{.stdcall, dynlib: lib, importc: "mysql_fetch_fields".} -proc row_tell*(res: PRES): TROW_OFFSET{.stdcall, dynlib: lib, +proc row_tell*(res: PRES): ROW_OFFSET{.stdcall, dynlib: lib, importc: "mysql_row_tell".} -proc field_tell*(res: PRES): TFIELD_OFFSET{.stdcall, dynlib: lib, +proc field_tell*(res: PRES): FIELD_OFFSET{.stdcall, dynlib: lib, importc: "mysql_field_tell".} proc field_count*(MySQL: PMySQL): cuint{.stdcall, dynlib: lib, importc: "mysql_field_count".} @@ -895,7 +925,7 @@ proc disable_reads_from_master*(MySQL: PMySQL){.stdcall, dynlib: lib, importc: " # get the value of the master read flag proc reads_from_master_enabled*(MySQL: PMySQL): my_bool{.stdcall, dynlib: lib, importc: "mysql_reads_from_master_enabled".} -proc rpl_query_type*(q: cstring, length: cint): Trpl_type{.stdcall, dynlib: lib, +proc rpl_query_type*(q: cstring, length: cint): Rpl_type{.stdcall, dynlib: lib, importc: "mysql_rpl_query_type".} # discover the master and its slaves proc rpl_probe*(MySQL: PMySQL): my_bool{.stdcall, dynlib: lib, importc: "mysql_rpl_probe".} @@ -904,14 +934,14 @@ proc set_master*(MySQL: PMySQL, host: cstring, port: cuint, user: cstring, passw stdcall, dynlib: lib, importc: "mysql_set_master".} proc add_slave*(MySQL: PMySQL, host: cstring, port: cuint, user: cstring, passwd: cstring): cint{. stdcall, dynlib: lib, importc: "mysql_add_slave".} -proc shutdown*(MySQL: PMySQL, shutdown_level: Tenum_shutdown_level): cint{.stdcall, +proc shutdown*(MySQL: PMySQL, shutdown_level: Enum_shutdown_level): cint{.stdcall, dynlib: lib, importc: "mysql_shutdown".} proc dump_debug_info*(MySQL: PMySQL): cint{.stdcall, dynlib: lib, importc: "mysql_dump_debug_info".} proc refresh*(sql: PMySQL, refresh_options: cuint): cint{.stdcall, dynlib: lib, importc: "mysql_refresh".} proc kill*(MySQL: PMySQL, pid: int): cint{.stdcall, dynlib: lib, importc: "mysql_kill".} -proc set_server_option*(MySQL: PMySQL, option: Tenum_mysql_set_option): cint{.stdcall, +proc set_server_option*(MySQL: PMySQL, option: Enum_mysql_set_option): cint{.stdcall, dynlib: lib, importc: "mysql_set_server_option".} proc ping*(MySQL: PMySQL): cint{.stdcall, dynlib: lib, importc: "mysql_ping".} proc stat*(MySQL: PMySQL): cstring{.stdcall, dynlib: lib, importc: "mysql_stat".} @@ -933,17 +963,17 @@ proc list_tables*(MySQL: PMySQL, wild: cstring): PRES{.stdcall, dynlib: lib, importc: "mysql_list_tables".} proc list_processes*(MySQL: PMySQL): PRES{.stdcall, dynlib: lib, importc: "mysql_list_processes".} -proc options*(MySQL: PMySQL, option: Toption, arg: cstring): cint{.stdcall, dynlib: lib, +proc options*(MySQL: PMySQL, option: Option, arg: cstring): cint{.stdcall, dynlib: lib, importc: "mysql_options".} proc free_result*(result: PRES){.stdcall, dynlib: lib, importc: "mysql_free_result".} proc data_seek*(result: PRES, offset: my_ulonglong){.stdcall, dynlib: lib, importc: "mysql_data_seek".} -proc row_seek*(result: PRES, offset: TROW_OFFSET): TROW_OFFSET{.stdcall, +proc row_seek*(result: PRES, offset: ROW_OFFSET): ROW_OFFSET{.stdcall, dynlib: lib, importc: "mysql_row_seek".} -proc field_seek*(result: PRES, offset: TFIELD_OFFSET): TFIELD_OFFSET{.stdcall, +proc field_seek*(result: PRES, offset: FIELD_OFFSET): FIELD_OFFSET{.stdcall, dynlib: lib, importc: "mysql_field_seek".} -proc fetch_row*(result: PRES): TROW{.stdcall, dynlib: lib, +proc fetch_row*(result: PRES): ROW{.stdcall, dynlib: lib, importc: "mysql_fetch_row".} proc fetch_lengths*(result: PRES): ptr int{.stdcall, dynlib: lib, importc: "mysql_fetch_lengths".} @@ -990,9 +1020,9 @@ proc stmt_store_result*(stmt: PSTMT): cint{.stdcall, dynlib: lib, importc: "mysql_stmt_store_result".} proc stmt_param_count*(stmt: PSTMT): int{.stdcall, dynlib: lib, importc: "mysql_stmt_param_count".} -proc stmt_attr_set*(stmt: PSTMT, attr_type: Tenum_stmt_attr_type, attr: pointer): my_bool{. +proc stmt_attr_set*(stmt: PSTMT, attr_type: Enum_stmt_attr_type, attr: pointer): my_bool{. stdcall, dynlib: lib, importc: "mysql_stmt_attr_set".} -proc stmt_attr_get*(stmt: PSTMT, attr_type: Tenum_stmt_attr_type, attr: pointer): my_bool{. +proc stmt_attr_get*(stmt: PSTMT, attr_type: Enum_stmt_attr_type, attr: pointer): my_bool{. stdcall, dynlib: lib, importc: "mysql_stmt_attr_get".} proc stmt_bind_param*(stmt: PSTMT, bnd: PBIND): my_bool{.stdcall, dynlib: lib, importc: "mysql_stmt_bind_param".} @@ -1017,9 +1047,9 @@ proc stmt_error*(stmt: PSTMT): cstring{.stdcall, dynlib: lib, importc: "mysql_stmt_error".} proc stmt_sqlstate*(stmt: PSTMT): cstring{.stdcall, dynlib: lib, importc: "mysql_stmt_sqlstate".} -proc stmt_row_seek*(stmt: PSTMT, offset: TROW_OFFSET): TROW_OFFSET{.stdcall, +proc stmt_row_seek*(stmt: PSTMT, offset: ROW_OFFSET): ROW_OFFSET{.stdcall, dynlib: lib, importc: "mysql_stmt_row_seek".} -proc stmt_row_tell*(stmt: PSTMT): TROW_OFFSET{.stdcall, dynlib: lib, +proc stmt_row_tell*(stmt: PSTMT): ROW_OFFSET{.stdcall, dynlib: lib, importc: "mysql_stmt_row_tell".} proc stmt_data_seek*(stmt: PSTMT, offset: my_ulonglong){.stdcall, dynlib: lib, importc: "mysql_stmt_data_seek".} @@ -1066,7 +1096,7 @@ proc IS_BLOB(n: int32): bool = proc IS_NUM_FIELD(f: Pst_mysql_field): bool = result = (f.flags and NUM_FLAG) != 0 -proc IS_NUM(t: Tenum_field_types): bool = +proc IS_NUM(t: Enum_field_types): bool = result = (t <= FIELD_TYPE_INT24) or (t == FIELD_TYPE_YEAR) or (t == FIELD_TYPE_NEWDECIMAL) diff --git a/lib/wrappers/odbcsql.nim b/lib/wrappers/odbcsql.nim index 77719e85f..22297497c 100644 --- a/lib/wrappers/odbcsql.nim +++ b/lib/wrappers/odbcsql.nim @@ -30,28 +30,39 @@ else: type TSqlChar* = char TSqlSmallInt* = int16 - TSqlUSmallInt* = int16 - TSqlHandle* = pointer - TSqlHEnv* = TSqlHandle - TSqlHDBC* = TSqlHandle - TSqlHStmt* = TSqlHandle - TSqlHDesc* = TSqlHandle + SqlUSmallInt* = int16 + SqlHandle* = pointer + SqlHEnv* = SqlHandle + SqlHDBC* = SqlHandle + SqlHStmt* = SqlHandle + SqlHDesc* = SqlHandle TSqlInteger* = int - TSqlUInteger* = int - TSqlPointer* = pointer + SqlUInteger* = int + SqlPointer* = pointer TSqlReal* = cfloat TSqlDouble* = cdouble TSqlFloat* = cdouble - TSqlHWND* = pointer + SqlHWND* = pointer PSQLCHAR* = cstring PSQLINTEGER* = ptr TSqlInteger - PSQLUINTEGER* = ptr TSqlUInteger + PSQLUINTEGER* = ptr SqlUInteger PSQLSMALLINT* = ptr TSqlSmallInt - PSQLUSMALLINT* = ptr TSqlUSmallInt + PSQLUSMALLINT* = ptr SqlUSmallInt PSQLREAL* = ptr TSqlReal PSQLDOUBLE* = ptr TSqlDouble PSQLFLOAT* = ptr TSqlFloat - PSQLHANDLE* = ptr TSqlHandle + PSQLHANDLE* = ptr SqlHandle +{.deprecated: [ + # TSqlChar: TSqlChar, # Name conflict if we drop`T` + # TSqlSmallInt: TSqlSmallInt, # Name conflict if we drop`T` + TSqlUSmallInt: SqlUSmallInt, TSqlHandle: SqlHandle, TSqlHEnv: SqlHEnv, + TSqlHDBC: SqlHDBC, TSqlHStmt: SqlHStmt, TSqlHDesc: SqlHDesc, + # TSqlInteger: TSqlInteger, # Name conflict if we drop `T` + TSqlUInteger: SqlUInteger, TSqlPointer: SqlPointer, + # TSqlReal: TSqlReal, # Name conflict if we drop`T` + # TSqlDouble: TSqlDouble, # Name conflict if we drop`T` + # TSqlFloat: TSqlFloat, # Name conflict if we drop `T` + TSqlHWND: SqlHWND].} const # SQL data type codes SQL_UNKNOWN_TYPE* = 0 @@ -199,24 +210,24 @@ const type SQL_DATE_STRUCT* {.final, pure.} = object Year*: TSqlSmallInt - Month*: TSqlUSmallInt - Day*: TSqlUSmallInt + Month*: SqlUSmallInt + Day*: SqlUSmallInt PSQL_DATE_STRUCT* = ptr SQL_DATE_STRUCT SQL_TIME_STRUCT* {.final, pure.} = object - Hour*: TSqlUSmallInt - Minute*: TSqlUSmallInt - Second*: TSqlUSmallInt + Hour*: SqlUSmallInt + Minute*: SqlUSmallInt + Second*: SqlUSmallInt PSQL_TIME_STRUCT* = ptr SQL_TIME_STRUCT SQL_TIMESTAMP_STRUCT* {.final, pure.} = object - Year*: TSqlUSmallInt - Month*: TSqlUSmallInt - Day*: TSqlUSmallInt - Hour*: TSqlUSmallInt - Minute*: TSqlUSmallInt - Second*: TSqlUSmallInt - Fraction*: TSqlUInteger + Year*: SqlUSmallInt + Month*: SqlUSmallInt + Day*: SqlUSmallInt + Hour*: SqlUSmallInt + Minute*: SqlUSmallInt + Second*: SqlUSmallInt + Fraction*: SqlUInteger PSQL_TIMESTAMP_STRUCT* = ptr SQL_TIMESTAMP_STRUCT @@ -509,11 +520,11 @@ const SQL_FETCH_PRIOR* = 4 SQL_FETCH_ABSOLUTE* = 5 SQL_FETCH_RELATIVE* = 6 - SQL_NULL_HENV* = TSqlHEnv(nil) - SQL_NULL_HDBC* = TSqlHDBC(nil) - SQL_NULL_HSTMT* = TSqlHStmt(nil) - SQL_NULL_HDESC* = TSqlHDesc(nil) #* null handle used in place of parent handle when allocating HENV */ - SQL_NULL_HANDLE* = TSqlHandle(nil) #* Values that may appear in the result set of SQLSpecialColumns() */ + SQL_NULL_HENV* = SqlHEnv(nil) + SQL_NULL_HDBC* = SqlHDBC(nil) + SQL_NULL_HSTMT* = SqlHStmt(nil) + SQL_NULL_HDESC* = SqlHDesc(nil) #* null handle used in place of parent handle when allocating HENV */ + SQL_NULL_HANDLE* = SqlHandle(nil) #* Values that may appear in the result set of SQLSpecialColumns() */ SQL_SCOPE_CURROW* = 0 SQL_SCOPE_TRANSACTION* = 1 SQL_SCOPE_SESSION* = 2 #* Column types and scopes in SQLSpecialColumns. */ @@ -622,167 +633,167 @@ const ODBC_CONFIG_SYS_DSN* = 5 ODBC_REMOVE_SYS_DSN* = 6 -proc SQLAllocHandle*(HandleType: TSqlSmallInt, InputHandle: TSqlHandle, - OutputHandlePtr: var TSqlHandle): TSqlSmallInt{. +proc SQLAllocHandle*(HandleType: TSqlSmallInt, InputHandle: SqlHandle, + OutputHandlePtr: var SqlHandle): TSqlSmallInt{. dynlib: odbclib, importc.} -proc SQLSetEnvAttr*(EnvironmentHandle: TSqlHEnv, Attribute: TSqlInteger, - Value: TSqlPointer, StringLength: TSqlInteger): TSqlSmallInt{. +proc SQLSetEnvAttr*(EnvironmentHandle: SqlHEnv, Attribute: TSqlInteger, + Value: SqlPointer, StringLength: TSqlInteger): TSqlSmallInt{. dynlib: odbclib, importc.} -proc SQLGetEnvAttr*(EnvironmentHandle: TSqlHEnv, Attribute: TSqlInteger, - Value: TSqlPointer, BufferLength: TSqlInteger, +proc SQLGetEnvAttr*(EnvironmentHandle: SqlHEnv, Attribute: TSqlInteger, + Value: SqlPointer, BufferLength: TSqlInteger, StringLength: PSQLINTEGER): TSqlSmallInt{.dynlib: odbclib, importc.} -proc SQLFreeHandle*(HandleType: TSqlSmallInt, Handle: TSqlHandle): TSqlSmallInt{. +proc SQLFreeHandle*(HandleType: TSqlSmallInt, Handle: SqlHandle): TSqlSmallInt{. dynlib: odbclib, importc.} -proc SQLGetDiagRec*(HandleType: TSqlSmallInt, Handle: TSqlHandle, +proc SQLGetDiagRec*(HandleType: TSqlSmallInt, Handle: SqlHandle, RecNumber: TSqlSmallInt, Sqlstate: PSQLCHAR, NativeError: var TSqlInteger, MessageText: PSQLCHAR, BufferLength: TSqlSmallInt, TextLength: var TSqlSmallInt): TSqlSmallInt{. dynlib: odbclib, importc.} -proc SQLGetDiagField*(HandleType: TSqlSmallInt, Handle: TSqlHandle, +proc SQLGetDiagField*(HandleType: TSqlSmallInt, Handle: SqlHandle, RecNumber: TSqlSmallInt, DiagIdentifier: TSqlSmallInt, - DiagInfoPtr: TSqlPointer, BufferLength: TSqlSmallInt, + DiagInfoPtr: SqlPointer, BufferLength: TSqlSmallInt, StringLengthPtr: var TSqlSmallInt): TSqlSmallInt{. dynlib: odbclib, importc.} -proc SQLConnect*(ConnectionHandle: TSqlHDBC, ServerName: PSQLCHAR, +proc SQLConnect*(ConnectionHandle: SqlHDBC, ServerName: PSQLCHAR, NameLength1: TSqlSmallInt, UserName: PSQLCHAR, NameLength2: TSqlSmallInt, Authentication: PSQLCHAR, NameLength3: TSqlSmallInt): TSqlSmallInt{.dynlib: odbclib, importc.} -proc SQLDisconnect*(ConnectionHandle: TSqlHDBC): TSqlSmallInt{.dynlib: odbclib, +proc SQLDisconnect*(ConnectionHandle: SqlHDBC): TSqlSmallInt{.dynlib: odbclib, importc.} -proc SQLDriverConnect*(hdbc: TSqlHDBC, hwnd: TSqlHWND, szCsin: cstring, +proc SQLDriverConnect*(hdbc: SqlHDBC, hwnd: SqlHWND, szCsin: cstring, szCLen: TSqlSmallInt, szCsout: cstring, cbCSMax: TSqlSmallInt, cbCsOut: var TSqlSmallInt, - f: TSqlUSmallInt): TSqlSmallInt{.dynlib: odbclib, importc.} -proc SQLBrowseConnect*(hdbc: TSqlHDBC, szConnStrIn: PSQLCHAR, + f: SqlUSmallInt): TSqlSmallInt{.dynlib: odbclib, importc.} +proc SQLBrowseConnect*(hdbc: SqlHDBC, szConnStrIn: PSQLCHAR, cbConnStrIn: TSqlSmallInt, szConnStrOut: PSQLCHAR, cbConnStrOutMax: TSqlSmallInt, cbConnStrOut: var TSqlSmallInt): TSqlSmallInt{. dynlib: odbclib, importc.} -proc SQLExecDirect*(StatementHandle: TSqlHStmt, StatementText: PSQLCHAR, +proc SQLExecDirect*(StatementHandle: SqlHStmt, StatementText: PSQLCHAR, TextLength: TSqlInteger): TSqlSmallInt{.dynlib: odbclib, importc.} -proc SQLPrepare*(StatementHandle: TSqlHStmt, StatementText: PSQLCHAR, +proc SQLPrepare*(StatementHandle: SqlHStmt, StatementText: PSQLCHAR, TextLength: TSqlInteger): TSqlSmallInt{.dynlib: odbclib, importc.} -proc SQLCloseCursor*(StatementHandle: TSqlHStmt): TSqlSmallInt{.dynlib: odbclib, +proc SQLCloseCursor*(StatementHandle: SqlHStmt): TSqlSmallInt{.dynlib: odbclib, importc.} -proc SQLExecute*(StatementHandle: TSqlHStmt): TSqlSmallInt{.dynlib: odbclib, importc.} -proc SQLFetch*(StatementHandle: TSqlHStmt): TSqlSmallInt{.dynlib: odbclib, importc.} -proc SQLNumResultCols*(StatementHandle: TSqlHStmt, ColumnCount: var TSqlSmallInt): TSqlSmallInt{. +proc SQLExecute*(StatementHandle: SqlHStmt): TSqlSmallInt{.dynlib: odbclib, importc.} +proc SQLFetch*(StatementHandle: SqlHStmt): TSqlSmallInt{.dynlib: odbclib, importc.} +proc SQLNumResultCols*(StatementHandle: SqlHStmt, ColumnCount: var TSqlSmallInt): TSqlSmallInt{. dynlib: odbclib, importc.} -proc SQLDescribeCol*(StatementHandle: TSqlHStmt, ColumnNumber: TSqlUSmallInt, +proc SQLDescribeCol*(StatementHandle: SqlHStmt, ColumnNumber: SqlUSmallInt, ColumnName: PSQLCHAR, BufferLength: TSqlSmallInt, NameLength: var TSqlSmallInt, DataType: var TSqlSmallInt, - ColumnSize: var TSqlUInteger, + ColumnSize: var SqlUInteger, DecimalDigits: var TSqlSmallInt, Nullable: var TSqlSmallInt): TSqlSmallInt{. dynlib: odbclib, importc.} -proc SQLFetchScroll*(StatementHandle: TSqlHStmt, FetchOrientation: TSqlSmallInt, +proc SQLFetchScroll*(StatementHandle: SqlHStmt, FetchOrientation: TSqlSmallInt, FetchOffset: TSqlInteger): TSqlSmallInt{.dynlib: odbclib, importc.} -proc SQLExtendedFetch*(hstmt: TSqlHStmt, fFetchType: TSqlUSmallInt, +proc SQLExtendedFetch*(hstmt: SqlHStmt, fFetchType: SqlUSmallInt, irow: TSqlInteger, pcrow: PSQLUINTEGER, rgfRowStatus: PSQLUSMALLINT): TSqlSmallInt{.dynlib: odbclib, importc.} -proc SQLGetData*(StatementHandle: TSqlHStmt, ColumnNumber: TSqlUSmallInt, - TargetType: TSqlSmallInt, TargetValue: TSqlPointer, +proc SQLGetData*(StatementHandle: SqlHStmt, ColumnNumber: SqlUSmallInt, + TargetType: TSqlSmallInt, TargetValue: SqlPointer, BufferLength: TSqlInteger, StrLen_or_Ind: PSQLINTEGER): TSqlSmallInt{. dynlib: odbclib, importc.} -proc SQLSetStmtAttr*(StatementHandle: TSqlHStmt, Attribute: TSqlInteger, - Value: TSqlPointer, StringLength: TSqlInteger): TSqlSmallInt{. +proc SQLSetStmtAttr*(StatementHandle: SqlHStmt, Attribute: TSqlInteger, + Value: SqlPointer, StringLength: TSqlInteger): TSqlSmallInt{. dynlib: odbclib, importc.} -proc SQLGetStmtAttr*(StatementHandle: TSqlHStmt, Attribute: TSqlInteger, - Value: TSqlPointer, BufferLength: TSqlInteger, +proc SQLGetStmtAttr*(StatementHandle: SqlHStmt, Attribute: TSqlInteger, + Value: SqlPointer, BufferLength: TSqlInteger, StringLength: PSQLINTEGER): TSqlSmallInt{.dynlib: odbclib, importc.} -proc SQLGetInfo*(ConnectionHandle: TSqlHDBC, InfoType: TSqlUSmallInt, - InfoValue: TSqlPointer, BufferLength: TSqlSmallInt, +proc SQLGetInfo*(ConnectionHandle: SqlHDBC, InfoType: SqlUSmallInt, + InfoValue: SqlPointer, BufferLength: TSqlSmallInt, StringLength: PSQLSMALLINT): TSqlSmallInt{.dynlib: odbclib, importc.} -proc SQLBulkOperations*(StatementHandle: TSqlHStmt, Operation: TSqlSmallInt): TSqlSmallInt{. +proc SQLBulkOperations*(StatementHandle: SqlHStmt, Operation: TSqlSmallInt): TSqlSmallInt{. dynlib: odbclib, importc.} -proc SQLPutData*(StatementHandle: TSqlHStmt, Data: TSqlPointer, +proc SQLPutData*(StatementHandle: SqlHStmt, Data: SqlPointer, StrLen_or_Ind: TSqlInteger): TSqlSmallInt{.dynlib: odbclib, importc.} -proc SQLBindCol*(StatementHandle: TSqlHStmt, ColumnNumber: TSqlUSmallInt, - TargetType: TSqlSmallInt, TargetValue: TSqlPointer, +proc SQLBindCol*(StatementHandle: SqlHStmt, ColumnNumber: SqlUSmallInt, + TargetType: TSqlSmallInt, TargetValue: SqlPointer, BufferLength: TSqlInteger, StrLen_or_Ind: PSQLINTEGER): TSqlSmallInt{. dynlib: odbclib, importc.} -proc SQLSetPos*(hstmt: TSqlHStmt, irow: TSqlUSmallInt, fOption: TSqlUSmallInt, - fLock: TSqlUSmallInt): TSqlSmallInt{.dynlib: odbclib, importc.} -proc SQLDataSources*(EnvironmentHandle: TSqlHEnv, Direction: TSqlUSmallInt, +proc SQLSetPos*(hstmt: SqlHStmt, irow: SqlUSmallInt, fOption: SqlUSmallInt, + fLock: SqlUSmallInt): TSqlSmallInt{.dynlib: odbclib, importc.} +proc SQLDataSources*(EnvironmentHandle: SqlHEnv, Direction: SqlUSmallInt, ServerName: PSQLCHAR, BufferLength1: TSqlSmallInt, NameLength1: PSQLSMALLINT, Description: PSQLCHAR, BufferLength2: TSqlSmallInt, NameLength2: PSQLSMALLINT): TSqlSmallInt{. dynlib: odbclib, importc.} -proc SQLDrivers*(EnvironmentHandle: TSqlHEnv, Direction: TSqlUSmallInt, +proc SQLDrivers*(EnvironmentHandle: SqlHEnv, Direction: SqlUSmallInt, DriverDescription: PSQLCHAR, BufferLength1: TSqlSmallInt, DescriptionLength1: PSQLSMALLINT, DriverAttributes: PSQLCHAR, BufferLength2: TSqlSmallInt, AttributesLength2: PSQLSMALLINT): TSqlSmallInt{. dynlib: odbclib, importc.} -proc SQLSetConnectAttr*(ConnectionHandle: TSqlHDBC, Attribute: TSqlInteger, - Value: TSqlPointer, StringLength: TSqlInteger): TSqlSmallInt{. +proc SQLSetConnectAttr*(ConnectionHandle: SqlHDBC, Attribute: TSqlInteger, + Value: SqlPointer, StringLength: TSqlInteger): TSqlSmallInt{. dynlib: odbclib, importc.} -proc SQLGetCursorName*(StatementHandle: TSqlHStmt, CursorName: PSQLCHAR, +proc SQLGetCursorName*(StatementHandle: SqlHStmt, CursorName: PSQLCHAR, BufferLength: TSqlSmallInt, NameLength: PSQLSMALLINT): TSqlSmallInt{. dynlib: odbclib, importc.} -proc SQLSetCursorName*(StatementHandle: TSqlHStmt, CursorName: PSQLCHAR, +proc SQLSetCursorName*(StatementHandle: SqlHStmt, CursorName: PSQLCHAR, NameLength: TSqlSmallInt): TSqlSmallInt{.dynlib: odbclib, importc.} -proc SQLRowCount*(StatementHandle: TSqlHStmt, RowCount: var TSqlInteger): TSqlSmallInt{. +proc SQLRowCount*(StatementHandle: SqlHStmt, RowCount: var TSqlInteger): TSqlSmallInt{. dynlib: odbclib, importc.} -proc SQLBindParameter*(hstmt: TSqlHStmt, ipar: TSqlUSmallInt, +proc SQLBindParameter*(hstmt: SqlHStmt, ipar: SqlUSmallInt, fParamType: TSqlSmallInt, fCType: TSqlSmallInt, - fSqlType: TSqlSmallInt, cbColDef: TSqlUInteger, - ibScale: TSqlSmallInt, rgbValue: TSqlPointer, + fSqlType: TSqlSmallInt, cbColDef: SqlUInteger, + ibScale: TSqlSmallInt, rgbValue: SqlPointer, cbValueMax: TSqlInteger, pcbValue: PSQLINTEGER): TSqlSmallInt{. dynlib: odbclib, importc.} -proc SQLFreeStmt*(StatementHandle: TSqlHStmt, Option: TSqlUSmallInt): TSqlSmallInt{. +proc SQLFreeStmt*(StatementHandle: SqlHStmt, Option: SqlUSmallInt): TSqlSmallInt{. dynlib: odbclib, importc.} -proc SQLColAttribute*(StatementHandle: TSqlHStmt, ColumnNumber: TSqlUSmallInt, - FieldIdentifier: TSqlUSmallInt, +proc SQLColAttribute*(StatementHandle: SqlHStmt, ColumnNumber: SqlUSmallInt, + FieldIdentifier: SqlUSmallInt, CharacterAttribute: PSQLCHAR, BufferLength: TSqlSmallInt, StringLength: PSQLSMALLINT, - NumericAttribute: TSqlPointer): TSqlSmallInt{. + NumericAttribute: SqlPointer): TSqlSmallInt{. dynlib: odbclib, importc.} -proc SQLEndTran*(HandleType: TSqlSmallInt, Handle: TSqlHandle, +proc SQLEndTran*(HandleType: TSqlSmallInt, Handle: SqlHandle, CompletionType: TSqlSmallInt): TSqlSmallInt{.dynlib: odbclib, importc.} -proc SQLTables*(hstmt: TSqlHStmt, szTableQualifier: PSQLCHAR, +proc SQLTables*(hstmt: SqlHStmt, szTableQualifier: PSQLCHAR, cbTableQualifier: TSqlSmallInt, szTableOwner: PSQLCHAR, cbTableOwner: TSqlSmallInt, szTableName: PSQLCHAR, cbTableName: TSqlSmallInt, szTableType: PSQLCHAR, cbTableType: TSqlSmallInt): TSqlSmallInt{.dynlib: odbclib, importc.} -proc SQLColumns*(hstmt: TSqlHStmt, szTableQualifier: PSQLCHAR, +proc SQLColumns*(hstmt: SqlHStmt, szTableQualifier: PSQLCHAR, cbTableQualifier: TSqlSmallInt, szTableOwner: PSQLCHAR, cbTableOwner: TSqlSmallInt, szTableName: PSQLCHAR, cbTableName: TSqlSmallInt, szColumnName: PSQLCHAR, cbColumnName: TSqlSmallInt): TSqlSmallInt{.dynlib: odbclib, importc.} -proc SQLSpecialColumns*(StatementHandle: TSqlHStmt, IdentifierType: TSqlUSmallInt, +proc SQLSpecialColumns*(StatementHandle: SqlHStmt, IdentifierType: SqlUSmallInt, CatalogName: PSQLCHAR, NameLength1: TSqlSmallInt, SchemaName: PSQLCHAR, NameLength2: TSqlSmallInt, TableName: PSQLCHAR, NameLength3: TSqlSmallInt, - Scope: TSqlUSmallInt, - Nullable: TSqlUSmallInt): TSqlSmallInt{. + Scope: SqlUSmallInt, + Nullable: SqlUSmallInt): TSqlSmallInt{. dynlib: odbclib, importc.} -proc SQLProcedures*(hstmt: TSqlHStmt, szTableQualifier: PSQLCHAR, +proc SQLProcedures*(hstmt: SqlHStmt, szTableQualifier: PSQLCHAR, cbTableQualifier: TSqlSmallInt, szTableOwner: PSQLCHAR, cbTableOwner: TSqlSmallInt, szTableName: PSQLCHAR, cbTableName: TSqlSmallInt): TSqlSmallInt{.dynlib: odbclib, importc.} -proc SQLPrimaryKeys*(hstmt: TSqlHStmt, CatalogName: PSQLCHAR, +proc SQLPrimaryKeys*(hstmt: SqlHStmt, CatalogName: PSQLCHAR, NameLength1: TSqlSmallInt, SchemaName: PSQLCHAR, NameLength2: TSqlSmallInt, TableName: PSQLCHAR, NameLength3: TSqlSmallInt): TSqlSmallInt{.dynlib: odbclib, importc.} -proc SQLProcedureColumns*(hstmt: TSqlHStmt, CatalogName: PSQLCHAR, +proc SQLProcedureColumns*(hstmt: SqlHStmt, CatalogName: PSQLCHAR, NameLength1: TSqlSmallInt, SchemaName: PSQLCHAR, NameLength2: TSqlSmallInt, ProcName: PSQLCHAR, NameLength3: TSqlSmallInt, ColumnName: PSQLCHAR, NameLength4: TSqlSmallInt): TSqlSmallInt{.dynlib: odbclib, importc.} -proc SQLStatistics*(hstmt: TSqlHStmt, CatalogName: PSQLCHAR, +proc SQLStatistics*(hstmt: SqlHStmt, CatalogName: PSQLCHAR, NameLength1: TSqlSmallInt, SchemaName: PSQLCHAR, NameLength2: TSqlSmallInt, TableName: PSQLCHAR, - NameLength3: TSqlSmallInt, Unique: TSqlUSmallInt, - Reserved: TSqlUSmallInt): TSqlSmallInt {. + NameLength3: TSqlSmallInt, Unique: SqlUSmallInt, + Reserved: SqlUSmallInt): TSqlSmallInt {. dynlib: odbclib, importc.} {.pop.} diff --git a/lib/wrappers/pdcurses.nim b/lib/wrappers/pdcurses.nim index bed69648a..7e7a6c47f 100644 --- a/lib/wrappers/pdcurses.nim +++ b/lib/wrappers/pdcurses.nim @@ -406,15 +406,15 @@ type button*: array[0..3 - 1, cshort] # state of each button changes*: cint # flags indicating what has changed with the mouse - TMEVENT*{.pure, final.} = object + MEVENT*{.pure, final.} = object id*: cshort # unused, always 0 x*: cint y*: cint - z*: cint # x, y same as MOUSE_STATUS; z unused + z*: cint # x, y same as TMOUSE_STATUS; z unused bstate*: cunsignedlong # equivalent to changes + button[], but - # in the same format as used for mousemask() + # in the same format as used for mousemask() - TWINDOW*{.pure, final.} = object + WINDOW*{.pure, final.} = object cury*: cint # current pseudo-cursor curx*: cint maxy*: cint # max window coordinates @@ -439,26 +439,30 @@ type delayms*: cint # milliseconds of delay for getch() parx*: cint pary*: cint # coords relative to parent (0,0) - parent*: ptr TWINDOW # subwin's pointer to parent win + parent*: ptr WINDOW # subwin's pointer to parent win - TPANELOBS*{.pure, final.} = object - above*: ptr TPANELOBS - pan*: ptr TPANEL + PANELOBS*{.pure, final.} = object + above*: ptr PANELOBS + pan*: ptr PANEL - TPANEL*{.pure, final.} = object - win*: ptr TWINDOW + PANEL*{.pure, final.} = object + win*: ptr WINDOW wstarty*: cint wendy*: cint wstartx*: cint wendx*: cint - below*: ptr TPANEL - above*: ptr TPANEL + below*: ptr PANEL + above*: ptr PANEL user*: pointer - obscure*: ptr TPANELOBS + obscure*: ptr PANELOBS +{.deprecated: [ + #TMOUSE_STATUS: MOUSE_STATUS, # Name conflict when we drop the `T` + TMEVENT: MEVENT, TWINDOW: WINDOW, + TPANELOBS: PANELOBS, TPANEL:PANEL].} when unixOS: type - TSCREEN*{.pure, final.} = object + SCREEN*{.pure, final.} = object alive*: cunsignedchar # if initscr() called, and not endwin() autocr*: cunsignedchar # if cr -> lf cbreak*: cunsignedchar # if terminal unbuffered @@ -481,7 +485,7 @@ when unixOS: map_mbe_to_key*: cunsignedlong # map mouse buttons to slk mouse_wait*: cint # time to wait (in ms) for a button release after a press slklines*: cint # lines in use by slk_init() - slk_winptr*: ptr TWINDOW # window for slk + slk_winptr*: ptr WINDOW # window for slk linesrippedoff*: cint # lines ripped off via ripoffline() linesrippedoffontop*: cint # lines ripped off on top via ripoffline() delaytenths*: cint # 1/10ths second to wait block getch() for @@ -499,9 +503,10 @@ when unixOS: sb_cur_y*: cint sb_cur_x*: cint line_color*: cshort # color of line attributes - default -1 + {.deprecated: [TSCREEN: SCREEN].} else: type - TSCREEN*{.pure, final.} = object + SCREEN*{.pure, final.} = object alive*: cunsignedchar # if initscr() called, and not endwin() autocr*: cunsignedchar # if cr -> lf cbreak*: cunsignedchar # if terminal unbuffered @@ -524,7 +529,7 @@ else: map_mbe_to_key*: cunsignedlong # map mouse buttons to slk mouse_wait*: cint # time to wait (in ms) for a button release after a press slklines*: cint # lines in use by slk_init() - slk_winptr*: ptr TWINDOW # window for slk + slk_winptr*: ptr WINDOW # window for slk linesrippedoff*: cint # lines ripped off via ripoffline() linesrippedoffontop*: cint # lines ripped off on top via ripoffline() delaytenths*: cint # 1/10ths second to wait block getch() for @@ -534,14 +539,15 @@ else: return_key_modifiers*: cunsignedchar # TRUE if modifier keys are returned as "real" keys key_code*: cunsignedchar # TRUE if last key is a special key; line_color*: cshort # color of line attributes - default -1 + {.deprecated: [TSCREEN: SCREEN].} var LINES*{.importc: "LINES", dynlib: pdcursesdll.}: cint COLS*{.importc: "COLS", dynlib: pdcursesdll.}: cint - stdscr*{.importc: "stdscr", dynlib: pdcursesdll.}: ptr TWINDOW - curscr*{.importc: "curscr", dynlib: pdcursesdll.}: ptr TWINDOW - SP*{.importc: "SP", dynlib: pdcursesdll.}: ptr TSCREEN - Mouse_status*{.importc: "Mouse_status", dynlib: pdcursesdll.}: TMOUSE_STATUS + stdscr*{.importc: "stdscr", dynlib: pdcursesdll.}: ptr WINDOW + curscr*{.importc: "curscr", dynlib: pdcursesdll.}: ptr WINDOW + SP*{.importc: "SP", dynlib: pdcursesdll.}: ptr SCREEN + Mouse_status*{.importc: "Mouse_status", dynlib: pdcursesdll.}: MOUSE_STATUS COLORS*{.importc: "COLORS", dynlib: pdcursesdll.}: cint COLOR_PAIRS*{.importc: "COLOR_PAIRS", dynlib: pdcursesdll.}: cint TABSIZE*{.importc: "TABSIZE", dynlib: pdcursesdll.}: cint @@ -690,14 +696,14 @@ proc border*(a2: cunsignedlong; a3: cunsignedlong; a4: cunsignedlong; a5: cunsignedlong; a6: cunsignedlong; a7: cunsignedlong; a8: cunsignedlong; a9: cunsignedlong): cint{.extdecl, importc: "border", dynlib: pdcursesdll.} -proc box*(a2: ptr TWINDOW; a3: cunsignedlong; a4: cunsignedlong): cint{.extdecl, +proc box*(a2: ptr WINDOW; a3: cunsignedlong; a4: cunsignedlong): cint{.extdecl, importc: "box", dynlib: pdcursesdll.} proc can_change_color*(): cunsignedchar{.extdecl, importc: "can_change_color", dynlib: pdcursesdll.} proc cbreak*(): cint{.extdecl, importc: "cbreak", dynlib: pdcursesdll.} proc chgat*(a2: cint; a3: cunsignedlong; a4: cshort; a5: pointer): cint{.extdecl, importc: "chgat", dynlib: pdcursesdll.} -proc clearok*(a2: ptr TWINDOW; a3: cunsignedchar): cint{.extdecl, +proc clearok*(a2: ptr WINDOW; a3: cunsignedchar): cint{.extdecl, importc: "clearok", dynlib: pdcursesdll.} proc clear*(): cint{.extdecl, importc: "clear", dynlib: pdcursesdll.} proc clrtobot*(): cint{.extdecl, importc: "clrtobot", dynlib: pdcursesdll.} @@ -706,7 +712,7 @@ proc color_content*(a2: cshort; a3: ptr cshort; a4: ptr cshort; a5: ptr cshort): extdecl, importc: "color_content", dynlib: pdcursesdll.} proc color_set*(a2: cshort; a3: pointer): cint{.extdecl, importc: "color_set", dynlib: pdcursesdll.} -proc copywin*(a2: ptr TWINDOW; a3: ptr TWINDOW; a4: cint; a5: cint; a6: cint; +proc copywin*(a2: ptr WINDOW; a3: ptr WINDOW; a4: cint; a5: cint; a6: cint; a7: cint; a8: cint; a9: cint; a10: cint): cint{.extdecl, importc: "copywin", dynlib: pdcursesdll.} proc curs_set*(a2: cint): cint{.extdecl, importc: "curs_set", dynlib: pdcursesdll.} @@ -718,14 +724,14 @@ proc delay_output*(a2: cint): cint{.extdecl, importc: "delay_output", dynlib: pdcursesdll.} proc delch*(): cint{.extdecl, importc: "delch", dynlib: pdcursesdll.} proc deleteln*(): cint{.extdecl, importc: "deleteln", dynlib: pdcursesdll.} -proc delscreen*(a2: ptr TSCREEN){.extdecl, importc: "delscreen", +proc delscreen*(a2: ptr SCREEN){.extdecl, importc: "delscreen", dynlib: pdcursesdll.} -proc delwin*(a2: ptr TWINDOW): cint{.extdecl, importc: "delwin", +proc delwin*(a2: ptr WINDOW): cint{.extdecl, importc: "delwin", dynlib: pdcursesdll.} -proc derwin*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: cint; a6: cint): ptr TWINDOW{. +proc derwin*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cint; a6: cint): ptr WINDOW{. extdecl, importc: "derwin", dynlib: pdcursesdll.} proc doupdate*(): cint{.extdecl, importc: "doupdate", dynlib: pdcursesdll.} -proc dupwin*(a2: ptr TWINDOW): ptr TWINDOW{.extdecl, importc: "dupwin", +proc dupwin*(a2: ptr WINDOW): ptr WINDOW{.extdecl, importc: "dupwin", dynlib: pdcursesdll.} proc echochar*(a2: cunsignedlong): cint{.extdecl, importc: "echochar", dynlib: pdcursesdll.} @@ -736,12 +742,12 @@ proc erase*(): cint{.extdecl, importc: "erase", dynlib: pdcursesdll.} proc filter*(){.extdecl, importc: "filter", dynlib: pdcursesdll.} proc flash*(): cint{.extdecl, importc: "flash", dynlib: pdcursesdll.} proc flushinp*(): cint{.extdecl, importc: "flushinp", dynlib: pdcursesdll.} -proc getbkgd*(a2: ptr TWINDOW): cunsignedlong{.extdecl, importc: "getbkgd", +proc getbkgd*(a2: ptr WINDOW): cunsignedlong{.extdecl, importc: "getbkgd", dynlib: pdcursesdll.} proc getnstr*(a2: cstring; a3: cint): cint{.extdecl, importc: "getnstr", dynlib: pdcursesdll.} proc getstr*(a2: cstring): cint{.extdecl, importc: "getstr", dynlib: pdcursesdll.} -proc getwin*(a2: File): ptr TWINDOW{.extdecl, importc: "getwin", +proc getwin*(a2: File): ptr WINDOW{.extdecl, importc: "getwin", dynlib: pdcursesdll.} proc halfdelay*(a2: cint): cint{.extdecl, importc: "halfdelay", dynlib: pdcursesdll.} @@ -751,11 +757,11 @@ proc has_ic*(): cunsignedchar{.extdecl, importc: "has_ic", dynlib: pdcursesdll.} proc has_il*(): cunsignedchar{.extdecl, importc: "has_il", dynlib: pdcursesdll.} proc hline*(a2: cunsignedlong; a3: cint): cint{.extdecl, importc: "hline", dynlib: pdcursesdll.} -proc idcok*(a2: ptr TWINDOW; a3: cunsignedchar){.extdecl, importc: "idcok", +proc idcok*(a2: ptr WINDOW; a3: cunsignedchar){.extdecl, importc: "idcok", dynlib: pdcursesdll.} -proc idlok*(a2: ptr TWINDOW; a3: cunsignedchar): cint{.extdecl, importc: "idlok", +proc idlok*(a2: ptr WINDOW; a3: cunsignedchar): cint{.extdecl, importc: "idlok", dynlib: pdcursesdll.} -proc immedok*(a2: ptr TWINDOW; a3: cunsignedchar){.extdecl, importc: "immedok", +proc immedok*(a2: ptr WINDOW; a3: cunsignedchar){.extdecl, importc: "immedok", dynlib: pdcursesdll.} proc inchnstr*(a2: ptr cunsignedlong; a3: cint): cint{.extdecl, importc: "inchnstr", dynlib: pdcursesdll.} @@ -766,7 +772,7 @@ proc init_color*(a2: cshort; a3: cshort; a4: cshort; a5: cshort): cint{.extdecl, importc: "init_color", dynlib: pdcursesdll.} proc init_pair*(a2: cshort; a3: cshort; a4: cshort): cint{.extdecl, importc: "init_pair", dynlib: pdcursesdll.} -proc initscr*(): ptr TWINDOW{.extdecl, importc: "initscr", dynlib: pdcursesdll.} +proc initscr*(): ptr WINDOW{.extdecl, importc: "initscr", dynlib: pdcursesdll.} proc innstr*(a2: cstring; a3: cint): cint{.extdecl, importc: "innstr", dynlib: pdcursesdll.} proc insch*(a2: cunsignedlong): cint{.extdecl, importc: "insch", @@ -777,21 +783,21 @@ proc insnstr*(a2: cstring; a3: cint): cint{.extdecl, importc: "insnstr", dynlib: pdcursesdll.} proc insstr*(a2: cstring): cint{.extdecl, importc: "insstr", dynlib: pdcursesdll.} proc instr*(a2: cstring): cint{.extdecl, importc: "instr", dynlib: pdcursesdll.} -proc intrflush*(a2: ptr TWINDOW; a3: cunsignedchar): cint{.extdecl, +proc intrflush*(a2: ptr WINDOW; a3: cunsignedchar): cint{.extdecl, importc: "intrflush", dynlib: pdcursesdll.} proc isendwin*(): cunsignedchar{.extdecl, importc: "isendwin", dynlib: pdcursesdll.} -proc is_linetouched*(a2: ptr TWINDOW; a3: cint): cunsignedchar{.extdecl, +proc is_linetouched*(a2: ptr WINDOW; a3: cint): cunsignedchar{.extdecl, importc: "is_linetouched", dynlib: pdcursesdll.} -proc is_wintouched*(a2: ptr TWINDOW): cunsignedchar{.extdecl, +proc is_wintouched*(a2: ptr WINDOW): cunsignedchar{.extdecl, importc: "is_wintouched", dynlib: pdcursesdll.} proc keyname*(a2: cint): cstring{.extdecl, importc: "keyname", dynlib: pdcursesdll.} -proc keypad*(a2: ptr TWINDOW; a3: cunsignedchar): cint{.extdecl, importc: "keypad", +proc keypad*(a2: ptr WINDOW; a3: cunsignedchar): cint{.extdecl, importc: "keypad", dynlib: pdcursesdll.} proc killchar*(): char{.extdecl, importc: "killchar", dynlib: pdcursesdll.} -proc leaveok*(a2: ptr TWINDOW; a3: cunsignedchar): cint{.extdecl, +proc leaveok*(a2: ptr WINDOW; a3: cunsignedchar): cint{.extdecl, importc: "leaveok", dynlib: pdcursesdll.} proc longname*(): cstring{.extdecl, importc: "longname", dynlib: pdcursesdll.} -proc meta*(a2: ptr TWINDOW; a3: cunsignedchar): cint{.extdecl, importc: "meta", +proc meta*(a2: ptr WINDOW; a3: cunsignedchar): cint{.extdecl, importc: "meta", dynlib: pdcursesdll.} proc move*(a2: cint; a3: cint): cint{.extdecl, importc: "move", dynlib: pdcursesdll.} @@ -811,7 +817,7 @@ proc mvcur*(a2: cint; a3: cint; a4: cint; a5: cint): cint{.extdecl, importc: "mvcur", dynlib: pdcursesdll.} proc mvdelch*(a2: cint; a3: cint): cint{.extdecl, importc: "mvdelch", dynlib: pdcursesdll.} -proc mvderwin*(a2: ptr TWINDOW; a3: cint; a4: cint): cint{.extdecl, +proc mvderwin*(a2: ptr WINDOW; a3: cint; a4: cint): cint{.extdecl, importc: "mvderwin", dynlib: pdcursesdll.} proc mvgetch*(a2: cint; a3: cint): cint{.extdecl, importc: "mvgetch", dynlib: pdcursesdll.} @@ -843,92 +849,92 @@ proc mvscanw*(a2: cint; a3: cint; a4: cstring): cint{.varargs, extdecl, importc: "mvscanw", dynlib: pdcursesdll.} proc mvvline*(a2: cint; a3: cint; a4: cunsignedlong; a5: cint): cint{.extdecl, importc: "mvvline", dynlib: pdcursesdll.} -proc mvwaddchnstr*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong; +proc mvwaddchnstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong; a6: cint): cint{.extdecl, importc: "mvwaddchnstr", dynlib: pdcursesdll.} -proc mvwaddchstr*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong): cint{. +proc mvwaddchstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong): cint{. extdecl, importc: "mvwaddchstr", dynlib: pdcursesdll.} -proc mvwaddch*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: cunsignedlong): cint{. +proc mvwaddch*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cunsignedlong): cint{. extdecl, importc: "mvwaddch", dynlib: pdcursesdll.} -proc mvwaddnstr*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: cstring; a6: cint): cint{. +proc mvwaddnstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cstring; a6: cint): cint{. extdecl, importc: "mvwaddnstr", dynlib: pdcursesdll.} -proc mvwaddstr*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: cstring): cint{.extdecl, +proc mvwaddstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cstring): cint{.extdecl, importc: "mvwaddstr", dynlib: pdcursesdll.} -proc mvwchgat*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: cint; a6: cunsignedlong; +proc mvwchgat*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cint; a6: cunsignedlong; a7: cshort; a8: pointer): cint{.extdecl, importc: "mvwchgat", dynlib: pdcursesdll.} -proc mvwdelch*(a2: ptr TWINDOW; a3: cint; a4: cint): cint{.extdecl, +proc mvwdelch*(a2: ptr WINDOW; a3: cint; a4: cint): cint{.extdecl, importc: "mvwdelch", dynlib: pdcursesdll.} -proc mvwgetch*(a2: ptr TWINDOW; a3: cint; a4: cint): cint{.extdecl, +proc mvwgetch*(a2: ptr WINDOW; a3: cint; a4: cint): cint{.extdecl, importc: "mvwgetch", dynlib: pdcursesdll.} -proc mvwgetnstr*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: cstring; a6: cint): cint{. +proc mvwgetnstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cstring; a6: cint): cint{. extdecl, importc: "mvwgetnstr", dynlib: pdcursesdll.} -proc mvwgetstr*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: cstring): cint{.extdecl, +proc mvwgetstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cstring): cint{.extdecl, importc: "mvwgetstr", dynlib: pdcursesdll.} -proc mvwhline*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: cunsignedlong; a6: cint): cint{. +proc mvwhline*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cunsignedlong; a6: cint): cint{. extdecl, importc: "mvwhline", dynlib: pdcursesdll.} -proc mvwinchnstr*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong; +proc mvwinchnstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong; a6: cint): cint{.extdecl, importc: "mvwinchnstr", dynlib: pdcursesdll.} -proc mvwinchstr*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong): cint{. +proc mvwinchstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong): cint{. extdecl, importc: "mvwinchstr", dynlib: pdcursesdll.} -proc mvwinch*(a2: ptr TWINDOW; a3: cint; a4: cint): cunsignedlong{.extdecl, +proc mvwinch*(a2: ptr WINDOW; a3: cint; a4: cint): cunsignedlong{.extdecl, importc: "mvwinch", dynlib: pdcursesdll.} -proc mvwinnstr*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: cstring; a6: cint): cint{. +proc mvwinnstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cstring; a6: cint): cint{. extdecl, importc: "mvwinnstr", dynlib: pdcursesdll.} -proc mvwinsch*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: cunsignedlong): cint{. +proc mvwinsch*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cunsignedlong): cint{. extdecl, importc: "mvwinsch", dynlib: pdcursesdll.} -proc mvwinsnstr*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: cstring; a6: cint): cint{. +proc mvwinsnstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cstring; a6: cint): cint{. extdecl, importc: "mvwinsnstr", dynlib: pdcursesdll.} -proc mvwinsstr*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: cstring): cint{.extdecl, +proc mvwinsstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cstring): cint{.extdecl, importc: "mvwinsstr", dynlib: pdcursesdll.} -proc mvwinstr*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: cstring): cint{.extdecl, +proc mvwinstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cstring): cint{.extdecl, importc: "mvwinstr", dynlib: pdcursesdll.} -proc mvwin*(a2: ptr TWINDOW; a3: cint; a4: cint): cint{.extdecl, importc: "mvwin", +proc mvwin*(a2: ptr WINDOW; a3: cint; a4: cint): cint{.extdecl, importc: "mvwin", dynlib: pdcursesdll.} -proc mvwprintw*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: cstring): cint{.varargs, +proc mvwprintw*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cstring): cint{.varargs, extdecl, importc: "mvwprintw", dynlib: pdcursesdll.} -proc mvwscanw*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: cstring): cint{.varargs, +proc mvwscanw*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cstring): cint{.varargs, extdecl, importc: "mvwscanw", dynlib: pdcursesdll.} -proc mvwvline*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: cunsignedlong; a6: cint): cint{. +proc mvwvline*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cunsignedlong; a6: cint): cint{. extdecl, importc: "mvwvline", dynlib: pdcursesdll.} proc napms*(a2: cint): cint{.extdecl, importc: "napms", dynlib: pdcursesdll.} -proc newpad*(a2: cint; a3: cint): ptr TWINDOW{.extdecl, importc: "newpad", +proc newpad*(a2: cint; a3: cint): ptr WINDOW{.extdecl, importc: "newpad", dynlib: pdcursesdll.} -proc newterm*(a2: cstring; a3: File; a4: File): ptr TSCREEN{.extdecl, +proc newterm*(a2: cstring; a3: File; a4: File): ptr SCREEN{.extdecl, importc: "newterm", dynlib: pdcursesdll.} -proc newwin*(a2: cint; a3: cint; a4: cint; a5: cint): ptr TWINDOW{.extdecl, +proc newwin*(a2: cint; a3: cint; a4: cint; a5: cint): ptr WINDOW{.extdecl, importc: "newwin", dynlib: pdcursesdll.} proc nl*(): cint{.extdecl, importc: "nl", dynlib: pdcursesdll.} proc nocbreak*(): cint{.extdecl, importc: "nocbreak", dynlib: pdcursesdll.} -proc nodelay*(a2: ptr TWINDOW; a3: cunsignedchar): cint{.extdecl, +proc nodelay*(a2: ptr WINDOW; a3: cunsignedchar): cint{.extdecl, importc: "nodelay", dynlib: pdcursesdll.} proc noecho*(): cint{.extdecl, importc: "noecho", dynlib: pdcursesdll.} proc nonl*(): cint{.extdecl, importc: "nonl", dynlib: pdcursesdll.} proc noqiflush*(){.extdecl, importc: "noqiflush", dynlib: pdcursesdll.} proc noraw*(): cint{.extdecl, importc: "noraw", dynlib: pdcursesdll.} -proc notimeout*(a2: ptr TWINDOW; a3: cunsignedchar): cint{.extdecl, +proc notimeout*(a2: ptr WINDOW; a3: cunsignedchar): cint{.extdecl, importc: "notimeout", dynlib: pdcursesdll.} -proc overlay*(a2: ptr TWINDOW; a3: ptr TWINDOW): cint{.extdecl, importc: "overlay", +proc overlay*(a2: ptr WINDOW; a3: ptr WINDOW): cint{.extdecl, importc: "overlay", dynlib: pdcursesdll.} -proc overwrite*(a2: ptr TWINDOW; a3: ptr TWINDOW): cint{.extdecl, +proc overwrite*(a2: ptr WINDOW; a3: ptr WINDOW): cint{.extdecl, importc: "overwrite", dynlib: pdcursesdll.} proc pair_content*(a2: cshort; a3: ptr cshort; a4: ptr cshort): cint{.extdecl, importc: "pair_content", dynlib: pdcursesdll.} -proc pechochar*(a2: ptr TWINDOW; a3: cunsignedlong): cint{.extdecl, +proc pechochar*(a2: ptr WINDOW; a3: cunsignedlong): cint{.extdecl, importc: "pechochar", dynlib: pdcursesdll.} -proc pnoutrefresh*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: cint; a6: cint; +proc pnoutrefresh*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cint; a6: cint; a7: cint; a8: cint): cint{.extdecl, importc: "pnoutrefresh", dynlib: pdcursesdll.} -proc prefresh*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: cint; a6: cint; a7: cint; +proc prefresh*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cint; a6: cint; a7: cint; a8: cint): cint{.extdecl, importc: "prefresh", dynlib: pdcursesdll.} proc printw*(a2: cstring): cint{.varargs, extdecl, importc: "printw", dynlib: pdcursesdll.} -proc putwin*(a2: ptr TWINDOW; a3: File): cint{.extdecl, importc: "putwin", +proc putwin*(a2: ptr WINDOW; a3: File): cint{.extdecl, importc: "putwin", dynlib: pdcursesdll.} proc qiflush*(){.extdecl, importc: "qiflush", dynlib: pdcursesdll.} proc raw*(): cint{.extdecl, importc: "raw", dynlib: pdcursesdll.} -proc redrawwin*(a2: ptr TWINDOW): cint{.extdecl, importc: "redrawwin", +proc redrawwin*(a2: ptr WINDOW): cint{.extdecl, importc: "redrawwin", dynlib: pdcursesdll.} proc refresh*(): cint{.extdecl, importc: "refresh", dynlib: pdcursesdll.} proc reset_prog_mode*(): cint{.extdecl, importc: "reset_prog_mode", @@ -936,7 +942,7 @@ proc reset_prog_mode*(): cint{.extdecl, importc: "reset_prog_mode", proc reset_shell_mode*(): cint{.extdecl, importc: "reset_shell_mode", dynlib: pdcursesdll.} proc resetty*(): cint{.extdecl, importc: "resetty", dynlib: pdcursesdll.} -#int ripoffline(int, int (*)(TWINDOW *, int)); +#int ripoffline(int, int (*)(WINDOW *, int)); proc savetty*(): cint{.extdecl, importc: "savetty", dynlib: pdcursesdll.} proc scanw*(a2: cstring): cint{.varargs, extdecl, importc: "scanw", dynlib: pdcursesdll.} @@ -948,11 +954,11 @@ proc scr_restore*(a2: cstring): cint{.extdecl, importc: "scr_restore", dynlib: pdcursesdll.} proc scr_set*(a2: cstring): cint{.extdecl, importc: "scr_set", dynlib: pdcursesdll.} proc scrl*(a2: cint): cint{.extdecl, importc: "scrl", dynlib: pdcursesdll.} -proc scroll*(a2: ptr TWINDOW): cint{.extdecl, importc: "scroll", +proc scroll*(a2: ptr WINDOW): cint{.extdecl, importc: "scroll", dynlib: pdcursesdll.} -proc scrollok*(a2: ptr TWINDOW; a3: cunsignedchar): cint{.extdecl, +proc scrollok*(a2: ptr WINDOW; a3: cunsignedchar): cint{.extdecl, importc: "scrollok", dynlib: pdcursesdll.} -proc set_term*(a2: ptr TSCREEN): ptr TSCREEN{.extdecl, importc: "set_term", +proc set_term*(a2: ptr SCREEN): ptr SCREEN{.extdecl, importc: "set_term", dynlib: pdcursesdll.} proc setscrreg*(a2: cint; a3: cint): cint{.extdecl, importc: "setscrreg", dynlib: pdcursesdll.} @@ -984,11 +990,11 @@ proc slk_touch*(): cint{.extdecl, importc: "slk_touch", dynlib: pdcursesdll.} proc standend*(): cint{.extdecl, importc: "standend", dynlib: pdcursesdll.} proc standout*(): cint{.extdecl, importc: "standout", dynlib: pdcursesdll.} proc start_color*(): cint{.extdecl, importc: "start_color", dynlib: pdcursesdll.} -proc subpad*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: cint; a6: cint): ptr TWINDOW{. +proc subpad*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cint; a6: cint): ptr WINDOW{. extdecl, importc: "subpad", dynlib: pdcursesdll.} -proc subwin*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: cint; a6: cint): ptr TWINDOW{. +proc subwin*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cint; a6: cint): ptr WINDOW{. extdecl, importc: "subwin", dynlib: pdcursesdll.} -proc syncok*(a2: ptr TWINDOW; a3: cunsignedchar): cint{.extdecl, importc: "syncok", +proc syncok*(a2: ptr WINDOW; a3: cunsignedchar): cint{.extdecl, importc: "syncok", dynlib: pdcursesdll.} proc termattrs*(): cunsignedlong{.extdecl, importc: "termattrs", dynlib: pdcursesdll.} @@ -996,13 +1002,13 @@ proc termattrs2*(): cunsignedlong{.extdecl, importc: "term_attrs", dynlib: pdcursesdll.} proc termname*(): cstring{.extdecl, importc: "termname", dynlib: pdcursesdll.} proc timeout*(a2: cint){.extdecl, importc: "timeout", dynlib: pdcursesdll.} -proc touchline*(a2: ptr TWINDOW; a3: cint; a4: cint): cint{.extdecl, +proc touchline*(a2: ptr WINDOW; a3: cint; a4: cint): cint{.extdecl, importc: "touchline", dynlib: pdcursesdll.} -proc touchwin*(a2: ptr TWINDOW): cint{.extdecl, importc: "touchwin", +proc touchwin*(a2: ptr WINDOW): cint{.extdecl, importc: "touchwin", dynlib: pdcursesdll.} proc typeahead*(a2: cint): cint{.extdecl, importc: "typeahead", dynlib: pdcursesdll.} -proc untouchwin*(a2: ptr TWINDOW): cint{.extdecl, importc: "untouchwin", +proc untouchwin*(a2: ptr WINDOW): cint{.extdecl, importc: "untouchwin", dynlib: pdcursesdll.} proc use_env*(a2: cunsignedchar){.extdecl, importc: "use_env", dynlib: pdcursesdll.} proc vidattr*(a2: cunsignedlong): cint{.extdecl, importc: "vidattr", @@ -1013,123 +1019,123 @@ proc vid_attr*(a2: cunsignedlong; a3: cshort; a4: pointer): cint{.extdecl, #int vid_puts(attr_t, short, void *, int (*)(int)); proc vline*(a2: cunsignedlong; a3: cint): cint{.extdecl, importc: "vline", dynlib: pdcursesdll.} -proc vwprintw*(a2: ptr TWINDOW; a3: cstring): cint{.extdecl, varargs, +proc vwprintw*(a2: ptr WINDOW; a3: cstring): cint{.extdecl, varargs, importc: "vw_printw", dynlib: pdcursesdll.} -proc vwprintw2*(a2: ptr TWINDOW; a3: cstring): cint{.extdecl, varargs, +proc vwprintw2*(a2: ptr WINDOW; a3: cstring): cint{.extdecl, varargs, importc: "vwprintw", dynlib: pdcursesdll.} -proc vwscanw*(a2: ptr TWINDOW; a3: cstring): cint{.extdecl, varargs, +proc vwscanw*(a2: ptr WINDOW; a3: cstring): cint{.extdecl, varargs, importc: "vw_scanw", dynlib: pdcursesdll.} -proc vwscanw2*(a2: ptr TWINDOW; a3: cstring): cint{.extdecl, varargs, +proc vwscanw2*(a2: ptr WINDOW; a3: cstring): cint{.extdecl, varargs, importc: "vwscanw", dynlib: pdcursesdll.} -proc waddchnstr*(a2: ptr TWINDOW; a3: ptr cunsignedlong; a4: cint): cint{.extdecl, +proc waddchnstr*(a2: ptr WINDOW; a3: ptr cunsignedlong; a4: cint): cint{.extdecl, importc: "waddchnstr", dynlib: pdcursesdll.} -proc waddchstr*(a2: ptr TWINDOW; a3: ptr cunsignedlong): cint{.extdecl, +proc waddchstr*(a2: ptr WINDOW; a3: ptr cunsignedlong): cint{.extdecl, importc: "waddchstr", dynlib: pdcursesdll.} -proc waddch*(a2: ptr TWINDOW; a3: cunsignedlong): cint{.extdecl, importc: "waddch", +proc waddch*(a2: ptr WINDOW; a3: cunsignedlong): cint{.extdecl, importc: "waddch", dynlib: pdcursesdll.} -proc waddnstr*(a2: ptr TWINDOW; a3: cstring; a4: cint): cint{.extdecl, +proc waddnstr*(a2: ptr WINDOW; a3: cstring; a4: cint): cint{.extdecl, importc: "waddnstr", dynlib: pdcursesdll.} -proc waddstr*(a2: ptr TWINDOW; a3: cstring): cint{.extdecl, importc: "waddstr", +proc waddstr*(a2: ptr WINDOW; a3: cstring): cint{.extdecl, importc: "waddstr", dynlib: pdcursesdll.} -proc wattroff*(a2: ptr TWINDOW; a3: cunsignedlong): cint{.extdecl, +proc wattroff*(a2: ptr WINDOW; a3: cunsignedlong): cint{.extdecl, importc: "wattroff", dynlib: pdcursesdll.} -proc wattron*(a2: ptr TWINDOW; a3: cunsignedlong): cint{.extdecl, +proc wattron*(a2: ptr WINDOW; a3: cunsignedlong): cint{.extdecl, importc: "wattron", dynlib: pdcursesdll.} -proc wattrset*(a2: ptr TWINDOW; a3: cunsignedlong): cint{.extdecl, +proc wattrset*(a2: ptr WINDOW; a3: cunsignedlong): cint{.extdecl, importc: "wattrset", dynlib: pdcursesdll.} -proc wattr_get*(a2: ptr TWINDOW; a3: ptr cunsignedlong; a4: ptr cshort; +proc wattr_get*(a2: ptr WINDOW; a3: ptr cunsignedlong; a4: ptr cshort; a5: pointer): cint{.extdecl, importc: "wattr_get", dynlib: pdcursesdll.} -proc wattr_off*(a2: ptr TWINDOW; a3: cunsignedlong; a4: pointer): cint{.extdecl, +proc wattr_off*(a2: ptr WINDOW; a3: cunsignedlong; a4: pointer): cint{.extdecl, importc: "wattr_off", dynlib: pdcursesdll.} -proc wattr_on*(a2: ptr TWINDOW; a3: cunsignedlong; a4: pointer): cint{.extdecl, +proc wattr_on*(a2: ptr WINDOW; a3: cunsignedlong; a4: pointer): cint{.extdecl, importc: "wattr_on", dynlib: pdcursesdll.} -proc wattr_set*(a2: ptr TWINDOW; a3: cunsignedlong; a4: cshort; a5: pointer): cint{. +proc wattr_set*(a2: ptr WINDOW; a3: cunsignedlong; a4: cshort; a5: pointer): cint{. extdecl, importc: "wattr_set", dynlib: pdcursesdll.} -proc wbkgdset*(a2: ptr TWINDOW; a3: cunsignedlong){.extdecl, importc: "wbkgdset", +proc wbkgdset*(a2: ptr WINDOW; a3: cunsignedlong){.extdecl, importc: "wbkgdset", dynlib: pdcursesdll.} -proc wbkgd*(a2: ptr TWINDOW; a3: cunsignedlong): cint{.extdecl, importc: "wbkgd", +proc wbkgd*(a2: ptr WINDOW; a3: cunsignedlong): cint{.extdecl, importc: "wbkgd", dynlib: pdcursesdll.} -proc wborder*(a2: ptr TWINDOW; a3: cunsignedlong; a4: cunsignedlong; +proc wborder*(a2: ptr WINDOW; a3: cunsignedlong; a4: cunsignedlong; a5: cunsignedlong; a6: cunsignedlong; a7: cunsignedlong; a8: cunsignedlong; a9: cunsignedlong; a10: cunsignedlong): cint{. extdecl, importc: "wborder", dynlib: pdcursesdll.} -proc wchgat*(a2: ptr TWINDOW; a3: cint; a4: cunsignedlong; a5: cshort; +proc wchgat*(a2: ptr WINDOW; a3: cint; a4: cunsignedlong; a5: cshort; a6: pointer): cint{.extdecl, importc: "wchgat", dynlib: pdcursesdll.} -proc wclear*(a2: ptr TWINDOW): cint{.extdecl, importc: "wclear", +proc wclear*(a2: ptr WINDOW): cint{.extdecl, importc: "wclear", dynlib: pdcursesdll.} -proc wclrtobot*(a2: ptr TWINDOW): cint{.extdecl, importc: "wclrtobot", +proc wclrtobot*(a2: ptr WINDOW): cint{.extdecl, importc: "wclrtobot", dynlib: pdcursesdll.} -proc wclrtoeol*(a2: ptr TWINDOW): cint{.extdecl, importc: "wclrtoeol", +proc wclrtoeol*(a2: ptr WINDOW): cint{.extdecl, importc: "wclrtoeol", dynlib: pdcursesdll.} -proc wcolor_set*(a2: ptr TWINDOW; a3: cshort; a4: pointer): cint{.extdecl, +proc wcolor_set*(a2: ptr WINDOW; a3: cshort; a4: pointer): cint{.extdecl, importc: "wcolor_set", dynlib: pdcursesdll.} -proc wcursyncup*(a2: ptr TWINDOW){.extdecl, importc: "wcursyncup", +proc wcursyncup*(a2: ptr WINDOW){.extdecl, importc: "wcursyncup", dynlib: pdcursesdll.} -proc wdelch*(a2: ptr TWINDOW): cint{.extdecl, importc: "wdelch", +proc wdelch*(a2: ptr WINDOW): cint{.extdecl, importc: "wdelch", dynlib: pdcursesdll.} -proc wdeleteln*(a2: ptr TWINDOW): cint{.extdecl, importc: "wdeleteln", +proc wdeleteln*(a2: ptr WINDOW): cint{.extdecl, importc: "wdeleteln", dynlib: pdcursesdll.} -proc wechochar*(a2: ptr TWINDOW; a3: cunsignedlong): cint{.extdecl, +proc wechochar*(a2: ptr WINDOW; a3: cunsignedlong): cint{.extdecl, importc: "wechochar", dynlib: pdcursesdll.} -proc werase*(a2: ptr TWINDOW): cint{.extdecl, importc: "werase", +proc werase*(a2: ptr WINDOW): cint{.extdecl, importc: "werase", dynlib: pdcursesdll.} -proc wgetch*(a2: ptr TWINDOW): cint{.extdecl, importc: "wgetch", +proc wgetch*(a2: ptr WINDOW): cint{.extdecl, importc: "wgetch", dynlib: pdcursesdll.} -proc wgetnstr*(a2: ptr TWINDOW; a3: cstring; a4: cint): cint{.extdecl, +proc wgetnstr*(a2: ptr WINDOW; a3: cstring; a4: cint): cint{.extdecl, importc: "wgetnstr", dynlib: pdcursesdll.} -proc wgetstr*(a2: ptr TWINDOW; a3: cstring): cint{.extdecl, importc: "wgetstr", +proc wgetstr*(a2: ptr WINDOW; a3: cstring): cint{.extdecl, importc: "wgetstr", dynlib: pdcursesdll.} -proc whline*(a2: ptr TWINDOW; a3: cunsignedlong; a4: cint): cint{.extdecl, +proc whline*(a2: ptr WINDOW; a3: cunsignedlong; a4: cint): cint{.extdecl, importc: "whline", dynlib: pdcursesdll.} -proc winchnstr*(a2: ptr TWINDOW; a3: ptr cunsignedlong; a4: cint): cint{.extdecl, +proc winchnstr*(a2: ptr WINDOW; a3: ptr cunsignedlong; a4: cint): cint{.extdecl, importc: "winchnstr", dynlib: pdcursesdll.} -proc winchstr*(a2: ptr TWINDOW; a3: ptr cunsignedlong): cint{.extdecl, +proc winchstr*(a2: ptr WINDOW; a3: ptr cunsignedlong): cint{.extdecl, importc: "winchstr", dynlib: pdcursesdll.} -proc winch*(a2: ptr TWINDOW): cunsignedlong{.extdecl, importc: "winch", +proc winch*(a2: ptr WINDOW): cunsignedlong{.extdecl, importc: "winch", dynlib: pdcursesdll.} -proc winnstr*(a2: ptr TWINDOW; a3: cstring; a4: cint): cint{.extdecl, +proc winnstr*(a2: ptr WINDOW; a3: cstring; a4: cint): cint{.extdecl, importc: "winnstr", dynlib: pdcursesdll.} -proc winsch*(a2: ptr TWINDOW; a3: cunsignedlong): cint{.extdecl, importc: "winsch", +proc winsch*(a2: ptr WINDOW; a3: cunsignedlong): cint{.extdecl, importc: "winsch", dynlib: pdcursesdll.} -proc winsdelln*(a2: ptr TWINDOW; a3: cint): cint{.extdecl, importc: "winsdelln", +proc winsdelln*(a2: ptr WINDOW; a3: cint): cint{.extdecl, importc: "winsdelln", dynlib: pdcursesdll.} -proc winsertln*(a2: ptr TWINDOW): cint{.extdecl, importc: "winsertln", +proc winsertln*(a2: ptr WINDOW): cint{.extdecl, importc: "winsertln", dynlib: pdcursesdll.} -proc winsnstr*(a2: ptr TWINDOW; a3: cstring; a4: cint): cint{.extdecl, +proc winsnstr*(a2: ptr WINDOW; a3: cstring; a4: cint): cint{.extdecl, importc: "winsnstr", dynlib: pdcursesdll.} -proc winsstr*(a2: ptr TWINDOW; a3: cstring): cint{.extdecl, importc: "winsstr", +proc winsstr*(a2: ptr WINDOW; a3: cstring): cint{.extdecl, importc: "winsstr", dynlib: pdcursesdll.} -proc winstr*(a2: ptr TWINDOW; a3: cstring): cint{.extdecl, importc: "winstr", +proc winstr*(a2: ptr WINDOW; a3: cstring): cint{.extdecl, importc: "winstr", dynlib: pdcursesdll.} -proc wmove*(a2: ptr TWINDOW; a3: cint; a4: cint): cint{.extdecl, importc: "wmove", +proc wmove*(a2: ptr WINDOW; a3: cint; a4: cint): cint{.extdecl, importc: "wmove", dynlib: pdcursesdll.} -proc wnoutrefresh*(a2: ptr TWINDOW): cint{.extdecl, importc: "wnoutrefresh", +proc wnoutrefresh*(a2: ptr WINDOW): cint{.extdecl, importc: "wnoutrefresh", dynlib: pdcursesdll.} -proc wprintw*(a2: ptr TWINDOW; a3: cstring): cint{.varargs, extdecl, +proc wprintw*(a2: ptr WINDOW; a3: cstring): cint{.varargs, extdecl, importc: "wprintw", dynlib: pdcursesdll.} -proc wredrawln*(a2: ptr TWINDOW; a3: cint; a4: cint): cint{.extdecl, +proc wredrawln*(a2: ptr WINDOW; a3: cint; a4: cint): cint{.extdecl, importc: "wredrawln", dynlib: pdcursesdll.} -proc wrefresh*(a2: ptr TWINDOW): cint{.extdecl, importc: "wrefresh", +proc wrefresh*(a2: ptr WINDOW): cint{.extdecl, importc: "wrefresh", dynlib: pdcursesdll.} -proc wscanw*(a2: ptr TWINDOW; a3: cstring): cint{.varargs, extdecl, +proc wscanw*(a2: ptr WINDOW; a3: cstring): cint{.varargs, extdecl, importc: "wscanw", dynlib: pdcursesdll.} -proc wscrl*(a2: ptr TWINDOW; a3: cint): cint{.extdecl, importc: "wscrl", +proc wscrl*(a2: ptr WINDOW; a3: cint): cint{.extdecl, importc: "wscrl", dynlib: pdcursesdll.} -proc wsetscrreg*(a2: ptr TWINDOW; a3: cint; a4: cint): cint{.extdecl, +proc wsetscrreg*(a2: ptr WINDOW; a3: cint; a4: cint): cint{.extdecl, importc: "wsetscrreg", dynlib: pdcursesdll.} -proc wstandend*(a2: ptr TWINDOW): cint{.extdecl, importc: "wstandend", +proc wstandend*(a2: ptr WINDOW): cint{.extdecl, importc: "wstandend", dynlib: pdcursesdll.} -proc wstandout*(a2: ptr TWINDOW): cint{.extdecl, importc: "wstandout", +proc wstandout*(a2: ptr WINDOW): cint{.extdecl, importc: "wstandout", dynlib: pdcursesdll.} -proc wsyncdown*(a2: ptr TWINDOW){.extdecl, importc: "wsyncdown", +proc wsyncdown*(a2: ptr WINDOW){.extdecl, importc: "wsyncdown", dynlib: pdcursesdll.} -proc wsyncup*(a2: ptr TWINDOW){.extdecl, importc: "wsyncup", dynlib: pdcursesdll.} -proc wtimeout*(a2: ptr TWINDOW; a3: cint){.extdecl, importc: "wtimeout", +proc wsyncup*(a2: ptr WINDOW){.extdecl, importc: "wsyncup", dynlib: pdcursesdll.} +proc wtimeout*(a2: ptr WINDOW; a3: cint){.extdecl, importc: "wtimeout", dynlib: pdcursesdll.} -proc wtouchln*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: cint): cint{.extdecl, +proc wtouchln*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cint): cint{.extdecl, importc: "wtouchln", dynlib: pdcursesdll.} -proc wvline*(a2: ptr TWINDOW; a3: cunsignedlong; a4: cint): cint{.extdecl, +proc wvline*(a2: ptr WINDOW; a3: cunsignedlong; a4: cint): cint{.extdecl, importc: "wvline", dynlib: pdcursesdll.} proc addnwstr*(a2: cstring; a3: cint): cint{.extdecl, importc: "addnwstr", dynlib: pdcursesdll.} @@ -1146,7 +1152,7 @@ proc border_set*(a2: ptr cunsignedlong; a3: ptr cunsignedlong; a6: ptr cunsignedlong; a7: ptr cunsignedlong; a8: ptr cunsignedlong; a9: ptr cunsignedlong): cint{.extdecl, importc: "border_set", dynlib: pdcursesdll.} -proc box_set*(a2: ptr TWINDOW; a3: ptr cunsignedlong; a4: ptr cunsignedlong): cint{. +proc box_set*(a2: ptr WINDOW; a3: ptr cunsignedlong; a4: ptr cunsignedlong): cint{. extdecl, importc: "box_set", dynlib: pdcursesdll.} proc echo_wchar*(a2: ptr cunsignedlong): cint{.extdecl, importc: "echo_wchar", dynlib: pdcursesdll.} @@ -1221,47 +1227,47 @@ proc mvin_wchstr*(a2: cint; a3: cint; a4: ptr cunsignedlong): cint{.extdecl, importc: "mvin_wchstr", dynlib: pdcursesdll.} proc mvvline_set*(a2: cint; a3: cint; a4: ptr cunsignedlong; a5: cint): cint{. extdecl, importc: "mvvline_set", dynlib: pdcursesdll.} -proc mvwaddnwstr*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: cstring; a6: cint): cint{. +proc mvwaddnwstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cstring; a6: cint): cint{. extdecl, importc: "mvwaddnwstr", dynlib: pdcursesdll.} -proc mvwaddwstr*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: cstring): cint{. +proc mvwaddwstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cstring): cint{. extdecl, importc: "mvwaddwstr", dynlib: pdcursesdll.} -proc mvwadd_wch*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong): cint{. +proc mvwadd_wch*(a2: ptr WINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong): cint{. extdecl, importc: "mvwadd_wch", dynlib: pdcursesdll.} -proc mvwadd_wchnstr*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong; +proc mvwadd_wchnstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong; a6: cint): cint{.extdecl, importc: "mvwadd_wchnstr", dynlib: pdcursesdll.} -proc mvwadd_wchstr*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong): cint{. +proc mvwadd_wchstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong): cint{. extdecl, importc: "mvwadd_wchstr", dynlib: pdcursesdll.} -proc mvwgetn_wstr*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: ptr cint; a6: cint): cint{. +proc mvwgetn_wstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: ptr cint; a6: cint): cint{. extdecl, importc: "mvwgetn_wstr", dynlib: pdcursesdll.} -proc mvwget_wch*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: ptr cint): cint{. +proc mvwget_wch*(a2: ptr WINDOW; a3: cint; a4: cint; a5: ptr cint): cint{. extdecl, importc: "mvwget_wch", dynlib: pdcursesdll.} -proc mvwget_wstr*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: ptr cint): cint{. +proc mvwget_wstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: ptr cint): cint{. extdecl, importc: "mvwget_wstr", dynlib: pdcursesdll.} -proc mvwhline_set*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong; +proc mvwhline_set*(a2: ptr WINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong; a6: cint): cint{.extdecl, importc: "mvwhline_set", dynlib: pdcursesdll.} -proc mvwinnwstr*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: cstring; a6: cint): cint{. +proc mvwinnwstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cstring; a6: cint): cint{. extdecl, importc: "mvwinnwstr", dynlib: pdcursesdll.} -proc mvwins_nwstr*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: cstring; a6: cint): cint{. +proc mvwins_nwstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cstring; a6: cint): cint{. extdecl, importc: "mvwins_nwstr", dynlib: pdcursesdll.} -proc mvwins_wch*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong): cint{. +proc mvwins_wch*(a2: ptr WINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong): cint{. extdecl, importc: "mvwins_wch", dynlib: pdcursesdll.} -proc mvwins_wstr*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: cstring): cint{. +proc mvwins_wstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cstring): cint{. extdecl, importc: "mvwins_wstr", dynlib: pdcursesdll.} -proc mvwin_wch*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong): cint{. +proc mvwin_wch*(a2: ptr WINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong): cint{. extdecl, importc: "mvwin_wch", dynlib: pdcursesdll.} -proc mvwin_wchnstr*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong; +proc mvwin_wchnstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong; a6: cint): cint{.extdecl, importc: "mvwin_wchnstr", dynlib: pdcursesdll.} -proc mvwin_wchstr*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong): cint{. +proc mvwin_wchstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong): cint{. extdecl, importc: "mvwin_wchstr", dynlib: pdcursesdll.} -proc mvwinwstr*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: cstring): cint{. +proc mvwinwstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cstring): cint{. extdecl, importc: "mvwinwstr", dynlib: pdcursesdll.} -proc mvwvline_set*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong; +proc mvwvline_set*(a2: ptr WINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong; a6: cint): cint{.extdecl, importc: "mvwvline_set", dynlib: pdcursesdll.} -proc pecho_wchar*(a2: ptr TWINDOW; a3: ptr cunsignedlong): cint{.extdecl, +proc pecho_wchar*(a2: ptr WINDOW; a3: ptr cunsignedlong): cint{.extdecl, importc: "pecho_wchar", dynlib: pdcursesdll.} proc setcchar*(a2: ptr cunsignedlong; a3: cstring; a4: cunsignedlong; a5: cshort; a6: pointer): cint{.extdecl, importc: "setcchar", @@ -1272,74 +1278,74 @@ proc unget_wch*(a2: char): cint{.extdecl, importc: "unget_wch", dynlib: pdcursesdll.} proc vline_set*(a2: ptr cunsignedlong; a3: cint): cint{.extdecl, importc: "vline_set", dynlib: pdcursesdll.} -proc waddnwstr*(a2: ptr TWINDOW; a3: cstring; a4: cint): cint{.extdecl, +proc waddnwstr*(a2: ptr WINDOW; a3: cstring; a4: cint): cint{.extdecl, importc: "waddnwstr", dynlib: pdcursesdll.} -proc waddwstr*(a2: ptr TWINDOW; a3: cstring): cint{.extdecl, +proc waddwstr*(a2: ptr WINDOW; a3: cstring): cint{.extdecl, importc: "waddwstr", dynlib: pdcursesdll.} -proc wadd_wch*(a2: ptr TWINDOW; a3: ptr cunsignedlong): cint{.extdecl, +proc wadd_wch*(a2: ptr WINDOW; a3: ptr cunsignedlong): cint{.extdecl, importc: "wadd_wch", dynlib: pdcursesdll.} -proc wadd_wchnstr*(a2: ptr TWINDOW; a3: ptr cunsignedlong; a4: cint): cint{. +proc wadd_wchnstr*(a2: ptr WINDOW; a3: ptr cunsignedlong; a4: cint): cint{. extdecl, importc: "wadd_wchnstr", dynlib: pdcursesdll.} -proc wadd_wchstr*(a2: ptr TWINDOW; a3: ptr cunsignedlong): cint{.extdecl, +proc wadd_wchstr*(a2: ptr WINDOW; a3: ptr cunsignedlong): cint{.extdecl, importc: "wadd_wchstr", dynlib: pdcursesdll.} -proc wbkgrnd*(a2: ptr TWINDOW; a3: ptr cunsignedlong): cint{.extdecl, +proc wbkgrnd*(a2: ptr WINDOW; a3: ptr cunsignedlong): cint{.extdecl, importc: "wbkgrnd", dynlib: pdcursesdll.} -proc wbkgrndset*(a2: ptr TWINDOW; a3: ptr cunsignedlong){.extdecl, +proc wbkgrndset*(a2: ptr WINDOW; a3: ptr cunsignedlong){.extdecl, importc: "wbkgrndset", dynlib: pdcursesdll.} -proc wborder_set*(a2: ptr TWINDOW; a3: ptr cunsignedlong; a4: ptr cunsignedlong; +proc wborder_set*(a2: ptr WINDOW; a3: ptr cunsignedlong; a4: ptr cunsignedlong; a5: ptr cunsignedlong; a6: ptr cunsignedlong; a7: ptr cunsignedlong; a8: ptr cunsignedlong; a9: ptr cunsignedlong; a10: ptr cunsignedlong): cint{.extdecl, importc: "wborder_set", dynlib: pdcursesdll.} -proc wecho_wchar*(a2: ptr TWINDOW; a3: ptr cunsignedlong): cint{.extdecl, +proc wecho_wchar*(a2: ptr WINDOW; a3: ptr cunsignedlong): cint{.extdecl, importc: "wecho_wchar", dynlib: pdcursesdll.} -proc wgetbkgrnd*(a2: ptr TWINDOW; a3: ptr cunsignedlong): cint{.extdecl, +proc wgetbkgrnd*(a2: ptr WINDOW; a3: ptr cunsignedlong): cint{.extdecl, importc: "wgetbkgrnd", dynlib: pdcursesdll.} -proc wgetn_wstr*(a2: ptr TWINDOW; a3: ptr cint; a4: cint): cint{.extdecl, +proc wgetn_wstr*(a2: ptr WINDOW; a3: ptr cint; a4: cint): cint{.extdecl, importc: "wgetn_wstr", dynlib: pdcursesdll.} -proc wget_wch*(a2: ptr TWINDOW; a3: ptr cint): cint{.extdecl, +proc wget_wch*(a2: ptr WINDOW; a3: ptr cint): cint{.extdecl, importc: "wget_wch", dynlib: pdcursesdll.} -proc wget_wstr*(a2: ptr TWINDOW; a3: ptr cint): cint{.extdecl, +proc wget_wstr*(a2: ptr WINDOW; a3: ptr cint): cint{.extdecl, importc: "wget_wstr", dynlib: pdcursesdll.} -proc whline_set*(a2: ptr TWINDOW; a3: ptr cunsignedlong; a4: cint): cint{.extdecl, +proc whline_set*(a2: ptr WINDOW; a3: ptr cunsignedlong; a4: cint): cint{.extdecl, importc: "whline_set", dynlib: pdcursesdll.} -proc winnwstr*(a2: ptr TWINDOW; a3: cstring; a4: cint): cint{.extdecl, +proc winnwstr*(a2: ptr WINDOW; a3: cstring; a4: cint): cint{.extdecl, importc: "winnwstr", dynlib: pdcursesdll.} -proc wins_nwstr*(a2: ptr TWINDOW; a3: cstring; a4: cint): cint{.extdecl, +proc wins_nwstr*(a2: ptr WINDOW; a3: cstring; a4: cint): cint{.extdecl, importc: "wins_nwstr", dynlib: pdcursesdll.} -proc wins_wch*(a2: ptr TWINDOW; a3: ptr cunsignedlong): cint{.extdecl, +proc wins_wch*(a2: ptr WINDOW; a3: ptr cunsignedlong): cint{.extdecl, importc: "wins_wch", dynlib: pdcursesdll.} -proc wins_wstr*(a2: ptr TWINDOW; a3: cstring): cint{.extdecl, +proc wins_wstr*(a2: ptr WINDOW; a3: cstring): cint{.extdecl, importc: "wins_wstr", dynlib: pdcursesdll.} -proc winwstr*(a2: ptr TWINDOW; a3: cstring): cint{.extdecl, importc: "winwstr", +proc winwstr*(a2: ptr WINDOW; a3: cstring): cint{.extdecl, importc: "winwstr", dynlib: pdcursesdll.} -proc win_wch*(a2: ptr TWINDOW; a3: ptr cunsignedlong): cint{.extdecl, +proc win_wch*(a2: ptr WINDOW; a3: ptr cunsignedlong): cint{.extdecl, importc: "win_wch", dynlib: pdcursesdll.} -proc win_wchnstr*(a2: ptr TWINDOW; a3: ptr cunsignedlong; a4: cint): cint{.extdecl, +proc win_wchnstr*(a2: ptr WINDOW; a3: ptr cunsignedlong; a4: cint): cint{.extdecl, importc: "win_wchnstr", dynlib: pdcursesdll.} -proc win_wchstr*(a2: ptr TWINDOW; a3: ptr cunsignedlong): cint{.extdecl, +proc win_wchstr*(a2: ptr WINDOW; a3: ptr cunsignedlong): cint{.extdecl, importc: "win_wchstr", dynlib: pdcursesdll.} proc wunctrl*(a2: ptr cunsignedlong): cstring{.extdecl, importc: "wunctrl", dynlib: pdcursesdll.} -proc wvline_set*(a2: ptr TWINDOW; a3: ptr cunsignedlong; a4: cint): cint{.extdecl, +proc wvline_set*(a2: ptr WINDOW; a3: ptr cunsignedlong; a4: cint): cint{.extdecl, importc: "wvline_set", dynlib: pdcursesdll.} -proc getattrs*(a2: ptr TWINDOW): cunsignedlong{.extdecl, importc: "getattrs", +proc getattrs*(a2: ptr WINDOW): cunsignedlong{.extdecl, importc: "getattrs", dynlib: pdcursesdll.} -proc getbegx*(a2: ptr TWINDOW): cint{.extdecl, importc: "getbegx", +proc getbegx*(a2: ptr WINDOW): cint{.extdecl, importc: "getbegx", dynlib: pdcursesdll.} -proc getbegy*(a2: ptr TWINDOW): cint{.extdecl, importc: "getbegy", +proc getbegy*(a2: ptr WINDOW): cint{.extdecl, importc: "getbegy", dynlib: pdcursesdll.} -proc getmaxx*(a2: ptr TWINDOW): cint{.extdecl, importc: "getmaxx", +proc getmaxx*(a2: ptr WINDOW): cint{.extdecl, importc: "getmaxx", dynlib: pdcursesdll.} -proc getmaxy*(a2: ptr TWINDOW): cint{.extdecl, importc: "getmaxy", +proc getmaxy*(a2: ptr WINDOW): cint{.extdecl, importc: "getmaxy", dynlib: pdcursesdll.} -proc getparx*(a2: ptr TWINDOW): cint{.extdecl, importc: "getparx", +proc getparx*(a2: ptr WINDOW): cint{.extdecl, importc: "getparx", dynlib: pdcursesdll.} -proc getpary*(a2: ptr TWINDOW): cint{.extdecl, importc: "getpary", +proc getpary*(a2: ptr WINDOW): cint{.extdecl, importc: "getpary", dynlib: pdcursesdll.} -proc getcurx*(a2: ptr TWINDOW): cint{.extdecl, importc: "getcurx", +proc getcurx*(a2: ptr WINDOW): cint{.extdecl, importc: "getcurx", dynlib: pdcursesdll.} -proc getcury*(a2: ptr TWINDOW): cint{.extdecl, importc: "getcury", +proc getcury*(a2: ptr WINDOW): cint{.extdecl, importc: "getcury", dynlib: pdcursesdll.} proc traceoff*(){.extdecl, importc: "traceoff", dynlib: pdcursesdll.} proc traceon*(){.extdecl, importc: "traceon", dynlib: pdcursesdll.} @@ -1363,7 +1369,7 @@ proc request_mouse_pos*(): cint{.extdecl, importc: "request_mouse_pos", dynlib: pdcursesdll.} proc map_button*(a2: cunsignedlong): cint{.extdecl, importc: "map_button", dynlib: pdcursesdll.} -proc wmouse_position*(a2: ptr TWINDOW; a3: ptr cint; a4: ptr cint){.extdecl, +proc wmouse_position*(a2: ptr WINDOW; a3: ptr cint; a4: ptr cint){.extdecl, importc: "wmouse_position", dynlib: pdcursesdll.} proc getmouse*(): cunsignedlong{.extdecl, importc: "getmouse", dynlib: pdcursesdll.} proc getbmap*(): cunsignedlong{.extdecl, importc: "getbmap", dynlib: pdcursesdll.} @@ -1375,7 +1381,7 @@ proc has_key*(a2: cint): cunsignedchar{.extdecl, importc: "has_key", dynlib: pdcursesdll.} proc use_default_colors*(): cint{.extdecl, importc: "use_default_colors", dynlib: pdcursesdll.} -proc wresize*(a2: ptr TWINDOW; a3: cint; a4: cint): cint{.extdecl, +proc wresize*(a2: ptr WINDOW; a3: cint; a4: cint): cint{.extdecl, importc: "wresize", dynlib: pdcursesdll.} proc mouseinterval*(a2: cint): cint{.extdecl, importc: "mouseinterval", dynlib: pdcursesdll.} @@ -1383,13 +1389,13 @@ proc mousemask*(a2: cunsignedlong; a3: ptr cunsignedlong): cunsignedlong{.extdec importc: "mousemask", dynlib: pdcursesdll.} proc mouse_trafo*(a2: ptr cint; a3: ptr cint; a4: cunsignedchar): cunsignedchar{. extdecl, importc: "mouse_trafo", dynlib: pdcursesdll.} -proc nc_getmouse*(a2: ptr TMEVENT): cint{.extdecl, importc: "nc_getmouse", +proc nc_getmouse*(a2: ptr MEVENT): cint{.extdecl, importc: "nc_getmouse", dynlib: pdcursesdll.} -proc ungetmouse*(a2: ptr TMEVENT): cint{.extdecl, importc: "ungetmouse", +proc ungetmouse*(a2: ptr MEVENT): cint{.extdecl, importc: "ungetmouse", dynlib: pdcursesdll.} -proc wenclose*(a2: ptr TWINDOW; a3: cint; a4: cint): cunsignedchar{.extdecl, +proc wenclose*(a2: ptr WINDOW; a3: cint; a4: cint): cunsignedchar{.extdecl, importc: "wenclose", dynlib: pdcursesdll.} -proc wmouse_trafo*(a2: ptr TWINDOW; a3: ptr cint; a4: ptr cint; a5: cunsignedchar): cunsignedchar{. +proc wmouse_trafo*(a2: ptr WINDOW; a3: ptr cint; a4: ptr cint; a5: cunsignedchar): cunsignedchar{. extdecl, importc: "wmouse_trafo", dynlib: pdcursesdll.} proc addrawch*(a2: cunsignedlong): cint{.extdecl, importc: "addrawch", dynlib: pdcursesdll.} @@ -1405,23 +1411,23 @@ proc mvinsertln*(a2: cint; a3: cint): cint{.extdecl, importc: "mvinsertln", dynlib: pdcursesdll.} proc mvinsrawch*(a2: cint; a3: cint; a4: cunsignedlong): cint{.extdecl, importc: "mvinsrawch", dynlib: pdcursesdll.} -proc mvwaddrawch*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: cunsignedlong): cint{. +proc mvwaddrawch*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cunsignedlong): cint{. extdecl, importc: "mvwaddrawch", dynlib: pdcursesdll.} -proc mvwdeleteln*(a2: ptr TWINDOW; a3: cint; a4: cint): cint{.extdecl, +proc mvwdeleteln*(a2: ptr WINDOW; a3: cint; a4: cint): cint{.extdecl, importc: "mvwdeleteln", dynlib: pdcursesdll.} -proc mvwinsertln*(a2: ptr TWINDOW; a3: cint; a4: cint): cint{.extdecl, +proc mvwinsertln*(a2: ptr WINDOW; a3: cint; a4: cint): cint{.extdecl, importc: "mvwinsertln", dynlib: pdcursesdll.} -proc mvwinsrawch*(a2: ptr TWINDOW; a3: cint; a4: cint; a5: cunsignedlong): cint{. +proc mvwinsrawch*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cunsignedlong): cint{. extdecl, importc: "mvwinsrawch", dynlib: pdcursesdll.} proc raw_output*(a2: cunsignedchar): cint{.extdecl, importc: "raw_output", dynlib: pdcursesdll.} proc resize_term*(a2: cint; a3: cint): cint{.extdecl, importc: "resize_term", dynlib: pdcursesdll.} -proc resize_window*(a2: ptr TWINDOW; a3: cint; a4: cint): ptr TWINDOW{.extdecl, +proc resize_window*(a2: ptr WINDOW; a3: cint; a4: cint): ptr WINDOW{.extdecl, importc: "resize_window", dynlib: pdcursesdll.} -proc waddrawch*(a2: ptr TWINDOW; a3: cunsignedlong): cint{.extdecl, +proc waddrawch*(a2: ptr WINDOW; a3: cunsignedlong): cint{.extdecl, importc: "waddrawch", dynlib: pdcursesdll.} -proc winsrawch*(a2: ptr TWINDOW; a3: cunsignedlong): cint{.extdecl, +proc winsrawch*(a2: ptr WINDOW; a3: cunsignedlong): cint{.extdecl, importc: "winsrawch", dynlib: pdcursesdll.} proc wordchar*(): char{.extdecl, importc: "wordchar", dynlib: pdcursesdll.} proc slk_wlabel*(a2: cint): cstring{.extdecl, importc: "slk_wlabel", @@ -1452,38 +1458,38 @@ proc return_key_modifiers*(a2: cunsignedchar): cint{.extdecl, importc: "PDC_return_key_modifiers", dynlib: pdcursesdll.} proc save_key_modifiers*(a2: cunsignedchar): cint{.extdecl, importc: "PDC_save_key_modifiers", dynlib: pdcursesdll.} -proc bottom_panel*(pan: ptr TPANEL): cint{.extdecl, importc: "bottom_panel", +proc bottom_panel*(pan: ptr PANEL): cint{.extdecl, importc: "bottom_panel", dynlib: pdcursesdll.} -proc del_panel*(pan: ptr TPANEL): cint{.extdecl, importc: "del_panel", +proc del_panel*(pan: ptr PANEL): cint{.extdecl, importc: "del_panel", dynlib: pdcursesdll.} -proc hide_panel*(pan: ptr TPANEL): cint{.extdecl, importc: "hide_panel", +proc hide_panel*(pan: ptr PANEL): cint{.extdecl, importc: "hide_panel", dynlib: pdcursesdll.} -proc move_panel*(pan: ptr TPANEL; starty: cint; startx: cint): cint{.extdecl, +proc move_panel*(pan: ptr PANEL; starty: cint; startx: cint): cint{.extdecl, importc: "move_panel", dynlib: pdcursesdll.} -proc new_panel*(win: ptr TWINDOW): ptr TPANEL{.extdecl, importc: "new_panel", +proc new_panel*(win: ptr WINDOW): ptr PANEL{.extdecl, importc: "new_panel", dynlib: pdcursesdll.} -proc panel_above*(pan: ptr TPANEL): ptr TPANEL{.extdecl, importc: "panel_above", +proc panel_above*(pan: ptr PANEL): ptr PANEL{.extdecl, importc: "panel_above", dynlib: pdcursesdll.} -proc panel_below*(pan: ptr TPANEL): ptr TPANEL{.extdecl, importc: "panel_below", +proc panel_below*(pan: ptr PANEL): ptr PANEL{.extdecl, importc: "panel_below", dynlib: pdcursesdll.} -proc panel_hidden*(pan: ptr TPANEL): cint{.extdecl, importc: "panel_hidden", +proc panel_hidden*(pan: ptr PANEL): cint{.extdecl, importc: "panel_hidden", dynlib: pdcursesdll.} -proc panel_userptr*(pan: ptr TPANEL): pointer{.extdecl, importc: "panel_userptr", +proc panel_userptr*(pan: ptr PANEL): pointer{.extdecl, importc: "panel_userptr", dynlib: pdcursesdll.} -proc panel_window*(pan: ptr TPANEL): ptr TWINDOW{.extdecl, importc: "panel_window", +proc panel_window*(pan: ptr PANEL): ptr WINDOW{.extdecl, importc: "panel_window", dynlib: pdcursesdll.} -proc replace_panel*(pan: ptr TPANEL; win: ptr TWINDOW): cint{.extdecl, +proc replace_panel*(pan: ptr PANEL; win: ptr WINDOW): cint{.extdecl, importc: "replace_panel", dynlib: pdcursesdll.} -proc set_panel_userptr*(pan: ptr TPANEL; uptr: pointer): cint{.extdecl, +proc set_panel_userptr*(pan: ptr PANEL; uptr: pointer): cint{.extdecl, importc: "set_panel_userptr", dynlib: pdcursesdll.} -proc show_panel*(pan: ptr TPANEL): cint{.extdecl, importc: "show_panel", +proc show_panel*(pan: ptr PANEL): cint{.extdecl, importc: "show_panel", dynlib: pdcursesdll.} -proc top_panel*(pan: ptr TPANEL): cint{.extdecl, importc: "top_panel", +proc top_panel*(pan: ptr PANEL): cint{.extdecl, importc: "top_panel", dynlib: pdcursesdll.} proc update_panels*(){.extdecl, importc: "update_panels", dynlib: pdcursesdll.} when unixOS: - proc Xinitscr*(a2: cint; a3: cstringArray): ptr TWINDOW{.extdecl, + proc Xinitscr*(a2: cint; a3: cstringArray): ptr WINDOW{.extdecl, importc: "Xinitscr", dynlib: pdcursesdll.} proc XCursesExit*(){.extdecl, importc: "XCursesExit", dynlib: pdcursesdll.} proc sb_init*(): cint{.extdecl, importc: "sb_init", dynlib: pdcursesdll.} @@ -1536,4 +1542,4 @@ when defined(windows): quick_edit*{.importc: "pdc_quick_edit", dynlib: pdcursesdll.}: DWORD proc get_buffer_rows*(): cint{.extdecl, importc: "PDC_get_buffer_rows", - dynlib: pdcursesdll.} \ No newline at end of file + dynlib: pdcursesdll.} diff --git a/lib/wrappers/postgres.nim b/lib/wrappers/postgres.nim index cb39c41bb..3c35bc590 100644 --- a/lib/wrappers/postgres.nim +++ b/lib/wrappers/postgres.nim @@ -26,25 +26,25 @@ const CMDSTATUS_LEN* = 40 type - TSockAddr* = array[1..112, int8] - TPGresAttDesc*{.pure, final.} = object + SockAddr* = array[1..112, int8] + PGresAttDesc*{.pure, final.} = object name*: cstring adtid*: Oid adtsize*: int - PPGresAttDesc* = ptr TPGresAttDesc + PPGresAttDesc* = ptr PGresAttDesc PPPGresAttDesc* = ptr PPGresAttDesc - TPGresAttValue*{.pure, final.} = object + PGresAttValue*{.pure, final.} = object length*: int32 value*: cstring - PPGresAttValue* = ptr TPGresAttValue + PPGresAttValue* = ptr PGresAttValue PPPGresAttValue* = ptr PPGresAttValue - PExecStatusType* = ptr TExecStatusType - TExecStatusType* = enum + PExecStatusType* = ptr ExecStatusType + ExecStatusType* = enum PGRES_EMPTY_QUERY = 0, PGRES_COMMAND_OK, PGRES_TUPLES_OK, PGRES_COPY_OUT, PGRES_COPY_IN, PGRES_BAD_RESPONSE, PGRES_NONFATAL_ERROR, PGRES_FATAL_ERROR - TPGlobjfuncs*{.pure, final.} = object + PGlobjfuncs*{.pure, final.} = object fn_lo_open*: Oid fn_lo_close*: Oid fn_lo_creat*: Oid @@ -54,26 +54,26 @@ type fn_lo_read*: Oid fn_lo_write*: Oid - PPGlobjfuncs* = ptr TPGlobjfuncs - PConnStatusType* = ptr TConnStatusType - TConnStatusType* = enum + PPGlobjfuncs* = ptr PGlobjfuncs + PConnStatusType* = ptr ConnStatusType + ConnStatusType* = enum CONNECTION_OK, CONNECTION_BAD, CONNECTION_STARTED, CONNECTION_MADE, CONNECTION_AWAITING_RESPONSE, CONNECTION_AUTH_OK, CONNECTION_SETENV, CONNECTION_SSL_STARTUP, CONNECTION_NEEDED - TPGconn*{.pure, final.} = object + PGconn*{.pure, final.} = object pghost*: cstring pgtty*: cstring pgport*: cstring pgoptions*: cstring dbName*: cstring - status*: TConnStatusType + status*: ConnStatusType errorMessage*: array[0..(ERROR_MSG_LENGTH) - 1, char] Pfin*: File Pfout*: File Pfdebug*: File sock*: int32 - laddr*: TSockAddr - raddr*: TSockAddr + laddr*: SockAddr + raddr*: SockAddr salt*: array[0..(2) - 1, char] asyncNotifyWaiting*: int32 notifyList*: pointer @@ -81,19 +81,19 @@ type pgpass*: cstring lobjfuncs*: PPGlobjfuncs - PPGconn* = ptr TPGconn - TPGresult*{.pure, final.} = object + PPGconn* = ptr PGconn + PGresult*{.pure, final.} = object ntups*: int32 numAttributes*: int32 attDescs*: PPGresAttDesc tuples*: PPPGresAttValue tupArrSize*: int32 - resultStatus*: TExecStatusType + resultStatus*: ExecStatusType cmdStatus*: array[0..(CMDSTATUS_LEN) - 1, char] binary*: int32 conn*: PPGconn - PPGresult* = ptr TPGresult + PPGresult* = ptr PGresult PPostgresPollingStatusType* = ptr PostgresPollingStatusType PostgresPollingStatusType* = enum PGRES_POLLING_FAILED = 0, PGRES_POLLING_READING, PGRES_POLLING_WRITING, @@ -143,7 +143,10 @@ type length*: int32 isint*: int32 p*: pointer - +{.deprecated: [TSockAddr: SockAddr, TPGresAttDesc: PgresAttDesc, + TPGresAttValue: PgresAttValue, TExecStatusType: ExecStatusType, + TPGlobjfuncs: Pglobjfuncs, TConnStatusType: ConnStatusType, TPGconn: Pgconn, + TPGresult: PGresult].} proc pqconnectStart*(conninfo: cstring): PPGconn{.cdecl, dynlib: dllName, importc: "PQconnectStart".} @@ -175,7 +178,7 @@ proc pqport*(conn: PPGconn): cstring{.cdecl, dynlib: dllName, importc: "PQport". proc pqtty*(conn: PPGconn): cstring{.cdecl, dynlib: dllName, importc: "PQtty".} proc pqoptions*(conn: PPGconn): cstring{.cdecl, dynlib: dllName, importc: "PQoptions".} -proc pqstatus*(conn: PPGconn): TConnStatusType{.cdecl, dynlib: dllName, +proc pqstatus*(conn: PPGconn): ConnStatusType{.cdecl, dynlib: dllName, importc: "PQstatus".} proc pqtransactionStatus*(conn: PPGconn): PGTransactionStatusType{.cdecl, dynlib: dllName, importc: "PQtransactionStatus".} @@ -263,9 +266,9 @@ proc pqflush*(conn: PPGconn): int32{.cdecl, dynlib: dllName, importc: "PQflush". proc pqfn*(conn: PPGconn, fnid: int32, result_buf, result_len: ptr int32, result_is_int: int32, args: PPQArgBlock, nargs: int32): PPGresult{. cdecl, dynlib: dllName, importc: "PQfn".} -proc pqresultStatus*(res: PPGresult): TExecStatusType{.cdecl, dynlib: dllName, +proc pqresultStatus*(res: PPGresult): ExecStatusType{.cdecl, dynlib: dllName, importc: "PQresultStatus".} -proc pqresStatus*(status: TExecStatusType): cstring{.cdecl, dynlib: dllName, +proc pqresStatus*(status: ExecStatusType): cstring{.cdecl, dynlib: dllName, importc: "PQresStatus".} proc pqresultErrorMessage*(res: PPGresult): cstring{.cdecl, dynlib: dllName, importc: "PQresultErrorMessage".} @@ -309,7 +312,7 @@ proc pqgetisnull*(res: PPGresult, tup_num: int32, field_num: int32): int32{. cdecl, dynlib: dllName, importc: "PQgetisnull".} proc pqclear*(res: PPGresult){.cdecl, dynlib: dllName, importc: "PQclear".} proc pqfreemem*(p: pointer){.cdecl, dynlib: dllName, importc: "PQfreemem".} -proc pqmakeEmptyPGresult*(conn: PPGconn, status: TExecStatusType): PPGresult{. +proc pqmakeEmptyPGresult*(conn: PPGconn, status: ExecStatusType): PPGresult{. cdecl, dynlib: dllName, importc: "PQmakeEmptyPGresult".} proc pqescapeString*(till, `from`: cstring, len: int): int{.cdecl, dynlib: dllName, importc: "PQescapeString".} diff --git a/lib/wrappers/readline/history.nim b/lib/wrappers/readline/history.nim index 495bc15e4..610c76a62 100644 --- a/lib/wrappers/readline/history.nim +++ b/lib/wrappers/readline/history.nim @@ -28,16 +28,17 @@ const import times, rltypedefs type - Thistdata* = pointer + Histdata* = pointer +{.deprecated: [Thistdata: Histdata].} # The structure used to store a history entry. type - THIST_ENTRY*{.pure, final.} = object + HIST_ENTRY*{.pure, final.} = object line*: cstring timestamp*: cstring # char * rather than time_t for read/write - data*: Thistdata - + data*: Histdata +{.deprecated: [THIST_ENTRY: HIST_ENTRY].} # Size of the history-library-managed space in history entry HS. @@ -47,12 +48,13 @@ template HISTENT_BYTES*(hs: expr): expr = # A structure used to pass the current state of the history stuff around. type - THISTORY_STATE*{.pure, final.} = object - entries*: ptr ptr THIST_ENTRY # Pointer to the entries themselves. + HISTORY_STATE*{.pure, final.} = object + entries*: ptr ptr HIST_ENTRY # Pointer to the entries themselves. offset*: cint # The location pointer within this array. length*: cint # Number of elements within this array. size*: cint # Number of slots allocated to this array. flags*: cint +{.deprecated: [THISTORY_STATE: HISTORY_STATE].} # Flag values for the `flags' member of HISTORY_STATE. @@ -67,11 +69,11 @@ const proc using_history*(){.cdecl, importc: "using_history", dynlib: historyDll.} # Return the current HISTORY_STATE of the history. -proc history_get_history_state*(): ptr THISTORY_STATE{.cdecl, +proc history_get_history_state*(): ptr HISTORY_STATE{.cdecl, importc: "history_get_history_state", dynlib: historyDll.} # Set the state of the current history array to STATE. -proc history_set_history_state*(a2: ptr THISTORY_STATE){.cdecl, +proc history_set_history_state*(a2: ptr HISTORY_STATE){.cdecl, importc: "history_set_history_state", dynlib: historyDll.} # Manage the history list. # Place STRING at the end of the history list. @@ -88,18 +90,18 @@ proc add_history_time*(a2: cstring){.cdecl, importc: "add_history_time", # is the magic number that tells us which element to delete. The # elements are numbered from 0. -proc remove_history*(a2: cint): ptr THIST_ENTRY{.cdecl, +proc remove_history*(a2: cint): ptr HIST_ENTRY{.cdecl, importc: "remove_history", dynlib: historyDll.} # Free the history entry H and return any application-specific data # associated with it. -proc free_history_entry*(a2: ptr THIST_ENTRY): Thistdata{.cdecl, +proc free_history_entry*(a2: ptr HIST_ENTRY): Histdata{.cdecl, importc: "free_history_entry", dynlib: historyDll.} # Make the history entry at WHICH have LINE and DATA. This returns # the old entry so you can dispose of the data. In the case of an # invalid WHICH, a NULL pointer is returned. -proc replace_history_entry*(a2: cint, a3: cstring, a4: Thistdata): ptr THIST_ENTRY{. +proc replace_history_entry*(a2: cint, a3: cstring, a4: Histdata): ptr HIST_ENTRY{. cdecl, importc: "replace_history_entry", dynlib: historyDll.} # Clear the history list and start over. @@ -123,7 +125,7 @@ proc history_is_stifled*(): cint{.cdecl, importc: "history_is_stifled", # history. Element 0 of this list is the beginning of time. If there # is no history, return NULL. -proc history_list*(): ptr ptr THIST_ENTRY{.cdecl, importc: "history_list", +proc history_list*(): ptr ptr HIST_ENTRY{.cdecl, importc: "history_list", dynlib: historyDll.} # Returns the number which says what history element we are now # looking at. @@ -132,17 +134,17 @@ proc where_history*(): cint{.cdecl, importc: "where_history", dynlib: historyDll # Return the history entry at the current position, as determined by # history_offset. If there is no entry there, return a NULL pointer. -proc current_history*(): ptr THIST_ENTRY{.cdecl, importc: "current_history", +proc current_history*(): ptr HIST_ENTRY{.cdecl, importc: "current_history", dynlib: historyDll.} # Return the history entry which is logically at OFFSET in the history # array. OFFSET is relative to history_base. -proc history_get*(a2: cint): ptr THIST_ENTRY{.cdecl, importc: "history_get", +proc history_get*(a2: cint): ptr HIST_ENTRY{.cdecl, importc: "history_get", dynlib: historyDll.} # Return the timestamp associated with the HIST_ENTRY * passed as an # argument -proc history_get_time*(a2: ptr THIST_ENTRY): Time{.cdecl, +proc history_get_time*(a2: ptr HIST_ENTRY): Time{.cdecl, importc: "history_get_time", dynlib: historyDll.} # Return the number of bytes that the primary history entries are using. # This just adds up the lengths of the_history->lines. @@ -158,13 +160,13 @@ proc history_set_pos*(a2: cint): cint{.cdecl, importc: "history_set_pos", # a pointer to that entry. If there is no previous entry, return # a NULL pointer. -proc previous_history*(): ptr THIST_ENTRY{.cdecl, importc: "previous_history", +proc previous_history*(): ptr HIST_ENTRY{.cdecl, importc: "previous_history", dynlib: historyDll.} # Move history_offset forward to the next item in the input_history, # and return the a pointer to that entry. If there is no next entry, # return a NULL pointer. -proc next_history*(): ptr THIST_ENTRY{.cdecl, importc: "next_history", +proc next_history*(): ptr HIST_ENTRY{.cdecl, importc: "next_history", dynlib: historyDll.} # Searching the history list. # Search the history for STRING, starting at history_offset. diff --git a/lib/wrappers/readline/readline.nim b/lib/wrappers/readline/readline.nim index 5a319243e..4173a0e0f 100644 --- a/lib/wrappers/readline/readline.nim +++ b/lib/wrappers/readline/readline.nim @@ -78,9 +78,10 @@ const # TYPE says which kind of thing FUNCTION is. type - TKEYMAP_ENTRY*{.pure, final.} = object + KEYMAP_ENTRY*{.pure, final.} = object typ*: char function*: TCommandFunc +{.deprecated: [TKEYMAP_ENTRY: KEYMAP_ENTRY].} # This must be large enough to hold bindings for all of the characters @@ -97,8 +98,9 @@ const # Maybe I need C lessons. type - TKEYMAP_ENTRY_ARRAY* = array[0..KEYMAP_SIZE - 1, TKEYMAP_ENTRY] - PKeymap* = ptr TKEYMAP_ENTRY + KEYMAP_ENTRY_ARRAY* = array[0..KEYMAP_SIZE - 1, KEYMAP_ENTRY] + PKeymap* = ptr KEYMAP_ENTRY +{.deprecated: [TKEYMAP_ENTRY_ARRAY: KEYMAP_ENTRY_ARRAY].} # The values that TYPE can have in a keymap entry. @@ -110,12 +112,12 @@ const when false: var emacs_standard_keymap*{.importc: "emacs_standard_keymap", - dynlib: readlineDll.}: TKEYMAP_ENTRY_ARRAY - emacs_meta_keymap*{.importc: "emacs_meta_keymap", dynlib: readlineDll.}: TKEYMAP_ENTRY_ARRAY - emacs_ctlx_keymap*{.importc: "emacs_ctlx_keymap", dynlib: readlineDll.}: TKEYMAP_ENTRY_ARRAY + dynlib: readlineDll.}: KEYMAP_ENTRY_ARRAY + emacs_meta_keymap*{.importc: "emacs_meta_keymap", dynlib: readlineDll.}: KEYMAP_ENTRY_ARRAY + emacs_ctlx_keymap*{.importc: "emacs_ctlx_keymap", dynlib: readlineDll.}: KEYMAP_ENTRY_ARRAY var - vi_insertion_keymap*{.importc: "vi_insertion_keymap", dynlib: readlineDll.}: TKEYMAP_ENTRY_ARRAY - vi_movement_keymap*{.importc: "vi_movement_keymap", dynlib: readlineDll.}: TKEYMAP_ENTRY_ARRAY + vi_insertion_keymap*{.importc: "vi_insertion_keymap", dynlib: readlineDll.}: KEYMAP_ENTRY_ARRAY + vi_movement_keymap*{.importc: "vi_movement_keymap", dynlib: readlineDll.}: KEYMAP_ENTRY_ARRAY # Return a new, empty keymap. # Free it with free() when you are done. @@ -154,7 +156,8 @@ const tildeDll = readlineDll type - Thook_func* = proc (a2: cstring): cstring{.cdecl.} + Hook_func* = proc (a2: cstring): cstring{.cdecl.} +{.deprecated: [Thook_func: Hook_func].} when not defined(macosx): # If non-null, this contains the address of a function that the application @@ -163,7 +166,7 @@ when not defined(macosx): # which is the expansion, or a NULL pointer if the expansion fails. var expansion_preexpansion_hook*{.importc: "tilde_expansion_preexpansion_hook", - dynlib: tildeDll.}: Thook_func + dynlib: tildeDll.}: Hook_func # If non-null, this contains the address of a function to call if the # standard meaning for expanding a tilde fails. The function is called @@ -171,7 +174,7 @@ when not defined(macosx): # which is the expansion, or a NULL pointer if there is no expansion. var expansion_failure_hook*{.importc: "tilde_expansion_failure_hook", - dynlib: tildeDll.}: Thook_func + dynlib: tildeDll.}: Hook_func # When non-null, this is a NULL terminated array of strings which # are duplicates for a tilde prefix. Bash uses this to expand @@ -214,35 +217,38 @@ const # the code tells undo what to undo, not how to undo it. type - Tundo_code* = enum + Undo_code* = enum UNDO_DELETE, UNDO_INSERT, UNDO_BEGIN, UNDO_END +{.deprecated: [Tundo_code: Undo_code].} # What an element of THE_UNDO_LIST looks like. type - TUNDO_LIST*{.pure, final.} = object - next*: ptr Tundo_list + UNDO_LIST*{.pure, final.} = object + next*: ptr UNDO_LIST start*: cint theEnd*: cint # Where the change took place. text*: cstring # The text to insert, if undoing a delete. - what*: Tundo_code # Delete, Insert, Begin, End. + what*: Undo_code # Delete, Insert, Begin, End. +{.deprecated: [TUNDO_LIST: UNDO_LIST].} # The current undo list for RL_LINE_BUFFER. when not defined(macosx): - var undo_list*{.importc: "rl_undo_list", dynlib: readlineDll.}: ptr TUNDO_LIST + var undo_list*{.importc: "rl_undo_list", dynlib: readlineDll.}: ptr UNDO_LIST # The data structure for mapping textual names to code addresses. type - TFUNMAP*{.pure, final.} = object + FUNMAP*{.pure, final.} = object name*: cstring function*: TCommandFunc +{.deprecated: [TFUNMAP: FUNMAP].} when not defined(macosx): - var funmap*{.importc: "funmap", dynlib: readlineDll.}: ptr ptr TFUNMAP + var funmap*{.importc: "funmap", dynlib: readlineDll.}: ptr ptr FUNMAP # **************************************************************** # @@ -697,7 +703,7 @@ proc push_macro_input*(a2: cstring){.cdecl, importc: "rl_push_macro_input", dynlib: readlineDll.} # Functions for undoing, from undo.c -proc add_undo*(a2: Tundo_code, a3: cint, a4: cint, a5: cstring){.cdecl, +proc add_undo*(a2: Undo_code, a3: cint, a4: cint, a5: cstring){.cdecl, importc: "rl_add_undo", dynlib: readlineDll.} proc free_undo_list*(){.cdecl, importc: "rl_free_undo_list", dynlib: readlineDll.} proc do_undo*(): cint{.cdecl, importc: "rl_do_undo", dynlib: readlineDll.} @@ -816,7 +822,7 @@ proc complete_internal*(a2: cint): cint{.cdecl, importc: "rl_complete_internal", dynlib: readlineDll.} proc display_match_list*(a2: cstringArray, a3: cint, a4: cint){.cdecl, importc: "rl_display_match_list", dynlib: readlineDll.} -proc completion_matches*(a2: cstring, a3: Tcompentry_func): cstringArray{. +proc completion_matches*(a2: cstring, a3: Compentry_func): cstringArray{. cdecl, importc: "rl_completion_matches", dynlib: readlineDll.} proc username_completion_function*(a2: cstring, a3: cint): cstring{.cdecl, importc: "rl_username_completion_function", dynlib: readlineDll.} @@ -1169,13 +1175,13 @@ template ISSTATE*(x: expr): expr = (readline_state and x) != 0 type - Treadline_state*{.pure, final.} = object + Readline_state*{.pure, final.} = object point*: cint # line state theEnd*: cint mark*: cint buffer*: cstring buflen*: cint - ul*: ptr TUNDO_LIST + ul*: ptr UNDO_LIST prompt*: cstring # global state rlstate*: cint done*: cint @@ -1194,9 +1200,10 @@ type # options state # reserved for future expansion, so the struct size doesn't change reserved*: array[0..64 - 1, char] +{.deprecated: [Treadline_state: Readline_state].} -proc save_state*(a2: ptr Treadline_state): cint{.cdecl, +proc save_state*(a2: ptr Readline_state): cint{.cdecl, importc: "rl_save_state", dynlib: readlineDll.} -proc restore_state*(a2: ptr Treadline_state): cint{.cdecl, +proc restore_state*(a2: ptr Readline_state): cint{.cdecl, importc: "rl_restore_state", dynlib: readlineDll.} diff --git a/lib/wrappers/readline/rltypedefs.nim b/lib/wrappers/readline/rltypedefs.nim index 847834e80..759b81297 100644 --- a/lib/wrappers/readline/rltypedefs.nim +++ b/lib/wrappers/readline/rltypedefs.nim @@ -19,27 +19,32 @@ # type - TFunction* = proc (): cint{.cdecl.} - TVFunction* = proc (){.cdecl.} - TCPFunction* = proc (): cstring{.cdecl.} - TCPPFunction* = proc (): cstringArray{.cdecl.} + Function* = proc (): cint{.cdecl.} + VFunction* = proc (){.cdecl.} + CPFunction* = proc (): cstring{.cdecl.} + CPPFunction* = proc (): cstringArray{.cdecl.} +{.deprecated: [TFunction: Function, TVFunction: VFunction, + TCPFunction: CPFunction, TCPPFunction: CPPFunction].} # Bindable functions type - Tcommand_func* = proc (a2: cint, a3: cint): cint{.cdecl.} + Command_func* = proc (a2: cint, a3: cint): cint{.cdecl.} +{.deprecated: [Tcommand_func: Command_func].} # Typedefs for the completion system type - Tcompentry_func* = proc (a2: cstring, a3: cint): cstring{.cdecl.} - Tcompletion_func* = proc (a2: cstring, a3: cint, a4: cint): cstringArray{. + Compentry_func* = proc (a2: cstring, a3: cint): cstring{.cdecl.} + Completion_func* = proc (a2: cstring, a3: cint, a4: cint): cstringArray{. cdecl.} - Tquote_func* = proc (a2: cstring, a3: cint, a4: cstring): cstring{.cdecl.} - Tdequote_func* = proc (a2: cstring, a3: cint): cstring{.cdecl.} - Tcompignore_func* = proc (a2: cstringArray): cint{.cdecl.} - Tcompdisp_func* = proc (a2: cstringArray, a3: cint, a4: cint){.cdecl.} - + Quote_func* = proc (a2: cstring, a3: cint, a4: cstring): cstring{.cdecl.} + Dequote_func* = proc (a2: cstring, a3: cint): cstring{.cdecl.} + Compignore_func* = proc (a2: cstringArray): cint{.cdecl.} + Compdisp_func* = proc (a2: cstringArray, a3: cint, a4: cint){.cdecl.} +{.deprecated: [Tcompentry_func: Compentry_func,Tcompletion_func: Completion_func, + Tquote_func: Quote_func, Tdequote_func: Dequote_func, + Tcompignore_func: Compignore_func, Tcompdisp_func: Compdisp_func].} # Type for input and pre-read hook functions like rl_event_hook type From cbd8da93f4eebf07df35866c0987eff4cdcd7d6a Mon Sep 17 00:00:00 2001 From: pdw Date: Sun, 24 May 2015 22:50:19 -0500 Subject: [PATCH 0357/1263] lib/wrappers/s-z - Dropped 'T' from types --- lib/wrappers/sdl/sdl.nim | 443 ++++++++++++++----------- lib/wrappers/sdl/sdl_gfx.nim | 14 +- lib/wrappers/sdl/sdl_image.nim | 4 +- lib/wrappers/sdl/sdl_mixer.nim | 71 ++-- lib/wrappers/sdl/sdl_mixer_nosmpeg.nim | 70 ++-- lib/wrappers/sdl/sdl_net.nim | 60 ++-- lib/wrappers/sdl/sdl_ttf.nim | 37 ++- lib/wrappers/sdl/smpeg.nim | 29 +- lib/wrappers/sphinx.nim | 104 +++--- lib/wrappers/sqlite3.nim | 64 ++-- lib/wrappers/tinyc.nim | 9 +- lib/wrappers/tre.nim | 44 +-- lib/wrappers/zip/libzip.nim | 28 +- lib/wrappers/zip/zlib.nim | 76 ++--- lib/wrappers/zip/zzip.nim | 100 +++--- 15 files changed, 613 insertions(+), 540 deletions(-) diff --git a/lib/wrappers/sdl/sdl.nim b/lib/wrappers/sdl/sdl.nim index 5bb5b7ec2..707c65a53 100644 --- a/lib/wrappers/sdl/sdl.nim +++ b/lib/wrappers/sdl/sdl.nim @@ -346,7 +346,7 @@ const HAT_LEFTDOWN* = HAT_LEFT or HAT_DOWN # SDL_events.h constants type - TEventKind* = enum # kind of an SDL event + EventKind* = enum # kind of an SDL event NOEVENT = 0, # Unused (do not remove) ACTIVEEVENT = 1, # Application loses/gains visibility KEYDOWN = 2, # Keys pressed @@ -374,6 +374,7 @@ type # Events SDL_USEREVENT through SDL_MAXEVENTS-1 are for your use USEREVENT = 24 # This last event is only for bounding internal arrays # It is the number of bits in the event mask datatype -- int32 +{.deprecated: [TEventKind: EventKind].} const NUMEVENTS* = 32 @@ -750,12 +751,12 @@ const # Enumeration of valid key mods (possibly OR'd tog GRAB_ON* = 1 #SDL_GRAB_FULLSCREEN // Used internally type - THandle* = int #SDL_types.h types + Handle* = int #SDL_types.h types # Basic data types - TBool* = enum + Bool* = enum sdlFALSE, sdlTRUE - PUInt8Array* = ptr TUInt8Array - TUInt8Array* = array[0..high(int) shr 1, byte] + PUInt8Array* = ptr UInt8Array + UInt8Array* = array[0..high(int) shr 1, byte] PUInt16* = ptr uint16 PUInt32* = ptr uint32 PUInt64* = ptr UInt64 @@ -768,15 +769,14 @@ type hi*: int32 lo*: int32 - TGrabMode* = int32 # SDL_error.h types - Terrorcode* = enum + GrabMode* = int32 # SDL_error.h types + ErrorCode* = enum ENOMEM, EFREAD, EFWRITE, EFSEEK, LASTERROR - Errorcode* = Terrorcode - TArg*{.final.} = object + Arg*{.final.} = object buf*: array[0..ERR_MAX_STRLEN - 1, int8] Perror* = ptr Terror - TError*{.final.} = object # This is a numeric value corresponding to the current error + Error*{.final.} = object # This is a numeric value corresponding to the current error # SDL_rwops.h types # This is the read/write operation structure -- very basic # some helper types to handle the unions @@ -787,51 +787,51 @@ type # used directly as an error message format string. key*: array[0..ERR_MAX_STRLEN - 1, int8] # These are the arguments for the error functions argc*: int - args*: array[0..ERR_MAX_ARGS - 1, TArg] + args*: array[0..ERR_MAX_ARGS - 1, Arg] - TStdio*{.final.} = object + Stdio*{.final.} = object autoclose*: int # FILE * is only defined in Kylix so we use a simple pointer fp*: pointer - TMem*{.final.} = object + Mem*{.final.} = object base*: ptr byte here*: ptr byte stop*: ptr byte - PRWops* = ptr TRWops # now the pointer to function types - TSeek* = proc (context: PRWops, offset: int, whence: int): int{.cdecl.} - TRead* = proc (context: PRWops, thePtr: pointer, size: int, maxnum: int): int{. + PRWops* = ptr RWops # now the pointer to function types + Seek* = proc (context: PRWops, offset: int, whence: int): int{.cdecl.} + Read* = proc (context: PRWops, thePtr: pointer, size: int, maxnum: int): int{. cdecl.} - TWrite* = proc (context: PRWops, thePtr: pointer, size: int, num: int): int{. + Write* = proc (context: PRWops, thePtr: pointer, size: int, num: int): int{. cdecl.} - TClose* = proc (context: PRWops): int{.cdecl.} # the variant record itself - TRWops*{.final.} = object - seek*: TSeek - read*: TRead - write*: TWrite - closeFile*: TClose # a keyword as name is not allowed + Close* = proc (context: PRWops): int{.cdecl.} # the variant record itself + RWops*{.final.} = object + seek*: Seek + read*: Read + write*: Write + closeFile*: Close # a keyword as name is not allowed # be warned! structure alignment may arise at this point theType*: cint - mem*: TMem + mem*: Mem - RWops* = TRWops # SDL_timer.h types + RWops* = RWops # SDL_timer.h types # Function prototype for the timer callback function - TTimerCallback* = proc (interval: int32): int32{.cdecl.} - TNewTimerCallback* = proc (interval: int32, param: pointer): int32{.cdecl.} + TimerCallback* = proc (interval: int32): int32{.cdecl.} + NewTimerCallback* = proc (interval: int32, param: pointer): int32{.cdecl.} - PTimerID* = ptr TTimerID - TTimerID*{.final.} = object + PTimerID* = ptr TimerID + TimerID*{.final.} = object interval*: int32 - callback*: TNewTimerCallback + callback*: NewTimerCallback param*: pointer lastAlarm*: int32 next*: PTimerID - TAudioSpecCallback* = proc (userdata: pointer, stream: ptr byte, length: int){. + AudioSpecCallback* = proc (userdata: pointer, stream: ptr byte, length: int){. cdecl.} # SDL_audio.h types # The calculated values in this structure are calculated by SDL_OpenAudio() - PAudioSpec* = ptr TAudioSpec - TAudioSpec*{.final.} = object # A structure to hold a set of audio conversion filters and buffers + PAudioSpec* = ptr AudioSpec + AudioSpec*{.final.} = object # A structure to hold a set of audio conversion filters and buffers freq*: int # DSP frequency -- samples per second format*: uint16 # Audio data format channels*: byte # Number of channels: 1 mono, 2 stereo @@ -844,18 +844,18 @@ type # 'len' is the length of that buffer in bytes. # Once the callback returns, the buffer will no longer be valid. # Stereo samples are stored in a LRLRLR ordering. - callback*: TAudioSpecCallback + callback*: AudioSpecCallback userdata*: pointer - PAudioCVT* = ptr TAudioCVT - PAudioCVTFilter* = ptr TAudioCVTFilter - TAudioCVTFilter*{.final.} = object + PAudioCVT* = ptr AudioCVT + PAudioCVTFilter* = ptr AudioCVTFilter + AudioCVTFilter*{.final.} = object cvt*: PAudioCVT format*: uint16 - PAudioCVTFilterArray* = ptr TAudioCVTFilterArray - TAudioCVTFilterArray* = array[0..9, PAudioCVTFilter] - TAudioCVT*{.final.} = object + PAudioCVTFilterArray* = ptr AudioCVTFilterArray + AudioCVTFilterArray* = array[0..9, PAudioCVTFilter] + AudioCVT*{.final.} = object needed*: int # Set to 1 if conversion possible srcFormat*: uint16 # Source audio format dstFormat*: uint16 # Target audio format @@ -865,49 +865,49 @@ type lenCvt*: int # Length of converted audio buffer lenMult*: int # buffer must be len*len_mult big lenRatio*: float64 # Given len, final size is len*len_ratio - filters*: TAudioCVTFilterArray + filters*: AudioCVTFilterArray filterIndex*: int # Current audio conversion function - TAudiostatus* = enum # SDL_cdrom.h types + AudioStatus* = enum # SDL_cdrom.h types AUDIO_STOPPED, AUDIO_PLAYING, AUDIO_PAUSED - TCDStatus* = enum + CDStatus* = enum CD_ERROR, CD_TRAYEMPTY, CD_STOPPED, CD_PLAYING, CD_PAUSED - PCDTrack* = ptr TCDTrack - TCDTrack*{.final.} = object # This structure is only current as of the last call to SDL_CDStatus() + PCDTrack* = ptr CDTrack + CDTrack*{.final.} = object # This structure is only current as of the last call to SDL_CDStatus() id*: byte # Track number theType*: byte # Data or audio track unused*: uint16 len*: int32 # Length, in frames, of this track offset*: int32 # Offset, in frames, from start of disk - PCD* = ptr TCD - TCD*{.final.} = object #SDL_joystick.h types + PCD* = ptr CD + CD*{.final.} = object #SDL_joystick.h types id*: int # Private drive identifier - status*: TCDStatus # Current drive status + status*: CDStatus # Current drive status # The rest of this structure is only valid if there's a CD in drive numtracks*: int # Number of tracks on disk - curTrack*: int # Current track position + curTrack*: int # Current track position curFrame*: int # Current frame offset within current track - track*: array[0..MAX_TRACKS, TCDTrack] + track*: array[0..MAX_TRACKS, CDTrack] - PTransAxis* = ptr TTransAxis - TTransAxis*{.final.} = object # The private structure used to keep track of a joystick + PTransAxis* = ptr TransAxis + TransAxis*{.final.} = object # The private structure used to keep track of a joystick offset*: int scale*: float32 - PJoystickHwdata* = ptr TJoystickHwdata - TJoystick_hwdata*{.final.} = object # joystick ID + PJoystickHwdata* = ptr JoystickHwdata + Joystick_hwdata*{.final.} = object # joystick ID id*: int # values used to translate device-specific coordinates into SDL-standard ranges - transaxis*: array[0..5, TTransAxis] + transaxis*: array[0..5, TransAxis] - PBallDelta* = ptr TBallDelta - TBallDelta*{.final.} = object # Current ball motion deltas + PBallDelta* = ptr BallDelta + BallDelta*{.final.} = object # Current ball motion deltas # The SDL joystick structure dx*: int dy*: int - PJoystick* = ptr TJoystick - TJoystick*{.final.} = object # SDL_verion.h types + PJoystick* = ptr Joystick + Joystick*{.final.} = object # SDL_verion.h types index*: byte # Device index name*: cstring # Joystick name - system dependent naxes*: int # Number of axis controls on the joystick @@ -921,16 +921,16 @@ type hwdata*: PJoystickHwdata # Driver dependent information refCount*: int # Reference count for multiple opens - Pversion* = ptr Tversion - Tversion*{.final.} = object # SDL_keyboard.h types + Pversion* = ptr Version + Version*{.final.} = object # SDL_keyboard.h types major*: byte minor*: byte patch*: byte - TKey* = int32 - TMod* = int32 - PKeySym* = ptr TKeySym - TKeySym*{.final.} = object # SDL_events.h types + Key* = int32 + Mod* = int32 + PKeySym* = ptr KeySym + KeySym*{.final.} = object # SDL_events.h types #Checks the event queue for messages and optionally returns them. # If 'action' is SDL_ADDEVENT, up to 'numevents' events will be added to # the back of the event queue. @@ -943,69 +943,69 @@ type # This function returns the number of events actually stored, or -1 # if there was an error. This function is thread-safe. scancode*: byte # hardware specific scancode - sym*: TKey # SDL virtual keysym - modifier*: TMod # current key modifiers + sym*: Key # SDL virtual keysym + modifier*: Mod # current key modifiers unicode*: uint16 # translated character - TEventAction* = enum # Application visibility event structure + EventAction* = enum # Application visibility event structure ADDEVENT, PEEKEVENT, GETEVENT - PActiveEvent* = ptr TActiveEvent - TActiveEvent*{.final.} = object # SDL_ACTIVEEVENT + PActiveEvent* = ptr ActiveEvent + ActiveEvent*{.final.} = object # SDL_ACTIVEEVENT # Keyboard event structure - kind*: TEventKind + kind*: EventKind gain*: byte # Whether given states were gained or lost (1/0) state*: byte # A mask of the focus states - PKeyboardEvent* = ptr TKeyboardEvent - TKeyboardEvent*{.final.} = object # SDL_KEYDOWN or SDL_KEYUP + PKeyboardEvent* = ptr KeyboardEvent + KeyboardEvent*{.final.} = object # SDL_KEYDOWN or SDL_KEYUP # Mouse motion event structure - kind*: TEventKind + kind*: EventKind which*: byte # The keyboard device index state*: byte # SDL_PRESSED or SDL_RELEASED - keysym*: TKeySym + keysym*: KeySym - PMouseMotionEvent* = ptr TMouseMotionEvent - TMouseMotionEvent*{.final.} = object # SDL_MOUSEMOTION + PMouseMotionEvent* = ptr MouseMotionEvent + MouseMotionEvent*{.final.} = object # SDL_MOUSEMOTION # Mouse button event structure - kind*: TEventKind + kind*: EventKind which*: byte # The mouse device index state*: byte # The current button state x*, y*: uint16 # The X/Y coordinates of the mouse xrel*: int16 # The relative motion in the X direction yrel*: int16 # The relative motion in the Y direction - PMouseButtonEvent* = ptr TMouseButtonEvent - TMouseButtonEvent*{.final.} = object # SDL_MOUSEBUTTONDOWN or SDL_MOUSEBUTTONUP + PMouseButtonEvent* = ptr MouseButtonEvent + MouseButtonEvent*{.final.} = object # SDL_MOUSEBUTTONDOWN or SDL_MOUSEBUTTONUP # Joystick axis motion event structure - kind*: TEventKind + kind*: EventKind which*: byte # The mouse device index button*: byte # The mouse button index state*: byte # SDL_PRESSED or SDL_RELEASED x*: uint16 # The X coordinates of the mouse at press time y*: uint16 # The Y coordinates of the mouse at press time - PJoyAxisEvent* = ptr TJoyAxisEvent - TJoyAxisEvent*{.final.} = object # SDL_JOYAXISMOTION + PJoyAxisEvent* = ptr JoyAxisEvent + JoyAxisEvent*{.final.} = object # SDL_JOYAXISMOTION # Joystick trackball motion event structure - kind*: TEventKind + kind*: EventKind which*: byte # The joystick device index axis*: byte # The joystick axis index value*: int16 # The axis value (range: -32768 to 32767) - PJoyBallEvent* = ptr TJoyBallEvent - TJoyBallEvent*{.final.} = object # SDL_JOYAVBALLMOTION + PJoyBallEvent* = ptr JoyBallEvent + JoyBallEvent*{.final.} = object # SDL_JOYAVBALLMOTION # Joystick hat position change event structure - kind*: TEventKind + kind*: EventKind which*: byte # The joystick device index ball*: byte # The joystick trackball index xrel*: int16 # The relative motion in the X direction yrel*: int16 # The relative motion in the Y direction - PJoyHatEvent* = ptr TJoyHatEvent - TJoyHatEvent*{.final.} = object # SDL_JOYHATMOTION */ + PJoyHatEvent* = ptr JoyHatEvent + JoyHatEvent*{.final.} = object # SDL_JOYHATMOTION */ # Joystick button event structure - kind*: TEventKind + kind*: EventKind which*: byte # The joystick device index */ hat*: byte # The joystick hat index */ value*: byte # The hat position value: @@ -1014,146 +1014,171 @@ type # 6 5 4 # Note that zero means the POV is centered. - PJoyButtonEvent* = ptr TJoyButtonEvent - TJoyButtonEvent*{.final.} = object # SDL_JOYBUTTONDOWN or SDL_JOYBUTTONUP + PJoyButtonEvent* = ptr JoyButtonEvent + JoyButtonEvent*{.final.} = object # SDL_JOYBUTTONDOWN or SDL_JOYBUTTONUP # The "window resized" event # When you get this event, you are # responsible for setting a new video # mode with the new width and height. - kind*: TEventKind + kind*: EventKind which*: byte # The joystick device index button*: byte # The joystick button index state*: byte # SDL_PRESSED or SDL_RELEASED - PResizeEvent* = ptr TResizeEvent - TResizeEvent*{.final.} = object # SDL_VIDEORESIZE + PResizeEvent* = ptr ResizeEvent + ResizeEvent*{.final.} = object # SDL_VIDEORESIZE # A user-defined event type - kind*: TEventKind + kind*: EventKind w*: cint # New width h*: cint # New height - PUserEvent* = ptr TUserEvent - TUserEvent*{.final.} = object # SDL_USEREVENT through SDL_NUMEVENTS-1 - kind*: TEventKind - code*: cint # User defined event code + PUserEvent* = ptr UserEvent + UserEvent*{.final.} = object # SDL_USEREVENT through SDL_NUMEVENTS-1 + kind*: EventKind + code*: cint # User defined event code data1*: pointer # User defined data pointer data2*: pointer # User defined data pointer +{.deprecated: [THandle: Handle, TEventAction: EventAction, TKey: Key, TArg: Arg, + TKeySym: KeySym, TKeyboardEvent: KeyboardEvent, TError: Error, + TWrite: Write, TBool: Bool, TUInt8Array: UInt8Array, + TGrabMode: GrabMode, Terrorcode: Errorcode, TStdio: Stdio, + TMem: Mem, TSeek: Seek, TRead: Read, TClose: Close, + TTimerCallback: TimerCallback, TNewTimerCallback: NewTimerCallabck, + TTimerID: TimerID, TAudioSpecCallback: AudioSpecCallback, + TAudioSpec: AudioSpec, TAudioCVTFilter: AudioCVTFilter, + TAudioCVTFilterArray: AudioCVTFilterArray, TAudioCVT: AudioCVT, + TAudioStatus: AudioStatus, TCDStatus: CDStatus, TCDTrack: CDTrack, + TCD: CD, TTransAxis: TransAxis, TJoystick_hwdata: Joystick_hwdata, + TJoystick: Joystick, TJoyAxisEvent: JoyAxisEvent, TRWops: RWops, + TJoyBallEvent: JoyBallEvent, TJoyHatEvent: JoyHatEvent, + TJoyButtonEvent: JoyButtonEvent, TBallDelta: BallDelta, + Tversion: Version, TMod: Mod, TActiveEvent: ActiveEvent, + TMouseMotionEvent: MouseMotionEvent, TMouseButtonEvent: MouseButtonEvent, + TResizeEvent: ResizeEvent, TUserEvent: UserEvent].} when defined(Unix): type #These are the various supported subsystems under UNIX - TSysWm* = enum + SysWm* = enum SYSWM_X11 + {.deprecated: [TSysWm: SysWm].} when defined(WINDOWS): type - PSysWMmsg* = ptr TSysWMmsg - TSysWMmsg*{.final.} = object - version*: Tversion - hwnd*: THandle # The window for the message + PSysWMmsg* = ptr SysWMmsg + SysWMmsg*{.final.} = object + version*: Version + hwnd*: Handle # The window for the message msg*: int # The type of message wParam*: int32 # WORD message parameter lParam*: int32 # LONG message parameter + {.deprecated: [TSysWMmsg: SysWMmsg].} elif defined(Unix): type # The Linux custom event structure - PSysWMmsg* = ptr TSysWMmsg - TSysWMmsg*{.final.} = object - version*: Tversion - subsystem*: TSysWm + PSysWMmsg* = ptr SysWMmsg + SysWMmsg*{.final.} = object + version*: Version + subsystem*: SysWm when false: event*: TXEvent + {.deprecated: [TSysWMmsg: SysWMmsg].} else: type # The generic custom event structure - PSysWMmsg* = ptr TSysWMmsg - TSysWMmsg*{.final.} = object - version*: Tversion + PSysWMmsg* = ptr SysWMmsg + SysWMmsg*{.final.} = object + version*: Version data*: int + {.deprecated: [TSysWMmsg: SysWMmsg].} # The Windows custom window manager information structure when defined(WINDOWS): type - PSysWMinfo* = ptr TSysWMinfo - TSysWMinfo*{.final.} = object - version*: Tversion - window*: THandle # The display window + PSysWMinfo* = ptr SysWMinfo + SysWMinfo*{.final.} = object + version*: Version + window*: Handle # The display window + {.deprecated: [TSysWMinfo: SysWMinfo].} elif defined(Unix): type - TX11*{.final.} = object + X11*{.final.} = object when false: display*: PDisplay # The X11 display - window*: TWindow # The X11 display window + window*: Window # The X11 display window # These locking functions should be called around # any X11 functions using the display variable. # They lock the event thread, so should not be # called around event functions or from event filters. lock_func*: pointer unlock_func*: pointer # Introduced in SDL 1.0.2 - fswindow*: TWindow # The X11 fullscreen window - wmwindow*: TWindow # The X11 managed input window + fswindow*: Window # The X11 fullscreen window + wmwindow*: Window # The X11 managed input window + {.deprecated: [TX11: X11].} type - PSysWMinfo* = ptr TSysWMinfo - TSysWMinfo*{.final.} = object - version*: Tversion - subsystem*: TSysWm - X11*: TX11 + PSysWMinfo* = ptr SysWMinfo + SysWMinfo*{.final.} = object + version*: Version + subsystem*: SysWm + X11*: X11 + {.deprecated: [TSysWMinfo: SysWMinfo].} else: type # The generic custom window manager information structure - PSysWMinfo* = ptr TSysWMinfo - TSysWMinfo*{.final.} = object - version*: Tversion + PSysWMinfo* = ptr SysWMinfo + SysWMinfo*{.final.} = object + version*: Version data*: int + {.deprecated: [TSysWMinfo: SysWMinfo].} type - PSysWMEvent* = ptr TSysWMEvent - TSysWMEvent*{.final.} = object - kind*: TEventKind + PSysWMEvent* = ptr SysWMEvent + SysWMEvent*{.final.} = object + kind*: EventKind msg*: PSysWMmsg - PExposeEvent* = ptr TExposeEvent - TExposeEvent*{.final.} = object - kind*: TEventKind + PExposeEvent* = ptr ExposeEvent + ExposeEvent*{.final.} = object + kind*: EventKind - PQuitEvent* = ptr TQuitEvent - TQuitEvent*{.final.} = object - kind*: TEventKind + PQuitEvent* = ptr QuitEvent + QuitEvent*{.final.} = object + kind*: EventKind - PEvent* = ptr TEvent - TEvent*{.final.} = object - kind*: TEventKind + PEvent* = ptr Event + Event*{.final.} = object + kind*: EventKind pad: array[0..19, byte] - TEventFilter* = proc (event: PEvent): int{.cdecl.} # SDL_video.h types + EventFilter* = proc (event: PEvent): int{.cdecl.} # SDL_video.h types # Useful data types PPSDL_Rect* = ptr PRect - PRect* = ptr TRect - TRect*{.final.} = object + PRect* = ptr Rect + Rect*{.final.} = object x*, y*: int16 w*, h*: uint16 - Rect* = TRect - PColor* = ptr TColor - TColor*{.final.} = object +# Rect* = TRect + PColor* = ptr Color + Color*{.final.} = object r*: byte g*: byte b*: byte unused*: byte - PColorArray* = ptr TColorArray - TColorArray* = array[0..65000, TColor] + PColorArray* = ptr ColorArray + ColorArray* = array[0..65000, Color] PPalette* = ptr TPalette - TPalette*{.final.} = object # Everything in the pixel format structure is read-only + Palette*{.final.} = object # Everything in the pixel format structure is read-only ncolors*: int colors*: PColorArray PPixelFormat* = ptr TPixelFormat - TPixelFormat*{.final.} = object # The structure passed to the low level blit functions + PixelFormat*{.final.} = object # The structure passed to the low level blit functions palette*: PPalette bitsPerPixel*: byte bytesPerPixel*: byte @@ -1172,8 +1197,8 @@ type colorkey*: int32 # RGB color key information alpha*: byte # Alpha value information (per-surface alpha) - PBlitInfo* = ptr TBlitInfo - TBlitInfo*{.final.} = object # typedef for private surface blitting functions + PBlitInfo* = ptr BlitInfo + BlitInfo*{.final.} = object # typedef for private surface blitting functions sPixels*: ptr byte sWidth*: int sHeight*: int @@ -1187,10 +1212,10 @@ type table*: ptr byte dst*: PPixelFormat - PSurface* = ptr TSurface - TBlit* = proc (src: PSurface, srcrect: PRect, + PSurface* = ptr Surface + Blit* = proc (src: PSurface, srcrect: PRect, dst: PSurface, dstrect: PRect): int{.cdecl.} - TSurface*{.final.} = object # Useful for determining the video hardware capabilities + Surface*{.final.} = object # Useful for determining the video hardware capabilities flags*: int32 # Read-only format*: PPixelFormat # Read-only w*, h*: cint # Read-only @@ -1199,7 +1224,7 @@ type offset*: cint # Private hwdata*: pointer #TPrivate_hwdata; Hardware-specific surface info # clipping information: - clipRect*: TRect # Read-only + clipRect*: Rect # Read-only unused1*: int32 # for binary compatibility # Allow recursive locks locked*: int32 # Private @@ -1209,8 +1234,8 @@ type formatVersion*: cint # Private refcount*: cint - PVideoInfo* = ptr TVideoInfo - TVideoInfo*{.final.} = object # The YUV hardware video overlay + PVideoInfo* = ptr VideoInfo + VideoInfo*{.final.} = object # The YUV hardware video overlay hwAvailable*: byte blitHw*: byte unusedBits3*: byte # Unused at this point @@ -1219,8 +1244,8 @@ type currentW*: int32 # Value: The current video mode width currentH*: int32 # Value: The current video mode height - POverlay* = ptr TOverlay - TOverlay*{.final.} = object # Public enumeration for setting the OpenGL window attributes. + POverlay* = ptr Overlay + Overlay*{.final.} = object # Public enumeration for setting the OpenGL window attributes. format*: int32 # Overlay format w*, h*: int # Width and height of overlay planes*: int # Number of planes in the overlay. Usually either 1 or 3 @@ -1228,61 +1253,73 @@ type pixels*: ptr ptr byte # An array of pointers to the data of each plane. The overlay should be locked before these pointers are used. hwOverlay*: int32 # This will be set to 1 if the overlay is hardware accelerated. - TGLAttr* = enum + GLAttr* = enum GL_RED_SIZE, GL_GREEN_SIZE, GL_BLUE_SIZE, GL_ALPHA_SIZE, GL_BUFFER_SIZE, GL_DOUBLEBUFFER, GL_DEPTH_SIZE, GL_STENCIL_SIZE, GL_ACCUM_RED_SIZE, GL_ACCUM_GREEN_SIZE, GL_ACCUM_BLUE_SIZE, GL_ACCUM_ALPHA_SIZE, GL_STEREO, GL_MULTISAMPLEBUFFERS, GL_MULTISAMPLESAMPLES, GL_ACCELERATED_VISUAL, GL_SWAP_CONTROL - PCursor* = ptr TCursor - TCursor*{.final.} = object # SDL_mutex.h types - area*: TRect # The area of the mouse cursor + PCursor* = ptr Cursor + Cursor*{.final.} = object # SDL_mutex.h types + area*: Rect # The area of the mouse cursor hotX*, hot_y*: int16 # The "tip" of the cursor data*: ptr byte # B/W cursor data mask*: ptr byte # B/W cursor mask save*: array[1..2, ptr byte] # Place to save cursor area wmCursor*: pointer # Window-manager cursor - +{.deprecated: [TRect: Rect, TSurface: Surface, TEvent: Event, TColor: Color, + TEventFilter: EventFilter, TColorArray: ColorArray, + TSysWMEvent: SysWMEvent, TExposeEvent: ExposeEvent, + TQuitEvent: QuitEvent, TPalette: Palette, TPixelFormat: PixelFormat, + TBlitInfo: BlitInfo, TBlit: Blit, TVideoInfo: VideoInfo, + TOverlay: Overlay, TGLAttr: GLAttr, TCursor: Cursor].} type - PMutex* = ptr TMutex - TMutex*{.final.} = object - Psemaphore* = ptr Tsemaphore - Tsemaphore*{.final.} = object - PSem* = ptr TSem - TSem* = Tsemaphore - PCond* = ptr TCond - TCond*{.final.} = object # SDL_thread.h types + PMutex* = ptr Mutex + Mutex*{.final.} = object + Psemaphore* = ptr Semaphore + Semaphore*{.final.} = object + PSem* = ptr Sem + Sem* = Semaphore + PCond* = ptr Cond + Cond*{.final.} = object # SDL_thread.h types +{.deprecated: [TCond: Cond, TSem: Sem, TMutex: Mutex, Tsemaphore: Semaphore].} when defined(WINDOWS): type - TSYS_ThreadHandle* = THandle + SYS_ThreadHandle* = Handle + {.deprecated: [TSYS_ThreadHandle: SYS_ThreadHandle].} when defined(Unix): type - TSYS_ThreadHandle* = pointer + SYS_ThreadHandle* = pointer + {.deprecated: [TSYS_ThreadHandle: SYS_ThreadHandle].} type # This is the system-independent thread info structure - PThread* = ptr TThread - TThread*{.final.} = object # Helper Types + PThread* = ptr Thread + Thread*{.final.} = object # Helper Types # Keyboard State Array ( See demos for how to use ) threadid*: int32 - handle*: TSYS_ThreadHandle + handle*: SYS_ThreadHandle status*: int errbuf*: Terror data*: pointer - PKeyStateArr* = ptr TKeyStateArr - TKeyStateArr* = array[0..65000, byte] # Types required so we don't need to use Windows.pas + PKeyStateArr* = ptr KeyStateArr + KeyStateArr* = array[0..65000, byte] # Types required so we don't need to use Windows.pas PInteger* = ptr int PByte* = ptr int8 PWord* = ptr int16 PLongWord* = ptr int32 # General arrays - PByteArray* = ptr TByteArray - TByteArray* = array[0..32767, int8] - PWordArray* = ptr TWordArray - TWordArray* = array[0..16383, int16] # Generic procedure pointer + PByteArray* = ptr ByteArray + ByteArray* = array[0..32767, int8] + PWordArray* = ptr WordArray + WordArray* = array[0..16383, int16] # Generic procedure pointer +{.deprecated: [TKeyStateArr: KeyStateArr, TByteArray: ByteArray, TThread: Thread, + TWordArray: WordArray].} -type TEventSeq = set[TEventKind] -template evconv(procName: expr, ptrName: typedesc, assertions: TEventSeq): stmt {.immediate.} = +type EventSeq = set[EventKind] +{.deprecated: [TEventSeq: EventSeq].} + +template evconv(procName: expr, ptrName: typedesc, assertions: EventSeq): stmt {.immediate.} = proc `procName`*(event: PEvent): ptrName = assert(contains(assertions, event.kind)) result = cast[ptrName](event) @@ -1337,7 +1374,7 @@ proc getError*(): cstring{.cdecl, importc: "SDL_GetError", dynlib: LibName.} proc setError*(fmt: cstring){.cdecl, importc: "SDL_SetError", dynlib: LibName.} proc clearError*(){.cdecl, importc: "SDL_ClearError", dynlib: LibName.} when not (defined(WINDOWS)): - proc error*(Code: Terrorcode){.cdecl, importc: "SDL_Error", dynlib: LibName.} + proc error*(Code: ErrorCode){.cdecl, importc: "SDL_Error", dynlib: LibName.} #------------------------------------------------------------------------------ # io handling #------------------------------------------------------------------------------ @@ -1368,13 +1405,13 @@ proc getTicks*(): int32{.cdecl, importc: "SDL_GetTicks", dynlib: LibName.} proc delay*(msec: int32){.cdecl, importc: "SDL_Delay", dynlib: LibName.} # Add a new timer to the pool of timers already running. # Returns a timer ID, or NULL when an error occurs. -proc addTimer*(interval: int32, callback: TNewTimerCallback, param: pointer): PTimerID{. +proc addTimer*(interval: int32, callback: NewTimerCallback, param: pointer): PTimerID{. cdecl, importc: "SDL_AddTimer", dynlib: LibName.} # Remove one of the multiple timers knowing its ID. # Returns a boolean value indicating success. -proc removeTimer*(t: PTimerID): TBool{.cdecl, importc: "SDL_RemoveTimer", +proc removeTimer*(t: PTimerID): Bool{.cdecl, importc: "SDL_RemoveTimer", dynlib: LibName.} -proc setTimer*(interval: int32, callback: TTimerCallback): int{.cdecl, +proc setTimer*(interval: int32, callback: TimerCallback): int{.cdecl, importc: "SDL_SetTimer", dynlib: LibName.} #------------------------------------------------------------------------------ # audio-routines @@ -1432,7 +1469,7 @@ proc audioDriverName*(namebuf: cstring, maxlen: int): cstring{.cdecl, proc openAudio*(desired, obtained: PAudioSpec): int{.cdecl, importc: "SDL_OpenAudio", dynlib: LibName.} # Get the current audio state: -proc getAudioStatus*(): TAudiostatus{.cdecl, importc: "SDL_GetAudioStatus", +proc getAudioStatus*(): Audiostatus{.cdecl, importc: "SDL_GetAudioStatus", dynlib: LibName.} # This function pauses and unpauses the audio callback processing. # It should be called with a parameter of 0 after opening the audio @@ -1518,7 +1555,7 @@ proc cdOpen*(drive: int): PCD{.cdecl, importc: "SDL_CDOpen", dynlib: LibName.} # This function returns the current status of the given drive. # If the drive has a CD in it, the table of contents of the CD and current # play position of the CD will be stored in the SDL_CD structure. -proc cdStatus*(cdrom: PCD): TCDStatus{.cdecl, importc: "SDL_CDStatus", +proc cdStatus*(cdrom: PCD): CDStatus{.cdecl, importc: "SDL_CDStatus", dynlib: LibName.} # Play the given CD starting at 'start_track' and 'start_frame' for 'ntracks' # tracks and 'nframes' frames. If both 'ntrack' and 'nframe' are 0, play @@ -1559,7 +1596,7 @@ proc cdEject*(cdrom: PCD): int{.cdecl, importc: "SDL_CDEject", dynlib: LibName.} # Closes the handle for the CD-ROM drive proc cdClose*(cdrom: PCD){.cdecl, importc: "SDL_CDClose", dynlib: LibName.} # Given a status, returns true if there's a disk in the drive -proc cdInDrive*(status: TCDStatus): bool +proc cdInDrive*(status: CDStatus): bool proc numJoysticks*(): int{.cdecl, importc: "SDL_NumJoysticks", dynlib: LibName.} # Get the implementation dependent name of a joystick. @@ -1643,7 +1680,7 @@ proc pumpEvents*(){.cdecl, importc: "SDL_PumpEvents", dynlib: LibName.} # removed from the queue. # This function returns the number of events actually stored, or -1 # if there was an error. This function is thread-safe. -proc peepEvents*(events: PEvent, numevents: int, action: TEventAction, +proc peepEvents*(events: PEvent, numevents: int, action: EventAction, mask: int32): int{.cdecl, importc: "SDL_PeepEvents", dynlib: LibName.} # Polls for currently pending events, and returns 1 if there are any pending @@ -1672,11 +1709,11 @@ proc pushEvent*(event: PEvent): int{.cdecl, importc: "SDL_PushEvent", # be closed, otherwise the window will remain open if possible. # If the quit event is generated by an interrupt signal, it will bypass the # internal queue and be delivered to the application at the next event poll. -proc setEventFilter*(filter: TEventFilter){.cdecl, +proc setEventFilter*(filter: EventFilter){.cdecl, importc: "SDL_SetEventFilter", dynlib: LibName.} # Return the current event filter - can be used to "chain" filters. # If there is no event filter set, this function returns NULL. -proc getEventFilter*(): TEventFilter{.cdecl, importc: "SDL_GetEventFilter", +proc getEventFilter*(): EventFilter{.cdecl, importc: "SDL_GetEventFilter", dynlib: LibName.} # This function allows you to set the state of processing certain events. # If 'state' is set to SDL_IGNORE, that event will be automatically dropped @@ -1691,7 +1728,7 @@ proc eventState*(theType: byte, state: int): byte{.cdecl, #------------------------------------------------------------------------------ # This macro can be used to fill a version structure with the compile-time # version of the SDL library. -proc version*(x: var Tversion) +proc version*(x: var Version) # This macro turns the version numbers into a numeric value: # (1,2,3) -> (1203) # This assumes that there will never be more than 100 patchlevels @@ -2230,7 +2267,7 @@ proc wmToggleFullScreen*(surface: PSurface): int{.cdecl, # Grabbing means that the mouse is confined to the application window, # and nearly all keyboard input is passed directly to the application, # and not interpreted by a window manager, if any. -proc wmGrabInput*(mode: TGrabMode): TGrabMode{.cdecl, +proc wmGrabInput*(mode: TGrabMode): GrabMode{.cdecl, importc: "SDL_WM_GrabInput", dynlib: LibName.} #------------------------------------------------------------------------------ # mouse-routines @@ -2305,13 +2342,13 @@ proc getKeyRepeat*(delay: PInteger, interval: PInteger){.cdecl, proc getKeyState*(numkeys: pointer): ptr byte{.cdecl, importc: "SDL_GetKeyState", dynlib: LibName.} # Get the current key modifier state -proc getModState*(): TMod{.cdecl, importc: "SDL_GetModState", dynlib: LibName.} +proc getModState*(): Mod{.cdecl, importc: "SDL_GetModState", dynlib: LibName.} # Set the current key modifier state # This does not change the keyboard state, only the key modifier flags. -proc setModState*(modstate: TMod){.cdecl, importc: "SDL_SetModState", +proc setModState*(modstate: Mod){.cdecl, importc: "SDL_SetModState", dynlib: LibName.} # Get the name of an SDL virtual keysym -proc getKeyName*(key: TKey): cstring{.cdecl, importc: "SDL_GetKeyName", +proc getKeyName*(key: Key): cstring{.cdecl, importc: "SDL_GetKeyName", dynlib: LibName.} #------------------------------------------------------------------------------ # Active Routines @@ -2469,7 +2506,7 @@ proc loadWAV(filename: cstring, spec: PAudioSpec, audioBuf: ptr byte, audiolen: PUInt32): PAudioSpec = result = loadWAV_RW(rWFromFile(filename, "rb"), 1, spec, audioBuf, audiolen) -proc cdInDrive(status: TCDStatus): bool = +proc cdInDrive(status: CDStatus): bool = result = ord(status) > ord(CD_ERROR) proc framesToMsf*(frames: int; m, s, f: var int) = @@ -2483,7 +2520,7 @@ proc framesToMsf*(frames: int; m, s, f: var int) = proc msfToFrames*(m, s, f: int): int = result = m * 60 * CD_FPS + s * CD_FPS + f -proc version(x: var Tversion) = +proc version(x: var Version) = x.major = MAJOR_VERSION x.minor = MINOR_VERSION x.patch = PATCHLEVEL diff --git a/lib/wrappers/sdl/sdl_gfx.nim b/lib/wrappers/sdl/sdl_gfx.nim index 5523ad0a2..0f5afaa9b 100644 --- a/lib/wrappers/sdl/sdl_gfx.nim +++ b/lib/wrappers/sdl/sdl_gfx.nim @@ -37,22 +37,22 @@ const # Some rates in Hz SMOOTHING_ON* = 1 type - PFPSmanager* = ptr TFPSmanager - TFPSmanager*{.final.} = object # ---- Structures + PFPSmanager* = ptr FPSmanager + FPSmanager*{.final.} = object # ---- Structures framecount*: uint32 rateticks*: float32 lastticks*: uint32 rate*: uint32 - PColorRGBA* = ptr TColorRGBA - TColorRGBA*{.final.} = object + PColorRGBA* = ptr ColorRGBA + ColorRGBA*{.final.} = object r*: byte g*: byte b*: byte a*: byte - PColorY* = ptr TColorY - TColorY*{.final.} = object # + PColorY* = ptr ColorY + ColorY*{.final.} = object # # # SDL_framerate: framerate manager # @@ -60,7 +60,7 @@ type # # y*: byte - +{.deprecated: [TFPSmanager: FPSmanager, TColorRGBA: ColorRGBA, TColorY: ColorY].} proc initFramerate*(manager: PFPSmanager){.cdecl, importc: "SDL_initFramerate", dynlib: gfxLibName.} diff --git a/lib/wrappers/sdl/sdl_image.nim b/lib/wrappers/sdl/sdl_image.nim index 9c56e6a46..7f99c8069 100644 --- a/lib/wrappers/sdl/sdl_image.nim +++ b/lib/wrappers/sdl/sdl_image.nim @@ -148,7 +148,7 @@ const # This macro can be used to fill a version structure with the compile-time # version of the SDL_image library. -proc imageVersion*(x: var Tversion) +proc imageVersion*(x: var Version) # This function gets the version of the dynamically linked SDL_image library. # it should NOT be used to fill a version structure, instead you should # use the SDL_IMAGE_VERSION() macro. @@ -236,7 +236,7 @@ proc imgLoadXV_RW*(src: PRWops): PSurface{.cdecl, importc: "IMG_LoadXV_RW", proc imgReadXPMFromArray*(xpm: cstringArray): PSurface{.cdecl, importc: "IMG_ReadXPMFromArray", dynlib: ImageLibName.} -proc imageVersion(x: var Tversion) = +proc imageVersion(x: var Version) = x.major = IMAGE_MAJOR_VERSION x.minor = IMAGE_MINOR_VERSION x.patch = IMAGE_PATCHLEVEL diff --git a/lib/wrappers/sdl/sdl_mixer.nim b/lib/wrappers/sdl/sdl_mixer.nim index 2f8664635..b8f013a4a 100644 --- a/lib/wrappers/sdl/sdl_mixer.nim +++ b/lib/wrappers/sdl/sdl_mixer.nim @@ -188,34 +188,34 @@ const (LIBMIKMOD_VERSION_MINOR shl 8) or (LIBMIKMOD_REVISION)) type #music_cmd.h types - PMusicCMD* = ptr TMusicCMD - TMusicCMD*{.final.} = object #wavestream.h types + PMusicCMD* = ptr MusicCMD + MusicCMD*{.final.} = object #wavestream.h types filename*: array[0..PATH_MAX - 1, char] cmd*: array[0..PATH_MAX - 1, char] pid*: TSYS_ThreadHandle - PWAVStream* = ptr TWAVStream - TWAVStream*{.final.} = object #playmidi.h types + PWAVStream* = ptr WAVStream + WAVStream*{.final.} = object #playmidi.h types wavefp*: pointer start*: int32 stop*: int32 cvt*: TAudioCVT - PMidiEvent* = ptr TMidiEvent - TMidiEvent*{.final.} = object + PMidiEvent* = ptr MidiEvent + MidiEvent*{.final.} = object time*: int32 channel*: byte typ*: byte a*: byte b*: byte - PMidiSong* = ptr TMidiSong - TMidiSong*{.final.} = object #music_ogg.h types + PMidiSong* = ptr MidiSong + MidiSong*{.final.} = object #music_ogg.h types samples*: int32 events*: PMidiEvent - POGG_Music* = ptr TOGG_Music - TOGG_Music*{.final.} = object # mikmod.h types + POGG_Music* = ptr OGG_Music + OGG_Music*{.final.} = object # mikmod.h types #* # * Error codes # * @@ -226,7 +226,7 @@ type #music_cmd.h types lenAvailable*: int32 sndAvailable*: pointer - TErrorEnum* = enum + ErrorEnum* = enum MMERR_OPENING_FILE, MMERR_OUT_OF_MEMORY, MMERR_DYNAMIC_LINKING, MMERR_SAMPLE_TOO_BIG, MMERR_OUT_OF_HANDLES, MMERR_UNKNOWN_WAVE_TYPE, MMERR_LOADING_PATTERN, MMERR_LOADING_TRACK, MMERR_LOADING_HEADER, @@ -246,37 +246,41 @@ type #music_cmd.h types MMERR_DS_EVENT, MMERR_DS_THREAD, MMERR_DS_UPDATE, MMERR_WINMM_HANDLE, MMERR_WINMM_ALLOCATED, MMERR_WINMM_DEVICEID, MMERR_WINMM_FORMAT, MMERR_WINMM_UNKNOWN, MMERR_MAC_SPEED, MMERR_MAC_START, MMERR_MAX - PMODULE* = ptr TMODULE - TMODULE*{.final.} = object - PUNIMOD* = ptr TUNIMOD - TUNIMOD* = TMODULE #SDL_mixer.h types + PMODULE* = ptr MODULE + MODULE*{.final.} = object + PUNIMOD* = ptr UNIMOD + UNIMOD* = MODULE #SDL_mixer.h types # The internal format for an audio chunk - PChunk* = ptr TChunk - TChunk*{.final.} = object + PChunk* = ptr Chunk + Chunk*{.final.} = object allocated*: cint abuf*: pointer alen*: uint32 volume*: byte # Per-sample volume, 0-128 - TFading* = enum + Fading* = enum MIX_NO_FADING, MIX_FADING_OUT, MIX_FADING_IN - TMusicType* = enum + MusicType* = enum MUS_NONE, MUS_CMD, MUS_WAV, MUS_MOD, MUS_MID, MUS_OGG, MUS_MP3 - PMusic* = ptr TMusic - TMusic*{.final.} = object # The internal format for a music chunk interpreted via mikmod - mixtype*: TMusicType # other fields are not aviable - # data : TMusicUnion; + PMusic* = ptr Music + Music*{.final.} = object # The internal format for a music chunk interpreted via mikmod + mixtype*: MusicType # other fields are not aviable + # data : MusicUnion; # fading : TMix_Fading; # fade_volume : integer; # fade_step : integer; # fade_steps : integer; # error : integer; - TMixFunction* = proc (udata, stream: pointer, length: cint): pointer{. + MixFunction* = proc (udata, stream: pointer, length: cint): pointer{. cdecl.} # This macro can be used to fill a version structure with the compile-time # version of the SDL_mixer library. +{.deprecated: [TMusicCMD: MusicCMD, TWAVStream: WAVStream, TMidiEvent: MidiEvent, + TMidiSong: MidiSong, TOGG_Music: OGG_Music, TErrorEnum: ErrorEnum, + TMODULE: MODULE, TUNIMOD: UNIMOD, TChunk: Chunk, TFading: Fading, + TMusicType: MusicType, TMusic: Music, TMixFunction: MixFunction].} -proc version*(x: var sdl.Tversion) +proc version*(x: var sdl.Version) # This function gets the version of the dynamically linked SDL_mixer library. # It should NOT be used to fill a version structure, instead you should use the # SDL_MIXER_VERSION() macro. @@ -314,18 +318,18 @@ proc freeMusic*(music: PMusic){.cdecl, importc: "Mix_FreeMusic", dynlib: MixerLibName.} # Find out the music format of a mixer music, or the currently playing # music, if 'music' is NULL. -proc getMusicType*(music: PMusic): TMusicType{.cdecl, +proc getMusicType*(music: PMusic): MusicType{.cdecl, importc: "Mix_GetMusicType", dynlib: MixerLibName.} # Set a function that is called after all mixing is performed. # This can be used to provide real-time visual display of the audio stream # or add a custom mixer filter for the stream data. # -proc setPostMix*(mixFunc: TMixFunction, arg: pointer){.cdecl, +proc setPostMix*(mixFunc: MixFunction, arg: pointer){.cdecl, importc: "Mix_SetPostMix", dynlib: MixerLibName.} # Add your own music player or additional mixer function. # If 'mix_func' is NULL, the default music player is re-enabled. # -proc hookMusic*(mixFunc: TMixFunction, arg: pointer){.cdecl, +proc hookMusic*(mixFunc: MixFunction, arg: pointer){.cdecl, importc: "Mix_HookMusic", dynlib: MixerLibName.} # Add your own callback when the music has finished playing. # @@ -337,9 +341,10 @@ proc getMusicHookData*(): pointer{.cdecl, importc: "Mix_GetMusicHookData", #* Add your own callback when a channel has finished playing. NULL # * to disable callback.* type - TChannelFinished* = proc (channel: cint){.cdecl.} + ChannelFinished* = proc (channel: cint){.cdecl.} +{.deprecated: [TChannelFinished: ChannelFinished].} -proc channelFinished*(channelFinished: TChannelFinished){.cdecl, +proc channelFinished*(channelFinished: ChannelFinished){.cdecl, importc: "Mix_ChannelFinished", dynlib: MixerLibName.} const CHANNEL_POST* = - 2 @@ -430,9 +435,9 @@ proc fadeOutGroup*(tag: cint, ms: cint): cint{.cdecl, proc fadeOutMusic*(ms: cint): cint{.cdecl, importc: "Mix_FadeOutMusic", dynlib: MixerLibName.} # Query the fading status of a channel -proc fadingMusic*(): TFading{.cdecl, importc: "Mix_FadingMusic", +proc fadingMusic*(): Fading{.cdecl, importc: "Mix_FadingMusic", dynlib: MixerLibName.} -proc fadingChannel*(which: cint): TFading{.cdecl, +proc fadingChannel*(which: cint): Fading{.cdecl, importc: "Mix_FadingChannel", dynlib: MixerLibName.} proc pause*(channel: cint){.cdecl, importc: "Mix_Pause", dynlib: MixerLibName.} @@ -468,7 +473,7 @@ proc getChunk*(channel: cint): PChunk{.cdecl, importc: "Mix_GetChunk", proc closeAudio*(){.cdecl, importc: "Mix_CloseAudio", dynlib: MixerLibName.} -proc version(x: var sdl.Tversion) = +proc version(x: var sdl.Version) = x.major = MAJOR_VERSION x.minor = MINOR_VERSION x.patch = PATCHLEVEL diff --git a/lib/wrappers/sdl/sdl_mixer_nosmpeg.nim b/lib/wrappers/sdl/sdl_mixer_nosmpeg.nim index 7a8c41af1..670cf1643 100644 --- a/lib/wrappers/sdl/sdl_mixer_nosmpeg.nim +++ b/lib/wrappers/sdl/sdl_mixer_nosmpeg.nim @@ -40,34 +40,34 @@ const (LIBMIKMOD_VERSION_MINOR shl 8) or (LIBMIKMOD_REVISION)) type #music_cmd.h types - PMusicCMD* = ptr TMusicCMD - TMusicCMD*{.final.} = object #wavestream.h types + PMusicCMD* = ptr MusicCMD + MusicCMD*{.final.} = object #wavestream.h types filename*: array[0..PATH_MAX - 1, char] cmd*: array[0..PATH_MAX - 1, char] pid*: TSYS_ThreadHandle - PWAVStream* = ptr TWAVStream - TWAVStream*{.final.} = object #playmidi.h types + PWAVStream* = ptr WAVStream + WAVStream*{.final.} = object #playmidi.h types wavefp*: pointer start*: int32 stop*: int32 cvt*: TAudioCVT - PMidiEvent* = ptr TMidiEvent - TMidiEvent*{.final.} = object + PMidiEvent* = ptr MidiEvent + MidiEvent*{.final.} = object time*: int32 channel*: byte typ*: byte a*: byte b*: byte - PMidiSong* = ptr TMidiSong - TMidiSong*{.final.} = object #music_ogg.h types + PMidiSong* = ptr MidiSong + MidiSong*{.final.} = object #music_ogg.h types samples*: int32 events*: PMidiEvent - POGG_Music* = ptr TOGG_Music - TOGG_Music*{.final.} = object # mikmod.h types + POGG_Music* = ptr OGG_Music + OGG_Music*{.final.} = object # mikmod.h types #* # * Error codes # * @@ -78,7 +78,7 @@ type #music_cmd.h types lenAvailable*: cint sndAvailable*: pointer - TErrorEnum* = enum + ErrorEnum* = enum MMERR_OPENING_FILE, MMERR_OUT_OF_MEMORY, MMERR_DYNAMIC_LINKING, MMERR_SAMPLE_TOO_BIG, MMERR_OUT_OF_HANDLES, MMERR_UNKNOWN_WAVE_TYPE, MMERR_LOADING_PATTERN, MMERR_LOADING_TRACK, MMERR_LOADING_HEADER, @@ -98,31 +98,36 @@ type #music_cmd.h types MMERR_DS_EVENT, MMERR_DS_THREAD, MMERR_DS_UPDATE, MMERR_WINMM_HANDLE, MMERR_WINMM_ALLOCATED, MMERR_WINMM_DEVICEID, MMERR_WINMM_FORMAT, MMERR_WINMM_UNKNOWN, MMERR_MAC_SPEED, MMERR_MAC_START, MMERR_MAX - PMODULE* = ptr TMODULE - TMODULE*{.final.} = object - PUNIMOD* = ptr TUNIMOD - TUNIMOD* = TMODULE #SDL_mixer.h types + PMODULE* = ptr MODULE + MODULE*{.final.} = object + PUNIMOD* = ptr UNIMOD + UNIMOD* = MODULE #SDL_mixer.h types # The internal format for an audio chunk - PChunk* = ptr TChunk - TChunk*{.final.} = object + PChunk* = ptr Chunk + Chunk*{.final.} = object allocated*: cint abuf*: pointer alen*: uint32 volume*: byte # Per-sample volume, 0-128 - TFading* = enum + Fading* = enum MIX_NO_FADING, MIX_FADING_OUT, MIX_FADING_IN - TMusicType* = enum + MusicType* = enum MUS_NONE, MUS_CMD, MUS_WAV, MUS_MOD, MUS_MID, MUS_OGG - PMusic* = ptr TMusic - TMusic*{.final.} = object - typ*: TMusicType + PMusic* = ptr Music + Music*{.final.} = object + typ*: MusicType - TMixFunction* = proc (udata, stream: pointer, length: cint): pointer{. + MixFunction* = proc (udata, stream: pointer, length: cint): pointer{. cdecl.} # This macro can be used to fill a version structure with the compile-time # version of the SDL_mixer library. +{.deprecated: [TMusicCMD: MusicCMD, TWAVStream: WAVStream, TMidiEvent: MidiEvent, + TMidiSong: MidiSong, TOGG_Music: OGG_Music, TErrorEnum: ErrorEnum, + TMODULE: MODULE, TUNIMOD: UNIMOD, TChunk: Chunk, TFading: Fading, + TMusicType: MusicType, TMusic: Music, TMixFunction: MixFunction].} -proc version*(x: var sdl.Tversion) + +proc version*(x: var sdl.Version) # This function gets the version of the dynamically linked SDL_mixer library. # It should NOT be used to fill a version structure, instead you should use the # SDL_MIXER_VERSION() macro. @@ -160,18 +165,18 @@ proc freeMusic*(music: PMusic){.cdecl, importc: "Mix_FreeMusic", dynlib: MixerLibName.} # Find out the music format of a mixer music, or the currently playing # music, if 'music' is NULL. -proc getMusicType*(music: PMusic): TMusicType{.cdecl, +proc getMusicType*(music: PMusic): MusicType{.cdecl, importc: "Mix_GetMusicType", dynlib: MixerLibName.} # Set a function that is called after all mixing is performed. # This can be used to provide real-time visual display of the audio stream # or add a custom mixer filter for the stream data. # -proc setPostMix*(mixfunc: TMixFunction, arg: pointer){.cdecl, +proc setPostMix*(mixfunc: MixFunction, arg: pointer){.cdecl, importc: "Mix_SetPostMix", dynlib: MixerLibName.} # Add your own music player or additional mixer function. # If 'mix_func' is NULL, the default music player is re-enabled. # -proc hookMusic*(mixFunc: TMixFunction, arg: pointer){.cdecl, +proc hookMusic*(mixFunc: MixFunction, arg: pointer){.cdecl, importc: "Mix_HookMusic", dynlib: MixerLibName.} # Add your own callback when the music has finished playing. # @@ -183,9 +188,10 @@ proc getMusicHookData*(): pointer{.cdecl, importc: "Mix_GetMusicHookData", #* Add your own callback when a channel has finished playing. NULL # * to disable callback.* type - TChannelFinished* = proc (channel: cint){.cdecl.} + ChannelFinished* = proc (channel: cint){.cdecl.} +{.deprecated: [TChannelFinished: ChannelFinished].} -proc channelFinished*(channelFinished: TChannelFinished){.cdecl, +proc channelFinished*(channelFinished: ChannelFinished){.cdecl, importc: "Mix_ChannelFinished", dynlib: MixerLibName.} const CHANNEL_POST* = - 2 @@ -286,9 +292,9 @@ proc fadeOutGroup*(tag: cint, ms: cint): cint{.cdecl, proc fadeOutMusic*(ms: cint): cint{.cdecl, importc: "Mix_FadeOutMusic", dynlib: MixerLibName.} # Query the fading status of a channel -proc fadingMusic*(): TFading{.cdecl, importc: "Mix_FadingMusic", +proc fadingMusic*(): Fading{.cdecl, importc: "Mix_FadingMusic", dynlib: MixerLibName.} -proc fadingChannel*(which: cint): TFading{.cdecl, +proc fadingChannel*(which: cint): Fading{.cdecl, importc: "Mix_FadingChannel", dynlib: MixerLibName.} # Pause/Resume a particular channel proc pause*(channel: cint){.cdecl, importc: "Mix_Pause", dynlib: MixerLibName.} @@ -335,7 +341,7 @@ proc getChunk*(channel: cint): PChunk{.cdecl, importc: "Mix_GetChunk", proc closeAudio*(){.cdecl, importc: "Mix_CloseAudio", dynlib: MixerLibName.} # We'll use SDL for reporting errors -proc version(x: var Tversion) = +proc version(x: var Version) = x.major = MAJOR_VERSION x.minor = MINOR_VERSION x.patch = PATCHLEVEL diff --git a/lib/wrappers/sdl/sdl_net.nim b/lib/wrappers/sdl/sdl_net.nim index 1ffdb5cca..5bde607f7 100644 --- a/lib/wrappers/sdl/sdl_net.nim +++ b/lib/wrappers/sdl/sdl_net.nim @@ -143,34 +143,34 @@ type # SDL_net.h types #*********************************************************************** #* IPv4 hostname resolution API * #*********************************************************************** - PIPAddress* = ptr TIPAddress - TIPAddress*{.final.} = object #* TCP network API + PIPAddress* = ptr IPAddress + IPAddress*{.final.} = object #* TCP network API host*: uint32 # 32-bit IPv4 host address */ port*: uint16 # 16-bit protocol port */ - PTCPSocket* = ptr TTCPSocket - TTCPSocket*{.final.} = object # UDP network API + PTCPSocket* = ptr TCPSocket + TCPSocket*{.final.} = object # UDP network API ready*: int channel*: int - remoteAddress*: TIPAddress - localAddress*: TIPAddress + remoteAddress*: IPAddress + localAddress*: IPAddress sflag*: int - PUDP_Channel* = ptr TUDP_Channel - TUDP_Channel*{.final.} = object + PUDP_Channel* = ptr UDP_Channel + UDP_Channel*{.final.} = object numbound*: int - address*: array[0..MAX_UDPADDRESSES - 1, TIPAddress] + address*: array[0..MAX_UDPADDRESSES - 1, IPAddress] - PUDPSocket* = ptr TUDPSocket - TUDPSocket*{.final.} = object + PUDPSocket* = ptr UDPSocket + UDPSocket*{.final.} = object ready*: int channel*: int - address*: TIPAddress - binding*: array[0..MAX_UDPCHANNELS - 1, TUDP_Channel] + address*: IPAddress + binding*: array[0..MAX_UDPCHANNELS - 1, UDP_Channel] - PUDPpacket* = ptr TUDPpacket + PUDPpacket* = ptr UDPpacket PPUDPpacket* = ptr PUDPpacket - TUDPpacket*{.final.} = object #*********************************************************************** + UDPpacket*{.final.} = object #*********************************************************************** #* Hooks for checking sockets for available data * #*********************************************************************** channel*: int #* The src/dst channel of the packet * @@ -178,25 +178,27 @@ type # SDL_net.h types length*: int #* The length of the packet data * maxlen*: int #* The size of the data buffer * status*: int #* packet status after sending * - address*: TIPAddress #* The source/dest address of an incoming/outgoing packet * + address*: IPAddress #* The source/dest address of an incoming/outgoing packet * - PSocket* = ptr TSocket - TSocket*{.final.} = object + PSocket* = ptr Socket + Socket*{.final.} = object ready*: int channel*: int - PSocketSet* = ptr TSocketSet - TSocketSet*{.final.} = object # Any network socket can be safely cast to this socket type * + PSocketSet* = ptr SocketSet + SocketSet*{.final.} = object # Any network socket can be safely cast to this socket type * numsockets*: int maxsockets*: int sockets*: PSocket - PGenericSocket* = ptr TGenericSocket - TGenericSocket*{.final.} = object + PGenericSocket* = ptr GenericSocket + GenericSocket*{.final.} = object ready*: int +{.deprecated: [TSocket: Socket, TSocketSet: SocketSet, TIPAddress: IpAddress, + TTCPSocket: TCPSocket, TUDP_Channel: UDP_Channel, TUDPSocket: UDPSocket, + TUDPpacket: UDPpacket, TGenericSocket: GenericSocket].} - -proc version*(x: var Tversion) +proc version*(x: var Version) #* Initialize/Cleanup the network API # SDL must be initialized before calls to functions in this library, # because this library uses utility functions from the SDL library. @@ -209,14 +211,14 @@ proc quit*(){.cdecl, importc: "SDLNet_Quit", dynlib: NetLibName.} # address will be INADDR_NONE, and the function will return -1. # If 'host' is NULL, the resolved host will be set to INADDR_ANY. # * -proc resolveHost*(address: var TIPAddress, host: cstring, port: uint16): int{. +proc resolveHost*(address: var IPAddress, host: cstring, port: uint16): int{. cdecl, importc: "SDLNet_ResolveHost", dynlib: NetLibName.} #* Resolve an ip address to a host name in canonical form. # If the ip couldn't be resolved, this function returns NULL, # otherwise a pointer to a static buffer containing the hostname # is returned. Note that this function is not thread-safe. #* -proc resolveIP*(ip: var TIPAddress): cstring{.cdecl, +proc resolveIP*(ip: var IPAddress): cstring{.cdecl, importc: "SDLNet_ResolveIP", dynlib: NetLibName.} #*********************************************************************** #* TCP network API * @@ -229,7 +231,7 @@ proc resolveIP*(ip: var TIPAddress): cstring{.cdecl, # in the correct form). # The newly created socket is returned, or NULL if there was an error. #* -proc tcpOpen*(ip: var TIPAddress): PTCPSocket{.cdecl, +proc tcpOpen*(ip: var IPAddress): PTCPSocket{.cdecl, importc: "SDLNet_TCP_Open", dynlib: NetLibName.} #* Accept an incoming connection on the given server socket. # The newly created socket is returned, or NULL if there was an error. @@ -295,7 +297,7 @@ proc udpOpen*(port: uint16): PUDPSocket{.cdecl, importc: "SDLNet_UDP_Open", # address, to which all outbound packets on the channel are sent. # This function returns the channel which was bound, or -1 on error. #* -proc udpBind*(sock: PUDPSocket, channel: int, address: var TIPAddress): int{. +proc udpBind*(sock: PUDPSocket, channel: int, address: var IPAddress): int{. cdecl, importc: "SDLNet_UDP_Bind", dynlib: NetLibName.} #* Unbind all addresses from the given channel * proc udpUnbind*(sock: PUDPSocket, channel: int){.cdecl, @@ -405,7 +407,7 @@ proc read16*(area: pointer): uint16{.cdecl, importc: "SDLNet_Read16", proc read32*(area: pointer): uint32{.cdecl, importc: "SDLNet_Read32", dynlib: NetLibName.} -proc version(x: var Tversion) = +proc version(x: var Version) = x.major = MAJOR_VERSION x.minor = MINOR_VERSION x.patch = PATCHLEVEL diff --git a/lib/wrappers/sdl/sdl_ttf.nim b/lib/wrappers/sdl/sdl_ttf.nim index 9ebe70b9d..06604f96e 100644 --- a/lib/wrappers/sdl/sdl_ttf.nim +++ b/lib/wrappers/sdl/sdl_ttf.nim @@ -177,8 +177,9 @@ const UNICODE_BOM_SWAPPED* = 0x0000FFFE type - PFont* = ptr TFont - TFont = object + PFont* = ptr Font + Font = object +{.deprecated: [TFont: Font].} # This macro can be used to fill a version structure with the compile-time @@ -256,9 +257,9 @@ proc sizeUNICODE*(font: PFont, text: PUInt16, w: var cint, y: var cint): cint{. # to the text color. # This function returns the new surface, or NULL if there was an error. # -proc renderUTF8Solid*(font: PFont, text: cstring, fg: TColor): PSurface{. +proc renderUTF8Solid*(font: PFont, text: cstring, fg: Color): PSurface{. cdecl, importc: "TTF_RenderUTF8_Solid", dynlib: ttfLibName.} -proc renderUNICODE_Solid*(font: PFont, text: PUInt16, fg: TColor): PSurface{. +proc renderUNICODE_Solid*(font: PFont, text: PUInt16, fg: Color): PSurface{. cdecl, importc: "TTF_RenderUNICODE_Solid", dynlib: ttfLibName.} # #Create an 8-bit palettized surface and render the given glyph at @@ -268,21 +269,21 @@ proc renderUNICODE_Solid*(font: PFont, text: PUInt16, fg: TColor): PSurface{. # centering in the X direction, and aligned normally in the Y direction. # This function returns the new surface, or NULL if there was an error. # -proc renderGlyphSolid*(font: PFont, ch: uint16, fg: TColor): PSurface{. +proc renderGlyphSolid*(font: PFont, ch: uint16, fg: Color): PSurface{. cdecl, importc: "TTF_RenderGlyph_Solid", dynlib: ttfLibName.} # Create an 8-bit palettized surface and render the given text at # high quality with the given font and colors. The 0 pixel is background, # while other pixels have varying degrees of the foreground color. # This function returns the new surface, or NULL if there was an error. # -proc renderTextShaded*(font: PFont, text: cstring, fg: TColor, - bg: TColor): PSurface{.cdecl, +proc renderTextShaded*(font: PFont, text: cstring, fg: Color, + bg: Color): PSurface{.cdecl, importc: "TTF_RenderText_Shaded", dynlib: ttfLibName.} -proc renderUTF8Shaded*(font: PFont, text: cstring, fg: TColor, - bg: TColor): PSurface{.cdecl, +proc renderUTF8Shaded*(font: PFont, text: cstring, fg: Color, + bg: Color): PSurface{.cdecl, importc: "TTF_RenderUTF8_Shaded", dynlib: ttfLibName.} -proc renderUNICODE_Shaded*(font: PFont, text: PUInt16, fg: TColor, - bg: TColor): PSurface{.cdecl, +proc renderUNICODE_Shaded*(font: PFont, text: PUInt16, fg: Color, + bg: Color): PSurface{.cdecl, importc: "TTF_RenderUNICODE_Shaded", dynlib: ttfLibName.} # Create an 8-bit palettized surface and render the given glyph at # high quality with the given font and colors. The 0 pixel is background, @@ -291,17 +292,17 @@ proc renderUNICODE_Shaded*(font: PFont, text: PUInt16, fg: TColor, # direction, and aligned normally in the Y direction. # This function returns the new surface, or NULL if there was an error. # -proc renderGlyphShaded*(font: PFont, ch: uint16, fg: TColor, bg: TColor): PSurface{. +proc renderGlyphShaded*(font: PFont, ch: uint16, fg: Color, bg: Color): PSurface{. cdecl, importc: "TTF_RenderGlyph_Shaded", dynlib: ttfLibName.} # Create a 32-bit ARGB surface and render the given text at high quality, # using alpha blending to dither the font with the given color. # This function returns the new surface, or NULL if there was an error. # -proc renderTextBlended*(font: PFont, text: cstring, fg: TColor): PSurface{. +proc renderTextBlended*(font: PFont, text: cstring, fg: Color): PSurface{. cdecl, importc: "TTF_RenderText_Blended", dynlib: ttfLibName.} -proc renderUTF8Blended*(font: PFont, text: cstring, fg: TColor): PSurface{. +proc renderUTF8Blended*(font: PFont, text: cstring, fg: Color): PSurface{. cdecl, importc: "TTF_RenderUTF8_Blended", dynlib: ttfLibName.} -proc RenderUNICODE_Blended*(font: PFont, text: PUInt16, fg: TColor): PSurface{. +proc RenderUNICODE_Blended*(font: PFont, text: PUInt16, fg: Color): PSurface{. cdecl, importc: "TTF_RenderUNICODE_Blended", dynlib: ttfLibName.} # Create a 32-bit ARGB surface and render the given glyph at high quality, # using alpha blending to dither the font with the given color. @@ -309,7 +310,7 @@ proc RenderUNICODE_Blended*(font: PFont, text: PUInt16, fg: TColor): PSurface{. # direction, and aligned normally in the Y direction. # This function returns the new surface, or NULL if there was an error. # -proc renderGlyphBlended*(font: PFont, ch: uint16, fg: TColor): PSurface{. +proc renderGlyphBlended*(font: PFont, ch: uint16, fg: Color): PSurface{. cdecl, importc: "TTF_RenderGlyph_Blended", dynlib: ttfLibName.} # For compatibility with previous versions, here are the old functions # #define TTF_RenderText(font, text, fg, bg) @@ -327,11 +328,11 @@ proc quit*(){.cdecl, importc: "TTF_Quit", dynlib: ttfLibName.} proc wasInit*(): cint{.cdecl, importc: "TTF_WasInit", dynlib: ttfLibName.} -proc version*(x: var sdl.Tversion) = +proc version*(x: var sdl.Version) = x.major = MAJOR_VERSION x.minor = MINOR_VERSION x.patch = PATCHLEVEL -proc renderTextSolid*(font: PFont, text: cstring, fg: TColor): PSurface{. +proc renderTextSolid*(font: PFont, text: cstring, fg: Color): PSurface{. cdecl, importc: "TTF_RenderText_Solid", dynlib: ttfLibName.} diff --git a/lib/wrappers/sdl/smpeg.nim b/lib/wrappers/sdl/smpeg.nim index 318c0b3df..57c16fa47 100644 --- a/lib/wrappers/sdl/smpeg.nim +++ b/lib/wrappers/sdl/smpeg.nim @@ -142,22 +142,23 @@ const FILTER_INFO_PIXEL_ERROR* = 2 # Filter info from SMPEG type - TFilterInfo*{.final.} = object + FilterInfo*{.final.} = object yuvMbSquareError*: PUInt16 yuvPixelSquareError*: PUInt16 - PFilterInfo* = ptr TFilterInfo # MPEG filter definition - PFilter* = ptr TFilter # Callback functions for the filter - TFilterCallback* = proc (dest, source: POverlay, region: PRect, + PFilterInfo* = ptr FilterInfo # MPEG filter definition + PFilter* = ptr Filter # Callback functions for the filter + FilterCallback* = proc (dest, source: POverlay, region: PRect, filterInfo: PFilterInfo, data: pointer): pointer{. cdecl.} - TFilterDestroy* = proc (filter: PFilter): pointer{.cdecl.} # The filter definition itself - TFilter*{.final.} = object # The null filter (default). It simply copies the source rectangle to the video overlay. + FilterDestroy* = proc (filter: PFilter): pointer{.cdecl.} # The filter definition itself + Filter*{.final.} = object # The null filter (default). It simply copies the source rectangle to the video overlay. flags*: uint32 data*: pointer - callback*: TFilterCallback - destroy*: TFilterDestroy - + callback*: FilterCallback + destroy*: FilterDestroy +{.deprecated: [TFilterInfo: FilterInfo, TFilterCallback: FilterCallback, + TFilterDestroy: FilterDestroy, TFilter: Filter].} proc filterNull*(): PFilter{.cdecl, importc: "SMPEGfilter_null", dynlib: SmpegLibName.} @@ -184,7 +185,7 @@ type Pversion* = ptr TVersion # This is the actual SMPEG object TSMPEG* = object PSMPEG* = ptr TSMPEG # Used to get information about the SMPEG object - TInfo* = object + Info* = object hasAudio*: int32 hasVideo*: int32 width*: int32 @@ -198,7 +199,8 @@ type currentTime*: float64 totalTime*: float64 - PInfo* = ptr TInfo # Possible MPEG status codes + PInfo* = ptr Info # Possible MPEG status codes +{.deprecated: [TInfo: Info].} const STATUS_ERROR* = - 1 @@ -206,7 +208,7 @@ const STATUS_PLAYING* = 1 type - Tstatus* = int32 + Status* = int32 Pstatus* = ptr int32 # Matches the declaration of SDL_UpdateRect() TDisplayCallback* = proc (dst: PSurface, x, y: int, w, h: int): pointer{. cdecl.} # Create a new SMPEG object from an MPEG file. @@ -217,6 +219,7 @@ type # The sdl_audio parameter indicates if SMPEG should initialize the SDL audio # subsystem. If not, you will have to use the playaudio() function below # to extract the decoded data. +{.deprecated: [Tstatus: Status].} proc new*(theFile: cstring, info: PInfo, audio: int): PSMPEG{.cdecl, importc: "SMPEG_new", dynlib: SmpegLibName.} @@ -243,7 +246,7 @@ proc enablevideo*(mpeg: PSMPEG, enable: int){.cdecl, proc delete*(mpeg: PSMPEG){.cdecl, importc: "SMPEG_delete", dynlib: SmpegLibName.} # Get the current status of an SMPEG object -proc status*(mpeg: PSMPEG): Tstatus{.cdecl, importc: "SMPEG_status", +proc status*(mpeg: PSMPEG): Status{.cdecl, importc: "SMPEG_status", dynlib: SmpegLibName.} # status # Set the audio volume of an MPEG stream, in the range 0-100 diff --git a/lib/wrappers/sphinx.nim b/lib/wrappers/sphinx.nim index e4a282968..d9e98faa8 100644 --- a/lib/wrappers/sphinx.nim +++ b/lib/wrappers/sphinx.nim @@ -96,18 +96,18 @@ const SPH_GROUPBY_ATTRPAIR* = 5 type - TSphinxBool* {.size: sizeof(cint).} = enum + SphinxBool* {.size: sizeof(cint).} = enum SPH_FALSE = 0, SPH_TRUE = 1 - Tclient {.pure, final.} = object - PClient* = ptr TClient - Twordinfo*{.pure, final.} = object + Client {.pure, final.} = object + PClient* = ptr Client + Wordinfo*{.pure, final.} = object word*: cstring docs*: cint hits*: cint - Tresult*{.pure, final.} = object + Result*{.pure, final.} = object error*: cstring warning*: cstring status*: cint @@ -122,9 +122,9 @@ type total_found*: cint time_msec*: cint num_words*: cint - words*: ptr array [0..100_000, TWordinfo] + words*: ptr array [0..100_000, Wordinfo] - Texcerpt_options*{.pure, final.} = object + Excerpt_options*{.pure, final.} = object before_match*: cstring after_match*: cstring chunk_separator*: cstring @@ -135,24 +135,26 @@ type limit_words*: cint around*: cint start_passage_id*: cint - exact_phrase*: TSphinxBool - single_passage*: TSphinxBool - use_boundaries*: TSphinxBool - weight_order*: TSphinxBool - query_mode*: TSphinxBool - force_all_words*: TSphinxBool - load_files*: TSphinxBool - allow_empty*: TSphinxBool - emit_zones*: TSphinxBool + exact_phrase*: SphinxBool + single_passage*: SphinxBool + use_boundaries*: SphinxBool + weight_order*: SphinxBool + query_mode*: SphinxBool + force_all_words*: SphinxBool + load_files*: SphinxBool + allow_empty*: SphinxBool + emit_zones*: SphinxBool - Tkeyword_info*{.pure, final.} = object + Keyword_info*{.pure, final.} = object tokenized*: cstring normalized*: cstring num_docs*: cint num_hits*: cint +{.deprecated: [TSphinxBool: SphinxBool, + Tclient: Client, Twordinfo: Wordinfo, Tresult: Result, + Texcerpt_options: Excerpt_options, Tkeyword_info: Keyword_info].} - -proc create*(copy_args: TSphinxBool): PClient{.cdecl, importc: "sphinx_create", +proc create*(copy_args: SphinxBool): PClient{.cdecl, importc: "sphinx_create", dynlib: sphinxDll.} proc cleanup*(client: PClient){.cdecl, importc: "sphinx_cleanup", dynlib: sphinxDll.} @@ -162,87 +164,87 @@ proc error*(client: PClient): cstring{.cdecl, importc: "sphinx_error", dynlib: sphinxDll.} proc warning*(client: PClient): cstring{.cdecl, importc: "sphinx_warning", dynlib: sphinxDll.} -proc set_server*(client: PClient, host: cstring, port: cint): TSphinxBool{.cdecl, +proc set_server*(client: PClient, host: cstring, port: cint): SphinxBool{.cdecl, importc: "sphinx_set_server", dynlib: sphinxDll.} -proc set_connect_timeout*(client: PClient, seconds: float32): TSphinxBool{.cdecl, +proc set_connect_timeout*(client: PClient, seconds: float32): SphinxBool{.cdecl, importc: "sphinx_set_connect_timeout", dynlib: sphinxDll.} -proc open*(client: PClient): TSphinxBool{.cdecl, importc: "sphinx_open", +proc open*(client: PClient): SphinxBool{.cdecl, importc: "sphinx_open", dynlib: sphinxDll.} -proc close*(client: PClient): TSphinxBool{.cdecl, importc: "sphinx_close", +proc close*(client: PClient): SphinxBool{.cdecl, importc: "sphinx_close", dynlib: sphinxDll.} proc set_limits*(client: PClient, offset: cint, limit: cint, - max_matches: cint, cutoff: cint): TSphinxBool{.cdecl, + max_matches: cint, cutoff: cint): SphinxBool{.cdecl, importc: "sphinx_set_limits", dynlib: sphinxDll.} -proc set_max_query_time*(client: PClient, max_query_time: cint): TSphinxBool{. +proc set_max_query_time*(client: PClient, max_query_time: cint): SphinxBool{. cdecl, importc: "sphinx_set_max_query_time", dynlib: sphinxDll.} -proc set_match_mode*(client: PClient, mode: cint): TSphinxBool{.cdecl, +proc set_match_mode*(client: PClient, mode: cint): SphinxBool{.cdecl, importc: "sphinx_set_match_mode", dynlib: sphinxDll.} -proc set_ranking_mode*(client: PClient, ranker: cint): TSphinxBool{.cdecl, +proc set_ranking_mode*(client: PClient, ranker: cint): SphinxBool{.cdecl, importc: "sphinx_set_ranking_mode", dynlib: sphinxDll.} -proc set_sort_mode*(client: PClient, mode: cint, sortby: cstring): TSphinxBool{. +proc set_sort_mode*(client: PClient, mode: cint, sortby: cstring): SphinxBool{. cdecl, importc: "sphinx_set_sort_mode", dynlib: sphinxDll.} proc set_field_weights*(client: PClient, num_weights: cint, - field_names: cstringArray, field_weights: ptr cint): TSphinxBool{. + field_names: cstringArray, field_weights: ptr cint): SphinxBool{. cdecl, importc: "sphinx_set_field_weights", dynlib: sphinxDll.} proc set_index_weights*(client: PClient, num_weights: cint, - index_names: cstringArray, index_weights: ptr cint): TSphinxBool{. + index_names: cstringArray, index_weights: ptr cint): SphinxBool{. cdecl, importc: "sphinx_set_index_weights", dynlib: sphinxDll.} -proc set_id_range*(client: PClient, minid: int64, maxid: int64): TSphinxBool{. +proc set_id_range*(client: PClient, minid: int64, maxid: int64): SphinxBool{. cdecl, importc: "sphinx_set_id_range", dynlib: sphinxDll.} proc add_filter*(client: PClient, attr: cstring, num_values: cint, - values: ptr int64, exclude: TSphinxBool): TSphinxBool{.cdecl, + values: ptr int64, exclude: SphinxBool): SphinxBool{.cdecl, importc: "sphinx_add_filter", dynlib: sphinxDll.} proc add_filter_range*(client: PClient, attr: cstring, umin: int64, - umax: int64, exclude: TSphinxBool): TSphinxBool{.cdecl, + umax: int64, exclude: SphinxBool): SphinxBool{.cdecl, importc: "sphinx_add_filter_range", dynlib: sphinxDll.} proc add_filter_float_range*(client: PClient, attr: cstring, fmin: float32, - fmax: float32, exclude: TSphinxBool): TSphinxBool{.cdecl, + fmax: float32, exclude: SphinxBool): SphinxBool{.cdecl, importc: "sphinx_add_filter_float_range", dynlib: sphinxDll.} proc set_geoanchor*(client: PClient, attr_latitude: cstring, - attr_longitude: cstring, latitude: float32, longitude: float32): TSphinxBool{. + attr_longitude: cstring, latitude: float32, longitude: float32): SphinxBool{. cdecl, importc: "sphinx_set_geoanchor", dynlib: sphinxDll.} proc set_groupby*(client: PClient, attr: cstring, groupby_func: cint, - group_sort: cstring): TSphinxBool{.cdecl, + group_sort: cstring): SphinxBool{.cdecl, importc: "sphinx_set_groupby", dynlib: sphinxDll.} -proc set_groupby_distinct*(client: PClient, attr: cstring): TSphinxBool{.cdecl, +proc set_groupby_distinct*(client: PClient, attr: cstring): SphinxBool{.cdecl, importc: "sphinx_set_groupby_distinct", dynlib: sphinxDll.} -proc set_retries*(client: PClient, count: cint, delay: cint): TSphinxBool{.cdecl, +proc set_retries*(client: PClient, count: cint, delay: cint): SphinxBool{.cdecl, importc: "sphinx_set_retries", dynlib: sphinxDll.} proc add_override*(client: PClient, attr: cstring, docids: ptr int64, - num_values: cint, values: ptr cint): TSphinxBool{.cdecl, + num_values: cint, values: ptr cint): SphinxBool{.cdecl, importc: "sphinx_add_override", dynlib: sphinxDll.} -proc set_select*(client: PClient, select_list: cstring): TSphinxBool{.cdecl, +proc set_select*(client: PClient, select_list: cstring): SphinxBool{.cdecl, importc: "sphinx_set_select", dynlib: sphinxDll.} proc reset_filters*(client: PClient){.cdecl, importc: "sphinx_reset_filters", dynlib: sphinxDll.} proc reset_groupby*(client: PClient){.cdecl, importc: "sphinx_reset_groupby", dynlib: sphinxDll.} proc query*(client: PClient, query: cstring, index_list: cstring, - comment: cstring): ptr Tresult{.cdecl, importc: "sphinx_query", + comment: cstring): ptr Result{.cdecl, importc: "sphinx_query", dynlib: sphinxDll.} proc add_query*(client: PClient, query: cstring, index_list: cstring, comment: cstring): cint{.cdecl, importc: "sphinx_add_query", dynlib: sphinxDll.} -proc run_queries*(client: PClient): ptr Tresult{.cdecl, +proc run_queries*(client: PClient): ptr Result{.cdecl, importc: "sphinx_run_queries", dynlib: sphinxDll.} proc get_num_results*(client: PClient): cint{.cdecl, importc: "sphinx_get_num_results", dynlib: sphinxDll.} -proc get_id*(result: ptr Tresult, match: cint): int64{.cdecl, +proc get_id*(result: ptr Result, match: cint): int64{.cdecl, importc: "sphinx_get_id", dynlib: sphinxDll.} -proc get_weight*(result: ptr Tresult, match: cint): cint{.cdecl, +proc get_weight*(result: ptr Result, match: cint): cint{.cdecl, importc: "sphinx_get_weight", dynlib: sphinxDll.} -proc get_int*(result: ptr Tresult, match: cint, attr: cint): int64{.cdecl, +proc get_int*(result: ptr Result, match: cint, attr: cint): int64{.cdecl, importc: "sphinx_get_int", dynlib: sphinxDll.} -proc get_float*(result: ptr Tresult, match: cint, attr: cint): float32{.cdecl, +proc get_float*(result: ptr Result, match: cint, attr: cint): float32{.cdecl, importc: "sphinx_get_float", dynlib: sphinxDll.} -proc get_mva*(result: ptr Tresult, match: cint, attr: cint): ptr cint{. +proc get_mva*(result: ptr Result, match: cint, attr: cint): ptr cint{. cdecl, importc: "sphinx_get_mva", dynlib: sphinxDll.} -proc get_string*(result: ptr Tresult, match: cint, attr: cint): cstring{.cdecl, +proc get_string*(result: ptr Result, match: cint, attr: cint): cstring{.cdecl, importc: "sphinx_get_string", dynlib: sphinxDll.} -proc init_excerpt_options*(opts: ptr Texcerpt_options){.cdecl, +proc init_excerpt_options*(opts: ptr Excerpt_options){.cdecl, importc: "sphinx_init_excerpt_options", dynlib: sphinxDll.} proc build_excerpts*(client: PClient, num_docs: cint, docs: cstringArray, - index: cstring, words: cstring, opts: ptr Texcerpt_options): cstringArray{. + index: cstring, words: cstring, opts: ptr Excerpt_options): cstringArray{. cdecl, importc: "sphinx_build_excerpts", dynlib: sphinxDll.} proc update_attributes*(client: PClient, index: cstring, num_attrs: cint, attrs: cstringArray, num_docs: cint, @@ -253,7 +255,7 @@ proc update_attributes_mva*(client: PClient, index: cstring, attr: cstring, values: ptr cint): cint{.cdecl, importc: "sphinx_update_attributes_mva", dynlib: sphinxDll.} proc build_keywords*(client: PClient, query: cstring, index: cstring, - hits: TSphinxBool, out_num_keywords: ptr cint): ptr Tkeyword_info{. + hits: SphinxBool, out_num_keywords: ptr cint): ptr Keyword_info{. cdecl, importc: "sphinx_build_keywords", dynlib: sphinxDll.} proc status*(client: PClient, num_rows: ptr cint, num_cols: ptr cint): cstringArray{. cdecl, importc: "sphinx_status", dynlib: sphinxDll.} diff --git a/lib/wrappers/sqlite3.nim b/lib/wrappers/sqlite3.nim index e3a3fa0b8..8dacb15e7 100644 --- a/lib/wrappers/sqlite3.nim +++ b/lib/wrappers/sqlite3.nim @@ -97,33 +97,39 @@ const SQLITE_TRANSIENT* = cast[pointer](- 1) type - TSqlite3 {.pure, final.} = object - PSqlite3* = ptr TSqlite3 + Sqlite3 {.pure, final.} = object + PSqlite3* = ptr Sqlite3 PPSqlite3* = ptr PSqlite3 - TContext{.pure, final.} = object - Pcontext* = ptr TContext + Context{.pure, final.} = object + Pcontext* = ptr Context Tstmt{.pure, final.} = object Pstmt* = ptr Tstmt - Tvalue{.pure, final.} = object - Pvalue* = ptr Tvalue + Value{.pure, final.} = object + Pvalue* = ptr Value PValueArg* = array[0..127, Pvalue] - Tcallback* = proc (para1: pointer, para2: int32, para3, + Callback* = proc (para1: pointer, para2: int32, para3, para4: cstringArray): int32{.cdecl.} Tbind_destructor_func* = proc (para1: pointer){.cdecl.} - Tcreate_function_step_func* = proc (para1: Pcontext, para2: int32, + Create_function_step_func* = proc (para1: Pcontext, para2: int32, para3: PValueArg){.cdecl.} - Tcreate_function_func_func* = proc (para1: Pcontext, para2: int32, + Create_function_func_func* = proc (para1: Pcontext, para2: int32, para3: PValueArg){.cdecl.} - Tcreate_function_final_func* = proc (para1: Pcontext){.cdecl.} - Tresult_func* = proc (para1: pointer){.cdecl.} - Tcreate_collation_func* = proc (para1: pointer, para2: int32, para3: pointer, + Create_function_final_func* = proc (para1: Pcontext){.cdecl.} + Result_func* = proc (para1: pointer){.cdecl.} + Create_collation_func* = proc (para1: pointer, para2: int32, para3: pointer, para4: int32, para5: pointer): int32{.cdecl.} - Tcollation_needed_func* = proc (para1: pointer, para2: PSqlite3, eTextRep: int32, + Collation_needed_func* = proc (para1: pointer, para2: PSqlite3, eTextRep: int32, para4: cstring){.cdecl.} +{.deprecated: [TSqlite3: Sqlite3, TContext: Context, Tvalue: Value, + Tcallback: Callback, Tcreate_function_step_func: Create_function_step_func, + Tcreate_function_func_func: Create_function_func_func, + Tcreate_function_final_func: Create_function_final_func, + Tresult_func: Result_func, Tcreate_collation_func: Create_collation_func, + Tcollation_needed_func: Collation_needed_func].} proc close*(para1: PSqlite3): int32{.cdecl, dynlib: Lib, importc: "sqlite3_close".} -proc exec*(para1: PSqlite3, sql: cstring, para3: Tcallback, para4: pointer, +proc exec*(para1: PSqlite3, sql: cstring, para3: Callback, para4: pointer, errmsg: var cstring): int32{.cdecl, dynlib: Lib, importc: "sqlite3_exec".} proc last_insert_rowid*(para1: PSqlite3): int64{.cdecl, dynlib: Lib, @@ -261,15 +267,15 @@ proc finalize*(pStmt: Pstmt): int32{.cdecl, dynlib: Lib, proc reset*(pStmt: Pstmt): int32{.cdecl, dynlib: Lib, importc: "sqlite3_reset".} proc create_function*(para1: PSqlite3, zFunctionName: cstring, nArg: int32, eTextRep: int32, para5: pointer, - xFunc: Tcreate_function_func_func, - xStep: Tcreate_function_step_func, - xFinal: Tcreate_function_final_func): int32{.cdecl, + xFunc: Create_function_func_func, + xStep: Create_function_step_func, + xFinal: Create_function_final_func): int32{.cdecl, dynlib: Lib, importc: "sqlite3_create_function".} proc create_function16*(para1: PSqlite3, zFunctionName: pointer, nArg: int32, eTextRep: int32, para5: pointer, - xFunc: Tcreate_function_func_func, - xStep: Tcreate_function_step_func, - xFinal: Tcreate_function_final_func): int32{.cdecl, + xFunc: Create_function_func_func, + xStep: Create_function_step_func, + xFinal: Create_function_final_func): int32{.cdecl, dynlib: Lib, importc: "sqlite3_create_function16".} proc aggregate_count*(para1: Pcontext): int32{.cdecl, dynlib: Lib, importc: "sqlite3_aggregate_count".} @@ -305,7 +311,7 @@ proc set_auxdata*(para1: Pcontext, para2: int32, para3: pointer, para4: proc (para1: pointer){.cdecl.}){.cdecl, dynlib: Lib, importc: "sqlite3_set_auxdata".} proc result_blob*(para1: Pcontext, para2: pointer, para3: int32, - para4: Tresult_func){.cdecl, dynlib: Lib, + para4: Result_func){.cdecl, dynlib: Lib, importc: "sqlite3_result_blob".} proc result_double*(para1: Pcontext, para2: float64){.cdecl, dynlib: Lib, importc: "sqlite3_result_double".} @@ -320,28 +326,28 @@ proc result_int64*(para1: Pcontext, para2: int64){.cdecl, dynlib: Lib, proc result_null*(para1: Pcontext){.cdecl, dynlib: Lib, importc: "sqlite3_result_null".} proc result_text*(para1: Pcontext, para2: cstring, para3: int32, - para4: Tresult_func){.cdecl, dynlib: Lib, + para4: Result_func){.cdecl, dynlib: Lib, importc: "sqlite3_result_text".} proc result_text16*(para1: Pcontext, para2: pointer, para3: int32, - para4: Tresult_func){.cdecl, dynlib: Lib, + para4: Result_func){.cdecl, dynlib: Lib, importc: "sqlite3_result_text16".} proc result_text16le*(para1: Pcontext, para2: pointer, para3: int32, - para4: Tresult_func){.cdecl, dynlib: Lib, + para4: Result_func){.cdecl, dynlib: Lib, importc: "sqlite3_result_text16le".} proc result_text16be*(para1: Pcontext, para2: pointer, para3: int32, - para4: Tresult_func){.cdecl, dynlib: Lib, + para4: Result_func){.cdecl, dynlib: Lib, importc: "sqlite3_result_text16be".} proc result_value*(para1: Pcontext, para2: Pvalue){.cdecl, dynlib: Lib, importc: "sqlite3_result_value".} proc create_collation*(para1: PSqlite3, zName: cstring, eTextRep: int32, - para4: pointer, xCompare: Tcreate_collation_func): int32{. + para4: pointer, xCompare: Create_collation_func): int32{. cdecl, dynlib: Lib, importc: "sqlite3_create_collation".} proc create_collation16*(para1: PSqlite3, zName: cstring, eTextRep: int32, - para4: pointer, xCompare: Tcreate_collation_func): int32{. + para4: pointer, xCompare: Create_collation_func): int32{. cdecl, dynlib: Lib, importc: "sqlite3_create_collation16".} -proc collation_needed*(para1: PSqlite3, para2: pointer, para3: Tcollation_needed_func): int32{. +proc collation_needed*(para1: PSqlite3, para2: pointer, para3: Collation_needed_func): int32{. cdecl, dynlib: Lib, importc: "sqlite3_collation_needed".} -proc collation_needed16*(para1: PSqlite3, para2: pointer, para3: Tcollation_needed_func): int32{. +proc collation_needed16*(para1: PSqlite3, para2: pointer, para3: Collation_needed_func): int32{. cdecl, dynlib: Lib, importc: "sqlite3_collation_needed16".} proc libversion*(): cstring{.cdecl, dynlib: Lib, importc: "sqlite3_libversion".} #Alias for allowing better code portability (win32 is not working with external variables) diff --git a/lib/wrappers/tinyc.nim b/lib/wrappers/tinyc.nim index ac6cb70f1..05c65b12f 100644 --- a/lib/wrappers/tinyc.nim +++ b/lib/wrappers/tinyc.nim @@ -8,10 +8,11 @@ # type - TccState {.pure, final.} = object - PccState* = ptr TccState + CcState {.pure, final.} = object + PccState* = ptr CcState - TErrorFunc* = proc (opaque: pointer, msg: cstring) {.cdecl.} + ErrorFunc* = proc (opaque: pointer, msg: cstring) {.cdecl.} +{.deprecated: [TccState: CcState, TErrorFunc: ErrorFunc].} proc openCCState*(): PccState {.importc: "tcc_new", cdecl.} ## create a new TCC compilation context @@ -22,7 +23,7 @@ proc closeCCState*(s: PccState) {.importc: "tcc_delete", cdecl.} proc enableDebug*(s: PccState) {.importc: "tcc_enable_debug", cdecl.} ## add debug information in the generated code -proc setErrorFunc*(s: PccState, errorOpaque: pointer, errorFun: TErrorFunc) {. +proc setErrorFunc*(s: PccState, errorOpaque: pointer, errorFun: ErrorFunc) {. cdecl, importc: "tcc_set_error_func".} ## set error/warning display callback diff --git a/lib/wrappers/tre.nim b/lib/wrappers/tre.nim index 92cd16333..36bf3cb69 100644 --- a/lib/wrappers/tre.nim +++ b/lib/wrappers/tre.nim @@ -27,16 +27,16 @@ const # structs and enums ourselves. type - TRegoff* = cint - TRegex*{.pure, final.} = object + Regoff* = cint + Regex*{.pure, final.} = object re_nsub*: int ## Number of parenthesized subexpressions. value*: pointer ## For internal use only. - TRegmatch*{.pure, final.} = object - rm_so*: TRegoff - rm_eo*: TRegoff + Regmatch*{.pure, final.} = object + rm_so*: Regoff + rm_eo*: Regoff - TReg_errcode*{.size: 4.} = enum ## POSIX tre_regcomp() return error codes. + Reg_errcode*{.size: 4.} = enum ## POSIX tre_regcomp() return error codes. ## (In the order listed in the standard.) REG_OK = 0, ## No error. REG_NOMATCH, ## No match. @@ -52,6 +52,8 @@ type REG_ERANGE, ## Invalid use of range operator REG_ESPACE, ## Out of memory. REG_BADRPT ## Invalid use of repetition operators. +{.deprecated: [TRegoff: Regoff, TRegex: Regex, TRegmatch: Regmatch, + TReg_errcode: Reg_errcode].} # POSIX tre_regcomp() flags. @@ -88,22 +90,22 @@ const # The POSIX.2 regexp functions -proc regcomp*(preg: var TRegex, regex: cstring, cflags: cint): cint{.cdecl, +proc regcomp*(preg: var Regex, regex: cstring, cflags: cint): cint{.cdecl, importc: "tre_regcomp", dynlib: treDll.} -proc regexec*(preg: var TRegex, string: cstring, nmatch: int, - pmatch: ptr TRegmatch, eflags: cint): cint{.cdecl, +proc regexec*(preg: var Regex, string: cstring, nmatch: int, + pmatch: ptr Regmatch, eflags: cint): cint{.cdecl, importc: "tre_regexec", dynlib: treDll.} -proc regerror*(errcode: cint, preg: var TRegex, errbuf: cstring, +proc regerror*(errcode: cint, preg: var Regex, errbuf: cstring, errbuf_size: int): int{.cdecl, importc: "tre_regerror", dynlib: treDll.} -proc regfree*(preg: var TRegex){.cdecl, importc: "tre_regfree", dynlib: treDll.} +proc regfree*(preg: var Regex){.cdecl, importc: "tre_regfree", dynlib: treDll.} # Versions with a maximum length argument and therefore the capability to # handle null characters in the middle of the strings (not in POSIX.2). -proc regncomp*(preg: var TRegex, regex: cstring, len: int, cflags: cint): cint{. +proc regncomp*(preg: var Regex, regex: cstring, len: int, cflags: cint): cint{. cdecl, importc: "tre_regncomp", dynlib: treDll.} -proc regnexec*(preg: var TRegex, string: cstring, len: int, nmatch: int, - pmatch: ptr TRegmatch, eflags: cint): cint{.cdecl, +proc regnexec*(preg: var Regex, string: cstring, len: int, nmatch: int, + pmatch: ptr Regmatch, eflags: cint): cint{.cdecl, importc: "tre_regnexec", dynlib: treDll.} # Approximate matching parameter struct. @@ -124,7 +126,7 @@ type type TRegamatch*{.pure, final.} = object nmatch*: int ## Length of pmatch[] array. - pmatch*: ptr TRegmatch ## Submatch data. + pmatch*: ptr Regmatch ## Submatch data. cost*: cint ## Cost of the match. num_ins*: cint ## Number of inserts in the match. num_del*: cint ## Number of deletes in the match. @@ -133,10 +135,10 @@ type # Approximate matching functions. -proc regaexec*(preg: var TRegex, string: cstring, match: ptr TRegamatch, +proc regaexec*(preg: var Regex, string: cstring, match: ptr TRegamatch, params: TRegaparams, eflags: cint): cint{.cdecl, importc: "tre_regaexec", dynlib: treDll.} -proc reganexec*(preg: var TRegex, string: cstring, len: int, +proc reganexec*(preg: var Regex, string: cstring, len: int, match: ptr TRegamatch, params: TRegaparams, eflags: cint): cint{. cdecl, importc: "tre_reganexec", dynlib: treDll.} @@ -155,8 +157,8 @@ type context*: pointer -proc reguexec*(preg: var TRegex, string: ptr TStrSource, nmatch: int, - pmatch: ptr TRegmatch, eflags: cint): cint{.cdecl, +proc reguexec*(preg: var Regex, string: ptr TStrSource, nmatch: int, + pmatch: ptr Regmatch, eflags: cint): cint{.cdecl, importc: "tre_reguexec", dynlib: treDll.} proc runtimeVersion*(): cstring{.cdecl, importc: "tre_version", dynlib: treDll.} @@ -177,10 +179,10 @@ const # Returns 1 if the compiled pattern has back references, 0 if not. -proc have_backrefs*(preg: var TRegex): cint{.cdecl, +proc have_backrefs*(preg: var Regex): cint{.cdecl, importc: "tre_have_backrefs", dynlib: treDll.} # Returns 1 if the compiled pattern uses approximate matching features, # 0 if not. -proc have_approx*(preg: var TRegex): cint{.cdecl, importc: "tre_have_approx", +proc have_approx*(preg: var Regex): cint{.cdecl, importc: "tre_have_approx", dynlib: treDll.} diff --git a/lib/wrappers/zip/libzip.nim b/lib/wrappers/zip/libzip.nim index 86670b450..076965d46 100644 --- a/lib/wrappers/zip/libzip.nim +++ b/lib/wrappers/zip/libzip.nim @@ -59,12 +59,12 @@ else: {.pragma: mydll.} type - TZipSourceCmd* = int32 + ZipSourceCmd* = int32 - TZipSourceCallback* = proc (state: pointer, data: pointer, length: int, - cmd: TZipSourceCmd): int {.cdecl.} - PZipStat* = ptr TZipStat - TZipStat* = object ## the 'zip_stat' struct + ZipSourceCallback* = proc (state: pointer, data: pointer, length: int, + cmd: ZipSourceCmd): int {.cdecl.} + PZipStat* = ptr ZipStat + ZipStat* = object ## the 'zip_stat' struct name*: cstring ## name of the file index*: int32 ## index within archive crc*: int32 ## crc of file data @@ -74,14 +74,16 @@ type compMethod*: int16 ## compression method used encryptionMethod*: int16 ## encryption method used - TZip = object - TZipSource = object - TZipFile = object - - PZip* = ptr TZip ## represents a zip archive - PZipFile* = ptr TZipFile ## represents a file within an archive - PZipSource* = ptr TZipSource ## represents a source for an archive + Zip = object + ZipSource = object + ZipFile = object + PZip* = ptr Zip ## represents a zip archive + PZipFile* = ptr ZipFile ## represents a file within an archive + PZipSource* = ptr ZipSource ## represents a source for an archive +{.deprecated: [TZipSourceCmd: ZipSourceCmd, TZipStat: ZipStat, TZip: Zip, + TZipSourceCallback: ZipSourceCallback, TZipSource: ZipSource, + TZipFile: ZipFile].} # flags for zip_name_locate, zip_fopen, zip_stat, ... const @@ -229,7 +231,7 @@ proc zip_source_filep*(para1: PZip, para2: File, para3: int, para4: int): PZipSo cdecl, mydll, importc: "zip_source_filep".} proc zip_source_free*(para1: PZipSource) {.cdecl, mydll, importc: "zip_source_free".} -proc zip_source_function*(para1: PZip, para2: TZipSourceCallback, +proc zip_source_function*(para1: PZip, para2: ZipSourceCallback, para3: pointer): PZipSource {.cdecl, mydll, importc: "zip_source_function".} proc zip_source_zip*(para1: PZip, para2: PZip, para3: int32, para4: int32, diff --git a/lib/wrappers/zip/zlib.nim b/lib/wrappers/zip/zlib.nim index 8bdb47106..6bb582b79 100644 --- a/lib/wrappers/zip/zlib.nim +++ b/lib/wrappers/zip/zlib.nim @@ -17,11 +17,11 @@ type ZOffT* = int32 Pbyte* = cstring Pbytef* = cstring - TAllocfunc* = proc (p: pointer, items: Uint, size: Uint): pointer{.cdecl.} - TFreeFunc* = proc (p: pointer, address: pointer){.cdecl.} - TInternalState*{.final, pure.} = object - PInternalState* = ptr TInternalState - TZStream*{.final, pure.} = object + Allocfunc* = proc (p: pointer, items: Uint, size: Uint): pointer{.cdecl.} + FreeFunc* = proc (p: pointer, address: pointer){.cdecl.} + InternalState*{.final, pure.} = object + PInternalState* = ptr InternalState + ZStream*{.final, pure.} = object nextIn*: Pbytef availIn*: Uint totalIn*: Ulong @@ -30,16 +30,18 @@ type totalOut*: Ulong msg*: Pbytef state*: PInternalState - zalloc*: TAllocfunc - zfree*: TFreeFunc + zalloc*: Allocfunc + zfree*: FreeFunc opaque*: pointer dataType*: int32 adler*: Ulong reserved*: Ulong - TZStreamRec* = TZStream - PZstream* = ptr TZStream + ZStreamRec* = ZStream + PZstream* = ptr ZStream GzFile* = pointer +{.deprecated: [TInternalState: InternalState, TAllocfunc: Allocfunc, + TFreeFunc: FreeFunc, TZStream: ZStream, TZStreamRec: ZStreamRec].} const Z_NO_FLUSH* = 0 @@ -70,29 +72,29 @@ const Z_NULL* = 0 proc zlibVersion*(): cstring{.cdecl, dynlib: libz, importc: "zlibVersion".} -proc deflate*(strm: var TZStream, flush: int32): int32{.cdecl, dynlib: libz, +proc deflate*(strm: var ZStream, flush: int32): int32{.cdecl, dynlib: libz, importc: "deflate".} -proc deflateEnd*(strm: var TZStream): int32{.cdecl, dynlib: libz, +proc deflateEnd*(strm: var ZStream): int32{.cdecl, dynlib: libz, importc: "deflateEnd".} -proc inflate*(strm: var TZStream, flush: int32): int32{.cdecl, dynlib: libz, +proc inflate*(strm: var ZStream, flush: int32): int32{.cdecl, dynlib: libz, importc: "inflate".} -proc inflateEnd*(strm: var TZStream): int32{.cdecl, dynlib: libz, +proc inflateEnd*(strm: var ZStream): int32{.cdecl, dynlib: libz, importc: "inflateEnd".} -proc deflateSetDictionary*(strm: var TZStream, dictionary: Pbytef, +proc deflateSetDictionary*(strm: var ZStream, dictionary: Pbytef, dictLength: Uint): int32{.cdecl, dynlib: libz, importc: "deflateSetDictionary".} -proc deflateCopy*(dest, source: var TZStream): int32{.cdecl, dynlib: libz, +proc deflateCopy*(dest, source: var ZStream): int32{.cdecl, dynlib: libz, importc: "deflateCopy".} -proc deflateReset*(strm: var TZStream): int32{.cdecl, dynlib: libz, +proc deflateReset*(strm: var ZStream): int32{.cdecl, dynlib: libz, importc: "deflateReset".} -proc deflateParams*(strm: var TZStream, level: int32, strategy: int32): int32{. +proc deflateParams*(strm: var ZStream, level: int32, strategy: int32): int32{. cdecl, dynlib: libz, importc: "deflateParams".} -proc inflateSetDictionary*(strm: var TZStream, dictionary: Pbytef, +proc inflateSetDictionary*(strm: var ZStream, dictionary: Pbytef, dictLength: Uint): int32{.cdecl, dynlib: libz, importc: "inflateSetDictionary".} -proc inflateSync*(strm: var TZStream): int32{.cdecl, dynlib: libz, +proc inflateSync*(strm: var ZStream): int32{.cdecl, dynlib: libz, importc: "inflateSync".} -proc inflateReset*(strm: var TZStream): int32{.cdecl, dynlib: libz, +proc inflateReset*(strm: var ZStream): int32{.cdecl, dynlib: libz, importc: "inflateReset".} proc compress*(dest: Pbytef, destLen: Pulongf, source: Pbytef, sourceLen: Ulong): cint{. cdecl, dynlib: libz, importc: "compress".} @@ -137,45 +139,45 @@ proc adler32*(adler: Ulong, buf: Pbytef, length: Uint): Ulong{.cdecl, ## **Warning**: Adler-32 requires at least a few hundred bytes to get rolling. proc crc32*(crc: Ulong, buf: Pbytef, length: Uint): Ulong{.cdecl, dynlib: libz, importc: "crc32".} -proc deflateInitu*(strm: var TZStream, level: int32, version: cstring, +proc deflateInitu*(strm: var ZStream, level: int32, version: cstring, streamSize: int32): int32{.cdecl, dynlib: libz, importc: "deflateInit_".} -proc inflateInitu*(strm: var TZStream, version: cstring, +proc inflateInitu*(strm: var ZStream, version: cstring, streamSize: int32): int32 {. cdecl, dynlib: libz, importc: "inflateInit_".} -proc deflateInit*(strm: var TZStream, level: int32): int32 -proc inflateInit*(strm: var TZStream): int32 -proc deflateInit2u*(strm: var TZStream, level: int32, `method`: int32, +proc deflateInit*(strm: var ZStream, level: int32): int32 +proc inflateInit*(strm: var ZStream): int32 +proc deflateInit2u*(strm: var ZStream, level: int32, `method`: int32, windowBits: int32, memLevel: int32, strategy: int32, version: cstring, streamSize: int32): int32 {.cdecl, dynlib: libz, importc: "deflateInit2_".} -proc inflateInit2u*(strm: var TZStream, windowBits: int32, version: cstring, +proc inflateInit2u*(strm: var ZStream, windowBits: int32, version: cstring, streamSize: int32): int32{.cdecl, dynlib: libz, importc: "inflateInit2_".} -proc deflateInit2*(strm: var TZStream, +proc deflateInit2*(strm: var ZStream, level, `method`, windowBits, memLevel, strategy: int32): int32 -proc inflateInit2*(strm: var TZStream, windowBits: int32): int32 +proc inflateInit2*(strm: var ZStream, windowBits: int32): int32 proc zError*(err: int32): cstring{.cdecl, dynlib: libz, importc: "zError".} proc inflateSyncPoint*(z: PZstream): int32{.cdecl, dynlib: libz, importc: "inflateSyncPoint".} proc getCrcTable*(): pointer{.cdecl, dynlib: libz, importc: "get_crc_table".} -proc deflateInit(strm: var TZStream, level: int32): int32 = - result = deflateInitu(strm, level, zlibVersion(), sizeof(TZStream).cint) +proc deflateInit(strm: var ZStream, level: int32): int32 = + result = deflateInitu(strm, level, zlibVersion(), sizeof(ZStream).cint) -proc inflateInit(strm: var TZStream): int32 = - result = inflateInitu(strm, zlibVersion(), sizeof(TZStream).cint) +proc inflateInit(strm: var ZStream): int32 = + result = inflateInitu(strm, zlibVersion(), sizeof(ZStream).cint) -proc deflateInit2(strm: var TZStream, +proc deflateInit2(strm: var ZStream, level, `method`, windowBits, memLevel, strategy: int32): int32 = result = deflateInit2u(strm, level, `method`, windowBits, memLevel, - strategy, zlibVersion(), sizeof(TZStream).cint) + strategy, zlibVersion(), sizeof(ZStream).cint) -proc inflateInit2(strm: var TZStream, windowBits: int32): int32 = +proc inflateInit2(strm: var ZStream, windowBits: int32): int32 = result = inflateInit2u(strm, windowBits, zlibVersion(), - sizeof(TZStream).cint) + sizeof(ZStream).cint) proc zlibAllocMem*(appData: pointer, items, size: int): pointer {.cdecl.} = result = alloc(items * size) @@ -200,7 +202,7 @@ proc uncompress*(sourceBuf: cstring, sourceLen: int): string = ## concatenated deflated values properly. assert (not sourceBuf.isNil) - var z: TZStream + var z: ZStream # Initialize input. z.nextIn = sourceBuf diff --git a/lib/wrappers/zip/zzip.nim b/lib/wrappers/zip/zzip.nim index 73fd53c34..fab7d55b3 100644 --- a/lib/wrappers/zip/zzip.nim +++ b/lib/wrappers/zip/zzip.nim @@ -27,7 +27,8 @@ else: dllname = "libzzip.so" type - TZZipError* = int32 + TZZipError* = int32 # Name conflict if we drop the `T` + const ZZIP_ERROR* = -4096'i32 ZZIP_NO_ERROR* = 0'i32 # no error, may be used if user sets it. @@ -54,119 +55,122 @@ const ZZIP_THREADED* = 1'i32 shl 19'i32 type - TZZipDir* {.final, pure.} = object - TZZipFile* {.final, pure.} = object - TZZipPluginIO* {.final, pure.} = object + ZZipDir* {.final, pure.} = object + ZZipFile* {.final, pure.} = object + ZZipPluginIO* {.final, pure.} = object - TZZipDirent* {.final, pure.} = object + ZZipDirent* {.final, pure.} = object d_compr*: int32 ## compression method d_csize*: int32 ## compressed size st_size*: int32 ## file size / decompressed size d_name*: cstring ## file name / strdupped name - TZZipStat* = TZZipDirent + ZZipStat* = ZZipDirent +{.deprecated: [TZZipDir: ZzipDir, TZZipFile: ZzipFile, + TZZipPluginIO: ZzipPluginIO, TZZipDirent: ZzipDirent, + TZZipStat: ZZipStat].} proc zzip_strerror*(errcode: int32): cstring {.cdecl, dynlib: dllname, importc: "zzip_strerror".} -proc zzip_strerror_of*(dir: ptr TZZipDir): cstring {.cdecl, dynlib: dllname, +proc zzip_strerror_of*(dir: ptr ZZipDir): cstring {.cdecl, dynlib: dllname, importc: "zzip_strerror_of".} proc zzip_errno*(errcode: int32): int32 {.cdecl, dynlib: dllname, importc: "zzip_errno".} -proc zzip_geterror*(dir: ptr TZZipDir): int32 {.cdecl, dynlib: dllname, +proc zzip_geterror*(dir: ptr ZZipDir): int32 {.cdecl, dynlib: dllname, importc: "zzip_error".} -proc zzip_seterror*(dir: ptr TZZipDir, errcode: int32) {.cdecl, dynlib: dllname, +proc zzip_seterror*(dir: ptr ZZipDir, errcode: int32) {.cdecl, dynlib: dllname, importc: "zzip_seterror".} proc zzip_compr_str*(compr: int32): cstring {.cdecl, dynlib: dllname, importc: "zzip_compr_str".} -proc zzip_dirhandle*(fp: ptr TZZipFile): ptr TZZipDir {.cdecl, dynlib: dllname, +proc zzip_dirhandle*(fp: ptr ZZipFile): ptr ZZipDir {.cdecl, dynlib: dllname, importc: "zzip_dirhandle".} -proc zzip_dirfd*(dir: ptr TZZipDir): int32 {.cdecl, dynlib: dllname, +proc zzip_dirfd*(dir: ptr ZZipDir): int32 {.cdecl, dynlib: dllname, importc: "zzip_dirfd".} -proc zzip_dir_real*(dir: ptr TZZipDir): int32 {.cdecl, dynlib: dllname, +proc zzip_dir_real*(dir: ptr ZZipDir): int32 {.cdecl, dynlib: dllname, importc: "zzip_dir_real".} -proc zzip_file_real*(fp: ptr TZZipFile): int32 {.cdecl, dynlib: dllname, +proc zzip_file_real*(fp: ptr ZZipFile): int32 {.cdecl, dynlib: dllname, importc: "zzip_file_real".} -proc zzip_realdir*(dir: ptr TZZipDir): pointer {.cdecl, dynlib: dllname, +proc zzip_realdir*(dir: ptr ZZipDir): pointer {.cdecl, dynlib: dllname, importc: "zzip_realdir".} -proc zzip_realfd*(fp: ptr TZZipFile): int32 {.cdecl, dynlib: dllname, +proc zzip_realfd*(fp: ptr ZZipFile): int32 {.cdecl, dynlib: dllname, importc: "zzip_realfd".} -proc zzip_dir_alloc*(fileext: cstringArray): ptr TZZipDir {.cdecl, +proc zzip_dir_alloc*(fileext: cstringArray): ptr ZZipDir {.cdecl, dynlib: dllname, importc: "zzip_dir_alloc".} -proc zzip_dir_free*(para1: ptr TZZipDir): int32 {.cdecl, dynlib: dllname, +proc zzip_dir_free*(para1: ptr ZZipDir): int32 {.cdecl, dynlib: dllname, importc: "zzip_dir_free".} -proc zzip_dir_fdopen*(fd: int32, errcode_p: ptr TZZipError): ptr TZZipDir {.cdecl, +proc zzip_dir_fdopen*(fd: int32, errcode_p: ptr TZZipError): ptr ZZipDir {.cdecl, dynlib: dllname, importc: "zzip_dir_fdopen".} -proc zzip_dir_open*(filename: cstring, errcode_p: ptr TZZipError): ptr TZZipDir {. +proc zzip_dir_open*(filename: cstring, errcode_p: ptr TZZipError): ptr ZZipDir {. cdecl, dynlib: dllname, importc: "zzip_dir_open".} -proc zzip_dir_close*(dir: ptr TZZipDir) {.cdecl, dynlib: dllname, +proc zzip_dir_close*(dir: ptr ZZipDir) {.cdecl, dynlib: dllname, importc: "zzip_dir_close".} -proc zzip_dir_read*(dir: ptr TZZipDir, dirent: ptr TZZipDirent): int32 {.cdecl, +proc zzip_dir_read*(dir: ptr ZZipDir, dirent: ptr ZZipDirent): int32 {.cdecl, dynlib: dllname, importc: "zzip_dir_read".} -proc zzip_opendir*(filename: cstring): ptr TZZipDir {.cdecl, dynlib: dllname, +proc zzip_opendir*(filename: cstring): ptr ZZipDir {.cdecl, dynlib: dllname, importc: "zzip_opendir".} -proc zzip_closedir*(dir: ptr TZZipDir) {.cdecl, dynlib: dllname, +proc zzip_closedir*(dir: ptr ZZipDir) {.cdecl, dynlib: dllname, importc: "zzip_closedir".} -proc zzip_readdir*(dir: ptr TZZipDir): ptr TZZipDirent {.cdecl, dynlib: dllname, +proc zzip_readdir*(dir: ptr ZZipDir): ptr ZZipDirent {.cdecl, dynlib: dllname, importc: "zzip_readdir".} -proc zzip_rewinddir*(dir: ptr TZZipDir) {.cdecl, dynlib: dllname, +proc zzip_rewinddir*(dir: ptr ZZipDir) {.cdecl, dynlib: dllname, importc: "zzip_rewinddir".} -proc zzip_telldir*(dir: ptr TZZipDir): int {.cdecl, dynlib: dllname, +proc zzip_telldir*(dir: ptr ZZipDir): int {.cdecl, dynlib: dllname, importc: "zzip_telldir".} -proc zzip_seekdir*(dir: ptr TZZipDir, offset: int) {.cdecl, dynlib: dllname, +proc zzip_seekdir*(dir: ptr ZZipDir, offset: int) {.cdecl, dynlib: dllname, importc: "zzip_seekdir".} -proc zzip_file_open*(dir: ptr TZZipDir, name: cstring, flags: int32): ptr TZZipFile {. +proc zzip_file_open*(dir: ptr ZZipDir, name: cstring, flags: int32): ptr ZZipFile {. cdecl, dynlib: dllname, importc: "zzip_file_open".} -proc zzip_file_close*(fp: ptr TZZipFile) {.cdecl, dynlib: dllname, +proc zzip_file_close*(fp: ptr ZZipFile) {.cdecl, dynlib: dllname, importc: "zzip_file_close".} -proc zzip_file_read*(fp: ptr TZZipFile, buf: pointer, length: int): int {. +proc zzip_file_read*(fp: ptr ZZipFile, buf: pointer, length: int): int {. cdecl, dynlib: dllname, importc: "zzip_file_read".} -proc zzip_open*(name: cstring, flags: int32): ptr TZZipFile {.cdecl, +proc zzip_open*(name: cstring, flags: int32): ptr ZZipFile {.cdecl, dynlib: dllname, importc: "zzip_open".} -proc zzip_close*(fp: ptr TZZipFile) {.cdecl, dynlib: dllname, +proc zzip_close*(fp: ptr ZZipFile) {.cdecl, dynlib: dllname, importc: "zzip_close".} -proc zzip_read*(fp: ptr TZZipFile, buf: pointer, length: int): int {. +proc zzip_read*(fp: ptr ZZipFile, buf: pointer, length: int): int {. cdecl, dynlib: dllname, importc: "zzip_read".} -proc zzip_freopen*(name: cstring, mode: cstring, para3: ptr TZZipFile): ptr TZZipFile {. +proc zzip_freopen*(name: cstring, mode: cstring, para3: ptr ZZipFile): ptr ZZipFile {. cdecl, dynlib: dllname, importc: "zzip_freopen".} -proc zzip_fopen*(name: cstring, mode: cstring): ptr TZZipFile {.cdecl, +proc zzip_fopen*(name: cstring, mode: cstring): ptr ZZipFile {.cdecl, dynlib: dllname, importc: "zzip_fopen".} proc zzip_fread*(p: pointer, size: int, nmemb: int, - file: ptr TZZipFile): int {.cdecl, dynlib: dllname, + file: ptr ZZipFile): int {.cdecl, dynlib: dllname, importc: "zzip_fread".} -proc zzip_fclose*(fp: ptr TZZipFile) {.cdecl, dynlib: dllname, +proc zzip_fclose*(fp: ptr ZZipFile) {.cdecl, dynlib: dllname, importc: "zzip_fclose".} -proc zzip_rewind*(fp: ptr TZZipFile): int32 {.cdecl, dynlib: dllname, +proc zzip_rewind*(fp: ptr ZZipFile): int32 {.cdecl, dynlib: dllname, importc: "zzip_rewind".} -proc zzip_seek*(fp: ptr TZZipFile, offset: int, whence: int32): int {. +proc zzip_seek*(fp: ptr ZZipFile, offset: int, whence: int32): int {. cdecl, dynlib: dllname, importc: "zzip_seek".} -proc zzip_tell*(fp: ptr TZZipFile): int {.cdecl, dynlib: dllname, +proc zzip_tell*(fp: ptr ZZipFile): int {.cdecl, dynlib: dllname, importc: "zzip_tell".} -proc zzip_dir_stat*(dir: ptr TZZipDir, name: cstring, zs: ptr TZZipStat, +proc zzip_dir_stat*(dir: ptr ZZipDir, name: cstring, zs: ptr ZZipStat, flags: int32): int32 {.cdecl, dynlib: dllname, importc: "zzip_dir_stat".} -proc zzip_file_stat*(fp: ptr TZZipFile, zs: ptr TZZipStat): int32 {.cdecl, +proc zzip_file_stat*(fp: ptr ZZipFile, zs: ptr ZZipStat): int32 {.cdecl, dynlib: dllname, importc: "zzip_file_stat".} -proc zzip_fstat*(fp: ptr TZZipFile, zs: ptr TZZipStat): int32 {.cdecl, dynlib: dllname, +proc zzip_fstat*(fp: ptr ZZipFile, zs: ptr ZZipStat): int32 {.cdecl, dynlib: dllname, importc: "zzip_fstat".} -proc zzip_open_shared_io*(stream: ptr TZZipFile, name: cstring, +proc zzip_open_shared_io*(stream: ptr ZZipFile, name: cstring, o_flags: int32, o_modes: int32, ext: cstringArray, - io: ptr TZZipPluginIO): ptr TZZipFile {.cdecl, + io: ptr ZZipPluginIO): ptr ZZipFile {.cdecl, dynlib: dllname, importc: "zzip_open_shared_io".} proc zzip_open_ext_io*(name: cstring, o_flags: int32, o_modes: int32, - ext: cstringArray, io: ptr TZZipPluginIO): ptr TZZipFile {. + ext: cstringArray, io: ptr ZZipPluginIO): ptr ZZipFile {. cdecl, dynlib: dllname, importc: "zzip_open_ext_io".} proc zzip_opendir_ext_io*(name: cstring, o_modes: int32, - ext: cstringArray, io: ptr TZZipPluginIO): ptr TZZipDir {. + ext: cstringArray, io: ptr ZZipPluginIO): ptr ZZipDir {. cdecl, dynlib: dllname, importc: "zzip_opendir_ext_io".} proc zzip_dir_open_ext_io*(filename: cstring, errcode_p: ptr TZZipError, - ext: cstringArray, io: ptr TZZipPluginIO): ptr TZZipDir {. + ext: cstringArray, io: ptr ZZipPluginIO): ptr ZZipDir {. cdecl, dynlib: dllname, importc: "zzip_dir_open_ext_io".} From 2124952db381b2cf8347552daadf4c5491c6ff7e Mon Sep 17 00:00:00 2001 From: Perelandric Date: Sun, 24 May 2015 23:57:50 -0500 Subject: [PATCH 0358/1263] Added line breaks to long 'deprecated' pragmas --- lib/windows/windows.nim | 167 +++++++++++++++++++++++++++++++++++++--- 1 file changed, 158 insertions(+), 9 deletions(-) diff --git a/lib/windows/windows.nim b/lib/windows/windows.nim index 49b82a4ba..bddb4cef7 100644 --- a/lib/windows/windows.nim +++ b/lib/windows/windows.nim @@ -9726,13 +9726,85 @@ type LPLDT_ENTRY* = ptr LDT_ENTRY PLDT_ENTRY* = ptr LDT_ENTRY -{.deprecated: [TEXCEPTIONRECORD: EXCEPTION_RECORD, TEXCEPTIONDEBUGINFO: EXCEPTION_DEBUG_INFO, TExceptionRecord32: EXCEPTION_RECORD32, TExceptionDebugInfo32: EXCEPTION_DEBUG_INFO32, TExceptionRecord64: EXCEPTION_RECORD64, TExceptionDebugInfo64: EXCEPTION_DEBUG_INFO64, TEXITPROCESSDEBUGINFO: EXIT_PROCESS_DEBUG_INFO, TEXITTHREADDEBUGINFO: EXIT_THREAD_DEBUG_INFO, TLOADDLLDEBUGINFO: LOAD_DLL_DEBUG_INFO, TUNLOADDLLDEBUGINFO: UNLOAD_DLL_DEBUG_INFO, TOUTPUTDEBUGSTRINGINFO: OUTPUT_DEBUG_STRING_INFO, TRIPINFO: RIP_INFO, TDEBUGEVENT: DEBUG_EVENT, TDEBUGHOOKINFO: DEBUGHOOKINFO, TDELETEITEMSTRUCT: DELETEITEMSTRUCT, TDEVBROADCASTHDR: DEV_BROADCAST_HDR, TDEVBROADCASTOEM: DEV_BROADCAST_OEM, TDEVBROADCASTPORT: DEV_BROADCAST_PORT, TDEVBROADCASTUSERDEFINED: DEV_BROADCAST_USERDEFINED, TDEVBROADCASTVOLUME: DEV_BROADCAST_VOLUME, TDevicemode: DEVMODE, TDevicemodeA: DEVMODE, TDEVMODE: DEVMODE, TDEVNAMES: DEVNAMES, TDEVMODEW: DEVMODEW, TDeviceModeW: DEVMODEW, TDIBSECTION: DIBSECTION, TLargeInteger: LargeInteger, TULargeInteger: ULargeInteger, TDISKPERFORMANCE: DISK_PERFORMANCE, TDISKGEOMETRY: DISK_GEOMETRY, TDOCINFO1: DOC_INFO_1, TDLGTEMPLATE: DLGTEMPLATE, TDLGITEMTEMPLATE: DLGITEMTEMPLATE, TDRAWTEXTPARAMS: DRAWTEXTPARAMS, TDRAWITEMSTRUCT: DRAWITEMSTRUCT, TDRAGLISTINFO: DRAGLISTINFO, TDOCINFO: DOCINFO, TDOCINFOA: DOCINFO, TDOCINFO2: DOC_INFO_2, TPARTITIONINFORMATION: PARTITION_INFORMATION, TDRIVELAYOUTINFORMATION: DRIVE_LAYOUT_INFORMATION, TEMRARC: EMRARC, TEMRANGLEARC: EMRANGLEARC, TEMR: EMR, Teditstream: EDITSTREAM, TDRIVERINFO3: DRIVER_INFO_3, TDRIVERINFO2: DRIVER_INFO_2, TDRIVERINFO1: DRIVER_INFO_1, TEMREXTCREATEFONTINDIRECTW: EMREXTCREATEFONTINDIRECTW].} +{.deprecated: [TEXCEPTIONRECORD: EXCEPTION_RECORD, TEXCEPTIONDEBUGINFO: EXCEPTION_DEBUG_INFO, + TExceptionRecord32: EXCEPTION_RECORD32, TExceptionDebugInfo32: EXCEPTION_DEBUG_INFO32, + TExceptionRecord64: EXCEPTION_RECORD64, TExceptionDebugInfo64: EXCEPTION_DEBUG_INFO64, + TEXITPROCESSDEBUGINFO: EXIT_PROCESS_DEBUG_INFO, TEXITTHREADDEBUGINFO: EXIT_THREAD_DEBUG_INFO, + TLOADDLLDEBUGINFO: LOAD_DLL_DEBUG_INFO, TUNLOADDLLDEBUGINFO: UNLOAD_DLL_DEBUG_INFO, + TOUTPUTDEBUGSTRINGINFO: OUTPUT_DEBUG_STRING_INFO, TRIPINFO: RIP_INFO, TDEBUGEVENT: DEBUG_EVENT, + TDEBUGHOOKINFO: DEBUGHOOKINFO, TDELETEITEMSTRUCT: DELETEITEMSTRUCT, TDEVBROADCASTHDR: DEV_BROADCAST_HDR, + TDEVBROADCASTOEM: DEV_BROADCAST_OEM, TDEVBROADCASTPORT: DEV_BROADCAST_PORT, + TDEVBROADCASTUSERDEFINED: DEV_BROADCAST_USERDEFINED, TDEVBROADCASTVOLUME: DEV_BROADCAST_VOLUME, + TDevicemode: DEVMODE, TDevicemodeA: DEVMODE, TDEVMODE: DEVMODE, TDEVNAMES: DEVNAMES, TDEVMODEW: DEVMODEW, + TDeviceModeW: DEVMODEW, TDIBSECTION: DIBSECTION, TLargeInteger: LargeInteger, + TULargeInteger: ULargeInteger, TDISKPERFORMANCE: DISK_PERFORMANCE, TDISKGEOMETRY: DISK_GEOMETRY, + TDOCINFO1: DOC_INFO_1, TDLGTEMPLATE: DLGTEMPLATE, TDLGITEMTEMPLATE: DLGITEMTEMPLATE, + TDRAWTEXTPARAMS: DRAWTEXTPARAMS, TDRAWITEMSTRUCT: DRAWITEMSTRUCT, TDRAGLISTINFO: DRAGLISTINFO, + TDOCINFO: DOCINFO, TDOCINFOA: DOCINFO, TDOCINFO2: DOC_INFO_2, TPARTITIONINFORMATION: PARTITION_INFORMATION, + TDRIVELAYOUTINFORMATION: DRIVE_LAYOUT_INFORMATION, TEMRARC: EMRARC, TEMRANGLEARC: EMRANGLEARC, + TEMR: EMR, Teditstream: EDITSTREAM, TDRIVERINFO3: DRIVER_INFO_3, TDRIVERINFO2: DRIVER_INFO_2, + TDRIVERINFO1: DRIVER_INFO_1, TEMREXTCREATEFONTINDIRECTW: EMREXTCREATEFONTINDIRECTW].} -{.deprecated: [TEXTLOGFONT: EXTLOGFONT, TPANOSE: PANOSE, TEMRINTERSECTCLIPRECT: EMREXCLUDECLIPRECT, TEMREXCLUDECLIPRECT: EMREXCLUDECLIPRECT, TEMREOF: EMREOF, TEMRRECTANGLE: EMRELLIPSE, TEMRELLIPSE: EMRELLIPSE, TEMRCREATEPEN: EMRCREATEPEN, TLOGPEN: LOGPEN, TEMRCREATEPALETTE: EMRCREATEPALETTE, TLOGPALETTE: LOGPALETTE, TPALETTEENTRY: PALETTEENTRY, TEMRCREATEMONOBRUSH: EMRCREATEMONOBRUSH, TEMRCREATEDIBPATTERNBRUSHPT: EMRCREATEDIBPATTERNBRUSHPT, TEMRCREATECOLORSPACE: EMRCREATECOLORSPACE, TLOGCOLORSPACE: LOGCOLORSPACE, TLOGCOLORSPACEA: LOGCOLORSPACE, TEMRCREATEBRUSHINDIRECT: EMRCREATEBRUSHINDIRECT, TLOGBRUSH: LOGBRUSH, TEMRBITBLT: EMRBITBLT, TXFORM: XFORM, TEMRPIE: EMRARC, TEMRCHORD: EMRARC, TEMRARCTO: EMRARC, TSERVICESTATUS: SERVICE_STATUS, TENUMSERVICESTATUS: ENUM_SERVICE_STATUS, TENUMLOGFONT: ENUMLOGFONT, TENUMLOGFONTEX: ENUMLOGFONTEX, TEVENTLOGRECORD: EVENTLOGRECORD, TEVENTMSG: EVENTMSG, TEXCEPTIONPOINTERS: EXCEPTION_POINTERS, TEXTBUTTON: EXT_BUTTON, TFILTERKEYS: FILTERKEYS, TFINDNAMEBUFFER: FIND_NAME_BUFFER, TFINDNAMEHEADER: FIND_NAME_HEADER, TFINDREPLACE: FINDREPLACE, Tfindtextex: FINDTEXTEX, TFMSGETDRIVEINFO: FMS_GETDRIVEINFO, TFMSGETFILESEL: FMS_GETFILESEL, TFMSLOAD: FMS_LOAD, TFMSTOOLBARLOAD: FMS_TOOLBARLOAD, TFOCUSEVENTRECORD: FOCUS_EVENT_RECORD, TFORMINFO1: FORM_INFO_1, TFORMATPARAMETERS: FORMAT_PARAMETERS, Tformatrange: FORMATRANGE, TGCPRESULTS: GCP_RESULTS, TGENERICMAPPING: GENERIC_MAPPING, TGLYPHMETRICS: GLYPHMETRICS, THANDLETABLE: HANDLETABLE, THDHITTESTINFO: HD_HITTESTINFO, THDITEM: HD_ITEM, TWINDOWPOS: WINDOWPOS, THDLAYOUT: HD_LAYOUT, THDNOTIFY: HD_NOTIFY, THELPINFO: HELPINFO, THELPWININFO: HELPWININFO, THIGHCONTRAST: HIGHCONTRAST, THSZPAIR: HSZPAIR, TICONINFO: ICONINFO, TICONMETRICS: ICONMETRICS, TIMAGEINFO: IMAGEINFO, TKEYEVENTRECORD: KEY_EVENT_RECORD, TMOUSEEVENTRECORD: MOUSE_EVENT_RECORD, TWINDOWBUFFERSIZERECORD: WINDOW_BUFFER_SIZE_RECORD, TMENUEVENTRECORD: MENU_EVENT_RECORD, TINPUTRECORD: INPUT_RECORD, TSYSTEMTIME: SYSTEMTIME, TJOBINFO1: JOB_INFO_1].} +{.deprecated: [TEXTLOGFONT: EXTLOGFONT, TPANOSE: PANOSE, TEMRINTERSECTCLIPRECT: EMREXCLUDECLIPRECT, + TEMREXCLUDECLIPRECT: EMREXCLUDECLIPRECT, TEMREOF: EMREOF, TEMRRECTANGLE: EMRELLIPSE, + TEMRELLIPSE: EMRELLIPSE, TEMRCREATEPEN: EMRCREATEPEN, TLOGPEN: LOGPEN, TEMRCREATEPALETTE: EMRCREATEPALETTE, + TLOGPALETTE: LOGPALETTE, TPALETTEENTRY: PALETTEENTRY, TEMRCREATEMONOBRUSH: EMRCREATEMONOBRUSH, + TEMRCREATEDIBPATTERNBRUSHPT: EMRCREATEDIBPATTERNBRUSHPT, TEMRCREATECOLORSPACE: EMRCREATECOLORSPACE, + TLOGCOLORSPACE: LOGCOLORSPACE, TLOGCOLORSPACEA: LOGCOLORSPACE, TEMRCREATEBRUSHINDIRECT: EMRCREATEBRUSHINDIRECT, + TLOGBRUSH: LOGBRUSH, TEMRBITBLT: EMRBITBLT, TXFORM: XFORM, TEMRPIE: EMRARC, TEMRCHORD: EMRARC, + TEMRARCTO: EMRARC, TSERVICESTATUS: SERVICE_STATUS, TENUMSERVICESTATUS: ENUM_SERVICE_STATUS, + TENUMLOGFONT: ENUMLOGFONT, TENUMLOGFONTEX: ENUMLOGFONTEX, TEVENTLOGRECORD: EVENTLOGRECORD, + TEVENTMSG: EVENTMSG, TEXCEPTIONPOINTERS: EXCEPTION_POINTERS, TEXTBUTTON: EXT_BUTTON, + TFILTERKEYS: FILTERKEYS, TFINDNAMEBUFFER: FIND_NAME_BUFFER, TFINDNAMEHEADER: FIND_NAME_HEADER, + TFINDREPLACE: FINDREPLACE, Tfindtextex: FINDTEXTEX, TFMSGETDRIVEINFO: FMS_GETDRIVEINFO, + TFMSGETFILESEL: FMS_GETFILESEL, TFMSLOAD: FMS_LOAD, TFMSTOOLBARLOAD: FMS_TOOLBARLOAD, + TFOCUSEVENTRECORD: FOCUS_EVENT_RECORD, TFORMINFO1: FORM_INFO_1, TFORMATPARAMETERS: FORMAT_PARAMETERS, + Tformatrange: FORMATRANGE, TGCPRESULTS: GCP_RESULTS, TGENERICMAPPING: GENERIC_MAPPING, + TGLYPHMETRICS: GLYPHMETRICS, THANDLETABLE: HANDLETABLE, THDHITTESTINFO: HD_HITTESTINFO, + THDITEM: HD_ITEM, TWINDOWPOS: WINDOWPOS, THDLAYOUT: HD_LAYOUT, THDNOTIFY: HD_NOTIFY, + THELPINFO: HELPINFO, THELPWININFO: HELPWININFO, THIGHCONTRAST: HIGHCONTRAST, THSZPAIR: HSZPAIR, + TICONINFO: ICONINFO, TICONMETRICS: ICONMETRICS, TIMAGEINFO: IMAGEINFO, TKEYEVENTRECORD: KEY_EVENT_RECORD, + TMOUSEEVENTRECORD: MOUSE_EVENT_RECORD, TWINDOWBUFFERSIZERECORD: WINDOW_BUFFER_SIZE_RECORD, + TMENUEVENTRECORD: MENU_EVENT_RECORD, TINPUTRECORD: INPUT_RECORD, TSYSTEMTIME: SYSTEMTIME, + TJOBINFO1: JOB_INFO_1].} -{.deprecated: [TSIDIDENTIFIERAUTHORITY: SID_IDENTIFIER_AUTHORITY, TSID: SID, TSECURITYDESCRIPTORCONTROL: SECURITY_DESCRIPTOR_CONTROL, TSECURITYDESCRIPTOR: SECURITY_DESCRIPTOR, TJOBINFO2: JOB_INFO_2, TLANAENUM: LANA_ENUM, TLDTENTRY: LDT_ENTRY, TEMRPOLYPOLYGON: EMRPOLYPOLYLINE, TEMRPOLYPOLYLINE: EMRPOLYPOLYLINE, TEMRPOLYLINETO16: EMRPOLYLINE16, TEMRPOLYBEZIERTO16: EMRPOLYLINE16, TEMRPOLYGON16: EMRPOLYLINE16, TEMRPOLYBEZIER16: EMRPOLYLINE16, TEMRPOLYLINE16: EMRPOLYLINE16, TEMRPOLYLINETO: EMRPOLYLINE, TEMRPOLYBEZIERTO: EMRPOLYLINE, TEMRPOLYGON: EMRPOLYLINE, TEMRPOLYBEZIER: EMRPOLYLINE, TEMRPOLYLINE: EMRPOLYLINE, TEMRPOLYDRAW16: EMRPOLYDRAW16, TEMRPOLYDRAW: EMRPOLYDRAW, TEMRPLGBLT: EMRPLGBLT, TEMROFFSETCLIPRGN: EMROFFSETCLIPRGN, TEMRMODIFYWORLDTRANSFORM: EMRMODIFYWORLDTRANSFORM, TEMRMASKBLT: EMRMASKBLT, TEMRMOVETOEX: EMRLINETO, TEMRLINETO: EMRLINETO, TEMRPAINTRGN: EMRINVERTRGN, TEMRINVERTRGN: EMRINVERTRGN, TEMRGDICOMMENT: EMRGDICOMMENT, TEMRFRAMERGN: EMRFRAMERGN, TEMRFORMAT: EMRFORMAT, TEMRFILLRGN: EMRFILLRGN, TEMRSTROKEPATH: EMRFILLPATH, TEMRSTROKEANDFILLPATH: EMRFILLPATH, TEMRFILLPATH: EMRFILLPATH, TEMREXTTEXTOUTW: EMREXTTEXTOUTA, TEMREXTTEXTOUTA: EMREXTTEXTOUTA, TEMRTEXT: EMRTEXT, TEMREXTSELECTCLIPRGN: EMREXTSELECTCLIPRGN, TEMREXTFLOODFILL: EMREXTFLOODFILL, TEMREXTCREATEPEN: EMREXTCREATEPEN, TEXTLOGPEN: EXTLOGPEN, TNMHDR: NMHDR, TEMRENABLEICM: EMRSELECTCLIPPATH, TEMRSETTEXTALIGN: EMRSELECTCLIPPATH, TEMRSETSTRETCHBLTMODE: EMRSELECTCLIPPATH, TEMRSETROP2: EMRSELECTCLIPPATH, TEMRSETPOLYFILLMODE: EMRSELECTCLIPPATH, TEMRSETMAPMODE: EMRSELECTCLIPPATH, TEMRSETBKMODE: EMRSELECTCLIPPATH, TEMRSELECTCLIPPATH: EMRSELECTCLIPPATH, TEMRREALIZEPALETTE: EMRABORTPATH, TEMRSAVEDC: EMRABORTPATH, TEMRSETMETARGN: EMRABORTPATH, TEMRWIDENPATH: EMRABORTPATH].} +{.deprecated: [TSIDIDENTIFIERAUTHORITY: SID_IDENTIFIER_AUTHORITY, TSID: SID, + TSECURITYDESCRIPTORCONTROL: SECURITY_DESCRIPTOR_CONTROL, TSECURITYDESCRIPTOR: SECURITY_DESCRIPTOR, + TJOBINFO2: JOB_INFO_2, TLANAENUM: LANA_ENUM, TLDTENTRY: LDT_ENTRY, TEMRPOLYPOLYGON: EMRPOLYPOLYLINE, + TEMRPOLYPOLYLINE: EMRPOLYPOLYLINE, TEMRPOLYLINETO16: EMRPOLYLINE16, TEMRPOLYBEZIERTO16: EMRPOLYLINE16, + TEMRPOLYGON16: EMRPOLYLINE16, TEMRPOLYBEZIER16: EMRPOLYLINE16, TEMRPOLYLINE16: EMRPOLYLINE16, + TEMRPOLYLINETO: EMRPOLYLINE, TEMRPOLYBEZIERTO: EMRPOLYLINE, TEMRPOLYGON: EMRPOLYLINE, + TEMRPOLYBEZIER: EMRPOLYLINE, TEMRPOLYLINE: EMRPOLYLINE, TEMRPOLYDRAW16: EMRPOLYDRAW16, + TEMRPOLYDRAW: EMRPOLYDRAW, TEMRPLGBLT: EMRPLGBLT, TEMROFFSETCLIPRGN: EMROFFSETCLIPRGN, + TEMRMODIFYWORLDTRANSFORM: EMRMODIFYWORLDTRANSFORM, TEMRMASKBLT: EMRMASKBLT, TEMRMOVETOEX: EMRLINETO, + TEMRLINETO: EMRLINETO, TEMRPAINTRGN: EMRINVERTRGN, TEMRINVERTRGN: EMRINVERTRGN, + TEMRGDICOMMENT: EMRGDICOMMENT, TEMRFRAMERGN: EMRFRAMERGN, TEMRFORMAT: EMRFORMAT, TEMRFILLRGN: EMRFILLRGN, + TEMRSTROKEPATH: EMRFILLPATH, TEMRSTROKEANDFILLPATH: EMRFILLPATH, TEMRFILLPATH: EMRFILLPATH, + TEMREXTTEXTOUTW: EMREXTTEXTOUTA, TEMREXTTEXTOUTA: EMREXTTEXTOUTA, TEMRTEXT: EMRTEXT, + TEMREXTSELECTCLIPRGN: EMREXTSELECTCLIPRGN, TEMREXTFLOODFILL: EMREXTFLOODFILL, + TEMREXTCREATEPEN: EMREXTCREATEPEN, TEXTLOGPEN: EXTLOGPEN, TNMHDR: NMHDR, TEMRENABLEICM: EMRSELECTCLIPPATH, + TEMRSETTEXTALIGN: EMRSELECTCLIPPATH, TEMRSETSTRETCHBLTMODE: EMRSELECTCLIPPATH, + TEMRSETROP2: EMRSELECTCLIPPATH, TEMRSETPOLYFILLMODE: EMRSELECTCLIPPATH, TEMRSETMAPMODE: EMRSELECTCLIPPATH, + TEMRSETBKMODE: EMRSELECTCLIPPATH, TEMRSELECTCLIPPATH: EMRSELECTCLIPPATH, TEMRREALIZEPALETTE: EMRABORTPATH, + TEMRSAVEDC: EMRABORTPATH, TEMRSETMETARGN: EMRABORTPATH, TEMRWIDENPATH: EMRABORTPATH].} -{.deprecated: [TEMRFLATTENPATH: EMRABORTPATH, TEMRCLOSEFIGURE: EMRABORTPATH, TEMRENDPATH: EMRABORTPATH, TEMRBEGINPATH: EMRABORTPATH, TABORTPATH: EMRABORTPATH, TEMRABORTPATH: EMRABORTPATH, TEMRSTRETCHDIBITS: EMRSTRETCHDIBITS, TEMRSTRETCHBLT: EMRSTRETCHBLT, TEMRSETWORLDTRANSFORM: EMRSETWORLDTRANSFORM, TEMRSETBRUSHORGEX: EMRSETVIEWPORTORGEX, TEMRSETWINDOWORGEX: EMRSETVIEWPORTORGEX, TEMRSETVIEWPORTORGEX: EMRSETVIEWPORTORGEX, TEMRSETWINDOWEXTEX: EMRSETVIEWPORTEXTEX, TEMRSETVIEWPORTEXTEX: EMRSETVIEWPORTEXTEX, TEMRSETPIXELV: EMRSETPIXELV, TEMRSETPALETTEENTRIES: EMRSETPALETTEENTRIES, TEMRSETMITERLIMIT: EMRSETMITERLIMIT, TEMRSETMAPPERFLAGS: EMRSETMAPPERFLAGS, TEMRSETDIBITSTODEVICE: EMRSETDIBITSTODEVICE, TEMRSETCOLORADJUSTMENT: EMRSETCOLORADJUSTMENT, TEMRSETTEXTCOLOR: EMRSETBKCOLOR, TEMRSETBKCOLOR: EMRSETBKCOLOR, TEMRSETARCDIRECTION: EMRSETARCDIRECTION, TEMRSELECTPALETTE: EMRSELECTPALETTE, TEMRDELETEOBJECT: EMRSELECTOBJECT, TEMRSELECTOBJECT: EMRSELECTOBJECT, TEMRDELETECOLORSPACE: EMRSELECTCOLORSPACE, TEMRSELECTCOLORSPACE: EMRSELECTCOLORSPACE, TEMRSCALEWINDOWEXTEX: EMRSCALEVIEWPORTEXTEX, TEMRSCALEVIEWPORTEXTEX: EMRSCALEVIEWPORTEXTEX, TEMRROUNDRECT: EMRROUNDRECT, TEMRRESTOREDC: EMRRESTOREDC, TEMRRESIZEPALETTE: EMRRESIZEPALETTE, TEMRPOLYTEXTOUTW: EMRPOLYTEXTOUTA, TEMRPOLYTEXTOUTA: EMRPOLYTEXTOUTA, TEMRPOLYPOLYGON16: EMRPOLYPOLYLINE16, TEMRPOLYPOLYLINE16: EMRPOLYPOLYLINE16, TENHMETAHEADER: ENHMETAHEADER, TENHMETARECORD: ENHMETARECORD].} +{.deprecated: [TEMRFLATTENPATH: EMRABORTPATH, TEMRCLOSEFIGURE: EMRABORTPATH, TEMRENDPATH: EMRABORTPATH, + TEMRBEGINPATH: EMRABORTPATH, TABORTPATH: EMRABORTPATH, TEMRABORTPATH: EMRABORTPATH, + TEMRSTRETCHDIBITS: EMRSTRETCHDIBITS, TEMRSTRETCHBLT: EMRSTRETCHBLT, + TEMRSETWORLDTRANSFORM: EMRSETWORLDTRANSFORM, TEMRSETBRUSHORGEX: EMRSETVIEWPORTORGEX, + TEMRSETWINDOWORGEX: EMRSETVIEWPORTORGEX, TEMRSETVIEWPORTORGEX: EMRSETVIEWPORTORGEX, + TEMRSETWINDOWEXTEX: EMRSETVIEWPORTEXTEX, TEMRSETVIEWPORTEXTEX: EMRSETVIEWPORTEXTEX, + TEMRSETPIXELV: EMRSETPIXELV, TEMRSETPALETTEENTRIES: EMRSETPALETTEENTRIES, + TEMRSETMITERLIMIT: EMRSETMITERLIMIT, TEMRSETMAPPERFLAGS: EMRSETMAPPERFLAGS, + TEMRSETDIBITSTODEVICE: EMRSETDIBITSTODEVICE, TEMRSETCOLORADJUSTMENT: EMRSETCOLORADJUSTMENT, + TEMRSETTEXTCOLOR: EMRSETBKCOLOR, TEMRSETBKCOLOR: EMRSETBKCOLOR, TEMRSETARCDIRECTION: EMRSETARCDIRECTION, + TEMRSELECTPALETTE: EMRSELECTPALETTE, TEMRDELETEOBJECT: EMRSELECTOBJECT, TEMRSELECTOBJECT: EMRSELECTOBJECT, + TEMRDELETECOLORSPACE: EMRSELECTCOLORSPACE, TEMRSELECTCOLORSPACE: EMRSELECTCOLORSPACE, + TEMRSCALEWINDOWEXTEX: EMRSCALEVIEWPORTEXTEX, TEMRSCALEVIEWPORTEXTEX: EMRSCALEVIEWPORTEXTEX, + TEMRROUNDRECT: EMRROUNDRECT, TEMRRESTOREDC: EMRRESTOREDC, TEMRRESIZEPALETTE: EMRRESIZEPALETTE, + TEMRPOLYTEXTOUTW: EMRPOLYTEXTOUTA, TEMRPOLYTEXTOUTA: EMRPOLYTEXTOUTA, + TEMRPOLYPOLYGON16: EMRPOLYPOLYLINE16, TEMRPOLYPOLYLINE16: EMRPOLYPOLYLINE16, + TENHMETAHEADER: ENHMETAHEADER, TENHMETARECORD: ENHMETARECORD].} @@ -11917,15 +11989,92 @@ type WOHandleArray* = array[0..MAXIMUM_WAIT_OBJECTS - 1, HANDLE] PWOHandleArray* = ptr WOHandleArray MMRESULT* = int32 -{.deprecated: [TPRINTERNOTIFYINFO: PRINTER_NOTIFY_INFO, TPRINTERNOTIFYINFODATA: PRINTER_NOTIFY_INFO_DATA, TPRINTERINFO5: PRINTER_INFO_5, TPRINTERINFO4: PRINTER_INFO_4, TPRINTERINFO3: PRINTER_INFO_3, TPRINTERINFO2: PRINTER_INFO_2, TPRINTERINFO1: PRINTER_INFO_1, TPRINTERDEFAULTS: PRINTER_DEFAULTS, TPD: TPRINTDLG, TPREVENTMEDIAREMOVAL: PREVENT_MEDIA_REMOVAL, TPORTINFO2: PORT_INFO_2, TPORTINFO1: PORT_INFO_1, TPOLYTEXT: POLYTEXT, TPERFOBJECTTYPE: PERF_OBJECT_TYPE, TPERFINSTANCEDEFINITION: PERF_INSTANCE_DEFINITION, TPERFDATABLOCK: PERF_DATA_BLOCK, TPERFCOUNTERDEFINITION: PERF_COUNTER_DEFINITION, TPERFCOUNTERBLOCK: PERF_COUNTER_BLOCK, Tparaformat: PARAFORMAT, TPAINTSTRUCT: PAINTSTRUCT, TPSD: TPAGESETUPDLG, TOVERLAPPED: OVERLAPPED, TOUTLINETEXTMETRIC: OUTLINETEXTMETRIC, TTEXTMETRICW: TEXTMETRICW, TTEXTMETRIC: TEXTMETRIC, TOSVERSIONINFOW: OSVERSIONINFOW, TOSVERSIONINFO: OSVERSIONINFO, TOFNOTIFY: OFNOTIFY, TOPENFILENAME_NT4: OPENFILENAME_NT4, TOFSTRUCT: OFSTRUCT, Tnumberfmt: NUMBERFMT, TNSSERVICEINFO: NS_SERVICE_INFO, TSERVICEINFO: SERVICE_INFO, TCLSID: CLSID, TSERVICEADDRESSES: SERVICE_ADDRESSES, TSERVICEADDRESS: SERVICE_ADDRESS, TNONCLIENTMETRICS: NONCLIENTMETRICS, TNMUPDOWN: NM_UPDOWNW, TNMTREEVIEW: NM_TREEVIEW, TTVITEM: TV_ITEM, TNMLISTVIEW: NM_LISTVIEW, TNEWTEXTMETRICEX: NEWTEXTMETRICEX, TNEWTEXTMETRIC: NEWTEXTMETRIC].} +{.deprecated: [TPRINTERNOTIFYINFO: PRINTER_NOTIFY_INFO, TPRINTERNOTIFYINFODATA: PRINTER_NOTIFY_INFO_DATA, + TPRINTERINFO5: PRINTER_INFO_5, TPRINTERINFO4: PRINTER_INFO_4, TPRINTERINFO3: PRINTER_INFO_3, + TPRINTERINFO2: PRINTER_INFO_2, TPRINTERINFO1: PRINTER_INFO_1, TPRINTERDEFAULTS: PRINTER_DEFAULTS, + TPD: TPRINTDLG, TPREVENTMEDIAREMOVAL: PREVENT_MEDIA_REMOVAL, TPORTINFO2: PORT_INFO_2, + TPORTINFO1: PORT_INFO_1, TPOLYTEXT: POLYTEXT, TPERFOBJECTTYPE: PERF_OBJECT_TYPE, + TPERFINSTANCEDEFINITION: PERF_INSTANCE_DEFINITION, TPERFDATABLOCK: PERF_DATA_BLOCK, + TPERFCOUNTERDEFINITION: PERF_COUNTER_DEFINITION, TPERFCOUNTERBLOCK: PERF_COUNTER_BLOCK, + Tparaformat: PARAFORMAT, TPAINTSTRUCT: PAINTSTRUCT, TPSD: TPAGESETUPDLG, TOVERLAPPED: OVERLAPPED, + TOUTLINETEXTMETRIC: OUTLINETEXTMETRIC, TTEXTMETRICW: TEXTMETRICW, TTEXTMETRIC: TEXTMETRIC, + TOSVERSIONINFOW: OSVERSIONINFOW, TOSVERSIONINFO: OSVERSIONINFO, TOFNOTIFY: OFNOTIFY, + TOPENFILENAME_NT4: OPENFILENAME_NT4, TOFSTRUCT: OFSTRUCT, Tnumberfmt: NUMBERFMT, + TNSSERVICEINFO: NS_SERVICE_INFO, TSERVICEINFO: SERVICE_INFO, TCLSID: CLSID, + TSERVICEADDRESSES: SERVICE_ADDRESSES, TSERVICEADDRESS: SERVICE_ADDRESS, + TNONCLIENTMETRICS: NONCLIENTMETRICS, TNMUPDOWN: NM_UPDOWNW, TNMTREEVIEW: NM_TREEVIEW, + TTVITEM: TV_ITEM, TNMLISTVIEW: NM_LISTVIEW, TNEWTEXTMETRICEX: NEWTEXTMETRICEX, + TNEWTEXTMETRIC: NEWTEXTMETRIC].} -{.deprecated: [TNEWCPLINFO: NEWCPLINFO, TNETRESOURCE: NETRESOURCE, TNETRESOURCEA: NETRESOURCE, TNDDESHAREINFO: NDDESHAREINFO, TNCB: NCB, TNAMEBUFFER: NAME_BUFFER, TMULTIKEYHELP: MULTIKEYHELP, Tmsgfilter: MSGFILTER, TMSGBOXPARAMS: MSGBOXPARAMS, TMSGBOXPARAMSA: MSGBOXPARAMS, TMOUSEKEYS: MOUSEKEYS, TMOUSEHOOKSTRUCT: MOUSEHOOKSTRUCT, TMONMSGSTRUCT: MONMSGSTRUCT, TMONLINKSTRUCT: MONLINKSTRUCT, TMONITORINFO2: MONITOR_INFO_2, TMONITORINFO1: MONITOR_INFO_1, TMONHSZSTRUCT: MONHSZSTRUCT, TMONERRSTRUCT: MONERRSTRUCT, TMONCONVSTRUCT: MONCONVSTRUCT, TMONCBSTRUCT: MONCBSTRUCT, TMODEMSETTINGS: MODEMSETTINGS, TMODEMDEVCAPS: MODEMDEVCAPS, TMINMAXINFO: MINMAXINFO, TMINIMIZEDMETRICS: MINIMIZEDMETRICS, TMETARECORD: METARECORD, TMETAHEADER: METAHEADER, TMETAFILEPICT: METAFILEPICT, TMENUTEMPLATE: MENUTEMPLATE, TMENUITEMTEMPLATEHEADER: MENUITEMTEMPLATEHEADER, TMENUITEMTEMPLATE: MENUITEMTEMPLATE, TMENUITEMINFOA: MENUITEMINFO, TMENUITEMINFO: MENUITEMINFO, TMENUINFO: MENUINFO, TMENUEXTEMPLATEITEM: MENUEX_TEMPLATE_ITEM, TMENUXTEMPLATEHEADER: MENUEX_TEMPLATE_HEADER, TMEMORYSTATUS: MEMORYSTATUS, TMEMORYBASICINFORMATION: MEMORY_BASIC_INFORMATION, TMEASUREITEMSTRUCT: MEASUREITEMSTRUCT, TMDICREATESTRUCT: MDICREATESTRUCT, TMAT2: MAT2, TLVKEYDOWN: LV_KEYDOWN, TLVHITTESTINFO: LV_HITTESTINFO, TLVFINDINFO: LV_FINDINFO, TLVDISPINFO: LV_DISPINFO, TLVITEM: LV_ITEM, TLVCOLUMN: LV_COLUMN, TLUIDANDATTRIBUTESARRAY: LUID_AND_ATTRIBUTES_ARRAY, TLUIDANDATTRIBUTES: LUID_AND_ATTRIBUTES, TLUID: LUID, TFXPT16DOT16: FXPT16DOT16, TLOCALGROUPMEMBERSINFO3: LOCALGROUP_MEMBERS_INFO_3, TLOCALGROUPMEMBERSINFO0: LOCALGROUP_MEMBERS_INFO_0, TLOCALESIGNATURE: LOCALESIGNATURE, TGUID: GUID, TOPENFILENAME: OPENFILENAME].} +{.deprecated: [TNEWCPLINFO: NEWCPLINFO, TNETRESOURCE: NETRESOURCE, TNETRESOURCEA: NETRESOURCE, + TNDDESHAREINFO: NDDESHAREINFO, TNCB: NCB, TNAMEBUFFER: NAME_BUFFER, TMULTIKEYHELP: MULTIKEYHELP, + Tmsgfilter: MSGFILTER, TMSGBOXPARAMS: MSGBOXPARAMS, TMSGBOXPARAMSA: MSGBOXPARAMS, TMOUSEKEYS: MOUSEKEYS, + TMOUSEHOOKSTRUCT: MOUSEHOOKSTRUCT, TMONMSGSTRUCT: MONMSGSTRUCT, TMONLINKSTRUCT: MONLINKSTRUCT, + TMONITORINFO2: MONITOR_INFO_2, TMONITORINFO1: MONITOR_INFO_1, TMONHSZSTRUCT: MONHSZSTRUCT, + TMONERRSTRUCT: MONERRSTRUCT, TMONCONVSTRUCT: MONCONVSTRUCT, TMONCBSTRUCT: MONCBSTRUCT, + TMODEMSETTINGS: MODEMSETTINGS, TMODEMDEVCAPS: MODEMDEVCAPS, TMINMAXINFO: MINMAXINFO, + TMINIMIZEDMETRICS: MINIMIZEDMETRICS, TMETARECORD: METARECORD, TMETAHEADER: METAHEADER, + TMETAFILEPICT: METAFILEPICT, TMENUTEMPLATE: MENUTEMPLATE, TMENUITEMTEMPLATEHEADER: MENUITEMTEMPLATEHEADER, + TMENUITEMTEMPLATE: MENUITEMTEMPLATE, TMENUITEMINFOA: MENUITEMINFO, TMENUITEMINFO: MENUITEMINFO, + TMENUINFO: MENUINFO, TMENUEXTEMPLATEITEM: MENUEX_TEMPLATE_ITEM, + TMENUXTEMPLATEHEADER: MENUEX_TEMPLATE_HEADER, TMEMORYSTATUS: MEMORYSTATUS, + TMEMORYBASICINFORMATION: MEMORY_BASIC_INFORMATION, TMEASUREITEMSTRUCT: MEASUREITEMSTRUCT, + TMDICREATESTRUCT: MDICREATESTRUCT, TMAT2: MAT2, TLVKEYDOWN: LV_KEYDOWN, TLVHITTESTINFO: LV_HITTESTINFO, + TLVFINDINFO: LV_FINDINFO, TLVDISPINFO: LV_DISPINFO, TLVITEM: LV_ITEM, TLVCOLUMN: LV_COLUMN, + TLUIDANDATTRIBUTESARRAY: LUID_AND_ATTRIBUTES_ARRAY, TLUIDANDATTRIBUTES: LUID_AND_ATTRIBUTES, + TLUID: LUID, TFXPT16DOT16: FXPT16DOT16, TLOCALGROUPMEMBERSINFO3: LOCALGROUP_MEMBERS_INFO_3, + TLOCALGROUPMEMBERSINFO0: LOCALGROUP_MEMBERS_INFO_0, TLOCALESIGNATURE: LOCALESIGNATURE, + TGUID: GUID, TOPENFILENAME: OPENFILENAME].} -{.deprecated: [TTOGGLEKEYS: TOGGLEKEYS, TTIMEZONEINFORMATION: TIME_ZONE_INFORMATION, Ttextrange: TEXTRANGE, TTCKEYDOWN: TC_KEYDOWN, TTCITEMHEADER: TC_ITEMHEADER, TTCITEM: TC_ITEM, TTCHITTESTINFO: TC_HITTESTINFO, TTBSAVEPARAMS: TBSAVEPARAMS, TTBNOTIFY: TBNOTIFY, TTBBUTTON: TBBUTTON, TTAPEWRITEMARKS: TAPE_WRITE_MARKS, TTAPESETPOSITION: TAPE_SET_POSITION, TTAPESETMEDIAPARAMETERS: TAPE_SET_MEDIA_PARAMETERS, TTAPESETDRIVEPARAMETERS: TAPE_SET_DRIVE_PARAMETERS, TTAPEPREPARE: TAPE_PREPARE, TTAPEGETPOSITION: TAPE_GET_POSITION, TTAPEGETMEDIAPARAMETERS: TAPE_GET_MEDIA_PARAMETERS, TTAPEGETDRIVEPARAMETERS: TAPE_GET_DRIVE_PARAMETERS, TTAPEERASE: TAPE_ERASE, TSYSTEMPOWERSTATUS: SYSTEM_POWER_STATUS, TSYSTEMINFO: SYSTEM_INFO, TSYSTEMAUDITACE: SYSTEM_AUDIT_ACE, TSTYLESTRUCT: STYLESTRUCT, TSTYLEBUF: STYLEBUF, TSTRRET: STRRET, TSTICKYKEYS: STICKYKEYS, TSTARTUPINFO: STARTUPINFO, TSOUNDSENTRY: SOUNDSENTRY, TSINGLELISTENTRY: SINGLE_LIST_ENTRY, TSIDANDATTRIBUTESARRAY: SID_AND_ATTRIBUTES_ARRAY, TSIDANDATTRIBUTES: SID_AND_ATTRIBUTES, TSHNAMEMAPPING: SHNAMEMAPPING, TSHGDN: SHGNO, TSHFILEOPSTRUCT: SHFILEOPSTRUCT, TFILEOPFLAGS: FILEOP_FLAGS, TSHFILEINFO: SHFILEINFO, TSHCONTF: SHCONTF, TSETPARTITIONINFORMATION: SET_PARTITION_INFORMATION, TSESSIONHEADER: SESSION_HEADER].} +{.deprecated: [TTOGGLEKEYS: TOGGLEKEYS, TTIMEZONEINFORMATION: TIME_ZONE_INFORMATION, + Ttextrange: TEXTRANGE, TTCKEYDOWN: TC_KEYDOWN, TTCITEMHEADER: TC_ITEMHEADER, TTCITEM: TC_ITEM, + TTCHITTESTINFO: TC_HITTESTINFO, TTBSAVEPARAMS: TBSAVEPARAMS, TTBNOTIFY: TBNOTIFY, TTBBUTTON: TBBUTTON, + TTAPEWRITEMARKS: TAPE_WRITE_MARKS, TTAPESETPOSITION: TAPE_SET_POSITION, + TTAPESETMEDIAPARAMETERS: TAPE_SET_MEDIA_PARAMETERS, TTAPESETDRIVEPARAMETERS: TAPE_SET_DRIVE_PARAMETERS, + TTAPEPREPARE: TAPE_PREPARE, TTAPEGETPOSITION: TAPE_GET_POSITION, + TTAPEGETMEDIAPARAMETERS: TAPE_GET_MEDIA_PARAMETERS, TTAPEGETDRIVEPARAMETERS: TAPE_GET_DRIVE_PARAMETERS, + TTAPEERASE: TAPE_ERASE, TSYSTEMPOWERSTATUS: SYSTEM_POWER_STATUS, TSYSTEMINFO: SYSTEM_INFO, + TSYSTEMAUDITACE: SYSTEM_AUDIT_ACE, TSTYLESTRUCT: STYLESTRUCT, TSTYLEBUF: STYLEBUF, TSTRRET: STRRET, + TSTICKYKEYS: STICKYKEYS, TSTARTUPINFO: STARTUPINFO, TSOUNDSENTRY: SOUNDSENTRY, + TSINGLELISTENTRY: SINGLE_LIST_ENTRY, TSIDANDATTRIBUTESARRAY: SID_AND_ATTRIBUTES_ARRAY, + TSIDANDATTRIBUTES: SID_AND_ATTRIBUTES, TSHNAMEMAPPING: SHNAMEMAPPING, TSHGDN: SHGNO, + TSHFILEOPSTRUCT: SHFILEOPSTRUCT, TFILEOPFLAGS: FILEOP_FLAGS, TSHFILEINFO: SHFILEINFO, TSHCONTF: SHCONTF, + TSETPARTITIONINFORMATION: SET_PARTITION_INFORMATION, TSESSIONHEADER: SESSION_HEADER].} -{.deprecated: [TSESSIONBUFFER: SESSION_BUFFER, TSERVICETYPEINFOABS: SERVICE_TYPE_INFO_ABS, TSERVICETYPEVALUEABS: SERVICE_TYPE_VALUE_ABS, TSERVICETABLEENTRY: SERVICE_TABLE_ENTRY, TSERIALKEYS: SERIALKEYS, Tselchange: SELCHANGE, TSECURITYINFORMATION: SECURITY_INFORMATION, TSECURITYATTRIBUTES: SECURITY_ATTRIBUTES, TSCROLLINFO: SCROLLINFO, TRGNDATA: RGNDATA, TRGNDATAHEADER: RGNDATAHEADER, Treqresize: REQRESIZE, Trepastespecial: REPASTESPECIAL, TREMOTENAMEINFO: REMOTE_NAME_INFO, TREASSIGNBLOCKS: REASSIGN_BLOCKS, TRASTERIZERSTATUS: RASTERIZER_STATUS, TRASPPPNBF: RASPPPNBF, TRASPPPIPX: RASPPPIPX, TRASPPPIP: RASPPPIP, TRASENTRYNAME: RASENTRYNAME, TRASDIALPARAMS: RASDIALPARAMS, TRASDIALEXTENSIONS: RASDIALEXTENSIONS, TRASCONNSTATUS: RASCONNSTATUS, TRASCONN: RASCONN, TRASAMB: RASAMB, Tpunctuation: PUNCTUATION, TPSHNOTIFY: PSHNOTIFY, TPROVIDORINFO1: PROVIDOR_INFO_1, TPROTOCOLINFO: PROTOCOL_INFO, TFNADDPROPSHEETPAGES: LPFNADDPROPSHEETPAGES, TFNADDPROPSHEETPAGE: LPFNADDPROPSHEETPAGE, TPROPSHEETHEADER: PROPSHEETHEADER, TPROPSHEETPAGE: PROPSHEETPAGE, TFNPSPCALLBACK: LPFNPSPCALLBACK, TPROCESSINFORMATION: PROCESS_INFORMATION, TPROCESSHEAPENTRY: PROCESS_HEAPENTRY, TPRIVILEGESET: PRIVILEGE_SET, TPRINTPROCESSORINFO1: PRINTPROCESSOR_INFO_1, TPRINTERNOTIFYOPTIONS: PRINTER_NOTIFY_OPTIONS, TPRINTERNOTIFYOPTIONSTYPE: PRINTER_NOTIFY_OPTIONS_TYPE].} +{.deprecated: [TSESSIONBUFFER: SESSION_BUFFER, TSERVICETYPEINFOABS: SERVICE_TYPE_INFO_ABS, + TSERVICETYPEVALUEABS: SERVICE_TYPE_VALUE_ABS, TSERVICETABLEENTRY: SERVICE_TABLE_ENTRY, + TSERIALKEYS: SERIALKEYS, Tselchange: SELCHANGE, TSECURITYINFORMATION: SECURITY_INFORMATION, + TSECURITYATTRIBUTES: SECURITY_ATTRIBUTES, TSCROLLINFO: SCROLLINFO, TRGNDATA: RGNDATA, + TRGNDATAHEADER: RGNDATAHEADER, Treqresize: REQRESIZE, Trepastespecial: REPASTESPECIAL, + TREMOTENAMEINFO: REMOTE_NAME_INFO, TREASSIGNBLOCKS: REASSIGN_BLOCKS, TRASTERIZERSTATUS: RASTERIZER_STATUS, + TRASPPPNBF: RASPPPNBF, TRASPPPIPX: RASPPPIPX, TRASPPPIP: RASPPPIP, TRASENTRYNAME: RASENTRYNAME, + TRASDIALPARAMS: RASDIALPARAMS, TRASDIALEXTENSIONS: RASDIALEXTENSIONS, TRASCONNSTATUS: RASCONNSTATUS, + TRASCONN: RASCONN, TRASAMB: RASAMB, Tpunctuation: PUNCTUATION, TPSHNOTIFY: PSHNOTIFY, + TPROVIDORINFO1: PROVIDOR_INFO_1, TPROTOCOLINFO: PROTOCOL_INFO, + TFNADDPROPSHEETPAGES: LPFNADDPROPSHEETPAGES, TFNADDPROPSHEETPAGE: LPFNADDPROPSHEETPAGE, + TPROPSHEETHEADER: PROPSHEETHEADER, TPROPSHEETPAGE: PROPSHEETPAGE, TFNPSPCALLBACK: LPFNPSPCALLBACK, + TPROCESSINFORMATION: PROCESS_INFORMATION, TPROCESSHEAPENTRY: PROCESS_HEAPENTRY, + TPRIVILEGESET: PRIVILEGE_SET, TPRINTPROCESSORINFO1: PRINTPROCESSOR_INFO_1, + TPRINTERNOTIFYOPTIONS: PRINTER_NOTIFY_OPTIONS, TPRINTERNOTIFYOPTIONSTYPE: PRINTER_NOTIFY_OPTIONS_TYPE].} -{.deprecated: [TNotifyIconDataA: NOTIFYICONDATAA, TNotifyIconDataW: NOTIFYICONDATAW, TNotifyIconData: NotifyIconDataA, TIMAGEDOSHEADER: IMAGE_DOS_HEADER, TLOCALGROUPINFO0: LOCALGROUP_INFO_0, TGROUPINFO2: GROUP_INFO_2, TUSERINFO3: USER_INFO_3, TUSERINFO0: USER_INFO_0, TUSERINFO2: USER_INFO_2, TPIXELFORMATDESCRIPTOR: PIXELFORMATDESCRIPTOR, TLAYERPLANEDESCRIPTOR: LAYERPLANEDESCRIPTOR, TGLYPHMETRICSFLOAT: GLYPHMETRICSFLOAT, TPOINTFLOAT: POINTFLOAT, TNETCONNECTINFOSTRUCT: NETCONNECTINFOSTRUCT, TNETINFOSTRUCT: NETINFOSTRUCT, TDISCDLGSTRUCT: DISCDLGSTRUCT, TDISCDLGSTRUCTA: DISCDLGSTRUCT, TCONNECTDLGSTRUCT: CONNECTDLGSTRUCT, TWNDCLASSEXW: WNDCLASSEXW, TWNDCLASSEX: WNDCLASSEX, TWNDCLASSEXA: WNDCLASSEX, TWNDCLASSW: WNDCLASSW, TWNDCLASS: WNDCLASS, TWNDCLASSA: WNDCLASS, TWINDOWPLACEMENT: WINDOWPLACEMENT, TWIN32STREAMID: WIN32_STREAM_ID, TWIN32FINDDATAW: WIN32_FIND_DATAW, TWIN32FINDDATAA: WIN32_FIND_DATA, TWIN32FINDDATA: WIN32_FIND_DATA, TVSFIXEDFILEINFO: VS_FIXEDFILEINFO, TVERIFYINFORMATION: VERIFY_INFORMATION, Tvalue_ent: VALENT, TVALENT: VALENT, TUSEROBJECTFLAGS: USEROBJECTFLAGS, TUNIVERSALNAMEINFO: UNIVERSAL_NAME_INFO, TUDACCEL: UDACCEL, TTVSORTCB: TV_SORTCB, TTVKEYDOWN: TV_KEYDOWN, TTVINSERTSTRUCT: TV_INSERTSTRUCT, TTVHITTESTINFO: TV_HITTESTINFO, TTVDISPINFO: TV_DISPINFO, TTTPOLYGONHEADER: TTPOLYGONHEADER, TTTPOLYCURVE: TTPOLYCURVE, TTTHITTESTINFO: TTHITTESTINFO, TTRANSMITFILEBUFFERS: TRANSMIT_FILE_BUFFERS, TTPMPARAMS: TPMPARAMS, TTOOLTIPTEXT: TOOLTIPTEXT, TTOOLINFO: TOOLINFO, TTOKENCONTROL: TOKEN_CONTROL, TWOHandleArray: WOHandleArray].} +{.deprecated: [TNotifyIconDataA: NOTIFYICONDATAA, TNotifyIconDataW: NOTIFYICONDATAW, + TNotifyIconData: NotifyIconDataA, TIMAGEDOSHEADER: IMAGE_DOS_HEADER, TLOCALGROUPINFO0: LOCALGROUP_INFO_0, + TGROUPINFO2: GROUP_INFO_2, TUSERINFO3: USER_INFO_3, TUSERINFO0: USER_INFO_0, TUSERINFO2: USER_INFO_2, + TPIXELFORMATDESCRIPTOR: PIXELFORMATDESCRIPTOR, TLAYERPLANEDESCRIPTOR: LAYERPLANEDESCRIPTOR, + TGLYPHMETRICSFLOAT: GLYPHMETRICSFLOAT, TPOINTFLOAT: POINTFLOAT, + TNETCONNECTINFOSTRUCT: NETCONNECTINFOSTRUCT, TNETINFOSTRUCT: NETINFOSTRUCT, + TDISCDLGSTRUCT: DISCDLGSTRUCT, TDISCDLGSTRUCTA: DISCDLGSTRUCT, TCONNECTDLGSTRUCT: CONNECTDLGSTRUCT, + TWNDCLASSEXW: WNDCLASSEXW, TWNDCLASSEX: WNDCLASSEX, TWNDCLASSEXA: WNDCLASSEX, TWNDCLASSW: WNDCLASSW, + TWNDCLASS: WNDCLASS, TWNDCLASSA: WNDCLASS, TWINDOWPLACEMENT: WINDOWPLACEMENT, + TWIN32STREAMID: WIN32_STREAM_ID, TWIN32FINDDATAW: WIN32_FIND_DATAW, TWIN32FINDDATAA: WIN32_FIND_DATA, + TWIN32FINDDATA: WIN32_FIND_DATA, TVSFIXEDFILEINFO: VS_FIXEDFILEINFO, + TVERIFYINFORMATION: VERIFY_INFORMATION, Tvalue_ent: VALENT, TVALENT: VALENT, + TUSEROBJECTFLAGS: USEROBJECTFLAGS, TUNIVERSALNAMEINFO: UNIVERSAL_NAME_INFO, TUDACCEL: UDACCEL, + TTVSORTCB: TV_SORTCB, TTVKEYDOWN: TV_KEYDOWN, TTVINSERTSTRUCT: TV_INSERTSTRUCT, + TTVHITTESTINFO: TV_HITTESTINFO, TTVDISPINFO: TV_DISPINFO, TTTPOLYGONHEADER: TTPOLYGONHEADER, + TTTPOLYCURVE: TTPOLYCURVE, TTTHITTESTINFO: TTHITTESTINFO, TTRANSMITFILEBUFFERS: TRANSMIT_FILE_BUFFERS, + TTPMPARAMS: TPMPARAMS, TTOOLTIPTEXT: TOOLTIPTEXT, TTOOLINFO: TOOLINFO, + TTOKENCONTROL: TOKEN_CONTROL, TWOHandleArray: WOHandleArray].} type From b0469c11e334e96cebe53cbe804b6a877831c85a Mon Sep 17 00:00:00 2001 From: Perelandric Date: Tue, 26 May 2015 14:45:51 -0500 Subject: [PATCH 0359/1263] Reverted TZipFileStream name change --- lib/impure/zipfiles.nim | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/lib/impure/zipfiles.nim b/lib/impure/zipfiles.nim index 56483c586..d66d7d7f3 100644 --- a/lib/impure/zipfiles.nim +++ b/lib/impure/zipfiles.nim @@ -109,13 +109,12 @@ proc addFile*(z: var ZipArchive, dest: string, src: Stream) = # -------------- zip file stream --------------------------------------------- type - ZipFileStream = object of StreamObj + TZipFileStream = object of StreamObj f: PZipFile atEnd: bool PZipFileStream* = ref ZipFileStream ## a reader stream of a file within a zip archive -{.deprecated: [TZipFileStream: ZipFileStream].} proc fsClose(s: Stream) = zip_fclose(PZipFileStream(s).f) proc fsAtEnd(s: Stream): bool = PZipFileStream(s).atEnd From e0ecaa86ba91037d11e992749740416793ee152d Mon Sep 17 00:00:00 2001 From: Perelandric Date: Tue, 26 May 2015 14:46:43 -0500 Subject: [PATCH 0360/1263] Reverted all changes --- lib/js/dom.nim | 142 +++++++++++++++++++++++-------------------------- 1 file changed, 68 insertions(+), 74 deletions(-) diff --git a/lib/js/dom.nim b/lib/js/dom.nim index bc870999b..b063fa838 100644 --- a/lib/js/dom.nim +++ b/lib/js/dom.nim @@ -14,56 +14,56 @@ when not defined(js) and not defined(Nimdoc): {.error: "This module only works on the JavaScript platform".} type - EventHandlers* {.importc.} = object of RootObj - onabort*: proc (event: ref Event) {.nimcall.} - onblur*: proc (event: ref Event) {.nimcall.} - onchange*: proc (event: ref Event) {.nimcall.} - onclick*: proc (event: ref Event) {.nimcall.} - ondblclick*: proc (event: ref Event) {.nimcall.} - onerror*: proc (event: ref Event) {.nimcall.} - onfocus*: proc (event: ref Event) {.nimcall.} - onkeydown*: proc (event: ref Event) {.nimcall.} - onkeypress*: proc (event: ref Event) {.nimcall.} - onkeyup*: proc (event: ref Event) {.nimcall.} - onload*: proc (event: ref Event) {.nimcall.} - onmousedown*: proc (event: ref Event) {.nimcall.} - onmousemove*: proc (event: ref Event) {.nimcall.} - onmouseout*: proc (event: ref Event) {.nimcall.} - onmouseover*: proc (event: ref Event) {.nimcall.} - onmouseup*: proc (event: ref Event) {.nimcall.} - onreset*: proc (event: ref Event) {.nimcall.} - onselect*: proc (event: ref Event) {.nimcall.} - onsubmit*: proc (event: ref Event) {.nimcall.} - onunload*: proc (event: ref Event) {.nimcall.} + TEventHandlers* {.importc.} = object of RootObj + onabort*: proc (event: ref TEvent) {.nimcall.} + onblur*: proc (event: ref TEvent) {.nimcall.} + onchange*: proc (event: ref TEvent) {.nimcall.} + onclick*: proc (event: ref TEvent) {.nimcall.} + ondblclick*: proc (event: ref TEvent) {.nimcall.} + onerror*: proc (event: ref TEvent) {.nimcall.} + onfocus*: proc (event: ref TEvent) {.nimcall.} + onkeydown*: proc (event: ref TEvent) {.nimcall.} + onkeypress*: proc (event: ref TEvent) {.nimcall.} + onkeyup*: proc (event: ref TEvent) {.nimcall.} + onload*: proc (event: ref TEvent) {.nimcall.} + onmousedown*: proc (event: ref TEvent) {.nimcall.} + onmousemove*: proc (event: ref TEvent) {.nimcall.} + onmouseout*: proc (event: ref TEvent) {.nimcall.} + onmouseover*: proc (event: ref TEvent) {.nimcall.} + onmouseup*: proc (event: ref TEvent) {.nimcall.} + onreset*: proc (event: ref TEvent) {.nimcall.} + onselect*: proc (event: ref TEvent) {.nimcall.} + onsubmit*: proc (event: ref TEvent) {.nimcall.} + onunload*: proc (event: ref TEvent) {.nimcall.} - addEventListener*: proc(ev: cstring, cb: proc(ev: ref Event), useCapture: bool = false) {.nimcall.} + addEventListener*: proc(ev: cstring, cb: proc(ev: ref TEvent), useCapture: bool = false) {.nimcall.} Window* = ref WindowObj - WindowObj {.importc.} = object of EventHandlers + WindowObj {.importc.} = object of TEventHandlers document*: Document - event*: ref Event - history*: ref History - location*: ref Location + event*: ref TEvent + history*: ref THistory + location*: ref TLocation closed*: bool defaultStatus*: cstring innerHeight*, innerWidth*: int - locationbar*: ref LocationBar - menubar*: ref MenuBar + locationbar*: ref TLocationBar + menubar*: ref TMenuBar name*: cstring outerHeight*, outerWidth*: int pageXOffset*, pageYOffset*: int - personalbar*: ref PersonalBar - scrollbars*: ref ScrollBars - statusbar*: ref StatusBar + personalbar*: ref TPersonalBar + scrollbars*: ref TScrollBars + statusbar*: ref TStatusBar status*: cstring - toolbar*: ref ToolBar + toolbar*: ref TToolBar alert*: proc (msg: cstring) {.nimcall.} back*: proc () {.nimcall.} blur*: proc () {.nimcall.} captureEvents*: proc (eventMask: int) {.nimcall.} - clearInterval*: proc (interval: ref Interval) {.nimcall.} - clearTimeout*: proc (timeout: ref TimeOut) {.nimcall.} + clearInterval*: proc (interval: ref TInterval) {.nimcall.} + clearTimeout*: proc (timeout: ref TTimeOut) {.nimcall.} close*: proc () {.nimcall.} confirm*: proc (msg: cstring): bool {.nimcall.} disableExternalCapture*: proc () {.nimcall.} @@ -72,7 +72,7 @@ type backwards = false) {.nimcall.} focus*: proc () {.nimcall.} forward*: proc () {.nimcall.} - handleEvent*: proc (e: ref Event) {.nimcall.} + handleEvent*: proc (e: ref TEvent) {.nimcall.} home*: proc () {.nimcall.} moveBy*: proc (x, y: int) {.nimcall.} moveTo*: proc (x, y: int) {.nimcall.} @@ -83,13 +83,13 @@ type releaseEvents*: proc (eventMask: int) {.nimcall.} resizeBy*: proc (x, y: int) {.nimcall.} resizeTo*: proc (x, y: int) {.nimcall.} - routeEvent*: proc (event: ref Event) {.nimcall.} + routeEvent*: proc (event: ref TEvent) {.nimcall.} scrollBy*: proc (x, y: int) {.nimcall.} scrollTo*: proc (x, y: int) {.nimcall.} - setInterval*: proc (code: cstring, pause: int): ref Interval {.nimcall.} - setTimeout*: proc (code: cstring, pause: int): ref TimeOut {.nimcall.} + setInterval*: proc (code: cstring, pause: int): ref TInterval {.nimcall.} + setTimeout*: proc (code: cstring, pause: int): ref TTimeOut {.nimcall.} stop*: proc () {.nimcall.} - frames*: seq[FrameObj] + frames*: seq[TFrame] Frame* = ref FrameObj FrameObj {.importc.} = object of WindowObj @@ -100,7 +100,7 @@ type contains*: proc (class: cstring):bool {.nimcall.} toggle*: proc (class: cstring) {.nimcall.} - NodeType* = enum + TNodeType* = enum ElementNode = 1, AttributeNode, TextNode, @@ -115,7 +115,7 @@ type NotationNode Node* = ref NodeObj - NodeObj {.importc.} = object of EventHandlers + NodeObj {.importc.} = object of TEventHandlers attributes*: seq[Node] childNodes*: seq[Node] children*: seq[Node] @@ -124,7 +124,7 @@ type lastChild*: Node nextSibling*: Node nodeName*: cstring - nodeType*: NodeType + nodeType*: TNodeType nodeValue*: cstring parentNode*: Node previousSibling*: Node @@ -146,7 +146,7 @@ type scrollIntoView*: proc () {.nimcall.} setAttribute*: proc (name, value: cstring) {.nimcall.} setAttributeNode*: proc (attr: Node) {.nimcall.} - style*: ref Style + style*: ref TStyle Document* = ref DocumentObj DocumentObj {.importc.} = object of NodeObj @@ -173,16 +173,16 @@ type getElementsByTagName*: proc (name: cstring): seq[Element] {.nimcall.} getElementsByClassName*: proc (name: cstring): seq[Element] {.nimcall.} getSelection*: proc (): cstring {.nimcall.} - handleEvent*: proc (event: ref Event) {.nimcall.} + handleEvent*: proc (event: ref TEvent) {.nimcall.} open*: proc () {.nimcall.} releaseEvents*: proc (eventMask: int) {.nimcall.} - routeEvent*: proc (event: ref Event) {.nimcall.} + routeEvent*: proc (event: ref TEvent) {.nimcall.} write*: proc (text: cstring) {.nimcall.} writeln*: proc (text: cstring) {.nimcall.} anchors*: seq[AnchorElement] forms*: seq[FormElement] images*: seq[ImageElement] - applets*: seq[ref Applet] + applets*: seq[ref TApplet] embeds*: seq[EmbedElement] links*: seq[LinkElement] @@ -199,7 +199,7 @@ type blur*: proc () {.nimcall.} click*: proc () {.nimcall.} focus*: proc () {.nimcall.} - handleEvent*: proc (event: ref Event) {.nimcall.} + handleEvent*: proc (event: ref TEvent) {.nimcall.} select*: proc () {.nimcall.} options*: seq[OptionElement] getElementsByTagName*: proc (name: cstring): seq[Element] {.nimcall.} @@ -228,7 +228,7 @@ type text*: cstring x*, y*: int - Applet* {.importc.} = object of RootObj + TApplet* {.importc.} = object of RootObj OptionElement* = ref OptionObj OptionObj {.importc.} = object of ElementObj @@ -260,7 +260,7 @@ type width*: int - Style* {.importc.} = object of RootObj + TStyle* {.importc.} = object of RootObj background*: cstring backgroundAttachment*: cstring backgroundColor*: cstring @@ -354,7 +354,7 @@ type removeAttribute*: proc (attr: cstring, caseSensitive=false) {.nimcall.} setAttribute*: proc (attr, value: cstring, caseSensitive=false) {.nimcall.} - Event* {.importc.} = object of RootObj + TEvent* {.importc.} = object of RootObj target*: Node altKey*, ctrlKey*, shiftKey*: bool button*: int @@ -393,7 +393,7 @@ type SUBMIT*: int UNLOAD*: int - Location* {.importc.} = object of RootObj + TLocation* {.importc.} = object of RootObj hash*: cstring host*: cstring hostname*: cstring @@ -405,13 +405,13 @@ type reload*: proc () {.nimcall.} replace*: proc (s: cstring) {.nimcall.} - History* {.importc.} = object of RootObj + THistory* {.importc.} = object of RootObj length*: int back*: proc () {.nimcall.} forward*: proc () {.nimcall.} go*: proc (pagesToJump: int) {.nimcall.} - Navigator* {.importc.} = object of RootObj + TNavigator* {.importc.} = object of RootObj appCodeName*: cstring appName*: cstring appVersion*: cstring @@ -420,28 +420,28 @@ type platform*: cstring userAgent*: cstring javaEnabled*: proc (): bool {.nimcall.} - mimeTypes*: seq[ref MimeType] + mimeTypes*: seq[ref TMimeType] - Plugin* {.importc.} = object of RootObj + TPlugin* {.importc.} = object of RootObj description*: cstring filename*: cstring name*: cstring - MimeType* {.importc.} = object of RootObj + TMimeType* {.importc.} = object of RootObj description*: cstring - enabledPlugin*: ref Plugin + enabledPlugin*: ref TPlugin suffixes*: seq[cstring] `type`*: cstring - LocationBar* {.importc.} = object of RootObj + TLocationBar* {.importc.} = object of RootObj visible*: bool - MenuBar* = LocationBar - PersonalBar* = LocationBar - ScrollBars* = LocationBar - ToolBar* = LocationBar - StatusBar* = LocationBar + TMenuBar* = TLocationBar + TPersonalBar* = TLocationBar + TScrollBars* = TLocationBar + TToolBar* = TLocationBar + TStatusBar* = TLocationBar - Screen* {.importc.} = object of RootObj + TScreen* {.importc.} = object of RootObj availHeight*: int availWidth*: int colorDepth*: int @@ -449,20 +449,14 @@ type pixelDepth*: int width*: int - TimeOut* {.importc.} = object of RootObj - Interval* {.importc.} = object of RootObj -{.deprecated: [TEventHandlers: EventHandlers, TEvent: Event, TNodeType: NodeType, - TInterval: Interval, TTimeOut: TimeOut, TStatusBar: StatusBar, - TMenuBar: MenuBar, TApplet: Applet, TLocation: Location, - THistory: History, TNavigator: Navigator, TPlugin: Plugin, - TMimeType: MimeType, TLocationBar: LocationBar, TPersonalBar: PersonalBar, - TScrollBars: ScrollBars, TToolBar: ToolBar, TScreen: Screen].} + TTimeOut* {.importc.} = object of RootObj + TInterval* {.importc.} = object of RootObj var window* {.importc, nodecl.}: Window document* {.importc, nodecl.}: Document - navigator* {.importc, nodecl.}: ref Navigator - screen* {.importc, nodecl.}: ref Screen + navigator* {.importc, nodecl.}: ref TNavigator + screen* {.importc, nodecl.}: ref TScreen proc decodeURI*(uri: cstring): cstring {.importc, nodecl.} proc encodeURI*(uri: cstring): cstring {.importc, nodecl.} From ccb9ae2d52cc42f2489a7bbd758c924a4dbbe872 Mon Sep 17 00:00:00 2001 From: Araq Date: Thu, 4 Jun 2015 13:13:25 +0200 Subject: [PATCH 0361/1263] stdlib: don't use deprecated symbols --- lib/pure/os.nim | 74 ++++++++++++++++++++--------------------- lib/pure/osproc.nim | 14 ++++---- lib/pure/times.nim | 2 +- lib/windows/winlean.nim | 14 ++++---- 4 files changed, 52 insertions(+), 52 deletions(-) diff --git a/lib/pure/os.nim b/lib/pure/os.nim index 38ad9d6ec..4deb79f86 100644 --- a/lib/pure/os.nim +++ b/lib/pure/os.nim @@ -41,7 +41,7 @@ type OSErrorCode* = distinct int32 ## Specifies an OS Error Code. -{.deprecated: [FReadEnv: ReadEnvEffect, FWriteEnv: WriteEnvEffect, +{.deprecated: [FReadEnv: ReadEnvEffect, FWriteEnv: WriteEnvEffect, FReadDir: ReadDirEffect, FWriteDir: WriteDirEffect, TOSErrorCode: OSErrorCode @@ -359,7 +359,7 @@ when defined(windows): template wrapBinary(varname, winApiProc, arg, arg2: expr) {.immediate.} = var varname = winApiProc(newWideCString(arg), arg2) - proc findFirstFile(a: string, b: var TWIN32_FIND_DATA): Handle = + proc findFirstFile(a: string, b: var WIN32_FIND_DATA): Handle = result = findFirstFileW(newWideCString(a), b) template findNextFile(a, b: expr): expr = findNextFileW(a, b) template getCommandLine(): expr = getCommandLineW() @@ -373,7 +373,7 @@ when defined(windows): template getFilename(f: expr): expr = $f.cFilename - proc skipFindData(f: TWIN32_FIND_DATA): bool {.inline.} = + proc skipFindData(f: WIN32_FIND_DATA): bool {.inline.} = # Note - takes advantage of null delimiter in the cstring const dot = ord('.') result = f.cFileName[0].int == dot and (f.cFileName[1].int == 0 or @@ -437,7 +437,7 @@ proc getLastModificationTime*(file: string): Time {.rtl, extern: "nos$1".} = if stat(file, res) < 0'i32: raiseOSError(osLastError()) return res.st_mtime else: - var f: TWIN32_FIND_DATA + var f: WIN32_FIND_DATA var h = findFirstFile(file, f) if h == -1'i32: raiseOSError(osLastError()) result = winTimeToUnixTime(rdFileTime(f.ftLastWriteTime)) @@ -450,7 +450,7 @@ proc getLastAccessTime*(file: string): Time {.rtl, extern: "nos$1".} = if stat(file, res) < 0'i32: raiseOSError(osLastError()) return res.st_atime else: - var f: TWIN32_FIND_DATA + var f: WIN32_FIND_DATA var h = findFirstFile(file, f) if h == -1'i32: raiseOSError(osLastError()) result = winTimeToUnixTime(rdFileTime(f.ftLastAccessTime)) @@ -465,7 +465,7 @@ proc getCreationTime*(file: string): Time {.rtl, extern: "nos$1".} = if stat(file, res) < 0'i32: raiseOSError(osLastError()) return res.st_ctime else: - var f: TWIN32_FIND_DATA + var f: WIN32_FIND_DATA var h = findFirstFile(file, f) if h == -1'i32: raiseOSError(osLastError()) result = winTimeToUnixTime(rdFileTime(f.ftCreationTime)) @@ -801,13 +801,13 @@ when defined(Windows): when useWinUnicode: result = createFileW( - newWideCString(path), 0'i32, + newWideCString(path), 0'i32, FILE_SHARE_DELETE or FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING, flags, 0 ) else: result = createFileA( - path, 0'i32, + path, 0'i32, FILE_SHARE_DELETE or FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING, flags, 0 ) @@ -827,7 +827,7 @@ proc sameFile*(path1, path2: string): bool {.rtl, extern: "nos$1", var lastErr: OSErrorCode if f1 != INVALID_HANDLE_VALUE and f2 != INVALID_HANDLE_VALUE: - var fi1, fi2: TBY_HANDLE_FILE_INFORMATION + var fi1, fi2: BY_HANDLE_FILE_INFORMATION if getFileInformationByHandle(f1, addr(fi1)) != 0 and getFileInformationByHandle(f2, addr(fi2)) != 0: @@ -924,11 +924,11 @@ proc getFilePermissions*(filename: string): set[FilePermission] {. var res = getFileAttributesA(filename) if res == -1'i32: raiseOSError(osLastError()) if (res and FILE_ATTRIBUTE_READONLY) != 0'i32: - result = {fpUserExec, fpUserRead, fpGroupExec, fpGroupRead, + result = {fpUserExec, fpUserRead, fpGroupExec, fpGroupRead, fpOthersExec, fpOthersRead} else: result = {fpUserExec..fpOthersRead} - + proc setFilePermissions*(filename: string, permissions: set[FilePermission]) {. rtl, extern: "nos$1", tags: [WriteDirEffect].} = ## sets the file permissions for `filename`. `OSError` is raised in case of @@ -939,15 +939,15 @@ proc setFilePermissions*(filename: string, permissions: set[FilePermission]) {. if fpUserRead in permissions: p = p or S_IRUSR if fpUserWrite in permissions: p = p or S_IWUSR if fpUserExec in permissions: p = p or S_IXUSR - + if fpGroupRead in permissions: p = p or S_IRGRP if fpGroupWrite in permissions: p = p or S_IWGRP if fpGroupExec in permissions: p = p or S_IXGRP - + if fpOthersRead in permissions: p = p or S_IROTH if fpOthersWrite in permissions: p = p or S_IWOTH if fpOthersExec in permissions: p = p or S_IXOTH - + if chmod(filename, p) != 0: raiseOSError(osLastError()) else: when useWinUnicode: @@ -955,7 +955,7 @@ proc setFilePermissions*(filename: string, permissions: set[FilePermission]) {. else: var res = getFileAttributesA(filename) if res == -1'i32: raiseOSError(osLastError()) - if fpUserWrite in permissions: + if fpUserWrite in permissions: res = res and not FILE_ATTRIBUTE_READONLY else: res = res or FILE_ATTRIBUTE_READONLY @@ -1030,11 +1030,11 @@ when not declared(ENOENT) and not defined(Windows): when defined(Windows): when useWinUnicode: template deleteFile(file: expr): expr {.immediate.} = deleteFileW(file) - template setFileAttributes(file, attrs: expr): expr {.immediate.} = + template setFileAttributes(file, attrs: expr): expr {.immediate.} = setFileAttributesW(file, attrs) else: template deleteFile(file: expr): expr {.immediate.} = deleteFileA(file) - template setFileAttributes(file, attrs: expr): expr {.immediate.} = + template setFileAttributes(file, attrs: expr): expr {.immediate.} = setFileAttributesA(file, attrs) proc removeFile*(file: string) {.rtl, extern: "nos$1", tags: [WriteDirEffect].} = @@ -1047,7 +1047,7 @@ proc removeFile*(file: string) {.rtl, extern: "nos$1", tags: [WriteDirEffect].} else: let f = file if deleteFile(f) == 0: - if getLastError() == ERROR_ACCESS_DENIED: + if getLastError() == ERROR_ACCESS_DENIED: if setFileAttributes(f, FILE_ATTRIBUTE_NORMAL) == 0: raiseOSError(osLastError()) if deleteFile(f) == 0: @@ -1220,7 +1220,7 @@ iterator walkFiles*(pattern: string): string {.tags: [ReadDirEffect].} = ## notation is supported. when defined(windows): var - f: TWIN32_FIND_DATA + f: WIN32_FIND_DATA res: int res = findFirstFile(pattern, f) if res != -1: @@ -1276,7 +1276,7 @@ iterator walkDir*(dir: string): tuple[kind: PathComponent, path: string] {. ## dirA/fileA1.txt ## dirA/fileA2.txt when defined(windows): - var f: TWIN32_FIND_DATA + var f: WIN32_FIND_DATA var h = findFirstFile(dir / "*", f) if h != -1: while true: @@ -1319,9 +1319,9 @@ iterator walkDirRec*(dir: string, filter={pcFile, pcDir}): string {. ## walks over the directory `dir` and yields for each file in `dir`. The ## full path for each file is returned. ## **Warning**: - ## Modifying the directory structure while the iterator - ## is traversing may result in undefined behavior! - ## + ## Modifying the directory structure while the iterator + ## is traversing may result in undefined behavior! + ## ## Walking is recursive. `filter` controls the behaviour of the iterator: ## ## --------------------- --------------------------------------------- @@ -1424,7 +1424,7 @@ proc createSymlink*(src, dest: string) = ## by `src`. On most operating systems, will fail if a lonk ## ## **Warning**: - ## Some OS's (such as Microsoft Windows) restrict the creation + ## Some OS's (such as Microsoft Windows) restrict the creation ## of symlinks to root users (administrators). when defined(Windows): let flag = dirExists(src).int32 @@ -1444,7 +1444,7 @@ proc createHardlink*(src, dest: string) = ## Create a hard link at `dest` which points to the item specified ## by `src`. ## - ## **Warning**: Most OS's restrict the creation of hard links to + ## **Warning**: Most OS's restrict the creation of hard links to ## root users (administrators) . when defined(Windows): when useWinUnicode: @@ -1548,7 +1548,7 @@ proc parseCmdLine*(c: string): seq[string] {. add(a, c[i]) inc(i) add(result, a) - + proc copyFileWithPermissions*(source, dest: string, ignorePermissionErrors = true) = ## Copies a file from `source` to `dest` preserving file permissions. @@ -1851,7 +1851,7 @@ proc getFileSize*(file: string): BiggestInt {.rtl, extern: "nos$1", tags: [ReadIOEffect].} = ## returns the file size of `file`. Can raise ``OSError``. when defined(windows): - var a: TWIN32_FIND_DATA + var a: WIN32_FIND_DATA var resA = findFirstFile(file, a) if resA == -1: raiseOSError(osLastError()) result = rdFileSize(a) @@ -1936,10 +1936,10 @@ template rawToFormalFileInfo(rawInfo, formalInfo): expr = formalInfo.lastAccessTime = toTime(rawInfo.ftLastAccessTime) formalInfo.lastWriteTime = toTime(rawInfo.ftLastWriteTime) formalInfo.creationTime = toTime(rawInfo.ftCreationTime) - + # Retrieve basic permissions if (rawInfo.dwFileAttributes and FILE_ATTRIBUTE_READONLY) != 0'i32: - formalInfo.permissions = {fpUserExec, fpUserRead, fpGroupExec, + formalInfo.permissions = {fpUserExec, fpUserRead, fpGroupExec, fpGroupRead, fpOthersExec, fpOthersRead} else: result.permissions = {fpUserExec..fpOthersRead} @@ -1953,7 +1953,7 @@ template rawToFormalFileInfo(rawInfo, formalInfo): expr = else: - template checkAndIncludeMode(rawMode, formalMode: expr) = + template checkAndIncludeMode(rawMode, formalMode: expr) = if (rawInfo.st_mode and rawMode) != 0'i32: formalInfo.permissions.incl(formalMode) formalInfo.id = (rawInfo.st_dev, rawInfo.st_ino) @@ -1988,7 +1988,7 @@ proc getFileInfo*(handle: FileHandle): FileInfo = ## is invalid, an error will be thrown. # Done: ID, Kind, Size, Permissions, Link Count when defined(Windows): - var rawInfo: TBY_HANDLE_FILE_INFORMATION + var rawInfo: BY_HANDLE_FILE_INFORMATION # We have to use the super special '_get_osfhandle' call (wrapped above) # To transform the C file descripter to a native file handle. var realHandle = get_osfhandle(handle) @@ -2008,22 +2008,22 @@ proc getFileInfo*(file: File): FileInfo = proc getFileInfo*(path: string, followSymlink = true): FileInfo = ## Retrieves file information for the file object pointed to by `path`. - ## + ## ## Due to intrinsic differences between operating systems, the information ## contained by the returned `FileInfo` structure will be slightly different ## across platforms, and in some cases, incomplete or inaccurate. - ## + ## ## When `followSymlink` is true, symlinks are followed and the information ## retrieved is information related to the symlink's target. Otherwise, ## information on the symlink itself is retrieved. - ## + ## ## If the information cannot be retrieved, such as when the path doesn't ## exist, or when permission restrictions prevent the program from retrieving ## file information, an error will be thrown. when defined(Windows): - var + var handle = openHandle(path, followSymlink) - rawInfo: TBY_HANDLE_FILE_INFORMATION + rawInfo: BY_HANDLE_FILE_INFORMATION if handle == INVALID_HANDLE_VALUE: raiseOSError(osLastError()) if getFileInformationByHandle(handle, addr rawInfo) == 0: @@ -2044,7 +2044,7 @@ proc isHidden*(path: string): bool = ## Determines whether a given path is hidden or not. Returns false if the ## file doesn't exist. The given path must be accessible from the current ## working directory of the program. - ## + ## ## On Windows, a file is hidden if the file's 'hidden' attribute is set. ## On Unix-like systems, a file is hidden if it starts with a '.' (period) ## and is not *just* '.' or '..' ' ." diff --git a/lib/pure/osproc.nim b/lib/pure/osproc.nim index f4a0ae3a0..33f5419d5 100644 --- a/lib/pure/osproc.nim +++ b/lib/pure/osproc.nim @@ -396,8 +396,8 @@ when defined(Windows) and not defined(useNimRtl): # O_RDONLY {.importc: "_O_RDONLY", header: "".}: int proc createPipeHandles(rdHandle, wrHandle: var Handle) = - var piInheritablePipe: TSECURITY_ATTRIBUTES - piInheritablePipe.nLength = sizeof(TSECURITY_ATTRIBUTES).cint + var piInheritablePipe: SECURITY_ATTRIBUTES + piInheritablePipe.nLength = sizeof(SECURITY_ATTRIBUTES).cint piInheritablePipe.lpSecurityDescriptor = nil piInheritablePipe.bInheritHandle = 1 if createPipe(rdHandle, wrHandle, piInheritablePipe, 1024) == 0'i32: @@ -412,8 +412,8 @@ when defined(Windows) and not defined(useNimRtl): env: StringTableRef = nil, options: set[ProcessOption] = {poStdErrToStdOut}): Process = var - si: TSTARTUPINFO - procInfo: TPROCESS_INFORMATION + si: STARTUPINFO + procInfo: PROCESS_INFORMATION success: int hi, ho, he: Handle new(result) @@ -526,8 +526,8 @@ when defined(Windows) and not defined(useNimRtl): proc execCmd(command: string): int = var - si: TSTARTUPINFO - procInfo: TPROCESS_INFORMATION + si: STARTUPINFO + procInfo: PROCESS_INFORMATION process: Handle L: int32 si.cb = sizeof(si).cint @@ -555,7 +555,7 @@ when defined(Windows) and not defined(useNimRtl): proc select(readfds: var seq[Process], timeout = 500): int = assert readfds.len <= MAXIMUM_WAIT_OBJECTS - var rfds: TWOHandleArray + var rfds: WOHandleArray for i in 0..readfds.len()-1: rfds[i] = readfds[i].fProcessHandle diff --git a/lib/pure/times.nim b/lib/pure/times.nim index b8836c15b..597488782 100644 --- a/lib/pure/times.nim +++ b/lib/pure/times.nim @@ -470,7 +470,7 @@ when not defined(JS): posix_gettimeofday(a) result = toFloat(a.tv_sec) + toFloat(a.tv_usec)*0.00_0001 elif defined(windows): - var f: winlean.TFILETIME + var f: winlean.FILETIME getSystemTimeAsFileTime(f) var i64 = rdFileTime(f) - epochDiff var secs = i64 div rateDiff diff --git a/lib/windows/winlean.nim b/lib/windows/winlean.nim index 596507ebe..39f2be61d 100644 --- a/lib/windows/winlean.nim +++ b/lib/windows/winlean.nim @@ -439,7 +439,7 @@ type h_length*: int16 h_addr_list*: cstringArray - FdSet* = object + TFdSet* = object fd_count*: cint # unsigned fd_array*: array[0..FD_SETSIZE-1, SocketHandle] @@ -461,7 +461,7 @@ type TSockAddr: SockAddr, TSockLen: SockLen, TTimeval: Timeval, TWSADATA: WSADATA, Thostent: Hostent, TServent: Servent, TInAddr: InAddr, Tin6_addr: In6_addr, Tsockaddr_in6: Sockaddr_in6, - Tsockaddr_in6_old: Sockaddr_in6_old, TFdSet: FdSet].} + Tsockaddr_in6_old: Sockaddr_in6_old].} var @@ -525,7 +525,7 @@ proc recv*(s: SocketHandle, buf: pointer, len, flags: cint): cint {. proc recvfrom*(s: SocketHandle, buf: cstring, len, flags: cint, fromm: ptr SockAddr, fromlen: ptr SockLen): cint {. stdcall, importc: "recvfrom", dynlib: ws2dll.} -proc select*(nfds: cint, readfds, writefds, exceptfds: ptr FdSet, +proc select*(nfds: cint, readfds, writefds, exceptfds: ptr TFdSet, timeout: ptr Timeval): cint {. stdcall, importc: "select", dynlib: ws2dll.} proc send*(s: SocketHandle, buf: pointer, len, flags: cint): cint {. @@ -545,18 +545,18 @@ proc getnameinfo*(a1: ptr SockAddr, a2: SockLen, proc inet_addr*(cp: cstring): int32 {. stdcall, importc: "inet_addr", dynlib: ws2dll.} -proc WSAFDIsSet(s: SocketHandle, set: var FdSet): bool {. +proc WSAFDIsSet(s: SocketHandle, set: var TFdSet): bool {. stdcall, importc: "__WSAFDIsSet", dynlib: ws2dll, noSideEffect.} -proc FD_ISSET*(socket: SocketHandle, set: var FdSet): cint = +proc FD_ISSET*(socket: SocketHandle, set: var TFdSet): cint = result = if WSAFDIsSet(socket, set): 1'i32 else: 0'i32 -proc FD_SET*(socket: SocketHandle, s: var FdSet) = +proc FD_SET*(socket: SocketHandle, s: var TFdSet) = if s.fd_count < FD_SETSIZE: s.fd_array[int(s.fd_count)] = socket inc(s.fd_count) -proc FD_ZERO*(s: var FdSet) = +proc FD_ZERO*(s: var TFdSet) = s.fd_count = 0 proc wsaStartup*(wVersionRequired: int16, WSData: ptr WSAData): cint {. From 22f6017ab89e2fa7101c72e05a7703a83f1385d6 Mon Sep 17 00:00:00 2001 From: Dominik Picheta Date: Thu, 4 Jun 2015 13:55:48 +0100 Subject: [PATCH 0362/1263] Fixes #2584 Better compiler errors for accessing undeclared fields, calling undeclared procedures and procedure fields. --- compiler/msgs.nim | 7 ++++++- compiler/semcall.nim | 9 ++++++++- tests/enum/tenumitems.nim | 2 +- tests/misc/tissue710.nim | 2 +- tests/misc/tnoop.nim | 2 +- tests/modules/topaque.nim | 8 ++++---- tests/tuples/twrongtupleaccess.nim | 2 +- 7 files changed, 22 insertions(+), 10 deletions(-) diff --git a/compiler/msgs.nim b/compiler/msgs.nim index e97032db4..de0caad79 100644 --- a/compiler/msgs.nim +++ b/compiler/msgs.nim @@ -34,7 +34,9 @@ type errNoneSpeedOrSizeExpectedButXFound, errGuiConsoleOrLibExpectedButXFound, errUnknownOS, errUnknownCPU, errGenOutExpectedButXFound, errArgsNeedRunOption, errInvalidMultipleAsgn, errColonOrEqualsExpected, - errExprExpected, errUndeclaredIdentifier, errUseQualifier, errTypeExpected, + errExprExpected, errUndeclaredIdentifier, errUndeclaredField, + errUndeclaredProcedure, errUndeclaredProcedureField, errUseQualifier, + errTypeExpected, errSystemNeeds, errExecutionOfProgramFailed, errNotOverloadable, errInvalidArgForX, errStmtHasNoEffect, errXExpectsTypeOrValue, errXExpectsArrayType, errIteratorCannotBeInstantiated, errExprXAmbiguous, @@ -190,6 +192,9 @@ const errColonOrEqualsExpected: "\':\' or \'=\' expected, but found \'$1\'", errExprExpected: "expression expected, but found \'$1\'", errUndeclaredIdentifier: "undeclared identifier: \'$1\'", + errUndeclaredField: "undeclared field: \'$1\'", + errUndeclaredProcedure: "attempting to call undeclared procedure: \'$1\'", + errUndeclaredProcedureField: "attempting to call undeclared procedure field: \'$1\'", errUseQualifier: "ambiguous identifier: \'$1\' -- use a qualifier", errTypeExpected: "type expected", errSystemNeeds: "system module needs \'$1\'", diff --git a/compiler/semcall.nim b/compiler/semcall.nim index c48e761e3..342397740 100644 --- a/compiler/semcall.nim +++ b/compiler/semcall.nim @@ -209,7 +209,14 @@ proc resolveOverloads(c: PContext, n, orig: PNode, pickBest(callOp) if overloadsState == csEmpty and result.state == csEmpty: - localError(n.info, errUndeclaredIdentifier, considerQuotedIdent(f).s) + if nfDotField in n.flags: + if nfExplicitCall in n.flags: + localError(n.info, errUndeclaredProcedureField, + considerQuotedIdent(f).s) + else: + localError(n.info, errUndeclaredField, considerQuotedIdent(f).s) + else: + localError(n.info, errUndeclaredProcedure, considerQuotedIdent(f).s) return elif result.state != csMatch: if nfExprCall in n.flags: diff --git a/tests/enum/tenumitems.nim b/tests/enum/tenumitems.nim index 04737fa9e..bebeb059f 100644 --- a/tests/enum/tenumitems.nim +++ b/tests/enum/tenumitems.nim @@ -1,6 +1,6 @@ discard """ line: 7 - errormsg: "undeclared identifier: 'items'" + errormsg: "attempting to call undeclared procedure: 'items'" """ type a = enum b,c,d diff --git a/tests/misc/tissue710.nim b/tests/misc/tissue710.nim index ecfdf653e..85b5e79a8 100644 --- a/tests/misc/tissue710.nim +++ b/tests/misc/tissue710.nim @@ -1,7 +1,7 @@ discard """ file: "tissue710.nim" line: 8 - errorMsg: "undeclared identifier: '||'" + errorMsg: "attempting to call undeclared procedure: '||'" """ var sum = 0 for x in 3..1000: diff --git a/tests/misc/tnoop.nim b/tests/misc/tnoop.nim index 10c2eb2ec..50f750d60 100644 --- a/tests/misc/tnoop.nim +++ b/tests/misc/tnoop.nim @@ -1,7 +1,7 @@ discard """ file: "tnoop.nim" line: 11 - errormsg: "undeclared identifier: 'a'" + errormsg: "attempting to call undeclared procedure: 'a'" """ diff --git a/tests/modules/topaque.nim b/tests/modules/topaque.nim index f0587c959..84e2388bc 100644 --- a/tests/modules/topaque.nim +++ b/tests/modules/topaque.nim @@ -1,16 +1,16 @@ discard """ file: "topaque.nim" line: 16 - errormsg: "undeclared identifier: \'buffer\'" + errormsg: "undeclared field: \'buffer\'" """ # Test the new opaque types -import +import mopaque - + var L: TLexer - + L.filename = "ha" L.line = 34 L.buffer[0] = '\0' #ERROR_MSG undeclared field: 'buffer' diff --git a/tests/tuples/twrongtupleaccess.nim b/tests/tuples/twrongtupleaccess.nim index 1a9ae64a2..3ff967eea 100644 --- a/tests/tuples/twrongtupleaccess.nim +++ b/tests/tuples/twrongtupleaccess.nim @@ -1,7 +1,7 @@ discard """ file: "twrongtupleaccess.nim" line: 9 - errormsg: "undeclared identifier: \'setBLAH\'" + errormsg: "attempting to call undeclared procedure field: \'setBLAH\'" """ # Bugfix From 5d6f16cc1ac066aad6d4a8146a558d073b860d12 Mon Sep 17 00:00:00 2001 From: Dominik Picheta Date: Thu, 4 Jun 2015 16:39:38 +0100 Subject: [PATCH 0363/1263] Got rid of errUndeclaredProcedureField. --- compiler/msgs.nim | 3 +-- compiler/semcall.nim | 8 ++------ tests/tuples/twrongtupleaccess.nim | 2 +- 3 files changed, 4 insertions(+), 9 deletions(-) diff --git a/compiler/msgs.nim b/compiler/msgs.nim index de0caad79..6a5707776 100644 --- a/compiler/msgs.nim +++ b/compiler/msgs.nim @@ -35,7 +35,7 @@ type errUnknownOS, errUnknownCPU, errGenOutExpectedButXFound, errArgsNeedRunOption, errInvalidMultipleAsgn, errColonOrEqualsExpected, errExprExpected, errUndeclaredIdentifier, errUndeclaredField, - errUndeclaredProcedure, errUndeclaredProcedureField, errUseQualifier, + errUndeclaredProcedure, errUseQualifier, errTypeExpected, errSystemNeeds, errExecutionOfProgramFailed, errNotOverloadable, errInvalidArgForX, errStmtHasNoEffect, errXExpectsTypeOrValue, @@ -194,7 +194,6 @@ const errUndeclaredIdentifier: "undeclared identifier: \'$1\'", errUndeclaredField: "undeclared field: \'$1\'", errUndeclaredProcedure: "attempting to call undeclared procedure: \'$1\'", - errUndeclaredProcedureField: "attempting to call undeclared procedure field: \'$1\'", errUseQualifier: "ambiguous identifier: \'$1\' -- use a qualifier", errTypeExpected: "type expected", errSystemNeeds: "system module needs \'$1\'", diff --git a/compiler/semcall.nim b/compiler/semcall.nim index 342397740..fc51ac849 100644 --- a/compiler/semcall.nim +++ b/compiler/semcall.nim @@ -209,12 +209,8 @@ proc resolveOverloads(c: PContext, n, orig: PNode, pickBest(callOp) if overloadsState == csEmpty and result.state == csEmpty: - if nfDotField in n.flags: - if nfExplicitCall in n.flags: - localError(n.info, errUndeclaredProcedureField, - considerQuotedIdent(f).s) - else: - localError(n.info, errUndeclaredField, considerQuotedIdent(f).s) + if nfDotField in n.flags and nfExplicitCall notin n.flags: + localError(n.info, errUndeclaredField, considerQuotedIdent(f).s) else: localError(n.info, errUndeclaredProcedure, considerQuotedIdent(f).s) return diff --git a/tests/tuples/twrongtupleaccess.nim b/tests/tuples/twrongtupleaccess.nim index 3ff967eea..5e1068fdf 100644 --- a/tests/tuples/twrongtupleaccess.nim +++ b/tests/tuples/twrongtupleaccess.nim @@ -1,7 +1,7 @@ discard """ file: "twrongtupleaccess.nim" line: 9 - errormsg: "attempting to call undeclared procedure field: \'setBLAH\'" + errormsg: "attempting to call undeclared procedure: \'setBLAH\'" """ # Bugfix From 9d3b2d1e058990df65c44f76e2c07eeb1c623dbb Mon Sep 17 00:00:00 2001 From: apense Date: Thu, 4 Jun 2015 13:31:40 -0400 Subject: [PATCH 0364/1263] Fixed code indentation in procs.txt Now matches tut2.txt --- doc/manual/procs.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/manual/procs.txt b/doc/manual/procs.txt index 38e343686..23b5e4d1e 100644 --- a/doc/manual/procs.txt +++ b/doc/manual/procs.txt @@ -404,7 +404,7 @@ dispatch. result.a = a result.b = b -echo eval(newPlus(newPlus(newLit(1), newLit(2)), newLit(4))) + echo eval(newPlus(newPlus(newLit(1), newLit(2)), newLit(4))) In the example the constructors ``newLit`` and ``newPlus`` are procs because they should use static binding, but ``eval`` is a method because it From 846489f81330a092953ca5d4651d72f6e1341cd7 Mon Sep 17 00:00:00 2001 From: apense Date: Thu, 4 Jun 2015 16:18:18 -0400 Subject: [PATCH 0365/1263] Fixed links in Error hierarchy Manual contained invalid links --- doc/exception_hierarchy_fragment.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc/exception_hierarchy_fragment.txt b/doc/exception_hierarchy_fragment.txt index f4a419fc4..a02d9ccef 100644 --- a/doc/exception_hierarchy_fragment.txt +++ b/doc/exception_hierarchy_fragment.txt @@ -11,8 +11,8 @@ * `FloatInvalidOpError `_ * `FloatOverflowError `_ * `FloatUnderflowError `_ - * `FieldError `_ - * `IndexError `_ + * `FieldError `_ + * `IndexError `_ * `ObjectAssignmentError `_ * `ObjectConversionError `_ * `ValueError `_ From 0a810fd10f81e11e6b738a18ff18e62c89479436 Mon Sep 17 00:00:00 2001 From: Oscar Campbell Date: Thu, 4 Jun 2015 22:53:39 +0200 Subject: [PATCH 0366/1263] Treat unitest's default esc.seq. output as empty. --- tests/testament/tester.nim | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/tests/testament/tester.nim b/tests/testament/tester.nim index ebfea591a..2c4460395 100644 --- a/tests/testament/tester.nim +++ b/tests/testament/tester.nim @@ -286,6 +286,7 @@ proc testSpec(r: var TResults, test: TTest) = let (buf, exitCode) = execCmdEx(exeCmd) let bufB = if expected.sortoutput: makeDeterministic(strip(buf.string)) else: strip(buf.string) + let expectedOut = strip(expected.outp) if exitCode != expected.exitCode: r.addResult(test, "exitcode: " & $expected.exitCode, @@ -294,11 +295,13 @@ proc testSpec(r: var TResults, test: TTest) = reExitCodesDiffer) return - if bufB != strip(expected.outp): - if not (expected.substr and expected.outp in bufB): - given.err = reOutputsDiffer - r.addResult(test, expected.outp, bufB, reOutputsDiffer) - return + # This is a bit ugly atm. + if bufB != expectedOut: + if not (expected.substr and expectedOut in bufB): + if not (expectedOut == "" and bufB == "\27[0m"): + given.err = reOutputsDiffer + r.addResult(test, expected.outp, bufB, reOutputsDiffer) + return compilerOutputTests(test, given, expected, r) return From 2d9a24f3f6af0f978a95bc833ccc76ca47054b3c Mon Sep 17 00:00:00 2001 From: Dominik Picheta Date: Thu, 4 Jun 2015 23:07:57 +0100 Subject: [PATCH 0367/1263] Hopefully fixes nimsuggest building against the compiler package. --- compiler/nimfix/nimfix.nim | 14 ++++++++------ compiler/nimfix/pretty.nim | 20 +++++++++++--------- compiler/nimfix/prettybase.nim | 7 ++++--- compiler/plugins/locals/locals.nim | 3 ++- 4 files changed, 25 insertions(+), 19 deletions(-) diff --git a/compiler/nimfix/nimfix.nim b/compiler/nimfix/nimfix.nim index 8caa23ee3..3641aec36 100644 --- a/compiler/nimfix/nimfix.nim +++ b/compiler/nimfix/nimfix.nim @@ -10,8 +10,10 @@ ## Nimfix is a tool that helps to convert old-style Nimrod code to Nim code. import strutils, os, parseopt -import options, commands, modules, sem, passes, passaux, pretty, msgs, nimconf, - extccomp, condsyms, lists +import compiler/options, compiler/commands, compiler/modules, compiler/sem, + compiler/passes, compiler/passaux, compiler/nimfix/pretty, + compiler/msgs, compiler/nimconf, + compiler/extccomp, compiler/condsyms, compiler/lists const Usage = """ Nimfix - Tool to patch Nim code @@ -24,7 +26,7 @@ Options: --wholeProject overwrite every processed file. --checkExtern:on|off style check also extern names --styleCheck:on|off|auto performs style checking for identifiers - and suggests an alternative spelling; + and suggests an alternative spelling; 'auto' corrects the spelling. --bestEffort try to fix the code even when there are errors. @@ -48,11 +50,11 @@ proc processCmdLine*(pass: TCmdLinePass, cmd: string) = var p = parseopt.initOptParser(cmd) var argsCount = 0 gOnlyMainfile = true - while true: + while true: parseopt.next(p) case p.kind - of cmdEnd: break - of cmdLongoption, cmdShortOption: + of cmdEnd: break + of cmdLongoption, cmdShortOption: case p.key.normalize of "overwritefiles": case p.val.normalize diff --git a/compiler/nimfix/pretty.nim b/compiler/nimfix/pretty.nim index d2d5b5e83..1123afb9e 100644 --- a/compiler/nimfix/pretty.nim +++ b/compiler/nimfix/pretty.nim @@ -10,9 +10,11 @@ ## This module implements the code "prettifier". This is part of the toolchain ## to convert Nim code into a consistent style. -import - strutils, os, options, ast, astalgo, msgs, ropes, idents, - intsets, strtabs, semdata, prettybase +import + strutils, os, intsets, strtabs + +import compiler/options, compiler/ast, compiler/astalgo, compiler/msgs, + compiler/semdata, compiler/nimfix/prettybase, compiler/ropes, compiler/idents type StyleCheck* {.pure.} = enum None, Warn, Auto @@ -92,7 +94,7 @@ proc beautifyName(s: string, k: TSymKind): string = proc replaceInFile(info: TLineInfo; newName: string) = loadFile(info) - + let line = gSourceFiles[info.fileIndex].lines[info.line-1] var first = min(info.col.int, line.len) if first < 0: return @@ -100,18 +102,18 @@ proc replaceInFile(info: TLineInfo; newName: string) = while first > 0 and line[first-1] in prettybase.Letters: dec first if first < 0: return if line[first] == '`': inc first - + let last = first+identLen(line, first)-1 if differ(line, first, last, newName): - # last-first+1 != newName.len or - var x = line.substr(0, first-1) & newName & line.substr(last+1) + # last-first+1 != newName.len or + var x = line.substr(0, first-1) & newName & line.substr(last+1) system.shallowCopy(gSourceFiles[info.fileIndex].lines[info.line-1], x) gSourceFiles[info.fileIndex].dirty = true proc checkStyle(info: TLineInfo, s: string, k: TSymKind; sym: PSym) = let beau = beautifyName(s, k) if s != beau: - if gStyleCheck == StyleCheck.Auto: + if gStyleCheck == StyleCheck.Auto: sym.name = getIdent(beau) replaceInFile(info, beau) else: @@ -137,7 +139,7 @@ proc styleCheckUseImpl(info: TLineInfo; s: PSym) = if info.fileIndex < 0: return # we simply convert it to what it looks like in the definition # for consistency - + # operators stay as they are: if s.kind in {skResult, skTemp} or s.name.s[0] notin prettybase.Letters: return diff --git a/compiler/nimfix/prettybase.nim b/compiler/nimfix/prettybase.nim index 5130d1863..0f17cbcb1 100644 --- a/compiler/nimfix/prettybase.nim +++ b/compiler/nimfix/prettybase.nim @@ -7,7 +7,8 @@ # distribution, for details about the copyright. # -import ast, msgs, strutils, idents, lexbase, streams +import strutils, lexbase, streams +import compiler/ast, compiler/msgs, compiler/idents from os import splitFile type @@ -39,7 +40,7 @@ proc loadFile*(info: TLineInfo) = var pos = lex.bufpos while true: case lex.buf[pos] - of '\c': + of '\c': gSourceFiles[i].newline = "\c\L" break of '\L', '\0': @@ -70,7 +71,7 @@ proc replaceDeprecated*(info: TLineInfo; oldSym, newSym: PIdent) = while first > 0 and line[first-1] in Letters: dec first if first < 0: return if line[first] == '`': inc first - + let last = first+identLen(line, first)-1 if cmpIgnoreStyle(line[first..last], oldSym.s) == 0: var x = line.substr(0, first-1) & newSym.s & line.substr(last+1) diff --git a/compiler/plugins/locals/locals.nim b/compiler/plugins/locals/locals.nim index d89149f33..59e3d677d 100644 --- a/compiler/plugins/locals/locals.nim +++ b/compiler/plugins/locals/locals.nim @@ -9,7 +9,8 @@ ## The builtin 'system.locals' implemented as a plugin. -import plugins, ast, astalgo, magicsys, lookups, semdata, lowerings +import compiler/plugins, compiler/ast, compiler/astalgo, compiler/magicsys, + compiler/lookups, compiler/semdata, compiler/lowerings proc semLocals(c: PContext, n: PNode): PNode = var counter = 0 From 0b124a20434738f60a50c3703f4b970c9f697e37 Mon Sep 17 00:00:00 2001 From: Dominik Picheta Date: Thu, 4 Jun 2015 23:12:38 +0100 Subject: [PATCH 0368/1263] Fixes compilation with --gc:markandsweep. --- lib/system/gc_ms.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/system/gc_ms.nim b/lib/system/gc_ms.nim index aab28eba2..ee80c61e9 100644 --- a/lib/system/gc_ms.nim +++ b/lib/system/gc_ms.nim @@ -58,7 +58,7 @@ type stat: GcStat additionalRoots: CellSeq # dummy roots for GC_ref/unref {.deprecated: [TWalkOp: WalkOp, TFinalizer: Finalizer, TGcStat: GcStat, - TGlobalMarkerProc: GlobalMarkerProc, TGcHeap, GcHeap].} + TGlobalMarkerProc: GlobalMarkerProc, TGcHeap: GcHeap].} var gch {.rtlThreadVar.}: GcHeap From ed46ca6d57e4db8d229ac6d8b608ca71f6fc7081 Mon Sep 17 00:00:00 2001 From: Dominik Picheta Date: Thu, 4 Jun 2015 23:23:41 +0100 Subject: [PATCH 0369/1263] Add WSAEADDRINUSE to winlean. --- lib/windows/winlean.nim | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/windows/winlean.nim b/lib/windows/winlean.nim index 39f2be61d..9f04bab35 100644 --- a/lib/windows/winlean.nim +++ b/lib/windows/winlean.nim @@ -690,6 +690,7 @@ const ERROR_IO_PENDING* = 997 # a.k.a WSA_IO_PENDING FILE_FLAG_OVERLAPPED* = 1073741824 WSAECONNABORTED* = 10053 + WSAEADDRINUSE* = 10048 WSAECONNRESET* = 10054 WSAEDISCON* = 10101 WSAENETRESET* = 10052 From 16da925a0aec91525fd124a238698d010d77e81d Mon Sep 17 00:00:00 2001 From: Dominik Picheta Date: Thu, 4 Jun 2015 23:25:29 +0100 Subject: [PATCH 0370/1263] Removed nimsuggest from this repo. --- compiler/nimsuggest/nimsuggest.nim | 328 +------------------------ compiler/nimsuggest/nimsuggest.nim.cfg | 17 -- 2 files changed, 2 insertions(+), 343 deletions(-) delete mode 100644 compiler/nimsuggest/nimsuggest.nim.cfg diff --git a/compiler/nimsuggest/nimsuggest.nim b/compiler/nimsuggest/nimsuggest.nim index 2c785d118..2be368d68 100644 --- a/compiler/nimsuggest/nimsuggest.nim +++ b/compiler/nimsuggest/nimsuggest.nim @@ -7,330 +7,6 @@ # distribution, for details about the copyright. # -## Nimsuggest is a tool that helps to give editors IDE like capabilities. +## Nimsuggest has been moved to https://github.com/nim-lang/nimsuggest -import strutils, os, parseopt, parseutils, sequtils, net -# Do NOT import suggest. It will lead to wierd bugs with -# suggestionResultHook, because suggest.nim is included by sigmatch. -# So we import that one instead. -import options, commands, modules, sem, passes, passaux, msgs, nimconf, - extccomp, condsyms, lists, net, rdstdin, sexp, sigmatch, ast - -when defined(windows): - import winlean -else: - import posix - -const Usage = """ -Nimsuggest - Tool to give every editor IDE like capabilities for Nim -Usage: - nimsuggest [options] projectfile.nim - -Options: - --port:PORT port, by default 6000 - --address:HOST binds to that address, by default "" - --stdin read commands from stdin and write results to - stdout instead of using sockets - --epc use emacs epc mode - -The server then listens to the connection and takes line-based commands. - -In addition, all command line options of Nim that do not affect code generation -are supported. -""" -type - Mode = enum mstdin, mtcp, mepc - -var - gPort = 6000.Port - gAddress = "" - gMode: Mode - -const - seps = {':', ';', ' ', '\t'} - Help = "usage: sug|con|def|use file.nim[;dirtyfile.nim]:line:col\n"& - "type 'quit' to quit\n" & - "type 'debug' to toggle debug mode on/off\n" & - "type 'terse' to toggle terse mode on/off" - -type - EUnexpectedCommand = object of Exception - -proc parseQuoted(cmd: string; outp: var string; start: int): int = - var i = start - i += skipWhitespace(cmd, i) - if cmd[i] == '"': - i += parseUntil(cmd, outp, '"', i+1)+2 - else: - i += parseUntil(cmd, outp, seps, i) - result = i - -proc sexp(s: IdeCmd): SexpNode = sexp($s) - -proc sexp(s: TSymKind): SexpNode = sexp($s) - -proc sexp(s: Suggest): SexpNode = - # If you change the oder here, make sure to change it over in - # nim-mode.el too. - result = convertSexp([ - s.section, - s.symkind, - s.qualifiedPath.map(newSString), - s.filePath, - s.forth, - s.line, - s.column, - s.doc - ]) - -proc sexp(s: seq[Suggest]): SexpNode = - result = newSList() - for sug in s: - result.add(sexp(sug)) - -proc listEPC(): SexpNode = - let - argspecs = sexp("file line column dirtyfile".split(" ").map(newSSymbol)) - docstring = sexp("line starts at 1, column at 0, dirtyfile is optional") - result = newSList() - for command in ["sug", "con", "def", "use"]: - let - cmd = sexp(command) - methodDesc = newSList() - methodDesc.add(cmd) - methodDesc.add(argspecs) - methodDesc.add(docstring) - result.add(methodDesc) - -proc execute(cmd: IdeCmd, file, dirtyfile: string, line, col: int) = - gIdeCmd = cmd - if cmd == ideUse: - modules.resetAllModules() - var isKnownFile = true - let dirtyIdx = file.fileInfoIdx(isKnownFile) - - if dirtyfile.len != 0: msgs.setDirtyFile(dirtyIdx, dirtyfile) - else: msgs.setDirtyFile(dirtyIdx, nil) - - resetModule dirtyIdx - if dirtyIdx != gProjectMainIdx: - resetModule gProjectMainIdx - - gTrackPos = newLineInfo(dirtyIdx, line, col) - gErrorCounter = 0 - if not isKnownFile: - compileProject() - compileProject(dirtyIdx) - -proc executeEPC(cmd: IdeCmd, args: SexpNode) = - let - file = args[0].getStr - line = args[1].getNum - column = args[2].getNum - var dirtyfile = "" - if len(args) > 3: - dirtyfile = args[3].getStr(nil) - execute(cmd, file, dirtyfile, int(line), int(column)) - -proc returnEPC(socket: var Socket, uid: BiggestInt, s: SexpNode, return_symbol = "return") = - let response = $convertSexp([newSSymbol(return_symbol), uid, s]) - socket.send(toHex(len(response), 6)) - socket.send(response) - -proc connectToNextFreePort(server: Socket, host: string, start = 30000): int = - result = start - while true: - try: - server.bindaddr(Port(result), host) - return - except OsError: - when defined(windows): - let checkFor = WSAEADDRINUSE.OSErrorCode - else: - let checkFor = EADDRINUSE.OSErrorCode - if osLastError() != checkFor: - raise getCurrentException() - else: - result += 1 - -proc parseCmdLine(cmd: string) = - template toggle(sw) = - if sw in gGlobalOptions: - excl(gGlobalOptions, sw) - else: - incl(gGlobalOptions, sw) - return - - template err() = - echo Help - return - - var opc = "" - var i = parseIdent(cmd, opc, 0) - case opc.normalize - of "sug": gIdeCmd = ideSug - of "con": gIdeCmd = ideCon - of "def": gIdeCmd = ideDef - of "use": gIdeCmd = ideUse - of "quit": quit() - of "debug": toggle optIdeDebug - of "terse": toggle optIdeTerse - else: err() - var dirtyfile = "" - var orig = "" - i = parseQuoted(cmd, orig, i) - if cmd[i] == ';': - i = parseQuoted(cmd, dirtyfile, i+1) - i += skipWhile(cmd, seps, i) - var line = -1 - var col = 0 - i += parseInt(cmd, line, i) - i += skipWhile(cmd, seps, i) - i += parseInt(cmd, col, i) - - execute(gIdeCmd, orig, dirtyfile, line, col-1) - -proc serve() = - case gMode: - of mstdin: - echo Help - var line = "" - while readLineFromStdin("> ", line): - parseCmdLine line - echo "" - flushFile(stdout) - of mtcp: - var server = newSocket() - server.bindAddr(gPort, gAddress) - var inp = "".TaintedString - server.listen() - - while true: - var stdoutSocket = newSocket() - msgs.writelnHook = proc (line: string) = - stdoutSocket.send(line & "\c\L") - - accept(server, stdoutSocket) - - stdoutSocket.readLine(inp) - parseCmdLine inp.string - - stdoutSocket.send("\c\L") - stdoutSocket.close() - of mepc: - var server = newSocket() - let port = connectToNextFreePort(server, "localhost") - var inp = "".TaintedString - server.listen() - echo(port) - var client = newSocket() - # Wait for connection - accept(server, client) - while true: - var sizeHex = "" - if client.recv(sizeHex, 6) != 6: - raise newException(ValueError, "didn't get all the hexbytes") - var size = 0 - if parseHex(sizeHex, size) == 0: - raise newException(ValueError, "invalid size hex: " & $sizeHex) - var messageBuffer = "" - if client.recv(messageBuffer, size) != size: - raise newException(ValueError, "didn't get all the bytes") - let - message = parseSexp($messageBuffer) - messageType = message[0].getSymbol - case messageType: - of "call": - var results: seq[Suggest] = @[] - suggestionResultHook = proc (s: Suggest) = - results.add(s) - - let - uid = message[1].getNum - cmd = parseIdeCmd(message[2].getSymbol) - args = message[3] - executeEPC(cmd, args) - returnEPC(client, uid, sexp(results)) - of "return": - raise newException(EUnexpectedCommand, "no return expected") - of "return-error": - raise newException(EUnexpectedCommand, "no return expected") - of "epc-error": - stderr.writeln("recieved epc error: " & $messageBuffer) - raise newException(IOError, "epc error") - of "methods": - returnEPC(client, message[1].getNum, listEPC()) - else: - raise newException(EUnexpectedCommand, "unexpected call: " & messageType) - -proc mainCommand = - registerPass verbosePass - registerPass semPass - gCmd = cmdIdeTools - incl gGlobalOptions, optCaasEnabled - isServing = true - wantMainModule() - appendStr(searchPaths, options.libpath) - if gProjectFull.len != 0: - # current path is always looked first for modules - prependStr(searchPaths, gProjectPath) - - # do not stop after the first error: - msgs.gErrorMax = high(int) - compileProject() - serve() - -proc processCmdLine*(pass: TCmdLinePass, cmd: string) = - var p = parseopt.initOptParser(cmd) - while true: - parseopt.next(p) - case p.kind - of cmdEnd: break - of cmdLongoption, cmdShortOption: - case p.key.normalize - of "port": - gPort = parseInt(p.val).Port - gMode = mtcp - of "address": - gAddress = p.val - gMode = mtcp - of "stdin": gMode = mstdin - of "epc": - gMode = mepc - gVerbosity = 0 # Port number gotta be first. - else: processSwitch(pass, p) - of cmdArgument: - options.gProjectName = unixToNativePath(p.key) - # if processArgument(pass, p, argsCount): break - -proc handleCmdLine() = - if paramCount() == 0: - stdout.writeln(Usage) - else: - processCmdLine(passCmd1, "") - if gProjectName != "": - try: - gProjectFull = canonicalizePath(gProjectName) - except OSError: - gProjectFull = gProjectName - var p = splitFile(gProjectFull) - gProjectPath = p.dir - gProjectName = p.name - else: - gProjectPath = getCurrentDir() - loadConfigs(DefaultConfig) # load all config files - # now process command line arguments again, because some options in the - # command line can overwite the config file's settings - extccomp.initVars() - processCmdLine(passCmd2, "") - mainCommand() - -when false: - proc quitCalled() {.noconv.} = - writeStackTrace() - - addQuitProc(quitCalled) - -condsyms.initDefines() -defineSymbol "nimsuggest" -handleCmdline() +{.error: "This project has moved to the following repo: https://github.com/nim-lang/nimsuggest".} diff --git a/compiler/nimsuggest/nimsuggest.nim.cfg b/compiler/nimsuggest/nimsuggest.nim.cfg deleted file mode 100644 index acca17396..000000000 --- a/compiler/nimsuggest/nimsuggest.nim.cfg +++ /dev/null @@ -1,17 +0,0 @@ -# Special configuration file for the Nim project - -gc:markAndSweep - -hint[XDeclaredButNotUsed]:off -path:"$projectPath/../.." - -path:"$lib/packages/docutils" -path:"../../compiler" - -define:useStdoutAsStdmsg -define:nimsuggest - -cs:partial -#define:useNodeIds -define:booting -#define:noDocgen From 2dcaa75e2dc9b607fab54ebcb744d31220f99322 Mon Sep 17 00:00:00 2001 From: Adam Strzelecki Date: Fri, 5 Jun 2015 12:44:28 +0200 Subject: [PATCH 0371/1263] Fixup: Reverted TZipFileStream name change This fixes broken b0469c11e334e96cebe53cbe804b6a877831c85a that incompletely reverted TZipFileStream name change. --- lib/impure/zipfiles.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/impure/zipfiles.nim b/lib/impure/zipfiles.nim index d66d7d7f3..d8903f5c1 100644 --- a/lib/impure/zipfiles.nim +++ b/lib/impure/zipfiles.nim @@ -114,7 +114,7 @@ type atEnd: bool PZipFileStream* = - ref ZipFileStream ## a reader stream of a file within a zip archive + ref TZipFileStream ## a reader stream of a file within a zip archive proc fsClose(s: Stream) = zip_fclose(PZipFileStream(s).f) proc fsAtEnd(s: Stream): bool = PZipFileStream(s).atEnd From 7909591d41436c5a0563158943aece55cb167e34 Mon Sep 17 00:00:00 2001 From: Adam Strzelecki Date: Fri, 5 Jun 2015 14:00:27 +0200 Subject: [PATCH 0372/1263] Bring back (again) bootstrap.sh executable bit Reverts "bootstrap.sh: cannot keep exec bit on windows" commit 2d2eca18b8c326f1e3ea9101d00b3370c8c5c290. We do not need to remove executable bits to workaround old msysGit bug that shows files having executable bits as modified. This can and should be addressed by msysGit user either by using latest version that will treat `bootstrap.sh` as having executable bit because of UNIX Shebang presence, or setting Git config's `core.fileMode` to false. See: http://stackoverflow.com/questions/12193020/file-mode-with-msysgit http://www.grumpydev.com/2011/01/19/switching-from-cygwin-to-msysgit-git-thinks-everything-has-been-modified/ Quoting Git manual: core.fileMode If false, the executable bit differences between the index and the working copy are ignored; useful on broken filesystems like FAT. See git-update-index(1). True by default. --- bootstrap.sh | 0 1 file changed, 0 insertions(+), 0 deletions(-) mode change 100644 => 100755 bootstrap.sh diff --git a/bootstrap.sh b/bootstrap.sh old mode 100644 new mode 100755 From 1cf1610bdf19282b5bc9481fd27b05246a72c176 Mon Sep 17 00:00:00 2001 From: Dominik Picheta Date: Fri, 5 Jun 2015 14:50:14 +0100 Subject: [PATCH 0373/1263] Rename errUndeclaredProcedure to errUndeclaredRoutine. --- compiler/msgs.nim | 4 ++-- compiler/semcall.nim | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/compiler/msgs.nim b/compiler/msgs.nim index 6a5707776..81a62371e 100644 --- a/compiler/msgs.nim +++ b/compiler/msgs.nim @@ -35,7 +35,7 @@ type errUnknownOS, errUnknownCPU, errGenOutExpectedButXFound, errArgsNeedRunOption, errInvalidMultipleAsgn, errColonOrEqualsExpected, errExprExpected, errUndeclaredIdentifier, errUndeclaredField, - errUndeclaredProcedure, errUseQualifier, + errUndeclaredRoutine, errUseQualifier, errTypeExpected, errSystemNeeds, errExecutionOfProgramFailed, errNotOverloadable, errInvalidArgForX, errStmtHasNoEffect, errXExpectsTypeOrValue, @@ -193,7 +193,7 @@ const errExprExpected: "expression expected, but found \'$1\'", errUndeclaredIdentifier: "undeclared identifier: \'$1\'", errUndeclaredField: "undeclared field: \'$1\'", - errUndeclaredProcedure: "attempting to call undeclared procedure: \'$1\'", + errUndeclaredRoutine: "attempting to call undeclared routine: \'$1\'", errUseQualifier: "ambiguous identifier: \'$1\' -- use a qualifier", errTypeExpected: "type expected", errSystemNeeds: "system module needs \'$1\'", diff --git a/compiler/semcall.nim b/compiler/semcall.nim index fc51ac849..571504c3a 100644 --- a/compiler/semcall.nim +++ b/compiler/semcall.nim @@ -212,7 +212,7 @@ proc resolveOverloads(c: PContext, n, orig: PNode, if nfDotField in n.flags and nfExplicitCall notin n.flags: localError(n.info, errUndeclaredField, considerQuotedIdent(f).s) else: - localError(n.info, errUndeclaredProcedure, considerQuotedIdent(f).s) + localError(n.info, errUndeclaredRoutine, considerQuotedIdent(f).s) return elif result.state != csMatch: if nfExprCall in n.flags: From ad6ad5d8d083a87b4771df8f8e757655481d0f0a Mon Sep 17 00:00:00 2001 From: Dominik Picheta Date: Fri, 5 Jun 2015 14:53:49 +0100 Subject: [PATCH 0374/1263] s/procedure/routine/ in tests. --- tests/enum/tenumitems.nim | 2 +- tests/misc/tissue710.nim | 2 +- tests/misc/tnoop.nim | 2 +- tests/tuples/twrongtupleaccess.nim | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/enum/tenumitems.nim b/tests/enum/tenumitems.nim index bebeb059f..38233aad7 100644 --- a/tests/enum/tenumitems.nim +++ b/tests/enum/tenumitems.nim @@ -1,6 +1,6 @@ discard """ line: 7 - errormsg: "attempting to call undeclared procedure: 'items'" + errormsg: "attempting to call undeclared routine: 'items'" """ type a = enum b,c,d diff --git a/tests/misc/tissue710.nim b/tests/misc/tissue710.nim index 85b5e79a8..3b6d3e5f3 100644 --- a/tests/misc/tissue710.nim +++ b/tests/misc/tissue710.nim @@ -1,7 +1,7 @@ discard """ file: "tissue710.nim" line: 8 - errorMsg: "attempting to call undeclared procedure: '||'" + errorMsg: "attempting to call undeclared routine: '||'" """ var sum = 0 for x in 3..1000: diff --git a/tests/misc/tnoop.nim b/tests/misc/tnoop.nim index 50f750d60..1e3fbe6cf 100644 --- a/tests/misc/tnoop.nim +++ b/tests/misc/tnoop.nim @@ -1,7 +1,7 @@ discard """ file: "tnoop.nim" line: 11 - errormsg: "attempting to call undeclared procedure: 'a'" + errormsg: "attempting to call undeclared routine: 'a'" """ diff --git a/tests/tuples/twrongtupleaccess.nim b/tests/tuples/twrongtupleaccess.nim index 5e1068fdf..b1684b097 100644 --- a/tests/tuples/twrongtupleaccess.nim +++ b/tests/tuples/twrongtupleaccess.nim @@ -1,7 +1,7 @@ discard """ file: "twrongtupleaccess.nim" line: 9 - errormsg: "attempting to call undeclared procedure: \'setBLAH\'" + errormsg: "attempting to call undeclared routine: \'setBLAH\'" """ # Bugfix From c4c64804e5b26876b7f331f48dea052d4feade4c Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Fri, 5 Jun 2015 11:04:15 -0500 Subject: [PATCH 0375/1263] moved sexp.nim to nimsuggest repo --- lib/pure/sexp.nim | 698 ---------------------------------------------- 1 file changed, 698 deletions(-) delete mode 100644 lib/pure/sexp.nim diff --git a/lib/pure/sexp.nim b/lib/pure/sexp.nim deleted file mode 100644 index be6188c9e..000000000 --- a/lib/pure/sexp.nim +++ /dev/null @@ -1,698 +0,0 @@ -# -# -# Nim's Runtime Library -# (c) Copyright 2015 Andreas Rumpf, Dominik Picheta -# -# See the file "copying.txt", included in this -# distribution, for details about the copyright. -# - -import - hashes, strutils, lexbase, streams, unicode, macros - -type - SexpEventKind* = enum ## enumeration of all events that may occur when parsing - sexpError, ## an error occurred during parsing - sexpEof, ## end of file reached - sexpString, ## a string literal - sexpSymbol, ## a symbol - sexpInt, ## an integer literal - sexpFloat, ## a float literal - sexpNil, ## the value ``nil`` - sexpDot, ## the dot to separate car/cdr - sexpListStart, ## start of a list: the ``(`` token - sexpListEnd, ## end of a list: the ``)`` token - - TokKind = enum # must be synchronized with SexpEventKind! - tkError, - tkEof, - tkString, - tkSymbol, - tkInt, - tkFloat, - tkNil, - tkDot, - tkParensLe, - tkParensRi - tkSpace - - SexpError* = enum ## enumeration that lists all errors that can occur - errNone, ## no error - errInvalidToken, ## invalid token - errParensRiExpected, ## ``)`` expected - errQuoteExpected, ## ``"`` expected - errEofExpected, ## EOF expected - - SexpParser* = object of BaseLexer ## the parser object. - a: string - tok: TokKind - kind: SexpEventKind - err: SexpError -{.deprecated: [TTokKind: TokKind].} - -const - errorMessages: array [SexpError, string] = [ - "no error", - "invalid token", - "')' expected", - "'\"' or \"'\" expected", - "EOF expected", - ] - tokToStr: array [TokKind, string] = [ - "invalid token", - "EOF", - "string literal", - "symbol", - "int literal", - "float literal", - "nil", - ".", - "(", ")", "space" - ] - -proc close*(my: var SexpParser) {.inline.} = - ## closes the parser `my` and its associated input stream. - lexbase.close(my) - -proc str*(my: SexpParser): string {.inline.} = - ## returns the character data for the events: ``sexpInt``, ``sexpFloat``, - ## ``sexpString`` - assert(my.kind in {sexpInt, sexpFloat, sexpString}) - result = my.a - -proc getInt*(my: SexpParser): BiggestInt {.inline.} = - ## returns the number for the event: ``sexpInt`` - assert(my.kind == sexpInt) - result = parseBiggestInt(my.a) - -proc getFloat*(my: SexpParser): float {.inline.} = - ## returns the number for the event: ``sexpFloat`` - assert(my.kind == sexpFloat) - result = parseFloat(my.a) - -proc kind*(my: SexpParser): SexpEventKind {.inline.} = - ## returns the current event type for the SEXP parser - result = my.kind - -proc getColumn*(my: SexpParser): int {.inline.} = - ## get the current column the parser has arrived at. - result = getColNumber(my, my.bufpos) - -proc getLine*(my: SexpParser): int {.inline.} = - ## get the current line the parser has arrived at. - result = my.lineNumber - -proc errorMsg*(my: SexpParser): string = - ## returns a helpful error message for the event ``sexpError`` - assert(my.kind == sexpError) - result = "($1, $2) Error: $3" % [$getLine(my), $getColumn(my), errorMessages[my.err]] - -proc errorMsgExpected*(my: SexpParser, e: string): string = - ## returns an error message "`e` expected" in the same format as the - ## other error messages - result = "($1, $2) Error: $3" % [$getLine(my), $getColumn(my), e & " expected"] - -proc handleHexChar(c: char, x: var int): bool = - result = true # Success - case c - of '0'..'9': x = (x shl 4) or (ord(c) - ord('0')) - of 'a'..'f': x = (x shl 4) or (ord(c) - ord('a') + 10) - of 'A'..'F': x = (x shl 4) or (ord(c) - ord('A') + 10) - else: result = false # error - -proc parseString(my: var SexpParser): TokKind = - result = tkString - var pos = my.bufpos + 1 - var buf = my.buf - while true: - case buf[pos] - of '\0': - my.err = errQuoteExpected - result = tkError - break - of '"': - inc(pos) - break - of '\\': - case buf[pos+1] - of '\\', '"', '\'', '/': - add(my.a, buf[pos+1]) - inc(pos, 2) - of 'b': - add(my.a, '\b') - inc(pos, 2) - of 'f': - add(my.a, '\f') - inc(pos, 2) - of 'n': - add(my.a, '\L') - inc(pos, 2) - of 'r': - add(my.a, '\C') - inc(pos, 2) - of 't': - add(my.a, '\t') - inc(pos, 2) - of 'u': - inc(pos, 2) - var r: int - if handleHexChar(buf[pos], r): inc(pos) - if handleHexChar(buf[pos], r): inc(pos) - if handleHexChar(buf[pos], r): inc(pos) - if handleHexChar(buf[pos], r): inc(pos) - add(my.a, toUTF8(Rune(r))) - else: - # don't bother with the error - add(my.a, buf[pos]) - inc(pos) - of '\c': - pos = lexbase.handleCR(my, pos) - buf = my.buf - add(my.a, '\c') - of '\L': - pos = lexbase.handleLF(my, pos) - buf = my.buf - add(my.a, '\L') - else: - add(my.a, buf[pos]) - inc(pos) - my.bufpos = pos # store back - -proc parseNumber(my: var SexpParser) = - var pos = my.bufpos - var buf = my.buf - if buf[pos] == '-': - add(my.a, '-') - inc(pos) - if buf[pos] == '.': - add(my.a, "0.") - inc(pos) - else: - while buf[pos] in Digits: - add(my.a, buf[pos]) - inc(pos) - if buf[pos] == '.': - add(my.a, '.') - inc(pos) - # digits after the dot: - while buf[pos] in Digits: - add(my.a, buf[pos]) - inc(pos) - if buf[pos] in {'E', 'e'}: - add(my.a, buf[pos]) - inc(pos) - if buf[pos] in {'+', '-'}: - add(my.a, buf[pos]) - inc(pos) - while buf[pos] in Digits: - add(my.a, buf[pos]) - inc(pos) - my.bufpos = pos - -proc parseSymbol(my: var SexpParser) = - var pos = my.bufpos - var buf = my.buf - if buf[pos] in IdentStartChars: - while buf[pos] in IdentChars: - add(my.a, buf[pos]) - inc(pos) - my.bufpos = pos - -proc getTok(my: var SexpParser): TokKind = - setLen(my.a, 0) - case my.buf[my.bufpos] - of '-', '0'..'9': # numbers that start with a . are not parsed - # correctly. - parseNumber(my) - if {'.', 'e', 'E'} in my.a: - result = tkFloat - else: - result = tkInt - of '"': #" # gotta fix nim-mode - result = parseString(my) - of '(': - inc(my.bufpos) - result = tkParensLe - of ')': - inc(my.bufpos) - result = tkParensRi - of '\0': - result = tkEof - of 'a'..'z', 'A'..'Z', '_': - parseSymbol(my) - if my.a == "nil": - result = tkNil - else: - result = tkSymbol - of ' ': - result = tkSpace - inc(my.bufpos) - of '.': - result = tkDot - inc(my.bufpos) - else: - inc(my.bufpos) - result = tkError - my.tok = result - -# ------------- higher level interface --------------------------------------- - -type - SexpNodeKind* = enum ## possible SEXP node types - SNil, - SInt, - SFloat, - SString, - SSymbol, - SList, - SCons - - SexpNode* = ref SexpNodeObj ## SEXP node - SexpNodeObj* {.acyclic.} = object - case kind*: SexpNodeKind - of SString: - str*: string - of SSymbol: - symbol*: string - of SInt: - num*: BiggestInt - of SFloat: - fnum*: float - of SList: - elems*: seq[SexpNode] - of SCons: - car: SexpNode - cdr: SexpNode - of SNil: - discard - - Cons = tuple[car: SexpNode, cdr: SexpNode] - - SexpParsingError* = object of ValueError ## is raised for a SEXP error - -proc raiseParseErr*(p: SexpParser, msg: string) {.noinline, noreturn.} = - ## raises an `ESexpParsingError` exception. - raise newException(SexpParsingError, errorMsgExpected(p, msg)) - -proc newSString*(s: string): SexpNode {.procvar.}= - ## Creates a new `SString SexpNode`. - new(result) - result.kind = SString - result.str = s - -proc newSStringMove(s: string): SexpNode = - new(result) - result.kind = SString - shallowCopy(result.str, s) - -proc newSInt*(n: BiggestInt): SexpNode {.procvar.} = - ## Creates a new `SInt SexpNode`. - new(result) - result.kind = SInt - result.num = n - -proc newSFloat*(n: float): SexpNode {.procvar.} = - ## Creates a new `SFloat SexpNode`. - new(result) - result.kind = SFloat - result.fnum = n - -proc newSNil*(): SexpNode {.procvar.} = - ## Creates a new `SNil SexpNode`. - new(result) - -proc newSCons*(car, cdr: SexpNode): SexpNode {.procvar.} = - ## Creates a new `SCons SexpNode` - new(result) - result.kind = SCons - result.car = car - result.cdr = cdr - -proc newSList*(): SexpNode {.procvar.} = - ## Creates a new `SList SexpNode` - new(result) - result.kind = SList - result.elems = @[] - -proc newSSymbol*(s: string): SexpNode {.procvar.} = - new(result) - result.kind = SSymbol - result.symbol = s - -proc newSSymbolMove(s: string): SexpNode = - new(result) - result.kind = SSymbol - shallowCopy(result.symbol, s) - -proc getStr*(n: SexpNode, default: string = ""): string = - ## Retrieves the string value of a `SString SexpNode`. - ## - ## Returns ``default`` if ``n`` is not a ``SString``. - if n.kind != SString: return default - else: return n.str - -proc getNum*(n: SexpNode, default: BiggestInt = 0): BiggestInt = - ## Retrieves the int value of a `SInt SexpNode`. - ## - ## Returns ``default`` if ``n`` is not a ``SInt``. - if n.kind != SInt: return default - else: return n.num - -proc getFNum*(n: SexpNode, default: float = 0.0): float = - ## Retrieves the float value of a `SFloat SexpNode`. - ## - ## Returns ``default`` if ``n`` is not a ``SFloat``. - if n.kind != SFloat: return default - else: return n.fnum - -proc getSymbol*(n: SexpNode, default: string = ""): string = - ## Retrieves the int value of a `SList SexpNode`. - ## - ## Returns ``default`` if ``n`` is not a ``SList``. - if n.kind != SSymbol: return default - else: return n.symbol - -proc getElems*(n: SexpNode, default: seq[SexpNode] = @[]): seq[SexpNode] = - ## Retrieves the int value of a `SList SexpNode`. - ## - ## Returns ``default`` if ``n`` is not a ``SList``. - if n.kind == SNil: return @[] - elif n.kind != SList: return default - else: return n.elems - -proc getCons*(n: SexpNode, defaults: Cons = (newSNil(), newSNil())): Cons = - ## Retrieves the cons value of a `SList SexpNode`. - ## - ## Returns ``default`` if ``n`` is not a ``SList``. - if n.kind == SCons: return (n.car, n.cdr) - elif n.kind == SList: return (n.elems[0], n.elems[1]) - else: return defaults - -proc sexp*(s: string): SexpNode = - ## Generic constructor for SEXP data. Creates a new `SString SexpNode`. - new(result) - result.kind = SString - result.str = s - -proc sexp*(n: BiggestInt): SexpNode = - ## Generic constructor for SEXP data. Creates a new `SInt SexpNode`. - new(result) - result.kind = SInt - result.num = n - -proc sexp*(n: float): SexpNode = - ## Generic constructor for SEXP data. Creates a new `SFloat SexpNode`. - new(result) - result.kind = SFloat - result.fnum = n - -proc sexp*(b: bool): SexpNode = - ## Generic constructor for SEXP data. Creates a new `SSymbol - ## SexpNode` with value t or `SNil SexpNode`. - new(result) - if b: - result.kind = SSymbol - result.symbol = "t" - else: - result.kind = SNil - -proc sexp*(elements: openArray[SexpNode]): SexpNode = - ## Generic constructor for SEXP data. Creates a new `SList SexpNode` - new(result) - result.kind = SList - newSeq(result.elems, elements.len) - for i, p in pairs(elements): result.elems[i] = p - -proc sexp*(s: SexpNode): SexpNode = - result = s - -proc toSexp(x: NimNode): NimNode {.compiletime.} = - case x.kind - of nnkBracket: - result = newNimNode(nnkBracket) - for i in 0 .. = 32 and r <= 127: - var c = chr(r) - case c - of '"': result.add("\\\"") #" # gotta fix nim-mode - of '\\': result.add("\\\\") - else: result.add(c) - else: - result.add("\\u") - result.add(toHex(r, 4)) - result.add("\"") - -proc copy*(p: SexpNode): SexpNode = - ## Performs a deep copy of `a`. - case p.kind - of SString: - result = newSString(p.str) - of SInt: - result = newSInt(p.num) - of SFloat: - result = newSFloat(p.fnum) - of SNil: - result = newSNil() - of SSymbol: - result = newSSymbol(p.symbol) - of SList: - result = newSList() - for i in items(p.elems): - result.elems.add(copy(i)) - of SCons: - result = newSCons(copy(p.car), copy(p.cdr)) - -proc toPretty(result: var string, node: SexpNode, indent = 2, ml = true, - lstArr = false, currIndent = 0) = - case node.kind - of SString: - if lstArr: result.indent(currIndent) - result.add(escapeJson(node.str)) - of SInt: - if lstArr: result.indent(currIndent) - result.add($node.num) - of SFloat: - if lstArr: result.indent(currIndent) - result.add($node.fnum) - of SNil: - if lstArr: result.indent(currIndent) - result.add("nil") - of SSymbol: - if lstArr: result.indent(currIndent) - result.add($node.symbol) - of SList: - if lstArr: result.indent(currIndent) - if len(node.elems) != 0: - result.add("(") - result.nl(ml) - for i in 0..len(node.elems)-1: - if i > 0: - result.add(" ") - result.nl(ml) # New Line - toPretty(result, node.elems[i], indent, ml, - true, newIndent(currIndent, indent, ml)) - result.nl(ml) - result.indent(currIndent) - result.add(")") - else: result.add("nil") - of SCons: - if lstArr: result.indent(currIndent) - result.add("(") - toPretty(result, node.car, indent, ml, - true, newIndent(currIndent, indent, ml)) - result.add(" . ") - toPretty(result, node.cdr, indent, ml, - true, newIndent(currIndent, indent, ml)) - result.add(")") - -proc pretty*(node: SexpNode, indent = 2): string = - ## Converts `node` to its Sexp Representation, with indentation and - ## on multiple lines. - result = "" - toPretty(result, node, indent) - -proc `$`*(node: SexpNode): string = - ## Converts `node` to its SEXP Representation on one line. - result = "" - toPretty(result, node, 0, false) - -iterator items*(node: SexpNode): SexpNode = - ## Iterator for the items of `node`. `node` has to be a SList. - assert node.kind == SList - for i in items(node.elems): - yield i - -iterator mitems*(node: var SexpNode): var SexpNode = - ## Iterator for the items of `node`. `node` has to be a SList. Items can be - ## modified. - assert node.kind == SList - for i in mitems(node.elems): - yield i - -proc eat(p: var SexpParser, tok: TokKind) = - if p.tok == tok: discard getTok(p) - else: raiseParseErr(p, tokToStr[tok]) - -proc parseSexp(p: var SexpParser): SexpNode = - ## Parses SEXP from a SEXP Parser `p`. - case p.tok - of tkString: - # we capture 'p.a' here, so we need to give it a fresh buffer afterwards: - result = newSStringMove(p.a) - p.a = "" - discard getTok(p) - of tkInt: - result = newSInt(parseBiggestInt(p.a)) - discard getTok(p) - of tkFloat: - result = newSFloat(parseFloat(p.a)) - discard getTok(p) - of tkNil: - result = newSNil() - discard getTok(p) - of tkSymbol: - result = newSSymbolMove(p.a) - p.a = "" - discard getTok(p) - of tkParensLe: - result = newSList() - discard getTok(p) - while p.tok notin {tkParensRi, tkDot}: - result.add(parseSexp(p)) - if p.tok != tkSpace: break - discard getTok(p) - if p.tok == tkDot: - eat(p, tkDot) - eat(p, tkSpace) - result.add(parseSexp(p)) - result = newSCons(result[0], result[1]) - eat(p, tkParensRi) - of tkSpace, tkDot, tkError, tkParensRi, tkEof: - raiseParseErr(p, "(") - -proc open*(my: var SexpParser, input: Stream) = - ## initializes the parser with an input stream. - lexbase.open(my, input) - my.kind = sexpError - my.a = "" - -proc parseSexp*(s: Stream): SexpNode = - ## Parses from a buffer `s` into a `SexpNode`. - var p: SexpParser - p.open(s) - discard getTok(p) # read first token - result = p.parseSexp() - p.close() - -proc parseSexp*(buffer: string): SexpNode = - ## Parses Sexp from `buffer`. - result = parseSexp(newStringStream(buffer)) - -when isMainModule: - let testSexp = parseSexp("""(1 (98 2) nil (2) foobar "foo" 9.234)""") - assert(testSexp[0].getNum == 1) - assert(testSexp[1][0].getNum == 98) - assert(testSexp[2].getElems == @[]) - assert(testSexp[4].getSymbol == "foobar") - assert(testSexp[5].getStr == "foo") - - let alist = parseSexp("""((1 . 2) (2 . "foo"))""") - assert(alist[0].getCons.car.getNum == 1) - assert(alist[0].getCons.cdr.getNum == 2) - assert(alist[1].getCons.cdr.getStr == "foo") - - # Generator: - var j = convertSexp([true, false, "foobar", [1, 2, "baz"]]) - assert($j == """(t nil "foobar" (1 2 "baz"))""") From 9d03d166a8bc4fb933f76596a89e30447869f83f Mon Sep 17 00:00:00 2001 From: Dominik Picheta Date: Fri, 5 Jun 2015 17:10:17 +0100 Subject: [PATCH 0376/1263] Update version in compiler.nimble --- compiler.nimble | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/compiler.nimble b/compiler.nimble index 52eb4083b..9d39af502 100644 --- a/compiler.nimble +++ b/compiler.nimble @@ -1,6 +1,6 @@ [Package] name = "compiler" -version = "0.10.3" +version = "0.11.3" author = "Andreas Rumpf" description = "Compiler package providing the compiler sources as a library." license = "MIT" @@ -8,4 +8,4 @@ license = "MIT" InstallDirs = "doc, compiler" [Deps] -Requires: "nim >= 0.10.3" +Requires: "nim >= 0.11.3" From 706080dcbdafd8c87f73edac3707a2e5605656b8 Mon Sep 17 00:00:00 2001 From: Araq Date: Sat, 6 Jun 2015 11:04:48 +0200 Subject: [PATCH 0377/1263] fixes 'noreturn' regression for Visual C++ --- compiler/cgen.nim | 2 ++ 1 file changed, 2 insertions(+) diff --git a/compiler/cgen.nim b/compiler/cgen.nim index 4b0bac28a..91877833a 100644 --- a/compiler/cgen.nim +++ b/compiler/cgen.nim @@ -721,6 +721,8 @@ proc genProcPrototype(m: BModule, sym: PSym) = getTypeDesc(m, sym.loc.t), mangleDynLibProc(sym))) elif not containsOrIncl(m.declaredProtos, sym.id): var header = genProcHeader(m, sym) + if sfNoReturn in sym.flags and hasDeclspec in extccomp.CC[cCompiler].props: + header = "__declspec(noreturn) " & header if sym.typ.callConv != ccInline and crossesCppBoundary(m, sym): header = "extern \"C\" " & header if sfPure in sym.flags and hasAttribute in CC[cCompiler].props: From a730a974ed7c585b2f3ade88e06eb308244fa83e Mon Sep 17 00:00:00 2001 From: Araq Date: Sat, 6 Jun 2015 11:50:35 +0200 Subject: [PATCH 0378/1263] fixes #2854 --- compiler/ast.nim | 2 +- tests/parallel/tptr_to_ref.nim | 26 ++++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 tests/parallel/tptr_to_ref.nim diff --git a/compiler/ast.nim b/compiler/ast.nim index c349f81ed..c141352cb 100644 --- a/compiler/ast.nim +++ b/compiler/ast.nim @@ -1346,7 +1346,7 @@ proc propagateToOwner*(owner, elem: PType) = owner.flags.incl tfHasAsgn if owner.kind notin {tyProc, tyGenericInst, tyGenericBody, - tyGenericInvocation}: + tyGenericInvocation, tyPtr}: let elemB = elem.skipTypes({tyGenericInst}) if elemB.isGCedMem or tfHasGCedMem in elemB.flags: # for simplicity, we propagate this flag even to generics. We then diff --git a/tests/parallel/tptr_to_ref.nim b/tests/parallel/tptr_to_ref.nim new file mode 100644 index 000000000..66d618481 --- /dev/null +++ b/tests/parallel/tptr_to_ref.nim @@ -0,0 +1,26 @@ +# bug #2854 + +import locks, threadpool, osproc + +const MAX_WORKERS = 10 + +type + Killer = object + lock: Lock + bailed {.guard: lock.}: bool + processes {.guard: lock.}: array[0..MAX_WORKERS-1, foreign ptr Process] + +template hold(lock: Lock, body: stmt) = + lock.acquire + defer: lock.release + {.locks: [lock].}: + body + +proc initKiller*(): Killer = + initLock(result.lock) + result.lock.hold: + result.bailed = false + for i, _ in result.processes: + result.processes[i] = nil + +var killer = initKiller() From adfdb4623dc7f0150a75a1a0d71c439f540111bd Mon Sep 17 00:00:00 2001 From: Araq Date: Sat, 6 Jun 2015 11:50:51 +0200 Subject: [PATCH 0379/1263] use new type names --- lib/pure/concurrency/cpuload.nim | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/lib/pure/concurrency/cpuload.nim b/lib/pure/concurrency/cpuload.nim index 1f3f54056..22598b5c9 100644 --- a/lib/pure/concurrency/cpuload.nim +++ b/lib/pure/concurrency/cpuload.nim @@ -13,7 +13,7 @@ when defined(windows): import winlean, os, strutils, math - proc `-`(a, b: TFILETIME): int64 = a.rdFileTime - b.rdFileTime + proc `-`(a, b: FILETIME): int64 = a.rdFileTime - b.rdFileTime elif defined(linux): from cpuinfo import countProcessors @@ -25,16 +25,16 @@ type ThreadPoolState* = object when defined(windows): - prevSysKernel, prevSysUser, prevProcKernel, prevProcUser: TFILETIME + prevSysKernel, prevSysUser, prevProcKernel, prevProcUser: FILETIME calls*: int proc advice*(s: var ThreadPoolState): ThreadPoolAdvice = when defined(windows): var sysIdle, sysKernel, sysUser, - procCreation, procExit, procKernel, procUser: TFILETIME + procCreation, procExit, procKernel, procUser: FILETIME if getSystemTimes(sysIdle, sysKernel, sysUser) == 0 or - getProcessTimes(Handle(-1), procCreation, procExit, + getProcessTimes(Handle(-1), procCreation, procExit, procKernel, procUser) == 0: return doNothing if s.calls > 0: @@ -57,7 +57,7 @@ proc advice*(s: var ThreadPoolState): ThreadPoolAdvice = s.prevProcKernel = procKernel s.prevProcUser = procUser elif defined(linux): - proc fscanf(c: File, frmt: cstring) {.varargs, importc, + proc fscanf(c: File, frmt: cstring) {.varargs, importc, header: "".} var f = open("/proc/loadavg") From d94fcb38f04c51ecc7929a7b9649ef21738592d7 Mon Sep 17 00:00:00 2001 From: Araq Date: Sat, 6 Jun 2015 11:57:27 +0200 Subject: [PATCH 0380/1263] fixes #2687 --- compiler/sempass2.nim | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/compiler/sempass2.nim b/compiler/sempass2.nim index adf03be64..12c4a7c7b 100644 --- a/compiler/sempass2.nim +++ b/compiler/sempass2.nim @@ -207,9 +207,9 @@ proc markGcUnsafe(a: PEffects; reason: PNode) = a.owner.gcUnsafetyReason = newSym(skUnknown, getIdent(""), a.owner, reason.info) -proc listGcUnsafety(s: PSym; onlyWarning: bool) = +proc listGcUnsafety(s: PSym; onlyWarning: bool; cycleCheck: var IntSet) = let u = s.gcUnsafetyReason - if u != nil: + if u != nil and not cycleCheck.containsOrIncl(u.id): let msgKind = if onlyWarning: warnGcUnsafe2 else: errGenerated if u.kind in {skLet, skVar}: message(s.info, msgKind, @@ -218,7 +218,7 @@ proc listGcUnsafety(s: PSym; onlyWarning: bool) = elif u.kind in routineKinds: # recursive call *always* produces only a warning so the full error # message is printed: - listGcUnsafety(u, true) + listGcUnsafety(u, true, cycleCheck) message(s.info, msgKind, "'$#' is not GC-safe as it calls '$#'" % [s.name.s, u.name.s]) @@ -227,6 +227,10 @@ proc listGcUnsafety(s: PSym; onlyWarning: bool) = message(u.info, msgKind, "'$#' is not GC-safe as it performs an indirect call here" % s.name.s) +proc listGcUnsafety(s: PSym; onlyWarning: bool) = + var cycleCheck = initIntSet() + listGcUnsafety(s, onlyWarning, cycleCheck) + proc useVar(a: PEffects, n: PNode) = let s = n.sym if isLocalVar(a, s): From 54750f608df65b1f56035da424cc2c9098e70841 Mon Sep 17 00:00:00 2001 From: Araq Date: Sat, 6 Jun 2015 13:25:20 +0200 Subject: [PATCH 0381/1263] fixes #2774 --- compiler/ccgexprs.nim | 2 +- tests/vm/tconstobj.nim | 14 ++++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) create mode 100644 tests/vm/tconstobj.nim diff --git a/compiler/ccgexprs.nim b/compiler/ccgexprs.nim index 05a3602d1..64902c3fc 100644 --- a/compiler/ccgexprs.nim +++ b/compiler/ccgexprs.nim @@ -2150,7 +2150,7 @@ proc genNamedConstExpr(p: BProc, n: PNode): Rope = proc genConstSimpleList(p: BProc, n: PNode): Rope = var length = sonsLen(n) result = rope("{") - for i in countup(0, length - 2): + for i in countup(ord(n.kind == nkObjConstr), length - 2): addf(result, "$1,$n", [genNamedConstExpr(p, n.sons[i])]) if length > 0: add(result, genNamedConstExpr(p, n.sons[length - 1])) addf(result, "}$n", []) diff --git a/tests/vm/tconstobj.nim b/tests/vm/tconstobj.nim new file mode 100644 index 000000000..414708945 --- /dev/null +++ b/tests/vm/tconstobj.nim @@ -0,0 +1,14 @@ +discard """ + output: '''(name: hello)''' +""" + +# bug #2774 + +type Foo = object + name: string + +const fooArray = [ + Foo(name: "hello") +] + +echo fooArray[0] From a40098759066d9f7ee411aec509f04bee72bc695 Mon Sep 17 00:00:00 2001 From: patrick dw Date: Sat, 6 Jun 2015 08:57:13 -0500 Subject: [PATCH 0382/1263] Dropped from TZipFileStream --- lib/impure/zipfiles.nim | 3 ++- tools/niminst/niminst.nim | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/lib/impure/zipfiles.nim b/lib/impure/zipfiles.nim index d66d7d7f3..56483c586 100644 --- a/lib/impure/zipfiles.nim +++ b/lib/impure/zipfiles.nim @@ -109,12 +109,13 @@ proc addFile*(z: var ZipArchive, dest: string, src: Stream) = # -------------- zip file stream --------------------------------------------- type - TZipFileStream = object of StreamObj + ZipFileStream = object of StreamObj f: PZipFile atEnd: bool PZipFileStream* = ref ZipFileStream ## a reader stream of a file within a zip archive +{.deprecated: [TZipFileStream: ZipFileStream].} proc fsClose(s: Stream) = zip_fclose(PZipFileStream(s).f) proc fsAtEnd(s: Stream): bool = PZipFileStream(s).atEnd diff --git a/tools/niminst/niminst.nim b/tools/niminst/niminst.nim index 99befa92d..253543a50 100644 --- a/tools/niminst/niminst.nim +++ b/tools/niminst/niminst.nim @@ -538,7 +538,7 @@ when haveZipLib: var n = "$#.zip" % proj if c.outdir.len == 0: n = "build" / n else: n = c.outdir / n - var z: TZipArchive + var z: ZipArchive if open(z, n, fmWrite): addFile(z, proj / buildBatFile32, "build" / buildBatFile32) addFile(z, proj / buildBatFile64, "build" / buildBatFile64) From a51156282209e3121445589a8a4cf421f694b00e Mon Sep 17 00:00:00 2001 From: patrick dw Date: Sat, 6 Jun 2015 09:09:48 -0500 Subject: [PATCH 0383/1263] Renaming fixes in sdl.nim --- lib/wrappers/sdl/sdl.nim | 50 ++++++++++++++++++++++------------------ 1 file changed, 27 insertions(+), 23 deletions(-) diff --git a/lib/wrappers/sdl/sdl.nim b/lib/wrappers/sdl/sdl.nim index 707c65a53..3fc96a07e 100644 --- a/lib/wrappers/sdl/sdl.nim +++ b/lib/wrappers/sdl/sdl.nim @@ -775,7 +775,7 @@ type Arg*{.final.} = object buf*: array[0..ERR_MAX_STRLEN - 1, int8] - Perror* = ptr Terror + Perror* = ptr Error Error*{.final.} = object # This is a numeric value corresponding to the current error # SDL_rwops.h types # This is the read/write operation structure -- very basic @@ -814,7 +814,7 @@ type theType*: cint mem*: Mem - RWops* = RWops # SDL_timer.h types + # SDL_timer.h types # Function prototype for the timer callback function TimerCallback* = proc (interval: int32): int32{.cdecl.} NewTimerCallback* = proc (interval: int32, param: pointer): int32{.cdecl.} @@ -950,8 +950,8 @@ type EventAction* = enum # Application visibility event structure ADDEVENT, PEEKEVENT, GETEVENT - PActiveEvent* = ptr ActiveEvent - ActiveEvent*{.final.} = object # SDL_ACTIVEEVENT + PActiveEvent* = ptr TActiveEvent + TActiveEvent*{.final.} = object # SDL_ACTIVEEVENT # Keyboard event structure kind*: EventKind gain*: byte # Whether given states were gained or lost (1/0) @@ -1032,8 +1032,8 @@ type w*: cint # New width h*: cint # New height - PUserEvent* = ptr UserEvent - UserEvent*{.final.} = object # SDL_USEREVENT through SDL_NUMEVENTS-1 + PUserEvent* = ptr TUserEvent + TUserEvent*{.final.} = object # SDL_USEREVENT through SDL_NUMEVENTS-1 kind*: EventKind code*: cint # User defined event code data1*: pointer # User defined data pointer @@ -1044,7 +1044,7 @@ type TWrite: Write, TBool: Bool, TUInt8Array: UInt8Array, TGrabMode: GrabMode, Terrorcode: Errorcode, TStdio: Stdio, TMem: Mem, TSeek: Seek, TRead: Read, TClose: Close, - TTimerCallback: TimerCallback, TNewTimerCallback: NewTimerCallabck, + TTimerCallback: TimerCallback, TNewTimerCallback: NewTimerCallback, TTimerID: TimerID, TAudioSpecCallback: AudioSpecCallback, TAudioSpec: AudioSpec, TAudioCVTFilter: AudioCVTFilter, TAudioCVTFilterArray: AudioCVTFilterArray, TAudioCVT: AudioCVT, @@ -1053,16 +1053,19 @@ type TJoystick: Joystick, TJoyAxisEvent: JoyAxisEvent, TRWops: RWops, TJoyBallEvent: JoyBallEvent, TJoyHatEvent: JoyHatEvent, TJoyButtonEvent: JoyButtonEvent, TBallDelta: BallDelta, - Tversion: Version, TMod: Mod, TActiveEvent: ActiveEvent, + Tversion: Version, TMod: Mod, + # TActiveEvent: ActiveEvent, # Naming conflict when we drop the `T` TMouseMotionEvent: MouseMotionEvent, TMouseButtonEvent: MouseButtonEvent, - TResizeEvent: ResizeEvent, TUserEvent: UserEvent].} + TResizeEvent: ResizeEvent, + # TUserEvent: UserEvent # Naming conflict when we drop the `T` + ].} -when defined(Unix): +when defined(Unix): type #These are the various supported subsystems under UNIX SysWm* = enum SYSWM_X11 {.deprecated: [TSysWm: SysWm].} -when defined(WINDOWS): +when defined(WINDOWS): type PSysWMmsg* = ptr SysWMmsg SysWMmsg*{.final.} = object @@ -1136,8 +1139,8 @@ else: {.deprecated: [TSysWMinfo: SysWMinfo].} type - PSysWMEvent* = ptr SysWMEvent - SysWMEvent*{.final.} = object + PSysWMEvent* = ptr TSysWMEvent + TSysWMEvent*{.final.} = object kind*: EventKind msg*: PSysWMmsg @@ -1172,12 +1175,12 @@ type PColorArray* = ptr ColorArray ColorArray* = array[0..65000, Color] - PPalette* = ptr TPalette + PPalette* = ptr Palette Palette*{.final.} = object # Everything in the pixel format structure is read-only ncolors*: int colors*: PColorArray - PPixelFormat* = ptr TPixelFormat + PPixelFormat* = ptr PixelFormat PixelFormat*{.final.} = object # The structure passed to the low level blit functions palette*: PPalette bitsPerPixel*: byte @@ -1254,10 +1257,10 @@ type hwOverlay*: int32 # This will be set to 1 if the overlay is hardware accelerated. GLAttr* = enum - GL_RED_SIZE, GL_GREEN_SIZE, GL_BLUE_SIZE, GL_ALPHA_SIZE, GL_BUFFER_SIZE, - GL_DOUBLEBUFFER, GL_DEPTH_SIZE, GL_STENCIL_SIZE, GL_ACCUM_RED_SIZE, - GL_ACCUM_GREEN_SIZE, GL_ACCUM_BLUE_SIZE, GL_ACCUM_ALPHA_SIZE, GL_STEREO, - GL_MULTISAMPLEBUFFERS, GL_MULTISAMPLESAMPLES, GL_ACCELERATED_VISUAL, + GL_RED_SIZE, GL_GREEN_SIZE, GL_BLUE_SIZE, GL_ALPHA_SIZE, GL_BUFFER_SIZE, + GL_DOUBLEBUFFER, GL_DEPTH_SIZE, GL_STENCIL_SIZE, GL_ACCUM_RED_SIZE, + GL_ACCUM_GREEN_SIZE, GL_ACCUM_BLUE_SIZE, GL_ACCUM_ALPHA_SIZE, GL_STEREO, + GL_MULTISAMPLEBUFFERS, GL_MULTISAMPLESAMPLES, GL_ACCELERATED_VISUAL, GL_SWAP_CONTROL PCursor* = ptr Cursor Cursor*{.final.} = object # SDL_mutex.h types @@ -1269,7 +1272,8 @@ type wmCursor*: pointer # Window-manager cursor {.deprecated: [TRect: Rect, TSurface: Surface, TEvent: Event, TColor: Color, TEventFilter: EventFilter, TColorArray: ColorArray, - TSysWMEvent: SysWMEvent, TExposeEvent: ExposeEvent, + # TSysWMEvent: SysWMEvent, # Naming conflict when we drop the `T` + TExposeEvent: ExposeEvent, TQuitEvent: QuitEvent, TPalette: Palette, TPixelFormat: PixelFormat, TBlitInfo: BlitInfo, TBlit: Blit, TVideoInfo: VideoInfo, TOverlay: Overlay, TGLAttr: GLAttr, TCursor: Cursor].} @@ -1285,11 +1289,11 @@ type Cond*{.final.} = object # SDL_thread.h types {.deprecated: [TCond: Cond, TSem: Sem, TMutex: Mutex, Tsemaphore: Semaphore].} -when defined(WINDOWS): +when defined(WINDOWS): type SYS_ThreadHandle* = Handle {.deprecated: [TSYS_ThreadHandle: SYS_ThreadHandle].} -when defined(Unix): +when defined(Unix): type SYS_ThreadHandle* = pointer {.deprecated: [TSYS_ThreadHandle: SYS_ThreadHandle].} @@ -1300,7 +1304,7 @@ type # This is the system-independent thread info struc threadid*: int32 handle*: SYS_ThreadHandle status*: int - errbuf*: Terror + errbuf*: Error data*: pointer PKeyStateArr* = ptr KeyStateArr From 2e25574ff1adfe2dd07875854cb292470056cd2f Mon Sep 17 00:00:00 2001 From: patrick dw Date: Sat, 6 Jun 2015 09:35:15 -0500 Subject: [PATCH 0384/1263] Updated usage of deprecated types --- lib/wrappers/readline/readline.nim | 44 +++++++++++++++--------------- lib/wrappers/sdl/sdl.nim | 6 ++-- 2 files changed, 25 insertions(+), 25 deletions(-) diff --git a/lib/wrappers/readline/readline.nim b/lib/wrappers/readline/readline.nim index 4173a0e0f..652808576 100644 --- a/lib/wrappers/readline/readline.nim +++ b/lib/wrappers/readline/readline.nim @@ -29,7 +29,7 @@ elif defined(macosx): else: const readlineDll* = "libreadline.so.6(|.0)" -# mangle "'TCommandFunc'" TCommandFunc +# mangle "'CommandFunc'" CommandFunc # mangle TvcpFunc TvcpFunc import rltypedefs @@ -80,7 +80,7 @@ const type KEYMAP_ENTRY*{.pure, final.} = object typ*: char - function*: TCommandFunc + function*: CommandFunc {.deprecated: [TKEYMAP_ENTRY: KEYMAP_ENTRY].} @@ -243,7 +243,7 @@ when not defined(macosx): type FUNMAP*{.pure, final.} = object name*: cstring - function*: TCommandFunc + function*: CommandFunc {.deprecated: [TFUNMAP: FUNMAP].} @@ -610,31 +610,31 @@ proc discard_argument*(): cint{.cdecl, importc: "rl_discard_argument", dynlib: readlineDll.} # Utility functions to bind keys to readline commands. -proc add_defun*(a2: cstring, a3: TCommandFunc, a4: cint): cint{.cdecl, +proc add_defun*(a2: cstring, a3: CommandFunc, a4: cint): cint{.cdecl, importc: "rl_add_defun", dynlib: readlineDll.} -proc bind_key*(a2: cint, a3: TCommandFunc): cint{.cdecl, +proc bind_key*(a2: cint, a3: CommandFunc): cint{.cdecl, importc: "rl_bind_key", dynlib: readlineDll.} -proc bind_key_in_map*(a2: cint, a3: TCommandFunc, a4: PKeymap): cint{.cdecl, +proc bind_key_in_map*(a2: cint, a3: CommandFunc, a4: PKeymap): cint{.cdecl, importc: "rl_bind_key_in_map", dynlib: readlineDll.} proc unbind_key*(a2: cint): cint{.cdecl, importc: "rl_unbind_key", dynlib: readlineDll.} proc unbind_key_in_map*(a2: cint, a3: PKeymap): cint{.cdecl, importc: "rl_unbind_key_in_map", dynlib: readlineDll.} -proc bind_key_if_unbound*(a2: cint, a3: TCommandFunc): cint{.cdecl, +proc bind_key_if_unbound*(a2: cint, a3: CommandFunc): cint{.cdecl, importc: "rl_bind_key_if_unbound", dynlib: readlineDll.} -proc bind_key_if_unbound_in_map*(a2: cint, a3: TCommandFunc, a4: PKeymap): cint{. +proc bind_key_if_unbound_in_map*(a2: cint, a3: CommandFunc, a4: PKeymap): cint{. cdecl, importc: "rl_bind_key_if_unbound_in_map", dynlib: readlineDll.} -proc unbind_function_in_map*(a2: TCommandFunc, a3: PKeymap): cint{.cdecl, +proc unbind_function_in_map*(a2: CommandFunc, a3: PKeymap): cint{.cdecl, importc: "rl_unbind_function_in_map", dynlib: readlineDll.} proc unbind_command_in_map*(a2: cstring, a3: PKeymap): cint{.cdecl, importc: "rl_unbind_command_in_map", dynlib: readlineDll.} -proc bind_keyseq*(a2: cstring, a3: TCommandFunc): cint{.cdecl, +proc bind_keyseq*(a2: cstring, a3: CommandFunc): cint{.cdecl, importc: "rl_bind_keyseq", dynlib: readlineDll.} -proc bind_keyseq_in_map*(a2: cstring, a3: TCommandFunc, a4: PKeymap): cint{. +proc bind_keyseq_in_map*(a2: cstring, a3: CommandFunc, a4: PKeymap): cint{. cdecl, importc: "rl_bind_keyseq_in_map", dynlib: readlineDll.} -proc bind_keyseq_if_unbound*(a2: cstring, a3: TCommandFunc): cint{.cdecl, +proc bind_keyseq_if_unbound*(a2: cstring, a3: CommandFunc): cint{.cdecl, importc: "rl_bind_keyseq_if_unbound", dynlib: readlineDll.} -proc bind_keyseq_if_unbound_in_map*(a2: cstring, a3: TCommandFunc, +proc bind_keyseq_if_unbound_in_map*(a2: cstring, a3: CommandFunc, a4: PKeymap): cint{.cdecl, importc: "rl_bind_keyseq_if_unbound_in_map", dynlib: readlineDll.} proc generic_bind*(a2: cint, a3: cstring, a4: cstring, a5: PKeymap): cint{. @@ -645,7 +645,7 @@ proc variable_bind*(a2: cstring, a3: cstring): cint{.cdecl, importc: "rl_variable_bind", dynlib: readlineDll.} # Backwards compatibility, use rl_bind_keyseq_in_map instead. -proc set_key*(a2: cstring, a3: TCommandFunc, a4: PKeymap): cint{.cdecl, +proc set_key*(a2: cstring, a3: CommandFunc, a4: PKeymap): cint{.cdecl, importc: "rl_set_key", dynlib: readlineDll.} # Backwards compatibility, use rl_generic_bind instead. @@ -657,15 +657,15 @@ proc translate_keyseq*(a2: cstring, a3: cstring, a4: ptr cint): cint{.cdecl, importc: "rl_translate_keyseq", dynlib: readlineDll.} proc untranslate_keyseq*(a2: cint): cstring{.cdecl, importc: "rl_untranslate_keyseq", dynlib: readlineDll.} -proc named_function*(a2: cstring): TCommandFunc{.cdecl, +proc named_function*(a2: cstring): CommandFunc{.cdecl, importc: "rl_named_function", dynlib: readlineDll.} -proc function_of_keyseq*(a2: cstring, a3: PKeymap, a4: ptr cint): TCommandFunc{. +proc function_of_keyseq*(a2: cstring, a3: PKeymap, a4: ptr cint): CommandFunc{. cdecl, importc: "rl_function_of_keyseq", dynlib: readlineDll.} proc list_funmap_names*(){.cdecl, importc: "rl_list_funmap_names", dynlib: readlineDll.} -proc invoking_keyseqs_in_map*(a2: TCommandFunc, a3: PKeymap): cstringArray{. +proc invoking_keyseqs_in_map*(a2: CommandFunc, a3: PKeymap): cstringArray{. cdecl, importc: "rl_invoking_keyseqs_in_map", dynlib: readlineDll.} -proc invoking_keyseqs*(a2: TCommandFunc): cstringArray{.cdecl, +proc invoking_keyseqs*(a2: CommandFunc): cstringArray{.cdecl, importc: "rl_invoking_keyseqs", dynlib: readlineDll.} proc function_dumper*(a2: cint){.cdecl, importc: "rl_function_dumper", dynlib: readlineDll.} @@ -688,7 +688,7 @@ proc get_keymap_name_from_edit_mode*(): cstring{.cdecl, importc: "rl_get_keymap_name_from_edit_mode", dynlib: readlineDll.} # Functions for manipulating the funmap, which maps command names to functions. -proc add_funmap_entry*(a2: cstring, a3: TCommandFunc): cint{.cdecl, +proc add_funmap_entry*(a2: cstring, a3: CommandFunc): cint{.cdecl, importc: "rl_add_funmap_entry", dynlib: readlineDll.} proc funmap_names*(): cstringArray{.cdecl, importc: "rl_funmap_names", dynlib: readlineDll.} @@ -828,7 +828,7 @@ proc username_completion_function*(a2: cstring, a3: cint): cstring{.cdecl, importc: "rl_username_completion_function", dynlib: readlineDll.} proc filename_completion_function*(a2: cstring, a3: cint): cstring{.cdecl, importc: "rl_filename_completion_function", dynlib: readlineDll.} -proc completion_mode*(a2: TCommandFunc): cint{.cdecl, +proc completion_mode*(a2: CommandFunc): cint{.cdecl, importc: "rl_completion_mode", dynlib: readlineDll.} # **************************************************************** # @@ -883,7 +883,7 @@ when false: # The current value of the numeric argument specified by the user. var numeric_arg*{.importc: "rl_numeric_arg", dynlib: readlineDll.}: cint # The address of the last command function Readline executed. - var last_func*{.importc: "rl_last_func", dynlib: readlineDll.}: TCommandFunc + var last_func*{.importc: "rl_last_func", dynlib: readlineDll.}: CommandFunc # The name of the terminal to use. var terminal_name*{.importc: "rl_terminal_name", dynlib: readlineDll.}: cstring # The input and output streams. @@ -1186,7 +1186,7 @@ type rlstate*: cint done*: cint kmap*: PKeymap # input state - lastfunc*: TCommandFunc + lastfunc*: CommandFunc insmode*: cint edmode*: cint kseqlen*: cint diff --git a/lib/wrappers/sdl/sdl.nim b/lib/wrappers/sdl/sdl.nim index 3fc96a07e..376de8e08 100644 --- a/lib/wrappers/sdl/sdl.nim +++ b/lib/wrappers/sdl/sdl.nim @@ -2215,7 +2215,7 @@ proc glLoadLibrary*(filename: cstring): int{.cdecl, proc glGetProcAddress*(procname: cstring): pointer{.cdecl, importc: "SDL_GL_GetProcAddress", dynlib: LibName.} # Set an attribute of the OpenGL subsystem before intialization. -proc glSetAttribute*(attr: TGLAttr, value: int): int{.cdecl, +proc glSetAttribute*(attr: GLAttr, value: int): int{.cdecl, importc: "SDL_GL_SetAttribute", dynlib: LibName.} # Get an attribute of the OpenGL subsystem from the windowing # interface, such as glX. This is of course different from getting @@ -2224,7 +2224,7 @@ proc glSetAttribute*(attr: TGLAttr, value: int): int{.cdecl, # # Developers should track the values they pass into SDL_GL_SetAttribute # themselves if they want to retrieve these values. -proc glGetAttribute*(attr: TGLAttr, value: var int): int{.cdecl, +proc glGetAttribute*(attr: GLAttr, value: var int): int{.cdecl, importc: "SDL_GL_GetAttribute", dynlib: LibName.} # Swap the OpenGL buffers, if double-buffering is supported. proc glSwapBuffers*(){.cdecl, importc: "SDL_GL_SwapBuffers", dynlib: LibName.} @@ -2271,7 +2271,7 @@ proc wmToggleFullScreen*(surface: PSurface): int{.cdecl, # Grabbing means that the mouse is confined to the application window, # and nearly all keyboard input is passed directly to the application, # and not interpreted by a window manager, if any. -proc wmGrabInput*(mode: TGrabMode): GrabMode{.cdecl, +proc wmGrabInput*(mode: GrabMode): GrabMode{.cdecl, importc: "SDL_WM_GrabInput", dynlib: LibName.} #------------------------------------------------------------------------------ # mouse-routines From ca684da044ed42b4f357fba030fba8920f8497f0 Mon Sep 17 00:00:00 2001 From: patrick dw Date: Sat, 6 Jun 2015 10:18:16 -0500 Subject: [PATCH 0385/1263] Updated deprecated names --- lib/pure/fsmonitor.nim | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/pure/fsmonitor.nim b/lib/pure/fsmonitor.nim index 83779eb9c..229df80b5 100644 --- a/lib/pure/fsmonitor.nim +++ b/lib/pure/fsmonitor.nim @@ -108,7 +108,7 @@ proc del*(monitor: FSMonitor, wd: cint) = proc getEvent(m: FSMonitor, fd: cint): seq[MonitorEvent] = result = @[] - let size = (sizeof(TINotifyEvent)+2000)*MaxEvents + let size = (sizeof(INotifyEvent)+2000)*MaxEvents var buffer = newString(size) let le = read(fd, addr(buffer[0]), size) @@ -117,7 +117,7 @@ proc getEvent(m: FSMonitor, fd: cint): seq[MonitorEvent] = var i = 0 while i < le: - var event = cast[ptr TINotifyEvent](addr(buffer[i])) + var event = cast[ptr INotifyEvent](addr(buffer[i])) var mev: MonitorEvent mev.wd = event.wd if event.len.int != 0: @@ -129,7 +129,7 @@ proc getEvent(m: FSMonitor, fd: cint): seq[MonitorEvent] = if (event.mask.int and IN_MOVED_FROM) != 0: # Moved from event, add to m's collection movedFrom.add(event.cookie.cint, (mev.wd, mev.name)) - inc(i, sizeof(TINotifyEvent) + event.len.int) + inc(i, sizeof(INotifyEvent) + event.len.int) continue elif (event.mask.int and IN_MOVED_TO) != 0: mev.kind = MonitorMoved @@ -159,7 +159,7 @@ proc getEvent(m: FSMonitor, fd: cint): seq[MonitorEvent] = mev.fullname = "" result.add(mev) - inc(i, sizeof(TINotifyEvent) + event.len.int) + inc(i, sizeof(INotifyEvent) + event.len.int) # If movedFrom events have not been matched with a moveTo. File has # been moved to an unwatched location, emit a MonitorDelete. From 13163ff13f65fdde3d7af13496e99fb88917c99c Mon Sep 17 00:00:00 2001 From: patrick dw Date: Sat, 6 Jun 2015 10:45:01 -0500 Subject: [PATCH 0386/1263] Reverted TZipFileStream (is going to be reference type) --- lib/impure/zipfiles.nim | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/lib/impure/zipfiles.nim b/lib/impure/zipfiles.nim index 56483c586..d8903f5c1 100644 --- a/lib/impure/zipfiles.nim +++ b/lib/impure/zipfiles.nim @@ -109,13 +109,12 @@ proc addFile*(z: var ZipArchive, dest: string, src: Stream) = # -------------- zip file stream --------------------------------------------- type - ZipFileStream = object of StreamObj + TZipFileStream = object of StreamObj f: PZipFile atEnd: bool PZipFileStream* = - ref ZipFileStream ## a reader stream of a file within a zip archive -{.deprecated: [TZipFileStream: ZipFileStream].} + ref TZipFileStream ## a reader stream of a file within a zip archive proc fsClose(s: Stream) = zip_fclose(PZipFileStream(s).f) proc fsAtEnd(s: Stream): bool = PZipFileStream(s).atEnd From ff83efa76772eb108ef445e0bb815b49f39c7faa Mon Sep 17 00:00:00 2001 From: patrick dw Date: Sat, 6 Jun 2015 12:01:26 -0500 Subject: [PATCH 0387/1263] Fixed malformed pragma --- lib/wrappers/libffi/libffi.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/wrappers/libffi/libffi.nim b/lib/wrappers/libffi/libffi.nim index d7e11a20c..34b91f8c7 100644 --- a/lib/wrappers/libffi/libffi.nim +++ b/lib/wrappers/libffi/libffi.nim @@ -60,7 +60,7 @@ else: type Arg* = int SArg* = int -{deprecated: [TArg: Arg, TSArg: SArg].} +{.deprecated: [TArg: Arg, TSArg: SArg].} when defined(windows) and defined(x86): type From c55f5dfca263788169c21fcff2dd78103a20e891 Mon Sep 17 00:00:00 2001 From: yglukhov Date: Wed, 27 May 2015 16:48:10 +0300 Subject: [PATCH 0388/1263] Perform lambda lifting for compile-time stuff when targeting JS. Enable unittest test. --- compiler/lambdalifting.nim | 6 +++++- lib/pure/unittest.nim | 9 ++++----- tests/js/tunittests.nim | 5 +---- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/compiler/lambdalifting.nim b/compiler/lambdalifting.nim index c68bc352c..69b45c980 100644 --- a/compiler/lambdalifting.nim +++ b/compiler/lambdalifting.nim @@ -946,7 +946,11 @@ proc transformOuterProc(o: POuterContext, n: PNode; it: TIter): PNode = proc liftLambdas*(fn: PSym, body: PNode): PNode = # XXX gCmd == cmdCompileToJS does not suffice! The compiletime stuff needs # the transformation even when compiling to JS ... - if body.kind == nkEmpty or gCmd == cmdCompileToJS or + + # However we can do lifting for the stuff which is *only* compiletime. + let isCompileTime = sfCompileTime in fn.flags or fn.kind == skMacro + + if body.kind == nkEmpty or (gCmd == cmdCompileToJS and not isCompileTime) or fn.skipGenericOwner.kind != skModule: # ignore forward declaration: result = body diff --git a/lib/pure/unittest.nim b/lib/pure/unittest.nim index 092b1fba2..dbbd3cabc 100644 --- a/lib/pure/unittest.nim +++ b/lib/pure/unittest.nim @@ -99,8 +99,9 @@ template test*(name: expr, body: stmt): stmt {.immediate, dirty.} = body except: - checkpoint("Unhandled exception: " & getCurrentExceptionMsg()) - echo getCurrentException().getStackTrace() + when not defined(js): + checkpoint("Unhandled exception: " & getCurrentExceptionMsg()) + echo getCurrentException().getStackTrace() fail() finally: @@ -114,9 +115,7 @@ proc checkpoint*(msg: string) = template fail* = bind checkpoints for msg in items(checkpoints): - # this used to be 'echo' which now breaks due to a bug. XXX will revisit - # this issue later. - stdout.writeln msg + echo msg when not defined(ECMAScript): if abortOnError: quit(1) diff --git a/tests/js/tunittests.nim b/tests/js/tunittests.nim index 8a264a5e0..4b09c99a9 100644 --- a/tests/js/tunittests.nim +++ b/tests/js/tunittests.nim @@ -1,10 +1,7 @@ discard """ - disabled: "true" + output: '''[OK] >:)''' """ -# Unittest uses lambdalifting at compile-time which we disable for the JS -# codegen! So this cannot and will not work for quite some time. - import unittest suite "Bacon": From 4674b3eb8003b44656ae15ff0a5b7fc742714597 Mon Sep 17 00:00:00 2001 From: Adam Strzelecki Date: Tue, 2 Jun 2015 21:29:28 +0200 Subject: [PATCH 0389/1263] Introduce {.noRewrite.} expr pragma disabling TR Term rewriting macros/templates are currently greedy and they will rewrite as long as there is a match. So there was no way to ensure some rewrite happens only once, eg. when rewriting term to same term plus extra content. With new macro we can actually prevent further rewriting on marked expr or stmts, eg. with given example echo(...) will be rewritten just once: template pwnEcho{echo(x)}(x: expr) = {.noRewrite.}: echo("pwned!") echo "ab" --- compiler/ast.nim | 1 + compiler/patterns.nim | 4 +++- compiler/pragmas.nim | 4 +++- compiler/semstmts.nim | 2 ++ compiler/wordrecg.nim | 4 ++-- 5 files changed, 11 insertions(+), 4 deletions(-) diff --git a/compiler/ast.nim b/compiler/ast.nim index 044f21341..c349f81ed 100644 --- a/compiler/ast.nim +++ b/compiler/ast.nim @@ -423,6 +423,7 @@ type # but unfortunately it has measurable impact for compilation # efficiency nfTransf, # node has been transformed + nfNoRewrite # node should not be transformed anymore nfSem # node has been checked for semantics nfLL # node has gone through lambda lifting nfDotField # the call can use a dot operator diff --git a/compiler/patterns.nim b/compiler/patterns.nim index 368b0b37b..3f8b05940 100644 --- a/compiler/patterns.nim +++ b/compiler/patterns.nim @@ -130,7 +130,9 @@ proc matchNested(c: PPatternContext, p, n: PNode, rpn: bool): bool = proc matches(c: PPatternContext, p, n: PNode): bool = # hidden conversions (?) - if isPatternParam(c, p): + if nfNoRewrite in n.flags: + result = false + elif isPatternParam(c, p): result = bindOrCheck(c, p.sym, n) elif n.kind == nkSym and p.kind == nkIdent: result = p.ident.id == n.sym.name.id diff --git a/compiler/pragmas.nim b/compiler/pragmas.nim index c048d78e9..6f37fe756 100644 --- a/compiler/pragmas.nim +++ b/compiler/pragmas.nim @@ -37,7 +37,7 @@ const wImportc, wExportc, wNodecl, wMagic, wDeprecated, wBorrow, wExtern, wImportCpp, wImportObjC, wError, wDiscardable, wGensym, wInject, wRaises, wTags, wLocks, wGcSafe} - exprPragmas* = {wLine, wLocks} + exprPragmas* = {wLine, wLocks, wNoRewrite} stmtPragmas* = {wChecks, wObjChecks, wFieldChecks, wRangechecks, wBoundchecks, wOverflowchecks, wNilchecks, wAssertions, wWarnings, wHints, wLinedir, wStacktrace, wLinetrace, wOptimization, wHint, wWarning, wError, @@ -859,6 +859,8 @@ proc singlePragma(c: PContext, sym: PSym, n: PNode, i: int, c.module.flags.incl sfExperimental else: localError(it.info, "'experimental' pragma only valid as toplevel statement") + of wNoRewrite: + noVal(it) else: invalidPragma(it) else: invalidPragma(it) else: processNote(c, it) diff --git a/compiler/semstmts.nim b/compiler/semstmts.nim index c355a5bf1..43cdca866 100644 --- a/compiler/semstmts.nim +++ b/compiler/semstmts.nim @@ -1268,6 +1268,8 @@ proc semPragmaBlock(c: PContext, n: PNode): PNode = of wLocks: result = n result.typ = n.sons[1].typ + of wNoRewrite: + incl(result.flags, nfNoRewrite) else: discard proc semStaticStmt(c: PContext, n: PNode): PNode = diff --git a/compiler/wordrecg.nim b/compiler/wordrecg.nim index 63fd995c4..deb12536f 100644 --- a/compiler/wordrecg.nim +++ b/compiler/wordrecg.nim @@ -55,7 +55,7 @@ type wFloatchecks, wNanChecks, wInfChecks, wAssertions, wPatterns, wWarnings, wHints, wOptimization, wRaises, wWrites, wReads, wSize, wEffects, wTags, - wDeadCodeElim, wSafecode, wNoForward, + wDeadCodeElim, wSafecode, wNoForward, wNoRewrite, wPragma, wCompileTime, wNoInit, wPassc, wPassl, wBorrow, wDiscardable, @@ -139,7 +139,7 @@ const "assertions", "patterns", "warnings", "hints", "optimization", "raises", "writes", "reads", "size", "effects", "tags", - "deadcodeelim", "safecode", "noforward", + "deadcodeelim", "safecode", "noforward", "norewrite", "pragma", "compiletime", "noinit", "passc", "passl", "borrow", "discardable", "fieldchecks", From 07c40add8fbc3b4c248c1403f903617a6bdb027e Mon Sep 17 00:00:00 2001 From: Adam Strzelecki Date: Tue, 2 Jun 2015 21:51:41 +0200 Subject: [PATCH 0390/1263] Parser: Properly represent parsePar in grammar --- compiler/parser.nim | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/compiler/parser.nim b/compiler/parser.nim index 0d2ba7cfc..18ef06e64 100644 --- a/compiler/parser.nim +++ b/compiler/parser.nim @@ -499,10 +499,12 @@ proc parsePar(p: var TParser): PNode = #| parKeyw = 'discard' | 'include' | 'if' | 'while' | 'case' | 'try' #| | 'finally' | 'except' | 'for' | 'block' | 'const' | 'let' #| | 'when' | 'var' | 'mixin' - #| par = '(' optInd (&parKeyw complexOrSimpleStmt ^+ ';' - #| | simpleExpr ('=' expr (';' complexOrSimpleStmt ^+ ';' )? )? - #| | (':' expr)? (',' (exprColonEqExpr comma?)*)? )? - #| optPar ')' + #| par = '(' optInd + #| ( &parKeyw complexOrSimpleStmt ^+ ';' + #| | ';' complexOrSimpleStmt ^+ ';' + #| | simpleExpr ( ('=' expr (';' complexOrSimpleStmt ^+ ';' )? ) + #| | (':' expr (',' exprColonEqExpr ^+ ',' )? ) ) ) + #| optPar ')' # # unfortunately it's ambiguous: (expr: expr) vs (exprStmt); however a # leading ';' could be used to enforce a 'stmt' context ... From 83369f4bce15d6d8f4d0bd9a7cb17b2def6daa54 Mon Sep 17 00:00:00 2001 From: Adam Strzelecki Date: Tue, 2 Jun 2015 21:56:44 +0200 Subject: [PATCH 0391/1263] Parser: Inline expr pragmas with parenthesis Previously pragmas could be attached only to whole statements, this change allows attaching pragmas to inline statements, eg.: template rewriteAdd{a + b}(a: expr, b: expr): expr = ({.noRewrite.}: a + b) + 1 Code above will cause a + b to be rewritten once, because rewriteAdd attaches {.noRewrite.} to resulting a + b expr. --- compiler/parser.nim | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/compiler/parser.nim b/compiler/parser.nim index 18ef06e64..05b4df13d 100644 --- a/compiler/parser.nim +++ b/compiler/parser.nim @@ -64,6 +64,7 @@ proc setBaseFlags*(n: PNode, base: TNumericalBase) proc parseSymbol*(p: var TParser, allowNil = false): PNode proc parseTry(p: var TParser; isExpr: bool): PNode proc parseCase(p: var TParser): PNode +proc parseStmtPragma(p: var TParser): PNode # implementation proc getTok(p: var TParser) = @@ -502,6 +503,7 @@ proc parsePar(p: var TParser): PNode = #| par = '(' optInd #| ( &parKeyw complexOrSimpleStmt ^+ ';' #| | ';' complexOrSimpleStmt ^+ ';' + #| | pragmaStmt #| | simpleExpr ( ('=' expr (';' complexOrSimpleStmt ^+ ';' )? ) #| | (':' expr (',' exprColonEqExpr ^+ ',' )? ) ) ) #| optPar ')' @@ -523,6 +525,8 @@ proc parsePar(p: var TParser): PNode = getTok(p) optInd(p, result) semiStmtList(p, result) + elif p.tok.tokType == tkCurlyDotLe: + result.add(parseStmtPragma(p)) elif p.tok.tokType != tkParRi: var a = simpleExpr(p) if p.tok.tokType == tkEquals: From e132032b0f3af7fd03dd35b68a795c4dbc25ddfc Mon Sep 17 00:00:00 2001 From: apense Date: Thu, 4 Jun 2015 13:31:40 -0400 Subject: [PATCH 0392/1263] Fixed code indentation in procs.txt Now matches tut2.txt --- doc/manual/procs.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/manual/procs.txt b/doc/manual/procs.txt index 38e343686..23b5e4d1e 100644 --- a/doc/manual/procs.txt +++ b/doc/manual/procs.txt @@ -404,7 +404,7 @@ dispatch. result.a = a result.b = b -echo eval(newPlus(newPlus(newLit(1), newLit(2)), newLit(4))) + echo eval(newPlus(newPlus(newLit(1), newLit(2)), newLit(4))) In the example the constructors ``newLit`` and ``newPlus`` are procs because they should use static binding, but ``eval`` is a method because it From c126b8ad0f1c3b9749819737c9fd02fb82fd4497 Mon Sep 17 00:00:00 2001 From: apense Date: Thu, 4 Jun 2015 16:18:18 -0400 Subject: [PATCH 0393/1263] Fixed links in Error hierarchy Manual contained invalid links --- doc/exception_hierarchy_fragment.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc/exception_hierarchy_fragment.txt b/doc/exception_hierarchy_fragment.txt index f4a419fc4..a02d9ccef 100644 --- a/doc/exception_hierarchy_fragment.txt +++ b/doc/exception_hierarchy_fragment.txt @@ -11,8 +11,8 @@ * `FloatInvalidOpError `_ * `FloatOverflowError `_ * `FloatUnderflowError `_ - * `FieldError `_ - * `IndexError `_ + * `FieldError `_ + * `IndexError `_ * `ObjectAssignmentError `_ * `ObjectConversionError `_ * `ValueError `_ From 25c6304abbd855cd5b7f45227fcf44d1cb24490e Mon Sep 17 00:00:00 2001 From: Dominik Picheta Date: Thu, 4 Jun 2015 23:07:57 +0100 Subject: [PATCH 0394/1263] Hopefully fixes nimsuggest building against the compiler package. --- compiler/nimfix/nimfix.nim | 14 ++++++++------ compiler/nimfix/pretty.nim | 20 +++++++++++--------- compiler/nimfix/prettybase.nim | 7 ++++--- compiler/plugins/locals/locals.nim | 3 ++- 4 files changed, 25 insertions(+), 19 deletions(-) diff --git a/compiler/nimfix/nimfix.nim b/compiler/nimfix/nimfix.nim index 8caa23ee3..3641aec36 100644 --- a/compiler/nimfix/nimfix.nim +++ b/compiler/nimfix/nimfix.nim @@ -10,8 +10,10 @@ ## Nimfix is a tool that helps to convert old-style Nimrod code to Nim code. import strutils, os, parseopt -import options, commands, modules, sem, passes, passaux, pretty, msgs, nimconf, - extccomp, condsyms, lists +import compiler/options, compiler/commands, compiler/modules, compiler/sem, + compiler/passes, compiler/passaux, compiler/nimfix/pretty, + compiler/msgs, compiler/nimconf, + compiler/extccomp, compiler/condsyms, compiler/lists const Usage = """ Nimfix - Tool to patch Nim code @@ -24,7 +26,7 @@ Options: --wholeProject overwrite every processed file. --checkExtern:on|off style check also extern names --styleCheck:on|off|auto performs style checking for identifiers - and suggests an alternative spelling; + and suggests an alternative spelling; 'auto' corrects the spelling. --bestEffort try to fix the code even when there are errors. @@ -48,11 +50,11 @@ proc processCmdLine*(pass: TCmdLinePass, cmd: string) = var p = parseopt.initOptParser(cmd) var argsCount = 0 gOnlyMainfile = true - while true: + while true: parseopt.next(p) case p.kind - of cmdEnd: break - of cmdLongoption, cmdShortOption: + of cmdEnd: break + of cmdLongoption, cmdShortOption: case p.key.normalize of "overwritefiles": case p.val.normalize diff --git a/compiler/nimfix/pretty.nim b/compiler/nimfix/pretty.nim index d2d5b5e83..1123afb9e 100644 --- a/compiler/nimfix/pretty.nim +++ b/compiler/nimfix/pretty.nim @@ -10,9 +10,11 @@ ## This module implements the code "prettifier". This is part of the toolchain ## to convert Nim code into a consistent style. -import - strutils, os, options, ast, astalgo, msgs, ropes, idents, - intsets, strtabs, semdata, prettybase +import + strutils, os, intsets, strtabs + +import compiler/options, compiler/ast, compiler/astalgo, compiler/msgs, + compiler/semdata, compiler/nimfix/prettybase, compiler/ropes, compiler/idents type StyleCheck* {.pure.} = enum None, Warn, Auto @@ -92,7 +94,7 @@ proc beautifyName(s: string, k: TSymKind): string = proc replaceInFile(info: TLineInfo; newName: string) = loadFile(info) - + let line = gSourceFiles[info.fileIndex].lines[info.line-1] var first = min(info.col.int, line.len) if first < 0: return @@ -100,18 +102,18 @@ proc replaceInFile(info: TLineInfo; newName: string) = while first > 0 and line[first-1] in prettybase.Letters: dec first if first < 0: return if line[first] == '`': inc first - + let last = first+identLen(line, first)-1 if differ(line, first, last, newName): - # last-first+1 != newName.len or - var x = line.substr(0, first-1) & newName & line.substr(last+1) + # last-first+1 != newName.len or + var x = line.substr(0, first-1) & newName & line.substr(last+1) system.shallowCopy(gSourceFiles[info.fileIndex].lines[info.line-1], x) gSourceFiles[info.fileIndex].dirty = true proc checkStyle(info: TLineInfo, s: string, k: TSymKind; sym: PSym) = let beau = beautifyName(s, k) if s != beau: - if gStyleCheck == StyleCheck.Auto: + if gStyleCheck == StyleCheck.Auto: sym.name = getIdent(beau) replaceInFile(info, beau) else: @@ -137,7 +139,7 @@ proc styleCheckUseImpl(info: TLineInfo; s: PSym) = if info.fileIndex < 0: return # we simply convert it to what it looks like in the definition # for consistency - + # operators stay as they are: if s.kind in {skResult, skTemp} or s.name.s[0] notin prettybase.Letters: return diff --git a/compiler/nimfix/prettybase.nim b/compiler/nimfix/prettybase.nim index 5130d1863..0f17cbcb1 100644 --- a/compiler/nimfix/prettybase.nim +++ b/compiler/nimfix/prettybase.nim @@ -7,7 +7,8 @@ # distribution, for details about the copyright. # -import ast, msgs, strutils, idents, lexbase, streams +import strutils, lexbase, streams +import compiler/ast, compiler/msgs, compiler/idents from os import splitFile type @@ -39,7 +40,7 @@ proc loadFile*(info: TLineInfo) = var pos = lex.bufpos while true: case lex.buf[pos] - of '\c': + of '\c': gSourceFiles[i].newline = "\c\L" break of '\L', '\0': @@ -70,7 +71,7 @@ proc replaceDeprecated*(info: TLineInfo; oldSym, newSym: PIdent) = while first > 0 and line[first-1] in Letters: dec first if first < 0: return if line[first] == '`': inc first - + let last = first+identLen(line, first)-1 if cmpIgnoreStyle(line[first..last], oldSym.s) == 0: var x = line.substr(0, first-1) & newSym.s & line.substr(last+1) diff --git a/compiler/plugins/locals/locals.nim b/compiler/plugins/locals/locals.nim index d89149f33..59e3d677d 100644 --- a/compiler/plugins/locals/locals.nim +++ b/compiler/plugins/locals/locals.nim @@ -9,7 +9,8 @@ ## The builtin 'system.locals' implemented as a plugin. -import plugins, ast, astalgo, magicsys, lookups, semdata, lowerings +import compiler/plugins, compiler/ast, compiler/astalgo, compiler/magicsys, + compiler/lookups, compiler/semdata, compiler/lowerings proc semLocals(c: PContext, n: PNode): PNode = var counter = 0 From 52192ffa9f1436b6be15aae6ad7f5a63b49d5b03 Mon Sep 17 00:00:00 2001 From: Dominik Picheta Date: Thu, 4 Jun 2015 23:12:38 +0100 Subject: [PATCH 0395/1263] Fixes compilation with --gc:markandsweep. --- lib/system/gc_ms.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/system/gc_ms.nim b/lib/system/gc_ms.nim index aab28eba2..ee80c61e9 100644 --- a/lib/system/gc_ms.nim +++ b/lib/system/gc_ms.nim @@ -58,7 +58,7 @@ type stat: GcStat additionalRoots: CellSeq # dummy roots for GC_ref/unref {.deprecated: [TWalkOp: WalkOp, TFinalizer: Finalizer, TGcStat: GcStat, - TGlobalMarkerProc: GlobalMarkerProc, TGcHeap, GcHeap].} + TGlobalMarkerProc: GlobalMarkerProc, TGcHeap: GcHeap].} var gch {.rtlThreadVar.}: GcHeap From 4a7c0e887211d5697c03f147141605e0f46d0736 Mon Sep 17 00:00:00 2001 From: Dominik Picheta Date: Thu, 4 Jun 2015 23:23:41 +0100 Subject: [PATCH 0396/1263] Add WSAEADDRINUSE to winlean. --- lib/windows/winlean.nim | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/windows/winlean.nim b/lib/windows/winlean.nim index 39f2be61d..9f04bab35 100644 --- a/lib/windows/winlean.nim +++ b/lib/windows/winlean.nim @@ -690,6 +690,7 @@ const ERROR_IO_PENDING* = 997 # a.k.a WSA_IO_PENDING FILE_FLAG_OVERLAPPED* = 1073741824 WSAECONNABORTED* = 10053 + WSAEADDRINUSE* = 10048 WSAECONNRESET* = 10054 WSAEDISCON* = 10101 WSAENETRESET* = 10052 From 4b0089bf58fb0922da0322745a8e1cd957fe0240 Mon Sep 17 00:00:00 2001 From: Dominik Picheta Date: Thu, 4 Jun 2015 23:25:29 +0100 Subject: [PATCH 0397/1263] Removed nimsuggest from this repo. --- compiler/nimsuggest/nimsuggest.nim | 328 +------------------------ compiler/nimsuggest/nimsuggest.nim.cfg | 17 -- 2 files changed, 2 insertions(+), 343 deletions(-) delete mode 100644 compiler/nimsuggest/nimsuggest.nim.cfg diff --git a/compiler/nimsuggest/nimsuggest.nim b/compiler/nimsuggest/nimsuggest.nim index 2c785d118..2be368d68 100644 --- a/compiler/nimsuggest/nimsuggest.nim +++ b/compiler/nimsuggest/nimsuggest.nim @@ -7,330 +7,6 @@ # distribution, for details about the copyright. # -## Nimsuggest is a tool that helps to give editors IDE like capabilities. +## Nimsuggest has been moved to https://github.com/nim-lang/nimsuggest -import strutils, os, parseopt, parseutils, sequtils, net -# Do NOT import suggest. It will lead to wierd bugs with -# suggestionResultHook, because suggest.nim is included by sigmatch. -# So we import that one instead. -import options, commands, modules, sem, passes, passaux, msgs, nimconf, - extccomp, condsyms, lists, net, rdstdin, sexp, sigmatch, ast - -when defined(windows): - import winlean -else: - import posix - -const Usage = """ -Nimsuggest - Tool to give every editor IDE like capabilities for Nim -Usage: - nimsuggest [options] projectfile.nim - -Options: - --port:PORT port, by default 6000 - --address:HOST binds to that address, by default "" - --stdin read commands from stdin and write results to - stdout instead of using sockets - --epc use emacs epc mode - -The server then listens to the connection and takes line-based commands. - -In addition, all command line options of Nim that do not affect code generation -are supported. -""" -type - Mode = enum mstdin, mtcp, mepc - -var - gPort = 6000.Port - gAddress = "" - gMode: Mode - -const - seps = {':', ';', ' ', '\t'} - Help = "usage: sug|con|def|use file.nim[;dirtyfile.nim]:line:col\n"& - "type 'quit' to quit\n" & - "type 'debug' to toggle debug mode on/off\n" & - "type 'terse' to toggle terse mode on/off" - -type - EUnexpectedCommand = object of Exception - -proc parseQuoted(cmd: string; outp: var string; start: int): int = - var i = start - i += skipWhitespace(cmd, i) - if cmd[i] == '"': - i += parseUntil(cmd, outp, '"', i+1)+2 - else: - i += parseUntil(cmd, outp, seps, i) - result = i - -proc sexp(s: IdeCmd): SexpNode = sexp($s) - -proc sexp(s: TSymKind): SexpNode = sexp($s) - -proc sexp(s: Suggest): SexpNode = - # If you change the oder here, make sure to change it over in - # nim-mode.el too. - result = convertSexp([ - s.section, - s.symkind, - s.qualifiedPath.map(newSString), - s.filePath, - s.forth, - s.line, - s.column, - s.doc - ]) - -proc sexp(s: seq[Suggest]): SexpNode = - result = newSList() - for sug in s: - result.add(sexp(sug)) - -proc listEPC(): SexpNode = - let - argspecs = sexp("file line column dirtyfile".split(" ").map(newSSymbol)) - docstring = sexp("line starts at 1, column at 0, dirtyfile is optional") - result = newSList() - for command in ["sug", "con", "def", "use"]: - let - cmd = sexp(command) - methodDesc = newSList() - methodDesc.add(cmd) - methodDesc.add(argspecs) - methodDesc.add(docstring) - result.add(methodDesc) - -proc execute(cmd: IdeCmd, file, dirtyfile: string, line, col: int) = - gIdeCmd = cmd - if cmd == ideUse: - modules.resetAllModules() - var isKnownFile = true - let dirtyIdx = file.fileInfoIdx(isKnownFile) - - if dirtyfile.len != 0: msgs.setDirtyFile(dirtyIdx, dirtyfile) - else: msgs.setDirtyFile(dirtyIdx, nil) - - resetModule dirtyIdx - if dirtyIdx != gProjectMainIdx: - resetModule gProjectMainIdx - - gTrackPos = newLineInfo(dirtyIdx, line, col) - gErrorCounter = 0 - if not isKnownFile: - compileProject() - compileProject(dirtyIdx) - -proc executeEPC(cmd: IdeCmd, args: SexpNode) = - let - file = args[0].getStr - line = args[1].getNum - column = args[2].getNum - var dirtyfile = "" - if len(args) > 3: - dirtyfile = args[3].getStr(nil) - execute(cmd, file, dirtyfile, int(line), int(column)) - -proc returnEPC(socket: var Socket, uid: BiggestInt, s: SexpNode, return_symbol = "return") = - let response = $convertSexp([newSSymbol(return_symbol), uid, s]) - socket.send(toHex(len(response), 6)) - socket.send(response) - -proc connectToNextFreePort(server: Socket, host: string, start = 30000): int = - result = start - while true: - try: - server.bindaddr(Port(result), host) - return - except OsError: - when defined(windows): - let checkFor = WSAEADDRINUSE.OSErrorCode - else: - let checkFor = EADDRINUSE.OSErrorCode - if osLastError() != checkFor: - raise getCurrentException() - else: - result += 1 - -proc parseCmdLine(cmd: string) = - template toggle(sw) = - if sw in gGlobalOptions: - excl(gGlobalOptions, sw) - else: - incl(gGlobalOptions, sw) - return - - template err() = - echo Help - return - - var opc = "" - var i = parseIdent(cmd, opc, 0) - case opc.normalize - of "sug": gIdeCmd = ideSug - of "con": gIdeCmd = ideCon - of "def": gIdeCmd = ideDef - of "use": gIdeCmd = ideUse - of "quit": quit() - of "debug": toggle optIdeDebug - of "terse": toggle optIdeTerse - else: err() - var dirtyfile = "" - var orig = "" - i = parseQuoted(cmd, orig, i) - if cmd[i] == ';': - i = parseQuoted(cmd, dirtyfile, i+1) - i += skipWhile(cmd, seps, i) - var line = -1 - var col = 0 - i += parseInt(cmd, line, i) - i += skipWhile(cmd, seps, i) - i += parseInt(cmd, col, i) - - execute(gIdeCmd, orig, dirtyfile, line, col-1) - -proc serve() = - case gMode: - of mstdin: - echo Help - var line = "" - while readLineFromStdin("> ", line): - parseCmdLine line - echo "" - flushFile(stdout) - of mtcp: - var server = newSocket() - server.bindAddr(gPort, gAddress) - var inp = "".TaintedString - server.listen() - - while true: - var stdoutSocket = newSocket() - msgs.writelnHook = proc (line: string) = - stdoutSocket.send(line & "\c\L") - - accept(server, stdoutSocket) - - stdoutSocket.readLine(inp) - parseCmdLine inp.string - - stdoutSocket.send("\c\L") - stdoutSocket.close() - of mepc: - var server = newSocket() - let port = connectToNextFreePort(server, "localhost") - var inp = "".TaintedString - server.listen() - echo(port) - var client = newSocket() - # Wait for connection - accept(server, client) - while true: - var sizeHex = "" - if client.recv(sizeHex, 6) != 6: - raise newException(ValueError, "didn't get all the hexbytes") - var size = 0 - if parseHex(sizeHex, size) == 0: - raise newException(ValueError, "invalid size hex: " & $sizeHex) - var messageBuffer = "" - if client.recv(messageBuffer, size) != size: - raise newException(ValueError, "didn't get all the bytes") - let - message = parseSexp($messageBuffer) - messageType = message[0].getSymbol - case messageType: - of "call": - var results: seq[Suggest] = @[] - suggestionResultHook = proc (s: Suggest) = - results.add(s) - - let - uid = message[1].getNum - cmd = parseIdeCmd(message[2].getSymbol) - args = message[3] - executeEPC(cmd, args) - returnEPC(client, uid, sexp(results)) - of "return": - raise newException(EUnexpectedCommand, "no return expected") - of "return-error": - raise newException(EUnexpectedCommand, "no return expected") - of "epc-error": - stderr.writeln("recieved epc error: " & $messageBuffer) - raise newException(IOError, "epc error") - of "methods": - returnEPC(client, message[1].getNum, listEPC()) - else: - raise newException(EUnexpectedCommand, "unexpected call: " & messageType) - -proc mainCommand = - registerPass verbosePass - registerPass semPass - gCmd = cmdIdeTools - incl gGlobalOptions, optCaasEnabled - isServing = true - wantMainModule() - appendStr(searchPaths, options.libpath) - if gProjectFull.len != 0: - # current path is always looked first for modules - prependStr(searchPaths, gProjectPath) - - # do not stop after the first error: - msgs.gErrorMax = high(int) - compileProject() - serve() - -proc processCmdLine*(pass: TCmdLinePass, cmd: string) = - var p = parseopt.initOptParser(cmd) - while true: - parseopt.next(p) - case p.kind - of cmdEnd: break - of cmdLongoption, cmdShortOption: - case p.key.normalize - of "port": - gPort = parseInt(p.val).Port - gMode = mtcp - of "address": - gAddress = p.val - gMode = mtcp - of "stdin": gMode = mstdin - of "epc": - gMode = mepc - gVerbosity = 0 # Port number gotta be first. - else: processSwitch(pass, p) - of cmdArgument: - options.gProjectName = unixToNativePath(p.key) - # if processArgument(pass, p, argsCount): break - -proc handleCmdLine() = - if paramCount() == 0: - stdout.writeln(Usage) - else: - processCmdLine(passCmd1, "") - if gProjectName != "": - try: - gProjectFull = canonicalizePath(gProjectName) - except OSError: - gProjectFull = gProjectName - var p = splitFile(gProjectFull) - gProjectPath = p.dir - gProjectName = p.name - else: - gProjectPath = getCurrentDir() - loadConfigs(DefaultConfig) # load all config files - # now process command line arguments again, because some options in the - # command line can overwite the config file's settings - extccomp.initVars() - processCmdLine(passCmd2, "") - mainCommand() - -when false: - proc quitCalled() {.noconv.} = - writeStackTrace() - - addQuitProc(quitCalled) - -condsyms.initDefines() -defineSymbol "nimsuggest" -handleCmdline() +{.error: "This project has moved to the following repo: https://github.com/nim-lang/nimsuggest".} diff --git a/compiler/nimsuggest/nimsuggest.nim.cfg b/compiler/nimsuggest/nimsuggest.nim.cfg deleted file mode 100644 index acca17396..000000000 --- a/compiler/nimsuggest/nimsuggest.nim.cfg +++ /dev/null @@ -1,17 +0,0 @@ -# Special configuration file for the Nim project - -gc:markAndSweep - -hint[XDeclaredButNotUsed]:off -path:"$projectPath/../.." - -path:"$lib/packages/docutils" -path:"../../compiler" - -define:useStdoutAsStdmsg -define:nimsuggest - -cs:partial -#define:useNodeIds -define:booting -#define:noDocgen From 25cc9befd538ec92938c9030d2e68658514f358c Mon Sep 17 00:00:00 2001 From: Adam Strzelecki Date: Fri, 5 Jun 2015 12:44:28 +0200 Subject: [PATCH 0398/1263] Fixup: Reverted TZipFileStream name change This fixes broken b0469c11e334e96cebe53cbe804b6a877831c85a that incompletely reverted TZipFileStream name change. --- lib/impure/zipfiles.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/impure/zipfiles.nim b/lib/impure/zipfiles.nim index d66d7d7f3..d8903f5c1 100644 --- a/lib/impure/zipfiles.nim +++ b/lib/impure/zipfiles.nim @@ -114,7 +114,7 @@ type atEnd: bool PZipFileStream* = - ref ZipFileStream ## a reader stream of a file within a zip archive + ref TZipFileStream ## a reader stream of a file within a zip archive proc fsClose(s: Stream) = zip_fclose(PZipFileStream(s).f) proc fsAtEnd(s: Stream): bool = PZipFileStream(s).atEnd From cb443ce73d8d451fc8a4168f035ec85350b349c7 Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Fri, 5 Jun 2015 11:04:15 -0500 Subject: [PATCH 0399/1263] moved sexp.nim to nimsuggest repo --- lib/pure/sexp.nim | 698 ---------------------------------------------- 1 file changed, 698 deletions(-) delete mode 100644 lib/pure/sexp.nim diff --git a/lib/pure/sexp.nim b/lib/pure/sexp.nim deleted file mode 100644 index be6188c9e..000000000 --- a/lib/pure/sexp.nim +++ /dev/null @@ -1,698 +0,0 @@ -# -# -# Nim's Runtime Library -# (c) Copyright 2015 Andreas Rumpf, Dominik Picheta -# -# See the file "copying.txt", included in this -# distribution, for details about the copyright. -# - -import - hashes, strutils, lexbase, streams, unicode, macros - -type - SexpEventKind* = enum ## enumeration of all events that may occur when parsing - sexpError, ## an error occurred during parsing - sexpEof, ## end of file reached - sexpString, ## a string literal - sexpSymbol, ## a symbol - sexpInt, ## an integer literal - sexpFloat, ## a float literal - sexpNil, ## the value ``nil`` - sexpDot, ## the dot to separate car/cdr - sexpListStart, ## start of a list: the ``(`` token - sexpListEnd, ## end of a list: the ``)`` token - - TokKind = enum # must be synchronized with SexpEventKind! - tkError, - tkEof, - tkString, - tkSymbol, - tkInt, - tkFloat, - tkNil, - tkDot, - tkParensLe, - tkParensRi - tkSpace - - SexpError* = enum ## enumeration that lists all errors that can occur - errNone, ## no error - errInvalidToken, ## invalid token - errParensRiExpected, ## ``)`` expected - errQuoteExpected, ## ``"`` expected - errEofExpected, ## EOF expected - - SexpParser* = object of BaseLexer ## the parser object. - a: string - tok: TokKind - kind: SexpEventKind - err: SexpError -{.deprecated: [TTokKind: TokKind].} - -const - errorMessages: array [SexpError, string] = [ - "no error", - "invalid token", - "')' expected", - "'\"' or \"'\" expected", - "EOF expected", - ] - tokToStr: array [TokKind, string] = [ - "invalid token", - "EOF", - "string literal", - "symbol", - "int literal", - "float literal", - "nil", - ".", - "(", ")", "space" - ] - -proc close*(my: var SexpParser) {.inline.} = - ## closes the parser `my` and its associated input stream. - lexbase.close(my) - -proc str*(my: SexpParser): string {.inline.} = - ## returns the character data for the events: ``sexpInt``, ``sexpFloat``, - ## ``sexpString`` - assert(my.kind in {sexpInt, sexpFloat, sexpString}) - result = my.a - -proc getInt*(my: SexpParser): BiggestInt {.inline.} = - ## returns the number for the event: ``sexpInt`` - assert(my.kind == sexpInt) - result = parseBiggestInt(my.a) - -proc getFloat*(my: SexpParser): float {.inline.} = - ## returns the number for the event: ``sexpFloat`` - assert(my.kind == sexpFloat) - result = parseFloat(my.a) - -proc kind*(my: SexpParser): SexpEventKind {.inline.} = - ## returns the current event type for the SEXP parser - result = my.kind - -proc getColumn*(my: SexpParser): int {.inline.} = - ## get the current column the parser has arrived at. - result = getColNumber(my, my.bufpos) - -proc getLine*(my: SexpParser): int {.inline.} = - ## get the current line the parser has arrived at. - result = my.lineNumber - -proc errorMsg*(my: SexpParser): string = - ## returns a helpful error message for the event ``sexpError`` - assert(my.kind == sexpError) - result = "($1, $2) Error: $3" % [$getLine(my), $getColumn(my), errorMessages[my.err]] - -proc errorMsgExpected*(my: SexpParser, e: string): string = - ## returns an error message "`e` expected" in the same format as the - ## other error messages - result = "($1, $2) Error: $3" % [$getLine(my), $getColumn(my), e & " expected"] - -proc handleHexChar(c: char, x: var int): bool = - result = true # Success - case c - of '0'..'9': x = (x shl 4) or (ord(c) - ord('0')) - of 'a'..'f': x = (x shl 4) or (ord(c) - ord('a') + 10) - of 'A'..'F': x = (x shl 4) or (ord(c) - ord('A') + 10) - else: result = false # error - -proc parseString(my: var SexpParser): TokKind = - result = tkString - var pos = my.bufpos + 1 - var buf = my.buf - while true: - case buf[pos] - of '\0': - my.err = errQuoteExpected - result = tkError - break - of '"': - inc(pos) - break - of '\\': - case buf[pos+1] - of '\\', '"', '\'', '/': - add(my.a, buf[pos+1]) - inc(pos, 2) - of 'b': - add(my.a, '\b') - inc(pos, 2) - of 'f': - add(my.a, '\f') - inc(pos, 2) - of 'n': - add(my.a, '\L') - inc(pos, 2) - of 'r': - add(my.a, '\C') - inc(pos, 2) - of 't': - add(my.a, '\t') - inc(pos, 2) - of 'u': - inc(pos, 2) - var r: int - if handleHexChar(buf[pos], r): inc(pos) - if handleHexChar(buf[pos], r): inc(pos) - if handleHexChar(buf[pos], r): inc(pos) - if handleHexChar(buf[pos], r): inc(pos) - add(my.a, toUTF8(Rune(r))) - else: - # don't bother with the error - add(my.a, buf[pos]) - inc(pos) - of '\c': - pos = lexbase.handleCR(my, pos) - buf = my.buf - add(my.a, '\c') - of '\L': - pos = lexbase.handleLF(my, pos) - buf = my.buf - add(my.a, '\L') - else: - add(my.a, buf[pos]) - inc(pos) - my.bufpos = pos # store back - -proc parseNumber(my: var SexpParser) = - var pos = my.bufpos - var buf = my.buf - if buf[pos] == '-': - add(my.a, '-') - inc(pos) - if buf[pos] == '.': - add(my.a, "0.") - inc(pos) - else: - while buf[pos] in Digits: - add(my.a, buf[pos]) - inc(pos) - if buf[pos] == '.': - add(my.a, '.') - inc(pos) - # digits after the dot: - while buf[pos] in Digits: - add(my.a, buf[pos]) - inc(pos) - if buf[pos] in {'E', 'e'}: - add(my.a, buf[pos]) - inc(pos) - if buf[pos] in {'+', '-'}: - add(my.a, buf[pos]) - inc(pos) - while buf[pos] in Digits: - add(my.a, buf[pos]) - inc(pos) - my.bufpos = pos - -proc parseSymbol(my: var SexpParser) = - var pos = my.bufpos - var buf = my.buf - if buf[pos] in IdentStartChars: - while buf[pos] in IdentChars: - add(my.a, buf[pos]) - inc(pos) - my.bufpos = pos - -proc getTok(my: var SexpParser): TokKind = - setLen(my.a, 0) - case my.buf[my.bufpos] - of '-', '0'..'9': # numbers that start with a . are not parsed - # correctly. - parseNumber(my) - if {'.', 'e', 'E'} in my.a: - result = tkFloat - else: - result = tkInt - of '"': #" # gotta fix nim-mode - result = parseString(my) - of '(': - inc(my.bufpos) - result = tkParensLe - of ')': - inc(my.bufpos) - result = tkParensRi - of '\0': - result = tkEof - of 'a'..'z', 'A'..'Z', '_': - parseSymbol(my) - if my.a == "nil": - result = tkNil - else: - result = tkSymbol - of ' ': - result = tkSpace - inc(my.bufpos) - of '.': - result = tkDot - inc(my.bufpos) - else: - inc(my.bufpos) - result = tkError - my.tok = result - -# ------------- higher level interface --------------------------------------- - -type - SexpNodeKind* = enum ## possible SEXP node types - SNil, - SInt, - SFloat, - SString, - SSymbol, - SList, - SCons - - SexpNode* = ref SexpNodeObj ## SEXP node - SexpNodeObj* {.acyclic.} = object - case kind*: SexpNodeKind - of SString: - str*: string - of SSymbol: - symbol*: string - of SInt: - num*: BiggestInt - of SFloat: - fnum*: float - of SList: - elems*: seq[SexpNode] - of SCons: - car: SexpNode - cdr: SexpNode - of SNil: - discard - - Cons = tuple[car: SexpNode, cdr: SexpNode] - - SexpParsingError* = object of ValueError ## is raised for a SEXP error - -proc raiseParseErr*(p: SexpParser, msg: string) {.noinline, noreturn.} = - ## raises an `ESexpParsingError` exception. - raise newException(SexpParsingError, errorMsgExpected(p, msg)) - -proc newSString*(s: string): SexpNode {.procvar.}= - ## Creates a new `SString SexpNode`. - new(result) - result.kind = SString - result.str = s - -proc newSStringMove(s: string): SexpNode = - new(result) - result.kind = SString - shallowCopy(result.str, s) - -proc newSInt*(n: BiggestInt): SexpNode {.procvar.} = - ## Creates a new `SInt SexpNode`. - new(result) - result.kind = SInt - result.num = n - -proc newSFloat*(n: float): SexpNode {.procvar.} = - ## Creates a new `SFloat SexpNode`. - new(result) - result.kind = SFloat - result.fnum = n - -proc newSNil*(): SexpNode {.procvar.} = - ## Creates a new `SNil SexpNode`. - new(result) - -proc newSCons*(car, cdr: SexpNode): SexpNode {.procvar.} = - ## Creates a new `SCons SexpNode` - new(result) - result.kind = SCons - result.car = car - result.cdr = cdr - -proc newSList*(): SexpNode {.procvar.} = - ## Creates a new `SList SexpNode` - new(result) - result.kind = SList - result.elems = @[] - -proc newSSymbol*(s: string): SexpNode {.procvar.} = - new(result) - result.kind = SSymbol - result.symbol = s - -proc newSSymbolMove(s: string): SexpNode = - new(result) - result.kind = SSymbol - shallowCopy(result.symbol, s) - -proc getStr*(n: SexpNode, default: string = ""): string = - ## Retrieves the string value of a `SString SexpNode`. - ## - ## Returns ``default`` if ``n`` is not a ``SString``. - if n.kind != SString: return default - else: return n.str - -proc getNum*(n: SexpNode, default: BiggestInt = 0): BiggestInt = - ## Retrieves the int value of a `SInt SexpNode`. - ## - ## Returns ``default`` if ``n`` is not a ``SInt``. - if n.kind != SInt: return default - else: return n.num - -proc getFNum*(n: SexpNode, default: float = 0.0): float = - ## Retrieves the float value of a `SFloat SexpNode`. - ## - ## Returns ``default`` if ``n`` is not a ``SFloat``. - if n.kind != SFloat: return default - else: return n.fnum - -proc getSymbol*(n: SexpNode, default: string = ""): string = - ## Retrieves the int value of a `SList SexpNode`. - ## - ## Returns ``default`` if ``n`` is not a ``SList``. - if n.kind != SSymbol: return default - else: return n.symbol - -proc getElems*(n: SexpNode, default: seq[SexpNode] = @[]): seq[SexpNode] = - ## Retrieves the int value of a `SList SexpNode`. - ## - ## Returns ``default`` if ``n`` is not a ``SList``. - if n.kind == SNil: return @[] - elif n.kind != SList: return default - else: return n.elems - -proc getCons*(n: SexpNode, defaults: Cons = (newSNil(), newSNil())): Cons = - ## Retrieves the cons value of a `SList SexpNode`. - ## - ## Returns ``default`` if ``n`` is not a ``SList``. - if n.kind == SCons: return (n.car, n.cdr) - elif n.kind == SList: return (n.elems[0], n.elems[1]) - else: return defaults - -proc sexp*(s: string): SexpNode = - ## Generic constructor for SEXP data. Creates a new `SString SexpNode`. - new(result) - result.kind = SString - result.str = s - -proc sexp*(n: BiggestInt): SexpNode = - ## Generic constructor for SEXP data. Creates a new `SInt SexpNode`. - new(result) - result.kind = SInt - result.num = n - -proc sexp*(n: float): SexpNode = - ## Generic constructor for SEXP data. Creates a new `SFloat SexpNode`. - new(result) - result.kind = SFloat - result.fnum = n - -proc sexp*(b: bool): SexpNode = - ## Generic constructor for SEXP data. Creates a new `SSymbol - ## SexpNode` with value t or `SNil SexpNode`. - new(result) - if b: - result.kind = SSymbol - result.symbol = "t" - else: - result.kind = SNil - -proc sexp*(elements: openArray[SexpNode]): SexpNode = - ## Generic constructor for SEXP data. Creates a new `SList SexpNode` - new(result) - result.kind = SList - newSeq(result.elems, elements.len) - for i, p in pairs(elements): result.elems[i] = p - -proc sexp*(s: SexpNode): SexpNode = - result = s - -proc toSexp(x: NimNode): NimNode {.compiletime.} = - case x.kind - of nnkBracket: - result = newNimNode(nnkBracket) - for i in 0 .. = 32 and r <= 127: - var c = chr(r) - case c - of '"': result.add("\\\"") #" # gotta fix nim-mode - of '\\': result.add("\\\\") - else: result.add(c) - else: - result.add("\\u") - result.add(toHex(r, 4)) - result.add("\"") - -proc copy*(p: SexpNode): SexpNode = - ## Performs a deep copy of `a`. - case p.kind - of SString: - result = newSString(p.str) - of SInt: - result = newSInt(p.num) - of SFloat: - result = newSFloat(p.fnum) - of SNil: - result = newSNil() - of SSymbol: - result = newSSymbol(p.symbol) - of SList: - result = newSList() - for i in items(p.elems): - result.elems.add(copy(i)) - of SCons: - result = newSCons(copy(p.car), copy(p.cdr)) - -proc toPretty(result: var string, node: SexpNode, indent = 2, ml = true, - lstArr = false, currIndent = 0) = - case node.kind - of SString: - if lstArr: result.indent(currIndent) - result.add(escapeJson(node.str)) - of SInt: - if lstArr: result.indent(currIndent) - result.add($node.num) - of SFloat: - if lstArr: result.indent(currIndent) - result.add($node.fnum) - of SNil: - if lstArr: result.indent(currIndent) - result.add("nil") - of SSymbol: - if lstArr: result.indent(currIndent) - result.add($node.symbol) - of SList: - if lstArr: result.indent(currIndent) - if len(node.elems) != 0: - result.add("(") - result.nl(ml) - for i in 0..len(node.elems)-1: - if i > 0: - result.add(" ") - result.nl(ml) # New Line - toPretty(result, node.elems[i], indent, ml, - true, newIndent(currIndent, indent, ml)) - result.nl(ml) - result.indent(currIndent) - result.add(")") - else: result.add("nil") - of SCons: - if lstArr: result.indent(currIndent) - result.add("(") - toPretty(result, node.car, indent, ml, - true, newIndent(currIndent, indent, ml)) - result.add(" . ") - toPretty(result, node.cdr, indent, ml, - true, newIndent(currIndent, indent, ml)) - result.add(")") - -proc pretty*(node: SexpNode, indent = 2): string = - ## Converts `node` to its Sexp Representation, with indentation and - ## on multiple lines. - result = "" - toPretty(result, node, indent) - -proc `$`*(node: SexpNode): string = - ## Converts `node` to its SEXP Representation on one line. - result = "" - toPretty(result, node, 0, false) - -iterator items*(node: SexpNode): SexpNode = - ## Iterator for the items of `node`. `node` has to be a SList. - assert node.kind == SList - for i in items(node.elems): - yield i - -iterator mitems*(node: var SexpNode): var SexpNode = - ## Iterator for the items of `node`. `node` has to be a SList. Items can be - ## modified. - assert node.kind == SList - for i in mitems(node.elems): - yield i - -proc eat(p: var SexpParser, tok: TokKind) = - if p.tok == tok: discard getTok(p) - else: raiseParseErr(p, tokToStr[tok]) - -proc parseSexp(p: var SexpParser): SexpNode = - ## Parses SEXP from a SEXP Parser `p`. - case p.tok - of tkString: - # we capture 'p.a' here, so we need to give it a fresh buffer afterwards: - result = newSStringMove(p.a) - p.a = "" - discard getTok(p) - of tkInt: - result = newSInt(parseBiggestInt(p.a)) - discard getTok(p) - of tkFloat: - result = newSFloat(parseFloat(p.a)) - discard getTok(p) - of tkNil: - result = newSNil() - discard getTok(p) - of tkSymbol: - result = newSSymbolMove(p.a) - p.a = "" - discard getTok(p) - of tkParensLe: - result = newSList() - discard getTok(p) - while p.tok notin {tkParensRi, tkDot}: - result.add(parseSexp(p)) - if p.tok != tkSpace: break - discard getTok(p) - if p.tok == tkDot: - eat(p, tkDot) - eat(p, tkSpace) - result.add(parseSexp(p)) - result = newSCons(result[0], result[1]) - eat(p, tkParensRi) - of tkSpace, tkDot, tkError, tkParensRi, tkEof: - raiseParseErr(p, "(") - -proc open*(my: var SexpParser, input: Stream) = - ## initializes the parser with an input stream. - lexbase.open(my, input) - my.kind = sexpError - my.a = "" - -proc parseSexp*(s: Stream): SexpNode = - ## Parses from a buffer `s` into a `SexpNode`. - var p: SexpParser - p.open(s) - discard getTok(p) # read first token - result = p.parseSexp() - p.close() - -proc parseSexp*(buffer: string): SexpNode = - ## Parses Sexp from `buffer`. - result = parseSexp(newStringStream(buffer)) - -when isMainModule: - let testSexp = parseSexp("""(1 (98 2) nil (2) foobar "foo" 9.234)""") - assert(testSexp[0].getNum == 1) - assert(testSexp[1][0].getNum == 98) - assert(testSexp[2].getElems == @[]) - assert(testSexp[4].getSymbol == "foobar") - assert(testSexp[5].getStr == "foo") - - let alist = parseSexp("""((1 . 2) (2 . "foo"))""") - assert(alist[0].getCons.car.getNum == 1) - assert(alist[0].getCons.cdr.getNum == 2) - assert(alist[1].getCons.cdr.getStr == "foo") - - # Generator: - var j = convertSexp([true, false, "foobar", [1, 2, "baz"]]) - assert($j == """(t nil "foobar" (1 2 "baz"))""") From 87a6d08e95c940775577c8f2bc5a74408c956a89 Mon Sep 17 00:00:00 2001 From: Dominik Picheta Date: Fri, 5 Jun 2015 17:10:17 +0100 Subject: [PATCH 0400/1263] Update version in compiler.nimble --- compiler.nimble | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/compiler.nimble b/compiler.nimble index 52eb4083b..9d39af502 100644 --- a/compiler.nimble +++ b/compiler.nimble @@ -1,6 +1,6 @@ [Package] name = "compiler" -version = "0.10.3" +version = "0.11.3" author = "Andreas Rumpf" description = "Compiler package providing the compiler sources as a library." license = "MIT" @@ -8,4 +8,4 @@ license = "MIT" InstallDirs = "doc, compiler" [Deps] -Requires: "nim >= 0.10.3" +Requires: "nim >= 0.11.3" From 9db6070d731330a4eb41784b04e72322851ac684 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Tue, 26 May 2015 19:33:34 -0400 Subject: [PATCH 0401/1263] Fix nre tests --- tests/stdlib/nre/init.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/stdlib/nre/init.nim b/tests/stdlib/nre/init.nim index 76ffaba19..1a1470842 100644 --- a/tests/stdlib/nre/init.nim +++ b/tests/stdlib/nre/init.nim @@ -1,4 +1,4 @@ -import unittest, private/pcre +import unittest include nre suite "Test NRE initialization": From be64b8d0d4fe3ab3ed339e1157a18654dca41399 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Tue, 26 May 2015 19:33:44 -0400 Subject: [PATCH 0402/1263] Ensure no one uses internal module --- lib/impure/nre/private/util.nim | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/impure/nre/private/util.nim b/lib/impure/nre/private/util.nim index 00fd40fac..253bfada7 100644 --- a/lib/impure/nre/private/util.nim +++ b/lib/impure/nre/private/util.nim @@ -1,3 +1,4 @@ +## INTERNAL FILE FOR USE ONLY BY nre.nim. import tables proc fget*[K, V](self: Table[K, V], key: K): V = From b27c1946c9ea1ff29e070d42c9f0f3cd9e67e185 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Tue, 26 May 2015 19:37:19 -0400 Subject: [PATCH 0403/1263] Update news for nre --- web/news.txt | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/web/news.txt b/web/news.txt index 6a82b3f26..49b49a9f1 100644 --- a/web/news.txt +++ b/web/news.txt @@ -13,12 +13,17 @@ News Code accessing that property is deprecated and code using ``miliseconds`` during object initialization or as a named parameter of ``initInterval()`` will need to be updated. - - ``std.logging`` functions no longer do formatting and semantically treat their arguments just like ``echo`` does. Affected functions: ``log``, ``debug``, ``info``, ``warn``, ``error``, ``fatal``. Custom subtypes of ``Logger`` also need to be adjusted accordingly. + Library additions + ----------------- + + - The nre module has been added, providing a better interface to PCRE than + re. + Language Additions ------------------ From dc60a51e1545d8c73bc9415d1045864b72cfda0b Mon Sep 17 00:00:00 2001 From: Oleh Prypin Date: Tue, 26 May 2015 19:44:46 -0400 Subject: [PATCH 0404/1263] Base re off of nre --- lib/impure/re.nim | 378 +++++++++++++++++----------------------------- 1 file changed, 141 insertions(+), 237 deletions(-) diff --git a/lib/impure/re.nim b/lib/impure/re.nim index 279f8aadd..a2689a45c 100644 --- a/lib/impure/re.nim +++ b/lib/impure/re.nim @@ -2,16 +2,13 @@ # # Nim's Runtime Library # (c) Copyright 2012 Andreas Rumpf +# (c) Copyright 2015 Oleh Prypin # # See the file "copying.txt", included in this # distribution, for details about the copyright. # -## Regular expression support for Nim. Consider using the pegs module instead. -## -## There is an alternative regular expressions library with a more unified API: -## `nre `_. It may be added to the standard -## library in the future, instead of `re`. +## Regular expression support for Nim. ## ## **Note:** The 're' proc defaults to the **extended regular expression ## syntax** which lets you use whitespace freely to make your regexes readable. @@ -28,13 +25,15 @@ ## .. include:: ../doc/regexprs.txt ## -import - pcre, strutils, rtarrays + +import strutils +import nre, options + +type Regex = nre.Regex const - MaxSubpatterns* = 20 - ## defines the maximum number of subpatterns that can be captured. - ## This limit still exists for ``replacef`` and ``parallelReplace``. + MaxSubpatterns* {.deprecated.} = 1000 + ## This is obsolete. There is no limit on the number of subpatterns. type RegexFlag* = enum ## options for regular expressions @@ -44,66 +43,61 @@ type reExtended = 3, ## ignore whitespace and ``#`` comments reStudy = 4 ## study the expression (may be omitted if the ## expression will be used only once) - - RegexDesc = object - h: ptr Pcre - e: ptr ExtraData - - Regex* = ref RegexDesc ## a compiled regular expression RegexError* = object of ValueError ## is raised if the pattern is no valid regular expression. -{.deprecated: [TRegexFlag: RegexFlag, TRegexDesc: RegexDesc, TRegex: Regex, - EInvalidRegEx: RegexError].} - -proc raiseInvalidRegex(msg: string) {.noinline, noreturn.} = - var e: ref RegexError - new(e) - e.msg = msg - raise e - -proc rawCompile(pattern: string, flags: cint): ptr Pcre = - var - msg: cstring - offset: cint - result = pcre.compile(pattern, flags, addr(msg), addr(offset), nil) - if result == nil: - raiseInvalidRegex($msg & "\n" & pattern & "\n" & spaces(offset) & "^\n") - -proc finalizeRegEx(x: Regex) = - # XXX This is a hack, but PCRE does not export its "free" function properly. - # Sigh. The hack relies on PCRE's implementation (see ``pcre_get.c``). - # Fortunately the implementation is unlikely to change. - pcre.free_substring(cast[cstring](x.h)) - if not isNil(x.e): - pcre.free_substring(cast[cstring](x.e)) proc re*(s: string, flags = {reExtended, reStudy}): Regex = ## Constructor of regular expressions. Note that Nim's ## extended raw string literals support this syntax ``re"[abc]"`` as ## a short form for ``re(r"[abc]")``. - new(result, finalizeRegEx) - result.h = rawCompile(s, cast[cint](flags - {reStudy})) - if reStudy in flags: - var msg: cstring - result.e = pcre.study(result.h, 0, addr msg) - if not isNil(msg): raiseInvalidRegex($msg) + var options = "" + if reStudy notin flags: + options.add "(*NO_STUDY)" + for t in [ + (reIgnoreCase, "(?i)"), + (reMultiLine, "(?m)"), + (reDotAll, "(?s)"), + (reExtended, "(?x)") + ]: + if t[0] in flags: + options.add t[1] + try: + return nre.re(options & s) + except nre.SyntaxError: + let e = nre.SyntaxError(getCurrentException()) + raise newException(RegexError, e.msg & "\n" & e.pattern & "\n" & + repeat(' ', e.pos) & "^\n") + except nre.StudyError: + let e = nre.StudyError(getCurrentException()) + raise newException(RegexError, "Study error: " & e.msg) -proc matchOrFind(s: string, pattern: Regex, matches: var openArray[string], - start, flags: cint): cint = - var - rtarray = initRtArray[cint]((matches.len+1)*3) - rawMatches = rtarray.getRawData - res = pcre.exec(pattern.h, pattern.e, s, len(s).cint, start, flags, - cast[ptr cint](rawMatches), (matches.len+1).cint*3) - if res < 0'i32: return res - for i in 1..int(res)-1: - var a = rawMatches[i * 2] - var b = rawMatches[i * 2 + 1] - if a >= 0'i32: matches[i-1] = substr(s, int(a), int(b)-1) - else: matches[i-1] = nil - return rawMatches[1] - rawMatches[0] + +template execute(f: expr, notFound: stmt): stmt {.immediate, dirty.} = + let mm = f(s, pattern, start) + var m: RegexMatch + if mm.isSome: + m = mm.unsafeGet() + else: + notFound + +template stringCaptures(): stmt {.immediate, dirty.} = + for i in 0 .. = 0'i32: matches[i-1] = substr(s, int(a), int(b)-1) - else: matches[i-1] = nil - return (rawMatches[0].int, rawMatches[1].int - 1) + execute nre.find: + return (-1, 0) + stringCaptures() + returnBounds() proc findBounds*(s: string, pattern: Regex, matches: var openArray[tuple[first, last: int]], @@ -131,56 +117,42 @@ proc findBounds*(s: string, pattern: Regex, ## and the captured substrings in the array `matches`. ## If it does not match, nothing is written into `matches` and ## ``(-1,0)`` is returned. - var - rtarray = initRtArray[cint]((matches.len+1)*3) - rawMatches = rtarray.getRawData - res = pcre.exec(pattern.h, pattern.e, s, len(s).cint, start.cint, 0'i32, - cast[ptr cint](rawMatches), (matches.len+1).cint*3) - if res < 0'i32: return (-1, 0) - for i in 1..int(res)-1: - var a = rawMatches[i * 2] - var b = rawMatches[i * 2 + 1] - if a >= 0'i32: matches[i-1] = (int(a), int(b)-1) - else: matches[i-1] = (-1,0) - return (rawMatches[0].int, rawMatches[1].int - 1) + execute nre.find: + return (-1, 0) + boundCaptures() + returnBounds() proc findBounds*(s: string, pattern: Regex, start = 0): tuple[first, last: int] = - ## returns the starting position and end position of ``pattern`` in ``s``. - ## If it does not match, ``(-1,0)`` is returned. - var - rtarray = initRtArray[cint](3) - rawMatches = rtarray.getRawData - res = pcre.exec(pattern.h, nil, s, len(s).cint, start.cint, 0'i32, - cast[ptr cint](rawMatches), 3) - if res < 0'i32: return (int(res), 0) - return (int(rawMatches[0]), int(rawMatches[1]-1)) - -proc matchOrFind(s: string, pattern: Regex, start, flags: cint): cint = - var - rtarray = initRtArray[cint](3) - rawMatches = rtarray.getRawData - result = pcre.exec(pattern.h, pattern.e, s, len(s).cint, start, flags, - cast[ptr cint](rawMatches), 3) - if result >= 0'i32: - result = rawMatches[1] - rawMatches[0] + ## returns the starting position of `pattern` in `s`. If it does not + ## match, ``(-1,0)`` is returned. + execute nre.find: + return (-1, 0) + returnBounds() proc matchLen*(s: string, pattern: Regex, matches: var openArray[string], - start = 0): int = + start = 0): int = ## the same as ``match``, but it returns the length of the match, ## if there is no match, -1 is returned. Note that a match length ## of zero can happen. - return matchOrFind(s, pattern, matches, start.cint, pcre.ANCHORED) + execute nre.match: + return -1 + stringCaptures() + returnLength() proc matchLen*(s: string, pattern: Regex, start = 0): int = ## the same as ``match``, but it returns the length of the match, ## if there is no match, -1 is returned. Note that a match length ## of zero can happen. - return matchOrFind(s, pattern, start.cint, pcre.ANCHORED) + execute nre.match: + return -1 + returnLength() proc match*(s: string, pattern: Regex, start = 0): bool = ## returns ``true`` if ``s[start..]`` matches the ``pattern``. - result = matchLen(s, pattern, start) != -1 + execute nre.match: + return false + return true proc match*(s: string, pattern: Regex, matches: var openArray[string], start = 0): bool = @@ -188,65 +160,45 @@ proc match*(s: string, pattern: Regex, matches: var openArray[string], ## the captured substrings in the array ``matches``. If it does not ## match, nothing is written into ``matches`` and ``false`` is ## returned. - result = matchLen(s, pattern, matches, start) != -1 + execute nre.match: + return false + stringCaptures() + return true proc find*(s: string, pattern: Regex, matches: var openArray[string], start = 0): int = ## returns the starting position of ``pattern`` in ``s`` and the captured ## substrings in the array ``matches``. If it does not match, nothing ## is written into ``matches`` and -1 is returned. - var - rtarray = initRtArray[cint]((matches.len+1)*3) - rawMatches = rtarray.getRawData - res = pcre.exec(pattern.h, pattern.e, s, len(s).cint, start.cint, 0'i32, - cast[ptr cint](rawMatches), (matches.len+1).cint*3) - if res < 0'i32: return res - for i in 1..int(res)-1: - var a = rawMatches[i * 2] - var b = rawMatches[i * 2 + 1] - if a >= 0'i32: matches[i-1] = substr(s, int(a), int(b)-1) - else: matches[i-1] = nil - return rawMatches[0] + execute nre.find: + return -1 + stringCaptures() + return m.matchBounds.a proc find*(s: string, pattern: Regex, start = 0): int = ## returns the starting position of ``pattern`` in ``s``. If it does not ## match, -1 is returned. - var - rtarray = initRtArray[cint](3) - rawMatches = rtarray.getRawData - res = pcre.exec(pattern.h, nil, s, len(s).cint, start.cint, 0'i32, - cast[ptr cint](rawMatches), 3) - if res < 0'i32: return res - return rawMatches[0] + execute nre.find: + return -1 + return m.matchBounds.a iterator findAll*(s: string, pattern: Regex, start = 0): string = ## Yields all matching *substrings* of `s` that match `pattern`. ## ## Note that since this is an iterator you should not modify the string you ## are iterating over: bad things could happen. - var - i = int32(start) - rtarray = initRtArray[cint](3) - rawMatches = rtarray.getRawData - while true: - let res = pcre.exec(pattern.h, pattern.e, s, len(s).cint, i, 0'i32, - cast[ptr cint](rawMatches), 3) - if res < 0'i32: break - let a = rawMatches[0] - let b = rawMatches[1] - if a == b and a == i: break - yield substr(s, int(a), int(b)-1) - i = b + for m in nre.findIter(s, pattern, start): + yield $m proc findAll*(s: string, pattern: Regex, start = 0): seq[string] = ## returns all matching *substrings* of `s` that match `pattern`. ## If it does not match, @[] is returned. - accumulateResult(findAll(s, pattern, start)) + accumulateResult findAll(s, pattern, start) when not defined(nimhygiene): {.pragma: inject.} -template `=~` *(s: string, pattern: Regex): expr = +template `=~`*(s: string, pattern: Regex, start = 0): expr = ## This calls ``match`` with an implicit declared ``matches`` array that ## can be used in the scope of the ``=~`` call: ## @@ -264,10 +216,11 @@ template `=~` *(s: string, pattern: Regex): expr = ## else: ## echo("syntax error") ## - bind MaxSubpatterns - when not declaredInScope(matches): - var matches {.inject.}: array[MaxSubpatterns, string] - match(s, pattern, matches) + let mm = nre.match(s, pattern, start) + var matches {.inject.}: seq[string] + if mm.isSome: + matches = mm.unsafeGet().captures.toSeq() + mm.isSome # ------------------------- more string handling ------------------------------ @@ -286,8 +239,9 @@ proc startsWith*(s: string, prefix: Regex): bool = proc endsWith*(s: string, suffix: Regex): bool = ## returns true if `s` ends with the pattern `prefix` - for i in 0 .. s.len-1: - if matchLen(s, suffix, i) == s.len - i: return true + for i in 0 .. s.high: + if matchLen(s, suffix, i) == s.len - i: + return true proc replace*(s: string, sub: Regex, by = ""): string = ## Replaces `sub` in `s` by the string `by`. Captures cannot be @@ -301,15 +255,7 @@ proc replace*(s: string, sub: Regex, by = ""): string = ## .. code-block:: nim ## ## "; " - result = "" - var prev = 0 - while true: - var match = findBounds(s, sub, prev) - if match.first < 0: break - add(result, substr(s, prev, match.first-1)) - add(result, by) - prev = match.last + 1 - add(result, substr(s, prev)) + return nre.replace(s, sub, by.replace("$", "$$")) proc replacef*(s: string, sub: Regex, by: string): string = ## Replaces `sub` in `s` by the string `by`. Captures can be accessed in `by` @@ -323,18 +269,7 @@ proc replacef*(s: string, sub: Regex, by: string): string = ## .. code-block:: nim ## ## "var1<-keykey; val2<-key2key2" - result = "" - var caps: array[MaxSubpatterns, string] - var prev = 0 - while true: - var match = findBounds(s, sub, caps, prev) - if match.first < 0: break - assert result != nil - assert s != nil - add(result, substr(s, prev, match.first-1)) - addf(result, by, caps) - prev = match.last + 1 - add(result, substr(s, prev)) + return nre.replace(s, sub, by) proc parallelReplace*(s: string, subs: openArray[ tuple[pattern: Regex, repl: string]]): string = @@ -342,19 +277,20 @@ proc parallelReplace*(s: string, subs: openArray[ ## applied in parallel. result = "" var i = 0 - var caps: array[MaxSubpatterns, string] while i < s.len: block searchSubs: - for j in 0..high(subs): - var x = matchLen(s, subs[j][0], caps, i) - if x > 0: - addf(result, subs[j][1], caps) - inc(i, x) - break searchSubs - add(result, s[i]) - inc(i) + for sub in subs: + let pattern = sub.pattern + let start = i + execute nre.match: + continue + result.addf sub.repl, m.captures.toSeq() + i += m.matchBounds.b - m.matchBounds.a + break searchSubs + result.add s[i] + inc i # copy the rest: - add(result, substr(s, i)) + result.add s.substr(i) proc transformFile*(infile, outfile: string, subs: openArray[tuple[pattern: Regex, repl: string]]) = @@ -377,67 +313,42 @@ iterator split*(s: string, sep: Regex): string = ## Results in: ## ## .. code-block:: nim - ## "" ## "this" ## "is" ## "an" ## "example" - ## "" ## - var - first = -1 - last = -1 - while last < len(s): - var x = matchLen(s, sep, last) - if x > 0: inc(last, x) - first = last - if x == 0: inc(last) - while last < len(s): - x = matchLen(s, sep, last) - if x >= 0: break - inc(last) - if first <= last: - yield substr(s, first, last-1) + for m in nre.split(s, sep): + yield m proc split*(s: string, sep: Regex): seq[string] = ## Splits the string `s` into substrings. - accumulateResult(split(s, sep)) + return nre.split(s, sep) proc escapeRe*(s: string): string = ## escapes `s` so that it is matched verbatim when used as a regular ## expression. - result = "" - for c in items(s): - case c - of 'a'..'z', 'A'..'Z', '0'..'9', '_': - result.add(c) - else: - result.add("\\x") - result.add(toHex(ord(c), 2)) + return nre.escapeRe(s) const ## common regular expressions - reIdentifier* {.deprecated.} = r"\b[a-zA-Z_]+[a-zA-Z_0-9]*\b" - ## describes an identifier - reNatural* {.deprecated.} = r"\b\d+\b" - ## describes a natural number - reInteger* {.deprecated.} = r"\b[-+]?\d+\b" - ## describes an integer - reHex* {.deprecated.} = r"\b0[xX][0-9a-fA-F]+\b" - ## describes a hexadecimal number - reBinary* {.deprecated.} = r"\b0[bB][01]+\b" - ## describes a binary number (example: 0b11101) - reOctal* {.deprecated.} = r"\b0[oO][0-7]+\b" - ## describes an octal number (example: 0o777) - reFloat* {.deprecated.} = r"\b[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?\b" + reIdentifier* = r"\b[a-zA-Z_]+[a-zA-Z_0-9]*\b" ## describes an identifier + reNatural* = r"\b\d+\b" ## describes a natural number + reInteger* = r"\b[-+]?\d+\b" ## describes an integer + reHex* = r"\b0[xX][0-9a-fA-F]+\b" ## describes a hexadecimal number + reBinary* = r"\b0[bB][01]+\b" ## describes a binary number (example: 0b11101) + reOctal* = r"\b0[oO][0-7]+\b" ## describes an octal number (example: 0o777) + reFloat* = r"\b[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?\b" ## describes a floating point number - reEmail* {.deprecated.} = r"\b[a-zA-Z0-9!#$%&'*+/=?^_`{|}~\-]+(?:\. &" & - r"[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@" & - r"(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+" & - r"(?:[a-zA-Z]{2}|com|org|net|gov|mil|biz|" & - r"info|mobi|name|aero|jobs|museum)\b" + reEmail* {.deprecated.} = + r"\b[a-zA-Z0-9!#$%&'*+/=?^_`{|}~\-]+(?:\. &" & + r"[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)" & + r"*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+" & + r"(?:[a-zA-Z]{2}|com|org|" & + r"net|gov|mil|biz|info|mobi|name|aero|jobs|museum)\b" ## describes a common email address - reURL* {.deprecated.} = r"\b(http(s)?|ftp|gopher|telnet|file|notes|ms-help)" & - r":((//)|(\\\\))+[\w\d:#@%/;$()~_?\+\-\=\\\.\&]*\b" + reURL* {.deprecated.} = + r"\b(http(s)?|ftp|gopher|telnet|file|notes|ms\-help):" & + r"((//)|(\\\\))+[\w\d:#@%/;$()~_?\+\-\=\\\.\&]*\b" ## describes an URL when isMainModule: @@ -455,7 +366,7 @@ when isMainModule: assert find("_____abc_______", re"abc") == 5 - var matches: array[6, string] + var matches: array[0..5, string] if match("abcdefg", re"c(d)ef(g)", matches, 2): assert matches[0] == "d" assert matches[1] == "g" @@ -464,8 +375,7 @@ when isMainModule: if "abc" =~ re"(a)bcxyz|(\w+)": assert matches[1] == "abc" - else: - assert false + else: assert false if "abc" =~ re"(cba)?.*": assert matches[0] == nil @@ -481,16 +391,9 @@ when isMainModule: assert("var1=key; var2=key2".replace(re"(\w+)=(\w+)", "$1<-$2$2") == "$1<-$2$2; $1<-$2$2") - var accum: seq[string] = @[] - for word in split("00232this02939is39an22example111", re"\d+"): - accum.add(word) + var accum: seq[string] = split("00232this02939is39an22example111", re"\d+") assert(accum == @["", "this", "is", "an", "example", ""]) - accum = @[] - for word in split("AAA : : BBB", re"\s*:\s*"): - accum.add(word) - assert(accum == @["AAA", "", "BBB"]) - for x in findAll("abcdef", re"^{.}", 3): assert x == "d" accum = @[] @@ -502,9 +405,10 @@ when isMainModule: assert("XYZ".match(re"^\d*") == true) block: - var matches: array[16, string] - if match("abcdefghijklmnop", re"(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)(m)(n)(o)(p)", matches): - for i in 0..matches.high: + var matches: array[0..15, string] + if match("abcdefghijklmnop", + re"(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)(m)(n)(o)(p)", matches): + for i in 0 .. matches.high: assert matches[i] == $chr(i + 'a'.ord) else: assert false From 15ef227c48417819fab86c86103565e2a324ad92 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Tue, 26 May 2015 19:48:58 -0400 Subject: [PATCH 0405/1263] Adjust re for nre's inclusive bounds --- lib/impure/re.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/impure/re.nim b/lib/impure/re.nim index a2689a45c..5ee6e7005 100644 --- a/lib/impure/re.nim +++ b/lib/impure/re.nim @@ -97,7 +97,7 @@ template returnBounds(): stmt {.immediate, dirty.} = return (m.matchBounds.a, Date: Tue, 26 May 2015 19:51:43 -0400 Subject: [PATCH 0406/1263] Deprecate re --- lib/impure/re.nim | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/impure/re.nim b/lib/impure/re.nim index 5ee6e7005..6aac9593b 100644 --- a/lib/impure/re.nim +++ b/lib/impure/re.nim @@ -29,7 +29,7 @@ import strutils import nre, options -type Regex = nre.Regex +type Regex* = nre.Regex const MaxSubpatterns* {.deprecated.} = 1000 @@ -48,7 +48,7 @@ type ## is raised if the pattern is no valid regular expression. -proc re*(s: string, flags = {reExtended, reStudy}): Regex = +proc re*(s: string, flags = {reExtended, reStudy}): Regex {.deprecated.} = ## Constructor of regular expressions. Note that Nim's ## extended raw string literals support this syntax ``re"[abc]"`` as ## a short form for ``re(r"[abc]")``. From 38064d043ae1475c7fe0db7123c9ab53d4d8ed9c Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Tue, 26 May 2015 19:53:32 -0400 Subject: [PATCH 0407/1263] Use stdlib's PCRE in nre --- lib/impure/nre.nim | 2 +- lib/impure/nre/private/pcre.nim | 442 -------------------------------- 2 files changed, 1 insertion(+), 443 deletions(-) delete mode 100644 lib/impure/nre/private/pcre.nim diff --git a/lib/impure/nre.nim b/lib/impure/nre.nim index a351fd8d3..3eb84bb1f 100644 --- a/lib/impure/nre.nim +++ b/lib/impure/nre.nim @@ -7,7 +7,7 @@ # -import nre.private.pcre as pcre +import pcre as pcre import nre.private.util import tables import unsigned diff --git a/lib/impure/nre/private/pcre.nim b/lib/impure/nre/private/pcre.nim deleted file mode 100644 index 83b0d5f79..000000000 --- a/lib/impure/nre/private/pcre.nim +++ /dev/null @@ -1,442 +0,0 @@ -const pcreHeader = "" -when not defined(pcreDll): - when hostOS == "windows": - const pcreDll = "pcre.dll" - elif hostOS == "macosx": - const pcreDll = "libpcre(.3|.1|).dylib" - else: - const pcreDll = "libpcre.so(.3|.1|)" - {.pragma: pcreImport, dynlib: pcreDll.} -else: - {.pragma: pcreImport, header: pcreHeader.} -{.deadCodeElim: on.} # Don't error unless unsupported features are used - -#************************************************ -# Perl-Compatible Regular Expressions * -#*********************************************** -# This is the public header file for the Pcre library, to be #included by -#applications that call the Pcre functions. -# -# Copyright (c) 1997-2014 University of Cambridge -# -#----------------------------------------------------------------------------- -#Redistribution and use in source and binary forms, with or without -#modification, are permitted provided that the following conditions are met: -# -# Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# -# Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# -# Neither the name of the University of Cambridge nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -#AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -#IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -#ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -#LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -#CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -#SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -#INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -#ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -#POSSIBILITY OF SUCH DAMAGE. -#----------------------------------------------------------------------------- -# -# The current Pcre version information. - - -const - MAJOR* = 8 - MINOR* = 36 - PRERELEASE* = true - DATE* = 2014 - 9 - 26 - -# When an application links to a Pcre DLL in Windows, the symbols that are -#imported have to be identified as such. When building PCRE, the appropriate -#export setting is defined in pcre_internal.h, which includes this file. So we -#don't change existing definitions of PCRE_EXP_DECL and PCRECPP_EXP_DECL. -# By default, we use the standard "extern" declarations. -# Have to include stdlib.h in order to ensure that size_t is defined; -#it is needed here for malloc. - -# Allow for C++ users -# Public options. Some are compile-time only, some are run-time only, and some -#are both. Most of the compile-time options are saved with the compiled regex so -#that they can be inspected during studying (and therefore JIT compiling). Note -#that pcre_study() has its own set of options. Originally, all the options -#defined here used distinct bits. However, almost all the bits in a 32-bit word -#are now used, so in order to conserve them, option bits that were previously -#only recognized at matching time (i.e. by pcre_exec() or pcre_dfa_exec()) may -#also be used for compile-time options that affect only compiling and are not -#relevant for studying or JIT compiling. -# -#Some options for pcre_compile() change its behaviour but do not affect the -#behaviour of the execution functions. Other options are passed through to the -#execution functions and affect their behaviour, with or without affecting the -#behaviour of pcre_compile(). -# -#Options that can be passed to pcre_compile() are tagged Cx below, with these -#variants: -# -#C1 Affects compile only -#C2 Does not affect compile; affects exec, dfa_exec -#C3 Affects compile, exec, dfa_exec -#C4 Affects compile, exec, dfa_exec, study -#C5 Affects compile, exec, study -# -#Options that can be set for pcre_exec() and/or pcre_dfa_exec() are flagged with -#E and D, respectively. They take precedence over C3, C4, and C5 settings passed -#from pcre_compile(). Those that are compatible with JIT execution are flagged -#with J. - -const - CASELESS* = 0x00000001 - MULTILINE* = 0x00000002 - DOTALL* = 0x00000004 - EXTENDED* = 0x00000008 - ANCHORED* = 0x00000010 - DOLLAR_ENDONLY* = 0x00000020 - EXTRA* = 0x00000040 - NOTBOL* = 0x00000080 - NOTEOL* = 0x00000100 - UNGREEDY* = 0x00000200 - NOTEMPTY* = 0x00000400 - UTF8* = 0x00000800 - UTF16* = 0x00000800 - UTF32* = 0x00000800 - NO_AUTO_CAPTURE* = 0x00001000 - NO_UTF8_CHECK* = 0x00002000 - NO_UTF16_CHECK* = 0x00002000 - NO_UTF32_CHECK* = 0x00002000 - AUTO_CALLOUT* = 0x00004000 - PARTIAL_SOFT* = 0x00008000 - PARTIAL* = 0x00008000 - -# This pair use the same bit. - -const - NEVER_UTF* = 0x00010000 - DFA_SHORTEST* = 0x00010000 - -# This pair use the same bit. - -const - NO_AUTO_POSSESS* = 0x00020000 - DFA_RESTART* = 0x00020000 - FIRSTLINE* = 0x00040000 - DUPNAMES* = 0x00080000 - NEWLINE_CR* = 0x00100000 - NEWLINE_LF* = 0x00200000 - NEWLINE_CRLF* = 0x00300000 - NEWLINE_ANY* = 0x00400000 - NEWLINE_ANYCRLF* = 0x00500000 - BSR_ANYCRLF* = 0x00800000 - BSR_UNICODE* = 0x01000000 - JAVASCRIPT_COMPAT* = 0x02000000 - NO_START_OPTIMIZE* = 0x04000000 - NO_START_OPTIMISE* = 0x04000000 - PARTIAL_HARD* = 0x08000000 - NOTEMPTY_ATSTART* = 0x10000000 - UCP* = 0x20000000 - -# Exec-time and get/set-time error codes - -const - ERROR_NOMATCH* = (- 1) - ERROR_NULL* = (- 2) - ERROR_BADOPTION* = (- 3) - ERROR_BADMAGIC* = (- 4) - ERROR_UNKNOWN_OPCODE* = (- 5) - ERROR_UNKNOWN_NODE* = (- 5) # For backward compatibility - ERROR_NOMEMORY* = (- 6) - ERROR_NOSUBSTRING* = (- 7) - ERROR_MATCHLIMIT* = (- 8) - ERROR_CALLOUT* = (- 9) # Never used by Pcre itself - ERROR_BADUTF8* = (- 10) # Same for 8/16/32 - ERROR_BADUTF16* = (- 10) # Same for 8/16/32 - ERROR_BADUTF32* = (- 10) # Same for 8/16/32 - ERROR_BADUTF8_OFFSET* = (- 11) # Same for 8/16 - ERROR_BADUTF16_OFFSET* = (- 11) # Same for 8/16 - ERROR_PARTIAL* = (- 12) - ERROR_BADPARTIAL* = (- 13) - ERROR_INTERNAL* = (- 14) - ERROR_BADCOUNT* = (- 15) - ERROR_DFA_UITEM* = (- 16) - ERROR_DFA_UCOND* = (- 17) - ERROR_DFA_UMLIMIT* = (- 18) - ERROR_DFA_WSSIZE* = (- 19) - ERROR_DFA_RECURSE* = (- 20) - ERROR_RECURSIONLIMIT* = (- 21) - ERROR_NULLWSLIMIT* = (- 22) # No longer actually used - ERROR_BADNEWLINE* = (- 23) - ERROR_BADOFFSET* = (- 24) - ERROR_SHORTUTF8* = (- 25) - ERROR_SHORTUTF16* = (- 25) # Same for 8/16 - ERROR_RECURSELOOP* = (- 26) - ERROR_JIT_STACKLIMIT* = (- 27) - ERROR_BADMODE* = (- 28) - ERROR_BADENDIANNESS* = (- 29) - ERROR_DFA_BADRESTART* = (- 30) - ERROR_JIT_BADOPTION* = (- 31) - ERROR_BADLENGTH* = (- 32) - ERROR_UNSET* = (- 33) - -# Specific error codes for UTF-8 validity checks - -const - UTF8_ERR0* = 0 - UTF8_ERR1* = 1 - UTF8_ERR2* = 2 - UTF8_ERR3* = 3 - UTF8_ERR4* = 4 - UTF8_ERR5* = 5 - UTF8_ERR6* = 6 - UTF8_ERR7* = 7 - UTF8_ERR8* = 8 - UTF8_ERR9* = 9 - UTF8_ERR10* = 10 - UTF8_ERR11* = 11 - UTF8_ERR12* = 12 - UTF8_ERR13* = 13 - UTF8_ERR14* = 14 - UTF8_ERR15* = 15 - UTF8_ERR16* = 16 - UTF8_ERR17* = 17 - UTF8_ERR18* = 18 - UTF8_ERR19* = 19 - UTF8_ERR20* = 20 - UTF8_ERR21* = 21 - UTF8_ERR22* = 22 - -# Specific error codes for UTF-16 validity checks - -const - UTF16_ERR0* = 0 - UTF16_ERR1* = 1 - UTF16_ERR2* = 2 - UTF16_ERR3* = 3 - UTF16_ERR4* = 4 - -# Specific error codes for UTF-32 validity checks - -const - UTF32_ERR0* = 0 - UTF32_ERR1* = 1 - UTF32_ERR2* = 2 - UTF32_ERR3* = 3 - -# Request types for pcre_fullinfo() - -const - INFO_OPTIONS* = 0 - INFO_SIZE* = 1 - INFO_CAPTURECOUNT* = 2 - INFO_BACKREFMAX* = 3 - INFO_FIRSTBYTE* = 4 - INFO_FIRSTCHAR* = 4 - INFO_FIRSTTABLE* = 5 - INFO_LASTLITERAL* = 6 - INFO_NAMEENTRYSIZE* = 7 - INFO_NAMECOUNT* = 8 - INFO_NAMETABLE* = 9 - INFO_STUDYSIZE* = 10 - INFO_DEFAULT_TABLES* = 11 - INFO_OKPARTIAL* = 12 - INFO_JCHANGED* = 13 - INFO_HASCRORLF* = 14 - INFO_MINLENGTH* = 15 - INFO_JIT* = 16 - INFO_JITSIZE* = 17 - INFO_MAXLOOKBEHIND* = 18 - INFO_FIRSTCHARACTER* = 19 - INFO_FIRSTCHARACTERFLAGS* = 20 - INFO_REQUIREDCHAR* = 21 - INFO_REQUIREDCHARFLAGS* = 22 - INFO_MATCHLIMIT* = 23 - INFO_RECURSIONLIMIT* = 24 - INFO_MATCH_EMPTY* = 25 - -# Request types for pcre_config(). Do not re-arrange, in order to remain -#compatible. - -const - CONFIG_UTF8* = 0 - CONFIG_NEWLINE* = 1 - CONFIG_LINK_SIZE* = 2 - CONFIG_POSIX_MALLOC_THRESHOLD* = 3 - CONFIG_MATCH_LIMIT* = 4 - CONFIG_STACKRECURSE* = 5 - CONFIG_UNICODE_PROPERTIES* = 6 - CONFIG_MATCH_LIMIT_RECURSION* = 7 - CONFIG_BSR* = 8 - CONFIG_JIT* = 9 - CONFIG_UTF16* = 10 - CONFIG_JITTARGET* = 11 - CONFIG_UTF32* = 12 - CONFIG_PARENS_LIMIT* = 13 - -# Request types for pcre_study(). Do not re-arrange, in order to remain -#compatible. - -const - STUDY_JIT_COMPILE* = 0x00000001 - STUDY_JIT_PARTIAL_SOFT_COMPILE* = 0x00000002 - STUDY_JIT_PARTIAL_HARD_COMPILE* = 0x00000004 - STUDY_EXTRA_NEEDED* = 0x00000008 - -# Bit flags for the pcre[16|32]_extra structure. Do not re-arrange or redefine -#these bits, just add new ones on the end, in order to remain compatible. - -const - EXTRA_STUDY_DATA* = 0x00000001 - EXTRA_MATCH_LIMIT* = 0x00000002 - EXTRA_CALLOUT_DATA* = 0x00000004 - EXTRA_TABLES* = 0x00000008 - EXTRA_MATCH_LIMIT_RECURSION* = 0x00000010 - EXTRA_MARK* = 0x00000020 - EXTRA_EXECUTABLE_JIT* = 0x00000040 - -# Types - -type - Pcre* = object - Pcre16* = object - Pcre32* = object - jit_stack* = object - jit_stack16* = object - jit_stack32* = object - -# The structure for passing additional data to pcre_exec(). This is defined in -#such as way as to be extensible. Always add new fields at the end, in order to -#remain compatible. - -type - ExtraData* = object - flags*: culong # Bits for which fields are set - study_data*: pointer # Opaque data from pcre_study() - match_limit*: culong # Maximum number of calls to match() - callout_data*: pointer # Data passed back in callouts - tables*: ptr cuchar # Pointer to character tables - match_limit_recursion*: culong # Max - # recursive calls to match() - mark*: ptr ptr cuchar # For passing back a mark pointer - executable_jit*: pointer # Contains a pointer to a compiled jit code - -# The structure for passing out data via the pcre_callout_function. We use a -#structure so that new fields can be added on the end in future versions, -#without changing the API of the function, thereby allowing old clients to work -#without modification. - -type - callout_block* = object - version*: cint # Identifies version of block - # ------------------------ Version 0 ------------------------------- - callout_number*: cint # Number compiled into pattern - offset_vector*: ptr cint # The offset vector - subject*: cstring # The subject being matched - subject_length*: cint # The length of the subject - start_match*: cint # Offset to start of this match attempt - current_position*: cint # Where we currently are in the subject - capture_top*: cint # Max current capture - capture_last*: cint # Most recently closed capture - callout_data*: pointer # Data passed in with the call - # ------------------- Added for Version 1 - # -------------------------- - pattern_position*: cint # Offset to next item in the pattern - next_item_length*: cint # Length of next item in the pattern - # ------------------- Added for Version 2 - # -------------------------- - mark*: ptr cuchar # Pointer to current mark or NULL - # - # ------------------------------------------------------------------ -# Indirection for store get and free functions. These can be set to -#alternative malloc/free functions if required. Special ones are used in the -#non-recursive case for "frames". There is also an optional callout function -#that is triggered by the (?) regex item. For Virtual Pascal, these definitions -#have to take another form. - -proc malloc*(a2: csize): pointer {.cdecl, importc: "pcre_malloc", pcreImport.} -proc free*(a2: pointer) {.cdecl, importc: "pcre_free", pcreImport.} -proc stack_malloc*(a2: csize): pointer {.cdecl, importc: "pcre_stack_malloc", pcreImport.} -proc stack_free*(a2: pointer) {.cdecl, importc: "pcre_free", pcreImport.} -proc callout*(a2: ptr callout_block): cint {.cdecl, importc: "pcre_callout", pcreImport.} -proc stack_guard*(): cint {.cdecl, importc: "pcre_stack_guard", pcreImport.} - -# User defined callback which provides a stack just before the match starts. - -type - jit_callback* = proc (a2: pointer): ptr jit_stack {.cdecl.} - -# Exported Pcre functions - -proc compile*(a2: cstring; a3: cint; a4: ptr cstring; a5: ptr cint; - a6: ptr cuchar): ptr Pcre {.cdecl, importc: "pcre_compile", - pcreImport.} -proc compile2*(a2: cstring; a3: cint; a4: ptr cint; a5: ptr cstring; - a6: ptr cint; a7: ptr cuchar): ptr Pcre {.cdecl, - importc: "pcre_compile2", pcreImport.} -proc config*(a2: cint; a3: pointer): cint {.cdecl, importc: "pcre_config", - pcreImport.} -proc copy_named_substring*(a2: ptr Pcre; a3: cstring; a4: ptr cint; a5: cint; - a6: cstring; a7: cstring; a8: cint): cint {.cdecl, - importc: "pcre_copy_named_substring", pcreImport.} -proc copy_substring*(a2: cstring; a3: ptr cint; a4: cint; a5: cint; a6: cstring; - a7: cint): cint {.cdecl, importc: "pcre_copy_substring", - pcreImport.} -proc dfa_exec*(a2: ptr Pcre; a3: ptr ExtraData; a4: cstring; a5: cint; a6: cint; - a7: cint; a8: ptr cint; a9: cint; a10: ptr cint; a11: cint): cint {. - cdecl, importc: "pcre_dfa_exec", pcreImport.} -proc exec*(a2: ptr Pcre; a3: ptr ExtraData; a4: cstring; a5: cint; a6: cint; a7: cint; - a8: ptr cint; a9: cint): cint {.cdecl, importc: "pcre_exec", - pcreImport.} -proc jit_exec*(a2: ptr Pcre; a3: ptr ExtraData; a4: cstring; a5: cint; a6: cint; - a7: cint; a8: ptr cint; a9: cint; a10: ptr jit_stack): cint {. - cdecl, importc: "pcre_jit_exec", pcreImport.} -proc free_substring*(a2: cstring) {.cdecl, importc: "pcre_free_substring", - pcreImport.} -proc free_substring_list*(a2: ptr cstring) {.cdecl, - importc: "pcre_free_substring_list", pcreImport.} -proc fullinfo*(a2: ptr Pcre; a3: ptr ExtraData; a4: cint; a5: pointer): cint {. - cdecl, importc: "pcre_fullinfo", pcreImport.} -proc get_named_substring*(a2: ptr Pcre; a3: cstring; a4: ptr cint; a5: cint; - a6: cstring; a7: cstringArray): cint {.cdecl, - importc: "pcre_get_named_substring", pcreImport.} -proc get_stringnumber*(a2: ptr Pcre; a3: cstring): cint {.cdecl, - importc: "pcre_get_stringnumber", pcreImport.} -proc get_stringtable_entries*(a2: ptr Pcre; a3: cstring; a4: cstringArray; - a5: cstringArray): cint {.cdecl, - importc: "pcre_get_stringtable_entries", pcreImport.} -proc get_substring*(a2: cstring; a3: ptr cint; a4: cint; a5: cint; - a6: cstringArray): cint {.cdecl, - importc: "pcre_get_substring", pcreImport.} -proc get_substring_list*(a2: cstring; a3: ptr cint; a4: cint; - a5: ptr cstringArray): cint {.cdecl, - importc: "pcre_get_substring_list", pcreImport.} -proc maketables*(): ptr cuchar {.cdecl, importc: "pcre_maketables", - pcreImport.} -proc refcount*(a2: ptr Pcre; a3: cint): cint {.cdecl, importc: "pcre_refcount", - pcreImport.} -proc study*(a2: ptr Pcre; a3: cint; a4: ptr cstring): ptr ExtraData {.cdecl, - importc: "pcre_study", pcreImport.} -proc free_study*(a2: ptr ExtraData) {.cdecl, importc: "pcre_free_study", - pcreImport.} -proc version*(): cstring {.cdecl, importc: "pcre_version", pcreImport.} -# Utility functions for byte order swaps. - -proc pattern_to_host_byte_order*(a2: ptr Pcre; a3: ptr ExtraData; a4: ptr cuchar): cint {. - cdecl, importc: "pcre_pattern_to_host_byte_order", pcreImport.} -# JIT compiler related functions. - -proc jit_stack_alloc*(a2: cint; a3: cint): ptr jit_stack {.cdecl, - importc: "pcre_jit_stack_alloc", pcreImport.} -proc jit_stack_free*(a2: ptr jit_stack) {.cdecl, importc: "pcre_jit_stack_free", - pcreImport.} -proc assign_jit_stack*(a2: ptr ExtraData; a3: jit_callback; a4: pointer) {.cdecl, - importc: "pcre_assign_jit_stack", pcreImport.} -proc jit_free_unused_memory*() {.cdecl, importc: "pcre_jit_free_unused_memory", - pcreImport.} From 4fbd95549dd65b98e14f180ea9f70a72074200f1 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Tue, 26 May 2015 20:00:31 -0400 Subject: [PATCH 0408/1263] Clean up nre imports --- lib/impure/nre.nim | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/lib/impure/nre.nim b/lib/impure/nre.nim index 3eb84bb1f..c58cf2501 100644 --- a/lib/impure/nre.nim +++ b/lib/impure/nre.nim @@ -7,11 +7,10 @@ # -import pcre as pcre +from pcre import nil import nre.private.util import tables import unsigned -from future import lc, `[]` from strutils import toLower, `%` from math import ceil import options From a707f8de65fb9ece674b926a529044fc206e43b3 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Tue, 26 May 2015 20:02:51 -0400 Subject: [PATCH 0409/1263] Edit re and nre doc comments --- lib/impure/nre.nim | 19 ------------------- lib/impure/re.nim | 2 +- 2 files changed, 1 insertion(+), 20 deletions(-) diff --git a/lib/impure/nre.nim b/lib/impure/nre.nim index c58cf2501..5a6050ac2 100644 --- a/lib/impure/nre.nim +++ b/lib/impure/nre.nim @@ -22,25 +22,6 @@ from unicode import runeLenAt ## ## A regular expression library for Nim using PCRE to do the hard work. ## -## Why? -## ---- -## -## The `re.nim `__ module that -## `Nim `__ provides in its standard library is -## inadequate: -## -## - It provides only a limited number of captures, while the underling -## library (PCRE) allows an unlimited number. -## -## - Instead of having one proc that returns both the bounds and -## substring, it has one for the bounds and another for the substring. -## -## - If the splitting regex is empty (``""``), then it returns the input -## string instead of following `Perl `__, -## `Javascript `__, and -## `Java `__'s precedent of returning a list -## of each character (``"123".split(re"") == @["1", "2", "3"]``). -## ## Licencing ## --------- ## diff --git a/lib/impure/re.nim b/lib/impure/re.nim index 6aac9593b..0ff6e9555 100644 --- a/lib/impure/re.nim +++ b/lib/impure/re.nim @@ -8,7 +8,7 @@ # distribution, for details about the copyright. # -## Regular expression support for Nim. +## Regular expression support for Nim. Deprecated in favor of nre. ## ## **Note:** The 're' proc defaults to the **extended regular expression ## syntax** which lets you use whitespace freely to make your regexes readable. From ca81749f2ab3af9d3d86b865c2e4dfa116f7aad3 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Tue, 26 May 2015 20:07:16 -0400 Subject: [PATCH 0410/1263] Rename RegexException according to NEP1 --- lib/impure/nre.nim | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/lib/impure/nre.nim b/lib/impure/nre.nim index 5a6050ac2..6363f278a 100644 --- a/lib/impure/nre.nim +++ b/lib/impure/nre.nim @@ -191,22 +191,22 @@ type Captures* = distinct RegexMatch CaptureBounds* = distinct RegexMatch - RegexException* = ref object of Exception + RegexError* = ref object of Exception - RegexInternalError* = ref object of RegexException + RegexInternalError* = ref object of RegexError ## Internal error in the module, this probably means that there is a bug - InvalidUnicodeError* = ref object of RegexException + InvalidUnicodeError* = ref object of RegexError ## Thrown when matching fails due to invalid unicode in strings pos*: int ## the location of the invalid unicode in bytes - SyntaxError* = ref object of RegexException + SyntaxError* = ref object of RegexError ## Thrown when there is a syntax error in the ## regular expression string passed in pos*: int ## the location of the syntax error in bytes pattern*: string ## the pattern that caused the problem - StudyError* = ref object of RegexException + StudyError* = ref object of RegexError ## Thrown when studying the regular expression failes ## for whatever reason. The message contains the error ## code. From 3bbbb1a6825c5bcff2d4dfc41c1cebff83751498 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Tue, 26 May 2015 20:29:12 -0400 Subject: [PATCH 0411/1263] Fix potential code bloat --- lib/impure/nre.nim | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/lib/impure/nre.nim b/lib/impure/nre.nim index 6363f278a..bfe2ad33a 100644 --- a/lib/impure/nre.nim +++ b/lib/impure/nre.nim @@ -305,10 +305,11 @@ proc toTable*(pattern: CaptureBounds, default = none(Slice[int])): template itemsImpl(cond: bool): stmt {.immediate, dirty.} = for i in 0 .. Date: Tue, 26 May 2015 20:49:49 -0400 Subject: [PATCH 0412/1263] Fix ambiguous character literal --- lib/impure/nre.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/impure/nre.nim b/lib/impure/nre.nim index bfe2ad33a..6f92b0d71 100644 --- a/lib/impure/nre.nim +++ b/lib/impure/nre.nim @@ -534,7 +534,7 @@ iterator findIter*(str: string, pattern: Regex, start = 0, endpos = int.high): R break if matchesCrLf and offset < (str.len - 1) and - str[offset] == '\r' and str[offset + 1] == '\l': + str[offset] == '\r' and str[offset + 1] == '\L': # if PCRE treats CrLf as newline, skip both at the same time offset += 2 elif unicode: From ab1b1c9251f6d787cf78eefd2c3d1d391f5287fd Mon Sep 17 00:00:00 2001 From: apense Date: Mon, 8 Jun 2015 16:03:57 -0400 Subject: [PATCH 0413/1263] Note about deprecation in generics.txt I'm happy to change the wording or anything. It does seem like an important thing to mention, though. It might be better not to even mention typeless procs so as not to encourage bad behavior. --- doc/manual/generics.txt | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/doc/manual/generics.txt b/doc/manual/generics.txt index 2736f88fb..f82cad531 100644 --- a/doc/manual/generics.txt +++ b/doc/manual/generics.txt @@ -164,11 +164,13 @@ Alternatively, the ``distinct`` type modifier can be applied to the type class to allow each param matching the type class to bind to a different type. If a proc param doesn't have a type specified, Nim will use the -``distinct auto`` type class (also known as ``any``): +``distinct auto`` type class (also known as ``any``). Note this behavior is +deprecated for procs; templates, however, support them: .. code-block:: nim # allow any combination of param types - proc concat(a, b): string = $a & $b + proc concat(a, b): string = $a & $b # deprecated + proc concat(a, b: any): string = $a & $b # preferred Procs written with the implicitly generic style will often need to refer to the type parameters of the matched generic type. They can be easily accessed using From c4009c61820190c188f6bcf7469754b3c40201e5 Mon Sep 17 00:00:00 2001 From: Dominik Picheta Date: Mon, 8 Jun 2015 23:10:50 +0100 Subject: [PATCH 0414/1263] Fixes #2884 Haven't tested this patch but should work. --- lib/pure/httpclient.nim | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/lib/pure/httpclient.nim b/lib/pure/httpclient.nim index e083d44ea..6a2913713 100644 --- a/lib/pure/httpclient.nim +++ b/lib/pure/httpclient.nim @@ -569,7 +569,7 @@ proc downloadFile*(url: string, outputFilename: string, fileError("Unable to open file") proc generateHeaders(r: Uri, httpMethod: string, - headers: StringTableRef): string = + headers: StringTableRef, body: string): string = # TODO: Use this in the blocking HttpClient once it supports proxies. result = substr(httpMethod, len("http")) # TODO: Proxies @@ -582,6 +582,8 @@ proc generateHeaders(r: Uri, httpMethod: string, add(result, "Host: " & r.hostname & "\c\L") add(result, "Connection: Keep-Alive\c\L") + if body.len > 0 and not headers.hasKey("Content-Length"): + add(result, "Content-Length: " & $body.len & "\c\L") for key, val in headers: add(result, key & ": " & val & "\c\L") @@ -786,7 +788,7 @@ proc request*(client: AsyncHttpClient, url: string, httpMethod: string, if not client.headers.hasKey("user-agent") and client.userAgent != "": client.headers["User-Agent"] = client.userAgent - var headers = generateHeaders(r, $httpMethod, client.headers) + var headers = generateHeaders(r, $httpMethod, client.headers, body) await client.socket.send(headers) if body != "": From 0ee1672d69272aa75cf9be15dede34773a4fa487 Mon Sep 17 00:00:00 2001 From: apense Date: Mon, 8 Jun 2015 19:48:57 -0400 Subject: [PATCH 0415/1263] Updated whitespace ranges Ranges sourced from _. Wikipedia also uses these ranges on its information page _. 0xfeff isn't included in the list, but it is a no-break space, so I guess it makes sense. 0x200b is actually a format character, but it is a zero-width space. To fit Unicode, both 0x200b and 0xfeff would be removed. --- lib/pure/unicode.nim | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/lib/pure/unicode.nim b/lib/pure/unicode.nim index 5fd3c2418..4446eaa0c 100644 --- a/lib/pure/unicode.nim +++ b/lib/pure/unicode.nim @@ -372,11 +372,17 @@ const 0xfe74] # spaceRanges = [ - 0x0009, 0x000a, # tab and newline + 0x0009, 0x000d, # tab and newline 0x0020, 0x0020, # space + 0x0085, 0x0085, # next line 0x00a0, 0x00a0, # - 0x2000, 0x200b, # - + 0x1680, 0x1680, # Ogham space mark + 0x2000, 0x200b, # en dash .. zero-width space + 0x200e, 0x200f, # LTR mark .. RTL mark (pattern whitespace) 0x2028, 0x2029, # - 0x3000, 0x3000, # + 0x202f, 0x202f, # narrow no-break space + 0x205f, 0x205f, # medium mathematical space + 0x3000, 0x3000, # ideographic space 0xfeff, 0xfeff] # toupperRanges = [ From 02ddbae8f659b2c3bf3f05a924bccbc3c15c3137 Mon Sep 17 00:00:00 2001 From: Stefan Talpalaru Date: Tue, 9 Jun 2015 17:58:54 +0200 Subject: [PATCH 0416/1263] fix growObj() with strings --- lib/system/sysstr.nim | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/system/sysstr.nim b/lib/system/sysstr.nim index d44552902..6e3c8722d 100644 --- a/lib/system/sysstr.nim +++ b/lib/system/sysstr.nim @@ -50,12 +50,14 @@ proc rawNewStringNoInit(space: int): NimString {.compilerProc.} = if s < 7: s = 7 result = allocStrNoInit(sizeof(TGenericSeq) + s + 1) result.reserved = s + result.elemSize = 1 proc rawNewString(space: int): NimString {.compilerProc.} = var s = space if s < 7: s = 7 result = allocStr(sizeof(TGenericSeq) + s + 1) result.reserved = s + result.elemSize = 1 proc mnewString(len: int): NimString {.compilerProc.} = result = rawNewString(len) From d152ccc1e2ae07cff4685a9d1b8146297fffba38 Mon Sep 17 00:00:00 2001 From: Spencer Stirling Date: Tue, 9 Jun 2015 11:59:26 -0600 Subject: [PATCH 0417/1263] fixed threadpool and atomics to work with Visual Studio 32 and 64 bit --- lib/pure/concurrency/threadpool.nim | 2 +- lib/system/atomics.nim | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/pure/concurrency/threadpool.nim b/lib/pure/concurrency/threadpool.nim index 749a2fa2d..43a9dea11 100644 --- a/lib/pure/concurrency/threadpool.nim +++ b/lib/pure/concurrency/threadpool.nim @@ -290,7 +290,7 @@ proc slave(w: ptr Worker) {.thread.} = readyWorker = w signal(gSomeReady) await(w.taskArrived) - assert(not w.ready) + #assert(not w.ready) # doesn't work with Visual Studio w.f(w, w.data) if w.q.len != 0: w.cleanFlowVars if w.shutdown: diff --git a/lib/system/atomics.nim b/lib/system/atomics.nim index 0b16b63bf..158fe91bc 100644 --- a/lib/system/atomics.nim +++ b/lib/system/atomics.nim @@ -191,11 +191,11 @@ proc atomicDec*(memLoc: var int, x: int = 1): int = result = memLoc when defined(windows) and not someGcc: - proc interlockedCompareExchange(p: pointer; exchange, comparand: int32): int32 + proc interlockedCompareExchange(p: pointer; exchange, comparand: int): int {.importc: "InterlockedCompareExchange", header: "", cdecl.} proc cas*[T: bool|int|ptr](p: ptr T; oldValue, newValue: T): bool = - interlockedCompareExchange(p, newValue.int32, oldValue.int32) != 0 + interlockedCompareExchange(p, cast[int](newValue), cast[int](oldValue)) != 0 # XXX fix for 64 bit build else: # this is valid for GCC and Intel C++ From 87429071330cc8516dab2612b45689a510528f6a Mon Sep 17 00:00:00 2001 From: Adam Strzelecki Date: Thu, 4 Jun 2015 00:38:49 +0200 Subject: [PATCH 0418/1263] db: InstantRow and instantRows It is drop-in replacement for Row and fastRows, however instantRows returns a handle, not seq[string], so no Nim string is created until [] operator is called on the given handle. Also there is a len() proc returning number of columns in the handle. In some situations, when we iterate through many rows, but later we just read few columns this solution will be quicker than converting all column to Nim seq[string] on each iteration. --- lib/impure/db_mysql.nim | 27 +++++++++++++++++++++++++++ lib/impure/db_postgres.nim | 21 +++++++++++++++++++++ lib/impure/db_sqlite.nim | 24 +++++++++++++++++++++++- 3 files changed, 71 insertions(+), 1 deletion(-) diff --git a/lib/impure/db_mysql.nim b/lib/impure/db_mysql.nim index 619c2a656..7c2901efd 100644 --- a/lib/impure/db_mysql.nim +++ b/lib/impure/db_mysql.nim @@ -16,6 +16,9 @@ type DbConn* = PMySQL ## encapsulates a database connection Row* = seq[string] ## a row of a dataset. NULL database values will be ## transformed always to the empty string. + InstantRow* = tuple[row: cstringArray, len: int] ## a handle that can be + ## used to get a row's + ## column text on demand EDb* = object of IOError ## exception that is raised if a database error occurs SqlQuery* = distinct string ## an SQL query string @@ -127,6 +130,30 @@ iterator fastRows*(db: DbConn, query: SqlQuery, yield result properFreeResult(sqlres, row) +iterator instantRows*(db: DbConn, query: SqlQuery, + args: varargs[string, `$`]): InstantRow + {.tags: [FReadDb].} = + ## same as fastRows but returns a handle that can be used to get column text + ## on demand using []. Returned handle is valid only within interator body. + rawExec(db, query, args) + var sqlres = mysql.useResult(db) + if sqlres != nil: + let L = int(mysql.numFields(sqlres)) + var row: cstringArray + while true: + row = mysql.fetchRow(sqlres) + if row == nil: break + yield (row: row, len: L) + properFreeResult(sqlres, row) + +proc `[]`*(row: InstantRow, col: int): string {.inline.} = + ## returns text for given column of the row + $row.row[col] + +proc len*(row: InstantRow): int {.inline.} = + ## returns number of columns in the row + row.len + proc getRow*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]): Row {.tags: [FReadDB].} = ## retrieves a single row. If the query doesn't return any rows, this proc diff --git a/lib/impure/db_postgres.nim b/lib/impure/db_postgres.nim index 774cb1510..c88e660f4 100644 --- a/lib/impure/db_postgres.nim +++ b/lib/impure/db_postgres.nim @@ -16,6 +16,9 @@ type DbConn* = PPGconn ## encapsulates a database connection Row* = seq[string] ## a row of a dataset. NULL database values will be ## transformed always to the empty string. + InstantRow* = tuple[res: PPGresult, line: int32] ## a handle that can be + ## used to get a row's + ## column text on demand EDb* = object of IOError ## exception that is raised if a database error occurs SqlQuery* = distinct string ## an SQL query string @@ -159,6 +162,24 @@ iterator fastRows*(db: DbConn, stmtName: SqlPrepared, yield result pqClear(res) +iterator instantRows*(db: DbConn, query: SqlQuery, + args: varargs[string, `$`]): InstantRow + {.tags: [FReadDb].} = + ## same as fastRows but returns a handle that can be used to get column text + ## on demand using []. Returned handle is valid only within interator body. + var res = setupQuery(db, query, args) + for i in 0..pqNtuples(res)-1: + yield (res: res, line: i) + pqClear(res) + +proc `[]`*(row: InstantRow, col: int32): string {.inline.} = + ## returns text for given column of the row + $pqgetvalue(row.res, row.line, col) + +proc len*(row: InstantRow): int32 {.inline.} = + ## returns number of columns in the row + pqNfields(row.res) + proc getRow*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]): Row {.tags: [FReadDB].} = ## retrieves a single row. If the query doesn't return any rows, this proc diff --git a/lib/impure/db_sqlite.nim b/lib/impure/db_sqlite.nim index 47e7c1900..1a037becc 100644 --- a/lib/impure/db_sqlite.nim +++ b/lib/impure/db_sqlite.nim @@ -16,6 +16,8 @@ type DbConn* = PSqlite3 ## encapsulates a database connection Row* = seq[string] ## a row of a dataset. NULL database values will be ## transformed always to the empty string. + InstantRow* = Pstmt ## a handle that can be used to get a row's column + ## text on demand EDb* = object of IOError ## exception that is raised if a database error occurs SqlQuery* = distinct string ## an SQL query string @@ -109,6 +111,24 @@ iterator fastRows*(db: DbConn, query: SqlQuery, yield result if finalize(stmt) != SQLITE_OK: dbError(db) +iterator instantRows*(db: DbConn, query: SqlQuery, + args: varargs[string, `$`]): InstantRow + {.tags: [FReadDb].} = + ## same as fastRows but returns a handle that can be used to get column text + ## on demand using []. Returned handle is valid only within interator body. + var stmt = setupQuery(db, query, args) + while step(stmt) == SQLITE_ROW: + yield stmt + if finalize(stmt) != SQLITE_OK: dbError(db) + +proc `[]`*(row: InstantRow, col: int32): string {.inline.} = + ## returns text for given column of the row + $column_text(row, col) + +proc len*(row: InstantRow): int32 {.inline.} = + ## returns number of columns in the row + column_count(row) + proc getRow*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]): Row {.tags: [FReadDb].} = ## retrieves a single row. If the query doesn't return any rows, this proc @@ -216,5 +236,7 @@ when not defined(testing) and isMainModule: #db.query("insert into tbl1 values('goodbye', 20)") for r in db.rows(sql"select * from tbl1", []): echo(r[0], r[1]) - + for r in db.instantRows(sql"select * from tbl1", []): + echo(r[0], r[1]) + db_sqlite.close(db) From 3d266433a75449d76b589aba6edaf488d5a8c921 Mon Sep 17 00:00:00 2001 From: Adam Strzelecki Date: Tue, 9 Jun 2015 22:16:43 +0200 Subject: [PATCH 0419/1263] securehash: Keep module name consistent 1. All other modules don't use underscore, why this should be different? 2. Wrap some imports to 80 column --- compiler/ast.nim | 2 +- compiler/cgen.nim | 2 +- compiler/extccomp.nim | 3 ++- compiler/jsgen.nim | 2 +- compiler/modules.nim | 2 +- compiler/rodread.nim | 2 +- compiler/rodwrite.nim | 3 ++- compiler/{secure_hash.nim => securehash.nim} | 0 8 files changed, 9 insertions(+), 7 deletions(-) rename compiler/{secure_hash.nim => securehash.nim} (100%) diff --git a/compiler/ast.nim b/compiler/ast.nim index dc190fd7f..36d29e06a 100644 --- a/compiler/ast.nim +++ b/compiler/ast.nim @@ -10,7 +10,7 @@ # abstract syntax tree + symbol table import - msgs, hashes, nversion, options, strutils, secure_hash, ropes, idents, lists, + msgs, hashes, nversion, options, strutils, securehash, ropes, idents, lists, intsets, idgen type diff --git a/compiler/cgen.nim b/compiler/cgen.nim index 03aa0b4d4..390150cf7 100644 --- a/compiler/cgen.nim +++ b/compiler/cgen.nim @@ -11,7 +11,7 @@ import ast, astalgo, hashes, trees, platform, magicsys, extccomp, options, intsets, - nversion, nimsets, msgs, secure_hash, bitsets, idents, lists, types, + nversion, nimsets, msgs, securehash, bitsets, idents, lists, types, ccgutils, os, ropes, math, passes, rodread, wordrecg, treetab, cgmeth, condsyms, rodutils, renderer, idgen, cgendata, ccgmerge, semfold, aliases, lowerings, semparallel diff --git a/compiler/extccomp.nim b/compiler/extccomp.nim index 2ddb98aba..38427b367 100644 --- a/compiler/extccomp.nim +++ b/compiler/extccomp.nim @@ -13,7 +13,8 @@ # nim files. import - lists, ropes, os, strutils, osproc, platform, condsyms, options, msgs, secure_hash + lists, ropes, os, strutils, osproc, platform, condsyms, options, msgs, + securehash type TSystemCC* = enum diff --git a/compiler/jsgen.nim b/compiler/jsgen.nim index 346a52cfc..1f82306d2 100644 --- a/compiler/jsgen.nim +++ b/compiler/jsgen.nim @@ -31,7 +31,7 @@ implements the required case distinction. import ast, astalgo, strutils, hashes, trees, platform, magicsys, extccomp, options, - nversion, nimsets, msgs, secure_hash, bitsets, idents, lists, types, os, + nversion, nimsets, msgs, securehash, bitsets, idents, lists, types, os, times, ropes, math, passes, ccgutils, wordrecg, renderer, rodread, rodutils, intsets, cgmeth, lowerings diff --git a/compiler/modules.nim b/compiler/modules.nim index 0573b91f8..6cb14c091 100644 --- a/compiler/modules.nim +++ b/compiler/modules.nim @@ -10,7 +10,7 @@ ## implements the module handling import - ast, astalgo, magicsys, secure_hash, rodread, msgs, cgendata, sigmatch, options, + ast, astalgo, magicsys, securehash, rodread, msgs, cgendata, sigmatch, options, idents, os, lexer, idgen, passes, syntaxes, llstream type diff --git a/compiler/rodread.nim b/compiler/rodread.nim index 27cb96ca1..dad7d111e 100644 --- a/compiler/rodread.nim +++ b/compiler/rodread.nim @@ -90,7 +90,7 @@ import os, options, strutils, nversion, ast, astalgo, msgs, platform, condsyms, - ropes, idents, secure_hash, idgen, types, rodutils, memfiles + ropes, idents, securehash, idgen, types, rodutils, memfiles type TReasonForRecompile* = enum ## all the reasons that can trigger recompilation diff --git a/compiler/rodwrite.nim b/compiler/rodwrite.nim index 3454b9ade..737387597 100644 --- a/compiler/rodwrite.nim +++ b/compiler/rodwrite.nim @@ -13,7 +13,8 @@ import intsets, os, options, strutils, nversion, ast, astalgo, msgs, platform, - condsyms, ropes, idents, secure_hash, rodread, passes, importer, idgen, rodutils + condsyms, ropes, idents, securehash, rodread, passes, importer, idgen, + rodutils # implementation diff --git a/compiler/secure_hash.nim b/compiler/securehash.nim similarity index 100% rename from compiler/secure_hash.nim rename to compiler/securehash.nim From eccc2f87e9dfa7e849e027bef857a390de3e9bae Mon Sep 17 00:00:00 2001 From: Adam Strzelecki Date: Tue, 9 Jun 2015 22:15:08 +0200 Subject: [PATCH 0420/1263] securehash: remove unused emptySecureHash --- compiler/securehash.nim | 8 -------- 1 file changed, 8 deletions(-) diff --git a/compiler/securehash.nim b/compiler/securehash.nim index 3383f23a2..12950f137 100644 --- a/compiler/securehash.nim +++ b/compiler/securehash.nim @@ -16,14 +16,6 @@ type SHA1Digest = array[0 .. sha_digest_size-1, uint8] SecureHash* = distinct SHA1Digest -const emptySecureHash = SecureHash([ - 0u8, 0, 0, 0, - 0, 0, 0, 0, - 0, 0, 0, 0, - 0, 0, 0, 0, - 0, 0, 0, 0, -]) - proc sha1(src: string) : SHA1Digest proc secureHash*(str: string): SecureHash = SecureHash(sha1(str)) From 54c863d6ae36faa9ba14fa2a5c34ea38d4be6efe Mon Sep 17 00:00:00 2001 From: Adam Strzelecki Date: Tue, 9 Jun 2015 22:15:51 +0200 Subject: [PATCH 0421/1263] securehash: sha_digest_size is not following style https://github.com/Araq/Nim/wiki/Style-Guide-for-Nim-Code --- compiler/securehash.nim | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/compiler/securehash.nim b/compiler/securehash.nim index 12950f137..ad15c2e8f 100644 --- a/compiler/securehash.nim +++ b/compiler/securehash.nim @@ -10,10 +10,10 @@ import strutils, unsigned -const sha_digest_size = 20 +const SHA1DigestSize = 20 type - SHA1Digest = array[0 .. sha_digest_size-1, uint8] + SHA1Digest = array[0 .. SHA1DigestSize-1, uint8] SecureHash* = distinct SHA1Digest proc sha1(src: string) : SHA1Digest @@ -26,7 +26,7 @@ proc `$`*(self: SecureHash): string = result.add(toHex(int(v), 2)) proc parseSecureHash*(hash: string): SecureHash = - for i in 0.. Date: Tue, 9 Jun 2015 16:21:33 -0400 Subject: [PATCH 0422/1263] Removed unnecessary template `-|` only used in the compiler for negative indexing --- lib/system.nim | 3 --- 1 file changed, 3 deletions(-) diff --git a/lib/system.nim b/lib/system.nim index 90587f306..949443dd9 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -2859,9 +2859,6 @@ proc `/`*(x, y: int): float {.inline, noSideEffect.} = ## integer division that results in a float. result = toFloat(x) / toFloat(y) -template `-|`*(b, s: expr): expr = - (if b >= 0: b else: s.len + b) - template spliceImpl(s, a, L, b: expr): stmt {.immediate.} = # make room for additional elements or cut: var slen = s.len From d4d5f95808f0db59dd46a6793fd35d8a32f693fb Mon Sep 17 00:00:00 2001 From: Ryan Gonzalez Date: Tue, 9 Jun 2015 15:21:33 -0500 Subject: [PATCH 0423/1263] Remove unnecessary import --- compiler/extccomp.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/extccomp.nim b/compiler/extccomp.nim index ea69f6c25..186a3884d 100644 --- a/compiler/extccomp.nim +++ b/compiler/extccomp.nim @@ -13,7 +13,7 @@ # nim files. import - lists, ropes, os, strutils, osproc, platform, condsyms, options, msgs, crc, terminal + lists, ropes, os, strutils, osproc, platform, condsyms, options, msgs, crc type TSystemCC* = enum From 867b38496b234df22ab34ef15344f848278b096d Mon Sep 17 00:00:00 2001 From: apense Date: Tue, 9 Jun 2015 16:24:13 -0400 Subject: [PATCH 0424/1263] Moved negative indexing operator here Only used here (not in standard library) --- compiler/ast.nim | 3 +++ 1 file changed, 3 insertions(+) diff --git a/compiler/ast.nim b/compiler/ast.nim index dc190fd7f..f48003797 100644 --- a/compiler/ast.nim +++ b/compiler/ast.nim @@ -948,6 +948,9 @@ proc add*(father, son: PNode) = proc `[]`*(n: PNode, i: int): PNode {.inline.} = result = n.sons[i] +template `-|`*(b, s: expr): expr = + (if b >= 0: b else: s.len + b) + # son access operators with support for negative indices template `{}`*(n: PNode, i: int): expr = n[i -| n] template `{}=`*(n: PNode, i: int, s: PNode): stmt = From 4e14c0ad9fc790a8a8d22ddcd2a28ed90322c4e7 Mon Sep 17 00:00:00 2001 From: Adam Strzelecki Date: Tue, 9 Jun 2015 22:55:29 +0200 Subject: [PATCH 0425/1263] securehash: SHA1 -> Sha1 according to style guide --- compiler/securehash.nim | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/compiler/securehash.nim b/compiler/securehash.nim index ad15c2e8f..8ac6acb0e 100644 --- a/compiler/securehash.nim +++ b/compiler/securehash.nim @@ -10,28 +10,28 @@ import strutils, unsigned -const SHA1DigestSize = 20 +const Sha1DigestSize = 20 type - SHA1Digest = array[0 .. SHA1DigestSize-1, uint8] - SecureHash* = distinct SHA1Digest + Sha1Digest = array[0 .. Sha1DigestSize-1, uint8] + SecureHash* = distinct Sha1Digest -proc sha1(src: string) : SHA1Digest +proc sha1(src: string) : Sha1Digest proc secureHash*(str: string): SecureHash = SecureHash(sha1(str)) proc secureHashFile*(filename: string): SecureHash = secureHash(readFile(filename)) proc `$`*(self: SecureHash): string = result = "" - for v in SHA1Digest(self): + for v in Sha1Digest(self): result.add(toHex(int(v), 2)) proc parseSecureHash*(hash: string): SecureHash = - for i in 0.. Date: Tue, 9 Jun 2015 22:25:31 -0300 Subject: [PATCH 0426/1263] Allow to set position at end of stream --- lib/pure/streams.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/pure/streams.nim b/lib/pure/streams.nim index e6004b5d0..50b5c219a 100644 --- a/lib/pure/streams.nim +++ b/lib/pure/streams.nim @@ -279,7 +279,7 @@ proc ssAtEnd(s: Stream): bool = proc ssSetPosition(s: Stream, pos: int) = var s = StringStream(s) - s.pos = clamp(pos, 0, s.data.high) + s.pos = clamp(pos, 0, s.data.len) proc ssGetPosition(s: Stream): int = var s = StringStream(s) From 372a5d3cbb782db117cde582589bf3514b36a814 Mon Sep 17 00:00:00 2001 From: rku Date: Mon, 4 May 2015 11:36:31 +0300 Subject: [PATCH 0427/1263] Removed magics: mAddI64, mSubI64, mMulI64, mDivI64, mModI64 Author: rku --- compiler/ast.nim | 8 ++++---- compiler/ccgexprs.nim | 5 ----- compiler/guards.nim | 10 +++++----- compiler/jsgen.nim | 10 ---------- compiler/semfold.nim | 20 ++++++++++---------- compiler/vmgen.nim | 10 +++++----- lib/system.nim | 10 +++++----- 7 files changed, 29 insertions(+), 44 deletions(-) diff --git a/compiler/ast.nim b/compiler/ast.nim index dc190fd7f..10c0ec56d 100644 --- a/compiler/ast.nim +++ b/compiler/ast.nim @@ -539,8 +539,8 @@ type mIncl, mExcl, mCard, mChr, mGCref, mGCunref, - mAddI, mSubI, mMulI, mDivI, mModI, mAddI64, mSubI64, mMulI64, - mDivI64, mModI64, mSucc, mPred, + mAddI, mSubI, mMulI, mDivI, mModI, + mSucc, mPred, mAddF64, mSubF64, mMulF64, mDivF64, mShrI, mShlI, mBitandI, mBitorI, mBitxorI, mMinI, mMaxI, @@ -594,8 +594,8 @@ const mPred, mInc, mDec, mOrd, mLengthOpenArray, mLengthStr, mLengthArray, mLengthSeq, mXLenStr, mXLenSeq, mIncl, mExcl, mCard, mChr, - mAddI, mSubI, mMulI, mDivI, mModI, mAddI64, mSubI64, mMulI64, - mDivI64, mModI64, mAddF64, mSubF64, mMulF64, mDivF64, + mAddI, mSubI, mMulI, mDivI, mModI, + mAddF64, mSubF64, mMulF64, mDivF64, mShrI, mShlI, mBitandI, mBitorI, mBitxorI, mMinI, mMaxI, mShrI64, mShlI64, mBitandI64, mBitorI64, mBitxorI64, mMinF64, mMaxF64, mAddU, mSubU, mMulU, diff --git a/compiler/ccgexprs.nim b/compiler/ccgexprs.nim index 64902c3fc..722d1b020 100644 --- a/compiler/ccgexprs.nim +++ b/compiler/ccgexprs.nim @@ -503,13 +503,8 @@ proc binaryArithOverflow(p: BProc, e: PNode, d: var TLoc, m: TMagic) = "$# = #addInt($#, $#);$n", "$# = #subInt($#, $#);$n", "$# = #mulInt($#, $#);$n", "$# = #divInt($#, $#);$n", "$# = #modInt($#, $#);$n", - "$# = #addInt64($#, $#);$n", "$# = #subInt64($#, $#);$n", - "$# = #mulInt64($#, $#);$n", "$# = #divInt64($#, $#);$n", - "$# = #modInt64($#, $#);$n", "$# = #addInt($#, $#);$n", "$# = #subInt($#, $#);$n"] opr: array[mAddI..mPred, string] = [ - "($#)($# + $#)", "($#)($# - $#)", "($#)($# * $#)", - "($#)($# / $#)", "($#)($# % $#)", "($#)($# + $#)", "($#)($# - $#)", "($#)($# * $#)", "($#)($# / $#)", "($#)($# % $#)", "($#)($# + $#)", "($#)($# - $#)"] diff --git a/compiler/guards.nim b/compiler/guards.nim index df2c1dd75..45413ee62 100644 --- a/compiler/guards.nim +++ b/compiler/guards.nim @@ -30,11 +30,11 @@ const someHigh = {mHigh} # we don't list unsigned here because wrap around semantics suck for # proving anything: - someAdd = {mAddI, mAddI64, mAddF64, mSucc} - someSub = {mSubI, mSubI64, mSubF64, mPred} - someMul = {mMulI, mMulI64, mMulF64} - someDiv = {mDivI, mDivI64, mDivF64} - someMod = {mModI, mModI64} + someAdd = {mAddI, mAddF64, mSucc} + someSub = {mSubI, mSubF64, mPred} + someMul = {mMulI, mMulF64} + someDiv = {mDivI, mDivF64} + someMod = {mModI} someMax = {mMaxI, mMaxF64} someMin = {mMinI, mMinF64} diff --git a/compiler/jsgen.nim b/compiler/jsgen.nim index 346a52cfc..0339f0b30 100644 --- a/compiler/jsgen.nim +++ b/compiler/jsgen.nim @@ -258,11 +258,6 @@ const # magic checked op; magic unchecked op; checked op; unchecked op ["mulInt", "", "mulInt($1, $2)", "($1 * $2)"], # MulI ["divInt", "", "divInt($1, $2)", "Math.floor($1 / $2)"], # DivI ["modInt", "", "modInt($1, $2)", "Math.floor($1 % $2)"], # ModI - ["addInt64", "", "addInt64($1, $2)", "($1 + $2)"], # AddI64 - ["subInt64", "", "subInt64($1, $2)", "($1 - $2)"], # SubI64 - ["mulInt64", "", "mulInt64($1, $2)", "($1 * $2)"], # MulI64 - ["divInt64", "", "divInt64($1, $2)", "Math.floor($1 / $2)"], # DivI64 - ["modInt64", "", "modInt64($1, $2)", "Math.floor($1 % $2)"], # ModI64 ["addInt", "", "addInt($1, $2)", "($1 + $2)"], # Succ ["subInt", "", "subInt($1, $2)", "($1 - $2)"], # Pred ["", "", "($1 + $2)", "($1 + $2)"], # AddF64 @@ -357,11 +352,6 @@ const # magic checked op; magic unchecked op; checked op; unchecked op ["mulInt", "", "mulInt($1, $2)", "($1 * $2)"], # MulI ["divInt", "", "divInt($1, $2)", "Math.floor($1 / $2)"], # DivI ["modInt", "", "modInt($1, $2)", "Math.floor($1 % $2)"], # ModI - ["addInt64", "", "addInt64($1, $2)", "($1 + $2)"], # AddI64 - ["subInt64", "", "subInt64($1, $2)", "($1 - $2)"], # SubI64 - ["mulInt64", "", "mulInt64($1, $2)", "($1 * $2)"], # MulI64 - ["divInt64", "", "divInt64($1, $2)", "Math.floor($1 / $2)"], # DivI64 - ["modInt64", "", "modInt64($1, $2)", "Math.floor($1 % $2)"], # ModI64 ["addInt", "", "addInt($1, $2)", "($1 + $2)"], # Succ ["subInt", "", "subInt($1, $2)", "($1 - $2)"], # Pred ["", "", "($1 + $2)", "($1 + $2)"], # AddF64 diff --git a/compiler/semfold.nim b/compiler/semfold.nim index da24005c2..2b8aaccaa 100644 --- a/compiler/semfold.nim +++ b/compiler/semfold.nim @@ -200,11 +200,11 @@ proc getIntervalType*(m: TMagic, n: PNode): PType = if isIntRange(a) and isIntLit(b): result = makeRange(a, pickMinInt(n.sons[1]) |-| pickMinInt(n.sons[2]), pickMaxInt(n.sons[1]) |-| pickMaxInt(n.sons[2])) - of mAddI, mAddI64, mAddU: + of mAddI, mAddU: commutativeOp(`|+|`) - of mMulI, mMulI64, mMulU: + of mMulI, mMulU: commutativeOp(`|*|`) - of mSubI, mSubI64, mSubU: + of mSubI, mSubU: binaryOp(`|-|`) of mBitandI, mBitandI64: # since uint64 is still not even valid for 'range' (since it's no ordinal @@ -225,7 +225,7 @@ proc getIntervalType*(m: TMagic, n: PNode): PType = result = makeRange(a.typ, 0, b.intVal-1) else: result = makeRange(a.typ, b.intVal+1, 0) - of mModI, mModI64: + of mModI: # so ... if you ever wondered about modulo's signedness; this defines it: let a = n.sons[1] let b = n.sons[2] @@ -234,7 +234,7 @@ proc getIntervalType*(m: TMagic, n: PNode): PType = result = makeRange(a.typ, -(b.intVal-1), b.intVal-1) else: result = makeRange(a.typ, b.intVal+1, -(b.intVal+1)) - of mDivI, mDivI64, mDivU: + of mDivI, mDivU: binaryOp(`|div|`) of mMinI: commutativeOp(min) @@ -310,9 +310,9 @@ proc evalOp(m: TMagic, n, a, b, c: PNode): PNode = of mUnaryLt: result = newIntNodeT(getOrdValue(a) - 1, n) of mSucc: result = newIntNodeT(getOrdValue(a) + getInt(b), n) of mPred: result = newIntNodeT(getOrdValue(a) - getInt(b), n) - of mAddI, mAddI64: result = newIntNodeT(getInt(a) + getInt(b), n) - of mSubI, mSubI64: result = newIntNodeT(getInt(a) - getInt(b), n) - of mMulI, mMulI64: result = newIntNodeT(getInt(a) * getInt(b), n) + of mAddI: result = newIntNodeT(getInt(a) + getInt(b), n) + of mSubI: result = newIntNodeT(getInt(a) - getInt(b), n) + of mMulI: result = newIntNodeT(getInt(a) * getInt(b), n) of mMinI: if getInt(a) > getInt(b): result = newIntNodeT(getInt(b), n) else: result = newIntNodeT(getInt(a), n) @@ -335,11 +335,11 @@ proc evalOp(m: TMagic, n, a, b, c: PNode): PNode = of tyInt64, tyInt, tyUInt..tyUInt64: result = newIntNodeT(`shr`(getInt(a), getInt(b)), n) else: internalError(n.info, "constant folding for shr") - of mDivI, mDivI64: + of mDivI: let y = getInt(b) if y != 0: result = newIntNodeT(getInt(a) div y, n) - of mModI, mModI64: + of mModI: let y = getInt(b) if y != 0: result = newIntNodeT(getInt(a) mod y, n) diff --git a/compiler/vmgen.nim b/compiler/vmgen.nim index 0743a4502..5b3ef3c0b 100644 --- a/compiler/vmgen.nim +++ b/compiler/vmgen.nim @@ -710,9 +710,9 @@ proc genMagic(c: PCtx; n: PNode; dest: var TDest; m: TMagic) = if dest < 0: dest = c.getTemp(n.typ) c.gABI(n, opcSubImmInt, dest, tmp, 1) c.freeTemp(tmp) - of mPred, mSubI, mSubI64: + of mPred, mSubI: c.genAddSubInt(n, dest, opcSubInt) - of mSucc, mAddI, mAddI64: + of mSucc, mAddI: c.genAddSubInt(n, dest, opcAddInt) of mInc, mDec: unused(n, dest) @@ -759,9 +759,9 @@ proc genMagic(c: PCtx; n: PNode; dest: var TDest; m: TMagic) = c.freeTemp(d) c.freeTemp(tmp) of mCard: genCard(c, n, dest) - of mMulI, mMulI64: genBinaryABCnarrow(c, n, dest, opcMulInt) - of mDivI, mDivI64: genBinaryABCnarrow(c, n, dest, opcDivInt) - of mModI, mModI64: genBinaryABCnarrow(c, n, dest, opcModInt) + of mMulI: genBinaryABCnarrow(c, n, dest, opcMulInt) + of mDivI: genBinaryABCnarrow(c, n, dest, opcDivInt) + of mModI: genBinaryABCnarrow(c, n, dest, opcModInt) of mAddF64: genBinaryABC(c, n, dest, opcAddFloat) of mSubF64: genBinaryABC(c, n, dest, opcSubFloat) of mMulF64: genBinaryABC(c, n, dest, opcMulFloat) diff --git a/lib/system.nim b/lib/system.nim index 90587f306..a8e521d68 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -684,28 +684,28 @@ proc `+` *(x, y: int): int {.magic: "AddI", noSideEffect.} proc `+` *(x, y: int8): int8 {.magic: "AddI", noSideEffect.} proc `+` *(x, y: int16): int16 {.magic: "AddI", noSideEffect.} proc `+` *(x, y: int32): int32 {.magic: "AddI", noSideEffect.} -proc `+` *(x, y: int64): int64 {.magic: "AddI64", noSideEffect.} +proc `+` *(x, y: int64): int64 {.magic: "AddI", noSideEffect.} ## Binary `+` operator for an integer. proc `-` *(x, y: int): int {.magic: "SubI", noSideEffect.} proc `-` *(x, y: int8): int8 {.magic: "SubI", noSideEffect.} proc `-` *(x, y: int16): int16 {.magic: "SubI", noSideEffect.} proc `-` *(x, y: int32): int32 {.magic: "SubI", noSideEffect.} -proc `-` *(x, y: int64): int64 {.magic: "SubI64", noSideEffect.} +proc `-` *(x, y: int64): int64 {.magic: "SubI", noSideEffect.} ## Binary `-` operator for an integer. proc `*` *(x, y: int): int {.magic: "MulI", noSideEffect.} proc `*` *(x, y: int8): int8 {.magic: "MulI", noSideEffect.} proc `*` *(x, y: int16): int16 {.magic: "MulI", noSideEffect.} proc `*` *(x, y: int32): int32 {.magic: "MulI", noSideEffect.} -proc `*` *(x, y: int64): int64 {.magic: "MulI64", noSideEffect.} +proc `*` *(x, y: int64): int64 {.magic: "MulI", noSideEffect.} ## Binary `*` operator for an integer. proc `div` *(x, y: int): int {.magic: "DivI", noSideEffect.} proc `div` *(x, y: int8): int8 {.magic: "DivI", noSideEffect.} proc `div` *(x, y: int16): int16 {.magic: "DivI", noSideEffect.} proc `div` *(x, y: int32): int32 {.magic: "DivI", noSideEffect.} -proc `div` *(x, y: int64): int64 {.magic: "DivI64", noSideEffect.} +proc `div` *(x, y: int64): int64 {.magic: "DivI", noSideEffect.} ## computes the integer division. This is roughly the same as ## ``floor(x/y)``. ## @@ -718,7 +718,7 @@ proc `mod` *(x, y: int): int {.magic: "ModI", noSideEffect.} proc `mod` *(x, y: int8): int8 {.magic: "ModI", noSideEffect.} proc `mod` *(x, y: int16): int16 {.magic: "ModI", noSideEffect.} proc `mod` *(x, y: int32): int32 {.magic: "ModI", noSideEffect.} -proc `mod` *(x, y: int64): int64 {.magic: "ModI64", noSideEffect.} +proc `mod` *(x, y: int64): int64 {.magic: "ModI", noSideEffect.} ## computes the integer modulo operation. This is the same as ## ``x - (x div y) * y``. From 658dcd2a58d85e2e786007b2f60d42650cd3ddac Mon Sep 17 00:00:00 2001 From: rku Date: Mon, 4 May 2015 11:45:18 +0300 Subject: [PATCH 0428/1263] Removed magics: mShrI64, mShlI64, mBitandI64, mBitorI64, mBitxorI64 Author: rku --- compiler/ast.nim | 2 -- compiler/ccgexprs.nim | 5 ----- compiler/jsgen.nim | 10 ---------- compiler/semfold.nim | 16 ++++++++-------- compiler/vmgen.nim | 10 +++++----- lib/system.nim | 10 +++++----- 6 files changed, 18 insertions(+), 35 deletions(-) diff --git a/compiler/ast.nim b/compiler/ast.nim index 10c0ec56d..bd0d56b7a 100644 --- a/compiler/ast.nim +++ b/compiler/ast.nim @@ -544,7 +544,6 @@ type mAddF64, mSubF64, mMulF64, mDivF64, mShrI, mShlI, mBitandI, mBitorI, mBitxorI, mMinI, mMaxI, - mShrI64, mShlI64, mBitandI64, mBitorI64, mBitxorI64, mMinF64, mMaxF64, mAddU, mSubU, mMulU, mDivU, mModU, mEqI, mLeI, mLtI, @@ -597,7 +596,6 @@ const mAddI, mSubI, mMulI, mDivI, mModI, mAddF64, mSubF64, mMulF64, mDivF64, mShrI, mShlI, mBitandI, mBitorI, mBitxorI, mMinI, mMaxI, - mShrI64, mShlI64, mBitandI64, mBitorI64, mBitxorI64, mMinF64, mMaxF64, mAddU, mSubU, mMulU, mDivU, mModU, mEqI, mLeI, mLtI, diff --git a/compiler/ccgexprs.nim b/compiler/ccgexprs.nim index 722d1b020..c44af524d 100644 --- a/compiler/ccgexprs.nim +++ b/compiler/ccgexprs.nim @@ -556,11 +556,6 @@ proc binaryArith(p: BProc, e: PNode, d: var TLoc, op: TMagic) = "($4)($1 ^ $2)", # BitxorI "(($1 <= $2) ? $1 : $2)", # MinI "(($1 >= $2) ? $1 : $2)", # MaxI - "($4)((NU64)($1) >> (NU64)($2))", # ShrI64 - "($4)((NU64)($1) << (NU64)($2))", # ShlI64 - "($4)($1 & $2)", # BitandI64 - "($4)($1 | $2)", # BitorI64 - "($4)($1 ^ $2)", # BitxorI64 "(($1 <= $2) ? $1 : $2)", # MinF64 "(($1 >= $2) ? $1 : $2)", # MaxF64 "($4)((NU$3)($1) + (NU$3)($2))", # AddU diff --git a/compiler/jsgen.nim b/compiler/jsgen.nim index 0339f0b30..3874ce85c 100644 --- a/compiler/jsgen.nim +++ b/compiler/jsgen.nim @@ -271,11 +271,6 @@ const # magic checked op; magic unchecked op; checked op; unchecked op ["", "", "($1 ^ $2)", "($1 ^ $2)"], # BitxorI ["nimMin", "nimMin", "nimMin($1, $2)", "nimMin($1, $2)"], # MinI ["nimMax", "nimMax", "nimMax($1, $2)", "nimMax($1, $2)"], # MaxI - ["", "", "($1 >>> $2)", "($1 >>> $2)"], # ShrI64 - ["", "", "($1 << $2)", "($1 << $2)"], # ShlI64 - ["", "", "($1 & $2)", "($1 & $2)"], # BitandI64 - ["", "", "($1 | $2)", "($1 | $2)"], # BitorI64 - ["", "", "($1 ^ $2)", "($1 ^ $2)"], # BitxorI64 ["nimMin", "nimMin", "nimMin($1, $2)", "nimMin($1, $2)"], # MinF64 ["nimMax", "nimMax", "nimMax($1, $2)", "nimMax($1, $2)"], # MaxF64 ["addU", "addU", "addU($1, $2)", "addU($1, $2)"], # addU @@ -365,11 +360,6 @@ const # magic checked op; magic unchecked op; checked op; unchecked op ["", "", "($1 ^ $2)", "($1 ^ $2)"], # BitxorI ["nimMin", "nimMin", "nimMin($1, $2)", "nimMin($1, $2)"], # MinI ["nimMax", "nimMax", "nimMax($1, $2)", "nimMax($1, $2)"], # MaxI - ["", "", "($1 >>> $2)", "($1 >>> $2)"], # ShrI64 - ["", "", "($1 << $2)", "($1 << $2)"], # ShlI64 - ["", "", "($1 & $2)", "($1 & $2)"], # BitandI64 - ["", "", "($1 | $2)", "($1 | $2)"], # BitorI64 - ["", "", "($1 ^ $2)", "($1 ^ $2)"], # BitxorI64 ["nimMin", "nimMin", "nimMin($1, $2)", "nimMin($1, $2)"], # MinF64 ["nimMax", "nimMax", "nimMax($1, $2)", "nimMax($1, $2)"], # MaxF64 ["addU", "addU", "addU($1, $2)", "addU($1, $2)"], # addU diff --git a/compiler/semfold.nim b/compiler/semfold.nim index 2b8aaccaa..c2230a59e 100644 --- a/compiler/semfold.nim +++ b/compiler/semfold.nim @@ -206,7 +206,7 @@ proc getIntervalType*(m: TMagic, n: PNode): PType = commutativeOp(`|*|`) of mSubI, mSubU: binaryOp(`|-|`) - of mBitandI, mBitandI64: + of mBitandI: # since uint64 is still not even valid for 'range' (since it's no ordinal # yet), we exclude it from the list (see bug #1638) for now: var a = n.sons[1] @@ -243,8 +243,8 @@ proc getIntervalType*(m: TMagic, n: PNode): PType = else: discard discard """ - mShlI, mShlI64, - mShrI, mShrI64, mAddF64, mSubF64, mMulF64, mDivF64, mMaxF64, mMinF64 + mShlI, + mShrI, mAddF64, mSubF64, mMulF64, mDivF64, mMaxF64, mMinF64 """ proc evalIs(n, a: PNode): PNode = @@ -319,7 +319,7 @@ proc evalOp(m: TMagic, n, a, b, c: PNode): PNode = of mMaxI: if getInt(a) > getInt(b): result = newIntNodeT(getInt(a), n) else: result = newIntNodeT(getInt(b), n) - of mShlI, mShlI64: + of mShlI: case skipTypes(n.typ, abstractRange).kind of tyInt8: result = newIntNodeT(int8(getInt(a)) shl int8(getInt(b)), n) of tyInt16: result = newIntNodeT(int16(getInt(a)) shl int16(getInt(b)), n) @@ -327,7 +327,7 @@ proc evalOp(m: TMagic, n, a, b, c: PNode): PNode = of tyInt64, tyInt, tyUInt..tyUInt64: result = newIntNodeT(`shl`(getInt(a), getInt(b)), n) else: internalError(n.info, "constant folding for shl") - of mShrI, mShrI64: + of mShrI: case skipTypes(n.typ, abstractRange).kind of tyInt8: result = newIntNodeT(int8(getInt(a)) shr int8(getInt(b)), n) of tyInt16: result = newIntNodeT(int16(getInt(a)) shr int16(getInt(b)), n) @@ -375,9 +375,9 @@ proc evalOp(m: TMagic, n, a, b, c: PNode): PNode = result = newIntNodeT(ord(`<%`(getOrdValue(a), getOrdValue(b))), n) of mLeU, mLeU64: result = newIntNodeT(ord(`<=%`(getOrdValue(a), getOrdValue(b))), n) - of mBitandI, mBitandI64, mAnd: result = newIntNodeT(a.getInt and b.getInt, n) - of mBitorI, mBitorI64, mOr: result = newIntNodeT(getInt(a) or getInt(b), n) - of mBitxorI, mBitxorI64, mXor: result = newIntNodeT(a.getInt xor b.getInt, n) + of mBitandI, mAnd: result = newIntNodeT(a.getInt and b.getInt, n) + of mBitorI, mOr: result = newIntNodeT(getInt(a) or getInt(b), n) + of mBitxorI, mXor: result = newIntNodeT(a.getInt xor b.getInt, n) of mAddU: result = newIntNodeT(`+%`(getInt(a), getInt(b)), n) of mSubU: result = newIntNodeT(`-%`(getInt(a), getInt(b)), n) of mMulU: result = newIntNodeT(`*%`(getInt(a), getInt(b)), n) diff --git a/compiler/vmgen.nim b/compiler/vmgen.nim index 5b3ef3c0b..db25b84ce 100644 --- a/compiler/vmgen.nim +++ b/compiler/vmgen.nim @@ -766,11 +766,11 @@ proc genMagic(c: PCtx; n: PNode; dest: var TDest; m: TMagic) = of mSubF64: genBinaryABC(c, n, dest, opcSubFloat) of mMulF64: genBinaryABC(c, n, dest, opcMulFloat) of mDivF64: genBinaryABC(c, n, dest, opcDivFloat) - of mShrI, mShrI64: genBinaryABCnarrowU(c, n, dest, opcShrInt) - of mShlI, mShlI64: genBinaryABCnarrowU(c, n, dest, opcShlInt) - of mBitandI, mBitandI64: genBinaryABCnarrowU(c, n, dest, opcBitandInt) - of mBitorI, mBitorI64: genBinaryABCnarrowU(c, n, dest, opcBitorInt) - of mBitxorI, mBitxorI64: genBinaryABCnarrowU(c, n, dest, opcBitxorInt) + of mShrI: genBinaryABCnarrowU(c, n, dest, opcShrInt) + of mShlI: genBinaryABCnarrowU(c, n, dest, opcShlInt) + of mBitandI: genBinaryABCnarrowU(c, n, dest, opcBitandInt) + of mBitorI: genBinaryABCnarrowU(c, n, dest, opcBitorInt) + of mBitxorI: genBinaryABCnarrowU(c, n, dest, opcBitxorInt) of mAddU: genBinaryABCnarrowU(c, n, dest, opcAddu) of mSubU: genBinaryABCnarrowU(c, n, dest, opcSubu) of mMulU: genBinaryABCnarrowU(c, n, dest, opcMulu) diff --git a/lib/system.nim b/lib/system.nim index a8e521d68..fb9720b21 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -726,7 +726,7 @@ proc `shr` *(x, y: int): int {.magic: "ShrI", noSideEffect.} proc `shr` *(x, y: int8): int8 {.magic: "ShrI", noSideEffect.} proc `shr` *(x, y: int16): int16 {.magic: "ShrI", noSideEffect.} proc `shr` *(x, y: int32): int32 {.magic: "ShrI", noSideEffect.} -proc `shr` *(x, y: int64): int64 {.magic: "ShrI64", noSideEffect.} +proc `shr` *(x, y: int64): int64 {.magic: "ShrI", noSideEffect.} ## computes the `shift right` operation of `x` and `y`. ## ## .. code-block:: Nim @@ -738,28 +738,28 @@ proc `shl` *(x, y: int): int {.magic: "ShlI", noSideEffect.} proc `shl` *(x, y: int8): int8 {.magic: "ShlI", noSideEffect.} proc `shl` *(x, y: int16): int16 {.magic: "ShlI", noSideEffect.} proc `shl` *(x, y: int32): int32 {.magic: "ShlI", noSideEffect.} -proc `shl` *(x, y: int64): int64 {.magic: "ShlI64", noSideEffect.} +proc `shl` *(x, y: int64): int64 {.magic: "ShlI", noSideEffect.} ## computes the `shift left` operation of `x` and `y`. proc `and` *(x, y: int): int {.magic: "BitandI", noSideEffect.} proc `and` *(x, y: int8): int8 {.magic: "BitandI", noSideEffect.} proc `and` *(x, y: int16): int16 {.magic: "BitandI", noSideEffect.} proc `and` *(x, y: int32): int32 {.magic: "BitandI", noSideEffect.} -proc `and` *(x, y: int64): int64 {.magic: "BitandI64", noSideEffect.} +proc `and` *(x, y: int64): int64 {.magic: "BitandI", noSideEffect.} ## computes the `bitwise and` of numbers `x` and `y`. proc `or` *(x, y: int): int {.magic: "BitorI", noSideEffect.} proc `or` *(x, y: int8): int8 {.magic: "BitorI", noSideEffect.} proc `or` *(x, y: int16): int16 {.magic: "BitorI", noSideEffect.} proc `or` *(x, y: int32): int32 {.magic: "BitorI", noSideEffect.} -proc `or` *(x, y: int64): int64 {.magic: "BitorI64", noSideEffect.} +proc `or` *(x, y: int64): int64 {.magic: "BitorI", noSideEffect.} ## computes the `bitwise or` of numbers `x` and `y`. proc `xor` *(x, y: int): int {.magic: "BitxorI", noSideEffect.} proc `xor` *(x, y: int8): int8 {.magic: "BitxorI", noSideEffect.} proc `xor` *(x, y: int16): int16 {.magic: "BitxorI", noSideEffect.} proc `xor` *(x, y: int32): int32 {.magic: "BitxorI", noSideEffect.} -proc `xor` *(x, y: int64): int64 {.magic: "BitxorI64", noSideEffect.} +proc `xor` *(x, y: int64): int64 {.magic: "BitxorI", noSideEffect.} ## computes the `bitwise xor` of numbers `x` and `y`. proc `==` *(x, y: int): bool {.magic: "EqI", noSideEffect.} From 47114342c4b9a09214029f7e46e9f8679e274253 Mon Sep 17 00:00:00 2001 From: rku Date: Mon, 8 Jun 2015 14:16:42 +0300 Subject: [PATCH 0429/1263] Removed magics: mEqI64 mLtI64 mLeI64 --- compiler/ast.nim | 4 ++-- compiler/ccgexprs.nim | 3 --- compiler/forloops.nim | 6 +++--- compiler/guards.nim | 6 +++--- compiler/jsgen.nim | 6 ------ compiler/semfold.nim | 6 +++--- compiler/vmgen.nim | 6 +++--- lib/system.nim | 6 +++--- 8 files changed, 17 insertions(+), 26 deletions(-) diff --git a/compiler/ast.nim b/compiler/ast.nim index bd0d56b7a..1cf449eb8 100644 --- a/compiler/ast.nim +++ b/compiler/ast.nim @@ -547,7 +547,7 @@ type mMinF64, mMaxF64, mAddU, mSubU, mMulU, mDivU, mModU, mEqI, mLeI, mLtI, - mEqI64, mLeI64, mLtI64, mEqF64, mLeF64, mLtF64, + mEqF64, mLeF64, mLtF64, mLeU, mLtU, mLeU64, mLtU64, mEqEnum, mLeEnum, mLtEnum, mEqCh, mLeCh, mLtCh, mEqB, mLeB, mLtB, mEqRef, mEqUntracedRef, mLePtr, mLtPtr, mEqCString, mXor, mEqProc, mUnaryMinusI, @@ -599,7 +599,7 @@ const mMinF64, mMaxF64, mAddU, mSubU, mMulU, mDivU, mModU, mEqI, mLeI, mLtI, - mEqI64, mLeI64, mLtI64, mEqF64, mLeF64, mLtF64, + mEqF64, mLeF64, mLtF64, mLeU, mLtU, mLeU64, mLtU64, mEqEnum, mLeEnum, mLtEnum, mEqCh, mLeCh, mLtCh, mEqB, mLeB, mLtB, mEqRef, mEqProc, mEqUntracedRef, mLePtr, mLtPtr, mEqCString, mXor, mUnaryMinusI, diff --git a/compiler/ccgexprs.nim b/compiler/ccgexprs.nim index c44af524d..49c0d4176 100644 --- a/compiler/ccgexprs.nim +++ b/compiler/ccgexprs.nim @@ -566,9 +566,6 @@ proc binaryArith(p: BProc, e: PNode, d: var TLoc, op: TMagic) = "($1 == $2)", # EqI "($1 <= $2)", # LeI "($1 < $2)", # LtI - "($1 == $2)", # EqI64 - "($1 <= $2)", # LeI64 - "($1 < $2)", # LtI64 "($1 == $2)", # EqF64 "($1 <= $2)", # LeF64 "($1 < $2)", # LtF64 diff --git a/compiler/forloops.nim b/compiler/forloops.nim index efe000968..949b7d8c6 100644 --- a/compiler/forloops.nim +++ b/compiler/forloops.nim @@ -12,9 +12,9 @@ import ast, astalgo const - someCmp = {mEqI, mEqI64, mEqF64, mEqEnum, mEqCh, mEqB, mEqRef, mEqProc, - mEqUntracedRef, mLeI, mLeI64, mLeF64, mLeU, mLeU64, mLeEnum, - mLeCh, mLeB, mLePtr, mLtI, mLtI64, mLtF64, mLtU, mLtU64, mLtEnum, + someCmp = {mEqI, mEqF64, mEqEnum, mEqCh, mEqB, mEqRef, mEqProc, + mEqUntracedRef, mLeI, mLeF64, mLeU, mLeU64, mLeEnum, + mLeCh, mLeB, mLePtr, mLtI, mLtF64, mLtU, mLtU64, mLtEnum, mLtCh, mLtB, mLtPtr} proc isCounter(s: PSym): bool {.inline.} = diff --git a/compiler/guards.nim b/compiler/guards.nim index 45413ee62..bc802ae33 100644 --- a/compiler/guards.nim +++ b/compiler/guards.nim @@ -13,13 +13,13 @@ import ast, astalgo, msgs, magicsys, nimsets, trees, types, renderer, idents, saturate const - someEq = {mEqI, mEqI64, mEqF64, mEqEnum, mEqCh, mEqB, mEqRef, mEqProc, + someEq = {mEqI, mEqF64, mEqEnum, mEqCh, mEqB, mEqRef, mEqProc, mEqUntracedRef, mEqStr, mEqSet, mEqCString} # set excluded here as the semantics are vastly different: - someLe = {mLeI, mLeI64, mLeF64, mLeU, mLeU64, mLeEnum, + someLe = {mLeI, mLeF64, mLeU, mLeU64, mLeEnum, mLeCh, mLeB, mLePtr, mLeStr} - someLt = {mLtI, mLtI64, mLtF64, mLtU, mLtU64, mLtEnum, + someLt = {mLtI, mLtF64, mLtU, mLtU64, mLtEnum, mLtCh, mLtB, mLtPtr, mLtStr} someLen = {mLengthOpenArray, mLengthStr, mLengthArray, mLengthSeq, diff --git a/compiler/jsgen.nim b/compiler/jsgen.nim index 3874ce85c..55cbed7e8 100644 --- a/compiler/jsgen.nim +++ b/compiler/jsgen.nim @@ -281,9 +281,6 @@ const # magic checked op; magic unchecked op; checked op; unchecked op ["", "", "($1 == $2)", "($1 == $2)"], # EqI ["", "", "($1 <= $2)", "($1 <= $2)"], # LeI ["", "", "($1 < $2)", "($1 < $2)"], # LtI - ["", "", "($1 == $2)", "($1 == $2)"], # EqI64 - ["", "", "($1 <= $2)", "($1 <= $2)"], # LeI64 - ["", "", "($1 < $2)", "($1 < $2)"], # LtI64 ["", "", "($1 == $2)", "($1 == $2)"], # EqF64 ["", "", "($1 <= $2)", "($1 <= $2)"], # LeF64 ["", "", "($1 < $2)", "($1 < $2)"], # LtF64 @@ -370,9 +367,6 @@ const # magic checked op; magic unchecked op; checked op; unchecked op ["", "", "($1 == $2)", "($1 == $2)"], # EqI ["", "", "($1 <= $2)", "($1 <= $2)"], # LeI ["", "", "($1 < $2)", "($1 < $2)"], # LtI - ["", "", "($1 == $2)", "($1 == $2)"], # EqI64 - ["", "", "($1 <= $2)", "($1 <= $2)"], # LeI64 - ["", "", "($1 < $2)", "($1 < $2)"], # LtI64 ["", "", "($1 == $2)", "($1 == $2)"], # EqF64 ["", "", "($1 <= $2)", "($1 <= $2)"], # LeF64 ["", "", "($1 < $2)", "($1 < $2)"], # LtF64 diff --git a/compiler/semfold.nim b/compiler/semfold.nim index c2230a59e..d422146d1 100644 --- a/compiler/semfold.nim +++ b/compiler/semfold.nim @@ -359,11 +359,11 @@ proc evalOp(m: TMagic, n, a, b, c: PNode): PNode = if getFloat(a) > getFloat(b): result = newFloatNodeT(getFloat(b), n) else: result = newFloatNodeT(getFloat(a), n) of mIsNil: result = newIntNodeT(ord(a.kind == nkNilLit), n) - of mLtI, mLtI64, mLtB, mLtEnum, mLtCh: + of mLtI, mLtB, mLtEnum, mLtCh: result = newIntNodeT(ord(getOrdValue(a) < getOrdValue(b)), n) - of mLeI, mLeI64, mLeB, mLeEnum, mLeCh: + of mLeI, mLeB, mLeEnum, mLeCh: result = newIntNodeT(ord(getOrdValue(a) <= getOrdValue(b)), n) - of mEqI, mEqI64, mEqB, mEqEnum, mEqCh: + of mEqI, mEqB, mEqEnum, mEqCh: result = newIntNodeT(ord(getOrdValue(a) == getOrdValue(b)), n) of mLtF64: result = newIntNodeT(ord(getFloat(a) < getFloat(b)), n) of mLeF64: result = newIntNodeT(ord(getFloat(a) <= getFloat(b)), n) diff --git a/compiler/vmgen.nim b/compiler/vmgen.nim index db25b84ce..bb2b54ca0 100644 --- a/compiler/vmgen.nim +++ b/compiler/vmgen.nim @@ -776,11 +776,11 @@ proc genMagic(c: PCtx; n: PNode; dest: var TDest; m: TMagic) = of mMulU: genBinaryABCnarrowU(c, n, dest, opcMulu) of mDivU: genBinaryABCnarrowU(c, n, dest, opcDivu) of mModU: genBinaryABCnarrowU(c, n, dest, opcModu) - of mEqI, mEqI64, mEqB, mEqEnum, mEqCh: + of mEqI, mEqB, mEqEnum, mEqCh: genBinaryABC(c, n, dest, opcEqInt) - of mLeI, mLeI64, mLeEnum, mLeCh, mLeB: + of mLeI, mLeEnum, mLeCh, mLeB: genBinaryABC(c, n, dest, opcLeInt) - of mLtI, mLtI64, mLtEnum, mLtCh, mLtB: + of mLtI, mLtEnum, mLtCh, mLtB: genBinaryABC(c, n, dest, opcLtInt) of mEqF64: genBinaryABC(c, n, dest, opcEqFloat) of mLeF64: genBinaryABC(c, n, dest, opcLeFloat) diff --git a/lib/system.nim b/lib/system.nim index fb9720b21..7e5c5cb8c 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -766,21 +766,21 @@ proc `==` *(x, y: int): bool {.magic: "EqI", noSideEffect.} proc `==` *(x, y: int8): bool {.magic: "EqI", noSideEffect.} proc `==` *(x, y: int16): bool {.magic: "EqI", noSideEffect.} proc `==` *(x, y: int32): bool {.magic: "EqI", noSideEffect.} -proc `==` *(x, y: int64): bool {.magic: "EqI64", noSideEffect.} +proc `==` *(x, y: int64): bool {.magic: "EqI", noSideEffect.} ## Compares two integers for equality. proc `<=` *(x, y: int): bool {.magic: "LeI", noSideEffect.} proc `<=` *(x, y: int8): bool {.magic: "LeI", noSideEffect.} proc `<=` *(x, y: int16): bool {.magic: "LeI", noSideEffect.} proc `<=` *(x, y: int32): bool {.magic: "LeI", noSideEffect.} -proc `<=` *(x, y: int64): bool {.magic: "LeI64", noSideEffect.} +proc `<=` *(x, y: int64): bool {.magic: "LeI", noSideEffect.} ## Returns true iff `x` is less than or equal to `y`. proc `<` *(x, y: int): bool {.magic: "LtI", noSideEffect.} proc `<` *(x, y: int8): bool {.magic: "LtI", noSideEffect.} proc `<` *(x, y: int16): bool {.magic: "LtI", noSideEffect.} proc `<` *(x, y: int32): bool {.magic: "LtI", noSideEffect.} -proc `<` *(x, y: int64): bool {.magic: "LtI64", noSideEffect.} +proc `<` *(x, y: int64): bool {.magic: "LtI", noSideEffect.} ## Returns true iff `x` is less than `y`. type From 3984fecae66f4578dc806a37b19cee13b92643c0 Mon Sep 17 00:00:00 2001 From: rku Date: Mon, 8 Jun 2015 14:22:04 +0300 Subject: [PATCH 0430/1263] Removed magics: mBitnotI64 --- compiler/ast.nim | 4 ++-- compiler/ccgexprs.nim | 1 - compiler/jsgen.nim | 2 -- compiler/semfold.nim | 2 +- compiler/vmgen.nim | 2 +- lib/system.nim | 2 +- 6 files changed, 5 insertions(+), 8 deletions(-) diff --git a/compiler/ast.nim b/compiler/ast.nim index 1cf449eb8..e3af6c8cb 100644 --- a/compiler/ast.nim +++ b/compiler/ast.nim @@ -553,7 +553,7 @@ type mEqUntracedRef, mLePtr, mLtPtr, mEqCString, mXor, mEqProc, mUnaryMinusI, mUnaryMinusI64, mAbsI, mAbsI64, mNot, mUnaryPlusI, mBitnotI, - mBitnotI64, mUnaryPlusF64, mUnaryMinusF64, mAbsF64, mZe8ToI, mZe8ToI64, + mUnaryPlusF64, mUnaryMinusF64, mAbsF64, mZe8ToI, mZe8ToI64, mZe16ToI, mZe16ToI64, mZe32ToI64, mZeIToI64, mToU8, mToU16, mToU32, mToFloat, mToBiggestFloat, mToInt, mToBiggestInt, mCharToStr, mBoolToStr, mIntToStr, mInt64ToStr, mFloatToStr, mCStrToStr, mStrToStr, mEnumToStr, @@ -605,7 +605,7 @@ const mEqProc, mEqUntracedRef, mLePtr, mLtPtr, mEqCString, mXor, mUnaryMinusI, mUnaryMinusI64, mAbsI, mAbsI64, mNot, mUnaryPlusI, mBitnotI, - mBitnotI64, mUnaryPlusF64, mUnaryMinusF64, mAbsF64, mZe8ToI, mZe8ToI64, + mUnaryPlusF64, mUnaryMinusF64, mAbsF64, mZe8ToI, mZe8ToI64, mZe16ToI, mZe16ToI64, mZe32ToI64, mZeIToI64, mToU8, mToU16, mToU32, mToFloat, mToBiggestFloat, mToInt, mToBiggestInt, mCharToStr, mBoolToStr, mIntToStr, mInt64ToStr, mFloatToStr, mCStrToStr, mStrToStr, mEnumToStr, diff --git a/compiler/ccgexprs.nim b/compiler/ccgexprs.nim index 49c0d4176..3e897eef6 100644 --- a/compiler/ccgexprs.nim +++ b/compiler/ccgexprs.nim @@ -625,7 +625,6 @@ proc unaryArith(p: BProc, e: PNode, d: var TLoc, op: TMagic) = unArithTab: array[mNot..mToBiggestInt, string] = ["!($1)", # Not "$1", # UnaryPlusI "($3)((NU$2) ~($1))", # BitnotI - "($3)((NU$2) ~($1))", # BitnotI64 "$1", # UnaryPlusF64 "-($1)", # UnaryMinusF64 "($1 > 0? ($1) : -($1))", # AbsF64; BUGFIX: fabs() makes problems diff --git a/compiler/jsgen.nim b/compiler/jsgen.nim index 55cbed7e8..1c475b163 100644 --- a/compiler/jsgen.nim +++ b/compiler/jsgen.nim @@ -311,7 +311,6 @@ const # magic checked op; magic unchecked op; checked op; unchecked op ["", "", "!($1)", "!($1)"], # Not ["", "", "+($1)", "+($1)"], # UnaryPlusI ["", "", "~($1)", "~($1)"], # BitnotI - ["", "", "~($1)", "~($1)"], # BitnotI64 ["", "", "+($1)", "+($1)"], # UnaryPlusF64 ["", "", "-($1)", "-($1)"], # UnaryMinusF64 ["", "", "Math.abs($1)", "Math.abs($1)"], # AbsF64 @@ -397,7 +396,6 @@ const # magic checked op; magic unchecked op; checked op; unchecked op ["", "", "not ($1)", "not ($1)"], # Not ["", "", "+($1)", "+($1)"], # UnaryPlusI ["", "", "~($1)", "~($1)"], # BitnotI - ["", "", "~($1)", "~($1)"], # BitnotI64 ["", "", "+($1)", "+($1)"], # UnaryPlusF64 ["", "", "-($1)", "-($1)"], # UnaryMinusF64 ["", "", "Math.abs($1)", "Math.abs($1)"], # AbsF64 diff --git a/compiler/semfold.nim b/compiler/semfold.nim index d422146d1..e05690afc 100644 --- a/compiler/semfold.nim +++ b/compiler/semfold.nim @@ -285,7 +285,7 @@ proc evalOp(m: TMagic, n, a, b, c: PNode): PNode = of mUnaryMinusF64: result = newFloatNodeT(- getFloat(a), n) of mNot: result = newIntNodeT(1 - getInt(a), n) of mCard: result = newIntNodeT(nimsets.cardSet(a), n) - of mBitnotI, mBitnotI64: result = newIntNodeT(not getInt(a), n) + of mBitnotI: result = newIntNodeT(not getInt(a), n) of mLengthStr, mXLenStr: if a.kind == nkNilLit: result = newIntNodeT(0, n) else: result = newIntNodeT(len(getStr(a)), n) diff --git a/compiler/vmgen.nim b/compiler/vmgen.nim index bb2b54ca0..de7e7ab28 100644 --- a/compiler/vmgen.nim +++ b/compiler/vmgen.nim @@ -796,7 +796,7 @@ proc genMagic(c: PCtx; n: PNode; dest: var TDest; m: TMagic) = genNarrow(c, n, dest) of mUnaryMinusF64: genUnaryABC(c, n, dest, opcUnaryMinusFloat) of mUnaryPlusI, mUnaryPlusF64: gen(c, n.sons[1], dest) - of mBitnotI, mBitnotI64: + of mBitnotI: genUnaryABC(c, n, dest, opcBitnotInt) genNarrowU(c, n, dest) of mZe8ToI, mZe8ToI64, mZe16ToI, mZe16ToI64, mZe32ToI64, mZeIToI64, diff --git a/lib/system.nim b/lib/system.nim index 7e5c5cb8c..d65a69e35 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -677,7 +677,7 @@ proc `not` *(x: int): int {.magic: "BitnotI", noSideEffect.} proc `not` *(x: int8): int8 {.magic: "BitnotI", noSideEffect.} proc `not` *(x: int16): int16 {.magic: "BitnotI", noSideEffect.} proc `not` *(x: int32): int32 {.magic: "BitnotI", noSideEffect.} -proc `not` *(x: int64): int64 {.magic: "BitnotI64", noSideEffect.} +proc `not` *(x: int64): int64 {.magic: "BitnotI", noSideEffect.} ## computes the `bitwise complement` of the integer `x`. proc `+` *(x, y: int): int {.magic: "AddI", noSideEffect.} From 87b6220897035e0844958b6d9a2fd4cd7ad5dd46 Mon Sep 17 00:00:00 2001 From: rku Date: Mon, 8 Jun 2015 14:26:49 +0300 Subject: [PATCH 0431/1263] Removed magics: mAbsI64 --- compiler/ast.nim | 4 ++-- compiler/ccgexprs.nim | 7 +++---- compiler/jsgen.nim | 2 -- compiler/semfold.nim | 4 ++-- compiler/vmgen.nim | 2 +- lib/system.nim | 2 +- 6 files changed, 9 insertions(+), 12 deletions(-) diff --git a/compiler/ast.nim b/compiler/ast.nim index e3af6c8cb..263e06575 100644 --- a/compiler/ast.nim +++ b/compiler/ast.nim @@ -551,7 +551,7 @@ type mLeU, mLtU, mLeU64, mLtU64, mEqEnum, mLeEnum, mLtEnum, mEqCh, mLeCh, mLtCh, mEqB, mLeB, mLtB, mEqRef, mEqUntracedRef, mLePtr, mLtPtr, mEqCString, mXor, mEqProc, mUnaryMinusI, - mUnaryMinusI64, mAbsI, mAbsI64, mNot, + mUnaryMinusI64, mAbsI, mNot, mUnaryPlusI, mBitnotI, mUnaryPlusF64, mUnaryMinusF64, mAbsF64, mZe8ToI, mZe8ToI64, mZe16ToI, mZe16ToI64, mZe32ToI64, mZeIToI64, mToU8, mToU16, mToU32, @@ -603,7 +603,7 @@ const mLeU, mLtU, mLeU64, mLtU64, mEqEnum, mLeEnum, mLtEnum, mEqCh, mLeCh, mLtCh, mEqB, mLeB, mLtB, mEqRef, mEqProc, mEqUntracedRef, mLePtr, mLtPtr, mEqCString, mXor, mUnaryMinusI, - mUnaryMinusI64, mAbsI, mAbsI64, mNot, + mUnaryMinusI64, mAbsI, mNot, mUnaryPlusI, mBitnotI, mUnaryPlusF64, mUnaryMinusF64, mAbsF64, mZe8ToI, mZe8ToI64, mZe16ToI, mZe16ToI64, mZe32ToI64, mZeIToI64, mToU8, mToU16, mToU32, diff --git a/compiler/ccgexprs.nim b/compiler/ccgexprs.nim index 3e897eef6..862776740 100644 --- a/compiler/ccgexprs.nim +++ b/compiler/ccgexprs.nim @@ -525,11 +525,10 @@ proc binaryArithOverflow(p: BProc, e: PNode, d: var TLoc, m: TMagic) = proc unaryArithOverflow(p: BProc, e: PNode, d: var TLoc, m: TMagic) = const - opr: array[mUnaryMinusI..mAbsI64, string] = [ + opr: array[mUnaryMinusI..mAbsI, string] = [ mUnaryMinusI: "((NI$2)-($1))", mUnaryMinusI64: "-($1)", - mAbsI: "($1 > 0? ($1) : -($1))", - mAbsI64: "($1 > 0? ($1) : -($1))"] + mAbsI: "($1 > 0? ($1) : -($1))"] var a: TLoc t: PType @@ -1647,7 +1646,7 @@ proc genMagicExpr(p: BProc, e: PNode, d: var TLoc, op: TMagic) = case op of mOr, mAnd: genAndOr(p, e, d, op) of mNot..mToBiggestInt: unaryArith(p, e, d, op) - of mUnaryMinusI..mAbsI64: unaryArithOverflow(p, e, d, op) + of mUnaryMinusI..mAbsI: unaryArithOverflow(p, e, d, op) of mAddF64..mDivF64: binaryFloatArith(p, e, d, op) of mShrI..mXor: binaryArith(p, e, d, op) of mEqProc: genEqProc(p, e, d) diff --git a/compiler/jsgen.nim b/compiler/jsgen.nim index 1c475b163..70bd115c0 100644 --- a/compiler/jsgen.nim +++ b/compiler/jsgen.nim @@ -307,7 +307,6 @@ const # magic checked op; magic unchecked op; checked op; unchecked op ["negInt", "", "negInt($1)", "-($1)"], # UnaryMinusI ["negInt64", "", "negInt64($1)", "-($1)"], # UnaryMinusI64 ["absInt", "", "absInt($1)", "Math.abs($1)"], # AbsI - ["absInt64", "", "absInt64($1)", "Math.abs($1)"], # AbsI64 ["", "", "!($1)", "!($1)"], # Not ["", "", "+($1)", "+($1)"], # UnaryPlusI ["", "", "~($1)", "~($1)"], # BitnotI @@ -392,7 +391,6 @@ const # magic checked op; magic unchecked op; checked op; unchecked op ["negInt", "", "negInt($1)", "-($1)"], # UnaryMinusI ["negInt64", "", "negInt64($1)", "-($1)"], # UnaryMinusI64 ["absInt", "", "absInt($1)", "Math.abs($1)"], # AbsI - ["absInt64", "", "absInt64($1)", "Math.abs($1)"], # AbsI64 ["", "", "not ($1)", "not ($1)"], # Not ["", "", "+($1)", "+($1)"], # UnaryPlusI ["", "", "~($1)", "~($1)"], # BitnotI diff --git a/compiler/semfold.nim b/compiler/semfold.nim index e05690afc..b83641706 100644 --- a/compiler/semfold.nim +++ b/compiler/semfold.nim @@ -179,7 +179,7 @@ proc getIntervalType*(m: TMagic, n: PNode): PType = else: result = makeRangeF(a, abs(getFloat(a.n.sons[1])), abs(getFloat(a.n.sons[0]))) - of mAbsI, mAbsI64: + of mAbsI: let a = n.sons[1].typ if isIntRange(a): if a.n[0].intVal <= 0: @@ -298,7 +298,7 @@ proc evalOp(m: TMagic, n, a, b, c: PNode): PNode = result = newFloatNodeT(toFloat(int(getInt(a))), n) of mToInt, mToBiggestInt: result = newIntNodeT(system.toInt(getFloat(a)), n) of mAbsF64: result = newFloatNodeT(abs(getFloat(a)), n) - of mAbsI, mAbsI64: + of mAbsI: if getInt(a) >= 0: result = a else: result = newIntNodeT(- getInt(a), n) of mZe8ToI, mZe8ToI64, mZe16ToI, mZe16ToI64, mZe32ToI64, mZeIToI64: diff --git a/compiler/vmgen.nim b/compiler/vmgen.nim index de7e7ab28..c68282fde 100644 --- a/compiler/vmgen.nim +++ b/compiler/vmgen.nim @@ -1013,7 +1013,7 @@ proc genMagic(c: PCtx; n: PNode; dest: var TDest; m: TMagic) = c.gABC(n, opcCallSite, dest) of mNGenSym: genBinaryABC(c, n, dest, opcGenSym) of mMinI, mMaxI, mAbsF64, mMinF64, mMaxF64, mAbsI, - mAbsI64, mDotDot: + mDotDot: c.genCall(n, dest) of mExpandToAst: if n.len != 2: diff --git a/lib/system.nim b/lib/system.nim index d65a69e35..9e97d7cfe 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -2304,7 +2304,7 @@ proc abs*(x: int16): int16 {.magic: "AbsI", noSideEffect.} = if x < 0: -x else: x proc abs*(x: int32): int32 {.magic: "AbsI", noSideEffect.} = if x < 0: -x else: x -proc abs*(x: int64): int64 {.magic: "AbsI64", noSideEffect.} = +proc abs*(x: int64): int64 {.magic: "AbsI", noSideEffect.} = ## returns the absolute value of `x`. If `x` is ``low(x)`` (that ## is -MININT for its type), an overflow exception is thrown (if overflow ## checking is turned on). From 1b98d3257988b8878bef5fe637410ea125cfeb44 Mon Sep 17 00:00:00 2001 From: Araq Date: Sun, 7 Jun 2015 18:15:47 +0200 Subject: [PATCH 0432/1263] no private deprecated symbols --- bootstrap.sh | 0 lib/pure/pegs.nim | 1 - 2 files changed, 1 deletion(-) mode change 100755 => 100644 bootstrap.sh diff --git a/bootstrap.sh b/bootstrap.sh old mode 100755 new mode 100644 diff --git a/lib/pure/pegs.nim b/lib/pure/pegs.nim index ce837d9d1..e165d7dca 100644 --- a/lib/pure/pegs.nim +++ b/lib/pure/pegs.nim @@ -1060,7 +1060,6 @@ type lineStart: int ## index of last line start in buffer colOffset: int ## column to add filename: string -{.deprecated: [TTokKind: TokKind, TToken: Token, TModifier: Modifier].} const tokKindToStr: array[TokKind, string] = [ From d4610d7716c4c82d738548d7169aa150b803ef1d Mon Sep 17 00:00:00 2001 From: Araq Date: Wed, 10 Jun 2015 11:32:10 +0200 Subject: [PATCH 0433/1263] terminal doesn't use enormous windows module anymore --- lib/pure/terminal.nim | 103 +++++++++++++++++++++++++++++++++--------- 1 file changed, 81 insertions(+), 22 deletions(-) diff --git a/lib/pure/terminal.nim b/lib/pure/terminal.nim index 1e9c40f06..15e2eefec 100644 --- a/lib/pure/terminal.nim +++ b/lib/pure/terminal.nim @@ -17,28 +17,87 @@ import macros when defined(windows): - import windows, os + import winlean, os + + const + DUPLICATE_SAME_ACCESS = 2 + FOREGROUND_BLUE = 1 + FOREGROUND_GREEN = 2 + FOREGROUND_RED = 4 + FOREGROUND_INTENSITY = 8 + BACKGROUND_BLUE = 16 + BACKGROUND_GREEN = 32 + BACKGROUND_RED = 64 + BACKGROUND_INTENSITY = 128 + + type + SHORT = int16 + COORD = object + X: SHORT + Y: SHORT + + SMALL_RECT = object + Left: SHORT + Top: SHORT + Right: SHORT + Bottom: SHORT + + CONSOLE_SCREEN_BUFFER_INFO = object + dwSize: COORD + dwCursorPosition: COORD + wAttributes: int16 + srWindow: SMALL_RECT + dwMaximumWindowSize: COORD + + proc duplicateHandle(hSourceProcessHandle: HANDLE, hSourceHandle: HANDLE, + hTargetProcessHandle: HANDLE, lpTargetHandle: ptr HANDLE, + dwDesiredAccess: DWORD, bInheritHandle: WINBOOL, + dwOptions: DWORD): WINBOOL{.stdcall, dynlib: "kernel32", + importc: "DuplicateHandle".} + proc getCurrentProcess(): HANDLE{.stdcall, dynlib: "kernel32", + importc: "GetCurrentProcess".} + proc getConsoleScreenBufferInfo(hConsoleOutput: HANDLE, + lpConsoleScreenBufferInfo: ptr CONSOLE_SCREEN_BUFFER_INFO): WINBOOL{.stdcall, + dynlib: "kernel32", importc: "GetConsoleScreenBufferInfo".} + + proc setConsoleCursorPosition(hConsoleOutput: HANDLE, + dwCursorPosition: COORD): WINBOOL{. + stdcall, dynlib: "kernel32", importc: "SetConsoleCursorPosition".} + + proc fillConsoleOutputCharacter(hConsoleOutput: Handle, cCharacter: char, + nLength: DWORD, dwWriteCoord: Coord, + lpNumberOfCharsWritten: ptr DWORD): WINBOOL{. + stdcall, dynlib: "kernel32", importc: "FillConsoleOutputCharacterA".} + + proc fillConsoleOutputAttribute(hConsoleOutput: HANDLE, wAttribute: int16, + nLength: DWORD, dwWriteCoord: COORD, + lpNumberOfAttrsWritten: ptr DWORD): WINBOOL{. + stdcall, dynlib: "kernel32", importc: "FillConsoleOutputAttribute".} + + proc setConsoleTextAttribute(hConsoleOutput: HANDLE, + wAttributes: int16): WINBOOL{. + stdcall, dynlib: "kernel32", importc: "SetConsoleTextAttribute".} var conHandle: Handle # = createFile("CONOUT$", GENERIC_WRITE, 0, nil, OPEN_ALWAYS, 0, 0) block: - var hTemp = GetStdHandle(STD_OUTPUT_HANDLE) - if DuplicateHandle(GetCurrentProcess(), hTemp, GetCurrentProcess(), + var hTemp = getStdHandle(STD_OUTPUT_HANDLE) + if duplicateHandle(getCurrentProcess(), hTemp, getCurrentProcess(), addr(conHandle), 0, 1, DUPLICATE_SAME_ACCESS) == 0: raiseOSError(osLastError()) proc getCursorPos(): tuple [x,y: int] = var c: CONSOLESCREENBUFFERINFO - if GetConsoleScreenBufferInfo(conHandle, addr(c)) == 0: + if getConsoleScreenBufferInfo(conHandle, addr(c)) == 0: raiseOSError(osLastError()) return (int(c.dwCursorPosition.X), int(c.dwCursorPosition.Y)) proc getAttributes(): int16 = var c: CONSOLESCREENBUFFERINFO # workaround Windows bugs: try several times - if GetConsoleScreenBufferInfo(conHandle, addr(c)) != 0: + if getConsoleScreenBufferInfo(conHandle, addr(c)) != 0: return c.wAttributes return 0x70'i16 # ERROR: return white background, black text @@ -67,7 +126,7 @@ proc setCursorPos*(x, y: int) = var c: COORD c.X = int16(x) c.Y = int16(y) - if SetConsoleCursorPosition(conHandle, c) == 0: raiseOSError(osLastError()) + if setConsoleCursorPosition(conHandle, c) == 0: raiseOSError(osLastError()) else: stdout.write("\e[" & $y & ';' & $x & 'f') @@ -77,11 +136,11 @@ proc setCursorXPos*(x: int) = when defined(windows): var scrbuf: CONSOLESCREENBUFFERINFO var hStdout = conHandle - if GetConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0: + if getConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0: raiseOSError(osLastError()) var origin = scrbuf.dwCursorPosition origin.X = int16(x) - if SetConsoleCursorPosition(conHandle, origin) == 0: + if setConsoleCursorPosition(conHandle, origin) == 0: raiseOSError(osLastError()) else: stdout.write("\e[" & $x & 'G') @@ -93,11 +152,11 @@ when defined(windows): when defined(windows): var scrbuf: CONSOLESCREENBUFFERINFO var hStdout = conHandle - if GetConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0: + if getConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0: raiseOSError(osLastError()) var origin = scrbuf.dwCursorPosition origin.Y = int16(y) - if SetConsoleCursorPosition(conHandle, origin) == 0: + if setConsoleCursorPosition(conHandle, origin) == 0: raiseOSError(osLastError()) else: discard @@ -175,18 +234,18 @@ proc eraseLine* = var scrbuf: CONSOLESCREENBUFFERINFO var numwrote: DWORD var hStdout = conHandle - if GetConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0: + if getConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0: raiseOSError(osLastError()) var origin = scrbuf.dwCursorPosition origin.X = 0'i16 - if SetConsoleCursorPosition(conHandle, origin) == 0: + if setConsoleCursorPosition(conHandle, origin) == 0: raiseOSError(osLastError()) var ht = scrbuf.dwSize.Y - origin.Y var wt = scrbuf.dwSize.X - origin.X - if FillConsoleOutputCharacter(hStdout,' ', ht*wt, + if fillConsoleOutputCharacter(hStdout,' ', ht*wt, origin, addr(numwrote)) == 0: raiseOSError(osLastError()) - if FillConsoleOutputAttribute(hStdout, scrbuf.wAttributes, ht * wt, + if fillConsoleOutputAttribute(hStdout, scrbuf.wAttributes, ht * wt, scrbuf.dwCursorPosition, addr(numwrote)) == 0: raiseOSError(osLastError()) else: @@ -201,14 +260,14 @@ proc eraseScreen* = var origin: COORD # is inititalized to 0, 0 var hStdout = conHandle - if GetConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0: + if getConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0: raiseOSError(osLastError()) let numChars = int32(scrbuf.dwSize.X)*int32(scrbuf.dwSize.Y) - if FillConsoleOutputCharacter(hStdout, ' ', numChars, + if fillConsoleOutputCharacter(hStdout, ' ', numChars, origin, addr(numwrote)) == 0: raiseOSError(osLastError()) - if FillConsoleOutputAttribute(hStdout, scrbuf.wAttributes, numChars, + if fillConsoleOutputAttribute(hStdout, scrbuf.wAttributes, numChars, origin, addr(numwrote)) == 0: raiseOSError(osLastError()) setCursorXPos(0) @@ -219,7 +278,7 @@ proc resetAttributes* {.noconv.} = ## resets all attributes; it is advisable to register this as a quit proc ## with ``system.addQuitProc(resetAttributes)``. when defined(windows): - discard SetConsoleTextAttribute(conHandle, oldAttr) + discard setConsoleTextAttribute(conHandle, oldAttr) else: stdout.write("\e[0m") @@ -249,7 +308,7 @@ proc setStyle*(style: set[Style]) = if styleBlink in style: a = a or int16(BACKGROUND_INTENSITY) if styleReverse in style: a = a or 0x4000'i16 # COMMON_LVB_REVERSE_VIDEO if styleUnderscore in style: a = a or 0x8000'i16 # COMMON_LVB_UNDERSCORE - discard SetConsoleTextAttribute(conHandle, a) + discard setConsoleTextAttribute(conHandle, a) else: for s in items(style): stdout.write("\e[" & $ord(s) & 'm') @@ -260,7 +319,7 @@ proc writeStyled*(txt: string, style: set[Style] = {styleBright}) = var old = getAttributes() setStyle(style) stdout.write(txt) - discard SetConsoleTextAttribute(conHandle, old) + discard setConsoleTextAttribute(conHandle, old) else: setStyle(style) stdout.write(txt) @@ -309,7 +368,7 @@ proc setForegroundColor*(fg: ForegroundColor, bright=false) = (FOREGROUND_RED or FOREGROUND_BLUE), (FOREGROUND_BLUE or FOREGROUND_GREEN), (FOREGROUND_BLUE or FOREGROUND_GREEN or FOREGROUND_RED)] - discard SetConsoleTextAttribute(conHandle, toU16(old or lookup[fg])) + discard setConsoleTextAttribute(conHandle, toU16(old or lookup[fg])) else: gFG = ord(fg) if bright: inc(gFG, 60) @@ -330,7 +389,7 @@ proc setBackgroundColor*(bg: BackgroundColor, bright=false) = (BACKGROUND_RED or BACKGROUND_BLUE), (BACKGROUND_BLUE or BACKGROUND_GREEN), (BACKGROUND_BLUE or BACKGROUND_GREEN or BACKGROUND_RED)] - discard SetConsoleTextAttribute(conHandle, toU16(old or lookup[bg])) + discard setConsoleTextAttribute(conHandle, toU16(old or lookup[bg])) else: gBG = ord(bg) if bright: inc(gBG, 60) From 6c256ddcaef0c92b94d1a3e61f4e56cf7d017b50 Mon Sep 17 00:00:00 2001 From: Araq Date: Wed, 10 Jun 2015 11:50:08 +0200 Subject: [PATCH 0434/1263] cause I have no life --- bootstrap.sh | 0 1 file changed, 0 insertions(+), 0 deletions(-) mode change 100644 => 100755 bootstrap.sh diff --git a/bootstrap.sh b/bootstrap.sh old mode 100644 new mode 100755 From 8905ed1dda69dca5cd8a3f1099abb7e3878b842a Mon Sep 17 00:00:00 2001 From: msiglreith Date: Wed, 10 Jun 2015 14:34:53 +0200 Subject: [PATCH 0435/1263] Fix doc typos in basic2d and basic3d --- lib/pure/basic2d.nim | 2 +- lib/pure/basic3d.nim | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/pure/basic2d.nim b/lib/pure/basic2d.nim index d18e73c16..1392fdeba 100644 --- a/lib/pure/basic2d.nim +++ b/lib/pure/basic2d.nim @@ -64,7 +64,7 @@ type ## not used for geometric transformations in 2d. ax*,ay*,bx*,by*,tx*,ty*:float Point2d* = object - ## Implements a non-homegeneous 2d point stored as + ## Implements a non-homogeneous 2d point stored as ## an `x` coordinate and an `y` coordinate. x*,y*:float Vector2d* = object diff --git a/lib/pure/basic3d.nim b/lib/pure/basic3d.nim index b99357e3a..7fea54d58 100644 --- a/lib/pure/basic3d.nim +++ b/lib/pure/basic3d.nim @@ -53,7 +53,7 @@ type ## [ tx ty tz tw ] ax*,ay*,az*,aw*, bx*,by*,bz*,bw*, cx*,cy*,cz*,cw*, tx*,ty*,tz*,tw*:float Point3d* = object - ## Implements a non-homegeneous 2d point stored as + ## Implements a non-homogeneous 3d point stored as ## an `x` , `y` and `z` coordinate. x*,y*,z*:float Vector3d* = object From 891d953a4cd0be4693204e3d62ae7a22ec89aba9 Mon Sep 17 00:00:00 2001 From: Spencer Stirling Date: Wed, 10 Jun 2015 07:23:07 -0600 Subject: [PATCH 0436/1263] disabled threadpool assertion only for vcc --- lib/pure/concurrency/threadpool.nim | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/pure/concurrency/threadpool.nim b/lib/pure/concurrency/threadpool.nim index 43a9dea11..247aa377c 100644 --- a/lib/pure/concurrency/threadpool.nim +++ b/lib/pure/concurrency/threadpool.nim @@ -290,7 +290,8 @@ proc slave(w: ptr Worker) {.thread.} = readyWorker = w signal(gSomeReady) await(w.taskArrived) - #assert(not w.ready) # doesn't work with Visual Studio + # XXX Somebody needs to look into this (why does this assertion fail in Visual Studio?) + when not defined(vcc): assert(not w.ready) w.f(w, w.data) if w.q.len != 0: w.cleanFlowVars if w.shutdown: From 6ecce2941e3c05822dffb8ea80715225f9053855 Mon Sep 17 00:00:00 2001 From: Adam Strzelecki Date: Tue, 9 Jun 2015 23:57:41 +0200 Subject: [PATCH 0437/1263] macros: exprStructuralEquivalent for EqNimrodNode Previously NimNode comparison in macros way returning false for anything else than nil literal. --- compiler/vm.nim | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/compiler/vm.nim b/compiler/vm.nim index e49bed522..9f0d0bfce 100644 --- a/compiler/vm.nim +++ b/compiler/vm.nim @@ -682,11 +682,15 @@ proc rawExecute(c: PCtx, start: int, tos: PStackFrame): TFullReg = of opcLtu: decodeBC(rkInt) regs[ra].intVal = ord(regs[rb].intVal <% regs[rc].intVal) - of opcEqRef, opcEqNimrodNode: + of opcEqRef: decodeBC(rkInt) regs[ra].intVal = ord((regs[rb].node.kind == nkNilLit and regs[rc].node.kind == nkNilLit) or regs[rb].node == regs[rc].node) + of opcEqNimrodNode: + decodeBC(rkInt) + regs[ra].intVal = + ord(exprStructuralEquivalent(regs[rb].node, regs[rc].node)) of opcXor: decodeBC(rkInt) regs[ra].intVal = ord(regs[rb].intVal != regs[rc].intVal) From b49c75c82a5588ea6a3f14c9cb966ad87d99637e Mon Sep 17 00:00:00 2001 From: Adam Strzelecki Date: Wed, 10 Jun 2015 00:17:48 +0200 Subject: [PATCH 0438/1263] macros: Add test for node comparsion --- tests/macros/tnodecompare.nim | 39 +++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 tests/macros/tnodecompare.nim diff --git a/tests/macros/tnodecompare.nim b/tests/macros/tnodecompare.nim new file mode 100644 index 000000000..ef25ae370 --- /dev/null +++ b/tests/macros/tnodecompare.nim @@ -0,0 +1,39 @@ +discard """ +output: '''1 +0 +1 +0 +1 +0 +1 +0''' +""" + +import macros + +macro test(a: typed, b: typed): expr = + newLit(a == b) + +echo test(1, 1) +echo test(1, 2) + +type + Obj = object of RootObj + Other = object of RootObj + +echo test(Obj, Obj) +echo test(Obj, Other) + +var a, b: int + +echo test(a, a) +echo test(a, b) + +macro test2: expr = + newLit(bindSym"Obj" == bindSym"Obj") + +macro test3: expr = + newLit(bindSym"Obj" == bindSym"Other") + +echo test2() +echo test3() From ee3d390b3ffc394fca27fef42e7e36277df22dad Mon Sep 17 00:00:00 2001 From: Oscar Campbell Date: Wed, 10 Jun 2015 19:52:26 +0200 Subject: [PATCH 0439/1263] Revert from columnar layout. Remove temp-fix for 2857. --- tests/testament/tester.nim | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/tests/testament/tester.nim b/tests/testament/tester.nim index 2c4460395..704d7e76e 100644 --- a/tests/testament/tester.nim +++ b/tests/testament/tester.nim @@ -126,9 +126,6 @@ proc `$`(x: TResults): string = "Tests skipped: $2 / $3
    \n") % [$x.passed, $x.skipped, $x.total] -proc leftAlign(s: string, count: Natural, padding = ' '): string = - s & repeat(padding, max(0, count - s.len)) - proc addResult(r: var TResults, test: TTest, expected, given: string, success: TResultEnum) = let name = test.name.extractFilename & test.options @@ -140,13 +137,12 @@ proc addResult(r: var TResults, test: TTest, expected = expected, given = given) r.data.addf("$#\t$#\t$#\t$#", name, expected, given, $success) - let alignedName = leftAlign(name, 72) # Make the total line length 78 chars if success == reSuccess: - styledEcho fgCyan, alignedName, fgGreen, " [PASS]" + styledEcho fgGreen, "PASS: ", fgCyan, name elif success == reIgnored: - styledEcho styleBright, fgCyan, alignedName, styleDim, fgYellow, " [SKIP]" + styledEcho styleDim, fgYellow, "SKIP: ", styleBright, fgCyan, name else: - styledEcho styleBright, fgCyan, alignedName, fgRed, " [FAIL]" + styledEcho styleBright, fgRed, "FAIL: ", fgCyan, name styledEcho styleBright, fgCyan, "Test \"", test.name, "\"", " in category \"", test.cat.string, "\"" styledEcho styleBright, fgRed, "Failure: ", $success styledEcho fgYellow, "Expected:" @@ -295,13 +291,11 @@ proc testSpec(r: var TResults, test: TTest) = reExitCodesDiffer) return - # This is a bit ugly atm. if bufB != expectedOut: if not (expected.substr and expectedOut in bufB): - if not (expectedOut == "" and bufB == "\27[0m"): - given.err = reOutputsDiffer - r.addResult(test, expected.outp, bufB, reOutputsDiffer) - return + given.err = reOutputsDiffer + r.addResult(test, expected.outp, bufB, reOutputsDiffer) + return compilerOutputTests(test, given, expected, r) return From 31514550d38132cdd64be723a7a25819dbf31f97 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Wed, 10 Jun 2015 17:12:30 -0400 Subject: [PATCH 0440/1263] Revert "Base re off of nre" This reverts commit dc60a51e1545d8c73bc9415d1045864b72cfda0b. --- lib/impure/re.nim | 375 +++++++++++++++++++++++++++++----------------- 1 file changed, 234 insertions(+), 141 deletions(-) diff --git a/lib/impure/re.nim b/lib/impure/re.nim index 0ff6e9555..5f9371f28 100644 --- a/lib/impure/re.nim +++ b/lib/impure/re.nim @@ -2,13 +2,13 @@ # # Nim's Runtime Library # (c) Copyright 2012 Andreas Rumpf -# (c) Copyright 2015 Oleh Prypin # # See the file "copying.txt", included in this # distribution, for details about the copyright. # -## Regular expression support for Nim. Deprecated in favor of nre. +## Regular expression support for Nim. Deprecated. Consider using the ``nre`` +## or ``pegs`` modules instead. ## ## **Note:** The 're' proc defaults to the **extended regular expression ## syntax** which lets you use whitespace freely to make your regexes readable. @@ -25,15 +25,13 @@ ## .. include:: ../doc/regexprs.txt ## - -import strutils -import nre, options - -type Regex* = nre.Regex +import + pcre, strutils, rtarrays const - MaxSubpatterns* {.deprecated.} = 1000 - ## This is obsolete. There is no limit on the number of subpatterns. + MaxSubpatterns* = 20 + ## defines the maximum number of subpatterns that can be captured. + ## This limit still exists for ``replacef`` and ``parallelReplace``. type RegexFlag* = enum ## options for regular expressions @@ -43,61 +41,66 @@ type reExtended = 3, ## ignore whitespace and ``#`` comments reStudy = 4 ## study the expression (may be omitted if the ## expression will be used only once) + + RegexDesc = object + h: ptr Pcre + e: ptr ExtraData + + Regex* {.deprecated.} = ref RegexDesc ## a compiled regular expression RegexError* = object of ValueError ## is raised if the pattern is no valid regular expression. +{.deprecated: [TRegexFlag: RegexFlag, TRegexDesc: RegexDesc, TRegex: Regex, + EInvalidRegEx: RegexError].} + +proc raiseInvalidRegex(msg: string) {.noinline, noreturn.} = + var e: ref RegexError + new(e) + e.msg = msg + raise e + +proc rawCompile(pattern: string, flags: cint): ptr Pcre = + var + msg: cstring + offset: cint + result = pcre.compile(pattern, flags, addr(msg), addr(offset), nil) + if result == nil: + raiseInvalidRegex($msg & "\n" & pattern & "\n" & spaces(offset) & "^\n") + +proc finalizeRegEx(x: Regex) = + # XXX This is a hack, but PCRE does not export its "free" function properly. + # Sigh. The hack relies on PCRE's implementation (see ``pcre_get.c``). + # Fortunately the implementation is unlikely to change. + pcre.free_substring(cast[cstring](x.h)) + if not isNil(x.e): + pcre.free_substring(cast[cstring](x.e)) proc re*(s: string, flags = {reExtended, reStudy}): Regex {.deprecated.} = ## Constructor of regular expressions. Note that Nim's ## extended raw string literals support this syntax ``re"[abc]"`` as ## a short form for ``re(r"[abc]")``. - var options = "" - if reStudy notin flags: - options.add "(*NO_STUDY)" - for t in [ - (reIgnoreCase, "(?i)"), - (reMultiLine, "(?m)"), - (reDotAll, "(?s)"), - (reExtended, "(?x)") - ]: - if t[0] in flags: - options.add t[1] - try: - return nre.re(options & s) - except nre.SyntaxError: - let e = nre.SyntaxError(getCurrentException()) - raise newException(RegexError, e.msg & "\n" & e.pattern & "\n" & - repeat(' ', e.pos) & "^\n") - except nre.StudyError: - let e = nre.StudyError(getCurrentException()) - raise newException(RegexError, "Study error: " & e.msg) + new(result, finalizeRegEx) + result.h = rawCompile(s, cast[cint](flags - {reStudy})) + if reStudy in flags: + var msg: cstring + result.e = pcre.study(result.h, 0, addr msg) + if not isNil(msg): raiseInvalidRegex($msg) - -template execute(f: expr, notFound: stmt): stmt {.immediate, dirty.} = - let mm = f(s, pattern, start) - var m: RegexMatch - if mm.isSome: - m = mm.unsafeGet() - else: - notFound - -template stringCaptures(): stmt {.immediate, dirty.} = - for i in 0 .. = 0'i32: matches[i-1] = substr(s, int(a), int(b)-1) + else: matches[i-1] = nil + return rawMatches[1] - rawMatches[0] proc findBounds*(s: string, pattern: Regex, matches: var openArray[string], start = 0): tuple[first, last: int] = @@ -105,10 +108,18 @@ proc findBounds*(s: string, pattern: Regex, matches: var openArray[string], ## and the captured ## substrings in the array `matches`. If it does not match, nothing ## is written into `matches` and ``(-1,0)`` is returned. - execute nre.find: - return (-1, 0) - stringCaptures() - returnBounds() + var + rtarray = initRtArray[cint]((matches.len+1)*3) + rawMatches = rtarray.getRawData + res = pcre.exec(pattern.h, pattern.e, s, len(s).cint, start.cint, 0'i32, + cast[ptr cint](rawMatches), (matches.len+1).cint*3) + if res < 0'i32: return (-1, 0) + for i in 1..int(res)-1: + var a = rawMatches[i * 2] + var b = rawMatches[i * 2 + 1] + if a >= 0'i32: matches[i-1] = substr(s, int(a), int(b)-1) + else: matches[i-1] = nil + return (rawMatches[0].int, rawMatches[1].int - 1) proc findBounds*(s: string, pattern: Regex, matches: var openArray[tuple[first, last: int]], @@ -117,42 +128,56 @@ proc findBounds*(s: string, pattern: Regex, ## and the captured substrings in the array `matches`. ## If it does not match, nothing is written into `matches` and ## ``(-1,0)`` is returned. - execute nre.find: - return (-1, 0) - boundCaptures() - returnBounds() + var + rtarray = initRtArray[cint]((matches.len+1)*3) + rawMatches = rtarray.getRawData + res = pcre.exec(pattern.h, pattern.e, s, len(s).cint, start.cint, 0'i32, + cast[ptr cint](rawMatches), (matches.len+1).cint*3) + if res < 0'i32: return (-1, 0) + for i in 1..int(res)-1: + var a = rawMatches[i * 2] + var b = rawMatches[i * 2 + 1] + if a >= 0'i32: matches[i-1] = (int(a), int(b)-1) + else: matches[i-1] = (-1,0) + return (rawMatches[0].int, rawMatches[1].int - 1) proc findBounds*(s: string, pattern: Regex, start = 0): tuple[first, last: int] = - ## returns the starting position of `pattern` in `s`. If it does not - ## match, ``(-1,0)`` is returned. - execute nre.find: - return (-1, 0) - returnBounds() + ## returns the starting position and end position of ``pattern`` in ``s``. + ## If it does not match, ``(-1,0)`` is returned. + var + rtarray = initRtArray[cint](3) + rawMatches = rtarray.getRawData + res = pcre.exec(pattern.h, nil, s, len(s).cint, start.cint, 0'i32, + cast[ptr cint](rawMatches), 3) + if res < 0'i32: return (int(res), 0) + return (int(rawMatches[0]), int(rawMatches[1]-1)) + +proc matchOrFind(s: string, pattern: Regex, start, flags: cint): cint = + var + rtarray = initRtArray[cint](3) + rawMatches = rtarray.getRawData + result = pcre.exec(pattern.h, pattern.e, s, len(s).cint, start, flags, + cast[ptr cint](rawMatches), 3) + if result >= 0'i32: + result = rawMatches[1] - rawMatches[0] proc matchLen*(s: string, pattern: Regex, matches: var openArray[string], - start = 0): int = + start = 0): int = ## the same as ``match``, but it returns the length of the match, ## if there is no match, -1 is returned. Note that a match length ## of zero can happen. - execute nre.match: - return -1 - stringCaptures() - returnLength() + return matchOrFind(s, pattern, matches, start.cint, pcre.ANCHORED) proc matchLen*(s: string, pattern: Regex, start = 0): int = ## the same as ``match``, but it returns the length of the match, ## if there is no match, -1 is returned. Note that a match length ## of zero can happen. - execute nre.match: - return -1 - returnLength() + return matchOrFind(s, pattern, start.cint, pcre.ANCHORED) proc match*(s: string, pattern: Regex, start = 0): bool = ## returns ``true`` if ``s[start..]`` matches the ``pattern``. - execute nre.match: - return false - return true + result = matchLen(s, pattern, start) != -1 proc match*(s: string, pattern: Regex, matches: var openArray[string], start = 0): bool = @@ -160,45 +185,65 @@ proc match*(s: string, pattern: Regex, matches: var openArray[string], ## the captured substrings in the array ``matches``. If it does not ## match, nothing is written into ``matches`` and ``false`` is ## returned. - execute nre.match: - return false - stringCaptures() - return true + result = matchLen(s, pattern, matches, start) != -1 proc find*(s: string, pattern: Regex, matches: var openArray[string], start = 0): int = ## returns the starting position of ``pattern`` in ``s`` and the captured ## substrings in the array ``matches``. If it does not match, nothing ## is written into ``matches`` and -1 is returned. - execute nre.find: - return -1 - stringCaptures() - return m.matchBounds.a + var + rtarray = initRtArray[cint]((matches.len+1)*3) + rawMatches = rtarray.getRawData + res = pcre.exec(pattern.h, pattern.e, s, len(s).cint, start.cint, 0'i32, + cast[ptr cint](rawMatches), (matches.len+1).cint*3) + if res < 0'i32: return res + for i in 1..int(res)-1: + var a = rawMatches[i * 2] + var b = rawMatches[i * 2 + 1] + if a >= 0'i32: matches[i-1] = substr(s, int(a), int(b)-1) + else: matches[i-1] = nil + return rawMatches[0] proc find*(s: string, pattern: Regex, start = 0): int = ## returns the starting position of ``pattern`` in ``s``. If it does not ## match, -1 is returned. - execute nre.find: - return -1 - return m.matchBounds.a + var + rtarray = initRtArray[cint](3) + rawMatches = rtarray.getRawData + res = pcre.exec(pattern.h, nil, s, len(s).cint, start.cint, 0'i32, + cast[ptr cint](rawMatches), 3) + if res < 0'i32: return res + return rawMatches[0] iterator findAll*(s: string, pattern: Regex, start = 0): string = ## Yields all matching *substrings* of `s` that match `pattern`. ## ## Note that since this is an iterator you should not modify the string you ## are iterating over: bad things could happen. - for m in nre.findIter(s, pattern, start): - yield $m + var + i = int32(start) + rtarray = initRtArray[cint](3) + rawMatches = rtarray.getRawData + while true: + let res = pcre.exec(pattern.h, pattern.e, s, len(s).cint, i, 0'i32, + cast[ptr cint](rawMatches), 3) + if res < 0'i32: break + let a = rawMatches[0] + let b = rawMatches[1] + if a == b and a == i: break + yield substr(s, int(a), int(b)-1) + i = b proc findAll*(s: string, pattern: Regex, start = 0): seq[string] = ## returns all matching *substrings* of `s` that match `pattern`. ## If it does not match, @[] is returned. - accumulateResult findAll(s, pattern, start) + accumulateResult(findAll(s, pattern, start)) when not defined(nimhygiene): {.pragma: inject.} -template `=~`*(s: string, pattern: Regex, start = 0): expr = +template `=~` *(s: string, pattern: Regex): expr = ## This calls ``match`` with an implicit declared ``matches`` array that ## can be used in the scope of the ``=~`` call: ## @@ -216,11 +261,10 @@ template `=~`*(s: string, pattern: Regex, start = 0): expr = ## else: ## echo("syntax error") ## - let mm = nre.match(s, pattern, start) - var matches {.inject.}: seq[string] - if mm.isSome: - matches = mm.unsafeGet().captures.toSeq() - mm.isSome + bind MaxSubpatterns + when not declaredInScope(matches): + var matches {.inject.}: array[MaxSubpatterns, string] + match(s, pattern, matches) # ------------------------- more string handling ------------------------------ @@ -239,9 +283,8 @@ proc startsWith*(s: string, prefix: Regex): bool = proc endsWith*(s: string, suffix: Regex): bool = ## returns true if `s` ends with the pattern `prefix` - for i in 0 .. s.high: - if matchLen(s, suffix, i) == s.len - i: - return true + for i in 0 .. s.len-1: + if matchLen(s, suffix, i) == s.len - i: return true proc replace*(s: string, sub: Regex, by = ""): string = ## Replaces `sub` in `s` by the string `by`. Captures cannot be @@ -255,7 +298,15 @@ proc replace*(s: string, sub: Regex, by = ""): string = ## .. code-block:: nim ## ## "; " - return nre.replace(s, sub, by.replace("$", "$$")) + result = "" + var prev = 0 + while true: + var match = findBounds(s, sub, prev) + if match.first < 0: break + add(result, substr(s, prev, match.first-1)) + add(result, by) + prev = match.last + 1 + add(result, substr(s, prev)) proc replacef*(s: string, sub: Regex, by: string): string = ## Replaces `sub` in `s` by the string `by`. Captures can be accessed in `by` @@ -269,7 +320,18 @@ proc replacef*(s: string, sub: Regex, by: string): string = ## .. code-block:: nim ## ## "var1<-keykey; val2<-key2key2" - return nre.replace(s, sub, by) + result = "" + var caps: array[MaxSubpatterns, string] + var prev = 0 + while true: + var match = findBounds(s, sub, caps, prev) + if match.first < 0: break + assert result != nil + assert s != nil + add(result, substr(s, prev, match.first-1)) + addf(result, by, caps) + prev = match.last + 1 + add(result, substr(s, prev)) proc parallelReplace*(s: string, subs: openArray[ tuple[pattern: Regex, repl: string]]): string = @@ -277,20 +339,19 @@ proc parallelReplace*(s: string, subs: openArray[ ## applied in parallel. result = "" var i = 0 + var caps: array[MaxSubpatterns, string] while i < s.len: block searchSubs: - for sub in subs: - let pattern = sub.pattern - let start = i - execute nre.match: - continue - result.addf sub.repl, m.captures.toSeq() - i += m.matchBounds.b - m.matchBounds.a - break searchSubs - result.add s[i] - inc i + for j in 0..high(subs): + var x = matchLen(s, subs[j][0], caps, i) + if x > 0: + addf(result, subs[j][1], caps) + inc(i, x) + break searchSubs + add(result, s[i]) + inc(i) # copy the rest: - result.add s.substr(i) + add(result, substr(s, i)) proc transformFile*(infile, outfile: string, subs: openArray[tuple[pattern: Regex, repl: string]]) = @@ -313,42 +374,67 @@ iterator split*(s: string, sep: Regex): string = ## Results in: ## ## .. code-block:: nim + ## "" ## "this" ## "is" ## "an" ## "example" + ## "" ## - for m in nre.split(s, sep): - yield m + var + first = -1 + last = -1 + while last < len(s): + var x = matchLen(s, sep, last) + if x > 0: inc(last, x) + first = last + if x == 0: inc(last) + while last < len(s): + x = matchLen(s, sep, last) + if x >= 0: break + inc(last) + if first <= last: + yield substr(s, first, last-1) proc split*(s: string, sep: Regex): seq[string] = ## Splits the string `s` into substrings. - return nre.split(s, sep) + accumulateResult(split(s, sep)) proc escapeRe*(s: string): string = ## escapes `s` so that it is matched verbatim when used as a regular ## expression. - return nre.escapeRe(s) + result = "" + for c in items(s): + case c + of 'a'..'z', 'A'..'Z', '0'..'9', '_': + result.add(c) + else: + result.add("\\x") + result.add(toHex(ord(c), 2)) const ## common regular expressions - reIdentifier* = r"\b[a-zA-Z_]+[a-zA-Z_0-9]*\b" ## describes an identifier - reNatural* = r"\b\d+\b" ## describes a natural number - reInteger* = r"\b[-+]?\d+\b" ## describes an integer - reHex* = r"\b0[xX][0-9a-fA-F]+\b" ## describes a hexadecimal number - reBinary* = r"\b0[bB][01]+\b" ## describes a binary number (example: 0b11101) - reOctal* = r"\b0[oO][0-7]+\b" ## describes an octal number (example: 0o777) - reFloat* = r"\b[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?\b" + reIdentifier* {.deprecated.} = r"\b[a-zA-Z_]+[a-zA-Z_0-9]*\b" + ## describes an identifier + reNatural* {.deprecated.} = r"\b\d+\b" + ## describes a natural number + reInteger* {.deprecated.} = r"\b[-+]?\d+\b" + ## describes an integer + reHex* {.deprecated.} = r"\b0[xX][0-9a-fA-F]+\b" + ## describes a hexadecimal number + reBinary* {.deprecated.} = r"\b0[bB][01]+\b" + ## describes a binary number (example: 0b11101) + reOctal* {.deprecated.} = r"\b0[oO][0-7]+\b" + ## describes an octal number (example: 0o777) + reFloat* {.deprecated.} = r"\b[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?\b" ## describes a floating point number - reEmail* {.deprecated.} = - r"\b[a-zA-Z0-9!#$%&'*+/=?^_`{|}~\-]+(?:\. &" & - r"[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)" & - r"*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+" & - r"(?:[a-zA-Z]{2}|com|org|" & - r"net|gov|mil|biz|info|mobi|name|aero|jobs|museum)\b" + reEmail* {.deprecated.} = r"\b[a-zA-Z0-9!#$%&'*+/=?^_`{|}~\-]+(?:\. &" & + r"[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@" & + r"(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+" & + r"(?:[a-zA-Z]{2}|com|org|net|gov|mil|biz|" & + r"info|mobi|name|aero|jobs|museum)\b" ## describes a common email address - reURL* {.deprecated.} = - r"\b(http(s)?|ftp|gopher|telnet|file|notes|ms\-help):" & - r"((//)|(\\\\))+[\w\d:#@%/;$()~_?\+\-\=\\\.\&]*\b" + reURL* {.deprecated.} = r"\b(http(s)?|ftp|gopher|telnet|file|notes|ms-help)" & + r":((//)|(\\\\))+[\w\d:#@%/;$()~_?\+\-\=\\\.\&]*\b" ## describes an URL when isMainModule: @@ -366,7 +452,7 @@ when isMainModule: assert find("_____abc_______", re"abc") == 5 - var matches: array[0..5, string] + var matches: array[6, string] if match("abcdefg", re"c(d)ef(g)", matches, 2): assert matches[0] == "d" assert matches[1] == "g" @@ -375,7 +461,8 @@ when isMainModule: if "abc" =~ re"(a)bcxyz|(\w+)": assert matches[1] == "abc" - else: assert false + else: + assert false if "abc" =~ re"(cba)?.*": assert matches[0] == nil @@ -391,9 +478,16 @@ when isMainModule: assert("var1=key; var2=key2".replace(re"(\w+)=(\w+)", "$1<-$2$2") == "$1<-$2$2; $1<-$2$2") - var accum: seq[string] = split("00232this02939is39an22example111", re"\d+") + var accum: seq[string] = @[] + for word in split("00232this02939is39an22example111", re"\d+"): + accum.add(word) assert(accum == @["", "this", "is", "an", "example", ""]) + accum = @[] + for word in split("AAA : : BBB", re"\s*:\s*"): + accum.add(word) + assert(accum == @["AAA", "", "BBB"]) + for x in findAll("abcdef", re"^{.}", 3): assert x == "d" accum = @[] @@ -405,10 +499,9 @@ when isMainModule: assert("XYZ".match(re"^\d*") == true) block: - var matches: array[0..15, string] - if match("abcdefghijklmnop", - re"(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)(m)(n)(o)(p)", matches): - for i in 0 .. matches.high: + var matches: array[16, string] + if match("abcdefghijklmnop", re"(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)(m)(n)(o)(p)", matches): + for i in 0..matches.high: assert matches[i] == $chr(i + 'a'.ord) else: assert false From f47081b3004eb1bed538a74c4902b51256925fea Mon Sep 17 00:00:00 2001 From: yglukhov Date: Thu, 11 Jun 2015 18:32:22 +0300 Subject: [PATCH 0441/1263] Fixed addr of bracket expression. Fixes #2148. --- compiler/jsgen.nim | 19 +++++++++++-------- tests/js/taddr.nim | 22 ++++++++++++++++++++++ 2 files changed, 33 insertions(+), 8 deletions(-) diff --git a/compiler/jsgen.nim b/compiler/jsgen.nim index 1f82306d2..bb5f6812b 100644 --- a/compiler/jsgen.nim +++ b/compiler/jsgen.nim @@ -976,14 +976,17 @@ proc genAddr(p: PProc, n: PNode, r: var TCompRes) = genFieldAccess(p, n.sons[0], r) of nkBracketExpr: var ty = skipTypes(n.sons[0].typ, abstractVarRange) - if ty.kind in {tyRef, tyPtr}: ty = skipTypes(ty.lastSon, abstractVarRange) - case ty.kind - of tyArray, tyArrayConstr, tyOpenArray, tySequence, tyString, tyCString, - tyVarargs, tyChar: - genArrayAddr(p, n.sons[0], r) - of tyTuple: - genFieldAddr(p, n.sons[0], r) - else: internalError(n.sons[0].info, "expr(nkBracketExpr, " & $ty.kind & ')') + if ty.kind in MappedToObject: + gen(p, n.sons[0], r) + else: + let kindOfIndexedExpr = n.sons[0].sons[0].typ.kind + case kindOfIndexedExpr + of tyArray, tyArrayConstr, tyOpenArray, tySequence, tyString, tyCString, + tyVarargs: + genArrayAddr(p, n.sons[0], r) + of tyTuple: + genFieldAddr(p, n.sons[0], r) + else: internalError(n.sons[0].info, "expr(nkBracketExpr, " & $kindOfIndexedExpr & ')') else: internalError(n.sons[0].info, "genAddr") proc genProcForSymIfNeeded(p: PProc, s: PSym) = diff --git a/tests/js/taddr.nim b/tests/js/taddr.nim index f9c89fbc3..e5c8d0881 100644 --- a/tests/js/taddr.nim +++ b/tests/js/taddr.nim @@ -40,3 +40,25 @@ indexAddr[] = 'd' doAssert indexAddr[] == 'd' doAssert obj.s == "lodem ipsum dolor sit amet" + +# Bug #2148 +var x: array[2, int] +var y = addr x[1] + +y[] = 12 +doAssert(x[1] == 12) + +type + Foo = object + bar: int + +var foo: array[2, Foo] +var z = addr foo[1] + +z[].bar = 12345 +doAssert(foo[1].bar == 12345) + +var t : tuple[a, b: int] +var pt = addr t[1] +pt[] = 123 +doAssert(t.b == 123) From 98ec9615f3bfb645dda0f3790de95e84b49c6978 Mon Sep 17 00:00:00 2001 From: yglukhov Date: Thu, 11 Jun 2015 23:01:44 +0300 Subject: [PATCH 0442/1263] Fixed unittest output. --- lib/pure/unittest.nim | 1 - 1 file changed, 1 deletion(-) diff --git a/lib/pure/unittest.nim b/lib/pure/unittest.nim index dbbd3cabc..407db0a51 100644 --- a/lib/pure/unittest.nim +++ b/lib/pure/unittest.nim @@ -39,7 +39,6 @@ when declared(stdout): when not defined(ECMAScript): import terminal - system.addQuitProc(resetAttributes) type TestStatus* = enum OK, FAILED From 6436d1920c4b7754caede5d1d4e535666a2debea Mon Sep 17 00:00:00 2001 From: yglukhov Date: Thu, 11 Jun 2015 15:55:46 +0300 Subject: [PATCH 0443/1263] Fixed copying of aggregates in JS. --- compiler/jsgen.nim | 4 ++-- lib/system/jssys.nim | 52 +++++++++++++++++++++++++------------------ tests/js/tcopying.nim | 13 +++++++++++ 3 files changed, 45 insertions(+), 24 deletions(-) create mode 100644 tests/js/tcopying.nim diff --git a/compiler/jsgen.nim b/compiler/jsgen.nim index 1f82306d2..200cb4cd9 100644 --- a/compiler/jsgen.nim +++ b/compiler/jsgen.nim @@ -817,7 +817,7 @@ proc genAsgnAux(p: PProc, x, y: PNode, noCopyNeeded: bool) = addf(p.body, "$1 = $2;$n", [a.rdLoc, b.rdLoc]) else: useMagic(p, "nimCopy") - addf(p.body, "$1 = nimCopy($2, $3);$n", + addf(p.body, "$1 = nimCopy($1, $2, $3);$n", [a.res, b.res, genTypeInfo(p, y.typ)]) of etyBaseIndex: if a.typ != etyBaseIndex or b.typ != etyBaseIndex: @@ -1206,7 +1206,7 @@ proc genVarInit(p: PProc, v: PSym, n: PNode) = s = a.res else: useMagic(p, "nimCopy") - s = "nimCopy($1, $2)" % [a.res, genTypeInfo(p, n.typ)] + s = "nimCopy(null, $1, $2)" % [a.res, genTypeInfo(p, n.typ)] of etyBaseIndex: if (a.typ != etyBaseIndex): internalError(n.info, "genVarInit") if {sfAddrTaken, sfGlobal} * v.flags != {}: diff --git a/lib/system/jssys.nim b/lib/system/jssys.nim index 4a26e1e08..f082023ee 100644 --- a/lib/system/jssys.nim +++ b/lib/system/jssys.nim @@ -517,62 +517,70 @@ proc isFatPointer(ti: PNimType): bool = tyArray, tyArrayConstr, tyTuple, tyOpenArray, tySet, tyVar, tyRef, tyPtr} -proc nimCopy(x: pointer, ti: PNimType): pointer {.compilerproc.} +proc nimCopy(dest, src: pointer, ti: PNimType): pointer {.compilerproc.} proc nimCopyAux(dest, src: pointer, n: ptr TNimNode) {.compilerproc.} = case n.kind of nkNone: sysAssert(false, "nimCopyAux") of nkSlot: - asm "`dest`[`n`.offset] = nimCopy(`src`[`n`.offset], `n`.typ);" + asm """ + var ddest = `dest`[`n`.offset]; + if (ddest === undefined) ddest = null; + `dest`[`n`.offset] = nimCopy(ddest, `src`[`n`.offset], `n`.typ); + """ of nkList: for i in 0..n.len-1: nimCopyAux(dest, src, n.sons[i]) of nkCase: asm """ - `dest`[`n`.offset] = nimCopy(`src`[`n`.offset], `n`.typ); + var ddest = `dest`[`n`.offset]; + if (ddest === undefined) ddest = null; + `dest`[`n`.offset] = nimCopy(ddest, `src`[`n`.offset], `n`.typ); for (var i = 0; i < `n`.sons.length; ++i) { nimCopyAux(`dest`, `src`, `n`.sons[i][1]); } """ -proc nimCopy(x: pointer, ti: PNimType): pointer = +proc nimCopy(dest, src: pointer, ti: PNimType): pointer = case ti.kind of tyPtr, tyRef, tyVar, tyNil: if not isFatPointer(ti): - result = x + result = src else: - asm """ - `result` = [null, 0]; - `result`[0] = `x`[0]; - `result`[1] = `x`[1]; - """ + asm "`result` = [`src`[0], `src`[1]];" of tySet: asm """ `result` = {}; - for (var key in `x`) { `result`[key] = `x`[key]; } + for (var key in `src`) { `result`[key] = `src`[key]; } """ of tyTuple, tyObject: - if ti.base != nil: result = nimCopy(x, ti.base) + if ti.base != nil: result = nimCopy(dest, src, ti.base) elif ti.kind == tyObject: - asm "`result` = {m_type: `ti`};" + asm "`result` = (`dest` === null) ? {m_type: `ti`} : `dest`;" else: - asm "`result` = {};" - nimCopyAux(result, x, ti.node) + asm "`result` = (`dest` === null) ? {} : `dest`;" + nimCopyAux(result, src, ti.node) of tySequence, tyArrayConstr, tyOpenArray, tyArray: asm """ - `result` = new Array(`x`.length); - for (var i = 0; i < `x`.length; ++i) { - `result`[i] = nimCopy(`x`[i], `ti`.base); + if (`dest` === null) { + `dest` = new Array(`src`.length); + } + else { + `dest`.length = `src`.length; + } + `result` = `dest`; + for (var i = 0; i < `src`.length; ++i) { + `result`[i] = nimCopy(`result`[i], `src`[i], `ti`.base); } """ of tyString: asm """ - if (`x` !== null) { - `result` = `x`.slice(0); + if (`src` !== null) { + `result` = `src`.slice(0); } """ else: - result = x + result = src proc genericReset(x: pointer, ti: PNimType): pointer {.compilerproc.} = case ti.kind @@ -611,7 +619,7 @@ proc arrayConstr(len: int, value: pointer, typ: PNimType): pointer {. # types are fake asm """ var result = new Array(`len`); - for (var i = 0; i < `len`; ++i) result[i] = nimCopy(`value`, `typ`); + for (var i = 0; i < `len`; ++i) result[i] = nimCopy(null, `value`, `typ`); return result; """ diff --git a/tests/js/tcopying.nim b/tests/js/tcopying.nim new file mode 100644 index 000000000..4f72d6ada --- /dev/null +++ b/tests/js/tcopying.nim @@ -0,0 +1,13 @@ +discard """ + output: '''123 +''' +""" + +type MyArray = array[1, int] + +proc changeArray(a: var MyArray) = + a = [123] + +var a : MyArray +changeArray(a) +echo a[0] From f14ca63417136a4d9fedb4ce776bdea958c9faef Mon Sep 17 00:00:00 2001 From: yglukhov Date: Fri, 12 Jun 2015 00:06:01 +0300 Subject: [PATCH 0444/1263] Singing and dancing with skipTypes. --- compiler/jsgen.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/jsgen.nim b/compiler/jsgen.nim index bb5f6812b..6724a8100 100644 --- a/compiler/jsgen.nim +++ b/compiler/jsgen.nim @@ -979,7 +979,7 @@ proc genAddr(p: PProc, n: PNode, r: var TCompRes) = if ty.kind in MappedToObject: gen(p, n.sons[0], r) else: - let kindOfIndexedExpr = n.sons[0].sons[0].typ.kind + let kindOfIndexedExpr = skipTypes(n.sons[0].sons[0].typ, abstractVarRange).kind case kindOfIndexedExpr of tyArray, tyArrayConstr, tyOpenArray, tySequence, tyString, tyCString, tyVarargs: From 294989daf515d8cad63bb30a8a80e39a45766a80 Mon Sep 17 00:00:00 2001 From: apense Date: Thu, 11 Jun 2015 18:47:28 -0400 Subject: [PATCH 0445/1263] Updated random functions For Windows, `rand_s` has been available since Windows XP (see https://msdn.microsoft.com/en-us/library/sxtz2fa8.aspx). It gives a better quality random number in a larger range (the max is actually `0xffffffff`). --- lib/pure/math.nim | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/lib/pure/math.nim b/lib/pure/math.nim index a9e9010f6..6c03dee4f 100644 --- a/lib/pure/math.nim +++ b/lib/pure/math.nim @@ -202,8 +202,15 @@ when not defined(JS): ## computes x to power raised of y. # C procs: - proc srand(seed: cint) {.importc: "srand", header: "".} - proc rand(): cint {.importc: "rand", header: "".} + when defined(windows): + # The "secure" random, available from Windows XP + # https://msdn.microsoft.com/en-us/library/sxtz2fa8.aspx + proc rand_s(val: var cuint) {.importc: "rand_s", header: "".} + # To behave like the normal version + proc rand(): cuint = rand_s(result) + else: + proc srand(seed: cint) {.importc: "srand", header: "".} + proc rand(): cint {.importc: "rand", header: "".} when not defined(windows): proc srand48(seed: clong) {.importc: "srand48", header: "".} @@ -216,13 +223,14 @@ when not defined(JS): # importcing macros is extremely problematic # and because the value is publicly documented # on MSDN and very unlikely to change - const rand_max = 32767 + # See https://msdn.microsoft.com/en-us/library/296az74e.aspx + const rand_max = 4294967295 result = (float(rand()) / float(rand_max)) * max proc randomize() = randomize(cast[int](epochTime())) proc randomize(seed: int) = - srand(cint(seed)) + when declared(srand): srand(cint(seed)) # rand_s doesn't use srand when declared(srand48): srand48(seed) proc random(max: int): int = result = int(rand()) mod max From 7fba7d934b04d7a602944c1a8d0785e6d6a34b9a Mon Sep 17 00:00:00 2001 From: apense Date: Thu, 11 Jun 2015 18:56:59 -0400 Subject: [PATCH 0446/1263] Discarded randomize for windows It actually doesn't use it because `rand_s` doesn't. --- lib/pure/math.nim | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/lib/pure/math.nim b/lib/pure/math.nim index 6c03dee4f..34070dd91 100644 --- a/lib/pure/math.nim +++ b/lib/pure/math.nim @@ -217,6 +217,12 @@ when not defined(JS): proc drand48(): float {.importc: "drand48", header: "".} proc random(max: float): float = result = drand48() * max + proc randomize() = + randomize(cast[int](epochTime())) + + proc randomize(seed: int) = + srand(cint(seed)) # rand_s doesn't use srand + srand48(seed) when defined(windows): proc random(max: float): float = # we are hardcodeing this because @@ -226,12 +232,9 @@ when not defined(JS): # See https://msdn.microsoft.com/en-us/library/296az74e.aspx const rand_max = 4294967295 result = (float(rand()) / float(rand_max)) * max - proc randomize() = - randomize(cast[int](epochTime())) - - proc randomize(seed: int) = - when declared(srand): srand(cint(seed)) # rand_s doesn't use srand - when declared(srand48): srand48(seed) + proc randomize() = discard + proc randomize(seed: int) = discard + proc random(max: int): int = result = int(rand()) mod max From a723362d85c077e572240d55301e715ff6dbcf64 Mon Sep 17 00:00:00 2001 From: Oscar Campbell Date: Tue, 9 Jun 2015 14:38:54 +0200 Subject: [PATCH 0447/1263] Fix bug #1179 + some more found while testing. - The char(-1) < char(0) is not covered in this PR - different beast. - Additionally to #1179, I found that non base-10 literals wheren't bounds checked at all. --- compiler/lexer.nim | 119 +++++++++++++++++++++++++++------------------ 1 file changed, 72 insertions(+), 47 deletions(-) diff --git a/compiler/lexer.nim b/compiler/lexer.nim index 6b38ee062..09eca3100 100644 --- a/compiler/lexer.nim +++ b/compiler/lexer.nim @@ -262,14 +262,11 @@ template eatChar(L: var TLexer, t: var TToken) = add(t.literal, L.buf[L.bufpos]) inc(L.bufpos) -proc getNumber(L: var TLexer): TToken = - var - startpos, endpos: int - xi: BiggestInt - const literalishChars = { 'A'..'F', 'a'..'f', '0'..'9', 'X', 'x', 'o', 'c', - 'C', 'b', 'B', '_', '.', '\''} - const literalishCharsNoDot = literalishChars - {'.'} + + + +proc getNumber(L: var TLexer): TToken = proc matchUnderscoreChars(L: var TLexer, tok: var TToken, chars: set[char]) = var pos = L.bufpos # use registers for pos, buf var buf = L.buf @@ -318,14 +315,22 @@ proc getNumber(L: var TLexer): TToken = L.bufpos = msgPos lexMessage(L, msg, t.literal) + var + startpos, endpos: int + xi: BiggestInt + isBase10 = true + const + baseCodeChars = {'X', 'x', 'o', 'c', 'C', 'b', 'B'} + literalishChars = baseCodeChars + {'A'..'F', 'a'..'f', '0'..'9', '_', '\''} + floatTypes = {tkFloatLit, tkFloat32Lit, tkFloat64Lit, tkFloat128Lit} result.tokType = tkIntLit # int literal until we know better result.literal = "" result.base = base10 startpos = L.bufpos - var isAFloatLiteral = false + # First stage: find out base, make verifications, build token literal string - if L.buf[L.bufpos] == '0' and - L.buf[L.bufpos + 1] in {'X', 'x', 'o', 'O', 'c', 'C', 'b', 'B'}: + if L.buf[L.bufpos] == '0' and L.buf[L.bufpos + 1] in baseCodeChars + {'O'}: + isBase10 = false eatChar(L, result, '0') case L.buf[L.bufpos] of 'O': @@ -344,21 +349,23 @@ proc getNumber(L: var TLexer): TToken = else: matchUnderscoreChars(L, result, {'0'..'9'}) if (L.buf[L.bufpos] == '.') and (L.buf[L.bufpos + 1] in {'0'..'9'}): - isAFloatLiteral = true + result.tokType = tkFloat64Lit eatChar(L, result, '.') matchUnderscoreChars(L, result, {'0'..'9'}) if L.buf[L.bufpos] in {'e', 'E'}: - isAFloatLiteral = true + result.tokType = tkFloat64Lit eatChar(L, result, 'e') if L.buf[L.bufpos] in {'+', '-'}: eatChar(L, result) matchUnderscoreChars(L, result, {'0'..'9'}) endpos = L.bufpos - # Second stage, find out if there's a datatype postfix and handle it + + # Second stage, find out if there's a datatype suffix and handle it var postPos = endpos if L.buf[postPos] in {'\'', 'f', 'F', 'd', 'D', 'i', 'I', 'u', 'U'}: - if L.buf[postPos] == '\'': + if L.buf[postPos] == '\'': inc(postPos) + case L.buf[postPos] of 'f', 'F': inc(postPos) @@ -410,21 +417,23 @@ proc getNumber(L: var TLexer): TToken = inc(postPos) else: result.tokType = tkUIntLit - else: + else: lexMessageLitNum(L, errInvalidNumber, startpos) + # Is there still a literalish char awaiting? Then it's an error! - if L.buf[postPos] in literalishCharsNoDot or + if L.buf[postPos] in literalishChars or (L.buf[postPos] == '.' and L.buf[postPos + 1] in {'0'..'9'}): lexMessageLitNum(L, errInvalidNumber, startpos) + # Third stage, extract actual number L.bufpos = startpos # restore position var pos: int = startpos try: - if (L.buf[pos] == '0') and - (L.buf[pos + 1] in {'x', 'X', 'b', 'B', 'o', 'O', 'c', 'C'}): + if (L.buf[pos] == '0') and (L.buf[pos + 1] in baseCodeChars): inc(pos, 2) xi = 0 # it is a base prefix - case L.buf[pos - 1] # now look at the optional type suffix: + + case L.buf[pos - 1] of 'b', 'B': result.base = base2 while pos < endpos: @@ -452,48 +461,64 @@ proc getNumber(L: var TLexer): TToken = of 'A'..'F': xi = `shl`(xi, 4) or (ord(L.buf[pos]) - ord('A') + 10) inc(pos) - else: + else: break - else: + else: internalError(getLineInfo(L), "getNumber") + case result.tokType of tkIntLit, tkInt64Lit: result.iNumber = xi of tkInt8Lit: result.iNumber = BiggestInt(int8(toU8(int(xi)))) - of tkInt16Lit: result.iNumber = BiggestInt(toU16(int(xi))) - of tkInt32Lit: result.iNumber = BiggestInt(toU32(xi)) + of tkInt16Lit: result.iNumber = BiggestInt(int16(toU16(int(xi)))) + of tkInt32Lit: result.iNumber = BiggestInt(int32(toU32(int64(xi)))) of tkUIntLit, tkUInt64Lit: result.iNumber = xi - of tkUInt8Lit: result.iNumber = BiggestInt(int8(toU8(int(xi)))) - of tkUInt16Lit: result.iNumber = BiggestInt(toU16(int(xi))) - of tkUInt32Lit: result.iNumber = BiggestInt(toU32(xi)) + of tkUInt8Lit: result.iNumber = BiggestInt(uint8(toU8(int(xi)))) + of tkUInt16Lit: result.iNumber = BiggestInt(uint16(toU16(int(xi)))) + of tkUInt32Lit: result.iNumber = BiggestInt(uint32(toU32(int64(xi)))) of tkFloat32Lit: result.fNumber = (cast[PFloat32](addr(xi)))[] # note: this code is endian neutral! # XXX: Test this on big endian machine! of tkFloat64Lit: result.fNumber = (cast[PFloat64](addr(xi)))[] else: internalError(getLineInfo(L), "getNumber") - elif isAFloatLiteral or (result.tokType == tkFloat32Lit) or - (result.tokType == tkFloat64Lit): - result.fNumber = parseFloat(result.literal) - if result.tokType == tkIntLit: result.tokType = tkFloatLit - elif result.tokType == tkUint64Lit: - xi = 0 - let len = unsafeParseUInt(result.literal, xi) - if len != result.literal.len or len == 0: - raise newException(ValueError, "invalid integer: " & $xi) - result.iNumber = xi + + # Simple bounds check + if result.tokType notin floatTypes and xi != result.iNumber: + lexMessageLitNum(L, errNumberOutOfRange, startpos) + else: - result.iNumber = parseBiggestInt(result.literal) - if (result.iNumber < low(int32)) or (result.iNumber > high(int32)): - if result.tokType == tkIntLit: + case result.tokType + of floatTypes: + result.fNumber = parseFloat(result.literal) + of tkUint64Lit: + xi = 0 + let len = unsafeParseUInt(result.literal, xi) + if len != result.literal.len or len == 0: + raise newException(ValueError, "invalid integer: " & $xi) + result.iNumber = xi + else: + result.iNumber = parseBiggestInt(result.literal) + + # Explicit bounds checks + let outOfRange = case result.tokType: + of tkInt8Lit: (result.iNumber < int8.low or result.iNumber > int8.high) + of tkUInt8Lit: (result.iNumber < BiggestInt(uint8.low) or + result.iNumber > BiggestInt(uint8.high)) + of tkInt16Lit: (result.iNumber < int16.low or result.iNumber > int16.high) + of tkUInt16Lit: (result.iNumber < BiggestInt(uint16.low) or + result.iNumber > BiggestInt(uint16.high)) + of tkInt32Lit: (result.iNumber < int32.low or result.iNumber > int32.high) + of tkUInt32Lit: (result.iNumber < BiggestInt(uint32.low) or + result.iNumber > BiggestInt(uint32.high)) + else: false + + if outOfRange: lexMessageLitNum(L, errNumberOutOfRange, startpos) + + # Promote int literal to int64? Not always necessary, but more consistent + if result.tokType == tkIntLit: + if (result.iNumber < low(int32)) or (result.iNumber > high(int32)): result.tokType = tkInt64Lit - elif result.tokType in {tkInt8Lit, tkInt16Lit, tkInt32Lit}: - lexMessageLitNum(L, errNumberOutOfRange, startpos) - elif result.tokType == tkInt8Lit and - (result.iNumber < int8.low or result.iNumber > int8.high): - lexMessageLitNum(L, errNumberOutOfRange, startpos) - elif result.tokType == tkInt16Lit and - (result.iNumber < int16.low or result.iNumber > int16.high): - lexMessageLitNum(L, errNumberOutOfRange, startpos) + except ValueError: lexMessageLitNum(L, errInvalidNumber, startpos) except OverflowError, RangeError: From 3998220f866f776b1ef6bf278ba5a02c220c7702 Mon Sep 17 00:00:00 2001 From: Oscar Campbell Date: Thu, 11 Jun 2015 01:53:34 +0200 Subject: [PATCH 0448/1263] Non-base10 overflow allowed if bit-stable. Tests. --- compiler/lexer.nim | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/compiler/lexer.nim b/compiler/lexer.nim index 09eca3100..5c7baf7d3 100644 --- a/compiler/lexer.nim +++ b/compiler/lexer.nim @@ -482,9 +482,21 @@ proc getNumber(L: var TLexer): TToken = of tkFloat64Lit: result.fNumber = (cast[PFloat64](addr(xi)))[] else: internalError(getLineInfo(L), "getNumber") - # Simple bounds check - if result.tokType notin floatTypes and xi != result.iNumber: - lexMessageLitNum(L, errNumberOutOfRange, startpos) + # Bounds checks. Non decimal literals are allowed to overflow the range of + # the datatype as long as their pattern don't overflow _bitwise_, hence + # below checks of signed sizes against uint*.high is deliberate: + # (0x80'u8 = 128, 0x80'i8 = -128, etc == OK) + if result.tokType notin floatTypes: + let outOfRange = case result.tokType: + of tkUInt8Lit, tkUInt16Lit, tkUInt32Lit: result.iNumber != xi + of tkInt8Lit: (xi > BiggestInt(uint8.high)) + of tkInt16Lit: (xi > BiggestInt(uint16.high)) + of tkInt32Lit: (xi > BiggestInt(uint32.high)) + else: false + + if outOfRange: + echo "out of range num: ", result.iNumber, " vs ", xi + lexMessageLitNum(L, errNumberOutOfRange, startpos) else: case result.tokType From 7ca61f484b67b231929432436ba9717494f1648f Mon Sep 17 00:00:00 2001 From: Oscar Campbell Date: Thu, 11 Jun 2015 01:53:34 +0200 Subject: [PATCH 0449/1263] Non-base10 overflow allowed if bit-stable. Tests. --- tests/misc/tunsignedmisc.nim | 68 ++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 tests/misc/tunsignedmisc.nim diff --git a/tests/misc/tunsignedmisc.nim b/tests/misc/tunsignedmisc.nim new file mode 100644 index 000000000..e6a497a3d --- /dev/null +++ b/tests/misc/tunsignedmisc.nim @@ -0,0 +1,68 @@ +import unsigned + +discard """ + errormsg: "number 0x123'u8 out of valid range" +""" + +# Bug #1179 + +# Unsigneds + +# 8 bit +let ref1 = 128'u8 shr 7 +let hex1 = 0x80'u8 shr 7 +let oct1 = 0c200'u8 shr 7 +let dig1 = 0b10000000'u8 shr 7 + +doAssert(ref1 == 1) +doAssert(ref1 == hex1) +doAssert(ref1 == oct1) +doAssert(ref1 == dig1) + +# 16 bit +let ref2 = 32768'u16 shr 15 +let hex2 = 0x8000'u16 shr 15 +let oct2 = 0c100000'u16 shr 15 +let dig2 = 0b1000000000000000'u16 shr 15 + +doAssert(ref2 == 1) +doAssert(ref2 == hex2) +doAssert(ref2 == oct2) +doAssert(ref2 == dig2) + +# 32 bit +let ref3 = 2147483648'u32 shr 31 +let hex3 = 0x80000000'u32 shr 31 +let oct3 = 0c20000000000'u32 shr 31 +let dig3 = 0b10000000000000000000000000000000'u32 shr 31 + +doAssert(ref3 == 1) +doAssert(ref3 == hex3) +doAssert(ref3 == oct3) +doAssert(ref3 == dig3) + +# Below doesn't work for lexer stage errors... +# doAssert(compiles(0xFF'u8) == true) +# doAssert(compiles(0xFFF'u16) == true) +# doAssert(compiles(0x7FFF'i16) == true) + +# doAssert(compiles(0x123'u8) == false) +# doAssert(compiles(0x123'i8) == false) +# doAssert(compiles(0x123123'u16) == false) +# doAssert(compiles(0x123123'i16) == false) + +# Should compile # +let boundOkHex1 = 0xFF'u8 +let boundOkHex2 = 0xFFFF'u16 +let boundOkHex3 = 0x7FFF'i16 + +let boundOkHex4 = 0x80'i8 +let boundOkHex5 = 0xFF'i8 +let boundOkHex6 = 0xFFFF'i16 +let boundOkHex7 = 0x7FFF'i16 + +# Should _not_ compile # +let boundBreakingHex1 = 0x123'u8 +let boundBreakingHex2 = 0x123'i8 +let boundBreakingHex3 = 0x123123'u16 +let boundBreakingHex4 = 0x123123'i16 From 85911a16592e5e4d3ca822fda707f652ec22c0df Mon Sep 17 00:00:00 2001 From: Sergey Avseyev Date: Fri, 12 Jun 2015 19:51:23 +0300 Subject: [PATCH 0450/1263] Add missing nre dependency to installer --- compiler/installer.ini | 1 + 1 file changed, 1 insertion(+) diff --git a/compiler/installer.ini b/compiler/installer.ini index 821309a34..70df9fd24 100644 --- a/compiler/installer.ini +++ b/compiler/installer.ini @@ -99,6 +99,7 @@ Files: "lib/pure/concurrency/*.nim" Files: "lib/pure/unidecode/*.nim" Files: "lib/pure/concurrency/*.cfg" Files: "lib/impure/*.nim" +Files: "lib/impure/nre/private/*.nim" Files: "lib/wrappers/*.nim" Files: "lib/wrappers/readline/*.nim" From 0fe54a5e14bae4931cd69dd88a5563eb5e23bdf7 Mon Sep 17 00:00:00 2001 From: Sergey Avseyev Date: Sat, 13 Jun 2015 10:35:55 +0300 Subject: [PATCH 0451/1263] Fix logger formatting Motivation ---------- Current implementation does not allow to specify any formatting. It even cannot output log level, because `writeln()` accepts `varags[string]` and silently ignores everything before last argument. Modification ------------ Perform formatting in the single place during substitution. Make log level optional as all other substitution variables. Also make verbose logging more informative and parseable. Result ------ Correct handling formatting and substitutions. Machine-friendly default output of verbose logger. --- lib/pure/logging.nim | 31 ++++++++++++++++++++----------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/lib/pure/logging.nim b/lib/pure/logging.nim index 379c18e9d..b28298dfa 100644 --- a/lib/pure/logging.nim +++ b/lib/pure/logging.nim @@ -19,7 +19,12 @@ ## ============ ======================= ## $date Current date ## $time Current time +## $datetime $dateT$time ## $app ``os.getAppFilename()`` +## $appname base name of $app +## $appdir directory name of $app +## $levelid first letter of log level +## $levelname log level name ## ============ ======================= ## ## @@ -59,8 +64,8 @@ const "DEBUG", "DEBUG", "INFO", "WARN", "ERROR", "FATAL", "NONE" ] - defaultFmtStr* = "" ## default string between log level and message per logger - verboseFmtStr* = "$date $time " + defaultFmtStr* = "$levelname " ## default format string + verboseFmtStr* = "$levelid, [$datetime] -- $appname: " type Logger* = ref object of RootObj ## abstract logger; the base type of all loggers @@ -87,12 +92,11 @@ type {.deprecated: [TLevel: Level, PLogger: Logger, PConsoleLogger: ConsoleLogger, PFileLogger: FileLogger, PRollingFileLogger: RollingFileLogger].} -proc substituteLog(frmt: string): string = - ## converts $date to the current date - ## converts $time to the current time - ## converts $app to getAppFilename() - ## converts - result = newStringOfCap(frmt.len + 20) +proc substituteLog(frmt: string, level: Level, args: varargs[string, `$`]): string = + var msgLen = 0 + for arg in args: + msgLen += arg.len + result = newStringOfCap(frmt.len + msgLen + 20) var i = 0 while i < frmt.len: if frmt[i] != '$': @@ -108,10 +112,15 @@ proc substituteLog(frmt: string): string = case v of "date": result.add(getDateStr()) of "time": result.add(getClockStr()) + of "datetime": result.add(getDateStr() & "T" & getClockStr()) of "app": result.add(app) of "appdir": result.add(app.splitFile.dir) of "appname": result.add(app.splitFile.name) + of "levelid": result.add(LevelNames[level][0]) + of "levelname": result.add(LevelNames[level]) else: discard + for arg in args: + result.add(arg) method log*(logger: Logger, level: Level, args: varargs[string, `$`]) {. raises: [Exception], @@ -123,12 +132,12 @@ method log*(logger: Logger, level: Level, args: varargs[string, `$`]) {. method log*(logger: ConsoleLogger, level: Level, args: varargs[string, `$`]) = ## Logs to the console using ``logger`` only. if level >= logger.levelThreshold: - writeln(stdout, LevelNames[level], " ", substituteLog(logger.fmtStr), args) + writeln(stdout, substituteLog(logger.fmtStr, level, args)) method log*(logger: FileLogger, level: Level, args: varargs[string, `$`]) = ## Logs to a file using ``logger`` only. if level >= logger.levelThreshold: - writeln(logger.f, LevelNames[level], " ", substituteLog(logger.fmtStr), args) + writeln(logger.f, substituteLog(logger.fmtStr, level, args)) proc defaultFilename*(): string = ## Returns the default filename for a logger. @@ -219,7 +228,7 @@ method log*(logger: RollingFileLogger, level: Level, args: varargs[string, `$`]) logger.curLine = 0 logger.f = open(logger.baseName, logger.baseMode, bufSize = logger.bufSize) - writeln(logger.f, LevelNames[level], " ", substituteLog(logger.fmtStr), args) + writeln(logger.f, substituteLog(logger.fmtStr, level, args)) logger.curLine.inc # -------- From ed73a90bd3192f4994cc467f71900b62e39b0ec0 Mon Sep 17 00:00:00 2001 From: Oscar Campbell Date: Sun, 14 Jun 2015 18:36:35 +0200 Subject: [PATCH 0452/1263] Regarding num literals, mod paths, ident equality. --- doc/manual/lexing.txt | 27 ++++++++++++++++++--------- doc/manual/modules.txt | 8 ++++++++ 2 files changed, 26 insertions(+), 9 deletions(-) diff --git a/doc/manual/lexing.txt b/doc/manual/lexing.txt index fab6da416..9419f8453 100644 --- a/doc/manual/lexing.txt +++ b/doc/manual/lexing.txt @@ -101,25 +101,28 @@ Two identifiers are considered equal if the following algorithm returns true: .. code-block:: nim proc sameIdentifier(a, b: string): bool = - a[0] == b[0] and a.replace("_", "").toLower == b.replace("_", "").toLower + a[0] == b[0] and + a.replace(re"_|–", "").toLower == b.replace(re"_|–", "").toLower That means only the first letters are compared in a case sensitive manner. Other -letters are compared case insensitively and underscores are ignored. +letters are compared case insensitively and underscores and en-dash (Unicode +point U+2013) are ignored. -This rather strange way to do identifier comparisons is called +This rather unorthodox way to do identifier comparisons is called `partial case insensitivity`:idx: and has some advantages over the conventional case sensitivity: It allows programmers to mostly use their own preferred -spelling style and libraries written by different programmers cannot use -incompatible conventions. A Nim-aware editor or IDE can show the identifiers as -preferred. Another advantage is that it frees the programmer from remembering +spelling style, be it humpStyle, snake_style or dash–style and libraries written +by different programmers cannot use incompatible conventions. +A Nim-aware editor or IDE can show the identifiers as preferred. +Another advantage is that it frees the programmer from remembering the exact spelling of an identifier. The exception with respect to the first letter allows common code like ``var foo: Foo`` to be parsed unambiguously. -Historically, Nim was a `style-insensitive`:idx: language. This means that it -was not case-sensitive and underscores were ignored and there was no distinction -between ``foo`` and ``Foo``. +Historically, Nim was a fully `style-insensitive`:idx: language. This meant that +it was not case-sensitive and underscores were ignored and there was no even a +distinction between ``foo`` and ``Foo``. String literals @@ -345,6 +348,12 @@ notation: ``0B0_10001110100_0000101001000111101011101111111011000101001101001001'f64`` is approximately 1.72826e35 according to the IEEE floating point standard. +Literals are bounds checked so that they fit the datatype. Non base-10 +literals are used mainly for flags and bit pattern representations, therefore +bounds checking is done on bit width, not value range. If the literal fits in +the bit width of the datatype, it is accepted. +Hence: 0b10000000'u8 == 0x80'u8 == 128, but, 0b10000000'i8 == 0x80'i8 == -1 +instead of causing an overflow error. Operators --------- diff --git a/doc/manual/modules.txt b/doc/manual/modules.txt index fe3360773..813505769 100644 --- a/doc/manual/modules.txt +++ b/doc/manual/modules.txt @@ -146,6 +146,14 @@ modules don't need to import a module's dependencies: var x: MyObject echo($x) +Note on paths +----------- +In module related statements, if any part of the module name / +path begins with a number, you may have to quote it in double quotes. +In the following example, it would be seen as a literal number '3.0' of type +'float64' if not quoted, if uncertain - quote it: +.. code-block:: nim + import "gfx/3d/somemodule" Scope rules ----------- From 2f68b0baf0c7b70c511a9988640ebd946f2408c0 Mon Sep 17 00:00:00 2001 From: Dominik Picheta Date: Sun, 14 Jun 2015 18:51:06 +0100 Subject: [PATCH 0453/1263] Introduce gPrefixDir for nimsuggest. --- compiler/options.nim | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/compiler/options.nim b/compiler/options.nim index 48e2db0c7..42a13f8e8 100644 --- a/compiler/options.nim +++ b/compiler/options.nim @@ -146,6 +146,7 @@ const var gConfigVars* = newStringTable(modeStyleInsensitive) gDllOverrides = newStringTable(modeCaseInsensitive) + gPrefixDir* = "" # Overrides the default prefix dir in getPrefixDir proc. libpath* = "" gProjectName* = "" # holds a name like 'nimrod' gProjectPath* = "" # holds a path like /home/alice/projects/nimrod/compiler/ @@ -184,8 +185,13 @@ proc getOutFile*(filename, ext: string): string = else: result = changeFileExt(filename, ext) proc getPrefixDir*(): string = - ## gets the application directory - result = splitPath(getAppDir()).head + ## Gets the prefix dir, usually the parent directory where the binary resides. + ## + ## This is overrided by some tools (namely nimsuggest) via the ``gPrefixDir`` + ## global. + if gPrefixDir != "": result = gPrefixDir + else: + result = splitPath(getAppDir()).head proc canonicalizePath*(path: string): string = when not FileSystemCaseSensitive: result = path.expandFilename.toLower From 059b05a804b50a590fd0d02894a599e86e9f47d0 Mon Sep 17 00:00:00 2001 From: Vlad Date: Sun, 14 Jun 2015 21:42:43 +0300 Subject: [PATCH 0454/1263] fixed #1985 --- lib/pure/os.nim | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/pure/os.nim b/lib/pure/os.nim index 4deb79f86..f29505590 100644 --- a/lib/pure/os.nim +++ b/lib/pure/os.nim @@ -1304,7 +1304,9 @@ iterator walkDir*(dir: string): tuple[kind: PathComponent, path: string] {. when defined(linux) or defined(macosx) or defined(bsd): if x.d_type != DT_UNKNOWN: if x.d_type == DT_DIR: k = pcDir - if x.d_type == DT_LNK: k = succ(k) + if x.d_type == DT_LNK: + if dirExists(y): k = pcLinkToDir + else: k = succ(k) yield (k, y) continue From 0e4e187476ce54aef699d0767c5fe3574688eba4 Mon Sep 17 00:00:00 2001 From: Dominik Picheta Date: Sun, 14 Jun 2015 20:19:49 +0100 Subject: [PATCH 0455/1263] Use full file path for CRC checks. Ref nim-lang/nimsuggest#6. Ref nim-lang/nimsuggest#4. --- compiler/modules.nim | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/compiler/modules.nim b/compiler/modules.nim index 6cb14c091..dcba5cf3d 100644 --- a/compiler/modules.nim +++ b/compiler/modules.nim @@ -51,19 +51,19 @@ proc crcChanged(fileIdx: int32): bool = of crcNotChanged: result = false of crcCached: - let newCrc = secureHashFile(fileIdx.toFilename) + let newCrc = secureHashFile(fileIdx.toFullPath) result = newCrc != gMemCacheData[fileIdx].crc gMemCacheData[fileIdx].crc = newCrc updateStatus() of crcNotTaken: - gMemCacheData[fileIdx].crc = secureHashFile(fileIdx.toFilename) + gMemCacheData[fileIdx].crc = secureHashFile(fileIdx.toFullPath) result = true updateStatus() proc doCRC(fileIdx: int32) = if gMemCacheData[fileIdx].crcStatus == crcNotTaken: # echo "FIRST CRC: ", fileIdx.ToFilename - gMemCacheData[fileIdx].crc = secureHashFile(fileIdx.toFilename) + gMemCacheData[fileIdx].crc = secureHashFile(fileIdx.toFullPath) proc addDep(x: PSym, dep: int32) = growCache gMemCacheData, dep From 1452edfbb9d7de1d654248cc709a7436d8d404c2 Mon Sep 17 00:00:00 2001 From: Araq Date: Thu, 11 Jun 2015 15:17:28 +0200 Subject: [PATCH 0456/1263] better test program --- tests/parallel/tptr_to_ref.nim | 53 +++++++++++++++++++++++++++++++--- 1 file changed, 49 insertions(+), 4 deletions(-) diff --git a/tests/parallel/tptr_to_ref.nim b/tests/parallel/tptr_to_ref.nim index 66d618481..229c247ce 100644 --- a/tests/parallel/tptr_to_ref.nim +++ b/tests/parallel/tptr_to_ref.nim @@ -1,21 +1,26 @@ # bug #2854 +# Test case for the compiler correctly detecting if a type used by a shared +# global is gcsafe. + import locks, threadpool, osproc -const MAX_WORKERS = 10 +const MAX_WORKERS = 50 type - Killer = object - lock: Lock - bailed {.guard: lock.}: bool + Killer* = object + lock: Lock + bailed {.guard: lock.}: bool processes {.guard: lock.}: array[0..MAX_WORKERS-1, foreign ptr Process] +# Hold a lock for a statement. template hold(lock: Lock, body: stmt) = lock.acquire defer: lock.release {.locks: [lock].}: body +# Return an initialized Killer. proc initKiller*(): Killer = initLock(result.lock) result.lock.hold: @@ -23,4 +28,44 @@ proc initKiller*(): Killer = for i, _ in result.processes: result.processes[i] = nil +# Global Killer instance. var killer = initKiller() + +# remember that a process has been launched, killing it if we have bailed. +proc launched*(process: foreign ptr Process): int {.gcsafe.} = + result = killer.processes.high + 1 + killer.lock.hold: + if killer.bailed: + process[].terminate() + else: + for i, _ in killer.processes: + if killer.processes[i] == nil: + killer.processes[i] = process + result = i + assert(result <= killer.processes.high) + + +# A process has been finished with - remove the process from death row. +# Return true if the process was still present, which will be the +# case unless we have bailed. +proc completed*(index: int): bool {.gcsafe.} = + result = true + if index <= killer.processes.high: + killer.lock.hold: + result = false + if killer.processes[index] != nil: + result = true + killer.processes[index] = nil + + +# Terminate all the processes killer knows about, doing nothing if +# already bailed. +proc bail(): bool {.gcsafe.} = + killer.lock.hold: + result = not killer.bailed + if not killer.bailed: + killer.bailed = true + for i, process in killer.processes: + if process != nil: + process[].terminate + killer.processes[i] = nil From 8d39669233880870a1c744e165a8510f5cc8d3c5 Mon Sep 17 00:00:00 2001 From: Araq Date: Mon, 15 Jun 2015 00:56:20 +0200 Subject: [PATCH 0457/1263] fixes #2909 --- compiler/ccgexprs.nim | 8 ++++++- compiler/condsyms.nim | 1 + compiler/lexer.nim | 12 ++++------ lib/pure/parseutils.nim | 32 ++++++++++++------------- lib/system.nim | 53 ++++++++++++++++++++++++++++++++--------- lib/system/arithm.nim | 2 +- 6 files changed, 71 insertions(+), 37 deletions(-) diff --git a/compiler/ccgexprs.nim b/compiler/ccgexprs.nim index 862776740..55fa7564c 100644 --- a/compiler/ccgexprs.nim +++ b/compiler/ccgexprs.nim @@ -504,6 +504,11 @@ proc binaryArithOverflow(p: BProc, e: PNode, d: var TLoc, m: TMagic) = "$# = #mulInt($#, $#);$n", "$# = #divInt($#, $#);$n", "$# = #modInt($#, $#);$n", "$# = #addInt($#, $#);$n", "$# = #subInt($#, $#);$n"] + prc64: array[mAddI..mPred, string] = [ + "$# = #addInt64($#, $#);$n", "$# = #subInt64($#, $#);$n", + "$# = #mulInt64($#, $#);$n", "$# = #divInt64($#, $#);$n", + "$# = #modInt64($#, $#);$n", + "$# = #addInt64($#, $#);$n", "$# = #subInt64($#, $#);$n"] opr: array[mAddI..mPred, string] = [ "($#)($# + $#)", "($#)($# - $#)", "($#)($# * $#)", "($#)($# / $#)", "($#)($# % $#)", @@ -520,7 +525,8 @@ proc binaryArithOverflow(p: BProc, e: PNode, d: var TLoc, m: TMagic) = let res = opr[m] % [getTypeDesc(p.module, t), rdLoc(a), rdLoc(b)] putIntoDest(p, d, e.typ, res) else: - let res = binaryArithOverflowRaw(p, t, a, b, prc[m]) + let res = binaryArithOverflowRaw(p, t, a, b, + if t.kind == tyInt64: prc64[m] else: prc[m]) putIntoDest(p, d, e.typ, "($#)($#)" % [getTypeDesc(p.module, t), res]) proc unaryArithOverflow(p: BProc, e: PNode, d: var TLoc, m: TMagic) = diff --git a/compiler/condsyms.nim b/compiler/condsyms.nim index ad7d80c85..34322471f 100644 --- a/compiler/condsyms.nim +++ b/compiler/condsyms.nim @@ -88,3 +88,4 @@ proc initDefines*() = defineSymbol("nimalias") defineSymbol("nimlocks") defineSymbol("nimnode") + defineSymbol("nimnomagic64") diff --git a/compiler/lexer.nim b/compiler/lexer.nim index 5c7baf7d3..cea42ad1e 100644 --- a/compiler/lexer.nim +++ b/compiler/lexer.nim @@ -262,10 +262,6 @@ template eatChar(L: var TLexer, t: var TToken) = add(t.literal, L.buf[L.bufpos]) inc(L.bufpos) - - - - proc getNumber(L: var TLexer): TToken = proc matchUnderscoreChars(L: var TLexer, tok: var TToken, chars: set[char]) = var pos = L.bufpos # use registers for pos, buf @@ -483,7 +479,7 @@ proc getNumber(L: var TLexer): TToken = else: internalError(getLineInfo(L), "getNumber") # Bounds checks. Non decimal literals are allowed to overflow the range of - # the datatype as long as their pattern don't overflow _bitwise_, hence + # the datatype as long as their pattern don't overflow _bitwise_, hence # below checks of signed sizes against uint*.high is deliberate: # (0x80'u8 = 128, 0x80'i8 = -128, etc == OK) if result.tokType notin floatTypes: @@ -495,7 +491,7 @@ proc getNumber(L: var TLexer): TToken = else: false if outOfRange: - echo "out of range num: ", result.iNumber, " vs ", xi + #echo "out of range num: ", result.iNumber, " vs ", xi lexMessageLitNum(L, errNumberOutOfRange, startpos) else: @@ -528,8 +524,8 @@ proc getNumber(L: var TLexer): TToken = # Promote int literal to int64? Not always necessary, but more consistent if result.tokType == tkIntLit: - if (result.iNumber < low(int32)) or (result.iNumber > high(int32)): - result.tokType = tkInt64Lit + if (result.iNumber < low(int32)) or (result.iNumber > high(int32)): + result.tokType = tkInt64Lit except ValueError: lexMessageLitNum(L, errInvalidNumber, startpos) diff --git a/lib/pure/parseutils.nim b/lib/pure/parseutils.nim index c07b713de..b3708838a 100644 --- a/lib/pure/parseutils.nim +++ b/lib/pure/parseutils.nim @@ -26,7 +26,7 @@ proc toLower(c: char): char {.inline.} = result = if c in {'A'..'Z'}: chr(ord(c)-ord('A')+ord('a')) else: c proc parseHex*(s: string, number: var int, start = 0): int {. - rtl, extern: "npuParseHex", noSideEffect.} = + rtl, extern: "npuParseHex", noSideEffect.} = ## Parses a hexadecimal number and stores its value in ``number``. ## ## Returns the number of the parsed characters or 0 in case of an error. This @@ -49,7 +49,7 @@ proc parseHex*(s: string, number: var int, start = 0): int {. var foundDigit = false if s[i] == '0' and (s[i+1] == 'x' or s[i+1] == 'X'): inc(i, 2) elif s[i] == '#': inc(i) - while true: + while true: case s[i] of '_': discard of '0'..'9': @@ -66,13 +66,13 @@ proc parseHex*(s: string, number: var int, start = 0): int {. if foundDigit: result = i-start proc parseOct*(s: string, number: var int, start = 0): int {. - rtl, extern: "npuParseOct", noSideEffect.} = + rtl, extern: "npuParseOct", noSideEffect.} = ## parses an octal number and stores its value in ``number``. Returns ## the number of the parsed characters or 0 in case of an error. var i = start var foundDigit = false if s[i] == '0' and (s[i+1] == 'o' or s[i+1] == 'O'): inc(i, 2) - while true: + while true: case s[i] of '_': discard of '0'..'7': @@ -93,7 +93,7 @@ proc parseIdent*(s: string, ident: var string, start = 0): int = result = i-start proc parseIdent*(s: string, start = 0): string = - ## parses an identifier and stores it in ``ident``. + ## parses an identifier and stores it in ``ident``. ## Returns the parsed identifier or an empty string in case of an error. result = "" var i = start @@ -101,14 +101,14 @@ proc parseIdent*(s: string, start = 0): string = if s[i] in IdentStartChars: inc(i) while s[i] in IdentChars: inc(i) - + result = substr(s, start, i-1) proc parseToken*(s: string, token: var string, validChars: set[char], start = 0): int {.inline, deprecated.} = ## parses a token and stores it in ``token``. Returns ## the number of the parsed characters or 0 in case of an error. A token - ## consists of the characters in `validChars`. + ## consists of the characters in `validChars`. ## ## **Deprecated since version 0.8.12**: Use ``parseWhile`` instead. var i = start @@ -126,13 +126,13 @@ proc skip*(s, token: string, start = 0): int {.inline.} = ## or 0 if there was no `token` at ``s[start]``. while result < token.len and s[result+start] == token[result]: inc(result) if result != token.len: result = 0 - + proc skipIgnoreCase*(s, token: string, start = 0): int = ## same as `skip` but case is ignored for token matching. while result < token.len and toLower(s[result+start]) == toLower(token[result]): inc(result) if result != token.len: result = 0 - + proc skipUntil*(s: string, until: set[char], start = 0): int {.inline.} = ## Skips all characters until one char from the set `until` is found ## or the end is reached. @@ -154,7 +154,7 @@ proc parseUntil*(s: string, token: var string, until: set[char], start = 0): int {.inline.} = ## parses a token and stores it in ``token``. Returns ## the number of the parsed characters or 0 in case of an error. A token - ## consists of the characters notin `until`. + ## consists of the characters notin `until`. var i = start while i < s.len and s[i] notin until: inc(i) result = i-start @@ -174,7 +174,7 @@ proc parseWhile*(s: string, token: var string, validChars: set[char], start = 0): int {.inline.} = ## parses a token and stores it in ``token``. Returns ## the number of the parsed characters or 0 in case of an error. A token - ## consists of the characters in `validChars`. + ## consists of the characters in `validChars`. var i = start while s[i] in validChars: inc(i) result = i-start @@ -214,7 +214,7 @@ proc parseBiggestInt*(s: string, number: var BiggestInt, start = 0): int {. ## `EOverflow` is raised if an overflow occurs. var res: BiggestInt # use 'res' for exception safety (don't write to 'number' in case of an - # overflow exception: + # overflow exception): result = rawParseInt(s, res, start) number = res @@ -246,7 +246,7 @@ proc parseFloat*(s: string, number: var float, start = 0): int {. result = parseBiggestFloat(s, bf, start) if result != 0: number = bf - + type InterpolatedKind* = enum ## describes for `interpolatedFragments` ## which part of the interpolated string is @@ -289,12 +289,12 @@ iterator interpolatedFragments*(s: string): tuple[kind: InterpolatedKind, case s[j] of '{': inc nesting of '}': - if nesting == 0: + if nesting == 0: inc j break dec nesting of '\0': - raise newException(ValueError, + raise newException(ValueError, "Expected closing '}': " & substr(s, i, s.high)) else: discard inc j @@ -310,7 +310,7 @@ iterator interpolatedFragments*(s: string): tuple[kind: InterpolatedKind, inc i # skip $ kind = ikDollar else: - raise newException(ValueError, + raise newException(ValueError, "Unable to parse a varible name at " & substr(s, i, s.high)) else: while j < s.len and s[j] != '$': inc j diff --git a/lib/system.nim b/lib/system.nim index 2204a5436..62c024d77 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -677,35 +677,50 @@ proc `not` *(x: int): int {.magic: "BitnotI", noSideEffect.} proc `not` *(x: int8): int8 {.magic: "BitnotI", noSideEffect.} proc `not` *(x: int16): int16 {.magic: "BitnotI", noSideEffect.} proc `not` *(x: int32): int32 {.magic: "BitnotI", noSideEffect.} -proc `not` *(x: int64): int64 {.magic: "BitnotI", noSideEffect.} ## computes the `bitwise complement` of the integer `x`. +when defined(nimnomagic64): + proc `not` *(x: int64): int64 {.magic: "BitnotI", noSideEffect.} +else: + proc `not` *(x: int64): int64 {.magic: "BitnotI64", noSideEffect.} + proc `+` *(x, y: int): int {.magic: "AddI", noSideEffect.} proc `+` *(x, y: int8): int8 {.magic: "AddI", noSideEffect.} proc `+` *(x, y: int16): int16 {.magic: "AddI", noSideEffect.} proc `+` *(x, y: int32): int32 {.magic: "AddI", noSideEffect.} -proc `+` *(x, y: int64): int64 {.magic: "AddI", noSideEffect.} ## Binary `+` operator for an integer. +when defined(nimnomagic64): + proc `+` *(x, y: int64): int64 {.magic: "AddI", noSideEffect.} +else: + proc `+` *(x, y: int64): int64 {.magic: "AddI64", noSideEffect.} + proc `-` *(x, y: int): int {.magic: "SubI", noSideEffect.} proc `-` *(x, y: int8): int8 {.magic: "SubI", noSideEffect.} proc `-` *(x, y: int16): int16 {.magic: "SubI", noSideEffect.} proc `-` *(x, y: int32): int32 {.magic: "SubI", noSideEffect.} -proc `-` *(x, y: int64): int64 {.magic: "SubI", noSideEffect.} ## Binary `-` operator for an integer. +when defined(nimnomagic64): + proc `-` *(x, y: int64): int64 {.magic: "SubI", noSideEffect.} +else: + proc `-` *(x, y: int64): int64 {.magic: "SubI64", noSideEffect.} + proc `*` *(x, y: int): int {.magic: "MulI", noSideEffect.} proc `*` *(x, y: int8): int8 {.magic: "MulI", noSideEffect.} proc `*` *(x, y: int16): int16 {.magic: "MulI", noSideEffect.} proc `*` *(x, y: int32): int32 {.magic: "MulI", noSideEffect.} -proc `*` *(x, y: int64): int64 {.magic: "MulI", noSideEffect.} ## Binary `*` operator for an integer. +when defined(nimnomagic64): + proc `*` *(x, y: int64): int64 {.magic: "MulI", noSideEffect.} +else: + proc `*` *(x, y: int64): int64 {.magic: "MulI64", noSideEffect.} + proc `div` *(x, y: int): int {.magic: "DivI", noSideEffect.} proc `div` *(x, y: int8): int8 {.magic: "DivI", noSideEffect.} proc `div` *(x, y: int16): int16 {.magic: "DivI", noSideEffect.} proc `div` *(x, y: int32): int32 {.magic: "DivI", noSideEffect.} -proc `div` *(x, y: int64): int64 {.magic: "DivI", noSideEffect.} ## computes the integer division. This is roughly the same as ## ``floor(x/y)``. ## @@ -714,14 +729,23 @@ proc `div` *(x, y: int64): int64 {.magic: "DivI", noSideEffect.} ## 2 div 2 == 1 ## 3 div 2 == 1 +when defined(nimnomagic64): + proc `div` *(x, y: int64): int64 {.magic: "DivI", noSideEffect.} +else: + proc `div` *(x, y: int64): int64 {.magic: "DivI64", noSideEffect.} + proc `mod` *(x, y: int): int {.magic: "ModI", noSideEffect.} proc `mod` *(x, y: int8): int8 {.magic: "ModI", noSideEffect.} proc `mod` *(x, y: int16): int16 {.magic: "ModI", noSideEffect.} proc `mod` *(x, y: int32): int32 {.magic: "ModI", noSideEffect.} -proc `mod` *(x, y: int64): int64 {.magic: "ModI", noSideEffect.} ## computes the integer modulo operation. This is the same as ## ``x - (x div y) * y``. +when defined(nimnomagic64): + proc `mod` *(x, y: int64): int64 {.magic: "ModI", noSideEffect.} +else: + proc `mod` *(x, y: int64): int64 {.magic: "ModI64", noSideEffect.} + proc `shr` *(x, y: int): int {.magic: "ShrI", noSideEffect.} proc `shr` *(x, y: int8): int8 {.magic: "ShrI", noSideEffect.} proc `shr` *(x, y: int16): int16 {.magic: "ShrI", noSideEffect.} @@ -2304,11 +2328,18 @@ proc abs*(x: int16): int16 {.magic: "AbsI", noSideEffect.} = if x < 0: -x else: x proc abs*(x: int32): int32 {.magic: "AbsI", noSideEffect.} = if x < 0: -x else: x -proc abs*(x: int64): int64 {.magic: "AbsI", noSideEffect.} = - ## returns the absolute value of `x`. If `x` is ``low(x)`` (that - ## is -MININT for its type), an overflow exception is thrown (if overflow - ## checking is turned on). - if x < 0: -x else: x +when defined(nimnomagic64): + proc abs*(x: int64): int64 {.magic: "AbsI", noSideEffect.} = + ## returns the absolute value of `x`. If `x` is ``low(x)`` (that + ## is -MININT for its type), an overflow exception is thrown (if overflow + ## checking is turned on). + if x < 0: -x else: x +else: + proc abs*(x: int64): int64 {.magic: "AbsI64", noSideEffect.} = + ## returns the absolute value of `x`. If `x` is ``low(x)`` (that + ## is -MININT for its type), an overflow exception is thrown (if overflow + ## checking is turned on). + if x < 0: -x else: x {.pop.} when not defined(JS): #and not defined(NimrodVM): diff --git a/lib/system/arithm.nim b/lib/system/arithm.nim index 907907e24..69c558799 100644 --- a/lib/system/arithm.nim +++ b/lib/system/arithm.nim @@ -18,7 +18,7 @@ proc raiseDivByZero {.compilerproc, noinline.} = sysFatal(DivByZeroError, "division by zero") when defined(builtinOverflow): -# Builtin compiler functions for improved performance + # Builtin compiler functions for improved performance when sizeof(clong) == 8: proc addInt64Overflow[T: int64|int](a, b: T, c: var T): bool {. importc: "__builtin_saddl_overflow", nodecl, nosideeffect.} From d6f94091ed467e9208ff4f43f565eef3ac195982 Mon Sep 17 00:00:00 2001 From: Araq Date: Mon, 15 Jun 2015 01:22:12 +0200 Subject: [PATCH 0458/1263] fixes #2904 --- web/news.txt | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/web/news.txt b/web/news.txt index 49b49a9f1..bf21dff8d 100644 --- a/web/news.txt +++ b/web/news.txt @@ -3,7 +3,7 @@ News ==== .. - 2015-05-05 Version 0.11.2 released + 2015-05-05 Version 0.11.4 released ================================== Changes affecting backwards compatibility @@ -17,6 +17,11 @@ News their arguments just like ``echo`` does. Affected functions: ``log``, ``debug``, ``info``, ``warn``, ``error``, ``fatal``. Custom subtypes of ``Logger`` also need to be adjusted accordingly. + - Floating point numbers can now look like ``2d`` (float64) + and ``2f`` (float32) which means imports like ``import scene/2d/sprite`` + do not work anymore. Instead quotes have to be + used: ``import "scene/2d/sprite"``. The former code never was valid Nim. + Library additions ----------------- From 8c671d22d6a7c55e13e7c02eb4fd65bbabb52131 Mon Sep 17 00:00:00 2001 From: Araq Date: Mon, 15 Jun 2015 01:30:25 +0200 Subject: [PATCH 0459/1263] website knows about new URLs --- install.txt | 14 +++++++------- readme.txt | 10 +++++----- web/community.txt | 18 +++++++++--------- web/download.txt | 2 +- web/index.txt | 2 +- web/learn.txt | 2 +- 6 files changed, 24 insertions(+), 24 deletions(-) diff --git a/install.txt b/install.txt index deca55599..efd60f9aa 100644 --- a/install.txt +++ b/install.txt @@ -9,10 +9,10 @@ should be in your ``$PATH`` (most likely the case). Note that some few Linux distributions do not ship with a GCC compiler preinstalled - then you have to install it. -Install Nim by downloading the appropriate ``.zip`` file and extracting it +Install Nim by downloading the appropriate ``.zip`` file and extracting it to a directory of your choice. The Nim Compiler will stay in this -directory (unless you copy it somewhere else). The compiler does not need -write access to its directory, so copying the nim folder to ``/opt`` +directory (unless you copy it somewhere else). The compiler does not need +write access to its directory, so copying the nim folder to ``/opt`` works. Then run the following command:: @@ -26,7 +26,7 @@ manually. An alternative is to create a symbolic link in ``/usr/bin``:: [sudo] ln -s $your_install_dir/bin/nim /usr/bin/nim -There are also ``install.sh`` and ``deinstall.sh`` scripts for distributing +There are also ``install.sh`` and ``deinstall.sh`` scripts for distributing the files over the UNIX hierarchy. However, updating your Nim installation is more cumbersome then. @@ -35,8 +35,8 @@ Installation on the Macintosh ----------------------------- Only MacOS X is supported. -Since MacOS X is UNIX based too, it works like the installation on Linux. -However, for unknown reasons the symbolic link method does not work on MacOS X. +Since MacOS X is UNIX based too, it works like the installation on Linux. +However, for unknown reasons the symbolic link method does not work on MacOS X. You need to install Apple's developer's tools for the GNU Compiler Collection. @@ -64,5 +64,5 @@ However, most testing is done with GCC. Bootstrapping from Github ------------------------- -Take a look at the readme file on github `here `_ +Take a look at the readme file on github `here `_ for instructions. diff --git a/readme.txt b/readme.txt index e3119f83d..595c70bf2 100644 --- a/readme.txt +++ b/readme.txt @@ -1,4 +1,4 @@ -This package contains the Nim compiler, Nim's stdlib, tools and +This package contains the Nim compiler, Nim's stdlib, tools and documentation. Nim is a compiled, garbage-collected systems programming language which has @@ -7,12 +7,12 @@ efficiency, expressiveness, elegance (in the order of priority). Read install.txt for instructions of how to build and install it. -The compiler and the standard library are licensed under the MIT license, -except for some modules where the documentation suggests otherwise. This means -that you can use any license for your own programs developed with Nim, +The compiler and the standard library are licensed under the MIT license, +except for some modules where the documentation suggests otherwise. This means +that you can use any license for your own programs developed with Nim, allowing you to create commercial applications. Read copying.txt for more details. -Copyright (c) 2006-2014 Andreas Rumpf. +Copyright (c) 2006-2015 Andreas Rumpf. All rights reserved. diff --git a/web/community.txt b/web/community.txt index 5d9343c98..12d024871 100644 --- a/web/community.txt +++ b/web/community.txt @@ -6,7 +6,7 @@ Nim's Community Forum ----- - The `Nim forum `_ is the place where most + The `Nim forum `_ is the place where most discussions related to the language happen. It not only includes discussions relating to the design of Nim but also allows for beginners to ask questions relating to Nim. @@ -44,14 +44,14 @@ Nim's Community Github ------ - Nim's `source code `_ is hosted on Github. - Together with the `wiki `_ and - `issue tracker `_. + Nim's `source code `_ is hosted on Github. + Together with the `wiki `_ and + `issue tracker `_. Github also hosts other projects relating to Nim. These projects are a part of the `nim-lang organisation `_. This includes the `Nimble package manager `_ - and its `package repository `_. + and its `package repository `_. .. container:: standout @@ -76,7 +76,7 @@ Nim's Community ------------- When asking a question relating to Nim, be sure to use the - `Nim `_ tag in your + `Nim `_ tag in your question. .. container:: standout @@ -85,8 +85,8 @@ Nim's Community ----------- There are always many things to be done in the main - `Nim repository `_, check out the - `issues `_ for + `Nim repository `_, check out the + `issues `_ for things to do; pull requests are always welcome. You can also contribute to the many other projects hosted by the `nim-lang `_ organisation on github. If you @@ -107,7 +107,7 @@ Nim's Community .. raw:: html Paypal diff --git a/web/download.txt b/web/download.txt index 6acc80b53..c193637b7 100644 --- a/web/download.txt +++ b/web/download.txt @@ -44,7 +44,7 @@ Installation from github Use the following commands to build the compiler from source. Change the branch to suit your needs:: - git clone -b master git://github.com/Araq/Nim.git + git clone -b master git://github.com/nim-lang/Nim.git cd Nim git clone -b master --depth 1 git://github.com/nim-lang/csources cd csources && sh build.sh diff --git a/web/index.txt b/web/index.txt index 95cac9316..506453423 100644 --- a/web/index.txt +++ b/web/index.txt @@ -85,5 +85,5 @@ Roadmap to 1.0 ============== Please have a look at -this `wiki page `_ for +this `wiki page `_ for an up-to-date overview. diff --git a/web/learn.txt b/web/learn.txt index bf0cc43ef..e1a3f1c8c 100644 --- a/web/learn.txt +++ b/web/learn.txt @@ -28,7 +28,7 @@ Learning Nim - | `Nim on Rosetta Code `_ | Many different Nim code examples comparable to other languages for reference. - - | `Nim for C/C++ Programmers `_ + - | `Nim for C/C++ Programmers `_ | A useful cheat-sheet for those most familiar with C/C++ languages. From 4072a39c69f2711683604c94884b1536a7bd5c41 Mon Sep 17 00:00:00 2001 From: apense Date: Sun, 14 Jun 2015 21:16:39 -0400 Subject: [PATCH 0460/1263] Updated RNG for Visual C Can't test it, but it should work just fine. Can be extended to MinGW w/ GCC and other compilers sometime in the future --- lib/pure/math.nim | 41 +++++++++++++++++++++++++++-------------- 1 file changed, 27 insertions(+), 14 deletions(-) diff --git a/lib/pure/math.nim b/lib/pure/math.nim index 34070dd91..b91c7f0d8 100644 --- a/lib/pure/math.nim +++ b/lib/pure/math.nim @@ -202,9 +202,11 @@ when not defined(JS): ## computes x to power raised of y. # C procs: - when defined(windows): + when defined(vcc): # The "secure" random, available from Windows XP # https://msdn.microsoft.com/en-us/library/sxtz2fa8.aspx + # Present in some variants of MinGW but not enough to justify + # `when defined(windows)` yet proc rand_s(val: var cuint) {.importc: "rand_s", header: "".} # To behave like the normal version proc rand(): cuint = rand_s(result) @@ -217,23 +219,34 @@ when not defined(JS): proc drand48(): float {.importc: "drand48", header: "".} proc random(max: float): float = result = drand48() * max + else: + when defined(vcc): # Windows with Visual C + proc random(max: float): float = + # we are hardcoding this because + # importc-ing macros is extremely problematic + # and because the value is publicly documented + # on MSDN and very unlikely to change + # See https://msdn.microsoft.com/en-us/library/296az74e.aspx + const rand_max = 4294967295 # UINT_MAX + result = (float(rand()) / float(rand_max)) * max + proc randomize() = discard + proc randomize(seed: int) = discard + else: # Windows with another compiler + proc random(max: float): float = + # we are hardcoding this because + # importc-ing macros is extremely problematic + # and because the value is publicly documented + # on MSDN and very unlikely to change + const rand_max = 32767 + result = (float(rand()) / float(rand_max)) * max + + when not defined(vcc): # the above code for vcc uses `discard` instead + # this is either not Windows or is Windows without vcc proc randomize() = randomize(cast[int](epochTime())) - proc randomize(seed: int) = srand(cint(seed)) # rand_s doesn't use srand - srand48(seed) - when defined(windows): - proc random(max: float): float = - # we are hardcodeing this because - # importcing macros is extremely problematic - # and because the value is publicly documented - # on MSDN and very unlikely to change - # See https://msdn.microsoft.com/en-us/library/296az74e.aspx - const rand_max = 4294967295 - result = (float(rand()) / float(rand_max)) * max - proc randomize() = discard - proc randomize(seed: int) = discard + when declared(srand48): srand48(seed) proc random(max: int): int = result = int(rand()) mod max From d4dd332c8d1767f411e2bed88b320aa698cbd396 Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Sun, 14 Jun 2015 20:57:21 -0500 Subject: [PATCH 0461/1263] initial draft for contributing.md --- contributing.md | 101 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 contributing.md diff --git a/contributing.md b/contributing.md new file mode 100644 index 000000000..9c589ae49 --- /dev/null +++ b/contributing.md @@ -0,0 +1,101 @@ +# The git stuff + +[Guide by github, scroll down a bit](https://guides.github.com/activities/contributing-to-open-source/) + +# Deprecation + +Backward compatibility is important, so if you are renaming a proc or +a type, you can use + +```nim +{.deprecated [oldName: new_name].} +``` + +Or you can simply use + +```nim +proc oldProc() {.deprecated.} +``` + +to mark a symbol as deprecated. Works for procs/types/vars/consts, +etc. + +[Deprecated pragma in the manual.](http://nim-lang.org/docs/manual.html#pragmas-deprecated-pragma) + +# Writing tests + +Not all the tests follow this scheme, feel free to change the ones +that don't. Always leave the code cleaner than you found it. + +## Stdlib + +If you change the stdlib (anything under `lib/`), put a test in the +file you changed. Add the tests under an `when isMainModule:` +condition so they only get executed when the tester is building the +file. Each test should be in a separate `block:` statement, such that +each has its own scope. Use boolean conditions and `assert` for the +testing by itself, don't rely on echo statements or similar. + +Sample test: + +```nim +when isMainModule: + block lenTest: + var values: HashSet[int] + assert(not values.isValid) + assert values.len == 0 + assert values.card == 0 + block setIterator: + type pair = tuple[a, b: int] + var a, b = initSet[pair]() + a.incl((2, 3)) + a.incl((3, 2)) + a.incl((2, 3)) + for x, y in a.items: + b.incl((x - 2, y + 1)) + assert a.len == b.card + assert a.len == 2 +``` + +## Compiler + +The tests for the compiler work differently, they are all located in +`tests/`. Each test has its own file, which is different from the +stdlib tests. At the beginning of every test is the expected side of +the test. Possible keys are: + +- output: The expected output, most likely via `echo` +- exitcode: Exit code of the test (via `exit(number)`) +- errormsg: The expected error message +- file: The file the errormsg +- line: The line the errormsg was produced at + +An example for a test: +```nim +discard """ + errormsg: "type mismatch: got (PTest)" +""" + +type + PTest = ref object + +proc test(x: PTest, y: int) = nil + +var buf: PTest +buf.test() +``` + +# Running tests + +You can run the tests with + + ./koch tests + +which will run a good subset of tests. Some tests may fail. + +# Comparing tests + +Because some tests fail in the current `devel` branch, not every fail +after your change is necessarily caused by your changes. + +TODO From 38cb13cde53c9af885c48da87db10e2c19d151bd Mon Sep 17 00:00:00 2001 From: apense Date: Mon, 15 Jun 2015 01:06:55 -0400 Subject: [PATCH 0462/1263] Added some documentation This is a start. Other updates for `macros.nim` are planned, but this at least fleshes out some of the sections. Comments are appreciated! --- doc/astspec.txt | 407 ++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 391 insertions(+), 16 deletions(-) diff --git a/doc/astspec.txt b/doc/astspec.txt index 68bb9f1cd..b3955c634 100644 --- a/doc/astspec.txt +++ b/doc/astspec.txt @@ -90,7 +90,11 @@ Concrete syntax: AST: .. code-block:: nim - nnkCommand(nnkIdent(!"echo"), nnkStrLit("abc"), nnkStrLit("xyz")) + nnkCommand( + nnkIdent(!"echo"), + nnkStrLit("abc"), + nnkStrLit("xyz") + ) Call with ``()`` @@ -104,7 +108,11 @@ Concrete syntax: AST: .. code-block:: nim - nnkCall(nnkIdent(!"echo"), nnkStrLit("abc"), nnkStrLit("xyz")) + nnkCall( + nnkIdent(!"echo"), + nnkStrLit("abc"), + nnkStrLit("xyz") + ) Infix operator call @@ -118,8 +126,53 @@ Concrete syntax: AST: .. code-block:: nim - nnkInfix(nnkIdent(!"&"), nnkStrLit("abc"), nnkStrLit("xyz")) + nnkInfix( + nnkIdent(!"&"), + nnkStrLit("abc"), + nnkStrLit("xyz") + ) +Note that with multiple infix operators, the command is parsed by operator +precedence, with the end result mirroring Reverse Polish Notation. + +Concrete syntax: + +.. code-block:: nim + 5 + 3 * 4 + +AST: + +.. code-block:: nim + nnkInfix( + nnkIdent(!"+"), + nnkIntLit(5), + nnkInfix( + nnkIdent(!"*"), + nnkIntLit(3), + nnkIntLit(4) + ) + ) + +As a side note, if you choose to use infix operators in a prefix form, the AST +behaves as a +[parenthetical function call](./macros.html#calls-expressions-call-with) with +``nnkAccQuoted``, as follows: + +Concrete syntax: + +.. code-block:: nim + `+`(3, 4) + +AST: + +.. code-block:: nim + nnkCall( + nnkAccQuoted( + nnkIdent(!"+") + ), + nnkIntLit(3), + nnkIntLit(4) + ) Prefix operator call -------------------- @@ -132,7 +185,10 @@ Concrete syntax: AST: .. code-block:: nim - nnkPrefix(nnkIdent(!"?"), nnkStrLit("abc")) + nnkPrefix( + nnkIdent(!"?"), + nnkStrLit("abc") + ) Postfix operator call @@ -149,7 +205,10 @@ Concrete syntax: AST: .. code-block:: nim - nnkPostfix(nnkIdent(!"*"), nnkIdent(!"identifier")) + nnkPostfix( + nnkIdent(!"*"), + nnkIdent(!"identifier") + ) Call with named arguments @@ -163,9 +222,14 @@ Concrete syntax: AST: .. code-block:: nim - nnkCall(nnkIdent(!"writeln"), - nnkExprEqExpr(nnkIdent(!"file"), nnkIdent(!"stdout")), - nnkStrLit("hallo")) + nnkCall( + nnkIdent(!"writeln"), + nnkExprEqExpr( + nnkIdent(!"file"), + nnkIdent(!"stdout") + ), + nnkStrLit("hallo") + ) Dereference operator ``[]`` @@ -223,6 +287,9 @@ AST: .. code-block:: nim nnkDotExpr(nnkIdent(!"x"), nnkIdent(!"y")) +If you use Nim's flexible calling syntax (as in ``x.len()``), the result is the +same as above but wrapped in an ``nnkCall``. + Array access operator ``[]`` ---------------------------- @@ -270,6 +337,21 @@ AST: .. code-block:: nim nnkCurly(nnkIntLit(1), nnkIntLit(2), nnkIntLit(3)) +When used as a table constructor, the syntax (and result) is different. + +Concrete syntax: + +.. code-block:: nim + {a: 3, b: 5} + +AST: + +.. code-block:: nim + nnkTableConstr( + nnkExprColonExpr(nnkIdent(!"a"), nnkIntLit(3)), + nnkExprColonExpr(nnkIdent(!"b"), nnkIntLit(5)) + ) + Brackets -------- @@ -290,7 +372,7 @@ AST: Ranges ------ -Ranges occur in set constructors, case statement branches or array slices. +Ranges occur in set constructors, case statement branches, or array slices. Concrete syntax: @@ -322,6 +404,69 @@ AST: nnkElseExpr(expr3) ) +Documentation Comments +---------------------- + +Double-hash (``##``) comments in the code actually have their own format, +but *it doesn't matter what is there*. The AST will only show that a comment +exists, not what it contains. Single-hash (``#``) comments are ignored. + +Concrete syntax: + +.. code-block:: nim + ## This is a comment + ## This is part of the first comment + stmt1 + ## Yet another + +AST: + +.. code-block:: nim + nnkCommentStmt() # only appears once for the first two lines! + stmt1 + nnkCommentStmt() # another nnkCommentStmt because there is another comment + # (separate from the first) + +Pragmas +------- + +One of Nim's cool features is pragmas, which allow fine-tuning of various +aspects of the language. They come in all types, such as adorning procs and +objects, but the standalone ``emit`` pragma shows the basics with the AST. + +Concrete syntax: + +.. code-block:: nim + {.emit: "#include ".} + +AST: + +.. code-block:: nim + nnkPragma( + nnkExprColonExpr( + nnkIdent(!"emit"), + nnkStrLit("#include ") # the "argument" + ) + ) + +As many ``nnkIdent``s appear as there are pragmas between ``{..}``. Note that +the declaration of new pragmas is essentially the same: + +Concrete syntax: + +.. code-block:: nim + {.pragma: cdeclRename, cdecl.} + +AST: + +.. code-block:: nim + nnkPragma( + nnkExprColonExpr( + nnkIdent(!"pragma"), # this is always first when declaring a new pragma + nnkIdent(!"cdeclRename") # the name of the pragma + ), + nnkIdent(!"cdecl") + ) Statements ========== @@ -374,6 +519,8 @@ AST: .. code-block:: nim nnkAsgn(nnkIdent(!"x"), nnkIntLit(42)) +This is not the syntax for assignment when combined with ``var``, ``let``, +or ``const``. Statement list -------------- @@ -499,12 +646,18 @@ Yield statement Like ``return``, but with ``nnkYieldStmt`` kind. +.. code-block:: nim + nnkYieldStmt(expr1) + Discard statement ----------------- Like ``return``, but with ``nnkDiscardStmt`` kind. +.. code-block:: nim + nnkDiscardStmt(expr1) + Continue statement ------------------ @@ -519,46 +672,268 @@ AST: .. code-block:: nim nnkContinueStmt() +Break statement +--------------- + +Concrete syntax: + +.. code-block:: nim + break otherLocation + +AST: + +.. code-block:: nim + nnkBreakStmt(nnkIdent(!"otherLocation")) + +If ``break`` is used without a jump-to location, ``nnkEmpty`` replaces ``nnkIdent``. + +Block statement +--------------- + +Concrete syntax: + +.. code-block:: nim + block name: + +AST: + +.. code-block:: nim + nnkBlockStmt(nnkIdent(!"name"), nnkStmtList(...)) + +A ``block`` doesn't need an name, in which case ``nnkEmpty`` is used. + +Asm statement +------------- + +Concrete syntax: + +.. code-block:: nim + asm """ + some asm + """ + +AST: + +.. code-block:: nim + nnkAsmStmt( + nnkEmpty(), # for pragmas + nnkTripleStrLit("some asm"), + ) + Var section ----------- -To be written. +Concrete syntax: +.. code-block:: nim + var a = 3 + +AST: + +.. code-block:: nim + nnkVarSection( + nnkIdentDefs( + nnkIdent(!"a"), + nnkEmpty(), # or nnkIdent(...) if the variable declares the type + nnkIntLit(3), + ) + ) + +Note that either the second or third (or both) parameters above must exist, +as the compiler needs to know the type somehow (which it can infer from +the given assignment). + +Let section +----------- + +This is equivalent to ``var``, but with ``nnkLetSection`` rather than +``nnkVarSection``. Const section ------------- -To be written. +Concrete syntax: +.. code-block:: nim + const a = 3 + +AST: + +.. code-block:: nim + nnkConstSection( + nnkConstDef( # not nnkConstDefs! + nnkIdent(!"a"), + nnkEmpty(), # or nnkIdent(...) if the variable declares the type + nnkIntLit(3), # required in a const declaration! + ) + ) Type section ------------ -To be written. +Starting with the simplest case, a ``type`` section appears much like ``var`` +and ``const``. + +Concrete syntax: + +.. code-block:: nim + type A = int + +AST: + +.. code-block:: nim + nnkTypeSection( + nnkTypeDef( + nnkIdent(!"A"), + nnkEmpty(), # for pragmas + nnkIdent(!"int") + ) + ) + +If a type section uses generic parameters, they are treated here: + +Concrete syntax: + +.. code-block:: nim + type A[T] = expr1 + +AST: + +.. code-block:: nim + nnkTypeSection( + nnkTypeDef( + nnkIdent(!"A"), + nnkGenericParams( + nnkIdentDefs( + nnkIdent(!"T"), + nnkEmpty(), # if the type is declared with options, like + # ``[T: SomeInteger]``, they are given here + nnkEmpty(), + ) + ) + expr1, + ) + ) Procedure declaration --------------------- -To be written. +Let's take a look at a procedure with a lot of interesting aspects to get +a feel for how procedure calls are broken down. +Concrete syntax: + +.. code-block:: nim + proc hello*[T: SomeInteger](x: int = 3, y: float32): int {.inline.} = discard + +AST: + +.. code-block:: nim + nnkProcDef( + nnkPostfix(nnkIdent(!"*"), nnkIdent(!"hello")), # the exported proc name + nnkEmpty(), # patterns for term rewriting in templates and macros (not procs) + nnkGenericParams( # generic type parameters, like with type declaration + nnkIdentDefs( + nnkIdent(!"T"), nnkIdent(!"SomeInteger") + ) + ), + nnkFormalParams( + nnkIdent(!"int"), # the first FormalParam is the return type. nnkEmpty() if there is none + nnkIdentDefs( + nnkIdent(!"x"), + nnkIdent(!"int"), # type type (required for procs, not for templates) + nnkIntLit(3) # a default value + ), + nnkIdentDefs( + nnkIdent(!"y"), + nnkIdent(!"float32"), + nnkEmpty() + ) + nnkPragma(nnkIdent(!"inline")), + nnkEmpty(), # reserved slot for future use + nnkStmtList(nnkDiscardStmt(nnkEmpty())) # the meat of the proc + ) + ) + +There is another consideration. Nim has flexible type identification for +its procs. Even though ``proc(a: int, b: int)`` and ``proc(a, b: int)`` +are equivalent in the code, the AST is a little different for the latter. + +Concrete syntax: + +.. code-block:: nim + proc(a, b: int) + +AST: + +.. code-block:: nim + # ...AST as above... + nnkFormalParams( + nnkEmpty(), # no return here + nnkIdentDefs( + nnkIdent(!"a"), # the first parameter + nnkIdent(!"b"), # directly to the second parameter + nnkIdent(!"int"), # their shared type identifier + nnkEmpty(), # default value would go here + ) + ), + # ... Iterator declaration -------------------- -To be written. +The syntax for iterators is similar to procs, but with ``nnkIteratorDef`` +replacing ``nnkProcDef``. + +Concrete syntax: + +.. code-block:: nim + iterator nonsense[T](x: seq[T]): float {.closure.} = ... + +AST: + +.. code-block:: nim + nnkIteratorDef( + nnkIdent(!"nonsense"), + nnkEmpty(), + ... + ) Template declaration -------------------- -To be written. +Templates (as well as macros, as we'll see) have a slightly expanded AST when +compared to procs and iterators. The reason for this is [term-rewriting +macros](http://nim-lang.org/docs/manual.html#term-rewriting-macros). Notice +the ``nnkEmpty()`` as the second argument to ``nnkProcDef`` and +``nnkIteratorDef`` above? That's where the term-rewriting macros go. +Concrete syntax: + +.. code-block:: nim + template optOpt{expr1}(a: int): int + +AST: + +.. code-block:: nim + nnkTemplateDef( + nnkIdent(!"optOpt"), + nnkStmtList( # instead of nnkEmpty() + expr1 + ), + # follows like a proc or iterator + ) + +If the template does not have types for its parameters, the type Identifiers +inside ``nnkFormalParams`` just becomes ``nnkEmpty``. Macro declaration ----------------- -To be written. +Macros behave like templates, but ``nnkTemplateDef`` is replaced with +``nnkMacroDef``. Special node kinds From 657d6f9de2d8fc8960fb703f927db2ff2070d5a4 Mon Sep 17 00:00:00 2001 From: Stefan Talpalaru Date: Mon, 15 Jun 2015 08:36:55 +0200 Subject: [PATCH 0463/1263] finalizer support --- lib/system/mmdisp.nim | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/lib/system/mmdisp.nim b/lib/system/mmdisp.nim index 377408f78..ef7b32001 100644 --- a/lib/system/mmdisp.nim +++ b/lib/system/mmdisp.nim @@ -341,11 +341,17 @@ elif defined(gogc): proc goRuntimeMallocGC(size: uint, typ: uint, flag: uint32): pointer {.importc: "runtime_mallocgc", dynlib: goLib.} proc goFree(v: pointer) {.importc: "__go_free", dynlib: goLib.} + proc goSetFinalizer(obj: pointer, f: pointer) {.importc: "set_finalizer", codegenDecl:"$1 $2$3 __asm__ (\"main.Set_finalizer\");\n$1 $2$3", dynlib: goLib.} + proc newObj(typ: PNimType, size: int): pointer {.compilerproc.} = result = goRuntimeMallocGC(roundup(size, sizeof(pointer)).uint, 0.uint, 0.uint32) + if typ.finalizer != nil: + goSetFinalizer(result, typ.finalizer) proc newObjNoInit(typ: PNimType, size: int): pointer = result = goRuntimeMallocGC(roundup(size, sizeof(pointer)).uint, 0.uint, goFlagNoZero) + if typ.finalizer != nil: + goSetFinalizer(result, typ.finalizer) proc newSeq(typ: PNimType, len: int): pointer {.compilerproc.} = result = newObj(typ, len * typ.base.size + GenericSeqSize) From fe0b6d74f58ed8d771b8d9ec44f5e8517fdefc1f Mon Sep 17 00:00:00 2001 From: Stefan Talpalaru Date: Mon, 15 Jun 2015 08:56:07 +0200 Subject: [PATCH 0464/1263] cleanup --- lib/system/mmdisp.nim | 5 ----- 1 file changed, 5 deletions(-) diff --git a/lib/system/mmdisp.nim b/lib/system/mmdisp.nim index 842f29fb7..b6e2ebf53 100644 --- a/lib/system/mmdisp.nim +++ b/lib/system/mmdisp.nim @@ -149,7 +149,6 @@ when defined(boehmgc): proc GC_enableMarkAndSweep() = discard proc GC_disableMarkAndSweep() = discard proc GC_getStatistics(): string = return "" - proc setupForeignThreadGc*() = discard proc getOccupiedMem(): int = return boehmGetHeapSize()-boehmGetFreeBytes() proc getFreeMem(): int = return boehmGetFreeBytes() @@ -287,7 +286,6 @@ elif defined(gogc): "[GC] enablegc: " & $(mstats.enablegc) & "\n" & "[GC] debuggc: " & $(mstats.debuggc) & "\n" & "[GC] total pause time [ms]: " & $(mstats.pause_total_ns div 1000_000) - proc setupForeignThreadGc*() = discard proc getOccupiedMem(): int = var mstats: goMStats @@ -423,7 +421,6 @@ elif defined(nogc) and defined(useMalloc): proc GC_enableMarkAndSweep() = discard proc GC_disableMarkAndSweep() = discard proc GC_getStatistics(): string = return "" - proc setupForeignThreadGc*() = discard proc getOccupiedMem(): int = discard proc getFreeMem(): int = discard @@ -487,8 +484,6 @@ elif defined(nogc): proc GC_enableMarkAndSweep() = discard proc GC_disableMarkAndSweep() = discard proc GC_getStatistics(): string = return "" - proc setupForeignThreadGc*() = discard - proc newObj(typ: PNimType, size: int): pointer {.compilerproc.} = result = alloc0(size) From 8624654c57cd55e49a6d64cc66cb8657dfe9e86d Mon Sep 17 00:00:00 2001 From: Stefan Talpalaru Date: Mon, 15 Jun 2015 09:18:44 +0200 Subject: [PATCH 0465/1263] TMemRegion -> MemRegion --- lib/system/mmdisp.nim | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/lib/system/mmdisp.nim b/lib/system/mmdisp.nim index b6e2ebf53..50f4cb4dc 100644 --- a/lib/system/mmdisp.nim +++ b/lib/system/mmdisp.nim @@ -379,14 +379,15 @@ elif defined(gogc): dest[] = src type - TMemRegion = object {.final, pure.} + MemRegion = object {.final, pure.} + {.deprecated: [TMemRegion: MemRegion].} - proc alloc(r: var TMemRegion, size: int): pointer = + proc alloc(r: var MemRegion, size: int): pointer = result = alloc(size) - proc alloc0(r: var TMemRegion, size: int): pointer = + proc alloc0(r: var MemRegion, size: int): pointer = result = alloc0(size) - proc dealloc(r: var TMemRegion, p: pointer) = dealloc(p) - proc deallocOsPages(r: var TMemRegion) {.inline.} = discard + proc dealloc(r: var MemRegion, p: pointer) = dealloc(p) + proc deallocOsPages(r: var MemRegion) {.inline.} = discard proc deallocOsPages() {.inline.} = discard elif defined(nogc) and defined(useMalloc): From 806dfe976d3771c242b9c6d8702a75773e6c9dab Mon Sep 17 00:00:00 2001 From: Adam Strzelecki Date: Wed, 10 Jun 2015 18:21:40 +0200 Subject: [PATCH 0466/1263] colors: Use colors by default on terminals --- compiler/msgs.nim | 3 +++ 1 file changed, 3 insertions(+) diff --git a/compiler/msgs.nim b/compiler/msgs.nim index 4df4430d7..2d7094e63 100644 --- a/compiler/msgs.nim +++ b/compiler/msgs.nim @@ -907,3 +907,6 @@ ropes.errorHandler = proc (err: RopesError, msg: string, useWarning: bool) = of rCannotOpenFile: rawMessage(if useWarning: warnCannotOpenFile else: errCannotOpenFile, msg) +# enable colors by default on terminals +if terminal.isatty(stdout): + incl(gGlobalOptions, optUseColors) From 1057770ce51c3ede38f743001bcb6e6d4a25d1c2 Mon Sep 17 00:00:00 2001 From: Adam Strzelecki Date: Thu, 11 Jun 2015 21:03:55 +0200 Subject: [PATCH 0467/1263] colors: Introduce resetStyle enum & use templates 1. Introduce TerminalCmd enum and resetStyle that can be issued to issue resetAttributes within styledEcho arguments. 2. Use templates to resolve styledEcho arguments for performance reasons. 3. Try to avoid calling trailing write "\n" and reset attributes where possible. --- lib/pure/terminal.nim | 35 ++++++++++++++++++++++++++++------- 1 file changed, 28 insertions(+), 7 deletions(-) diff --git a/lib/pure/terminal.nim b/lib/pure/terminal.nim index 15e2eefec..2efdf72d5 100644 --- a/lib/pure/terminal.nim +++ b/lib/pure/terminal.nim @@ -406,22 +406,43 @@ proc isatty*(f: File): bool = result = isatty(getFileHandle(f)) != 0'i32 -proc styledEchoProcessArg(s: string) = write stdout, s -proc styledEchoProcessArg(style: Style) = setStyle({style}) -proc styledEchoProcessArg(style: set[Style]) = setStyle style -proc styledEchoProcessArg(color: ForegroundColor) = setForegroundColor color -proc styledEchoProcessArg(color: BackgroundColor) = setBackgroundColor color +type + TerminalCmd* = enum ## commands that can be expressed as arguments + resetStyle ## reset attributes + +template styledEchoProcessArg(s: string) = write stdout, s +template styledEchoProcessArg(style: Style) = setStyle({style}) +template styledEchoProcessArg(style: set[Style]) = setStyle style +template styledEchoProcessArg(color: ForegroundColor) = setForegroundColor color +template styledEchoProcessArg(color: BackgroundColor) = setBackgroundColor color +template styledEchoProcessArg(cmd: TerminalCmd) = + when cmd == resetStyle: + resetAttributes() macro styledEcho*(m: varargs[expr]): stmt = ## to be documented. let m = callsite() + var reset = false result = newNimNode(nnkStmtList) for i in countup(1, m.len - 1): - result.add(newCall(bindSym"styledEchoProcessArg", m[i])) + let item = m[i] + case item.kind + of nnkStrLit..nnkTripleStrLit: + if i == m.len - 1: + # optimize if string literal is last, just call writeln + result.add(newCall(bindSym"writeln", bindSym"stdout", item)) + if reset: result.add(newCall(bindSym"resetAttributes")) + return + else: + # if it is string literal just call write, do not enable reset + result.add(newCall(bindSym"write", bindSym"stdout", item)) + else: + result.add(newCall(bindSym"styledEchoProcessArg", item)) + reset = true result.add(newCall(bindSym"write", bindSym"stdout", newStrLitNode("\n"))) - result.add(newCall(bindSym"resetAttributes")) + if reset: result.add(newCall(bindSym"resetAttributes")) when defined(nimdoc): proc getch*(): char = From 2ba36425447fee5459126aa7da8ebd21b539f187 Mon Sep 17 00:00:00 2001 From: Adam Strzelecki Date: Thu, 11 Jun 2015 21:46:17 +0200 Subject: [PATCH 0468/1263] msgs: styledMsgWriteln compatible with styledEcho 1. Introduce styledMsgWriteln which can be used same way as styledEcho. 2. Make file names and positions use bright white like in other compilers, so only message types are colored. --- compiler/msgs.nim | 143 +++++++++++++++++++++++++++++----------------- 1 file changed, 90 insertions(+), 53 deletions(-) diff --git a/compiler/msgs.nim b/compiler/msgs.nim index 2d7094e63..2edb869d8 100644 --- a/compiler/msgs.nim +++ b/compiler/msgs.nim @@ -8,7 +8,7 @@ # import - options, strutils, os, tables, ropes, platform, terminal + options, strutils, os, tables, ropes, platform, terminal, macros type TMsgKind* = enum @@ -605,13 +605,15 @@ proc suggestQuit*() = # this format is understood by many text editors: it is the same that # Borland and Freepascal use const - PosErrorFormat* = "$1($2, $3) Error: " - PosWarningFormat* = "$1($2, $3) Warning: " - PosHintFormat* = "$1($2, $3) Hint: " - PosContextFormat = "$1($2, $3) Info: " - RawError* = "Error: " - RawWarning* = "Warning: " - RawHint* = "Hint: " + PosFormat = "$1($2, $3) " + ErrorTitle = "Error: " + ErrorColor = fgRed + WarningTitle = "Warning: " + WarningColor = fgYellow + HintTitle = "Hint: " + HintColor = fgGreen + InfoTitle = "Info: " + InfoColor = fgCyan proc getInfoContextLen*(): int = return msgContext.len proc setInfoContextLen*(L: int) = setLen(msgContext, L) @@ -686,27 +688,58 @@ proc outWriteln*(s: string) = ## Writes to stdout. Always. if eStdOut in errorOutputs: writeln(stdout, s) -proc msgWriteln*(s: string, color: ForegroundColor = fgWhite, coloredText: string = "") = - ## Writes to stdout. If --stderr option is given, writes to stderr instead. +proc msgWriteln*(s: string) = + ## Writes to stdout. If --stdout option is given, writes to stderr instead. #if gCmd == cmdIdeTools and optCDebug notin gGlobalOptions: return - var hasColor = optUseColors in gGlobalOptions if not isNil(writelnHook): - writelnHook(coloredText & s) + writelnHook(s) + elif optStdout in gGlobalOptions: + if eStdErr in errorOutputs: writeln(stderr, s) else: - if optStdout in gGlobalOptions: - if eStdErr in errorOutputs: - if hasColor: setForegroundColor(color) - write(stderr, coloredText) - if hasColor: resetAttributes() - writeln(stderr, s) - else: - if eStdOut in errorOutputs: - if hasColor: setForegroundColor(color) - write(stdout, coloredText) - if hasColor: resetAttributes() - writeln(stdout, s) + if eStdOut in errorOutputs: writeln(stdout, s) + +macro callIgnoringStyle(theProc: typed, first: typed, + args: varargs[expr]): stmt = + let typForegroundColor = bindSym"ForegroundColor".getType + let typBackgroundColor = bindSym"BackgroundColor".getType + let typStyle = bindSym"Style".getType + let typTerminalCmd = bindSym"TerminalCmd".getType + result = newCall(theProc) + if first.kind != nnkNilLit: result.add(first) + for arg in children(args[0][1]): + if arg.kind == nnkNilLit: continue + let typ = arg.getType + if typ.kind != nnkEnumTy or + typ != typForegroundColor and + typ != typBackgroundColor and + typ != typStyle and + typ != typTerminalCmd: + result.add(arg) + +macro callStyledEcho(args: varargs[expr]): stmt = + result = newCall(bindSym"styledEcho") + for arg in children(args[0][1]): + result.add(arg) + +template callWritelnHook(args: varargs[string, `$`]) = + var s = "" + for arg in args: + s.add arg + writelnHook s + +template styledMsgWriteln*(args: varargs[expr]) = + if not isNil(writelnHook): + callIgnoringStyle(callWritelnHook, nil, args) + elif optStdout in gGlobalOptions: + if eStdErr in errorOutputs: callIgnoringStyle(writeln, stderr, args) + else: + if eStdOut in errorOutputs: + if optUseColors in gGlobalOptions: + callStyledEcho(args) + else: + callIgnoringStyle(writeln, stdout, args) proc coordToStr(coord: int): string = if coord == -1: result = "???" @@ -728,7 +761,7 @@ proc handleError(msg: TMsgKind, eh: TErrorHandling, s: string) = if stackTraceAvailable() and isNil(writelnHook): writeStackTrace() else: - msgWriteln("", fgRed, "No stack traceback available\nTo create a stacktrace, rerun compilation with ./koch temp " & options.command & " ") + styledMsgWriteln(fgRed, "No stack traceback available\nTo create a stacktrace, rerun compilation with ./koch temp " & options.command & " ") quit 1 if msg >= fatalMin and msg <= fatalMax: @@ -750,10 +783,12 @@ proc writeContext(lastinfo: TLineInfo) = var info = lastinfo for i in countup(0, len(msgContext) - 1): if msgContext[i] != lastinfo and msgContext[i] != info: - msgWriteln(PosContextFormat % [toMsgFilename(msgContext[i]), - coordToStr(msgContext[i].line), - coordToStr(msgContext[i].col+1), - getMessageStr(errInstantiationFrom, "")]) + styledMsgWriteln(styleBright, + PosFormat % [toMsgFilename(msgContext[i]), + coordToStr(msgContext[i].line), + coordToStr(msgContext[i].col+1)], + styleDim, + getMessageStr(errInstantiationFrom, "")) info = msgContext[i] proc ignoreMsgBecauseOfIdeTools(msg: TMsgKind): bool = @@ -761,29 +796,29 @@ proc ignoreMsgBecauseOfIdeTools(msg: TMsgKind): bool = proc rawMessage*(msg: TMsgKind, args: openArray[string]) = var - frmt: string + title: string color: ForegroundColor case msg of errMin..errMax: writeContext(unknownLineInfo()) - frmt = RawError - color = fgRed + title = ErrorTitle + color = ErrorColor of warnMin..warnMax: if optWarns notin gOptions: return if msg notin gNotes: return writeContext(unknownLineInfo()) - frmt = RawWarning + title = WarningTitle + color = WarningColor inc(gWarnCounter) - color = fgYellow of hintMin..hintMax: if optHints notin gOptions: return if msg notin gNotes: return - frmt = RawHint + title = HintTitle + color = HintColor inc(gHintCounter) - color = fgGreen let s = `%`(msgKindToString(msg), args) if not ignoreMsgBecauseOfIdeTools(msg): - msgWriteln(s, color, frmt) + styledMsgWriteln(color, title, resetStyle, s) handleError(msg, doAbort, s) proc rawMessage*(msg: TMsgKind, arg: string) = @@ -795,47 +830,49 @@ proc writeSurroundingSrc(info: TLineInfo) = msgWriteln(indent & spaces(info.col) & '^') proc formatMsg*(info: TLineInfo, msg: TMsgKind, arg: string): string = - let frmt = case msg - of warnMin..warnMax: PosWarningFormat - of hintMin..hintMax: PosHintFormat - else: PosErrorFormat - result = frmt % [toMsgFilename(info), coordToStr(info.line), - coordToStr(info.col+1), getMessageStr(msg, arg)] + let title = case msg + of warnMin..warnMax: WarningTitle + of hintMin..hintMax: HintTitle + else: ErrorTitle + result = PosFormat % [toMsgFilename(info), coordToStr(info.line), + coordToStr(info.col+1)] & + title & + getMessageStr(msg, arg) proc liMessage(info: TLineInfo, msg: TMsgKind, arg: string, eh: TErrorHandling) = var - frmt: string + title: string ignoreMsg = false color: ForegroundColor case msg of errMin..errMax: writeContext(info) - frmt = PosErrorFormat + title = ErrorTitle + color = ErrorColor # we try to filter error messages so that not two error message # in the same file and line are produced: #ignoreMsg = lastError == info and eh != doAbort lastError = info - color = fgRed of warnMin..warnMax: ignoreMsg = optWarns notin gOptions or msg notin gNotes if not ignoreMsg: writeContext(info) - frmt = PosWarningFormat + title = WarningTitle + color = WarningColor inc(gWarnCounter) - color = fgYellow of hintMin..hintMax: ignoreMsg = optHints notin gOptions or msg notin gNotes - frmt = PosHintFormat + title = HintTitle + color = HintColor inc(gHintCounter) - color = fgGreen # NOTE: currently line info line numbers start with 1, # but column numbers start with 0, however most editors expect # first column to be 1, so we need to +1 here - let x = frmt % [toMsgFilename(info), coordToStr(info.line), - coordToStr(info.col+1)] + let x = PosFormat % [toMsgFilename(info), coordToStr(info.line), + coordToStr(info.col+1)] let s = getMessageStr(msg, arg) if not ignoreMsg and not ignoreMsgBecauseOfIdeTools(msg): - msgWriteln(s, color, x) + styledMsgWriteln(styleBright, x, resetStyle, color, title, resetStyle, s) if optPrintSurroundingSrc and msg in errMin..errMax: info.writeSurroundingSrc handleError(msg, eh, s) From b4d3a27753e03b1da3b510e651378077ec4d1879 Mon Sep 17 00:00:00 2001 From: Adam Strzelecki Date: Thu, 11 Jun 2015 22:11:11 +0200 Subject: [PATCH 0469/1263] msgs: Append/color warning/hint kind in msgWriteln Rather than embedding it into the message format text itself. This also makes possible to color warning/hint kind. --- compiler/msgs.nim | 116 ++++++++++++++++++++++++++-------------------- 1 file changed, 66 insertions(+), 50 deletions(-) diff --git a/compiler/msgs.nim b/compiler/msgs.nim index 2edb869d8..6b71b7159 100644 --- a/compiler/msgs.nim +++ b/compiler/msgs.nim @@ -367,54 +367,54 @@ const "of the generic paramers can be inferred from the expected signature.", errCompilerDoesntSupportTarget: "The current compiler \'$1\' doesn't support the requested compilation target", errUser: "$1", - warnCannotOpenFile: "cannot open \'$1\' [CannotOpenFile]", - warnOctalEscape: "octal escape sequences do not exist; leading zero is ignored [OctalEscape]", - warnXIsNeverRead: "\'$1\' is never read [XIsNeverRead]", - warnXmightNotBeenInit: "\'$1\' might not have been initialized [XmightNotBeenInit]", - warnDeprecated: "$1 is deprecated [Deprecated]", - warnConfigDeprecated: "config file '$1' is deprecated [ConfigDeprecated]", - warnSmallLshouldNotBeUsed: "\'l\' should not be used as an identifier; may look like \'1\' (one) [SmallLshouldNotBeUsed]", - warnUnknownMagic: "unknown magic \'$1\' might crash the compiler [UnknownMagic]", - warnRedefinitionOfLabel: "redefinition of label \'$1\' [RedefinitionOfLabel]", - warnUnknownSubstitutionX: "unknown substitution \'$1\' [UnknownSubstitutionX]", - warnLanguageXNotSupported: "language \'$1\' not supported [LanguageXNotSupported]", - warnFieldXNotSupported: "field \'$1\' not supported [FieldXNotSupported]", - warnCommentXIgnored: "comment \'$1\' ignored [CommentXIgnored]", - warnNilStatement: "'nil' statement is deprecated; use an empty 'discard' statement instead [NilStmt]", - warnTypelessParam: "'$1' has no type. Typeless parameters are deprecated; only allowed for 'template' [TypelessParam]", - warnDifferentHeaps: "possible inconsistency of thread local heaps [DifferentHeaps]", - warnWriteToForeignHeap: "write to foreign heap [WriteToForeignHeap]", - warnUnsafeCode: "unsafe code: '$1' [UnsafeCode]", - warnEachIdentIsTuple: "each identifier is a tuple [EachIdentIsTuple]", - warnShadowIdent: "shadowed identifier: '$1' [ShadowIdent]", - warnProveInit: "Cannot prove that '$1' is initialized. This will become a compile time error in the future. [ProveInit]", - warnProveField: "cannot prove that field '$1' is accessible [ProveField]", - warnProveIndex: "cannot prove index '$1' is valid [ProveIndex]", - warnGcUnsafe: "not GC-safe: '$1' [GcUnsafe]", + warnCannotOpenFile: "cannot open \'$1\'", + warnOctalEscape: "octal escape sequences do not exist; leading zero is ignored", + warnXIsNeverRead: "\'$1\' is never read", + warnXmightNotBeenInit: "\'$1\' might not have been initialized", + warnDeprecated: "$1 is deprecated", + warnConfigDeprecated: "config file '$1' is deprecated", + warnSmallLshouldNotBeUsed: "\'l\' should not be used as an identifier; may look like \'1\' (one)", + warnUnknownMagic: "unknown magic \'$1\' might crash the compiler", + warnRedefinitionOfLabel: "redefinition of label \'$1\'", + warnUnknownSubstitutionX: "unknown substitution \'$1\'", + warnLanguageXNotSupported: "language \'$1\' not supported", + warnFieldXNotSupported: "field \'$1\' not supported", + warnCommentXIgnored: "comment \'$1\' ignored", + warnNilStatement: "'nil' statement is deprecated; use an empty 'discard' statement instead", + warnTypelessParam: "'$1' has no type. Typeless parameters are deprecated; only allowed for 'template'", + warnDifferentHeaps: "possible inconsistency of thread local heaps", + warnWriteToForeignHeap: "write to foreign heap", + warnUnsafeCode: "unsafe code: '$1'", + warnEachIdentIsTuple: "each identifier is a tuple", + warnShadowIdent: "shadowed identifier: '$1'", + warnProveInit: "Cannot prove that '$1' is initialized. This will become a compile time error in the future.", + warnProveField: "cannot prove that field '$1' is accessible", + warnProveIndex: "cannot prove index '$1' is valid", + warnGcUnsafe: "not GC-safe: '$1'", warnGcUnsafe2: "$1", - warnUninit: "'$1' might not have been initialized [Uninit]", - warnGcMem: "'$1' uses GC'ed memory [GcMem]", - warnDestructor: "usage of a type with a destructor in a non destructible context. This will become a compile time error in the future. [Destructor]", - warnLockLevel: "$1 [LockLevel]", - warnResultShadowed: "Special variable 'result' is shadowed. [ResultShadowed]", - warnUser: "$1 [User]", - hintSuccess: "operation successful [Success]", - hintSuccessX: "operation successful ($# lines compiled; $# sec total; $#; $#) [SuccessX]", - hintLineTooLong: "line too long [LineTooLong]", - hintXDeclaredButNotUsed: "\'$1\' is declared but not used [XDeclaredButNotUsed]", - hintConvToBaseNotNeeded: "conversion to base object is not needed [ConvToBaseNotNeeded]", - hintConvFromXtoItselfNotNeeded: "conversion from $1 to itself is pointless [ConvFromXtoItselfNotNeeded]", - hintExprAlwaysX: "expression evaluates always to \'$1\' [ExprAlwaysX]", - hintQuitCalled: "quit() called [QuitCalled]", - hintProcessing: "$1 [Processing]", - hintCodeBegin: "generated code listing: [CodeBegin]", - hintCodeEnd: "end of listing [CodeEnd]", - hintConf: "used config file \'$1\' [Conf]", - hintPath: "added path: '$1' [Path]", - hintConditionAlwaysTrue: "condition is always true: '$1' [CondTrue]", - hintName: "name should be: '$1' [Name]", - hintPattern: "$1 [Pattern]", - hintUser: "$1 [User]"] + warnUninit: "'$1' might not have been initialized", + warnGcMem: "'$1' uses GC'ed memory", + warnDestructor: "usage of a type with a destructor in a non destructible context. This will become a compile time error in the future.", + warnLockLevel: "$1", + warnResultShadowed: "Special variable 'result' is shadowed.", + warnUser: "$1", + hintSuccess: "operation successful", + hintSuccessX: "operation successful ($# lines compiled; $# sec total; $#; $#)", + hintLineTooLong: "line too long", + hintXDeclaredButNotUsed: "\'$1\' is declared but not used", + hintConvToBaseNotNeeded: "conversion to base object is not needed", + hintConvFromXtoItselfNotNeeded: "conversion from $1 to itself is pointless", + hintExprAlwaysX: "expression evaluates always to \'$1\'", + hintQuitCalled: "quit() called", + hintProcessing: "$1", + hintCodeBegin: "generated code listing:", + hintCodeEnd: "end of listing", + hintConf: "used config file \'$1\'", + hintPath: "added path: '$1'", + hintConditionAlwaysTrue: "condition is always true: '$1'", + hintName: "name should be: '$1'", + hintPattern: "$1", + hintUser: "$1"] const WarningsToStr*: array[0..30, string] = ["CannotOpenFile", "OctalEscape", @@ -606,6 +606,8 @@ proc suggestQuit*() = # Borland and Freepascal use const PosFormat = "$1($2, $3) " + KindFormat = " [$1]" + KindColor = fgCyan ErrorTitle = "Error: " ErrorColor = fgRed WarningTitle = "Warning: " @@ -798,6 +800,7 @@ proc rawMessage*(msg: TMsgKind, args: openArray[string]) = var title: string color: ForegroundColor + kind: string case msg of errMin..errMax: writeContext(unknownLineInfo()) @@ -809,16 +812,22 @@ proc rawMessage*(msg: TMsgKind, args: openArray[string]) = writeContext(unknownLineInfo()) title = WarningTitle color = WarningColor + kind = WarningsToStr[ord(msg) - ord(warnMin)] inc(gWarnCounter) of hintMin..hintMax: if optHints notin gOptions: return if msg notin gNotes: return title = HintTitle color = HintColor + kind = HintsToStr[ord(msg) - ord(hintMin)] inc(gHintCounter) let s = `%`(msgKindToString(msg), args) if not ignoreMsgBecauseOfIdeTools(msg): - styledMsgWriteln(color, title, resetStyle, s) + if kind != nil: + styledMsgWriteln(color, title, resetStyle, s, + KindColor, `%`(KindFormat, kind)) + else: + styledMsgWriteln(color, title, resetStyle, s) handleError(msg, doAbort, s) proc rawMessage*(msg: TMsgKind, arg: string) = @@ -843,8 +852,9 @@ proc liMessage(info: TLineInfo, msg: TMsgKind, arg: string, eh: TErrorHandling) = var title: string - ignoreMsg = false color: ForegroundColor + kind: string + ignoreMsg = false case msg of errMin..errMax: writeContext(info) @@ -859,11 +869,13 @@ proc liMessage(info: TLineInfo, msg: TMsgKind, arg: string, if not ignoreMsg: writeContext(info) title = WarningTitle color = WarningColor + kind = WarningsToStr[ord(msg) - ord(warnMin)] inc(gWarnCounter) of hintMin..hintMax: ignoreMsg = optHints notin gOptions or msg notin gNotes title = HintTitle color = HintColor + kind = HintsToStr[ord(msg) - ord(hintMin)] inc(gHintCounter) # NOTE: currently line info line numbers start with 1, # but column numbers start with 0, however most editors expect @@ -872,7 +884,11 @@ proc liMessage(info: TLineInfo, msg: TMsgKind, arg: string, coordToStr(info.col+1)] let s = getMessageStr(msg, arg) if not ignoreMsg and not ignoreMsgBecauseOfIdeTools(msg): - styledMsgWriteln(styleBright, x, resetStyle, color, title, resetStyle, s) + if kind != nil: + styledMsgWriteln(styleBright, x, resetStyle, color, title, resetStyle, s, + KindColor, `%`(KindFormat, kind)) + else: + styledMsgWriteln(styleBright, x, resetStyle, color, title, resetStyle, s) if optPrintSurroundingSrc and msg in errMin..errMax: info.writeSurroundingSrc handleError(msg, eh, s) From 8618530413d68df7fbf8c16ab76d8ef63114f3e2 Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Mon, 15 Jun 2015 08:34:11 -0500 Subject: [PATCH 0470/1263] switched over from assert to doAssert for guide --- contributing.md | 23 +++++++---------------- 1 file changed, 7 insertions(+), 16 deletions(-) diff --git a/contributing.md b/contributing.md index 9c589ae49..123fd5668 100644 --- a/contributing.md +++ b/contributing.md @@ -33,28 +33,19 @@ If you change the stdlib (anything under `lib/`), put a test in the file you changed. Add the tests under an `when isMainModule:` condition so they only get executed when the tester is building the file. Each test should be in a separate `block:` statement, such that -each has its own scope. Use boolean conditions and `assert` for the +each has its own scope. Use boolean conditions and `doAssert` for the testing by itself, don't rely on echo statements or similar. Sample test: ```nim when isMainModule: - block lenTest: - var values: HashSet[int] - assert(not values.isValid) - assert values.len == 0 - assert values.card == 0 - block setIterator: - type pair = tuple[a, b: int] - var a, b = initSet[pair]() - a.incl((2, 3)) - a.incl((3, 2)) - a.incl((2, 3)) - for x, y in a.items: - b.incl((x - 2, y + 1)) - assert a.len == b.card - assert a.len == 2 + block: # newSeqWith tests + var seq2D = newSeqWith(4, newSeq[bool](2)) + seq2D[0][0] = true + seq2D[1][0] = true + seq2D[0][1] = true + doAssert seq2D == @[@[true, true], @[true, false], @[false, false], @[false, false]] ``` ## Compiler From ac6ea4b76dda5ced9ebf10bc7bf58d29aef24748 Mon Sep 17 00:00:00 2001 From: apense Date: Mon, 15 Jun 2015 12:58:44 -0400 Subject: [PATCH 0471/1263] Clarified AST Generic parameters are treated in the next paragraph. Revised text for future compatibility --- doc/astspec.txt | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/doc/astspec.txt b/doc/astspec.txt index b3955c634..0d9475749 100644 --- a/doc/astspec.txt +++ b/doc/astspec.txt @@ -133,7 +133,7 @@ AST: ) Note that with multiple infix operators, the command is parsed by operator -precedence, with the end result mirroring Reverse Polish Notation. +precedence. Concrete syntax: @@ -408,8 +408,8 @@ Documentation Comments ---------------------- Double-hash (``##``) comments in the code actually have their own format, -but *it doesn't matter what is there*. The AST will only show that a comment -exists, not what it contains. Single-hash (``#``) comments are ignored. +but the comments do not yet show up in the AST, which will only show that +a comment exists, not what it contains. Single-hash (``#``) comments are ignored. Concrete syntax: @@ -785,7 +785,7 @@ AST: nnkTypeSection( nnkTypeDef( nnkIdent(!"A"), - nnkEmpty(), # for pragmas + nnkEmpty(), nnkIdent(!"int") ) ) From 7275a035b580627a58aad76a4f5302e05c060afc Mon Sep 17 00:00:00 2001 From: apense Date: Mon, 15 Jun 2015 13:30:09 -0400 Subject: [PATCH 0472/1263] Updated type section a little Objects are ubiquitous. Concepts don't use ``concept`` in their name. Really, a lot more could be added here. --- doc/astspec.txt | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/doc/astspec.txt b/doc/astspec.txt index 0d9475749..1f46070df 100644 --- a/doc/astspec.txt +++ b/doc/astspec.txt @@ -815,6 +815,50 @@ AST: ) ) +Note that not all ``nnkTypeDef`` utilize ``nnkIdent`` as their +their parameter. One of the most common uses of type declarations +is to work with objects. + +Concrete syntax: + +.. code-block:: nim + type IO = object of RootObj + +AST: + +.. code-block:: nim + # ... + nnkTypeDef( + nnkIdent(!"IO"), + nnkEmpty(), + nnkObjectTy( + nnkEmpty(), # no pragmas here + nnkOfInherit( + nnkIdent(!"RootObj") # inherits from RootObj + ) + nnkEmpty() + ) + ) + +The usage of ``concept`` (experimental) is similar. + +Concrete syntax: + +.. code-block:: nim + type Con = concept x,y,z + (x & y & z) is string + +AST: + +.. code-block:: nim + # ... + nnkTypeClassTy( # note this isn't nnkConceptTy! + nnkArglist( + # ... idents for x, y, z + ) + # ... + ) + Procedure declaration --------------------- From fce697b043efda8ac2711a958d99483605fab7f8 Mon Sep 17 00:00:00 2001 From: apense Date: Mon, 15 Jun 2015 13:37:58 -0400 Subject: [PATCH 0473/1263] Corrected capitalization Sorry to be making so many changes. --- doc/astspec.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/astspec.txt b/doc/astspec.txt index 1f46070df..0a7c29db7 100644 --- a/doc/astspec.txt +++ b/doc/astspec.txt @@ -970,7 +970,7 @@ AST: # follows like a proc or iterator ) -If the template does not have types for its parameters, the type Identifiers +If the template does not have types for its parameters, the type identifiers inside ``nnkFormalParams`` just becomes ``nnkEmpty``. Macro declaration From 090fc336416b9f7f9ee54dd8991bf1760d81df50 Mon Sep 17 00:00:00 2001 From: yglukhov Date: Sat, 13 Jun 2015 18:49:29 +0300 Subject: [PATCH 0474/1263] Fixed and slightly changed exception handling. --- compiler/jsgen.nim | 29 +++++++++++++++++++---------- lib/system/jssys.nim | 29 ++++------------------------- 2 files changed, 23 insertions(+), 35 deletions(-) diff --git a/compiler/jsgen.nim b/compiler/jsgen.nim index f6ec256d2..fd0e600b7 100644 --- a/compiler/jsgen.nim +++ b/compiler/jsgen.nim @@ -509,8 +509,8 @@ proc genTry(p: PProc, n: PNode, r: var TCompRes) = # excHandler = sp; # try { # stmts; - # TMP = e - # } catch (e) { + # } catch (EXC) { + # var prevJSError = lastJSError; lastJSError = EXC; # if (e.typ && e.typ == NTI433 || e.typ == NTI2321) { # stmts; # } else if (e.typ && e.typ == NTI32342) { @@ -518,9 +518,9 @@ proc genTry(p: PProc, n: PNode, r: var TCompRes) = # } else { # stmts; # } + # lastJSError = prevJSError; # } finally { # stmts; - # excHandler = excHandler.prev; # } genLineDir(p, n) if not isEmptyType(n.typ): @@ -529,7 +529,7 @@ proc genTry(p: PProc, n: PNode, r: var TCompRes) = inc(p.unique) var safePoint = "Tmp$1" % [rope(p.unique)] addf(p.body, - "var $1 = {prev: excHandler, exc: null};$nexcHandler = $1;$n" | + "" | "local $1 = pcall(", [safePoint]) if optStackTrace in p.options: add(p.body, "framePtr = F;" & tnl) @@ -539,14 +539,17 @@ proc genTry(p: PProc, n: PNode, r: var TCompRes) = gen(p, n.sons[0], a) moveInto(p, a, r) var i = 1 - if p.target == targetJS and length > 1 and n.sons[i].kind == nkExceptBranch: - addf(p.body, "} catch (EXC) {$n lastJSError = EXC;$n", []) + var generalCatchBranchExists = false + var catchBranchesExist = length > 1 and n.sons[i].kind == nkExceptBranch + if p.target == targetJS and catchBranchesExist: + addf(p.body, "} catch (EXC) {$n var prevJSError = lastJSError; lastJSError = EXC;$n", []) elif p.target == targetLua: addf(p.body, "end)$n", []) while i < length and n.sons[i].kind == nkExceptBranch: let blen = sonsLen(n.sons[i]) if blen == 1: # general except section: + generalCatchBranchExists = true if i > 1: addf(p.body, "else {$n" | "else$n", []) gen(p, n.sons[i].sons[0], a) moveInto(p, a, r) @@ -558,17 +561,22 @@ proc genTry(p: PProc, n: PNode, r: var TCompRes) = if n.sons[i].sons[j].kind != nkType: internalError(n.info, "genTryStmt") if orExpr != nil: add(orExpr, "||" | " or ") - addf(orExpr, "isObj($1.exc.m_type, $2)", - [safePoint, genTypeInfo(p, n.sons[i].sons[j].typ)]) + addf(orExpr, "isObj(lastJSError.m_type, $1)", + [genTypeInfo(p, n.sons[i].sons[j].typ)]) if i > 1: add(p.body, "else ") - addf(p.body, "if ($1.exc && ($2)) {$n" | "if $1.exc and ($2) then$n", + addf(p.body, "if (lastJSError && ($2)) {$n" | "if $1.exc and ($2) then$n", [safePoint, orExpr]) gen(p, n.sons[i].sons[blen - 1], a) moveInto(p, a, r) addf(p.body, "}$n" | "end$n", []) inc(i) if p.target == targetJS: - add(p.body, "} finally {" & tnl & "excHandler = excHandler.prev;" & tnl) + if catchBranchesExist: + if not generalCatchBranchExists: + useMagic(p, "reraiseException") + add(p.body, "else { reraiseException(); }") + add(p.body, "lastJSError = prevJSError;" & tnl) + add(p.body, "} finally {" & tnl) if i < length and n.sons[i].kind == nkFinally: genStmt(p, n.sons[i].sons[0]) if p.target == targetJS: @@ -1067,6 +1075,7 @@ proc genInfixCall(p: PProc, n: PNode, r: var TCompRes) = r.kind = resExpr proc genEcho(p: PProc, n: PNode, r: var TCompRes) = + useMagic(p, "toJSStr") # Used in rawEcho useMagic(p, "rawEcho") add(r.res, "rawEcho(") let n = n[1].skipConv diff --git a/lib/system/jssys.nim b/lib/system/jssys.nim index f082023ee..a6711a778 100644 --- a/lib/system/jssys.nim +++ b/lib/system/jssys.nim @@ -37,9 +37,6 @@ type var framePtr {.importc, nodecl, volatile.}: PCallFrame - excHandler {.importc, nodecl, volatile.}: PSafePoint = nil - # list of exception handlers - # a global variable for the root of all try blocks lastJSError {.importc, nodecl, volatile.}: PJSError = nil {.push stacktrace: off, profiler:off.} @@ -52,9 +49,7 @@ proc nimCharToStr(x: char): string {.compilerproc.} = result[0] = x proc getCurrentExceptionMsg*(): string = - if excHandler != nil and excHandler.exc != nil: - return $excHandler.exc.msg - elif lastJSError != nil: + if lastJSError != nil: return $lastJSError.message else: return "" @@ -102,29 +97,13 @@ proc rawWriteStackTrace(): string = proc raiseException(e: ref Exception, ename: cstring) {. compilerproc, asmNoStackFrame.} = e.name = ename - if excHandler != nil: - excHandler.exc = e - else: - when NimStackTrace: - var buf = rawWriteStackTrace() - else: - var buf = "" - if e.msg != nil and e.msg[0] != '\0': - add(buf, "Error: unhandled exception: ") - add(buf, e.msg) - else: - add(buf, "Error: unhandled exception") - add(buf, " [") - add(buf, ename) - add(buf, "]\n") - alert(buf) - asm """throw `e`;""" + asm "throw `e`;" proc reraiseException() {.compilerproc, asmNoStackFrame.} = - if excHandler == nil: + if lastJSError == nil: raise newException(ReraiseError, "no exception to reraise") else: - asm """throw excHandler.exc;""" + asm "throw lastJSError;" proc raiseOverflow {.exportc: "raiseOverflow", noreturn.} = raise newException(OverflowError, "over- or underflow") From 3c9d655b883129765c3716c209dee5d38d72f8f6 Mon Sep 17 00:00:00 2001 From: apense Date: Mon, 15 Jun 2015 16:03:04 -0400 Subject: [PATCH 0475/1263] Added raw string literal function calls docs Got curious as to how re"..." worked. --- doc/astspec.txt | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/doc/astspec.txt b/doc/astspec.txt index 0a7c29db7..6b64e5b91 100644 --- a/doc/astspec.txt +++ b/doc/astspec.txt @@ -231,6 +231,25 @@ AST: nnkStrLit("hallo") ) +Call with raw string literal +---------------------------- + +This is used, for example, in the ``bindSym`` examples +[here](http://nim-lang.org/docs/manual.html#macros-bindsym) and with +``re"some regexp"`` in the regular expression module. + +Concrete syntax: + +.. code-block:: nim + echo"abc" + +AST: + +.. code-block:: nim + nnkCallStrLit( + nnkIdent(!"echo"), + nnkRStrLit("hello") + ) Dereference operator ``[]`` --------------------------- From fa1f3aecce3398f4d7afe69294ba9b3f928a66a2 Mon Sep 17 00:00:00 2001 From: yglukhov Date: Mon, 15 Jun 2015 23:08:38 +0300 Subject: [PATCH 0476/1263] Unhandled exceptions handling brought back. --- compiler/jsgen.nim | 19 +++++++++++-------- lib/system/jssys.nim | 24 ++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 8 deletions(-) diff --git a/compiler/jsgen.nim b/compiler/jsgen.nim index fd0e600b7..d84b0f2f9 100644 --- a/compiler/jsgen.nim +++ b/compiler/jsgen.nim @@ -505,12 +505,12 @@ proc moveInto(p: PProc, src: var TCompRes, dest: TCompRes) = proc genTry(p: PProc, n: PNode, r: var TCompRes) = # code to generate: # - # var sp = {prev: excHandler, exc: null}; - # excHandler = sp; + # ++excHandler; # try { # stmts; # } catch (EXC) { # var prevJSError = lastJSError; lastJSError = EXC; + # --excHandler; # if (e.typ && e.typ == NTI433 || e.typ == NTI2321) { # stmts; # } else if (e.typ && e.typ == NTI32342) { @@ -527,6 +527,11 @@ proc genTry(p: PProc, n: PNode, r: var TCompRes) = r.kind = resVal r.res = getTemp(p) inc(p.unique) + var i = 1 + var length = sonsLen(n) + var catchBranchesExist = length > 1 and n.sons[i].kind == nkExceptBranch + if catchBranchesExist: + add(p.body, "++excHandler;" & tnl) var safePoint = "Tmp$1" % [rope(p.unique)] addf(p.body, "" | @@ -534,15 +539,13 @@ proc genTry(p: PProc, n: PNode, r: var TCompRes) = [safePoint]) if optStackTrace in p.options: add(p.body, "framePtr = F;" & tnl) addf(p.body, "try {$n" | "function()$n", []) - var length = sonsLen(n) var a: TCompRes gen(p, n.sons[0], a) moveInto(p, a, r) - var i = 1 var generalCatchBranchExists = false - var catchBranchesExist = length > 1 and n.sons[i].kind == nkExceptBranch if p.target == targetJS and catchBranchesExist: - addf(p.body, "} catch (EXC) {$n var prevJSError = lastJSError; lastJSError = EXC;$n", []) + addf(p.body, "} catch (EXC) {$n var prevJSError = lastJSError;$n" & + " lastJSError = EXC;$n --excHandler;$n", []) elif p.target == targetLua: addf(p.body, "end)$n", []) while i < length and n.sons[i].kind == nkExceptBranch: @@ -574,7 +577,7 @@ proc genTry(p: PProc, n: PNode, r: var TCompRes) = if catchBranchesExist: if not generalCatchBranchExists: useMagic(p, "reraiseException") - add(p.body, "else { reraiseException(); }") + add(p.body, "else {" & tnl & "reraiseException();" & tnl & "}" & tnl) add(p.body, "lastJSError = prevJSError;" & tnl) add(p.body, "} finally {" & tnl) if i < length and n.sons[i].kind == nkFinally: @@ -1685,7 +1688,7 @@ proc genHeader(): Rope = result = ("/* Generated by the Nim Compiler v$1 */$n" & "/* (c) 2015 Andreas Rumpf */$n$n" & "var framePtr = null;$n" & - "var excHandler = null;$n" & + "var excHandler = 0;$n" & "var lastJSError = null;$n") % [rope(VersionAsString)] diff --git a/lib/system/jssys.nim b/lib/system/jssys.nim index a6711a778..4d5ba1f73 100644 --- a/lib/system/jssys.nim +++ b/lib/system/jssys.nim @@ -37,6 +37,7 @@ type var framePtr {.importc, nodecl, volatile.}: PCallFrame + excHandler {.importc, nodecl, volatile.}: int = 0 lastJSError {.importc, nodecl, volatile.}: PJSError = nil {.push stacktrace: off, profiler:off.} @@ -94,15 +95,38 @@ proc rawWriteStackTrace(): string = else: result = "No stack traceback available\n" +proc unhandledException(e: ref Exception) {. + compilerproc, asmNoStackFrame.} = + when NimStackTrace: + var buf = rawWriteStackTrace() + else: + var buf = "" + if e.msg != nil and e.msg[0] != '\0': + add(buf, "Error: unhandled exception: ") + add(buf, e.msg) + else: + add(buf, "Error: unhandled exception") + add(buf, " [") + add(buf, e.name) + add(buf, "]\n") + alert(buf) + proc raiseException(e: ref Exception, ename: cstring) {. compilerproc, asmNoStackFrame.} = e.name = ename + if excHandler == 0: + unhandledException(e) asm "throw `e`;" proc reraiseException() {.compilerproc, asmNoStackFrame.} = if lastJSError == nil: raise newException(ReraiseError, "no exception to reraise") else: + if excHandler == 0: + var isNimException : bool + asm "`isNimException` = lastJSError.m_type;" + if isNimException: + unhandledException(cast[ref Exception](lastJSError)) asm "throw lastJSError;" proc raiseOverflow {.exportc: "raiseOverflow", noreturn.} = From 8c8e975bcd286b41e8308a6deab0f1d00849c681 Mon Sep 17 00:00:00 2001 From: apense Date: Mon, 15 Jun 2015 16:27:53 -0400 Subject: [PATCH 0477/1263] Added static types I put this within the type section, but I'm not sure if it should go here. It has a broader use. Should it get its own section? --- doc/astspec.txt | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/doc/astspec.txt b/doc/astspec.txt index 6b64e5b91..ef0c91bb8 100644 --- a/doc/astspec.txt +++ b/doc/astspec.txt @@ -878,6 +878,26 @@ AST: # ... ) +Static types, like ``static[int]``, use ``nnkIdent`` wrapped in +``nnkStaticTy``. + +Concrete syntax: + +.. code-block:: nim + type A[T: static[int]] = object + +AST: + +.. code-block:: nim + # ... within nnkGenericParams + nnkIdentDefs( + nnkIdent(!"T"), + nnkStaticTy( + nnkIdent(!"int") + ), + nnkEmpty() + ) + # ... Procedure declaration --------------------- From ffa4f8dc997331f2005f19ab2fb9f34b433f9e16 Mon Sep 17 00:00:00 2001 From: yglukhov Date: Mon, 15 Jun 2015 23:30:09 +0300 Subject: [PATCH 0478/1263] Added noUnhandledHandler --- lib/system/jssys.nim | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/lib/system/jssys.nim b/lib/system/jssys.nim index 4d5ba1f73..5a9333a0e 100644 --- a/lib/system/jssys.nim +++ b/lib/system/jssys.nim @@ -114,19 +114,21 @@ proc unhandledException(e: ref Exception) {. proc raiseException(e: ref Exception, ename: cstring) {. compilerproc, asmNoStackFrame.} = e.name = ename - if excHandler == 0: - unhandledException(e) + when not defined(noUnhandledHandler): + if excHandler == 0: + unhandledException(e) asm "throw `e`;" proc reraiseException() {.compilerproc, asmNoStackFrame.} = if lastJSError == nil: raise newException(ReraiseError, "no exception to reraise") else: - if excHandler == 0: - var isNimException : bool - asm "`isNimException` = lastJSError.m_type;" - if isNimException: - unhandledException(cast[ref Exception](lastJSError)) + when not defined(noUnhandledHandler): + if excHandler == 0: + var isNimException : bool + asm "`isNimException` = lastJSError.m_type;" + if isNimException: + unhandledException(cast[ref Exception](lastJSError)) asm "throw lastJSError;" proc raiseOverflow {.exportc: "raiseOverflow", noreturn.} = From 998f1fa67a2f4c0c28f387d969941464018d61e7 Mon Sep 17 00:00:00 2001 From: apense Date: Mon, 15 Jun 2015 18:35:05 -0400 Subject: [PATCH 0479/1263] Minor updates; addition of `var` return in procs --- doc/astspec.txt | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/doc/astspec.txt b/doc/astspec.txt index ef0c91bb8..50dfda1bc 100644 --- a/doc/astspec.txt +++ b/doc/astspec.txt @@ -762,6 +762,10 @@ Note that either the second or third (or both) parameters above must exist, as the compiler needs to know the type somehow (which it can infer from the given assignment). +This is not the same AST for all uses of ``var``. See +[Procedure declaration](http://nim-lang.org/docs/macros.html#statements-procedure-declaration) +for details. + Let section ----------- @@ -899,6 +903,32 @@ AST: ) # ... +Mixin statement +--------------- + +Concrete syntax: + +.. code-block:: nim + mixin x + +AST: + +.. code-block:: nim + nnkMixinStmt(nnkIdent(!"x")) + +Bind statement +-------------- + +Concrete syntax: + +.. code-block:: nim + bind x + +AST: + +.. code-block:: nim + nnkBindStmt(nnkIdent(!"x")) + Procedure declaration --------------------- @@ -963,6 +993,24 @@ AST: ), # ... +When a procedure uses the special ``var`` type return variable, the result +is different from that of a var section. + +Concrete syntax: + +.. code-block:: nim + proc hello(): var int + +AST: + +.. code-block:: nim + # ... + nnkFormalParams( + nnkVarTy( + nnkIdent(!"int") + ) + ) + Iterator declaration -------------------- From d75bdc31b4648efec8619b16a15ac9b89991141c Mon Sep 17 00:00:00 2001 From: apense Date: Mon, 15 Jun 2015 18:55:09 -0400 Subject: [PATCH 0480/1263] Added import-type statements import, import .. except, export, include, etc. --- doc/astspec.txt | 96 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) diff --git a/doc/astspec.txt b/doc/astspec.txt index 50dfda1bc..f68f9a2a3 100644 --- a/doc/astspec.txt +++ b/doc/astspec.txt @@ -739,6 +739,102 @@ AST: nnkTripleStrLit("some asm"), ) +Import section +-------------- + +Nim's ``import`` statement actually takes different variations depending +on what keywords are present. Let's start with the simplest form. + +Concrete syntax: + +.. code-block:: nim + import math + +AST: + +.. code-block:: nim + nnkImportStmt(nnkIdent(!"math")) + +With ``except``, we get ``nnkImportExceptStmt``. + +Concrete syntax: + +.. code-block:: nim + import math except pow + +AST: + +.. code-block:: nim + nnkImportExceptStmt(nnkIdent(!"math"),nnkIdent(!"pow")) + +Note that ``import math as m`` does not use a different node; rather, +we use ``nnkImportStmt`` with ``as`` as an infix operator. + +Concrete syntax: + +.. code-block:: nim + import strutils as su + +AST: + +.. code-block:: nim + nnkImportStmt( + nnkInfix( + nnkIdent(!"as"), + nnkIdent(!"strutils"), + nnkIdent(!"su") + ) + ) + +From statement +-------------- + +If we use ``from ... import``, the result is different, too. + +Concrete syntax: + +.. code-block:: nim + from math import pow + +AST: + +.. code-block:: nim + nnkFromStmt(nnkIdent(!"math"), nnkIdent(!"pow")) + +Using ``from math as m import pow`` works identically to the ``as`` modifier +with the ``import`` statement, but wrapped in ``nnkFromStmt``. + +Export statement +---------------- + +When you are making an imported module accessible by modules that import yours, +the ``export`` syntax is pretty straightforward. + +Concrete syntax: + +.. code-block:: nim + export unsigned + +AST: + +.. code-block:: nim + nnkExportStmt(nnkIdent(!"unsigned")) + +Include statement +----------------- + +Like a plain ``import`` statement. + +Concrete syntax: + +.. code-block:: nim + include blocks + +AST: + +.. code-block:: nim + nnkIncludeStmt(nnkIdent(!"blocks")) + Var section ----------- From 66ad9e3985177d6ee2527416a922c971fa64a23d Mon Sep 17 00:00:00 2001 From: apense Date: Mon, 15 Jun 2015 19:37:16 -0400 Subject: [PATCH 0481/1263] Fleshed out type section Hopefully this table renders correctly. Not sure this is the best place for this stuff. --- doc/astspec.txt | 105 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 103 insertions(+), 2 deletions(-) diff --git a/doc/astspec.txt b/doc/astspec.txt index f68f9a2a3..7514838da 100644 --- a/doc/astspec.txt +++ b/doc/astspec.txt @@ -53,7 +53,7 @@ A leaf of the AST often corresponds to a terminal symbol in the concrete syntax. ----------------- --------------------------------------------- -Nim expression corresponding AST +Nim expression Corresponding AST ----------------- --------------------------------------------- ``42`` ``nnkIntLit(intVal = 42)`` ``42'i8`` ``nnkInt8Lit(intVal = 42)`` @@ -909,6 +909,26 @@ AST: ) ) +Declaring ``distinct`` types is similar, with the last ``nnkIdent`` wrapped +in ``nnkDistinctTy``. + +Concrete syntax: + +.. code-block:: nim + type MyInt = distinct int + +AST: + +.. code-block:: nim + # ... + nnkTypeDef( + nnkIdent(!"MyInt"), + nnkEmpty(), + nnkDistinctTy( + nnkIdent(!"int") + ) + ) + If a type section uses generic parameters, they are treated here: Concrete syntax: @@ -959,7 +979,24 @@ AST: ) ) -The usage of ``concept`` (experimental) is similar. +Using an ``enum`` is similar to using an ``object``. + +Concrete syntax: + +.. code-block:: nim + type X = enum + First + +AST: + +.. code-block:: nim + # ... + nnkEnumTy( + nnkEmpty(), + nnkIdent(!"First") # you need at least one nnkIdent or the compiler complains + ) + +The usage of ``concept`` (experimental) is similar to objects. Concrete syntax: @@ -999,6 +1036,53 @@ AST: ) # ... +In general, declaring types mirrors this syntax (i.e., ``nnkStaticTy`` for +``static``, etc.). Examples follow (exceptions marked by ``*``: + +------------- --------------------------------------------- +Nim type Corresponding AST +------------- --------------------------------------------- +``static`` ``nnkStaticTy`` +``tuple`` ``nnkTupleTy`` +``var`` ``nnkVarTy`` +``ptr`` ``nnkPtrTy`` +``ref`` ``nnkRefTy`` +``distinct`` ``nnkDistinctTy`` +``enum`` ``nnkEnumTy`` +``concept`` ``nnkTypeClassTy``\* +``array`` ``nnkBracketExpr(nnkIdent(!"array"),...``\* +``proc`` ``nnkProcTy`` +``iterator`` ``nnkIteratorTy`` +``object`` ``nnkObjectTy`` + +Take special care when declaring types as ``proc``s. The behavior is similar +to ``Procedure declaration``, below, but does not treat ``nnkGenericParams``. +Generic parameters are treated in the type, not the ``proc`` itself. + +Concrete syntax: + +.. code-block:: nim + type MyProc[T] = proc(x: T) + +AST: + +.. code-block:: nim + # ... + nnkTypeDef( + nnkIdent(!"MyProc"), + nnkGenericParams( # here, not with the proc + # ... + ) + nnkProcTy( # behaves like a procedure declaration from here on + nnkFormalParams( + # ... + ) + ) + ) + +The same syntax applies to ``iterator``s (with ``nnkIteratorTy``), but +*does not* apply to ``converter``s or ``template``s. + Mixin statement --------------- @@ -1127,6 +1211,23 @@ AST: ... ) +Converter declaration +--------------------- + +A converter is similar to a proc. + +Concrete syntax: + +.. code-block:: nim + converter toBool(x: float): bool + +AST: + +.. code-block:: nim + nnkConverterDef( + nnkIdent(!"toBool"), + # ... + ) Template declaration -------------------- From abe1051374c2213ab28a8e7814ef3cc11d044e77 Mon Sep 17 00:00:00 2001 From: Alexander Date: Tue, 16 Jun 2015 15:58:21 +0300 Subject: [PATCH 0482/1263] Update tut1.txt --- doc/tut1.txt | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/doc/tut1.txt b/doc/tut1.txt index 1fa495054..6f10e7cbb 100644 --- a/doc/tut1.txt +++ b/doc/tut1.txt @@ -758,9 +758,13 @@ However, this cannot be done for mutually recursive procedures: proc even(n: int): bool proc odd(n: int): bool = + if n == 0: + true n == 1 or even(n-1) proc even(n: int): bool = + if n == 1: + true n == 0 or odd(n-1) Here ``odd`` depends on ``even`` and vice versa. Thus ``even`` needs to be From 5e2d7e81a23750661dca883adaa97745234879c4 Mon Sep 17 00:00:00 2001 From: Alexander Date: Tue, 16 Jun 2015 16:00:33 +0300 Subject: [PATCH 0483/1263] Update tut1.txt --- doc/tut1.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/tut1.txt b/doc/tut1.txt index 6f10e7cbb..084de453a 100644 --- a/doc/tut1.txt +++ b/doc/tut1.txt @@ -764,7 +764,7 @@ However, this cannot be done for mutually recursive procedures: proc even(n: int): bool = if n == 1: - true + false n == 0 or odd(n-1) Here ``odd`` depends on ``even`` and vice versa. Thus ``even`` needs to be From 77b51df09c6e853e4e852b8676ea0c2666b7683b Mon Sep 17 00:00:00 2001 From: Alexander Date: Tue, 16 Jun 2015 16:14:23 +0300 Subject: [PATCH 0484/1263] Update tut1.txt --- doc/tut1.txt | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/doc/tut1.txt b/doc/tut1.txt index 084de453a..500480cf0 100644 --- a/doc/tut1.txt +++ b/doc/tut1.txt @@ -757,20 +757,25 @@ However, this cannot be done for mutually recursive procedures: # forward declaration: proc even(n: int): bool - proc odd(n: int): bool = - if n == 0: - true +proc even(n: int): bool + +proc odd(n: int): bool = + assert(n >= 0) # makes sure we don't run into negative recursion + if n == 0: false + else: n == 1 or even(n-1) - proc even(n: int): bool = - if n == 1: - false +proc even(n: int): bool = + assert(n >= 0) # makes sure we don't run into negative recursion + if n == 1: false + else: n == 0 or odd(n-1) Here ``odd`` depends on ``even`` and vice versa. Thus ``even`` needs to be introduced to the compiler before it is completely defined. The syntax for such a forward declaration is simple: just omit the ``=`` and the -procedure's body. +procedure's body. The ``assert`` just adds border conditions, and will be +covered later in `Modules`_ section. Later versions of the language will weaken the requirements for forward declarations. From b487d4e42501fa5d1ef8f589a0cd89c187d09fc3 Mon Sep 17 00:00:00 2001 From: Stefan Talpalaru Date: Tue, 16 Jun 2015 15:15:17 +0200 Subject: [PATCH 0485/1263] conditional TGenericSeq extension --- lib/core/typeinfo.nim | 10 +++++++--- lib/system.nim | 10 +++++++--- lib/system/sysstr.nim | 6 ++++-- 3 files changed, 18 insertions(+), 8 deletions(-) diff --git a/lib/core/typeinfo.nim b/lib/core/typeinfo.nim index 9d29f6a00..dc97784c3 100644 --- a/lib/core/typeinfo.nim +++ b/lib/core/typeinfo.nim @@ -67,12 +67,16 @@ type pbyteArray = ptr array[0.. 0xffff, int8] TGenericSeq {.importc.} = object - len, space, elemSize: int + len, space: int + when defined(gogc): + elemSize: int PGenSeq = ptr TGenericSeq {.deprecated: [TAny: Any, TAnyKind: AnyKind].} -const - GenericSeqSize = (3 * sizeof(int)) +when defined(gogc): + const GenericSeqSize = (3 * sizeof(int)) +else: + const GenericSeqSize = (2 * sizeof(int)) proc genericAssign(dest, src: pointer, mt: PNimType) {.importCompilerProc.} proc genericShallowAssign(dest, src: pointer, mt: PNimType) {. diff --git a/lib/system.nim b/lib/system.nim index 5d723bed3..2beb5b88d 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -304,7 +304,9 @@ const ArrayDummySize = when defined(cpu16): 10_000 else: 100_000_000 when not defined(JS): type TGenericSeq {.compilerproc, pure, inheritable.} = object - len, reserved, elemSize: int + len, reserved: int + when defined(gogc): + elemSize: int PGenericSeq {.exportc.} = ptr TGenericSeq UncheckedCharArray {.unchecked.} = array[0..ArrayDummySize, char] # len and space without counting the terminating zero: @@ -2682,8 +2684,10 @@ when not defined(JS): #and not defined(NimrodVM): when not defined(NimrodVM): include "system/sets" - const - GenericSeqSize = (3 * sizeof(int)) + when defined(gogc): + const GenericSeqSize = (3 * sizeof(int)) + else: + const GenericSeqSize = (2 * sizeof(int)) proc getDiscriminant(aa: pointer, n: ptr TNimNode): int = sysAssert(n.kind == nkCase, "getDiscriminant: node != nkCase") diff --git a/lib/system/sysstr.nim b/lib/system/sysstr.nim index 6e3c8722d..33629016f 100644 --- a/lib/system/sysstr.nim +++ b/lib/system/sysstr.nim @@ -50,14 +50,16 @@ proc rawNewStringNoInit(space: int): NimString {.compilerProc.} = if s < 7: s = 7 result = allocStrNoInit(sizeof(TGenericSeq) + s + 1) result.reserved = s - result.elemSize = 1 + when defined(gogc): + result.elemSize = 1 proc rawNewString(space: int): NimString {.compilerProc.} = var s = space if s < 7: s = 7 result = allocStr(sizeof(TGenericSeq) + s + 1) result.reserved = s - result.elemSize = 1 + when defined(gogc): + result.elemSize = 1 proc mnewString(len: int): NimString {.compilerProc.} = result = rawNewString(len) From 68aa6309e4dcc2a2cdb96593cc345c4e43a7c717 Mon Sep 17 00:00:00 2001 From: apense Date: Tue, 16 Jun 2015 18:57:19 -0400 Subject: [PATCH 0486/1263] Added uints to Leaf nodes [This question on SO](http://stackoverflow.com/questions/30311110/how-to-create-a-nnkuint16lit-nimnode) made me realized these weren't in there --- doc/astspec.txt | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/doc/astspec.txt b/doc/astspec.txt index 7514838da..596d07bab 100644 --- a/doc/astspec.txt +++ b/doc/astspec.txt @@ -60,6 +60,10 @@ Nim expression Corresponding AST ``42'i16`` ``nnkInt16Lit(intVal = 42)`` ``42'i32`` ``nnkInt32Lit(intVal = 42)`` ``42'i64`` ``nnkInt64Lit(intVal = 42)`` +``42'u8`` ``nnkUInt8Lit(intVal = 42)`` +``42'u16`` ``nnkUInt16Lit(intVal = 42)`` +``42'u32`` ``nnkUInt32Lit(intVal = 42)`` +``42'u64`` ``nnkUInt64Lit(intVal = 42)`` ``42.0`` ``nnkFloatLit(floatVal = 42.0)`` ``42.0'f32`` ``nnkFloat32Lit(floatVal = 42.0)`` ``42.0'f64`` ``nnkFloat64Lit(floatVal = 42.0)`` From 80d6b0e9ca3c58d33d17c07f14744e8425864d8f Mon Sep 17 00:00:00 2001 From: apense Date: Wed, 17 Jun 2015 13:07:38 -0400 Subject: [PATCH 0487/1263] Fixed gcc batch issue See #18 on csources. Basically, some Windows system have gcc as a gcc.bat file. This isn't an issue unless you're calling from another batch file (like here). The call chain will follow to gcc.bat and end there, meaning only one command is processed. Using "CALL" before the other batch command will keep the calls in the main batch file after completion, meaning the compilation will actually succeed this way [see technet](https://technet.microsoft.com/en-us/library/bb490873.aspx). Otherwise you have to hope there is a gcc.exe somewhere instead --- tools/niminst/buildbat.tmpl | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/niminst/buildbat.tmpl b/tools/niminst/buildbat.tmpl index 3a11715bf..2c6a2b5a8 100644 --- a/tools/niminst/buildbat.tmpl +++ b/tools/niminst/buildbat.tmpl @@ -18,13 +18,13 @@ REM call the compiler: # for ff in items(c.cfiles[winIndex][cpuIndex]): # let f = ff.toWin ECHO %CC% %COMP_FLAGS% -Ic_code -c ?{f} -o ?{changeFileExt(f, "o")} -%CC% %COMP_FLAGS% -Ic_code -c ?{f} -o ?{changeFileExt(f, "o")} +CALL %CC% %COMP_FLAGS% -Ic_code -c ?{f} -o ?{changeFileExt(f, "o")} # linkCmd.add(" " & changeFileExt(f, "o")) IF ERRORLEVEL 1 (GOTO:END) # end for ECHO %LINKER% -o ?{"%BIN_DIR%"\toLower(c.name)}.exe ?linkCmd %LINK_FLAGS% -%LINKER% -o ?{"%BIN_DIR%"\toLower(c.name)}.exe ?linkCmd %LINK_FLAGS% +CALL %LINKER% -o ?{"%BIN_DIR%"\toLower(c.name)}.exe ?linkCmd %LINK_FLAGS% # end block From 5824b1c83982c53cc493129ea67047906f7ae02a Mon Sep 17 00:00:00 2001 From: yglukhov Date: Wed, 17 Jun 2015 20:56:56 +0300 Subject: [PATCH 0488/1263] Fixes #2917 --- lib/system/jssys.nim | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/lib/system/jssys.nim b/lib/system/jssys.nim index 5a9333a0e..82cf18299 100644 --- a/lib/system/jssys.nim +++ b/lib/system/jssys.nim @@ -175,12 +175,25 @@ proc cstrToNimstr(c: cstring): string {.asmNoStackFrame, compilerproc.} = proc toJSStr(s: string): cstring {.asmNoStackFrame, compilerproc.} = asm """ var len = `s`.length-1; - var result = new Array(len); + var asciiPart = new Array(len); var fcc = String.fromCharCode; + var nonAsciiPart = null; for (var i = 0; i < len; ++i) { - result[i] = fcc(`s`[i]); + if (nonAsciiPart !== null) { + nonAsciiPart[i * 2] = "%"; + nonAsciiPart[i * 2 + 1] = `s`[i].toString(16); + } + else if (`s`[i] < 128) + asciiPart[i] = fcc(`s`[i]); + else { + asciiPart.length = i; + nonAsciiPart = new Array((len - i) * 2); + --i; + } } - return result.join(""); + asciiPart = asciiPart.join(""); + return (nonAsciiPart === null) ? + asciiPart : asciiPart + decodeURIComponent(nonAsciiPart.join("")); """ proc mnewString(len: int): string {.asmNoStackFrame, compilerproc.} = From 50d2d54fb0799def08c2dcb42b64989d7b7bcfa8 Mon Sep 17 00:00:00 2001 From: yglukhov Date: Wed, 17 Jun 2015 23:26:38 +0300 Subject: [PATCH 0489/1263] Fixed fix of #2917 --- lib/system/jssys.nim | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/lib/system/jssys.nim b/lib/system/jssys.nim index 82cf18299..242f42c16 100644 --- a/lib/system/jssys.nim +++ b/lib/system/jssys.nim @@ -178,15 +178,18 @@ proc toJSStr(s: string): cstring {.asmNoStackFrame, compilerproc.} = var asciiPart = new Array(len); var fcc = String.fromCharCode; var nonAsciiPart = null; + var nonAsciiOffset = 0; for (var i = 0; i < len; ++i) { if (nonAsciiPart !== null) { - nonAsciiPart[i * 2] = "%"; - nonAsciiPart[i * 2 + 1] = `s`[i].toString(16); + var offset = (i - nonAsciiOffset) * 2; + nonAsciiPart[offset] = "%"; + nonAsciiPart[offset + 1] = `s`[i].toString(16); } else if (`s`[i] < 128) asciiPart[i] = fcc(`s`[i]); else { asciiPart.length = i; + nonAsciiOffset = i; nonAsciiPart = new Array((len - i) * 2); --i; } From 49465c470c348ef1e8fc8fd546666b1de66c1e7c Mon Sep 17 00:00:00 2001 From: apense Date: Wed, 17 Jun 2015 16:54:02 -0400 Subject: [PATCH 0490/1263] More documentation of AST Also gave some examples --- doc/astspec.txt | 96 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 95 insertions(+), 1 deletion(-) diff --git a/doc/astspec.txt b/doc/astspec.txt index 596d07bab..ebc39322f 100644 --- a/doc/astspec.txt +++ b/doc/astspec.txt @@ -824,10 +824,23 @@ AST: .. code-block:: nim nnkExportStmt(nnkIdent(!"unsigned")) +Similar to the ``import`` statement, the AST is different for +``export ... except``. + +Concrete syntax: + +.. code-block:: nim + export math except pow # we're going to implement our own exponentiation + +AST: + +.. code-block:: nim + nnkExportExceptStmt(nnkIdent(!"math"),nnkIdent(!"pow")) + Include statement ----------------- -Like a plain ``import`` statement. +Like a plain ``import`` statement but with ``nnkIncludeStmt``. Concrete syntax: @@ -872,6 +885,20 @@ Let section This is equivalent to ``var``, but with ``nnkLetSection`` rather than ``nnkVarSection``. +Concrete syntax: + +.. code-block:: nim + let v = 3 + +AST: + +.. code-block:: nim + nnkLetSection( + nnkIdentDefs(!"v"), + nnkEmpty(), # for the type + nnkIntLit(3) + ) + Const section ------------- @@ -983,6 +1010,73 @@ AST: ) ) +Nim's object syntax is rich. Let's take a look at an involved example in +its entirety to see some of the complexities. + +Concrete syntax: + +.. code-block:: nim + type Obj[T] = object {.inheritable.} + name: string + case isFat: bool + of true: + m: array[100_000, T] + of false: + m: array[10, T] + +AST: + +.. code-block:: nim + # ... + nnkObjectTy( + nnkPragma( + nnkIdent(!"inheritable") + ), + nnkEmpty(), + nnkRecList( # list of object parameters + nnkIdentDefs( + nnkIdent(!"name"), + nnkIdent(!"string"), + nnkEmpty() + ), + nnkRecCase( # case statement within object (not nnkCaseStmt) + nnkIdentDefs( + nnkIdent(!"isFat"), + nnkIdent(!"bool"), + nnkEmpty() + ), + nnkOfBranch( + nnkIdent(!"true"), + nnkRecList( # again, a list of object parameters + nnkIdentDefs( + nnkIdent(!"m"), + nnkBracketExpr( + nnkIdent(!"array"), + nnkIntLit(100000), + nnkIdent(!"T") + ), + nnkEmpty() + ) + ), + nnkOfBranch( + nnkIdent(!"false"), + nnkRecList( + nnkIdentDefs( + nnkIdent(!"m"), + nnkBracketExpr( + nnkIdent(!"array"), + nnkIntLit(10), + nnkIdent(!"T") + ), + nnkEmpty() + ) + ) + ) + ) + ) + ) + + Using an ``enum`` is similar to using an ``object``. Concrete syntax: From ea1809a931d401e97959f8fd3ddd44b5f65c77c0 Mon Sep 17 00:00:00 2001 From: apense Date: Wed, 17 Jun 2015 19:56:32 -0400 Subject: [PATCH 0491/1263] Added `isSorted` proc Linear-time verification that an openarray is sorted. Operates on the same parameters as `sort`. Seems much cheaper for large sorts. --- lib/pure/algorithm.nim | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/lib/pure/algorithm.nim b/lib/pure/algorithm.nim index c9f779018..bfc2e0351 100644 --- a/lib/pure/algorithm.nim +++ b/lib/pure/algorithm.nim @@ -237,6 +237,19 @@ template sortedByIt*(seq1, op: expr): expr = result = cmp(a, b)) result +proc isSorted*[T](a: openarray[T], + cmp: proc(x, y: T): int {.closure.}, + order = SortOrder.Ascending): bool = + ## Tests whether `a` is sorted + if len(a) <= 1: return true # empty or one-element lists are already sorted + + result = true + for i in 0.. Date: Wed, 17 Jun 2015 20:14:53 -0400 Subject: [PATCH 0492/1263] Fixed silly continue The old if/else was weird and unnecessary --- lib/pure/algorithm.nim | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/lib/pure/algorithm.nim b/lib/pure/algorithm.nim index bfc2e0351..32bf9eb98 100644 --- a/lib/pure/algorithm.nim +++ b/lib/pure/algorithm.nim @@ -240,14 +240,11 @@ template sortedByIt*(seq1, op: expr): expr = proc isSorted*[T](a: openarray[T], cmp: proc(x, y: T): int {.closure.}, order = SortOrder.Ascending): bool = - ## Tests whether `a` is sorted - if len(a) <= 1: return true # empty or one-element lists are already sorted + if len(a) <= 1: return true result = true for i in 0.. 0: return false proc product*[T](x: openArray[seq[T]]): seq[seq[T]] = From e5e80d20368fa79618210609e94f72b8ddb7e68f Mon Sep 17 00:00:00 2001 From: Felipe Mamud Date: Thu, 18 Jun 2015 00:21:08 -0300 Subject: [PATCH 0493/1263] Add G+ Nim community The G+ Nim community is another place where discussions related to the language happen. Read and follow various articles, posts and interesting links about Nim. --- web/community.txt | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/web/community.txt b/web/community.txt index 12d024871..1348f7bec 100644 --- a/web/community.txt +++ b/web/community.txt @@ -78,6 +78,13 @@ Nim's Community When asking a question relating to Nim, be sure to use the `Nim `_ tag in your question. + +.. container:: standout + + Google+ + ------- + + The `G+ Nim community `_ is another place where discussions related to the language happen. Read and follow various articles, posts and interesting links about Nim. .. container:: standout From 9ae4a0425a8ba50db2d536016ff7e61e87c41da0 Mon Sep 17 00:00:00 2001 From: yglukhov Date: Thu, 18 Jun 2015 13:35:21 +0300 Subject: [PATCH 0494/1263] Fixes #2617, fixes addr of obj downcast. --- compiler/jsgen.nim | 53 ++++++++++++++++++++++++++++------------------ 1 file changed, 32 insertions(+), 21 deletions(-) diff --git a/compiler/jsgen.nim b/compiler/jsgen.nim index d84b0f2f9..77cb805f6 100644 --- a/compiler/jsgen.nim +++ b/compiler/jsgen.nim @@ -33,7 +33,7 @@ import ast, astalgo, strutils, hashes, trees, platform, magicsys, extccomp, options, nversion, nimsets, msgs, securehash, bitsets, idents, lists, types, os, times, ropes, math, passes, ccgutils, wordrecg, renderer, rodread, rodutils, - intsets, cgmeth, lowerings + intsets, cgmeth, lowerings, sets type TTarget = enum @@ -968,7 +968,9 @@ proc genAddr(p: PProc, n: PNode, r: var TCompRes) = of tyTuple: genFieldAddr(p, n.sons[0], r) else: internalError(n.sons[0].info, "expr(nkBracketExpr, " & $kindOfIndexedExpr & ')') - else: internalError(n.sons[0].info, "genAddr") + of nkObjDownConv: + gen(p, n.sons[0], r) + else: internalError(n.sons[0].info, "genAddr: " & $n.sons[0].kind) proc genProcForSymIfNeeded(p: PProc, s: PSym) = if not p.g.generatedSyms.containsOrIncl(s.id): @@ -1096,24 +1098,34 @@ proc putToSeq(s: string, indirect: bool): Rope = if indirect: result = "[$1]" % [result] proc createVar(p: PProc, typ: PType, indirect: bool): Rope -proc createRecordVarAux(p: PProc, rec: PNode, c: var int): Rope = - result = nil +proc createRecordVarAux(p: PProc, rec: PNode, excludeMembers: HashSet[string], output: var Rope) = case rec.kind of nkRecList: for i in countup(0, sonsLen(rec) - 1): - add(result, createRecordVarAux(p, rec.sons[i], c)) + createRecordVarAux(p, rec.sons[i], excludeMembers, output) of nkRecCase: - add(result, createRecordVarAux(p, rec.sons[0], c)) + createRecordVarAux(p, rec.sons[0], excludeMembers, output) for i in countup(1, sonsLen(rec) - 1): - add(result, createRecordVarAux(p, lastSon(rec.sons[i]), c)) + createRecordVarAux(p, lastSon(rec.sons[i]), excludeMembers, output) of nkSym: - if c > 0: add(result, ", ") - add(result, mangleName(rec.sym)) - add(result, ": ") - add(result, createVar(p, rec.sym.typ, false)) - inc(c) + let name = $mangleName(rec.sym) + if not (name in excludeMembers): + if output.len > 0: output.add(", ") + output.add(name) + output.add(": ") + output.add(createVar(p, rec.sym.typ, false)) else: internalError(rec.info, "createRecordVarAux") +proc createObjInitList(p: PProc, typ: PType, excludeMembers: HashSet[string], output: var Rope) = + var t = typ + if tfFinal notin t.flags or t.sons[0] != nil: + if not ("m_type" in excludeMembers): + if output.len > 0: output.add(", ") + addf(output, "m_type: $1" | "m_type = $#", [genTypeInfo(p, t)]) + while t != nil: + createRecordVarAux(p, t.n, excludeMembers, output) + t = t.sons[0] + proc createVar(p: PProc, typ: PType, indirect: bool): Rope = var t = skipTypes(typ, abstractInst) case t.kind @@ -1154,15 +1166,10 @@ proc createVar(p: PProc, typ: PType, indirect: bool): Rope = add(result, "}") if indirect: result = "[$1]" % [result] of tyObject: - result = rope("{") - var c = 0 - if tfFinal notin t.flags or t.sons[0] != nil: - inc(c) - addf(result, "m_type: $1" | "m_type = $#", [genTypeInfo(p, t)]) - while t != nil: - add(result, createRecordVarAux(p, t.n, c)) - t = t.sons[0] - add(result, "}") + var emptySet = initSet[string](2) + var initList : Rope + createObjInitList(p, t, emptySet, initList) + result = "{$1}" % [initList] if indirect: result = "[$1]" % [result] of tyVar, tyPtr, tyRef: if mapType(t) == etyBaseIndex: @@ -1435,6 +1442,7 @@ proc genObjConstr(p: PProc, n: PNode, r: var TCompRes) = var a: TCompRes r.res = rope("{") r.kind = resExpr + var fieldNames = initSet[string]() for i in countup(1, sonsLen(n) - 1): if i > 1: add(r.res, ", ") var it = n.sons[i] @@ -1442,7 +1450,10 @@ proc genObjConstr(p: PProc, n: PNode, r: var TCompRes) = gen(p, it.sons[1], a) var f = it.sons[0].sym if f.loc.r == nil: f.loc.r = mangleName(f) + fieldNames.incl($f.loc.r) addf(r.res, "$#: $#" | "$# = $#" , [f.loc.r, a.res]) + let t = skipTypes(n.typ, abstractInst + skipPtrs) + createObjInitList(p, t, fieldNames, r.res) r.res.add("}") proc genConv(p: PProc, n: PNode, r: var TCompRes) = From 273d6ffc16aa56c1be9d1e7df0612105dcb10c77 Mon Sep 17 00:00:00 2001 From: Sergey Avseyev Date: Thu, 18 Jun 2015 13:57:20 +0300 Subject: [PATCH 0495/1263] Remove trailing spaces in doc/astspec.txt --- doc/astspec.txt | 114 ++++++++++++++++++++++++------------------------ 1 file changed, 57 insertions(+), 57 deletions(-) diff --git a/doc/astspec.txt b/doc/astspec.txt index 596d07bab..3945293d0 100644 --- a/doc/astspec.txt +++ b/doc/astspec.txt @@ -40,16 +40,16 @@ For the ``NimNode`` type, the ``[]`` operator has been overloaded: ``n[i]`` is ``n``'s ``i``-th child. To specify the AST for the different Nim constructs, the notation -``nodekind(son1, son2, ...)`` or ``nodekind(value)`` or +``nodekind(son1, son2, ...)`` or ``nodekind(value)`` or ``nodekind(field=value)`` is used. -Some child may be missing. A missing child is a node of kind ``nnkEmpty``; +Some child may be missing. A missing child is a node of kind ``nnkEmpty``; a child can never be nil. Leaf nodes/Atoms ================ -A leaf of the AST often corresponds to a terminal symbol in the concrete +A leaf of the AST often corresponds to a terminal symbol in the concrete syntax. ----------------- --------------------------------------------- @@ -95,8 +95,8 @@ AST: .. code-block:: nim nnkCommand( - nnkIdent(!"echo"), - nnkStrLit("abc"), + nnkIdent(!"echo"), + nnkStrLit("abc"), nnkStrLit("xyz") ) @@ -113,8 +113,8 @@ AST: .. code-block:: nim nnkCall( - nnkIdent(!"echo"), - nnkStrLit("abc"), + nnkIdent(!"echo"), + nnkStrLit("abc"), nnkStrLit("xyz") ) @@ -131,12 +131,12 @@ AST: .. code-block:: nim nnkInfix( - nnkIdent(!"&"), - nnkStrLit("abc"), + nnkIdent(!"&"), + nnkStrLit("abc"), nnkStrLit("xyz") ) -Note that with multiple infix operators, the command is parsed by operator +Note that with multiple infix operators, the command is parsed by operator precedence. Concrete syntax: @@ -148,18 +148,18 @@ AST: .. code-block:: nim nnkInfix( - nnkIdent(!"+"), + nnkIdent(!"+"), nnkIntLit(5), nnkInfix( - nnkIdent(!"*"), - nnkIntLit(3), + nnkIdent(!"*"), + nnkIntLit(3), nnkIntLit(4) ) ) -As a side note, if you choose to use infix operators in a prefix form, the AST -behaves as a -[parenthetical function call](./macros.html#calls-expressions-call-with) with +As a side note, if you choose to use infix operators in a prefix form, the AST +behaves as a +[parenthetical function call](./macros.html#calls-expressions-call-with) with ``nnkAccQuoted``, as follows: Concrete syntax: @@ -173,8 +173,8 @@ AST: nnkCall( nnkAccQuoted( nnkIdent(!"+") - ), - nnkIntLit(3), + ), + nnkIntLit(3), nnkIntLit(4) ) @@ -190,7 +190,7 @@ AST: .. code-block:: nim nnkPrefix( - nnkIdent(!"?"), + nnkIdent(!"?"), nnkStrLit("abc") ) @@ -198,7 +198,7 @@ AST: Postfix operator call --------------------- -**Note:** There are no postfix operators in Nim. However, the +**Note:** There are no postfix operators in Nim. However, the ``nnkPostfix`` node is used for the *asterisk export marker* ``*``: Concrete syntax: @@ -210,7 +210,7 @@ AST: .. code-block:: nim nnkPostfix( - nnkIdent(!"*"), + nnkIdent(!"*"), nnkIdent(!"identifier") ) @@ -227,11 +227,11 @@ AST: .. code-block:: nim nnkCall( - nnkIdent(!"writeln"), + nnkIdent(!"writeln"), nnkExprEqExpr( - nnkIdent(!"file"), + nnkIdent(!"file"), nnkIdent(!"stdout") - ), + ), nnkStrLit("hallo") ) @@ -310,7 +310,7 @@ AST: .. code-block:: nim nnkDotExpr(nnkIdent(!"x"), nnkIdent(!"y")) -If you use Nim's flexible calling syntax (as in ``x.len()``), the result is the +If you use Nim's flexible calling syntax (as in ``x.len()``), the result is the same as above but wrapped in an ``nnkCall``. @@ -331,7 +331,7 @@ AST: Parentheses ----------- -Parentheses for affecting operator precedence or tuple construction +Parentheses for affecting operator precedence or tuple construction are built with the ``nnkPar`` node. Concrete syntax: @@ -343,12 +343,12 @@ AST: .. code-block:: nim nnkPar(nnkIntLit(1), nnkIntLit(2), nnkPar(nnkIntLit(3))) - - + + Curly braces ------------ -Curly braces are used as the set constructor. +Curly braces are used as the set constructor. Concrete syntax: @@ -379,7 +379,7 @@ AST: Brackets -------- -Brackets are used as the array constructor. +Brackets are used as the array constructor. Concrete syntax: @@ -430,8 +430,8 @@ AST: Documentation Comments ---------------------- -Double-hash (``##``) comments in the code actually have their own format, -but the comments do not yet show up in the AST, which will only show that +Double-hash (``##``) comments in the code actually have their own format, +but the comments do not yet show up in the AST, which will only show that a comment exists, not what it contains. Single-hash (``#``) comments are ignored. Concrete syntax: @@ -447,14 +447,14 @@ AST: .. code-block:: nim nnkCommentStmt() # only appears once for the first two lines! stmt1 - nnkCommentStmt() # another nnkCommentStmt because there is another comment + nnkCommentStmt() # another nnkCommentStmt because there is another comment # (separate from the first) Pragmas ------- One of Nim's cool features is pragmas, which allow fine-tuning of various -aspects of the language. They come in all types, such as adorning procs and +aspects of the language. They come in all types, such as adorning procs and objects, but the standalone ``emit`` pragma shows the basics with the AST. Concrete syntax: @@ -503,7 +503,7 @@ there is no ``else`` branch, no ``nnkElse`` child exists. Concrete syntax: .. code-block:: nim - if cond1: + if cond1: stmt1 elif cond2: stmt2 @@ -560,7 +560,7 @@ AST: .. code-block:: nim nnkStmtList(stmt1, stmt2, stmt3) - + Case statement -------------- @@ -568,7 +568,7 @@ Concrete syntax: .. code-block:: nim case expr1 - of expr2, expr3..expr4: + of expr2, expr3..expr4: stmt1 of expr5: stmt2 @@ -629,11 +629,11 @@ Concrete syntax: .. code-block:: nim try: stmt1 - except e1, e2: + except e1, e2: stmt2 except e3: stmt3 - except: + except: stmt4 finally: stmt5 @@ -642,9 +642,9 @@ AST: .. code-block:: nim nnkTryStmt( - stmt1, - nnkExceptBranch(e1, e2, stmt2), - nnkExceptBranch(e3, stmt3), + stmt1, + nnkExceptBranch(e1, e2, stmt2), + nnkExceptBranch(e3, stmt3), nnkExceptBranch(stmt4), nnkFinally(stmt5) ) @@ -862,8 +862,8 @@ Note that either the second or third (or both) parameters above must exist, as the compiler needs to know the type somehow (which it can infer from the given assignment). -This is not the same AST for all uses of ``var``. See -[Procedure declaration](http://nim-lang.org/docs/macros.html#statements-procedure-declaration) +This is not the same AST for all uses of ``var``. See +[Procedure declaration](http://nim-lang.org/docs/macros.html#statements-procedure-declaration) for details. Let section @@ -894,7 +894,7 @@ AST: Type section ------------ -Starting with the simplest case, a ``type`` section appears much like ``var`` +Starting with the simplest case, a ``type`` section appears much like ``var`` and ``const``. Concrete syntax: @@ -949,7 +949,7 @@ AST: nnkGenericParams( nnkIdentDefs( nnkIdent(!"T"), - nnkEmpty(), # if the type is declared with options, like + nnkEmpty(), # if the type is declared with options, like # ``[T: SomeInteger]``, they are given here nnkEmpty(), ) @@ -1019,7 +1019,7 @@ AST: # ... ) -Static types, like ``static[int]``, use ``nnkIdent`` wrapped in +Static types, like ``static[int]``, use ``nnkIdent`` wrapped in ``nnkStaticTy``. Concrete syntax: @@ -1085,7 +1085,7 @@ AST: ) The same syntax applies to ``iterator``s (with ``nnkIteratorTy``), but -*does not* apply to ``converter``s or ``template``s. +*does not* apply to ``converter``s or ``template``s. Mixin statement --------------- @@ -1138,13 +1138,13 @@ AST: nnkFormalParams( nnkIdent(!"int"), # the first FormalParam is the return type. nnkEmpty() if there is none nnkIdentDefs( - nnkIdent(!"x"), + nnkIdent(!"x"), nnkIdent(!"int"), # type type (required for procs, not for templates) nnkIntLit(3) # a default value ), nnkIdentDefs( - nnkIdent(!"y"), - nnkIdent(!"float32"), + nnkIdent(!"y"), + nnkIdent(!"float32"), nnkEmpty() ) nnkPragma(nnkIdent(!"inline")), @@ -1177,7 +1177,7 @@ AST: ), # ... -When a procedure uses the special ``var`` type return variable, the result +When a procedure uses the special ``var`` type return variable, the result is different from that of a var section. Concrete syntax: @@ -1198,7 +1198,7 @@ AST: Iterator declaration -------------------- -The syntax for iterators is similar to procs, but with ``nnkIteratorDef`` +The syntax for iterators is similar to procs, but with ``nnkIteratorDef`` replacing ``nnkProcDef``. Concrete syntax: @@ -1239,7 +1239,7 @@ Template declaration Templates (as well as macros, as we'll see) have a slightly expanded AST when compared to procs and iterators. The reason for this is [term-rewriting macros](http://nim-lang.org/docs/manual.html#term-rewriting-macros). Notice -the ``nnkEmpty()`` as the second argument to ``nnkProcDef`` and +the ``nnkEmpty()`` as the second argument to ``nnkProcDef`` and ``nnkIteratorDef`` above? That's where the term-rewriting macros go. Concrete syntax: @@ -1264,16 +1264,16 @@ inside ``nnkFormalParams`` just becomes ``nnkEmpty``. Macro declaration ----------------- -Macros behave like templates, but ``nnkTemplateDef`` is replaced with +Macros behave like templates, but ``nnkTemplateDef`` is replaced with ``nnkMacroDef``. Special node kinds ================== -There are several node kinds that are used for semantic checking or code +There are several node kinds that are used for semantic checking or code generation. These are accessible from this module, but should not be used. Other node kinds are especially designed to make AST manipulations easier. -These are explained here. +These are explained here. To be written. From 137c836616f471abdcfafc21376ee5a5f65efc08 Mon Sep 17 00:00:00 2001 From: Sergey Avseyev Date: Thu, 18 Jun 2015 14:04:15 +0300 Subject: [PATCH 0496/1263] Fix reST syntax in doc/astspec.txt --- doc/astspec.txt | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/doc/astspec.txt b/doc/astspec.txt index 3945293d0..3a67eca7e 100644 --- a/doc/astspec.txt +++ b/doc/astspec.txt @@ -1059,7 +1059,7 @@ Nim type Corresponding AST ``iterator`` ``nnkIteratorTy`` ``object`` ``nnkObjectTy`` -Take special care when declaring types as ``proc``s. The behavior is similar +Take special care when declaring types as ``proc``. The behavior is similar to ``Procedure declaration``, below, but does not treat ``nnkGenericParams``. Generic parameters are treated in the type, not the ``proc`` itself. @@ -1084,8 +1084,8 @@ AST: ) ) -The same syntax applies to ``iterator``s (with ``nnkIteratorTy``), but -*does not* apply to ``converter``s or ``template``s. +The same syntax applies to ``iterator`` (with ``nnkIteratorTy``), but +*does not* apply to ``converter`` or ``template``. Mixin statement --------------- From 85d5c86efaa6c03903a7efff9721e8f89c42de89 Mon Sep 17 00:00:00 2001 From: yglukhov Date: Thu, 18 Jun 2015 15:09:43 +0300 Subject: [PATCH 0497/1263] Changed sets of strings to IntSets --- compiler/jsgen.nim | 33 +++++++++++++++------------------ 1 file changed, 15 insertions(+), 18 deletions(-) diff --git a/compiler/jsgen.nim b/compiler/jsgen.nim index 77cb805f6..ede759426 100644 --- a/compiler/jsgen.nim +++ b/compiler/jsgen.nim @@ -33,7 +33,7 @@ import ast, astalgo, strutils, hashes, trees, platform, magicsys, extccomp, options, nversion, nimsets, msgs, securehash, bitsets, idents, lists, types, os, times, ropes, math, passes, ccgutils, wordrecg, renderer, rodread, rodutils, - intsets, cgmeth, lowerings, sets + intsets, cgmeth, lowerings type TTarget = enum @@ -1098,32 +1098,30 @@ proc putToSeq(s: string, indirect: bool): Rope = if indirect: result = "[$1]" % [result] proc createVar(p: PProc, typ: PType, indirect: bool): Rope -proc createRecordVarAux(p: PProc, rec: PNode, excludeMembers: HashSet[string], output: var Rope) = +proc createRecordVarAux(p: PProc, rec: PNode, excludedFieldIDs: IntSet, output: var Rope) = case rec.kind of nkRecList: for i in countup(0, sonsLen(rec) - 1): - createRecordVarAux(p, rec.sons[i], excludeMembers, output) + createRecordVarAux(p, rec.sons[i], excludedFieldIDs, output) of nkRecCase: - createRecordVarAux(p, rec.sons[0], excludeMembers, output) + createRecordVarAux(p, rec.sons[0], excludedFieldIDs, output) for i in countup(1, sonsLen(rec) - 1): - createRecordVarAux(p, lastSon(rec.sons[i]), excludeMembers, output) + createRecordVarAux(p, lastSon(rec.sons[i]), excludedFieldIDs, output) of nkSym: - let name = $mangleName(rec.sym) - if not (name in excludeMembers): + if rec.sym.id notin excludedFieldIDs: if output.len > 0: output.add(", ") - output.add(name) + output.add(mangleName(rec.sym)) output.add(": ") output.add(createVar(p, rec.sym.typ, false)) else: internalError(rec.info, "createRecordVarAux") -proc createObjInitList(p: PProc, typ: PType, excludeMembers: HashSet[string], output: var Rope) = +proc createObjInitList(p: PProc, typ: PType, excludedFieldIDs: IntSet, output: var Rope) = var t = typ if tfFinal notin t.flags or t.sons[0] != nil: - if not ("m_type" in excludeMembers): - if output.len > 0: output.add(", ") - addf(output, "m_type: $1" | "m_type = $#", [genTypeInfo(p, t)]) + if output.len > 0: output.add(", ") + addf(output, "m_type: $1" | "m_type = $#", [genTypeInfo(p, t)]) while t != nil: - createRecordVarAux(p, t.n, excludeMembers, output) + createRecordVarAux(p, t.n, excludedFieldIDs, output) t = t.sons[0] proc createVar(p: PProc, typ: PType, indirect: bool): Rope = @@ -1166,9 +1164,8 @@ proc createVar(p: PProc, typ: PType, indirect: bool): Rope = add(result, "}") if indirect: result = "[$1]" % [result] of tyObject: - var emptySet = initSet[string](2) var initList : Rope - createObjInitList(p, t, emptySet, initList) + createObjInitList(p, t, initIntSet(), initList) result = "{$1}" % [initList] if indirect: result = "[$1]" % [result] of tyVar, tyPtr, tyRef: @@ -1442,7 +1439,7 @@ proc genObjConstr(p: PProc, n: PNode, r: var TCompRes) = var a: TCompRes r.res = rope("{") r.kind = resExpr - var fieldNames = initSet[string]() + var fieldIDs = initIntSet() for i in countup(1, sonsLen(n) - 1): if i > 1: add(r.res, ", ") var it = n.sons[i] @@ -1450,10 +1447,10 @@ proc genObjConstr(p: PProc, n: PNode, r: var TCompRes) = gen(p, it.sons[1], a) var f = it.sons[0].sym if f.loc.r == nil: f.loc.r = mangleName(f) - fieldNames.incl($f.loc.r) + fieldIDs.incl(f.id) addf(r.res, "$#: $#" | "$# = $#" , [f.loc.r, a.res]) let t = skipTypes(n.typ, abstractInst + skipPtrs) - createObjInitList(p, t, fieldNames, r.res) + createObjInitList(p, t, fieldIDs, r.res) r.res.add("}") proc genConv(p: PProc, n: PNode, r: var TCompRes) = From 17cace280ca927a97adc21314141947210fe17b5 Mon Sep 17 00:00:00 2001 From: Araq Date: Thu, 18 Jun 2015 15:05:44 +0200 Subject: [PATCH 0498/1263] fixes #2297, fixes #2946 --- compiler/lowerings.nim | 20 ++++++++++ compiler/vm.nim | 12 ------ compiler/vmdef.nim | 2 +- compiler/vmgen.nim | 7 +--- tests/vm/tconsttable2.nim | 81 +++++++++++++++++++++++++++++++++++++++ tests/vm/tswap.nim | 24 ++++++++++++ 6 files changed, 127 insertions(+), 19 deletions(-) create mode 100644 tests/vm/tconsttable2.nim create mode 100644 tests/vm/tswap.nim diff --git a/compiler/lowerings.nim b/compiler/lowerings.nim index b6b01d558..b4319b246 100644 --- a/compiler/lowerings.nim +++ b/compiler/lowerings.nim @@ -63,6 +63,26 @@ proc lowerTupleUnpacking*(n: PNode; owner: PSym): PNode = if n.sons[i].kind == nkSym: v.addVar(n.sons[i]) result.add newAsgnStmt(n.sons[i], newTupleAccess(tempAsNode, i)) +proc lowerSwap*(n: PNode; owner: PSym): PNode = + result = newNodeI(nkStmtList, n.info) + # note: cannot use 'skTemp' here cause we really need the copy for the VM :-( + var temp = newSym(skVar, getIdent(genPrefix), owner, n.info) + temp.typ = n.sons[1].typ + incl(temp.flags, sfFromGeneric) + + var v = newNodeI(nkVarSection, n.info) + let tempAsNode = newSymNode(temp) + + var vpart = newNodeI(nkIdentDefs, v.info, 3) + vpart.sons[0] = tempAsNode + vpart.sons[1] = ast.emptyNode + vpart.sons[2] = n[1] + addSon(v, vpart) + + result.add(v) + result.add newFastAsgnStmt(n[1], n[2]) + result.add newFastAsgnStmt(n[2], tempAsNode) + proc createObj*(owner: PSym, info: TLineInfo): PType = result = newType(tyObject, owner) rawAddSon(result, nil) diff --git a/compiler/vm.nim b/compiler/vm.nim index 9f0d0bfce..826356c68 100644 --- a/compiler/vm.nim +++ b/compiler/vm.nim @@ -1051,18 +1051,6 @@ proc rawExecute(c: PCtx, start: int, tos: PStackFrame): TFullReg = # set to default value: for i in oldLen .. Date: Tue, 16 Jun 2015 20:10:32 -0400 Subject: [PATCH 0500/1263] Fix flaviut/nre#20 --- lib/impure/nre.nim | 8 ++++++-- tests/stdlib/nre/split.nim | 1 + 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/lib/impure/nre.nim b/lib/impure/nre.nim index 6f92b0d71..973f1f2ee 100644 --- a/lib/impure/nre.nim +++ b/lib/impure/nre.nim @@ -586,9 +586,12 @@ proc split*(str: string, pattern: Regex, maxSplit = -1, start = 0): seq[string] result = @[] var lastIdx = start var splits = 0 - var bounds = 0 .. 0 + var bounds = 0 .. -1 + var never_ran = true for match in str.findIter(pattern, start = start): + never_ran = false + # bounds are inclusive: # # 0123456 @@ -615,7 +618,8 @@ proc split*(str: string, pattern: Regex, maxSplit = -1, start = 0): seq[string] # "12".split("\b") would be @["1", "2", ""], but # if we skip an empty last match, it's the correct # @["1", "2"] - if bounds.a <= bounds.b or bounds.b < str.high: + # If matches were never found, then the input string is the result + if bounds.a <= bounds.b or bounds.b < str.high or never_ran: # last match: Each match takes the previous substring, # but "1 2".split(/ /) needs to return @["1", "2"]. # This handles "2" diff --git a/tests/stdlib/nre/split.nim b/tests/stdlib/nre/split.nim index 8064e40b7..9d57ea7d8 100644 --- a/tests/stdlib/nre/split.nim +++ b/tests/stdlib/nre/split.nim @@ -8,6 +8,7 @@ suite "string splitting": check("1 2".split(re(" ")) == @["1", "2"]) check("foo".split(re("foo")) == @["", ""]) check("".split(re"foo") == @[""]) + check("9".split(re"\son\s") == @["9"]) test "captured patterns": check("12".split(re"(\d)") == @["", "1", "", "2", ""]) From 138cf777da38925a4f91239b8c858112d4464436 Mon Sep 17 00:00:00 2001 From: apense Date: Thu, 18 Jun 2015 14:43:38 -0400 Subject: [PATCH 0501/1263] Removed redundant check Loop takes care of it already --- lib/pure/algorithm.nim | 2 -- 1 file changed, 2 deletions(-) diff --git a/lib/pure/algorithm.nim b/lib/pure/algorithm.nim index 32bf9eb98..b6bcdab7e 100644 --- a/lib/pure/algorithm.nim +++ b/lib/pure/algorithm.nim @@ -240,8 +240,6 @@ template sortedByIt*(seq1, op: expr): expr = proc isSorted*[T](a: openarray[T], cmp: proc(x, y: T): int {.closure.}, order = SortOrder.Ascending): bool = - if len(a) <= 1: return true - result = true for i in 0.. 0: From 0d40fd7552e826aa6ce860d101a5bd49548ed785 Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Thu, 18 Jun 2015 13:51:29 -0500 Subject: [PATCH 0502/1263] explained how to run the tester to compare commits --- contributing.md | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/contributing.md b/contributing.md index 123fd5668..66a57971c 100644 --- a/contributing.md +++ b/contributing.md @@ -89,4 +89,27 @@ which will run a good subset of tests. Some tests may fail. Because some tests fail in the current `devel` branch, not every fail after your change is necessarily caused by your changes. -TODO +The tester can compare two test runs. First, you need to create the +reference test. You'll also need to the commit id, because that's what +the tester needs to know in order to compare the two. + +```bash +git checkout devel +DEVEL_COMMIT=$(git rev-parse HEAD) +./koch tests +``` + +Then switch over to your changes and run the tester again. + +```bash +git checkout your-changes +./koch tests +``` + +Then you can ask the tester to create a `testresults.html` which will +tell you if any new tests passed/failed. + +```bash +./koch html $DEVEL_COMMIT +(xdg-)open testresults.html +``` From 3d77d2b29fae43469f85dc9db38101d8d16470cf Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Thu, 18 Jun 2015 13:59:22 -0500 Subject: [PATCH 0503/1263] switched to ./koch --print html --- contributing.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/contributing.md b/contributing.md index 66a57971c..52088d693 100644 --- a/contributing.md +++ b/contributing.md @@ -110,6 +110,5 @@ Then you can ask the tester to create a `testresults.html` which will tell you if any new tests passed/failed. ```bash -./koch html $DEVEL_COMMIT -(xdg-)open testresults.html +./koch --print html $DEVEL_COMMIT ``` From c0c4a7d6a649e9934530364893228fa65d787991 Mon Sep 17 00:00:00 2001 From: apense Date: Thu, 18 Jun 2015 16:07:00 -0400 Subject: [PATCH 0504/1263] Added some C99 funcs Error function (and complementary) and gamma function (and truncated) --- lib/pure/math.nim | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/lib/pure/math.nim b/lib/pure/math.nim index b91c7f0d8..494dfc4c8 100644 --- a/lib/pure/math.nim +++ b/lib/pure/math.nim @@ -161,6 +161,8 @@ proc randomize*(seed: int) {.benign.} when not defined(JS): proc sqrt*(x: float): float {.importc: "sqrt", header: "".} ## computes the square root of `x`. + proc cbrt*(x: float): float {.importc: "cbrt", header: "".} + ## computes the cubic root of `x` proc ln*(x: float): float {.importc: "log", header: "".} ## computes ln(x). @@ -200,6 +202,16 @@ when not defined(JS): proc tanh*(x: float): float {.importc: "tanh", header: "".} proc pow*(x, y: float): float {.importc: "pow", header: "".} ## computes x to power raised of y. + + proc erf*(x: float): float {.importc: "erf", header: "".} + ## The error function + proc erfc*(x: float): float {.importc: "erfc", header: "".} + ## The complementary error function + + proc lgamma*(x: float): float {.importc: "lgamma", header: "".} + ## Natural log of the gamma function + proc tgamma*(x: float): float {.importc: "tgamma", header: "".} + ## The gamma function # C procs: when defined(vcc): @@ -411,3 +423,9 @@ when isMainModule and not defined(JS): # Check for no side effect annotation proc mySqrt(num: float): float {.noSideEffect.} = return sqrt(num) + + # check gamma function + assert(tgamma(5.0) == 24.0) # 4! + assert(lgamma(1.0) == 0.0) # ln(1.0) == 0.0 + assert(erf(6.0) > erf(5.0)) + assert(erfc(6.0) < erfc(5.0)) From 69ceede3fb363312b0a39042b4887ae2c52d3846 Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Thu, 18 Jun 2015 15:17:51 -0500 Subject: [PATCH 0505/1263] switched to contributing.rst --- contributing.md | 114 ----------------------------------------------- contributing.rst | 114 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 114 insertions(+), 114 deletions(-) delete mode 100644 contributing.md create mode 100644 contributing.rst diff --git a/contributing.md b/contributing.md deleted file mode 100644 index 52088d693..000000000 --- a/contributing.md +++ /dev/null @@ -1,114 +0,0 @@ -# The git stuff - -[Guide by github, scroll down a bit](https://guides.github.com/activities/contributing-to-open-source/) - -# Deprecation - -Backward compatibility is important, so if you are renaming a proc or -a type, you can use - -```nim -{.deprecated [oldName: new_name].} -``` - -Or you can simply use - -```nim -proc oldProc() {.deprecated.} -``` - -to mark a symbol as deprecated. Works for procs/types/vars/consts, -etc. - -[Deprecated pragma in the manual.](http://nim-lang.org/docs/manual.html#pragmas-deprecated-pragma) - -# Writing tests - -Not all the tests follow this scheme, feel free to change the ones -that don't. Always leave the code cleaner than you found it. - -## Stdlib - -If you change the stdlib (anything under `lib/`), put a test in the -file you changed. Add the tests under an `when isMainModule:` -condition so they only get executed when the tester is building the -file. Each test should be in a separate `block:` statement, such that -each has its own scope. Use boolean conditions and `doAssert` for the -testing by itself, don't rely on echo statements or similar. - -Sample test: - -```nim -when isMainModule: - block: # newSeqWith tests - var seq2D = newSeqWith(4, newSeq[bool](2)) - seq2D[0][0] = true - seq2D[1][0] = true - seq2D[0][1] = true - doAssert seq2D == @[@[true, true], @[true, false], @[false, false], @[false, false]] -``` - -## Compiler - -The tests for the compiler work differently, they are all located in -`tests/`. Each test has its own file, which is different from the -stdlib tests. At the beginning of every test is the expected side of -the test. Possible keys are: - -- output: The expected output, most likely via `echo` -- exitcode: Exit code of the test (via `exit(number)`) -- errormsg: The expected error message -- file: The file the errormsg -- line: The line the errormsg was produced at - -An example for a test: -```nim -discard """ - errormsg: "type mismatch: got (PTest)" -""" - -type - PTest = ref object - -proc test(x: PTest, y: int) = nil - -var buf: PTest -buf.test() -``` - -# Running tests - -You can run the tests with - - ./koch tests - -which will run a good subset of tests. Some tests may fail. - -# Comparing tests - -Because some tests fail in the current `devel` branch, not every fail -after your change is necessarily caused by your changes. - -The tester can compare two test runs. First, you need to create the -reference test. You'll also need to the commit id, because that's what -the tester needs to know in order to compare the two. - -```bash -git checkout devel -DEVEL_COMMIT=$(git rev-parse HEAD) -./koch tests -``` - -Then switch over to your changes and run the tester again. - -```bash -git checkout your-changes -./koch tests -``` - -Then you can ask the tester to create a `testresults.html` which will -tell you if any new tests passed/failed. - -```bash -./koch --print html $DEVEL_COMMIT -``` diff --git a/contributing.rst b/contributing.rst new file mode 100644 index 000000000..1f5653c61 --- /dev/null +++ b/contributing.rst @@ -0,0 +1,114 @@ +The git stuff +============= + +`Guide by github, scroll down a bit`_ + +# Deprecation + +Backward compatibility is important, so if you are renaming a proc or +a type, you can use + + +.. code-block:: nim + {.deprecated [oldName: new_name].} + +Or you can simply use + +.. code-block:: nim + proc oldProc() {.deprecated.} + +to mark a symbol as deprecated. Works for procs/types/vars/consts, +etc. + +`Deprecated pragma in the manual.`_ + +Writing tests +============= + +Not all the tests follow this scheme, feel free to change the ones +that don't. Always leave the code cleaner than you found it. + +Stdlib +------ + +If you change the stdlib (anything under ``lib/``), put a test in the +file you changed. Add the tests under an ``when isMainModule:`` +condition so they only get executed when the tester is building the +file. Each test should be in a separate ``block:`` statement, such that +each has its own scope. Use boolean conditions and ``doAssert`` for the +testing by itself, don't rely on echo statements or similar. + +Sample test: + +.. code-block:: nim + when isMainModule: + block: # newSeqWith tests + var seq2D = newSeqWith(4, newSeq[bool](2)) + seq2D[0][0] = true + seq2D[1][0] = true + seq2D[0][1] = true + doAssert seq2D == @[@[true, true], @[true, false], @[false, false], @[false, false]] + +Compiler +-------- + +The tests for the compiler work differently, they are all located in +``tests/``. Each test has its own file, which is different from the +stdlib tests. At the beginning of every test is the expected side of +the test. Possible keys are: + +- output: The expected output, most likely via ``echo`` +- exitcode: Exit code of the test (via ``exit(number)``) +- errormsg: The expected error message +- file: The file the errormsg +- line: The line the errormsg was produced at + +An example for a test: + +.. code-block:: nim + discard """ + errormsg: "type mismatch: got (PTest)" + + type + PTest = ref object + + proc test(x: PTest, y: int) = nil + + var buf: PTest + buf.test() + +Running tests +============= + +You can run the tests with + +.. code-block:: bash + ./koch tests + +which will run a good subset of tests. Some tests may fail. + +# Comparing tests + +Because some tests fail in the current ``devel`` branch, not every fail +after your change is necessarily caused by your changes. + +The tester can compare two test runs. First, you need to create the +reference test. You'll also need to the commit id, because that's what +the tester needs to know in order to compare the two. + +.. code-block:: bash + git checkout devel + DEVEL_COMMIT=$(git rev-parse HEAD) + ./koch tests + +Then switch over to your changes and run the tester again. + +.. code-block:: bash + git checkout your-changes + ./koch tests + +Then you can ask the tester to create a ``testresults.html`` which will +tell you if any new tests passed/failed. + +.. code-block:: bash + ./koch --print html $DEVEL_COMMIT From 24bb11c7bc3027fb05249c6394c2e078c22fe00c Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Thu, 18 Jun 2015 15:34:39 -0500 Subject: [PATCH 0506/1263] fixed some non-rst stuff --- contributing.rst | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/contributing.rst b/contributing.rst index 1f5653c61..0b65d7ae1 100644 --- a/contributing.rst +++ b/contributing.rst @@ -87,7 +87,8 @@ You can run the tests with which will run a good subset of tests. Some tests may fail. -# Comparing tests +Comparing tests +=============== Because some tests fail in the current ``devel`` branch, not every fail after your change is necessarily caused by your changes. From 73d95c9e7b4e8ae9c2e85ca3b9e7b2e394337010 Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Thu, 18 Jun 2015 15:35:22 -0500 Subject: [PATCH 0507/1263] and some more non-rst stuff fixed --- contributing.rst | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/contributing.rst b/contributing.rst index 0b65d7ae1..68265b7c9 100644 --- a/contributing.rst +++ b/contributing.rst @@ -3,7 +3,8 @@ The git stuff `Guide by github, scroll down a bit`_ -# Deprecation +Deprecation +=========== Backward compatibility is important, so if you are renaming a proc or a type, you can use From ab559814d8c53d113b9a46d330246a37612d408a Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Thu, 18 Jun 2015 16:10:54 -0500 Subject: [PATCH 0508/1263] fixed the rst code blocks --- contributing.rst | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/contributing.rst b/contributing.rst index 68265b7c9..74b15bf3f 100644 --- a/contributing.rst +++ b/contributing.rst @@ -11,11 +11,13 @@ a type, you can use .. code-block:: nim + {.deprecated [oldName: new_name].} Or you can simply use .. code-block:: nim + proc oldProc() {.deprecated.} to mark a symbol as deprecated. Works for procs/types/vars/consts, @@ -42,6 +44,7 @@ testing by itself, don't rely on echo statements or similar. Sample test: .. code-block:: nim + when isMainModule: block: # newSeqWith tests var seq2D = newSeqWith(4, newSeq[bool](2)) @@ -67,6 +70,7 @@ the test. Possible keys are: An example for a test: .. code-block:: nim + discard """ errormsg: "type mismatch: got (PTest)" @@ -84,6 +88,7 @@ Running tests You can run the tests with .. code-block:: bash + ./koch tests which will run a good subset of tests. Some tests may fail. @@ -99,6 +104,7 @@ reference test. You'll also need to the commit id, because that's what the tester needs to know in order to compare the two. .. code-block:: bash + git checkout devel DEVEL_COMMIT=$(git rev-parse HEAD) ./koch tests @@ -106,6 +112,7 @@ the tester needs to know in order to compare the two. Then switch over to your changes and run the tester again. .. code-block:: bash + git checkout your-changes ./koch tests @@ -113,4 +120,5 @@ Then you can ask the tester to create a ``testresults.html`` which will tell you if any new tests passed/failed. .. code-block:: bash + ./koch --print html $DEVEL_COMMIT From 17d2ab82a86d49d3b296fef888ef644cc42ee623 Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Thu, 18 Jun 2015 16:27:10 -0500 Subject: [PATCH 0509/1263] fixed rst links --- contributing.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/contributing.rst b/contributing.rst index 74b15bf3f..31ffccced 100644 --- a/contributing.rst +++ b/contributing.rst @@ -1,7 +1,7 @@ The git stuff ============= -`Guide by github, scroll down a bit`_ +`Guide by github, scroll down a bit `_ Deprecation =========== @@ -23,7 +23,7 @@ Or you can simply use to mark a symbol as deprecated. Works for procs/types/vars/consts, etc. -`Deprecated pragma in the manual.`_ +`Deprecated pragma in the manual. `_ Writing tests ============= From 7bdbfb766363472a62a05c54de5e983f12c130bd Mon Sep 17 00:00:00 2001 From: Rafael Date: Thu, 18 Jun 2015 23:36:06 +0200 Subject: [PATCH 0510/1263] Update tut2.txt --- doc/tut2.txt | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/doc/tut2.txt b/doc/tut2.txt index e1ac20074..966423844 100644 --- a/doc/tut2.txt +++ b/doc/tut2.txt @@ -233,17 +233,15 @@ is needed: type Socket* = ref object of RootObj - FHost: int # cannot be accessed from the outside of the module - # the `F` prefix is a convention to avoid clashes since - # the accessors are named `host` + host: int # cannot be accessed from the outside of the module due to missing star proc `host=`*(s: var Socket, value: int) {.inline.} = - ## setter of hostAddr - s.FHost = value + ## setter of host address + s.host = value proc host*(s: Socket): int {.inline.} = - ## getter of hostAddr - s.FHost + ## getter of host address + s.host var s: Socket new s From ef9dd0d4c5d8c1a547b557573bc782b92ea5abbf Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Thu, 18 Jun 2015 17:47:33 -0500 Subject: [PATCH 0511/1263] added comment about failing tests and categories --- contributing.rst | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/contributing.rst b/contributing.rst index 31ffccced..745db2377 100644 --- a/contributing.rst +++ b/contributing.rst @@ -91,7 +91,19 @@ You can run the tests with ./koch tests -which will run a good subset of tests. Some tests may fail. +which will run a good subset of tests. Some tests may fail. If you +only want to run failing tests, go for + +.. code-block:: bash + + ./koch tests --failing all + +You can also run only a single category of tests. For a list of +categories, see ``tests/testament/categories.nim``, at the bottom. + +.. code-block:: bash + + ./koch tests c lib Comparing tests =============== From dc41beed5a00db02b8d4accf40916b5684df3c3b Mon Sep 17 00:00:00 2001 From: apense Date: Thu, 18 Jun 2015 18:53:42 -0400 Subject: [PATCH 0512/1263] Added documentation Now `isSorted` is documented. --- lib/pure/algorithm.nim | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lib/pure/algorithm.nim b/lib/pure/algorithm.nim index b6bcdab7e..ac18ae420 100644 --- a/lib/pure/algorithm.nim +++ b/lib/pure/algorithm.nim @@ -240,6 +240,9 @@ template sortedByIt*(seq1, op: expr): expr = proc isSorted*[T](a: openarray[T], cmp: proc(x, y: T): int {.closure.}, order = SortOrder.Ascending): bool = + ## Checks to see whether `a` is already sorted in `order` + ## using `cmp` for the comparison. Parameters identical + ## to `sort` result = true for i in 0.. 0: From 072688d06ebe757993f4a17e51e5e74145eb65fd Mon Sep 17 00:00:00 2001 From: patrick dw Date: Thu, 18 Jun 2015 23:49:46 -0500 Subject: [PATCH 0513/1263] Renamed writeln procs to writeLine --- lib/pure/streams.nim | 4 +++- lib/system.nim | 6 +++--- lib/system/sysio.nim | 3 ++- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/lib/pure/streams.nim b/lib/pure/streams.nim index 50b5c219a..15022fe0d 100644 --- a/lib/pure/streams.nim +++ b/lib/pure/streams.nim @@ -117,12 +117,14 @@ proc write*(s: Stream, x: string) = ## terminating zero is written. writeData(s, cstring(x), x.len) -proc writeln*(s: Stream, args: varargs[string, `$`]) = +proc writeLine*(s: Stream, args: varargs[string, `$`]) = ## writes one or more strings to the the stream `s` followed ## by a new line. No length field or terminating zero is written. for str in args: write(s, str) write(s, "\n") +{.deprecated: [writeln:writeLine].} + proc read[T](s: Stream, result: var T) = ## generic read procedure. Reads `result` from the stream `s`. if readData(s, addr(result), sizeof(T)) != sizeof(T): diff --git a/lib/system.nim b/lib/system.nim index 2beb5b88d..9ffc51e80 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -898,7 +898,7 @@ proc contains*[T](x: set[T], y: T): bool {.magic: "InSet", noSideEffect.} ## ## .. code-block:: Nim ## var s: set[range['a'..'z']] = {'a'..'c'} - ## writeln(stdout, 'b' in s) + ## writeLine(stdout, 'b' in s) ## ## If ``in`` had been declared as ``[T](elem: T, s: set[T])`` then ``T`` would ## have been bound to ``char``. But ``s`` is not compatible to type @@ -2269,7 +2269,7 @@ proc echo*(x: varargs[expr, `$`]) {.magic: "Echo", tags: [WriteIOEffect], ## Special built-in that takes a variable number of arguments. Each argument ## is converted to a string via ``$``, so it works for user-defined ## types that have an overloaded ``$`` operator. - ## It is roughly equivalent to ``writeln(stdout, x); flushFile(stdout)``, but + ## It is roughly equivalent to ``writeLine(stdout, x); flushFile(stdout)``, but ## available for the JavaScript target too. ## ## Unlike other IO operations this is guaranteed to be thread-safe as @@ -2526,7 +2526,7 @@ when not defined(JS): #and not defined(NimrodVM): ## Returns ``false`` if the end of the file has been reached, ``true`` ## otherwise. If ``false`` is returned `line` contains no new data. - proc writeln*[Ty](f: File, x: varargs[Ty, `$`]) {.inline, + proc writeLine*[Ty](f: File, x: varargs[Ty, `$`]) {.inline, tags: [WriteIOEffect], benign.} ## writes the values `x` to `f` and then writes "\n". ## May throw an IO exception. diff --git a/lib/system/sysio.nim b/lib/system/sysio.nim index 3f860655e..e84c7ac3a 100644 --- a/lib/system/sysio.nim +++ b/lib/system/sysio.nim @@ -208,9 +208,10 @@ proc endOfFile(f: File): bool = ungetc(c, f) return c < 0'i32 -proc writeln[Ty](f: File, x: varargs[Ty, `$`]) = +proc writeLine[Ty](f: File, x: varargs[Ty, `$`]) = for i in items(x): write(f, i) write(f, "\n") +{.deprecated: [writeln:writeLine].} proc rawEcho(x: string) {.inline, compilerproc.} = write(stdout, x) proc rawEchoNL() {.inline, compilerproc.} = write(stdout, "\n") From 15e7fe787a2bf89b82aeba965ed4fd8b200dca1a Mon Sep 17 00:00:00 2001 From: patrick dw Date: Fri, 19 Jun 2015 01:02:22 -0500 Subject: [PATCH 0514/1263] renamed writeln to writeLine in lib --- lib/impure/re.nim | 2 +- lib/packages/docutils/rst.nim | 2 +- lib/pure/cgi.nim | 6 +++--- lib/pure/logging.nim | 6 +++--- lib/pure/nimprof.nim | 6 +++--- lib/pure/parsesql.nim | 2 +- lib/pure/pegs.nim | 2 +- lib/pure/strutils.nim | 12 ++++++------ lib/pure/terminal.nim | 6 +++--- lib/system/endb.nim | 6 +++--- 10 files changed, 25 insertions(+), 25 deletions(-) diff --git a/lib/impure/re.nim b/lib/impure/re.nim index 5f9371f28..0df8d4a9c 100644 --- a/lib/impure/re.nim +++ b/lib/impure/re.nim @@ -369,7 +369,7 @@ iterator split*(s: string, sep: Regex): string = ## ## .. code-block:: nim ## for word in split("00232this02939is39an22example111", re"\d+"): - ## writeln(stdout, word) + ## writeLine(stdout, word) ## ## Results in: ## diff --git a/lib/packages/docutils/rst.nim b/lib/packages/docutils/rst.nim index ae3ed8feb..2fbde632e 100644 --- a/lib/packages/docutils/rst.nim +++ b/lib/packages/docutils/rst.nim @@ -307,7 +307,7 @@ proc defaultMsgHandler*(filename: string, line, col: int, msgkind: MsgKind, let a = messages[msgkind] % arg let message = "$1($2, $3) $4: $5" % [filename, $line, $col, $mc, a] if mc == mcError: raise newException(EParseError, message) - else: writeln(stdout, message) + else: writeLine(stdout, message) proc defaultFindFile*(filename: string): string {.procvar.} = if existsFile(filename): result = filename diff --git a/lib/pure/cgi.nim b/lib/pure/cgi.nim index e8977b80b..cfd768f91 100644 --- a/lib/pure/cgi.nim +++ b/lib/pure/cgi.nim @@ -25,9 +25,9 @@ ## # generate content: ## write(stdout, "\n") ## write(stdout, "Test\n") -## writeln(stdout, "your name: " & myData["name"]) -## writeln(stdout, "your password: " & myData["password"]) -## writeln(stdout, "") +## writeLine(stdout, "your name: " & myData["name"]) +## writeLine(stdout, "your password: " & myData["password"]) +## writeLine(stdout, "") import strutils, os, strtabs, cookies diff --git a/lib/pure/logging.nim b/lib/pure/logging.nim index b28298dfa..7a900daae 100644 --- a/lib/pure/logging.nim +++ b/lib/pure/logging.nim @@ -132,12 +132,12 @@ method log*(logger: Logger, level: Level, args: varargs[string, `$`]) {. method log*(logger: ConsoleLogger, level: Level, args: varargs[string, `$`]) = ## Logs to the console using ``logger`` only. if level >= logger.levelThreshold: - writeln(stdout, substituteLog(logger.fmtStr, level, args)) + writeLine(stdout, substituteLog(logger.fmtStr, level, args)) method log*(logger: FileLogger, level: Level, args: varargs[string, `$`]) = ## Logs to a file using ``logger`` only. if level >= logger.levelThreshold: - writeln(logger.f, substituteLog(logger.fmtStr, level, args)) + writeLine(logger.f, substituteLog(logger.fmtStr, level, args)) proc defaultFilename*(): string = ## Returns the default filename for a logger. @@ -228,7 +228,7 @@ method log*(logger: RollingFileLogger, level: Level, args: varargs[string, `$`]) logger.curLine = 0 logger.f = open(logger.baseName, logger.baseMode, bufSize = logger.bufSize) - writeln(logger.f, substituteLog(logger.fmtStr, level, args)) + writeLine(logger.f, substituteLog(logger.fmtStr, level, args)) logger.curLine.inc # -------- diff --git a/lib/pure/nimprof.nim b/lib/pure/nimprof.nim index 765d1e341..cfe6bc40d 100644 --- a/lib/pure/nimprof.nim +++ b/lib/pure/nimprof.nim @@ -155,7 +155,7 @@ proc writeProfile() {.noconv.} = var f: File if open(f, filename, fmWrite): sort(profileData, cmpEntries) - writeln(f, "total executions of each stack trace:") + writeLine(f, "total executions of each stack trace:") var entries = 0 for i in 0..high(profileData): if profileData[i] != nil: inc entries @@ -175,13 +175,13 @@ proc writeProfile() {.noconv.} = for i in 0..min(100, entries-1): if profileData[i].total > 1: inc sum, profileData[i].total - writeln(f, "Entry: ", i+1, "/", entries, " Calls: ", + writeLine(f, "Entry: ", i+1, "/", entries, " Calls: ", profileData[i].total // totalCalls, " [sum: ", sum, "; ", sum // totalCalls, "]") for ii in 0..high(StackTrace): let procname = profileData[i].st[ii] if isNil(procname): break - writeln(f, " ", procname, " ", perProc[$procname] // totalCalls) + writeLine(f, " ", procname, " ", perProc[$procname] // totalCalls) close(f) echo "... done" else: diff --git a/lib/pure/parsesql.nim b/lib/pure/parsesql.nim index 91917b1c5..cfa60094d 100644 --- a/lib/pure/parsesql.nim +++ b/lib/pure/parsesql.nim @@ -1323,7 +1323,7 @@ proc ra(n: SqlNode, s: var string, indent: int) = # where: x.name == y.name #db.select(fromm = [t1, t2], where = t1.name == t2.name): #for x, y, z in db.select(fromm = a, b where = a.name == b.name): -# writeln x, y, z +# writeLine x, y, z proc renderSQL*(n: SqlNode): string = ## Converts an SQL abstract syntax tree to its string representation. diff --git a/lib/pure/pegs.nim b/lib/pure/pegs.nim index e165d7dca..28f6a17e6 100644 --- a/lib/pure/pegs.nim +++ b/lib/pure/pegs.nim @@ -979,7 +979,7 @@ iterator split*(s: string, sep: Peg): string = ## ## .. code-block:: nim ## for word in split("00232this02939is39an22example111", peg"\d+"): - ## writeln(stdout, word) + ## writeLine(stdout, word) ## ## Results in: ## diff --git a/lib/pure/strutils.nim b/lib/pure/strutils.nim index 317da9a0a..93fcf4d3d 100644 --- a/lib/pure/strutils.nim +++ b/lib/pure/strutils.nim @@ -206,7 +206,7 @@ iterator split*(s: string, seps: set[char] = Whitespace): string = ## ## .. code-block:: nim ## for word in split(" this is an example "): - ## writeln(stdout, word) + ## writeLine(stdout, word) ## ## ...generates this output: ## @@ -220,7 +220,7 @@ iterator split*(s: string, seps: set[char] = Whitespace): string = ## ## .. code-block:: nim ## for word in split(";;this;is;an;;example;;;", {';'}): - ## writeln(stdout, word) + ## writeLine(stdout, word) ## ## ...produces the same output as the first example. The code: ## @@ -228,7 +228,7 @@ iterator split*(s: string, seps: set[char] = Whitespace): string = ## let date = "2012-11-20T22:08:08.398990" ## let separators = {' ', '-', ':', 'T'} ## for number in split(date, separators): - ## writeln(stdout, number) + ## writeLine(stdout, number) ## ## ...results in: ## @@ -259,7 +259,7 @@ iterator split*(s: string, sep: char): string = ## ## .. code-block:: nim ## for word in split(";;this;is;an;;example;;;", ';'): - ## writeln(stdout, word) + ## writeLine(stdout, word) ## ## Results in: ## @@ -309,7 +309,7 @@ iterator splitLines*(s: string): string = ## ## .. code-block:: nim ## for line in splitLines("\nthis\nis\nan\n\nexample\n"): - ## writeln(stdout, line) + ## writeLine(stdout, line) ## ## Results in: ## @@ -571,7 +571,7 @@ iterator tokenize*(s: string, seps: set[char] = Whitespace): tuple[ ## ## .. code-block:: nim ## for word in tokenize(" this is an example "): - ## writeln(stdout, word) + ## writeLine(stdout, word) ## ## Results in: ## diff --git a/lib/pure/terminal.nim b/lib/pure/terminal.nim index 2efdf72d5..b6d99e429 100644 --- a/lib/pure/terminal.nim +++ b/lib/pure/terminal.nim @@ -430,8 +430,8 @@ macro styledEcho*(m: varargs[expr]): stmt = case item.kind of nnkStrLit..nnkTripleStrLit: if i == m.len - 1: - # optimize if string literal is last, just call writeln - result.add(newCall(bindSym"writeln", bindSym"stdout", item)) + # optimize if string literal is last, just call writeLine + result.add(newCall(bindSym"writeLine", bindSym"stdout", item)) if reset: result.add(newCall(bindSym"resetAttributes")) return else: @@ -470,7 +470,7 @@ when not defined(testing) and isMainModule: writeStyled("styled text ", {styleBright, styleBlink, styleUnderscore}) setBackGroundColor(bgCyan, true) setForeGroundColor(fgBlue) - writeln(stdout, "ordinary text") + writeLine(stdout, "ordinary text") styledEcho("styled text ", {styleBright, styleBlink, styleUnderscore}) diff --git a/lib/system/endb.nim b/lib/system/endb.nim index ef2664796..cba11ac5e 100644 --- a/lib/system/endb.nim +++ b/lib/system/endb.nim @@ -117,7 +117,7 @@ proc dbgRepr(p: pointer, typ: PNimType): string = proc writeVariable(stream: File, slot: VarSlot) = write(stream, slot.name) write(stream, " = ") - writeln(stream, dbgRepr(slot.address, slot.typ)) + writeLine(stream, dbgRepr(slot.address, slot.typ)) proc listFrame(stream: File, f: PFrame) = write(stream, EndbBeg) @@ -125,7 +125,7 @@ proc listFrame(stream: File, f: PFrame) = write(stream, f.len) write(stream, " slots):\n") for i in 0 .. f.len-1: - writeln(stream, getLocal(f, i).name) + writeLine(stream, getLocal(f, i).name) write(stream, EndbEnd) proc listLocals(stream: File, f: PFrame) = @@ -141,7 +141,7 @@ proc listGlobals(stream: File) = write(stream, EndbBeg) write(stream, "| Globals:\n") for i in 0 .. getGlobalLen()-1: - writeln(stream, getGlobal(i).name) + writeLine(stream, getGlobal(i).name) write(stream, EndbEnd) proc debugOut(msg: cstring) = From b6252af5c6ce99c6eaec91fb5570143151660b74 Mon Sep 17 00:00:00 2001 From: patrick dw Date: Fri, 19 Jun 2015 01:08:41 -0500 Subject: [PATCH 0515/1263] rename writeln to writeLine in doc --- doc/astspec.txt | 4 ++-- doc/manual/generics.txt | 2 +- doc/manual/procs.txt | 2 +- doc/manual/templates.txt | 30 +++++++++++++++--------------- doc/manual/trmacros.txt | 2 +- doc/tut2.txt | 26 +++++++++++++------------- 6 files changed, 33 insertions(+), 33 deletions(-) diff --git a/doc/astspec.txt b/doc/astspec.txt index d3ca7755e..9bedb00fc 100644 --- a/doc/astspec.txt +++ b/doc/astspec.txt @@ -222,13 +222,13 @@ Call with named arguments Concrete syntax: .. code-block:: nim - writeln(file=stdout, "hallo") + writeLine(file=stdout, "hallo") AST: .. code-block:: nim nnkCall( - nnkIdent(!"writeln"), + nnkIdent(!"writeLine"), nnkExprEqExpr( nnkIdent(!"file"), nnkIdent(!"stdout") diff --git a/doc/manual/generics.txt b/doc/manual/generics.txt index f82cad531..839e005a1 100644 --- a/doc/manual/generics.txt +++ b/doc/manual/generics.txt @@ -53,7 +53,7 @@ The following example shows a generic binary tree can be modelled: add(root, newNode("hallo")) # instantiates generic procs ``newNode`` and add(root, newNode("world")) # ``add`` for str in inorder(root): - writeln(stdout, str) + writeLine(stdout, str) Is operator diff --git a/doc/manual/procs.txt b/doc/manual/procs.txt index 23b5e4d1e..df633072d 100644 --- a/doc/manual/procs.txt +++ b/doc/manual/procs.txt @@ -132,7 +132,7 @@ to supply any type of first argument for procedures: echo("abc".len) # is the same as echo(len("abc")) echo("abc".toUpper()) echo({'a', 'b', 'c'}.card) - stdout.writeln("Hallo") # the same as writeln(stdout, "Hallo") + stdout.writeLine("Hallo") # the same as writeLine(stdout, "Hallo") Another way to look at the method call syntax is that it provides the missing postfix notation. diff --git a/doc/manual/templates.txt b/doc/manual/templates.txt index eeb907ce0..950d2fab7 100644 --- a/doc/manual/templates.txt +++ b/doc/manual/templates.txt @@ -77,10 +77,10 @@ special ``:`` syntax: quit("cannot open: " & fn) withFile(txt, "ttempl3.txt", fmWrite): - txt.writeln("line 1") - txt.writeln("line 2") + txt.writeLine("line 1") + txt.writeLine("line 2") -In the example the two ``writeln`` statements are bound to the ``actions`` +In the example the two ``writeLine`` statements are bound to the ``actions`` parameter. @@ -206,8 +206,8 @@ template parameter, it is an inject'ed symbol: ... withFile(txt, "ttempl3.txt", fmWrite): - txt.writeln("line 1") - txt.writeln("line 2") + txt.writeLine("line 1") + txt.writeLine("line 2") The ``inject`` and ``gensym`` pragmas are second class annotations; they have @@ -299,7 +299,7 @@ variable number of arguments: # add a call to the statement list that writes ": " add(result, newCall("write", newIdentNode("stdout"), newStrLitNode(": "))) # add a call to the statement list that writes the expressions value: - add(result, newCall("writeln", newIdentNode("stdout"), n[i])) + add(result, newCall("writeLine", newIdentNode("stdout"), n[i])) var a: array [0..10, int] @@ -314,15 +314,15 @@ The macro call expands to: .. code-block:: nim write(stdout, "a[0]") write(stdout, ": ") - writeln(stdout, a[0]) + writeLine(stdout, a[0]) write(stdout, "a[1]") write(stdout, ": ") - writeln(stdout, a[1]) + writeLine(stdout, a[1]) write(stdout, "x") write(stdout, ": ") - writeln(stdout, x) + writeLine(stdout, x) Arguments that are passed to a ``varargs`` parameter are wrapped in an array @@ -333,7 +333,7 @@ children. BindSym ------- -The above ``debug`` macro relies on the fact that ``write``, ``writeln`` and +The above ``debug`` macro relies on the fact that ``write``, ``writeLine`` and ``stdout`` are declared in the system module and thus visible in the instantiating context. There is a way to use bound identifiers (aka `symbols`:idx:) instead of using unbound identifiers. The ``bindSym`` @@ -348,7 +348,7 @@ builtin can be used for that: # we can bind symbols in scope via 'bindSym': add(result, newCall(bindSym"write", bindSym"stdout", toStrLit(n[i]))) add(result, newCall(bindSym"write", bindSym"stdout", newStrLitNode(": "))) - add(result, newCall(bindSym"writeln", bindSym"stdout", n[i])) + add(result, newCall(bindSym"writeLine", bindSym"stdout", n[i])) var a: array [0..10, int] @@ -363,17 +363,17 @@ The macro call expands to: .. code-block:: nim write(stdout, "a[0]") write(stdout, ": ") - writeln(stdout, a[0]) + writeLine(stdout, a[0]) write(stdout, "a[1]") write(stdout, ": ") - writeln(stdout, a[1]) + writeLine(stdout, a[1]) write(stdout, "x") write(stdout, ": ") - writeln(stdout, x) + writeLine(stdout, x) -However, the symbols ``write``, ``writeln`` and ``stdout`` are already bound +However, the symbols ``write``, ``writeLine`` and ``stdout`` are already bound and are not looked up again. As the example shows, ``bindSym`` does work with overloaded symbols implicitly. diff --git a/doc/manual/trmacros.txt b/doc/manual/trmacros.txt index 5ff24a36a..453e5f451 100644 --- a/doc/manual/trmacros.txt +++ b/doc/manual/trmacros.txt @@ -272,7 +272,7 @@ parameter is of the type ``varargs`` it is treated specially and it can match .. code-block:: nim template optWrite{ write(f, x) - ((write|writeln){w})(f, y) + ((write|writeLine){w})(f, y) }(x, y: varargs[expr], f: File, w: expr) = w(f, x, y) diff --git a/doc/tut2.txt b/doc/tut2.txt index 966423844..83ea9ad33 100644 --- a/doc/tut2.txt +++ b/doc/tut2.txt @@ -207,7 +207,7 @@ for any type: echo("abc".len) # is the same as echo(len("abc")) echo("abc".toUpper()) echo({'a', 'b', 'c'}.card) - stdout.writeln("Hallo") # the same as writeln(stdout, "Hallo") + stdout.writeLine("Hallo") # the same as writeLine(stdout, "Hallo") (Another way to look at the method call syntax is that it provides the missing postfix notation.) @@ -217,9 +217,9 @@ So "pure object oriented" code is easy to write: .. code-block:: nim import strutils - stdout.writeln("Give a list of numbers (separated by spaces): ") + stdout.writeLine("Give a list of numbers (separated by spaces): ") stdout.write(stdin.readLine.split.map(parseInt).max.`$`) - stdout.writeln(" is the maximum!") + stdout.writeLine(" is the maximum!") Properties @@ -535,7 +535,7 @@ containers: add(root, newNode("hello")) # instantiates ``newNode`` and ``add`` add(root, "world") # instantiates the second ``add`` proc for str in preorder(root): - stdout.writeln(str) + stdout.writeLine(str) The example shows a generic binary tree. Depending on context, the brackets are used either to introduce type parameters or to instantiate a generic proc, @@ -580,7 +580,7 @@ simple proc for logging: debug = true proc log(msg: string) {.inline.} = - if debug: stdout.writeln(msg) + if debug: stdout.writeLine(msg) var x = 4 @@ -597,7 +597,7 @@ Turning the ``log`` proc into a template solves this problem: debug = true template log(msg: string) = - if debug: stdout.writeln(msg) + if debug: stdout.writeLine(msg) var x = 4 @@ -627,10 +627,10 @@ via a special ``:`` syntax: quit("cannot open: " & fn) withFile(txt, "ttempl3.txt", fmWrite): - txt.writeln("line 1") - txt.writeln("line 2") + txt.writeLine("line 1") + txt.writeLine("line 2") -In the example the two ``writeln`` statements are bound to the ``body`` +In the example the two ``writeLine`` statements are bound to the ``body`` parameter. The ``withFile`` template contains boilerplate code and helps to avoid a common bug: to forget to close the file. Note how the ``let fn = filename`` statement ensures that ``filename`` is evaluated only @@ -684,7 +684,7 @@ variable number of arguments: # add a call to the statement list that writes ": " result.add(newCall("write", newIdentNode("stdout"), newStrLitNode(": "))) # add a call to the statement list that writes the expressions value: - result.add(newCall("writeln", newIdentNode("stdout"), n[i])) + result.add(newCall("writeLine", newIdentNode("stdout"), n[i])) var a: array[0..10, int] @@ -699,15 +699,15 @@ The macro call expands to: .. code-block:: nim write(stdout, "a[0]") write(stdout, ": ") - writeln(stdout, a[0]) + writeLine(stdout, a[0]) write(stdout, "a[1]") write(stdout, ": ") - writeln(stdout, a[1]) + writeLine(stdout, a[1]) write(stdout, "x") write(stdout, ": ") - writeln(stdout, x) + writeLine(stdout, x) From 69e15ac32fd92abe1d950275ab4b0d830d8b13e1 Mon Sep 17 00:00:00 2001 From: patrick dw Date: Fri, 19 Jun 2015 01:34:34 -0500 Subject: [PATCH 0516/1263] renamed writeln to writeLine in tests --- tests/ambsym/tambsym2.nim | 4 +- tests/ambsym/tambsym3.nim | 2 +- tests/assign/tassign.nim | 10 +- tests/assign/tcopy.nim | 4 +- tests/effects/teffects1.nim | 2 +- tests/effects/teffects2.nim | 2 +- tests/effects/teffects3.nim | 2 +- tests/effects/teffects4.nim | 2 +- tests/gc/gctest.nim | 28 +-- tests/generics/tbintre2.nim | 2 +- tests/generics/tbintree.nim | 2 +- tests/generics/tgeneric3.nim | 60 +++--- tests/lexer/tlexer.nim | 4 +- tests/macros/tdebugstmt.nim | 2 +- tests/misc/tcmdline.nim | 6 +- tests/misc/tendian.nim | 2 +- tests/misc/thallo.nim | 6 +- tests/misc/tlastmod.nim | 4 +- tests/misc/tmandelbrot.nim | 4 +- tests/misc/tnewuns.nim | 2 +- tests/misc/tvarnums.nim | 272 +++++++++++++------------- tests/objects/tobject2.nim | 2 +- tests/objects/toop1.nim | 24 +-- tests/overflw/toverflw.nim | 30 +-- tests/sets/tsets.nim | 2 +- tests/stdlib/tio.nim | 2 +- tests/stdlib/tparsopt.nim | 16 +- tests/stdlib/tpegs.nim | 348 ++++++++++++++++----------------- tests/stdlib/tposix.nim | 8 +- tests/stdlib/trepr.nim | 2 +- tests/stdlib/trepr2.nim | 8 +- tests/stdlib/tstrtabs.nim | 8 +- tests/stdlib/twalker.nim | 4 +- tests/template/tstempl.nim | 4 +- tests/template/ttempl3.nim | 4 +- tests/testament/caasdriver.nim | 8 +- tests/testament/htmlgen.nim | 12 +- tests/trmacros/targlist.nim | 4 +- tests/trmacros/tstmtlist.nim | 4 +- 39 files changed, 456 insertions(+), 456 deletions(-) diff --git a/tests/ambsym/tambsym2.nim b/tests/ambsym/tambsym2.nim index 745427c54..c3b997549 100644 --- a/tests/ambsym/tambsym2.nim +++ b/tests/ambsym/tambsym2.nim @@ -11,8 +11,8 @@ type proc len(x: TMyType): int {.inline.} = return x.len -proc x(s: TMyType, len: int) = - writeln(stdout, len(s)) +proc x(s: TMyType, len: int) = + writeLine(stdout, len(s)) var m: TMyType diff --git a/tests/ambsym/tambsym3.nim b/tests/ambsym/tambsym3.nim index 0155f258c..ed8a3058a 100644 --- a/tests/ambsym/tambsym3.nim +++ b/tests/ambsym/tambsym3.nim @@ -10,6 +10,6 @@ import mambsym1, times var v = mDec #ERROR_MSG ambiguous identifier -writeln(stdout, ord(v)) +writeLine(stdout, ord(v)) diff --git a/tests/assign/tassign.nim b/tests/assign/tassign.nim index f51c20783..9a4c1543b 100644 --- a/tests/assign/tassign.nim +++ b/tests/assign/tassign.nim @@ -22,10 +22,10 @@ proc test() = b = a # perform a deep copy here! b.seq = @["xyz", "huch", "was", "soll"] - writeln(stdout, len(a.seq)) - writeln(stdout, a.seq[3]) - writeln(stdout, len(b.seq)) - writeln(stdout, b.seq[3]) - writeln(stdout, b.y) + writeLine(stdout, len(a.seq)) + writeLine(stdout, a.seq[3]) + writeLine(stdout, len(b.seq)) + writeLine(stdout, b.seq[3]) + writeLine(stdout, b.y) test() diff --git a/tests/assign/tcopy.nim b/tests/assign/tcopy.nim index 5feb0d6b3..1e5bc3cba 100644 --- a/tests/assign/tcopy.nim +++ b/tests/assign/tcopy.nim @@ -16,8 +16,8 @@ proc main() = p = find(example, "=") a = substr(example, 0, p-1) b = substr(example, p+1) - writeln(stdout, a & '=' & b) - #writeln(stdout, b) + writeLine(stdout, a & '=' & b) + #writeLine(stdout, b) main() #OUT TEMP=C:\Programs\xyz\bin diff --git a/tests/effects/teffects1.nim b/tests/effects/teffects1.nim index ea1ea7b21..fad26a8d6 100644 --- a/tests/effects/teffects1.nim +++ b/tests/effects/teffects1.nim @@ -13,7 +13,7 @@ type proc forw: int {. .} proc lier(): int {.raises: [IO2Error].} = - writeln stdout, "arg" + writeLine stdout, "arg" proc forw: int = raise newException(IOError, "arg") diff --git a/tests/effects/teffects2.nim b/tests/effects/teffects2.nim index 89ad16edc..a97eacca6 100644 --- a/tests/effects/teffects2.nim +++ b/tests/effects/teffects2.nim @@ -13,7 +13,7 @@ type proc forw: int {.raises: [].} proc lier(): int {.raises: [IOError].} = - writeln stdout, "arg" + writeLine stdout, "arg" proc forw: int = raise newException(IOError, "arg") diff --git a/tests/effects/teffects3.nim b/tests/effects/teffects3.nim index 78543a929..3d597560f 100644 --- a/tests/effects/teffects3.nim +++ b/tests/effects/teffects3.nim @@ -12,7 +12,7 @@ type EIO2 = ref object of EIO proc raiser(): int {.tags: [TObj, FWriteIO].} = - writeln stdout, "arg" + writeLine stdout, "arg" var o: TObjB o.fn = raiser diff --git a/tests/effects/teffects4.nim b/tests/effects/teffects4.nim index 4584e6dc8..e2aa440a9 100644 --- a/tests/effects/teffects4.nim +++ b/tests/effects/teffects4.nim @@ -15,7 +15,7 @@ proc q() {.tags: [FIO].} = nil proc raiser(): int = - writeln stdout, "arg" + writeLine stdout, "arg" if true: q() diff --git a/tests/gc/gctest.nim b/tests/gc/gctest.nim index 2213a83ac..a634a47f2 100644 --- a/tests/gc/gctest.nim +++ b/tests/gc/gctest.nim @@ -63,12 +63,12 @@ proc caseTree(lvl: int = 0): PCaseNode = if lvl == 3: result = newCaseNode("data item") else: result = newCaseNode(caseTree(lvl+1), caseTree(lvl+1)) -proc finalizeBNode(n: TBNode) = writeln(stdout, n.data) +proc finalizeBNode(n: TBNode) = writeLine(stdout, n.data) proc finalizeNode(n: PNode) = assert(n != nil) write(stdout, "finalizing: ") - if isNil(n.data): writeln(stdout, "nil!") - else: writeln(stdout, n.data) + if isNil(n.data): writeLine(stdout, "nil!") + else: writeLine(stdout, n.data) var id: int = 1 @@ -82,7 +82,7 @@ proc buildTree(depth = 1): PNode = inc(id) proc returnTree(): PNode = - writeln(stdout, "creating id: " & $id) + writeLine(stdout, "creating id: " & $id) new(result, finalizeNode) result.data = $id new(result.le, finalizeNode) @@ -92,26 +92,26 @@ proc returnTree(): PNode = inc(id) # now create a cycle: - writeln(stdout, "creating id (cyclic): " & $id) + writeLine(stdout, "creating id (cyclic): " & $id) var cycle: PNode new(cycle, finalizeNode) cycle.data = $id cycle.le = cycle cycle.ri = cycle inc(id) - #writeln(stdout, "refcount: " & $refcount(cycle)) - #writeln(stdout, "refcount le: " & $refcount(cycle.le)) - #writeln(stdout, "refcount ri: " & $refcount(cycle.ri)) + #writeLine(stdout, "refcount: " & $refcount(cycle)) + #writeLine(stdout, "refcount le: " & $refcount(cycle.le)) + #writeLine(stdout, "refcount ri: " & $refcount(cycle.ri)) proc printTree(t: PNode) = if t == nil: return - writeln(stdout, "printing") - writeln(stdout, t.data) + writeLine(stdout, "printing") + writeLine(stdout, t.data) printTree(t.le) printTree(t.ri) proc unsureNew(result: var PNode) = - writeln(stdout, "creating unsure id: " & $id) + writeLine(stdout, "creating unsure id: " & $id) new(result, finalizeNode) result.data = $id new(result.le, finalizeNode) @@ -176,7 +176,7 @@ proc main() = var s: seq[string] = @[] for i in 1..100: add s, "hohoho" # test reallocation - writeln(stdout, s[89]) + writeLine(stdout, s[89]) write(stdout, "done!\n") var @@ -184,7 +184,7 @@ var s: string s = "" s = "" -writeln(stdout, repr(caseTree())) +writeLine(stdout, repr(caseTree())) father.t.data = @["ha", "lets", "stress", "it"] father.t.data = @["ha", "lets", "stress", "it"] var t = buildTree() @@ -199,5 +199,5 @@ GC_fullCollect() # the M&S GC fails with this call and it's unclear why. Definitely something # we need to fix! GC_fullCollect() -writeln(stdout, GC_getStatistics()) +writeLine(stdout, GC_getStatistics()) write(stdout, "finished\n") diff --git a/tests/generics/tbintre2.nim b/tests/generics/tbintre2.nim index 2a7225411..eb46b5157 100644 --- a/tests/generics/tbintre2.nim +++ b/tests/generics/tbintre2.nim @@ -15,7 +15,7 @@ if find(root, "world"): for str in items(root): stdout.write(str) else: - stdout.writeln("BUG") + stdout.writeLine("BUG") var r2: PBinaryTree[int] diff --git a/tests/generics/tbintree.nim b/tests/generics/tbintree.nim index 8cc8acb82..13163f764 100644 --- a/tests/generics/tbintree.nim +++ b/tests/generics/tbintree.nim @@ -92,7 +92,7 @@ when isMainModule: for str in items(root): stdout.write(str) else: - stdout.writeln("BUG") + stdout.writeLine("BUG") var r2: PBinaryTree[int] diff --git a/tests/generics/tgeneric3.nim b/tests/generics/tgeneric3.nim index 289bf1fd5..d4dac9385 100644 --- a/tests/generics/tgeneric3.nim +++ b/tests/generics/tgeneric3.nim @@ -37,25 +37,25 @@ proc clean[T: SomeOrdinal|SomeNumber](o: var T) {.inline.} = discard proc clean[T: string|seq](o: var T) {.inline.} = o = nil -proc clean[T,D] (o: ref TItem[T,D]) {.inline.} = +proc clean[T,D] (o: ref TItem[T,D]) {.inline.} = when (D is string) : o.value = nil else : o.val_set = false -proc isClean[T,D] (it: ref TItem[T,D]): bool {.inline.} = +proc isClean[T,D] (it: ref TItem[T,D]): bool {.inline.} = when (D is string) : return it.value == nil else : return not it.val_set -proc isClean[T,D](n: PNode[T,D], x: int): bool {.inline.} = +proc isClean[T,D](n: PNode[T,D], x: int): bool {.inline.} = when (D is string): return n.slots[x].value == nil else: return not n.slots[x].val_set -proc setItem[T,D](Akey: T, Avalue: D, ANode: PNode[T,D]): ref TItem[T,D] {.inline.} = +proc setItem[T,D](Akey: T, Avalue: D, ANode: PNode[T,D]): ref TItem[T,D] {.inline.} = new(result) result.key = Akey result.value = Avalue @@ -72,8 +72,8 @@ template binSearchImpl *(docmp: expr) {.immediate.} = var H = haystack.len -1 while result <= H : var I {.inject.} = (result + H) shr 1 - var SW = docmp - if SW < 0: result = I + 1 + var SW = docmp + if SW < 0: result = I + 1 else: H = I - 1 if SW == 0 : bFound = true @@ -85,14 +85,14 @@ proc bSearch[T,D] (haystack: PNode[T,D], needle:T): int {.inline.} = proc DeleteItem[T,D] (n: PNode[T,D], x: int): PNode[T,D] {.inline.} = var w = n.slots[x] - if w.node != nil : + if w.node != nil : clean(w) return n dec(n.count) if n.count > 0 : for i in countup(x, n.count -1) : n.slots[i] = n.slots[i + 1] n.slots[n.count] = nil - case n.count + case n.count of cLen1 : setLen(n.slots, cLen1) of cLen2 : setLen(n.slots, cLen2) of cLen3 : setLen(n.slots, cLen3) @@ -106,7 +106,7 @@ proc DeleteItem[T,D] (n: PNode[T,D], x: int): PNode[T,D] {.inline.} = n.slots = nil n.left = nil -proc internalDelete[T,D] (ANode: PNode[T,D], key: T, Avalue: var D): PNode[T,D] = +proc internalDelete[T,D] (ANode: PNode[T,D], key: T, Avalue: var D): PNode[T,D] = var Path: array[0..20, RPath[T,D]] var n = ANode result = n @@ -126,20 +126,20 @@ proc internalDelete[T,D] (ANode: PNode[T,D], key: T, Avalue: var D): PNode[T,D] n = n.slots[x].node else : n = nil - else : + else : dec(x) if isClean(n, x) : return Avalue = n.slots[x].value var n2 = DeleteItem(n, x) dec(h) while (n2 != n) and (h >=0) : - n = n2 + n = n2 var w = addr Path[h] x = w.Xi -1 if x >= 0 : if (n == nil) and isClean(w.Nd, x) : n = w.Nd - n.slots[x].node = nil + n.slots[x].node = nil n2 = DeleteItem(n, x) else : w.Nd.slots[x].node = n @@ -161,7 +161,7 @@ proc internalFind[T,D] (n: PNode[T,D], key: T): ref TItem[T,D] {.inline.} = wn = wn.left else : x = (-x) -1 - if x < wn.count : + if x < wn.count : wn = wn.slots[x].node else : return nil @@ -171,7 +171,7 @@ proc internalFind[T,D] (n: PNode[T,D], key: T): ref TItem[T,D] {.inline.} = return nil proc traceTree[T,D](root: PNode[T,D]) = - proc traceX(x: int) = + proc traceX(x: int) = write stdout, "(" write stdout, x write stdout, ") " @@ -184,7 +184,7 @@ proc traceTree[T,D](root: PNode[T,D]) = proc traceln(space: string) = - writeln stdout, "" + writeLine stdout, "" write stdout, space proc doTrace(n: PNode[T,D], level: int) = @@ -192,7 +192,7 @@ proc traceTree[T,D](root: PNode[T,D]) = traceln(space) write stdout, "node: " if n == nil: - writeln stdout, "is empty" + writeLine stdout, "is empty" return write stdout, n.count write stdout, " elements: " @@ -204,7 +204,7 @@ proc traceTree[T,D](root: PNode[T,D]) = if el != nil and not isClean(el): traceln(space) traceX(i) - if i >= n.count: + if i >= n.count: write stdout, "error " else: traceEl(el) @@ -219,14 +219,14 @@ proc traceTree[T,D](root: PNode[T,D]) = else : write stdout, el.key if el.node != nil: doTrace(el.node, level +1) else : write stdout, " empty " - writeln stdout,"" + writeLine stdout,"" doTrace(root, 0) proc InsertItem[T,D](APath: RPath[T,D], ANode:PNode[T,D], Akey: T, Avalue: D) = var x = - APath.Xi inc(APath.Nd.count) - case APath.Nd.count + case APath.Nd.count of cLen1: setLen(APath.Nd.slots, cLen2) of cLen2: setLen(APath.Nd.slots, cLen3) of cLen3: setLen(APath.Nd.slots, cLenCenter) @@ -286,7 +286,7 @@ proc internalPut[T,D](ANode: ref TNode[T,D], Akey: T, Avalue: D, Oldvalue: var D if x <= 0 : Path[h].Nd = n Path[h].Xi = x - inc(h) + inc(h) if x == 0 : n = n.left else : @@ -337,40 +337,40 @@ proc CleanTree[T,D](n: PNode[T,D]): PNode[T,D] = proc VisitAllNodes[T,D](n: PNode[T,D], visit: proc(n: PNode[T,D]): PNode[T,D] {.closure.} ): PNode[T,D] = if n != nil : if n.left != nil : - n.left = VisitAllNodes(n.left, visit) + n.left = VisitAllNodes(n.left, visit) for i in 0 .. n.count - 1 : var w = n.slots[i] if w.node != nil : - w.node = VisitAllNodes(w.node, visit) + w.node = VisitAllNodes(w.node, visit) return visit(n) return nil proc VisitAllNodes[T,D](n: PNode[T,D], visit: proc(n: PNode[T,D]) {.closure.} ) = if n != nil: if n.left != nil : - VisitAllNodes(n.left, visit) + VisitAllNodes(n.left, visit) for i in 0 .. n.count - 1 : var w = n.slots[i] if w.node != nil : - VisitAllNodes(w.node, visit) + VisitAllNodes(w.node, visit) visit(n) proc VisitAll[T,D](n: PNode[T,D], visit: proc(Akey: T, Avalue: D) {.closure.} ) = if n != nil: if n.left != nil : - VisitAll(n.left, visit) + VisitAll(n.left, visit) for i in 0 .. n.count - 1 : var w = n.slots[i] if not w.isClean : - visit(w.key, w.value) + visit(w.key, w.value) if w.node != nil : - VisitAll(w.node, visit) + VisitAll(w.node, visit) proc VisitAll[T,D](n: PNode[T,D], visit: proc(Akey: T, Avalue: var D):bool {.closure.} ): PNode[T,D] = if n != nil: var n1 = n.left if n1 != nil : - var n2 = VisitAll(n1, visit) + var n2 = VisitAll(n1, visit) if n1 != n2 : n.left = n2 var i = 0 @@ -395,7 +395,7 @@ iterator keys* [T,D] (n: PNode[T,D]): T = var level = 0 var nd = n var i = -1 - while true : + while true : if i < nd.count : Path[level].Nd = nd Path[level].Xi = i @@ -471,4 +471,4 @@ when isMainModule: - test() \ No newline at end of file + test() diff --git a/tests/lexer/tlexer.nim b/tests/lexer/tlexer.nim index 10a8ab51d..1dca6d9d0 100644 --- a/tests/lexer/tlexer.nim +++ b/tests/lexer/tlexer.nim @@ -50,8 +50,8 @@ proc main*(infile: string, a, b: int, someverylongnamewithtype = 0, # this should be an error! if initBaseLexer(L, infile, 30): nil else: - writeln(stdout, "could not open: " & infile) - writeln(stdout, "Success!") + writeLine(stdout, "could not open: " & infile) + writeLine(stdout, "Success!") call(3, # we use 3 12, # we use 12 43) # we use 43 diff --git a/tests/macros/tdebugstmt.nim b/tests/macros/tdebugstmt.nim index 00c55ccd8..421f8fd14 100644 --- a/tests/macros/tdebugstmt.nim +++ b/tests/macros/tdebugstmt.nim @@ -18,7 +18,7 @@ macro debug(n: varargs[expr]): stmt = # add a call to the statement list that writes ": " add(result, newCall("write", newIdentNode("stdout"), newStrLitNode(": "))) # add a call to the statement list that writes the expressions value: - add(result, newCall("writeln", newIdentNode("stdout"), n[i])) + add(result, newCall("writeLine", newIdentNode("stdout"), n[i])) var a: array [0..10, int] diff --git a/tests/misc/tcmdline.nim b/tests/misc/tcmdline.nim index f4ee20d31..cb8cb402c 100644 --- a/tests/misc/tcmdline.nim +++ b/tests/misc/tcmdline.nim @@ -7,8 +7,8 @@ var i: int params = paramCount() i = 0 -writeln(stdout, "This exe: " & getAppFilename()) -writeln(stdout, "Number of parameters: " & $params) +writeLine(stdout, "This exe: " & getAppFilename()) +writeLine(stdout, "Number of parameters: " & $params) while i <= params: - writeln(stdout, paramStr(i)) + writeLine(stdout, paramStr(i)) i = i + 1 diff --git a/tests/misc/tendian.nim b/tests/misc/tendian.nim index 256e2653c..91044f4d5 100644 --- a/tests/misc/tendian.nim +++ b/tests/misc/tendian.nim @@ -1,3 +1,3 @@ # test the new endian magic -writeln(stdout, repr(system.cpuEndian)) +writeLine(stdout, repr(system.cpuEndian)) diff --git a/tests/misc/thallo.nim b/tests/misc/thallo.nim index cbeb45b97..17e955f03 100644 --- a/tests/misc/thallo.nim +++ b/tests/misc/thallo.nim @@ -22,7 +22,7 @@ macro macrotest(n: expr): stmt {.immediate.} = result = newNimNode(nnkStmtList, n) for i in 2..n.len-1: result.add(newCall("write", n[1], n[i])) - result.add(newCall("writeln", n[1], newStrLitNode(""))) + result.add(newCall("writeLine", n[1], newStrLitNode(""))) macro debug(n: expr): stmt {.immediate.} = let n = callsite() @@ -30,7 +30,7 @@ macro debug(n: expr): stmt {.immediate.} = for i in 1..n.len-1: result.add(newCall("write", newIdentNode("stdout"), toStrLit(n[i]))) result.add(newCall("write", newIdentNode("stdout"), newStrLitNode(": "))) - result.add(newCall("writeln", newIdentNode("stdout"), n[i])) + result.add(newCall("writeLine", newIdentNode("stdout"), n[i])) macrotest(stdout, "finally", 4, 5, "variable", "argument lists") macrotest(stdout) @@ -38,7 +38,7 @@ macrotest(stdout) #GC_disable() echo("This was compiled by Nim version " & system.NimVersion) -writeln(stdout, "Hello", " World", "!") +writeLine(stdout, "Hello", " World", "!") echo(["a", "b", "c", "d"].len) for x in items(["What's", "your", "name", "?", ]): diff --git a/tests/misc/tlastmod.nim b/tests/misc/tlastmod.nim index 92ac922f7..857164022 100644 --- a/tests/misc/tlastmod.nim +++ b/tests/misc/tlastmod.nim @@ -8,8 +8,8 @@ proc main() = a, b: TTime a = getLastModificationTime(paramStr(1)) b = getLastModificationTime(paramStr(2)) - writeln(stdout, $a) - writeln(stdout, $b) + writeLine(stdout, $a) + writeLine(stdout, $b) if a < b: write(stdout, "$2 is newer than $1\n" % [paramStr(1), paramStr(2)]) else: diff --git a/tests/misc/tmandelbrot.nim b/tests/misc/tmandelbrot.nim index 4228b0416..e9b7a3e5a 100644 --- a/tests/misc/tmandelbrot.nim +++ b/tests/misc/tmandelbrot.nim @@ -24,10 +24,10 @@ var size = parseInt (paramStr (1)) var bit = 128 var byteAcc = 0 -stdout.writeln ("P4") +stdout.writeLine ("P4") stdout.write ($size) stdout.write (" ") -stdout.writeln ($size) +stdout.writeLine ($size) var fsize = float (size) for y in 0 .. size-1: diff --git a/tests/misc/tnewuns.nim b/tests/misc/tnewuns.nim index 5181e467c..267c73f5b 100644 --- a/tests/misc/tnewuns.nim +++ b/tests/misc/tnewuns.nim @@ -9,4 +9,4 @@ var x = 1 y = high(int) -writeln(stdout, $ ( x +% y ) ) +writeLine(stdout, $ ( x +% y ) ) diff --git a/tests/misc/tvarnums.nim b/tests/misc/tvarnums.nim index b880cf006..04a1ef53b 100644 --- a/tests/misc/tvarnums.nim +++ b/tests/misc/tvarnums.nim @@ -2,141 +2,141 @@ discard """ file: "tvarnums.nim" output: "Success!" """ -# Test variable length binary integers - -import - strutils - -type - TBuffer = array [0..10, int8] - -proc toVarNum(x: int32, b: var TBuffer) = - # encoding: first bit indicates end of number (0 if at end) - # second bit of the first byte denotes the sign (1 --> negative) - var a = x - if x != low(x): - # low(int) is a special case, - # because abs() does not work here! - # we leave x as it is and use the check >% instead of > - # for low(int) this is needed and positive numbers are not affected - # anyway - a = abs(x) - # first 6 bits: - b[0] = toU8(ord(a >% 63'i32) shl 7 or (ord(x < 0'i32) shl 6) or (int(a) and 63)) - a = a shr 6'i32 # skip first 6 bits - var i = 1 - while a != 0'i32: - b[i] = toU8(ord(a >% 127'i32) shl 7 or (int(a) and 127)) - inc(i) - a = a shr 7'i32 - -proc toVarNum64(x: int64, b: var TBuffer) = - # encoding: first bit indicates end of number (0 if at end) - # second bit of the first byte denotes the sign (1 --> negative) - var a = x - if x != low(x): - # low(int) is a special case, - # because abs() does not work here! - # we leave x as it is and use the check >% instead of > - # for low(int) this is needed and positive numbers are not affected - # anyway - a = abs(x) - # first 6 bits: - b[0] = toU8(ord(a >% 63'i64) shl 7 or (ord(x < 0'i64) shl 6) or int(a and 63)) - a = a shr 6 # skip first 6 bits - var i = 1 - while a != 0'i64: - b[i] = toU8(ord(a >% 127'i64) shl 7 or int(a and 127)) - inc(i) - a = a shr 7 - -proc toNum64(b: TBuffer): int64 = - # treat first byte different: - result = ze64(b[0]) and 63 - var - i = 0 - Shift = 6'i64 - while (ze(b[i]) and 128) != 0: - inc(i) - result = result or ((ze64(b[i]) and 127) shl Shift) - inc(Shift, 7) - if (ze(b[0]) and 64) != 0: # sign bit set? - result = not result +% 1 - # this is the same as ``- result`` - # but gives no overflow error for low(int) - -proc toNum(b: TBuffer): int32 = - # treat first byte different: - result = ze(b[0]) and 63 - var - i = 0 - Shift = 6'i32 - while (ze(b[i]) and 128) != 0: - inc(i) - result = result or ((int32(ze(b[i])) and 127'i32) shl Shift) - Shift = Shift + 7'i32 - if (ze(b[0]) and (1 shl 6)) != 0: # sign bit set? - result = (not result) +% 1'i32 - # this is the same as ``- result`` - # but gives no overflow error for low(int) - -proc toBinary(x: int64): string = - result = newString(64) - for i in 0..63: - result[63-i] = chr((int(x shr i) and 1) + ord('0')) - -proc t64(i: int64) = - var - b: TBuffer - toVarNum64(i, b) - var x = toNum64(b) - if x != i: - writeln(stdout, $i) - writeln(stdout, toBinary(i)) - writeln(stdout, toBinary(x)) - -proc t32(i: int32) = - var - b: TBuffer - toVarNum(i, b) - var x = toNum(b) - if x != i: - writeln(stdout, toBinary(i)) - writeln(stdout, toBinary(x)) - -proc tm(i: int32) = - var - b: TBuffer - toVarNum64(i, b) - var x = toNum(b) - if x != i: - writeln(stdout, toBinary(i)) - writeln(stdout, toBinary(x)) - -t32(0) -t32(1) -t32(-1) -t32(-100_000) -t32(100_000) -t32(low(int32)) -t32(high(int32)) - -t64(low(int64)) -t64(high(int64)) -t64(0) -t64(-1) -t64(1) -t64(1000_000) -t64(-1000_000) - -tm(0) -tm(1) -tm(-1) -tm(-100_000) -tm(100_000) -tm(low(int32)) -tm(high(int32)) - -writeln(stdout, "Success!") #OUT Success! +# Test variable length binary integers + +import + strutils + +type + TBuffer = array [0..10, int8] + +proc toVarNum(x: int32, b: var TBuffer) = + # encoding: first bit indicates end of number (0 if at end) + # second bit of the first byte denotes the sign (1 --> negative) + var a = x + if x != low(x): + # low(int) is a special case, + # because abs() does not work here! + # we leave x as it is and use the check >% instead of > + # for low(int) this is needed and positive numbers are not affected + # anyway + a = abs(x) + # first 6 bits: + b[0] = toU8(ord(a >% 63'i32) shl 7 or (ord(x < 0'i32) shl 6) or (int(a) and 63)) + a = a shr 6'i32 # skip first 6 bits + var i = 1 + while a != 0'i32: + b[i] = toU8(ord(a >% 127'i32) shl 7 or (int(a) and 127)) + inc(i) + a = a shr 7'i32 + +proc toVarNum64(x: int64, b: var TBuffer) = + # encoding: first bit indicates end of number (0 if at end) + # second bit of the first byte denotes the sign (1 --> negative) + var a = x + if x != low(x): + # low(int) is a special case, + # because abs() does not work here! + # we leave x as it is and use the check >% instead of > + # for low(int) this is needed and positive numbers are not affected + # anyway + a = abs(x) + # first 6 bits: + b[0] = toU8(ord(a >% 63'i64) shl 7 or (ord(x < 0'i64) shl 6) or int(a and 63)) + a = a shr 6 # skip first 6 bits + var i = 1 + while a != 0'i64: + b[i] = toU8(ord(a >% 127'i64) shl 7 or int(a and 127)) + inc(i) + a = a shr 7 + +proc toNum64(b: TBuffer): int64 = + # treat first byte different: + result = ze64(b[0]) and 63 + var + i = 0 + Shift = 6'i64 + while (ze(b[i]) and 128) != 0: + inc(i) + result = result or ((ze64(b[i]) and 127) shl Shift) + inc(Shift, 7) + if (ze(b[0]) and 64) != 0: # sign bit set? + result = not result +% 1 + # this is the same as ``- result`` + # but gives no overflow error for low(int) + +proc toNum(b: TBuffer): int32 = + # treat first byte different: + result = ze(b[0]) and 63 + var + i = 0 + Shift = 6'i32 + while (ze(b[i]) and 128) != 0: + inc(i) + result = result or ((int32(ze(b[i])) and 127'i32) shl Shift) + Shift = Shift + 7'i32 + if (ze(b[0]) and (1 shl 6)) != 0: # sign bit set? + result = (not result) +% 1'i32 + # this is the same as ``- result`` + # but gives no overflow error for low(int) + +proc toBinary(x: int64): string = + result = newString(64) + for i in 0..63: + result[63-i] = chr((int(x shr i) and 1) + ord('0')) + +proc t64(i: int64) = + var + b: TBuffer + toVarNum64(i, b) + var x = toNum64(b) + if x != i: + writeLine(stdout, $i) + writeLine(stdout, toBinary(i)) + writeLine(stdout, toBinary(x)) + +proc t32(i: int32) = + var + b: TBuffer + toVarNum(i, b) + var x = toNum(b) + if x != i: + writeLine(stdout, toBinary(i)) + writeLine(stdout, toBinary(x)) + +proc tm(i: int32) = + var + b: TBuffer + toVarNum64(i, b) + var x = toNum(b) + if x != i: + writeLine(stdout, toBinary(i)) + writeLine(stdout, toBinary(x)) + +t32(0) +t32(1) +t32(-1) +t32(-100_000) +t32(100_000) +t32(low(int32)) +t32(high(int32)) + +t64(low(int64)) +t64(high(int64)) +t64(0) +t64(-1) +t64(1) +t64(1000_000) +t64(-1000_000) + +tm(0) +tm(1) +tm(-1) +tm(-100_000) +tm(100_000) +tm(low(int32)) +tm(high(int32)) + +writeLine(stdout, "Success!") #OUT Success! diff --git a/tests/objects/tobject2.nim b/tests/objects/tobject2.nim index 0f1869695..a49296843 100644 --- a/tests/objects/tobject2.nim +++ b/tests/objects/tobject2.nim @@ -9,7 +9,7 @@ type proc getPoint( p: var TPoint2d) = {.breakpoint.} - writeln(stdout, p.x) + writeLine(stdout, p.x) var p: TPoint3d diff --git a/tests/objects/toop1.nim b/tests/objects/toop1.nim index 0d8ba124b..4727d146d 100644 --- a/tests/objects/toop1.nim +++ b/tests/objects/toop1.nim @@ -8,17 +8,17 @@ import macros type TFigure = object of RootObj # abstract base class: draw: proc (my: var TFigure) {.nimcall.} # concrete classes implement this - -proc init(f: var TFigure) = + +proc init(f: var TFigure) = f.draw = nil type TCircle = object of TFigure radius: int - -proc drawCircle(my: var TCircle) = stdout.writeln("o " & $my.radius) -proc init(my: var TCircle) = +proc drawCircle(my: var TCircle) = stdout.writeLine("o " & $my.radius) + +proc init(my: var TCircle) = init(TFigure(my)) # call base constructor my.radius = 5 my.draw = cast[proc (my: var TFigure) {.nimcall.}](drawCircle) @@ -29,13 +29,13 @@ type proc drawRectangle(my: var TRectangle) = stdout.write("[]") -proc init(my: var TRectangle) = +proc init(my: var TRectangle) = init(TFigure(my)) # call base constructor my.width = 5 my.height = 10 my.draw = cast[proc (my: var TFigure) {.nimcall.}](drawRectangle) -macro `!` (n: expr): stmt {.immediate.} = +macro `!` (n: expr): stmt {.immediate.} = let n = callsite() result = newNimNode(nnkCall, n) var dot = newNimNode(nnkDotExpr, n) @@ -60,16 +60,16 @@ type FHost: int # cannot be accessed from the outside of the module # the `F` prefix is a convention to avoid clashes since # the accessors are named `host` - -proc `host=`*(s: var TSocket, value: int) {.inline.} = + +proc `host=`*(s: var TSocket, value: int) {.inline.} = ## setter of hostAddr s.FHost = value proc host*(s: TSocket): int {.inline.} = ## getter of hostAddr return s.FHost - -var + +var s: TSocket s.host = 34 # same as `host=`(s, 34) stdout.write(s.host) @@ -81,6 +81,6 @@ var init(r) init(c) r!draw -c!draw() +c!draw() #OUT 34[]o 5 diff --git a/tests/overflw/toverflw.nim b/tests/overflw/toverflw.nim index fbe0d0a38..771a43303 100644 --- a/tests/overflw/toverflw.nim +++ b/tests/overflw/toverflw.nim @@ -2,20 +2,20 @@ discard """ file: "toverflw.nim" output: "the computation overflowed" """ -# Tests nim's ability to detect overflows - -{.push overflowChecks: on.} - -var - a, b: int -a = high(int) -b = -2 -try: - writeln(stdout, b - a) -except OverflowError: - writeln(stdout, "the computation overflowed") - -{.pop.} # overflow check -#OUT the computation overflowed +# Tests nim's ability to detect overflows + +{.push overflowChecks: on.} + +var + a, b: int +a = high(int) +b = -2 +try: + writeLine(stdout, b - a) +except OverflowError: + writeLine(stdout, "the computation overflowed") + +{.pop.} # overflow check +#OUT the computation overflowed diff --git a/tests/sets/tsets.nim b/tests/sets/tsets.nim index 646175329..2d37e893d 100644 --- a/tests/sets/tsets.nim +++ b/tests/sets/tsets.nim @@ -58,7 +58,7 @@ for x in low(TAZ) .. high(TAZ): for x in low(TTokTypeRange) .. high(TTokTypeRange): if x in tokTypes: discard - #writeln(stdout, "the token '$1' is in the set" % repr(x)) + #writeLine(stdout, "the token '$1' is in the set" % repr(x)) #OUT Ha ein F ist in s! diff --git a/tests/stdlib/tio.nim b/tests/stdlib/tio.nim index 5ae119f77..dcb6bd54f 100644 --- a/tests/stdlib/tio.nim +++ b/tests/stdlib/tio.nim @@ -2,6 +2,6 @@ proc main() = for line in lines("thello.nim"): - writeln(stdout, line) + writeLine(stdout, line) main() diff --git a/tests/stdlib/tparsopt.nim b/tests/stdlib/tparsopt.nim index 2b2da7e51..848fba2da 100644 --- a/tests/stdlib/tparsopt.nim +++ b/tests/stdlib/tparsopt.nim @@ -3,24 +3,24 @@ import parseopt -proc writeHelp() = - writeln(stdout, "Usage: tparsopt [options] filename [options]") +proc writeHelp() = + writeLine(stdout, "Usage: tparsopt [options] filename [options]") + +proc writeVersion() = + writeLine(stdout, "Version: 1.0.0") -proc writeVersion() = - writeln(stdout, "Version: 1.0.0") - var filename = "" for kind, key, val in getopt(): case kind - of cmdArgument: + of cmdArgument: filename = key of cmdLongOption, cmdShortOption: case key of "help", "h": writeHelp() of "version", "v": writeVersion() - else: - writeln(stdout, "Unknown command line option: ", key, ": ", val) + else: + writeLine(stdout, "Unknown command line option: ", key, ": ", val) of cmdEnd: assert(false) # cannot happen if filename == "": # no filename has been given, so we show the help: diff --git a/tests/stdlib/tpegs.nim b/tests/stdlib/tpegs.nim index cceea1693..3fe964d82 100644 --- a/tests/stdlib/tpegs.nim +++ b/tests/stdlib/tpegs.nim @@ -24,7 +24,7 @@ when useUnicode: const InlineThreshold = 5 ## number of leaves; -1 to disable inlining MaxSubpatterns* = 10 ## defines the maximum number of subpatterns that - ## can be captured. More subpatterns cannot be captured! + ## can be captured. More subpatterns cannot be captured! type TPegKind = enum @@ -80,12 +80,12 @@ type of pkBackRef..pkBackRefIgnoreStyle: index: range[0..MaxSubpatterns] else: sons: seq[TNode] PNonTerminal* = ref TNonTerminal - + TPeg* = TNode ## type that represents a PEG proc term*(t: string): TPeg {.rtl, extern: "npegs$1Str".} = ## constructs a PEG from a terminal string - if t.len != 1: + if t.len != 1: result.kind = pkTerminal result.term = t else: @@ -109,7 +109,7 @@ proc term*(t: char): TPeg {.rtl, extern: "npegs$1Char".} = assert t != '\0' result.kind = pkChar result.ch = t - + proc charSet*(s: set[char]): TPeg {.rtl, extern: "npegs$1".} = ## constructs a PEG from a character set `s` assert '\0' notin s @@ -120,31 +120,31 @@ proc charSet*(s: set[char]): TPeg {.rtl, extern: "npegs$1".} = proc len(a: TPeg): int {.inline.} = return a.sons.len proc add(d: var TPeg, s: TPeg) {.inline.} = add(d.sons, s) -proc copyPeg(a: TPeg): TPeg = +proc copyPeg(a: TPeg): TPeg = result.kind = a.kind case a.kind of pkEmpty..pkWhitespace: discard - of pkTerminal, pkTerminalIgnoreCase, pkTerminalIgnoreStyle: + of pkTerminal, pkTerminalIgnoreCase, pkTerminalIgnoreStyle: result.term = a.term - of pkChar, pkGreedyRepChar: + of pkChar, pkGreedyRepChar: result.ch = a.ch - of pkCharChoice, pkGreedyRepSet: + of pkCharChoice, pkGreedyRepSet: new(result.charChoice) result.charChoice[] = a.charChoice[] of pkNonTerminal: result.nt = a.nt - of pkBackRef..pkBackRefIgnoreStyle: + of pkBackRef..pkBackRefIgnoreStyle: result.index = a.index - else: + else: result.sons = a.sons proc addChoice(dest: var TPeg, elem: TPeg) = var L = dest.len-1 - if L >= 0 and dest.sons[L].kind == pkCharChoice: + if L >= 0 and dest.sons[L].kind == pkCharChoice: # caution! Do not introduce false aliasing here! case elem.kind of pkCharChoice: dest.sons[L] = charSet(dest.sons[L].charChoice[] + elem.charChoice[]) - of pkChar: + of pkChar: dest.sons[L] = charSet(dest.sons[L].charChoice[] + {elem.ch}) else: add(dest, elem) else: add(dest, elem) @@ -168,12 +168,12 @@ proc `/`*(a: varargs[TPeg]): TPeg {. proc addSequence(dest: var TPeg, elem: TPeg) = var L = dest.len-1 - if L >= 0 and dest.sons[L].kind == pkTerminal: + if L >= 0 and dest.sons[L].kind == pkTerminal: # caution! Do not introduce false aliasing here! case elem.kind - of pkTerminal: + of pkTerminal: dest.sons[L] = term(dest.sons[L].term & elem.term) - of pkChar: + of pkChar: dest.sons[L] = term(dest.sons[L].term & elem.ch) else: add(dest, elem) else: add(dest, elem) @@ -182,7 +182,7 @@ proc sequence*(a: varargs[TPeg]): TPeg {. rtl, extern: "npegs$1".} = ## constructs a sequence with all the PEGs from `a` multipleOp(pkSequence, addSequence) - + proc `?`*(a: TPeg): TPeg {.rtl, extern: "npegsOptional".} = ## constructs an optional for the PEG `a` if a.kind in {pkOption, pkGreedyRep, pkGreedyAny, pkGreedyRepChar, @@ -217,12 +217,12 @@ proc `!*`*(a: TPeg): TPeg {.rtl, extern: "npegsSearch".} = result.kind = pkSearch result.sons = @[a] -proc `!*\`*(a: TPeg): TPeg {.rtl, +proc `!*\`*(a: TPeg): TPeg {.rtl, extern: "npgegsCapturedSearch".} = ## constructs a "captured search" for the PEG `a` result.kind = pkCapturedSearch result.sons = @[a] - + when false: proc contains(a: TPeg, k: TPegKind): bool = if a.kind == k: return true @@ -238,7 +238,7 @@ when false: proc `+`*(a: TPeg): TPeg {.rtl, extern: "npegsGreedyPosRep".} = ## constructs a "greedy positive repetition" with the PEG `a` return sequence(a, *a) - + proc `&`*(a: TPeg): TPeg {.rtl, extern: "npegsAndPredicate".} = ## constructs an "and predicate" with the PEG `a` result.kind = pkAndPredicate @@ -261,33 +261,33 @@ proc newLine*: TPeg {.inline.} = ## constructs the PEG `newline`:idx: (``\n``) result.kind = pkNewline -proc UnicodeLetter*: TPeg {.inline.} = +proc UnicodeLetter*: TPeg {.inline.} = ## constructs the PEG ``\letter`` which matches any Unicode letter. result.kind = pkLetter - -proc UnicodeLower*: TPeg {.inline.} = - ## constructs the PEG ``\lower`` which matches any Unicode lowercase letter. - result.kind = pkLower -proc UnicodeUpper*: TPeg {.inline.} = +proc UnicodeLower*: TPeg {.inline.} = + ## constructs the PEG ``\lower`` which matches any Unicode lowercase letter. + result.kind = pkLower + +proc UnicodeUpper*: TPeg {.inline.} = ## constructs the PEG ``\upper`` which matches any Unicode lowercase letter. - result.kind = pkUpper - -proc UnicodeTitle*: TPeg {.inline.} = + result.kind = pkUpper + +proc UnicodeTitle*: TPeg {.inline.} = ## constructs the PEG ``\title`` which matches any Unicode title letter. result.kind = pkTitle -proc UnicodeWhitespace*: TPeg {.inline.} = - ## constructs the PEG ``\white`` which matches any Unicode +proc UnicodeWhitespace*: TPeg {.inline.} = + ## constructs the PEG ``\white`` which matches any Unicode ## whitespace character. result.kind = pkWhitespace -proc startAnchor*: TPeg {.inline.} = - ## constructs the PEG ``^`` which matches the start of the input. +proc startAnchor*: TPeg {.inline.} = + ## constructs the PEG ``^`` which matches the start of the input. result.kind = pkStartAnchor -proc endAnchor*: TPeg {.inline.} = - ## constructs the PEG ``$`` which matches the end of the input. +proc endAnchor*: TPeg {.inline.} = + ## constructs the PEG ``$`` which matches the end of the input. result = !any() proc capture*(a: TPeg): TPeg {.rtl, extern: "npegsCapture".} = @@ -296,21 +296,21 @@ proc capture*(a: TPeg): TPeg {.rtl, extern: "npegsCapture".} = result.sons = @[a] proc backref*(index: range[1..MaxSubPatterns]): TPeg {. - rtl, extern: "npegs$1".} = + rtl, extern: "npegs$1".} = ## constructs a back reference of the given `index`. `index` starts counting ## from 1. result.kind = pkBackRef result.index = index-1 proc backrefIgnoreCase*(index: range[1..MaxSubPatterns]): TPeg {. - rtl, extern: "npegs$1".} = + rtl, extern: "npegs$1".} = ## constructs a back reference of the given `index`. `index` starts counting ## from 1. Ignores case for matching. result.kind = pkBackRefIgnoreCase result.index = index-1 proc backrefIgnoreStyle*(index: range[1..MaxSubPatterns]): TPeg {. - rtl, extern: "npegs$1".}= + rtl, extern: "npegs$1".}= ## constructs a back reference of the given `index`. `index` starts counting ## from 1. Ignores style for matching. result.kind = pkBackRefIgnoreStyle @@ -320,7 +320,7 @@ proc spaceCost(n: TPeg): int = case n.kind of pkEmpty: discard of pkTerminal, pkTerminalIgnoreCase, pkTerminalIgnoreStyle, pkChar, - pkGreedyRepChar, pkCharChoice, pkGreedyRepSet, + pkGreedyRepChar, pkCharChoice, pkGreedyRepSet, pkAny..pkWhitespace, pkGreedyAny: result = 1 of pkNonTerminal: @@ -332,7 +332,7 @@ proc spaceCost(n: TPeg): int = if result >= InlineThreshold: break proc nonterminal*(n: PNonTerminal): TPeg {. - rtl, extern: "npegs$1".} = + rtl, extern: "npegs$1".} = ## constructs a PEG that consists of the nonterminal symbol assert n != nil if ntDeclared in n.flags and spaceCost(n.rule) < InlineThreshold: @@ -353,7 +353,7 @@ proc newNonTerminal*(name: string, line, column: int): PNonTerminal {. template letters*: expr = ## expands to ``charset({'A'..'Z', 'a'..'z'})`` charset({'A'..'Z', 'a'..'z'}) - + template digits*: expr = ## expands to ``charset({'0'..'9'})`` charset({'0'..'9'}) @@ -361,11 +361,11 @@ template digits*: expr = template whitespace*: expr = ## expands to ``charset({' ', '\9'..'\13'})`` charset({' ', '\9'..'\13'}) - + template identChars*: expr = ## expands to ``charset({'a'..'z', 'A'..'Z', '0'..'9', '_'})`` charset({'a'..'z', 'A'..'Z', '0'..'9', '_'}) - + template identStartChars*: expr = ## expands to ``charset({'A'..'Z', 'a'..'z', '_'})`` charset({'a'..'z', 'A'..'Z', '_'}) @@ -374,14 +374,14 @@ template ident*: expr = ## same as ``[a-zA-Z_][a-zA-z_0-9]*``; standard identifier sequence(charset({'a'..'z', 'A'..'Z', '_'}), *charset({'a'..'z', 'A'..'Z', '0'..'9', '_'})) - + template natural*: expr = ## same as ``\d+`` +digits # ------------------------- debugging ----------------------------------------- -proc esc(c: char, reserved = {'\0'..'\255'}): string = +proc esc(c: char, reserved = {'\0'..'\255'}): string = case c of '\b': result = "\\b" of '\t': result = "\\t" @@ -396,38 +396,38 @@ proc esc(c: char, reserved = {'\0'..'\255'}): string = elif c < ' ' or c >= '\128': result = '\\' & $ord(c) elif c in reserved: result = '\\' & c else: result = $c - + proc singleQuoteEsc(c: char): string = return "'" & esc(c, {'\''}) & "'" -proc singleQuoteEsc(str: string): string = +proc singleQuoteEsc(str: string): string = result = "'" for c in items(str): add result, esc(c, {'\''}) add result, '\'' - -proc charSetEscAux(cc: set[char]): string = + +proc charSetEscAux(cc: set[char]): string = const reserved = {'^', '-', ']'} result = "" var c1 = 0 - while c1 <= 0xff: - if chr(c1) in cc: + while c1 <= 0xff: + if chr(c1) in cc: var c2 = c1 while c2 < 0xff and chr(succ(c2)) in cc: inc(c2) - if c1 == c2: + if c1 == c2: add result, esc(chr(c1), reserved) - elif c2 == succ(c1): + elif c2 == succ(c1): add result, esc(chr(c1), reserved) & esc(chr(c2), reserved) - else: + else: add result, esc(chr(c1), reserved) & '-' & esc(chr(c2), reserved) c1 = c2 inc(c1) - + proc charSetEsc(cc: set[char]): string = - if card(cc) >= 128+64: + if card(cc) >= 128+64: result = "[^" & charSetEscAux({'\1'..'\xFF'} - cc) & ']' - else: + else: result = '[' & charSetEscAux(cc) & ']' - -proc toStrAux(r: TPeg, res: var string) = + +proc toStrAux(r: TPeg, res: var string) = case r.kind of pkEmpty: add(res, "()") of pkAny: add(res, '.') @@ -491,25 +491,25 @@ proc toStrAux(r: TPeg, res: var string) = toStrAux(r.sons[0], res) of pkCapture: add(res, '{') - toStrAux(r.sons[0], res) + toStrAux(r.sons[0], res) add(res, '}') - of pkBackRef: + of pkBackRef: add(res, '$') add(res, $r.index) - of pkBackRefIgnoreCase: + of pkBackRefIgnoreCase: add(res, "i$") add(res, $r.index) - of pkBackRefIgnoreStyle: + of pkBackRefIgnoreStyle: add(res, "y$") add(res, $r.index) of pkRule: - toStrAux(r.sons[0], res) + toStrAux(r.sons[0], res) add(res, " <- ") toStrAux(r.sons[1], res) of pkList: for i in 0 .. high(r.sons): toStrAux(r.sons[i], res) - add(res, "\n") + add(res, "\n") of pkStartAnchor: add(res, '^') @@ -526,8 +526,8 @@ type ml: int origStart: int -proc bounds*(c: TCaptures, - i: range[0..MaxSubpatterns-1]): tuple[first, last: int] = +proc bounds*(c: TCaptures, + i: range[0..MaxSubpatterns-1]): tuple[first, last: int] = ## returns the bounds ``[first..last]`` of the `i`'th capture. result = c.matches[i] @@ -547,7 +547,7 @@ when not useUnicode: proc rawMatch*(s: string, p: TPeg, start: int, c: var TCaptures): int {. rtl, extern: "npegs$1".} = - ## low-level matching proc that implements the PEG interpreter. Use this + ## low-level matching proc that implements the PEG interpreter. Use this ## for maximum efficiency (every other PEG operation ends up calling this ## proc). ## Returns -1 if it does not match, else the length of the match @@ -561,7 +561,7 @@ proc rawMatch*(s: string, p: TPeg, start: int, c: var TCaptures): int {. result = runeLenAt(s, start) else: result = -1 - of pkLetter: + of pkLetter: if s[start] != '\0': var a: Rune result = start @@ -570,7 +570,7 @@ proc rawMatch*(s: string, p: TPeg, start: int, c: var TCaptures): int {. else: result = -1 else: result = -1 - of pkLower: + of pkLower: if s[start] != '\0': var a: Rune result = start @@ -579,7 +579,7 @@ proc rawMatch*(s: string, p: TPeg, start: int, c: var TCaptures): int {. else: result = -1 else: result = -1 - of pkUpper: + of pkUpper: if s[start] != '\0': var a: Rune result = start @@ -588,16 +588,16 @@ proc rawMatch*(s: string, p: TPeg, start: int, c: var TCaptures): int {. else: result = -1 else: result = -1 - of pkTitle: + of pkTitle: if s[start] != '\0': var a: Rune result = start fastRuneAt(s, result, a) - if isTitle(a): dec(result, start) + if isTitle(a): dec(result, start) else: result = -1 else: result = -1 - of pkWhitespace: + of pkWhitespace: if s[start] != '\0': var a: Rune result = start @@ -661,7 +661,7 @@ proc rawMatch*(s: string, p: TPeg, start: int, c: var TCaptures): int {. when false: echo "leave: ", p.nt.name if result < 0: c.ml = oldMl of pkSequence: - var oldMl = c.ml + var oldMl = c.ml result = 0 assert(not isNil(p.sons)) for i in 0..high(p.sons): @@ -744,11 +744,11 @@ proc rawMatch*(s: string, p: TPeg, start: int, c: var TCaptures): int {. #else: silently ignore the capture else: c.ml = idx - of pkBackRef..pkBackRefIgnoreStyle: + of pkBackRef..pkBackRefIgnoreStyle: if p.index >= c.ml: return -1 var (a, b) = c.matches[p.index] var n: TPeg - n.kind = succ(pkTerminal, ord(p.kind)-ord(pkBackRef)) + n.kind = succ(pkTerminal, ord(p.kind)-ord(pkBackRef)) n.term = s.substr(a, b) result = rawMatch(s, n, start, c) of pkStartAnchor: @@ -769,7 +769,7 @@ proc match*(s: string, pattern: TPeg, matches: var openarray[string], for i in 0..c.ml-1: matches[i] = substr(s, c.matches[i][0], c.matches[i][1]) -proc match*(s: string, pattern: TPeg, +proc match*(s: string, pattern: TPeg, start = 0): bool {.rtl, extern: "npegs$1".} = ## returns ``true`` if ``s`` matches the ``pattern`` beginning from ``start``. var c: TCaptures @@ -789,7 +789,7 @@ proc matchLen*(s: string, pattern: TPeg, matches: var openarray[string], for i in 0..c.ml-1: matches[i] = substr(s, c.matches[i][0], c.matches[i][1]) -proc matchLen*(s: string, pattern: TPeg, +proc matchLen*(s: string, pattern: TPeg, start = 0): int {.rtl, extern: "npegs$1".} = ## the same as ``match``, but it returns the length of the match, ## if there is no match, -1 is returned. Note that a match length @@ -808,11 +808,11 @@ proc find*(s: string, pattern: TPeg, matches: var openarray[string], if matchLen(s, pattern, matches, i) >= 0: return i return -1 # could also use the pattern here: (!P .)* P - + proc findBounds*(s: string, pattern: TPeg, matches: var openarray[string], start = 0): tuple[first, last: int] {. rtl, extern: "npegs$1Capture".} = - ## returns the starting position and end position of ``pattern`` in ``s`` + ## returns the starting position and end position of ``pattern`` in ``s`` ## and the captured ## substrings in the array ``matches``. If it does not match, nothing ## is written into ``matches`` and (-1,0) is returned. @@ -820,40 +820,40 @@ proc findBounds*(s: string, pattern: TPeg, matches: var openarray[string], var L = matchLen(s, pattern, matches, i) if L >= 0: return (i, i+L-1) return (-1, 0) - -proc find*(s: string, pattern: TPeg, + +proc find*(s: string, pattern: TPeg, start = 0): int {.rtl, extern: "npegs$1".} = ## returns the starting position of ``pattern`` in ``s``. If it does not ## match, -1 is returned. for i in start .. s.len-1: if matchLen(s, pattern, i) >= 0: return i return -1 - -iterator findAll*(s: string, pattern: TPeg, start = 0): string = + +iterator findAll*(s: string, pattern: TPeg, start = 0): string = ## yields all matching captures of pattern in `s`. var matches: array[0..MaxSubpatterns-1, string] var i = start while i < s.len: var L = matchLen(s, pattern, matches, i) if L < 0: break - for k in 0..MaxSubPatterns-1: + for k in 0..MaxSubPatterns-1: if isNil(matches[k]): break yield matches[k] inc(i, L) - + proc findAll*(s: string, pattern: TPeg, start = 0): seq[string] {. - rtl, extern: "npegs$1".} = + rtl, extern: "npegs$1".} = ## returns all matching captures of pattern in `s`. ## If it does not match, @[] is returned. accumulateResult(findAll(s, pattern, start)) - + template `=~`*(s: string, pattern: TPeg): expr = - ## This calls ``match`` with an implicit declared ``matches`` array that - ## can be used in the scope of the ``=~`` call: - ## + ## This calls ``match`` with an implicit declared ``matches`` array that + ## can be used in the scope of the ``=~`` call: + ## ## .. code-block:: nim ## - ## if line =~ peg"\s* {\w+} \s* '=' \s* {\w+}": + ## if line =~ peg"\s* {\w+} \s* '=' \s* {\w+}": ## # matches a key=value pair: ## echo("Key: ", matches[0]) ## echo("Value: ", matches[1]) @@ -864,7 +864,7 @@ template `=~`*(s: string, pattern: TPeg): expr = ## echo("comment: ", matches[0]) ## else: ## echo("syntax error") - ## + ## when not declaredInScope(matches): var matches {.inject.}: array[0..MaxSubpatterns-1, string] match(s, pattern, matches) @@ -934,10 +934,10 @@ proc replace*(s: string, sub: TPeg, by = ""): string {. addf(result, by, caps) inc(i, x) add(result, substr(s, i)) - + proc parallelReplace*(s: string, subs: varargs[ tuple[pattern: TPeg, repl: string]]): string {. - rtl, extern: "npegs$1".} = + rtl, extern: "npegs$1".} = ## Returns a modified copy of `s` with the substitutions in `subs` ## applied in parallel. result = "" @@ -954,8 +954,8 @@ proc parallelReplace*(s: string, subs: varargs[ add(result, s[i]) inc(i) # copy the rest: - add(result, substr(s, i)) - + add(result, substr(s, i)) + proc transformFile*(infile, outfile: string, subs: varargs[tuple[pattern: TPeg, repl: string]]) {. rtl, extern: "npegs$1".} = @@ -972,7 +972,7 @@ proc transformFile*(infile, outfile: string, quit("cannot open for writing: " & outfile) else: quit("cannot open for reading: " & infile) - + iterator split*(s: string, sep: TPeg): string = ## Splits the string `s` into substrings. ## @@ -981,7 +981,7 @@ iterator split*(s: string, sep: TPeg): string = ## ## .. code-block:: nim ## for word in split("00232this02939is39an22example111", peg"\d+"): - ## writeln(stdout, word) + ## writeLine(stdout, word) ## ## Results in: ## @@ -1044,14 +1044,14 @@ type tkBackref, ## '$' tkDollar, ## '$' tkHat ## '^' - + TToken {.final.} = object ## a token kind: TTokKind ## the type of the token modifier: TModifier literal: string ## the parsed (string) literal charset: set[char] ## if kind == tkCharSet index: int ## if kind == tkBackref - + TPegLexer {.inheritable.} = object ## the lexer object. bufpos: int ## the current position within the buffer buf: cstring ## the buffer itself @@ -1081,7 +1081,7 @@ proc HandleLF(L: var TPegLexer, pos: int): int = result = pos+1 L.lineStart = result -proc init(L: var TPegLexer, input, filename: string, line = 1, col = 0) = +proc init(L: var TPegLexer, input, filename: string, line = 1, col = 0) = L.buf = input L.bufpos = 0 L.lineNumber = line @@ -1089,69 +1089,69 @@ proc init(L: var TPegLexer, input, filename: string, line = 1, col = 0) = L.lineStart = 0 L.filename = filename -proc getColumn(L: TPegLexer): int {.inline.} = +proc getColumn(L: TPegLexer): int {.inline.} = result = abs(L.bufpos - L.lineStart) + L.colOffset -proc getLine(L: TPegLexer): int {.inline.} = +proc getLine(L: TPegLexer): int {.inline.} = result = L.linenumber - + proc errorStr(L: TPegLexer, msg: string, line = -1, col = -1): string = var line = if line < 0: getLine(L) else: line var col = if col < 0: getColumn(L) else: col result = "$1($2, $3) Error: $4" % [L.filename, $line, $col, msg] -proc handleHexChar(c: var TPegLexer, xi: var int) = +proc handleHexChar(c: var TPegLexer, xi: var int) = case c.buf[c.bufpos] - of '0'..'9': + of '0'..'9': xi = (xi shl 4) or (ord(c.buf[c.bufpos]) - ord('0')) inc(c.bufpos) - of 'a'..'f': + of 'a'..'f': xi = (xi shl 4) or (ord(c.buf[c.bufpos]) - ord('a') + 10) inc(c.bufpos) - of 'A'..'F': + of 'A'..'F': xi = (xi shl 4) or (ord(c.buf[c.bufpos]) - ord('A') + 10) inc(c.bufpos) else: discard -proc getEscapedChar(c: var TPegLexer, tok: var TToken) = +proc getEscapedChar(c: var TPegLexer, tok: var TToken) = inc(c.bufpos) case c.buf[c.bufpos] - of 'r', 'R', 'c', 'C': + of 'r', 'R', 'c', 'C': add(tok.literal, '\c') inc(c.bufpos) - of 'l', 'L': + of 'l', 'L': add(tok.literal, '\L') inc(c.bufpos) - of 'f', 'F': + of 'f', 'F': add(tok.literal, '\f') inc(c.bufpos) - of 'e', 'E': + of 'e', 'E': add(tok.literal, '\e') inc(c.bufpos) - of 'a', 'A': + of 'a', 'A': add(tok.literal, '\a') inc(c.bufpos) - of 'b', 'B': + of 'b', 'B': add(tok.literal, '\b') inc(c.bufpos) - of 'v', 'V': + of 'v', 'V': add(tok.literal, '\v') inc(c.bufpos) - of 't', 'T': + of 't', 'T': add(tok.literal, '\t') inc(c.bufpos) - of 'x', 'X': + of 'x', 'X': inc(c.bufpos) var xi = 0 handleHexChar(c, xi) handleHexChar(c, xi) if xi == 0: tok.kind = tkInvalid else: add(tok.literal, chr(xi)) - of '0'..'9': + of '0'..'9': var val = ord(c.buf[c.bufpos]) - ord('0') inc(c.bufpos) var i = 1 - while (i <= 3) and (c.buf[c.bufpos] in {'0'..'9'}): + while (i <= 3) and (c.buf[c.bufpos] in {'0'..'9'}): val = val * 10 + ord(c.buf[c.bufpos]) - ord('0') inc(c.bufpos) inc(i) @@ -1164,32 +1164,32 @@ proc getEscapedChar(c: var TPegLexer, tok: var TToken) = else: add(tok.literal, c.buf[c.bufpos]) inc(c.bufpos) - -proc skip(c: var TPegLexer) = + +proc skip(c: var TPegLexer) = var pos = c.bufpos var buf = c.buf - while true: + while true: case buf[pos] - of ' ', '\t': + of ' ', '\t': inc(pos) of '#': while not (buf[pos] in {'\c', '\L', '\0'}): inc(pos) of '\c': pos = HandleCR(c, pos) buf = c.buf - of '\L': + of '\L': pos = HandleLF(c, pos) buf = c.buf - else: + else: break # EndOfFile also leaves the loop c.bufpos = pos - -proc getString(c: var TPegLexer, tok: var TToken) = + +proc getString(c: var TPegLexer, tok: var TToken) = tok.kind = tkStringLit var pos = c.bufPos + 1 var buf = c.buf var quote = buf[pos-1] - while true: + while true: case buf[pos] of '\\': c.bufpos = pos @@ -1200,13 +1200,13 @@ proc getString(c: var TPegLexer, tok: var TToken) = break elif buf[pos] == quote: inc(pos) - break + break else: add(tok.literal, buf[pos]) inc(pos) c.bufpos = pos - -proc getDollar(c: var TPegLexer, tok: var TToken) = + +proc getDollar(c: var TPegLexer, tok: var TToken) = var pos = c.bufPos + 1 var buf = c.buf if buf[pos] in {'0'..'9'}: @@ -1218,8 +1218,8 @@ proc getDollar(c: var TPegLexer, tok: var TToken) = else: tok.kind = tkDollar c.bufpos = pos - -proc getCharSet(c: var TPegLexer, tok: var TToken) = + +proc getCharSet(c: var TPegLexer, tok: var TToken) = tok.kind = tkCharSet tok.charset = {} var pos = c.bufPos + 1 @@ -1242,7 +1242,7 @@ proc getCharSet(c: var TPegLexer, tok: var TToken) = of '\C', '\L', '\0': tok.kind = tkInvalid break - else: + else: ch = buf[pos] inc(pos) incl(tok.charset, ch) @@ -1262,18 +1262,18 @@ proc getCharSet(c: var TPegLexer, tok: var TToken) = of '\C', '\L', '\0': tok.kind = tkInvalid break - else: + else: ch2 = buf[pos] inc(pos) for i in ord(ch)+1 .. ord(ch2): incl(tok.charset, chr(i)) c.bufpos = pos if caret: tok.charset = {'\1'..'\xFF'} - tok.charset - -proc getSymbol(c: var TPegLexer, tok: var TToken) = + +proc getSymbol(c: var TPegLexer, tok: var TToken) = var pos = c.bufpos var buf = c.buf - while true: + while true: add(tok.literal, buf[pos]) inc(pos) if buf[pos] notin strutils.IdentChars: break @@ -1289,7 +1289,7 @@ proc getBuiltin(c: var TPegLexer, tok: var TToken) = tok.kind = tkEscaped getEscapedChar(c, tok) # may set tok.kind to tkInvalid -proc getTok(c: var TPegLexer, tok: var TToken) = +proc getTok(c: var TPegLexer, tok: var TToken) = tok.kind = tkInvalid tok.modifier = modNone setlen(tok.literal, 0) @@ -1304,11 +1304,11 @@ proc getTok(c: var TPegLexer, tok: var TToken) = else: tok.kind = tkCurlyLe add(tok.literal, '{') - of '}': + of '}': tok.kind = tkCurlyRi inc(c.bufpos) add(tok.literal, '}') - of '[': + of '[': getCharset(c, tok) of '(': tok.kind = tkParLe @@ -1318,7 +1318,7 @@ proc getTok(c: var TPegLexer, tok: var TToken) = tok.kind = tkParRi inc(c.bufpos) add(tok.literal, ')') - of '.': + of '.': tok.kind = tkAny inc(c.bufpos) add(tok.literal, '.') @@ -1326,16 +1326,16 @@ proc getTok(c: var TPegLexer, tok: var TToken) = tok.kind = tkAnyRune inc(c.bufpos) add(tok.literal, '_') - of '\\': + of '\\': getBuiltin(c, tok) of '\'', '"': getString(c, tok) of '$': getDollar(c, tok) - of '\0': + of '\0': tok.kind = tkEof tok.literal = "[EOF]" of 'a'..'z', 'A'..'Z', '\128'..'\255': getSymbol(c, tok) - if c.buf[c.bufpos] in {'\'', '"'} or + if c.buf[c.bufpos] in {'\'', '"'} or c.buf[c.bufpos] == '$' and c.buf[c.bufpos+1] in {'0'..'9'}: case tok.literal of "i": tok.modifier = modIgnoreCase @@ -1383,7 +1383,7 @@ proc getTok(c: var TPegLexer, tok: var TToken) = tok.kind = tkAt inc(c.bufpos) add(tok.literal, '@') - if c.buf[c.bufpos] == '@': + if c.buf[c.bufpos] == '@': tok.kind = tkCurlyAt inc(c.bufpos) add(tok.literal, '@') @@ -1402,7 +1402,7 @@ proc arrowIsNextTok(c: TPegLexer): bool = result = c.buf[pos] == '<' and c.buf[pos+1] == '-' # ----------------------------- parser ---------------------------------------- - + type EInvalidPeg* = object of ValueError ## raised if an invalid ## PEG has been detected @@ -1420,7 +1420,7 @@ proc pegError(p: TPegParser, msg: string, line = -1, col = -1) = e.msg = errorStr(p, msg, line, col) raise e -proc getTok(p: var TPegParser) = +proc getTok(p: var TPegParser) = getTok(p, p.tok) if p.tok.kind == tkInvalid: pegError(p, "invalid token") @@ -1470,7 +1470,7 @@ proc builtin(p: var TPegParser): TPeg = of "white": result = UnicodeWhitespace() else: pegError(p, "unknown built-in: " & p.tok.literal) -proc token(terminal: TPeg, p: TPegParser): TPeg = +proc token(terminal: TPeg, p: TPegParser): TPeg = if p.skip.kind == pkEmpty: result = terminal else: result = sequence(p.skip, terminal) @@ -1491,7 +1491,7 @@ proc primary(p: var TPegParser): TPeg = else: discard case p.tok.kind of tkIdentifier: - if p.identIsVerbatim: + if p.identIsVerbatim: var m = p.tok.modifier if m == modNone: m = p.modifier result = modifiedTerm(p.tok.literal, m).token(p) @@ -1534,17 +1534,17 @@ proc primary(p: var TPegParser): TPeg = of tkEscaped: result = term(p.tok.literal[0]).token(p) getTok(p) - of tkDollar: + of tkDollar: result = endAnchor() getTok(p) - of tkHat: + of tkHat: result = startAnchor() getTok(p) of tkBackref: var m = p.tok.modifier if m == modNone: m = p.modifier result = modifiedBackRef(p.tok.index, m).token(p) - if p.tok.index < 0 or p.tok.index > p.captures: + if p.tok.index < 0 or p.tok.index > p.captures: pegError(p, "invalid back reference index: " & $p.tok.index) getTok(p) else: @@ -1568,7 +1568,7 @@ proc seqExpr(p: var TPegParser): TPeg = while true: case p.tok.kind of tkAmp, tkNot, tkAt, tkStringLit, tkCharset, tkParLe, tkCurlyLe, - tkAny, tkAnyRune, tkBuiltin, tkEscaped, tkDollar, tkBackref, + tkAny, tkAnyRune, tkBuiltin, tkEscaped, tkDollar, tkBackref, tkHat, tkCurlyAt: result = sequence(result, primary(p)) of tkIdentifier: @@ -1582,7 +1582,7 @@ proc parseExpr(p: var TPegParser): TPeg = while p.tok.kind == tkBar: getTok(p) result = result / seqExpr(p) - + proc parseRule(p: var TPegParser): PNonTerminal = if p.tok.kind == tkIdentifier and arrowIsNextTok(p): result = getNonTerminal(p, p.tok.literal) @@ -1596,7 +1596,7 @@ proc parseRule(p: var TPegParser): PNonTerminal = incl(result.flags, ntDeclared) # NOW inlining may be attempted else: pegError(p, "rule expected, but found: " & p.tok.literal) - + proc rawParse(p: var TPegParser): TPeg = ## parses a rule or a PEG expression while p.tok.kind == tkBuiltin: @@ -1649,20 +1649,20 @@ proc peg*(pattern: string): TPeg = ## peg"{\ident} \s* '=' \s* {.*}" result = parsePeg(pattern, "pattern") -proc escapePeg*(s: string): string = +proc escapePeg*(s: string): string = ## escapes `s` so that it is matched verbatim when used as a peg. result = "" var inQuote = false - for c in items(s): + for c in items(s): case c - of '\0'..'\31', '\'', '"', '\\': - if inQuote: + of '\0'..'\31', '\'', '"', '\\': + if inQuote: result.add('\'') inQuote = false result.add("\\x") result.add(toHex(ord(c), 2)) else: - if not inQuote: + if not inQuote: result.add('\'') inQuote = true result.add(c) @@ -1675,27 +1675,27 @@ when isMainModule: doAssert(not match("W_HI_L", peg"\y 'while'")) doAssert(not match("W_HI_Le", peg"\y v'while'")) doAssert match("W_HI_Le", peg"y'while'") - + doAssert($ +digits == $peg"\d+") doAssert "0158787".match(peg"\d+") doAssert "ABC 0232".match(peg"\w+\s+\d+") doAssert "ABC".match(peg"\d+ / \w+") for word in split("00232this02939is39an22example111", peg"\d+"): - writeln(stdout, word) + writeLine(stdout, word) doAssert matchLen("key", ident) == 3 var pattern = sequence(ident, *whitespace, term('='), *whitespace, ident) doAssert matchLen("key1= cal9", pattern) == 11 - + var ws = newNonTerminal("ws", 1, 1) ws.rule = *whitespace - + var expr = newNonTerminal("expr", 1, 1) expr.rule = sequence(capture(ident), *sequence( nonterminal(ws), term('+'), nonterminal(ws), nonterminal(expr))) - + var c: TCaptures var s = "a+b + c +d+e+f" doAssert rawMatch(s, expr.rule, 0, c) == len(s) @@ -1716,7 +1716,7 @@ when isMainModule: doAssert matches[0] == "abc" else: doAssert false - + var g2 = peg"""S <- A B / C D A <- 'a'+ B <- 'b'+ @@ -1733,10 +1733,10 @@ when isMainModule: doAssert matches[0] == "a" else: doAssert false - + block: var matches: array[0..2, string] - if match("abcdefg", peg"c {d} ef {g}", matches, 2): + if match("abcdefg", peg"c {d} ef {g}", matches, 2): doAssert matches[0] == "d" doAssert matches[1] == "g" else: @@ -1744,13 +1744,13 @@ when isMainModule: for x in findAll("abcdef", peg"{.}", 3): echo x - + if "f(a, b)" =~ peg"{[0-9]+} / ({\ident} '(' {@} ')')": doAssert matches[0] == "f" doAssert matches[1] == "a, b" else: doAssert false - + doAssert match("eine übersicht und außerdem", peg"(\letter \white*)+") # ß is not a lower cased letter?! doAssert match("eine übersicht und auerdem", peg"(\lower \white*)+") @@ -1762,7 +1762,7 @@ when isMainModule: "var1<-keykey;var2<-key2key2") doAssert match("prefix/start", peg"^start$", 7) - + # tricky test to check for false aliasing: block: var a = term"key" diff --git a/tests/stdlib/tposix.nim b/tests/stdlib/tposix.nim index bf0b49586..229035d22 100644 --- a/tests/stdlib/tposix.nim +++ b/tests/stdlib/tposix.nim @@ -9,8 +9,8 @@ when not defined(windows): discard uname(u) - writeln(stdout, u.sysname) - writeln(stdout, u.nodename) - writeln(stdout, u.release) - writeln(stdout, u.machine) + writeLine(stdout, u.sysname) + writeLine(stdout, u.nodename) + writeLine(stdout, u.release) + writeLine(stdout, u.machine) diff --git a/tests/stdlib/trepr.nim b/tests/stdlib/trepr.nim index 41c830621..8d1353173 100644 --- a/tests/stdlib/trepr.nim +++ b/tests/stdlib/trepr.nim @@ -9,7 +9,7 @@ type var val = {a, b} stdout.write(repr(val)) -stdout.writeln(repr({'a'..'z', 'A'..'Z'})) +stdout.writeLine(repr({'a'..'z', 'A'..'Z'})) type TObj {.pure, inheritable.} = object diff --git a/tests/stdlib/trepr2.nim b/tests/stdlib/trepr2.nim index b15081e48..b7c2bd152 100644 --- a/tests/stdlib/trepr2.nim +++ b/tests/stdlib/trepr2.nim @@ -26,7 +26,7 @@ q[] = p s = @[q, q, q, q] -writeln(stdout, repr(p)) -writeln(stdout, repr(q)) -writeln(stdout, repr(s)) -writeln(stdout, repr(en4)) +writeLine(stdout, repr(p)) +writeLine(stdout, repr(q)) +writeLine(stdout, repr(s)) +writeLine(stdout, repr(en4)) diff --git a/tests/stdlib/tstrtabs.nim b/tests/stdlib/tstrtabs.nim index 251ec77ef..8404a6c88 100644 --- a/tests/stdlib/tstrtabs.nim +++ b/tests/stdlib/tstrtabs.nim @@ -1,12 +1,12 @@ import strtabs -var tab = newStringTable({"key1": "val1", "key2": "val2"}, +var tab = newStringTable({"key1": "val1", "key2": "val2"}, modeStyleInsensitive) for i in 0..80: tab["key_" & $i] = "value" & $i for key, val in pairs(tab): - writeln(stdout, key, ": ", val) -writeln(stdout, "length of table ", $tab.len) + writeLine(stdout, key, ": ", val) +writeLine(stdout, "length of table ", $tab.len) -writeln(stdout, `%`("$key1 = $key2; ${PATH}", tab, {useEnvironment})) +writeLine(stdout, `%`("$key1 = $key2; ${PATH}", tab, {useEnvironment})) diff --git a/tests/stdlib/twalker.nim b/tests/stdlib/twalker.nim index 89e6c2b9d..aad0fa786 100644 --- a/tests/stdlib/twalker.nim +++ b/tests/stdlib/twalker.nim @@ -5,9 +5,9 @@ import proc main(filter: string) = for filename in walkFiles(filter): - writeln(stdout, filename) + writeLine(stdout, filename) for key, val in envPairs(): - writeln(stdout, key & '=' & val) + writeLine(stdout, key & '=' & val) main("*.nim") diff --git a/tests/template/tstempl.nim b/tests/template/tstempl.nim index 2b4a8baa0..f8e57abbb 100644 --- a/tests/template/tstempl.nim +++ b/tests/template/tstempl.nim @@ -15,10 +15,10 @@ var abclev = levB template tstLev(abclev: TLev) = bind tstempl.abclev, `%` - writeln(stdout, "global = $1, arg = $2, test = $3" % [ + writeLine(stdout, "global = $1, arg = $2, test = $3" % [ $tstempl.abclev, $abclev, $(tstempl.abclev == abclev)]) # evaluates to true, but must be false tstLev(levA) -writeln(stdout, $abclev) +writeLine(stdout, $abclev) diff --git a/tests/template/ttempl3.nim b/tests/template/ttempl3.nim index 59be24624..c5d78d414 100644 --- a/tests/template/ttempl3.nim +++ b/tests/template/ttempl3.nim @@ -13,8 +13,8 @@ template withOpenFile(f: expr, filename: string, mode: TFileMode, quit("cannot open for writing: " & filename) withOpenFile(txt, "ttempl3.txt", fmWrite): - writeln(txt, "line 1") - txt.writeln("line 2") + writeLine(txt, "line 1") + txt.writeLine("line 2") var myVar: array[0..1, int] diff --git a/tests/testament/caasdriver.nim b/tests/testament/caasdriver.nim index c61a9f108..30383bddb 100644 --- a/tests/testament/caasdriver.nim +++ b/tests/testament/caasdriver.nim @@ -137,11 +137,11 @@ proc doScenario(script: string, output: Stream, mode: TRunMode, verbose: bool): if line.strip.len == 0: continue if line.startsWith("#"): - output.writeln line + output.writeLine line continue elif line.startsWith(">"): s.doCommand(line.substr(1).strip) - output.writeln line, "\n", if verbose: s.lastOutput else: "" + output.writeLine line, "\n", if verbose: s.lastOutput else: "" else: var expectMatch = true var pattern = s.replaceVars(line) @@ -153,9 +153,9 @@ proc doScenario(script: string, output: Stream, mode: TRunMode, verbose: bool): s.lastOutput.find(re(pattern, flags = {reStudy})) != -1 if expectMatch == actualMatch: - output.writeln "SUCCESS ", line + output.writeLine "SUCCESS ", line else: - output.writeln "FAILURE ", line + output.writeLine "FAILURE ", line result = false iterator caasTestsRunner*(filter = "", verbose = false): tuple[test, diff --git a/tests/testament/htmlgen.nim b/tests/testament/htmlgen.nim index a9f739995..98ccf1170 100644 --- a/tests/testament/htmlgen.nim +++ b/tests/testament/htmlgen.nim @@ -138,7 +138,7 @@ proc generateHtml*(filename: string, commit: int; onlyFailing: bool) = # generate navigation: outfile.write("""
      """) for m in db.rows(sql"select id, name, os, cpu from Machine order by id"): - outfile.writeln """
    • $#: $#, $#
    • """ % m + outfile.writeLine """
    • $#: $#, $#
    • """ % m outfile.write("
    ") for currentMachine in db.rows(sql"select id from Machine order by id"): @@ -195,7 +195,7 @@ proc generateJson*(filename: string, commit: int) = let machine = $backend.getMachine(db) let data = db.getRow(sql(selRow), lastCommit, machine) - outfile.writeln("""{"total": $#, "passed": $#, "skipped": $#""" % data) + outfile.writeLine("""{"total": $#, "passed": $#, "skipped": $#""" % data) let results = newJArray() for row in db.rows(sql(selResults), lastCommit): @@ -208,7 +208,7 @@ proc generateJson*(filename: string, commit: int) = obj["expected"] = %row[5] obj["given"] = %row[6] results.add(obj) - outfile.writeln(""", "results": """) + outfile.writeLine(""", "results": """) outfile.write(results.pretty) if not previousCommit.isNil: @@ -220,9 +220,9 @@ proc generateJson*(filename: string, commit: int) = obj["old"] = %row[1] obj["new"] = %row[2] diff.add obj - outfile.writeln(""", "diff": """) - outfile.writeln(diff.pretty) + outfile.writeLine(""", "diff": """) + outfile.writeLine(diff.pretty) - outfile.writeln "}" + outfile.writeLine "}" close(db) close(outfile) diff --git a/tests/trmacros/targlist.nim b/tests/trmacros/targlist.nim index 321b3d5d2..f9d2cb6c6 100644 --- a/tests/trmacros/targlist.nim +++ b/tests/trmacros/targlist.nim @@ -3,7 +3,7 @@ discard """ """ proc f(x: varargs[string, `$`]) = discard -template optF{f(x)}(x: varargs[expr]) = - writeln(stdout, x) +template optF{f(x)}(x: varargs[expr]) = + writeLine(stdout, x) f 1, 2, false, 3, "ha" diff --git a/tests/trmacros/tstmtlist.nim b/tests/trmacros/tstmtlist.nim index 20cb5d688..5202f778b 100644 --- a/tests/trmacros/tstmtlist.nim +++ b/tests/trmacros/tstmtlist.nim @@ -7,13 +7,13 @@ discard """ template optWrite{ write(f, x) - ((write|writeln){w})(f, y) + ((write|writeLine){w})(f, y) }(x, y: varargs[expr], f, w: expr) = w(f, "|", x, y, "|") if true: echo "0" write stdout, "1" - writeln stdout, "2" + writeLine stdout, "2" write stdout, "3" echo "4" From f71eaf66be35b2f4e7c12ebbb16ec301564bb0ab Mon Sep 17 00:00:00 2001 From: patrick dw Date: Fri, 19 Jun 2015 01:36:57 -0500 Subject: [PATCH 0517/1263] renamed writeln to writeLine in tools --- tools/cmerge.nim | 4 +-- tools/nimgrep.nim | 90 +++++++++++++++++++++++------------------------ tools/nimweb.nim | 6 ++-- 3 files changed, 50 insertions(+), 50 deletions(-) diff --git a/tools/cmerge.nim b/tools/cmerge.nim index d2e540481..13bf8b64c 100644 --- a/tools/cmerge.nim +++ b/tools/cmerge.nim @@ -19,9 +19,9 @@ proc process(dir, infile: string, outfile: File, ig <- (comment / \s+)* """: # follow the include file: if process(dir, matches[0], outfile, processed) == prAddIncludeDir: - writeln(outfile, line) + writeLine(outfile, line) else: - writeln(outfile, line) + writeLine(outfile, line) proc main(dir, outfile: string) = var o: File diff --git a/tools/nimgrep.nim b/tools/nimgrep.nim index 72e4adc07..221181f66 100644 --- a/tools/nimgrep.nim +++ b/tools/nimgrep.nim @@ -21,10 +21,10 @@ Options: --find, -f find the pattern (default) --replace, -r replace the pattern --peg pattern is a peg - --re pattern is a regular expression (default); extended + --re pattern is a regular expression (default); extended syntax for the regular expression is always turned on --recursive process directories recursively - --confirm confirm each occurrence/replacement; there is a chance + --confirm confirm each occurrence/replacement; there is a chance to abort any time without touching the file --stdin read pattern from stdin (to avoid the shell's confusing quoting rules) @@ -39,13 +39,13 @@ Options: """ type - TOption = enum + TOption = enum optFind, optReplace, optPeg, optRegex, optRecursive, optConfirm, optStdin, optWord, optIgnoreCase, optIgnoreStyle, optVerbose TOptions = set[TOption] - TConfirmEnum = enum + TConfirmEnum = enum ceAbort, ceYes, ceAll, ceNo, ceNone - + var filenames: seq[string] = @[] pattern = "" @@ -58,34 +58,34 @@ proc ask(msg: string): string = stdout.write(msg) result = stdin.readLine() -proc confirm: TConfirmEnum = +proc confirm: TConfirmEnum = while true: case normalize(ask(" [a]bort; [y]es, a[l]l, [n]o, non[e]: ")) - of "a", "abort": return ceAbort + of "a", "abort": return ceAbort of "y", "yes": return ceYes of "l", "all": return ceAll of "n", "no": return ceNo of "e", "none": return ceNone else: discard -proc countLines(s: string, first, last: int): int = +proc countLines(s: string, first, last: int): int = var i = first while i <= last: - if s[i] == '\13': + if s[i] == '\13': inc result if i < last and s[i+1] == '\10': inc(i) - elif s[i] == '\10': + elif s[i] == '\10': inc result inc i -proc beforePattern(s: string, first: int): int = +proc beforePattern(s: string, first: int): int = result = first-1 while result >= 0: if s[result] in NewLines: break dec(result) inc(result) -proc afterPattern(s: string, last: int): int = +proc afterPattern(s: string, last: int): int = result = last+1 while result < s.len: if s[result] in NewLines: break @@ -99,7 +99,7 @@ proc writeColored(s: string) = stdout.write(s) proc highlight(s, match, repl: string, t: tuple[first, last: int], - line: int, showRepl: bool) = + line: int, showRepl: bool) = const alignment = 6 stdout.write(line.`$`.align(alignment), ": ") var x = beforePattern(s, t.first) @@ -118,17 +118,17 @@ proc highlight(s, match, repl: string, t: tuple[first, last: int], proc processFile(filename: string) = var filenameShown = false template beforeHighlight = - if not filenameShown and optVerbose notin options: - stdout.writeln(filename) + if not filenameShown and optVerbose notin options: + stdout.writeLine(filename) filenameShown = true - + var buffer: string try: buffer = system.readFile(filename) - except IOError: + except IOError: echo "cannot open file: ", filename return - if optVerbose in options: stdout.writeln(filename) + if optVerbose in options: stdout.writeLine(filename) var pegp: TPeg var rep: Regex var result: string @@ -140,10 +140,10 @@ proc processFile(filename: string) = rep = re(pattern) else: pegp = peg(pattern) - + if optReplace in options: result = newStringOfCap(buffer.len) - + var line = 1 var i = 0 var matches: array[0..re.MaxSubpatterns-1, string] @@ -157,24 +157,24 @@ proc processFile(filename: string) = t = findBounds(buffer, rep, matches, i) if t.first <= 0: break inc(line, countLines(buffer, i, t.first-1)) - + var wholeMatch = buffer.substr(t.first, t.last) - + beforeHighlight() - if optReplace notin options: + if optReplace notin options: highlight(buffer, wholeMatch, "", t, line, showRepl=false) else: var r: string if optRegex notin options: r = replace(wholeMatch, pegp, replacement % matches) - else: + else: r = replace(wholeMatch, rep, replacement % matches) - if optConfirm in options: + if optConfirm in options: highlight(buffer, wholeMatch, r, t, line, showRepl=true) case confirm() of ceAbort: quit(0) - of ceYes: reallyReplace = true - of ceAll: + of ceYes: reallyReplace = true + of ceAll: reallyReplace = true options.excl(optConfirm) of ceNo: @@ -203,11 +203,11 @@ proc processFile(filename: string) = proc hasRightExt(filename: string, exts: seq[string]): bool = var y = splitFile(filename).ext.substr(1) # skip leading '.' - for x in items(exts): + for x in items(exts): if os.cmpPaths(x, y) == 0: return true -proc styleInsensitive(s: string): string = - template addx: stmt = +proc styleInsensitive(s: string): string = + template addx: stmt = result.add(s[i]) inc(i) result = "" @@ -215,7 +215,7 @@ proc styleInsensitive(s: string): string = var brackets = 0 while i < s.len: case s[i] - of 'A'..'Z', 'a'..'z', '0'..'9': + of 'A'..'Z', 'a'..'z', '0'..'9': addx() if brackets == 0: result.add("_?") of '_': @@ -234,29 +234,29 @@ proc styleInsensitive(s: string): string = while s[i] != '>' and s[i] != '\0': addx() of '\\': addx() - if s[i] in strutils.Digits: + if s[i] in strutils.Digits: while s[i] in strutils.Digits: addx() else: addx() else: addx() -proc walker(dir: string) = +proc walker(dir: string) = for kind, path in walkDir(dir): case kind - of pcFile: + of pcFile: if extensions.len == 0 or path.hasRightExt(extensions): processFile(path) - of pcDir: + of pcDir: if optRecursive in options: walker(path) else: discard if existsFile(dir): processFile(dir) -proc writeHelp() = +proc writeHelp() = stdout.write(Usage) quit(0) -proc writeVersion() = +proc writeVersion() = stdout.write(Version & "\n") quit(0) @@ -267,9 +267,9 @@ proc checkOptions(subset: TOptions, a, b: string) = for kind, key, val in getopt(): case kind of cmdArgument: - if options.contains(optStdin): + if options.contains(optStdin): filenames.add(key) - elif pattern.len == 0: + elif pattern.len == 0: pattern = key elif options.contains(optReplace) and replacement.len == 0: replacement = key @@ -306,7 +306,7 @@ checkOptions({optFind, optReplace}, "find", "replace") checkOptions({optPeg, optRegex}, "peg", "re") checkOptions({optIgnoreCase, optIgnoreStyle}, "ignore_case", "ignore_style") -if optStdin in options: +if optStdin in options: pattern = ask("pattern [ENTER to exit]: ") if isNil(pattern) or pattern.len == 0: quit(0) if optReplace in options: @@ -314,18 +314,18 @@ if optStdin in options: if pattern.len == 0: writeHelp() -else: - if filenames.len == 0: +else: + if filenames.len == 0: filenames.add(os.getCurrentDir()) - if optRegex notin options: + if optRegex notin options: if optWord in options: pattern = r"(^ / !\letter)(" & pattern & r") !\letter" - if optIgnoreStyle in options: + if optIgnoreStyle in options: pattern = "\\y " & pattern elif optIgnoreCase in options: pattern = "\\i " & pattern else: - if optIgnoreStyle in options: + if optIgnoreStyle in options: pattern = styleInsensitive(pattern) if optWord in options: pattern = r"\b (:?" & pattern & r") \b" diff --git a/tools/nimweb.nim b/tools/nimweb.nim index a7301195e..852b43092 100644 --- a/tools/nimweb.nim +++ b/tools/nimweb.nim @@ -126,10 +126,10 @@ proc parseCmdLine(c: var TConfigData) = break of cmdLongOption, cmdShortOption: case normalize(key) - of "help", "h": + of "help", "h": stdout.write(usage) quit(0) - of "version", "v": + of "version", "v": stdout.write(version & "\n") quit(0) of "o", "output": c.outdir = val @@ -431,7 +431,7 @@ proc buildWebsite(c: var TConfigData) = if not existsDir("web/upload"): createDir("web/upload") if open(f, outfile, fmWrite): - writeln(f, generateHTMLPage(c, file, content, rss)) + writeLine(f, generateHTMLPage(c, file, content, rss)) close(f) else: quit("[Error] cannot write file: " & outfile) From 4e275f2a1a1995d6b7a2bc461b96d804368c0931 Mon Sep 17 00:00:00 2001 From: patrick dw Date: Fri, 19 Jun 2015 01:38:31 -0500 Subject: [PATCH 0518/1263] renamed writeln to writeLine in examples --- examples/cgi/example.nim | 2 +- examples/cgiex.nim | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/examples/cgi/example.nim b/examples/cgi/example.nim index 17629982a..761197cdb 100644 --- a/examples/cgi/example.nim +++ b/examples/cgi/example.nim @@ -4,4 +4,4 @@ write(stdout, "Content-type: text/html\n\n") write(stdout, "\n") write(stdout, "Test\n") write(stdout, "Hello!") -writeln(stdout, "") +writeLine(stdout, "") diff --git a/examples/cgiex.nim b/examples/cgiex.nim index 7e3292f35..fb55a731a 100644 --- a/examples/cgiex.nim +++ b/examples/cgiex.nim @@ -7,6 +7,6 @@ writeContentType() write(stdout, "\n") write(stdout, "Test\n") -writeln(stdout, "name: " & myData["name"]) -writeln(stdout, "password: " & myData["password"]) -writeln(stdout, "") +writeLine(stdout, "name: " & myData["name"]) +writeLine(stdout, "password: " & myData["password"]) +writeLine(stdout, "") From 2a0f7b5de72dc1d8c1018bb60630764f765376bb Mon Sep 17 00:00:00 2001 From: patrick dw Date: Fri, 19 Jun 2015 01:45:12 -0500 Subject: [PATCH 0519/1263] renamed writeln to writeLine in compiler --- compiler/astalgo.nim | 2 +- compiler/extccomp.nim | 2 +- compiler/idgen.nim | 22 +- compiler/msgs.nim | 12 +- compiler/nimfix/nimfix.nim | 2 +- compiler/options.nim | 2 +- compiler/rodread.nim | 402 ++++++++++++++++++------------------- compiler/sigmatch.nim | 12 +- 8 files changed, 228 insertions(+), 228 deletions(-) diff --git a/compiler/astalgo.nim b/compiler/astalgo.nim index 5980edb27..3ba43b4c5 100644 --- a/compiler/astalgo.nim +++ b/compiler/astalgo.nim @@ -452,7 +452,7 @@ proc debug(n: PSym) = elif n.kind == skUnknown: msgWriteln("skUnknown") else: - #writeln(stdout, $symToYaml(n, 0, 1)) + #writeLine(stdout, $symToYaml(n, 0, 1)) msgWriteln("$1_$2: $3, $4, $5, $6" % [ n.name.s, $n.id, $flagsToStr(n.flags), $flagsToStr(n.loc.flags), $lineInfoToStr(n.info), $n.kind]) diff --git a/compiler/extccomp.nim b/compiler/extccomp.nim index 38427b367..2c6e5294f 100644 --- a/compiler/extccomp.nim +++ b/compiler/extccomp.nim @@ -596,7 +596,7 @@ proc externalFileChanged(filename: string): bool = result = true if result: if open(f, crcFile, fmWrite): - f.writeln($currentCrc) + f.writeLine($currentCrc) close(f) proc addExternalFileToCompile*(filename: string) = diff --git a/compiler/idgen.nim b/compiler/idgen.nim index 3c5669b54..c07782fb2 100644 --- a/compiler/idgen.nim +++ b/compiler/idgen.nim @@ -18,26 +18,26 @@ const when debugIds: import intsets - + var usedIds = initIntSet() -proc registerID*(id: PIdObj) = - when debugIds: - if id.id == -1 or containsOrIncl(usedIds, id.id): +proc registerID*(id: PIdObj) = + when debugIds: + if id.id == -1 or containsOrIncl(usedIds, id.id): internalError("ID already used: " & $id.id) -proc getID*(): int {.inline.} = +proc getID*(): int {.inline.} = result = gFrontEndId inc(gFrontEndId) -proc backendId*(): int {.inline.} = +proc backendId*(): int {.inline.} = result = gBackendId inc(gBackendId) -proc setId*(id: int) {.inline.} = +proc setId*(id: int) {.inline.} = gFrontEndId = max(gFrontEndId, id + 1) -proc idSynchronizationPoint*(idRange: int) = +proc idSynchronizationPoint*(idRange: int) = gFrontEndId = (gFrontEndId div idRange + 1) * idRange + 1 proc toGid(f: string): string = @@ -48,10 +48,10 @@ proc toGid(f: string): string = proc saveMaxIds*(project: string) = var f = open(project.toGid, fmWrite) - f.writeln($gFrontEndId) - f.writeln($gBackendId) + f.writeLine($gFrontEndId) + f.writeLine($gBackendId) f.close() - + proc loadMaxIds*(project: string) = var f: File if open(f, project.toGid, fmRead): diff --git a/compiler/msgs.nim b/compiler/msgs.nim index 6b71b7159..3d5edaf40 100644 --- a/compiler/msgs.nim +++ b/compiler/msgs.nim @@ -593,7 +593,7 @@ var proc suggestWriteln*(s: string) = if eStdOut in errorOutputs: - if isNil(writelnHook): writeln(stdout, s) + if isNil(writelnHook): writeLine(stdout, s) else: writelnHook(s) proc msgQuit*(x: int8) = quit x @@ -688,7 +688,7 @@ var gTrackPos*: TLineInfo proc outWriteln*(s: string) = ## Writes to stdout. Always. - if eStdOut in errorOutputs: writeln(stdout, s) + if eStdOut in errorOutputs: writeLine(stdout, s) proc msgWriteln*(s: string) = ## Writes to stdout. If --stdout option is given, writes to stderr instead. @@ -698,9 +698,9 @@ proc msgWriteln*(s: string) = if not isNil(writelnHook): writelnHook(s) elif optStdout in gGlobalOptions: - if eStdErr in errorOutputs: writeln(stderr, s) + if eStdErr in errorOutputs: writeLine(stderr, s) else: - if eStdOut in errorOutputs: writeln(stdout, s) + if eStdOut in errorOutputs: writeLine(stdout, s) macro callIgnoringStyle(theProc: typed, first: typed, args: varargs[expr]): stmt = @@ -735,13 +735,13 @@ template styledMsgWriteln*(args: varargs[expr]) = if not isNil(writelnHook): callIgnoringStyle(callWritelnHook, nil, args) elif optStdout in gGlobalOptions: - if eStdErr in errorOutputs: callIgnoringStyle(writeln, stderr, args) + if eStdErr in errorOutputs: callIgnoringStyle(writeLine, stderr, args) else: if eStdOut in errorOutputs: if optUseColors in gGlobalOptions: callStyledEcho(args) else: - callIgnoringStyle(writeln, stdout, args) + callIgnoringStyle(writeLine, stdout, args) proc coordToStr(coord: int): string = if coord == -1: result = "???" diff --git a/compiler/nimfix/nimfix.nim b/compiler/nimfix/nimfix.nim index 3641aec36..39436702f 100644 --- a/compiler/nimfix/nimfix.nim +++ b/compiler/nimfix/nimfix.nim @@ -82,7 +82,7 @@ proc processCmdLine*(pass: TCmdLinePass, cmd: string) = proc handleCmdLine() = if paramCount() == 0: - stdout.writeln(Usage) + stdout.writeLine(Usage) else: processCmdLine(passCmd1, "") if gProjectName != "": diff --git a/compiler/options.nim b/compiler/options.nim index f3277f855..398d3171d 100644 --- a/compiler/options.nim +++ b/compiler/options.nim @@ -304,7 +304,7 @@ proc completeGeneratedFilePath*(f: string, createSubDir: bool = true): string = when noTimeMachine: excludeDirFromTimeMachine(subdir) except OSError: - writeln(stdout, "cannot create directory: " & subdir) + writeLine(stdout, "cannot create directory: " & subdir) quit(1) result = joinPath(subdir, tail) #echo "completeGeneratedFilePath(", f, ") = ", result diff --git a/compiler/rodread.nim b/compiler/rodread.nim index dad7d111e..c1c27aedb 100644 --- a/compiler/rodread.nim +++ b/compiler/rodread.nim @@ -12,7 +12,7 @@ # Reading and writing binary files are really hard to debug. Therefore we use # a "creative" text/binary hybrid format. ROD-files are more efficient # to process because symbols can be loaded on demand. -# +# # A ROD file consists of: # # - a header: @@ -44,7 +44,7 @@ # ) # - a compiler proc section: # COMPILERPROCS( -# identifier1 id\n # id is the symbol's id +# identifier1 id\n # id is the symbol's id # ) # - an index consisting of (ID, linenumber)-pairs: # INDEX( @@ -52,7 +52,7 @@ # id-diff idx-diff\n # ) # -# Since the whole index has to be read in advance, we compress it by +# Since the whole index has to be read in advance, we compress it by # storing the integer differences to the last entry instead of using the # real numbers. # @@ -88,11 +88,11 @@ # by using a mem'mapped file. # -import - os, options, strutils, nversion, ast, astalgo, msgs, platform, condsyms, +import + os, options, strutils, nversion, ast, astalgo, msgs, platform, condsyms, ropes, idents, securehash, idgen, types, rodutils, memfiles -type +type TReasonForRecompile* = enum ## all the reasons that can trigger recompilation rrEmpty, # dependencies not yet computed rrNone, # no need to recompile @@ -104,14 +104,14 @@ type rrInclDeps, # an include has changed rrModDeps # a module this module depends on has been changed -const - reasonToFrmt*: array[TReasonForRecompile, string] = ["", - "no need to recompile: $1", "symbol file for $1 does not exist", - "symbol file for $1 has the wrong version", - "file edited since last compilation: $1", - "list of conditional symbols changed for: $1", - "list of options changed for: $1", - "an include file edited: $1", +const + reasonToFrmt*: array[TReasonForRecompile, string] = ["", + "no need to recompile: $1", "symbol file for $1 does not exist", + "symbol file for $1 has the wrong version", + "file edited since last compilation: $1", + "list of conditional symbols changed for: $1", + "list of options changed for: $1", + "an include file edited: $1", "a module $1 depends on has changed"] type @@ -120,7 +120,7 @@ type tab*: TIITable r*: string # writers use this offset*: int # readers use this - + TRodReader* = object of RootObj pos: int # position; used for parsing s: cstring # mmap'ed file contents @@ -142,7 +142,7 @@ type methods*: TSymSeq origFile: string inViewMode: bool - + PRodReader* = ref TRodReader var rodCompilerprocs*: TStrTable @@ -161,16 +161,16 @@ proc rrGetSym(r: PRodReader, id: int, info: TLineInfo): PSym # `info` is only used for debugging purposes proc rrGetType(r: PRodReader, id: int, info: TLineInfo): PType -proc decodeLineInfo(r: PRodReader, info: var TLineInfo) = - if r.s[r.pos] == '?': +proc decodeLineInfo(r: PRodReader, info: var TLineInfo) = + if r.s[r.pos] == '?': inc(r.pos) if r.s[r.pos] == ',': info.col = -1'i16 else: info.col = int16(decodeVInt(r.s, r.pos)) - if r.s[r.pos] == ',': + if r.s[r.pos] == ',': inc(r.pos) if r.s[r.pos] == ',': info.line = -1'i16 else: info.line = int16(decodeVInt(r.s, r.pos)) - if r.s[r.pos] == ',': + if r.s[r.pos] == ',': inc(r.pos) info = newLineInfo(r.files[decodeVInt(r.s, r.pos)], info.line, info.col) @@ -188,56 +188,56 @@ proc skipNode(r: PRodReader) = inc pos r.pos = pos+1 # skip ')' -proc decodeNodeLazyBody(r: PRodReader, fInfo: TLineInfo, - belongsTo: PSym): PNode = +proc decodeNodeLazyBody(r: PRodReader, fInfo: TLineInfo, + belongsTo: PSym): PNode = result = nil - if r.s[r.pos] == '(': + if r.s[r.pos] == '(': inc(r.pos) - if r.s[r.pos] == ')': + if r.s[r.pos] == ')': inc(r.pos) return # nil node result = newNodeI(TNodeKind(decodeVInt(r.s, r.pos)), fInfo) decodeLineInfo(r, result.info) - if r.s[r.pos] == '$': + if r.s[r.pos] == '$': inc(r.pos) result.flags = cast[TNodeFlags](int32(decodeVInt(r.s, r.pos))) - if r.s[r.pos] == '^': + if r.s[r.pos] == '^': inc(r.pos) var id = decodeVInt(r.s, r.pos) result.typ = rrGetType(r, id, result.info) case result.kind - of nkCharLit..nkInt64Lit: - if r.s[r.pos] == '!': + of nkCharLit..nkInt64Lit: + if r.s[r.pos] == '!': inc(r.pos) result.intVal = decodeVBiggestInt(r.s, r.pos) - of nkFloatLit..nkFloat64Lit: - if r.s[r.pos] == '!': + of nkFloatLit..nkFloat64Lit: + if r.s[r.pos] == '!': inc(r.pos) var fl = decodeStr(r.s, r.pos) result.floatVal = parseFloat(fl) - of nkStrLit..nkTripleStrLit: - if r.s[r.pos] == '!': + of nkStrLit..nkTripleStrLit: + if r.s[r.pos] == '!': inc(r.pos) result.strVal = decodeStr(r.s, r.pos) - else: + else: result.strVal = "" # BUGFIX - of nkIdent: - if r.s[r.pos] == '!': + of nkIdent: + if r.s[r.pos] == '!': inc(r.pos) var fl = decodeStr(r.s, r.pos) result.ident = getIdent(fl) - else: + else: internalError(result.info, "decodeNode: nkIdent") - of nkSym: - if r.s[r.pos] == '!': + of nkSym: + if r.s[r.pos] == '!': inc(r.pos) var id = decodeVInt(r.s, r.pos) result.sym = rrGetSym(r, id, result.info) - else: + else: internalError(result.info, "decodeNode: nkSym") else: var i = 0 - while r.s[r.pos] != ')': + while r.s[r.pos] != ')': if belongsTo != nil and i == bodyPos: addSonNilAllowed(result, nil) belongsTo.offset = r.pos @@ -252,93 +252,93 @@ proc decodeNodeLazyBody(r: PRodReader, fInfo: TLineInfo, proc decodeNode(r: PRodReader, fInfo: TLineInfo): PNode = result = decodeNodeLazyBody(r, fInfo, nil) - -proc decodeLoc(r: PRodReader, loc: var TLoc, info: TLineInfo) = - if r.s[r.pos] == '<': + +proc decodeLoc(r: PRodReader, loc: var TLoc, info: TLineInfo) = + if r.s[r.pos] == '<': inc(r.pos) - if r.s[r.pos] in {'0'..'9', 'a'..'z', 'A'..'Z'}: + if r.s[r.pos] in {'0'..'9', 'a'..'z', 'A'..'Z'}: loc.k = TLocKind(decodeVInt(r.s, r.pos)) - else: + else: loc.k = low(loc.k) - if r.s[r.pos] == '*': + if r.s[r.pos] == '*': inc(r.pos) loc.s = TStorageLoc(decodeVInt(r.s, r.pos)) - else: + else: loc.s = low(loc.s) - if r.s[r.pos] == '$': + if r.s[r.pos] == '$': inc(r.pos) loc.flags = cast[TLocFlags](int32(decodeVInt(r.s, r.pos))) - else: + else: loc.flags = {} - if r.s[r.pos] == '^': + if r.s[r.pos] == '^': inc(r.pos) loc.t = rrGetType(r, decodeVInt(r.s, r.pos), info) - else: + else: loc.t = nil - if r.s[r.pos] == '!': + if r.s[r.pos] == '!': inc(r.pos) loc.r = rope(decodeStr(r.s, r.pos)) - else: + else: loc.r = nil if r.s[r.pos] == '>': inc(r.pos) else: internalError(info, "decodeLoc " & r.s[r.pos]) - -proc decodeType(r: PRodReader, info: TLineInfo): PType = + +proc decodeType(r: PRodReader, info: TLineInfo): PType = result = nil - if r.s[r.pos] == '[': + if r.s[r.pos] == '[': inc(r.pos) - if r.s[r.pos] == ']': + if r.s[r.pos] == ']': inc(r.pos) return # nil type new(result) result.kind = TTypeKind(decodeVInt(r.s, r.pos)) - if r.s[r.pos] == '+': + if r.s[r.pos] == '+': inc(r.pos) result.id = decodeVInt(r.s, r.pos) setId(result.id) if debugIds: registerID(result) - else: + else: internalError(info, "decodeType: no id") # here this also avoids endless recursion for recursive type - idTablePut(gTypeTable, result, result) + idTablePut(gTypeTable, result, result) if r.s[r.pos] == '(': result.n = decodeNode(r, unknownLineInfo()) - if r.s[r.pos] == '$': + if r.s[r.pos] == '$': inc(r.pos) result.flags = cast[TTypeFlags](int32(decodeVInt(r.s, r.pos))) - if r.s[r.pos] == '?': + if r.s[r.pos] == '?': inc(r.pos) result.callConv = TCallingConvention(decodeVInt(r.s, r.pos)) - if r.s[r.pos] == '*': + if r.s[r.pos] == '*': inc(r.pos) result.owner = rrGetSym(r, decodeVInt(r.s, r.pos), info) - if r.s[r.pos] == '&': + if r.s[r.pos] == '&': inc(r.pos) result.sym = rrGetSym(r, decodeVInt(r.s, r.pos), info) - if r.s[r.pos] == '/': + if r.s[r.pos] == '/': inc(r.pos) result.size = decodeVInt(r.s, r.pos) - else: + else: result.size = - 1 - if r.s[r.pos] == '=': + if r.s[r.pos] == '=': inc(r.pos) result.align = decodeVInt(r.s, r.pos).int16 - else: + else: result.align = 2 decodeLoc(r, result.loc, info) - while r.s[r.pos] == '^': + while r.s[r.pos] == '^': inc(r.pos) - if r.s[r.pos] == '(': + if r.s[r.pos] == '(': inc(r.pos) if r.s[r.pos] == ')': inc(r.pos) else: internalError(info, "decodeType ^(" & r.s[r.pos]) rawAddSon(result, nil) - else: + else: var d = decodeVInt(r.s, r.pos) rawAddSon(result, rrGetType(r, d, info)) -proc decodeLib(r: PRodReader, info: TLineInfo): PLib = +proc decodeLib(r: PRodReader, info: TLineInfo): PLib = result = nil - if r.s[r.pos] == '|': + if r.s[r.pos] == '|': new(result) inc(r.pos) result.kind = TLibKind(decodeVInt(r.s, r.pos)) @@ -349,31 +349,31 @@ proc decodeLib(r: PRodReader, info: TLineInfo): PLib = inc(r.pos) result.path = decodeNode(r, info) -proc decodeSym(r: PRodReader, info: TLineInfo): PSym = - var +proc decodeSym(r: PRodReader, info: TLineInfo): PSym = + var id: int ident: PIdent result = nil - if r.s[r.pos] == '{': + if r.s[r.pos] == '{': inc(r.pos) - if r.s[r.pos] == '}': + if r.s[r.pos] == '}': inc(r.pos) return # nil sym var k = TSymKind(decodeVInt(r.s, r.pos)) - if r.s[r.pos] == '+': + if r.s[r.pos] == '+': inc(r.pos) id = decodeVInt(r.s, r.pos) setId(id) else: internalError(info, "decodeSym: no id") - if r.s[r.pos] == '&': + if r.s[r.pos] == '&': inc(r.pos) ident = getIdent(decodeStr(r.s, r.pos)) else: internalError(info, "decodeSym: no ident") #echo "decoding: {", ident.s result = PSym(idTableGet(r.syms, id)) - if result == nil: + if result == nil: new(result) result.id = id idTablePut(r.syms, result, result) @@ -388,35 +388,35 @@ proc decodeSym(r: PRodReader, info: TLineInfo): PSym = result.id = id result.kind = k result.name = ident # read the rest of the symbol description: - if r.s[r.pos] == '^': + if r.s[r.pos] == '^': inc(r.pos) result.typ = rrGetType(r, decodeVInt(r.s, r.pos), info) decodeLineInfo(r, result.info) - if r.s[r.pos] == '*': + if r.s[r.pos] == '*': inc(r.pos) result.owner = rrGetSym(r, decodeVInt(r.s, r.pos), result.info) - if r.s[r.pos] == '$': + if r.s[r.pos] == '$': inc(r.pos) result.flags = cast[TSymFlags](int32(decodeVInt(r.s, r.pos))) - if r.s[r.pos] == '@': + if r.s[r.pos] == '@': inc(r.pos) result.magic = TMagic(decodeVInt(r.s, r.pos)) - if r.s[r.pos] == '!': + if r.s[r.pos] == '!': inc(r.pos) result.options = cast[TOptions](int32(decodeVInt(r.s, r.pos))) - else: + else: result.options = r.options - if r.s[r.pos] == '%': + if r.s[r.pos] == '%': inc(r.pos) result.position = decodeVInt(r.s, r.pos) elif result.kind notin routineKinds + {skModule}: result.position = 0 # this may have been misused as reader index! But we still # need it for routines as the body is loaded lazily. - if r.s[r.pos] == '`': + if r.s[r.pos] == '`': inc(r.pos) result.offset = decodeVInt(r.s, r.pos) - else: + else: result.offset = - 1 decodeLoc(r, result.loc, result.info) result.annex = decodeLib(r, info) @@ -433,35 +433,35 @@ proc decodeSym(r: PRodReader, info: TLineInfo): PSym = result.ast = decodeNode(r, result.info) #echo "decoded: ", ident.s, "}" -proc skipSection(r: PRodReader) = - if r.s[r.pos] == ':': +proc skipSection(r: PRodReader) = + if r.s[r.pos] == ':': while r.s[r.pos] > '\x0A': inc(r.pos) - elif r.s[r.pos] == '(': + elif r.s[r.pos] == '(': var c = 0 # count () pairs inc(r.pos) - while true: + while true: case r.s[r.pos] of '\x0A': inc(r.line) of '(': inc(c) - of ')': - if c == 0: + of ')': + if c == 0: inc(r.pos) - break - elif c > 0: + break + elif c > 0: dec(c) of '\0': break # end of file else: discard inc(r.pos) - else: + else: internalError("skipSection " & $r.line) - -proc rdWord(r: PRodReader): string = + +proc rdWord(r: PRodReader): string = result = "" - while r.s[r.pos] in {'A'..'Z', '_', 'a'..'z', '0'..'9'}: + while r.s[r.pos] in {'A'..'Z', '_', 'a'..'z', '0'..'9'}: add(result, r.s[r.pos]) inc(r.pos) -proc newStub(r: PRodReader, name: string, id: int): PSym = +proc newStub(r: PRodReader, name: string, id: int): PSym = new(result) result.kind = skStub result.id = id @@ -469,11 +469,11 @@ proc newStub(r: PRodReader, name: string, id: int): PSym = result.position = r.readerIndex setId(id) #MessageOut(result.name.s); if debugIds: registerID(result) - -proc processInterf(r: PRodReader, module: PSym) = + +proc processInterf(r: PRodReader, module: PSym) = if r.interfIdx == 0: internalError("processInterf") r.pos = r.interfIdx - while (r.s[r.pos] > '\x0A') and (r.s[r.pos] != ')'): + while (r.s[r.pos] > '\x0A') and (r.s[r.pos] != ')'): var w = decodeStr(r.s, r.pos) inc(r.pos) var key = decodeVInt(r.s, r.pos) @@ -483,28 +483,28 @@ proc processInterf(r: PRodReader, module: PSym) = strTableAdd(module.tab, s) idTablePut(r.syms, s, s) -proc processCompilerProcs(r: PRodReader, module: PSym) = +proc processCompilerProcs(r: PRodReader, module: PSym) = if r.compilerProcsIdx == 0: internalError("processCompilerProcs") r.pos = r.compilerProcsIdx - while (r.s[r.pos] > '\x0A') and (r.s[r.pos] != ')'): + while (r.s[r.pos] > '\x0A') and (r.s[r.pos] != ')'): var w = decodeStr(r.s, r.pos) inc(r.pos) var key = decodeVInt(r.s, r.pos) inc(r.pos) # #10 var s = PSym(idTableGet(r.syms, key)) - if s == nil: + if s == nil: s = newStub(r, w, key) s.owner = module idTablePut(r.syms, s, s) strTableAdd(rodCompilerprocs, s) -proc processIndex(r: PRodReader; idx: var TIndex; outf: File = nil) = +proc processIndex(r: PRodReader; idx: var TIndex; outf: File = nil) = var key, val, tmp: int inc(r.pos, 2) # skip "(\10" inc(r.line) - while (r.s[r.pos] > '\x0A') and (r.s[r.pos] != ')'): + while (r.s[r.pos] > '\x0A') and (r.s[r.pos] != ')'): tmp = decodeVInt(r.s, r.pos) - if r.s[r.pos] == ' ': + if r.s[r.pos] == ' ': inc(r.pos) key = idx.lastIdxKey + tmp val = decodeVInt(r.s, r.pos) + idx.lastIdxVal @@ -516,11 +516,11 @@ proc processIndex(r: PRodReader; idx: var TIndex; outf: File = nil) = idx.lastIdxKey = key idx.lastIdxVal = val setId(key) # ensure that this id will not be used - if r.s[r.pos] == '\x0A': + if r.s[r.pos] == '\x0A': inc(r.pos) inc(r.line) if r.s[r.pos] == ')': inc(r.pos) - + proc cmdChangeTriggersRecompilation(old, new: TCommands): bool = if old == new: return false # we use a 'case' statement without 'else' so that addition of a @@ -532,34 +532,34 @@ proc cmdChangeTriggersRecompilation(old, new: TCommands): bool = cmdInteractive}: return false of cmdNone, cmdDoc, cmdInterpret, cmdPretty, cmdGenDepend, cmdDump, - cmdCheck, cmdParse, cmdScan, cmdIdeTools, cmdDef, + cmdCheck, cmdParse, cmdScan, cmdIdeTools, cmdDef, cmdRst2html, cmdRst2tex, cmdInteractive, cmdRun: discard # else: trigger recompilation: result = true - -proc processRodFile(r: PRodReader, crc: SecureHash) = - var + +proc processRodFile(r: PRodReader, crc: SecureHash) = + var w: string d: int var inclCrc: SecureHash - while r.s[r.pos] != '\0': + while r.s[r.pos] != '\0': var section = rdWord(r) - if r.reason != rrNone: + if r.reason != rrNone: break # no need to process this file further - case section - of "CRC": + case section + of "CRC": inc(r.pos) # skip ':' if crc != parseSecureHash(decodeStr(r.s, r.pos)): r.reason = rrCrcChange - of "ID": + of "ID": inc(r.pos) # skip ':' r.moduleID = decodeVInt(r.s, r.pos) setId(r.moduleID) of "ORIGFILE": inc(r.pos) r.origFile = decodeStr(r.s, r.pos) - of "OPTIONS": + of "OPTIONS": inc(r.pos) # skip ':' r.options = cast[TOptions](int32(decodeVInt(r.s, r.pos))) if options.gOptions != r.options: r.reason = rrOptions @@ -574,14 +574,14 @@ proc processRodFile(r: PRodReader, crc: SecureHash) = of "DEFINES": inc(r.pos) # skip ':' d = 0 - while r.s[r.pos] > '\x0A': + while r.s[r.pos] > '\x0A': w = decodeStr(r.s, r.pos) inc(d) - if not condsyms.isDefined(getIdent(w)): + if not condsyms.isDefined(getIdent(w)): r.reason = rrDefines #MessageOut('not defined, but should: ' + w); if r.s[r.pos] == ' ': inc(r.pos) if (d != countDefinedSymbols()): r.reason = rrDefines - of "FILES": + of "FILES": inc(r.pos, 2) # skip "(\10" inc(r.line) while r.s[r.pos] != ')': @@ -592,17 +592,17 @@ proc processRodFile(r: PRodReader, crc: SecureHash) = inc(r.pos) # skip #10 inc(r.line) if r.s[r.pos] == ')': inc(r.pos) - of "INCLUDES": + of "INCLUDES": inc(r.pos, 2) # skip "(\10" inc(r.line) - while r.s[r.pos] != ')': + while r.s[r.pos] != ')': w = r.files[decodeVInt(r.s, r.pos)].toFullPath inc(r.pos) # skip ' ' inclCrc = parseSecureHash(decodeStr(r.s, r.pos)) - if r.reason == rrNone: - if not existsFile(w) or (inclCrc != secureHashFile(w)): + if r.reason == rrNone: + if not existsFile(w) or (inclCrc != secureHashFile(w)): r.reason = rrInclDeps - if r.s[r.pos] == '\x0A': + if r.s[r.pos] == '\x0A': inc(r.pos) inc(r.line) if r.s[r.pos] == ')': inc(r.pos) @@ -611,28 +611,28 @@ proc processRodFile(r: PRodReader, crc: SecureHash) = while r.s[r.pos] > '\x0A': r.modDeps.add(r.files[int32(decodeVInt(r.s, r.pos))]) if r.s[r.pos] == ' ': inc(r.pos) - of "INTERF": + of "INTERF": r.interfIdx = r.pos + 2 skipSection(r) - of "COMPILERPROCS": + of "COMPILERPROCS": r.compilerProcsIdx = r.pos + 2 skipSection(r) - of "INDEX": + of "INDEX": processIndex(r, r.index) - of "IMPORTS": + of "IMPORTS": processIndex(r, r.imports) - of "CONVERTERS": + of "CONVERTERS": r.convertersIdx = r.pos + 1 skipSection(r) of "METHODS": r.methodsIdx = r.pos + 1 skipSection(r) - of "DATA": + of "DATA": r.dataIdx = r.pos + 2 # "(\10" # We do not read the DATA section here! We read the needed objects on # demand. And the DATA section comes last in the file, so we stop here: break - of "INIT": + of "INIT": r.initIdx = r.pos + 2 # "(\10" skipSection(r) else: @@ -641,7 +641,7 @@ proc processRodFile(r: PRodReader, crc: SecureHash) = #MsgWriteln("skipping section: " & section & # " at " & $r.line & " in " & r.filename) skipSection(r) - if r.s[r.pos] == '\x0A': + if r.s[r.pos] == '\x0A': inc(r.pos) inc(r.line) @@ -652,7 +652,7 @@ proc startsWith(buf: cstring, token: string, pos = 0): bool = result = s == token.len proc newRodReader(modfilename: string, crc: SecureHash, - readerIndex: int): PRodReader = + readerIndex: int): PRodReader = new(result) try: result.memfile = memfiles.open(modfilename) @@ -671,7 +671,7 @@ proc newRodReader(modfilename: string, crc: SecureHash, # we terminate the file explicitly with ``\0``, so the cast to `cstring` # is safe: r.s = cast[cstring](r.memfile.mem) - if startsWith(r.s, "NIM:"): + if startsWith(r.s, "NIM:"): initIiTable(r.index.tab) initIiTable(r.imports.tab) # looks like a ROD file inc(r.pos, 4) @@ -680,16 +680,16 @@ proc newRodReader(modfilename: string, crc: SecureHash, add(version, r.s[r.pos]) inc(r.pos) if r.s[r.pos] == '\x0A': inc(r.pos) - if version != RodFileVersion: + if version != RodFileVersion: # since ROD files are only for caching, no backwards compatibility is # needed result = nil else: result = nil - -proc rrGetType(r: PRodReader, id: int, info: TLineInfo): PType = + +proc rrGetType(r: PRodReader, id: int, info: TLineInfo): PType = result = PType(idTableGet(gTypeTable, id)) - if result == nil: + if result == nil: # load the type: var oldPos = r.pos var d = iiTableGet(r.index.tab, id) @@ -698,8 +698,8 @@ proc rrGetType(r: PRodReader, id: int, info: TLineInfo): PType = result = decodeType(r, info) r.pos = oldPos -type - TFileModuleRec{.final.} = object +type + TFileModuleRec{.final.} = object filename*: string reason*: TReasonForRecompile rd*: PRodReader @@ -710,7 +710,7 @@ type var gMods*: TFileModuleMap = @[] -proc decodeSymSafePos(rd: PRodReader, offset: int, info: TLineInfo): PSym = +proc decodeSymSafePos(rd: PRodReader, offset: int, info: TLineInfo): PSym = # all compiled modules if rd.dataIdx == 0: internalError(info, "dataIdx == 0") var oldPos = rd.pos @@ -719,9 +719,9 @@ proc decodeSymSafePos(rd: PRodReader, offset: int, info: TLineInfo): PSym = rd.pos = oldPos proc findSomeWhere(id: int) = - for i in countup(0, high(gMods)): + for i in countup(0, high(gMods)): var rd = gMods[i].rd - if rd != nil: + if rd != nil: var d = iiTableGet(rd.index.tab, id) if d != InvalidKey: echo "found id ", id, " in ", gMods[i].filename @@ -736,12 +736,12 @@ proc getReader(moduleId: int): PRodReader = if result != nil and result.moduleID == moduleId: return result return nil -proc rrGetSym(r: PRodReader, id: int, info: TLineInfo): PSym = +proc rrGetSym(r: PRodReader, id: int, info: TLineInfo): PSym = result = PSym(idTableGet(r.syms, id)) - if result == nil: + if result == nil: # load the symbol: var d = iiTableGet(r.index.tab, id) - if d == InvalidKey: + if d == InvalidKey: # import from other module: var moduleID = iiTableGet(r.imports.tab, id) if moduleID < 0: @@ -750,24 +750,24 @@ proc rrGetSym(r: PRodReader, id: int, info: TLineInfo): PSym = internalError(info, "missing from both indexes: +" & x) var rd = getReader(moduleID) d = iiTableGet(rd.index.tab, id) - if d != InvalidKey: + if d != InvalidKey: result = decodeSymSafePos(rd, d, info) else: var x = "" encodeVInt(id, x) when false: findSomeWhere(id) internalError(info, "rrGetSym: no reader found: +" & x) - else: + else: # own symbol: result = decodeSymSafePos(r, d, info) if result != nil and result.kind == skStub: rawLoadStub(result) - -proc loadInitSection(r: PRodReader): PNode = + +proc loadInitSection(r: PRodReader): PNode = if r.initIdx == 0 or r.dataIdx == 0: internalError("loadInitSection") var oldPos = r.pos r.pos = r.initIdx result = newNode(nkStmtList) - while r.s[r.pos] > '\x0A' and r.s[r.pos] != ')': + while r.s[r.pos] > '\x0A' and r.s[r.pos] != ')': var d = decodeVInt(r.s, r.pos) inc(r.pos) # #10 var p = r.pos @@ -776,13 +776,13 @@ proc loadInitSection(r: PRodReader): PNode = r.pos = p r.pos = oldPos -proc loadConverters(r: PRodReader) = +proc loadConverters(r: PRodReader) = # We have to ensure that no exported converter is a stub anymore, and the # import mechanism takes care of the rest. - if r.convertersIdx == 0 or r.dataIdx == 0: + if r.convertersIdx == 0 or r.dataIdx == 0: internalError("importConverters") r.pos = r.convertersIdx - while r.s[r.pos] > '\x0A': + while r.s[r.pos] > '\x0A': var d = decodeVInt(r.s, r.pos) discard rrGetSym(r, d, unknownLineInfo()) if r.s[r.pos] == ' ': inc(r.pos) @@ -801,7 +801,7 @@ proc getCRC*(fileIdx: int32): SecureHash = if gMods[fileIdx].crcDone: return gMods[fileIdx].crc - + result = secureHashFile(fileIdx.toFilename) gMods[fileIdx].crc = result @@ -811,7 +811,7 @@ template growCache*(cache, pos) = proc checkDep(fileIdx: int32): TReasonForRecompile = assert fileIdx != InvalidFileIDX growCache gMods, fileIdx - if gMods[fileIdx].reason != rrEmpty: + if gMods[fileIdx].reason != rrEmpty: # reason has already been computed for this module: return gMods[fileIdx].reason let filename = fileIdx.toFilename @@ -821,12 +821,12 @@ proc checkDep(fileIdx: int32): TReasonForRecompile = var r: PRodReader = nil var rodfile = toGeneratedFile(filename.withPackageName, RodExt) r = newRodReader(rodfile, crc, fileIdx) - if r == nil: + if r == nil: result = (if existsFile(rodfile): rrRodInvalid else: rrRodDoesNotExist) else: processRodFile(r, crc) result = r.reason - if result == rrNone: + if result == rrNone: # check modules it depends on # NOTE: we need to process the entire module graph so that no ID will # be used twice! However, compilation speed does not suffer much from @@ -846,10 +846,10 @@ proc checkDep(fileIdx: int32): TReasonForRecompile = r = nil gMods[fileIdx].rd = r gMods[fileIdx].reason = result # now we know better - -proc handleSymbolFile(module: PSym): PRodReader = + +proc handleSymbolFile(module: PSym): PRodReader = let fileIdx = module.fileIdx - if optSymbolFiles notin gGlobalOptions: + if optSymbolFiles notin gGlobalOptions: module.id = getID() return nil idgen.loadMaxIds(options.gProjectPath / options.gProjectName) @@ -857,7 +857,7 @@ proc handleSymbolFile(module: PSym): PRodReader = discard checkDep(fileIdx) if gMods[fileIdx].reason == rrEmpty: internalError("handleSymbolFile") result = gMods[fileIdx].rd - if result != nil: + if result != nil: module.id = result.moduleID idTablePut(result.syms, module, module) processInterf(result, module) @@ -878,13 +878,13 @@ proc rawLoadStub(s: PSym) = #echo "rs: ", toHex(cast[int](rs.position), int.sizeof * 2), # "\ns: ", toHex(cast[int](s.position), int.sizeof * 2) internalError(rs.info, "loadStub: wrong symbol") - elif rs.id != theId: - internalError(rs.info, "loadStub: wrong ID") + elif rs.id != theId: + internalError(rs.info, "loadStub: wrong ID") #MessageOut('loaded stub: ' + s.name.s); - + proc loadStub*(s: PSym) = ## loads the stub symbol `s`. - + # deactivate the GC here because we do a deep recursion and generate no # garbage when restoring parts of the object graph anyway. # Since we die with internal errors if this fails, no try-finally is @@ -892,7 +892,7 @@ proc loadStub*(s: PSym) = GC_disable() rawLoadStub(s) GC_enable() - + proc getBody*(s: PSym): PNode = ## retrieves the AST's body of `s`. If `s` has been loaded from a rod-file ## it may perform an expensive reload operation. Otherwise it's a simple @@ -908,7 +908,7 @@ proc getBody*(s: PSym): PNode = r.pos = oldPos s.ast.sons[bodyPos] = result s.offset = 0 - + initIdTable(gTypeTable) initStrTable(rodCompilerprocs) @@ -921,16 +921,16 @@ proc writeNode(f: File; n: PNode) = f.write('^') f.write(n.typ.id) case n.kind - of nkCharLit..nkInt64Lit: + of nkCharLit..nkInt64Lit: if n.intVal != 0: f.write('!') f.write(n.intVal) - of nkFloatLit..nkFloat64Lit: - if n.floatVal != 0.0: + of nkFloatLit..nkFloat64Lit: + if n.floatVal != 0.0: f.write('!') f.write($n.floatVal) of nkStrLit..nkTripleStrLit: - if n.strVal != "": + if n.strVal != "": f.write('!') f.write(n.strVal.escape) of nkIdent: @@ -940,7 +940,7 @@ proc writeNode(f: File; n: PNode) = f.write('!') f.write(n.sym.id) else: - for i in countup(0, sonsLen(n) - 1): + for i in countup(0, sonsLen(n) - 1): writeNode(f, n.sons[i]) f.write(")") @@ -966,10 +966,10 @@ proc writeSym(f: File; s: PSym) = if s.magic != mNone: f.write('@') f.write($s.magic) - if s.options != gOptions: + if s.options != gOptions: f.write('!') f.write($s.options) - if s.position != 0: + if s.position != 0: f.write('%') f.write($s.position) if s.offset != -1: @@ -990,12 +990,12 @@ proc writeType(f: File; t: PType) = f.write($t.kind) f.write('+') f.write($t.id) - if t.n != nil: + if t.n != nil: f.writeNode(t.n) if t.flags != {}: f.write('$') f.write($t.flags) - if t.callConv != low(t.callConv): + if t.callConv != low(t.callConv): f.write('?') f.write($t.callConv) if t.owner != nil: @@ -1010,11 +1010,11 @@ proc writeType(f: File; t: PType) = if t.align != 2: f.write('=') f.write($t.align) - for i in countup(0, sonsLen(t) - 1): - if t.sons[i] == nil: + for i in countup(0, sonsLen(t) - 1): + if t.sons[i] == nil: f.write("^()") else: - f.write('^') + f.write('^') f.write($t.sons[i].id) f.write("]\n") @@ -1031,28 +1031,28 @@ proc viewFile(rodfile: string) = case section of "CRC": inc(r.pos) # skip ':' - outf.writeln("CRC:", $decodeVInt(r.s, r.pos)) - of "ID": + outf.writeLine("CRC:", $decodeVInt(r.s, r.pos)) + of "ID": inc(r.pos) # skip ':' r.moduleID = decodeVInt(r.s, r.pos) setId(r.moduleID) - outf.writeln("ID:", $r.moduleID) + outf.writeLine("ID:", $r.moduleID) of "ORIGFILE": inc(r.pos) r.origFile = decodeStr(r.s, r.pos) - outf.writeln("ORIGFILE:", r.origFile) + outf.writeLine("ORIGFILE:", r.origFile) of "OPTIONS": inc(r.pos) # skip ':' r.options = cast[TOptions](int32(decodeVInt(r.s, r.pos))) - outf.writeln("OPTIONS:", $r.options) + outf.writeLine("OPTIONS:", $r.options) of "GOPTIONS": inc(r.pos) # skip ':' let dep = cast[TGlobalOptions](int32(decodeVInt(r.s, r.pos))) - outf.writeln("GOPTIONS:", $dep) + outf.writeLine("GOPTIONS:", $dep) of "CMD": inc(r.pos) # skip ':' let dep = cast[TCommands](int32(decodeVInt(r.s, r.pos))) - outf.writeln("CMD:", $dep) + outf.writeLine("CMD:", $dep) of "DEFINES": inc(r.pos) # skip ':' var d = 0 @@ -1074,18 +1074,18 @@ proc viewFile(rodfile: string) = r.files.add(finalPath.fileInfoIdx) inc(r.pos) # skip #10 inc(r.line) - outf.writeln finalPath + outf.writeLine finalPath if r.s[r.pos] == ')': inc(r.pos) outf.write(")\n") - of "INCLUDES": + of "INCLUDES": inc(r.pos, 2) # skip "(\10" inc(r.line) outf.write("INCLUDES(\n") - while r.s[r.pos] != ')': + while r.s[r.pos] != ')': let w = r.files[decodeVInt(r.s, r.pos)] inc(r.pos) # skip ' ' let inclCrc = decodeVInt(r.s, r.pos) - if r.s[r.pos] == '\x0A': + if r.s[r.pos] == '\x0A': inc(r.pos) inc(r.line) outf.write(w, " ", inclCrc, "\n") @@ -1094,7 +1094,7 @@ proc viewFile(rodfile: string) = of "DEPS": inc(r.pos) # skip ':' outf.write("DEPS:") - while r.s[r.pos] > '\x0A': + while r.s[r.pos] > '\x0A': let v = int32(decodeVInt(r.s, r.pos)) r.modDeps.add(r.files[v]) if r.s[r.pos] == ' ': inc(r.pos) @@ -1126,7 +1126,7 @@ proc viewFile(rodfile: string) = if section == "METHODS": r.methodsIdx = r.pos else: r.convertersIdx = r.pos outf.write(section, ":") - while r.s[r.pos] > '\x0A': + while r.s[r.pos] > '\x0A': let d = decodeVInt(r.s, r.pos) outf.write(" ", $d) if r.s[r.pos] == ' ': inc(r.pos) @@ -1152,7 +1152,7 @@ proc viewFile(rodfile: string) = outf.write("INIT(\n") inc r.pos, 2 r.initIdx = r.pos - while r.s[r.pos] > '\x0A' and r.s[r.pos] != ')': + while r.s[r.pos] > '\x0A' and r.s[r.pos] != ')': let d = decodeVInt(r.s, r.pos) inc(r.pos) # #10 #let p = r.pos diff --git a/compiler/sigmatch.nim b/compiler/sigmatch.nim index f506e3ff5..cd6e1ff9a 100644 --- a/compiler/sigmatch.nim +++ b/compiler/sigmatch.nim @@ -218,12 +218,12 @@ proc cmpCandidates*(a, b: TCandidate): int = result = complexDisambiguation(a.callee, b.callee) proc writeMatches*(c: TCandidate) = - writeln(stdout, "exact matches: " & $c.exactMatches) - writeln(stdout, "generic matches: " & $c.genericMatches) - writeln(stdout, "subtype matches: " & $c.subtypeMatches) - writeln(stdout, "intconv matches: " & $c.intConvMatches) - writeln(stdout, "conv matches: " & $c.convMatches) - writeln(stdout, "inheritance: " & $c.inheritancePenalty) + writeLine(stdout, "exact matches: " & $c.exactMatches) + writeLine(stdout, "generic matches: " & $c.genericMatches) + writeLine(stdout, "subtype matches: " & $c.subtypeMatches) + writeLine(stdout, "intconv matches: " & $c.intConvMatches) + writeLine(stdout, "conv matches: " & $c.convMatches) + writeLine(stdout, "inheritance: " & $c.inheritancePenalty) proc argTypeToString(arg: PNode; prefer: TPreferedDesc): string = if arg.kind in nkSymChoices: From acc8d3746686a1797a9986b0aef78a7053cdd7dc Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Fri, 19 Jun 2015 10:32:29 -0500 Subject: [PATCH 0520/1263] closed the discard in the guide --- contributing.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/contributing.rst b/contributing.rst index 745db2377..8e669c614 100644 --- a/contributing.rst +++ b/contributing.rst @@ -73,6 +73,7 @@ An example for a test: discard """ errormsg: "type mismatch: got (PTest)" + """ type PTest = ref object From 1cdbd6b0a5865ba3ecb685c82338df1482aa118b Mon Sep 17 00:00:00 2001 From: patrick dw Date: Fri, 19 Jun 2015 18:50:01 -0500 Subject: [PATCH 0521/1263] reworked deprecation to retain old procs --- lib/pure/streams.nim | 7 +++++-- lib/system.nim | 4 ++++ lib/system/sysio.nim | 6 +++++- 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/lib/pure/streams.nim b/lib/pure/streams.nim index 15022fe0d..8aa8d35d8 100644 --- a/lib/pure/streams.nim +++ b/lib/pure/streams.nim @@ -117,14 +117,17 @@ proc write*(s: Stream, x: string) = ## terminating zero is written. writeData(s, cstring(x), x.len) +proc writeLn*(s: Stream, args: varargs[string, `$`]) {.deprecated.} = + ## **Deprecated since version 0.11.4:** Use **writeLine** instead. + for str in args: write(s, str) + write(s, "\n") + proc writeLine*(s: Stream, args: varargs[string, `$`]) = ## writes one or more strings to the the stream `s` followed ## by a new line. No length field or terminating zero is written. for str in args: write(s, str) write(s, "\n") -{.deprecated: [writeln:writeLine].} - proc read[T](s: Stream, result: var T) = ## generic read procedure. Reads `result` from the stream `s`. if readData(s, addr(result), sizeof(T)) != sizeof(T): diff --git a/lib/system.nim b/lib/system.nim index 9ffc51e80..34531eb46 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -2526,6 +2526,10 @@ when not defined(JS): #and not defined(NimrodVM): ## Returns ``false`` if the end of the file has been reached, ``true`` ## otherwise. If ``false`` is returned `line` contains no new data. + proc writeLn*[Ty](f: File, x: varargs[Ty, `$`]) {.inline, + tags: [WriteIOEffect], benign, deprecated.} + ## **Deprecated since version 0.11.4:** Use **writeLine** instead. + proc writeLine*[Ty](f: File, x: varargs[Ty, `$`]) {.inline, tags: [WriteIOEffect], benign.} ## writes the values `x` to `f` and then writes "\n". diff --git a/lib/system/sysio.nim b/lib/system/sysio.nim index e84c7ac3a..5464ee126 100644 --- a/lib/system/sysio.nim +++ b/lib/system/sysio.nim @@ -208,10 +208,14 @@ proc endOfFile(f: File): bool = ungetc(c, f) return c < 0'i32 +proc writeLn[Ty](f: File, x: varargs[Ty, `$`]) = + for i in items(x): write(f, i) + write(f, "\n") + proc writeLine[Ty](f: File, x: varargs[Ty, `$`]) = for i in items(x): write(f, i) write(f, "\n") -{.deprecated: [writeln:writeLine].} + proc rawEcho(x: string) {.inline, compilerproc.} = write(stdout, x) proc rawEchoNL() {.inline, compilerproc.} = write(stdout, "\n") From 25a5eaf7225c2a66d46949605913305bbfdadee6 Mon Sep 17 00:00:00 2001 From: Dominik Picheta Date: Sat, 20 Jun 2015 11:37:29 +0100 Subject: [PATCH 0522/1263] Added test file for #2813. --- tests/stdlib/thtmlparser2813.nim | 45 ++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 tests/stdlib/thtmlparser2813.nim diff --git a/tests/stdlib/thtmlparser2813.nim b/tests/stdlib/thtmlparser2813.nim new file mode 100644 index 000000000..4b04bc3f0 --- /dev/null +++ b/tests/stdlib/thtmlparser2813.nim @@ -0,0 +1,45 @@ +discard """ + output: "@[]" +""" +import htmlparser +import xmltree +from streams import newStringStream + +const + html = """ + + + Test + + + + + + + + + A + B + C + + + + +
    A
    B
    A
    + + + """ +var errors: seq[string] = @[] + +let tree = parseHtml(newStringStream(html), "test.html", errors) + +echo errors # Errors: expected,... + +var len = tree.findAll("tr").len # len = 6 + +var rows: seq[XmlNode] = @[] +for n in tree.findAll("table"): + n.findAll("tr", rows) # len = 2 + break + +assert tree.findAll("tr").len == rows.len From a31c36e98f7caa330160b55c21d48c06cce03a62 Mon Sep 17 00:00:00 2001 From: transfuturist Date: Sat, 20 Jun 2015 12:21:16 -0700 Subject: [PATCH 0523/1263] Undeprecate children --- lib/core/macros.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/core/macros.nim b/lib/core/macros.nim index 0bfdffc5d..3fd2c8502 100644 --- a/lib/core/macros.nim +++ b/lib/core/macros.nim @@ -713,7 +713,7 @@ iterator items*(n: NimNode): NimNode {.inline.} = for i in 0 .. high(n): yield n[i] -{.deprecated: [children: items].} +iterator children*(n: NimNode): NimNode {.inline.} = items template findChild*(n: NimNode; cond: expr): NimNode {. immediate, dirty.} = From 87f65f5e72148d6b44e09cfd4834c9366bfacd4c Mon Sep 17 00:00:00 2001 From: Araq Date: Sat, 20 Jun 2015 23:24:21 +0200 Subject: [PATCH 0524/1263] preparations for more Nimble packages; clear licensing; fixes #2949 --- doc/lib.txt | 66 +- lib/impure/zipfiles.nim | 183 - lib/pure/algorithm.nim | 2 +- lib/windows/mmsystem.nim | 2650 -- lib/windows/nb30.nim | 236 - lib/windows/psapi.nim | 202 - lib/windows/shellapi.nim | 863 - lib/windows/shfolder.nim | 93 - lib/windows/windows.nim | 23662 ---------------- lib/wrappers/claro.nim | 2748 -- lib/wrappers/expat.nim | 899 - lib/wrappers/iup.nim | 10 +- lib/wrappers/joyent_http_parser.nim | 11 +- lib/wrappers/libcurl.nim | 512 - lib/wrappers/libffi/common/ffi.h | 331 - lib/wrappers/libffi/common/ffi_common.h | 77 - lib/wrappers/libffi/common/fficonfig.h | 96 - lib/wrappers/libffi/common/ffitarget.h | 150 - lib/wrappers/libffi/common/malloc_closure.c | 110 - lib/wrappers/libffi/common/raw_api.c | 254 - lib/wrappers/libffi/gcc/closures.c | 627 - lib/wrappers/libffi/gcc/ffi.c | 841 - lib/wrappers/libffi/gcc/ffi64.c | 673 - lib/wrappers/libffi/gcc/prep_cif.c | 237 - lib/wrappers/libffi/gcc/types.c | 77 - lib/wrappers/libffi/gcc/win32_asm.asm | 759 - lib/wrappers/libffi/gcc/win32_asm.s | 736 - lib/wrappers/libffi/gcc/win64_asm.asm | 467 - lib/wrappers/libffi/gcc/win64_asm.s | 227 - lib/wrappers/libffi/libffi.nim | 176 - lib/wrappers/libffi/msvc/ffi.c | 457 - lib/wrappers/libffi/msvc/prep_cif.c | 175 - lib/wrappers/libffi/msvc/types.c | 104 - lib/wrappers/libffi/msvc/win32.c | 162 - lib/wrappers/libffi/msvc/win32_asm.asm | 470 - lib/wrappers/libffi/msvc/win64_asm.asm | 156 - lib/wrappers/libuv.nim | 11 +- lib/wrappers/odbcsql.nim | 358 +- lib/wrappers/openssl.nim | 148 +- lib/wrappers/pcre.nim | 41 +- lib/wrappers/pdcurses.nim | 1293 +- lib/wrappers/postgres.nim | 231 +- lib/wrappers/readline/history.nim | 279 - lib/wrappers/readline/readline.nim | 1209 - lib/wrappers/readline/rltypedefs.nim | 79 - lib/wrappers/readline/tweaked/history.h | 257 - lib/wrappers/readline/tweaked/readline.h | 956 - lib/wrappers/readline/tweaked/rltypedefs.h | 78 - lib/wrappers/readline/tweaked/tilde.h | 77 - lib/wrappers/sdl/sdl.nim | 2579 -- lib/wrappers/sdl/sdl_gfx.nim | 452 - lib/wrappers/sdl/sdl_image.nim | 243 - lib/wrappers/sdl/sdl_mixer.nim | 489 - lib/wrappers/sdl/sdl_mixer_nosmpeg.nim | 357 - lib/wrappers/sdl/sdl_net.nim | 428 - lib/wrappers/sdl/sdl_ttf.nim | 338 - lib/wrappers/sdl/smpeg.nim | 335 - lib/wrappers/sphinx.nim | 263 - lib/wrappers/tre.nim | 188 - lib/wrappers/zip/libzip.nim | 251 - lib/wrappers/zip/libzip_all.c | 4189 --- lib/wrappers/zip/zlib.nim | 312 - lib/wrappers/zip/zzip.nim | 176 - tests/generics/tcan_alias_generic.nim | 3 +- .../tcan_alias_specialised_generic.nim | 3 +- tests/generics/tcan_inherit_generic.nim | 3 +- tests/generics/tcan_specialise_generic.nim | 3 +- tests/generics/tspecialised_is_equivalent.nim | 1 - tools/niminst/niminst.nim | 2 +- web/website.ini | 15 +- 70 files changed, 1061 insertions(+), 54085 deletions(-) delete mode 100644 lib/impure/zipfiles.nim delete mode 100644 lib/windows/mmsystem.nim delete mode 100644 lib/windows/nb30.nim delete mode 100644 lib/windows/psapi.nim delete mode 100644 lib/windows/shellapi.nim delete mode 100644 lib/windows/shfolder.nim delete mode 100644 lib/windows/windows.nim delete mode 100644 lib/wrappers/claro.nim delete mode 100644 lib/wrappers/expat.nim delete mode 100644 lib/wrappers/libcurl.nim delete mode 100644 lib/wrappers/libffi/common/ffi.h delete mode 100644 lib/wrappers/libffi/common/ffi_common.h delete mode 100644 lib/wrappers/libffi/common/fficonfig.h delete mode 100644 lib/wrappers/libffi/common/ffitarget.h delete mode 100644 lib/wrappers/libffi/common/malloc_closure.c delete mode 100644 lib/wrappers/libffi/common/raw_api.c delete mode 100644 lib/wrappers/libffi/gcc/closures.c delete mode 100644 lib/wrappers/libffi/gcc/ffi.c delete mode 100644 lib/wrappers/libffi/gcc/ffi64.c delete mode 100644 lib/wrappers/libffi/gcc/prep_cif.c delete mode 100644 lib/wrappers/libffi/gcc/types.c delete mode 100644 lib/wrappers/libffi/gcc/win32_asm.asm delete mode 100644 lib/wrappers/libffi/gcc/win32_asm.s delete mode 100644 lib/wrappers/libffi/gcc/win64_asm.asm delete mode 100644 lib/wrappers/libffi/gcc/win64_asm.s delete mode 100644 lib/wrappers/libffi/libffi.nim delete mode 100644 lib/wrappers/libffi/msvc/ffi.c delete mode 100644 lib/wrappers/libffi/msvc/prep_cif.c delete mode 100644 lib/wrappers/libffi/msvc/types.c delete mode 100644 lib/wrappers/libffi/msvc/win32.c delete mode 100644 lib/wrappers/libffi/msvc/win32_asm.asm delete mode 100644 lib/wrappers/libffi/msvc/win64_asm.asm delete mode 100644 lib/wrappers/readline/history.nim delete mode 100644 lib/wrappers/readline/readline.nim delete mode 100644 lib/wrappers/readline/rltypedefs.nim delete mode 100644 lib/wrappers/readline/tweaked/history.h delete mode 100644 lib/wrappers/readline/tweaked/readline.h delete mode 100644 lib/wrappers/readline/tweaked/rltypedefs.h delete mode 100644 lib/wrappers/readline/tweaked/tilde.h delete mode 100644 lib/wrappers/sdl/sdl.nim delete mode 100644 lib/wrappers/sdl/sdl_gfx.nim delete mode 100644 lib/wrappers/sdl/sdl_image.nim delete mode 100644 lib/wrappers/sdl/sdl_mixer.nim delete mode 100644 lib/wrappers/sdl/sdl_mixer_nosmpeg.nim delete mode 100644 lib/wrappers/sdl/sdl_net.nim delete mode 100644 lib/wrappers/sdl/sdl_ttf.nim delete mode 100644 lib/wrappers/sdl/smpeg.nim delete mode 100644 lib/wrappers/sphinx.nim delete mode 100644 lib/wrappers/tre.nim delete mode 100644 lib/wrappers/zip/libzip.nim delete mode 100644 lib/wrappers/zip/libzip_all.c delete mode 100644 lib/wrappers/zip/zlib.nim delete mode 100644 lib/wrappers/zip/zzip.nim diff --git a/doc/lib.txt b/doc/lib.txt index fd5218b0a..14a13c0d2 100644 --- a/doc/lib.txt +++ b/doc/lib.txt @@ -394,13 +394,6 @@ Miscellaneous This module implements new experimental features. Currently the syntax sugar for anonymous procedures. -Database support ----------------- - -* `redis `_ - This module implements a redis client. It allows you to connect to a - redis-server instance, send commands and receive replies. - Modules for JS backend --------------------------- @@ -439,27 +432,10 @@ Database support Other ----- -* `graphics `_ - This module implements graphical output for Nim; the current - implementation uses SDL but the interface is meant to support multiple - backends some day. - -* `dialogs `_ - This module implements portable dialogs for Nim; the implementation - builds on the GTK interface. On Windows, native dialogs are shown if - appropriate. - -* `zipfiles `_ - This module implements a zip archive creator/reader/modifier. - * `ssl `_ This module provides an easy to use sockets-style Nim interface to the OpenSSL library. -* `rdstdin `_ - This module contains code for reading from `stdin`:idx:. On UNIX the GNU - readline library is wrapped and set up. - Wrappers ======== @@ -470,20 +446,8 @@ not contained in the distribution. You can then find them on the website. Windows specific ---------------- -* `windows `_ - Contains a wrapper for the Win32 API. * `winlean `_ Contains a wrapper for a small subset of the Win32 API. -* `shellapi `_ - Contains a wrapper for the ``shellapi.h`` header. -* `shfolder `_ - Contains a wrapper for the ``shfolder.h`` header. -* `mmsystem `_ - Contains a wrapper for the ``mmsystem.h`` header. -* `psapi `_ - Contains a wrapper for the ``psapi.h`` header. -* `nb30 `_ - This module contains the definitions for portable NetBIOS 3.0 support. UNIX specific @@ -491,12 +455,6 @@ UNIX specific * `posix `_ Contains a wrapper for the POSIX standard. -* `readline `_ - Part of the wrapper for the GNU readline library. -* `history `_ - Part of the wrapper for the GNU readline library. -* `rltypedefs `_ - Part of the wrapper for the GNU readline library. Regular expressions @@ -504,8 +462,6 @@ Regular expressions * `pcre `_ Wrapper for the PCRE library. -* `tre `_ - Wrapper for the TRE library. GUI libraries @@ -526,15 +482,6 @@ Database support Contains a wrapper for SQLite 3 API. * `odbcsql `_ interface to the ODBC driver. -* `sphinx `_ - Nim wrapper for ``sphinx``. - - -XML Processing --------------- - -* `expat `_ - Wrapper of the expat XML parser. Network Programming and Internet Protocols @@ -553,16 +500,6 @@ Network Programming and Internet Protocols Wrapper for OpenSSL. -Data Compression and Archiving ------------------------------- - -* `zlib `_ - Wrapper for the zlib library. - -* `libzip `_ - Interface to the `lib zip `_ library by - Dieter Baron and Thomas Klausner. - Scientific computing -------------------- @@ -570,8 +507,9 @@ Scientific computing * `libsvm `_ Low level wrapper for `lib svm `_. + Nimble -==================== +====== Nimble is a package manager for the Nim programming language. For instructions on how to install Nimble packages see diff --git a/lib/impure/zipfiles.nim b/lib/impure/zipfiles.nim deleted file mode 100644 index d8903f5c1..000000000 --- a/lib/impure/zipfiles.nim +++ /dev/null @@ -1,183 +0,0 @@ -# -# -# Nim's Runtime Library -# (c) Copyright 2012 Andreas Rumpf -# -# See the file "copying.txt", included in this -# distribution, for details about the copyright. -# - -## This module implements a zip archive creator/reader/modifier. - -import - streams, libzip, times, os, strutils - -type - ZipArchive* = object of RootObj ## represents a zip archive - mode: FileMode - w: PZip -{.deprecated: [TZipArchive: ZipArchive].} - -proc zipError(z: var ZipArchive) = - var e: ref IOError - new(e) - e.msg = $zip_strerror(z.w) - raise e - -proc open*(z: var ZipArchive, filename: string, mode: FileMode = fmRead): bool = - ## Opens a zip file for reading, writing or appending. All file modes are - ## supported. Returns true iff successful, false otherwise. - var err, flags: int32 - case mode - of fmRead, fmReadWriteExisting, fmAppend: flags = 0 - of fmWrite: - if existsFile(filename): removeFile(filename) - flags = ZIP_CREATE or ZIP_EXCL - of fmReadWrite: flags = ZIP_CREATE - z.w = zip_open(filename, flags, addr(err)) - z.mode = mode - result = z.w != nil - -proc close*(z: var ZipArchive) = - ## Closes a zip file. - zip_close(z.w) - -proc createDir*(z: var ZipArchive, dir: string) = - ## Creates a directory within the `z` archive. This does not fail if the - ## directory already exists. Note that for adding a file like - ## ``"path1/path2/filename"`` it is not necessary - ## to create the ``"path/path2"`` subdirectories - it will be done - ## automatically by ``addFile``. - assert(z.mode != fmRead) - discard zip_add_dir(z.w, dir) - zip_error_clear(z.w) - -proc addFile*(z: var ZipArchive, dest, src: string) = - ## Adds the file `src` to the archive `z` with the name `dest`. `dest` - ## may contain a path that will be created. - assert(z.mode != fmRead) - if not fileExists(src): - raise newException(IOError, "File '" & src & "' does not exist") - var zipsrc = zip_source_file(z.w, src, 0, -1) - if zipsrc == nil: - #echo("Dest: " & dest) - #echo("Src: " & src) - zipError(z) - if zip_add(z.w, dest, zipsrc) < 0'i32: - zip_source_free(zipsrc) - zipError(z) - -proc addFile*(z: var ZipArchive, file: string) = - ## A shortcut for ``addFile(z, file, file)``, i.e. the name of the source is - ## the name of the destination. - addFile(z, file, file) - -proc mySourceCallback(state, data: pointer, len: int, - cmd: ZipSourceCmd): int {.cdecl.} = - var src = cast[Stream](state) - case cmd - of ZIP_SOURCE_OPEN: - if src.setPositionImpl != nil: setPosition(src, 0) # reset - of ZIP_SOURCE_READ: - result = readData(src, data, len) - of ZIP_SOURCE_CLOSE: close(src) - of ZIP_SOURCE_STAT: - var stat = cast[PZipStat](data) - zip_stat_init(stat) - stat.size = high(int32)-1 # we don't know the size - stat.mtime = getTime() - result = sizeof(ZipStat) - of ZIP_SOURCE_ERROR: - var err = cast[ptr array[0..1, cint]](data) - err[0] = ZIP_ER_INTERNAL - err[1] = 0 - result = 2*sizeof(cint) - of constZIP_SOURCE_FREE: GC_unref(src) - else: assert(false) - -proc addFile*(z: var ZipArchive, dest: string, src: Stream) = - ## Adds a file named with `dest` to the archive `z`. `dest` - ## may contain a path. The file's content is read from the `src` stream. - assert(z.mode != fmRead) - GC_ref(src) - var zipsrc = zip_source_function(z.w, mySourceCallback, cast[pointer](src)) - if zipsrc == nil: zipError(z) - if zip_add(z.w, dest, zipsrc) < 0'i32: - zip_source_free(zipsrc) - zipError(z) - -# -------------- zip file stream --------------------------------------------- - -type - TZipFileStream = object of StreamObj - f: PZipFile - atEnd: bool - - PZipFileStream* = - ref TZipFileStream ## a reader stream of a file within a zip archive - -proc fsClose(s: Stream) = zip_fclose(PZipFileStream(s).f) -proc fsAtEnd(s: Stream): bool = PZipFileStream(s).atEnd -proc fsReadData(s: Stream, buffer: pointer, bufLen: int): int = - result = zip_fread(PZipFileStream(s).f, buffer, bufLen) - if result == 0: - PZipFileStream(s).atEnd = true - -proc newZipFileStream(f: PZipFile): PZipFileStream = - new(result) - result.f = f - result.atEnd = false - result.closeImpl = fsClose - result.readDataImpl = fsReadData - result.atEndImpl = fsAtEnd - # other methods are nil! - -# ---------------------------------------------------------------------------- - -proc getStream*(z: var ZipArchive, filename: string): PZipFileStream = - ## returns a stream that can be used to read the file named `filename` - ## from the archive `z`. Returns nil in case of an error. - ## The returned stream does not support the `setPosition`, `getPosition`, - ## `writeData` or `atEnd` methods. - var x = zip_fopen(z.w, filename, 0'i32) - if x != nil: result = newZipFileStream(x) - -iterator walkFiles*(z: var ZipArchive): string = - ## walks over all files in the archive `z` and returns the filename - ## (including the path). - var i = 0'i32 - var num = zip_get_num_files(z.w) - while i < num: - yield $zip_get_name(z.w, i, 0'i32) - inc(i) - - -proc extractFile*(z: var ZipArchive, srcFile: string, dest: Stream) = - ## extracts a file from the zip archive `z` to the destination stream. - var strm = getStream(z, srcFile) - while true: - if not strm.atEnd: - dest.write(strm.readStr(1)) - else: break - dest.flush() - strm.close() - -proc extractFile*(z: var ZipArchive, srcFile: string, dest: string) = - ## extracts a file from the zip archive `z` to the destination filename. - var file = newFileStream(dest, fmWrite) - extractFile(z, srcFile, file) - file.close() - -proc extractAll*(z: var ZipArchive, dest: string) = - ## extracts all files from archive `z` to the destination directory. - for file in walkFiles(z): - if file.endsWith("/"): - createDir(dest / file) - else: - extractFile(z, file, dest / file) - -when not defined(testing) and isMainModule: - var zip: ZipArchive - if not zip.open("nim-0.11.0.zip"): - raise newException(IOError, "opening zip failed") - zip.extractAll("test") diff --git a/lib/pure/algorithm.nim b/lib/pure/algorithm.nim index ac18ae420..e087b5ac9 100644 --- a/lib/pure/algorithm.nim +++ b/lib/pure/algorithm.nim @@ -355,7 +355,7 @@ when isMainModule: var srt1 = [1,2,3,4,4,4,4,5] var srt2 = ["iello","hello"] var srt3 = [1.0,1.0,1.0] - var srt4 = [] + var srt4: seq[int] = @[] assert srt1.isSorted(cmp) == true assert srt2.isSorted(cmp) == false assert srt3.isSorted(cmp) == true diff --git a/lib/windows/mmsystem.nim b/lib/windows/mmsystem.nim deleted file mode 100644 index 9bc6a873f..000000000 --- a/lib/windows/mmsystem.nim +++ /dev/null @@ -1,2650 +0,0 @@ -# -# -# Nim's Runtime Library -# (c) Copyright 2006 Andreas Rumpf -# -# See the file "copying.txt", included in this -# distribution, for details about the copyright. -# - -#********************************* -#******************************* -# Generated by c2pas32 v0.9b -# Fixed by P.V.Ozerski -# (c) 2001 Oleg Bulychov -# Original C header file -# Gladiators Software -# (created at Dec-03-1998) -# http://www.astonshell.com/ -# from LCC-win32 is used -#********************************* -# LCC-win32 (c) Jacob Navia -#******************************* - -{.deadCodeElim: on.} - -import - windows - -type - MMRESULT* = uint32 - MMVERSION* = uint32 - HWAVEOUT* = Handle - LPHWAVEOUT* = ptr HWAVEOUT - HWAVEIN* = Handle - LPHWAVEIN* = ptr HWAVEOUT - HWAVE* = Handle - LPHWAVE* = ptr Handle - LPUINT* = ptr uint32 - -const - MAXPNAMELEN* = 32 - MAXERRORLENGTH* = 256 - MAX_JOYSTICKOEMVXDNAME* = 260 - MM_MIDI_MAPPER* = 1 - MM_WAVE_MAPPER* = 2 - MM_SNDBLST_MIDIOUT* = 3 - MM_SNDBLST_MIDIIN* = 4 - MM_SNDBLST_SYNTH* = 5 - MM_SNDBLST_WAVEOUT* = 6 - MM_SNDBLST_WAVEIN* = 7 - MM_ADLIB* = 9 - MM_MPU401_MIDIOUT* = 10 - MM_MPU401_MIDIIN* = 11 - MM_PC_JOYSTICK* = 12 - TIME_MS* = 1 - TIME_SAMPLES* = 2 - TIME_BYTES* = 4 - TIME_SMPTE* = 8 - TIME_MIDI* = 16 - TIME_TICKS* = 32 - MM_MCINOTIFY* = 0x000003B9 - MM_WOM_OPEN* = 0x000003BB - MM_WOM_CLOSE* = 0x000003BC - MM_WOM_DONE* = 0x000003BD - MM_WIM_OPEN* = 0x000003BE - MM_WIM_CLOSE* = 0x000003BF - MM_WIM_DATA* = 0x000003C0 - MM_MIM_OPEN* = 0x000003C1 - MM_MIM_CLOSE* = 0x000003C2 - MM_MIM_DATA* = 0x000003C3 - MM_MIM_LONGDATA* = 0x000003C4 - MM_MIM_ERROR* = 0x000003C5 - MM_MIM_LONGERROR* = 0x000003C6 - MM_MOM_OPEN* = 0x000003C7 - MM_MOM_CLOSE* = 0x000003C8 - MM_MOM_DONE* = 0x000003C9 - MM_DRVM_OPEN* = 0x000003D0 - MM_DRVM_CLOSE* = 0x000003D1 - MM_DRVM_DATA* = 0x000003D2 - MM_DRVM_ERROR* = 0x000003D3 - MM_STREAM_OPEN* = 0x000003D4 - MM_STREAM_CLOSE* = 0x000003D5 - MM_STREAM_DONE* = 0x000003D6 - MM_STREAM_ERROR* = 0x000003D7 - MM_MOM_POSITIONCB* = 0x000003CA - MM_MCISIGNAL* = 0x000003CB - WAVE_INVALIDFORMAT* = 0 - WAVE_FORMAT_1M08* = 1 - WAVE_FORMAT_1S08* = 2 - WAVE_FORMAT_1M16* = 4 - WAVE_FORMAT_1S16* = 8 - WAVE_FORMAT_2M08* = 16 - WAVE_FORMAT_2S08* = 32 - WAVE_FORMAT_2M16* = 64 - WAVE_FORMAT_2S16* = 128 - WAVE_FORMAT_4M08* = 256 - WAVE_FORMAT_4S08* = 512 - WAVE_FORMAT_4M16* = 0x00000400 - WAVE_FORMAT_4S16* = 0x00000800 - MM_MIM_MOREDATA* = 0x000003CC - MM_MIXM_LINE_CHANGE* = 0x000003D0 - MM_MIXM_CONTROL_CHANGE* = 0x000003D1 - MMSYSERR_BASE* = 0 - WAVERR_BASE* = 32 - MIDIERR_BASE* = 64 - TIMERR_BASE* = 96 - JOYERR_BASE* = 160 - MCIERR_BASE* = 256 - MIXERR_BASE* = 1024 - MCI_STRING_OFFSET* = 512 - MCI_VD_OFFSET* = 1024 - MCI_CD_OFFSET* = 1088 - MCI_WAVE_OFFSET* = 1152 - MCI_SEQ_OFFSET* = 1216 - MMSYSERR_NOERROR* = 0 - MMSYSERR_ERROR* = (MMSYSERR_BASE + 1) - MMSYSERR_BADDEVICEID* = (MMSYSERR_BASE + 2) - MMSYSERR_NOTENABLED* = (MMSYSERR_BASE + 3) - MMSYSERR_ALLOCATED* = (MMSYSERR_BASE + 4) - MMSYSERR_INVALHANDLE* = (MMSYSERR_BASE + 5) - MMSYSERR_NODRIVER* = (MMSYSERR_BASE + 6) - MMSYSERR_NOMEM* = (MMSYSERR_BASE + 7) - MMSYSERR_NOTSUPPORTED* = (MMSYSERR_BASE + 8) - MMSYSERR_BADERRNUM* = (MMSYSERR_BASE + 9) - MMSYSERR_INVALFLAG* = (MMSYSERR_BASE + 10) - MMSYSERR_INVALPARAM* = (MMSYSERR_BASE + 11) - MMSYSERR_HANDLEBUSY* = (MMSYSERR_BASE + 12) - MMSYSERR_INVALIDALIAS* = (MMSYSERR_BASE + 13) - MMSYSERR_BADDB* = (MMSYSERR_BASE + 14) - MMSYSERR_KEYNOTFOUND* = (MMSYSERR_BASE + 15) - MMSYSERR_READERROR* = (MMSYSERR_BASE + 16) - MMSYSERR_WRITEERROR* = (MMSYSERR_BASE + 17) - MMSYSERR_DELETEERROR* = (MMSYSERR_BASE + 18) - MMSYSERR_VALNOTFOUND* = (MMSYSERR_BASE + 19) - MMSYSERR_NODRIVERCB* = (MMSYSERR_BASE + 20) - MMSYSERR_LASTERROR* = (MMSYSERR_BASE + 20) - MM_JOY1MOVE* = 0x000003A0 - MM_JOY2MOVE* = 0x000003A1 - MM_JOY1ZMOVE* = 0x000003A2 - MM_JOY2ZMOVE* = 0x000003A3 - MM_JOY1BUTTONDOWN* = 0x000003B5 - MM_JOY2BUTTONDOWN* = 0x000003B6 - MM_JOY1BUTTONUP* = 0x000003B7 - MM_JOY2BUTTONUP* = 0x000003B8 - CALLBACK_TYPEMASK* = 0x00070000 - CALLBACK_NULL* = 0 - CALLBACK_EVENT* = 0x00050000 - CALLBACK_WINDOW* = 0x00010000 - CALLBACK_TASK* = 0x00020000 - CALLBACK_THREAD* = CALLBACK_TASK - CALLBACK_FUNCTION* = 0x00030000 - -type - HDRVR* = Handle - -const - DRV_LOAD* = 1 - DRV_ENABLE* = 2 - DRV_OPEN* = 0x00000003 - DRV_CLOSE* = 4 - DRV_DISABLE* = 0x00000005 - DRV_FREE* = 0x00000006 - DRV_CONFIGURE* = 0x00000007 - DRV_QUERYCONFIGURE* = 8 - DRV_INSTALL* = 0x00000009 - DRV_REMOVE* = 0x0000000A - DRV_EXITSESSION* = 0x0000000B - DRV_POWER* = 0x0000000F - DRV_RESERVED* = 0x00000800 - DRV_USER* = 0x00004000 - DRVCNF_CANCEL* = 0 - DRVCNF_OK* = 1 - DRVCNF_RESTART* = 2 - DRV_CANCEL* = DRVCNF_CANCEL - DRV_OK* = DRVCNF_OK - DRV_RESTART* = DRVCNF_RESTART - DRV_MCI_FIRST* = DRV_RESERVED - DRV_MCI_LAST* = (DRV_RESERVED + 0x00000FFF) - -type - PDRVCALLBACK* = proc (hdrvr: Handle, uMsg: uint32, dwUser, dw1, dw2: DWORD){. - stdcall.} - -proc sndPlaySoundA*(Name: LPCSTR, flags: uint32): bool{.stdcall, - dynlib: "winmm.dll", importc: "sndPlaySoundA".} -proc sndPlaySoundW*(Name: LPCWSTR, flags: uint32): bool{.stdcall, - dynlib: "winmm.dll", importc: "sndPlaySoundW".} -when defined(winUNICODE): - proc sndPlaySound*(Name: cstring, flags: uint32): bool{.stdcall, - dynlib: "winmm.dll", importc: "sndPlaySoundW".} -else: - proc sndPlaySound*(Name: cstring, flags: uint32): bool{.stdcall, - dynlib: "winmm.dll", importc: "sndPlaySoundA".} -const - SND_NODEFAULT* = 2 - SND_MEMORY* = 4 - SND_LOOP* = 8 - SND_NOSTOP* = 16 - SND_SYNC* = 0 - SND_ASYNC* = 1 - SND_PURGE* = 64 - SND_APPLICATION* = 128 - SND_ALIAS_START* = 0 - SND_ALIAS_SYSTEMHAND* = 18515 - SND_ALIAS_SYSTEMEXCLAMATION* = 8531 - SND_ALIAS_SYSTEMASTERISK* = 10835 - SND_ALIAS_SYSTEMQUESTION* = 16211 - SND_ALIAS_SYSTEMDEFAULT* = 17491 - SND_ALIAS_SYSTEMEXIT* = 17747 - SND_ALIAS_SYSTEMSTART* = 21331 - SND_ALIAS_SYSTEMWELCOME* = 22355 - SND_NOWAIT* = 0x00002000 - SND_ALIAS* = 0x00010000 - SND_ALIAS_ID* = 0x00110000 - SND_FILENAME* = 0x00020000 - SND_RESOURCE* = 0x00040004 - WAVERR_BADFORMAT* = (WAVERR_BASE + 0) - WAVERR_STILLPLAYING* = (WAVERR_BASE + 1) - WAVERR_UNPREPARED* = (WAVERR_BASE + 2) - WAVERR_SYNC* = (WAVERR_BASE + 3) - WAVERR_LASTERROR* = (WAVERR_BASE + 3) - WOM_OPEN* = MM_WOM_OPEN - WOM_CLOSE* = MM_WOM_CLOSE - WOM_DONE* = MM_WOM_DONE - WIM_OPEN* = MM_WIM_OPEN - WIM_CLOSE* = MM_WIM_CLOSE - WIM_DATA* = MM_WIM_DATA - WAVE_MAPPER* = uint32(- 1) - WAVE_FORMAT_QUERY* = 1 - WAVE_ALLOWSYNC* = 2 - WAVE_MAPPED* = 4 - WAVE_FORMAT_DIRECT* = 8 - WAVE_FORMAT_DIRECT_QUERY* = (WAVE_FORMAT_QUERY or WAVE_FORMAT_DIRECT) - MIM_OPEN* = MM_MIM_OPEN - MIM_CLOSE* = MM_MIM_CLOSE - MIM_DATA* = MM_MIM_DATA - MIM_LONGDATA* = MM_MIM_LONGDATA - MIM_ERROR* = MM_MIM_ERROR - MIM_LONGERROR* = MM_MIM_LONGERROR - MOM_OPEN* = MM_MOM_OPEN - MOM_CLOSE* = MM_MOM_CLOSE - MOM_DONE* = MM_MOM_DONE - MIM_MOREDATA* = MM_MIM_MOREDATA - MOM_POSITIONCB* = MM_MOM_POSITIONCB - MIDIMAPPER* = uint32(- 1) - MIDI_IO_STATUS* = 32 - MIDI_CACHE_ALL* = 1 - MIDI_CACHE_BESTFIT* = 2 - MIDI_CACHE_QUERY* = 3 - MIDI_UNCACHE* = 4 - WHDR_DONE* = 1 - WHDR_PREPARED* = 2 - WHDR_BEGINLOOP* = 0x00000004 - WHDR_ENDLOOP* = 0x00000008 - WHDR_INQUEUE* = 0x00000010 - MOD_MIDIPORT* = 1 - MOD_SYNTH* = 2 - MOD_SQSYNTH* = 3 - MOD_FMSYNTH* = 4 - MOD_MAPPER* = 5 - MIDICAPS_VOLUME* = 1 - MIDICAPS_LRVOLUME* = 2 - MIDICAPS_CACHE* = 4 - MIDICAPS_STREAM* = 8 - MHDR_DONE* = 1 - MHDR_PREPARED* = 2 - MHDR_INQUEUE* = 0x00000004 - MHDR_ISSTRM* = 0x00000008 - MEVT_F_SHORT* = 0 - MEVT_F_LONG* = 0x80000000 - MEVT_F_CALLBACK* = 0x40000000 - -proc MEVT_EVENTTYPE*(x: int8): int8 -proc MEVT_EVENTPARM*(x: DWORD): DWORD -const - MEVT_SHORTMSG* = 0 - MEVT_TEMPO* = 0x00000001 - MEVT_NOP* = 0x00000002 - MEVT_LONGMSG* = 0x00000080 - MEVT_COMMENT* = 0x00000082 - MEVT_VERSION* = 0x00000084 - MIDISTRM_ERROR* = - 2 - MIDIPROP_SET* = 0x80000000 - MIDIPROP_GET* = 0x40000000 - MIDIPROP_TIMEDIV* = 1 - MIDIPROP_TEMPO* = 2 - MIXERLINE_LINEF_ACTIVE* = 1 - MIXERLINE_LINEF_DISCONNECTED* = 0x00008000 - MIXERLINE_LINEF_SOURCE* = 0x80000000 - MIXERLINE_COMPONENTTYPE_DST_FIRST* = 0 - MIXERLINE_COMPONENTTYPE_DST_UNDEFINED* = (MIXERLINE_COMPONENTTYPE_DST_FIRST) - MIXERLINE_COMPONENTTYPE_DST_DIGITAL* = (MIXERLINE_COMPONENTTYPE_DST_FIRST + 1) - MIXERLINE_COMPONENTTYPE_DST_LINE* = (MIXERLINE_COMPONENTTYPE_DST_FIRST + 2) - MIXERLINE_COMPONENTTYPE_DST_MONITOR* = (MIXERLINE_COMPONENTTYPE_DST_FIRST + 3) - MIXERLINE_COMPONENTTYPE_DST_SPEAKERS* = (MIXERLINE_COMPONENTTYPE_DST_FIRST + - 4) - MIXERLINE_COMPONENTTYPE_DST_HEADPHONES* = ( - MIXERLINE_COMPONENTTYPE_DST_FIRST + 5) - MIXERLINE_COMPONENTTYPE_DST_TELEPHONE* = ( - MIXERLINE_COMPONENTTYPE_DST_FIRST + 6) - MIXERLINE_COMPONENTTYPE_DST_WAVEIN* = (MIXERLINE_COMPONENTTYPE_DST_FIRST + 7) - MIXERLINE_COMPONENTTYPE_DST_VOICEIN* = (MIXERLINE_COMPONENTTYPE_DST_FIRST + 8) - MIXERLINE_COMPONENTTYPE_DST_LAST* = (MIXERLINE_COMPONENTTYPE_DST_FIRST + 8) - MIXERLINE_COMPONENTTYPE_SRC_FIRST* = 0x00001000 - MIXERLINE_COMPONENTTYPE_SRC_UNDEFINED* = ( - MIXERLINE_COMPONENTTYPE_SRC_FIRST + 0) - MIXERLINE_COMPONENTTYPE_SRC_DIGITAL* = (MIXERLINE_COMPONENTTYPE_SRC_FIRST + 1) - MIXERLINE_COMPONENTTYPE_SRC_LINE* = (MIXERLINE_COMPONENTTYPE_SRC_FIRST + 2) - MIXERLINE_COMPONENTTYPE_SRC_MICROPHONE* = ( - MIXERLINE_COMPONENTTYPE_SRC_FIRST + 3) - MIXERLINE_COMPONENTTYPE_SRC_SYNTHESIZER* = ( - MIXERLINE_COMPONENTTYPE_SRC_FIRST + 4) - MIXERLINE_COMPONENTTYPE_SRC_COMPACTDISC* = ( - MIXERLINE_COMPONENTTYPE_SRC_FIRST + 5) - MIXERLINE_COMPONENTTYPE_SRC_TELEPHONE* = ( - MIXERLINE_COMPONENTTYPE_SRC_FIRST + 6) - MIXERLINE_COMPONENTTYPE_SRC_PCSPEAKER* = ( - MIXERLINE_COMPONENTTYPE_SRC_FIRST + 7) - MIXERLINE_COMPONENTTYPE_SRC_WAVEOUT* = (MIXERLINE_COMPONENTTYPE_SRC_FIRST + 8) - MIXERLINE_COMPONENTTYPE_SRC_AUXILIARY* = ( - MIXERLINE_COMPONENTTYPE_SRC_FIRST + 9) - MIXERLINE_COMPONENTTYPE_SRC_ANALOG* = (MIXERLINE_COMPONENTTYPE_SRC_FIRST + 10) - MIXERLINE_COMPONENTTYPE_SRC_LAST* = (MIXERLINE_COMPONENTTYPE_SRC_FIRST + 10) - MIXERLINE_TARGETTYPE_UNDEFINED* = 0 - MIXERLINE_TARGETTYPE_WAVEOUT* = 1 - MIXERLINE_TARGETTYPE_WAVEIN* = 2 - MIXERLINE_TARGETTYPE_MIDIOUT* = 3 - MIXERLINE_TARGETTYPE_MIDIIN* = 4 - MIXERLINE_TARGETTYPE_AUX* = 5 - MIDIERR_UNPREPARED* = (MIDIERR_BASE + 0) - MIDIERR_STILLPLAYING* = (MIDIERR_BASE + 1) - MIDIERR_NOMAP* = (MIDIERR_BASE + 2) - MIDIERR_NOTREADY* = (MIDIERR_BASE + 3) - MIDIERR_NODEVICE* = (MIDIERR_BASE + 4) - MIDIERR_INVALIDSETUP* = (MIDIERR_BASE + 5) - MIDIERR_BADOPENMODE* = (MIDIERR_BASE + 6) - MIDIERR_DONT_CONTINUE* = (MIDIERR_BASE + 7) - MIDIERR_LASTERROR* = (MIDIERR_BASE + 7) - MIXERCONTROL_CONTROLF_UNIFORM* = 1 - MIXERCONTROL_CONTROLF_MULTIPLE* = 2 - MIXERCONTROL_CONTROLF_DISABLED* = 0x80000000 - MIXERCONTROL_CT_CLASS_MASK* = 0xF0000000 - MIXERCONTROL_CT_CLASS_CUSTOM* = 0 - MIXERCONTROL_CT_CLASS_METER* = 0x10000000 - MIXERCONTROL_CT_CLASS_SWITCH* = 0x20000000 - MIXERCONTROL_CT_CLASS_NUMBER* = 0x30000000 - MIXERCONTROL_CT_CLASS_SLIDER* = 0x40000000 - MIXERCONTROL_CT_CLASS_FADER* = 0x50000000 - MIXERCONTROL_CT_CLASS_TIME* = 0x60000000 - MIXERCONTROL_CT_CLASS_LIST* = 0x70000000 - MIXERCONTROL_CT_SUBCLASS_MASK* = 0x0F000000 - MIXERCONTROL_CT_SC_SWITCH_BOOLEAN* = 0 - MIXERCONTROL_CT_SC_SWITCH_BUTTON* = 0x01000000 - MIXERCONTROL_CT_SC_METER_POLLED* = 0 - MIXERCONTROL_CT_SC_TIME_MICROSECS* = 0 - MIXERCONTROL_CT_SC_TIME_MILLISECS* = 0x01000000 - MIXERCONTROL_CT_SC_LIST_SINGLE* = 0 - MIXERCONTROL_CT_SC_LIST_MULTIPLE* = 0x01000000 - MIXERCONTROL_CT_UNITS_MASK* = 0x00FF0000 - MIXERCONTROL_CT_UNITS_CUSTOM* = 0 - MIXERCONTROL_CT_UNITS_BOOLEAN* = 0x00010000 - MIXERCONTROL_CT_UNITS_SIGNED* = 0x00020000 - MIXERCONTROL_CT_UNITS_UNSIGNED* = 0x00030000 - MIXERCONTROL_CT_UNITS_DECIBELS* = 0x00040000 - MIXERCONTROL_CT_UNITS_PERCENT* = 0x00050000 - MIXERCONTROL_CONTROLTYPE_CUSTOM* = ( - MIXERCONTROL_CT_CLASS_CUSTOM or MIXERCONTROL_CT_UNITS_CUSTOM) - MIXERCONTROL_CONTROLTYPE_BOOLEANMETER* = (MIXERCONTROL_CT_CLASS_METER or - MIXERCONTROL_CT_SC_METER_POLLED or MIXERCONTROL_CT_UNITS_BOOLEAN) - MIXERCONTROL_CONTROLTYPE_SIGNEDMETER* = (MIXERCONTROL_CT_CLASS_METER or - MIXERCONTROL_CT_SC_METER_POLLED or MIXERCONTROL_CT_UNITS_SIGNED) - MIXERCONTROL_CONTROLTYPE_PEAKMETER* = ( - MIXERCONTROL_CONTROLTYPE_SIGNEDMETER + 1) - MIXERCONTROL_CONTROLTYPE_UNSIGNEDMETER* = (MIXERCONTROL_CT_CLASS_METER or - MIXERCONTROL_CT_SC_METER_POLLED or MIXERCONTROL_CT_UNITS_UNSIGNED) - MIXERCONTROL_CONTROLTYPE_BOOLEAN* = (MIXERCONTROL_CT_CLASS_SWITCH or - MIXERCONTROL_CT_SC_SWITCH_BOOLEAN or MIXERCONTROL_CT_UNITS_BOOLEAN) - MIXERCONTROL_CONTROLTYPE_ONOFF* = (MIXERCONTROL_CONTROLTYPE_BOOLEAN + 1) - MIXERCONTROL_CONTROLTYPE_MUTE* = (MIXERCONTROL_CONTROLTYPE_BOOLEAN + 2) - MIXERCONTROL_CONTROLTYPE_MONO* = (MIXERCONTROL_CONTROLTYPE_BOOLEAN + 3) - MIXERCONTROL_CONTROLTYPE_LOUDNESS* = (MIXERCONTROL_CONTROLTYPE_BOOLEAN + 4) - MIXERCONTROL_CONTROLTYPE_STEREOENH* = (MIXERCONTROL_CONTROLTYPE_BOOLEAN + 5) - MIXERCONTROL_CONTROLTYPE_BUTTON* = (MIXERCONTROL_CT_CLASS_SWITCH or - MIXERCONTROL_CT_SC_SWITCH_BUTTON or MIXERCONTROL_CT_UNITS_BOOLEAN) - MIXERCONTROL_CONTROLTYPE_DECIBELS* = ( - MIXERCONTROL_CT_CLASS_NUMBER or MIXERCONTROL_CT_UNITS_DECIBELS) - MIXERCONTROL_CONTROLTYPE_SIGNED* = ( - MIXERCONTROL_CT_CLASS_NUMBER or MIXERCONTROL_CT_UNITS_SIGNED) - MIXERCONTROL_CONTROLTYPE_UNSIGNED* = ( - MIXERCONTROL_CT_CLASS_NUMBER or MIXERCONTROL_CT_UNITS_UNSIGNED) - MIXERCONTROL_CONTROLTYPE_PERCENT* = ( - MIXERCONTROL_CT_CLASS_NUMBER or MIXERCONTROL_CT_UNITS_PERCENT) - MIXERCONTROL_CONTROLTYPE_SLIDER* = ( - MIXERCONTROL_CT_CLASS_SLIDER or MIXERCONTROL_CT_UNITS_SIGNED) - MIXERCONTROL_CONTROLTYPE_PAN* = (MIXERCONTROL_CONTROLTYPE_SLIDER + 1) - MIXERCONTROL_CONTROLTYPE_QSOUNDPAN* = (MIXERCONTROL_CONTROLTYPE_SLIDER + 2) - MIXERCONTROL_CONTROLTYPE_FADER* = ( - MIXERCONTROL_CT_CLASS_FADER or MIXERCONTROL_CT_UNITS_UNSIGNED) - MIXERCONTROL_CONTROLTYPE_VOLUME* = (MIXERCONTROL_CONTROLTYPE_FADER + 1) - MIXERCONTROL_CONTROLTYPE_BASS* = (MIXERCONTROL_CONTROLTYPE_FADER + 2) - MIXERCONTROL_CONTROLTYPE_TREBLE* = (MIXERCONTROL_CONTROLTYPE_FADER + 3) - MIXERCONTROL_CONTROLTYPE_EQUALIZER* = (MIXERCONTROL_CONTROLTYPE_FADER + 4) - MIXERCONTROL_CONTROLTYPE_SINGLESELECT* = (MIXERCONTROL_CT_CLASS_LIST or - MIXERCONTROL_CT_SC_LIST_SINGLE or MIXERCONTROL_CT_UNITS_BOOLEAN) - MIXERCONTROL_CONTROLTYPE_MUX* = (MIXERCONTROL_CONTROLTYPE_SINGLESELECT + 1) - MIXERCONTROL_CONTROLTYPE_MULTIPLESELECT* = (MIXERCONTROL_CT_CLASS_LIST or - MIXERCONTROL_CT_SC_LIST_MULTIPLE or MIXERCONTROL_CT_UNITS_BOOLEAN) - MIXERCONTROL_CONTROLTYPE_MIXER* = (MIXERCONTROL_CONTROLTYPE_MULTIPLESELECT + - 1) - MIXERCONTROL_CONTROLTYPE_MICROTIME* = (MIXERCONTROL_CT_CLASS_TIME or - MIXERCONTROL_CT_SC_TIME_MICROSECS or MIXERCONTROL_CT_UNITS_UNSIGNED) - MIXERCONTROL_CONTROLTYPE_MILLITIME* = (MIXERCONTROL_CT_CLASS_TIME or - MIXERCONTROL_CT_SC_TIME_MILLISECS or MIXERCONTROL_CT_UNITS_UNSIGNED) - MIXER_SHORT_NAME_CHARS* = 16 - MIXER_LONG_NAME_CHARS* = 64 - MIXERR_INVALLINE* = (MIXERR_BASE + 0) - MIXERR_INVALCONTROL* = (MIXERR_BASE + 1) - MIXERR_INVALVALUE* = (MIXERR_BASE + 2) - MIXERR_LASTERROR* = (MIXERR_BASE + 2) - MIXER_OBJECTF_HANDLE* = 0x80000000 - MIXER_OBJECTF_MIXER* = 0 - MIXER_OBJECTF_HMIXER* = (MIXER_OBJECTF_HANDLE or MIXER_OBJECTF_MIXER) - MIXER_OBJECTF_WAVEOUT* = 0x10000000 - MIXER_OBJECTF_HWAVEOUT* = (MIXER_OBJECTF_HANDLE or MIXER_OBJECTF_WAVEOUT) - MIXER_OBJECTF_WAVEIN* = 0x20000000 - MIXER_OBJECTF_HWAVEIN* = (MIXER_OBJECTF_HANDLE or MIXER_OBJECTF_WAVEIN) - MIXER_OBJECTF_MIDIOUT* = 0x30000000 - MIXER_OBJECTF_HMIDIOUT* = (MIXER_OBJECTF_HANDLE or MIXER_OBJECTF_MIDIOUT) - MIXER_OBJECTF_MIDIIN* = 0x40000000 - MIXER_OBJECTF_HMIDIIN* = (MIXER_OBJECTF_HANDLE or MIXER_OBJECTF_MIDIIN) - MIXER_OBJECTF_AUX* = 0x50000000 - MIXER_GETCONTROLDETAILSF_VALUE* = 0 - MIXER_GETCONTROLDETAILSF_LISTTEXT* = 1 - MIXER_GETCONTROLDETAILSF_QUERYMASK* = 0x0000000F - MIXER_SETCONTROLDETAILSF_VALUE* = 0 - MIXER_SETCONTROLDETAILSF_CUSTOM* = 1 - MIXER_SETCONTROLDETAILSF_QUERYMASK* = 0x0000000F - JOYERR_NOERROR* = (0) - JOYERR_PARMS* = (JOYERR_BASE + 5) - JOYERR_NOCANDO* = (JOYERR_BASE + 6) - JOYERR_UNPLUGGED* = (JOYERR_BASE + 7) - JOY_BUTTON1* = 1 - JOY_BUTTON2* = 2 - JOY_BUTTON3* = 4 - JOY_BUTTON4* = 8 - JOY_BUTTON1CHG* = 256 - JOY_BUTTON2CHG* = 512 - JOY_BUTTON3CHG* = 0x00000400 - JOY_BUTTON4CHG* = 0x00000800 - JOY_BUTTON5* = 16 - JOY_BUTTON6* = 32 - JOY_BUTTON7* = 64 - JOY_BUTTON8* = 128 - JOY_BUTTON9* = 256 - JOY_BUTTON10* = 512 - JOY_BUTTON11* = 0x00000400 - JOY_BUTTON12* = 0x00000800 - JOY_BUTTON13* = 0x00001000 - JOY_BUTTON14* = 0x00002000 - JOY_BUTTON15* = 0x00004000 - JOY_BUTTON16* = 0x00008000 - JOY_BUTTON17* = 0x00010000 - JOY_BUTTON18* = 0x00020000 - JOY_BUTTON19* = 0x00040000 - JOY_BUTTON20* = 0x00080000 - JOY_BUTTON21* = 0x00100000 - JOY_BUTTON22* = 0x00200000 - JOY_BUTTON23* = 0x00400000 - JOY_BUTTON24* = 0x00800000 - JOY_BUTTON25* = 0x01000000 - JOY_BUTTON26* = 0x02000000 - JOY_BUTTON27* = 0x04000000 - JOY_BUTTON28* = 0x08000000 - JOY_BUTTON29* = 0x10000000 - JOY_BUTTON30* = 0x20000000 - JOY_BUTTON31* = 0x40000000 - JOY_BUTTON32* = 0x80000000 - JOY_POVCENTERED* = - 1 - JOY_POVFORWARD* = 0 - JOY_POVRIGHT* = 9000 - JOY_POVBACKWARD* = 18000 - JOY_POVLEFT* = 27000 - JOY_RETURNX* = 1 - JOY_RETURNY* = 2 - JOY_RETURNZ* = 4 - JOY_RETURNR* = 8 - JOY_RETURNU* = 16 - JOY_RETURNV* = 32 - JOY_RETURNPOV* = 64 - JOY_RETURNBUTTONS* = 128 - JOY_RETURNRAWDATA* = 256 - JOY_RETURNPOVCTS* = 512 - JOY_RETURNCENTERED* = 0x00000400 - JOY_USEDEADZONE* = 0x00000800 - JOY_RETURNALL* = (JOY_RETURNX or JOY_RETURNY or JOY_RETURNZ or JOY_RETURNR or - JOY_RETURNU or JOY_RETURNV or JOY_RETURNPOV or JOY_RETURNBUTTONS) - JOY_CAL_READALWAYS* = 0x00010000 - JOY_CAL_READXYONLY* = 0x00020000 - JOY_CAL_READ3* = 0x00040000 - JOY_CAL_READ4* = 0x00080000 - JOY_CAL_READXONLY* = 0x00100000 - JOY_CAL_READYONLY* = 0x00200000 - JOY_CAL_READ5* = 0x00400000 - JOY_CAL_READ6* = 0x00800000 - JOY_CAL_READZONLY* = 0x01000000 - JOY_CAL_READRONLY* = 0x02000000 - JOY_CAL_READUONLY* = 0x04000000 - JOY_CAL_READVONLY* = 0x08000000 - JOYSTICKID1* = 0 - JOYSTICKID2* = 1 - JOYCAPS_HASZ* = 1 - JOYCAPS_HASR* = 2 - JOYCAPS_HASU* = 4 - JOYCAPS_HASV* = 8 - JOYCAPS_HASPOV* = 16 - JOYCAPS_POV4DIR* = 32 - JOYCAPS_POVCTS* = 64 - MMIOERR_BASE* = 256 - MMIOERR_FILENOTFOUND* = (MMIOERR_BASE + 1) - MMIOERR_OUTOFMEMORY* = (MMIOERR_BASE + 2) - MMIOERR_CANNOTOPEN* = (MMIOERR_BASE + 3) - MMIOERR_CANNOTCLOSE* = (MMIOERR_BASE + 4) - MMIOERR_CANNOTREAD* = (MMIOERR_BASE + 5) - MMIOERR_CANNOTWRITE* = (MMIOERR_BASE + 6) - MMIOERR_CANNOTSEEK* = (MMIOERR_BASE + 7) - MMIOERR_CANNOTEXPAND* = (MMIOERR_BASE + 8) - MMIOERR_CHUNKNOTFOUND* = (MMIOERR_BASE + 9) - MMIOERR_UNBUFFERED* = (MMIOERR_BASE + 10) - MMIOERR_PATHNOTFOUND* = (MMIOERR_BASE + 11) - MMIOERR_ACCESSDENIED* = (MMIOERR_BASE + 12) - MMIOERR_SHARINGVIOLATION* = (MMIOERR_BASE + 13) - MMIOERR_NETWORKERROR* = (MMIOERR_BASE + 14) - MMIOERR_TOOMANYOPENFILES* = (MMIOERR_BASE + 15) - MMIOERR_INVALIDFILE* = (MMIOERR_BASE + 16) - CFSEPCHAR* = '+' - WAVECAPS_PITCH* = 1 - WAVECAPS_PLAYBACKRATE* = 2 - WAVECAPS_VOLUME* = 4 - WAVECAPS_LRVOLUME* = 8 - WAVECAPS_SYNC* = 16 - WAVECAPS_SAMPLEACCURATE* = 32 - WAVECAPS_DIRECTSOUND* = 64 - MIXER_GETLINEINFOF_DESTINATION* = 0 - MIXER_GETLINEINFOF_SOURCE* = 1 - MIXER_GETLINEINFOF_LINEID* = 2 - MIXER_GETLINEINFOF_COMPONENTTYPE* = 3 - MIXER_GETLINEINFOF_TARGETTYPE* = 4 - MIXER_GETLINEINFOF_QUERYMASK* = 0x0000000F - MMIO_RWMODE* = 3 - MMIO_SHAREMODE* = 0x00000070 - MMIO_CREATE* = 0x00001000 - MMIO_PARSE* = 256 - MMIO_DELETE* = 512 - MMIO_EXIST* = 0x00004000 - MMIO_ALLOCBUF* = 0x00010000 - MMIO_GETTEMP* = 0x00020000 - MMIO_DIRTY* = 0x10000000 - cMMIO_READ* = 0 - cMMIO_WRITE* = 1 - MMIO_READWRITE* = 2 - MMIO_COMPAT* = 0 - MMIO_EXCLUSIVE* = 16 - MMIO_DENYWRITE* = 32 - MMIO_DENYREAD* = 0x00000030 - MMIO_DENYNONE* = 64 - MMIO_FHOPEN* = 16 - MMIO_EMPTYBUF* = 16 - MMIO_TOUPPER* = 16 - MMIO_INSTALLPROC* = 0x00010000 - MMIO_GLOBALPROC* = 0x10000000 - MMIO_REMOVEPROC* = 0x00020000 - MMIO_UNICODEPROC* = 0x01000000 - MMIO_FINDPROC* = 0x00040000 - MMIO_FINDCHUNK* = 16 - MMIO_FINDRIFF* = 32 - MMIO_FINDLIST* = 64 - MMIO_CREATERIFF* = 32 - MMIO_CREATELIST* = 64 - MMIOM_READ* = cMMIO_READ - MMIOM_WRITE* = cMMIO_WRITE - MMIOM_SEEK* = 2 - MMIOM_OPEN* = 3 - MMIOM_CLOSE* = 4 - MMIOM_WRITEFLUSH* = 5 - MMIOM_RENAME* = 6 - MMIOM_USER* = 0x00008000 - FOURCC_RIFF* = 0x46464952 #'R','I','F','F' - FOURCC_LIST* = 0x5453494C #'L','I','S','T' - FOURCC_DOS* = 0x20532F44 #'D','O','S',' ' - FOURCC_MEM* = 0x204D454D #'M','E','M',' ' - SEEK_SET* = 0 - SEEK_CUR* = 1 - SEEK_END* = 2 - MMIO_DEFAULTBUFFER* = 8192 - MCIERR_INVALID_DEVICE_ID* = (MCIERR_BASE + 1) - MCIERR_UNRECOGNIZED_KEYWORD* = (MCIERR_BASE + 3) - MCIERR_UNRECOGNIZED_COMMAND* = (MCIERR_BASE + 5) - MCIERR_HARDWARE* = (MCIERR_BASE + 6) - MCIERR_INVALID_DEVICE_NAME* = (MCIERR_BASE + 7) - MCIERR_OUT_OF_MEMORY* = (MCIERR_BASE + 8) - MCIERR_DEVICE_OPEN* = (MCIERR_BASE + 9) - MCIERR_CANNOT_LOAD_DRIVER* = (MCIERR_BASE + 10) - MCIERR_MISSING_COMMAND_STRING* = (MCIERR_BASE + 11) - MCIERR_PARAM_OVERFLOW* = (MCIERR_BASE + 12) - MCIERR_MISSING_STRING_ARGUMENT* = (MCIERR_BASE + 13) - MCIERR_BAD_INTEGER* = (MCIERR_BASE + 14) - MCIERR_PARSER_INTERNAL* = (MCIERR_BASE + 15) - MCIERR_DRIVER_INTERNAL* = (MCIERR_BASE + 16) - MCIERR_MISSING_PARAMETER* = (MCIERR_BASE + 17) - MCIERR_UNSUPPORTED_FUNCTION* = (MCIERR_BASE + 18) - MCIERR_FILE_NOT_FOUND* = (MCIERR_BASE + 19) - MCIERR_DEVICE_NOT_READY* = (MCIERR_BASE + 20) - MCIERR_INTERNAL* = (MCIERR_BASE + 21) - MCIERR_DRIVER* = (MCIERR_BASE + 22) - MCIERR_CANNOT_USE_ALL* = (MCIERR_BASE + 23) - MCIERR_MULTIPLE* = (MCIERR_BASE + 24) - MCIERR_EXTENSION_NOT_FOUND* = (MCIERR_BASE + 25) - MCIERR_OUTOFRANGE* = (MCIERR_BASE + 26) - MCIERR_FLAGS_NOT_COMPATIBLE* = (MCIERR_BASE + 28) - MCIERR_FILE_NOT_SAVED* = (MCIERR_BASE + 30) - MCIERR_DEVICE_TYPE_REQUIRED* = (MCIERR_BASE + 31) - MCIERR_DEVICE_LOCKED* = (MCIERR_BASE + 32) - MCIERR_DUPLICATE_ALIAS* = (MCIERR_BASE + 33) - MCIERR_BAD_CONSTANT* = (MCIERR_BASE + 34) - MCIERR_MUST_USE_SHAREABLE* = (MCIERR_BASE + 35) - MCIERR_MISSING_DEVICE_NAME* = (MCIERR_BASE + 36) - MCIERR_BAD_TIME_FORMAT* = (MCIERR_BASE + 37) - MCIERR_NO_CLOSING_QUOTE* = (MCIERR_BASE + 38) - MCIERR_DUPLICATE_FLAGS* = (MCIERR_BASE + 39) - MCIERR_INVALID_FILE* = (MCIERR_BASE + 40) - MCIERR_NULL_PARAMETER_BLOCK* = (MCIERR_BASE + 41) - MCIERR_UNNAMED_RESOURCE* = (MCIERR_BASE + 42) - MCIERR_NEW_REQUIRES_ALIAS* = (MCIERR_BASE + 43) - MCIERR_NOTIFY_ON_AUTO_OPEN* = (MCIERR_BASE + 44) - MCIERR_NO_ELEMENT_ALLOWED* = (MCIERR_BASE + 45) - MCIERR_NONAPPLICABLE_FUNCTION* = (MCIERR_BASE + 46) - MCIERR_ILLEGAL_FOR_AUTO_OPEN* = (MCIERR_BASE + 47) - MCIERR_FILENAME_REQUIRED* = (MCIERR_BASE + 48) - MCIERR_EXTRA_CHARACTERS* = (MCIERR_BASE + 49) - MCIERR_DEVICE_NOT_INSTALLED* = (MCIERR_BASE + 50) - MCIERR_GET_CD* = (MCIERR_BASE + 51) - MCIERR_SET_CD* = (MCIERR_BASE + 52) - MCIERR_SET_DRIVE* = (MCIERR_BASE + 53) - MCIERR_DEVICE_LENGTH* = (MCIERR_BASE + 54) - MCIERR_DEVICE_ORD_LENGTH* = (MCIERR_BASE + 55) - MCIERR_NO_INTEGER* = (MCIERR_BASE + 56) - MCIERR_WAVE_OUTPUTSINUSE* = (MCIERR_BASE + 64) - MCIERR_WAVE_SETOUTPUTINUSE* = (MCIERR_BASE + 65) - MCIERR_WAVE_INPUTSINUSE* = (MCIERR_BASE + 66) - MCIERR_WAVE_SETINPUTINUSE* = (MCIERR_BASE + 67) - MCIERR_WAVE_OUTPUTUNSPECIFIED* = (MCIERR_BASE + 68) - MCIERR_WAVE_INPUTUNSPECIFIED* = (MCIERR_BASE + 69) - MCIERR_WAVE_OUTPUTSUNSUITABLE* = (MCIERR_BASE + 70) - MCIERR_WAVE_SETOUTPUTUNSUITABLE* = (MCIERR_BASE + 71) - MCIERR_WAVE_INPUTSUNSUITABLE* = (MCIERR_BASE + 72) - MCIERR_WAVE_SETINPUTUNSUITABLE* = (MCIERR_BASE + 73) - MCIERR_SEQ_DIV_INCOMPATIBLE* = (MCIERR_BASE + 80) - MCIERR_SEQ_PORT_INUSE* = (MCIERR_BASE + 81) - MCIERR_SEQ_PORT_NONEXISTENT* = (MCIERR_BASE + 82) - MCIERR_SEQ_PORT_MAPNODEVICE* = (MCIERR_BASE + 83) - MCIERR_SEQ_PORT_MISCERROR* = (MCIERR_BASE + 84) - MCIERR_SEQ_TIMER* = (MCIERR_BASE + 85) - MCIERR_SEQ_PORTUNSPECIFIED* = (MCIERR_BASE + 86) - MCIERR_SEQ_NOMIDIPRESENT* = (MCIERR_BASE + 87) - MCIERR_NO_WINDOW* = (MCIERR_BASE + 90) - MCIERR_CREATEWINDOW* = (MCIERR_BASE + 91) - MCIERR_FILE_READ* = (MCIERR_BASE + 92) - MCIERR_FILE_WRITE* = (MCIERR_BASE + 93) - MCIERR_NO_IDENTITY* = (MCIERR_BASE + 94) - MCIERR_CUSTOM_DRIVER_BASE* = (MCIERR_BASE + 256) - MCI_FIRST* = DRV_MCI_FIRST - MCI_ESCAPE* = 0x00000805 - MCI_PLAY* = 0x00000806 - MCI_SEEK* = 0x00000807 - MCI_STOP* = 0x00000808 - MCI_PAUSE* = 0x00000809 - MCI_INFO* = 0x0000080A - MCI_GETDEVCAPS* = 0x0000080B - MCI_BREAK* = 0x00000811 - MCI_WHERE* = 0x00000843 - MCI_FREEZE* = 0x00000844 - MCI_UNFREEZE* = 0x00000845 - MCI_LOAD* = 0x00000850 - MCI_CUT* = 0x00000851 - MCI_COPY* = 0x00000852 - MCI_PASTE* = 0x00000853 - MCI_UPDATE* = 0x00000854 - MCI_RESUME* = 0x00000855 - MCI_DELETE* = 0x00000856 - MCI_SET* = 0x0000080D - MCI_STEP* = 0x0000080E - MCI_SAVE* = 0x00000813 - MCI_SPIN* = 0x0000080C - MCI_STATUS* = 0x00000814 - MCI_CUE* = 0x00000830 - MCI_REALIZE* = 0x00000840 - MCI_WINDOW* = 0x00000841 - MCI_PUT* = 0x00000842 - MCI_RECORD* = 0x0000080F - MCI_SYSINFO* = 0x00000810 - MCI_OPEN* = 0x00000803 - MCI_CLOSE* = 0x00000804 - MCI_USER_MESSAGES* = (DRV_MCI_FIRST + 0x00000400) - MCI_LAST* = 0x00000FFF - MCI_ALL_DEVICE_ID* = - 1 - MCI_DEVTYPE_VCR* = 513 - MCI_DEVTYPE_VIDEODISC* = 514 - MCI_DEVTYPE_OVERLAY* = 515 - MCI_DEVTYPE_CD_AUDIO* = 516 - MCI_DEVTYPE_DAT* = 517 - MCI_DEVTYPE_SCANNER* = 518 - MCI_DEVTYPE_ANIMATION* = 519 - MCI_DEVTYPE_DIGITAL_VIDEO* = 520 - MCI_DEVTYPE_OTHER* = 521 - MCI_DEVTYPE_WAVEFORM_AUDIO* = 522 - MCI_DEVTYPE_SEQUENCER* = 523 - MCI_DEVTYPE_FIRST* = MCI_DEVTYPE_VCR - MCI_DEVTYPE_LAST* = MCI_DEVTYPE_SEQUENCER - MCI_DEVTYPE_FIRST_USER* = 0x00001000 - MCI_MODE_NOT_READY* = (MCI_STRING_OFFSET + 12) - MCI_MODE_STOP* = (MCI_STRING_OFFSET + 13) - MCI_MODE_PLAY* = (MCI_STRING_OFFSET + 14) - MCI_MODE_RECORD* = (MCI_STRING_OFFSET + 15) - MCI_MODE_SEEK* = (MCI_STRING_OFFSET + 16) - MCI_MODE_PAUSE* = (MCI_STRING_OFFSET + 17) - MCI_MODE_OPEN* = (MCI_STRING_OFFSET + 18) - MCI_FORMAT_MILLISECONDS* = 0 - MCI_FORMAT_HMS* = 1 - MCI_FORMAT_MSF* = 2 - MCI_FORMAT_FRAMES* = 3 - MCI_FORMAT_SMPTE_24* = 4 - MCI_FORMAT_SMPTE_25* = 5 - MCI_FORMAT_SMPTE_30* = 6 - MCI_FORMAT_SMPTE_30DROP* = 7 - MCI_FORMAT_BYTES* = 8 - MCI_FORMAT_SAMPLES* = 9 - MCI_FORMAT_TMSF* = 10 - -proc MCI_MSF_MINUTE*(msf: int32): int8 -proc MCI_MSF_SECOND*(msf: int32): int8 -proc MCI_MSF_FRAME*(msf: int32): int8 -proc MCI_MAKE_MSF*(m, s, f: int8): int32 -const - MCI_SET_DOOR_OPEN* = 256 - MCI_SET_DOOR_CLOSED* = 512 - MCI_SET_TIME_FORMAT* = 0x00000400 - MCI_SET_AUDIO* = 0x00000800 - MCI_SET_VIDEO* = 0x00001000 - MCI_SET_ON* = 0x00002000 - MCI_SET_OFF* = 0x00004000 - MCI_SET_AUDIO_ALL* = 0 - MCI_SET_AUDIO_LEFT* = 1 - MCI_SET_AUDIO_RIGHT* = 2 - -proc MCI_TMSF_TRACK*(tmsf: int32): int8 -proc MCI_TMSF_MINUTE*(tmsf: int32): int8 -proc MCI_TMSF_SECOND*(tmsf: int32): int8 -proc MCI_TMSF_FRAME*(tmsf: int32): int8 -proc MCI_HMS_HOUR*(h: int32): int8 -proc MCI_HMS_MINUTE*(h: int32): int8 -proc MCI_HMS_SECOND*(h: int32): int8 -proc MCI_MAKE_HMS*(h, m, s: int8): int32 -const - MCI_INFO_PRODUCT* = 256 - MCI_INFO_FILE* = 512 - MCI_INFO_MEDIA_UPC* = 0x00000400 - MCI_INFO_MEDIA_IDENTITY* = 0x00000800 - MCI_INFO_NAME* = 0x00001000 - MCI_INFO_COPYRIGHT* = 0x00002000 - -proc MCI_MAKE_TMSF*(t, m, s, f: int8): int32 -const - MCI_WAIT* = 2 - MCI_FROM* = 4 - MCI_TO* = 8 - MCI_TRACK* = 16 - MCI_SEEK_TO_START* = 256 - MCI_SEEK_TO_END* = 512 - MCI_STATUS_ITEM* = 256 - MCI_STATUS_START* = 512 - MCI_STATUS_LENGTH* = 1 - MCI_STATUS_POSITION* = 2 - MCI_STATUS_NUMBER_OF_TRACKS* = 3 - MCI_STATUS_MODE* = 4 - MCI_STATUS_MEDIA_PRESENT* = 5 - MCI_STATUS_TIME_FORMAT* = 6 - MCI_STATUS_READY* = 7 - MCI_STATUS_CURRENT_TRACK* = 8 - MCI_OPEN_SHAREABLE* = 256 - MCI_OPEN_ELEMENT* = 512 - MCI_OPEN_ALIAS* = 0x00000400 - MCI_OPEN_ELEMENT_ID* = 0x00000800 - MCI_OPEN_TYPE_ID* = 0x00001000 - MCI_OPEN_TYPE* = 0x00002000 - MCI_GETDEVCAPS_ITEM* = 256 - MCI_GETDEVCAPS_CAN_RECORD* = 1 - MCI_GETDEVCAPS_HAS_AUDIO* = 2 - MCI_GETDEVCAPS_HAS_VIDEO* = 3 - MCI_GETDEVCAPS_DEVICE_TYPE* = 4 - MCI_GETDEVCAPS_USES_FILES* = 5 - MCI_GETDEVCAPS_COMPOUND_DEVICE* = 6 - MCI_GETDEVCAPS_CAN_EJECT* = 7 - MCI_GETDEVCAPS_CAN_PLAY* = 8 - MCI_GETDEVCAPS_CAN_SAVE* = 9 - MCI_SYSINFO_QUANTITY* = 256 - MCI_SYSINFO_OPEN* = 512 - MCI_SYSINFO_NAME* = 0x00000400 - MCI_SYSINFO_INSTALLNAME* = 0x00000800 - MCI_NOTIFY_SUCCESSFUL* = 1 - MCI_NOTIFY_SUPERSEDED* = 2 - MCI_NOTIFY_ABORTED* = 4 - MCI_NOTIFY_FAILURE* = 8 - MCI_NOTIFY* = 1 - MCI_BREAK_KEY* = 256 - MCI_BREAK_HWND* = 512 - MCI_BREAK_OFF* = 0x00000400 - MCI_RECORD_INSERT* = 256 - MCI_RECORD_OVERWRITE* = 512 - MCI_SAVE_FILE* = 256 - MCI_LOAD_FILE* = 256 - MCI_VD_GETDEVCAPS_FAST_RATE* = 0x00004003 - MCI_VD_GETDEVCAPS_SLOW_RATE* = 0x00004004 - MCI_VD_GETDEVCAPS_NORMAL_RATE* = 0x00004005 - MCI_VD_STEP_FRAMES* = 0x00010000 - MCI_VD_STEP_REVERSE* = 0x00020000 - MCI_VD_ESCAPE_STRING* = 256 - MCI_VD_FORMAT_TRACK* = 0x00004001 - MCI_VD_PLAY_REVERSE* = 0x00010000 - MCI_VD_PLAY_FAST* = 0x00020000 - MCI_VD_MODE_PARK* = (MCI_VD_OFFSET + 1) - MCI_VD_GETDEVCAPS_CAV* = 0x00020000 - MCI_VD_SPIN_UP* = 0x00010000 - MCI_VD_SPIN_DOWN* = 0x00020000 - MCI_VD_SEEK_REVERSE* = 0x00010000 - MCI_VD_STATUS_SPEED* = 0x00004002 - MCI_VD_STATUS_FORWARD* = 0x00004003 - MCI_VD_STATUS_MEDIA_TYPE* = 0x00004004 - MCI_VD_STATUS_SIDE* = 0x00004005 - MCI_VD_GETDEVCAPS_CAN_REVERSE* = 0x00004002 - MCI_VD_MEDIA_CLV* = (MCI_VD_OFFSET + 2) - MCI_VD_MEDIA_CAV* = (MCI_VD_OFFSET + 3) - MCI_VD_MEDIA_OTHER* = (MCI_VD_OFFSET + 4) - MCI_VD_STATUS_DISC_SIZE* = 0x00004006 - MCI_VD_GETDEVCAPS_CLV* = 0x00010000 - MCI_VD_PLAY_SPEED* = 0x00040000 - MCI_VD_PLAY_SCAN* = 0x00080000 - MCI_VD_PLAY_SLOW* = 0x00100000 - MCI_WAVE_STATUS_CHANNELS* = 0x00004002 - MCI_WAVE_STATUS_SAMPLESPERSEC* = 0x00004003 - MCI_WAVE_PCM* = MCI_WAVE_OFFSET - MCI_WAVE_MAPPER* = (MCI_WAVE_OFFSET + 1) - MCI_WAVE_OPEN_BUFFER* = 0x00010000 - MCI_WAVE_STATUS_BITSPERSAMPLE* = 0x00004006 - MCI_WAVE_STATUS_LEVEL* = 0x00004007 - MCI_WAVE_SET_FORMATTAG* = 0x00010000 - MCI_WAVE_SET_CHANNELS* = 0x00020000 - MCI_WAVE_SET_SAMPLESPERSEC* = 0x00040000 - MCI_WAVE_SET_AVGBYTESPERSEC* = 0x00080000 - MCI_WAVE_SET_BLOCKALIGN* = 0x00100000 - MCI_WAVE_SET_BITSPERSAMPLE* = 0x00200000 - MCI_WAVE_INPUT* = 0x00400000 - MCI_WAVE_OUTPUT* = 0x00800000 - MCI_WAVE_STATUS_FORMATTAG* = 0x00004001 - MCI_WAVE_SET_ANYINPUT* = 0x04000000 - MCI_WAVE_SET_ANYOUTPUT* = 0x08000000 - MCI_WAVE_GETDEVCAPS_INPUTS* = 0x00004001 - MCI_WAVE_GETDEVCAPS_OUTPUTS* = 0x00004002 - MCI_WAVE_STATUS_AVGBYTESPERSEC* = 0x00004004 - MCI_WAVE_STATUS_BLOCKALIGN* = 0x00004005 - MCI_CDA_STATUS_TYPE_TRACK* = 0x00004001 - MCI_CDA_TRACK_AUDIO* = (MCI_CD_OFFSET) - MCI_CDA_TRACK_OTHER* = (MCI_CD_OFFSET + 1) - MCI_SEQ_DIV_PPQN* = (MCI_SEQ_OFFSET) - MCI_SEQ_DIV_SMPTE_24* = (MCI_SEQ_OFFSET + 1) - MCI_SEQ_DIV_SMPTE_25* = (MCI_SEQ_OFFSET + 2) - MCI_SEQ_DIV_SMPTE_30DROP* = (MCI_SEQ_OFFSET + 3) - MCI_SEQ_DIV_SMPTE_30* = (MCI_SEQ_OFFSET + 4) - MCI_SEQ_FORMAT_SONGPTR* = 0x00004001 - MCI_SEQ_FILE* = 0x00004002 - MCI_SEQ_MIDI* = 0x00004003 - MCI_SEQ_SMPTE* = 0x00004004 - MCI_SEQ_NONE* = 65533 - MCI_SEQ_MAPPER* = 65535 - MCI_SEQ_STATUS_TEMPO* = 0x00004002 - MCI_SEQ_STATUS_PORT* = 0x00004003 - MCI_SEQ_STATUS_SLAVE* = 0x00004007 - MCI_SEQ_STATUS_MASTER* = 0x00004008 - MCI_SEQ_STATUS_OFFSET* = 0x00004009 - MCI_SEQ_STATUS_DIVTYPE* = 0x0000400A - MCI_SEQ_STATUS_NAME* = 0x0000400B - MCI_SEQ_STATUS_COPYRIGHT* = 0x0000400C - MCI_SEQ_SET_TEMPO* = 0x00010000 - MCI_SEQ_SET_PORT* = 0x00020000 - MCI_SEQ_SET_SLAVE* = 0x00040000 - MCI_SEQ_SET_MASTER* = 0x00080000 - MCI_SEQ_SET_OFFSET* = 0x01000000 - MCI_ANIM_PLAY_SLOW* = 0x00080000 - MCI_ANIM_PLAY_SCAN* = 0x00100000 - MCI_ANIM_GETDEVCAPS_SLOW_RATE* = 0x00004003 - MCI_ANIM_GETDEVCAPS_NORMAL_RATE* = 0x00004004 - MCI_ANIM_STEP_REVERSE* = 0x00010000 - MCI_ANIM_STEP_FRAMES* = 0x00020000 - MCI_ANIM_STATUS_SPEED* = 0x00004001 - MCI_ANIM_GETDEVCAPS_PALETTES* = 0x00004006 - MCI_ANIM_OPEN_WS* = 0x00010000 - MCI_ANIM_OPEN_PARENT* = 0x00020000 - MCI_ANIM_OPEN_NOSTATIC* = 0x00040000 - MCI_ANIM_GETDEVCAPS_FAST_RATE* = 0x00004002 - MCI_ANIM_PLAY_SPEED* = 0x00010000 - MCI_ANIM_PLAY_REVERSE* = 0x00020000 - MCI_ANIM_PLAY_FAST* = 0x00040000 - MCI_ANIM_STATUS_FORWARD* = 0x00004002 - MCI_ANIM_STATUS_HWND* = 0x00004003 - MCI_ANIM_STATUS_HPAL* = 0x00004004 - MCI_ANIM_STATUS_STRETCH* = 0x00004005 - MCI_ANIM_INFO_TEXT* = 0x00010000 - MCI_ANIM_GETDEVCAPS_CAN_REVERSE* = 0x00004001 - MCI_ANIM_WINDOW_TEXT* = 0x00080000 - MCI_ANIM_WINDOW_ENABLE_STRETCH* = 0x00100000 - MCI_ANIM_WINDOW_DISABLE_STRETCH* = 0x00200000 - MCI_ANIM_WINDOW_DEFAULT* = 0 - MCI_ANIM_RECT* = 0x00010000 - MCI_ANIM_PUT_SOURCE* = 0x00020000 - MCI_ANIM_PUT_DESTINATION* = 0x00040000 - MCI_ANIM_WHERE_SOURCE* = 0x00020000 - MCI_ANIM_WHERE_DESTINATION* = 0x00040000 - MCI_ANIM_UPDATE_HDC* = 0x00020000 - MCI_ANIM_GETDEVCAPS_CAN_STRETCH* = 0x00004007 - MCI_ANIM_GETDEVCAPS_MAX_WINDOWS* = 0x00004008 - MCI_ANIM_REALIZE_NORM* = 0x00010000 - MCI_ANIM_REALIZE_BKGD* = 0x00020000 - MCI_ANIM_WINDOW_HWND* = 0x00010000 - MCI_ANIM_WINDOW_STATE* = 0x00040000 - TIMERR_NOERROR* = 0 - TIMERR_NOCANDO* = (TIMERR_BASE + 1) - TIMERR_STRUCT* = (TIMERR_BASE + 33) - TIME_ONESHOT* = 0 - TIME_PERIODIC* = 1 - TIME_CALLBACK_FUNCTION* = 0 - TIME_CALLBACK_EVENT_SET* = 16 - TIME_CALLBACK_EVENT_PULSE* = 32 - MCI_OVLY_OPEN_WS* = 0x00010000 - MCI_OVLY_OPEN_PARENT* = 0x00020000 - MCI_OVLY_STATUS_HWND* = 0x00004001 - MCI_OVLY_STATUS_STRETCH* = 0x00004002 - MCI_OVLY_INFO_TEXT* = 0x00010000 - MCI_OVLY_GETDEVCAPS_CAN_STRETCH* = 0x00004001 - MCI_OVLY_GETDEVCAPS_CAN_FREEZE* = 0x00004002 - MCI_OVLY_GETDEVCAPS_MAX_WINDOWS* = 0x00004003 - MCI_OVLY_WINDOW_HWND* = 0x00010000 - MCI_OVLY_WINDOW_STATE* = 0x00040000 - MCI_OVLY_WINDOW_TEXT* = 0x00080000 - MCI_OVLY_WINDOW_ENABLE_STRETCH* = 0x00100000 - MCI_OVLY_WINDOW_DISABLE_STRETCH* = 0x00200000 - MCI_OVLY_WINDOW_DEFAULT* = 0 - MCI_OVLY_RECT* = 0x00010000 - MCI_OVLY_PUT_SOURCE* = 0x00020000 - MCI_OVLY_PUT_DESTINATION* = 0x00040000 - MCI_OVLY_PUT_FRAME* = 0x00080000 - MCI_OVLY_PUT_VIDEO* = 0x00100000 - MCI_OVLY_WHERE_SOURCE* = 0x00020000 - MCI_OVLY_WHERE_DESTINATION* = 0x00040000 - MCI_OVLY_WHERE_FRAME* = 0x00080000 - MCI_OVLY_WHERE_VIDEO* = 0x00100000 - AUX_MAPPER* = - 1 - MIXER_GETLINECONTROLSF_ONEBYID* = 1 - MIXER_GETLINECONTROLSF_ONEBYTYPE* = 2 - MIXER_GETLINECONTROLSF_ALL* = 0 - MIXER_GETLINECONTROLSF_QUERYMASK* = 0x0000000F - NEWTRANSPARENT* = 3 - QUERYROPSUPPORT* = 40 - SELECTDIB* = 41 - -proc DIBINDEX*(n: int32): int32 -const - SC_SCREENSAVE* = 0x0000F140 - AUXCAPS_CDAUDIO* = 1 - AUXCAPS_AUXIN* = 2 - AUXCAPS_VOLUME* = 1 - AUXCAPS_LRVOLUME* = 2 #///////////////////////////////////////////////////////// - # Structures and typedefs - #///////////////////////////////////////////////////////// - -type - MMTIME* {.final.} = object - wType*: uint32 - hour*, min*, sec*, frame*, fps*, dummy*: int8 - pad*: array[0..1, int8] - - PMMTIME* = ptr MMTIME - NPMMTIME* = ptr MMTIME - LPMMTIME* = ptr MMTIME - PWAVEHDR* = ptr WAVEHDR - WAVEHDR* {.final.} = object - lpData*: cstring - dwBufferLength*: DWORD - dwBytesRecorded*: DWORD - dwUser*: DWORD - dwFlags*: DWORD - dwLoops*: DWORD - lpNext*: PWAVEHDR - reserved*: DWORD - - NPWAVEHDR* = ptr WAVEHDR - LPWAVEHDR* = ptr WAVEHDR - WAVEOUTCAPSA* {.final.} = object - wMid*: int16 - wPid*: int16 - vDriverVersion*: MMVERSION - szPname*: array[0..pred(MAXPNAMELEN), char] - dwFormats*: DWORD - wChannels*: int16 - wReserved1*: int16 - dwSupport*: DWORD - - PWAVEOUTCAPSA* = ptr WAVEOUTCAPSA - NPWAVEOUTCAPSA* = ptr WAVEOUTCAPSA - LPWAVEOUTCAPSA* = ptr WAVEOUTCAPSA - WAVEOUTCAPSW* {.final.} = object - wMid*: int16 - wPid*: int16 - vDriverVersion*: MMVERSION - szPname*: array[0..pred(MAXPNAMELEN), WCHAR] - dwFormats*: DWORD - wChannels*: int16 - wReserved1*: int16 - dwSupport*: DWORD - - PWAVEOUTCAPSW* = ptr WAVEOUTCAPSW - NPWAVEOUTCAPSW* = ptr WAVEOUTCAPSW - LPWAVEOUTCAPSW* = ptr WAVEOUTCAPSW -{.deprecated: [Twavehdr: Wavehdr, Tmmtime: Mmtime, Twaveoutcapsa: Waveoutcapsa, - Twaveoutcapsw: Waveoutcapsw].} - -when defined(UNICODE): - type - WAVEOUTCAPS* = WAVEOUTCAPSW - PWAVEOUTCAPS* = PWAVEOUTCAPSW - NPWAVEOUTCAPS* = NPWAVEOUTCAPSW - LPWAVEOUTCAPS* = LPWAVEOUTCAPSW -else: - type - WAVEOUTCAPS* = WAVEOUTCAPSA - PWAVEOUTCAPS* = PWAVEOUTCAPSA - NPWAVEOUTCAPS* = NPWAVEOUTCAPSA - LPWAVEOUTCAPS* = LPWAVEOUTCAPSA -type - TWAVEOUTCAPS* = WAVEOUTCAPS - WAVEINCAPSA* {.final.} = object - wMid*: int16 - wPid*: int16 - vDriverVersion*: MMVERSION - szPname*: array[0..pred(MAXPNAMELEN), char] - dwFormats*: DWORD - wChannels*: int16 - wReserved1*: int16 - - PWAVEINCAPSA* = ptr WAVEINCAPSA - NPWAVEINCAPSA* = ptr WAVEINCAPSA - LPWAVEINCAPSA* = ptr WAVEINCAPSA - TWAVEINCAPSA* = WAVEINCAPSA - WAVEINCAPSW* {.final.} = object - wMid*: int16 - wPid*: int16 - vDriverVersion*: MMVERSION - szPname*: array[0..pred(MAXPNAMELEN), WCHAR] - dwFormats*: DWORD - wChannels*: int16 - wReserved1*: int16 - - PWAVEINCAPSW* = ptr WAVEINCAPSW - NPWAVEINCAPSW* = ptr WAVEINCAPSW - LPWAVEINCAPSW* = ptr WAVEINCAPSW - TWAVEINCAPSW* = WAVEINCAPSW - -when defined(UNICODE): - type - WAVEINCAPS* = WAVEINCAPSW - PWAVEINCAPS* = PWAVEINCAPSW - NPWAVEINCAPS* = NPWAVEINCAPSW - LPWAVEINCAPS* = LPWAVEINCAPSW -else: - type - WAVEINCAPS* = WAVEINCAPSA - PWAVEINCAPS* = PWAVEINCAPSA - NPWAVEINCAPS* = NPWAVEINCAPSA - LPWAVEINCAPS* = LPWAVEINCAPSA -type - TWAVEINCAPS* = WAVEINCAPS - WAVEFORMAT* {.final.} = object - wFormatTag*: int16 - nChannels*: int16 - nSamplesPerSec*: DWORD - nAvgBytesPerSec*: DWORD - nBlockAlign*: int16 - - PWAVEFORMAT* = ptr WAVEFORMAT - NPWAVEFORMAT* = ptr WAVEFORMAT - LPWAVEFORMAT* = ptr WAVEFORMAT - TWAVEFORMAT* = WAVEFORMAT - -const - WAVE_FORMAT_PCM* = 1 - -type - PCMWAVEFORMAT* {.final.} = object - wf*: WAVEFORMAT - wBitsPerSample*: int16 - - PPCMWAVEFORMAT* = ptr PCMWAVEFORMAT - NPPCMWAVEFORMAT* = ptr PCMWAVEFORMAT - LPPCMWAVEFORMAT* = ptr PCMWAVEFORMAT - TPCMWAVEFORMAT* = PCMWAVEFORMAT - WAVEFORMATEX* {.final.} = object - wFormatTag*: int16 - nChannels*: int16 - nSamplesPerSec*: DWORD - nAvgBytesPerSec*: DWORD - nBlockAlign*: int16 - wBitsPerSample*: int16 - cbSize*: int16 - - PWAVEFORMATEX* = ptr WAVEFORMATEX - NPWAVEFORMATEX* = ptr WAVEFORMATEX - LPWAVEFORMATEX* = ptr WAVEFORMATEX - LPCWAVEFORMATEX* = ptr WAVEFORMATEX - TWAVEFORMATEX* = WAVEFORMATEX - HMIDI* = Handle - HMIDIIN* = Handle - HMIDIOUT* = Handle - HMIDISTRM* = Handle - LPHMIDI* = ptr HMIDI - LPHMIDIIN* = ptr HMIDIIN - LPHMIDIOUT* = ptr HMIDIOUT - LPHMIDISTRM* = ptr HMIDISTRM - LPMIDICALLBACK* = PDRVCALLBACK - -const - MIDIPATCHSIZE* = 128 - -type - PATCHARRAY* = array[0..pred(MIDIPATCHSIZE), int16] - LPPATCHARRAY* = ptr int16 - KEYARRAY* = array[0..pred(MIDIPATCHSIZE), int16] - LPKEYARRAY* = ptr int16 - MIDIOUTCAPSA* {.final.} = object - wMid*: int16 - wPid*: int16 - vDriverVersion*: MMVERSION - szPname*: array[0..pred(MAXPNAMELEN), char] - wTechnology*: int16 - wVoices*: int16 - wNotes*: int16 - wChannelMask*: int16 - dwSupport*: DWORD - - PMIDIOUTCAPSA* = ptr MIDIOUTCAPSA - NPMIDIOUTCAPSA* = ptr MIDIOUTCAPSA - LPMIDIOUTCAPSA* = ptr MIDIOUTCAPSA - TMIDIOUTCAPSA* = MIDIOUTCAPSA - MIDIOUTCAPSW* {.final.} = object - wMid*: int16 - wPid*: int16 - vDriverVersion*: MMVERSION - szPname*: array[0..pred(MAXPNAMELEN), Wchar] - wTechnology*: int16 - wVoices*: int16 - wNotes*: int16 - wChannelMask*: int16 - dwSupport*: DWORD - - PMIDIOUTCAPSW* = ptr MIDIOUTCAPSW - NPMIDIOUTCAPSW* = ptr MIDIOUTCAPSW - LPMIDIOUTCAPSW* = ptr MIDIOUTCAPSW - TMIDIOUTCAPSW* = MIDIOUTCAPSW - MIDIINCAPSA* {.final.} = object - wMid*: int16 - wPid*: int16 - vDriverVersion*: MMVERSION - szPname*: array[0..pred(MAXPNAMELEN), char] - dwSupport*: DWORD - - PMIDIINCAPSA* = ptr MIDIINCAPSA - NPMIDIINCAPSA* = ptr MIDIINCAPSA - LPMIDIINCAPSA* = ptr MIDIINCAPSA - TMIDIINCAPSA* = MIDIINCAPSA - MIDIINCAPSW* {.final.} = object - wMid*: int16 - wPid*: int16 - vDriverVersion*: MMVERSION - szPname*: array[0..pred(MAXPNAMELEN), Wchar] - dwSupport*: DWORD - - PMIDIINCAPSW* = ptr MIDIINCAPSW - NPMIDIINCAPSW* = ptr MIDIINCAPSW - LPMIDIINCAPSW* = ptr MIDIINCAPSW - TMIDIINCAPSW* = MIDIINCAPSW - -when defined(UNICODE): - type - MIDIINCAPS* = MIDIINCAPSW - PMIDIINCAPS* = PMIDIINCAPSW - NPMIDIINCAPS* = NPMIDIINCAPSW - LPMIDIINCAPS* = LPMIDIINCAPSW - MIDIOUTCAPS* = MIDIOUTCAPSW - PMIDIOUTCAPS* = PMIDIOUTCAPSW - NPMIDIOUTCAPS* = NPMIDIOUTCAPSW - LPMIDIOUTCAPS* = LPMIDIOUTCAPSW -else: - type - MIDIOUTCAPS* = MIDIOUTCAPSA - PMIDIOUTCAPS* = PMIDIOUTCAPSA - NPMIDIOUTCAPS* = NPMIDIOUTCAPSA - LPMIDIOUTCAPS* = LPMIDIOUTCAPSA - MIDIINCAPS* = MIDIINCAPSA - PMIDIINCAPS* = PMIDIINCAPSA - NPMIDIINCAPS* = NPMIDIINCAPSA - LPMIDIINCAPS* = LPMIDIINCAPSA -type - TMIDIINCAPS* = MIDIINCAPS - PMIDIHDR* = ptr MIDIHDR - MIDIHDR* {.final.} = object - lpData*: cstring - dwBufferLength*: DWORD - dwBytesRecorded*: DWORD - dwUser*: DWORD - dwFlags*: DWORD - lpNext*: PMIDIHDR - reserved*: DWORD - dwOffset*: DWORD - dwReserved*: array[0..pred(8), DWORD] - - NPMIDIHDR* = ptr MIDIHDR - LPMIDIHDR* = ptr MIDIHDR - TMIDIHDR* = MIDIHDR - MIDIEVENT* {.final.} = object - dwDeltaTime*: DWORD - dwStreamID*: DWORD - dwEvent*: DWORD - dwParms*: array[0..pred(1), DWORD] - - TMIDIEVENT* = MIDIEVENT - MIDISTRMBUFFVER* {.final.} = object - dwVersion*: DWORD - dwMid*: DWORD - dwOEMVersion*: DWORD - - TMIDISTRMBUFFVER* = MIDISTRMBUFFVER - Tmidiproptimediv* {.final.} = object - cbStruct*: DWORD - dwTimeDiv*: DWORD - - LPMIDIPROPTIMEDIV* = ptr Tmidiproptimediv - Tmidiproptempo* {.final.} = object - cbStruct*: DWORD - dwTempo*: DWORD - - LPMIDIPROPTEMPO* = ptr Tmidiproptempo - AUXCAPSA* {.final.} = object - wMid*: int16 - wPid*: int16 - vDriverVersion*: MMVERSION - szPname*: array[0..pred(MAXPNAMELEN), char] - wTechnology*: int16 - wReserved1*: int16 - dwSupport*: DWORD - - PAUXCAPSA* = ptr AUXCAPSA - NPAUXCAPSA* = ptr AUXCAPSA - LPAUXCAPSA* = ptr AUXCAPSA - TAUXCAPSA* = AUXCAPSA - AUXCAPSW* {.final.} = object - wMid*: int16 - wPid*: int16 - vDriverVersion*: MMVERSION - szPname*: array[0..pred(MAXPNAMELEN), Wchar] - wTechnology*: int16 - wReserved1*: int16 - dwSupport*: DWORD - - PAUXCAPSW* = ptr AUXCAPSW - NPAUXCAPSW* = ptr AUXCAPSW - LPAUXCAPSW* = ptr AUXCAPSW - TAUXCAPSW* = AUXCAPSW - -when defined(UNICODE): - type - AUXCAPS* = AUXCAPSW - PAUXCAPS* = PAUXCAPSW - NPAUXCAPS* = NPAUXCAPSW - LPAUXCAPS* = LPAUXCAPSW -else: - type - AUXCAPS* = AUXCAPSA - PAUXCAPS* = PAUXCAPSA - NPAUXCAPS* = NPAUXCAPSA - LPAUXCAPS* = LPAUXCAPSA -type - TAUXCAPS* = AUXCAPS - HMIXEROBJ* = Handle - LPHMIXEROBJ* = ptr HMIXEROBJ - HMIXER* = Handle - LPHMIXER* = ptr HMIXER - -proc mixerGetNumDevs*(): uint32{.stdcall, dynlib: "winmm.dll", - importc: "mixerGetNumDevs".} -type - MIXERCAPSA* {.final.} = object - wMid*: int16 - wPid*: int16 - vDriverVersion*: MMVERSION - szPname*: array[0..pred(MAXPNAMELEN), char] - fdwSupport*: DWORD - cDestinations*: DWORD - - PMIXERCAPSA* = ptr MIXERCAPSA - LPMIXERCAPSA* = ptr MIXERCAPSA - TMIXERCAPSA* = MIXERCAPSA - MIXERCAPSW* {.final.} = object - wMid*: int16 - wPid*: int16 - vDriverVersion*: MMVERSION - szPname*: array[0..pred(MAXPNAMELEN), Wchar] - fdwSupport*: DWORD - cDestinations*: DWORD - - PMIXERCAPSW* = ptr MIXERCAPSW - LPMIXERCAPSW* = ptr MIXERCAPSW - TMIXERCAPSW* = MIXERCAPSW - -when defined(UNICODE): - type - MIXERCAPS* = MIXERCAPSW - PMIXERCAPS* = PMIXERCAPSW - LPMIXERCAPS* = LPMIXERCAPSW -else: - type - MIXERCAPS* = MIXERCAPSA - PMIXERCAPS* = PMIXERCAPSA - LPMIXERCAPS* = LPMIXERCAPSA -type - TMIXERCAPS* = MIXERCAPS - MIXERLINEA* {.final.} = object - cbStruct*: DWORD - dwDestination*: DWORD - dwSource*: DWORD - dwLineID*: DWORD - fdwLine*: DWORD - dwUser*: DWORD - dwComponentType*: DWORD - cChannels*: DWORD - cConnections*: DWORD - cControls*: DWORD - szShortName*: array[0..pred(MIXER_SHORT_NAME_CHARS), char] - szName*: array[0..pred(MIXER_LONG_NAME_CHARS), char] - dwType*, dwDeviceID*: DWORD - wMid*, wPid*: int16 - vDriverVersion*: MMVERSION - szPname*: array[0..pred(MAXPNAMELEN), char] - - PMIXERLINEA* = ptr MIXERLINEA - LPMIXERLINEA* = ptr MIXERLINEA - TMIXERLINEA* = MIXERLINEA - MIXERLINEW* {.final.} = object - cbStruct*: DWORD - dwDestination*: DWORD - dwSource*: DWORD - dwLineID*: DWORD - fdwLine*: DWORD - dwUser*: DWORD - dwComponentType*: DWORD - cChannels*: DWORD - cConnections*: DWORD - cControls*: DWORD - szShortName*: array[0..pred(MIXER_SHORT_NAME_CHARS), WCHAR] - szName*: array[0..pred(MIXER_LONG_NAME_CHARS), WCHAR] - dwType*, dwDeviceID*: DWORD - wMid*, wPid*: int16 - vDriverVersion*: MMVERSION - szPname*: array[0..pred(MAXPNAMELEN), WChar] - - TMIXERLINEW* = MIXERLINEW - PMIXERLINEW* = ptr MIXERLINEW - LPMIXERLINEW* = ptr MIXERLINEW - -when defined(UNICODE): - type - MIXERLINE* = MIXERLINEW - PMIXERLINE* = PMIXERLINEW - LPMIXERLINE* = LPMIXERLINEW -else: - type - MIXERLINE* = MIXERLINEA - PMIXERLINE* = PMIXERLINEA - LPMIXERLINE* = LPMIXERLINEA -type - TMIXERLINE* = MIXERLINE - MIXERCONTROLA* {.final.} = object - cbStruct*: DWORD - dwControlID*: DWORD - dwControlType*: DWORD - fdwControl*: DWORD - cMultipleItems*: DWORD - szShortName*: array[0..pred(MIXER_SHORT_NAME_CHARS), char] - szName*: array[0..pred(MIXER_LONG_NAME_CHARS), char] - dwMinimum*, dwMaximum*: DWORD - dwReserved*: array[0..3, DWORD] - cSteps*: DWORD - dwReserved2*: array[0..4, DWORD] - - PMIXERCONTROLA* = ptr MIXERCONTROLA - LPMIXERCONTROLA* = ptr MIXERCONTROLA - TMIXERCONTROLA* = MIXERCONTROLA - MIXERCONTROLW* {.final.} = object - cbStruct*: DWORD - dwControlID*: DWORD - dwControlType*: DWORD - fdwControl*: DWORD - cMultipleItems*: DWORD - szShortName*: array[0..pred(MIXER_SHORT_NAME_CHARS), WCHAR] - szName*: array[0..pred(MIXER_LONG_NAME_CHARS), WCHAR] - dwMinimum*, dwMaximum*: DWORD - dwReserved*: array[0..3, DWORD] - cSteps*: DWORD - dwReserved2*: array[0..4, DWORD] - - PMIXERCONTROLW* = ptr MIXERCONTROLW - LPMIXERCONTROLW* = ptr MIXERCONTROLW - TMIXERCONTROLW* = MIXERCONTROLW - -when defined(UNICODE): - type - MIXERCONTROL* = MIXERCONTROLW - PMIXERCONTROL* = PMIXERCONTROLW - LPMIXERCONTROL* = LPMIXERCONTROLW -else: - type - MIXERCONTROL* = MIXERCONTROLA - PMIXERCONTROL* = PMIXERCONTROLA - LPMIXERCONTROL* = LPMIXERCONTROLA -type - TMIXERCONTROL* = MIXERCONTROL - MIXERLINECONTROLSA* {.final.} = object - cbStruct*: DWORD - dwLineID*: DWORD - dwControlType*, cControls*, cbmxctrl*: DWORD - pamxctrl*: PMIXERCONTROLA - - PMIXERLINECONTROLSA* = ptr MIXERLINECONTROLSA - LPMIXERLINECONTROLSA* = ptr MIXERLINECONTROLSA - TMIXERLINECONTROLSA* = MIXERLINECONTROLSA - MIXERLINECONTROLSW* {.final.} = object - cbStruct*: DWORD - dwLineID*: DWORD - dwControlType*, cControls*, cbmxctrl*: DWORD - pamxctrl*: PMIXERCONTROLW - - PMIXERLINECONTROLSW* = ptr MIXERLINECONTROLSW - LPMIXERLINECONTROLSW* = ptr MIXERLINECONTROLSW - TMIXERLINECONTROLSW* = MIXERLINECONTROLSW - -when defined(UNICODE): - type - MIXERLINECONTROLS* = MIXERLINECONTROLSW - PMIXERLINECONTROLS* = PMIXERLINECONTROLSW - LPMIXERLINECONTROLS* = LPMIXERLINECONTROLSW -else: - type - MIXERLINECONTROLS* = MIXERLINECONTROLSA - PMIXERLINECONTROLS* = PMIXERLINECONTROLSA - LPMIXERLINECONTROLS* = LPMIXERLINECONTROLSA -type - TMIXERLINECONTROLS* = MIXERLINECONTROLS - TMIXERCONTROLDETAILS* {.final.} = object - cbStruct*: DWORD - dwControlID*: DWORD - cChannels*: DWORD - cMultipleItems*, cbDetails*: DWORD - paDetails*: pointer - - MIXERCONTROLDETAILS* = TMIXERCONTROLDETAILS - PMIXERCONTROLDETAILS* = ptr TMIXERCONTROLDETAILS - LPMIXERCONTROLDETAILS* = ptr TMIXERCONTROLDETAILS - MIXERCONTROLDETAILS_LISTTEXTA* {.final.} = object - dwParam1*: DWORD - dwParam2*: DWORD - szName*: array[0..pred(MIXER_LONG_NAME_CHARS), char] - - PMIXERCONTROLDETAILS_LISTTEXTA* = ptr MIXERCONTROLDETAILS_LISTTEXTA - LPMIXERCONTROLDETAILS_LISTTEXTA* = ptr MIXERCONTROLDETAILS_LISTTEXTA - TMIXERCONTROLDETAILS_LISTTEXTA* = MIXERCONTROLDETAILS_LISTTEXTA - MIXERCONTROLDETAILS_LISTTEXTW* {.final.} = object - dwParam1*: DWORD - dwParam2*: DWORD - szName*: array[0..pred(MIXER_LONG_NAME_CHARS), WCHAR] - - PMIXERCONTROLDETAILS_LISTTEXTW* = ptr MIXERCONTROLDETAILS_LISTTEXTW - LPMIXERCONTROLDETAILS_LISTTEXTW* = ptr MIXERCONTROLDETAILS_LISTTEXTW - TMIXERCONTROLDETAILS_LISTTEXTW* = MIXERCONTROLDETAILS_LISTTEXTW - -when defined(UNICODE): - type - MIXERCONTROLDETAILS_LISTTEXT* = MIXERCONTROLDETAILS_LISTTEXTW - PMIXERCONTROLDETAILS_LISTTEXT* = PMIXERCONTROLDETAILS_LISTTEXTW - LPMIXERCONTROLDETAILS_LISTTEXT* = LPMIXERCONTROLDETAILS_LISTTEXTW -else: - type - MIXERCONTROLDETAILS_LISTTEXT* = MIXERCONTROLDETAILS_LISTTEXTA - PMIXERCONTROLDETAILS_LISTTEXT* = PMIXERCONTROLDETAILS_LISTTEXTA - LPMIXERCONTROLDETAILS_LISTTEXT* = LPMIXERCONTROLDETAILS_LISTTEXTA -type - TMIXERCONTROLDETAILS_LISTTEXT* = MIXERCONTROLDETAILS_LISTTEXT - MIXERCONTROLDETAILS_BOOLEAN* {.final.} = object - fValue*: int32 - - PMIXERCONTROLDETAILS_BOOLEAN* = ptr MIXERCONTROLDETAILS_BOOLEAN - LPMIXERCONTROLDETAILS_BOOLEAN* = ptr MIXERCONTROLDETAILS_BOOLEAN - TMIXERCONTROLDETAILS_BOOLEAN* = MIXERCONTROLDETAILS_BOOLEAN - MIXERCONTROLDETAILS_SIGNED* {.final.} = object - lValue*: int32 - - PMIXERCONTROLDETAILS_SIGNED* = ptr MIXERCONTROLDETAILS_SIGNED - LPMIXERCONTROLDETAILS_SIGNED* = ptr MIXERCONTROLDETAILS_SIGNED - TMIXERCONTROLDETAILS_SIGNED* = MIXERCONTROLDETAILS_SIGNED - MIXERCONTROLDETAILS_UNSIGNED* {.final.} = object - dwValue*: DWORD - - PMIXERCONTROLDETAILS_UNSIGNED* = ptr MIXERCONTROLDETAILS_UNSIGNED - LPMIXERCONTROLDETAILS_UNSIGNED* = ptr MIXERCONTROLDETAILS_UNSIGNED - TMIXERCONTROLDETAILS_UNSIGNED* = MIXERCONTROLDETAILS_UNSIGNED - LPTIMECALLBACK* = proc (uTimerID, uMsg: uint32, dwUser, dw1, dw2: DWORD){. - stdcall.} - TTIMECALLBACK* = LPTIMECALLBACK - TIMECAPS* {.final.} = object - wPeriodMin*: uint32 - wPeriodMax*: uint32 - - PTIMECAPS* = ptr TIMECAPS - NPTIMECAPS* = ptr TIMECAPS - LPTIMECAPS* = ptr TIMECAPS - TTIMECAS* = TIMECAPS - JOYCAPSA* {.final.} = object - wMid*: int16 - wPid*: int16 - szPname*: array[0..pred(MAXPNAMELEN), char] - wXmin*: uint32 - wXmax*: uint32 - wYmin*: uint32 - wYmax*: uint32 - wZmin*: uint32 - wZmax*: uint32 - wNumButtons*: uint32 - wPeriodMin*: uint32 - wPeriodMax*: uint32 - wRmin*: uint32 - wRmax*: uint32 - wUmin*: uint32 - wUmax*: uint32 - wVmin*: uint32 - wVmax*: uint32 - wCaps*: uint32 - wMaxAxes*: uint32 - wNumAxes*: uint32 - wMaxButtons*: uint32 - szRegKey*: array[0..pred(MAXPNAMELEN), char] - szOEMVxD*: array[0..pred(MAX_JOYSTICKOEMVXDNAME), char] - - PJOYCAPSA* = ptr JOYCAPSA - NPJOYCAPSA* = ptr JOYCAPSA - LPJOYCAPSA* = ptr JOYCAPSA - TJOYCAPSA* = JOYCAPSA - JOYCAPSW* {.final.} = object - wMid*: int16 - wPid*: int16 - szPname*: array[0..pred(MAXPNAMELEN), WCHAR] - wXmin*: uint32 - wXmax*: uint32 - wYmin*: uint32 - wYmax*: uint32 - wZmin*: uint32 - wZmax*: uint32 - wNumButtons*: uint32 - wPeriodMin*: uint32 - wPeriodMax*: uint32 - wRmin*: uint32 - wRmax*: uint32 - wUmin*: uint32 - wUmax*: uint32 - wVmin*: uint32 - wVmax*: uint32 - wCaps*: uint32 - wMaxAxes*: uint32 - wNumAxes*: uint32 - wMaxButtons*: uint32 - szRegKey*: array[0..pred(MAXPNAMELEN), WCHAR] - szOEMVxD*: array[0..pred(MAX_JOYSTICKOEMVXDNAME), WCHAR] - - PJOYCAPSW* = ptr JOYCAPSW - NPJOYCAPSW* = ptr JOYCAPSW - LPJOYCAPSW* = ptr JOYCAPSW - TJOYCAPSW* = JOYCAPSW - -when defined(UNICODE): - type - JOYCAPS* = JOYCAPSW - PJOYCAPS* = PJOYCAPSW - NPJOYCAPS* = NPJOYCAPSW - LPJOYCAPS* = LPJOYCAPSW -else: - type - JOYCAPS* = JOYCAPSA - PJOYCAPS* = PJOYCAPSA - NPJOYCAPS* = NPJOYCAPSA - LPJOYCAPS* = LPJOYCAPSA -type - TJOYCAPS* = JOYCAPS - JOYINFO* {.final.} = object - wXpos*: uint32 - wYpos*: uint32 - wZpos*: uint32 - wButtons*: uint32 - - PJOYINFO* = ptr JOYINFO - NPJOYINFO* = ptr JOYINFO - LPJOYINFO* = ptr JOYINFO - TJOYINFO* = JOYINFO - JOYINFOEX* {.final.} = object - dwSize*: DWORD - dwFlags*: DWORD - wXpos*: uint32 - wYpos*: uint32 - wZpos*: uint32 - dwRpos*: DWORD - dwUpos*: DWORD - dwVpos*: DWORD - wButtons*: uint32 - dwButtonNumber*: DWORD - dwPOV*: DWORD - dwReserved1*: DWORD - dwReserved2*: DWORD - - PJOYINFOEX* = ptr JOYINFOEX - NPJOYINFOEX* = ptr JOYINFOEX - LPJOYINFOEX* = ptr JOYINFOEX - TJOYINFOEX* = JOYINFOEX - FOURCC* = DWORD - HPSTR* = cstring - HMMIO* = Handle - LPMMIOPROC* = proc (x1: LPSTR, x2: uint32, x3, x4: LPARAM): LRESULT{.stdcall.} - TMMIOPROC* = LPMMIOPROC - MMIOINFO* {.final.} = object - dwFlags*: DWORD - fccIOProc*: FOURCC - pIOProc*: LPMMIOPROC - wErrorRet*: uint32 - htask*: HTASK - cchBuffer*: int32 - pchBuffer*: HPSTR - pchNext*: HPSTR - pchEndRead*: HPSTR - pchEndWrite*: HPSTR - lBufOffset*: int32 - lDiskOffset*: int32 - adwInfo*: array[0..pred(3), DWORD] - dwReserved1*: DWORD - dwReserved2*: DWORD - hmmio*: HMMIO - - PMMIOINFO* = ptr MMIOINFO - NPMMIOINFO* = ptr MMIOINFO - LPMMIOINFO* = ptr MMIOINFO - LPCMMIOINFO* = ptr MMIOINFO - TMMIOINFO* = MMIOINFO - MMCKINFO* {.final.} = object - ckid*: FOURCC - cksize*: DWORD - fccType*: FOURCC - dwDataOffset*: DWORD - dwFlags*: DWORD - - PMMCKINFO* = ptr MMCKINFO - NPMMCKINFO* = ptr MMCKINFO - LPMMCKINFO* = ptr MMCKINFO - LPCMMCKINFO* = ptr MMCKINFO - TMMCKINFO* = MMCKINFO - MCIERROR* = DWORD - MCIDEVICEID* = uint32 - YIELDPROC* = proc (mciId: MCIDEVICEID, dwYieldData: DWORD): uint32{.stdcall.} - TYIELDPROC* = YIELDPROC - MCI_GENERIC_PARMS* {.final.} = object - dwCallback*: DWORD - - PMCI_GENERIC_PARMS* = ptr MCI_GENERIC_PARMS - LPMCI_GENERIC_PARMS* = ptr MCI_GENERIC_PARMS - TMCI_GENERIC_PARMS* = MCI_GENERIC_PARMS - MCI_OPEN_PARMSA* {.final.} = object - dwCallback*: DWORD - wDeviceID*: MCIDEVICEID - lpstrDeviceType*: LPCSTR - lpstrElementName*: LPCSTR - lpstrAlias*: LPCSTR - - PMCI_OPEN_PARMSA* = ptr MCI_OPEN_PARMSA - LPMCI_OPEN_PARMSA* = ptr MCI_OPEN_PARMSA - TMCI_OPEN_PARMSA* = MCI_OPEN_PARMSA - MCI_OPEN_PARMSW* {.final.} = object - dwCallback*: DWORD - wDeviceID*: MCIDEVICEID - lpstrDeviceType*: LPCWSTR - lpstrElementName*: LPCWSTR - lpstrAlias*: LPCWSTR - - PMCI_OPEN_PARMSW* = ptr MCI_OPEN_PARMSW - LPMCI_OPEN_PARMSW* = ptr MCI_OPEN_PARMSW - TMCI_OPEN_PARMSW* = MCI_OPEN_PARMSW - -when defined(UNICODE): - type - MCI_OPEN_PARMS* = MCI_OPEN_PARMSW - PMCI_OPEN_PARMS* = PMCI_OPEN_PARMSW - LPMCI_OPEN_PARMS* = LPMCI_OPEN_PARMSW -else: - type - MCI_OPEN_PARMS* = MCI_OPEN_PARMSA - PMCI_OPEN_PARMS* = PMCI_OPEN_PARMSA - LPMCI_OPEN_PARMS* = LPMCI_OPEN_PARMSA -type - TMCI_OPEN_PARMS* = MCI_OPEN_PARMS - MCI_PLAY_PARMS* {.final.} = object - dwCallback*: DWORD - dwFrom*: DWORD - dwTo*: DWORD - - PMCI_PLAY_PARMS* = ptr MCI_PLAY_PARMS - LPMCI_PLAY_PARMS* = ptr MCI_PLAY_PARMS - TMCI_PLAY_PARMS* = MCI_PLAY_PARMS - MCI_SEEK_PARMS* {.final.} = object - dwCallback*: DWORD - dwTo*: DWORD - - PMCI_SEEK_PARMS* = ptr MCI_SEEK_PARMS - LPMCI_SEEK_PARMS* = ptr MCI_SEEK_PARMS - TMCI_SEEK_PARMS* = MCI_SEEK_PARMS - MCI_STATUS_PARMS* {.final.} = object - dwCallback*: DWORD - dwReturn*: DWORD - dwItem*: DWORD - dwTrack*: DWORD - - PMCI_STATUS_PARMS* = ptr MCI_STATUS_PARMS - LPMCI_STATUS_PARMS* = ptr MCI_STATUS_PARMS - TMCI_STATUS_PARMS* = MCI_STATUS_PARMS - MCI_INFO_PARMSA* {.final.} = object - dwCallback*: DWORD - lpstrReturn*: cstring - dwRetSize*: DWORD - - LPMCI_INFO_PARMSA* = ptr MCI_INFO_PARMSA - TMCI_INFO_PARMSA* = MCI_INFO_PARMSA - MCI_INFO_PARMSW* {.final.} = object - dwCallback*: DWORD - lpstrReturn*: LPWSTR - dwRetSize*: DWORD - - LPMCI_INFO_PARMSW* = ptr MCI_INFO_PARMSW - TMCI_INFO_PARMSW* = MCI_INFO_PARMSW - -when defined(UNICODE): - type - MCI_INFO_PARMS* = MCI_INFO_PARMSW - LPMCI_INFO_PARMS* = LPMCI_INFO_PARMSW -else: - type - MCI_INFO_PARMS* = MCI_INFO_PARMSA - LPMCI_INFO_PARMS* = LPMCI_INFO_PARMSA -type - TMCI_INFO_PARMS* = MCI_INFO_PARMS - MCI_GETDEVCAPS_PARMS* {.final.} = object - dwCallback*: DWORD - dwReturn*: DWORD - dwItem*: DWORD - - PMCI_GETDEVCAPS_PARMS* = ptr MCI_GETDEVCAPS_PARMS - LPMCI_GETDEVCAPS_PARMS* = ptr MCI_GETDEVCAPS_PARMS - TMCI_GETDEVCAPS_PARMS* = MCI_GETDEVCAPS_PARMS - MCI_SYSINFO_PARMSA* {.final.} = object - dwCallback*: DWORD - lpstrReturn*: cstring - dwRetSize*: DWORD - dwNumber*: DWORD - wDeviceType*: uint32 - - PMCI_SYSINFO_PARMSA* = ptr MCI_SYSINFO_PARMSA - LPMCI_SYSINFO_PARMSA* = ptr MCI_SYSINFO_PARMSA - TMCI_SYSINFO_PARMSA* = MCI_SYSINFO_PARMSA - MCI_SYSINFO_PARMSW* {.final.} = object - dwCallback*: DWORD - lpstrReturn*: LPWSTR - dwRetSize*: DWORD - dwNumber*: DWORD - wDeviceType*: uint32 - - PMCI_SYSINFO_PARMSW* = ptr MCI_SYSINFO_PARMSW - LPMCI_SYSINFO_PARMSW* = ptr MCI_SYSINFO_PARMSW - TMCI_SYSINFO_PARMSW* = MCI_SYSINFO_PARMSW - -when defined(UNICODE): - type - MCI_SYSINFO_PARMS* = MCI_SYSINFO_PARMSW - PMCI_SYSINFO_PARMS* = PMCI_SYSINFO_PARMSW - LPMCI_SYSINFO_PARMS* = LPMCI_SYSINFO_PARMSW -else: - type - MCI_SYSINFO_PARMS* = MCI_SYSINFO_PARMSA - PMCI_SYSINFO_PARMS* = PMCI_SYSINFO_PARMSA - LPMCI_SYSINFO_PARMS* = LPMCI_SYSINFO_PARMSA -type - TMCI_SYSINFO_PARMS* = MCI_SYSINFO_PARMS - MCI_SET_PARMS* {.final.} = object - dwCallback*: DWORD - dwTimeFormat*: DWORD - dwAudio*: DWORD - - PMCI_SET_PARMS* = ptr MCI_SET_PARMS - LPMCI_SET_PARMS* = ptr MCI_SET_PARMS - TMCI_SET_PARMS* = MCI_SET_PARMS - MCI_BREAK_PARMS* {.final.} = object - dwCallback*: DWORD - nVirtKey*: int32 - hwndBreak*: HWND - - PMCI_BREAK_PARMS* = ptr MCI_BREAK_PARMS - LPMCI_BREAK_PARMS* = ptr MCI_BREAK_PARMS - TMCI_BREAK_PARMS* = MCI_BREAK_PARMS - MCI_SAVE_PARMSA* {.final.} = object - dwCallback*: DWORD - lpfilename*: LPCSTR - - PMCI_SAVE_PARMSA* = ptr MCI_SAVE_PARMSA - LPMCI_SAVE_PARMSA* = ptr MCI_SAVE_PARMSA - TMCI_SAVE_PARMSA* = MCI_SAVE_PARMSA - MCI_SAVE_PARMSW* {.final.} = object - dwCallback*: DWORD - lpfilename*: LPCWSTR - - PMCI_SAVE_PARMSW* = ptr MCI_SAVE_PARMSW - LPMCI_SAVE_PARMSW* = ptr MCI_SAVE_PARMSW - TMCI_SAVE_PARMSW* = MCI_SAVE_PARMSW - -when defined(UNICODE): - type - MCI_SAVE_PARMS* = MCI_SAVE_PARMSW - PMCI_SAVE_PARMS* = PMCI_SAVE_PARMSW - LPMCI_SAVE_PARMS* = LPMCI_SAVE_PARMSW -else: - type - MCI_SAVE_PARMS* = MCI_SAVE_PARMSA - PMCI_SAVE_PARMS* = PMCI_SAVE_PARMSA - LPMCI_SAVE_PARMS* = LPMCI_SAVE_PARMSA -type - TMCI_SAVE_PARMS* = MCI_SAVE_PARMS - MCI_LOAD_PARMSA* {.final.} = object - dwCallback*: DWORD - lpfilename*: LPCSTR - - PMCI_LOAD_PARMSA* = ptr MCI_LOAD_PARMSA - LPMCI_LOAD_PARMSA* = ptr MCI_LOAD_PARMSA - TMCI_LOAD_PARMSA* = MCI_LOAD_PARMSA - MCI_LOAD_PARMSW* {.final.} = object - dwCallback*: DWORD - lpfilename*: LPCWSTR - - PMCI_LOAD_PARMSW* = ptr MCI_LOAD_PARMSW - LPMCI_LOAD_PARMSW* = ptr MCI_LOAD_PARMSW - TMCI_LOAD_PARMSW* = MCI_LOAD_PARMSW - -when defined(UNICODE): - type - MCI_LOAD_PARMS* = MCI_LOAD_PARMSW - PMCI_LOAD_PARMS* = PMCI_LOAD_PARMSW - LPMCI_LOAD_PARMS* = LPMCI_LOAD_PARMSW -else: - type - MCI_LOAD_PARMS* = MCI_LOAD_PARMSA - PMCI_LOAD_PARMS* = PMCI_LOAD_PARMSA - LPMCI_LOAD_PARMS* = LPMCI_LOAD_PARMSA -type - TMCI_LOAD_PARMS* = MCI_LOAD_PARMS - MCI_RECORD_PARMS* {.final.} = object - dwCallback*: DWORD - dwFrom*: DWORD - dwTo*: DWORD - - LPMCI_RECORD_PARMS* = ptr MCI_RECORD_PARMS - TMCI_RECORD_PARMS* = MCI_RECORD_PARMS - MCI_VD_PLAY_PARMS* {.final.} = object - dwCallback*: DWORD - dwFrom*: DWORD - dwTo*: DWORD - dwSpeed*: DWORD - - PMCI_VD_PLAY_PARMS* = ptr MCI_VD_PLAY_PARMS - LPMCI_VD_PLAY_PARMS* = ptr MCI_VD_PLAY_PARMS - TMCI_VD_PLAY_PARMS* = MCI_VD_PLAY_PARMS - MCI_VD_STEP_PARMS* {.final.} = object - dwCallback*: DWORD - dwFrames*: DWORD - - PMCI_VD_STEP_PARMS* = ptr MCI_VD_STEP_PARMS - LPMCI_VD_STEP_PARMS* = ptr MCI_VD_STEP_PARMS - MCI_VD_ESCAPE_PARMSA* {.final.} = object - dwCallback*: DWORD - lpstrCommand*: LPCSTR - - PMCI_VD_ESCAPE_PARMSA* = ptr MCI_VD_ESCAPE_PARMSA - LPMCI_VD_ESCAPE_PARMSA* = ptr MCI_VD_ESCAPE_PARMSA - TMCI_VD_ESCAPE_PARMSA* = MCI_VD_ESCAPE_PARMSA - MCI_VD_ESCAPE_PARMSW* {.final.} = object - dwCallback*: DWORD - lpstrCommand*: LPCWSTR - - PMCI_VD_ESCAPE_PARMSW* = ptr MCI_VD_ESCAPE_PARMSW - LPMCI_VD_ESCAPE_PARMSW* = ptr MCI_VD_ESCAPE_PARMSW - TMCI_VD_ESCAPE_PARMSW* = MCI_VD_ESCAPE_PARMSW - -when defined(UNICODE): - type - MCI_VD_ESCAPE_PARMS* = MCI_VD_ESCAPE_PARMSW - PMCI_VD_ESCAPE_PARMS* = PMCI_VD_ESCAPE_PARMSW - LPMCI_VD_ESCAPE_PARMS* = LPMCI_VD_ESCAPE_PARMSW -else: - type - MCI_VD_ESCAPE_PARMS* = MCI_VD_ESCAPE_PARMSA - PMCI_VD_ESCAPE_PARMS* = PMCI_VD_ESCAPE_PARMSA - LPMCI_VD_ESCAPE_PARMS* = LPMCI_VD_ESCAPE_PARMSA -type - TMCI_VD_ESCAPE_PARMS* = MCI_VD_ESCAPE_PARMS - MCI_WAVE_OPEN_PARMSA* {.final.} = object - dwCallback*: DWORD - wDeviceID*: MCIDEVICEID - lpstrDeviceType*: LPCSTR - lpstrElementName*: LPCSTR - lpstrAlias*: LPCSTR - dwBufferSeconds*: DWORD - - PMCI_WAVE_OPEN_PARMSA* = ptr MCI_WAVE_OPEN_PARMSA - LPMCI_WAVE_OPEN_PARMSA* = ptr MCI_WAVE_OPEN_PARMSA - TMCI_WAVE_OPEN_PARMSA* = MCI_WAVE_OPEN_PARMSA - MCI_WAVE_OPEN_PARMSW* {.final.} = object - dwCallback*: DWORD - wDeviceID*: MCIDEVICEID - lpstrDeviceType*: LPCWSTR - lpstrElementName*: LPCWSTR - lpstrAlias*: LPCWSTR - dwBufferSeconds*: DWORD - - PMCI_WAVE_OPEN_PARMSW* = ptr MCI_WAVE_OPEN_PARMSW - LPMCI_WAVE_OPEN_PARMSW* = ptr MCI_WAVE_OPEN_PARMSW - TMCI_WAVE_OPEN_PARMSW* = MCI_WAVE_OPEN_PARMSW - -when defined(UNICODE): - type - MCI_WAVE_OPEN_PARMS* = MCI_WAVE_OPEN_PARMSW - PMCI_WAVE_OPEN_PARMS* = PMCI_WAVE_OPEN_PARMSW - LPMCI_WAVE_OPEN_PARMS* = LPMCI_WAVE_OPEN_PARMSW -else: - type - MCI_WAVE_OPEN_PARMS* = MCI_WAVE_OPEN_PARMSA - PMCI_WAVE_OPEN_PARMS* = PMCI_WAVE_OPEN_PARMSA - LPMCI_WAVE_OPEN_PARMS* = LPMCI_WAVE_OPEN_PARMSA -type - TMCI_WAVE_OPEN_PARMS* = MCI_WAVE_OPEN_PARMS - MCI_WAVE_DELETE_PARMS* {.final.} = object - dwCallback*: DWORD - dwFrom*: DWORD - dwTo*: DWORD - - PMCI_WAVE_DELETE_PARMS* = ptr MCI_WAVE_DELETE_PARMS - LPMCI_WAVE_DELETE_PARMS* = ptr MCI_WAVE_DELETE_PARMS - TMCI_WAVE_DELETE_PARMS* = MCI_WAVE_DELETE_PARMS - MCI_WAVE_SET_PARMS* {.final.} = object - dwCallback*: DWORD - dwTimeFormat*: DWORD - dwAudio*: DWORD - wInput*: uint32 - wOutput*: uint32 - wFormatTag*: int16 - wReserved2*: int16 - nChannels*: int16 - wReserved3*: int16 - nSamplesPerSec*: DWORD - nAvgBytesPerSec*: DWORD - nBlockAlign*: int16 - wReserved4*: int16 - wBitsPerSample*: int16 - wReserved5*: int16 - - PMCI_WAVE_SET_PARMS* = ptr MCI_WAVE_SET_PARMS - LPMCI_WAVE_SET_PARMS* = ptr MCI_WAVE_SET_PARMS - TMCI_WAVE_SET_PARMS* = MCI_WAVE_SET_PARMS - MCI_SEQ_SET_PARMS* {.final.} = object - dwCallback*: DWORD - dwTimeFormat*: DWORD - dwAudio*: DWORD - dwTempo*: DWORD - dwPort*: DWORD - dwSlave*: DWORD - dwMaster*: DWORD - dwOffset*: DWORD - - PMCI_SEQ_SET_PARMS* = ptr MCI_SEQ_SET_PARMS - LPMCI_SEQ_SET_PARMS* = ptr MCI_SEQ_SET_PARMS - TMCI_SEQ_SET_PARMS* = MCI_SEQ_SET_PARMS - MCI_ANIM_OPEN_PARMSA* {.final.} = object - dwCallback*: DWORD - wDeviceID*: MCIDEVICEID - lpstrDeviceType*: LPCSTR - lpstrElementName*: LPCSTR - lpstrAlias*: LPCSTR - dwStyle*: DWORD - hWndParent*: HWND - - PMCI_ANIM_OPEN_PARMSA* = ptr MCI_ANIM_OPEN_PARMSA - LPMCI_ANIM_OPEN_PARMSA* = ptr MCI_ANIM_OPEN_PARMSA - TMCI_ANIM_OPEN_PARMSA* = MCI_ANIM_OPEN_PARMSA - MCI_ANIM_OPEN_PARMSW* {.final.} = object - dwCallback*: DWORD - wDeviceID*: MCIDEVICEID - lpstrDeviceType*: LPCWSTR - lpstrElementName*: LPCWSTR - lpstrAlias*: LPCWSTR - dwStyle*: DWORD - hWndParent*: HWND - - PMCI_ANIM_OPEN_PARMSW* = ptr MCI_ANIM_OPEN_PARMSW - LPMCI_ANIM_OPEN_PARMSW* = ptr MCI_ANIM_OPEN_PARMSW - -when defined(UNICODE): - type - MCI_ANIM_OPEN_PARMS* = MCI_ANIM_OPEN_PARMSW - PMCI_ANIM_OPEN_PARMS* = PMCI_ANIM_OPEN_PARMSW - LPMCI_ANIM_OPEN_PARMS* = LPMCI_ANIM_OPEN_PARMSW -else: - type - MCI_ANIM_OPEN_PARMS* = MCI_ANIM_OPEN_PARMSA - PMCI_ANIM_OPEN_PARMS* = PMCI_ANIM_OPEN_PARMSA - LPMCI_ANIM_OPEN_PARMS* = LPMCI_ANIM_OPEN_PARMSA -type - TMCI_ANIM_OPEN_PARMS* = MCI_ANIM_OPEN_PARMS - MCI_ANIM_WINDOW_PARMSW* {.final.} = object - dwCallback*: DWORD - hWnd*: HWND - nCmdShow*: uint32 - lpstrText*: LPCWSTR - - PMCI_ANIM_WINDOW_PARMSW* = ptr MCI_ANIM_WINDOW_PARMSW - LPMCI_ANIM_WINDOW_PARMSW* = ptr MCI_ANIM_WINDOW_PARMSW - TMCI_ANIM_WINDOW_PARMSW* = MCI_ANIM_WINDOW_PARMSW - MCI_ANIM_STEP_PARMS* {.final.} = object - dwCallback*: DWORD - dwFrames*: DWORD - - PMCI_ANIM_STEP_PARMS* = ptr MCI_ANIM_STEP_PARMS - LPMCI_ANIM_STEP_PARMS* = ptr MCI_ANIM_STEP_PARMS - TMCI_ANIM_STEP_PARMS* = MCI_ANIM_STEP_PARMS - MCI_ANIM_WINDOW_PARMSA* {.final.} = object - dwCallback*: DWORD - hWnd*: HWND - nCmdShow*: uint32 - lpstrText*: LPCSTR - - PMCI_ANIM_WINDOW_PARMSA* = ptr MCI_ANIM_WINDOW_PARMSA - LPMCI_ANIM_WINDOW_PARMSA* = ptr MCI_ANIM_WINDOW_PARMSA - TMCI_ANIM_WINDOW_PARMSA* = MCI_ANIM_WINDOW_PARMSA - MCI_ANIM_PLAY_PARMS* {.final.} = object - dwCallback*: DWORD - dwFrom*: DWORD - dwTo*: DWORD - dwSpeed*: DWORD - - PMCI_ANIM_PLAY_PARMS* = ptr MCI_ANIM_PLAY_PARMS - LPMCI_ANIM_PLAY_PARMS* = ptr MCI_ANIM_PLAY_PARMS - -when defined(UNICODE): - type - MCI_ANIM_WINDOW_PARMS* = MCI_ANIM_WINDOW_PARMSW - PMCI_ANIM_WINDOW_PARMS* = PMCI_ANIM_WINDOW_PARMSW - LPMCI_ANIM_WINDOW_PARMS* = LPMCI_ANIM_WINDOW_PARMSW -else: - type - MCI_ANIM_WINDOW_PARMS* = MCI_ANIM_WINDOW_PARMSA - PMCI_ANIM_WINDOW_PARMS* = PMCI_ANIM_WINDOW_PARMSA - LPMCI_ANIM_WINDOW_PARMS* = LPMCI_ANIM_WINDOW_PARMSA -type - MCI_ANIM_RECT_PARMS* {.final.} = object - dwCallback*: DWORD - rc*: RECT - - PMCI_ANIM_RECT_PARMS* = ptr MCI_ANIM_RECT_PARMS - LPMCI_ANIM_RECT_PARMS* = ptr MCI_ANIM_RECT_PARMS - TMCI_ANIM_RECT_PARMS* = MCI_ANIM_RECT_PARMS - MCI_ANIM_UPDATE_PARMS* {.final.} = object - dwCallback*: DWORD - rc*: RECT - hDC*: HDC - - PMCI_ANIM_UPDATE_PARMS* = ptr MCI_ANIM_UPDATE_PARMS - LPMCI_ANIM_UPDATE_PARMS* = ptr MCI_ANIM_UPDATE_PARMS - TMCI_ANIM_UPDATE_PARMS* = MCI_ANIM_UPDATE_PARMS - MCI_OVLY_OPEN_PARMSA* {.final.} = object - dwCallback*: DWORD - wDeviceID*: MCIDEVICEID - lpstrDeviceType*: LPCSTR - lpstrElementName*: LPCSTR - lpstrAlias*: LPCSTR - dwStyle*: DWORD - hWndParent*: HWND - - PMCI_OVLY_OPEN_PARMSA* = ptr MCI_OVLY_OPEN_PARMSA - LPMCI_OVLY_OPEN_PARMSA* = ptr MCI_OVLY_OPEN_PARMSA - TMCI_OVLY_OPEN_PARMSA* = MCI_OVLY_OPEN_PARMSA - MCI_OVLY_OPEN_PARMSW* {.final.} = object - dwCallback*: DWORD - wDeviceID*: MCIDEVICEID - lpstrDeviceType*: LPCWSTR - lpstrElementName*: LPCWSTR - lpstrAlias*: LPCWSTR - dwStyle*: DWORD - hWndParent*: HWND - - PMCI_OVLY_OPEN_PARMSW* = ptr MCI_OVLY_OPEN_PARMSW - LPMCI_OVLY_OPEN_PARMSW* = ptr MCI_OVLY_OPEN_PARMSW - TMCI_OVLY_OPEN_PARMSW* = MCI_OVLY_OPEN_PARMSW - -when defined(UNICODE): - type - MCI_OVLY_OPEN_PARMS* = MCI_OVLY_OPEN_PARMSW - PMCI_OVLY_OPEN_PARMS* = PMCI_OVLY_OPEN_PARMSW - LPMCI_OVLY_OPEN_PARMS* = LPMCI_OVLY_OPEN_PARMSW -else: - type - MCI_OVLY_OPEN_PARMS* = MCI_OVLY_OPEN_PARMSA - PMCI_OVLY_OPEN_PARMS* = PMCI_OVLY_OPEN_PARMSA - LPMCI_OVLY_OPEN_PARMS* = LPMCI_OVLY_OPEN_PARMSA -type - TMCI_OVLY_OPEN_PARMS* = MCI_OVLY_OPEN_PARMS - MCI_OVLY_WINDOW_PARMSA* {.final.} = object - dwCallback*: DWORD - hWnd*: HWND - nCmdShow*: uint32 - lpstrText*: LPCSTR - - PMCI_OVLY_WINDOW_PARMSA* = ptr MCI_OVLY_WINDOW_PARMSA - LPMCI_OVLY_WINDOW_PARMSA* = ptr MCI_OVLY_WINDOW_PARMSA - TMCI_OVLY_WINDOW_PARMSA* = MCI_OVLY_WINDOW_PARMSA - MCI_OVLY_WINDOW_PARMSW* {.final.} = object - dwCallback*: DWORD - hWnd*: HWND - nCmdShow*: uint32 - lpstrText*: LPCWSTR - - PMCI_OVLY_WINDOW_PARMSW* = ptr MCI_OVLY_WINDOW_PARMSW - LPMCI_OVLY_WINDOW_PARMSW* = ptr MCI_OVLY_WINDOW_PARMSW - TMCI_OVLY_WINDOW_PARMSW* = MCI_OVLY_WINDOW_PARMSW - -when defined(UNICODE): - type - MCI_OVLY_WINDOW_PARMS* = MCI_OVLY_WINDOW_PARMSW - PMCI_OVLY_WINDOW_PARMS* = PMCI_OVLY_WINDOW_PARMSW - LPMCI_OVLY_WINDOW_PARMS* = LPMCI_OVLY_WINDOW_PARMSW -else: - type - MCI_OVLY_WINDOW_PARMS* = MCI_OVLY_WINDOW_PARMSA - PMCI_OVLY_WINDOW_PARMS* = PMCI_OVLY_WINDOW_PARMSA - LPMCI_OVLY_WINDOW_PARMS* = LPMCI_OVLY_WINDOW_PARMSA -type - TMCI_OVLY_WINDOW_PARMS* = MCI_OVLY_WINDOW_PARMSW - MCI_OVLY_RECT_PARMS* {.final.} = object - dwCallback*: DWORD - rc*: RECT - - PMCI_OVLY_RECT_PARMS* = ptr MCI_OVLY_RECT_PARMS - LPMCI_OVLY_RECT_PARMS* = ptr MCI_OVLY_RECT_PARMS - TMCI_OVLY_RECT_PARMS* = MCI_OVLY_RECT_PARMS - MCI_OVLY_SAVE_PARMSA* {.final.} = object - dwCallback*: DWORD - lpfilename*: LPCSTR - rc*: RECT - - PMCI_OVLY_SAVE_PARMSA* = ptr MCI_OVLY_SAVE_PARMSA - LPMCI_OVLY_SAVE_PARMSA* = ptr MCI_OVLY_SAVE_PARMSA - TMCI_OVLY_SAVE_PARMSA* = MCI_OVLY_SAVE_PARMSA - MCI_OVLY_SAVE_PARMSW* {.final.} = object - dwCallback*: DWORD - lpfilename*: LPCWSTR - rc*: RECT - - PMCI_OVLY_SAVE_PARMSW* = ptr MCI_OVLY_SAVE_PARMSW - LPMCI_OVLY_SAVE_PARMSW* = ptr MCI_OVLY_SAVE_PARMSW - TMCI_OVLY_SAVE_PARMSW* = MCI_OVLY_SAVE_PARMSW - -when defined(UNICODE): - type - MCI_OVLY_SAVE_PARMS* = MCI_OVLY_SAVE_PARMSW - PMCI_OVLY_SAVE_PARMS* = PMCI_OVLY_SAVE_PARMSW - LPMCI_OVLY_SAVE_PARMS* = LPMCI_OVLY_SAVE_PARMSW -else: - type - MCI_OVLY_SAVE_PARMS* = MCI_OVLY_SAVE_PARMSA - PMCI_OVLY_SAVE_PARMS* = PMCI_OVLY_SAVE_PARMSA - LPMCI_OVLY_SAVE_PARMS* = LPMCI_OVLY_SAVE_PARMSA -type - TMCI_OVLY_SAVE_PARMS* = MCI_OVLY_SAVE_PARMS - MCI_OVLY_LOAD_PARMSA* {.final.} = object - dwCallback*: DWORD - lpfilename*: LPCSTR - rc*: RECT - - PMCI_OVLY_LOAD_PARMSA* = ptr MCI_OVLY_LOAD_PARMSA - LPMCI_OVLY_LOAD_PARMSA* = ptr MCI_OVLY_LOAD_PARMSA - TMCI_OVLY_LOAD_PARMSA* = MCI_OVLY_LOAD_PARMSA - MCI_OVLY_LOAD_PARMSW* {.final.} = object - dwCallback*: DWORD - lpfilename*: LPCWSTR - rc*: RECT - - PMCI_OVLY_LOAD_PARMSW* = ptr MCI_OVLY_LOAD_PARMSW - LPMCI_OVLY_LOAD_PARMSW* = ptr MCI_OVLY_LOAD_PARMSW - TMCI_OVLY_LOAD_PARMSW* = MCI_OVLY_LOAD_PARMSW - -when defined(UNICODE): - type - MCI_OVLY_LOAD_PARMS* = MCI_OVLY_LOAD_PARMSW - PMCI_OVLY_LOAD_PARMS* = PMCI_OVLY_LOAD_PARMSW - LPMCI_OVLY_LOAD_PARMS* = LPMCI_OVLY_LOAD_PARMSW -else: - type - MCI_OVLY_LOAD_PARMS* = MCI_OVLY_LOAD_PARMSA - PMCI_OVLY_LOAD_PARMS* = PMCI_OVLY_LOAD_PARMSA - LPMCI_OVLY_LOAD_PARMS* = LPMCI_OVLY_LOAD_PARMSA -type - TMCI_OVLY_LOAD_PARMS* = MCI_OVLY_LOAD_PARMS - -proc mmioStringToFOURCCA*(x1: LPCSTR, x2: uint32): FOURCC{.stdcall, - dynlib: "winmm.dll", importc: "mmioStringToFOURCCA".} -proc mmioStringToFOURCCW*(x1: LPCWSTR, x2: uint32): FOURCC{.stdcall, - dynlib: "winmm.dll", importc: "mmioStringToFOURCCW".} -proc mmioStringToFOURCC*(x1: cstring, x2: uint32): FOURCC{.stdcall, - dynlib: "winmm.dll", importc: "mmioStringToFOURCCA".} -proc mmioInstallIOProcA*(x1: FOURCC, x2: LPMMIOPROC, x3: DWORD): LPMMIOPROC{. - stdcall, dynlib: "winmm.dll", importc: "mmioInstallIOProcA".} -proc mmioInstallIOProcW*(x1: FOURCC, x2: LPMMIOPROC, x3: DWORD): LPMMIOPROC{. - stdcall, dynlib: "winmm.dll", importc: "mmioInstallIOProcW".} -proc mmioInstallIOProc*(x1: FOURCC, x2: LPMMIOPROC, x3: DWORD): LPMMIOPROC{. - stdcall, dynlib: "winmm.dll", importc: "mmioInstallIOProcA".} -proc mmioOpenA*(x1: LPSTR, x2: LPMMIOINFO, x3: DWORD): HMMIO{.stdcall, - dynlib: "winmm.dll", importc: "mmioOpenA".} -proc mmioOpenW*(x1: LPWSTR, x2: LPMMIOINFO, x3: DWORD): HMMIO{.stdcall, - dynlib: "winmm.dll", importc: "mmioOpenW".} -proc mmioOpen*(x1: cstring, x2: LPMMIOINFO, x3: DWORD): HMMIO{.stdcall, - dynlib: "winmm.dll", importc: "mmioOpenA".} -proc mmioRenameA*(x1: LPCSTR, x2: LPCSTR, x3: LPCMMIOINFO, x4: DWORD): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "mmioRenameA".} -proc mmioRenameW*(x1: LPCWSTR, x2: LPCWSTR, x3: LPCMMIOINFO, x4: DWORD): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "mmioRenameW".} -proc mmioRename*(x1: cstring, x2: cstring, x3: LPCMMIOINFO, x4: DWORD): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "mmioRenameA".} -proc mmioClose*(x1: HMMIO, x2: uint32): MMRESULT{.stdcall, dynlib: "winmm.dll", - importc: "mmioClose".} -proc mmioRead*(x1: HMMIO, x2: HPSTR, x3: LONG): LONG{.stdcall, - dynlib: "winmm.dll", importc: "mmioRead".} -proc mmioWrite*(x1: HMMIO, x2: cstring, x3: LONG): LONG{.stdcall, - dynlib: "winmm.dll", importc: "mmioWrite".} -proc mmioSeek*(x1: HMMIO, x2: LONG, x3: WINT): LONG{.stdcall, - dynlib: "winmm.dll", importc: "mmioSeek".} -proc mmioGetInfo*(x1: HMMIO, x2: LPMMIOINFO, x3: uint32): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "mmioGetInfo".} -proc mmioSetInfo*(x1: HMMIO, x2: LPCMMIOINFO, x3: uint32): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "mmioSetInfo".} -proc mmioSetBuffer*(x1: HMMIO, x2: LPSTR, x3: LONG, x4: uint32): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "mmioSetBuffer".} -proc mmioFlush*(x1: HMMIO, x2: uint32): MMRESULT{.stdcall, dynlib: "winmm.dll", - importc: "mmioFlush".} -proc mmioAdvance*(x1: HMMIO, x2: LPMMIOINFO, x3: uint32): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "mmioAdvance".} -proc mmioSendMessage*(x1: HMMIO, x2: uint32, x3: LPARAM, x4: LPARAM): LRESULT{. - stdcall, dynlib: "winmm.dll", importc: "mmioSendMessage".} -proc mmioDescend*(x1: HMMIO, x2: LPMMCKINFO, x3: PMMCKINFO, x4: uint32): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "mmioDescend".} -proc mmioAscend*(x1: HMMIO, x2: LPMMCKINFO, x3: uint32): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "mmioAscend".} -proc mmioCreateChunk*(x1: HMMIO, x2: LPMMCKINFO, x3: uint32): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "mmioCreateChunk".} -proc mciSendCommandA*(x1: MCIDEVICEID, x2: uint32, x3: DWORD, x4: DWORD): MCIERROR{. - stdcall, dynlib: "winmm.dll", importc: "mciSendCommandA".} -proc mciSendCommandW*(x1: MCIDEVICEID, x2: uint32, x3: DWORD, x4: DWORD): MCIERROR{. - stdcall, dynlib: "winmm.dll", importc: "mciSendCommandW".} -proc mciSendCommand*(x1: MCIDEVICEID, x2: uint32, x3: DWORD, x4: DWORD): MCIERROR{. - stdcall, dynlib: "winmm.dll", importc: "mciSendCommandA".} -proc mciSendStringA*(x1: LPCSTR, x2: LPSTR, x3: uint32, x4: HWND): MCIERROR{. - stdcall, dynlib: "winmm.dll", importc: "mciSendStringA".} -proc mciSendStringW*(x1: LPCWSTR, x2: LPWSTR, x3: uint32, x4: HWND): MCIERROR{. - stdcall, dynlib: "winmm.dll", importc: "mciSendStringW".} -proc mciSendString*(x1: cstring, x2: cstring, x3: uint32, x4: HWND): MCIERROR{. - stdcall, dynlib: "winmm.dll", importc: "mciSendStringA".} -proc mciGetDeviceIDA*(x1: LPCSTR): MCIDEVICEID{.stdcall, dynlib: "winmm.dll", - importc: "mciGetDeviceIDA".} -proc mciGetDeviceIDW*(x1: LPCWSTR): MCIDEVICEID{.stdcall, dynlib: "winmm.dll", - importc: "mciGetDeviceIDW".} -proc mciGetDeviceID*(x1: cstring): MCIDEVICEID{.stdcall, dynlib: "winmm.dll", - importc: "mciGetDeviceIDA".} -proc mciGetDeviceIDFromElementIDA*(x1: DWORD, x2: LPCSTR): MCIDEVICEID{.stdcall, - dynlib: "winmm.dll", importc: "mciGetDeviceIDFromElementIDA".} -proc mciGetDeviceIDFromElementIDW*(x1: DWORD, x2: LPCWSTR): MCIDEVICEID{. - stdcall, dynlib: "winmm.dll", importc: "mciGetDeviceIDFromElementIDW".} -proc mciGetDeviceIDFromElementID*(x1: DWORD, x2: cstring): MCIDEVICEID{.stdcall, - dynlib: "winmm.dll", importc: "mciGetDeviceIDFromElementIDA".} -proc mciGetErrorStringA*(x1: MCIERROR, x2: LPSTR, x3: uint32): bool{.stdcall, - dynlib: "winmm.dll", importc: "mciGetErrorStringA".} -proc mciGetErrorStringW*(x1: MCIERROR, x2: LPWSTR, x3: uint32): bool{.stdcall, - dynlib: "winmm.dll", importc: "mciGetErrorStringW".} -proc mciGetErrorString*(x1: MCIERROR, x2: cstring, x3: uint32): bool{.stdcall, - dynlib: "winmm.dll", importc: "mciGetErrorStringA".} -proc mciSetYieldProc*(x1: MCIDEVICEID, x2: YIELDPROC, x3: DWORD): bool{.stdcall, - dynlib: "winmm.dll", importc: "mciSetYieldProc".} -proc mciGetCreatorTask*(x1: MCIDEVICEID): HTASK{.stdcall, dynlib: "winmm.dll", - importc: "mciGetCreatorTask".} -proc mciGetYieldProc*(x1: MCIDEVICEID, x2: LPDWORD): YIELDPROC{.stdcall, - dynlib: "winmm.dll", importc: "mciGetYieldProc".} -proc mciExecute*(x1: LPCSTR): bool{.stdcall, dynlib: "winmm.dll", - importc: "mciExecute".} -proc joyGetPos*(x1: uint32, x2: LPJOYINFO): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "joyGetPos".} -proc joyGetPosEx*(x1: uint32, x2: LPJOYINFOEX): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "joyGetPosEx".} -proc joyGetThreshold*(x1: uint32, x2: LPUINT): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "joyGetThreshold".} -proc joyReleaseCapture*(x1: uint32): MMRESULT{.stdcall, dynlib: "winmm.dll", - importc: "joyReleaseCapture".} -proc joySetCapture*(x1: HWND, x2: uint32, x3: uint32, x4: bool): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "joySetCapture".} -proc joySetThreshold*(x1: uint32, x2: uint32): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "joySetThreshold".} -proc waveOutGetNumDevs*(): uint32{.stdcall, dynlib: "winmm.dll", - importc: "waveOutGetNumDevs".} -proc waveOutGetDevCapsA*(x1: uint32, x2: LPWAVEOUTCAPSA, x3: uint32): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "waveOutGetDevCapsA".} -proc waveOutGetDevCapsW*(x1: uint32, x2: LPWAVEOUTCAPSW, x3: uint32): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "waveOutGetDevCapsW".} -proc waveOutGetDevCaps*(x1: uint32, x2: LPWAVEOUTCAPS, x3: uint32): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "waveOutGetDevCapsA".} -proc waveOutGetVolume*(x1: HWAVEOUT, x2: LPDWORD): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "waveOutGetVolume".} -proc waveOutSetVolume*(x1: HWAVEOUT, x2: DWORD): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "waveOutSetVolume".} -proc waveOutGetErrorTextA*(x1: MMRESULT, x2: LPSTR, x3: uint32): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "waveOutGetErrorTextA".} -proc waveOutGetErrorTextW*(x1: MMRESULT, x2: LPWSTR, x3: uint32): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "waveOutGetErrorTextW".} -proc waveOutGetErrorText*(x1: MMRESULT, x2: cstring, x3: uint32): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "waveOutGetErrorTextA".} -proc waveOutOpen*(x1: LPHWAVEOUT, x2: uint32, x3: LPCWAVEFORMATEX, x4: DWORD, - x5: DWORD, x6: DWORD): MMRESULT{.stdcall, dynlib: "winmm.dll", - importc: "waveOutOpen".} -proc waveOutClose*(x1: HWAVEOUT): MMRESULT{.stdcall, dynlib: "winmm.dll", - importc: "waveOutClose".} -proc waveOutPrepareHeader*(x1: HWAVEOUT, x2: LPWAVEHDR, x3: uint32): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "waveOutPrepareHeader".} -proc waveOutUnprepareHeader*(x1: HWAVEOUT, x2: LPWAVEHDR, x3: uint32): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "waveOutUnprepareHeader".} -proc waveOutWrite*(x1: HWAVEOUT, x2: LPWAVEHDR, x3: uint32): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "waveOutWrite".} -proc waveOutPause*(x1: HWAVEOUT): MMRESULT{.stdcall, dynlib: "winmm.dll", - importc: "waveOutPause".} -proc waveOutRestart*(x1: HWAVEOUT): MMRESULT{.stdcall, dynlib: "winmm.dll", - importc: "waveOutRestart".} -proc waveOutReset*(x1: HWAVEOUT): MMRESULT{.stdcall, dynlib: "winmm.dll", - importc: "waveOutReset".} -proc waveOutBreakLoop*(x1: HWAVEOUT): MMRESULT{.stdcall, dynlib: "winmm.dll", - importc: "waveOutBreakLoop".} -proc waveOutGetPosition*(x1: HWAVEOUT, x2: LPMMTIME, x3: uint32): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "waveOutGetPosition".} -proc waveOutGetPitch*(x1: HWAVEOUT, x2: LPDWORD): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "waveOutGetPitch".} -proc waveOutSetPitch*(x1: HWAVEOUT, x2: DWORD): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "waveOutSetPitch".} -proc waveOutGetPlaybackRate*(x1: HWAVEOUT, x2: LPDWORD): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "waveOutGetPlaybackRate".} -proc waveOutSetPlaybackRate*(x1: HWAVEOUT, x2: DWORD): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "waveOutSetPlaybackRate".} -proc waveOutGetID*(x1: HWAVEOUT, x2: LPUINT): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "waveOutGetID".} -proc waveOutMessage*(x1: HWAVEOUT, x2: uint32, x3: DWORD, x4: DWORD): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "waveOutMessage".} -proc waveInGetNumDevs*(): uint32{.stdcall, dynlib: "winmm.dll", - importc: "waveInGetNumDevs".} -proc waveInGetDevCapsA*(x1: uint32, x2: LPWAVEINCAPSA, x3: uint32): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "waveInGetDevCapsA".} -proc waveInGetDevCapsW*(x1: uint32, x2: LPWAVEINCAPSW, x3: uint32): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "waveInGetDevCapsW".} -proc waveInGetDevCaps*(x1: uint32, x2: LPWAVEINCAPS, x3: uint32): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "waveInGetDevCapsA".} -proc waveInGetErrorTextA*(x1: MMRESULT, x2: LPSTR, x3: uint32): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "waveInGetErrorTextA".} -proc waveInGetErrorTextW*(x1: MMRESULT, x2: LPWSTR, x3: uint32): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "waveInGetErrorTextW".} -proc waveInGetErrorText*(x1: MMRESULT, x2: cstring, x3: uint32): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "waveInGetErrorTextA".} -proc waveInOpen*(x1: LPHWAVEIN, x2: uint32, x3: LPCWAVEFORMATEX, x4: DWORD, - x5: DWORD, x6: DWORD): MMRESULT{.stdcall, dynlib: "winmm.dll", - importc: "waveInOpen".} -proc waveInClose*(x1: HWAVEIN): MMRESULT{.stdcall, dynlib: "winmm.dll", - importc: "waveInClose".} -proc waveInPrepareHeader*(x1: HWAVEIN, x2: LPWAVEHDR, x3: uint32): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "waveInPrepareHeader".} -proc waveInUnprepareHeader*(x1: HWAVEIN, x2: LPWAVEHDR, x3: uint32): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "waveInUnprepareHeader".} -proc waveInAddBuffer*(x1: HWAVEIN, x2: LPWAVEHDR, x3: uint32): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "waveInAddBuffer".} -proc waveInStart*(x1: HWAVEIN): MMRESULT{.stdcall, dynlib: "winmm.dll", - importc: "waveInStart".} -proc waveInStop*(x1: HWAVEIN): MMRESULT{.stdcall, dynlib: "winmm.dll", - importc: "waveInStop".} -proc waveInReset*(x1: HWAVEIN): MMRESULT{.stdcall, dynlib: "winmm.dll", - importc: "waveInReset".} -proc waveInGetPosition*(x1: HWAVEIN, x2: LPMMTIME, x3: uint32): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "waveInGetPosition".} -proc waveInGetID*(x1: HWAVEIN, x2: LPUINT): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "waveInGetID".} -proc waveInMessage*(x1: HWAVEIN, x2: uint32, x3: DWORD, x4: DWORD): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "waveInMessage".} -proc mixerGetLineControlsA*(x1: HMIXEROBJ, x2: LPMIXERLINECONTROLSA, x3: DWORD): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "mixerGetLineControlsA".} -proc mixerGetLineControlsW*(x1: HMIXEROBJ, x2: LPMIXERLINECONTROLSW, x3: DWORD): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "mixerGetLineControlsW".} -proc mixerGetLineControls*(x1: HMIXEROBJ, x2: LPMIXERLINECONTROLS, x3: DWORD): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "mixerGetLineControlsA".} -proc joyGetNumDevs*(): uint32{.stdcall, dynlib: "winmm.dll", - importc: "joyGetNumDevs".} -proc joyGetDevCapsA*(x1: uint32, x2: LPJOYCAPSA, x3: uint32): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "joyGetDevCapsA".} -proc joyGetDevCapsW*(x1: uint32, x2: LPJOYCAPSW, x3: uint32): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "joyGetDevCapsW".} -proc joyGetDevCaps*(x1: uint32, x2: LPJOYCAPS, x3: uint32): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "joyGetDevCapsA".} -proc mixerGetControlDetailsA*(x1: HMIXEROBJ, x2: LPMIXERCONTROLDETAILS, - x3: DWORD): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "mixerGetControlDetailsA".} -proc mixerGetControlDetailsW*(x1: HMIXEROBJ, x2: LPMIXERCONTROLDETAILS, - x3: DWORD): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "mixerGetControlDetailsW".} -proc mixerGetControlDetails*(x1: HMIXEROBJ, x2: LPMIXERCONTROLDETAILS, x3: DWORD): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "mixerGetControlDetailsA".} -proc timeGetSystemTime*(x1: LPMMTIME, x2: uint32): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "timeGetSystemTime".} -proc timeGetTime*(): DWORD{.stdcall, dynlib: "winmm.dll", importc: "timeGetTime".} -proc timeSetEvent*(x1: uint32, x2: uint32, x3: LPTIMECALLBACK, x4: DWORD, x5: uint32): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "timeSetEvent".} -proc timeKillEvent*(x1: uint32): MMRESULT{.stdcall, dynlib: "winmm.dll", - importc: "timeKillEvent".} -proc timeGetDevCaps*(x1: LPTIMECAPS, x2: uint32): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "timeGetDevCaps".} -proc timeBeginPeriod*(x1: uint32): MMRESULT{.stdcall, dynlib: "winmm.dll", - importc: "timeBeginPeriod".} -proc timeEndPeriod*(x1: uint32): MMRESULT{.stdcall, dynlib: "winmm.dll", - importc: "timeEndPeriod".} -proc mixerGetDevCapsA*(x1: uint32, x2: LPMIXERCAPSA, x3: uint32): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "mixerGetDevCapsA".} -proc mixerGetDevCapsW*(x1: uint32, x2: LPMIXERCAPSW, x3: uint32): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "mixerGetDevCapsW".} -proc mixerGetDevCaps*(x1: uint32, x2: LPMIXERCAPS, x3: uint32): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "mixerGetDevCapsA".} -proc mixerOpen*(x1: LPHMIXER, x2: uint32, x3: DWORD, x4: DWORD, x5: DWORD): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "mixerOpen".} -proc mixerClose*(x1: HMIXER): MMRESULT{.stdcall, dynlib: "winmm.dll", - importc: "mixerClose".} -proc mixerMessage*(x1: HMIXER, x2: uint32, x3: DWORD, x4: DWORD): DWORD{.stdcall, - dynlib: "winmm.dll", importc: "mixerMessage".} -proc auxGetNumDevs*(): uint32{.stdcall, dynlib: "winmm.dll", - importc: "auxGetNumDevs".} -proc auxGetDevCapsA*(x1: uint32, x2: LPAUXCAPSA, x3: uint32): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "auxGetDevCapsA".} -proc auxGetDevCapsW*(x1: uint32, x2: LPAUXCAPSW, x3: uint32): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "auxGetDevCapsW".} -proc auxGetDevCaps*(x1: uint32, x2: LPAUXCAPS, x3: uint32): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "auxGetDevCapsA".} -proc auxSetVolume*(x1: uint32, x2: DWORD): MMRESULT{.stdcall, dynlib: "winmm.dll", - importc: "auxSetVolume".} -proc auxGetVolume*(x1: uint32, x2: LPDWORD): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "auxGetVolume".} -proc auxOutMessage*(x1: uint32, x2: uint32, x3: DWORD, x4: DWORD): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "auxOutMessage".} -proc midiOutGetNumDevs*(): uint32{.stdcall, dynlib: "winmm.dll", - importc: "midiOutGetNumDevs".} -proc midiStreamOpen*(x1: LPHMIDISTRM, x2: LPUINT, x3: DWORD, x4: DWORD, - x5: DWORD, x6: DWORD): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "midiStreamOpen".} -proc midiStreamClose*(x1: HMIDISTRM): MMRESULT{.stdcall, dynlib: "winmm.dll", - importc: "midiStreamClose".} -proc midiStreamProperty*(x1: HMIDISTRM, x2: LPBYTE, x3: DWORD): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "midiStreamProperty".} -proc midiStreamPosition*(x1: HMIDISTRM, x2: LPMMTIME, x3: uint32): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "midiStreamPosition".} -proc midiStreamOut*(x1: HMIDISTRM, x2: LPMIDIHDR, x3: uint32): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "midiStreamOut".} -proc midiStreamPause*(x1: HMIDISTRM): MMRESULT{.stdcall, dynlib: "winmm.dll", - importc: "midiStreamPause".} -proc midiStreamRestart*(x1: HMIDISTRM): MMRESULT{.stdcall, dynlib: "winmm.dll", - importc: "midiStreamRestart".} -proc midiStreamStop*(x1: HMIDISTRM): MMRESULT{.stdcall, dynlib: "winmm.dll", - importc: "midiStreamStop".} -proc midiConnect*(x1: HMIDI, x2: HMIDIOUT, x3: pointer): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "midiConnect".} -proc midiDisconnect*(x1: HMIDI, x2: HMIDIOUT, x3: pointer): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "midiDisconnect".} -proc midiOutGetDevCapsA*(x1: uint32, x2: LPMIDIOUTCAPSA, x3: uint32): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "midiOutGetDevCapsA".} -proc midiOutGetDevCapsW*(x1: uint32, x2: LPMIDIOUTCAPSW, x3: uint32): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "midiOutGetDevCapsW".} -proc midiOutGetDevCaps*(x1: uint32, x2: LPMIDIOUTCAPS, x3: uint32): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "midiOutGetDevCapsA".} -proc midiOutGetVolume*(x1: HMIDIOUT, x2: LPDWORD): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "midiOutGetVolume".} -proc midiOutSetVolume*(x1: HMIDIOUT, x2: DWORD): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "midiOutSetVolume".} -proc midiOutGetErrorTextA*(x1: MMRESULT, x2: LPSTR, x3: uint32): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "midiOutGetErrorTextA".} -proc midiOutGetErrorTextW*(x1: MMRESULT, x2: LPWSTR, x3: uint32): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "midiOutGetErrorTextW".} -proc midiOutGetErrorText*(x1: MMRESULT, x2: cstring, x3: uint32): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "midiOutGetErrorTextA".} -proc midiOutOpen*(x1: LPHMIDIOUT, x2: uint32, x3: DWORD, x4: DWORD, x5: DWORD): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "midiOutOpen".} -proc midiOutClose*(x1: HMIDIOUT): MMRESULT{.stdcall, dynlib: "winmm.dll", - importc: "midiOutClose".} -proc midiOutPrepareHeader*(x1: HMIDIOUT, x2: LPMIDIHDR, x3: uint32): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "midiOutPrepareHeader".} -proc midiOutUnprepareHeader*(x1: HMIDIOUT, x2: LPMIDIHDR, x3: uint32): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "midiOutUnprepareHeader".} -proc midiOutShortMsg*(x1: HMIDIOUT, x2: DWORD): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "midiOutShortMsg".} -proc midiOutLongMsg*(x1: HMIDIOUT, x2: LPMIDIHDR, x3: uint32): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "midiOutLongMsg".} -proc midiOutReset*(x1: HMIDIOUT): MMRESULT{.stdcall, dynlib: "winmm.dll", - importc: "midiOutReset".} -proc midiOutCachePatches*(x1: HMIDIOUT, x2: uint32, x3: LPWORD, x4: uint32): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "midiOutCachePatches".} -proc midiOutCacheDrumPatches*(x1: HMIDIOUT, x2: uint32, x3: LPWORD, x4: uint32): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "midiOutCacheDrumPatches".} -proc midiOutGetID*(x1: HMIDIOUT, x2: LPUINT): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "midiOutGetID".} -proc midiOutMessage*(x1: HMIDIOUT, x2: uint32, x3: DWORD, x4: DWORD): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "midiOutMessage".} -proc midiInGetNumDevs*(): uint32{.stdcall, dynlib: "winmm.dll", - importc: "midiInGetNumDevs".} -proc midiInGetDevCapsA*(x1: uint32, x2: LPMIDIINCAPSA, x3: uint32): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "midiInGetDevCapsA".} -proc midiInGetDevCapsW*(x1: uint32, x2: LPMIDIINCAPSW, x3: uint32): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "midiInGetDevCapsW".} -proc midiInGetDevCaps*(x1: uint32, x2: LPMIDIINCAPS, x3: uint32): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "midiInGetDevCapsA".} -proc midiInGetErrorTextA*(x1: MMRESULT, x2: LPSTR, x3: uint32): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "midiInGetErrorTextA".} -proc midiInGetErrorTextW*(x1: MMRESULT, x2: LPWSTR, x3: uint32): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "midiInGetErrorTextW".} -proc midiInGetErrorText*(x1: MMRESULT, x2: cstring, x3: uint32): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "midiInGetErrorTextA".} -proc midiInOpen*(x1: LPHMIDIIN, x2: uint32, x3: DWORD, x4: DWORD, x5: DWORD): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "midiInOpen".} -proc midiInClose*(x1: HMIDIIN): MMRESULT{.stdcall, dynlib: "winmm.dll", - importc: "midiInClose".} -proc midiInPrepareHeader*(x1: HMIDIIN, x2: LPMIDIHDR, x3: uint32): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "midiInPrepareHeader".} -proc midiInUnprepareHeader*(x1: HMIDIIN, x2: LPMIDIHDR, x3: uint32): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "midiInUnprepareHeader".} -proc midiInAddBuffer*(x1: HMIDIIN, x2: LPMIDIHDR, x3: uint32): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "midiInAddBuffer".} -proc midiInStart*(x1: HMIDIIN): MMRESULT{.stdcall, dynlib: "winmm.dll", - importc: "midiInStart".} -proc midiInStop*(x1: HMIDIIN): MMRESULT{.stdcall, dynlib: "winmm.dll", - importc: "midiInStop".} -proc midiInReset*(x1: HMIDIIN): MMRESULT{.stdcall, dynlib: "winmm.dll", - importc: "midiInReset".} -proc midiInGetID*(x1: HMIDIIN, x2: LPUINT): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "midiInGetID".} -proc midiInMessage*(x1: HMIDIIN, x2: uint32, x3: DWORD, x4: DWORD): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "midiInMessage".} -proc mixerGetLineInfoA*(x1: HMIXEROBJ, x2: LPMIXERLINEA, x3: DWORD): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "mixerGetLineInfoA".} -proc mixerGetLineInfoW*(x1: HMIXEROBJ, x2: LPMIXERLINEW, x3: DWORD): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "mixerGetLineInfoW".} -proc mixerGetLineInfo*(x1: HMIXEROBJ, x2: LPMIXERLINE, x3: DWORD): MMRESULT{. - stdcall, dynlib: "winmm.dll", importc: "mixerGetLineInfoA".} -proc mixerGetID*(x1: HMIXEROBJ, x2: var uint32, x3: DWORD): MMRESULT{.stdcall, - dynlib: "winmm.dll", importc: "mixerGetID".} -proc PlaySoundA*(x1: LPCSTR, x2: HMODULE, x3: DWORD): bool{.stdcall, - dynlib: "winmm.dll", importc: "PlaySoundA".} -proc PlaySoundW*(x1: LPCWSTR, x2: HMODULE, x3: DWORD): bool{.stdcall, - dynlib: "winmm.dll", importc: "PlaySoundW".} -proc PlaySound*(x1: cstring, x2: HMODULE, x3: DWORD): bool{.stdcall, - dynlib: "winmm.dll", importc: "PlaySoundA".} -# implementation - -proc MEVT_EVENTTYPE(x: int8): int8 = - result = toU8(x shr 24) - -proc MEVT_EVENTPARM(x: DWORD): DWORD = - result = x and 0x00FFFFFF - -proc MCI_MSF_MINUTE(msf: int32): int8 = - result = toU8(msf and 0xff) - -proc MCI_TMSF_TRACK(tmsf: int32): int8 = - result = toU8(tmsf and 0xff) - -proc MCI_HMS_HOUR(h: int32): int8 = - result = toU8(h and 0xff) - -proc MCI_MSF_SECOND(msf: int32): int8 = - result = toU8(msf shr 8) - -proc MCI_TMSF_MINUTE(tmsf: int32): int8 = - result = toU8(tmsf shr 8) - -proc MCI_HMS_MINUTE(h: int32): int8 = - result = toU8(h shr 8) - -proc MCI_MSF_FRAME(msf: int32): int8 = - result = toU8(msf shr 16) - -proc MCI_TMSF_SECOND(tmsf: int32): int8 = - result = toU8(tmsf shr 16) - -proc MCI_HMS_SECOND(h: int32): int8 = - result = toU8(h shr 16) - -proc MCI_MAKE_MSF(m, s, f: int8): int32 = - result = toU32(ze(m) or ze(s) shl 8 or ze(f) shl 16) - -proc MCI_MAKE_HMS(h, m, s: int8): int32 = - result = toU32(ze(h) or ze(m) shl 8 or ze(s) shl 16) - -proc MCI_TMSF_FRAME(tmsf: int32): int8 = - result = toU8(tmsf shr 24) - -proc MCI_MAKE_TMSF(t, m, s, f: int8): int32 = - result = (ze(t) or ze(m) shl 8 or ze(s) shl 16 or ze(f) shl 24).int32 - -proc DIBINDEX(n: int32): int32 = - result = n or 0x000010FF'i32 shl 16'i32 diff --git a/lib/windows/nb30.nim b/lib/windows/nb30.nim deleted file mode 100644 index 820e0b7a3..000000000 --- a/lib/windows/nb30.nim +++ /dev/null @@ -1,236 +0,0 @@ -# -# -# Nim's Runtime Library -# (c) Copyright 2006 Andreas Rumpf -# -# See the file "copying.txt", included in this -# distribution, for details about the copyright. -# -# NetBIOS 3.0 interface unit - -# This module contains the definitions for portable NetBIOS 3.0 support. - -{.deadCodeElim: on.} - -import # Data structure templates - windows - -const - NCBNAMSZ* = 16 # absolute length of a net name - MAX_LANA* = 254 # lana's in range 0 to MAX_LANA inclusive - -type # Network Control Block - PNCB* = ptr NCB - NCBPostProc* = proc (P: PNCB) {.stdcall.} - NCB* {.final.} = object # Structure returned to the NCB command NCBASTAT is ADAPTER_STATUS followed - # by an array of NAME_BUFFER structures. - ncb_command*: char # command code - ncb_retcode*: char # return code - ncb_lsn*: char # local session number - ncb_num*: char # number of our network name - ncb_buffer*: cstring # address of message buffer - ncb_length*: int16 # size of message buffer - ncb_callname*: array[0..NCBNAMSZ - 1, char] # blank-padded name of remote - ncb_name*: array[0..NCBNAMSZ - 1, char] # our blank-padded netname - ncb_rto*: char # rcv timeout/retry count - ncb_sto*: char # send timeout/sys timeout - ncb_post*: NCBPostProc # POST routine address - ncb_lana_num*: char # lana (adapter) number - ncb_cmd_cplt*: char # 0xff => commmand pending - ncb_reserve*: array[0..9, char] # reserved, used by BIOS - ncb_event*: Handle # HANDLE to Win32 event which - # will be set to the signalled - # state when an ASYNCH command - # completes - - PAdapterStatus* = ptr AdapterStatus - AdapterStatus* {.final.} = object - adapter_address*: array[0..5, char] - rev_major*: char - reserved0*: char - adapter_type*: char - rev_minor*: char - duration*: int16 - frmr_recv*: int16 - frmr_xmit*: int16 - iframe_recv_err*: int16 - xmit_aborts*: int16 - xmit_success*: DWORD - recv_success*: DWORD - iframe_xmit_err*: int16 - recv_buff_unavail*: int16 - t1_timeouts*: int16 - ti_timeouts*: int16 - reserved1*: DWORD - free_ncbs*: int16 - max_cfg_ncbs*: int16 - max_ncbs*: int16 - xmit_buf_unavail*: int16 - max_dgram_size*: int16 - pending_sess*: int16 - max_cfg_sess*: int16 - max_sess*: int16 - max_sess_pkt_size*: int16 - name_count*: int16 - - PNameBuffer* = ptr NameBuffer - NameBuffer* {.final.} = object - name*: array[0..NCBNAMSZ - 1, char] - name_num*: char - name_flags*: char -{.deprecated: [TNCB: NCB, TNCBPostProc: NCBPostProc, - TAdapterStatus: AdapterStatus, TNameBuffer: NameBuffer].} - - -const # values for name_flags bits. - NAME_FLAGS_MASK* = 0x00000087 - GROUP_NAME* = 0x00000080 - UNIQUE_NAME* = 0x00000000 - REGISTERING* = 0x00000000 - REGISTERED* = 0x00000004 - DEREGISTERED* = 0x00000005 - DUPLICATE* = 0x00000006 - DUPLICATE_DEREG* = 0x00000007 - -type # Structure returned to the NCB command NCBSSTAT is SESSION_HEADER followed - # by an array of SESSION_BUFFER structures. If the NCB_NAME starts with an - # asterisk then an array of these structures is returned containing the - # status for all names. - PSessionHeader* = ptr SessionHeader - SessionHeader* {.final.} = object - sess_name*: char - num_sess*: char - rcv_dg_outstanding*: char - rcv_any_outstanding*: char - - PSessionBuffer* = ptr SessionBuffer - SessionBuffer* {.final.} = object - lsn*: char - state*: char - local_name*: array[0..NCBNAMSZ - 1, char] - remote_name*: array[0..NCBNAMSZ - 1, char] - rcvs_outstanding*: char - sends_outstanding*: char -{.deprecated: [TSessionHeader: SessionHeader, TSessionBuffer: SessionBuffer].} - - -const # Values for state - LISTEN_OUTSTANDING* = 0x00000001 - CALL_PENDING* = 0x00000002 - SESSION_ESTABLISHED* = 0x00000003 - HANGUP_PENDING* = 0x00000004 - HANGUP_COMPLETE* = 0x00000005 - SESSION_ABORTED* = 0x00000006 - -type # Structure returned to the NCB command NCBENUM. - # On a system containing lana's 0, 2 and 3, a structure with - # length =3, lana[0]=0, lana[1]=2 and lana[2]=3 will be returned. - PLanaEnum* = ptr TLanaEnum - TLanaEnum* {.final.} = object # Structure returned to the NCB command NCBFINDNAME is FIND_NAME_HEADER followed - # by an array of FIND_NAME_BUFFER structures. - len*: char # Number of valid entries in lana[] - lana*: array[0..MAX_LANA, char] - - PFindNameHeader* = ptr FindNameHeader - FindNameHeader* {.final.} = object - node_count*: int16 - reserved*: char - unique_group*: char - - PFindNameBuffer* = ptr FindNameBuffer - FindNameBuffer* {.final.} = object # Structure provided with NCBACTION. The purpose of NCBACTION is to provide - # transport specific extensions to netbios. - len*: char - access_control*: char - frame_control*: char - destination_addr*: array[0..5, char] - source_addr*: array[0..5, char] - routing_info*: array[0..17, char] - - PActionHeader* = ptr ActionHeader - ActionHeader* {.final.} = object - transport_id*: int32 - action_code*: int16 - reserved*: int16 -{.deprecated: [TFindNameHeader: FindNameHeader, TFindNameBuffer: FindNameBuffer, - TActionHeader: ActionHeader].} - -const # Values for transport_id - ALL_TRANSPORTS* = "M\0\0\0" - MS_NBF* = "MNBF" # Special values and constants - -const # NCB Command codes - NCBCALL* = 0x00000010 # NCB CALL - NCBLISTEN* = 0x00000011 # NCB LISTEN - NCBHANGUP* = 0x00000012 # NCB HANG UP - NCBSEND* = 0x00000014 # NCB SEND - NCBRECV* = 0x00000015 # NCB RECEIVE - NCBRECVANY* = 0x00000016 # NCB RECEIVE ANY - NCBCHAINSEND* = 0x00000017 # NCB CHAIN SEND - NCBDGSEND* = 0x00000020 # NCB SEND DATAGRAM - NCBDGRECV* = 0x00000021 # NCB RECEIVE DATAGRAM - NCBDGSENDBC* = 0x00000022 # NCB SEND BROADCAST DATAGRAM - NCBDGRECVBC* = 0x00000023 # NCB RECEIVE BROADCAST DATAGRAM - NCBADDNAME* = 0x00000030 # NCB ADD NAME - NCBDELNAME* = 0x00000031 # NCB DELETE NAME - NCBRESET* = 0x00000032 # NCB RESET - NCBASTAT* = 0x00000033 # NCB ADAPTER STATUS - NCBSSTAT* = 0x00000034 # NCB SESSION STATUS - NCBCANCEL* = 0x00000035 # NCB CANCEL - NCBADDGRNAME* = 0x00000036 # NCB ADD GROUP NAME - NCBENUM* = 0x00000037 # NCB ENUMERATE LANA NUMBERS - NCBUNLINK* = 0x00000070 # NCB UNLINK - NCBSENDNA* = 0x00000071 # NCB SEND NO ACK - NCBCHAINSENDNA* = 0x00000072 # NCB CHAIN SEND NO ACK - NCBLANSTALERT* = 0x00000073 # NCB LAN STATUS ALERT - NCBACTION* = 0x00000077 # NCB ACTION - NCBFINDNAME* = 0x00000078 # NCB FIND NAME - NCBTRACE* = 0x00000079 # NCB TRACE - ASYNCH* = 0x00000080 # high bit set = asynchronous - # NCB Return codes - NRC_GOODRET* = 0x00000000 # good return - # also returned when ASYNCH request accepted - NRC_BUFLEN* = 0x00000001 # illegal buffer length - NRC_ILLCMD* = 0x00000003 # illegal command - NRC_CMDTMO* = 0x00000005 # command timed out - NRC_INCOMP* = 0x00000006 # message incomplete, issue another command - NRC_BADDR* = 0x00000007 # illegal buffer address - NRC_SNUMOUT* = 0x00000008 # session number out of range - NRC_NORES* = 0x00000009 # no resource available - NRC_SCLOSED* = 0x0000000A # session closed - NRC_CMDCAN* = 0x0000000B # command cancelled - NRC_DUPNAME* = 0x0000000D # duplicate name - NRC_NAMTFUL* = 0x0000000E # name table full - NRC_ACTSES* = 0x0000000F # no deletions, name has active sessions - NRC_LOCTFUL* = 0x00000011 # local session table full - NRC_REMTFUL* = 0x00000012 # remote session table full - NRC_ILLNN* = 0x00000013 # illegal name number - NRC_NOCALL* = 0x00000014 # no callname - NRC_NOWILD* = 0x00000015 # cannot put * in NCB_NAME - NRC_INUSE* = 0x00000016 # name in use on remote adapter - NRC_NAMERR* = 0x00000017 # name deleted - NRC_SABORT* = 0x00000018 # session ended abnormally - NRC_NAMCONF* = 0x00000019 # name conflict detected - NRC_IFBUSY* = 0x00000021 # interface busy, IRET before retrying - NRC_TOOMANY* = 0x00000022 # too many commands outstanding, retry later - NRC_BRIDGE* = 0x00000023 # NCB_lana_num field invalid - NRC_CANOCCR* = 0x00000024 # command completed while cancel occurring - NRC_CANCEL* = 0x00000026 # command not valid to cancel - NRC_DUPENV* = 0x00000030 # name defined by anther local process - NRC_ENVNOTDEF* = 0x00000034 # environment undefined. RESET required - NRC_OSRESNOTAV* = 0x00000035 # required OS resources exhausted - NRC_MAXAPPS* = 0x00000036 # max number of applications exceeded - NRC_NOSAPS* = 0x00000037 # no saps available for netbios - NRC_NORESOURCES* = 0x00000038 # requested resources are not available - NRC_INVADDRESS* = 0x00000039 # invalid ncb address or length > segment - NRC_INVDDID* = 0x0000003B # invalid NCB DDID - NRC_LOCKFAIL* = 0x0000003C # lock of user area failed - NRC_OPENERR* = 0x0000003F # NETBIOS not loaded - NRC_SYSTEM* = 0x00000040 # system error - NRC_PENDING* = 0x000000FF # asynchronous command is not yet finished - # main user entry point for NetBIOS 3.0 - # Usage: Result = Netbios( pncb ); - -proc Netbios*(P: PNCB): char{.stdcall, dynlib: "netapi32.dll", - importc: "Netbios".} -# implementation diff --git a/lib/windows/psapi.nim b/lib/windows/psapi.nim deleted file mode 100644 index fd1dcada8..000000000 --- a/lib/windows/psapi.nim +++ /dev/null @@ -1,202 +0,0 @@ -# -# -# Nim's Runtime Library -# (c) Copyright 2009 Andreas Rumpf -# -# See the file "copying.txt", included in this -# distribution, for details about the copyright. -# - -# PSAPI interface unit - -# Contains the definitions for the APIs provided by PSAPI.DLL - -import # Data structure templates - Windows - -const - psapiDll = "psapi.dll" - -proc EnumProcesses*(lpidProcess: ptr DWORD, cb: DWORD, - cbNeeded: ptr DWORD): WINBOOL {.stdcall, - dynlib: psapiDll, importc: "EnumProcesses".} -proc EnumProcessModules*(hProcess: HANDLE, lphModule: ptr HMODULE, cb: DWORD, lpcbNeeded: LPDWORD): WINBOOL {.stdcall, - dynlib: psapiDll, importc: "EnumProcessModules".} - -proc GetModuleBaseNameA*(hProcess: HANDLE, hModule: HMODULE, lpBaseName: LPSTR, nSize: DWORD): DWORD {.stdcall, - dynlib: psapiDll, importc: "GetModuleBaseNameA".} -proc GetModuleBaseNameW*(hProcess: HANDLE, hModule: HMODULE, lpBaseName: LPWSTR, nSize: DWORD): DWORD {.stdcall, - dynlib: psapiDll, importc: "GetModuleBaseNameW".} -when defined(winUnicode): - proc GetModuleBaseName*(hProcess: HANDLE, hModule: HMODULE, lpBaseName: LPWSTR, nSize: DWORD): DWORD {.stdcall, - dynlib: psapiDll, importc: "GetModuleBaseNameW".} -else: - proc GetModuleBaseName*(hProcess: HANDLE, hModule: HMODULE, lpBaseName: LPSTR, nSize: DWORD): DWORD {.stdcall, - dynlib: psapiDll, importc: "GetModuleBaseNameA".} - -proc GetModuleFileNameExA*(hProcess: HANDLE, hModule: HMODULE, lpFileNameEx: LPSTR, nSize: DWORD): DWORD {.stdcall, - dynlib: psapiDll, importc: "GetModuleFileNameExA".} -proc GetModuleFileNameExW*(hProcess: HANDLE, hModule: HMODULE, lpFileNameEx: LPWSTR, nSize: DWORD): DWORD {.stdcall, - dynlib: psapiDll, importc: "GetModuleFileNameExW".} -when defined(winUnicode): - proc GetModuleFileNameEx*(hProcess: HANDLE, hModule: HMODULE, lpFileNameEx: LPWSTR, nSize: DWORD): DWORD {.stdcall, - dynlib: psapiDll, importc: "GetModuleFileNameExW".} -else: - proc GetModuleFileNameEx*(hProcess: HANDLE, hModule: HMODULE, lpFileNameEx: LPSTR, nSize: DWORD): DWORD {.stdcall, - dynlib: psapiDll, importc: "GetModuleFileNameExA".} - -type - MODULEINFO* {.final.} = object - lpBaseOfDll*: LPVOID - SizeOfImage*: DWORD - EntryPoint*: LPVOID - LPMODULEINFO* = ptr MODULEINFO - -proc GetModuleInformation*(hProcess: HANDLE, hModule: HMODULE, lpmodinfo: LPMODULEINFO, cb: DWORD): WINBOOL {.stdcall, - dynlib: psapiDll, importc: "GetModuleInformation".} -proc EmptyWorkingSet*(hProcess: HANDLE): WINBOOL {.stdcall, - dynlib: psapiDll, importc: "EmptyWorkingSet".} -proc QueryWorkingSet*(hProcess: HANDLE, pv: PVOID, cb: DWORD): WINBOOL {.stdcall, - dynlib: psapiDll, importc: "QueryWorkingSet".} -proc QueryWorkingSetEx*(hProcess: HANDLE, pv: PVOID, cb: DWORD): WINBOOL {.stdcall, - dynlib: psapiDll, importc: "QueryWorkingSetEx".} -proc InitializeProcessForWsWatch*(hProcess: HANDLE): WINBOOL {.stdcall, - dynlib: psapiDll, importc: "InitializeProcessForWsWatch".} - -type - PSAPI_WS_WATCH_INFORMATION* {.final.} = object - FaultingPc*: LPVOID - FaultingVa*: LPVOID - PPSAPI_WS_WATCH_INFORMATION* = ptr PSAPI_WS_WATCH_INFORMATION - -proc GetWsChanges*(hProcess: HANDLE, lpWatchInfo: PPSAPI_WS_WATCH_INFORMATION, cb: DWORD): WINBOOL {.stdcall, - dynlib: psapiDll, importc: "GetWsChanges".} - -proc GetMappedFileNameA*(hProcess: HANDLE, lpv: LPVOID, lpFilename: LPSTR, nSize: DWORD): DWORD {.stdcall, - dynlib: psapiDll, importc: "GetMappedFileNameA".} -proc GetMappedFileNameW*(hProcess: HANDLE, lpv: LPVOID, lpFilename: LPWSTR, nSize: DWORD): DWORD {.stdcall, - dynlib: psapiDll, importc: "GetMappedFileNameW".} -when defined(winUnicode): - proc GetMappedFileName*(hProcess: HANDLE, lpv: LPVOID, lpFilename: LPWSTR, nSize: DWORD): DWORD {.stdcall, - dynlib: psapiDll, importc: "GetMappedFileNameW".} -else: - proc GetMappedFileName*(hProcess: HANDLE, lpv: LPVOID, lpFilename: LPSTR, nSize: DWORD): DWORD {.stdcall, - dynlib: psapiDll, importc: "GetMappedFileNameA".} - -proc EnumDeviceDrivers*(lpImageBase: LPVOID, cb: DWORD, lpcbNeeded: LPDWORD): WINBOOL {.stdcall, - dynlib: psapiDll, importc: "EnumDeviceDrivers".} - -proc GetDeviceDriverBaseNameA*(ImageBase: LPVOID, lpBaseName: LPSTR, nSize: DWORD): DWORD {.stdcall, - dynlib: psapiDll, importc: "GetDeviceDriverBaseNameA".} -proc GetDeviceDriverBaseNameW*(ImageBase: LPVOID, lpBaseName: LPWSTR, nSize: DWORD): DWORD {.stdcall, - dynlib: psapiDll, importc: "GetDeviceDriverBaseNameW".} -when defined(winUnicode): - proc GetDeviceDriverBaseName*(ImageBase: LPVOID, lpBaseName: LPWSTR, nSize: DWORD): DWORD {.stdcall, - dynlib: psapiDll, importc: "GetDeviceDriverBaseNameW".} -else: - proc GetDeviceDriverBaseName*(ImageBase: LPVOID, lpBaseName: LPSTR, nSize: DWORD): DWORD {.stdcall, - dynlib: psapiDll, importc: "GetDeviceDriverBaseNameA".} - -proc GetDeviceDriverFileNameA*(ImageBase: LPVOID, lpFileName: LPSTR, nSize: DWORD): DWORD {.stdcall, - dynlib: psapiDll, importc: "GetDeviceDriverFileNameA".} -proc GetDeviceDriverFileNameW*(ImageBase: LPVOID, lpFileName: LPWSTR, nSize: DWORD): DWORD {.stdcall, - dynlib: psapiDll, importc: "GetDeviceDriverFileNameW".} -when defined(winUnicode): - proc GetDeviceDriverFileName*(ImageBase: LPVOID, lpFileName: LPWSTR, nSize: DWORD): DWORD {.stdcall, - dynlib: psapiDll, importc: "GetDeviceDriverFileNameW".} -else: - proc GetDeviceDriverFileName*(ImageBase: LPVOID, lpFileName: LPSTR, nSize: DWORD): DWORD {.stdcall, - dynlib: psapiDll, importc: "GetDeviceDriverFileNameA".} - -type - PROCESS_MEMORY_COUNTERS* {.final.} = object - cb*: DWORD - PageFaultCount*: DWORD - PeakWorkingSetSize: SIZE_T - WorkingSetSize: SIZE_T - QuotaPeakPagedPoolUsage: SIZE_T - QuotaPagedPoolUsage: SIZE_T - QuotaPeakNonPagedPoolUsage: SIZE_T - QuotaNonPagedPoolUsage: SIZE_T - PagefileUsage: SIZE_T - PeakPagefileUsage: SIZE_T - PPROCESS_MEMORY_COUNTERS* = ptr PROCESS_MEMORY_COUNTERS - -type - PROCESS_MEMORY_COUNTERS_EX* {.final.} = object - cb*: DWORD - PageFaultCount*: DWORD - PeakWorkingSetSize: SIZE_T - WorkingSetSize: SIZE_T - QuotaPeakPagedPoolUsage: SIZE_T - QuotaPagedPoolUsage: SIZE_T - QuotaPeakNonPagedPoolUsage: SIZE_T - QuotaNonPagedPoolUsage: SIZE_T - PagefileUsage: SIZE_T - PeakPagefileUsage: SIZE_T - PrivateUsage: SIZE_T - PPROCESS_MEMORY_COUNTERS_EX* = ptr PROCESS_MEMORY_COUNTERS_EX - -proc GetProcessMemoryInfo*(hProcess: HANDLE, ppsmemCounters: PPROCESS_MEMORY_COUNTERS, cb: DWORD): WINBOOL {.stdcall, - dynlib: psapiDll, importc: "GetProcessMemoryInfo".} - -type - PERFORMANCE_INFORMATION* {.final.} = object - cb*: DWORD - CommitTotal: SIZE_T - CommitLimit: SIZE_T - CommitPeak: SIZE_T - PhysicalTotal: SIZE_T - PhysicalAvailable: SIZE_T - SystemCache: SIZE_T - KernelTotal: SIZE_T - KernelPaged: SIZE_T - KernelNonpaged: SIZE_T - PageSize: SIZE_T - HandleCount*: DWORD - ProcessCount*: DWORD - ThreadCount*: DWORD - PPERFORMANCE_INFORMATION* = ptr PERFORMANCE_INFORMATION - # Skip definition of PERFORMACE_INFORMATION... - -proc GetPerformanceInfo*(pPerformanceInformation: PPERFORMANCE_INFORMATION, cb: DWORD): WINBOOL {.stdcall, - dynlib: psapiDll, importc: "GetPerformanceInfo".} - -type - ENUM_PAGE_FILE_INFORMATION* {.final.} = object - cb*: DWORD - Reserved*: DWORD - TotalSize: SIZE_T - TotalInUse: SIZE_T - PeakUsage: SIZE_T - PENUM_PAGE_FILE_INFORMATION* = ptr ENUM_PAGE_FILE_INFORMATION - -# Callback procedure -type - PENUM_PAGE_FILE_CALLBACKW* = proc (pContext: LPVOID, pPageFileInfo: PENUM_PAGE_FILE_INFORMATION, lpFilename: LPCWSTR): WINBOOL{.stdcall.} - PENUM_PAGE_FILE_CALLBACKA* = proc (pContext: LPVOID, pPageFileInfo: PENUM_PAGE_FILE_INFORMATION, lpFilename: LPCSTR): WINBOOL{.stdcall.} - -#TODO -proc EnumPageFilesA*(pCallBackRoutine: PENUM_PAGE_FILE_CALLBACKA, pContext: LPVOID): WINBOOL {.stdcall, - dynlib: psapiDll, importc: "EnumPageFilesA".} -proc EnumPageFilesW*(pCallBackRoutine: PENUM_PAGE_FILE_CALLBACKW, pContext: LPVOID): WINBOOL {.stdcall, - dynlib: psapiDll, importc: "EnumPageFilesW".} -when defined(winUnicode): - proc EnumPageFiles*(pCallBackRoutine: PENUM_PAGE_FILE_CALLBACKW, pContext: LPVOID): WINBOOL {.stdcall, - dynlib: psapiDll, importc: "EnumPageFilesW".} - type PENUM_PAGE_FILE_CALLBACK* = proc (pContext: LPVOID, pPageFileInfo: PENUM_PAGE_FILE_INFORMATION, lpFilename: LPCWSTR): WINBOOL{.stdcall.} -else: - proc EnumPageFiles*(pCallBackRoutine: PENUM_PAGE_FILE_CALLBACKA, pContext: LPVOID): WINBOOL {.stdcall, - dynlib: psapiDll, importc: "EnumPageFilesA".} - type PENUM_PAGE_FILE_CALLBACK* = proc (pContext: LPVOID, pPageFileInfo: PENUM_PAGE_FILE_INFORMATION, lpFilename: LPCSTR): WINBOOL{.stdcall.} - -proc GetProcessImageFileNameA*(hProcess: HANDLE, lpImageFileName: LPSTR, nSize: DWORD): DWORD {.stdcall, - dynlib: psapiDll, importc: "GetProcessImageFileNameA".} -proc GetProcessImageFileNameW*(hProcess: HANDLE, lpImageFileName: LPWSTR, nSize: DWORD): DWORD {.stdcall, - dynlib: psapiDll, importc: "GetProcessImageFileNameW".} -when defined(winUnicode): - proc GetProcessImageFileName*(hProcess: HANDLE, lpImageFileName: LPWSTR, nSize: DWORD): DWORD {.stdcall, - dynlib: psapiDll, importc: "GetProcessImageFileNameW".} -else: - proc GetProcessImageFileName*(hProcess: HANDLE, lpImageFileName: LPSTR, nSize: DWORD): DWORD {.stdcall, - dynlib: psapiDll, importc: "GetProcessImageFileNameA".} diff --git a/lib/windows/shellapi.nim b/lib/windows/shellapi.nim deleted file mode 100644 index 0f8bc5ea3..000000000 --- a/lib/windows/shellapi.nim +++ /dev/null @@ -1,863 +0,0 @@ -# -# -# Nim's Runtime Library -# (c) Copyright 2006 Andreas Rumpf -# -# See the file "copying.txt", included in this -# distribution, for details about the copyright. -# - -{.deadCodeElim: on.} - -# leave out unused functions so the unit can be used on win2000 as well - -#+------------------------------------------------------------------------- -# -# Microsoft Windows -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# File: shellapi.h -# -# Header translation by Marco van de Voort for Free Pascal Platform -# SDK dl'ed January 2002 -# -#-------------------------------------------------------------------------- - -# -# shellapi.h - SHELL.DLL functions, types, and definitions -# Copyright (c) Microsoft Corporation. All rights reserved. - -import - windows - -type - HDROP* = Handle - UINT_PTR* = ptr uint32 - DWORD_PTR* = ptr DWORD - PHICON* = ptr HICON - PBool* = ptr bool - STARTUPINFOW* {.final.} = object # a guess. Omission should get fixed in Windows. - cb*: DWORD - lpReserved*: LPTSTR - lpDesktop*: LPTSTR - lpTitle*: LPTSTR - dwX*: DWORD - dwY*: DWORD - dwXSize*: DWORD - dwYSize*: DWORD - dwXCountChars*: DWORD - dwYCountChars*: DWORD - dwFillAttribute*: DWORD - dwFlags*: DWORD - wShowWindow*: int16 - cbReserved2*: int16 - lpReserved2*: LPBYTE - hStdInput*: HANDLE - hStdOutput*: HANDLE - hStdError*: HANDLE - - LPSTARTUPINFOW* = ptr STARTUPINFOW - PSTARTUPINFOW* = ptr STARTUPINFOW #unicode -{.deprecated: [TSTARTUPINFOW: STARTUPINFOW].} - -proc DragQueryFileA*(arg1: HDROP, arg2: uint32, arg3: LPSTR, arg4: uint32): uint32{. - stdcall, dynlib: "shell32.dll", importc: "DragQueryFileA".} -proc DragQueryFileW*(arg1: HDROP, arg2: uint32, arg3: LPWSTR, arg4: uint32): uint32{. - stdcall, dynlib: "shell32.dll", importc: "DragQueryFileW".} -proc DragQueryFile*(arg1: HDROP, arg2: uint32, arg3: LPSTR, arg4: uint32): uint32{. - stdcall, dynlib: "shell32.dll", importc: "DragQueryFileA".} -proc DragQueryFile*(arg1: HDROP, arg2: uint32, arg3: LPWSTR, arg4: uint32): uint32{. - stdcall, dynlib: "shell32.dll", importc: "DragQueryFileW".} -proc DragQueryPoint*(arg1: HDROP, arg2: LPPOINT): bool{.stdcall, - dynlib: "shell32.dll", importc: "DragQueryPoint".} -proc DragFinish*(arg1: HDROP){.stdcall, dynlib: "shell32.dll", - importc: "DragFinish".} -proc DragAcceptFiles*(hwnd: HWND, arg2: bool){.stdcall, dynlib: "shell32.dll", - importc: "DragAcceptFiles".} -proc ShellExecuteA*(hwnd: HWND, lpOperation: LPCSTR, lpFile: LPCSTR, - lpParameters: LPCSTR, lpDirectory: LPCSTR, nShowCmd: int32): HInst{. - stdcall, dynlib: "shell32.dll", importc: "ShellExecuteA".} -proc ShellExecuteW*(hwnd: HWND, lpOperation: LPCWSTR, lpFile: LPCWSTR, - lpParameters: LPCWSTR, lpDirectory: LPCWSTR, nShowCmd: int32): HInst{. - stdcall, dynlib: "shell32.dll", importc: "ShellExecuteW".} -proc ShellExecute*(hwnd: HWND, lpOperation: LPCSTR, lpFile: LPCSTR, - lpParameters: LPCSTR, lpDirectory: LPCSTR, nShowCmd: int32): HInst{. - stdcall, dynlib: "shell32.dll", importc: "ShellExecuteA".} -proc ShellExecute*(hwnd: HWND, lpOperation: LPCWSTR, lpFile: LPCWSTR, - lpParameters: LPCWSTR, lpDirectory: LPCWSTR, nShowCmd: int32): HInst{. - stdcall, dynlib: "shell32.dll", importc: "ShellExecuteW".} -proc FindExecutableA*(lpFile: LPCSTR, lpDirectory: LPCSTR, lpResult: LPSTR): HInst{. - stdcall, dynlib: "shell32.dll", importc: "FindExecutableA".} -proc FindExecutableW*(lpFile: LPCWSTR, lpDirectory: LPCWSTR, lpResult: LPWSTR): HInst{. - stdcall, dynlib: "shell32.dll", importc: "FindExecutableW".} -proc FindExecutable*(lpFile: LPCSTR, lpDirectory: LPCSTR, lpResult: LPSTR): HInst{. - stdcall, dynlib: "shell32.dll", importc: "FindExecutableA".} -proc FindExecutable*(lpFile: LPCWSTR, lpDirectory: LPCWSTR, lpResult: LPWSTR): HInst{. - stdcall, dynlib: "shell32.dll", importc: "FindExecutableW".} -proc CommandLineToArgvW*(lpCmdLine: LPCWSTR, pNumArgs: ptr int32): PLPWSTR{. - stdcall, dynlib: "shell32.dll", importc: "CommandLineToArgvW".} -proc ShellAboutA*(hwnd: HWND, szApp: LPCSTR, szOtherStuff: LPCSTR, hIcon: HICON): int32{. - stdcall, dynlib: "shell32.dll", importc: "ShellAboutA".} -proc ShellAboutW*(hwnd: HWND, szApp: LPCWSTR, szOtherStuff: LPCWSTR, - hIcon: HICON): int32{.stdcall, dynlib: "shell32.dll", - importc: "ShellAboutW".} -proc ShellAbout*(hwnd: HWND, szApp: LPCSTR, szOtherStuff: LPCSTR, hIcon: HICON): int32{. - stdcall, dynlib: "shell32.dll", importc: "ShellAboutA".} -proc ShellAbout*(hwnd: HWND, szApp: LPCWSTR, szOtherStuff: LPCWSTR, hIcon: HICON): int32{. - stdcall, dynlib: "shell32.dll", importc: "ShellAboutW".} -proc DuplicateIcon*(inst: HINST, icon: HICON): HIcon{.stdcall, - dynlib: "shell32.dll", importc: "DuplicateIcon".} -proc ExtractAssociatedIconA*(hInst: HINST, lpIconPath: LPSTR, lpiIcon: LPWORD): HICON{. - stdcall, dynlib: "shell32.dll", importc: "ExtractAssociatedIconA".} -proc ExtractAssociatedIconW*(hInst: HINST, lpIconPath: LPWSTR, lpiIcon: LPWORD): HICON{. - stdcall, dynlib: "shell32.dll", importc: "ExtractAssociatedIconW".} -proc ExtractAssociatedIcon*(hInst: HINST, lpIconPath: LPSTR, lpiIcon: LPWORD): HICON{. - stdcall, dynlib: "shell32.dll", importc: "ExtractAssociatedIconA".} -proc ExtractAssociatedIcon*(hInst: HINST, lpIconPath: LPWSTR, lpiIcon: LPWORD): HICON{. - stdcall, dynlib: "shell32.dll", importc: "ExtractAssociatedIconW".} -proc ExtractIconA*(hInst: HINST, lpszExeFileName: LPCSTR, nIconIndex: uint32): HICON{. - stdcall, dynlib: "shell32.dll", importc: "ExtractIconA".} -proc ExtractIconW*(hInst: HINST, lpszExeFileName: LPCWSTR, nIconIndex: uint32): HICON{. - stdcall, dynlib: "shell32.dll", importc: "ExtractIconW".} -proc ExtractIcon*(hInst: HINST, lpszExeFileName: LPCSTR, nIconIndex: uint32): HICON{. - stdcall, dynlib: "shell32.dll", importc: "ExtractIconA".} -proc ExtractIcon*(hInst: HINST, lpszExeFileName: LPCWSTR, nIconIndex: uint32): HICON{. - stdcall, dynlib: "shell32.dll", importc: "ExtractIconW".} - # if(WINVER >= 0x0400) -type # init with sizeof(DRAGINFO) - DRAGINFOA* {.final.} = object - uSize*: uint32 - pt*: POINT - fNC*: bool - lpFileList*: LPSTR - grfKeyState*: DWORD - - LPDRAGINFOA* = ptr DRAGINFOA # init with sizeof(DRAGINFO) - DRAGINFOW* {.final.} = object - uSize*: uint32 - pt*: POINT - fNC*: bool - lpFileList*: LPWSTR - grfKeyState*: DWORD - - LPDRAGINFOW* = ptr DRAGINFOW -{.deprecated: [TDRAGINFOA: DRAGINFOA, TDRAGINFOW: DRAGINFOW].} - -when defined(UNICODE): - type - DRAGINFO* = DRAGINFOW - LPDRAGINFO* = LPDRAGINFOW - {.deprecated: [TDRAGINFO: DRAGINFOW].} -else: - type - DRAGINFO* = DRAGINFOA - LPDRAGINFO* = LPDRAGINFOA - {.deprecated: [TDRAGINFO: DRAGINFOW].} -const - ABM_NEW* = 0x00000000 - ABM_REMOVE* = 0x00000001 - ABM_QUERYPOS* = 0x00000002 - ABM_SETPOS* = 0x00000003 - ABM_GETSTATE* = 0x00000004 - ABM_GETTASKBARPOS* = 0x00000005 - ABM_ACTIVATE* = 0x00000006 # lParam == TRUE/FALSE means activate/deactivate - ABM_GETAUTOHIDEBAR* = 0x00000007 - ABM_SETAUTOHIDEBAR* = 0x00000008 # this can fail at any time. MUST check the result - # lParam = TRUE/FALSE Set/Unset - # uEdge = what edge - ABM_WINDOWPOSCHANGED* = 0x00000009 - ABM_SETSTATE* = 0x0000000A - ABN_STATECHANGE* = 0x00000000 # these are put in the wparam of callback messages - ABN_POSCHANGED* = 0x00000001 - ABN_FULLSCREENAPP* = 0x00000002 - ABN_WINDOWARRANGE* = 0x00000003 # lParam == TRUE means hide - # flags for get state - ABS_AUTOHIDE* = 0x00000001 - ABS_ALWAYSONTOP* = 0x00000002 - ABE_LEFT* = 0 - ABE_TOP* = 1 - ABE_RIGHT* = 2 - ABE_BOTTOM* = 3 - -type - AppBarData* {.final.} = object - cbSize*: DWORD - hWnd*: HWND - uCallbackMessage*: uint32 - uEdge*: uint32 - rc*: RECT - lParam*: LPARAM # message specific - - PAPPBARDATA* = ptr AppBarData -{.deprecated: [TAPPBARDATA: AppBarData].} - -proc SHAppBarMessage*(dwMessage: DWORD, pData: APPBARDATA): UINT_PTR{.stdcall, - dynlib: "shell32.dll", importc: "SHAppBarMessage".} - # - # EndAppBar - # -proc DoEnvironmentSubstA*(szString: LPSTR, cchString: uint32): DWORD{.stdcall, - dynlib: "shell32.dll", importc: "DoEnvironmentSubstA".} -proc DoEnvironmentSubstW*(szString: LPWSTR, cchString: uint32): DWORD{.stdcall, - dynlib: "shell32.dll", importc: "DoEnvironmentSubstW".} -proc DoEnvironmentSubst*(szString: LPSTR, cchString: uint32): DWORD{.stdcall, - dynlib: "shell32.dll", importc: "DoEnvironmentSubstA".} -proc DoEnvironmentSubst*(szString: LPWSTR, cchString: uint32): DWORD{.stdcall, - dynlib: "shell32.dll", importc: "DoEnvironmentSubstW".} - #Macro -proc EIRESID*(x: int32): int32 -proc ExtractIconExA*(lpszFile: LPCSTR, nIconIndex: int32, phiconLarge: PHICON, - phiconSmall: PHICON, nIcons: uint32): uint32{.stdcall, - dynlib: "shell32.dll", importc: "ExtractIconExA".} -proc ExtractIconExW*(lpszFile: LPCWSTR, nIconIndex: int32, phiconLarge: PHICON, - phiconSmall: PHICON, nIcons: uint32): uint32{.stdcall, - dynlib: "shell32.dll", importc: "ExtractIconExW".} -proc ExtractIconExA*(lpszFile: LPCSTR, nIconIndex: int32, - phiconLarge: var HICON, phiconSmall: var HIcon, - nIcons: uint32): uint32{.stdcall, dynlib: "shell32.dll", - importc: "ExtractIconExA".} -proc ExtractIconExW*(lpszFile: LPCWSTR, nIconIndex: int32, - phiconLarge: var HICON, phiconSmall: var HIcon, - nIcons: uint32): uint32{.stdcall, dynlib: "shell32.dll", - importc: "ExtractIconExW".} -proc ExtractIconEx*(lpszFile: LPCSTR, nIconIndex: int32, phiconLarge: PHICON, - phiconSmall: PHICON, nIcons: uint32): uint32{.stdcall, - dynlib: "shell32.dll", importc: "ExtractIconExA".} -proc ExtractIconEx*(lpszFile: LPCWSTR, nIconIndex: int32, phiconLarge: PHICON, - phiconSmall: PHICON, nIcons: uint32): uint32{.stdcall, - dynlib: "shell32.dll", importc: "ExtractIconExW".} -proc ExtractIconEx*(lpszFile: LPCSTR, nIconIndex: int32, phiconLarge: var HICON, - phiconSmall: var HIcon, nIcons: uint32): uint32{.stdcall, - dynlib: "shell32.dll", importc: "ExtractIconExA".} -proc ExtractIconEx*(lpszFile: LPCWSTR, nIconIndex: int32, - phiconLarge: var HICON, phiconSmall: var HIcon, nIcons: uint32): uint32{. - stdcall, dynlib: "shell32.dll", importc: "ExtractIconExW".} - # - # Shell File Operations - # - #ifndef FO_MOVE //these need to be kept in sync with the ones in shlobj.h} -const - FO_MOVE* = 0x00000001 - FO_COPY* = 0x00000002 - FO_DELETE* = 0x00000003 - FO_RENAME* = 0x00000004 - FOF_MULTIDESTFILES* = 0x00000001 - FOF_CONFIRMMOUSE* = 0x00000002 - FOF_SILENT* = 0x00000004 # don't create progress/report - FOF_RENAMEONCOLLISION* = 0x00000008 - FOF_NOCONFIRMATION* = 0x00000010 # Don't prompt the user. - FOF_WANTMAPPINGHANDLE* = 0x00000020 # Fill in SHFILEOPSTRUCT.hNameMappings - FOF_ALLOWUNDO* = 0x00000040 # Must be freed using SHFreeNameMappings - FOF_FILESONLY* = 0x00000080 # on *.*, do only files - FOF_SIMPLEPROGRESS* = 0x00000100 # means don't show names of files - FOF_NOCONFIRMMKDIR* = 0x00000200 # don't confirm making any needed dirs - FOF_NOERRORUI* = 0x00000400 # don't put up error UI - FOF_NOCOPYSECURITYATTRIBS* = 0x00000800 # dont copy NT file Security Attributes - FOF_NORECURSION* = 0x00001000 # don't recurse into directories. - #if (_WIN32_IE >= 0x0500) - FOF_NO_CONNECTED_ELEMENTS* = 0x00002000 # don't operate on connected elements. - FOF_WANTNUKEWARNING* = 0x00004000 # during delete operation, warn if nuking instead of recycling (partially overrides FOF_NOCONFIRMATION) - #endif - #if (_WIN32_WINNT >= 0x0501) - FOF_NORECURSEREPARSE* = 0x00008000 # treat reparse points as objects, not containers - #endif - -type - FILEOP_FLAGS* = int16 - -const - PO_DELETE* = 0x00000013 # printer is being deleted - PO_RENAME* = 0x00000014 # printer is being renamed - PO_PORTCHANGE* = 0x00000020 # port this printer connected to is being changed - # if this id is set, the strings received by - # the copyhook are a doubly-null terminated - # list of strings. The first is the printer - # name and the second is the printer port. - PO_REN_PORT* = 0x00000034 # PO_RENAME and PO_PORTCHANGE at same time. - # no POF_ flags currently defined - -type - PRINTEROP_FLAGS* = int16 #endif} - # FO_MOVE - # implicit parameters are: - # if pFrom or pTo are unqualified names the current directories are - # taken from the global current drive/directory settings managed - # by Get/SetCurrentDrive/Directory - # - # the global confirmation settings - # only used if FOF_SIMPLEPROGRESS - -type - SHFILEOPSTRUCTA* {.final.} = object - hwnd*: HWND - wFunc*: uint32 - pFrom*: LPCSTR - pTo*: LPCSTR - fFlags*: FILEOP_FLAGS - fAnyOperationsAborted*: bool - hNameMappings*: LPVOID - lpszProgressTitle*: LPCSTR # only used if FOF_SIMPLEPROGRESS - - LPSHFILEOPSTRUCTA* = ptr SHFILEOPSTRUCTA - SHFILEOPSTRUCTW* {.final.} = object - hwnd*: HWND - wFunc*: uint32 - pFrom*: LPCWSTR - pTo*: LPCWSTR - fFlags*: FILEOP_FLAGS - fAnyOperationsAborted*: bool - hNameMappings*: LPVOID - lpszProgressTitle*: LPCWSTR - - LPSHFILEOPSTRUCTW* = ptr SHFILEOPSTRUCTW -{.deprecated: [TSHFILEOPSTRUCTA: SHFILEOPSTRUCTA, - TSHFILEOPSTRUCTW: SHFILEOPSTRUCTW].} - -when defined(UNICODE): - type - SHFILEOPSTRUCT* = SHFILEOPSTRUCTW - LPSHFILEOPSTRUCT* = LPSHFILEOPSTRUCTW - {.deprecated: [TSHFILEOPSTRUCT: SHFILEOPSTRUCTW].} -else: - type - SHFILEOPSTRUCT* = SHFILEOPSTRUCTA - LPSHFILEOPSTRUCT* = LPSHFILEOPSTRUCTA - {.deprecated: [TSHFILEOPSTRUCT: SHFILEOPSTRUCTA].} - -proc SHFileOperationA*(lpFileOp: LPSHFILEOPSTRUCTA): int32{.stdcall, - dynlib: "shell32.dll", importc: "SHFileOperationA".} -proc SHFileOperationW*(lpFileOp: LPSHFILEOPSTRUCTW): int32{.stdcall, - dynlib: "shell32.dll", importc: "SHFileOperationW".} -proc SHFileOperation*(lpFileOp: LPSHFILEOPSTRUCTA): int32{.stdcall, - dynlib: "shell32.dll", importc: "SHFileOperationA".} -proc SHFileOperation*(lpFileOp: LPSHFILEOPSTRUCTW): int32{.stdcall, - dynlib: "shell32.dll", importc: "SHFileOperationW".} -proc SHFreeNameMappings*(hNameMappings: Handle){.stdcall, - dynlib: "shell32.dll", importc: "SHFreeNameMappings".} -type - SHNAMEMAPPINGA* {.final.} = object - pszOldPath*: LPSTR - pszNewPath*: LPSTR - cchOldPath*: int32 - cchNewPath*: int32 - - LPSHNAMEMAPPINGA* = ptr SHNAMEMAPPINGA - SHNAMEMAPPINGW* {.final.} = object - pszOldPath*: LPWSTR - pszNewPath*: LPWSTR - cchOldPath*: int32 - cchNewPath*: int32 - - LPSHNAMEMAPPINGW* = ptr SHNAMEMAPPINGW -{.deprecated: [TSHNAMEMAPPINGA: SHNAMEMAPPINGA, - TSHNAMEMAPPINGW: SHNAMEMAPPINGW].} - -when not(defined(UNICODE)): - type - SHNAMEMAPPING* = SHNAMEMAPPINGW - LPSHNAMEMAPPING* = LPSHNAMEMAPPINGW - {.deprecated: [TSHNAMEMAPPING: SHNAMEMAPPINGW].} -else: - type - SHNAMEMAPPING* = SHNAMEMAPPINGA - LPSHNAMEMAPPING* = LPSHNAMEMAPPINGA - {.deprecated: [TSHNAMEMAPPING: SHNAMEMAPPINGA].} -# -# End Shell File Operations -# -# -# Begin ShellExecuteEx and family -# -# ShellExecute() and ShellExecuteEx() error codes -# regular WinExec() codes - -const - SE_ERR_FNF* = 2 # file not found - SE_ERR_PNF* = 3 # path not found - SE_ERR_ACCESSDENIED* = 5 # access denied - SE_ERR_OOM* = 8 # out of memory - SE_ERR_DLLNOTFOUND* = 32 # endif WINVER >= 0x0400 - # error values for ShellExecute() beyond the regular WinExec() codes - SE_ERR_SHARE* = 26 - SE_ERR_ASSOCINCOMPLETE* = 27 - SE_ERR_DDETIMEOUT* = 28 - SE_ERR_DDEFAIL* = 29 - SE_ERR_DDEBUSY* = 30 - SE_ERR_NOASSOC* = 31 #if(WINVER >= 0x0400)} - # Note CLASSKEY overrides CLASSNAME - SEE_MASK_CLASSNAME* = 0x00000001 - SEE_MASK_CLASSKEY* = 0x00000003 # Note INVOKEIDLIST overrides IDLIST - SEE_MASK_IDLIST* = 0x00000004 - SEE_MASK_INVOKEIDLIST* = 0x0000000C - SEE_MASK_ICON* = 0x00000010 - SEE_MASK_HOTKEY* = 0x00000020 - SEE_MASK_NOCLOSEPROCESS* = 0x00000040 - SEE_MASK_CONNECTNETDRV* = 0x00000080 - SEE_MASK_FLAG_DDEWAIT* = 0x00000100 - SEE_MASK_DOENVSUBST* = 0x00000200 - SEE_MASK_FLAG_NO_UI* = 0x00000400 - SEE_MASK_UNICODE* = 0x00004000 - SEE_MASK_NO_CONSOLE* = 0x00008000 - SEE_MASK_ASYNCOK* = 0x00100000 - SEE_MASK_HMONITOR* = 0x00200000 #if (_WIN32_IE >= 0x0500) - SEE_MASK_NOQUERYCLASSSTORE* = 0x01000000 - SEE_MASK_WAITFORINPUTIDLE* = 0x02000000 #endif (_WIN32_IE >= 0x500) - #if (_WIN32_IE >= 0x0560) - SEE_MASK_FLAG_LOG_USAGE* = 0x04000000 #endif - # (_WIN32_IE >= 0x560) - -type - SHELLEXECUTEINFOA* {.final.} = object - cbSize*: DWORD - fMask*: ULONG - hwnd*: HWND - lpVerb*: LPCSTR - lpFile*: LPCSTR - lpParameters*: LPCSTR - lpDirectory*: LPCSTR - nShow*: int32 - hInstApp*: HINST - lpIDList*: LPVOID - lpClass*: LPCSTR - hkeyClass*: HKEY - dwHotKey*: DWORD - hMonitor*: HANDLE # also: hIcon - hProcess*: HANDLE - - LPSHELLEXECUTEINFOA* = ptr SHELLEXECUTEINFOA - SHELLEXECUTEINFOW* {.final.} = object - cbSize*: DWORD - fMask*: ULONG - hwnd*: HWND - lpVerb*: LPCWSTR - lpFile*: LPCWSTR - lpParameters*: LPCWSTR - lpDirectory*: LPCWSTR - nShow*: int32 - hInstApp*: HINST - lpIDList*: LPVOID - lpClass*: LPCWSTR - hkeyClass*: HKEY - dwHotKey*: DWORD - hMonitor*: HANDLE # also: hIcon - hProcess*: HANDLE - - LPSHELLEXECUTEINFOW* = ptr SHELLEXECUTEINFOW -{.deprecated: [TSHELLEXECUTEINFOA: SHELLEXECUTEINFOA, - TSHELLEXECUTEINFOW: SHELLEXECUTEINFOW].} - -when defined(UNICODE): - type - SHELLEXECUTEINFO* = SHELLEXECUTEINFOW - LPSHELLEXECUTEINFO* = LPSHELLEXECUTEINFOW - {.deprecated: [TSHELLEXECUTEINFO: SHELLEXECUTEINFOW].} -else: - type - SHELLEXECUTEINFO* = SHELLEXECUTEINFOA - LPSHELLEXECUTEINFO* = LPSHELLEXECUTEINFOA - {.deprecated: [TSHELLEXECUTEINFO: SHELLEXECUTEINFOA].} - -proc ShellExecuteExA*(lpExecInfo: LPSHELLEXECUTEINFOA): bool{.stdcall, - dynlib: "shell32.dll", importc: "ShellExecuteExA".} -proc ShellExecuteExW*(lpExecInfo: LPSHELLEXECUTEINFOW): bool{.stdcall, - dynlib: "shell32.dll", importc: "ShellExecuteExW".} -proc ShellExecuteEx*(lpExecInfo: LPSHELLEXECUTEINFOA): bool{.stdcall, - dynlib: "shell32.dll", importc: "ShellExecuteExA".} -proc ShellExecuteEx*(lpExecInfo: LPSHELLEXECUTEINFOW): bool{.stdcall, - dynlib: "shell32.dll", importc: "ShellExecuteExW".} -proc WinExecErrorA*(hwnd: HWND, error: int32, lpstrFileName: LPCSTR, - lpstrTitle: LPCSTR){.stdcall, dynlib: "shell32.dll", - importc: "WinExecErrorA".} -proc WinExecErrorW*(hwnd: HWND, error: int32, lpstrFileName: LPCWSTR, - lpstrTitle: LPCWSTR){.stdcall, dynlib: "shell32.dll", - importc: "WinExecErrorW".} -proc WinExecError*(hwnd: HWND, error: int32, lpstrFileName: LPCSTR, - lpstrTitle: LPCSTR){.stdcall, dynlib: "shell32.dll", - importc: "WinExecErrorA".} -proc WinExecError*(hwnd: HWND, error: int32, lpstrFileName: LPCWSTR, - lpstrTitle: LPCWSTR){.stdcall, dynlib: "shell32.dll", - importc: "WinExecErrorW".} -type - SHCREATEPROCESSINFOW* {.final.} = object - cbSize*: DWORD - fMask*: ULONG - hwnd*: HWND - pszFile*: LPCWSTR - pszParameters*: LPCWSTR - pszCurrentDirectory*: LPCWSTR - hUserToken*: HANDLE - lpProcessAttributes*: LPSECURITY_ATTRIBUTES - lpThreadAttributes*: LPSECURITY_ATTRIBUTES - bInheritHandles*: bool - dwCreationFlags*: DWORD - lpStartupInfo*: LPSTARTUPINFOW - lpProcessInformation*: LPPROCESS_INFORMATION - - PSHCREATEPROCESSINFOW* = ptr SHCREATEPROCESSINFOW -{.deprecated: [TSHCREATEPROCESSINFOW: SHCREATEPROCESSINFOW].} - -proc SHCreateProcessAsUserW*(pscpi: PSHCREATEPROCESSINFOW): bool{.stdcall, - dynlib: "shell32.dll", importc: "SHCreateProcessAsUserW".} - # - # End ShellExecuteEx and family } - # - # - # RecycleBin - # - # struct for query recycle bin info -type - SHQUERYRBINFO* {.final.} = object - cbSize*: DWORD - i64Size*: int64 - i64NumItems*: int64 - - LPSHQUERYRBINFO* = ptr SHQUERYRBINFO # flags for SHEmptyRecycleBin -{.deprecated: [TSHQUERYRBINFO: SHQUERYRBINFO].} - -const - SHERB_NOCONFIRMATION* = 0x00000001 - SHERB_NOPROGRESSUI* = 0x00000002 - SHERB_NOSOUND* = 0x00000004 - -proc SHQueryRecycleBinA*(pszRootPath: LPCSTR, pSHQueryRBInfo: LPSHQUERYRBINFO): HRESULT{. - stdcall, dynlib: "shell32.dll", importc: "SHQueryRecycleBinA".} -proc SHQueryRecycleBinW*(pszRootPath: LPCWSTR, pSHQueryRBInfo: LPSHQUERYRBINFO): HRESULT{. - stdcall, dynlib: "shell32.dll", importc: "SHQueryRecycleBinW".} -proc SHQueryRecycleBin*(pszRootPath: LPCSTR, pSHQueryRBInfo: LPSHQUERYRBINFO): HRESULT{. - stdcall, dynlib: "shell32.dll", importc: "SHQueryRecycleBinA".} -proc SHQueryRecycleBin*(pszRootPath: LPCWSTR, pSHQueryRBInfo: LPSHQUERYRBINFO): HRESULT{. - stdcall, dynlib: "shell32.dll", importc: "SHQueryRecycleBinW".} -proc SHEmptyRecycleBinA*(hwnd: HWND, pszRootPath: LPCSTR, dwFlags: DWORD): HRESULT{. - stdcall, dynlib: "shell32.dll", importc: "SHEmptyRecycleBinA".} -proc SHEmptyRecycleBinW*(hwnd: HWND, pszRootPath: LPCWSTR, dwFlags: DWORD): HRESULT{. - stdcall, dynlib: "shell32.dll", importc: "SHEmptyRecycleBinW".} -proc SHEmptyRecycleBin*(hwnd: HWND, pszRootPath: LPCSTR, dwFlags: DWORD): HRESULT{. - stdcall, dynlib: "shell32.dll", importc: "SHEmptyRecycleBinA".} -proc SHEmptyRecycleBin*(hwnd: HWND, pszRootPath: LPCWSTR, dwFlags: DWORD): HRESULT{. - stdcall, dynlib: "shell32.dll", importc: "SHEmptyRecycleBinW".} - # - # end of RecycleBin - # - # - # Tray notification definitions - # -type - NOTIFYICONDATAA* {.final.} = object - cbSize*: DWORD - hWnd*: HWND - uID*: uint32 - uFlags*: uint32 - uCallbackMessage*: uint32 - hIcon*: HICON - szTip*: array[0..127, char] - dwState*: DWORD - dwStateMask*: DWORD - szInfo*: array[0..255, char] - uTimeout*: uint32 # also: uVersion - szInfoTitle*: array[0..63, char] - dwInfoFlags*: DWORD - guidItem*: GUID - - PNOTIFYICONDATAA* = ptr NOTIFYICONDATAA - NOTIFYICONDATAW* {.final.} = object - cbSize*: DWORD - hWnd*: HWND - uID*: uint32 - uFlags*: uint32 - uCallbackMessage*: uint32 - hIcon*: HICON - szTip*: array[0..127, Wchar] - dwState*: DWORD - dwStateMask*: DWORD - szInfo*: array[0..255, Wchar] - uTimeout*: uint32 # also uVersion : UINT - szInfoTitle*: array[0..63, char] - dwInfoFlags*: DWORD - guidItem*: GUID - - PNOTIFYICONDATAW* = ptr NOTIFYICONDATAW -{.deprecated: [TNOTIFYICONDATAA: NOTIFYICONDATAA, - TNOTIFYICONDATAW: NOTIFYICONDATAW].} - -when defined(UNICODE): - type - NOTIFYICONDATA* = NOTIFYICONDATAW - PNOTIFYICONDATA* = PNOTIFYICONDATAW - {.deprecated: [TNOTIFYICONDATA: NOTIFYICONDATAW].} -else: - type - NOTIFYICONDATA* = NOTIFYICONDATAA - PNOTIFYICONDATA* = PNOTIFYICONDATAA - {.deprecated: [TNOTIFYICONDATA: NOTIFYICONDATAA].} -const - NIN_SELECT* = WM_USER + 0 - NINF_KEY* = 0x00000001 - NIN_KEYSELECT* = NIN_SELECT or NINF_KEY - NIN_BALLOONSHOW* = WM_USER + 2 - NIN_BALLOONHIDE* = WM_USER + 3 - NIN_BALLOONTIMEOUT* = WM_USER + 4 - NIN_BALLOONUSERCLICK* = WM_USER + 5 - NIM_ADD* = 0x00000000 - NIM_MODIFY* = 0x00000001 - NIM_DELETE* = 0x00000002 - NIM_SETFOCUS* = 0x00000003 - NIM_SETVERSION* = 0x00000004 - NOTIFYICON_VERSION* = 3 - NIF_MESSAGE* = 0x00000001 - NIF_ICON* = 0x00000002 - NIF_TIP* = 0x00000004 - NIF_STATE* = 0x00000008 - NIF_INFO* = 0x00000010 - NIF_GUID* = 0x00000020 - NIS_HIDDEN* = 0x00000001 - NIS_SHAREDICON* = 0x00000002 # says this is the source of a shared icon - # Notify Icon Infotip flags - NIIF_NONE* = 0x00000000 # icon flags are mutually exclusive - # and take only the lowest 2 bits - NIIF_INFO* = 0x00000001 - NIIF_WARNING* = 0x00000002 - NIIF_ERROR* = 0x00000003 - NIIF_ICON_MASK* = 0x0000000F - NIIF_NOSOUND* = 0x00000010 - -proc Shell_NotifyIconA*(dwMessage: Dword, lpData: PNOTIFYICONDATAA): bool{. - stdcall, dynlib: "shell32.dll", importc: "Shell_NotifyIconA".} -proc Shell_NotifyIconW*(dwMessage: Dword, lpData: PNOTIFYICONDATAW): bool{. - stdcall, dynlib: "shell32.dll", importc: "Shell_NotifyIconW".} -proc Shell_NotifyIcon*(dwMessage: Dword, lpData: PNOTIFYICONDATAA): bool{. - stdcall, dynlib: "shell32.dll", importc: "Shell_NotifyIconA".} -proc Shell_NotifyIcon*(dwMessage: Dword, lpData: PNOTIFYICONDATAW): bool{. - stdcall, dynlib: "shell32.dll", importc: "Shell_NotifyIconW".} - # - # The SHGetFileInfo API provides an easy way to get attributes - # for a file given a pathname. - # - # PARAMETERS - # - # pszPath file name to get info about - # dwFileAttributes file attribs, only used with SHGFI_USEFILEATTRIBUTES - # psfi place to return file info - # cbFileInfo size of structure - # uFlags flags - # - # RETURN - # TRUE if things worked - # - # out: icon - # out: icon index - # out: SFGAO_ flags - # out: display name (or path) - # out: type name -type - SHFILEINFOA* {.final.} = object - hIcon*: HICON # out: icon - iIcon*: int32 # out: icon index - dwAttributes*: DWORD # out: SFGAO_ flags - szDisplayName*: array[0..(MAX_PATH) - 1, char] # out: display name (or path) - szTypeName*: array[0..79, char] # out: type name - - PSHFILEINFOA* = ptr SHFILEINFOA - SHFILEINFOW* {.final.} = object - hIcon*: HICON # out: icon - iIcon*: int32 # out: icon index - dwAttributes*: DWORD # out: SFGAO_ flags - szDisplayName*: array[0..(MAX_PATH) - 1, Wchar] # out: display name (or path) - szTypeName*: array[0..79, Wchar] # out: type name - - PSHFILEINFOW* = ptr SHFILEINFOW -{.deprecated: [TSHFILEINFOA: SHFILEINFOA, TSHFILEINFOW: SHFILEINFOW].} - -when defined(UNICODE): - type - SHFILEINFO* = SHFILEINFOW - pFILEINFO* = SHFILEINFOW - {.deprecated: [TSHFILEINFO: SHFILEINFOW].} -else: - type - SHFILEINFO* = SHFILEINFOA - pFILEINFO* = SHFILEINFOA - {.deprecated: [TSHFILEINFO: SHFILEINFOA].} -# NOTE: This is also in shlwapi.h. Please keep in synch. - -const - SHGFI_ICON* = 0x00000100 # get Icon - SHGFI_DISPLAYNAME* = 0x00000200 # get display name - SHGFI_TYPENAME* = 0x00000400 # get type name - SHGFI_ATTRIBUTES* = 0x00000800 # get attributes - SHGFI_ICONLOCATION* = 0x00001000 # get icon location - SHGFI_EXETYPE* = 0x00002000 # return exe type - SHGFI_SYSICONINDEX* = 0x00004000 # get system icon index - SHGFI_LINKOVERLAY* = 0x00008000 # put a link overlay on icon - SHGFI_SELECTED* = 0x00010000 # show icon in selected state - SHGFI_ATTR_SPECIFIED* = 0x00020000 # get only specified attributes - SHGFI_LARGEICON* = 0x00000000 # get large icon - SHGFI_SMALLICON* = 0x00000001 # get small icon - SHGFI_OPENICON* = 0x00000002 # get open icon - SHGFI_SHELLICONSIZE* = 0x00000004 # get shell size icon - SHGFI_PIDL* = 0x00000008 # pszPath is a pidl - SHGFI_USEFILEATTRIBUTES* = 0x00000010 # use passed dwFileAttribute - SHGFI_ADDOVERLAYS* = 0x00000020 # apply the appropriate overlays - SHGFI_OVERLAYINDEX* = 0x00000040 # Get the index of the overlay - # in the upper 8 bits of the iIcon - -proc SHGetFileInfoA*(pszPath: LPCSTR, dwFileAttributes: DWORD, - psfi: PSHFILEINFOA, cbFileInfo, UFlags: uint32): DWORD{. - stdcall, dynlib: "shell32.dll", importc: "SHGetFileInfoA".} -proc SHGetFileInfoW*(pszPath: LPCWSTR, dwFileAttributes: DWORD, - psfi: PSHFILEINFOW, cbFileInfo, UFlags: uint32): DWORD{. - stdcall, dynlib: "shell32.dll", importc: "SHGetFileInfoW".} -proc SHGetFileInfo*(pszPath: LPCSTR, dwFileAttributes: DWORD, - psfi: PSHFILEINFOA, cbFileInfo, UFlags: uint32): DWORD{. - stdcall, dynlib: "shell32.dll", importc: "SHGetFileInfoA".} -proc SHGetFileInfoA*(pszPath: LPCSTR, dwFileAttributes: DWORD, - psfi: var SHFILEINFOA, cbFileInfo, UFlags: uint32): DWORD{. - stdcall, dynlib: "shell32.dll", importc: "SHGetFileInfoA".} -proc SHGetFileInfoW*(pszPath: LPCWSTR, dwFileAttributes: DWORD, - psfi: var SHFILEINFOW, cbFileInfo, UFlags: uint32): DWORD{. - stdcall, dynlib: "shell32.dll", importc: "SHGetFileInfoW".} -proc SHGetFileInfo*(pszPath: LPCSTR, dwFileAttributes: DWORD, - psfi: var SHFILEINFOA, cbFileInfo, UFlags: uint32): DWORD{. - stdcall, dynlib: "shell32.dll", importc: "SHGetFileInfoA".} -proc SHGetFileInfo*(pszPath: LPCWSTR, dwFileAttributes: DWORD, - psfi: var SHFILEINFOW, cbFileInfo, UFlags: uint32): DWORD{. - stdcall, dynlib: "shell32.dll", importc: "SHGetFileInfoW".} -proc SHGetDiskFreeSpaceExA*(pszDirectoryName: LPCSTR, - pulFreeBytesAvailableToCaller: PULARGE_INTEGER, - pulTotalNumberOfBytes: PULARGE_INTEGER, - pulTotalNumberOfFreeBytes: PULARGE_INTEGER): bool{. - stdcall, dynlib: "shell32.dll", importc: "SHGetDiskFreeSpaceExA".} -proc SHGetDiskFreeSpaceExW*(pszDirectoryName: LPCWSTR, - pulFreeBytesAvailableToCaller: PULARGE_INTEGER, - pulTotalNumberOfBytes: PULARGE_INTEGER, - pulTotalNumberOfFreeBytes: PULARGE_INTEGER): bool{. - stdcall, dynlib: "shell32.dll", importc: "SHGetDiskFreeSpaceExW".} -proc SHGetDiskFreeSpaceEx*(pszDirectoryName: LPCSTR, - pulFreeBytesAvailableToCaller: PULARGE_INTEGER, - pulTotalNumberOfBytes: PULARGE_INTEGER, - pulTotalNumberOfFreeBytes: PULARGE_INTEGER): bool{. - stdcall, dynlib: "shell32.dll", importc: "SHGetDiskFreeSpaceExA".} -proc SHGetDiskFreeSpace*(pszDirectoryName: LPCSTR, - pulFreeBytesAvailableToCaller: PULARGE_INTEGER, - pulTotalNumberOfBytes: PULARGE_INTEGER, - pulTotalNumberOfFreeBytes: PULARGE_INTEGER): bool{. - stdcall, dynlib: "shell32.dll", importc: "SHGetDiskFreeSpaceExA".} -proc SHGetDiskFreeSpaceEx*(pszDirectoryName: LPCWSTR, - pulFreeBytesAvailableToCaller: PULARGE_INTEGER, - pulTotalNumberOfBytes: PULARGE_INTEGER, - pulTotalNumberOfFreeBytes: PULARGE_INTEGER): bool{. - stdcall, dynlib: "shell32.dll", importc: "SHGetDiskFreeSpaceExW".} -proc SHGetDiskFreeSpace*(pszDirectoryName: LPCWSTR, - pulFreeBytesAvailableToCaller: PULARGE_INTEGER, - pulTotalNumberOfBytes: PULARGE_INTEGER, - pulTotalNumberOfFreeBytes: PULARGE_INTEGER): bool{. - stdcall, dynlib: "shell32.dll", importc: "SHGetDiskFreeSpaceExW".} -proc SHGetNewLinkInfoA*(pszLinkTo: LPCSTR, pszDir: LPCSTR, pszName: LPSTR, - pfMustCopy: PBool, uFlags: uint32): bool{.stdcall, - dynlib: "shell32.dll", importc: "SHGetNewLinkInfoA".} -proc SHGetNewLinkInfoW*(pszLinkTo: LPCWSTR, pszDir: LPCWSTR, pszName: LPWSTR, - pfMustCopy: PBool, uFlags: uint32): bool{.stdcall, - dynlib: "shell32.dll", importc: "SHGetNewLinkInfoW".} -proc SHGetNewLinkInfo*(pszLinkTo: LPCSTR, pszDir: LPCSTR, pszName: LPSTR, - pfMustCopy: PBool, uFlags: uint32): bool{.stdcall, - dynlib: "shell32.dll", importc: "SHGetNewLinkInfoA".} -proc SHGetNewLinkInfo*(pszLinkTo: LPCWSTR, pszDir: LPCWSTR, pszName: LPWSTR, - pfMustCopy: PBool, uFlags: uint32): bool{.stdcall, - dynlib: "shell32.dll", importc: "SHGetNewLinkInfoW".} -const - SHGNLI_PIDL* = 0x00000001 # pszLinkTo is a pidl - SHGNLI_PREFIXNAME* = 0x00000002 # Make name "Shortcut to xxx" - SHGNLI_NOUNIQUE* = 0x00000004 # don't do the unique name generation - SHGNLI_NOLNK* = 0x00000008 # don't add ".lnk" extension - PRINTACTION_OPEN* = 0 - PRINTACTION_PROPERTIES* = 1 - PRINTACTION_NETINSTALL* = 2 - PRINTACTION_NETINSTALLLINK* = 3 - PRINTACTION_TESTPAGE* = 4 - PRINTACTION_OPENNETPRN* = 5 - PRINTACTION_DOCUMENTDEFAULTS* = 6 - PRINTACTION_SERVERPROPERTIES* = 7 - -proc SHInvokePrinterCommandA*(hwnd: HWND, uAction: uint32, lpBuf1: LPCSTR, - lpBuf2: LPCSTR, fModal: bool): bool{.stdcall, - dynlib: "shell32.dll", importc: "SHInvokePrinterCommandA".} -proc SHInvokePrinterCommandW*(hwnd: HWND, uAction: uint32, lpBuf1: LPCWSTR, - lpBuf2: LPCWSTR, fModal: bool): bool{.stdcall, - dynlib: "shell32.dll", importc: "SHInvokePrinterCommandW".} -proc SHInvokePrinterCommand*(hwnd: HWND, uAction: uint32, lpBuf1: LPCSTR, - lpBuf2: LPCSTR, fModal: bool): bool{.stdcall, - dynlib: "shell32.dll", importc: "SHInvokePrinterCommandA".} -proc SHInvokePrinterCommand*(hwnd: HWND, uAction: uint32, lpBuf1: LPCWSTR, - lpBuf2: LPCWSTR, fModal: bool): bool{.stdcall, - dynlib: "shell32.dll", importc: "SHInvokePrinterCommandW".} -proc SHLoadNonloadedIconOverlayIdentifiers*(): HResult{.stdcall, - dynlib: "shell32.dll", importc: "SHInvokePrinterCommandW".} -proc SHIsFileAvailableOffline*(pwszPath: LPCWSTR, pdwStatus: LPDWORD): HRESULT{. - stdcall, dynlib: "shell32.dll", importc: "SHIsFileAvailableOffline".} -const - OFFLINE_STATUS_LOCAL* = 0x00000001 # If open, it's open locally - OFFLINE_STATUS_REMOTE* = 0x00000002 # If open, it's open remotely - OFFLINE_STATUS_INCOMPLETE* = 0x00000004 # The local copy is currently incomplete. - # The file will not be available offline - # until it has been synchronized. - # sets the specified path to use the string resource - # as the UI instead of the file system name - -proc SHSetLocalizedName*(pszPath: LPWSTR, pszResModule: LPCWSTR, idsRes: int32): HRESULT{. - stdcall, dynlib: "shell32.dll", importc: "SHSetLocalizedName".} -proc SHEnumerateUnreadMailAccountsA*(hKeyUser: HKEY, dwIndex: DWORD, - pszMailAddress: LPSTR, - cchMailAddress: int32): HRESULT{.stdcall, - dynlib: "shell32.dll", importc: "SHEnumerateUnreadMailAccountsA".} -proc SHEnumerateUnreadMailAccountsW*(hKeyUser: HKEY, dwIndex: DWORD, - pszMailAddress: LPWSTR, - cchMailAddress: int32): HRESULT{.stdcall, - dynlib: "shell32.dll", importc: "SHEnumerateUnreadMailAccountsW".} -proc SHEnumerateUnreadMailAccounts*(hKeyUser: HKEY, dwIndex: DWORD, - pszMailAddress: LPWSTR, - cchMailAddress: int32): HRESULT{.stdcall, - dynlib: "shell32.dll", importc: "SHEnumerateUnreadMailAccountsW".} -proc SHGetUnreadMailCountA*(hKeyUser: HKEY, pszMailAddress: LPCSTR, - pdwCount: PDWORD, pFileTime: PFILETIME, - pszShellExecuteCommand: LPSTR, - cchShellExecuteCommand: int32): HRESULT{.stdcall, - dynlib: "shell32.dll", importc: "SHGetUnreadMailCountA".} -proc SHGetUnreadMailCountW*(hKeyUser: HKEY, pszMailAddress: LPCWSTR, - pdwCount: PDWORD, pFileTime: PFILETIME, - pszShellExecuteCommand: LPWSTR, - cchShellExecuteCommand: int32): HRESULT{.stdcall, - dynlib: "shell32.dll", importc: "SHGetUnreadMailCountW".} -proc SHGetUnreadMailCount*(hKeyUser: HKEY, pszMailAddress: LPCSTR, - pdwCount: PDWORD, pFileTime: PFILETIME, - pszShellExecuteCommand: LPSTR, - cchShellExecuteCommand: int32): HRESULT{.stdcall, - dynlib: "shell32.dll", importc: "SHGetUnreadMailCountA".} -proc SHGetUnreadMailCount*(hKeyUser: HKEY, pszMailAddress: LPCWSTR, - pdwCount: PDWORD, pFileTime: PFILETIME, - pszShellExecuteCommand: LPWSTR, - cchShellExecuteCommand: int32): HRESULT{.stdcall, - dynlib: "shell32.dll", importc: "SHGetUnreadMailCountW".} -proc SHSetUnreadMailCountA*(pszMailAddress: LPCSTR, dwCount: DWORD, - pszShellExecuteCommand: LPCSTR): HRESULT{.stdcall, - dynlib: "shell32.dll", importc: "SHSetUnreadMailCountA".} -proc SHSetUnreadMailCountW*(pszMailAddress: LPCWSTR, dwCount: DWORD, - pszShellExecuteCommand: LPCWSTR): HRESULT{.stdcall, - dynlib: "shell32.dll", importc: "SHSetUnreadMailCountW".} -proc SHSetUnreadMailCount*(pszMailAddress: LPCSTR, dwCount: DWORD, - pszShellExecuteCommand: LPCSTR): HRESULT{.stdcall, - dynlib: "shell32.dll", importc: "SHSetUnreadMailCountA".} -proc SHSetUnreadMailCount*(pszMailAddress: LPCWSTR, dwCount: DWORD, - pszShellExecuteCommand: LPCWSTR): HRESULT{.stdcall, - dynlib: "shell32.dll", importc: "SHSetUnreadMailCountW".} -proc SHGetImageList*(iImageList: int32, riid: TIID, ppvObj: ptr pointer): HRESULT{. - stdcall, dynlib: "shell32.dll", importc: "SHGetImageList".} -const - SHIL_LARGE* = 0 # normally 32x32 - SHIL_SMALL* = 1 # normally 16x16 - SHIL_EXTRALARGE* = 2 - SHIL_SYSSMALL* = 3 # like SHIL_SMALL, but tracks system small icon metric correctly - SHIL_LAST* = SHIL_SYSSMALL - -# implementation - -proc EIRESID(x: int32): int32 = - result = -x diff --git a/lib/windows/shfolder.nim b/lib/windows/shfolder.nim deleted file mode 100644 index 99cdf6cf5..000000000 --- a/lib/windows/shfolder.nim +++ /dev/null @@ -1,93 +0,0 @@ -# -# -# Nim's Runtime Library -# (c) Copyright 2006 Andreas Rumpf -# -# See the file "copying.txt", included in this -# distribution, for details about the copyright. -# - -# --------------------------------------------------------------------- -# shfolder.dll is distributed standard with IE5.5, so it should ship -# with 2000/XP or higher but is likely to be installed on NT/95/98 or -# ME as well. It works on all these systems. -# -# The info found here is also in the registry: -# HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\ -# HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\ -# -# Note that not all CSIDL_* constants are supported by shlfolder.dll, -# they should be supported by the shell32.dll, though again not on all -# systems. -# --------------------------------------------------------------------- - -{.deadCodeElim: on.} - -import - windows - -const - LibName* = "SHFolder.dll" - -const - CSIDL_PROGRAMS* = 0x00000002 # %SYSTEMDRIVE%\Program Files - CSIDL_PERSONAL* = 0x00000005 # %USERPROFILE%\My Documents - CSIDL_FAVORITES* = 0x00000006 # %USERPROFILE%\Favorites - CSIDL_STARTUP* = 0x00000007 # %USERPROFILE%\Start menu\Programs\Startup - CSIDL_RECENT* = 0x00000008 # %USERPROFILE%\Recent - CSIDL_SENDTO* = 0x00000009 # %USERPROFILE%\Sendto - CSIDL_STARTMENU* = 0x0000000B # %USERPROFILE%\Start menu - CSIDL_MYMUSIC* = 0x0000000D # %USERPROFILE%\Documents\My Music - CSIDL_MYVIDEO* = 0x0000000E # %USERPROFILE%\Documents\My Videos - CSIDL_DESKTOPDIRECTORY* = 0x00000010 # %USERPROFILE%\Desktop - CSIDL_NETHOOD* = 0x00000013 # %USERPROFILE%\NetHood - CSIDL_TEMPLATES* = 0x00000015 # %USERPROFILE%\Templates - CSIDL_COMMON_STARTMENU* = 0x00000016 # %PROFILEPATH%\All users\Start menu - CSIDL_COMMON_PROGRAMS* = 0x00000017 # %PROFILEPATH%\All users\Start menu\Programs - CSIDL_COMMON_STARTUP* = 0x00000018 # %PROFILEPATH%\All users\Start menu\Programs\Startup - CSIDL_COMMON_DESKTOPDIRECTORY* = 0x00000019 # %PROFILEPATH%\All users\Desktop - CSIDL_APPDATA* = 0x0000001A # %USERPROFILE%\Application Data (roaming) - CSIDL_PRINTHOOD* = 0x0000001B # %USERPROFILE%\Printhood - CSIDL_LOCAL_APPDATA* = 0x0000001C # %USERPROFILE%\Local Settings\Application Data (non roaming) - CSIDL_COMMON_FAVORITES* = 0x0000001F # %PROFILEPATH%\All users\Favorites - CSIDL_INTERNET_CACHE* = 0x00000020 # %USERPROFILE%\Local Settings\Temporary Internet Files - CSIDL_COOKIES* = 0x00000021 # %USERPROFILE%\Cookies - CSIDL_HISTORY* = 0x00000022 # %USERPROFILE%\Local settings\History - CSIDL_COMMON_APPDATA* = 0x00000023 # %PROFILESPATH%\All Users\Application Data - CSIDL_WINDOWS* = 0x00000024 # %SYSTEMROOT% - CSIDL_SYSTEM* = 0x00000025 # %SYSTEMROOT%\SYSTEM32 (may be system on 95/98/ME) - CSIDL_PROGRAM_FILES* = 0x00000026 # %SYSTEMDRIVE%\Program Files - CSIDL_MYPICTURES* = 0x00000027 # %USERPROFILE%\My Documents\My Pictures - CSIDL_PROFILE* = 0x00000028 # %USERPROFILE% - CSIDL_PROGRAM_FILES_COMMON* = 0x0000002B # %SYSTEMDRIVE%\Program Files\Common - CSIDL_COMMON_TEMPLATES* = 0x0000002D # %PROFILEPATH%\All Users\Templates - CSIDL_COMMON_DOCUMENTS* = 0x0000002E # %PROFILEPATH%\All Users\Documents - CSIDL_COMMON_ADMINTOOLS* = 0x0000002F # %PROFILEPATH%\All Users\Start Menu\Programs\Administrative Tools - CSIDL_ADMINTOOLS* = 0x00000030 # %USERPROFILE%\Start Menu\Programs\Administrative Tools - CSIDL_COMMON_MUSIC* = 0x00000035 # %PROFILEPATH%\All Users\Documents\my music - CSIDL_COMMON_PICTURES* = 0x00000036 # %PROFILEPATH%\All Users\Documents\my pictures - CSIDL_COMMON_VIDEO* = 0x00000037 # %PROFILEPATH%\All Users\Documents\my videos - CSIDL_CDBURN_AREA* = 0x0000003B # %USERPROFILE%\Local Settings\Application Data\Microsoft\CD Burning - CSIDL_PROFILES* = 0x0000003E # %PROFILEPATH% - CSIDL_FLAG_CREATE* = 0x00008000 # (force creation of requested folder if it doesn't exist yet) - # Original entry points - -proc SHGetFolderPathA*(Ahwnd: HWND, Csidl: int, Token: Handle, Flags: DWord, - Path: cstring): HRESULT{.stdcall, dynlib: LibName, - importc: "SHGetFolderPathA".} -proc SHGetFolderPathW*(Ahwnd: HWND, Csidl: int, Token: Handle, Flags: DWord, - Path: cstring): HRESULT{.stdcall, dynlib: LibName, - importc: "SHGetFolderPathW".} -proc SHGetFolderPath*(Ahwnd: HWND, Csidl: int, Token: Handle, Flags: DWord, - Path: cstring): HRESULT{.stdcall, dynlib: LibName, - importc: "SHGetFolderPathA".} -type - PFNSHGetFolderPathA* = proc (Ahwnd: HWND, Csidl: int, Token: Handle, - Flags: DWord, Path: cstring): HRESULT{.stdcall.} - PFNSHGetFolderPathW* = proc (Ahwnd: HWND, Csidl: int, Token: Handle, - Flags: DWord, Path: cstring): HRESULT{.stdcall.} - PFNSHGetFolderPath* = PFNSHGetFolderPathA - -{.deprecated: [TSHGetFolderPathA: PFNSHGetFolderPathA, - TSHGetFolderPathW: PFNSHGetFolderPathW, - TSHGetFolderPath: SHGetFolderPathA].} diff --git a/lib/windows/windows.nim b/lib/windows/windows.nim deleted file mode 100644 index bddb4cef7..000000000 --- a/lib/windows/windows.nim +++ /dev/null @@ -1,23662 +0,0 @@ -# -# -# Nim's Runtime Library -# (c) Copyright 2010 Andreas Rumpf -# -# See the file "copying.txt", included in this -# distribution, for details about the copyright. -# - -## Define ``winUnicode`` before importing this module for the -## Unicode version. - -{.deadCodeElim: on.} -{.push gcsafe.} -type - WideChar* = uint16 - PWideChar* = ptr uint16 - -type # WinNT.h -- Defines the 32-Bit Windows types and constants - SHORT* = int16 - LONG* = int32 - # UNICODE (Wide Character) types - PWCHAR* = PWideChar - LPWCH* = PWideChar - PWCH* = PWideChar - LPCWCH* = PWideChar - PCWCH* = PWideChar - NWPSTR* = PWideChar - LPWSTR* = PWideChar - LPCWSTR* = PWideChar - PCWSTR* = PWideChar - # ANSI (Multi-byte Character) types - LPCH* = cstring - PCH* = cstring - LPCCH* = cstring - PCCH* = cstring - LPSTR* = cstring - PSTR* = cstring - LPCSTR* = cstring - PCSTR* = cstring - -type # BaseTsd.h -- Type definitions for the basic sized types - # Give here only the bare minimum, to be expanded as needs arise - LONG32* = int32 - ULONG32* = int32 - DWORD32* = int32 - LONG64* = int64 - ULONG64* = int64 - DWORD64* = int64 - PDWORD64* = ptr DWORD64 - # int32 on Win32, int64 on Win64 - INT_PTR* = ByteAddress - UINT_PTR* = ByteAddress - LONG_PTR* = ByteAddress - ULONG_PTR* = ByteAddress - SIZE_T* = ByteAddress - SSIZE_T* = ByteAddress - DWORD_PTR* = ByteAddress - # Thread affinity - KAFFINITY* = ByteAddress - PKAFFINITY* = ptr KAFFINITY - -type # WinDef.h -- Basic Windows Type Definitions - # BaseTypes - WINUINT* = int32 - ULONG* = int - PULONG* = ptr int - USHORT* = int16 - PUSHORT* = ptr int16 - UCHAR* = int8 - PUCHAR* = ptr int8 - PSZ* = cstring - - DWORD* = int32 - WINBOOL* = int32 - WORD* = int16 - #FLOAT* = float - PFLOAT* = ptr float32 - PWINBOOL* = ptr WINBOOL - LPWINBOOL* = ptr WINBOOL - PBYTE* = ptr int8 - LPBYTE* = ptr int8 - PINT* = ptr int32 - LPINT* = ptr int32 - PWORD* = ptr int16 - LPWORD* = ptr int16 - LPLONG* = ptr int32 - PDWORD* = ptr DWORD - LPDWORD* = ptr DWORD - LPVOID* = pointer - LPCVOID* = pointer - - # INT* = int # Cannot work and not necessary anyway - PUINT* = ptr int - - WPARAM* = LONG_PTR - LPARAM* = LONG_PTR - LRESULT* = LONG_PTR - - ATOM* = int16 - HANDLE* = int -# Handle* = HANDLE - PHANDLE* = ptr HANDLE - LPHANDLE* = ptr HANDLE - HWND* = HANDLE - HHOOK* = HANDLE - HEVENT* = HANDLE - HGLOBAL* = HANDLE - HLOCAL* = HANDLE - HGDIOBJ* = HANDLE - HKEY* = HANDLE - PHKEY* = ptr HKEY - HACCEL* = HANDLE - HBITMAP* = HANDLE - HBRUSH* = HANDLE - HCOLORSPACE* = HANDLE - HDC* = HANDLE - HGLRC* = HANDLE - HDESK* = HANDLE - HENHMETAFILE* = HANDLE - HFONT* = HANDLE - HICON* = HANDLE - HMETAFILE* = HANDLE - HINST* = HANDLE # Not HINSTANCE, else it has problems with the var HInstance - HMODULE* = HANDLE - HPALETTE* = HANDLE - HPEN* = HANDLE - HRGN* = HANDLE - HRSRC* = HANDLE - HTASK* = HANDLE - HWINSTA* = HANDLE - HKL* = HANDLE - HMONITOR* = HANDLE - HWINEVENTHOOK* = HANDLE - HUMPD* = HANDLE - - HFILE* = HANDLE - HCURSOR* = HANDLE # = HICON - COLORREF* = DWORD - LPCOLORREF* = ptr COLORREF - - POINT* {.final, pure.} = object - x*: LONG - y*: LONG - PPOINT* = ptr POINT - LPPOINT* = ptr POINT - POINTL* {.final, pure.} = object - x*: LONG - y*: LONG - PPOINTL* = ptr POINTL - - RECT* {.final, pure.} = object - TopLeft*, BottomRight*: Point - PRECT* = ptr RECT - LPRECT* = ptr RECT - - RECTL* {.final, pure.} = object - left*: LONG - top*: LONG - right*: LONG - bottom*: LONG - PRECTL* = ptr RECTL - - SIZE* {.final, pure.} = object - cx*: LONG - cy*: LONG - PSIZE* = ptr SIZE - LPSIZE* = ptr SIZE - SIZEL* = SIZE - PSIZEL* = ptr SIZE - LPSIZEL* = ptr SIZE - - POINTS* {.final, pure.} = object - x*: SHORT - y*: SHORT - PPOINTS* = ptr POINTS - - FILETIME* {.final, pure.} = object - dwLowDateTime*: DWORD - dwHighDateTime*: DWORD - PFILETIME* = ptr FILETIME - LPFILETIME* = ptr FILETIME -{.deprecated: [THandle: Handle, TAtom: ATOM, TFILETIME: FILETIME, TRECT: RECT, - TRECTL: RECTL, TSIZE: SIZE, TSIZEL: SIZE, TPOINTS: POINTS, - TPOINT: POINT, TPOINTL: POINTL].} - -const - MAX_PATH* = 260 - HFILE_ERROR* = HFILE(-1) - - # mode selections for the device mode function - # DocumentProperties - DM_UPDATE* = 1 - DM_COPY* = 2 - DM_PROMPT* = 4 - DM_MODIFY* = 8 - - DM_IN_BUFFER* = DM_MODIFY - DM_IN_PROMPT* = DM_PROMPT - DM_OUT_BUFFER* = DM_COPY - DM_OUT_DEFAULT* = DM_UPDATE - - # device capabilities indices - DC_FIELDS* = 1 - DC_PAPERS* = 2 - DC_PAPERSIZE* = 3 - DC_MINEXTENT* = 4 - DC_MAXEXTENT* = 5 - DC_BINS* = 6 - DC_DUPLEX* = 7 - DC_SIZE* = 8 - DC_EXTRA* = 9 - DC_VERSION* = 10 - DC_DRIVER* = 11 - DC_BINNAMES* = 12 - DC_ENUMRESOLUTIONS* = 13 - DC_FILEDEPENDENCIES* = 14 - DC_TRUETYPE* = 15 - DC_PAPERNAMES* = 16 - DC_ORIENTATION* = 17 - DC_COPIES* = 18 - - DC_BINADJUST* = 19 - DC_EMF_COMPLIANT* = 20 - DC_DATATYPE_PRODUCED* = 21 - -type - WORDBOOL* = int16 # XXX: not a bool - CALTYPE* = int - CALID* = int - CCHAR* = char - WINT* = int32 - PINTEGER* = ptr int32 - PBOOL* = ptr WINBOOL - LONGLONG* = int64 - PLONGLONG* = ptr LONGLONG - LPLONGLONG* = ptr LONGLONG - ULONGLONG* = int64 # used in AMD64 CONTEXT - PULONGLONG* = ptr ULONGLONG # - DWORDLONG* = int64 # was unsigned long - PDWORDLONG* = ptr DWORDLONG - HRESULT* = int - PHRESULT* = ptr HRESULT - HCONV* = HANDLE - HCONVLIST* = HANDLE - HDBC* = HANDLE - HDDEDATA* = HANDLE - HDROP* = HANDLE - HDWP* = HANDLE - HENV* = HANDLE - HIMAGELIST* = HANDLE - HMENU* = HANDLE - HRASCONN* = HANDLE - HSTMT* = HANDLE - HSTR* = HANDLE - HSZ* = HANDLE - LANGID* = int16 - LCID* = DWORD - LCTYPE* = DWORD - LP* = ptr int16 - LPBOOL* = ptr WINBOOL -{.deprecated: [TCOLORREF: COLORREF].} - -when defined(winUnicode): - type - LPCTSTR* = PWideChar -else: - type - LPCTSTR* = cstring -type - LPPCSTR* = ptr LPCSTR - LPPCTSTR* = ptr LPCTSTR - LPPCWSTR* = ptr LPCWSTR - -when defined(winUnicode): - type - LPTCH* = PWideChar - LPTSTR* = PWideChar -else: - type - LPTCH* = cstring - LPTSTR* = cstring -type - PBOOLEAN* = ptr int8 - PLONG* = ptr int32 - PSHORT* = ptr SHORT - -when defined(winUnicode): - type - PTBYTE* = ptr uint16 - PTCH* = PWideChar - PTCHAR* = PWideChar - PTSTR* = PWideChar -else: - type - PTBYTE* = ptr byte - PTCH* = cstring - PTCHAR* = cstring - PTSTR* = cstring -type - PVOID* = pointer - RETCODE* = SHORT - SC_HANDLE* = HANDLE - SC_LOCK* = LPVOID - LPSC_HANDLE* = ptr SC_HANDLE - SERVICE_STATUS_HANDLE* = DWORD - -when defined(winUnicode): - type - BYTE* = uint16 - CHAR* = widechar - BCHAR* = int16 - {.deprecated: [TBYTE: BYTE, TCHAR: CHAR].} -else: - type - BYTE* = uint8 - CHAR* = char - BCHAR* = int8 - {.deprecated: [TBYTE: BYTE, TCHAR: CHAR].} -type - WCHAR* = WideChar - PLPSTR* = ptr LPSTR - PLPWStr* = ptr LPWStr - ACL_INFORMATION_CLASS* = enum - AclRevisionInformation = 1, AclSizeInformation - MEDIA_TYPE* = enum - Unknown, F5_1Pt2_512, F3_1Pt44_512, F3_2Pt88_512, F3_20Pt8_512, F3_720_512, - F5_360_512, F5_320_512, F5_320_1024, F5_180_512, F5_160_512, RemovableMedia, - FixedMedia - -const - RASCS_DONE* = 0x00002000 - RASCS_PAUSED* = 0x00001000 - -type - RASCONNSTATE* = enum - RASCS_OpenPort = 0, RASCS_PortOpened, RASCS_ConnectDevice, - RASCS_DeviceConnected, RASCS_AllDevicesConnected, RASCS_Authenticate, - RASCS_AuthNotify, RASCS_AuthRetry, RASCS_AuthCallback, - RASCS_AuthChangePassword, RASCS_AuthProject, RASCS_AuthLinkSpeed, - RASCS_AuthAck, RASCS_ReAuthenticate, RASCS_Authenticated, - RASCS_PrepareForCallback, RASCS_WaitForModemReset, RASCS_WaitForCallback, - RASCS_Projected, RASCS_StartAuthentication, RASCS_CallbackComplete, - RASCS_LogonNetwork, RASCS_Interactive = RASCS_PAUSED, - RASCS_RetryAuthentication, RASCS_CallbackSetByCaller, RASCS_PasswordExpired, - RASCS_Connected = RASCS_DONE, RASCS_Disconnected - RASPROJECTION* = enum - RASP_PppIp = 0x00008021, RASP_PppIpx = 0x0000802B, RASP_PppNbf = 0x0000803F, - RASP_Amb = 0x00010000 - SECURITY_IMPERSONATION_LEVEL* = enum - - - SecurityAnonymous, SecurityIdentification, SecurityImpersonation, - SecurityDelegation - SID_NAME_USE* = enum - SidTypeUser = 1, SidTypeGroup, SidTypeDomain, SidTypeAlias, - SidTypeWellKnownGroup, SidTypeDeletedAccount, SidTypeInvalid, SidTypeUnknown - PSID_NAME_USE* = ptr SID_NAME_USE - TOKEN_INFORMATION_CLASS* = enum - TokenUser = 1, TokenGroups, TokenPrivileges, TokenOwner, TokenPrimaryGroup, - TokenDefaultDacl, TokenSource, TokenType, TokenImpersonationLevel, - TokenStatistics - TTOKEN_TYPE* = enum # Name conflict if we drop the `T` - TokenPrimary = 1, TokenImpersonation - MakeIntResourceA* = cstring - MakeIntResourceW* = PWideChar - MakeIntResource* = MakeIntResourceA - -# -# Definitions for callback procedures -# -type - BFFCALLBACK* = proc (para1: HWND, para2: WINUINT, para3: LPARAM, para4: LPARAM): int32{. - stdcall.} - LPCCHOOKPROC* = proc (para1: HWND, para2: WINUINT, para3: WPARAM, para4: LPARAM): WINUINT{. - stdcall.} - LPCFHOOKPROC* = proc (para1: HWND, para2: WINUINT, para3: WPARAM, para4: LPARAM): WINUINT{. - stdcall.} - PTHREAD_START_ROUTINE* = pointer - LPTHREAD_START_ROUTINE* = PTHREAD_START_ROUTINE - EDITSTREAMCALLBACK* = proc (para1: DWORD, para2: LPBYTE, para3: LONG, - para4: LONG): DWORD{.stdcall.} - LPFRHOOKPROC* = proc (para1: HWND, para2: WINUINT, para3: WPARAM, para4: LPARAM): WINUINT{. - stdcall.} - LPOFNHOOKPROC* = proc (para1: HWND, para2: WINUINT, para3: WPARAM, para4: LPARAM): WINUINT{. - stdcall.} - LPPRINTHOOKPROC* = proc (para1: HWND, para2: WINUINT, para3: WPARAM, - para4: LPARAM): WINUINT{.stdcall.} - LPSETUPHOOKPROC* = proc (para1: HWND, para2: WINUINT, para3: WPARAM, - para4: LPARAM): WINUINT{.stdcall.} - DLGPROC* = proc (para1: HWND, para2: WINUINT, para3: WPARAM, para4: LPARAM): LRESULT{. - stdcall.} - PFNPROPSHEETCALLBACK* = proc (para1: HWND, para2: WINUINT, para3: LPARAM): int32{. - stdcall.} - LPSERVICE_MAIN_FUNCTION* = proc (para1: DWORD, para2: LPTSTR){.stdcall.} - PFNTVCOMPARE* = proc (para1: LPARAM, para2: LPARAM, para3: LPARAM): int32{. - stdcall.} - WNDPROC* = proc (para1: HWND, para2: WINUINT, para3: WPARAM, para4: LPARAM): LRESULT{. - stdcall.} - FARPROC* = pointer - Proc* = pointer - ENUMRESTYPEPROC* = proc (para1: HANDLE, para2: LPTSTR, para3: LONG): WINBOOL{. - stdcall.} - ENUMRESNAMEPROC* = proc (para1: HANDLE, para2: LPCTSTR, para3: LPTSTR, - para4: LONG): WINBOOL{.stdcall.} - ENUMRESLANGPROC* = proc (para1: HANDLE, para2: LPCTSTR, para3: LPCTSTR, - para4: int16, para5: LONG): WINBOOL{.stdcall.} - DESKTOPENUMPROC* = FARPROC - ENUMWINDOWSPROC* = proc (para1: HWND, para2: LPARAM): WINBOOL{.stdcall.} - ENUMWINDOWSTATIONPROC* = proc (para1: LPTSTR, para2: LPARAM): WINBOOL{.stdcall.} - SENDASYNCPROC* = proc (para1: HWND, para2: WINUINT, para3: DWORD, para4: LRESULT){. - stdcall.} - TIMERPROC* = proc (para1: HWND, para2: WINUINT, para3: WINUINT, para4: DWORD){. - stdcall.} - GRAYSTRINGPROC* = FARPROC - DRAWSTATEPROC* = proc (para1: HDC, para2: LPARAM, para3: WPARAM, para4: int32, - para5: int32): WINBOOL{.stdcall.} - PROPENUMPROCEX* = proc (para1: HWND, para2: LPCTSTR, para3: HANDLE, - para4: DWORD): WINBOOL{.stdcall.} - PROPENUMPROC* = proc (para1: HWND, para2: LPCTSTR, para3: HANDLE): WINBOOL{. - stdcall.} - HOOKPROC* = proc (para1: int32, para2: WPARAM, para3: LPARAM): LRESULT{. - stdcall.} - ENUMOBJECTSPROC* = proc (para1: LPVOID, para2: LPARAM){.stdcall.} - LINEDDAPROC* = proc (para1: int32, para2: int32, para3: LPARAM){.stdcall.} - ABORTPROC* = proc (para1: HDC, para2: int32): WINBOOL{.stdcall.} - LPPAGEPAINTHOOK* = proc (para1: HWND, para2: WINUINT, para3: WPARAM, - para4: LPARAM): WINUINT{.stdcall.} - LPPAGESETUPHOOK* = proc (para1: HWND, para2: WINUINT, para3: WPARAM, - para4: LPARAM): WINUINT{.stdcall.} - ICMENUMPROC* = proc (para1: LPTSTR, para2: LPARAM): int32{.stdcall.} - EDITWORDBREAKPROCEX* = proc (para1: cstring, para2: LONG, para3: int8, - para4: WINT): LONG{.stdcall.} - PFNLVCOMPARE* = proc (para1: LPARAM, para2: LPARAM, para3: LPARAM): int32{. - stdcall.} - LOCALE_ENUMPROC* = proc (para1: LPTSTR): WINBOOL{.stdcall.} - CODEPAGE_ENUMPROC* = proc (para1: LPTSTR): WINBOOL{.stdcall.} - DATEFMT_ENUMPROC* = proc (para1: LPTSTR): WINBOOL{.stdcall.} - TIMEFMT_ENUMPROC* = proc (para1: LPTSTR): WINBOOL{.stdcall.} - CALINFO_ENUMPROC* = proc (para1: LPTSTR): WINBOOL{.stdcall.} - PHANDLER_ROUTINE* = proc (para1: DWORD): WINBOOL{.stdcall.} - LPHANDLER_FUNCTION* = proc (para1: DWORD): WINBOOL{.stdcall.} - PFNGETPROFILEPATH* = proc (para1: LPCTSTR, para2: LPSTR, para3: WINUINT): WINUINT{. - stdcall.} - PFNRECONCILEPROFILE* = proc (para1: LPCTSTR, para2: LPCTSTR, para3: DWORD): WINUINT{. - stdcall.} - PFNPROCESSPOLICIES* = proc (para1: HWND, para2: LPCTSTR, para3: LPCTSTR, - para4: LPCTSTR, para5: DWORD): WINBOOL{.stdcall.} -{.deprecated: [TFarProc: FARPROC, TProc: Proc, TABORTPROC: ABORTPROC].} - -const - SE_CREATE_TOKEN_NAME* = "SeCreateTokenPrivilege" - SE_ASSIGNPRIMARYTOKEN_NAME* = "SeAssignPrimaryTokenPrivilege" - SE_LOCK_MEMORY_NAME* = "SeLockMemoryPrivilege" - SE_INCREASE_QUOTA_NAME* = "SeIncreaseQuotaPrivilege" - SE_UNSOLICITED_INPUT_NAME* = "SeUnsolicitedInputPrivilege" - SE_MACHINE_ACCOUNT_NAME* = "SeMachineAccountPrivilege" - SE_TCB_NAME* = "SeTcbPrivilege" - SE_SECURITY_NAME* = "SeSecurityPrivilege" - SE_TAKE_OWNERSHIP_NAME* = "SeTakeOwnershipPrivilege" - SE_LOAD_DRIVER_NAME* = "SeLoadDriverPrivilege" - SE_SYSTEM_PROFILE_NAME* = "SeSystemProfilePrivilege" - SE_SYSTEMTIME_NAME* = "SeSystemtimePrivilege" - SE_PROF_SINGLE_PROCESS_NAME* = "SeProfileSingleProcessPrivilege" - SE_INC_BASE_PRIORITY_NAME* = "SeIncreaseBasePriorityPrivilege" - SE_CREATE_PAGEFILE_NAME* = "SeCreatePagefilePrivilege" - SE_CREATE_PERMANENT_NAME* = "SeCreatePermanentPrivilege" - SE_BACKUP_NAME* = "SeBackupPrivilege" - SE_RESTORE_NAME* = "SeRestorePrivilege" - SE_SHUTDOWN_NAME* = "SeShutdownPrivilege" - SE_DEBUG_NAME* = "SeDebugPrivilege" - SE_AUDIT_NAME* = "SeAuditPrivilege" - SE_SYSTEM_ENVIRONMENT_NAME* = "SeSystemEnvironmentPrivilege" - SE_CHANGE_NOTIFY_NAME* = "SeChangeNotifyPrivilege" - SE_REMOTE_SHUTDOWN_NAME* = "SeRemoteShutdownPrivilege" - SERVICES_ACTIVE_DATABASEW* = "ServicesActive" - SERVICES_FAILED_DATABASEW* = "ServicesFailed" - SERVICES_ACTIVE_DATABASEA* = "ServicesActive" - SERVICES_FAILED_DATABASEA* = "ServicesFailed" - SC_GROUP_IDENTIFIERW* = "+" - SC_GROUP_IDENTIFIERA* = "+" - -when defined(winUnicode): - const - SERVICES_ACTIVE_DATABASE* = SERVICES_ACTIVE_DATABASEW - SERVICES_FAILED_DATABASE* = SERVICES_FAILED_DATABASEW - SC_GROUP_IDENTIFIER* = SC_GROUP_IDENTIFIERW -else: - const - SERVICES_ACTIVE_DATABASE* = SERVICES_ACTIVE_DATABASEA - SERVICES_FAILED_DATABASE* = SERVICES_FAILED_DATABASEA - SC_GROUP_IDENTIFIER* = SC_GROUP_IDENTIFIERA -type - PFNCALLBACK* = proc (para1, para2: WINUINT, para3: HCONV, para4, para5: HSZ, - para6: HDDEDATA, para7, para8: DWORD): HDDEData{.stdcall.} - CALLB* = PFNCALLBACK - SECURITY_CONTEXT_TRACKING_MODE* = WINBOOL - # End of stuff from ddeml.h in old Cygnus headers - - WNDENUMPROC* = FARPROC - ENHMFENUMPROC* = FARPROC - CCSTYLE* = DWORD - PCCSTYLE* = ptr CCSTYLE - LPCCSTYLE* = ptr CCSTYLE - CCSTYLEFLAGA* = DWORD - PCCSTYLEFLAGA* = ptr CCSTYLEFLAGA - LPCCSTYLEFLAGA* = ptr CCSTYLEFLAGA - -const - LZERROR_UNKNOWNALG* = -8 - LZERROR_BADVALUE* = -7 - LZERROR_GLOBLOCK* = -6 - LZERROR_GLOBALLOC* = -5 - LZERROR_WRITE* = -4 - LZERROR_READ* = -3 - LZERROR_BADOUTHANDLE* = -2 - LZERROR_BADINHANDLE* = -1 - NO_ERROR* = 0 - ERROR_SUCCESS* = 0 - ERROR_INVALID_FUNCTION* = 1 - ERROR_FILE_NOT_FOUND* = 2 - ERROR_PATH_NOT_FOUND* = 3 - ERROR_TOO_MANY_OPEN_FILES* = 4 - ERROR_ACCESS_DENIED* = 5 - ERROR_INVALID_HANDLE* = 6 - ERROR_ARENA_TRASHED* = 7 - ERROR_NOT_ENOUGH_MEMORY* = 8 - ERROR_INVALID_BLOCK* = 9 - ERROR_BAD_ENVIRONMENT* = 10 - ERROR_BAD_FORMAT* = 11 - ERROR_INVALID_ACCESS* = 12 - ERROR_INVALID_DATA* = 13 - ERROR_OUTOFMEMORY* = 14 - ERROR_INVALID_DRIVE* = 15 - ERROR_CURRENT_DIRECTORY* = 16 - ERROR_NOT_SAME_DEVICE* = 17 - ERROR_NO_MORE_FILES* = 18 - ERROR_WRITE_PROTECT* = 19 - ERROR_BAD_UNIT* = 20 - ERROR_NOT_READY* = 21 - ERROR_BAD_COMMAND* = 22 - ERROR_CRC* = 23 - ERROR_BAD_LENGTH* = 24 - ERROR_SEEK* = 25 - ERROR_NOT_DOS_DISK* = 26 - ERROR_SECTOR_NOT_FOUND* = 27 - ERROR_OUT_OF_PAPER* = 28 - ERROR_WRITE_FAULT* = 29 - ERROR_READ_FAULT* = 30 - ERROR_GEN_FAILURE* = 31 - ERROR_SHARING_VIOLATION* = 32 - ERROR_LOCK_VIOLATION* = 33 - ERROR_WRONG_DISK* = 34 - ERROR_SHARING_BUFFER_EXCEEDED* = 36 - ERROR_HANDLE_EOF* = 38 - ERROR_HANDLE_DISK_FULL* = 39 - ERROR_NOT_SUPPORTED* = 50 - ERROR_REM_NOT_LIST* = 51 - ERROR_DUP_NAME* = 52 - ERROR_BAD_NETPATH* = 53 - ERROR_NETWORK_BUSY* = 54 - ERROR_DEV_NOT_EXIST* = 55 - ERROR_TOO_MANY_CMDS* = 56 - ERROR_ADAP_HDW_ERR* = 57 - ERROR_BAD_NET_RESP* = 58 - ERROR_UNEXP_NET_ERR* = 59 - ERROR_BAD_REM_ADAP* = 60 - ERROR_PRINTQ_FULL* = 61 - ERROR_NO_SPOOL_SPACE* = 62 - ERROR_PRINT_CANCELLED* = 63 - ERROR_NETNAME_DELETED* = 64 - ERROR_NETWORK_ACCESS_DENIED* = 65 - ERROR_BAD_DEV_TYPE* = 66 - ERROR_BAD_NET_NAME* = 67 - ERROR_TOO_MANY_NAMES* = 68 - ERROR_TOO_MANY_SESS* = 69 - ERROR_SHARING_PAUSED* = 70 - ERROR_REQ_NOT_ACCEP* = 71 - ERROR_REDIR_PAUSED* = 72 - ERROR_FILE_EXISTS* = 80 - ERROR_CANNOT_MAKE* = 82 - ERROR_FAIL_I24* = 83 - ERROR_OUT_OF_STRUCTURES* = 84 - ERROR_ALREADY_ASSIGNED* = 85 - ERROR_INVALID_PASSWORD* = 86 - ERROR_INVALID_PARAMETER* = 87 - ERROR_NET_WRITE_FAULT* = 88 - ERROR_NO_PROC_SLOTS* = 89 - ERROR_TOO_MANY_SEMAPHORES* = 100 - ERROR_EXCL_SEM_ALREADY_OWNED* = 101 - ERROR_SEM_IS_SET* = 102 - ERROR_TOO_MANY_SEM_REQUESTS* = 103 - ERROR_INVALID_AT_INTERRUPT_TIME* = 104 - ERROR_SEM_OWNER_DIED* = 105 - ERROR_SEM_USER_LIMIT* = 106 - ERROR_DISK_CHANGE* = 107 - ERROR_DRIVE_LOCKED* = 108 - ERROR_BROKEN_PIPE* = 109 - ERROR_OPEN_FAILED* = 110 - ERROR_BUFFER_OVERFLOW* = 111 - ERROR_DISK_FULL* = 112 - ERROR_NO_MORE_SEARCH_HANDLES* = 113 - ERROR_INVALID_TARGET_HANDLE* = 114 - ERROR_INVALID_CATEGORY* = 117 - ERROR_INVALID_VERIFY_SWITCH* = 118 - ERROR_BAD_DRIVER_LEVEL* = 119 - ERROR_CALL_NOT_IMPLEMENTED* = 120 - ERROR_SEM_TIMEOUT* = 121 - ERROR_INSUFFICIENT_BUFFER* = 122 - ERROR_INVALID_NAME* = 123 - ERROR_INVALID_LEVEL* = 124 - ERROR_NO_VOLUME_LABEL* = 125 - ERROR_MOD_NOT_FOUND* = 126 - ERROR_PROC_NOT_FOUND* = 127 - ERROR_WAIT_NO_CHILDREN* = 128 - ERROR_CHILD_NOT_COMPLETE* = 129 - ERROR_DIRECT_ACCESS_HANDLE* = 130 - ERROR_NEGATIVE_SEEK* = 131 - ERROR_SEEK_ON_DEVICE* = 132 - ERROR_IS_JOIN_TARGET* = 133 - ERROR_IS_JOINED* = 134 - ERROR_IS_SUBSTED* = 135 - ERROR_NOT_JOINED* = 136 - ERROR_NOT_SUBSTED* = 137 - ERROR_JOIN_TO_JOIN* = 138 - ERROR_SUBST_TO_SUBST* = 139 - ERROR_JOIN_TO_SUBST* = 140 - ERROR_SUBST_TO_JOIN* = 141 - ERROR_BUSY_DRIVE* = 142 - ERROR_SAME_DRIVE* = 143 - ERROR_DIR_NOT_ROOT* = 144 - ERROR_DIR_NOT_EMPTY* = 145 - ERROR_IS_SUBST_PATH* = 146 - ERROR_IS_JOIN_PATH* = 147 - ERROR_PATH_BUSY* = 148 - ERROR_IS_SUBST_TARGET* = 149 - ERROR_SYSTEM_TRACE* = 150 - ERROR_INVALID_EVENT_COUNT* = 151 - ERROR_TOO_MANY_MUXWAITERS* = 152 - ERROR_INVALID_LIST_FORMAT* = 153 - ERROR_LABEL_TOO_LONG* = 154 - ERROR_TOO_MANY_TCBS* = 155 - ERROR_SIGNAL_REFUSED* = 156 - ERROR_DISCARDED* = 157 - ERROR_NOT_LOCKED* = 158 - ERROR_BAD_THREADID_ADDR* = 159 - ERROR_BAD_ARGUMENTS* = 160 - ERROR_BAD_PATHNAME* = 161 - ERROR_SIGNAL_PENDING* = 162 - ERROR_MAX_THRDS_REACHED* = 164 - ERROR_LOCK_FAILED* = 167 - ERROR_BUSY* = 170 - ERROR_CANCEL_VIOLATION* = 173 - ERROR_ATOMIC_LOCKS_NOT_SUPPORTED* = 174 - ERROR_INVALID_SEGMENT_NUMBER* = 180 - ERROR_INVALID_ORDINAL* = 182 - ERROR_ALREADY_EXISTS* = 183 - ERROR_INVALID_FLAG_NUMBER* = 186 - ERROR_SEM_NOT_FOUND* = 187 - ERROR_INVALID_STARTING_CODESEG* = 188 - ERROR_INVALID_STACKSEG* = 189 - ERROR_INVALID_MODULETYPE* = 190 - ERROR_INVALID_EXE_SIGNATURE* = 191 - ERROR_EXE_MARKED_INVALID* = 192 - ERROR_BAD_EXE_FORMAT* = 193 - ERROR_ITERATED_DATA_EXCEEDS_64k* = 194 - ERROR_INVALID_MINALLOCSIZE* = 195 - ERROR_DYNLINK_FROM_INVALID_RING* = 196 - ERROR_IOPL_NOT_ENABLED* = 197 - ERROR_INVALID_SEGDPL* = 198 - ERROR_AUTODATASEG_EXCEEDS_64k* = 199 - ERROR_RING2SEG_MUST_BE_MOVABLE* = 200 - ERROR_RELOC_CHAIN_XEEDS_SEGLIM* = 201 - ERROR_INFLOOP_IN_RELOC_CHAIN* = 202 - ERROR_ENVVAR_NOT_FOUND* = 203 - ERROR_NO_SIGNAL_SENT* = 205 - ERROR_FILENAME_EXCED_RANGE* = 206 - ERROR_RING2_STACK_IN_USE* = 207 - ERROR_META_EXPANSION_TOO_LONG* = 208 - ERROR_INVALID_SIGNAL_NUMBER* = 209 - ERROR_THREAD_1_INACTIVE* = 210 - ERROR_LOCKED* = 212 - ERROR_TOO_MANY_MODULES* = 214 - ERROR_NESTING_NOT_ALLOWED* = 215 - ERROR_BAD_PIPE* = 230 - ERROR_PIPE_BUSY* = 231 - ERROR_NO_DATA* = 232 - ERROR_PIPE_NOT_CONNECTED* = 233 - ERROR_MORE_DATA* = 234 - ERROR_VC_DISCONNECTED* = 240 - ERROR_INVALID_EA_NAME* = 254 - ERROR_EA_LIST_INCONSISTENT* = 255 - ERROR_NO_MORE_ITEMS* = 259 - ERROR_CANNOT_COPY* = 266 - ERROR_DIRECTORY* = 267 - ERROR_EAS_DIDNT_FIT* = 275 - ERROR_EA_FILE_CORRUPT* = 276 - ERROR_EA_TABLE_FULL* = 277 - ERROR_INVALID_EA_HANDLE* = 278 - ERROR_EAS_NOT_SUPPORTED* = 282 - ERROR_NOT_OWNER* = 288 - ERROR_TOO_MANY_POSTS* = 298 - ERROR_PARTIAL_COPY* = 299 - ERROR_MR_MID_NOT_FOUND* = 317 - ERROR_INVALID_ADDRESS* = 487 - ERROR_ARITHMETIC_OVERFLOW* = 534 - ERROR_PIPE_CONNECTED* = 535 - ERROR_PIPE_LISTENING* = 536 - ERROR_EA_ACCESS_DENIED* = 994 - ERROR_OPERATION_ABORTED* = 995 - ERROR_IO_INCOMPLETE* = 996 - ERROR_IO_PENDING* = 997 - ERROR_NOACCESS* = 998 - ERROR_SWAPERROR* = 999 - ERROR_STACK_OVERFLOW* = 1001 - ERROR_INVALID_MESSAGE* = 1002 - ERROR_CAN_NOT_COMPLETE* = 1003 - ERROR_INVALID_FLAGS* = 1004 - ERROR_UNRECOGNIZED_VOLUME* = 1005 - ERROR_FILE_INVALID* = 1006 - ERROR_FULLSCREEN_MODE* = 1007 - ERROR_NO_TOKEN* = 1008 - ERROR_BADDB* = 1009 - ERROR_BADKEY* = 1010 - ERROR_CANTOPEN* = 1011 - ERROR_CANTREAD* = 1012 - ERROR_CANTWRITE* = 1013 - ERROR_REGISTRY_RECOVERED* = 1014 - ERROR_REGISTRY_CORRUPT* = 1015 - ERROR_REGISTRY_IO_FAILED* = 1016 - ERROR_NOT_REGISTRY_FILE* = 1017 - ERROR_KEY_DELETED* = 1018 - ERROR_NO_LOG_SPACE* = 1019 - ERROR_KEY_HAS_CHILDREN* = 1020 - ERROR_CHILD_MUST_BE_VOLATILE* = 1021 - ERROR_NOTIFY_ENUM_DIR* = 1022 - ERROR_DEPENDENT_SERVICES_RUNNING* = 1051 - ERROR_INVALID_SERVICE_CONTROL* = 1052 - ERROR_SERVICE_REQUEST_TIMEOUT* = 1053 - ERROR_SERVICE_NO_THREAD* = 1054 - ERROR_SERVICE_DATABASE_LOCKED* = 1055 - ERROR_SERVICE_ALREADY_RUNNING* = 1056 - ERROR_INVALID_SERVICE_ACCOUNT* = 1057 - ERROR_SERVICE_DISABLED* = 1058 - ERROR_CIRCULAR_DEPENDENCY* = 1059 - ERROR_SERVICE_DOES_NOT_EXIST* = 1060 - ERROR_SERVICE_CANNOT_ACCEPT_CTRL* = 1061 - ERROR_SERVICE_NOT_ACTIVE* = 1062 - ERROR_FAILED_SERVICE_CONTROLLER_CONNECT* = 1063 - ERROR_EXCEPTION_IN_SERVICE* = 1064 - ERROR_DATABASE_DOES_NOT_EXIST* = 1065 - ERROR_SERVICE_SPECIFIC_ERROR* = 1066 - ERROR_PROCESS_ABORTED* = 1067 - ERROR_SERVICE_DEPENDENCY_FAIL* = 1068 - ERROR_SERVICE_LOGON_FAILED* = 1069 - ERROR_SERVICE_START_HANG* = 1070 - ERROR_INVALID_SERVICE_LOCK* = 1071 - ERROR_SERVICE_MARKED_FOR_DELETE* = 1072 - ERROR_SERVICE_EXISTS* = 1073 - ERROR_ALREADY_RUNNING_LKG* = 1074 - ERROR_SERVICE_DEPENDENCY_DELETED* = 1075 - ERROR_BOOT_ALREADY_ACCEPTED* = 1076 - ERROR_SERVICE_NEVER_STARTED* = 1077 - ERROR_DUPLICATE_SERVICE_NAME* = 1078 - ERROR_END_OF_MEDIA* = 1100 - ERROR_FILEMARK_DETECTED* = 1101 - ERROR_BEGINNING_OF_MEDIA* = 1102 - ERROR_SETMARK_DETECTED* = 1103 - ERROR_NO_DATA_DETECTED* = 1104 - ERROR_PARTITION_FAILURE* = 1105 - ERROR_INVALID_BLOCK_LENGTH* = 1106 - ERROR_DEVICE_NOT_PARTITIONED* = 1107 - ERROR_UNABLE_TO_LOCK_MEDIA* = 1108 - ERROR_UNABLE_TO_UNLOAD_MEDIA* = 1109 - ERROR_MEDIA_CHANGED* = 1110 - ERROR_BUS_RESET* = 1111 - ERROR_NO_MEDIA_IN_DRIVE* = 1112 - ERROR_NO_UNICODE_TRANSLATION* = 1113 - ERROR_DLL_INIT_FAILED* = 1114 - ERROR_SHUTDOWN_IN_PROGRESS* = 1115 - ERROR_NO_SHUTDOWN_IN_PROGRESS* = 1116 - ERROR_IO_DEVICE* = 1117 - ERROR_SERIAL_NO_DEVICE* = 1118 - ERROR_IRQ_BUSY* = 1119 - ERROR_MORE_WRITES* = 1120 - ERROR_COUNTER_TIMEOUT* = 1121 - ERROR_FLOPPY_ID_MARK_NOT_FOUND* = 1122 - ERROR_FLOPPY_WRONG_CYLINDER* = 1123 - ERROR_FLOPPY_UNKNOWN_ERROR* = 1124 - ERROR_FLOPPY_BAD_REGISTERS* = 1125 - ERROR_DISK_RECALIBRATE_FAILED* = 1126 - ERROR_DISK_OPERATION_FAILED* = 1127 - ERROR_DISK_RESET_FAILED* = 1128 - ERROR_EOM_OVERFLOW* = 1129 - ERROR_NOT_ENOUGH_SERVER_MEMORY* = 1130 - ERROR_POSSIBLE_DEADLOCK* = 1131 - ERROR_MAPPED_ALIGNMENT* = 1132 - ERROR_SET_POWER_STATE_VETOED* = 1140 - ERROR_SET_POWER_STATE_FAILED* = 1141 - ERROR_OLD_WIN_VERSION* = 1150 - ERROR_APP_WRONG_OS* = 1151 - ERROR_SINGLE_INSTANCE_APP* = 1152 - ERROR_RMODE_APP* = 1153 - ERROR_INVALID_DLL* = 1154 - ERROR_NO_ASSOCIATION* = 1155 - ERROR_DDE_FAIL* = 1156 - ERROR_DLL_NOT_FOUND* = 1157 - ERROR_BAD_USERNAME* = 2202 - ERROR_NOT_CONNECTED* = 2250 - ERROR_OPEN_FILES* = 2401 - ERROR_ACTIVE_CONNECTIONS* = 2402 - ERROR_DEVICE_IN_USE* = 2404 - ERROR_BAD_DEVICE* = 1200 - ERROR_CONNECTION_UNAVAIL* = 1201 - ERROR_DEVICE_ALREADY_REMEMBERED* = 1202 - ERROR_NO_NET_OR_BAD_PATH* = 1203 - ERROR_BAD_PROVIDER* = 1204 - ERROR_CANNOT_OPEN_PROFILE* = 1205 - ERROR_BAD_PROFILE* = 1206 - ERROR_NOT_CONTAINER* = 1207 - ERROR_EXTENDED_ERROR* = 1208 - ERROR_INVALID_GROUPNAME* = 1209 - ERROR_INVALID_COMPUTERNAME* = 1210 - ERROR_INVALID_EVENTNAME* = 1211 - ERROR_INVALID_DOMAINNAME* = 1212 - ERROR_INVALID_SERVICENAME* = 1213 - ERROR_INVALID_NETNAME* = 1214 - ERROR_INVALID_SHARENAME* = 1215 - ERROR_INVALID_PASSWORDNAME* = 1216 - ERROR_INVALID_MESSAGENAME* = 1217 - ERROR_INVALID_MESSAGEDEST* = 1218 - ERROR_SESSION_CREDENTIAL_CONFLICT* = 1219 - ERROR_REMOTE_SESSION_LIMIT_EXCEEDED* = 1220 - ERROR_DUP_DOMAINNAME* = 1221 - ERROR_NO_NETWORK* = 1222 - ERROR_CANCELLED* = 1223 - ERROR_USER_MAPPED_FILE* = 1224 - ERROR_CONNECTION_REFUSED* = 1225 - ERROR_GRACEFUL_DISCONNECT* = 1226 - ERROR_ADDRESS_ALREADY_ASSOCIATED* = 1227 - ERROR_ADDRESS_NOT_ASSOCIATED* = 1228 - ERROR_CONNECTION_INVALID* = 1229 - ERROR_CONNECTION_ACTIVE* = 1230 - ERROR_NETWORK_UNREACHABLE* = 1231 - ERROR_HOST_UNREACHABLE* = 1232 - ERROR_PROTOCOL_UNREACHABLE* = 1233 - ERROR_PORT_UNREACHABLE* = 1234 - ERROR_REQUEST_ABORTED* = 1235 - ERROR_CONNECTION_ABORTED* = 1236 - ERROR_RETRY* = 1237 - ERROR_CONNECTION_COUNT_LIMIT* = 1238 - ERROR_LOGIN_TIME_RESTRICTION* = 1239 - ERROR_LOGIN_WKSTA_RESTRICTION* = 1240 - ERROR_INCORRECT_ADDRESS* = 1241 - ERROR_ALREADY_REGISTERED* = 1242 - ERROR_SERVICE_NOT_FOUND* = 1243 - ERROR_NOT_AUTHENTICATED* = 1244 - ERROR_NOT_LOGGED_ON* = 1245 - ERROR_CONTINUE* = 1246 - ERROR_ALREADY_INITIALIZED* = 1247 - ERROR_NO_MORE_DEVICES* = 1248 - ERROR_NOT_ALL_ASSIGNED* = 1300 - ERROR_SOME_NOT_MAPPED* = 1301 - ERROR_NO_QUOTAS_FOR_ACCOUNT* = 1302 - ERROR_LOCAL_USER_SESSION_KEY* = 1303 - ERROR_NULL_LM_PASSWORD* = 1304 - ERROR_UNKNOWN_REVISION* = 1305 - ERROR_REVISION_MISMATCH* = 1306 - ERROR_INVALID_OWNER* = 1307 - ERROR_INVALID_PRIMARY_GROUP* = 1308 - ERROR_NO_IMPERSONATION_TOKEN* = 1309 - ERROR_CANT_DISABLE_MANDATORY* = 1310 - ERROR_NO_LOGON_SERVERS* = 1311 - ERROR_NO_SUCH_LOGON_SESSION* = 1312 - ERROR_NO_SUCH_PRIVILEGE* = 1313 - ERROR_PRIVILEGE_NOT_HELD* = 1314 - ERROR_INVALID_ACCOUNT_NAME* = 1315 - ERROR_USER_EXISTS* = 1316 - ERROR_NO_SUCH_USER* = 1317 - ERROR_GROUP_EXISTS* = 1318 - ERROR_NO_SUCH_GROUP* = 1319 - ERROR_MEMBER_IN_GROUP* = 1320 - ERROR_MEMBER_NOT_IN_GROUP* = 1321 - ERROR_LAST_ADMIN* = 1322 - ERROR_WRONG_PASSWORD* = 1323 - ERROR_ILL_FORMED_PASSWORD* = 1324 - ERROR_PASSWORD_RESTRICTION* = 1325 - ERROR_LOGON_FAILURE* = 1326 - ERROR_ACCOUNT_RESTRICTION* = 1327 - ERROR_INVALID_LOGON_HOURS* = 1328 - ERROR_INVALID_WORKSTATION* = 1329 - ERROR_PASSWORD_EXPIRED* = 1330 - ERROR_ACCOUNT_DISABLED* = 1331 - ERROR_NONE_MAPPED* = 1332 - ERROR_TOO_MANY_LUIDS_REQUESTED* = 1333 - ERROR_LUIDS_EXHAUSTED* = 1334 - ERROR_INVALID_SUB_AUTHORITY* = 1335 - ERROR_INVALID_ACL* = 1336 - ERROR_INVALID_SID* = 1337 - ERROR_INVALID_SECURITY_DESCR* = 1338 - ERROR_BAD_INHERITANCE_ACL* = 1340 - ERROR_SERVER_DISABLED* = 1341 - ERROR_SERVER_NOT_DISABLED* = 1342 - ERROR_INVALID_ID_AUTHORITY* = 1343 - ERROR_ALLOTTED_SPACE_EXCEEDED* = 1344 - ERROR_INVALID_GROUP_ATTRIBUTES* = 1345 - ERROR_BAD_IMPERSONATION_LEVEL* = 1346 - ERROR_CANT_OPEN_ANONYMOUS* = 1347 - ERROR_BAD_VALIDATION_CLASS* = 1348 - ERROR_BAD_TOKEN_TYPE* = 1349 - ERROR_NO_SECURITY_ON_OBJECT* = 1350 - ERROR_CANT_ACCESS_DOMAIN_INFO* = 1351 - ERROR_INVALID_SERVER_STATE* = 1352 - ERROR_INVALID_DOMAIN_STATE* = 1353 - ERROR_INVALID_DOMAIN_ROLE* = 1354 - ERROR_NO_SUCH_DOMAIN* = 1355 - ERROR_DOMAIN_EXISTS* = 1356 - ERROR_DOMAIN_LIMIT_EXCEEDED* = 1357 - ERROR_INTERNAL_DB_CORRUPTION* = 1358 - ERROR_INTERNAL_ERROR* = 1359 - ERROR_GENERIC_NOT_MAPPED* = 1360 - ERROR_BAD_DESCRIPTOR_FORMAT* = 1361 - ERROR_NOT_LOGON_PROCESS* = 1362 - ERROR_LOGON_SESSION_EXISTS* = 1363 - ERROR_NO_SUCH_PACKAGE* = 1364 - ERROR_BAD_LOGON_SESSION_STATE* = 1365 - ERROR_LOGON_SESSION_COLLISION* = 1366 - ERROR_INVALID_LOGON_TYPE* = 1367 - ERROR_CANNOT_IMPERSONATE* = 1368 - ERROR_RXACT_INVALID_STATE* = 1369 - ERROR_RXACT_COMMIT_FAILURE* = 1370 - ERROR_SPECIAL_ACCOUNT* = 1371 - ERROR_SPECIAL_GROUP* = 1372 - ERROR_SPECIAL_USER* = 1373 - ERROR_MEMBERS_PRIMARY_GROUP* = 1374 - ERROR_TOKEN_ALREADY_IN_USE* = 1375 - ERROR_NO_SUCH_ALIAS* = 1376 - ERROR_MEMBER_NOT_IN_ALIAS* = 1377 - ERROR_MEMBER_IN_ALIAS* = 1378 - ERROR_ALIAS_EXISTS* = 1379 - ERROR_LOGON_NOT_GRANTED* = 1380 - ERROR_TOO_MANY_SECRETS* = 1381 - ERROR_SECRET_TOO_LONG* = 1382 - ERROR_INTERNAL_DB_ERROR* = 1383 - ERROR_TOO_MANY_CONTEXT_IDS* = 1384 - ERROR_LOGON_TYPE_NOT_GRANTED* = 1385 - ERROR_NT_CROSS_ENCRYPTION_REQUIRED* = 1386 - ERROR_NO_SUCH_MEMBER* = 1387 - ERROR_INVALID_MEMBER* = 1388 - ERROR_TOO_MANY_SIDS* = 1389 - ERROR_LM_CROSS_ENCRYPTION_REQUIRED* = 1390 - ERROR_NO_INHERITANCE* = 1391 - ERROR_FILE_CORRUPT* = 1392 - ERROR_DISK_CORRUPT* = 1393 - ERROR_NO_USER_SESSION_KEY* = 1394 - ERROR_LICENSE_QUOTA_EXCEEDED* = 1395 - ERROR_INVALID_WINDOW_HANDLE* = 1400 - ERROR_INVALID_MENU_HANDLE* = 1401 - ERROR_INVALID_CURSOR_HANDLE* = 1402 - ERROR_INVALID_ACCEL_HANDLE* = 1403 - ERROR_INVALID_HOOK_HANDLE* = 1404 - ERROR_INVALID_DWP_HANDLE* = 1405 - ERROR_TLW_WITH_WSCHILD* = 1406 - ERROR_CANNOT_FIND_WND_CLASS* = 1407 - ERROR_WINDOW_OF_OTHER_THREAD* = 1408 - ERROR_HOTKEY_ALREADY_REGISTERED* = 1409 - ERROR_CLASS_ALREADY_EXISTS* = 1410 - ERROR_CLASS_DOES_NOT_EXIST* = 1411 - ERROR_CLASS_HAS_WINDOWS* = 1412 - ERROR_INVALID_INDEX* = 1413 - ERROR_INVALID_ICON_HANDLE* = 1414 - ERROR_PRIVATE_DIALOG_INDEX* = 1415 - ERROR_LISTBOX_ID_NOT_FOUND* = 1416 - ERROR_NO_WILDCARD_CHARACTERS* = 1417 - ERROR_CLIPBOARD_NOT_OPEN* = 1418 - ERROR_HOTKEY_NOT_REGISTERED* = 1419 - ERROR_WINDOW_NOT_DIALOG* = 1420 - ERROR_CONTROL_ID_NOT_FOUND* = 1421 - ERROR_INVALID_COMBOBOX_MESSAGE* = 1422 - ERROR_WINDOW_NOT_COMBOBOX* = 1423 - ERROR_INVALID_EDIT_HEIGHT* = 1424 - ERROR_DC_NOT_FOUND* = 1425 - ERROR_INVALID_HOOK_FILTER* = 1426 - ERROR_INVALID_FILTER_PROC* = 1427 - ERROR_HOOK_NEEDS_HMOD* = 1428 - ERROR_GLOBAL_ONLY_HOOK* = 1429 - ERROR_JOURNAL_HOOK_SET* = 1430 - ERROR_HOOK_NOT_INSTALLED* = 1431 - ERROR_INVALID_LB_MESSAGE* = 1432 - ERROR_SETCOUNT_ON_BAD_LB* = 1433 - ERROR_LB_WITHOUT_TABSTOPS* = 1434 - ERROR_DESTROY_OBJECT_OF_OTHER_THREAD* = 1435 - ERROR_CHILD_WINDOW_MENU* = 1436 - ERROR_NO_SYSTEM_MENU* = 1437 - ERROR_INVALID_MSGBOX_STYLE* = 1438 - ERROR_INVALID_SPI_VALUE* = 1439 - ERROR_SCREEN_ALREADY_LOCKED* = 1440 - ERROR_HWNDS_HAVE_DIFF_PARENT* = 1441 - ERROR_NOT_CHILD_WINDOW* = 1442 - ERROR_INVALID_GW_COMMAND* = 1443 - ERROR_INVALID_THREAD_ID* = 1444 - ERROR_NON_MDICHILD_WINDOW* = 1445 - ERROR_POPUP_ALREADY_ACTIVE* = 1446 - ERROR_NO_SCROLLBARS* = 1447 - ERROR_INVALID_SCROLLBAR_RANGE* = 1448 - ERROR_INVALID_SHOWWIN_COMMAND* = 1449 - ERROR_NO_SYSTEM_RESOURCES* = 1450 - ERROR_NONPAGED_SYSTEM_RESOURCES* = 1451 - ERROR_PAGED_SYSTEM_RESOURCES* = 1452 - ERROR_WORKING_SET_QUOTA* = 1453 - ERROR_PAGEFILE_QUOTA* = 1454 - ERROR_COMMITMENT_LIMIT* = 1455 - ERROR_MENU_ITEM_NOT_FOUND* = 1456 - ERROR_INVALID_KEYBOARD_HANDLE* = 1457 - ERROR_HOOK_TYPE_NOT_ALLOWED* = 1458 - ERROR_REQUIRES_INTERACTIVE_WINDOWSTATION* = 1459 - ERROR_TIMEOUT* = 1460 - ERROR_EVENTLOG_FILE_CORRUPT* = 1500 - ERROR_EVENTLOG_CANT_START* = 1501 - ERROR_LOG_FILE_FULL* = 1502 - ERROR_EVENTLOG_FILE_CHANGED* = 1503 - RPC_S_INVALID_STRING_BINDING* = 1700 - RPC_S_WRONG_KIND_OF_BINDING* = 1701 - RPC_S_INVALID_BINDING* = 1702 - RPC_S_PROTSEQ_NOT_SUPPORTED* = 1703 - RPC_S_INVALID_RPC_PROTSEQ* = 1704 - RPC_S_INVALID_STRING_UUID* = 1705 - RPC_S_INVALID_ENDPOINT_FORMAT* = 1706 - RPC_S_INVALID_NET_ADDR* = 1707 - RPC_S_NO_ENDPOINT_FOUND* = 1708 - RPC_S_INVALID_TIMEOUT* = 1709 - RPC_S_OBJECT_NOT_FOUND* = 1710 - RPC_S_ALREADY_REGISTERED* = 1711 - RPC_S_TYPE_ALREADY_REGISTERED* = 1712 - RPC_S_ALREADY_LISTENING* = 1713 - RPC_S_NO_PROTSEQS_REGISTERED* = 1714 - RPC_S_NOT_LISTENING* = 1715 - RPC_S_UNKNOWN_MGR_TYPE* = 1716 - RPC_S_UNKNOWN_IF* = 1717 - RPC_S_NO_BINDINGS* = 1718 - RPC_S_NO_PROTSEQS* = 1719 - RPC_S_CANT_CREATE_ENDPOINT* = 1720 - RPC_S_OUT_OF_RESOURCES* = 1721 - RPC_S_SERVER_UNAVAILABLE* = 1722 - RPC_S_SERVER_TOO_BUSY* = 1723 - RPC_S_INVALID_NETWORK_OPTIONS* = 1724 - RPC_S_NO_CALL_ACTIVE* = 1725 - RPC_S_CALL_FAILED* = 1726 - RPC_S_CALL_FAILED_DNE* = 1727 - RPC_S_PROTOCOL_ERROR* = 1728 - RPC_S_UNSUPPORTED_TRANS_SYN* = 1730 - RPC_S_UNSUPPORTED_TYPE* = 1732 - RPC_S_INVALID_TAG* = 1733 - RPC_S_INVALID_BOUND* = 1734 - RPC_S_NO_ENTRY_NAME* = 1735 - RPC_S_INVALID_NAME_SYNTAX* = 1736 - RPC_S_UNSUPPORTED_NAME_SYNTAX* = 1737 - RPC_S_UUID_NO_ADDRESS* = 1739 - RPC_S_DUPLICATE_ENDPOINT* = 1740 - RPC_S_UNKNOWN_AUTHN_TYPE* = 1741 - RPC_S_MAX_CALLS_TOO_SMALL* = 1742 - RPC_S_STRING_TOO_LONG* = 1743 - RPC_S_PROTSEQ_NOT_FOUND* = 1744 - RPC_S_PROCNUM_OUT_OF_RANGE* = 1745 - RPC_S_BINDING_HAS_NO_AUTH* = 1746 - RPC_S_UNKNOWN_AUTHN_SERVICE* = 1747 - RPC_S_UNKNOWN_AUTHN_LEVEL* = 1748 - RPC_S_INVALID_AUTH_IDENTITY* = 1749 - RPC_S_UNKNOWN_AUTHZ_SERVICE* = 1750 - EPT_S_INVALID_ENTRY* = 1751 - EPT_S_CANT_PERFORM_OP* = 1752 - EPT_S_NOT_REGISTERED* = 1753 - RPC_S_NOTHING_TO_EXPORT* = 1754 - RPC_S_INCOMPLETE_NAME* = 1755 - RPC_S_INVALID_VERS_OPTION* = 1756 - RPC_S_NO_MORE_MEMBERS* = 1757 - RPC_S_NOT_ALL_OBJS_UNEXPORTED* = 1758 - RPC_S_INTERFACE_NOT_FOUND* = 1759 - RPC_S_ENTRY_ALREADY_EXISTS* = 1760 - RPC_S_ENTRY_NOT_FOUND* = 1761 - RPC_S_NAME_SERVICE_UNAVAILABLE* = 1762 - RPC_S_INVALID_NAF_ID* = 1763 - RPC_S_CANNOT_SUPPORT* = 1764 - RPC_S_NO_CONTEXT_AVAILABLE* = 1765 - RPC_S_INTERNAL_ERROR* = 1766 - RPC_S_ZERO_DIVIDE* = 1767 - RPC_S_ADDRESS_ERROR* = 1768 - RPC_S_FP_DIV_ZERO* = 1769 - RPC_S_FP_UNDERFLOW* = 1770 - RPC_S_FP_OVERFLOW* = 1771 - RPC_X_NO_MORE_ENTRIES* = 1772 - RPC_X_SS_CHAR_TRANS_OPEN_FAIL* = 1773 - RPC_X_SS_CHAR_TRANS_SHORT_FILE* = 1774 - RPC_X_SS_IN_NULL_CONTEXT* = 1775 - RPC_X_SS_CONTEXT_DAMAGED* = 1777 - RPC_X_SS_HANDLES_MISMATCH* = 1778 - RPC_X_SS_CANNOT_GET_CALL_HANDLE* = 1779 - RPC_X_NULL_REF_POINTER* = 1780 - RPC_X_ENUM_VALUE_OUT_OF_RANGE* = 1781 - RPC_X_BYTE_COUNT_TOO_SMALL* = 1782 - RPC_X_BAD_STUB_DATA* = 1783 - ERROR_INVALID_USER_BUFFER* = 1784 - ERROR_UNRECOGNIZED_MEDIA* = 1785 - ERROR_NO_TRUST_LSA_SECRET* = 1786 - ERROR_NO_TRUST_SAM_ACCOUNT* = 1787 - ERROR_TRUSTED_DOMAIN_FAILURE* = 1788 - ERROR_TRUSTED_RELATIONSHIP_FAILURE* = 1789 - ERROR_TRUST_FAILURE* = 1790 - RPC_S_CALL_IN_PROGRESS* = 1791 - ERROR_NETLOGON_NOT_STARTED* = 1792 - ERROR_ACCOUNT_EXPIRED* = 1793 - ERROR_REDIRECTOR_HAS_OPEN_HANDLES* = 1794 - ERROR_PRINTER_DRIVER_ALREADY_INSTALLED* = 1795 - ERROR_UNKNOWN_PORT* = 1796 - ERROR_UNKNOWN_PRINTER_DRIVER* = 1797 - ERROR_UNKNOWN_PRINTPROCESSOR* = 1798 - ERROR_INVALID_SEPARATOR_FILE* = 1799 - ERROR_INVALID_PRIORITY* = 1800 - ERROR_INVALID_PRINTER_NAME* = 1801 - ERROR_PRINTER_ALREADY_EXISTS* = 1802 - ERROR_INVALID_PRINTER_COMMAND* = 1803 - ERROR_INVALID_DATATYPE* = 1804 - ERROR_INVALID_ENVIRONMENT* = 1805 - RPC_S_NO_MORE_BINDINGS* = 1806 - ERROR_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT* = 1807 - ERROR_NOLOGON_WORKSTATION_TRUST_ACCOUNT* = 1808 - ERROR_NOLOGON_SERVER_TRUST_ACCOUNT* = 1809 - ERROR_DOMAIN_TRUST_INCONSISTENT* = 1810 - ERROR_SERVER_HAS_OPEN_HANDLES* = 1811 - ERROR_RESOURCE_DATA_NOT_FOUND* = 1812 - ERROR_RESOURCE_TYPE_NOT_FOUND* = 1813 - ERROR_RESOURCE_NAME_NOT_FOUND* = 1814 - ERROR_RESOURCE_LANG_NOT_FOUND* = 1815 - ERROR_NOT_ENOUGH_QUOTA* = 1816 - RPC_S_NO_INTERFACES* = 1817 - RPC_S_CALL_CANCELLED* = 1818 - RPC_S_BINDING_INCOMPLETE* = 1819 - RPC_S_COMM_FAILURE* = 1820 - RPC_S_UNSUPPORTED_AUTHN_LEVEL* = 1821 - RPC_S_NO_PRINC_NAME* = 1822 - RPC_S_NOT_RPC_ERROR* = 1823 - RPC_S_UUID_LOCAL_ONLY* = 1824 - RPC_S_SEC_PKG_ERROR* = 1825 - RPC_S_NOT_CANCELLED* = 1826 - RPC_X_INVALID_ES_ACTION* = 1827 - RPC_X_WRONG_ES_VERSION* = 1828 - RPC_X_WRONG_STUB_VERSION* = 1829 - RPC_X_INVALID_PIPE_OBJECT* = 1830 - RPC_X_INVALID_PIPE_OPERATION* = 1831 - RPC_S_GROUP_MEMBER_NOT_FOUND* = 1898 - EPT_S_CANT_CREATE* = 1899 - RPC_S_INVALID_OBJECT* = 1900 - ERROR_INVALID_TIME* = 1901 - ERROR_INVALID_FORM_NAME* = 1902 - ERROR_INVALID_FORM_SIZE* = 1903 - ERROR_ALREADY_WAITING* = 1904 - ERROR_PRINTER_DELETED* = 1905 - ERROR_INVALID_PRINTER_STATE* = 1906 - ERROR_PASSWORD_MUST_CHANGE* = 1907 - ERROR_DOMAIN_CONTROLLER_NOT_FOUND* = 1908 - ERROR_ACCOUNT_LOCKED_OUT* = 1909 - OR_INVALID_OXID* = 1910 - OR_INVALID_OID* = 1911 - OR_INVALID_SET* = 1912 - RPC_S_SEND_INCOMPLETE* = 1913 - ERROR_NO_BROWSER_SERVERS_FOUND* = 6118 - ERROR_INVALID_PIXEL_FORMAT* = 2000 - ERROR_BAD_DRIVER* = 2001 - ERROR_INVALID_WINDOW_STYLE* = 2002 - ERROR_METAFILE_NOT_SUPPORTED* = 2003 - ERROR_TRANSFORM_NOT_SUPPORTED* = 2004 - ERROR_CLIPPING_NOT_SUPPORTED* = 2005 - ERROR_UNKNOWN_PRINT_MONITOR* = 3000 - ERROR_PRINTER_DRIVER_IN_USE* = 3001 - ERROR_SPOOL_FILE_NOT_FOUND* = 3002 - ERROR_SPL_NO_STARTDOC* = 3003 - ERROR_SPL_NO_ADDJOB* = 3004 - ERROR_PRINT_PROCESSOR_ALREADY_INSTALLED* = 3005 - ERROR_PRINT_MONITOR_ALREADY_INSTALLED* = 3006 - ERROR_INVALID_PRINT_MONITOR* = 3007 - ERROR_PRINT_MONITOR_IN_USE* = 3008 - ERROR_PRINTER_HAS_JOBS_QUEUED* = 3009 - ERROR_SUCCESS_REBOOT_REQUIRED* = 3010 - ERROR_SUCCESS_RESTART_REQUIRED* = 3011 - ERROR_WINS_INTERNAL* = 4000 - ERROR_CAN_NOT_DEL_LOCAL_WINS* = 4001 - ERROR_STATIC_INIT* = 4002 - ERROR_INC_BACKUP* = 4003 - ERROR_FULL_BACKUP* = 4004 - ERROR_REC_NON_EXISTENT* = 4005 - ERROR_RPL_NOT_ALLOWED* = 4006 - E_UNEXPECTED* = HRESULT(0x8000FFFF) - E_NOTIMPL* = HRESULT(0x80004001) - E_OUTOFMEMORY* = HRESULT(0x8007000E) - E_INVALIDARG* = HRESULT(0x80070057) - E_NOINTERFACE* = HRESULT(0x80004002) - E_POINTER* = HRESULT(0x80004003) - E_HANDLE* = HRESULT(0x80070006) - E_ABORT* = HRESULT(0x80004004) - E_FAIL* = HRESULT(0x80004005) - E_ACCESSDENIED* = HRESULT(0x80070005) - E_PENDING* = HRESULT(0x8000000A) - CO_E_INIT_TLS* = HRESULT(0x80004006) - CO_E_INIT_SHARED_ALLOCATOR* = HRESULT(0x80004007) - CO_E_INIT_MEMORY_ALLOCATOR* = HRESULT(0x80004008) - CO_E_INIT_CLASS_CACHE* = HRESULT(0x80004009) - CO_E_INIT_RPC_CHANNEL* = HRESULT(0x8000400A) - CO_E_INIT_TLS_SET_CHANNEL_CONTROL* = HRESULT(0x8000400B) - CO_E_INIT_TLS_CHANNEL_CONTROL* = HRESULT(0x8000400C) - CO_E_INIT_UNACCEPTED_USER_ALLOCATOR* = HRESULT(0x8000400D) - CO_E_INIT_SCM_MUTEX_EXISTS* = HRESULT(0x8000400E) - CO_E_INIT_SCM_FILE_MAPPING_EXISTS* = HRESULT(0x8000400F) - CO_E_INIT_SCM_MAP_VIEW_OF_FILE* = HRESULT(0x80004010) - CO_E_INIT_SCM_EXEC_FAILURE* = HRESULT(0x80004011) - CO_E_INIT_ONLY_SINGLE_THREADED* = HRESULT(0x80004012) - CO_E_CANT_REMOTE* = HRESULT(0x80004013) - CO_E_BAD_SERVER_NAME* = HRESULT(0x80004014) - CO_E_WRONG_SERVER_IDENTITY* = HRESULT(0x80004015) - CO_E_OLE1DDE_DISABLED* = HRESULT(0x80004016) - CO_E_RUNAS_SYNTAX* = HRESULT(0x80004017) - CO_E_CREATEPROCESS_FAILURE* = HRESULT(0x80004018) - CO_E_RUNAS_CREATEPROCESS_FAILURE* = HRESULT(0x80004019) - CO_E_RUNAS_LOGON_FAILURE* = HRESULT(0x8000401A) - CO_E_LAUNCH_PERMSSION_DENIED* = HRESULT(0x8000401B) - CO_E_START_SERVICE_FAILURE* = HRESULT(0x8000401C) - CO_E_REMOTE_COMMUNICATION_FAILURE* = HRESULT(0x8000401D) - CO_E_SERVER_START_TIMEOUT* = HRESULT(0x8000401E) - CO_E_CLSREG_INCONSISTENT* = HRESULT(0x8000401F) - CO_E_IIDREG_INCONSISTENT* = HRESULT(0x80004020) - CO_E_NOT_SUPPORTED* = HRESULT(0x80004021) - CO_E_FIRST* = DWORD(0x800401F0) - CO_E_LAST* = DWORD(0x800401FF) - CO_S_FIRST* = DWORD(0x000401F0) - CO_S_LAST* = DWORD(0x000401FF) - S_OK* = HRESULT(0x00000000) - S_FALSE* = HRESULT(0x00000001) - CO_E_NOTINITIALIZED* = HRESULT(0x800401F0) - CO_E_ALREADYINITIALIZED* = HRESULT(0x800401F1) - CO_E_CANTDETERMINECLASS* = HRESULT(0x800401F2) - CO_E_CLASSSTRING* = HRESULT(0x800401F3) - CO_E_IIDSTRING* = HRESULT(0x800401F4) - CO_E_APPNOTFOUND* = HRESULT(0x800401F5) - CO_E_APPSINGLEUSE* = HRESULT(0x800401F6) - CO_E_ERRORINAPP* = HRESULT(0x800401F7) - CO_E_DLLNOTFOUND* = HRESULT(0x800401F8) - CO_E_ERRORINDLL* = HRESULT(0x800401F9) - CO_E_WRONGOSFORAPP* = HRESULT(0x800401FA) - CO_E_OBJNOTREG* = HRESULT(0x800401FB) - CO_E_OBJISREG* = HRESULT(0x800401FC) - CO_E_OBJNOTCONNECTED* = HRESULT(0x800401FD) - CO_E_APPDIDNTREG* = HRESULT(0x800401FE) - CO_E_RELEASED* = HRESULT(0x800401FF) - OLE_E_FIRST* = HRESULT(0x80040000) - OLE_E_LAST* = HRESULT(0x800400FF) - OLE_S_FIRST* = HRESULT(0x00040000) - OLE_S_LAST* = HRESULT(0x000400FF) - OLE_E_OLEVERB* = HRESULT(0x80040000) - OLE_E_ADVF* = HRESULT(0x80040001) - OLE_E_ENUM_NOMORE* = HRESULT(0x80040002) - OLE_E_ADVISENOTSUPPORTED* = HRESULT(0x80040003) - OLE_E_NOCONNECTION* = HRESULT(0x80040004) - OLE_E_NOTRUNNING* = HRESULT(0x80040005) - OLE_E_NOCACHE* = HRESULT(0x80040006) - OLE_E_BLANK* = HRESULT(0x80040007) - OLE_E_CLASSDIFF* = HRESULT(0x80040008) - OLE_E_CANT_GETMONIKER* = HRESULT(0x80040009) - OLE_E_CANT_BINDTOSOURCE* = HRESULT(0x8004000A) - OLE_E_STATIC* = HRESULT(0x8004000B) - OLE_E_PROMPTSAVECANCELLED* = HRESULT(0x8004000C) - OLE_E_INVALIDRECT* = HRESULT(0x8004000D) - OLE_E_WRONGCOMPOBJ* = HRESULT(0x8004000E) - OLE_E_INVALIDHWND* = HRESULT(0x8004000F) - OLE_E_NOT_INPLACEACTIVE* = HRESULT(0x80040010) - OLE_E_CANTCONVERT* = HRESULT(0x80040011) - OLE_E_NOSTORAGE* = HRESULT(0x80040012) - DV_E_FORMATETC* = HRESULT(0x80040064) - DV_E_DVTARGETDEVICE* = HRESULT(0x80040065) - DV_E_STGMEDIUM* = HRESULT(0x80040066) - DV_E_STATDATA* = HRESULT(0x80040067) - DV_E_LINDEX* = HRESULT(0x80040068) - DV_E_TYMED* = HRESULT(0x80040069) - DV_E_CLIPFORMAT* = HRESULT(0x8004006A) - DV_E_DVASPECT* = HRESULT(0x8004006B) - DV_E_DVTARGETDEVICE_SIZE* = HRESULT(0x8004006C) - DV_E_NOIVIEWOBJECT* = HRESULT(0x8004006D) - DRAGDROP_E_FIRST* = DWORD(0x80040100) - DRAGDROP_E_LAST* = DWORD(0x8004010F) - DRAGDROP_S_FIRST* = DWORD(0x00040100) - DRAGDROP_S_LAST* = DWORD(0x0004010F) - DRAGDROP_E_NOTREGISTERED* = HRESULT(0x80040100) - DRAGDROP_E_ALREADYREGISTERED* = HRESULT(0x80040101) - DRAGDROP_E_INVALIDHWND* = HRESULT(0x80040102) - CLASSFACTORY_E_FIRST* = DWORD(0x80040110) - CLASSFACTORY_E_LAST* = DWORD(0x8004011F) - CLASSFACTORY_S_FIRST* = DWORD(0x00040110) - CLASSFACTORY_S_LAST* = DWORD(0x0004011F) - CLASS_E_NOAGGREGATION* = HRESULT(0x80040110) - CLASS_E_CLASSNOTAVAILABLE* = HRESULT(0x80040111) - MARSHAL_E_FIRST* = DWORD(0x80040120) - MARSHAL_E_LAST* = DWORD(0x8004012F) - MARSHAL_S_FIRST* = DWORD(0x00040120) - MARSHAL_S_LAST* = DWORD(0x0004012F) - DATA_E_FIRST* = DWORD(0x80040130) - DATA_E_LAST* = DWORD(0x8004013F) - DATA_S_FIRST* = DWORD(0x00040130) - DATA_S_LAST* = DWORD(0x0004013F) - VIEW_E_FIRST* = DWORD(0x80040140) - VIEW_E_LAST* = DWORD(0x8004014F) - VIEW_S_FIRST* = DWORD(0x00040140) - VIEW_S_LAST* = DWORD(0x0004014F) - VIEW_E_DRAW* = HRESULT(0x80040140) - REGDB_E_FIRST* = DWORD(0x80040150) - REGDB_E_LAST* = DWORD(0x8004015F) - REGDB_S_FIRST* = DWORD(0x00040150) - REGDB_S_LAST* = DWORD(0x0004015F) - REGDB_E_READREGDB* = HRESULT(0x80040150) - REGDB_E_WRITEREGDB* = HRESULT(0x80040151) - REGDB_E_KEYMISSING* = HRESULT(0x80040152) - REGDB_E_INVALIDVALUE* = HRESULT(0x80040153) - REGDB_E_CLASSNOTREG* = HRESULT(0x80040154) - REGDB_E_IIDNOTREG* = HRESULT(0x80040155) - CACHE_E_FIRST* = DWORD(0x80040170) - CACHE_E_LAST* = DWORD(0x8004017F) - CACHE_S_FIRST* = DWORD(0x00040170) - CACHE_S_LAST* = DWORD(0x0004017F) - CACHE_E_NOCACHE_UPDATED* = HRESULT(0x80040170) - OLEOBJ_E_FIRST* = DWORD(0x80040180) - OLEOBJ_E_LAST* = DWORD(0x8004018F) - OLEOBJ_S_FIRST* = DWORD(0x00040180) - OLEOBJ_S_LAST* = DWORD(0x0004018F) - OLEOBJ_E_NOVERBS* = HRESULT(0x80040180) - OLEOBJ_E_INVALIDVERB* = HRESULT(0x80040181) - CLIENTSITE_E_FIRST* = DWORD(0x80040190) - CLIENTSITE_E_LAST* = DWORD(0x8004019F) - CLIENTSITE_S_FIRST* = DWORD(0x00040190) - CLIENTSITE_S_LAST* = DWORD(0x0004019F) - INPLACE_E_NOTUNDOABLE* = HRESULT(0x800401A0) - INPLACE_E_NOTOOLSPACE* = HRESULT(0x800401A1) - INPLACE_E_FIRST* = DWORD(0x800401A0) - INPLACE_E_LAST* = DWORD(0x800401AF) - INPLACE_S_FIRST* = DWORD(0x000401A0) - INPLACE_S_LAST* = DWORD(0x000401AF) - ENUM_E_FIRST* = DWORD(0x800401B0) - ENUM_E_LAST* = DWORD(0x800401BF) - ENUM_S_FIRST* = DWORD(0x000401B0) - ENUM_S_LAST* = DWORD(0x000401BF) - CONVERT10_E_FIRST* = DWORD(0x800401C0) - CONVERT10_E_LAST* = DWORD(0x800401CF) - CONVERT10_S_FIRST* = DWORD(0x000401C0) - CONVERT10_S_LAST* = DWORD(0x000401CF) - CONVERT10_E_OLESTREAM_GET* = HRESULT(0x800401C0) - CONVERT10_E_OLESTREAM_PUT* = HRESULT(0x800401C1) - CONVERT10_E_OLESTREAM_FMT* = HRESULT(0x800401C2) - CONVERT10_E_OLESTREAM_BITMAP_TO_DIB* = HRESULT(0x800401C3) - CONVERT10_E_STG_FMT* = HRESULT(0x800401C4) - CONVERT10_E_STG_NO_STD_STREAM* = HRESULT(0x800401C5) - CONVERT10_E_STG_DIB_TO_BITMAP* = HRESULT(0x800401C6) - CLIPBRD_E_FIRST* = DWORD(0x800401D0) - CLIPBRD_E_LAST* = DWORD(0x800401DF) - CLIPBRD_S_FIRST* = DWORD(0x000401D0) - CLIPBRD_S_LAST* = DWORD(0x000401DF) - CLIPBRD_E_CANT_OPEN* = HRESULT(0x800401D0) - CLIPBRD_E_CANT_EMPTY* = HRESULT(0x800401D1) - CLIPBRD_E_CANT_SET* = HRESULT(0x800401D2) - CLIPBRD_E_BAD_DATA* = HRESULT(0x800401D3) - CLIPBRD_E_CANT_CLOSE* = HRESULT(0x800401D4) - MK_E_FIRST* = DWORD(0x800401E0) - MK_E_LAST* = DWORD(0x800401EF) - MK_S_FIRST* = DWORD(0x000401E0) - MK_S_LAST* = DWORD(0x000401EF) - MK_E_CONNECTMANUALLY* = HRESULT(0x800401E0) - MK_E_EXCEEDEDDEADLINE* = HRESULT(0x800401E1) - MK_E_NEEDGENERIC* = HRESULT(0x800401E2) - MK_E_UNAVAILABLE* = HRESULT(0x800401E3) - MK_E_SYNTAX* = HRESULT(0x800401E4) - MK_E_NOOBJECT* = HRESULT(0x800401E5) - MK_E_INVALIDEXTENSION* = HRESULT(0x800401E6) - MK_E_INTERMEDIATEINTERFACENOTSUPPORTED* = HRESULT(0x800401E7) - MK_E_NOTBINDABLE* = HRESULT(0x800401E8) - MK_E_NOTBOUND* = HRESULT(0x800401E9) - MK_E_CANTOPENFILE* = HRESULT(0x800401EA) - MK_E_MUSTBOTHERUSER* = HRESULT(0x800401EB) - MK_E_NOINVERSE* = HRESULT(0x800401EC) - MK_E_NOSTORAGE* = HRESULT(0x800401ED) - MK_E_NOPREFIX* = HRESULT(0x800401EE) - MK_E_ENUMERATION_FAILED* = HRESULT(0x800401EF) - OLE_S_USEREG* = HRESULT(0x00040000) - OLE_S_STATIC* = HRESULT(0x00040001) - OLE_S_MAC_CLIPFORMAT* = HRESULT(0x00040002) - DRAGDROP_S_DROP* = HRESULT(0x00040100) - DRAGDROP_S_CANCEL* = HRESULT(0x00040101) - DRAGDROP_S_USEDEFAULTCURSORS* = HRESULT(0x00040102) - DATA_S_SAMEFORMATETC* = HRESULT(0x00040130) - VIEW_S_ALREADY_FROZEN* = HRESULT(0x00040140) - CACHE_S_FORMATETC_NOTSUPPORTED* = HRESULT(0x00040170) - CACHE_S_SAMECACHE* = HRESULT(0x00040171) - CACHE_S_SOMECACHES_NOTUPDATED* = HRESULT(0x00040172) - OLEOBJ_S_INVALIDVERB* = HRESULT(0x00040180) - OLEOBJ_S_CANNOT_DOVERB_NOW* = HRESULT(0x00040181) - OLEOBJ_S_INVALIDHWND* = HRESULT(0x00040182) - INPLACE_S_TRUNCATED* = HRESULT(0x000401A0) - CONVERT10_S_NO_PRESENTATION* = HRESULT(0x000401C0) - MK_S_REDUCED_TO_SELF* = HRESULT(0x000401E2) - MK_S_ME* = HRESULT(0x000401E4) - MK_S_HIM* = HRESULT(0x000401E5) - MK_S_US* = HRESULT(0x000401E6) - MK_S_MONIKERALREADYREGISTERED* = HRESULT(0x000401E7) - CO_E_CLASS_CREATE_FAILED* = HRESULT(0x80080001) - CO_E_SCM_ERROR* = HRESULT(0x80080002) - CO_E_SCM_RPC_FAILURE* = HRESULT(0x80080003) - CO_E_BAD_PATH* = HRESULT(0x80080004) - CO_E_SERVER_EXEC_FAILURE* = HRESULT(0x80080005) - CO_E_OBJSRV_RPC_FAILURE* = HRESULT(0x80080006) - MK_E_NO_NORMALIZED* = HRESULT(0x80080007) - CO_E_SERVER_STOPPING* = HRESULT(0x80080008) - MEM_E_INVALID_ROOT* = HRESULT(0x80080009) - MEM_E_INVALID_LINK* = HRESULT(0x80080010) - MEM_E_INVALID_SIZE* = HRESULT(0x80080011) - CO_S_NOTALLINTERFACES* = HRESULT(0x00080012) - DISP_E_UNKNOWNINTERFACE* = HRESULT(0x80020001) - DISP_E_MEMBERNOTFOUND* = HRESULT(0x80020003) - DISP_E_PARAMNOTFOUND* = HRESULT(0x80020004) - DISP_E_TYPEMISMATCH* = HRESULT(0x80020005) - DISP_E_UNKNOWNNAME* = HRESULT(0x80020006) - DISP_E_NONAMEDARGS* = HRESULT(0x80020007) - DISP_E_BADVARTYPE* = HRESULT(0x80020008) - DISP_E_EXCEPTION* = HRESULT(0x80020009) - DISP_E_OVERFLOW* = HRESULT(0x8002000A) - DISP_E_BADINDEX* = HRESULT(0x8002000B) - DISP_E_UNKNOWNLCID* = HRESULT(0x8002000C) - DISP_E_ARRAYISLOCKED* = HRESULT(0x8002000D) - DISP_E_BADPARAMCOUNT* = HRESULT(0x8002000E) - DISP_E_PARAMNOTOPTIONAL* = HRESULT(0x8002000F) - DISP_E_BADCALLEE* = HRESULT(0x80020010) - DISP_E_NOTACOLLECTION* = HRESULT(0x80020011) - TYPE_E_BUFFERTOOSMALL* = HRESULT(0x80028016) - TYPE_E_INVDATAREAD* = HRESULT(0x80028018) - TYPE_E_UNSUPFORMAT* = HRESULT(0x80028019) - TYPE_E_REGISTRYACCESS* = HRESULT(0x8002801C) - TYPE_E_LIBNOTREGISTERED* = HRESULT(0x8002801D) - TYPE_E_UNDEFINEDTYPE* = HRESULT(0x80028027) - TYPE_E_QUALIFIEDNAMEDISALLOWED* = HRESULT(0x80028028) - TYPE_E_INVALIDSTATE* = HRESULT(0x80028029) - TYPE_E_WRONGTYPEKIND* = HRESULT(0x8002802A) - TYPE_E_ELEMENTNOTFOUND* = HRESULT(0x8002802B) - TYPE_E_AMBIGUOUSNAME* = HRESULT(0x8002802C) - TYPE_E_NAMECONFLICT* = HRESULT(0x8002802D) - TYPE_E_UNKNOWNLCID* = HRESULT(0x8002802E) - TYPE_E_DLLFUNCTIONNOTFOUND* = HRESULT(0x8002802F) - TYPE_E_BADMODULEKIND* = HRESULT(0x800288BD) - TYPE_E_SIZETOOBIG* = HRESULT(0x800288C5) - TYPE_E_DUPLICATEID* = HRESULT(0x800288C6) - TYPE_E_INVALIDID* = HRESULT(0x800288CF) - TYPE_E_TYPEMISMATCH* = HRESULT(0x80028CA0) - TYPE_E_OUTOFBOUNDS* = HRESULT(0x80028CA1) - TYPE_E_IOERROR* = HRESULT(0x80028CA2) - TYPE_E_CANTCREATETMPFILE* = HRESULT(0x80028CA3) - TYPE_E_CANTLOADLIBRARY* = HRESULT(0x80029C4A) - TYPE_E_INCONSISTENTPROPFUNCS* = HRESULT(0x80029C83) - TYPE_E_CIRCULARTYPE* = HRESULT(0x80029C84) - STG_E_INVALIDFUNCTION* = HRESULT(0x80030001) - STG_E_FILENOTFOUND* = HRESULT(0x80030002) - STG_E_PATHNOTFOUND* = HRESULT(0x80030003) - STG_E_TOOMANYOPENFILES* = HRESULT(0x80030004) - STG_E_ACCESSDENIED* = HRESULT(0x80030005) - STG_E_INVALIDHANDLE* = HRESULT(0x80030006) - STG_E_INSUFFICIENTMEMORY* = HRESULT(0x80030008) - STG_E_INVALIDPOINTER* = HRESULT(0x80030009) - STG_E_NOMOREFILES* = HRESULT(0x80030012) - STG_E_DISKISWRITEPROTECTED* = HRESULT(0x80030013) - STG_E_SEEKERROR* = HRESULT(0x80030019) - STG_E_WRITEFAULT* = HRESULT(0x8003001D) - STG_E_READFAULT* = HRESULT(0x8003001E) - STG_E_SHAREVIOLATION* = HRESULT(0x80030020) - STG_E_LOCKVIOLATION* = HRESULT(0x80030021) - STG_E_FILEALREADYEXISTS* = HRESULT(0x80030050) - STG_E_INVALIDPARAMETER* = HRESULT(0x80030057) - STG_E_MEDIUMFULL* = HRESULT(0x80030070) - STG_E_PROPSETMISMATCHED* = HRESULT(0x800300F0) - STG_E_ABNORMALAPIEXIT* = HRESULT(0x800300FA) - STG_E_INVALIDHEADER* = HRESULT(0x800300FB) - STG_E_INVALIDNAME* = HRESULT(0x800300FC) - STG_E_UNKNOWN* = HRESULT(0x800300FD) - STG_E_UNIMPLEMENTEDFUNCTION* = HRESULT(0x800300FE) - STG_E_INVALIDFLAG* = HRESULT(0x800300FF) - STG_E_INUSE* = HRESULT(0x80030100) - STG_E_NOTCURRENT* = HRESULT(0x80030101) - STG_E_REVERTED* = HRESULT(0x80030102) - STG_E_CANTSAVE* = HRESULT(0x80030103) - STG_E_OLDFORMAT* = HRESULT(0x80030104) - STG_E_OLDDLL* = HRESULT(0x80030105) - STG_E_SHAREREQUIRED* = HRESULT(0x80030106) - STG_E_NOTFILEBASEDSTORAGE* = HRESULT(0x80030107) - STG_E_EXTANTMARSHALLINGS* = HRESULT(0x80030108) - STG_E_DOCFILECORRUPT* = HRESULT(0x80030109) - STG_E_BADBASEADDRESS* = HRESULT(0x80030110) - STG_E_INCOMPLETE* = HRESULT(0x80030201) - STG_E_TERMINATED* = HRESULT(0x80030202) - STG_S_CONVERTED* = HRESULT(0x00030200) - STG_S_BLOCK* = HRESULT(0x00030201) - STG_S_RETRYNOW* = HRESULT(0x00030202) - STG_S_MONITORING* = HRESULT(0x00030203) - RPC_E_CALL_REJECTED* = HRESULT(0x80010001) - RPC_E_CALL_CANCELED* = HRESULT(0x80010002) - RPC_E_CANTPOST_INSENDCALL* = HRESULT(0x80010003) - RPC_E_CANTCALLOUT_INASYNCCALL* = HRESULT(0x80010004) - RPC_E_CANTCALLOUT_INEXTERNALCALL* = HRESULT(0x80010005) - RPC_E_CONNECTION_TERMINATED* = HRESULT(0x80010006) - RPC_E_SERVER_DIED* = HRESULT(0x80010007) - RPC_E_CLIENT_DIED* = HRESULT(0x80010008) - RPC_E_INVALID_DATAPACKET* = HRESULT(0x80010009) - RPC_E_CANTTRANSMIT_CALL* = HRESULT(0x8001000A) - RPC_E_CLIENT_CANTMARSHAL_DATA* = HRESULT(0x8001000B) - RPC_E_CLIENT_CANTUNMARSHAL_DATA* = HRESULT(0x8001000C) - RPC_E_SERVER_CANTMARSHAL_DATA* = HRESULT(0x8001000D) - RPC_E_SERVER_CANTUNMARSHAL_DATA* = HRESULT(0x8001000E) - RPC_E_INVALID_DATA* = HRESULT(0x8001000F) - RPC_E_INVALID_PARAMETER* = HRESULT(0x80010010) - RPC_E_CANTCALLOUT_AGAIN* = HRESULT(0x80010011) - RPC_E_SERVER_DIED_DNE* = HRESULT(0x80010012) - RPC_E_SYS_CALL_FAILED* = HRESULT(0x80010100) - RPC_E_OUT_OF_RESOURCES* = HRESULT(0x80010101) - RPC_E_ATTEMPTED_MULTITHREAD* = HRESULT(0x80010102) - RPC_E_NOT_REGISTERED* = HRESULT(0x80010103) - RPC_E_FAULT* = HRESULT(0x80010104) - RPC_E_SERVERFAULT* = HRESULT(0x80010105) - RPC_E_CHANGED_MODE* = HRESULT(0x80010106) - RPC_E_INVALIDMETHOD* = HRESULT(0x80010107) - RPC_E_DISCONNECTED* = HRESULT(0x80010108) - RPC_E_RETRY* = HRESULT(0x80010109) - RPC_E_SERVERCALL_RETRYLATER* = HRESULT(0x8001010A) - RPC_E_SERVERCALL_REJECTED* = HRESULT(0x8001010B) - RPC_E_INVALID_CALLDATA* = HRESULT(0x8001010C) - RPC_E_CANTCALLOUT_ININPUTSYNCCALL* = HRESULT(0x8001010D) - RPC_E_WRONG_THREAD* = HRESULT(0x8001010E) - RPC_E_THREAD_NOT_INIT* = HRESULT(0x8001010F) - RPC_E_VERSION_MISMATCH* = HRESULT(0x80010110) - RPC_E_INVALID_HEADER* = HRESULT(0x80010111) - RPC_E_INVALID_EXTENSION* = HRESULT(0x80010112) - RPC_E_INVALID_IPID* = HRESULT(0x80010113) - RPC_E_INVALID_OBJECT* = HRESULT(0x80010114) - RPC_S_CALLPENDING* = HRESULT(0x80010115) - RPC_S_WAITONTIMER* = HRESULT(0x80010116) - RPC_E_CALL_COMPLETE* = HRESULT(0x80010117) - RPC_E_UNSECURE_CALL* = HRESULT(0x80010118) - RPC_E_TOO_LATE* = HRESULT(0x80010119) - RPC_E_NO_GOOD_SECURITY_PACKAGES* = HRESULT(0x8001011A) - RPC_E_ACCESS_DENIED* = HRESULT(0x8001011B) - RPC_E_REMOTE_DISABLED* = HRESULT(0x8001011C) - RPC_E_INVALID_OBJREF* = HRESULT(0x8001011D) - RPC_E_UNEXPECTED* = HRESULT(0x8001FFFF) - NTE_BAD_UID* = HRESULT(0x80090001) - NTE_BAD_HASH* = HRESULT(0x80090002) - NTE_BAD_KEY* = HRESULT(0x80090003) - NTE_BAD_LEN* = HRESULT(0x80090004) - NTE_BAD_DATA* = HRESULT(0x80090005) - NTE_BAD_SIGNATURE* = HRESULT(0x80090006) - NTE_BAD_VER* = HRESULT(0x80090007) - NTE_BAD_ALGID* = HRESULT(0x80090008) - NTE_BAD_FLAGS* = HRESULT(0x80090009) - NTE_BAD_TYPE* = HRESULT(0x8009000A) - NTE_BAD_KEY_STATE* = HRESULT(0x8009000B) - NTE_BAD_HASH_STATE* = HRESULT(0x8009000C) - NTE_NO_KEY* = HRESULT(0x8009000D) - NTE_NO_MEMORY* = HRESULT(0x8009000E) - NTE_EXISTS* = HRESULT(0x8009000F) - NTE_PERM* = HRESULT(0x80090010) - NTE_NOT_FOUND* = HRESULT(0x80090011) - NTE_DOUBLE_ENCRYPT* = HRESULT(0x80090012) - NTE_BAD_PROVIDER* = HRESULT(0x80090013) - NTE_BAD_PROV_TYPE* = HRESULT(0x80090014) - NTE_BAD_PUBLIC_KEY* = HRESULT(0x80090015) - NTE_BAD_KEYSET* = HRESULT(0x80090016) - NTE_PROV_TYPE_NOT_DEF* = HRESULT(0x80090017) - NTE_PROV_TYPE_ENTRY_BAD* = HRESULT(0x80090018) - NTE_KEYSET_NOT_DEF* = HRESULT(0x80090019) - NTE_KEYSET_ENTRY_BAD* = HRESULT(0x8009001A) - NTE_PROV_TYPE_NO_MATCH* = HRESULT(0x8009001B) - NTE_SIGNATURE_FILE_BAD* = HRESULT(0x8009001C) - NTE_PROVIDER_DLL_FAIL* = HRESULT(0x8009001D) - NTE_PROV_DLL_NOT_FOUND* = HRESULT(0x8009001E) - NTE_BAD_KEYSET_PARAM* = HRESULT(0x8009001F) - NTE_FAIL* = HRESULT(0x80090020) - NTE_SYS_ERR* = HRESULT(0x80090021) - NTE_OP_OK* = HRESULT(0) - TRUST_E_PROVIDER_UNKNOWN* = HRESULT(0x800B0001) - TRUST_E_ACTION_UNKNOWN* = HRESULT(0x800B0002) - TRUST_E_SUBJECT_FORM_UNKNOWN* = HRESULT(0x800B0003) - TRUST_E_SUBJECT_NOT_TRUSTED* = HRESULT(0x800B0004) - DIGSIG_E_ENCODE* = HRESULT(0x800B0005) - DIGSIG_E_DECODE* = HRESULT(0x800B0006) - DIGSIG_E_EXTENSIBILITY* = HRESULT(0x800B0007) - DIGSIG_E_CRYPTO* = HRESULT(0x800B0008) - PERSIST_E_SIZEDEFINITE* = HRESULT(0x800B0009) - PERSIST_E_SIZEINDEFINITE* = HRESULT(0x800B000A) - PERSIST_E_NOTSELFSIZING* = HRESULT(0x800B000B) - TRUST_E_NOSIGNATURE* = HRESULT(0x800B0100) - CERT_E_EXPIRED* = HRESULT(0x800B0101) - CERT_E_VALIDIYPERIODNESTING* = HRESULT(0x800B0102) - CERT_E_ROLE* = HRESULT(0x800B0103) - CERT_E_PATHLENCONST* = HRESULT(0x800B0104) - CERT_E_CRITICAL* = HRESULT(0x800B0105) - CERT_E_PURPOSE* = HRESULT(0x800B0106) - CERT_E_ISSUERCHAINING* = HRESULT(0x800B0107) - CERT_E_MALFORMED* = HRESULT(0x800B0108) - CERT_E_UNTRUSTEDROOT* = HRESULT(0x800B0109) - CERT_E_CHAINING* = HRESULT(0x800B010A) - -proc UNICODE_NULL*(): WCHAR -const - LF_FACESIZE* = 32 - LF_FULLFACESIZE* = 64 - ELF_VENDOR_SIZE* = 4 - SECURITY_STATIC_TRACKING* = 0 - SECURITY_DYNAMIC_TRACKING* = 1 - MAX_DEFAULTCHAR* = 2 - MAX_LEADBYTES* = 12 - EXCEPTION_MAXIMUM_PARAMETERS* = 15 - CCHDEVICENAME* = 32 - CCHFORMNAME* = 32 - MENU_TEXT_LEN* = 40 - MAX_LANA* = 254 - NCBNAMSZ* = 16 - NETBIOS_NAME_LEN* = 16 - OFS_MAXPATHNAME* = 128 - MAX_TAB_STOPS* = 32 - ANYSIZE_ARRAY* = 1 - RAS_MaxCallbackNumber* = 128 - RAS_MaxDeviceName* = 128 - RAS_MaxDeviceType* = 16 - RAS_MaxEntryName* = 256 - RAS_MaxIpAddress* = 15 - RAS_MaxIpxAddress* = 21 - RAS_MaxPhoneNumber* = 128 - UNLEN* = 256 - PWLEN* = 256 - CNLEN* = 15 - DNLEN* = 15 - # Unsigned types max - MAXDWORD* = 0xFFFFFFFF - MAXWORD* = 0x0000FFFF - MAXBYTE* = 0x000000FF - # Signed types max/min - MINCHAR* = 0x00000080 - MAXCHAR* = 0x0000007F - MINSHORT* = 0x00008000 - MAXSHORT* = 0x00007FFF - MINLONG* = 0x80000000 - MAXLONG* = 0x7FFFFFFF - # _llseek - FILE_BEGIN* = 0 - FILE_CURRENT* = 1 - FILE_END* = 2 - # _lopen, LZOpenFile, OpenFile - OF_READ* = 0 - OF_READWRITE* = 2 - OF_WRITE* = 1 - OF_SHARE_COMPAT* = 0 - OF_SHARE_DENY_NONE* = 64 - OF_SHARE_DENY_READ* = 48 - OF_SHARE_DENY_WRITE* = 32 - OF_SHARE_EXCLUSIVE* = 16 - OF_CANCEL* = 2048 - OF_CREATE* = 4096 - OF_DELETE* = 512 - OF_EXIST* = 16384 - OF_PARSE* = 256 - OF_PROMPT* = 8192 - OF_REOPEN* = 32768 - OF_VERIFY* = 1024 - # ActivateKeyboardLayout, LoadKeyboardLayout - HKL_NEXT* = 1 - HKL_PREV* = 0 - KLF_REORDER* = 8 - KLF_UNLOADPREVIOUS* = 4 - KLF_ACTIVATE* = 1 - KLF_NOTELLSHELL* = 128 - KLF_REPLACELANG* = 16 - KLF_SUBSTITUTE_OK* = 2 - # AppendMenu - MF_BITMAP* = 0x00000004 - MF_DISABLED* = 0x00000002 - MF_ENABLED* = 0 - MF_GRAYED* = 0x00000001 - MF_HELP* = 0x00004000 - MF_MENUBARBREAK* = 0x00000020 - MF_MENUBREAK* = 0x00000040 - MF_MOUSESELECT* = 0x00008000 - MF_OWNERDRAW* = 0x00000100 - MF_POPUP* = 0x00000010 - MF_SEPARATOR* = 0x00000800 - MF_STRING* = 0 - MF_SYSMENU* = 0x00002000 - MF_USECHECKBITMAPS* = 0x00000200 - # Ternary Raster Operations - BitBlt - BLACKNESS* = 0x00000042 - NOTSRCERASE* = 0x001100A6 - NOTSRCCOPY* = 0x00330008 - SRCERASE* = 0x00440328 - DSTINVERT* = 0x00550009 - PATINVERT* = 0x005A0049 - SRCINVERT* = 0x00660046 - SRCAND* = 0x008800C6 - MERGEPAINT* = 0x00BB0226 - MERGECOPY* = 0x00C000CA - SRCCOPY* = 0x00CC0020 - SRCPAINT* = 0x00EE0086 - PATCOPY* = 0x00F00021 - PATPAINT* = 0x00FB0A09 - WHITENESS* = 0x00FF0062 - # Binary Raster Operations - R2_BLACK* = 1 - R2_COPYPEN* = 13 - R2_MASKNOTPEN* = 3 - R2_MASKPEN* = 9 - R2_MASKPENNOT* = 5 - R2_MERGENOTPEN* = 12 - R2_MERGEPEN* = 15 - R2_MERGEPENNOT* = 14 - R2_NOP* = 11 - R2_NOT* = 6 - R2_NOTCOPYPEN* = 4 - R2_NOTMASKPEN* = 8 - R2_NOTMERGEPEN* = 2 - R2_NOTXORPEN* = 10 - R2_WHITE* = 16 - R2_XORPEN* = 7 - # BroadcastSystemMessage - BSF_FLUSHDISK* = 4 - BSF_FORCEIFHUNG* = 32 - BSF_IGNORECURRENTTASK* = 2 - BSF_NOHANG* = 8 - BSF_POSTMESSAGE* = 16 - BSF_QUERY* = 1 - BSM_ALLCOMPONENTS* = 0 - BSM_APPLICATIONS* = 8 - BSM_INSTALLABLEDRIVERS* = 4 - BSM_NETDRIVER* = 2 - BSM_VXDS* = 1 - BROADCAST_QUERY_DENY* = 1112363332 - # CallNamedPipe - NMPWAIT_NOWAIT* = 1 - NMPWAIT_WAIT_FOREVER* = -1 - NMPWAIT_USE_DEFAULT_WAIT* = 0 - # CascadeWindows, TileWindows - MDITILE_SKIPDISABLED* = 2 - MDITILE_HORIZONTAL* = 1 - MDITILE_VERTICAL* = 0 - # CBTProc - HCBT_ACTIVATE* = 5 - HCBT_CLICKSKIPPED* = 6 - HCBT_CREATEWND* = 3 - HCBT_DESTROYWND* = 4 - HCBT_KEYSKIPPED* = 7 - HCBT_MINMAX* = 1 - HCBT_MOVESIZE* = 0 - HCBT_QS* = 2 - HCBT_SETFOCUS* = 9 - HCBT_SYSCOMMAND* = 8 - - CDS_UPDATEREGISTRY* = 1 - CDS_TEST* = 2 - CDS_FULLSCREEN* = 4 - CDS_GLOBAL* = 8 - CDS_SET_PRIMARY* = 0x00000010 - CDS_RESET* = 0x40000000 - CDS_SETRECT* = 0x20000000 - CDS_NORESET* = 0x10000000 - DISP_CHANGE_SUCCESSFUL* = 0 - DISP_CHANGE_RESTART* = 1 - DISP_CHANGE_BADFLAGS* = -4 - DISP_CHANGE_FAILED* = -1 - DISP_CHANGE_BADMODE* = -2 - DISP_CHANGE_NOTUPDATED* = -3 - # ChangeServiceConfig - SERVICE_NO_CHANGE* = -1 - SERVICE_WIN32_OWN_PROCESS* = 16 - SERVICE_WIN32_SHARE_PROCESS* = 32 - SERVICE_KERNEL_DRIVER* = 1 - SERVICE_FILE_SYSTEM_DRIVER* = 2 - SERVICE_INTERACTIVE_PROCESS* = 256 - SERVICE_BOOT_START* = 0 - SERVICE_SYSTEM_START* = 1 - SERVICE_AUTO_START* = 2 - SERVICE_DEMAND_START* = 3 - SERVICE_DISABLED* = 4 - SERVICE_STOPPED* = 1 - SERVICE_START_PENDING* = 2 - SERVICE_STOP_PENDING* = 3 - SERVICE_RUNNING* = 4 - SERVICE_CONTINUE_PENDING* = 5 - SERVICE_PAUSE_PENDING* = 6 - SERVICE_PAUSED* = 7 - SERVICE_ACCEPT_STOP* = 1 - SERVICE_ACCEPT_PAUSE_CONTINUE* = 2 - SERVICE_ACCEPT_SHUTDOWN* = 4 - # CheckDlgButton - BST_CHECKED* = 1 - BST_INDETERMINATE* = 2 - BST_UNCHECKED* = 0 - BST_FOCUS* = 8 - BST_PUSHED* = 4 - # CheckMenuItem, HiliteMenuItem - MF_BYCOMMAND* = 0 - MF_BYPOSITION* = 0x00000400 - MF_CHECKED* = 0x00000008 - MF_UNCHECKED* = 0 - MF_HILITE* = 0x00000080 - MF_UNHILITE* = 0 - # ChildWindowFromPointEx - CWP_ALL* = 0 - CWP_SKIPINVISIBLE* = 1 - CWP_SKIPDISABLED* = 2 - CWP_SKIPTRANSPARENT* = 4 - # ClearCommError - CE_BREAK* = 16 - CE_DNS* = 2048 - CE_FRAME* = 8 - CE_IOE* = 1024 - CE_MODE* = 32768 - CE_OOP* = 4096 - CE_OVERRUN* = 2 - CE_PTO* = 512 - CE_RXOVER* = 1 - CE_RXPARITY* = 4 - CE_TXFULL* = 256 - # CombineRgn - RGN_AND* = 1 - RGN_COPY* = 5 - RGN_DIFF* = 4 - RGN_OR* = 2 - RGN_XOR* = 3 - NULLREGION* = 1 - SIMPLEREGION* = 2 - COMPLEXREGION* = 3 - ERROR* = 0 - # CommonDlgExtendedError - CDERR_DIALOGFAILURE* = 0x0000FFFF - CDERR_FINDRESFAILURE* = 6 - CDERR_INITIALIZATION* = 2 - CDERR_LOADRESFAILURE* = 7 - CDERR_LOADSTRFAILURE* = 5 - CDERR_LOCKRESFAILURE* = 8 - CDERR_MEMALLOCFAILURE* = 9 - CDERR_MEMLOCKFAILURE* = 10 - CDERR_NOHINSTANCE* = 4 - CDERR_NOHOOK* = 11 - CDERR_NOTEMPLATE* = 3 - CDERR_REGISTERMSGFAIL* = 12 - CDERR_STRUCTSIZE* = 1 - PDERR_CREATEICFAILURE* = 0x00001000 + 10 - PDERR_DEFAULTDIFFERENT* = 0x00001000 + 12 - PDERR_DNDMMISMATCH* = 0x00001000 + 9 - PDERR_GETDEVMODEFAIL* = 0x00001000 + 5 - PDERR_INITFAILURE* = 0x00001000 + 6 - PDERR_LOADDRVFAILURE* = 0x00001000 + 4 - PDERR_NODEFAULTPRN* = 0x00001000 + 8 - PDERR_NODEVICES* = 0x00001000 + 7 - PDERR_PARSEFAILURE* = 0x00001000 + 2 - PDERR_PRINTERNOTFOUND* = 0x00001000 + 11 - PDERR_RETDEFFAILURE* = 0x00001000 + 3 - PDERR_SETUPFAILURE* = 0x00001000 + 1 - CFERR_MAXLESSTHANMIN* = 0x00002000 + 2 - CFERR_NOFONTS* = 0x00002000 + 1 - FNERR_BUFFERTOOSMALL* = 0x00003000 + 3 - FNERR_INVALIDFILENAME* = 0x00003000 + 2 - FNERR_SUBCLASSFAILURE* = 0x00003000 + 1 - FRERR_BUFFERLENGTHZERO* = 0x00004000 + 1 - # CompareString, LCMapString - LOCALE_SYSTEM_DEFAULT* = 0x00000800 - LOCALE_USER_DEFAULT* = 0x00000400 - NORM_IGNORECASE* = 1 - NORM_IGNOREKANATYPE* = 65536 - NORM_IGNORENONSPACE* = 2 - NORM_IGNORESYMBOLS* = 4 - NORM_IGNOREWIDTH* = 131072 - SORT_STRINGSORT* = 4096 - LCMAP_BYTEREV* = 2048 - LCMAP_FULLWIDTH* = 8388608 - LCMAP_HALFWIDTH* = 4194304 - LCMAP_HIRAGANA* = 1048576 - LCMAP_KATAKANA* = 2097152 - LCMAP_LOWERCASE* = 256 - LCMAP_SORTKEY* = 1024 - LCMAP_UPPERCASE* = 512 - # ContinueDebugEvent - DBG_CONTINUE* = 0x00010002 - DBG_CONTROL_BREAK* = 0x40010008 - DBG_CONTROL_C* = 0x40010005 - DBG_EXCEPTION_NOT_HANDLED* = 0x80010001 - DBG_TERMINATE_THREAD* = 0x40010003 - DBG_TERMINATE_PROCESS* = 0x40010004 - # ControlService - SERVICE_CONTROL_STOP* = 1 - SERVICE_CONTROL_PAUSE* = 2 - SERVICE_CONTROL_CONTINUE* = 3 - SERVICE_CONTROL_INTERROGATE* = 4 - SERVICE_CONTROL_SHUTDOWN* = 5 - # CopyImage, LoadImage - IMAGE_BITMAP* = 0 - IMAGE_CURSOR* = 2 - IMAGE_ENHMETAFILE* = 1 - IMAGE_ICON* = 1 - LR_MONOCHROME* = 1 - LR_COLOR* = 2 - LR_COPYRETURNORG* = 4 - LR_COPYDELETEORG* = 8 - LR_DEFAULTSIZE* = 64 - LR_CREATEDIBSECTION* = 8192 - LR_COPYFROMRESOURCE* = 0x00004000 - LR_SHARED* = 0x00008000 - # CreateDesktop - DF_ALLOWOTHERACCOUNTHOOK* = 0x00000001 - DESKTOP_CREATEMENU* = 0x00000004 - DESKTOP_CREATEWINDOW* = 0x00000002 - DESKTOP_ENUMERATE* = 0x00000040 - DESKTOP_HOOKCONTROL* = 0x00000008 - DESKTOP_JOURNALPLAYBACK* = 0x00000020 - DESKTOP_JOURNALRECORD* = 0x00000010 - DESKTOP_READOBJECTS* = 0x00000001 - DESKTOP_SWITCHDESKTOP* = 0x00000100 - DESKTOP_WRITEOBJECTS* = 0x00000080 - WSF_VISIBLE* = 0x00000001 - # CreateDIBitmap - CBM_INIT* = 0x00000004 - DIB_PAL_COLORS* = 1 - DIB_RGB_COLORS* = 0 - # CreateFile, GetFileAttributes, SetFileAttributes - GENERIC_READ* = 0x80000000 - GENERIC_WRITE* = 0x40000000 - FILE_READ_DATA* = 0x00000001 # file & pipe - FILE_LIST_DIRECTORY* = 0x00000001 # directory - FILE_WRITE_DATA* = 0x00000002 # file & pipe - FILE_ADD_FILE* = 0x00000002 # directory - FILE_APPEND_DATA* = 0x00000004 # file - FILE_ADD_SUBDIRECTORY* = 0x00000004 # directory - FILE_CREATE_PIPE_INSTANCE* = 0x00000004 # named pipe - FILE_READ_EA* = 0x00000008 # file & directory - FILE_READ_PROPERTIES* = FILE_READ_EA - FILE_WRITE_EA* = 0x00000010 # file & directory - FILE_WRITE_PROPERTIES* = FILE_WRITE_EA - FILE_EXECUTE* = 0x00000020 # file - FILE_TRAVERSE* = 0x00000020 # directory - FILE_DELETE_CHILD* = 0x00000040 # directory - FILE_READ_ATTRIBUTES* = 0x00000080 # all - FILE_WRITE_ATTRIBUTES* = 0x00000100 # all - FILE_SHARE_DELETE* = 4 - FILE_SHARE_READ* = 1 - FILE_SHARE_WRITE* = 2 - CONSOLE_TEXTMODE_BUFFER* = 1 - CREATE_NEW* = 1 - CREATE_ALWAYS* = 2 - OPEN_EXISTING* = 3 - OPEN_ALWAYS* = 4 - TRUNCATE_EXISTING* = 5 - FILE_ATTRIBUTE_ARCHIVE* = 32 - FILE_ATTRIBUTE_COMPRESSED* = 2048 - FILE_ATTRIBUTE_NORMAL* = 128 - FILE_ATTRIBUTE_DIRECTORY* = 16 - FILE_ATTRIBUTE_HIDDEN* = 2 - FILE_ATTRIBUTE_READONLY* = 1 - FILE_ATTRIBUTE_SYSTEM* = 4 - FILE_ATTRIBUTE_TEMPORARY* = 256 - FILE_FLAG_WRITE_THROUGH* = 0x80000000 - FILE_FLAG_OVERLAPPED* = 1073741824 - FILE_FLAG_NO_BUFFERING* = 536870912 - FILE_FLAG_RANDOM_ACCESS* = 268435456 - FILE_FLAG_SEQUENTIAL_SCAN* = 134217728 - FILE_FLAG_DELETE_ON_CLOSE* = 67108864 - FILE_FLAG_BACKUP_SEMANTICS* = 33554432 - FILE_FLAG_POSIX_SEMANTICS* = 16777216 - cSECURITY_ANONYMOUS* = 0 - cSECURITY_IDENTIFICATION* = 65536 - cSECURITY_IMPERSONATION* = 131072 - cSECURITY_DELEGATION* = 196608 - cSECURITY_CONTEXT_TRACKING* = 262144 - cSECURITY_EFFECTIVE_ONLY* = 524288 - cSECURITY_SQOS_PRESENT* = 1048576 - # CreateFileMapping, VirtualAlloc, VirtualFree, VirtualProtect - SEC_COMMIT* = 134217728 - SEC_IMAGE* = 16777216 - SEC_NOCACHE* = 268435456 - SEC_RESERVE* = 67108864 - PAGE_READONLY* = 2 - PAGE_READWRITE* = 4 - PAGE_WRITECOPY* = 8 - PAGE_EXECUTE* = 16 - PAGE_EXECUTE_READ* = 32 - PAGE_EXECUTE_READWRITE* = 64 - PAGE_EXECUTE_WRITECOPY* = 128 - PAGE_GUARD* = 256 - PAGE_NOACCESS* = 1 - PAGE_NOCACHE* = 512 - MEM_COMMIT* = 4096 - MEM_FREE* = 65536 - MEM_RESERVE* = 8192 - MEM_IMAGE* = 16777216 - MEM_MAPPED* = 262144 - MEM_PRIVATE* = 131072 - MEM_DECOMMIT* = 16384 - MEM_RELEASE* = 32768 - MEM_TOP_DOWN* = 1048576 - EXCEPTION_GUARD_PAGE* = 0x80000001 - SECTION_EXTEND_SIZE* = 0x00000010 - SECTION_MAP_READ* = 0x00000004 - SECTION_MAP_WRITE* = 0x00000002 - SECTION_QUERY* = 0x00000001 - SECTION_ALL_ACCESS* = 0x000F001F - # CreateFont - FW_DONTCARE* = 0 - FW_THIN* = 100 - FW_EXTRALIGHT* = 200 - FW_LIGHT* = 300 - FW_NORMAL* = 400 - FW_REGULAR* = FW_NORMAL - FW_MEDIUM* = 500 - FW_SEMIBOLD* = 600 - FW_BOLD* = 700 - FW_EXTRABOLD* = 800 - FW_HEAVY* = 900 - ANSI_CHARSET* = 0 - DEFAULT_CHARSET* = 1 - SYMBOL_CHARSET* = 2 - SHIFTJIS_CHARSET* = 128 - HANGEUL_CHARSET* = 129 - GB2312_CHARSET* = 134 - CHINESEBIG5_CHARSET* = 136 - GREEK_CHARSET* = 161 - TURKISH_CHARSET* = 162 - HEBREW_CHARSET* = 177 - ARABIC_CHARSET* = 178 - BALTIC_CHARSET* = 186 - RUSSIAN_CHARSET* = 204 - THAI_CHARSET* = 222 - EASTEUROPE_CHARSET* = 238 - OEM_CHARSET* = 255 - OUT_DEFAULT_PRECIS* = 0 - OUT_STRING_PRECIS* = 1 - OUT_CHARACTER_PRECIS* = 2 - OUT_STROKE_PRECIS* = 3 - OUT_TT_PRECIS* = 4 - OUT_DEVICE_PRECIS* = 5 - OUT_RASTER_PRECIS* = 6 - OUT_TT_ONLY_PRECIS* = 7 - OUT_OUTLINE_PRECIS* = 8 - CLIP_DEFAULT_PRECIS* = 0 - CLIP_CHARACTER_PRECIS* = 1 - CLIP_STROKE_PRECIS* = 2 - CLIP_MASK* = 15 - CLIP_LH_ANGLES* = 16 - CLIP_TT_ALWAYS* = 32 - CLIP_EMBEDDED* = 128 - DEFAULT_QUALITY* = 0 - DRAFT_QUALITY* = 1 - PROOF_QUALITY* = 2 - NONANTIALIASED_QUALITY* = 3 - ANTIALIASED_QUALITY* = 4 - DEFAULT_PITCH* = 0 - FIXED_PITCH* = 1 - VARIABLE_PITCH* = 2 - MONO_FONT* = 8 - FF_DECORATIVE* = 80 - FF_DONTCARE* = 0 - FF_MODERN* = 48 - FF_ROMAN* = 16 - FF_SCRIPT* = 64 - FF_SWISS* = 32 - # CreateHatchBrush - HS_BDIAGONAL* = 3 - HS_CROSS* = 4 - HS_DIAGCROSS* = 5 - HS_FDIAGONAL* = 2 - HS_HORIZONTAL* = 0 - HS_VERTICAL* = 1 - # CreateIconFromResourceEx - LR_DEFAULTCOLOR* = 0 - LR_LOADREALSIZE* = 128 - # CreateMailslot, GetMailslotInfo - MAILSLOT_WAIT_FOREVER* = 0xFFFFFFFF - MAILSLOT_NO_MESSAGE* = 0xFFFFFFFF - # CreateMappedBitmap - CMB_MASKED* = 2 - # CreateNamedPipe - PIPE_ACCESS_DUPLEX* = 3 - PIPE_ACCESS_INBOUND* = 1 - PIPE_ACCESS_OUTBOUND* = 2 - WRITE_DAC* = 0x00040000 - WRITE_OWNER* = 0x00080000 - ACCESS_SYSTEM_SECURITY* = 0x01000000 - PIPE_TYPE_BYTE* = 0 - PIPE_TYPE_MESSAGE* = 4 - PIPE_READMODE_BYTE* = 0 - PIPE_READMODE_MESSAGE* = 2 - PIPE_WAIT* = 0 - PIPE_NOWAIT* = 1 - # CreatePen, ExtCreatePen - PS_GEOMETRIC* = 65536 - PS_COSMETIC* = 0 - PS_ALTERNATE* = 8 - PS_SOLID* = 0 - PS_DASH* = 1 - PS_DOT* = 2 - PS_DASHDOT* = 3 - PS_DASHDOTDOT* = 4 - PS_NULL* = 5 - PS_USERSTYLE* = 7 - PS_INSIDEFRAME* = 6 - PS_ENDCAP_ROUND* = 0 - PS_ENDCAP_SQUARE* = 256 - PS_ENDCAP_FLAT* = 512 - PS_JOIN_BEVEL* = 4096 - PS_JOIN_MITER* = 8192 - PS_JOIN_ROUND* = 0 - PS_STYLE_MASK* = 15 - PS_ENDCAP_MASK* = 3840 - PS_TYPE_MASK* = 983040 - # CreatePolygonRgn - ALTERNATE* = 1 - WINDING* = 2 - # CreateProcess - CREATE_DEFAULT_ERROR_MODE* = 67108864 - CREATE_NEW_CONSOLE* = 16 - CREATE_NEW_PROCESS_GROUP* = 512 - CREATE_SEPARATE_WOW_VDM* = 2048 - CREATE_SUSPENDED* = 4 - CREATE_UNICODE_ENVIRONMENT* = 1024 - DEBUG_PROCESS* = 1 - DEBUG_ONLY_THIS_PROCESS* = 2 - DETACHED_PROCESS* = 8 - HIGH_PRIORITY_CLASS* = 128 - IDLE_PRIORITY_CLASS* = 64 - NORMAL_PRIORITY_CLASS* = 32 - REALTIME_PRIORITY_CLASS* = 256 - # CreateService - SERVICE_ALL_ACCESS* = 0x000F01FF - SERVICE_CHANGE_CONFIG* = 2 - SERVICE_ENUMERATE_DEPENDENTS* = 8 - SERVICE_INTERROGATE* = 128 - SERVICE_PAUSE_CONTINUE* = 64 - SERVICE_QUERY_CONFIG* = 1 - SERVICE_QUERY_STATUS* = 4 - SERVICE_START* = 16 - SERVICE_STOP* = 32 - SERVICE_USER_DEFINED_CONTROL* = 256 - SERVICE_DELETE* = 0x00010000 - SERVICE_READ_CONTROL* = 0x00020000 - SERVICE_GENERIC_EXECUTE* = 0x20000000 - SERVICE_ERROR_IGNORE* = 0 - SERVICE_ERROR_NORMAL* = 1 - SERVICE_ERROR_SEVERE* = 2 - SERVICE_ERROR_CRITICAL* = 3 - # CreateTapePartition, WriteTapemark - TAPE_FIXED_PARTITIONS* = 0 - TAPE_INITIATOR_PARTITIONS* = 0x00000002 - TAPE_SELECT_PARTITIONS* = 0x00000001 - TAPE_FILEMARKS* = 0x00000001 - TAPE_LONG_FILEMARKS* = 0x00000003 - TAPE_SETMARKS* = 0 - TAPE_SHORT_FILEMARKS* = 0x00000002 - # CreateWindow - CW_USEDEFAULT* = int32(0x80000000) - WS_BORDER* = 0x00800000 - WS_CAPTION* = 0x00C00000 - WS_CHILD* = 0x40000000 - WS_CHILDWINDOW* = 0x40000000 - WS_CLIPCHILDREN* = 0x02000000 - WS_CLIPSIBLINGS* = 0x04000000 - WS_DISABLED* = 0x08000000 - WS_DLGFRAME* = 0x00400000 - WS_GROUP* = 0x00020000 - WS_HSCROLL* = 0x00100000 - WS_ICONIC* = 0x20000000 - WS_MAXIMIZE* = 0x01000000 - WS_MAXIMIZEBOX* = 0x00010000 - WS_MINIMIZE* = 0x20000000 - WS_MINIMIZEBOX* = 0x00020000 - WS_OVERLAPPED* = 0 - WS_OVERLAPPEDWINDOW* = 0x00CF0000 - WS_POPUP* = LONG(0x80000000) - WS_POPUPWINDOW* = LONG(0x80880000) - WS_SIZEBOX* = 0x00040000 - WS_SYSMENU* = 0x00080000 - WS_TABSTOP* = 0x00010000 - WS_THICKFRAME* = 0x00040000 - - WS_TILED* = 0 - WS_TILEDWINDOW* = 0x00CF0000 - WS_VISIBLE* = 0x10000000 - WS_VSCROLL* = 0x00200000 - MDIS_ALLCHILDSTYLES* = 0x00000001 - BS_3STATE* = 0x00000005 - BS_AUTO3STATE* = 0x00000006 - BS_AUTOCHECKBOX* = 0x00000003 - BS_AUTORADIOBUTTON* = 0x00000009 - BS_BITMAP* = 0x00000080 - BS_BOTTOM* = 0x00000800 - BS_CENTER* = 0x00000300 - BS_CHECKBOX* = 0x00000002 - BS_DEFPUSHBUTTON* = 0x00000001 - BS_GROUPBOX* = 0x00000007 - BS_ICON* = 0x00000040 - BS_LEFT* = 0x00000100 - BS_LEFTTEXT* = 0x00000020 - BS_MULTILINE* = 0x00002000 - BS_NOTIFY* = 0x00004000 - BS_OWNERDRAW* = 0x0000000B - BS_PUSHBUTTON* = 0 - BS_PUSHLIKE* = 0x00001000 - BS_RADIOBUTTON* = 0x00000004 - BS_RIGHT* = 0x00000200 - BS_RIGHTBUTTON* = 0x00000020 - BS_TEXT* = 0 - BS_TOP* = 0x00000400 - BS_USERBUTTON* = 0x00000008 - BS_VCENTER* = 0x00000C00 - BS_FLAT* = 0x00008000 - CBS_AUTOHSCROLL* = 0x00000040 - CBS_DISABLENOSCROLL* = 0x00000800 - CBS_DROPDOWN* = 0x00000002 - CBS_DROPDOWNLIST* = 0x00000003 - CBS_HASSTRINGS* = 0x00000200 - CBS_LOWERCASE* = 0x00004000 - CBS_NOINTEGRALHEIGHT* = 0x00000400 - CBS_OEMCONVERT* = 0x00000080 - CBS_OWNERDRAWFIXED* = 0x00000010 - CBS_OWNERDRAWVARIABLE* = 0x00000020 - CBS_SIMPLE* = 0x00000001 - CBS_SORT* = 0x00000100 - CBS_UPPERCASE* = 0x00002000 - ES_AUTOHSCROLL* = 0x00000080 - ES_AUTOVSCROLL* = 0x00000040 - ES_CENTER* = 0x00000001 - ES_LEFT* = 0 - ES_LOWERCASE* = 0x00000010 - ES_MULTILINE* = 0x00000004 - ES_NOHIDESEL* = 0x00000100 - ES_NUMBER* = 0x00002000 - ES_OEMCONVERT* = 0x00000400 - ES_PASSWORD* = 0x00000020 - ES_READONLY* = 0x00000800 - ES_RIGHT* = 0x00000002 - ES_UPPERCASE* = 0x00000008 - ES_WANTRETURN* = 0x00001000 - LBS_DISABLENOSCROLL* = 0x00001000 - LBS_EXTENDEDSEL* = 0x00000800 - LBS_HASSTRINGS* = 0x00000040 - LBS_MULTICOLUMN* = 0x00000200 - LBS_MULTIPLESEL* = 0x00000008 - LBS_NODATA* = 0x00002000 - LBS_NOINTEGRALHEIGHT* = 0x00000100 - LBS_NOREDRAW* = 0x00000004 - LBS_NOSEL* = 0x00004000 - LBS_NOTIFY* = 0x00000001 - LBS_OWNERDRAWFIXED* = 0x00000010 - LBS_OWNERDRAWVARIABLE* = 0x00000020 - LBS_SORT* = 0x00000002 - LBS_STANDARD* = 0x00A00003 - LBS_USETABSTOPS* = 0x00000080 - LBS_WANTKEYBOARDINPUT* = 0x00000400 - SBS_BOTTOMALIGN* = 0x00000004 - SBS_HORZ* = 0 - SBS_LEFTALIGN* = 0x00000002 - SBS_RIGHTALIGN* = 0x00000004 - SBS_SIZEBOX* = 0x00000008 - SBS_SIZEBOXBOTTOMRIGHTALIGN* = 0x00000004 - SBS_SIZEBOXTOPLEFTALIGN* = 0x00000002 - SBS_SIZEGRIP* = 0x00000010 - SBS_TOPALIGN* = 0x00000002 - SBS_VERT* = 0x00000001 - SS_BITMAP* = 0x0000000E - SS_BLACKFRAME* = 0x00000007 - SS_BLACKRECT* = 0x00000004 - SS_CENTER* = 0x00000001 - SS_CENTERIMAGE* = 0x00000200 - SS_ENHMETAFILE* = 0x0000000F - SS_ETCHEDFRAME* = 0x00000012 - SS_ETCHEDHORZ* = 0x00000010 - SS_ETCHEDVERT* = 0x00000011 - SS_GRAYFRAME* = 0x00000008 - SS_GRAYRECT* = 0x00000005 - SS_ICON* = 0x00000003 - SS_LEFT* = 0 - SS_LEFTNOWORDWRAP* = 0x0000000C - SS_NOPREFIX* = 0x00000080 - SS_NOTIFY* = 0x00000100 - SS_OWNERDRAW* = 0x0000000D - SS_REALSIZEIMAGE* = 0x00000800 - SS_RIGHT* = 0x00000002 - SS_RIGHTJUST* = 0x00000400 - SS_SIMPLE* = 0x0000000B - SS_SUNKEN* = 0x00001000 - SS_USERITEM* = 0x0000000A - SS_WHITEFRAME* = 0x00000009 - SS_WHITERECT* = 0x00000006 - DS_3DLOOK* = 0x00000004 - DS_ABSALIGN* = 0x00000001 - DS_CENTER* = 0x00000800 - DS_CENTERMOUSE* = 0x00001000 - DS_CONTEXTHELP* = 0x00002000 - DS_CONTROL* = 0x00000400 - DS_FIXEDSYS* = 0x00000008 - DS_LOCALEDIT* = 0x00000020 - DS_MODALFRAME* = 0x00000080 - DS_NOFAILCREATE* = 0x00000010 - DS_NOIDLEMSG* = 0x00000100 - DS_SETFONT* = 0x00000040 - DS_SETFOREGROUND* = 0x00000200 - DS_SYSMODAL* = 0x00000002 - # CreateWindowEx - WS_EX_ACCEPTFILES* = 0x00000010 - WS_EX_APPWINDOW* = 0x00040000 - WS_EX_CLIENTEDGE* = 0x00000200 - WS_EX_CONTEXTHELP* = 0x00000400 - WS_EX_CONTROLPARENT* = 0x00010000 - WS_EX_DLGMODALFRAME* = 0x00000001 - WS_EX_LEFT* = 0 - WS_EX_LEFTSCROLLBAR* = 0x00004000 - WS_EX_LTRREADING* = 0 - WS_EX_MDICHILD* = 0x00000040 - WS_EX_NOPARENTNOTIFY* = 0x00000004 - WS_EX_OVERLAPPEDWINDOW* = 0x00000300 - WS_EX_PALETTEWINDOW* = 0x00000188 - WS_EX_RIGHT* = 0x00001000 - WS_EX_RIGHTSCROLLBAR* = 0 - WS_EX_RTLREADING* = 0x00002000 - WS_EX_STATICEDGE* = 0x00020000 - WS_EX_TOOLWINDOW* = 0x00000080 - WS_EX_TOPMOST* = 0x00000008 - WS_EX_TRANSPARENT* = 0x00000020 - WS_EX_WINDOWEDGE* = 0x00000100 - # CreateWindowStation - WINSTA_ACCESSCLIPBOARD* = 0x00000004 - WINSTA_ACCESSGLOBALATOMS* = 0x00000020 - WINSTA_CREATEDESKTOP* = 0x00000008 - WINSTA_ENUMDESKTOPS* = 0x00000001 - WINSTA_ENUMERATE* = 0x00000100 - WINSTA_EXITWINDOWS* = 0x00000040 - WINSTA_READATTRIBUTES* = 0x00000002 - WINSTA_READSCREEN* = 0x00000200 - WINSTA_WRITEATTRIBUTES* = 0x00000010 - # DdeCallback - # DdeClientTransaction - # DdeEnableCallback - # DdeGetLastError - # DdeInitialize - # DdeNameService - # DebugProc - WH_CALLWNDPROC* = 4 - WH_CALLWNDPROCRET* = 12 - WH_CBT* = 5 - WH_DEBUG* = 9 - WH_GETMESSAGE* = 3 - WH_JOURNALPLAYBACK* = 1 - WH_JOURNALRECORD* = 0 - WH_KEYBOARD* = 2 - WH_MOUSE* = 7 - WH_MSGFILTER* = -1 - WH_SHELL* = 10 - WH_SYSMSGFILTER* = 6 - WH_FOREGROUNDIDLE* = 11 - # DefineDosDevice - DDD_RAW_TARGET_PATH* = 1 - DDD_REMOVE_DEFINITION* = 2 - DDD_EXACT_MATCH_ON_REMOVE* = 4 - # DeviceCapbilities - DCTT_BITMAP* = 0x00000001 - DCTT_DOWNLOAD* = 0x00000002 - DCTT_SUBDEV* = 0x00000004 - # DlgDirList - DDL_ARCHIVE* = 32 - DDL_DIRECTORY* = 16 - DDL_DRIVES* = 16384 - DDL_EXCLUSIVE* = 32768 - DDL_HIDDEN* = 2 - DDL_READONLY* = 1 - DDL_READWRITE* = 0 - DDL_SYSTEM* = 4 - DDL_POSTMSGS* = 8192 - # DllEntryPoint - DLL_PROCESS_ATTACH* = 1 - DLL_THREAD_ATTACH* = 2 - DLL_PROCESS_DETACH* = 0 - DLL_THREAD_DETACH* = 3 - # DrawAnimatedRects - IDANI_OPEN* = 1 - IDANI_CLOSE* = 2 - # DrawCaption - DC_ACTIVE* = 1 - DC_SMALLCAP* = 2 - # DrawEdge - BDR_RAISEDINNER* = 4 - BDR_SUNKENINNER* = 8 - BDR_RAISEDOUTER* = 1 - BDR_SUNKENOUTER* = 2 - BDR_OUTER* = BDR_RAISEDOUTER or BDR_SUNKENOUTER - BDR_INNER* = BDR_RAISEDINNER or BDR_SUNKENINNER - BDR_RAISED* = BDR_RAISEDOUTER or BDR_RAISEDINNER - BDR_SUNKEN* = BDR_SUNKENOUTER or BDR_SUNKENINNER - EDGE_BUMP* = 9 - EDGE_ETCHED* = 6 - EDGE_RAISED* = 5 - EDGE_SUNKEN* = 10 - BF_ADJUST* = 8192 - BF_BOTTOM* = 8 - BF_BOTTOMLEFT* = 9 - BF_BOTTOMRIGHT* = 12 - BF_DIAGONAL* = 16 - BF_DIAGONAL_ENDBOTTOMLEFT* = 25 - BF_DIAGONAL_ENDBOTTOMRIGHT* = 28 - BF_DIAGONAL_ENDTOPLEFT* = 19 - BF_DIAGONAL_ENDTOPRIGHT* = 22 - BF_FLAT* = 16384 - BF_LEFT* = 1 - BF_MIDDLE* = 2048 - BF_MONO* = 32768 - BF_RECT* = 15 - BF_RIGHT* = 4 - BF_SOFT* = 4096 - BF_TOP* = 2 - BF_TOPLEFT* = 3 - BF_TOPRIGHT* = 6 - # DrawFrameControl - DFC_BUTTON* = 4 - DFC_CAPTION* = 1 - DFC_MENU* = 2 - DFC_SCROLL* = 3 - DFCS_BUTTON3STATE* = 8 - DFCS_BUTTONCHECK* = 0 - DFCS_BUTTONPUSH* = 16 - DFCS_BUTTONRADIO* = 4 - DFCS_BUTTONRADIOIMAGE* = 1 - DFCS_BUTTONRADIOMASK* = 2 - DFCS_CAPTIONCLOSE* = 0 - DFCS_CAPTIONHELP* = 4 - DFCS_CAPTIONMAX* = 2 - DFCS_CAPTIONMIN* = 1 - DFCS_CAPTIONRESTORE* = 3 - DFCS_MENUARROW* = 0 - DFCS_MENUBULLET* = 2 - DFCS_MENUCHECK* = 1 - DFCS_SCROLLCOMBOBOX* = 5 - DFCS_SCROLLDOWN* = 1 - DFCS_SCROLLLEFT* = 2 - DFCS_SCROLLRIGHT* = 3 - DFCS_SCROLLSIZEGRIP* = 8 - DFCS_SCROLLUP* = 0 - DFCS_ADJUSTRECT* = 8192 - DFCS_CHECKED* = 1024 - DFCS_FLAT* = 16384 - DFCS_INACTIVE* = 256 - DFCS_MONO* = 32768 - DFCS_PUSHED* = 512 - # DrawIconEx - DI_COMPAT* = 4 - DI_DEFAULTSIZE* = 8 - DI_IMAGE* = 2 - DI_MASK* = 1 - DI_NORMAL* = 3 - # DrawState - DST_BITMAP* = 4 - DST_COMPLEX* = 0 - DST_ICON* = 3 - DST_PREFIXTEXT* = 2 - DST_TEXT* = 1 - DSS_NORMAL* = 0 - DSS_UNION* = 16 - DSS_DISABLED* = 32 - DSS_MONO* = 128 - # DrawStatusText - SBT_NOBORDERS* = 256 - SBT_OWNERDRAW* = 4096 - SBT_POPOUT* = 512 - SBT_RTLREADING* = 1024 - # DrawText, DrawTextEx - DT_BOTTOM* = 8 - DT_CALCRECT* = 1024 - DT_CENTER* = 1 - DT_EDITCONTROL* = 8192 - DT_END_ELLIPSIS* = 32768 - DT_PATH_ELLIPSIS* = 16384 - DT_EXPANDTABS* = 64 - DT_EXTERNALLEADING* = 512 - DT_LEFT* = 0 - DT_MODIFYSTRING* = 65536 - DT_NOCLIP* = 256 - DT_NOPREFIX* = 2048 - DT_RIGHT* = 2 - DT_RTLREADING* = 131072 - DT_SINGLELINE* = 32 - DT_TABSTOP* = 128 - DT_TOP* = 0 - DT_VCENTER* = 4 - DT_WORDBREAK* = 16 - DT_INTERNAL* = 4096 - DT_WORD_ELLIPSIS* = 0x00040000 - DT_HIDEPREFIX* = 0x00100000 - DT_PREFIXONLY* = 0x00200000 - # DuplicateHandle, MapViewOfFile - DUPLICATE_CLOSE_SOURCE* = 1 - DUPLICATE_SAME_ACCESS* = 2 - FILE_MAP_ALL_ACCESS* = 0x000F001F - FILE_MAP_READ* = 4 - FILE_MAP_WRITE* = 2 - FILE_MAP_COPY* = 1 - MUTEX_ALL_ACCESS* = 0x001F0001 - MUTEX_MODIFY_STATE* = 1 - SYNCHRONIZE* = 0x00100000 - SEMAPHORE_ALL_ACCESS* = 0x001F0003 - SEMAPHORE_MODIFY_STATE* = 2 - EVENT_ALL_ACCESS* = 0x001F0003 - EVENT_MODIFY_STATE* = 2 - KEY_ALL_ACCESS* = 0x000F003F - KEY_CREATE_LINK* = 32 - KEY_CREATE_SUB_KEY* = 4 - KEY_ENUMERATE_SUB_KEYS* = 8 - KEY_EXECUTE* = 0x00020019 - KEY_NOTIFY* = 16 - KEY_QUERY_VALUE* = 1 - KEY_READ* = 0x00020019 - KEY_SET_VALUE* = 2 - KEY_WRITE* = 0x00020006 - PROCESS_ALL_ACCESS* = 0x001F0FFF - PROCESS_CREATE_PROCESS* = 128 - PROCESS_CREATE_THREAD* = 2 - PROCESS_DUP_HANDLE* = 64 - PROCESS_QUERY_INFORMATION* = 1024 - PROCESS_SET_INFORMATION* = 512 - PROCESS_TERMINATE* = 1 - PROCESS_VM_OPERATION* = 8 - PROCESS_VM_READ* = 16 - PROCESS_VM_WRITE* = 32 - THREAD_ALL_ACCESS* = 0x001F03FF - THREAD_DIRECT_IMPERSONATION* = 512 - THREAD_GET_CONTEXT* = 8 - THREAD_IMPERSONATE* = 256 - THREAD_QUERY_INFORMATION* = 64 - THREAD_SET_CONTEXT* = 16 - THREAD_SET_INFORMATION* = 32 - THREAD_SET_THREAD_TOKEN* = 128 - THREAD_SUSPEND_RESUME* = 2 - THREAD_TERMINATE* = 1 - # EditWordBreakProc - WB_ISDELIMITER* = 2 - WB_LEFT* = 0 - WB_RIGHT* = 1 - # EnableScrollBar - SB_BOTH* = 3 - SB_CTL* = 2 - SB_HORZ* = 0 - SB_VERT* = 1 - ESB_DISABLE_BOTH* = 3 - ESB_DISABLE_DOWN* = 2 - ESB_DISABLE_LEFT* = 1 - ESB_DISABLE_LTUP* = 1 - ESB_DISABLE_RIGHT* = 2 - ESB_DISABLE_RTDN* = 2 - ESB_DISABLE_UP* = 1 - ESB_ENABLE_BOTH* = 0 - # Scroll Bar notifications - SB_LINEUP* = 0 - SB_LINEDOWN* = 1 - SB_LINELEFT* = 0 - SB_LINERIGHT* = 1 - SB_PAGEUP* = 2 - SB_PAGEDOWN* = 3 - SB_PAGELEFT* = 2 - SB_PAGERIGHT* = 3 - SB_THUMBPOSITION* = 4 - SB_THUMBTRACK* = 5 - SB_ENDSCROLL* = 8 - SB_LEFT* = 6 - SB_RIGHT* = 7 - SB_BOTTOM* = 7 - SB_TOP* = 6 - # EnumCalendarInfo - ENUM_ALL_CALENDARS* = -1 - # EnumDateFormats - # GetDateFormat - DATE_SHORTDATE* = 1 - DATE_LONGDATE* = 2 - DATE_USE_ALT_CALENDAR* = 4 - # EnumDependentServices - SERVICE_ACTIVE* = 1 - SERVICE_INACTIVE* = 2 - # EnumFontFamExProc - DEVICE_FONTTYPE* = 2 - RASTER_FONTTYPE* = 1 - TRUETYPE_FONTTYPE* = 4 - # EnumObjects, GetCurrentObject, GetObjectType - OBJ_BRUSH* = 2 - OBJ_PEN* = 1 - OBJ_PAL* = 5 - OBJ_FONT* = 6 - OBJ_BITMAP* = 7 - OBJ_EXTPEN* = 11 - OBJ_REGION* = 8 - OBJ_DC* = 3 - OBJ_MEMDC* = 10 - OBJ_METAFILE* = 9 - OBJ_METADC* = 4 - OBJ_ENHMETAFILE* = 13 - OBJ_ENHMETADC* = 12 - - # - # Predefined Resource Types - # -const - RT_CURSOR* = cast[MAKEINTRESOURCE](1) - RT_BITMAP* = cast[MAKEINTRESOURCE](2) - RT_ICON* = cast[MAKEINTRESOURCE](3) - RT_MENU* = cast[MAKEINTRESOURCE](4) - RT_DIALOG* = cast[MAKEINTRESOURCE](5) - RT_STRING* = cast[MAKEINTRESOURCE](6) - RT_FONTDIR* = cast[MAKEINTRESOURCE](7) - RT_FONT* = cast[MAKEINTRESOURCE](8) - RT_ACCELERATOR* = cast[MAKEINTRESOURCE](9) - RT_RCDATA* = cast[MAKEINTRESOURCE](10) - RT_MESSAGETABLE* = cast[MAKEINTRESOURCE](11) - DIFFERENCE* = 11 - RT_GROUP_CURSOR* = cast[MAKEINTRESOURCE](12) - RT_GROUP_ICON* = cast[MAKEINTRESOURCE](14) - RT_VERSION* = cast[MAKEINTRESOURCE](16) - RT_DLGINCLUDE* = cast[MAKEINTRESOURCE](17) - RT_PLUGPLAY* = cast[MAKEINTRESOURCE](19) - RT_VXD* = cast[MAKEINTRESOURCE](20) - RT_ANICURSOR* = cast[MAKEINTRESOURCE](21) - RT_ANIICON* = cast[MAKEINTRESOURCE](22) - RT_HTML* = cast[MAKEINTRESOURCE](23) - RT_MANIFEST* = cast[MAKEINTRESOURCE](24) - -const - # EnumServicesStatus - SERVICE_WIN32* = 48 - SERVICE_DRIVER* = 11 - # EnumSystemCodePages - CP_INSTALLED* = 1 - CP_SUPPORTED* = 2 - # EnumSystemLocales - LCID_INSTALLED* = 1 - LCID_SUPPORTED* = 2 - # EraseTape - TAPE_ERASE_LONG* = 0x00000001 - TAPE_ERASE_SHORT* = 0 - # Escape - SP_ERROR* = -1 - SP_OUTOFDISK* = -4 - SP_OUTOFMEMORY* = -5 - SP_USERABORT* = -3 - PHYSICALWIDTH* = 110 - PHYSICALHEIGHT* = 111 - PHYSICALOFFSETX* = 112 - PHYSICALOFFSETY* = 113 - SCALINGFACTORX* = 114 - SCALINGFACTORY* = 115 - QUERYESCSUPPORT* = 8 - #ABORTDOC = 2; conflicts with AbortDoc function - cABORTDOC* = 2 - #ENDDOC = 11; conflicts with AbortDoc function - cENDDOC* = 11 - GETPHYSPAGESIZE* = 12 - GETPRINTINGOFFSET* = 13 - GETSCALINGFACTOR* = 14 - NEWFRAME* = 1 - NEXTBAND* = 3 - PASSTHROUGH* = 19 - #SETABORTPROC = 9; conflicts with AbortDoc function - cSETABORTPROC* = 9 - #STARTDOC = 10; conflicts with AbortDoc function - cSTARTDOC* = 10 - # EscapeCommFunction - CLRDTR* = 6 - CLRRTS* = 4 - SETDTR* = 5 - SETRTS* = 3 - SETXOFF* = 1 - SETXON* = 2 - SETBREAK* = 8 - CLRBREAK* = 9 - # ExitWindowsEx - EWX_FORCE* = 4 - EWX_LOGOFF* = 0 - EWX_POWEROFF* = 8 - EWX_REBOOT* = 2 - EWX_SHUTDOWN* = 1 - # ExtFloodFill - FLOODFILLBORDER* = 0 - FLOODFILLSURFACE* = 1 - # ExtTextOut - ETO_CLIPPED* = 4 - ETO_GLYPH_INDEX* = 16 - ETO_OPAQUE* = 2 - ETO_RTLREADING* = 128 - # FillConsoleOutputAttribute - FOREGROUND_BLUE* = 1 - FOREGROUND_GREEN* = 2 - FOREGROUND_RED* = 4 - FOREGROUND_INTENSITY* = 8 - BACKGROUND_BLUE* = 16 - BACKGROUND_GREEN* = 32 - BACKGROUND_RED* = 64 - BACKGROUND_INTENSITY* = 128 - # FindFirstChangeNotification - FILE_NOTIFY_CHANGE_FILE_NAME* = 1 - FILE_NOTIFY_CHANGE_DIR_NAME* = 2 - FILE_NOTIFY_CHANGE_ATTRIBUTES* = 4 - FILE_NOTIFY_CHANGE_SIZE* = 8 - FILE_NOTIFY_CHANGE_LAST_WRITE* = 16 - FILE_NOTIFY_CHANGE_SECURITY* = 256 - # FindFirstPrinterChangeNotification - # FindNextPrinterNotification - # FMExtensionProc - # FoldString - MAP_FOLDCZONE* = 16 - MAP_FOLDDIGITS* = 128 - MAP_PRECOMPOSED* = 32 - MAP_COMPOSITE* = 64 - # ForegroundIdleProc - HC_ACTION* = 0 - # FormatMessage - FORMAT_MESSAGE_ALLOCATE_BUFFER* = 256 - FORMAT_MESSAGE_IGNORE_INSERTS* = 512 - FORMAT_MESSAGE_FROM_STRING* = 1024 - FORMAT_MESSAGE_FROM_HMODULE* = 2048 - FORMAT_MESSAGE_FROM_SYSTEM* = 4096 - FORMAT_MESSAGE_ARGUMENT_ARRAY* = 8192 - FORMAT_MESSAGE_MAX_WIDTH_MASK* = 255 - # GdiComment - GDICOMMENT_WINDOWS_METAFILE* = -2147483647 - GDICOMMENT_BEGINGROUP* = 2 - GDICOMMENT_ENDGROUP* = 3 - GDICOMMENT_MULTIFORMATS* = 1073741828 - GDICOMMENT_IDENTIFIER* = 1128875079 - # GenerateConsoleCtrlEvent, HandlerRoutine - CTRL_C_EVENT* = 0 - CTRL_BREAK_EVENT* = 1 - CTRL_CLOSE_EVENT* = 2 - CTRL_LOGOFF_EVENT* = 5 - CTRL_SHUTDOWN_EVENT* = 6 - # GetAddressByName - # GetArcDirection - AD_COUNTERCLOCKWISE* = 1 - AD_CLOCKWISE* = 2 - # GetBinaryTypes - SCS_32BIT_BINARY* = 0 - SCS_DOS_BINARY* = 1 - SCS_OS216_BINARY* = 5 - SCS_PIF_BINARY* = 3 - SCS_POSIX_BINARY* = 4 - SCS_WOW_BINARY* = 2 - # GetBoundsRect, SetBoundsRect - DCB_DISABLE* = 8 - DCB_ENABLE* = 4 - DCB_RESET* = 1 - DCB_SET* = 3 - DCB_ACCUMULATE* = 2 - # GetCharacterPlacement, GetFontLanguageInfo - GCP_DBCS* = 1 - GCP_ERROR* = 0x00008000 - GCP_CLASSIN* = 0x00080000 - GCP_DIACRITIC* = 256 - GCP_DISPLAYZWG* = 0x00400000 - GCP_GLYPHSHAPE* = 16 - GCP_JUSTIFY* = 0x00010000 - GCP_JUSTIFYIN* = 0x00200000 - GCP_KASHIDA* = 1024 - GCP_LIGATE* = 32 - GCP_MAXEXTENT* = 0x00100000 - GCP_NEUTRALOVERRIDE* = 0x02000000 - GCP_NUMERICOVERRIDE* = 0x01000000 - GCP_NUMERICSLATIN* = 0x04000000 - GCP_NUMERICSLOCAL* = 0x08000000 - GCP_REORDER* = 2 - GCP_SYMSWAPOFF* = 0x00800000 - GCP_USEKERNING* = 8 - FLI_GLYPHS* = 0x00040000 - FLI_MASK* = 0x0000103B - # GetClassLong, GetClassWord - GCW_ATOM* = -32 - GCL_CBCLSEXTRA* = -20 - GCL_CBWNDEXTRA* = -18 - GCL_HBRBACKGROUND* = -10 - GCL_HCURSOR* = -12 - GCL_HICON* = -14 - GCL_HICONSM* = -34 - GCL_HMODULE* = -16 - GCL_MENUNAME* = -8 - GCL_STYLE* = -26 - GCL_WNDPROC* = -24 - # GetClipboardFormat, SetClipboardData - CF_BITMAP* = 2 - CF_DIB* = 8 - CF_PALETTE* = 9 - CF_ENHMETAFILE* = 14 - CF_METAFILEPICT* = 3 - CF_OEMTEXT* = 7 - CF_TEXT* = 1 - CF_UNICODETEXT* = 13 - CF_DIF* = 5 - CF_DSPBITMAP* = 130 - CF_DSPENHMETAFILE* = 142 - CF_DSPMETAFILEPICT* = 131 - CF_DSPTEXT* = 129 - CF_GDIOBJFIRST* = 768 - CF_GDIOBJLAST* = 1023 - CF_HDROP* = 15 - CF_LOCALE* = 16 - CF_OWNERDISPLAY* = 128 - CF_PENDATA* = 10 - CF_PRIVATEFIRST* = 512 - CF_PRIVATELAST* = 767 - CF_RIFF* = 11 - CF_SYLK* = 4 - CF_WAVE* = 12 - CF_TIFF* = 6 - # GetCommMask - EV_BREAK* = 64 - EV_CTS* = 8 - EV_DSR* = 16 - EV_ERR* = 128 - EV_EVENT1* = 2048 - EV_EVENT2* = 4096 - EV_PERR* = 512 - EV_RING* = 256 - EV_RLSD* = 32 - EV_RX80FULL* = 1024 - EV_RXCHAR* = 1 - EV_RXFLAG* = 2 - EV_TXEMPTY* = 4 - # GetCommModemStatus - MS_CTS_ON* = 0x00000010 - MS_DSR_ON* = 0x00000020 - MS_RING_ON* = 0x00000040 - MS_RLSD_ON* = 0x00000080 - # GetComputerName - MAX_COMPUTERNAME_LENGTH* = 15 - # GetConsoleMode - ENABLE_LINE_INPUT* = 2 - ENABLE_ECHO_INPUT* = 4 - ENABLE_PROCESSED_INPUT* = 1 - ENABLE_WINDOW_INPUT* = 8 - ENABLE_MOUSE_INPUT* = 16 - ENABLE_PROCESSED_OUTPUT* = 1 - ENABLE_WRAP_AT_EOL_OUTPUT* = 2 - # GetCPInfo - CP_ACP* = 0 - CP_MACCP* = 2 - CP_OEMCP* = 1 - # GetDCEx - DCX_WINDOW* = 0x00000001 - DCX_CACHE* = 0x00000002 - DCX_PARENTCLIP* = 0x00000020 - DCX_CLIPSIBLINGS* = 0x00000010 - DCX_CLIPCHILDREN* = 0x00000008 - DCX_NORESETATTRS* = 0x00000004 - DCX_LOCKWINDOWUPDATE* = 0x00000400 - DCX_EXCLUDERGN* = 0x00000040 - DCX_INTERSECTRGN* = 0x00000080 - DCX_VALIDATE* = 0x00200000 - # GetDeviceCaps - DRIVERVERSION* = 0 - TECHNOLOGY* = 2 - DT_PLOTTER* = 0 - DT_RASDISPLAY* = 1 - DT_RASPRINTER* = 2 - DT_RASCAMERA* = 3 - DT_CHARSTREAM* = 4 - DT_METAFILE* = 5 - DT_DISPFILE* = 6 - HORZSIZE* = 4 - VERTSIZE* = 6 - HORZRES* = 8 - VERTRES* = 10 - LOGPIXELSX* = 88 - LOGPIXELSY* = 90 - BITSPIXEL* = 12 - PLANES* = 14 - NUMBRUSHES* = 16 - NUMPENS* = 18 - NUMFONTS* = 22 - NUMCOLORS* = 24 - ASPECTX* = 40 - ASPECTY* = 42 - ASPECTXY* = 44 - PDEVICESIZE* = 26 - CLIPCAPS* = 36 - SIZEPALETTE* = 104 - NUMRESERVED* = 106 - COLORRES* = 108 - VREFRESH* = 116 - DESKTOPHORZRES* = 118 - DESKTOPVERTRES* = 117 - BLTALIGNMENT* = 119 - RASTERCAPS* = 38 - RC_BANDING* = 2 - RC_BITBLT* = 1 - RC_BITMAP64* = 8 - RC_DI_BITMAP* = 128 - RC_DIBTODEV* = 512 - RC_FLOODFILL* = 4096 - RC_GDI20_OUTPUT* = 16 - RC_PALETTE* = 256 - RC_SCALING* = 4 - RC_STRETCHBLT* = 2048 - RC_STRETCHDIB* = 8192 - CURVECAPS* = 28 - CC_NONE* = 0 - CC_CIRCLES* = 1 - CC_PIE* = 2 - CC_CHORD* = 4 - CC_ELLIPSES* = 8 - CC_WIDE* = 16 - CC_STYLED* = 32 - CC_WIDESTYLED* = 64 - CC_INTERIORS* = 128 - CC_ROUNDRECT* = 256 - LINECAPS* = 30 - LC_NONE* = 0 - LC_POLYLINE* = 2 - LC_MARKER* = 4 - LC_POLYMARKER* = 8 - LC_WIDE* = 16 - LC_STYLED* = 32 - LC_WIDESTYLED* = 64 - LC_INTERIORS* = 128 - POLYGONALCAPS* = 32 - PC_NONE* = 0 - PC_POLYGON* = 1 - PC_RECTANGLE* = 2 - PC_WINDPOLYGON* = 4 - PC_SCANLINE* = 8 - PC_WIDE* = 16 - PC_STYLED* = 32 - PC_WIDESTYLED* = 64 - PC_INTERIORS* = 128 - TEXTCAPS* = 34 - TC_OP_CHARACTER* = 1 - TC_OP_STROKE* = 2 - TC_CP_STROKE* = 4 - TC_CR_90* = 8 - TC_CR_ANY* = 16 - TC_SF_X_YINDEP* = 32 - TC_SA_DOUBLE* = 64 - TC_SA_INTEGER* = 128 - TC_SA_CONTIN* = 256 - TC_EA_DOUBLE* = 512 - TC_IA_ABLE* = 1024 - TC_UA_ABLE* = 2048 - TC_SO_ABLE* = 4096 - TC_RA_ABLE* = 8192 - TC_VA_ABLE* = 16384 - TC_RESERVED* = 32768 - TC_SCROLLBLT* = 65536 - PC_PATHS* = 512 - # GetDriveType - DRIVE_REMOVABLE* = 2 - DRIVE_FIXED* = 3 - DRIVE_REMOTE* = 4 - DRIVE_CDROM* = 5 - DRIVE_RAMDISK* = 6 - DRIVE_UNKNOWN* = 0 - DRIVE_NO_ROOT_DIR* = 1 - # GetExceptionCode - EXCEPTION_ACCESS_VIOLATION* = 0xC0000005 - EXCEPTION_BREAKPOINT* = 0x80000003 - EXCEPTION_DATATYPE_MISALIGNMENT* = 0x80000002 - EXCEPTION_SINGLE_STEP* = 0x80000004 - EXCEPTION_ARRAY_BOUNDS_EXCEEDED* = 0xC000008C - EXCEPTION_FLT_DENORMAL_OPERAND* = 0xC000008D - EXCEPTION_FLT_DIVIDE_BY_ZERO* = 0xC000008E - EXCEPTION_FLT_INEXACT_RESULT* = 0xC000008F - EXCEPTION_FLT_INVALID_OPERATION* = 0xC0000090 - EXCEPTION_FLT_OVERFLOW* = 0xC0000091 - EXCEPTION_FLT_STACK_CHECK* = 0xC0000092 - EXCEPTION_FLT_UNDERFLOW* = 0xC0000093 - EXCEPTION_INT_DIVIDE_BY_ZERO* = 0xC0000094 - EXCEPTION_INT_OVERFLOW* = 0xC0000095 - EXCEPTION_INVALID_HANDLE* = 0xC0000008 - EXCEPTION_PRIV_INSTRUCTION* = 0xC0000096 - EXCEPTION_NONCONTINUABLE_EXCEPTION* = 0xC0000025 - EXCEPTION_NONCONTINUABLE* = 0x00000001 - EXCEPTION_STACK_OVERFLOW* = 0xC00000FD - EXCEPTION_INVALID_DISPOSITION* = 0xC0000026 - EXCEPTION_IN_PAGE_ERROR* = 0xC0000006 - EXCEPTION_ILLEGAL_INSTRUCTION* = 0xC000001D - EXCEPTION_POSSIBLE_DEADLOCK* = 0xC0000194 - # GetFileType - FILE_TYPE_UNKNOWN* = 0 - FILE_TYPE_DISK* = 1 - FILE_TYPE_CHAR* = 2 - FILE_TYPE_PIPE* = 3 - # GetGlyphOutline - GGO_BITMAP* = 1 - GGO_NATIVE* = 2 - GGO_METRICS* = 0 - GGO_GRAY2_BITMAP* = 4 - GGO_GRAY4_BITMAP* = 5 - GGO_GRAY8_BITMAP* = 6 - GDI_ERROR* = 0xFFFFFFFF - # GetGraphicsMode - GM_COMPATIBLE* = 1 - GM_ADVANCED* = 2 - # GetHandleInformation - HANDLE_FLAG_INHERIT* = 1 - HANDLE_FLAG_PROTECT_FROM_CLOSE* = 2 - # GetIconInfo - IDC_ARROW* = cast[MAKEINTRESOURCE](32512) - IDC_IBEAM* = cast[MAKEINTRESOURCE](32513) - IDC_WAIT* = cast[MAKEINTRESOURCE](32514) - IDC_CROSS* = cast[MAKEINTRESOURCE](32515) - IDC_UPARROW* = cast[MAKEINTRESOURCE](32516) - IDC_SIZE* = cast[MAKEINTRESOURCE](32640) # OBSOLETE: use IDC_SIZEALL - IDC_ICON* = cast[MAKEINTRESOURCE](32641) # OBSOLETE: use IDC_ARROW - IDC_SIZENWSE* = cast[MAKEINTRESOURCE](32642) - IDC_SIZENESW* = cast[MAKEINTRESOURCE](32643) - IDC_SIZEWE* = cast[MAKEINTRESOURCE](32644) - IDC_SIZENS* = cast[MAKEINTRESOURCE](32645) - IDC_SIZEALL* = cast[MAKEINTRESOURCE](32646) - IDC_NO* = cast[MAKEINTRESOURCE](32648) - IDC_HAND* = cast[MAKEINTRESOURCE](32649) - IDC_APPSTARTING* = cast[MAKEINTRESOURCE](32650) - IDC_HELP* = cast[MAKEINTRESOURCE](32651) - - IDI_APPLICATION* = cast[MAKEINTRESOURCE](32512) - IDI_HAND* = cast[MAKEINTRESOURCE](32513) - IDI_QUESTION* = cast[MAKEINTRESOURCE](32514) - IDI_EXCLAMATION* = cast[MAKEINTRESOURCE](32515) - IDI_ASTERISK* = cast[MAKEINTRESOURCE](32516) - IDI_WINLOGO* = cast[MAKEINTRESOURCE](32517) - IDI_WARNING* = IDI_EXCLAMATION - IDI_ERROR* = IDI_HAND - IDI_INFORMATION* = IDI_ASTERISK - -const - # GetMapMode - MM_ANISOTROPIC* = 8 - MM_HIENGLISH* = 5 - MM_HIMETRIC* = 3 - MM_ISOTROPIC* = 7 - MM_LOENGLISH* = 4 - MM_LOMETRIC* = 2 - MM_TEXT* = 1 - MM_TWIPS* = 6 - # GetMenuDefaultItem - GMDI_GOINTOPOPUPS* = 0x00000002 - GMDI_USEDISABLED* = 0x00000001 - # PeekMessage - PM_NOREMOVE* = 0 - PM_REMOVE* = 1 - PM_NOYIELD* = 2 - # GetNamedPipeHandleState - # PIPE_NOWAIT = 1; already above - # PIPE_READMODE_MESSAGE = 2;already above - # GetNamedPipeInfo - PIPE_CLIENT_END* = 0 - PIPE_SERVER_END* = 1 - # PIPE_TYPE_MESSAGE = 4;already above - # GetNextWindow, GetWindow - GW_HWNDNEXT* = 2 - GW_HWNDPREV* = 3 - GW_CHILD* = 5 - GW_HWNDFIRST* = 0 - GW_HWNDLAST* = 1 - GW_OWNER* = 4 - # GetPath - PT_MOVETO* = 6 - PT_LINETO* = 2 - PT_BEZIERTO* = 4 - PT_CLOSEFIGURE* = 1 - # GetProcessShutdownParameters - SHUTDOWN_NORETRY* = 1 - # GetQueueStatus - QS_ALLEVENTS* = 191 - QS_ALLINPUT* = 255 - QS_HOTKEY* = 128 - QS_INPUT* = 7 - QS_KEY* = 1 - QS_MOUSE* = 6 - QS_MOUSEBUTTON* = 4 - QS_MOUSEMOVE* = 2 - QS_PAINT* = 32 - QS_POSTMESSAGE* = 8 - QS_SENDMESSAGE* = 64 - QS_TIMER* = 16 - # GetScrollInfo, SetScrollInfo - SIF_ALL* = 23 - SIF_PAGE* = 2 - SIF_POS* = 4 - SIF_RANGE* = 1 - SIF_DISABLENOSCROLL* = 8 - - # GetStdHandle - STD_INPUT_HANDLE* = DWORD(-10) - STD_OUTPUT_HANDLE* = DWORD(-11) - STD_ERROR_HANDLE* = DWORD(-12) - - INVALID_HANDLE_VALUE* = HANDLE(-1) - INVALID_SET_FILE_POINTER* = ULONG(-1) - INVALID_FILE_SIZE* = ULONG(-1) - INVALID_FILE_ATTRIBUTES* = ULONG(-1) - -const - # GetStockObject - BLACK_BRUSH* = 4 - DKGRAY_BRUSH* = 3 - GRAY_BRUSH* = 2 - HOLLOW_BRUSH* = 5 - LTGRAY_BRUSH* = 1 - NULL_BRUSH* = 5 - WHITE_BRUSH* = 0 - BLACK_PEN* = 7 - NULL_PEN* = 8 - WHITE_PEN* = 6 - ANSI_FIXED_FONT* = 11 - ANSI_VAR_FONT* = 12 - DEVICE_DEFAULT_FONT* = 14 - DEFAULT_GUI_FONT* = 17 - OEM_FIXED_FONT* = 10 - SYSTEM_FONT* = 13 - SYSTEM_FIXED_FONT* = 16 - DEFAULT_PALETTE* = 15 - # GetStringTypeA - CT_CTYPE1* = 1 - CT_CTYPE2* = 2 - CT_CTYPE3* = 4 - C1_UPPER* = 1 - C1_LOWER* = 2 - C1_DIGIT* = 4 - C1_SPACE* = 8 - C1_PUNCT* = 16 - C1_CNTRL* = 32 - C1_BLANK* = 64 - C1_XDIGIT* = 128 - C1_ALPHA* = 256 - C2_LEFTTORIGHT* = 1 - C2_RIGHTTOLEFT* = 2 - C2_EUROPENUMBER* = 3 - C2_EUROPESEPARATOR* = 4 - C2_EUROPETERMINATOR* = 5 - C2_ARABICNUMBER* = 6 - C2_COMMONSEPARATOR* = 7 - C2_BLOCKSEPARATOR* = 8 - C2_SEGMENTSEPARATOR* = 9 - C2_WHITESPACE* = 10 - C2_OTHERNEUTRAL* = 11 - C2_NOTAPPLICABLE* = 0 - C3_NONSPACING* = 1 - C3_DIACRITIC* = 2 - C3_VOWELMARK* = 4 - C3_SYMBOL* = 8 - C3_KATAKANA* = 16 - C3_HIRAGANA* = 32 - C3_HALFWIDTH* = 64 - C3_FULLWIDTH* = 128 - C3_IDEOGRAPH* = 256 - C3_KASHIDA* = 512 - C3_ALPHA* = 32768 - C3_NOTAPPLICABLE* = 0 - # GetSysColor - COLOR_3DDKSHADOW* = 21 - COLOR_3DFACE* = 15 - COLOR_3DHILIGHT* = 20 - COLOR_3DLIGHT* = 22 - COLOR_BTNHILIGHT* = 20 - COLOR_3DSHADOW* = 16 - COLOR_ACTIVEBORDER* = 10 - COLOR_ACTIVECAPTION* = 2 - COLOR_APPWORKSPACE* = 12 - COLOR_BACKGROUND* = 1 - COLOR_DESKTOP* = 1 - COLOR_BTNFACE* = 15 - COLOR_BTNHIGHLIGHT* = 20 - COLOR_BTNSHADOW* = 16 - COLOR_BTNTEXT* = 18 - COLOR_CAPTIONTEXT* = 9 - COLOR_GRAYTEXT* = 17 - COLOR_HIGHLIGHT* = 13 - COLOR_HIGHLIGHTTEXT* = 14 - COLOR_INACTIVEBORDER* = 11 - COLOR_INACTIVECAPTION* = 3 - COLOR_INACTIVECAPTIONTEXT* = 19 - COLOR_INFOBK* = 24 - COLOR_INFOTEXT* = 23 - COLOR_MENU* = 4 - COLOR_MENUTEXT* = 7 - COLOR_SCROLLBAR* = 0 - COLOR_WINDOW* = 5 - COLOR_WINDOWFRAME* = 6 - COLOR_WINDOWTEXT* = 8 - # GetSystemMetrics - SM_CYMIN* = 29 - SM_CXMIN* = 28 - SM_ARRANGE* = 56 - SM_CLEANBOOT* = 67 - # The right value for SM_CEMETRICS for NT 3.5 is 75. For Windows 95 - # and NT 4.0, it is 76. The meaning is undocumented, anyhow. - SM_CMETRICS* = 76 - SM_CMOUSEBUTTONS* = 43 - SM_CXBORDER* = 5 - SM_CYBORDER* = 6 - SM_CXCURSOR* = 13 - SM_CYCURSOR* = 14 - SM_CXDLGFRAME* = 7 - SM_CYDLGFRAME* = 8 - SM_CXDOUBLECLK* = 36 - SM_CYDOUBLECLK* = 37 - SM_CXDRAG* = 68 - SM_CYDRAG* = 69 - SM_CXEDGE* = 45 - SM_CYEDGE* = 46 - SM_CXFIXEDFRAME* = 7 - SM_CYFIXEDFRAME* = 8 - SM_CXFRAME* = 32 - SM_CYFRAME* = 33 - SM_CXFULLSCREEN* = 16 - SM_CYFULLSCREEN* = 17 - SM_CXHSCROLL* = 21 - SM_CYHSCROLL* = 3 - SM_CXHTHUMB* = 10 - SM_CXICON* = 11 - SM_CYICON* = 12 - SM_CXICONSPACING* = 38 - SM_CYICONSPACING* = 39 - SM_CXMAXIMIZED* = 61 - SM_CYMAXIMIZED* = 62 - SM_CXMAXTRACK* = 59 - SM_CYMAXTRACK* = 60 - SM_CXMENUCHECK* = 71 - SM_CYMENUCHECK* = 72 - SM_CXMENUSIZE* = 54 - SM_CYMENUSIZE* = 55 - SM_CXMINIMIZED* = 57 - SM_CYMINIMIZED* = 58 - SM_CXMINSPACING* = 47 - SM_CYMINSPACING* = 48 - SM_CXMINTRACK* = 34 - SM_CYMINTRACK* = 35 - SM_CXSCREEN* = 0 - SM_CYSCREEN* = 1 - SM_CXSIZE* = 30 - SM_CYSIZE* = 31 - SM_CXSIZEFRAME* = 32 - SM_CYSIZEFRAME* = 33 - SM_CXSMICON* = 49 - SM_CYSMICON* = 50 - SM_CXSMSIZE* = 52 - SM_CYSMSIZE* = 53 - SM_CXVSCROLL* = 2 - #SM_CYHSCROLL = 3;already above - #SM_CXHSCROLL = 21;already above - SM_CYVSCROLL* = 20 - SM_CYVTHUMB* = 9 - SM_CYCAPTION* = 4 - SM_CYKANJIWINDOW* = 18 - SM_CYMENU* = 15 - SM_CYSMCAPTION* = 51 - SM_DBCSENABLED* = 42 - SM_DEBUG* = 22 - SM_MENUDROPALIGNMENT* = 40 - SM_MIDEASTENABLED* = 74 - SM_MOUSEPRESENT* = 19 - SM_MOUSEWHEELPRESENT* = 75 - SM_NETWORK* = 63 - SM_PENWINDOWS* = 41 - SM_SECURE* = 44 - SM_SHOWSOUNDS* = 70 - SM_SLOWMACHINE* = 73 - SM_SWAPBUTTON* = 23 - ARW_BOTTOMLEFT* = 0 - ARW_BOTTOMRIGHT* = 0x00000001 - ARW_HIDE* = 0x00000008 - ARW_TOPLEFT* = 0x00000002 - ARW_TOPRIGHT* = 0x00000003 - ARW_DOWN* = 0x00000004 - ARW_LEFT* = 0 - ARW_RIGHT* = 0 - ARW_UP* = 0x00000004 - # GetSystemPaletteUse - SYSPAL_NOSTATIC* = 2 - SYSPAL_STATIC* = 1 - SYSPAL_ERROR* = 0 - # GetTapeParameters, SetTapeParameters - GET_TAPE_MEDIA_INFORMATION* = 0 - GET_TAPE_DRIVE_INFORMATION* = 1 - SET_TAPE_MEDIA_INFORMATION* = 0 - SET_TAPE_DRIVE_INFORMATION* = 1 - # GetTapePosition - TAPE_ABSOLUTE_POSITION* = 0 - TAPE_LOGICAL_POSITION* = 0x00000001 - # GetTextAlign - TA_BASELINE* = 24 - TA_BOTTOM* = 8 - TA_TOP* = 0 - TA_CENTER* = 6 - TA_LEFT* = 0 - TA_RIGHT* = 2 - TA_RTLREADING* = 256 - TA_NOUPDATECP* = 0 - TA_UPDATECP* = 1 - VTA_BASELINE* = 24 - VTA_CENTER* = 6 - # GetThreadPriority - THREAD_PRIORITY_ABOVE_NORMAL* = 1 - THREAD_PRIORITY_BELOW_NORMAL* = -1 - THREAD_PRIORITY_HIGHEST* = 2 - THREAD_PRIORITY_IDLE* = -15 - THREAD_PRIORITY_LOWEST* = -2 - THREAD_PRIORITY_NORMAL* = 0 - THREAD_PRIORITY_TIME_CRITICAL* = 15 - THREAD_PRIORITY_ERROR_RETURN* = 2147483647 - TLS_MINIMUM_AVAILABLE* = 64 - # GetTimeFormat - TIME_NOMINUTESORSECONDS* = 1 - TIME_NOSECONDS* = 2 - TIME_NOTIMEMARKER* = 4 - TIME_FORCE24HOURFORMAT* = 8 - -const - # GetTimeZoneInformation - TIME_ZONE_ID_INVALID* = DWORD(- 1) - TIME_ZONE_ID_UNKNOWN* = 0 - TIME_ZONE_ID_STANDARD* = 1 - TIME_ZONE_ID_DAYLIGHT* = 2 - # GetUserObjectInformation - UOI_FLAGS* = 1 - UOI_NAME* = 2 - UOI_TYPE* = 3 - # GetVolumeInformation - FS_CASE_IS_PRESERVED* = 2 - FS_CASE_SENSITIVE* = 1 - FS_UNICODE_STORED_ON_DISK* = 4 - FS_PERSISTENT_ACLS* = 8 - FS_FILE_COMPRESSION* = 16 - FS_VOL_IS_COMPRESSED* = 32768 - # GetWindowLong - GWL_EXSTYLE* = -20 - GWL_STYLE* = -16 - GWL_WNDPROC* = -4 - GWL_HINSTANCE* = -6 - GWL_HWNDPARENT* = -8 - GWL_ID* = -12 - GWL_USERDATA* = -21 - DWL_DLGPROC* = 4 - DWL_MSGRESULT* = 0 - DWL_USER* = 8 - # GlobalAlloc, GlobalFlags - GMEM_FIXED* = 0 - GMEM_MOVEABLE* = 2 - GPTR* = 64 - GHND* = 66 - GMEM_DDESHARE* = 8192 - GMEM_DISCARDABLE* = 256 - GMEM_LOWER* = 4096 - GMEM_NOCOMPACT* = 16 - GMEM_NODISCARD* = 32 - GMEM_NOT_BANKED* = 4096 - GMEM_NOTIFY* = 16384 - GMEM_SHARE* = 8192 - GMEM_ZEROINIT* = 64 - GMEM_DISCARDED* = 16384 - GMEM_INVALID_HANDLE* = 32768 - GMEM_LOCKCOUNT* = 255 - # HeapAlloc, HeapReAlloc - HEAP_GENERATE_EXCEPTIONS* = 4 - HEAP_NO_SERIALIZE* = 1 - HEAP_ZERO_MEMORY* = 8 - STATUS_NO_MEMORY* = 0xC0000017 - STATUS_ACCESS_VIOLATION* = 0xC0000005 - HEAP_REALLOC_IN_PLACE_ONLY* = 16 - # ImageList_Create - ILC_COLOR* = 0 - ILC_COLOR4* = 4 - ILC_COLOR8* = 8 - ILC_COLOR16* = 16 - ILC_COLOR24* = 24 - ILC_COLOR32* = 32 - ILC_COLORDDB* = 254 - ILC_MASK* = 1 - ILC_PALETTE* = 2048 - # ImageList_Draw, ImageList_DrawEx - ILD_BLEND25* = 2 - ILD_BLEND50* = 4 - ILD_SELECTED* = 4 - ILD_BLEND* = 4 - ILD_FOCUS* = 2 - ILD_MASK* = 16 - ILD_NORMAL* = 0 - ILD_TRANSPARENT* = 1 - CLR_NONE* = 0xFFFFFFFF - CLR_DEFAULT* = 0xFF000000 - CLR_INVALID* = 0xFFFFFFFF - # ImageList_LoadImage - #LR_DEFAULTCOLOR = 0;already above - LR_LOADFROMFILE* = 16 - LR_LOADMAP3DCOLORS* = 4096 - LR_LOADTRANSPARENT* = 32 - # ImmConfigureIME - IME_CONFIG_GENERAL* = 1 - IME_CONFIG_REGISTERWORD* = 2 - IME_CONFIG_SELECTDICTIONARY* = 3 - # ImmGetConversionList - GCL_CONVERSION* = 1 - GCL_REVERSECONVERSION* = 2 - GCL_REVERSE_LENGTH* = 3 - # ImmGetGuideLine - GGL_LEVEL* = 1 - GGL_INDEX* = 2 - GGL_STRING* = 3 - GGL_PRIVATE* = 4 - GL_LEVEL_ERROR* = 2 - GL_LEVEL_FATAL* = 1 - GL_LEVEL_INFORMATION* = 4 - GL_LEVEL_NOGUIDELINE* = 0 - GL_LEVEL_WARNING* = 3 - GL_ID_CANNOTSAVE* = 17 - GL_ID_NOCONVERT* = 32 - GL_ID_NODICTIONARY* = 16 - GL_ID_NOMODULE* = 1 - GL_ID_READINGCONFLICT* = 35 - GL_ID_TOOMANYSTROKE* = 34 - GL_ID_TYPINGERROR* = 33 - GL_ID_UNKNOWN* = 0 - GL_ID_INPUTREADING* = 36 - GL_ID_INPUTRADICAL* = 37 - GL_ID_INPUTCODE* = 38 - GL_ID_CHOOSECANDIDATE* = 40 - GL_ID_REVERSECONVERSION* = 41 - # ImmGetProperty - IGP_PROPERTY* = 4 - IGP_CONVERSION* = 8 - IGP_SENTENCE* = 12 - IGP_UI* = 16 - IGP_SETCOMPSTR* = 20 - IGP_SELECT* = 24 - IME_PROP_AT_CARET* = 65536 - IME_PROP_SPECIAL_UI* = 131072 - IME_PROP_CANDLIST_START_FROM_1* = 262144 - IME_PROP_UNICODE* = 524288 - UI_CAP_2700* = 1 - UI_CAP_ROT90* = 2 - UI_CAP_ROTANY* = 4 - SCS_CAP_COMPSTR* = 1 - SCS_CAP_MAKEREAD* = 2 - SELECT_CAP_CONVERSION* = 1 - SELECT_CAP_SENTENCE* = 2 - # ImmNotifyIME - NI_CHANGECANDIDATELIST* = 19 - NI_CLOSECANDIDATE* = 17 - NI_COMPOSITIONSTR* = 21 - NI_OPENCANDIDATE* = 16 - NI_SELECTCANDIDATESTR* = 18 - NI_SETCANDIDATE_PAGESIZE* = 23 - NI_SETCANDIDATE_PAGESTART* = 22 - CPS_CANCEL* = 4 - CPS_COMPLETE* = 1 - CPS_CONVERT* = 2 - CPS_REVERT* = 3 - # ImmSetCompositionString - SCS_SETSTR* = 9 - SCS_CHANGEATTR* = 18 - SCS_CHANGECLAUSE* = 36 - # ImmUnregisterWord - IME_REGWORD_STYLE_EUDC* = 1 - IME_REGWORD_STYLE_USER_FIRST* = 0x80000000 - IME_REGWORD_STYLE_USER_LAST* = -1 - # InitializeSecurityDescriptor - SECURITY_DESCRIPTOR_REVISION* = 1 - # IsTextUnicode - IS_TEXT_UNICODE_ASCII16* = 1 - IS_TEXT_UNICODE_REVERSE_ASCII16* = 16 - IS_TEXT_UNICODE_STATISTICS* = 2 - IS_TEXT_UNICODE_REVERSE_STATISTICS* = 32 - IS_TEXT_UNICODE_CONTROLS* = 4 - IS_TEXT_UNICODE_REVERSE_CONTROLS* = 64 - IS_TEXT_UNICODE_SIGNATURE* = 8 - IS_TEXT_UNICODE_REVERSE_SIGNATURE* = 128 - IS_TEXT_UNICODE_ILLEGAL_CHARS* = 256 - IS_TEXT_UNICODE_ODD_LENGTH* = 512 - IS_TEXT_UNICODE_NULL_BYTES* = 4096 - IS_TEXT_UNICODE_UNICODE_MASK* = 15 - IS_TEXT_UNICODE_REVERSE_MASK* = 240 - IS_TEXT_UNICODE_NOT_UNICODE_MASK* = 3840 - IS_TEXT_UNICODE_NOT_ASCII_MASK* = 61440 - # JournalPlaybackProc, KeyboardProc - HC_GETNEXT* = 1 - HC_SKIP* = 2 - HC_SYSMODALOFF* = 5 - HC_SYSMODALON* = 4 - HC_NOREMOVE* = 3 - # keybd_event - KEYEVENTF_EXTENDEDKEY* = 1 - KEYEVENTF_KEYUP* = 2 - # LoadBitmap - OBM_BTNCORNERS* = 32758 - OBM_BTSIZE* = 32761 - OBM_CHECK* = 32760 - OBM_CHECKBOXES* = 32759 - OBM_CLOSE* = 32754 - OBM_COMBO* = 32738 - OBM_DNARROW* = 32752 - OBM_DNARROWD* = 32742 - OBM_DNARROWI* = 32736 - OBM_LFARROW* = 32750 - OBM_LFARROWI* = 32734 - OBM_LFARROWD* = 32740 - OBM_MNARROW* = 32739 - OBM_OLD_CLOSE* = 32767 - OBM_OLD_DNARROW* = 32764 - OBM_OLD_LFARROW* = 32762 - OBM_OLD_REDUCE* = 32757 - OBM_OLD_RESTORE* = 32755 - OBM_OLD_RGARROW* = 32763 - OBM_OLD_UPARROW* = 32765 - OBM_OLD_ZOOM* = 32756 - OBM_REDUCE* = 32749 - OBM_REDUCED* = 32746 - OBM_RESTORE* = 32747 - OBM_RESTORED* = 32744 - OBM_RGARROW* = 32751 - OBM_RGARROWD* = 32741 - OBM_RGARROWI* = 32735 - OBM_SIZE* = 32766 - OBM_UPARROW* = 32753 - OBM_UPARROWD* = 32743 - OBM_UPARROWI* = 32737 - OBM_ZOOM* = 32748 - OBM_ZOOMD* = 32745 - # LoadLibraryEx - DONT_RESOLVE_DLL_REFERENCES* = 1 - LOAD_LIBRARY_AS_DATAFILE* = 2 - LOAD_WITH_ALTERED_SEARCH_PATH* = 8 - # LocalAlloc, LocalFlags - LPTR* = 64 - LHND* = 66 - NONZEROLHND* = 2 - NONZEROLPTR* = 0 - LMEM_NONZEROLHND* = 2 - LMEM_NONZEROLPTR* = 0 - LMEM_FIXED* = 0 - LMEM_MOVEABLE* = 2 - LMEM_NOCOMPACT* = 16 - LMEM_NODISCARD* = 32 - LMEM_ZEROINIT* = 64 - LMEM_MODIFY* = 128 - LMEM_LOCKCOUNT* = 255 - LMEM_DISCARDABLE* = 3840 - LMEM_DISCARDED* = 16384 - LMEM_INVALID_HANDLE* = 32768 - # LockFileEx - LOCKFILE_FAIL_IMMEDIATELY* = 1 - LOCKFILE_EXCLUSIVE_LOCK* = 2 - # LogonUser - # LZCopy, LZInit, LZRead - # MessageBeep, MessageBox - MB_USERICON* = 0x00000080 - MB_ICONASTERISK* = 0x00000040 - MB_ICONEXCLAMATION* = 0x00000030 - MB_ICONWARNING* = 0x00000030 - MB_ICONERROR* = 0x00000010 - MB_ICONHAND* = 0x00000010 - MB_ICONQUESTION* = 0x00000020 - MB_OK* = 0 - MB_ABORTRETRYIGNORE* = 0x00000002 - MB_APPLMODAL* = 0 - MB_DEFAULT_DESKTOP_ONLY* = 0x00020000 - MB_HELP* = 0x00004000 - MB_RIGHT* = 0x00080000 - MB_RTLREADING* = 0x00100000 - MB_TOPMOST* = 0x00040000 - MB_DEFBUTTON1* = 0 - MB_DEFBUTTON2* = 0x00000100 - MB_DEFBUTTON3* = 0x00000200 - MB_DEFBUTTON4* = 0x00000300 - MB_ICONINFORMATION* = 0x00000040 - MB_ICONSTOP* = 0x00000010 - MB_OKCANCEL* = 0x00000001 - MB_RETRYCANCEL* = 0x00000005 - MB_SERVICE_NOTIFICATION* = 0x00040000 - MB_SETFOREGROUND* = 0x00010000 - MB_SYSTEMMODAL* = 0x00001000 - MB_TASKMODAL* = 0x00002000 - MB_YESNO* = 0x00000004 - MB_YESNOCANCEL* = 0x00000003 - IDABORT* = 3 - IDCANCEL* = 2 - IDCLOSE* = 8 - IDHELP* = 9 - IDIGNORE* = 5 - IDNO* = 7 - IDOK* = 1 - IDRETRY* = 4 - IDYES* = 6 - # MessageProc - MSGF_DIALOGBOX* = 0 - MSGF_MENU* = 2 - MSGF_NEXTWINDOW* = 6 - MSGF_SCROLLBAR* = 5 - MSGF_MAINLOOP* = 8 - MSGF_USER* = 4096 - # ModifyWorldTransform - MWT_IDENTITY* = 1 - MWT_LEFTMULTIPLY* = 2 - MWT_RIGHTMULTIPLY* = 3 - # mouse_event - MOUSEEVENTF_ABSOLUTE* = 32768 - MOUSEEVENTF_MOVE* = 1 - MOUSEEVENTF_LEFTDOWN* = 2 - MOUSEEVENTF_LEFTUP* = 4 - MOUSEEVENTF_RIGHTDOWN* = 8 - MOUSEEVENTF_RIGHTUP* = 16 - MOUSEEVENTF_MIDDLEDOWN* = 32 - MOUSEEVENTF_MIDDLEUP* = 64 - # MoveFileEx - MOVEFILE_REPLACE_EXISTING* = 1 - MOVEFILE_COPY_ALLOWED* = 2 - MOVEFILE_DELAY_UNTIL_REBOOT* = 4 - # MsgWaitForMultipleObjects, WaitForMultipleObjectsEx - WAIT_OBJECT_0* = 0 - WAIT_ABANDONED_0* = 0x00000080 - WAIT_TIMEOUT* = 0x00000102 - WAIT_IO_COMPLETION* = 0x000000C0 - WAIT_ABANDONED* = 0x00000080 - WAIT_FAILED* = 0xFFFFFFFF - MAXIMUM_WAIT_OBJECTS* = 0x00000040 - MAXIMUM_SUSPEND_COUNT* = 0x0000007F - # MultiByteToWideChar - MB_PRECOMPOSED* = 1 - MB_COMPOSITE* = 2 - MB_ERR_INVALID_CHARS* = 8 - MB_USEGLYPHCHARS* = 4 - # NDdeSetTrustedShare - # NetAccessCheck - # NetServerEnum - # NetServiceControl - # NetUserEnum - # OpenProcessToken - TOKEN_ADJUST_DEFAULT* = 128 - TOKEN_ADJUST_GROUPS* = 64 - TOKEN_ADJUST_PRIVILEGES* = 32 - TOKEN_ALL_ACCESS* = 0x000F00FF - TOKEN_ASSIGN_PRIMARY* = 1 - TOKEN_DUPLICATE* = 2 - TOKEN_EXECUTE* = 0x00020000 - TOKEN_IMPERSONATE* = 4 - TOKEN_QUERY* = 8 - TOKEN_QUERY_SOURCE* = 16 - TOKEN_READ* = 0x00020008 - TOKEN_WRITE* = 0x000200E0 - # OpenSCManager - SC_MANAGER_ALL_ACCESS* = 0x000F003F - SC_MANAGER_CONNECT* = 1 - SC_MANAGER_CREATE_SERVICE* = 2 - SC_MANAGER_ENUMERATE_SERVICE* = 4 - SC_MANAGER_LOCK* = 8 - SC_MANAGER_QUERY_LOCK_STATUS* = 16 - SC_MANAGER_MODIFY_BOOT_CONFIG* = 32 - # PostMessage - HWND_BROADCAST* = HWND(0xffff) - -const - # PrepareTape - TAPE_FORMAT* = 0x00000005 - TAPE_LOAD* = 0 - TAPE_LOCK* = 0x00000003 - TAPE_TENSION* = 0x00000002 - TAPE_UNLOAD* = 0x00000001 - TAPE_UNLOCK* = 0x00000004 - # PropertySheet - IS_PSREBOOTSYSTEM* = 3 - IS_PSRESTARTWINDOWS* = 2 - # PropSheetPageProc - PSPCB_CREATE* = 2 - PSPCB_RELEASE* = 1 - # PurgeComm - PURGE_TXABORT* = 1 - PURGE_RXABORT* = 2 - PURGE_TXCLEAR* = 4 - PURGE_RXCLEAR* = 8 - # QueryServiceObjectSecurity - OWNER_SECURITY_INFORMATION* = 0x00000001 - GROUP_SECURITY_INFORMATION* = 0x00000002 - DACL_SECURITY_INFORMATION* = 0x00000004 - SACL_SECURITY_INFORMATION* = 0x00000008 - # ReadEventLog, ReportEvent - EVENTLOG_FORWARDS_READ* = 4 - EVENTLOG_BACKWARDS_READ* = 8 - EVENTLOG_SEEK_READ* = 2 - EVENTLOG_SEQUENTIAL_READ* = 1 - EVENTLOG_ERROR_TYPE* = 1 - EVENTLOG_WARNING_TYPE* = 2 - EVENTLOG_INFORMATION_TYPE* = 4 - EVENTLOG_AUDIT_SUCCESS* = 8 - - EVENTLOG_AUDIT_FAILURE* = 16 - # RedrawWindow - RDW_ERASE* = 4 - RDW_FRAME* = 1024 - RDW_INTERNALPAINT* = 2 - RDW_INVALIDATE* = 1 - RDW_NOERASE* = 32 - RDW_NOFRAME* = 2048 - RDW_NOINTERNALPAINT* = 16 - RDW_VALIDATE* = 8 - RDW_ERASENOW* = 512 - RDW_UPDATENOW* = 256 - RDW_ALLCHILDREN* = 128 - RDW_NOCHILDREN* = 64 - - # RegCreateKey - HKEY_CLASSES_ROOT* = HKEY(0x80000000) - HKEY_CURRENT_USER* = HKEY(0x80000001) - HKEY_LOCAL_MACHINE* = HKEY(0x80000002) - HKEY_USERS* = HKEY(0x80000003) - HKEY_PERFORMANCE_DATA* = HKEY(0x80000004) - HKEY_CURRENT_CONFIG* = HKEY(0x80000005) - HKEY_DYN_DATA* = HKEY(0x80000006) - -const - # RegCreateKeyEx - REG_OPTION_VOLATILE* = 0x00000001 - REG_OPTION_NON_VOLATILE* = 0 - REG_CREATED_NEW_KEY* = 0x00000001 - REG_OPENED_EXISTING_KEY* = 0x00000002 - # RegEnumValue - REG_BINARY* = 3 - REG_DWORD* = 4 - REG_DWORD_LITTLE_ENDIAN* = 4 - REG_DWORD_BIG_ENDIAN* = 5 - REG_EXPAND_SZ* = 2 - REG_FULL_RESOURCE_DESCRIPTOR* = 9 - REG_LINK* = 6 - REG_MULTI_SZ* = 7 - REG_NONE* = 0 - REG_RESOURCE_LIST* = 8 - REG_RESOURCE_REQUIREMENTS_LIST* = 10 - REG_SZ* = 1 - # RegisterHotKey - MOD_ALT* = 1 - MOD_CONTROL* = 2 - MOD_SHIFT* = 4 - MOD_WIN* = 8 - IDHOT_SNAPDESKTOP* = -2 - IDHOT_SNAPWINDOW* = -1 - # RegNotifyChangeKeyValue - REG_NOTIFY_CHANGE_NAME* = 0x00000001 - REG_NOTIFY_CHANGE_ATTRIBUTES* = 0x00000002 - REG_NOTIFY_CHANGE_LAST_SET* = 0x00000004 - REG_NOTIFY_CHANGE_SECURITY* = 0x00000008 - # ScrollWindowEx - SW_ERASE* = 4 - SW_INVALIDATE* = 2 - SW_SCROLLCHILDREN* = 1 - # SendMessageTimeout - SMTO_ABORTIFHUNG* = 2 - SMTO_BLOCK* = 1 - SMTO_NORMAL* = 0 - # SetBkMode - OPAQUE* = 2 - - TRANSPARENT* = 1 - # SetDebugErrorLevel - SLE_ERROR* = 1 - SLE_MINORERROR* = 2 - SLE_WARNING* = 3 - # SetErrorMode - SEM_FAILCRITICALERRORS* = 1 - SEM_NOALIGNMENTFAULTEXCEPT* = 4 - SEM_NOGPFAULTERRORBOX* = 2 - SEM_NOOPENFILEERRORBOX* = 32768 - # SetICMMode - ICM_ON* = 2 - ICM_OFF* = 1 - ICM_QUERY* = 3 - # SetJob - # Locale Information - LOCALE_ILANGUAGE* = 1 - LOCALE_SLANGUAGE* = 2 - LOCALE_SENGLANGUAGE* = 4097 - LOCALE_SABBREVLANGNAME* = 3 - LOCALE_SNATIVELANGNAME* = 4 - LOCALE_ICOUNTRY* = 5 - LOCALE_SCOUNTRY* = 6 - LOCALE_SENGCOUNTRY* = 4098 - LOCALE_SABBREVCTRYNAME* = 7 - LOCALE_SNATIVECTRYNAME* = 8 - LOCALE_IDEFAULTLANGUAGE* = 9 - LOCALE_IDEFAULTCOUNTRY* = 10 - LOCALE_IDEFAULTANSICODEPAGE* = 4100 - LOCALE_IDEFAULTCODEPAGE* = 11 - LOCALE_SLIST* = 12 - LOCALE_IMEASURE* = 13 - LOCALE_SDECIMAL* = 14 - LOCALE_STHOUSAND* = 15 - LOCALE_SGROUPING* = 16 - LOCALE_IDIGITS* = 17 - LOCALE_ILZERO* = 18 - LOCALE_INEGNUMBER* = 4112 - LOCALE_SCURRENCY* = 20 - LOCALE_SMONDECIMALSEP* = 22 - LOCALE_SMONTHOUSANDSEP* = 23 - LOCALE_SMONGROUPING* = 24 - LOCALE_ICURRDIGITS* = 25 - LOCALE_ICURRENCY* = 27 - LOCALE_INEGCURR* = 28 - LOCALE_SDATE* = 29 - LOCALE_STIME* = 30 - LOCALE_STIMEFORMAT* = 4099 - LOCALE_SSHORTDATE* = 31 - LOCALE_SLONGDATE* = 32 - LOCALE_IDATE* = 33 - LOCALE_ILDATE* = 34 - LOCALE_ITIME* = 35 - LOCALE_ITLZERO* = 37 - LOCALE_IDAYLZERO* = 38 - LOCALE_IMONLZERO* = 39 - LOCALE_S1159* = 40 - LOCALE_S2359* = 41 - LOCALE_ICALENDARTYPE* = 4105 - LOCALE_IOPTIONALCALENDAR* = 4107 - LOCALE_IFIRSTDAYOFWEEK* = 4108 - LOCALE_IFIRSTWEEKOFYEAR* = 4109 - LOCALE_SDAYNAME1* = 42 - LOCALE_SDAYNAME2* = 43 - LOCALE_SDAYNAME3* = 44 - LOCALE_SDAYNAME4* = 45 - LOCALE_SDAYNAME5* = 46 - LOCALE_SDAYNAME6* = 47 - LOCALE_SDAYNAME7* = 48 - LOCALE_SABBREVDAYNAME1* = 49 - LOCALE_SABBREVDAYNAME2* = 50 - LOCALE_SABBREVDAYNAME3* = 51 - LOCALE_SABBREVDAYNAME4* = 52 - LOCALE_SABBREVDAYNAME5* = 53 - LOCALE_SABBREVDAYNAME6* = 54 - LOCALE_SABBREVDAYNAME7* = 55 - LOCALE_SMONTHNAME1* = 56 - LOCALE_SMONTHNAME2* = 57 - LOCALE_SMONTHNAME3* = 58 - LOCALE_SMONTHNAME4* = 59 - LOCALE_SMONTHNAME5* = 60 - LOCALE_SMONTHNAME6* = 61 - LOCALE_SMONTHNAME7* = 62 - LOCALE_SMONTHNAME8* = 63 - LOCALE_SMONTHNAME9* = 64 - LOCALE_SMONTHNAME10* = 65 - LOCALE_SMONTHNAME11* = 66 - LOCALE_SMONTHNAME12* = 67 - LOCALE_SMONTHNAME13* = 4110 - LOCALE_SABBREVMONTHNAME1* = 68 - LOCALE_SABBREVMONTHNAME2* = 69 - LOCALE_SABBREVMONTHNAME3* = 70 - LOCALE_SABBREVMONTHNAME4* = 71 - LOCALE_SABBREVMONTHNAME5* = 72 - LOCALE_SABBREVMONTHNAME6* = 73 - LOCALE_SABBREVMONTHNAME7* = 74 - LOCALE_SABBREVMONTHNAME8* = 75 - LOCALE_SABBREVMONTHNAME9* = 76 - LOCALE_SABBREVMONTHNAME10* = 77 - LOCALE_SABBREVMONTHNAME11* = 78 - LOCALE_SABBREVMONTHNAME12* = 79 - LOCALE_SABBREVMONTHNAME13* = 4111 - LOCALE_SPOSITIVESIGN* = 80 - LOCALE_SNEGATIVESIGN* = 81 - LOCALE_IPOSSIGNPOSN* = 82 - LOCALE_INEGSIGNPOSN* = 83 - LOCALE_IPOSSYMPRECEDES* = 84 - LOCALE_IPOSSEPBYSPACE* = 85 - LOCALE_INEGSYMPRECEDES* = 86 - LOCALE_INEGSEPBYSPACE* = 87 - LOCALE_NOUSEROVERRIDE* = 0x80000000 - LOCALE_USE_CP_ACP* = 0x40000000 # use the system ACP - LOCALE_RETURN_NUMBER* = 0x20000000 # return number instead - LOCALE_SISO639LANGNAME* = 0x00000059 - LOCALE_SISO3166CTRYNAME* = 0x0000005A - # Calendar Type Information - CAL_ICALINTVALUE* = 1 - CAL_IYEAROFFSETRANGE* = 3 - CAL_SABBREVDAYNAME1* = 14 - CAL_SABBREVDAYNAME2* = 15 - CAL_SABBREVDAYNAME3* = 16 - CAL_SABBREVDAYNAME4* = 17 - CAL_SABBREVDAYNAME5* = 18 - CAL_SABBREVDAYNAME6* = 19 - CAL_SABBREVDAYNAME7* = 20 - CAL_SABBREVMONTHNAME1* = 34 - CAL_SABBREVMONTHNAME2* = 35 - CAL_SABBREVMONTHNAME3* = 36 - CAL_SABBREVMONTHNAME4* = 37 - CAL_SABBREVMONTHNAME5* = 38 - CAL_SABBREVMONTHNAME6* = 39 - CAL_SABBREVMONTHNAME7* = 40 - CAL_SABBREVMONTHNAME8* = 41 - CAL_SABBREVMONTHNAME9* = 42 - CAL_SABBREVMONTHNAME10* = 43 - CAL_SABBREVMONTHNAME11* = 44 - CAL_SABBREVMONTHNAME12* = 45 - CAL_SABBREVMONTHNAME13* = 46 - CAL_SCALNAME* = 2 - CAL_SDAYNAME1* = 7 - CAL_SDAYNAME2* = 8 - CAL_SDAYNAME3* = 9 - CAL_SDAYNAME4* = 10 - CAL_SDAYNAME5* = 11 - CAL_SDAYNAME6* = 12 - CAL_SDAYNAME7* = 13 - CAL_SERASTRING* = 4 - CAL_SLONGDATE* = 6 - CAL_SMONTHNAME1* = 21 - CAL_SMONTHNAME2* = 22 - CAL_SMONTHNAME3* = 23 - CAL_SMONTHNAME4* = 24 - CAL_SMONTHNAME5* = 25 - CAL_SMONTHNAME6* = 26 - CAL_SMONTHNAME7* = 27 - CAL_SMONTHNAME8* = 28 - CAL_SMONTHNAME9* = 29 - CAL_SMONTHNAME10* = 30 - CAL_SMONTHNAME11* = 31 - CAL_SMONTHNAME12* = 32 - CAL_SMONTHNAME13* = 33 - CAL_SSHORTDATE* = 5 - # SetProcessWorkingSetSize - PROCESS_SET_QUOTA* = 256 - # SetPrinter - # SetService - # SetStretchBltMode - BLACKONWHITE* = 1 - COLORONCOLOR* = 3 - HALFTONE* = 4 - STRETCH_ANDSCANS* = 1 - STRETCH_DELETESCANS* = 3 - STRETCH_HALFTONE* = 4 - STRETCH_ORSCANS* = 2 - WHITEONBLACK* = 2 - # SetSystemCursor - OCR_NORMAL* = 32512 - OCR_IBEAM* = 32513 - OCR_WAIT* = 32514 - OCR_CROSS* = 32515 - OCR_UP* = 32516 - OCR_SIZE* = 32640 - OCR_ICON* = 32641 - OCR_SIZENWSE* = 32642 - OCR_SIZENESW* = 32643 - OCR_SIZEWE* = 32644 - OCR_SIZENS* = 32645 - OCR_SIZEALL* = 32646 - OCR_NO* = 32648 - OCR_APPSTARTING* = 32650 - # SetTapePosition - TAPE_ABSOLUTE_BLOCK* = 0x00000001 - TAPE_LOGICAL_BLOCK* = 0x00000002 - TAPE_REWIND* = 0 - TAPE_SPACE_END_OF_DATA* = 0x00000004 - TAPE_SPACE_FILEMARKS* = 0x00000006 - TAPE_SPACE_RELATIVE_BLOCKS* = 0x00000005 - TAPE_SPACE_SEQUENTIAL_FMKS* = 0x00000007 - TAPE_SPACE_SEQUENTIAL_SMKS* = 0x00000009 - TAPE_SPACE_SETMARKS* = 0x00000008 - # SetUnhandledExceptionFilter - EXCEPTION_EXECUTE_HANDLER* = 1 - EXCEPTION_CONTINUE_EXECUTION* = -1 - EXCEPTION_CONTINUE_SEARCH* = 0 - - # SetWindowPos, DeferWindowPos - HWND_BOTTOM* = HWND(1) - HWND_NOTOPMOST* = HWND(-2) - HWND_TOP* = HWND(0) - HWND_TOPMOST* = HWND(-1) - -const - SWP_DRAWFRAME* = 32 - SWP_FRAMECHANGED* = 32 - SWP_HIDEWINDOW* = 128 - SWP_NOACTIVATE* = 16 - SWP_NOCOPYBITS* = 256 - SWP_NOMOVE* = 2 - SWP_NOSIZE* = 1 - SWP_NOREDRAW* = 8 - SWP_NOZORDER* = 4 - SWP_SHOWWINDOW* = 64 - SWP_NOOWNERZORDER* = 512 - SWP_NOREPOSITION* = 512 - SWP_NOSENDCHANGING* = 1024 - # SHAddToRecentDocs - # SHAppBarMessage - # SHChangeNotify - # ShellProc - HSHELL_ACTIVATESHELLWINDOW* = 3 - HSHELL_GETMINRECT* = 5 - HSHELL_LANGUAGE* = 8 - HSHELL_REDRAW* = 6 - HSHELL_TASKMAN* = 7 - HSHELL_WINDOWACTIVATED* = 4 - HSHELL_WINDOWCREATED* = 1 - HSHELL_WINDOWDESTROYED* = 2 - # SHGetFileInfo - # SHGetSpecialFolderLocation - # ShowWindow - SW_HIDE* = 0 - SW_MAXIMIZE* = 3 - SW_MINIMIZE* = 6 - SW_NORMAL* = 1 - SW_RESTORE* = 9 - SW_SHOW* = 5 - SW_SHOWDEFAULT* = 10 - SW_SHOWMAXIMIZED* = 3 - SW_SHOWMINIMIZED* = 2 - SW_SHOWMINNOACTIVE* = 7 - SW_SHOWNA* = 8 - SW_SHOWNOACTIVATE* = 4 - SW_SHOWNORMAL* = 1 - WPF_RESTORETOMAXIMIZED* = 2 - WPF_SETMINPOSITION* = 1 - # Sleep - INFINITE* = -1'i32 - # SystemParametersInfo - SPI_GETBEEP* = 1 - SPI_SETBEEP* = 2 - SPI_GETMOUSE* = 3 - SPI_SETMOUSE* = 4 - SPI_GETBORDER* = 5 - SPI_SETBORDER* = 6 - SPI_GETKEYBOARDSPEED* = 10 - SPI_SETKEYBOARDSPEED* = 11 - SPI_LANGDRIVER* = 12 - SPI_ICONHORIZONTALSPACING* = 13 - SPI_GETSCREENSAVETIMEOUT* = 14 - SPI_SETSCREENSAVETIMEOUT* = 15 - SPI_GETSCREENSAVEACTIVE* = 16 - SPI_SETSCREENSAVEACTIVE* = 17 - SPI_GETGRIDGRANULARITY* = 18 - SPI_SETGRIDGRANULARITY* = 19 - SPI_SETDESKWALLPAPER* = 20 - SPI_SETDESKPATTERN* = 21 - SPI_GETKEYBOARDDELAY* = 22 - SPI_SETKEYBOARDDELAY* = 23 - SPI_ICONVERTICALSPACING* = 24 - SPI_GETICONTITLEWRAP* = 25 - SPI_SETICONTITLEWRAP* = 26 - SPI_GETMENUDROPALIGNMENT* = 27 - SPI_SETMENUDROPALIGNMENT* = 28 - SPI_SETDOUBLECLKWIDTH* = 29 - SPI_SETDOUBLECLKHEIGHT* = 30 - SPI_GETICONTITLELOGFONT* = 31 - SPI_SETDOUBLECLICKTIME* = 32 - SPI_SETMOUSEBUTTONSWAP* = 33 - SPI_SETICONTITLELOGFONT* = 34 - SPI_GETFASTTASKSWITCH* = 35 - SPI_SETFASTTASKSWITCH* = 36 - SPI_SETDRAGFULLWINDOWS* = 37 - SPI_GETDRAGFULLWINDOWS* = 38 - SPI_GETNONCLIENTMETRICS* = 41 - SPI_SETNONCLIENTMETRICS* = 42 - - SPI_GETMINIMIZEDMETRICS* = 43 - SPI_SETMINIMIZEDMETRICS* = 44 - SPI_GETICONMETRICS* = 45 - SPI_SETICONMETRICS* = 46 - SPI_SETWORKAREA* = 47 - SPI_GETWORKAREA* = 48 - SPI_SETPENWINDOWS* = 49 - SPI_GETFILTERKEYS* = 50 - SPI_SETFILTERKEYS* = 51 - SPI_GETTOGGLEKEYS* = 52 - SPI_SETTOGGLEKEYS* = 53 - SPI_GETMOUSEKEYS* = 54 - SPI_SETMOUSEKEYS* = 55 - SPI_GETSHOWSOUNDS* = 56 - SPI_SETSHOWSOUNDS* = 57 - SPI_GETSTICKYKEYS* = 58 - SPI_SETSTICKYKEYS* = 59 - SPI_GETACCESSTIMEOUT* = 60 - SPI_SETACCESSTIMEOUT* = 61 - SPI_GETSERIALKEYS* = 62 - SPI_SETSERIALKEYS* = 63 - SPI_GETSOUNDSENTRY* = 64 - SPI_SETSOUNDSENTRY* = 65 - SPI_GETHIGHCONTRAST* = 66 - SPI_SETHIGHCONTRAST* = 67 - SPI_GETKEYBOARDPREF* = 68 - SPI_SETKEYBOARDPREF* = 69 - SPI_GETSCREENREADER* = 70 - SPI_SETSCREENREADER* = 71 - SPI_GETANIMATION* = 72 - SPI_SETANIMATION* = 73 - SPI_GETFONTSMOOTHING* = 74 - SPI_SETFONTSMOOTHING* = 75 - SPI_SETDRAGWIDTH* = 76 - SPI_SETDRAGHEIGHT* = 77 - SPI_SETHANDHELD* = 78 - SPI_GETLOWPOWERTIMEOUT* = 79 - SPI_GETPOWEROFFTIMEOUT* = 80 - SPI_SETLOWPOWERTIMEOUT* = 81 - SPI_SETPOWEROFFTIMEOUT* = 82 - SPI_GETLOWPOWERACTIVE* = 83 - SPI_GETPOWEROFFACTIVE* = 84 - SPI_SETLOWPOWERACTIVE* = 85 - SPI_SETPOWEROFFACTIVE* = 86 - SPI_SETCURSORS* = 87 - SPI_SETICONS* = 88 - SPI_GETDEFAULTINPUTLANG* = 89 - SPI_SETDEFAULTINPUTLANG* = 90 - SPI_SETLANGTOGGLE* = 91 - SPI_GETWINDOWSEXTENSION* = 92 - SPI_SETMOUSETRAILS* = 93 - SPI_GETMOUSETRAILS* = 94 - SPI_GETSNAPTODEFBUTTON* = 95 - SPI_SETSNAPTODEFBUTTON* = 96 - SPI_SCREENSAVERRUNNING* = 97 - SPI_SETSCREENSAVERRUNNING* = 97 - SPI_GETMOUSEHOVERWIDTH* = 98 - SPI_SETMOUSEHOVERWIDTH* = 99 - SPI_GETMOUSEHOVERHEIGHT* = 100 - SPI_SETMOUSEHOVERHEIGHT* = 101 - SPI_GETMOUSEHOVERTIME* = 102 - SPI_SETMOUSEHOVERTIME* = 103 - SPI_GETWHEELSCROLLLINES* = 104 - SPI_SETWHEELSCROLLLINES* = 105 - SPI_GETMENUSHOWDELAY* = 106 - SPI_SETMENUSHOWDELAY* = 107 - SPI_GETSHOWIMEUI* = 110 - SPI_SETSHOWIMEUI* = 111 - # Windows Me/2000 and higher - SPI_GETMOUSESPEED* = 112 - SPI_SETMOUSESPEED* = 113 - SPI_GETSCREENSAVERRUNNING* = 114 - SPI_GETDESKWALLPAPER* = 115 - SPI_GETACTIVEWINDOWTRACKING* = 4096 - SPI_SETACTIVEWINDOWTRACKING* = 4097 - SPI_GETMENUANIMATION* = 4098 - SPI_SETMENUANIMATION* = 4099 - SPI_GETCOMBOBOXANIMATION* = 4100 - SPI_SETCOMBOBOXANIMATION* = 4101 - SPI_GETLISTBOXSMOOTHSCROLLING* = 4102 - SPI_SETLISTBOXSMOOTHSCROLLING* = 4103 - SPI_GETGRADIENTCAPTIONS* = 4104 - SPI_SETGRADIENTCAPTIONS* = 4105 - SPI_GETKEYBOARDCUES* = 4106 - SPI_SETKEYBOARDCUES* = 4107 - SPI_GETMENUUNDERLINES* = 4106 - SPI_SETMENUUNDERLINES* = 4107 - SPI_GETACTIVEWNDTRKZORDER* = 4108 - SPI_SETACTIVEWNDTRKZORDER* = 4109 - SPI_GETHOTTRACKING* = 4110 - SPI_SETHOTTRACKING* = 4111 - SPI_GETMENUFADE* = 4114 - SPI_SETMENUFADE* = 4115 - SPI_GETSELECTIONFADE* = 4116 - SPI_SETSELECTIONFADE* = 4117 - SPI_GETTOOLTIPANIMATION* = 4118 - SPI_SETTOOLTIPANIMATION* = 4119 - SPI_GETTOOLTIPFADE* = 4120 - SPI_SETTOOLTIPFADE* = 4121 - SPI_GETCURSORSHADOW* = 4122 - SPI_SETCURSORSHADOW* = 4123 - SPI_GETUIEFFECTS* = 4158 - SPI_SETUIEFFECTS* = 4159 - SPI_GETFOREGROUNDLOCKTIMEOUT* = 8192 - SPI_SETFOREGROUNDLOCKTIMEOUT* = 8193 - SPI_GETACTIVEWNDTRKTIMEOUT* = 8194 - SPI_SETACTIVEWNDTRKTIMEOUT* = 8195 - SPI_GETFOREGROUNDFLASHCOUNT* = 8196 - SPI_SETFOREGROUNDFLASHCOUNT* = 8197 - SPI_GETCARETWIDTH* = 8198 - SPI_SETCARETWIDTH* = 8199 - # Windows XP and higher - SPI_GETMOUSESONAR* = 4124 - SPI_SETMOUSESONAR* = 4125 - SPI_GETMOUSECLICKLOCK* = 4126 - SPI_SETMOUSECLICKLOCK* = 4127 - SPI_GETMOUSEVANISH* = 4128 - SPI_SETMOUSEVANISH* = 4129 - SPI_GETFLATMENU* = 4130 - SPI_SETFLATMENU* = 4131 - SPI_GETDROPSHADOW* = 4132 - SPI_SETDROPSHADOW* = 4133 - SPI_GETBLOCKSENDINPUTRESETS* = 4134 - SPI_SETBLOCKSENDINPUTRESETS* = 4135 - SPI_GETMOUSECLICKLOCKTIME* = 8200 - SPI_SETMOUSECLICKLOCKTIME* = 8201 - SPI_GETFONTSMOOTHINGTYPE* = 8202 - SPI_SETFONTSMOOTHINGTYPE* = 8203 - SPI_GETFONTSMOOTHINGCONTRAST* = 8204 - SPI_SETFONTSMOOTHINGCONTRAST* = 8205 - SPI_GETFOCUSBORDERWIDTH* = 8206 - SPI_SETFOCUSBORDERWIDTH* = 8207 - SPI_GETFOCUSBORDERHEIGHT* = 8208 - SPI_SETFOCUSBORDERHEIGHT* = 8209 - SPI_GETFONTSMOOTHINGORIENTATION* = 8210 - SPI_SETFONTSMOOTHINGORIENTATION* = 8211 - # constants for SPI_GETFONTSMOOTHINGTYPE and SPI_SETFONTSMOOTHINGTYPE: - FE_FONTSMOOTHINGSTANDARD* = 1 - FE_FONTSMOOTHINGCLEARTYPE* = 2 - FE_FONTSMOOTHINGDOCKING* = 32768 - # constants for SPI_GETFONTSMOOTHINGORIENTATION and SPI_SETFONTSMOOTHINGORIENTATION: - FE_FONTSMOOTHINGORIENTATIONBGR* = 0 - FE_FONTSMOOTHINGORIENTATIONRGB* = 1 - # Flags - SPIF_UPDATEINIFILE* = 1 - SPIF_SENDWININICHANGE* = 2 - SPIF_SENDCHANGE* = 2 - # TrackPopupMenu, TrackPopMenuEx - TPM_CENTERALIGN* = 0x00000004 - TPM_LEFTALIGN* = 0 - TPM_RIGHTALIGN* = 0x00000008 - TPM_LEFTBUTTON* = 0 - TPM_RIGHTBUTTON* = 0x00000002 - TPM_HORIZONTAL* = 0 - TPM_VERTICAL* = 0x00000040 - # TranslateCharsetInfo - TCI_SRCCHARSET* = 1 - TCI_SRCCODEPAGE* = 2 - TCI_SRCFONTSIG* = 3 - # VerFindFile - VFFF_ISSHAREDFILE* = 1 - VFF_CURNEDEST* = 1 - VFF_FILEINUSE* = 2 - VFF_BUFFTOOSMALL* = 4 - # VerInstallFile - VIFF_FORCEINSTALL* = 1 - VIFF_DONTDELETEOLD* = 2 - VIF_TEMPFILE* = 0x00000001 - VIF_MISMATCH* = 0x00000002 - VIF_SRCOLD* = 0x00000004 - VIF_DIFFLANG* = 0x00000008 - VIF_DIFFCODEPG* = 0x00000010 - VIF_DIFFTYPE* = 0x00000020 - VIF_WRITEPROT* = 0x00000040 - VIF_FILEINUSE* = 0x00000080 - VIF_OUTOFSPACE* = 0x00000100 - VIF_ACCESSVIOLATION* = 0x00000200 - VIF_SHARINGVIOLATION* = 0x00000400 - VIF_CANNOTCREATE* = 0x00000800 - VIF_CANNOTDELETE* = 0x00001000 - VIF_CANNOTDELETECUR* = 0x00004000 - VIF_CANNOTRENAME* = 0x00002000 - VIF_OUTOFMEMORY* = 0x00008000 - VIF_CANNOTREADSRC* = 0x00010000 - VIF_CANNOTREADDST* = 0x00020000 - VIF_BUFFTOOSMALL* = 0x00040000 - # WideCharToMultiByte - WC_COMPOSITECHECK* = 512 - WC_DISCARDNS* = 16 - WC_SEPCHARS* = 32 - WC_DEFAULTCHAR* = 64 - # WinHelp - HELP_COMMAND* = 0x00000102 - HELP_CONTENTS* = 0x00000003 - HELP_CONTEXT* = 0x00000001 - HELP_CONTEXTPOPUP* = 0x00000008 - HELP_FORCEFILE* = 0x00000009 - HELP_HELPONHELP* = 0x00000004 - HELP_INDEX* = 0x00000003 - HELP_KEY* = 0x00000101 - HELP_MULTIKEY* = 0x00000201 - HELP_PARTIALKEY* = 0x00000105 - HELP_QUIT* = 0x00000002 - HELP_SETCONTENTS* = 0x00000005 - HELP_SETINDEX* = 0x00000005 - HELP_CONTEXTMENU* = 0x0000000A - HELP_FINDER* = 0x0000000B - HELP_WM_HELP* = 0x0000000C - HELP_TCARD* = 0x00008000 - HELP_TCARD_DATA* = 0x00000010 - HELP_TCARD_OTHER_CALLER* = 0x00000011 - # WNetAddConnectino2 - CONNECT_UPDATE_PROFILE* = 1 - # WNetConnectionDialog, WNetDisconnectDialog, WNetOpenEnum - RESOURCETYPE_DISK* = 1 - RESOURCETYPE_PRINT* = 2 - RESOURCETYPE_ANY* = 0 - RESOURCE_CONNECTED* = 1 - RESOURCE_GLOBALNET* = 2 - RESOURCE_REMEMBERED* = 3 - RESOURCEUSAGE_CONNECTABLE* = 1 - RESOURCEUSAGE_CONTAINER* = 2 - # WNetGetResourceInformation, WNetGetResourceParent - WN_BAD_NETNAME* = 0x00000043 - WN_EXTENDED_ERROR* = 0x000004B8 - WN_MORE_DATA* = 0x000000EA - WN_NO_NETWORK* = 0x000004C6 - WN_SUCCESS* = 0 - WN_ACCESS_DENIED* = 0x00000005 - WN_BAD_PROVIDER* = 0x000004B4 - WN_NOT_AUTHENTICATED* = 0x000004DC - # WNetGetUniversalName - UNIVERSAL_NAME_INFO_LEVEL* = 1 - REMOTE_NAME_INFO_LEVEL* = 2 - # GetExitCodeThread - STILL_ACTIVE* = 0x00000103 - # COMMPROP structure - SP_SERIALCOMM* = 0x00000001 - BAUD_075* = 0x00000001 - BAUD_110* = 0x00000002 - BAUD_134_5* = 0x00000004 - BAUD_150* = 0x00000008 - BAUD_300* = 0x00000010 - BAUD_600* = 0x00000020 - BAUD_1200* = 0x00000040 - BAUD_1800* = 0x00000080 - BAUD_2400* = 0x00000100 - BAUD_4800* = 0x00000200 - BAUD_7200* = 0x00000400 - BAUD_9600* = 0x00000800 - BAUD_14400* = 0x00001000 - BAUD_19200* = 0x00002000 - BAUD_38400* = 0x00004000 - BAUD_56K* = 0x00008000 - BAUD_57600* = 0x00040000 - BAUD_115200* = 0x00020000 - BAUD_128K* = 0x00010000 - BAUD_USER* = 0x10000000 - PST_FAX* = 0x00000021 - PST_LAT* = 0x00000101 - PST_MODEM* = 0x00000006 - PST_NETWORK_BRIDGE* = 0x00000100 - PST_PARALLELPORT* = 0x00000002 - PST_RS232* = 0x00000001 - PST_RS422* = 0x00000003 - PST_RS423* = 0x00000004 - PST_RS449* = 0x00000005 - PST_SCANNER* = 0x00000022 - PST_TCPIP_TELNET* = 0x00000102 - PST_UNSPECIFIED* = 0 - PST_X25* = 0x00000103 - PCF_16BITMODE* = 0x00000200 - PCF_DTRDSR* = 0x00000001 - PCF_INTTIMEOUTS* = 0x00000080 - PCF_PARITY_CHECK* = 0x00000008 - PCF_RLSD* = 0x00000004 - PCF_RTSCTS* = 0x00000002 - PCF_SETXCHAR* = 0x00000020 - PCF_SPECIALCHARS* = 0x00000100 - PCF_TOTALTIMEOUTS* = 0x00000040 - PCF_XONXOFF* = 0x00000010 - SP_BAUD* = 0x00000002 - SP_DATABITS* = 0x00000004 - SP_HANDSHAKING* = 0x00000010 - SP_PARITY* = 0x00000001 - SP_PARITY_CHECK* = 0x00000020 - SP_RLSD* = 0x00000040 - SP_STOPBITS* = 0x00000008 - DATABITS_5* = 1 - DATABITS_6* = 2 - DATABITS_7* = 4 - DATABITS_8* = 8 - DATABITS_16* = 16 - DATABITS_16X* = 32 - STOPBITS_10* = 1 - STOPBITS_15* = 2 - STOPBITS_20* = 4 - PARITY_NONE* = 256 - PARITY_ODD* = 512 - PARITY_EVEN* = 1024 - PARITY_MARK* = 2048 - PARITY_SPACE* = 4096 - COMMPROP_INITIALIZED* = 0xE73CF52E - # DCB structure - CBR_110* = 110 - CBR_300* = 300 - CBR_600* = 600 - CBR_1200* = 1200 - CBR_2400* = 2400 - CBR_4800* = 4800 - CBR_9600* = 9600 - CBR_14400* = 14400 - CBR_19200* = 19200 - CBR_38400* = 38400 - CBR_56000* = 56000 - CBR_57600* = 57600 - CBR_115200* = 115200 - CBR_128000* = 128000 - CBR_256000* = 256000 - DTR_CONTROL_DISABLE* = 0 - DTR_CONTROL_ENABLE* = 1 - DTR_CONTROL_HANDSHAKE* = 2 - RTS_CONTROL_DISABLE* = 0 - RTS_CONTROL_ENABLE* = 1 - RTS_CONTROL_HANDSHAKE* = 2 - RTS_CONTROL_TOGGLE* = 3 - EVENPARITY* = 2 - MARKPARITY* = 3 - NOPARITY* = 0 - ODDPARITY* = 1 - SPACEPARITY* = 4 - ONESTOPBIT* = 0 - ONE5STOPBITS* = 1 - TWOSTOPBITS* = 2 - # Debugging events - CREATE_PROCESS_DEBUG_EVENT* = 3 - CREATE_THREAD_DEBUG_EVENT* = 2 - EXCEPTION_DEBUG_EVENT* = 1 - EXIT_PROCESS_DEBUG_EVENT* = 5 - EXIT_THREAD_DEBUG_EVENT* = 4 - LOAD_DLL_DEBUG_EVENT* = 6 - OUTPUT_DEBUG_STRING_EVENT* = 8 - UNLOAD_DLL_DEBUG_EVENT* = 7 - RIP_EVENT* = 9 - # PROCESS_HEAP_ENTRY structure - PROCESS_HEAP_REGION* = 1 - PROCESS_HEAP_UNCOMMITTED_RANGE* = 2 - PROCESS_HEAP_ENTRY_BUSY* = 4 - PROCESS_HEAP_ENTRY_MOVEABLE* = 16 - PROCESS_HEAP_ENTRY_DDESHARE* = 32 - # Win32s - HINSTANCE_ERROR* = 32 - # WIN32_STREAM_ID structure - BACKUP_DATA* = 1 - BACKUP_EA_DATA* = 2 - BACKUP_SECURITY_DATA* = 3 - BACKUP_ALTERNATE_DATA* = 4 - BACKUP_LINK* = 5 - STREAM_MODIFIED_WHEN_READ* = 1 - STREAM_CONTAINS_SECURITY* = 2 - # STARTUPINFO structure - STARTF_USESHOWWINDOW* = 1 - STARTF_USEPOSITION* = 4 - STARTF_USESIZE* = 2 - STARTF_USECOUNTCHARS* = 8 - STARTF_USEFILLATTRIBUTE* = 16 - STARTF_RUNFULLSCREEN* = 32 - STARTF_FORCEONFEEDBACK* = 64 - STARTF_FORCEOFFFEEDBACK* = 128 - STARTF_USESTDHANDLES* = 256 - STARTF_USEHOTKEY* = 512 - # OSVERSIONINFO structure - VER_PLATFORM_WIN32s* = 0 - VER_PLATFORM_WIN32_WINDOWS* = 1 - VER_PLATFORM_WIN32_NT* = 2 - # More versions - VER_SERVER_NT* = 0x80000000 - VER_WORKSTATION_NT* = 0x40000000 - VER_SUITE_SMALLBUSINESS* = 0x00000001 - VER_SUITE_ENTERPRISE* = 0x00000002 - VER_SUITE_BACKOFFICE* = 0x00000004 - VER_SUITE_COMMUNICATIONS* = 0x00000008 - VER_SUITE_TERMINAL* = 0x00000010 - VER_SUITE_SMALLBUSINESS_RESTRICTED* = 0x00000020 - VER_SUITE_EMBEDDEDNT* = 0x00000040 - VER_SUITE_DATACENTER* = 0x00000080 - VER_SUITE_SINGLEUSERTS* = 0x00000100 - VER_SUITE_PERSONAL* = 0x00000200 - VER_SUITE_BLADE* = 0x00000400 - VER_SUITE_EMBEDDED_RESTRICTED* = 0x00000800 - # PROPSHEETPAGE structure - MAXPROPPAGES* = 100 - PSP_DEFAULT* = 0 - PSP_DLGINDIRECT* = 1 - PSP_HASHELP* = 32 - PSP_USECALLBACK* = 128 - PSP_USEHICON* = 2 - PSP_USEICONID* = 4 - PSP_USEREFPARENT* = 64 - PSP_USETITLE* = 8 - PSP_RTLREADING* = 16 - # PROPSHEETHEADER structure - PSH_DEFAULT* = 0 - PSH_HASHELP* = 512 - PSH_MODELESS* = 1024 - PSH_NOAPPLYNOW* = 128 - PSH_PROPSHEETPAGE* = 8 - PSH_PROPTITLE* = 1 - PSH_USECALLBACK* = 256 - PSH_USEHICON* = 2 - PSH_USEICONID* = 4 - PSH_USEPSTARTPAGE* = 64 - PSH_WIZARD* = 32 - PSH_RTLREADING* = 2048 - PSCB_INITIALIZED* = 1 - PSCB_PRECREATE* = 2 - # PSN_APPLY message - PSNRET_NOERROR* = 0 - PSNRET_INVALID_NOCHANGEPAGE* = 2 - # Property Sheet - PSBTN_APPLYNOW* = 4 - PSBTN_BACK* = 0 - PSBTN_CANCEL* = 5 - PSBTN_FINISH* = 2 - PSBTN_HELP* = 6 - PSBTN_NEXT* = 1 - PSBTN_OK* = 3 - PSWIZB_BACK* = 1 - PSWIZB_NEXT* = 2 - PSWIZB_FINISH* = 4 - PSWIZB_DISABLEDFINISH* = 8 - ID_PSREBOOTSYSTEM* = 3 - ID_PSRESTARTWINDOWS* = 2 - WIZ_BODYCX* = 184 - WIZ_BODYX* = 92 - WIZ_CXBMP* = 80 - WIZ_CXDLG* = 276 - WIZ_CYDLG* = 140 - - # VX_FIXEDFILEINFO structure - VS_FILE_INFO* = cast[MAKEINTRESOURCE](16) - -const - VS_VERSION_INFO* = 1 - VS_FF_DEBUG* = 0x00000001 - VS_FF_INFOINFERRED* = 0x00000010 - VS_FF_PATCHED* = 0x00000004 - VS_FF_PRERELEASE* = 0x00000002 - VS_FF_PRIVATEBUILD* = 0x00000008 - VS_FF_SPECIALBUILD* = 0x00000020 - VOS_UNKNOWN* = 0 - VOS_DOS* = 0x00010000 - VOS_OS216* = 0x00020000 - VOS_OS232* = 0x00030000 - VOS_NT* = 0x00040000 - VOS_DOS_WINDOWS16* = 0x00010001 - VOS_DOS_WINDOWS32* = 0x00010004 - VOS_OS216_PM16* = 0x00020002 - VOS_OS232_PM32* = 0x00030003 - VOS_NT_WINDOWS32* = 0x00040004 - VFT_UNKNOWN* = 0 - VFT_APP* = 0x00000001 - VFT_DLL* = 0x00000002 - VFT_DRV* = 0x00000003 - VFT_FONT* = 0x00000004 - VFT_VXD* = 0x00000005 - VFT_STATIC_LIB* = 0x00000007 - VFT2_UNKNOWN* = 0 - VFT2_DRV_PRINTER* = 0x00000001 - VFT2_DRV_KEYBOARD* = 0x00000002 - VFT2_DRV_LANGUAGE* = 0x00000003 - VFT2_DRV_DISPLAY* = 0x00000004 - VFT2_DRV_MOUSE* = 0x00000005 - VFT2_DRV_NETWORK* = 0x00000006 - VFT2_DRV_SYSTEM* = 0x00000007 - VFT2_DRV_INSTALLABLE* = 0x00000008 - VFT2_DRV_SOUND* = 0x00000009 - VFT2_FONT_RASTER* = 0x00000001 - VFT2_FONT_VECTOR* = 0x00000002 - VFT2_FONT_TRUETYPE* = 0x00000003 - # PANOSE structure - PAN_ANY* = 0 - PAN_NO_FIT* = 1 - PAN_FAMILY_TEXT_DISPLAY* = 2 - PAN_FAMILY_SCRIPT* = 3 - PAN_FAMILY_DECORATIVE* = 4 - PAN_FAMILY_PICTORIAL* = 5 - PAN_SERIF_COVE* = 2 - PAN_SERIF_OBTUSE_COVE* = 3 - PAN_SERIF_SQUARE_COVE* = 4 - PAN_SERIF_OBTUSE_SQUARE_COVE* = 5 - PAN_SERIF_SQUARE* = 6 - PAN_SERIF_THIN* = 7 - PAN_SERIF_BONE* = 8 - PAN_SERIF_EXAGGERATED* = 9 - PAN_SERIF_TRIANGLE* = 10 - PAN_SERIF_NORMAL_SANS* = 11 - PAN_SERIF_OBTUSE_SANS* = 12 - PAN_SERIF_PERP_SANS* = 13 - PAN_SERIF_FLARED* = 14 - PAN_SERIF_ROUNDED* = 15 - PAN_WEIGHT_VERY_LIGHT* = 2 - PAN_WEIGHT_LIGHT* = 3 - PAN_WEIGHT_THIN* = 4 - PAN_WEIGHT_BOOK* = 5 - PAN_WEIGHT_MEDIUM* = 6 - PAN_WEIGHT_DEMI* = 7 - PAN_WEIGHT_BOLD* = 8 - PAN_WEIGHT_HEAVY* = 9 - PAN_WEIGHT_BLACK* = 10 - PAN_WEIGHT_NORD* = 11 - PAN_PROP_OLD_STYLE* = 2 - PAN_PROP_MODERN* = 3 - PAN_PROP_EVEN_WIDTH* = 4 - PAN_PROP_EXPANDED* = 5 - PAN_PROP_CONDENSED* = 6 - PAN_PROP_VERY_EXPANDED* = 7 - PAN_PROP_VERY_CONDENSED* = 8 - PAN_PROP_MONOSPACED* = 9 - PAN_CONTRAST_NONE* = 2 - PAN_CONTRAST_VERY_LOW* = 3 - PAN_CONTRAST_LOW* = 4 - PAN_CONTRAST_MEDIUM_LOW* = 5 - PAN_CONTRAST_MEDIUM* = 6 - PAN_CONTRAST_MEDIUM_HIGH* = 7 - PAN_CONTRAST_HIGH* = 8 - PAN_CONTRAST_VERY_HIGH* = 9 - PAN_STROKE_GRADUAL_DIAG* = 2 - PAN_STROKE_GRADUAL_TRAN* = 3 - PAN_STROKE_GRADUAL_VERT* = 4 - PAN_STROKE_GRADUAL_HORZ* = 5 - PAN_STROKE_RAPID_VERT* = 6 - PAN_STROKE_RAPID_HORZ* = 7 - PAN_STROKE_INSTANT_VERT* = 8 - PAN_STRAIGHT_ARMS_HORZ* = 2 - PAN_STRAIGHT_ARMS_WEDGE* = 3 - PAN_STRAIGHT_ARMS_VERT* = 4 - PAN_STRAIGHT_ARMS_SINGLE_SERIF* = 5 - PAN_STRAIGHT_ARMS_DOUBLE_SERIF* = 6 - PAN_BENT_ARMS_HORZ* = 7 - PAN_BENT_ARMS_VERT* = 9 - PAN_BENT_ARMS_WEDGE* = 8 - PAN_BENT_ARMS_SINGLE_SERIF* = 10 - PAN_BENT_ARMS_DOUBLE_SERIF* = 11 - PAN_LETT_NORMAL_CONTACT* = 2 - PAN_LETT_NORMAL_WEIGHTED* = 3 - PAN_LETT_NORMAL_BOXED* = 4 - PAN_LETT_NORMAL_FLATTENED* = 5 - PAN_LETT_NORMAL_ROUNDED* = 6 - PAN_LETT_NORMAL_OFF_CENTER* = 7 - PAN_LETT_NORMAL_SQUARE* = 8 - PAN_LETT_OBLIQUE_CONTACT* = 9 - PAN_LETT_OBLIQUE_WEIGHTED* = 10 - PAN_LETT_OBLIQUE_BOXED* = 11 - PAN_LETT_OBLIQUE_FLATTENED* = 12 - PAN_LETT_OBLIQUE_ROUNDED* = 13 - PAN_LETT_OBLIQUE_OFF_CENTER* = 14 - PAN_LETT_OBLIQUE_SQUARE* = 15 - PAN_MIDLINE_STANDARD_TRIMMED* = 2 - PAN_MIDLINE_STANDARD_POINTED* = 3 - PAN_MIDLINE_STANDARD_SERIFED* = 4 - PAN_MIDLINE_HIGH_TRIMMED* = 5 - PAN_MIDLINE_HIGH_POINTED* = 6 - PAN_MIDLINE_HIGH_SERIFED* = 7 - PAN_MIDLINE_CONSTANT_TRIMMED* = 8 - PAN_MIDLINE_CONSTANT_POINTED* = 9 - PAN_MIDLINE_CONSTANT_SERIFED* = 10 - PAN_MIDLINE_LOW_TRIMMED* = 11 - PAN_MIDLINE_LOW_POINTED* = 12 - PAN_MIDLINE_LOW_SERIFED* = 13 - PAN_XHEIGHT_CONSTANT_SMALL* = 2 - PAN_XHEIGHT_CONSTANT_STD* = 3 - PAN_XHEIGHT_CONSTANT_LARGE* = 4 - PAN_XHEIGHT_DUCKING_SMALL* = 5 - PAN_XHEIGHT_DUCKING_STD* = 6 - PAN_XHEIGHT_DUCKING_LARGE* = 7 - # PALETTENTRY structure - PC_EXPLICIT* = 2 - PC_NOCOLLAPSE* = 4 - PC_RESERVED* = 1 - # LOGBRUSH structure - BS_DIBPATTERN* = 5 - BS_DIBPATTERN8X8* = 8 - BS_DIBPATTERNPT* = 6 - BS_HATCHED* = 2 - BS_HOLLOW* = 1 - BS_NULL* = 1 - BS_PATTERN* = 3 - BS_PATTERN8X8* = 7 - BS_SOLID* = 0 - # DEVMODE structure, field selection bits - DM_ORIENTATION* = 0x00000001 - DM_PAPERSIZE* = 0x00000002 - DM_PAPERLENGTH* = 0x00000004 - DM_PAPERWIDTH* = 0x00000008 - DM_SCALE* = 0x00000010 - DM_POSITION* = 0x00000020 - DM_NUP* = 0x00000040 - DM_DISPLAYORIENTATION* = 0x00000080 - DM_COPIES* = 0x00000100 - DM_DEFAULTSOURCE* = 0x00000200 - DM_PRINTQUALITY* = 0x00000400 - DM_COLOR* = 0x00000800 - DM_DUPLEX* = 0x00001000 - DM_YRESOLUTION* = 0x00002000 - DM_TTOPTION* = 0x00004000 - DM_COLLATE* = 0x00008000 - DM_FORMNAME* = 0x00010000 - DM_LOGPIXELS* = 0x00020000 - DM_BITSPERPEL* = 0x00040000 - DM_PELSWIDTH* = 0x00080000 - DM_PELSHEIGHT* = 0x00100000 - DM_DISPLAYFLAGS* = 0x00200000 - DM_DISPLAYFREQUENCY* = 0x00400000 - DM_ICMMETHOD* = 0x00800000 - DM_ICMINTENT* = 0x01000000 - DM_MEDIATYPE* = 0x02000000 - DM_DITHERTYPE* = 0x04000000 - DM_PANNINGWIDTH* = 0x08000000 - DM_PANNINGHEIGHT* = 0x10000000 - DM_DISPLAYFIXEDOUTPUT* = 0x20000000 - # orientation selections - DMORIENT_LANDSCAPE* = 2 - DMORIENT_PORTRAIT* = 1 - # paper selections - DMPAPER_LETTER* = 1 - DMPAPER_LEGAL* = 5 - DMPAPER_A4* = 9 - DMPAPER_CSHEET* = 24 - DMPAPER_DSHEET* = 25 - DMPAPER_ESHEET* = 26 - DMPAPER_LETTERSMALL* = 2 - DMPAPER_TABLOID* = 3 - DMPAPER_LEDGER* = 4 - DMPAPER_STATEMENT* = 6 - DMPAPER_EXECUTIVE* = 7 - DMPAPER_A3* = 8 - DMPAPER_A4SMALL* = 10 - DMPAPER_A5* = 11 - DMPAPER_B4* = 12 - DMPAPER_B5* = 13 - DMPAPER_FOLIO* = 14 - DMPAPER_QUARTO* = 15 - DMPAPER_10X14* = 16 - DMPAPER_11X17* = 17 - DMPAPER_NOTE* = 18 - DMPAPER_ENV_9* = 19 - DMPAPER_ENV_10* = 20 - DMPAPER_ENV_11* = 21 - DMPAPER_ENV_12* = 22 - DMPAPER_ENV_14* = 23 - DMPAPER_ENV_DL* = 27 - DMPAPER_ENV_C5* = 28 - DMPAPER_ENV_C3* = 29 - DMPAPER_ENV_C4* = 30 - DMPAPER_ENV_C6* = 31 - DMPAPER_ENV_C65* = 32 - DMPAPER_ENV_B4* = 33 - DMPAPER_ENV_B5* = 34 - DMPAPER_ENV_B6* = 35 - DMPAPER_ENV_ITALY* = 36 - DMPAPER_ENV_MONARCH* = 37 - DMPAPER_ENV_PERSONAL* = 38 - DMPAPER_FANFOLD_US* = 39 - DMPAPER_FANFOLD_STD_GERMAN* = 40 - DMPAPER_FANFOLD_LGL_GERMAN* = 41 - DMPAPER_ISO_B4* = 42 - DMPAPER_JAPANESE_POSTCARD* = 43 - DMPAPER_9X11* = 44 - DMPAPER_10X11* = 45 - DMPAPER_15X11* = 46 - DMPAPER_ENV_INVITE* = 47 - DMPAPER_RESERVED_48* = 48 - DMPAPER_RESERVED_49* = 49 - DMPAPER_LETTER_EXTRA* = 50 - DMPAPER_LEGAL_EXTRA* = 51 - DMPAPER_TABLOID_EXTRA* = 52 - DMPAPER_A4_EXTRA* = 53 - DMPAPER_LETTER_TRANSVERSE* = 54 - DMPAPER_A4_TRANSVERSE* = 55 - DMPAPER_LETTER_EXTRA_TRANSVERSE* = 56 - DMPAPER_A_PLUS* = 57 - DMPAPER_B_PLUS* = 58 - DMPAPER_LETTER_PLUS* = 59 - DMPAPER_A4_PLUS* = 60 - DMPAPER_A5_TRANSVERSE* = 61 - DMPAPER_B5_TRANSVERSE* = 62 - DMPAPER_A3_EXTRA* = 63 - DMPAPER_A5_EXTRA* = 64 - DMPAPER_B5_EXTRA* = 65 - DMPAPER_A2* = 66 - DMPAPER_A3_TRANSVERSE* = 67 - DMPAPER_A3_EXTRA_TRANSVERSE* = 68 - DMPAPER_DBL_JAPANESE_POSTCARD* = 69 - DMPAPER_A6* = 70 - DMPAPER_JENV_KAKU2* = 71 - DMPAPER_JENV_KAKU3* = 72 - DMPAPER_JENV_CHOU3* = 73 - DMPAPER_JENV_CHOU4* = 74 - DMPAPER_LETTER_ROTATED* = 75 - DMPAPER_A3_ROTATED* = 76 - DMPAPER_A4_ROTATED* = 77 - DMPAPER_A5_ROTATED* = 78 - DMPAPER_B4_JIS_ROTATED* = 79 - DMPAPER_B5_JIS_ROTATED* = 80 - DMPAPER_JAPANESE_POSTCARD_ROTATED* = 81 - DMPAPER_DBL_JAPANESE_POSTCARD_ROTATED* = 82 - DMPAPER_A6_ROTATED* = 83 - DMPAPER_JENV_KAKU2_ROTATED* = 84 - DMPAPER_JENV_KAKU3_ROTATED* = 85 - DMPAPER_JENV_CHOU3_ROTATED* = 86 - DMPAPER_JENV_CHOU4_ROTATED* = 87 - DMPAPER_B6_JIS* = 88 - DMPAPER_B6_JIS_ROTATED* = 89 - DMPAPER_12X11* = 90 - DMPAPER_JENV_YOU4* = 91 - DMPAPER_JENV_YOU4_ROTATED* = 92 - DMPAPER_P16K* = 93 - DMPAPER_P32K* = 94 - DMPAPER_P32KBIG* = 95 - DMPAPER_PENV_1* = 96 - DMPAPER_PENV_2* = 97 - DMPAPER_PENV_3* = 98 - DMPAPER_PENV_4* = 99 - DMPAPER_PENV_5* = 100 - DMPAPER_PENV_6* = 101 - DMPAPER_PENV_7* = 102 - DMPAPER_PENV_8* = 103 - DMPAPER_PENV_9* = 104 - DMPAPER_PENV_10* = 105 - DMPAPER_P16K_ROTATED* = 106 - DMPAPER_P32K_ROTATED* = 107 - DMPAPER_P32KBIG_ROTATED* = 108 - DMPAPER_PENV_1_ROTATED* = 109 - DMPAPER_PENV_2_ROTATED* = 110 - DMPAPER_PENV_3_ROTATED* = 111 - DMPAPER_PENV_4_ROTATED* = 112 - DMPAPER_PENV_5_ROTATED* = 113 - DMPAPER_PENV_6_ROTATED* = 114 - DMPAPER_PENV_7_ROTATED* = 115 - DMPAPER_PENV_8_ROTATED* = 116 - DMPAPER_PENV_9_ROTATED* = 117 - DMPAPER_PENV_10_ROTATED* = 118 - DMPAPER_USER* = 256 - # bin selections - DMBIN_UPPER* = 1 - DMBIN_ONLYONE* = 1 - DMBIN_LOWER* = 2 - DMBIN_MIDDLE* = 3 - DMBIN_MANUAL* = 4 - DMBIN_ENVELOPE* = 5 - DMBIN_ENVMANUAL* = 6 - DMBIN_AUTO* = 7 - DMBIN_TRACTOR* = 8 - DMBIN_SMALLFMT* = 9 - DMBIN_LARGEFMT* = 10 - DMBIN_LARGECAPACITY* = 11 - DMBIN_CASSETTE* = 14 - DMBIN_FORMSOURCE* = 15 - DMBIN_USER* = 256 - # print qualities - DMRES_DRAFT* = -1 - DMRES_LOW* = -2 - DMRES_MEDIUM* = -3 - DMRES_HIGH* = -4 - # color enable/disable for color printers - DMCOLOR_MONOCHROME* = 1 - DMCOLOR_COLOR* = 2 - # duplex enable - DMDUP_SIMPLEX* = 1 - DMDUP_VERTICAL* = 2 - DMDUP_HORIZONTAL* = 3 - # TrueType options - DMTT_BITMAP* = 1 - DMTT_DOWNLOAD* = 2 - DMTT_SUBDEV* = 3 - # Collation selections - DMCOLLATE_TRUE* = 1 - DMCOLLATE_FALSE* = 0 - # DEVMODE dmDisplayOrientation specifiations - DMDO_DEFAULT* = 0 - DMDO_90* = 1 - DMDO_180* = 2 - DMDO_270* = 3 - # DEVMODE dmDisplayFixedOutput specifiations - DMDFO_DEFAULT* = 0 - DMDFO_STRETCH* = 1 - DMDFO_CENTER* = 2 - # Deprecated - #DM_GRAYSCALE* = 1 - #DM_INTERLACED* = 2 - DMDISPLAYFLAGS_TEXTMODE* = 0x00000004 - # dmNup , multiple logical page per physical page options - DMNUP_SYSTEM* = 1 - DMNUP_ONEUP* = 2 - # ICM methods - DMICMMETHOD_NONE* = 1 - DMICMMETHOD_SYSTEM* = 2 - DMICMMETHOD_DRIVER* = 3 - DMICMMETHOD_DEVICE* = 4 - DMICMMETHOD_USER* = 256 - # ICM Intents - DMICM_SATURATE* = 1 - DMICM_CONTRAST* = 2 - DMICM_COLORMETRIC* = 3 - DMICM_USER* = 256 - # Media types - DMMEDIA_STANDARD* = 1 - DMMEDIA_TRANSPARENCY* = 2 - DMMEDIA_GLOSSY* = 3 - DMMEDIA_USER* = 256 - # Dither types - DMDITHER_NONE* = 1 - DMDITHER_COARSE* = 2 - DMDITHER_FINE* = 3 - DMDITHER_LINEART* = 4 - DMDITHER_GRAYSCALE* = 10 - DMDITHER_USER* = 256 - # RGNDATAHEADER structure - RDH_RECTANGLES* = 1 - # TTPOLYGONHEADER structure - TT_POLYGON_TYPE* = 24 - # TTPOLYCURVE structure - TT_PRIM_LINE* = 1 - TT_PRIM_QSPLINE* = 2 - # GCP_RESULTS structure - GCPCLASS_ARABIC* = 2 - GCPCLASS_HEBREW* = 2 - GCPCLASS_LATIN* = 1 - GCPCLASS_LATINNUMBER* = 5 - GCPCLASS_LOCALNUMBER* = 4 - GCPCLASS_LATINNUMERICSEPARATOR* = 7 - GCPCLASS_LATINNUMERICTERMINATOR* = 6 - GCPCLASS_NEUTRAL* = 3 - GCPCLASS_NUMERICSEPARATOR* = 8 - GCPCLASS_PREBOUNDLTR* = 128 - GCPCLASS_PREBOUNDRTL* = 64 - GCPCLASS_POSTBOUNDLTR* = 32 - GCPCLASS_POSTBOUNDRTL* = 16 - GCPGLYPH_LINKBEFORE* = 32768 - GCPGLYPH_LINKAFTER* = 16384 - # RASTERIZER_STATUS structure - TT_AVAILABLE* = 1 - TT_ENABLED* = 2 - # COLORADJUSTMENT structure - CA_NEGATIVE* = 1 - CA_LOG_FILTER* = 2 - ILLUMINANT_DEVICE_DEFAULT* = 0 - ILLUMINANT_A* = 1 - ILLUMINANT_B* = 2 - ILLUMINANT_C* = 3 - ILLUMINANT_D50* = 4 - ILLUMINANT_D55* = 5 - ILLUMINANT_D65* = 6 - ILLUMINANT_D75* = 7 - ILLUMINANT_F2* = 8 - ILLUMINANT_TUNGSTEN* = 1 - ILLUMINANT_DAYLIGHT* = 3 - ILLUMINANT_FLUORESCENT* = 8 - ILLUMINANT_NTSC* = 3 - # DOCINFO structure - DI_APPBANDING* = 1 - # EMRMETAHEADER structure - EMR_HEADER* = 1 - ENHMETA_SIGNATURE* = 1179469088 - # RTF event masks - ENM_CHANGE* = 1 - ENM_CORRECTTEXT* = 4194304 - ENM_DROPFILES* = 1048576 - ENM_KEYEVENTS* = 65536 - ENM_MOUSEEVENTS* = 131072 - ENM_PROTECTED* = 2097152 - ENM_REQUESTRESIZE* = 262144 - ENM_SCROLL* = 4 - ENM_SELCHANGE* = 524288 - ENM_UPDATE* = 2 - ENM_NONE* = 0 - # RTF styles - ES_DISABLENOSCROLL* = 8192 - ES_EX_NOCALLOLEINIT* = 16777216 - ES_NOIME* = 524288 - ES_SAVESEL* = 32768 - ES_SELFIME* = 262144 - ES_SUNKEN* = 16384 - ES_VERTICAL* = 4194304 - ES_SELECTIONBAR* = 16777216 - # EM_SETOPTIONS message - ECOOP_SET* = 1 - ECOOP_OR* = 2 - ECOOP_AND* = 3 - ECOOP_XOR* = 4 - ECO_AUTOWORDSELECTION* = 1 - ECO_AUTOVSCROLL* = 64 - ECO_AUTOHSCROLL* = 128 - ECO_NOHIDESEL* = 256 - ECO_READONLY* = 2048 - ECO_WANTRETURN* = 4096 - ECO_SAVESEL* = 32768 - ECO_SELECTIONBAR* = 16777216 - ECO_VERTICAL* = 4194304 - # EM_SETCHARFORMAT message - SCF_WORD* = 2 - SCF_SELECTION* = 1 - # EM_STREAMOUT message - SF_TEXT* = 1 - SF_RTF* = 2 - SF_RTFNOOBJS* = 3 - SF_TEXTIZED* = 4 - SFF_SELECTION* = 32768 - SFF_PLAINRTF* = 16384 - # EM_FINDWORDBREAK message - WB_CLASSIFY* = 3 - #WB_ISDELIMITER = 2; - # WB_LEFT = 0; already above - WB_LEFTBREAK* = 6 - WB_PREVBREAK* = 6 - WB_MOVEWORDLEFT* = 4 - WB_MOVEWORDPREV* = 4 - WB_MOVEWORDRIGHT* = 5 - WB_MOVEWORDNEXT* = 5 - #WB_RIGHT = 1;already above - WB_RIGHTBREAK* = 7 - WB_NEXTBREAK* = 7 - # EM_GETPUNCTUATION message - PC_LEADING* = 2 - PC_FOLLOWING* = 1 - PC_DELIMITER* = 4 - PC_OVERFLOW* = 3 - # EM_SETWORDWRAPMODE message - WBF_WORDWRAP* = 16 - WBF_WORDBREAK* = 32 - WBF_OVERFLOW* = 64 - WBF_LEVEL1* = 128 - WBF_LEVEL2* = 256 - WBF_CUSTOM* = 512 - WBF_BREAKAFTER* = 64 - WBF_BREAKLINE* = 32 - WBF_ISWHITE* = 16 - # CHARFORMAT structure - CFM_BOLD* = 1 - CFM_COLOR* = 1073741824 - CFM_FACE* = 536870912 - CFM_ITALIC* = 2 - CFM_OFFSET* = 268435456 - CFM_PROTECTED* = 16 - CFM_SIZE* = 0x80000000 - CFM_STRIKEOUT* = 8 - CFM_UNDERLINE* = 4 - CFE_AUTOCOLOR* = 1073741824 - CFE_BOLD* = 1 - CFE_ITALIC* = 2 - CFE_STRIKEOUT* = 8 - CFE_UNDERLINE* = 4 - CFE_PROTECTED* = 16 - # PARAFORMAT structure - PFM_ALIGNMENT* = 8 - PFM_NUMBERING* = 32 - PFM_OFFSET* = 4 - PFM_OFFSETINDENT* = 0x80000000 - PFM_RIGHTINDENT* = 2 - PFM_STARTINDENT* = 1 - PFM_TABSTOPS* = 16 - PFN_BULLET* = 1 - PFA_LEFT* = 1 - PFA_RIGHT* = 2 - PFA_CENTER* = 3 - # SELCHANGE structure - SEL_EMPTY* = 0 - SEL_TEXT* = 1 - SEL_OBJECT* = 2 - SEL_MULTICHAR* = 4 - SEL_MULTIOBJECT* = 8 - # RTF clipboard formats - CF_RTF* = "Rich Text Format" - CF_RETEXTOBJ* = "RichEdit Text and Objects" - # DRAWITEMSTRUCT structure - ODT_BUTTON* = 4 - ODT_COMBOBOX* = 3 - ODT_LISTBOX* = 2 - ODT_LISTVIEW* = 102 - ODT_MENU* = 1 - ODT_STATIC* = 5 - ODT_TAB* = 101 - ODT_HEADER* = 100 - ODA_DRAWENTIRE* = 1 - ODA_FOCUS* = 4 - ODA_SELECT* = 2 - ODS_SELECTED* = 1 - ODS_GRAYED* = 2 - ODS_DISABLED* = 4 - ODS_CHECKED* = 8 - ODS_FOCUS* = 16 - ODS_DEFAULT* = 32 - ODS_HOTLIGHT* = 0x00000040 - ODS_INACTIVE* = 0x00000080 - ODS_NOACCEL* = 0x00000100 - ODS_NOFOCUSRECT* = 0x00000200 - ODS_COMBOBOXEDIT* = 0x00001000 - # Common control styles - CCS_ADJUSTABLE* = 0x00000020 - CCS_BOTTOM* = 0x00000003 - CCS_NODIVIDER* = 0x00000040 - CCS_NOMOVEY* = 0x00000002 - CCS_NOPARENTALIGN* = 0x00000008 - CCS_NORESIZE* = 0x00000004 - CCS_TOP* = 0x00000001 - - # Common control window classes - ANIMATE_CLASSW* = "SysAnimate32" - HOTKEY_CLASSW* = "msctls_hotkey32" - PROGRESS_CLASSW* = "msctls_progress32" - STATUSCLASSNAMEW* = "msctls_statusbar32" - TOOLBARCLASSNAMEW* = "ToolbarWindow32" - TOOLTIPS_CLASSW* = "tooltips_class32" - TRACKBAR_CLASSW* = "msctls_trackbar32" - UPDOWN_CLASSW* = "msctls_updown32" - WC_HEADERW* = "SysHeader32" - WC_LISTVIEWW* = "SysListView32" - WC_TABCONTROLW* = "SysTabControl32" - WC_TREEVIEWW* = "SysTreeView32" - - ANIMATE_CLASSA* = "SysAnimate32" - HOTKEY_CLASSA* = "msctls_hotkey32" - PROGRESS_CLASSA* = "msctls_progress32" - STATUSCLASSNAMEA* = "msctls_statusbar32" - TOOLBARCLASSNAMEA* = "ToolbarWindow32" - TOOLTIPS_CLASSA* = "tooltips_class32" - TRACKBAR_CLASSA* = "msctls_trackbar32" - UPDOWN_CLASSA* = "msctls_updown32" - WC_HEADERA* = "SysHeader32" - WC_LISTVIEWA* = "SysListView32" - WC_TABCONTROLA* = "SysTabControl32" - WC_TREEVIEWA* = "SysTreeView32" - -when defined(winUnicode): - const - ANIMATE_CLASS* = ANIMATE_CLASSW - HOTKEY_CLASS* = HOTKEY_CLASSW - PROGRESS_CLASS* = PROGRESS_CLASSW - STATUSCLASSNAME* = STATUSCLASSNAMEW - TOOLBARCLASSNAME* = TOOLBARCLASSNAMEW - TOOLTIPS_CLASS* = TOOLTIPS_CLASSW - TRACKBAR_CLASS* = TRACKBAR_CLASSW - UPDOWN_CLASS* = UPDOWN_CLASSW - WC_HEADER* = WC_HEADERW - WC_LISTVIEW* = WC_LISTVIEWW - WC_TABCONTROL* = WC_TABCONTROLW - WC_TREEVIEW* = WC_TREEVIEWW -else: - const - ANIMATE_CLASS* = ANIMATE_CLASSA - HOTKEY_CLASS* = HOTKEY_CLASSA - PROGRESS_CLASS* = PROGRESS_CLASSA - STATUSCLASSNAME* = STATUSCLASSNAMEA - TOOLBARCLASSNAME* = TOOLBARCLASSNAMEA - TOOLTIPS_CLASS* = TOOLTIPS_CLASSA - TRACKBAR_CLASS* = TRACKBAR_CLASSA - UPDOWN_CLASS* = UPDOWN_CLASSA - WC_HEADER* = WC_HEADERA - WC_LISTVIEW* = WC_LISTVIEWA - WC_TABCONTROL* = WC_TABCONTROLA - WC_TREEVIEW* = WC_TREEVIEWA -# UNICODE - -const - # Header control styles - HDS_BUTTONS* = 2 - HDS_HIDDEN* = 8 - HDS_HORZ* = 0 - # HD_ITEM structure - HDI_BITMAP* = 16 - HDI_FORMAT* = 4 - HDI_HEIGHT* = 1 - HDI_LPARAM* = 8 - HDI_TEXT* = 2 - HDI_WIDTH* = 1 - HDF_CENTER* = 2 - HDF_LEFT* = 0 - HDF_RIGHT* = 1 - HDF_RTLREADING* = 4 - HDF_BITMAP* = 8192 - HDF_OWNERDRAW* = 32768 - HDF_STRING* = 16384 - HDF_JUSTIFYMASK* = 3 - # HD_HITTESTINFO structure - HHT_NOWHERE* = 1 - HHT_ONDIVIDER* = 4 - HHT_ONDIVOPEN* = 8 - HHT_ONHEADER* = 2 - HHT_TOLEFT* = 2048 - HHT_TORIGHT* = 1024 - # TBADDBITMAP structure - HINST_COMMCTRL* = HINST(-1) - -const - IDB_STD_LARGE_COLOR* = 1 - IDB_STD_SMALL_COLOR* = 0 - IDB_VIEW_LARGE_COLOR* = 5 - IDB_VIEW_SMALL_COLOR* = 4 - STD_COPY* = 1 - STD_CUT* = 0 - STD_DELETE* = 5 - STD_FILENEW* = 6 - STD_FILEOPEN* = 7 - STD_FILESAVE* = 8 - STD_FIND* = 12 - STD_HELP* = 11 - STD_PASTE* = 2 - STD_PRINT* = 14 - STD_PRINTPRE* = 9 - STD_PROPERTIES* = 10 - STD_REDOW* = 4 - STD_REPLACE* = 13 - STD_UNDO* = 3 - VIEW_LARGEICONS* = 0 - VIEW_SMALLICONS* = 1 - VIEW_LIST* = 2 - VIEW_DETAILS* = 3 - VIEW_SORTNAME* = 4 - VIEW_SORTSIZE* = 5 - VIEW_SORTDATE* = 6 - VIEW_SORTTYPE* = 7 - # Toolbar styles - TBSTYLE_ALTDRAG* = 1024 - TBSTYLE_TOOLTIPS* = 256 - TBSTYLE_WRAPABLE* = 512 - TBSTYLE_BUTTON* = 0 - TBSTYLE_CHECK* = 2 - TBSTYLE_CHECKGROUP* = 6 - TBSTYLE_GROUP* = 4 - TBSTYLE_SEP* = 1 - # Toolbar states - TBSTATE_CHECKED* = 1 - TBSTATE_ENABLED* = 4 - TBSTATE_HIDDEN* = 8 - TBSTATE_INDETERMINATE* = 16 - TBSTATE_PRESSED* = 2 - TBSTATE_WRAP* = 32 - # Tooltip styles - TTS_ALWAYSTIP* = 1 - TTS_NOPREFIX* = 2 - # TOOLINFO structure - TTF_IDISHWND* = 1 - TTF_CENTERTIP* = 2 - TTF_RTLREADING* = 4 - TTF_SUBCLASS* = 16 - # TTM_SETDELAYTIME message - TTDT_AUTOMATIC* = 0 - TTDT_AUTOPOP* = 2 - TTDT_INITIAL* = 3 - TTDT_RESHOW* = 1 - # Status window - SBARS_SIZEGRIP* = 256 - #SBARS_SIZEGRIP = 256;already above - # DL_DRAGGING message - DL_MOVECURSOR* = 3 - DL_COPYCURSOR* = 2 - DL_STOPCURSOR* = 1 - # Up-down control styles - UDS_ALIGNLEFT* = 8 - UDS_ALIGNRIGHT* = 4 - UDS_ARROWKEYS* = 32 - UDS_AUTOBUDDY* = 16 - UDS_HORZ* = 64 - UDS_NOTHOUSANDS* = 128 - UDS_SETBUDDYINT* = 2 - UDS_WRAP* = 1 - # UDM_SETRANGE message - UD_MAXVAL* = 32767 - UD_MINVAL* = -32767 - # HKM_GETHOTKEY message - HOTKEYF_ALT* = 4 - HOTKEYF_CONTROL* = 2 - HOTKEYF_EXT* = 8 - HOTKEYF_SHIFT* = 1 - # HKM_SETRULES message - HKCOMB_A* = 8 - HKCOMB_C* = 4 - HKCOMB_CA* = 64 - HKCOMB_NONE* = 1 - HKCOMB_S* = 2 - HKCOMB_SA* = 32 - HKCOMB_SC* = 16 - HKCOMB_SCA* = 128 - # Trackbar styles - TBS_HORZ* = 0 - TBS_VERT* = 2 - TBS_AUTOTICKS* = 1 - TBS_NOTICKS* = 16 - TBS_TOP* = 4 - TBS_BOTTOM* = 0 - TBS_LEFT* = 4 - TBS_RIGHT* = 0 - TBS_BOTH* = 8 - TBS_ENABLESELRANGE* = 32 - TBS_FIXEDLENGTH* = 64 - TBS_NOTHUMB* = 128 - TB_BOTTOM* = 7 - TB_ENDTRACK* = 8 - TB_LINEDOWN* = 1 - TB_LINEUP* = 0 - TB_PAGEDOWN* = 3 - TB_PAGEUP* = 2 - TB_THUMBPOSITION* = 4 - TB_THUMBTRACK* = 5 - TB_TOP* = 6 - # List view styles - LVS_ALIGNLEFT* = 2048 - LVS_ALIGNTOP* = 0 - LVS_AUTOARRANGE* = 256 - LVS_EDITLABELS* = 512 - LVS_ICON* = 0 - LVS_LIST* = 3 - LVS_NOCOLUMNHEADER* = 16384 - LVS_NOLABELWRAP* = 128 - LVS_NOSCROLL* = 8192 - LVS_NOSORTHEADER* = 32768 - LVS_OWNERDRAWFIXED* = 1024 - LVS_REPORT* = 1 - LVS_SHAREIMAGELISTS* = 64 - LVS_SHOWSELALWAYS* = 8 - LVS_SINGLESEL* = 4 - LVS_SMALLICON* = 2 - LVS_SORTASCENDING* = 16 - LVS_SORTDESCENDING* = 32 - LVS_TYPESTYLEMASK* = 64512 - LVSIL_NORMAL* = 0 - LVSIL_SMALL* = 1 - LVSIL_STATE* = 2 - LVIS_CUT* = 4 - LVIS_DROPHILITED* = 8 - LVIS_FOCUSED* = 1 - LVIS_SELECTED* = 2 - LVIS_OVERLAYMASK* = 3840 - LVIS_STATEIMAGEMASK* = 61440 - - LPSTR_TEXTCALLBACKW* = cast[LPWSTR](-1) - LPSTR_TEXTCALLBACKA* = cast[LPSTR](-1) -when defined(winUnicode): - const LPSTR_TEXTCALLBACK* = cast[LPWSTR](-1) -else: - const LPSTR_TEXTCALLBACK* = cast[LPSTR](-1) - -const - LVIF_TEXT* = 1 - LVIF_IMAGE* = 2 - LVIF_PARAM* = 4 - LVIF_STATE* = 8 - LVIF_DI_SETITEM* = 4096 - # LVM_GETNEXTITEM structure - LVNI_ABOVE* = 256 - LVNI_ALL* = 0 - LVNI_BELOW* = 512 - LVNI_TOLEFT* = 1024 - LVNI_TORIGHT* = 2048 - LVNI_CUT* = 4 - LVNI_DROPHILITED* = 8 - LVNI_FOCUSED* = 1 - LVNI_SELECTED* = 2 - # LV_FINDINFO structure - LVFI_PARAM* = 1 - LVFI_PARTIAL* = 8 - LVFI_STRING* = 2 - LVFI_WRAP* = 32 - LVFI_NEARESTXY* = 64 - # LV_HITTESTINFO structure - LVHT_ABOVE* = 8 - LVHT_BELOW* = 16 - LVHT_NOWHERE* = 1 - LVHT_ONITEMICON* = 2 - LVHT_ONITEMLABEL* = 4 - LVHT_ONITEMSTATEICON* = 8 - LVHT_TOLEFT* = 64 - LVHT_TORIGHT* = 32 - # LV_COLUMN structure - LVCF_FMT* = 1 - LVCF_SUBITEM* = 8 - LVCF_TEXT* = 4 - LVCF_WIDTH* = 2 - LVCFMT_CENTER* = 2 - LVCFMT_LEFT* = 0 - LVCFMT_RIGHT* = 1 - # ListView_GetItemRect - LVIR_BOUNDS* = 0 - LVIR_ICON* = 1 - LVIR_LABEL* = 2 - LVIR_SELECTBOUNDS* = 3 - # LVM_ARRANGE message - LVA_ALIGNLEFT* = 1 - LVA_ALIGNTOP* = 2 - LVA_DEFAULT* = 0 - LVA_SNAPTOGRID* = 5 - # LVM_SETCOLUMNWIDTH message - LVSCW_AUTOSIZE* = -1 - LVSCW_AUTOSIZE_USEHEADER* = -2 - # Tree View styles - TVS_DISABLEDRAGDROP* = 16 - TVS_EDITLABELS* = 8 - TVS_HASBUTTONS* = 1 - TVS_HASLINES* = 2 - TVS_LINESATROOT* = 4 - TVS_SHOWSELALWAYS* = 32 - # Tree View states - TVIS_BOLD* = 16 - TVIS_CUT* = 4 - TVIS_DROPHILITED* = 8 - TVIS_EXPANDED* = 32 - TVIS_EXPANDEDONCE* = 64 - TVIS_FOCUSED* = 1 - TVIS_OVERLAYMASK* = 3840 - TVIS_SELECTED* = 2 - TVIS_STATEIMAGEMASK* = 61440 - TVIS_USERMASK* = 61440 - # TV_ITEM structure - TVIF_CHILDREN* = 64 - TVIF_HANDLE* = 16 - TVIF_IMAGE* = 2 - TVIF_PARAM* = 4 - TVIF_SELECTEDIMAGE* = 32 - TVIF_STATE* = 8 - TVIF_TEXT* = 1 - I_CHILDRENCALLBACK* = -1 - I_IMAGECALLBACK* = -1 - # TV_INSERTSTRUCT structure - -type - TREEITEM* {.final, pure.} = object - HTREEITEM* = ptr TREEITEM - PTREEITEM* = ptr TREEITEM -{.deprecated: [TTREEITEM: TREEITEM].} - -const - TVI_ROOT* = cast[HTREEITEM](0xFFFF0000) - TVI_FIRST* = cast[HTREEITEM](0xFFFF0001) - TVI_LAST* = cast[HTREEITEM](0xFFFF0002) - TVI_SORT* = cast[HTREEITEM](0xFFFF0003) - -const - # TV_HITTESTINFO structure - TVHT_ABOVE* = 256 - TVHT_BELOW* = 512 - TVHT_NOWHERE* = 1 - TVHT_ONITEM* = 70 - TVHT_ONITEMBUTTON* = 16 - TVHT_ONITEMICON* = 2 - TVHT_ONITEMINDENT* = 8 - TVHT_ONITEMLABEL* = 4 - TVHT_ONITEMRIGHT* = 32 - TVHT_ONITEMSTATEICON* = 64 - TVHT_TOLEFT* = 2048 - TVHT_TORIGHT* = 1024 - # TVM_EXPAND message - TVE_COLLAPSE* = 1 - TVE_COLLAPSERESET* = 32768 - TVE_EXPAND* = 2 - TVE_TOGGLE* = 3 - # TVM_GETIMAGELIST message - TVSIL_NORMAL* = 0 - TVSIL_STATE* = 2 - # TVM_GETNEXTITEM message - TVGN_CARET* = 9 - TVGN_CHILD* = 4 - TVGN_DROPHILITE* = 8 - TVGN_FIRSTVISIBLE* = 5 - TVGN_NEXT* = 1 - TVGN_NEXTVISIBLE* = 6 - TVGN_PARENT* = 3 - TVGN_PREVIOUS* = 2 - TVGN_PREVIOUSVISIBLE* = 7 - TVGN_ROOT* = 0 - # TVN_SELCHANGED message - TVC_BYKEYBOARD* = 2 - TVC_BYMOUSE* = 1 - TVC_UNKNOWN* = 0 - # Tab control styles - TCS_BUTTONS* = 256 - TCS_FIXEDWIDTH* = 1024 - TCS_FOCUSNEVER* = 32768 - TCS_FOCUSONBUTTONDOWN* = 4096 - TCS_FORCEICONLEFT* = 16 - TCS_FORCELABELLEFT* = 32 - TCS_MULTILINE* = 512 - TCS_OWNERDRAWFIXED* = 8192 - TCS_RAGGEDRIGHT* = 2048 - TCS_RIGHTJUSTIFY* = 0 - TCS_SINGLELINE* = 0 - TCS_TABS* = 0 - TCS_TOOLTIPS* = 16384 - # TC_ITEM structure - TCIF_TEXT* = 1 - TCIF_IMAGE* = 2 - TCIF_PARAM* = 8 - TCIF_RTLREADING* = 4 - # TC_HITTESTINFO structure - TCHT_NOWHERE* = 1 - TCHT_ONITEM* = 6 - TCHT_ONITEMICON* = 2 - TCHT_ONITEMLABEL* = 4 - # Animation control styles - ACS_AUTOPLAY* = 4 - ACS_CENTER* = 1 - ACS_TRANSPARENT* = 2 - # MODEMDEVCAPS structure - DIALOPTION_BILLING* = 64 - DIALOPTION_QUIET* = 128 - DIALOPTION_DIALTONE* = 256 - MDMVOLFLAG_LOW* = 1 - MDMVOLFLAG_MEDIUM* = 2 - MDMVOLFLAG_HIGH* = 4 - MDMVOL_LOW* = 0 - MDMVOL_MEDIUM* = 1 - MDMVOL_HIGH* = 2 - MDMSPKRFLAG_OFF* = 1 - MDMSPKRFLAG_DIAL* = 2 - MDMSPKRFLAG_ON* = 4 - MDMSPKRFLAG_CALLSETUP* = 8 - MDMSPKR_OFF* = 0 - MDMSPKR_DIAL* = 1 - MDMSPKR_ON* = 2 - MDMSPKR_CALLSETUP* = 3 - MDM_BLIND_DIAL* = 512 - MDM_CCITT_OVERRIDE* = 64 - MDM_CELLULAR* = 8 - MDM_COMPRESSION* = 1 - MDM_ERROR_CONTROL* = 2 - MDM_FLOWCONTROL_HARD* = 16 - MDM_FLOWCONTROL_SOFT* = 32 - MDM_FORCED_EC* = 4 - MDM_SPEED_ADJUST* = 128 - MDM_TONE_DIAL* = 256 - MDM_V23_OVERRIDE* = 1024 - - # Languages - # - # Language IDs. - # - # The following two combinations of primary language ID and - # sublanguage ID have special semantics: - # - # Primary Language ID Sublanguage ID Result - # ------------------- --------------- ------------------------ - # LANG_NEUTRAL SUBLANG_NEUTRAL Language neutral - # LANG_NEUTRAL SUBLANG_DEFAULT User default language - # LANG_NEUTRAL SUBLANG_SYS_DEFAULT System default language - # LANG_INVARIANT SUBLANG_NEUTRAL Invariant locale - # - # - # Primary language IDs. - # - LANG_NEUTRAL* = 0x00000000 - LANG_INVARIANT* = 0x0000007F - LANG_AFRIKAANS* = 0x00000036 - LANG_ALBANIAN* = 0x0000001C - LANG_ARABIC* = 0x00000001 - LANG_ARMENIAN* = 0x0000002B - LANG_ASSAMESE* = 0x0000004D - LANG_AZERI* = 0x0000002C - LANG_BASQUE* = 0x0000002D - LANG_BELARUSIAN* = 0x00000023 - LANG_BENGALI* = 0x00000045 - LANG_BULGARIAN* = 0x00000002 - LANG_CATALAN* = 0x00000003 - LANG_CHINESE* = 0x00000004 - LANG_CROATIAN* = 0x0000001A - LANG_CZECH* = 0x00000005 - LANG_DANISH* = 0x00000006 - LANG_DIVEHI* = 0x00000065 - LANG_DUTCH* = 0x00000013 - LANG_ENGLISH* = 0x00000009 - LANG_ESTONIAN* = 0x00000025 - LANG_FAEROESE* = 0x00000038 - LANG_FARSI* = 0x00000029 - LANG_FINNISH* = 0x0000000B - LANG_FRENCH* = 0x0000000C - LANG_GALICIAN* = 0x00000056 - LANG_GEORGIAN* = 0x00000037 - LANG_GERMAN* = 0x00000007 - LANG_GREEK* = 0x00000008 - LANG_GUJARATI* = 0x00000047 - LANG_HEBREW* = 0x0000000D - LANG_HINDI* = 0x00000039 - LANG_HUNGARIAN* = 0x0000000E - LANG_ICELANDIC* = 0x0000000F - LANG_INDONESIAN* = 0x00000021 - LANG_ITALIAN* = 0x00000010 - LANG_JAPANESE* = 0x00000011 - LANG_KANNADA* = 0x0000004B - LANG_KASHMIRI* = 0x00000060 - LANG_KAZAK* = 0x0000003F - LANG_KONKANI* = 0x00000057 - LANG_KOREAN* = 0x00000012 - LANG_KYRGYZ* = 0x00000040 - LANG_LATVIAN* = 0x00000026 - LANG_LITHUANIAN* = 0x00000027 - LANG_MACEDONIAN* = 0x0000002F # the Former Yugoslav Republic of Macedonia - LANG_MALAY* = 0x0000003E - LANG_MALAYALAM* = 0x0000004C - LANG_MANIPURI* = 0x00000058 - LANG_MARATHI* = 0x0000004E - LANG_MONGOLIAN* = 0x00000050 - LANG_NEPALI* = 0x00000061 - LANG_NORWEGIAN* = 0x00000014 - LANG_ORIYA* = 0x00000048 - LANG_POLISH* = 0x00000015 - LANG_PORTUGUESE* = 0x00000016 - LANG_PUNJABI* = 0x00000046 - LANG_ROMANIAN* = 0x00000018 - LANG_RUSSIAN* = 0x00000019 - LANG_SANSKRIT* = 0x0000004F - LANG_SERBIAN* = 0x0000001A - LANG_SINDHI* = 0x00000059 - LANG_SLOVAK* = 0x0000001B - LANG_SLOVENIAN* = 0x00000024 - LANG_SPANISH* = 0x0000000A - LANG_SWAHILI* = 0x00000041 - LANG_SWEDISH* = 0x0000001D - LANG_SYRIAC* = 0x0000005A - LANG_TAMIL* = 0x00000049 - LANG_TATAR* = 0x00000044 - LANG_TELUGU* = 0x0000004A - LANG_THAI* = 0x0000001E - LANG_TURKISH* = 0x0000001F - LANG_UKRAINIAN* = 0x00000022 - LANG_URDU* = 0x00000020 - LANG_UZBEK* = 0x00000043 - LANG_VIETNAMESE* = 0x0000002A - # - # Sublanguage IDs. - # - # The name immediately following SUBLANG_ dictates which primary - # language ID that sublanguage ID can be combined with to form a - # valid language ID. - # - SUBLANG_NEUTRAL* = 0x00000000 # language neutral - SUBLANG_DEFAULT* = 0x00000001 # user default - SUBLANG_SYS_DEFAULT* = 0x00000002 # system default - SUBLANG_ARABIC_SAUDI_ARABIA* = 0x00000001 # Arabic (Saudi Arabia) - SUBLANG_ARABIC_IRAQ* = 0x00000002 # Arabic (Iraq) - SUBLANG_ARABIC_EGYPT* = 0x00000003 # Arabic (Egypt) - SUBLANG_ARABIC_LIBYA* = 0x00000004 # Arabic (Libya) - SUBLANG_ARABIC_ALGERIA* = 0x00000005 # Arabic (Algeria) - SUBLANG_ARABIC_MOROCCO* = 0x00000006 # Arabic (Morocco) - SUBLANG_ARABIC_TUNISIA* = 0x00000007 # Arabic (Tunisia) - SUBLANG_ARABIC_OMAN* = 0x00000008 # Arabic (Oman) - SUBLANG_ARABIC_YEMEN* = 0x00000009 # Arabic (Yemen) - SUBLANG_ARABIC_SYRIA* = 0x0000000A # Arabic (Syria) - SUBLANG_ARABIC_JORDAN* = 0x0000000B # Arabic (Jordan) - SUBLANG_ARABIC_LEBANON* = 0x0000000C # Arabic (Lebanon) - SUBLANG_ARABIC_KUWAIT* = 0x0000000D # Arabic (Kuwait) - SUBLANG_ARABIC_UAE* = 0x0000000E # Arabic (U.A.E) - SUBLANG_ARABIC_BAHRAIN* = 0x0000000F # Arabic (Bahrain) - SUBLANG_ARABIC_QATAR* = 0x00000010 # Arabic (Qatar) - SUBLANG_AZERI_LATIN* = 0x00000001 # Azeri (Latin) - SUBLANG_AZERI_CYRILLIC* = 0x00000002 # Azeri (Cyrillic) - SUBLANG_CHINESE_TRADITIONAL* = 0x00000001 # Chinese (Taiwan) - SUBLANG_CHINESE_SIMPLIFIED* = 0x00000002 # Chinese (PR China) - SUBLANG_CHINESE_HONGKONG* = 0x00000003 # Chinese (Hong Kong S.A.R., P.R.C.) - SUBLANG_CHINESE_SINGAPORE* = 0x00000004 # Chinese (Singapore) - SUBLANG_CHINESE_MACAU* = 0x00000005 # Chinese (Macau S.A.R.) - SUBLANG_DUTCH* = 0x00000001 # Dutch - SUBLANG_DUTCH_BELGIAN* = 0x00000002 # Dutch (Belgian) - SUBLANG_ENGLISH_US* = 0x00000001 # English (USA) - SUBLANG_ENGLISH_UK* = 0x00000002 # English (UK) - SUBLANG_ENGLISH_AUS* = 0x00000003 # English (Australian) - SUBLANG_ENGLISH_CAN* = 0x00000004 # English (Canadian) - SUBLANG_ENGLISH_NZ* = 0x00000005 # English (New Zealand) - SUBLANG_ENGLISH_EIRE* = 0x00000006 # English (Irish) - SUBLANG_ENGLISH_SOUTH_AFRICA* = 0x00000007 # English (South Africa) - SUBLANG_ENGLISH_JAMAICA* = 0x00000008 # English (Jamaica) - SUBLANG_ENGLISH_CARIBBEAN* = 0x00000009 # English (Caribbean) - SUBLANG_ENGLISH_BELIZE* = 0x0000000A # English (Belize) - SUBLANG_ENGLISH_TRINIDAD* = 0x0000000B # English (Trinidad) - SUBLANG_ENGLISH_ZIMBABWE* = 0x0000000C # English (Zimbabwe) - SUBLANG_ENGLISH_PHILIPPINES* = 0x0000000D # English (Philippines) - SUBLANG_FRENCH* = 0x00000001 # French - SUBLANG_FRENCH_BELGIAN* = 0x00000002 # French (Belgian) - SUBLANG_FRENCH_CANADIAN* = 0x00000003 # French (Canadian) - SUBLANG_FRENCH_SWISS* = 0x00000004 # French (Swiss) - SUBLANG_FRENCH_LUXEMBOURG* = 0x00000005 # French (Luxembourg) - SUBLANG_FRENCH_MONACO* = 0x00000006 # French (Monaco) - SUBLANG_GERMAN* = 0x00000001 # German - SUBLANG_GERMAN_SWISS* = 0x00000002 # German (Swiss) - SUBLANG_GERMAN_AUSTRIAN* = 0x00000003 # German (Austrian) - SUBLANG_GERMAN_LUXEMBOURG* = 0x00000004 # German (Luxembourg) - SUBLANG_GERMAN_LIECHTENSTEIN* = 0x00000005 # German (Liechtenstein) - SUBLANG_ITALIAN* = 0x00000001 # Italian - SUBLANG_ITALIAN_SWISS* = 0x00000002 # Italian (Swiss) - SUBLANG_KASHMIRI_SASIA* = 0x00000002 # Kashmiri (South Asia) - SUBLANG_KASHMIRI_INDIA* = 0x00000002 # For app compatibility only - SUBLANG_KOREAN* = 0x00000001 # Korean (Extended Wansung) - SUBLANG_LITHUANIAN* = 0x00000001 # Lithuanian - SUBLANG_MALAY_MALAYSIA* = 0x00000001 # Malay (Malaysia) - SUBLANG_MALAY_BRUNEI_DARUSSALAM* = 0x00000002 # Malay (Brunei Darussalam) - SUBLANG_NEPALI_INDIA* = 0x00000002 # Nepali (India) - SUBLANG_NORWEGIAN_BOKMAL* = 0x00000001 # Norwegian (Bokmal) - SUBLANG_NORWEGIAN_NYNORSK* = 0x00000002 # Norwegian (Nynorsk) - SUBLANG_PORTUGUESE* = 0x00000002 # Portuguese - SUBLANG_PORTUGUESE_BRAZILIAN* = 0x00000001 # Portuguese (Brazilian) - SUBLANG_SERBIAN_LATIN* = 0x00000002 # Serbian (Latin) - SUBLANG_SERBIAN_CYRILLIC* = 0x00000003 # Serbian (Cyrillic) - SUBLANG_SPANISH* = 0x00000001 # Spanish (Castilian) - SUBLANG_SPANISH_MEXICAN* = 0x00000002 # Spanish (Mexican) - SUBLANG_SPANISH_MODERN* = 0x00000003 # Spanish (Spain) - SUBLANG_SPANISH_GUATEMALA* = 0x00000004 # Spanish (Guatemala) - SUBLANG_SPANISH_COSTA_RICA* = 0x00000005 # Spanish (Costa Rica) - SUBLANG_SPANISH_PANAMA* = 0x00000006 # Spanish (Panama) - SUBLANG_SPANISH_DOMINICAN_REPUBLIC* = 0x00000007 # Spanish (Dominican Republic) - SUBLANG_SPANISH_VENEZUELA* = 0x00000008 # Spanish (Venezuela) - SUBLANG_SPANISH_COLOMBIA* = 0x00000009 # Spanish (Colombia) - SUBLANG_SPANISH_PERU* = 0x0000000A # Spanish (Peru) - SUBLANG_SPANISH_ARGENTINA* = 0x0000000B # Spanish (Argentina) - SUBLANG_SPANISH_ECUADOR* = 0x0000000C # Spanish (Ecuador) - SUBLANG_SPANISH_CHILE* = 0x0000000D # Spanish (Chile) - SUBLANG_SPANISH_URUGUAY* = 0x0000000E # Spanish (Uruguay) - SUBLANG_SPANISH_PARAGUAY* = 0x0000000F # Spanish (Paraguay) - SUBLANG_SPANISH_BOLIVIA* = 0x00000010 # Spanish (Bolivia) - SUBLANG_SPANISH_EL_SALVADOR* = 0x00000011 # Spanish (El Salvador) - SUBLANG_SPANISH_HONDURAS* = 0x00000012 # Spanish (Honduras) - SUBLANG_SPANISH_NICARAGUA* = 0x00000013 # Spanish (Nicaragua) - SUBLANG_SPANISH_PUERTO_RICO* = 0x00000014 # Spanish (Puerto Rico) - SUBLANG_SWEDISH* = 0x00000001 # Swedish - SUBLANG_SWEDISH_FINLAND* = 0x00000002 # Swedish (Finland) - SUBLANG_URDU_PAKISTAN* = 0x00000001 # Urdu (Pakistan) - SUBLANG_URDU_INDIA* = 0x00000002 # Urdu (India) - SUBLANG_UZBEK_LATIN* = 0x00000001 # Uzbek (Latin) - SUBLANG_UZBEK_CYRILLIC* = 0x00000002 # Uzbek (Cyrillic) - # - # Sorting IDs. - # - SORT_DEFAULT* = 0x00000000 # sorting default - SORT_JAPANESE_XJIS* = 0x00000000 # Japanese XJIS order - SORT_JAPANESE_UNICODE* = 0x00000001 # Japanese Unicode order - SORT_CHINESE_BIG5* = 0x00000000 # Chinese BIG5 order - SORT_CHINESE_PRCP* = 0x00000000 # PRC Chinese Phonetic order - SORT_CHINESE_UNICODE* = 0x00000001 # Chinese Unicode order - SORT_CHINESE_PRC* = 0x00000002 # PRC Chinese Stroke Count order - SORT_CHINESE_BOPOMOFO* = 0x00000003 # Traditional Chinese Bopomofo order - SORT_KOREAN_KSC* = 0x00000000 # Korean KSC order - SORT_KOREAN_UNICODE* = 0x00000001 # Korean Unicode order - SORT_GERMAN_PHONE_BOOK* = 0x00000001 # German Phone Book order - SORT_HUNGARIAN_DEFAULT* = 0x00000000 # Hungarian Default order - SORT_HUNGARIAN_TECHNICAL* = 0x00000001 # Hungarian Technical order - SORT_GEORGIAN_TRADITIONAL* = 0x00000000 # Georgian Traditional order - SORT_GEORGIAN_MODERN* = 0x00000001 # Georgian Modern order - # SYSTEM_INFO structure - PROCESSOR_INTEL_386* = 386 - PROCESSOR_INTEL_486* = 486 - PROCESSOR_INTEL_PENTIUM* = 586 - PROCESSOR_MIPS_R4000* = 4000 - PROCESSOR_ALPHA_21064* = 21064 - # FSCTL_SET_COMPRESSION - COMPRESSION_FORMAT_NONE* = 0 - COMPRESSION_FORMAT_DEFAULT* = 1 - COMPRESSION_FORMAT_LZNT1* = 2 - # TAPE_GET_DRIVE_PARAMETERS structure - TAPE_DRIVE_COMPRESSION* = 131072 - TAPE_DRIVE_ECC* = 65536 - TAPE_DRIVE_ERASE_BOP_ONLY* = 64 - TAPE_DRIVE_ERASE_LONG* = 32 - TAPE_DRIVE_ERASE_IMMEDIATE* = 128 - TAPE_DRIVE_ERASE_SHORT* = 16 - TAPE_DRIVE_FIXED* = 1 - TAPE_DRIVE_FIXED_BLOCK* = 1024 - TAPE_DRIVE_INITIATOR* = 4 - TAPE_DRIVE_PADDING* = 262144 - TAPE_DRIVE_GET_ABSOLUTE_BLK* = 1048576 - TAPE_DRIVE_GET_LOGICAL_BLK* = 2097152 - TAPE_DRIVE_REPORT_SMKS* = 524288 - TAPE_DRIVE_SELECT* = 2 - TAPE_DRIVE_SET_EOT_WZ_SIZE* = 4194304 - TAPE_DRIVE_TAPE_CAPACITY* = 256 - TAPE_DRIVE_TAPE_REMAINING* = 512 - TAPE_DRIVE_VARIABLE_BLOCK* = 2048 - TAPE_DRIVE_WRITE_PROTECT* = 4096 - TAPE_DRIVE_ABS_BLK_IMMED* = -2147475456 - TAPE_DRIVE_ABSOLUTE_BLK* = -2147479552 - TAPE_DRIVE_END_OF_DATA* = -2147418112 - TAPE_DRIVE_FILEMARKS* = -2147221504 - TAPE_DRIVE_LOAD_UNLOAD* = -2147483647 - TAPE_DRIVE_LOAD_UNLD_IMMED* = -2147483616 - TAPE_DRIVE_LOCK_UNLOCK* = -2147483644 - TAPE_DRIVE_LOCK_UNLK_IMMED* = -2147483520 - TAPE_DRIVE_LOG_BLK_IMMED* = -2147450880 - TAPE_DRIVE_LOGICAL_BLK* = -2147467264 - TAPE_DRIVE_RELATIVE_BLKS* = -2147352576 - TAPE_DRIVE_REVERSE_POSITION* = -2143289344 - TAPE_DRIVE_REWIND_IMMEDIATE* = -2147483640 - TAPE_DRIVE_SEQUENTIAL_FMKS* = -2146959360 - TAPE_DRIVE_SEQUENTIAL_SMKS* = -2145386496 - TAPE_DRIVE_SET_BLOCK_SIZE* = -2147483632 - TAPE_DRIVE_SET_COMPRESSION* = -2147483136 - TAPE_DRIVE_SET_ECC* = -2147483392 - TAPE_DRIVE_SET_PADDING* = -2147482624 - TAPE_DRIVE_SET_REPORT_SMKS* = -2147481600 - TAPE_DRIVE_SETMARKS* = -2146435072 - TAPE_DRIVE_SPACE_IMMEDIATE* = -2139095040 - TAPE_DRIVE_TENSION* = -2147483646 - TAPE_DRIVE_TENSION_IMMED* = -2147483584 - TAPE_DRIVE_WRITE_FILEMARKS* = -2113929216 - TAPE_DRIVE_WRITE_LONG_FMKS* = -2013265920 - TAPE_DRIVE_WRITE_MARK_IMMED* = -1879048192 - TAPE_DRIVE_WRITE_SETMARKS* = -2130706432 - TAPE_DRIVE_WRITE_SHORT_FMKS* = -2080374784 - # Standard rights - STANDARD_RIGHTS_REQUIRED* = 0x000F0000 - STANDARD_RIGHTS_WRITE* = 0x00020000 - STANDARD_RIGHTS_READ* = 0x00020000 - STANDARD_RIGHTS_EXECUTE* = 0x00020000 - STANDARD_RIGHTS_ALL* = 0x001F0000 - SPECIFIC_RIGHTS_ALL* = 0x0000FFFF - - FILE_GENERIC_READ* = STANDARD_RIGHTS_READ or - FILE_READ_DATA or - FILE_READ_ATTRIBUTES or - FILE_READ_EA or - SYNCHRONIZE - FILE_GENERIC_WRITE* = STANDARD_RIGHTS_WRITE or - FILE_WRITE_DATA or - FILE_WRITE_ATTRIBUTES or - FILE_WRITE_EA or - FILE_APPEND_DATA or - SYNCHRONIZE - FILE_GENERIC_EXECUTE* = STANDARD_RIGHTS_EXECUTE or - FILE_READ_ATTRIBUTES or - FILE_EXECUTE or - SYNCHRONIZE - FILE_ALL_ACCESS* = STANDARD_RIGHTS_REQUIRED or SYNCHRONIZE or 0x1FF - - # ACCESS_MASK - MAXIMUM_ALLOWED* = 0x02000000 - GENERIC_ALL* = 0x10000000 - # SID - SECURITY_NULL_RID* = 0 - SECURITY_WORLD_RID* = 0 - SECURITY_LOCAL_RID* = 0 - SECURITY_CREATOR_OWNER_RID* = 0 - SECURITY_CREATOR_GROUP_RID* = 0x00000001 - SECURITY_DIALUP_RID* = 0x00000001 - SECURITY_NETWORK_RID* = 0x00000002 - SECURITY_BATCH_RID* = 0x00000003 - SECURITY_INTERACTIVE_RID* = 0x00000004 - SECURITY_LOGON_IDS_RID* = 0x00000005 - SECURITY_LOGON_IDS_RID_COUNT* = 0x00000003 - SECURITY_SERVICE_RID* = 0x00000006 - SECURITY_LOCAL_SYSTEM_RID* = 0x00000012 - SECURITY_BUILTIN_DOMAIN_RID* = 0x00000020 - DOMAIN_USER_RID_ADMIN* = 0x000001F4 - DOMAIN_USER_RID_GUEST* = 0x000001F5 - DOMAIN_GROUP_RID_ADMINS* = 0x00000200 - DOMAIN_GROUP_RID_USERS* = 0x00000201 - DOMAIN_ALIAS_RID_ADMINS* = 0x00000220 - DOMAIN_ALIAS_RID_USERS* = 0x00000221 - DOMAIN_ALIAS_RID_GUESTS* = 0x00000222 - DOMAIN_ALIAS_RID_POWER_USERS* = 0x00000223 - DOMAIN_ALIAS_RID_ACCOUNT_OPS* = 0x00000224 - DOMAIN_ALIAS_RID_SYSTEM_OPS* = 0x00000225 - DOMAIN_ALIAS_RID_PRINT_OPS* = 0x00000226 - DOMAIN_ALIAS_RID_BACKUP_OPS* = 0x00000227 - DOMAIN_ALIAS_RID_REPLICATOR* = 0x00000228 - # TOKEN_GROUPS structure - SE_GROUP_MANDATORY* = 0x00000001 - SE_GROUP_ENABLED_BY_DEFAULT* = 0x00000002 - SE_GROUP_ENABLED* = 0x00000004 - SE_GROUP_OWNER* = 0x00000008 - SE_GROUP_LOGON_ID* = 0xC0000000 - # ACL Defines - ACL_REVISION* = 2 - # ACE_HEADER structure - ACCESS_ALLOWED_ACE_TYPE* = 0x00000000 - ACCESS_DENIED_ACE_TYPE* = 0x00000001 - SYSTEM_AUDIT_ACE_TYPE* = 0x00000002 - SYSTEM_ALARM_ACE_TYPE* = 0x00000003 - # ACE flags in the ACE_HEADER structure - OBJECT_INHERIT_ACE* = 0x00000001 - CONTAINER_INHERIT_ACE* = 0x00000002 - NO_PROPAGATE_INHERIT_ACE* = 0x00000004 - INHERIT_ONLY_ACE* = 0x00000008 - SUCCESSFUL_ACCESS_ACE_FLAG* = 0x00000040 - FAILED_ACCESS_ACE_FLAG* = 0x00000080 - # SECURITY_DESCRIPTOR_CONTROL - #SECURITY_DESCRIPTOR_REVISION = 1;already defined above - SECURITY_DESCRIPTOR_MIN_LENGTH* = 20 - SE_OWNER_DEFAULTED* = 1 - SE_GROUP_DEFAULTED* = 2 - SE_DACL_PRESENT* = 4 - SE_DACL_DEFAULTED* = 8 - SE_SACL_PRESENT* = 16 - SE_SACL_DEFAULTED* = 32 - SE_SELF_RELATIVE* = 32768 - # PRIVILEGE_SET - SE_PRIVILEGE_ENABLED_BY_DEFAULT* = 0x00000001 - SE_PRIVILEGE_ENABLED* = 0x00000002 - SE_PRIVILEGE_USED_FOR_ACCESS* = 0x80000000 - PRIVILEGE_SET_ALL_NECESSARY* = 0x00000001 - # OPENFILENAME structure - OFN_ALLOWMULTISELECT* = 0x00000200 - OFN_CREATEPROMPT* = 0x00002000 - OFN_ENABLEHOOK* = 0x00000020 - OFN_ENABLETEMPLATE* = 0x00000040 - OFN_ENABLETEMPLATEHANDLE* = 0x00000080 - OFN_EXPLORER* = 0x00080000 - OFN_EXTENSIONDIFFERENT* = 0x00000400 - OFN_FILEMUSTEXIST* = 0x00001000 - OFN_HIDEREADONLY* = 0x00000004 - OFN_LONGNAMES* = 0x00200000 - OFN_NOCHANGEDIR* = 0x00000008 - OFN_NODEREFERENCELINKS* = 0x00100000 - OFN_NOLONGNAMES* = 0x00040000 - OFN_NONETWORKBUTTON* = 0x00020000 - OFN_NOREADONLYRETURN* = 0x00008000 - OFN_NOTESTFILECREATE* = 0x00010000 - OFN_NOVALIDATE* = 0x00000100 - OFN_OVERWRITEPROMPT* = 0x00000002 - OFN_PATHMUSTEXIST* = 0x00000800 - OFN_READONLY* = 0x00000001 - OFN_SHAREAWARE* = 0x00004000 - OFN_SHOWHELP* = 0x00000010 - # SHAREVISTRING message - OFN_SHAREFALLTHROUGH* = 0x00000002 - OFN_SHARENOWARN* = 0x00000001 - OFN_SHAREWARN* = 0 - # Open/Save notifications - CDN_INITDONE* = 0xFFFFFDA7 - CDN_SELCHANGE* = 0xFFFFFDA6 - CDN_FOLDERCHANGE* = 0xFFFFFDA5 - CDN_SHAREVIOLATION* = 0xFFFFFDA4 - CDN_HELP* = 0xFFFFFDA3 - CDN_FILEOK* = 0xFFFFFDA2 - CDN_TYPECHANGE* = 0xFFFFFDA1 - # Open/Save messages - CDM_GETFILEPATH* = 0x00000465 - CDM_GETFOLDERIDLIST* = 0x00000467 - CDM_GETFOLDERPATH* = 0x00000466 - CDM_GETSPEC* = 0x00000464 - CDM_HIDECONTROL* = 0x00000469 - CDM_SETCONTROLTEXT* = 0x00000468 - CDM_SETDEFEXT* = 0x0000046A - # CHOOSECOLOR structure - CC_ENABLEHOOK* = 0x00000010 - CC_ENABLETEMPLATE* = 0x00000020 - CC_ENABLETEMPLATEHANDLE* = 0x00000040 - CC_FULLOPEN* = 0x00000002 - CC_PREVENTFULLOPEN* = 0x00000004 - CC_RGBINIT* = 0x00000001 - CC_SHOWHELP* = 0x00000008 - CC_SOLIDCOLOR* = 0x00000080 - # FINDREPLACE structure - FR_DIALOGTERM* = 0x00000040 - FR_DOWN* = 0x00000001 - FR_ENABLEHOOK* = 0x00000100 - FR_ENABLETEMPLATE* = 0x00000200 - FR_ENABLETEMPLATEHANDLE* = 0x00002000 - FR_FINDNEXT* = 0x00000008 - FR_HIDEUPDOWN* = 0x00004000 - FR_HIDEMATCHCASE* = 0x00008000 - FR_HIDEWHOLEWORD* = 0x00010000 - FR_MATCHCASE* = 0x00000004 - FR_NOMATCHCASE* = 0x00000800 - FR_NOUPDOWN* = 0x00000400 - FR_NOWHOLEWORD* = 0x00001000 - FR_REPLACE* = 0x00000010 - FR_REPLACEALL* = 0x00000020 - FR_SHOWHELP* = 0x00000080 - FR_WHOLEWORD* = 0x00000002 - # CHOOSEFONT structure - CF_APPLY* = 0x00000200 - CF_ANSIONLY* = 0x00000400 - CF_BOTH* = 0x00000003 - CF_TTONLY* = 0x00040000 - CF_EFFECTS* = 0x00000100 - CF_ENABLEHOOK* = 0x00000008 - CF_ENABLETEMPLATE* = 0x00000010 - CF_ENABLETEMPLATEHANDLE* = 0x00000020 - CF_FIXEDPITCHONLY* = 0x00004000 - CF_FORCEFONTEXIST* = 0x00010000 - CF_INITTOLOGFONTSTRUCT* = 0x00000040 - CF_LIMITSIZE* = 0x00002000 - CF_NOOEMFONTS* = 0x00000800 - CF_NOFACESEL* = 0x00080000 - CF_NOSCRIPTSEL* = 0x00800000 - CF_NOSTYLESEL* = 0x00100000 - CF_NOSIZESEL* = 0x00200000 - CF_NOSIMULATIONS* = 0x00001000 - CF_NOVECTORFONTS* = 0x00000800 - CF_NOVERTFONTS* = 0x01000000 - CF_PRINTERFONTS* = 0x00000002 - CF_SCALABLEONLY* = 0x00020000 - CF_SCREENFONTS* = 0x00000001 - CF_SCRIPTSONLY* = 0x00000400 - CF_SELECTSCRIPT* = 0x00400000 - CF_SHOWHELP* = 0x00000004 - CF_USESTYLE* = 0x00000080 - CF_WYSIWYG* = 0x00008000 - BOLD_FONTTYPE* = 0x00000100 - ITALIC_FONTTYPE* = 0x00000200 - PRINTER_FONTTYPE* = 0x00004000 - REGULAR_FONTTYPE* = 0x00000400 - SCREEN_FONTTYPE* = 0x00002000 - SIMULATED_FONTTYPE* = 0x00008000 - # Common dialog messages - COLOROKSTRINGW* = "commdlg_ColorOK" - FILEOKSTRINGW* = "commdlg_FileNameOK" - FINDMSGSTRINGW* = "commdlg_FindReplace" - HELPMSGSTRINGW* = "commdlg_help" - LBSELCHSTRINGW* = "commdlg_LBSelChangedNotify" - SETRGBSTRINGW* = "commdlg_SetRGBColor" - SHAREVISTRINGW* = "commdlg_ShareViolation" - COLOROKSTRINGA* = "commdlg_ColorOK" - FILEOKSTRINGA* = "commdlg_FileNameOK" - FINDMSGSTRINGA* = "commdlg_FindReplace" - HELPMSGSTRINGA* = "commdlg_help" - LBSELCHSTRINGA* = "commdlg_LBSelChangedNotify" - SETRGBSTRINGA* = "commdlg_SetRGBColor" - SHAREVISTRINGA* = "commdlg_ShareViolation" - -when defined(winUnicode): - const - COLOROKSTRING* = COLOROKSTRINGW - FILEOKSTRING* = FILEOKSTRINGW - FINDMSGSTRING* = FINDMSGSTRINGW - HELPMSGSTRING* = HELPMSGSTRINGW - LBSELCHSTRING* = LBSELCHSTRINGW - SETRGBSTRING* = SETRGBSTRINGW - SHAREVISTRING* = SHAREVISTRINGW -else: - const - COLOROKSTRING* = COLOROKSTRINGA - FILEOKSTRING* = FILEOKSTRINGA - FINDMSGSTRING* = FINDMSGSTRINGA - HELPMSGSTRING* = HELPMSGSTRINGA - LBSELCHSTRING* = LBSELCHSTRINGA - SETRGBSTRING* = SETRGBSTRINGA - SHAREVISTRING* = SHAREVISTRINGA - -const - # LBSELCHSTRING message - CD_LBSELCHANGE* = 0 - CD_LBSELADD* = 2 - CD_LBSELSUB* = 1 - CD_LBSELNOITEMS* = -1 - # DEVNAMES structure - DN_DEFAULTPRN* = 1 - # PRINTDLG structure - PD_ALLPAGES* = 0 - PD_COLLATE* = 16 - PD_DISABLEPRINTTOFILE* = 524288 - PD_ENABLEPRINTHOOK* = 4096 - PD_ENABLEPRINTTEMPLATE* = 16384 - PD_ENABLEPRINTTEMPLATEHANDLE* = 65536 - PD_ENABLESETUPHOOK* = 8192 - PD_ENABLESETUPTEMPLATE* = 32768 - PD_ENABLESETUPTEMPLATEHANDLE* = 131072 - PD_HIDEPRINTTOFILE* = 1048576 - PD_NOPAGENUMS* = 8 - PD_NOSELECTION* = 4 - PD_NOWARNING* = 128 - PD_PAGENUMS* = 2 - PD_PRINTSETUP* = 64 - PD_PRINTTOFILE* = 32 - PD_RETURNDC* = 256 - PD_RETURNDEFAULT* = 1024 - PD_RETURNIC* = 512 - PD_SELECTION* = 1 - PD_SHOWHELP* = 2048 - PD_USEDEVMODECOPIES* = 262144 - PD_USEDEVMODECOPIESANDCOLLATE* = 262144 - # PAGESETUPDLG structure - PSD_DEFAULTMINMARGINS* = 0 - PSD_DISABLEMARGINS* = 16 - PSD_DISABLEORIENTATION* = 256 - PSD_DISABLEPAGEPAINTING* = 524288 - PSD_DISABLEPAPER* = 512 - PSD_DISABLEPRINTER* = 32 - PSD_ENABLEPAGEPAINTHOOK* = 262144 - PSD_ENABLEPAGESETUPHOOK* = 8192 - PSD_ENABLEPAGESETUPTEMPLATE* = 32768 - PSD_ENABLEPAGESETUPTEMPLATEHANDLE* = 131072 - PSD_INHUNDREDTHSOFMILLIMETERS* = 8 - PSD_INTHOUSANDTHSOFINCHES* = 4 - PSD_INWININIINTLMEASURE* = 0 - PSD_MARGINS* = 2 - PSD_MINMARGINS* = 1 - PSD_NOWARNING* = 128 - PSD_RETURNDEFAULT* = 1024 - PSD_SHOWHELP* = 2048 - # WM_SHOWWINDOW message - SW_OTHERUNZOOM* = 4 - SW_OTHERZOOM* = 2 - SW_PARENTCLOSING* = 1 - SW_PARENTOPENING* = 3 - # Virtual Key codes - VK_LBUTTON* = 1 - VK_RBUTTON* = 2 - VK_CANCEL* = 3 - VK_MBUTTON* = 4 - VK_BACK* = 8 - VK_TAB* = 9 - VK_CLEAR* = 12 - VK_RETURN* = 13 - VK_SHIFT* = 16 - VK_CONTROL* = 17 - VK_MENU* = 18 - VK_PAUSE* = 19 - VK_CAPITAL* = 20 - VK_ESCAPE* = 27 - VK_SPACE* = 32 - VK_PRIOR* = 33 - VK_NEXT* = 34 - VK_END* = 35 - VK_HOME* = 36 - VK_LEFT* = 37 - VK_UP* = 38 - VK_RIGHT* = 39 - VK_DOWN* = 40 - VK_SELECT* = 41 - VK_PRINT* = 42 - VK_EXECUTE* = 43 - VK_SNAPSHOT* = 44 - VK_INSERT* = 45 - VK_DELETE* = 46 - VK_HELP* = 47 - VK_0* = 48 - VK_1* = 49 - VK_2* = 50 - VK_3* = 51 - VK_4* = 52 - VK_5* = 53 - VK_6* = 54 - VK_7* = 55 - VK_8* = 56 - VK_9* = 57 - VK_A* = 65 - VK_B* = 66 - VK_C* = 67 - VK_D* = 68 - VK_E* = 69 - VK_F* = 70 - VK_G* = 71 - VK_H* = 72 - VK_I* = 73 - VK_J* = 74 - VK_K* = 75 - VK_L* = 76 - VK_M* = 77 - VK_N* = 78 - VK_O* = 79 - VK_P* = 80 - VK_Q* = 81 - VK_R* = 82 - VK_S* = 83 - VK_T* = 84 - VK_U* = 85 - VK_V* = 86 - VK_W* = 87 - VK_X* = 88 - VK_Y* = 89 - VK_Z* = 90 - VK_LWIN* = 91 - VK_RWIN* = 92 - VK_APPS* = 93 - VK_NUMPAD0* = 96 - VK_NUMPAD1* = 97 - VK_NUMPAD2* = 98 - VK_NUMPAD3* = 99 - VK_NUMPAD4* = 100 - VK_NUMPAD5* = 101 - VK_NUMPAD6* = 102 - VK_NUMPAD7* = 103 - VK_NUMPAD8* = 104 - VK_NUMPAD9* = 105 - VK_MULTIPLY* = 106 - VK_ADD* = 107 - VK_SEPARATOR* = 108 - VK_SUBTRACT* = 109 - VK_DECIMAL* = 110 - VK_DIVIDE* = 111 - VK_F1* = 112 - VK_F2* = 113 - VK_F3* = 114 - VK_F4* = 115 - VK_F5* = 116 - VK_F6* = 117 - VK_F7* = 118 - VK_F8* = 119 - VK_F9* = 120 - VK_F10* = 121 - VK_F11* = 122 - VK_F12* = 123 - VK_F13* = 124 - VK_F14* = 125 - VK_F15* = 126 - VK_F16* = 127 - VK_F17* = 128 - VK_F18* = 129 - VK_F19* = 130 - VK_F20* = 131 - VK_F21* = 132 - VK_F22* = 133 - VK_F23* = 134 - VK_F24* = 135 - # GetAsyncKeyState - VK_NUMLOCK* = 144 - VK_SCROLL* = 145 - VK_LSHIFT* = 160 - VK_LCONTROL* = 162 - VK_LMENU* = 164 - VK_RSHIFT* = 161 - VK_RCONTROL* = 163 - VK_RMENU* = 165 - # ImmGetVirtualKey - VK_PROCESSKEY* = 229 - # Keystroke Message Flags - KF_ALTDOWN* = 8192 - KF_DLGMODE* = 2048 - KF_EXTENDED* = 256 - KF_MENUMODE* = 4096 - KF_REPEAT* = 16384 - KF_UP* = 32768 - # GetKeyboardLayoutName - KL_NAMELENGTH* = 9 - # WM_ACTIVATE message - WA_ACTIVE* = 1 - WA_CLICKACTIVE* = 2 - WA_INACTIVE* = 0 - # WM_ACTIVATE message - PWR_CRITICALRESUME* = 3 - PWR_SUSPENDREQUEST* = 1 - PWR_SUSPENDRESUME* = 2 - PWR_FAIL* = -1 - PWR_OK* = 1 - # WM_NOTIFYFORMAT message - NF_QUERY* = 3 - NF_REQUERY* = 4 - NFR_ANSI* = 1 - NFR_UNICODE* = 2 - # WM_SIZING message - WMSZ_BOTTOM* = 6 - WMSZ_BOTTOMLEFT* = 7 - WMSZ_BOTTOMRIGHT* = 8 - WMSZ_LEFT* = 1 - WMSZ_RIGHT* = 2 - WMSZ_TOP* = 3 - WMSZ_TOPLEFT* = 4 - WMSZ_TOPRIGHT* = 5 - # WM_MOUSEACTIVATE message - MA_ACTIVATE* = 1 - MA_ACTIVATEANDEAT* = 2 - MA_NOACTIVATE* = 3 - MA_NOACTIVATEANDEAT* = 4 - # WM_SIZE message - SIZE_MAXHIDE* = 4 - SIZE_MAXIMIZED* = 2 - SIZE_MAXSHOW* = 3 - SIZE_MINIMIZED* = 1 - SIZE_RESTORED* = 0 - # WM_NCCALCSIZE message - WVR_ALIGNTOP* = 16 - WVR_ALIGNLEFT* = 32 - WVR_ALIGNBOTTOM* = 64 - WVR_ALIGNRIGHT* = 128 - WVR_HREDRAW* = 256 - WVR_VREDRAW* = 512 - WVR_REDRAW* = 768 - WVR_VALIDRECTS* = 1024 - # WM_NCHITTEST message - HTBOTTOM* = 15 - HTBOTTOMLEFT* = 16 - HTBOTTOMRIGHT* = 17 - HTCAPTION* = 2 - HTCLIENT* = 1 - HTERROR* = -2 - HTGROWBOX* = 4 - HTHSCROLL* = 6 - HTLEFT* = 10 - HTMENU* = 5 - HTNOWHERE* = 0 - HTREDUCE* = 8 - - HTRIGHT* = 11 - HTSIZE* = 4 - HTSYSMENU* = 3 - HTTOP* = 12 - HTTOPLEFT* = 13 - HTTOPRIGHT* = 14 - HTTRANSPARENT* = -1 - HTVSCROLL* = 7 - HTZOOM* = 9 - # Mouse messages - MK_CONTROL* = 8 - MK_LBUTTON* = 1 - MK_MBUTTON* = 16 - MK_RBUTTON* = 2 - MK_SHIFT* = 4 - # WNDCLASS structure - CS_BYTEALIGNCLIENT* = 4096 - CS_BYTEALIGNWINDOW* = 8192 - CS_CLASSDC* = 64 - CS_DBLCLKS* = 8 - CS_GLOBALCLASS* = 16384 - CS_HREDRAW* = 2 - CS_KEYCVTWINDOW* = 4 - CS_NOCLOSE* = 512 - CS_NOKEYCVT* = 256 - CS_OWNDC* = 32 - CS_PARENTDC* = 128 - CS_SAVEBITS* = 2048 - CS_VREDRAW* = 1 - DLGWINDOWEXTRA* = 30 - # ACCEL structure - FALT* = 16 - FCONTROL* = 8 - FNOINVERT* = 2 - FSHIFT* = 4 - FVIRTKEY* = 1 - # WM_MENUCHAR return constants - MNC_IGNORE* = 0 - MNC_CLOSE* = 1 - MNC_EXECUTE* = 2 - MNC_SELECT* = 3 - # MENUINFO structure - MIM_MAXHEIGHT* = 1 - MIM_BACKGROUND* = 2 - MIM_HELPID* = 4 - MIM_MENUDATA* = 8 - MIM_STYLE* = 16 - MIM_APPLYTOSUBMENUS* = 0x80000000 - MNS_CHECKORBMP* = 0x04000000 - MNS_NOTIFYBYPOS* = 0x08000000 - MNS_AUTODISMISS* = 0x10000000 - MNS_DRAGDROP* = 0x20000000 - MNS_MODELESS* = 0x40000000 - MNS_NOCHECK* = 0x80000000 - # MENUITEMINFO structure - MIIM_CHECKMARKS* = 8 - MIIM_DATA* = 32 - MIIM_ID* = 2 - MIIM_STATE* = 1 - MIIM_SUBMENU* = 4 - MIIM_TYPE* = 16 - MIIM_STRING* = 64 - MIIM_BITMAP* = 128 - MIIM_FTYPE* = 256 - MFT_BITMAP* = 0x00000004 - MFT_MENUBARBREAK* = 0x00000020 - MFT_MENUBREAK* = 0x00000040 - MFT_OWNERDRAW* = 0x00000100 - MFT_RADIOCHECK* = 0x00000200 - MFT_RIGHTJUSTIFY* = 0x00004000 - MFT_SEPARATOR* = 0x00000800 - MFT_RIGHTORDER* = 0x00002000 - MFT_STRING* = 0 - MFS_CHECKED* = 0x00000008 - MFS_DEFAULT* = 0x00001000 - MFS_DISABLED* = 0x00000003 - MFS_ENABLED* = 0 - MFS_GRAYED* = 0x00000003 - MFS_HILITE* = 0x00000080 - MFS_UNCHECKED* = 0 - MFS_UNHILITE* = 0 - HBMMENU_CALLBACK* = - 1 - HBMMENU_SYSTEM* = 1 - HBMMENU_MBAR_RESTORE* = 2 - HBMMENU_MBAR_MINIMIZE* = 3 - HBMMENU_MBAR_CLOSE* = 5 - HBMMENU_MBAR_CLOSE_D* = 6 - HBMMENU_MBAR_MINIMIZE_D* = 7 - HBMMENU_POPUP_CLOSE* = 8 - HBMMENU_POPUP_RESTORE* = 9 - HBMMENU_POPUP_MAXIMIZE* = 10 - HBMMENU_POPUP_MINIMIZE* = 11 - # SERIALKEYS structure - SERKF_AVAILABLE* = 2 - SERKF_INDICATOR* = 4 - SERKF_SERIALKEYSON* = 1 - # FILTERKEYS structure - FKF_AVAILABLE* = 2 - FKF_CLICKON* = 64 - FKF_FILTERKEYSON* = 1 - FKF_HOTKEYACTIVE* = 4 - FKF_HOTKEYSOUND* = 16 - FKF_CONFIRMHOTKEY* = 8 - FKF_INDICATOR* = 32 - # HELPINFO structure - HELPINFO_MENUITEM* = 2 - HELPINFO_WINDOW* = 1 - # WM_PRINT message - PRF_CHECKVISIBLE* = 0x00000001 - PRF_CHILDREN* = 0x00000010 - PRF_CLIENT* = 0x00000004 - PRF_ERASEBKGND* = 0x00000008 - PRF_NONCLIENT* = 0x00000002 - PRF_OWNED* = 0x00000020 - - # MapWindowPoints - HWND_DESKTOP* = HWND(0) - -const - # WM_SYSCOMMAND message - SC_CLOSE* = 61536 - SC_CONTEXTHELP* = 61824 - SC_DEFAULT* = 61792 - SC_HOTKEY* = 61776 - SC_HSCROLL* = 61568 - SC_KEYMENU* = 61696 - SC_MAXIMIZE* = 61488 - SC_ZOOM* = 61488 - SC_MINIMIZE* = 61472 - SC_ICON* = 61472 - SC_MONITORPOWER* = 61808 - SC_MOUSEMENU* = 61584 - SC_MOVE* = 61456 - SC_NEXTWINDOW* = 61504 - SC_PREVWINDOW* = 61520 - SC_RESTORE* = 61728 - SC_SCREENSAVE* = 61760 - SC_SIZE* = 61440 - SC_TASKLIST* = 61744 - SC_VSCROLL* = 61552 - # DM_GETDEFID message - DC_HASDEFID* = 21323 - # WM_GETDLGCODE message - DLGC_BUTTON* = 8192 - DLGC_DEFPUSHBUTTON* = 16 - DLGC_HASSETSEL* = 8 - DLGC_RADIOBUTTON* = 64 - DLGC_STATIC* = 256 - DLGC_UNDEFPUSHBUTTON* = 32 - DLGC_WANTALLKEYS* = 4 - DLGC_WANTARROWS* = 1 - DLGC_WANTCHARS* = 128 - DLGC_WANTMESSAGE* = 4 - DLGC_WANTTAB* = 2 - # EM_SETMARGINS message - EC_LEFTMARGIN* = 1 - EC_RIGHTMARGIN* = 2 - EC_USEFONTINFO* = 65535 - # LB_SETCOUNT message - LB_ERR* = -1 - LB_ERRSPACE* = -2 - LB_OKAY* = 0 - # CB_DIR message - CB_ERR* = -1 - CB_ERRSPACE* = -2 - # WM_IME_CONTROL message - IMC_GETCANDIDATEPOS* = 7 - IMC_GETCOMPOSITIONFONT* = 9 - IMC_GETCOMPOSITIONWINDOW* = 11 - IMC_GETSTATUSWINDOWPOS* = 15 - IMC_CLOSESTATUSWINDOW* = 33 - IMC_OPENSTATUSWINDOW* = 34 - IMC_SETCANDIDATEPOS* = 8 - IMC_SETCOMPOSITIONFONT* = 10 - IMC_SETCOMPOSITIONWINDOW* = 12 - IMC_SETSTATUSWINDOWPOS* = 16 - # WM_IME_CONTROL message - IMN_CHANGECANDIDATE* = 3 - IMN_CLOSECANDIDATE* = 4 - IMN_CLOSESTATUSWINDOW* = 1 - IMN_GUIDELINE* = 13 - IMN_OPENCANDIDATE* = 5 - IMN_OPENSTATUSWINDOW* = 2 - IMN_SETCANDIDATEPOS* = 9 - IMN_SETCOMPOSITIONFONT* = 10 - IMN_SETCOMPOSITIONWINDOW* = 11 - IMN_SETCONVERSIONMODE* = 6 - IMN_SETOPENSTATUS* = 8 - IMN_SETSENTENCEMODE* = 7 - IMN_SETSTATUSWINDOWPOS* = 12 - IMN_PRIVATE* = 14 - # STICKYKEYS structure - SKF_AUDIBLEFEEDBACK* = 64 - SKF_AVAILABLE* = 2 - SKF_CONFIRMHOTKEY* = 8 - SKF_HOTKEYACTIVE* = 4 - SKF_HOTKEYSOUND* = 16 - SKF_INDICATOR* = 32 - SKF_STICKYKEYSON* = 1 - SKF_TRISTATE* = 128 - SKF_TWOKEYSOFF* = 256 - # MOUSEKEYS structure - MKF_AVAILABLE* = 2 - MKF_CONFIRMHOTKEY* = 8 - MKF_HOTKEYACTIVE* = 4 - MKF_HOTKEYSOUND* = 16 - MKF_INDICATOR* = 32 - MKF_MOUSEKEYSON* = 1 - MKF_MODIFIERS* = 64 - MKF_REPLACENUMBERS* = 128 - # SOUNDSENTRY structure - SSF_AVAILABLE* = 2 - SSF_SOUNDSENTRYON* = 1 - SSTF_BORDER* = 2 - SSTF_CHARS* = 1 - SSTF_DISPLAY* = 3 - SSTF_NONE* = 0 - SSGF_DISPLAY* = 3 - SSGF_NONE* = 0 - SSWF_CUSTOM* = 4 - SSWF_DISPLAY* = 3 - SSWF_NONE* = 0 - SSWF_TITLE* = 1 - SSWF_WINDOW* = 2 - # ACCESSTIMEOUT structure - ATF_ONOFFFEEDBACK* = 2 - ATF_TIMEOUTON* = 1 - # HIGHCONTRAST structure - HCF_AVAILABLE* = 2 - HCF_CONFIRMHOTKEY* = 8 - HCF_HIGHCONTRASTON* = 1 - HCF_HOTKEYACTIVE* = 4 - HCF_HOTKEYAVAILABLE* = 64 - HCF_HOTKEYSOUND* = 16 - HCF_INDICATOR* = 32 - # TOGGLEKEYS structure - TKF_AVAILABLE* = 2 - TKF_CONFIRMHOTKEY* = 8 - TKF_HOTKEYACTIVE* = 4 - TKF_HOTKEYSOUND* = 16 - TKF_TOGGLEKEYSON* = 1 - # Installable Policy - PP_DISPLAYERRORS* = 1 - # SERVICE_INFO structure - RESOURCEDISPLAYTYPE_DOMAIN* = 1 - RESOURCEDISPLAYTYPE_FILE* = 4 - RESOURCEDISPLAYTYPE_GENERIC* = 0 - RESOURCEDISPLAYTYPE_GROUP* = 5 - RESOURCEDISPLAYTYPE_SERVER* = 2 - RESOURCEDISPLAYTYPE_SHARE* = 3 - # KEY_EVENT_RECORD structure - CAPSLOCK_ON* = 128 - ENHANCED_KEY* = 256 - LEFT_ALT_PRESSED* = 2 - LEFT_CTRL_PRESSED* = 8 - NUMLOCK_ON* = 32 - RIGHT_ALT_PRESSED* = 1 - RIGHT_CTRL_PRESSED* = 4 - SCROLLLOCK_ON* = 64 - SHIFT_PRESSED* = 16 - # MOUSE_EVENT_RECORD structure - FROM_LEFT_1ST_BUTTON_PRESSED* = 1 - RIGHTMOST_BUTTON_PRESSED* = 2 - FROM_LEFT_2ND_BUTTON_PRESSED* = 4 - FROM_LEFT_3RD_BUTTON_PRESSED* = 8 - FROM_LEFT_4TH_BUTTON_PRESSED* = 16 - DOUBLE_CLICK* = 2 - MOUSE_MOVED* = 1 - # INPUT_RECORD structure - KEY_EVENT* = 1 - cMOUSE_EVENT* = 2 - WINDOW_BUFFER_SIZE_EVENT* = 4 - MENU_EVENT* = 8 - FOCUS_EVENT* = 16 - # BITMAPINFOHEADER structure - BI_RGB* = 0 - BI_RLE8* = 1 - BI_RLE4* = 2 - BI_BITFIELDS* = 3 - # Extensions to OpenGL - # ChoosePixelFormat - PFD_DOUBLEBUFFER* = 0x00000001 - PFD_STEREO* = 0x00000002 - PFD_DRAW_TO_WINDOW* = 0x00000004 - PFD_DRAW_TO_BITMAP* = 0x00000008 - PFD_SUPPORT_GDI* = 0x00000010 - PFD_SUPPORT_OPENGL* = 0x00000020 - PFD_DEPTH_DONTCARE* = 0x20000000 - PFD_DOUBLEBUFFER_DONTCARE* = 0x40000000 - PFD_STEREO_DONTCARE* = 0x80000000 - PFD_TYPE_RGBA* = 0 - PFD_TYPE_COLORINDEX* = 1 - PFD_MAIN_PLANE* = 0 - PFD_OVERLAY_PLANE* = 1 - PFD_UNDERLAY_PLANE* = -1 - # wglUseFontOutlines - WGL_FONT_LINES* = 0 - WGL_FONT_POLYGONS* = 1 - PFD_GENERIC_FORMAT* = 0x00000040 - PFD_NEED_PALETTE* = 0x00000080 - PFD_NEED_SYSTEM_PALETTE* = 0x00000100 - PFD_SWAP_EXCHANGE* = 0x00000200 - PFD_SWAP_COPY* = 0x00000400 - PFD_SWAP_LAYER_BUFFERS* = 0x00000800 - PFD_GENERIC_ACCELERATED* = 0x00001000 - PFD_SUPPORT_DIRECTDRAW* = 0x00002000 - TMPF_FIXED_PITCH* = 0x00000001 - TMPF_VECTOR* = 0x00000002 - TMPF_TRUETYPE* = 0x00000004 - TMPF_DEVICE* = 0x00000008 - WM_CTLCOLOR* = 25 - LWA_COLORKEY* = 0x00000001 - LWA_ALPHA* = 0x00000002 - ULW_COLORKEY* = 0x00000001 - ULW_ALPHA* = 0x00000002 - ULW_OPAQUE* = 0x00000004 - WS_EX_LAYERED* = 0x00080000 - WS_EX_NOINHERITLAYOUT* = 0x00100000 - WS_EX_LAYOUTRTL* = 0x00400000 - WS_EX_COMPOSITED* = 0x02000000 - WS_EX_NOACTIVATE* = 0x08000000 - C3_LEXICAL* = 1024 - -# --------------------- old stuff, need to organize! --------------- -# BEGINNING of windowsx.h stuff from old headers: - -# was #define dname(params) def_expr -proc GetFirstChild*(h: HWND): HWND - # was #define dname(params) def_expr -proc GetNextSibling*(h: HWND): HWND - # was #define dname(params) def_expr -proc GetWindowID*(h: HWND): int32 - # was #define dname(params) def_expr -proc SubclassWindow*(h: HWND, p: LONG): LONG - # was #define dname(params) def_expr - # argument types are unknown - # return type might be wrong -proc GET_WM_COMMAND_CMD*(w, L: int32): int32 - # return type might be wrong - # was #define dname(params) def_expr - # argument types are unknown - # return type might be wrong -proc GET_WM_COMMAND_ID*(w, L: int32): int32 - # return type might be wrong - # was #define dname(params) def_expr - # argument types are unknown -proc GET_WM_CTLCOLOR_HDC*(w, L, msg: int32): HDC - # was #define dname(params) def_expr - # argument types are unknown -proc GET_WM_CTLCOLOR_HWND*(w, L, msg: int32): HWND - # was #define dname(params) def_expr - # argument types are unknown - # return type might be wrong -proc GET_WM_HSCROLL_CODE*(w, L: int32): int32 - # return type might be wrong - # was #define dname(params) def_expr - # argument types are unknown -proc GET_WM_HSCROLL_HWND*(w, L: int32): HWND - # was #define dname(params) def_expr - # argument types are unknown - # return type might be wrong -proc GET_WM_HSCROLL_POS*(w, L: int32): int32 - # return type might be wrong - # was #define dname(params) def_expr - # argument types are unknown - # return type might be wrong -proc GET_WM_MDIACTIVATE_FACTIVATE*(h, a, b: int32): int32 - # return type might be wrong - # was #define dname(params) def_expr - # argument types are unknown -proc GET_WM_MDIACTIVATE_HWNDACTIVATE*(a, b: int32): HWND - # was #define dname(params) def_expr - # argument types are unknown -proc GET_WM_MDIACTIVATE_HWNDDEACT*(a, b: int32): HWND - # was #define dname(params) def_expr - # argument types are unknown - # return type might be wrong -proc GET_WM_VSCROLL_CODE*(w, L: int32): int32 - # return type might be wrong - # was #define dname(params) def_expr - # argument types are unknown -proc GET_WM_VSCROLL_HWND*(w, L: int32): HWND - # was #define dname(params) def_expr - # argument types are unknown - # return type might be wrong -proc GET_WM_VSCROLL_POS*(w, L: int32): int32 - # return type might be wrong - # Not convertable by H2PAS - # END OF windowsx.h stuff from old headers - # ------------------------------------------------------------------ - -const - # BEGINNING of shellapi.h stuff from old headers - SE_ERR_SHARE* = 26 - SE_ERR_ASSOCINCOMPLETE* = 27 - SE_ERR_DDETIMEOUT* = 28 - SE_ERR_DDEFAIL* = 29 - SE_ERR_DDEBUSY* = 30 - SE_ERR_NOASSOC* = 31 - # END OF shellapi.h stuff from old headers - # - # ------------------------------------------------------------------ - # From ddeml.h in old Cygnus headers - XCLASS_BOOL* = 0x00001000 - XCLASS_DATA* = 0x00002000 - XCLASS_FLAGS* = 0x00004000 - XCLASS_MASK* = 0x0000FC00 - XCLASS_NOTIFICATION* = 0x00008000 - XTYPF_NOBLOCK* = 0x00000002 - XTYP_ADVDATA* = 0x00004010 - XTYP_ADVREQ* = 0x00002022 - XTYP_ADVSTART* = 0x00001030 - XTYP_ADVSTOP* = 0x00008040 - XTYP_CONNECT* = 0x00001062 - XTYP_CONNECT_CONFIRM* = 0x00008072 - XTYP_DISCONNECT* = 0x000080C2 - XTYP_EXECUTE* = 0x00004050 - XTYP_POKE* = 0x00004090 - XTYP_REQUEST* = 0x000020B0 - XTYP_WILDCONNECT* = 0x000020E2 - XTYP_REGISTER* = 0x000080A2 - XTYP_ERROR* = 0x00008002 - XTYP_XACT_COMPLETE* = 0x00008080 - XTYP_UNREGISTER* = 0x000080D2 - DMLERR_DLL_USAGE* = 0x00004004 - DMLERR_INVALIDPARAMETER* = 0x00004006 - DMLERR_NOTPROCESSED* = 0x00004009 - DMLERR_POSTMSG_FAILED* = 0x0000400C - DMLERR_SERVER_DIED* = 0x0000400E - DMLERR_SYS_ERROR* = 0x0000400F - DMLERR_BUSY* = 0x00004001 - DMLERR_DATAACKTIMEOUT* = 0x00004002 - DMLERR_ADVACKTIMEOUT* = 0x00004000 - DMLERR_DLL_NOT_INITIALIZED* = 0x00004003 - DMLERR_LOW_MEMORY* = 0x00004007 - DMLERR_MEMORY_ERROR* = 0x00004008 - DMLERR_POKEACKTIMEOUT* = 0x0000400B - DMLERR_NO_CONV_ESTABLISHED* = 0x0000400A - DMLERR_REENTRANCY* = 0x0000400D - DMLERR_UNFOUND_QUEUE_ID* = 0x00004011 - DMLERR_UNADVACKTIMEOUT* = 0x00004010 - DMLERR_EXECACKTIMEOUT* = 0x00004005 - DDE_FACK* = 0x00008000 - DDE_FNOTPROCESSED* = 0x00000000 - DNS_REGISTER* = 0x00000001 - DNS_UNREGISTER* = 0x00000002 - CP_WINANSI* = 1004 - CP_WINUNICODE* = 1200 - # Not convertable by H2PAS - # #define EXPENTRY CALLBACK - APPCLASS_STANDARD* = 0x00000000 - # End of stuff from ddeml.h in old Cygnus headers - - BKMODE_LAST* = 2 - CTLCOLOR_MSGBOX* = 0 - CTLCOLOR_EDIT* = 1 - CTLCOLOR_LISTBOX* = 2 - CTLCOLOR_BTN* = 3 - CTLCOLOR_DLG* = 4 - CTLCOLOR_SCROLLBAR* = 5 - CTLCOLOR_STATIC* = 6 - CTLCOLOR_MAX* = 7 - META_SETMAPMODE* = 0x00000103 - META_SETWINDOWORG* = 0x0000020B - META_SETWINDOWEXT* = 0x0000020C - POLYFILL_LAST* = 2 - STATUS_WAIT_0* = 0x00000000 - STATUS_ABANDONED_WAIT_0* = 0x00000080 - STATUS_USER_APC* = 0x000000C0 - STATUS_TIMEOUT* = 0x00000102 - STATUS_PENDING* = 0x00000103 - STATUS_GUARD_PAGE_VIOLATION* = 0x80000001 - STATUS_DATATYPE_MISALIGNMENT* = 0x80000002 - STATUS_BREAKPOINT* = 0x80000003 - STATUS_SINGLE_STEP* = 0x80000004 - STATUS_IN_PAGE_ERROR* = 0xC0000006 - STATUS_INVALID_HANDLE* = 0xC0000008 - STATUS_ILLEGAL_INSTRUCTION* = 0xC000001D - STATUS_NONCONTINUABLE_EXCEPTION* = 0xC0000025 - STATUS_INVALID_DISPOSITION* = 0xC0000026 - STATUS_ARRAY_BOUNDS_EXCEEDED* = 0xC000008C - STATUS_FLOAT_DENORMAL_OPERAND* = 0xC000008D - STATUS_FLOAT_DIVIDE_BY_ZERO* = 0xC000008E - STATUS_FLOAT_INEXACT_RESULT* = 0xC000008F - STATUS_FLOAT_INVALID_OPERATION* = 0xC0000090 - STATUS_FLOAT_OVERFLOW* = 0xC0000091 - STATUS_FLOAT_STACK_CHECK* = 0xC0000092 - STATUS_FLOAT_UNDERFLOW* = 0xC0000093 - STATUS_INTEGER_DIVIDE_BY_ZERO* = 0xC0000094 - STATUS_INTEGER_OVERFLOW* = 0xC0000095 - STATUS_PRIVILEGED_INSTRUCTION* = 0xC0000096 - STATUS_STACK_OVERFLOW* = 0xC00000FD - STATUS_CONTROL_C_EXIT* = 0xC000013A - PROCESSOR_ARCHITECTURE_INTEL* = 0 - PROCESSOR_ARCHITECTURE_MIPS* = 1 - PROCESSOR_ARCHITECTURE_ALPHA* = 2 - PROCESSOR_ARCHITECTURE_PPC* = 3 - -const - SIZEFULLSCREEN* = SIZE_MAXIMIZED - SIZENORMAL* = SIZE_RESTORED - SIZEICONIC* = SIZE_MINIMIZED - -const - EXCEPTION_READ_FAULT* = 0 # Access violation was caused by a read - EXCEPTION_WRITE_FAULT* = 1 # Access violation was caused by a write - -when hostCPU == "ia64": - const - EXCEPTION_EXECUTE_FAULT* = 2 # Access violation was caused by an instruction fetch -else: - const - EXCEPTION_EXECUTE_FAULT* = 8 -when hostCPU == "powerpc": - # ppc - const - CONTEXT_CONTROL* = 1 - CONTEXT_FLOATING_POINT* = 2 - CONTEXT_INTEGER* = 4 - CONTEXT_DEBUG_REGISTERS* = 8 - CONTEXT_FULL* = CONTEXT_CONTROL or CONTEXT_FLOATING_POINT or CONTEXT_INTEGER - CONTEXT_DEBUGGER* = CONTEXT_FULL -when hostCPU == "i386": - # x86 - # The doc refered me to winnt.h, so I had to look... - const - SIZE_OF_80387_REGISTERS* = 80 # Values for contextflags - CONTEXT_i386* = 0x00010000 # this assumes that i386 and - CONTEXT_i486* = 0x00010000 # i486 have identical context records - CONTEXT_CONTROL* = CONTEXT_i386 or 1 # SS:SP, CS:IP, FLAGS, BP - CONTEXT_INTEGER* = CONTEXT_i386 or 2 # AX, BX, CX, DX, SI, DI - CONTEXT_SEGMENTS* = CONTEXT_i386 or 4 # DS, ES, FS, GS - CONTEXT_FLOATING_POINT* = CONTEXT_i386 or 8 # 387 state - CONTEXT_DEBUG_REGISTERS* = CONTEXT_i386 or 0x00000010 # DB 0-3,6,7 - CONTEXT_EXTENDED_REGISTERS* = CONTEXT_i386 or 0x00000020 # cpu specific extensions - CONTEXT_FULL* = (CONTEXT_CONTROL or CONTEXT_INTEGER) or CONTEXT_SEGMENTS - CONTEXT_ALL* = CONTEXT_FULL or CONTEXT_FLOATING_POINT or - CONTEXT_DEBUG_REGISTERS or CONTEXT_EXTENDED_REGISTERS # our own invention - FLAG_TRACE_BIT* = 0x00000100 - CONTEXT_DEBUGGER* = CONTEXT_FULL or CONTEXT_FLOATING_POINT -when hostCPU == "amd64": - const - INITIAL_MXCSR* = 0x00001F80 # initial MXCSR value - INITIAL_FPCSR* = 0x0000027F # initial FPCSR value - CONTEXT_AMD64* = 0x00100000 - CONTEXT_CONTROL* = (CONTEXT_AMD64 or 0x00000001) - CONTEXT_INTEGER* = (CONTEXT_AMD64 or 0x00000002) - CONTEXT_SEGMENTS* = (CONTEXT_AMD64 or 0x00000004) - CONTEXT_FLOATING_POINT* = (CONTEXT_AMD64 or 0x00000008) - CONTEXT_DEBUG_REGISTERS* = (CONTEXT_AMD64 or 0x00000010) - CONTEXT_FULL* = CONTEXT_CONTROL or CONTEXT_INTEGER or CONTEXT_FLOATING_POINT - CONTEXT_ALL* = CONTEXT_CONTROL or CONTEXT_INTEGER or CONTEXT_SEGMENTS or - CONTEXT_FLOATING_POINT or CONTEXT_DEBUG_REGISTERS - CONTEXT_EXCEPTION_ACTIVE* = 0x08000000 - CONTEXT_SERVICE_ACTIVE* = 0x10000000 - CONTEXT_EXCEPTION_REQUEST* = 0x40000000 - CONTEXT_EXCEPTION_REPORTING* = 0x80000000 - -const - FILTER_TEMP_DUPLICATE_ACCOUNT* = 0x00000001 - FILTER_NORMAL_ACCOUNT* = 0x00000002 - FILTER_INTERDOMAIN_TRUST_ACCOUNT* = 0x00000008 - FILTER_WORKSTATION_TRUST_ACCOUNT* = 0x00000010 - FILTER_SERVER_TRUST_ACCOUNT* = 0x00000020 - LOGON32_LOGON_INTERACTIVE* = 0x00000002 - LOGON32_LOGON_BATCH* = 0x00000004 - LOGON32_LOGON_SERVICE* = 0x00000005 - LOGON32_PROVIDER_DEFAULT* = 0x00000000 - LOGON32_PROVIDER_WINNT35* = 0x00000001 - QID_SYNC* = 0xFFFFFFFF - # Magic numbers in PE executable header. # e_magic field - IMAGE_DOS_SIGNATURE* = 0x00005A4D - # nt_signature field - IMAGE_NT_SIGNATURE* = 0x00004550 - # Severity values - SEVERITY_SUCCESS* = 0 - SEVERITY_ERROR* = 1 - # Variant type codes (wtypes.h). - # Some, not all though - VT_EMPTY* = 0 - VT_NULL* = 1 - VT_I2* = 2 - VT_I4* = 3 - VT_R4* = 4 - VT_R8* = 5 - VT_BSTR* = 8 - VT_ERROR* = 10 - VT_BOOL* = 11 - VT_UI1* = 17 - VT_BYREF* = 0x00004000 - VT_RESERVED* = 0x00008000 - -const - # Define the facility codes - FACILITY_WINDOWS* = 8 - FACILITY_STORAGE* = 3 - FACILITY_RPC* = 1 - FACILITY_SSPI* = 9 - FACILITY_WIN32* = 7 - FACILITY_CONTROL* = 10 - FACILITY_NULL* = 0 - FACILITY_INTERNET* = 12 - FACILITY_ITF* = 4 - FACILITY_DISPATCH* = 2 - FACILITY_CERT* = 11 # Manually added, bug 2672 - ICON_SMALL* = 0 - ICON_BIG* = 1 - # For the TrackMouseEvent - TME_HOVER* = 0x00000001 - TME_LEAVE* = 0x00000002 - TME_QUERY* = 0x40000000 - TME_CANCEL* = DWORD(0x80000000) - HOVER_DEFAULT* = DWORD(0xFFFFFFFF) # Manually added, bug 3270 - COLOR_HOTLIGHT* = 26 - COLOR_GRADIENTACTIVECAPTION* = 27 - COLOR_GRADIENTINACTIVECAPTION* = 28 - COLOR_MENUHILIGHT* = 29 - COLOR_MENUBAR* = 30 - WM_APP* = 0x00008000 - SYSRGN* = 4 - UIS_SET* = 1 - UIS_CLEAR* = 2 - UIS_INITIALIZE* = 3 - UISF_HIDEFOCUS* = 0x00000001 - UISF_HIDEACCEL* = 0x00000002 - UISF_ACTIVE* = 0x00000004 - -type - # WARNING - # the variable argument list - # is not implemented for FPC - # va_list is just a dummy record - # MvdV: Nevertheless it should be a pointer type, not a record - va_list* = cstring - ABC* {.final, pure.} = object - abcA*: int32 - abcB*: WINUINT - abcC*: int32 - - LPABC* = ptr ABC - PABC* = ptr ABC - ABCFLOAT* {.final, pure.} = object - abcfA*: float32 - abcfB*: float32 - abcfC*: float32 - LPABCFLOAT* = ptr ABCFLOAT - PABCFLOAT* = ptr ABCFLOAT - - ACCEL* {.final, pure.} = object - fVirt*: int8 - key*: int16 - cmd*: int16 - LPACCEL* = ptr ACCEL - PACCEL* = ptr ACCEL - ACE_HEADER* {.final, pure.} = object - AceType*: int8 - AceFlags*: int8 - AceSize*: int16 - - PACE_HEADER* = ptr ACE_HEADER - ACCESS_MASK* = DWORD - REGSAM* = ACCESS_MASK - ACCESS_ALLOWED_ACE* {.final, pure.} = object - Header*: ACE_HEADER - Mask*: ACCESS_MASK - SidStart*: DWORD - - PACCESS_ALLOWED_ACE* = ptr ACCESS_ALLOWED_ACE - ACCESS_DENIED_ACE* {.final, pure.} = object - Header*: ACE_HEADER - Mask*: ACCESS_MASK - SidStart*: DWORD - - ACCESSTIMEOUT* {.final, pure.} = object - cbSize*: WINUINT - dwFlags*: DWORD - iTimeOutMSec*: DWORD - - PACCESSTIMEOUT* = ptr ACCESSTIMEOUT - ACL* {.final, pure.} = object - AclRevision*: int8 - Sbz1*: int8 - AclSize*: int16 - AceCount*: int16 - Sbz2*: int16 - - PACL* = ptr ACL - TACL_REVISION_INFORMATION* {.final, pure.} = object # Name conflit if we drop the `T` - AclRevision*: DWORD - PACLREVISIONINFORMATION* = ptr TACL_REVISION_INFORMATION - - TACL_SIZE_INFORMATION* {.final, pure.} = object # Name conflict if we drop the `T` - AceCount*: DWORD - AclBytesInUse*: DWORD - AclBytesFree*: DWORD - PACLSIZEINFORMATION* = ptr TACL_SIZE_INFORMATION - ACTION_HEADER* {.final, pure.} = object - transport_id*: ULONG - action_code*: USHORT - reserved*: USHORT - - PACTIONHEADER* = ptr ACTION_HEADER - ADAPTER_STATUS* {.final, pure.} = object - adapter_address*: array[0..5, UCHAR] - rev_major*: UCHAR - reserved0*: UCHAR - adapter_type*: UCHAR - rev_minor*: UCHAR - duration*: int16 - frmr_recv*: int16 - frmr_xmit*: int16 - iframe_recv_err*: int16 - xmit_aborts*: int16 - xmit_success*: DWORD - recv_success*: DWORD - iframe_xmit_err*: int16 - recv_buff_unavail*: int16 - t1_timeouts*: int16 - ti_timeouts*: int16 - reserved1*: DWORD - free_ncbs*: int16 - max_cfg_ncbs*: int16 - max_ncbs*: int16 - xmit_buf_unavail*: int16 - max_dgram_size*: int16 - pending_sess*: int16 - max_cfg_sess*: int16 - max_sess*: int16 - max_sess_pkt_size*: int16 - name_count*: int16 - - PADAPTERSTATUS* = ptr ADAPTER_STATUS - ADDJOB_INFO_1* {.final, pure.} = object - Path*: LPTSTR - JobId*: DWORD - - PADDJOB_INFO_1* = ptr ADDJOB_INFO_1 - ANIMATIONINFO* {.final, pure.} = object - cbSize*: WINUINT - iMinAnimate*: int32 - - LPANIMATIONINFO* = ptr ANIMATIONINFO - PANIMATIONINFO* = ptr ANIMATIONINFO - - APPBARDATA* {.final, pure.} = object - cbSize*: DWORD - hWnd*: HWND - uCallbackMessage*: WINUINT - uEdge*: WINUINT - rc*: RECT - lParam*: LPARAM - - PAppBarData* = ptr APPBARDATA - BITMAP* {.final, pure.} = object - bmType*: LONG - bmWidth*: LONG - bmHeight*: LONG - bmWidthBytes*: LONG - bmPlanes*: int16 - bmBitsPixel*: int16 - bmBits*: LPVOID - - PBITMAP* = ptr BITMAP - NPBITMAP* = ptr BITMAP - LPBITMAP* = ptr BITMAP - BITMAPCOREHEADER* {.final, pure.} = object - bcSize*: DWORD - bcWidth*: int16 - bcHeight*: int16 - bcPlanes*: int16 - bcBitCount*: int16 - - PBITMAPCOREHEADER* = ptr BITMAPCOREHEADER - RGBTRIPLE* {.final, pure.} = object - rgbtBlue*: int8 - rgbtGreen*: int8 - rgbtRed*: int8 - - PRGBTRIPLE* = ptr RGBTRIPLE - BITMAPCOREINFO* {.final, pure.} = object - bmciHeader*: BITMAPCOREHEADER - bmciColors*: array[0..0, RGBTRIPLE] - - PBITMAPCOREINFO* = ptr BITMAPCOREINFO - LPBITMAPCOREINFO* = ptr BITMAPCOREINFO -# TBITMAPCOREINFO* = BITMAPCOREINFO # error - # WORD bfReserved1; - # WORD bfReserved2; - # in declarator_list - BITMAPINFOHEADER* {.final, pure.} = object - biSize*: DWORD - biWidth*: LONG - biHeight*: LONG - biPlanes*: int16 - biBitCount*: int16 - biCompression*: DWORD - biSizeImage*: DWORD - biXPelsPerMeter*: LONG - biYPelsPerMeter*: LONG - biClrUsed*: DWORD - biClrImportant*: DWORD - - LPBITMAPINFOHEADER* = ptr BITMAPINFOHEADER - PBITMAPINFOHEADER* = ptr BITMAPINFOHEADER - RGBQUAD* {.final, pure.} = object - rgbBlue*: int8 - rgbGreen*: int8 - rgbRed*: int8 - rgbReserved*: int8 - - PRGBQUAD* = ptr RGBQUAD - BITMAPINFO* {.final, pure.} = object - bmiHeader*: BITMAPINFOHEADER - bmiColors*: array[0..0, RGBQUAD] - - LPBITMAPINFO* = ptr BITMAPINFO - PBITMAPINFO* = ptr BITMAPINFO - FXPT2DOT30* = int32 - LPFXPT2DOT30* = ptr FXPT2DOT30 - TPFXPT2DOT30* = FXPT2DOT30 - PPFXPT2DOT30* = ptr FXPT2DOT30 - CIEXYZ* {.final, pure.} = object - ciexyzX*: FXPT2DOT30 - ciexyzY*: FXPT2DOT30 - ciexyzZ*: FXPT2DOT30 - - LPCIEXYZ* = ptr CIEXYZ - PCIEXYZ* = ptr CIEXYZ - CIEXYZTRIPLE* {.final, pure.} = object - ciexyzRed*: CIEXYZ - ciexyzGreen*: CIEXYZ - ciexyzBlue*: CIEXYZ - - LPCIEXYZTRIPLE* = ptr CIEXYZTRIPLE - PCIEXYZTRIPLE* = ptr CIEXYZTRIPLE - BITMAPV4HEADER* {.final, pure.} = object - bV4Size*: DWORD - bV4Width*: LONG - bV4Height*: LONG - bV4Planes*: int16 - bV4BitCount*: int16 - bV4V4Compression*: DWORD - bV4SizeImage*: DWORD - bV4XPelsPerMeter*: LONG - bV4YPelsPerMeter*: LONG - bV4ClrUsed*: DWORD - bV4ClrImportant*: DWORD - bV4RedMask*: DWORD - bV4GreenMask*: DWORD - bV4BlueMask*: DWORD - bV4AlphaMask*: DWORD - bV4CSType*: DWORD - bV4Endpoints*: CIEXYZTRIPLE - bV4GammaRed*: DWORD - bV4GammaGreen*: DWORD - bV4GammaBlue*: DWORD - - LPBITMAPV4HEADER* = ptr BITMAPV4HEADER - PBITMAPV4HEADER* = ptr BITMAPV4HEADER - BITMAPFILEHEADER* {.final, pure.} = object - bfType*: int16 - bfSize*: DWord - bfReserved1*: int16 - bfReserved2*: int16 - bfOffBits*: DWord - - BLOB* {.final, pure.} = object - cbSize*: ULONG - pBlobData*: ptr int8 - - PBLOB* = ptr BLOB - SHITEMID* {.final, pure.} = object - cb*: USHORT - abID*: array[0..0, int8] - - LPSHITEMID* = ptr SHITEMID - LPCSHITEMID* = ptr SHITEMID - PSHITEMID* = ptr SHITEMID - ITEMIDLIST* {.final, pure.} = object - mkid*: SHITEMID - - LPITEMIDLIST* = ptr ITEMIDLIST - LPCITEMIDLIST* = ptr ITEMIDLIST - PITEMIDLIST* = ptr ITEMIDLIST - BROWSEINFO* {.final, pure.} = object - hwndOwner*: HWND - pidlRoot*: LPCITEMIDLIST - pszDisplayName*: LPSTR - lpszTitle*: LPCSTR - ulFlags*: WINUINT - lpfn*: BFFCALLBACK - lParam*: LPARAM - iImage*: int32 - - LPBROWSEINFO* = ptr BROWSEINFO - PBROWSEINFO* = ptr BROWSEINFO - - BY_HANDLE_FILE_INFORMATION* {.final, pure.} = object - dwFileAttributes*: DWORD - ftCreationTime*: FILETIME - ftLastAccessTime*: FILETIME - ftLastWriteTime*: FILETIME - dwVolumeSerialNumber*: DWORD - nFileSizeHigh*: DWORD - nFileSizeLow*: DWORD - nNumberOfLinks*: DWORD - nFileIndexHigh*: DWORD - nFileIndexLow*: DWORD - - LPBY_HANDLE_FILE_INFORMATION* = ptr BY_HANDLE_FILE_INFORMATION - PBYHANDLEFILEINFORMATION* = ptr BY_HANDLE_FILE_INFORMATION - FIXED* {.final, pure.} = object - fract*: int16 - value*: SHORT - - PFIXED* = ptr FIXED - POINTFX* {.final, pure.} = object - x*: FIXED - y*: FIXED - - PPOINTFX* = ptr POINTFX - - SmallPoint* {.final, pure.} = object - X*, Y*: SHORT - - CANDIDATEFORM* {.final, pure.} = object - dwIndex*: DWORD - dwStyle*: DWORD - ptCurrentPos*: POINT - rcArea*: RECT - - LPCANDIDATEFORM* = ptr CANDIDATEFORM - PCANDIDATEFORM* = ptr CANDIDATEFORM - CANDIDATELIST* {.final, pure.} = object - dwSize*: DWORD - dwStyle*: DWORD - dwCount*: DWORD - dwSelection*: DWORD - dwPageStart*: DWORD - dwPageSize*: DWORD - dwOffset*: array[0..0, DWORD] - - LPCANDIDATELIST* = ptr CANDIDATELIST - PCANDIDATELIST* = ptr CANDIDATELIST - CREATESTRUCT* {.final, pure.} = object - lpCreateParams*: LPVOID - hInstance*: HINST - hMenu*: HMENU - hwndParent*: HWND - cy*: int32 - cx*: int32 - y*: int32 - x*: int32 - style*: LONG - lpszName*: LPCTSTR - lpszClass*: LPCTSTR - dwExStyle*: DWORD - - LPCREATESTRUCT* = ptr CREATESTRUCT - PCREATESTRUCT* = ptr CREATESTRUCT - CBT_CREATEWND* {.final, pure.} = object - lpcs*: LPCREATESTRUCT - hwndInsertAfter*: HWND - - PCBT_CREATEWND* = ptr CBT_CREATEWND - CBTACTIVATESTRUCT* {.final, pure.} = object - fMouse*: WINBOOL - hWndActive*: HWND - - PCBTACTIVATESTRUCT* = ptr CBTACTIVATESTRUCT - CHAR_INFO* {.final, pure.} = object - UnicodeChar*: WCHAR - Attributes*: int16 # other union part: AsciiChar : CHAR - - PCHAR_INFO* = ptr CHAR_INFO - CHARFORMAT* {.final, pure.} = object - cbSize*: WINUINT - dwMask*: DWORD - dwEffects*: DWORD - yHeight*: LONG - yOffset*: LONG - crTextColor*: COLORREF - bCharSet*: int8 - bPitchAndFamily*: int8 - szFaceName*: array[0..(LF_FACESIZE) - 1, CHAR] - - Pcharformat* = ptr CHARFORMAT - CHARRANGE* {.final, pure.} = object - cpMin*: LONG - cpMax*: LONG - - Pcharrange* = ptr CHARRANGE - CHARSET* {.final, pure.} = object - aflBlock*: array[0..2, DWORD] - flLang*: DWORD - - PCHARSET* = ptr CHARSET - FONTSIGNATURE* {.final, pure.} = object - fsUsb*: array[0..3, DWORD] - fsCsb*: array[0..1, DWORD] - - LPFONTSIGNATURE* = ptr FONTSIGNATURE - PFONTSIGNATURE* = ptr FONTSIGNATURE - CHARSETINFO* {.final, pure.} = object - ciCharset*: WINUINT - ciACP*: WINUINT - fs*: FONTSIGNATURE - - LPCHARSETINFO* = ptr CHARSETINFO - PCHARSETINFO* = ptr CHARSETINFO - #CHOOSECOLOR = record confilcts with function ChooseColor - TCHOOSECOLOR* {.final, pure.} = object - lStructSize*: DWORD - hwndOwner*: HWND - hInstance*: HWND - rgbResult*: COLORREF - lpCustColors*: ptr COLORREF - Flags*: DWORD - lCustData*: LPARAM - lpfnHook*: LPCCHOOKPROC - lpTemplateName*: LPCTSTR - - LPCHOOSECOLOR* = ptr TCHOOSECOLOR - PCHOOSECOLOR* = ptr TCHOOSECOLOR - LOGFONT* {.final, pure.} = object - lfHeight*: LONG - lfWidth*: LONG - lfEscapement*: LONG - lfOrientation*: LONG - lfWeight*: LONG - lfItalic*: int8 - lfUnderline*: int8 - lfStrikeOut*: int8 - lfCharSet*: int8 - lfOutPrecision*: int8 - lfClipPrecision*: int8 - lfQuality*: int8 - lfPitchAndFamily*: int8 - lfFaceName*: array[0..(LF_FACESIZE) - 1, CHAR] - - LPLOGFONT* = ptr LOGFONT - PLOGFONT* = ptr LOGFONT - PLOGFONTA* = PLOGFONT - LOGFONTW* {.final, pure.} = object - lfHeight*: LONG - lfWidth*: LONG - lfEscapement*: LONG - lfOrientation*: LONG - lfWeight*: LONG - lfItalic*: int8 - lfUnderline*: int8 - lfStrikeOut*: int8 - lfCharSet*: int8 - lfOutPrecision*: int8 - lfClipPrecision*: int8 - lfQuality*: int8 - lfPitchAndFamily*: int8 - lfFaceName*: array[0..LF_FACESIZE - 1, WCHAR] - - LPLOGFONTW* = ptr LOGFONTW - NPLOGFONTW* = ptr LOGFONTW - PLogFontW* = ptr LogFontW - TCHOOSEFONT* {.final, pure.} = object # Name conflict if we drop the `T` - lStructSize*: DWORD - hwndOwner*: HWND - hDC*: HDC - lpLogFont*: LPLOGFONT - iPointSize*: WINT - Flags*: DWORD - rgbColors*: DWORD - lCustData*: LPARAM - lpfnHook*: LPCFHOOKPROC - lpTemplateName*: LPCTSTR - hInstance*: HINST - lpszStyle*: LPTSTR - nFontType*: int16 - MISSING_ALIGNMENT*: int16 - nSizeMin*: WINT - nSizeMax*: WINT - - LPCHOOSEFONT* = ptr TCHOOSEFONT - PCHOOSEFONT* = ptr TCHOOSEFONT - CIDA* {.final, pure.} = object - cidl*: WINUINT - aoffset*: array[0..0, WINUINT] - - LPIDA* = ptr CIDA - PIDA* = ptr CIDA - CLIENTCREATESTRUCT* {.final, pure.} = object - hWindowMenu*: HANDLE - idFirstChild*: WINUINT - - LPCLIENTCREATESTRUCT* = ptr CLIENTCREATESTRUCT - PCLIENTCREATESTRUCT* = ptr CLIENTCREATESTRUCT - CMINVOKECOMMANDINFO* {.final, pure.} = object - cbSize*: DWORD - fMask*: DWORD - hwnd*: HWND - lpVerb*: LPCSTR - lpParameters*: LPCSTR - lpDirectory*: LPCSTR - nShow*: int32 - dwHotKey*: DWORD - hIcon*: HANDLE - - LPCMINVOKECOMMANDINFO* = ptr CMINVOKECOMMANDINFO - PCMInvokeCommandInfo* = ptr CMINVOKECOMMANDINFO - COLORADJUSTMENT* {.final, pure.} = object - caSize*: int16 - caFlags*: int16 - caIlluminantIndex*: int16 - caRedGamma*: int16 - caGreenGamma*: int16 - caBlueGamma*: int16 - caReferenceBlack*: int16 - caReferenceWhite*: int16 - caContrast*: SHORT - caBrightness*: SHORT - caColorfulness*: SHORT - caRedGreenTint*: SHORT - - LPCOLORADJUSTMENT* = ptr COLORADJUSTMENT - PCOLORADJUSTMENT* = ptr COLORADJUSTMENT - COLORMAP* {.final, pure.} = object - `from`*: COLORREF - `to`*: COLORREF # XXX! - - LPCOLORMAP* = ptr COLORMAP - PCOLORMAP* = ptr COLORMAP - DCB* {.final, pure.} = object - DCBlength*: DWORD - BaudRate*: DWORD - flags*: DWORD - wReserved*: int16 - XonLim*: int16 - XoffLim*: int16 - ByteSize*: int8 - Parity*: int8 - StopBits*: int8 - XonChar*: char - XoffChar*: char - ErrorChar*: char - EofChar*: char - EvtChar*: char - wReserved1*: int16 - - LPDCB* = ptr DCB - PDCB* = ptr DCB -{.deprecated: [TABC: ABC, TABCFLOAT: ABCFLOAT, TACCEL: ACCEL, TACE_HEADER: ACE_HEADER, - TACCESS_ALLOWED_ACE: ACCESS_ALLOWED_ACE, TACCESS_DENIED_ACE: ACCESS_DENIED_ACE, - TACCESSTIMEOUT: ACCESSTIMEOUT, TACL: ACL, TACTIONHEADER: ACTION_HEADER, - TADAPTERSTATUS: ADAPTER_STATUS, TADDJOB_INFO_1: ADDJOB_INFO_1, - TANIMATIONINFO: ANIMATIONINFO, TAppBarData: APPBARDATA, TBITMAP: BITMAP, - TBITMAPCOREHEADER: BITMAPCOREHEADER, TRGBTRIPLE: RGBTRIPLE, - TBITMAPCOREINFO: BITMAPCOREINFO, TBITMAPINFOHEADER: BITMAPINFOHEADER, - TRGBQUAD: RGBQUAD, TBITMAPINFO: BITMAPINFO, TPCIEXYZ: CIEXYZ, - TCIEXYZTRIPLE: CIEXYZTRIPLE, TBITMAPV4HEADER: BITMAPV4HEADER, TBLOB: BLOB, - TSHITEMID: SHITEMID, TITEMIDLIST: ITEMIDLIST, Tbrowseinfo: BROWSEINFO, - TBYHANDLEFILEINFORMATION: BY_HANDLE_FILE_INFORMATION, TFIXED: FIXED, - TPOINTFX: POINTFX, TSmallPoint: SmallPoint, TCANDIDATEFORM: CANDIDATEFORM, - TCANDIDATELIST: CANDIDATELIST, TCREATESTRUCT: CREATESTRUCT, - TCBT_CREATEWND: CBT_CREATEWND, TCBTACTIVATESTRUCT: CBTACTIVATESTRUCT, - TCHAR_INFO: CHAR_INFO, Tcharformat: CHARFORMAT, Tcharrange: CHARRANGE, - TCHARSET: CHARSET, TFONTSIGNATURE: FONTSIGNATURE, TCHARSETINFO: CHARSETINFO, - TLOGFONT: LOGFONT, TLOGFONTA: LOGFONT, TLogFontW: LOGFONTW, - TIDA: CIDA, TCLIENTCREATESTRUCT: CLIENTCREATESTRUCT, - TCMInvokeCommandInfo: CMINVOKECOMMANDINFO, TCOLORADJUSTMENT: COLORADJUSTMENT, - TCOLORMAP: COLORMAP, TDCB: DCB -].} - -const - bm_DCB_fBinary* = 1 - bp_DCB_fBinary* = 0'i32 - bm_DCB_fParity* = 0x00000002 - bp_DCB_fParity* = 1'i32 - bm_DCB_fOutxCtsFlow* = 0x00000004 - bp_DCB_fOutxCtsFlow* = 2'i32 - bm_DCB_fOutxDsrFlow* = 0x00000008 - bp_DCB_fOutxDsrFlow* = 3'i32 - bm_DCB_fDtrControl* = 0x00000030 - bp_DCB_fDtrControl* = 4'i32 - bm_DCB_fDsrSensitivity* = 0x00000040 - bp_DCB_fDsrSensitivity* = 6'i32 - bm_DCB_fTXContinueOnXoff* = 0x00000080 - bp_DCB_fTXContinueOnXoff* = 7'i32 - bm_DCB_fOutX* = 0x00000100 - bp_DCB_fOutX* = 8'i32 - bm_DCB_fInX* = 0x00000200 - bp_DCB_fInX* = 9'i32 - bm_DCB_fErrorChar* = 0x00000400 - bp_DCB_fErrorChar* = 10'i32 - bm_DCB_fNull* = 0x00000800 - bp_DCB_fNull* = 11'i32 - bm_DCB_fRtsControl* = 0x00003000 - bp_DCB_fRtsControl* = 12'i32 - bm_DCB_fAbortOnError* = 0x00004000 - bp_DCB_fAbortOnError* = 14'i32 - bm_DCB_fDummy2* = 0xFFFF8000'i32 - bp_DCB_fDummy2* = 15'i32 - -proc fBinary*(a: var DCB): DWORD -proc set_fBinary*(a: var DCB, fBinary: DWORD) -proc fParity*(a: var DCB): DWORD -proc set_fParity*(a: var DCB, fParity: DWORD) -proc fOutxCtsFlow*(a: var DCB): DWORD -proc set_fOutxCtsFlow*(a: var DCB, fOutxCtsFlow: DWORD) -proc fOutxDsrFlow*(a: var DCB): DWORD -proc set_fOutxDsrFlow*(a: var DCB, fOutxDsrFlow: DWORD) -proc fDtrControl*(a: var DCB): DWORD -proc set_fDtrControl*(a: var DCB, fDtrControl: DWORD) -proc fDsrSensitivity*(a: var DCB): DWORD -proc set_fDsrSensitivity*(a: var DCB, fDsrSensitivity: DWORD) -proc fTXContinueOnXoff*(a: var DCB): DWORD -proc set_fTXContinueOnXoff*(a: var DCB, fTXContinueOnXoff: DWORD) -proc fOutX*(a: var DCB): DWORD -proc set_fOutX*(a: var DCB, fOutX: DWORD) -proc fInX*(a: var DCB): DWORD -proc set_fInX*(a: var DCB, fInX: DWORD) -proc fErrorChar*(a: var DCB): DWORD -proc set_fErrorChar*(a: var DCB, fErrorChar: DWORD) -proc fNull*(a: var DCB): DWORD -proc set_fNull*(a: var DCB, fNull: DWORD) -proc fRtsControl*(a: var DCB): DWORD -proc set_fRtsControl*(a: var DCB, fRtsControl: DWORD) -proc fAbortOnError*(a: var DCB): DWORD -proc set_fAbortOnError*(a: var DCB, fAbortOnError: DWORD) -proc fDummy2*(a: var DCB): DWORD -proc set_fDummy2*(a: var DCB, fDummy2: DWORD) -type - COMMCONFIG* {.final, pure.} = object - dwSize*: DWORD - wVersion*: int16 - wReserved*: int16 - dcb*: DCB - dwProviderSubType*: DWORD - dwProviderOffset*: DWORD - dwProviderSize*: DWORD - wcProviderData*: array[0..0, WCHAR] - - LPCOMMCONFIG* = ptr COMMCONFIG - PCOMMCONFIG* = ptr COMMCONFIG - COMMPROP* {.final, pure.} = object - wPacketLength*: int16 - wPacketVersion*: int16 - dwServiceMask*: DWORD - dwReserved1*: DWORD - dwMaxTxQueue*: DWORD - dwMaxRxQueue*: DWORD - dwMaxBaud*: DWORD - dwProvSubType*: DWORD - dwProvCapabilities*: DWORD - dwSettableParams*: DWORD - dwSettableBaud*: DWORD - wSettableData*: int16 - wSettableStopParity*: int16 - dwCurrentTxQueue*: DWORD - dwCurrentRxQueue*: DWORD - dwProvSpec1*: DWORD - dwProvSpec2*: DWORD - wcProvChar*: array[0..0, WCHAR] - - LPCOMMPROP* = ptr COMMPROP - PCOMMPROP* = ptr COMMPROP - COMMTIMEOUTS* {.final, pure.} = object - ReadIntervalTimeout*: DWORD - ReadTotalTimeoutMultiplier*: DWORD - ReadTotalTimeoutConstant*: DWORD - WriteTotalTimeoutMultiplier*: DWORD - WriteTotalTimeoutConstant*: DWORD - - LPCOMMTIMEOUTS* = ptr COMMTIMEOUTS - PCOMMTIMEOUTS* = ptr COMMTIMEOUTS - COMPAREITEMSTRUCT* {.final, pure.} = object - CtlType*: WINUINT - CtlID*: WINUINT - hwndItem*: HWND - itemID1*: WINUINT - itemData1*: ULONG_PTR - itemID2*: WINUINT - itemData2*: ULONG_PTR - - PCOMPAREITEMSTRUCT* = ptr COMPAREITEMSTRUCT - COMPCOLOR* {.final, pure.} = object - crText*: COLORREF - crBackground*: COLORREF - dwEffects*: DWORD - - PCOMPCOLOR* = ptr COMPCOLOR - COMPOSITIONFORM* {.final, pure.} = object - dwStyle*: DWORD - ptCurrentPos*: POINT - rcArea*: RECT - - LPCOMPOSITIONFORM* = ptr COMPOSITIONFORM - PCOMPOSITIONFORM* = ptr COMPOSITIONFORM # ComStatFlags = set of (fCtsHold, fDsrHold, fRlsdHold , fXoffHold , - # fXoffSent , fEof , fTxim , fReserved); - COMSTAT* {.final, pure.} = object - flag0*: DWORD # can't use comstatflags, set packing issues - # and conflicts with macro's - cbInQue*: DWORD - cbOutQue*: DWORD - - LPCOMSTAT* = ptr COMSTAT - PCOMSTAT* = ptr COMSTAT -{.deprecated: [TCOMSTAT: COMSTAT, TCOMPOSITIONFORM: COMPOSITIONFORM, - TCOMPCOLOR: COMPCOLOR, TCOMPAREITEMSTRUCT: COMPAREITEMSTRUCT, - TCOMMTIMEOUTS: COMMTIMEOUTS, TCOMMPROP: COMMPROP, TCOMMCONFIG: COMMCONFIG].} - -const - bm_COMSTAT_fCtsHold* = 0x00000001 - bp_COMSTAT_fCtsHold* = 0'i32 - bm_COMSTAT_fDsrHold* = 0x00000002 - bp_COMSTAT_fDsrHold* = 1'i32 - bm_COMSTAT_fRlsdHold* = 0x00000004 - bp_COMSTAT_fRlsdHold* = 2'i32 - bm_COMSTAT_fXoffHold* = 0x00000008 - bp_COMSTAT_fXoffHold* = 3'i32 - bm_COMSTAT_fXoffSent* = 0x00000010 - bp_COMSTAT_fXoffSent* = 4'i32 - bm_COMSTAT_fEof* = 0x00000020 - bp_COMSTAT_fEof* = 5'i32 - bm_COMSTAT_fTxim* = 0x00000040 - bp_COMSTAT_fTxim* = 6'i32 - bm_COMSTAT_fReserved* = 0xFFFFFF80'i32 - bp_COMSTAT_fReserved* = 7'i32 - -proc fCtsHold*(a: var COMSTAT): DWORD - # should be renamed to get_? -proc set_fCtsHold*(a: var COMSTAT, fCtsHold: DWORD) -proc fDsrHold*(a: var COMSTAT): DWORD -proc set_fDsrHold*(a: var COMSTAT, fDsrHold: DWORD) -proc fRlsdHold*(a: var COMSTAT): DWORD -proc set_fRlsdHold*(a: var COMSTAT, fRlsdHold: DWORD) -proc fXoffHold*(a: var COMSTAT): DWORD -proc set_fXoffHold*(a: var COMSTAT, fXoffHold: DWORD) -proc fXoffSent*(a: var COMSTAT): DWORD -proc set_fXoffSent*(a: var COMSTAT, fXoffSent: DWORD) -proc fEof*(a: var COMSTAT): DWORD -proc set_fEof*(a: var COMSTAT, fEof: DWORD) -proc fTxim*(a: var COMSTAT): DWORD -proc set_fTxim*(a: var COMSTAT, fTxim: DWORD) -proc fReserved*(a: var COMSTAT): DWORD -proc set_fReserved*(a: var COMSTAT, fReserved: DWORD) -type - CONSOLE_CURSOR_INFO* {.final, pure.} = object - dwSize*: DWORD - bVisible*: WINBOOL - - PCONSOLE_CURSOR_INFO* = ptr CONSOLE_CURSOR_INFO - COORD* {.final, pure.} = object - X*: SHORT - Y*: SHORT - - PCOORD* = ptr COORD - SMALL_RECT* {.final, pure.} = object - Left*: SHORT - Top*: SHORT - Right*: SHORT - Bottom*: SHORT - - PSMALL_RECT* = ptr SMALL_RECT - CONSOLE_SCREEN_BUFFER_INFO* {.final, pure.} = object - dwSize*: COORD - dwCursorPosition*: COORD - wAttributes*: int16 - srWindow*: SMALL_RECT - dwMaximumWindowSize*: COORD - - PCONSOLE_SCREEN_BUFFER_INFO* = ptr CONSOLE_SCREEN_BUFFER_INFO - -{.deprecated: [TCONSOLECURSORINFO: CONSOLE_CURSOR_INFO, - TCURSORINFO: CONSOLE_CURSOR_INFO, TCOORD: COORD, TSMALL_RECT: SMALL_RECT, - TCONSOLESCREENBUFFERINFO: CONSOLE_SCREEN_BUFFER_INFO].} - -when defined(i386): - type - FLOATING_SAVE_AREA* {.final, pure.} = object - ControlWord*: DWORD - StatusWord*: DWORD - TagWord*: DWORD - ErrorOffset*: DWORD - ErrorSelector*: DWORD - DataOffset*: DWORD - DataSelector*: DWORD - RegisterArea*: array[0..79, int8] - Cr0NpxState*: DWORD - - PFLOATINGSAVEAREA* = ptr FLOATING_SAVE_AREA - CONTEXT* {.final, pure.} = object - ContextFlags*: DWORD - Dr0*: DWORD - Dr1*: DWORD - Dr2*: DWORD - Dr3*: DWORD - Dr6*: DWORD - Dr7*: DWORD - FloatSave*: FLOATING_SAVE_AREA - SegGs*: DWORD - SegFs*: DWORD - SegEs*: DWORD - SegDs*: DWORD - Edi*: DWORD - Esi*: DWORD - Ebx*: DWORD - Edx*: DWORD - Ecx*: DWORD - Eax*: DWORD - Ebp*: DWORD - Eip*: DWORD - SegCs*: DWORD - EFlags*: DWORD - Esp*: DWORD - SegSs*: DWORD - {.deprecated: [TFLOATINGSAVEAREA: FLOATING_SAVE_AREA].} - -elif defined(x86_64): - # - # Define 128-bit 16-byte aligned xmm register type. - # - type - M128A* {.final, pure.} = object - Low*: ULONGLONG - High*: LONGLONG - - PM128A* = M128A #typedef struct _XMM_SAVE_AREA32 { - XMM_SAVE_AREA32* {.final, pure.} = object - ControlWord*: int16 - StatusWord*: int16 - TagWord*: int8 - Reserved1*: int8 - ErrorOpcode*: int16 - ErrorOffset*: DWORD - ErrorSelector*: int16 - Reserved2*: int16 - DataOffset*: DWORD - DataSelector*: int16 - Reserved3*: int16 - MxCsr*: DWORD - MxCsr_Mask*: DWORD - FloatRegisters*: array[0..7, M128A] - XmmRegisters*: array[0..16, M128A] - Reserved4*: array[0..95, int8] - - PXmmSaveArea* = ptr XmmSaveArea32 - {.deprecated: [TM128A: M128A, TXmmSaveArea: XMM_SAVE_AREA32].} - - type - CONTEXT* {.final, pure.} = object - P1Home*: DWORD64 - P2Home*: DWORD64 - P3Home*: DWORD64 - P4Home*: DWORD64 - P5Home*: DWORD64 - P6Home*: DWORD64 # - # Control flags. - # - ContextFlags*: DWORD - MxCsr*: DWORD # - # Segment Registers and processor flags. - # - SegCs*: int16 - SegDs*: int16 - SegEs*: int16 - SegFs*: int16 - SegGs*: int16 - SegSs*: int16 - EFlags*: DWORD # - # Debug registers - # - Dr0*: DWORD64 - Dr1*: DWORD64 - Dr2*: DWORD64 - Dr3*: DWORD64 - Dr6*: DWORD64 - Dr7*: DWORD64 # - # Integer registers. - # - Rax*: DWORD64 - Rcx*: DWORD64 - Rdx*: DWORD64 - Rbx*: DWORD64 - Rsp*: DWORD64 - Rbp*: DWORD64 - Rsi*: DWORD64 - Rdi*: DWORD64 - R8*: DWORD64 - R9*: DWORD64 - R10*: DWORD64 - R11*: DWORD64 - R12*: DWORD64 - R13*: DWORD64 - R14*: DWORD64 - R15*: DWORD64 # - # Program counter. - # - Rip*: DWORD64 # - # Floating point state. - # - FltSave*: XMM_SAVE_AREA32 # MWE: only translated the FltSave part of the union - # - # Vector registers. - # - VectorRegister*: array[0..25, M128A] - VectorControl*: DWORD64 # - # Special debug control registers. - # - DebugControl*: DWORD64 - LastBranchToRip*: DWORD64 - LastBranchFromRip*: DWORD64 - LastExceptionToRip*: DWORD64 - LastExceptionFromRip*: DWORD64 - -elif hostCPU == "powerpc": - # ppc - # Floating point registers returned when CONTEXT_FLOATING_POINT is set - # Integer registers returned when CONTEXT_INTEGER is set. - # Condition register - # Fixed point exception register - # The following are set when CONTEXT_CONTROL is set. - # Machine status register - # Instruction address register - # Link register - # Control register - # Control which context values are returned - # Registers returned if CONTEXT_DEBUG_REGISTERS is set. - # Breakpoint Register 1 - # Breakpoint Register 2 - # Breakpoint Register 3 - # Breakpoint Register 4 - # Breakpoint Register 5 - # Breakpoint Register 6 - # Debug Status Register - # Debug Control Register - type - CONTEXT* {.final, pure.} = object - Fpr0*: float64 - Fpr1*: float64 - Fpr2*: float64 - Fpr3*: float64 - Fpr4*: float64 - Fpr5*: float64 - Fpr6*: float64 - Fpr7*: float64 - Fpr8*: float64 - Fpr9*: float64 - Fpr10*: float64 - Fpr11*: float64 - Fpr12*: float64 - Fpr13*: float64 - Fpr14*: float64 - Fpr15*: float64 - Fpr16*: float64 - Fpr17*: float64 - Fpr18*: float64 - Fpr19*: float64 - Fpr20*: float64 - Fpr21*: float64 - Fpr22*: float64 - Fpr23*: float64 - Fpr24*: float64 - Fpr25*: float64 - Fpr26*: float64 - Fpr27*: float64 - Fpr28*: float64 - Fpr29*: float64 - Fpr30*: float64 - Fpr31*: float64 - Fpscr*: float64 - Gpr0*: DWORD - Gpr1*: DWORD - Gpr2*: DWORD - Gpr3*: DWORD - Gpr4*: DWORD - Gpr5*: DWORD - Gpr6*: DWORD - Gpr7*: DWORD - Gpr8*: DWORD - Gpr9*: DWORD - Gpr10*: DWORD - Gpr11*: DWORD - Gpr12*: DWORD - Gpr13*: DWORD - Gpr14*: DWORD - Gpr15*: DWORD - Gpr16*: DWORD - Gpr17*: DWORD - Gpr18*: DWORD - Gpr19*: DWORD - Gpr20*: DWORD - Gpr21*: DWORD - Gpr22*: DWORD - Gpr23*: DWORD - Gpr24*: DWORD - Gpr25*: DWORD - Gpr26*: DWORD - Gpr27*: DWORD - Gpr28*: DWORD - Gpr29*: DWORD - Gpr30*: DWORD - Gpr31*: DWORD - Cr*: DWORD - Xer*: DWORD - Msr*: DWORD - Iar*: DWORD - Lr*: DWORD - Ctr*: DWORD - ContextFlags*: DWORD - Fill*: array[0..2, DWORD] - Dr0*: DWORD - Dr1*: DWORD - Dr2*: DWORD - Dr3*: DWORD - Dr4*: DWORD - Dr5*: DWORD - Dr6*: DWORD - Dr7*: DWORD - -else: - # dummy CONTEXT so that it compiles: - type - CONTEXT* {.final, pure.} = object - data: array [0..255, float64] - -type - LPCONTEXT* = ptr CONTEXT - PCONTEXT* = ptr CONTEXT -{.deprecated: [TCONTEXT: CONTEXT].} - -type - LIST_ENTRY* {.final, pure.} = object - Flink*: ptr LIST_ENTRY - Blink*: ptr LIST_ENTRY - - PLISTENTRY* = ptr LIST_ENTRY - CRITICAL_SECTION_DEBUG* {.final, pure.} = object - `type`*: int16 - CreatorBackTraceIndex*: int16 - CriticalSection*: ptr TRTL_CRITICAL_SECTION - ProcessLocksList*: LIST_ENTRY - EntryCount*: DWORD - ContentionCount*: DWORD - Depth*: DWORD - OwnerBackTrace*: array[0..4, PVOID] - - TRTL_CRITICAL_SECTION* {.final, pure.} = object - DebugInfo*: ptr CRITICAL_SECTION_DEBUG - LockCount*: int32 - RecursionCount*: int32 - OwningThread*: Handle - LockSemaphore*: Handle - Reserved*: DWORD - - PRTLCriticalSection* = ptr TRTLCriticalSection - - LPCRITICAL_SECTION_DEBUG* = ptr CRITICAL_SECTION_DEBUG - PCRITICAL_SECTION_DEBUG* = ptr CRITICAL_SECTION_DEBUG - PCRITICAL_SECTION* = PRTLCriticalSection - LPCRITICAL_SECTION* = PRTLCriticalSection - SECURITY_QUALITY_OF_SERVICE* {.final, pure.} = object - len*: DWORD - ImpersonationLevel*: SECURITY_IMPERSONATION_LEVEL - ContextTrackingMode*: WINBOOL - EffectiveOnly*: bool - - PSECURITY_QUALITY_OF_SERVICE* = ptr SECURITY_QUALITY_OF_SERVICE - CONVCONTEXT* {.final, pure.} = object - cb*: WINUINT - wFlags*: WINUINT - wCountryID*: WINUINT - iCodePage*: int32 - dwLangID*: DWORD - dwSecurity*: DWORD - qos*: SECURITY_QUALITY_OF_SERVICE - - PCONVCONTEXT* = ptr CONVCONTEXT - CONVINFO* {.final, pure.} = object - cb*: DWORD - hUser*: DWORD - hConvPartner*: HCONV - hszSvcPartner*: HSZ - hszServiceReq*: HSZ - hszTopic*: HSZ - hszItem*: HSZ - wFmt*: WINUINT - wType*: WINUINT - wStatus*: WINUINT - wConvst*: WINUINT - wLastError*: WINUINT - hConvList*: HCONVLIST - ConvCtxt*: CONVCONTEXT - hwnd*: HWND - hwndPartner*: HWND - - PCONVINFO* = ptr CONVINFO - COPYDATASTRUCT* {.final, pure.} = object - dwData*: DWORD - cbData*: DWORD - lpData*: PVOID - - PCOPYDATASTRUCT* = ptr COPYDATASTRUCT - CPINFO* {.final, pure.} = object - MaxCharSize*: WINUINT - DefaultChar*: array[0..(MAX_DEFAULTCHAR) - 1, int8] - LeadByte*: array[0..(MAX_LEADBYTES) - 1, int8] - - LPCPINFO* = ptr CPINFO - Pcpinfo* = ptr CPINFO - CPLINFO* {.final, pure.} = object - idIcon*: int32 - idName*: int32 - idInfo*: int32 - lData*: LONG - - PCPLINFO* = ptr CPLINFO - CREATE_PROCESS_DEBUG_INFO* {.final, pure.} = object - hFile*: HANDLE - hProcess*: HANDLE - hThread*: HANDLE - lpBaseOfImage*: LPVOID - dwDebugInfoFileOffset*: DWORD - nDebugInfoSize*: DWORD - lpThreadLocalBase*: LPVOID - lpStartAddress*: LPTHREAD_START_ROUTINE - lpImageName*: LPVOID - fUnicode*: int16 - - PCREATEPROCESSDEBUGINFO* = ptr CREATE_PROCESS_DEBUG_INFO - CREATE_THREAD_DEBUG_INFO* {.final, pure.} = object - hThread*: HANDLE - lpThreadLocalBase*: LPVOID - lpStartAddress*: LPTHREAD_START_ROUTINE - - PCREATETHREADDEBUGINFO* = ptr CREATE_THREAD_DEBUG_INFO - - CURRENCYFMT* {.final, pure.} = object - NumDigits*: WINUINT - LeadingZero*: WINUINT - Grouping*: WINUINT - lpDecimalSep*: LPTSTR - lpThousandSep*: LPTSTR - NegativeOrder*: WINUINT - PositiveOrder*: WINUINT - lpCurrencySymbol*: LPTSTR - - Pcurrencyfmt* = ptr CURRENCYFMT - CURSORSHAPE* {.final, pure.} = object - xHotSpot*: int32 - yHotSpot*: int32 - cx*: int32 - cy*: int32 - cbWidth*: int32 - Planes*: int8 - BitsPixel*: int8 - - LPCURSORSHAPE* = ptr CURSORSHAPE - PCURSORSHAPE* = ptr CURSORSHAPE - CWPRETSTRUCT* {.final, pure.} = object - lResult*: LRESULT - lParam*: LPARAM - wParam*: WPARAM - message*: DWORD - hwnd*: HWND - - PCWPRETSTRUCT* = ptr CWPRETSTRUCT - CWPSTRUCT* {.final, pure.} = object - lParam*: LPARAM - wParam*: WPARAM - message*: WINUINT - hwnd*: HWND - - PCWPSTRUCT* = ptr CWPSTRUCT - DATATYPES_INFO_1* {.final, pure.} = object - pName*: LPTSTR - - PDATATYPESINFO1* = ptr DATATYPES_INFO_1 - DDEACK* {.final, pure.} = object - flag0*: int16 - - PDDEACK* = ptr DDEACK -{.deprecated: [TLISTENTRY: LIST_ENTRY, TDATATYPESINFO1: DATATYPES_INFO_1, - TCWPSTRUCT: CWPSTRUCT, TCWPRETSTRUCT: CWPRETSTRUCT, TCURSORSHAPE: CURSORSHAPE, - Tcurrencyfmt: CURRENCYFMT, TCREATETHREADDEBUGINFO: CREATE_THREAD_DEBUG_INFO, - TCREATEPROCESSDEBUGINFO: CREATE_PROCESS_DEBUG_INFO, TCPLINFO: CPLINFO, - Tcpinfo: CPINFO, TCOPYDATASTRUCT: COPYDATASTRUCT, TCONVINFO: CONVINFO, - TCONVCONTEXT: CONVCONTEXT, TSECURITYQUALITYOFSERVICE: SECURITY_QUALITY_OF_SERVICE, - TCRITICAL_SECTION: TRTLCriticalSection, TCRITICALSECTIONDEBUG: CRITICAL_SECTION_DEBUG, - TDDEACK: DDEACK -].} - -const - bm_DDEACK_bAppReturnCode* = 0x000000FF'i16 - bp_DDEACK_bAppReturnCode* = 0'i16 - bm_DDEACK_reserved* = 0x00003F00'i16 - bp_DDEACK_reserved* = 8'i16 - bm_DDEACK_fBusy* = 0x00004000'i16 - bp_DDEACK_fBusy* = 14'i16 - bm_DDEACK_fAck* = 0x00008000'i16 - bp_DDEACK_fAck* = 15'i16 - -proc bAppReturnCode*(a: var DDEACK): int16 -proc set_bAppReturnCode*(a: var DDEACK, bAppReturnCode: int16) -proc reserved*(a: var DDEACK): int16 -proc set_reserved*(a: var DDEACK, reserved: int16) -proc fBusy*(a: var DDEACK): int16 -proc set_fBusy*(a: var DDEACK, fBusy: int16) -proc fAck*(a: var DDEACK): int16 -proc set_fAck*(a: var DDEACK, fAck: int16) -type - DDEADVISE* {.final, pure.} = object - flag0*: int16 - cfFormat*: SHORT - - PDDEADVISE* = ptr DDEADVISE -{.deprecated: [TDDEADVISE: DDEADVISE].} - -const - bm_DDEADVISE_reserved* = 0x00003FFF'i16 - bp_DDEADVISE_reserved* = 0'i16 - bm_DDEADVISE_fDeferUpd* = 0x00004000'i16 - bp_DDEADVISE_fDeferUpd* = 14'i16 - bm_DDEADVISE_fAckReq* = 0x00008000'i16 - bp_DDEADVISE_fAckReq* = 15'i16 - -proc reserved*(a: var DDEADVISE): int16 -proc set_reserved*(a: var DDEADVISE, reserved: int16) -proc fDeferUpd*(a: var DDEADVISE): int16 -proc set_fDeferUpd*(a: var DDEADVISE, fDeferUpd: int16) -proc fAckReq*(a: var DDEADVISE): int16 -proc set_fAckReq*(a: var DDEADVISE, fAckReq: int16) -type - DDEDATA* {.final, pure.} = object - flag0*: int16 - cfFormat*: SHORT - Value*: array[0..0, int8] - - PDDEDATA* = ptr DDEDATA - -const - bm_DDEDATA_unused* = 0x00000FFF'i16 - bp_DDEDATA_unused* = 0'i16 - bm_DDEDATA_fResponse* = 0x00001000'i16 - bp_DDEDATA_fResponse* = 12'i16 - bm_DDEDATA_fRelease* = 0x00002000'i16 - bp_DDEDATA_fRelease* = 13'i16 - bm_DDEDATA_reserved* = 0x00004000'i16 - bp_DDEDATA_reserved* = 14'i16 - bm_DDEDATA_fAckReq* = 0x00008000'i16 - bp_DDEDATA_fAckReq* = 15'i16 - -proc unused*(a: var DDEDATA): int16 -proc set_unused*(a: var DDEDATA, unused: int16) -proc fResponse*(a: var DDEDATA): int16 -proc set_fResponse*(a: var DDEDATA, fResponse: int16) -proc fRelease*(a: var DDEDATA): int16 -proc set_fRelease*(a: var DDEDATA, fRelease: int16) -proc reserved*(a: var DDEDATA): int16 -proc set_reserved*(a: var DDEDATA, reserved: int16) -proc fAckReq*(a: var DDEDATA): int16 -proc set_fAckReq*(a: var DDEDATA, fAckReq: int16) -type - DDELN* {.final, pure.} = object - flag0*: int16 - cfFormat*: SHORT - - PDDELN* = ptr DDELN -{.deprecated: [TDDELN: DDELN].} - -const - bm_DDELN_unused* = 0x00001FFF'i16 - bp_DDELN_unused* = 0'i16 - bm_DDELN_fRelease* = 0x00002000'i16 - bp_DDELN_fRelease* = 13'i16 - bm_DDELN_fDeferUpd* = 0x00004000'i16 - bp_DDELN_fDeferUpd* = 14'i16 - bm_DDELN_fAckReq* = 0x00008000'i16 - bp_DDELN_fAckReq* = 15'i16 - -proc unused*(a: var DDELN): int16 -proc set_unused*(a: var DDELN, unused: int16) -proc fRelease*(a: var DDELN): int16 -proc set_fRelease*(a: var DDELN, fRelease: int16) -proc fDeferUpd*(a: var DDELN): int16 -proc set_fDeferUpd*(a: var DDELN, fDeferUpd: int16) -proc fAckReq*(a: var DDELN): int16 -proc set_fAckReq*(a: var DDELN, fAckReq: int16) -type - DDEML_MSG_HOOK_DATA* {.final, pure.} = object - uiLo*: WINUINT - uiHi*: WINUINT - cbData*: DWORD - Data*: array[0..7, DWORD] - - PDDEMLMSGHOOKDATA* = ptr DDEML_MSG_HOOK_DATA - DDEPOKE* {.final, pure.} = object - flag0*: int16 - cfFormat*: SHORT - Value*: array[0..0, int8] - - PDDEPOKE* = ptr DDEPOKE -{.deprecated: [TDDEMLMSGHOOKDATA: DDEML_MSG_HOOK_DATA, TDDEPOKE: DDEPOKE].} - -const - bm_DDEPOKE_unused* = 0x00001FFF'i16 - bp_DDEPOKE_unused* = 0'i16 - bm_DDEPOKE_fRelease* = 0x00002000'i16 - bp_DDEPOKE_fRelease* = 13'i16 - bm_DDEPOKE_fReserved* = 0x0000C000'i16 - bp_DDEPOKE_fReserved* = 14'i16 - -proc unused*(a: var DDEPOKE): int16 -proc set_unused*(a: var DDEPOKE, unused: int16) -proc fRelease*(a: var DDEPOKE): int16 -proc set_fRelease*(a: var DDEPOKE, fRelease: int16) -proc fReserved*(a: var DDEPOKE): int16 -proc set_fReserved*(a: var DDEPOKE, fReserved: int16) -type - DDEUP* {.final, pure.} = object - flag0*: int16 - cfFormat*: SHORT - rgb*: array[0..0, int8] - - PDDEUP* = ptr DDEUP -{.deprecated: [TDDEUP: DDEUP].} - -const - bm_DDEUP_unused* = 0x00000FFF'i16 - bp_DDEUP_unused* = 0'i16 - bm_DDEUP_fAck* = 0x00001000'i16 - bp_DDEUP_fAck* = 12'i16 - bm_DDEUP_fRelease* = 0x00002000'i16 - bp_DDEUP_fRelease* = 13'i16 - bm_DDEUP_fReserved* = 0x00004000'i16 - bp_DDEUP_fReserved* = 14'i16 - bm_DDEUP_fAckReq* = 0x00008000'i16 - bp_DDEUP_fAckReq* = 15'i16 - -proc unused*(a: var DDEUP): int16 -proc set_unused*(a: var DDEUP, unused: int16) -proc fAck*(a: var DDEUP): int16 -proc set_fAck*(a: var DDEUP, fAck: int16) -proc fRelease*(a: var DDEUP): int16 -proc set_fRelease*(a: var DDEUP, fRelease: int16) -proc fReserved*(a: var DDEUP): int16 -proc set_fReserved*(a: var DDEUP, fReserved: int16) -proc fAckReq*(a: var DDEUP): int16 -proc set_fAckReq*(a: var DDEUP, fAckReq: int16) -type - EXCEPTION_RECORD* {.final, pure.} = object - ExceptionCode*: DWORD - ExceptionFlags*: DWORD - ExceptionRecord*: ptr EXCEPTION_RECORD - ExceptionAddress*: PVOID - NumberParameters*: DWORD - ExceptionInformation*: array[0..(EXCEPTION_MAXIMUM_PARAMETERS) - 1, - ULONG_PTR] - - PEXCEPTION_RECORD* = ptr EXCEPTION_RECORD - EXCEPTION_DEBUG_INFO* {.final, pure.} = object - ExceptionRecord*: EXCEPTION_RECORD - dwFirstChance*: DWORD - - PEXCEPTION_DEBUG_INFO* = ptr EXCEPTION_DEBUG_INFO - EXCEPTION_RECORD32* {.final, pure.} = object - ExceptionCode*: DWORD - ExceptionFlags*: DWORD - ExceptionRecord*: DWORD - ExceptionAddress*: DWORD - NumberParameters*: DWORD - ExceptionInformation*: array[0..(EXCEPTION_MAXIMUM_PARAMETERS) - 1, DWORD] - - PEXCEPTION_RECORD32* = ptr EXCEPTION_RECORD32 - EXCEPTION_DEBUG_INFO32* {.final, pure.} = object - ExceptionRecord*: EXCEPTION_RECORD32 - dwFirstChance*: DWORD - - PEXCEPTION_DEBUG_INFO32* = ptr EXCEPTION_DEBUG_INFO32 - EXCEPTION_RECORD64* {.final, pure.} = object - ExceptionCode*: DWORD - ExceptionFlags*: DWORD - ExceptionRecord*: DWORD64 - ExceptionAddress*: DWORD64 - NumberParameters*: DWORD - unusedAlignment*: DWORD - ExceptionInformation*: array[0..(EXCEPTION_MAXIMUM_PARAMETERS) - 1, DWORD64] - - PEXCEPTION_RECORD64* = ptr EXCEPTION_RECORD64 - EXCEPTION_DEBUG_INFO64* {.final, pure.} = object - ExceptionRecord*: EXCEPTION_RECORD64 - dwFirstChance*: DWORD - - PEXCEPTION_DEBUG_INFO64* = ptr EXCEPTION_DEBUG_INFO64 - EXIT_PROCESS_DEBUG_INFO* {.final, pure.} = object - dwExitCode*: DWORD - - PEXITPROCESSDEBUGINFO* = ptr EXIT_PROCESS_DEBUG_INFO - EXIT_THREAD_DEBUG_INFO* {.final, pure.} = object - dwExitCode*: DWORD - - PEXITTHREADDEBUGINFO* = ptr EXIT_THREAD_DEBUG_INFO - LOAD_DLL_DEBUG_INFO* {.final, pure.} = object - hFile*: HANDLE - lpBaseOfDll*: LPVOID - dwDebugInfoFileOffset*: DWORD - nDebugInfoSize*: DWORD - lpImageName*: LPVOID - fUnicode*: int16 - - PLOADDLLDEBUGINFO* = ptr LOAD_DLL_DEBUG_INFO - UNLOAD_DLL_DEBUG_INFO* {.final, pure.} = object - lpBaseOfDll*: LPVOID - - PUNLOADDLLDEBUGINFO* = ptr UNLOAD_DLL_DEBUG_INFO - OUTPUT_DEBUG_STRING_INFO* {.final, pure.} = object - lpDebugStringData*: LPSTR - fUnicode*: int16 - nDebugStringLength*: int16 - - POUTPUTDEBUGSTRINGINFO* = ptr OUTPUT_DEBUG_STRING_INFO - RIP_INFO* {.final, pure.} = object - dwError*: DWORD - dwType*: DWORD - - PRIPINFO* = ptr RIP_INFO - DEBUG_EVENT* {.final, pure.} = object - dwDebugEventCode*: DWORD - dwProcessId*: DWORD - dwThreadId*: DWORD - data*: array[0..15, DWORD] - - LPDEBUG_EVENT* = ptr DEBUG_EVENT - PDEBUGEVENT* = ptr DEBUG_EVENT - DEBUGHOOKINFO* {.final, pure.} = object - idThread*: DWORD - idThreadInstaller*: DWORD - lParam*: LPARAM - wParam*: WPARAM - code*: int32 - - PDEBUGHOOKINFO* = ptr DEBUGHOOKINFO - DELETEITEMSTRUCT* {.final, pure.} = object - CtlType*: WINUINT - CtlID*: WINUINT - itemID*: WINUINT - hwndItem*: HWND - itemData*: ULONG_PTR - - PDELETEITEMSTRUCT* = ptr DELETEITEMSTRUCT - DEV_BROADCAST_HDR* {.final, pure.} = object - dbch_size*: ULONG - dbch_devicetype*: ULONG - dbch_reserved*: ULONG - - PDEV_BROADCAST_HDR* = ptr DEV_BROADCAST_HDR - DEV_BROADCAST_OEM* {.final, pure.} = object - dbco_size*: ULONG - dbco_devicetype*: ULONG - dbco_reserved*: ULONG - dbco_identifier*: ULONG - dbco_suppfunc*: ULONG - - PDEV_BROADCAST_OEM* = ptr DEV_BROADCAST_OEM - DEV_BROADCAST_PORT* {.final, pure.} = object - dbcp_size*: ULONG - dbcp_devicetype*: ULONG - dbcp_reserved*: ULONG - dbcp_name*: array[0..0, char] - - PDEV_BROADCAST_PORT* = ptr DEV_BROADCAST_PORT - DEV_BROADCAST_USERDEFINED* {.final, pure.} = object - dbud_dbh*: DEV_BROADCAST_HDR - dbud_szName*: array[0..0, char] - dbud_rgbUserDefined*: array[0..0, int8] - - PDEVBROADCASTUSERDEFINED* = ptr DEV_BROADCAST_USERDEFINED - DEV_BROADCAST_VOLUME* {.final, pure.} = object - dbcv_size*: ULONG - dbcv_devicetype*: ULONG - dbcv_reserved*: ULONG - dbcv_unitmask*: ULONG - dbcv_flags*: USHORT - - PDEV_BROADCAST_VOLUME* = ptr DEV_BROADCAST_VOLUME - DEVMODE* {.final, pure.} = object - dmDeviceName*: array[0..(CCHDEVICENAME) - 1, BCHAR] - dmSpecVersion*: int16 - dmDriverVersion*: int16 - dmSize*: int16 - dmDriverExtra*: int16 - dmFields*: DWORD - dmOrientation*: int16 - dmPaperSize*: int16 - dmPaperLength*: int16 - dmPaperWidth*: int16 - dmScale*: int16 - dmCopies*: int16 - dmDefaultSource*: int16 - dmPrintQuality*: int16 - dmColor*: int16 - dmDuplex*: int16 - dmYResolution*: int16 - dmTTOption*: int16 - dmCollate*: int16 - dmFormName*: array[0..(CCHFORMNAME) - 1, BCHAR] - dmLogPixels*: int16 - dmBitsPerPel*: DWORD - dmPelsWidth*: DWORD - dmPelsHeight*: DWORD - dmDisplayFlags*: DWORD - dmDisplayFrequency*: DWORD - dmICMMethod*: DWORD - dmICMIntent*: DWORD - dmMediaType*: DWORD - dmDitherType*: DWORD - dmICCManufacturer*: DWORD - dmICCModel*: DWORD # other union part: - # dmPosition: POINTL; - # dmDisplayOrientation: DWORD; - # dmDisplayFixedOutput: DWORD; - - LPDEVMODE* = ptr DEVMODE - Devicemode* = DEVMODE - PDeviceModeA* = LPDEVMODE - PDeviceMode* = LPDEVMODE - PDEVMODE* = LPDEVMODE - DEVMODEW* {.final, pure.} = object - dmDeviceName*: array[0..CCHDEVICENAME - 1, WCHAR] - dmSpecVersion*: int16 - dmDriverVersion*: int16 - dmSize*: int16 - dmDriverExtra*: int16 - dmFields*: DWORD - dmOrientation*: SHORT - dmPaperSize*: SHORT - dmPaperLength*: SHORT - dmPaperWidth*: SHORT - dmScale*: SHORT - dmCopies*: SHORT - dmDefaultSource*: SHORT - dmPrintQuality*: SHORT - dmColor*: SHORT - dmDuplex*: SHORT - dmYResolution*: SHORT - dmTTOption*: SHORT - dmCollate*: SHORT - dmFormName*: array[0..CCHFORMNAME - 1, WCHAR] - dmLogPixels*: int16 - dmBitsPerPel*: DWORD - dmPelsWidth*: DWORD - dmPelsHeight*: DWORD - dmDisplayFlags*: DWORD - dmDisplayFrequency*: DWORD - dmICMMethod*: DWORD - dmICMIntent*: DWORD - dmMediaType*: DWORD - dmDitherType*: DWORD - dmReserved1*: DWORD - dmReserved2*: DWORD - dmPanningWidth*: DWORD - dmPanningHeight*: DWORD - - LPDEVMODEW* = ptr DEVMODEW - DevicemodeW* = DEVMODEW - PDeviceModeW* = LPDEVMODEW - PDEVMODEW* = LPDEVMODEW - DEVNAMES* {.final, pure.} = object - wDriverOffset*: int16 - wDeviceOffset*: int16 - wOutputOffset*: int16 - wDefault*: int16 - - LPDEVNAMES* = ptr DEVNAMES - PDEVNAMES* = ptr DEVNAMES - DIBSECTION* {.final, pure.} = object - dsBm*: BITMAP - dsBmih*: BITMAPINFOHEADER - dsBitfields*: array[0..2, DWORD] - dshSection*: HANDLE - dsOffset*: DWORD - - PDIBSECTION* = ptr DIBSECTION # - # LARGE_INTEGER = record - # case byte of - # 0: (LowPart : DWORD; - # HighPart : LONG); - # 1: (QuadPart : LONGLONG); - # end; ULARGE_INTEGER = record - # case byte of - # 0: (LowPart : DWORD; - # HighPart : DWORD); - # 1: (QuadPart : LONGLONG); - # end; - # - LARGE_INTEGER* = int64 - ULARGE_INTEGER* = int64 - PLARGE_INTEGER* = ptr LARGE_INTEGER - PULARGE_INTEGER* = ptr ULARGE_INTEGER - DISK_GEOMETRY* {.final, pure.} = object - Cylinders*: LARGE_INTEGER - MediaType*: MEDIA_TYPE - TracksPerCylinder*: DWORD - SectorsPerTrack*: DWORD - BytesPerSector*: DWORD - - PDISKGEOMETRY* = ptr DISK_GEOMETRY - DISK_PERFORMANCE* {.final, pure.} = object - BytesRead*: LARGE_INTEGER - BytesWritten*: LARGE_INTEGER - ReadTime*: LARGE_INTEGER - WriteTime*: LARGE_INTEGER - ReadCount*: DWORD - WriteCount*: DWORD - QueueDepth*: DWORD - - PDISKPERFORMANCE* = ptr DISK_PERFORMANCE - DLGITEMTEMPLATE* {.final, pure.} = object - style*: DWORD - dwExtendedStyle*: DWORD - x*: int16 - y*: int16 - cx*: int16 - cy*: int16 - id*: int16 - - LPDLGITEMTEMPLATE* = ptr DLGITEMTEMPLATE - PDLGITEMTEMPLATE* = ptr DLGITEMTEMPLATE - DLGTEMPLATE* {.final, pure.} = object - style*: DWORD - dwExtendedStyle*: DWORD - cdit*: int16 - x*: int16 - y*: int16 - cx*: int16 - cy*: int16 - - LPDLGTEMPLATE* = ptr DLGTEMPLATE - LPCDLGTEMPLATE* = ptr DLGTEMPLATE - PDLGTEMPLATE* = ptr DLGTEMPLATE - DOC_INFO_1* {.final, pure.} = object - pDocName*: LPTSTR - pOutputFile*: LPTSTR - pDatatype*: LPTSTR - - PDOCINFO1* = ptr DOC_INFO_1 - DOC_INFO_2* {.final, pure.} = object - pDocName*: LPTSTR - pOutputFile*: LPTSTR - pDatatype*: LPTSTR - dwMode*: DWORD - JobId*: DWORD - - PDOCINFO2* = ptr DOC_INFO_2 - DOCINFO* {.final, pure.} = object - cbSize*: int32 - lpszDocName*: LPCTSTR - lpszOutput*: LPCTSTR - lpszDatatype*: LPCTSTR - fwType*: DWORD - - PDOCINFO* = ptr DOCINFO - DRAGLISTINFO* {.final, pure.} = object - uNotification*: WINUINT - hWnd*: HWND - ptCursor*: POINT - - LPDRAGLISTINFO* = ptr DRAGLISTINFO - PDRAGLISTINFO* = ptr DRAGLISTINFO - DRAWITEMSTRUCT* {.final, pure.} = object - CtlType*: WINUINT - CtlID*: WINUINT - itemID*: WINUINT - itemAction*: WINUINT - itemState*: WINUINT - hwndItem*: HWND - hDC*: HDC - rcItem*: RECT - itemData*: ULONG_PTR - - LPDRAWITEMSTRUCT* = ptr DRAWITEMSTRUCT - PDRAWITEMSTRUCT* = ptr DRAWITEMSTRUCT - DRAWTEXTPARAMS* {.final, pure.} = object - cbSize*: WINUINT - iTabLength*: int32 - iLeftMargin*: int32 - iRightMargin*: int32 - uiLengthDrawn*: WINUINT - - LPDRAWTEXTPARAMS* = ptr DRAWTEXTPARAMS - PDRAWTEXTPARAMS* = ptr DRAWTEXTPARAMS - PARTITION_INFORMATION* {.final, pure.} = object - PartitionType*: int8 - BootIndicator*: bool - RecognizedPartition*: bool - RewritePartition*: bool - StartingOffset*: LARGE_INTEGER - PartitionLength*: LARGE_INTEGER - HiddenSectors*: LARGE_INTEGER - - PPARTITIONINFORMATION* = ptr PARTITION_INFORMATION - DRIVE_LAYOUT_INFORMATION* {.final, pure.} = object - PartitionCount*: DWORD - Signature*: DWORD - PartitionEntry*: array[0..0, PARTITION_INFORMATION] - - PDRIVELAYOUTINFORMATION* = ptr DRIVE_LAYOUT_INFORMATION - DRIVER_INFO_1* {.final, pure.} = object - pName*: LPTSTR - - PDRIVERINFO1* = ptr DRIVER_INFO_1 - DRIVER_INFO_2* {.final, pure.} = object - cVersion*: DWORD - pName*: LPTSTR - pEnvironment*: LPTSTR - pDriverPath*: LPTSTR - pDataFile*: LPTSTR - pConfigFile*: LPTSTR - - PDRIVERINFO2* = ptr DRIVER_INFO_2 - DRIVER_INFO_3* {.final, pure.} = object - cVersion*: DWORD - pName*: LPTSTR - pEnvironment*: LPTSTR - pDriverPath*: LPTSTR - pDataFile*: LPTSTR - pConfigFile*: LPTSTR - pHelpFile*: LPTSTR - pDependentFiles*: LPTSTR - pMonitorName*: LPTSTR - pDefaultDataType*: LPTSTR - - PDRIVERINFO3* = ptr DRIVER_INFO_3 - EDITSTREAM* {.final, pure.} = object - dwCookie*: DWORD - dwError*: DWORD - pfnCallback*: EDITSTREAMCALLBACK - - Peditstream* = ptr EDITSTREAM - EMR* {.final, pure.} = object - iType*: DWORD - nSize*: DWORD - - PEMR* = ptr EMR - EMRANGLEARC* {.final, pure.} = object - emr*: EMR - ptlCenter*: POINTL - nRadius*: DWORD - eStartAngle*: float32 - eSweepAngle*: float32 - - PEMRANGLEARC* = ptr EMRANGLEARC - EMRARC* {.final, pure.} = object - emr*: EMR - rclBox*: RECTL - ptlStart*: POINTL - ptlEnd*: POINTL - - PEMRARC* = ptr EMRARC - EMRARCTO* = EMRARC - PEMRARCTO* = ptr EMRARC - EMRCHORD* = EMRARC - PEMRCHORD* = ptr EMRARC - EMRPIE* = EMRARC - PEMRPIE* = ptr EMRARC - XFORM* {.final, pure.} = object - eM11*: float32 - eM12*: float32 - eM21*: float32 - eM22*: float32 - eDx*: float32 - eDy*: float32 - - LPXFORM* = ptr XFORM - PXFORM* = ptr XFORM - EMRBITBLT* {.final, pure.} = object - emr*: EMR - rclBounds*: RECTL - xDest*: LONG - yDest*: LONG - cxDest*: LONG - cyDest*: LONG - dwRop*: DWORD - xSrc*: LONG - ySrc*: LONG - xformSrc*: XFORM - crBkColorSrc*: COLORREF - iUsageSrc*: DWORD - offBmiSrc*: DWORD - offBitsSrc*: DWORD - cbBitsSrc*: DWORD - - PEMRBITBLT* = ptr EMRBITBLT - LOGBRUSH* {.final, pure.} = object - lbStyle*: WINUINT - lbColor*: COLORREF - lbHatch*: LONG - - PLOGBRUSH* = ptr LOGBRUSH - EMRCREATEBRUSHINDIRECT* {.final, pure.} = object - emr*: EMR - ihBrush*: DWORD - lb*: LOGBRUSH - - PEMRCREATEBRUSHINDIRECT* = ptr EMRCREATEBRUSHINDIRECT - LCSCSTYPE* = LONG - LCSGAMUTMATCH* = LONG - LOGCOLORSPACE* {.final, pure.} = object - lcsSignature*: DWORD - lcsVersion*: DWORD - lcsSize*: DWORD - lcsCSType*: LCSCSTYPE - lcsIntent*: LCSGAMUTMATCH - lcsEndpoints*: CIEXYZTRIPLE - lcsGammaRed*: DWORD - lcsGammaGreen*: DWORD - lcsGammaBlue*: DWORD - lcsFilename*: array[0..(MAX_PATH) - 1, CHAR] - - LPLOGCOLORSPACE* = ptr LOGCOLORSPACE - PLOGCOLORSPACE* = ptr LOGCOLORSPACE - EMRCREATECOLORSPACE* {.final, pure.} = object - emr*: EMR - ihCS*: DWORD - lcs*: LOGCOLORSPACE - - PEMRCREATECOLORSPACE* = ptr EMRCREATECOLORSPACE - EMRCREATEDIBPATTERNBRUSHPT* {.final, pure.} = object - emr*: EMR - ihBrush*: DWORD - iUsage*: DWORD - offBmi*: DWORD - cbBmi*: DWORD - offBits*: DWORD - cbBits*: DWORD - - PEMRCREATEDIBPATTERNBRUSHPT* = EMRCREATEDIBPATTERNBRUSHPT - EMRCREATEMONOBRUSH* {.final, pure.} = object - emr*: EMR - ihBrush*: DWORD - iUsage*: DWORD - offBmi*: DWORD - cbBmi*: DWORD - offBits*: DWORD - cbBits*: DWORD - - PEMRCREATEMONOBRUSH* = ptr EMRCREATEMONOBRUSH - PALETTEENTRY* {.final, pure.} = object - peRed*: int8 - peGreen*: int8 - peBlue*: int8 - peFlags*: int8 - - LPPALETTEENTRY* = ptr PALETTEENTRY - PPALETTEENTRY* = ptr PALETTEENTRY - LOGPALETTE* {.final, pure.} = object - palVersion*: int16 - palNumEntries*: int16 - palPalEntry*: array[0..0, PALETTEENTRY] - - LPLOGPALETTE* = ptr LOGPALETTE - NPLOGPALETTE* = ptr LOGPALETTE - PLOGPALETTE* = ptr LOGPALETTE - EMRCREATEPALETTE* {.final, pure.} = object - emr*: EMR - ihPal*: DWORD - lgpl*: LOGPALETTE - - PEMRCREATEPALETTE* = ptr EMRCREATEPALETTE - LOGPEN* {.final, pure.} = object - lopnStyle*: WINUINT - lopnWidth*: POINT - lopnColor*: COLORREF - - PLOGPEN* = ptr LOGPEN - EMRCREATEPEN* {.final, pure.} = object - emr*: EMR - ihPen*: DWORD - lopn*: LOGPEN - - PEMRCREATEPEN* = ptr EMRCREATEPEN - EMRELLIPSE* {.final, pure.} = object - emr*: EMR - rclBox*: RECTL - - PEMRELLIPSE* = ptr EMRELLIPSE - EMRRECTANGLE* = EMRELLIPSE - PEMRRECTANGLE* = ptr EMRELLIPSE - EMREOF* {.final, pure.} = object - emr*: EMR - nPalEntries*: DWORD - offPalEntries*: DWORD - nSizeLast*: DWORD - - PEMREOF* = ptr EMREOF - EMREXCLUDECLIPRECT* {.final, pure.} = object - emr*: EMR - rclClip*: RECTL - - PEMREXCLUDECLIPRECT* = ptr EMREXCLUDECLIPRECT - EMRINTERSECTCLIPRECT* = EMREXCLUDECLIPRECT - PEMRINTERSECTCLIPRECT* = ptr EMREXCLUDECLIPRECT - PANOSE* {.final, pure.} = object - bFamilyType*: int8 - bSerifStyle*: int8 - bWeight*: int8 - bProportion*: int8 - bContrast*: int8 - bStrokeVariation*: int8 - bArmStyle*: int8 - bLetterform*: int8 - bMidline*: int8 - bXHeight*: int8 - - PPANOSE* = ptr PANOSE - EXTLOGFONT* {.final, pure.} = object - elfLogFont*: LOGFONT - elfFullName*: array[0..(LF_FULLFACESIZE) - 1, BCHAR] - elfStyle*: array[0..(LF_FACESIZE) - 1, BCHAR] - elfVersion*: DWORD - elfStyleSize*: DWORD - elfMatch*: DWORD - elfReserved*: DWORD - elfVendorId*: array[0..(ELF_VENDOR_SIZE) - 1, int8] - elfCulture*: DWORD - elfPanose*: PANOSE - - PEXTLOGFONT* = ptr EXTLOGFONT - EMREXTCREATEFONTINDIRECTW* {.final, pure.} = object - emr*: EMR - ihFont*: DWORD - elfw*: EXTLOGFONT - - PEMREXTCREATEFONTINDIRECTW* = ptr EMREXTCREATEFONTINDIRECTW - EXTLOGPEN* {.final, pure.} = object - elpPenStyle*: WINUINT - elpWidth*: WINUINT - elpBrushStyle*: WINUINT - elpColor*: COLORREF - elpHatch*: LONG - elpNumEntries*: DWORD - elpStyleEntry*: array[0..0, DWORD] - - PEXTLOGPEN* = ptr EXTLOGPEN - EMREXTCREATEPEN* {.final, pure.} = object - emr*: EMR - ihPen*: DWORD - offBmi*: DWORD - cbBmi*: DWORD - offBits*: DWORD - cbBits*: DWORD - elp*: EXTLOGPEN - - PEMREXTCREATEPEN* = ptr EMREXTCREATEPEN - EMREXTFLOODFILL* {.final, pure.} = object - emr*: EMR - ptlStart*: POINTL - crColor*: COLORREF - iMode*: DWORD - - PEMREXTFLOODFILL* = ptr EMREXTFLOODFILL - EMREXTSELECTCLIPRGN* {.final, pure.} = object - emr*: EMR - cbRgnData*: DWORD - iMode*: DWORD - RgnData*: array[0..0, int8] - - PEMREXTSELECTCLIPRGN* = ptr EMREXTSELECTCLIPRGN - EMRTEXT* {.final, pure.} = object - ptlReference*: POINTL - nChars*: DWORD - offString*: DWORD - fOptions*: DWORD - rcl*: RECTL - offDx*: DWORD - - PEMRTEXT* = ptr EMRTEXT - EMREXTTEXTOUTA* {.final, pure.} = object - emr*: EMR - rclBounds*: RECTL - iGraphicsMode*: DWORD - exScale*: float32 - eyScale*: float32 - emrtext*: EMRTEXT - - PEMREXTTEXTOUTA* = ptr EMREXTTEXTOUTA - EMREXTTEXTOUTW* = EMREXTTEXTOUTA - PEMREXTTEXTOUTW* = ptr EMREXTTEXTOUTA - EMRFILLPATH* {.final, pure.} = object - emr*: EMR - rclBounds*: RECTL - - PEMRFILLPATH* = ptr EMRFILLPATH - EMRSTROKEANDFILLPATH* = EMRFILLPATH - PEMRSTROKEANDFILLPATH* = ptr EMRFILLPATH - EMRSTROKEPATH* = EMRFILLPATH - PEMRSTROKEPATH* = ptr EMRFILLPATH - EMRFILLRGN* {.final, pure.} = object - emr*: EMR - rclBounds*: RECTL - cbRgnData*: DWORD - ihBrush*: DWORD - RgnData*: array[0..0, int8] - - PEMRFILLRGN* = ptr EMRFILLRGN - EMRFORMAT* {.final, pure.} = object - dSignature*: DWORD - nVersion*: DWORD - cbData*: DWORD - offData*: DWORD - - PEMRFORMAT* = ptr EMRFORMAT - - EMRFRAMERGN* {.final, pure.} = object - emr*: EMR - rclBounds*: RECTL - cbRgnData*: DWORD - ihBrush*: DWORD - szlStroke*: SIZEL - RgnData*: array[0..0, int8] - - PEMRFRAMERGN* = ptr EMRFRAMERGN - EMRGDICOMMENT* {.final, pure.} = object - emr*: EMR - cbData*: DWORD - Data*: array[0..0, int8] - - PEMRGDICOMMENT* = ptr EMRGDICOMMENT - EMRINVERTRGN* {.final, pure.} = object - emr*: EMR - rclBounds*: RECTL - cbRgnData*: DWORD - RgnData*: array[0..0, int8] - - PEMRINVERTRGN* = ptr EMRINVERTRGN - EMRPAINTRGN* = EMRINVERTRGN - PEMRPAINTRGN* = ptr EMRINVERTRGN - EMRLINETO* {.final, pure.} = object - emr*: EMR - ptl*: POINTL - - PEMRLINETO* = ptr EMRLINETO - EMRMOVETOEX* = EMRLINETO - PEMRMOVETOEX* = ptr EMRLINETO - EMRMASKBLT* {.final, pure.} = object - emr*: EMR - rclBounds*: RECTL - xDest*: LONG - yDest*: LONG - cxDest*: LONG - cyDest*: LONG - dwRop*: DWORD - xSrc*: LONG - ySrc*: LONG - xformSrc*: XFORM - crBkColorSrc*: COLORREF - iUsageSrc*: DWORD - offBmiSrc*: DWORD - cbBmiSrc*: DWORD - offBitsSrc*: DWORD - cbBitsSrc*: DWORD - xMask*: LONG - yMask*: LONG - iUsageMask*: DWORD - offBmiMask*: DWORD - cbBmiMask*: DWORD - offBitsMask*: DWORD - cbBitsMask*: DWORD - - PEMRMASKBLT* = ptr EMRMASKBLT - EMRMODIFYWORLDTRANSFORM* {.final, pure.} = object - emr*: EMR - xform*: XFORM - iMode*: DWORD - - PEMRMODIFYWORLDTRANSFORM* = EMRMODIFYWORLDTRANSFORM - EMROFFSETCLIPRGN* {.final, pure.} = object - emr*: EMR - ptlOffset*: POINTL - - PEMROFFSETCLIPRGN* = ptr EMROFFSETCLIPRGN - EMRPLGBLT* {.final, pure.} = object - emr*: EMR - rclBounds*: RECTL - aptlDest*: array[0..2, POINTL] - xSrc*: LONG - ySrc*: LONG - cxSrc*: LONG - cySrc*: LONG - xformSrc*: XFORM - crBkColorSrc*: COLORREF - iUsageSrc*: DWORD - offBmiSrc*: DWORD - cbBmiSrc*: DWORD - offBitsSrc*: DWORD - cbBitsSrc*: DWORD - xMask*: LONG - yMask*: LONG - iUsageMask*: DWORD - offBmiMask*: DWORD - cbBmiMask*: DWORD - offBitsMask*: DWORD - cbBitsMask*: DWORD - - PEMRPLGBLT* = ptr EMRPLGBLT - EMRPOLYDRAW* {.final, pure.} = object - emr*: EMR - rclBounds*: RECTL - cptl*: DWORD - aptl*: array[0..0, POINTL] - abTypes*: array[0..0, int8] - - PEMRPOLYDRAW* = ptr EMRPOLYDRAW - EMRPOLYDRAW16* {.final, pure.} = object - emr*: EMR - rclBounds*: RECTL - cpts*: DWORD - apts*: array[0..0, POINTS] - abTypes*: array[0..0, int8] - - PEMRPOLYDRAW16* = ptr EMRPOLYDRAW16 - EMRPOLYLINE* {.final, pure.} = object - emr*: EMR - rclBounds*: RECTL - cptl*: DWORD - aptl*: array[0..0, POINTL] - - PEMRPOLYLINE* = ptr EMRPOLYLINE - EMRPOLYBEZIER* = EMRPOLYLINE - PEMRPOLYBEZIER* = ptr EMRPOLYLINE - EMRPOLYGON* = EMRPOLYLINE - PEMRPOLYGON* = ptr EMRPOLYLINE - EMRPOLYBEZIERTO* = EMRPOLYLINE - PEMRPOLYBEZIERTO* = ptr EMRPOLYLINE - EMRPOLYLINETO* = EMRPOLYLINE - PEMRPOLYLINETO* = ptr EMRPOLYLINE - EMRPOLYLINE16* {.final, pure.} = object - emr*: EMR - rclBounds*: RECTL - cpts*: DWORD - apts*: array[0..0, POINTL] - - PEMRPOLYLINE16* = ptr EMRPOLYLINE16 - EMRPOLYBEZIER16* = EMRPOLYLINE16 - PEMRPOLYBEZIER16* = ptr EMRPOLYLINE16 - EMRPOLYGON16* = EMRPOLYLINE16 - PEMRPOLYGON16* = ptr EMRPOLYLINE16 - EMRPOLYBEZIERTO16* = EMRPOLYLINE16 - PEMRPOLYBEZIERTO16* = ptr EMRPOLYLINE16 - EMRPOLYLINETO16* = EMRPOLYLINE16 - PEMRPOLYLINETO16* = ptr EMRPOLYLINE16 - EMRPOLYPOLYLINE* {.final, pure.} = object - emr*: EMR - rclBounds*: RECTL - nPolys*: DWORD - cptl*: DWORD - aPolyCounts*: array[0..0, DWORD] - aptl*: array[0..0, POINTL] - - PEMRPOLYPOLYLINE* = ptr EMRPOLYPOLYLINE - EMRPOLYPOLYGON* = EMRPOLYPOLYLINE - PEMRPOLYPOLYGON* = ptr EMRPOLYPOLYLINE - EMRPOLYPOLYLINE16* {.final, pure.} = object - emr*: EMR - rclBounds*: RECTL - nPolys*: DWORD - cpts*: DWORD - aPolyCounts*: array[0..0, DWORD] - apts*: array[0..0, POINTS] - - PEMRPOLYPOLYLINE16* = ptr EMRPOLYPOLYLINE16 - EMRPOLYPOLYGON16* = EMRPOLYPOLYLINE16 - PEMRPOLYPOLYGON16* = ptr EMRPOLYPOLYLINE16 - EMRPOLYTEXTOUTA* {.final, pure.} = object - emr*: EMR - rclBounds*: RECTL - iGraphicsMode*: DWORD - exScale*: float32 - eyScale*: float32 - cStrings*: LONG - aemrtext*: array[0..0, EMRTEXT] - - PEMRPOLYTEXTOUTA* = ptr EMRPOLYTEXTOUTA - EMRPOLYTEXTOUTW* = EMRPOLYTEXTOUTA - PEMRPOLYTEXTOUTW* = ptr EMRPOLYTEXTOUTA - EMRRESIZEPALETTE* {.final, pure.} = object - emr*: EMR - ihPal*: DWORD - cEntries*: DWORD - - PEMRRESIZEPALETTE* = ptr EMRRESIZEPALETTE - EMRRESTOREDC* {.final, pure.} = object - emr*: EMR - iRelative*: LONG - - PEMRRESTOREDC* = ptr EMRRESTOREDC - EMRROUNDRECT* {.final, pure.} = object - emr*: EMR - rclBox*: RECTL - szlCorner*: SIZEL - - PEMRROUNDRECT* = ptr EMRROUNDRECT - EMRSCALEVIEWPORTEXTEX* {.final, pure.} = object - emr*: EMR - xNum*: LONG - xDenom*: LONG - yNum*: LONG - yDenom*: LONG - - PEMRSCALEVIEWPORTEXTEX* = ptr EMRSCALEVIEWPORTEXTEX - EMRSCALEWINDOWEXTEX* = EMRSCALEVIEWPORTEXTEX - PEMRSCALEWINDOWEXTEX* = ptr EMRSCALEVIEWPORTEXTEX - EMRSELECTCOLORSPACE* {.final, pure.} = object - emr*: EMR - - ihCS*: DWORD - - PEMRSELECTCOLORSPACE* = ptr EMRSELECTCOLORSPACE - EMRDELETECOLORSPACE* = EMRSELECTCOLORSPACE - PEMRDELETECOLORSPACE* = ptr EMRSELECTCOLORSPACE - EMRSELECTOBJECT* {.final, pure.} = object - emr*: EMR - ihObject*: DWORD - - PEMRSELECTOBJECT* = ptr EMRSELECTOBJECT - EMRDELETEOBJECT* = EMRSELECTOBJECT - PEMRDELETEOBJECT* = ptr EMRSELECTOBJECT - EMRSELECTPALETTE* {.final, pure.} = object - emr*: EMR - ihPal*: DWORD - - PEMRSELECTPALETTE* = ptr EMRSELECTPALETTE - EMRSETARCDIRECTION* {.final, pure.} = object - emr*: EMR - iArcDirection*: DWORD - - PEMRSETARCDIRECTION* = ptr EMRSETARCDIRECTION - EMRSETBKCOLOR* {.final, pure.} = object - emr*: EMR - crColor*: COLORREF - - PEMRSETBKCOLOR* = ptr EMRSETBKCOLOR - EMRSETTEXTCOLOR* = EMRSETBKCOLOR - PEMRSETTEXTCOLOR* = ptr EMRSETBKCOLOR - EMRSETCOLORADJUSTMENT* {.final, pure.} = object - emr*: EMR - ColorAdjustment*: COLORADJUSTMENT - - PEMRSETCOLORADJUSTMENT* = ptr EMRSETCOLORADJUSTMENT - EMRSETDIBITSTODEVICE* {.final, pure.} = object - emr*: EMR - rclBounds*: RECTL - xDest*: LONG - yDest*: LONG - xSrc*: LONG - ySrc*: LONG - cxSrc*: LONG - cySrc*: LONG - offBmiSrc*: DWORD - cbBmiSrc*: DWORD - offBitsSrc*: DWORD - cbBitsSrc*: DWORD - iUsageSrc*: DWORD - iStartScan*: DWORD - cScans*: DWORD - - PEMRSETDIBITSTODEVICE* = ptr EMRSETDIBITSTODEVICE - EMRSETMAPPERFLAGS* {.final, pure.} = object - emr*: EMR - dwFlags*: DWORD - - PEMRSETMAPPERFLAGS* = ptr EMRSETMAPPERFLAGS - EMRSETMITERLIMIT* {.final, pure.} = object - emr*: EMR - eMiterLimit*: float32 - - PEMRSETMITERLIMIT* = ptr EMRSETMITERLIMIT - EMRSETPALETTEENTRIES* {.final, pure.} = object - emr*: EMR - ihPal*: DWORD - iStart*: DWORD - cEntries*: DWORD - aPalEntries*: array[0..0, PALETTEENTRY] - - PEMRSETPALETTEENTRIES* = ptr EMRSETPALETTEENTRIES - EMRSETPIXELV* {.final, pure.} = object - emr*: EMR - ptlPixel*: POINTL - crColor*: COLORREF - - PEMRSETPIXELV* = ptr EMRSETPIXELV - EMRSETVIEWPORTEXTEX* {.final, pure.} = object - emr*: EMR - szlExtent*: SIZEL - - PEMRSETVIEWPORTEXTEX* = ptr EMRSETVIEWPORTEXTEX - EMRSETWINDOWEXTEX* = EMRSETVIEWPORTEXTEX - PEMRSETWINDOWEXTEX* = ptr EMRSETVIEWPORTEXTEX - EMRSETVIEWPORTORGEX* {.final, pure.} = object - emr*: EMR - ptlOrigin*: POINTL - - PEMRSETVIEWPORTORGEX* = ptr EMRSETVIEWPORTORGEX - EMRSETWINDOWORGEX* = EMRSETVIEWPORTORGEX - PEMRSETWINDOWORGEX* = ptr EMRSETVIEWPORTORGEX - EMRSETBRUSHORGEX* = EMRSETVIEWPORTORGEX - PEMRSETBRUSHORGEX* = ptr EMRSETVIEWPORTORGEX - EMRSETWORLDTRANSFORM* {.final, pure.} = object - emr*: EMR - xform*: XFORM - - PEMRSETWORLDTRANSFORM* = ptr EMRSETWORLDTRANSFORM - EMRSTRETCHBLT* {.final, pure.} = object - emr*: EMR - rclBounds*: RECTL - xDest*: LONG - yDest*: LONG - cxDest*: LONG - cyDest*: LONG - dwRop*: DWORD - xSrc*: LONG - ySrc*: LONG - xformSrc*: XFORM - crBkColorSrc*: COLORREF - iUsageSrc*: DWORD - offBmiSrc*: DWORD - cbBmiSrc*: DWORD - offBitsSrc*: DWORD - cbBitsSrc*: DWORD - cxSrc*: LONG - cySrc*: LONG - - PEMRSTRETCHBLT* = ptr EMRSTRETCHBLT - EMRSTRETCHDIBITS* {.final, pure.} = object - emr*: EMR - rclBounds*: RECTL - xDest*: LONG - yDest*: LONG - xSrc*: LONG - ySrc*: LONG - cxSrc*: LONG - cySrc*: LONG - offBmiSrc*: DWORD - cbBmiSrc*: DWORD - offBitsSrc*: DWORD - cbBitsSrc*: DWORD - iUsageSrc*: DWORD - dwRop*: DWORD - cxDest*: LONG - cyDest*: LONG - - PEMRSTRETCHDIBITS* = ptr EMRSTRETCHDIBITS - EMRABORTPATH* {.final, pure.} = object - emr*: EMR - - PEMRABORTPATH* = ptr EMRABORTPATH - EMRBEGINPATH* = EMRABORTPATH - PEMRBEGINPATH* = ptr EMRABORTPATH - EMRENDPATH* = EMRABORTPATH - PEMRENDPATH* = ptr EMRABORTPATH - EMRCLOSEFIGURE* = EMRABORTPATH - PEMRCLOSEFIGURE* = ptr EMRABORTPATH - EMRFLATTENPATH* = EMRABORTPATH - PEMRFLATTENPATH* = ptr EMRABORTPATH - EMRWIDENPATH* = EMRABORTPATH - PEMRWIDENPATH* = ptr EMRABORTPATH - EMRSETMETARGN* = EMRABORTPATH - PEMRSETMETARGN* = ptr EMRABORTPATH - EMRSAVEDC* = EMRABORTPATH - PEMRSAVEDC* = ptr EMRABORTPATH - EMRREALIZEPALETTE* = EMRABORTPATH - PEMRREALIZEPALETTE* = ptr EMRABORTPATH - EMRSELECTCLIPPATH* {.final, pure.} = object - emr*: EMR - iMode*: DWORD - - PEMRSELECTCLIPPATH* = ptr EMRSELECTCLIPPATH - EMRSETBKMODE* = EMRSELECTCLIPPATH - PEMRSETBKMODE* = ptr EMRSELECTCLIPPATH - EMRSETMAPMODE* = EMRSELECTCLIPPATH - PEMRSETMAPMODE* = ptr EMRSELECTCLIPPATH - EMRSETPOLYFILLMODE* = EMRSELECTCLIPPATH - PEMRSETPOLYFILLMODE* = ptr EMRSELECTCLIPPATH - EMRSETROP2* = EMRSELECTCLIPPATH - PEMRSETROP2* = ptr EMRSELECTCLIPPATH - EMRSETSTRETCHBLTMODE* = EMRSELECTCLIPPATH - PEMRSETSTRETCHBLTMODE* = ptr EMRSELECTCLIPPATH - EMRSETTEXTALIGN* = EMRSELECTCLIPPATH - PEMRSETTEXTALIGN* = ptr EMRSELECTCLIPPATH - EMRENABLEICM* = EMRSELECTCLIPPATH - PEMRENABLEICM* = ptr EMRSELECTCLIPPATH - NMHDR* {.final, pure.} = object - hwndFrom*: HWND - idFrom*: WINUINT - code*: WINUINT - - PNMHDR* = ptr NMHDR - TENCORRECTTEXT* {.final, pure.} = object # Name conflict if we drop the `T` - nmhdr*: NMHDR - chrg*: CHARRANGE - seltyp*: int16 - - Pencorrecttext* = ptr TENCORRECTTEXT - TENDROPFILES* {.final, pure.} = object # Name conflict if we drop the `T` - nmhdr*: NMHDR - hDrop*: HANDLE - cp*: LONG - fProtected*: WINBOOL - - Pendropfiles* = ptr TENDROPFILES - TENSAVECLIPBOARD* {.final, pure.} = object # Name conflict if we drop the `T` - nmhdr*: NMHDR - cObjectCount*: LONG - cch*: LONG - - PENSAVECLIPBOARD* = ptr TENSAVECLIPBOARD - TENOLEOPFAILED* {.final, pure.} = object # Name conflict if we drop the `T` - nmhdr*: NMHDR - iob*: LONG - lOper*: LONG - hr*: HRESULT - - PENOLEOPFAILED* = ptr TENOLEOPFAILED - ENHMETAHEADER* {.final, pure.} = object - iType*: DWORD - nSize*: DWORD - rclBounds*: RECTL - rclFrame*: RECTL - dSignature*: DWORD - nVersion*: DWORD - nBytes*: DWORD - nRecords*: DWORD - nHandles*: int16 - sReserved*: int16 - nDescription*: DWORD - offDescription*: DWORD - nPalEntries*: DWORD - szlDevice*: SIZEL - szlMillimeters*: SIZEL - - LPENHMETAHEADER* = ptr ENHMETAHEADER - PENHMETAHEADER* = ptr ENHMETAHEADER - ENHMETARECORD* {.final, pure.} = object - iType*: DWORD - nSize*: DWORD - dParm*: array[0..0, DWORD] - - LPENHMETARECORD* = ptr ENHMETARECORD - PENHMETARECORD* = ptr ENHMETARECORD - TENPROTECTED* {.final, pure.} = object # Name conflict if we drop the `T` - nmhdr*: NMHDR - msg*: WINUINT - wParam*: WPARAM - lParam*: LPARAM - chrg*: CHARRANGE - - Penprotected* = ptr TENPROTECTED - SERVICE_STATUS* {.final, pure.} = object - dwServiceType*: DWORD - dwCurrentState*: DWORD - dwControlsAccepted*: DWORD - dwWin32ExitCode*: DWORD - dwServiceSpecificExitCode*: DWORD - dwCheckPoint*: DWORD - dwWaitHint*: DWORD - - LPSERVICE_STATUS* = ptr SERVICE_STATUS - PSERVICESTATUS* = ptr SERVICE_STATUS - ENUM_SERVICE_STATUS* {.final, pure.} = object - lpServiceName*: LPTSTR - lpDisplayName*: LPTSTR - ServiceStatus*: SERVICE_STATUS - - LPENUM_SERVICE_STATUS* = ptr ENUM_SERVICE_STATUS - PENUMSERVICESTATUS* = ptr ENUM_SERVICE_STATUS - ENUMLOGFONT* {.final, pure.} = object - elfLogFont*: LOGFONT - elfFullName*: array[0..(LF_FULLFACESIZE) - 1, BCHAR] - elfStyle*: array[0..(LF_FACESIZE) - 1, BCHAR] - - PENUMLOGFONT* = ptr ENUMLOGFONT - ENUMLOGFONTEX* {.final, pure.} = object - elfLogFont*: LOGFONT - elfFullName*: array[0..(LF_FULLFACESIZE) - 1, BCHAR] - elfStyle*: array[0..(LF_FACESIZE) - 1, BCHAR] - elfScript*: array[0..(LF_FACESIZE) - 1, BCHAR] - - PENUMLOGFONTEX* = ptr ENUMLOGFONTEX - - EVENTLOGRECORD* {.final, pure.} = object - Length*: DWORD - Reserved*: DWORD - RecordNumber*: DWORD - TimeGenerated*: DWORD - TimeWritten*: DWORD - EventID*: DWORD - EventType*: int16 - NumStrings*: int16 - EventCategory*: int16 - ReservedFlags*: int16 - ClosingRecordNumber*: DWORD - StringOffset*: DWORD - UserSidLength*: DWORD - UserSidOffset*: DWORD - DataLength*: DWORD - DataOffset*: DWORD - - PEVENTLOGRECORD* = ptr EVENTLOGRECORD - EVENTMSG* {.final, pure.} = object - message*: WINUINT - paramL*: WINUINT - paramH*: WINUINT - time*: DWORD - hwnd*: HWND - - PEVENTMSG* = ptr EVENTMSG - EXCEPTION_POINTERS* {.final, pure.} = object - ExceptionRecord*: PEXCEPTION_RECORD - ContextRecord*: PCONTEXT - - LPEXCEPTION_POINTERS* = ptr EXCEPTION_POINTERS - PEXCEPTION_POINTERS* = ptr EXCEPTION_POINTERS - EXT_BUTTON* {.final, pure.} = object - idCommand*: int16 - idsHelp*: int16 - fsStyle*: int16 - - LPEXT_BUTTON* = ptr EXT_BUTTON - PEXTBUTTON* = ptr EXT_BUTTON - FILTERKEYS* {.final, pure.} = object - cbSize*: WINUINT - dwFlags*: DWORD - iWaitMSec*: DWORD - iDelayMSec*: DWORD - iRepeatMSec*: DWORD - iBounceMSec*: DWORD - - PFILTERKEYS* = ptr FILTERKEYS - FIND_NAME_BUFFER* {.final, pure.} = object - len*: UCHAR - access_control*: UCHAR - frame_control*: UCHAR - destination_addr*: array[0..5, UCHAR] - source_addr*: array[0..5, UCHAR] - routing_info*: array[0..17, UCHAR] - - PFINDNAMEBUFFER* = ptr FIND_NAME_BUFFER - FIND_NAME_HEADER* {.final, pure.} = object - node_count*: int16 - reserved*: UCHAR - unique_group*: UCHAR - - PFINDNAMEHEADER* = ptr FIND_NAME_HEADER - FINDREPLACE* {.final, pure.} = object - lStructSize*: DWORD - hwndOwner*: HWND - hInstance*: HINST - Flags*: DWORD - lpstrFindWhat*: LPTSTR - lpstrReplaceWith*: LPTSTR - wFindWhatLen*: int16 - wReplaceWithLen*: int16 - lCustData*: LPARAM - lpfnHook*: LPFRHOOKPROC - lpTemplateName*: LPCTSTR - - LPFINDREPLACE* = ptr FINDREPLACE - PFINDREPLACE* = ptr FINDREPLACE - #FINDTEXT = record conflicts with FindText function - TFINDTEXT* {.final, pure.} = object - chrg*: CHARRANGE - lpstrText*: LPSTR - - Pfindtext* = ptr TFINDTEXT - FINDTEXTEX* {.final, pure.} = object - chrg*: CHARRANGE - lpstrText*: LPSTR - chrgText*: CHARRANGE - - Pfindtextex* = ptr FINDTEXTEX - FMS_GETDRIVEINFO* {.final, pure.} = object - dwTotalSpace*: DWORD - dwFreeSpace*: DWORD - szPath*: array[0..259, CHAR] - szVolume*: array[0..13, CHAR] - szShare*: array[0..127, CHAR] - - PFMSGETDRIVEINFO* = ptr FMS_GETDRIVEINFO - FMS_GETFILESEL* {.final, pure.} = object - ftTime*: FILETIME - dwSize*: DWORD - bAttr*: int8 - szName*: array[0..259, CHAR] - - PFMSGETFILESEL* = ptr FMS_GETFILESEL - FMS_LOAD* {.final, pure.} = object - dwSize*: DWORD - szMenuName*: array[0..(MENU_TEXT_LEN) - 1, CHAR] - hMenu*: HMENU - wMenuDelta*: WINUINT - - PFMSLOAD* = ptr FMS_LOAD - FMS_TOOLBARLOAD* {.final, pure.} = object - dwSize*: DWORD - lpButtons*: LPEXT_BUTTON - cButtons*: int16 - cBitmaps*: int16 - idBitmap*: int16 - hBitmap*: HBITMAP - - PFMSTOOLBARLOAD* = ptr FMS_TOOLBARLOAD - FOCUS_EVENT_RECORD* {.final, pure.} = object - bSetFocus*: WINBOOL - - PFOCUSEVENTRECORD* = ptr FOCUS_EVENT_RECORD - FORM_INFO_1* {.final, pure.} = object - Flags*: DWORD - pName*: LPTSTR - Size*: SIZEL - ImageableArea*: RECTL - - PFORMINFO1* = ptr FORM_INFO_1 - FORMAT_PARAMETERS* {.final, pure.} = object - MediaType*: MEDIA_TYPE - StartCylinderNumber*: DWORD - EndCylinderNumber*: DWORD - StartHeadNumber*: DWORD - EndHeadNumber*: DWORD - - PFORMATPARAMETERS* = ptr FORMAT_PARAMETERS - FORMATRANGE* {.final, pure.} = object - hdc*: HDC - hdcTarget*: HDC - rc*: RECT - rcPage*: RECT - chrg*: CHARRANGE - - Pformatrange* = ptr FORMATRANGE - GCP_RESULTS* {.final, pure.} = object - lStructSize*: DWORD - lpOutString*: LPTSTR - lpOrder*: ptr WINUINT - lpDx*: ptr WINT - lpCaretPos*: ptr WINT - lpClass*: LPTSTR - lpGlyphs*: ptr WINUINT - nGlyphs*: WINUINT - nMaxFit*: WINUINT - - LPGCP_RESULTS* = ptr GCP_RESULTS - PGCPRESULTS* = ptr GCP_RESULTS - GENERIC_MAPPING* {.final, pure.} = object - GenericRead*: ACCESS_MASK - GenericWrite*: ACCESS_MASK - GenericExecute*: ACCESS_MASK - GenericAll*: ACCESS_MASK - - PGENERIC_MAPPING* = ptr GENERIC_MAPPING - GLYPHMETRICS* {.final, pure.} = object - gmBlackBoxX*: WINUINT - gmBlackBoxY*: WINUINT - gmptGlyphOrigin*: POINT - gmCellIncX*: SHORT - gmCellIncY*: SHORT - - LPGLYPHMETRICS* = ptr GLYPHMETRICS - PGLYPHMETRICS* = ptr GLYPHMETRICS - HANDLETABLE* {.final, pure.} = object - objectHandle*: array[0..0, HGDIOBJ] - - LPHANDLETABLE* = ptr HANDLETABLE - HD_HITTESTINFO* {.final, pure.} = object - pt*: POINT - flags*: WINUINT - iItem*: int32 - - PHDHITTESTINFO* = ptr HD_HITTESTINFO - HD_ITEM* {.final, pure.} = object - mask*: WINUINT - cxy*: int32 - pszText*: LPTSTR - hbm*: HBITMAP - cchTextMax*: int32 - fmt*: int32 - lParam*: LPARAM - - PHDITEM* = ptr HD_ITEM - WINDOWPOS* {.final, pure.} = object - hwnd*: HWND - hwndInsertAfter*: HWND - x*: int32 - y*: int32 - cx*: int32 - cy*: int32 - flags*: WINUINT - - LPWINDOWPOS* = ptr WINDOWPOS - PWINDOWPOS* = ptr WINDOWPOS - HD_LAYOUT* {.final, pure.} = object - prc*: ptr RECT - pwpos*: ptr WINDOWPOS - - PHDLAYOUT* = ptr HD_LAYOUT - HD_NOTIFY* {.final, pure.} = object - hdr*: NMHDR - iItem*: int32 - iButton*: int32 - pitem*: ptr HD_ITEM - - PHDNOTIFY* = ptr HD_NOTIFY - HELPINFO* {.final, pure.} = object - cbSize*: WINUINT - iContextType*: int32 - iCtrlId*: int32 - hItemHandle*: HANDLE - dwContextId*: DWORD - MousePos*: POINT - - LPHELPINFO* = ptr HELPINFO - PHELPINFO* = ptr HELPINFO - HELPWININFO* {.final, pure.} = object - wStructSize*: int32 - x*: int32 - y*: int32 - dx*: int32 - dy*: int32 - wMax*: int32 - rgchMember*: array[0..1, CHAR] - - PHELPWININFO* = ptr HELPWININFO - HIGHCONTRAST* {.final, pure.} = object - cbSize*: WINUINT - dwFlags*: DWORD - lpszDefaultScheme*: LPTSTR - - LPHIGHCONTRAST* = ptr HIGHCONTRAST - PHIGHCONTRAST* = ptr HIGHCONTRAST - HSZPAIR* {.final, pure.} = object - hszSvc*: HSZ - hszTopic*: HSZ - - PHSZPAIR* = ptr HSZPAIR - ICONINFO* {.final, pure.} = object - fIcon*: WINBOOL - xHotspot*: DWORD - yHotspot*: DWORD - hbmMask*: HBITMAP - hbmColor*: HBITMAP - - PICONINFO* = ptr ICONINFO - ICONMETRICS* {.final, pure.} = object - cbSize*: WINUINT - iHorzSpacing*: int32 - iVertSpacing*: int32 - iTitleWrap*: int32 - lfFont*: LOGFONT - - LPICONMETRICS* = ptr ICONMETRICS - PICONMETRICS* = ptr ICONMETRICS - IMAGEINFO* {.final, pure.} = object - hbmImage*: HBITMAP - hbmMask*: HBITMAP - Unused1*: int32 - Unused2*: int32 - rcImage*: RECT - - PIMAGEINFO* = ptr IMAGEINFO - KEY_EVENT_RECORD* {.final, pure.} = object - bKeyDown*: WINBOOL - wRepeatCount*: int16 - wVirtualKeyCode*: int16 - wVirtualScanCode*: int16 - UnicodeChar*: WCHAR - dwControlKeyState*: DWORD # other union part: AsciiChar: CHAR - - PKEYEVENTRECORD* = ptr KEY_EVENT_RECORD - MOUSE_EVENT_RECORD* {.final, pure.} = object - dwMousePosition*: COORD - dwButtonState*: DWORD - dwControlKeyState*: DWORD - dwEventFlags*: DWORD - - PMOUSEEVENTRECORD* = ptr MOUSE_EVENT_RECORD - WINDOW_BUFFER_SIZE_RECORD* {.final, pure.} = object - dwSize*: COORD - - PWINDOWBUFFERSIZERECORD* = ptr WINDOW_BUFFER_SIZE_RECORD - MENU_EVENT_RECORD* {.final, pure.} = object - dwCommandId*: WINUINT - - PMENU_EVENT_RECORD* = ptr MENU_EVENT_RECORD - INPUT_RECORD* {.final, pure.} = object - EventType*: int16 - Reserved*: int16 - event*: array[0..5, DWORD] - - PINPUT_RECORD* = ptr INPUT_RECORD - SYSTEMTIME* {.final, pure.} = object - wYear*: int16 - wMonth*: int16 - wDayOfWeek*: int16 - wDay*: int16 - wHour*: int16 - wMinute*: int16 - wSecond*: int16 - wMilliseconds*: int16 - - LPSYSTEMTIME* = ptr SYSTEMTIME - PSYSTEMTIME* = ptr SYSTEMTIME - JOB_INFO_1* {.final, pure.} = object - JobId*: DWORD - pPrinterName*: LPTSTR - pMachineName*: LPTSTR - pUserName*: LPTSTR - pDocument*: LPTSTR - pDatatype*: LPTSTR - pStatus*: LPTSTR - Status*: DWORD - Priority*: DWORD - Position*: DWORD - TotalPages*: DWORD - PagesPrinted*: DWORD - Submitted*: SYSTEMTIME - - PJOBINFO1* = ptr JOB_INFO_1 - SID_IDENTIFIER_AUTHORITY* {.final, pure.} = object - Value*: array[0..5, int8] - - LPSID_IDENTIFIER_AUTHORITY* = ptr SID_IDENTIFIER_AUTHORITY - PSID_IDENTIFIER_AUTHORITY* = ptr SID_IDENTIFIER_AUTHORITY - SID* {.final, pure.} = object - Revision*: int8 - SubAuthorityCount*: int8 - IdentifierAuthority*: SID_IDENTIFIER_AUTHORITY - SubAuthority*: array[0..(ANYSIZE_ARRAY) - 1, DWORD] - - PSID* = ptr SID - SECURITY_DESCRIPTOR_CONTROL* = int16 - PSECURITY_DESCRIPTOR_CONTROL* = ptr SECURITY_DESCRIPTOR_CONTROL - SECURITY_DESCRIPTOR* {.final, pure.} = object - Revision*: int8 - Sbz1*: int8 - Control*: SECURITY_DESCRIPTOR_CONTROL - Owner*: PSID - Group*: PSID - Sacl*: PACL - Dacl*: PACL - - PSECURITY_DESCRIPTOR* = ptr SECURITY_DESCRIPTOR - JOB_INFO_2* {.final, pure.} = object - JobId*: DWORD - pPrinterName*: LPTSTR - pMachineName*: LPTSTR - pUserName*: LPTSTR - pDocument*: LPTSTR - pNotifyName*: LPTSTR - pDatatype*: LPTSTR - pPrintProcessor*: LPTSTR - pParameters*: LPTSTR - pDriverName*: LPTSTR - pDevMode*: LPDEVMODE - pStatus*: LPTSTR - pSecurityDescriptor*: PSECURITY_DESCRIPTOR - Status*: DWORD - Priority*: DWORD - Position*: DWORD - StartTime*: DWORD - UntilTime*: DWORD - TotalPages*: DWORD - Size*: DWORD - Submitted*: SYSTEMTIME - Time*: DWORD - PagesPrinted*: DWORD - - PJOBINFO2* = ptr JOB_INFO_2 - KERNINGPAIR* {.final, pure.} = object - wFirst*: int16 - wSecond*: int16 - iKernAmount*: int32 - - LPKERNINGPAIR* = ptr KERNINGPAIR - TKERNINGPAIR* = KERNINGPAIR - PKERNINGPAIR* = ptr KERNINGPAIR - LANA_ENUM* {.final, pure.} = object - len*: UCHAR - lana*: array[0..(MAX_LANA) - 1, UCHAR] - - PLANAENUM* = ptr LANA_ENUM - LDT_ENTRY* {.final, pure.} = object - LimitLow*: int16 - BaseLow*: int16 - BaseMid*: int8 - Flags1*: int8 - Flags2*: int8 - BaseHi*: int8 - - LPLDT_ENTRY* = ptr LDT_ENTRY - PLDT_ENTRY* = ptr LDT_ENTRY - -{.deprecated: [TEXCEPTIONRECORD: EXCEPTION_RECORD, TEXCEPTIONDEBUGINFO: EXCEPTION_DEBUG_INFO, - TExceptionRecord32: EXCEPTION_RECORD32, TExceptionDebugInfo32: EXCEPTION_DEBUG_INFO32, - TExceptionRecord64: EXCEPTION_RECORD64, TExceptionDebugInfo64: EXCEPTION_DEBUG_INFO64, - TEXITPROCESSDEBUGINFO: EXIT_PROCESS_DEBUG_INFO, TEXITTHREADDEBUGINFO: EXIT_THREAD_DEBUG_INFO, - TLOADDLLDEBUGINFO: LOAD_DLL_DEBUG_INFO, TUNLOADDLLDEBUGINFO: UNLOAD_DLL_DEBUG_INFO, - TOUTPUTDEBUGSTRINGINFO: OUTPUT_DEBUG_STRING_INFO, TRIPINFO: RIP_INFO, TDEBUGEVENT: DEBUG_EVENT, - TDEBUGHOOKINFO: DEBUGHOOKINFO, TDELETEITEMSTRUCT: DELETEITEMSTRUCT, TDEVBROADCASTHDR: DEV_BROADCAST_HDR, - TDEVBROADCASTOEM: DEV_BROADCAST_OEM, TDEVBROADCASTPORT: DEV_BROADCAST_PORT, - TDEVBROADCASTUSERDEFINED: DEV_BROADCAST_USERDEFINED, TDEVBROADCASTVOLUME: DEV_BROADCAST_VOLUME, - TDevicemode: DEVMODE, TDevicemodeA: DEVMODE, TDEVMODE: DEVMODE, TDEVNAMES: DEVNAMES, TDEVMODEW: DEVMODEW, - TDeviceModeW: DEVMODEW, TDIBSECTION: DIBSECTION, TLargeInteger: LargeInteger, - TULargeInteger: ULargeInteger, TDISKPERFORMANCE: DISK_PERFORMANCE, TDISKGEOMETRY: DISK_GEOMETRY, - TDOCINFO1: DOC_INFO_1, TDLGTEMPLATE: DLGTEMPLATE, TDLGITEMTEMPLATE: DLGITEMTEMPLATE, - TDRAWTEXTPARAMS: DRAWTEXTPARAMS, TDRAWITEMSTRUCT: DRAWITEMSTRUCT, TDRAGLISTINFO: DRAGLISTINFO, - TDOCINFO: DOCINFO, TDOCINFOA: DOCINFO, TDOCINFO2: DOC_INFO_2, TPARTITIONINFORMATION: PARTITION_INFORMATION, - TDRIVELAYOUTINFORMATION: DRIVE_LAYOUT_INFORMATION, TEMRARC: EMRARC, TEMRANGLEARC: EMRANGLEARC, - TEMR: EMR, Teditstream: EDITSTREAM, TDRIVERINFO3: DRIVER_INFO_3, TDRIVERINFO2: DRIVER_INFO_2, - TDRIVERINFO1: DRIVER_INFO_1, TEMREXTCREATEFONTINDIRECTW: EMREXTCREATEFONTINDIRECTW].} - -{.deprecated: [TEXTLOGFONT: EXTLOGFONT, TPANOSE: PANOSE, TEMRINTERSECTCLIPRECT: EMREXCLUDECLIPRECT, - TEMREXCLUDECLIPRECT: EMREXCLUDECLIPRECT, TEMREOF: EMREOF, TEMRRECTANGLE: EMRELLIPSE, - TEMRELLIPSE: EMRELLIPSE, TEMRCREATEPEN: EMRCREATEPEN, TLOGPEN: LOGPEN, TEMRCREATEPALETTE: EMRCREATEPALETTE, - TLOGPALETTE: LOGPALETTE, TPALETTEENTRY: PALETTEENTRY, TEMRCREATEMONOBRUSH: EMRCREATEMONOBRUSH, - TEMRCREATEDIBPATTERNBRUSHPT: EMRCREATEDIBPATTERNBRUSHPT, TEMRCREATECOLORSPACE: EMRCREATECOLORSPACE, - TLOGCOLORSPACE: LOGCOLORSPACE, TLOGCOLORSPACEA: LOGCOLORSPACE, TEMRCREATEBRUSHINDIRECT: EMRCREATEBRUSHINDIRECT, - TLOGBRUSH: LOGBRUSH, TEMRBITBLT: EMRBITBLT, TXFORM: XFORM, TEMRPIE: EMRARC, TEMRCHORD: EMRARC, - TEMRARCTO: EMRARC, TSERVICESTATUS: SERVICE_STATUS, TENUMSERVICESTATUS: ENUM_SERVICE_STATUS, - TENUMLOGFONT: ENUMLOGFONT, TENUMLOGFONTEX: ENUMLOGFONTEX, TEVENTLOGRECORD: EVENTLOGRECORD, - TEVENTMSG: EVENTMSG, TEXCEPTIONPOINTERS: EXCEPTION_POINTERS, TEXTBUTTON: EXT_BUTTON, - TFILTERKEYS: FILTERKEYS, TFINDNAMEBUFFER: FIND_NAME_BUFFER, TFINDNAMEHEADER: FIND_NAME_HEADER, - TFINDREPLACE: FINDREPLACE, Tfindtextex: FINDTEXTEX, TFMSGETDRIVEINFO: FMS_GETDRIVEINFO, - TFMSGETFILESEL: FMS_GETFILESEL, TFMSLOAD: FMS_LOAD, TFMSTOOLBARLOAD: FMS_TOOLBARLOAD, - TFOCUSEVENTRECORD: FOCUS_EVENT_RECORD, TFORMINFO1: FORM_INFO_1, TFORMATPARAMETERS: FORMAT_PARAMETERS, - Tformatrange: FORMATRANGE, TGCPRESULTS: GCP_RESULTS, TGENERICMAPPING: GENERIC_MAPPING, - TGLYPHMETRICS: GLYPHMETRICS, THANDLETABLE: HANDLETABLE, THDHITTESTINFO: HD_HITTESTINFO, - THDITEM: HD_ITEM, TWINDOWPOS: WINDOWPOS, THDLAYOUT: HD_LAYOUT, THDNOTIFY: HD_NOTIFY, - THELPINFO: HELPINFO, THELPWININFO: HELPWININFO, THIGHCONTRAST: HIGHCONTRAST, THSZPAIR: HSZPAIR, - TICONINFO: ICONINFO, TICONMETRICS: ICONMETRICS, TIMAGEINFO: IMAGEINFO, TKEYEVENTRECORD: KEY_EVENT_RECORD, - TMOUSEEVENTRECORD: MOUSE_EVENT_RECORD, TWINDOWBUFFERSIZERECORD: WINDOW_BUFFER_SIZE_RECORD, - TMENUEVENTRECORD: MENU_EVENT_RECORD, TINPUTRECORD: INPUT_RECORD, TSYSTEMTIME: SYSTEMTIME, - TJOBINFO1: JOB_INFO_1].} - -{.deprecated: [TSIDIDENTIFIERAUTHORITY: SID_IDENTIFIER_AUTHORITY, TSID: SID, - TSECURITYDESCRIPTORCONTROL: SECURITY_DESCRIPTOR_CONTROL, TSECURITYDESCRIPTOR: SECURITY_DESCRIPTOR, - TJOBINFO2: JOB_INFO_2, TLANAENUM: LANA_ENUM, TLDTENTRY: LDT_ENTRY, TEMRPOLYPOLYGON: EMRPOLYPOLYLINE, - TEMRPOLYPOLYLINE: EMRPOLYPOLYLINE, TEMRPOLYLINETO16: EMRPOLYLINE16, TEMRPOLYBEZIERTO16: EMRPOLYLINE16, - TEMRPOLYGON16: EMRPOLYLINE16, TEMRPOLYBEZIER16: EMRPOLYLINE16, TEMRPOLYLINE16: EMRPOLYLINE16, - TEMRPOLYLINETO: EMRPOLYLINE, TEMRPOLYBEZIERTO: EMRPOLYLINE, TEMRPOLYGON: EMRPOLYLINE, - TEMRPOLYBEZIER: EMRPOLYLINE, TEMRPOLYLINE: EMRPOLYLINE, TEMRPOLYDRAW16: EMRPOLYDRAW16, - TEMRPOLYDRAW: EMRPOLYDRAW, TEMRPLGBLT: EMRPLGBLT, TEMROFFSETCLIPRGN: EMROFFSETCLIPRGN, - TEMRMODIFYWORLDTRANSFORM: EMRMODIFYWORLDTRANSFORM, TEMRMASKBLT: EMRMASKBLT, TEMRMOVETOEX: EMRLINETO, - TEMRLINETO: EMRLINETO, TEMRPAINTRGN: EMRINVERTRGN, TEMRINVERTRGN: EMRINVERTRGN, - TEMRGDICOMMENT: EMRGDICOMMENT, TEMRFRAMERGN: EMRFRAMERGN, TEMRFORMAT: EMRFORMAT, TEMRFILLRGN: EMRFILLRGN, - TEMRSTROKEPATH: EMRFILLPATH, TEMRSTROKEANDFILLPATH: EMRFILLPATH, TEMRFILLPATH: EMRFILLPATH, - TEMREXTTEXTOUTW: EMREXTTEXTOUTA, TEMREXTTEXTOUTA: EMREXTTEXTOUTA, TEMRTEXT: EMRTEXT, - TEMREXTSELECTCLIPRGN: EMREXTSELECTCLIPRGN, TEMREXTFLOODFILL: EMREXTFLOODFILL, - TEMREXTCREATEPEN: EMREXTCREATEPEN, TEXTLOGPEN: EXTLOGPEN, TNMHDR: NMHDR, TEMRENABLEICM: EMRSELECTCLIPPATH, - TEMRSETTEXTALIGN: EMRSELECTCLIPPATH, TEMRSETSTRETCHBLTMODE: EMRSELECTCLIPPATH, - TEMRSETROP2: EMRSELECTCLIPPATH, TEMRSETPOLYFILLMODE: EMRSELECTCLIPPATH, TEMRSETMAPMODE: EMRSELECTCLIPPATH, - TEMRSETBKMODE: EMRSELECTCLIPPATH, TEMRSELECTCLIPPATH: EMRSELECTCLIPPATH, TEMRREALIZEPALETTE: EMRABORTPATH, - TEMRSAVEDC: EMRABORTPATH, TEMRSETMETARGN: EMRABORTPATH, TEMRWIDENPATH: EMRABORTPATH].} - -{.deprecated: [TEMRFLATTENPATH: EMRABORTPATH, TEMRCLOSEFIGURE: EMRABORTPATH, TEMRENDPATH: EMRABORTPATH, - TEMRBEGINPATH: EMRABORTPATH, TABORTPATH: EMRABORTPATH, TEMRABORTPATH: EMRABORTPATH, - TEMRSTRETCHDIBITS: EMRSTRETCHDIBITS, TEMRSTRETCHBLT: EMRSTRETCHBLT, - TEMRSETWORLDTRANSFORM: EMRSETWORLDTRANSFORM, TEMRSETBRUSHORGEX: EMRSETVIEWPORTORGEX, - TEMRSETWINDOWORGEX: EMRSETVIEWPORTORGEX, TEMRSETVIEWPORTORGEX: EMRSETVIEWPORTORGEX, - TEMRSETWINDOWEXTEX: EMRSETVIEWPORTEXTEX, TEMRSETVIEWPORTEXTEX: EMRSETVIEWPORTEXTEX, - TEMRSETPIXELV: EMRSETPIXELV, TEMRSETPALETTEENTRIES: EMRSETPALETTEENTRIES, - TEMRSETMITERLIMIT: EMRSETMITERLIMIT, TEMRSETMAPPERFLAGS: EMRSETMAPPERFLAGS, - TEMRSETDIBITSTODEVICE: EMRSETDIBITSTODEVICE, TEMRSETCOLORADJUSTMENT: EMRSETCOLORADJUSTMENT, - TEMRSETTEXTCOLOR: EMRSETBKCOLOR, TEMRSETBKCOLOR: EMRSETBKCOLOR, TEMRSETARCDIRECTION: EMRSETARCDIRECTION, - TEMRSELECTPALETTE: EMRSELECTPALETTE, TEMRDELETEOBJECT: EMRSELECTOBJECT, TEMRSELECTOBJECT: EMRSELECTOBJECT, - TEMRDELETECOLORSPACE: EMRSELECTCOLORSPACE, TEMRSELECTCOLORSPACE: EMRSELECTCOLORSPACE, - TEMRSCALEWINDOWEXTEX: EMRSCALEVIEWPORTEXTEX, TEMRSCALEVIEWPORTEXTEX: EMRSCALEVIEWPORTEXTEX, - TEMRROUNDRECT: EMRROUNDRECT, TEMRRESTOREDC: EMRRESTOREDC, TEMRRESIZEPALETTE: EMRRESIZEPALETTE, - TEMRPOLYTEXTOUTW: EMRPOLYTEXTOUTA, TEMRPOLYTEXTOUTA: EMRPOLYTEXTOUTA, - TEMRPOLYPOLYGON16: EMRPOLYPOLYLINE16, TEMRPOLYPOLYLINE16: EMRPOLYPOLYLINE16, - TENHMETAHEADER: ENHMETAHEADER, TENHMETARECORD: ENHMETARECORD].} - - - -const - bm_LDT_ENTRY_BaseMid* = 0x000000FF - bp_LDT_ENTRY_BaseMid* = 0'i32 - bm_LDT_ENTRY_Type* = 0x00001F00 - bp_LDT_ENTRY_Type* = 8'i32 - bm_LDT_ENTRY_Dpl* = 0x00006000 - bp_LDT_ENTRY_Dpl* = 13'i32 - bm_LDT_ENTRY_Pres* = 0x00008000 - bp_LDT_ENTRY_Pres* = 15'i32 - bm_LDT_ENTRY_LimitHi* = 0x000F0000 - bp_LDT_ENTRY_LimitHi* = 16'i32 - bm_LDT_ENTRY_Sys* = 0x00100000 - bp_LDT_ENTRY_Sys* = 20'i32 - bm_LDT_ENTRY_Reserved_0* = 0x00200000 - bp_LDT_ENTRY_Reserved_0* = 21'i32 - bm_LDT_ENTRY_Default_Big* = 0x00400000 - bp_LDT_ENTRY_Default_Big* = 22'i32 - bm_LDT_ENTRY_Granularity* = 0x00800000 - bp_LDT_ENTRY_Granularity* = 23'i32 - bm_LDT_ENTRY_BaseHi* = 0xFF000000 - bp_LDT_ENTRY_BaseHi* = 24'i32 - -type - LOCALESIGNATURE* {.final, pure.} = object - lsUsb*: array[0..3, DWORD] - lsCsbDefault*: array[0..1, DWORD] - lsCsbSupported*: array[0..1, DWORD] - - PLOCALESIGNATURE* = ptr LOCALESIGNATURE - LOCALGROUP_MEMBERS_INFO_0* {.final, pure.} = object - lgrmi0_sid*: PSID - - PLOCALGROUPMEMBERSINFO0* = ptr LOCALGROUP_MEMBERS_INFO_0 - LOCALGROUP_MEMBERS_INFO_3* {.final, pure.} = object - lgrmi3_domainandname*: LPWSTR - - PLOCALGROUPMEMBERSINFO3* = ptr LOCALGROUP_MEMBERS_INFO_3 - FXPT16DOT16* = int32 - LPFXPT16DOT16* = ptr FXPT16DOT16 - PFXPT16DOT16* = ptr FXPT16DOT16 - LUID* = LargeInteger - PLUID* = ptr LUID - LUID_AND_ATTRIBUTES* {.final, pure.} = object - Luid*: LUID - Attributes*: DWORD - - PLUIDANDATTRIBUTES* = ptr LUID_AND_ATTRIBUTES - LUID_AND_ATTRIBUTES_ARRAY* = array[0..(ANYSIZE_ARRAY) - 1, LUID_AND_ATTRIBUTES] - PLUID_AND_ATTRIBUTES_ARRAY* = ptr LUID_AND_ATTRIBUTES_ARRAY - LV_COLUMN* {.final, pure.} = object - mask*: WINUINT - fmt*: int32 - cx*: int32 - pszText*: LPTSTR - cchTextMax*: int32 - iSubItem*: int32 - - PLVCOLUMN* = ptr LV_COLUMN - LV_ITEM* {.final, pure.} = object - mask*: WINUINT - iItem*: int32 - iSubItem*: int32 - state*: WINUINT - stateMask*: WINUINT - pszText*: LPTSTR - cchTextMax*: int32 - iImage*: int32 - lParam*: LPARAM - - PLVITEM* = ptr LV_ITEM - LV_DISPINFO* {.final, pure.} = object - hdr*: NMHDR - item*: LV_ITEM - - PLVDISPINFO* = ptr LV_DISPINFO - LV_FINDINFO* {.final, pure.} = object - flags*: WINUINT - psz*: LPCTSTR - lParam*: LPARAM - pt*: POINT - vkDirection*: WINUINT - - PLVFINDINFO* = ptr LV_FINDINFO - LV_HITTESTINFO* {.final, pure.} = object - pt*: POINT - flags*: WINUINT - iItem*: int32 - - PLVHITTESTINFO* = ptr LV_HITTESTINFO - LV_KEYDOWN* {.final, pure.} = object - hdr*: NMHDR - wVKey*: int16 - flags*: WINUINT - - PLVKEYDOWN* = ptr LV_KEYDOWN - MAT2* {.final, pure.} = object - eM11*: FIXED - eM12*: FIXED - eM21*: FIXED - eM22*: FIXED - - PMAT2* = ptr MAT2 - MDICREATESTRUCT* {.final, pure.} = object - szClass*: LPCTSTR - szTitle*: LPCTSTR - hOwner*: HANDLE - x*: int32 - y*: int32 - cx*: int32 - cy*: int32 - style*: DWORD - lParam*: LPARAM - - LPMDICREATESTRUCT* = ptr MDICREATESTRUCT - PMDICREATESTRUCT* = ptr MDICREATESTRUCT - MEASUREITEMSTRUCT* {.final, pure.} = object - CtlType*: WINUINT - CtlID*: WINUINT - itemID*: WINUINT - itemWidth*: WINUINT - itemHeight*: WINUINT - itemData*: ULONG_PTR - - LPMEASUREITEMSTRUCT* = ptr MEASUREITEMSTRUCT - PMEASUREITEMSTRUCT* = ptr MEASUREITEMSTRUCT - MEMORY_BASIC_INFORMATION* {.final, pure.} = object - BaseAddress*: PVOID - AllocationBase*: PVOID - AllocationProtect*: DWORD - RegionSize*: DWORD - State*: DWORD - Protect*: DWORD - `type`*: DWORD - - PMEMORY_BASIC_INFORMATION* = ptr MEMORY_BASIC_INFORMATION - MEMORYSTATUS* {.final, pure.} = object - dwLength*: DWORD - dwMemoryLoad*: DWORD - dwTotalPhys*: int - dwAvailPhys*: int - dwTotalPageFile*: int - dwAvailPageFile*: int - dwTotalVirtual*: int - dwAvailVirtual*: int - - GUID* {.final, pure.} = object - D1*: int32 - D2*: int16 - D3*: int16 - D4*: array [0..7, int8] - - LPMEMORYSTATUS* = ptr MEMORYSTATUS - PMEMORYSTATUS* = ptr MEMORYSTATUS - MENUEX_TEMPLATE_HEADER* {.final, pure.} = object - wVersion*: int16 - wOffset*: int16 - dwHelpId*: DWORD - - PMENUXTEMPLATEHEADER* = ptr MENUEX_TEMPLATE_HEADER - MENUEX_TEMPLATE_ITEM* {.final, pure.} = object - dwType*: DWORD - dwState*: DWORD - uId*: WINUINT - bResInfo*: int8 - szText*: array[0..0, WCHAR] - dwHelpId*: DWORD - - PMENUEXTEMPLATEITEM* = ptr MENUEX_TEMPLATE_ITEM - MENUINFO* {.final, pure.} = object - cbSize*: DWORD - fMask*: DWORD - dwStyle*: DWORD - cyMax*: WINUINT - hbrBack*: HBRUSH - dwContextHelpID*: DWORD - dwMenuData*: ULONG_PTR - - LPMENUINFO* = ptr MENUINFO - LPCMENUINFO* = ptr MENUINFO - PMENUINFO* = ptr MENUINFO - MENUITEMINFO* {.final, pure.} = object - cbSize*: WINUINT - fMask*: WINUINT - fType*: WINUINT - fState*: WINUINT - wID*: WINUINT - hSubMenu*: HMENU - hbmpChecked*: HBITMAP - hbmpUnchecked*: HBITMAP - dwItemData*: ULONG_PTR - dwTypeData*: LPTSTR - cch*: WINUINT - hbmpItem*: HBITMAP - - LPMENUITEMINFO* = ptr MENUITEMINFO - LPCMENUITEMINFO* = ptr MENUITEMINFO - PMENUITEMINFO* = ptr MENUITEMINFO - MENUITEMTEMPLATE* {.final, pure.} = object - mtOption*: int16 - mtID*: int16 - mtString*: array[0..0, WCHAR] - - PMENUITEMTEMPLATE* = ptr MENUITEMTEMPLATE - MENUITEMTEMPLATEHEADER* {.final, pure.} = object - versionNumber*: int16 - offset*: int16 - - PMENUITEMTEMPLATEHEADER* = ptr MENUITEMTEMPLATEHEADER - MENUTEMPLATE* {.final, pure.} = object - LPMENUTEMPLATE* = ptr MENUTEMPLATE - PMENUTEMPLATE* = ptr MENUTEMPLATE - METAFILEPICT* {.final, pure.} = object - mm*: LONG - xExt*: LONG - yExt*: LONG - hMF*: HMETAFILE - - LPMETAFILEPICT* = ptr METAFILEPICT - PMETAFILEPICT* = ptr METAFILEPICT - METAHEADER* {.final, pure.} = object - mtType*: int16 - mtHeaderSize*: int16 - mtVersion*: int16 - mtSize*: DWORD - mtNoObjects*: int16 - mtMaxRecord*: DWORD - mtNoParameters*: int16 - - PMETAHEADER* = ptr METAHEADER - METARECORD* {.final, pure.} = object - rdSize*: DWORD - rdFunction*: int16 - rdParm*: array[0..0, int16] - - LPMETARECORD* = ptr METARECORD - PMETARECORD* = ptr METARECORD - MINIMIZEDMETRICS* {.final, pure.} = object - cbSize*: WINUINT - iWidth*: int32 - iHorzGap*: int32 - iVertGap*: int32 - iArrange*: int32 - - LPMINIMIZEDMETRICS* = ptr MINIMIZEDMETRICS - PMINIMIZEDMETRICS* = ptr MINIMIZEDMETRICS - MINMAXINFO* {.final, pure.} = object - ptReserved*: POINT - ptMaxSize*: POINT - ptMaxPosition*: POINT - ptMinTrackSize*: POINT - ptMaxTrackSize*: POINT - - PMINMAXINFO* = ptr MINMAXINFO - MODEMDEVCAPS* {.final, pure.} = object - dwActualSize*: DWORD - dwRequiredSize*: DWORD - dwDevSpecificOffset*: DWORD - dwDevSpecificSize*: DWORD - dwModemProviderVersion*: DWORD - dwModemManufacturerOffset*: DWORD - dwModemManufacturerSize*: DWORD - dwModemModelOffset*: DWORD - dwModemModelSize*: DWORD - dwModemVersionOffset*: DWORD - dwModemVersionSize*: DWORD - dwDialOptions*: DWORD - dwCallSetupFailTimer*: DWORD - dwInactivityTimeout*: DWORD - dwSpeakerVolume*: DWORD - dwSpeakerMode*: DWORD - dwModemOptions*: DWORD - dwMaxDTERate*: DWORD - dwMaxDCERate*: DWORD - abVariablePortion*: array[0..0, int8] - - LPMODEMDEVCAPS* = ptr MODEMDEVCAPS - PMODEMDEVCAPS* = ptr MODEMDEVCAPS - MODEMSETTINGS* {.final, pure.} = object - dwActualSize*: DWORD - dwRequiredSize*: DWORD - dwDevSpecificOffset*: DWORD - dwDevSpecificSize*: DWORD - dwCallSetupFailTimer*: DWORD - dwInactivityTimeout*: DWORD - dwSpeakerVolume*: DWORD - dwSpeakerMode*: DWORD - dwPreferredModemOptions*: DWORD - dwNegotiatedModemOptions*: DWORD - dwNegotiatedDCERate*: DWORD - abVariablePortion*: array[0..0, int8] - - LPMODEMSETTINGS* = ptr MODEMSETTINGS - PMODEMSETTINGS* = ptr MODEMSETTINGS - MONCBSTRUCT* {.final, pure.} = object - cb*: WINUINT - dwTime*: DWORD - hTask*: HANDLE - dwRet*: DWORD - wType*: WINUINT - wFmt*: WINUINT - hConv*: HCONV - hsz1*: HSZ - hsz2*: HSZ - hData*: HDDEDATA - dwData1*: DWORD - dwData2*: DWORD - cc*: CONVCONTEXT - cbData*: DWORD - Data*: array[0..7, DWORD] - - PMONCBSTRUCT* = ptr MONCBSTRUCT - MONCONVSTRUCT* {.final, pure.} = object - cb*: WINUINT - fConnect*: WINBOOL - dwTime*: DWORD - hTask*: HANDLE - hszSvc*: HSZ - hszTopic*: HSZ - hConvClient*: HCONV - hConvServer*: HCONV - - PMONCONVSTRUCT* = ptr MONCONVSTRUCT - MONERRSTRUCT* {.final, pure.} = object - cb*: WINUINT - wLastError*: WINUINT - dwTime*: DWORD - hTask*: HANDLE - - PMONERRSTRUCT* = ptr MONERRSTRUCT - MONHSZSTRUCT* {.final, pure.} = object - cb*: WINUINT - fsAction*: WINBOOL - dwTime*: DWORD - hsz*: HSZ - hTask*: HANDLE - str*: array[0..0, CHAR] - - PMONHSZSTRUCT* = ptr MONHSZSTRUCT - MONITOR_INFO_1* {.final, pure.} = object - pName*: LPTSTR - - PMONITORINFO1* = ptr MONITOR_INFO_1 - MONITOR_INFO_2* {.final, pure.} = object - pName*: LPTSTR - pEnvironment*: LPTSTR - pDLLName*: LPTSTR - - PMONITORINFO2* = ptr MONITOR_INFO_2 - MONLINKSTRUCT* {.final, pure.} = object - cb*: WINUINT - dwTime*: DWORD - hTask*: HANDLE - fEstablished*: WINBOOL - fNoData*: WINBOOL - hszSvc*: HSZ - hszTopic*: HSZ - hszItem*: HSZ - wFmt*: WINUINT - fServer*: WINBOOL - hConvServer*: HCONV - hConvClient*: HCONV - - PMONLINKSTRUCT* = ptr MONLINKSTRUCT - MONMSGSTRUCT* {.final, pure.} = object - cb*: WINUINT - hwndTo*: HWND - dwTime*: DWORD - hTask*: HANDLE - wMsg*: WINUINT - wParam*: WPARAM - lParam*: LPARAM - dmhd*: DDEML_MSG_HOOK_DATA - - PMONMSGSTRUCT* = ptr MONMSGSTRUCT - MOUSEHOOKSTRUCT* {.final, pure.} = object - pt*: POINT - hwnd*: HWND - wHitTestCode*: WINUINT - dwExtraInfo*: DWORD - - LPMOUSEHOOKSTRUCT* = ptr MOUSEHOOKSTRUCT - PMOUSEHOOKSTRUCT* = ptr MOUSEHOOKSTRUCT - MOUSEKEYS* {.final, pure.} = object - cbSize*: DWORD - dwFlags*: DWORD - iMaxSpeed*: DWORD - iTimeToMaxSpeed*: DWORD - iCtrlSpeed*: DWORD - dwReserved1*: DWORD - dwReserved2*: DWORD - - PMOUSEKEYS* = ptr MOUSEKEYS - MSGBOXCALLBACK* = proc (lpHelpInfo: LPHELPINFO){.stdcall.} - TMSGBOXCALLBACK* = MSGBOXCALLBACK - MSGBOXPARAMS* {.final, pure.} = object - cbSize*: WINUINT - hwndOwner*: HWND - hInstance*: HINST - lpszText*: LPCSTR - lpszCaption*: LPCSTR - dwStyle*: DWORD - lpszIcon*: LPCSTR - dwContextHelpId*: DWORD - lpfnMsgBoxCallback*: MSGBOXCALLBACK - dwLanguageId*: DWORD - - LPMSGBOXPARAMS* = ptr MSGBOXPARAMS - PMSGBOXPARAMS* = ptr MSGBOXPARAMS - MSGFILTER* {.final, pure.} = object - nmhdr*: NMHDR - msg*: WINUINT - wParam*: WPARAM - lParam*: LPARAM - - Pmsgfilter* = ptr MSGFILTER - MULTIKEYHELP* {.final, pure.} = object - mkSize*: DWORD - mkKeylist*: CHAR - szKeyphrase*: array[0..0, CHAR] - - PMULTIKEYHELP* = ptr MULTIKEYHELP - NAME_BUFFER* {.final, pure.} = object - name*: array[0..(NCBNAMSZ) - 1, UCHAR] - name_num*: UCHAR - name_flags*: UCHAR - - PNAMEBUFFER* = ptr NAME_BUFFER - p_NCB* = ptr NCB - NCB* {.final, pure.} = object - ncb_command*: UCHAR - ncb_retcode*: UCHAR - ncb_lsn*: UCHAR - ncb_num*: UCHAR - ncb_buffer*: PUCHAR - ncb_length*: int16 - ncb_callname*: array[0..(NCBNAMSZ) - 1, UCHAR] - ncb_name*: array[0..(NCBNAMSZ) - 1, UCHAR] - ncb_rto*: UCHAR - ncb_sto*: UCHAR - ncb_post*: proc (para1: p_NCB){.cdecl.} - ncb_lana_num*: UCHAR - ncb_cmd_cplt*: UCHAR - ncb_reserve*: array[0..9, UCHAR] - ncb_event*: HANDLE - - NCCALCSIZE_PARAMS* {.final, pure.} = object - rgrc*: array[0..2, RECT] - lppos*: PWINDOWPOS - - TNCCALCSIZEPARAMS* = NCCALCSIZE_PARAMS - PNCCALCSIZEPARAMS* = ptr NCCALCSIZE_PARAMS - NDDESHAREINFO* {.final, pure.} = object - lRevision*: LONG - lpszShareName*: LPTSTR - lShareType*: LONG - lpszAppTopicList*: LPTSTR - fSharedFlag*: LONG - fService*: LONG - fStartAppFlag*: LONG - nCmdShow*: LONG - qModifyId*: array[0..1, LONG] - cNumItems*: LONG - lpszItemList*: LPTSTR - - PNDDESHAREINFO* = ptr NDDESHAREINFO - NETRESOURCE* {.final, pure.} = object - dwScope*: DWORD - dwType*: DWORD - dwDisplayType*: DWORD - dwUsage*: DWORD - lpLocalName*: LPTSTR - lpRemoteName*: LPTSTR - lpComment*: LPTSTR - lpProvider*: LPTSTR - - LPNETRESOURCE* = ptr NETRESOURCE - PNETRESOURCE* = ptr NETRESOURCE - PNETRESOURCEA* = ptr NETRESOURCE - NEWCPLINFO* {.final, pure.} = object - dwSize*: DWORD - dwFlags*: DWORD - dwHelpContext*: DWORD - lData*: LONG - hIcon*: HICON - szName*: array[0..31, CHAR] - szInfo*: array[0..63, CHAR] - szHelpFile*: array[0..127, CHAR] - - PNEWCPLINFO* = ptr NEWCPLINFO - NEWTEXTMETRIC* {.final, pure.} = object - tmHeight*: LONG - tmAscent*: LONG - tmDescent*: LONG - tmInternalLeading*: LONG - tmExternalLeading*: LONG - tmAveCharWidth*: LONG - tmMaxCharWidth*: LONG - tmWeight*: LONG - tmOverhang*: LONG - tmDigitizedAspectX*: LONG - tmDigitizedAspectY*: LONG - tmFirstChar*: BCHAR - tmLastChar*: BCHAR - tmDefaultChar*: BCHAR - tmBreakChar*: BCHAR - tmItalic*: int8 - tmUnderlined*: int8 - tmStruckOut*: int8 - tmPitchAndFamily*: int8 - tmCharSet*: int8 - ntmFlags*: DWORD - ntmSizeEM*: WINUINT - ntmCellHeight*: WINUINT - ntmAvgWidth*: WINUINT - - PNEWTEXTMETRIC* = ptr NEWTEXTMETRIC - NEWTEXTMETRICEX* {.final, pure.} = object - ntmentm*: NEWTEXTMETRIC - ntmeFontSignature*: FONTSIGNATURE - - PNEWTEXTMETRICEX* = ptr NEWTEXTMETRICEX - NM_LISTVIEW* {.final, pure.} = object - hdr*: NMHDR - iItem*: int32 - iSubItem*: int32 - uNewState*: WINUINT - uOldState*: WINUINT - uChanged*: WINUINT - ptAction*: POINT - lParam*: LPARAM - - PNMLISTVIEW* = ptr NM_LISTVIEW - TV_ITEM* {.final, pure.} = object - mask*: WINUINT - hItem*: HTREEITEM - state*: WINUINT - stateMask*: WINUINT - pszText*: LPTSTR - cchTextMax*: int32 - iImage*: int32 - iSelectedImage*: int32 - cChildren*: int32 - lParam*: LPARAM - - LPTV_ITEM* = ptr TV_ITEM - PTVITEM* = ptr TV_ITEM - NM_TREEVIEW* {.final, pure.} = object - hdr*: NMHDR - action*: WINUINT - itemOld*: TV_ITEM - itemNew*: TV_ITEM - ptDrag*: POINT - - LPNM_TREEVIEW* = ptr NM_TREEVIEW - PNMTREEVIEW* = ptr NM_TREEVIEW - NM_UPDOWNW* {.final, pure.} = object - hdr*: NMHDR - iPos*: int32 - iDelta*: int32 - - PNMUPDOWN* = ptr NM_UPDOWNW - NONCLIENTMETRICS* {.final, pure.} = object - cbSize*: WINUINT - iBorderWidth*: int32 - iScrollWidth*: int32 - iScrollHeight*: int32 - iCaptionWidth*: int32 - iCaptionHeight*: int32 - lfCaptionFont*: LOGFONT - iSmCaptionWidth*: int32 - iSmCaptionHeight*: int32 - lfSmCaptionFont*: LOGFONT - iMenuWidth*: int32 - iMenuHeight*: int32 - lfMenuFont*: LOGFONT - lfStatusFont*: LOGFONT - lfMessageFont*: LOGFONT - - LPNONCLIENTMETRICS* = ptr NONCLIENTMETRICS - PNONCLIENTMETRICS* = ptr NONCLIENTMETRICS - SERVICE_ADDRESS* {.final, pure.} = object - dwAddressType*: DWORD - dwAddressFlags*: DWORD - dwAddressLength*: DWORD - dwPrincipalLength*: DWORD - lpAddress*: ptr int8 - lpPrincipal*: ptr int8 - - PSERVICEADDRESS* = ptr SERVICE_ADDRESS - SERVICE_ADDRESSES* {.final, pure.} = object - dwAddressCount*: DWORD - Addresses*: array[0..0, SERVICE_ADDRESS] - - LPSERVICE_ADDRESSES* = ptr SERVICE_ADDRESSES - PSERVICEADDRESSES* = ptr SERVICE_ADDRESSES - LPGUID* = ptr GUID - PGUID* = ptr GUID - CLSID* = GUID - LPCLSID* = ptr CLSID - PCLSID* = ptr CLSID - SERVICE_INFO* {.final, pure.} = object - lpServiceType*: LPGUID - lpServiceName*: LPTSTR - lpComment*: LPTSTR - lpLocale*: LPTSTR - dwDisplayHint*: DWORD - dwVersion*: DWORD - dwTime*: DWORD - lpMachineName*: LPTSTR - lpServiceAddress*: LPSERVICE_ADDRESSES - ServiceSpecificInfo*: BLOB - - PSERVICEINFO* = ptr SERVICE_INFO - NS_SERVICE_INFO* {.final, pure.} = object - dwNameSpace*: DWORD - ServiceInfo*: SERVICE_INFO - - PNSSERVICEINFO* = ptr NS_SERVICE_INFO - NUMBERFMT* {.final, pure.} = object - NumDigits*: WINUINT - LeadingZero*: WINUINT - Grouping*: WINUINT - lpDecimalSep*: LPTSTR - lpThousandSep*: LPTSTR - NegativeOrder*: WINUINT - - Pnumberfmt* = ptr NUMBERFMT - OFSTRUCT* {.final, pure.} = object - cBytes*: int8 - fFixedDisk*: int8 - nErrCode*: int16 - Reserved1*: int16 - Reserved2*: int16 - szPathName*: array[0..(OFS_MAXPATHNAME) - 1, char] - - LPOFSTRUCT* = ptr OFSTRUCT - POFSTRUCT* = ptr OFSTRUCT - OPENFILENAME_NT4* {.final, pure.} = object - lStructSize*: DWORD - hwndOwner*: HWND - hInstance*: HINST - lpstrFilter*: LPCTSTR - lpstrCustomFilter*: LPTSTR - nMaxCustFilter*: DWORD - nFilterIndex*: DWORD - lpstrFile*: LPTSTR - nMaxFile*: DWORD - lpstrFileTitle*: LPTSTR - nMaxFileTitle*: DWORD - lpstrInitialDir*: LPCTSTR - lpstrTitle*: LPCTSTR - Flags*: DWORD - nFileOffset*: int16 - nFileExtension*: int16 - lpstrDefExt*: LPCTSTR - lCustData*: LPARAM - lpfnHook*: LPOFNHOOKPROC - lpTemplateName*: LPCTSTR - - LPOPENFILENAME_NT4* = ptr OPENFILENAME_NT4 - POPENFILENAME_NT4* = ptr OPENFILENAME_NT4 - OPENFILENAME* {.final, pure.} = object - lStructSize*: DWORD - hwndOwner*: HWND - hInstance*: HINST - lpstrFilter*: LPCTSTR - lpstrCustomFilter*: LPTSTR - nMaxCustFilter*: DWORD - nFilterIndex*: DWORD - lpstrFile*: LPTSTR - nMaxFile*: DWORD - lpstrFileTitle*: LPTSTR - nMaxFileTitle*: DWORD - lpstrInitialDir*: LPCTSTR - lpstrTitle*: LPCTSTR - flags*: DWORD - nFileOffset*: int16 - nFileExtension*: int16 - lpstrDefExt*: LPCTSTR - lCustData*: LPARAM - lpfnHook*: LPOFNHOOKPROC - lpTemplateName*: LPCTSTR - pvReserved*: pointer - dwreserved*: DWORD - FlagsEx*: DWORD - - LPOPENFILENAME* = ptr OPENFILENAME - POPENFILENAME* = ptr OPENFILENAME - OFN* = OPENFILENAME - POFN* = ptr OPENFILENAME - OFNOTIFY* {.final, pure.} = object - hdr*: NMHDR - lpOFN*: LPOPENFILENAME - pszFile*: LPTSTR - - LPOFNOTIFY* = ptr OFNOTIFY - POFNOTIFY* = ptr OFNOTIFY - OSVERSIONINFO* {.final, pure.} = object - dwOSVersionInfoSize*: DWORD - dwMajorVersion*: DWORD - dwMinorVersion*: DWORD - dwBuildNumber*: DWORD - dwPlatformId*: DWORD - szCSDVersion*: array[0..127, CHAR] - - LPOSVERSIONINFO* = ptr OSVERSIONINFO - POSVERSIONINFO* = ptr OSVERSIONINFO - OSVERSIONINFOW* {.final, pure.} = object - dwOSVersionInfoSize*: DWORD - dwMajorVersion*: DWORD - dwMinorVersion*: DWORD - dwBuildNumber*: DWORD - dwPlatformId*: DWORD - szCSDVersion*: array[0..127, WCHAR] - - LPOSVERSIONINFOW* = ptr OSVERSIONINFOW - POSVERSIONINFOW* = ptr OSVERSIONINFOW - TEXTMETRIC* {.final, pure.} = object - tmHeight*: LONG - tmAscent*: LONG - tmDescent*: LONG - tmInternalLeading*: LONG - tmExternalLeading*: LONG - tmAveCharWidth*: LONG - tmMaxCharWidth*: LONG - tmWeight*: LONG - tmOverhang*: LONG - tmDigitizedAspectX*: LONG - tmDigitizedAspectY*: LONG - tmFirstChar*: BCHAR - tmLastChar*: BCHAR - tmDefaultChar*: BCHAR - tmBreakChar*: BCHAR - tmItalic*: int8 - tmUnderlined*: int8 - tmStruckOut*: int8 - tmPitchAndFamily*: int8 - tmCharSet*: int8 - - LPTEXTMETRIC* = ptr TEXTMETRIC - PTEXTMETRIC* = ptr TEXTMETRIC - TEXTMETRICW* {.final, pure.} = object - tmHeight*: LONG - tmAscent*: LONG - tmDescent*: LONG - tmInternalLeading*: LONG - tmExternalLeading*: LONG - tmAveCharWidth*: LONG - tmMaxCharWidth*: LONG - tmWeight*: LONG - tmOverhang*: LONG - tmDigitizedAspectX*: LONG - tmDigitizedAspectY*: LONG - tmFirstChar*: WCHAR - tmLastChar*: WCHAR - tmDefaultChar*: WCHAR - tmBreakChar*: WCHAR - tmItalic*: int8 - tmUnderlined*: int8 - tmStruckOut*: int8 - tmPitchAndFamily*: int8 - tmCharSet*: int8 - - LPTEXTMETRICW* = ptr TEXTMETRICW - PTEXTMETRICW* = ptr TEXTMETRICW - OUTLINETEXTMETRIC* {.final, pure.} = object - otmSize*: WINUINT - otmTextMetrics*: TEXTMETRIC - otmFiller*: int8 - otmPanoseNumber*: PANOSE - otmfsSelection*: WINUINT - otmfsType*: WINUINT - otmsCharSlopeRise*: int32 - otmsCharSlopeRun*: int32 - otmItalicAngle*: int32 - otmEMSquare*: WINUINT - otmAscent*: int32 - otmDescent*: int32 - otmLineGap*: WINUINT - otmsCapEmHeight*: WINUINT - otmsXHeight*: WINUINT - otmrcFontBox*: RECT - otmMacAscent*: int32 - otmMacDescent*: int32 - otmMacLineGap*: WINUINT - otmusMinimumPPEM*: WINUINT - otmptSubscriptSize*: POINT - otmptSubscriptOffset*: POINT - otmptSuperscriptSize*: POINT - otmptSuperscriptOffset*: POINT - otmsStrikeoutSize*: WINUINT - otmsStrikeoutPosition*: int32 - otmsUnderscoreSize*: int32 - otmsUnderscorePosition*: int32 - otmpFamilyName*: PSTR - otmpFaceName*: PSTR - otmpStyleName*: PSTR - otmpFullName*: PSTR - - LPOUTLINETEXTMETRIC* = ptr OUTLINETEXTMETRIC - POUTLINETEXTMETRIC* = ptr OUTLINETEXTMETRIC - OVERLAPPED* {.final, pure.} = object - Internal*: DWORD - InternalHigh*: DWORD - Offset*: DWORD - OffsetHigh*: DWORD - hEvent*: HANDLE - - LPOVERLAPPED* = ptr OVERLAPPED - POVERLAPPED* = ptr OVERLAPPED - #PAGESETUPDLG = record conflicts with function PageSetupDlg - TPAGESETUPDLG* {.final, pure.} = object - lStructSize*: DWORD - hwndOwner*: HWND - hDevMode*: HGLOBAL - hDevNames*: HGLOBAL - Flags*: DWORD - ptPaperSize*: POINT - rtMinMargin*: RECT - rtMargin*: RECT - hInstance*: HINST - lCustData*: LPARAM - lpfnPageSetupHook*: LPPAGESETUPHOOK - lpfnPagePaintHook*: LPPAGEPAINTHOOK - lpPageSetupTemplateName*: LPCTSTR - hPageSetupTemplate*: HGLOBAL - - LPPAGESETUPDLG* = ptr TPAGESETUPDLG - PPAGESETUPDLG* = ptr TPAGESETUPDLG - PPSD* = ptr TPAGESETUPDLG - PAINTSTRUCT* {.final, pure.} = object - hdc*: HDC - fErase*: WINBOOL - rcPaint*: RECT - fRestore*: WINBOOL - fIncUpdate*: WINBOOL - rgbReserved*: array[0..31, int8] - - LPPAINTSTRUCT* = ptr PAINTSTRUCT - PPAINTSTRUCT* = ptr PAINTSTRUCT - PARAFORMAT* {.final, pure.} = object - cbSize*: WINUINT - dwMask*: DWORD - wNumbering*: int16 - wReserved*: int16 - dxStartIndent*: LONG - dxRightIndent*: LONG - dxOffset*: LONG - wAlignment*: int16 - cTabCount*: SHORT - rgxTabs*: array[0..(MAX_TAB_STOPS) - 1, LONG] - - Pparaformat* = ptr PARAFORMAT - PERF_COUNTER_BLOCK* {.final, pure.} = object - ByteLength*: DWORD - - PPERFCOUNTERBLOCK* = ptr PERF_COUNTER_BLOCK - PERF_COUNTER_DEFINITION* {.final, pure.} = object - ByteLength*: DWORD - CounterNameTitleIndex*: DWORD - CounterNameTitle*: LPWSTR - CounterHelpTitleIndex*: DWORD - CounterHelpTitle*: LPWSTR - DefaultScale*: DWORD - DetailLevel*: DWORD - CounterType*: DWORD - CounterSize*: DWORD - CounterOffset*: DWORD - - PPERFCOUNTERDEFINITION* = ptr PERF_COUNTER_DEFINITION - PERF_DATA_BLOCK* {.final, pure.} = object - Signature*: array[0..3, WCHAR] - LittleEndian*: DWORD - Version*: DWORD - Revision*: DWORD - TotalByteLength*: DWORD - HeaderLength*: DWORD - NumObjectTypes*: DWORD - DefaultObject*: DWORD - SystemTime*: SYSTEMTIME - PerfTime*: LARGE_INTEGER - PerfFreq*: LARGE_INTEGER - PerfTime100nSec*: LARGE_INTEGER - SystemNameLength*: DWORD - SystemNameOffset*: DWORD - - PPERFDATABLOCK* = ptr PERF_DATA_BLOCK - PERF_INSTANCE_DEFINITION* {.final, pure.} = object - ByteLength*: DWORD - ParentObjectTitleIndex*: DWORD - ParentObjectInstance*: DWORD - UniqueID*: DWORD - NameOffset*: DWORD - NameLength*: DWORD - - PPERFINSTANCEDEFINITION* = PERF_INSTANCE_DEFINITION - PERF_OBJECT_TYPE* {.final, pure.} = object - TotalByteLength*: DWORD - DefinitionLength*: DWORD - HeaderLength*: DWORD - ObjectNameTitleIndex*: DWORD - ObjectNameTitle*: LPWSTR - ObjectHelpTitleIndex*: DWORD - ObjectHelpTitle*: LPWSTR - DetailLevel*: DWORD - NumCounters*: DWORD - DefaultCounter*: DWORD - NumInstances*: DWORD - CodePage*: DWORD - PerfTime*: LARGE_INTEGER - PerfFreq*: LARGE_INTEGER - - PPERFOBJECTTYPE* = ptr PERF_OBJECT_TYPE - POLYTEXT* {.final, pure.} = object - x*: int32 - y*: int32 - n*: WINUINT - lpstr*: LPCTSTR - uiFlags*: WINUINT - rcl*: RECT - pdx*: ptr int32 - - PPOLYTEXT* = ptr POLYTEXT - PORT_INFO_1* {.final, pure.} = object - pName*: LPTSTR - - PPORTINFO1* = ptr PORT_INFO_1 - PORT_INFO_2* {.final, pure.} = object - pPortName*: LPSTR - pMonitorName*: LPSTR - pDescription*: LPSTR - fPortType*: DWORD - Reserved*: DWORD - - PPORTINFO2* = ptr PORT_INFO_2 - PREVENT_MEDIA_REMOVAL* {.final, pure.} = object - PreventMediaRemoval*: bool - - PPREVENTMEDIAREMOVAL* = ptr PREVENT_MEDIA_REMOVAL - #PRINTDLG = record conflicts with PrintDlg function - TPRINTDLG* {.final, pure.} = object - lStructSize*: DWORD - hwndOwner*: HWND - hDevMode*: HANDLE - hDevNames*: HANDLE - hDC*: HDC - Flags*: DWORD - nFromPage*: int16 - nToPage*: int16 - nMinPage*: int16 - nMaxPage*: int16 - nCopies*: int16 - hInstance*: HINST - lCustData*: DWORD - lpfnPrintHook*: LPPRINTHOOKPROC - lpfnSetupHook*: LPSETUPHOOKPROC - lpPrintTemplateName*: LPCTSTR - lpSetupTemplateName*: LPCTSTR - hPrintTemplate*: HANDLE - hSetupTemplate*: HANDLE - - LPPRINTDLG* = ptr TPRINTDLG - PPRINTDLG* = ptr TPRINTDLG - PPD* = ptr TPRINTDLG - PRINTER_DEFAULTS* {.final, pure.} = object - pDatatype*: LPTSTR - pDevMode*: LPDEVMODE - DesiredAccess*: ACCESS_MASK - - PPRINTERDEFAULTS* = ptr PRINTER_DEFAULTS - PRINTER_INFO_1* {.final, pure.} = object - Flags*: DWORD - pDescription*: LPTSTR - pName*: LPTSTR - pComment*: LPTSTR - - LPPRINTER_INFO_1* = ptr PRINTER_INFO_1 - PPRINTER_INFO_1* = ptr PRINTER_INFO_1 - PRINTER_INFO_2* {.final, pure.} = object - pServerName*: LPTSTR - pPrinterName*: LPTSTR - pShareName*: LPTSTR - pPortName*: LPTSTR - pDriverName*: LPTSTR - pComment*: LPTSTR - pLocation*: LPTSTR - pDevMode*: LPDEVMODE - pSepFile*: LPTSTR - pPrintProcessor*: LPTSTR - pDatatype*: LPTSTR - pParameters*: LPTSTR - pSecurityDescriptor*: PSECURITY_DESCRIPTOR - Attributes*: DWORD - Priority*: DWORD - DefaultPriority*: DWORD - StartTime*: DWORD - UntilTime*: DWORD - Status*: DWORD - cJobs*: DWORD - AveragePPM*: DWORD - - PPRINTERINFO2* = ptr PRINTER_INFO_2 - PRINTER_INFO_3* {.final, pure.} = object - pSecurityDescriptor*: PSECURITY_DESCRIPTOR - - PPRINTERINFO3* = ptr PRINTER_INFO_3 - PRINTER_INFO_4* {.final, pure.} = object - pPrinterName*: LPTSTR - pServerName*: LPTSTR - Attributes*: DWORD - - PPRINTERINFO4* = ptr PRINTER_INFO_4 - PRINTER_INFO_5* {.final, pure.} = object - pPrinterName*: LPTSTR - pPortName*: LPTSTR - Attributes*: DWORD - DeviceNotSelectedTimeout*: DWORD - TransmissionRetryTimeout*: DWORD - - PPRINTERINFO5* = ptr PRINTER_INFO_5 - PRINTER_NOTIFY_INFO_DATA* {.final, pure.} = object - `type`*: int16 - Field*: int16 - Reserved*: DWORD - Id*: DWORD - cbBuf*: DWORD - pBuf*: LPVOID - - PPRINTERNOTIFYINFODATA* = ptr PRINTER_NOTIFY_INFO_DATA - PRINTER_NOTIFY_INFO* {.final, pure.} = object - Version*: DWORD - Flags*: DWORD - Count*: DWORD - aData*: array[0..0, PRINTER_NOTIFY_INFO_DATA] - - PPRINTERNOTIFYINFO* = ptr PRINTER_NOTIFY_INFO - PRINTER_NOTIFY_OPTIONS_TYPE* {.final, pure.} = object - `type`*: int16 - Reserved0*: int16 - Reserved1*: DWORD - Reserved2*: DWORD - Count*: DWORD - pFields*: PWORD - - PPRINTER_NOTIFY_OPTIONS_TYPE* = ptr PRINTER_NOTIFY_OPTIONS_TYPE - PRINTER_NOTIFY_OPTIONS* {.final, pure.} = object - Version*: DWORD - Flags*: DWORD - Count*: DWORD - pTypes*: PPRINTER_NOTIFY_OPTIONS_TYPE - - PPRINTERNOTIFYOPTIONS* = ptr PRINTER_NOTIFY_OPTIONS - PRINTPROCESSOR_INFO_1* {.final, pure.} = object - pName*: LPTSTR - - PPRINTPROCESSORINFO1* = ptr PRINTPROCESSOR_INFO_1 - PRIVILEGE_SET* {.final, pure.} = object - PrivilegeCount*: DWORD - Control*: DWORD - Privilege*: array[0..(ANYSIZE_ARRAY) - 1, LUID_AND_ATTRIBUTES] - - LPPRIVILEGE_SET* = ptr PRIVILEGE_SET - PPRIVILEGE_SET* = ptr PRIVILEGE_SET - PROCESS_HEAPENTRY* {.final, pure.} = object - lpData*: PVOID - cbData*: DWORD - cbOverhead*: int8 - iRegionIndex*: int8 - wFlags*: int16 - dwCommittedSize*: DWORD - dwUnCommittedSize*: DWORD - lpFirstBlock*: LPVOID - lpLastBlock*: LPVOID - hMem*: HANDLE - - LPPROCESS_HEAP_ENTRY* = ptr PROCESS_HEAPENTRY - PPROCESSHEAPENTRY* = ptr PROCESS_HEAPENTRY - PROCESS_INFORMATION* {.final, pure.} = object - hProcess*: HANDLE - hThread*: HANDLE - dwProcessId*: DWORD - dwThreadId*: DWORD - - LPPROCESS_INFORMATION* = ptr PROCESS_INFORMATION - PPROCESSINFORMATION* = ptr PROCESS_INFORMATION - LPFNPSPCALLBACK* = proc (para1: HWND, para2: WINUINT, para3: LPVOID): WINUINT{. - stdcall.} - PROPSHEETPAGE* {.final, pure.} = object - dwSize*: DWORD - dwFlags*: DWORD - hInstance*: HINST - pszIcon*: LPCTSTR - pszTitle*: LPCTSTR - pfnDlgProc*: DLGPROC - lParam*: LPARAM - pfnCallback*: LPFNPSPCALLBACK - pcRefParent*: ptr WINUINT - - LPPROPSHEETPAGE* = ptr PROPSHEETPAGE - LPCPROPSHEETPAGE* = ptr PROPSHEETPAGE - PPROPSHEETPAGE* = ptr PROPSHEETPAGE - emptyrecord* {.final, pure.} = object - lpemptyrecord* = ptr emptyrecord - HPROPSHEETPAGE* = ptr emptyrecord - PROPSHEETHEADER* {.final, pure.} = object - dwSize*: DWORD - dwFlags*: DWORD - hwndParent*: HWND - hInstance*: HINST - pszIcon*: LPCTSTR - pszCaption*: LPCTSTR - nPages*: WINUINT - pStartPage*: LPCTSTR - phpage*: ptr HPROPSHEETPAGE - pfnCallback*: PFNPROPSHEETCALLBACK - pszbmWatermark*: LPCTSTR - hplWatermark*: HPALETTE - pszbmHeader*: cstring - - LPPROPSHEETHEADER* = ptr PROPSHEETHEADER - LPCPROPSHEETHEADER* = ptr PROPSHEETHEADER - PPROPSHEETHEADER* = ptr PROPSHEETHEADER - # PropertySheet callbacks - LPFNADDPROPSHEETPAGE* = proc (para1: HPROPSHEETPAGE, para2: LPARAM): WINBOOL{. - stdcall.} - LPFNADDPROPSHEETPAGES* = proc (para1: LPVOID, para2: LPFNADDPROPSHEETPAGE, - para3: LPARAM): WINBOOL{.stdcall.} - PROTOCOL_INFO* {.final, pure.} = object - dwServiceFlags*: DWORD - iAddressFamily*: WINT - iMaxSockAddr*: WINT - iMinSockAddr*: WINT - iSocketType*: WINT - iProtocol*: WINT - dwMessageSize*: DWORD - lpProtocol*: LPTSTR - - PPROTOCOLINFO* = ptr PROTOCOL_INFO - PROVIDOR_INFO_1* {.final, pure.} = object - pName*: LPTSTR - pEnvironment*: LPTSTR - pDLLName*: LPTSTR - - PPROVIDORINFO1* = ptr PROVIDOR_INFO_1 - PSHNOTIFY* {.final, pure.} = object - hdr*: NMHDR - lParam*: LPARAM - - LPPSHNOTIFY* = ptr PSHNOTIFY - PPSHNOTIFY* = ptr PSHNOTIFY - PUNCTUATION* {.final, pure.} = object - iSize*: WINUINT - szPunctuation*: LPSTR - - Ppunctuation* = ptr PUNCTUATION - TQUERY_SERVICE_CONFIG* {.final, pure.} = object # Name conflict if we drop the `T` - dwServiceType*: DWORD - dwStartType*: DWORD - dwErrorControl*: DWORD - lpBinaryPathName*: LPTSTR - lpLoadOrderGroup*: LPTSTR - dwTagId*: DWORD - lpDependencies*: LPTSTR - lpServiceStartName*: LPTSTR - lpDisplayName*: LPTSTR - - LPQUERY_SERVICE_CONFIG* = ptr TQUERY_SERVICE_CONFIG - PQUERYSERVICECONFIG* = ptr TQUERY_SERVICE_CONFIG - TQUERY_SERVICE_LOCK_STATUS* {.final, pure.} = object # Name conflict if we drop the `T` - fIsLocked*: DWORD - lpLockOwner*: LPTSTR - dwLockDuration*: DWORD - - LPQUERY_SERVICE_LOCK_STATUS* = ptr TQUERY_SERVICE_LOCK_STATUS - PQUERYSERVICELOCKSTATUS* = ptr TQUERY_SERVICE_LOCK_STATUS - RASAMB* {.final, pure.} = object - dwSize*: DWORD - dwError*: DWORD - szNetBiosError*: array[0..(NETBIOS_NAME_LEN + 1) - 1, CHAR] - bLana*: int8 - - PRASAMB* = ptr RASAMB - RASCONN* {.final, pure.} = object - dwSize*: DWORD - hrasconn*: HRASCONN - szEntryName*: array[0..(RAS_MaxEntryName + 1) - 1, CHAR] - szDeviceType*: array[0..(RAS_MaxDeviceType + 1) - 1, char] - szDeviceName*: array[0..(RAS_MaxDeviceName + 1) - 1, char] - - PRASCONN* = ptr RASCONN - RASCONNSTATUS* {.final, pure.} = object - dwSize*: DWORD - rasconnstate*: RASCONNSTATE - dwError*: DWORD - szDeviceType*: array[0..(RAS_MaxDeviceType + 1) - 1, CHAR] - szDeviceName*: array[0..(RAS_MaxDeviceName + 1) - 1, CHAR] - - PRASCONNSTATUS* = ptr RASCONNSTATUS - RASDIALEXTENSIONS* {.final, pure.} = object - dwSize*: DWORD - dwfOptions*: DWORD - hwndParent*: HWND - reserved*: DWORD - - PRASDIALEXTENSIONS* = ptr RASDIALEXTENSIONS - RASDIALPARAMS* {.final, pure.} = object - dwSize*: DWORD - szEntryName*: array[0..(RAS_MaxEntryName + 1) - 1, CHAR] - szPhoneNumber*: array[0..(RAS_MaxPhoneNumber + 1) - 1, CHAR] - szCallbackNumber*: array[0..(RAS_MaxCallbackNumber + 1) - 1, CHAR] - szUserName*: array[0..(UNLEN + 1) - 1, CHAR] - szPassword*: array[0..(PWLEN + 1) - 1, CHAR] - szDomain*: array[0..(DNLEN + 1) - 1, CHAR] - - PRASDIALPARAMS* = ptr RASDIALPARAMS - RASENTRYNAME* {.final, pure.} = object - dwSize*: DWORD - szEntryName*: array[0..(RAS_MaxEntryName + 1) - 1, CHAR] - - PRASENTRYNAME* = ptr RASENTRYNAME - RASPPPIP* {.final, pure.} = object - dwSize*: DWORD - dwError*: DWORD - szIpAddress*: array[0..(RAS_MaxIpAddress + 1) - 1, CHAR] - - PRASPPPIP* = ptr RASPPPIP - RASPPPIPX* {.final, pure.} = object - dwSize*: DWORD - dwError*: DWORD - szIpxAddress*: array[0..(RAS_MaxIpxAddress + 1) - 1, CHAR] - - PRASPPPIPX* = ptr RASPPPIPX - RASPPPNBF* {.final, pure.} = object - dwSize*: DWORD - dwError*: DWORD - dwNetBiosError*: DWORD - szNetBiosError*: array[0..(NETBIOS_NAME_LEN + 1) - 1, CHAR] - szWorkstationName*: array[0..(NETBIOS_NAME_LEN + 1) - 1, CHAR] - bLana*: int8 - - PRASPPPNBF* = ptr RASPPPNBF - RASTERIZER_STATUS* {.final, pure.} = object - nSize*: SHORT - wFlags*: SHORT - nLanguageID*: SHORT - - LPRASTERIZER_STATUS* = ptr RASTERIZER_STATUS - PRASTERIZERSTATUS* = ptr RASTERIZER_STATUS - REASSIGN_BLOCKS* {.final, pure.} = object - Reserved*: int16 - Count*: int16 - BlockNumber*: array[0..0, DWORD] - - PREASSIGNBLOCKS* = ptr REASSIGN_BLOCKS - REMOTE_NAME_INFO* {.final, pure.} = object - lpUniversalName*: LPTSTR - lpConnectionName*: LPTSTR - lpRemainingPath*: LPTSTR - - PREMOTENAMEINFO* = ptr REMOTE_NAME_INFO - - REPASTESPECIAL* {.final, pure.} = object - dwAspect*: DWORD - dwParam*: DWORD - - Prepastespecial* = ptr REPASTESPECIAL - REQRESIZE* {.final, pure.} = object - nmhdr*: NMHDR - rc*: RECT - - Preqresize* = ptr REQRESIZE - RGNDATAHEADER* {.final, pure.} = object - dwSize*: DWORD - iType*: DWORD - nCount*: DWORD - nRgnSize*: DWORD - rcBound*: RECT - - PRGNDATAHEADER* = ptr RGNDATAHEADER - RGNDATA* {.final, pure.} = object - rdh*: RGNDATAHEADER - Buffer*: array[0..0, char] - - LPRGNDATA* = ptr RGNDATA - PRGNDATA* = ptr RGNDATA - SCROLLINFO* {.final, pure.} = object - cbSize*: WINUINT - fMask*: WINUINT - nMin*: int32 - nMax*: int32 - nPage*: WINUINT - nPos*: int32 - nTrackPos*: int32 - - LPSCROLLINFO* = ptr SCROLLINFO - LPCSCROLLINFO* = ptr SCROLLINFO - PSCROLLINFO* = ptr SCROLLINFO - SECURITY_ATTRIBUTES* {.final, pure.} = object - nLength*: DWORD - lpSecurityDescriptor*: LPVOID - bInheritHandle*: WINBOOL - - LPSECURITY_ATTRIBUTES* = ptr SECURITY_ATTRIBUTES - PSECURITYATTRIBUTES* = ptr SECURITY_ATTRIBUTES - SECURITY_INFORMATION* = DWORD - PSECURITY_INFORMATION* = ptr SECURITY_INFORMATION - SELCHANGE* {.final, pure.} = object - nmhdr*: NMHDR - chrg*: CHARRANGE - seltyp*: int16 - - Pselchange* = ptr SELCHANGE - SERIALKEYS* {.final, pure.} = object - cbSize*: DWORD - dwFlags*: DWORD - lpszActivePort*: LPSTR - lpszPort*: LPSTR - iBaudRate*: DWORD - iPortState*: DWORD - - LPSERIALKEYS* = ptr SERIALKEYS - PSERIALKEYS* = ptr SERIALKEYS - SERVICE_TABLE_ENTRY* {.final, pure.} = object - lpServiceName*: LPTSTR - lpServiceProc*: LPSERVICE_MAIN_FUNCTION - - LPSERVICE_TABLE_ENTRY* = ptr SERVICE_TABLE_ENTRY - PSERVICETABLEENTRY* = ptr SERVICE_TABLE_ENTRY - SERVICE_TYPE_VALUE_ABS* {.final, pure.} = object - dwNameSpace*: DWORD - dwValueType*: DWORD - dwValueSize*: DWORD - lpValueName*: LPTSTR - lpValue*: PVOID - - PSERVICETYPEVALUEABS* = ptr SERVICE_TYPE_VALUE_ABS - SERVICE_TYPE_INFO_ABS* {.final, pure.} = object - lpTypeName*: LPTSTR - dwValueCount*: DWORD - Values*: array[0..0, SERVICE_TYPE_VALUE_ABS] - - PSERVICETYPEINFOABS* = ptr SERVICE_TYPE_INFO_ABS - SESSION_BUFFER* {.final, pure.} = object - lsn*: UCHAR - state*: UCHAR - local_name*: array[0..(NCBNAMSZ) - 1, UCHAR] - remote_name*: array[0..(NCBNAMSZ) - 1, UCHAR] - rcvs_outstanding*: UCHAR - sends_outstanding*: UCHAR - - PSESSIONBUFFER* = ptr SESSION_BUFFER - SESSION_HEADER* {.final, pure.} = object - sess_name*: UCHAR - num_sess*: UCHAR - rcv_dg_outstanding*: UCHAR - rcv_any_outstanding*: UCHAR - - PSESSIONHEADER* = ptr SESSION_HEADER - SET_PARTITION_INFORMATION* {.final, pure.} = object - PartitionType*: int8 - - PSETPARTITIONINFORMATION* = ptr SET_PARTITION_INFORMATION - SHCONTF* = enum - SHCONTF_FOLDERS = 32, SHCONTF_NONFOLDERS = 64, SHCONTF_INCLUDEHIDDEN = 128 - SHFILEINFO* {.final, pure.} = object - hIcon*: HICON - iIcon*: int32 - dwAttributes*: DWORD - szDisplayName*: array[0..(MAX_PATH) - 1, char] - szTypeName*: array[0..79, char] - - PSHFILEINFO* = ptr SHFILEINFO - FILEOP_FLAGS* = int16 - PFILEOPFLAGS* = ptr FILEOP_FLAGS - SHFILEOPSTRUCT* {.final, pure.} = object - hwnd*: HWND - wFunc*: WINUINT - pFrom*: LPCSTR - pTo*: LPCSTR - fFlags*: FILEOP_FLAGS - fAnyOperationsAborted*: WINBOOL - hNameMappings*: LPVOID - lpszProgressTitle*: LPCSTR - - LPSHFILEOPSTRUCT* = ptr SHFILEOPSTRUCT - PSHFILEOPSTRUCT* = ptr SHFILEOPSTRUCT - SHGNO* = enum - SHGDN_NORMAL = 0, SHGDN_INFOLDER = 1, SHGDN_FORPARSING = 0x00008000 - SHNAMEMAPPING* {.final, pure.} = object - pszOldPath*: LPSTR - pszNewPath*: LPSTR - cchOldPath*: int32 - cchNewPath*: int32 - - LPSHNAMEMAPPING* = ptr SHNAMEMAPPING - PSHNAMEMAPPING* = ptr SHNAMEMAPPING - SID_AND_ATTRIBUTES* {.final, pure.} = object - Sid*: PSID - Attributes*: DWORD - - PSIDANDATTRIBUTES* = ptr SID_AND_ATTRIBUTES - SID_AND_ATTRIBUTES_ARRAY* = array[0..(ANYSIZE_ARRAY) - 1, SID_AND_ATTRIBUTES] - PSID_AND_ATTRIBUTES_ARRAY* = ptr SID_AND_ATTRIBUTES_ARRAY - SINGLE_LIST_ENTRY* {.final, pure.} = object - Next*: ptr SINGLE_LIST_ENTRY - - PSINGLELISTENTRY* = ptr SINGLE_LIST_ENTRY - SOUNDSENTRY* {.final, pure.} = object - cbSize*: WINUINT - dwFlags*: DWORD - iFSTextEffect*: DWORD - iFSTextEffectMSec*: DWORD - iFSTextEffectColorBits*: DWORD - iFSGrafEffect*: DWORD - iFSGrafEffectMSec*: DWORD - iFSGrafEffectColor*: DWORD - iWindowsEffect*: DWORD - iWindowsEffectMSec*: DWORD - lpszWindowsEffectDLL*: LPTSTR - iWindowsEffectOrdinal*: DWORD - - LPSOUNDSENTRY* = ptr SOUNDSENTRY - PSOUNDSENTRY* = ptr SOUNDSENTRY - STARTUPINFO* {.final, pure.} = object - cb*: DWORD - lpReserved*: LPTSTR - lpDesktop*: LPTSTR - lpTitle*: LPTSTR - dwX*: DWORD - dwY*: DWORD - dwXSize*: DWORD - dwYSize*: DWORD - dwXCountChars*: DWORD - dwYCountChars*: DWORD - dwFillAttribute*: DWORD - dwFlags*: DWORD - wShowWindow*: int16 - cbReserved2*: int16 - lpReserved2*: LPBYTE - hStdInput*: HANDLE - hStdOutput*: HANDLE - hStdError*: HANDLE - - LPSTARTUPINFO* = ptr STARTUPINFO - PSTARTUPINFO* = ptr STARTUPINFO - STICKYKEYS* {.final, pure.} = object - cbSize*: DWORD - dwFlags*: DWORD - - LPSTICKYKEYS* = ptr STICKYKEYS - PSTICKYKEYS* = ptr STICKYKEYS - STRRET* {.final, pure.} = object - uType*: WINUINT - cStr*: array[0..(MAX_PATH) - 1, char] - - LPSTRRET* = ptr STRRET - PSTRRET* = ptr STRRET - STYLEBUF* {.final, pure.} = object - dwStyle*: DWORD - szDescription*: array[0..31, char] - - LPSTYLEBUF* = ptr STYLEBUF - PSTYLEBUF* = ptr STYLEBUF - STYLESTRUCT* {.final, pure.} = object - styleOld*: DWORD - styleNew*: DWORD - - LPSTYLESTRUCT* = ptr STYLESTRUCT - PSTYLESTRUCT* = ptr STYLESTRUCT - SYSTEM_AUDIT_ACE* {.final, pure.} = object - Header*: ACE_HEADER - Mask*: ACCESS_MASK - SidStart*: DWORD - - PSYSTEMAUDITACE* = ptr SYSTEM_AUDIT_ACE - SYSTEM_INFO* {.final, pure.} = object - dwOemId*: DWORD - dwPageSize*: DWORD - lpMinimumApplicationAddress*: LPVOID - lpMaximumApplicationAddress*: LPVOID - dwActiveProcessorMask*: DWORD_PTR - dwNumberOfProcessors*: DWORD - dwProcessorType*: DWORD - dwAllocationGranularity*: DWORD - wProcessorLevel*: int16 - wProcessorRevision*: int16 - - LPSYSTEM_INFO* = ptr SYSTEM_INFO - PSYSTEMINFO* = ptr SYSTEM_INFO - SYSTEM_POWER_STATUS* {.final, pure.} = object - ACLineStatus*: int8 - BatteryFlag*: int8 - BatteryLifePercent*: int8 - Reserved1*: int8 - BatteryLifeTime*: DWORD - BatteryFullLifeTime*: DWORD - - PSYSTEMPOWERSTATUS* = ptr SYSTEM_POWER_STATUS - LPSYSTEM_POWER_STATUS* = ptr emptyrecord - TAPE_ERASE* {.final, pure.} = object - `type`*: ULONG - - PTAPEERASE* = ptr TAPE_ERASE - TAPE_GET_DRIVE_PARAMETERS* {.final, pure.} = object - ECC*: bool - Compression*: bool - DataPadding*: bool - ReportSetmarks*: bool - DefaultBlockSize*: ULONG - MaximumBlockSize*: ULONG - MinimumBlockSize*: ULONG - MaximumPartitionCount*: ULONG - FeaturesLow*: ULONG - FeaturesHigh*: ULONG - EOTWarningZoneSize*: ULONG - - PTAPEGETDRIVEPARAMETERS* = ptr TAPE_GET_DRIVE_PARAMETERS - TAPE_GET_MEDIA_PARAMETERS* {.final, pure.} = object - Capacity*: LARGE_INTEGER - Remaining*: LARGE_INTEGER - BlockSize*: DWORD - PartitionCount*: DWORD - WriteProtected*: bool - - PTAPEGETMEDIAPARAMETERS* = ptr TAPE_GET_MEDIA_PARAMETERS - TAPE_GET_POSITION* {.final, pure.} = object - `type`*: ULONG - Partition*: ULONG - OffsetLow*: ULONG - OffsetHigh*: ULONG - - PTAPEGETPOSITION* = ptr TAPE_GET_POSITION - TAPE_PREPARE* {.final, pure.} = object - Operation*: ULONG - - PTAPEPREPARE* = ptr TAPE_PREPARE - TAPE_SET_DRIVE_PARAMETERS* {.final, pure.} = object - ECC*: bool - Compression*: bool - DataPadding*: bool - ReportSetmarks*: bool - EOTWarningZoneSize*: ULONG - - PTAPESETDRIVEPARAMETERS* = ptr TAPE_SET_DRIVE_PARAMETERS - TAPE_SET_MEDIA_PARAMETERS* {.final, pure.} = object - BlockSize*: ULONG - - PTAPESETMEDIAPARAMETERS* = ptr TAPE_SET_MEDIA_PARAMETERS - TAPE_SET_POSITION* {.final, pure.} = object - `Method`*: ULONG - Partition*: ULONG - OffsetLow*: ULONG - OffsetHigh*: ULONG - - PTAPESETPOSITION* = ptr TAPE_SET_POSITION - TAPE_WRITE_MARKS* {.final, pure.} = object - `type`*: ULONG - Count*: ULONG - - PTAPEWRITEMARKS* = ptr TAPE_WRITE_MARKS - TTBADDBITMAP* {.final, pure.} = object # Name conflict if we drop the `T` - hInst*: HINST - nID*: WINUINT - - LPTBADDBITMAP* = ptr TTBADDBITMAP - PTBADDBITMAP* = ptr TTBADDBITMAP - TBBUTTON* {.final, pure.} = object - iBitmap*: int32 - idCommand*: int32 - fsState*: int8 - fsStyle*: int8 - dwData*: DWORD - iString*: int32 - - LPTBBUTTON* = ptr TBBUTTON - LPCTBBUTTON* = ptr TBBUTTON - PTBBUTTON* = ptr TBBUTTON - TBNOTIFY* {.final, pure.} = object - hdr*: NMHDR - iItem*: int32 - tbButton*: TBBUTTON - cchText*: int32 - pszText*: LPTSTR - - LPTBNOTIFY* = ptr TBNOTIFY - PTBNOTIFY* = ptr TBNOTIFY - TBSAVEPARAMS* {.final, pure.} = object - hkr*: HKEY - pszSubKey*: LPCTSTR - pszValueName*: LPCTSTR - - PTBSAVEPARAMS* = ptr TBSAVEPARAMS - TC_HITTESTINFO* {.final, pure.} = object - pt*: POINT - flags*: WINUINT - - PTCHITTESTINFO* = ptr TC_HITTESTINFO - TC_ITEM* {.final, pure.} = object - mask*: WINUINT - lpReserved1*: WINUINT - lpReserved2*: WINUINT - pszText*: LPTSTR - cchTextMax*: int32 - iImage*: int32 - lParam*: LPARAM - - PTCITEM* = ptr TC_ITEM - TC_ITEMHEADER* {.final, pure.} = object - mask*: WINUINT - lpReserved1*: WINUINT - lpReserved2*: WINUINT - pszText*: LPTSTR - cchTextMax*: int32 - iImage*: int32 - - PTCITEMHEADER* = ptr TC_ITEMHEADER - TC_KEYDOWN* {.final, pure.} = object - hdr*: NMHDR - wVKey*: int16 - flags*: WINUINT - - PTCKEYDOWN* = ptr TC_KEYDOWN - TEXTRANGE* {.final, pure.} = object - chrg*: CHARRANGE - lpstrText*: LPSTR - - Ptextrange* = ptr TEXTRANGE - TIME_ZONE_INFORMATION* {.final, pure.} = object - Bias*: LONG - StandardName*: array[0..31, WCHAR] - StandardDate*: SYSTEMTIME - StandardBias*: LONG - DaylightName*: array[0..31, WCHAR] - DaylightDate*: SYSTEMTIME - DaylightBias*: LONG - - LPTIME_ZONE_INFORMATION* = ptr TIME_ZONE_INFORMATION - PTIMEZONEINFORMATION* = ptr TIME_ZONE_INFORMATION - TOGGLEKEYS* {.final, pure.} = object - cbSize*: DWORD - dwFlags*: DWORD - - PTOGGLEKEYS* = ptr TOGGLEKEYS - TTOKEN_SOURCE* {.final, pure.} = object # Name confict if we drop the `T` - SourceName*: array[0..7, char] - SourceIdentifier*: LUID - - PTOKENSOURCE* = ptr TTOKEN_SOURCE - TOKEN_CONTROL* {.final, pure.} = object - TokenId*: LUID - AuthenticationId*: LUID - ModifiedId*: LUID - TokenSource*: TTOKEN_SOURCE - - PTOKENCONTROL* = ptr TOKEN_CONTROL - TTOKEN_DEFAULT_DACL* {.final, pure.} = object - DefaultDacl*: PACL - - PTOKENDEFAULTDACL* = ptr TTOKEN_DEFAULT_DACL # Name conflict if we drop the `T` - TTOKEN_GROUPS* {.final, pure.} = object # Name conflict if we drop the `T` - GroupCount*: DWORD - Groups*: array[0..(ANYSIZE_ARRAY) - 1, SID_AND_ATTRIBUTES] - - LPTOKEN_GROUPS* = ptr TTOKEN_GROUPS - PTOKENGROUPS* = ptr TTOKEN_GROUPS - TTOKEN_OWNER* {.final, pure.} = object # Name conflict if we drop the `T` - Owner*: PSID - - PTOKENOWNER* = ptr TTOKEN_OWNER - TTOKEN_PRIMARY_GROUP* {.final, pure.} = object - PrimaryGroup*: PSID - - PTOKENPRIMARYGROUP* = ptr TTOKEN_PRIMARY_GROUP # Name conflict if we drop the `T` - TTOKEN_PRIVILEGES* {.final, pure.} = object # Name conflict if we drop the `T` - PrivilegeCount*: DWORD - Privileges*: array[0..(ANYSIZE_ARRAY) - 1, LUID_AND_ATTRIBUTES] - - PTOKEN_PRIVILEGES* = ptr TTOKEN_PRIVILEGES - LPTOKEN_PRIVILEGES* = ptr TTOKEN_PRIVILEGES - TTOKEN_STATISTICS* {.final, pure.} = object # Name conflict if we drop the `T` - TokenId*: LUID - AuthenticationId*: LUID - ExpirationTime*: LARGE_INTEGER - TokenType*: TTOKEN_TYPE - ImpersonationLevel*: SECURITY_IMPERSONATION_LEVEL - DynamicCharged*: DWORD - DynamicAvailable*: DWORD - GroupCount*: DWORD - PrivilegeCount*: DWORD - ModifiedId*: LUID - - PTOKENSTATISTICS* = ptr TTOKEN_STATISTICS - TTOKEN_USER* {.final, pure.} = object # Name conflict if we drop the `T` - User*: SID_AND_ATTRIBUTES - - PTOKENUSER* = ptr TTOKEN_USER - TOOLINFO* {.final, pure.} = object - cbSize*: WINUINT - uFlags*: WINUINT - hwnd*: HWND - uId*: WINUINT - rect*: RECT - hinst*: HINST - lpszText*: LPTSTR - - LPTOOLINFO* = ptr TOOLINFO - PTOOLINFO* = ptr TOOLINFO - TOOLTIPTEXT* {.final, pure.} = object - hdr*: NMHDR - lpszText*: LPTSTR - szText*: array[0..79, char] - hinst*: HINST - uFlags*: WINUINT - - LPTOOLTIPTEXT* = ptr TOOLTIPTEXT - PTOOLTIPTEXT* = ptr TOOLTIPTEXT - TPMPARAMS* {.final, pure.} = object - cbSize*: WINUINT - rcExclude*: RECT - - LPTPMPARAMS* = ptr TPMPARAMS - PTPMPARAMS* = ptr TPMPARAMS - TRANSMIT_FILE_BUFFERS* {.final, pure.} = object - Head*: PVOID - HeadLength*: DWORD - Tail*: PVOID - TailLength*: DWORD - - PTRANSMITFILEBUFFERS* = ptr TRANSMIT_FILE_BUFFERS - TTHITTESTINFO* {.final, pure.} = object - hwnd*: HWND - pt*: POINT - ti*: TOOLINFO - - LPHITTESTINFO* = ptr TTHITTESTINFO - PTTHITTESTINFO* = ptr TTHITTESTINFO - TTPOLYCURVE* {.final, pure.} = object - wType*: int16 - cpfx*: int16 - apfx*: array[0..0, POINTFX] - - LPTTPOLYCURVE* = ptr TTPOLYCURVE - PTTPOLYCURVE* = ptr TTPOLYCURVE - TTPOLYGONHEADER* {.final, pure.} = object - cb*: DWORD - dwType*: DWORD - pfxStart*: POINTFX - - LPTTPOLYGONHEADER* = ptr TTPOLYGONHEADER - PTTPOLYGONHEADER* = ptr TTPOLYGONHEADER - TV_DISPINFO* {.final, pure.} = object - hdr*: NMHDR - item*: TV_ITEM - - PTVDISPINFO* = ptr TV_DISPINFO - TV_HITTESTINFO* {.final, pure.} = object - pt*: POINT - flags*: WINUINT - hItem*: HTREEITEM - - LPTV_HITTESTINFO* = ptr TV_HITTESTINFO - PTVHITTESTINFO* = ptr TV_HITTESTINFO - TV_INSERTSTRUCT* {.final, pure.} = object - hParent*: HTREEITEM - hInsertAfter*: HTREEITEM - item*: TV_ITEM - - LPTV_INSERTSTRUCT* = ptr TV_INSERTSTRUCT - PTVINSERTSTRUCT* = ptr TV_INSERTSTRUCT - TV_KEYDOWN* {.final, pure.} = object - hdr*: NMHDR - wVKey*: int16 - flags*: WINUINT - - PTVKEYDOWN* = ptr TV_KEYDOWN - TV_SORTCB* {.final, pure.} = object - hParent*: HTREEITEM - lpfnCompare*: PFNTVCOMPARE - lParam*: LPARAM - - LPTV_SORTCB* = ptr TV_SORTCB - PTVSORTCB* = ptr TV_SORTCB - UDACCEL* {.final, pure.} = object - nSec*: WINUINT - nInc*: WINUINT - - PUDACCEL* = ptr UDACCEL - UNIVERSAL_NAME_INFO* {.final, pure.} = object - lpUniversalName*: LPTSTR - - PUNIVERSALNAMEINFO* = ptr UNIVERSAL_NAME_INFO - USEROBJECTFLAGS* {.final, pure.} = object - fInherit*: WINBOOL - fReserved*: WINBOOL - dwFlags*: DWORD - - PUSEROBJECTFLAGS* = ptr USEROBJECTFLAGS - VALENT* {.final, pure.} = object - ve_valuename*: LPTSTR - ve_valuelen*: DWORD - ve_valueptr*: DWORD - ve_type*: DWORD - - PVALENT* = ptr VALENT - value_ent* = VALENT - Pvalue_ent* = ptr VALENT - VERIFY_INFORMATION* {.final, pure.} = object - StartingOffset*: LARGE_INTEGER - len*: DWORD - - PVERIFYINFORMATION* = ptr VERIFY_INFORMATION - VS_FIXEDFILEINFO* {.final, pure.} = object - dwSignature*: DWORD - dwStrucVersion*: DWORD - dwFileVersionMS*: DWORD - dwFileVersionLS*: DWORD - dwProductVersionMS*: DWORD - dwProductVersionLS*: DWORD - dwFileFlagsMask*: DWORD - dwFileFlags*: DWORD - dwFileOS*: DWORD - dwFileType*: DWORD - dwFileSubtype*: DWORD - dwFileDateMS*: DWORD - dwFileDateLS*: DWORD - - PVSFIXEDFILEINFO* = ptr VS_FIXEDFILEINFO - WIN32_FIND_DATA* {.final, pure.} = object - dwFileAttributes*: DWORD - ftCreationTime*: FILETIME - ftLastAccessTime*: FILETIME - ftLastWriteTime*: FILETIME - nFileSizeHigh*: DWORD - nFileSizeLow*: DWORD - dwReserved0*: DWORD - dwReserved1*: DWORD - cFileName*: array[0..(MAX_PATH) - 1, CHAR] - cAlternateFileName*: array[0..13, CHAR] - - LPWIN32_FIND_DATA* = ptr WIN32_FIND_DATA - PWIN32_FIND_DATA* = ptr WIN32_FIND_DATA - WIN32_FIND_DATAW* {.final, pure.} = object - dwFileAttributes*: DWORD - ftCreationTime*: FILETIME - ftLastAccessTime*: FILETIME - ftLastWriteTime*: FILETIME - nFileSizeHigh*: DWORD - nFileSizeLow*: DWORD - dwReserved0*: DWORD - dwReserved1*: DWORD - cFileName*: array[0..(MAX_PATH) - 1, WCHAR] - cAlternateFileName*: array[0..13, WCHAR] - - LPWIN32_FIND_DATAW* = ptr WIN32_FIND_DATAW - PWIN32_FIND_DATAW* = ptr WIN32_FIND_DATAW - WIN32_STREAM_ID* {.final, pure.} = object - dwStreamId*: DWORD - dwStreamAttributes*: DWORD - Size*: LARGE_INTEGER - dwStreamNameSize*: DWORD - cStreamName*: ptr WCHAR - - PWIN32STREAMID* = ptr WIN32_STREAM_ID - WINDOWPLACEMENT* {.final, pure.} = object - len*: WINUINT - flags*: WINUINT - showCmd*: WINUINT - ptMinPosition*: POINT - ptMaxPosition*: POINT - rcNormalPosition*: RECT - - PWINDOWPLACEMENT* = ptr WINDOWPLACEMENT - WNDCLASS* {.final, pure.} = object - style*: WINUINT - lpfnWndProc*: WNDPROC - cbClsExtra*: int32 - cbWndExtra*: int32 - hInstance*: HANDLE - hIcon*: HICON - hCursor*: HCURSOR - hbrBackground*: HBRUSH - lpszMenuName*: LPCTSTR - lpszClassName*: LPCTSTR - - LPWNDCLASS* = ptr WNDCLASS - PWNDCLASS* = ptr WNDCLASS - WNDCLASSW* {.final, pure.} = object - style*: WINUINT - lpfnWndProc*: WNDPROC - cbClsExtra*: int32 - cbWndExtra*: int32 - hInstance*: HANDLE - hIcon*: HICON - hCursor*: HCURSOR - hbrBackground*: HBRUSH - lpszMenuName*: LPCWSTR - lpszClassName*: LPCWSTR - - LPWNDCLASSW* = ptr WNDCLASSW - PWNDCLASSW* = ptr WNDCLASSW - WNDCLASSEX* {.final, pure.} = object - cbSize*: WINUINT - style*: WINUINT - lpfnWndProc*: WNDPROC - cbClsExtra*: int32 - cbWndExtra*: int32 - hInstance*: HANDLE - hIcon*: HICON - hCursor*: HCURSOR - hbrBackground*: HBRUSH - lpszMenuName*: LPCTSTR - lpszClassName*: LPCTSTR - hIconSm*: HANDLE - - LPWNDCLASSEX* = ptr WNDCLASSEX - PWNDCLASSEX* = ptr WNDCLASSEX - WNDCLASSEXW* {.final, pure.} = object - cbSize*: WINUINT - style*: WINUINT - lpfnWndProc*: WNDPROC - cbClsExtra*: int32 - cbWndExtra*: int32 - hInstance*: HANDLE - hIcon*: HICON - hCursor*: HCURSOR - hbrBackground*: HBRUSH - lpszMenuName*: LPCWSTR - lpszClassName*: LPCWSTR - hIconSm*: HANDLE - - LPWNDCLASSEXW* = ptr WNDCLASSEXW - PWNDCLASSEXW* = ptr WNDCLASSEXW - CONNECTDLGSTRUCT* {.final, pure.} = object - cbStructure*: DWORD - hwndOwner*: HWND - lpConnRes*: LPNETRESOURCE - dwFlags*: DWORD - dwDevNum*: DWORD - - LPCONNECTDLGSTRUCT* = ptr CONNECTDLGSTRUCT - PCONNECTDLGSTRUCT* = ptr CONNECTDLGSTRUCT - DISCDLGSTRUCT* {.final, pure.} = object - cbStructure*: DWORD - hwndOwner*: HWND - lpLocalName*: LPTSTR - lpRemoteName*: LPTSTR - dwFlags*: DWORD - - LPDISCDLGSTRUCT* = ptr DISCDLGSTRUCT - PDISCDLGSTRUCT* = ptr DISCDLGSTRUCT - NETINFOSTRUCT* {.final, pure.} = object - cbStructure*: DWORD - dwProviderVersion*: DWORD - dwStatus*: DWORD - dwCharacteristics*: DWORD - dwHandle*: DWORD - wNetType*: int16 - dwPrinters*: DWORD - dwDrives*: DWORD - - LPNETINFOSTRUCT* = ptr NETINFOSTRUCT - PNETINFOSTRUCT* = ptr NETINFOSTRUCT - NETCONNECTINFOSTRUCT* {.final, pure.} = object - cbStructure*: DWORD - dwFlags*: DWORD - dwSpeed*: DWORD - dwDelay*: DWORD - dwOptDataSize*: DWORD - - LPNETCONNECTINFOSTRUCT* = ptr NETCONNECTINFOSTRUCT - PNETCONNECTINFOSTRUCT* = ptr NETCONNECTINFOSTRUCT - ENUMMETAFILEPROC* = proc (para1: HDC, para2: HANDLETABLE, para3: METARECORD, - para4: int32, para5: LPARAM): int32{.stdcall.} - ENHMETAFILEPROC* = proc (para1: HDC, para2: HANDLETABLE, para3: ENHMETARECORD, - para4: int32, para5: LPARAM): int32{.stdcall.} - ENUMFONTSPROC* = proc (para1: LPLOGFONT, para2: LPTEXTMETRIC, para3: DWORD, - para4: LPARAM): int32{.stdcall.} - FONTENUMPROC* = proc (para1: var ENUMLOGFONT, para2: var NEWTEXTMETRIC, - para3: int32, para4: LPARAM): int32{.stdcall.} - FONTENUMEXPROC* = proc (para1: var ENUMLOGFONTEX, para2: var NEWTEXTMETRICEX, - para3: int32, para4: LPARAM): int32{.stdcall.} - LPOVERLAPPED_COMPLETION_ROUTINE* = proc (para1: DWORD, para2: DWORD, - para3: LPOVERLAPPED){.stdcall.} - # Structures for the extensions to OpenGL - POINTFLOAT* {.final, pure.} = object - x*: float32 - y*: float32 - - PPOINTFLOAT* = ptr POINTFLOAT - GLYPHMETRICSFLOAT* {.final, pure.} = object - gmfBlackBoxX*: float32 - gmfBlackBoxY*: float32 - gmfptGlyphOrigin*: POINTFLOAT - gmfCellIncX*: float32 - gmfCellIncY*: float32 - - LPGLYPHMETRICSFLOAT* = ptr GLYPHMETRICSFLOAT - PGLYPHMETRICSFLOAT* = ptr GLYPHMETRICSFLOAT - LAYERPLANEDESCRIPTOR* {.final, pure.} = object - nSize*: int16 - nVersion*: int16 - dwFlags*: DWORD - iPixelType*: int8 - cColorBits*: int8 - cRedBits*: int8 - cRedShift*: int8 - cGreenBits*: int8 - cGreenShift*: int8 - cBlueBits*: int8 - cBlueShift*: int8 - cAlphaBits*: int8 - cAlphaShift*: int8 - cAccumBits*: int8 - cAccumRedBits*: int8 - cAccumGreenBits*: int8 - cAccumBlueBits*: int8 - cAccumAlphaBits*: int8 - cDepthBits*: int8 - cStencilBits*: int8 - cAuxBuffers*: int8 - iLayerPlane*: int8 - bReserved*: int8 - crTransparent*: COLORREF - - LPLAYERPLANEDESCRIPTOR* = ptr LAYERPLANEDESCRIPTOR - PLAYERPLANEDESCRIPTOR* = ptr LAYERPLANEDESCRIPTOR - PIXELFORMATDESCRIPTOR* {.final, pure.} = object - nSize*: int16 - nVersion*: int16 - dwFlags*: DWORD - iPixelType*: int8 - cColorBits*: int8 - cRedBits*: int8 - cRedShift*: int8 - cGreenBits*: int8 - cGreenShift*: int8 - cBlueBits*: int8 - cBlueShift*: int8 - cAlphaBits*: int8 - cAlphaShift*: int8 - cAccumBits*: int8 - cAccumRedBits*: int8 - cAccumGreenBits*: int8 - cAccumBlueBits*: int8 - cAccumAlphaBits*: int8 - cDepthBits*: int8 - cStencilBits*: int8 - cAuxBuffers*: int8 - iLayerType*: int8 - bReserved*: int8 - dwLayerMask*: DWORD - dwVisibleMask*: DWORD - dwDamageMask*: DWORD - - LPPIXELFORMATDESCRIPTOR* = ptr PIXELFORMATDESCRIPTOR - PPIXELFORMATDESCRIPTOR* = ptr PIXELFORMATDESCRIPTOR - USER_INFO_2* {.final, pure.} = object - usri2_name*: LPWSTR - usri2_password*: LPWSTR - usri2_password_age*: DWORD - usri2_priv*: DWORD - usri2_home_dir*: LPWSTR - usri2_comment*: LPWSTR - usri2_flags*: DWORD - usri2_script_path*: LPWSTR - usri2_auth_flags*: DWORD - usri2_full_name*: LPWSTR - usri2_usr_comment*: LPWSTR - usri2_parms*: LPWSTR - usri2_workstations*: LPWSTR - usri2_last_logon*: DWORD - usri2_last_logoff*: DWORD - usri2_acct_expires*: DWORD - usri2_max_storage*: DWORD - usri2_units_per_week*: DWORD - usri2_logon_hours*: PBYTE - usri2_bad_pw_count*: DWORD - usri2_num_logons*: DWORD - usri2_logon_server*: LPWSTR - usri2_country_code*: DWORD - usri2_code_page*: DWORD - - PUSER_INFO_2* = ptr USER_INFO_2 - LPUSER_INFO_2* = ptr USER_INFO_2 - USER_INFO_0* {.final, pure.} = object - usri0_name*: LPWSTR - - PUSER_INFO_0* = ptr USER_INFO_0 - LPUSER_INFO_0* = ptr USER_INFO_0 - USER_INFO_3* {.final, pure.} = object - usri3_name*: LPWSTR - usri3_password*: LPWSTR - usri3_password_age*: DWORD - usri3_priv*: DWORD - usri3_home_dir*: LPWSTR - usri3_comment*: LPWSTR - usri3_flags*: DWORD - usri3_script_path*: LPWSTR - usri3_auth_flags*: DWORD - usri3_full_name*: LPWSTR - usri3_usr_comment*: LPWSTR - usri3_parms*: LPWSTR - usri3_workstations*: LPWSTR - usri3_last_logon*: DWORD - usri3_last_logoff*: DWORD - usri3_acct_expires*: DWORD - usri3_max_storage*: DWORD - usri3_units_per_week*: DWORD - usri3_logon_hours*: PBYTE - usri3_bad_pw_count*: DWORD - usri3_num_logons*: DWORD - usri3_logon_server*: LPWSTR - usri3_country_code*: DWORD - usri3_code_page*: DWORD - usri3_user_id*: DWORD - usri3_primary_group_id*: DWORD - usri3_profile*: LPWSTR - usri3_home_dir_drive*: LPWSTR - usri3_password_expired*: DWORD - - PUSER_INFO_3* = ptr USER_INFO_3 - LPUSER_INFO_3* = ptr USER_INFO_3 - GROUP_INFO_2* {.final, pure.} = object - grpi2_name*: LPWSTR - grpi2_comment*: LPWSTR - grpi2_group_id*: DWORD - grpi2_attributes*: DWORD - - PGROUP_INFO_2* = ptr GROUP_INFO_2 - LOCALGROUP_INFO_0* {.final, pure.} = object - lgrpi0_name*: LPWSTR - - PLOCALGROUP_INFO_0* = ptr LOCALGROUP_INFO_0 - LPLOCALGROUP_INFO_0* = ptr LOCALGROUP_INFO_0 - IMAGE_DOS_HEADER* {.final, pure.} = object - e_magic*: int16 - e_cblp*: int16 - e_cp*: int16 - e_crlc*: int16 - e_cparhdr*: int16 - e_minalloc*: int16 - e_maxalloc*: int16 - e_ss*: int16 - e_sp*: int16 - e_csum*: int16 - e_ip*: int16 - e_cs*: int16 - e_lfarlc*: int16 - e_ovno*: int16 - e_res*: array[0..3, int16] - e_oemid*: int16 - e_oeminfo*: int16 - e_res2*: array[0..9, int16] - e_lfanew*: LONG - - PIMAGE_DOS_HEADER* = ptr IMAGE_DOS_HEADER - NOTIFYICONDATAA* {.final, pure.} = object - cbSize*: DWORD - Wnd*: HWND - uID*: WINUINT - uFlags*: WINUINT - uCallbackMessage*: WINUINT - hIcon*: HICON - szTip*: array[0..63, char] - - NOTIFYICONDATA* = NOTIFYICONDATAA - NOTIFYICONDATAW* {.final, pure.} = object - cbSize*: DWORD - Wnd*: HWND - uID*: WINUINT - uFlags*: WINUINT - uCallbackMessage*: WINUINT - hIcon*: HICON - szTip*: array[0..63, int16] - - PNotifyIconDataA* = ptr NotifyIconDataA - PNotifyIconDataW* = ptr NotifyIconDataW - PNotifyIconData* = PNotifyIconDataA - WOHandleArray* = array[0..MAXIMUM_WAIT_OBJECTS - 1, HANDLE] - PWOHandleArray* = ptr WOHandleArray - MMRESULT* = int32 -{.deprecated: [TPRINTERNOTIFYINFO: PRINTER_NOTIFY_INFO, TPRINTERNOTIFYINFODATA: PRINTER_NOTIFY_INFO_DATA, - TPRINTERINFO5: PRINTER_INFO_5, TPRINTERINFO4: PRINTER_INFO_4, TPRINTERINFO3: PRINTER_INFO_3, - TPRINTERINFO2: PRINTER_INFO_2, TPRINTERINFO1: PRINTER_INFO_1, TPRINTERDEFAULTS: PRINTER_DEFAULTS, - TPD: TPRINTDLG, TPREVENTMEDIAREMOVAL: PREVENT_MEDIA_REMOVAL, TPORTINFO2: PORT_INFO_2, - TPORTINFO1: PORT_INFO_1, TPOLYTEXT: POLYTEXT, TPERFOBJECTTYPE: PERF_OBJECT_TYPE, - TPERFINSTANCEDEFINITION: PERF_INSTANCE_DEFINITION, TPERFDATABLOCK: PERF_DATA_BLOCK, - TPERFCOUNTERDEFINITION: PERF_COUNTER_DEFINITION, TPERFCOUNTERBLOCK: PERF_COUNTER_BLOCK, - Tparaformat: PARAFORMAT, TPAINTSTRUCT: PAINTSTRUCT, TPSD: TPAGESETUPDLG, TOVERLAPPED: OVERLAPPED, - TOUTLINETEXTMETRIC: OUTLINETEXTMETRIC, TTEXTMETRICW: TEXTMETRICW, TTEXTMETRIC: TEXTMETRIC, - TOSVERSIONINFOW: OSVERSIONINFOW, TOSVERSIONINFO: OSVERSIONINFO, TOFNOTIFY: OFNOTIFY, - TOPENFILENAME_NT4: OPENFILENAME_NT4, TOFSTRUCT: OFSTRUCT, Tnumberfmt: NUMBERFMT, - TNSSERVICEINFO: NS_SERVICE_INFO, TSERVICEINFO: SERVICE_INFO, TCLSID: CLSID, - TSERVICEADDRESSES: SERVICE_ADDRESSES, TSERVICEADDRESS: SERVICE_ADDRESS, - TNONCLIENTMETRICS: NONCLIENTMETRICS, TNMUPDOWN: NM_UPDOWNW, TNMTREEVIEW: NM_TREEVIEW, - TTVITEM: TV_ITEM, TNMLISTVIEW: NM_LISTVIEW, TNEWTEXTMETRICEX: NEWTEXTMETRICEX, - TNEWTEXTMETRIC: NEWTEXTMETRIC].} - -{.deprecated: [TNEWCPLINFO: NEWCPLINFO, TNETRESOURCE: NETRESOURCE, TNETRESOURCEA: NETRESOURCE, - TNDDESHAREINFO: NDDESHAREINFO, TNCB: NCB, TNAMEBUFFER: NAME_BUFFER, TMULTIKEYHELP: MULTIKEYHELP, - Tmsgfilter: MSGFILTER, TMSGBOXPARAMS: MSGBOXPARAMS, TMSGBOXPARAMSA: MSGBOXPARAMS, TMOUSEKEYS: MOUSEKEYS, - TMOUSEHOOKSTRUCT: MOUSEHOOKSTRUCT, TMONMSGSTRUCT: MONMSGSTRUCT, TMONLINKSTRUCT: MONLINKSTRUCT, - TMONITORINFO2: MONITOR_INFO_2, TMONITORINFO1: MONITOR_INFO_1, TMONHSZSTRUCT: MONHSZSTRUCT, - TMONERRSTRUCT: MONERRSTRUCT, TMONCONVSTRUCT: MONCONVSTRUCT, TMONCBSTRUCT: MONCBSTRUCT, - TMODEMSETTINGS: MODEMSETTINGS, TMODEMDEVCAPS: MODEMDEVCAPS, TMINMAXINFO: MINMAXINFO, - TMINIMIZEDMETRICS: MINIMIZEDMETRICS, TMETARECORD: METARECORD, TMETAHEADER: METAHEADER, - TMETAFILEPICT: METAFILEPICT, TMENUTEMPLATE: MENUTEMPLATE, TMENUITEMTEMPLATEHEADER: MENUITEMTEMPLATEHEADER, - TMENUITEMTEMPLATE: MENUITEMTEMPLATE, TMENUITEMINFOA: MENUITEMINFO, TMENUITEMINFO: MENUITEMINFO, - TMENUINFO: MENUINFO, TMENUEXTEMPLATEITEM: MENUEX_TEMPLATE_ITEM, - TMENUXTEMPLATEHEADER: MENUEX_TEMPLATE_HEADER, TMEMORYSTATUS: MEMORYSTATUS, - TMEMORYBASICINFORMATION: MEMORY_BASIC_INFORMATION, TMEASUREITEMSTRUCT: MEASUREITEMSTRUCT, - TMDICREATESTRUCT: MDICREATESTRUCT, TMAT2: MAT2, TLVKEYDOWN: LV_KEYDOWN, TLVHITTESTINFO: LV_HITTESTINFO, - TLVFINDINFO: LV_FINDINFO, TLVDISPINFO: LV_DISPINFO, TLVITEM: LV_ITEM, TLVCOLUMN: LV_COLUMN, - TLUIDANDATTRIBUTESARRAY: LUID_AND_ATTRIBUTES_ARRAY, TLUIDANDATTRIBUTES: LUID_AND_ATTRIBUTES, - TLUID: LUID, TFXPT16DOT16: FXPT16DOT16, TLOCALGROUPMEMBERSINFO3: LOCALGROUP_MEMBERS_INFO_3, - TLOCALGROUPMEMBERSINFO0: LOCALGROUP_MEMBERS_INFO_0, TLOCALESIGNATURE: LOCALESIGNATURE, - TGUID: GUID, TOPENFILENAME: OPENFILENAME].} - -{.deprecated: [TTOGGLEKEYS: TOGGLEKEYS, TTIMEZONEINFORMATION: TIME_ZONE_INFORMATION, - Ttextrange: TEXTRANGE, TTCKEYDOWN: TC_KEYDOWN, TTCITEMHEADER: TC_ITEMHEADER, TTCITEM: TC_ITEM, - TTCHITTESTINFO: TC_HITTESTINFO, TTBSAVEPARAMS: TBSAVEPARAMS, TTBNOTIFY: TBNOTIFY, TTBBUTTON: TBBUTTON, - TTAPEWRITEMARKS: TAPE_WRITE_MARKS, TTAPESETPOSITION: TAPE_SET_POSITION, - TTAPESETMEDIAPARAMETERS: TAPE_SET_MEDIA_PARAMETERS, TTAPESETDRIVEPARAMETERS: TAPE_SET_DRIVE_PARAMETERS, - TTAPEPREPARE: TAPE_PREPARE, TTAPEGETPOSITION: TAPE_GET_POSITION, - TTAPEGETMEDIAPARAMETERS: TAPE_GET_MEDIA_PARAMETERS, TTAPEGETDRIVEPARAMETERS: TAPE_GET_DRIVE_PARAMETERS, - TTAPEERASE: TAPE_ERASE, TSYSTEMPOWERSTATUS: SYSTEM_POWER_STATUS, TSYSTEMINFO: SYSTEM_INFO, - TSYSTEMAUDITACE: SYSTEM_AUDIT_ACE, TSTYLESTRUCT: STYLESTRUCT, TSTYLEBUF: STYLEBUF, TSTRRET: STRRET, - TSTICKYKEYS: STICKYKEYS, TSTARTUPINFO: STARTUPINFO, TSOUNDSENTRY: SOUNDSENTRY, - TSINGLELISTENTRY: SINGLE_LIST_ENTRY, TSIDANDATTRIBUTESARRAY: SID_AND_ATTRIBUTES_ARRAY, - TSIDANDATTRIBUTES: SID_AND_ATTRIBUTES, TSHNAMEMAPPING: SHNAMEMAPPING, TSHGDN: SHGNO, - TSHFILEOPSTRUCT: SHFILEOPSTRUCT, TFILEOPFLAGS: FILEOP_FLAGS, TSHFILEINFO: SHFILEINFO, TSHCONTF: SHCONTF, - TSETPARTITIONINFORMATION: SET_PARTITION_INFORMATION, TSESSIONHEADER: SESSION_HEADER].} - -{.deprecated: [TSESSIONBUFFER: SESSION_BUFFER, TSERVICETYPEINFOABS: SERVICE_TYPE_INFO_ABS, - TSERVICETYPEVALUEABS: SERVICE_TYPE_VALUE_ABS, TSERVICETABLEENTRY: SERVICE_TABLE_ENTRY, - TSERIALKEYS: SERIALKEYS, Tselchange: SELCHANGE, TSECURITYINFORMATION: SECURITY_INFORMATION, - TSECURITYATTRIBUTES: SECURITY_ATTRIBUTES, TSCROLLINFO: SCROLLINFO, TRGNDATA: RGNDATA, - TRGNDATAHEADER: RGNDATAHEADER, Treqresize: REQRESIZE, Trepastespecial: REPASTESPECIAL, - TREMOTENAMEINFO: REMOTE_NAME_INFO, TREASSIGNBLOCKS: REASSIGN_BLOCKS, TRASTERIZERSTATUS: RASTERIZER_STATUS, - TRASPPPNBF: RASPPPNBF, TRASPPPIPX: RASPPPIPX, TRASPPPIP: RASPPPIP, TRASENTRYNAME: RASENTRYNAME, - TRASDIALPARAMS: RASDIALPARAMS, TRASDIALEXTENSIONS: RASDIALEXTENSIONS, TRASCONNSTATUS: RASCONNSTATUS, - TRASCONN: RASCONN, TRASAMB: RASAMB, Tpunctuation: PUNCTUATION, TPSHNOTIFY: PSHNOTIFY, - TPROVIDORINFO1: PROVIDOR_INFO_1, TPROTOCOLINFO: PROTOCOL_INFO, - TFNADDPROPSHEETPAGES: LPFNADDPROPSHEETPAGES, TFNADDPROPSHEETPAGE: LPFNADDPROPSHEETPAGE, - TPROPSHEETHEADER: PROPSHEETHEADER, TPROPSHEETPAGE: PROPSHEETPAGE, TFNPSPCALLBACK: LPFNPSPCALLBACK, - TPROCESSINFORMATION: PROCESS_INFORMATION, TPROCESSHEAPENTRY: PROCESS_HEAPENTRY, - TPRIVILEGESET: PRIVILEGE_SET, TPRINTPROCESSORINFO1: PRINTPROCESSOR_INFO_1, - TPRINTERNOTIFYOPTIONS: PRINTER_NOTIFY_OPTIONS, TPRINTERNOTIFYOPTIONSTYPE: PRINTER_NOTIFY_OPTIONS_TYPE].} - -{.deprecated: [TNotifyIconDataA: NOTIFYICONDATAA, TNotifyIconDataW: NOTIFYICONDATAW, - TNotifyIconData: NotifyIconDataA, TIMAGEDOSHEADER: IMAGE_DOS_HEADER, TLOCALGROUPINFO0: LOCALGROUP_INFO_0, - TGROUPINFO2: GROUP_INFO_2, TUSERINFO3: USER_INFO_3, TUSERINFO0: USER_INFO_0, TUSERINFO2: USER_INFO_2, - TPIXELFORMATDESCRIPTOR: PIXELFORMATDESCRIPTOR, TLAYERPLANEDESCRIPTOR: LAYERPLANEDESCRIPTOR, - TGLYPHMETRICSFLOAT: GLYPHMETRICSFLOAT, TPOINTFLOAT: POINTFLOAT, - TNETCONNECTINFOSTRUCT: NETCONNECTINFOSTRUCT, TNETINFOSTRUCT: NETINFOSTRUCT, - TDISCDLGSTRUCT: DISCDLGSTRUCT, TDISCDLGSTRUCTA: DISCDLGSTRUCT, TCONNECTDLGSTRUCT: CONNECTDLGSTRUCT, - TWNDCLASSEXW: WNDCLASSEXW, TWNDCLASSEX: WNDCLASSEX, TWNDCLASSEXA: WNDCLASSEX, TWNDCLASSW: WNDCLASSW, - TWNDCLASS: WNDCLASS, TWNDCLASSA: WNDCLASS, TWINDOWPLACEMENT: WINDOWPLACEMENT, - TWIN32STREAMID: WIN32_STREAM_ID, TWIN32FINDDATAW: WIN32_FIND_DATAW, TWIN32FINDDATAA: WIN32_FIND_DATA, - TWIN32FINDDATA: WIN32_FIND_DATA, TVSFIXEDFILEINFO: VS_FIXEDFILEINFO, - TVERIFYINFORMATION: VERIFY_INFORMATION, Tvalue_ent: VALENT, TVALENT: VALENT, - TUSEROBJECTFLAGS: USEROBJECTFLAGS, TUNIVERSALNAMEINFO: UNIVERSAL_NAME_INFO, TUDACCEL: UDACCEL, - TTVSORTCB: TV_SORTCB, TTVKEYDOWN: TV_KEYDOWN, TTVINSERTSTRUCT: TV_INSERTSTRUCT, - TTVHITTESTINFO: TV_HITTESTINFO, TTVDISPINFO: TV_DISPINFO, TTTPOLYGONHEADER: TTPOLYGONHEADER, - TTTPOLYCURVE: TTPOLYCURVE, TTTHITTESTINFO: TTHITTESTINFO, TTRANSMITFILEBUFFERS: TRANSMIT_FILE_BUFFERS, - TTPMPARAMS: TPMPARAMS, TTOOLTIPTEXT: TOOLTIPTEXT, TTOOLINFO: TOOLINFO, - TTOKENCONTROL: TOKEN_CONTROL, TWOHandleArray: WOHandleArray].} - - -type - PWaveFormatEx* = ptr TWaveFormatEx - TWaveFormatEx* {.final, pure.} = object - wFormatTag*: int16 # format type - nChannels*: int16 # number of channels (i.e. mono, stereo, etc.) - nSamplesPerSec*: DWORD # sample rate - nAvgBytesPerSec*: DWORD # for buffer estimation - nBlockAlign*: int16 # block size of data - wBitsPerSample*: int16 # number of bits per sample of mono data - cbSize*: int16 # the count in bytes of the size of - - WIN32_FILE_ATTRIBUTE_DATA* {.final, pure.} = object - dwFileAttributes*: DWORD - ftCreationTime*: FILETIME - ftLastAccessTime*: FILETIME - ftLastWriteTime*: FILETIME - nFileSizeHigh*: DWORD - nFileSizeLow*: DWORD - - LPWIN32_FILE_ATTRIBUTE_DATA* = ptr WIN32_FILE_ATTRIBUTE_DATA - TWIN32FILEATTRIBUTEDATA* = WIN32_FILE_ATTRIBUTE_DATA - PWIN32FILEATTRIBUTEDATA* = ptr WIN32_FILE_ATTRIBUTE_DATA - # TrackMouseEvent. NT or higher only. - TTrackMouseEvent* {.final, pure.} = object - cbSize*: DWORD - dwFlags*: DWORD - hwndTrack*: HWND - dwHoverTime*: DWORD - - PTrackMouseEvent* = ptr TTrackMouseEvent - -const - ACM_OPENW* = 1127 - ACM_OPENA* = 1124 - -when defined(winUnicode): - const - ACM_OPEN* = ACM_OPENW -else: - const - ACM_OPEN* = ACM_OPENA -# UNICODE - -const - ACM_PLAY* = 1125 - ACM_STOP* = 1126 - ACN_START* = 1 - ACN_STOP* = 2 - # Buttons - BM_CLICK* = 245 - BM_GETCHECK* = 240 - BM_GETIMAGE* = 246 - BM_GETSTATE* = 242 - BM_SETCHECK* = 241 - BM_SETIMAGE* = 247 - BM_SETSTATE* = 243 - BM_SETSTYLE* = 244 - BN_CLICKED* = 0 - BN_DBLCLK* = 5 - BN_DISABLE* = 4 - BN_DOUBLECLICKED* = 5 - BN_HILITE* = 2 - BN_KILLFOCUS* = 7 - BN_PAINT* = 1 - BN_PUSHED* = 2 - BN_SETFOCUS* = 6 - BN_UNHILITE* = 3 - BN_UNPUSHED* = 3 - # Combo Box - CB_ADDSTRING* = 323 - CB_DELETESTRING* = 324 - CB_DIR* = 325 - CB_FINDSTRING* = 332 - CB_FINDSTRINGEXACT* = 344 - CB_GETCOUNT* = 326 - CB_GETCURSEL* = 327 - CB_GETDROPPEDCONTROLRECT* = 338 - CB_GETDROPPEDSTATE* = 343 - CB_GETDROPPEDWIDTH* = 351 - CB_GETEDITSEL* = 320 - CB_GETEXTENDEDUI* = 342 - CB_GETHORIZONTALEXTENT* = 349 - CB_GETITEMDATA* = 336 - CB_GETITEMHEIGHT* = 340 - CB_GETLBTEXT* = 328 - CB_GETLBTEXTLEN* = 329 - CB_GETLOCALE* = 346 - CB_GETTOPINDEX* = 347 - CB_INITSTORAGE* = 353 - CB_INSERTSTRING* = 330 - CB_LIMITTEXT* = 321 - CB_RESETCONTENT* = 331 - CB_SELECTSTRING* = 333 - CB_SETCURSEL* = 334 - CB_SETDROPPEDWIDTH* = 352 - CB_SETEDITSEL* = 322 - CB_SETEXTENDEDUI* = 341 - CB_SETHORIZONTALEXTENT* = 350 - CB_SETITEMDATA* = 337 - CB_SETITEMHEIGHT* = 339 - CB_SETLOCALE* = 345 - CB_SETTOPINDEX* = 348 - CB_SHOWDROPDOWN* = 335 - # Combo Box notifications - CBN_CLOSEUP* = 8 - CBN_DBLCLK* = 2 - CBN_DROPDOWN* = 7 - CBN_EDITCHANGE* = 5 - CBN_EDITUPDATE* = 6 - CBN_ERRSPACE* = -1 - CBN_KILLFOCUS* = 4 - CBN_SELCHANGE* = 1 - CBN_SELENDCANCEL* = 10 - CBN_SELENDOK* = 9 - CBN_SETFOCUS* = 3 - # Control Panel - # Device messages - # Drag list box - DL_BEGINDRAG* = 1157 - DL_CANCELDRAG* = 1160 - DL_DRAGGING* = 1158 - DL_DROPPED* = 1159 - # Default push button - DM_GETDEFID* = 1024 - DM_REPOSITION* = 1026 - DM_SETDEFID* = 1025 - # RTF control - EM_CANPASTE* = 1074 - EM_CANUNDO* = 198 - EM_CHARFROMPOS* = 215 - EM_DISPLAYBAND* = 1075 - EM_EMPTYUNDOBUFFER* = 205 - EM_EXGETSEL* = 1076 - EM_EXLIMITTEXT* = 1077 - EM_EXLINEFROMCHAR* = 1078 - EM_EXSETSEL* = 1079 - EM_FINDTEXT* = 1080 - EM_FINDTEXTEX* = 1103 - EM_FINDWORDBREAK* = 1100 - EM_FMTLINES* = 200 - EM_FORMATRANGE* = 1081 - EM_GETCHARFORMAT* = 1082 - EM_GETEVENTMASK* = 1083 - EM_GETFIRSTVISIBLELINE* = 206 - EM_GETHANDLE* = 189 - EM_GETLIMITTEXT* = 213 - EM_GETLINE* = 196 - EM_GETLINECOUNT* = 186 - EM_GETMARGINS* = 212 - EM_GETMODIFY* = 184 - EM_GETIMECOLOR* = 1129 - EM_GETIMEOPTIONS* = 1131 - EM_GETOPTIONS* = 1102 - EM_GETOLEINTERFACE* = 1084 - EM_GETPARAFORMAT* = 1085 - EM_GETPASSWORDCHAR* = 210 - EM_GETPUNCTUATION* = 1125 - EM_GETRECT* = 178 - EM_GETSEL* = 176 - EM_GETSELTEXT* = 1086 - EM_GETTEXTRANGE* = 1099 - EM_GETTHUMB* = 190 - EM_GETWORDBREAKPROC* = 209 - EM_GETWORDBREAKPROCEX* = 1104 - EM_GETWORDWRAPMODE* = 1127 - EM_HIDESELECTION* = 1087 - EM_LIMITTEXT* = 197 - EM_LINEFROMCHAR* = 201 - EM_LINEINDEX* = 187 - EM_LINELENGTH* = 193 - EM_LINESCROLL* = 182 - EM_PASTESPECIAL* = 1088 - EM_POSFROMCHAR* = 214 - EM_REPLACESEL* = 194 - EM_REQUESTRESIZE* = 1089 - EM_SCROLL* = 181 - EM_SCROLLCARET* = 183 - EM_SELECTIONTYPE* = 1090 - EM_SETBKGNDCOLOR* = 1091 - EM_SETCHARFORMAT* = 1092 - EM_SETEVENTMASK* = 1093 - EM_SETHANDLE* = 188 - EM_SETIMECOLOR* = 1128 - EM_SETIMEOPTIONS* = 1130 - EM_SETLIMITTEXT* = 197 - EM_SETMARGINS* = 211 - EM_SETMODIFY* = 185 - EM_SETOLECALLBACK* = 1094 - EM_SETOPTIONS* = 1101 - EM_SETPARAFORMAT* = 1095 - EM_SETPASSWORDCHAR* = 204 - EM_SETPUNCTUATION* = 1124 - EM_SETREADONLY* = 207 - EM_SETRECT* = 179 - EM_SETRECTNP* = 180 - EM_SETSEL* = 177 - EM_SETTABSTOPS* = 203 - EM_SETTARGETDEVICE* = 1096 - EM_SETWORDBREAKPROC* = 208 - EM_SETWORDBREAKPROCEX* = 1105 - EM_SETWORDWRAPMODE* = 1126 - EM_STREAMIN* = 1097 - EM_STREAMOUT* = 1098 - EM_UNDO* = 199 - # Edit control - EN_CHANGE* = 768 - EN_CORRECTTEXT* = 1797 - EN_DROPFILES* = 1795 - EN_ERRSPACE* = 1280 - EN_HSCROLL* = 1537 - EN_IMECHANGE* = 1799 - EN_KILLFOCUS* = 512 - EN_MAXTEXT* = 1281 - EN_MSGFILTER* = 1792 - EN_OLEOPFAILED* = 1801 - EN_PROTECTED* = 1796 - EN_REQUESTRESIZE* = 1793 - EN_SAVECLIPBOARD* = 1800 - EN_SELCHANGE* = 1794 - EN_SETFOCUS* = 256 - EN_STOPNOUNDO* = 1798 - EN_UPDATE* = 1024 - EN_VSCROLL* = 1538 - # File Manager extensions - # File Manager extensions DLL events - # Header control - HDM_DELETEITEM* = 4610 - HDM_GETITEMW* = 4619 - HDM_INSERTITEMW* = 4618 - HDM_SETITEMW* = 4620 - HDM_GETITEMA* = 4611 - HDM_INSERTITEMA* = 4609 - HDM_SETITEMA* = 4612 - -when defined(winUnicode): - const - HDM_GETITEM* = HDM_GETITEMW - HDM_INSERTITEM* = HDM_INSERTITEMW - HDM_SETITEM* = HDM_SETITEMW -else: - const - HDM_GETITEM* = HDM_GETITEMA - HDM_INSERTITEM* = HDM_INSERTITEMA - HDM_SETITEM* = HDM_SETITEMA -# UNICODE - -const - HDM_GETITEMCOUNT* = 4608 - HDM_HITTEST* = 4614 - HDM_LAYOUT* = 4613 - # Header control notifications - HDN_BEGINTRACKW* = -326 - HDN_DIVIDERDBLCLICKW* = -325 - HDN_ENDTRACKW* = -327 - HDN_ITEMCHANGEDW* = -321 - HDN_ITEMCHANGINGW* = -320 - HDN_ITEMCLICKW* = -322 - HDN_ITEMDBLCLICKW* = -323 - HDN_TRACKW* = -328 - HDN_BEGINTRACKA* = -306 - HDN_DIVIDERDBLCLICKA* = -305 - HDN_ENDTRACKA* = -307 - HDN_ITEMCHANGEDA* = -301 - HDN_ITEMCHANGINGA* = -300 - HDN_ITEMCLICKA* = -302 - HDN_ITEMDBLCLICKA* = -303 - HDN_TRACKA* = -308 - -when defined(winUnicode): - const - HDN_BEGINTRACK* = HDN_BEGINTRACKW - HDN_DIVIDERDBLCLICK* = HDN_DIVIDERDBLCLICKW - HDN_ENDTRACK* = HDN_ENDTRACKW - HDN_ITEMCHANGED* = HDN_ITEMCHANGEDW - HDN_ITEMCHANGING* = HDN_ITEMCHANGINGW - HDN_ITEMCLICK* = HDN_ITEMCLICKW - HDN_ITEMDBLCLICK* = HDN_ITEMDBLCLICKW - HDN_TRACK* = HDN_TRACKW -else: - const - HDN_BEGINTRACK* = HDN_BEGINTRACKA - HDN_DIVIDERDBLCLICK* = HDN_DIVIDERDBLCLICKA - HDN_ENDTRACK* = HDN_ENDTRACKA - HDN_ITEMCHANGED* = HDN_ITEMCHANGEDA - HDN_ITEMCHANGING* = HDN_ITEMCHANGINGA - HDN_ITEMCLICK* = HDN_ITEMCLICKA - HDN_ITEMDBLCLICK* = HDN_ITEMDBLCLICKA - HDN_TRACK* = HDN_TRACKA -# UNICODE - -const - # Hot key control - HKM_GETHOTKEY* = 1026 - HKM_SETHOTKEY* = 1025 - HKM_SETRULES* = 1027 - # List box - LB_ADDFILE* = 406 - LB_ADDSTRING* = 384 - LB_DELETESTRING* = 386 - LB_DIR* = 397 - LB_FINDSTRING* = 399 - LB_FINDSTRINGEXACT* = 418 - LB_GETANCHORINDEX* = 413 - LB_GETCARETINDEX* = 415 - LB_GETCOUNT* = 395 - LB_GETCURSEL* = 392 - LB_GETHORIZONTALEXTENT* = 403 - LB_GETITEMDATA* = 409 - LB_GETITEMHEIGHT* = 417 - LB_GETITEMRECT* = 408 - LB_GETLOCALE* = 422 - LB_GETSEL* = 391 - LB_GETSELCOUNT* = 400 - LB_GETSELITEMS* = 401 - LB_GETTEXT* = 393 - LB_GETTEXTLEN* = 394 - LB_GETTOPINDEX* = 398 - LB_INITSTORAGE* = 424 - LB_INSERTSTRING* = 385 - LB_ITEMFROMPOINT* = 425 - LB_RESETCONTENT* = 388 - LB_SELECTSTRING* = 396 - LB_SELITEMRANGE* = 411 - LB_SELITEMRANGEEX* = 387 - LB_SETANCHORINDEX* = 412 - LB_SETCARETINDEX* = 414 - LB_SETCOLUMNWIDTH* = 405 - LB_SETCOUNT* = 423 - LB_SETCURSEL* = 390 - LB_SETHORIZONTALEXTENT* = 404 - LB_SETITEMDATA* = 410 - LB_SETITEMHEIGHT* = 416 - LB_SETLOCALE* = 421 - LB_SETSEL* = 389 - LB_SETTABSTOPS* = 402 - LB_SETTOPINDEX* = 407 - # List box notifications - LBN_DBLCLK* = 2 - LBN_ERRSPACE* = -2 - LBN_KILLFOCUS* = 5 - LBN_SELCANCEL* = 3 - LBN_SELCHANGE* = 1 - LBN_SETFOCUS* = 4 - # List view control - LVM_ARRANGE* = 4118 - LVM_CREATEDRAGIMAGE* = 4129 - LVM_DELETEALLITEMS* = 4105 - LVM_DELETECOLUMN* = 4124 - LVM_DELETEITEM* = 4104 - LVM_ENSUREVISIBLE* = 4115 - LVM_GETBKCOLOR* = 4096 - LVM_GETCALLBACKMASK* = 4106 - LVM_GETCOLUMNWIDTH* = 4125 - LVM_GETCOUNTPERPAGE* = 4136 - LVM_GETEDITCONTROL* = 4120 - LVM_GETIMAGELIST* = 4098 - LVM_EDITLABELW* = 4214 - LVM_FINDITEMW* = 4179 - LVM_GETCOLUMNW* = 4191 - LVM_GETISEARCHSTRINGW* = 4213 - LVM_GETITEMW* = 4171 - LVM_GETITEMTEXTW* = 4211 - LVM_GETSTRINGWIDTHW* = 4183 - LVM_INSERTCOLUMNW* = 4193 - LVM_INSERTITEMW* = 4173 - LVM_SETCOLUMNW* = 4192 - LVM_SETITEMW* = 4172 - LVM_SETITEMTEXTW* = 4212 - LVM_EDITLABELA* = 4119 - LVM_FINDITEMA* = 4109 - LVM_GETCOLUMNA* = 4121 - LVM_GETISEARCHSTRINGA* = 4148 - LVM_GETITEMA* = 4101 - LVM_GETITEMTEXTA* = 4141 - LVM_GETSTRINGWIDTHA* = 4113 - LVM_INSERTCOLUMNA* = 4123 - LVM_INSERTITEMA* = 4103 - LVM_SETCOLUMNA* = 4122 - LVM_SETITEMA* = 4102 - LVM_SETITEMTEXTA* = 4142 - -when defined(winUnicode): - const - LVM_EDITLABEL* = LVM_EDITLABELW - LVM_FINDITEM* = LVM_FINDITEMW - LVM_GETCOLUMN* = LVM_GETCOLUMNW - LVM_GETISEARCHSTRING* = LVM_GETISEARCHSTRINGW - LVM_GETITEM* = LVM_GETITEMW - LVM_GETITEMTEXT* = LVM_GETITEMTEXTW - LVM_GETSTRINGWIDTH* = LVM_GETSTRINGWIDTHW - LVM_INSERTCOLUMN* = LVM_INSERTCOLUMNW - LVM_INSERTITEM* = LVM_INSERTITEMW - LVM_SETCOLUMN* = LVM_SETCOLUMNW - LVM_SETITEM* = LVM_SETITEMW - LVM_SETITEMTEXT* = LVM_SETITEMTEXTW -else: - const - LVM_EDITLABEL* = LVM_EDITLABELA - LVM_FINDITEM* = LVM_FINDITEMA - LVM_GETCOLUMN* = LVM_GETCOLUMNA - LVM_GETISEARCHSTRING* = LVM_GETISEARCHSTRINGA - LVM_GETITEM* = LVM_GETITEMA - LVM_GETITEMTEXT* = LVM_GETITEMTEXTA - LVM_GETSTRINGWIDTH* = LVM_GETSTRINGWIDTHA - LVM_INSERTCOLUMN* = LVM_INSERTCOLUMNA - LVM_INSERTITEM* = LVM_INSERTITEMA - LVM_SETCOLUMN* = LVM_SETCOLUMNA - LVM_SETITEM* = LVM_SETITEMA - LVM_SETITEMTEXT* = LVM_SETITEMTEXTA -# UNICODE - -const - LVM_GETITEMCOUNT* = 4100 - LVM_GETITEMPOSITION* = 4112 - LVM_GETITEMRECT* = 4110 - LVM_GETITEMSPACING* = 4147 - LVM_GETITEMSTATE* = 4140 - LVM_GETNEXTITEM* = 4108 - LVM_GETORIGIN* = 4137 - LVM_GETSELECTEDCOUNT* = 4146 - LVM_GETTEXTBKCOLOR* = 4133 - LVM_GETTEXTCOLOR* = 4131 - LVM_GETTOPINDEX* = 4135 - LVM_GETVIEWRECT* = 4130 - LVM_HITTEST* = 4114 - LVM_REDRAWITEMS* = 4117 - LVM_SCROLL* = 4116 - LVM_SETBKCOLOR* = 4097 - LVM_SETCALLBACKMASK* = 4107 - LVM_SETCOLUMNWIDTH* = 4126 - LVM_SETIMAGELIST* = 4099 - LVM_SETITEMCOUNT* = 4143 - LVM_SETITEMPOSITION* = 4111 - LVM_SETITEMPOSITION32* = 4145 - LVM_SETITEMSTATE* = 4139 - LVM_SETTEXTBKCOLOR* = 4134 - LVM_SETTEXTCOLOR* = 4132 - LVM_SORTITEMS* = 4144 - LVM_UPDATE* = 4138 - # List view control notifications - LVN_BEGINDRAG* = -109 - LVN_BEGINRDRAG* = -111 - LVN_COLUMNCLICK* = -108 - LVN_DELETEALLITEMS* = -104 - LVN_DELETEITEM* = -103 - LVN_BEGINLABELEDITW* = -175 - LVN_ENDLABELEDITW* = -176 - LVN_GETDISPINFOW* = -177 - LVN_SETDISPINFOW* = -178 - LVN_BEGINLABELEDITA* = -105 - LVN_ENDLABELEDITA* = -106 - LVN_GETDISPINFOA* = -150 - LVN_SETDISPINFOA* = -151 - -when defined(winUnicode): - const - LVN_BEGINLABELEDIT* = LVN_BEGINLABELEDITW - LVN_ENDLABELEDIT* = LVN_ENDLABELEDITW - LVN_GETDISPINFO* = LVN_GETDISPINFOW - LVN_SETDISPINFO* = LVN_SETDISPINFOW -else: - const - LVN_BEGINLABELEDIT* = LVN_BEGINLABELEDITA - LVN_ENDLABELEDIT* = LVN_ENDLABELEDITA - LVN_GETDISPINFO* = LVN_GETDISPINFOA - LVN_SETDISPINFO* = LVN_SETDISPINFOA -# UNICODE - -const - LVN_INSERTITEM* = -102 - LVN_ITEMCHANGED* = -101 - LVN_ITEMCHANGING* = -100 - LVN_KEYDOWN* = -155 - # Control notification - NM_CLICK* = -2 - NM_DBLCLK* = -3 - NM_KILLFOCUS* = -8 - NM_OUTOFMEMORY* = -1 - NM_RCLICK* = -5 - NM_RDBLCLK* = -6 - NM_RETURN* = -4 - NM_SETFOCUS* = -7 - # Power status - # Progress bar control - PBM_DELTAPOS* = 1027 - PBM_SETPOS* = 1026 - PBM_SETRANGE* = 1025 - PBM_SETRANGE32* = 1030 - PBM_SETSTEP* = 1028 - PBM_STEPIT* = 1029 - # Property sheets - PSM_ADDPAGE* = 1127 - PSM_APPLY* = 1134 - PSM_CANCELTOCLOSE* = 1131 - PSM_CHANGED* = 1128 - PSM_GETTABCONTROL* = 1140 - PSM_GETCURRENTPAGEHWND* = 1142 - PSM_ISDIALOGMESSAGE* = 1141 - PSM_PRESSBUTTON* = 1137 - PSM_QUERYSIBLINGS* = 1132 - PSM_REBOOTSYSTEM* = 1130 - PSM_REMOVEPAGE* = 1126 - PSM_RESTARTWINDOWS* = 1129 - PSM_SETCURSEL* = 1125 - PSM_SETCURSELID* = 1138 - PSM_SETFINISHTEXTW* = 1145 - PSM_SETTITLEW* = 1144 - PSM_SETFINISHTEXTA* = 1139 - PSM_SETTITLEA* = 1135 - -when defined(winUnicode): - const - PSM_SETFINISHTEXT* = PSM_SETFINISHTEXTW - PSM_SETTITLE* = PSM_SETTITLEW -else: - const - PSM_SETFINISHTEXT* = PSM_SETFINISHTEXTA - PSM_SETTITLE* = PSM_SETTITLEA -# UNICODE - -const - PSM_SETWIZBUTTONS* = 1136 - PSM_UNCHANGED* = 1133 - # Property sheet notifications - PSN_APPLY* = -202 - PSN_HELP* = -205 - PSN_KILLACTIVE* = -201 - PSN_QUERYCANCEL* = -209 - PSN_RESET* = -203 - PSN_SETACTIVE* = -200 - PSN_WIZBACK* = -206 - PSN_WIZFINISH* = -208 - PSN_WIZNEXT* = -207 - # Status window - SB_GETBORDERS* = 1031 - SB_GETPARTS* = 1030 - SB_GETRECT* = 1034 - SB_GETTEXTW* = 1037 - SB_GETTEXTLENGTHW* = 1036 - SB_SETTEXTW* = 1035 - SB_GETTEXTA* = 1026 - SB_GETTEXTLENGTHA* = 1027 - SB_SETTEXTA* = 1025 - -when defined(winUnicode): - const - SB_GETTEXT* = SB_GETTEXTW - SB_GETTEXTLENGTH* = SB_GETTEXTLENGTHW - SB_SETTEXT* = SB_SETTEXTW -else: - const - SB_GETTEXT* = SB_GETTEXTA - SB_GETTEXTLENGTH* = SB_GETTEXTLENGTHA - SB_SETTEXT* = SB_SETTEXTA -# UNICODE - -const - SB_SETMINHEIGHT* = 1032 - SB_SETPARTS* = 1028 - SB_SIMPLE* = 1033 - # Scroll bar control - SBM_ENABLE_ARROWS* = 228 - SBM_GETPOS* = 225 - SBM_GETRANGE* = 227 - SBM_GETSCROLLINFO* = 234 - SBM_SETPOS* = 224 - SBM_SETRANGE* = 226 - SBM_SETRANGEREDRAW* = 230 - SBM_SETSCROLLINFO* = 233 - # Static control - STM_GETICON* = 369 - STM_GETIMAGE* = 371 - STM_SETICON* = 368 - STM_SETIMAGE* = 370 - # Static control notifications - STN_CLICKED* = 0 - STN_DBLCLK* = 1 - STN_DISABLE* = 3 - STN_ENABLE* = 2 - # Toolbar control - TB_ADDBITMAP* = 1043 - TB_ADDBUTTONS* = 1044 - TB_AUTOSIZE* = 1057 - TB_BUTTONCOUNT* = 1048 - TB_BUTTONSTRUCTSIZE* = 1054 - TB_CHANGEBITMAP* = 1067 - TB_CHECKBUTTON* = 1026 - TB_COMMANDTOINDEX* = 1049 - TB_CUSTOMIZE* = 1051 - TB_DELETEBUTTON* = 1046 - TB_ENABLEBUTTON* = 1025 - TB_GETBITMAP* = 1068 - TB_GETBITMAPFLAGS* = 1065 - TB_GETBUTTON* = 1047 - TB_ADDSTRINGW* = 1101 - TB_GETBUTTONTEXTW* = 1099 - TB_SAVERESTOREW* = 1100 - TB_ADDSTRINGA* = 1052 - TB_GETBUTTONTEXTA* = 1069 - TB_SAVERESTOREA* = 1050 - -when defined(winUnicode): - const - TB_ADDSTRING* = TB_ADDSTRINGW - TB_GETBUTTONTEXT* = TB_GETBUTTONTEXTW - TB_SAVERESTORE* = TB_SAVERESTOREW -else: - const - TB_ADDSTRING* = TB_ADDSTRINGA - TB_GETBUTTONTEXT* = TB_GETBUTTONTEXTA - TB_SAVERESTORE* = TB_SAVERESTOREA -# UNICODE - -const - TB_GETITEMRECT* = 1053 - TB_GETROWS* = 1064 - TB_GETSTATE* = 1042 - TB_GETTOOLTIPS* = 1059 - TB_HIDEBUTTON* = 1028 - TB_INDETERMINATE* = 1029 - TB_INSERTBUTTON* = 1045 - TB_ISBUTTONCHECKED* = 1034 - TB_ISBUTTONENABLED* = 1033 - TB_ISBUTTONHIDDEN* = 1036 - TB_ISBUTTONINDETERMINATE* = 1037 - TB_ISBUTTONPRESSED* = 1035 - TB_PRESSBUTTON* = 1027 - TB_SETBITMAPSIZE* = 1056 - TB_SETBUTTONSIZE* = 1055 - TB_SETCMDID* = 1066 - TB_SETPARENT* = 1061 - TB_SETROWS* = 1063 - TB_SETSTATE* = 1041 - TB_SETTOOLTIPS* = 1060 - # Track bar control - TBM_CLEARSEL* = 1043 - TBM_CLEARTICS* = 1033 - TBM_GETCHANNELRECT* = 1050 - TBM_GETLINESIZE* = 1048 - TBM_GETNUMTICS* = 1040 - TBM_GETPAGESIZE* = 1046 - TBM_GETPOS* = 1024 - TBM_GETPTICS* = 1038 - TBM_GETRANGEMAX* = 1026 - TBM_GETRANGEMIN* = 1025 - TBM_GETSELEND* = 1042 - TBM_GETSELSTART* = 1041 - TBM_GETTHUMBLENGTH* = 1052 - TBM_GETTHUMBRECT* = 1049 - TBM_GETTIC* = 1027 - TBM_GETTICPOS* = 1039 - TBM_SETLINESIZE* = 1047 - TBM_SETPAGESIZE* = 1045 - TBM_SETPOS* = 1029 - TBM_SETRANGE* = 1030 - TBM_SETRANGEMAX* = 1032 - TBM_SETRANGEMIN* = 1031 - TBM_SETSEL* = 1034 - TBM_SETSELEND* = 1036 - TBM_SETSELSTART* = 1035 - TBM_SETTHUMBLENGTH* = 1051 - TBM_SETTIC* = 1028 - TBM_SETTICFREQ* = 1044 - # Tool bar control notifications - TBN_BEGINADJUST* = -703 - TBN_BEGINDRAG* = -701 - TBN_CUSTHELP* = -709 - TBN_ENDADJUST* = -704 - TBN_ENDDRAG* = -702 - TBN_GETBUTTONINFOW* = -720 - TBN_GETBUTTONINFOA* = -700 - -when defined(winUnicode): - const - TBN_GETBUTTONINFO* = TBN_GETBUTTONINFOW -else: - const - TBN_GETBUTTONINFO* = TBN_GETBUTTONINFOA -# UNICODE - -const - TBN_QUERYDELETE* = -707 - TBN_QUERYINSERT* = -706 - TBN_RESET* = -705 - TBN_TOOLBARCHANGE* = -708 - # Tab control - TCM_ADJUSTRECT* = 4904 - TCM_DELETEALLITEMS* = 4873 - TCM_DELETEITEM* = 4872 - TCM_GETCURFOCUS* = 4911 - TCM_GETCURSEL* = 4875 - TCM_GETIMAGELIST* = 4866 - TCM_GETITEMW* = 4924 - TCM_INSERTITEMW* = 4926 - TCM_SETITEMW* = 4925 - TCM_GETITEMA* = 4869 - TCM_INSERTITEMA* = 4871 - TCM_SETITEMA* = 4870 - -when defined(winUnicode): - const - TCM_GETITEM* = TCM_GETITEM - TCM_INSERTITEM* = TCM_INSERTITEMW - TCM_SETITEM* = TCM_SETITEMW -else: - const - TCM_GETITEM* = TCM_GETITEMA - TCM_INSERTITEM* = TCM_INSERTITEMA - TCM_SETITEM* = TCM_SETITEMA -# UNICODE - -const - TCM_GETITEMCOUNT* = 4868 - TCM_GETITEMRECT* = 4874 - TCM_GETROWCOUNT* = 4908 - TCM_GETTOOLTIPS* = 4909 - TCM_HITTEST* = 4877 - TCM_REMOVEIMAGE* = 4906 - TCM_SETCURFOCUS* = 4912 - TCM_SETCURSEL* = 4876 - TCM_SETIMAGELIST* = 4867 - TCM_SETITEMEXTRA* = 4878 - TCM_SETITEMSIZE* = 4905 - TCM_SETPADDING* = 4907 - TCM_SETTOOLTIPS* = 4910 - # Tab control notifications - TCN_KEYDOWN* = -550 - TCN_SELCHANGE* = -551 - TCN_SELCHANGING* = -552 - # Tool tip control - TTM_ACTIVATE* = 1025 - TTM_ADDTOOLW* = 1074 - TTM_DELTOOLW* = 1075 - TTM_ENUMTOOLSW* = 1082 - TTM_GETCURRENTTOOLW* = 1083 - TTM_GETTEXTW* = 1080 - TTM_GETTOOLINFOW* = 1077 - TTM_HITTESTW* = 1079 - TTM_NEWTOOLRECTW* = 1076 - TTM_SETTOOLINFOW* = 1078 - TTM_UPDATETIPTEXTW* = 1081 - TTM_ADDTOOLA* = 1028 - TTM_DELTOOLA* = 1029 - TTM_ENUMTOOLSA* = 1038 - TTM_GETCURRENTTOOLA* = 1039 - TTM_GETTEXTA* = 1035 - TTM_GETTOOLINFOA* = 1032 - TTM_HITTESTA* = 1034 - TTM_NEWTOOLRECTA* = 1030 - TTM_SETTOOLINFOA* = 1033 - TTM_UPDATETIPTEXTA* = 1036 - -when defined(winUnicode): - const - TTM_ADDTOOL* = TTM_ADDTOOLW - TTM_DELTOOL* = TTM_DELTOOLW - TTM_ENUMTOOLS* = TTM_ENUMTOOLSW - TTM_GETCURRENTTOOL* = TTM_GETCURRENTTOOLW - TTM_GETTEXT* = TTM_GETTEXTW - TTM_GETTOOLINFO* = TTM_GETTOOLINFOW - TTM_HITTEST* = TTM_HITTESTW - TTM_NEWTOOLRECT* = TTM_NEWTOOLRECTW - TTM_SETTOOLINFO* = TTM_SETTOOLINFOW - TTM_UPDATETIPTEXT* = TTM_UPDATETIPTEXTW -else: - const - TTM_ADDTOOL* = TTM_ADDTOOLA - TTM_DELTOOL* = TTM_DELTOOLA - TTM_ENUMTOOLS* = TTM_ENUMTOOLSA - TTM_GETCURRENTTOOL* = TTM_GETCURRENTTOOLA - TTM_GETTEXT* = TTM_GETTEXTA - TTM_GETTOOLINFO* = TTM_GETTOOLINFOA - TTM_HITTEST* = TTM_HITTESTA - TTM_NEWTOOLRECT* = TTM_NEWTOOLRECTA - TTM_SETTOOLINFO* = TTM_SETTOOLINFOA - TTM_UPDATETIPTEXT* = TTM_UPDATETIPTEXTA -# UNICODE - -const - TTM_GETTOOLCOUNT* = 1037 - TTM_RELAYEVENT* = 1031 - TTM_SETDELAYTIME* = 1027 - TTM_WINDOWFROMPOINT* = 1040 - # Tool tip control notification - TTN_NEEDTEXTW* = -530 - TTN_NEEDTEXTA* = -520 - -when defined(winUnicode): - const - TTN_NEEDTEXT* = TTN_NEEDTEXTW -else: - const - TTN_NEEDTEXT* = TTN_NEEDTEXTA -# UNICODE - -const - TTN_POP* = -522 - TTN_SHOW* = -521 - # Tree view control - TVM_CREATEDRAGIMAGE* = 4370 - TVM_DELETEITEM* = 4353 - TVM_ENDEDITLABELNOW* = 4374 - TVM_ENSUREVISIBLE* = 4372 - TVM_EXPAND* = 4354 - TVM_GETCOUNT* = 4357 - TVM_GETEDITCONTROL* = 4367 - TVM_GETIMAGELIST* = 4360 - TVM_GETINDENT* = 4358 - TVM_GETITEMRECT* = 4356 - TVM_GETNEXTITEM* = 4362 - TVM_GETVISIBLECOUNT* = 4368 - TVM_HITTEST* = 4369 - TVM_EDITLABELW* = 4417 - TVM_GETISEARCHSTRINGW* = 4416 - TVM_GETITEMW* = 4414 - TVM_INSERTITEMW* = 4402 - TVM_SETITEMW* = 4415 - TVM_EDITLABELA* = 4366 - TVM_GETISEARCHSTRINGA* = 4375 - TVM_GETITEMA* = 4364 - TVM_INSERTITEMA* = 4352 - TVM_SETITEMA* = 4365 - -when defined(winUnicode): - const - TVM_EDITLABEL* = TVM_EDITLABELW - TVM_GETISEARCHSTRING* = TVM_GETISEARCHSTRINGW - TVM_GETITEM* = TVM_GETITEMW - TVM_INSERTITEM* = TVM_INSERTITEMW - TVM_SETITEM* = TVM_SETITEMW -else: - const - TVM_EDITLABEL* = TVM_EDITLABELA - TVM_GETISEARCHSTRING* = TVM_GETISEARCHSTRINGA - TVM_GETITEM* = TVM_GETITEMA - TVM_INSERTITEM* = TVM_INSERTITEMA - TVM_SETITEM* = TVM_SETITEMA -# UNICODE - -const - TVM_SELECTITEM* = 4363 - TVM_SETIMAGELIST* = 4361 - TVM_SETINDENT* = 4359 - TVM_SORTCHILDREN* = 4371 - TVM_SORTCHILDRENCB* = 4373 - # Tree view control notification - TVN_KEYDOWN* = -412 - TVN_BEGINDRAGW* = -456 - TVN_BEGINLABELEDITW* = -459 - TVN_BEGINRDRAGW* = -457 - TVN_DELETEITEMW* = -458 - TVN_ENDLABELEDITW* = -460 - TVN_GETDISPINFOW* = -452 - TVN_ITEMEXPANDEDW* = -455 - TVN_ITEMEXPANDINGW* = -454 - TVN_SELCHANGEDW* = -451 - TVN_SELCHANGINGW* = -450 - TVN_SETDISPINFOW* = -453 - TVN_BEGINDRAGA* = -407 - TVN_BEGINLABELEDITA* = -410 - TVN_BEGINRDRAGA* = -408 - TVN_DELETEITEMA* = -409 - TVN_ENDLABELEDITA* = -411 - TVN_GETDISPINFOA* = -403 - TVN_ITEMEXPANDEDA* = -406 - TVN_ITEMEXPANDINGA* = -405 - TVN_SELCHANGEDA* = -402 - TVN_SELCHANGINGA* = -401 - TVN_SETDISPINFOA* = -404 - -when defined(winUnicode): - const - TVN_BEGINDRAG* = TVN_BEGINDRAGW - TVN_BEGINLABELEDIT* = TVN_BEGINLABELEDITW - TVN_BEGINRDRAG* = TVN_BEGINRDRAGW - TVN_DELETEITEM* = TVN_DELETEITEMW - TVN_ENDLABELEDIT* = TVN_ENDLABELEDITW - TVN_GETDISPINFO* = TVN_GETDISPINFOW - TVN_ITEMEXPANDED* = TVN_ITEMEXPANDEDW - TVN_ITEMEXPANDING* = TVN_ITEMEXPANDINGW - TVN_SELCHANGED* = TVN_SELCHANGEDW - TVN_SELCHANGING* = TVN_SELCHANGINGW - TVN_SETDISPINFO* = TVN_SETDISPINFOW -else: - const - TVN_BEGINDRAG* = TVN_BEGINDRAGA - TVN_BEGINLABELEDIT* = TVN_BEGINLABELEDITA - TVN_BEGINRDRAG* = TVN_BEGINRDRAGA - TVN_DELETEITEM* = TVN_DELETEITEMA - TVN_ENDLABELEDIT* = TVN_ENDLABELEDITA - TVN_GETDISPINFO* = TVN_GETDISPINFOA - TVN_ITEMEXPANDED* = TVN_ITEMEXPANDEDA - TVN_ITEMEXPANDING* = TVN_ITEMEXPANDINGA - TVN_SELCHANGED* = TVN_SELCHANGEDA - TVN_SELCHANGING* = TVN_SELCHANGINGA - TVN_SETDISPINFO* = TVN_SETDISPINFOA -# UNICODE - -const - # Up/down control - UDM_GETACCEL* = 1132 - UDM_GETBASE* = 1134 - UDM_GETBUDDY* = 1130 - UDM_GETPOS* = 1128 - UDM_GETPOS32* = 1138 - UDM_GETRANGE* = 1126 - UDM_GETRANGE32* = 1136 - UDM_SETACCEL* = 1131 - UDM_SETBASE* = 1133 - UDM_SETBUDDY* = 1129 - UDM_SETPOS* = 1127 - UDM_SETPOS32* = 1137 - UDM_SETRANGE* = 1125 - UDM_SETRANGE32* = 1135 - # Up/down control notification - UDN_DELTAPOS* = -722 - # Window messages - WM_ACTIVATE* = 6 - WM_ACTIVATEAPP* = 28 - WM_ASKCBFORMATNAME* = 780 - WM_CANCELJOURNAL* = 75 - WM_CANCELMODE* = 31 - WM_CAPTURECHANGED* = 533 - WM_CHANGECBCHAIN* = 781 - WM_CHAR* = 258 - WM_CHARTOITEM* = 47 - WM_CHILDACTIVATE* = 34 - WM_CHOOSEFONT_GETLOGFONT* = 1025 - WM_CHOOSEFONT_SETLOGFONT* = 1125 - WM_CHOOSEFONT_SETFLAGS* = 1126 - WM_CLEAR* = 771 - WM_CLOSE* = 16 - WM_COMMAND* = 273 - WM_COMPACTING* = 65 - WM_COMPAREITEM* = 57 - WM_CONTEXTMENU* = 123 - WM_COPY* = 769 - WM_COPYDATA* = 74 - WM_CREATE* = 1 - WM_CTLCOLORBTN* = 309 - WM_CTLCOLORDLG* = 310 - WM_CTLCOLOREDIT* = 307 - WM_CTLCOLORLISTBOX* = 308 - WM_CTLCOLORMSGBOX* = 306 - WM_CTLCOLORSCROLLBAR* = 311 - WM_CTLCOLORSTATIC* = 312 - WM_CUT* = 768 - WM_DEADCHAR* = 259 - WM_DELETEITEM* = 45 - WM_DESTROY* = 2 - WM_DESTROYCLIPBOARD* = 775 - WM_DEVICECHANGE* = 537 - WM_DEVMODECHANGE* = 27 - WM_DISPLAYCHANGE* = 126 - WM_DRAWCLIPBOARD* = 776 - WM_DRAWITEM* = 43 - WM_DROPFILES* = 563 - WM_ENABLE* = 10 - WM_ENDSESSION* = 22 - WM_ENTERIDLE* = 289 - WM_ENTERMENULOOP* = 529 - WM_ENTERSIZEMOVE* = 561 - WM_ERASEBKGND* = 20 - WM_EXITMENULOOP* = 530 - WM_EXITSIZEMOVE* = 562 - WM_FONTCHANGE* = 29 - WM_GETDLGCODE* = 135 - WM_GETFONT* = 49 - WM_GETHOTKEY* = 51 - WM_GETICON* = 127 - WM_GETMINMAXINFO* = 36 - WM_GETTEXT* = 13 - WM_GETTEXTLENGTH* = 14 - WM_HELP* = 83 - WM_HOTKEY* = 786 - WM_HSCROLL* = 276 - WM_HSCROLLCLIPBOARD* = 782 - WM_ICONERASEBKGND* = 39 - WM_IME_CHAR* = 646 - WM_IME_COMPOSITION* = 271 - WM_IME_COMPOSITIONFULL* = 644 - WM_IME_CONTROL* = 643 - WM_IME_ENDCOMPOSITION* = 270 - WM_IME_KEYDOWN* = 656 - WM_IME_KEYUP* = 657 - WM_IME_NOTIFY* = 642 - WM_IME_SELECT* = 645 - WM_IME_SETCONTEXT* = 641 - WM_IME_STARTCOMPOSITION* = 269 - WM_INITDIALOG* = 272 - WM_INITMENU* = 278 - WM_INITMENUPOPUP* = 279 - WM_INPUTLANGCHANGE* = 81 - WM_INPUTLANGCHANGEREQUEST* = 80 - WM_KEYDOWN* = 256 - WM_KEYUP* = 257 - WM_KILLFOCUS* = 8 - WM_LBUTTONDBLCLK* = 515 - WM_LBUTTONDOWN* = 513 - WM_LBUTTONUP* = 514 - WM_MBUTTONDBLCLK* = 521 - WM_MBUTTONDOWN* = 519 - WM_MBUTTONUP* = 520 - WM_MDIACTIVATE* = 546 - WM_MDICASCADE* = 551 - WM_MDICREATE* = 544 - WM_MDIDESTROY* = 545 - WM_MDIGETACTIVE* = 553 - WM_MDIICONARRANGE* = 552 - WM_MDIMAXIMIZE* = 549 - WM_MDINEXT* = 548 - WM_MDIREFRESHMENU* = 564 - WM_MDIRESTORE* = 547 - WM_MDISETMENU* = 560 - WM_MDITILE* = 550 - WM_MEASUREITEM* = 44 - WM_MENUCHAR* = 288 - WM_MENUSELECT* = 287 - WM_MOUSEACTIVATE* = 33 - WM_MOUSEMOVE* = 512 - WM_MOUSEWHEEL* = 522 - WM_MOUSEHOVER* = 673 - WM_MOUSELEAVE* = 675 - WM_MOVE* = 3 - WM_MOVING* = 534 - WM_NCACTIVATE* = 134 - WM_NCCALCSIZE* = 131 - WM_NCCREATE* = 129 - WM_NCDESTROY* = 130 - WM_NCHITTEST* = 132 - WM_NCLBUTTONDBLCLK* = 163 - WM_NCLBUTTONDOWN* = 161 - WM_NCLBUTTONUP* = 162 - WM_NCMBUTTONDBLCLK* = 169 - WM_NCMBUTTONDOWN* = 167 - WM_NCMBUTTONUP* = 168 - WM_NCMOUSEMOVE* = 160 - WM_NCPAINT* = 133 - WM_NCRBUTTONDBLCLK* = 166 - WM_NCRBUTTONDOWN* = 164 - WM_NCRBUTTONUP* = 165 - WM_NEXTDLGCTL* = 40 - WM_NOTIFY* = 78 - WM_NOTIFYFORMAT* = 85 - WM_NULL* = 0 - WM_PAINT* = 15 - WM_PAINTCLIPBOARD* = 777 - WM_PAINTICON* = 38 - WM_PALETTECHANGED* = 785 - WM_PALETTEISCHANGING* = 784 - WM_PARENTNOTIFY* = 528 - WM_PASTE* = 770 - WM_PENWINFIRST* = 896 - WM_PENWINLAST* = 911 - WM_POWER* = 72 - WM_POWERBROADCAST* = 536 - WM_PRINT* = 791 - WM_PRINTCLIENT* = 792 - WM_PSD_ENVSTAMPRECT* = 1029 - WM_PSD_FULLPAGERECT* = 1025 - WM_PSD_GREEKTEXTRECT* = 1028 - WM_PSD_MARGINRECT* = 1027 - WM_PSD_MINMARGINRECT* = 1026 - WM_PSD_PAGESETUPDLG* = 1024 - WM_PSD_YAFULLPAGERECT* = 1030 - WM_QUERYDRAGICON* = 55 - WM_QUERYENDSESSION* = 17 - WM_QUERYNEWPALETTE* = 783 - WM_QUERYOPEN* = 19 - WM_QUEUESYNC* = 35 - WM_QUIT* = 18 - WM_RBUTTONDBLCLK* = 518 - WM_RBUTTONDOWN* = 516 - WM_RBUTTONUP* = 517 - WM_RENDERALLFORMATS* = 774 - WM_RENDERFORMAT* = 773 - WM_SETCURSOR* = 32 - WM_SETFOCUS* = 7 - WM_SETFONT* = 48 - WM_SETHOTKEY* = 50 - WM_SETICON* = 128 - WM_SETREDRAW* = 11 - WM_SETTEXT* = 12 - WM_SETTINGCHANGE* = 26 - WM_SHOWWINDOW* = 24 - WM_SIZE* = 5 - WM_SIZECLIPBOARD* = 779 - WM_SIZING* = 532 - WM_SPOOLERSTATUS* = 42 - WM_STYLECHANGED* = 125 - WM_STYLECHANGING* = 124 - WM_SYSCHAR* = 262 - WM_SYSCOLORCHANGE* = 21 - WM_SYSCOMMAND* = 274 - WM_SYSDEADCHAR* = 263 - WM_SYSKEYDOWN* = 260 - WM_SYSKEYUP* = 261 - WM_TCARD* = 82 - WM_TIMECHANGE* = 30 - WM_TIMER* = 275 - WM_UNDO* = 772 - WM_USER* = 1024 - WM_USERCHANGED* = 84 - WM_VKEYTOITEM* = 46 - WM_VSCROLL* = 277 - WM_VSCROLLCLIPBOARD* = 778 - WM_WINDOWPOSCHANGED* = 71 - WM_WINDOWPOSCHANGING* = 70 - WM_WININICHANGE* = 26 - # Window message ranges - WM_KEYFIRST* = 256 - WM_KEYLAST* = 264 - WM_MOUSEFIRST* = 512 - WM_MOUSELAST* = 525 - WM_XBUTTONDOWN* = 523 - WM_XBUTTONUP* = 524 - WM_XBUTTONDBLCLK* = 525 - -when defined(cpu64): - type - HALFLRESULT* = DWORD - HALFPARAM* = DWORD - HALFPARAMBOOL* = WINBOOL -else: - type - HALFLRESULT* = int16 - HALFPARAM* = int16 - HALFPARAMBOOL* = WORDBOOL -type - MSG* {.final, pure.} = object - hwnd*: HWND - message*: WINUINT - wParam*: WPARAM - lParam*: LPARAM - time*: DWORD - pt*: POINT - - LPMSG* = ptr MSG - TMSG* = MSG - PMSG* = ptr MSG - PMessage* = ptr TMessage - TMessage* {.final, pure.} = object #fields according to ICS - msg*: WINUINT - wParam*: WPARAM - lParam*: LPARAM - Result*: LRESULT - - TWMSize* {.final, pure.} = object - Msg*: WINUINT - SizeType*: WPARAM - Width*: HALFPARAM - Height*: HALFPARAM - Result*: LRESULT - - TWMNoParams* {.final, pure.} = object - Msg*: WINUINT - Unused*: array[0..3, HALFPARAM] - Result*: LRESULT - - TWMCancelMode* = TWMNoParams - TWMNCDestroy* = TWMNoParams - TWMDestroy* = TWMNoParams - TWMClose* = TWMNoParams - TWMQueryUIState* = TWMNoParams - TWMUIState* {.final, pure.} = object - Msg*: WINUINT - Action*: int16 - Flags*: int16 - Unused*: HRESULT - - TWMChangeUIState* = TWMUIState - TWMUpdateUIState* = TWMUIState - TWMKey* {.final, pure.} = object - Msg*: WINUINT - CharCode*: int16 - Unused*: int16 - KeyData*: int32 - Result*: LRESULT - - TWMKeyDown* = TWMKey - TWMKeyUp* = TWMKey - TWMChar* = TWMKey - TWMSysChar* = TWMKey - TWMSysKeyDown* = TWMKey - TWMSysKeyUp* = TWMKey - TWMMenuChar* {.final, pure.} = object - Msg*: WINUINT - User*: char - MenuFlag*: int16 - Menu*: HMENU - Result*: LRESULT - - TWMGetDlgCode* = TWMNoParams - TWMFontChange* = TWMNoParams - TWMGetFont* = TWMNoParams - TWMSysColorChange* = TWMNoParams - TWMQueryDragIcon* = TWMNoParams - TWMScroll* {.final, pure.} = object - Msg*: WINUINT - ScrollCode*: HALFPARAM - Pos*: HALFPARAM - ScrollBar*: HWND - Result*: LRESULT - - TWMHScroll* = TWMScroll - TWMVScroll* = TWMScroll - TWMGetText* {.final, pure.} = object - Msg*: WINUINT - TextMax*: LPARAM - Text*: cstring - Result*: LRESULT - - TWMGetTextLength* = TWMNoParams - TWMKillFocus* {.final, pure.} = object - Msg*: WINUINT - FocusedWnd*: HWND - UnUsed*: WPARAM - Result*: LRESULT - - TWMSetCursor* {.final, pure.} = object - Msg*: WINUINT - CursorWnd*: HWND - HitTest*: HALFPARAM - MouseMsg*: HALFPARAM - Result*: LRESULT - - TWMSetFocus* {.final, pure.} = object - Msg*: WINUINT - FocusedWnd*: HWND - Unused*: WPARAM - Result*: LRESULT - - TWMSetFont* {.final, pure.} = object - Msg*: WINUINT - Font*: HFONT - Redraw*: HALFPARAMBOOL - Unused*: HALFPARAM - Result*: LRESULT - - TWMShowWindow* {.final, pure.} = object - Msg*: WINUINT - Show*: HALFPARAMBOOL - Unused*: HALFPARAM - Status*: WPARAM - Result*: LRESULT - - TWMEraseBkgnd* {.final, pure.} = object - Msg*: WINUINT - DC*: HDC - Unused*: LPARAM - Result*: LRESULT - - TWMNCHitTest* {.final, pure.} = object - Msg*: WINUINT - Unused*: int32 - Pos*: SmallPoint - Result*: LRESULT - - TWMMouse* {.final, pure.} = object - Msg*: WINUINT - Keys*: int32 - Pos*: SmallPoint - Result*: LRESULT - - TWMLButtonDblClk* = TWMMouse - TWMLButtonDown* = TWMMouse - TWMLButtonUp* = TWMMouse - TWMMButtonDblClk* = TWMMouse - TWMMButtonDown* = TWMMouse - TWMMButtonUp* = TWMMouse - TWMMouseWheel* {.final, pure.} = object - Msg*: WINUINT - Keys*: int16 - WheelDelta*: int16 - Pos*: SmallPoint - Result*: LRESULT - - TWMNCHitMessage* {.final, pure.} = object - Msg*: WINUINT - HitTest*: int32 - XCursor*: int16 - YCursor*: int16 - Result*: LRESULT - - TWMNCLButtonDblClk* = TWMNCHitMessage - TWMNCLButtonDown* = TWMNCHitMessage - TWMNCLButtonUp* = TWMNCHitMessage - TWMNCMButtonDblClk* = TWMNCHitMessage - TWMNCMButtonDown* = TWMNCHitMessage - TWMNCMButtonUp* = TWMNCHitMessage - TWMNCMouseMove* = TWMNCHitMessage - TWMRButtonDblClk* = TWMMouse - TWMRButtonDown* = TWMMouse - TWMRButtonUp* = TWMMouse - TWMMouseMove* = TWMMouse - TWMPaint* {.final, pure.} = object - Msg*: WINUINT - DC*: HDC - Unused*: int32 - Result*: LRESULT - - TWMCommand* {.final, pure.} = object - Msg*: WINUINT - ItemID*: int16 - NotifyCode*: int16 - Ctl*: HWND - Result*: LRESULT - - TWMNotify* {.final, pure.} = object - Msg*: WINUINT - IDCtrl*: int32 - NMHdr*: PNMHdr - Result*: LRESULT - - TWMPrint* {.final, pure.} = object - Msg*: WINUINT - DC*: HDC - Flags*: int - Result*: LRESULT - - TWMPrintClient* = TWMPrint - TWMWinIniChange* {.final, pure.} = object - Msg*: WINUINT - Unused*: int - Section*: cstring - Result*: LRESULT - - TWMContextMenu* {.final, pure.} = object - Msg*: WINUINT - hWnd*: HWND - Pos*: SmallPoint - Result*: LRESULT - - TWMNCCalcSize* {.final, pure.} = object - Msg*: WINUINT - CalcValidRects*: WINBOOL - CalcSize_Params*: PNCCalcSizeParams - Result*: LRESULT - - TWMCharToItem* {.final, pure.} = object - Msg*: WINUINT - Key*: int16 - CaretPos*: int16 - ListBox*: HWND - Result*: LRESULT - - TWMVKeyToItem* = TWMCharToItem - TMyEventRange = range[0'i16..16000'i16] - TWMParentNotify* {.final, pure.} = object - Msg*: WINUINT - case Event*: TMyEventRange - of TMyEventRange(WM_CREATE), TMyEventRange(WM_DESTROY): - ChildID*: int16 - ChildWnd*: HWnd - - of TMyEventRange(WM_LBUTTONDOWN), - TMyEventRange(WM_MBUTTONDOWN), - TMyEventRange(WM_RBUTTONDOWN): - Value*: int16 - XPos*: int16 - YPos*: int16 - - else: - Value1*: int16 - Value2*: int32 - Result*: LRESULT - - TWMSysCommand* {.final, pure.} = object - Msg*: WINUINT - CmdType*: int32 - XPos*: int16 - YPos*: int16 - Result*: LRESULT - # case CmdType*: int32 - # of SC_HOTKEY: - # ActivateWnd*: HWND - # of SC_CLOSE, SC_HSCROLL, SC_MAXIMIZE, SC_MINIMIZE, SC_MOUSEMENU, SC_MOVE, - # SC_NEXTWINDOW, SC_PREVWINDOW, SC_RESTORE, SC_SCREENSAVE, SC_SIZE, - # SC_TASKLIST, SC_VSCROLL: - # XPos*: int16 - # YPos*: int16 - # Result*: LRESULT - # else: # of SC_KEYMENU: - # Key*: int16 - - TWMMove* {.final, pure.} = object - Msg*: WINUINT - Unused*: int - Pos*: SmallPoint - Result*: LRESULT - - TWMWindowPosMsg* {.final, pure.} = object - Msg*: WINUINT - Unused*: int - WindowPos*: PWindowPos - Result*: LRESULT - - TWMWindowPosChanged* = TWMWindowPosMsg - TWMWindowPosChanging* = TWMWindowPosMsg - TWMCompareItem* {.final, pure.} = object - Msg*: WINUINT - Ctl*: HWnd - CompareItemStruct*: PCompareItemStruct - Result*: LRESULT - - TWMDeleteItem* {.final, pure.} = object - Msg*: WINUINT - Ctl*: HWND - DeleteItemStruct*: PDeleteItemStruct - Result*: LRESULT - - TWMDrawItem* {.final, pure.} = object - Msg*: WINUINT - Ctl*: HWND - DrawItemStruct*: PDrawItemStruct - Result*: LRESULT - - TWMMeasureItem* {.final, pure.} = object - Msg*: WINUINT - IDCtl*: HWnd - MeasureItemStruct*: PMeasureItemStruct - Result*: LRESULT - - TWMNCCreate* {.final, pure.} = object - Msg*: WINUINT - Unused*: int - CreateStruct*: PCreateStruct - Result*: LRESULT - - TWMInitMenuPopup* {.final, pure.} = object - Msg*: WINUINT - MenuPopup*: HMENU - Pos*: int16 - SystemMenu*: WordBool - Result*: LRESULT - - TWMMenuSelect* {.final, pure.} = object - Msg*: WINUINT - IDItem*: int16 - MenuFlag*: int16 - Menu*: HMENU - Result*: LRESULT - - TWMActivate* {.final, pure.} = object - Msg*: WINUINT - Active*: int16 - Minimized*: WordBool - ActiveWindow*: HWND - Result*: LRESULT - - TWMQueryEndSession* {.final, pure.} = object - Msg*: WINUINT - Source*: int32 - Unused*: int32 - Result*: LRESULT - - TWMMDIActivate* {.final, pure.} = object - Msg*: WINUINT - DeactiveWnd*: HWND - ActiveWnd*: HWND - Result*: LRESULT - - TWMNextDlgCtl* {.final, pure.} = object - Msg*: WINUINT - CtlFocus*: int32 - Handle*: WordBool - Unused*: int16 - Result*: LRESULT - - TWMHelp* {.final, pure.} = object - Msg*: WINUINT - Unused*: int - HelpInfo*: PHelpInfo - Result*: LRESULT - - TWMGetMinMaxInfo* {.final, pure.} = object - Msg*: WINUINT - Unused*: int - MinMaxInfo*: PMinMaxInfo - Result*: LRESULT - - TWMSettingChange* {.final, pure.} = object - Msg*: WINUINT - Flag*: int - Section*: cstring - Result*: LRESULT - - TWMCreate* {.final, pure.} = object - Msg*: WINUINT - Unused*: int - CreateStruct*: PCreateStruct - Result*: LRESULT - - TWMCtlColor* {.final, pure.} = object - Msg*: WINUINT - ChildDC*: HDC - ChildWnd*: HWND - Result*: LRESULT - - TWMCtlColorScrollbar* = TWMCtlColor - TWMCtlColorStatic* = TWMCtlColor - TWMCtlColorBtn* = TWMCtlColor - TWMCtlColorListbox* = TWMCtlColor - TWMCtlColorMsgbox* = TWMCtlColor - TWMCtlColorDlg* = TWMCtlColor - TWMCtlColorEdit* = TWMCtlColor - TWMInitDialog* {.final, pure.} = object - Msg*: WINUINT - Focus*: HWND - InitParam*: int32 - Result*: LRESULT - - TWMNCPaint* {.final, pure.} = object - Msg*: WINUINT - RGN*: HRGN - Unused*: int32 - Result*: LRESULT - - TWMSetText* {.final, pure.} = object - Msg*: WINUINT - Unused*: int32 - Text*: cstring - Result*: LRESULT - - TWMSizeClipboard* {.final, pure.} = object - Msg*: WINUINT - Viewer*: HWND - RC*: Handle - Result*: LRESULT - - TWMSpoolerStatus* {.final, pure.} = object - Msg*: WINUINT - JobStatus*: LPARAM - JobsLeft*: WPARAM - Unused*: WPARAM - Result*: LRESULT - - TWMStyleChange* {.final, pure.} = object - Msg*: WINUINT - StyleType*: LPARAM - StyleStruct*: PStyleStruct - Result*: LRESULT - - TWMStyleChanged* = TWMStyleChange - TWMStyleChanging* = TWMStyleChange - TWMSysDeadChar* {.final, pure.} = object - Msg*: WINUINT - CharCode*: WPARAM - Unused*: WPARAM - KeyData*: LPARAM - Result*: LRESULT - - TWMSystemError* {.final, pure.} = object - Msg*: WINUINT - ErrSpec*: WPARAM - Unused*: LPARAM - Result*: LRESULT - - TWMTimeChange* = TWMNoParams - TWMTimer* {.final, pure.} = object - Msg*: WINUINT - TimerID*: LPARAM - TimerProc*: FarProc - Result*: LRESULT - - TWMUndo* = TWMNoParams - TWMVScrollClipboard* {.final, pure.} = object - Msg*: WINUINT - Viewer*: HWND - ScollCode*: WPARAM - ThumbPos*: WPARAM - Result*: LRESULT - - TWMDisplayChange* {.final, pure.} = object - Msg*: WINUINT - BitsPerPixel*: int - Width*: WPARAM - Height*: WPARAM - Result*: LRESULT - - TWMDropFiles* {.final, pure.} = object - Msg*: WINUINT - Drop*: HANDLE - Unused*: LPARAM - Result*: LRESULT - - TWMEnable* {.final, pure.} = object - Msg*: int - Enabled*: WINBOOL - Unused*: int32 - Result*: int32 - - TWMMouseActivate* {.final, pure.} = object - Msg*: int - TopLevel*: HWND - HitTestCode*: int16 - MouseMsg*: int16 - Result*: int32 - - -proc GetBinaryTypeA*(lpApplicationName: LPCSTR, lpBinaryType: LPDWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetBinaryTypeA".} - -proc GetShortPathNameA*(lpszLongPath: LPCSTR, lpszShortPath: LPSTR, - cchBuffer: DWORD): DWORD{.stdcall, - dynlib: "kernel32", importc.} -proc GetEnvironmentStringsA*(): LPSTR{.stdcall, dynlib: "kernel32", importc.} -proc FreeEnvironmentStringsA*(para1: LPSTR): WINBOOL{.stdcall, dynlib: "kernel32", importc.} -proc FormatMessageA*(dwFlags: DWORD, lpSource: LPCVOID, dwMessageId: DWORD, - dwLanguageId: DWORD, lpBuffer: LPSTR, nSize: DWORD, - Arguments: va_list): DWORD{.stdcall,dynlib: "kernel32", importc.} -proc CreateMailslotA*(lpName: LPCSTR, nMaxMessageSize: DWORD, - lReadTimeout: DWORD, - lpSecurityAttributes: LPSECURITY_ATTRIBUTES): HANDLE{. - stdcall, dynlib: "kernel32", importc.} -proc lstrcmpA*(lpString1: LPCSTR, lpString2: LPCSTR): int32{.stdcall, - dynlib: "kernel32", importc.} -proc lstrcmpiA*(lpString1: LPCSTR, lpString2: LPCSTR): int32{.stdcall, dynlib: "kernel32", importc.} -proc lstrcpynA*(lpString1: LPSTR, lpString2: LPCSTR, iMaxLength: int32): LPSTR{. - stdcall, dynlib: "kernel32", importc.} -proc CreateMutexA*(lpMutexAttributes: LPSECURITY_ATTRIBUTES, - bInitialOwner: WINBOOL, lpName: LPCSTR): HANDLE{.stdcall, - dynlib: "kernel32", importc.} -proc OpenMutexA*(dwDesiredAccess: DWORD, bInheritHandle: WINBOOL, lpName: LPCSTR): HANDLE{. - stdcall, dynlib: "kernel32", importc.} -proc CreateEventA*(lpEventAttributes: LPSECURITY_ATTRIBUTES, - bManualReset: WINBOOL, bInitialState: WINBOOL, lpName: LPCSTR): HANDLE{. - stdcall, dynlib: "kernel32", importc.} -proc OpenEventA*(dwDesiredAccess: DWORD, bInheritHandle: WINBOOL, lpName: LPCSTR): HANDLE{. - stdcall, dynlib: "kernel32", importc.} -proc CreateSemaphoreA*(lpSemaphoreAttributes: LPSECURITY_ATTRIBUTES, - lInitialCount: LONG, lMaximumCount: LONG, lpName: LPCSTR): HANDLE{. - stdcall, dynlib: "kernel32", importc.} -proc OpenSemaphoreA*(dwDesiredAccess: DWORD, bInheritHandle: WINBOOL, - lpName: LPCSTR): HANDLE{.stdcall, - dynlib: "kernel32", importc.} -proc CreateFileMappingA*(hFile: HANDLE, - lpFileMappingAttributes: LPSECURITY_ATTRIBUTES, - flProtect: DWORD, dwMaximumSizeHigh: DWORD, - dwMaximumSizeLow: DWORD, lpName: LPCSTR): HANDLE{. - stdcall, dynlib: "kernel32", importc.} -proc OpenFileMappingA*(dwDesiredAccess: DWORD, bInheritHandle: WINBOOL, - lpName: LPCSTR): HANDLE{.stdcall, - dynlib: "kernel32", importc.} -proc GetLogicalDriveStringsA*(nBufferLength: DWORD, lpBuffer: LPSTR): DWORD{. - stdcall, dynlib: "kernel32", importc.} -proc LoadLibraryA*(lpLibFileName: LPCSTR): HINST{.stdcall, - dynlib: "kernel32", importc.} -proc LoadLibraryExA*(lpLibFileName: LPCSTR, hFile: HANDLE, dwFlags: DWORD): HINST{. - stdcall, dynlib: "kernel32", importc.} -proc GetModuleFileNameA*(hModule: HINST, lpFilename: LPSTR, nSize: DWORD): DWORD{. - stdcall, dynlib: "kernel32", importc.} -proc GetModuleHandleA*(lpModuleName: LPCSTR): HMODULE{.stdcall, - dynlib: "kernel32", importc.} -proc FatalAppExitA*(uAction: WINUINT, lpMessageText: LPCSTR){.stdcall, - dynlib: "kernel32", importc.} -proc GetCommandLineA*(): LPSTR{.stdcall, dynlib: "kernel32", importc.} -proc GetEnvironmentVariableA*(lpName: LPCSTR, lpBuffer: LPSTR, nSize: DWORD): DWORD{. - stdcall, dynlib: "kernel32", importc.} -proc SetEnvironmentVariableA*(lpName: LPCSTR, lpValue: LPCSTR): WINBOOL{.stdcall, - dynlib: "kernel32", importc.} -proc ExpandEnvironmentStringsA*(lpSrc: LPCSTR, lpDst: LPSTR, nSize: DWORD): DWORD{. - stdcall, dynlib: "kernel32", importc.} -proc OutputDebugStringA*(lpOutputString: LPCSTR){.stdcall, - dynlib: "kernel32", importc.} -proc FindResourceA*(hModule: HINST, lpName: LPCSTR, lpType: LPCSTR): HRSRC{. - stdcall, dynlib: "kernel32", importc.} -proc FindResourceExA*(hModule: HINST, lpType: LPCSTR, lpName: LPCSTR, - wLanguage: int16): HRSRC{.stdcall, - dynlib: "kernel32", importc.} -proc EnumResourceTypesA*(hModule: HINST, lpEnumFunc: ENUMRESTYPEPROC, - lParam: LONG): WINBOOL{.stdcall, - dynlib: "kernel32", importc.} -proc EnumResourceNamesA*(hModule: HINST, lpType: LPCSTR, - lpEnumFunc: ENUMRESNAMEPROC, lParam: LONG): WINBOOL{. - stdcall, dynlib: "kernel32", importc.} -proc EnumResourceLanguagesA*(hModule: HINST, lpType: LPCSTR, lpName: LPCSTR, - lpEnumFunc: ENUMRESLANGPROC, lParam: LONG): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "EnumResourceLanguagesA".} - -proc BeginUpdateResourceA*(pFileName: LPCSTR, bDeleteExistingResources: WINBOOL): HANDLE{. - stdcall, dynlib: "kernel32", importc: "BeginUpdateResourceA".} - -proc UpdateResourceA*(hUpdate: HANDLE, lpType: LPCSTR, lpName: LPCSTR, - wLanguage: int16, lpData: LPVOID, cbData: DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "UpdateResourceA".} -proc EndUpdateResourceA*(hUpdate: HANDLE, fDiscard: WINBOOL): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "EndUpdateResourceA".} -proc GlobalAddAtomA*(lpString: LPCSTR): ATOM{.stdcall, dynlib: "kernel32", - importc: "GlobalAddAtomA".} -proc GlobalFindAtomA*(lpString: LPCSTR): ATOM{.stdcall, dynlib: "kernel32", - importc: "GlobalFindAtomA".} -proc GlobalGetAtomNameA*(nAtom: ATOM, lpBuffer: LPSTR, nSize: int32): WINUINT{. - stdcall, dynlib: "kernel32", importc: "GlobalGetAtomNameA".} -proc AddAtomA*(lpString: LPCSTR): ATOM{.stdcall, dynlib: "kernel32", - importc: "AddAtomA".} -proc FindAtomA*(lpString: LPCSTR): ATOM{.stdcall, dynlib: "kernel32", - importc: "FindAtomA".} -proc GetAtomNameA*(nAtom: ATOM, lpBuffer: LPSTR, nSize: int32): WINUINT{.stdcall, - dynlib: "kernel32", importc: "GetAtomNameA".} -proc GetProfileIntA*(lpAppName: LPCSTR, lpKeyName: LPCSTR, nDefault: WINT): WINUINT{. - stdcall, dynlib: "kernel32", importc: "GetProfileIntA".} -proc GetProfileStringA*(lpAppName: LPCSTR, lpKeyName: LPCSTR, lpDefault: LPCSTR, - lpReturnedString: LPSTR, nSize: DWORD): DWORD{.stdcall, - dynlib: "kernel32", importc: "GetProfileStringA".} -proc WriteProfileStringA*(lpAppName: LPCSTR, lpKeyName: LPCSTR, lpString: LPCSTR): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "WriteProfileStringA".} -proc GetProfileSectionA*(lpAppName: LPCSTR, lpReturnedString: LPSTR, - nSize: DWORD): DWORD{.stdcall, dynlib: "kernel32", - importc: "GetProfileSectionA".} -proc WriteProfileSectionA*(lpAppName: LPCSTR, lpString: LPCSTR): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "WriteProfileSectionA".} -proc GetPrivateProfileIntA*(lpAppName: LPCSTR, lpKeyName: LPCSTR, - nDefault: WINT, lpFileName: LPCSTR): WINUINT{.stdcall, - dynlib: "kernel32", importc: "GetPrivateProfileIntA".} -proc GetPrivateProfileStringA*(lpAppName: LPCSTR, lpKeyName: LPCSTR, - lpDefault: LPCSTR, lpReturnedString: LPSTR, - nSize: DWORD, lpFileName: LPCSTR): DWORD{. - stdcall, dynlib: "kernel32", importc: "GetPrivateProfileStringA".} - -proc WritePrivateProfileStringA*(lpAppName: LPCSTR, lpKeyName: LPCSTR, - lpString: LPCSTR, lpFileName: LPCSTR): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "WritePrivateProfileStringA".} -proc GetPrivateProfileSectionA*(lpAppName: LPCSTR, lpReturnedString: LPSTR, - nSize: DWORD, lpFileName: LPCSTR): DWORD{. - stdcall, dynlib: "kernel32", importc: "GetPrivateProfileSectionA".} -proc WritePrivateProfileSectionA*(lpAppName: LPCSTR, lpString: LPCSTR, - lpFileName: LPCSTR): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "WritePrivateProfileSectionA".} -proc GetDriveTypeA*(lpRootPathName: LPCSTR): WINUINT{.stdcall, dynlib: "kernel32", - importc: "GetDriveTypeA".} -proc GetSystemDirectoryA*(lpBuffer: LPSTR, uSize: WINUINT): WINUINT{.stdcall, - dynlib: "kernel32", importc: "GetSystemDirectoryA".} -proc GetTempPathA*(nBufferLength: DWORD, lpBuffer: LPSTR): DWORD{.stdcall, - dynlib: "kernel32", importc: "GetTempPathA".} -proc GetTempFileNameA*(lpPathName: LPCSTR, lpPrefixString: LPCSTR, - uUnique: WINUINT, lpTempFileName: LPSTR): WINUINT{.stdcall, - dynlib: "kernel32", importc: "GetTempFileNameA".} -proc GetWindowsDirectoryA*(lpBuffer: LPSTR, uSize: WINUINT): WINUINT{.stdcall, - dynlib: "kernel32", importc: "GetWindowsDirectoryA".} -proc SetCurrentDirectoryA*(lpPathName: LPCSTR): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "SetCurrentDirectoryA".} -proc GetCurrentDirectoryA*(nBufferLength: DWORD, lpBuffer: LPSTR): DWORD{. - stdcall, dynlib: "kernel32", importc: "GetCurrentDirectoryA".} -proc GetDiskFreeSpaceA*(lpRootPathName: LPCSTR, lpSectorsPerCluster: LPDWORD, - lpBytesPerSector: LPDWORD, - lpNumberOfFreeClusters: LPDWORD, - lpTotalNumberOfClusters: LPDWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetDiskFreeSpaceA".} -proc CreateDirectoryA*(lpPathName: LPCSTR, - - lpSecurityAttributes: LPSECURITY_ATTRIBUTES): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "CreateDirectoryA".} -proc CreateDirectoryExA*(lpTemplateDirectory: LPCSTR, lpNewDirectory: LPCSTR, - lpSecurityAttributes: LPSECURITY_ATTRIBUTES): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "CreateDirectoryExA".} -proc RemoveDirectoryA*(lpPathName: LPCSTR): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "RemoveDirectoryA".} -proc GetFullPathNameA*(lpFileName: LPCSTR, nBufferLength: DWORD, - lpBuffer: LPSTR, lpFilePart: var LPSTR): DWORD{.stdcall, - dynlib: "kernel32", importc: "GetFullPathNameA".} -proc DefineDosDeviceA*(dwFlags: DWORD, lpDeviceName: LPCSTR, - lpTargetPath: LPCSTR): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "DefineDosDeviceA".} -proc QueryDosDeviceA*(lpDeviceName: LPCSTR, lpTargetPath: LPSTR, ucchMax: DWORD): DWORD{. - stdcall, dynlib: "kernel32", importc: "QueryDosDeviceA".} -proc CreateFileA*(lpFileName: LPCSTR, dwDesiredAccess: DWORD, - dwShareMode: DWORD, - lpSecurityAttributes: LPSECURITY_ATTRIBUTES, - dwCreationDisposition: DWORD, dwFlagsAndAttributes: DWORD, - hTemplateFile: HANDLE): HANDLE{.stdcall, dynlib: "kernel32", - importc: "CreateFileA".} -proc SetFileAttributesA*(lpFileName: LPCSTR, dwFileAttributes: DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "SetFileAttributesA".} -proc GetFileAttributesA*(lpFileName: LPCSTR): DWORD{.stdcall, - dynlib: "kernel32", importc: "GetFileAttributesA".} -proc GetCompressedFileSizeA*(lpFileName: LPCSTR, lpFileSizeHigh: LPDWORD): DWORD{. - stdcall, dynlib: "kernel32", importc: "GetCompressedFileSizeA".} -proc DeleteFileA*(lpFileName: LPCSTR): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "DeleteFileA".} -proc SearchPathA*(lpPath: LPCSTR, lpFileName: LPCSTR, lpExtension: LPCSTR, - nBufferLength: DWORD, lpBuffer: LPSTR, lpFilePart: LPSTR): DWORD{. - stdcall, dynlib: "kernel32", importc: "SearchPathA".} -proc CopyFileA*(lpExistingFileName: LPCSTR, lpNewFileName: LPCSTR, - bFailIfExists: WINBOOL): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "CopyFileA".} -proc MoveFileA*(lpExistingFileName: LPCSTR, lpNewFileName: LPCSTR): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "MoveFileA".} -proc MoveFileExA*(lpExistingFileName: LPCSTR, lpNewFileName: LPCSTR, - dwFlags: DWORD): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "MoveFileExA".} -proc CreateNamedPipeA*(lpName: LPCSTR, dwOpenMode: DWORD, dwPipeMode: DWORD, - nMaxInstances: DWORD, nOutBufferSize: DWORD, - nInBufferSize: DWORD, nDefaultTimeOut: DWORD, - lpSecurityAttributes: LPSECURITY_ATTRIBUTES): HANDLE{. - stdcall, dynlib: "kernel32", importc: "CreateNamedPipeA".} -proc GetNamedPipeHandleStateA*(hNamedPipe: HANDLE, lpState: LPDWORD, - lpCurInstances: LPDWORD, - lpMaxCollectionCount: LPDWORD, - lpCollectDataTimeout: LPDWORD, lpUserName: LPSTR, - nMaxUserNameSize: DWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetNamedPipeHandleStateA".} -proc CallNamedPipeA*(lpNamedPipeName: LPCSTR, lpInBuffer: LPVOID, - nInBufferSize: DWORD, lpOutBuffer: LPVOID, - nOutBufferSize: DWORD, lpBytesRead: LPDWORD, - nTimeOut: DWORD): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "CallNamedPipeA".} -proc WaitNamedPipeA*(lpNamedPipeName: LPCSTR, nTimeOut: DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "WaitNamedPipeA".} -proc SetVolumeLabelA*(lpRootPathName: LPCSTR, lpVolumeName: LPCSTR): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "SetVolumeLabelA".} -proc GetVolumeInformationA*(lpRootPathName: LPCSTR, lpVolumeNameBuffer: LPSTR, - nVolumeNameSize: DWORD, - lpVolumeSerialNumber: LPDWORD, - lpMaximumComponentLength: LPDWORD, - lpFileSystemFlags: LPDWORD, - lpFileSystemNameBuffer: LPSTR, - nFileSystemNameSize: DWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetVolumeInformationA".} -proc ClearEventLogA*(hEventLog: HANDLE, lpBackupFileName: LPCSTR): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "ClearEventLogA".} -proc BackupEventLogA*(hEventLog: HANDLE, lpBackupFileName: LPCSTR): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "BackupEventLogA".} -proc OpenEventLogA*(lpUNCServerName: LPCSTR, lpSourceName: LPCSTR): HANDLE{. - stdcall, dynlib: "advapi32", importc: "OpenEventLogA".} -proc RegisterEventSourceA*(lpUNCServerName: LPCSTR, lpSourceName: LPCSTR): HANDLE{. - stdcall, dynlib: "advapi32", importc: "RegisterEventSourceA".} -proc OpenBackupEventLogA*(lpUNCServerName: LPCSTR, lpFileName: LPCSTR): HANDLE{. - stdcall, dynlib: "advapi32", importc: "OpenBackupEventLogA".} -proc ReadEventLogA*(hEventLog: HANDLE, dwReadFlags: DWORD, - dwRecordOffset: DWORD, lpBuffer: LPVOID, - nNumberOfBytesToRead: DWORD, pnBytesRead: LPDWORD, - pnMinNumberOfBytesNeeded: LPDWORD): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "ReadEventLogA".} -proc ReportEventA*(hEventLog: HANDLE, wType: int16, wCategory: int16, - dwEventID: DWORD, lpUserSid: PSID, wNumStrings: int16, - dwDataSize: DWORD, lpStrings: LPPCSTR, lpRawData: LPVOID): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "ReportEventA".} -proc AccessCheckAndAuditAlarmA*(SubsystemName: LPCSTR, HandleId: LPVOID, - ObjectTypeName: LPSTR, ObjectName: LPSTR, - SecurityDescriptor: PSECURITY_DESCRIPTOR, - DesiredAccess: DWORD, - GenericMapping: PGENERIC_MAPPING, - ObjectCreation: WINBOOL, GrantedAccess: LPDWORD, - AccessStatus: LPBOOL, pfGenerateOnClose: LPBOOL): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "AccessCheckAndAuditAlarmA".} -proc ObjectOpenAuditAlarmA*(SubsystemName: LPCSTR, HandleId: LPVOID, - ObjectTypeName: LPSTR, ObjectName: LPSTR, - pSecurityDescriptor: PSECURITY_DESCRIPTOR, - ClientToken: HANDLE, DesiredAccess: DWORD, - GrantedAccess: DWORD, Privileges: PPRIVILEGE_SET, - ObjectCreation: WINBOOL, AccessGranted: WINBOOL, - GenerateOnClose: LPBOOL): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "ObjectOpenAuditAlarmA".} -proc ObjectPrivilegeAuditAlarmA*(SubsystemName: LPCSTR, HandleId: LPVOID, - ClientToken: HANDLE, DesiredAccess: DWORD, - Privileges: PPRIVILEGE_SET, - AccessGranted: WINBOOL): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "ObjectPrivilegeAuditAlarmA".} -proc ObjectCloseAuditAlarmA*(SubsystemName: LPCSTR, HandleId: LPVOID, - GenerateOnClose: WINBOOL): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "ObjectCloseAuditAlarmA".} -proc PrivilegedServiceAuditAlarmA*(SubsystemName: LPCSTR, ServiceName: LPCSTR, - ClientToken: HANDLE, - Privileges: PPRIVILEGE_SET, - AccessGranted: WINBOOL): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "PrivilegedServiceAuditAlarmA".} -proc SetFileSecurityA*(lpFileName: LPCSTR, - SecurityInformation: SECURITY_INFORMATION, - pSecurityDescriptor: PSECURITY_DESCRIPTOR): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "SetFileSecurityA".} -proc GetFileSecurityA*(lpFileName: LPCSTR, - RequestedInformation: SECURITY_INFORMATION, - pSecurityDescriptor: PSECURITY_DESCRIPTOR, - nLength: DWORD, lpnLengthNeeded: LPDWORD): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "GetFileSecurityA".} -proc FindFirstChangeNotificationA*(lpPathName: LPCSTR, bWatchSubtree: WINBOOL, - dwNotifyFilter: DWORD): HANDLE{.stdcall, - dynlib: "kernel32", importc: "FindFirstChangeNotificationA".} -proc IsBadStringPtrA*(lpsz: LPCSTR, ucchMax: WINUINT): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "IsBadStringPtrA".} -proc LookupAccountSidA*(lpSystemName: LPCSTR, Sid: PSID, Name: LPSTR, - cbName: LPDWORD, ReferencedDomainName: LPSTR, - cbReferencedDomainName: LPDWORD, peUse: PSID_NAME_USE): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "LookupAccountSidA".} -proc LookupAccountNameA*(lpSystemName: LPCSTR, lpAccountName: LPCSTR, Sid: PSID, - cbSid: LPDWORD, ReferencedDomainName: LPSTR, - cbReferencedDomainName: LPDWORD, peUse: PSID_NAME_USE): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "LookupAccountNameA".} -proc LookupPrivilegeValueA*(lpSystemName: LPCSTR, lpName: LPCSTR, lpLuid: PLUID): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "LookupPrivilegeValueA".} -proc LookupPrivilegeNameA*(lpSystemName: LPCSTR, lpLuid: PLUID, lpName: LPSTR, - cbName: LPDWORD): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "LookupPrivilegeNameA".} -proc LookupPrivilegeDisplayNameA*(lpSystemName: LPCSTR, lpName: LPCSTR, - lpDisplayName: LPSTR, cbDisplayName: LPDWORD, - lpLanguageId: LPDWORD): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "LookupPrivilegeDisplayNameA".} -proc BuildCommDCBA*(lpDef: LPCSTR, lpDCB: LPDCB): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "BuildCommDCBA".} -proc BuildCommDCBAndTimeoutsA*(lpDef: LPCSTR, lpDCB: LPDCB, - lpCommTimeouts: LPCOMMTIMEOUTS): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "BuildCommDCBAndTimeoutsA".} -proc CommConfigDialogA*(lpszName: LPCSTR, wnd: HWND, lpCC: LPCOMMCONFIG): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "CommConfigDialogA".} -proc GetDefaultCommConfigA*(lpszName: LPCSTR, lpCC: LPCOMMCONFIG, - lpdwSize: LPDWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetDefaultCommConfigA".} -proc SetDefaultCommConfigA*(lpszName: LPCSTR, lpCC: LPCOMMCONFIG, dwSize: DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "SetDefaultCommConfigA".} -proc GetComputerNameA*(lpBuffer: LPSTR, nSize: LPDWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetComputerNameA".} -proc SetComputerNameA*(lpComputerName: LPCSTR): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "SetComputerNameA".} -proc GetUserNameA*(lpBuffer: LPSTR, nSize: LPDWORD): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "GetUserNameA".} -proc LoadKeyboardLayoutA*(pwszKLID: LPCSTR, Flags: WINUINT): HKL{.stdcall, - dynlib: "user32", importc: "LoadKeyboardLayoutA".} -proc GetKeyboardLayoutNameA*(pwszKLID: LPSTR): WINBOOL{.stdcall, - dynlib: "user32", importc: "GetKeyboardLayoutNameA".} -proc CreateDesktopA*(lpszDesktop: LPSTR, lpszDevice: LPSTR, pDevmode: LPDEVMODE, - dwFlags: DWORD, dwDesiredAccess: DWORD, - lpsa: LPSECURITY_ATTRIBUTES): HDESK{.stdcall, - dynlib: "user32", importc: "CreateDesktopA".} -proc OpenDesktopA*(lpszDesktop: LPSTR, dwFlags: DWORD, fInherit: WINBOOL, - dwDesiredAccess: DWORD): HDESK{.stdcall, dynlib: "user32", - importc: "OpenDesktopA".} -proc EnumDesktopsA*(hwinsta: HWINSTA, lpEnumFunc: DESKTOPENUMPROC, - lp: LPARAM): WINBOOL{.stdcall, dynlib: "user32", - importc: "EnumDesktopsA".} -proc CreateWindowStationA*(lpwinsta: LPSTR, dwReserved: DWORD, - dwDesiredAccess: DWORD, lpsa: LPSECURITY_ATTRIBUTES): HWINSTA{. - stdcall, dynlib: "user32", importc: "CreateWindowStationA".} -proc OpenWindowStationA*(lpszWinSta: LPSTR, fInherit: WINBOOL, - dwDesiredAccess: DWORD): HWINSTA{.stdcall, - dynlib: "user32", importc: "OpenWindowStationA".} -proc EnumWindowStationsA*(lpEnumFunc: ENUMWINDOWSTATIONPROC, lp: LPARAM): WINBOOL{. - stdcall, dynlib: "user32", importc: "EnumWindowStationsA".} -proc GetUserObjectInformationA*(hObj: HANDLE, nIndex: int32, pvInfo: PVOID, - nLength: DWORD, lpnLengthNeeded: LPDWORD): WINBOOL{. - stdcall, dynlib: "user32", importc: "GetUserObjectInformationA".} -proc SetUserObjectInformationA*(hObj: HANDLE, nIndex: int32, pvInfo: PVOID, - nLength: DWORD): WINBOOL{.stdcall, - dynlib: "user32", importc: "SetUserObjectInformationA".} -proc RegisterWindowMessageA*(lpString: LPCSTR): WINUINT{.stdcall, dynlib: "user32", - importc: "RegisterWindowMessageA".} -proc GetMessageA*(lpMsg: LPMSG, wnd: HWND, wMsgFilterMin: WINUINT, - wMsgFilterMax: WINUINT): WINBOOL{.stdcall, dynlib: "user32", - importc: "GetMessageA".} -proc DispatchMessageA*(lpMsg: LPMSG): LONG{.stdcall, dynlib: "user32", - importc: "DispatchMessageA".} -proc PeekMessageA*(lpMsg: LPMSG, wnd: HWND, wMsgFilterMin: WINUINT, - wMsgFilterMax: WINUINT, wRemoveMsg: WINUINT): WINBOOL{.stdcall, - dynlib: "user32", importc: "PeekMessageA".} -proc SendMessageA*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): LRESULT{. - stdcall, dynlib: "user32", importc: "SendMessageA".} -proc SendMessageTimeoutA*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM, - fuFlags: WINUINT, uTimeout: WINUINT, lpdwResult: LPDWORD): LRESULT{. - stdcall, dynlib: "user32", importc: "SendMessageTimeoutA".} -proc SendNotifyMessageA*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): WINBOOL{. - stdcall, dynlib: "user32", importc: "SendNotifyMessageA".} -proc SendMessageCallbackA*(wnd: HWND, Msg: WINUINT, wp: WPARAM, - lp: LPARAM, lpResultCallBack: SENDASYNCPROC, - dwData: DWORD): WINBOOL{.stdcall, dynlib: "user32", - importc: "SendMessageCallbackA".} -proc PostMessageA*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): WINBOOL{. - stdcall, dynlib: "user32", importc: "PostMessageA".} -proc PostThreadMessageA*(idThread: DWORD, Msg: WINUINT, wp: WPARAM, - lp: LPARAM): WINBOOL{.stdcall, dynlib: "user32", - importc: "PostThreadMessageA".} -proc DefWindowProcA*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): LRESULT{. - stdcall, dynlib: "user32", importc: "DefWindowProcA".} -proc CallWindowProcA*(lpPrevWndFunc: WNDPROC, wnd: HWND, Msg: WINUINT, - wp: WPARAM, lp: LPARAM): LRESULT{.stdcall, - dynlib: "user32", importc: "CallWindowProcA".} -proc RegisterClassA*(lpWndClass: LPWNDCLASS): ATOM{.stdcall, dynlib: "user32", - importc: "RegisterClassA".} -proc UnregisterClassA*(lpClassName: LPCSTR, hInstance: HINST): WINBOOL{.stdcall, - dynlib: "user32", importc: "UnregisterClassA".} -proc GetClassInfoA*(hInstance: HINST, lpClassName: LPCSTR, - lpWndClass: LPWNDCLASS): WINBOOL{.stdcall, dynlib: "user32", - importc: "GetClassInfoA".} -proc RegisterClassExA*(para1: LPWNDCLASSEX): ATOM{.stdcall, dynlib: "user32", - importc: "RegisterClassExA".} -proc GetClassInfoExA*(para1: HINST, para2: LPCSTR, para3: LPWNDCLASSEX): WINBOOL{. - stdcall, dynlib: "user32", importc: "GetClassInfoExA".} -proc CreateWindowExA*(dwExStyle: DWORD, lpClassName: LPCSTR, - lpWindowName: LPCSTR, dwStyle: DWORD, X: int32, Y: int32, - nWidth: int32, nHeight: int32, hWndParent: HWND, - menu: HMENU, hInstance: HINST, lpParam: LPVOID): HWND{. - stdcall, dynlib: "user32", importc: "CreateWindowExA".} -proc CreateDialogParamA*(hInstance: HINST, lpTemplateName: LPCSTR, - hWndParent: HWND, lpDialogFunc: DLGPROC, - dwInitParam: LPARAM): HWND{.stdcall, dynlib: "user32", - importc: "CreateDialogParamA".} -proc CreateDialogIndirectParamA*(hInstance: HINST, lpTemplate: LPCDLGTEMPLATE, - hWndParent: HWND, lpDialogFunc: DLGPROC, - dwInitParam: LPARAM): HWND{.stdcall, - dynlib: "user32", importc: "CreateDialogIndirectParamA".} -proc DialogBoxParamA*(hInstance: HINST, lpTemplateName: LPCSTR, - hWndParent: HWND, lpDialogFunc: DLGPROC, - dwInitParam: LPARAM): int32{.stdcall, dynlib: "user32", - importc: "DialogBoxParamA".} -proc DialogBoxIndirectParamA*(hInstance: HINST, hDialogTemplate: LPCDLGTEMPLATE, - hWndParent: HWND, lpDialogFunc: DLGPROC, - dwInitParam: LPARAM): int32{.stdcall, - dynlib: "user32", importc: "DialogBoxIndirectParamA".} -proc SetDlgItemTextA*(hDlg: HWND, nIDDlgItem: int32, lpString: LPCSTR): WINBOOL{. - stdcall, dynlib: "user32", importc: "SetDlgItemTextA".} -proc GetDlgItemTextA*(hDlg: HWND, nIDDlgItem: int32, lpString: LPSTR, - nMaxCount: int32): WINUINT{.stdcall, dynlib: "user32", - importc: "GetDlgItemTextA".} -proc SendDlgItemMessageA*(hDlg: HWND, nIDDlgItem: int32, Msg: WINUINT, - wp: WPARAM, lp: LPARAM): LONG{.stdcall, - dynlib: "user32", importc: "SendDlgItemMessageA".} -proc DefDlgProcA*(hDlg: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): LRESULT{. - stdcall, dynlib: "user32", importc: "DefDlgProcA".} -proc CallMsgFilterA*(lpMsg: LPMSG, nCode: int32): WINBOOL{.stdcall, - dynlib: "user32", importc: "CallMsgFilterA".} -proc RegisterClipboardFormatA*(lpszFormat: LPCSTR): WINUINT{.stdcall, - dynlib: "user32", importc: "RegisterClipboardFormatA".} -proc GetClipboardFormatNameA*(format: WINUINT, lpszFormatName: LPSTR, - cchMaxCount: int32): int32{.stdcall, - dynlib: "user32", importc: "GetClipboardFormatNameA".} -proc CharToOemA*(lpszSrc: LPCSTR, lpszDst: LPSTR): WINBOOL{.stdcall, - dynlib: "user32", importc: "CharToOemA".} -proc OemToCharA*(lpszSrc: LPCSTR, lpszDst: LPSTR): WINBOOL{.stdcall, - dynlib: "user32", importc: "OemToCharA".} -proc CharToOemBuffA*(lpszSrc: LPCSTR, lpszDst: LPSTR, cchDstLength: DWORD): WINBOOL{. - stdcall, dynlib: "user32", importc: "CharToOemBuffA".} -proc OemToCharBuffA*(lpszSrc: LPCSTR, lpszDst: LPSTR, cchDstLength: DWORD): WINBOOL{. - stdcall, dynlib: "user32", importc: "OemToCharBuffA".} -proc CharUpperA*(lpsz: LPSTR): LPSTR{.stdcall, dynlib: "user32", - importc: "CharUpperA".} -proc CharUpperBuffA*(lpsz: LPSTR, cchLength: DWORD): DWORD{.stdcall, - dynlib: "user32", importc: "CharUpperBuffA".} -proc CharLowerA*(lpsz: LPSTR): LPSTR{.stdcall, dynlib: "user32", - importc: "CharLowerA".} -proc CharLowerBuffA*(lpsz: LPSTR, cchLength: DWORD): DWORD{.stdcall, - dynlib: "user32", importc: "CharLowerBuffA".} -proc CharNextA*(lpsz: LPCSTR): LPSTR{.stdcall, dynlib: "user32", - importc: "CharNextA".} -proc CharPrevA*(lpszStart: LPCSTR, lpszCurrent: LPCSTR): LPSTR{.stdcall, - dynlib: "user32", importc: "CharPrevA".} -proc IsCharAlphaA*(ch: char): WINBOOL{.stdcall, dynlib: "user32", - importc: "IsCharAlphaA".} -proc IsCharAlphaNumericA*(ch: char): WINBOOL{.stdcall, dynlib: "user32", - importc: "IsCharAlphaNumericA".} -proc IsCharUpperA*(ch: char): WINBOOL{.stdcall, dynlib: "user32", - importc: "IsCharUpperA".} -proc IsCharLowerA*(ch: char): WINBOOL{.stdcall, dynlib: "user32", - importc: "IsCharLowerA".} -proc GetKeyNameTextA*(lParam: LONG, lpString: LPSTR, nSize: int32): int32{. - stdcall, dynlib: "user32", importc: "GetKeyNameTextA".} -proc VkKeyScanA*(ch: char): SHORT{.stdcall, dynlib: "user32", - importc: "VkKeyScanA".} -proc VkKeyScanExA*(ch: char, dwhkl: HKL): SHORT{.stdcall, dynlib: "user32", - importc: "VkKeyScanExA".} -proc MapVirtualKeyA*(uCode: WINUINT, uMapType: WINUINT): WINUINT{.stdcall, - dynlib: "user32", importc: "MapVirtualKeyA".} -proc MapVirtualKeyExA*(uCode: WINUINT, uMapType: WINUINT, dwhkl: HKL): WINUINT{.stdcall, - dynlib: "user32", importc: "MapVirtualKeyExA".} -proc LoadAcceleratorsA*(hInstance: HINST, lpTableName: LPCSTR): HACCEL{.stdcall, - dynlib: "user32", importc: "LoadAcceleratorsA".} -proc CreateAcceleratorTableA*(para1: LPACCEL, para2: int32): HACCEL{.stdcall, - dynlib: "user32", importc: "CreateAcceleratorTableA".} -proc CopyAcceleratorTableA*(hAccelSrc: HACCEL, lpAccelDst: LPACCEL, - cAccelEntries: int32): int32{.stdcall, - dynlib: "user32", importc: "CopyAcceleratorTableA".} -proc TranslateAcceleratorA*(wnd: HWND, hAccTable: HACCEL, lpMsg: LPMSG): int32{. - stdcall, dynlib: "user32", importc: "TranslateAcceleratorA".} -proc LoadMenuA*(hInstance: HINST, lpMenuName: LPCSTR): HMENU{.stdcall, - dynlib: "user32", importc: "LoadMenuA".} -proc LoadMenuIndirectA*(lpMenuTemplate: LPMENUTEMPLATE): HMENU{.stdcall, - dynlib: "user32", importc: "LoadMenuIndirectA".} -proc ChangeMenuA*(menu: HMENU, cmd: WINUINT, lpszNewItem: LPCSTR, cmdInsert: WINUINT, - flags: WINUINT): WINBOOL{.stdcall, dynlib: "user32", - importc: "ChangeMenuA".} -proc GetMenuStringA*(menu: HMENU, uIDItem: WINUINT, lpString: LPSTR, - nMaxCount: int32, uFlag: WINUINT): int32{.stdcall, - dynlib: "user32", importc: "GetMenuStringA".} -proc InsertMenuA*(menu: HMENU, uPosition: WINUINT, uFlags: WINUINT, uIDNewItem: WINUINT, - lpNewItem: LPCSTR): WINBOOL{.stdcall, dynlib: "user32", - importc: "InsertMenuA".} -proc AppendMenuA*(menu: HMENU, uFlags: WINUINT, uIDNewItem: WINUINT, - lpNewItem: LPCSTR): WINBOOL{.stdcall, dynlib: "user32", - importc: "AppendMenuA".} -proc ModifyMenuA*(hMnu: HMENU, uPosition: WINUINT, uFlags: WINUINT, uIDNewItem: WINUINT, - lpNewItem: LPCSTR): WINBOOL{.stdcall, dynlib: "user32", - importc: "ModifyMenuA".} -proc InsertMenuItemA*(para1: HMENU, para2: WINUINT, para3: WINBOOL, - para4: LPCMENUITEMINFO): WINBOOL{.stdcall, - dynlib: "user32", importc: "InsertMenuItemA".} -proc GetMenuItemInfoA*(para1: HMENU, para2: WINUINT, para3: WINBOOL, - para4: LPMENUITEMINFO): WINBOOL{.stdcall, - dynlib: "user32", importc: "GetMenuItemInfoA".} -proc SetMenuItemInfoA*(para1: HMENU, para2: WINUINT, para3: WINBOOL, - para4: LPCMENUITEMINFO): WINBOOL{.stdcall, - dynlib: "user32", importc: "SetMenuItemInfoA".} -proc DrawTextA*(hDC: HDC, lpString: LPCSTR, nCount: int32, lpRect: LPRECT, - uFormat: WINUINT): int32{.stdcall, dynlib: "user32", - importc: "DrawTextA".} -proc DrawTextExA*(para1: HDC, para2: LPSTR, para3: int32, para4: LPRECT, - para5: WINUINT, para6: LPDRAWTEXTPARAMS): int32{.stdcall, - dynlib: "user32", importc: "DrawTextExA".} -proc GrayStringA*(hDC: HDC, hBrush: HBRUSH, lpOutputFunc: GRAYSTRINGPROC, - lpData: LPARAM, nCount: int32, X: int32, Y: int32, - nWidth: int32, nHeight: int32): WINBOOL{.stdcall, - dynlib: "user32", importc: "GrayStringA".} -proc DrawStateA*(para1: HDC, para2: HBRUSH, para3: DRAWSTATEPROC, para4: LPARAM, - para5: WPARAM, para6: int32, para7: int32, para8: int32, - para9: int32, para10: WINUINT): WINBOOL{.stdcall, - dynlib: "user32", importc: "DrawStateA".} -proc TabbedTextOutA*(hDC: HDC, X: int32, Y: int32, lpString: LPCSTR, - nCount: int32, nTabPositions: int32, - lpnTabStopPositions: LPINT, nTabOrigin: int32): LONG{. - stdcall, dynlib: "user32", importc: "TabbedTextOutA".} -proc GetTabbedTextExtentA*(hDC: HDC, lpString: LPCSTR, nCount: int32, - nTabPositions: int32, lpnTabStopPositions: LPINT): DWORD{. - stdcall, dynlib: "user32", importc: "GetTabbedTextExtentA".} -proc SetPropA*(wnd: HWND, lpString: LPCSTR, hData: HANDLE): WINBOOL{.stdcall, - dynlib: "user32", importc: "SetPropA".} -proc GetPropA*(wnd: HWND, lpString: LPCSTR): HANDLE{.stdcall, dynlib: "user32", - importc: "GetPropA".} -proc RemovePropA*(wnd: HWND, lpString: LPCSTR): HANDLE{.stdcall, - dynlib: "user32", importc: "RemovePropA".} -proc EnumPropsExA*(wnd: HWND, lpEnumFunc: PROPENUMPROCEX, lp: LPARAM): int32{. - stdcall, dynlib: "user32", importc: "EnumPropsExA".} -proc EnumPropsA*(wnd: HWND, lpEnumFunc: PROPENUMPROC): int32{.stdcall, - dynlib: "user32", importc: "EnumPropsA".} -proc SetWindowTextA*(wnd: HWND, lpString: LPCSTR): WINBOOL{.stdcall, - dynlib: "user32", importc: "SetWindowTextA".} -proc GetWindowTextA*(wnd: HWND, lpString: LPSTR, nMaxCount: int32): int32{. - stdcall, dynlib: "user32", importc: "GetWindowTextA".} -proc GetWindowTextLengthA*(wnd: HWND): int32{.stdcall, dynlib: "user32", - importc: "GetWindowTextLengthA".} -proc MessageBoxA*(wnd: HWND, lpText: LPCSTR, lpCaption: LPCSTR, uType: int): int32{. - stdcall, dynlib: "user32", importc: "MessageBoxA".} -proc MessageBoxExA*(wnd: HWND, lpText: LPCSTR, lpCaption: LPCSTR, uType: WINUINT, - wLanguageId: int16): int32{.stdcall, dynlib: "user32", - importc: "MessageBoxExA".} -proc MessageBoxIndirectA*(para1: LPMSGBOXPARAMS): int32{.stdcall, - dynlib: "user32", importc: "MessageBoxIndirectA".} -proc GetWindowLongA*(wnd: HWND, nIndex: int32): LONG{.stdcall, - dynlib: "user32", importc: "GetWindowLongA".} -proc SetWindowLongA*(wnd: HWND, nIndex: int32, dwNewLong: LONG): LONG{.stdcall, - dynlib: "user32", importc: "SetWindowLongA".} -proc GetClassLongA*(wnd: HWND, nIndex: int32): DWORD{.stdcall, - dynlib: "user32", importc: "GetClassLongA".} -proc SetClassLongA*(wnd: HWND, nIndex: int32, dwNewLong: LONG): DWORD{.stdcall, - dynlib: "user32", importc: "SetClassLongA".} -when defined(cpu64): - proc GetWindowLongPtrA*(wnd: HWND, nIndex: int32): LONG_PTR{.stdcall, - dynlib: "user32", importc: "GetWindowLongPtrA".} - proc SetWindowLongPtrA*(wnd: HWND, nIndex: int32, dwNewLong: LONG_PTR): LONG_PTR{. - stdcall, dynlib: "user32", importc: "SetWindowLongPtrA".} - proc GetClassLongPtrA*(wnd: HWND, nIndex: int32): LONG_PTR{.stdcall, - dynlib: "user32", importc: "GetClassLongPtrA".} - proc SetClassLongPtrA*(wnd: HWND, nIndex: int32, dwNewLong: LONG_PTR): LONG_PTR{. - stdcall, dynlib: "user32", importc: "SetClassLongPtrA".} -else: - proc GetWindowLongPtrA*(wnd: HWND, nIndex: int32): LONG_PTR{.stdcall, - dynlib: "user32", importc: "GetWindowLongA".} - proc SetWindowLongPtrA*(wnd: HWND, nIndex: int32, dwNewLong: LONG_PTR): LONG_PTR{. - stdcall, dynlib: "user32", importc: "SetWindowLongA".} - proc GetClassLongPtrA*(wnd: HWND, nIndex: int32): LONG_PTR{.stdcall, - dynlib: "user32", importc: "GetClassLongA".} - proc SetClassLongPtrA*(wnd: HWND, nIndex: int32, dwNewLong: LONG_PTR): LONG_PTR{. - stdcall, dynlib: "user32", importc: "SetClassLongA".} -proc FindWindowA*(lpClassName: LPCSTR, lpWindowName: LPCSTR): HWND{.stdcall, - dynlib: "user32", importc: "FindWindowA".} -proc FindWindowExA*(para1: HWND, para2: HWND, para3: LPCSTR, para4: LPCSTR): HWND{. - stdcall, dynlib: "user32", importc: "FindWindowExA".} -proc GetClassNameA*(wnd: HWND, lpClassName: LPSTR, nMaxCount: int32): int32{. - stdcall, dynlib: "user32", importc: "GetClassNameA".} -proc SetWindowsHookExA*(idHook: int32, lpfn: HOOKPROC, hmod: HINST, - dwThreadId: DWORD): HHOOK{.stdcall, dynlib: "user32", - importc: "SetWindowsHookExA".} -proc LoadBitmapA*(hInstance: HINST, lpBitmapName: LPCSTR): HBITMAP{.stdcall, - dynlib: "user32", importc: "LoadBitmapA".} -proc LoadCursorA*(hInstance: HINST, lpCursorName: LPCSTR): HCURSOR{.stdcall, - dynlib: "user32", importc: "LoadCursorA".} -proc LoadCursorFromFileA*(lpFileName: LPCSTR): HCURSOR{.stdcall, - dynlib: "user32", importc: "LoadCursorFromFileA".} -proc LoadIconA*(hInstance: HINST, lpIconName: LPCSTR): HICON{.stdcall, - dynlib: "user32", importc: "LoadIconA".} -proc LoadImageA*(para1: HINST, para2: LPCSTR, para3: WINUINT, para4: int32, - para5: int32, para6: WINUINT): HANDLE{.stdcall, dynlib: "user32", - importc: "LoadImageA".} -proc LoadStringA*(hInstance: HINST, uID: WINUINT, lpBuffer: LPSTR, - nBufferMax: int32): int32{.stdcall, dynlib: "user32", - importc: "LoadStringA".} -proc IsDialogMessageA*(hDlg: HWND, lpMsg: LPMSG): WINBOOL{.stdcall, - dynlib: "user32", importc: "IsDialogMessageA".} -proc DlgDirListA*(hDlg: HWND, lpPathSpec: LPSTR, nIDListBox: int32, - nIDStaticPath: int32, uFileType: WINUINT): int32{.stdcall, - dynlib: "user32", importc: "DlgDirListA".} -proc DlgDirSelectExA*(hDlg: HWND, lpString: LPSTR, nCount: int32, - nIDListBox: int32): WINBOOL{.stdcall, dynlib: "user32", - importc: "DlgDirSelectExA".} -proc DlgDirListComboBoxA*(hDlg: HWND, lpPathSpec: LPSTR, nIDComboBox: int32, - nIDStaticPath: int32, uFiletype: WINUINT): int32{. - stdcall, dynlib: "user32", importc: "DlgDirListComboBoxA".} -proc DlgDirSelectComboBoxExA*(hDlg: HWND, lpString: LPSTR, nCount: int32, - nIDComboBox: int32): WINBOOL{.stdcall, - dynlib: "user32", importc: "DlgDirSelectComboBoxExA".} -proc DefFrameProcA*(wnd: HWND, hWndMDIClient: HWND, uMsg: WINUINT, wp: WPARAM, - lp: LPARAM): LRESULT{.stdcall, dynlib: "user32", - importc: "DefFrameProcA".} -proc DefMDIChildProcA*(wnd: HWND, uMsg: WINUINT, wp: WPARAM, lp: LPARAM): LRESULT{. - stdcall, dynlib: "user32", importc: "DefMDIChildProcA".} -proc CreateMDIWindowA*(lpClassName: LPSTR, lpWindowName: LPSTR, dwStyle: DWORD, - X: int32, Y: int32, nWidth: int32, nHeight: int32, - hWndParent: HWND, hInstance: HINST, lp: LPARAM): HWND{. - stdcall, dynlib: "user32", importc: "CreateMDIWindowA".} -proc WinHelpA*(hWndMain: HWND, lpszHelp: LPCSTR, uCommand: WINUINT, dwData: DWORD): WINBOOL{. - stdcall, dynlib: "user32", importc: "WinHelpA".} -proc ChangeDisplaySettingsA*(lpDevMode: LPDEVMODE, dwFlags: DWORD): LONG{. - stdcall, dynlib: "user32", importc: "ChangeDisplaySettingsA".} -proc EnumDisplaySettingsA*(lpszDeviceName: LPCSTR, iModeNum: DWORD, - lpDevMode: LPDEVMODE): WINBOOL{.stdcall, - dynlib: "user32", importc: "EnumDisplaySettingsA".} -proc SystemParametersInfoA*(uiAction: WINUINT, uiParam: WINUINT, pvParam: PVOID, - fWinIni: WINUINT): WINBOOL{.stdcall, dynlib: "user32", - importc: "SystemParametersInfoA".} -proc AddFontResourceA*(para1: LPCSTR): int32{.stdcall, dynlib: "gdi32", - importc: "AddFontResourceA".} -proc CopyMetaFileA*(para1: HMETAFILE, para2: LPCSTR): HMETAFILE{.stdcall, - dynlib: "gdi32", importc: "CopyMetaFileA".} -proc CreateFontA*(para1: int32, para2: int32, para3: int32, para4: int32, - para5: int32, para6: DWORD, para7: DWORD, para8: DWORD, - para9: DWORD, para10: DWORD, para11: DWORD, para12: DWORD, - para13: DWORD, para14: LPCSTR): HFONT{.stdcall, - dynlib: "gdi32", importc: "CreateFontA".} -proc CreateFontIndirectA*(para1: LPLOGFONT): HFONT{.stdcall, dynlib: "gdi32", - importc: "CreateFontIndirectA".} -proc CreateFontIndirectA*(para1: var LOGFONT): HFONT{.stdcall, dynlib: "gdi32", - importc: "CreateFontIndirectA".} -proc CreateICA*(para1: LPCSTR, para2: LPCSTR, para3: LPCSTR, para4: LPDEVMODE): HDC{. - stdcall, dynlib: "gdi32", importc: "CreateICA".} -proc CreateMetaFileA*(para1: LPCSTR): HDC{.stdcall, dynlib: "gdi32", - importc: "CreateMetaFileA".} -proc CreateScalableFontResourceA*(para1: DWORD, para2: LPCSTR, para3: LPCSTR, - para4: LPCSTR): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "CreateScalableFontResourceA".} -proc EnumFontFamiliesExA*(para1: HDC, para2: LPLOGFONT, para3: FONTENUMEXPROC, - para4: LPARAM, para5: DWORD): int32{.stdcall, - dynlib: "gdi32", importc: "EnumFontFamiliesExA".} -proc EnumFontFamiliesA*(para1: HDC, para2: LPCSTR, para3: FONTENUMPROC, - para4: LPARAM): int32{.stdcall, dynlib: "gdi32", - importc: "EnumFontFamiliesA".} -proc EnumFontsA*(para1: HDC, para2: LPCSTR, para3: ENUMFONTSPROC, para4: LPARAM): int32{. - stdcall, dynlib: "gdi32", importc: "EnumFontsA".} -proc EnumFontsA*(para1: HDC, para2: LPCSTR, para3: ENUMFONTSPROC, para4: pointer): int32{. - stdcall, dynlib: "gdi32", importc: "EnumFontsA".} -proc GetCharWidthA*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: LPINT): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "GetCharWidthA".} -proc GetCharWidth32A*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: LPINT): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "GetCharWidth32A".} -proc GetCharWidthFloatA*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: ptr float32): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "GetCharWidthFloatA".} -proc GetCharABCWidthsA*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: LPABC): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "GetCharABCWidthsA".} -proc GetCharABCWidthsFloatA*(para1: HDC, para2: WINUINT, para3: WINUINT, - para4: LPABCFLOAT): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "GetCharABCWidthsFloatA".} -proc GetGlyphOutlineA*(para1: HDC, para2: WINUINT, para3: WINUINT, - para4: LPGLYPHMETRICS, para5: DWORD, para6: LPVOID, - para7: PMAT2): DWORD{.stdcall, dynlib: "gdi32", - importc: "GetGlyphOutlineA".} -proc GetMetaFileA*(para1: LPCSTR): HMETAFILE{.stdcall, dynlib: "gdi32", - importc: "GetMetaFileA".} -proc GetOutlineTextMetricsA*(para1: HDC, para2: WINUINT, para3: LPOUTLINETEXTMETRIC): WINUINT{. - stdcall, dynlib: "gdi32", importc: "GetOutlineTextMetricsA".} -proc GetTextExtentPointA*(para1: HDC, para2: LPCSTR, para3: int32, para4: LPSIZE): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "GetTextExtentPointA".} -proc GetTextExtentPoint32A*(para1: HDC, para2: LPCSTR, para3: int32, - para4: LPSIZE): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "GetTextExtentPoint32A".} -proc GetTextExtentExPointA*(para1: HDC, para2: LPCSTR, para3: int32, - para4: int32, para5: LPINT, para6: LPINT, - para7: LPSIZE): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "GetTextExtentExPointA".} -proc GetCharacterPlacementA*(para1: HDC, para2: LPCSTR, para3: int32, - para4: int32, para5: LPGCP_RESULTS, para6: DWORD): DWORD{. - stdcall, dynlib: "gdi32", importc: "GetCharacterPlacementA".} -proc ResetDCA*(para1: HDC, para2: LPDEVMODE): HDC{.stdcall, dynlib: "gdi32", - importc: "ResetDCA".} -proc RemoveFontResourceA*(para1: LPCSTR): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "RemoveFontResourceA".} -proc CopyEnhMetaFileA*(para1: HENHMETAFILE, para2: LPCSTR): HENHMETAFILE{. - stdcall, dynlib: "gdi32", importc: "CopyEnhMetaFileA".} -proc CreateEnhMetaFileA*(para1: HDC, para2: LPCSTR, para3: LPRECT, para4: LPCSTR): HDC{. - stdcall, dynlib: "gdi32", importc: "CreateEnhMetaFileA".} -proc GetEnhMetaFileA*(para1: LPCSTR): HENHMETAFILE{.stdcall, dynlib: "gdi32", - importc: "GetEnhMetaFileA".} -proc GetEnhMetaFileDescriptionA*(para1: HENHMETAFILE, para2: WINUINT, para3: LPSTR): WINUINT{. - stdcall, dynlib: "gdi32", importc: "GetEnhMetaFileDescriptionA".} -proc GetTextMetricsA*(para1: HDC, para2: LPTEXTMETRIC): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "GetTextMetricsA".} -proc StartDocA*(para1: HDC, para2: PDOCINFO): int32{.stdcall, dynlib: "gdi32", - importc: "StartDocA".} -proc GetObjectA*(para1: HGDIOBJ, para2: int32, para3: LPVOID): int32{.stdcall, - dynlib: "gdi32", importc: "GetObjectA".} -proc TextOutA*(para1: HDC, para2: int32, para3: int32, para4: LPCSTR, - para5: int32): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "TextOutA".} -proc ExtTextOutA*(para1: HDC, para2: int32, para3: int32, para4: WINUINT, - para5: LPRECT, para6: LPCSTR, para7: WINUINT, para8: LPINT): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "ExtTextOutA".} -proc PolyTextOutA*(para1: HDC, para2: PPOLYTEXT, para3: int32): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "PolyTextOutA".} -proc GetTextFaceA*(para1: HDC, para2: int32, para3: LPSTR): int32{.stdcall, - dynlib: "gdi32", importc: "GetTextFaceA".} -proc GetKerningPairsA*(para1: HDC, para2: DWORD, para3: LPKERNINGPAIR): DWORD{. - stdcall, dynlib: "gdi32", importc: "GetKerningPairsA".} -proc CreateColorSpaceA*(para1: LPLOGCOLORSPACE): HCOLORSPACE{.stdcall, - dynlib: "gdi32", importc: "CreateColorSpaceA".} -proc GetLogColorSpaceA*(para1: HCOLORSPACE, para2: LPLOGCOLORSPACE, para3: DWORD): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "GetLogColorSpaceA".} -proc GetICMProfileA*(para1: HDC, para2: DWORD, para3: LPSTR): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "GetICMProfileA".} -proc SetICMProfileA*(para1: HDC, para2: LPSTR): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "SetICMProfileA".} -proc UpdateICMRegKeyA*(para1: DWORD, para2: DWORD, para3: LPSTR, para4: WINUINT): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "UpdateICMRegKeyA".} -proc EnumICMProfilesA*(para1: HDC, para2: ICMENUMPROC, para3: LPARAM): int32{. - stdcall, dynlib: "gdi32", importc: "EnumICMProfilesA".} -proc PropertySheetA*(lppsph: LPCPROPSHEETHEADER): int32{.stdcall, - dynlib: "comctl32", importc: "PropertySheetA".} -proc ImageList_LoadImageA*(hi: HINST, lpbmp: LPCSTR, cx: int32, cGrow: int32, - crMask: COLORREF, uType: WINUINT, uFlags: WINUINT): HIMAGELIST{. - stdcall, dynlib: "comctl32", importc: "ImageList_LoadImageA".} -proc CreateStatusWindowA*(style: LONG, lpszText: LPCSTR, hwndParent: HWND, - wID: WINUINT): HWND{.stdcall, dynlib: "comctl32", - importc: "CreateStatusWindowA".} -proc DrawStatusTextA*(hDC: HDC, lprc: LPRECT, pszText: LPCSTR, uFlags: WINUINT){. - stdcall, dynlib: "comctl32", importc: "DrawStatusTextA".} -proc GetOpenFileNameA*(para1: LPOPENFILENAME): WINBOOL{.stdcall, - dynlib: "comdlg32", importc: "GetOpenFileNameA".} -proc GetSaveFileNameA*(para1: LPOPENFILENAME): WINBOOL{.stdcall, - dynlib: "comdlg32", importc: "GetSaveFileNameA".} -proc GetFileTitleA*(para1: LPCSTR, para2: LPSTR, para3: int16): int{.stdcall, - dynlib: "comdlg32", importc: "GetFileTitleA".} -proc ChooseColorA*(para1: LPCHOOSECOLOR): WINBOOL{.stdcall, dynlib: "comdlg32", - importc: "ChooseColorA".} -proc FindTextA*(para1: LPFINDREPLACE): HWND{.stdcall, dynlib: "comdlg32", - importc: "FindTextA".} -proc ReplaceTextA*(para1: LPFINDREPLACE): HWND{.stdcall, dynlib: "comdlg32", - importc: "ReplaceTextA".} -proc ChooseFontA*(para1: LPCHOOSEFONT): WINBOOL{.stdcall, dynlib: "comdlg32", - importc: "ChooseFontA".} -proc PrintDlgA*(para1: LPPRINTDLG): WINBOOL{.stdcall, dynlib: "comdlg32", - importc: "PrintDlgA".} -proc PageSetupDlgA*(para1: LPPAGESETUPDLG): WINBOOL{.stdcall, - dynlib: "comdlg32", importc: "PageSetupDlgA".} -proc CreateProcessA*(lpApplicationName: LPCSTR, lpCommandLine: LPSTR, - lpProcessAttributes: LPSECURITY_ATTRIBUTES, - lpThreadAttributes: LPSECURITY_ATTRIBUTES, - bInheritHandles: WINBOOL, dwCreationFlags: DWORD, - lpEnvironment: LPVOID, lpCurrentDirectory: LPCSTR, - lpStartupInfo: LPSTARTUPINFO, - lpProcessInformation: LPPROCESS_INFORMATION): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "CreateProcessA".} -proc GetStartupInfoA*(lpStartupInfo: LPSTARTUPINFO){.stdcall, - dynlib: "kernel32", importc: "GetStartupInfoA".} -proc FindFirstFileA*(lpFileName: LPCSTR, lpFindFileData: LPWIN32_FIND_DATA): HANDLE{. - stdcall, dynlib: "kernel32", importc: "FindFirstFileA".} -proc FindNextFileA*(hFindFile: HANDLE, lpFindFileData: LPWIN32_FIND_DATA): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "FindNextFileA".} -proc GetVersionExA*(VersionInformation: LPOSVERSIONINFO): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetVersionExA".} -proc CreateWindowA*(lpClassName: LPCSTR, lpWindowName: LPCSTR, dwStyle: DWORD, - X: int32, Y: int32, nWidth: int32, nHeight: int32, - hWndParent: HWND, menu: HMENU, hInstance: HINST, - lpParam: LPVOID): HWND -proc CreateDialogA*(hInstance: HINST, lpTemplateName: LPCSTR, hWndParent: HWND, - lpDialogFunc: DLGPROC): HWND -proc CreateDialogIndirectA*(hInstance: HINST, lpTemplate: LPCDLGTEMPLATE, - hWndParent: HWND, lpDialogFunc: DLGPROC): HWND -proc DialogBoxA*(hInstance: HINST, lpTemplateName: LPCSTR, hWndParent: HWND, - lpDialogFunc: DLGPROC): int32 -proc DialogBoxIndirectA*(hInstance: HINST, hDialogTemplate: LPCDLGTEMPLATE, - hWndParent: HWND, lpDialogFunc: DLGPROC): int32 -proc CreateDCA*(para1: LPCSTR, para2: LPCSTR, para3: LPCSTR, para4: PDEVMODE): HDC{. - stdcall, dynlib: "gdi32", importc: "CreateDCA".} -proc VerInstallFileA*(uFlags: DWORD, szSrcFileName: LPSTR, - szDestFileName: LPSTR, szSrcDir: LPSTR, szDestDir: LPSTR, - szCurDir: LPSTR, szTmpFile: LPSTR, lpuTmpFileLen: PUINT): DWORD{. - stdcall, dynlib: "version", importc: "VerInstallFileA".} -proc GetFileVersionInfoSizeA*(lptstrFilename: LPSTR, lpdwHandle: LPDWORD): DWORD{. - stdcall, dynlib: "version", importc: "GetFileVersionInfoSizeA".} -proc GetFileVersionInfoA*(lptstrFilename: LPSTR, dwHandle: DWORD, dwLen: DWORD, - lpData: LPVOID): WINBOOL{.stdcall, dynlib: "version", - importc: "GetFileVersionInfoA".} -proc VerLanguageNameA*(wLang: DWORD, szLang: LPSTR, nSize: DWORD): DWORD{. - stdcall, dynlib: "kernel32", importc: "VerLanguageNameA".} -proc VerQueryValueA*(pBlock: LPVOID, lpSubBlock: LPSTR, lplpBuffer: LPVOID, - puLen: PUINT): WINBOOL{.stdcall, dynlib: "version", - importc: "VerQueryValueA".} -proc VerFindFileA*(uFlags: DWORD, szFileName: LPSTR, szWinDir: LPSTR, - szAppDir: LPSTR, szCurDir: LPSTR, lpuCurDirLen: PUINT, - szDestDir: LPSTR, lpuDestDirLen: PUINT): DWORD{.stdcall, - dynlib: "version", importc: "VerFindFileA".} -proc RegConnectRegistryA*(lpMachineName: LPSTR, key: HKEY, phkResult: PHKEY): LONG{. - stdcall, dynlib: "advapi32", importc: "RegConnectRegistryA".} -proc RegCreateKeyA*(key: HKEY, lpSubKey: LPCSTR, phkResult: PHKEY): LONG{. - stdcall, dynlib: "advapi32", importc: "RegCreateKeyA".} -proc RegCreateKeyExA*(key: HKEY, lpSubKey: LPCSTR, Reserved: DWORD, - lpClass: LPSTR, dwOptions: DWORD, samDesired: REGSAM, - lpSecurityAttributes: LPSECURITY_ATTRIBUTES, - phkResult: PHKEY, lpdwDisposition: LPDWORD): LONG{. - stdcall, dynlib: "advapi32", importc: "RegCreateKeyExA".} -proc RegDeleteKeyA*(key: HKEY, lpSubKey: LPCSTR): LONG{.stdcall, - dynlib: "advapi32", importc: "RegDeleteKeyA".} -proc RegDeleteValueA*(key: HKEY, lpValueName: LPCSTR): LONG{.stdcall, - dynlib: "advapi32", importc: "RegDeleteValueA".} -proc RegEnumKeyA*(key: HKEY, dwIndex: DWORD, lpName: LPSTR, cbName: DWORD): LONG{. - stdcall, dynlib: "advapi32", importc: "RegEnumKeyA".} -proc RegEnumKeyExA*(key: HKEY, dwIndex: DWORD, lpName: LPSTR, - lpcbName: LPDWORD, lpReserved: LPDWORD, lpClass: LPSTR, - lpcbClass: LPDWORD, lpftLastWriteTime: PFILETIME): LONG{. - stdcall, dynlib: "advapi32", importc: "RegEnumKeyExA".} -proc RegEnumValueA*(key: HKEY, dwIndex: DWORD, lpValueName: LPSTR, - lpcbValueName: LPDWORD, lpReserved: LPDWORD, - lpType: LPDWORD, lpData: LPBYTE, lpcbData: LPDWORD): LONG{. - stdcall, dynlib: "advapi32", importc: "RegEnumValueA".} -proc RegLoadKeyA*(key: HKEY, lpSubKey: LPCSTR, lpFile: LPCSTR): LONG{.stdcall, - dynlib: "advapi32", importc: "RegLoadKeyA".} -proc RegOpenKeyA*(key: HKEY, lpSubKey: LPCSTR, phkResult: PHKEY): LONG{. - stdcall, dynlib: "advapi32", importc: "RegOpenKeyA".} -proc RegOpenKeyExA*(key: HKEY, lpSubKey: LPCSTR, ulOptions: DWORD, - samDesired: REGSAM, phkResult: PHKEY): LONG{.stdcall, - dynlib: "advapi32", importc: "RegOpenKeyExA".} -proc RegQueryInfoKeyA*(key: HKEY, lpClass: LPSTR, lpcbClass: LPDWORD, - lpReserved: LPDWORD, lpcSubKeys: LPDWORD, - lpcbMaxSubKeyLen: LPDWORD, lpcbMaxClassLen: LPDWORD, - lpcValues: LPDWORD, lpcbMaxValueNameLen: LPDWORD, - lpcbMaxValueLen: LPDWORD, - lpcbSecurityDescriptor: LPDWORD, - lpftLastWriteTime: PFILETIME): LONG{.stdcall, - dynlib: "advapi32", importc: "RegQueryInfoKeyA".} -proc RegQueryValueA*(key: HKEY, lpSubKey: LPCSTR, lpValue: LPSTR, - lpcbValue: PLONG): LONG{.stdcall, dynlib: "advapi32", - importc: "RegQueryValueA".} -proc RegQueryMultipleValuesA*(key: HKEY, val_list: PVALENT, num_vals: DWORD, - lpValueBuf: LPSTR, ldwTotsize: LPDWORD): LONG{. - stdcall, dynlib: "advapi32", importc: "RegQueryMultipleValuesA".} -proc RegQueryValueExA*(key: HKEY, lpValueName: LPCSTR, lpReserved: LPDWORD, - lpType: LPDWORD, lpData: LPBYTE, lpcbData: LPDWORD): LONG{. - stdcall, dynlib: "advapi32", importc: "RegQueryValueExA".} -proc RegReplaceKeyA*(key: HKEY, lpSubKey: LPCSTR, lpNewFile: LPCSTR, - lpOldFile: LPCSTR): LONG{.stdcall, dynlib: "advapi32", - importc: "RegReplaceKeyA".} -proc RegRestoreKeyA*(key: HKEY, lpFile: LPCSTR, dwFlags: DWORD): LONG{.stdcall, - dynlib: "advapi32", importc: "RegRestoreKeyA".} -proc RegSaveKeyA*(key: HKEY, lpFile: LPCSTR, - lpSecurityAttributes: LPSECURITY_ATTRIBUTES): LONG{.stdcall, - dynlib: "advapi32", importc: "RegSaveKeyA".} -proc RegSetValueA*(key: HKEY, lpSubKey: LPCSTR, dwType: DWORD, lpData: LPCSTR, - cbData: DWORD): LONG{.stdcall, dynlib: "advapi32", - importc: "RegSetValueA".} -proc RegSetValueExA*(key: HKEY, lpValueName: LPCSTR, Reserved: DWORD, - dwType: DWORD, lpData: LPBYTE, cbData: DWORD): LONG{. - stdcall, dynlib: "advapi32", importc: "RegSetValueExA".} -proc RegUnLoadKeyA*(key: HKEY, lpSubKey: LPCSTR): LONG{.stdcall, - dynlib: "advapi32", importc: "RegUnLoadKeyA".} -proc InitiateSystemShutdownA*(lpMachineName: LPSTR, lpMessage: LPSTR, - dwTimeout: DWORD, bForceAppsClosed: WINBOOL, - bRebootAfterShutdown: WINBOOL): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "InitiateSystemShutdownA".} -proc AbortSystemShutdownA*(lpMachineName: LPSTR): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "AbortSystemShutdownA".} -proc CompareStringA*(Locale: LCID, dwCmpFlags: DWORD, lpString1: LPCSTR, - cchCount1: int32, lpString2: LPCSTR, cchCount2: int32): int32{. - stdcall, dynlib: "kernel32", importc: "CompareStringA".} -proc LCMapStringA*(Locale: LCID, dwMapFlags: DWORD, lpSrcStr: LPCSTR, - cchSrc: int32, lpDestStr: LPSTR, cchDest: int32): int32{. - stdcall, dynlib: "kernel32", importc: "LCMapStringA".} -proc GetLocaleInfoA*(Locale: LCID, LCType: LCTYPE, lpLCData: LPSTR, - cchData: int32): int32{.stdcall, dynlib: "kernel32", - importc: "GetLocaleInfoA".} -proc SetLocaleInfoA*(Locale: LCID, LCType: LCTYPE, lpLCData: LPCSTR): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "SetLocaleInfoA".} -proc GetTimeFormatA*(Locale: LCID, dwFlags: DWORD, lpTime: LPSYSTEMTIME, - lpFormat: LPCSTR, lpTimeStr: LPSTR, cchTime: int32): int32{. - stdcall, dynlib: "kernel32", importc: "GetTimeFormatA".} -proc GetDateFormatA*(Locale: LCID, dwFlags: DWORD, lpDate: LPSYSTEMTIME, - lpFormat: LPCSTR, lpDateStr: LPSTR, cchDate: int32): int32{. - stdcall, dynlib: "kernel32", importc: "GetDateFormatA".} -proc GetNumberFormatA*(Locale: LCID, dwFlags: DWORD, lpValue: LPCSTR, - lpFormat: PNUMBERFMT, lpNumberStr: LPSTR, - cchNumber: int32): int32{.stdcall, dynlib: "kernel32", - importc: "GetNumberFormatA".} -proc GetCurrencyFormatA*(Locale: LCID, dwFlags: DWORD, lpValue: LPCSTR, - lpFormat: PCURRENCYFMT, lpCurrencyStr: LPSTR, - cchCurrency: int32): int32{.stdcall, - dynlib: "kernel32", importc: "GetCurrencyFormatA".} -proc EnumCalendarInfoA*(lpCalInfoEnumProc: CALINFO_ENUMPROC, Locale: LCID, - Calendar: CALID, CalType: CALTYPE): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "EnumCalendarInfoA".} -proc EnumTimeFormatsA*(lpTimeFmtEnumProc: TIMEFMT_ENUMPROC, Locale: LCID, - dwFlags: DWORD): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "EnumTimeFormatsA".} -proc EnumDateFormatsA*(lpDateFmtEnumProc: DATEFMT_ENUMPROC, Locale: LCID, - dwFlags: DWORD): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "EnumDateFormatsA".} -proc GetStringTypeExA*(Locale: LCID, dwInfoType: DWORD, lpSrcStr: LPCSTR, - cchSrc: int32, lpCharType: LPWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetStringTypeExA".} -proc GetStringTypeA*(Locale: LCID, dwInfoType: DWORD, lpSrcStr: LPCSTR, - cchSrc: int32, lpCharType: LPWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetStringTypeA".} -proc FoldStringA*(dwMapFlags: DWORD, lpSrcStr: LPCSTR, cchSrc: int32, - lpDestStr: LPSTR, cchDest: int32): int32{.stdcall, - dynlib: "kernel32", importc: "FoldStringA".} -proc EnumSystemLocalesA*(lpLocaleEnumProc: LOCALE_ENUMPROC, dwFlags: DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "EnumSystemLocalesA".} -proc EnumSystemCodePagesA*(lpCodePageEnumProc: CODEPAGE_ENUMPROC, dwFlags: DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "EnumSystemCodePagesA".} -proc PeekConsoleInputA*(hConsoleInput: HANDLE, lpBuffer: PINPUTRECORD, - nLength: DWORD, lpNumberOfEventsRead: LPDWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "PeekConsoleInputA".} -proc ReadConsoleInputA*(hConsoleInput: HANDLE, lpBuffer: PINPUTRECORD, - nLength: DWORD, lpNumberOfEventsRead: LPDWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "ReadConsoleInputA".} -proc WriteConsoleInputA*(hConsoleInput: HANDLE, lpBuffer: PINPUTRECORD, - nLength: DWORD, lpNumberOfEventsWritten: LPDWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "WriteConsoleInputA".} -proc ReadConsoleOutputA*(hConsoleOutput: HANDLE, lpBuffer: PCHAR_INFO, - dwBufferSize: COORD, dwBufferCoord: COORD, - lpReadRegion: PSMALL_RECT): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "ReadConsoleOutputA".} -proc WriteConsoleOutputA*(hConsoleOutput: HANDLE, lpBuffer: PCHAR_INFO, - dwBufferSize: COORD, dwBufferCoord: COORD, - lpWriteRegion: PSMALL_RECT): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "WriteConsoleOutputA".} -proc ReadConsoleOutputCharacterA*(hConsoleOutput: HANDLE, lpCharacter: LPSTR, - nLength: DWORD, dwReadCoord: COORD, - lpNumberOfCharsRead: LPDWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "ReadConsoleOutputCharacterA".} -proc WriteConsoleOutputCharacterA*(hConsoleOutput: HANDLE, lpCharacter: LPCSTR, - nLength: DWORD, dwWriteCoord: COORD, - lpNumberOfCharsWritten: LPDWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "WriteConsoleOutputCharacterA".} -proc FillConsoleOutputCharacterA*(hConsoleOutput: HANDLE, cCharacter: char, - nLength: DWORD, dwWriteCoord: COORD, - lpNumberOfCharsWritten: LPDWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "FillConsoleOutputCharacterA".} -proc ScrollConsoleScreenBufferA*(hConsoleOutput: HANDLE, - lpScrollRectangle: PSMALL_RECT, - lpClipRectangle: PSMALL_RECT, - dwDestinationOrigin: COORD, lpFill: PCHAR_INFO): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "ScrollConsoleScreenBufferA".} -proc GetConsoleTitleA*(lpConsoleTitle: LPSTR, nSize: DWORD): DWORD{.stdcall, - dynlib: "kernel32", importc: "GetConsoleTitleA".} -proc SetConsoleTitleA*(lpConsoleTitle: LPCSTR): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "SetConsoleTitleA".} -proc ReadConsoleA*(hConsoleInput: HANDLE, lpBuffer: LPVOID, - nNumberOfCharsToRead: DWORD, lpNumberOfCharsRead: LPDWORD, - lpReserved: LPVOID): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "ReadConsoleA".} -proc WriteConsoleA*(hConsoleOutput: HANDLE, lpBuffer: pointer, - nNumberOfCharsToWrite: DWORD, - lpNumberOfCharsWritten: LPDWORD, lpReserved: LPVOID): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "WriteConsoleA".} -proc WNetAddConnectionA*(lpRemoteName: LPCSTR, lpPassword: LPCSTR, - lpLocalName: LPCSTR): DWORD{.stdcall, dynlib: "mpr", - importc: "WNetAddConnectionA".} -proc WNetAddConnection2A*(lpNetResource: LPNETRESOURCE, lpPassword: LPCSTR, - lpUserName: LPCSTR, dwFlags: DWORD): DWORD{.stdcall, - dynlib: "mpr", importc: "WNetAddConnection2A".} -proc WNetAddConnection3A*(hwndOwner: HWND, lpNetResource: LPNETRESOURCE, - lpPassword: LPCSTR, lpUserName: LPCSTR, dwFlags: DWORD): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetAddConnection3A".} -proc WNetCancelConnectionA*(lpName: LPCSTR, fForce: WINBOOL): DWORD{.stdcall, - dynlib: "mpr", importc: "WNetCancelConnectionA".} -proc WNetCancelConnection2A*(lpName: LPCSTR, dwFlags: DWORD, fForce: WINBOOL): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetCancelConnection2A".} -proc WNetGetConnectionA*(lpLocalName: LPCSTR, lpRemoteName: LPSTR, - lpnLength: LPDWORD): DWORD{.stdcall, dynlib: "mpr", - importc: "WNetGetConnectionA".} -proc WNetUseConnectionA*(hwndOwner: HWND, lpNetResource: LPNETRESOURCE, - lpUserID: LPCSTR, lpPassword: LPCSTR, dwFlags: DWORD, - lpAccessName: LPSTR, lpBufferSize: LPDWORD, - lpResult: LPDWORD): DWORD{.stdcall, dynlib: "mpr", - importc: "WNetUseConnectionA".} -proc WNetSetConnectionA*(lpName: LPCSTR, dwProperties: DWORD, pvValues: LPVOID): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetSetConnectionA".} -proc WNetConnectionDialog1A*(lpConnDlgStruct: LPCONNECTDLGSTRUCT): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetConnectionDialog1A".} -proc WNetDisconnectDialog1A*(lpConnDlgStruct: LPDISCDLGSTRUCT): DWORD{.stdcall, - dynlib: "mpr", importc: "WNetDisconnectDialog1A".} -proc WNetOpenEnumA*(dwScope: DWORD, dwType: DWORD, dwUsage: DWORD, - lpNetResource: LPNETRESOURCE, lphEnum: LPHANDLE): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetOpenEnumA".} -proc WNetEnumResourceA*(hEnum: HANDLE, lpcCount: LPDWORD, lpBuffer: LPVOID, - lpBufferSize: LPDWORD): DWORD{.stdcall, dynlib: "mpr", - importc: "WNetEnumResourceA".} -proc WNetGetUniversalNameA*(lpLocalPath: LPCSTR, dwInfoLevel: DWORD, - lpBuffer: LPVOID, lpBufferSize: LPDWORD): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetGetUniversalNameA".} -proc WNetGetUserA*(lpName: LPCSTR, lpUserName: LPSTR, lpnLength: LPDWORD): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetGetUserA".} -proc WNetGetProviderNameA*(dwNetType: DWORD, lpProviderName: LPSTR, - lpBufferSize: LPDWORD): DWORD{.stdcall, - dynlib: "mpr", importc: "WNetGetProviderNameA".} -proc WNetGetNetworkInformationA*(lpProvider: LPCSTR, - lpNetInfoStruct: LPNETINFOSTRUCT): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetGetNetworkInformationA".} -proc WNetGetLastErrorA*(lpError: LPDWORD, lpErrorBuf: LPSTR, - nErrorBufSize: DWORD, lpNameBuf: LPSTR, - nNameBufSize: DWORD): DWORD{.stdcall, dynlib: "mpr", - importc: "WNetGetLastErrorA".} -proc MultinetGetConnectionPerformanceA*(lpNetResource: LPNETRESOURCE, - lpNetConnectInfoStruct: LPNETCONNECTINFOSTRUCT): DWORD{.stdcall, - dynlib: "mpr", importc: "MultinetGetConnectionPerformanceA".} -proc ChangeServiceConfigA*(hService: SC_HANDLE, dwServiceType: DWORD, - dwStartType: DWORD, dwErrorControl: DWORD, - lpBinaryPathName: LPCSTR, lpLoadOrderGroup: LPCSTR, - lpdwTagId: LPDWORD, lpDependencies: LPCSTR, - lpServiceStartName: LPCSTR, lpPassword: LPCSTR, - lpDisplayName: LPCSTR): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "ChangeServiceConfigA".} -proc CreateServiceA*(hSCManager: SC_HANDLE, lpServiceName: LPCSTR, - lpDisplayName: LPCSTR, dwDesiredAccess: DWORD, - dwServiceType: DWORD, dwStartType: DWORD, - dwErrorControl: DWORD, lpBinaryPathName: LPCSTR, - lpLoadOrderGroup: LPCSTR, lpdwTagId: LPDWORD, - lpDependencies: LPCSTR, lpServiceStartName: LPCSTR, - lpPassword: LPCSTR): SC_HANDLE{.stdcall, - dynlib: "advapi32", importc: "CreateServiceA".} -proc EnumDependentServicesA*(hService: SC_HANDLE, dwServiceState: DWORD, - lpServices: LPENUM_SERVICE_STATUS, - cbBufSize: DWORD, pcbBytesNeeded: LPDWORD, - lpServicesReturned: LPDWORD): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "EnumDependentServicesA".} -proc EnumServicesStatusA*(hSCManager: SC_HANDLE, dwServiceType: DWORD, - dwServiceState: DWORD, - lpServices: LPENUM_SERVICE_STATUS, cbBufSize: DWORD, - pcbBytesNeeded: LPDWORD, lpServicesReturned: LPDWORD, - lpResumeHandle: LPDWORD): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "EnumServicesStatusA".} -proc GetServiceKeyNameA*(hSCManager: SC_HANDLE, lpDisplayName: LPCSTR, - lpServiceName: LPSTR, lpcchBuffer: LPDWORD): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "GetServiceKeyNameA".} -proc GetServiceDisplayNameA*(hSCManager: SC_HANDLE, lpServiceName: LPCSTR, - lpDisplayName: LPSTR, lpcchBuffer: LPDWORD): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "GetServiceDisplayNameA".} -proc OpenSCManagerA*(lpMachineName: LPCSTR, lpDatabaseName: LPCSTR, - dwDesiredAccess: DWORD): SC_HANDLE{.stdcall, - dynlib: "advapi32", importc: "OpenSCManagerA".} -proc OpenServiceA*(hSCManager: SC_HANDLE, lpServiceName: LPCSTR, - dwDesiredAccess: DWORD): SC_HANDLE{.stdcall, - dynlib: "advapi32", importc: "OpenServiceA".} -proc QueryServiceConfigA*(hService: SC_HANDLE, - lpServiceConfig: LPQUERY_SERVICE_CONFIG, - cbBufSize: DWORD, pcbBytesNeeded: LPDWORD): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "QueryServiceConfigA".} -proc QueryServiceLockStatusA*(hSCManager: SC_HANDLE, - lpLockStatus: LPQUERY_SERVICE_LOCK_STATUS, - cbBufSize: DWORD, pcbBytesNeeded: LPDWORD): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "QueryServiceLockStatusA".} -proc RegisterServiceCtrlHandlerA*(lpServiceName: LPCSTR, - lpHandlerProc: LPHANDLER_FUNCTION): SERVICE_STATUS_HANDLE{. - stdcall, dynlib: "advapi32", importc: "RegisterServiceCtrlHandlerA".} -proc StartServiceCtrlDispatcherA*(lpServiceStartTable: LPSERVICE_TABLE_ENTRY): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "StartServiceCtrlDispatcherA".} -proc StartServiceA*(hService: SC_HANDLE, dwNumServiceArgs: DWORD, - lpServiceArgVectors: LPCSTR): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "StartServiceA".} -proc DragQueryFileA*(para1: HDROP, para2: int, para3: cstring, para4: int): int{. - stdcall, dynlib: "shell32", importc: "DragQueryFileA".} -proc ExtractAssociatedIconA*(para1: HINST, para2: cstring, para3: LPWORD): HICON{. - stdcall, dynlib: "shell32", importc: "ExtractAssociatedIconA".} -proc ExtractIconA*(para1: HINST, para2: cstring, para3: int): HICON{.stdcall, - dynlib: "shell32", importc: "ExtractIconA".} -proc FindExecutableA*(para1: cstring, para2: cstring, para3: cstring): HINST{. - stdcall, dynlib: "shell32", importc: "FindExecutableA".} -proc ShellAboutA*(para1: HWND, para2: cstring, para3: cstring, para4: HICON): int32{. - stdcall, dynlib: "shell32", importc: "ShellAboutA".} -proc ShellExecuteA*(para1: HWND, para2: cstring, para3: cstring, para4: cstring, - para5: cstring, para6: int32): HINST{.stdcall, - dynlib: "shell32", importc: "ShellExecuteA".} -proc Shell_NotifyIconA*(dwMessage: DWORD, lpData: PNotifyIconDataA): WINBOOL{. - stdcall, dynlib: "shell32", importc: "Shell_NotifyIconA".} -proc DdeCreateStringHandleA*(para1: DWORD, para2: cstring, para3: int32): HSZ{. - stdcall, dynlib: "user32", importc: "DdeCreateStringHandleA".} -proc DdeInitializeA*(para1: LPDWORD, para2: PFNCALLBACK, para3: DWORD, - para4: DWORD): WINUINT{.stdcall, dynlib: "user32", - importc: "DdeInitializeA".} -proc DdeQueryStringA*(para1: DWORD, para2: HSZ, para3: cstring, para4: DWORD, - para5: int32): DWORD{.stdcall, dynlib: "user32", - importc: "DdeQueryStringA".} -proc LogonUserA*(para1: LPSTR, para2: LPSTR, para3: LPSTR, para4: DWORD, - para5: DWORD, para6: PHANDLE): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "LogonUserA".} -proc CreateProcessAsUserA*(para1: HANDLE, para2: LPCTSTR, para3: LPTSTR, - para4: LPSECURITY_ATTRIBUTES, - para5: LPSECURITY_ATTRIBUTES, para6: WINBOOL, - para7: DWORD, para8: LPVOID, para9: LPCTSTR, - para10: LPSTARTUPINFO, para11: LPPROCESS_INFORMATION): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "CreateProcessAsUserA".} -proc GetBinaryTypeW*(lpApplicationName: LPCWSTR, lpBinaryType: LPDWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetBinaryTypeW".} -proc GetShortPathNameW*(lpszLongPath: LPCWSTR, lpszShortPath: LPWSTR, - cchBuffer: DWORD): DWORD{.stdcall, dynlib: "kernel32", - importc: "GetShortPathNameW".} -proc GetEnvironmentStringsW*(): LPWSTR{.stdcall, dynlib: "kernel32", - importc: "GetEnvironmentStringsW".} -proc FreeEnvironmentStringsW*(para1: LPWSTR): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "FreeEnvironmentStringsW".} -proc FormatMessageW*(dwFlags: DWORD, lpSource: LPCVOID, dwMessageId: DWORD, - dwLanguageId: DWORD, lpBuffer: LPWSTR, nSize: DWORD, - Arguments: va_list): DWORD{.stdcall, dynlib: "kernel32", - importc: "FormatMessageW".} -proc CreateMailslotW*(lpName: LPCWSTR, nMaxMessageSize: DWORD, - lReadTimeout: DWORD, - lpSecurityAttributes: LPSECURITY_ATTRIBUTES): HANDLE{. - stdcall, dynlib: "kernel32", importc: "CreateMailslotW".} -proc lstrcmpW*(lpString1: LPCWSTR, lpString2: LPCWSTR): int32{.stdcall, - dynlib: "kernel32", importc: "lstrcmpW".} -proc lstrcmpiW*(lpString1: LPCWSTR, lpString2: LPCWSTR): int32{.stdcall, - dynlib: "kernel32", importc: "lstrcmpiW".} -proc lstrcpynW*(lpString1: LPWSTR, lpString2: LPCWSTR, iMaxLength: int32): LPWSTR{. - stdcall, dynlib: "kernel32", importc: "lstrcpynW".} -proc lstrcpyW*(lpString1: LPWSTR, lpString2: LPCWSTR): LPWSTR{.stdcall, - dynlib: "kernel32", importc: "lstrcpyW".} -proc lstrcatW*(lpString1: LPWSTR, lpString2: LPCWSTR): LPWSTR{.stdcall, - dynlib: "kernel32", importc: "lstrcatW".} -proc lstrlenW*(lpString: LPCWSTR): int32{.stdcall, dynlib: "kernel32", - importc: "lstrlenW".} -proc CreateMutexW*(lpMutexAttributes: LPSECURITY_ATTRIBUTES, - bInitialOwner: WINBOOL, lpName: LPCWSTR): HANDLE{.stdcall, - dynlib: "kernel32", importc: "CreateMutexW".} -proc OpenMutexW*(dwDesiredAccess: DWORD, bInheritHandle: WINBOOL, - lpName: LPCWSTR): HANDLE{.stdcall, dynlib: "kernel32", - importc: "OpenMutexW".} -proc CreateEventW*(lpEventAttributes: LPSECURITY_ATTRIBUTES, - bManualReset: WINBOOL, bInitialState: WINBOOL, - lpName: LPCWSTR): HANDLE{.stdcall, dynlib: "kernel32", - importc: "CreateEventW".} -proc OpenEventW*(dwDesiredAccess: DWORD, bInheritHandle: WINBOOL, - lpName: LPCWSTR): HANDLE{.stdcall, dynlib: "kernel32", - importc: "OpenEventW".} -proc CreateSemaphoreW*(lpSemaphoreAttributes: LPSECURITY_ATTRIBUTES, - lInitialCount: LONG, lMaximumCount: LONG, lpName: LPCWSTR): HANDLE{. - stdcall, dynlib: "kernel32", importc: "CreateSemaphoreW".} -proc OpenSemaphoreW*(dwDesiredAccess: DWORD, bInheritHandle: WINBOOL, - lpName: LPCWSTR): HANDLE{.stdcall, dynlib: "kernel32", - importc: "OpenSemaphoreW".} -proc CreateFileMappingW*(hFile: HANDLE, - lpFileMappingAttributes: LPSECURITY_ATTRIBUTES, - flProtect: DWORD, dwMaximumSizeHigh: DWORD, - dwMaximumSizeLow: DWORD, lpName: LPCWSTR): HANDLE{. - stdcall, dynlib: "kernel32", importc: "CreateFileMappingW".} -proc OpenFileMappingW*(dwDesiredAccess: DWORD, bInheritHandle: WINBOOL, - lpName: LPCWSTR): HANDLE{.stdcall, dynlib: "kernel32", - importc: "OpenFileMappingW".} -proc GetLogicalDriveStringsW*(nBufferLength: DWORD, lpBuffer: LPWSTR): DWORD{. - stdcall, dynlib: "kernel32", importc: "GetLogicalDriveStringsW".} -proc LoadLibraryW*(lpLibFileName: LPCWSTR): HINST{.stdcall, dynlib: "kernel32", - importc: "LoadLibraryW".} -proc LoadLibraryExW*(lpLibFileName: LPCWSTR, hFile: HANDLE, dwFlags: DWORD): HINST{. - stdcall, dynlib: "kernel32", importc: "LoadLibraryExW".} -proc GetModuleFileNameW*(hModule: HINST, lpFilename: LPWSTR, nSize: DWORD): DWORD{. - stdcall, dynlib: "kernel32", importc: "GetModuleFileNameW".} -proc GetModuleHandleW*(lpModuleName: LPCWSTR): HMODULE{.stdcall, - dynlib: "kernel32", importc: "GetModuleHandleW".} -proc FatalAppExitW*(uAction: WINUINT, lpMessageText: LPCWSTR){.stdcall, - dynlib: "kernel32", importc: "FatalAppExitW".} -proc GetCommandLineW*(): LPWSTR{.stdcall, dynlib: "kernel32", - importc: "GetCommandLineW".} -proc GetEnvironmentVariableW*(lpName: LPCWSTR, lpBuffer: LPWSTR, nSize: DWORD): DWORD{. - stdcall, dynlib: "kernel32", importc: "GetEnvironmentVariableW".} -proc SetEnvironmentVariableW*(lpName: LPCWSTR, lpValue: LPCWSTR): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "SetEnvironmentVariableW".} -proc ExpandEnvironmentStringsW*(lpSrc: LPCWSTR, lpDst: LPWSTR, nSize: DWORD): DWORD{. - stdcall, dynlib: "kernel32", importc: "ExpandEnvironmentStringsW".} -proc OutputDebugStringW*(lpOutputString: LPCWSTR){.stdcall, dynlib: "kernel32", - importc: "OutputDebugStringW".} -proc FindResourceW*(hModule: HINST, lpName: LPCWSTR, lpType: LPCWSTR): HRSRC{. - stdcall, dynlib: "kernel32", importc: "FindResourceW".} -proc FindResourceExW*(hModule: HINST, lpType: LPCWSTR, lpName: LPCWSTR, - wLanguage: int16): HRSRC{.stdcall, dynlib: "kernel32", - importc: "FindResourceExW".} -proc EnumResourceTypesW*(hModule: HINST, lpEnumFunc: ENUMRESTYPEPROC, - lParam: LONG): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "EnumResourceTypesW".} -proc EnumResourceNamesW*(hModule: HINST, lpType: LPCWSTR, - lpEnumFunc: ENUMRESNAMEPROC, lParam: LONG): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "EnumResourceNamesW".} -proc EnumResourceLanguagesW*(hModule: HINST, lpType: LPCWSTR, lpName: LPCWSTR, - lpEnumFunc: ENUMRESLANGPROC, lParam: LONG): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "EnumResourceLanguagesW".} -proc BeginUpdateResourceW*(pFileName: LPCWSTR, bDeleteExistingResources: WINBOOL): HANDLE{. - stdcall, dynlib: "kernel32", importc: "BeginUpdateResourceW".} -proc UpdateResourceW*(hUpdate: HANDLE, lpType: LPCWSTR, lpName: LPCWSTR, - wLanguage: int16, lpData: LPVOID, cbData: DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "UpdateResourceW".} -proc EndUpdateResourceW*(hUpdate: HANDLE, fDiscard: WINBOOL): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "EndUpdateResourceW".} -proc GlobalAddAtomW*(lpString: LPCWSTR): ATOM{.stdcall, dynlib: "kernel32", - importc: "GlobalAddAtomW".} -proc GlobalFindAtomW*(lpString: LPCWSTR): ATOM{.stdcall, dynlib: "kernel32", - importc: "GlobalFindAtomW".} -proc GlobalGetAtomNameW*(nAtom: ATOM, lpBuffer: LPWSTR, nSize: int32): WINUINT{. - stdcall, dynlib: "kernel32", importc: "GlobalGetAtomNameW".} -proc AddAtomW*(lpString: LPCWSTR): ATOM{.stdcall, dynlib: "kernel32", - importc: "AddAtomW".} -proc FindAtomW*(lpString: LPCWSTR): ATOM{.stdcall, dynlib: "kernel32", - importc: "FindAtomW".} -proc GetAtomNameW*(nAtom: ATOM, lpBuffer: LPWSTR, nSize: int32): WINUINT{.stdcall, - dynlib: "kernel32", importc: "GetAtomNameW".} -proc GetProfileIntW*(lpAppName: LPCWSTR, lpKeyName: LPCWSTR, nDefault: WINT): WINUINT{. - stdcall, dynlib: "kernel32", importc: "GetProfileIntW".} -proc GetProfileStringW*(lpAppName: LPCWSTR, lpKeyName: LPCWSTR, - lpDefault: LPCWSTR, lpReturnedString: LPWSTR, - nSize: DWORD): DWORD{.stdcall, dynlib: "kernel32", - importc: "GetProfileStringW".} -proc WriteProfileStringW*(lpAppName: LPCWSTR, lpKeyName: LPCWSTR, - lpString: LPCWSTR): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "WriteProfileStringW".} -proc GetProfileSectionW*(lpAppName: LPCWSTR, lpReturnedString: LPWSTR, - nSize: DWORD): DWORD{.stdcall, dynlib: "kernel32", - importc: "GetProfileSectionW".} -proc WriteProfileSectionW*(lpAppName: LPCWSTR, lpString: LPCWSTR): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "WriteProfileSectionW".} -proc GetPrivateProfileIntW*(lpAppName: LPCWSTR, lpKeyName: LPCWSTR, - nDefault: WINT, lpFileName: LPCWSTR): WINUINT{.stdcall, - dynlib: "kernel32", importc: "GetPrivateProfileIntW".} -proc GetPrivateProfileStringW*(lpAppName: LPCWSTR, lpKeyName: LPCWSTR, - lpDefault: LPCWSTR, lpReturnedString: LPWSTR, - nSize: DWORD, lpFileName: LPCWSTR): DWORD{. - stdcall, dynlib: "kernel32", importc: "GetPrivateProfileStringW".} -proc WritePrivateProfileStringW*(lpAppName: LPCWSTR, lpKeyName: LPCWSTR, - lpString: LPCWSTR, lpFileName: LPCWSTR): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "WritePrivateProfileStringW".} -proc GetPrivateProfileSectionW*(lpAppName: LPCWSTR, lpReturnedString: LPWSTR, - nSize: DWORD, lpFileName: LPCWSTR): DWORD{. - stdcall, dynlib: "kernel32", importc: "GetPrivateProfileSectionW".} -proc WritePrivateProfileSectionW*(lpAppName: LPCWSTR, lpString: LPCWSTR, - lpFileName: LPCWSTR): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "WritePrivateProfileSectionW".} -proc GetDriveTypeW*(lpRootPathName: LPCWSTR): WINUINT{.stdcall, dynlib: "kernel32", - importc: "GetDriveTypeW".} -proc GetSystemDirectoryW*(lpBuffer: LPWSTR, uSize: WINUINT): WINUINT{.stdcall, - dynlib: "kernel32", importc: "GetSystemDirectoryW".} -proc GetTempPathW*(nBufferLength: DWORD, lpBuffer: LPWSTR): DWORD{.stdcall, - dynlib: "kernel32", importc: "GetTempPathW".} -proc GetTempFileNameW*(lpPathName: LPCWSTR, lpPrefixString: LPCWSTR, - uUnique: WINUINT, lpTempFileName: LPWSTR): WINUINT{.stdcall, - dynlib: "kernel32", importc: "GetTempFileNameW".} -proc GetWindowsDirectoryW*(lpBuffer: LPWSTR, uSize: WINUINT): WINUINT{.stdcall, - dynlib: "kernel32", importc: "GetWindowsDirectoryW".} -proc SetCurrentDirectoryW*(lpPathName: LPCWSTR): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "SetCurrentDirectoryW".} -proc GetCurrentDirectoryW*(nBufferLength: DWORD, lpBuffer: LPWSTR): DWORD{. - stdcall, dynlib: "kernel32", importc: "GetCurrentDirectoryW".} -proc GetDiskFreeSpaceW*(lpRootPathName: LPCWSTR, lpSectorsPerCluster: LPDWORD, - lpBytesPerSector: LPDWORD, - lpNumberOfFreeClusters: LPDWORD, - lpTotalNumberOfClusters: LPDWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetDiskFreeSpaceW".} -proc CreateDirectoryW*(lpPathName: LPCWSTR, - lpSecurityAttributes: LPSECURITY_ATTRIBUTES): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "CreateDirectoryW".} -proc CreateDirectoryExW*(lpTemplateDirectory: LPCWSTR, lpNewDirectory: LPCWSTR, - lpSecurityAttributes: LPSECURITY_ATTRIBUTES): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "CreateDirectoryExW".} -proc RemoveDirectoryW*(lpPathName: LPCWSTR): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "RemoveDirectoryW".} -proc GetFullPathNameW*(lpFileName: LPCWSTR, nBufferLength: DWORD, - lpBuffer: LPWSTR, lpFilePart: var LPWSTR): DWORD{. - stdcall, dynlib: "kernel32", importc: "GetFullPathNameW".} -proc DefineDosDeviceW*(dwFlags: DWORD, lpDeviceName: LPCWSTR, - lpTargetPath: LPCWSTR): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "DefineDosDeviceW".} -proc QueryDosDeviceW*(lpDeviceName: LPCWSTR, lpTargetPath: LPWSTR, - ucchMax: DWORD): DWORD{.stdcall, dynlib: "kernel32", - importc: "QueryDosDeviceW".} -proc CreateFileW*(lpFileName: LPCWSTR, dwDesiredAccess: DWORD, - dwShareMode: DWORD, - lpSecurityAttributes: LPSECURITY_ATTRIBUTES, - dwCreationDisposition: DWORD, dwFlagsAndAttributes: DWORD, - hTemplateFile: HANDLE): HANDLE{.stdcall, dynlib: "kernel32", - importc: "CreateFileW".} -proc SetFileAttributesW*(lpFileName: LPCWSTR, dwFileAttributes: DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "SetFileAttributesW".} -proc GetFileAttributesW*(lpFileName: LPCWSTR): DWORD{.stdcall, - dynlib: "kernel32", importc: "GetFileAttributesW".} -proc GetCompressedFileSizeW*(lpFileName: LPCWSTR, lpFileSizeHigh: LPDWORD): DWORD{. - stdcall, dynlib: "kernel32", importc: "GetCompressedFileSizeW".} -proc DeleteFileW*(lpFileName: LPCWSTR): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "DeleteFileW".} -proc SearchPathW*(lpPath: LPCWSTR, lpFileName: LPCWSTR, lpExtension: LPCWSTR, - nBufferLength: DWORD, lpBuffer: LPWSTR, lpFilePart: LPWSTR): DWORD{. - stdcall, dynlib: "kernel32", importc: "SearchPathW".} -proc CopyFileW*(lpExistingFileName: LPCWSTR, lpNewFileName: LPCWSTR, - bFailIfExists: WINBOOL): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "CopyFileW".} -proc MoveFileW*(lpExistingFileName: LPCWSTR, lpNewFileName: LPCWSTR): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "MoveFileW".} -proc MoveFileExW*(lpExistingFileName: LPCWSTR, lpNewFileName: LPCWSTR, - dwFlags: DWORD): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "MoveFileExW".} -proc CreateNamedPipeW*(lpName: LPCWSTR, dwOpenMode: DWORD, dwPipeMode: DWORD, - nMaxInstances: DWORD, nOutBufferSize: DWORD, - nInBufferSize: DWORD, nDefaultTimeOut: DWORD, - lpSecurityAttributes: LPSECURITY_ATTRIBUTES): HANDLE{. - stdcall, dynlib: "kernel32", importc: "CreateNamedPipeW".} -proc GetNamedPipeHandleStateW*(hNamedPipe: HANDLE, lpState: LPDWORD, - lpCurInstances: LPDWORD, - lpMaxCollectionCount: LPDWORD, - lpCollectDataTimeout: LPDWORD, - lpUserName: LPWSTR, nMaxUserNameSize: DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetNamedPipeHandleStateW".} -proc CallNamedPipeW*(lpNamedPipeName: LPCWSTR, lpInBuffer: LPVOID, - nInBufferSize: DWORD, lpOutBuffer: LPVOID, - nOutBufferSize: DWORD, lpBytesRead: LPDWORD, - nTimeOut: DWORD): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "CallNamedPipeW".} -proc WaitNamedPipeW*(lpNamedPipeName: LPCWSTR, nTimeOut: DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "WaitNamedPipeW".} -proc SetVolumeLabelW*(lpRootPathName: LPCWSTR, lpVolumeName: LPCWSTR): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "SetVolumeLabelW".} -proc GetVolumeInformationW*(lpRootPathName: LPCWSTR, lpVolumeNameBuffer: LPWSTR, - nVolumeNameSize: DWORD, - lpVolumeSerialNumber: LPDWORD, - lpMaximumComponentLength: LPDWORD, - lpFileSystemFlags: LPDWORD, - lpFileSystemNameBuffer: LPWSTR, - nFileSystemNameSize: DWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetVolumeInformationW".} -proc ClearEventLogW*(hEventLog: HANDLE, lpBackupFileName: LPCWSTR): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "ClearEventLogW".} -proc BackupEventLogW*(hEventLog: HANDLE, lpBackupFileName: LPCWSTR): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "BackupEventLogW".} -proc OpenEventLogW*(lpUNCServerName: LPCWSTR, lpSourceName: LPCWSTR): HANDLE{. - stdcall, dynlib: "advapi32", importc: "OpenEventLogW".} -proc RegisterEventSourceW*(lpUNCServerName: LPCWSTR, lpSourceName: LPCWSTR): HANDLE{. - stdcall, dynlib: "advapi32", importc: "RegisterEventSourceW".} -proc OpenBackupEventLogW*(lpUNCServerName: LPCWSTR, lpFileName: LPCWSTR): HANDLE{. - stdcall, dynlib: "advapi32", importc: "OpenBackupEventLogW".} -proc ReadEventLogW*(hEventLog: HANDLE, dwReadFlags: DWORD, - dwRecordOffset: DWORD, lpBuffer: LPVOID, - nNumberOfBytesToRead: DWORD, pnBytesRead: LPDWORD, - pnMinNumberOfBytesNeeded: LPDWORD): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "ReadEventLogW".} -proc ReportEventW*(hEventLog: HANDLE, wType: int16, wCategory: int16, - dwEventID: DWORD, lpUserSid: PSID, wNumStrings: int16, - dwDataSize: DWORD, lpStrings: LPPCWSTR, lpRawData: LPVOID): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "ReportEventW".} -proc AccessCheckAndAuditAlarmW*(SubsystemName: LPCWSTR, HandleId: LPVOID, - ObjectTypeName: LPWSTR, ObjectName: LPWSTR, - SecurityDescriptor: PSECURITY_DESCRIPTOR, - DesiredAccess: DWORD, - GenericMapping: PGENERIC_MAPPING, - ObjectCreation: WINBOOL, GrantedAccess: LPDWORD, - AccessStatus: LPBOOL, pfGenerateOnClose: LPBOOL): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "AccessCheckAndAuditAlarmW".} -proc ObjectOpenAuditAlarmW*(SubsystemName: LPCWSTR, HandleId: LPVOID, - ObjectTypeName: LPWSTR, ObjectName: LPWSTR, - pSecurityDescriptor: PSECURITY_DESCRIPTOR, - ClientToken: HANDLE, DesiredAccess: DWORD, - GrantedAccess: DWORD, Privileges: PPRIVILEGE_SET, - ObjectCreation: WINBOOL, AccessGranted: WINBOOL, - GenerateOnClose: LPBOOL): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "ObjectOpenAuditAlarmW".} -proc ObjectPrivilegeAuditAlarmW*(SubsystemName: LPCWSTR, HandleId: LPVOID, - ClientToken: HANDLE, DesiredAccess: DWORD, - Privileges: PPRIVILEGE_SET, - AccessGranted: WINBOOL): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "ObjectPrivilegeAuditAlarmW".} -proc ObjectCloseAuditAlarmW*(SubsystemName: LPCWSTR, HandleId: LPVOID, - GenerateOnClose: WINBOOL): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "ObjectCloseAuditAlarmW".} -proc PrivilegedServiceAuditAlarmW*(SubsystemName: LPCWSTR, ServiceName: LPCWSTR, - ClientToken: HANDLE, - Privileges: PPRIVILEGE_SET, - AccessGranted: WINBOOL): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "PrivilegedServiceAuditAlarmW".} -proc SetFileSecurityW*(lpFileName: LPCWSTR, - SecurityInformation: SECURITY_INFORMATION, - pSecurityDescriptor: PSECURITY_DESCRIPTOR): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "SetFileSecurityW".} -proc GetFileSecurityW*(lpFileName: LPCWSTR, - RequestedInformation: SECURITY_INFORMATION, - pSecurityDescriptor: PSECURITY_DESCRIPTOR, - nLength: DWORD, lpnLengthNeeded: LPDWORD): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "GetFileSecurityW".} -proc FindFirstChangeNotificationW*(lpPathName: LPCWSTR, bWatchSubtree: WINBOOL, - dwNotifyFilter: DWORD): HANDLE{.stdcall, - dynlib: "kernel32", importc: "FindFirstChangeNotificationW".} -proc IsBadStringPtrW*(lpsz: LPCWSTR, ucchMax: WINUINT): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "IsBadStringPtrW".} -proc LookupAccountSidW*(lpSystemName: LPCWSTR, Sid: PSID, Name: LPWSTR, - cbName: LPDWORD, ReferencedDomainName: LPWSTR, - cbReferencedDomainName: LPDWORD, peUse: PSID_NAME_USE): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "LookupAccountSidW".} -proc LookupAccountNameW*(lpSystemName: LPCWSTR, lpAccountName: LPCWSTR, - Sid: PSID, cbSid: LPDWORD, - ReferencedDomainName: LPWSTR, - cbReferencedDomainName: LPDWORD, peUse: PSID_NAME_USE): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "LookupAccountNameW".} -proc LookupPrivilegeValueW*(lpSystemName: LPCWSTR, lpName: LPCWSTR, - lpLuid: PLUID): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "LookupPrivilegeValueW".} -proc LookupPrivilegeNameW*(lpSystemName: LPCWSTR, lpLuid: PLUID, lpName: LPWSTR, - cbName: LPDWORD): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "LookupPrivilegeNameW".} -proc LookupPrivilegeDisplayNameW*(lpSystemName: LPCWSTR, lpName: LPCWSTR, - lpDisplayName: LPWSTR, cbDisplayName: LPDWORD, - lpLanguageId: LPDWORD): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "LookupPrivilegeDisplayNameW".} -proc BuildCommDCBW*(lpDef: LPCWSTR, lpDCB: LPDCB): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "BuildCommDCBW".} -proc BuildCommDCBAndTimeoutsW*(lpDef: LPCWSTR, lpDCB: LPDCB, - lpCommTimeouts: LPCOMMTIMEOUTS): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "BuildCommDCBAndTimeoutsW".} -proc CommConfigDialogW*(lpszName: LPCWSTR, wnd: HWND, lpCC: LPCOMMCONFIG): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "CommConfigDialogW".} -proc GetDefaultCommConfigW*(lpszName: LPCWSTR, lpCC: LPCOMMCONFIG, - lpdwSize: LPDWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetDefaultCommConfigW".} -proc SetDefaultCommConfigW*(lpszName: LPCWSTR, lpCC: LPCOMMCONFIG, dwSize: DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "SetDefaultCommConfigW".} -proc GetComputerNameW*(lpBuffer: LPWSTR, nSize: LPDWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetComputerNameW".} -proc SetComputerNameW*(lpComputerName: LPCWSTR): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "SetComputerNameW".} -proc GetUserNameW*(lpBuffer: LPWSTR, nSize: LPDWORD): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "GetUserNameW".} -proc LoadKeyboardLayoutW*(pwszKLID: LPCWSTR, Flags: WINUINT): HKL{.stdcall, - dynlib: "user32", importc: "LoadKeyboardLayoutW".} -proc GetKeyboardLayoutNameW*(pwszKLID: LPWSTR): WINBOOL{.stdcall, - dynlib: "user32", importc: "GetKeyboardLayoutNameW".} -proc CreateDesktopW*(lpszDesktop: LPWSTR, lpszDevice: LPWSTR, - pDevmodew: LPDEVMODEw, dwFlags: DWORD, - dwDesiredAccess: DWORD, lpsa: LPSECURITY_ATTRIBUTES): HDESK{. - stdcall, dynlib: "user32", importc: "CreateDesktopW".} -proc OpenDesktopW*(lpszDesktop: LPWSTR, dwFlags: DWORD, fInherit: WINBOOL, - dwDesiredAccess: DWORD): HDESK{.stdcall, dynlib: "user32", - importc: "OpenDesktopW".} -proc EnumDesktopsW*(hwinsta: HWINSTA, lpEnumFunc: DESKTOPENUMPROC, - lp: LPARAM): WINBOOL{.stdcall, dynlib: "user32", - importc: "EnumDesktopsW".} -proc CreateWindowStationW*(lpwinsta: LPWSTR, dwReserved: DWORD, - dwDesiredAccess: DWORD, lpsa: LPSECURITY_ATTRIBUTES): HWINSTA{. - stdcall, dynlib: "user32", importc: "CreateWindowStationW".} -proc OpenWindowStationW*(lpszWinSta: LPWSTR, fInherit: WINBOOL, - dwDesiredAccess: DWORD): HWINSTA{.stdcall, - dynlib: "user32", importc: "OpenWindowStationW".} -proc EnumWindowStationsW*(lpEnumFunc: ENUMWINDOWSTATIONPROC, lp: LPARAM): WINBOOL{. - stdcall, dynlib: "user32", importc: "EnumWindowStationsW".} -proc GetUserObjectInformationW*(hObj: HANDLE, nIndex: int32, pvInfo: PVOID, - nLength: DWORD, lpnLengthNeeded: LPDWORD): WINBOOL{. - stdcall, dynlib: "user32", importc: "GetUserObjectInformationW".} -proc SetUserObjectInformationW*(hObj: HANDLE, nIndex: int32, pvInfo: PVOID, - nLength: DWORD): WINBOOL{.stdcall, - dynlib: "user32", importc: "SetUserObjectInformationW".} -proc RegisterWindowMessageW*(lpString: LPCWSTR): WINUINT{.stdcall, - dynlib: "user32", importc: "RegisterWindowMessageW".} -proc GetMessageW*(lpMsg: LPMSG, wnd: HWND, wMsgFilterMin: WINUINT, - wMsgFilterMax: WINUINT): WINBOOL{.stdcall, dynlib: "user32", - importc: "GetMessageW".} -proc DispatchMessageW*(lpMsg: LPMSG): LONG{.stdcall, dynlib: "user32", - importc: "DispatchMessageW".} -proc PeekMessageW*(lpMsg: LPMSG, wnd: HWND, wMsgFilterMin: WINUINT, - wMsgFilterMax: WINUINT, wRemoveMsg: WINUINT): WINBOOL{.stdcall, - dynlib: "user32", importc: "PeekMessageW".} -proc SendMessageW*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): LRESULT{. - stdcall, dynlib: "user32", importc: "SendMessageW".} -proc SendMessageTimeoutW*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM, - fuFlags: WINUINT, uTimeout: WINUINT, lpdwResult: LPDWORD): LRESULT{. - stdcall, dynlib: "user32", importc: "SendMessageTimeoutW".} -proc SendNotifyMessageW*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): WINBOOL{. - stdcall, dynlib: "user32", importc: "SendNotifyMessageW".} -proc SendMessageCallbackW*(wnd: HWND, Msg: WINUINT, wp: WPARAM, - lp: LPARAM, lpResultCallBack: SENDASYNCPROC, - dwData: DWORD): WINBOOL{.stdcall, dynlib: "user32", - importc: "SendMessageCallbackW".} -proc PostMessageW*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): WINBOOL{. - stdcall, dynlib: "user32", importc: "PostMessageW".} -proc PostThreadMessageW*(idThread: DWORD, Msg: WINUINT, wp: WPARAM, - lp: LPARAM): WINBOOL{.stdcall, dynlib: "user32", - importc: "PostThreadMessageW".} -proc DefWindowProcW*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): LRESULT{. - stdcall, dynlib: "user32", importc: "DefWindowProcW".} -proc CallWindowProcW*(lpPrevWndFunc: WNDPROC, wnd: HWND, Msg: WINUINT, - wp: WPARAM, lp: LPARAM): LRESULT{.stdcall, - dynlib: "user32", importc: "CallWindowProcW".} -proc RegisterClassW*(lpWndClass: LPWNDCLASSW): ATOM{.stdcall, dynlib: "user32", - importc: "RegisterClassW".} -proc UnregisterClassW*(lpClassName: LPCWSTR, hInstance: HINST): WINBOOL{. - stdcall, dynlib: "user32", importc: "UnregisterClassW".} -proc GetClassInfoW*(hInstance: HINST, lpClassName: LPCWSTR, - lpWndClass: LPWNDCLASS): WINBOOL{.stdcall, dynlib: "user32", - importc: "GetClassInfoW".} -proc RegisterClassExW*(para1: LPWNDCLASSEXW): ATOM{.stdcall, dynlib: "user32", - importc: "RegisterClassExW".} -proc GetClassInfoExW*(para1: HINST, para2: LPCWSTR, para3: LPWNDCLASSEX): WINBOOL{. - stdcall, dynlib: "user32", importc: "GetClassInfoExW".} -proc CreateWindowExW*(dwExStyle: DWORD, lpClassName: LPCWSTR, - lpWindowName: LPCWSTR, dwStyle: DWORD, X: int32, Y: int32, - nWidth: int32, nHeight: int32, hWndParent: HWND, - menu: HMENU, hInstance: HINST, lpParam: LPVOID): HWND{. - stdcall, dynlib: "user32", importc: "CreateWindowExW".} -proc CreateDialogParamW*(hInstance: HINST, lpTemplateName: LPCWSTR, - hWndParent: HWND, lpDialogFunc: DLGPROC, - dwInitParam: LPARAM): HWND{.stdcall, dynlib: "user32", - importc: "CreateDialogParamW".} -proc CreateDialogIndirectParamW*(hInstance: HINST, lpTemplate: LPCDLGTEMPLATE, - hWndParent: HWND, lpDialogFunc: DLGPROC, - dwInitParam: LPARAM): HWND{.stdcall, - dynlib: "user32", importc: "CreateDialogIndirectParamW".} -proc DialogBoxParamW*(hInstance: HINST, lpTemplateName: LPCWSTR, - hWndParent: HWND, lpDialogFunc: DLGPROC, - dwInitParam: LPARAM): int32{.stdcall, dynlib: "user32", - importc: "DialogBoxParamW".} -proc DialogBoxIndirectParamW*(hInstance: HINST, hDialogTemplate: LPCDLGTEMPLATE, - hWndParent: HWND, lpDialogFunc: DLGPROC, - dwInitParam: LPARAM): int32{.stdcall, - dynlib: "user32", importc: "DialogBoxIndirectParamW".} -proc SetDlgItemTextW*(hDlg: HWND, nIDDlgItem: int32, lpString: LPCWSTR): WINBOOL{. - stdcall, dynlib: "user32", importc: "SetDlgItemTextW".} -proc GetDlgItemTextW*(hDlg: HWND, nIDDlgItem: int32, lpString: LPWSTR, - nMaxCount: int32): WINUINT{.stdcall, dynlib: "user32", - importc: "GetDlgItemTextW".} -proc SendDlgItemMessageW*(hDlg: HWND, nIDDlgItem: int32, Msg: WINUINT, - wp: WPARAM, lp: LPARAM): LONG{.stdcall, - dynlib: "user32", importc: "SendDlgItemMessageW".} -proc DefDlgProcW*(hDlg: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): LRESULT{. - stdcall, dynlib: "user32", importc: "DefDlgProcW".} -proc CallMsgFilterW*(lpMsg: LPMSG, nCode: int32): WINBOOL{.stdcall, - dynlib: "user32", importc: "CallMsgFilterW".} -proc RegisterClipboardFormatW*(lpszFormat: LPCWSTR): WINUINT{.stdcall, - dynlib: "user32", importc: "RegisterClipboardFormatW".} -proc GetClipboardFormatNameW*(format: WINUINT, lpszFormatName: LPWSTR, - cchMaxCount: int32): int32{.stdcall, - dynlib: "user32", importc: "GetClipboardFormatNameW".} -proc CharToOemW*(lpszSrc: LPCWSTR, lpszDst: LPSTR): WINBOOL{.stdcall, - dynlib: "user32", importc: "CharToOemW".} -proc OemToCharW*(lpszSrc: LPCSTR, lpszDst: LPWSTR): WINBOOL{.stdcall, - dynlib: "user32", importc: "OemToCharW".} -proc CharToOemBuffW*(lpszSrc: LPCWSTR, lpszDst: LPSTR, cchDstLength: DWORD): WINBOOL{. - stdcall, dynlib: "user32", importc: "CharToOemBuffW".} -proc OemToCharBuffW*(lpszSrc: LPCSTR, lpszDst: LPWSTR, cchDstLength: DWORD): WINBOOL{. - stdcall, dynlib: "user32", importc: "OemToCharBuffW".} -proc CharUpperW*(lpsz: LPWSTR): LPWSTR{.stdcall, dynlib: "user32", - importc: "CharUpperW".} -proc CharUpperBuffW*(lpsz: LPWSTR, cchLength: DWORD): DWORD{.stdcall, - dynlib: "user32", importc: "CharUpperBuffW".} -proc CharLowerW*(lpsz: LPWSTR): LPWSTR{.stdcall, dynlib: "user32", - importc: "CharLowerW".} -proc CharLowerBuffW*(lpsz: LPWSTR, cchLength: DWORD): DWORD{.stdcall, - dynlib: "user32", importc: "CharLowerBuffW".} -proc CharNextW*(lpsz: LPCWSTR): LPWSTR{.stdcall, dynlib: "user32", - importc: "CharNextW".} -proc CharPrevW*(lpszStart: LPCWSTR, lpszCurrent: LPCWSTR): LPWSTR{.stdcall, - dynlib: "user32", importc: "CharPrevW".} -proc IsCharAlphaW*(ch: WCHAR): WINBOOL{.stdcall, dynlib: "user32", - importc: "IsCharAlphaW".} -proc IsCharAlphaNumericW*(ch: WCHAR): WINBOOL{.stdcall, dynlib: "user32", - importc: "IsCharAlphaNumericW".} -proc IsCharUpperW*(ch: WCHAR): WINBOOL{.stdcall, dynlib: "user32", - importc: "IsCharUpperW".} -proc IsCharLowerW*(ch: WCHAR): WINBOOL{.stdcall, dynlib: "user32", - importc: "IsCharLowerW".} -proc GetKeyNameTextW*(lParam: LONG, lpString: LPWSTR, nSize: int32): int32{. - stdcall, dynlib: "user32", importc: "GetKeyNameTextW".} -proc VkKeyScanW*(ch: WCHAR): SHORT{.stdcall, dynlib: "user32", - importc: "VkKeyScanW".} -proc VkKeyScanExW*(ch: WCHAR, dwhkl: HKL): SHORT{.stdcall, dynlib: "user32", - importc: "VkKeyScanExW".} -proc MapVirtualKeyW*(uCode: WINUINT, uMapType: WINUINT): WINUINT{.stdcall, - dynlib: "user32", importc: "MapVirtualKeyW".} -proc MapVirtualKeyExW*(uCode: WINUINT, uMapType: WINUINT, dwhkl: HKL): WINUINT{.stdcall, - dynlib: "user32", importc: "MapVirtualKeyExW".} -proc LoadAcceleratorsW*(hInstance: HINST, lpTableName: LPCWSTR): HACCEL{. - stdcall, dynlib: "user32", importc: "LoadAcceleratorsW".} -proc CreateAcceleratorTableW*(para1: LPACCEL, para2: int32): HACCEL{.stdcall, - dynlib: "user32", importc: "CreateAcceleratorTableW".} -proc CopyAcceleratorTableW*(hAccelSrc: HACCEL, lpAccelDst: LPACCEL, - cAccelEntries: int32): int32{.stdcall, - dynlib: "user32", importc: "CopyAcceleratorTableW".} -proc TranslateAcceleratorW*(wnd: HWND, hAccTable: HACCEL, lpMsg: LPMSG): int32{. - stdcall, dynlib: "user32", importc: "TranslateAcceleratorW".} -proc LoadMenuW*(hInstance: HINST, lpMenuName: LPCWSTR): HMENU{.stdcall, - dynlib: "user32", importc: "LoadMenuW".} -proc LoadMenuIndirectW*(lpMenuTemplate: LPMENUTEMPLATE): HMENU{.stdcall, - dynlib: "user32", importc: "LoadMenuIndirectW".} -proc ChangeMenuW*(menu: HMENU, cmd: WINUINT, lpszNewItem: LPCWSTR, - cmdInsert: WINUINT, flags: WINUINT): WINBOOL{.stdcall, - dynlib: "user32", importc: "ChangeMenuW".} -proc GetMenuStringW*(menu: HMENU, uIDItem: WINUINT, lpString: LPWSTR, - nMaxCount: int32, uFlag: WINUINT): int32{.stdcall, - dynlib: "user32", importc: "GetMenuStringW".} -proc InsertMenuW*(menu: HMENU, uPosition: WINUINT, uFlags: WINUINT, uIDNewItem: WINUINT, - lpNewItem: LPCWSTR): WINBOOL{.stdcall, dynlib: "user32", - importc: "InsertMenuW".} -proc AppendMenuW*(menu: HMENU, uFlags: WINUINT, uIDNewItem: WINUINT, - lpNewItem: LPCWSTR): WINBOOL{.stdcall, dynlib: "user32", - importc: "AppendMenuW".} -proc ModifyMenuW*(hMnu: HMENU, uPosition: WINUINT, uFlags: WINUINT, uIDNewItem: WINUINT, - lpNewItem: LPCWSTR): WINBOOL{.stdcall, dynlib: "user32", - importc: "ModifyMenuW".} -proc InsertMenuItemW*(para1: HMENU, para2: WINUINT, para3: WINBOOL, - para4: LPCMENUITEMINFO): WINBOOL{.stdcall, - dynlib: "user32", importc: "InsertMenuItemW".} -proc GetMenuItemInfoW*(para1: HMENU, para2: WINUINT, para3: WINBOOL, - para4: LPMENUITEMINFO): WINBOOL{.stdcall, - dynlib: "user32", importc: "GetMenuItemInfoW".} -proc SetMenuItemInfoW*(para1: HMENU, para2: WINUINT, para3: WINBOOL, - para4: LPCMENUITEMINFO): WINBOOL{.stdcall, - dynlib: "user32", importc: "SetMenuItemInfoW".} -proc DrawTextW*(hDC: HDC, lpString: LPCWSTR, nCount: int32, lpRect: LPRECT, - uFormat: WINUINT): int32{.stdcall, dynlib: "user32", - importc: "DrawTextW".} -proc DrawTextExW*(para1: HDC, para2: LPWSTR, para3: int32, para4: LPRECT, - para5: WINUINT, para6: LPDRAWTEXTPARAMS): int32{.stdcall, - dynlib: "user32", importc: "DrawTextExW".} -proc GrayStringW*(hDC: HDC, hBrush: HBRUSH, lpOutputFunc: GRAYSTRINGPROC, - lpData: LPARAM, nCount: int32, X: int32, Y: int32, - nWidth: int32, nHeight: int32): WINBOOL{.stdcall, - dynlib: "user32", importc: "GrayStringW".} -proc DrawStateW*(para1: HDC, para2: HBRUSH, para3: DRAWSTATEPROC, para4: LPARAM, - para5: WPARAM, para6: int32, para7: int32, para8: int32, - para9: int32, para10: WINUINT): WINBOOL{.stdcall, - dynlib: "user32", importc: "DrawStateW".} -proc TabbedTextOutW*(hDC: HDC, X: int32, Y: int32, lpString: LPCWSTR, - nCount: int32, nTabPositions: int32, - lpnTabStopPositions: LPINT, nTabOrigin: int32): LONG{. - stdcall, dynlib: "user32", importc: "TabbedTextOutW".} -proc GetTabbedTextExtentW*(hDC: HDC, lpString: LPCWSTR, nCount: int32, - nTabPositions: int32, lpnTabStopPositions: LPINT): DWORD{. - stdcall, dynlib: "user32", importc: "GetTabbedTextExtentW".} -proc SetPropW*(wnd: HWND, lpString: LPCWSTR, hData: HANDLE): WINBOOL{.stdcall, - dynlib: "user32", importc: "SetPropW".} -proc GetPropW*(wnd: HWND, lpString: LPCWSTR): HANDLE{.stdcall, - dynlib: "user32", importc: "GetPropW".} -proc RemovePropW*(wnd: HWND, lpString: LPCWSTR): HANDLE{.stdcall, - dynlib: "user32", importc: "RemovePropW".} -proc EnumPropsExW*(wnd: HWND, lpEnumFunc: PROPENUMPROCEX, lp: LPARAM): int32{. - stdcall, dynlib: "user32", importc: "EnumPropsExW".} -proc EnumPropsW*(wnd: HWND, lpEnumFunc: PROPENUMPROC): int32{.stdcall, - dynlib: "user32", importc: "EnumPropsW".} -proc SetWindowTextW*(wnd: HWND, lpString: LPCWSTR): WINBOOL{.stdcall, - dynlib: "user32", importc: "SetWindowTextW".} -proc GetWindowTextW*(wnd: HWND, lpString: LPWSTR, nMaxCount: int32): int32{. - stdcall, dynlib: "user32", importc: "GetWindowTextW".} -proc GetWindowTextLengthW*(wnd: HWND): int32{.stdcall, dynlib: "user32", - importc: "GetWindowTextLengthW".} -proc MessageBoxW*(wnd: HWND, lpText: LPCWSTR, lpCaption: LPCWSTR, uType: WINUINT): int32{. - stdcall, dynlib: "user32", importc: "MessageBoxW".} -proc MessageBoxExW*(wnd: HWND, lpText: LPCWSTR, lpCaption: LPCWSTR, - uType: WINUINT, wLanguageId: int16): int32{.stdcall, - dynlib: "user32", importc: "MessageBoxExW".} -proc MessageBoxIndirectW*(para1: LPMSGBOXPARAMS): int32{.stdcall, - dynlib: "user32", importc: "MessageBoxIndirectW".} -proc GetWindowLongW*(wnd: HWND, nIndex: int32): LONG{.stdcall, - dynlib: "user32", importc: "GetWindowLongW".} -proc SetWindowLongW*(wnd: HWND, nIndex: int32, dwNewLong: LONG): LONG{.stdcall, - dynlib: "user32", importc: "SetWindowLongW".} -proc GetClassLongW*(wnd: HWND, nIndex: int32): DWORD{.stdcall, - dynlib: "user32", importc: "GetClassLongW".} -proc SetClassLongW*(wnd: HWND, nIndex: int32, dwNewLong: LONG): DWORD{.stdcall, - dynlib: "user32", importc: "SetClassLongW".} -when defined(cpu64): - proc GetWindowLongPtrW*(wnd: HWND, nIndex: int32): LONG_PTR{.stdcall, - dynlib: "user32", importc: "GetWindowLongPtrW".} - proc SetWindowLongPtrW*(wnd: HWND, nIndex: int32, dwNewLong: LONG_PTR): LONG_PTR{. - stdcall, dynlib: "user32", importc: "SetWindowLongPtrW".} - proc GetClassLongPtrW*(wnd: HWND, nIndex: int32): LONG_PTR{.stdcall, - dynlib: "user32", importc: "GetClassLongPtrW".} - proc SetClassLongPtrW*(wnd: HWND, nIndex: int32, dwNewLong: LONG_PTR): LONG_PTR{. - stdcall, dynlib: "user32", importc: "SetClassLongPtrW".} -else: - proc GetWindowLongPtrW*(wnd: HWND, nIndex: int32): LONG_PTR{.stdcall, - dynlib: "user32", importc: "GetWindowLongW".} - proc SetWindowLongPtrW*(wnd: HWND, nIndex: int32, dwNewLong: LONG_PTR): LONG_PTR{. - stdcall, dynlib: "user32", importc: "SetWindowLongW".} - proc GetClassLongPtrW*(wnd: HWND, nIndex: int32): LONG_PTR{.stdcall, - dynlib: "user32", importc: "GetClassLongW".} - proc SetClassLongPtrW*(wnd: HWND, nIndex: int32, dwNewLong: LONG_PTR): LONG_PTR{. - stdcall, dynlib: "user32", importc: "SetClassLongW".} -proc FindWindowW*(lpClassName: LPCWSTR, lpWindowName: LPCWSTR): HWND{.stdcall, - dynlib: "user32", importc: "FindWindowW".} -proc FindWindowExW*(para1: HWND, para2: HWND, para3: LPCWSTR, para4: LPCWSTR): HWND{. - stdcall, dynlib: "user32", importc: "FindWindowExW".} -proc GetClassNameW*(wnd: HWND, lpClassName: LPWSTR, nMaxCount: int32): int32{. - stdcall, dynlib: "user32", importc: "GetClassNameW".} -proc SetWindowsHookExW*(idHook: int32, lpfn: HOOKPROC, hmod: HINST, - dwThreadId: DWORD): HHOOK{.stdcall, dynlib: "user32", - importc: "SetWindowsHookExW".} -proc LoadBitmapW*(hInstance: HINST, lpBitmapName: LPCWSTR): HBITMAP{.stdcall, - dynlib: "user32", importc: "LoadBitmapW".} -proc LoadCursorW*(hInstance: HINST, lpCursorName: LPCWSTR): HCURSOR{.stdcall, - dynlib: "user32", importc: "LoadCursorW".} -proc LoadCursorFromFileW*(lpFileName: LPCWSTR): HCURSOR{.stdcall, - dynlib: "user32", importc: "LoadCursorFromFileW".} -proc LoadIconW*(hInstance: HINST, lpIconName: LPCWSTR): HICON{.stdcall, - dynlib: "user32", importc: "LoadIconW".} -proc LoadImageW*(para1: HINST, para2: LPCWSTR, para3: WINUINT, para4: int32, - para5: int32, para6: WINUINT): HANDLE{.stdcall, dynlib: "user32", - importc: "LoadImageW".} -proc LoadStringW*(hInstance: HINST, uID: WINUINT, lpBuffer: LPWSTR, - nBufferMax: int32): int32{.stdcall, dynlib: "user32", - importc: "LoadStringW".} -proc IsDialogMessageW*(hDlg: HWND, lpMsg: LPMSG): WINBOOL{.stdcall, - dynlib: "user32", importc: "IsDialogMessageW".} -proc DlgDirListW*(hDlg: HWND, lpPathSpec: LPWSTR, nIDListBox: int32, - nIDStaticPath: int32, uFileType: WINUINT): int32{.stdcall, - dynlib: "user32", importc: "DlgDirListW".} -proc DlgDirSelectExW*(hDlg: HWND, lpString: LPWSTR, nCount: int32, - nIDListBox: int32): WINBOOL{.stdcall, dynlib: "user32", - importc: "DlgDirSelectExW".} -proc DlgDirListComboBoxW*(hDlg: HWND, lpPathSpec: LPWSTR, nIDComboBox: int32, - nIDStaticPath: int32, uFiletype: WINUINT): int32{. - stdcall, dynlib: "user32", importc: "DlgDirListComboBoxW".} -proc DlgDirSelectComboBoxExW*(hDlg: HWND, lpString: LPWSTR, nCount: int32, - nIDComboBox: int32): WINBOOL{.stdcall, - dynlib: "user32", importc: "DlgDirSelectComboBoxExW".} -proc DefFrameProcW*(wnd: HWND, hWndMDIClient: HWND, uMsg: WINUINT, w: WPARAM, - lp: LPARAM): LRESULT{.stdcall, dynlib: "user32", - importc: "DefFrameProcW".} -proc DefMDIChildProcW*(wnd: HWND, uMsg: WINUINT, wp: WPARAM, lp: LPARAM): LRESULT{. - stdcall, dynlib: "user32", importc: "DefMDIChildProcW".} -proc CreateMDIWindowW*(lpClassName: LPWSTR, lpWindowName: LPWSTR, - dwStyle: DWORD, X: int32, Y: int32, nWidth: int32, - nHeight: int32, hWndParent: HWND, hInstance: HINST, - lp: LPARAM): HWND{.stdcall, dynlib: "user32", - importc: "CreateMDIWindowW".} -proc WinHelpW*(hWndMain: HWND, lpszHelp: LPCWSTR, uCommand: WINUINT, dwData: DWORD): WINBOOL{. - stdcall, dynlib: "user32", importc: "WinHelpW".} -proc ChangeDisplaySettingsW*(lpDevMode: LPDEVMODEW, dwFlags: DWORD): LONG{. - stdcall, dynlib: "user32", importc: "ChangeDisplaySettingsW".} -proc EnumDisplaySettingsW*(lpszDeviceName: LPCWSTR, iModeNum: DWORD, - lpDevMode: LPDEVMODEW): WINBOOL{.stdcall, - dynlib: "user32", importc: "EnumDisplaySettingsW".} -proc SystemParametersInfoW*(uiAction: WINUINT, uiParam: WINUINT, pvParam: PVOID, - fWinIni: WINUINT): WINBOOL{.stdcall, dynlib: "user32", - importc: "SystemParametersInfoW".} -proc AddFontResourceW*(para1: LPCWSTR): int32{.stdcall, dynlib: "gdi32", - importc: "AddFontResourceW".} -proc CopyMetaFileW*(para1: HMETAFILE, para2: LPCWSTR): HMETAFILE{.stdcall, - dynlib: "gdi32", importc: "CopyMetaFileW".} -proc CreateFontIndirectW*(para1: PLOGFONT): HFONT{.stdcall, dynlib: "gdi32", - importc: "CreateFontIndirectW".} -proc CreateFontIndirectW*(para1: var LOGFONT): HFONT{.stdcall, dynlib: "gdi32", - importc: "CreateFontIndirectW".} -proc CreateFontW*(para1: int32, para2: int32, para3: int32, para4: int32, - para5: int32, para6: DWORD, para7: DWORD, para8: DWORD, - para9: DWORD, para10: DWORD, para11: DWORD, para12: DWORD, - para13: DWORD, para14: LPCWSTR): HFONT{.stdcall, - dynlib: "gdi32", importc: "CreateFontW".} -proc CreateICW*(para1: LPCWSTR, para2: LPCWSTR, para3: LPCWSTR, - para4: LPDEVMODEw): HDC{.stdcall, dynlib: "gdi32", - importc: "CreateICW".} -proc CreateMetaFileW*(para1: LPCWSTR): HDC{.stdcall, dynlib: "gdi32", - importc: "CreateMetaFileW".} -proc CreateScalableFontResourceW*(para1: DWORD, para2: LPCWSTR, para3: LPCWSTR, - para4: LPCWSTR): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "CreateScalableFontResourceW".} -proc EnumFontFamiliesExW*(para1: HDC, para2: LPLOGFONT, para3: FONTENUMEXPROC, - para4: LPARAM, para5: DWORD): int32{.stdcall, - dynlib: "gdi32", importc: "EnumFontFamiliesExW".} -proc EnumFontFamiliesW*(para1: HDC, para2: LPCWSTR, para3: FONTENUMPROC, - para4: LPARAM): int32{.stdcall, dynlib: "gdi32", - importc: "EnumFontFamiliesW".} -proc EnumFontsW*(para1: HDC, para2: LPCWSTR, para3: ENUMFONTSPROC, para4: LPARAM): int32{. - stdcall, dynlib: "gdi32", importc: "EnumFontsW".} -proc EnumFontsW*(para1: HDC, para2: LPCWSTR, para3: ENUMFONTSPROC, - para4: pointer): int32{.stdcall, dynlib: "gdi32", - importc: "EnumFontsW".} -proc GetCharWidthW*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: LPINT): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "GetCharWidthW".} -proc GetCharWidth32W*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: LPINT): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "GetCharWidth32W".} -proc GetCharWidthFloatW*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: ptr float32): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "GetCharWidthFloatW".} -proc GetCharABCWidthsW*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: LPABC): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "GetCharABCWidthsW".} -proc GetCharABCWidthsFloatW*(para1: HDC, para2: WINUINT, para3: WINUINT, - para4: LPABCFLOAT): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "GetCharABCWidthsFloatW".} -proc GetGlyphOutlineW*(para1: HDC, para2: WINUINT, para3: WINUINT, - para4: LPGLYPHMETRICS, para5: DWORD, para6: LPVOID, - para7: PMAT2): DWORD{.stdcall, dynlib: "gdi32", - importc: "GetGlyphOutlineW".} -proc GetMetaFileW*(para1: LPCWSTR): HMETAFILE{.stdcall, dynlib: "gdi32", - importc: "GetMetaFileW".} -proc GetOutlineTextMetricsW*(para1: HDC, para2: WINUINT, para3: LPOUTLINETEXTMETRIC): WINUINT{. - stdcall, dynlib: "gdi32", importc: "GetOutlineTextMetricsW".} -proc GetTextExtentPointW*(para1: HDC, para2: LPCWSTR, para3: int32, - para4: LPSIZE): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "GetTextExtentPointW".} -proc GetTextExtentPoint32W*(para1: HDC, para2: LPCWSTR, para3: int32, - para4: LPSIZE): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "GetTextExtentPoint32W".} -proc GetTextExtentExPointW*(para1: HDC, para2: LPCWSTR, para3: int32, - para4: int32, para5: LPINT, para6: LPINT, - para7: LPSIZE): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "GetTextExtentExPointW".} -proc GetCharacterPlacementW*(para1: HDC, para2: LPCWSTR, para3: int32, - para4: int32, para5: LPGCP_RESULTS, para6: DWORD): DWORD{. - stdcall, dynlib: "gdi32", importc: "GetCharacterPlacementW".} -proc ResetDCW*(para1: HDC, para2: LPDEVMODEW): HDC{.stdcall, dynlib: "gdi32", - importc: "ResetDCW".} -proc RemoveFontResourceW*(para1: LPCWSTR): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "RemoveFontResourceW".} -proc CopyEnhMetaFileW*(para1: HENHMETAFILE, para2: LPCWSTR): HENHMETAFILE{. - stdcall, dynlib: "gdi32", importc: "CopyEnhMetaFileW".} -proc CreateEnhMetaFileW*(para1: HDC, para2: LPCWSTR, para3: LPRECT, - para4: LPCWSTR): HDC{.stdcall, dynlib: "gdi32", - importc: "CreateEnhMetaFileW".} -proc GetEnhMetaFileW*(para1: LPCWSTR): HENHMETAFILE{.stdcall, dynlib: "gdi32", - importc: "GetEnhMetaFileW".} -proc GetEnhMetaFileDescriptionW*(para1: HENHMETAFILE, para2: WINUINT, para3: LPWSTR): WINUINT{. - stdcall, dynlib: "gdi32", importc: "GetEnhMetaFileDescriptionW".} -proc GetTextMetricsW*(para1: HDC, para2: LPTEXTMETRIC): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "GetTextMetricsW".} -proc StartDocW*(para1: HDC, para2: PDOCINFO): int32{.stdcall, dynlib: "gdi32", - importc: "StartDocW".} -proc GetObjectW*(para1: HGDIOBJ, para2: int32, para3: LPVOID): int32{.stdcall, - dynlib: "gdi32", importc: "GetObjectW".} -proc TextOutW*(para1: HDC, para2: int32, para3: int32, para4: LPCWSTR, - para5: int32): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "TextOutW".} -proc ExtTextOutW*(para1: HDC, para2: int32, para3: int32, para4: WINUINT, - para5: LPRECT, para6: LPCWSTR, para7: WINUINT, para8: LPINT): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "ExtTextOutW".} -proc PolyTextOutW*(para1: HDC, para2: PPOLYTEXT, para3: int32): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "PolyTextOutW".} -proc GetTextFaceW*(para1: HDC, para2: int32, para3: LPWSTR): int32{.stdcall, - dynlib: "gdi32", importc: "GetTextFaceW".} -proc GetKerningPairsW*(para1: HDC, para2: DWORD, para3: LPKERNINGPAIR): DWORD{. - stdcall, dynlib: "gdi32", importc: "GetKerningPairsW".} -proc GetLogColorSpaceW*(para1: HCOLORSPACE, para2: LPLOGCOLORSPACE, para3: DWORD): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "GetLogColorSpaceW".} -proc CreateColorSpaceW*(para1: LPLOGCOLORSPACE): HCOLORSPACE{.stdcall, - dynlib: "gdi32", importc: "CreateColorSpaceW".} -proc GetICMProfileW*(para1: HDC, para2: DWORD, para3: LPWSTR): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "GetICMProfileW".} -proc SetICMProfileW*(para1: HDC, para2: LPWSTR): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "SetICMProfileW".} -proc UpdateICMRegKeyW*(para1: DWORD, para2: DWORD, para3: LPWSTR, para4: WINUINT): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "UpdateICMRegKeyW".} -proc EnumICMProfilesW*(para1: HDC, para2: ICMENUMPROC, para3: LPARAM): int32{. - stdcall, dynlib: "gdi32", importc: "EnumICMProfilesW".} -proc CreatePropertySheetPageW*(lppsp: LPCPROPSHEETPAGE): HPROPSHEETPAGE{. - stdcall, dynlib: "comctl32", importc: "CreatePropertySheetPageW".} -proc PropertySheetW*(lppsph: LPCPROPSHEETHEADER): int32{.stdcall, - dynlib: "comctl32", importc: "PropertySheetW".} -proc ImageList_LoadImageW*(hi: HINST, lpbmp: LPCWSTR, cx: int32, cGrow: int32, - crMask: COLORREF, uType: WINUINT, uFlags: WINUINT): HIMAGELIST{. - stdcall, dynlib: "comctl32", importc: "ImageList_LoadImageW".} -proc CreateStatusWindowW*(style: LONG, lpszText: LPCWSTR, hwndParent: HWND, - wID: WINUINT): HWND{.stdcall, dynlib: "comctl32", - importc: "CreateStatusWindowW".} -proc DrawStatusTextW*(hDC: HDC, lprc: LPRECT, pszText: LPCWSTR, uFlags: WINUINT){. - stdcall, dynlib: "comctl32", importc: "DrawStatusTextW".} -proc GetOpenFileNameW*(para1: LPOPENFILENAME): WINBOOL{.stdcall, - dynlib: "comdlg32", importc: "GetOpenFileNameW".} -proc GetSaveFileNameW*(para1: LPOPENFILENAME): WINBOOL{.stdcall, - dynlib: "comdlg32", importc: "GetSaveFileNameW".} -proc GetFileTitleW*(para1: LPCWSTR, para2: LPWSTR, para3: int16): int{.stdcall, - dynlib: "comdlg32", importc: "GetFileTitleW".} -proc ChooseColorW*(para1: LPCHOOSECOLOR): WINBOOL{.stdcall, dynlib: "comdlg32", - importc: "ChooseColorW".} -proc ReplaceTextW*(para1: LPFINDREPLACE): HWND{.stdcall, dynlib: "comdlg32", - importc: "ReplaceTextW".} -proc ChooseFontW*(para1: LPCHOOSEFONT): WINBOOL{.stdcall, dynlib: "comdlg32", - importc: "ChooseFontW".} -proc FindTextW*(para1: LPFINDREPLACE): HWND{.stdcall, dynlib: "comdlg32", - importc: "FindTextW".} -proc PrintDlgW*(para1: LPPRINTDLG): WINBOOL{.stdcall, dynlib: "comdlg32", - importc: "PrintDlgW".} -proc PageSetupDlgW*(para1: LPPAGESETUPDLG): WINBOOL{.stdcall, - dynlib: "comdlg32", importc: "PageSetupDlgW".} -proc CreateProcessW*(lpApplicationName: LPCWSTR, lpCommandLine: LPWSTR, - lpProcessAttributes: LPSECURITY_ATTRIBUTES, - lpThreadAttributes: LPSECURITY_ATTRIBUTES, - bInheritHandles: WINBOOL, dwCreationFlags: DWORD, - lpEnvironment: LPVOID, lpCurrentDirectory: LPCWSTR, - lpStartupInfo: LPSTARTUPINFO, - lpProcessInformation: LPPROCESS_INFORMATION): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "CreateProcessW".} -proc GetStartupInfoW*(lpStartupInfo: LPSTARTUPINFO){.stdcall, - dynlib: "kernel32", importc: "GetStartupInfoW".} -proc FindFirstFileW*(lpFileName: LPCWSTR, lpFindFileData: LPWIN32_FIND_DATAW): HANDLE{. - stdcall, dynlib: "kernel32", importc: "FindFirstFileW".} -proc FindNextFileW*(hFindFile: HANDLE, lpFindFileData: LPWIN32_FIND_DATAW): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "FindNextFileW".} -proc GetVersionExW*(VersionInformation: LPOSVERSIONINFOW): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetVersionExW".} -proc CreateWindowW*(lpClassName: LPCWSTR, lpWindowName: LPCWSTR, dwStyle: DWORD, - X: int32, Y: int32, nWidth: int32, nHeight: int32, - hWndParent: HWND, menu: HMENU, hInstance: HINST, - lpParam: LPVOID): HWND -proc CreateDialogW*(hInstance: HINST, lpName: LPCWSTR, hWndParent: HWND, - lpDialogFunc: DLGPROC): HWND -proc CreateDialogIndirectW*(hInstance: HINST, lpTemplate: LPCDLGTEMPLATE, - hWndParent: HWND, lpDialogFunc: DLGPROC): HWND -proc DialogBoxW*(hInstance: HINST, lpTemplate: LPCWSTR, hWndParent: HWND, - lpDialogFunc: DLGPROC): int32 -proc DialogBoxIndirectW*(hInstance: HINST, lpTemplate: LPCDLGTEMPLATE, - hWndParent: HWND, lpDialogFunc: DLGPROC): int32 -proc CreateDCW*(para1: LPCWSTR, para2: LPCWSTR, para3: LPCWSTR, para4: PDEVMODEW): HDC{. - stdcall, dynlib: "gdi32", importc: "CreateDCW".} -proc VerInstallFileW*(uFlags: DWORD, szSrcFileName: LPWSTR, - szDestFileName: LPWSTR, szSrcDir: LPWSTR, - szDestDir: LPWSTR, szCurDir: LPWSTR, szTmpFile: LPWSTR, - lpuTmpFileLen: PUINT): DWORD{.stdcall, dynlib: "version", - importc: "VerInstallFileW".} -proc GetFileVersionInfoSizeW*(lptstrFilename: LPWSTR, lpdwHandle: LPDWORD): DWORD{. - stdcall, dynlib: "version", importc: "GetFileVersionInfoSizeW".} -proc GetFileVersionInfoW*(lptstrFilename: LPWSTR, dwHandle: DWORD, dwLen: DWORD, - lpData: LPVOID): WINBOOL{.stdcall, dynlib: "version", - importc: "GetFileVersionInfoW".} -proc VerLanguageNameW*(wLang: DWORD, szLang: LPWSTR, nSize: DWORD): DWORD{. - stdcall, dynlib: "kernel32", importc: "VerLanguageNameW".} -proc VerQueryValueW*(pBlock: LPVOID, lpSubBlock: LPWSTR, lplpBuffer: LPVOID, - puLen: PUINT): WINBOOL{.stdcall, dynlib: "version", - importc: "VerQueryValueW".} -proc VerFindFileW*(uFlags: DWORD, szFileName: LPWSTR, szWinDir: LPWSTR, - szAppDir: LPWSTR, szCurDir: LPWSTR, lpuCurDirLen: PUINT, - szDestDir: LPWSTR, lpuDestDirLen: PUINT): DWORD{.stdcall, - dynlib: "version", importc: "VerFindFileW".} -proc RegSetValueExW*(key: HKEY, lpValueName: LPCWSTR, Reserved: DWORD, - dwType: DWORD, lpData: LPBYTE, cbData: DWORD): LONG{. - stdcall, dynlib: "advapi32", importc: "RegSetValueExW".} -proc RegUnLoadKeyW*(key: HKEY, lpSubKey: LPCWSTR): LONG{.stdcall, - dynlib: "advapi32", importc: "RegUnLoadKeyW".} -proc InitiateSystemShutdownW*(lpMachineName: LPWSTR, lpMessage: LPWSTR, - dwTimeout: DWORD, bForceAppsClosed: WINBOOL, - bRebootAfterShutdown: WINBOOL): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "InitiateSystemShutdownW".} -proc AbortSystemShutdownW*(lpMachineName: LPWSTR): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "AbortSystemShutdownW".} -proc RegRestoreKeyW*(key: HKEY, lpFile: LPCWSTR, dwFlags: DWORD): LONG{. - stdcall, dynlib: "advapi32", importc: "RegRestoreKeyW".} -proc RegSaveKeyW*(key: HKEY, lpFile: LPCWSTR, - lpSecurityAttributes: LPSECURITY_ATTRIBUTES): LONG{.stdcall, - dynlib: "advapi32", importc: "RegSaveKeyW".} -proc RegSetValueW*(key: HKEY, lpSubKey: LPCWSTR, dwType: DWORD, - lpData: LPCWSTR, cbData: DWORD): LONG{.stdcall, - dynlib: "advapi32", importc: "RegSetValueW".} -proc RegQueryValueW*(key: HKEY, lpSubKey: LPCWSTR, lpValue: LPWSTR, - lpcbValue: PLONG): LONG{.stdcall, dynlib: "advapi32", - importc: "RegQueryValueW".} -proc RegQueryMultipleValuesW*(key: HKEY, val_list: PVALENT, num_vals: DWORD, - lpValueBuf: LPWSTR, ldwTotsize: LPDWORD): LONG{. - stdcall, dynlib: "advapi32", importc: "RegQueryMultipleValuesW".} -proc RegQueryValueExW*(key: HKEY, lpValueName: LPCWSTR, lpReserved: LPDWORD, - lpType: LPDWORD, lpData: LPBYTE, lpcbData: LPDWORD): LONG{. - stdcall, dynlib: "advapi32", importc: "RegQueryValueExW".} -proc RegReplaceKeyW*(key: HKEY, lpSubKey: LPCWSTR, lpNewFile: LPCWSTR, - lpOldFile: LPCWSTR): LONG{.stdcall, dynlib: "advapi32", - importc: "RegReplaceKeyW".} -proc RegConnectRegistryW*(lpMachineName: LPWSTR, key: HKEY, phkResult: PHKEY): LONG{. - stdcall, dynlib: "advapi32", importc: "RegConnectRegistryW".} -proc RegCreateKeyW*(key: HKEY, lpSubKey: LPCWSTR, phkResult: PHKEY): LONG{. - stdcall, dynlib: "advapi32", importc: "RegCreateKeyW".} -proc RegCreateKeyExW*(key: HKEY, lpSubKey: LPCWSTR, Reserved: DWORD, - lpClass: LPWSTR, dwOptions: DWORD, samDesired: REGSAM, - lpSecurityAttributes: LPSECURITY_ATTRIBUTES, - phkResult: PHKEY, lpdwDisposition: LPDWORD): LONG{. - stdcall, dynlib: "advapi32", importc: "RegCreateKeyExW".} -proc RegDeleteKeyW*(key: HKEY, lpSubKey: LPCWSTR): LONG{.stdcall, - dynlib: "advapi32", importc: "RegDeleteKeyW".} -proc RegDeleteValueW*(key: HKEY, lpValueName: LPCWSTR): LONG{.stdcall, - dynlib: "advapi32", importc: "RegDeleteValueW".} -proc RegEnumKeyW*(key: HKEY, dwIndex: DWORD, lpName: LPWSTR, cbName: DWORD): LONG{. - stdcall, dynlib: "advapi32", importc: "RegEnumKeyW".} -proc RegEnumKeyExW*(key: HKEY, dwIndex: DWORD, lpName: LPWSTR, - lpcbName: LPDWORD, lpReserved: LPDWORD, lpClass: LPWSTR, - lpcbClass: LPDWORD, lpftLastWriteTime: PFILETIME): LONG{. - stdcall, dynlib: "advapi32", importc: "RegEnumKeyExW".} -proc RegEnumValueW*(key: HKEY, dwIndex: DWORD, lpValueName: LPWSTR, - lpcbValueName: LPDWORD, lpReserved: LPDWORD, - lpType: LPDWORD, lpData: LPBYTE, lpcbData: LPDWORD): LONG{. - stdcall, dynlib: "advapi32", importc: "RegEnumValueW".} -proc RegLoadKeyW*(key: HKEY, lpSubKey: LPCWSTR, lpFile: LPCWSTR): LONG{. - stdcall, dynlib: "advapi32", importc: "RegLoadKeyW".} -proc RegOpenKeyW*(key: HKEY, lpSubKey: LPCWSTR, phkResult: PHKEY): LONG{. - stdcall, dynlib: "advapi32", importc: "RegOpenKeyW".} -proc RegOpenKeyExW*(key: HKEY, lpSubKey: LPCWSTR, ulOptions: DWORD, - samDesired: REGSAM, phkResult: PHKEY): LONG{.stdcall, - dynlib: "advapi32", importc: "RegOpenKeyExW".} -proc RegQueryInfoKeyW*(key: HKEY, lpClass: LPWSTR, lpcbClass: LPDWORD, - lpReserved: LPDWORD, lpcSubKeys: LPDWORD, - lpcbMaxSubKeyLen: LPDWORD, lpcbMaxClassLen: LPDWORD, - lpcValues: LPDWORD, lpcbMaxValueNameLen: LPDWORD, - lpcbMaxValueLen: LPDWORD, - lpcbSecurityDescriptor: LPDWORD, - lpftLastWriteTime: PFILETIME): LONG{.stdcall, - dynlib: "advapi32", importc: "RegQueryInfoKeyW".} -proc CompareStringW*(Locale: LCID, dwCmpFlags: DWORD, lpString1: LPCWSTR, - cchCount1: int32, lpString2: LPCWSTR, cchCount2: int32): int32{. - stdcall, dynlib: "kernel32", importc: "CompareStringW".} -proc LCMapStringW*(Locale: LCID, dwMapFlags: DWORD, lpSrcStr: LPCWSTR, - cchSrc: int32, lpDestStr: LPWSTR, cchDest: int32): int32{. - stdcall, dynlib: "kernel32", importc: "LCMapStringW".} -proc GetLocaleInfoW*(Locale: LCID, LCType: LCTYPE, lpLCData: LPWSTR, - cchData: int32): int32{.stdcall, dynlib: "kernel32", - importc: "GetLocaleInfoW".} -proc SetLocaleInfoW*(Locale: LCID, LCType: LCTYPE, lpLCData: LPCWSTR): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "SetLocaleInfoW".} -proc GetTimeFormatW*(Locale: LCID, dwFlags: DWORD, lpTime: LPSYSTEMTIME, - lpFormat: LPCWSTR, lpTimeStr: LPWSTR, cchTime: int32): int32{. - stdcall, dynlib: "kernel32", importc: "GetTimeFormatW".} -proc GetDateFormatW*(Locale: LCID, dwFlags: DWORD, lpDate: LPSYSTEMTIME, - lpFormat: LPCWSTR, lpDateStr: LPWSTR, cchDate: int32): int32{. - stdcall, dynlib: "kernel32", importc: "GetDateFormatW".} -proc GetNumberFormatW*(Locale: LCID, dwFlags: DWORD, lpValue: LPCWSTR, - lpFormat: PNUMBERFMT, lpNumberStr: LPWSTR, - cchNumber: int32): int32{.stdcall, dynlib: "kernel32", - importc: "GetNumberFormatW".} -proc GetCurrencyFormatW*(Locale: LCID, dwFlags: DWORD, lpValue: LPCWSTR, - lpFormat: PCURRENCYFMT, lpCurrencyStr: LPWSTR, - cchCurrency: int32): int32{.stdcall, - dynlib: "kernel32", importc: "GetCurrencyFormatW".} -proc EnumCalendarInfoW*(lpCalInfoEnumProc: CALINFO_ENUMPROC, Locale: LCID, - Calendar: CALID, CalType: CALTYPE): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "EnumCalendarInfoW".} -proc EnumTimeFormatsW*(lpTimeFmtEnumProc: TIMEFMT_ENUMPROC, Locale: LCID, - dwFlags: DWORD): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "EnumTimeFormatsW".} -proc EnumDateFormatsW*(lpDateFmtEnumProc: DATEFMT_ENUMPROC, Locale: LCID, - dwFlags: DWORD): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "EnumDateFormatsW".} -proc GetStringTypeExW*(Locale: LCID, dwInfoType: DWORD, lpSrcStr: LPCWSTR, - cchSrc: int32, lpCharType: LPWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetStringTypeExW".} -proc GetStringTypeW*(dwInfoType: DWORD, lpSrcStr: LPCWSTR, cchSrc: int32, - lpCharType: LPWORD): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "GetStringTypeW".} -proc FoldStringW*(dwMapFlags: DWORD, lpSrcStr: LPCWSTR, cchSrc: int32, - lpDestStr: LPWSTR, cchDest: int32): int32{.stdcall, - dynlib: "kernel32", importc: "FoldStringW".} -proc EnumSystemLocalesW*(lpLocaleEnumProc: LOCALE_ENUMPROC, dwFlags: DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "EnumSystemLocalesW".} -proc EnumSystemCodePagesW*(lpCodePageEnumProc: CODEPAGE_ENUMPROC, dwFlags: DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "EnumSystemCodePagesW".} -proc PeekConsoleInputW*(hConsoleInput: HANDLE, lpBuffer: PINPUTRECORD, - nLength: DWORD, lpNumberOfEventsRead: LPDWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "PeekConsoleInputW".} -proc ReadConsoleInputW*(hConsoleInput: HANDLE, lpBuffer: PINPUTRECORD, - nLength: DWORD, lpNumberOfEventsRead: LPDWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "ReadConsoleInputW".} -proc WriteConsoleInputW*(hConsoleInput: HANDLE, lpBuffer: PINPUTRECORD, - nLength: DWORD, lpNumberOfEventsWritten: LPDWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "WriteConsoleInputW".} -proc ReadConsoleOutputW*(hConsoleOutput: HANDLE, lpBuffer: PCHAR_INFO, - dwBufferSize: COORD, dwBufferCoord: COORD, - lpReadRegion: PSMALL_RECT): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "ReadConsoleOutputW".} -proc WriteConsoleOutputW*(hConsoleOutput: HANDLE, lpBuffer: PCHAR_INFO, - dwBufferSize: COORD, dwBufferCoord: COORD, - lpWriteRegion: PSMALL_RECT): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "WriteConsoleOutputW".} -proc ReadConsoleOutputCharacterW*(hConsoleOutput: HANDLE, lpCharacter: LPWSTR, - nLength: DWORD, dwReadCoord: COORD, - lpNumberOfCharsRead: LPDWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "ReadConsoleOutputCharacterW".} -proc WriteConsoleOutputCharacterW*(hConsoleOutput: HANDLE, lpCharacter: LPCWSTR, - nLength: DWORD, dwWriteCoord: COORD, - lpNumberOfCharsWritten: LPDWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "WriteConsoleOutputCharacterW".} -proc FillConsoleOutputCharacterW*(hConsoleOutput: HANDLE, cCharacter: WCHAR, - nLength: DWORD, dwWriteCoord: COORD, - lpNumberOfCharsWritten: LPDWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "FillConsoleOutputCharacterW".} -proc ScrollConsoleScreenBufferW*(hConsoleOutput: HANDLE, - lpScrollRectangle: PSMALL_RECT, - lpClipRectangle: PSMALL_RECT, - dwDestinationOrigin: COORD, lpFill: PCHAR_INFO): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "ScrollConsoleScreenBufferW".} -proc GetConsoleTitleW*(lpConsoleTitle: LPWSTR, nSize: DWORD): DWORD{.stdcall, - dynlib: "kernel32", importc: "GetConsoleTitleW".} -proc SetConsoleTitleW*(lpConsoleTitle: LPCWSTR): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "SetConsoleTitleW".} -proc ReadConsoleW*(hConsoleInput: HANDLE, lpBuffer: LPVOID, - nNumberOfCharsToRead: DWORD, lpNumberOfCharsRead: LPDWORD, - lpReserved: LPVOID): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "ReadConsoleW".} -proc WriteConsoleW*(hConsoleOutput: HANDLE, lpBuffer: pointer, - nNumberOfCharsToWrite: DWORD, - lpNumberOfCharsWritten: LPDWORD, lpReserved: LPVOID): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "WriteConsoleW".} -proc WNetAddConnectionW*(lpRemoteName: LPCWSTR, lpPassword: LPCWSTR, - lpLocalName: LPCWSTR): DWORD{.stdcall, dynlib: "mpr", - importc: "WNetAddConnectionW".} -proc WNetAddConnection2W*(lpNetResource: LPNETRESOURCE, lpPassword: LPCWSTR, - lpUserName: LPCWSTR, dwFlags: DWORD): DWORD{.stdcall, - dynlib: "mpr", importc: "WNetAddConnection2W".} -proc WNetAddConnection3W*(hwndOwner: HWND, lpNetResource: LPNETRESOURCE, - lpPassword: LPCWSTR, lpUserName: LPCWSTR, - dwFlags: DWORD): DWORD{.stdcall, dynlib: "mpr", - importc: "WNetAddConnection3W".} -proc WNetCancelConnectionW*(lpName: LPCWSTR, fForce: WINBOOL): DWORD{.stdcall, - dynlib: "mpr", importc: "WNetCancelConnectionW".} -proc WNetCancelConnection2W*(lpName: LPCWSTR, dwFlags: DWORD, fForce: WINBOOL): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetCancelConnection2W".} -proc WNetGetConnectionW*(lpLocalName: LPCWSTR, lpRemoteName: LPWSTR, - lpnLength: LPDWORD): DWORD{.stdcall, dynlib: "mpr", - importc: "WNetGetConnectionW".} -proc WNetUseConnectionW*(hwndOwner: HWND, lpNetResource: LPNETRESOURCE, - lpUserID: LPCWSTR, lpPassword: LPCWSTR, dwFlags: DWORD, - lpAccessName: LPWSTR, lpBufferSize: LPDWORD, - lpResult: LPDWORD): DWORD{.stdcall, dynlib: "mpr", - importc: "WNetUseConnectionW".} -proc WNetSetConnectionW*(lpName: LPCWSTR, dwProperties: DWORD, pvValues: LPVOID): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetSetConnectionW".} -proc WNetConnectionDialog1W*(lpConnDlgStruct: LPCONNECTDLGSTRUCT): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetConnectionDialog1W".} -proc WNetDisconnectDialog1W*(lpConnDlgStruct: LPDISCDLGSTRUCT): DWORD{.stdcall, - dynlib: "mpr", importc: "WNetDisconnectDialog1W".} -proc WNetOpenEnumW*(dwScope: DWORD, dwType: DWORD, dwUsage: DWORD, - lpNetResource: LPNETRESOURCE, lphEnum: LPHANDLE): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetOpenEnumW".} -proc WNetEnumResourceW*(hEnum: HANDLE, lpcCount: LPDWORD, lpBuffer: LPVOID, - lpBufferSize: LPDWORD): DWORD{.stdcall, dynlib: "mpr", - importc: "WNetEnumResourceW".} -proc WNetGetUniversalNameW*(lpLocalPath: LPCWSTR, dwInfoLevel: DWORD, - lpBuffer: LPVOID, lpBufferSize: LPDWORD): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetGetUniversalNameW".} -proc WNetGetUserW*(lpName: LPCWSTR, lpUserName: LPWSTR, lpnLength: LPDWORD): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetGetUserW".} -proc WNetGetProviderNameW*(dwNetType: DWORD, lpProviderName: LPWSTR, - lpBufferSize: LPDWORD): DWORD{.stdcall, - dynlib: "mpr", importc: "WNetGetProviderNameW".} -proc WNetGetNetworkInformationW*(lpProvider: LPCWSTR, - lpNetInfoStruct: LPNETINFOSTRUCT): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetGetNetworkInformationW".} -proc WNetGetLastErrorW*(lpError: LPDWORD, lpErrorBuf: LPWSTR, - nErrorBufSize: DWORD, lpNameBuf: LPWSTR, - nNameBufSize: DWORD): DWORD{.stdcall, dynlib: "mpr", - importc: "WNetGetLastErrorW".} -proc MultinetGetConnectionPerformanceW*(lpNetResource: LPNETRESOURCE, - lpNetConnectInfoStruct: LPNETCONNECTINFOSTRUCT): DWORD{.stdcall, - dynlib: "mpr", importc: "MultinetGetConnectionPerformanceW".} -proc ChangeServiceConfigW*(hService: SC_HANDLE, dwServiceType: DWORD, - dwStartType: DWORD, dwErrorControl: DWORD, - lpBinaryPathName: LPCWSTR, lpLoadOrderGroup: LPCWSTR, - lpdwTagId: LPDWORD, lpDependencies: LPCWSTR, - lpServiceStartName: LPCWSTR, lpPassword: LPCWSTR, - lpDisplayName: LPCWSTR): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "ChangeServiceConfigW".} -proc CreateServiceW*(hSCManager: SC_HANDLE, lpServiceName: LPCWSTR, - lpDisplayName: LPCWSTR, dwDesiredAccess: DWORD, - dwServiceType: DWORD, dwStartType: DWORD, - dwErrorControl: DWORD, lpBinaryPathName: LPCWSTR, - lpLoadOrderGroup: LPCWSTR, lpdwTagId: LPDWORD, - lpDependencies: LPCWSTR, lpServiceStartName: LPCWSTR, - lpPassword: LPCWSTR): SC_HANDLE{.stdcall, - dynlib: "advapi32", importc: "CreateServiceW".} -proc EnumDependentServicesW*(hService: SC_HANDLE, dwServiceState: DWORD, - lpServices: LPENUM_SERVICE_STATUS, - cbBufSize: DWORD, pcbBytesNeeded: LPDWORD, - lpServicesReturned: LPDWORD): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "EnumDependentServicesW".} -proc EnumServicesStatusW*(hSCManager: SC_HANDLE, dwServiceType: DWORD, - dwServiceState: DWORD, - lpServices: LPENUM_SERVICE_STATUS, cbBufSize: DWORD, - pcbBytesNeeded: LPDWORD, lpServicesReturned: LPDWORD, - lpResumeHandle: LPDWORD): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "EnumServicesStatusW".} -proc GetServiceKeyNameW*(hSCManager: SC_HANDLE, lpDisplayName: LPCWSTR, - lpServiceName: LPWSTR, lpcchBuffer: LPDWORD): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "GetServiceKeyNameW".} -proc GetServiceDisplayNameW*(hSCManager: SC_HANDLE, lpServiceName: LPCWSTR, - lpDisplayName: LPWSTR, lpcchBuffer: LPDWORD): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "GetServiceDisplayNameW".} -proc OpenSCManagerW*(lpMachineName: LPCWSTR, lpDatabaseName: LPCWSTR, - dwDesiredAccess: DWORD): SC_HANDLE{.stdcall, - dynlib: "advapi32", importc: "OpenSCManagerW".} -proc OpenServiceW*(hSCManager: SC_HANDLE, lpServiceName: LPCWSTR, - dwDesiredAccess: DWORD): SC_HANDLE{.stdcall, - dynlib: "advapi32", importc: "OpenServiceW".} -proc QueryServiceConfigW*(hService: SC_HANDLE, - lpServiceConfig: LPQUERY_SERVICE_CONFIG, - cbBufSize: DWORD, pcbBytesNeeded: LPDWORD): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "QueryServiceConfigW".} -proc QueryServiceLockStatusW*(hSCManager: SC_HANDLE, - lpLockStatus: LPQUERY_SERVICE_LOCK_STATUS, - cbBufSize: DWORD, pcbBytesNeeded: LPDWORD): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "QueryServiceLockStatusW".} -proc RegisterServiceCtrlHandlerW*(lpServiceName: LPCWSTR, - lpHandlerProc: LPHANDLER_FUNCTION): SERVICE_STATUS_HANDLE{. - stdcall, dynlib: "advapi32", importc: "RegisterServiceCtrlHandlerW".} -proc StartServiceCtrlDispatcherW*(lpServiceStartTable: LPSERVICE_TABLE_ENTRY): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "StartServiceCtrlDispatcherW".} -proc StartServiceW*(hService: SC_HANDLE, dwNumServiceArgs: DWORD, - lpServiceArgVectors: LPCWSTR): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "StartServiceW".} -proc DragQueryFileW*(para1: HDROP, para2: int, para3: LPCWSTR, para4: int): int{. - stdcall, dynlib: "shell32", importc: "DragQueryFileW".} -proc ExtractAssociatedIconW*(para1: HINST, para2: LPCWSTR, para3: LPWORD): HICON{. - stdcall, dynlib: "shell32", importc: "ExtractAssociatedIconW".} -proc ExtractIconW*(para1: HINST, para2: LPCWSTR, para3: int): HICON{.stdcall, - dynlib: "shell32", importc: "ExtractIconW".} -proc FindExecutableW*(para1: LPCWSTR, para2: LPCWSTR, para3: LPCWSTR): HINST{. - stdcall, dynlib: "shell32", importc: "FindExecutableW".} -proc ShellAboutW*(para1: HWND, para2: LPCWSTR, para3: LPCWSTR, para4: HICON): int32{. - stdcall, dynlib: "shell32", importc: "ShellAboutW".} -proc ShellExecuteW*(para1: HWND, para2: LPCWSTR, para3: LPCWSTR, para4: LPCWSTR, - para5: LPCWSTR, para6: int32): HINST{.stdcall, - dynlib: "shell32", importc: "ShellExecuteW".} -proc Shell_NotifyIconW*(dwMessage: DWORD, lpData: PNotifyIconDataA): WINBOOL{. - stdcall, dynlib: "shell32", importc: "Shell_NotifyIconW".} -proc DdeCreateStringHandleW*(para1: DWORD, para2: LPCWSTR, para3: int32): HSZ{. - stdcall, dynlib: "user32", importc: "DdeCreateStringHandleW".} -proc DdeInitializeW*(para1: LPDWORD, para2: PFNCALLBACK, para3: DWORD, - para4: DWORD): WINUINT{.stdcall, dynlib: "user32", - importc: "DdeInitializeW".} -proc DdeQueryStringW*(para1: DWORD, para2: HSZ, para3: LPCWSTR, para4: DWORD, - para5: int32): DWORD{.stdcall, dynlib: "user32", - importc: "DdeQueryStringW".} -proc LogonUserW*(para1: LPWSTR, para2: LPWSTR, para3: LPWSTR, para4: DWORD, - para5: DWORD, para6: PHANDLE): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "LogonUserW".} -proc CreateProcessAsUserW*(para1: HANDLE, para2: LPCWSTR, para3: LPWSTR, - para4: LPSECURITY_ATTRIBUTES, - para5: LPSECURITY_ATTRIBUTES, para6: WINBOOL, - para7: DWORD, para8: LPVOID, para9: LPCWSTR, - para10: LPSTARTUPINFO, para11: LPPROCESS_INFORMATION): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "CreateProcessAsUserW".} -when defined(winUnicode): - proc GetBinaryType*(lpApplicationName: LPCWSTR, lpBinaryType: LPDWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetBinaryTypeW".} - proc GetShortPathName*(lpszLongPath: LPCWSTR, lpszShortPath: LPWSTR, - cchBuffer: DWORD): DWORD{.stdcall, dynlib: "kernel32", - importc: "GetShortPathNameW".} - proc GetEnvironmentStrings*(): LPWSTR{.stdcall, dynlib: "kernel32", - importc: "GetEnvironmentStringsW".} - proc FreeEnvironmentStrings*(para1: LPWSTR): WINBOOL{.stdcall, - - dynlib: "kernel32", importc: "FreeEnvironmentStringsW".} - proc FormatMessage*(dwFlags: DWORD, lpSource: LPCVOID, dwMessageId: DWORD, - dwLanguageId: DWORD, lpBuffer: LPWSTR, nSize: DWORD, - Arguments: va_list): DWORD{.stdcall, dynlib: "kernel32", - importc: "FormatMessageW".} - proc CreateMailslot*(lpName: LPCWSTR, nMaxMessageSize: DWORD, - lReadTimeout: DWORD, - lpSecurityAttributes: LPSECURITY_ATTRIBUTES): HANDLE{. - stdcall, dynlib: "kernel32", importc: "CreateMailslotW".} - proc lstrcmp*(lpString1: LPCWSTR, lpString2: LPCWSTR): int32{.stdcall, - dynlib: "kernel32", importc: "lstrcmpW".} - proc lstrcmpi*(lpString1: LPCWSTR, lpString2: LPCWSTR): int32{.stdcall, - dynlib: "kernel32", importc: "lstrcmpiW".} - proc lstrcpyn*(lpString1: LPWSTR, lpString2: LPCWSTR, iMaxLength: int32): LPWSTR{. - stdcall, dynlib: "kernel32", importc: "lstrcpynW".} - proc lstrcpy*(lpString1: LPWSTR, lpString2: LPCWSTR): LPWSTR{.stdcall, - dynlib: "kernel32", importc: "lstrcpyW".} - proc lstrcat*(lpString1: LPWSTR, lpString2: LPCWSTR): LPWSTR{.stdcall, - dynlib: "kernel32", importc: "lstrcatW".} - proc lstrlen*(lpString: LPCWSTR): int32{.stdcall, dynlib: "kernel32", - importc: "lstrlenW".} - proc CreateMutex*(lpMutexAttributes: LPSECURITY_ATTRIBUTES, - bInitialOwner: WINBOOL, lpName: LPCWSTR): HANDLE{.stdcall, - dynlib: "kernel32", importc: "CreateMutexW".} - proc OpenMutex*(dwDesiredAccess: DWORD, bInheritHandle: WINBOOL, - lpName: LPCWSTR): HANDLE{.stdcall, dynlib: "kernel32", - importc: "OpenMutexW".} - proc CreateEvent*(lpEventAttributes: LPSECURITY_ATTRIBUTES, - bManualReset: WINBOOL, bInitialState: WINBOOL, - lpName: LPCWSTR): HANDLE{.stdcall, dynlib: "kernel32", - importc: "CreateEventW".} - proc OpenEvent*(dwDesiredAccess: DWORD, bInheritHandle: WINBOOL, - lpName: LPCWSTR): HANDLE{.stdcall, dynlib: "kernel32", - importc: "OpenEventW".} - proc CreateSemaphore*(lpSemaphoreAttributes: LPSECURITY_ATTRIBUTES, - lInitialCount: LONG, lMaximumCount: LONG, - lpName: LPCWSTR): HANDLE{.stdcall, dynlib: "kernel32", - importc: "CreateSemaphoreW".} - proc OpenSemaphore*(dwDesiredAccess: DWORD, bInheritHandle: WINBOOL, - lpName: LPCWSTR): HANDLE{.stdcall, dynlib: "kernel32", - importc: "OpenSemaphoreW".} - proc CreateFileMapping*(hFile: HANDLE, - lpFileMappingAttributes: LPSECURITY_ATTRIBUTES, - flProtect: DWORD, dwMaximumSizeHigh: DWORD, - dwMaximumSizeLow: DWORD, lpName: LPCWSTR): HANDLE{. - stdcall, dynlib: "kernel32", importc: "CreateFileMappingW".} - proc OpenFileMapping*(dwDesiredAccess: DWORD, bInheritHandle: WINBOOL, - lpName: LPCWSTR): HANDLE{.stdcall, dynlib: "kernel32", - importc: "OpenFileMappingW".} - proc GetLogicalDriveStrings*(nBufferLength: DWORD, lpBuffer: LPWSTR): DWORD{. - stdcall, dynlib: "kernel32", importc: "GetLogicalDriveStringsW".} - proc LoadLibrary*(lpLibFileName: LPCWSTR): HINST{.stdcall, dynlib: "kernel32", - importc: "LoadLibraryW".} - proc LoadLibraryEx*(lpLibFileName: LPCWSTR, hFile: HANDLE, dwFlags: DWORD): HINST{. - stdcall, dynlib: "kernel32", importc: "LoadLibraryExW".} - proc GetModuleFileName*(hModule: HINST, lpFilename: LPWSTR, nSize: DWORD): DWORD{. - stdcall, dynlib: "kernel32", importc: "GetModuleFileNameW".} - proc GetModuleHandle*(lpModuleName: LPCWSTR): HMODULE{.stdcall, - dynlib: "kernel32", importc: "GetModuleHandleW".} - proc FatalAppExit*(uAction: WINUINT, lpMessageText: LPCWSTR){.stdcall, - dynlib: "kernel32", importc: "FatalAppExitW".} - proc GetCommandLine*(): LPWSTR{.stdcall, dynlib: "kernel32", - importc: "GetCommandLineW".} - proc GetEnvironmentVariable*(lpName: LPCWSTR, lpBuffer: LPWSTR, nSize: DWORD): DWORD{. - stdcall, dynlib: "kernel32", importc: "GetEnvironmentVariableW".} - proc SetEnvironmentVariable*(lpName: LPCWSTR, lpValue: LPCWSTR): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "SetEnvironmentVariableW".} - proc ExpandEnvironmentStrings*(lpSrc: LPCWSTR, lpDst: LPWSTR, nSize: DWORD): DWORD{. - stdcall, dynlib: "kernel32", importc: "ExpandEnvironmentStringsW".} - proc OutputDebugString*(lpOutputString: LPCWSTR){.stdcall, dynlib: "kernel32", - importc: "OutputDebugStringW".} - proc FindResource*(hModule: HINST, lpName: LPCWSTR, lpType: LPCWSTR): HRSRC{. - stdcall, dynlib: "kernel32", importc: "FindResourceW".} - proc FindResourceEx*(hModule: HINST, lpType: LPCWSTR, lpName: LPCWSTR, - wLanguage: int16): HRSRC{.stdcall, dynlib: "kernel32", - importc: "FindResourceExW".} - proc EnumResourceTypes*(hModule: HINST, lpEnumFunc: ENUMRESTYPEPROC, - lParam: LONG): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "EnumResourceTypesW".} - proc EnumResourceNames*(hModule: HINST, lpType: LPCWSTR, - lpEnumFunc: ENUMRESNAMEPROC, lParam: LONG): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "EnumResourceNamesW".} - proc EnumResourceLanguages*(hModule: HINST, lpType: LPCWSTR, lpName: LPCWSTR, - lpEnumFunc: ENUMRESLANGPROC, lParam: LONG): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "EnumResourceLanguagesW".} - proc BeginUpdateResource*(pFileName: LPCWSTR, - bDeleteExistingResources: WINBOOL): HANDLE{.stdcall, - dynlib: "kernel32", importc: "BeginUpdateResourceW".} - proc UpdateResource*(hUpdate: HANDLE, lpType: LPCWSTR, lpName: LPCWSTR, - wLanguage: int16, lpData: LPVOID, cbData: DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "UpdateResourceW".} - proc EndUpdateResource*(hUpdate: HANDLE, fDiscard: WINBOOL): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "EndUpdateResourceW".} - proc GlobalAddAtom*(lpString: LPCWSTR): ATOM{.stdcall, dynlib: "kernel32", - importc: "GlobalAddAtomW".} - proc GlobalFindAtom*(lpString: LPCWSTR): ATOM{.stdcall, dynlib: "kernel32", - importc: "GlobalFindAtomW".} - proc GlobalGetAtomName*(nAtom: ATOM, lpBuffer: LPWSTR, nSize: int32): WINUINT{. - stdcall, dynlib: "kernel32", importc: "GlobalGetAtomNameW".} - proc AddAtom*(lpString: LPCWSTR): ATOM{.stdcall, dynlib: "kernel32", - importc: "AddAtomW".} - proc FindAtom*(lpString: LPCWSTR): ATOM{.stdcall, dynlib: "kernel32", - importc: "FindAtomW".} - proc GetAtomName*(nAtom: ATOM, lpBuffer: LPWSTR, nSize: int32): WINUINT{.stdcall, - dynlib: "kernel32", importc: "GetAtomNameW".} - proc GetProfileInt*(lpAppName: LPCWSTR, lpKeyName: LPCWSTR, nDefault: WINT): WINUINT{. - stdcall, dynlib: "kernel32", importc: "GetProfileIntW".} - proc GetProfileString*(lpAppName: LPCWSTR, lpKeyName: LPCWSTR, - lpDefault: LPCWSTR, lpReturnedString: LPWSTR, - nSize: DWORD): DWORD{.stdcall, dynlib: "kernel32", - importc: "GetProfileStringW".} - proc WriteProfileString*(lpAppName: LPCWSTR, lpKeyName: LPCWSTR, - lpString: LPCWSTR): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "WriteProfileStringW".} - proc GetProfileSection*(lpAppName: LPCWSTR, lpReturnedString: LPWSTR, - nSize: DWORD): DWORD{.stdcall, dynlib: "kernel32", - importc: "GetProfileSectionW".} - proc WriteProfileSection*(lpAppName: LPCWSTR, lpString: LPCWSTR): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "WriteProfileSectionW".} - proc GetPrivateProfileInt*(lpAppName: LPCWSTR, lpKeyName: LPCWSTR, - nDefault: WINT, lpFileName: LPCWSTR): WINUINT{. - stdcall, dynlib: "kernel32", importc: "GetPrivateProfileIntW".} - proc GetPrivateProfileString*(lpAppName: LPCWSTR, lpKeyName: LPCWSTR, - lpDefault: LPCWSTR, lpReturnedString: LPWSTR, - nSize: DWORD, lpFileName: LPCWSTR): DWORD{. - stdcall, dynlib: "kernel32", importc: "GetPrivateProfileStringW".} - proc WritePrivateProfileString*(lpAppName: LPCWSTR, lpKeyName: LPCWSTR, - lpString: LPCWSTR, lpFileName: LPCWSTR): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "WritePrivateProfileStringW".} - proc GetPrivateProfileSection*(lpAppName: LPCWSTR, lpReturnedString: LPWSTR, - nSize: DWORD, lpFileName: LPCWSTR): DWORD{. - stdcall, dynlib: "kernel32", importc: "GetPrivateProfileSectionW".} - proc WritePrivateProfileSection*(lpAppName: LPCWSTR, lpString: LPCWSTR, - lpFileName: LPCWSTR): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "WritePrivateProfileSectionW".} - proc GetDriveType*(lpRootPathName: LPCWSTR): WINUINT{.stdcall, - dynlib: "kernel32", importc: "GetDriveTypeW".} - proc GetSystemDirectory*(lpBuffer: LPWSTR, uSize: WINUINT): WINUINT{.stdcall, - dynlib: "kernel32", importc: "GetSystemDirectoryW".} - proc GetTempPath*(nBufferLength: DWORD, lpBuffer: LPWSTR): DWORD{.stdcall, - dynlib: "kernel32", importc: "GetTempPathW".} - proc GetTempFileName*(lpPathName: LPCWSTR, lpPrefixString: LPCWSTR, - uUnique: WINUINT, lpTempFileName: LPWSTR): WINUINT{.stdcall, - dynlib: "kernel32", importc: "GetTempFileNameW".} - proc GetWindowsDirectory*(lpBuffer: LPWSTR, uSize: WINUINT): WINUINT{.stdcall, - dynlib: "kernel32", importc: "GetWindowsDirectoryW".} - proc SetCurrentDirectory*(lpPathName: LPCWSTR): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "SetCurrentDirectoryW".} - proc GetCurrentDirectory*(nBufferLength: DWORD, lpBuffer: LPWSTR): DWORD{. - stdcall, dynlib: "kernel32", importc: "GetCurrentDirectoryW".} - proc GetDiskFreeSpace*(lpRootPathName: LPCWSTR, lpSectorsPerCluster: LPDWORD, - lpBytesPerSector: LPDWORD, - lpNumberOfFreeClusters: LPDWORD, - lpTotalNumberOfClusters: LPDWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetDiskFreeSpaceW".} - proc CreateDirectory*(lpPathName: LPCWSTR, - lpSecurityAttributes: LPSECURITY_ATTRIBUTES): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "CreateDirectoryW".} - proc CreateDirectoryEx*(lpTemplateDirectory: LPCWSTR, lpNewDirectory: LPCWSTR, - lpSecurityAttributes: LPSECURITY_ATTRIBUTES): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "CreateDirectoryExW".} - proc RemoveDirectory*(lpPathName: LPCWSTR): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "RemoveDirectoryW".} - proc GetFullPathName*(lpFileName: LPCWSTR, nBufferLength: DWORD, - lpBuffer: LPWSTR, lpFilePart: var LPWSTR): DWORD{. - stdcall, dynlib: "kernel32", importc: "GetFullPathNameW".} - proc DefineDosDevice*(dwFlags: DWORD, lpDeviceName: LPCWSTR, - lpTargetPath: LPCWSTR): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "DefineDosDeviceW".} - proc QueryDosDevice*(lpDeviceName: LPCWSTR, lpTargetPath: LPWSTR, - ucchMax: DWORD): DWORD{.stdcall, dynlib: "kernel32", - importc: "QueryDosDeviceW".} - proc CreateFile*(lpFileName: LPCWSTR, dwDesiredAccess: DWORD, - dwShareMode: DWORD, - lpSecurityAttributes: LPSECURITY_ATTRIBUTES, - dwCreationDisposition: DWORD, dwFlagsAndAttributes: DWORD, - hTemplateFile: HANDLE): HANDLE{.stdcall, dynlib: "kernel32", - importc: "CreateFileW".} - proc SetFileAttributes*(lpFileName: LPCWSTR, dwFileAttributes: DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "SetFileAttributesW".} - proc GetFileAttributes*(lpFileName: LPCWSTR): DWORD{.stdcall, - dynlib: "kernel32", importc: "GetFileAttributesW".} - proc GetCompressedFileSize*(lpFileName: LPCWSTR, lpFileSizeHigh: LPDWORD): DWORD{. - stdcall, dynlib: "kernel32", importc: "GetCompressedFileSizeW".} - proc DeleteFile*(lpFileName: LPCWSTR): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "DeleteFileW".} - proc SearchPath*(lpPath: LPCWSTR, lpFileName: LPCWSTR, lpExtension: LPCWSTR, - nBufferLength: DWORD, lpBuffer: LPWSTR, lpFilePart: LPWSTR): DWORD{. - stdcall, dynlib: "kernel32", importc: "SearchPathW".} - proc CopyFile*(lpExistingFileName: LPCWSTR, lpNewFileName: LPCWSTR, - bFailIfExists: WINBOOL): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "CopyFileW".} - proc MoveFile*(lpExistingFileName: LPCWSTR, lpNewFileName: LPCWSTR): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "MoveFileW".} - proc MoveFileEx*(lpExistingFileName: LPCWSTR, lpNewFileName: LPCWSTR, - dwFlags: DWORD): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "MoveFileExW".} - proc CreateNamedPipe*(lpName: LPCWSTR, dwOpenMode: DWORD, dwPipeMode: DWORD, - nMaxInstances: DWORD, nOutBufferSize: DWORD, - nInBufferSize: DWORD, nDefaultTimeOut: DWORD, - lpSecurityAttributes: LPSECURITY_ATTRIBUTES): HANDLE{. - stdcall, dynlib: "kernel32", importc: "CreateNamedPipeW".} - proc GetNamedPipeHandleState*(hNamedPipe: HANDLE, lpState: LPDWORD, - lpCurInstances: LPDWORD, - lpMaxCollectionCount: LPDWORD, - lpCollectDataTimeout: LPDWORD, - lpUserName: LPWSTR, nMaxUserNameSize: DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetNamedPipeHandleStateW".} - proc CallNamedPipe*(lpNamedPipeName: LPCWSTR, lpInBuffer: LPVOID, - nInBufferSize: DWORD, lpOutBuffer: LPVOID, - nOutBufferSize: DWORD, lpBytesRead: LPDWORD, - nTimeOut: DWORD): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "CallNamedPipeW".} - proc WaitNamedPipe*(lpNamedPipeName: LPCWSTR, nTimeOut: DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "WaitNamedPipeW".} - proc SetVolumeLabel*(lpRootPathName: LPCWSTR, lpVolumeName: LPCWSTR): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "SetVolumeLabelW".} - proc GetVolumeInformation*(lpRootPathName: LPCWSTR, - lpVolumeNameBuffer: LPWSTR, nVolumeNameSize: DWORD, - lpVolumeSerialNumber: LPDWORD, - lpMaximumComponentLength: LPDWORD, - lpFileSystemFlags: LPDWORD, - lpFileSystemNameBuffer: LPWSTR, - nFileSystemNameSize: DWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetVolumeInformationW".} - proc ClearEventLog*(hEventLog: HANDLE, lpBackupFileName: LPCWSTR): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "ClearEventLogW".} - proc BackupEventLog*(hEventLog: HANDLE, lpBackupFileName: LPCWSTR): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "BackupEventLogW".} - proc OpenEventLog*(lpUNCServerName: LPCWSTR, lpSourceName: LPCWSTR): HANDLE{. - stdcall, dynlib: "advapi32", importc: "OpenEventLogW".} - proc RegisterEventSource*(lpUNCServerName: LPCWSTR, lpSourceName: LPCWSTR): HANDLE{. - stdcall, dynlib: "advapi32", importc: "RegisterEventSourceW".} - proc OpenBackupEventLog*(lpUNCServerName: LPCWSTR, lpFileName: LPCWSTR): HANDLE{. - stdcall, dynlib: "advapi32", importc: "OpenBackupEventLogW".} - proc ReadEventLog*(hEventLog: HANDLE, dwReadFlags: DWORD, - dwRecordOffset: DWORD, lpBuffer: LPVOID, - nNumberOfBytesToRead: DWORD, pnBytesRead: LPDWORD, - pnMinNumberOfBytesNeeded: LPDWORD): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "ReadEventLogW".} - proc ReportEvent*(hEventLog: HANDLE, wType: int16, wCategory: int16, - dwEventID: DWORD, lpUserSid: PSID, wNumStrings: int16, - dwDataSize: DWORD, lpStrings: LPPCWSTR, lpRawData: LPVOID): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "ReportEventW".} - proc AccessCheckAndAuditAlarm*(SubsystemName: LPCWSTR, HandleId: LPVOID, - ObjectTypeName: LPWSTR, ObjectName: LPWSTR, - SecurityDescriptor: PSECURITY_DESCRIPTOR, - DesiredAccess: DWORD, - GenericMapping: PGENERIC_MAPPING, - ObjectCreation: WINBOOL, - GrantedAccess: LPDWORD, AccessStatus: LPBOOL, - pfGenerateOnClose: LPBOOL): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "AccessCheckAndAuditAlarmW".} - proc ObjectOpenAuditAlarm*(SubsystemName: LPCWSTR, HandleId: LPVOID, - ObjectTypeName: LPWSTR, ObjectName: LPWSTR, - pSecurityDescriptor: PSECURITY_DESCRIPTOR, - ClientToken: HANDLE, DesiredAccess: DWORD, - GrantedAccess: DWORD, Privileges: PPRIVILEGE_SET, - ObjectCreation: WINBOOL, AccessGranted: WINBOOL, - GenerateOnClose: LPBOOL): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "ObjectOpenAuditAlarmW".} - proc ObjectPrivilegeAuditAlarm*(SubsystemName: LPCWSTR, HandleId: LPVOID, - ClientToken: HANDLE, DesiredAccess: DWORD, - Privileges: PPRIVILEGE_SET, - AccessGranted: WINBOOL): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "ObjectPrivilegeAuditAlarmW".} - proc ObjectCloseAuditAlarm*(SubsystemName: LPCWSTR, HandleId: LPVOID, - GenerateOnClose: WINBOOL): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "ObjectCloseAuditAlarmW".} - proc PrivilegedServiceAuditAlarm*(SubsystemName: LPCWSTR, - ServiceName: LPCWSTR, ClientToken: HANDLE, - Privileges: PPRIVILEGE_SET, - AccessGranted: WINBOOL): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "PrivilegedServiceAuditAlarmW".} - proc SetFileSecurity*(lpFileName: LPCWSTR, - SecurityInformation: SECURITY_INFORMATION, - pSecurityDescriptor: PSECURITY_DESCRIPTOR): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "SetFileSecurityW".} - proc GetFileSecurity*(lpFileName: LPCWSTR, - RequestedInformation: SECURITY_INFORMATION, - pSecurityDescriptor: PSECURITY_DESCRIPTOR, - nLength: DWORD, lpnLengthNeeded: LPDWORD): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "GetFileSecurityW".} - proc FindFirstChangeNotification*(lpPathName: LPCWSTR, bWatchSubtree: WINBOOL, - dwNotifyFilter: DWORD): HANDLE{.stdcall, - dynlib: "kernel32", importc: "FindFirstChangeNotificationW".} - proc IsBadStringPtr*(lpsz: LPCWSTR, ucchMax: WINUINT): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "IsBadStringPtrW".} - proc LookupAccountSid*(lpSystemName: LPCWSTR, Sid: PSID, Name: LPWSTR, - cbName: LPDWORD, ReferencedDomainName: LPWSTR, - cbReferencedDomainName: LPDWORD, peUse: PSID_NAME_USE): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "LookupAccountSidW".} - proc LookupAccountName*(lpSystemName: LPCWSTR, lpAccountName: LPCWSTR, - Sid: PSID, cbSid: LPDWORD, - ReferencedDomainName: LPWSTR, - cbReferencedDomainName: LPDWORD, peUse: PSID_NAME_USE): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "LookupAccountNameW".} - proc LookupPrivilegeValue*(lpSystemName: LPCWSTR, lpName: LPCWSTR, - lpLuid: PLUID): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "LookupPrivilegeValueW".} - proc LookupPrivilegeName*(lpSystemName: LPCWSTR, lpLuid: PLUID, - lpName: LPWSTR, cbName: LPDWORD): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "LookupPrivilegeNameW".} - proc LookupPrivilegeDisplayName*(lpSystemName: LPCWSTR, lpName: LPCWSTR, - lpDisplayName: LPWSTR, - cbDisplayName: LPDWORD, lpLanguageId: LPDWORD): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "LookupPrivilegeDisplayNameW".} - proc BuildCommDCB*(lpDef: LPCWSTR, lpDCB: LPDCB): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "BuildCommDCBW".} - proc BuildCommDCBAndTimeouts*(lpDef: LPCWSTR, lpDCB: LPDCB, - lpCommTimeouts: LPCOMMTIMEOUTS): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "BuildCommDCBAndTimeoutsW".} - proc CommConfigDialog*(lpszName: LPCWSTR, wnd: HWND, lpCC: LPCOMMCONFIG): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "CommConfigDialogW".} - proc GetDefaultCommConfig*(lpszName: LPCWSTR, lpCC: LPCOMMCONFIG, - lpdwSize: LPDWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetDefaultCommConfigW".} - proc SetDefaultCommConfig*(lpszName: LPCWSTR, lpCC: LPCOMMCONFIG, - dwSize: DWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "SetDefaultCommConfigW".} - proc GetComputerName*(lpBuffer: LPWSTR, nSize: LPDWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetComputerNameW".} - proc SetComputerName*(lpComputerName: LPCWSTR): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "SetComputerNameW".} - proc GetUserName*(lpBuffer: LPWSTR, nSize: LPDWORD): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "GetUserNameW".} - proc LoadKeyboardLayout*(pwszKLID: LPCWSTR, Flags: WINUINT): HKL{.stdcall, - dynlib: "user32", importc: "LoadKeyboardLayoutW".} - proc GetKeyboardLayoutName*(pwszKLID: LPWSTR): WINBOOL{.stdcall, - dynlib: "user32", importc: "GetKeyboardLayoutNameW".} - proc CreateDesktop*(lpszDesktop: LPWSTR, lpszDevice: LPWSTR, - pDevmode: LPDEVMODE, dwFlags: DWORD, - dwDesiredAccess: DWORD, lpsa: LPSECURITY_ATTRIBUTES): HDESK{. - stdcall, dynlib: "user32", importc: "CreateDesktopW".} - proc OpenDesktop*(lpszDesktop: LPWSTR, dwFlags: DWORD, fInherit: WINBOOL, - dwDesiredAccess: DWORD): HDESK{.stdcall, dynlib: "user32", - importc: "OpenDesktopW".} - proc EnumDesktops*(hwinsta: HWINSTA, lpEnumFunc: DESKTOPENUMPROC, - lp: LPARAM): WINBOOL{.stdcall, dynlib: "user32", - importc: "EnumDesktopsW".} - proc CreateWindowStation*(lpwinsta: LPWSTR, dwReserved: DWORD, - dwDesiredAccess: DWORD, lpsa: LPSECURITY_ATTRIBUTES): HWINSTA{. - stdcall, dynlib: "user32", importc: "CreateWindowStationW".} - proc OpenWindowStation*(lpszWinSta: LPWSTR, fInherit: WINBOOL, - dwDesiredAccess: DWORD): HWINSTA{.stdcall, - dynlib: "user32", importc: "OpenWindowStationW".} - proc EnumWindowStations*(lpEnumFunc: ENUMWINDOWSTATIONPROC, lp: LPARAM): WINBOOL{. - stdcall, dynlib: "user32", importc: "EnumWindowStationsW".} - proc GetUserObjectInformation*(hObj: HANDLE, nIndex: int32, pvInfo: PVOID, - nLength: DWORD, lpnLengthNeeded: LPDWORD): WINBOOL{. - stdcall, dynlib: "user32", importc: "GetUserObjectInformationW".} - proc SetUserObjectInformation*(hObj: HANDLE, nIndex: int32, pvInfo: PVOID, - nLength: DWORD): WINBOOL{.stdcall, - dynlib: "user32", importc: "SetUserObjectInformationW".} - proc RegisterWindowMessage*(lpString: LPCWSTR): WINUINT{.stdcall, - dynlib: "user32", importc: "RegisterWindowMessageW".} - proc GetMessage*(lpMsg: LPMSG, wnd: HWND, wMsgFilterMin: WINUINT, - wMsgFilterMax: WINUINT): WINBOOL{.stdcall, dynlib: "user32", - importc: "GetMessageW".} - proc DispatchMessage*(lpMsg: LPMSG): LONG{.stdcall, dynlib: "user32", - importc: "DispatchMessageW".} - proc PeekMessage*(lpMsg: LPMSG, wnd: HWND, wMsgFilterMin: WINUINT, - wMsgFilterMax: WINUINT, wRemoveMsg: WINUINT): WINBOOL{.stdcall, - dynlib: "user32", importc: "PeekMessageW".} - proc SendMessage*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): LRESULT{. - stdcall, dynlib: "user32", importc: "SendMessageW".} - proc SendMessageTimeout*(wnd: HWND, Msg: WINUINT, wp: WPARAM, - lp: LPARAM, fuFlags: WINUINT, uTimeout: WINUINT, - lpdwResult: LPDWORD): LRESULT{.stdcall, - dynlib: "user32", importc: "SendMessageTimeoutW".} - proc SendNotifyMessage*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): WINBOOL{. - stdcall, dynlib: "user32", importc: "SendNotifyMessageW".} - proc SendMessageCallback*(wnd: HWND, Msg: WINUINT, wp: WPARAM, - lp: LPARAM, lpResultCallBack: SENDASYNCPROC, - dwData: DWORD): WINBOOL{.stdcall, dynlib: "user32", - importc: "SendMessageCallbackW".} - proc PostMessage*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): WINBOOL{. - stdcall, dynlib: "user32", importc: "PostMessageW".} - proc PostThreadMessage*(idThread: DWORD, Msg: WINUINT, wp: WPARAM, - lp: LPARAM): WINBOOL{.stdcall, dynlib: "user32", - importc: "PostThreadMessageW".} - proc DefWindowProc*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): LRESULT{. - stdcall, dynlib: "user32", importc: "DefWindowProcW".} - proc CallWindowProc*(lpPrevWndFunc: WNDPROC, wnd: HWND, Msg: WINUINT, - wp: WPARAM, lp: LPARAM): LRESULT{.stdcall, - dynlib: "user32", importc: "CallWindowProcW".} - proc RegisterClass*(lpWndClass: LPWNDCLASS): ATOM{.stdcall, dynlib: "user32", - importc: "RegisterClassW".} - proc UnregisterClass*(lpClassName: LPCWSTR, hInstance: HINST): WINBOOL{. - stdcall, dynlib: "user32", importc: "UnregisterClassW".} - proc GetClassInfo*(hInstance: HINST, lpClassName: LPCWSTR, - lpWndClass: LPWNDCLASS): WINBOOL{.stdcall, - dynlib: "user32", importc: "GetClassInfoW".} - proc RegisterClassEx*(para1: LPWNDCLASSEXW): ATOM{.stdcall, dynlib: "user32", - importc: "RegisterClassExW".} - proc GetClassInfoEx*(para1: HINST, para2: LPCWSTR, para3: LPWNDCLASSEX): WINBOOL{. - stdcall, dynlib: "user32", importc: "GetClassInfoExW".} - proc CreateWindowEx*(dwExStyle: DWORD, lpClassName: LPCWSTR, - lpWindowName: LPCWSTR, dwStyle: DWORD, X: int32, - Y: int32, nWidth: int32, nHeight: int32, - hWndParent: HWND, menu: HMENU, hInstance: HINST, - lpParam: LPVOID): HWND{.stdcall, dynlib: "user32", - importc: "CreateWindowExW".} - proc CreateDialogParam*(hInstance: HINST, lpTemplateName: LPCWSTR, - hWndParent: HWND, lpDialogFunc: DLGPROC, - dwInitParam: LPARAM): HWND{.stdcall, dynlib: "user32", - importc: "CreateDialogParamW".} - proc CreateDialogIndirectParam*(hInstance: HINST, lpTemplate: LPCDLGTEMPLATE, - hWndParent: HWND, lpDialogFunc: DLGPROC, - dwInitParam: LPARAM): HWND{.stdcall, - dynlib: "user32", importc: "CreateDialogIndirectParamW".} - proc DialogBoxParam*(hInstance: HINST, lpTemplateName: LPCWSTR, - hWndParent: HWND, lpDialogFunc: DLGPROC, - dwInitParam: LPARAM): int32{.stdcall, dynlib: "user32", - importc: "DialogBoxParamW".} - proc DialogBoxIndirectParam*(hInstance: HINST, - hDialogTemplate: LPCDLGTEMPLATE, - hWndParent: HWND, lpDialogFunc: DLGPROC, - dwInitParam: LPARAM): int32{.stdcall, - dynlib: "user32", importc: "DialogBoxIndirectParamW".} - proc SetDlgItemText*(hDlg: HWND, nIDDlgItem: int32, lpString: LPCWSTR): WINBOOL{. - stdcall, dynlib: "user32", importc: "SetDlgItemTextW".} - proc GetDlgItemText*(hDlg: HWND, nIDDlgItem: int32, lpString: LPWSTR, - nMaxCount: int32): WINUINT{.stdcall, dynlib: "user32", - importc: "GetDlgItemTextW".} - proc SendDlgItemMessage*(hDlg: HWND, nIDDlgItem: int32, Msg: WINUINT, - wp: WPARAM, lp: LPARAM): LONG{.stdcall, - dynlib: "user32", importc: "SendDlgItemMessageW".} - proc DefDlgProc*(hDlg: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): LRESULT{. - stdcall, dynlib: "user32", importc: "DefDlgProcW".} - proc CallMsgFilter*(lpMsg: LPMSG, nCode: int32): WINBOOL{.stdcall, - dynlib: "user32", importc: "CallMsgFilterW".} - proc RegisterClipboardFormat*(lpszFormat: LPCWSTR): WINUINT{.stdcall, - dynlib: "user32", importc: "RegisterClipboardFormatW".} - proc GetClipboardFormatName*(format: WINUINT, lpszFormatName: LPWSTR, - cchMaxCount: int32): int32{.stdcall, - dynlib: "user32", importc: "GetClipboardFormatNameW".} - proc CharToOem*(lpszSrc: LPCWSTR, lpszDst: LPSTR): WINBOOL{.stdcall, - dynlib: "user32", importc: "CharToOemW".} - proc OemToChar*(lpszSrc: LPCSTR, lpszDst: LPWSTR): WINBOOL{.stdcall, - dynlib: "user32", importc: "OemToCharW".} - proc CharToOemBuff*(lpszSrc: LPCWSTR, lpszDst: LPSTR, cchDstLength: DWORD): WINBOOL{. - stdcall, dynlib: "user32", importc: "CharToOemBuffW".} - proc OemToCharBuff*(lpszSrc: LPCSTR, lpszDst: LPWSTR, cchDstLength: DWORD): WINBOOL{. - stdcall, dynlib: "user32", importc: "OemToCharBuffW".} - proc CharUpper*(lpsz: LPWSTR): LPWSTR{.stdcall, dynlib: "user32", - importc: "CharUpperW".} - proc CharUpperBuff*(lpsz: LPWSTR, cchLength: DWORD): DWORD{.stdcall, - dynlib: "user32", importc: "CharUpperBuffW".} - proc CharLower*(lpsz: LPWSTR): LPWSTR{.stdcall, dynlib: "user32", - importc: "CharLowerW".} - proc CharLowerBuff*(lpsz: LPWSTR, cchLength: DWORD): DWORD{.stdcall, - dynlib: "user32", importc: "CharLowerBuffW".} - proc CharNext*(lpsz: LPCWSTR): LPWSTR{.stdcall, dynlib: "user32", - importc: "CharNextW".} - proc CharPrev*(lpszStart: LPCWSTR, lpszCurrent: LPCWSTR): LPWSTR{.stdcall, - dynlib: "user32", importc: "CharPrevW".} - proc IsCharAlpha*(ch: WCHAR): WINBOOL{.stdcall, dynlib: "user32", - importc: "IsCharAlphaW".} - proc IsCharAlphaNumeric*(ch: WCHAR): WINBOOL{.stdcall, dynlib: "user32", - importc: "IsCharAlphaNumericW".} - proc IsCharUpper*(ch: WCHAR): WINBOOL{.stdcall, dynlib: "user32", - importc: "IsCharUpperW".} - proc IsCharLower*(ch: WCHAR): WINBOOL{.stdcall, dynlib: "user32", - importc: "IsCharLowerW".} - proc GetKeyNameText*(lParam: LONG, lpString: LPWSTR, nSize: int32): int32{. - stdcall, dynlib: "user32", importc: "GetKeyNameTextW".} - proc VkKeyScan*(ch: WCHAR): SHORT{.stdcall, dynlib: "user32", - importc: "VkKeyScanW".} - proc VkKeyScanEx*(ch: WCHAR, dwhkl: HKL): SHORT{.stdcall, dynlib: "user32", - importc: "VkKeyScanExW".} - proc MapVirtualKey*(uCode: WINUINT, uMapType: WINUINT): WINUINT{.stdcall, - dynlib: "user32", importc: "MapVirtualKeyW".} - proc MapVirtualKeyEx*(uCode: WINUINT, uMapType: WINUINT, dwhkl: HKL): WINUINT{.stdcall, - dynlib: "user32", importc: "MapVirtualKeyExW".} - proc LoadAccelerators*(hInstance: HINST, lpTableName: LPCWSTR): HACCEL{. - stdcall, dynlib: "user32", importc: "LoadAcceleratorsW".} - proc CreateAcceleratorTable*(para1: LPACCEL, para2: int32): HACCEL{.stdcall, - dynlib: "user32", importc: "CreateAcceleratorTableW".} - proc CopyAcceleratorTable*(hAccelSrc: HACCEL, lpAccelDst: LPACCEL, - cAccelEntries: int32): int32{.stdcall, - dynlib: "user32", importc: "CopyAcceleratorTableW".} - proc TranslateAccelerator*(wnd: HWND, hAccTable: HACCEL, lpMsg: LPMSG): int32{. - stdcall, dynlib: "user32", importc: "TranslateAcceleratorW".} - proc LoadMenu*(hInstance: HINST, lpMenuName: LPCWSTR): HMENU{.stdcall, - dynlib: "user32", importc: "LoadMenuW".} - proc LoadMenuIndirect*(lpMenuTemplate: LPMENUTEMPLATE): HMENU{.stdcall, - dynlib: "user32", importc: "LoadMenuIndirectW".} - proc ChangeMenu*(menu: HMENU, cmd: WINUINT, lpszNewItem: LPCWSTR, - cmdInsert: WINUINT, flags: WINUINT): WINBOOL{.stdcall, - dynlib: "user32", importc: "ChangeMenuW".} - proc GetMenuString*(menu: HMENU, uIDItem: WINUINT, lpString: LPWSTR, - nMaxCount: int32, uFlag: WINUINT): int32{.stdcall, - dynlib: "user32", importc: "GetMenuStringW".} - proc InsertMenu*(menu: HMENU, uPosition: WINUINT, uFlags: WINUINT, - uIDNewItem: WINUINT, lpNewItem: LPCWSTR): WINBOOL{.stdcall, - dynlib: "user32", importc: "InsertMenuW".} - proc AppendMenu*(menu: HMENU, uFlags: WINUINT, uIDNewItem: WINUINT, - lpNewItem: LPCWSTR): WINBOOL{.stdcall, dynlib: "user32", - importc: "AppendMenuW".} - proc ModifyMenu*(hMnu: HMENU, uPosition: WINUINT, uFlags: WINUINT, uIDNewItem: WINUINT, - lpNewItem: LPCWSTR): WINBOOL{.stdcall, dynlib: "user32", - importc: "ModifyMenuW".} - proc InsertMenuItem*(para1: HMENU, para2: WINUINT, para3: WINBOOL, - para4: LPCMENUITEMINFO): WINBOOL{.stdcall, - dynlib: "user32", importc: "InsertMenuItemW".} - proc GetMenuItemInfo*(para1: HMENU, para2: WINUINT, para3: WINBOOL, - para4: LPMENUITEMINFO): WINBOOL{.stdcall, - dynlib: "user32", importc: "GetMenuItemInfoW".} - proc SetMenuItemInfo*(para1: HMENU, para2: WINUINT, para3: WINBOOL, - para4: LPCMENUITEMINFO): WINBOOL{.stdcall, - dynlib: "user32", importc: "SetMenuItemInfoW".} - proc DrawText*(hDC: HDC, lpString: LPCWSTR, nCount: int32, lpRect: LPRECT, - uFormat: WINUINT): int32{.stdcall, dynlib: "user32", - importc: "DrawTextW".} - proc DrawTextEx*(para1: HDC, para2: LPWSTR, para3: int32, para4: LPRECT, - para5: WINUINT, para6: LPDRAWTEXTPARAMS): int32{.stdcall, - dynlib: "user32", importc: "DrawTextExW".} - proc GrayString*(hDC: HDC, hBrush: HBRUSH, lpOutputFunc: GRAYSTRINGPROC, - lpData: LPARAM, nCount: int32, X: int32, Y: int32, - nWidth: int32, nHeight: int32): WINBOOL{.stdcall, - dynlib: "user32", importc: "GrayStringW".} - proc DrawState*(para1: HDC, para2: HBRUSH, para3: DRAWSTATEPROC, - para4: LPARAM, para5: WPARAM, para6: int32, para7: int32, - para8: int32, para9: int32, para10: WINUINT): WINBOOL{.stdcall, - dynlib: "user32", importc: "DrawStateW".} - proc TabbedTextOut*(hDC: HDC, X: int32, Y: int32, lpString: LPCWSTR, - nCount: int32, nTabPositions: int32, - lpnTabStopPositions: LPINT, nTabOrigin: int32): LONG{. - stdcall, dynlib: "user32", importc: "TabbedTextOutW".} - proc GetTabbedTextExtent*(hDC: HDC, lpString: LPCWSTR, nCount: int32, - nTabPositions: int32, lpnTabStopPositions: LPINT): DWORD{. - stdcall, dynlib: "user32", importc: "GetTabbedTextExtentW".} - proc SetProp*(wnd: HWND, lpString: LPCWSTR, hData: HANDLE): WINBOOL{.stdcall, - dynlib: "user32", importc: "SetPropW".} - proc GetProp*(wnd: HWND, lpString: LPCWSTR): HANDLE{.stdcall, - dynlib: "user32", importc: "GetPropW".} - proc RemoveProp*(wnd: HWND, lpString: LPCWSTR): HANDLE{.stdcall, - dynlib: "user32", importc: "RemovePropW".} - proc EnumPropsEx*(wnd: HWND, lpEnumFunc: PROPENUMPROCEX, lp: LPARAM): int32{. - stdcall, dynlib: "user32", importc: "EnumPropsExW".} - proc EnumProps*(wnd: HWND, lpEnumFunc: PROPENUMPROC): int32{.stdcall, - dynlib: "user32", importc: "EnumPropsW".} - proc SetWindowText*(wnd: HWND, lpString: LPCWSTR): WINBOOL{.stdcall, - dynlib: "user32", importc: "SetWindowTextW".} - proc GetWindowText*(wnd: HWND, lpString: LPWSTR, nMaxCount: int32): int32{. - stdcall, dynlib: "user32", importc: "GetWindowTextW".} - proc GetWindowTextLength*(wnd: HWND): int32{.stdcall, dynlib: "user32", - importc: "GetWindowTextLengthW".} - proc MessageBox*(wnd: HWND, lpText: LPCWSTR, lpCaption: LPCWSTR, uType: WINUINT): int32{. - stdcall, dynlib: "user32", importc: "MessageBoxW".} - proc MessageBoxEx*(wnd: HWND, lpText: LPCWSTR, lpCaption: LPCWSTR, - uType: WINUINT, wLanguageId: int16): int32{.stdcall, - dynlib: "user32", importc: "MessageBoxExW".} - proc MessageBoxIndirect*(para1: LPMSGBOXPARAMS): int32{.stdcall, - dynlib: "user32", importc: "MessageBoxIndirectW".} - proc GetWindowLong*(wnd: HWND, nIndex: int32): LONG{.stdcall, - dynlib: "user32", importc: "GetWindowLongW".} - proc SetWindowLong*(wnd: HWND, nIndex: int32, dwNewLong: LONG): LONG{. - stdcall, dynlib: "user32", importc: "SetWindowLongW".} - proc GetClassLong*(wnd: HWND, nIndex: int32): DWORD{.stdcall, - dynlib: "user32", importc: "GetClassLongW".} - proc SetClassLong*(wnd: HWND, nIndex: int32, dwNewLong: LONG): DWORD{. - stdcall, dynlib: "user32", importc: "SetClassLongW".} - when defined(cpu64): - proc GetWindowLongPtr*(wnd: HWND, nIndex: int32): LONG_PTR{.stdcall, - dynlib: "user32", importc: "GetWindowLongPtrW".} - proc SetWindowLongPtr*(wnd: HWND, nIndex: int32, dwNewLong: LONG_PTR): LONG_PTR{. - stdcall, dynlib: "user32", importc: "SetWindowLongPtrW".} - proc GetClassLongPtr*(wnd: HWND, nIndex: int32): LONG_PTR{.stdcall, - dynlib: "user32", importc: "GetClassLongPtrW".} - proc SetClassLongPtr*(wnd: HWND, nIndex: int32, dwNewLong: LONG_PTR): LONG_PTR{. - stdcall, dynlib: "user32", importc: "SetClassLongPtrW".} - else: - proc GetWindowLongPtr*(wnd: HWND, nIndex: int32): LONG_PTR{.stdcall, - dynlib: "user32", importc: "GetWindowLongW".} - proc SetWindowLongPtr*(wnd: HWND, nIndex: int32, dwNewLong: LONG_PTR): LONG_PTR{. - stdcall, dynlib: "user32", importc: "SetWindowLongW".} - proc GetClassLongPtr*(wnd: HWND, nIndex: int32): LONG_PTR{.stdcall, - dynlib: "user32", importc: "GetClassLongW".} - proc SetClassLongPtr*(wnd: HWND, nIndex: int32, dwNewLong: LONG_PTR): LONG_PTR{. - stdcall, dynlib: "user32", importc: "SetClassLongW".} - proc FindWindow*(lpClassName: LPCWSTR, lpWindowName: LPCWSTR): HWND{.stdcall, - dynlib: "user32", importc: "FindWindowW".} - proc FindWindowEx*(para1: HWND, para2: HWND, para3: LPCWSTR, para4: LPCWSTR): HWND{. - stdcall, dynlib: "user32", importc: "FindWindowExW".} - proc GetClassName*(wnd: HWND, lpClassName: LPWSTR, nMaxCount: int32): int32{. - stdcall, dynlib: "user32", importc: "GetClassNameW".} - proc SetWindowsHookEx*(idHook: int32, lpfn: HOOKPROC, hmod: HINST, - dwThreadId: DWORD): HHOOK{.stdcall, dynlib: "user32", - importc: "SetWindowsHookExW".} - proc LoadBitmap*(hInstance: HINST, lpBitmapName: LPCWSTR): HBITMAP{.stdcall, - dynlib: "user32", importc: "LoadBitmapW".} - proc LoadCursor*(hInstance: HINST, lpCursorName: LPCWSTR): HCURSOR{.stdcall, - dynlib: "user32", importc: "LoadCursorW".} - proc LoadCursorFromFile*(lpFileName: LPCWSTR): HCURSOR{.stdcall, - dynlib: "user32", importc: "LoadCursorFromFileW".} - proc LoadIcon*(hInstance: HINST, lpIconName: LPCWSTR): HICON{.stdcall, - dynlib: "user32", importc: "LoadIconW".} - proc LoadImage*(para1: HINST, para2: LPCWSTR, para3: WINUINT, para4: int32, - para5: int32, para6: WINUINT): HANDLE{.stdcall, dynlib: "user32", - importc: "LoadImageW".} - proc LoadString*(hInstance: HINST, uID: WINUINT, lpBuffer: LPWSTR, - nBufferMax: int32): int32{.stdcall, dynlib: "user32", - importc: "LoadStringW".} - proc IsDialogMessage*(hDlg: HWND, lpMsg: LPMSG): WINBOOL{.stdcall, - dynlib: "user32", importc: "IsDialogMessageW".} - proc DlgDirList*(hDlg: HWND, lpPathSpec: LPWSTR, nIDListBox: int32, - nIDStaticPath: int32, uFileType: WINUINT): int32{.stdcall, - dynlib: "user32", importc: "DlgDirListW".} - proc DlgDirSelectEx*(hDlg: HWND, lpString: LPWSTR, nCount: int32, - nIDListBox: int32): WINBOOL{.stdcall, dynlib: "user32", - importc: "DlgDirSelectExW".} - proc DlgDirListComboBox*(hDlg: HWND, lpPathSpec: LPWSTR, nIDComboBox: int32, - nIDStaticPath: int32, uFiletype: WINUINT): int32{. - stdcall, dynlib: "user32", importc: "DlgDirListComboBoxW".} - proc DlgDirSelectComboBoxEx*(hDlg: HWND, lpString: LPWSTR, nCount: int32, - nIDComboBox: int32): WINBOOL{.stdcall, - dynlib: "user32", importc: "DlgDirSelectComboBoxExW".} - proc DefFrameProc*(wnd: HWND, hWndMDIClient: HWND, uMsg: WINUINT, - wp: WPARAM, lp: LPARAM): LRESULT{.stdcall, - dynlib: "user32", importc: "DefFrameProcW".} - proc DefMDIChildProc*(wnd: HWND, uMsg: WINUINT, wp: WPARAM, lp: LPARAM): LRESULT{. - stdcall, dynlib: "user32", importc: "DefMDIChildProcW".} - proc CreateMDIWindow*(lpClassName: LPWSTR, lpWindowName: LPWSTR, - dwStyle: DWORD, X: int32, Y: int32, nWidth: int32, - nHeight: int32, hWndParent: HWND, hInstance: HINST, - lp: LPARAM): HWND{.stdcall, dynlib: "user32", - importc: "CreateMDIWindowW".} - proc WinHelp*(hWndMain: HWND, lpszHelp: LPCWSTR, uCommand: WINUINT, dwData: DWORD): WINBOOL{. - stdcall, dynlib: "user32", importc: "WinHelpW".} - proc ChangeDisplaySettings*(lpDevMode: LPDEVMODE, dwFlags: DWORD): LONG{. - stdcall, dynlib: "user32", importc: "ChangeDisplaySettingsW".} - proc EnumDisplaySettings*(lpszDeviceName: LPCWSTR, iModeNum: DWORD, - lpDevMode: LPDEVMODEW): WINBOOL{.stdcall, - dynlib: "user32", importc: "EnumDisplaySettingsW".} - proc SystemParametersInfo*(uiAction: WINUINT, uiParam: WINUINT, pvParam: PVOID, - fWinIni: WINUINT): WINBOOL{.stdcall, dynlib: "user32", - importc: "SystemParametersInfoW".} - proc AddFontResource*(para1: LPCWSTR): int32{.stdcall, dynlib: "gdi32", - importc: "AddFontResourceW".} - proc CopyMetaFile*(para1: HMETAFILE, para2: LPCWSTR): HMETAFILE{.stdcall, - dynlib: "gdi32", importc: "CopyMetaFileW".} - proc CreateFontIndirect*(para1: PLOGFONT): HFONT{.stdcall, dynlib: "gdi32", - importc: "CreateFontIndirectW".} - proc CreateFontIndirect*(para1: var LOGFONT): HFONT{.stdcall, dynlib: "gdi32", - importc: "CreateFontIndirectW".} - proc CreateFont*(para1: int32, para2: int32, para3: int32, para4: int32, - para5: int32, para6: DWORD, para7: DWORD, para8: DWORD, - para9: DWORD, para10: DWORD, para11: DWORD, para12: DWORD, - para13: DWORD, para14: LPCWSTR): HFONT{.stdcall, - dynlib: "gdi32", importc: "CreateFontW".} - proc CreateIC*(para1: LPCWSTR, para2: LPCWSTR, para3: LPCWSTR, - para4: LPDEVMODE): HDC{.stdcall, dynlib: "gdi32", - importc: "CreateICW".} - proc CreateMetaFile*(para1: LPCWSTR): HDC{.stdcall, dynlib: "gdi32", - importc: "CreateMetaFileW".} - proc CreateScalableFontResource*(para1: DWORD, para2: LPCWSTR, para3: LPCWSTR, - para4: LPCWSTR): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "CreateScalableFontResourceW".} - proc EnumFontFamiliesEx*(para1: HDC, para2: LPLOGFONT, para3: FONTENUMEXPROC, - para4: LPARAM, para5: DWORD): int32{.stdcall, - dynlib: "gdi32", importc: "EnumFontFamiliesExW".} - proc EnumFontFamilies*(para1: HDC, para2: LPCWSTR, para3: FONTENUMPROC, - para4: LPARAM): int32{.stdcall, dynlib: "gdi32", - importc: "EnumFontFamiliesW".} - proc EnumFonts*(para1: HDC, para2: LPCWSTR, para3: ENUMFONTSPROC, - para4: LPARAM): int32{.stdcall, dynlib: "gdi32", - importc: "EnumFontsW".} - proc EnumFonts*(para1: HDC, para2: LPCWSTR, para3: ENUMFONTSPROC, - para4: pointer): int32{.stdcall, dynlib: "gdi32", - importc: "EnumFontsW".} - proc GetCharWidth*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: LPINT): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "GetCharWidthW".} - proc GetCharWidth32*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: LPINT): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "GetCharWidth32W".} - proc GetCharWidthFloat*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: ptr float32): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "GetCharWidthFloatW".} - proc GetCharABCWidths*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: LPABC): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "GetCharABCWidthsW".} - proc GetCharABCWidthsFloat*(para1: HDC, para2: WINUINT, para3: WINUINT, - para4: LPABCFLOAT): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "GetCharABCWidthsFloatW".} - proc GetGlyphOutline*(para1: HDC, para2: WINUINT, para3: WINUINT, - para4: LPGLYPHMETRICS, para5: DWORD, para6: LPVOID, - para7: PMAT2): DWORD{.stdcall, dynlib: "gdi32", - importc: "GetGlyphOutlineW".} - proc GetMetaFile*(para1: LPCWSTR): HMETAFILE{.stdcall, dynlib: "gdi32", - importc: "GetMetaFileW".} - proc GetOutlineTextMetrics*(para1: HDC, para2: WINUINT, - para3: LPOUTLINETEXTMETRIC): WINUINT{.stdcall, - dynlib: "gdi32", importc: "GetOutlineTextMetricsW".} - proc GetTextExtentPoint*(para1: HDC, para2: LPCWSTR, para3: int32, - para4: LPSIZE): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "GetTextExtentPointW".} - proc GetTextExtentPoint32*(para1: HDC, para2: LPCWSTR, para3: int32, - para4: LPSIZE): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "GetTextExtentPoint32W".} - proc GetTextExtentExPoint*(para1: HDC, para2: LPCWSTR, para3: int32, - para4: int32, para5: LPINT, para6: LPINT, - para7: LPSIZE): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "GetTextExtentExPointW".} - proc GetCharacterPlacement*(para1: HDC, para2: LPCWSTR, para3: int32, - para4: int32, para5: LPGCP_RESULTS, para6: DWORD): DWORD{. - stdcall, dynlib: "gdi32", importc: "GetCharacterPlacementW".} - proc ResetDC*(para1: HDC, para2: LPDEVMODE): HDC{.stdcall, dynlib: "gdi32", - importc: "ResetDCW".} - proc RemoveFontResource*(para1: LPCWSTR): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "RemoveFontResourceW".} - proc CopyEnhMetaFile*(para1: HENHMETAFILE, para2: LPCWSTR): HENHMETAFILE{. - stdcall, dynlib: "gdi32", importc: "CopyEnhMetaFileW".} - proc CreateEnhMetaFile*(para1: HDC, para2: LPCWSTR, para3: LPRECT, - para4: LPCWSTR): HDC{.stdcall, dynlib: "gdi32", - importc: "CreateEnhMetaFileW".} - proc GetEnhMetaFile*(para1: LPCWSTR): HENHMETAFILE{.stdcall, dynlib: "gdi32", - importc: "GetEnhMetaFileW".} - proc GetEnhMetaFileDescription*(para1: HENHMETAFILE, para2: WINUINT, - para3: LPWSTR): WINUINT{.stdcall, - dynlib: "gdi32", importc: "GetEnhMetaFileDescriptionW".} - proc GetTextMetrics*(para1: HDC, para2: LPTEXTMETRIC): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "GetTextMetricsW".} - proc StartDoc*(para1: HDC, para2: PDOCINFO): int32{.stdcall, dynlib: "gdi32", - importc: "StartDocW".} - proc GetObject*(para1: HGDIOBJ, para2: int32, para3: LPVOID): int32{.stdcall, - dynlib: "gdi32", importc: "GetObjectW".} - proc TextOut*(para1: HDC, para2: int32, para3: int32, para4: LPCWSTR, - para5: int32): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "TextOutW".} - proc ExtTextOut*(para1: HDC, para2: int32, para3: int32, para4: WINUINT, - para5: LPRECT, para6: LPCWSTR, para7: WINUINT, para8: LPINT): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "ExtTextOutW".} - proc PolyTextOut*(para1: HDC, para2: PPOLYTEXT, para3: int32): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "PolyTextOutW".} - proc GetTextFace*(para1: HDC, para2: int32, para3: LPWSTR): int32{.stdcall, - dynlib: "gdi32", importc: "GetTextFaceW".} - proc GetKerningPairs*(para1: HDC, para2: DWORD, para3: LPKERNINGPAIR): DWORD{. - stdcall, dynlib: "gdi32", importc: "GetKerningPairsW".} - proc GetLogColorSpace*(para1: HCOLORSPACE, para2: LPLOGCOLORSPACE, - para3: DWORD): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "GetLogColorSpaceW".} - proc CreateColorSpace*(para1: LPLOGCOLORSPACE): HCOLORSPACE{.stdcall, - dynlib: "gdi32", importc: "CreateColorSpaceW".} - proc GetICMProfile*(para1: HDC, para2: DWORD, para3: LPWSTR): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "GetICMProfileW".} - proc SetICMProfile*(para1: HDC, para2: LPWSTR): WINBOOL{.stdcall, - - dynlib: "gdi32", importc: "SetICMProfileW".} - proc UpdateICMRegKey*(para1: DWORD, para2: DWORD, para3: LPWSTR, para4: WINUINT): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "UpdateICMRegKeyW".} - proc EnumICMProfiles*(para1: HDC, para2: ICMENUMPROC, para3: LPARAM): int32{. - stdcall, dynlib: "gdi32", importc: "EnumICMProfilesW".} - proc CreatePropertySheetPage*(lppsp: LPCPROPSHEETPAGE): HPROPSHEETPAGE{. - stdcall, dynlib: "comctl32", importc: "CreatePropertySheetPageW".} - proc PropertySheet*(lppsph: LPCPROPSHEETHEADER): int32{.stdcall, - dynlib: "comctl32", importc: "PropertySheetW".} - proc ImageList_LoadImage*(hi: HINST, lpbmp: LPCWSTR, cx: int32, cGrow: int32, - crMask: COLORREF, uType: WINUINT, uFlags: WINUINT): HIMAGELIST{. - stdcall, dynlib: "comctl32", importc: "ImageList_LoadImageW".} - proc CreateStatusWindow*(style: LONG, lpszText: LPCWSTR, hwndParent: HWND, - wID: WINUINT): HWND{.stdcall, dynlib: "comctl32", - importc: "CreateStatusWindowW".} - proc DrawStatusText*(hDC: HDC, lprc: LPRECT, pszText: LPCWSTR, uFlags: WINUINT){. - stdcall, dynlib: "comctl32", importc: "DrawStatusTextW".} - proc GetOpenFileName*(para1: LPOPENFILENAME): WINBOOL{.stdcall, - dynlib: "comdlg32", importc: "GetOpenFileNameW".} - proc GetSaveFileName*(para1: LPOPENFILENAME): WINBOOL{.stdcall, - dynlib: "comdlg32", importc: "GetSaveFileNameW".} - proc GetFileTitle*(para1: LPCWSTR, para2: LPWSTR, para3: int16): int{.stdcall, - dynlib: "comdlg32", importc: "GetFileTitleW".} - proc ChooseColor*(para1: LPCHOOSECOLOR): WINBOOL{.stdcall, dynlib: "comdlg32", - importc: "ChooseColorW".} - proc ReplaceText*(para1: LPFINDREPLACE): HWND{.stdcall, dynlib: "comdlg32", - importc: "ReplaceTextW".} - proc ChooseFont*(para1: LPCHOOSEFONT): WINBOOL{.stdcall, dynlib: "comdlg32", - importc: "ChooseFontW".} - proc FindText*(para1: LPFINDREPLACE): HWND{.stdcall, dynlib: "comdlg32", - importc: "FindTextW".} - proc PrintDlg*(para1: LPPRINTDLG): WINBOOL{.stdcall, dynlib: "comdlg32", - importc: "PrintDlgW".} - proc PageSetupDlg*(para1: LPPAGESETUPDLG): WINBOOL{.stdcall, - dynlib: "comdlg32", importc: "PageSetupDlgW".} - proc CreateProcess*(lpApplicationName: LPCWSTR, lpCommandLine: LPWSTR, - lpProcessAttributes: LPSECURITY_ATTRIBUTES, - lpThreadAttributes: LPSECURITY_ATTRIBUTES, - bInheritHandles: WINBOOL, dwCreationFlags: DWORD, - lpEnvironment: LPVOID, lpCurrentDirectory: LPCWSTR, - lpStartupInfo: LPSTARTUPINFO, - lpProcessInformation: LPPROCESS_INFORMATION): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "CreateProcessW".} - proc GetStartupInfo*(lpStartupInfo: LPSTARTUPINFO){.stdcall, - dynlib: "kernel32", importc: "GetStartupInfoW".} - proc FindFirstFile*(lpFileName: LPCWSTR, lpFindFileData: LPWIN32_FIND_DATA): HANDLE{. - stdcall, dynlib: "kernel32", importc: "FindFirstFileW".} - proc FindNextFile*(hFindFile: HANDLE, lpFindFileData: LPWIN32_FIND_DATA): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "FindNextFileW".} - proc GetVersionEx*(VersionInformation: LPOSVERSIONINFOW): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetVersionExW".} - proc GetVersionExW*(VersionInformation: LPOSVERSIONINFOW): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetVersionExW".} - proc CreateWindow*(lpClassName: LPCWSTR, lpWindowName: LPCWSTR, - dwStyle: DWORD, X: int32, Y: int32, nWidth: int32, - nHeight: int32, hWndParent: HWND, menu: HMENU, - hInstance: HINST, lpParam: LPVOID): HWND - proc CreateDialog*(hInstance: HINST, lpName: LPCWSTR, hWndParent: HWND, - lpDialogFunc: DLGPROC): HWND - proc CreateDialogIndirect*(hInstance: HINST, lpTemplate: LPCDLGTEMPLATE, - hWndParent: HWND, lpDialogFunc: DLGPROC): HWND - proc DialogBox*(hInstance: HINST, lpTemplate: LPCWSTR, hWndParent: HWND, - lpDialogFunc: DLGPROC): int32 - proc DialogBoxIndirect*(hInstance: HINST, lpTemplate: LPCDLGTEMPLATE, - hWndParent: HWND, lpDialogFunc: DLGPROC): int32 - proc CreateDC*(para1: LPCWSTR, para2: LPCWSTR, para3: LPCWSTR, para4: PDEVMODE): HDC{. - stdcall, dynlib: "gdi32", importc: "CreateDCW".} - proc VerInstallFile*(uFlags: DWORD, szSrcFileName: LPWSTR, - szDestFileName: LPWSTR, szSrcDir: LPWSTR, - szDestDir: LPWSTR, szCurDir: LPWSTR, szTmpFile: LPWSTR, - lpuTmpFileLen: PUINT): DWORD{.stdcall, dynlib: "version", - importc: "VerInstallFileW".} - proc GetFileVersionInfoSize*(lptstrFilename: LPWSTR, lpdwHandle: LPDWORD): DWORD{. - stdcall, dynlib: "version", importc: "GetFileVersionInfoSizeW".} - proc GetFileVersionInfo*(lptstrFilename: LPWSTR, dwHandle: DWORD, - dwLen: DWORD, lpData: LPVOID): WINBOOL{.stdcall, - dynlib: "version", importc: "GetFileVersionInfoW".} - proc VerLanguageName*(wLang: DWORD, szLang: LPWSTR, nSize: DWORD): DWORD{. - stdcall, dynlib: "kernel32", importc: "VerLanguageNameW".} - proc VerQueryValue*(pBlock: LPVOID, lpSubBlock: LPWSTR, lplpBuffer: LPVOID, - puLen: PUINT): WINBOOL{.stdcall, dynlib: "version", - importc: "VerQueryValueW".} - proc VerFindFile*(uFlags: DWORD, szFileName: LPWSTR, szWinDir: LPWSTR, - szAppDir: LPWSTR, szCurDir: LPWSTR, lpuCurDirLen: PUINT, - szDestDir: LPWSTR, lpuDestDirLen: PUINT): DWORD{.stdcall, - dynlib: "version", importc: "VerFindFileW".} - proc RegSetValueEx*(key: HKEY, lpValueName: LPCWSTR, Reserved: DWORD, - dwType: DWORD, lpData: LPBYTE, cbData: DWORD): LONG{. - stdcall, dynlib: "advapi32", importc: "RegSetValueExW".} - proc RegUnLoadKey*(key: HKEY, lpSubKey: LPCWSTR): LONG{.stdcall, - dynlib: "advapi32", importc: "RegUnLoadKeyW".} - proc InitiateSystemShutdown*(lpMachineName: LPWSTR, lpMessage: LPWSTR, - dwTimeout: DWORD, bForceAppsClosed: WINBOOL, - bRebootAfterShutdown: WINBOOL): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "InitiateSystemShutdownW".} - proc AbortSystemShutdown*(lpMachineName: LPWSTR): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "AbortSystemShutdownW".} - proc RegRestoreKey*(key: HKEY, lpFile: LPCWSTR, dwFlags: DWORD): LONG{. - stdcall, dynlib: "advapi32", importc: "RegRestoreKeyW".} - proc RegSaveKey*(key: HKEY, lpFile: LPCWSTR, - lpSecurityAttributes: LPSECURITY_ATTRIBUTES): LONG{.stdcall, - dynlib: "advapi32", importc: "RegSaveKeyW".} - proc RegSetValue*(key: HKEY, lpSubKey: LPCWSTR, dwType: DWORD, - lpData: LPCWSTR, cbData: DWORD): LONG{.stdcall, - dynlib: "advapi32", importc: "RegSetValueW".} - proc RegQueryValue*(key: HKEY, lpSubKey: LPCWSTR, lpValue: LPWSTR, - lpcbValue: PLONG): LONG{.stdcall, dynlib: "advapi32", - importc: "RegQueryValueW".} - proc RegQueryMultipleValues*(key: HKEY, val_list: PVALENT, num_vals: DWORD, - lpValueBuf: LPWSTR, ldwTotsize: LPDWORD): LONG{. - stdcall, dynlib: "advapi32", importc: "RegQueryMultipleValuesW".} - proc RegQueryValueEx*(key: HKEY, lpValueName: LPCWSTR, lpReserved: LPDWORD, - lpType: LPDWORD, lpData: LPBYTE, lpcbData: LPDWORD): LONG{. - stdcall, dynlib: "advapi32", importc: "RegQueryValueExW".} - proc RegReplaceKey*(key: HKEY, lpSubKey: LPCWSTR, lpNewFile: LPCWSTR, - lpOldFile: LPCWSTR): LONG{.stdcall, dynlib: "advapi32", - importc: "RegReplaceKeyW".} - proc RegConnectRegistry*(lpMachineName: LPWSTR, key: HKEY, phkResult: PHKEY): LONG{. - stdcall, dynlib: "advapi32", importc: "RegConnectRegistryW".} - proc RegCreateKey*(key: HKEY, lpSubKey: LPCWSTR, phkResult: PHKEY): LONG{. - stdcall, dynlib: "advapi32", importc: "RegCreateKeyW".} - proc RegCreateKeyEx*(key: HKEY, lpSubKey: LPCWSTR, Reserved: DWORD, - lpClass: LPWSTR, dwOptions: DWORD, samDesired: REGSAM, - lpSecurityAttributes: LPSECURITY_ATTRIBUTES, - phkResult: PHKEY, lpdwDisposition: LPDWORD): LONG{. - stdcall, dynlib: "advapi32", importc: "RegCreateKeyExW".} - proc RegDeleteKey*(key: HKEY, lpSubKey: LPCWSTR): LONG{.stdcall, - dynlib: "advapi32", importc: "RegDeleteKeyW".} - proc RegDeleteValue*(key: HKEY, lpValueName: LPCWSTR): LONG{.stdcall, - dynlib: "advapi32", importc: "RegDeleteValueW".} - proc RegEnumKey*(key: HKEY, dwIndex: DWORD, lpName: LPWSTR, cbName: DWORD): LONG{. - stdcall, dynlib: "advapi32", importc: "RegEnumKeyW".} - proc RegEnumKeyEx*(key: HKEY, dwIndex: DWORD, lpName: LPWSTR, - lpcbName: LPDWORD, lpReserved: LPDWORD, lpClass: LPWSTR, - lpcbClass: LPDWORD, lpftLastWriteTime: PFILETIME): LONG{. - stdcall, dynlib: "advapi32", importc: "RegEnumKeyExW".} - proc RegEnumValue*(key: HKEY, dwIndex: DWORD, lpValueName: LPWSTR, - lpcbValueName: LPDWORD, lpReserved: LPDWORD, - lpType: LPDWORD, lpData: LPBYTE, lpcbData: LPDWORD): LONG{. - stdcall, dynlib: "advapi32", importc: "RegEnumValueW".} - proc RegLoadKey*(key: HKEY, lpSubKey: LPCWSTR, lpFile: LPCWSTR): LONG{. - stdcall, dynlib: "advapi32", importc: "RegLoadKeyW".} - proc RegOpenKey*(key: HKEY, lpSubKey: LPCWSTR, phkResult: PHKEY): LONG{. - stdcall, dynlib: "advapi32", importc: "RegOpenKeyW".} - proc RegOpenKeyEx*(key: HKEY, lpSubKey: LPCWSTR, ulOptions: DWORD, - samDesired: REGSAM, phkResult: PHKEY): LONG{.stdcall, - dynlib: "advapi32", importc: "RegOpenKeyExW".} - proc RegQueryInfoKey*(key: HKEY, lpClass: LPWSTR, lpcbClass: LPDWORD, - lpReserved: LPDWORD, lpcSubKeys: LPDWORD, - lpcbMaxSubKeyLen: LPDWORD, lpcbMaxClassLen: LPDWORD, - lpcValues: LPDWORD, lpcbMaxValueNameLen: LPDWORD, - lpcbMaxValueLen: LPDWORD, - lpcbSecurityDescriptor: LPDWORD, - lpftLastWriteTime: PFILETIME): LONG{.stdcall, - dynlib: "advapi32", importc: "RegQueryInfoKeyW".} - proc CompareString*(Locale: LCID, dwCmpFlags: DWORD, lpString1: LPCWSTR, - cchCount1: int32, lpString2: LPCWSTR, cchCount2: int32): int32{. - stdcall, dynlib: "kernel32", importc: "CompareStringW".} - proc LCMapString*(Locale: LCID, dwMapFlags: DWORD, lpSrcStr: LPCWSTR, - cchSrc: int32, lpDestStr: LPWSTR, cchDest: int32): int32{. - stdcall, dynlib: "kernel32", importc: "LCMapStringW".} - proc GetLocaleInfo*(Locale: LCID, LCType: LCTYPE, lpLCData: LPWSTR, - cchData: int32): int32{.stdcall, dynlib: "kernel32", - importc: "GetLocaleInfoW".} - proc SetLocaleInfo*(Locale: LCID, LCType: LCTYPE, lpLCData: LPCWSTR): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "SetLocaleInfoW".} - proc GetTimeFormat*(Locale: LCID, dwFlags: DWORD, lpTime: LPSYSTEMTIME, - lpFormat: LPCWSTR, lpTimeStr: LPWSTR, cchTime: int32): int32{. - stdcall, dynlib: "kernel32", importc: "GetTimeFormatW".} - proc GetDateFormat*(Locale: LCID, dwFlags: DWORD, lpDate: LPSYSTEMTIME, - lpFormat: LPCWSTR, lpDateStr: LPWSTR, cchDate: int32): int32{. - stdcall, dynlib: "kernel32", importc: "GetDateFormatW".} - proc GetNumberFormat*(Locale: LCID, dwFlags: DWORD, lpValue: LPCWSTR, - lpFormat: PNUMBERFMT, lpNumberStr: LPWSTR, - cchNumber: int32): int32{.stdcall, dynlib: "kernel32", - importc: "GetNumberFormatW".} - proc GetCurrencyFormat*(Locale: LCID, dwFlags: DWORD, lpValue: LPCWSTR, - lpFormat: PCURRENCYFMT, lpCurrencyStr: LPWSTR, - cchCurrency: int32): int32{.stdcall, - dynlib: "kernel32", importc: "GetCurrencyFormatW".} - proc EnumCalendarInfo*(lpCalInfoEnumProc: CALINFO_ENUMPROC, Locale: LCID, - Calendar: CALID, CalType: CALTYPE): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "EnumCalendarInfoW".} - proc EnumTimeFormats*(lpTimeFmtEnumProc: TIMEFMT_ENUMPROC, Locale: LCID, - dwFlags: DWORD): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "EnumTimeFormatsW".} - proc EnumDateFormats*(lpDateFmtEnumProc: DATEFMT_ENUMPROC, Locale: LCID, - dwFlags: DWORD): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "EnumDateFormatsW".} - proc GetStringTypeEx*(Locale: LCID, dwInfoType: DWORD, lpSrcStr: LPCWSTR, - cchSrc: int32, lpCharType: LPWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetStringTypeExW".} - proc GetStringType*(dwInfoType: DWORD, lpSrcStr: LPCWSTR, cchSrc: int32, - lpCharType: LPWORD): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "GetStringTypeW".} - proc FoldString*(dwMapFlags: DWORD, lpSrcStr: LPCWSTR, cchSrc: int32, - lpDestStr: LPWSTR, cchDest: int32): int32{.stdcall, - dynlib: "kernel32", importc: "FoldStringW".} - proc EnumSystemLocales*(lpLocaleEnumProc: LOCALE_ENUMPROC, dwFlags: DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "EnumSystemLocalesW".} - proc EnumSystemCodePages*(lpCodePageEnumProc: CODEPAGE_ENUMPROC, - dwFlags: DWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "EnumSystemCodePagesW".} - proc PeekConsoleInput*(hConsoleInput: HANDLE, lpBuffer: PINPUTRECORD, - nLength: DWORD, lpNumberOfEventsRead: LPDWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "PeekConsoleInputW".} - proc ReadConsoleInput*(hConsoleInput: HANDLE, lpBuffer: PINPUTRECORD, - nLength: DWORD, lpNumberOfEventsRead: LPDWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "ReadConsoleInputW".} - proc WriteConsoleInput*(hConsoleInput: HANDLE, lpBuffer: PINPUTRECORD, - nLength: DWORD, lpNumberOfEventsWritten: LPDWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "WriteConsoleInputW".} - proc ReadConsoleOutput*(hConsoleOutput: HANDLE, lpBuffer: PCHAR_INFO, - dwBufferSize: COORD, dwBufferCoord: COORD, - lpReadRegion: PSMALL_RECT): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "ReadConsoleOutputW".} - proc WriteConsoleOutput*(hConsoleOutput: HANDLE, lpBuffer: PCHAR_INFO, - dwBufferSize: COORD, dwBufferCoord: COORD, - lpWriteRegion: PSMALL_RECT): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "WriteConsoleOutputW".} - proc ReadConsoleOutputCharacter*(hConsoleOutput: HANDLE, lpCharacter: LPWSTR, - nLength: DWORD, dwReadCoord: COORD, - lpNumberOfCharsRead: LPDWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "ReadConsoleOutputCharacterW".} - proc WriteConsoleOutputCharacter*(hConsoleOutput: HANDLE, - lpCharacter: LPCWSTR, nLength: DWORD, - dwWriteCoord: COORD, - lpNumberOfCharsWritten: LPDWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "WriteConsoleOutputCharacterW".} - proc FillConsoleOutputCharacter*(hConsoleOutput: HANDLE, cCharacter: WCHAR, - nLength: DWORD, dwWriteCoord: COORD, - lpNumberOfCharsWritten: LPDWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "FillConsoleOutputCharacterW".} - proc ScrollConsoleScreenBuffer*(hConsoleOutput: HANDLE, - lpScrollRectangle: PSMALL_RECT, - lpClipRectangle: PSMALL_RECT, - dwDestinationOrigin: COORD, lpFill: PCHAR_INFO): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "ScrollConsoleScreenBufferW".} - proc GetConsoleTitle*(lpConsoleTitle: LPWSTR, nSize: DWORD): DWORD{.stdcall, - dynlib: "kernel32", importc: "GetConsoleTitleW".} - proc SetConsoleTitle*(lpConsoleTitle: LPCWSTR): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "SetConsoleTitleW".} - proc ReadConsole*(hConsoleInput: HANDLE, lpBuffer: LPVOID, - nNumberOfCharsToRead: DWORD, lpNumberOfCharsRead: LPDWORD, - lpReserved: LPVOID): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "ReadConsoleW".} - proc WriteConsole*(hConsoleOutput: HANDLE, lpBuffer: pointer, - nNumberOfCharsToWrite: DWORD, - lpNumberOfCharsWritten: LPDWORD, lpReserved: LPVOID): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "WriteConsoleW".} - proc WNetAddConnection*(lpRemoteName: LPCWSTR, lpPassword: LPCWSTR, - lpLocalName: LPCWSTR): DWORD{.stdcall, dynlib: "mpr", - importc: "WNetAddConnectionW".} - proc WNetAddConnection2*(lpNetResource: LPNETRESOURCE, lpPassword: LPCWSTR, - lpUserName: LPCWSTR, dwFlags: DWORD): DWORD{.stdcall, - dynlib: "mpr", importc: "WNetAddConnection2W".} - proc WNetAddConnection3*(hwndOwner: HWND, lpNetResource: LPNETRESOURCE, - lpPassword: LPCWSTR, lpUserName: LPCWSTR, - dwFlags: DWORD): DWORD{.stdcall, dynlib: "mpr", - importc: "WNetAddConnection3W".} - proc WNetCancelConnection*(lpName: LPCWSTR, fForce: WINBOOL): DWORD{.stdcall, - dynlib: "mpr", importc: "WNetCancelConnectionW".} - proc WNetCancelConnection2*(lpName: LPCWSTR, dwFlags: DWORD, fForce: WINBOOL): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetCancelConnection2W".} - proc WNetGetConnection*(lpLocalName: LPCWSTR, lpRemoteName: LPWSTR, - lpnLength: LPDWORD): DWORD{.stdcall, dynlib: "mpr", - importc: "WNetGetConnectionW".} - proc WNetUseConnection*(hwndOwner: HWND, lpNetResource: LPNETRESOURCE, - lpUserID: LPCWSTR, lpPassword: LPCWSTR, - dwFlags: DWORD, lpAccessName: LPWSTR, - lpBufferSize: LPDWORD, lpResult: LPDWORD): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetUseConnectionW".} - proc WNetSetConnection*(lpName: LPCWSTR, dwProperties: DWORD, pvValues: LPVOID): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetSetConnectionW".} - proc WNetConnectionDialog1*(lpConnDlgStruct: LPCONNECTDLGSTRUCT): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetConnectionDialog1W".} - proc WNetDisconnectDialog1*(lpConnDlgStruct: LPDISCDLGSTRUCT): DWORD{.stdcall, - dynlib: "mpr", importc: "WNetDisconnectDialog1W".} - proc WNetOpenEnum*(dwScope: DWORD, dwType: DWORD, dwUsage: DWORD, - lpNetResource: LPNETRESOURCE, lphEnum: LPHANDLE): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetOpenEnumW".} - proc WNetEnumResource*(hEnum: HANDLE, lpcCount: LPDWORD, lpBuffer: LPVOID, - lpBufferSize: LPDWORD): DWORD{.stdcall, dynlib: "mpr", - importc: "WNetEnumResourceW".} - proc WNetGetUniversalName*(lpLocalPath: LPCWSTR, dwInfoLevel: DWORD, - lpBuffer: LPVOID, lpBufferSize: LPDWORD): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetGetUniversalNameW".} - proc WNetGetUser*(lpName: LPCWSTR, lpUserName: LPWSTR, lpnLength: LPDWORD): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetGetUserW".} - proc WNetGetProviderName*(dwNetType: DWORD, lpProviderName: LPWSTR, - lpBufferSize: LPDWORD): DWORD{.stdcall, - dynlib: "mpr", importc: "WNetGetProviderNameW".} - proc WNetGetNetworkInformation*(lpProvider: LPCWSTR, - lpNetInfoStruct: LPNETINFOSTRUCT): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetGetNetworkInformationW".} - proc WNetGetLastError*(lpError: LPDWORD, lpErrorBuf: LPWSTR, - nErrorBufSize: DWORD, lpNameBuf: LPWSTR, - nNameBufSize: DWORD): DWORD{.stdcall, dynlib: "mpr", - importc: "WNetGetLastErrorW".} - proc MultinetGetConnectionPerformance*(lpNetResource: LPNETRESOURCE, - lpNetConnectInfoStruct: LPNETCONNECTINFOSTRUCT): DWORD{.stdcall, - dynlib: "mpr", importc: "MultinetGetConnectionPerformanceW".} - proc ChangeServiceConfig*(hService: SC_HANDLE, dwServiceType: DWORD, - dwStartType: DWORD, dwErrorControl: DWORD, - lpBinaryPathName: LPCWSTR, - lpLoadOrderGroup: LPCWSTR, lpdwTagId: LPDWORD, - lpDependencies: LPCWSTR, - lpServiceStartName: LPCWSTR, lpPassword: LPCWSTR, - lpDisplayName: LPCWSTR): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "ChangeServiceConfigW".} - proc CreateService*(hSCManager: SC_HANDLE, lpServiceName: LPCWSTR, - lpDisplayName: LPCWSTR, dwDesiredAccess: DWORD, - dwServiceType: DWORD, dwStartType: DWORD, - dwErrorControl: DWORD, lpBinaryPathName: LPCWSTR, - lpLoadOrderGroup: LPCWSTR, lpdwTagId: LPDWORD, - lpDependencies: LPCWSTR, lpServiceStartName: LPCWSTR, - lpPassword: LPCWSTR): SC_HANDLE{.stdcall, - dynlib: "advapi32", importc: "CreateServiceW".} - proc EnumDependentServices*(hService: SC_HANDLE, dwServiceState: DWORD, - lpServices: LPENUM_SERVICE_STATUS, - cbBufSize: DWORD, pcbBytesNeeded: LPDWORD, - lpServicesReturned: LPDWORD): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "EnumDependentServicesW".} - proc EnumServicesStatus*(hSCManager: SC_HANDLE, dwServiceType: DWORD, - dwServiceState: DWORD, - lpServices: LPENUM_SERVICE_STATUS, cbBufSize: DWORD, - pcbBytesNeeded: LPDWORD, lpServicesReturned: LPDWORD, - lpResumeHandle: LPDWORD): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "EnumServicesStatusW".} - proc GetServiceKeyName*(hSCManager: SC_HANDLE, lpDisplayName: LPCWSTR, - lpServiceName: LPWSTR, lpcchBuffer: LPDWORD): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "GetServiceKeyNameW".} - proc GetServiceDisplayName*(hSCManager: SC_HANDLE, lpServiceName: LPCWSTR, - lpDisplayName: LPWSTR, lpcchBuffer: LPDWORD): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "GetServiceDisplayNameW".} - proc OpenSCManager*(lpMachineName: LPCWSTR, lpDatabaseName: LPCWSTR, - dwDesiredAccess: DWORD): SC_HANDLE{.stdcall, - dynlib: "advapi32", importc: "OpenSCManagerW".} - proc OpenService*(hSCManager: SC_HANDLE, lpServiceName: LPCWSTR, - dwDesiredAccess: DWORD): SC_HANDLE{.stdcall, - dynlib: "advapi32", importc: "OpenServiceW".} - proc QueryServiceConfig*(hService: SC_HANDLE, - lpServiceConfig: LPQUERY_SERVICE_CONFIG, - cbBufSize: DWORD, pcbBytesNeeded: LPDWORD): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "QueryServiceConfigW".} - proc QueryServiceLockStatus*(hSCManager: SC_HANDLE, - lpLockStatus: LPQUERY_SERVICE_LOCK_STATUS, - cbBufSize: DWORD, pcbBytesNeeded: LPDWORD): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "QueryServiceLockStatusW".} - proc RegisterServiceCtrlHandler*(lpServiceName: LPCWSTR, - lpHandlerProc: LPHANDLER_FUNCTION): SERVICE_STATUS_HANDLE{. - stdcall, dynlib: "advapi32", importc: "RegisterServiceCtrlHandlerW".} - proc StartServiceCtrlDispatcher*(lpServiceStartTable: LPSERVICE_TABLE_ENTRY): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "StartServiceCtrlDispatcherW".} - proc StartService*(hService: SC_HANDLE, dwNumServiceArgs: DWORD, - lpServiceArgVectors: LPCWSTR): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "StartServiceW".} - proc DragQueryFile*(para1: HDROP, para2: int, para3: LPCWSTR, para4: int): int{. - stdcall, dynlib: "shell32", importc: "DragQueryFileW".} - proc ExtractAssociatedIcon*(para1: HINST, para2: LPCWSTR, para3: LPWORD): HICON{. - stdcall, dynlib: "shell32", importc: "ExtractAssociatedIconW".} - proc ExtractIcon*(para1: HINST, para2: LPCWSTR, para3: int): HICON{.stdcall, - dynlib: "shell32", importc: "ExtractIconW".} - proc FindExecutable*(para1: LPCWSTR, para2: LPCWSTR, para3: LPCWSTR): HINST{. - stdcall, dynlib: "shell32", importc: "FindExecutableW".} - proc ShellAbout*(para1: HWND, para2: LPCWSTR, para3: LPCWSTR, para4: HICON): int32{. - stdcall, dynlib: "shell32", importc: "ShellAboutW".} - proc ShellExecute*(para1: HWND, para2: LPCWSTR, para3: LPCWSTR, - para4: LPCWSTR, para5: LPCWSTR, para6: int32): HINST{. - stdcall, dynlib: "shell32", importc: "ShellExecuteW".} - proc Shell_NotifyIcon*(dwMessage: DWORD, lpData: PNotifyIconDataA): WINBOOL{. - stdcall, dynlib: "shell32", importc: "Shell_NotifyIconW".} - proc DdeCreateStringHandle*(para1: DWORD, para2: LPCWSTR, para3: int32): HSZ{. - stdcall, dynlib: "user32", importc: "DdeCreateStringHandleW".} - proc DdeInitialize*(para1: LPDWORD, para2: PFNCALLBACK, para3: DWORD, - para4: DWORD): WINUINT{.stdcall, dynlib: "user32", - importc: "DdeInitializeW".} - proc DdeQueryString*(para1: DWORD, para2: HSZ, para3: LPCWSTR, para4: DWORD, - para5: int32): DWORD{.stdcall, dynlib: "user32", - importc: "DdeQueryStringW".} - proc LogonUser*(para1: LPWSTR, para2: LPWSTR, para3: LPWSTR, para4: DWORD, - para5: DWORD, para6: PHANDLE): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "LogonUserW".} - proc CreateProcessAsUser*(para1: HANDLE, para2: LPCWSTR, para3: LPWSTR, - para4: LPSECURITY_ATTRIBUTES, - para5: LPSECURITY_ATTRIBUTES, para6: WINBOOL, - para7: DWORD, para8: LPVOID, para9: LPCWSTR, - para10: LPSTARTUPINFO, para11: LPPROCESS_INFORMATION): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "CreateProcessAsUserW".} -else: - proc GetBinaryType*(lpApplicationName: LPCSTR, lpBinaryType: LPDWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetBinaryTypeA".} - proc GetShortPathName*(lpszLongPath: LPCSTR, lpszShortPath: LPSTR, - cchBuffer: DWORD): DWORD{.stdcall, dynlib: "kernel32", - importc: "GetShortPathNameA".} - proc GetEnvironmentStrings*(): LPSTR{.stdcall, dynlib: "kernel32", - importc: "GetEnvironmentStringsA".} - proc FreeEnvironmentStrings*(para1: LPSTR): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "FreeEnvironmentStringsA".} - proc FormatMessage*(dwFlags: DWORD, lpSource: LPCVOID, dwMessageId: DWORD, - dwLanguageId: DWORD, lpBuffer: LPSTR, nSize: DWORD, - Arguments: va_list): DWORD{.stdcall, dynlib: "kernel32", - importc: "FormatMessageA".} - proc CreateMailslot*(lpName: LPCSTR, nMaxMessageSize: DWORD, - lReadTimeout: DWORD, - lpSecurityAttributes: LPSECURITY_ATTRIBUTES): HANDLE{. - stdcall, dynlib: "kernel32", importc: "CreateMailslotA".} - proc lstrcmp*(lpString1: LPCSTR, lpString2: LPCSTR): int32{.stdcall, - dynlib: "kernel32", importc: "lstrcmpA".} - proc lstrcmpi*(lpString1: LPCSTR, lpString2: LPCSTR): int32{.stdcall, - dynlib: "kernel32", importc: "lstrcmpiA".} - proc lstrcpyn*(lpString1: LPSTR, lpString2: LPCSTR, iMaxLength: int32): LPSTR{. - stdcall, dynlib: "kernel32", importc: "lstrcpynA".} - proc lstrcpy*(lpString1: LPSTR, lpString2: LPCSTR): LPSTR{.stdcall, - dynlib: "kernel32", importc: "lstrcpyA".} - proc lstrcat*(lpString1: LPSTR, lpString2: LPCSTR): LPSTR{.stdcall, - dynlib: "kernel32", importc: "lstrcatA".} - proc lstrlen*(lpString: LPCSTR): int32{.stdcall, dynlib: "kernel32", - importc: "lstrlenA".} - proc CreateMutex*(lpMutexAttributes: LPSECURITY_ATTRIBUTES, - bInitialOwner: WINBOOL, lpName: LPCSTR): HANDLE{.stdcall, - dynlib: "kernel32", importc: "CreateMutexA".} - proc OpenMutex*(dwDesiredAccess: DWORD, bInheritHandle: WINBOOL, - lpName: LPCSTR): HANDLE{.stdcall, dynlib: "kernel32", - importc: "OpenMutexA".} - proc CreateEvent*(lpEventAttributes: LPSECURITY_ATTRIBUTES, - bManualReset: WINBOOL, bInitialState: WINBOOL, - lpName: LPCSTR): HANDLE{.stdcall, dynlib: "kernel32", - importc: "CreateEventA".} - proc OpenEvent*(dwDesiredAccess: DWORD, bInheritHandle: WINBOOL, - lpName: LPCSTR): HANDLE{.stdcall, dynlib: "kernel32", - importc: "OpenEventA".} - proc CreateSemaphore*(lpSemaphoreAttributes: LPSECURITY_ATTRIBUTES, - lInitialCount: LONG, lMaximumCount: LONG, lpName: LPCSTR): HANDLE{. - stdcall, dynlib: "kernel32", importc: "CreateSemaphoreA".} - proc OpenSemaphore*(dwDesiredAccess: DWORD, bInheritHandle: WINBOOL, - lpName: LPCSTR): HANDLE{.stdcall, dynlib: "kernel32", - importc: "OpenSemaphoreA".} - proc CreateFileMapping*(hFile: HANDLE, - lpFileMappingAttributes: LPSECURITY_ATTRIBUTES, - flProtect: DWORD, dwMaximumSizeHigh: DWORD, - dwMaximumSizeLow: DWORD, lpName: LPCSTR): HANDLE{. - stdcall, dynlib: "kernel32", importc: "CreateFileMappingA".} - proc OpenFileMapping*(dwDesiredAccess: DWORD, bInheritHandle: WINBOOL, - lpName: LPCSTR): HANDLE{.stdcall, dynlib: "kernel32", - importc: "OpenFileMappingA".} - proc GetLogicalDriveStrings*(nBufferLength: DWORD, lpBuffer: LPSTR): DWORD{. - stdcall, dynlib: "kernel32", importc: "GetLogicalDriveStringsA".} - proc LoadLibrary*(lpLibFileName: LPCSTR): HINST{.stdcall, dynlib: "kernel32", - importc: "LoadLibraryA".} - proc LoadLibraryEx*(lpLibFileName: LPCSTR, hFile: HANDLE, dwFlags: DWORD): HINST{. - stdcall, dynlib: "kernel32", importc: "LoadLibraryExA".} - proc GetModuleFileName*(hModule: HINST, lpFilename: LPSTR, nSize: DWORD): DWORD{. - stdcall, dynlib: "kernel32", importc: "GetModuleFileNameA".} - proc GetModuleHandle*(lpModuleName: LPCSTR): HMODULE{.stdcall, - dynlib: "kernel32", importc: "GetModuleHandleA".} - proc FatalAppExit*(uAction: WINUINT, lpMessageText: LPCSTR){.stdcall, - dynlib: "kernel32", importc: "FatalAppExitA".} - proc GetCommandLine*(): LPSTR{.stdcall, dynlib: "kernel32", - importc: "GetCommandLineA".} - proc GetEnvironmentVariable*(lpName: LPCSTR, lpBuffer: LPSTR, nSize: DWORD): DWORD{. - stdcall, dynlib: "kernel32", importc: "GetEnvironmentVariableA".} - proc SetEnvironmentVariable*(lpName: LPCSTR, lpValue: LPCSTR): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "SetEnvironmentVariableA".} - proc ExpandEnvironmentStrings*(lpSrc: LPCSTR, lpDst: LPSTR, nSize: DWORD): DWORD{. - stdcall, dynlib: "kernel32", importc: "ExpandEnvironmentStringsA".} - proc OutputDebugString*(lpOutputString: LPCSTR){.stdcall, dynlib: "kernel32", - importc: "OutputDebugStringA".} - proc FindResource*(hModule: HINST, lpName: LPCSTR, lpType: LPCSTR): HRSRC{. - stdcall, dynlib: "kernel32", importc: "FindResourceA".} - proc FindResourceEx*(hModule: HINST, lpType: LPCSTR, lpName: LPCSTR, - wLanguage: int16): HRSRC{.stdcall, dynlib: "kernel32", - importc: "FindResourceExA".} - proc EnumResourceTypes*(hModule: HINST, lpEnumFunc: ENUMRESTYPEPROC, - lParam: LONG): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "EnumResourceTypesA".} - proc EnumResourceNames*(hModule: HINST, lpType: LPCSTR, - lpEnumFunc: ENUMRESNAMEPROC, lParam: LONG): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "EnumResourceNamesA".} - proc EnumResourceLanguages*(hModule: HINST, lpType: LPCSTR, lpName: LPCSTR, - lpEnumFunc: ENUMRESLANGPROC, lParam: LONG): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "EnumResourceLanguagesA".} - proc BeginUpdateResource*(pFileName: LPCSTR, bDeleteExistingResources: WINBOOL): HANDLE{. - stdcall, dynlib: "kernel32", importc: "BeginUpdateResourceA".} - proc UpdateResource*(hUpdate: HANDLE, lpType: LPCSTR, lpName: LPCSTR, - wLanguage: int16, lpData: LPVOID, cbData: DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "UpdateResourceA".} - proc EndUpdateResource*(hUpdate: HANDLE, fDiscard: WINBOOL): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "EndUpdateResourceA".} - proc GlobalAddAtom*(lpString: LPCSTR): ATOM{.stdcall, dynlib: "kernel32", - importc: "GlobalAddAtomA".} - proc GlobalFindAtom*(lpString: LPCSTR): ATOM{.stdcall, dynlib: "kernel32", - importc: "GlobalFindAtomA".} - proc GlobalGetAtomName*(nAtom: ATOM, lpBuffer: LPSTR, nSize: int32): WINUINT{. - stdcall, dynlib: "kernel32", importc: "GlobalGetAtomNameA".} - proc AddAtom*(lpString: LPCSTR): ATOM{.stdcall, dynlib: "kernel32", - importc: "AddAtomA".} - proc FindAtom*(lpString: LPCSTR): ATOM{.stdcall, dynlib: "kernel32", - importc: "FindAtomA".} - proc GetAtomName*(nAtom: ATOM, lpBuffer: LPSTR, nSize: int32): WINUINT{.stdcall, - dynlib: "kernel32", importc: "GetAtomNameA".} - proc GetProfileInt*(lpAppName: LPCSTR, lpKeyName: LPCSTR, nDefault: WINT): WINUINT{. - stdcall, dynlib: "kernel32", importc: "GetProfileIntA".} - proc GetProfileString*(lpAppName: LPCSTR, lpKeyName: LPCSTR, - lpDefault: LPCSTR, lpReturnedString: LPSTR, - nSize: DWORD): DWORD{.stdcall, dynlib: "kernel32", - importc: "GetProfileStringA".} - proc WriteProfileString*(lpAppName: LPCSTR, lpKeyName: LPCSTR, - lpString: LPCSTR): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "WriteProfileStringA".} - proc GetProfileSection*(lpAppName: LPCSTR, lpReturnedString: LPSTR, - nSize: DWORD): DWORD{.stdcall, dynlib: "kernel32", - importc: "GetProfileSectionA".} - proc WriteProfileSection*(lpAppName: LPCSTR, lpString: LPCSTR): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "WriteProfileSectionA".} - proc GetPrivateProfileInt*(lpAppName: LPCSTR, lpKeyName: LPCSTR, - nDefault: WINT, lpFileName: LPCSTR): WINUINT{.stdcall, - dynlib: "kernel32", importc: "GetPrivateProfileIntA".} - proc GetPrivateProfileString*(lpAppName: LPCSTR, lpKeyName: LPCSTR, - lpDefault: LPCSTR, lpReturnedString: LPSTR, - nSize: DWORD, lpFileName: LPCSTR): DWORD{. - stdcall, dynlib: "kernel32", importc: "GetPrivateProfileStringA".} - proc WritePrivateProfileString*(lpAppName: LPCSTR, lpKeyName: LPCSTR, - lpString: LPCSTR, lpFileName: LPCSTR): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "WritePrivateProfileStringA".} - proc GetPrivateProfileSection*(lpAppName: LPCSTR, lpReturnedString: LPSTR, - nSize: DWORD, lpFileName: LPCSTR): DWORD{. - stdcall, dynlib: "kernel32", importc: "GetPrivateProfileSectionA".} - proc WritePrivateProfileSection*(lpAppName: LPCSTR, lpString: LPCSTR, - lpFileName: LPCSTR): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "WritePrivateProfileSectionA".} - proc GetDriveType*(lpRootPathName: LPCSTR): WINUINT{.stdcall, dynlib: "kernel32", - importc: "GetDriveTypeA".} - proc GetSystemDirectory*(lpBuffer: LPSTR, uSize: WINUINT): WINUINT{.stdcall, - dynlib: "kernel32", importc: "GetSystemDirectoryA".} - proc GetTempPath*(nBufferLength: DWORD, lpBuffer: LPSTR): DWORD{.stdcall, - dynlib: "kernel32", importc: "GetTempPathA".} - proc GetTempFileName*(lpPathName: LPCSTR, lpPrefixString: LPCSTR, - uUnique: WINUINT, lpTempFileName: LPSTR): WINUINT{.stdcall, - dynlib: "kernel32", importc: "GetTempFileNameA".} - proc GetWindowsDirectory*(lpBuffer: LPSTR, uSize: WINUINT): WINUINT{.stdcall, - dynlib: "kernel32", importc: "GetWindowsDirectoryA".} - proc SetCurrentDirectory*(lpPathName: LPCSTR): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "SetCurrentDirectoryA".} - proc GetCurrentDirectory*(nBufferLength: DWORD, lpBuffer: LPSTR): DWORD{. - stdcall, dynlib: "kernel32", importc: "GetCurrentDirectoryA".} - proc GetDiskFreeSpace*(lpRootPathName: LPCSTR, lpSectorsPerCluster: LPDWORD, - lpBytesPerSector: LPDWORD, - lpNumberOfFreeClusters: LPDWORD, - lpTotalNumberOfClusters: LPDWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetDiskFreeSpaceA".} - proc CreateDirectory*(lpPathName: LPCSTR, - lpSecurityAttributes: LPSECURITY_ATTRIBUTES): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "CreateDirectoryA".} - proc CreateDirectoryEx*(lpTemplateDirectory: LPCSTR, lpNewDirectory: LPCSTR, - lpSecurityAttributes: LPSECURITY_ATTRIBUTES): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "CreateDirectoryExA".} - proc RemoveDirectory*(lpPathName: LPCSTR): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "RemoveDirectoryA".} - proc GetFullPathName*(lpFileName: LPCSTR, nBufferLength: DWORD, - lpBuffer: LPSTR, lpFilePart: var LPSTR): DWORD{.stdcall, - dynlib: "kernel32", importc: "GetFullPathNameA".} - proc DefineDosDevice*(dwFlags: DWORD, lpDeviceName: LPCSTR, - lpTargetPath: LPCSTR): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "DefineDosDeviceA".} - proc QueryDosDevice*(lpDeviceName: LPCSTR, lpTargetPath: LPSTR, ucchMax: DWORD): DWORD{. - stdcall, dynlib: "kernel32", importc: "QueryDosDeviceA".} - proc CreateFile*(lpFileName: LPCSTR, dwDesiredAccess: DWORD, - dwShareMode: DWORD, - lpSecurityAttributes: LPSECURITY_ATTRIBUTES, - dwCreationDisposition: DWORD, dwFlagsAndAttributes: DWORD, - hTemplateFile: HANDLE): HANDLE{.stdcall, dynlib: "kernel32", - importc: "CreateFileA".} - proc SetFileAttributes*(lpFileName: LPCSTR, dwFileAttributes: DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "SetFileAttributesA".} - proc GetFileAttributes*(lpFileName: LPCSTR): DWORD{.stdcall, - dynlib: "kernel32", importc: "GetFileAttributesA".} - proc GetCompressedFileSize*(lpFileName: LPCSTR, lpFileSizeHigh: LPDWORD): DWORD{. - stdcall, dynlib: "kernel32", importc: "GetCompressedFileSizeA".} - proc DeleteFile*(lpFileName: LPCSTR): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "DeleteFileA".} - proc SearchPath*(lpPath: LPCSTR, lpFileName: LPCSTR, lpExtension: LPCSTR, - nBufferLength: DWORD, lpBuffer: LPSTR, lpFilePart: LPSTR): DWORD{. - stdcall, dynlib: "kernel32", importc: "SearchPathA".} - proc CopyFile*(lpExistingFileName: LPCSTR, lpNewFileName: LPCSTR, - bFailIfExists: WINBOOL): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "CopyFileA".} - proc MoveFile*(lpExistingFileName: LPCSTR, lpNewFileName: LPCSTR): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "MoveFileA".} - proc MoveFileEx*(lpExistingFileName: LPCSTR, lpNewFileName: LPCSTR, - dwFlags: DWORD): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "MoveFileExA".} - proc CreateNamedPipe*(lpName: LPCSTR, dwOpenMode: DWORD, dwPipeMode: DWORD, - nMaxInstances: DWORD, nOutBufferSize: DWORD, - nInBufferSize: DWORD, nDefaultTimeOut: DWORD, - lpSecurityAttributes: LPSECURITY_ATTRIBUTES): HANDLE{. - stdcall, dynlib: "kernel32", importc: "CreateNamedPipeA".} - proc GetNamedPipeHandleState*(hNamedPipe: HANDLE, lpState: LPDWORD, - lpCurInstances: LPDWORD, - lpMaxCollectionCount: LPDWORD, - lpCollectDataTimeout: LPDWORD, - lpUserName: LPSTR, nMaxUserNameSize: DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetNamedPipeHandleStateA".} - proc CallNamedPipe*(lpNamedPipeName: LPCSTR, lpInBuffer: LPVOID, - nInBufferSize: DWORD, lpOutBuffer: LPVOID, - nOutBufferSize: DWORD, lpBytesRead: LPDWORD, - nTimeOut: DWORD): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "CallNamedPipeA".} - proc WaitNamedPipe*(lpNamedPipeName: LPCSTR, nTimeOut: DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "WaitNamedPipeA".} - proc SetVolumeLabel*(lpRootPathName: LPCSTR, lpVolumeName: LPCSTR): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "SetVolumeLabelA".} - proc GetVolumeInformation*(lpRootPathName: LPCSTR, lpVolumeNameBuffer: LPSTR, - nVolumeNameSize: DWORD, - lpVolumeSerialNumber: LPDWORD, - lpMaximumComponentLength: LPDWORD, - lpFileSystemFlags: LPDWORD, - lpFileSystemNameBuffer: LPSTR, - nFileSystemNameSize: DWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetVolumeInformationA".} - proc ClearEventLog*(hEventLog: HANDLE, lpBackupFileName: LPCSTR): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "ClearEventLogA".} - proc BackupEventLog*(hEventLog: HANDLE, lpBackupFileName: LPCSTR): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "BackupEventLogA".} - proc OpenEventLog*(lpUNCServerName: LPCSTR, lpSourceName: LPCSTR): HANDLE{. - stdcall, dynlib: "advapi32", importc: "OpenEventLogA".} - proc RegisterEventSource*(lpUNCServerName: LPCSTR, lpSourceName: LPCSTR): HANDLE{. - stdcall, dynlib: "advapi32", importc: "RegisterEventSourceA".} - proc OpenBackupEventLog*(lpUNCServerName: LPCSTR, lpFileName: LPCSTR): HANDLE{. - stdcall, dynlib: "advapi32", importc: "OpenBackupEventLogA".} - proc ReadEventLog*(hEventLog: HANDLE, dwReadFlags: DWORD, - dwRecordOffset: DWORD, lpBuffer: LPVOID, - nNumberOfBytesToRead: DWORD, pnBytesRead: LPDWORD, - pnMinNumberOfBytesNeeded: LPDWORD): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "ReadEventLogA".} - proc ReportEvent*(hEventLog: HANDLE, wType: int16, wCategory: int16, - dwEventID: DWORD, lpUserSid: PSID, wNumStrings: int16, - dwDataSize: DWORD, lpStrings: LPPCSTR, lpRawData: LPVOID): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "ReportEventA".} - proc AccessCheckAndAuditAlarm*(SubsystemName: LPCSTR, HandleId: LPVOID, - ObjectTypeName: LPSTR, ObjectName: LPSTR, - SecurityDescriptor: PSECURITY_DESCRIPTOR, - DesiredAccess: DWORD, - GenericMapping: PGENERIC_MAPPING, - ObjectCreation: WINBOOL, - GrantedAccess: LPDWORD, AccessStatus: LPBOOL, - pfGenerateOnClose: LPBOOL): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "AccessCheckAndAuditAlarmA".} - proc ObjectOpenAuditAlarm*(SubsystemName: LPCSTR, HandleId: LPVOID, - ObjectTypeName: LPSTR, ObjectName: LPSTR, - pSecurityDescriptor: PSECURITY_DESCRIPTOR, - ClientToken: HANDLE, DesiredAccess: DWORD, - GrantedAccess: DWORD, Privileges: PPRIVILEGE_SET, - ObjectCreation: WINBOOL, AccessGranted: WINBOOL, - GenerateOnClose: LPBOOL): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "ObjectOpenAuditAlarmA".} - proc ObjectPrivilegeAuditAlarm*(SubsystemName: LPCSTR, HandleId: LPVOID, - ClientToken: HANDLE, DesiredAccess: DWORD, - Privileges: PPRIVILEGE_SET, - AccessGranted: WINBOOL): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "ObjectPrivilegeAuditAlarmA".} - proc ObjectCloseAuditAlarm*(SubsystemName: LPCSTR, HandleId: LPVOID, - GenerateOnClose: WINBOOL): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "ObjectCloseAuditAlarmA".} - proc PrivilegedServiceAuditAlarm*(SubsystemName: LPCSTR, ServiceName: LPCSTR, - ClientToken: HANDLE, - Privileges: PPRIVILEGE_SET, - AccessGranted: WINBOOL): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "PrivilegedServiceAuditAlarmA".} - proc SetFileSecurity*(lpFileName: LPCSTR, - SecurityInformation: SECURITY_INFORMATION, - pSecurityDescriptor: PSECURITY_DESCRIPTOR): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "SetFileSecurityA".} - proc GetFileSecurity*(lpFileName: LPCSTR, - RequestedInformation: SECURITY_INFORMATION, - pSecurityDescriptor: PSECURITY_DESCRIPTOR, - nLength: DWORD, lpnLengthNeeded: LPDWORD): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "GetFileSecurityA".} - proc FindFirstChangeNotification*(lpPathName: LPCSTR, bWatchSubtree: WINBOOL, - dwNotifyFilter: DWORD): HANDLE{.stdcall, - dynlib: "kernel32", importc: "FindFirstChangeNotificationA".} - proc IsBadStringPtr*(lpsz: LPCSTR, ucchMax: WINUINT): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "IsBadStringPtrA".} - proc LookupAccountSid*(lpSystemName: LPCSTR, Sid: PSID, Name: LPSTR, - cbName: LPDWORD, ReferencedDomainName: LPSTR, - cbReferencedDomainName: LPDWORD, peUse: PSID_NAME_USE): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "LookupAccountSidA".} - proc LookupAccountName*(lpSystemName: LPCSTR, lpAccountName: LPCSTR, - Sid: PSID, cbSid: LPDWORD, - ReferencedDomainName: LPSTR, - cbReferencedDomainName: LPDWORD, peUse: PSID_NAME_USE): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "LookupAccountNameA".} - proc LookupPrivilegeValue*(lpSystemName: LPCSTR, lpName: LPCSTR, lpLuid: PLUID): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "LookupPrivilegeValueA".} - proc LookupPrivilegeName*(lpSystemName: LPCSTR, lpLuid: PLUID, lpName: LPSTR, - cbName: LPDWORD): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "LookupPrivilegeNameA".} - proc LookupPrivilegeDisplayName*(lpSystemName: LPCSTR, lpName: LPCSTR, - lpDisplayName: LPSTR, cbDisplayName: LPDWORD, - lpLanguageId: LPDWORD): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "LookupPrivilegeDisplayNameA".} - proc BuildCommDCB*(lpDef: LPCSTR, lpDCB: LPDCB): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "BuildCommDCBA".} - proc BuildCommDCBAndTimeouts*(lpDef: LPCSTR, lpDCB: LPDCB, - lpCommTimeouts: LPCOMMTIMEOUTS): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "BuildCommDCBAndTimeoutsA".} - proc CommConfigDialog*(lpszName: LPCSTR, wnd: HWND, lpCC: LPCOMMCONFIG): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "CommConfigDialogA".} - proc GetDefaultCommConfig*(lpszName: LPCSTR, lpCC: LPCOMMCONFIG, - lpdwSize: LPDWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetDefaultCommConfigA".} - proc SetDefaultCommConfig*(lpszName: LPCSTR, lpCC: LPCOMMCONFIG, dwSize: DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "SetDefaultCommConfigA".} - proc GetComputerName*(lpBuffer: LPSTR, nSize: LPDWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetComputerNameA".} - proc SetComputerName*(lpComputerName: LPCSTR): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "SetComputerNameA".} - proc GetUserName*(lpBuffer: LPSTR, nSize: LPDWORD): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "GetUserNameA".} - proc wvsprintf*(para1: LPSTR, para2: LPCSTR, arglist: va_list): int32{. - stdcall, dynlib: "user32", importc: "wvsprintfA".} - proc LoadKeyboardLayout*(pwszKLID: LPCSTR, Flags: WINUINT): HKL{.stdcall, - dynlib: "user32", importc: "LoadKeyboardLayoutA".} - proc GetKeyboardLayoutName*(pwszKLID: LPSTR): WINBOOL{.stdcall, - dynlib: "user32", importc: "GetKeyboardLayoutNameA".} - proc CreateDesktop*(lpszDesktop: LPSTR, lpszDevice: LPSTR, - pDevmode: LPDEVMODE, dwFlags: DWORD, - dwDesiredAccess: DWORD, lpsa: LPSECURITY_ATTRIBUTES): HDESK{. - stdcall, dynlib: "user32", importc: "CreateDesktopA".} - proc OpenDesktop*(lpszDesktop: LPSTR, dwFlags: DWORD, fInherit: WINBOOL, - dwDesiredAccess: DWORD): HDESK{.stdcall, dynlib: "user32", - importc: "OpenDesktopA".} - proc EnumDesktops*(hwinsta: HWINSTA, lpEnumFunc: DESKTOPENUMPROC, - lp: LPARAM): WINBOOL{.stdcall, dynlib: "user32", - importc: "EnumDesktopsA".} - proc CreateWindowStation*(lpwinsta: LPSTR, dwReserved: DWORD, - dwDesiredAccess: DWORD, lpsa: LPSECURITY_ATTRIBUTES): HWINSTA{. - stdcall, dynlib: "user32", importc: "CreateWindowStationA".} - proc OpenWindowStation*(lpszWinSta: LPSTR, fInherit: WINBOOL, - dwDesiredAccess: DWORD): HWINSTA{.stdcall, - dynlib: "user32", importc: "OpenWindowStationA".} - proc EnumWindowStations*(lpEnumFunc: ENUMWINDOWSTATIONPROC, lp: LPARAM): WINBOOL{. - stdcall, dynlib: "user32", importc: "EnumWindowStationsA".} - proc GetUserObjectInformation*(hObj: HANDLE, nIndex: int32, pvInfo: PVOID, - nLength: DWORD, lpnLengthNeeded: LPDWORD): WINBOOL{. - stdcall, dynlib: "user32", importc: "GetUserObjectInformationA".} - proc SetUserObjectInformation*(hObj: HANDLE, nIndex: int32, pvInfo: PVOID, - nLength: DWORD): WINBOOL{.stdcall, - dynlib: "user32", importc: "SetUserObjectInformationA".} - proc RegisterWindowMessage*(lpString: LPCSTR): WINUINT{.stdcall, - dynlib: "user32", importc: "RegisterWindowMessageA".} - proc GetMessage*(lpMsg: LPMSG, wnd: HWND, wMsgFilterMin: WINUINT, - wMsgFilterMax: WINUINT): WINBOOL{.stdcall, dynlib: "user32", - importc: "GetMessageA".} - proc DispatchMessage*(lpMsg: LPMSG): LONG{.stdcall, dynlib: "user32", - importc: "DispatchMessageA".} - proc PeekMessage*(lpMsg: LPMSG, wnd: HWND, wMsgFilterMin: WINUINT, - wMsgFilterMax: WINUINT, wRemoveMsg: WINUINT): WINBOOL{.stdcall, - dynlib: "user32", importc: "PeekMessageA".} - proc SendMessage*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): LRESULT{. - stdcall, dynlib: "user32", importc: "SendMessageA".} - proc SendMessageTimeout*(wnd: HWND, Msg: WINUINT, wp: WPARAM, - lp: LPARAM, fuFlags: WINUINT, uTimeout: WINUINT, - lpdwResult: LPDWORD): LRESULT{.stdcall, - dynlib: "user32", importc: "SendMessageTimeoutA".} - proc SendNotifyMessage*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): WINBOOL{. - stdcall, dynlib: "user32", importc: "SendNotifyMessageA".} - proc SendMessageCallback*(wnd: HWND, Msg: WINUINT, wp: WPARAM, - lp: LPARAM, lpResultCallBack: SENDASYNCPROC, - dwData: DWORD): WINBOOL{.stdcall, dynlib: "user32", - importc: "SendMessageCallbackA".} - proc PostMessage*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): WINBOOL{. - stdcall, dynlib: "user32", importc: "PostMessageA".} - proc PostThreadMessage*(idThread: DWORD, Msg: WINUINT, wp: WPARAM, - lp: LPARAM): WINBOOL{.stdcall, dynlib: "user32", - importc: "PostThreadMessageA".} - proc DefWindowProc*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): LRESULT{. - stdcall, dynlib: "user32", importc: "DefWindowProcA".} - proc CallWindowProc*(lpPrevWndFunc: WNDPROC, wnd: HWND, Msg: WINUINT, - wp: WPARAM, lp: LPARAM): LRESULT{.stdcall, - dynlib: "user32", importc: "CallWindowProcA".} - proc RegisterClass*(lpWndClass: LPWNDCLASS): ATOM{.stdcall, dynlib: "user32", - importc: "RegisterClassA".} - proc UnregisterClass*(lpClassName: LPCSTR, hInstance: HINST): WINBOOL{. - stdcall, dynlib: "user32", importc: "UnregisterClassA".} - proc GetClassInfo*(hInstance: HINST, lpClassName: LPCSTR, - lpWndClass: LPWNDCLASS): WINBOOL{.stdcall, - dynlib: "user32", importc: "GetClassInfoA".} - proc RegisterClassEx*(para1: LPWNDCLASSEX): ATOM{.stdcall, dynlib: "user32", - importc: "RegisterClassExA".} - proc GetClassInfoEx*(para1: HINST, para2: LPCSTR, para3: LPWNDCLASSEX): WINBOOL{. - stdcall, dynlib: "user32", importc: "GetClassInfoExA".} - proc CreateWindowEx*(dwExStyle: DWORD, lpClassName: LPCSTR, - lpWindowName: LPCSTR, dwStyle: DWORD, X: int32, Y: int32, - nWidth: int32, nHeight: int32, hWndParent: HWND, - menu: HMENU, hInstance: HINST, lpParam: LPVOID): HWND{. - stdcall, dynlib: "user32", importc: "CreateWindowExA".} - proc CreateDialogParam*(hInstance: HINST, lpTemplateName: LPCSTR, - hWndParent: HWND, lpDialogFunc: DLGPROC, - dwInitParam: LPARAM): HWND{.stdcall, dynlib: "user32", - importc: "CreateDialogParamA".} - proc CreateDialogIndirectParam*(hInstance: HINST, lpTemplate: LPCDLGTEMPLATE, - - hWndParent: HWND, lpDialogFunc: DLGPROC, - dwInitParam: LPARAM): HWND{.stdcall, - dynlib: "user32", importc: "CreateDialogIndirectParamA".} - proc DialogBoxParam*(hInstance: HINST, lpTemplateName: LPCSTR, - hWndParent: HWND, lpDialogFunc: DLGPROC, - dwInitParam: LPARAM): int32{.stdcall, dynlib: "user32", - importc: "DialogBoxParamA".} - proc DialogBoxIndirectParam*(hInstance: HINST, - hDialogTemplate: LPCDLGTEMPLATE, - hWndParent: HWND, lpDialogFunc: DLGPROC, - dwInitParam: LPARAM): int32{.stdcall, - dynlib: "user32", importc: "DialogBoxIndirectParamA".} - proc SetDlgItemText*(hDlg: HWND, nIDDlgItem: int32, lpString: LPCSTR): WINBOOL{. - stdcall, dynlib: "user32", importc: "SetDlgItemTextA".} - proc GetDlgItemText*(hDlg: HWND, nIDDlgItem: int32, lpString: LPSTR, - nMaxCount: int32): WINUINT{.stdcall, dynlib: "user32", - importc: "GetDlgItemTextA".} - proc SendDlgItemMessage*(hDlg: HWND, nIDDlgItem: int32, Msg: WINUINT, - wp: WPARAM, lp: LPARAM): LONG{.stdcall, - dynlib: "user32", importc: "SendDlgItemMessageA".} - proc DefDlgProc*(hDlg: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): LRESULT{. - stdcall, dynlib: "user32", importc: "DefDlgProcA".} - proc CallMsgFilter*(lpMsg: LPMSG, nCode: int32): WINBOOL{.stdcall, - dynlib: "user32", importc: "CallMsgFilterA".} - proc RegisterClipboardFormat*(lpszFormat: LPCSTR): WINUINT{.stdcall, - dynlib: "user32", importc: "RegisterClipboardFormatA".} - proc GetClipboardFormatName*(format: WINUINT, lpszFormatName: LPSTR, - cchMaxCount: int32): int32{.stdcall, - dynlib: "user32", importc: "GetClipboardFormatNameA".} - proc CharToOem*(lpszSrc: LPCSTR, lpszDst: LPSTR): WINBOOL{.stdcall, - dynlib: "user32", importc: "CharToOemA".} - proc OemToChar*(lpszSrc: LPCSTR, lpszDst: LPSTR): WINBOOL{.stdcall, - dynlib: "user32", importc: "OemToCharA".} - proc CharToOemBuff*(lpszSrc: LPCSTR, lpszDst: LPSTR, cchDstLength: DWORD): WINBOOL{. - stdcall, dynlib: "user32", importc: "CharToOemBuffA".} - proc OemToCharBuff*(lpszSrc: LPCSTR, lpszDst: LPSTR, cchDstLength: DWORD): WINBOOL{. - stdcall, dynlib: "user32", importc: "OemToCharBuffA".} - proc CharUpper*(lpsz: LPSTR): LPSTR{.stdcall, dynlib: "user32", - importc: "CharUpperA".} - proc CharUpperBuff*(lpsz: LPSTR, cchLength: DWORD): DWORD{.stdcall, - dynlib: "user32", importc: "CharUpperBuffA".} - proc CharLower*(lpsz: LPSTR): LPSTR{.stdcall, dynlib: "user32", - importc: "CharLowerA".} - proc CharLowerBuff*(lpsz: LPSTR, cchLength: DWORD): DWORD{.stdcall, - dynlib: "user32", importc: "CharLowerBuffA".} - proc CharNext*(lpsz: LPCSTR): LPSTR{.stdcall, dynlib: "user32", - importc: "CharNextA".} - proc CharPrev*(lpszStart: LPCSTR, lpszCurrent: LPCSTR): LPSTR{.stdcall, - dynlib: "user32", importc: "CharPrevA".} - proc IsCharAlpha*(ch: char): WINBOOL{.stdcall, dynlib: "user32", - importc: "IsCharAlphaA".} - proc IsCharAlphaNumeric*(ch: char): WINBOOL{.stdcall, dynlib: "user32", - importc: "IsCharAlphaNumericA".} - proc IsCharUpper*(ch: char): WINBOOL{.stdcall, dynlib: "user32", - importc: "IsCharUpperA".} - proc IsCharLower*(ch: char): WINBOOL{.stdcall, dynlib: "user32", - importc: "IsCharLowerA".} - proc GetKeyNameText*(lParam: LONG, lpString: LPSTR, nSize: int32): int32{. - stdcall, dynlib: "user32", importc: "GetKeyNameTextA".} - proc VkKeyScan*(ch: char): SHORT{.stdcall, dynlib: "user32", - importc: "VkKeyScanA".} - proc VkKeyScanEx*(ch: char, dwhkl: HKL): SHORT{.stdcall, dynlib: "user32", - importc: "VkKeyScanExA".} - proc MapVirtualKey*(uCode: WINUINT, uMapType: WINUINT): WINUINT{.stdcall, - dynlib: "user32", importc: "MapVirtualKeyA".} - proc MapVirtualKeyEx*(uCode: WINUINT, uMapType: WINUINT, dwhkl: HKL): WINUINT{.stdcall, - dynlib: "user32", importc: "MapVirtualKeyExA".} - proc LoadAccelerators*(hInstance: HINST, lpTableName: LPCSTR): HACCEL{. - stdcall, dynlib: "user32", importc: "LoadAcceleratorsA".} - proc CreateAcceleratorTable*(para1: LPACCEL, para2: int32): HACCEL{.stdcall, - dynlib: "user32", importc: "CreateAcceleratorTableA".} - proc CopyAcceleratorTable*(hAccelSrc: HACCEL, lpAccelDst: LPACCEL, - cAccelEntries: int32): int32{.stdcall, - dynlib: "user32", importc: "CopyAcceleratorTableA".} - proc TranslateAccelerator*(wnd: HWND, hAccTable: HACCEL, lpMsg: LPMSG): int32{. - stdcall, dynlib: "user32", importc: "TranslateAcceleratorA".} - proc LoadMenu*(hInstance: HINST, lpMenuName: LPCSTR): HMENU{.stdcall, - dynlib: "user32", importc: "LoadMenuA".} - proc LoadMenuIndirect*(lpMenuTemplate: LPMENUTEMPLATE): HMENU{.stdcall, - dynlib: "user32", importc: "LoadMenuIndirectA".} - proc ChangeMenu*(menu: HMENU, cmd: WINUINT, lpszNewItem: LPCSTR, - cmdInsert: WINUINT, flags: WINUINT): WINBOOL{.stdcall, - dynlib: "user32", importc: "ChangeMenuA".} - proc GetMenuString*(menu: HMENU, uIDItem: WINUINT, lpString: LPSTR, - nMaxCount: int32, uFlag: WINUINT): int32{.stdcall, - dynlib: "user32", importc: "GetMenuStringA".} - proc InsertMenu*(menu: HMENU, uPosition: WINUINT, uFlags: WINUINT, - uIDNewItem: WINUINT, lpNewItem: LPCSTR): WINBOOL{.stdcall, - dynlib: "user32", importc: "InsertMenuA".} - proc AppendMenu*(menu: HMENU, uFlags: WINUINT, uIDNewItem: WINUINT, - lpNewItem: LPCSTR): WINBOOL{.stdcall, dynlib: "user32", - importc: "AppendMenuA".} - proc ModifyMenu*(hMnu: HMENU, uPosition: WINUINT, uFlags: WINUINT, uIDNewItem: WINUINT, - lpNewItem: LPCSTR): WINBOOL{.stdcall, dynlib: "user32", - importc: "ModifyMenuA".} - proc InsertMenuItem*(para1: HMENU, para2: WINUINT, para3: WINBOOL, - para4: LPCMENUITEMINFO): WINBOOL{.stdcall, - dynlib: "user32", importc: "InsertMenuItemA".} - proc GetMenuItemInfo*(para1: HMENU, para2: WINUINT, para3: WINBOOL, - para4: LPMENUITEMINFO): WINBOOL{.stdcall, - dynlib: "user32", importc: "GetMenuItemInfoA".} - proc SetMenuItemInfo*(para1: HMENU, para2: WINUINT, para3: WINBOOL, - para4: LPCMENUITEMINFO): WINBOOL{.stdcall, - dynlib: "user32", importc: "SetMenuItemInfoA".} - proc DrawText*(hDC: HDC, lpString: LPCSTR, nCount: int32, lpRect: LPRECT, - uFormat: WINUINT): int32{.stdcall, dynlib: "user32", - importc: "DrawTextA".} - proc DrawTextEx*(para1: HDC, para2: LPSTR, para3: int32, para4: LPRECT, - para5: WINUINT, para6: LPDRAWTEXTPARAMS): int32{.stdcall, - dynlib: "user32", importc: "DrawTextExA".} - proc GrayString*(hDC: HDC, hBrush: HBRUSH, lpOutputFunc: GRAYSTRINGPROC, - lpData: LPARAM, nCount: int32, X: int32, Y: int32, - nWidth: int32, nHeight: int32): WINBOOL{.stdcall, - dynlib: "user32", importc: "GrayStringA".} - proc DrawState*(para1: HDC, para2: HBRUSH, para3: DRAWSTATEPROC, - para4: LPARAM, para5: WPARAM, para6: int32, para7: int32, - para8: int32, para9: int32, para10: WINUINT): WINBOOL{.stdcall, - dynlib: "user32", importc: "DrawStateA".} - proc TabbedTextOut*(dc: HDC, X: int32, Y: int32, lpString: LPCSTR, - nCount: int32, nTabPositions: int32, - lpnTabStopPositions: LPINT, nTabOrigin: int32): LONG{. - stdcall, dynlib: "user32", importc: "TabbedTextOutA".} - proc GetTabbedTextExtent*(hDC: HDC, lpString: LPCSTR, nCount: int32, - nTabPositions: int32, lpnTabStopPositions: LPINT): DWORD{. - stdcall, dynlib: "user32", importc: "GetTabbedTextExtentA".} - proc SetProp*(wnd: HWND, lpString: LPCSTR, hData: HANDLE): WINBOOL{.stdcall, - dynlib: "user32", importc: "SetPropA".} - proc GetProp*(wnd: HWND, lpString: LPCSTR): HANDLE{.stdcall, - dynlib: "user32", importc: "GetPropA".} - proc RemoveProp*(wnd: HWND, lpString: LPCSTR): HANDLE{.stdcall, - dynlib: "user32", importc: "RemovePropA".} - proc EnumPropsEx*(wnd: HWND, lpEnumFunc: PROPENUMPROCEX, lp: LPARAM): int32{. - stdcall, dynlib: "user32", importc: "EnumPropsExA".} - proc EnumProps*(wnd: HWND, lpEnumFunc: PROPENUMPROC): int32{.stdcall, - dynlib: "user32", importc: "EnumPropsA".} - proc SetWindowText*(wnd: HWND, lpString: LPCSTR): WINBOOL{.stdcall, - dynlib: "user32", importc: "SetWindowTextA".} - proc GetWindowText*(wnd: HWND, lpString: LPSTR, nMaxCount: int32): int32{. - stdcall, dynlib: "user32", importc: "GetWindowTextA".} - proc GetWindowTextLength*(wnd: HWND): int32{.stdcall, dynlib: "user32", - importc: "GetWindowTextLengthA".} - proc MessageBox*(wnd: HWND, lpText: LPCSTR, lpCaption: LPCSTR, uType: WINUINT): int32{. - stdcall, dynlib: "user32", importc: "MessageBoxA".} - proc MessageBoxEx*(wnd: HWND, lpText: LPCSTR, lpCaption: LPCSTR, uType: WINUINT, - wLanguageId: int16): int32{.stdcall, dynlib: "user32", - importc: "MessageBoxExA".} - proc MessageBoxIndirect*(para1: LPMSGBOXPARAMS): int32{.stdcall, - dynlib: "user32", importc: "MessageBoxIndirectA".} - proc GetWindowLong*(wnd: HWND, nIndex: int32): LONG{.stdcall, - dynlib: "user32", importc: "GetWindowLongA".} - proc SetWindowLong*(wnd: HWND, nIndex: int32, dwNewLong: LONG): LONG{. - stdcall, dynlib: "user32", importc: "SetWindowLongA".} - proc GetClassLong*(wnd: HWND, nIndex: int32): DWORD{.stdcall, - dynlib: "user32", importc: "GetClassLongA".} - proc SetClassLong*(wnd: HWND, nIndex: int32, dwNewLong: LONG): DWORD{. - stdcall, dynlib: "user32", importc: "SetClassLongA".} - when defined(cpu64): - proc GetWindowLongPtr*(wnd: HWND, nIndex: int32): LONG_PTR{.stdcall, - dynlib: "user32", importc: "GetWindowLongPtrA".} - proc SetWindowLongPtr*(wnd: HWND, nIndex: int32, dwNewLong: LONG_PTR): LONG_PTR{. - stdcall, dynlib: "user32", importc: "SetWindowLongPtrA".} - proc GetClassLongPtr*(wnd: HWND, nIndex: int32): LONG_PTR{.stdcall, - dynlib: "user32", importc: "GetClassLongPtrA".} - proc SetClassLongPtr*(wnd: HWND, nIndex: int32, dwNewLong: LONG_PTR): LONG_PTR{. - stdcall, dynlib: "user32", importc: "SetClassLongPtrA".} - else: - proc GetWindowLongPtr*(wnd: HWND, nIndex: int32): LONG_PTR{.stdcall, - dynlib: "user32", importc: "GetWindowLongA".} - proc SetWindowLongPtr*(wnd: HWND, nIndex: int32, dwNewLong: LONG_PTR): LONG_PTR{. - stdcall, dynlib: "user32", importc: "SetWindowLongA".} - proc GetClassLongPtr*(wnd: HWND, nIndex: int32): LONG_PTR{.stdcall, - dynlib: "user32", importc: "GetClassLongA".} - proc SetClassLongPtr*(wnd: HWND, nIndex: int32, dwNewLong: LONG_PTR): LONG_PTR{. - stdcall, dynlib: "user32", importc: "SetClassLongA".} - proc FindWindow*(lpClassName: LPCSTR, lpWindowName: LPCSTR): HWND{.stdcall, - dynlib: "user32", importc: "FindWindowA".} - proc FindWindowEx*(para1: HWND, para2: HWND, para3: LPCSTR, para4: LPCSTR): HWND{. - stdcall, dynlib: "user32", importc: "FindWindowExA".} - proc GetClassName*(wnd: HWND, lpClassName: LPSTR, nMaxCount: int32): int32{. - stdcall, dynlib: "user32", importc: "GetClassNameA".} - proc SetWindowsHookEx*(idHook: int32, lpfn: HOOKPROC, hmod: HINST, - dwThreadId: DWORD): HHOOK{.stdcall, dynlib: "user32", - importc: "SetWindowsHookExA".} - proc LoadBitmap*(hInstance: HINST, lpBitmapName: LPCSTR): HBITMAP{.stdcall, - dynlib: "user32", importc: "LoadBitmapA".} - proc LoadCursor*(hInstance: HINST, lpCursorName: LPCSTR): HCURSOR{.stdcall, - dynlib: "user32", importc: "LoadCursorA".} - proc LoadCursorFromFile*(lpFileName: LPCSTR): HCURSOR{.stdcall, - dynlib: "user32", importc: "LoadCursorFromFileA".} - proc LoadIcon*(hInstance: HINST, lpIconName: LPCSTR): HICON{.stdcall, - dynlib: "user32", importc: "LoadIconA".} - proc LoadImage*(para1: HINST, para2: LPCSTR, para3: WINUINT, para4: int32, - para5: int32, para6: WINUINT): HANDLE{.stdcall, dynlib: "user32", - importc: "LoadImageA".} - proc LoadString*(hInstance: HINST, uID: WINUINT, lpBuffer: LPSTR, - nBufferMax: int32): int32{.stdcall, dynlib: "user32", - importc: "LoadStringA".} - proc IsDialogMessage*(hDlg: HWND, lpMsg: LPMSG): WINBOOL{.stdcall, - dynlib: "user32", importc: "IsDialogMessageA".} - proc DlgDirList*(hDlg: HWND, lpPathSpec: LPSTR, nIDListBox: int32, - nIDStaticPath: int32, uFileType: WINUINT): int32{.stdcall, - dynlib: "user32", importc: "DlgDirListA".} - proc DlgDirSelectEx*(hDlg: HWND, lpString: LPSTR, nCount: int32, - nIDListBox: int32): WINBOOL{.stdcall, dynlib: "user32", - importc: "DlgDirSelectExA".} - proc DlgDirListComboBox*(hDlg: HWND, lpPathSpec: LPSTR, nIDComboBox: int32, - nIDStaticPath: int32, uFiletype: WINUINT): int32{. - stdcall, dynlib: "user32", importc: "DlgDirListComboBoxA".} - proc DlgDirSelectComboBoxEx*(hDlg: HWND, lpString: LPSTR, nCount: int32, - nIDComboBox: int32): WINBOOL{.stdcall, - dynlib: "user32", importc: "DlgDirSelectComboBoxExA".} - proc DefFrameProc*(wnd: HWND, hWndMDIClient: HWND, uMsg: WINUINT, - wp: WPARAM, lp: LPARAM): LRESULT{.stdcall, - dynlib: "user32", importc: "DefFrameProcA".} - proc DefMDIChildProc*(wnd: HWND, uMsg: WINUINT, wp: WPARAM, lp: LPARAM): LRESULT{. - stdcall, dynlib: "user32", importc: "DefMDIChildProcA".} - proc CreateMDIWindow*(lpClassName: LPSTR, lpWindowName: LPSTR, dwStyle: DWORD, - X: int32, Y: int32, nWidth: int32, nHeight: int32, - hWndParent: HWND, hInstance: HINST, lp: LPARAM): HWND{. - stdcall, dynlib: "user32", importc: "CreateMDIWindowA".} - proc WinHelp*(hWndMain: HWND, lpszHelp: LPCSTR, uCommand: WINUINT, dwData: DWORD): WINBOOL{. - stdcall, dynlib: "user32", importc: "WinHelpA".} - proc ChangeDisplaySettings*(lpDevMode: LPDEVMODE, dwFlags: DWORD): LONG{. - stdcall, dynlib: "user32", importc: "ChangeDisplaySettingsA".} - proc EnumDisplaySettings*(lpszDeviceName: LPCSTR, iModeNum: DWORD, - lpDevMode: LPDEVMODE): WINBOOL{.stdcall, - dynlib: "user32", importc: "EnumDisplaySettingsA".} - proc SystemParametersInfo*(uiAction: WINUINT, uiParam: WINUINT, pvParam: PVOID, - fWinIni: WINUINT): WINBOOL{.stdcall, dynlib: "user32", - importc: "SystemParametersInfoA".} - proc AddFontResource*(para1: LPCSTR): int32{.stdcall, dynlib: "gdi32", - importc: "AddFontResourceA".} - proc CopyMetaFile*(para1: HMETAFILE, para2: LPCSTR): HMETAFILE{.stdcall, - dynlib: "gdi32", importc: "CopyMetaFileA".} - proc CreateFont*(para1: int32, para2: int32, para3: int32, para4: int32, - para5: int32, para6: DWORD, para7: DWORD, para8: DWORD, - para9: DWORD, para10: DWORD, para11: DWORD, para12: DWORD, - para13: DWORD, para14: LPCSTR): HFONT{.stdcall, - dynlib: "gdi32", importc: "CreateFontA".} - proc CreateFontIndirect*(para1: LPLOGFONT): HFONT{.stdcall, dynlib: "gdi32", - importc: "CreateFontIndirectA".} - proc CreateFontIndirect*(para1: var LOGFONT): HFONT{.stdcall, dynlib: "gdi32", - importc: "CreateFontIndirectA".} - proc CreateIC*(para1: LPCSTR, para2: LPCSTR, para3: LPCSTR, para4: LPDEVMODE): HDC{. - stdcall, dynlib: "gdi32", importc: "CreateICA".} - proc CreateMetaFile*(para1: LPCSTR): HDC{.stdcall, dynlib: "gdi32", - importc: "CreateMetaFileA".} - proc CreateScalableFontResource*(para1: DWORD, para2: LPCSTR, para3: LPCSTR, - para4: LPCSTR): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "CreateScalableFontResourceA".} - proc EnumFontFamiliesEx*(para1: HDC, para2: LPLOGFONT, para3: FONTENUMEXPROC, - para4: LPARAM, para5: DWORD): int32{.stdcall, - dynlib: "gdi32", importc: "EnumFontFamiliesExA".} - proc EnumFontFamilies*(para1: HDC, para2: LPCSTR, para3: FONTENUMPROC, - para4: LPARAM): int32{.stdcall, dynlib: "gdi32", - importc: "EnumFontFamiliesA".} - proc EnumFonts*(para1: HDC, para2: LPCSTR, para3: ENUMFONTSPROC, para4: LPARAM): int32{. - stdcall, dynlib: "gdi32", importc: "EnumFontsA".} - proc EnumFonts*(para1: HDC, para2: LPCSTR, para3: ENUMFONTSPROC, - para4: pointer): int32{.stdcall, dynlib: "gdi32", - importc: "EnumFontsA".} - proc GetCharWidth*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: LPINT): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "GetCharWidthA".} - proc GetCharWidth32*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: LPINT): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "GetCharWidth32A".} - proc GetCharWidthFloat*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: ptr float32): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "GetCharWidthFloatA".} - proc GetCharABCWidths*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: LPABC): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "GetCharABCWidthsA".} - proc GetCharABCWidthsFloat*(para1: HDC, para2: WINUINT, para3: WINUINT, - para4: LPABCFLOAT): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "GetCharABCWidthsFloatA".} - proc GetGlyphOutline*(para1: HDC, para2: WINUINT, para3: WINUINT, - para4: LPGLYPHMETRICS, para5: DWORD, para6: LPVOID, - para7: PMAT2): DWORD{.stdcall, dynlib: "gdi32", - importc: "GetGlyphOutlineA".} - proc GetMetaFile*(para1: LPCSTR): HMETAFILE{.stdcall, dynlib: "gdi32", - importc: "GetMetaFileA".} - proc GetOutlineTextMetrics*(para1: HDC, para2: WINUINT, - para3: LPOUTLINETEXTMETRIC): WINUINT{.stdcall, - dynlib: "gdi32", importc: "GetOutlineTextMetricsA".} - proc GetTextExtentPoint*(para1: HDC, para2: LPCSTR, para3: int32, - para4: LPSIZE): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "GetTextExtentPointA".} - proc GetTextExtentPoint32*(para1: HDC, para2: LPCSTR, para3: int32, - para4: LPSIZE): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "GetTextExtentPoint32A".} - proc GetTextExtentExPoint*(para1: HDC, para2: LPCSTR, para3: int32, - para4: int32, para5: LPINT, para6: LPINT, - para7: LPSIZE): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "GetTextExtentExPointA".} - proc GetCharacterPlacement*(para1: HDC, para2: LPCSTR, para3: int32, - para4: int32, para5: LPGCP_RESULTS, para6: DWORD): DWORD{. - stdcall, dynlib: "gdi32", importc: "GetCharacterPlacementA".} - proc ResetDC*(para1: HDC, para2: LPDEVMODE): HDC{.stdcall, dynlib: "gdi32", - importc: "ResetDCA".} - proc RemoveFontResource*(para1: LPCSTR): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "RemoveFontResourceA".} - proc CopyEnhMetaFile*(para1: HENHMETAFILE, para2: LPCSTR): HENHMETAFILE{. - stdcall, dynlib: "gdi32", importc: "CopyEnhMetaFileA".} - proc CreateEnhMetaFile*(para1: HDC, para2: LPCSTR, para3: LPRECT, - para4: LPCSTR): HDC{.stdcall, dynlib: "gdi32", - importc: "CreateEnhMetaFileA".} - proc GetEnhMetaFile*(para1: LPCSTR): HENHMETAFILE{.stdcall, dynlib: "gdi32", - importc: "GetEnhMetaFileA".} - proc GetEnhMetaFileDescription*(para1: HENHMETAFILE, para2: WINUINT, para3: LPSTR): WINUINT{. - stdcall, dynlib: "gdi32", importc: "GetEnhMetaFileDescriptionA".} - proc GetTextMetrics*(para1: HDC, para2: LPTEXTMETRIC): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "GetTextMetricsA".} - proc StartDoc*(para1: HDC, para2: PDOCINFO): int32{.stdcall, dynlib: "gdi32", - importc: "StartDocA".} - proc GetObject*(para1: HGDIOBJ, para2: int32, para3: LPVOID): int32{.stdcall, - dynlib: "gdi32", importc: "GetObjectA".} - proc TextOut*(para1: HDC, para2: int32, para3: int32, para4: LPCSTR, - para5: int32): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "TextOutA".} - proc ExtTextOut*(para1: HDC, para2: int32, para3: int32, para4: WINUINT, - para5: LPRECT, para6: LPCSTR, para7: WINUINT, para8: LPINT): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "ExtTextOutA".} - proc PolyTextOut*(para1: HDC, para2: PPOLYTEXT, para3: int32): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "PolyTextOutA".} - proc GetTextFace*(para1: HDC, para2: int32, para3: LPSTR): int32{.stdcall, - dynlib: "gdi32", importc: "GetTextFaceA".} - proc GetKerningPairs*(para1: HDC, para2: DWORD, para3: LPKERNINGPAIR): DWORD{. - stdcall, dynlib: "gdi32", importc: "GetKerningPairsA".} - proc CreateColorSpace*(para1: LPLOGCOLORSPACE): HCOLORSPACE{.stdcall, - dynlib: "gdi32", importc: "CreateColorSpaceA".} - proc GetLogColorSpace*(para1: HCOLORSPACE, para2: LPLOGCOLORSPACE, - para3: DWORD): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "GetLogColorSpaceA".} - proc GetICMProfile*(para1: HDC, para2: DWORD, para3: LPSTR): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "GetICMProfileA".} - proc SetICMProfile*(para1: HDC, para2: LPSTR): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "SetICMProfileA".} - proc UpdateICMRegKey*(para1: DWORD, para2: DWORD, para3: LPSTR, para4: WINUINT): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "UpdateICMRegKeyA".} - proc EnumICMProfiles*(para1: HDC, para2: ICMENUMPROC, para3: LPARAM): int32{. - stdcall, dynlib: "gdi32", importc: "EnumICMProfilesA".} - proc PropertySheet*(lppsph: LPCPROPSHEETHEADER): int32{.stdcall, - dynlib: "comctl32", importc: "PropertySheetA".} - proc ImageList_LoadImage*(hi: HINST, lpbmp: LPCSTR, cx: int32, cGrow: int32, - crMask: COLORREF, uType: WINUINT, uFlags: WINUINT): HIMAGELIST{. - stdcall, dynlib: "comctl32", importc: "ImageList_LoadImageA".} - proc CreateStatusWindow*(style: LONG, lpszText: LPCSTR, hwndParent: HWND, - wID: WINUINT): HWND{.stdcall, dynlib: "comctl32", - importc: "CreateStatusWindowA".} - proc DrawStatusText*(hDC: HDC, lprc: LPRECT, pszText: LPCSTR, uFlags: WINUINT){. - stdcall, dynlib: "comctl32", importc: "DrawStatusTextA".} - proc GetOpenFileName*(para1: LPOPENFILENAME): WINBOOL{.stdcall, - dynlib: "comdlg32", importc: "GetOpenFileNameA".} - proc GetSaveFileName*(para1: LPOPENFILENAME): WINBOOL{.stdcall, - dynlib: "comdlg32", importc: "GetSaveFileNameA".} - proc GetFileTitle*(para1: LPCSTR, para2: LPSTR, para3: int16): int{.stdcall, - dynlib: "comdlg32", importc: "GetFileTitleA".} - proc ChooseColor*(para1: LPCHOOSECOLOR): WINBOOL{.stdcall, dynlib: "comdlg32", - importc: "ChooseColorA".} - proc FindText*(para1: LPFINDREPLACE): HWND{.stdcall, dynlib: "comdlg32", - importc: "FindTextA".} - proc ReplaceText*(para1: LPFINDREPLACE): HWND{.stdcall, dynlib: "comdlg32", - importc: "ReplaceTextA".} - proc ChooseFont*(para1: LPCHOOSEFONT): WINBOOL{.stdcall, dynlib: "comdlg32", - importc: "ChooseFontA".} - proc PrintDlg*(para1: LPPRINTDLG): WINBOOL{.stdcall, dynlib: "comdlg32", - importc: "PrintDlgA".} - proc PageSetupDlg*(para1: LPPAGESETUPDLG): WINBOOL{.stdcall, - dynlib: "comdlg32", importc: "PageSetupDlgA".} - proc CreateProcess*(lpApplicationName: LPCSTR, lpCommandLine: LPSTR, - lpProcessAttributes: LPSECURITY_ATTRIBUTES, - lpThreadAttributes: LPSECURITY_ATTRIBUTES, - bInheritHandles: WINBOOL, dwCreationFlags: DWORD, - lpEnvironment: LPVOID, lpCurrentDirectory: LPCSTR, - lpStartupInfo: LPSTARTUPINFO, - lpProcessInformation: LPPROCESS_INFORMATION): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "CreateProcessA".} - proc GetStartupInfo*(lpStartupInfo: LPSTARTUPINFO){.stdcall, - dynlib: "kernel32", importc: "GetStartupInfoA".} - proc FindFirstFile*(lpFileName: LPCSTR, lpFindFileData: LPWIN32_FIND_DATA): HANDLE{. - stdcall, dynlib: "kernel32", importc: "FindFirstFileA".} - proc FindNextFile*(hFindFile: HANDLE, lpFindFileData: LPWIN32_FIND_DATA): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "FindNextFileA".} - proc GetVersionEx*(VersionInformation: LPOSVERSIONINFO): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetVersionExA".} - proc CreateWindow*(lpClassName: LPCSTR, lpWindowName: LPCSTR, dwStyle: DWORD, - X: int32, Y: int32, nWidth: int32, nHeight: int32, - hWndParent: HWND, menu: HMENU, hInstance: HINST, - lpParam: LPVOID): HWND - proc CreateDialog*(hInstance: HINST, lpTemplateName: LPCSTR, hWndParent: HWND, - lpDialogFunc: DLGPROC): HWND - proc CreateDialogIndirect*(hInstance: HINST, lpTemplate: LPCDLGTEMPLATE, - hWndParent: HWND, lpDialogFunc: DLGPROC): HWND - proc DialogBox*(hInstance: HINST, lpTemplateName: LPCSTR, hWndParent: HWND, - lpDialogFunc: DLGPROC): int32 - proc DialogBoxIndirect*(hInstance: HINST, hDialogTemplate: LPCDLGTEMPLATE, - hWndParent: HWND, lpDialogFunc: DLGPROC): int32 - proc CreateDC*(para1: LPCSTR, para2: LPCSTR, para3: LPCSTR, para4: PDEVMODE): HDC{. - stdcall, dynlib: "gdi32", importc: "CreateDCA".} - proc VerInstallFile*(uFlags: DWORD, szSrcFileName: LPSTR, - szDestFileName: LPSTR, szSrcDir: LPSTR, szDestDir: LPSTR, - szCurDir: LPSTR, szTmpFile: LPSTR, lpuTmpFileLen: PUINT): DWORD{. - stdcall, dynlib: "version", importc: "VerInstallFileA".} - proc GetFileVersionInfoSize*(lptstrFilename: LPSTR, lpdwHandle: LPDWORD): DWORD{. - stdcall, dynlib: "version", importc: "GetFileVersionInfoSizeA".} - proc GetFileVersionInfo*(lptstrFilename: LPSTR, dwHandle: DWORD, dwLen: DWORD, - lpData: LPVOID): WINBOOL{.stdcall, dynlib: "version", - importc: "GetFileVersionInfoA".} - proc VerLanguageName*(wLang: DWORD, szLang: LPSTR, nSize: DWORD): DWORD{. - stdcall, dynlib: "kernel32", importc: "VerLanguageNameA".} - proc VerQueryValue*(pBlock: LPVOID, lpSubBlock: LPSTR, lplpBuffer: LPVOID, - puLen: PUINT): WINBOOL{.stdcall, dynlib: "version", - importc: "VerQueryValueA".} - proc VerFindFile*(uFlags: DWORD, szFileName: LPSTR, szWinDir: LPSTR, - szAppDir: LPSTR, szCurDir: LPSTR, lpuCurDirLen: PUINT, - szDestDir: LPSTR, lpuDestDirLen: PUINT): DWORD{.stdcall, - dynlib: "version", importc: "VerFindFileA".} - proc RegConnectRegistry*(lpMachineName: LPSTR, key: HKEY, phkResult: PHKEY): LONG{. - stdcall, dynlib: "advapi32", importc: "RegConnectRegistryA".} - proc RegCreateKey*(key: HKEY, lpSubKey: LPCSTR, phkResult: PHKEY): LONG{. - stdcall, dynlib: "advapi32", importc: "RegCreateKeyA".} - proc RegCreateKeyEx*(key: HKEY, lpSubKey: LPCSTR, Reserved: DWORD, - lpClass: LPSTR, dwOptions: DWORD, samDesired: REGSAM, - lpSecurityAttributes: LPSECURITY_ATTRIBUTES, - phkResult: PHKEY, lpdwDisposition: LPDWORD): LONG{. - stdcall, dynlib: "advapi32", importc: "RegCreateKeyExA".} - proc RegDeleteKey*(key: HKEY, lpSubKey: LPCSTR): LONG{.stdcall, - dynlib: "advapi32", importc: "RegDeleteKeyA".} - proc RegDeleteValue*(key: HKEY, lpValueName: LPCSTR): LONG{.stdcall, - dynlib: "advapi32", importc: "RegDeleteValueA".} - proc RegEnumKey*(key: HKEY, dwIndex: DWORD, lpName: LPSTR, cbName: DWORD): LONG{. - stdcall, dynlib: "advapi32", importc: "RegEnumKeyA".} - proc RegEnumKeyEx*(key: HKEY, dwIndex: DWORD, lpName: LPSTR, - lpcbName: LPDWORD, lpReserved: LPDWORD, lpClass: LPSTR, - lpcbClass: LPDWORD, lpftLastWriteTime: PFILETIME): LONG{. - stdcall, dynlib: "advapi32", importc: "RegEnumKeyExA".} - proc RegEnumValue*(key: HKEY, dwIndex: DWORD, lpValueName: LPSTR, - lpcbValueName: LPDWORD, lpReserved: LPDWORD, - lpType: LPDWORD, lpData: LPBYTE, lpcbData: LPDWORD): LONG{. - stdcall, dynlib: "advapi32", importc: "RegEnumValueA".} - proc RegLoadKey*(key: HKEY, lpSubKey: LPCSTR, lpFile: LPCSTR): LONG{.stdcall, - dynlib: "advapi32", importc: "RegLoadKeyA".} - proc RegOpenKey*(key: HKEY, lpSubKey: LPCSTR, phkResult: PHKEY): LONG{. - stdcall, dynlib: "advapi32", importc: "RegOpenKeyA".} - proc RegOpenKeyEx*(key: HKEY, lpSubKey: LPCSTR, ulOptions: DWORD, - samDesired: REGSAM, phkResult: PHKEY): LONG{.stdcall, - dynlib: "advapi32", importc: "RegOpenKeyExA".} - proc RegQueryInfoKey*(key: HKEY, lpClass: LPSTR, lpcbClass: LPDWORD, - lpReserved: LPDWORD, lpcSubKeys: LPDWORD, - lpcbMaxSubKeyLen: LPDWORD, lpcbMaxClassLen: LPDWORD, - lpcValues: LPDWORD, lpcbMaxValueNameLen: LPDWORD, - lpcbMaxValueLen: LPDWORD, - lpcbSecurityDescriptor: LPDWORD, - lpftLastWriteTime: PFILETIME): LONG{.stdcall, - dynlib: "advapi32", importc: "RegQueryInfoKeyA".} - proc RegQueryValue*(key: HKEY, lpSubKey: LPCSTR, lpValue: LPSTR, - lpcbValue: PLONG): LONG{.stdcall, dynlib: "advapi32", - importc: "RegQueryValueA".} - proc RegQueryMultipleValues*(key: HKEY, val_list: PVALENT, num_vals: DWORD, - lpValueBuf: LPSTR, ldwTotsize: LPDWORD): LONG{. - stdcall, dynlib: "advapi32", importc: "RegQueryMultipleValuesA".} - proc RegQueryValueEx*(key: HKEY, lpValueName: LPCSTR, lpReserved: LPDWORD, - lpType: LPDWORD, lpData: LPBYTE, lpcbData: LPDWORD): LONG{. - stdcall, dynlib: "advapi32", importc: "RegQueryValueExA".} - proc RegReplaceKey*(key: HKEY, lpSubKey: LPCSTR, lpNewFile: LPCSTR, - lpOldFile: LPCSTR): LONG{.stdcall, dynlib: "advapi32", - importc: "RegReplaceKeyA".} - proc RegRestoreKey*(key: HKEY, lpFile: LPCSTR, dwFlags: DWORD): LONG{. - stdcall, dynlib: "advapi32", importc: "RegRestoreKeyA".} - proc RegSaveKey*(key: HKEY, lpFile: LPCSTR, - lpSecurityAttributes: LPSECURITY_ATTRIBUTES): LONG{.stdcall, - dynlib: "advapi32", importc: "RegSaveKeyA".} - proc RegSetValue*(key: HKEY, lpSubKey: LPCSTR, dwType: DWORD, lpData: LPCSTR, - cbData: DWORD): LONG{.stdcall, dynlib: "advapi32", - importc: "RegSetValueA".} - proc RegSetValueEx*(key: HKEY, lpValueName: LPCSTR, Reserved: DWORD, - dwType: DWORD, lpData: LPBYTE, cbData: DWORD): LONG{. - stdcall, dynlib: "advapi32", importc: "RegSetValueExA".} - proc RegUnLoadKey*(key: HKEY, lpSubKey: LPCSTR): LONG{.stdcall, - dynlib: "advapi32", importc: "RegUnLoadKeyA".} - proc InitiateSystemShutdown*(lpMachineName: LPSTR, lpMessage: LPSTR, - dwTimeout: DWORD, bForceAppsClosed: WINBOOL, - bRebootAfterShutdown: WINBOOL): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "InitiateSystemShutdownA".} - proc AbortSystemShutdown*(lpMachineName: LPSTR): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "AbortSystemShutdownA".} - proc CompareString*(Locale: LCID, dwCmpFlags: DWORD, lpString1: LPCSTR, - cchCount1: int32, lpString2: LPCSTR, cchCount2: int32): int32{. - stdcall, dynlib: "kernel32", importc: "CompareStringA".} - proc LCMapString*(Locale: LCID, dwMapFlags: DWORD, lpSrcStr: LPCSTR, - cchSrc: int32, lpDestStr: LPSTR, cchDest: int32): int32{. - stdcall, dynlib: "kernel32", importc: "LCMapStringA".} - proc GetLocaleInfo*(Locale: LCID, LCType: LCTYPE, lpLCData: LPSTR, - cchData: int32): int32{.stdcall, dynlib: "kernel32", - importc: "GetLocaleInfoA".} - proc SetLocaleInfo*(Locale: LCID, LCType: LCTYPE, lpLCData: LPCSTR): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "SetLocaleInfoA".} - proc GetTimeFormat*(Locale: LCID, dwFlags: DWORD, lpTime: LPSYSTEMTIME, - lpFormat: LPCSTR, lpTimeStr: LPSTR, cchTime: int32): int32{. - stdcall, dynlib: "kernel32", importc: "GetTimeFormatA".} - proc GetDateFormat*(Locale: LCID, dwFlags: DWORD, lpDate: LPSYSTEMTIME, - lpFormat: LPCSTR, lpDateStr: LPSTR, cchDate: int32): int32{. - stdcall, dynlib: "kernel32", importc: "GetDateFormatA".} - proc GetNumberFormat*(Locale: LCID, dwFlags: DWORD, lpValue: LPCSTR, - lpFormat: PNUMBERFMT, lpNumberStr: LPSTR, - cchNumber: int32): int32{.stdcall, dynlib: "kernel32", - importc: "GetNumberFormatA".} - proc GetCurrencyFormat*(Locale: LCID, dwFlags: DWORD, lpValue: LPCSTR, - lpFormat: PCURRENCYFMT, lpCurrencyStr: LPSTR, - cchCurrency: int32): int32{.stdcall, - dynlib: "kernel32", importc: "GetCurrencyFormatA".} - proc EnumCalendarInfo*(lpCalInfoEnumProc: CALINFO_ENUMPROC, Locale: LCID, - Calendar: CALID, CalType: CALTYPE): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "EnumCalendarInfoA".} - proc EnumTimeFormats*(lpTimeFmtEnumProc: TIMEFMT_ENUMPROC, Locale: LCID, - dwFlags: DWORD): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "EnumTimeFormatsA".} - proc EnumDateFormats*(lpDateFmtEnumProc: DATEFMT_ENUMPROC, Locale: LCID, - dwFlags: DWORD): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "EnumDateFormatsA".} - proc GetStringTypeEx*(Locale: LCID, dwInfoType: DWORD, lpSrcStr: LPCSTR, - cchSrc: int32, lpCharType: LPWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetStringTypeExA".} - proc GetStringType*(Locale: LCID, dwInfoType: DWORD, lpSrcStr: LPCSTR, - cchSrc: int32, lpCharType: LPWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetStringTypeA".} - proc FoldString*(dwMapFlags: DWORD, lpSrcStr: LPCSTR, cchSrc: int32, - lpDestStr: LPSTR, cchDest: int32): int32{.stdcall, - dynlib: "kernel32", importc: "FoldStringA".} - proc EnumSystemLocales*(lpLocaleEnumProc: LOCALE_ENUMPROC, dwFlags: DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "EnumSystemLocalesA".} - proc EnumSystemCodePages*(lpCodePageEnumProc: CODEPAGE_ENUMPROC, - dwFlags: DWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "EnumSystemCodePagesA".} - proc PeekConsoleInput*(hConsoleInput: HANDLE, lpBuffer: PINPUTRECORD, - nLength: DWORD, lpNumberOfEventsRead: LPDWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "PeekConsoleInputA".} - proc ReadConsoleInput*(hConsoleInput: HANDLE, lpBuffer: PINPUTRECORD, - nLength: DWORD, lpNumberOfEventsRead: LPDWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "ReadConsoleInputA".} - proc WriteConsoleInput*(hConsoleInput: HANDLE, lpBuffer: PINPUTRECORD, - nLength: DWORD, lpNumberOfEventsWritten: LPDWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "WriteConsoleInputA".} - proc ReadConsoleOutput*(hConsoleOutput: HANDLE, lpBuffer: PCHAR_INFO, - dwBufferSize: COORD, dwBufferCoord: COORD, - lpReadRegion: PSMALL_RECT): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "ReadConsoleOutputA".} - proc WriteConsoleOutput*(hConsoleOutput: HANDLE, lpBuffer: PCHAR_INFO, - dwBufferSize: COORD, dwBufferCoord: COORD, - lpWriteRegion: PSMALL_RECT): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "WriteConsoleOutputA".} - proc ReadConsoleOutputCharacter*(hConsoleOutput: HANDLE, lpCharacter: LPSTR, - nLength: DWORD, dwReadCoord: COORD, - lpNumberOfCharsRead: LPDWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "ReadConsoleOutputCharacterA".} - proc WriteConsoleOutputCharacter*(hConsoleOutput: HANDLE, lpCharacter: LPCSTR, - nLength: DWORD, dwWriteCoord: COORD, - lpNumberOfCharsWritten: LPDWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "WriteConsoleOutputCharacterA".} - proc FillConsoleOutputCharacter*(hConsoleOutput: HANDLE, cCharacter: char, - nLength: DWORD, dwWriteCoord: COORD, - lpNumberOfCharsWritten: LPDWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "FillConsoleOutputCharacterA".} - proc ScrollConsoleScreenBuffer*(hConsoleOutput: HANDLE, - lpScrollRectangle: PSMALL_RECT, - lpClipRectangle: PSMALL_RECT, - dwDestinationOrigin: COORD, lpFill: PCHAR_INFO): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "ScrollConsoleScreenBufferA".} - proc GetConsoleTitle*(lpConsoleTitle: LPSTR, nSize: DWORD): DWORD{.stdcall, - dynlib: "kernel32", importc: "GetConsoleTitleA".} - proc SetConsoleTitle*(lpConsoleTitle: LPCSTR): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "SetConsoleTitleA".} - proc ReadConsole*(hConsoleInput: HANDLE, lpBuffer: LPVOID, - nNumberOfCharsToRead: DWORD, lpNumberOfCharsRead: LPDWORD, - lpReserved: LPVOID): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "ReadConsoleA".} - proc WriteConsole*(hConsoleOutput: HANDLE, lpBuffer: pointer, - nNumberOfCharsToWrite: DWORD, - lpNumberOfCharsWritten: LPDWORD, lpReserved: LPVOID): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "WriteConsoleA".} - proc WNetAddConnection*(lpRemoteName: LPCSTR, lpPassword: LPCSTR, - lpLocalName: LPCSTR): DWORD{.stdcall, dynlib: "mpr", - importc: "WNetAddConnectionA".} - proc WNetAddConnection2*(lpNetResource: LPNETRESOURCE, lpPassword: LPCSTR, - lpUserName: LPCSTR, dwFlags: DWORD): DWORD{.stdcall, - dynlib: "mpr", importc: "WNetAddConnection2A".} - proc WNetAddConnection3*(hwndOwner: HWND, lpNetResource: LPNETRESOURCE, - lpPassword: LPCSTR, lpUserName: LPCSTR, - dwFlags: DWORD): DWORD{.stdcall, dynlib: "mpr", - importc: "WNetAddConnection3A".} - proc WNetCancelConnection*(lpName: LPCSTR, fForce: WINBOOL): DWORD{.stdcall, - dynlib: "mpr", importc: "WNetCancelConnectionA".} - proc WNetCancelConnection2*(lpName: LPCSTR, dwFlags: DWORD, fForce: WINBOOL): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetCancelConnection2A".} - proc WNetGetConnection*(lpLocalName: LPCSTR, lpRemoteName: LPSTR, - lpnLength: LPDWORD): DWORD{.stdcall, dynlib: "mpr", - importc: "WNetGetConnectionA".} - proc WNetUseConnection*(hwndOwner: HWND, lpNetResource: LPNETRESOURCE, - lpUserID: LPCSTR, lpPassword: LPCSTR, dwFlags: DWORD, - lpAccessName: LPSTR, lpBufferSize: LPDWORD, - lpResult: LPDWORD): DWORD{.stdcall, dynlib: "mpr", - importc: "WNetUseConnectionA".} - proc WNetSetConnection*(lpName: LPCSTR, dwProperties: DWORD, pvValues: LPVOID): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetSetConnectionA".} - proc WNetConnectionDialog1*(lpConnDlgStruct: LPCONNECTDLGSTRUCT): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetConnectionDialog1A".} - proc WNetDisconnectDialog1*(lpConnDlgStruct: LPDISCDLGSTRUCT): DWORD{.stdcall, - dynlib: "mpr", importc: "WNetDisconnectDialog1A".} - proc WNetOpenEnum*(dwScope: DWORD, dwType: DWORD, dwUsage: DWORD, - lpNetResource: LPNETRESOURCE, lphEnum: LPHANDLE): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetOpenEnumA".} - proc WNetEnumResource*(hEnum: HANDLE, lpcCount: LPDWORD, lpBuffer: LPVOID, - lpBufferSize: LPDWORD): DWORD{.stdcall, dynlib: "mpr", - importc: "WNetEnumResourceA".} - proc WNetGetUniversalName*(lpLocalPath: LPCSTR, dwInfoLevel: DWORD, - lpBuffer: LPVOID, lpBufferSize: LPDWORD): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetGetUniversalNameA".} - proc WNetGetUser*(lpName: LPCSTR, lpUserName: LPSTR, lpnLength: LPDWORD): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetGetUserA".} - proc WNetGetProviderName*(dwNetType: DWORD, lpProviderName: LPSTR, - lpBufferSize: LPDWORD): DWORD{.stdcall, - dynlib: "mpr", importc: "WNetGetProviderNameA".} - proc WNetGetNetworkInformation*(lpProvider: LPCSTR, - lpNetInfoStruct: LPNETINFOSTRUCT): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetGetNetworkInformationA".} - proc WNetGetLastError*(lpError: LPDWORD, lpErrorBuf: LPSTR, - nErrorBufSize: DWORD, lpNameBuf: LPSTR, - nNameBufSize: DWORD): DWORD{.stdcall, dynlib: "mpr", - importc: "WNetGetLastErrorA".} - proc MultinetGetConnectionPerformance*(lpNetResource: LPNETRESOURCE, - lpNetConnectInfoStruct: LPNETCONNECTINFOSTRUCT): DWORD{.stdcall, - dynlib: "mpr", importc: "MultinetGetConnectionPerformanceA".} - proc ChangeServiceConfig*(hService: SC_HANDLE, dwServiceType: DWORD, - dwStartType: DWORD, dwErrorControl: DWORD, - lpBinaryPathName: LPCSTR, lpLoadOrderGroup: LPCSTR, - lpdwTagId: LPDWORD, lpDependencies: LPCSTR, - lpServiceStartName: LPCSTR, lpPassword: LPCSTR, - lpDisplayName: LPCSTR): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "ChangeServiceConfigA".} - proc CreateService*(hSCManager: SC_HANDLE, lpServiceName: LPCSTR, - lpDisplayName: LPCSTR, dwDesiredAccess: DWORD, - dwServiceType: DWORD, dwStartType: DWORD, - dwErrorControl: DWORD, lpBinaryPathName: LPCSTR, - lpLoadOrderGroup: LPCSTR, lpdwTagId: LPDWORD, - lpDependencies: LPCSTR, lpServiceStartName: LPCSTR, - lpPassword: LPCSTR): SC_HANDLE{.stdcall, - dynlib: "advapi32", importc: "CreateServiceA".} - proc EnumDependentServices*(hService: SC_HANDLE, dwServiceState: DWORD, - lpServices: LPENUM_SERVICE_STATUS, - cbBufSize: DWORD, pcbBytesNeeded: LPDWORD, - lpServicesReturned: LPDWORD): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "EnumDependentServicesA".} - proc EnumServicesStatus*(hSCManager: SC_HANDLE, dwServiceType: DWORD, - dwServiceState: DWORD, - lpServices: LPENUM_SERVICE_STATUS, cbBufSize: DWORD, - pcbBytesNeeded: LPDWORD, lpServicesReturned: LPDWORD, - lpResumeHandle: LPDWORD): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "EnumServicesStatusA".} - proc GetServiceKeyName*(hSCManager: SC_HANDLE, lpDisplayName: LPCSTR, - lpServiceName: LPSTR, lpcchBuffer: LPDWORD): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "GetServiceKeyNameA".} - proc GetServiceDisplayName*(hSCManager: SC_HANDLE, lpServiceName: LPCSTR, - lpDisplayName: LPSTR, lpcchBuffer: LPDWORD): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "GetServiceDisplayNameA".} - proc OpenSCManager*(lpMachineName: LPCSTR, lpDatabaseName: LPCSTR, - dwDesiredAccess: DWORD): SC_HANDLE{.stdcall, - dynlib: "advapi32", importc: "OpenSCManagerA".} - proc OpenService*(hSCManager: SC_HANDLE, lpServiceName: LPCSTR, - dwDesiredAccess: DWORD): SC_HANDLE{.stdcall, - dynlib: "advapi32", importc: "OpenServiceA".} - proc QueryServiceConfig*(hService: SC_HANDLE, - lpServiceConfig: LPQUERY_SERVICE_CONFIG, - cbBufSize: DWORD, pcbBytesNeeded: LPDWORD): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "QueryServiceConfigA".} - proc QueryServiceLockStatus*(hSCManager: SC_HANDLE, - lpLockStatus: LPQUERY_SERVICE_LOCK_STATUS, - cbBufSize: DWORD, pcbBytesNeeded: LPDWORD): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "QueryServiceLockStatusA".} - proc RegisterServiceCtrlHandler*(lpServiceName: LPCSTR, - lpHandlerProc: LPHANDLER_FUNCTION): SERVICE_STATUS_HANDLE{. - stdcall, dynlib: "advapi32", importc: "RegisterServiceCtrlHandlerA".} - proc StartServiceCtrlDispatcher*(lpServiceStartTable: LPSERVICE_TABLE_ENTRY): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "StartServiceCtrlDispatcherA".} - proc StartService*(hService: SC_HANDLE, dwNumServiceArgs: DWORD, - lpServiceArgVectors: LPCSTR): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "StartServiceA".} - proc DragQueryFile*(para1: HDROP, para2: int, para3: cstring, para4: int): int{. - stdcall, dynlib: "shell32", importc: "DragQueryFileA".} - proc ExtractAssociatedIcon*(para1: HINST, para2: cstring, para3: LPWORD): HICON{. - stdcall, dynlib: "shell32", importc: "ExtractAssociatedIconA".} - proc ExtractIcon*(para1: HINST, para2: cstring, para3: int): HICON{.stdcall, - dynlib: "shell32", importc: "ExtractIconA".} - proc FindExecutable*(para1: cstring, para2: cstring, para3: cstring): HINST{. - stdcall, dynlib: "shell32", importc: "FindExecutableA".} - proc ShellAbout*(para1: HWND, para2: cstring, para3: cstring, para4: HICON): int32{. - stdcall, dynlib: "shell32", importc: "ShellAboutA".} - proc ShellExecute*(para1: HWND, para2: cstring, para3: cstring, - para4: cstring, para5: cstring, para6: int32): HINST{. - stdcall, dynlib: "shell32", importc: "ShellExecuteA".} - proc Shell_NotifyIcon*(dwMessage: DWORD, lpData: PNotifyIconDataA): WINBOOL{. - stdcall, dynlib: "shell32", importc: "Shell_NotifyIconA".} - proc DdeCreateStringHandle*(para1: DWORD, para2: cstring, para3: int32): HSZ{. - stdcall, dynlib: "user32", importc: "DdeCreateStringHandleA".} - proc DdeInitialize*(para1: LPDWORD, para2: PFNCALLBACK, para3: DWORD, - para4: DWORD): WINUINT{.stdcall, dynlib: "user32", - importc: "DdeInitializeA".} - proc DdeQueryString*(para1: DWORD, para2: HSZ, para3: cstring, para4: DWORD, - para5: int32): DWORD{.stdcall, dynlib: "user32", - importc: "DdeQueryStringA".} - proc LogonUser*(para1: LPSTR, para2: LPSTR, para3: LPSTR, para4: DWORD, - para5: DWORD, para6: PHANDLE): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "LogonUserA".} - proc CreateProcessAsUser*(para1: HANDLE, para2: LPCTSTR, para3: LPTSTR, - para4: LPSECURITY_ATTRIBUTES, - para5: LPSECURITY_ATTRIBUTES, para6: WINBOOL, - para7: DWORD, para8: LPVOID, para9: LPCTSTR, - para10: LPSTARTUPINFO, para11: LPPROCESS_INFORMATION): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "CreateProcessAsUserA".} -proc GetRandomRgn*(aHDC: HDC, aHRGN: HRGN, iNum: WINT): WINT{.stdcall, - importc, dynlib: "gdi32".} - -proc AccessCheck*(pSecurityDescriptor: PSECURITY_DESCRIPTOR, - ClientToken: HANDLE, DesiredAccess: DWORD, - GenericMapping: PGENERIC_MAPPING, - PrivilegeSet: PPRIVILEGE_SET, PrivilegeSetLength: LPDWORD, - GrantedAccess: LPDWORD, AccessStatus: LPBOOL): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "AccessCheck".} -proc FreeResource*(hResData: HGLOBAL): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "FreeResource".} -proc LockResource*(hResData: HGLOBAL): LPVOID{.stdcall, dynlib: "kernel32", - importc: "LockResource".} -proc FreeLibrary*(hLibModule: HINST): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "FreeLibrary".} -proc FreeLibraryAndExitThread*(hLibModule: HMODULE, dwExitCode: DWORD){.stdcall, - dynlib: "kernel32", importc: "FreeLibraryAndExitThread".} -proc DisableThreadLibraryCalls*(hLibModule: HMODULE): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "DisableThreadLibraryCalls".} -proc GetProcAddress*(hModule: HINST, lpProcName: LPCSTR): FARPROC{.stdcall, - dynlib: "kernel32", importc: "GetProcAddress".} -proc GetVersion*(): DWORD{.stdcall, dynlib: "kernel32", importc: "GetVersion".} -proc GlobalAlloc*(uFlags: int32, dwBytes: SIZE_T): HGLOBAL{.stdcall, - dynlib: "kernel32", importc: "GlobalAlloc".} -proc GlobalAlloc*(uFlags: int32, dwBytes: DWORD): HGLOBAL{.stdcall, - dynlib: "kernel32", importc: "GlobalAlloc", deprecated.} -proc GlobalReAlloc*(hMem: HGLOBAL, dwBytes: SIZE_T, uFlags: int32): HGLOBAL{. - stdcall, dynlib: "kernel32", importc: "GlobalReAlloc".} -proc GlobalReAlloc*(hMem: HGLOBAL, dwBytes: DWORD, uFlags: int32): HGLOBAL{. - stdcall, dynlib: "kernel32", importc: "GlobalReAlloc", deprecated.} -proc GlobalSize*(hMem: HGLOBAL): SIZE_T{.stdcall, dynlib: "kernel32", - importc: "GlobalSize".} -proc GlobalFlags*(hMem: HGLOBAL): WINUINT{.stdcall, dynlib: "kernel32", - importc: "GlobalFlags".} -proc GlobalLock*(hMem: HGLOBAL): LPVOID{.stdcall, dynlib: "kernel32", - importc: "GlobalLock".} -proc GlobalHandle*(pMem: LPCVOID): HGLOBAL{.stdcall, dynlib: "kernel32", - importc: "GlobalHandle".} -proc GlobalUnlock*(hMem: HGLOBAL): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "GlobalUnlock".} -proc GlobalFree*(hMem: HGLOBAL): HGLOBAL{.stdcall, dynlib: "kernel32", - importc: "GlobalFree".} -proc GlobalCompact*(dwMinFree: DWORD): WINUINT{.stdcall, dynlib: "kernel32", - importc: "GlobalCompact".} -proc GlobalFix*(hMem: HGLOBAL){.stdcall, dynlib: "kernel32", - importc: "GlobalFix".} -proc GlobalUnfix*(hMem: HGLOBAL){.stdcall, dynlib: "kernel32", - importc: "GlobalUnfix".} -proc GlobalWire*(hMem: HGLOBAL): LPVOID{.stdcall, dynlib: "kernel32", - importc: "GlobalWire".} -proc GlobalUnWire*(hMem: HGLOBAL): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "GlobalUnWire".} -proc GlobalMemoryStatus*(lpBuffer: LPMEMORYSTATUS){.stdcall, dynlib: "kernel32", - importc: "GlobalMemoryStatus".} -proc LocalAlloc*(uFlags: WINUINT, uBytes: SIZE_T): HLOCAL{.stdcall, - dynlib: "kernel32", importc: "LocalAlloc".} -proc LocalAlloc*(uFlags: WINUINT, uBytes: DWORD): HLOCAL{.stdcall, - dynlib: "kernel32", importc: "LocalAlloc", deprecated.} -proc LocalReAlloc*(hMem: HLOCAL, uBytes: SIZE_T, uFlags: WINUINT): HLOCAL{.stdcall, - dynlib: "kernel32", importc: "LocalReAlloc".} -proc LocalReAlloc*(hMem: HLOCAL, uBytes: DWORD, uFlags: WINUINT): HLOCAL{.stdcall, - dynlib: "kernel32", importc: "LocalReAlloc", deprecated.} -proc LocalLock*(hMem: HLOCAL): LPVOID{.stdcall, dynlib: "kernel32", - importc: "LocalLock".} -proc LocalHandle*(pMem: LPCVOID): HLOCAL{.stdcall, dynlib: "kernel32", - importc: "LocalHandle".} -proc LocalUnlock*(hMem: HLOCAL): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "LocalUnlock".} -proc LocalSize*(hMem: HLOCAL): WINUINT{.stdcall, dynlib: "kernel32", - importc: "LocalSize".} -proc LocalFlags*(hMem: HLOCAL): WINUINT{.stdcall, dynlib: "kernel32", - importc: "LocalFlags".} -proc LocalFree*(hMem: HLOCAL): HLOCAL{.stdcall, dynlib: "kernel32", - importc: "LocalFree".} -proc LocalShrink*(hMem: HLOCAL, cbNewSize: WINUINT): WINUINT{.stdcall, - dynlib: "kernel32", importc: "LocalShrink".} -proc LocalCompact*(uMinFree: WINUINT): WINUINT{.stdcall, dynlib: "kernel32", - importc: "LocalCompact".} -proc FlushInstructionCache*(hProcess: HANDLE, lpBaseAddress: LPCVOID, - dwSize: DWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "FlushInstructionCache".} -proc VirtualAlloc*(lpAddress: LPVOID, dwSize: SIZE_T, flAllocationType: DWORD, - flProtect: DWORD): LPVOID{.stdcall, dynlib: "kernel32", - importc: "VirtualAlloc".} -proc VirtualAlloc*(lpAddress: LPVOID, dwSize: DWORD, flAllocationType: DWORD, - flProtect: DWORD): LPVOID{.stdcall, dynlib: "kernel32", - importc: "VirtualAlloc", deprecated.} -proc VirtualAllocEx*(hProcess: HANDLE, lpAddress: LPVOID, dwSize: SIZE_T, - flAllocationType: DWORD, flProtect: DWORD): LPVOID - {.stdcall, dynlib: "kernel32", importc: "VirtualAllocEx".} -proc VirtualAllocEx*(hProcess: HANDLE, lpAddress: LPVOID, dwSize: DWORD, - flAllocationType: DWORD, flProtect: DWORD): LPVOID - {.stdcall, dynlib: "kernel32", importc: "VirtualAllocEx", - deprecated.} -proc VirtualFree*(lpAddress: LPVOID, dwSize: SIZE_T, dwFreeType: DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "VirtualFree".} -proc VirtualFree*(lpAddress: LPVOID, dwSize: DWORD, dwFreeType: DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "VirtualFree", deprecated.} -proc VirtualFreeEx*(hProcess: HANDLE, lpAddress: LPVOID, dwSize: SIZE_T, - dwFreeType: DWORD): WINBOOL - {.stdcall, dynlib: "kernel32", importc: "VirtualFree".} -proc VirtualFreeEx*(hProcess: HANDLE, lpAddress: LPVOID, dwSize: DWORD, - dwFreeType: DWORD): WINBOOL - {.stdcall, dynlib: "kernel32", importc: "VirtualFree".} -proc VirtualProtect*(lpAddress: LPVOID, dwSize: SIZE_T, flNewProtect: DWORD, - lpflOldProtect: PDWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "VirtualProtect".} -proc VirtualProtect*(lpAddress: LPVOID, dwSize: DWORD, flNewProtect: DWORD, - lpflOldProtect: PDWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "VirtualProtect", deprecated.} -proc VirtualQuery*(lpAddress: LPCVOID, lpBuffer: PMEMORY_BASIC_INFORMATION, - dwLength: DWORD): DWORD{.stdcall, dynlib: "kernel32", - importc: "VirtualQuery".} -proc VirtualProtectEx*(hProcess: HANDLE, lpAddress: LPVOID, dwSize: SIZE_T, - flNewProtect: DWORD, lpflOldProtect: PDWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "VirtualProtectEx".} -proc VirtualProtectEx*(hProcess: HANDLE, lpAddress: LPVOID, dwSize: DWORD, - flNewProtect: DWORD, lpflOldProtect: PDWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "VirtualProtectEx", deprecated.} -proc VirtualQueryEx*(hProcess: HANDLE, lpAddress: LPCVOID, - lpBuffer: PMEMORY_BASIC_INFORMATION, dwLength: SIZE_T): DWORD{. - stdcall, dynlib: "kernel32", importc: "VirtualQueryEx".} -proc VirtualQueryEx*(hProcess: HANDLE, lpAddress: LPCVOID, - lpBuffer: PMEMORY_BASIC_INFORMATION, dwLength: DWORD): DWORD{. - stdcall, dynlib: "kernel32", importc: "VirtualQueryEx", deprecated.} -proc HeapCreate*(flOptions: DWORD, dwInitialSize: SIZE_T, dwMaximumSize: SIZE_T): HANDLE{. - stdcall, dynlib: "kernel32", importc: "HeapCreate".} -proc HeapCreate*(flOptions: DWORD, dwInitialSize: DWORD, dwMaximumSize: DWORD): HANDLE{. - stdcall, dynlib: "kernel32", importc: "HeapCreate", deprecated.} -proc HeapDestroy*(hHeap: HANDLE): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "HeapDestroy".} -proc HeapAlloc*(hHeap: HANDLE, dwFlags: DWORD, dwBytes: SIZE_T): LPVOID{.stdcall, - dynlib: "kernel32", importc: "HeapAlloc".} -proc HeapAlloc*(hHeap: HANDLE, dwFlags: DWORD, dwBytes: DWORD): LPVOID{.stdcall, - dynlib: "kernel32", importc: "HeapAlloc", deprecated.} -proc HeapReAlloc*(hHeap: HANDLE, dwFlags: DWORD, lpMem: LPVOID, dwBytes: SIZE_T): LPVOID{. - stdcall, dynlib: "kernel32", importc: "HeapReAlloc".} -proc HeapReAlloc*(hHeap: HANDLE, dwFlags: DWORD, lpMem: LPVOID, dwBytes: DWORD): LPVOID{. - stdcall, dynlib: "kernel32", importc: "HeapReAlloc", deprecated.} -proc HeapFree*(hHeap: HANDLE, dwFlags: DWORD, lpMem: LPVOID): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "HeapFree".} -proc HeapSize*(hHeap: HANDLE, dwFlags: DWORD, lpMem: LPCVOID): SIZE_T{.stdcall, - dynlib: "kernel32", importc: "HeapSize".} -proc HeapValidate*(hHeap: HANDLE, dwFlags: DWORD, lpMem: LPCVOID): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "HeapValidate".} -proc HeapCompact*(hHeap: HANDLE, dwFlags: DWORD): SIZE_T{.stdcall, - dynlib: "kernel32", importc: "HeapCompact".} -proc GetProcessHeap*(): HANDLE{.stdcall, dynlib: "kernel32", - importc: "GetProcessHeap".} -proc GetProcessHeaps*(NumberOfHeaps: DWORD, ProcessHeaps: PHANDLE): DWORD{. - stdcall, dynlib: "kernel32", importc: "GetProcessHeaps".} -proc HeapLock*(hHeap: HANDLE): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "HeapLock".} -proc HeapUnlock*(hHeap: HANDLE): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "HeapUnlock".} -proc HeapWalk*(hHeap: HANDLE, lpEntry: LPPROCESS_HEAP_ENTRY): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "HeapWalk".} -proc GetProcessAffinityMask*(hProcess: HANDLE, lpProcessAffinityMask: LPDWORD, - lpSystemAffinityMask: LPDWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetProcessAffinityMask".} -proc GetProcessTimes*(hProcess: HANDLE, lpCreationTime: LPFILETIME, - lpExitTime: LPFILETIME, lpKernelTime: LPFILETIME, - lpUserTime: LPFILETIME): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetProcessTimes".} -proc GetProcessWorkingSetSize*(hProcess: HANDLE, - lpMinimumWorkingSetSize: LPDWORD, - lpMaximumWorkingSetSize: LPDWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetProcessWorkingSetSize".} -proc SetProcessWorkingSetSize*(hProcess: HANDLE, dwMinimumWorkingSetSize: DWORD, - dwMaximumWorkingSetSize: DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "SetProcessWorkingSetSize".} -proc OpenProcess*(dwDesiredAccess: DWORD, bInheritHandle: WINBOOL, - dwProcessId: DWORD): HANDLE{.stdcall, dynlib: "kernel32", - importc: "OpenProcess".} -proc GetCurrentProcess*(): HANDLE{.stdcall, dynlib: "kernel32", - importc: "GetCurrentProcess".} -proc GetCurrentProcessId*(): DWORD{.stdcall, dynlib: "kernel32", - importc: "GetCurrentProcessId".} -proc ExitProcess*(uExitCode: WINUINT){.stdcall, dynlib: "kernel32", - importc: "ExitProcess".} -proc TerminateProcess*(hProcess: HANDLE, uExitCode: WINUINT): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "TerminateProcess".} -proc SetProcessAffinityMask*(hProcess: Handle, dwProcessAffinityMask: DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "SetProcessAffinityMask".} -proc GetExitCodeProcess*(hProcess: HANDLE, lpExitCode: LPDWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetExitCodeProcess".} -proc FatalExit*(ExitCode: int32){.stdcall, dynlib: "kernel32", - importc: "FatalExit".} -proc RaiseException*(dwExceptionCode: DWORD, dwExceptionFlags: DWORD, - nNumberOfArguments: DWORD, lpArguments: LPDWORD){.stdcall, - dynlib: "kernel32", importc: "RaiseException".} -proc UnhandledExceptionFilter*(ExceptionInfo: lpemptyrecord): LONG{.stdcall, - dynlib: "kernel32", importc: "UnhandledExceptionFilter".} -proc CreateRemoteThread*(hProcess: HANDLE, - lpThreadAttributes: LPSECURITY_ATTRIBUTES, - dwStackSize: DWORD, - lpStartAddress: LPTHREAD_START_ROUTINE, - lpParameter: LPVOID, dwCreationFlags: DWORD, - lpThreadId: LPDWORD): HANDLE{.stdcall, - dynlib: "kernel32", importc: "CreateRemoteThread".} -proc GetCurrentThread*(): HANDLE{.stdcall, dynlib: "kernel32", - importc: "GetCurrentThread".} -proc GetCurrentThreadId*(): DWORD{.stdcall, dynlib: "kernel32", - importc: "GetCurrentThreadId".} -proc SetThreadAffinityMask*(hThread: HANDLE, dwThreadAffinityMask: DWORD): DWORD{. - stdcall, dynlib: "kernel32", importc: "SetThreadAffinityMask".} -proc SetThreadPriority*(hThread: HANDLE, nPriority: int32): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "SetThreadPriority".} -proc GetThreadPriority*(hThread: HANDLE): int32{.stdcall, dynlib: "kernel32", - importc: "GetThreadPriority".} -proc GetThreadTimes*(hThread: HANDLE, lpCreationTime: LPFILETIME, - lpExitTime: LPFILETIME, lpKernelTime: LPFILETIME, - lpUserTime: LPFILETIME): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetThreadTimes".} -proc ExitThread*(dwExitCode: DWORD){.stdcall, dynlib: "kernel32", - importc: "ExitThread".} -proc TerminateThread*(hThread: HANDLE, dwExitCode: DWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "TerminateThread".} -proc GetExitCodeThread*(hThread: HANDLE, lpExitCode: LPDWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetExitCodeThread".} -proc GetThreadSelectorEntry*(hThread: HANDLE, dwSelector: DWORD, - lpSelectorEntry: LPLDT_ENTRY): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetThreadSelectorEntry".} -proc GetLastError*(): DWORD{.stdcall, dynlib: "kernel32", - importc: "GetLastError".} -proc SetLastError*(dwErrCode: DWORD){.stdcall, dynlib: "kernel32", - importc: "SetLastError".} -proc CreateIoCompletionPort*(FileHandle: HANDLE, ExistingCompletionPort: HANDLE, - CompletionKey: DWORD, - NumberOfConcurrentThreads: DWORD): HANDLE{.stdcall, - dynlib: "kernel32", importc: "CreateIoCompletionPort".} -proc SetErrorMode*(uMode: WINUINT): WINUINT{.stdcall, dynlib: "kernel32", - importc: "SetErrorMode".} -proc ReadProcessMemory*(hProcess: HANDLE, lpBaseAddress: LPCVOID, - lpBuffer: LPVOID, nSize: DWORD, - lpNumberOfBytesRead: LPDWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "ReadProcessMemory".} -proc WriteProcessMemory*(hProcess: HANDLE, lpBaseAddress: LPVOID, - lpBuffer: LPVOID, nSize: DWORD, - lpNumberOfBytesWritten: LPDWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "WriteProcessMemory".} -proc GetThreadContext*(hThread: HANDLE, lpContext: LPCONTEXT): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetThreadContext".} -proc SuspendThread*(hThread: HANDLE): DWORD{.stdcall, dynlib: "kernel32", - importc: "SuspendThread".} -proc ResumeThread*(hThread: HANDLE): DWORD{.stdcall, dynlib: "kernel32", - importc: "ResumeThread".} -proc DebugBreak*(){.stdcall, dynlib: "kernel32", importc: "DebugBreak".} -proc WaitForDebugEvent*(lpDebugEvent: LPDEBUG_EVENT, dwMilliseconds: DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "WaitForDebugEvent".} -proc ContinueDebugEvent*(dwProcessId: DWORD, dwThreadId: DWORD, - dwContinueStatus: DWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "ContinueDebugEvent".} -proc DebugActiveProcess*(dwProcessId: DWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "DebugActiveProcess".} -proc InitializeCriticalSection*(lpCriticalSection: LPCRITICAL_SECTION){.stdcall, - dynlib: "kernel32", importc: "InitializeCriticalSection".} -proc EnterCriticalSection*(lpCriticalSection: LPCRITICAL_SECTION){.stdcall, - dynlib: "kernel32", importc: "EnterCriticalSection".} -proc LeaveCriticalSection*(lpCriticalSection: LPCRITICAL_SECTION){.stdcall, - dynlib: "kernel32", importc: "LeaveCriticalSection".} -proc DeleteCriticalSection*(lpCriticalSection: LPCRITICAL_SECTION){.stdcall, - dynlib: "kernel32", importc: "DeleteCriticalSection".} -proc TryEnterCriticalSection*(lpCriticalSection: LPCRITICAL_SECTION): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "TryEnterCriticalSection".} -proc SetEvent*(hEvent: HANDLE): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "SetEvent".} -proc ResetEvent*(hEvent: HANDLE): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "ResetEvent".} -proc PulseEvent*(hEvent: HANDLE): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "PulseEvent".} -proc ReleaseSemaphore*(hSemaphore: HANDLE, lReleaseCount: LONG, - lpPreviousCount: LPLONG): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "ReleaseSemaphore".} -proc ReleaseMutex*(hMutex: HANDLE): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "ReleaseMutex".} -proc WaitForSingleObject*(hHandle: HANDLE, dwMilliseconds: DWORD): DWORD{. - stdcall, dynlib: "kernel32", importc: "WaitForSingleObject".} - -proc Sleep*(dwMilliseconds: DWORD){.stdcall, dynlib: "kernel32", - importc: "Sleep".} -proc LoadResource*(hModule: HINST, hResInfo: HRSRC): HGLOBAL{.stdcall, - dynlib: "kernel32", importc: "LoadResource".} -proc SizeofResource*(hModule: HINST, hResInfo: HRSRC): DWORD{.stdcall, - dynlib: "kernel32", importc: "SizeofResource".} -proc GlobalDeleteAtom*(nAtom: ATOM): ATOM{.stdcall, dynlib: "kernel32", - importc: "GlobalDeleteAtom".} -proc InitAtomTable*(nSize: DWORD): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "InitAtomTable".} -proc DeleteAtom*(nAtom: ATOM): ATOM{.stdcall, dynlib: "kernel32", - importc: "DeleteAtom".} -proc SetHandleCount*(uNumber: WINUINT): WINUINT{.stdcall, dynlib: "kernel32", - importc: "SetHandleCount".} -proc GetLogicalDrives*(): DWORD{.stdcall, dynlib: "kernel32", - importc: "GetLogicalDrives".} -proc LockFile*(hFile: HANDLE, dwFileOffsetLow: DWORD, dwFileOffsetHigh: DWORD, - nNumberOfBytesToLockLow: DWORD, nNumberOfBytesToLockHigh: DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "LockFile".} -proc UnlockFile*(hFile: HANDLE, dwFileOffsetLow: DWORD, dwFileOffsetHigh: DWORD, - nNumberOfBytesToUnlockLow: DWORD, - nNumberOfBytesToUnlockHigh: DWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "UnlockFile".} -proc LockFileEx*(hFile: HANDLE, dwFlags: DWORD, dwReserved: DWORD, - nNumberOfBytesToLockLow: DWORD, - nNumberOfBytesToLockHigh: DWORD, lpOverlapped: LPOVERLAPPED): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "LockFileEx".} -proc UnlockFileEx*(hFile: HANDLE, dwReserved: DWORD, - nNumberOfBytesToUnlockLow: DWORD, - nNumberOfBytesToUnlockHigh: DWORD, lpOverlapped: LPOVERLAPPED): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "UnlockFileEx".} -proc GetFileInformationByHandle*(hFile: HANDLE, lpFileInformation: LPBY_HANDLE_FILE_INFORMATION): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetFileInformationByHandle".} -proc GetFileType*(hFile: HANDLE): DWORD{.stdcall, dynlib: "kernel32", - importc: "GetFileType".} -proc GetFileSize*(hFile: HANDLE, lpFileSizeHigh: LPDWORD): DWORD{.stdcall, - dynlib: "kernel32", importc: "GetFileSize".} -proc GetStdHandle*(nStdHandle: DWORD): HANDLE{.stdcall, dynlib: "kernel32", - importc: "GetStdHandle".} -proc SetStdHandle*(nStdHandle: DWORD, hHandle: HANDLE): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "SetStdHandle".} -proc FlushFileBuffers*(hFile: HANDLE): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "FlushFileBuffers".} -proc DeviceIoControl*(hDevice: HANDLE, dwIoControlCode: DWORD, - lpInBuffer: LPVOID, nInBufferSize: DWORD, - lpOutBuffer: LPVOID, nOutBufferSize: DWORD, - lpBytesReturned: LPDWORD, lpOverlapped: LPOVERLAPPED): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "DeviceIoControl".} -proc SetEndOfFile*(hFile: HANDLE): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "SetEndOfFile".} -proc SetFilePointer*(hFile: HANDLE, lDistanceToMove: LONG, - lpDistanceToMoveHigh: PLONG, dwMoveMethod: DWORD): DWORD{. - stdcall, dynlib: "kernel32", importc: "SetFilePointer".} -proc FindClose*(hFindFile: HANDLE): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "FindClose".} -proc GetFileTime*(hFile: HANDLE, lpCreationTime: LPFILETIME, - lpLastAccessTime: LPFILETIME, lpLastWriteTime: LPFILETIME): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetFileTime".} -proc SetFileTime*(hFile: HANDLE, lpCreationTime: LPFILETIME, - lpLastAccessTime: LPFILETIME, lpLastWriteTime: LPFILETIME): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "SetFileTime".} -proc CloseHandle*(hObject: HANDLE): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "CloseHandle".} -proc DuplicateHandle*(hSourceProcessHandle: HANDLE, hSourceHandle: HANDLE, - hTargetProcessHandle: HANDLE, lpTargetHandle: LPHANDLE, - dwDesiredAccess: DWORD, bInheritHandle: WINBOOL, - dwOptions: DWORD): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "DuplicateHandle".} -proc GetHandleInformation*(hObject: HANDLE, lpdwFlags: LPDWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetHandleInformation".} -proc SetHandleInformation*(hObject: HANDLE, dwMask: DWORD, dwFlags: DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "SetHandleInformation".} -proc LoadModule*(lpModuleName: LPCSTR, lpParameterBlock: LPVOID): DWORD{. - stdcall, dynlib: "kernel32", importc: "LoadModule".} -proc WinExec*(lpCmdLine: LPCSTR, uCmdShow: WINUINT): WINUINT{.stdcall, - dynlib: "kernel32", importc: "WinExec".} -proc ClearCommBreak*(hFile: HANDLE): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "ClearCommBreak".} -proc ClearCommError*(hFile: HANDLE, lpErrors: LPDWORD, lpStat: LPCOMSTAT): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "ClearCommError".} -proc SetupComm*(hFile: HANDLE, dwInQueue: DWORD, dwOutQueue: DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "SetupComm".} -proc EscapeCommFunction*(hFile: HANDLE, dwFunc: DWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "EscapeCommFunction".} -proc GetCommConfig*(hCommDev: HANDLE, lpCC: LPCOMMCONFIG, lpdwSize: LPDWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetCommConfig".} -proc GetCommProperties*(hFile: HANDLE, lpCommProp: LPCOMMPROP): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetCommProperties".} -proc GetCommModemStatus*(hFile: HANDLE, lpModemStat: PDWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetCommModemStatus".} -proc GetCommState*(hFile: HANDLE, lpDCB: PDCB): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetCommState".} -proc GetCommTimeouts*(hFile: HANDLE, lpCommTimeouts: PCOMMTIMEOUTS): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetCommTimeouts".} -proc PurgeComm*(hFile: HANDLE, dwFlags: DWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "PurgeComm".} -proc SetCommBreak*(hFile: HANDLE): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "SetCommBreak".} -proc SetCommConfig*(hCommDev: HANDLE, lpCC: LPCOMMCONFIG, dwSize: DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "SetCommConfig".} -proc SetCommMask*(hFile: HANDLE, dwEvtMask: DWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "SetCommMask".} -proc SetCommState*(hFile: HANDLE, lpDCB: LPDCB): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "SetCommState".} -proc SetCommTimeouts*(hFile: HANDLE, lpCommTimeouts: LPCOMMTIMEOUTS): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "SetCommTimeouts".} -proc TransmitCommChar*(hFile: HANDLE, cChar: char): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "TransmitCommChar".} -proc WaitCommEvent*(hFile: HANDLE, lpEvtMask: LPDWORD, - lpOverlapped: LPOVERLAPPED): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "WaitCommEvent".} -proc SetTapePosition*(hDevice: HANDLE, dwPositionMethod: DWORD, - dwPartition: DWORD, dwOffsetLow: DWORD, - dwOffsetHigh: DWORD, bImmediate: WINBOOL): DWORD{.stdcall, - dynlib: "kernel32", importc: "SetTapePosition".} -proc GetTapePosition*(hDevice: HANDLE, dwPositionType: DWORD, - lpdwPartition: LPDWORD, lpdwOffsetLow: LPDWORD, - lpdwOffsetHigh: LPDWORD): DWORD{.stdcall, - dynlib: "kernel32", importc: "GetTapePosition".} -proc PrepareTape*(hDevice: HANDLE, dwOperation: DWORD, bImmediate: WINBOOL): DWORD{. - stdcall, dynlib: "kernel32", importc: "PrepareTape".} -proc EraseTape*(hDevice: HANDLE, dwEraseType: DWORD, bImmediate: WINBOOL): DWORD{. - stdcall, dynlib: "kernel32", importc: "EraseTape".} -proc CreateTapePartition*(hDevice: HANDLE, dwPartitionMethod: DWORD, - dwCount: DWORD, dwSize: DWORD): DWORD{.stdcall, - dynlib: "kernel32", importc: "CreateTapePartition".} -proc WriteTapemark*(hDevice: HANDLE, dwTapemarkType: DWORD, - dwTapemarkCount: DWORD, bImmediate: WINBOOL): DWORD{. - stdcall, dynlib: "kernel32", importc: "WriteTapemark".} -proc GetTapeStatus*(hDevice: HANDLE): DWORD{.stdcall, dynlib: "kernel32", - importc: "GetTapeStatus".} -proc GetTapeParameters*(hDevice: HANDLE, dwOperation: DWORD, lpdwSize: LPDWORD, - lpTapeInformation: LPVOID): DWORD{.stdcall, - dynlib: "kernel32", importc: "GetTapeParameters".} -proc SetTapeParameters*(hDevice: HANDLE, dwOperation: DWORD, - lpTapeInformation: LPVOID): DWORD{.stdcall, - dynlib: "kernel32", importc: "SetTapeParameters".} -proc Beep*(dwFreq: DWORD, dwDuration: DWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "Beep".} -proc MulDiv*(nNumber: int32, nNumerator: int32, nDenominator: int32): int32{. - stdcall, dynlib: "kernel32", importc: "MulDiv".} -proc GetSystemTime*(lpSystemTime: LPSYSTEMTIME){.stdcall, dynlib: "kernel32", - importc: "GetSystemTime".} -proc GetSystemTimeAsFileTime*(lpSystemTimeAsFileTime: LPFILETIME){.stdcall, - dynlib: "kernel32", importc: "GetSystemTimeAsFileTime".} -proc SetSystemTime*(lpSystemTime: LPSYSTEMTIME): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "SetSystemTime".} -proc GetLocalTime*(lpSystemTime: LPSYSTEMTIME){.stdcall, dynlib: "kernel32", - importc: "GetLocalTime".} -proc SetLocalTime*(lpSystemTime: LPSYSTEMTIME): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "SetLocalTime".} -proc GetSystemInfo*(lpSystemInfo: LPSYSTEM_INFO){.stdcall, dynlib: "kernel32", - importc: "GetSystemInfo".} -proc SystemTimeToTzSpecificLocalTime*(lpTimeZoneInformation: LPTIME_ZONE_INFORMATION, - lpUniversalTime: LPSYSTEMTIME, - lpLocalTime: LPSYSTEMTIME): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "SystemTimeToTzSpecificLocalTime".} -proc GetTimeZoneInformation*(lpTimeZoneInformation: LPTIME_ZONE_INFORMATION): DWORD{. - stdcall, dynlib: "kernel32", importc: "GetTimeZoneInformation".} -proc SetTimeZoneInformation*(lpTimeZoneInformation: LPTIME_ZONE_INFORMATION): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "SetTimeZoneInformation".} -proc SystemTimeToFileTime*(lpSystemTime: LPSYSTEMTIME, lpFileTime: LPFILETIME): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "SystemTimeToFileTime".} -proc FileTimeToLocalFileTime*(FileTime: LPFILETIME, - lpLocalFileTime: LPFILETIME): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "FileTimeToLocalFileTime".} -proc LocalFileTimeToFileTime*(lpLocalFileTime: LPFILETIME, - lpFileTime: LPFILETIME): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "LocalFileTimeToFileTime".} -proc FileTimeToSystemTime*(lpFileTime: LPFILETIME, lpSystemTime: LPSYSTEMTIME): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "FileTimeToSystemTime".} -proc CompareFileTime*(lpFileTime1: LPFILETIME, lpFileTime2: LPFILETIME): LONG{. - stdcall, dynlib: "kernel32", importc: "CompareFileTime".} -proc FileTimeToDosDateTime*(lpFileTime: LPFILETIME, lpFatDate: LPWORD, - lpFatTime: LPWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "FileTimeToDosDateTime".} -proc DosDateTimeToFileTime*(wFatDate: int16, wFatTime: int16, - lpFileTime: LPFILETIME): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "DosDateTimeToFileTime".} -proc GetTickCount*(): DWORD{.stdcall, dynlib: "kernel32", - importc: "GetTickCount".} -proc SetSystemTimeAdjustment*(dwTimeAdjustment: DWORD, - bTimeAdjustmentDisabled: WINBOOL): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "SetSystemTimeAdjustment".} -proc GetSystemTimeAdjustment*(lpTimeAdjustment: PDWORD, lpTimeIncrement: PDWORD, - lpTimeAdjustmentDisabled: PWINBOOL): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetSystemTimeAdjustment".} -proc CreatePipe*(hReadPipe: PHANDLE, hWritePipe: PHANDLE, - lpPipeAttributes: LPSECURITY_ATTRIBUTES, nSize: DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "CreatePipe".} -proc ConnectNamedPipe*(hNamedPipe: HANDLE, lpOverlapped: LPOVERLAPPED): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "ConnectNamedPipe".} -proc DisconnectNamedPipe*(hNamedPipe: HANDLE): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "DisconnectNamedPipe".} -proc SetNamedPipeHandleState*(hNamedPipe: HANDLE, lpMode: LPDWORD, - lpMaxCollectionCount: LPDWORD, - lpCollectDataTimeout: LPDWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "SetNamedPipeHandleState".} -proc GetNamedPipeInfo*(hNamedPipe: HANDLE, lpFlags: LPDWORD, - lpOutBufferSize: LPDWORD, lpInBufferSize: LPDWORD, - lpMaxInstances: LPDWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetNamedPipeInfo".} -proc PeekNamedPipe*(hNamedPipe: HANDLE, lpBuffer: LPVOID, nBufferSize: DWORD, - lpBytesRead: LPDWORD, lpTotalBytesAvail: LPDWORD, - lpBytesLeftThisMessage: LPDWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "PeekNamedPipe".} -proc TransactNamedPipe*(hNamedPipe: HANDLE, lpInBuffer: LPVOID, - nInBufferSize: DWORD, lpOutBuffer: LPVOID, - nOutBufferSize: DWORD, lpBytesRead: LPDWORD, - lpOverlapped: LPOVERLAPPED): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "TransactNamedPipe".} -proc GetMailslotInfo*(hMailslot: HANDLE, lpMaxMessageSize: LPDWORD, - lpNextSize: LPDWORD, lpMessageCount: LPDWORD, - lpReadTimeout: LPDWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetMailslotInfo".} -proc SetMailslotInfo*(hMailslot: HANDLE, lReadTimeout: DWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "SetMailslotInfo".} -proc MapViewOfFile*(hFileMappingObject: HANDLE, dwDesiredAccess: DWORD, - dwFileOffsetHigh: DWORD, dwFileOffsetLow: DWORD, - dwNumberOfBytesToMap: DWORD): LPVOID{.stdcall, - dynlib: "kernel32", importc: "MapViewOfFile".} -proc FlushViewOfFile*(lpBaseAddress: LPCVOID, dwNumberOfBytesToFlush: DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "FlushViewOfFile".} -proc UnmapViewOfFile*(lpBaseAddress: LPVOID): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "UnmapViewOfFile".} -proc OpenFile*(lpFileName: LPCSTR, lpReOpenBuff: LPOFSTRUCT, uStyle: WINUINT): HFILE{. - stdcall, dynlib: "kernel32", importc: "OpenFile".} -proc lopen*(lpPathName: LPCSTR, iReadWrite: int32): HFILE{.stdcall, - dynlib: "kernel32", importc: "_lopen".} -proc lcreat*(lpPathName: LPCSTR, iAttribute: int32): HFILE{.stdcall, - dynlib: "kernel32", importc: "_lcreat".} -proc lread*(hFile: HFILE, lpBuffer: LPVOID, uBytes: WINUINT): WINUINT{.stdcall, - dynlib: "kernel32", importc: "_lread".} -proc lwrite*(hFile: HFILE, lpBuffer: LPCSTR, uBytes: WINUINT): WINUINT{.stdcall, - dynlib: "kernel32", importc: "_lwrite".} -proc hread*(hFile: HFILE, lpBuffer: LPVOID, lBytes: int32): int32{.stdcall, - dynlib: "kernel32", importc: "_hread".} -proc hwrite*(hFile: HFILE, lpBuffer: LPCSTR, lBytes: int32): int32{.stdcall, - dynlib: "kernel32", importc: "_hwrite".} -proc lclose*(file: HFILE): HFILE{.stdcall, dynlib: "kernel32", - importc: "_lclose".} -proc llseek*(file: HFILE, lOffset: LONG, iOrigin: int32): LONG{.stdcall, - dynlib: "kernel32", importc: "_llseek".} -proc IsTextUnicode*(lpBuffer: LPVOID, cb: int32, lpi: LPINT): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "IsTextUnicode".} -proc TlsAlloc*(): DWORD{.stdcall, dynlib: "kernel32", importc: "TlsAlloc".} -proc TlsGetValue*(dwTlsIndex: DWORD): LPVOID{.stdcall, dynlib: "kernel32", - importc: "TlsGetValue".} -proc TlsSetValue*(dwTlsIndex: DWORD, lpTlsValue: LPVOID): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "TlsSetValue".} -proc TlsFree*(dwTlsIndex: DWORD): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "TlsFree".} -proc SleepEx*(dwMilliseconds: DWORD, bAlertable: WINBOOL): DWORD{.stdcall, - dynlib: "kernel32", importc: "SleepEx".} -proc WaitForSingleObjectEx*(hHandle: HANDLE, dwMilliseconds: DWORD, - bAlertable: WINBOOL): DWORD{.stdcall, - dynlib: "kernel32", importc: "WaitForSingleObjectEx".} -proc WaitForMultipleObjectsEx*(nCount: DWORD, lpHandles: LPHANDLE, - bWaitAll: WINBOOL, dwMilliseconds: DWORD, - bAlertable: WINBOOL): DWORD{.stdcall, - dynlib: "kernel32", importc: "WaitForMultipleObjectsEx".} -proc ReadFileEx*(hFile: HANDLE, lpBuffer: LPVOID, nNumberOfBytesToRead: DWORD, - lpOverlapped: LPOVERLAPPED, - lpCompletionRoutine: LPOVERLAPPED_COMPLETION_ROUTINE): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "ReadFileEx".} -proc WriteFileEx*(hFile: HANDLE, lpBuffer: LPCVOID, - nNumberOfBytesToWrite: DWORD, lpOverlapped: LPOVERLAPPED, - lpCompletionRoutine: LPOVERLAPPED_COMPLETION_ROUTINE): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "WriteFileEx".} -proc BackupRead*(hFile: HANDLE, lpBuffer: LPBYTE, nNumberOfBytesToRead: DWORD, - lpNumberOfBytesRead: LPDWORD, bAbort: WINBOOL, - bProcessSecurity: WINBOOL, lpContext: var LPVOID): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "BackupRead".} -proc BackupSeek*(hFile: HANDLE, dwLowBytesToSeek: DWORD, - dwHighBytesToSeek: DWORD, lpdwLowByteSeeked: LPDWORD, - lpdwHighByteSeeked: LPDWORD, lpContext: var LPVOID): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "BackupSeek".} -proc BackupWrite*(hFile: HANDLE, lpBuffer: LPBYTE, nNumberOfBytesToWrite: DWORD, - lpNumberOfBytesWritten: LPDWORD, bAbort: WINBOOL, - bProcessSecurity: WINBOOL, lpContext: var LPVOID): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "BackupWrite".} -proc SetProcessShutdownParameters*(dwLevel: DWORD, dwFlags: DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "SetProcessShutdownParameters".} -proc GetProcessShutdownParameters*(lpdwLevel: LPDWORD, lpdwFlags: LPDWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetProcessShutdownParameters".} -proc SetFileApisToOEM*(){.stdcall, dynlib: "kernel32", - importc: "SetFileApisToOEM".} -proc SetFileApisToANSI*(){.stdcall, dynlib: "kernel32", - importc: "SetFileApisToANSI".} -proc AreFileApisANSI*(): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "AreFileApisANSI".} -proc CloseEventLog*(hEventLog: HANDLE): WINBOOL{.stdcall, dynlib: "advapi32", - importc: "CloseEventLog".} -proc DeregisterEventSource*(hEventLog: HANDLE): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "DeregisterEventSource".} -proc NotifyChangeEventLog*(hEventLog: HANDLE, hEvent: HANDLE): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "NotifyChangeEventLog".} -proc GetNumberOfEventLogRecords*(hEventLog: HANDLE, NumberOfRecords: PDWORD): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "GetNumberOfEventLogRecords".} -proc GetOldestEventLogRecord*(hEventLog: HANDLE, OldestRecord: PDWORD): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "GetOldestEventLogRecord".} -proc DuplicateToken*(ExistingTokenHandle: HANDLE, - ImpersonationLevel: SECURITY_IMPERSONATION_LEVEL, - DuplicateTokenHandle: PHANDLE): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "DuplicateToken".} -proc GetKernelObjectSecurity*(Handle: HANDLE, - RequestedInformation: SECURITY_INFORMATION, - pSecurityDescriptor: PSECURITY_DESCRIPTOR, - nLength: DWORD, lpnLengthNeeded: LPDWORD): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "GetKernelObjectSecurity".} -proc ImpersonateNamedPipeClient*(hNamedPipe: HANDLE): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "ImpersonateNamedPipeClient".} -proc ImpersonateLoggedOnUser*(hToken: HANDLE): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "ImpersonateLoggedOnUser".} -proc ImpersonateSelf*(ImpersonationLevel: SECURITY_IMPERSONATION_LEVEL): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "ImpersonateSelf".} -proc RevertToSelf*(): WINBOOL{.stdcall, dynlib: "advapi32", - importc: "RevertToSelf".} -proc SetThreadToken*(Thread: PHANDLE, Token: HANDLE): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "SetThreadToken".} -proc OpenProcessToken*(ProcessHandle: HANDLE, DesiredAccess: DWORD, - TokenHandle: PHANDLE): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "OpenProcessToken".} -proc OpenThreadToken*(ThreadHandle: HANDLE, DesiredAccess: DWORD, - OpenAsSelf: WINBOOL, TokenHandle: PHANDLE): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "OpenThreadToken".} -proc GetTokenInformation*(TokenHandle: HANDLE, - TokenInformationClass: TOKEN_INFORMATION_CLASS, - TokenInformation: LPVOID, - TokenInformationLength: DWORD, ReturnLength: PDWORD): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "GetTokenInformation".} -proc SetTokenInformation*(TokenHandle: HANDLE, - TokenInformationClass: TOKEN_INFORMATION_CLASS, - TokenInformation: LPVOID, - TokenInformationLength: DWORD): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "SetTokenInformation".} -proc AdjustTokenPrivileges*(TokenHandle: HANDLE, DisableAllPrivileges: WINBOOL, - NewState: PTOKEN_PRIVILEGES, BufferLength: DWORD, - PreviousState: PTOKEN_PRIVILEGES, - ReturnLength: PDWORD): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "AdjustTokenPrivileges".} -proc AdjustTokenGroups*(TokenHandle: HANDLE, ResetToDefault: WINBOOL, - NewState: PTOKEN_GROUPS, BufferLength: DWORD, - PreviousState: PTOKEN_GROUPS, ReturnLength: PDWORD): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "AdjustTokenGroups".} -proc PrivilegeCheck*(ClientToken: HANDLE, RequiredPrivileges: PPRIVILEGE_SET, - pfResult: LPBOOL): WINBOOL{.stdcall, dynlib: "advapi32", - importc: "PrivilegeCheck".} -proc IsValidSid*(pSid: PSID): WINBOOL{.stdcall, dynlib: "advapi32", - importc: "IsValidSid".} -proc EqualSid*(pSid1: PSID, pSid2: PSID): WINBOOL{.stdcall, dynlib: "advapi32", - importc: "EqualSid".} -proc EqualPrefixSid*(pSid1: PSID, pSid2: PSID): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "EqualPrefixSid".} -proc GetSidLengthRequired*(nSubAuthorityCount: UCHAR): DWORD{.stdcall, - dynlib: "advapi32", importc: "GetSidLengthRequired".} -proc AllocateAndInitializeSid*(pIdentifierAuthority: PSID_IDENTIFIER_AUTHORITY, - nSubAuthorityCount: int8, nSubAuthority0: DWORD, - nSubAuthority1: DWORD, nSubAuthority2: DWORD, - nSubAuthority3: DWORD, nSubAuthority4: DWORD, - nSubAuthority5: DWORD, nSubAuthority6: DWORD, - nSubAuthority7: DWORD, pSid: var PSID): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "AllocateAndInitializeSid".} -proc FreeSid*(pSid: PSID): PVOID{.stdcall, dynlib: "advapi32", - importc: "FreeSid".} -proc InitializeSid*(Sid: PSID, pIdentifierAuthority: PSID_IDENTIFIER_AUTHORITY, - nSubAuthorityCount: int8): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "InitializeSid".} -proc GetSidIdentifierAuthority*(pSid: PSID): PSID_IDENTIFIER_AUTHORITY{.stdcall, - dynlib: "advapi32", importc: "GetSidIdentifierAuthority".} -proc GetSidSubAuthority*(pSid: PSID, nSubAuthority: DWORD): PDWORD{.stdcall, - dynlib: "advapi32", importc: "GetSidSubAuthority".} -proc GetSidSubAuthorityCount*(pSid: PSID): PUCHAR{.stdcall, dynlib: "advapi32", - importc: "GetSidSubAuthorityCount".} -proc GetLengthSid*(pSid: PSID): DWORD{.stdcall, dynlib: "advapi32", - importc: "GetLengthSid".} -proc CopySid*(nDestinationSidLength: DWORD, pDestinationSid: PSID, - pSourceSid: PSID): WINBOOL{.stdcall, dynlib: "advapi32", - importc: "CopySid".} -proc AreAllAccessesGranted*(GrantedAccess: DWORD, DesiredAccess: DWORD): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "AreAllAccessesGranted".} -proc AreAnyAccessesGranted*(GrantedAccess: DWORD, DesiredAccess: DWORD): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "AreAnyAccessesGranted".} -proc MapGenericMask*(AccessMask: PDWORD, GenericMapping: PGENERIC_MAPPING){. - stdcall, dynlib: "advapi32", importc: "MapGenericMask".} -proc IsValidAcl*(pAcl: PACL): WINBOOL{.stdcall, dynlib: "advapi32", - importc: "IsValidAcl".} -proc InitializeAcl*(pAcl: PACL, nAclLength: DWORD, dwAclRevision: DWORD): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "InitializeAcl".} -proc GetAclInformation*(pAcl: PACL, pAclInformation: LPVOID, - nAclInformationLength: DWORD, - dwAclInformationClass: ACL_INFORMATION_CLASS): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "GetAclInformation".} -proc SetAclInformation*(pAcl: PACL, pAclInformation: LPVOID, - nAclInformationLength: DWORD, - dwAclInformationClass: ACL_INFORMATION_CLASS): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "SetAclInformation".} -proc AddAce*(pAcl: PACL, dwAceRevision: DWORD, dwStartingAceIndex: DWORD, - pAceList: LPVOID, nAceListLength: DWORD): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "AddAce".} -proc DeleteAce*(pAcl: PACL, dwAceIndex: DWORD): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "DeleteAce".} -proc GetAce*(pAcl: PACL, dwAceIndex: DWORD, pAce: var LPVOID): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "GetAce".} -proc AddAccessAllowedAce*(pAcl: PACL, dwAceRevision: DWORD, AccessMask: DWORD, - pSid: PSID): WINBOOL{.stdcall, dynlib: "advapi32", - importc: "AddAccessAllowedAce".} -proc AddAccessDeniedAce*(pAcl: PACL, dwAceRevision: DWORD, AccessMask: DWORD, - pSid: PSID): WINBOOL{.stdcall, dynlib: "advapi32", - importc: "AddAccessDeniedAce".} -proc AddAuditAccessAce*(pAcl: PACL, dwAceRevision: DWORD, dwAccessMask: DWORD, - pSid: PSID, bAuditSuccess: WINBOOL, - bAuditFailure: WINBOOL): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "AddAuditAccessAce".} -proc FindFirstFreeAce*(pAcl: PACL, pAce: var LPVOID): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "FindFirstFreeAce".} -proc InitializeSecurityDescriptor*(pSecurityDescriptor: PSECURITY_DESCRIPTOR, - dwRevision: DWORD): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "InitializeSecurityDescriptor".} -proc IsValidSecurityDescriptor*(pSecurityDescriptor: PSECURITY_DESCRIPTOR): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "IsValidSecurityDescriptor".} -proc GetSecurityDescriptorLength*(pSecurityDescriptor: PSECURITY_DESCRIPTOR): DWORD{. - stdcall, dynlib: "advapi32", importc: "GetSecurityDescriptorLength".} -proc GetSecurityDescriptorControl*(pSecurityDescriptor: PSECURITY_DESCRIPTOR, - pControl: PSECURITY_DESCRIPTOR_CONTROL, - lpdwRevision: LPDWORD): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "GetSecurityDescriptorControl".} -proc SetSecurityDescriptorDacl*(pSecurityDescriptor: PSECURITY_DESCRIPTOR, - bDaclPresent: WINBOOL, pDacl: PACL, - bDaclDefaulted: WINBOOL): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "SetSecurityDescriptorDacl".} -proc GetSecurityDescriptorDacl*(pSecurityDescriptor: PSECURITY_DESCRIPTOR, - lpbDaclPresent: LPBOOL, pDacl: var PACL, - lpbDaclDefaulted: LPBOOL): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "GetSecurityDescriptorDacl".} -proc SetSecurityDescriptorSacl*(pSecurityDescriptor: PSECURITY_DESCRIPTOR, - bSaclPresent: WINBOOL, pSacl: PACL, - bSaclDefaulted: WINBOOL): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "SetSecurityDescriptorSacl".} -proc GetSecurityDescriptorSacl*(pSecurityDescriptor: PSECURITY_DESCRIPTOR, - lpbSaclPresent: LPBOOL, pSacl: var PACL, - lpbSaclDefaulted: LPBOOL): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "GetSecurityDescriptorSacl".} -proc SetSecurityDescriptorOwner*(pSecurityDescriptor: PSECURITY_DESCRIPTOR, - pOwner: PSID, bOwnerDefaulted: WINBOOL): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "SetSecurityDescriptorOwner".} -proc GetSecurityDescriptorOwner*(pSecurityDescriptor: PSECURITY_DESCRIPTOR, - pOwner: var PSID, lpbOwnerDefaulted: LPBOOL): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "GetSecurityDescriptorOwner".} -proc SetSecurityDescriptorGroup*(pSecurityDescriptor: PSECURITY_DESCRIPTOR, - pGroup: PSID, bGroupDefaulted: WINBOOL): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "SetSecurityDescriptorGroup".} -proc GetSecurityDescriptorGroup*(pSecurityDescriptor: PSECURITY_DESCRIPTOR, - pGroup: var PSID, lpbGroupDefaulted: LPBOOL): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "GetSecurityDescriptorGroup".} -proc CreatePrivateObjectSecurity*(ParentDescriptor: PSECURITY_DESCRIPTOR, - CreatorDescriptor: PSECURITY_DESCRIPTOR, - NewDescriptor: var PSECURITY_DESCRIPTOR, - IsDirectoryObject: WINBOOL, Token: HANDLE, - GenericMapping: PGENERIC_MAPPING): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "CreatePrivateObjectSecurity".} -proc SetPrivateObjectSecurity*(SecurityInformation: SECURITY_INFORMATION, - ModificationDescriptor: PSECURITY_DESCRIPTOR, - ObjectsSecurityDescriptor: var PSECURITY_DESCRIPTOR, - GenericMapping: PGENERIC_MAPPING, Token: HANDLE): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "SetPrivateObjectSecurity".} -proc GetPrivateObjectSecurity*(ObjectDescriptor: PSECURITY_DESCRIPTOR, - SecurityInformation: SECURITY_INFORMATION, - ResultantDescriptor: PSECURITY_DESCRIPTOR, - DescriptorLength: DWORD, ReturnLength: PDWORD): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "GetPrivateObjectSecurity".} -proc DestroyPrivateObjectSecurity*(ObjectDescriptor: PSECURITY_DESCRIPTOR): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "DestroyPrivateObjectSecurity".} -proc MakeSelfRelativeSD*(pAbsoluteSecurityDescriptor: PSECURITY_DESCRIPTOR, - pSelfRelativeSecurityDescriptor: PSECURITY_DESCRIPTOR, - lpdwBufferLength: LPDWORD): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "MakeSelfRelativeSD".} -proc MakeAbsoluteSD*(pSelfRelativeSecurityDescriptor: PSECURITY_DESCRIPTOR, - pAbsoluteSecurityDescriptor: PSECURITY_DESCRIPTOR, - lpdwAbsoluteSecurityDescriptorSize: LPDWORD, pDacl: PACL, - lpdwDaclSize: LPDWORD, pSacl: PACL, lpdwSaclSize: LPDWORD, - pOwner: PSID, lpdwOwnerSize: LPDWORD, pPrimaryGroup: PSID, - lpdwPrimaryGroupSize: LPDWORD): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "MakeAbsoluteSD".} -proc SetKernelObjectSecurity*(Handle: HANDLE, - SecurityInformation: SECURITY_INFORMATION, - SecurityDescriptor: PSECURITY_DESCRIPTOR): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "SetKernelObjectSecurity".} -proc FindNextChangeNotification*(hChangeHandle: HANDLE): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "FindNextChangeNotification".} -proc FindCloseChangeNotification*(hChangeHandle: HANDLE): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "FindCloseChangeNotification".} -proc VirtualLock*(lpAddress: LPVOID, dwSize: SIZE_T): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "VirtualLock".} -proc VirtualLock*(lpAddress: LPVOID, dwSize: DWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "VirtualLock", deprecated.} -proc VirtualUnlock*(lpAddress: LPVOID, dwSize: SIZE_T): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "VirtualUnlock".} -proc VirtualUnlock*(lpAddress: LPVOID, dwSize: DWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "VirtualUnlock", deprecated.} -proc MapViewOfFileEx*(hFileMappingObject: HANDLE, dwDesiredAccess: DWORD, - dwFileOffsetHigh: DWORD, dwFileOffsetLow: DWORD, - dwNumberOfBytesToMap: DWORD, lpBaseAddress: LPVOID): LPVOID{. - stdcall, dynlib: "kernel32", importc: "MapViewOfFileEx".} -proc SetPriorityClass*(hProcess: HANDLE, dwPriorityClass: DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "SetPriorityClass".} -proc GetPriorityClass*(hProcess: HANDLE): DWORD{.stdcall, dynlib: "kernel32", - importc: "GetPriorityClass".} -proc IsBadReadPtr*(lp: pointer, ucb: WINUINT): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "IsBadReadPtr".} -proc IsBadWritePtr*(lp: LPVOID, ucb: WINUINT): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "IsBadWritePtr".} -proc IsBadHugeReadPtr*(lp: pointer, ucb: WINUINT): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "IsBadHugeReadPtr".} -proc IsBadHugeWritePtr*(lp: LPVOID, ucb: WINUINT): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "IsBadHugeWritePtr".} -proc IsBadCodePtr*(lpfn: FARPROC): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "IsBadCodePtr".} -proc AllocateLocallyUniqueId*(Luid: PLUID): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "AllocateLocallyUniqueId".} -proc QueryPerformanceCounter*(lpPerformanceCount: PLARGE_INTEGER): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "QueryPerformanceCounter".} -proc QueryPerformanceFrequency*(lpFrequency: PLARGE_INTEGER): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "QueryPerformanceFrequency".} -proc ActivateKeyboardLayout*(hkl: HKL, Flags: WINUINT): WINBOOL{.stdcall, - dynlib: "user32", importc: "ActivateKeyboardLayout".} -proc UnloadKeyboardLayout*(hkl: HKL): WINBOOL{.stdcall, dynlib: "user32", - importc: "UnloadKeyboardLayout".} -proc GetKeyboardLayoutList*(nBuff: int32, lpList: var HKL): int32{.stdcall, - dynlib: "user32", importc: "GetKeyboardLayoutList".} -proc GetKeyboardLayout*(dwLayout: DWORD): HKL{.stdcall, dynlib: "user32", - importc: "GetKeyboardLayout".} -proc OpenInputDesktop*(dwFlags: DWORD, fInherit: WINBOOL, dwDesiredAccess: DWORD): HDESK{. - stdcall, dynlib: "user32", importc: "OpenInputDesktop".} -proc EnumDesktopWindows*(hDesktop: HDESK, lpfn: ENUMWINDOWSPROC, lp: LPARAM): WINBOOL{. - stdcall, dynlib: "user32", importc: "EnumDesktopWindows".} -proc SwitchDesktop*(hDesktop: HDESK): WINBOOL{.stdcall, dynlib: "user32", - importc: "SwitchDesktop".} -proc SetThreadDesktop*(hDesktop: HDESK): WINBOOL{.stdcall, dynlib: "user32", - importc: "SetThreadDesktop".} -proc CloseDesktop*(hDesktop: HDESK): WINBOOL{.stdcall, dynlib: "user32", - importc: "CloseDesktop".} -proc GetThreadDesktop*(dwThreadId: DWORD): HDESK{.stdcall, dynlib: "user32", - importc: "GetThreadDesktop".} -proc CloseWindowStation*(hWinSta: HWINSTA): WINBOOL{.stdcall, dynlib: "user32", - importc: "CloseWindowStation".} -proc SetProcessWindowStation*(hWinSta: HWINSTA): WINBOOL{.stdcall, - dynlib: "user32", importc: "SetProcessWindowStation".} -proc GetProcessWindowStation*(): HWINSTA{.stdcall, dynlib: "user32", - importc: "GetProcessWindowStation".} -proc SetUserObjectSecurity*(hObj: HANDLE, pSIRequested: PSECURITY_INFORMATION, - pSID: PSECURITY_DESCRIPTOR): WINBOOL{.stdcall, - dynlib: "user32", importc: "SetUserObjectSecurity".} -proc GetUserObjectSecurity*(hObj: HANDLE, pSIRequested: PSECURITY_INFORMATION, - pSID: PSECURITY_DESCRIPTOR, nLength: DWORD, - lpnLengthNeeded: LPDWORD): WINBOOL{.stdcall, - dynlib: "user32", importc: "GetUserObjectSecurity".} -proc TranslateMessage*(lpMsg: LPMSG): WINBOOL{.stdcall, dynlib: "user32", - importc: "TranslateMessage".} -proc SetMessageQueue*(cMessagesMax: int32): WINBOOL{.stdcall, dynlib: "user32", - importc: "SetMessageQueue".} -proc RegisterHotKey*(wnd: HWND, anID: int32, fsModifiers: WINUINT, vk: WINUINT): WINBOOL{. - stdcall, dynlib: "user32", importc: "RegisterHotKey".} -proc UnregisterHotKey*(wnd: HWND, anID: int32): WINBOOL{.stdcall, - dynlib: "user32", importc: "UnregisterHotKey".} -proc ExitWindowsEx*(uFlags: WINUINT, dwReserved: DWORD): WINBOOL{.stdcall, - dynlib: "user32", importc: "ExitWindowsEx".} -proc SwapMouseButton*(fSwap: WINBOOL): WINBOOL{.stdcall, dynlib: "user32", - importc: "SwapMouseButton".} -proc GetMessagePos*(): DWORD{.stdcall, dynlib: "user32", - importc: "GetMessagePos".} -proc GetMessageTime*(): LONG{.stdcall, dynlib: "user32", - importc: "GetMessageTime".} -proc GetMessageExtraInfo*(): LONG{.stdcall, dynlib: "user32", - importc: "GetMessageExtraInfo".} -proc SetMessageExtraInfo*(lp: LPARAM): LPARAM{.stdcall, dynlib: "user32", - importc: "SetMessageExtraInfo".} -proc BroadcastSystemMessage*(para1: DWORD, para2: LPDWORD, para3: WINUINT, - para4: WPARAM, para5: LPARAM): int32{.stdcall, - dynlib: "user32", importc: "BroadcastSystemMessage".} -proc AttachThreadInput*(idAttach: DWORD, idAttachTo: DWORD, fAttach: WINBOOL): WINBOOL{. - stdcall, dynlib: "user32", importc: "AttachThreadInput".} -proc ReplyMessage*(lResult: LRESULT): WINBOOL{.stdcall, dynlib: "user32", - importc: "ReplyMessage".} -proc WaitMessage*(): WINBOOL{.stdcall, dynlib: "user32", importc: "WaitMessage".} -proc WaitForInputIdle*(hProcess: HANDLE, dwMilliseconds: DWORD): DWORD{.stdcall, - dynlib: "user32", importc: "WaitForInputIdle".} -proc PostQuitMessage*(nExitCode: int32){.stdcall, dynlib: "user32", - importc: "PostQuitMessage".} -proc InSendMessage*(): WINBOOL{.stdcall, dynlib: "user32", - importc: "InSendMessage".} -proc GetDoubleClickTime*(): WINUINT{.stdcall, dynlib: "user32", - importc: "GetDoubleClickTime".} -proc SetDoubleClickTime*(para1: WINUINT): WINBOOL{.stdcall, dynlib: "user32", - importc: "SetDoubleClickTime".} -proc IsWindow*(wnd: HWND): WINBOOL{.stdcall, dynlib: "user32", - importc: "IsWindow".} -proc IsMenu*(menu: HMENU): WINBOOL{.stdcall, dynlib: "user32", - importc: "IsMenu".} -proc IsChild*(hWndParent: HWND, wnd: HWND): WINBOOL{.stdcall, dynlib: "user32", - importc: "IsChild".} -proc DestroyWindow*(wnd: HWND): WINBOOL{.stdcall, dynlib: "user32", - importc: "DestroyWindow".} -proc ShowWindow*(wnd: HWND, nCmdShow: int32): WINBOOL{.stdcall, - dynlib: "user32", importc: "ShowWindow".} -proc ShowWindowAsync*(wnd: HWND, nCmdShow: int32): WINBOOL{.stdcall, - dynlib: "user32", importc: "ShowWindowAsync".} -proc FlashWindow*(wnd: HWND, bInvert: WINBOOL): WINBOOL{.stdcall, - dynlib: "user32", importc: "FlashWindow".} -proc ShowOwnedPopups*(wnd: HWND, fShow: WINBOOL): WINBOOL{.stdcall, - dynlib: "user32", importc: "ShowOwnedPopups".} -proc OpenIcon*(wnd: HWND): WINBOOL{.stdcall, dynlib: "user32", - importc: "OpenIcon".} -proc CloseWindow*(wnd: HWND): WINBOOL{.stdcall, dynlib: "user32", - importc: "CloseWindow".} -proc MoveWindow*(wnd: HWND, X: int32, Y: int32, nWidth: int32, nHeight: int32, - bRepaint: WINBOOL): WINBOOL{.stdcall, dynlib: "user32", - importc: "MoveWindow".} -proc SetWindowPos*(wnd: HWND, hWndInsertAfter: HWND, X: int32, Y: int32, - cx: int32, cy: int32, uFlags: WINUINT): WINBOOL{.stdcall, - dynlib: "user32", importc: "SetWindowPos".} -proc GetWindowPlacement*(wnd: HWND, lpwndpl: var WINDOWPLACEMENT): WINBOOL{. - stdcall, dynlib: "user32", importc: "GetWindowPlacement".} -proc SetWindowPlacement*(wnd: HWND, lpwndpl: var WINDOWPLACEMENT): WINBOOL{. - stdcall, dynlib: "user32", importc: "SetWindowPlacement".} -proc GetWindowPlacement*(wnd: HWND, lpwndpl: PWINDOWPLACEMENT): WINBOOL{. - stdcall, dynlib: "user32", importc: "GetWindowPlacement".} -proc SetWindowPlacement*(wnd: HWND, lpwndpl: PWINDOWPLACEMENT): WINBOOL{. - stdcall, dynlib: "user32", importc: "SetWindowPlacement".} -proc BeginDeferWindowPos*(nNumWindows: int32): HDWP{.stdcall, dynlib: "user32", - importc: "BeginDeferWindowPos".} -proc DeferWindowPos*(hWinPosInfo: HDWP, wnd: HWND, hWndInsertAfter: HWND, - x: int32, y: int32, cx: int32, cy: int32, uFlags: WINUINT): HDWP{. - stdcall, dynlib: "user32", importc: "DeferWindowPos".} -proc EndDeferWindowPos*(hWinPosInfo: HDWP): WINBOOL{.stdcall, dynlib: "user32", - importc: "EndDeferWindowPos".} -proc IsWindowVisible*(wnd: HWND): WINBOOL{.stdcall, dynlib: "user32", - importc: "IsWindowVisible".} -proc IsIconic*(wnd: HWND): WINBOOL{.stdcall, dynlib: "user32", - importc: "IsIconic".} -proc AnyPopup*(): WINBOOL{.stdcall, dynlib: "user32", importc: "AnyPopup".} -proc BringWindowToTop*(wnd: HWND): WINBOOL{.stdcall, dynlib: "user32", - importc: "BringWindowToTop".} -proc IsZoomed*(wnd: HWND): WINBOOL{.stdcall, dynlib: "user32", - importc: "IsZoomed".} -proc EndDialog*(hDlg: HWND, nResult: int32): WINBOOL{.stdcall, dynlib: "user32", - importc: "EndDialog".} -proc GetDlgItem*(hDlg: HWND, nIDDlgItem: int32): HWND{.stdcall, - dynlib: "user32", importc: "GetDlgItem".} -proc SetDlgItemInt*(hDlg: HWND, nIDDlgItem: int32, uValue: WINUINT, - bSigned: WINBOOL): WINBOOL{.stdcall, dynlib: "user32", - importc: "SetDlgItemInt".} -proc GetDlgItemInt*(hDlg: HWND, nIDDlgItem: int32, lpTranslated: var WINBOOL, - bSigned: WINBOOL): WINUINT{.stdcall, dynlib: "user32", - importc: "GetDlgItemInt".} -proc CheckDlgButton*(hDlg: HWND, nIDButton: int32, uCheck: WINUINT): WINBOOL{. - stdcall, dynlib: "user32", importc: "CheckDlgButton".} -proc CheckRadioButton*(hDlg: HWND, nIDFirstButton: int32, nIDLastButton: int32, - nIDCheckButton: int32): WINBOOL{.stdcall, - dynlib: "user32", importc: "CheckRadioButton".} -proc IsDlgButtonChecked*(hDlg: HWND, nIDButton: int32): WINUINT{.stdcall, - dynlib: "user32", importc: "IsDlgButtonChecked".} -proc GetNextDlgGroupItem*(hDlg: HWND, hCtl: HWND, bPrevious: WINBOOL): HWND{. - stdcall, dynlib: "user32", importc: "GetNextDlgGroupItem".} -proc GetNextDlgTabItem*(hDlg: HWND, hCtl: HWND, bPrevious: WINBOOL): HWND{. - stdcall, dynlib: "user32", importc: "GetNextDlgTabItem".} -proc GetDlgCtrlID*(wnd: HWND): int32{.stdcall, dynlib: "user32", - importc: "GetDlgCtrlID".} -proc GetDialogBaseUnits*(): int32{.stdcall, dynlib: "user32", - importc: "GetDialogBaseUnits".} -proc OpenClipboard*(hWndNewOwner: HWND): WINBOOL{.stdcall, dynlib: "user32", - importc: "OpenClipboard".} -proc CloseClipboard*(): WINBOOL{.stdcall, dynlib: "user32", - importc: "CloseClipboard".} -proc GetClipboardOwner*(): HWND{.stdcall, dynlib: "user32", - importc: "GetClipboardOwner".} -proc SetClipboardViewer*(hWndNewViewer: HWND): HWND{.stdcall, dynlib: "user32", - importc: "SetClipboardViewer".} -proc GetClipboardViewer*(): HWND{.stdcall, dynlib: "user32", - importc: "GetClipboardViewer".} -proc ChangeClipboardChain*(hWndRemove: HWND, hWndNewNext: HWND): WINBOOL{. - stdcall, dynlib: "user32", importc: "ChangeClipboardChain".} -proc SetClipboardData*(uFormat: WINUINT, hMem: HANDLE): HANDLE{.stdcall, - dynlib: "user32", importc: "SetClipboardData".} -proc GetClipboardData*(uFormat: WINUINT): HANDLE{.stdcall, dynlib: "user32", - importc: "GetClipboardData".} -proc CountClipboardFormats*(): int32{.stdcall, dynlib: "user32", - importc: "CountClipboardFormats".} -proc EnumClipboardFormats*(format: WINUINT): WINUINT{.stdcall, dynlib: "user32", - importc: "EnumClipboardFormats".} -proc EmptyClipboard*(): WINBOOL{.stdcall, dynlib: "user32", - importc: "EmptyClipboard".} -proc IsClipboardFormatAvailable*(format: WINUINT): WINBOOL{.stdcall, - dynlib: "user32", importc: "IsClipboardFormatAvailable".} -proc GetPriorityClipboardFormat*(paFormatPriorityList: var WINUINT, cFormats: int32): int32{. - stdcall, dynlib: "user32", importc: "GetPriorityClipboardFormat".} -proc GetOpenClipboardWindow*(): HWND{.stdcall, dynlib: "user32", - importc: "GetOpenClipboardWindow".} -proc CharNextExA*(CodePage: int16, lpCurrentChar: LPCSTR, dwFlags: DWORD): LPSTR{. - stdcall, dynlib: "user32", importc: "CharNextExA".} -proc CharPrevExA*(CodePage: int16, lpStart: LPCSTR, lpCurrentChar: LPCSTR, - dwFlags: DWORD): LPSTR{.stdcall, dynlib: "user32", - importc: "CharPrevExA".} -proc SetFocus*(wnd: HWND): HWND{.stdcall, dynlib: "user32", importc: "SetFocus".} -proc GetActiveWindow*(): HWND{.stdcall, dynlib: "user32", - importc: "GetActiveWindow".} -proc GetFocus*(): HWND{.stdcall, dynlib: "user32", importc: "GetFocus".} -proc GetKBCodePage*(): WINUINT{.stdcall, dynlib: "user32", importc: "GetKBCodePage".} -proc GetKeyState*(nVirtKey: int32): SHORT{.stdcall, dynlib: "user32", - importc: "GetKeyState".} -proc GetAsyncKeyState*(vKey: int32): SHORT{.stdcall, dynlib: "user32", - importc: "GetAsyncKeyState".} -proc GetKeyboardState*(lpKeyState: PBYTE): WINBOOL{.stdcall, dynlib: "user32", - importc: "GetKeyboardState".} -proc SetKeyboardState*(lpKeyState: LPBYTE): WINBOOL{.stdcall, dynlib: "user32", - importc: "SetKeyboardState".} -proc GetKeyboardType*(nTypeFlag: int32): int32{.stdcall, dynlib: "user32", - importc: "GetKeyboardType".} -proc ToAscii*(uVirtKey: WINUINT, uScanCode: WINUINT, lpKeyState: PBYTE, - lpChar: LPWORD, uFlags: WINUINT): int32{.stdcall, dynlib: "user32", - importc: "ToAscii".} -proc ToAsciiEx*(uVirtKey: WINUINT, uScanCode: WINUINT, lpKeyState: PBYTE, - lpChar: LPWORD, uFlags: WINUINT, dwhkl: HKL): int32{.stdcall, - dynlib: "user32", importc: "ToAsciiEx".} -proc ToUnicode*(wVirtKey: WINUINT, wScanCode: WINUINT, lpKeyState: PBYTE, - pwszBuff: LPWSTR, cchBuff: int32, wFlags: WINUINT): int32{.stdcall, - dynlib: "user32", importc: "ToUnicode".} -proc OemKeyScan*(wOemChar: int16): DWORD{.stdcall, dynlib: "user32", - importc: "OemKeyScan".} -proc keybd_event*(bVk: int8, bScan: int8, dwFlags: DWORD, dwExtraInfo: DWORD){. - stdcall, dynlib: "user32", importc: "keybd_event".} -proc mouse_event*(dwFlags: DWORD, dx: DWORD, dy: DWORD, cButtons: DWORD, - dwExtraInfo: DWORD){.stdcall, dynlib: "user32", - importc: "mouse_event".} -proc GetInputState*(): WINBOOL{.stdcall, dynlib: "user32", - importc: "GetInputState".} -proc GetQueueStatus*(flags: WINUINT): DWORD{.stdcall, dynlib: "user32", - importc: "GetQueueStatus".} -proc GetCapture*(): HWND{.stdcall, dynlib: "user32", importc: "GetCapture".} -proc SetCapture*(wnd: HWND): HWND{.stdcall, dynlib: "user32", - importc: "SetCapture".} -proc ReleaseCapture*(): WINBOOL{.stdcall, dynlib: "user32", - importc: "ReleaseCapture".} -proc MsgWaitForMultipleObjects*(nCount: DWORD, pHandles: LPHANDLE, - fWaitAll: WINBOOL, dwMilliseconds: DWORD, - dwWakeMask: DWORD): DWORD{.stdcall, - dynlib: "user32", importc: "MsgWaitForMultipleObjects".} -proc SetTimer*(wnd: HWND, nIDEvent: WINUINT, uElapse: WINUINT, lpTimerFunc: TIMERPROC): WINUINT{. - stdcall, dynlib: "user32", importc: "SetTimer".} -proc KillTimer*(wnd: HWND, uIDEvent: WINUINT): WINBOOL{.stdcall, dynlib: "user32", - importc: "KillTimer".} -proc IsWindowUnicode*(wnd: HWND): WINBOOL{.stdcall, dynlib: "user32", - importc: "IsWindowUnicode".} -proc EnableWindow*(wnd: HWND, bEnable: WINBOOL): WINBOOL{.stdcall, - dynlib: "user32", importc: "EnableWindow".} -proc IsWindowEnabled*(wnd: HWND): WINBOOL{.stdcall, dynlib: "user32", - importc: "IsWindowEnabled".} -proc DestroyAcceleratorTable*(hAccel: HACCEL): WINBOOL{.stdcall, - dynlib: "user32", importc: "DestroyAcceleratorTable".} -proc GetSystemMetrics*(nIndex: int32): int32{.stdcall, dynlib: "user32", - importc: "GetSystemMetrics".} -proc GetMenu*(wnd: HWND): HMENU{.stdcall, dynlib: "user32", importc: "GetMenu".} -proc SetMenu*(wnd: HWND, menu: HMENU): WINBOOL{.stdcall, dynlib: "user32", - importc: "SetMenu".} -proc HiliteMenuItem*(wnd: HWND, menu: HMENU, uIDHiliteItem: WINUINT, - uHilite: WINUINT): WINBOOL{.stdcall, dynlib: "user32", - importc: "HiliteMenuItem".} -proc GetMenuState*(menu: HMENU, uId: WINUINT, uFlags: WINUINT): WINUINT{.stdcall, - dynlib: "user32", importc: "GetMenuState".} -proc DrawMenuBar*(wnd: HWND): WINBOOL{.stdcall, dynlib: "user32", - importc: "DrawMenuBar".} -proc GetSystemMenu*(wnd: HWND, bRevert: WINBOOL): HMENU{.stdcall, - dynlib: "user32", importc: "GetSystemMenu".} -proc CreateMenu*(): HMENU{.stdcall, dynlib: "user32", importc: "CreateMenu".} -proc CreatePopupMenu*(): HMENU{.stdcall, dynlib: "user32", - importc: "CreatePopupMenu".} -proc DestroyMenu*(menu: HMENU): WINBOOL{.stdcall, dynlib: "user32", - importc: "DestroyMenu".} -proc CheckMenuItem*(menu: HMENU, uIDCheckItem: WINUINT, uCheck: WINUINT): DWORD{. - stdcall, dynlib: "user32", importc: "CheckMenuItem".} -proc EnableMenuItem*(menu: HMENU, uIDEnableItem: WINUINT, uEnable: WINUINT): WINBOOL{. - stdcall, dynlib: "user32", importc: "EnableMenuItem".} -proc GetSubMenu*(menu: HMENU, nPos: int32): HMENU{.stdcall, dynlib: "user32", - importc: "GetSubMenu".} -proc GetMenuItemID*(menu: HMENU, nPos: int32): WINUINT{.stdcall, dynlib: "user32", - importc: "GetMenuItemID".} -proc GetMenuItemCount*(menu: HMENU): int32{.stdcall, dynlib: "user32", - importc: "GetMenuItemCount".} -proc RemoveMenu*(menu: HMENU, uPosition: WINUINT, uFlags: WINUINT): WINBOOL{.stdcall, - dynlib: "user32", importc: "RemoveMenu".} -proc DeleteMenu*(menu: HMENU, uPosition: WINUINT, uFlags: WINUINT): WINBOOL{.stdcall, - dynlib: "user32", importc: "DeleteMenu".} -proc SetMenuItemBitmaps*(menu: HMENU, uPosition: WINUINT, uFlags: WINUINT, - hBitmapUnchecked: HBITMAP, hBitmapChecked: HBITMAP): WINBOOL{. - stdcall, dynlib: "user32", importc: "SetMenuItemBitmaps".} -proc GetMenuCheckMarkDimensions*(): LONG{.stdcall, dynlib: "user32", - importc: "GetMenuCheckMarkDimensions".} -proc TrackPopupMenu*(menu: HMENU, uFlags: WINUINT, x: int32, y: int32, - nReserved: int32, wnd: HWND, prcRect: var RECT): WINBOOL{. - stdcall, dynlib: "user32", importc: "TrackPopupMenu".} -proc GetMenuDefaultItem*(menu: HMENU, fByPos: WINUINT, gmdiFlags: WINUINT): WINUINT{. - stdcall, dynlib: "user32", importc: "GetMenuDefaultItem".} -proc SetMenuDefaultItem*(menu: HMENU, uItem: WINUINT, fByPos: WINUINT): WINBOOL{. - stdcall, dynlib: "user32", importc: "SetMenuDefaultItem".} -proc GetMenuItemRect*(wnd: HWND, menu: HMENU, uItem: WINUINT, lprcItem: LPRECT): WINBOOL{. - stdcall, dynlib: "user32", importc: "GetMenuItemRect".} -proc MenuItemFromPoint*(wnd: HWND, menu: HMENU, ptScreen: POINT): int32{. - stdcall, dynlib: "user32", importc: "MenuItemFromPoint".} -proc DragObject*(para1: HWND, para2: HWND, para3: WINUINT, para4: DWORD, - para5: HCURSOR): DWORD{.stdcall, dynlib: "user32", - importc: "DragObject".} -proc DragDetect*(wnd: HWND, pt: POINT): WINBOOL{.stdcall, dynlib: "user32", - importc: "DragDetect".} -proc DrawIcon*(hDC: HDC, X: int32, Y: int32, icon: HICON): WINBOOL{.stdcall, - dynlib: "user32", importc: "DrawIcon".} -proc UpdateWindow*(wnd: HWND): WINBOOL{.stdcall, dynlib: "user32", - importc: "UpdateWindow".} -proc SetActiveWindow*(wnd: HWND): HWND{.stdcall, dynlib: "user32", - importc: "SetActiveWindow".} -proc GetForegroundWindow*(): HWND{.stdcall, dynlib: "user32", - importc: "GetForegroundWindow".} -proc PaintDesktop*(hdc: HDC): WINBOOL{.stdcall, dynlib: "user32", - importc: "PaintDesktop".} -proc SetForegroundWindow*(wnd: HWND): WINBOOL{.stdcall, dynlib: "user32", - importc: "SetForegroundWindow".} -proc WindowFromDC*(hDC: HDC): HWND{.stdcall, dynlib: "user32", - importc: "WindowFromDC".} -proc GetDC*(wnd: HWND): HDC{.stdcall, dynlib: "user32", importc: "GetDC".} -proc GetDCEx*(wnd: HWND, hrgnClip: HRGN, flags: DWORD): HDC{.stdcall, - dynlib: "user32", importc: "GetDCEx".} -proc GetWindowDC*(wnd: HWND): HDC{.stdcall, dynlib: "user32", - importc: "GetWindowDC".} -proc ReleaseDC*(wnd: HWND, hDC: HDC): int32{.stdcall, dynlib: "user32", - importc: "ReleaseDC".} -proc BeginPaint*(wnd: HWND, lpPaint: LPPAINTSTRUCT): HDC{.stdcall, - dynlib: "user32", importc: "BeginPaint".} -proc EndPaint*(wnd: HWND, lpPaint: LPPAINTSTRUCT): WINBOOL{.stdcall, - dynlib: "user32", importc: "EndPaint".} -proc GetUpdateRect*(wnd: HWND, lpRect: LPRECT, bErase: WINBOOL): WINBOOL{. - stdcall, dynlib: "user32", importc: "GetUpdateRect".} -proc GetUpdateRgn*(wnd: HWND, hRgn: HRGN, bErase: WINBOOL): int32{.stdcall, - dynlib: "user32", importc: "GetUpdateRgn".} -proc SetWindowRgn*(wnd: HWND, hRgn: HRGN, bRedraw: WINBOOL): int32{.stdcall, - dynlib: "user32", importc: "SetWindowRgn".} -proc GetWindowRgn*(wnd: HWND, hRgn: HRGN): int32{.stdcall, dynlib: "user32", - importc: "GetWindowRgn".} -proc ExcludeUpdateRgn*(hDC: HDC, wnd: HWND): int32{.stdcall, dynlib: "user32", - importc: "ExcludeUpdateRgn".} -proc InvalidateRect*(wnd: HWND, lpRect: var RECT, bErase: WINBOOL): WINBOOL{. - stdcall, dynlib: "user32", importc: "InvalidateRect".} -proc InvalidateRect*(wnd: HWND, lpRect: LPRECT, bErase: WINBOOL): WINBOOL{. - stdcall, dynlib: "user32", importc: "InvalidateRect".} -proc ValidateRect*(wnd: HWND, lpRect: var RECT): WINBOOL{.stdcall, - dynlib: "user32", importc: "ValidateRect".} -proc ValidateRect*(wnd: HWND, lpRect: LPRECT): WINBOOL{.stdcall, - dynlib: "user32", importc: "ValidateRect".} -proc InvalidateRgn*(wnd: HWND, hRgn: HRGN, bErase: WINBOOL): WINBOOL{.stdcall, - dynlib: "user32", importc: "InvalidateRgn".} -proc ValidateRgn*(wnd: HWND, hRgn: HRGN): WINBOOL{.stdcall, dynlib: "user32", - importc: "ValidateRgn".} -proc RedrawWindow*(wnd: HWND, lprcUpdate: var RECT, hrgnUpdate: HRGN, - flags: WINUINT): WINBOOL{.stdcall, dynlib: "user32", - importc: "RedrawWindow".} -proc RedrawWindow*(wnd: HWND, lprcUpdate: LPRECT, hrgnUpdate: HRGN, flags: WINUINT): WINBOOL{. - stdcall, dynlib: "user32", importc: "RedrawWindow".} -proc LockWindowUpdate*(hWndLock: HWND): WINBOOL{.stdcall, dynlib: "user32", - importc: "LockWindowUpdate".} -proc ScrollWindow*(wnd: HWND, XAmount: int32, YAmount: int32, lpRect: var RECT, - lpClipRect: var RECT): WINBOOL{.stdcall, dynlib: "user32", - importc: "ScrollWindow".} -proc ScrollDC*(hDC: HDC, dx: int32, dy: int32, lprcScroll: var RECT, - lprcClip: var RECT, hrgnUpdate: HRGN, lprcUpdate: LPRECT): WINBOOL{. - stdcall, dynlib: "user32", importc: "ScrollDC".} -proc ScrollWindowEx*(wnd: HWND, dx: int32, dy: int32, prcScroll: var RECT, - prcClip: var RECT, hrgnUpdate: HRGN, prcUpdate: LPRECT, - flags: WINUINT): int32{.stdcall, dynlib: "user32", - importc: "ScrollWindowEx".} -proc SetScrollPos*(wnd: HWND, nBar: int32, nPos: int32, bRedraw: WINBOOL): int32{. - stdcall, dynlib: "user32", importc: "SetScrollPos".} -proc GetScrollPos*(wnd: HWND, nBar: int32): int32{.stdcall, dynlib: "user32", - importc: "GetScrollPos".} -proc SetScrollRange*(wnd: HWND, nBar: int32, nMinPos: int32, nMaxPos: int32, - bRedraw: WINBOOL): WINBOOL{.stdcall, dynlib: "user32", - importc: "SetScrollRange".} -proc GetScrollRange*(wnd: HWND, nBar: int32, lpMinPos: LPINT, lpMaxPos: LPINT): WINBOOL{. - stdcall, dynlib: "user32", importc: "GetScrollRange".} -proc ShowScrollBar*(wnd: HWND, wBar: int32, bShow: WINBOOL): WINBOOL{.stdcall, - dynlib: "user32", importc: "ShowScrollBar".} -proc EnableScrollBar*(wnd: HWND, wSBflags: WINUINT, wArrows: WINUINT): WINBOOL{. - stdcall, dynlib: "user32", importc: "EnableScrollBar".} -proc GetClientRect*(wnd: HWND, lpRect: LPRECT): WINBOOL{.stdcall, - dynlib: "user32", importc: "GetClientRect".} -proc GetWindowRect*(wnd: HWND, lpRect: LPRECT): WINBOOL{.stdcall, - dynlib: "user32", importc: "GetWindowRect".} -proc AdjustWindowRect*(lpRect: LPRECT, dwStyle: DWORD, bMenu: WINBOOL): WINBOOL{. - stdcall, dynlib: "user32", importc: "AdjustWindowRect".} -proc AdjustWindowRectEx*(lpRect: LPRECT, dwStyle: DWORD, bMenu: WINBOOL, - dwExStyle: DWORD): WINBOOL{.stdcall, dynlib: "user32", - importc: "AdjustWindowRectEx".} -proc SetWindowContextHelpId*(para1: HWND, para2: DWORD): WINBOOL{.stdcall, - dynlib: "user32", importc: "SetWindowContextHelpId".} -proc GetWindowContextHelpId*(para1: HWND): DWORD{.stdcall, dynlib: "user32", - importc: "GetWindowContextHelpId".} -proc SetMenuContextHelpId*(para1: HMENU, para2: DWORD): WINBOOL{.stdcall, - dynlib: "user32", importc: "SetMenuContextHelpId".} -proc GetMenuContextHelpId*(para1: HMENU): DWORD{.stdcall, dynlib: "user32", - importc: "GetMenuContextHelpId".} -proc MessageBeep*(uType: WINUINT): WINBOOL{.stdcall, dynlib: "user32", - importc: "MessageBeep".} -proc ShowCursor*(bShow: WINBOOL): int32{.stdcall, dynlib: "user32", - importc: "ShowCursor".} -proc SetCursorPos*(X: int32, Y: int32): WINBOOL{.stdcall, dynlib: "user32", - importc: "SetCursorPos".} -proc SetCursor*(cursor: HCURSOR): HCURSOR{.stdcall, dynlib: "user32", - importc: "SetCursor".} -proc GetCursorPos*(lpPoint: LPPOINT): WINBOOL{.stdcall, dynlib: "user32", - importc: "GetCursorPos".} -proc ClipCursor*(lpRect: LPRECT): WINBOOL{.stdcall, dynlib: "user32", - importc: "ClipCursor".} -proc GetClipCursor*(lpRect: LPRECT): WINBOOL{.stdcall, dynlib: "user32", - importc: "GetClipCursor".} -proc GetCursor*(): HCURSOR{.stdcall, dynlib: "user32", importc: "GetCursor".} -proc CreateCaret*(wnd: HWND, hBitmap: HBITMAP, nWidth: int32, nHeight: int32): WINBOOL{. - stdcall, dynlib: "user32", importc: "CreateCaret".} -proc GetCaretBlinkTime*(): WINUINT{.stdcall, dynlib: "user32", - importc: "GetCaretBlinkTime".} -proc SetCaretBlinkTime*(uMSeconds: WINUINT): WINBOOL{.stdcall, dynlib: "user32", - importc: "SetCaretBlinkTime".} -proc DestroyCaret*(): WINBOOL{.stdcall, dynlib: "user32", - importc: "DestroyCaret".} -proc HideCaret*(wnd: HWND): WINBOOL{.stdcall, dynlib: "user32", - importc: "HideCaret".} -proc ShowCaret*(wnd: HWND): WINBOOL{.stdcall, dynlib: "user32", - importc: "ShowCaret".} -proc SetCaretPos*(X: int32, Y: int32): WINBOOL{.stdcall, dynlib: "user32", - importc: "SetCaretPos".} -proc GetCaretPos*(lpPoint: LPPOINT): WINBOOL{.stdcall, dynlib: "user32", - importc: "GetCaretPos".} -proc ClientToScreen*(wnd: HWND, lpPoint: LPPOINT): WINBOOL{.stdcall, - dynlib: "user32", importc: "ClientToScreen".} -proc ScreenToClient*(wnd: HWND, lpPoint: LPPOINT): WINBOOL{.stdcall, - dynlib: "user32", importc: "ScreenToClient".} -proc MapWindowPoints*(hWndFrom: HWND, hWndTo: HWND, lpPoints: LPPOINT, - cPoints: WINUINT): int32{.stdcall, dynlib: "user32", - importc: "MapWindowPoints".} -proc WindowFromPoint*(Point: POINT): HWND{.stdcall, dynlib: "user32", - importc: "WindowFromPoint".} -proc ChildWindowFromPoint*(hWndParent: HWND, Point: POINT): HWND{.stdcall, - dynlib: "user32", importc: "ChildWindowFromPoint".} -proc GetSysColor*(nIndex: int32): DWORD{.stdcall, dynlib: "user32", - importc: "GetSysColor".} -proc GetSysColorBrush*(nIndex: int32): HBRUSH{.stdcall, dynlib: "user32", - importc: "GetSysColorBrush".} -proc SetSysColors*(cElements: int32, lpaElements: var WINT, - lpaRgbValues: var COLORREF): WINBOOL{.stdcall, - dynlib: "user32", importc: "SetSysColors".} -proc DrawFocusRect*(hDC: HDC, lprc: var RECT): WINBOOL{.stdcall, - dynlib: "user32", importc: "DrawFocusRect".} -proc FillRect*(hDC: HDC, lprc: var RECT, hbr: HBRUSH): int32{.stdcall, - dynlib: "user32", importc: "FillRect".} -proc FrameRect*(hDC: HDC, lprc: var RECT, hbr: HBRUSH): int32{.stdcall, - dynlib: "user32", importc: "FrameRect".} -proc InvertRect*(hDC: HDC, lprc: var RECT): WINBOOL{.stdcall, dynlib: "user32", - importc: "InvertRect".} -proc SetRect*(lprc: LPRECT, xLeft: int32, yTop: int32, xRight: int32, - yBottom: int32): WINBOOL{.stdcall, dynlib: "user32", - importc: "SetRect".} -proc SetRectEmpty*(lprc: LPRECT): WINBOOL{.stdcall, dynlib: "user32", - importc: "SetRectEmpty".} -proc CopyRect*(lprcDst: LPRECT, lprcSrc: var RECT): WINBOOL{.stdcall, - dynlib: "user32", importc: "CopyRect".} -proc InflateRect*(lprc: LPRECT, dx: int32, dy: int32): WINBOOL{.stdcall, - dynlib: "user32", importc: "InflateRect".} -proc IntersectRect*(lprcDst: LPRECT, lprcSrc1: var RECT, lprcSrc2: var RECT): WINBOOL{. - stdcall, dynlib: "user32", importc: "IntersectRect".} -proc UnionRect*(lprcDst: LPRECT, lprcSrc1: var RECT, lprcSrc2: var RECT): WINBOOL{. - stdcall, dynlib: "user32", importc: "UnionRect".} -proc SubtractRect*(lprcDst: LPRECT, lprcSrc1: var RECT, lprcSrc2: var RECT): WINBOOL{. - stdcall, dynlib: "user32", importc: "SubtractRect".} -proc OffsetRect*(lprc: LPRECT, dx: int32, dy: int32): WINBOOL{.stdcall, - dynlib: "user32", importc: "OffsetRect".} -proc IsRectEmpty*(lprc: var RECT): WINBOOL{.stdcall, dynlib: "user32", - importc: "IsRectEmpty".} -proc EqualRect*(lprc1: var RECT, lprc2: var RECT): WINBOOL{.stdcall, - dynlib: "user32", importc: "EqualRect".} -proc PtInRect*(lprc: var RECT, pt: POINT): WINBOOL{.stdcall, dynlib: "user32", - importc: "PtInRect".} -proc PtInRect*(lprc: LPRECT, pt: POINT): WINBOOL{.stdcall, dynlib: "user32", - importc: "PtInRect".} -proc GetWindowWord*(wnd: HWND, nIndex: int32): int16{.stdcall, - dynlib: "user32", importc: "GetWindowWord".} -proc SetWindowWord*(wnd: HWND, nIndex: int32, wNewWord: int16): int16{.stdcall, - dynlib: "user32", importc: "SetWindowWord".} -proc GetClassWord*(wnd: HWND, nIndex: int32): int16{.stdcall, dynlib: "user32", - importc: "GetClassWord".} -proc SetClassWord*(wnd: HWND, nIndex: int32, wNewWord: int16): int16{.stdcall, - dynlib: "user32", importc: "SetClassWord".} -proc GetDesktopWindow*(): HWND{.stdcall, dynlib: "user32", - importc: "GetDesktopWindow".} -proc GetParent*(wnd: HWND): HWND{.stdcall, dynlib: "user32", - importc: "GetParent".} -proc SetParent*(hWndChild: HWND, hWndNewParent: HWND): HWND{.stdcall, - dynlib: "user32", importc: "SetParent".} -proc EnumChildWindows*(hWndParent: HWND, lpEnumFunc: ENUMWINDOWSPROC, - lp: LPARAM): WINBOOL{.stdcall, dynlib: "user32", - importc: "EnumChildWindows".} -proc EnumWindows*(lpEnumFunc: ENUMWINDOWSPROC, lp: LPARAM): WINBOOL{. - stdcall, dynlib: "user32", importc: "EnumWindows".} -proc EnumThreadWindows*(dwThreadId: DWORD, lpfn: ENUMWINDOWSPROC, lp: LPARAM): WINBOOL{. - stdcall, dynlib: "user32", importc: "EnumThreadWindows".} -proc EnumTaskWindows*(hTask: HWND, lpfn: FARPROC, lp: LPARAM): WINBOOL{. - stdcall, dynlib: "user32", importc: "EnumThreadWindows".} -proc GetTopWindow*(wnd: HWND): HWND{.stdcall, dynlib: "user32", - importc: "GetTopWindow".} -proc GetWindowThreadProcessId*(wnd: HWND, lpdwProcessId: LPDWORD): DWORD{. - stdcall, dynlib: "user32", importc: "GetWindowThreadProcessId".} -proc GetLastActivePopup*(wnd: HWND): HWND{.stdcall, dynlib: "user32", - importc: "GetLastActivePopup".} -proc GetWindow*(wnd: HWND, uCmd: WINUINT): HWND{.stdcall, dynlib: "user32", - importc: "GetWindow".} -proc UnhookWindowsHook*(nCode: int32, pfnFilterProc: HOOKPROC): WINBOOL{. - stdcall, dynlib: "user32", importc: "UnhookWindowsHook".} -proc UnhookWindowsHookEx*(hhk: HHOOK): WINBOOL{.stdcall, dynlib: "user32", - importc: "UnhookWindowsHookEx".} -proc CallNextHookEx*(hhk: HHOOK, nCode: int32, wp: WPARAM, lp: LPARAM): LRESULT{. - stdcall, dynlib: "user32", importc: "CallNextHookEx".} -proc CheckMenuRadioItem*(para1: HMENU, para2: WINUINT, para3: WINUINT, para4: WINUINT, - para5: WINUINT): WINBOOL{.stdcall, dynlib: "user32", - importc: "CheckMenuRadioItem".} -proc CreateCursor*(hInst: HINST, xHotSpot: int32, yHotSpot: int32, - nWidth: int32, nHeight: int32, pvANDPlane: pointer, - pvXORPlane: pointer): HCURSOR{.stdcall, dynlib: "user32", - importc: "CreateCursor".} -proc DestroyCursor*(cursor: HCURSOR): WINBOOL{.stdcall, dynlib: "user32", - importc: "DestroyCursor".} -proc SetSystemCursor*(hcur: HCURSOR, anID: DWORD): WINBOOL{.stdcall, - dynlib: "user32", importc: "SetSystemCursor".} -proc CreateIcon*(hInstance: HINST, nWidth: int32, nHeight: int32, cPlanes: int8, - cBitsPixel: int8, lpbANDbits: var int8, lpbXORbits: var int8): HICON{. - stdcall, dynlib: "user32", importc: "CreateIcon".} -proc DestroyIcon*(icon: HICON): WINBOOL{.stdcall, dynlib: "user32", - importc: "DestroyIcon".} -proc LookupIconIdFromDirectory*(presbits: PBYTE, fIcon: WINBOOL): int32{. - stdcall, dynlib: "user32", importc: "LookupIconIdFromDirectory".} -proc LookupIconIdFromDirectoryEx*(presbits: PBYTE, fIcon: WINBOOL, - cxDesired: int32, cyDesired: int32, - Flags: WINUINT): int32{.stdcall, - dynlib: "user32", importc: "LookupIconIdFromDirectoryEx".} -proc CreateIconFromResource*(presbits: PBYTE, dwResSize: DWORD, fIcon: WINBOOL, - dwVer: DWORD): HICON{.stdcall, dynlib: "user32", - importc: "CreateIconFromResource".} -proc CreateIconFromResourceEx*(presbits: PBYTE, dwResSize: DWORD, - fIcon: WINBOOL, dwVer: DWORD, cxDesired: int32, - cyDesired: int32, Flags: WINUINT): HICON{.stdcall, - dynlib: "user32", importc: "CreateIconFromResourceEx".} -proc CopyImage*(para1: HANDLE, para2: WINUINT, para3: int32, para4: int32, - para5: WINUINT): HICON{.stdcall, dynlib: "user32", - importc: "CopyImage".} -proc CreateIconIndirect*(piconinfo: PICONINFO): HICON{.stdcall, - dynlib: "user32", importc: "CreateIconIndirect".} -proc CopyIcon*(icon: HICON): HICON{.stdcall, dynlib: "user32", - importc: "CopyIcon".} -proc GetIconInfo*(icon: HICON, piconinfo: PICONINFO): WINBOOL{.stdcall, - dynlib: "user32", importc: "GetIconInfo".} -proc MapDialogRect*(hDlg: HWND, lpRect: LPRECT): WINBOOL{.stdcall, - dynlib: "user32", importc: "MapDialogRect".} -proc SetScrollInfo*(para1: HWND, para2: int32, para3: LPCSCROLLINFO, - para4: WINBOOL): int32{.stdcall, dynlib: "user32", - importc: "SetScrollInfo".} -proc GetScrollInfo*(para1: HWND, para2: int32, para3: LPSCROLLINFO): WINBOOL{. - stdcall, dynlib: "user32", importc: "GetScrollInfo".} -proc TranslateMDISysAccel*(hWndClient: HWND, lpMsg: LPMSG): WINBOOL{.stdcall, - dynlib: "user32", importc: "TranslateMDISysAccel".} -proc ArrangeIconicWindows*(wnd: HWND): WINUINT{.stdcall, dynlib: "user32", - importc: "ArrangeIconicWindows".} -proc TileWindows*(hwndParent: HWND, wHow: WINUINT, lpRect: var RECT, cKids: WINUINT, - lpKids: var HWND): int16{.stdcall, dynlib: "user32", - importc: "TileWindows".} -proc CascadeWindows*(hwndParent: HWND, wHow: WINUINT, lpRect: var RECT, - cKids: WINUINT, lpKids: var HWND): int16{.stdcall, - dynlib: "user32", importc: "CascadeWindows".} -proc SetLastErrorEx*(dwErrCode: DWORD, dwType: DWORD){.stdcall, - dynlib: "user32", importc: "SetLastErrorEx".} -proc SetDebugErrorLevel*(dwLevel: DWORD){.stdcall, dynlib: "user32", - importc: "SetDebugErrorLevel".} -proc DrawEdge*(hdc: HDC, qrc: LPRECT, edge: WINUINT, grfFlags: WINUINT): WINBOOL{. - stdcall, dynlib: "user32", importc: "DrawEdge".} -proc DrawFrameControl*(para1: HDC, para2: LPRECT, para3: WINUINT, para4: WINUINT): WINBOOL{. - stdcall, dynlib: "user32", importc: "DrawFrameControl".} -proc DrawCaption*(para1: HWND, para2: HDC, para3: var RECT, para4: WINUINT): WINBOOL{. - stdcall, dynlib: "user32", importc: "DrawCaption".} -proc DrawAnimatedRects*(wnd: HWND, idAni: int32, lprcFrom: var RECT, - lprcTo: var RECT): WINBOOL{.stdcall, dynlib: "user32", - importc: "DrawAnimatedRects".} -proc TrackPopupMenuEx*(para1: HMENU, para2: WINUINT, para3: int32, para4: int32, - para5: HWND, para6: LPTPMPARAMS): WINBOOL{.stdcall, - dynlib: "user32", importc: "TrackPopupMenuEx".} -proc ChildWindowFromPointEx*(para1: HWND, para2: POINT, para3: WINUINT): HWND{. - stdcall, dynlib: "user32", importc: "ChildWindowFromPointEx".} -proc DrawIconEx*(hdc: HDC, xLeft: int32, yTop: int32, icon: HICON, - cxWidth: int32, cyWidth: int32, istepIfAniCur: WINUINT, - hbrFlickerFreeDraw: HBRUSH, diFlags: WINUINT): WINBOOL{.stdcall, - dynlib: "user32", importc: "DrawIconEx".} -proc AnimatePalette*(para1: HPALETTE, para2: WINUINT, para3: WINUINT, - para4: var PALETTEENTRY): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "AnimatePalette".} -proc Arc*(para1: HDC, para2: int32, para3: int32, para4: int32, para5: int32, - para6: int32, para7: int32, para8: int32, para9: int32): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "Arc".} -proc BitBlt*(para1: HDC, para2: int32, para3: int32, para4: int32, para5: int32, - para6: HDC, para7: int32, para8: int32, para9: DWORD): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "BitBlt".} -proc CancelDC*(para1: HDC): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "CancelDC".} -proc Chord*(para1: HDC, para2: int32, para3: int32, para4: int32, para5: int32, - para6: int32, para7: int32, para8: int32, para9: int32): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "Chord".} -proc CloseMetaFile*(para1: HDC): HMETAFILE{.stdcall, dynlib: "gdi32", - importc: "CloseMetaFile".} -proc CombineRgn*(para1: HRGN, para2: HRGN, para3: HRGN, para4: int32): int32{. - stdcall, dynlib: "gdi32", importc: "CombineRgn".} -proc CreateBitmap*(para1: int32, para2: int32, para3: WINUINT, para4: WINUINT, - para5: pointer): HBITMAP{.stdcall, dynlib: "gdi32", - importc: "CreateBitmap".} -proc CreateBitmapIndirect*(para1: var BITMAP): HBITMAP{.stdcall, - dynlib: "gdi32", importc: "CreateBitmapIndirect".} -proc CreateBrushIndirect*(para1: var LOGBRUSH): HBRUSH{.stdcall, - dynlib: "gdi32", importc: "CreateBrushIndirect".} -proc CreateCompatibleBitmap*(para1: HDC, para2: int32, para3: int32): HBITMAP{. - stdcall, dynlib: "gdi32", importc: "CreateCompatibleBitmap".} -proc CreateDiscardableBitmap*(para1: HDC, para2: int32, para3: int32): HBITMAP{. - stdcall, dynlib: "gdi32", importc: "CreateDiscardableBitmap".} -proc CreateCompatibleDC*(para1: HDC): HDC{.stdcall, dynlib: "gdi32", - importc: "CreateCompatibleDC".} -proc CreateDIBitmap*(para1: HDC, para2: var BITMAPINFOHEADER, para3: DWORD, - para4: pointer, para5: var BITMAPINFO, para6: WINUINT): HBITMAP{. - stdcall, dynlib: "gdi32", importc: "CreateDIBitmap".} -proc CreateDIBPatternBrush*(para1: HGLOBAL, para2: WINUINT): HBRUSH{.stdcall, - dynlib: "gdi32", importc: "CreateDIBPatternBrush".} -proc CreateDIBPatternBrushPt*(para1: pointer, para2: WINUINT): HBRUSH{.stdcall, - dynlib: "gdi32", importc: "CreateDIBPatternBrushPt".} -proc CreateEllipticRgn*(para1: int32, para2: int32, para3: int32, para4: int32): HRGN{. - stdcall, dynlib: "gdi32", importc: "CreateEllipticRgn".} -proc CreateEllipticRgnIndirect*(para1: var RECT): HRGN{.stdcall, - dynlib: "gdi32", importc: "CreateEllipticRgnIndirect".} -proc CreateHatchBrush*(para1: int32, para2: COLORREF): HBRUSH{.stdcall, - dynlib: "gdi32", importc: "CreateHatchBrush".} -proc CreatePalette*(para1: var LOGPALETTE): HPALETTE{.stdcall, dynlib: "gdi32", - importc: "CreatePalette".} -proc CreatePen*(para1: int32, para2: int32, para3: COLORREF): HPEN{.stdcall, - dynlib: "gdi32", importc: "CreatePen".} -proc CreatePenIndirect*(para1: var LOGPEN): HPEN{.stdcall, dynlib: "gdi32", - importc: "CreatePenIndirect".} -proc CreatePolyPolygonRgn*(para1: var POINT, para2: var WINT, para3: int32, - para4: int32): HRGN{.stdcall, dynlib: "gdi32", - importc: "CreatePolyPolygonRgn".} -proc CreatePatternBrush*(para1: HBITMAP): HBRUSH{.stdcall, dynlib: "gdi32", - importc: "CreatePatternBrush".} -proc CreateRectRgn*(para1: int32, para2: int32, para3: int32, para4: int32): HRGN{. - stdcall, dynlib: "gdi32", importc: "CreateRectRgn".} -proc CreateRectRgnIndirect*(para1: var RECT): HRGN{.stdcall, dynlib: "gdi32", - importc: "CreateRectRgnIndirect".} -proc CreateRoundRectRgn*(para1: int32, para2: int32, para3: int32, para4: int32, - para5: int32, para6: int32): HRGN{.stdcall, - dynlib: "gdi32", importc: "CreateRoundRectRgn".} -proc CreateSolidBrush*(para1: COLORREF): HBRUSH{.stdcall, dynlib: "gdi32", - importc: "CreateSolidBrush".} -proc DeleteDC*(para1: HDC): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "DeleteDC".} -proc DeleteMetaFile*(para1: HMETAFILE): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "DeleteMetaFile".} -proc DeleteObject*(para1: HGDIOBJ): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "DeleteObject".} -proc DrawEscape*(para1: HDC, para2: int32, para3: int32, para4: LPCSTR): int32{. - stdcall, dynlib: "gdi32", importc: "DrawEscape".} -proc Ellipse*(para1: HDC, para2: int32, para3: int32, para4: int32, para5: int32): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "Ellipse".} -proc EnumObjects*(para1: HDC, para2: int32, para3: ENUMOBJECTSPROC, - para4: LPARAM): int32{.stdcall, dynlib: "gdi32", - importc: "EnumObjects".} -proc EqualRgn*(para1: HRGN, para2: HRGN): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "EqualRgn".} -proc Escape*(para1: HDC, para2: int32, para3: int32, para4: LPCSTR, - para5: LPVOID): int32{.stdcall, dynlib: "gdi32", importc: "Escape".} -proc ExtEscape*(para1: HDC, para2: int32, para3: int32, para4: LPCSTR, - para5: int32, para6: LPSTR): int32{.stdcall, dynlib: "gdi32", - importc: "ExtEscape".} -proc ExcludeClipRect*(para1: HDC, para2: int32, para3: int32, para4: int32, - para5: int32): int32{.stdcall, dynlib: "gdi32", - importc: "ExcludeClipRect".} -proc ExtCreateRegion*(para1: var XFORM, para2: DWORD, para3: var RGNDATA): HRGN{. - stdcall, dynlib: "gdi32", importc: "ExtCreateRegion".} -proc ExtFloodFill*(para1: HDC, para2: int32, para3: int32, para4: COLORREF, - para5: WINUINT): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "ExtFloodFill".} -proc FillRgn*(para1: HDC, para2: HRGN, para3: HBRUSH): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "FillRgn".} -proc FloodFill*(para1: HDC, para2: int32, para3: int32, para4: COLORREF): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "FloodFill".} -proc FrameRgn*(para1: HDC, para2: HRGN, para3: HBRUSH, para4: int32, - para5: int32): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "FrameRgn".} -proc GetROP2*(para1: HDC): int32{.stdcall, dynlib: "gdi32", importc: "GetROP2".} -proc GetAspectRatioFilterEx*(para1: HDC, para2: LPSIZE): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "GetAspectRatioFilterEx".} -proc GetBkColor*(para1: HDC): COLORREF{.stdcall, dynlib: "gdi32", - importc: "GetBkColor".} -proc GetBkMode*(para1: HDC): int32{.stdcall, dynlib: "gdi32", - importc: "GetBkMode".} -proc GetBitmapBits*(para1: HBITMAP, para2: LONG, para3: LPVOID): LONG{.stdcall, - dynlib: "gdi32", importc: "GetBitmapBits".} -proc GetBitmapDimensionEx*(para1: HBITMAP, para2: LPSIZE): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "GetBitmapDimensionEx".} -proc GetBoundsRect*(para1: HDC, para2: LPRECT, para3: WINUINT): WINUINT{.stdcall, - dynlib: "gdi32", importc: "GetBoundsRect".} -proc GetBrushOrgEx*(para1: HDC, para2: LPPOINT): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "GetBrushOrgEx".} -proc GetClipBox*(para1: HDC, para2: LPRECT): int32{.stdcall, dynlib: "gdi32", - importc: "GetClipBox".} -proc GetClipRgn*(para1: HDC, para2: HRGN): int32{.stdcall, dynlib: "gdi32", - importc: "GetClipRgn".} -proc GetMetaRgn*(para1: HDC, para2: HRGN): int32{.stdcall, dynlib: "gdi32", - importc: "GetMetaRgn".} -proc GetCurrentObject*(para1: HDC, para2: WINUINT): HGDIOBJ{.stdcall, - dynlib: "gdi32", importc: "GetCurrentObject".} -proc GetCurrentPositionEx*(para1: HDC, para2: LPPOINT): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "GetCurrentPositionEx".} -proc GetDeviceCaps*(para1: HDC, para2: int32): int32{.stdcall, dynlib: "gdi32", - importc: "GetDeviceCaps".} -proc GetDIBits*(para1: HDC, para2: HBITMAP, para3: WINUINT, para4: WINUINT, - para5: LPVOID, para6: LPBITMAPINFO, para7: WINUINT): int32{. - stdcall, dynlib: "gdi32", importc: "GetDIBits".} -proc GetFontData*(para1: HDC, para2: DWORD, para3: DWORD, para4: LPVOID, - para5: DWORD): DWORD{.stdcall, dynlib: "gdi32", - importc: "GetFontData".} -proc GetGraphicsMode*(para1: HDC): int32{.stdcall, dynlib: "gdi32", - importc: "GetGraphicsMode".} -proc GetMapMode*(para1: HDC): int32{.stdcall, dynlib: "gdi32", - importc: "GetMapMode".} -proc GetMetaFileBitsEx*(para1: HMETAFILE, para2: WINUINT, para3: LPVOID): WINUINT{. - stdcall, dynlib: "gdi32", importc: "GetMetaFileBitsEx".} -proc GetNearestColor*(para1: HDC, para2: COLORREF): COLORREF{.stdcall, - dynlib: "gdi32", importc: "GetNearestColor".} -proc GetNearestPaletteIndex*(para1: HPALETTE, para2: COLORREF): WINUINT{.stdcall, - dynlib: "gdi32", importc: "GetNearestPaletteIndex".} -proc GetObjectType*(h: HGDIOBJ): DWORD{.stdcall, dynlib: "gdi32", - importc: "GetObjectType".} -proc GetPaletteEntries*(para1: HPALETTE, para2: WINUINT, para3: WINUINT, - para4: LPPALETTEENTRY): WINUINT{.stdcall, dynlib: "gdi32", - importc: "GetPaletteEntries".} -proc GetPixel*(para1: HDC, para2: int32, para3: int32): COLORREF{.stdcall, - dynlib: "gdi32", importc: "GetPixel".} -proc GetPixelFormat*(para1: HDC): int32{.stdcall, dynlib: "gdi32", - importc: "GetPixelFormat".} -proc GetPolyFillMode*(para1: HDC): int32{.stdcall, dynlib: "gdi32", - importc: "GetPolyFillMode".} -proc GetRasterizerCaps*(para1: LPRASTERIZER_STATUS, para2: WINUINT): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "GetRasterizerCaps".} -proc GetRegionData*(para1: HRGN, para2: DWORD, para3: LPRGNDATA): DWORD{. - stdcall, dynlib: "gdi32", importc: "GetRegionData".} -proc GetRgnBox*(para1: HRGN, para2: LPRECT): int32{.stdcall, dynlib: "gdi32", - importc: "GetRgnBox".} -proc GetStockObject*(para1: int32): HGDIOBJ{.stdcall, dynlib: "gdi32", - importc: "GetStockObject".} -proc GetStretchBltMode*(para1: HDC): int32{.stdcall, dynlib: "gdi32", - importc: "GetStretchBltMode".} -proc GetSystemPaletteEntries*(para1: HDC, para2: WINUINT, para3: WINUINT, - para4: LPPALETTEENTRY): WINUINT{.stdcall, - dynlib: "gdi32", importc: "GetSystemPaletteEntries".} -proc GetSystemPaletteUse*(para1: HDC): WINUINT{.stdcall, dynlib: "gdi32", - importc: "GetSystemPaletteUse".} -proc GetTextCharacterExtra*(para1: HDC): int32{.stdcall, dynlib: "gdi32", - importc: "GetTextCharacterExtra".} -proc GetTextAlign*(para1: HDC): WINUINT{.stdcall, dynlib: "gdi32", - importc: "GetTextAlign".} -proc GetTextColor*(para1: HDC): COLORREF{.stdcall, dynlib: "gdi32", - importc: "GetTextColor".} -proc GetTextCharset*(hdc: HDC): int32{.stdcall, dynlib: "gdi32", - importc: "GetTextCharset".} -proc GetTextCharsetInfo*(hdc: HDC, lpSig: LPFONTSIGNATURE, dwFlags: DWORD): int32{. - stdcall, dynlib: "gdi32", importc: "GetTextCharsetInfo".} -proc TranslateCharsetInfo*(lpSrc: var DWORD, lpCs: LPCHARSETINFO, dwFlags: DWORD): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "TranslateCharsetInfo".} -proc GetFontLanguageInfo*(para1: HDC): DWORD{.stdcall, dynlib: "gdi32", - importc: "GetFontLanguageInfo".} -proc GetViewportExtEx*(para1: HDC, para2: LPSIZE): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "GetViewportExtEx".} -proc GetViewportOrgEx*(para1: HDC, para2: LPPOINT): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "GetViewportOrgEx".} -proc GetWindowExtEx*(para1: HDC, para2: LPSIZE): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "GetWindowExtEx".} -proc GetWindowOrgEx*(para1: HDC, para2: LPPOINT): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "GetWindowOrgEx".} -proc IntersectClipRect*(para1: HDC, para2: int32, para3: int32, para4: int32, - para5: int32): int32{.stdcall, dynlib: "gdi32", - importc: "IntersectClipRect".} -proc InvertRgn*(para1: HDC, para2: HRGN): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "InvertRgn".} -proc LineDDA*(para1: int32, para2: int32, para3: int32, para4: int32, - para5: LINEDDAPROC, para6: LPARAM): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "LineDDA".} -proc LineTo*(para1: HDC, para2: int32, para3: int32): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "LineTo".} -proc MaskBlt*(para1: HDC, para2: int32, para3: int32, para4: int32, - para5: int32, para6: HDC, para7: int32, para8: int32, - para9: HBITMAP, para10: int32, para11: int32, para12: DWORD): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "MaskBlt".} -proc PlgBlt*(para1: HDC, para2: var POINT, para3: HDC, para4: int32, - para5: int32, para6: int32, para7: int32, para8: HBITMAP, - para9: int32, para10: int32): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "PlgBlt".} -proc OffsetClipRgn*(para1: HDC, para2: int32, para3: int32): int32{.stdcall, - dynlib: "gdi32", importc: "OffsetClipRgn".} -proc OffsetRgn*(para1: HRGN, para2: int32, para3: int32): int32{.stdcall, - dynlib: "gdi32", importc: "OffsetRgn".} -proc PatBlt*(para1: HDC, para2: int32, para3: int32, para4: int32, para5: int32, - para6: DWORD): WINBOOL{.stdcall, dynlib: "gdi32", importc: "PatBlt".} -proc Pie*(para1: HDC, para2: int32, para3: int32, para4: int32, para5: int32, - para6: int32, para7: int32, para8: int32, para9: int32): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "Pie".} -proc PlayMetaFile*(para1: HDC, para2: HMETAFILE): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "PlayMetaFile".} -proc PaintRgn*(para1: HDC, para2: HRGN): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "PaintRgn".} -proc PolyPolygon*(para1: HDC, para2: var POINT, para3: var WINT, para4: int32): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "PolyPolygon".} -proc PtInRegion*(para1: HRGN, para2: int32, para3: int32): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "PtInRegion".} -proc PtVisible*(para1: HDC, para2: int32, para3: int32): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "PtVisible".} -proc RectInRegion*(para1: HRGN, para2: var RECT): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "RectInRegion".} -proc RectVisible*(para1: HDC, para2: var RECT): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "RectVisible".} -proc Rectangle*(para1: HDC, para2: int32, para3: int32, para4: int32, - para5: int32): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "Rectangle".} -proc RestoreDC*(para1: HDC, para2: int32): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "RestoreDC".} -proc RealizePalette*(para1: HDC): WINUINT{.stdcall, dynlib: "gdi32", - importc: "RealizePalette".} -proc RoundRect*(para1: HDC, para2: int32, para3: int32, para4: int32, - para5: int32, para6: int32, para7: int32): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "RoundRect".} -proc ResizePalette*(para1: HPALETTE, para2: WINUINT): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "ResizePalette".} -proc SaveDC*(para1: HDC): int32{.stdcall, dynlib: "gdi32", importc: "SaveDC".} -proc SelectClipRgn*(para1: HDC, para2: HRGN): int32{.stdcall, dynlib: "gdi32", - importc: "SelectClipRgn".} -proc ExtSelectClipRgn*(para1: HDC, para2: HRGN, para3: int32): int32{.stdcall, - dynlib: "gdi32", importc: "ExtSelectClipRgn".} -proc SetMetaRgn*(para1: HDC): int32{.stdcall, dynlib: "gdi32", - importc: "SetMetaRgn".} -proc SelectObject*(para1: HDC, para2: HGDIOBJ): HGDIOBJ{.stdcall, - dynlib: "gdi32", importc: "SelectObject".} -proc SelectPalette*(para1: HDC, para2: HPALETTE, para3: WINBOOL): HPALETTE{. - stdcall, dynlib: "gdi32", importc: "SelectPalette".} -proc SetBkColor*(para1: HDC, para2: COLORREF): COLORREF{.stdcall, - dynlib: "gdi32", importc: "SetBkColor".} -proc SetBkMode*(para1: HDC, para2: int32): int32{.stdcall, dynlib: "gdi32", - importc: "SetBkMode".} -proc SetBitmapBits*(para1: HBITMAP, para2: DWORD, para3: pointer): LONG{. - stdcall, dynlib: "gdi32", importc: "SetBitmapBits".} -proc SetBoundsRect*(para1: HDC, para2: var RECT, para3: WINUINT): WINUINT{.stdcall, - dynlib: "gdi32", importc: "SetBoundsRect".} -proc SetDIBits*(para1: HDC, para2: HBITMAP, para3: WINUINT, para4: WINUINT, - para5: pointer, para6: PBITMAPINFO, para7: WINUINT): int32{. - stdcall, dynlib: "gdi32", importc: "SetDIBits".} -proc SetDIBitsToDevice*(para1: HDC, para2: int32, para3: int32, para4: DWORD, - para5: DWORD, para6: int32, para7: int32, para8: WINUINT, - para9: WINUINT, para10: pointer, para11: var BITMAPINFO, - para12: WINUINT): int32{.stdcall, dynlib: "gdi32", - importc: "SetDIBitsToDevice".} -proc SetMapperFlags*(para1: HDC, para2: DWORD): DWORD{.stdcall, dynlib: "gdi32", - importc: "SetMapperFlags".} -proc SetGraphicsMode*(hdc: HDC, iMode: int32): int32{.stdcall, dynlib: "gdi32", - importc: "SetGraphicsMode".} -proc SetMapMode*(para1: HDC, para2: int32): int32{.stdcall, dynlib: "gdi32", - importc: "SetMapMode".} -proc SetMetaFileBitsEx*(para1: WINUINT, para2: var int8): HMETAFILE{.stdcall, - dynlib: "gdi32", importc: "SetMetaFileBitsEx".} -proc SetPaletteEntries*(para1: HPALETTE, para2: WINUINT, para3: WINUINT, - para4: var PALETTEENTRY): WINUINT{.stdcall, - dynlib: "gdi32", importc: "SetPaletteEntries".} -proc SetPixel*(para1: HDC, para2: int32, para3: int32, para4: COLORREF): COLORREF{. - stdcall, dynlib: "gdi32", importc: "SetPixel".} -proc SetPixelV*(para1: HDC, para2: int32, para3: int32, para4: COLORREF): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "SetPixelV".} -proc SetPolyFillMode*(para1: HDC, para2: int32): int32{.stdcall, - dynlib: "gdi32", importc: "SetPolyFillMode".} -proc StretchBlt*(para1: HDC, para2: int32, para3: int32, para4: int32, - para5: int32, para6: HDC, para7: int32, para8: int32, - para9: int32, para10: int32, para11: DWORD): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "StretchBlt".} -proc SetRectRgn*(para1: HRGN, para2: int32, para3: int32, para4: int32, - para5: int32): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "SetRectRgn".} -proc StretchDIBits*(para1: HDC, para2: int32, para3: int32, para4: int32, - para5: int32, para6: int32, para7: int32, para8: int32, - para9: int32, para10: pointer, para11: var BITMAPINFO, - para12: WINUINT, para13: DWORD): int32{.stdcall, - dynlib: "gdi32", importc: "StretchDIBits".} -proc SetROP2*(para1: HDC, para2: int32): int32{.stdcall, dynlib: "gdi32", - importc: "SetROP2".} -proc SetStretchBltMode*(para1: HDC, para2: int32): int32{.stdcall, - dynlib: "gdi32", importc: "SetStretchBltMode".} -proc SetSystemPaletteUse*(para1: HDC, para2: WINUINT): WINUINT{.stdcall, - dynlib: "gdi32", importc: "SetSystemPaletteUse".} -proc SetTextCharacterExtra*(para1: HDC, para2: int32): int32{.stdcall, - dynlib: "gdi32", importc: "SetTextCharacterExtra".} -proc SetTextColor*(para1: HDC, para2: COLORREF): COLORREF{.stdcall, - dynlib: "gdi32", importc: "SetTextColor".} -proc SetTextAlign*(para1: HDC, para2: WINUINT): WINUINT{.stdcall, dynlib: "gdi32", - importc: "SetTextAlign".} -proc SetTextJustification*(para1: HDC, para2: int32, para3: int32): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "SetTextJustification".} -proc UpdateColors*(para1: HDC): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "UpdateColors".} -proc PlayMetaFileRecord*(para1: HDC, para2: LPHANDLETABLE, para3: LPMETARECORD, - para4: WINUINT): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "PlayMetaFileRecord".} -proc EnumMetaFile*(para1: HDC, para2: HMETAFILE, para3: ENUMMETAFILEPROC, - para4: LPARAM): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "EnumMetaFile".} -proc CloseEnhMetaFile*(para1: HDC): HENHMETAFILE{.stdcall, dynlib: "gdi32", - importc: "CloseEnhMetaFile".} -proc DeleteEnhMetaFile*(para1: HENHMETAFILE): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "DeleteEnhMetaFile".} -proc EnumEnhMetaFile*(para1: HDC, para2: HENHMETAFILE, para3: ENHMETAFILEPROC, - para4: LPVOID, para5: var RECT): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "EnumEnhMetaFile".} -proc GetEnhMetaFileHeader*(para1: HENHMETAFILE, para2: WINUINT, - para3: LPENHMETAHEADER): WINUINT{.stdcall, - dynlib: "gdi32", importc: "GetEnhMetaFileHeader".} -proc GetEnhMetaFilePaletteEntries*(para1: HENHMETAFILE, para2: WINUINT, - para3: LPPALETTEENTRY): WINUINT{.stdcall, - dynlib: "gdi32", importc: "GetEnhMetaFilePaletteEntries".} -proc GetEnhMetaFileBits*(para1: HENHMETAFILE, para2: WINUINT, para3: LPBYTE): WINUINT{. - stdcall, dynlib: "gdi32", importc: "GetEnhMetaFileBits".} -proc GetWinMetaFileBits*(para1: HENHMETAFILE, para2: WINUINT, para3: LPBYTE, - para4: WINT, para5: HDC): WINUINT{.stdcall, - dynlib: "gdi32", importc: "GetWinMetaFileBits".} -proc PlayEnhMetaFile*(para1: HDC, para2: HENHMETAFILE, para3: RECT): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "PlayEnhMetaFile".} -proc PlayEnhMetaFileRecord*(para1: HDC, para2: LPHANDLETABLE, - para3: var ENHMETARECORD, para4: WINUINT): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "PlayEnhMetaFileRecord".} -proc SetEnhMetaFileBits*(para1: WINUINT, para2: var int8): HENHMETAFILE{.stdcall, - dynlib: "gdi32", importc: "SetEnhMetaFileBits".} -proc SetWinMetaFileBits*(para1: WINUINT, para2: var int8, para3: HDC, - para4: var METAFILEPICT): HENHMETAFILE{.stdcall, - dynlib: "gdi32", importc: "SetWinMetaFileBits".} -proc GdiComment*(para1: HDC, para2: WINUINT, para3: var int8): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "GdiComment".} -proc AngleArc*(para1: HDC, para2: int32, para3: int32, para4: DWORD, - para5: float32, para6: float32): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "AngleArc".} -proc PolyPolyline*(para1: HDC, para2: var POINT, para3: var DWORD, para4: DWORD): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "PolyPolyline".} -proc GetWorldTransform*(para1: HDC, para2: LPXFORM): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "GetWorldTransform".} -proc SetWorldTransform*(para1: HDC, para2: var XFORM): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "SetWorldTransform".} -proc ModifyWorldTransform*(para1: HDC, para2: var XFORM, para3: DWORD): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "ModifyWorldTransform".} -proc CombineTransform*(para1: LPXFORM, para2: var XFORM, para3: var XFORM): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "CombineTransform".} -proc CreateDIBSection*(para1: HDC, para2: var BITMAPINFO, para3: WINUINT, - para4: var pointer, para5: HANDLE, para6: DWORD): HBITMAP{. - stdcall, dynlib: "gdi32", importc: "CreateDIBSection".} -proc GetDIBColorTable*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: var RGBQUAD): WINUINT{. - stdcall, dynlib: "gdi32", importc: "GetDIBColorTable".} -proc SetDIBColorTable*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: var RGBQUAD): WINUINT{. - stdcall, dynlib: "gdi32", importc: "SetDIBColorTable".} -proc SetColorAdjustment*(para1: HDC, para2: var COLORADJUSTMENT): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "SetColorAdjustment".} -proc GetColorAdjustment*(para1: HDC, para2: LPCOLORADJUSTMENT): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "GetColorAdjustment".} -proc CreateHalftonePalette*(para1: HDC): HPALETTE{.stdcall, dynlib: "gdi32", - importc: "CreateHalftonePalette".} -proc EndDoc*(para1: HDC): int32{.stdcall, dynlib: "gdi32", importc: "EndDoc".} -proc StartPage*(para1: HDC): int32{.stdcall, dynlib: "gdi32", - importc: "StartPage".} -proc EndPage*(para1: HDC): int32{.stdcall, dynlib: "gdi32", importc: "EndPage".} -proc AbortDoc*(para1: HDC): int32{.stdcall, dynlib: "gdi32", importc: "AbortDoc".} -proc SetAbortProc*(para1: HDC, para2: ABORTPROC): int32{.stdcall, - dynlib: "gdi32", importc: "SetAbortProc".} -proc ArcTo*(para1: HDC, para2: int32, para3: int32, para4: int32, para5: int32, - para6: int32, para7: int32, para8: int32, para9: int32): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "ArcTo".} -proc BeginPath*(para1: HDC): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "BeginPath".} -proc CloseFigure*(para1: HDC): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "CloseFigure".} -proc EndPath*(para1: HDC): WINBOOL{.stdcall, dynlib: "gdi32", importc: "EndPath".} -proc FillPath*(para1: HDC): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "FillPath".} -proc FlattenPath*(para1: HDC): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "FlattenPath".} -proc GetPath*(para1: HDC, para2: LPPOINT, para3: LPBYTE, para4: int32): int32{. - stdcall, dynlib: "gdi32", importc: "GetPath".} -proc PathToRegion*(para1: HDC): HRGN{.stdcall, dynlib: "gdi32", - importc: "PathToRegion".} -proc PolyDraw*(para1: HDC, para2: var POINT, para3: var int8, para4: int32): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "PolyDraw".} -proc SelectClipPath*(para1: HDC, para2: int32): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "SelectClipPath".} -proc SetArcDirection*(para1: HDC, para2: int32): int32{.stdcall, - dynlib: "gdi32", importc: "SetArcDirection".} -proc SetMiterLimit*(para1: HDC, para2: float32, para3: ptr float32): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "SetMiterLimit".} -proc StrokeAndFillPath*(para1: HDC): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "StrokeAndFillPath".} -proc StrokePath*(para1: HDC): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "StrokePath".} -proc WidenPath*(para1: HDC): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "WidenPath".} -proc ExtCreatePen*(para1: DWORD, para2: DWORD, para3: var LOGBRUSH, - para4: DWORD, para5: var DWORD): HPEN{.stdcall, - dynlib: "gdi32", importc: "ExtCreatePen".} -proc GetMiterLimit*(para1: HDC, para2: ptr float32): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "GetMiterLimit".} -proc GetArcDirection*(para1: HDC): int32{.stdcall, dynlib: "gdi32", - importc: "GetArcDirection".} -proc MoveToEx*(para1: HDC, para2: int32, para3: int32, para4: LPPOINT): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "MoveToEx".} -proc CreatePolygonRgn*(para1: var POINT, para2: int32, para3: int32): HRGN{. - stdcall, dynlib: "gdi32", importc: "CreatePolygonRgn".} -proc DPtoLP*(para1: HDC, para2: LPPOINT, para3: int32): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "DPtoLP".} -proc LPtoDP*(para1: HDC, para2: LPPOINT, para3: int32): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "LPtoDP".} -proc Polygon*(para1: HDC, para2: LPPOINT, para3: int32): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "Polygon".} -proc Polyline*(para1: HDC, para2: LPPOINT, para3: int32): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "Polyline".} -proc PolyBezier*(para1: HDC, para2: LPPOINT, para3: DWORD): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "PolyBezier".} -proc PolyBezierTo*(para1: HDC, para2: POINT, para3: DWORD): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "PolyBezierTo".} -proc PolylineTo*(para1: HDC, para2: LPPOINT, para3: DWORD): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "PolylineTo".} -proc SetViewportExtEx*(para1: HDC, para2: int32, para3: int32, para4: LPSIZE): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "SetViewportExtEx".} -proc SetViewportOrgEx*(para1: HDC, para2: int32, para3: int32, para4: LPPOINT): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "SetViewportOrgEx".} -proc SetWindowExtEx*(para1: HDC, para2: int32, para3: int32, para4: LPSIZE): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "SetWindowExtEx".} -proc SetWindowOrgEx*(para1: HDC, para2: int32, para3: int32, para4: LPPOINT): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "SetWindowOrgEx".} -proc OffsetViewportOrgEx*(para1: HDC, para2: int32, para3: int32, para4: LPPOINT): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "OffsetViewportOrgEx".} -proc OffsetWindowOrgEx*(para1: HDC, para2: int32, para3: int32, para4: LPPOINT): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "OffsetWindowOrgEx".} -proc ScaleViewportExtEx*(para1: HDC, para2: int32, para3: int32, para4: int32, - para5: int32, para6: LPSIZE): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "ScaleViewportExtEx".} -proc ScaleWindowExtEx*(para1: HDC, para2: int32, para3: int32, para4: int32, - para5: int32, para6: LPSIZE): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "ScaleWindowExtEx".} -proc SetBitmapDimensionEx*(para1: HBITMAP, para2: int32, para3: int32, - para4: LPSIZE): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "SetBitmapDimensionEx".} -proc SetBrushOrgEx*(para1: HDC, para2: int32, para3: int32, para4: LPPOINT): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "SetBrushOrgEx".} -proc GetDCOrgEx*(para1: HDC, para2: LPPOINT): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "GetDCOrgEx".} -proc FixBrushOrgEx*(para1: HDC, para2: int32, para3: int32, para4: LPPOINT): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "FixBrushOrgEx".} -proc UnrealizeObject*(para1: HGDIOBJ): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "UnrealizeObject".} -proc GdiFlush*(): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GdiFlush".} -proc GdiSetBatchLimit*(para1: DWORD): DWORD{.stdcall, dynlib: "gdi32", - importc: "GdiSetBatchLimit".} -proc GdiGetBatchLimit*(): DWORD{.stdcall, dynlib: "gdi32", - importc: "GdiGetBatchLimit".} -proc SetICMMode*(para1: HDC, para2: int32): int32{.stdcall, dynlib: "gdi32", - importc: "SetICMMode".} -proc CheckColorsInGamut*(para1: HDC, para2: LPVOID, para3: LPVOID, para4: DWORD): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "CheckColorsInGamut".} -proc GetColorSpace*(para1: HDC): HANDLE{.stdcall, dynlib: "gdi32", - importc: "GetColorSpace".} -proc SetColorSpace*(para1: HDC, para2: HCOLORSPACE): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "SetColorSpace".} -proc DeleteColorSpace*(para1: HCOLORSPACE): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "DeleteColorSpace".} -proc GetDeviceGammaRamp*(para1: HDC, para2: LPVOID): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "GetDeviceGammaRamp".} -proc SetDeviceGammaRamp*(para1: HDC, para2: LPVOID): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "SetDeviceGammaRamp".} -proc ColorMatchToTarget*(para1: HDC, para2: HDC, para3: DWORD): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "ColorMatchToTarget".} -proc CreatePropertySheetPageA*(lppsp: LPCPROPSHEETPAGE): HPROPSHEETPAGE{. - stdcall, dynlib: "comctl32", importc: "CreatePropertySheetPageA".} -proc DestroyPropertySheetPage*(hPSPage: HPROPSHEETPAGE): WINBOOL{.stdcall, - dynlib: "comctl32", importc: "DestroyPropertySheetPage".} -proc InitCommonControls*(){.stdcall, dynlib: "comctl32", - importc: "InitCommonControls".} -proc ImageList_AddIcon*(himl: HIMAGELIST, hicon: HICON): int32 -proc ImageList_Create*(cx: int32, cy: int32, flags: WINUINT, cInitial: int32, - cGrow: int32): HIMAGELIST{.stdcall, dynlib: "comctl32", - importc: "ImageList_Create".} -proc ImageList_Destroy*(himl: HIMAGELIST): WINBOOL{.stdcall, dynlib: "comctl32", - importc: "ImageList_Destroy".} -proc ImageList_GetImageCount*(himl: HIMAGELIST): int32{.stdcall, - dynlib: "comctl32", importc: "ImageList_GetImageCount".} -proc ImageList_Add*(himl: HIMAGELIST, hbmImage: HBITMAP, hbmMask: HBITMAP): int32{. - stdcall, dynlib: "comctl32", importc: "ImageList_Add".} -proc ImageList_ReplaceIcon*(himl: HIMAGELIST, i: int32, hicon: HICON): int32{. - stdcall, dynlib: "comctl32", importc: "ImageList_ReplaceIcon".} -proc ImageList_SetBkColor*(himl: HIMAGELIST, clrBk: COLORREF): COLORREF{. - stdcall, dynlib: "comctl32", importc: "ImageList_SetBkColor".} -proc ImageList_GetBkColor*(himl: HIMAGELIST): COLORREF{.stdcall, - dynlib: "comctl32", importc: "ImageList_GetBkColor".} -proc ImageList_SetOverlayImage*(himl: HIMAGELIST, iImage: int32, iOverlay: int32): WINBOOL{. - stdcall, dynlib: "comctl32", importc: "ImageList_SetOverlayImage".} -proc ImageList_Draw*(himl: HIMAGELIST, i: int32, hdcDst: HDC, x: int32, - y: int32, fStyle: WINUINT): WINBOOL{.stdcall, - dynlib: "comctl32", importc: "ImageList_Draw".} -proc ImageList_Replace*(himl: HIMAGELIST, i: int32, hbmImage: HBITMAP, - hbmMask: HBITMAP): WINBOOL{.stdcall, dynlib: "comctl32", - importc: "ImageList_Replace".} -proc ImageList_AddMasked*(himl: HIMAGELIST, hbmImage: HBITMAP, crMask: COLORREF): int32{. - stdcall, dynlib: "comctl32", importc: "ImageList_AddMasked".} -proc ImageList_DrawEx*(himl: HIMAGELIST, i: int32, hdcDst: HDC, x: int32, - y: int32, dx: int32, dy: int32, rgbBk: COLORREF, - rgbFg: COLORREF, fStyle: WINUINT): WINBOOL{.stdcall, - dynlib: "comctl32", importc: "ImageList_DrawEx".} -proc ImageList_Remove*(himl: HIMAGELIST, i: int32): WINBOOL{.stdcall, - dynlib: "comctl32", importc: "ImageList_Remove".} -proc ImageList_GetIcon*(himl: HIMAGELIST, i: int32, flags: WINUINT): HICON{. - stdcall, dynlib: "comctl32", importc: "ImageList_GetIcon".} -proc ImageList_BeginDrag*(himlTrack: HIMAGELIST, iTrack: int32, - dxHotspot: int32, dyHotspot: int32): WINBOOL{.stdcall, - dynlib: "comctl32", importc: "ImageList_BeginDrag".} -proc ImageList_EndDrag*(){.stdcall, dynlib: "comctl32", - importc: "ImageList_EndDrag".} -proc ImageList_DragEnter*(hwndLock: HWND, x: int32, y: int32): WINBOOL{.stdcall, - dynlib: "comctl32", importc: "ImageList_DragEnter".} -proc ImageList_DragLeave*(hwndLock: HWND): WINBOOL{.stdcall, dynlib: "comctl32", - importc: "ImageList_DragLeave".} -proc ImageList_DragMove*(x: int32, y: int32): WINBOOL{.stdcall, - dynlib: "comctl32", importc: "ImageList_DragMove".} -proc ImageList_SetDragCursorImage*(himlDrag: HIMAGELIST, iDrag: int32, - dxHotspot: int32, dyHotspot: int32): WINBOOL{. - stdcall, dynlib: "comctl32", importc: "ImageList_SetDragCursorImage".} -proc ImageList_DragShowNolock*(fShow: WINBOOL): WINBOOL{.stdcall, - dynlib: "comctl32", importc: "ImageList_DragShowNolock".} -proc ImageList_GetDragImage*(ppt: LPPOINT, pptHotspot: LPPOINT): HIMAGELIST{. - stdcall, dynlib: "comctl32", importc: "ImageList_GetDragImage".} -proc ImageList_GetIconSize*(himl: HIMAGELIST, cx: var int32, cy: var int32): WINBOOL{. - stdcall, dynlib: "comctl32", importc: "ImageList_GetIconSize".} -proc ImageList_SetIconSize*(himl: HIMAGELIST, cx: int32, cy: int32): WINBOOL{. - stdcall, dynlib: "comctl32", importc: "ImageList_SetIconSize".} -proc ImageList_GetImageInfo*(himl: HIMAGELIST, i: int32, - pImageInfo: var IMAGEINFO): WINBOOL{.stdcall, - dynlib: "comctl32", importc: "ImageList_GetImageInfo".} -proc ImageList_Merge*(himl1: HIMAGELIST, i1: int32, himl2: HIMAGELIST, - i2: int32, dx: int32, dy: int32): HIMAGELIST{.stdcall, - dynlib: "comctl32", importc: "ImageList_Merge".} -proc ImageList_SetImageCount*(himl: HIMAGELIST, uNewCount: WINUINT): int{.stdcall, - dynlib: "comctl32.dll", importc: "ImageList_SetImageCount".} -proc CreateToolbarEx*(wnd: HWND, ws: DWORD, wID: WINUINT, nBitmaps: int32, - hBMInst: HINST, wBMID: WINUINT, lpButtons: LPCTBBUTTON, - iNumButtons: int32, dxButton: int32, dyButton: int32, - dxBitmap: int32, dyBitmap: int32, uStructSize: WINUINT): HWND{. - stdcall, dynlib: "comctl32", importc: "CreateToolbarEx".} -proc CreateMappedBitmap*(hInstance: HINST, idBitmap: int32, wFlags: WINUINT, - lpColorMap: LPCOLORMAP, iNumMaps: int32): HBITMAP{. - stdcall, dynlib: "comctl32", importc: "CreateMappedBitmap".} -proc MenuHelp*(uMsg: WINUINT, wp: WPARAM, lp: LPARAM, hMainMenu: HMENU, - hInst: HINST, hwndStatus: HWND, lpwIDs: var WINUINT){.stdcall, - dynlib: "comctl32", importc: "MenuHelp".} -proc ShowHideMenuCtl*(wnd: HWND, uFlags: WINUINT, lpInfo: LPINT): WINBOOL{. - stdcall, dynlib: "comctl32", importc: "ShowHideMenuCtl".} -proc GetEffectiveClientRect*(wnd: HWND, lprc: LPRECT, lpInfo: LPINT){.stdcall, - dynlib: "comctl32", importc: "GetEffectiveClientRect".} -proc MakeDragList*(hLB: HWND): WINBOOL{.stdcall, dynlib: "comctl32", - importc: "MakeDragList".} -proc DrawInsert*(handParent: HWND, hLB: HWND, nItem: int32){.stdcall, - dynlib: "comctl32", importc: "DrawInsert".} -proc LBItemFromPt*(hLB: HWND, pt: POINT, bAutoScroll: WINBOOL): int32{.stdcall, - dynlib: "comctl32", importc: "LBItemFromPt".} -proc CreateUpDownControl*(dwStyle: DWORD, x: int32, y: int32, cx: int32, - cy: int32, hParent: HWND, nID: int32, hInst: HINST, - hBuddy: HWND, nUpper: int32, nLower: int32, - nPos: int32): HWND{.stdcall, dynlib: "comctl32", - importc: "CreateUpDownControl".} -proc RegCloseKey*(key: HKEY): LONG{.stdcall, dynlib: "advapi32", - importc: "RegCloseKey".} -proc RegSetKeySecurity*(key: HKEY, SecurityInformation: SECURITY_INFORMATION, - pSecurityDescriptor: PSECURITY_DESCRIPTOR): LONG{. - stdcall, dynlib: "advapi32", importc: "RegSetKeySecurity".} -proc RegFlushKey*(key: HKEY): LONG{.stdcall, dynlib: "advapi32", - importc: "RegFlushKey".} -proc RegGetKeySecurity*(key: HKEY, SecurityInformation: SECURITY_INFORMATION, - pSecurityDescriptor: PSECURITY_DESCRIPTOR, - lpcbSecurityDescriptor: LPDWORD): LONG{.stdcall, - dynlib: "advapi32", importc: "RegGetKeySecurity".} -proc RegNotifyChangeKeyValue*(key: HKEY, bWatchSubtree: WINBOOL, - dwNotifyFilter: DWORD, hEvent: HANDLE, - fAsynchronus: WINBOOL): LONG{.stdcall, - dynlib: "advapi32", importc: "RegNotifyChangeKeyValue".} -proc IsValidCodePage*(CodePage: WINUINT): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "IsValidCodePage".} -proc GetACP*(): WINUINT{.stdcall, dynlib: "kernel32", importc: "GetACP".} -proc GetOEMCP*(): WINUINT{.stdcall, dynlib: "kernel32", importc: "GetOEMCP".} -proc GetCPInfo*(para1: WINUINT, para2: LPCPINFO): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetCPInfo".} -proc IsDBCSLeadByte*(TestChar: int8): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "IsDBCSLeadByte".} -proc IsDBCSLeadByteEx*(CodePage: WINUINT, TestChar: int8): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "IsDBCSLeadByteEx".} -proc MultiByteToWideChar*(CodePage: WINUINT, dwFlags: DWORD, - lpMultiByteStr: LPCSTR, cchMultiByte: int32, - lpWideCharStr: LPWSTR, cchWideChar: int32): int32{. - stdcall, dynlib: "kernel32", importc: "MultiByteToWideChar".} -proc WideCharToMultiByte*(CodePage: WINUINT, dwFlags: DWORD, - lpWideCharStr: LPCWSTR, cchWideChar: int32, - lpMultiByteStr: LPSTR, cchMultiByte: int32, - lpDefaultChar: LPCSTR, lpUsedDefaultChar: LPBOOL): int32{. - stdcall, dynlib: "kernel32", importc: "WideCharToMultiByte".} -proc IsValidLocale*(Locale: LCID, dwFlags: DWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "IsValidLocale".} -proc ConvertDefaultLocale*(Locale: LCID): LCID{.stdcall, dynlib: "kernel32", - importc: "ConvertDefaultLocale".} -proc GetThreadLocale*(): LCID{.stdcall, dynlib: "kernel32", - importc: "GetThreadLocale".} -proc SetThreadLocale*(Locale: LCID): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "SetThreadLocale".} -proc GetSystemDefaultLangID*(): LANGID{.stdcall, dynlib: "kernel32", - importc: "GetSystemDefaultLangID".} -proc GetUserDefaultLangID*(): LANGID{.stdcall, dynlib: "kernel32", - importc: "GetUserDefaultLangID".} -proc GetSystemDefaultLCID*(): LCID{.stdcall, dynlib: "kernel32", - importc: "GetSystemDefaultLCID".} -proc GetUserDefaultLCID*(): LCID{.stdcall, dynlib: "kernel32", - importc: "GetUserDefaultLCID".} -proc ReadConsoleOutputAttribute*(hConsoleOutput: HANDLE, lpAttribute: LPWORD, - nLength: DWORD, dwReadCoord: COORD, - lpNumberOfAttrsRead: LPDWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "ReadConsoleOutputAttribute".} -proc WriteConsoleOutputAttribute*(hConsoleOutput: HANDLE, - lpAttribute: var int16, nLength: DWORD, - dwWriteCoord: COORD, - lpNumberOfAttrsWritten: LPDWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "WriteConsoleOutputAttribute".} -proc FillConsoleOutputAttribute*(hConsoleOutput: HANDLE, wAttribute: int16, - nLength: DWORD, dwWriteCoord: COORD, - lpNumberOfAttrsWritten: LPDWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "FillConsoleOutputAttribute".} -proc GetConsoleMode*(hConsoleHandle: HANDLE, lpMode: LPDWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetConsoleMode".} -proc GetNumberOfConsoleInputEvents*(hConsoleInput: HANDLE, - lpNumberOfEvents: PDWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetNumberOfConsoleInputEvents".} -proc GetConsoleScreenBufferInfo*(hConsoleOutput: HANDLE, - lpConsoleScreenBufferInfo: PCONSOLE_SCREEN_BUFFER_INFO): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetConsoleScreenBufferInfo".} -proc GetLargestConsoleWindowSize*(hConsoleOutput: HANDLE): COORD -proc GetConsoleCursorInfo*(hConsoleOutput: HANDLE, - lpConsoleCursorInfo: PCONSOLE_CURSOR_INFO): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetConsoleCursorInfo".} -proc GetNumberOfConsoleMouseButtons*(lpNumberOfMouseButtons: LPDWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetNumberOfConsoleMouseButtons".} -proc SetConsoleMode*(hConsoleHandle: HANDLE, dwMode: DWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "SetConsoleMode".} -proc SetConsoleActiveScreenBuffer*(hConsoleOutput: HANDLE): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "SetConsoleActiveScreenBuffer".} -proc FlushConsoleInputBuffer*(hConsoleInput: HANDLE): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "FlushConsoleInputBuffer".} -proc SetConsoleScreenBufferSize*(hConsoleOutput: HANDLE, dwSize: COORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "SetConsoleScreenBufferSize".} -proc SetConsoleCursorPosition*(hConsoleOutput: HANDLE, dwCursorPosition: COORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "SetConsoleCursorPosition".} -proc SetConsoleCursorInfo*(hConsoleOutput: HANDLE, - lpConsoleCursorInfo: PCONSOLE_CURSOR_INFO): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "SetConsoleCursorInfo".} -proc SetConsoleWindowInfo*(hConsoleOutput: HANDLE, bAbsolute: WINBOOL, - lpConsoleWindow: var SMALL_RECT): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "SetConsoleWindowInfo".} -proc SetConsoleTextAttribute*(hConsoleOutput: HANDLE, wAttributes: int16): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "SetConsoleTextAttribute".} -proc SetConsoleCtrlHandler*(HandlerRoutine: PHANDLER_ROUTINE, Add: WINBOOL): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "SetConsoleCtrlHandler".} -proc GenerateConsoleCtrlEvent*(dwCtrlEvent: DWORD, dwProcessGroupId: DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GenerateConsoleCtrlEvent".} -proc AllocConsole*(): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "AllocConsole".} -proc FreeConsole*(): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "FreeConsole".} -proc CreateConsoleScreenBuffer*(dwDesiredAccess: DWORD, dwShareMode: DWORD, - lpSecurityAttributes: var SECURITY_ATTRIBUTES, - dwFlags: DWORD, lpScreenBufferData: LPVOID): HANDLE{. - stdcall, dynlib: "kernel32", importc: "CreateConsoleScreenBuffer".} -proc GetConsoleCP*(): WINUINT{.stdcall, dynlib: "kernel32", importc: "GetConsoleCP".} -proc SetConsoleCP*(wCodePageID: WINUINT): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "SetConsoleCP".} -proc GetConsoleOutputCP*(): WINUINT{.stdcall, dynlib: "kernel32", - importc: "GetConsoleOutputCP".} -proc SetConsoleOutputCP*(wCodePageID: WINUINT): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "SetConsoleOutputCP".} -proc WNetConnectionDialog*(wnd: HWND, dwType: DWORD): DWORD{.stdcall, - dynlib: "mpr", importc: "WNetConnectionDialog".} -proc WNetDisconnectDialog*(wnd: HWND, dwType: DWORD): DWORD{.stdcall, - dynlib: "mpr", importc: "WNetDisconnectDialog".} -proc WNetCloseEnum*(hEnum: HANDLE): DWORD{.stdcall, dynlib: "mpr", - importc: "WNetCloseEnum".} -proc CloseServiceHandle*(hSCObject: SC_HANDLE): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "CloseServiceHandle".} -proc ControlService*(hService: SC_HANDLE, dwControl: DWORD, - lpServiceStatus: LPSERVICE_STATUS): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "ControlService".} -proc DeleteService*(hService: SC_HANDLE): WINBOOL{.stdcall, dynlib: "advapi32", - importc: "DeleteService".} -proc LockServiceDatabase*(hSCManager: SC_HANDLE): SC_LOCK{.stdcall, - dynlib: "advapi32", importc: "LockServiceDatabase".} -proc NotifyBootConfigStatus*(BootAcceptable: WINBOOL): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "NotifyBootConfigStatus".} -proc QueryServiceObjectSecurity*(hService: SC_HANDLE, - dwSecurityInformation: SECURITY_INFORMATION, - lpSecurityDescriptor: PSECURITY_DESCRIPTOR, - cbBufSize: DWORD, pcbBytesNeeded: LPDWORD): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "QueryServiceObjectSecurity".} -proc QueryServiceStatus*(hService: SC_HANDLE, lpServiceStatus: LPSERVICE_STATUS): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "QueryServiceStatus".} -proc SetServiceObjectSecurity*(hService: SC_HANDLE, - dwSecurityInformation: SECURITY_INFORMATION, - lpSecurityDescriptor: PSECURITY_DESCRIPTOR): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "SetServiceObjectSecurity".} -proc SetServiceStatus*(hServiceStatus: SERVICE_STATUS_HANDLE, - lpServiceStatus: LPSERVICE_STATUS): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "SetServiceStatus".} -proc UnlockServiceDatabase*(ScLock: SC_LOCK): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "UnlockServiceDatabase".} -proc ChoosePixelFormat*(para1: HDC, para2: PPIXELFORMATDESCRIPTOR): int32{. - stdcall, dynlib: "gdi32", importc: "ChoosePixelFormat".} -proc DescribePixelFormat*(para1: HDC, para2: int32, para3: WINUINT, - para4: LPPIXELFORMATDESCRIPTOR): int32{.stdcall, - dynlib: "gdi32", importc: "DescribePixelFormat".} -proc SetPixelFormat*(para1: HDC, para2: int32, para3: PPIXELFORMATDESCRIPTOR): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "SetPixelFormat".} -proc SwapBuffers*(para1: HDC): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "SwapBuffers".} -proc DragQueryPoint*(para1: HDROP, para2: LPPOINT): WINBOOL{.stdcall, - dynlib: "shell32", importc: "DragQueryPoint".} -proc DragFinish*(para1: HDROP){.stdcall, dynlib: "shell32", - importc: "DragFinish".} -proc DragAcceptFiles*(para1: HWND, para2: WINBOOL){.stdcall, dynlib: "shell32", - importc: "DragAcceptFiles".} -proc DuplicateIcon*(para1: HINST, para2: HICON): HICON{.stdcall, - dynlib: "shell32", importc: "DuplicateIcon".} -proc DdeAbandonTransaction*(para1: DWORD, para2: HCONV, para3: DWORD): WINBOOL{. - stdcall, dynlib: "user32", importc: "DdeAbandonTransaction".} -proc DdeAccessData*(para1: HDDEDATA, para2: PDWORD): PBYTE{.stdcall, - dynlib: "user32", importc: "DdeAccessData".} -proc DdeAddData*(para1: HDDEDATA, para2: PBYTE, para3: DWORD, para4: DWORD): HDDEDATA{. - stdcall, dynlib: "user32", importc: "DdeAddData".} -proc DdeClientTransaction*(para1: PBYTE, para2: DWORD, para3: HCONV, para4: HSZ, - para5: WINUINT, para6: WINUINT, para7: DWORD, para8: PDWORD): HDDEDATA{. - stdcall, dynlib: "user32", importc: "DdeClientTransaction".} -proc DdeCmpStringHandles*(para1: HSZ, para2: HSZ): int32{.stdcall, - dynlib: "user32", importc: "DdeCmpStringHandles".} -proc DdeConnect*(para1: DWORD, para2: HSZ, para3: HSZ, para4: var CONVCONTEXT): HCONV{. - stdcall, dynlib: "user32", importc: "DdeConnect".} -proc DdeConnectList*(para1: DWORD, para2: HSZ, para3: HSZ, para4: HCONVLIST, - para5: PCONVCONTEXT): HCONVLIST{.stdcall, dynlib: "user32", - importc: "DdeConnectList".} -proc DdeCreateDataHandle*(para1: DWORD, para2: LPBYTE, para3: DWORD, - para4: DWORD, para5: HSZ, para6: WINUINT, para7: WINUINT): HDDEDATA{. - stdcall, dynlib: "user32", importc: "DdeCreateDataHandle".} -proc DdeDisconnect*(para1: HCONV): WINBOOL{.stdcall, dynlib: "user32", - importc: "DdeDisconnect".} -proc DdeDisconnectList*(para1: HCONVLIST): WINBOOL{.stdcall, dynlib: "user32", - importc: "DdeDisconnectList".} -proc DdeEnableCallback*(para1: DWORD, para2: HCONV, para3: WINUINT): WINBOOL{. - stdcall, dynlib: "user32", importc: "DdeEnableCallback".} -proc DdeFreeDataHandle*(para1: HDDEDATA): WINBOOL{.stdcall, dynlib: "user32", - importc: "DdeFreeDataHandle".} -proc DdeFreeStringHandle*(para1: DWORD, para2: HSZ): WINBOOL{.stdcall, - dynlib: "user32", importc: "DdeFreeStringHandle".} -proc DdeGetData*(para1: HDDEDATA, para2: LPBYTE, para3: DWORD, para4: DWORD): DWORD{. - stdcall, dynlib: "user32", importc: "DdeGetData".} -proc DdeGetLastError*(para1: DWORD): WINUINT{.stdcall, dynlib: "user32", - importc: "DdeGetLastError".} -proc DdeImpersonateClient*(para1: HCONV): WINBOOL{.stdcall, dynlib: "user32", - importc: "DdeImpersonateClient".} -proc DdeKeepStringHandle*(para1: DWORD, para2: HSZ): WINBOOL{.stdcall, - dynlib: "user32", importc: "DdeKeepStringHandle".} -proc DdeNameService*(para1: DWORD, para2: HSZ, para3: HSZ, para4: WINUINT): HDDEDATA{. - stdcall, dynlib: "user32", importc: "DdeNameService".} -proc DdePostAdvise*(para1: DWORD, para2: HSZ, para3: HSZ): WINBOOL{.stdcall, - dynlib: "user32", importc: "DdePostAdvise".} -proc DdeQueryConvInfo*(para1: HCONV, para2: DWORD, para3: PCONVINFO): WINUINT{. - stdcall, dynlib: "user32", importc: "DdeQueryConvInfo".} -proc DdeQueryNextServer*(para1: HCONVLIST, para2: HCONV): HCONV{.stdcall, - dynlib: "user32", importc: "DdeQueryNextServer".} -proc DdeReconnect*(para1: HCONV): HCONV{.stdcall, dynlib: "user32", - importc: "DdeReconnect".} -proc DdeSetUserHandle*(para1: HCONV, para2: DWORD, para3: DWORD): WINBOOL{. - stdcall, dynlib: "user32", importc: "DdeSetUserHandle".} -proc DdeUnaccessData*(para1: HDDEDATA): WINBOOL{.stdcall, dynlib: "user32", - importc: "DdeUnaccessData".} -proc DdeUninitialize*(para1: DWORD): WINBOOL{.stdcall, dynlib: "user32", - importc: "DdeUninitialize".} -proc SHAddToRecentDocs*(para1: WINUINT, para2: LPCVOID){.stdcall, - dynlib: "shell32", importc: "SHAddToRecentDocs".} -proc SHBrowseForFolder*(para1: LPBROWSEINFO): LPITEMIDLIST{.stdcall, - dynlib: "shell32", importc: "SHBrowseForFolder".} -proc SHChangeNotify*(para1: LONG, para2: WINUINT, para3: LPCVOID, para4: LPCVOID){. - stdcall, dynlib: "shell32", importc: "SHChangeNotify".} -proc SHFileOperation*(para1: LPSHFILEOPSTRUCT): int32{.stdcall, - dynlib: "shell32", importc: "SHFileOperation".} -proc SHFreeNameMappings*(para1: HANDLE){.stdcall, dynlib: "shell32", - importc: "SHFreeNameMappings".} -proc SHGetFileInfo*(para1: LPCTSTR, para2: DWORD, para3: var SHFILEINFO, - para4: WINUINT, para5: WINUINT): DWORD{.stdcall, - dynlib: "shell32", importc: "SHGetFileInfo".} -proc SHGetPathFromIDList*(para1: LPCITEMIDLIST, para2: LPTSTR): WINBOOL{. - stdcall, dynlib: "shell32", importc: "SHGetPathFromIDList".} -proc SHGetSpecialFolderLocation*(para1: HWND, para2: int32, - para3: var LPITEMIDLIST): HRESULT{.stdcall, - dynlib: "shell32", importc: "SHGetSpecialFolderLocation".} -proc CommDlgExtendedError*(): DWORD{.stdcall, dynlib: "comdlg32", - importc: "CommDlgExtendedError".} - # wgl Windows OpenGL helper functions -proc wglUseFontBitmaps*(para1: HDC, para2: DWORD, para3: DWORD, para4: DWORD): WINBOOL{. - stdcall, dynlib: "opengl32", importc: "wglUseFontBitmapsA".} -proc wglCreateContext*(para1: HDC): HGLRC{.stdcall, dynlib: "opengl32", - importc: "wglCreateContext".} -proc wglCreateLayerContext*(para1: HDC, para2: int32): HGLRC{.stdcall, - dynlib: "opengl32", importc: "wglCreateLayerContext".} -proc wglCopyContext*(para1: HGLRC, para2: HGLRC, para3: WINUINT): WINBOOL{.stdcall, - dynlib: "opengl32", importc: "wglCopyContext".} -proc wglDeleteContext*(para1: HGLRC): WINBOOL{.stdcall, dynlib: "opengl32", - importc: "wglDeleteContext".} -proc wglGetCurrentContext*(): HGLRC{.stdcall, dynlib: "opengl32", - importc: "wglGetCurrentContext".} -proc wglGetCurrentDC*(): HDC{.stdcall, dynlib: "opengl32", - importc: "wglGetCurrentDC".} -proc wglMakeCurrent*(para1: HDC, para2: HGLRC): WINBOOL{.stdcall, - dynlib: "opengl32", importc: "wglMakeCurrent".} -proc wglShareLists*(para1: HGLRC, para2: HGLRC): WINBOOL{.stdcall, - dynlib: "opengl32", importc: "wglShareLists".} -proc wglUseFontBitmapsW*(para1: HDC, para2: DWORD, para3: DWORD, para4: DWORD): WINBOOL{. - stdcall, dynlib: "opengl32", importc: "wglUseFontBitmapsW".} -proc wglUseFontOutlines*(para1: HDC, para2: DWORD, para3: DWORD, para4: DWORD, - para5: float32, para6: float32, para7: int32, - para8: LPGLYPHMETRICSFLOAT): WINBOOL{.stdcall, - dynlib: "opengl32", importc: "wglUseFontOutlinesA".} -proc wglUseFontBitmapsA*(para1: HDC, para2: DWORD, para3: DWORD, para4: DWORD): WINBOOL{. - stdcall, dynlib: "opengl32", importc: "wglUseFontBitmapsA".} -proc wglUseFontOutlinesA*(para1: HDC, para2: DWORD, para3: DWORD, para4: DWORD, - para5: float32, para6: float32, para7: int32, - para8: LPGLYPHMETRICSFLOAT): WINBOOL{.stdcall, - dynlib: "opengl32", importc: "wglUseFontOutlinesA".} -proc wglDescribeLayerPlane*(para1: HDC, para2: int32, para3: int32, para4: WINUINT, - para5: LPLAYERPLANEDESCRIPTOR): WINBOOL{.stdcall, - dynlib: "opengl32", importc: "wglDescribeLayerPlane".} -proc wglGetLayerPaletteEntries*(para1: HDC, para2: int32, para3: int32, - para4: int32, para5: var COLORREF): int32{. - stdcall, dynlib: "opengl32", importc: "wglGetLayerPaletteEntries".} -proc wglGetProcAddress*(para1: LPCSTR): Proc{.stdcall, dynlib: "opengl32", - importc: "wglGetProcAddress".} -proc wglRealizeLayerPalette*(para1: HDC, para2: int32, para3: WINBOOL): WINBOOL{. - stdcall, dynlib: "opengl32", importc: "wglRealizeLayerPalette".} -proc wglSetLayerPaletteEntries*(para1: HDC, para2: int32, para3: int32, - para4: int32, para5: var COLORREF): int32{. - stdcall, dynlib: "opengl32", importc: "wglSetLayerPaletteEntries".} -proc wglSwapLayerBuffers*(para1: HDC, para2: WINUINT): WINBOOL{.stdcall, - dynlib: "opengl32", importc: "wglSwapLayerBuffers".} -proc wglUseFontOutlinesW*(para1: HDC, para2: DWORD, para3: DWORD, para4: DWORD, - para5: float32, para6: float32, para7: int32, - para8: LPGLYPHMETRICSFLOAT): WINBOOL{.stdcall, - dynlib: "opengl32", importc: "wglUseFontOutlinesW".} - # translated macros -proc Animate_Create*(hWndP: HWND, id: HMENU, dwStyle: DWORD, hInstance: HINST): HWND -proc Animate_Open*(wnd: HWND, szName: LPTSTR): LRESULT -proc Animate_Play*(wnd: HWND, `from`, `to`: int32, rep: WINUINT): LRESULT - -proc Animate_Stop*(wnd: HWND): LRESULT -proc Animate_Close*(wnd: HWND): LRESULT -proc Animate_Seek*(wnd: HWND, frame: int32): LRESULT -proc PropSheet_AddPage*(hPropSheetDlg: HWND, hpage: HPROPSHEETPAGE): LRESULT -proc PropSheet_Apply*(hPropSheetDlg: HWND): LRESULT -proc PropSheet_CancelToClose*(hPropSheetDlg: HWND): LRESULT -proc PropSheet_Changed*(hPropSheetDlg, hwndPage: HWND): LRESULT -proc PropSheet_GetCurrentPageHwnd*(hDlg: HWND): LRESULT -proc PropSheet_GetTabControl*(hPropSheetDlg: HWND): LRESULT -proc PropSheet_IsDialogMessage*(hDlg: HWND, pMsg: int32): LRESULT -proc PropSheet_PressButton*(hPropSheetDlg: HWND, iButton: int32): LRESULT -proc PropSheet_QuerySiblings*(hPropSheetDlg: HWND, param1, param2: int32): LRESULT -proc PropSheet_RebootSystem*(hPropSheetDlg: HWND): LRESULT -proc PropSheet_RemovePage*(hPropSheetDlg: HWND, hpage: HPROPSHEETPAGE, - index: int32): LRESULT -proc PropSheet_RestartWindows*(hPropSheetDlg: HWND): LRESULT -proc PropSheet_SetCurSel*(hPropSheetDlg: HWND, hpage: HPROPSHEETPAGE, - index: int32): LRESULT -proc PropSheet_SetCurSelByID*(hPropSheetDlg: HWND, id: int32): LRESULT -proc PropSheet_SetFinishText*(hPropSheetDlg: HWND, lpszText: LPTSTR): LRESULT -proc PropSheet_SetTitle*(hPropSheetDlg: HWND, dwStyle: DWORD, lpszText: LPCTSTR): LRESULT -proc PropSheet_SetWizButtons*(hPropSheetDlg: HWND, dwFlags: DWORD): LRESULT -proc PropSheet_UnChanged*(hPropSheetDlg: HWND, hwndPage: HWND): LRESULT -proc Header_DeleteItem*(hwndHD: HWND, index: int32): WINBOOL -proc Header_GetItem*(hwndHD: HWND, index: int32, hdi: var HD_ITEM): WINBOOL -proc Header_GetItemCount*(hwndHD: HWND): int32 -proc Header_InsertItem*(hwndHD: HWND, index: int32, hdi: var HD_ITEM): int32 -proc Header_Layout*(hwndHD: HWND, layout: var HD_LAYOUT): WINBOOL -proc Header_SetItem*(hwndHD: HWND, index: int32, hdi: var HD_ITEM): WINBOOL -proc ListView_Arrange*(hwndLV: HWND, code: WINUINT): LRESULT -proc ListView_CreateDragImage*(wnd: HWND, i: int32, lpptUpLeft: LPPOINT): LRESULT -proc ListView_DeleteAllItems*(wnd: HWND): LRESULT -proc ListView_DeleteColumn*(wnd: HWND, iCol: int32): LRESULT -proc ListView_DeleteItem*(wnd: HWND, iItem: int32): LRESULT -proc ListView_EditLabel*(hwndLV: HWND, i: int32): LRESULT -proc ListView_EnsureVisible*(hwndLV: HWND, i, fPartialOK: int32): LRESULT -proc ListView_FindItem*(wnd: HWND, iStart: int32, lvfi: var LV_FINDINFO): int32 -proc ListView_GetBkColor*(wnd: HWND): LRESULT -proc ListView_GetCallbackMask*(wnd: HWND): LRESULT -proc ListView_GetColumn*(wnd: HWND, iCol: int32, col: var LV_COLUMN): LRESULT -proc ListView_GetColumnWidth*(wnd: HWND, iCol: int32): LRESULT -proc ListView_GetCountPerPage*(hwndLV: HWND): LRESULT -proc ListView_GetEditControl*(hwndLV: HWND): LRESULT -proc ListView_GetImageList*(wnd: HWND, iImageList: WINT): LRESULT -proc ListView_GetISearchString*(hwndLV: HWND, lpsz: LPTSTR): LRESULT -proc ListView_GetItem*(wnd: HWND, item: var LV_ITEM): LRESULT -proc ListView_GetItemCount*(wnd: HWND): LRESULT -proc ListView_GetItemPosition*(hwndLV: HWND, i: int32, pt: var POINT): int32 -proc ListView_GetItemSpacing*(hwndLV: HWND, fSmall: int32): LRESULT -proc ListView_GetItemState*(hwndLV: HWND, i, mask: int32): LRESULT -proc ListView_GetNextItem*(wnd: HWND, iStart, flags: int32): LRESULT -proc ListView_GetOrigin*(hwndLV: HWND, pt: var POINT): LRESULT -proc ListView_GetSelectedCount*(hwndLV: HWND): LRESULT -proc ListView_GetStringWidth*(hwndLV: HWND, psz: LPCTSTR): LRESULT -proc ListView_GetTextBkColor*(wnd: HWND): LRESULT -proc ListView_GetTextColor*(wnd: HWND): LRESULT -proc ListView_GetTopIndex*(hwndLV: HWND): LRESULT -proc ListView_GetViewRect*(wnd: HWND, rc: var RECT): LRESULT -proc ListView_HitTest*(hwndLV: HWND, info: var LV_HITTESTINFO): LRESULT -proc ListView_InsertColumn*(wnd: HWND, iCol: int32, col: var LV_COLUMN): LRESULT -proc ListView_InsertItem*(wnd: HWND, item: var LV_ITEM): LRESULT -proc ListView_RedrawItems*(hwndLV: HWND, iFirst, iLast: int32): LRESULT -proc ListView_Scroll*(hwndLV: HWND, dx, dy: int32): LRESULT -proc ListView_SetBkColor*(wnd: HWND, clrBk: COLORREF): LRESULT -proc ListView_SetCallbackMask*(wnd: HWND, mask: WINUINT): LRESULT -proc ListView_SetColumn*(wnd: HWND, iCol: int32, col: var LV_COLUMN): LRESULT -proc ListView_SetColumnWidth*(wnd: HWND, iCol, cx: int32): LRESULT -proc ListView_SetImageList*(wnd: HWND, himl: int32, iImageList: HIMAGELIST): LRESULT -proc ListView_SetItem*(wnd: HWND, item: var LV_ITEM): LRESULT -proc ListView_SetItemCount*(hwndLV: HWND, cItems: int32): LRESULT -proc ListView_SetItemPosition*(hwndLV: HWND, i, x, y: int32): LRESULT -proc ListView_SetItemPosition32*(hwndLV: HWND, i, x, y: int32): LRESULT -proc ListView_SetItemState*(hwndLV: HWND, i, data, mask: int32): LRESULT -proc ListView_SetItemText*(hwndLV: HWND, i, iSubItem: int32, pszText: LPTSTR): LRESULT -proc ListView_SetTextBkColor*(wnd: HWND, clrTextBk: COLORREF): LRESULT -proc ListView_SetTextColor*(wnd: HWND, clrText: COLORREF): LRESULT -proc ListView_SortItems*(hwndLV: HWND, pfnCompare: PFNLVCOMPARE, lPrm: LPARAM): LRESULT -proc ListView_Update*(hwndLV: HWND, i: int32): LRESULT -proc TreeView_InsertItem*(wnd: HWND, lpis: LPTV_INSERTSTRUCT): LRESULT -proc TreeView_DeleteItem*(wnd: HWND, hitem: HTREEITEM): LRESULT -proc TreeView_DeleteAllItems*(wnd: HWND): LRESULT -proc TreeView_Expand*(wnd: HWND, hitem: HTREEITEM, code: int32): LRESULT -proc TreeView_GetCount*(wnd: HWND): LRESULT -proc TreeView_GetIndent*(wnd: HWND): LRESULT -proc TreeView_SetIndent*(wnd: HWND, indent: int32): LRESULT -proc TreeView_GetImageList*(wnd: HWND, iImage: WPARAM): LRESULT -proc TreeView_SetImageList*(wnd: HWND, himl: HIMAGELIST, iImage: WPARAM): LRESULT -proc TreeView_GetNextItem*(wnd: HWND, hitem: HTREEITEM, code: int32): LRESULT -proc TreeView_GetChild*(wnd: HWND, hitem: HTREEITEM): LRESULT -proc TreeView_GetNextSibling*(wnd: HWND, hitem: HTREEITEM): LRESULT -proc TreeView_GetPrevSibling*(wnd: HWND, hitem: HTREEITEM): LRESULT -proc TreeView_GetParent*(wnd: HWND, hitem: HTREEITEM): LRESULT -proc TreeView_GetFirstVisible*(wnd: HWND): LRESULT -proc TreeView_GetNextVisible*(wnd: HWND, hitem: HTREEITEM): LRESULT -proc TreeView_GetPrevVisible*(wnd: HWND, hitem: HTREEITEM): LRESULT -proc TreeView_GetSelection*(wnd: HWND): LRESULT -proc TreeView_GetDropHilight*(wnd: HWND): LRESULT -proc TreeView_GetRoot*(wnd: HWND): LRESULT -proc TreeView_Select*(wnd: HWND, hitem: HTREEITEM, code: int32): LRESULT -proc TreeView_SelectItem*(wnd: HWND, hitem: HTREEITEM): LRESULT -proc TreeView_SelectDropTarget*(wnd: HWND, hitem: HTREEITEM): LRESULT -proc TreeView_SelectSetFirstVisible*(wnd: HWND, hitem: HTREEITEM): LRESULT -proc TreeView_GetItem*(wnd: HWND, item: var TV_ITEM): LRESULT -proc TreeView_SetItem*(wnd: HWND, item: var TV_ITEM): LRESULT -proc TreeView_EditLabel*(wnd: HWND, hitem: HTREEITEM): LRESULT -proc TreeView_GetEditControl*(wnd: HWND): LRESULT -proc TreeView_GetVisibleCount*(wnd: HWND): LRESULT -proc TreeView_HitTest*(wnd: HWND, lpht: LPTV_HITTESTINFO): LRESULT -proc TreeView_CreateDragImage*(wnd: HWND, hitem: HTREEITEM): LRESULT -proc TreeView_SortChildren*(wnd: HWND, hitem: HTREEITEM, recurse: int32): LRESULT -proc TreeView_EnsureVisible*(wnd: HWND, hitem: HTREEITEM): LRESULT -proc TreeView_SortChildrenCB*(wnd: HWND, psort: LPTV_SORTCB, recurse: int32): LRESULT -proc TreeView_EndEditLabelNow*(wnd: HWND, fCancel: int32): LRESULT -proc TreeView_GetISearchString*(hwndTV: HWND, lpsz: LPTSTR): LRESULT -proc TabCtrl_GetImageList*(wnd: HWND): LRESULT -proc TabCtrl_SetImageList*(wnd: HWND, himl: HIMAGELIST): LRESULT -proc TabCtrl_GetItemCount*(wnd: HWND): LRESULT -proc TabCtrl_GetItem*(wnd: HWND, iItem: int32, item: var TC_ITEM): LRESULT -proc TabCtrl_SetItem*(wnd: HWND, iItem: int32, item: var TC_ITEM): LRESULT - -proc TabCtrl_InsertItem*(wnd: HWND, iItem: int32, item: var TC_ITEM): LRESULT -proc TabCtrl_DeleteItem*(wnd: HWND, i: int32): LRESULT -proc TabCtrl_DeleteAllItems*(wnd: HWND): LRESULT -proc TabCtrl_GetItemRect*(wnd: HWND, i: int32, rc: var RECT): LRESULT -proc TabCtrl_GetCurSel*(wnd: HWND): LRESULT -proc TabCtrl_SetCurSel*(wnd: HWND, i: int32): LRESULT -proc TabCtrl_HitTest*(hwndTC: HWND, info: var TC_HITTESTINFO): LRESULT -proc TabCtrl_SetItemExtra*(hwndTC: HWND, cb: int32): LRESULT -proc TabCtrl_AdjustRect*(wnd: HWND, bLarger: WINBOOL, rc: var RECT): LRESULT -proc TabCtrl_SetItemSize*(wnd: HWND, x, y: int32): LRESULT -proc TabCtrl_RemoveImage*(wnd: HWND, i: WPARAM): LRESULT -proc TabCtrl_SetPadding*(wnd: HWND, cx, cy: int32): LRESULT -proc TabCtrl_GetRowCount*(wnd: HWND): LRESULT -proc TabCtrl_GetToolTips*(wnd: HWND): LRESULT -proc TabCtrl_SetToolTips*(wnd: HWND, hwndTT: int32): LRESULT -proc TabCtrl_GetCurFocus*(wnd: HWND): LRESULT -proc TabCtrl_SetCurFocus*(wnd: HWND, i: int32): LRESULT -proc SNDMSG*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): LRESULT -proc CommDlg_OpenSave_GetSpecA*(hdlg: HWND, psz: LPSTR, cbmax: int32): LRESULT -proc CommDlg_OpenSave_GetSpecW*(hdlg: HWND, psz: LPWSTR, cbmax: int32): LRESULT -when defined(winUnicode): - proc CommDlg_OpenSave_GetSpec*(hdlg: HWND, psz: LPWSTR, cbmax: int32): LRESULT -else: - proc CommDlg_OpenSave_GetSpec*(hdlg: HWND, psz: LPSTR, cbmax: int32): LRESULT -proc CommDlg_OpenSave_GetFilePathA*(hdlg: HWND, psz: LPSTR, cbmax: int32): LRESULT -proc CommDlg_OpenSave_GetFilePathW*(hdlg: HWND, psz: LPWSTR, cbmax: int32): LRESULT -when defined(winUnicode): - proc CommDlg_OpenSave_GetFilePath*(hdlg: HWND, psz: LPWSTR, cbmax: int32): LRESULT -else: - proc CommDlg_OpenSave_GetFilePath*(hdlg: HWND, psz: LPSTR, cbmax: int32): LRESULT -proc CommDlg_OpenSave_GetFolderPathA*(hdlg: HWND, psz: LPSTR, cbmax: int32): LRESULT -proc CommDlg_OpenSave_GetFolderPathW*(hdlg: HWND, psz: LPWSTR, cbmax: int32): LRESULT -when defined(winUnicode): - proc CommDlg_OpenSave_GetFolderPath*(hdlg: HWND, psz: LPWSTR, cbmax: int32): LRESULT -else: - proc CommDlg_OpenSave_GetFolderPath*(hdlg: HWND, psz: LPSTR, cbmax: int32): LRESULT -proc CommDlg_OpenSave_GetFolderIDList*(hdlg: HWND, pidl: LPVOID, cbmax: int32): LRESULT -proc CommDlg_OpenSave_SetControlText*(hdlg: HWND, id: int32, text: LPSTR): LRESULT -proc CommDlg_OpenSave_HideControl*(hdlg: HWND, id: int32): LRESULT -proc CommDlg_OpenSave_SetDefExt*(hdlg: HWND, pszext: LPSTR): LRESULT -proc GetNextWindow*(wnd: HWND, uCmd: WINUINT): HWND{.stdcall, dynlib: "user32", - importc: "GetWindow".} -proc GlobalAllocPtr*(flags, cb: DWord): pointer -proc GlobalFreePtr*(lp: pointer): pointer -proc GlobalUnlockPtr*(lp: pointer): pointer -proc GlobalLockPtr*(lp: pointer): pointer -proc GlobalReAllocPtr*(lp: pointer, cbNew, flags: DWord): pointer -proc GlobalPtrHandle*(lp: pointer): pointer -proc SetLayeredWindowAttributes*(hwnd: HWND, crKey: COLORREF, bAlpha: int8, - dwFlags: DWORD): WINBOOL{.stdcall, - dynlib: "user32", importc: "SetLayeredWindowAttributes".} -type - PIID* = PGUID - TIID* = GUID - TFNDlgProc* = FARPROC - TFNThreadStartRoutine* = FARPROC - TFNTimerAPCRoutine* = FARPROC - TFNFiberStartRoutine* = FARPROC - TFNHookProc* = HOOKPROC - PObjectTypeList* = ptr TObjectTypeList - OBJECT_TYPE_LIST* {.final, pure.} = object - Level*: int16 - Sbz*: int16 - ObjectType*: PGUID - - TObjectTypeList* = OBJECT_TYPE_LIST - AUDIT_EVENT_TYPE* = DWORD - PBlendFunction* = ptr TBlendFunction - BLENDFUNCTION* {.final, pure.} = object - BlendOp*: int8 - BlendFlags*: int8 - SourceConstantAlpha*: int8 - AlphaFormat*: int8 - - TBlendFunction* = BLENDFUNCTION - WIN_CERTIFICATE* {.final, pure.} = object - dwLength*: DWord - wRevision*: int16 - wCertificateType*: int16 - bCertificate*: array[0..0, int8] - - TWinCertificate* = WIN_CERTIFICATE - PWinCertificate* = ptr TWinCertificate - TMaxLogPalette* {.final, pure.} = object - palVersion*: int16 - palNumEntries*: int16 - palPalEntry*: array[int8, PaletteEntry] - - PMaxLogPalette* = ptr TMaxLogPalette - POSVersionInfoA* = POSVERSIONINFO - TBitmapFileHeader* = BITMAPFILEHEADER - PBitmapFileHeader* = ptr TBitmapFileHeader - -const - # dll names - advapi32* = "advapi32.dll" - kernel32* = "kernel32.dll" - mpr* = "mpr.dll" - version* = "version.dll" - comctl32* = "comctl32.dll" - gdi32* = "gdi32.dll" - opengl32* = "opengl32.dll" - user32* = "user32.dll" - wintrust* = "wintrust.dll" - # Openfile Share modes normally declared in sysutils - fmShareCompat* = 0x00000000 - fmShareExclusive* = 0x00000010 - fmShareDenyWrite* = 0x00000020 - fmShareDenyRead* = 0x00000030 - fmShareDenyNone* = 0x00000040 - # HRESULT codes, delphilike - SIF_TRACKPOS* = 0x00000010 - HTBORDER* = 18 - CP_UTF7* = 65000 - CP_UTF8* = 65001 - CREATE_NO_WINDOW* = 0x08000000 - VK_ATTN* = 246 - VK_CRSEL* = 247 - VK_EXSEL* = 248 - VK_EREOF* = 249 - VK_PLAY* = 250 - VK_ZOOM* = 251 - VK_NONAME* = 252 - VK_PA1* = 253 - VK_OEM_CLEAR* = 254 - -const # Severity values - FACILITY_NT_BIT* = 0x10000000 - - # A language ID is a 16 bit value which is the combination of a - # primary language ID and a secondary language ID. The bits are - # allocated as follows: - # - # +-----------------------+-------------------------+ - # | Sublanguage ID | Primary Language ID | - # +-----------------------+-------------------------+ - # 15 10 9 0 bit - # - # - # Language ID creation/extraction macros: - # - # MAKELANGID - construct language id from a primary language id and - # a sublanguage id. - # PRIMARYLANGID - extract primary language id from a language id. - # SUBLANGID - extract sublanguage id from a language id. - # -proc MAKELANGID*(PrimaryLang, SubLang: USHORT): int16 -proc PRIMARYLANGID*(LangId: int16): int16 -proc SUBLANGID*(LangId: int16): int16 - - # - # A locale ID is a 32 bit value which is the combination of a - # language ID, a sort ID, and a reserved area. The bits are - # allocated as follows: - # - # +-------------+---------+-------------------------+ - # | Reserved | Sort ID | Language ID | - # +-------------+---------+-------------------------+ - # 31 20 19 16 15 0 bit - # - # - # Locale ID creation/extraction macros: - # - # MAKELCID - construct the locale id from a language id and a sort id. - # MAKESORTLCID - construct the locale id from a language id, sort id, and sort version. - # LANGIDFROMLCID - extract the language id from a locale id. - # SORTIDFROMLCID - extract the sort id from a locale id. - # SORTVERSIONFROMLCID - extract the sort version from a locale id. - # -const - NLS_VALID_LOCALE_MASK* = 0x000FFFFF - -proc MAKELCID*(LangId, SortId: int16): DWORD -proc MAKESORTLCID*(LangId, SortId, SortVersion: int16): DWORD -proc LANGIDFROMLCID*(LocaleId: LCID): int16 -proc SORTIDFROMLCID*(LocaleId: LCID): int16 -proc SORTVERSIONFROMLCID*(LocaleId: LCID): int16 - - # - # Default System and User IDs for language and locale. - # -proc LANG_SYSTEM_DEFAULT*(): int16 -proc LANG_USER_DEFAULT*(): int16 -proc LOCALE_NEUTRAL*(): DWORD -proc LOCALE_INVARIANT*(): DWORD -proc Succeeded*(Status: HRESULT): WINBOOL -proc Failed*(Status: HRESULT): WINBOOL -proc IsError*(Status: HRESULT): WINBOOL -proc HResultCode*(hr: HRESULT): int32 -proc HResultFacility*(hr: HRESULT): int32 -proc HResultSeverity*(hr: HRESULT): int32 -proc MakeResult*(p1, p2, mask: int32): HRESULT -proc HResultFromWin32*(x: int32): HRESULT -proc HResultFromNT*(x: int32): HRESULT -proc InitializeCriticalSection*(CriticalSection: var TRTLCriticalSection){. - stdcall, dynlib: "kernel32", importc: "InitializeCriticalSection".} -proc EnterCriticalSection*(CriticalSection: var TRTLCriticalSection){.stdcall, - dynlib: "kernel32", importc: "EnterCriticalSection".} -proc LeaveCriticalSection*(CriticalSection: var TRTLCriticalSection){.stdcall, - dynlib: "kernel32", importc: "LeaveCriticalSection".} -proc DeleteCriticalSection*(CriticalSection: var TRTLCriticalSection){.stdcall, - dynlib: "kernel32", importc: "DeleteCriticalSection".} -proc InitializeCriticalSectionAndSpinCount*( - CriticalSection: var TRTLCriticalSection, dwSpinCount: DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", - importc: "InitializeCriticalSectionAndSpinCount".} -proc SetCriticalSectionSpinCount*(CriticalSection: var TRTLCriticalSection, - dwSpinCount: DWORD): DWORD{.stdcall, - dynlib: "kernel32", importc: "SetCriticalSectionSpinCount".} -proc TryEnterCriticalSection*(CriticalSection: var TRTLCriticalSection): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "TryEnterCriticalSection".} -proc ControlService*(hService: SC_HANDLE, dwControl: DWORD, - ServiceStatus: var SERVICESTATUS): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "ControlService".} -proc QueryServiceStatus*(hService: SC_HANDLE, - lpServiceStatus: var SERVICESTATUS): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "QueryServiceStatus".} -proc SetServiceStatus*(hServiceStatus: SERVICE_STATUS_HANDLE, - ServiceStatus: SERVICESTATUS): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "SetServiceStatus".} -proc AdjustTokenPrivileges*(TokenHandle: Handle, DisableAllPrivileges: WINBOOL, - NewState: TTokenPrivileges, BufferLength: DWORD, - PreviousState: var TTokenPrivileges, - ReturnLength: var DWORD): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "AdjustTokenPrivileges".} -proc AdjustWindowRect*(lpRect: var Rect, dwStyle: DWORD, bMenu: WINBOOL): WINBOOL{. - stdcall, dynlib: "user32", importc: "AdjustWindowRect".} -proc AdjustWindowRectEx*(lpRect: var Rect, dwStyle: DWORD, bMenu: WINBOOL, - dwExStyle: DWORD): WINBOOL{.stdcall, dynlib: "user32", - importc: "AdjustWindowRectEx".} -proc AllocateAndInitializeSid*(pIdentifierAuthority: SIDIdentifierAuthority, - nSubAuthorityCount: int8, - nSubAuthority0, nSubAuthority1: DWORD, - nSubAuthority2, nSubAuthority3, nSubAuthority4: DWORD, nSubAuthority5, - nSubAuthority6, nSubAuthority7: DWORD, pSid: var pointer): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "AllocateAndInitializeSid".} -proc AllocateLocallyUniqueId*(Luid: var LargeInteger): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "AllocateLocallyUniqueId".} -proc BackupRead*(hFile: Handle, lpBuffer: PByte, nNumberOfBytesToRead: DWORD, - lpNumberOfBytesRead: var DWORD, bAbort: WINBOOL, - bProcessSecurity: WINBOOL, lpContext: var pointer): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "BackupRead".} -proc BackupSeek*(hFile: Handle, dwLowBytesToSeek, dwHighBytesToSeek: DWORD, - lpdwLowByteSeeked, lpdwHighByteSeeked: var DWORD, - lpContext: pointer): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "BackupSeek".} -proc BackupWrite*(hFile: Handle, lpBuffer: PByte, nNumberOfBytesToWrite: DWORD, - lpNumberOfBytesWritten: var DWORD, - bAbort, bProcessSecurity: WINBOOL, lpContext: var pointer): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "BackupWrite".} -proc BeginPaint*(wnd: HWND, lpPaint: var PaintStruct): HDC{.stdcall, - dynlib: "user32", importc: "BeginPaint".} -proc BuildCommDCB*(lpDef: cstring, lpDCB: var DCB): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "BuildCommDCBA".} -proc BuildCommDCBA*(lpDef: LPCSTR, lpDCB: var DCB): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "BuildCommDCBA".} -proc BuildCommDCBAndTimeouts*(lpDef: cstring, lpDCB: var DCB, - lpCommTimeouts: var CommTimeouts): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "BuildCommDCBAndTimeoutsA".} -proc BuildCommDCBAndTimeoutsA*(lpDef: LPCSTR, lpDCB: var DCB, - lpCommTimeouts: var CommTimeouts): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "BuildCommDCBAndTimeoutsA".} -proc BuildCommDCBAndTimeoutsW*(lpDef: LPWSTR, lpDCB: var DCB, - lpCommTimeouts: var CommTimeouts): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "BuildCommDCBAndTimeoutsW".} -proc BuildCommDCBW*(lpDef: LPWSTR, lpDCB: var DCB): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "BuildCommDCBW".} -proc CallMsgFilter*(lpMsg: var TMsg, nCode: int): WINBOOL{.stdcall, - dynlib: "user32", importc: "CallMsgFilterA".} -proc CallMsgFilterA*(lpMsg: var TMsg, nCode: int): WINBOOL{.stdcall, - dynlib: "user32", importc: "CallMsgFilterA".} -proc CallMsgFilterW*(lpMsg: var TMsg, nCode: int): WINBOOL{.stdcall, - dynlib: "user32", importc: "CallMsgFilterW".} -proc CallNamedPipe*(lpNamedPipeName: cstring, lpInBuffer: pointer, - nInBufferSize: DWORD, lpOutBuffer: pointer, - nOutBufferSize: DWORD, lpBytesRead: var DWORD, - nTimeOut: DWORD): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "CallNamedPipeA".} -proc CallNamedPipeA*(lpNamedPipeName: LPCSTR, lpInBuffer: pointer, - nInBufferSize: DWORD, lpOutBuffer: pointer, - nOutBufferSize: DWORD, lpBytesRead: var DWORD, - nTimeOut: DWORD): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "CallNamedPipeA".} -proc CallNamedPipeW*(lpNamedPipeName: LPWSTR, lpInBuffer: pointer, - nInBufferSize: DWORD, lpOutBuffer: pointer, - nOutBufferSize: DWORD, lpBytesRead: var DWORD, - nTimeOut: DWORD): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "CallNamedPipeW".} -proc CoRegisterClassObject*(para1: CLSID, para2: pointer, para3: DWORD, - para4: DWORD, out_para5: DWORD): HRESULT{.stdcall, - dynlib: "ole32.dll", importc: "CoRegisterClassObject".} -proc ChangeDisplaySettings*(lpDevMode: var DevMode, dwFlags: DWORD): int32{. - stdcall, dynlib: "user32", importc: "ChangeDisplaySettingsA".} -proc ChangeDisplaySettingsA*(lpDevMode: var DevMode, dwFlags: DWORD): int32{. - stdcall, dynlib: "user32", importc: "ChangeDisplaySettingsA".} -proc ChangeDisplaySettingsEx*(lpszDeviceName: cstring, - lpDevMode: var DevMode, wnd: HWND, - dwFlags: DWORD, lParam: pointer): int32{.stdcall, - dynlib: "user32", importc: "ChangeDisplaySettingsExA".} -proc ChangeDisplaySettingsExA*(lpszDeviceName: LPCSTR, - lpDevMode: var DevMode, wnd: HWND, - dwFlags: DWORD, lParam: pointer): int32{.stdcall, - dynlib: "user32", importc: "ChangeDisplaySettingsExA".} -proc ChangeDisplaySettingsExW*(lpszDeviceName: LPWSTR, - lpDevMode: var DevModeW, wnd: HWND, - dwFlags: DWORD, lParam: pointer): int32{.stdcall, - dynlib: "user32", importc: "ChangeDisplaySettingsExW".} -proc ChangeDisplaySettingsW*(lpDevMode: var DevModeW, dwFlags: DWORD): int32{. - stdcall, dynlib: "user32", importc: "ChangeDisplaySettingsW".} - #function CheckColorsInGamut(DC: HDC; var RGBQuads, Results; Count: DWORD): WINBOOL; stdcall; external 'gdi32' name 'CheckColorsInGamut'; -proc ChoosePixelFormat*(para1: HDC, para2: var PIXELFORMATDESCRIPTOR): int32{. - stdcall, dynlib: "gdi32", importc: "ChoosePixelFormat".} -proc ClearCommError*(hFile: Handle, lpErrors: var DWORD, lpStat: PComStat): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "ClearCommError".} -proc ClientToScreen*(wnd: HWND, lpPoint: var Point): WINBOOL{.stdcall, - dynlib: "user32", importc: "ClientToScreen".} -proc ClipCursor*(lpRect: var RECT): WINBOOL{.stdcall, dynlib: "user32", - importc: "ClipCursor".} - #function CombineTransform(var p1: XForm; const p2, p3: XForm): WINBOOL; stdcall; external 'gdi32' name 'CombineTransform'; -proc CommConfigDialog*(lpszName: cstring, wnd: HWND, lpCC: var CommConfig): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "CommConfigDialogA".} -proc CommConfigDialogA*(lpszName: LPCSTR, wnd: HWND, lpCC: var CommConfig): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "CommConfigDialogA".} -proc CommConfigDialogW*(lpszName: LPWSTR, wnd: HWND, lpCC: var CommConfig): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "CommConfigDialogW".} - #function CompareFileTime(const lpFileTime1, lpFileTime2: FileTime): Longint; stdcall; external 'kernel32' name 'CompareFileTime'; - #function ConvertToAutoInheritPrivateObjectSecurity(ParentDescriptor, CurrentSecurityDescriptor: PSecurityDescriptor; var NewDescriptor: PSecurityDescriptor; ObjectType: PGUID; IsDirectoryObject: WINBOOL; const GenericMapping: GenericMapping): WINBOOL; - # stdcall; external 'advapi32' name 'ConvertToAutoInheritPrivateObjectSecurity'; -proc CopyAcceleratorTable*(hAccelSrc: HACCEL, lpAccelDst: pointer, - cAccelEntries: int): int{.stdcall, dynlib: "user32", - importc: "CopyAcceleratorTableA".} -proc CopyAcceleratorTableA*(hAccelSrc: HACCEL, lpAccelDst: pointer, - cAccelEntries: int): int{.stdcall, dynlib: "user32", - importc: "CopyAcceleratorTableA".} -proc CopyAcceleratorTableW*(hAccelSrc: HACCEL, lpAccelDst: pointer, - cAccelEntries: int): int{.stdcall, dynlib: "user32", - importc: "CopyAcceleratorTableW".} -proc CopyRect*(lprcDst: var Rect, lprcSrc: Rect): WINBOOL{.stdcall, - dynlib: "user32", importc: "CopyRect".} -proc CreateAcceleratorTable*(Accel: pointer, Count: int): HACCEL{.stdcall, - dynlib: "user32", importc: "CreateAcceleratorTableA".} -proc CreateAcceleratorTableA*(Accel: pointer, Count: int): HACCEL{.stdcall, - dynlib: "user32", importc: "CreateAcceleratorTableA".} -proc CreateAcceleratorTableW*(Accel: pointer, Count: int): HACCEL{.stdcall, - dynlib: "user32", importc: "CreateAcceleratorTableW".} - #function CreateBitmapIndirect(const p1: Bitmap): HBITMAP; stdcall; external 'gdi32' name 'CreateBitmapIndirect'; - #function CreateBrushIndirect(const p1: LogBrush): HBRUSH; stdcall; external 'gdi32' name 'CreateBrushIndirect'; -proc CreateColorSpace*(ColorSpace: var LogColorSpace): HCOLORSPACE{.stdcall, - dynlib: "gdi32", importc: "CreateColorSpaceA".} -proc CreateColorSpaceA*(ColorSpace: var LogColorSpace): HCOLORSPACE{.stdcall, - dynlib: "gdi32", importc: "CreateColorSpaceA".} - #function CreateColorSpaceW(var ColorSpace: LogColorSpaceW): HCOLORSPACE; stdcall; external 'gdi32' name 'CreateColorSpaceW'; -proc CreateDialogIndirectParam*(hInstance: HINST, lpTemplate: DlgTemplate, - hWndParent: HWND, lpDialogFunc: TFNDlgProc, - dwInitParam: LPARAM): HWND{.stdcall, - dynlib: "user32", importc: "CreateDialogIndirectParamA".} - #function CreateDialogIndirectParamA(hInstance: HINST; const lpTemplate: DlgTemplate; hWndParent: HWND; lpDialogFunc: TFNDlgProc; dwInitParam: LPARAM): HWND; stdcall; external 'user32' name 'CreateDialogIndirectParamA'; - #function CreateDialogIndirectParamW(hInstance: HINST; const lpTemplate: DlgTemplate; hWndParent: HWND; lpDialogFunc: TFNDlgProc; dwInitParam: LPARAM): HWND; stdcall; external 'user32' name 'CreateDialogIndirectParamW'; - #function CreateDIBitmap(DC: HDC; var InfoHeader: BitmapInfoHeader; dwUsage: DWORD; InitBits: PChar; var InitInfo: BitmapInfo; wUsage: WINUINT): HBITMAP; stdcall; external 'gdi32' name 'CreateDIBitmap'; - #function CreateDIBPatternBrushPt(const p1: pointer; p2: WINUINT): HBRUSH; stdcall; external 'gdi32' name 'CreateDIBPatternBrushPt'; - #function CreateDIBSection(DC: HDC; const p2: BitmapInfo; p3: WINUINT; var p4: pointer; p5: Handle; p6: DWORD): HBITMAP; stdcall; external 'gdi32' name 'CreateDIBSection'; - #function CreateEllipticRgnIndirect(const p1: Rect): HRGN; stdcall; external 'gdi32' name 'CreateEllipticRgnIndirect'; - #function CreateFontIndirect(const p1: LogFont): HFONT;stdcall; external 'gdi32' name 'CreateFontIndirectA'; - #function CreateFontIndirectA(const p1: LogFont): HFONT; stdcall; external 'gdi32' name 'CreateFontIndirectA'; - #function CreateFontIndirectEx(const p1: PEnumLogFontExDV): HFONT;stdcall; external 'gdi32' name 'CreateFontIndirectExA'; - #function CreateFontIndirectExA(const p1: PEnumLogFontExDVA): HFONT;stdcall; external 'gdi32' name 'CreateFontIndirectExA'; - #function CreateFontIndirectExW(const p1: PEnumLogFontExDVW): HFONT;stdcall; external 'gdi32' name 'CreateFontIndirectExW'; - #function CreateFontIndirectW(const p1: LogFontW): HFONT; stdcall; external 'gdi32' name 'CreateFontIndirectW'; -proc CreateIconIndirect*(piconinfo: var IconInfo): HICON{.stdcall, - dynlib: "user32", importc: "CreateIconIndirect".} - #function CreatePalette(const LogPalette: LogPalette): HPalette; stdcall; external 'gdi32' name 'CreatePalette'; - #function CreatePenIndirect(const LogPen: LogPen): HPEN; stdcall; external 'gdi32' name 'CreatePenIndirect'; -proc CreatePipe*(hReadPipe, hWritePipe: var Handle, - lpPipeAttributes: PSecurityAttributes, nSize: DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "CreatePipe".} -proc CreatePolygonRgn*(Points: pointer, Count, FillMode: int): HRGN{.stdcall, - dynlib: "gdi32", importc: "CreatePolygonRgn".} -proc CreatePolyPolygonRgn*(pPtStructs: pointer, pIntArray: pointer, p3, p4: int): HRGN{. - stdcall, dynlib: "gdi32", importc: "CreatePolyPolygonRgn".} - #function CreatePrivateObjectSecurity(ParentDescriptor, CreatorDescriptor: PSecurityDescriptor; var NewDescriptor: PSecurityDescriptor; IsDirectoryObject: WINBOOL; Token: Handle; const GenericMapping: GenericMapping): WINBOOL; - # stdcall; external 'advapi32' name 'CreatePrivateObjectSecurity'; - #function CreatePrivateObjectSecurityEx(ParentDescriptor, CreatorDescriptor: PSecurityDescriptor; var NewDescriptor: PSecurityDescriptor; ObjectType: PGUID; IsContainerObject: WINBOOL; AutoInheritFlags: ULONG; Token: Handle; - # const GenericMapping: GenericMapping): WINBOOL;stdcall; external 'advapi32' name 'CreatePrivateObjectSecurityEx'; -proc CreateProcess*(lpApplicationName: cstring, lpCommandLine: cstring, - lpProcessAttributes, lpThreadAttributes: PSecurityAttributes, - bInheritHandles: WINBOOL, dwCreationFlags: DWORD, - lpEnvironment: pointer, lpCurrentDirectory: cstring, - lpStartupInfo: StartupInfo, - lpProcessInformation: var ProcessInformation): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "CreateProcessA".} -proc CreateProcessA*(lpApplicationName: LPCSTR, lpCommandLine: LPCSTR, - lpProcessAttributes, lpThreadAttributes: PSecurityAttributes, - bInheritHandles: WINBOOL, dwCreationFlags: DWORD, - lpEnvironment: pointer, lpCurrentDirectory: LPCSTR, - lpStartupInfo: StartupInfo, - lpProcessInformation: var ProcessInformation): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "CreateProcessA".} - #function CreateProcessAsUser(hToken: Handle; lpApplicationName: PChar; lpCommandLine: PChar; lpProcessAttributes: PSecurityAttributes; lpThreadAttributes: PSecurityAttributes; bInheritHandles: WINBOOL; dwCreationFlags: DWORD; - # lpEnvironment: pointer; lpCurrentDirectory: PChar; const lpStartupInfo: StartupInfo; var lpProcessInformation: ProcessInformation): WINBOOL;stdcall; external 'advapi32' name 'CreateProcessAsUserA'; - #function CreateProcessAsUserA(hToken: Handle; lpApplicationName: LPCSTR; lpCommandLine: LPCSTR; lpProcessAttributes: PSecurityAttributes; lpThreadAttributes: PSecurityAttributes; bInheritHandles: WINBOOL; dwCreationFlags: DWORD; - # lpEnvironment: pointer; lpCurrentDirectory: LPCSTR; const lpStartupInfo: StartupInfo; var lpProcessInformation: ProcessInformation): WINBOOL; stdcall; external 'advapi32' name 'CreateProcessAsUserA'; - #function CreateProcessAsUserW(hToken: Handle; lpApplicationName: LPWSTR; lpCommandLine: LPWSTR; lpProcessAttributes: PSecurityAttributes; lpThreadAttributes: PSecurityAttributes; bInheritHandles: WINBOOL; dwCreationFlags: DWORD; - # lpEnvironment: pointer; lpCurrentDirectory: LPWSTR; const lpStartupInfo: StartupInfo; var lpProcessInformation: ProcessInformation): WINBOOL; stdcall; external 'advapi32' name 'CreateProcessAsUserW'; -proc CreateProcessW*(lpApplicationName: LPWSTR, lpCommandLine: LPWSTR, - lpProcessAttributes, lpThreadAttributes: PSecurityAttributes, - bInheritHandles: WINBOOL, dwCreationFlags: DWORD, - lpEnvironment: pointer, lpCurrentDirectory: LPWSTR, - lpStartupInfo: StartupInfo, - lpProcessInformation: var ProcessInformation): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "CreateProcessW".} - #function CreateRectRgnIndirect(const p1: Rect): HRGN; stdcall; external 'gdi32' name 'CreateRectRgnIndirect'; -proc CreateRemoteThread*(hProcess: Handle, lpThreadAttributes: pointer, - dwStackSize: DWORD, - lpStartAddress: TFNThreadStartRoutine, - lpParameter: pointer, dwCreationFlags: DWORD, - lpThreadId: var DWORD): Handle{.stdcall, - dynlib: "kernel32", importc: "CreateRemoteThread".} -proc CreateThread*(lpThreadAttributes: pointer, dwStackSize: DWORD, - lpStartAddress: TFNThreadStartRoutine, lpParameter: pointer, - dwCreationFlags: DWORD, lpThreadId: var DWORD): Handle{. - stdcall, dynlib: "kernel32", importc: "CreateThread".} -proc DdeSetQualityOfService*(hWndClient: HWnd, - pqosNew: SecurityQualityOfService, - pqosPrev: PSecurityQualityOfService): WINBOOL{. - stdcall, dynlib: "user32", importc: "DdeSetQualityOfService".} - #function DeleteAce(var pAcl: ACL; dwAceIndex: DWORD): WINBOOL; stdcall; external 'advapi32' name 'DeleteAce'; -proc DescribePixelFormat*(DC: HDC, p2: int, p3: WINUINT, - p4: var PixelFormatDescriptor): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "DescribePixelFormat".} - #function DestroyPrivateObjectSecurity(var ObjectDescriptor: PSecurityDescriptor): WINBOOL; stdcall; external 'advapi32' name 'DestroyPrivateObjectSecurity'; -proc DeviceIoControl*(hDevice: Handle, dwIoControlCode: DWORD, - lpInBuffer: pointer, nInBufferSize: DWORD, - lpOutBuffer: pointer, nOutBufferSize: DWORD, - lpBytesReturned: var DWORD, lpOverlapped: POverlapped): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "DeviceIoControl".} -proc DialogBoxIndirectParam*(hInstance: HINST, lpDialogTemplate: DlgTemplate, - hWndParent: HWND, lpDialogFunc: TFNDlgProc, - dwInitParam: LPARAM): int{.stdcall, - dynlib: "user32", importc: "DialogBoxIndirectParamA".} -proc DialogBoxIndirectParamA*(hInstance: HINST, lpDialogTemplate: DlgTemplate, - hWndParent: HWND, lpDialogFunc: TFNDlgProc, - dwInitParam: LPARAM): int{.stdcall, - dynlib: "user32", importc: "DialogBoxIndirectParamA".} -proc DialogBoxIndirectParamW*(hInstance: HINST, lpDialogTemplate: DlgTemplate, - hWndParent: HWND, lpDialogFunc: TFNDlgProc, - dwInitParam: LPARAM): int{.stdcall, - dynlib: "user32", importc: "DialogBoxIndirectParamW".} -proc DispatchMessage*(lpMsg: TMsg): int32{.stdcall, dynlib: "user32", - importc: "DispatchMessageA".} -proc DispatchMessageA*(lpMsg: TMsg): int32{.stdcall, dynlib: "user32", - importc: "DispatchMessageA".} -proc DispatchMessageW*(lpMsg: TMsg): int32{.stdcall, dynlib: "user32", - importc: "DispatchMessageW".} -proc DosDateTimeToFileTime*(wFatDate, wFatTime: int16, lpFileTime: var FileTime): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "DosDateTimeToFileTime".} -proc DPtoLP*(DC: HDC, Points: pointer, Count: int): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "DPtoLP".} - # function DrawAnimatedRects(wnd: HWND; idAni: Integer; const lprcFrom, lprcTo: Rect): WINBOOL; stdcall; external 'user32' name 'DrawAnimatedRects'; - #function DrawCaption(p1: HWND; p2: HDC; const p3: Rect; p4: WINUINT): WINBOOL; stdcall; external 'user32' name 'DrawCaption'; -proc DrawEdge*(hdc: HDC, qrc: var Rect, edge: WINUINT, grfFlags: WINUINT): WINBOOL{. - stdcall, dynlib: "user32", importc: "DrawEdge".} - #function DrawFocusRect(hDC: HDC; const lprc: Rect): WINBOOL; stdcall; external 'user32' name 'DrawFocusRect'; -proc DrawFrameControl*(DC: HDC, Rect: Rect, uType, uState: WINUINT): WINBOOL{. - stdcall, dynlib: "user32", importc: "DrawFrameControl".} -proc DrawText*(hDC: HDC, lpString: cstring, nCount: int, lpRect: var Rect, - uFormat: WINUINT): int{.stdcall, dynlib: "user32", - importc: "DrawTextA".} -proc DrawTextA*(hDC: HDC, lpString: LPCSTR, nCount: int, lpRect: var Rect, - uFormat: WINUINT): int{.stdcall, dynlib: "user32", - importc: "DrawTextA".} -proc DrawTextEx*(DC: HDC, lpchText: cstring, cchText: int, p4: var Rect, - dwDTFormat: WINUINT, DTParams: PDrawTextParams): int{.stdcall, - dynlib: "user32", importc: "DrawTextExA".} -proc DrawTextExA*(DC: HDC, lpchText: LPCSTR, cchText: int, p4: var Rect, - dwDTFormat: WINUINT, DTParams: PDrawTextParams): int{.stdcall, - dynlib: "user32", importc: "DrawTextExA".} -proc DrawTextExW*(DC: HDC, lpchText: LPWSTR, cchText: int, p4: var Rect, - dwDTFormat: WINUINT, DTParams: PDrawTextParams): int{.stdcall, - dynlib: "user32", importc: "DrawTextExW".} -proc DrawTextW*(hDC: HDC, lpString: LPWSTR, nCount: int, lpRect: var Rect, - uFormat: WINUINT): int{.stdcall, dynlib: "user32", - importc: "DrawTextW".} - #function DuplicateTokenEx(hExistingToken: Handle; dwDesiredAccess: DWORD; lpTokenAttributes: PSecurityAttributes; ImpersonationLevel: TSecurityImpersonationLevel; TokenType: TTokenType; var phNewToken: Handle): WINBOOL; - # stdcall; external 'advapi32' name 'DuplicateTokenEx'; -proc EndPaint*(wnd: HWND, lpPaint: PaintStruct): WINBOOL{.stdcall, - dynlib: "user32", importc: "EndPaint".} - #function EnumDisplayDevices(Unused: pointer; iDevNum: DWORD; var lpDisplayDevice: TDisplayDevice; dwFlags: DWORD): WINBOOL;stdcall; external 'user32' name 'EnumDisplayDevicesA'; - #function EnumDisplayDevicesA(Unused: pointer; iDevNum: DWORD; var lpDisplayDevice: TDisplayDeviceA; dwFlags: DWORD): WINBOOL;stdcall; external 'user32' name 'EnumDisplayDevicesA'; - #function EnumDisplayDevicesW(Unused: pointer; iDevNum: DWORD; var lpDisplayDevice: TDisplayDeviceW; dwFlags: DWORD): WINBOOL;stdcall; external 'user32' name 'EnumDisplayDevicesW'; -proc EnumDisplaySettings*(lpszDeviceName: cstring, iModeNum: DWORD, - lpDevMode: var DevMode): WINBOOL{.stdcall, - dynlib: "user32", importc: "EnumDisplaySettingsA".} -proc EnumDisplaySettingsA*(lpszDeviceName: LPCSTR, iModeNum: DWORD, - lpDevMode: var DevMode): WINBOOL{.stdcall, - dynlib: "user32", importc: "EnumDisplaySettingsA".} -proc EnumDisplaySettingsW*(lpszDeviceName: LPWSTR, iModeNum: DWORD, - lpDevMode: var DevModeW): WINBOOL{.stdcall, - dynlib: "user32", importc: "EnumDisplaySettingsW".} - #function EnumEnhMetaFile(DC: HDC; p2: HENHMETAFILE; p3: TFNEnhMFEnumProc; p4: pointer; const p5: Rect): WINBOOL; stdcall; external 'gdi32' name 'EnumEnhMetaFile'; - #function EnumFontFamiliesEx(DC: HDC; var p2: LogFont; p3: TFNFontEnumProc; p4: LPARAM; p5: DWORD): WINBOOL;stdcall; external 'gdi32' name 'EnumFontFamiliesExA'; - #function EnumFontFamiliesExA(DC: HDC; var p2: LogFont; p3: TFNFontEnumProcA; p4: LPARAM; p5: DWORD): WINBOOL; stdcall; external 'gdi32' name 'EnumFontFamiliesExA'; - #function EnumFontFamiliesExW(DC: HDC; var p2: LogFontW; p3: TFNFontEnumProcW; p4: LPARAM; p5: DWORD): WINBOOL; stdcall; external 'gdi32' name 'EnumFontFamiliesExW'; - #function EqualRect(const lprc1, lprc2: Rect): WINBOOL; stdcall; external 'user32' name 'EqualRect'; -proc ExtCreatePen*(PenStyle, Width: DWORD, Brush: LogBrush, StyleCount: DWORD, - Style: pointer): HPEN{.stdcall, dynlib: "gdi32", - importc: "ExtCreatePen".} -proc ExtCreateRegion*(p1: PXForm, p2: DWORD, p3: RgnData): HRGN{.stdcall, - dynlib: "gdi32", importc: "ExtCreateRegion".} - # function ExtEscape(DC: HDC; p2, p3: Integer; const p4: LPCSTR; p5: Integer; p6: LPSTR): Integer; stdcall; external 'gdi32' name 'ExtEscape'; -proc FileTimeToDosDateTime*(lpFileTime: FileTime, - lpFatDate, lpFatTime: var int16): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "FileTimeToDosDateTime".} -proc FileTimeToLocalFileTime*(lpFileTime: FileTime, - lpLocalFileTime: var FileTime): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "FileTimeToLocalFileTime".} -proc FileTimeToSystemTime*(lpFileTime: FileTime, lpSystemTime: var SystemTime): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "FileTimeToSystemTime".} -proc FillConsoleOutputAttribute*(hConsoleOutput: Handle, wAttribute: int16, - nLength: DWORD, dwWriteCoord: Coord, - lpNumberOfAttrsWritten: var DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "FillConsoleOutputAttribute".} -proc FillConsoleOutputCharacter*(hConsoleOutput: Handle, cCharacter: char, - nLength: DWORD, dwWriteCoord: Coord, - lpNumberOfCharsWritten: var DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "FillConsoleOutputCharacterA".} -proc FillConsoleOutputCharacterA*(hConsoleOutput: Handle, cCharacter: char, - nLength: DWORD, dwWriteCoord: Coord, - lpNumberOfCharsWritten: var DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "FillConsoleOutputCharacterA".} -proc FillConsoleOutputCharacterW*(hConsoleOutput: Handle, cCharacter: WideChar, - nLength: DWORD, dwWriteCoord: Coord, - lpNumberOfCharsWritten: var DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "FillConsoleOutputCharacterW".} - #function FillRect(hDC: HDC; const lprc: Rect; hbr: HBRUSH): Integer; stdcall; external 'user32' name 'FillRect'; -proc FindFirstFile*(lpFileName: cstring, lpFindFileData: var WIN32FindData): Handle{. - stdcall, dynlib: "kernel32", importc: "FindFirstFileA".} -proc FindFirstFileA*(lpFileName: LPCSTR, lpFindFileData: var WIN32FindData): Handle{. - stdcall, dynlib: "kernel32", importc: "FindFirstFileA".} -proc FindFirstFileW*(lpFileName: LPWSTR, lpFindFileData: var WIN32FindDataW): Handle{. - stdcall, dynlib: "kernel32", importc: "FindFirstFileW".} - #function FindFirstFreeAce(var pAcl: ACL; var pAce: pointer): WINBOOL; stdcall; external 'advapi32' name 'FindFirstFreeAce'; -proc FindNextFile*(hFindFile: Handle, lpFindFileData: var WIN32FindData): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "FindNextFileA".} -proc FindNextFileA*(hFindFile: Handle, lpFindFileData: var WIN32FindData): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "FindNextFileA".} -proc FindNextFileW*(hFindFile: Handle, lpFindFileData: var WIN32FindDataW): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "FindNextFileW".} - #function FlushInstructionCache(hProcess: Handle; const lpBaseAddress: pointer; dwSize: DWORD): WINBOOL; stdcall; external 'kernel32' name 'FlushInstructionCache'; - #function FlushViewOfFile(const lpBaseAddress: pointer; dwNumberOfBytesToFlush: DWORD): WINBOOL; stdcall; external 'kernel32' name 'FlushViewOfFile'; - #function FrameRect(hDC: HDC; const lprc: Rect; hbr: HBRUSH): Integer; stdcall; external 'user32' name 'FrameRect'; - #function GetAce(const pAcl: ACL; dwAceIndex: DWORD; var pAce: pointer): WINBOOL; stdcall; external 'advapi32' name 'GetAce'; - #function GetAclInformation(const pAcl: ACL; pAclInformation: pointer; nAclInformationLength: DWORD; dwAclInformationClass: AclInformationClass): WINBOOL; stdcall; external 'advapi32' name 'GetAclInformation'; - #function GetAltTabInfo(wnd: HWND; iItem: Integer; var pati: TAltTabInfo; pszItemText: PChar; cchItemText: WINUINT): WINBOOL;stdcall; external 'user32' name 'GetAltTabInfoA'; - #function GetAltTabInfoA(wnd: HWND; iItem: Integer; var pati: TAltTabInfo; pszItemText: LPCSTR; cchItemText: WINUINT): WINBOOL;stdcall; external 'user32' name 'GetAltTabInfoA'; - #function GetAltTabInfoW(wnd: HWND; iItem: Integer; var pati: TAltTabInfo; pszItemText: LPWSTR; cchItemText: WINUINT): WINBOOL;stdcall; external 'user32' name 'GetAltTabInfoW'; -proc GetAspectRatioFilterEx*(DC: HDC, p2: var Size): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "GetAspectRatioFilterEx".} -proc GetBinaryType*(lpApplicationName: cstring, lpBinaryType: var DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetBinaryTypeA".} -proc GetBinaryTypeA*(lpApplicationName: LPCSTR, lpBinaryType: var DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetBinaryTypeA".} -proc GetBinaryTypeW*(lpApplicationName: LPWSTR, lpBinaryType: var DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetBinaryTypeW".} -proc GetBitmapDimensionEx*(p1: HBITMAP, p2: var Size): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "GetBitmapDimensionEx".} -proc GetBoundsRect*(DC: HDC, p2: var Rect, p3: WINUINT): WINUINT{.stdcall, - dynlib: "gdi32", importc: "GetBoundsRect".} -proc GetBrushOrgEx*(DC: HDC, p2: var Point): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "GetBrushOrgEx".} -proc GetCaretPos*(lpPoint: var Point): WINBOOL{.stdcall, dynlib: "user32", - importc: "GetCaretPos".} -proc GetCharABCWidths*(DC: HDC, p2, p3: WINUINT, ABCStructs: pointer): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "GetCharABCWidthsA".} -proc GetCharABCWidthsA*(DC: HDC, p2, p3: WINUINT, ABCStructs: pointer): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "GetCharABCWidthsA".} -proc GetCharABCWidthsFloat*(DC: HDC, p2, p3: WINUINT, ABCFloatSturcts: pointer): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "GetCharABCWidthsFloatA".} -proc GetCharABCWidthsFloatA*(DC: HDC, p2, p3: WINUINT, ABCFloatSturcts: pointer): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "GetCharABCWidthsFloatA".} -proc GetCharABCWidthsFloatW*(DC: HDC, p2, p3: WINUINT, ABCFloatSturcts: pointer): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "GetCharABCWidthsFloatW".} - #function GetCharABCWidthsI(DC: HDC; p2, p3: WINUINT; p4: PWORD; const Widths): WINBOOL;stdcall; external 'gdi32' name 'GetCharABCWidthsI'; -proc GetCharABCWidthsW*(DC: HDC, p2, p3: WINUINT, ABCStructs: pointer): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "GetCharABCWidthsW".} -proc GetCharacterPlacement*(DC: HDC, p2: cstring, p3, p4: WINBOOL, - p5: var GCPResults, p6: DWORD): DWORD{.stdcall, - dynlib: "gdi32", importc: "GetCharacterPlacementA".} -proc GetCharacterPlacementA*(DC: HDC, p2: LPCSTR, p3, p4: WINBOOL, - p5: var GCPResults, p6: DWORD): DWORD{.stdcall, - dynlib: "gdi32", importc: "GetCharacterPlacementA".} -proc GetCharacterPlacementW*(DC: HDC, p2: LPWSTR, p3, p4: WINBOOL, - p5: var GCPResults, p6: DWORD): DWORD{.stdcall, - dynlib: "gdi32", importc: "GetCharacterPlacementW".} -proc GetCharWidth*(DC: HDC, p2, p3: WINUINT, Widths: pointer): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "GetCharWidthA".} -proc GetCharWidth32*(DC: HDC, p2, p3: WINUINT, Widths: pointer): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "GetCharWidth32A".} -proc GetCharWidth32A*(DC: HDC, p2, p3: WINUINT, Widths: pointer): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "GetCharWidth32A".} -proc GetCharWidth32W*(DC: HDC, p2, p3: WINUINT, Widths: pointer): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "GetCharWidth32W".} -proc GetCharWidthA*(DC: HDC, p2, p3: WINUINT, Widths: pointer): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "GetCharWidthA".} -proc GetCharWidthFloat*(DC: HDC, p2, p3: WINUINT, Widths: pointer): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "GetCharWidthFloatA".} -proc GetCharWidthFloatA*(DC: HDC, p2, p3: WINUINT, Widths: pointer): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "GetCharWidthFloatA".} -proc GetCharWidthFloatW*(DC: HDC, p2, p3: WINUINT, Widths: pointer): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "GetCharWidthFloatW".} - #function GetCharWidthI(DC: HDC; p2, p3: WINUINT; p4: PWORD; const Widths:pointer): WINBOOL;stdcall; external 'gdi32' name 'GetCharWidthI'; -proc GetCharWidthW*(DC: HDC, p2, p3: WINUINT, Widths: pointer): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "GetCharWidthW".} -proc GetClassInfo*(hInstance: HINST, lpClassName: cstring, - lpWndClass: var WndClass): WINBOOL{.stdcall, - dynlib: "user32", importc: "GetClassInfoA".} -proc GetClassInfoA*(hInstance: HINST, lpClassName: LPCSTR, - lpWndClass: var WndClass): WINBOOL{.stdcall, - dynlib: "user32", importc: "GetClassInfoA".} -proc GetClassInfoEx*(Instance: HINST, Classname: cstring, - WndClass: var WndClassEx): WINBOOL{.stdcall, - dynlib: "user32", importc: "GetClassInfoExA".} - #function GetClassInfoExA(Instance: HINST; Classname: LPCSTR; var WndClass: WndClassEx): WINBOOL; stdcall; external 'user32' name 'GetClassInfoExA'; - #function GetClassInfoExW(Instance: HINST; Classname: LPWSTR; var WndClass: WndClassExW): WINBOOL; stdcall; external 'user32' name 'GetClassInfoExW'; - #function GetClassInfoW(hInstance: HINST; lpClassName: LPWSTR; var lpWndClass: WndClassW): WINBOOL; stdcall; external 'user32' name 'GetClassInfoW'; -proc GetClientRect*(wnd: HWND, lpRect: var Rect): WINBOOL{.stdcall, - dynlib: "user32", importc: "GetClientRect".} -proc GetClipBox*(DC: HDC, Rect: var Rect): int{.stdcall, dynlib: "gdi32", - importc: "GetClipBox".} -proc GetClipCursor*(lpRect: var Rect): WINBOOL{.stdcall, dynlib: "user32", - importc: "GetClipCursor".} -proc GetColorAdjustment*(DC: HDC, p2: var ColorAdjustment): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "GetColorAdjustment".} -proc GetCommConfig*(hCommDev: Handle, lpCC: var CommConfig, - lpdwSize: var DWORD): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "GetCommConfig".} -proc GetCommMask*(hFile: Handle, lpEvtMask: var DWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetCommMask".} -proc GetCommModemStatus*(hFile: Handle, lpModemStat: var DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetCommModemStatus".} -proc GetCommProperties*(hFile: Handle, lpCommProp: var CommProp): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetCommProperties".} -proc GetCommState*(hFile: Handle, lpDCB: var DCB): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetCommState".} -proc GetCommTimeouts*(hFile: Handle, lpCommTimeouts: var CommTimeouts): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetCommTimeouts".} -proc GetComputerName*(lpBuffer: cstring, nSize: var DWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetComputerNameA".} -proc GetComputerNameA*(lpBuffer: LPCSTR, nSize: var DWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetComputerNameA".} -proc GetComputerNameW*(lpBuffer: LPWSTR, nSize: var DWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetComputerNameW".} -proc GetConsoleCursorInfo*(hConsoleOutput: Handle, - lpConsoleCursorInfo: var ConsoleCursorInfo): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetConsoleCursorInfo".} -proc GetConsoleMode*(hConsoleHandle: Handle, lpMode: var DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetConsoleMode".} -proc GetConsoleScreenBufferInfo*(hConsoleOutput: Handle, - lpConsoleScreenBufferInfo: var ConsoleScreenBufferInfo): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetConsoleScreenBufferInfo".} -proc GetCPInfo*(CodePage: WINUINT, lpCPInfo: var CPInfo): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetCPInfo".} - #function GetCurrentHwProfile(var lpHwProfileInfo: THWProfileInfo): WINBOOL;stdcall; external 'advapi32' name 'GetCurrentHwProfileA'; - #function GetCurrentHwProfileA(var lpHwProfileInfo: THWProfileInfoA): WINBOOL;stdcall; external 'advapi32' name 'GetCurrentHwProfileA'; - #function GetCurrentHwProfileW(var lpHwProfileInfo: THWProfileInfoW): WINBOOL;stdcall; external 'advapi32' name 'GetCurrentHwProfileW'; -proc GetCursorInfo*(pci: var ConsoleCursorInfo): WINBOOL{.stdcall, dynlib: "user32", - importc: "GetCursorInfo".} -proc GetCursorPos*(lpPoint: var Point): WINBOOL{.stdcall, dynlib: "user32", - importc: "GetCursorPos".} -proc GetDCOrgEx*(DC: HDC, Origin: var Point): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "GetDCOrgEx".} -proc GetDefaultCommConfig*(lpszName: cstring, lpCC: var CommConfig, - lpdwSize: var DWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetDefaultCommConfigA".} -proc GetDefaultCommConfigA*(lpszName: LPCSTR, lpCC: var CommConfig, - lpdwSize: var DWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetDefaultCommConfigA".} -proc GetDefaultCommConfigW*(lpszName: LPWSTR, lpCC: var CommConfig, - lpdwSize: var DWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetDefaultCommConfigW".} -proc GetDIBColorTable*(DC: HDC, p2, p3: WINUINT, RGBQuadStructs: pointer): WINUINT{. - stdcall, dynlib: "gdi32", importc: "GetDIBColorTable".} -proc GetDIBits*(DC: HDC, Bitmap: HBitmap, StartScan, NumScans: WINUINT, - Bits: pointer, BitInfo: var BitmapInfo, Usage: WINUINT): int{. - stdcall, dynlib: "gdi32", importc: "GetDIBits".} -proc GetDiskFreeSpace*(lpRootPathName: cstring, lpSectorsPerCluster, - lpBytesPerSector, lpNumberOfFreeClusters, lpTotalNumberOfClusters: var DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetDiskFreeSpaceA".} -proc GetDiskFreeSpaceA*(lpRootPathName: LPCSTR, lpSectorsPerCluster, - lpBytesPerSector, lpNumberOfFreeClusters, lpTotalNumberOfClusters: var DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetDiskFreeSpaceA".} -proc GetDiskFreeSpaceEx*(lpDirectoryName: cstring, lpFreeBytesAvailableToCaller, - lpTotalNumberOfBytes: var LargeInteger, - lpTotalNumberOfFreeBytes: PLargeInteger): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetDiskFreeSpaceExA".} -proc GetDiskFreeSpaceExA*(lpDirectoryName: LPCSTR, lpFreeBytesAvailableToCaller, - lpTotalNumberOfBytes: var LargeInteger, - lpTotalNumberOfFreeBytes: PLargeInteger): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetDiskFreeSpaceExA".} -proc GetDiskFreeSpaceExW*(lpDirectoryName: LPWSTR, lpFreeBytesAvailableToCaller, - lpTotalNumberOfBytes: var LargeInteger, - lpTotalNumberOfFreeBytes: PLargeInteger): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetDiskFreeSpaceExW".} -proc GetDiskFreeSpaceW*(lpRootPathName: LPWSTR, lpSectorsPerCluster, - lpBytesPerSector, lpNumberOfFreeClusters, lpTotalNumberOfClusters: var DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetDiskFreeSpaceW".} -proc GetDiskFreeSpaceEx*(lpDirectoryName: cstring, lpFreeBytesAvailableToCaller, - lpTotalNumberOfBytes: PLargeInteger, lpTotalNumberOfFreeBytes: PLargeInteger): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetDiskFreeSpaceExA".} -proc GetDiskFreeSpaceExA*(lpDirectoryName: LPCSTR, lpFreeBytesAvailableToCaller, - lpTotalNumberOfBytes: PLargeInteger, lpTotalNumberOfFreeBytes: PLargeInteger): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetDiskFreeSpaceExA".} -proc GetDiskFreeSpaceExW*(lpDirectoryName: LPWSTR, lpFreeBytesAvailableToCaller, - lpTotalNumberOfBytes: PLargeInteger, lpTotalNumberOfFreeBytes: PLargeInteger): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetDiskFreeSpaceExW".} - #function GetEnhMetaFilePixelFormat(p1: HENHMETAFILE; p2: Cardinal; var p3: PixelFormatDescriptor): WINUINT;stdcall; external 'gdi32' name 'GetEnhMetaFilePixelFormat'; -proc GetExitCodeProcess*(hProcess: Handle, lpExitCode: var DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetExitCodeProcess".} -proc GetExitCodeThread*(hThread: Handle, lpExitCode: var DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetExitCodeThread".} -proc GetFileInformationByHandle*(hFile: Handle, lpFileInformation: var ByHandleFileInformation): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetFileInformationByHandle".} - #function GetFileSecurity(lpFileName: PChar; RequestedInformation: SECURITY_INFORMATION; pSecurityDescriptor: PSecurityDescriptor; nLength: DWORD; var lpnLengthNeeded: DWORD): WINBOOL;stdcall; external 'advapi32' name 'GetFileSecurityA'; - #function GetFileSecurityA(lpFileName: LPCSTR; RequestedInformation: SECURITY_INFORMATION; pSecurityDescriptor: PSecurityDescriptor; nLength: DWORD; var lpnLengthNeeded: DWORD): WINBOOL; stdcall; external 'advapi32' name 'GetFileSecurityA'; - #function GetFileSecurityW(lpFileName: LPWSTR; RequestedInformation: SECURITY_INFORMATION; pSecurityDescriptor: PSecurityDescriptor; nLength: DWORD; var lpnLengthNeeded: DWORD): WINBOOL; stdcall; external 'advapi32' name 'GetFileSecurityW'; -proc GetFileVersionInfoSize*(lptstrFilename: cstring, lpdwHandle: var DWORD): DWORD{. - stdcall, dynlib: "version", importc: "GetFileVersionInfoSizeA".} -proc GetFileVersionInfoSizeA*(lptstrFilename: LPCSTR, lpdwHandle: var DWORD): DWORD{. - stdcall, dynlib: "version", importc: "GetFileVersionInfoSizeA".} -proc GetFileVersionInfoSizeW*(lptstrFilename: LPWSTR, lpdwHandle: var DWORD): DWORD{. - stdcall, dynlib: "version", importc: "GetFileVersionInfoSizeW".} - # removed because old definition was wrong ! - # function GetFullPathName(lpFileName: PChar; nBufferLength: DWORD; lpBuffer: PChar; var lpFilePart: PChar): DWORD;stdcall; external 'kernel32' name 'GetFullPathNameA'; - # function GetFullPathNameA(lpFileName: LPCSTR; nBufferLength: DWORD; lpBuffer: LPCSTR; var lpFilePart: LPCSTR): DWORD; stdcall; external 'kernel32' name 'GetFullPathNameA'; - # function GetFullPathNameW(lpFileName: LPWSTR; nBufferLength: DWORD; lpBuffer: LPWSTR; var lpFilePart: LPWSTR): DWORD; stdcall; external 'kernel32' name 'GetFullPathNameW'; -proc GetGlyphOutline*(DC: HDC, p2, p3: WINUINT, p4: GlyphMetrics, p5: DWORD, - p6: pointer, p7: Mat2): DWORD{.stdcall, dynlib: "gdi32", - importc: "GetGlyphOutlineA".} -proc GetGlyphOutlineA*(DC: HDC, p2, p3: WINUINT, p4: GlyphMetrics, p5: DWORD, - p6: pointer, p7: Mat2): DWORD{.stdcall, dynlib: "gdi32", - importc: "GetGlyphOutlineA".} -proc GetGlyphOutlineW*(DC: HDC, p2, p3: WINUINT, p4: GlyphMetrics, p5: DWORD, - p6: pointer, p7: Mat2): DWORD{.stdcall, dynlib: "gdi32", - importc: "GetGlyphOutlineW".} - #function GetGUIThreadInfo(idThread: DWORD; var pgui: TGUIThreadinfo): WINBOOL;stdcall; external 'user32' name 'GetGUIThreadInfo'; -proc GetHandleInformation*(hObject: Handle, lpdwFlags: var DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetHandleInformation".} - #function GetICMProfile(DC: HDC; var Size: DWORD; Name: PChar): WINBOOL;stdcall; external 'gdi32' name 'GetICMProfileA'; - #function GetICMProfileA(DC: HDC; var Size: DWORD; Name: LPCSTR): WINBOOL; stdcall; external 'gdi32' name 'GetICMProfileA'; - #function GetICMProfileW(DC: HDC; var Size: DWORD; Name: LPWSTR): WINBOOL; stdcall; external 'gdi32' name 'GetICMProfileW'; -proc GetIconInfo*(icon: HICON, piconinfo: var IconInfo): WINBOOL{.stdcall, - dynlib: "user32", importc: "GetIconInfo".} - #function GetKernelObjectSecurity(Handle: Handle; RequestedInformation: SECURITY_INFORMATION; pSecurityDescriptor: PSecurityDescriptor; nLength: DWORD; var lpnLengthNeeded: DWORD): WINBOOL; stdcall; external 'advapi32' name 'GetKernelObjectSecurity'; -proc GetKerningPairs*(DC: HDC, Count: DWORD, KerningPairs: pointer): DWORD{. - stdcall, dynlib: "gdi32", importc: "GetKerningPairs".} -proc GetKeyboardLayoutList*(nBuff: int, List: pointer): WINUINT{.stdcall, - dynlib: "user32", importc: "GetKeyboardLayoutList".} - #function GetKeyboardState(var KeyState: TKeyboardState): WINBOOL; stdcall; external 'user32' name 'GetKeyboardState'; - #function GetLastInputInfo(var plii: TLastInputInfo): WINBOOL;stdcall; external 'user32' name 'GetLastInputInfo'; -proc GetSystemTime*(lpSystemTime: var SYSTEMTIME){.stdcall, dynlib: "kernel32", - importc: "GetSystemTime".} -proc GetLocalTime*(SystemTime: var SYSTEMTIME){.stdcall, dynlib: "kernel32", - importc: "GetLocalTime".} -proc GetSystemInfo*(SystemInfo: var SYSTEM_INFO){.stdcall, dynlib: "kernel32", - importc: "GetSystemInfo".} -proc SetSystemTime*(lpSystemTime: var SYSTEMTIME): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "SetSystemTime".} -proc SetLocalTime*(lpSystemTime: var SYSTEMTIME): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "SetLocalTime".} -proc GetLogColorSpace*(p1: HCOLORSPACE, ColorSpace: var LogColorSpace, - Size: DWORD): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "GetLogColorSpaceA".} -proc GetLogColorSpaceA*(p1: HCOLORSPACE, ColorSpace: var LogColorSpace, - Size: DWORD): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "GetLogColorSpaceA".} - #function GetLogColorSpaceW(p1: HCOLORSPACE; var ColorSpace: LogColorSpaceW; Size: DWORD): WINBOOL; stdcall; external 'gdi32' name 'GetLogColorSpaceW'; -proc GetMailslotInfo*(hMailslot: Handle, lpMaxMessageSize: pointer, - lpNextSize: var DWORD, - lpMessageCount, lpReadTimeout: pointer): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetMailslotInfo".} - #function GetMenuBarInfo(hend: HWND; idObject, idItem: Longint; var pmbi: TMenuBarInfo): WINBOOL;stdcall; external 'user32' name 'GetMenuBarInfo'; - #function GetMenuInfo(menu: HMENU; var lpmi: TMenuInfo): WINBOOL;stdcall; external 'user32' name 'GetMenuInfo'; -proc GetMenuItemInfo*(p1: HMENU, p2: WINUINT, p3: WINBOOL, p4: var MenuItemInfo): WINBOOL{. - stdcall, dynlib: "user32", importc: "GetMenuItemInfoA".} -proc GetMenuItemInfoA*(p1: HMENU, p2: WINUINT, p3: WINBOOL, p4: var MenuItemInfo): WINBOOL{. - stdcall, dynlib: "user32", importc: "GetMenuItemInfoA".} - #function GetMenuItemInfoW(p1: HMENU; p2: WINUINT; p3: WINBOOL; var p4: MenuItemInfoW): WINBOOL; stdcall; external 'user32' name 'GetMenuItemInfoW'; -proc GetMenuItemRect*(wnd: HWND, menu: HMENU, uItem: WINUINT, lprcItem: var Rect): WINBOOL{. - stdcall, dynlib: "user32", importc: "GetMenuItemRect".} -proc GetMessage*(lpMsg: var TMsg, wnd: HWND, wMsgFilterMin, wMsgFilterMax: WINUINT): WINBOOL{. - stdcall, dynlib: "user32", importc: "GetMessageA".} -proc GetMessageA*(lpMsg: var TMsg, wnd: HWND, - wMsgFilterMin, wMsgFilterMax: WINUINT): WINBOOL{.stdcall, - dynlib: "user32", importc: "GetMessageA".} -proc GetMessageW*(lpMsg: var TMsg, wnd: HWND, - wMsgFilterMin, wMsgFilterMax: WINUINT): WINBOOL{.stdcall, - dynlib: "user32", importc: "GetMessageW".} -proc GetMiterLimit*(DC: HDC, Limit: var float32): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "GetMiterLimit".} - #function GetMouseMovePoints(cbSize: WINUINT; var lppt, lpptBuf: TMouseMovePoint; nBufPoints: Integer; resolution: DWORD): Integer;stdcall; external 'user32' name 'GetMouseMovePoints'; -proc GetNamedPipeInfo*(hNamedPipe: Handle, lpFlags: var DWORD, - lpOutBufferSize, lpInBufferSize, lpMaxInstances: pointer): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetNamedPipeInfo".} -proc GetNumberOfConsoleInputEvents*(hConsoleInput: Handle, - lpNumberOfEvents: var DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetNumberOfConsoleInputEvents".} -proc GetNumberOfConsoleMouseButtons*(lpNumberOfMouseButtons: var DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetNumberOfConsoleMouseButtons".} - #function GetNumberOfEventLogRecords(hEventLog: Handle; var NumberOfRecords: DWORD): WINBOOL; stdcall; external 'advapi32' name 'GetNumberOfEventLogRecords'; - #function GetOldestEventLogRecord(hEventLog: Handle; var OldestRecord: DWORD): WINBOOL; stdcall; external 'advapi32' name 'GetOldestEventLogRecord'; -proc GetOverlappedResult*(hFile: Handle, lpOverlapped: Overlapped, - lpNumberOfBytesTransferred: var DWORD, bWait: WINBOOL): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetOverlappedResult".} -proc GetPaletteEntries*(Palette: HPALETTE, StartIndex, NumEntries: WINUINT, - PaletteEntries: pointer): WINUINT{.stdcall, - dynlib: "gdi32", importc: "GetPaletteEntries".} -proc GetPath*(DC: HDC, Points, Types: pointer, nSize: int): int{.stdcall, - dynlib: "gdi32", importc: "GetPath".} -proc GetPriorityClipboardFormat*(paFormatPriorityList: pointer, cFormats: int): int{. - stdcall, dynlib: "user32", importc: "GetPriorityClipboardFormat".} - #function GetPrivateObjectSecurity(ObjectDescriptor: PSecurityDescriptor; SecurityInformation: SECURITY_INFORMATION; ResultantDescriptor: PSecurityDescriptor; DescriptorLength: DWORD; var ReturnLength: DWORD): WINBOOL; - # stdcall; external 'advapi32' name 'GetPrivateObjectSecurity'; -proc GetPrivateProfileSectionNamesA*(lpszReturnBuffer: LPSTR, nSize: DWORD, - lpFileName: LPCSTR): DWORD{.stdcall, - dynlib: "kernel32", importc: "GetPrivateProfileSectionNamesA".} -proc GetPrivateProfileSectionNamesW*(lpszReturnBuffer: LPWSTR, nSize: DWORD, - lpFileName: LPCWSTR): DWORD{.stdcall, - dynlib: "kernel32", importc: "GetPrivateProfileSectionNamesW".} -proc GetPrivateProfileSectionNames*(lpszReturnBuffer: LPTSTR, nSize: DWORD, - lpFileName: LPCTSTR): DWORD{.stdcall, - dynlib: "kernel32", importc: "GetPrivateProfileSectionNamesA".} -proc GetPrivateProfileStructA*(lpszSection, lpszKey: LPCSTR, lpStruct: LPVOID, - uSizeStruct: WINUINT, szFile: LPCSTR): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetPrivateProfileStructA".} -proc GetPrivateProfileStructW*(lpszSection, lpszKey: LPCWSTR, lpStruct: LPVOID, - uSizeStruct: WINUINT, szFile: LPCWSTR): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetPrivateProfileStructW".} -proc GetPrivateProfileStruct*(lpszSection, lpszKey: LPCTSTR, lpStruct: LPVOID, - uSizeStruct: WINUINT, szFile: LPCTSTR): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetPrivateProfileStructA".} -proc GetProcessAffinityMask*(hProcess: Handle, lpProcessAffinityMask, - lpSystemAffinityMask: var DWORD): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "GetProcessAffinityMask".} -proc GetProcessHeaps*(NumberOfHeaps: DWORD, ProcessHeaps: var Handle): DWORD{. - stdcall, dynlib: "kernel32", importc: "GetProcessHeaps".} -proc GetProcessPriorityBoost*(hThread: Handle, - DisablePriorityBoost: var WINBOOL): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetProcessPriorityBoost".} -proc GetProcessShutdownParameters*(lpdwLevel, lpdwFlags: var DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetProcessShutdownParameters".} -proc GetProcessTimes*(hProcess: Handle, lpCreationTime, lpExitTime, - lpKernelTime, lpUserTime: var FileTime): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetProcessTimes".} -proc GetProcessWorkingSetSize*(hProcess: Handle, lpMinimumWorkingSetSize, - lpMaximumWorkingSetSize: var DWORD): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "GetProcessWorkingSetSize".} -proc GetQueuedCompletionStatus*(CompletionPort: Handle, - lpNumberOfBytesTransferred, lpCompletionKey: var DWORD, - lpOverlapped: var POverlapped, - dwMilliseconds: DWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetQueuedCompletionStatus".} -proc GetRasterizerCaps*(p1: var RasterizerStatus, p2: WINUINT): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "GetRasterizerCaps".} -proc GetRgnBox*(RGN: HRGN, p2: var Rect): int{.stdcall, dynlib: "gdi32", - importc: "GetRgnBox".} -proc GetScrollInfo*(wnd: HWND, BarFlag: int, ScrollInfo: var ScrollInfo): WINBOOL{. - stdcall, dynlib: "user32", importc: "GetScrollInfo".} -proc GetScrollRange*(wnd: HWND, nBar: int, lpMinPos, lpMaxPos: var int): WINBOOL{. - stdcall, dynlib: "user32", importc: "GetScrollRange".} - #function GetSecurityDescriptorControl(pSecurityDescriptor: PSecurityDescriptor; var pControl: SECURITY_DESCRIPTOR_CONTROL; var lpdwRevision: DWORD): WINBOOL; stdcall; external 'advapi32' name 'GetSecurityDescriptorControl'; - #function GetSecurityDescriptorDacl(pSecurityDescriptor: PSecurityDescriptor; var lpbDaclPresent: WINBOOL; var pDacl: PACL; var lpbDaclDefaulted: WINBOOL): WINBOOL; stdcall; external 'advapi32' name 'GetSecurityDescriptorDacl'; - #function GetSecurityDescriptorGroup(pSecurityDescriptor: PSecurityDescriptor; var pGroup: PSID; var lpbGroupDefaulted: WINBOOL): WINBOOL; stdcall; external 'advapi32' name 'GetSecurityDescriptorGroup'; - #function GetSecurityDescriptorOwner(pSecurityDescriptor: PSecurityDescriptor; var pOwner: PSID; var lpbOwnerDefaulted: WINBOOL): WINBOOL; stdcall; external 'advapi32' name 'GetSecurityDescriptorOwner'; - #function GetSecurityDescriptorSacl(pSecurityDescriptor: PSecurityDescriptor; var lpbSaclPresent: WINBOOL; var pSacl: PACL; var lpbSaclDefaulted: WINBOOL): WINBOOL; stdcall; external 'advapi32' name 'GetSecurityDescriptorSacl'; -proc GetStartupInfo*(lpStartupInfo: var STARTUPINFO){.stdcall, - dynlib: "kernel32", importc: "GetStartupInfoA".} -proc GetStringTypeA*(Locale: LCID, dwInfoType: DWORD, lpSrcStr: LPCSTR, - cchSrc: WINBOOL, lpCharType: var int16): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetStringTypeA".} -proc GetStringTypeEx*(Locale: LCID, dwInfoType: DWORD, lpSrcStr: cstring, - cchSrc: int, lpCharType: var int16): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetStringTypeExA".} -proc GetStringTypeExA*(Locale: LCID, dwInfoType: DWORD, lpSrcStr: LPCSTR, - cchSrc: int, lpCharType: var int16): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetStringTypeExA".} -proc GetStringTypeExW*(Locale: LCID, dwInfoType: DWORD, lpSrcStr: LPWSTR, - cchSrc: int, lpCharType: var int16): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetStringTypeExW".} -proc GetStringTypeW*(dwInfoType: DWORD, lpSrcStr: WCHAR, cchSrc: WINBOOL, - lpCharType: var int16): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetStringTypeW".} -proc GetSystemPaletteEntries*(DC: HDC, StartIndex, NumEntries: WINUINT, - PaletteEntries: pointer): WINUINT{.stdcall, - dynlib: "gdi32", importc: "GetSystemPaletteEntries".} -proc GetSystemPowerStatus*(lpSystemPowerStatus: var SystemPowerStatus): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetSystemPowerStatus".} -proc GetSystemTimeAdjustment*(lpTimeAdjustment, lpTimeIncrement: var DWORD, - lpTimeAdjustmentDisabled: var WINBOOL): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetSystemTimeAdjustment".} -proc GetSystemTimeAsFileTime*(lpSystemTimeAsFileTime: var FILETIME){.stdcall, - dynlib: "kernel32", importc: "GetSystemTimeAsFileTime".} -proc GetTabbedTextExtent*(hDC: HDC, lpString: cstring, - nCount, nTabPositions: int, - lpnTabStopPositions: pointer): DWORD{.stdcall, - dynlib: "user32", importc: "GetTabbedTextExtentA".} -proc GetTabbedTextExtentA*(hDC: HDC, lpString: LPCSTR, - nCount, nTabPositions: int, - lpnTabStopPositions: pointer): DWORD{.stdcall, - dynlib: "user32", importc: "GetTabbedTextExtentA".} -proc GetTabbedTextExtentW*(hDC: HDC, lpString: LPWSTR, - nCount, nTabPositions: int, - lpnTabStopPositions: pointer): DWORD{.stdcall, - dynlib: "user32", importc: "GetTabbedTextExtentW".} -proc GetTapeParameters*(hDevice: Handle, dwOperation: DWORD, - lpdwSize: var DWORD, lpTapeInformation: pointer): DWORD{. - stdcall, dynlib: "kernel32", importc: "GetTapeParameters".} -proc GetTapePosition*(hDevice: Handle, dwPositionType: DWORD, - lpdwPartition, lpdwOffsetLow: var DWORD, - lpdwOffsetHigh: pointer): DWORD{.stdcall, - dynlib: "kernel32", importc: "GetTapePosition".} -proc GetTextExtentExPoint*(DC: HDC, p2: cstring, p3, p4: int, p5, p6: PInteger, - p7: var Size): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "GetTextExtentExPointA".} -proc GetTextExtentExPointA*(DC: HDC, p2: LPCSTR, p3, p4: int, p5, p6: PInteger, - p7: var Size): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "GetTextExtentExPointA".} - #function GetTextExtentExPointI(DC: HDC; p2: PWORD; p3, p4: Integer; p5, p6: PINT; var p7: Size): WINBOOL;stdcall; external 'gdi32' name 'GetTextExtentExPointI'; -proc GetTextExtentExPointW*(DC: HDC, p2: LPWSTR, p3, p4: int, p5, p6: PInteger, - p7: var Size): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "GetTextExtentExPointW".} -proc GetTextExtentPoint*(DC: HDC, Str: cstring, Count: int, Size: var Size): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "GetTextExtentPointA".} -proc GetTextExtentPoint32*(DC: HDC, Str: cstring, Count: int, Size: var Size): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "GetTextExtentPoint32A".} -proc GetTextExtentPoint32A*(DC: HDC, Str: LPCSTR, Count: int, Size: var Size): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "GetTextExtentPoint32A".} -proc GetTextExtentPoint32W*(DC: HDC, Str: LPWSTR, Count: int, Size: var Size): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "GetTextExtentPoint32W".} -proc GetTextExtentPointA*(DC: HDC, Str: LPCSTR, Count: int, Size: var Size): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "GetTextExtentPointA".} - #function GetTextExtentPointI(DC: HDC; p2: PWORD; p3: Integer; var p4: Size): WINBOOL;stdcall; external 'gdi32' name 'GetTextExtentPointI'; -proc GetTextExtentPointW*(DC: HDC, Str: LPWSTR, Count: int, Size: var Size): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "GetTextExtentPointW".} -proc GetTextMetrics*(DC: HDC, TM: var TextMetric): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "GetTextMetricsA".} - #function GetTextMetricsA(DC: HDC; var TM: TextMetricA): WINBOOL; stdcall; external 'gdi32' name 'GetTextMetricsA'; - #function GetTextMetricsW(DC: HDC; var TM: TextMetricW): WINBOOL; stdcall; external 'gdi32' name 'GetTextMetricsW'; -proc GetThreadContext*(hThread: Handle, lpContext: var Context): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetThreadContext".} -proc GetThreadPriorityBoost*(hThread: Handle, DisablePriorityBoost: var WINBOOL): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetThreadPriorityBoost".} -proc GetThreadSelectorEntry*(hThread: Handle, dwSelector: DWORD, - lpSelectorEntry: var LDTEntry): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetThreadSelectorEntry".} -proc GetThreadTimes*(hThread: Handle, lpCreationTime, lpExitTime, lpKernelTime, - lpUserTime: var FileTime): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetThreadTimes".} -proc GetTimeZoneInformation*(lpTimeZoneInformation: var TimeZoneInformation): DWORD{. - stdcall, dynlib: "kernel32", importc: "GetTimeZoneInformation".} - #function GetTitleBarInfo(wnd: HWND; var pti: TTitleBarInfo): WINBOOL;stdcall; external 'user32' name 'GetTitleBarInfo'; - #function GetTokenInformation(TokenHandle: Handle; TokenInformationClass: TokenInformationClass; TokenInformation: pointer; TokenInformationLength: DWORD; var ReturnLength: DWORD): WINBOOL; stdcall; external 'advapi32' name 'GetTokenInformation'; -proc GetUpdateRect*(wnd: HWND, lpRect: var Rect, bErase: WINBOOL): WINBOOL{. - stdcall, dynlib: "user32", importc: "GetUpdateRect".} -proc GetUserName*(lpBuffer: cstring, nSize: var DWORD): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "GetUserNameA".} -proc GetUserNameA*(lpBuffer: LPCSTR, nSize: var DWORD): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "GetUserNameA".} -proc GetUserNameW*(lpBuffer: LPWSTR, nSize: var DWORD): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "GetUserNameW".} -proc GetUserObjectInformation*(hObj: Handle, nIndex: int, pvInfo: pointer, - nLength: DWORD, lpnLengthNeeded: var DWORD): WINBOOL{. - stdcall, dynlib: "user32", importc: "GetUserObjectInformationA".} -proc GetUserObjectInformationA*(hObj: Handle, nIndex: int, pvInfo: pointer, - nLength: DWORD, lpnLengthNeeded: var DWORD): WINBOOL{. - stdcall, dynlib: "user32", importc: "GetUserObjectInformationA".} -proc GetUserObjectInformationW*(hObj: Handle, nIndex: int, pvInfo: pointer, - nLength: DWORD, lpnLengthNeeded: var DWORD): WINBOOL{. - stdcall, dynlib: "user32", importc: "GetUserObjectInformationW".} -proc GetUserObjectSecurity*(hObj: Handle, pSIRequested: var DWORD, - pSID: PSecurityDescriptor, nLength: DWORD, - lpnLengthNeeded: var DWORD): WINBOOL{.stdcall, - dynlib: "user32", importc: "GetUserObjectSecurity".} -proc GetVersionEx*(lpVersionInformation: var OSVersionInfo): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetVersionExA".} -proc GetVersionExA*(lpVersionInformation: var OSVersionInfo): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetVersionExA".} -proc GetVersionExW*(lpVersionInformation: var OSVersionInfoW): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "GetVersionExW".} -proc GetViewportExtEx*(DC: HDC, Size: var Size): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "GetViewportExtEx".} -proc GetViewportOrgEx*(DC: HDC, Point: var Point): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "GetViewportOrgEx".} -proc GetVolumeInformation*(lpRootPathName: cstring, lpVolumeNameBuffer: cstring, - nVolumeNameSize: DWORD, lpVolumeSerialNumber: PDWORD, - lpMaximumComponentLength, lpFileSystemFlags: var DWORD, - lpFileSystemNameBuffer: cstring, - nFileSystemNameSize: DWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetVolumeInformationA".} -proc GetVolumeInformationA*(lpRootPathName: LPCSTR, lpVolumeNameBuffer: LPCSTR, - nVolumeNameSize: DWORD, - lpVolumeSerialNumber: PDWORD, - lpMaximumComponentLength, lpFileSystemFlags: var DWORD, - lpFileSystemNameBuffer: LPCSTR, - nFileSystemNameSize: DWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetVolumeInformationA".} -proc GetVolumeInformationW*(lpRootPathName: LPWSTR, lpVolumeNameBuffer: LPWSTR, - nVolumeNameSize: DWORD, - lpVolumeSerialNumber: PDWORD, - lpMaximumComponentLength, lpFileSystemFlags: var DWORD, - lpFileSystemNameBuffer: LPWSTR, - nFileSystemNameSize: DWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "GetVolumeInformationW".} -proc GetWindowExtEx*(DC: HDC, Size: var Size): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "GetWindowExtEx".} - #function GetWindowInfo(wnd: HWND; var pwi: TWindowInfo): WINBOOL;stdcall; external 'user32' name 'GetWindowInfo'; -proc GetWindowOrgEx*(DC: HDC, Point: var Point): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "GetWindowOrgEx".} -proc GetWindowRect*(wnd: HWND, lpRect: var Rect): WINBOOL{.stdcall, - dynlib: "user32", importc: "GetWindowRect".} -proc GetWorldTransform*(DC: HDC, p2: var XForm): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "GetWorldTransform".} - #function GradientFill(DC: HDC; var p2: TTriVertex; p3: ULONG; p4: pointer; p5, p6: ULONG): WINBOOL;stdcall; external 'gdi32' name 'GradientFill'; -proc GlobalMemoryStatus*(Buffer: var MEMORYSTATUS){.stdcall, dynlib: "kernel32", - importc: "GlobalMemoryStatus".} -proc HeapWalk*(hHeap: Handle, lpEntry: var ProcessHeapEntry): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "HeapWalk".} -proc ImageList_GetDragImage*(ppt: var POINT, pptHotspot: var POINT): HIMAGELIST{. - stdcall, dynlib: "comctl32", importc: "ImageList_GetDragImage".} -proc InflateRect*(lprc: var Rect, dx, dy: int): WINBOOL{.stdcall, - dynlib: "user32", importc: "InflateRect".} -proc InitializeAcl*(pAcl: var ACL, nAclLength, dwAclRevision: DWORD): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "InitializeAcl".} -proc InitializeSid*(Sid: pointer, pIdentifierAuthority: SIDIdentifierAuthority, - nSubAuthorityCount: int8): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "InitializeSid".} -proc InsertMenuItemA*(p1: HMENU, p2: WINUINT, p3: WINBOOL, p4: MenuItemInfo): WINBOOL{. - stdcall, dynlib: "user32", importc: "InsertMenuItemA".} - #function InsertMenuItemW(p1: HMENU; p2: WINUINT; p3: WINBOOL; const p4: MenuItemInfoW): WINBOOL; stdcall; external 'user32' name 'InsertMenuItemW'; -proc IntersectRect*(lprcDst: var Rect, lprcSrc1, lprcSrc2: Rect): WINBOOL{. - stdcall, dynlib: "user32", importc: "IntersectRect".} - #function InvertRect(hDC: HDC; const lprc: Rect): WINBOOL; stdcall; external 'user32' name 'InvertRect'; -proc IsDialogMessage*(hDlg: HWND, lpMsg: var TMsg): WINBOOL{.stdcall, - dynlib: "user32", importc: "IsDialogMessageA".} -proc IsDialogMessageA*(hDlg: HWND, lpMsg: var TMsg): WINBOOL{.stdcall, - dynlib: "user32", importc: "IsDialogMessageA".} -proc IsDialogMessageW*(hDlg: HWND, lpMsg: var TMsg): WINBOOL{.stdcall, - dynlib: "user32", importc: "IsDialogMessageW".} - #function IsRectEmpty(const lprc: Rect): WINBOOL; stdcall; external 'user32' name 'IsRectEmpty'; -proc IsValidAcl*(pAcl: ACL): WINBOOL{.stdcall, dynlib: "advapi32", - importc: "IsValidAcl".} -proc LocalFileTimeToFileTime*(lpLocalFileTime: FileTime, - lpFileTime: var FileTime): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "LocalFileTimeToFileTime".} -proc LockFileEx*(hFile: Handle, dwFlags, dwReserved: DWORD, - nNumberOfBytesToLockLow, nNumberOfBytesToLockHigh: DWORD, - lpOverlapped: Overlapped): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "LockFileEx".} -proc LogonUser*(lpszUsername, lpszDomain, lpszPassword: cstring, - dwLogonType, dwLogonProvider: DWORD, phToken: var Handle): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "LogonUserA".} -proc LogonUserA*(lpszUsername, lpszDomain, lpszPassword: LPCSTR, - dwLogonType, dwLogonProvider: DWORD, phToken: var Handle): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "LogonUserA".} -proc LogonUserW*(lpszUsername, lpszDomain, lpszPassword: LPWSTR, - dwLogonType, dwLogonProvider: DWORD, phToken: var Handle): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "LogonUserW".} -proc LookupAccountName*(lpSystemName, lpAccountName: cstring, Sid: PSID, - cbSid: var DWORD, ReferencedDomainName: cstring, - cbReferencedDomainName: var DWORD, - peUse: var SID_NAME_USE): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "LookupAccountNameA".} -proc LookupAccountNameA*(lpSystemName, lpAccountName: LPCSTR, Sid: PSID, - cbSid: var DWORD, ReferencedDomainName: LPCSTR, - cbReferencedDomainName: var DWORD, - peUse: var SID_NAME_USE): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "LookupAccountNameA".} -proc LookupAccountNameW*(lpSystemName, lpAccountName: LPWSTR, Sid: PSID, - cbSid: var DWORD, ReferencedDomainName: LPWSTR, - cbReferencedDomainName: var DWORD, - peUse: var SID_NAME_USE): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "LookupAccountNameW".} -proc LookupAccountSid*(lpSystemName: cstring, Sid: PSID, Name: cstring, - cbName: var DWORD, ReferencedDomainName: cstring, - cbReferencedDomainName: var DWORD, - peUse: var SID_NAME_USE): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "LookupAccountSidA".} -proc LookupAccountSidA*(lpSystemName: LPCSTR, Sid: PSID, Name: LPCSTR, - cbName: var DWORD, ReferencedDomainName: LPCSTR, - cbReferencedDomainName: var DWORD, - peUse: var SID_NAME_USE): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "LookupAccountSidA".} -proc LookupAccountSidW*(lpSystemName: LPWSTR, Sid: PSID, Name: LPWSTR, - cbName: var DWORD, ReferencedDomainName: LPWSTR, - cbReferencedDomainName: var DWORD, - peUse: var SID_NAME_USE): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "LookupAccountSidW".} -proc LookupPrivilegeDisplayName*(lpSystemName, lpName: LPCSTR, - lpDisplayName: cstring, - cbDisplayName, lpLanguageId: var DWORD): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "LookupPrivilegeDisplayNameA".} -proc LookupPrivilegeDisplayNameA*(lpSystemName, lpName: LPCSTR, - lpDisplayName: LPCSTR, - cbDisplayName, lpLanguageId: var DWORD): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "LookupPrivilegeDisplayNameA".} -proc LookupPrivilegeDisplayNameW*(lpSystemName, lpName: LPCSTR, - lpDisplayName: LPWSTR, - cbDisplayName, lpLanguageId: var DWORD): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "LookupPrivilegeDisplayNameW".} -proc LookupPrivilegeName*(lpSystemName: cstring, lpLuid: var LargeInteger, - lpName: cstring, cbName: var DWORD): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "LookupPrivilegeNameA".} -proc LookupPrivilegeNameA*(lpSystemName: LPCSTR, lpLuid: var LargeInteger, - lpName: LPCSTR, cbName: var DWORD): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "LookupPrivilegeNameA".} -proc LookupPrivilegeNameW*(lpSystemName: LPWSTR, lpLuid: var LargeInteger, - lpName: LPWSTR, cbName: var DWORD): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "LookupPrivilegeNameW".} -proc LookupPrivilegeValue*(lpSystemName, lpName: cstring, - lpLuid: var LargeInteger): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "LookupPrivilegeValueA".} -proc LookupPrivilegeValueA*(lpSystemName, lpName: LPCSTR, - lpLuid: var LargeInteger): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "LookupPrivilegeValueA".} -proc LookupPrivilegeValueW*(lpSystemName, lpName: LPWSTR, - lpLuid: var LargeInteger): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "LookupPrivilegeValueW".} -proc LPtoDP*(DC: HDC, Points: pointer, Count: int): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "LPtoDP".} -proc MakeAbsoluteSD*(pSelfRelativeSecurityDescriptor: PSecurityDescriptor, - pAbsoluteSecurityDescriptor: PSecurityDescriptor, - lpdwAbsoluteSecurityDescriptorSi: var DWORD, - pDacl: var ACL, lpdwDaclSize: var DWORD, pSacl: var ACL, - - lpdwSaclSize: var DWORD, pOwner: PSID, - lpdwOwnerSize: var DWORD, pPrimaryGroup: pointer, - lpdwPrimaryGroupSize: var DWORD): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "MakeAbsoluteSD".} -proc MakeSelfRelativeSD*(pAbsoluteSecurityDescriptor: PSecurityDescriptor, - pSelfRelativeSecurityDescriptor: PSecurityDescriptor, - lpdwBufferLength: var DWORD): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "MakeSelfRelativeSD".} -proc MapDialogRect*(hDlg: HWND, lpRect: var Rect): WINBOOL{.stdcall, - dynlib: "user32", importc: "MapDialogRect".} -proc MapWindowPoints*(hWndFrom, hWndTo: HWND, lpPoints: pointer, cPoints: WINUINT): int{. - stdcall, dynlib: "user32", importc: "MapWindowPoints".} -proc MessageBoxIndirect*(MsgBoxParams: MsgBoxParams): WINBOOL{.stdcall, - dynlib: "user32", importc: "MessageBoxIndirectA".} -proc MessageBoxIndirectA*(MsgBoxParams: MsgBoxParams): WINBOOL{.stdcall, - dynlib: "user32", importc: "MessageBoxIndirectA".} - #function MessageBoxIndirectW(const MsgBoxParams: MsgBoxParamsW): WINBOOL; stdcall; external 'user32' name 'MessageBoxIndirectW'; - #function ModifyWorldTransform(DC: HDC; const p2: XForm; p3: DWORD): WINBOOL; stdcall; external 'gdi32' name 'ModifyWorldTransform'; -proc MsgWaitForMultipleObjects*(nCount: DWORD, pHandles: pointer, - fWaitAll: WINBOOL, - dwMilliseconds, dwWakeMask: DWORD): DWORD{. - stdcall, dynlib: "user32", importc: "MsgWaitForMultipleObjects".} -proc MsgWaitForMultipleObjectsEx*(nCount: DWORD, pHandles: pointer, - dwMilliseconds, dwWakeMask, dwFlags: DWORD): DWORD{. - stdcall, dynlib: "user32", importc: "MsgWaitForMultipleObjectsEx".} - # function MultiByteToWideChar(CodePage: WINUINT; dwFlags: DWORD; const lpMultiByteStr: LPCSTR; cchMultiByte: Integer; lLPWSTRStr: LPWSTR; cchWideChar: Integer): Integer; stdcall; external 'kernel32' name 'MultiByteToWideChar'; -proc ObjectOpenAuditAlarm*(SubsystemName: cstring, HandleId: pointer, - ObjectTypeName: cstring, ObjectName: cstring, - pSecurityDescriptor: PSecurityDescriptor, - ClientToken: Handle, - DesiredAccess, GrantedAccess: DWORD, - Privileges: var PrivilegeSet, - ObjectCreation, AccessGranted: WINBOOL, - GenerateOnClose: var WINBOOL): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "ObjectOpenAuditAlarmA".} -proc ObjectOpenAuditAlarmA*(SubsystemName: LPCSTR, HandleId: pointer, - ObjectTypeName: LPCSTR, ObjectName: LPCSTR, - pSecurityDescriptor: PSecurityDescriptor, - ClientToken: Handle, - DesiredAccess, GrantedAccess: DWORD, - Privileges: var PrivilegeSet, - ObjectCreation, AccessGranted: WINBOOL, - GenerateOnClose: var WINBOOL): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "ObjectOpenAuditAlarmA".} -proc ObjectOpenAuditAlarmW*(SubsystemName: LPWSTR, HandleId: pointer, - ObjectTypeName: LPWSTR, ObjectName: LPWSTR, - pSecurityDescriptor: PSecurityDescriptor, - ClientToken: Handle, - DesiredAccess, GrantedAccess: DWORD, - Privileges: var PrivilegeSet, - ObjectCreation, AccessGranted: WINBOOL, - GenerateOnClose: var WINBOOL): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "ObjectOpenAuditAlarmW".} -proc ObjectPrivilegeAuditAlarm*(SubsystemName: cstring, HandleId: pointer, - ClientToken: Handle, DesiredAccess: DWORD, - Privileges: var PrivilegeSet, - AccessGranted: WINBOOL): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "ObjectPrivilegeAuditAlarmA".} -proc ObjectPrivilegeAuditAlarmA*(SubsystemName: LPCSTR, HandleId: pointer, - ClientToken: Handle, DesiredAccess: DWORD, - Privileges: var PrivilegeSet, - AccessGranted: WINBOOL): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "ObjectPrivilegeAuditAlarmA".} -proc ObjectPrivilegeAuditAlarmW*(SubsystemName: LPWSTR, HandleId: pointer, - ClientToken: Handle, DesiredAccess: DWORD, - Privileges: var PrivilegeSet, - AccessGranted: WINBOOL): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "ObjectPrivilegeAuditAlarmW".} -proc OffsetRect*(lprc: var Rect, dx, dy: int): WINBOOL{.stdcall, - dynlib: "user32", importc: "OffsetRect".} -proc OffsetViewportOrgEx*(DC: HDC, X, Y: int, Points: pointer): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "OffsetViewportOrgEx".} -proc OffsetWindowOrgEx*(DC: HDC, X, Y: int, Points: pointer): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "OffsetWindowOrgEx".} -proc OpenFile*(lpFileName: LPCSTR, lpReOpenBuff: var OFStruct, uStyle: WINUINT): HFILE{. - stdcall, dynlib: "kernel32", importc: "OpenFile".} -proc OpenProcessToken*(ProcessHandle: Handle, DesiredAccess: DWORD, - TokenHandle: var Handle): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "OpenProcessToken".} -proc OpenThreadToken*(ThreadHandle: Handle, DesiredAccess: DWORD, - OpenAsSelf: WINBOOL, TokenHandle: var Handle): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "OpenThreadToken".} -proc PeekConsoleInput*(hConsoleInput: Handle, lpBuffer: var InputRecord, - nLength: DWORD, lpNumberOfEventsRead: var DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "PeekConsoleInputA".} -proc PeekConsoleInputA*(hConsoleInput: Handle, lpBuffer: var InputRecord, - nLength: DWORD, lpNumberOfEventsRead: var DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "PeekConsoleInputA".} -proc PeekConsoleInputW*(hConsoleInput: Handle, lpBuffer: var InputRecord, - nLength: DWORD, lpNumberOfEventsRead: var DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "PeekConsoleInputW".} -proc PeekMessage*(lpMsg: var TMsg, wnd: HWND, - wMsgFilterMin, wMsgFilterMax, wRemoveMsg: WINUINT): WINBOOL{. - stdcall, dynlib: "user32", importc: "PeekMessageA".} -proc PeekMessageA*(lpMsg: var TMsg, wnd: HWND, - wMsgFilterMin, wMsgFilterMax, wRemoveMsg: WINUINT): WINBOOL{. - stdcall, dynlib: "user32", importc: "PeekMessageA".} -proc PeekMessageW*(lpMsg: var TMsg, wnd: HWND, - wMsgFilterMin, wMsgFilterMax, wRemoveMsg: WINUINT): WINBOOL{. - stdcall, dynlib: "user32", importc: "PeekMessageW".} - #function PlayEnhMetaFile(DC: HDC; p2: HENHMETAFILE; const p3: Rect): WINBOOL; stdcall; external 'gdi32' name 'PlayEnhMetaFile'; -proc PlayEnhMetaFileRecord*(DC: HDC, p2: var HandleTable, p3: EnhMetaRecord, - p4: WINUINT): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "PlayEnhMetaFileRecord".} -proc PlayMetaFileRecord*(DC: HDC, p2: HandleTable, p3: MetaRecord, p4: WINUINT): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "PlayMetaFileRecord".} -proc PlgBlt*(DC: HDC, PointsArray: pointer, p3: HDC, p4, p5, p6, p7: int, - p8: HBITMAP, p9, p10: int): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "PlgBlt".} -proc PolyBezier*(DC: HDC, Points: pointer, Count: DWORD): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "PolyBezier".} -proc PolyBezierTo*(DC: HDC, Points: pointer, Count: DWORD): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "PolyBezierTo".} -proc PolyDraw*(DC: HDC, Points, Types: pointer, cCount: int): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "PolyDraw".} -proc Polygon*(DC: HDC, Points: pointer, Count: int): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "Polygon".} -proc Polyline*(DC: HDC, Points: pointer, Count: int): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "Polyline".} -proc PolyLineTo*(DC: HDC, Points: pointer, Count: DWORD): WINBOOL{.stdcall, - dynlib: "gdi32", importc: "PolylineTo".} -proc PolyPolygon*(DC: HDC, Points: pointer, nPoints: pointer, p4: int): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "PolyPolygon".} -proc PolyPolyline*(DC: HDC, PointStructs: pointer, Points: pointer, p4: DWORD): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "PolyPolyline".} -proc PolyTextOut*(DC: HDC, PolyTextArray: pointer, Strings: int): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "PolyTextOutA".} -proc PolyTextOutA*(DC: HDC, PolyTextArray: pointer, Strings: int): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "PolyTextOutA".} -proc PolyTextOutW*(DC: HDC, PolyTextArray: pointer, Strings: int): WINBOOL{. - stdcall, dynlib: "gdi32", importc: "PolyTextOutW".} -proc PrivilegeCheck*(ClientToken: Handle, RequiredPrivileges: PrivilegeSet, - pfResult: var WINBOOL): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "PrivilegeCheck".} -proc PrivilegedServiceAuditAlarm*(SubsystemName, ServiceName: cstring, - ClientToken: Handle, - Privileges: var PrivilegeSet, - AccessGranted: WINBOOL): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "PrivilegedServiceAuditAlarmA".} -proc PrivilegedServiceAuditAlarmA*(SubsystemName, ServiceName: LPCSTR, - ClientToken: Handle, - Privileges: var PrivilegeSet, - AccessGranted: WINBOOL): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "PrivilegedServiceAuditAlarmA".} -proc PrivilegedServiceAuditAlarmW*(SubsystemName, ServiceName: LPWSTR, - ClientToken: Handle, - Privileges: var PrivilegeSet, - AccessGranted: WINBOOL): WINBOOL{.stdcall, - dynlib: "advapi32", importc: "PrivilegedServiceAuditAlarmW".} - #function PtInRect(const lprc: Rect; pt: Point): WINBOOL; stdcall; external 'user32' name 'PtInRect'; -proc QueryPerformanceCounter*(lpPerformanceCount: var LargeInteger): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "QueryPerformanceCounter".} -proc QueryPerformanceFrequency*(lpFrequency: var LargeInteger): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "QueryPerformanceFrequency".} - #function QueryRecoveryAgents(p1: PChar; var p2: pointer; var p3: TRecoveryAgentInformation): DWORD;stdcall; external 'kernel32' name 'QueryRecoveryAgentsA'; - #function QueryRecoveryAgentsA(p1: LPCSTR; var p2: pointer; var p3: TRecoveryAgentInformationA): DWORD;stdcall; external 'kernel32' name 'QueryRecoveryAgentsA'; - #function QueryRecoveryAgentsW(p1: LPWSTR; var p2: pointer; var p3: TRecoveryAgentInformationW): DWORD;stdcall; external 'kernel32' name 'QueryRecoveryAgentsW'; -proc RaiseException*(dwExceptionCode: DWORD, dwExceptionFlags: DWORD, - nNumberOfArguments: DWORD, lpArguments: var DWORD){. - stdcall, dynlib: "kernel32", importc: "RaiseException".} -proc UnhandledExceptionFilter*(ExceptionInfo: var emptyrecord): LONG{.stdcall, - dynlib: "kernel32", importc: "UnhandledExceptionFilter".} -proc ReadConsole*(hConsoleInput: Handle, lpBuffer: pointer, - nNumberOfCharsToRead: DWORD, lpNumberOfCharsRead: var DWORD, - lpReserved: pointer): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "ReadConsoleA".} -proc ReadConsoleA*(hConsoleInput: Handle, lpBuffer: pointer, - nNumberOfCharsToRead: DWORD, lpNumberOfCharsRead: var DWORD, - lpReserved: pointer): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "ReadConsoleA".} -proc ReadConsoleInput*(hConsoleInput: Handle, lpBuffer: var InputRecord, - nLength: DWORD, lpNumberOfEventsRead: var DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "ReadConsoleInputA".} -proc ReadConsoleInputA*(hConsoleInput: Handle, lpBuffer: var InputRecord, - nLength: DWORD, lpNumberOfEventsRead: var DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "ReadConsoleInputA".} -proc ReadConsoleInputW*(hConsoleInput: Handle, lpBuffer: var InputRecord, - nLength: DWORD, lpNumberOfEventsRead: var DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "ReadConsoleInputW".} -proc ReadConsoleOutput*(hConsoleOutput: Handle, lpBuffer: pointer, - dwBufferSize, dwBufferCoord: Coord, - lpReadRegion: var SmallRect): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "ReadConsoleOutputA".} -proc ReadConsoleOutputA*(hConsoleOutput: Handle, lpBuffer: pointer, - dwBufferSize, dwBufferCoord: Coord, - lpReadRegion: var SmallRect): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "ReadConsoleOutputA".} -proc ReadConsoleOutputAttribute*(hConsoleOutput: Handle, lpAttribute: pointer, - nLength: DWORD, dwReadCoord: Coord, - lpNumberOfAttrsRead: var DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "ReadConsoleOutputAttribute".} -proc ReadConsoleOutputCharacter*(hConsoleOutput: Handle, lpCharacter: LPCSTR, - nLength: DWORD, dwReadCoord: Coord, - lpNumberOfCharsRead: var DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "ReadConsoleOutputCharacterA".} -proc ReadConsoleOutputCharacterA*(hConsoleOutput: Handle, lpCharacter: LPCSTR, - nLength: DWORD, dwReadCoord: Coord, - lpNumberOfCharsRead: var DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "ReadConsoleOutputCharacterA".} -proc ReadConsoleOutputCharacterW*(hConsoleOutput: Handle, lpCharacter: LPCSTR, - nLength: DWORD, dwReadCoord: Coord, - lpNumberOfCharsRead: var DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "ReadConsoleOutputCharacterW".} -proc ReadConsoleOutputW*(hConsoleOutput: Handle, lpBuffer: pointer, - dwBufferSize, dwBufferCoord: Coord, - lpReadRegion: var SmallRect): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "ReadConsoleOutputW".} -proc ReadConsoleW*(hConsoleInput: Handle, lpBuffer: pointer, - nNumberOfCharsToRead: DWORD, lpNumberOfCharsRead: var DWORD, - lpReserved: pointer): WINBOOL{.stdcall, dynlib: "kernel32", - importc: "ReadConsoleW".} -proc ReadEventLog*(hEventLog: Handle, dwReadFlags, dwRecordOffset: DWORD, - lpBuffer: pointer, nNumberOfBytesToRead: DWORD, - pnBytesRead, pnMinNumberOfBytesNeeded: var DWORD): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "ReadEventLogA".} -proc ReadEventLogA*(hEventLog: Handle, dwReadFlags, dwRecordOffset: DWORD, - lpBuffer: pointer, nNumberOfBytesToRead: DWORD, - pnBytesRead, pnMinNumberOfBytesNeeded: var DWORD): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "ReadEventLogA".} -proc ReadEventLogW*(hEventLog: Handle, dwReadFlags, dwRecordOffset: DWORD, - lpBuffer: pointer, nNumberOfBytesToRead: DWORD, - pnBytesRead, pnMinNumberOfBytesNeeded: var DWORD): WINBOOL{. - stdcall, dynlib: "advapi32", importc: "ReadEventLogW".} -proc ReadFile*(hFile: Handle, Buffer: pointer, nNumberOfBytesToRead: DWORD, - lpNumberOfBytesRead: var DWORD, lpOverlapped: POverlapped): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "ReadFile".} -proc ReadProcessMemory*(hProcess: Handle, lpBaseAddress: pointer, - lpBuffer: pointer, nSize: DWORD, - lpNumberOfBytesRead: var DWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "ReadProcessMemory".} - #function RectInRegion(RGN: HRGN; const p2: Rect): WINBOOL; stdcall; external 'gdi32' name 'RectInRegion'; - #function RectVisible(DC: HDC; const Rect: Rect): WINBOOL; stdcall; external 'gdi32' name 'RectVisible'; -proc RegConnectRegistry*(lpMachineName: cstring, key: HKEY, phkResult: var HKEY): int32{. - stdcall, dynlib: "advapi32", importc: "RegConnectRegistryA".} -proc RegConnectRegistryA*(lpMachineName: LPCSTR, key: HKEY, phkResult: var HKEY): int32{. - stdcall, dynlib: "advapi32", importc: "RegConnectRegistryA".} -proc RegConnectRegistryW*(lpMachineName: LPWSTR, key: HKEY, phkResult: var HKEY): int32{. - stdcall, dynlib: "advapi32", importc: "RegConnectRegistryW".} -proc RegCreateKey*(key: HKEY, lpSubKey: cstring, phkResult: var HKEY): int32{. - stdcall, dynlib: "advapi32", importc: "RegCreateKeyA".} -proc RegCreateKeyA*(key: HKEY, lpSubKey: LPCSTR, phkResult: var HKEY): int32{. - stdcall, dynlib: "advapi32", importc: "RegCreateKeyA".} -proc RegCreateKeyEx*(key: HKEY, lpSubKey: cstring, Reserved: DWORD, - lpClass: cstring, dwOptions: DWORD, samDesired: REGSAM, - lpSecurityAttributes: PSecurityAttributes, - phkResult: var HKEY, lpdwDisposition: PDWORD): int32{. - stdcall, dynlib: "advapi32", importc: "RegCreateKeyExA".} -proc RegCreateKeyExA*(key: HKEY, lpSubKey: LPCSTR, Reserved: DWORD, - lpClass: LPCSTR, dwOptions: DWORD, samDesired: REGSAM, - lpSecurityAttributes: PSecurityAttributes, - phkResult: var HKEY, lpdwDisposition: PDWORD): int32{. - stdcall, dynlib: "advapi32", importc: "RegCreateKeyExA".} -proc RegCreateKeyExW*(key: HKEY, lpSubKey: LPWSTR, Reserved: DWORD, - lpClass: LPWSTR, dwOptions: DWORD, samDesired: REGSAM, - lpSecurityAttributes: PSecurityAttributes, - phkResult: var HKEY, lpdwDisposition: PDWORD): int32{. - stdcall, dynlib: "advapi32", importc: "RegCreateKeyExW".} -proc RegCreateKeyW*(key: HKEY, lpSubKey: LPWSTR, phkResult: var HKEY): int32{. - stdcall, dynlib: "advapi32", importc: "RegCreateKeyW".} -proc RegEnumKeyEx*(key: HKEY, dwIndex: DWORD, lpName: cstring, - lpcbName: var DWORD, lpReserved: pointer, lpClass: cstring, - lpcbClass: PDWORD, lpftLastWriteTime: PFileTime): int32{. - stdcall, dynlib: "advapi32", importc: "RegEnumKeyExA".} -proc RegEnumKeyExA*(key: HKEY, dwIndex: DWORD, lpName: LPCSTR, - lpcbName: var DWORD, lpReserved: pointer, lpClass: LPCSTR, - lpcbClass: PDWORD, lpftLastWriteTime: PFileTime): int32{. - stdcall, dynlib: "advapi32", importc: "RegEnumKeyExA".} -proc RegEnumKeyExW*(key: HKEY, dwIndex: DWORD, lpName: LPWSTR, - lpcbName: var DWORD, lpReserved: pointer, lpClass: LPWSTR, - lpcbClass: PDWORD, lpftLastWriteTime: PFileTime): int32{. - stdcall, dynlib: "advapi32", importc: "RegEnumKeyExW".} -proc RegEnumValue*(key: HKEY, dwIndex: DWORD, lpValueName: cstring, - lpcbValueName: var DWORD, lpReserved: pointer, - lpType: PDWORD, lpData: PByte, lpcbData: PDWORD): int32{. - stdcall, dynlib: "advapi32", importc: "RegEnumValueA".} -proc RegEnumValueA*(key: HKEY, dwIndex: DWORD, lpValueName: cstring, - lpcbValueName: var DWORD, lpReserved: pointer, - lpType: PDWORD, lpData: PByte, lpcbData: PDWORD): int32{. - stdcall, dynlib: "advapi32", importc: "RegEnumValueA".} -proc RegEnumValueW*(key: HKEY, dwIndex: DWORD, lpValueName: cstring, - lpcbValueName: var DWORD, lpReserved: pointer, - lpType: PDWORD, lpData: PByte, lpcbData: PDWORD): int32{. - stdcall, dynlib: "advapi32", importc: "RegEnumValueW".} -proc RegGetKeySecurity*(key: HKEY, SecurityInformation: SECURITY_INFORMATION, - pSecurityDescriptor: PSecurityDescriptor, - lpcbSecurityDescriptor: var DWORD): int32{.stdcall, - dynlib: "advapi32", importc: "RegGetKeySecurity".} -proc RegSetValueEx*(key: HKEY, lpValueName: LPCSTR, Reserved: DWORD, - dwType: DWORD, lpData: pointer, cbData: DWORD): LONG{. - stdcall, dynlib: "advapi32", importc: "RegSetValueExA".} -proc RegSetValueExA*(key: HKEY, lpValueName: LPCSTR, Reserved: DWORD, - dwType: DWORD, lpData: pointer, cbData: DWORD): LONG{. - stdcall, dynlib: "advapi32", importc: "RegSetValueExA".} -proc RegSetValueExW*(key: HKEY, lpValueName: LPCWSTR, Reserved: DWORD, - dwType: DWORD, lpData: pointer, cbData: DWORD): LONG{. - stdcall, dynlib: "advapi32", importc: "RegSetValueExW".} -proc RegisterClass*(lpWndClass: WndClass): ATOM{.stdcall, dynlib: "user32", - importc: "RegisterClassA".} -proc RegisterClassA*(lpWndClass: WndClass): ATOM{.stdcall, dynlib: "user32", - importc: "RegisterClassA".} -proc RegisterClassEx*(WndClass: WndClassEx): ATOM{.stdcall, dynlib: "user32", - importc: "RegisterClassExA".} -proc RegisterClassExA*(WndClass: WndClassEx): ATOM{.stdcall, dynlib: "user32", - importc: "RegisterClassExA".} -proc RegisterClassExW*(WndClass: WndClassExW): ATOM{.stdcall, dynlib: "user32", - importc: "RegisterClassExW".} -proc RegisterClassW*(lpWndClass: WndClassW): ATOM{.stdcall, dynlib: "user32", - importc: "RegisterClassW".} -proc RegOpenKey*(key: HKEY, lpSubKey: cstring, phkResult: var HKEY): int32{. - stdcall, dynlib: "advapi32", importc: "RegOpenKeyA".} -proc RegOpenKeyA*(key: HKEY, lpSubKey: LPCSTR, phkResult: var HKEY): int32{. - stdcall, dynlib: "advapi32", importc: "RegOpenKeyA".} -proc RegOpenKeyEx*(key: HKEY, lpSubKey: cstring, ulOptions: DWORD, - samDesired: REGSAM, phkResult: var HKEY): int32{.stdcall, - dynlib: "advapi32", importc: "RegOpenKeyExA".} -proc RegOpenKeyExA*(key: HKEY, lpSubKey: LPCSTR, ulOptions: DWORD, - samDesired: REGSAM, phkResult: var HKEY): int32{.stdcall, - dynlib: "advapi32", importc: "RegOpenKeyExA".} -proc RegOpenKeyExW*(key: HKEY, lpSubKey: LPWSTR, ulOptions: DWORD, - samDesired: REGSAM, phkResult: var HKEY): int32{.stdcall, - dynlib: "advapi32", importc: "RegOpenKeyExW".} -proc RegOpenKeyW*(key: HKEY, lpSubKey: LPWSTR, phkResult: var HKEY): int32{. - stdcall, dynlib: "advapi32", importc: "RegOpenKeyW".} -proc RegQueryMultipleValues*(key: HKEY, ValList: pointer, NumVals: DWORD, - lpValueBuf: cstring, ldwTotsize: var DWORD): int32{. - stdcall, dynlib: "advapi32", importc: "RegQueryMultipleValuesA".} -proc RegQueryMultipleValuesA*(key: HKEY, ValList: pointer, NumVals: DWORD, - lpValueBuf: LPCSTR, ldwTotsize: var DWORD): int32{. - stdcall, dynlib: "advapi32", importc: "RegQueryMultipleValuesA".} -proc RegQueryMultipleValuesW*(key: HKEY, ValList: pointer, NumVals: DWORD, - lpValueBuf: LPWSTR, ldwTotsize: var DWORD): int32{. - stdcall, dynlib: "advapi32", importc: "RegQueryMultipleValuesW".} -proc RegQueryValue*(key: HKEY, lpSubKey: cstring, lpValue: cstring, - lpcbValue: var int32): int32{.stdcall, dynlib: "advapi32", - importc: "RegQueryValueA".} -proc RegQueryValueA*(key: HKEY, lpSubKey: LPCSTR, lpValue: LPCSTR, - lpcbValue: var int32): int32{.stdcall, dynlib: "advapi32", - importc: "RegQueryValueA".} -proc RegQueryValueW*(key: HKEY, lpSubKey: LPWSTR, lpValue: LPWSTR, - lpcbValue: var int32): int32{.stdcall, dynlib: "advapi32", - importc: "RegQueryValueW".} -proc ResetDC*(DC: HDC, p2: DevMode): HDC{.stdcall, dynlib: "gdi32", - importc: "ResetDCA".} -proc ResetDCA*(DC: HDC, p2: DevMode): HDC{.stdcall, dynlib: "gdi32", - importc: "ResetDCA".} - #function ResetDCW(DC: HDC; const p2: DevModeW): HDC; stdcall; external 'gdi32' name 'ResetDCW'; -proc ScreenToClient*(wnd: HWND, lpPoint: var Point): WINBOOL{.stdcall, - dynlib: "user32", importc: "ScreenToClient".} -proc ScrollConsoleScreenBuffer*(hConsoleOutput: Handle, - lpScrollRectangle: SmallRect, - lpClipRectangle: SmallRect, - dwDestinationOrigin: Coord, - lpFill: var CharInfo): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "ScrollConsoleScreenBufferA".} -proc ScrollConsoleScreenBufferA*(hConsoleOutput: Handle, - lpScrollRectangle: SmallRect, - lpClipRectangle: SmallRect, - dwDestinationOrigin: Coord, - lpFill: var CharInfo): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "ScrollConsoleScreenBufferA".} -proc ScrollConsoleScreenBufferW*(hConsoleOutput: Handle, - lpScrollRectangle: SmallRect, - lpClipRectangle: SmallRect, - dwDestinationOrigin: Coord, - lpFill: var CharInfo): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "ScrollConsoleScreenBufferW".} -proc ScrollWindow*(wnd: HWND, XAmount: int32, YAmount: int32, rect: LPRECT, - lpClipRect: LPRECT): WINBOOL{.stdcall, dynlib: "user32", - importc: "ScrollWindow".} -proc ScrollWindowEx*(wnd: HWND, dx: int32, dy: int32, prcScroll: LPRECT, - prcClip: LPRECT, hrgnUpdate: HRGN, prcUpdate: LPRECT, - flags: WINUINT): int32{.stdcall, dynlib: "user32", - importc: "ScrollWindowEx".} - #function ScrollDC(DC: HDC; DX, DY: Integer; var Scroll, Clip: Rect; Rgn: HRGN; Update: PRect): WINBOOL; stdcall; external 'user32' name 'ScrollDC'; - #function SearchPath(lpPath, lpFileName, lpExtension: PChar; nBufferLength: DWORD; lpBuffer: PChar; var lpFilePart: PChar): DWORD;stdcall; external 'kernel32' name 'SearchPathA'; - #function SearchPathA(lpPath, lpFileName, lpExtension: LPCSTR; nBufferLength: DWORD; lpBuffer: LPCSTR; var lpFilePart: LPCSTR): DWORD; stdcall; external 'kernel32' name 'SearchPathA'; - #function SearchPathW(lpPath, lpFileName, lpExtension: LPWSTR; nBufferLength: DWORD; lpBuffer: LPWSTR; var lpFilePart: LPWSTR): DWORD; stdcall; external 'kernel32' name 'SearchPathW'; - #function SendInput(cInputs: WINUINT; var pInputs: TInput; cbSize: Integer): WINUINT;stdcall; external 'user32' name 'SendInput'; -proc SendMessageTimeout*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM, - fuFlags, uTimeout: WINUINT, lpdwResult: var DWORD): LRESULT{. - stdcall, dynlib: "user32", importc: "SendMessageTimeoutA".} -proc SendMessageTimeoutA*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM, - fuFlags, uTimeout: WINUINT, lpdwResult: var DWORD): LRESULT{. - stdcall, dynlib: "user32", importc: "SendMessageTimeoutA".} -proc SendMessageTimeoutW*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM, - fuFlags, uTimeout: WINUINT, lpdwResult: var DWORD): LRESULT{. - stdcall, dynlib: "user32", importc: "SendMessageTimeoutW".} - #function SetAclInformation(var pAcl: ACL; pAclInformation: pointer; nAclInformationLength: DWORD; dwAclInformationClass: AclInformationClass): WINBOOL; stdcall; external 'advapi32' name 'SetAclInformation'; - #function SetColorAdjustment(DC: HDC; const p2: ColorAdjustment): WINBOOL; stdcall; external 'gdi32' name 'SetColorAdjustment'; -proc SetCommConfig*(hCommDev: Handle, lpCC: CommConfig, dwSize: DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "SetCommConfig".} -proc SetCommState*(hFile: Handle, lpDCB: DCB): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "SetCommState".} -proc SetCommTimeouts*(hFile: Handle, lpCommTimeouts: CommTimeouts): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "SetCommTimeouts".} -proc SetConsoleCursorInfo*(hConsoleOutput: Handle, - lpConsoleCursorInfo: ConsoleCursorInfo): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "SetConsoleCursorInfo".} - #function SetConsoleWindowInfo(hConsoleOutput: Handle; bAbsolute: WINBOOL; const lpConsoleWindow: SmallRect): WINBOOL; stdcall; external 'kernel32' name 'SetConsoleWindowInfo'; -proc SetDIBColorTable*(DC: HDC, p2, p3: WINUINT, RGBQuadSTructs: pointer): WINUINT{. - stdcall, dynlib: "gdi32", importc: "SetDIBColorTable".} -proc SetDIBits*(DC: HDC, Bitmap: HBITMAP, StartScan, NumScans: WINUINT, - Bits: pointer, BitsInfo: var BitmapInfo, Usage: WINUINT): int{. - stdcall, dynlib: "gdi32", importc: "SetDIBits".} - #function SetDIBitsToDevice(DC: HDC; DestX, DestY: Integer; Width, Height: DWORD; SrcX, SrcY: Integer; nStartScan, NumScans: WINUINT; Bits: pointer; var BitsInfo: BitmapInfo; Usage: WINUINT): Integer; stdcall; external 'gdi32' name 'SetDIBitsToDevice'; -proc SetEnhMetaFileBits*(para1: WINUINT, para2: pointer): HENHMETAFILE{.stdcall, - dynlib: "gdi32", importc: "SetEnhMetaFileBits".} -proc SetFileTime*(hFile: HANDLE, lpCreationTime: var FILETIME, - lpLastAccessTime: var FILETIME, lpLastWriteTime: var FILETIME): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "SetFileTime".} - #function SetKeyboardState(var KeyState: TKeyboardState): WINBOOL; stdcall; external 'user32' name 'SetKeyboardState'; - #function SetLocalTime(const lpSystemTime: SystemTime): WINBOOL; stdcall; external 'kernel32' name 'SetLocalTime'; - #function SetMenuInfo(menu: HMENU; const lpcmi: TMenuInfo): WINBOOL;stdcall; external 'user32' name 'SetMenuInfo'; -proc SetMenuItemInfo*(p1: HMENU, p2: WINUINT, p3: WINBOOL, p4: MenuItemInfo): WINBOOL{. - stdcall, dynlib: "user32", importc: "SetMenuItemInfoA".} -proc SetMenuItemInfoA*(p1: HMENU, p2: WINUINT, p3: WINBOOL, p4: MenuItemInfo): WINBOOL{. - stdcall, dynlib: "user32", importc: "SetMenuItemInfoA".} - #function SetMenuItemInfoW(p1: HMENU; p2: WINUINT; p3: WINBOOL; const p4: MenuItemInfoW): WINBOOL; stdcall; external 'user32' name 'SetMenuItemInfoW'; -proc SetMetaFileBitsEx*(p1: WINUINT, p2: cstring): HMETAFILE{.stdcall, - dynlib: "gdi32", importc: "SetMetaFileBitsEx".} -proc SetNamedPipeHandleState*(hNamedPipe: Handle, lpMode: var DWORD, - lpMaxCollectionCount, lpCollectDataTimeout: pointer): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "SetNamedPipeHandleState".} -proc SetPaletteEntries*(Palette: HPALETTE, StartIndex, NumEntries: WINUINT, - PaletteEntries: pointer): WINUINT{.stdcall, - dynlib: "gdi32", importc: "SetPaletteEntries".} - #function SetPrivateObjectSecurity(SecurityInformation: SECURITY_INFORMATION; ModificationDescriptor: PSecurityDescriptor; var ObjectsSecurityDescriptor: PSecurityDescriptor; const GenericMapping: GenericMapping; Token: Handle): WINBOOL; - # stdcall; external 'advapi32' name 'SetPrivateObjectSecurity'; - #function SetPrivateObjectSecurityEx(SecurityInformation: SECURITY_INFORMATION; ModificationDescriptor: PSecurityDescriptor; var ObjectsSecurityDescriptor: PSecurityDescriptor; AutoInheritFlags: ULONG; - # const GenericMapping: GenericMapping; Token: Handle): WINBOOL;stdcall; external 'advapi32' name 'SetPrivateObjectSecurityEx'; -proc SetRect*(lprc: var Rect, xLeft, yTop, xRight, yBottom: int): WINBOOL{. - stdcall, dynlib: "user32", importc: "SetRect".} -proc SetRectEmpty*(lprc: var Rect): WINBOOL{.stdcall, dynlib: "user32", - importc: "SetRectEmpty".} -proc SetScrollInfo*(wnd: HWND, BarFlag: int, ScrollInfo: ScrollInfo, - Redraw: WINBOOL): int{.stdcall, dynlib: "user32", - importc: "SetScrollInfo".} -proc SetSysColors*(cElements: int, lpaElements: pointer, lpaRgbValues: pointer): WINBOOL{. - stdcall, dynlib: "user32", importc: "SetSysColors".} - #function SetSystemTime(const lpSystemTime: SystemTime): WINBOOL; stdcall; external 'kernel32' name 'SetSystemTime'; -proc SetThreadContext*(hThread: Handle, lpContext: Context): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "SetThreadContext".} - #function SetTimeZoneInformation(const lpTimeZoneInformation: TimeZoneInformation): WINBOOL; stdcall; external 'kernel32' name 'SetTimeZoneInformation'; -proc SetUserObjectSecurity*(hObj: Handle, pSIRequested: var DWORD, - pSID: PSecurityDescriptor): WINBOOL{.stdcall, - dynlib: "user32", importc: "SetUserObjectSecurity".} -proc SetWaitableTimer*(hTimer: Handle, lpDueTime: var LargeInteger, - lPeriod: int32, pfnCompletionRoutine: TFNTimerAPCRoutine, - lpArgToCompletionRoutine: pointer, fResume: WINBOOL): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "SetWaitableTimer".} -proc SetWinMetaFileBits*(p1: WINUINT, p2: cstring, p3: HDC, p4: MetaFilePict): HENHMETAFILE{. - stdcall, dynlib: "gdi32", importc: "SetWinMetaFileBits".} - #function SetWorldTransform(DC: HDC; const p2: XForm): WINBOOL; stdcall; external 'gdi32' name 'SetWorldTransform'; -proc StartDoc*(DC: HDC, p2: DocInfo): int{.stdcall, dynlib: "gdi32", - importc: "StartDocA".} -proc StartDocA*(DC: HDC, p2: DocInfo): int{.stdcall, dynlib: "gdi32", - importc: "StartDocA".} - #function StartDocW(DC: HDC; const p2: DocInfoW): Integer; stdcall; external 'gdi32' name 'StartDocW'; - #function StretchDIBits(DC: HDC; DestX, DestY, DestWidth, DestHegiht, SrcX, SrcY, SrcWidth, SrcHeight: Integer; Bits: pointer; var BitsInfo: BitmapInfo; Usage: WINUINT; Rop: DWORD): Integer; stdcall; external 'gdi32' name 'StretchDIBits'; -proc SubtractRect*(lprcDst: var Rect, lprcSrc1, lprcSrc2: Rect): WINBOOL{. - stdcall, dynlib: "user32", importc: "SubtractRect".} -proc SystemTimeToFileTime*(lpSystemTime: SystemTime, lpFileTime: var FileTime): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "SystemTimeToFileTime".} -proc SystemTimeToTzSpecificLocalTime*(lpTimeZoneInformation: PTimeZoneInformation, - lpUniversalTime, lpLocalTime: var SystemTime): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "SystemTimeToTzSpecificLocalTime".} -proc TabbedTextOut*(hDC: HDC, X, Y: int, lpString: cstring, - nCount, nTabPositions: int, lpnTabStopPositions: pointer, - nTabOrigin: int): int32{.stdcall, dynlib: "user32", - importc: "TabbedTextOutA".} -proc TabbedTextOutA*(hDC: HDC, X, Y: int, lpString: LPCSTR, - nCount, nTabPositions: int, lpnTabStopPositions: pointer, - nTabOrigin: int): int32{.stdcall, dynlib: "user32", - importc: "TabbedTextOutA".} -proc TabbedTextOutW*(hDC: HDC, X, Y: int, lpString: LPWSTR, - nCount, nTabPositions: int, lpnTabStopPositions: pointer, - nTabOrigin: int): int32{.stdcall, dynlib: "user32", - importc: "TabbedTextOutW".} - #function ToAscii(uVirtKey, uScanCode: WINUINT; const KeyState: TKeyboardState; lpChar: PChar; uFlags: WINUINT): Integer; stdcall; external 'user32' name 'ToAscii'; - #function ToAsciiEx(uVirtKey: WINUINT; uScanCode: WINUINT; const KeyState: TKeyboardState; lpChar: PChar; uFlags: WINUINT; dwhkl: HKL): Integer; stdcall; external 'user32' name 'ToAsciiEx'; - #function ToUnicode(wVirtKey, wScanCode: WINUINT; const KeyState: TKeyboardState; var pwszBuff; cchBuff: Integer; wFlags: WINUINT): Integer; stdcall; external 'user32' name 'ToUnicode'; - # Careful, NT and higher only. -proc TrackMouseEvent*(EventTrack: var TTrackMouseEvent): WINBOOL{.stdcall, - dynlib: "user32", importc: "TrackMouseEvent".} -proc TrackMouseEvent*(lpEventTrack: PTrackMouseEvent): WINBOOL{.stdcall, - dynlib: "user32", importc: "TrackMouseEvent".} -proc TrackPopupMenu*(menu: HMENU, uFlags: WINUINT, x: int32, y: int32, - nReserved: int32, wnd: HWND, prcRect: PRect): WINBOOL{. - stdcall, dynlib: "user32", importc: "TrackPopupMenu".} -proc TransactNamedPipe*(hNamedPipe: Handle, lpInBuffer: pointer, - nInBufferSize: DWORD, lpOutBuffer: pointer, - nOutBufferSize: DWORD, lpBytesRead: var DWORD, - lpOverlapped: POverlapped): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "TransactNamedPipe".} -proc TranslateAccelerator*(wnd: HWND, hAccTable: HACCEL, lpMsg: var TMsg): int{. - stdcall, dynlib: "user32", importc: "TranslateAcceleratorA".} -proc TranslateAcceleratorA*(wnd: HWND, hAccTable: HACCEL, lpMsg: var TMsg): int{. - stdcall, dynlib: "user32", importc: "TranslateAcceleratorA".} -proc TranslateAcceleratorW*(wnd: HWND, hAccTable: HACCEL, lpMsg: var TMsg): int{. - stdcall, dynlib: "user32", importc: "TranslateAcceleratorW".} -proc TranslateCharsetInfo*(lpSrc: var DWORD, lpCs: var CharsetInfo, - dwFlags: DWORD): WINBOOL{.stdcall, dynlib: "gdi32", - importc: "TranslateCharsetInfo".} -proc TranslateMDISysAccel*(hWndClient: HWND, lpMsg: TMsg): WINBOOL{.stdcall, - dynlib: "user32", importc: "TranslateMDISysAccel".} -proc TranslateMessage*(lpMsg: TMsg): WINBOOL{.stdcall, dynlib: "user32", - importc: "TranslateMessage".} - #function TransparentDIBits(DC: HDC; p2, p3, p4, p5: Integer; const p6: pointer; const p7: PBitmapInfo; p8: WINUINT; p9, p10, p11, p12: Integer; p13: WINUINT): WINBOOL;stdcall; external 'gdi32' name 'TransparentDIBits'; -proc UnhandledExceptionFilter*(ExceptionInfo: Exceptionpointers): int32{. - stdcall, dynlib: "kernel32", importc: "UnhandledExceptionFilter".} -proc UnionRect*(lprcDst: var Rect, lprcSrc1, lprcSrc2: Rect): WINBOOL{. - stdcall, dynlib: "user32", importc: "UnionRect".} -proc UnlockFileEx*(hFile: Handle, dwReserved, nNumberOfBytesToUnlockLow: DWORD, - nNumberOfBytesToUnlockHigh: DWORD, lpOverlapped: Overlapped): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "UnlockFileEx".} -proc VerFindFile*(uFlags: DWORD, - szFileName, szWinDir, szAppDir, szCurDir: cstring, - lpuCurDirLen: var WINUINT, szDestDir: cstring, - lpuDestDirLen: var WINUINT): DWORD{.stdcall, dynlib: "version", - importc: "VerFindFileA".} -proc VerFindFileA*(uFlags: DWORD, - szFileName, szWinDir, szAppDir, szCurDir: LPCSTR, - lpuCurDirLen: var WINUINT, szDestDir: LPCSTR, - lpuDestDirLen: var WINUINT): DWORD{.stdcall, dynlib: "version", - importc: "VerFindFileA".} -proc VerFindFileW*(uFlags: DWORD, - szFileName, szWinDir, szAppDir, szCurDir: LPWSTR, - lpuCurDirLen: var WINUINT, szDestDir: LPWSTR, - lpuDestDirLen: var WINUINT): DWORD{.stdcall, dynlib: "version", - importc: "VerFindFileW".} -proc VerInstallFile*(uFlags: DWORD, szSrcFileName, szDestFileName, szSrcDir, - szDestDir, szCurDir, szTmpFile: cstring, - lpuTmpFileLen: var WINUINT): DWORD{.stdcall, - dynlib: "version", importc: "VerInstallFileA".} -proc VerInstallFileA*(uFlags: DWORD, szSrcFileName, szDestFileName, szSrcDir, - szDestDir, szCurDir, szTmpFile: LPCSTR, - lpuTmpFileLen: var WINUINT): DWORD{.stdcall, - dynlib: "version", importc: "VerInstallFileA".} -proc VerInstallFileW*(uFlags: DWORD, szSrcFileName, szDestFileName, szSrcDir, - szDestDir, szCurDir, szTmpFile: LPWSTR, - lpuTmpFileLen: var WINUINT): DWORD{.stdcall, - dynlib: "version", importc: "VerInstallFileW".} -proc VerQueryValue*(pBlock: pointer, lpSubBlock: cstring, - lplpBuffer: var pointer, puLen: var WINUINT): WINBOOL{.stdcall, - dynlib: "version", importc: "VerQueryValueA".} -proc VerQueryValueA*(pBlock: pointer, lpSubBlock: LPCSTR, - lplpBuffer: var pointer, puLen: var WINUINT): WINBOOL{. - stdcall, dynlib: "version", importc: "VerQueryValueA".} -proc VerQueryValueW*(pBlock: pointer, lpSubBlock: LPWSTR, - lplpBuffer: var pointer, puLen: var WINUINT): WINBOOL{. - stdcall, dynlib: "version", importc: "VerQueryValueW".} -proc VirtualQuery*(lpAddress: pointer, lpBuffer: var MemoryBasicInformation, - dwLength: DWORD): DWORD{.stdcall, dynlib: "kernel32", - importc: "VirtualQuery".} -proc VirtualQueryEx*(hProcess: Handle, lpAddress: pointer, - lpBuffer: var MemoryBasicInformation, dwLength: DWORD): DWORD{. - stdcall, dynlib: "kernel32", importc: "VirtualQueryEx".} -proc WaitCommEvent*(hFile: Handle, lpEvtMask: var DWORD, - lpOverlapped: POverlapped): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "WaitCommEvent".} -proc WaitForDebugEvent*(lpDebugEvent: var DebugEvent, dwMilliseconds: DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "WaitForDebugEvent".} -proc wglDescribeLayerPlane*(p1: HDC, p2, p3: int, p4: int, - p5: var LayerPlaneDescriptor): WINBOOL{.stdcall, - dynlib: "opengl32", importc: "wglDescribeLayerPlane".} -proc wglGetLayerPaletteEntries*(p1: HDC, p2, p3, p4: int, pcr: pointer): int{. - stdcall, dynlib: "opengl32", importc: "wglGetLayerPaletteEntries".} -proc wglSetLayerPaletteEntries*(p1: HDC, p2, p3, p4: int, pcr: pointer): int{. - stdcall, dynlib: "opengl32", importc: "wglSetLayerPaletteEntries".} - #function wglSwapMultipleBuffers(p1: WINUINT; const p2: PWGLSwap): DWORD;stdcall; external 'opengl32' name 'wglSwapMultipleBuffers'; - #function WinSubmitCertificate(var lpCertificate: TWinCertificate): WINBOOL;stdcall; external 'imaghlp' name 'WinSubmitCertificate'; - #function WinVerifyTrust(wnd: HWND; const ActionID: GUID; ActionData: pointer): Longint;stdcall; external 'imaghlp' name 'WinVerifyTrust'; -proc WNetAddConnection2*(lpNetResource: var NetResource, - lpPassword, lpUserName: cstring, dwFlags: DWORD): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetAddConnection2A".} -proc WNetAddConnection2A*(lpNetResource: var NetResource, - lpPassword, lpUserName: LPCSTR, dwFlags: DWORD): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetAddConnection2A".} - #function WNetAddConnection2W(var lpNetResource: NetResourceW; lpPassword, lpUserName: LPWSTR; dwFlags: DWORD): DWORD; stdcall; external 'mpr' name 'WNetAddConnection2W'; -proc WNetAddConnection3*(hwndOwner: HWND, lpNetResource: var NetResource, - lpPassword, lpUserName: cstring, dwFlags: DWORD): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetAddConnection3A".} -proc WNetAddConnection3A*(hwndOwner: HWND, lpNetResource: var NetResource, - lpPassword, lpUserName: LPCSTR, dwFlags: DWORD): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetAddConnection3A".} - #function WNetAddConnection3W(hwndOwner: HWND; var lpNetResource: NetResourceW; lpPassword, lpUserName: LPWSTR; dwFlags: DWORD): DWORD; stdcall; external 'mpr' name 'WNetAddConnection3W'; -proc WNetConnectionDialog1*(lpConnDlgStruct: var ConnectDlgStruct): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetConnectionDialog1A".} -proc WNetConnectionDialog1A*(lpConnDlgStruct: var ConnectDlgStruct): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetConnectionDialog1A".} - #function WNetConnectionDialog1W(var lpConnDlgStruct: ConnectDlgStruct): DWORD; stdcall; external 'mpr' name 'WNetConnectionDialog1W'; -proc WNetDisconnectDialog1*(lpConnDlgStruct: var DiscDlgStruct): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetDisconnectDialog1A".} -proc WNetDisconnectDialog1A*(lpConnDlgStruct: var DiscDlgStruct): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetDisconnectDialog1A".} - #function WNetDisconnectDialog1W(var lpConnDlgStruct: DiscDlgStructW): DWORD; stdcall; external 'mpr' name 'WNetDisconnectDialog1W'; -proc WNetEnumResource*(hEnum: Handle, lpcCount: var DWORD, lpBuffer: pointer, - lpBufferSize: var DWORD): DWORD{.stdcall, dynlib: "mpr", - importc: "WNetEnumResourceA".} -proc WNetEnumResourceA*(hEnum: Handle, lpcCount: var DWORD, lpBuffer: pointer, - lpBufferSize: var DWORD): DWORD{.stdcall, dynlib: "mpr", - importc: "WNetEnumResourceA".} -proc WNetEnumResourceW*(hEnum: Handle, lpcCount: var DWORD, lpBuffer: pointer, - lpBufferSize: var DWORD): DWORD{.stdcall, dynlib: "mpr", - importc: "WNetEnumResourceW".} -proc WNetGetConnection*(lpLocalName: cstring, lpRemoteName: cstring, - lpnLength: var DWORD): DWORD{.stdcall, dynlib: "mpr", - importc: "WNetGetConnectionA".} -proc WNetGetConnectionA*(lpLocalName: LPCSTR, lpRemoteName: LPCSTR, - lpnLength: var DWORD): DWORD{.stdcall, dynlib: "mpr", - importc: "WNetGetConnectionA".} -proc WNetGetConnectionW*(lpLocalName: LPWSTR, lpRemoteName: LPWSTR, - lpnLength: var DWORD): DWORD{.stdcall, dynlib: "mpr", - importc: "WNetGetConnectionW".} -proc WNetGetLastError*(lpError: var DWORD, lpErrorBuf: cstring, - nErrorBufSize: DWORD, lpNameBuf: cstring, - nNameBufSize: DWORD): DWORD{.stdcall, dynlib: "mpr", - importc: "WNetGetLastErrorA".} -proc WNetGetLastErrorA*(lpError: var DWORD, lpErrorBuf: LPCSTR, - nErrorBufSize: DWORD, lpNameBuf: LPCSTR, - nNameBufSize: DWORD): DWORD{.stdcall, dynlib: "mpr", - importc: "WNetGetLastErrorA".} -proc WNetGetLastErrorW*(lpError: var DWORD, lpErrorBuf: LPWSTR, - nErrorBufSize: DWORD, lpNameBuf: LPWSTR, - nNameBufSize: DWORD): DWORD{.stdcall, dynlib: "mpr", - importc: "WNetGetLastErrorW".} -proc WNetGetNetworkInformation*(lpProvider: cstring, - lpNetInfoStruct: var NetInfoStruct): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetGetNetworkInformationA".} -proc WNetGetNetworkInformationA*(lpProvider: LPCSTR, - lpNetInfoStruct: var NetInfoStruct): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetGetNetworkInformationA".} -proc WNetGetNetworkInformationW*(lpProvider: LPWSTR, - lpNetInfoStruct: var NetInfoStruct): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetGetNetworkInformationW".} -proc WNetGetProviderName*(dwNetType: DWORD, lpProviderName: cstring, - lpBufferSize: var DWORD): DWORD{.stdcall, - dynlib: "mpr", importc: "WNetGetProviderNameA".} -proc WNetGetProviderNameA*(dwNetType: DWORD, lpProviderName: LPCSTR, - lpBufferSize: var DWORD): DWORD{.stdcall, - dynlib: "mpr", importc: "WNetGetProviderNameA".} -proc WNetGetProviderNameW*(dwNetType: DWORD, lpProviderName: LPWSTR, - lpBufferSize: var DWORD): DWORD{.stdcall, - dynlib: "mpr", importc: "WNetGetProviderNameW".} -proc WNetGetResourceParent*(lpNetResource: PNetResource, lpBuffer: pointer, - cbBuffer: var DWORD): DWORD{.stdcall, dynlib: "mpr", - importc: "WNetGetResourceParentA".} -proc WNetGetResourceParentA*(lpNetResource: PNetResourceA, lpBuffer: pointer, - cbBuffer: var DWORD): DWORD{.stdcall, - dynlib: "mpr", importc: "WNetGetResourceParentA".} - #function WNetGetResourceParentW(lpNetResource: PNetResourceW; lpBuffer: pointer; var cbBuffer: DWORD): DWORD;stdcall; external 'mpr' name 'WNetGetResourceParentW'; -proc WNetGetUniversalName*(lpLocalPath: cstring, dwInfoLevel: DWORD, - lpBuffer: pointer, lpBufferSize: var DWORD): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetGetUniversalNameA".} -proc WNetGetUniversalNameA*(lpLocalPath: LPCSTR, dwInfoLevel: DWORD, - lpBuffer: pointer, lpBufferSize: var DWORD): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetGetUniversalNameA".} -proc WNetGetUniversalNameW*(lpLocalPath: LPWSTR, dwInfoLevel: DWORD, - lpBuffer: pointer, lpBufferSize: var DWORD): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetGetUniversalNameW".} -proc WNetGetUser*(lpName: cstring, lpUserName: cstring, lpnLength: var DWORD): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetGetUserA".} -proc WNetGetUserA*(lpName: LPCSTR, lpUserName: LPCSTR, lpnLength: var DWORD): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetGetUserA".} -proc WNetGetUserW*(lpName: LPWSTR, lpUserName: LPWSTR, lpnLength: var DWORD): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetGetUserW".} -proc WNetOpenEnum*(dwScope, dwType, dwUsage: DWORD, lpNetResource: PNetResource, - lphEnum: var Handle): DWORD{.stdcall, dynlib: "mpr", - importc: "WNetOpenEnumA".} -proc WNetOpenEnumA*(dwScope, dwType, dwUsage: DWORD, - lpNetResource: PNetResourceA, lphEnum: var Handle): DWORD{. - stdcall, dynlib: "mpr", importc: "WNetOpenEnumA".} - #function WNetOpenEnumW(dwScope, dwType, dwUsage: DWORD; lpNetResource: PNetResourceW; var lphEnum: Handle): DWORD; stdcall; external 'mpr' name 'WNetOpenEnumW'; -proc WNetUseConnection*(hwndOwner: HWND, lpNetResource: var NetResource, - lpUserID: cstring, lpPassword: cstring, dwFlags: DWORD, - lpAccessName: cstring, lpBufferSize: var DWORD, - lpResult: var DWORD): DWORD{.stdcall, dynlib: "mpr", - importc: "WNetUseConnectionA".} -proc WNetUseConnectionA*(hwndOwner: HWND, lpNetResource: var NetResource, - lpUserID: LPCSTR, lpPassword: LPCSTR, dwFlags: DWORD, - lpAccessName: LPCSTR, lpBufferSize: var DWORD, - lpResult: var DWORD): DWORD{.stdcall, dynlib: "mpr", - importc: "WNetUseConnectionA".} - #function WNetUseConnectionW(hwndOwner: HWND; var lpNetResource: NetResourceW; lpUserID: LPWSTR; lpPassword: LPWSTR; dwFlags: DWORD; lpAccessName: LPWSTR; var lpBufferSize: DWORD; var lpResult: DWORD): DWORD; stdcall; external 'mpr' name 'WNetUseConnectionW'; -proc WriteConsole*(hConsoleOutput: Handle, lpBuffer: pointer, - nNumberOfCharsToWrite: DWORD, - lpNumberOfCharsWritten: var DWORD, lpReserved: pointer): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "WriteConsoleA".} -proc WriteConsoleA*(hConsoleOutput: Handle, lpBuffer: pointer, - nNumberOfCharsToWrite: DWORD, - lpNumberOfCharsWritten: var DWORD, lpReserved: pointer): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "WriteConsoleA".} -proc WriteConsoleInput*(hConsoleInput: Handle, lpBuffer: InputRecord, - nLength: DWORD, lpNumberOfEventsWritten: var DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "WriteConsoleInputA".} -proc WriteConsoleInputA*(hConsoleInput: Handle, lpBuffer: InputRecord, - nLength: DWORD, lpNumberOfEventsWritten: var DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "WriteConsoleInputA".} -proc WriteConsoleInputW*(hConsoleInput: Handle, lpBuffer: InputRecord, - nLength: DWORD, lpNumberOfEventsWritten: var DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "WriteConsoleInputW".} -proc WriteConsoleOutput*(hConsoleOutput: Handle, lpBuffer: pointer, - dwBufferSize, dwBufferCoord: Coord, - lpWriteRegion: var SmallRect): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "WriteConsoleOutputA".} -proc WriteConsoleOutputA*(hConsoleOutput: Handle, lpBuffer: pointer, - dwBufferSize, dwBufferCoord: Coord, - lpWriteRegion: var SmallRect): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "WriteConsoleOutputA".} -proc WriteConsoleOutputAttribute*(hConsoleOutput: Handle, lpAttribute: pointer, - nLength: DWORD, dwWriteCoord: Coord, - lpNumberOfAttrsWritten: var DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "WriteConsoleOutputAttribute".} -proc WriteConsoleOutputCharacter*(hConsoleOutput: Handle, lpCharacter: cstring, - nLength: DWORD, dwWriteCoord: Coord, - lpNumberOfCharsWritten: var DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "WriteConsoleOutputCharacterA".} -proc WriteConsoleOutputCharacterA*(hConsoleOutput: Handle, lpCharacter: LPCSTR, - nLength: DWORD, dwWriteCoord: Coord, - lpNumberOfCharsWritten: var DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "WriteConsoleOutputCharacterA".} -proc WriteConsoleOutputCharacterW*(hConsoleOutput: Handle, lpCharacter: LPWSTR, - nLength: DWORD, dwWriteCoord: Coord, - lpNumberOfCharsWritten: var DWORD): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "WriteConsoleOutputCharacterW".} -proc WriteConsoleOutputW*(hConsoleOutput: Handle, lpBuffer: pointer, - dwBufferSize, dwBufferCoord: Coord, - lpWriteRegion: var SmallRect): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "WriteConsoleOutputW".} -proc WriteConsoleW*(hConsoleOutput: Handle, lpBuffer: pointer, - nNumberOfCharsToWrite: DWORD, - lpNumberOfCharsWritten: var DWORD, lpReserved: pointer): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "WriteConsoleW".} -proc WriteFile*(hFile: Handle, Buffer: pointer, nNumberOfBytesToWrite: DWORD, - lpNumberOfBytesWritten: var DWORD, lpOverlapped: POverlapped): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "WriteFile".} -proc WriteFileEx*(hFile: Handle, lpBuffer: pointer, - nNumberOfBytesToWrite: DWORD, lpOverlapped: Overlapped, - lpCompletionRoutine: FARPROC): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "WriteFileEx".} -proc WritePrivateProfileStructA*(lpszSection, lpszKey: LPCSTR, lpStruct: LPVOID, - uSizeStruct: WINUINT, szFile: LPCSTR): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "WritePrivateProfileStructA".} -proc WritePrivateProfileStructW*(lpszSection, lpszKey: LPCWSTR, - lpStruct: LPVOID, uSizeStruct: WINUINT, - szFile: LPCWSTR): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "WritePrivateProfileStructW".} -proc WritePrivateProfileStruct*(lpszSection, lpszKey: LPCTSTR, lpStruct: LPVOID, - uSizeStruct: WINUINT, szFile: LPCTSTR): WINBOOL{. - stdcall, dynlib: "kernel32", importc: "WritePrivateProfileStructA".} -proc WriteProcessMemory*(hProcess: Handle, lpBaseAddress: pointer, - lpBuffer: pointer, nSize: DWORD, - lpNumberOfBytesWritten: var DWORD): WINBOOL{.stdcall, - dynlib: "kernel32", importc: "WriteProcessMemory".} -proc SHFileOperation*(para1: var SHFILEOPSTRUCT): int32{.stdcall, - dynlib: "shell32", importc: "SHFileOperation".} - - # these are old Win16 funcs that under win32 are aliases for several char* funcs. -# exist under Win32 (even in SDK's from 2002), but are officially "deprecated" -proc AnsiNext*(lpsz: LPCSTR): LPSTR{.stdcall, dynlib: "user32", - importc: "CharNextA".} -proc AnsiPrev*(lpszStart: LPCSTR, lpszCurrent: LPCSTR): LPSTR{.stdcall, - dynlib: "user32", importc: "CharPrevA".} -proc AnsiToOem*(lpszSrc: LPCSTR, lpszDst: LPSTR): WINBOOL{.stdcall, - dynlib: "user32", importc: "CharToOemA".} -proc OemToAnsi*(lpszSrc: LPCSTR, lpszDst: LPSTR): WINBOOL{.stdcall, - dynlib: "user32", importc: "OemToCharA".} -proc AnsiToOemBuff*(lpszSrc: LPCSTR, lpszDst: LPSTR, cchDstLength: DWORD): WINBOOL{. - stdcall, dynlib: "user32", importc: "CharToOemBuffA".} -proc OemToAnsiBuff*(lpszSrc: LPCSTR, lpszDst: LPSTR, cchDstLength: DWORD): WINBOOL{. - stdcall, dynlib: "user32", importc: "OemToCharBuffA".} -proc AnsiUpper*(lpsz: LPSTR): LPSTR{.stdcall, dynlib: "user32", - importc: "CharUpperA".} -proc AnsiUpperBuff*(lpsz: LPSTR, cchLength: DWORD): DWORD{.stdcall, - dynlib: "user32", importc: "CharUpperBuffA".} -proc AnsiLower*(lpsz: LPSTR): LPSTR{.stdcall, dynlib: "user32", - importc: "CharLowerA".} -proc AnsiLowerBuff*(lpsz: LPSTR, cchLength: DWORD): DWORD{.stdcall, - dynlib: "user32", importc: "CharLowerBuffA".} - -#== Implementation of macros - -# WinBase.h - -proc FreeModule*(h: HINST): WINBOOL = - result = FreeLibrary(h) - -proc MakeProcInstance*(p, i: pointer): pointer = - result = p - -proc FreeProcInstance*(p: pointer): pointer = - result = p - -proc GlobalDiscard*(hglbMem: HGLOBAL): HGLOBAL = - result = GlobalReAlloc(hglbMem, 0, GMEM_MOVEABLE) - -proc LocalDiscard*(hlocMem: HLOCAL): HLOCAL = - result = LocalReAlloc(hlocMem, 0, LMEM_MOVEABLE) - -# WinGDI.h - -discard """proc GetGValue*(rgb: int32): int8 = - result = toU8(rgb shr 8'i32)""" -proc RGB*(r, g, b: int): COLORREF = - result = toU32(r) or (toU32(g) shl 8) or (toU32(b) shl 16) -proc RGB*(r, g, b: range[0 .. 255]): COLORREF = - result = toU32(r) or (toU32(g) shl 8) or (toU32(b) shl 16) - -proc PALETTERGB*(r, g, b: range[0..255]): COLORREF = - result = 0x02000000 or RGB(r, g, b) - -proc PALETTEINDEX*(i: DWORD): COLORREF = - result = COLORREF(0x01000000'i32 or i and 0xffff'i32) - - -proc GetRValue*(rgb: COLORREF): int8 = - result = toU8(rgb) - -proc GetGValue*(rgb: COLORREF): int8 = - result = toU8(rgb shr 8) - -proc GetBValue*(rgb: COLORREF): int8 = - result = toU8(rgb shr 16) - -# - -proc HIBYTE*(w: int32): int8 = - result = toU8(w shr 8'i32 and 0x000000FF'i32) - -proc HIWORD*(L: int32): int16 = - result = toU16(L shr 16'i32 and 0x0000FFFF'i32) - -proc LOBYTE*(w: int32): int8 = - result = toU8(w) - -proc LOWORD*(L: int32): int16 = - result = toU16(L) - -proc MAKELONG*(a, b: int32): LONG = - result = a and 0x0000ffff'i32 or b shl 16'i32 - -proc MAKEWORD*(a, b: int32): int16 = - result = toU16(a and 0xff'i32) or toU16(b shl 8'i32) - -proc SEXT_HIWORD*(L: int32): int32 = - # return type might be wrong - result = HIWORD(L) - -proc ZEXT_HIWORD*(L: int32): int32 = - # return type might be wrong - result = HIWORD(L) and 0xffff'i32 - -proc SEXT_LOWORD*(L: int32): int32 = - result = LOWORD(L) - -proc INDEXTOOVERLAYMASK*(i: int32): int32 = - # return type might be wrong - result = i shl 8'i32 - -proc INDEXTOSTATEIMAGEMASK*(i: int32): int32 = - # return type might be wrong - result = i shl 12'i32 - -proc MAKEINTATOM*(i: int32): LPTSTR = - result = cast[LPTSTR](cast[ULONG_PTR](toU16(i))) - -proc MAKELANGID*(p, s: int32): int32 = - # return type might be wrong - result = toU16(s) shl 10'i16 or toU16(p) - -proc PRIMARYLANGID*(lgid: int32): int16 = - result = toU16(lgid) and 0x000003FF'i16 - -proc SUBLANGID*(lgid: int32): int32 = - # return type might be wrong - result = toU16(lgid) shr 10'i16 - -proc MAKELCID*(lgid, srtid: int32): DWORD = - result = toU32(srtid shl 16'i32 or lgid and 0xffff'i32) - -proc MAKELPARAM*(L, h: int32): LPARAM = - result = LPARAM(MAKELONG(L, h)) - -proc MAKELRESULT*(L, h: int32): LRESULT = - result = LRESULT(MAKELONG(L, h)) - -proc MAKEROP4*(fore, back: int32): DWORD = - result = back shl 8'i32 and 0xFF000000'i32 or fore - -proc MAKEWPARAM*(L, h: int32): WPARAM = - result = WPARAM(MAKELONG(L, h)) - -proc GET_X_LPARAM*(lp: windows.LParam): int32 = - result = LOWORD(lp.int32) - -proc GET_Y_LPARAM*(lp: windows.LParam): int32 = - result = HIWORD(lp.int32) - -proc UNICODE_NULL*(): WCHAR = - result = 0'u16 - - - -proc GetFirstChild*(h: HWND): HWND = - result = GetTopWindow(h) - -proc GetNextSibling*(h: HWND): HWND = - result = GetWindow(h, GW_HWNDNEXT) - -proc GetWindowID*(h: HWND): int32 = - result = GetDlgCtrlID(h) - -proc SubclassWindow*(h: HWND, p: LONG): LONG = - result = SetWindowLong(h, GWL_WNDPROC, p) - -proc GET_WM_COMMAND_CMD*(w, L: int32): int32 = - # return type might be wrong - result = HIWORD(w) - -proc GET_WM_COMMAND_ID(w, L: int32): int32 = - # return type might be wrong - result = LOWORD(w) - -proc GET_WM_CTLCOLOR_HDC(w, L, msg: int32): HDC = - result = HDC(w) - -proc GET_WM_CTLCOLOR_HWND(w, L, msg: int32): HWND = - result = HWND(L) - -proc GET_WM_HSCROLL_CODE(w, L: int32): int32 = - # return type might be wrong - result = LOWORD(w) - -proc GET_WM_HSCROLL_HWND(w, L: int32): HWND = - result = HWND(L) - -proc GET_WM_HSCROLL_POS(w, L: int32): int32 = - # return type might be wrong - result = HIWORD(w) - -proc GET_WM_MDIACTIVATE_FACTIVATE(h, a, b: int32): int32 = - # return type might be wrong - result = ord(b == h) - -proc GET_WM_MDIACTIVATE_HWNDACTIVATE(a, b: int32): HWND = - result = HWND(b) - -proc GET_WM_MDIACTIVATE_HWNDDEACT(a, b: int32): HWND = - result = HWND(a) - -proc GET_WM_VSCROLL_CODE(w, L: int32): int32 = - # return type might be wrong - result = LOWORD(w) - -proc GET_WM_VSCROLL_HWND(w, L: int32): HWND = - result = HWND(L) - -proc GET_WM_VSCROLL_POS(w, L: int32): int32 = - # return type might be wrong - result = HIWORD(w) - -proc fBinary(a: var DCB): DWORD = - result = (a.flags and bm_DCB_fBinary) shr bp_DCB_fBinary - -proc set_fBinary(a: var DCB, fBinary: DWORD) = - a.flags = a.flags or ((fBinary shl bp_DCB_fBinary) and bm_DCB_fBinary) - -proc fParity(a: var DCB): DWORD = - result = (a.flags and bm_DCB_fParity) shr bp_DCB_fParity - -proc set_fParity(a: var DCB, fParity: DWORD) = - a.flags = a.flags or ((fParity shl bp_DCB_fParity) and bm_DCB_fParity) - -proc fOutxCtsFlow(a: var DCB): DWORD = - result = (a.flags and bm_DCB_fOutxCtsFlow) shr bp_DCB_fOutxCtsFlow - -proc set_fOutxCtsFlow(a: var DCB, fOutxCtsFlow: DWORD) = - a.flags = a.flags or - ((fOutxCtsFlow shl bp_DCB_fOutxCtsFlow) and bm_DCB_fOutxCtsFlow) - -proc fOutxDsrFlow(a: var DCB): DWORD = - result = (a.flags and bm_DCB_fOutxDsrFlow) shr bp_DCB_fOutxDsrFlow - -proc set_fOutxDsrFlow(a: var DCB, fOutxDsrFlow: DWORD) = - a.flags = a.flags or - ((fOutxDsrFlow shl bp_DCB_fOutxDsrFlow) and bm_DCB_fOutxDsrFlow) - -proc fDtrControl(a: var DCB): DWORD = - result = (a.flags and bm_DCB_fDtrControl) shr bp_DCB_fDtrControl - -proc set_fDtrControl(a: var DCB, fDtrControl: DWORD) = - a.flags = a.flags or - ((fDtrControl shl bp_DCB_fDtrControl) and bm_DCB_fDtrControl) - -proc fDsrSensitivity(a: var DCB): DWORD = - result = (a.flags and bm_DCB_fDsrSensitivity) shr bp_DCB_fDsrSensitivity - -proc set_fDsrSensitivity(a: var DCB, fDsrSensitivity: DWORD) = - a.flags = a.flags or - ((fDsrSensitivity shl bp_DCB_fDsrSensitivity) and - bm_DCB_fDsrSensitivity) - -proc fTXContinueOnXoff(a: var DCB): DWORD = - result = (a.flags and bm_DCB_fTXContinueOnXoff) shr - bp_DCB_fTXContinueOnXoff - -proc set_fTXContinueOnXoff(a: var DCB, fTXContinueOnXoff: DWORD) = - a.flags = a.flags or - ((fTXContinueOnXoff shl bp_DCB_fTXContinueOnXoff) and - bm_DCB_fTXContinueOnXoff) - -proc fOutX(a: var DCB): DWORD = - result = (a.flags and bm_DCB_fOutX) shr bp_DCB_fOutX - -proc set_fOutX(a: var DCB, fOutX: DWORD) = - a.flags = a.flags or ((fOutX shl bp_DCB_fOutX) and bm_DCB_fOutX) - -proc fInX(a: var DCB): DWORD = - result = (a.flags and bm_DCB_fInX) shr bp_DCB_fInX - -proc set_fInX(a: var DCB, fInX: DWORD) = - a.flags = a.flags or ((fInX shl bp_DCB_fInX) and bm_DCB_fInX) - -proc fErrorChar(a: var DCB): DWORD = - result = (a.flags and bm_DCB_fErrorChar) shr bp_DCB_fErrorChar - -proc set_fErrorChar(a: var DCB, fErrorChar: DWORD) = - a.flags = a.flags or - ((fErrorChar shl bp_DCB_fErrorChar) and bm_DCB_fErrorChar) - -proc fNull(a: var DCB): DWORD = - result = (a.flags and bm_DCB_fNull) shr bp_DCB_fNull - -proc set_fNull(a: var DCB, fNull: DWORD) = - a.flags = a.flags or ((fNull shl bp_DCB_fNull) and bm_DCB_fNull) - -proc fRtsControl(a: var DCB): DWORD = - result = (a.flags and bm_DCB_fRtsControl) shr bp_DCB_fRtsControl - -proc set_fRtsControl(a: var DCB, fRtsControl: DWORD) = - a.flags = a.flags or - ((fRtsControl shl bp_DCB_fRtsControl) and bm_DCB_fRtsControl) - -proc fAbortOnError(a: var DCB): DWORD = - result = (a.flags and bm_DCB_fAbortOnError) shr bp_DCB_fAbortOnError - -proc set_fAbortOnError(a: var DCB, fAbortOnError: DWORD) = - a.flags = a.flags or - ((fAbortOnError shl bp_DCB_fAbortOnError) and bm_DCB_fAbortOnError) - -proc fDummy2(a: var DCB): DWORD = - result = (a.flags and bm_DCB_fDummy2) shr bp_DCB_fDummy2 - -proc set_fDummy2(a: var DCB, fDummy2: DWORD) = - a.flags = a.flags or ((fDummy2 shl bp_DCB_fDummy2) and bm_DCB_fDummy2) - -proc fCtsHold(a: var COMSTAT): DWORD = - result = (a.flag0 and bm_COMSTAT_fCtsHold) shr bp_COMSTAT_fCtsHold - -proc set_fCtsHold(a: var COMSTAT, fCtsHold: DWORD) = - a.flag0 = a.flag0 or - ((fCtsHold shl bp_COMSTAT_fCtsHold) and bm_COMSTAT_fCtsHold) - -proc fDsrHold(a: var COMSTAT): DWORD = - result = (a.flag0 and bm_COMSTAT_fDsrHold) shr bp_COMSTAT_fDsrHold - -proc set_fDsrHold(a: var COMSTAT, fDsrHold: DWORD) = - a.flag0 = a.flag0 or - ((fDsrHold shl bp_COMSTAT_fDsrHold) and bm_COMSTAT_fDsrHold) - -proc fRlsdHold(a: var COMSTAT): DWORD = - result = (a.flag0 and bm_COMSTAT_fRlsdHold) shr bp_COMSTAT_fRlsdHold - -proc set_fRlsdHold(a: var COMSTAT, fRlsdHold: DWORD) = - a.flag0 = a.flag0 or - ((fRlsdHold shl bp_COMSTAT_fRlsdHold) and bm_COMSTAT_fRlsdHold) - -proc fXoffHold(a: var COMSTAT): DWORD = - result = (a.flag0 and bm_COMSTAT_fXoffHold) shr bp_COMSTAT_fXoffHold - -proc set_fXoffHold(a: var COMSTAT, fXoffHold: DWORD) = - a.flag0 = a.flag0 or - ((fXoffHold shl bp_COMSTAT_fXoffHold) and bm_COMSTAT_fXoffHold) - -proc fXoffSent(a: var COMSTAT): DWORD = - result = (a.flag0 and bm_COMSTAT_fXoffSent) shr bp_COMSTAT_fXoffSent - -proc set_fXoffSent(a: var COMSTAT, fXoffSent: DWORD) = - a.flag0 = a.flag0 or - ((fXoffSent shl bp_COMSTAT_fXoffSent) and bm_COMSTAT_fXoffSent) - -proc fEof(a: var COMSTAT): DWORD = - result = (a.flag0 and bm_COMSTAT_fEof) shr bp_COMSTAT_fEof - -proc set_fEof(a: var COMSTAT, fEof: DWORD) = - a.flag0 = a.flag0 or ((fEof shl bp_COMSTAT_fEof) and bm_COMSTAT_fEof) - -proc fTxim(a: var COMSTAT): DWORD = - result = (a.flag0 and bm_COMSTAT_fTxim) shr bp_COMSTAT_fTxim - -proc set_fTxim(a: var COMSTAT, fTxim: DWORD) = - a.flag0 = a.flag0 or ((fTxim shl bp_COMSTAT_fTxim) and bm_COMSTAT_fTxim) - -proc fReserved(a: var COMSTAT): DWORD = - result = (a.flag0 and bm_COMSTAT_fReserved) shr bp_COMSTAT_fReserved - -proc set_fReserved(a: var COMSTAT, fReserved: DWORD) = - a.flag0 = a.flag0 or - ((fReserved shl bp_COMSTAT_fReserved) and bm_COMSTAT_fReserved) - -proc bAppReturnCode(a: var DDEACK): int16 = - result = (a.flag0 and bm_DDEACK_bAppReturnCode) shr - bp_DDEACK_bAppReturnCode - -proc set_bAppReturnCode(a: var DDEACK, bAppReturnCode: int16) = - a.flag0 = a.flag0 or - ((bAppReturnCode shl bp_DDEACK_bAppReturnCode) and - bm_DDEACK_bAppReturnCode) - -proc reserved(a: var DDEACK): int16 = - result = (a.flag0 and bm_DDEACK_reserved) shr bp_DDEACK_reserved - -proc set_reserved(a: var DDEACK, reserved: int16) = - a.flag0 = a.flag0 or - ((reserved shl bp_DDEACK_reserved) and bm_DDEACK_reserved) - -proc fBusy(a: var DDEACK): int16 = - result = (a.flag0 and bm_DDEACK_fBusy) shr bp_DDEACK_fBusy - -proc set_fBusy(a: var DDEACK, fBusy: int16) = - a.flag0 = a.flag0 or ((fBusy shl bp_DDEACK_fBusy) and bm_DDEACK_fBusy) - -proc fAck(a: var DDEACK): int16 = - result = (a.flag0 and bm_DDEACK_fAck) shr bp_DDEACK_fAck - -proc set_fAck(a: var DDEACK, fAck: int16) = - a.flag0 = a.flag0 or ((fAck shl bp_DDEACK_fAck) and bm_DDEACK_fAck) - -proc reserved(a: var DDEADVISE): int16 = - result = (a.flag0 and bm_DDEADVISE_reserved) shr bp_DDEADVISE_reserved - -proc set_reserved(a: var DDEADVISE, reserved: int16) = - a.flag0 = a.flag0 or - ((reserved shl bp_DDEADVISE_reserved) and bm_DDEADVISE_reserved) - -proc fDeferUpd(a: var DDEADVISE): int16 = - result = (a.flag0 and bm_DDEADVISE_fDeferUpd) shr bp_DDEADVISE_fDeferUpd - -proc set_fDeferUpd(a: var DDEADVISE, fDeferUpd: int16) = - a.flag0 = a.flag0 or - ((fDeferUpd shl bp_DDEADVISE_fDeferUpd) and bm_DDEADVISE_fDeferUpd) - -proc fAckReq(a: var DDEADVISE): int16 = - result = (a.flag0 and bm_DDEADVISE_fAckReq) shr bp_DDEADVISE_fAckReq - -proc set_fAckReq(a: var DDEADVISE, fAckReq: int16) = - a.flag0 = a.flag0 or - ((fAckReq shl bp_DDEADVISE_fAckReq) and bm_DDEADVISE_fAckReq) - -proc unused(a: var DDEDATA): int16 = - result = (a.flag0 and bm_DDEDATA_unused) shr bp_DDEDATA_unused - -proc set_unused(a: var DDEDATA, unused: int16) = - a.flag0 = a.flag0 or ((unused shl bp_DDEDATA_unused) and bm_DDEDATA_unused) - -proc fResponse(a: var DDEDATA): int16 = - result = (a.flag0 and bm_DDEDATA_fResponse) shr bp_DDEDATA_fResponse - -proc set_fResponse(a: var DDEDATA, fResponse: int16) = - a.flag0 = a.flag0 or - ((fResponse shl bp_DDEDATA_fResponse) and bm_DDEDATA_fResponse) - -proc fRelease(a: var DDEDATA): int16 = - result = (a.flag0 and bm_DDEDATA_fRelease) shr bp_DDEDATA_fRelease - -proc set_fRelease(a: var DDEDATA, fRelease: int16) = - a.flag0 = a.flag0 or - ((fRelease shl bp_DDEDATA_fRelease) and bm_DDEDATA_fRelease) - -proc reserved(a: var DDEDATA): int16 = - result = (a.flag0 and bm_DDEDATA_reserved) shr bp_DDEDATA_reserved - -proc set_reserved(a: var DDEDATA, reserved: int16) = - a.flag0 = a.flag0 or - ((reserved shl bp_DDEDATA_reserved) and bm_DDEDATA_reserved) - -proc fAckReq(a: var DDEDATA): int16 = - result = (a.flag0 and bm_DDEDATA_fAckReq) shr bp_DDEDATA_fAckReq - -proc set_fAckReq(a: var DDEDATA, fAckReq: int16) = - a.flag0 = a.flag0 or - ((fAckReq shl bp_DDEDATA_fAckReq) and bm_DDEDATA_fAckReq) - -proc unused(a: var DDELN): int16 = - result = (a.flag0 and bm_DDELN_unused) shr bp_DDELN_unused - -proc set_unused(a: var DDELN, unused: int16) = - a.flag0 = a.flag0 or ((unused shl bp_DDELN_unused) and bm_DDELN_unused) - -proc fRelease(a: var DDELN): int16 = - result = (a.flag0 and bm_DDELN_fRelease) shr bp_DDELN_fRelease - -proc set_fRelease(a: var DDELN, fRelease: int16) = - a.flag0 = a.flag0 or - ((fRelease shl bp_DDELN_fRelease) and bm_DDELN_fRelease) - -proc fDeferUpd(a: var DDELN): int16 = - result = (a.flag0 and bm_DDELN_fDeferUpd) shr bp_DDELN_fDeferUpd - -proc set_fDeferUpd(a: var DDELN, fDeferUpd: int16) = - a.flag0 = a.flag0 or - ((fDeferUpd shl bp_DDELN_fDeferUpd) and bm_DDELN_fDeferUpd) - -proc fAckReq(a: var DDELN): int16 = - result = (a.flag0 and bm_DDELN_fAckReq) shr bp_DDELN_fAckReq - -proc set_fAckReq(a: var DDELN, fAckReq: int16) = - a.flag0 = a.flag0 or ((fAckReq shl bp_DDELN_fAckReq) and bm_DDELN_fAckReq) - -proc unused(a: var DDEPOKE): int16 = - result = (a.flag0 and bm_DDEPOKE_unused) shr bp_DDEPOKE_unused - -proc set_unused(a: var DDEPOKE, unused: int16) = - a.flag0 = a.flag0 or ((unused shl bp_DDEPOKE_unused) and bm_DDEPOKE_unused) - -proc fRelease(a: var DDEPOKE): int16 = - result = (a.flag0 and bm_DDEPOKE_fRelease) shr bp_DDEPOKE_fRelease - -proc set_fRelease(a: var DDEPOKE, fRelease: int16) = - a.flag0 = a.flag0 or - ((fRelease shl bp_DDEPOKE_fRelease) and bm_DDEPOKE_fRelease) - -proc fReserved(a: var DDEPOKE): int16 = - result = (a.flag0 and bm_DDEPOKE_fReserved) shr bp_DDEPOKE_fReserved - -proc set_fReserved(a: var DDEPOKE, fReserved: int16) = - a.flag0 = a.flag0 or - ((fReserved shl bp_DDEPOKE_fReserved) and bm_DDEPOKE_fReserved) - -proc unused(a: var DDEUP): int16 = - result = (a.flag0 and bm_DDEUP_unused) shr bp_DDEUP_unused - -proc set_unused(a: var DDEUP, unused: int16) = - a.flag0 = a.flag0 or ((unused shl bp_DDEUP_unused) and bm_DDEUP_unused) - -proc fAck(a: var DDEUP): int16 = - result = (a.flag0 and bm_DDEUP_fAck) shr bp_DDEUP_fAck - -proc set_fAck(a: var DDEUP, fAck: int16) = - a.flag0 = a.flag0 or ((fAck shl bp_DDEUP_fAck) and bm_DDEUP_fAck) - -proc fRelease(a: var DDEUP): int16 = - result = (a.flag0 and bm_DDEUP_fRelease) shr bp_DDEUP_fRelease - -proc set_fRelease(a: var DDEUP, fRelease: int16) = - a.flag0 = a.flag0 or - ((fRelease shl bp_DDEUP_fRelease) and bm_DDEUP_fRelease) - -proc fReserved(a: var DDEUP): int16 = - result = (a.flag0 and bm_DDEUP_fReserved) shr bp_DDEUP_fReserved - -proc set_fReserved(a: var DDEUP, fReserved: int16) = - a.flag0 = a.flag0 or - ((fReserved shl bp_DDEUP_fReserved) and bm_DDEUP_fReserved) - -proc fAckReq(a: var DDEUP): int16 = - result = (a.flag0 and bm_DDEUP_fAckReq) shr bp_DDEUP_fAckReq - -proc set_fAckReq(a: var DDEUP, fAckReq: int16) = - a.flag0 = a.flag0 or ((fAckReq shl bp_DDEUP_fAckReq) and bm_DDEUP_fAckReq) - -proc CreateWindowA(lpClassName: LPCSTR, lpWindowName: LPCSTR, dwStyle: DWORD, - X, Y, nWidth, nHeight: int32, - hWndParent: HWND, menu: HMENU, hInstance: HINST, - lpParam: LPVOID): HWND = - result = CreateWindowExA(0, lpClassName, lpWindowName, dwStyle, X, Y, nWidth, - nHeight, hWndParent, menu, hInstance, lpParam) - -proc CreateDialogA(hInstance: HINST, lpTemplateName: LPCSTR, hWndParent: HWND, - lpDialogFunc: DLGPROC): HWND = - result = CreateDialogParamA(hInstance, lpTemplateName, hWndParent, - lpDialogFunc, 0) - -proc CreateDialogIndirectA(hInstance: HINST, lpTemplate: LPCDLGTEMPLATE, - hWndParent: HWND, lpDialogFunc: DLGPROC): HWND = - result = CreateDialogIndirectParamA(hInstance, lpTemplate, hWndParent, - lpDialogFunc, 0) - -proc DialogBoxA(hInstance: HINST, lpTemplateName: LPCSTR, hWndParent: HWND, - lpDialogFunc: DLGPROC): int32 = - result = DialogBoxParamA(hInstance, lpTemplateName, hWndParent, lpDialogFunc, - 0) - -proc DialogBoxIndirectA(hInstance: HINST, hDialogTemplate: LPCDLGTEMPLATE, - hWndParent: HWND, lpDialogFunc: DLGPROC): int32 = - result = DialogBoxIndirectParamA(hInstance, hDialogTemplate, hWndParent, - lpDialogFunc, 0) - -proc CreateWindowW(lpClassName: LPCWSTR, lpWindowName: LPCWSTR, dwStyle: DWORD, - X: int32, Y: int32, nWidth: int32, nHeight: int32, - hWndParent: HWND, menu: HMENU, hInstance: HINST, - lpParam: LPVOID): HWND = - result = CreateWindowExW(0, lpClassName, lpWindowName, dwStyle, X, Y, nWidth, - nHeight, hWndParent, menu, hInstance, lpParam) - -proc CreateDialogW(hInstance: HINST, lpName: LPCWSTR, hWndParent: HWND, - lpDialogFunc: DLGPROC): HWND = - result = CreateDialogParamW(hInstance, lpName, hWndParent, lpDialogFunc, 0) - -proc CreateDialogIndirectW(hInstance: HINST, lpTemplate: LPCDLGTEMPLATE, - hWndParent: HWND, lpDialogFunc: DLGPROC): HWND = - result = CreateDialogIndirectParamW(hInstance, lpTemplate, hWndParent, - lpDialogFunc, 0) - -proc DialogBoxW(hInstance: HINST, lpTemplate: LPCWSTR, hWndParent: HWND, - lpDialogFunc: DLGPROC): int32 = - result = DialogBoxParamW(hInstance, lpTemplate, hWndParent, lpDialogFunc, 0) - -proc DialogBoxIndirectW(hInstance: HINST, lpTemplate: LPCDLGTEMPLATE, - hWndParent: HWND, lpDialogFunc: DLGPROC): int32 = - result = DialogBoxIndirectParamW(hInstance, lpTemplate, hWndParent, - lpDialogFunc, 0) - -when defined(winUnicode): - proc CreateWindow(lpClassName: LPCWSTR, lpWindowName: LPCWSTR, dwStyle: DWORD, - X: int32, Y: int32, nWidth: int32, nHeight: int32, - hWndParent: HWND, menu: HMENU, hInstance: HINST, - lpParam: LPVOID): HWND = - result = CreateWindowEx(0, lpClassName, lpWindowName, dwStyle, X, Y, nWidth, - nHeight, hWndParent, hMenu, hInstance, lpParam) - - proc CreateDialog(hInstance: HINST, lpName: LPCWSTR, hWndParent: HWND, - lpDialogFunc: DLGPROC): HWND = - result = CreateDialogParam(hInstance, lpName, hWndParent, lpDialogFunc, 0) - - proc CreateDialogIndirect(hInstance: HINST, lpTemplate: LPCDLGTEMPLATE, - hWndParent: HWND, lpDialogFunc: DLGPROC): HWND = - result = CreateDialogIndirectParam(hInstance, lpTemplate, hWndParent, - lpDialogFunc, 0) - - proc DialogBox(hInstance: HINST, lpTemplate: LPCWSTR, hWndParent: HWND, - lpDialogFunc: DLGPROC): int32 = - result = DialogBoxParam(hInstance, lpTemplate, hWndParent, lpDialogFunc, 0) - - proc DialogBoxIndirect(hInstance: HINST, lpTemplate: LPCDLGTEMPLATE, - hWndParent: HWND, lpDialogFunc: DLGPROC): int32 = - result = DialogBoxIndirectParam(hInstance, lpTemplate, hWndParent, - lpDialogFunc, 0) - -else: - proc CreateWindow(lpClassName: LPCSTR, lpWindowName: LPCSTR, dwStyle: DWORD, - X: int32, Y: int32, nWidth: int32, nHeight: int32, - hWndParent: HWND, menu: HMENU, hInstance: HINST, - lpParam: LPVOID): HWND = - result = CreateWindowEx(0, lpClassName, lpWindowName, dwStyle, X, Y, nWidth, - nHeight, hWndParent, menu, hInstance, lpParam) - - proc CreateDialog(hInstance: HINST, lpTemplateName: LPCSTR, hWndParent: HWND, - lpDialogFunc: DLGPROC): HWND = - result = CreateDialogParam(hInstance, lpTemplateName, hWndParent, - lpDialogFunc, 0) - - proc CreateDialogIndirect(hInstance: HINST, lpTemplate: LPCDLGTEMPLATE, - hWndParent: HWND, lpDialogFunc: DLGPROC): HWND = - result = CreateDialogIndirectParam(hInstance, lpTemplate, hWndParent, - lpDialogFunc, 0) - - proc DialogBox(hInstance: HINST, lpTemplateName: LPCSTR, hWndParent: HWND, - lpDialogFunc: DLGPROC): int32 = - result = DialogBoxParam(hInstance, lpTemplateName, hWndParent, lpDialogFunc, - 0) - - proc DialogBoxIndirect(hInstance: HINST, hDialogTemplate: LPCDLGTEMPLATE, - hWndParent: HWND, lpDialogFunc: DLGPROC): int32 = - result = DialogBoxIndirectParam(hInstance, hDialogTemplate, hWndParent, - lpDialogFunc, 0) - -proc GlobalAllocPtr(flags, cb: DWord): pointer = - result = GlobalLock(GlobalAlloc(flags, cb)) - -proc GlobalFreePtr(lp: pointer): pointer = - result = cast[pointer](GlobalFree(cast[HWND](GlobalUnlockPtr(lp)))) - -proc GlobalUnlockPtr(lp: pointer): pointer = - discard GlobalUnlock(GlobalHandle(lp)) - result = lp - -proc GlobalLockPtr(lp: pointer): pointer = - result = GlobalLock(GlobalHandle(lp)) - -proc GlobalReAllocPtr(lp: pointer, cbNew, flags: DWord): pointer = - result = GlobalLock(GlobalReAlloc(cast[HWND](GlobalUnlockPtr(lp)), cbNew, flags)) - -proc GlobalPtrHandle(lp: pointer): pointer = - result = cast[pointer](GlobalHandle(lp)) - -proc ImageList_AddIcon(himl: HIMAGELIST, hicon: HICON): int32 = - result = ImageList_ReplaceIcon(himl, -1, hicon) - -proc Animate_Create(hWndP: HWND, id: HMENU, dwStyle: DWORD, hInstance: HINST): HWND = - result = CreateWindow(cast[LPCSTR](ANIMATE_CLASS), nil, dwStyle, 0, 0, 0, 0, hwndP, - id, hInstance, nil) - -proc Animate_Open(wnd: HWND, szName: LPTSTR): LRESULT = - result = SendMessage(wnd, ACM_OPEN, 0, cast[LPARAM](szName)) - -proc Animate_Play(wnd: HWND, `from`, `to`: int32, rep: WINUINT): LRESULT = - result = SendMessage(wnd, ACM_PLAY, WPARAM(rep), - LPARAM(MAKELONG(`from`, `to`))) - -proc Animate_Stop(wnd: HWND): LRESULT = - result = SendMessage(wnd, ACM_STOP, 0, 0) - -proc Animate_Close(wnd: HWND): LRESULT = - result = Animate_Open(wnd, nil) - -proc Animate_Seek(wnd: HWND, frame: int32): LRESULT = - result = Animate_Play(wnd, frame, frame, 1) - -proc PropSheet_AddPage(hPropSheetDlg: HWND, hpage: HPROPSHEETPAGE): LRESULT = - result = SendMessage(hPropSheetDlg, PSM_ADDPAGE, 0, cast[LPARAM](hpage)) - -proc PropSheet_Apply(hPropSheetDlg: HWND): LRESULT = - result = SendMessage(hPropSheetDlg, PSM_APPLY, 0, 0) - -proc PropSheet_CancelToClose(hPropSheetDlg: HWND): LRESULT = - result = SendMessage(hPropSheetDlg, PSM_CANCELTOCLOSE, 0, 0) - -proc PropSheet_Changed(hPropSheetDlg, hwndPage: HWND): LRESULT = - result = SendMessage(hPropSheetDlg, PSM_CHANGED, WPARAM(hwndPage), 0) - -proc PropSheet_GetCurrentPageHwnd(hDlg: HWND): LRESULT = - result = SendMessage(hDlg, PSM_GETCURRENTPAGEHWND, 0, 0) - -proc PropSheet_GetTabControl(hPropSheetDlg: HWND): LRESULT = - result = SendMessage(hPropSheetDlg, PSM_GETTABCONTROL, 0, 0) - -proc PropSheet_IsDialogMessage(hDlg: HWND, pMsg: int32): LRESULT = - result = SendMessage(hDlg, PSM_ISDIALOGMESSAGE, 0, LPARAM(pMsg)) - -proc PropSheet_PressButton(hPropSheetDlg: HWND, iButton: int32): LRESULT = - result = SendMessage(hPropSheetDlg, PSM_PRESSBUTTON, WPARAM(int32(iButton)), 0) - -proc PropSheet_QuerySiblings(hPropSheetDlg: HWND, param1, param2: int32): LRESULT = - result = SendMessage(hPropSheetDlg, PSM_QUERYSIBLINGS, WPARAM(param1), - LPARAM(param2)) - -proc PropSheet_RebootSystem(hPropSheetDlg: HWND): LRESULT = - result = SendMessage(hPropSheetDlg, PSM_REBOOTSYSTEM, 0, 0) - -proc PropSheet_RemovePage(hPropSheetDlg: HWND, hpage: HPROPSHEETPAGE, - index: int32): LRESULT = - result = SendMessage(hPropSheetDlg, PSM_REMOVEPAGE, WPARAM(index), - cast[LPARAM](hpage)) - -proc PropSheet_RestartWindows(hPropSheetDlg: HWND): LRESULT = - result = SendMessage(hPropSheetDlg, PSM_RESTARTWINDOWS, 0, 0) - -proc PropSheet_SetCurSel(hPropSheetDlg: HWND, hpage: HPROPSHEETPAGE, - index: int32): LRESULT = - result = SendMessage(hPropSheetDlg, PSM_SETCURSEL, WPARAM(index), - cast[LPARAM](hpage)) - -proc PropSheet_SetCurSelByID(hPropSheetDlg: HWND, id: int32): LRESULT = - result = SendMessage(hPropSheetDlg, PSM_SETCURSELID, 0, LPARAM(id)) - -proc PropSheet_SetFinishText(hPropSheetDlg: HWND, lpszText: LPTSTR): LRESULT = - result = SendMessage(hPropSheetDlg, PSM_SETFINISHTEXT, 0, cast[LPARAM](lpszText)) - -proc PropSheet_SetTitle(hPropSheetDlg: HWND, dwStyle: DWORD, lpszText: LPCTSTR): LRESULT = - result = SendMessage(hPropSheetDlg, PSM_SETTITLE, WPARAM(dwStyle), - cast[LPARAM](lpszText)) - -proc PropSheet_SetWizButtons(hPropSheetDlg: HWND, dwFlags: DWORD): LRESULT = - result = SendMessage(hPropSheetDlg, PSM_SETWIZBUTTONS, 0, LPARAM(dwFlags)) - -proc PropSheet_UnChanged(hPropSheetDlg: HWND, hwndPage: HWND): LRESULT = - result = SendMessage(hPropSheetDlg, PSM_UNCHANGED, WPARAM(hwndPage), 0) - -proc Header_DeleteItem(hwndHD: HWND, index: int32): WINBOOL = - result = WINBOOL(SendMessage(hwndHD, HDM_DELETEITEM, WPARAM(index), 0)) - -proc Header_GetItem(hwndHD: HWND, index: int32, hdi: var HD_ITEM): WINBOOL = - result = WINBOOL(SendMessage(hwndHD, HDM_GETITEM, WPARAM(index), - cast[LPARAM](addr(hdi)))) - -proc Header_GetItemCount(hwndHD: HWND): int32 = - result = int32(SendMessage(hwndHD, HDM_GETITEMCOUNT, 0, 0)) - -proc Header_InsertItem(hwndHD: HWND, index: int32, hdi: var HD_ITEM): int32 = - result = int32(SendMessage(hwndHD, HDM_INSERTITEM, WPARAM(index), - cast[LPARAM](addr(hdi)))) - -proc Header_Layout(hwndHD: HWND, layout: var HD_LAYOUT): WINBOOL = - result = WINBOOL(SendMessage(hwndHD, HDM_LAYOUT, 0, - cast[LPARAM](addr(layout)))) - -proc Header_SetItem(hwndHD: HWND, index: int32, hdi: var HD_ITEM): WINBOOL = - result = WINBOOL(SendMessage(hwndHD, HDM_SETITEM, WPARAM(index), - cast[LPARAM](addr(hdi)))) - -proc ListView_Arrange(hwndLV: HWND, code: WINUINT): LRESULT = - result = SendMessage(hwndLV, LVM_ARRANGE, WPARAM(code), 0) - -proc ListView_CreateDragImage(wnd: HWND, i: int32, lpptUpLeft: LPPOINT): LRESULT = - result = SendMessage(wnd, LVM_CREATEDRAGIMAGE, WPARAM(i), cast[LPARAM](lpptUpLeft)) - -proc ListView_DeleteAllItems(wnd: HWND): LRESULT = - result = SendMessage(wnd, LVM_DELETEALLITEMS, 0, 0) - -proc ListView_DeleteColumn(wnd: HWND, iCol: int32): LRESULT = - result = SendMessage(wnd, LVM_DELETECOLUMN, WPARAM(iCol), 0) - -proc ListView_DeleteItem(wnd: HWND, iItem: int32): LRESULT = - result = SendMessage(wnd, LVM_DELETEITEM, WPARAM(iItem), 0) - -proc ListView_EditLabel(hwndLV: HWND, i: int32): LRESULT = - result = SendMessage(hwndLV, LVM_EDITLABEL, WPARAM(int32(i)), 0) - -proc ListView_EnsureVisible(hwndLV: HWND, i, fPartialOK: int32): LRESULT = - result = SendMessage(hwndLV, LVM_ENSUREVISIBLE, WPARAM(i), - MAKELPARAM(fPartialOK, 0)) - -proc ListView_FindItem(wnd: HWND, iStart: int32, lvfi: var LV_FINDINFO): int32 = - result = SendMessage(wnd, LVM_FINDITEM, WPARAM(iStart), - cast[LPARAM](addr(lvfi))).int32 - -proc ListView_GetBkColor(wnd: HWND): LRESULT = - result = SendMessage(wnd, LVM_GETBKCOLOR, 0, 0) - -proc ListView_GetCallbackMask(wnd: HWND): LRESULT = - result = SendMessage(wnd, LVM_GETCALLBACKMASK, 0, 0) - -proc ListView_GetColumn(wnd: HWND, iCol: int32, col: var LV_COLUMN): LRESULT = - result = SendMessage(wnd, LVM_GETCOLUMN, WPARAM(iCol), cast[LPARAM](addr(col))) - -proc ListView_GetColumnWidth(wnd: HWND, iCol: int32): LRESULT = - result = SendMessage(wnd, LVM_GETCOLUMNWIDTH, WPARAM(iCol), 0) - -proc ListView_GetCountPerPage(hwndLV: HWND): LRESULT = - result = SendMessage(hwndLV, LVM_GETCOUNTPERPAGE, 0, 0) - -proc ListView_GetEditControl(hwndLV: HWND): LRESULT = - result = SendMessage(hwndLV, LVM_GETEDITCONTROL, 0, 0) - -proc ListView_GetImageList(wnd: HWND, iImageList: WINT): LRESULT = - result = SendMessage(wnd, LVM_GETIMAGELIST, WPARAM(iImageList), 0) - -proc ListView_GetISearchString(hwndLV: HWND, lpsz: LPTSTR): LRESULT = - result = SendMessage(hwndLV, LVM_GETISEARCHSTRING, 0, cast[LPARAM](lpsz)) - -proc ListView_GetItem(wnd: HWND, item: var LV_ITEM): LRESULT = - result = SendMessage(wnd, LVM_GETITEM, 0, cast[LPARAM](addr(item))) - -proc ListView_GetItemCount(wnd: HWND): LRESULT = - result = SendMessage(wnd, LVM_GETITEMCOUNT, 0, 0) - -proc ListView_GetItemPosition(hwndLV: HWND, i: int32, pt: var POINT): int32 = - result = SendMessage(hwndLV, LVM_GETITEMPOSITION, WPARAM(int32(i)), - cast[LPARAM](addr(pt))).int32 - -proc ListView_GetItemSpacing(hwndLV: HWND, fSmall: int32): LRESULT = - result = SendMessage(hwndLV, LVM_GETITEMSPACING, fSmall, 0) - -proc ListView_GetItemState(hwndLV: HWND, i, mask: int32): LRESULT = - result = SendMessage(hwndLV, LVM_GETITEMSTATE, WPARAM(i), LPARAM(mask)) - -proc ListView_GetNextItem(wnd: HWND, iStart, flags: int32): LRESULT = - result = SendMessage(wnd, LVM_GETNEXTITEM, WPARAM(iStart), LPARAM(flags)) - -proc ListView_GetOrigin(hwndLV: HWND, pt: var POINT): LRESULT = - result = SendMessage(hwndLV, LVM_GETORIGIN, WPARAM(0), cast[LPARAM](addr(pt))) - -proc ListView_GetSelectedCount(hwndLV: HWND): LRESULT = - result = SendMessage(hwndLV, LVM_GETSELECTEDCOUNT, 0, 0) - -proc ListView_GetStringWidth(hwndLV: HWND, psz: LPCTSTR): LRESULT = - result = SendMessage(hwndLV, LVM_GETSTRINGWIDTH, 0, cast[LPARAM](psz)) - -proc ListView_GetTextBkColor(wnd: HWND): LRESULT = - result = SendMessage(wnd, LVM_GETTEXTBKCOLOR, 0, 0) - -proc ListView_GetTextColor(wnd: HWND): LRESULT = - result = SendMessage(wnd, LVM_GETTEXTCOLOR, 0, 0) - -proc ListView_GetTopIndex(hwndLV: HWND): LRESULT = - result = SendMessage(hwndLV, LVM_GETTOPINDEX, 0, 0) - -proc ListView_GetViewRect(wnd: HWND, rc: var RECT): LRESULT = - result = SendMessage(wnd, LVM_GETVIEWRECT, 0, cast[LPARAM](addr(rc))) - -proc ListView_HitTest(hwndLV: HWND, info: var LV_HITTESTINFO): LRESULT = - result = SendMessage(hwndLV, LVM_HITTEST, 0, cast[LPARAM](addr(info))) - -proc ListView_InsertColumn(wnd: HWND, iCol: int32, col: var LV_COLUMN): LRESULT = - result = SendMessage(wnd, LVM_INSERTCOLUMN, WPARAM(iCol), cast[LPARAM](addr(col))) - -proc ListView_InsertItem(wnd: HWND, item: var LV_ITEM): LRESULT = - result = SendMessage(wnd, LVM_INSERTITEM, 0, cast[LPARAM](addr(item))) - -proc ListView_RedrawItems(hwndLV: HWND, iFirst, iLast: int32): LRESULT = - result = SendMessage(hwndLV, LVM_REDRAWITEMS, WPARAM(iFirst), LPARAM(iLast)) - -proc ListView_Scroll(hwndLV: HWND, dx, dy: int32): LRESULT = - result = SendMessage(hwndLV, LVM_SCROLL, WPARAM(dx), LPARAM(dy)) - -proc ListView_SetBkColor(wnd: HWND, clrBk: COLORREF): LRESULT = - result = SendMessage(wnd, LVM_SETBKCOLOR, 0, LPARAM(clrBk)) - -proc ListView_SetCallbackMask(wnd: HWND, mask: WINUINT): LRESULT = - result = SendMessage(wnd, LVM_SETCALLBACKMASK, WPARAM(mask), 0) - -proc ListView_SetColumn(wnd: HWND, iCol: int32, col: var LV_COLUMN): LRESULT = - result = SendMessage(wnd, LVM_SETCOLUMN, WPARAM(iCol), cast[LPARAM](addr(col))) - -proc ListView_SetColumnWidth(wnd: HWND, iCol, cx: int32): LRESULT = - result = SendMessage(wnd, LVM_SETCOLUMNWIDTH, WPARAM(iCol), MAKELPARAM(cx, 0)) - -proc ListView_SetImageList(wnd: HWND, himl: int32, iImageList: HIMAGELIST): LRESULT = - result = SendMessage(wnd, LVM_SETIMAGELIST, WPARAM(iImageList), - LPARAM(WINUINT(himl))) - -proc ListView_SetItem(wnd: HWND, item: var LV_ITEM): LRESULT = - result = SendMessage(wnd, LVM_SETITEM, 0, cast[LPARAM](addr(item))) - -proc ListView_SetItemCount(hwndLV: HWND, cItems: int32): LRESULT = - result = SendMessage(hwndLV, LVM_SETITEMCOUNT, WPARAM(cItems), 0) - -proc ListView_SetItemPosition(hwndLV: HWND, i, x, y: int32): LRESULT = - result = SendMessage(hwndLV, LVM_SETITEMPOSITION, WPARAM(i), MAKELPARAM(x, y)) - -proc ListView_SetItemPosition32(hwndLV: HWND, i, x, y: int32): LRESULT = - var ptNewPos: POINT - ptNewPos.x = x - ptNewPos.y = y - result = SendMessage(hwndLV, LVM_SETITEMPOSITION32, WPARAM(i), - cast[LPARAM](addr(ptNewPos))) - -proc ListView_SetItemState(hwndLV: HWND, i, data, mask: int32): LRESULT = - var gnu_lvi: LV_ITEM - gnu_lvi.stateMask = WINUINT(mask) - gnu_lvi.state = WINUINT(data) - result = SendMessage(hwndLV, LVM_SETITEMSTATE, WPARAM(i), - cast[LPARAM](addr(gnu_lvi))) - -proc ListView_SetItemText(hwndLV: HWND, i, iSubItem: int32, pszText: LPTSTR): LRESULT = - var gnu_lvi: LV_ITEM - gnu_lvi.iSubItem = iSubItem - gnu_lvi.pszText = pszText - result = SendMessage(hwndLV, LVM_SETITEMTEXT, WPARAM(i), - cast[LPARAM](addr(gnu_lvi))) - -proc ListView_SetTextBkColor(wnd: HWND, clrTextBk: COLORREF): LRESULT = - result = SendMessage(wnd, LVM_SETTEXTBKCOLOR, 0, LPARAM(clrTextBk)) - -proc ListView_SetTextColor(wnd: HWND, clrText: COLORREF): LRESULT = - result = SendMessage(wnd, LVM_SETTEXTCOLOR, 0, LPARAM(clrText)) - -proc ListView_SortItems(hwndLV: HWND, pfnCompare: PFNLVCOMPARE, - lPrm: LPARAM): LRESULT = - result = SendMessage(hwndLV, LVM_SORTITEMS, WPARAM(lPrm), - cast[LPARAM](pfnCompare)) - -proc ListView_Update(hwndLV: HWND, i: int32): LRESULT = - result = SendMessage(hwndLV, LVM_UPDATE, WPARAM(i), 0) - -proc TreeView_InsertItem(wnd: HWND, lpis: LPTV_INSERTSTRUCT): LRESULT = - result = SendMessage(wnd, TVM_INSERTITEM, 0, cast[LPARAM](lpis)) - -proc TreeView_DeleteItem(wnd: HWND, hitem: HTREEITEM): LRESULT = - result = SendMessage(wnd, TVM_DELETEITEM, 0, cast[LPARAM](hitem)) - -proc TreeView_DeleteAllItems(wnd: HWND): LRESULT = - result = SendMessage(wnd, TVM_DELETEITEM, 0, cast[LPARAM](TVI_ROOT)) - -proc TreeView_Expand(wnd: HWND, hitem: HTREEITEM, code: int32): LRESULT = - result = SendMessage(wnd, TVM_EXPAND, WPARAM(code), cast[LPARAM](hitem)) - -proc TreeView_GetCount(wnd: HWND): LRESULT = - result = SendMessage(wnd, TVM_GETCOUNT, 0, 0) - -proc TreeView_GetIndent(wnd: HWND): LRESULT = - result = SendMessage(wnd, TVM_GETINDENT, 0, 0) - -proc TreeView_SetIndent(wnd: HWND, indent: int32): LRESULT = - result = SendMessage(wnd, TVM_SETINDENT, WPARAM(indent), 0) - -proc TreeView_GetImageList(wnd: HWND, iImage: WPARAM): LRESULT = - result = SendMessage(wnd, TVM_GETIMAGELIST, iImage, 0) - -proc TreeView_SetImageList(wnd: HWND, himl: HIMAGELIST, iImage: WPARAM): LRESULT = - result = SendMessage(wnd, TVM_SETIMAGELIST, iImage, LPARAM(WINUINT(himl))) - -proc TreeView_GetNextItem(wnd: HWND, hitem: HTREEITEM, code: int32): LRESULT = - result = SendMessage(wnd, TVM_GETNEXTITEM, WPARAM(code), cast[LPARAM](hitem)) - -proc TreeView_GetChild(wnd: HWND, hitem: HTREEITEM): LRESULT = - result = TreeView_GetNextItem(wnd, hitem, TVGN_CHILD) - -proc TreeView_GetNextSibling(wnd: HWND, hitem: HTREEITEM): LRESULT = - result = TreeView_GetNextItem(wnd, hitem, TVGN_NEXT) - -proc TreeView_GetPrevSibling(wnd: HWND, hitem: HTREEITEM): LRESULT = - result = TreeView_GetNextItem(wnd, hitem, TVGN_PREVIOUS) - -proc TreeView_GetParent(wnd: HWND, hitem: HTREEITEM): LRESULT = - result = TreeView_GetNextItem(wnd, hitem, TVGN_PARENT) - -proc TreeView_GetFirstVisible(wnd: HWND): LRESULT = - result = TreeView_GetNextItem(wnd, HTREEITEM(nil), TVGN_FIRSTVISIBLE) - -proc TreeView_GetNextVisible(wnd: HWND, hitem: HTREEITEM): LRESULT = - result = TreeView_GetNextItem(wnd, hitem, TVGN_NEXTVISIBLE) - -proc TreeView_GetPrevVisible(wnd: HWND, hitem: HTREEITEM): LRESULT = - result = TreeView_GetNextItem(wnd, hitem, TVGN_PREVIOUSVISIBLE) - -proc TreeView_GetSelection(wnd: HWND): LRESULT = - result = TreeView_GetNextItem(wnd, HTREEITEM(nil), TVGN_CARET) - -proc TreeView_GetDropHilight(wnd: HWND): LRESULT = - result = TreeView_GetNextItem(wnd, HTREEITEM(nil), TVGN_DROPHILITE) - -proc TreeView_GetRoot(wnd: HWND): LRESULT = - result = TreeView_GetNextItem(wnd, HTREEITEM(nil), TVGN_ROOT) - -proc TreeView_Select(wnd: HWND, hitem: HTREEITEM, code: int32): LRESULT = - result = SendMessage(wnd, TVM_SELECTITEM, WPARAM(code), cast[LPARAM](hitem)) - -proc TreeView_SelectItem(wnd: HWND, hitem: HTREEITEM): LRESULT = - result = TreeView_Select(wnd, hitem, TVGN_CARET) - -proc TreeView_SelectDropTarget(wnd: HWND, hitem: HTREEITEM): LRESULT = - result = TreeView_Select(wnd, hitem, TVGN_DROPHILITE) - -proc TreeView_SelectSetFirstVisible(wnd: HWND, hitem: HTREEITEM): LRESULT = - result = TreeView_Select(wnd, hitem, TVGN_FIRSTVISIBLE) - -proc TreeView_GetItem(wnd: HWND, item: var TV_ITEM): LRESULT = - result = SendMessage(wnd, TVM_GETITEM, 0, cast[LPARAM](addr(item))) - -proc TreeView_SetItem(wnd: HWND, item: var TV_ITEM): LRESULT = - result = SendMessage(wnd, TVM_SETITEM, 0, cast[LPARAM](addr(item))) - -proc TreeView_EditLabel(wnd: HWND, hitem: HTREEITEM): LRESULT = - result = SendMessage(wnd, TVM_EDITLABEL, 0, cast[LPARAM](hitem)) - -proc TreeView_GetEditControl(wnd: HWND): LRESULT = - result = SendMessage(wnd, TVM_GETEDITCONTROL, 0, 0) - -proc TreeView_GetVisibleCount(wnd: HWND): LRESULT = - result = SendMessage(wnd, TVM_GETVISIBLECOUNT, 0, 0) - -proc TreeView_HitTest(wnd: HWND, lpht: LPTV_HITTESTINFO): LRESULT = - result = SendMessage(wnd, TVM_HITTEST, 0, cast[LPARAM](lpht)) - -proc TreeView_CreateDragImage(wnd: HWND, hitem: HTREEITEM): LRESULT = - result = SendMessage(wnd, TVM_CREATEDRAGIMAGE, 0, cast[LPARAM](hitem)) - -proc TreeView_SortChildren(wnd: HWND, hitem: HTREEITEM, recurse: int32): LRESULT = - result = SendMessage(wnd, TVM_SORTCHILDREN, WPARAM(recurse), cast[LPARAM](hitem)) - -proc TreeView_EnsureVisible(wnd: HWND, hitem: HTREEITEM): LRESULT = - result = SendMessage(wnd, TVM_ENSUREVISIBLE, 0, cast[LPARAM](hitem)) - -proc TreeView_SortChildrenCB(wnd: HWND, psort: LPTV_SORTCB, recurse: int32): LRESULT = - result = SendMessage(wnd, TVM_SORTCHILDRENCB, WPARAM(recurse), cast[LPARAM](psort)) - -proc TreeView_EndEditLabelNow(wnd: HWND, fCancel: int32): LRESULT = - result = SendMessage(wnd, TVM_ENDEDITLABELNOW, WPARAM(fCancel), 0) - -proc TreeView_GetISearchString(hwndTV: HWND, lpsz: LPTSTR): LRESULT = - result = SendMessage(hwndTV, TVM_GETISEARCHSTRING, 0, cast[LPARAM](lpsz)) - -proc TabCtrl_GetImageList(wnd: HWND): LRESULT = - result = SendMessage(wnd, TCM_GETIMAGELIST, 0, 0) - -proc TabCtrl_SetImageList(wnd: HWND, himl: HIMAGELIST): LRESULT = - result = SendMessage(wnd, TCM_SETIMAGELIST, 0, LPARAM(WINUINT(himl))) - -proc TabCtrl_GetItemCount(wnd: HWND): LRESULT = - result = SendMessage(wnd, TCM_GETITEMCOUNT, 0, 0) - -proc TabCtrl_GetItem(wnd: HWND, iItem: int32, item: var TC_ITEM): LRESULT = - result = SendMessage(wnd, TCM_GETITEM, WPARAM(iItem), cast[LPARAM](addr(item))) - -proc TabCtrl_SetItem(wnd: HWND, iItem: int32, item: var TC_ITEM): LRESULT = - result = SendMessage(wnd, TCM_SETITEM, WPARAM(iItem), cast[LPARAM](addr(item))) - -proc TabCtrl_InsertItem(wnd: HWND, iItem: int32, item: var TC_ITEM): LRESULT = - result = SendMessage(wnd, TCM_INSERTITEM, WPARAM(iItem), cast[LPARAM](addr(item))) - -proc TabCtrl_DeleteItem(wnd: HWND, i: int32): LRESULT = - result = SendMessage(wnd, TCM_DELETEITEM, WPARAM(i), 0) - -proc TabCtrl_DeleteAllItems(wnd: HWND): LRESULT = - result = SendMessage(wnd, TCM_DELETEALLITEMS, 0, 0) - -proc TabCtrl_GetItemRect(wnd: HWND, i: int32, rc: var RECT): LRESULT = - result = SendMessage(wnd, TCM_GETITEMRECT, WPARAM(int32(i)), cast[LPARAM](addr(rc))) - -proc TabCtrl_GetCurSel(wnd: HWND): LRESULT = - result = SendMessage(wnd, TCM_GETCURSEL, 0, 0) - -proc TabCtrl_SetCurSel(wnd: HWND, i: int32): LRESULT = - result = SendMessage(wnd, TCM_SETCURSEL, WPARAM(i), 0) - -proc TabCtrl_HitTest(hwndTC: HWND, info: var TC_HITTESTINFO): LRESULT = - result = SendMessage(hwndTC, TCM_HITTEST, 0, cast[LPARAM](addr(info))) - -proc TabCtrl_SetItemExtra(hwndTC: HWND, cb: int32): LRESULT = - result = SendMessage(hwndTC, TCM_SETITEMEXTRA, WPARAM(cb), 0) - -proc TabCtrl_AdjustRect(wnd: HWND, bLarger: WINBOOL, rc: var RECT): LRESULT = - result = SendMessage(wnd, TCM_ADJUSTRECT, WPARAM(bLarger), cast[LPARAM](addr(rc))) - -proc TabCtrl_SetItemSize(wnd: HWND, x, y: int32): LRESULT = - result = SendMessage(wnd, TCM_SETITEMSIZE, 0, MAKELPARAM(x, y)) - -proc TabCtrl_RemoveImage(wnd: HWND, i: WPARAM): LRESULT = - result = SendMessage(wnd, TCM_REMOVEIMAGE, i, 0) - -proc TabCtrl_SetPadding(wnd: HWND, cx, cy: int32): LRESULT = - result = SendMessage(wnd, TCM_SETPADDING, 0, MAKELPARAM(cx, cy)) - -proc TabCtrl_GetRowCount(wnd: HWND): LRESULT = - result = SendMessage(wnd, TCM_GETROWCOUNT, 0, 0) - -proc TabCtrl_GetToolTips(wnd: HWND): LRESULT = - result = SendMessage(wnd, TCM_GETTOOLTIPS, 0, 0) - -proc TabCtrl_SetToolTips(wnd: HWND, hwndTT: int32): LRESULT = - result = SendMessage(wnd, TCM_SETTOOLTIPS, WPARAM(hwndTT), 0) - -proc TabCtrl_GetCurFocus(wnd: HWND): LRESULT = - result = SendMessage(wnd, TCM_GETCURFOCUS, 0, 0) - -proc TabCtrl_SetCurFocus(wnd: HWND, i: int32): LRESULT = - result = SendMessage(wnd, TCM_SETCURFOCUS, i, 0) - -proc SNDMSG(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): LRESULT = - result = SendMessage(wnd, Msg, wp, lp) - -proc CommDlg_OpenSave_GetSpecA(hdlg: HWND, psz: LPSTR, cbmax: int32): LRESULT = - result = SNDMSG(hdlg, CDM_GETSPEC, WPARAM(cbmax), cast[LPARAM](psz)) - -proc CommDlg_OpenSave_GetSpecW(hdlg: HWND, psz: LPWSTR, cbmax: int32): LRESULT = - result = SNDMSG(hdlg, CDM_GETSPEC, WPARAM(cbmax), cast[LPARAM](psz)) - -when defined(winUnicode): - proc CommDlg_OpenSave_GetSpec(hdlg: HWND, psz: LPWSTR, cbmax: int32): LRESULT = - result = SNDMSG(hdlg, CDM_GETSPEC, WPARAM(cbmax), cast[LPARAM](psz)) -else: - proc CommDlg_OpenSave_GetSpec(hdlg: HWND, psz: LPSTR, cbmax: int32): LRESULT = - result = SNDMSG(hdlg, CDM_GETSPEC, WPARAM(cbmax), cast[LPARAM](psz)) - -proc CommDlg_OpenSave_GetFilePathA(hdlg: HWND, psz: LPSTR, cbmax: int32): LRESULT = - result = SNDMSG(hdlg, CDM_GETFILEPATH, WPARAM(cbmax), cast[LPARAM](psz)) - -proc CommDlg_OpenSave_GetFilePathW(hdlg: HWND, psz: LPWSTR, cbmax: int32): LRESULT = - result = SNDMSG(hdlg, CDM_GETFILEPATH, WPARAM(cbmax), cast[LPARAM](psz)) - -when defined(winUnicode): - proc CommDlg_OpenSave_GetFilePath(hdlg: HWND, psz: LPWSTR, cbmax: int32): LRESULT = - result = SNDMSG(hdlg, CDM_GETFILEPATH, WPARAM(cbmax), cast[LPARAM](psz)) -else: - proc CommDlg_OpenSave_GetFilePath(hdlg: HWND, psz: LPSTR, cbmax: int32): LRESULT = - result = SNDMSG(hdlg, CDM_GETFILEPATH, WPARAM(cbmax), cast[LPARAM](psz)) - -proc CommDlg_OpenSave_GetFolderPathA(hdlg: HWND, psz: LPSTR, cbmax: int32): LRESULT = - result = SNDMSG(hdlg, CDM_GETFOLDERPATH, WPARAM(cbmax), cast[LPARAM](psz)) - -proc CommDlg_OpenSave_GetFolderPathW(hdlg: HWND, psz: LPWSTR, cbmax: int32): LRESULT = - result = SNDMSG(hdlg, CDM_GETFOLDERPATH, WPARAM(cbmax), cast[LPARAM](psz)) - -when defined(winUnicode): - proc CommDlg_OpenSave_GetFolderPath(hdlg: HWND, psz: LPWSTR, cbmax: int32): LRESULT = - result = SNDMSG(hdlg, CDM_GETFOLDERPATH, WPARAM(cbmax), cast[LPARAM]((psz))) -else: - proc CommDlg_OpenSave_GetFolderPath(hdlg: HWND, psz: LPSTR, cbmax: int32): LRESULT = - result = SNDMSG(hdlg, CDM_GETFOLDERPATH, WPARAM(cbmax), cast[LPARAM](psz)) - -proc CommDlg_OpenSave_GetFolderIDList(hdlg: HWND, pidl: LPVOID, cbmax: int32): LRESULT = - result = SNDMSG(hdlg, CDM_GETFOLDERIDLIST, WPARAM(cbmax), cast[LPARAM](pidl)) - -proc CommDlg_OpenSave_SetControlText(hdlg: HWND, id: int32, text: LPSTR): LRESULT = - result = SNDMSG(hdlg, CDM_SETCONTROLTEXT, WPARAM(id), cast[LPARAM](text)) - -proc CommDlg_OpenSave_HideControl(hdlg: HWND, id: int32): LRESULT = - result = SNDMSG(hdlg, CDM_HIDECONTROL, WPARAM(id), 0) - -proc CommDlg_OpenSave_SetDefExt(hdlg: HWND, pszext: LPSTR): LRESULT = - result = SNDMSG(hdlg, CDM_SETDEFEXT, 0, cast[LPARAM](pszext)) - -proc InternalGetLargestConsoleWindowSize(hConsoleOutput: HANDLE): DWord{. - stdcall, dynlib: "kernel32", importc: "GetLargestConsoleWindowSize".} -proc GetLargestConsoleWindowSize(hConsoleOutput: HANDLE): COORD = - var res: DWORD - res = InternalGetLargestConsoleWindowSize(hConsoleOutput) - result.Y = toU16(res and 0x0000ffff) # XXX: correct? - result.X = toU16(res shr 16) - -proc Succeeded(Status: HRESULT): WINBOOL = - result = (Status and 0x80000000).WinBool - -proc Failed(Status: HRESULT): WINBOOL = - result = (Status and 0x80000000).WinBool - -proc IsError(Status: HRESULT): WINBOOL = - result = ord((int(Status) shr 31) == SEVERITY_ERROR) - -proc HResultCode(hr: HRESULT): int32 = - result = hr and 0x0000FFFF'i32 - -proc HResultFacility(hr: HRESULT): int32 = - result = (hr shr 16'i32) and 0x00001FFF'i32 - -proc HResultSeverity(hr: HRESULT): int32 = - result = (hr shr 31'i32) and 0x00000001'i32 - -proc MakeResult(p1, p2, mask: int32): HRESULT = - result = (p1 shl 31'i32) or (p2 shl 16'i32) or mask - -proc HResultFromWin32(x: int32): HRESULT = - result = x - if result != 0'i32: - result = ((result and 0x0000FFFF'i32) or (int32(FACILITY_WIN32) shl 16'i32) or - 0x80000000'i32) - -proc HResultFromNT(x: int32): HRESULT = - result = x or int32(FACILITY_NT_BIT) - -proc MAKELANGID(PrimaryLang, SubLang: USHORT): int16 = - result = (SubLang shl 10'i16) or PrimaryLang - -proc PRIMARYLANGID(LangId: int16): int16 = - result = LangId and 0x000003FF'i16 - -proc SUBLANGID(LangId: int16): int16 = - result = LangId shr 10'i16 - -proc MAKELCID(LangId, SortId: int16): DWORD = - result = toU32((ze(SortId) shl 16) or ze(LangId)) - -proc MAKESORTLCID(LangId, SortId, SortVersion: int16): DWORD = - result = MAKELCID(LangId, SortId) or (SortVersion shl 20'i32) - -proc LANGIDFROMLCID(LocaleId: LCID): int16 = - result = toU16(LocaleId) - -proc SORTIDFROMLCID(LocaleId: LCID): int16 = - result = toU16((DWORD(LocaleId) shr 16) and 0x0000000F) - -proc SORTVERSIONFROMLCID(LocaleId: LCID): int16 = - result = toU16((DWORD(LocaleId) shr 20) and 0x0000000F) - -proc LANG_SYSTEM_DEFAULT(): int16 = - result = toU16(MAKELANGID(toU16(LANG_NEUTRAL), SUBLANG_SYS_DEFAULT)) - -proc LANG_USER_DEFAULT(): int16 = - result = toU16(MAKELANGID(toU16(LANG_NEUTRAL), SUBLANG_DEFAULT)) - -proc LOCALE_NEUTRAL(): DWORD = - result = MAKELCID(MAKELANGID(toU16(LANG_NEUTRAL), SUBLANG_NEUTRAL), SORT_DEFAULT) - -proc LOCALE_INVARIANT(): DWORD = - result = MAKELCID(MAKELANGID(toU16(LANG_INVARIANT), SUBLANG_NEUTRAL), SORT_DEFAULT) - -{.pop.} diff --git a/lib/wrappers/claro.nim b/lib/wrappers/claro.nim deleted file mode 100644 index 41956c28a..000000000 --- a/lib/wrappers/claro.nim +++ /dev/null @@ -1,2748 +0,0 @@ -# Claro Graphics - an abstraction layer for native UI libraries -# -# $Id$ -# -# The contents of this file are subject to the Mozilla Public License -# Version 1.1 (the "License"); you may not use this file except in -# compliance with the License. You may obtain a copy of the License at -# http://www.mozilla.org/MPL/ -# -# Software distributed under the License is distributed on an "AS IS" -# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the -# License for the specific language governing rights and limitations -# under the License. -# -# See the LICENSE file for more details. -# - -## Wrapper for the Claro GUI library. -## This wrapper calls ``claro_base_init`` and ``claro_graphics_init`` -## automatically on startup, so you don't have to do it and in fact cannot do -## it because they are not exported. - -{.deadCodeElim: on.} - -when defined(windows): - const - clarodll = "claro.dll" -elif defined(macosx): - const - clarodll = "libclaro.dylib" -else: - const - clarodll = "libclaro.so" - -import cairo - -type - Node* {.pure.} = object - next*: ptr Node - prev*: ptr Node # pointer to real structure - data*: pointer - - List* {.pure.} = object - head*: ptr Node - tail*: ptr Node - count*: int32 -{.deprecated: [TNode: Node, TList: List].} - -proc list_init*(){.cdecl, importc: "list_init", dynlib: clarodll.} -proc list_create*(list: ptr List){.cdecl, importc: "list_create", - dynlib: clarodll.} -proc node_create*(): ptr Node{.cdecl, importc: "node_create", - dynlib: clarodll.} -proc node_free*(n: ptr Node){.cdecl, importc: "node_free", dynlib: clarodll.} -proc node_add*(data: pointer, n: ptr Node, L: ptr List){.cdecl, - importc: "node_add", dynlib: clarodll.} -proc node_prepend*(data: pointer, n: ptr Node, L: ptr List){.cdecl, - importc: "node_prepend", dynlib: clarodll.} -proc node_del*(n: ptr Node, L: ptr List){.cdecl, importc: "node_del", - dynlib: clarodll.} -proc node_find*(data: pointer, L: ptr List): ptr Node{.cdecl, - importc: "node_find", dynlib: clarodll.} -proc node_move*(n: ptr Node, oldlist: ptr List, newlist: ptr List){. - cdecl, importc: "node_move", dynlib: clarodll.} - -type - ClaroObj*{.pure, inheritable.} = object - typ*: array[0..64 - 1, char] - destroy_pending*: cint - event_handlers*: List - children*: List - parent*: ptr ClaroObj - appdata*: pointer # !! this is for APPLICATION USE ONLY !! - - Event*{.pure.} = object - obj*: ptr ClaroObj # the object which this event was sent to - name*: array[0..64 - 1, char] - handled*: cint - arg_num*: cint # number of arguments - format*: array[0..16 - 1, char] # format of the arguments sent - arglist*: ptr pointer # list of args, as per format. - - EventFunc* = proc (obj: ptr ClaroObj, event: ptr Event){.cdecl.} - EventIfaceFunc* = proc (obj: ptr ClaroObj, event: ptr Event, - data: pointer){.cdecl.} - EventHandler*{.pure.} = object - typ*: array[0..32 - 1, char] - data*: pointer - fun*: EventFunc # the function that handles this event -{.deprecated: [TEvent: Event, TEventFunc: EventFunc, TClaroObj: ClaroObj, - TEventIfaceFunc: EventIfaceFunc, TEventHandler: EventHandler].} - -# #define event_handler(n) void n ( ClaroObj *object, event_t *event ) -#CLVEXP list_t object_list; - -proc object_init*(){.cdecl, importc: "object_init", dynlib: clarodll.} - -proc object_override_next_size*(size: cint){.cdecl, - importc: "object_override_next_size", dynlib: clarodll.} - ## Overrides the size of next object to be created, providing the - ## size is more than is requested by default. - ## - ## `size` specifies the full size, which is greater than both ClaroObj - ## and the size that will be requested automatically. - -proc event_get_arg_ptr*(e: ptr Event, arg: cint): pointer{.cdecl, - importc: "event_get_arg_ptr", dynlib: clarodll.} -proc event_get_arg_double*(e: ptr Event, arg: cint): cdouble{.cdecl, - importc: "event_get_arg_double", dynlib: clarodll.} -proc event_get_arg_int*(e: ptr Event, arg: cint): cint{.cdecl, - importc: "event_get_arg_int", dynlib: clarodll.} -proc object_create*(parent: ptr ClaroObj, size: int32, - typ: cstring): ptr ClaroObj{. - cdecl, importc: "object_create", dynlib: clarodll.} -proc object_destroy*(obj: ptr ClaroObj){.cdecl, importc: "object_destroy", - dynlib: clarodll.} -proc object_set_parent*(obj: ptr ClaroObj, parent: ptr ClaroObj){.cdecl, - importc: "object_set_parent", dynlib: clarodll.} - -##define object_cmptype(o,t) (!strcmp(((ClaroObj *)o)->type,t)) - -# event functions - -proc object_addhandler*(obj: ptr ClaroObj, event: cstring, - fun: EventFunc){.cdecl, - importc: "object_addhandler", dynlib: clarodll.} -proc object_addhandler_interface*(obj: ptr ClaroObj, event: cstring, - fun: EventFunc, data: pointer){.cdecl, - importc: "object_addhandler_interface", dynlib: clarodll.} -proc event_send*(obj: ptr ClaroObj, event: cstring, fmt: cstring): cint{. - varargs, cdecl, importc: "event_send", dynlib: clarodll.} -proc event_get_name*(event: ptr Event): cstring{.cdecl, - importc: "event_get_name", dynlib: clarodll.} -proc claro_base_init(){.cdecl, importc: "claro_base_init", dynlib: clarodll.} -proc claro_loop*(){.cdecl, importc: "claro_loop", dynlib: clarodll.} -proc claro_run*(){.cdecl, importc: "claro_run", dynlib: clarodll.} -proc claro_shutdown*(){.cdecl, importc: "claro_shutdown", dynlib: clarodll.} -proc mssleep*(ms: cint){.cdecl, importc: "mssleep", dynlib: clarodll.} -proc claro_graphics_init(){.cdecl, importc: "claro_graphics_init", - dynlib: clarodll.} - -const - cWidgetNoBorder* = (1 shl 24) - cWidgetCustomDraw* = (1 shl 25) - -type - Bounds*{.pure.} = object - x*: cint - y*: cint - w*: cint - h*: cint - owner*: ptr ClaroObj -{.deprecated: [TBounds: Bounds].} - -const - cSizeRequestChanged* = 1 - -type - Font*{.pure.} = object - used*: cint - face*: cstring - size*: cint - weight*: cint - slant*: cint - decoration*: cint - native*: pointer - - Color*{.pure.} = object - used*: cint - r*: cfloat - g*: cfloat - b*: cfloat - a*: cfloat - - Widget* {.pure.} = object of ClaroObj - size_req*: ptr Bounds - size*: Bounds - size_ct*: Bounds - supports_alpha*: cint - size_flags*: cint - flags*: cint - visible*: cint - notify_flags*: cint - font*: Font - native*: pointer # native widget - ndata*: pointer # additional native data - container*: pointer # native widget container (if not ->native) - naddress*: array[0..3, pointer] # addressed for something - # we override or need to remember -{.deprecated: [TFont: Font, TColor: Color, TWidget: Widget].} - -proc clipboard_set_text*(w: ptr Widget, text: cstring): cint{.cdecl, - importc: "clipboard_set_text", dynlib: clarodll.} - ## Sets the (text) clipboard to the specified text value. - ## - ## `w` The widget requesting the action, some platforms may use this value. - ## `text` The text to place in the clipboard. - ## returns 1 on success, 0 on failure. - -const - cNotifyMouse* = 1'i32 - cNotifyKey* = 2'i32 - - cFontSlantNormal* = 0 - cFontSlantItalic* = 1 - cFontWeightNormal* = 0 - cFontWeightBold* = 1 - cFontDecorationNormal* = 0 - cFontDecorationUnderline* = 1 - - -proc widget_set_font*(widget: ptr ClaroObj, face: cstring, size: cint, - weight: cint, slant: cint, decoration: cint){.cdecl, - importc: "widget_set_font", dynlib: clarodll.} - ## Sets the font details of the specified widget. - ## - ## `widget` A widget - ## `face` Font face string - ## `size` Size of the font in pixels - ## `weight` The weight of the font - ## `slant` The sland of the font - ## `decoration` The decoration of the font - -proc widget_font_string_width*(widget: ptr ClaroObj, text: cstring, - chars: cint): cint {. - cdecl, importc: "widget_font_string_width", dynlib: clarodll.} - ## Calculates the pixel width of the text in the widget's font. - ## `chars` is the number of characters of text to calculate. Return value - ## is the width of the specified text in pixels. - -const - CLARO_APPLICATION* = "claro.graphics" - -type - Image* {.pure.} = object of ClaroObj - width*: cint - height*: cint - native*: pointer - native2*: pointer - native3*: pointer - icon*: pointer -{.deprecated: [TImage: Image].} - -proc image_load*(parent: ptr ClaroObj, file: cstring): ptr Image{.cdecl, - importc: "image_load", dynlib: clarodll.} - ## Loads an image from a file and returns a new image object. - ## - ## The supported formats depend on the platform. - ## The main effort is to ensure that PNG images will always work. - ## Generally, JPEGs and possibly GIFs will also work. - ## - ## `Parent` object (usually the application's main window), can be nil. - -proc image_load_inline_png*(parent: ptr ClaroObj, data: cstring, - len: cint): ptr Image{.cdecl, - importc: "image_load_inline_png", dynlib: clarodll.} - ## Loads an image from inline data and returns a new image object. - ## `Parent` object (usually the application's main window), can be nil. - ## data raw PNG image - ## len size of data - -when true: - discard -else: - # status icons are not supported on all platforms yet: - type - StatusIcon* {.pure.} = object of ClaroObj - icon*: ptr Image - native*: pointer - native2*: pointer - {.deprecated: [TStatusIcon: StatusIcon].} - - #* - # \brief Creates a status icon - # - # \param parent Parent object (usually the application's main window), - # can be NULL. - # \param image The image object for the icon NOT NULL - # \param flags Flags - # \return New status_icon_t object - # - - proc status_icon_create*(parent: ptr ClaroObj, icon: ptr Image, - flags: cint): ptr StatusIcon {. - cdecl, importc: "status_icon_create", dynlib: clarodll.} - - #* - # \brief sets the status icon's image - # - # \param status Status Icon - # \param image The image object for the icon - # - - proc status_icon_set_icon*(status: ptr StatusIcon, icon: ptr Image){.cdecl, - importc: "status_icon_set_icon", dynlib: clarodll.} - - #* - # \brief sets the status icons's menu - # - # \param status Status Icon - # \param menu The menu object for the popup menu - # - - proc status_icon_set_menu*(status: ptr StatusIcon, menu: ptr ClaroObj){.cdecl, - importc: "status_icon_set_menu", dynlib: clarodll.} - #* - # \brief sets the status icon's visibility - # - # \param status Status Icon - # \param visible whether the status icon is visible or not - # - - proc status_icon_set_visible*(status: ptr StatusIcon, visible: cint){.cdecl, - importc: "status_icon_set_visible", dynlib: clarodll.} - #* - # \brief sets the status icon's tooltip - # - # \param status Status Icon - # \param tooltip Tooltip string - # - - proc status_icon_set_tooltip*(status: ptr StatusIcon, tooltip: cstring){.cdecl, - importc: "status_icon_set_tooltip", dynlib: clarodll.} - -#* -# \brief Makes the specified widget visible. -# -# \param widget A widget -# - -proc widget_show*(widget: ptr Widget){.cdecl, importc: "widget_show", - dynlib: clarodll.} -#* -# \brief Makes the specified widget invisible. -# -# \param widget A widget -# - -proc widget_hide*(widget: ptr Widget){.cdecl, importc: "widget_hide", - dynlib: clarodll.} -#* -# \brief Enables the widget, allowing focus -# -# \param widget A widget -# - -proc widget_enable*(widget: ptr Widget){.cdecl, importc: "widget_enable", - dynlib: clarodll.} -#* -# \brief Disables the widget -# When disabled, a widget appears greyed and cannot -# receive focus. -# -# \param widget A widget -# - -proc widget_disable*(widget: ptr Widget){.cdecl, importc: "widget_disable", - dynlib: clarodll.} -#* -# \brief Give focus to the specified widget -# -# \param widget A widget -# - -proc widget_focus*(widget: ptr Widget){.cdecl, importc: "widget_focus", - dynlib: clarodll.} -#* -# \brief Closes a widget -# -# Requests that a widget be closed by the platform code. -# This may or may not result in immediate destruction of the widget, -# however the actual Claro widget object will remain valid until at -# least the next loop iteration. -# -# \param widget A widget -# - -proc widget_close*(widget: ptr Widget){.cdecl, importc: "widget_close", - dynlib: clarodll.} -#* -# \brief Retrieve the screen offset of the specified widget. -# -# Retrieves the X and Y screen positions of the widget. -# -# \param widget A widget -# \param dx Pointer to the location to place the X position. -# \param dy Pointer to the location to place the Y position. -# - -proc widget_screen_offset*(widget: ptr Widget, dx: ptr cint, dy: ptr cint){. - cdecl, importc: "widget_screen_offset", dynlib: clarodll.} -#* -# \brief Sets the additional notify events that should be sent. -# -# For performance reasons, some events, like mouse and key events, -# are not sent by default. By specifying such events here, you can -# elect to receive these events. -# -# \param widget A widget -# \param flags Any number of cWidgetNotify flags ORed together. -# - -proc widget_set_notify*(widget: ptr Widget, flags: cint){.cdecl, - importc: "widget_set_notify", dynlib: clarodll.} - - -type - CursorType* {.size: sizeof(cint).} = enum - cCursorNormal = 0, - cCursorTextEdit = 1, - cCursorWait = 2, - cCursorPoint = 3 -{.deprecated: [TCursorType: CursorType].} - -#* -# \brief Sets the mouse cursor for the widget -# -# \param widget A widget -# \param cursor A valid cCursor* value -# - -proc widget_set_cursor*(widget: ptr Widget, cursor: CursorType){.cdecl, - importc: "widget_set_cursor", dynlib: clarodll.} - -#* -# \brief Retrieves the key pressed in a key notify event. -# -# \param widget A widget -# \param event An event resource -# \return The keycode of the key pressed. -# - -proc widget_get_notify_key*(widget: ptr Widget, event: ptr Event): cint{. - cdecl, importc: "widget_get_notify_key", dynlib: clarodll.} - -#* -# \brief Updates the bounds structure with new values -# -# This function should \b always be used instead of setting the -# members manually. In the future, there may be a \b real reason -# for this. -# -# \param bounds A bounds structure -# \param x The new X position -# \param y The new Y position -# \param w The new width -# \param h The new height -# - -proc bounds_set*(bounds: ptr Bounds, x: cint, y: cint, w: cint, h: cint){. - cdecl, importc: "bounds_set", dynlib: clarodll.} -#* -# \brief Create a new bounds object -# -# Creates a new bounds_t for the specified bounds. -# -# \param x X position -# \param y Y position -# \param w Width -# \param h Height -# \return A new bounds_t structure -# - -proc new_bounds*(x: cint, y: cint, w: cint, h: cint): ptr Bounds{.cdecl, - importc: "new_bounds", dynlib: clarodll.} -proc get_req_bounds*(widget: ptr Widget): ptr Bounds{.cdecl, - importc: "get_req_bounds", dynlib: clarodll.} - -var - noBoundsVar: Bounds # set to all zero which is correct - -template noBounds*: expr = (addr(bind noBoundsVar)) - -#* \internal -# \brief Internal pre-inititalisation hook -# -# \param widget A widget -# - -proc widget_pre_init*(widget: ptr Widget){.cdecl, importc: "widget_pre_init", - dynlib: clarodll.} -#* \internal -# \brief Internal post-inititalisation hook -# -# \param widget A widget -# - -proc widget_post_init*(widget: ptr Widget){.cdecl, - importc: "widget_post_init", dynlib: clarodll.} -#* \internal -# \brief Internal resize event handler -# -# \param obj An object -# \param event An event resource -# - -proc widget_resized_handle*(obj: ptr Widget, event: ptr Event){.cdecl, - importc: "widget_resized_handle", dynlib: clarodll.} -# CLVEXP bounds_t no_bounds; -#* \internal -# \brief Internal default widget creation function -# -# \param parent The parent of the widget -# \param widget_size The size in bytes of the widget's structure -# \param widget_name The object type of the widget (claro.graphics.widgets.*) -# \param size_req The initial bounds of the widget -# \param flags Widget flags -# \param creator The platform function that will be called to actually create -# the widget natively. -# \return A new widget object -# - -type - CgraphicsCreateFunction* = proc (widget: ptr Widget) {.cdecl.} -{.deprecated: [TcgraphicsCreateFunction: CgraphicsCreateFunction].} - -proc newdefault*(parent: ptr Widget, widget_size: int, - widget_name: cstring, size_req: ptr Bounds, flags: cint, - creator: CgraphicsCreateFunction): ptr Widget{.cdecl, - importc: "default_widget_create", dynlib: clarodll.} -#* \internal -# \brief Retrieves the native container of the widget's children -# -# \param widget A widget -# \return A pointer to the native widget that will hold w's children -# - -proc widget_get_container*(widget: ptr Widget): pointer{.cdecl, - importc: "widget_get_container", dynlib: clarodll.} -#* \internal -# \brief Sets the content size of the widget. -# -# \param widget A widget -# \param w New width of the content area of the widget -# \param h New height of the content area of the widget -# \param event Whether to send a content_size event -# - -proc widget_set_content_size*(widget: ptr Widget, w: cint, h: cint, - event: cint){.cdecl, - importc: "widget_set_content_size", dynlib: clarodll.} -#* \internal -# \brief Sets the size of the widget. -# -# \param widget A widget -# \param w New width of the widget -# \param h New height of the widget -# \param event Whether to send a resize event -# - -proc widget_set_size*(widget: ptr Widget, w: cint, h: cint, event: cint){. - cdecl, importc: "widget_set_size", dynlib: clarodll.} -#* \internal -# \brief Sets the position of the widget's content area. -# -# \param widget A widget -# \param x New X position of the widget's content area -# \param y New Y position of the widget's content area -# \param event Whether to send a content_move event -# - -proc widget_set_content_position*(widget: ptr Widget, x: cint, y: cint, - event: cint){.cdecl, - importc: "widget_set_content_position", dynlib: clarodll.} -#* \internal -# \brief Sets the position of the widget. -# -# \param widget A widget -# \param x New X position of the widget's content area -# \param y New Y position of the widget's content area -# \param event Whether to send a moved event -# - -proc widget_set_position*(widget: ptr Widget, x: cint, y: cint, event: cint){. - cdecl, importc: "widget_set_position", dynlib: clarodll.} -#* \internal -# \brief Sends a destroy event to the specified widget. -# -# You should use widget_close() in application code instead. -# -# \param widget A widget -# - -proc widget_destroy*(widget: ptr Widget){.cdecl, importc: "widget_destroy", - dynlib: clarodll.} - -type - OpenglWidget* {.pure.} = object of Widget - gldata*: pointer -{.deprecated: [TOpenglWidget: OpenglWidget].} - -# functions -#* -# \brief Creates a OpenGL widget -# -# \param parent The parent widget of this widget, NOT NULL. -# \param bounds The initial bounds of this widget, or NO_BOUNDS. -# \param flags Widget flags. -# \return A new OpenGL widget object. -# - -proc newopengl*(parent: ptr ClaroObj, bounds: ptr Bounds, - flags: cint): ptr OpenglWidget {. - cdecl, importc: "opengl_widget_create", dynlib: clarodll.} -#* -# \brief Flips the front and back buffers -# -# \param widget A valid OpenGL widget object -# - -proc opengl_flip*(widget: ptr OpenglWidget) {.cdecl, importc: "opengl_flip", - dynlib: clarodll.} -#* -# \brief Activates this OpenGL widget's context -# -# \param widget A valid OpenGL widget object -# - -proc opengl_activate*(widget: ptr OpenglWidget) {. - cdecl, importc: "opengl_activate", dynlib: clarodll.} - -type - Button* {.pure.} = object of Widget - text*: array[0..256-1, char] -{.deprecated: [TButton: Button].} - -# functions -#* -# \brief Creates a Button widget -# -# \param parent The parent widget of this widget, NOT NULL. -# \param bounds The initial bounds of this widget, or NO_BOUNDS. -# \param flags Widget flags. -# \return A new Button widget object. -# - -proc newbutton*(parent: ptr ClaroObj, bounds: ptr Bounds, - flags: cint): ptr Button {. - cdecl, importc: "button_widget_create", dynlib: clarodll.} -#* -# \brief Creates a Button widget with a label -# -# \param parent The parent widget of this widget, NOT NULL. -# \param bounds The initial bounds of this widget, or NO_BOUNDS. -# \param flags Widget flags. -# \param label The label for the button -# \return A new Button widget object. -# - -proc newbutton*(parent: ptr ClaroObj, - bounds: ptr Bounds, flags: cint, - label: cstring): ptr Button{.cdecl, - importc: "button_widget_create_with_label", dynlib: clarodll.} -#* -# \brief Changes the label of the button -# -# \param obj A valid Button widget object -# \param label The new label for the button -# - -proc button_set_text*(obj: ptr Button, label: cstring){.cdecl, - importc: "button_set_label", dynlib: clarodll.} - -#* -# \brief Changes the image of the button -# -# \warning This function is not implemented yet and is not portable. -# Do not use it. -# -# \param obj A valid Button widget object -# \param image The new image for the button -# - -proc button_set_image*(obj: ptr Button, image: ptr Image){.cdecl, - importc: "button_set_image", dynlib: clarodll.} - -const - CTEXT_SLANT_NORMAL* = cFontSlantNormal - CTEXT_SLANT_ITALIC* = cFontSlantItalic - CTEXT_WEIGHT_NORMAL* = cFontWeightNormal - CTEXT_WEIGHT_BOLD* = cFontWeightBold - CTEXT_EXTRA_NONE* = cFontDecorationNormal - CTEXT_EXTRA_UNDERLINE* = cFontDecorationUnderline - -# END OLD - -type - Canvas*{.pure.} = object of Widget - surface*: cairo.PSurface - cr*: cairo.PContext - surfdata*: pointer - fontdata*: pointer - font_height*: cint - fr*: cfloat - fg*: cfloat - fb*: cfloat - fa*: cfloat - br*: cfloat - bg*: cfloat - bb*: cfloat - ba*: cfloat - charsize*: array[0..256 - 1, cairo.TTextExtents] - csz_loaded*: cint - fontsize*: cint -{.deprecated: [TCanvas: Canvas].} - -# functions -#* -# \brief Creates a Canvas widget -# -# \param parent The parent widget of this widget, NOT NULL. -# \param bounds The initial bounds of this widget, or NO_BOUNDS. -# \param flags Widget flags. -# \return A new Canvas widget object. -# - -proc newcanvas*(parent: ptr ClaroObj, bounds: ptr Bounds, - flags: cint): ptr Canvas{. - cdecl, importc: "canvas_widget_create", dynlib: clarodll.} -#* -# \brief Invalidates and redraws a canvas widget -# -# \param widget A valid Canvas widget object. -# - -proc canvas_redraw*(widget: ptr Canvas){.cdecl, importc: "canvas_redraw", - dynlib: clarodll.} -# claro text functions -#* -# \brief Set the current text color -# -# \param widget A valid Canvas widget object. -# \param r Red component (0.0 - 1.0) -# \param g Green component (0.0 - 1.0) -# \param b Blue component (0.0 - 1.0) -# \param a Alpha component (0.0 - 1.0) -# - -proc canvas_set_text_color*(widget: ptr Canvas, r: cdouble, g: cdouble, - b: cdouble, a: cdouble){.cdecl, - importc: "canvas_set_text_color", dynlib: clarodll.} -#* -# \brief Set the current text background color -# -# \param widget A valid Canvas widget object. -# \param r Red component (0.0 - 1.0) -# \param g Green component (0.0 - 1.0) -# \param b Blue component (0.0 - 1.0) -# \param a Alpha component (0.0 - 1.0) -# - -proc canvas_set_text_bgcolor*(widget: ptr Canvas, r: cdouble, g: cdouble, - b: cdouble, a: cdouble){.cdecl, - importc: "canvas_set_text_bgcolor", dynlib: clarodll.} -#* -# \brief Set the current canvas font -# -# \param widget A valid Canvas widget object. -# \param face The font face -# \param size The font height in pixels -# \param weight The weight of the font -# \param slant The slant of the font -# \param decoration Font decorations -# - -proc canvas_set_text_font*(widget: ptr Canvas, face: cstring, size: cint, - weight: cint, slant: cint, decoration: cint){.cdecl, - importc: "canvas_set_text_font", dynlib: clarodll.} -#* -# \brief Calculates the width of the specified text -# -# \param widget A valid Canvas widget object. -# \param text The text to calulate the length of -# \param len The number of characters of text to calulcate -# \return Width of the text in pixels -# - -proc canvas_text_width*(widget: ptr Canvas, text: cstring, len: cint): cint{. - cdecl, importc: "canvas_text_width", dynlib: clarodll.} -#* -# \brief Calculates the width of the specified text's bounding box -# -# \param widget A valid Canvas widget object. -# \param text The text to calulate the length of -# \param len The number of characters of text to calulcate -# \return Width of the text's bounding box in pixels -# - -proc canvas_text_box_width*(widget: ptr Canvas, text: cstring, - len: cint): cint{. - cdecl, importc: "canvas_text_box_width", dynlib: clarodll.} -#* -# \brief Calculates the number of characters of text that can be displayed -# before width pixels. -# -# \param widget A valid Canvas widget object. -# \param text The text to calulate the length of -# \param width The width to fit the text in -# \return The number of characters of text that will fit in width pixels. -# - -proc canvas_text_display_count*(widget: ptr Canvas, text: cstring, - width: cint): cint{.cdecl, - importc: "canvas_text_display_count", dynlib: clarodll.} -#* -# \brief Displays the specified text on the canvas -# -# \param widget A valid Canvas widget object. -# \param x The X position at which the text will be drawn -# \param y The Y position at which the text will be drawn -# \param text The text to calulate the length of -# \param len The number of characters of text to calulcate -# - -proc canvas_show_text*(widget: ptr Canvas, x: cint, y: cint, text: cstring, - len: cint){.cdecl, importc: "canvas_show_text", - dynlib: clarodll.} -#* -# \brief Draws a filled rectangle -# -# \param widget A valid Canvas widget object. -# \param x The X position at which the rectangle will start -# \param y The Y position at which the rectangle will start -# \param w The width of the rectangle -# \param h The height of the rectangle -# \param r Red component (0.0 - 1.0) -# \param g Green component (0.0 - 1.0) -# \param b Blue component (0.0 - 1.0) -# \param a Alpha component (0.0 - 1.0) -# - -proc canvas_fill_rect*(widget: ptr Canvas, x: cint, y: cint, w: cint, - h: cint, r, g, b, a: cdouble){. - cdecl, importc: "canvas_fill_rect", dynlib: clarodll.} -#* -# \brief Draws the specified image on the canvas -# -# \param widget A valid Canvas widget object. -# \param image The image to draw -# \param x The X position at which the image will be drawn -# \param y The Y position at which the image will be drawn -# - -proc canvas_draw_image*(widget: ptr Canvas, image: ptr Image, x: cint, - y: cint){.cdecl, importc: "canvas_draw_image", - dynlib: clarodll.} -# claro "extensions" of cairo -#* \internal -# \brief Internal claro extension of cairo text functions -# - -proc canvas_cairo_buffered_text_width*(widget: ptr Canvas, - text: cstring, len: cint): cint{.cdecl, - importc: "canvas_cairo_buffered_text_width", dynlib: clarodll.} -#* \internal -# \brief Internal claro extension of cairo text functions -# - -proc canvas_cairo_buffered_text_display_count*(widget: ptr Canvas, - text: cstring, width: cint): cint{.cdecl, - importc: "canvas_cairo_buffered_text_display_count", - dynlib: clarodll.} -proc canvas_get_cairo_context*(widget: ptr Canvas): cairo.PContext {.cdecl, - importc: "canvas_get_cairo_context", dynlib: clarodll.} - -type - CheckBox*{.pure.} = object of Widget - text*: array[0..256-1, char] - checked*: cint -{.deprecated: [TCheckBox: CheckBox].} -#* -# \brief Creates a Checkbox widget -# -# \param parent The parent widget of this widget, NOT NULL. -# \param bounds The initial bounds of this widget, or NO_BOUNDS. -# \param flags Widget flags. -# \return A new Checkbox widget object. -# - -proc newcheckbox*(parent: ptr ClaroObj, bounds: ptr Bounds, - flags: cint): ptr CheckBox{. - cdecl, importc: "checkbox_widget_create", dynlib: clarodll.} -#* -# \brief Creates a Checkbox widget with a label -# -# \param parent The parent widget of this widget, NOT NULL. -# \param bounds The initial bounds of this widget, or NO_BOUNDS. -# \param flags Widget flags. -# \param label The label for the checkbox -# \return A new Checkbox widget object. -# - -proc newcheckbox*(parent: ptr ClaroObj, - bounds: ptr Bounds, flags: cint, - label: cstring): ptr CheckBox {.cdecl, - importc: "checkbox_widget_create_with_label", dynlib: clarodll.} -#* -# \brief Sets a new label for the Checkbox widget -# -# \param obj A valid Checkbox widget object. -# \param label The new label for the checkbox -# - -proc checkbox_set_text*(obj: ptr CheckBox, label: cstring){.cdecl, - importc: "checkbox_set_label", dynlib: clarodll.} -#* -# \brief Retrieves the checkbox's check state -# -# \param obj A valid Checkbox widget object. -# \return 1 if the checkbox is checked, otherwise 0 -# - -proc checkbox_checked*(obj: ptr CheckBox): cint{.cdecl, - importc: "checkbox_get_checked", dynlib: clarodll.} -#* -# \brief Sets the checkbox's checked state -# -# \param obj A valid Checkbox widget object. -# \param checked 1 if the checkbox should become checked, otherwise 0 -# - -proc checkbox_set_checked*(obj: ptr CheckBox, checked: cint){.cdecl, - importc: "checkbox_set_checked", dynlib: clarodll.} - - -#* -# List items define items in a list_widget -# - -type - ListItem*{.pure.} = object of ClaroObj - row*: cint - native*: pointer - nativeid*: int - menu*: ptr ClaroObj - enabled*: cint - data*: ptr pointer - ListItemChildren*: List - ListItemParent*: ptr List - parent_item*: ptr ListItem # drawing related info, not always required - text_color*: Color - sel_text_color*: Color - back_color*: Color - sel_back_color*: Color - font*: Font - - ListWidget* {.pure.} = object of Widget ## List widget, base for - ## widgets containing items - columns*: cint - coltypes*: ptr cint - items*: List - - Combo*{.pure.} = object of ListWidget - selected*: ptr ListItem -{.deprecated: [TListItem: ListItem, TListWidget: ListWidget, TCombo: Combo].} - -# functions -#* -# \brief Creates a Combo widget -# -# \param parent The parent widget of this widget, NOT NULL. -# \param bounds The initial bounds of this widget, or NO_BOUNDS. -# \param flags Widget flags. -# \return A new Combo widget object. -# - -proc newcombo*(parent: ptr ClaroObj, bounds: ptr Bounds, - flags: cint): ptr Combo{. - cdecl, importc: "combo_widget_create", dynlib: clarodll.} -#* -# \brief Append a row to a Combo widget -# -# \param combo A valid Combo widget object. -# \param text The text for the item. -# \return A new list item. -# - -proc combo_append_row*(combo: ptr Combo, text: cstring): ptr ListItem {. - cdecl, importc: "combo_append_row", dynlib: clarodll.} -#* -# \brief Insert a row at the specified position into a Combo widget -# -# \param combo A valid Combo widget object. -# \param pos The index at which this item will be placed. -# \param text The text for the item. -# \return A new list item. -# - -proc combo_insert_row*(combo: ptr Combo, pos: cint, - text: cstring): ptr ListItem {. - cdecl, importc: "combo_insert_row", dynlib: clarodll.} -#* -# \brief Move a row in a Combo widget -# -# \param combo A valid Combo widget object. -# \param item A valid list item -# \param row New position to place this item -# - -proc combo_move_row*(combo: ptr Combo, item: ptr ListItem, row: cint){. - cdecl, importc: "combo_move_row", dynlib: clarodll.} -#* -# \brief Remove a row from a Combo widget -# -# \param combo A valid Combo widget object. -# \param item A valid list item -# - -proc combo_remove_row*(combo: ptr Combo, item: ptr ListItem){.cdecl, - importc: "combo_remove_row", dynlib: clarodll.} -#* -# \brief Returns the currently selected Combo item -# -# \param obj A valid Combo widget object. -# \return The currently selected Combo item, or NULL if no item is selected. -# - -proc combo_get_selected*(obj: ptr Combo): ptr ListItem{.cdecl, - importc: "combo_get_selected", dynlib: clarodll.} -#* -# \brief Returns the number of rows in a Combo widget -# -# \param obj A valid Combo widget object. -# \return Number of rows -# - -proc combo_get_rows*(obj: ptr Combo): cint{.cdecl, - importc: "combo_get_rows", dynlib: clarodll.} -#* -# \brief Selects a row in a Combo widget -# -# \param obj A valid Combo widget object. -# \param item A valid list item -# - -proc combo_select_item*(obj: ptr Combo, item: ptr ListItem){.cdecl, - importc: "combo_select_item", dynlib: clarodll.} -#* -# \brief Removes all entries from a Combo widget -# -# \param obj A valid Combo widget object. -# - -proc combo_clear*(obj: ptr Combo){.cdecl, importc: "combo_clear", - dynlib: clarodll.} - -type - ContainerWidget* {.pure.} = object of Widget -{.deprecated: [TContainerWidget: ContainerWidget].} - - -# functions -#* -# \brief Creates a Container widget -# -# \param parent The parent widget of this widget, NOT NULL. -# \param bounds The initial bounds of this widget, or NO_BOUNDS. -# \param flags Widget flags. -# \return A new Container widget object. -# - -proc newcontainer*(parent: ptr ClaroObj, bounds: ptr Bounds, - flags: cint): ptr ContainerWidget{. - cdecl, importc: "container_widget_create", dynlib: clarodll.} - -proc newdialog*(parent: ptr ClaroObj, bounds: ptr Bounds, format: cstring, - flags: cint): ptr ClaroObj{.cdecl, - importc: "dialog_widget_create", dynlib: clarodll.} -proc dialog_set_text*(obj: ptr ClaroObj, text: cstring){.cdecl, - importc: "dialog_set_text", dynlib: clarodll.} -proc dialog_set_default_icon*(typ: cstring, file: cstring){.cdecl, - importc: "dialog_set_default_icon", dynlib: clarodll.} -proc dialog_get_default_icon*(dialog_type: cint): cstring{.cdecl, - importc: "dialog_get_default_icon", dynlib: clarodll.} -proc dialog_warning*(format: cstring, text: cstring): cint{.cdecl, - importc: "dialog_warning", dynlib: clarodll.} -proc dialog_info*(format: cstring, text: cstring): cint{.cdecl, - importc: "dialog_info", dynlib: clarodll.} -proc dialog_error*(format: cstring, text: cstring): cint{.cdecl, - importc: "dialog_error", dynlib: clarodll.} -proc dialog_other*(format: cstring, text: cstring, default_icon: cstring): cint{. - cdecl, importc: "dialog_other", dynlib: clarodll.} - -type - FontDialog* {.pure.} = object of Widget - selected*: Font -{.deprecated: [TFontDialog: FontDialog].} - -# functions -#* -# \brief Creates a Font Selection widget -# -# \param parent The parent widget of this widget, NOT NULL. -# \param flags Widget flags. -# \return A new Font Selection widget object. -# - -proc newFontDialog*(parent: ptr ClaroObj, flags: cint): ptr FontDialog {. - cdecl, importc: "font_dialog_widget_create", dynlib: clarodll.} -#* -# \brief Changes the selected font -# -# \param obj A valid Font Selection widget object -# \param font The name of the font -# - -proc font_dialog_set_font*(obj: ptr FontDialog, face: cstring, size: cint, - weight: cint, slant: cint, decoration: cint){.cdecl, - importc: "font_dialog_set_font", dynlib: clarodll.} -#* -# \brief Returns a structure representing the currently selected font -# -# \param obj A valid Font Selection widget object -# \return A font_t structure containing information about the selected font. -# - -proc font_dialog_get_font*(obj: ptr FontDialog): ptr Font{.cdecl, - importc: "font_dialog_get_font", dynlib: clarodll.} - -type - Frame* {.pure.} = object of Widget - text*: array[0..256-1, char] -{.deprecated: [TFrame: Frame].} - -#* -# \brief Creates a Frame widget -# -# \param parent The parent widget of this widget, NOT NULL. -# \param bounds The initial bounds of this widget, or NO_BOUNDS. -# \param flags Widget flags. -# \return A new Frame widget object. -# - -proc newframe*(parent: ptr ClaroObj, bounds: ptr Bounds, - flags: cint): ptr Frame{. - cdecl, importc: "frame_widget_create", dynlib: clarodll.} -#* -# \brief Creates a Frame widget with a label -# -# \param parent The parent widget of this widget, NOT NULL. -# \param bounds The initial bounds of this widget, or NO_BOUNDS. -# \param flags Widget flags. -# \param label The initial label for the frame -# \return A new Frame widget object. -# - -proc newframe*(parent: ptr ClaroObj, bounds: ptr Bounds, flags: cint, - label: cstring): ptr Frame {.cdecl, - importc: "frame_widget_create_with_label", dynlib: clarodll.} -#* -# \brief Creates a Container widget -# -# \param parent The parent widget of this widget, NOT NULL. -# \param bounds The initial bounds of this widget, or NO_BOUNDS. -# \param flags Widget flags. -# \return A new Container widget object. -# - -proc frame_set_text*(frame: ptr Frame, label: cstring){.cdecl, - importc: "frame_set_label", dynlib: clarodll.} - -type - ImageWidget* {.pure.} = object of Widget - src*: ptr Image -{.deprecated: [TImageWidget: ImageWidget].} - -#* -# \brief Creates an Image widget -# -# \param parent The parent widget of this widget, NOT NULL. -# \param bounds The initial bounds of this widget, or NO_BOUNDS. -# \param flags Widget flags. -# \return A new Image widget object. -# - -proc newimageWidget*(parent: ptr ClaroObj, bounds: ptr Bounds, - flags: cint): ptr ImageWidget{. - cdecl, importc: "image_widget_create", dynlib: clarodll.} -#* -# \brief Creates an Image widget with an image -# -# \param parent The parent widget of this widget, NOT NULL. -# \param bounds The initial bounds of this widget, or NO_BOUNDS. -# \param flags Widget flags. -# \param image A valid Image object. -# \return A new Image widget object. -# - -proc newimageWidget*(parent: ptr ClaroObj, - bounds: ptr Bounds, flags: cint, - image: ptr Image): ptr ImageWidget{.cdecl, - importc: "image_widget_create_with_image", dynlib: clarodll.} -#* -# \brief Sets the image object of the image widget -# -# \param image A valid image widget -# \param src The source image object -# - -proc image_set_image*(image: ptr ImageWidget, src: ptr Image){.cdecl, - importc: "image_set_image", dynlib: clarodll.} - -type - Label*{.pure.} = object of Widget - text*: array[0..256-1, char] - - CLabelJustify* = enum - cLabelLeft = 0x00000001, cLabelRight = 0x00000002, - cLabelCenter = 0x00000004, cLabelFill = 0x00000008 -{.deprecated: [TLabel: Label, TcLabelJustify: CLabelJustify].} - -#* -# \brief Creates a Label widget -# -# \param parent The parent widget of this widget, NOT NULL. -# \param bounds The initial bounds of this widget, or NO_BOUNDS. -# \param flags Widget flags. -# \return A new Label widget object. -# - -proc newlabel*(parent: ptr ClaroObj, bounds: ptr Bounds, - flags: cint): ptr Label{. - cdecl, importc: "label_widget_create", dynlib: clarodll.} -#* -# \brief Creates a Label widget -# -# \param parent The parent widget of this widget, NOT NULL. -# \param bounds The initial bounds of this widget, or NO_BOUNDS. -# \param flags Widget flags. -# \return A new Label widget object. -# - -proc newLabel*(parent: ptr ClaroObj, - bounds: ptr Bounds, flags: cint, - text: cstring): ptr Label{.cdecl, - importc: "label_widget_create_with_text", dynlib: clarodll.} -#* -# \brief Sets the text of a label widget -# -# \param obj A valid label widget -# \param text The text this label widget will show -# - -proc label_set_text*(obj: ptr Label, text: cstring){.cdecl, - importc: "label_set_text", dynlib: clarodll.} - -#* -# \brief Sets the alignment/justification of a label -# -# \param obj A valid label widget -# \param text The justification (see cLabelJustify enum) -# - -proc label_set_justify*(obj: ptr Label, flags: cint){.cdecl, - importc: "label_set_justify", dynlib: clarodll.} - -const - CLIST_TYPE_PTR* = 0 - CLIST_TYPE_STRING* = 1 - CLIST_TYPE_INT* = 2 - CLIST_TYPE_UINT* = 3 - CLIST_TYPE_DOUBLE* = 4 - -# functions -#* -# \brief Initialises a list_widget_t derivative's storage space. -# -# \param obj list widget -# \param col_num number of columns to be used -# \param cols An array of col_num integers, specifying the -# types of the columns. -# - -proc list_widget_init_ptr*(obj: ptr ListWidget, col_num: cint, - cols: ptr cint) {.cdecl, - importc: "list_widget_init_ptr", dynlib: clarodll.} -#* -# \brief Copies and passes on the arg list to list_widget_init_ptr. -# -# \param obj list widget -# \param col_num number of columns to be used -# \param argpi A pointer to a va_list to parse -# - -#proc list_widget_init_vaptr*(obj: ptr ClaroObj, col_num: cunsignedint, -# argpi: va_list){.cdecl, -# importc: "list_widget_init_vaptr", dynlib: clarodll.} - -#* -# Shortcut function, simply calls list_widget_init_ptr with -# it's own arguments, and a pointer to the first variable argument. -# - -proc list_widget_init*(obj: ptr ListWidget, col_num: cint){.varargs, - cdecl, importc: "list_widget_init", dynlib: clarodll.} -#* -# \brief Inserts a row to a list under parent at the position specified. -# -# \param list list to insert item in -# \param parent item in tree to be used as parent. NULL specifies -# that it should be a root node. -# \param row item will be inserted before the item currently at -# this position. -1 specifies an append. -# \param argp points to the first element of an array containing -# the column data as specified by the types in list_widget_init. -# - -#* -# Shortcut function, calls list_widget_row_insert_ptr with -# it's own arguments, a position at the end of the list, and -# a pointer to the first variable argument. -# - -proc list_widget_row_append*(list: ptr ListWidget, - parent: ptr ListItem): ptr ListItem{. - varargs, cdecl, importc: "list_widget_row_append", dynlib: clarodll.} -#* -# Shortcut function, calls list_widget_row_insert_ptr with -# it's own arguments, and a pointer to the first variable argument. -# - -proc list_widget_row_insert*(list: ptr ListWidget, parent: ptr ListItem, - pos: cint): ptr ListItem {.varargs, cdecl, - importc: "list_widget_row_insert", dynlib: clarodll.} -#* -# \brief Removes a row from a list -# -# \param list List widget to operate on -# \param item The item to remove -# - -proc list_widget_row_remove*(list: ptr ListWidget, item: ptr ListItem){. - cdecl, importc: "list_widget_row_remove", dynlib: clarodll.} -#* -# \brief Moves a row to a new position in the list -# -# \param list List widget to operate on -# \param item The item to move -# \param row Row position to place item before. Passing the current -# position will result in no change. -# - -proc list_widget_row_move*(list: ptr ListWidget, item: ptr ListItem, - row: cint){.cdecl, importc: "list_widget_row_move", - dynlib: clarodll.} -#* -# \brief Return the nth row under parent in the list -# -# \param list List widget search -# \param parent Parent of the item -# \param row Row index of item to return -# - -proc list_widget_get_row*(list: ptr ListWidget, parent: ptr ListItem, - row: cint): ptr ListItem{.cdecl, - importc: "list_widget_get_row", dynlib: clarodll.} -#* -# \brief Edit items of a row in the list. -# -# \param list List widget to edit -# \param item Row to modify -# \param args num,val,...,-1 where num is the column and val is the new -# value of the column's type. Terminate with -1. -# Don't forget the -1. -# - -#* -# \brief Edit items of a row in the list. -# -# \param list List-based (list_widget_t) object -# \param item Row to modify -# \param ... num,val,...,-1 where num is the column and val is the new -# value of the column's type. Terminate with -1. -# Don't forget the -1. -# - -proc list_widget_edit_row*(list: ptr ListWidget, item: ptr ListItem){. - varargs, cdecl, importc: "list_widget_edit_row", dynlib: clarodll.} -#* -# \brief Set the text color of an item. -# This is currently only supported by the TreeView widget. -# -# \param item Target list item -# \param r Red component between 0.0 and 1.0 -# \param g Green component between 0.0 and 1.0 -# \param b Blue component between 0.0 and 1.0 -# \param a Alpha component between 0.0 and 1.0 (reserved for future use, -# should be 1.0) -# - -proc list_item_set_text_color*(item: ptr ListItem, r: cfloat, g: cfloat, - b: cfloat, a: cfloat){.cdecl, - importc: "list_item_set_text_color", dynlib: clarodll.} -#* -# \brief Set the text background color of an item. -# This is currently only supported by the TreeView widget. -# -# \param item Target list item -# \param r Red component between 0.0 and 1.0 -# \param g Green component between 0.0 and 1.0 -# \param b Blue component between 0.0 and 1.0 -# \param a Alpha component between 0.0 and 1.0 (reserved for future use, -# should be 1.0) -# - -proc list_item_set_text_bgcolor*(item: ptr ListItem, r: cfloat, g: cfloat, - b: cfloat, a: cfloat){.cdecl, - importc: "list_item_set_text_bgcolor", dynlib: clarodll.} -#* -# \brief Set the text color of a selected item. -# This is currently only supported by the TreeView widget. -# -# \param item Target list item -# \param r Red component between 0.0 and 1.0 -# \param g Green component between 0.0 and 1.0 -# \param b Blue component between 0.0 and 1.0 -# \param a Alpha component between 0.0 and 1.0 (reserved for future use, -# should be 1.0) -# - -proc list_item_set_sel_text_color*(item: ptr ListItem, r: cfloat, g: cfloat, - b: cfloat, a: cfloat){.cdecl, - importc: "list_item_set_sel_text_color", dynlib: clarodll.} -#* -# \brief Set the text background color of a selected item. -# This is currently only supported by the TreeView widget. -# -# \param item Target list item -# \param r Red component between 0.0 and 1.0 -# \param g Green component between 0.0 and 1.0 -# \param b Blue component between 0.0 and 1.0 -# \param a Alpha component between 0.0 and 1.0 (reserved for future use, -# should be 1.0) -# - -proc list_item_set_sel_text_bgcolor*(item: ptr ListItem, r: cfloat, - g: cfloat, b: cfloat, a: cfloat){.cdecl, - importc: "list_item_set_sel_text_bgcolor", dynlib: clarodll.} -#* -# \brief Set the font details of the specified item. -# -# \param item Target list item -# \param weight The weight of the font -# \param slant The slant of the font -# \param decoration Font decorations -# - -proc list_item_set_font_extra*(item: ptr ListItem, weight: cint, - slant: cint, decoration: cint){.cdecl, - importc: "list_item_set_font_extra", dynlib: clarodll.} - -type - Listbox* {.pure.} = object of ListWidget - selected*: ptr ListItem -{.deprecated: [TListbox: Listbox].} - -# functions -#* -# \brief Creates a ListBox widget -# -# \param parent The parent widget of this widget, NOT NULL. -# \param bounds The initial bounds of this widget, or NO_BOUNDS. -# \param flags Widget flags. -# \return A new ListBox widget object. -# - -proc newlistbox*(parent: ptr ClaroObj, bounds: ptr Bounds, - flags: cint): ptr Listbox{. - cdecl, importc: "listbox_widget_create", dynlib: clarodll.} -#* -# \brief Insert a row at the specified position into a ListBox widget -# -# \param listbox A valid ListBox widget object. -# \param pos The index at which this item will be placed. -# \param text The text for the item. -# \return A new list item. -# - -proc listbox_insert_row*(listbox: ptr Listbox, pos: cint, - text: cstring): ptr ListItem{. - cdecl, importc: "listbox_insert_row", dynlib: clarodll.} -#* -# \brief Append a row to a ListBox widget -# -# \param listbox A valid ListBox widget object. -# \param text The text for the item. -# \return A new list item. -# - -proc listbox_append_row*(listbox: ptr Listbox, text: cstring): ptr ListItem{. - cdecl, importc: "listbox_append_row", dynlib: clarodll.} -#* -# \brief Move a row in a ListBox widget -# -# \param listbox A valid ListBox widget object. -# \param item A valid list item -# \param row New position to place this item -# - -proc listbox_move_row*(listbox: ptr Listbox, item: ptr ListItem, row: cint){. - cdecl, importc: "listbox_move_row", dynlib: clarodll.} -#* -# \brief Remove a row from a ListBox widget -# -# \param listbox A valid ListBox widget object. -# \param item A valid list item -# - -proc listbox_remove_row*(listbox: ptr Listbox, item: ptr ListItem){.cdecl, - importc: "listbox_remove_row", dynlib: clarodll.} -#* -# \brief Returns the currently selected ListBox item -# -# \param obj A valid ListBox widget object. -# \return The currently selected ListBox item, or NULL if no item is selected. -# - -proc listbox_get_selected*(obj: ptr Listbox): ptr ListItem{.cdecl, - importc: "listbox_get_selected", dynlib: clarodll.} -#* -# \brief Returns the number of rows in a ListBox widget -# -# \param obj A valid ListBox widget object. -# \return Number of rows -# - -proc listbox_get_rows*(obj: ptr Listbox): cint{.cdecl, - importc: "listbox_get_rows", dynlib: clarodll.} -#* -# \brief Selects a row in a ListBox widget -# -# \param obj A valid ListBox widget object. -# \param item A valid list item -# - -proc listbox_select_item*(obj: ptr Listbox, item: ptr ListItem){.cdecl, - importc: "listbox_select_item", dynlib: clarodll.} - -const - cListViewTypeNone* = 0 - cListViewTypeText* = 1 - cListViewTypeCheckBox* = 2 - cListViewTypeProgress* = 3 - -# whole row checkboxes.. will we really need this? hmm. - -const - cListViewRowCheckBoxes* = 1 - -type - Listview* {.pure.} = object of ListWidget - titles*: cstringArray - nativep*: pointer - selected*: ptr ListItem -{.deprecated: [TListview: Listview].} - -# functions -#* -# \brief Creates a ListView widget -# -# \param parent The parent widget of this widget, NOT NULL. -# \param bounds The initial bounds of this widget, or NO_BOUNDS. -# \param flags Widget flags. -# \param columns The number of columns in the listview -# \param ... specifies the titles and types of each column. -# ("Enable",cListViewTypeCheckBox,"Title",cListViewTypeText,...) -# \return A new ListView widget object. -# - -proc newlistview*(parent: ptr ClaroObj, bounds: ptr Bounds, columns: cint, - flags: cint): ptr Listview {.varargs, cdecl, - importc: "listview_widget_create", dynlib: clarodll.} -#* -# \brief Append a row to a ListView widget -# -# \param listview A valid ListView widget object. -# \param ... A list of values for each column -# \return A new list item. -# - -proc listview_append_row*(listview: ptr Listview): ptr ListItem{.varargs, - cdecl, importc: "listview_append_row", dynlib: clarodll.} -#* -# \brief Insert a row at the specified position into a ListView widget -# -# \param listview A valid ListView widget object. -# \param pos The index at which this item will be placed. -# \param ... A list of values for each column -# \return A new list item. -# - -proc listview_insert_row*(listview: ptr Listview, pos: cint): ptr ListItem{. - varargs, cdecl, importc: "listview_insert_row", dynlib: clarodll.} -#* -# \brief Move a row in a ListView widget -# -# \param listview A valid ListView widget object. -# \param item A valid list item -# \param row New position to place this item -# - -proc listview_move_row*(listview: ptr Listview, item: ptr ListItem, - row: cint){.cdecl, importc: "listview_move_row", - dynlib: clarodll.} -#* -# \brief Remove a row from a ListView widget -# -# \param listview A valid ListView widget object. -# \param item A valid list item -# - -proc listview_remove_row*(listview: ptr Listview, item: ptr ListItem){. - cdecl, importc: "listview_remove_row", dynlib: clarodll.} -#* -# \brief Returns the currently selected ListView item -# -# \param obj A valid ListView widget object. -# \return The currently selected ListView item, or NULL if no item is selected. -# - -proc listview_get_selected*(obj: ptr Listview): ptr ListItem{.cdecl, - importc: "listview_get_selected", dynlib: clarodll.} -#* -# \brief Returns the number of rows in a ListView widget -# -# \param obj A valid ListView widget object. -# \return Number of rows -# - -proc listview_get_rows*(obj: ptr Listview): cint{.cdecl, - importc: "listview_get_rows", dynlib: clarodll.} -#* -# \brief Selects a row in a ListView widget -# -# \param obj A valid ListView widget object. -# \param item A valid list item -# - -proc listview_select_item*(obj: ptr Listview, item: ptr ListItem){.cdecl, - importc: "listview_select_item", dynlib: clarodll.} - -const - cMenuPopupAtCursor* = 1 - -type - Menu* {.pure.} = object of ListWidget -{.deprecated: [TMenu: Menu].} - -#* -# \brief Creates a Menu widget -# -# \param parent The parent widget of this widget, NOT NULL. -# \param flags Widget flags. -# \return A new Menu widget object. -# - -proc newmenu*(parent: ptr ClaroObj, flags: cint): ptr Menu {.cdecl, - importc: "menu_widget_create", dynlib: clarodll.} -#* -# \brief Append a row to a Menu widget -# -# \param menu A valid Menu widget object. -# \param parent The item to place the new item under, or NULL for a root item. -# \param image An image object, or NULL. -# \param title A string title, or NULL. -# \return A new list item. -# - -proc menu_append_item*(menu: ptr Menu, parent: ptr ListItem, - image: ptr Image, title: cstring): ptr ListItem{. - cdecl, importc: "menu_append_item", dynlib: clarodll.} -#* -# \brief Insert a row into a Menu widget -# -# \param menu A valid Menu widget object. -# \param parent The item to place the new item under, or NULL for a root item. -# \param pos The position at which to insert this item -# \param image An image object, or NULL. -# \param title A string title, or NULL. -# \return A new list item. -# - -proc menu_insert_item*(menu: ptr Menu, parent: ptr ListItem, pos: cint, - image: ptr Image, title: cstring): ptr ListItem{. - cdecl, importc: "menu_insert_item", dynlib: clarodll.} -#* -# \brief Append a separator to a Menu widget -# -# \param menu A valid Menu widget object. -# \param parent The item to place the new item under, or NULL for a root item. -# \return A new list item. -# - -proc menu_append_separator*(menu: ptr Menu, - parent: ptr ListItem): ptr ListItem{. - cdecl, importc: "menu_append_separator", dynlib: clarodll.} -#* -# \brief Insert a separator into a Menu widget -# -# \param menu A valid Menu widget object. -# \param parent The item to place the new item under, or NULL for a root item. -# \param pos The position at which to insert this item -# \return A new list item. -# - -proc menu_insert_separator*(menu: ptr Menu, parent: ptr ListItem, - pos: cint): ptr ListItem{.cdecl, - importc: "menu_insert_separator", dynlib: clarodll.} -#* -# \brief Move a row in a Menu widget -# -# \param menu A valid Menu widget object. -# \param item A valid list item -# \param row New position to place this item -# - -proc menu_move_item*(menu: ptr Menu, item: ptr ListItem, row: cint){. - cdecl, importc: "menu_move_item", dynlib: clarodll.} -#* -# \brief Remove a row from a Menu widget -# -# \param menu A valid Menu widget object. -# \param item A valid list item -# - -proc menu_remove_item*(menu: ptr Menu, item: ptr ListItem){.cdecl, - importc: "menu_remove_item", dynlib: clarodll.} -#* -# \brief Returns the number of rows in a Menu widget -# -# \param obj A valid Menu widget object. -# \param parent Item whose children count to return, -# or NULL for root item count. -# \return Number of rows -# - -proc menu_item_count*(obj: ptr Menu, parent: ptr ListItem): cint{. - cdecl, importc: "menu_item_count", dynlib: clarodll.} -#* -# \brief Disables a menu item (no focus and greyed out) -# -# \param menu A valid Menu widget object. -# \param item A valid list item -# - -proc menu_disable_item*(menu: ptr Menu, item: ptr ListItem){.cdecl, - importc: "menu_disable_item", dynlib: clarodll.} -#* -# \brief Enables a menu item (allows focus and not greyed out) -# -# \param menu A valid Menu widget object. -# \param item A valid list item -# - -proc menu_enable_item*(menu: ptr Menu, item: ptr ListItem){.cdecl, - importc: "menu_enable_item", dynlib: clarodll.} -#* -# \brief Pops up the menu at the position specified -# -# \param menu A valid Menu widget object. -# \param x The X position -# \param y The Y position -# \param flags Flags -# - -proc menu_popup*(menu: ptr Menu, x: cint, y: cint, flags: cint){.cdecl, - importc: "menu_popup", dynlib: clarodll.} -# -# Menu modifiers -# - -const - cModifierShift* = 1 shl 0 - cModifierCommand* = 1 shl 1 - -type - Menubar* {.pure.} = object of ListWidget -{.deprecated: [TMenubar: Menubar].} -#* -# \brief Creates a MenuBar widget -# -# \param parent The parent widget of this widget, NOT NULL. -# \param flags Widget flags. -# \return A new MenuBar widget object. -# - -proc newmenubar*(parent: ptr ClaroObj, flags: cint): ptr Menubar {.cdecl, - importc: "menubar_widget_create", dynlib: clarodll.} -#* -# \brief Add a key binding to a menu items -# -# \param menubar A valid MenuBar widget object. -# \param item The item -# \param utf8_key The key to use, NOT NULL. -# \param modifier The modifier key, or 0. -# - -proc menubar_add_key_binding*(menubar: ptr Menubar, item: ptr ListItem, - utf8_key: cstring, modifier: cint){.cdecl, - importc: "menubar_add_key_binding", dynlib: clarodll.} -#* -# \brief Append a row to a MenuBar widget -# -# \param menubar A valid MenuBar widget object. -# \param parent The item to place the new item under, or NULL for a root item. -# \param image An image object, or NULL. -# \param title A string title, or NULL. -# \return A new list item. -# - -proc menubar_append_item*(menubar: ptr Menubar, parent: ptr ListItem, - image: ptr Image, title: cstring): ptr ListItem{. - cdecl, importc: "menubar_append_item", dynlib: clarodll.} -#* -# \brief Insert a row into a MenuBar widget -# -# \param menubar A valid MenuBar widget object. -# \param parent The item to place the new item under, or NULL for a root item. -# \param pos The position at which to insert this item -# \param image An image object, or NULL. -# \param title A string title, or NULL. -# \return A new list item. -# - -proc menubar_insert_item*(menubar: ptr Menubar, parent: ptr ListItem, - pos: cint, image: ptr Image, - title: cstring): ptr ListItem{. - cdecl, importc: "menubar_insert_item", dynlib: clarodll.} -#* -# \brief Append a separator to a MenuBar widget -# -# \param menubar A valid MenuBar widget object. -# \param parent The item to place the new item under, or NULL for a root item. -# \return A new list item. -# - -proc menubar_append_separator*(menubar: ptr Menubar, - parent: ptr ListItem): ptr ListItem{. - cdecl, importc: "menubar_append_separator", dynlib: clarodll.} -#* -# \brief Insert a separator into a MenuBar widget -# -# \param menubar A valid MenuBar widget object. -# \param parent The item to place the new item under, or NULL for a root item. -# \param pos The position at which to insert this item -# \return A new list item. -# - -proc menubar_insert_separator*(menubar: ptr Menubar, parent: ptr ListItem, - pos: cint): ptr ListItem{.cdecl, - importc: "menubar_insert_separator", dynlib: clarodll.} -#* -# \brief Move a row in a MenuBar widget -# -# \param menubar A valid MenuBar widget object. -# \param item A valid list item -# \param row New position to place this item -# - -proc menubar_move_item*(menubar: ptr Menubar, item: ptr ListItem, - row: cint){.cdecl, importc: "menubar_move_item", - dynlib: clarodll.} -#* -# \brief Remove a row from a MenuBar widget -# -# \param menubar A valid MenuBar widget object. -# \param item A valid list item -# - -proc menubar_remove_item*(menubar: ptr Menubar, item: ptr ListItem) {. - cdecl, importc: "menubar_remove_item", dynlib: clarodll.} -#* -# \brief Returns the number of rows in a MenuBar widget -# -# \param obj A valid MenuBar widget object. -# \param parent Item whose children count to return, or NULL for root -# item count. -# \return Number of rows -# - -proc menubar_item_count*(obj: ptr Menubar, parent: ptr ListItem): cint{. - cdecl, importc: "menubar_item_count", dynlib: clarodll.} -#* -# \brief Disables a menu item (no focus and greyed out) -# -# \param menubar A valid MenuBar widget object. -# \param item A valid list item -# - -proc menubar_disable_item*(menubar: ptr Menubar, item: ptr ListItem){. - cdecl, importc: "menubar_disable_item", dynlib: clarodll.} -#* -# \brief Enables a menu item (allows focus and not greyed out) -# -# \param menubar A valid MenuBar widget object. -# \param item A valid list item -# - -proc menubar_enable_item*(menubar: ptr Menubar, item: ptr ListItem){. - cdecl, importc: "menubar_enable_item", dynlib: clarodll.} - -type - Progress* {.pure.} = object of Widget - - CProgressStyle* = enum - cProgressLeftRight = 0x00000000, cProgressRightLeft = 0x00000001, - cProgressTopBottom = 0x00000002, cProgressBottomTop = 0x00000004 -{.deprecated: [TProgress: Progress, TcProgressStyle: CProgressStyle].} - -#* -# \brief Creates a Progress widget -# -# \param parent The parent widget of this widget, NOT NULL. -# \param bounds The initial bounds of this widget, or NO_BOUNDS. -# \param flags Widget flags. -# \return A new Progress widget object. -# - -proc newprogress*(parent: ptr ClaroObj, bounds: ptr Bounds, - flags: cint): ptr Progress {. - cdecl, importc: "progress_widget_create", dynlib: clarodll.} -#* -# \brief Sets the value of a progress widget -# -# \param progress A valid progress widget object -# \param percentage Progress value -# - -proc progress_set_level*(progress: ptr Progress, percentage: cdouble){.cdecl, - importc: "progress_set_level", dynlib: clarodll.} -#* -# \brief Sets the orientation of a progress widget -# -# \param progress A valid progress widget object -# \param flags One of the cProgressStyle values -# - -proc progress_set_orientation*(progress: ptr Progress, flags: cint){.cdecl, - importc: "progress_set_orientation", dynlib: clarodll.} - -type - RadioGroup* {.pure.} = object of ClaroObj - buttons*: List - selected*: ptr ClaroObj - ndata*: pointer - - RadioButton* {.pure.} = object of Widget - text*: array[0..256-1, char] - group*: ptr RadioGroup -{.deprecated: [TRadioGroup: RadioGroup, TRadioButton: RadioButton].} - -#* -# \brief Creates a Radio Group widget -# -# \param parent The parent widget of this widget, NOT NULL. -# \param flags Widget flags. -# \return A new Radio Group widget object. -# - -proc newRadiogroup*(parent: ptr ClaroObj, flags: cint): ptr RadioGroup {. - cdecl, importc: "radiogroup_create", dynlib: clarodll.} -#* -# \brief Creates a Radio Button widget -# -# \param parent The parent widget of this widget, NOT NULL. -# \param group A valid Radio Group widget object -# \param bounds The initial bounds of this widget, or NO_BOUNDS. -# \param label The label of the radio widget -# \param flags Widget flags. -# \return A new Radio Button widget object. -# - -proc newradiobutton*(parent: ptr ClaroObj, group: ptr RadioGroup, - bounds: ptr Bounds, label: cstring, - flags: cint): ptr RadioButton{. - cdecl, importc: "radiobutton_widget_create", dynlib: clarodll.} -#* -# \brief Set the label of a Radio Button -# -# \param obj A valid Radio Button widget -# \param label The new label for the Radio Button -# - -proc radiobutton_set_text*(obj: ptr RadioButton, label: cstring){.cdecl, - importc: "radiobutton_set_label", dynlib: clarodll.} -#* -# \brief Set the group of a Radio Button -# -# \param rbutton A valid Radio Button widget -# \param group A valid Radio Group widget object -# - -proc radiobutton_set_group*(rbutton: ptr RadioButton, group: ptr RadioGroup){. - cdecl, importc: "radiobutton_set_group", dynlib: clarodll.} - -const - CLARO_SCROLLBAR_MAXIMUM* = 256 - -type - Scrollbar* {.pure.} = object of Widget - min*: cint - max*: cint - pagesize*: cint -{.deprecated: [TScrollbar: Scrollbar].} - -const - cScrollbarHorizontal* = 0 - cScrollbarVertical* = 1 - -# functions -#* -# \brief Creates a ScrollBar widget -# -# \param parent The parent widget of this widget, NOT NULL. -# \param bounds The initial bounds of this widget, or NO_BOUNDS. -# \param flags Widget flags. -# \return A new ScrollBar widget object. -# - -proc newscrollbar*(parent: ptr ClaroObj, bounds: ptr Bounds, - flags: cint): ptr Scrollbar{. - cdecl, importc: "scrollbar_widget_create", dynlib: clarodll.} -#* -# \brief Returns the width that scrollbars should be on this platform -# -# \return Width of vertical scrollbars -# - -proc scrollbar_get_sys_width*(): cint{.cdecl, - importc: "scrollbar_get_sys_width", - dynlib: clarodll.} -#* -# \brief Sets the range of a ScrollBar widget -# -# \param w A valid ScrollBar widget object -# \param min The minimum value -# \param max The maximum value -# - -proc scrollbar_set_range*(w: ptr Scrollbar, min: cint, max: cint){.cdecl, - importc: "scrollbar_set_range", dynlib: clarodll.} -#* -# \brief Sets the position of a ScrollBar widget -# -# \param w A valid ScrollBar widget object -# \param pos The new position -# - -proc scrollbar_set_pos*(w: ptr Scrollbar, pos: cint){.cdecl, - importc: "scrollbar_set_pos", dynlib: clarodll.} -#* -# \brief Gets the position of a ScrollBar widget -# -# \param w A valid ScrollBar widget object -# \return The current position -# - -proc scrollbar_get_pos*(w: ptr Scrollbar): cint{.cdecl, - importc: "scrollbar_get_pos", dynlib: clarodll.} -#* -# \brief Sets the page size of a ScrollBar widget -# -# \param w A valid ScrollBar widget object -# \param pagesize The size of a page (the number of units visible at one time) -# - -proc scrollbar_set_pagesize*(w: ptr Scrollbar, pagesize: cint){.cdecl, - importc: "scrollbar_set_pagesize", dynlib: clarodll.} - -type - CSplitterChildren* = enum - cSplitterFirst = 0, cSplitterSecond = 1 - SplitterChild* {.pure.} = object - flex*: cint - size*: cint - w*: ptr Widget - - Splitter* {.pure.} = object of Widget - pair*: array[0..1, SplitterChild] -{.deprecated: [TcSplitterChildren: CSplitterChildren, TSplitter: Splitter, - TSplitterChild: SplitterChild].} - -const - cSplitterHorizontal* = 0 - cSplitterVertical* = 1 - -# functions -#* -# \brief Creates a Splitter widget -# -# \param parent The parent widget of this widget, NOT NULL. -# \param bounds The initial bounds of this widget, or NO_BOUNDS. -# \param flags Widget flags. -# \return A new Splitter widget object. -# - -proc newsplitter*(parent: ptr ClaroObj, bounds: ptr Bounds, - flags: cint): ptr Splitter{. - cdecl, importc: "splitter_widget_create", dynlib: clarodll.} -#* -# \brief Sets the sizing information of a child -# -# \param splitter A valid splitter widget object -# \param child The child number, either cSplitterFirst or cSplitterSecond. -# \param flex 1 if this child should receive extra space as the splitter -# expands, 0 if not -# \param size The size of this child -# - -proc splitter_set_info*(splitter: ptr Splitter, child: cint, flex: cint, - size: cint){.cdecl, importc: "splitter_set_info", - dynlib: clarodll.} - -type - Statusbar* {.pure.} = object of Widget - text*: array[0..256 - 1, char] -{.deprecated: [TStatusbar: Statusbar].} - - -#* -# \brief Creates a StatusBar widget -# -# \param parent The parent widget of this widget, NOT NULL. -# \param flags Widget flags. -# \return A new StatusBar widget object. -# - -proc newstatusbar*(parent: ptr ClaroObj, flags: cint): ptr Statusbar {.cdecl, - importc: "statusbar_widget_create", dynlib: clarodll.} -#* -# \brief Sets the text of a statusbar -# -# \param obj A valid StatusBar widget -# \param text The new text -# - -proc statusbar_set_text*(obj: ptr Statusbar, text: cstring){.cdecl, - importc: "statusbar_set_text", dynlib: clarodll.} -#* -# \brief obtains a stock image -# -# \param stock_id The string ID of the stock image, NOT NULL. -# \return The Image object. -# - -proc stock_get_image*(stock_id: cstring): ptr Image{.cdecl, - importc: "stock_get_image", dynlib: clarodll.} -#* -# \brief adds a stock id image -# -# \param stock_id The string ID of the stock image, NOT NULL. -# \param img The Image object to add. -# \return The Image object. -# - -proc stock_add_image*(stock_id: cstring, img: ptr Image){.cdecl, - importc: "stock_add_image", dynlib: clarodll.} - -const - CLARO_TEXTAREA_MAXIMUM = (1024 * 1024) - -type - TextArea* {.pure.} = object of Widget - text*: array[0..CLARO_TEXTAREA_MAXIMUM - 1, char] -{.deprecated: [TTextArea: TextArea].} - - -#* -# \brief Creates a TextArea widget -# -# \param parent The parent widget of this widget, NOT NULL. -# \param bounds The initial bounds of this widget, or NO_BOUNDS. -# \param flags Widget flags. -# \return A new TextArea widget object. -# - -proc newtextarea*(parent: ptr ClaroObj, bounds: ptr Bounds, - flags: cint): ptr TextArea{. - cdecl, importc: "textarea_widget_create", dynlib: clarodll.} -#* -# \brief Sets the text of a textarea -# -# \param obj A valid TextArea widget -# \param text The new text -# - -proc textarea_set_text*(obj: ptr TextArea, text: cstring){.cdecl, - importc: "textarea_set_text", dynlib: clarodll.} -#* -# \brief Retrieve the text of a textarea -# -# \param obj A valid TextArea widget -# \return Pointer to an internal reference of the text. Should not be changed. -# - -proc textarea_get_text*(obj: ptr TextArea): cstring{.cdecl, - importc: "textarea_get_text", dynlib: clarodll.} - -const - CLARO_TEXTBOX_MAXIMUM = 8192 - -type - TextBox* {.pure.} = object of Widget - text*: array[0..CLARO_TEXTBOX_MAXIMUM-1, char] -{.deprecated: [TTextBox: TextBox].} - -const - cTextBoxTypePassword* = 1 - -# functions -#* -# \brief Creates a TextBox widget -# -# \param parent The parent widget of this widget, NOT NULL. -# \param bounds The initial bounds of this widget, or NO_BOUNDS. -# \param flags Widget flags. -# \return A new TextBox widget object. -# - -proc newtextbox*(parent: ptr ClaroObj, bounds: ptr Bounds, - flags: cint): ptr TextBox{. - cdecl, importc: "textbox_widget_create", dynlib: clarodll.} -#* -# \brief Sets the text of a textbox -# -# \param obj A valid TextBox widget -# \param text The new text -# - -proc textbox_set_text*(obj: ptr TextBox, text: cstring){.cdecl, - importc: "textbox_set_text", dynlib: clarodll.} -#* -# \brief Retrieve the text of a textbox -# -# \param obj A valid TextBox widget -# \return Pointer to an internal reference of the text. Should not be changed. -# - -proc textbox_get_text*(obj: ptr TextBox): cstring{.cdecl, - importc: "textbox_get_text", dynlib: clarodll.} -#* -# \brief Retrieve the cursor position inside a textbox -# -# \param obj A valid TextBox widget -# \return Cursor position inside TextBox -# - -proc textbox_get_pos*(obj: ptr TextBox): cint{.cdecl, - importc: "textbox_get_pos", dynlib: clarodll.} -#* -# \brief Sets the cursor position inside a textbox -# -# \param obj A valid TextBox widget -# \param pos New cursor position inside TextBox -# - -proc textbox_set_pos*(obj: ptr TextBox, pos: cint){.cdecl, - importc: "textbox_set_pos", dynlib: clarodll.} - -const - cToolbarShowText* = 1 - cToolbarShowImages* = 2 - cToolbarShowBoth* = 3 - cToolbarAutoSizeButtons* = 4 - -type - Toolbar* {.pure.} = object of ListWidget -{.deprecated: [TToolbar: Toolbar].} -#* -# \brief Creates a ToolBar widget -# -# \param parent The parent widget of this widget, NOT NULL. -# \param flags Widget flags. -# \return A new ToolBar widget object. -# - -proc newtoolbar*(parent: ptr ClaroObj, flags: cint): ptr Toolbar{.cdecl, - importc: "toolbar_widget_create", dynlib: clarodll.} -#* -# \brief Append a row to a ToolBar widget -# -# \param toolbar A valid ToolBar widget object. -# \param image An image object, or NULL. -# \param title A string title, or NULL. -# \param tooltip A string tooltip, or NULL. -# \return A new list item. -# - -proc toolbar_append_icon*(toolbar: ptr Toolbar, image: ptr Image, - title: cstring, tooltip: cstring): ptr ListItem{. - cdecl, importc: "toolbar_append_icon", dynlib: clarodll.} -#* -# \brief Insert a row into a ToolBar widget -# -# \param toolbar A valid ToolBar widget object. -# \param pos The position at which to insert this item -# \param image An image object, or NULL. -# \param title A string title, or NULL. -# \param tooltip A string tooltip, or NULL. -# \return A new list item. -# - -proc toolbar_insert_icon*(toolbar: ptr Toolbar, pos: cint, - image: ptr Image, title: cstring, - tooltip: cstring): ptr ListItem{. - cdecl, importc: "toolbar_insert_icon", dynlib: clarodll.} -#* -# \brief Append a separator to a ToolBar widget -# -# \param toolbar A valid ToolBar widget object. -# \return A new list item. -# - -proc toolbar_append_separator*(toolbar: ptr Toolbar): ptr ListItem{.cdecl, - importc: "toolbar_append_separator", dynlib: clarodll.} -#* -# \brief Insert a separator into a ToolBar widget -# -# \param toolbar A valid ToolBar widget object. -# \param pos The position at which to insert this item -# \return A new list item. -# - -proc toolbar_insert_separator*(toolbar: ptr Toolbar, - pos: cint): ptr ListItem {. - cdecl, importc: "toolbar_insert_separator", dynlib: clarodll.} -#* -# \brief Assign a menu widget to an item. -# -# This will show a small down arrow next to the item -# that will open this menu. -# -# \param toolbar A valid ToolBar widget object. -# \param item Toolbar item the menu is for. -# \param menu Menu widget object, or NULL to remove a menu. -# - -proc toolbar_set_item_menu*(toolbar: ptr Toolbar, item: ptr ListItem, - menu: ptr Menu){.cdecl, - importc: "toolbar_set_item_menu", dynlib: clarodll.} -#* -# \brief Move a row in a ToolBar widget -# -# \param toolbar A valid ToolBar widget object. -# \param item A valid list item -# \param row New position to place this item -# - -proc toolbar_move_icon*(toolbar: ptr Toolbar, item: ptr ListItem, - row: cint){.cdecl, importc: "toolbar_move_icon", - dynlib: clarodll.} -#* -# \brief Remove a row from a ToolBar widget -# -# \param toolbar A valid ToolBar widget object. -# \param item A valid list item -# - -proc toolbar_remove_icon*(toolbar: ptr Toolbar, item: ptr ListItem){. - cdecl, importc: "toolbar_remove_icon", dynlib: clarodll.} -#* -# \brief Returns the number of rows in a ToolBar widget -# -# \param obj A valid ToolBar widget object. -# \return Number of rows -# - -proc toolbar_item_count*(obj: ptr Toolbar): cint{.cdecl, - importc: "toolbar_item_count", dynlib: clarodll.} -#* -# \brief TreeView widget -# - -type - Treeview* {.pure.} = object of ListWidget - selected*: ptr ListItem -{.deprecated: [TTreeview: Treeview].} - -# functions -#* -# \brief Creates a TreeView widget -# -# \param parent The parent widget of this widget, NOT NULL. -# \param bounds The initial bounds of this widget, or NO_BOUNDS. -# \param flags Widget flags. -# \return A new TreeView widget object. -# - -proc newtreeview*(parent: ptr ClaroObj, bounds: ptr Bounds, - flags: cint): ptr Treeview{. - cdecl, importc: "treeview_widget_create", dynlib: clarodll.} -#* -# \brief Append a row to a TreeView -# -# \param treeview A valid TreeView widget object. -# \param parent The item under which to place the new item, or NULL for a root node. -# \param image An image to go to the left of the item, or NULL for no image. -# \param title The text for the item. -# \return A new list item. -# - -proc treeview_append_row*(treeview: ptr Treeview, parent: ptr ListItem, - image: ptr Image, title: cstring): ptr ListItem{. - cdecl, importc: "treeview_append_row", dynlib: clarodll.} -#* -# \brief Insert a row at the specified position into a TreeView -# -# \param treeview A valid TreeView widget object. -# \param parent The item under which to place the new item, or NULL for a root node. -# \param pos The index at which this item will be placed. -# \param image An image to go to the left of the item, or NULL for no image. -# \param title The text for the item. -# \return A new list item. -# - -proc treeview_insert_row*(treeview: ptr Treeview, parent: ptr ListItem, - pos: cint, image: ptr Image, - title: cstring): ptr ListItem{. - cdecl, importc: "treeview_insert_row", dynlib: clarodll.} -#* -# \brief Move a row in a TreeView -# -# \param treeview A valid TreeView widget object. -# \param item A valid list item -# \param row New position to place this item -# - -proc treeview_move_row*(treeview: ptr Treeview, item: ptr ListItem, - row: cint){.cdecl, importc: "treeview_move_row", - dynlib: clarodll.} -#* -# \brief Remove a row from a TreeView -# -# \param treeview A valid TreeView widget object. -# \param item A valid list item -# - -proc treeview_remove_row*(treeview: ptr Treeview, item: ptr ListItem){. - cdecl, importc: "treeview_remove_row", dynlib: clarodll.} -#* -# \brief Expand a row in a TreeView -# -# \param treeview A valid TreeView widget object. -# \param item A valid list item -# - -proc treeview_expand*(treeview: ptr Treeview, item: ptr ListItem){.cdecl, - importc: "treeview_expand", dynlib: clarodll.} -#* -# \brief Collapse a row in a TreeView -# -# \param treeview A valid TreeView widget object. -# \param item A valid list item -# - -proc treeview_collapse*(treeview: ptr Treeview, item: ptr ListItem){.cdecl, - importc: "treeview_collapse", dynlib: clarodll.} -#* -# \brief Returns the currently selected TreeView item -# -# \param obj A valid TreeView widget object. -# \return The currently selected TreeView item, or NULL if no item is selected. -# - -proc treeview_get_selected*(obj: ptr Treeview): ptr ListItem{.cdecl, - importc: "treeview_get_selected", dynlib: clarodll.} -#* -# \brief Returns the number of rows in a TreeView -# -# \param obj A valid TreeView widget object. -# \param parent Return the number of children of this item, or the number of -# root items if NULL -# \return Number of rows -# - -proc treeview_get_rows*(obj: ptr Treeview, parent: ptr ListItem): cint{. - cdecl, importc: "treeview_get_rows", dynlib: clarodll.} -#* -# \brief Selects a row in a TreeView -# -# \param obj A valid TreeView widget object. -# \param item A valid list item -# - -proc treeview_select_item*(obj: ptr Treeview, item: ptr ListItem){.cdecl, - importc: "treeview_select_item", dynlib: clarodll.} - -const - cWindowModalDialog* = 1 - cWindowCenterParent* = 2 - cWindowNoResizing* = 4 - -type - Window* {.pure.} = object of Widget - title*: array[0..512 - 1, char] - icon*: ptr Image - menubar*: ptr Widget - workspace*: ptr Widget - exsp_tools*: cint - exsp_status*: cint - exsp_init*: cint -{.deprecated: [TWindow: Window].} - -const - cWindowFixedSize* = 1 - -# functions -#* -# \brief Creates a Window widget -# -# \param parent The parent widget of this widget, NOT NULL. -# \param bounds The initial bounds of this widget, or NO_BOUNDS. -# \param flags Widget flags. -# \return A new Window widget object. -# - -proc newwindow*(parent: ptr ClaroObj, bounds: ptr Bounds, - flags: cint): ptr Window {. - cdecl, importc: "window_widget_create", dynlib: clarodll.} -#* -# \brief Sets a Window's title -# -# \param w A valid Window widget object -# \param title The new title for the window -# - -proc window_set_title*(w: ptr Window, title: cstring){.cdecl, - importc: "window_set_title", dynlib: clarodll.} -#* -# \brief Makes a window visible -# -# \param w A valid Window widget object -# - -proc window_show*(w: ptr Window){.cdecl, importc: "window_show", - dynlib: clarodll.} -#* -# \brief Makes a window invisible -# -# \param w A valid Window widget object -# - -proc window_hide*(w: ptr Window){.cdecl, importc: "window_hide", - dynlib: clarodll.} -#* -# \brief Gives focus to a window -# -# \param w A valid Window widget object -# - -proc window_focus*(w: ptr Window){.cdecl, importc: "window_focus", - dynlib: clarodll.} -#* -# \brief Maximises a window -# -# \param w A valid Window widget object -# - -proc window_maximize*(w: ptr Window){.cdecl, importc: "window_maximise", - dynlib: clarodll.} -#* -# \brief Minimises a window -# -# \param w A valid Window widget object -# - -proc window_minimize*(w: ptr Window){.cdecl, importc: "window_minimise", - dynlib: clarodll.} -#* -# \brief Restores a window -# -# \param w A valid Window widget object -# - -proc window_restore*(w: ptr Window){.cdecl, importc: "window_restore", - dynlib: clarodll.} -#* -# \brief Sets a window's icon -# -# \param w A valid Window widget object -# \param icon A valid Image object -# - -proc window_set_icon*(w: ptr Window, icon: ptr Image){.cdecl, - importc: "window_set_icon", dynlib: clarodll.} - -const - cWorkspaceTileHorizontally* = 0 - cWorkspaceTileVertically* = 1 - -type - Workspace*{.pure.} = object of Widget - - WorkspaceWindow*{.pure.} = object of Widget - icon*: ptr Image - title*: array[0..512 - 1, char] - workspace*: ptr Workspace -{.deprecated: [TWorkspace: Workspace, TWorkspaceWindow: WorkspaceWindow].} - -# functions (workspace) -#* -# \brief Creates a Workspace widget -# -# \param parent The parent widget of this widget, NOT NULL. -# \param bounds The initial bounds of this widget, or NO_BOUNDS. -# \param flags Widget flags. -# \return A new Workspace widget object. -# - -proc newworkspace*(parent: ptr ClaroObj, bounds: ptr Bounds, - flags: cint): ptr Workspace{. - cdecl, importc: "workspace_widget_create", dynlib: clarodll.} -#* -# \brief Sets the active (visible) workspace child -# -# \param workspace A valid workspace widget -# \param child A valid workspace window widget -# - -proc workspace_set_active*(workspace: ptr Workspace, child: ptr ClaroObj){. - cdecl, importc: "workspace_set_active", dynlib: clarodll.} -#* -# \brief Returns the active (visible) workspace child -# -# \param workspace A valid workspace widget -# \return The active workspace window widget -# - -proc workspace_get_active*(workspace: ptr Workspace): ptr Workspace{.cdecl, - importc: "workspace_get_active", dynlib: clarodll.} -#* -# \brief Cascades all workspace windows -# -# \param workspace A valid workspace widget -# - -proc workspace_cascade*(workspace: ptr Workspace){.cdecl, - importc: "workspace_cascade", dynlib: clarodll.} -#* -# \brief Tiles all workspace windows -# -# \param workspace A valid workspace widget -# \param dir The direction to tile child widgets -# - -proc workspace_tile*(workspace: ptr Workspace, dir: cint){.cdecl, - importc: "workspace_tile", dynlib: clarodll.} -# functions (workspace_window) -#* -# \brief Creates a Workspace widget -# -# \param parent The parent widget of this widget, NOT NULL. -# \param bounds The initial bounds of this widget, or NO_BOUNDS. -# \param flags Widget flags. -# \return A new Workspace widget object. -# - -proc newWorkspaceWindow*(parent: ptr ClaroObj, - bounds: ptr Bounds, - flags: cint): ptr WorkspaceWindow{. - cdecl, importc: "workspace_window_widget_create", dynlib: clarodll.} -#* -# \brief Sets the title of a Workspace Window widget -# -# \param window A valid Workspace Window widget -# \param title The new title for the widget -# - -proc workspace_window_set_title*(window: ptr WorkspaceWindow, - title: cstring){.cdecl, - importc: "workspace_window_set_title", dynlib: clarodll.} -#* -# \brief Makes a Workspace Window widget visible -# -# \param window A valid Workspace Window widget -# - -proc workspace_window_show*(window: ptr WorkspaceWindow){.cdecl, - importc: "workspace_window_show", dynlib: clarodll.} -#* -# \brief Makes a Workspace Window widget invisible -# -# \param window A valid Workspace Window widget -# - -proc workspace_window_hide*(window: ptr WorkspaceWindow){.cdecl, - importc: "workspace_window_hide", dynlib: clarodll.} -#* -# \brief Restores a Workspace Window widget -# -# \param window A valid Workspace Window widget -# - -proc workspace_window_restore*(window: ptr WorkspaceWindow){.cdecl, - importc: "workspace_window_restore", dynlib: clarodll.} -# American spelling - -#* -# \brief Minimises a Workspace Window widget -# -# \param window A valid Workspace Window widget -# - -proc workspace_window_minimize*(window: ptr WorkspaceWindow){.cdecl, - importc: "workspace_window_minimise", dynlib: clarodll.} -#* -# \brief Maxmimises a Workspace Window widget -# -# \param window A valid Workspace Window widget -# - -proc workspace_window_maximize*(window: ptr WorkspaceWindow){.cdecl, - importc: "workspace_window_maximise", dynlib: clarodll.} -#* -# \brief Sets the icon of a Workspace Window widget -# -# \param window A valid Workspace Window widget -# \param icon A valid Image object. -# - -proc workspace_window_set_icon*(w: ptr WorkspaceWindow, icon: ptr Image){. - cdecl, importc: "workspace_window_set_icon", dynlib: clarodll.} - -claro_base_init() -claro_graphics_init() - -when not defined(testing) and isMainModule: - var w = newWindow(nil, newBounds(100, 100, 230, 230), 0) - window_set_title(w, "Hello, World!") - - var t = newTextbox(w, new_bounds(10, 10, 210, -1), 0) - widget_set_notify(t, cNotifyKey) - textbox_set_text(t, "Yeehaw!") - - var b = newButton(w, new_bounds(40, 45, 150, -1), 0, "Push my button!") - - proc push_my_button(obj: ptr ClaroObj, event: ptr Event) {.cdecl.} = - textbox_set_text(t, "You pushed my button!") - var button = cast[ptr Button](obj) - button_set_text(button, "Ouch!") - - object_addhandler(b, "pushed", push_my_button) - - window_show(w) - window_focus(w) - - claro_loop() - diff --git a/lib/wrappers/expat.nim b/lib/wrappers/expat.nim deleted file mode 100644 index e1897e2b4..000000000 --- a/lib/wrappers/expat.nim +++ /dev/null @@ -1,899 +0,0 @@ -# Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd -# See the file COPYING for copying permission. -# - -when not defined(expatDll): - when defined(windows): - const - expatDll = "expat.dll" - elif defined(macosx): - const - expatDll = "libexpat.dylib" - else: - const - expatDll = "libexpat.so(.1|)" -type - ParserStruct{.pure, final.} = object - - PParser* = ptr ParserStruct - -# The XML_Status enum gives the possible return values for several -# API functions. The preprocessor #defines are included so this -# stanza can be added to code that still needs to support older -# versions of Expat 1.95.x: -# -# #ifndef XML_STATUS_OK -# #define XML_STATUS_OK 1 -# #define XML_STATUS_ERROR 0 -# #endif -# -# Otherwise, the #define hackery is quite ugly and would have been -# dropped. -# -{.deprecated: [TParserStruct: ParserStruct].} - -type - Status*{.size: sizeof(cint).} = enum - STATUS_ERROR = 0, STATUS_OK = 1, STATUS_SUSPENDED = 2 - Error*{.size: sizeof(cint).} = enum - ERROR_NONE, ERROR_NO_MEMORY, ERROR_SYNTAX, ERROR_NO_ELEMENTS, - ERROR_INVALID_TOKEN, ERROR_UNCLOSED_TOKEN, ERROR_PARTIAL_CHAR, - ERROR_TAG_MISMATCH, ERROR_DUPLICATE_ATTRIBUTE, - ERROR_JUNK_AFTER_DOC_ELEMENT, - ERROR_PARAM_ENTITY_REF, ERROR_UNDEFINED_ENTITY, ERROR_RECURSIVE_ENTITY_REF, - ERROR_ASYNC_ENTITY, ERROR_BAD_CHAR_REF, ERROR_BINARY_ENTITY_REF, - ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF, ERROR_MISPLACED_XML_PI, - ERROR_UNKNOWN_ENCODING, ERROR_INCORRECT_ENCODING, - ERROR_UNCLOSED_CDATA_SECTION, ERROR_EXTERNAL_ENTITY_HANDLING, - ERROR_NOT_STANDALONE, ERROR_UNEXPECTED_STATE, ERROR_ENTITY_DECLARED_IN_PE, - ERROR_FEATURE_REQUIRES_XML_DTD, ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING, - ERROR_UNBOUND_PREFIX, - ERROR_UNDECLARING_PREFIX, ERROR_INCOMPLETE_PE, ERROR_XML_DECL, - ERROR_TEXT_DECL, ERROR_PUBLICID, ERROR_SUSPENDED, ERROR_NOT_SUSPENDED, - ERROR_ABORTED, ERROR_FINISHED, ERROR_SUSPEND_PE, - ERROR_RESERVED_PREFIX_XML, ERROR_RESERVED_PREFIX_XMLNS, - ERROR_RESERVED_NAMESPACE_URI - ContentType*{.size: sizeof(cint).} = enum - CTYPE_EMPTY = 1, CTYPE_ANY, CTYPE_MIXED, CTYPE_NAME, CTYPE_CHOICE, CTYPE_SEQ - ContentQuant*{.size: sizeof(cint).} = enum - CQUANT_NONE, CQUANT_OPT, CQUANT_REP, CQUANT_PLUS -{.deprecated: [TStatus: Status, TError: Error, TContent_Type: ContentType, - TContent_Quant: ContentQuant].} - -# If type == XML_CTYPE_EMPTY or XML_CTYPE_ANY, then quant will be -# XML_CQUANT_NONE, and the other fields will be zero or NULL. -# If type == XML_CTYPE_MIXED, then quant will be NONE or REP and -# numchildren will contain number of elements that may be mixed in -# and children point to an array of XML_Content cells that will be -# all of XML_CTYPE_NAME type with no quantification. -# -# If type == XML_CTYPE_NAME, then the name points to the name, and -# the numchildren field will be zero and children will be NULL. The -# quant fields indicates any quantifiers placed on the name. -# -# CHOICE and SEQ will have name NULL, the number of children in -# numchildren and children will point, recursively, to an array -# of XML_Content cells. -# -# The EMPTY, ANY, and MIXED types will only occur at top level. -# - -type - Content*{.pure, final.} = object - typ*: ContentType - quant*: ContentQuant - name*: cstring - numchildren*: cint - children*: ptr Content -{.deprecated: [TContent: Content].} - -# This is called for an element declaration. See above for -# description of the model argument. It's the caller's responsibility -# to free model when finished with it. -# - -type - ElementDeclHandler* = proc (userData: pointer, name: cstring, - model: ptr Content){.cdecl.} -{.deprecated: [TElementDeclHandler: ElementDeclHandler].} - -proc setElementDeclHandler*(parser: PParser, eldecl: ElementDeclHandler){. - cdecl, importc: "XML_SetElementDeclHandler", dynlib: expatDll.} -# The Attlist declaration handler is called for *each* attribute. So -# a single Attlist declaration with multiple attributes declared will -# generate multiple calls to this handler. The "default" parameter -# may be NULL in the case of the "#IMPLIED" or "#REQUIRED" -# keyword. The "isrequired" parameter will be true and the default -# value will be NULL in the case of "#REQUIRED". If "isrequired" is -# true and default is non-NULL, then this is a "#FIXED" default. -# - -type - AttlistDeclHandler* = proc (userData: pointer, elname: cstring, - attname: cstring, attType: cstring, - dflt: cstring, isrequired: cint){.cdecl.} -{.deprecated: [TAttlistDeclHandler: AttlistDeclHandler].} - -proc setAttlistDeclHandler*(parser: PParser, attdecl: AttlistDeclHandler){. - cdecl, importc: "XML_SetAttlistDeclHandler", dynlib: expatDll.} -# The XML declaration handler is called for *both* XML declarations -# and text declarations. The way to distinguish is that the version -# parameter will be NULL for text declarations. The encoding -# parameter may be NULL for XML declarations. The standalone -# parameter will be -1, 0, or 1 indicating respectively that there -# was no standalone parameter in the declaration, that it was given -# as no, or that it was given as yes. -# - -type - XmlDeclHandler* = proc (userData: pointer, version: cstring, - encoding: cstring, standalone: cint){.cdecl.} -{.deprecated: [TXmlDeclHandler: XmlDeclHandler].} - -proc setXmlDeclHandler*(parser: PParser, xmldecl: XmlDeclHandler){.cdecl, - importc: "XML_SetXmlDeclHandler", dynlib: expatDll.} -type - Memory_Handling_Suite*{.pure, final.} = object - mallocFcn*: proc (size: int): pointer{.cdecl.} - reallocFcn*: proc (p: pointer, size: int): pointer{.cdecl.} - freeFcn*: proc (p: pointer){.cdecl.} -{.deprecated: [TMemory_Handling_Suite: MemoryHandlingSuite].} - -# Constructs a new parser; encoding is the encoding specified by the -# external protocol or NULL if there is none specified. -# - -proc parserCreate*(encoding: cstring): PParser{.cdecl, - importc: "XML_ParserCreate", dynlib: expatDll.} -# Constructs a new parser and namespace processor. Element type -# names and attribute names that belong to a namespace will be -# expanded; unprefixed attribute names are never expanded; unprefixed -# element type names are expanded only if there is a default -# namespace. The expanded name is the concatenation of the namespace -# URI, the namespace separator character, and the local part of the -# name. If the namespace separator is '\0' then the namespace URI -# and the local part will be concatenated without any separator. -# It is a programming error to use the separator '\0' with namespace -# triplets (see XML_SetReturnNSTriplet). -# - -proc parserCreateNS*(encoding: cstring, namespaceSeparator: char): PParser{. - cdecl, importc: "XML_ParserCreateNS", dynlib: expatDll.} -# Constructs a new parser using the memory management suite referred to -# by memsuite. If memsuite is NULL, then use the standard library memory -# suite. If namespaceSeparator is non-NULL it creates a parser with -# namespace processing as described above. The character pointed at -# will serve as the namespace separator. -# -# All further memory operations used for the created parser will come from -# the given suite. -# - -proc parserCreateMM*(encoding: cstring, memsuite: ptr TMemoryHandlingSuite, - namespaceSeparator: cstring): PParser{.cdecl, - importc: "XML_ParserCreate_MM", dynlib: expatDll.} -# Prepare a parser object to be re-used. This is particularly -# valuable when memory allocation overhead is disproportionatly high, -# such as when a large number of small documnents need to be parsed. -# All handlers are cleared from the parser, except for the -# unknownEncodingHandler. The parser's external state is re-initialized -# except for the values of ns and ns_triplets. -# -# Added in Expat 1.95.3. -# - -proc parserReset*(parser: PParser, encoding: cstring): bool{.cdecl, - importc: "XML_ParserReset", dynlib: expatDll.} -# atts is array of name/value pairs, terminated by 0; -# names and values are 0 terminated. -# - -type - StartElementHandler* = proc (userData: pointer, name: cstring, - atts: cstringArray){.cdecl.} - EndElementHandler* = proc (userData: pointer, name: cstring){.cdecl.} -{.deprecated: [TStartElementHandler: StartElementHandler, - TEndElementHandler: EndElementHandler].} -# s is not 0 terminated. - -type - CharacterDataHandler* = proc (userData: pointer, s: cstring, len: cint){. - cdecl.} -{.deprecated: [TCharacterDataHandler: CharacterDataHandler].} -# target and data are 0 terminated - -type - ProcessingInstructionHandler* = proc (userData: pointer, target: cstring, - data: cstring){.cdecl.} -{.deprecated: [TProcessingInstructionHandler: ProcessingInstructionHandler].} - -# data is 0 terminated - -type - CommentHandler* = proc (userData: pointer, data: cstring){.cdecl.} - StartCdataSectionHandler* = proc (userData: pointer){.cdecl.} - EndCdataSectionHandler* = proc (userData: pointer){.cdecl.} -{.deprecated: [TCommentHandler: CommentHandler, - TStartCdataSectionHandler: StartCdataSectionHandler, - TEndCdataSectionHandler: EndCdataSectionHandler].} -# This is called for any characters in the XML document for which -# there is no applicable handler. This includes both characters that -# are part of markup which is of a kind that is not reported -# (comments, markup declarations), or characters that are part of a -# construct which could be reported but for which no handler has been -# supplied. The characters are passed exactly as they were in the XML -# document except that they will be encoded in UTF-8 or UTF-16. -# Line boundaries are not normalized. Note that a byte order mark -# character is not passed to the default handler. There are no -# guarantees about how characters are divided between calls to the -# default handler: for example, a comment might be split between -# multiple calls. -# - -type - DefaultHandler* = proc (userData: pointer, s: cstring, len: cint){.cdecl.} -{.deprecated: [TDefaultHandler: DefaultHandler].} -# This is called for the start of the DOCTYPE declaration, before -# any DTD or internal subset is parsed. -# - -type - StartDoctypeDeclHandler* = proc (userData: pointer, doctypeName: cstring, - sysid: cstring, pubid: cstring, - hasInternalSubset: cint){.cdecl.} -{.deprecated: [TStartDoctypeDeclHandler: StartDoctypeDeclHandler].} - -# This is called for the start of the DOCTYPE declaration when the -# closing > is encountered, but after processing any external -# subset. -# - -type - EndDoctypeDeclHandler* = proc (userData: pointer){.cdecl.} -{.deprecated: [TEndDoctypeDeclHandler: EndDoctypeDeclHandler].} - -# This is called for entity declarations. The is_parameter_entity -# argument will be non-zero if the entity is a parameter entity, zero -# otherwise. -# -# For internal entities (), value will -# be non-NULL and systemId, publicID, and notationName will be NULL. -# The value string is NOT nul-terminated; the length is provided in -# the value_length argument. Since it is legal to have zero-length -# values, do not use this argument to test for internal entities. -# -# For external entities, value will be NULL and systemId will be -# non-NULL. The publicId argument will be NULL unless a public -# identifier was provided. The notationName argument will have a -# non-NULL value only for unparsed entity declarations. -# -# Note that is_parameter_entity can't be changed to XML_Bool, since -# that would break binary compatibility. -# - -type - EntityDeclHandler* = proc (userData: pointer, entityName: cstring, - isParameterEntity: cint, value: cstring, - valueLength: cint, base: cstring, - systemId: cstring, publicId: cstring, - notationName: cstring){.cdecl.} -{.deprecated: [TEntityDeclHandler: EntityDeclHandler].} - -proc setEntityDeclHandler*(parser: PParser, handler: EntityDeclHandler){.cdecl, - importc: "XML_SetEntityDeclHandler", dynlib: expatDll.} -# OBSOLETE -- OBSOLETE -- OBSOLETE -# This handler has been superceded by the EntityDeclHandler above. -# It is provided here for backward compatibility. -# -# This is called for a declaration of an unparsed (NDATA) entity. -# The base argument is whatever was set by XML_SetBase. The -# entityName, systemId and notationName arguments will never be -# NULL. The other arguments may be. -# - -type - UnparsedEntityDeclHandler* = proc (userData: pointer, entityName: cstring, - base: cstring, systemId: cstring, - publicId, notationName: cstring){. - cdecl.} -{.deprecated: [TUnparsedEntityDeclHandler: UnparsedEntityDeclHandler].} - -# This is called for a declaration of notation. The base argument is -# whatever was set by XML_SetBase. The notationName will never be -# NULL. The other arguments can be. -# - -type - NotationDeclHandler* = proc (userData: pointer, notationName: cstring, - base: cstring, systemId: cstring, - publicId: cstring){.cdecl.} -{.deprecated: [TNotationDeclHandler: NotationDeclHandler].} - -# When namespace processing is enabled, these are called once for -# each namespace declaration. The call to the start and end element -# handlers occur between the calls to the start and end namespace -# declaration handlers. For an xmlns attribute, prefix will be -# NULL. For an xmlns="" attribute, uri will be NULL. -# - -type - StartNamespaceDeclHandler* = proc (userData: pointer, prefix: cstring, - uri: cstring){.cdecl.} - EndNamespaceDeclHandler* = proc (userData: pointer, prefix: cstring){.cdecl.} -{.deprecated: [TStartNamespaceDeclHandler: StartNamespaceDeclHandler, - TEndNamespaceDeclHandler: EndNamespaceDeclHandler].} -# This is called if the document is not standalone, that is, it has an -# external subset or a reference to a parameter entity, but does not -# have standalone="yes". If this handler returns XML_STATUS_ERROR, -# then processing will not continue, and the parser will return a -# XML_ERROR_NOT_STANDALONE error. -# If parameter entity parsing is enabled, then in addition to the -# conditions above this handler will only be called if the referenced -# entity was actually read. -# - -type - NotStandaloneHandler* = proc (userData: pointer): cint{.cdecl.} -{.deprecated: [TNotStandaloneHandler: NotStandaloneHandler].} - -# This is called for a reference to an external parsed general -# entity. The referenced entity is not automatically parsed. The -# application can parse it immediately or later using -# XML_ExternalEntityParserCreate. -# -# The parser argument is the parser parsing the entity containing the -# reference; it can be passed as the parser argument to -# XML_ExternalEntityParserCreate. The systemId argument is the -# system identifier as specified in the entity declaration; it will -# not be NULL. -# -# The base argument is the system identifier that should be used as -# the base for resolving systemId if systemId was relative; this is -# set by XML_SetBase; it may be NULL. -# -# The publicId argument is the public identifier as specified in the -# entity declaration, or NULL if none was specified; the whitespace -# in the public identifier will have been normalized as required by -# the XML spec. -# -# The context argument specifies the parsing context in the format -# expected by the context argument to XML_ExternalEntityParserCreate; -# context is valid only until the handler returns, so if the -# referenced entity is to be parsed later, it must be copied. -# context is NULL only when the entity is a parameter entity. -# -# The handler should return XML_STATUS_ERROR if processing should not -# continue because of a fatal error in the handling of the external -# entity. In this case the calling parser will return an -# XML_ERROR_EXTERNAL_ENTITY_HANDLING error. -# -# Note that unlike other handlers the first argument is the parser, -# not userData. -# - -type - ExternalEntityRefHandler* = proc (parser: PParser, context: cstring, - base: cstring, systemId: cstring, - publicId: cstring): cint{.cdecl.} -{.deprecated: [TExternalEntityRefHandler: ExternalEntityRefHandler].} -# This is called in two situations: -# 1) An entity reference is encountered for which no declaration -# has been read *and* this is not an error. -# 2) An internal entity reference is read, but not expanded, because -# XML_SetDefaultHandler has been called. -# Note: skipped parameter entities in declarations and skipped general -# entities in attribute values cannot be reported, because -# the event would be out of sync with the reporting of the -# declarations or attribute values -# - -type - SkippedEntityHandler* = proc (userData: pointer, entityName: cstring, - isParameterEntity: cint){.cdecl.} -{.deprecated: [TSkippedEntityHandler: SkippedEntityHandler].} - -# This structure is filled in by the XML_UnknownEncodingHandler to -# provide information to the parser about encodings that are unknown -# to the parser. -# -# The map[b] member gives information about byte sequences whose -# first byte is b. -# -# If map[b] is c where c is >= 0, then b by itself encodes the -# Unicode scalar value c. -# -# If map[b] is -1, then the byte sequence is malformed. -# -# If map[b] is -n, where n >= 2, then b is the first byte of an -# n-byte sequence that encodes a single Unicode scalar value. -# -# The data member will be passed as the first argument to the convert -# function. -# -# The convert function is used to convert multibyte sequences; s will -# point to a n-byte sequence where map[(unsigned char)*s] == -n. The -# convert function must return the Unicode scalar value represented -# by this byte sequence or -1 if the byte sequence is malformed. -# -# The convert function may be NULL if the encoding is a single-byte -# encoding, that is if map[b] >= -1 for all bytes b. -# -# When the parser is finished with the encoding, then if release is -# not NULL, it will call release passing it the data member; once -# release has been called, the convert function will not be called -# again. -# -# Expat places certain restrictions on the encodings that are supported -# using this mechanism. -# -# 1. Every ASCII character that can appear in a well-formed XML document, -# other than the characters -# -# $@\^`{}~ -# -# must be represented by a single byte, and that byte must be the -# same byte that represents that character in ASCII. -# -# 2. No character may require more than 4 bytes to encode. -# -# 3. All characters encoded must have Unicode scalar values <= -# 0xFFFF, (i.e., characters that would be encoded by surrogates in -# UTF-16 are not allowed). Note that this restriction doesn't -# apply to the built-in support for UTF-8 and UTF-16. -# -# 4. No Unicode character may be encoded by more than one distinct -# sequence of bytes. -# - -type - Encoding*{.pure, final.} = object - map*: array[0..256 - 1, cint] - data*: pointer - convert*: proc (data: pointer, s: cstring): cint{.cdecl.} - release*: proc (data: pointer){.cdecl.} -{.deprecated: [TEncoding: Encoding].} - - -# This is called for an encoding that is unknown to the parser. -# -# The encodingHandlerData argument is that which was passed as the -# second argument to XML_SetUnknownEncodingHandler. -# -# The name argument gives the name of the encoding as specified in -# the encoding declaration. -# -# If the callback can provide information about the encoding, it must -# fill in the XML_Encoding structure, and return XML_STATUS_OK. -# Otherwise it must return XML_STATUS_ERROR. -# -# If info does not describe a suitable encoding, then the parser will -# return an XML_UNKNOWN_ENCODING error. -# - -type - UnknownEncodingHandler* = proc (encodingHandlerData: pointer, name: cstring, - info: ptr Encoding): cint{.cdecl.} -{.deprecated: [TUnknownEncodingHandler: UnknownEncodingHandler].} - -proc setElementHandler*(parser: PParser, start: StartElementHandler, - endHandler: EndElementHandler){.cdecl, - importc: "XML_SetElementHandler", dynlib: expatDll.} -proc setStartElementHandler*(parser: PParser, handler: StartElementHandler){. - cdecl, importc: "XML_SetStartElementHandler", dynlib: expatDll.} -proc setEndElementHandler*(parser: PParser, handler: EndElementHandler){.cdecl, - importc: "XML_SetEndElementHandler", dynlib: expatDll.} -proc setCharacterDataHandler*(parser: PParser, handler: CharacterDataHandler){. - cdecl, importc: "XML_SetCharacterDataHandler", dynlib: expatDll.} -proc setProcessingInstructionHandler*(parser: PParser, - handler: ProcessingInstructionHandler){. - cdecl, importc: "XML_SetProcessingInstructionHandler", dynlib: expatDll.} -proc setCommentHandler*(parser: PParser, handler: CommentHandler){.cdecl, - importc: "XML_SetCommentHandler", dynlib: expatDll.} -proc setCdataSectionHandler*(parser: PParser, start: StartCdataSectionHandler, - endHandler: EndCdataSectionHandler){.cdecl, - importc: "XML_SetCdataSectionHandler", dynlib: expatDll.} -proc setStartCdataSectionHandler*(parser: PParser, - start: StartCdataSectionHandler){.cdecl, - importc: "XML_SetStartCdataSectionHandler", dynlib: expatDll.} -proc setEndCdataSectionHandler*(parser: PParser, - endHandler: EndCdataSectionHandler){.cdecl, - importc: "XML_SetEndCdataSectionHandler", dynlib: expatDll.} -# This sets the default handler and also inhibits expansion of -# internal entities. These entity references will be passed to the -# default handler, or to the skipped entity handler, if one is set. -# - -proc setDefaultHandler*(parser: PParser, handler: DefaultHandler){.cdecl, - importc: "XML_SetDefaultHandler", dynlib: expatDll.} -# This sets the default handler but does not inhibit expansion of -# internal entities. The entity reference will not be passed to the -# default handler. -# - -proc setDefaultHandlerExpand*(parser: PParser, handler: DefaultHandler){.cdecl, - importc: "XML_SetDefaultHandlerExpand", dynlib: expatDll.} -proc setDoctypeDeclHandler*(parser: PParser, start: StartDoctypeDeclHandler, - endHandler: EndDoctypeDeclHandler){.cdecl, - importc: "XML_SetDoctypeDeclHandler", dynlib: expatDll.} -proc setStartDoctypeDeclHandler*(parser: PParser, - start: StartDoctypeDeclHandler){.cdecl, - importc: "XML_SetStartDoctypeDeclHandler", dynlib: expatDll.} -proc setEndDoctypeDeclHandler*(parser: PParser, - endHandler: EndDoctypeDeclHandler){.cdecl, - importc: "XML_SetEndDoctypeDeclHandler", dynlib: expatDll.} -proc setUnparsedEntityDeclHandler*(parser: PParser, - handler: UnparsedEntityDeclHandler){.cdecl, - importc: "XML_SetUnparsedEntityDeclHandler", dynlib: expatDll.} -proc setNotationDeclHandler*(parser: PParser, handler: NotationDeclHandler){. - cdecl, importc: "XML_SetNotationDeclHandler", dynlib: expatDll.} -proc setNamespaceDeclHandler*(parser: PParser, - start: StartNamespaceDeclHandler, - endHandler: EndNamespaceDeclHandler){.cdecl, - importc: "XML_SetNamespaceDeclHandler", dynlib: expatDll.} -proc setStartNamespaceDeclHandler*(parser: PParser, - start: StartNamespaceDeclHandler){.cdecl, - importc: "XML_SetStartNamespaceDeclHandler", dynlib: expatDll.} -proc setEndNamespaceDeclHandler*(parser: PParser, - endHandler: EndNamespaceDeclHandler){.cdecl, - importc: "XML_SetEndNamespaceDeclHandler", dynlib: expatDll.} -proc setNotStandaloneHandler*(parser: PParser, handler: NotStandaloneHandler){. - cdecl, importc: "XML_SetNotStandaloneHandler", dynlib: expatDll.} -proc setExternalEntityRefHandler*(parser: PParser, - handler: ExternalEntityRefHandler){.cdecl, - importc: "XML_SetExternalEntityRefHandler", dynlib: expatDll.} -# If a non-NULL value for arg is specified here, then it will be -# passed as the first argument to the external entity ref handler -# instead of the parser object. -# - -proc setExternalEntityRefHandlerArg*(parser: PParser, arg: pointer){.cdecl, - importc: "XML_SetExternalEntityRefHandlerArg", dynlib: expatDll.} -proc setSkippedEntityHandler*(parser: PParser, handler: SkippedEntityHandler){. - cdecl, importc: "XML_SetSkippedEntityHandler", dynlib: expatDll.} -proc setUnknownEncodingHandler*(parser: PParser, - handler: UnknownEncodingHandler, - encodingHandlerData: pointer){.cdecl, - importc: "XML_SetUnknownEncodingHandler", dynlib: expatDll.} -# This can be called within a handler for a start element, end -# element, processing instruction or character data. It causes the -# corresponding markup to be passed to the default handler. -# - -proc defaultCurrent*(parser: PParser){.cdecl, importc: "XML_DefaultCurrent", - dynlib: expatDll.} -# If do_nst is non-zero, and namespace processing is in effect, and -# a name has a prefix (i.e. an explicit namespace qualifier) then -# that name is returned as a triplet in a single string separated by -# the separator character specified when the parser was created: URI -# + sep + local_name + sep + prefix. -# -# If do_nst is zero, then namespace information is returned in the -# default manner (URI + sep + local_name) whether or not the name -# has a prefix. -# -# Note: Calling XML_SetReturnNSTriplet after XML_Parse or -# XML_ParseBuffer has no effect. -# - -proc setReturnNSTriplet*(parser: PParser, doNst: cint){.cdecl, - importc: "XML_SetReturnNSTriplet", dynlib: expatDll.} -# This value is passed as the userData argument to callbacks. - -proc setUserData*(parser: PParser, userData: pointer){.cdecl, - importc: "XML_SetUserData", dynlib: expatDll.} -# Returns the last value set by XML_SetUserData or NULL. - -template getUserData*(parser: expr): expr = - (cast[ptr pointer]((parser))[] ) - -# This is equivalent to supplying an encoding argument to -# XML_ParserCreate. On success XML_SetEncoding returns non-zero, -# zero otherwise. -# Note: Calling XML_SetEncoding after XML_Parse or XML_ParseBuffer -# has no effect and returns XML_STATUS_ERROR. -# - -proc setEncoding*(parser: PParser, encoding: cstring): Status{.cdecl, - importc: "XML_SetEncoding", dynlib: expatDll.} -# If this function is called, then the parser will be passed as the -# first argument to callbacks instead of userData. The userData will -# still be accessible using XML_GetUserData. -# - -proc useParserAsHandlerArg*(parser: PParser){.cdecl, - importc: "XML_UseParserAsHandlerArg", dynlib: expatDll.} -# If useDTD == XML_TRUE is passed to this function, then the parser -# will assume that there is an external subset, even if none is -# specified in the document. In such a case the parser will call the -# externalEntityRefHandler with a value of NULL for the systemId -# argument (the publicId and context arguments will be NULL as well). -# Note: For the purpose of checking WFC: Entity Declared, passing -# useDTD == XML_TRUE will make the parser behave as if the document -# had a DTD with an external subset. -# Note: If this function is called, then this must be done before -# the first call to XML_Parse or XML_ParseBuffer, since it will -# have no effect after that. Returns -# XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING. -# Note: If the document does not have a DOCTYPE declaration at all, -# then startDoctypeDeclHandler and endDoctypeDeclHandler will not -# be called, despite an external subset being parsed. -# Note: If XML_DTD is not defined when Expat is compiled, returns -# XML_ERROR_FEATURE_REQUIRES_XML_DTD. -# - -proc useForeignDTD*(parser: PParser, useDTD: bool): Error{.cdecl, - importc: "XML_UseForeignDTD", dynlib: expatDll.} -# Sets the base to be used for resolving relative URIs in system -# identifiers in declarations. Resolving relative identifiers is -# left to the application: this value will be passed through as the -# base argument to the XML_ExternalEntityRefHandler, -# XML_NotationDeclHandler and XML_UnparsedEntityDeclHandler. The base -# argument will be copied. Returns XML_STATUS_ERROR if out of memory, -# XML_STATUS_OK otherwise. -# - -proc setBase*(parser: PParser, base: cstring): Status{.cdecl, - importc: "XML_SetBase", dynlib: expatDll.} -proc getBase*(parser: PParser): cstring{.cdecl, importc: "XML_GetBase", - dynlib: expatDll.} -# Returns the number of the attribute/value pairs passed in last call -# to the XML_StartElementHandler that were specified in the start-tag -# rather than defaulted. Each attribute/value pair counts as 2; thus -# this correspondds to an index into the atts array passed to the -# XML_StartElementHandler. -# - -proc getSpecifiedAttributeCount*(parser: PParser): cint{.cdecl, - importc: "XML_GetSpecifiedAttributeCount", dynlib: expatDll.} -# Returns the index of the ID attribute passed in the last call to -# XML_StartElementHandler, or -1 if there is no ID attribute. Each -# attribute/value pair counts as 2; thus this correspondds to an -# index into the atts array passed to the XML_StartElementHandler. -# - -proc getIdAttributeIndex*(parser: PParser): cint{.cdecl, - importc: "XML_GetIdAttributeIndex", dynlib: expatDll.} -# Parses some input. Returns XML_STATUS_ERROR if a fatal error is -# detected. The last call to XML_Parse must have isFinal true; len -# may be zero for this call (or any other). -# -# Though the return values for these functions has always been -# described as a Boolean value, the implementation, at least for the -# 1.95.x series, has always returned exactly one of the XML_Status -# values. -# - -proc parse*(parser: PParser, s: cstring, len: cint, isFinal: cint): Status{. - cdecl, importc: "XML_Parse", dynlib: expatDll.} -proc getBuffer*(parser: PParser, len: cint): pointer{.cdecl, - importc: "XML_GetBuffer", dynlib: expatDll.} -proc parseBuffer*(parser: PParser, len: cint, isFinal: cint): Status{.cdecl, - importc: "XML_ParseBuffer", dynlib: expatDll.} -# Stops parsing, causing XML_Parse() or XML_ParseBuffer() to return. -# Must be called from within a call-back handler, except when aborting -# (resumable = 0) an already suspended parser. Some call-backs may -# still follow because they would otherwise get lost. Examples: -# - endElementHandler() for empty elements when stopped in -# startElementHandler(), -# - endNameSpaceDeclHandler() when stopped in endElementHandler(), -# and possibly others. -# -# Can be called from most handlers, including DTD related call-backs, -# except when parsing an external parameter entity and resumable != 0. -# Returns XML_STATUS_OK when successful, XML_STATUS_ERROR otherwise. -# Possible error codes: -# - XML_ERROR_SUSPENDED: when suspending an already suspended parser. -# - XML_ERROR_FINISHED: when the parser has already finished. -# - XML_ERROR_SUSPEND_PE: when suspending while parsing an external PE. -# -# When resumable != 0 (true) then parsing is suspended, that is, -# XML_Parse() and XML_ParseBuffer() return XML_STATUS_SUSPENDED. -# Otherwise, parsing is aborted, that is, XML_Parse() and XML_ParseBuffer() -# return XML_STATUS_ERROR with error code XML_ERROR_ABORTED. -# -# Note*: -# This will be applied to the current parser instance only, that is, if -# there is a parent parser then it will continue parsing when the -# externalEntityRefHandler() returns. It is up to the implementation of -# the externalEntityRefHandler() to call XML_StopParser() on the parent -# parser (recursively), if one wants to stop parsing altogether. -# -# When suspended, parsing can be resumed by calling XML_ResumeParser(). -# - -proc stopParser*(parser: PParser, resumable: bool): Status{.cdecl, - importc: "XML_StopParser", dynlib: expatDll.} -# Resumes parsing after it has been suspended with XML_StopParser(). -# Must not be called from within a handler call-back. Returns same -# status codes as XML_Parse() or XML_ParseBuffer(). -# Additional error code XML_ERROR_NOT_SUSPENDED possible. -# -# Note*: -# This must be called on the most deeply nested child parser instance -# first, and on its parent parser only after the child parser has finished, -# to be applied recursively until the document entity's parser is restarted. -# That is, the parent parser will not resume by itself and it is up to the -# application to call XML_ResumeParser() on it at the appropriate moment. -# - -proc resumeParser*(parser: PParser): Status{.cdecl, - importc: "XML_ResumeParser", dynlib: expatDll.} -type - TParsing* = enum - INITIALIZED, PARSING, FINISHED, SUSPENDED - ParsingStatus*{.pure, final.} = object - parsing*: TParsing - finalBuffer*: bool -{.deprecated: [#TParsing: Parsing, # Naming conflict if we drop the `T` - TParsingStatus: ParsingStatus].} - -# Returns status of parser with respect to being initialized, parsing, -# finished, or suspended and processing the final buffer. -# XXX XML_Parse() and XML_ParseBuffer() should return XML_ParsingStatus, -# XXX with XML_FINISHED_OK or XML_FINISHED_ERROR replacing XML_FINISHED -# - -proc getParsingStatus*(parser: PParser, status: ptr ParsingStatus){.cdecl, - importc: "XML_GetParsingStatus", dynlib: expatDll.} -# Creates an XML_Parser object that can parse an external general -# entity; context is a '\0'-terminated string specifying the parse -# context; encoding is a '\0'-terminated string giving the name of -# the externally specified encoding, or NULL if there is no -# externally specified encoding. The context string consists of a -# sequence of tokens separated by formfeeds (\f); a token consisting -# of a name specifies that the general entity of the name is open; a -# token of the form prefix=uri specifies the namespace for a -# particular prefix; a token of the form =uri specifies the default -# namespace. This can be called at any point after the first call to -# an ExternalEntityRefHandler so longer as the parser has not yet -# been freed. The new parser is completely independent and may -# safely be used in a separate thread. The handlers and userData are -# initialized from the parser argument. Returns NULL if out of memory. -# Otherwise returns a new XML_Parser object. -# - -proc externalEntityParserCreate*(parser: PParser, context: cstring, - encoding: cstring): PParser{.cdecl, - importc: "XML_ExternalEntityParserCreate", dynlib: expatDll.} -type - ParamEntityParsing* = enum - PARAM_ENTITY_PARSING_NEVER, PARAM_ENTITY_PARSING_UNLESS_STANDALONE, - PARAM_ENTITY_PARSING_ALWAYS -{.deprecated: [TParamEntityParsing: ParamEntityParsing].} - -# Controls parsing of parameter entities (including the external DTD -# subset). If parsing of parameter entities is enabled, then -# references to external parameter entities (including the external -# DTD subset) will be passed to the handler set with -# XML_SetExternalEntityRefHandler. The context passed will be 0. -# -# Unlike external general entities, external parameter entities can -# only be parsed synchronously. If the external parameter entity is -# to be parsed, it must be parsed during the call to the external -# entity ref handler: the complete sequence of -# XML_ExternalEntityParserCreate, XML_Parse/XML_ParseBuffer and -# XML_ParserFree calls must be made during this call. After -# XML_ExternalEntityParserCreate has been called to create the parser -# for the external parameter entity (context must be 0 for this -# call), it is illegal to make any calls on the old parser until -# XML_ParserFree has been called on the newly created parser. -# If the library has been compiled without support for parameter -# entity parsing (ie without XML_DTD being defined), then -# XML_SetParamEntityParsing will return 0 if parsing of parameter -# entities is requested; otherwise it will return non-zero. -# Note: If XML_SetParamEntityParsing is called after XML_Parse or -# XML_ParseBuffer, then it has no effect and will always return 0. -# - -proc setParamEntityParsing*(parser: PParser, parsing: ParamEntityParsing): cint{. - cdecl, importc: "XML_SetParamEntityParsing", dynlib: expatDll.} -# If XML_Parse or XML_ParseBuffer have returned XML_STATUS_ERROR, then -# XML_GetErrorCode returns information about the error. -# - -proc getErrorCode*(parser: PParser): Error{.cdecl, importc: "XML_GetErrorCode", - dynlib: expatDll.} -# These functions return information about the current parse -# location. They may be called from any callback called to report -# some parse event; in this case the location is the location of the -# first of the sequence of characters that generated the event. When -# called from callbacks generated by declarations in the document -# prologue, the location identified isn't as neatly defined, but will -# be within the relevant markup. When called outside of the callback -# functions, the position indicated will be just past the last parse -# event (regardless of whether there was an associated callback). -# -# They may also be called after returning from a call to XML_Parse -# or XML_ParseBuffer. If the return value is XML_STATUS_ERROR then -# the location is the location of the character at which the error -# was detected; otherwise the location is the location of the last -# parse event, as described above. -# - -proc getCurrentLineNumber*(parser: PParser): int{.cdecl, - importc: "XML_GetCurrentLineNumber", dynlib: expatDll.} -proc getCurrentColumnNumber*(parser: PParser): int{.cdecl, - importc: "XML_GetCurrentColumnNumber", dynlib: expatDll.} -proc getCurrentByteIndex*(parser: PParser): int{.cdecl, - importc: "XML_GetCurrentByteIndex", dynlib: expatDll.} -# Return the number of bytes in the current event. -# Returns 0 if the event is in an internal entity. -# - -proc getCurrentByteCount*(parser: PParser): cint{.cdecl, - importc: "XML_GetCurrentByteCount", dynlib: expatDll.} -# If XML_CONTEXT_BYTES is defined, returns the input buffer, sets -# the integer pointed to by offset to the offset within this buffer -# of the current parse position, and sets the integer pointed to by size -# to the size of this buffer (the number of input bytes). Otherwise -# returns a NULL pointer. Also returns a NULL pointer if a parse isn't -# active. -# -# NOTE: The character pointer returned should not be used outside -# the handler that makes the call. -# - -proc getInputContext*(parser: PParser, offset: ptr cint, size: ptr cint): cstring{. - cdecl, importc: "XML_GetInputContext", dynlib: expatDll.} -# Frees the content model passed to the element declaration handler - -proc freeContentModel*(parser: PParser, model: ptr Content){.cdecl, - importc: "XML_FreeContentModel", dynlib: expatDll.} -# Exposing the memory handling functions used in Expat - -proc memMalloc*(parser: PParser, size: int): pointer{.cdecl, - importc: "XML_MemMalloc", dynlib: expatDll.} -proc memRealloc*(parser: PParser, p: pointer, size: int): pointer{.cdecl, - importc: "XML_MemRealloc", dynlib: expatDll.} -proc memFree*(parser: PParser, p: pointer){.cdecl, importc: "XML_MemFree", - dynlib: expatDll.} -# Frees memory used by the parser. - -proc parserFree*(parser: PParser){.cdecl, importc: "XML_ParserFree", - dynlib: expatDll.} -# Returns a string describing the error. - -proc errorString*(code: Error): cstring{.cdecl, importc: "XML_ErrorString", - dynlib: expatDll.} -# Return a string containing the version number of this expat - -proc expatVersion*(): cstring{.cdecl, importc: "XML_ExpatVersion", - dynlib: expatDll.} -type - Expat_Version*{.pure, final.} = object - major*: cint - minor*: cint - micro*: cint -{.deprecated: [TExpat_Version: ExpatVersion].} - -# Return an XML_Expat_Version structure containing numeric version -# number information for this version of expat. -# - -proc expatVersionInfo*(): ExpatVersion{.cdecl, - importc: "XML_ExpatVersionInfo", dynlib: expatDll.} -# Added in Expat 1.95.5. - -type - FeatureEnum* = enum - FEATURE_END = 0, FEATURE_UNICODE, FEATURE_UNICODE_WCHAR_T, FEATURE_DTD, - FEATURE_CONTEXT_BYTES, FEATURE_MIN_SIZE, FEATURE_SIZEOF_XML_CHAR, - FEATURE_SIZEOF_XML_LCHAR, FEATURE_NS, FEATURE_LARGE_SIZE # Additional features must be added to the end of this enum. - Feature*{.pure, final.} = object - feature*: FeatureEnum - name*: cstring - value*: int -{.deprecated: [TFeatureEnum: FeatureEnum, TFeature: Feature].} - -proc getFeatureList*(): ptr Feature{.cdecl, importc: "XML_GetFeatureList", - dynlib: expatDll.} -# Expat follows the GNU/Linux convention of odd number minor version for -# beta/development releases and even number minor version for stable -# releases. Micro is bumped with each release, and set to 0 with each -# change to major or minor version. -# - -const - MAJOR_VERSION* = 2 - MINOR_VERSION* = 0 - MICRO_VERSION* = 1 diff --git a/lib/wrappers/iup.nim b/lib/wrappers/iup.nim index 93e14cccd..cbd9b5ae9 100644 --- a/lib/wrappers/iup.nim +++ b/lib/wrappers/iup.nim @@ -1,6 +1,12 @@ # -# Binding for the IUP GUI toolkit -# (c) 2012 Andreas Rumpf +# +# Nim's Runtime Library +# (c) Copyright 2012 Andreas Rumpf +# +# See the file "copying.txt", included in this +# distribution, for details about the copyright. +# + # C header files translated by hand # Licence of IUP follows: diff --git a/lib/wrappers/joyent_http_parser.nim b/lib/wrappers/joyent_http_parser.nim index 2fed392b9..f7412d2b8 100644 --- a/lib/wrappers/joyent_http_parser.nim +++ b/lib/wrappers/joyent_http_parser.nim @@ -1,6 +1,15 @@ +# +# +# Nim's Runtime Library +# (c) Copyright 2015 Andreas Rumpf +# +# See the file "copying.txt", included in this +# distribution, for details about the copyright. +# + type csize = int - + HttpDataProc* = proc (a2: ptr HttpParser, at: cstring, length: csize): cint {.cdecl.} HttpProc* = proc (a2: ptr HttpParser): cint {.cdecl.} diff --git a/lib/wrappers/libcurl.nim b/lib/wrappers/libcurl.nim deleted file mode 100644 index 924879e75..000000000 --- a/lib/wrappers/libcurl.nim +++ /dev/null @@ -1,512 +0,0 @@ -# -# $Id: header,v 1.1 2000/07/13 06:33:45 michael Exp $ -# This file is part of the Free Pascal packages -# Copyright (c) 1999-2000 by the Free Pascal development team -# -# See the file COPYING.FPC, included in this distribution, -# for details about the copyright. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -# -# ********************************************************************** -# -# the curl library is governed by its own copyright, see the curl -# website for this. -# - -{.deadCodeElim: on.} - -import - times - -when defined(windows): - const - libname = "libcurl.dll" -elif defined(macosx): - const - libname = "libcurl-7.19.3.dylib" -elif defined(unix): - const - libname = "libcurl.so.4" -type - Pcalloc_callback* = ptr Calloc_callback - Pclosepolicy* = ptr Closepolicy - Pforms* = ptr Forms - Pftpauth* = ptr Ftpauth - Pftpmethod* = ptr Ftpmethod - Pftpssl* = ptr Ftpssl - PHTTP_VERSION* = ptr HTTP_VERSION - Phttppost* = ptr Httppost - PPcurl_httppost* = ptr Phttppost - Pinfotype* = ptr Infotype - Plock_access* = ptr Lock_access - Plock_data* = ptr Lock_data - Pmalloc_callback* = ptr Malloc_callback - PNETRC_OPTION* = ptr NETRC_OPTION - Pproxytype* = ptr Proxytype - Prealloc_callback* = ptr Realloc_callback - Pslist* = ptr Slist - Psocket* = ptr Socket - PSSL_VERSION* = ptr SSL_VERSION - Pstrdup_callback* = ptr Strdup_callback - PTIMECOND* = ptr TIMECOND - Pversion_info_data* = ptr Version_info_data - Pcode* = ptr Code - PFORMcode* = ptr FORMcode - Pformoption* = ptr Formoption - PINFO* = ptr INFO - Piocmd* = ptr Iocmd - Pioerr* = ptr Ioerr - PM* = ptr M - PMcode* = ptr Mcode - PMoption* = ptr Moption - PMSG* = ptr MSG - Poption* = ptr Option - PSH* = ptr SH - PSHcode* = ptr SHcode - PSHoption* = ptr SHoption - Pversion* = ptr Version - Pfd_set* = pointer - PCurl* = ptr Curl - Curl* = pointer - Httppost*{.final, pure.} = object - next*: Phttppost - name*: cstring - namelength*: int32 - contents*: cstring - contentslength*: int32 - buffer*: cstring - bufferlength*: int32 - contenttype*: cstring - contentheader*: Pslist - more*: Phttppost - flags*: int32 - showfilename*: cstring - - Progress_callback* = proc (clientp: pointer, dltotal: float64, - dlnow: float64, ultotal: float64, - ulnow: float64): int32 {.cdecl.} - Write_callback* = proc (buffer: cstring, size: int, nitems: int, - outstream: pointer): int{.cdecl.} - Read_callback* = proc (buffer: cstring, size: int, nitems: int, - instream: pointer): int{.cdecl.} - Passwd_callback* = proc (clientp: pointer, prompt: cstring, buffer: cstring, - buflen: int32): int32{.cdecl.} - Ioerr* = enum - IOE_OK, IOE_UNKNOWNCMD, IOE_FAILRESTART, IOE_LAST - Iocmd* = enum - IOCMD_NOP, IOCMD_RESTARTREAD, IOCMD_LAST - Ioctl_callback* = proc (handle: PCurl, cmd: int32, clientp: pointer): Ioerr{. - cdecl.} - Malloc_callback* = proc (size: int): pointer{.cdecl.} - Free_callback* = proc (p: pointer){.cdecl.} - Realloc_callback* = proc (p: pointer, size: int): pointer{.cdecl.} - Strdup_callback* = proc (str: cstring): cstring{.cdecl.} - Calloc_callback* = proc (nmemb: int, size: int): pointer{.noconv.} - Infotype* = enum - INFO_TEXT = 0, INFO_HEADER_IN, INFO_HEADER_OUT, INFO_DATA_IN, INFO_DATA_OUT, - INFO_SSL_DATA_IN, INFO_SSL_DATA_OUT, INFO_END - Debug_callback* = proc (handle: PCurl, theType: Infotype, data: cstring, - size: int, userptr: pointer): int32{.cdecl.} - Code* = enum - E_OK = 0, E_UNSUPPORTED_PROTOCOL, E_FAILED_INIT, E_URL_MALFORMAT, - E_URL_MALFORMAT_USER, E_COULDNT_RESOLVE_PROXY, E_COULDNT_RESOLVE_HOST, - E_COULDNT_CONNECT, E_FTP_WEIRD_SERVER_REPLY, E_FTP_ACCESS_DENIED, - E_FTP_USER_PASSWORD_INCORRECT, E_FTP_WEIRD_PASS_REPLY, - E_FTP_WEIRD_USER_REPLY, E_FTP_WEIRD_PASV_REPLY, E_FTP_WEIRD_227_FORMAT, - E_FTP_CANT_GET_HOST, E_FTP_CANT_RECONNECT, E_FTP_COULDNT_SET_BINARY, - E_PARTIAL_FILE, E_FTP_COULDNT_RETR_FILE, E_FTP_WRITE_ERROR, - E_FTP_QUOTE_ERROR, E_HTTP_RETURNED_ERROR, E_WRITE_ERROR, E_MALFORMAT_USER, - E_FTP_COULDNT_STOR_FILE, E_READ_ERROR, E_OUT_OF_MEMORY, - E_OPERATION_TIMEOUTED, E_FTP_COULDNT_SET_ASCII, E_FTP_PORT_FAILED, - E_FTP_COULDNT_USE_REST, E_FTP_COULDNT_GET_SIZE, E_HTTP_RANGE_ERROR, - E_HTTP_POST_ERROR, E_SSL_CONNECT_ERROR, E_BAD_DOWNLOAD_RESUME, - E_FILE_COULDNT_READ_FILE, E_LDAP_CANNOT_BIND, E_LDAP_SEARCH_FAILED, - E_LIBRARY_NOT_FOUND, E_FUNCTION_NOT_FOUND, E_ABORTED_BY_CALLBACK, - E_BAD_FUNCTION_ARGUMENT, E_BAD_CALLING_ORDER, E_INTERFACE_FAILED, - E_BAD_PASSWORD_ENTERED, E_TOO_MANY_REDIRECTS, E_UNKNOWN_TELNET_OPTION, - E_TELNET_OPTION_SYNTAX, E_OBSOLETE, E_SSL_PEER_CERTIFICATE, E_GOT_NOTHING, - E_SSL_ENGINE_NOTFOUND, E_SSL_ENGINE_SETFAILED, E_SEND_ERROR, E_RECV_ERROR, - E_SHARE_IN_USE, E_SSL_CERTPROBLEM, E_SSL_CIPHER, E_SSL_CACERT, - E_BAD_CONTENT_ENCODING, E_LDAP_INVALID_URL, E_FILESIZE_EXCEEDED, - E_FTP_SSL_FAILED, E_SEND_FAIL_REWIND, E_SSL_ENGINE_INITFAILED, - E_LOGIN_DENIED, E_TFTP_NOTFOUND, E_TFTP_PERM, E_TFTP_DISKFULL, - E_TFTP_ILLEGAL, E_TFTP_UNKNOWNID, E_TFTP_EXISTS, E_TFTP_NOSUCHUSER, - E_CONV_FAILED, E_CONV_REQD, LAST - Conv_callback* = proc (buffer: cstring, len: int): Code{.cdecl.} - Ssl_ctx_callback* = proc (curl: PCurl, ssl_ctx, userptr: pointer): Code{.cdecl.} - Proxytype* = enum - PROXY_HTTP = 0, PROXY_SOCKS4 = 4, PROXY_SOCKS5 = 5 - Ftpssl* = enum - FTPSSL_NONE, FTPSSL_TRY, FTPSSL_CONTROL, FTPSSL_ALL, FTPSSL_LAST - Ftpauth* = enum - FTPAUTH_DEFAULT, FTPAUTH_SSL, FTPAUTH_TLS, FTPAUTH_LAST - Ftpmethod* = enum - FTPMETHOD_DEFAULT, FTPMETHOD_MULTICWD, FTPMETHOD_NOCWD, FTPMETHOD_SINGLECWD, - FTPMETHOD_LAST - Option* = enum - OPT_PORT = 0 + 3, OPT_TIMEOUT = 0 + 13, OPT_INFILESIZE = 0 + 14, - OPT_LOW_SPEED_LIMIT = 0 + 19, OPT_LOW_SPEED_TIME = 0 + 20, - OPT_RESUME_FROM = 0 + 21, OPT_CRLF = 0 + 27, OPT_SSLVERSION = 0 + 32, - OPT_TIMECONDITION = 0 + 33, OPT_TIMEVALUE = 0 + 34, OPT_VERBOSE = 0 + 41, - OPT_HEADER = 0 + 42, OPT_NOPROGRESS = 0 + 43, OPT_NOBODY = 0 + 44, - OPT_FAILONERROR = 0 + 45, OPT_UPLOAD = 0 + 46, OPT_POST = 0 + 47, - OPT_FTPLISTONLY = 0 + 48, OPT_FTPAPPEND = 0 + 50, OPT_NETRC = 0 + 51, - OPT_FOLLOWLOCATION = 0 + 52, OPT_TRANSFERTEXT = 0 + 53, OPT_PUT = 0 + 54, - OPT_AUTOREFERER = 0 + 58, OPT_PROXYPORT = 0 + 59, - OPT_POSTFIELDSIZE = 0 + 60, OPT_HTTPPROXYTUNNEL = 0 + 61, - OPT_SSL_VERIFYPEER = 0 + 64, OPT_MAXREDIRS = 0 + 68, OPT_FILETIME = 0 + 69, - OPT_MAXCONNECTS = 0 + 71, OPT_CLOSEPOLICY = 0 + 72, - OPT_FRESH_CONNECT = 0 + 74, OPT_FORBID_REUSE = 0 + 75, - OPT_CONNECTTIMEOUT = 0 + 78, OPT_HTTPGET = 0 + 80, - OPT_SSL_VERIFYHOST = 0 + 81, OPT_HTTP_VERSION = 0 + 84, - OPT_FTP_USE_EPSV = 0 + 85, OPT_SSLENGINE_DEFAULT = 0 + 90, - OPT_DNS_USE_GLOBAL_CACHE = 0 + 91, OPT_DNS_CACHE_TIMEOUT = 0 + 92, - OPT_COOKIESESSION = 0 + 96, OPT_BUFFERSIZE = 0 + 98, OPT_NOSIGNAL = 0 + 99, - OPT_PROXYTYPE = 0 + 101, OPT_UNRESTRICTED_AUTH = 0 + 105, - OPT_FTP_USE_EPRT = 0 + 106, OPT_HTTPAUTH = 0 + 107, - OPT_FTP_CREATE_MISSING_DIRS = 0 + 110, OPT_PROXYAUTH = 0 + 111, - OPT_FTP_RESPONSE_TIMEOUT = 0 + 112, OPT_IPRESOLVE = 0 + 113, - OPT_MAXFILESIZE = 0 + 114, OPT_FTP_SSL = 0 + 119, OPT_TCP_NODELAY = 0 + 121, - OPT_FTPSSLAUTH = 0 + 129, OPT_IGNORE_CONTENT_LENGTH = 0 + 136, - OPT_FTP_SKIP_PASV_IP = 0 + 137, OPT_FTP_FILEMETHOD = 0 + 138, - OPT_LOCALPORT = 0 + 139, OPT_LOCALPORTRANGE = 0 + 140, - OPT_CONNECT_ONLY = 0 + 141, OPT_FILE = 10000 + 1, OPT_URL = 10000 + 2, - OPT_PROXY = 10000 + 4, OPT_USERPWD = 10000 + 5, - OPT_PROXYUSERPWD = 10000 + 6, OPT_RANGE = 10000 + 7, OPT_INFILE = 10000 + 9, - OPT_ERRORBUFFER = 10000 + 10, OPT_POSTFIELDS = 10000 + 15, - OPT_REFERER = 10000 + 16, OPT_FTPPORT = 10000 + 17, - OPT_USERAGENT = 10000 + 18, OPT_COOKIE = 10000 + 22, - OPT_HTTPHEADER = 10000 + 23, OPT_HTTPPOST = 10000 + 24, - OPT_SSLCERT = 10000 + 25, OPT_SSLCERTPASSWD = 10000 + 26, - OPT_QUOTE = 10000 + 28, OPT_WRITEHEADER = 10000 + 29, - OPT_COOKIEFILE = 10000 + 31, OPT_CUSTOMREQUEST = 10000 + 36, - OPT_STDERR = 10000 + 37, OPT_POSTQUOTE = 10000 + 39, - OPT_WRITEINFO = 10000 + 40, OPT_PROGRESSDATA = 10000 + 57, - OPT_INTERFACE = 10000 + 62, OPT_KRB4LEVEL = 10000 + 63, - OPT_CAINFO = 10000 + 65, OPT_TELNETOPTIONS = 10000 + 70, - OPT_RANDOM_FILE = 10000 + 76, OPT_EGDSOCKET = 10000 + 77, - OPT_COOKIEJAR = 10000 + 82, OPT_SSL_CIPHER_LIST = 10000 + 83, - OPT_SSLCERTTYPE = 10000 + 86, OPT_SSLKEY = 10000 + 87, - OPT_SSLKEYTYPE = 10000 + 88, OPT_SSLENGINE = 10000 + 89, - OPT_PREQUOTE = 10000 + 93, OPT_DEBUGDATA = 10000 + 95, - OPT_CAPATH = 10000 + 97, OPT_SHARE = 10000 + 100, - OPT_ENCODING = 10000 + 102, OPT_PRIVATE = 10000 + 103, - OPT_HTTP200ALIASES = 10000 + 104, OPT_SSL_CTX_DATA = 10000 + 109, - OPT_NETRC_FILE = 10000 + 118, OPT_SOURCE_USERPWD = 10000 + 123, - OPT_SOURCE_PREQUOTE = 10000 + 127, OPT_SOURCE_POSTQUOTE = 10000 + 128, - OPT_IOCTLDATA = 10000 + 131, OPT_SOURCE_URL = 10000 + 132, - OPT_SOURCE_QUOTE = 10000 + 133, OPT_FTP_ACCOUNT = 10000 + 134, - OPT_COOKIELIST = 10000 + 135, OPT_FTP_ALTERNATIVE_TO_USER = 10000 + 147, - OPT_LASTENTRY = 10000 + 148, OPT_WRITEFUNCTION = 20000 + 11, - OPT_READFUNCTION = 20000 + 12, OPT_PROGRESSFUNCTION = 20000 + 56, - OPT_HEADERFUNCTION = 20000 + 79, OPT_DEBUGFUNCTION = 20000 + 94, - OPT_SSL_CTX_FUNCTION = 20000 + 108, OPT_IOCTLFUNCTION = 20000 + 130, - OPT_CONV_FROM_NETWORK_FUNCTION = 20000 + 142, - OPT_CONV_TO_NETWORK_FUNCTION = 20000 + 143, - OPT_CONV_FROM_UTF8_FUNCTION = 20000 + 144, - OPT_INFILESIZE_LARGE = 30000 + 115, OPT_RESUME_FROM_LARGE = 30000 + 116, - OPT_MAXFILESIZE_LARGE = 30000 + 117, OPT_POSTFIELDSIZE_LARGE = 30000 + 120, - OPT_MAX_SEND_SPEED_LARGE = 30000 + 145, - OPT_MAX_RECV_SPEED_LARGE = 30000 + 146 - HTTP_VERSION* = enum - HTTP_VERSION_NONE, HTTP_VERSION_1_0, HTTP_VERSION_1_1, HTTP_VERSION_LAST - NETRC_OPTION* = enum - NETRC_IGNORED, NETRC_OPTIONAL, NETRC_REQUIRED, NETRC_LAST - SSL_VERSION* = enum - SSLVERSION_DEFAULT, SSLVERSION_TLSv1, SSLVERSION_SSLv2, SSLVERSION_SSLv3, - SSLVERSION_LAST - TIMECOND* = enum - TIMECOND_NONE, TIMECOND_IFMODSINCE, TIMECOND_IFUNMODSINCE, TIMECOND_LASTMOD, - TIMECOND_LAST - Formoption* = enum - FORM_NOTHING, FORM_COPYNAME, FORM_PTRNAME, FORM_NAMELENGTH, - FORM_COPYCONTENTS, FORM_PTRCONTENTS, FORM_CONTENTSLENGTH, FORM_FILECONTENT, - FORM_ARRAY, FORM_OBSOLETE, FORM_FILE, FORM_BUFFER, FORM_BUFFERPTR, - FORM_BUFFERLENGTH, FORM_CONTENTTYPE, FORM_CONTENTHEADER, FORM_FILENAME, - FORM_END, FORM_OBSOLETE2, FORM_LASTENTRY - Forms*{.pure, final.} = object - option*: Formoption - value*: cstring - - FORMcode* = enum - FORMADD_OK, FORMADD_MEMORY, FORMADD_OPTION_TWICE, FORMADD_NULL, - FORMADD_UNKNOWN_OPTION, FORMADD_INCOMPLETE, FORMADD_ILLEGAL_ARRAY, - FORMADD_DISABLED, FORMADD_LAST - Formget_callback* = proc (arg: pointer, buf: cstring, length: int): int{. - cdecl.} - Slist*{.pure, final.} = object - data*: cstring - next*: Pslist - - INFO* = enum - INFO_NONE = 0, INFO_LASTONE = 30, INFO_EFFECTIVE_URL = 0x00100000 + 1, - INFO_CONTENT_TYPE = 0x00100000 + 18, INFO_PRIVATE = 0x00100000 + 21, - INFO_FTP_ENTRY_PATH = 0x00100000 + 30, INFO_RESPONSE_CODE = 0x00200000 + 2, - INFO_HEADER_SIZE = 0x00200000 + 11, INFO_REQUEST_SIZE = 0x00200000 + 12, - INFO_SSL_VERIFYRESULT = 0x00200000 + 13, INFO_FILETIME = 0x00200000 + 14, - INFO_REDIRECT_COUNT = 0x00200000 + 20, - INFO_HTTP_CONNECTCODE = 0x00200000 + 22, - INFO_HTTPAUTH_AVAIL = 0x00200000 + 23, - INFO_PROXYAUTH_AVAIL = 0x00200000 + 24, INFO_OS_ERRNO = 0x00200000 + 25, - INFO_NUM_CONNECTS = 0x00200000 + 26, INFO_LASTSOCKET = 0x00200000 + 29, - INFO_TOTAL_TIME = 0x00300000 + 3, INFO_NAMELOOKUP_TIME = 0x00300000 + 4, - INFO_CONNECT_TIME = 0x00300000 + 5, INFO_PRETRANSFER_TIME = 0x00300000 + 6, - INFO_SIZE_UPLOAD = 0x00300000 + 7, INFO_SIZE_DOWNLOAD = 0x00300000 + 8, - INFO_SPEED_DOWNLOAD = 0x00300000 + 9, INFO_SPEED_UPLOAD = 0x00300000 + 10, - INFO_CONTENT_LENGTH_DOWNLOAD = 0x00300000 + 15, - INFO_CONTENT_LENGTH_UPLOAD = 0x00300000 + 16, - INFO_STARTTRANSFER_TIME = 0x00300000 + 17, - INFO_REDIRECT_TIME = 0x00300000 + 19, INFO_SSL_ENGINES = 0x00400000 + 27, - INFO_COOKIELIST = 0x00400000 + 28 - Closepolicy* = enum - CLOSEPOLICY_NONE, CLOSEPOLICY_OLDEST, CLOSEPOLICY_LEAST_RECENTLY_USED, - CLOSEPOLICY_LEAST_TRAFFIC, CLOSEPOLICY_SLOWEST, CLOSEPOLICY_CALLBACK, - CLOSEPOLICY_LAST - Lock_data* = enum - LOCK_DATA_NONE = 0, LOCK_DATA_SHARE, LOCK_DATA_COOKIE, LOCK_DATA_DNS, - LOCK_DATA_SSL_SESSION, LOCK_DATA_CONNECT, LOCK_DATA_LAST - Lock_access* = enum - LOCK_ACCESS_NONE = 0, LOCK_ACCESS_SHARED = 1, LOCK_ACCESS_SINGLE = 2, - LOCK_ACCESS_LAST - Lock_function* = proc (handle: PCurl, data: Lock_data, - locktype: Lock_access, - userptr: pointer){.cdecl.} - Unlock_function* = proc (handle: PCurl, data: Lock_data, userptr: pointer){. - cdecl.} - SH* = pointer - SHcode* = enum - SHE_OK, SHE_BAD_OPTION, SHE_IN_USE, SHE_INVALID, SHE_NOMEM, SHE_LAST - SHoption* = enum - SHOPT_NONE, SHOPT_SHARE, SHOPT_UNSHARE, SHOPT_LOCKFUNC, SHOPT_UNLOCKFUNC, - SHOPT_USERDATA, SHOPT_LAST - Version* = enum - VERSION_FIRST, VERSION_SECOND, VERSION_THIRD, VERSION_LAST - Version_info_data*{.pure, final.} = object - age*: Version - version*: cstring - version_num*: int32 - host*: cstring - features*: int32 - ssl_version*: cstring - ssl_version_num*: int32 - libz_version*: cstring - protocols*: cstringArray - ares*: cstring - ares_num*: int32 - libidn*: cstring - iconv_ver_num*: int32 - - M* = pointer - Socket* = int32 - Mcode* = enum - M_CALL_MULTI_PERFORM = - 1, M_OK = 0, M_BAD_HANDLE, M_BAD_EASY_HANDLE, - M_OUT_OF_MEMORY, M_INTERNAL_ERROR, M_BAD_SOCKET, M_UNKNOWN_OPTION, M_LAST - MSGEnum* = enum - MSG_NONE, MSG_DONE, MSG_LAST - Msg*{.pure, final.} = object - msg*: MSGEnum - easy_handle*: PCurl - whatever*: pointer #data : record - # case longint of - # 0 : ( whatever : pointer ); - # 1 : ( result : CURLcode ); - # end; - - Socket_callback* = proc (easy: PCurl, s: Socket, what: int32, - userp, socketp: pointer): int32{.cdecl.} - Moption* = enum - MOPT_SOCKETDATA = 10000 + 2, MOPT_LASTENTRY = 10000 + 3, - MOPT_SOCKETFUNCTION = 20000 + 1 -{.deprecated: [TMsg: Msg, TCurl: Curl, Thttppost: Httppost, - Tprogress_callback: Progress_callback, Twrite_callback: Write_callback, - Tread_callback: Read_callback, Tpasswd_callback: Passwd_callback, Tioerr: Ioerr, - Tiocmd: Iocmd, Tioctl_callback: Ioctl_callback, Tmalloc_callback: Malloc_callback, - Tfree_callback: Free_callback, Trealloc_callback: Realloc_callback, - Tstrdup_callback: Strdup_callback, Tcalloc_callback: Calloc_callback, - Tinfotype: Infotype, Tdebug_callback: Debug_callback, Tcode: Code, - Tconv_callback: Conv_callback, Tssl_ctx_callback: Ssl_ctx_callback, - Tproxytype: Proxytype, Tftpssl: Ftpssl, Tftpauth: Ftpauth, Tftpmethod: Ftpmethod, - Toption: Option, THTTP_VERSION: HTTP_VERSION, TNETRC_OPTION: NETRC_OPTION, - TSSL_VERSION: SSL_VERSION, TTIMECOND: TIMECOND, Tformoption: Formoption, - Tforms: Forms, TFORMcode: FORMcode, Tformget_callback: Formget_callback, - Tslist: Slist, TINFO: INFO, Tclosepolicy: Closepolicy, Tlock_data: Lock_data, - Tlock_access: Lock_access, Tlock_function: Lock_function, - Tunlock_function: Unlock_function, TSH: Sh, TSHcode: SHcode, TSHoption: SHoption, - Tversion: Version, Tversion_info_data: Version_info_data, TM: M, Tsocket: Socket, - TMcode: Mcode, TMSGEnum: MsGEnum, Tsocket_callback: Socket_callback, - TMoption: Moption].} - -const - OPT_SSLKEYPASSWD* = OPT_SSLCERTPASSWD - AUTH_ANY* = not (0) - AUTH_BASIC* = 1 shl 0 - AUTH_ANYSAFE* = not (AUTH_BASIC) - AUTH_DIGEST* = 1 shl 1 - AUTH_GSSNEGOTIATE* = 1 shl 2 - AUTH_NONE* = 0 - AUTH_NTLM* = 1 shl 3 - E_ALREADY_COMPLETE* = 99999 - E_FTP_BAD_DOWNLOAD_RESUME* = E_BAD_DOWNLOAD_RESUME - E_FTP_PARTIAL_FILE* = E_PARTIAL_FILE - E_HTTP_NOT_FOUND* = E_HTTP_RETURNED_ERROR - E_HTTP_PORT_FAILED* = E_INTERFACE_FAILED - E_OPERATION_TIMEDOUT* = E_OPERATION_TIMEOUTED - ERROR_SIZE* = 256 - FORMAT_OFF_T* = "%ld" - GLOBAL_NOTHING* = 0 - GLOBAL_SSL* = 1 shl 0 - GLOBAL_WIN32* = 1 shl 1 - GLOBAL_ALL* = GLOBAL_SSL or GLOBAL_WIN32 - GLOBAL_DEFAULT* = GLOBAL_ALL - INFO_DOUBLE* = 0x00300000 - INFO_HTTP_CODE* = INFO_RESPONSE_CODE - INFO_LONG* = 0x00200000 - INFO_MASK* = 0x000FFFFF - INFO_SLIST* = 0x00400000 - INFO_STRING* = 0x00100000 - INFO_TYPEMASK* = 0x00F00000 - IPRESOLVE_V4* = 1 - IPRESOLVE_V6* = 2 - IPRESOLVE_WHATEVER* = 0 - MAX_WRITE_SIZE* = 16384 - M_CALL_MULTI_SOCKET* = M_CALL_MULTI_PERFORM - OPT_CLOSEFUNCTION* = - (5) - OPT_FTPASCII* = OPT_TRANSFERTEXT - OPT_HEADERDATA* = OPT_WRITEHEADER - OPT_HTTPREQUEST* = - (1) - OPT_MUTE* = - (2) - OPT_PASSWDDATA* = - (4) - OPT_PASSWDFUNCTION* = - (3) - OPT_PASV_HOST* = - (9) - OPT_READDATA* = OPT_INFILE - OPT_SOURCE_HOST* = - (6) - OPT_SOURCE_PATH* = - (7) - OPT_SOURCE_PORT* = - (8) - OPTTYPE_FUNCTIONPOINT* = 20000 - OPTTYPE_LONG* = 0 - OPTTYPE_OBJECTPOINT* = 10000 - OPTTYPE_OFF_T* = 30000 - OPT_WRITEDATA* = OPT_FILE - POLL_IN* = 1 - POLL_INOUT* = 3 - POLL_NONE* = 0 - POLL_OUT* = 2 - POLL_REMOVE* = 4 - READFUNC_ABORT* = 0x10000000 - SOCKET_BAD* = - (1) - SOCKET_TIMEOUT* = SOCKET_BAD - VERSION_ASYNCHDNS* = 1 shl 7 - VERSION_CONV* = 1 shl 12 - VERSION_DEBUG* = 1 shl 6 - VERSION_GSSNEGOTIATE* = 1 shl 5 - VERSION_IDN* = 1 shl 10 - VERSION_IPV6* = 1 shl 0 - VERSION_KERBEROS4* = 1 shl 1 - VERSION_LARGEFILE* = 1 shl 9 - VERSION_LIBZ* = 1 shl 3 - VERSION_NOW* = VERSION_THIRD - VERSION_NTLM* = 1 shl 4 - VERSION_SPNEGO* = 1 shl 8 - VERSION_SSL* = 1 shl 2 - VERSION_SSPI* = 1 shl 11 - FILE_OFFSET_BITS* = 0 - FILESIZEBITS* = 0 - FUNCTIONPOINT* = OPTTYPE_FUNCTIONPOINT - HTTPPOST_BUFFER* = 1 shl 4 - HTTPPOST_FILENAME* = 1 shl 0 - HTTPPOST_PTRBUFFER* = 1 shl 5 - HTTPPOST_PTRCONTENTS* = 1 shl 3 - HTTPPOST_PTRNAME* = 1 shl 2 - HTTPPOST_READFILE* = 1 shl 1 - LIBCURL_VERSION* = "7.15.5" - LIBCURL_VERSION_MAJOR* = 7 - LIBCURL_VERSION_MINOR* = 15 - LIBCURL_VERSION_NUM* = 0x00070F05 - LIBCURL_VERSION_PATCH* = 5 - -proc strequal*(s1, s2: cstring): int32{.cdecl, dynlib: libname, - importc: "curl_strequal".} -proc strnequal*(s1, s2: cstring, n: int): int32{.cdecl, dynlib: libname, - importc: "curl_strnequal".} -proc formadd*(httppost, last_post: PPcurl_httppost): FORMcode{.cdecl, varargs, - dynlib: libname, importc: "curl_formadd".} -proc formget*(form: Phttppost, arg: pointer, append: Formget_callback): int32{. - cdecl, dynlib: libname, importc: "curl_formget".} -proc formfree*(form: Phttppost){.cdecl, dynlib: libname, - importc: "curl_formfree".} -proc getenv*(variable: cstring): cstring{.cdecl, dynlib: libname, - importc: "curl_getenv".} -proc version*(): cstring{.cdecl, dynlib: libname, importc: "curl_version".} -proc easy_escape*(handle: PCurl, str: cstring, len: int32): cstring{.cdecl, - dynlib: libname, importc: "curl_easy_escape".} -proc escape*(str: cstring, len: int32): cstring{.cdecl, dynlib: libname, - importc: "curl_escape".} -proc easy_unescape*(handle: PCurl, str: cstring, len: int32, outlength: var int32): cstring{. - cdecl, dynlib: libname, importc: "curl_easy_unescape".} -proc unescape*(str: cstring, len: int32): cstring{.cdecl, dynlib: libname, - importc: "curl_unescape".} -proc free*(p: pointer){.cdecl, dynlib: libname, importc: "curl_free".} -proc global_init*(flags: int32): Code{.cdecl, dynlib: libname, - importc: "curl_global_init".} -proc global_init_mem*(flags: int32, m: Malloc_callback, f: Free_callback, - r: Realloc_callback, s: Strdup_callback, - c: Calloc_callback): Code{.cdecl, dynlib: libname, - importc: "curl_global_init_mem".} -proc global_cleanup*(){.cdecl, dynlib: libname, importc: "curl_global_cleanup".} -proc slist_append*(slist: Pslist, p: cstring): Pslist{.cdecl, dynlib: libname, - importc: "curl_slist_append".} -proc slist_free_all*(para1: Pslist){.cdecl, dynlib: libname, - importc: "curl_slist_free_all".} -proc getdate*(p: cstring, unused: ptr Time): Time{.cdecl, dynlib: libname, - importc: "curl_getdate".} -proc share_init*(): PSH{.cdecl, dynlib: libname, importc: "curl_share_init".} -proc share_setopt*(para1: PSH, option: SHoption): SHcode{.cdecl, varargs, - dynlib: libname, importc: "curl_share_setopt".} -proc share_cleanup*(para1: PSH): SHcode{.cdecl, dynlib: libname, - importc: "curl_share_cleanup".} -proc version_info*(para1: Version): Pversion_info_data{.cdecl, dynlib: libname, - importc: "curl_version_info".} -proc easy_strerror*(para1: Code): cstring{.cdecl, dynlib: libname, - importc: "curl_easy_strerror".} -proc share_strerror*(para1: SHcode): cstring{.cdecl, dynlib: libname, - importc: "curl_share_strerror".} -proc easy_init*(): PCurl{.cdecl, dynlib: libname, importc: "curl_easy_init".} -proc easy_setopt*(curl: PCurl, option: Option): Code{.cdecl, varargs, dynlib: libname, - importc: "curl_easy_setopt".} -proc easy_perform*(curl: PCurl): Code{.cdecl, dynlib: libname, - importc: "curl_easy_perform".} -proc easy_cleanup*(curl: PCurl){.cdecl, dynlib: libname, importc: "curl_easy_cleanup".} -proc easy_getinfo*(curl: PCurl, info: INFO): Code{.cdecl, varargs, dynlib: libname, - importc: "curl_easy_getinfo".} -proc easy_duphandle*(curl: PCurl): PCurl{.cdecl, dynlib: libname, - importc: "curl_easy_duphandle".} -proc easy_reset*(curl: PCurl){.cdecl, dynlib: libname, importc: "curl_easy_reset".} -proc multi_init*(): PM{.cdecl, dynlib: libname, importc: "curl_multi_init".} -proc multi_add_handle*(multi_handle: PM, handle: PCurl): Mcode{.cdecl, - dynlib: libname, importc: "curl_multi_add_handle".} -proc multi_remove_handle*(multi_handle: PM, handle: PCurl): Mcode{.cdecl, - dynlib: libname, importc: "curl_multi_remove_handle".} -proc multi_fdset*(multi_handle: PM, read_fd_set: Pfd_set, write_fd_set: Pfd_set, - exc_fd_set: Pfd_set, max_fd: var int32): Mcode{.cdecl, - dynlib: libname, importc: "curl_multi_fdset".} -proc multi_perform*(multi_handle: PM, running_handles: var int32): Mcode{. - cdecl, dynlib: libname, importc: "curl_multi_perform".} -proc multi_cleanup*(multi_handle: PM): Mcode{.cdecl, dynlib: libname, - importc: "curl_multi_cleanup".} -proc multi_info_read*(multi_handle: PM, msgs_in_queue: var int32): PMsg{.cdecl, - dynlib: libname, importc: "curl_multi_info_read".} -proc multi_strerror*(para1: Mcode): cstring{.cdecl, dynlib: libname, - importc: "curl_multi_strerror".} -proc multi_socket*(multi_handle: PM, s: Socket, running_handles: var int32): Mcode{. - cdecl, dynlib: libname, importc: "curl_multi_socket".} -proc multi_socket_all*(multi_handle: PM, running_handles: var int32): Mcode{. - cdecl, dynlib: libname, importc: "curl_multi_socket_all".} -proc multi_timeout*(multi_handle: PM, milliseconds: var int32): Mcode{.cdecl, - dynlib: libname, importc: "curl_multi_timeout".} -proc multi_setopt*(multi_handle: PM, option: Moption): Mcode{.cdecl, varargs, - dynlib: libname, importc: "curl_multi_setopt".} -proc multi_assign*(multi_handle: PM, sockfd: Socket, sockp: pointer): Mcode{. - cdecl, dynlib: libname, importc: "curl_multi_assign".} diff --git a/lib/wrappers/libffi/common/ffi.h b/lib/wrappers/libffi/common/ffi.h deleted file mode 100644 index 07d650eac..000000000 --- a/lib/wrappers/libffi/common/ffi.h +++ /dev/null @@ -1,331 +0,0 @@ -/* -----------------------------------------------------------------*-C-*- - libffi 2.00-beta - Copyright (c) 1996-2003 Red Hat, Inc. - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files (the - ``Software''), to deal in the Software without restriction, including - without limitation the rights to use, copy, modify, merge, publish, - distribute, sublicense, and/or sell copies of the Software, and to - permit persons to whom the Software is furnished to do so, subject to - the following conditions: - - The above copyright notice and this permission notice shall be included - in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. - - ----------------------------------------------------------------------- */ - -/* ------------------------------------------------------------------- - The basic API is described in the README file. - - The raw API is designed to bypass some of the argument packing - and unpacking on architectures for which it can be avoided. - - The closure API allows interpreted functions to be packaged up - inside a C function pointer, so that they can be called as C functions, - with no understanding on the client side that they are interpreted. - It can also be used in other cases in which it is necessary to package - up a user specified parameter and a function pointer as a single - function pointer. - - The closure API must be implemented in order to get its functionality, - e.g. for use by gij. Routines are provided to emulate the raw API - if the underlying platform doesn't allow faster implementation. - - More details on the raw and cloure API can be found in: - - http://gcc.gnu.org/ml/java/1999-q3/msg00138.html - - and - - http://gcc.gnu.org/ml/java/1999-q3/msg00174.html - -------------------------------------------------------------------- */ - -#ifndef LIBFFI_H -#define LIBFFI_H - -#ifdef __cplusplus -extern "C" { -#endif - -/* Specify which architecture libffi is configured for. */ -//XXX #define X86 - -/* ---- System configuration information --------------------------------- */ - -#include - -#ifndef LIBFFI_ASM - -#include -#include - -/* LONG_LONG_MAX is not always defined (not if STRICT_ANSI, for example). - But we can find it either under the correct ANSI name, or under GNU - C's internal name. */ -#ifdef LONG_LONG_MAX -# define FFI_LONG_LONG_MAX LONG_LONG_MAX -#else -# ifdef LLONG_MAX -# define FFI_LONG_LONG_MAX LLONG_MAX -# else -# ifdef __GNUC__ -# define FFI_LONG_LONG_MAX __LONG_LONG_MAX__ -# endif -# ifdef _MSC_VER -# define FFI_LONG_LONG_MAX _I64_MAX -# endif -# endif -#endif - -#if SCHAR_MAX == 127 -# define ffi_type_uchar ffi_type_uint8 -# define ffi_type_schar ffi_type_sint8 -#else - #error "char size not supported" -#endif - -#if SHRT_MAX == 32767 -# define ffi_type_ushort ffi_type_uint16 -# define ffi_type_sshort ffi_type_sint16 -#elif SHRT_MAX == 2147483647 -# define ffi_type_ushort ffi_type_uint32 -# define ffi_type_sshort ffi_type_sint32 -#else - #error "short size not supported" -#endif - -#if INT_MAX == 32767 -# define ffi_type_uint ffi_type_uint16 -# define ffi_type_sint ffi_type_sint16 -#elif INT_MAX == 2147483647 -# define ffi_type_uint ffi_type_uint32 -# define ffi_type_sint ffi_type_sint32 -#elif INT_MAX == 9223372036854775807 -# define ffi_type_uint ffi_type_uint64 -# define ffi_type_sint ffi_type_sint64 -#else - #error "int size not supported" -#endif - -#define ffi_type_ulong ffi_type_uint64 -#define ffi_type_slong ffi_type_sint64 -#if LONG_MAX == 2147483647 -# if FFI_LONG_LONG_MAX != 9223372036854775807 - #error "no 64-bit data type supported" -# endif -#elif LONG_MAX != 9223372036854775807 - #error "long size not supported" -#endif - -/* The closure code assumes that this works on pointers, i.e. a size_t */ -/* can hold a pointer. */ - -typedef struct _ffi_type -{ - size_t size; - unsigned short alignment; - unsigned short type; - /*@null@*/ struct _ffi_type **elements; -} ffi_type; - -/* These are defined in types.c */ -extern const ffi_type ffi_type_void; -extern const ffi_type ffi_type_uint8; -extern const ffi_type ffi_type_sint8; -extern const ffi_type ffi_type_uint16; -extern const ffi_type ffi_type_sint16; -extern const ffi_type ffi_type_uint32; -extern const ffi_type ffi_type_sint32; -extern const ffi_type ffi_type_uint64; -extern const ffi_type ffi_type_sint64; -extern const ffi_type ffi_type_float; -extern const ffi_type ffi_type_double; -extern const ffi_type ffi_type_longdouble; -extern const ffi_type ffi_type_pointer; - - -typedef enum { - FFI_OK = 0, - FFI_BAD_TYPEDEF, - FFI_BAD_ABI -} ffi_status; - -typedef unsigned FFI_TYPE; - -typedef struct { - ffi_abi abi; - unsigned nargs; - /*@dependent@*/ ffi_type **arg_types; - /*@dependent@*/ ffi_type *rtype; - unsigned bytes; - unsigned flags; -#ifdef FFI_EXTRA_CIF_FIELDS - FFI_EXTRA_CIF_FIELDS; -#endif -} ffi_cif; - -/* ---- Definitions for the raw API -------------------------------------- */ - -#ifdef _WIN64 -#define FFI_SIZEOF_ARG 8 -#else -#define FFI_SIZEOF_ARG 4 -#endif - -typedef union { - ffi_sarg sint; - ffi_arg uint; - float flt; - char data[FFI_SIZEOF_ARG]; - void* ptr; -} ffi_raw; - -void ffi_raw_call (/*@dependent@*/ ffi_cif *cif, - void (*fn)(), - /*@out@*/ void *rvalue, - /*@dependent@*/ ffi_raw *avalue); - -void ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw); -void ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args); -size_t ffi_raw_size (ffi_cif *cif); - -/* This is analogous to the raw API, except it uses Java parameter */ -/* packing, even on 64-bit machines. I.e. on 64-bit machines */ -/* longs and doubles are followed by an empty 64-bit word. */ - -void ffi_java_raw_call (/*@dependent@*/ ffi_cif *cif, - void (*fn)(), - /*@out@*/ void *rvalue, - /*@dependent@*/ ffi_raw *avalue); - -void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw); -void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args); -size_t ffi_java_raw_size (ffi_cif *cif); - -/* ---- Definitions for closures ----------------------------------------- */ - -#if FFI_CLOSURES - -typedef struct { - char tramp[FFI_TRAMPOLINE_SIZE]; - ffi_cif *cif; - void (*fun)(ffi_cif*,void*,void**,void*); - void *user_data; -} ffi_closure; - -void ffi_closure_free(void *); -void *ffi_closure_alloc (size_t size, void **code); - -ffi_status -ffi_prep_closure_loc (ffi_closure*, - ffi_cif *, - void (*fun)(ffi_cif*,void*,void**,void*), - void *user_data, - void *codeloc); - -typedef struct { - char tramp[FFI_TRAMPOLINE_SIZE]; - - ffi_cif *cif; - -#if !FFI_NATIVE_RAW_API - - /* if this is enabled, then a raw closure has the same layout - as a regular closure. We use this to install an intermediate - handler to do the transaltion, void** -> ffi_raw*. */ - - void (*translate_args)(ffi_cif*,void*,void**,void*); - void *this_closure; - -#endif - - void (*fun)(ffi_cif*,void*,ffi_raw*,void*); - void *user_data; - -} ffi_raw_closure; - -ffi_status -ffi_prep_raw_closure (ffi_raw_closure*, - ffi_cif *cif, - void (*fun)(ffi_cif*,void*,ffi_raw*,void*), - void *user_data); - -ffi_status -ffi_prep_java_raw_closure (ffi_raw_closure*, - ffi_cif *cif, - void (*fun)(ffi_cif*,void*,ffi_raw*,void*), - void *user_data); - -#endif /* FFI_CLOSURES */ - -/* ---- Public interface definition -------------------------------------- */ - -ffi_status ffi_prep_cif(/*@out@*/ /*@partial@*/ ffi_cif *cif, - ffi_abi abi, - unsigned int nargs, - /*@dependent@*/ /*@out@*/ /*@partial@*/ ffi_type *rtype, - /*@dependent@*/ ffi_type **atypes); - -void -ffi_call(/*@dependent@*/ ffi_cif *cif, - void (*fn)(), - /*@out@*/ void *rvalue, - /*@dependent@*/ void **avalue); - -/* Useful for eliminating compiler warnings */ -#define FFI_FN(f) ((void (*)())f) - -/* ---- Definitions shared with assembly code ---------------------------- */ - -#endif - -/* If these change, update src/mips/ffitarget.h. */ -#define FFI_TYPE_VOID 0 -#define FFI_TYPE_INT 1 -#define FFI_TYPE_FLOAT 2 -#define FFI_TYPE_DOUBLE 3 -#if 1 -#define FFI_TYPE_LONGDOUBLE 4 -#else -#define FFI_TYPE_LONGDOUBLE FFI_TYPE_DOUBLE -#endif -#define FFI_TYPE_UINT8 5 -#define FFI_TYPE_SINT8 6 -#define FFI_TYPE_UINT16 7 -#define FFI_TYPE_SINT16 8 -#define FFI_TYPE_UINT32 9 -#define FFI_TYPE_SINT32 10 -#define FFI_TYPE_UINT64 11 -#define FFI_TYPE_SINT64 12 -#define FFI_TYPE_STRUCT 13 -#define FFI_TYPE_POINTER 14 - -/* This should always refer to the last type code (for sanity checks) */ -#define FFI_TYPE_LAST FFI_TYPE_POINTER - -#define FFI_HIDDEN /* no idea what the origial definition looks like ... */ - -#ifdef __GNUC__ -# define LIKELY(x) __builtin_expect(x, 1) -# define UNLIKELY(x) __builtin_expect(x, 0) -#else -# define LIKELY(x) (x) -# define UNLIKELY(x) (x) -#endif - -#define MAYBE_UNUSED - -#ifdef __cplusplus -} -#endif - -#endif - diff --git a/lib/wrappers/libffi/common/ffi_common.h b/lib/wrappers/libffi/common/ffi_common.h deleted file mode 100644 index 43fb83b48..000000000 --- a/lib/wrappers/libffi/common/ffi_common.h +++ /dev/null @@ -1,77 +0,0 @@ -/* ----------------------------------------------------------------------- - ffi_common.h - Copyright (c) 1996 Red Hat, Inc. - - Common internal definitions and macros. Only necessary for building - libffi. - ----------------------------------------------------------------------- */ - -#ifndef FFI_COMMON_H -#define FFI_COMMON_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include -#include - -/* Check for the existence of memcpy. */ -#if STDC_HEADERS -# include -#else -# ifndef HAVE_MEMCPY -# define memcpy(d, s, n) bcopy ((s), (d), (n)) -# endif -#endif - -#if defined(FFI_DEBUG) -#include -#endif - -#ifdef FFI_DEBUG -/*@exits@*/ void ffi_assert(/*@temp@*/ char *expr, /*@temp@*/ char *file, int line); -void ffi_stop_here(void); -void ffi_type_test(/*@temp@*/ /*@out@*/ ffi_type *a, /*@temp@*/ char *file, int line); - -#define FFI_ASSERT(x) ((x) ? (void)0 : ffi_assert(#x, __FILE__,__LINE__)) -#define FFI_ASSERT_AT(x, f, l) ((x) ? 0 : ffi_assert(#x, (f), (l))) -#define FFI_ASSERT_VALID_TYPE(x) ffi_type_test (x, __FILE__, __LINE__) -#else -#define FFI_ASSERT(x) -#define FFI_ASSERT_AT(x, f, l) -#define FFI_ASSERT_VALID_TYPE(x) -#endif - -#define ALIGN(v, a) (((((size_t) (v))-1) | ((a)-1))+1) - -/* Perform machine dependent cif processing */ -ffi_status ffi_prep_cif_machdep(ffi_cif *cif); - -/* Extended cif, used in callback from assembly routine */ -typedef struct -{ - /*@dependent@*/ ffi_cif *cif; - /*@dependent@*/ void *rvalue; - /*@dependent@*/ void **avalue; -} extended_cif; - -/* Terse sized type definitions. */ -typedef unsigned int UINT8 __attribute__((__mode__(__QI__))); -typedef signed int SINT8 __attribute__((__mode__(__QI__))); -typedef unsigned int UINT16 __attribute__((__mode__(__HI__))); -typedef signed int SINT16 __attribute__((__mode__(__HI__))); -typedef unsigned int UINT32 __attribute__((__mode__(__SI__))); -typedef signed int SINT32 __attribute__((__mode__(__SI__))); -typedef unsigned int UINT64 __attribute__((__mode__(__DI__))); -typedef signed int SINT64 __attribute__((__mode__(__DI__))); - -typedef float FLOAT32; - - -#ifdef __cplusplus -} -#endif - -#endif - - diff --git a/lib/wrappers/libffi/common/fficonfig.h b/lib/wrappers/libffi/common/fficonfig.h deleted file mode 100644 index c14f653ec..000000000 --- a/lib/wrappers/libffi/common/fficonfig.h +++ /dev/null @@ -1,96 +0,0 @@ -/* fficonfig.h. Originally created by configure, now hand_maintained for MSVC. */ - -/* fficonfig.h. Generated automatically by configure. */ -/* fficonfig.h.in. Generated automatically from configure.in by autoheader. */ - -/* Define this for MSVC, but not for mingw32! */ -#ifdef _MSC_VER -#define __attribute__(x) /* */ -#endif -#define alloca _alloca - -/*----------------------------------------------------------------*/ - -/* Define if using alloca.c. */ -/* #undef C_ALLOCA */ - -/* Define to one of _getb67, GETB67, getb67 for Cray-2 and Cray-YMP systems. - This function is required for alloca.c support on those systems. */ -/* #undef CRAY_STACKSEG_END */ - -/* Define if you have alloca, as a function or macro. */ -#define HAVE_ALLOCA 1 - -/* Define if you have and it should be used (not on Ultrix). */ -/* #define HAVE_ALLOCA_H 1 */ - -/* If using the C implementation of alloca, define if you know the - direction of stack growth for your system; otherwise it will be - automatically deduced at run-time. - STACK_DIRECTION > 0 => grows toward higher addresses - STACK_DIRECTION < 0 => grows toward lower addresses - STACK_DIRECTION = 0 => direction of growth unknown - */ -/* #undef STACK_DIRECTION */ - -/* Define if you have the ANSI C header files. */ -#define STDC_HEADERS 1 - -/* Define if you have the memcpy function. */ -#define HAVE_MEMCPY 1 - -/* Define if read-only mmap of a plain file works. */ -//#define HAVE_MMAP_FILE 1 - -/* Define if mmap of /dev/zero works. */ -//#define HAVE_MMAP_DEV_ZERO 1 - -/* Define if mmap with MAP_ANON(YMOUS) works. */ -//#define HAVE_MMAP_ANON 1 - -/* The number of bytes in type double */ -#define SIZEOF_DOUBLE 8 - -/* The number of bytes in type long double */ -#define SIZEOF_LONG_DOUBLE 12 - -/* Define if you have the long double type and it is bigger than a double */ -#define HAVE_LONG_DOUBLE 1 - -/* whether byteorder is bigendian */ -/* #undef WORDS_BIGENDIAN */ - -/* Define if the host machine stores words of multi-word integers in - big-endian order. */ -/* #undef HOST_WORDS_BIG_ENDIAN */ - -/* 1234 = LIL_ENDIAN, 4321 = BIGENDIAN */ -#define BYTEORDER 1234 - -/* Define if your assembler and linker support unaligned PC relative relocs. */ -/* #undef HAVE_AS_SPARC_UA_PCREL */ - -/* Define if your assembler supports .register. */ -/* #undef HAVE_AS_REGISTER_PSEUDO_OP */ - -/* Define if .eh_frame sections should be read-only. */ -/* #undef HAVE_RO_EH_FRAME */ - -/* Define to the flags needed for the .section .eh_frame directive. */ -/* #define EH_FRAME_FLAGS "aw" */ - -/* Define to the flags needed for the .section .eh_frame directive. */ -/* #define EH_FRAME_FLAGS "aw" */ - -/* Define this if you want extra debugging. */ -/* #undef FFI_DEBUG */ - -/* Define this is you do not want support for aggregate types. */ -/* #undef FFI_NO_STRUCTS */ - -/* Define this is you do not want support for the raw API. */ -/* #undef FFI_NO_RAW_API */ - -/* Define this if you are using Purify and want to suppress spurious messages. */ -/* #undef USING_PURIFY */ - diff --git a/lib/wrappers/libffi/common/ffitarget.h b/lib/wrappers/libffi/common/ffitarget.h deleted file mode 100644 index d8d60f2e7..000000000 --- a/lib/wrappers/libffi/common/ffitarget.h +++ /dev/null @@ -1,150 +0,0 @@ -/* -----------------------------------------------------------------*-C-*- - ffitarget.h - Copyright (c) 2012 Anthony Green - Copyright (c) 1996-2003, 2010 Red Hat, Inc. - Copyright (C) 2008 Free Software Foundation, Inc. - - Target configuration macros for x86 and x86-64. - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files (the - ``Software''), to deal in the Software without restriction, including - without limitation the rights to use, copy, modify, merge, publish, - distribute, sublicense, and/or sell copies of the Software, and to - permit persons to whom the Software is furnished to do so, subject to - the following conditions: - - The above copyright notice and this permission notice shall be included - in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - DEALINGS IN THE SOFTWARE. - - ----------------------------------------------------------------------- */ - -#ifndef LIBFFI_TARGET_H -#define LIBFFI_TARGET_H - -#ifndef LIBFFI_H -#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead." -#endif - -/* ---- System specific configurations ----------------------------------- */ - -/* For code common to all platforms on x86 and x86_64. */ -#define X86_ANY - -#if (defined(WIN32) || defined(_WIN32) || defined(__WIN32__)) -# if defined(__x86_64__) || defined(__x86_64) || defined(_M_X64) -# define X86_64 -# define X86_WIN64 -# else -# define X86_32 -# define X86_WIN32 -# endif -#endif - -#if defined (X86_64) && defined (__i386__) -#undef X86_64 -#define X86 -#endif - -#ifdef X86_WIN64 -#define FFI_SIZEOF_ARG 8 -#define USE_BUILTIN_FFS 0 /* not yet implemented in mingw-64 */ -#endif - -/* ---- Generic type definitions ----------------------------------------- */ - -#ifndef LIBFFI_ASM -#ifdef X86_WIN64 -#ifdef _MSC_VER -typedef unsigned __int64 ffi_arg; -typedef __int64 ffi_sarg; -#else -typedef unsigned long long ffi_arg; -typedef long long ffi_sarg; -#endif -#else -#if defined __x86_64__ && defined __ILP32__ -#define FFI_SIZEOF_ARG 8 -#define FFI_SIZEOF_JAVA_RAW 4 -typedef unsigned long long ffi_arg; -typedef long long ffi_sarg; -#else -typedef unsigned long ffi_arg; -typedef signed long ffi_sarg; -#endif -#endif - -typedef enum ffi_abi { - FFI_FIRST_ABI = 0, - - /* ---- Intel x86 Win32 ---------- */ -#ifdef X86_WIN32 - FFI_SYSV, - FFI_STDCALL, - FFI_THISCALL, - FFI_FASTCALL, - FFI_MS_CDECL, - FFI_LAST_ABI, -#ifdef _MSC_VER - FFI_DEFAULT_ABI = FFI_MS_CDECL -#else - FFI_DEFAULT_ABI = FFI_SYSV -#endif - -#elif defined(X86_WIN64) - FFI_WIN64, - FFI_LAST_ABI, - FFI_DEFAULT_ABI = FFI_WIN64 - -#else - /* ---- Intel x86 and AMD x86-64 - */ - FFI_SYSV, - FFI_UNIX64, /* Unix variants all use the same ABI for x86-64 */ - FFI_LAST_ABI, -#if defined(__i386__) || defined(__i386) - FFI_DEFAULT_ABI = FFI_SYSV -#else - FFI_DEFAULT_ABI = FFI_UNIX64 -#endif -#endif -} ffi_abi; -#endif - -/* ---- Definitions for closures ----------------------------------------- */ - -#define FFI_CLOSURES 1 -#define FFI_TYPE_SMALL_STRUCT_1B (FFI_TYPE_LAST + 1) -#define FFI_TYPE_SMALL_STRUCT_2B (FFI_TYPE_LAST + 2) -#define FFI_TYPE_SMALL_STRUCT_4B (FFI_TYPE_LAST + 3) -#define FFI_TYPE_MS_STRUCT (FFI_TYPE_LAST + 4) - -#if defined (X86_64) || (defined (__x86_64__) && defined (X86_DARWIN)) -#define FFI_TRAMPOLINE_SIZE 24 -#define FFI_NATIVE_RAW_API 0 -#else -#ifdef X86_WIN32 -#define FFI_TRAMPOLINE_SIZE 52 -#else -#ifdef X86_WIN64 -#define FFI_TRAMPOLINE_SIZE 29 -#define FFI_NATIVE_RAW_API 0 -#define FFI_NO_RAW_API 1 -#else -#define FFI_TRAMPOLINE_SIZE 10 -#endif -#endif -#ifndef X86_WIN64 -#define FFI_NATIVE_RAW_API 1 /* x86 has native raw api support */ -#endif -#endif - -#endif - diff --git a/lib/wrappers/libffi/common/malloc_closure.c b/lib/wrappers/libffi/common/malloc_closure.c deleted file mode 100644 index 5b33aa4ca..000000000 --- a/lib/wrappers/libffi/common/malloc_closure.c +++ /dev/null @@ -1,110 +0,0 @@ -#include -#ifdef MS_WIN32 -#include -#else -#include -#include -# if !defined(MAP_ANONYMOUS) && defined(MAP_ANON) -# define MAP_ANONYMOUS MAP_ANON -# endif -#endif -#include "ctypes.h" - -/* BLOCKSIZE can be adjusted. Larger blocksize will take a larger memory - overhead, but allocate less blocks from the system. It may be that some - systems have a limit of how many mmap'd blocks can be open. -*/ - -#define BLOCKSIZE _pagesize - -/* #define MALLOC_CLOSURE_DEBUG */ /* enable for some debugging output */ - -/******************************************************************/ - -typedef union _tagITEM { - ffi_closure closure; - union _tagITEM *next; -} ITEM; - -static ITEM *free_list; -static int _pagesize; - -static void more_core(void) -{ - ITEM *item; - int count, i; - -/* determine the pagesize */ -#ifdef MS_WIN32 - if (!_pagesize) { - SYSTEM_INFO systeminfo; - GetSystemInfo(&systeminfo); - _pagesize = systeminfo.dwPageSize; - } -#else - if (!_pagesize) { -#ifdef _SC_PAGESIZE - _pagesize = sysconf(_SC_PAGESIZE); -#else - _pagesize = getpagesize(); -#endif - } -#endif - - /* calculate the number of nodes to allocate */ - count = BLOCKSIZE / sizeof(ITEM); - - /* allocate a memory block */ -#ifdef MS_WIN32 - item = (ITEM *)VirtualAlloc(NULL, - count * sizeof(ITEM), - MEM_COMMIT, - PAGE_EXECUTE_READWRITE); - if (item == NULL) - return; -#else - item = (ITEM *)mmap(NULL, - count * sizeof(ITEM), - PROT_READ | PROT_WRITE | PROT_EXEC, - MAP_PRIVATE | MAP_ANONYMOUS, - -1, - 0); - if (item == (void *)MAP_FAILED) - return; -#endif - -#ifdef MALLOC_CLOSURE_DEBUG - printf("block at %p allocated (%d bytes), %d ITEMs\n", - item, count * sizeof(ITEM), count); -#endif - /* put them into the free list */ - for (i = 0; i < count; ++i) { - item->next = free_list; - free_list = item; - ++item; - } -} - -/******************************************************************/ - -/* put the item back into the free list */ -void ffi_closure_free(void *p) -{ - ITEM *item = (ITEM *)p; - item->next = free_list; - free_list = item; -} - -/* return one item from the free list, allocating more if needed */ -void *ffi_closure_alloc(size_t ignored, void** codeloc) -{ - ITEM *item; - if (!free_list) - more_core(); - if (!free_list) - return NULL; - item = free_list; - free_list = item->next; - *codeloc = (void *)item; - return (void *)item; -} diff --git a/lib/wrappers/libffi/common/raw_api.c b/lib/wrappers/libffi/common/raw_api.c deleted file mode 100644 index ce21372e2..000000000 --- a/lib/wrappers/libffi/common/raw_api.c +++ /dev/null @@ -1,254 +0,0 @@ -/* ----------------------------------------------------------------------- - raw_api.c - Copyright (c) 1999, 2008 Red Hat, Inc. - - Author: Kresten Krab Thorup - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files (the - ``Software''), to deal in the Software without restriction, including - without limitation the rights to use, copy, modify, merge, publish, - distribute, sublicense, and/or sell copies of the Software, and to - permit persons to whom the Software is furnished to do so, subject to - the following conditions: - - The above copyright notice and this permission notice shall be included - in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - DEALINGS IN THE SOFTWARE. - ----------------------------------------------------------------------- */ - -/* This file defines generic functions for use with the raw api. */ - -#include -#include - -#if !FFI_NO_RAW_API - -size_t -ffi_raw_size (ffi_cif *cif) -{ - size_t result = 0; - int i; - - ffi_type **at = cif->arg_types; - - for (i = cif->nargs-1; i >= 0; i--, at++) - { -#if !FFI_NO_STRUCTS - if ((*at)->type == FFI_TYPE_STRUCT) - result += ALIGN (sizeof (void*), FFI_SIZEOF_ARG); - else -#endif - result += ALIGN ((*at)->size, FFI_SIZEOF_ARG); - } - - return result; -} - - -void -ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args) -{ - unsigned i; - ffi_type **tp = cif->arg_types; - -#if WORDS_BIGENDIAN - - for (i = 0; i < cif->nargs; i++, tp++, args++) - { - switch ((*tp)->type) - { - case FFI_TYPE_UINT8: - case FFI_TYPE_SINT8: - *args = (void*) ((char*)(raw++) + FFI_SIZEOF_ARG - 1); - break; - - case FFI_TYPE_UINT16: - case FFI_TYPE_SINT16: - *args = (void*) ((char*)(raw++) + FFI_SIZEOF_ARG - 2); - break; - -#if FFI_SIZEOF_ARG >= 4 - case FFI_TYPE_UINT32: - case FFI_TYPE_SINT32: - *args = (void*) ((char*)(raw++) + FFI_SIZEOF_ARG - 4); - break; -#endif - -#if !FFI_NO_STRUCTS - case FFI_TYPE_STRUCT: - *args = (raw++)->ptr; - break; -#endif - - case FFI_TYPE_POINTER: - *args = (void*) &(raw++)->ptr; - break; - - default: - *args = raw; - raw += ALIGN ((*tp)->size, FFI_SIZEOF_ARG) / FFI_SIZEOF_ARG; - } - } - -#else /* WORDS_BIGENDIAN */ - -#if !PDP - - /* then assume little endian */ - for (i = 0; i < cif->nargs; i++, tp++, args++) - { -#if !FFI_NO_STRUCTS - if ((*tp)->type == FFI_TYPE_STRUCT) - { - *args = (raw++)->ptr; - } - else -#endif - { - *args = (void*) raw; - raw += ALIGN ((*tp)->size, sizeof (void*)) / sizeof (void*); - } - } - -#else -#error "pdp endian not supported" -#endif /* ! PDP */ - -#endif /* WORDS_BIGENDIAN */ -} - -void -ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw) -{ - unsigned i; - ffi_type **tp = cif->arg_types; - - for (i = 0; i < cif->nargs; i++, tp++, args++) - { - switch ((*tp)->type) - { - case FFI_TYPE_UINT8: - (raw++)->uint = *(UINT8*) (*args); - break; - - case FFI_TYPE_SINT8: - (raw++)->sint = *(SINT8*) (*args); - break; - - case FFI_TYPE_UINT16: - (raw++)->uint = *(UINT16*) (*args); - break; - - case FFI_TYPE_SINT16: - (raw++)->sint = *(SINT16*) (*args); - break; - -#if FFI_SIZEOF_ARG >= 4 - case FFI_TYPE_UINT32: - (raw++)->uint = *(UINT32*) (*args); - break; - - case FFI_TYPE_SINT32: - (raw++)->sint = *(SINT32*) (*args); - break; -#endif - -#if !FFI_NO_STRUCTS - case FFI_TYPE_STRUCT: - (raw++)->ptr = *args; - break; -#endif - - case FFI_TYPE_POINTER: - (raw++)->ptr = **(void***) args; - break; - - default: - memcpy ((void*) raw->data, (void*)*args, (*tp)->size); - raw += ALIGN ((*tp)->size, FFI_SIZEOF_ARG) / FFI_SIZEOF_ARG; - } - } -} - -#if !FFI_NATIVE_RAW_API - - -/* This is a generic definition of ffi_raw_call, to be used if the - * native system does not provide a machine-specific implementation. - * Having this, allows code to be written for the raw API, without - * the need for system-specific code to handle input in that format; - * these following couple of functions will handle the translation forth - * and back automatically. */ - -void ffi_raw_call (ffi_cif *cif, void (*fn)(void), void *rvalue, ffi_raw *raw) -{ - void **avalue = (void**) alloca (cif->nargs * sizeof (void*)); - ffi_raw_to_ptrarray (cif, raw, avalue); - ffi_call (cif, fn, rvalue, avalue); -} - -#if FFI_CLOSURES /* base system provides closures */ - -static void -ffi_translate_args (ffi_cif *cif, void *rvalue, - void **avalue, void *user_data) -{ - ffi_raw *raw = (ffi_raw*)alloca (ffi_raw_size (cif)); - ffi_raw_closure *cl = (ffi_raw_closure*)user_data; - - ffi_ptrarray_to_raw (cif, avalue, raw); - (*cl->fun) (cif, rvalue, raw, cl->user_data); -} - -ffi_status -ffi_prep_raw_closure_loc (ffi_raw_closure* cl, - ffi_cif *cif, - void (*fun)(ffi_cif*,void*,ffi_raw*,void*), - void *user_data, - void *codeloc) -{ - ffi_status status; - - status = ffi_prep_closure_loc ((ffi_closure*) cl, - cif, - &ffi_translate_args, - codeloc, - codeloc); - if (status == FFI_OK) - { - cl->fun = fun; - cl->user_data = user_data; - } - - return status; -} - -#endif /* FFI_CLOSURES */ -#endif /* !FFI_NATIVE_RAW_API */ - -#if FFI_CLOSURES - -/* Again, here is the generic version of ffi_prep_raw_closure, which - * will install an intermediate "hub" for translation of arguments from - * the pointer-array format, to the raw format */ - -ffi_status -ffi_prep_raw_closure (ffi_raw_closure* cl, - ffi_cif *cif, - void (*fun)(ffi_cif*,void*,ffi_raw*,void*), - void *user_data) -{ - return ffi_prep_raw_closure_loc (cl, cif, fun, user_data, cl); -} - -#endif /* FFI_CLOSURES */ - -#endif /* !FFI_NO_RAW_API */ diff --git a/lib/wrappers/libffi/gcc/closures.c b/lib/wrappers/libffi/gcc/closures.c deleted file mode 100644 index c0ee06891..000000000 --- a/lib/wrappers/libffi/gcc/closures.c +++ /dev/null @@ -1,627 +0,0 @@ -/* ----------------------------------------------------------------------- - closures.c - Copyright (c) 2007, 2009, 2010 Red Hat, Inc. - Copyright (C) 2007, 2009, 2010 Free Software Foundation, Inc - Copyright (c) 2011 Plausible Labs Cooperative, Inc. - - Code to allocate and deallocate memory for closures. - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files (the - ``Software''), to deal in the Software without restriction, including - without limitation the rights to use, copy, modify, merge, publish, - distribute, sublicense, and/or sell copies of the Software, and to - permit persons to whom the Software is furnished to do so, subject to - the following conditions: - - The above copyright notice and this permission notice shall be included - in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - DEALINGS IN THE SOFTWARE. - ----------------------------------------------------------------------- */ - -#if defined __linux__ && !defined _GNU_SOURCE -#define _GNU_SOURCE 1 -#endif - -#include -#include - -#if !FFI_MMAP_EXEC_WRIT && !FFI_EXEC_TRAMPOLINE_TABLE -# if __gnu_linux__ -/* This macro indicates it may be forbidden to map anonymous memory - with both write and execute permission. Code compiled when this - option is defined will attempt to map such pages once, but if it - fails, it falls back to creating a temporary file in a writable and - executable filesystem and mapping pages from it into separate - locations in the virtual memory space, one location writable and - another executable. */ -# define FFI_MMAP_EXEC_WRIT 1 -# define HAVE_MNTENT 1 -# endif -# if defined(X86_WIN32) || defined(X86_WIN64) || defined(__OS2__) -/* Windows systems may have Data Execution Protection (DEP) enabled, - which requires the use of VirtualMalloc/VirtualFree to alloc/free - executable memory. */ -# define FFI_MMAP_EXEC_WRIT 1 -# endif -#endif - -#if FFI_MMAP_EXEC_WRIT && !defined FFI_MMAP_EXEC_SELINUX -# ifdef __linux__ -/* When defined to 1 check for SELinux and if SELinux is active, - don't attempt PROT_EXEC|PROT_WRITE mapping at all, as that - might cause audit messages. */ -# define FFI_MMAP_EXEC_SELINUX 1 -# endif -#endif - -#if FFI_CLOSURES - -# if FFI_EXEC_TRAMPOLINE_TABLE - -// Per-target implementation; It's unclear what can reasonable be shared -// between two OS/architecture implementations. - -# elif FFI_MMAP_EXEC_WRIT /* !FFI_EXEC_TRAMPOLINE_TABLE */ - -#define USE_LOCKS 1 -#define USE_DL_PREFIX 1 -#ifdef __GNUC__ -#ifndef USE_BUILTIN_FFS -#define USE_BUILTIN_FFS 1 -#endif -#endif - -/* We need to use mmap, not sbrk. */ -#define HAVE_MORECORE 0 - -/* We could, in theory, support mremap, but it wouldn't buy us anything. */ -#define HAVE_MREMAP 0 - -/* We have no use for this, so save some code and data. */ -#define NO_MALLINFO 1 - -/* We need all allocations to be in regular segments, otherwise we - lose track of the corresponding code address. */ -#define DEFAULT_MMAP_THRESHOLD MAX_SIZE_T - -/* Don't allocate more than a page unless needed. */ -#define DEFAULT_GRANULARITY ((size_t)malloc_getpagesize) - -#if FFI_CLOSURE_TEST -/* Don't release single pages, to avoid a worst-case scenario of - continuously allocating and releasing single pages, but release - pairs of pages, which should do just as well given that allocations - are likely to be small. */ -#define DEFAULT_TRIM_THRESHOLD ((size_t)malloc_getpagesize) -#endif - -#include -#include -#include -#include -#ifndef _MSC_VER -#include -#endif -#include -#include -#if !defined(X86_WIN32) && !defined(X86_WIN64) -#ifdef HAVE_MNTENT -#include -#endif /* HAVE_MNTENT */ -#include -#include - -/* We don't want sys/mman.h to be included after we redefine mmap and - dlmunmap. */ -#include -#define LACKS_SYS_MMAN_H 1 - -#if FFI_MMAP_EXEC_SELINUX -#include -#include - -static int selinux_enabled = -1; - -static int -selinux_enabled_check (void) -{ - struct statfs sfs; - FILE *f; - char *buf = NULL; - size_t len = 0; - - if (statfs ("/selinux", &sfs) >= 0 - && (unsigned int) sfs.f_type == 0xf97cff8cU) - return 1; - f = fopen ("/proc/mounts", "r"); - if (f == NULL) - return 0; - while (getline (&buf, &len, f) >= 0) - { - char *p = strchr (buf, ' '); - if (p == NULL) - break; - p = strchr (p + 1, ' '); - if (p == NULL) - break; - if (strncmp (p + 1, "selinuxfs ", 10) == 0) - { - free (buf); - fclose (f); - return 1; - } - } - free (buf); - fclose (f); - return 0; -} - -#define is_selinux_enabled() (selinux_enabled >= 0 ? selinux_enabled \ - : (selinux_enabled = selinux_enabled_check ())) - -#else - -#define is_selinux_enabled() 0 - -#endif /* !FFI_MMAP_EXEC_SELINUX */ - -/* On PaX enable kernels that have MPROTECT enable we can't use PROT_EXEC. */ -#ifdef FFI_MMAP_EXEC_EMUTRAMP_PAX -#include - -static int emutramp_enabled = -1; - -static int -emutramp_enabled_check (void) -{ - if (getenv ("FFI_DISABLE_EMUTRAMP") == NULL) - return 1; - else - return 0; -} - -#define is_emutramp_enabled() (emutramp_enabled >= 0 ? emutramp_enabled \ - : (emutramp_enabled = emutramp_enabled_check ())) -#endif /* FFI_MMAP_EXEC_EMUTRAMP_PAX */ - -#elif defined (__CYGWIN__) || defined(__INTERIX) - -#include - -/* Cygwin is Linux-like, but not quite that Linux-like. */ -#define is_selinux_enabled() 0 - -#endif /* !defined(X86_WIN32) && !defined(X86_WIN64) */ - -#ifndef FFI_MMAP_EXEC_EMUTRAMP_PAX -#define is_emutramp_enabled() 0 -#endif /* FFI_MMAP_EXEC_EMUTRAMP_PAX */ - -#if !(defined(X86_WIN32) || defined(X86_WIN64) || defined(__OS2__)) || defined (__CYGWIN__) || defined(__INTERIX) -/* Use these for mmap and munmap within dlmalloc.c. */ -static void *dlmmap(void *, size_t, int, int, int, off_t); -static int dlmunmap(void *, size_t); -#endif /* !(defined(X86_WIN32) || defined(X86_WIN64) || defined(__OS2__)) || defined (__CYGWIN__) || defined(__INTERIX) */ - -#if !(defined(X86_WIN32) || defined(X86_WIN64) || defined(__OS2__)) || defined (__CYGWIN__) || defined(__INTERIX) - -/* A mutex used to synchronize access to *exec* variables in this file. */ -static pthread_mutex_t open_temp_exec_file_mutex = PTHREAD_MUTEX_INITIALIZER; - -/* A file descriptor of a temporary file from which we'll map - executable pages. */ -static int execfd = -1; - -/* The amount of space already allocated from the temporary file. */ -static size_t execsize = 0; - -/* Open a temporary file name, and immediately unlink it. */ -static int -open_temp_exec_file_name (char *name) -{ - int fd = mkstemp (name); - - if (fd != -1) - unlink (name); - - return fd; -} - -/* Open a temporary file in the named directory. */ -static int -open_temp_exec_file_dir (const char *dir) -{ - static const char suffix[] = "/ffiXXXXXX"; - int lendir = strlen (dir); - char *tempname = __builtin_alloca (lendir + sizeof (suffix)); - - if (!tempname) - return -1; - - memcpy (tempname, dir, lendir); - memcpy (tempname + lendir, suffix, sizeof (suffix)); - - return open_temp_exec_file_name (tempname); -} - -/* Open a temporary file in the directory in the named environment - variable. */ -static int -open_temp_exec_file_env (const char *envvar) -{ - const char *value = getenv (envvar); - - if (!value) - return -1; - - return open_temp_exec_file_dir (value); -} - -#ifdef HAVE_MNTENT -/* Open a temporary file in an executable and writable mount point - listed in the mounts file. Subsequent calls with the same mounts - keep searching for mount points in the same file. Providing NULL - as the mounts file closes the file. */ -static int -open_temp_exec_file_mnt (const char *mounts) -{ - static const char *last_mounts; - static FILE *last_mntent; - - if (mounts != last_mounts) - { - if (last_mntent) - endmntent (last_mntent); - - last_mounts = mounts; - - if (mounts) - last_mntent = setmntent (mounts, "r"); - else - last_mntent = NULL; - } - - if (!last_mntent) - return -1; - - for (;;) - { - int fd; - struct mntent mnt; - char buf[MAXPATHLEN * 3]; - - if (getmntent_r (last_mntent, &mnt, buf, sizeof (buf)) == NULL) - return -1; - - if (hasmntopt (&mnt, "ro") - || hasmntopt (&mnt, "noexec") - || access (mnt.mnt_dir, W_OK)) - continue; - - fd = open_temp_exec_file_dir (mnt.mnt_dir); - - if (fd != -1) - return fd; - } -} -#endif /* HAVE_MNTENT */ - -/* Instructions to look for a location to hold a temporary file that - can be mapped in for execution. */ -static struct -{ - int (*func)(const char *); - const char *arg; - int repeat; -} open_temp_exec_file_opts[] = { - { open_temp_exec_file_env, "TMPDIR", 0 }, - { open_temp_exec_file_dir, "/tmp", 0 }, - { open_temp_exec_file_dir, "/var/tmp", 0 }, - { open_temp_exec_file_dir, "/dev/shm", 0 }, - { open_temp_exec_file_env, "HOME", 0 }, -#ifdef HAVE_MNTENT - { open_temp_exec_file_mnt, "/etc/mtab", 1 }, - { open_temp_exec_file_mnt, "/proc/mounts", 1 }, -#endif /* HAVE_MNTENT */ -}; - -/* Current index into open_temp_exec_file_opts. */ -static int open_temp_exec_file_opts_idx = 0; - -/* Reset a current multi-call func, then advances to the next entry. - If we're at the last, go back to the first and return nonzero, - otherwise return zero. */ -static int -open_temp_exec_file_opts_next (void) -{ - if (open_temp_exec_file_opts[open_temp_exec_file_opts_idx].repeat) - open_temp_exec_file_opts[open_temp_exec_file_opts_idx].func (NULL); - - open_temp_exec_file_opts_idx++; - if (open_temp_exec_file_opts_idx - == (sizeof (open_temp_exec_file_opts) - / sizeof (*open_temp_exec_file_opts))) - { - open_temp_exec_file_opts_idx = 0; - return 1; - } - - return 0; -} - -/* Return a file descriptor of a temporary zero-sized file in a - writable and exexutable filesystem. */ -static int -open_temp_exec_file (void) -{ - int fd; - - do - { - fd = open_temp_exec_file_opts[open_temp_exec_file_opts_idx].func - (open_temp_exec_file_opts[open_temp_exec_file_opts_idx].arg); - - if (!open_temp_exec_file_opts[open_temp_exec_file_opts_idx].repeat - || fd == -1) - { - if (open_temp_exec_file_opts_next ()) - break; - } - } - while (fd == -1); - - return fd; -} - -/* Map in a chunk of memory from the temporary exec file into separate - locations in the virtual memory address space, one writable and one - executable. Returns the address of the writable portion, after - storing an offset to the corresponding executable portion at the - last word of the requested chunk. */ -static void * -dlmmap_locked (void *start, size_t length, int prot, int flags, off_t offset) -{ - void *ptr; - - if (execfd == -1) - { - open_temp_exec_file_opts_idx = 0; - retry_open: - execfd = open_temp_exec_file (); - if (execfd == -1) - return MFAIL; - } - - offset = execsize; - - if (ftruncate (execfd, offset + length)) - return MFAIL; - - flags &= ~(MAP_PRIVATE | MAP_ANONYMOUS); - flags |= MAP_SHARED; - - ptr = mmap (NULL, length, (prot & ~PROT_WRITE) | PROT_EXEC, - flags, execfd, offset); - if (ptr == MFAIL) - { - if (!offset) - { - close (execfd); - goto retry_open; - } - ftruncate (execfd, offset); - return MFAIL; - } - else if (!offset - && open_temp_exec_file_opts[open_temp_exec_file_opts_idx].repeat) - open_temp_exec_file_opts_next (); - - start = mmap (start, length, prot, flags, execfd, offset); - - if (start == MFAIL) - { - munmap (ptr, length); - ftruncate (execfd, offset); - return start; - } - - mmap_exec_offset ((char *)start, length) = (char*)ptr - (char*)start; - - execsize += length; - - return start; -} - -/* Map in a writable and executable chunk of memory if possible. - Failing that, fall back to dlmmap_locked. */ -static void * -dlmmap (void *start, size_t length, int prot, - int flags, int fd, off_t offset) -{ - void *ptr; - - assert (start == NULL && length % malloc_getpagesize == 0 - && prot == (PROT_READ | PROT_WRITE) - && flags == (MAP_PRIVATE | MAP_ANONYMOUS) - && fd == -1 && offset == 0); - -#if FFI_CLOSURE_TEST - printf ("mapping in %zi\n", length); -#endif - - if (execfd == -1 && is_emutramp_enabled ()) - { - ptr = mmap (start, length, prot & ~PROT_EXEC, flags, fd, offset); - return ptr; - } - - if (execfd == -1 && !is_selinux_enabled ()) - { - ptr = mmap (start, length, prot | PROT_EXEC, flags, fd, offset); - - if (ptr != MFAIL || (errno != EPERM && errno != EACCES)) - /* Cool, no need to mess with separate segments. */ - return ptr; - - /* If MREMAP_DUP is ever introduced and implemented, try mmap - with ((prot & ~PROT_WRITE) | PROT_EXEC) and mremap with - MREMAP_DUP and prot at this point. */ - } - - if (execsize == 0 || execfd == -1) - { - pthread_mutex_lock (&open_temp_exec_file_mutex); - ptr = dlmmap_locked (start, length, prot, flags, offset); - pthread_mutex_unlock (&open_temp_exec_file_mutex); - - return ptr; - } - - return dlmmap_locked (start, length, prot, flags, offset); -} - -/* Release memory at the given address, as well as the corresponding - executable page if it's separate. */ -static int -dlmunmap (void *start, size_t length) -{ - /* We don't bother decreasing execsize or truncating the file, since - we can't quite tell whether we're unmapping the end of the file. - We don't expect frequent deallocation anyway. If we did, we - could locate pages in the file by writing to the pages being - deallocated and checking that the file contents change. - Yuck. */ - msegmentptr seg = segment_holding (gm, start); - void *code; - -#if FFI_CLOSURE_TEST - printf ("unmapping %zi\n", length); -#endif - - if (seg && (code = add_segment_exec_offset (start, seg)) != start) - { - int ret = munmap (code, length); - if (ret) - return ret; - } - - return munmap (start, length); -} - -#if FFI_CLOSURE_FREE_CODE -/* Return segment holding given code address. */ -static msegmentptr -segment_holding_code (mstate m, char* addr) -{ - msegmentptr sp = &m->seg; - for (;;) { - if (addr >= add_segment_exec_offset (sp->base, sp) - && addr < add_segment_exec_offset (sp->base, sp) + sp->size) - return sp; - if ((sp = sp->next) == 0) - return 0; - } -} -#endif - -#endif /* !(defined(X86_WIN32) || defined(X86_WIN64) || defined(__OS2__)) || defined (__CYGWIN__) || defined(__INTERIX) */ - -/* Allocate a chunk of memory with the given size. Returns a pointer - to the writable address, and sets *CODE to the executable - corresponding virtual address. */ -void * -ffi_closure_alloc (size_t size, void **code) -{ - *code = malloc(size); - return *code; -#if 0 - void *ptr; - - if (!code) - return NULL; - - ptr = dlmalloc (size); - - if (ptr) - { - msegmentptr seg = segment_holding (gm, ptr); - - *code = add_segment_exec_offset (ptr, seg); - } - - return ptr; -#endif -} - -/* Release a chunk of memory allocated with ffi_closure_alloc. If - FFI_CLOSURE_FREE_CODE is nonzero, the given address can be the - writable or the executable address given. Otherwise, only the - writable address can be provided here. */ -void -ffi_closure_free (void *ptr) -{ -#if 0 -#if FFI_CLOSURE_FREE_CODE - msegmentptr seg = segment_holding_code(gm, ptr); - - if (seg) - ptr = sub_segment_exec_offset(ptr, seg); -#endif - - dlfree(ptr); -#endif - free(ptr); -} - - -#if FFI_CLOSURE_TEST -/* Do some internal sanity testing to make sure allocation and - deallocation of pages are working as intended. */ -int main () -{ - void *p[3]; -#define GET(idx, len) do { p[idx] = dlmalloc (len); printf ("allocated %zi for p[%i]\n", (len), (idx)); } while (0) -#define PUT(idx) do { printf ("freeing p[%i]\n", (idx)); dlfree (p[idx]); } while (0) - GET (0, malloc_getpagesize / 2); - GET (1, 2 * malloc_getpagesize - 64 * sizeof (void*)); - PUT (1); - GET (1, 2 * malloc_getpagesize); - GET (2, malloc_getpagesize / 2); - PUT (1); - PUT (0); - PUT (2); - return 0; -} -#endif /* FFI_CLOSURE_TEST */ -# else /* ! FFI_MMAP_EXEC_WRIT */ - -/* On many systems, memory returned by malloc is writable and - executable, so just use it. */ - -#include - -void * -ffi_closure_alloc (size_t size, void **code) -{ - if (!code) - return NULL; - - return *code = malloc (size); -} - -void -ffi_closure_free (void *ptr) -{ - free (ptr); -} - -# endif /* ! FFI_MMAP_EXEC_WRIT */ -#endif /* FFI_CLOSURES */ diff --git a/lib/wrappers/libffi/gcc/ffi.c b/lib/wrappers/libffi/gcc/ffi.c deleted file mode 100644 index 0600414d4..000000000 --- a/lib/wrappers/libffi/gcc/ffi.c +++ /dev/null @@ -1,841 +0,0 @@ -/* ----------------------------------------------------------------------- - ffi.c - Copyright (c) 1996, 1998, 1999, 2001, 2007, 2008 Red Hat, Inc. - Copyright (c) 2002 Ranjit Mathew - Copyright (c) 2002 Bo Thorsen - Copyright (c) 2002 Roger Sayle - Copyright (C) 2008, 2010 Free Software Foundation, Inc. - - x86 Foreign Function Interface - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files (the - ``Software''), to deal in the Software without restriction, including - without limitation the rights to use, copy, modify, merge, publish, - distribute, sublicense, and/or sell copies of the Software, and to - permit persons to whom the Software is furnished to do so, subject to - the following conditions: - - The above copyright notice and this permission notice shall be included - in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - DEALINGS IN THE SOFTWARE. - ----------------------------------------------------------------------- */ - -#if !defined(__x86_64__) || defined(_WIN64) - -#ifdef _WIN64 -#include -#endif - -#include -#include - -#include - -/* ffi_prep_args is called by the assembly routine once stack space - has been allocated for the function's arguments */ - -void ffi_prep_args(char *stack, extended_cif *ecif) -{ - register unsigned int i; - register void **p_argv; - register char *argp; - register ffi_type **p_arg; -#ifdef X86_WIN32 - size_t p_stack_args[2]; - void *p_stack_data[2]; - char *argp2 = stack; - int stack_args_count = 0; - int cabi = ecif->cif->abi; -#endif - - argp = stack; - - if ((ecif->cif->flags == FFI_TYPE_STRUCT - || ecif->cif->flags == FFI_TYPE_MS_STRUCT) -#ifdef X86_WIN64 - && (ecif->cif->rtype->size != 1 && ecif->cif->rtype->size != 2 - && ecif->cif->rtype->size != 4 && ecif->cif->rtype->size != 8) -#endif - ) - { - *(void **) argp = ecif->rvalue; -#ifdef X86_WIN32 - /* For fastcall/thiscall this is first register-passed - argument. */ - if (cabi == FFI_THISCALL || cabi == FFI_FASTCALL) - { - p_stack_args[stack_args_count] = sizeof (void*); - p_stack_data[stack_args_count] = argp; - ++stack_args_count; - } -#endif - argp += sizeof(void*); - } - - p_argv = ecif->avalue; - - for (i = ecif->cif->nargs, p_arg = ecif->cif->arg_types; - i != 0; - i--, p_arg++) - { - size_t z; - - /* Align if necessary */ - if ((sizeof(void*) - 1) & (size_t) argp) - argp = (char *) ALIGN(argp, sizeof(void*)); - - z = (*p_arg)->size; -#ifdef X86_WIN64 - if (z > sizeof(ffi_arg) - || ((*p_arg)->type == FFI_TYPE_STRUCT - && (z != 1 && z != 2 && z != 4 && z != 8)) -#if FFI_TYPE_DOUBLE != FFI_TYPE_LONGDOUBLE - || ((*p_arg)->type == FFI_TYPE_LONGDOUBLE) -#endif - ) - { - z = sizeof(ffi_arg); - *(void **)argp = *p_argv; - } - else if ((*p_arg)->type == FFI_TYPE_FLOAT) - { - memcpy(argp, *p_argv, z); - } - else -#endif - if (z < sizeof(ffi_arg)) - { - z = sizeof(ffi_arg); - switch ((*p_arg)->type) - { - case FFI_TYPE_SINT8: - *(ffi_sarg *) argp = (ffi_sarg)*(SINT8 *)(* p_argv); - break; - - case FFI_TYPE_UINT8: - *(ffi_arg *) argp = (ffi_arg)*(UINT8 *)(* p_argv); - break; - - case FFI_TYPE_SINT16: - *(ffi_sarg *) argp = (ffi_sarg)*(SINT16 *)(* p_argv); - break; - - case FFI_TYPE_UINT16: - *(ffi_arg *) argp = (ffi_arg)*(UINT16 *)(* p_argv); - break; - - case FFI_TYPE_SINT32: - *(ffi_sarg *) argp = (ffi_sarg)*(SINT32 *)(* p_argv); - break; - - case FFI_TYPE_UINT32: - *(ffi_arg *) argp = (ffi_arg)*(UINT32 *)(* p_argv); - break; - - case FFI_TYPE_STRUCT: - *(ffi_arg *) argp = *(ffi_arg *)(* p_argv); - break; - - default: - FFI_ASSERT(0); - } - } - else - { - memcpy(argp, *p_argv, z); - } - -#ifdef X86_WIN32 - /* For thiscall/fastcall convention register-passed arguments - are the first two none-floating-point arguments with a size - smaller or equal to sizeof (void*). */ - if ((cabi == FFI_THISCALL && stack_args_count < 1) - || (cabi == FFI_FASTCALL && stack_args_count < 2)) - { - if (z <= 4 - && ((*p_arg)->type != FFI_TYPE_FLOAT - && (*p_arg)->type != FFI_TYPE_STRUCT)) - { - p_stack_args[stack_args_count] = z; - p_stack_data[stack_args_count] = argp; - ++stack_args_count; - } - } -#endif - p_argv++; -#ifdef X86_WIN64 - argp += (z + sizeof(void*) - 1) & ~(sizeof(void*) - 1); -#else - argp += z; -#endif - } - -#ifdef X86_WIN32 - /* We need to move the register-passed arguments for thiscall/fastcall - on top of stack, so that those can be moved to registers ecx/edx by - call-handler. */ - if (stack_args_count > 0) - { - size_t zz = (p_stack_args[0] + 3) & ~3; - char *h; - - /* Move first argument to top-stack position. */ - if (p_stack_data[0] != argp2) - { - h = alloca (zz + 1); - memcpy (h, p_stack_data[0], zz); - memmove (argp2 + zz, argp2, - (size_t) ((char *) p_stack_data[0] - (char*)argp2)); - memcpy (argp2, h, zz); - } - - argp2 += zz; - --stack_args_count; - if (zz > 4) - stack_args_count = 0; - - /* If we have a second argument, then move it on top - after the first one. */ - if (stack_args_count > 0 && p_stack_data[1] != argp2) - { - zz = p_stack_args[1]; - zz = (zz + 3) & ~3; - h = alloca (zz + 1); - h = alloca (zz + 1); - memcpy (h, p_stack_data[1], zz); - memmove (argp2 + zz, argp2, (size_t) ((char*) p_stack_data[1] - (char*)argp2)); - memcpy (argp2, h, zz); - } - } -#endif - return; -} - -/* Perform machine dependent cif processing */ -ffi_status ffi_prep_cif_machdep(ffi_cif *cif) -{ - unsigned int i; - ffi_type **ptr; - - /* Set the return type flag */ - switch (cif->rtype->type) - { - case FFI_TYPE_VOID: - case FFI_TYPE_UINT8: - case FFI_TYPE_UINT16: - case FFI_TYPE_SINT8: - case FFI_TYPE_SINT16: -#ifdef X86_WIN64 - case FFI_TYPE_UINT32: - case FFI_TYPE_SINT32: -#endif - case FFI_TYPE_SINT64: - case FFI_TYPE_FLOAT: - case FFI_TYPE_DOUBLE: -#ifndef X86_WIN64 -#if FFI_TYPE_DOUBLE != FFI_TYPE_LONGDOUBLE - case FFI_TYPE_LONGDOUBLE: -#endif -#endif - cif->flags = (unsigned) cif->rtype->type; - break; - - case FFI_TYPE_UINT64: -#ifdef X86_WIN64 - case FFI_TYPE_POINTER: -#endif - cif->flags = FFI_TYPE_SINT64; - break; - - case FFI_TYPE_STRUCT: -#ifndef X86 - if (cif->rtype->size == 1) - { - cif->flags = FFI_TYPE_SMALL_STRUCT_1B; /* same as char size */ - } - else if (cif->rtype->size == 2) - { - cif->flags = FFI_TYPE_SMALL_STRUCT_2B; /* same as short size */ - } - else if (cif->rtype->size == 4) - { -#ifdef X86_WIN64 - cif->flags = FFI_TYPE_SMALL_STRUCT_4B; -#else - cif->flags = FFI_TYPE_INT; /* same as int type */ -#endif - } - else if (cif->rtype->size == 8) - { - cif->flags = FFI_TYPE_SINT64; /* same as int64 type */ - } - else -#endif - { -#ifdef X86_WIN32 - if (cif->abi == FFI_MS_CDECL) - cif->flags = FFI_TYPE_MS_STRUCT; - else -#endif - cif->flags = FFI_TYPE_STRUCT; - /* allocate space for return value pointer */ - cif->bytes += ALIGN(sizeof(void*), FFI_SIZEOF_ARG); - } - break; - - default: -#ifdef X86_WIN64 - cif->flags = FFI_TYPE_SINT64; - break; - case FFI_TYPE_INT: - cif->flags = FFI_TYPE_SINT32; -#else - cif->flags = FFI_TYPE_INT; -#endif - break; - } - - for (ptr = cif->arg_types, i = cif->nargs; i > 0; i--, ptr++) - { - if (((*ptr)->alignment - 1) & cif->bytes) - cif->bytes = ALIGN(cif->bytes, (*ptr)->alignment); - cif->bytes += ALIGN((*ptr)->size, FFI_SIZEOF_ARG); - } - -#ifdef X86_WIN64 - /* ensure space for storing four registers */ - cif->bytes += 4 * sizeof(ffi_arg); -#endif - - cif->bytes = (cif->bytes + 15) & ~0xF; - - return FFI_OK; -} - -#ifdef X86_WIN64 -extern int -ffi_call_win64(void (*)(char *, extended_cif *), extended_cif *, - unsigned, unsigned, unsigned *, void (*fn)(void)); -#elif defined(X86_WIN32) -extern void -ffi_call_win32(void (*)(char *, extended_cif *), extended_cif *, - unsigned, unsigned, unsigned, unsigned *, void (*fn)(void)); -#else -extern void ffi_call_SYSV(void (*)(char *, extended_cif *), extended_cif *, - unsigned, unsigned, unsigned *, void (*fn)(void)); -#endif - -void ffi_call(ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue) -{ - extended_cif ecif; - - ecif.cif = cif; - ecif.avalue = avalue; - - /* If the return value is a struct and we don't have a return */ - /* value address then we need to make one */ - -#ifdef X86_WIN64 - if (rvalue == NULL - && cif->flags == FFI_TYPE_STRUCT - && cif->rtype->size != 1 && cif->rtype->size != 2 - && cif->rtype->size != 4 && cif->rtype->size != 8) - { - ecif.rvalue = alloca((cif->rtype->size + 0xF) & ~0xF); - } -#else - if (rvalue == NULL - && (cif->flags == FFI_TYPE_STRUCT - || cif->flags == FFI_TYPE_MS_STRUCT)) - { - ecif.rvalue = alloca(cif->rtype->size); - } -#endif - else - ecif.rvalue = rvalue; - - - switch (cif->abi) - { -#ifdef X86_WIN64 - case FFI_WIN64: - ffi_call_win64(ffi_prep_args, &ecif, cif->bytes, - cif->flags, ecif.rvalue, fn); - break; -#elif defined(X86_WIN32) - case FFI_SYSV: - case FFI_STDCALL: - case FFI_MS_CDECL: - ffi_call_win32(ffi_prep_args, &ecif, cif->abi, cif->bytes, cif->flags, - ecif.rvalue, fn); - break; - case FFI_THISCALL: - case FFI_FASTCALL: - { - unsigned int abi = cif->abi; - unsigned int i, passed_regs = 0; - - if (cif->flags == FFI_TYPE_STRUCT) - ++passed_regs; - - for (i=0; i < cif->nargs && passed_regs < 2;i++) - { - size_t sz; - - if (cif->arg_types[i]->type == FFI_TYPE_FLOAT - || cif->arg_types[i]->type == FFI_TYPE_STRUCT) - continue; - sz = (cif->arg_types[i]->size + 3) & ~3; - if (sz == 0 || sz > 4) - continue; - ++passed_regs; - } - if (passed_regs < 2 && abi == FFI_FASTCALL) - abi = FFI_THISCALL; - if (passed_regs < 1 && abi == FFI_THISCALL) - abi = FFI_STDCALL; - ffi_call_win32(ffi_prep_args, &ecif, abi, cif->bytes, cif->flags, - ecif.rvalue, fn); - } - break; -#else - case FFI_SYSV: - ffi_call_SYSV(ffi_prep_args, &ecif, cif->bytes, cif->flags, ecif.rvalue, - fn); - break; -#endif - default: - FFI_ASSERT(0); - break; - } -} - - -/** private members **/ - -/* The following __attribute__((regparm(1))) decorations will have no effect - on MSVC or SUNPRO_C -- standard conventions apply. */ -static void ffi_prep_incoming_args_SYSV (char *stack, void **ret, - void** args, ffi_cif* cif); -void FFI_HIDDEN ffi_closure_SYSV (ffi_closure *) - __attribute__ ((regparm(1))); -unsigned int FFI_HIDDEN ffi_closure_SYSV_inner (ffi_closure *, void **, void *) - __attribute__ ((regparm(1))); -void FFI_HIDDEN ffi_closure_raw_SYSV (ffi_raw_closure *) - __attribute__ ((regparm(1))); -#ifdef X86_WIN32 -void FFI_HIDDEN ffi_closure_raw_THISCALL (ffi_raw_closure *) - __attribute__ ((regparm(1))); -void FFI_HIDDEN ffi_closure_STDCALL (ffi_closure *) - __attribute__ ((regparm(1))); -void FFI_HIDDEN ffi_closure_THISCALL (ffi_closure *) - __attribute__ ((regparm(1))); -#endif -#ifdef X86_WIN64 -void FFI_HIDDEN ffi_closure_win64 (ffi_closure *); -#endif - -/* This function is jumped to by the trampoline */ - -#ifdef X86_WIN64 -void * FFI_HIDDEN -ffi_closure_win64_inner (ffi_closure *closure, void *args) { - ffi_cif *cif; - void **arg_area; - void *result; - void *resp = &result; - - cif = closure->cif; - arg_area = (void**) alloca (cif->nargs * sizeof (void*)); - - /* this call will initialize ARG_AREA, such that each - * element in that array points to the corresponding - * value on the stack; and if the function returns - * a structure, it will change RESP to point to the - * structure return address. */ - - ffi_prep_incoming_args_SYSV(args, &resp, arg_area, cif); - - (closure->fun) (cif, resp, arg_area, closure->user_data); - - /* The result is returned in rax. This does the right thing for - result types except for floats; we have to 'mov xmm0, rax' in the - caller to correct this. - TODO: structure sizes of 3 5 6 7 are returned by reference, too!!! - */ - return cif->rtype->size > sizeof(void *) ? resp : *(void **)resp; -} - -#else -unsigned int FFI_HIDDEN __attribute__ ((regparm(1))) -ffi_closure_SYSV_inner (ffi_closure *closure, void **respp, void *args) -{ - /* our various things... */ - ffi_cif *cif; - void **arg_area; - - cif = closure->cif; - arg_area = (void**) alloca (cif->nargs * sizeof (void*)); - - /* this call will initialize ARG_AREA, such that each - * element in that array points to the corresponding - * value on the stack; and if the function returns - * a structure, it will change RESP to point to the - * structure return address. */ - - ffi_prep_incoming_args_SYSV(args, respp, arg_area, cif); - - (closure->fun) (cif, *respp, arg_area, closure->user_data); - - return cif->flags; -} -#endif /* !X86_WIN64 */ - -static void -ffi_prep_incoming_args_SYSV(char *stack, void **rvalue, void **avalue, - ffi_cif *cif) -{ - register unsigned int i; - register void **p_argv; - register char *argp; - register ffi_type **p_arg; - - argp = stack; - -#ifdef X86_WIN64 - if (cif->rtype->size > sizeof(ffi_arg) - || (cif->flags == FFI_TYPE_STRUCT - && (cif->rtype->size != 1 && cif->rtype->size != 2 - && cif->rtype->size != 4 && cif->rtype->size != 8))) { - *rvalue = *(void **) argp; - argp += sizeof(void *); - } -#else - if ( cif->flags == FFI_TYPE_STRUCT - || cif->flags == FFI_TYPE_MS_STRUCT ) { - *rvalue = *(void **) argp; - argp += sizeof(void *); - } -#endif - - p_argv = avalue; - - for (i = cif->nargs, p_arg = cif->arg_types; (i != 0); i--, p_arg++) - { - size_t z; - - /* Align if necessary */ - if ((sizeof(void*) - 1) & (size_t) argp) { - argp = (char *) ALIGN(argp, sizeof(void*)); - } - -#ifdef X86_WIN64 - if ((*p_arg)->size > sizeof(ffi_arg) - || ((*p_arg)->type == FFI_TYPE_STRUCT - && ((*p_arg)->size != 1 && (*p_arg)->size != 2 - && (*p_arg)->size != 4 && (*p_arg)->size != 8))) - { - z = sizeof(void *); - *p_argv = *(void **)argp; - } - else -#endif - { - z = (*p_arg)->size; - - /* because we're little endian, this is what it turns into. */ - - *p_argv = (void*) argp; - } - - p_argv++; -#ifdef X86_WIN64 - argp += (z + sizeof(void*) - 1) & ~(sizeof(void*) - 1); -#else - argp += z; -#endif - } - - return; -} - -#define FFI_INIT_TRAMPOLINE_WIN64(TRAMP,FUN,CTX,MASK) \ -{ unsigned char *__tramp = (unsigned char*)(TRAMP); \ - void* __fun = (void*)(FUN); \ - void* __ctx = (void*)(CTX); \ - *(unsigned char*) &__tramp[0] = 0x41; \ - *(unsigned char*) &__tramp[1] = 0xbb; \ - *(unsigned int*) &__tramp[2] = MASK; /* mov $mask, %r11 */ \ - *(unsigned char*) &__tramp[6] = 0x48; \ - *(unsigned char*) &__tramp[7] = 0xb8; \ - *(void**) &__tramp[8] = __ctx; /* mov __ctx, %rax */ \ - *(unsigned char *) &__tramp[16] = 0x49; \ - *(unsigned char *) &__tramp[17] = 0xba; \ - *(void**) &__tramp[18] = __fun; /* mov __fun, %r10 */ \ - *(unsigned char *) &__tramp[26] = 0x41; \ - *(unsigned char *) &__tramp[27] = 0xff; \ - *(unsigned char *) &__tramp[28] = 0xe2; /* jmp %r10 */ \ - } - -/* How to make a trampoline. Derived from gcc/config/i386/i386.c. */ - -#define FFI_INIT_TRAMPOLINE(TRAMP,FUN,CTX) \ -{ unsigned char *__tramp = (unsigned char*)(TRAMP); \ - unsigned int __fun = (unsigned int)(FUN); \ - unsigned int __ctx = (unsigned int)(CTX); \ - unsigned int __dis = __fun - (__ctx + 10); \ - *(unsigned char*) &__tramp[0] = 0xb8; \ - *(unsigned int*) &__tramp[1] = __ctx; /* movl __ctx, %eax */ \ - *(unsigned char *) &__tramp[5] = 0xe9; \ - *(unsigned int*) &__tramp[6] = __dis; /* jmp __fun */ \ - } - -#define FFI_INIT_TRAMPOLINE_THISCALL(TRAMP,FUN,CTX,SIZE) \ -{ unsigned char *__tramp = (unsigned char*)(TRAMP); \ - unsigned int __fun = (unsigned int)(FUN); \ - unsigned int __ctx = (unsigned int)(CTX); \ - unsigned int __dis = __fun - (__ctx + 49); \ - unsigned short __size = (unsigned short)(SIZE); \ - *(unsigned int *) &__tramp[0] = 0x8324048b; /* mov (%esp), %eax */ \ - *(unsigned int *) &__tramp[4] = 0x4c890cec; /* sub $12, %esp */ \ - *(unsigned int *) &__tramp[8] = 0x04890424; /* mov %ecx, 4(%esp) */ \ - *(unsigned char*) &__tramp[12] = 0x24; /* mov %eax, (%esp) */ \ - *(unsigned char*) &__tramp[13] = 0xb8; \ - *(unsigned int *) &__tramp[14] = __size; /* mov __size, %eax */ \ - *(unsigned int *) &__tramp[18] = 0x08244c8d; /* lea 8(%esp), %ecx */ \ - *(unsigned int *) &__tramp[22] = 0x4802e8c1; /* shr $2, %eax ; dec %eax */ \ - *(unsigned short*) &__tramp[26] = 0x0b74; /* jz 1f */ \ - *(unsigned int *) &__tramp[28] = 0x8908518b; /* 2b: mov 8(%ecx), %edx */ \ - *(unsigned int *) &__tramp[32] = 0x04c18311; /* mov %edx, (%ecx) ; add $4, %ecx */ \ - *(unsigned char*) &__tramp[36] = 0x48; /* dec %eax */ \ - *(unsigned short*) &__tramp[37] = 0xf575; /* jnz 2b ; 1f: */ \ - *(unsigned char*) &__tramp[39] = 0xb8; \ - *(unsigned int*) &__tramp[40] = __ctx; /* movl __ctx, %eax */ \ - *(unsigned char *) &__tramp[44] = 0xe8; \ - *(unsigned int*) &__tramp[45] = __dis; /* call __fun */ \ - *(unsigned char*) &__tramp[49] = 0xc2; /* ret */ \ - *(unsigned short*) &__tramp[50] = (__size + 8); /* ret (__size + 8) */ \ - } - -#define FFI_INIT_TRAMPOLINE_STDCALL(TRAMP,FUN,CTX,SIZE) \ -{ unsigned char *__tramp = (unsigned char*)(TRAMP); \ - unsigned int __fun = (unsigned int)(FUN); \ - unsigned int __ctx = (unsigned int)(CTX); \ - unsigned int __dis = __fun - (__ctx + 10); \ - unsigned short __size = (unsigned short)(SIZE); \ - *(unsigned char*) &__tramp[0] = 0xb8; \ - *(unsigned int*) &__tramp[1] = __ctx; /* movl __ctx, %eax */ \ - *(unsigned char *) &__tramp[5] = 0xe8; \ - *(unsigned int*) &__tramp[6] = __dis; /* call __fun */ \ - *(unsigned char *) &__tramp[10] = 0xc2; \ - *(unsigned short*) &__tramp[11] = __size; /* ret __size */ \ - } - -/* the cif must already be prep'ed */ - -ffi_status -ffi_prep_closure_loc (ffi_closure* closure, - ffi_cif* cif, - void (*fun)(ffi_cif*,void*,void**,void*), - void *user_data, - void *codeloc) -{ -#ifdef X86_WIN64 -#define ISFLOAT(IDX) (cif->arg_types[IDX]->type == FFI_TYPE_FLOAT || cif->arg_types[IDX]->type == FFI_TYPE_DOUBLE) -#define FLAG(IDX) (cif->nargs>(IDX)&&ISFLOAT(IDX)?(1<<(IDX)):0) - if (cif->abi == FFI_WIN64) - { - int mask = FLAG(0)|FLAG(1)|FLAG(2)|FLAG(3); - FFI_INIT_TRAMPOLINE_WIN64 (&closure->tramp[0], - &ffi_closure_win64, - codeloc, mask); - /* make sure we can execute here */ - } -#else - if (cif->abi == FFI_SYSV) - { - FFI_INIT_TRAMPOLINE (&closure->tramp[0], - &ffi_closure_SYSV, - (void*)codeloc); - } -#ifdef X86_WIN32 - else if (cif->abi == FFI_THISCALL) - { - FFI_INIT_TRAMPOLINE_THISCALL (&closure->tramp[0], - &ffi_closure_THISCALL, - (void*)codeloc, - cif->bytes); - } - else if (cif->abi == FFI_STDCALL) - { - FFI_INIT_TRAMPOLINE_STDCALL (&closure->tramp[0], - &ffi_closure_STDCALL, - (void*)codeloc, cif->bytes); - } - else if (cif->abi == FFI_MS_CDECL) - { - FFI_INIT_TRAMPOLINE (&closure->tramp[0], - &ffi_closure_SYSV, - (void*)codeloc); - } -#endif /* X86_WIN32 */ -#endif /* !X86_WIN64 */ - else - { - return FFI_BAD_ABI; - } - - closure->cif = cif; - closure->user_data = user_data; - closure->fun = fun; - - return FFI_OK; -} - -/* ------- Native raw API support -------------------------------- */ - -#if !FFI_NO_RAW_API - -ffi_status -ffi_prep_raw_closure_loc (ffi_raw_closure* closure, - ffi_cif* cif, - void (*fun)(ffi_cif*,void*,ffi_raw*,void*), - void *user_data, - void *codeloc) -{ - int i; - - if (cif->abi != FFI_SYSV) { -#ifdef X86_WIN32 - if (cif->abi != FFI_THISCALL) -#endif - return FFI_BAD_ABI; - } - - /* we currently don't support certain kinds of arguments for raw - closures. This should be implemented by a separate assembly - language routine, since it would require argument processing, - something we don't do now for performance. */ - - for (i = cif->nargs-1; i >= 0; i--) - { - FFI_ASSERT (cif->arg_types[i]->type != FFI_TYPE_STRUCT); - FFI_ASSERT (cif->arg_types[i]->type != FFI_TYPE_LONGDOUBLE); - } - -#ifdef X86_WIN32 - if (cif->abi == FFI_SYSV) - { -#endif - FFI_INIT_TRAMPOLINE (&closure->tramp[0], &ffi_closure_raw_SYSV, - codeloc); -#ifdef X86_WIN32 - } - else if (cif->abi == FFI_THISCALL) - { - FFI_INIT_TRAMPOLINE_THISCALL (&closure->tramp[0], &ffi_closure_raw_THISCALL, - codeloc, cif->bytes); - } -#endif - closure->cif = cif; - closure->user_data = user_data; - closure->fun = fun; - - return FFI_OK; -} - -static void -ffi_prep_args_raw(char *stack, extended_cif *ecif) -{ - memcpy (stack, ecif->avalue, ecif->cif->bytes); -} - -/* we borrow this routine from libffi (it must be changed, though, to - * actually call the function passed in the first argument. as of - * libffi-1.20, this is not the case.) - */ - -void -ffi_raw_call(ffi_cif *cif, void (*fn)(void), void *rvalue, ffi_raw *fake_avalue) -{ - extended_cif ecif; - void **avalue = (void **)fake_avalue; - - ecif.cif = cif; - ecif.avalue = avalue; - - /* If the return value is a struct and we don't have a return */ - /* value address then we need to make one */ - - if (rvalue == NULL - && (cif->flags == FFI_TYPE_STRUCT - || cif->flags == FFI_TYPE_MS_STRUCT)) - { - ecif.rvalue = alloca(cif->rtype->size); - } - else - ecif.rvalue = rvalue; - - - switch (cif->abi) - { -#ifdef X86_WIN32 - case FFI_SYSV: - case FFI_STDCALL: - case FFI_MS_CDECL: - ffi_call_win32(ffi_prep_args_raw, &ecif, cif->abi, cif->bytes, cif->flags, - ecif.rvalue, fn); - break; - case FFI_THISCALL: - case FFI_FASTCALL: - { - unsigned int abi = cif->abi; - unsigned int i, passed_regs = 0; - - if (cif->flags == FFI_TYPE_STRUCT) - ++passed_regs; - - for (i=0; i < cif->nargs && passed_regs < 2;i++) - { - size_t sz; - - if (cif->arg_types[i]->type == FFI_TYPE_FLOAT - || cif->arg_types[i]->type == FFI_TYPE_STRUCT) - continue; - sz = (cif->arg_types[i]->size + 3) & ~3; - if (sz == 0 || sz > 4) - continue; - ++passed_regs; - } - if (passed_regs < 2 && abi == FFI_FASTCALL) - cif->abi = abi = FFI_THISCALL; - if (passed_regs < 1 && abi == FFI_THISCALL) - cif->abi = abi = FFI_STDCALL; - ffi_call_win32(ffi_prep_args_raw, &ecif, abi, cif->bytes, cif->flags, - ecif.rvalue, fn); - } - break; -#else - case FFI_SYSV: - ffi_call_SYSV(ffi_prep_args_raw, &ecif, cif->bytes, cif->flags, - ecif.rvalue, fn); - break; -#endif - default: - FFI_ASSERT(0); - break; - } -} - -#endif - -#endif /* !__x86_64__ || X86_WIN64 */ - diff --git a/lib/wrappers/libffi/gcc/ffi64.c b/lib/wrappers/libffi/gcc/ffi64.c deleted file mode 100644 index 2014af24c..000000000 --- a/lib/wrappers/libffi/gcc/ffi64.c +++ /dev/null @@ -1,673 +0,0 @@ -/* ----------------------------------------------------------------------- - ffi64.c - Copyright (c) 2013 The Written Word, Inc. - Copyright (c) 2011 Anthony Green - Copyright (c) 2008, 2010 Red Hat, Inc. - Copyright (c) 2002, 2007 Bo Thorsen - - x86-64 Foreign Function Interface - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files (the - ``Software''), to deal in the Software without restriction, including - without limitation the rights to use, copy, modify, merge, publish, - distribute, sublicense, and/or sell copies of the Software, and to - permit persons to whom the Software is furnished to do so, subject to - the following conditions: - - The above copyright notice and this permission notice shall be included - in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - DEALINGS IN THE SOFTWARE. - ----------------------------------------------------------------------- */ - -#include -#include - -#include -#include - -#ifdef __x86_64__ - -#define MAX_GPR_REGS 6 -#define MAX_SSE_REGS 8 - -#if defined(__INTEL_COMPILER) -#define UINT128 __m128 -#else -#if defined(__SUNPRO_C) -#include -#define UINT128 __m128i -#else -#define UINT128 __int128_t -#endif -#endif - -union big_int_union -{ - UINT32 i32; - UINT64 i64; - UINT128 i128; -}; - -struct register_args -{ - /* Registers for argument passing. */ - UINT64 gpr[MAX_GPR_REGS]; - union big_int_union sse[MAX_SSE_REGS]; -}; - -extern void ffi_call_unix64 (void *args, unsigned long bytes, unsigned flags, - void *raddr, void (*fnaddr)(void), unsigned ssecount); - -/* All reference to register classes here is identical to the code in - gcc/config/i386/i386.c. Do *not* change one without the other. */ - -/* Register class used for passing given 64bit part of the argument. - These represent classes as documented by the PS ABI, with the - exception of SSESF, SSEDF classes, that are basically SSE class, - just gcc will use SF or DFmode move instead of DImode to avoid - reformatting penalties. - - Similary we play games with INTEGERSI_CLASS to use cheaper SImode moves - whenever possible (upper half does contain padding). */ -enum x86_64_reg_class - { - X86_64_NO_CLASS, - X86_64_INTEGER_CLASS, - X86_64_INTEGERSI_CLASS, - X86_64_SSE_CLASS, - X86_64_SSESF_CLASS, - X86_64_SSEDF_CLASS, - X86_64_SSEUP_CLASS, - X86_64_X87_CLASS, - X86_64_X87UP_CLASS, - X86_64_COMPLEX_X87_CLASS, - X86_64_MEMORY_CLASS - }; - -#define MAX_CLASSES 4 - -#define SSE_CLASS_P(X) ((X) >= X86_64_SSE_CLASS && X <= X86_64_SSEUP_CLASS) - -/* x86-64 register passing implementation. See x86-64 ABI for details. Goal - of this code is to classify each 8bytes of incoming argument by the register - class and assign registers accordingly. */ - -/* Return the union class of CLASS1 and CLASS2. - See the x86-64 PS ABI for details. */ - -static enum x86_64_reg_class -merge_classes (enum x86_64_reg_class class1, enum x86_64_reg_class class2) -{ - /* Rule #1: If both classes are equal, this is the resulting class. */ - if (class1 == class2) - return class1; - - /* Rule #2: If one of the classes is NO_CLASS, the resulting class is - the other class. */ - if (class1 == X86_64_NO_CLASS) - return class2; - if (class2 == X86_64_NO_CLASS) - return class1; - - /* Rule #3: If one of the classes is MEMORY, the result is MEMORY. */ - if (class1 == X86_64_MEMORY_CLASS || class2 == X86_64_MEMORY_CLASS) - return X86_64_MEMORY_CLASS; - - /* Rule #4: If one of the classes is INTEGER, the result is INTEGER. */ - if ((class1 == X86_64_INTEGERSI_CLASS && class2 == X86_64_SSESF_CLASS) - || (class2 == X86_64_INTEGERSI_CLASS && class1 == X86_64_SSESF_CLASS)) - return X86_64_INTEGERSI_CLASS; - if (class1 == X86_64_INTEGER_CLASS || class1 == X86_64_INTEGERSI_CLASS - || class2 == X86_64_INTEGER_CLASS || class2 == X86_64_INTEGERSI_CLASS) - return X86_64_INTEGER_CLASS; - - /* Rule #5: If one of the classes is X87, X87UP, or COMPLEX_X87 class, - MEMORY is used. */ - if (class1 == X86_64_X87_CLASS - || class1 == X86_64_X87UP_CLASS - || class1 == X86_64_COMPLEX_X87_CLASS - || class2 == X86_64_X87_CLASS - || class2 == X86_64_X87UP_CLASS - || class2 == X86_64_COMPLEX_X87_CLASS) - return X86_64_MEMORY_CLASS; - - /* Rule #6: Otherwise class SSE is used. */ - return X86_64_SSE_CLASS; -} - -/* Classify the argument of type TYPE and mode MODE. - CLASSES will be filled by the register class used to pass each word - of the operand. The number of words is returned. In case the parameter - should be passed in memory, 0 is returned. As a special case for zero - sized containers, classes[0] will be NO_CLASS and 1 is returned. - - See the x86-64 PS ABI for details. -*/ -static int -classify_argument (ffi_type *type, enum x86_64_reg_class classes[], - size_t byte_offset) -{ - switch (type->type) - { - case FFI_TYPE_UINT8: - case FFI_TYPE_SINT8: - case FFI_TYPE_UINT16: - case FFI_TYPE_SINT16: - case FFI_TYPE_UINT32: - case FFI_TYPE_SINT32: - case FFI_TYPE_UINT64: - case FFI_TYPE_SINT64: - case FFI_TYPE_POINTER: - { - int size = byte_offset + type->size; - - if (size <= 4) - { - classes[0] = X86_64_INTEGERSI_CLASS; - return 1; - } - else if (size <= 8) - { - classes[0] = X86_64_INTEGER_CLASS; - return 1; - } - else if (size <= 12) - { - classes[0] = X86_64_INTEGER_CLASS; - classes[1] = X86_64_INTEGERSI_CLASS; - return 2; - } - else if (size <= 16) - { - classes[0] = classes[1] = X86_64_INTEGERSI_CLASS; - return 2; - } - else - FFI_ASSERT (0); - } - case FFI_TYPE_FLOAT: - if (!(byte_offset % 8)) - classes[0] = X86_64_SSESF_CLASS; - else - classes[0] = X86_64_SSE_CLASS; - return 1; - case FFI_TYPE_DOUBLE: - classes[0] = X86_64_SSEDF_CLASS; - return 1; - case FFI_TYPE_LONGDOUBLE: - classes[0] = X86_64_X87_CLASS; - classes[1] = X86_64_X87UP_CLASS; - return 2; - case FFI_TYPE_STRUCT: - { - const int UNITS_PER_WORD = 8; - int words = (type->size + UNITS_PER_WORD - 1) / UNITS_PER_WORD; - ffi_type **ptr; - int i; - enum x86_64_reg_class subclasses[MAX_CLASSES]; - - /* If the struct is larger than 32 bytes, pass it on the stack. */ - if (type->size > 32) - return 0; - - for (i = 0; i < words; i++) - classes[i] = X86_64_NO_CLASS; - - /* Zero sized arrays or structures are NO_CLASS. We return 0 to - signalize memory class, so handle it as special case. */ - if (!words) - { - classes[0] = X86_64_NO_CLASS; - return 1; - } - - /* Merge the fields of structure. */ - for (ptr = type->elements; *ptr != NULL; ptr++) - { - int num; - - byte_offset = ALIGN (byte_offset, (*ptr)->alignment); - - num = classify_argument (*ptr, subclasses, byte_offset % 8); - if (num == 0) - return 0; - for (i = 0; i < num; i++) - { - int pos = byte_offset / 8; - classes[i + pos] = - merge_classes (subclasses[i], classes[i + pos]); - } - - byte_offset += (*ptr)->size; - } - - if (words > 2) - { - /* When size > 16 bytes, if the first one isn't - X86_64_SSE_CLASS or any other ones aren't - X86_64_SSEUP_CLASS, everything should be passed in - memory. */ - if (classes[0] != X86_64_SSE_CLASS) - return 0; - - for (i = 1; i < words; i++) - if (classes[i] != X86_64_SSEUP_CLASS) - return 0; - } - - /* Final merger cleanup. */ - for (i = 0; i < words; i++) - { - /* If one class is MEMORY, everything should be passed in - memory. */ - if (classes[i] == X86_64_MEMORY_CLASS) - return 0; - - /* The X86_64_SSEUP_CLASS should be always preceded by - X86_64_SSE_CLASS or X86_64_SSEUP_CLASS. */ - if (classes[i] == X86_64_SSEUP_CLASS - && classes[i - 1] != X86_64_SSE_CLASS - && classes[i - 1] != X86_64_SSEUP_CLASS) - { - /* The first one should never be X86_64_SSEUP_CLASS. */ - FFI_ASSERT (i != 0); - classes[i] = X86_64_SSE_CLASS; - } - - /* If X86_64_X87UP_CLASS isn't preceded by X86_64_X87_CLASS, - everything should be passed in memory. */ - if (classes[i] == X86_64_X87UP_CLASS - && (classes[i - 1] != X86_64_X87_CLASS)) - { - /* The first one should never be X86_64_X87UP_CLASS. */ - FFI_ASSERT (i != 0); - return 0; - } - } - return words; - } - - default: - FFI_ASSERT(0); - } - return 0; /* Never reached. */ -} - -/* Examine the argument and return set number of register required in each - class. Return zero iff parameter should be passed in memory, otherwise - the number of registers. */ - -static int -examine_argument (ffi_type *type, enum x86_64_reg_class classes[MAX_CLASSES], - _Bool in_return, int *pngpr, int *pnsse) -{ - int i, n, ngpr, nsse; - - n = classify_argument (type, classes, 0); - if (n == 0) - return 0; - - ngpr = nsse = 0; - for (i = 0; i < n; ++i) - switch (classes[i]) - { - case X86_64_INTEGER_CLASS: - case X86_64_INTEGERSI_CLASS: - ngpr++; - break; - case X86_64_SSE_CLASS: - case X86_64_SSESF_CLASS: - case X86_64_SSEDF_CLASS: - nsse++; - break; - case X86_64_NO_CLASS: - case X86_64_SSEUP_CLASS: - break; - case X86_64_X87_CLASS: - case X86_64_X87UP_CLASS: - case X86_64_COMPLEX_X87_CLASS: - return in_return != 0; - default: - abort (); - } - - *pngpr = ngpr; - *pnsse = nsse; - - return n; -} - -/* Perform machine dependent cif processing. */ - -ffi_status -ffi_prep_cif_machdep (ffi_cif *cif) -{ - int gprcount, ssecount, i, avn, n, ngpr, nsse, flags; - enum x86_64_reg_class classes[MAX_CLASSES]; - size_t bytes; - - gprcount = ssecount = 0; - - flags = cif->rtype->type; - if (flags != FFI_TYPE_VOID) - { - n = examine_argument (cif->rtype, classes, 1, &ngpr, &nsse); - if (n == 0) - { - /* The return value is passed in memory. A pointer to that - memory is the first argument. Allocate a register for it. */ - gprcount++; - /* We don't have to do anything in asm for the return. */ - flags = FFI_TYPE_VOID; - } - else if (flags == FFI_TYPE_STRUCT) - { - /* Mark which registers the result appears in. */ - _Bool sse0 = SSE_CLASS_P (classes[0]); - _Bool sse1 = n == 2 && SSE_CLASS_P (classes[1]); - if (sse0 && !sse1) - flags |= 1 << 8; - else if (!sse0 && sse1) - flags |= 1 << 9; - else if (sse0 && sse1) - flags |= 1 << 10; - /* Mark the true size of the structure. */ - flags |= cif->rtype->size << 12; - } - } - - /* Go over all arguments and determine the way they should be passed. - If it's in a register and there is space for it, let that be so. If - not, add it's size to the stack byte count. */ - for (bytes = 0, i = 0, avn = cif->nargs; i < avn; i++) - { - if (examine_argument (cif->arg_types[i], classes, 0, &ngpr, &nsse) == 0 - || gprcount + ngpr > MAX_GPR_REGS - || ssecount + nsse > MAX_SSE_REGS) - { - long align = cif->arg_types[i]->alignment; - - if (align < 8) - align = 8; - - bytes = ALIGN (bytes, align); - bytes += cif->arg_types[i]->size; - } - else - { - gprcount += ngpr; - ssecount += nsse; - } - } - if (ssecount) - flags |= 1 << 11; - cif->flags = flags; - cif->bytes = ALIGN (bytes, 8); - - return FFI_OK; -} - -void -ffi_call (ffi_cif *cif, void (*fn)(void), void *rvalue, void **avalue) -{ - enum x86_64_reg_class classes[MAX_CLASSES]; - char *stack, *argp; - ffi_type **arg_types; - int gprcount, ssecount, ngpr, nsse, i, avn; - _Bool ret_in_memory; - struct register_args *reg_args; - - /* Can't call 32-bit mode from 64-bit mode. */ - FFI_ASSERT (cif->abi == FFI_UNIX64); - - /* If the return value is a struct and we don't have a return value - address then we need to make one. Note the setting of flags to - VOID above in ffi_prep_cif_machdep. */ - ret_in_memory = (cif->rtype->type == FFI_TYPE_STRUCT - && (cif->flags & 0xff) == FFI_TYPE_VOID); - if (rvalue == NULL && ret_in_memory) - rvalue = alloca (cif->rtype->size); - - /* Allocate the space for the arguments, plus 4 words of temp space. */ - stack = alloca (sizeof (struct register_args) + cif->bytes + 4*8); - reg_args = (struct register_args *) stack; - argp = stack + sizeof (struct register_args); - - gprcount = ssecount = 0; - - /* If the return value is passed in memory, add the pointer as the - first integer argument. */ - if (ret_in_memory) - reg_args->gpr[gprcount++] = (unsigned long) rvalue; - - avn = cif->nargs; - arg_types = cif->arg_types; - - for (i = 0; i < avn; ++i) - { - size_t size = arg_types[i]->size; - int n; - - n = examine_argument (arg_types[i], classes, 0, &ngpr, &nsse); - if (n == 0 - || gprcount + ngpr > MAX_GPR_REGS - || ssecount + nsse > MAX_SSE_REGS) - { - long align = arg_types[i]->alignment; - - /* Stack arguments are *always* at least 8 byte aligned. */ - if (align < 8) - align = 8; - - /* Pass this argument in memory. */ - argp = (void *) ALIGN (argp, align); - memcpy (argp, avalue[i], size); - argp += size; - } - else - { - /* The argument is passed entirely in registers. */ - char *a = (char *) avalue[i]; - int j; - - for (j = 0; j < n; j++, a += 8, size -= 8) - { - switch (classes[j]) - { - case X86_64_INTEGER_CLASS: - case X86_64_INTEGERSI_CLASS: - /* Sign-extend integer arguments passed in general - purpose registers, to cope with the fact that - LLVM incorrectly assumes that this will be done - (the x86-64 PS ABI does not specify this). */ - switch (arg_types[i]->type) - { - case FFI_TYPE_SINT8: - *(SINT64 *)®_args->gpr[gprcount] = (SINT64) *((SINT8 *) a); - break; - case FFI_TYPE_SINT16: - *(SINT64 *)®_args->gpr[gprcount] = (SINT64) *((SINT16 *) a); - break; - case FFI_TYPE_SINT32: - *(SINT64 *)®_args->gpr[gprcount] = (SINT64) *((SINT32 *) a); - break; - default: - reg_args->gpr[gprcount] = 0; - memcpy (®_args->gpr[gprcount], a, size < 8 ? size : 8); - } - gprcount++; - break; - case X86_64_SSE_CLASS: - case X86_64_SSEDF_CLASS: - reg_args->sse[ssecount++].i64 = *(UINT64 *) a; - break; - case X86_64_SSESF_CLASS: - reg_args->sse[ssecount++].i32 = *(UINT32 *) a; - break; - default: - abort(); - } - } - } - } - - ffi_call_unix64 (stack, cif->bytes + sizeof (struct register_args), - cif->flags, rvalue, fn, ssecount); -} - - -extern void ffi_closure_unix64(void); - -ffi_status -ffi_prep_closure_loc (ffi_closure* closure, - ffi_cif* cif, - void (*fun)(ffi_cif*, void*, void**, void*), - void *user_data, - void *codeloc) -{ - volatile unsigned short *tramp; - - /* Sanity check on the cif ABI. */ - { - int abi = cif->abi; - if (UNLIKELY (! (abi > FFI_FIRST_ABI && abi < FFI_LAST_ABI))) - return FFI_BAD_ABI; - } - - tramp = (volatile unsigned short *) &closure->tramp[0]; - - tramp[0] = 0xbb49; /* mov , %r11 */ - *((unsigned long long * volatile) &tramp[1]) - = (unsigned long) ffi_closure_unix64; - tramp[5] = 0xba49; /* mov , %r10 */ - *((unsigned long long * volatile) &tramp[6]) - = (unsigned long) codeloc; - - /* Set the carry bit iff the function uses any sse registers. - This is clc or stc, together with the first byte of the jmp. */ - tramp[10] = cif->flags & (1 << 11) ? 0x49f9 : 0x49f8; - - tramp[11] = 0xe3ff; /* jmp *%r11 */ - - closure->cif = cif; - closure->fun = fun; - closure->user_data = user_data; - - return FFI_OK; -} - -int -ffi_closure_unix64_inner(ffi_closure *closure, void *rvalue, - struct register_args *reg_args, char *argp) -{ - ffi_cif *cif; - void **avalue; - ffi_type **arg_types; - long i, avn; - int gprcount, ssecount, ngpr, nsse; - int ret; - - cif = closure->cif; - avalue = alloca(cif->nargs * sizeof(void *)); - gprcount = ssecount = 0; - - ret = cif->rtype->type; - if (ret != FFI_TYPE_VOID) - { - enum x86_64_reg_class classes[MAX_CLASSES]; - int n = examine_argument (cif->rtype, classes, 1, &ngpr, &nsse); - if (n == 0) - { - /* The return value goes in memory. Arrange for the closure - return value to go directly back to the original caller. */ - rvalue = (void *) (unsigned long) reg_args->gpr[gprcount++]; - /* We don't have to do anything in asm for the return. */ - ret = FFI_TYPE_VOID; - } - else if (ret == FFI_TYPE_STRUCT && n == 2) - { - /* Mark which register the second word of the structure goes in. */ - _Bool sse0 = SSE_CLASS_P (classes[0]); - _Bool sse1 = SSE_CLASS_P (classes[1]); - if (!sse0 && sse1) - ret |= 1 << 8; - else if (sse0 && !sse1) - ret |= 1 << 9; - } - } - - avn = cif->nargs; - arg_types = cif->arg_types; - - for (i = 0; i < avn; ++i) - { - enum x86_64_reg_class classes[MAX_CLASSES]; - int n; - - n = examine_argument (arg_types[i], classes, 0, &ngpr, &nsse); - if (n == 0 - || gprcount + ngpr > MAX_GPR_REGS - || ssecount + nsse > MAX_SSE_REGS) - { - long align = arg_types[i]->alignment; - - /* Stack arguments are *always* at least 8 byte aligned. */ - if (align < 8) - align = 8; - - /* Pass this argument in memory. */ - argp = (void *) ALIGN (argp, align); - avalue[i] = argp; - argp += arg_types[i]->size; - } - /* If the argument is in a single register, or two consecutive - integer registers, then we can use that address directly. */ - else if (n == 1 - || (n == 2 && !(SSE_CLASS_P (classes[0]) - || SSE_CLASS_P (classes[1])))) - { - /* The argument is in a single register. */ - if (SSE_CLASS_P (classes[0])) - { - avalue[i] = ®_args->sse[ssecount]; - ssecount += n; - } - else - { - avalue[i] = ®_args->gpr[gprcount]; - gprcount += n; - } - } - /* Otherwise, allocate space to make them consecutive. */ - else - { - char *a = alloca (16); - int j; - - avalue[i] = a; - for (j = 0; j < n; j++, a += 8) - { - if (SSE_CLASS_P (classes[j])) - memcpy (a, ®_args->sse[ssecount++], 8); - else - memcpy (a, ®_args->gpr[gprcount++], 8); - } - } - } - - /* Invoke the closure. */ - closure->fun (cif, rvalue, avalue, closure->user_data); - - /* Tell assembly how to perform return type promotions. */ - return ret; -} - -#endif /* __x86_64__ */ diff --git a/lib/wrappers/libffi/gcc/prep_cif.c b/lib/wrappers/libffi/gcc/prep_cif.c deleted file mode 100644 index e8ec5cf1e..000000000 --- a/lib/wrappers/libffi/gcc/prep_cif.c +++ /dev/null @@ -1,237 +0,0 @@ -/* ----------------------------------------------------------------------- - prep_cif.c - Copyright (c) 2011, 2012 Anthony Green - Copyright (c) 1996, 1998, 2007 Red Hat, Inc. - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files (the - ``Software''), to deal in the Software without restriction, including - without limitation the rights to use, copy, modify, merge, publish, - distribute, sublicense, and/or sell copies of the Software, and to - permit persons to whom the Software is furnished to do so, subject to - the following conditions: - - The above copyright notice and this permission notice shall be included - in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - DEALINGS IN THE SOFTWARE. - ----------------------------------------------------------------------- */ - -#include -#include -#include - -/* Round up to FFI_SIZEOF_ARG. */ - -#define STACK_ARG_SIZE(x) ALIGN(x, FFI_SIZEOF_ARG) - -/* Perform machine independent initialization of aggregate type - specifications. */ - -static ffi_status initialize_aggregate(ffi_type *arg) -{ - ffi_type **ptr; - - if (UNLIKELY(arg == NULL || arg->elements == NULL)) - return FFI_BAD_TYPEDEF; - - arg->size = 0; - arg->alignment = 0; - - ptr = &(arg->elements[0]); - - if (UNLIKELY(ptr == 0)) - return FFI_BAD_TYPEDEF; - - while ((*ptr) != NULL) - { - if (UNLIKELY(((*ptr)->size == 0) - && (initialize_aggregate((*ptr)) != FFI_OK))) - return FFI_BAD_TYPEDEF; - - /* Perform a sanity check on the argument type */ - FFI_ASSERT_VALID_TYPE(*ptr); - - arg->size = ALIGN(arg->size, (*ptr)->alignment); - arg->size += (*ptr)->size; - - arg->alignment = (arg->alignment > (*ptr)->alignment) ? - arg->alignment : (*ptr)->alignment; - - ptr++; - } - - /* Structure size includes tail padding. This is important for - structures that fit in one register on ABIs like the PowerPC64 - Linux ABI that right justify small structs in a register. - It's also needed for nested structure layout, for example - struct A { long a; char b; }; struct B { struct A x; char y; }; - should find y at an offset of 2*sizeof(long) and result in a - total size of 3*sizeof(long). */ - arg->size = ALIGN (arg->size, arg->alignment); - - if (arg->size == 0) - return FFI_BAD_TYPEDEF; - else - return FFI_OK; -} - -#ifndef __CRIS__ -/* The CRIS ABI specifies structure elements to have byte - alignment only, so it completely overrides this functions, - which assumes "natural" alignment and padding. */ - -/* Perform machine independent ffi_cif preparation, then call - machine dependent routine. */ - -/* For non variadic functions isvariadic should be 0 and - nfixedargs==ntotalargs. - - For variadic calls, isvariadic should be 1 and nfixedargs - and ntotalargs set as appropriate. nfixedargs must always be >=1 */ - - -ffi_status FFI_HIDDEN ffi_prep_cif_core(ffi_cif *cif, ffi_abi abi, - unsigned int isvariadic, - unsigned int nfixedargs, - unsigned int ntotalargs, - ffi_type *rtype, ffi_type **atypes) -{ - unsigned bytes = 0; - unsigned int i; - ffi_type **ptr; - - FFI_ASSERT(cif != NULL); - FFI_ASSERT((!isvariadic) || (nfixedargs >= 1)); - FFI_ASSERT(nfixedargs <= ntotalargs); - -#ifndef X86_WIN32 - if (! (abi > FFI_FIRST_ABI && abi < FFI_LAST_ABI)) - return FFI_BAD_ABI; -#else - if (! (abi > FFI_FIRST_ABI && abi < FFI_LAST_ABI || abi == FFI_THISCALL)) - return FFI_BAD_ABI; -#endif - - cif->abi = abi; - cif->arg_types = atypes; - cif->nargs = ntotalargs; - cif->rtype = rtype; - - cif->flags = 0; - - /* Initialize the return type if necessary */ - if ((cif->rtype->size == 0) && (initialize_aggregate(cif->rtype) != FFI_OK)) - return FFI_BAD_TYPEDEF; - - /* Perform a sanity check on the return type */ - FFI_ASSERT_VALID_TYPE(cif->rtype); - - /* x86, x86-64 and s390 stack space allocation is handled in prep_machdep. */ -#if !defined M68K && !defined X86_ANY && !defined S390 && !defined PA - /* Make space for the return structure pointer */ - if (cif->rtype->type == FFI_TYPE_STRUCT -#ifdef SPARC - && (cif->abi != FFI_V9 || cif->rtype->size > 32) -#endif -#ifdef TILE - && (cif->rtype->size > 10 * FFI_SIZEOF_ARG) -#endif -#ifdef XTENSA - && (cif->rtype->size > 16) -#endif - - ) - bytes = STACK_ARG_SIZE(sizeof(void*)); -#endif - - for (ptr = cif->arg_types, i = cif->nargs; i > 0; i--, ptr++) - { - - /* Initialize any uninitialized aggregate type definitions */ - if (((*ptr)->size == 0) && (initialize_aggregate((*ptr)) != FFI_OK)) - return FFI_BAD_TYPEDEF; - - /* Perform a sanity check on the argument type, do this - check after the initialization. */ - FFI_ASSERT_VALID_TYPE(*ptr); - -#if !defined X86_ANY && !defined S390 && !defined PA -#ifdef SPARC - if (((*ptr)->type == FFI_TYPE_STRUCT - && ((*ptr)->size > 16 || cif->abi != FFI_V9)) - || ((*ptr)->type == FFI_TYPE_LONGDOUBLE - && cif->abi != FFI_V9)) - bytes += sizeof(void*); - else -#endif - { - /* Add any padding if necessary */ - if (((*ptr)->alignment - 1) & bytes) - bytes = ALIGN(bytes, (*ptr)->alignment); - -#ifdef TILE - if (bytes < 10 * FFI_SIZEOF_ARG && - bytes + STACK_ARG_SIZE((*ptr)->size) > 10 * FFI_SIZEOF_ARG) - { - /* An argument is never split between the 10 parameter - registers and the stack. */ - bytes = 10 * FFI_SIZEOF_ARG; - } -#endif -#ifdef XTENSA - if (bytes <= 6*4 && bytes + STACK_ARG_SIZE((*ptr)->size) > 6*4) - bytes = 6*4; -#endif - - bytes += STACK_ARG_SIZE((*ptr)->size); - } -#endif - } - - cif->bytes = bytes; - - /* Perform machine dependent cif processing */ -#ifdef FFI_TARGET_SPECIFIC_VARIADIC - if (isvariadic) - return ffi_prep_cif_machdep_var(cif, nfixedargs, ntotalargs); -#endif - - return ffi_prep_cif_machdep(cif); -} -#endif /* not __CRIS__ */ - -ffi_status ffi_prep_cif(ffi_cif *cif, ffi_abi abi, unsigned int nargs, - ffi_type *rtype, ffi_type **atypes) -{ - return ffi_prep_cif_core(cif, abi, 0, nargs, nargs, rtype, atypes); -} - -ffi_status ffi_prep_cif_var(ffi_cif *cif, - ffi_abi abi, - unsigned int nfixedargs, - unsigned int ntotalargs, - ffi_type *rtype, - ffi_type **atypes) -{ - return ffi_prep_cif_core(cif, abi, 1, nfixedargs, ntotalargs, rtype, atypes); -} - -#if FFI_CLOSURES - -ffi_status -ffi_prep_closure (ffi_closure* closure, - ffi_cif* cif, - void (*fun)(ffi_cif*,void*,void**,void*), - void *user_data) -{ - return ffi_prep_closure_loc (closure, cif, fun, user_data, closure); -} - -#endif diff --git a/lib/wrappers/libffi/gcc/types.c b/lib/wrappers/libffi/gcc/types.c deleted file mode 100644 index 0a11eb0fb..000000000 --- a/lib/wrappers/libffi/gcc/types.c +++ /dev/null @@ -1,77 +0,0 @@ -/* ----------------------------------------------------------------------- - types.c - Copyright (c) 1996, 1998 Red Hat, Inc. - - Predefined ffi_types needed by libffi. - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files (the - ``Software''), to deal in the Software without restriction, including - without limitation the rights to use, copy, modify, merge, publish, - distribute, sublicense, and/or sell copies of the Software, and to - permit persons to whom the Software is furnished to do so, subject to - the following conditions: - - The above copyright notice and this permission notice shall be included - in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - DEALINGS IN THE SOFTWARE. - ----------------------------------------------------------------------- */ - -/* Hide the basic type definitions from the header file, so that we - can redefine them here as "const". */ -#define LIBFFI_HIDE_BASIC_TYPES - -#include -#include - -/* Type definitions */ - -#define FFI_TYPEDEF(name, type, id) \ -struct struct_align_##name { \ - char c; \ - type x; \ -}; \ -const ffi_type ffi_type_##name = { \ - sizeof(type), \ - offsetof(struct struct_align_##name, x), \ - id, NULL \ -} - -/* Size and alignment are fake here. They must not be 0. */ -const ffi_type ffi_type_void = { - 1, 1, FFI_TYPE_VOID, NULL -}; - -FFI_TYPEDEF(uint8, UINT8, FFI_TYPE_UINT8); -FFI_TYPEDEF(sint8, SINT8, FFI_TYPE_SINT8); -FFI_TYPEDEF(uint16, UINT16, FFI_TYPE_UINT16); -FFI_TYPEDEF(sint16, SINT16, FFI_TYPE_SINT16); -FFI_TYPEDEF(uint32, UINT32, FFI_TYPE_UINT32); -FFI_TYPEDEF(sint32, SINT32, FFI_TYPE_SINT32); -FFI_TYPEDEF(uint64, UINT64, FFI_TYPE_UINT64); -FFI_TYPEDEF(sint64, SINT64, FFI_TYPE_SINT64); - -FFI_TYPEDEF(pointer, void*, FFI_TYPE_POINTER); - -FFI_TYPEDEF(float, float, FFI_TYPE_FLOAT); -FFI_TYPEDEF(double, double, FFI_TYPE_DOUBLE); - -#ifdef __alpha__ -/* Even if we're not configured to default to 128-bit long double, - maintain binary compatibility, as -mlong-double-128 can be used - at any time. */ -/* Validate the hard-coded number below. */ -# if defined(__LONG_DOUBLE_128__) && FFI_TYPE_LONGDOUBLE != 4 -# error FFI_TYPE_LONGDOUBLE out of date -# endif -const ffi_type ffi_type_longdouble = { 16, 16, 4, NULL }; -#elif FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE -FFI_TYPEDEF(longdouble, long double, FFI_TYPE_LONGDOUBLE); -#endif diff --git a/lib/wrappers/libffi/gcc/win32_asm.asm b/lib/wrappers/libffi/gcc/win32_asm.asm deleted file mode 100644 index ce3c4f3f3..000000000 --- a/lib/wrappers/libffi/gcc/win32_asm.asm +++ /dev/null @@ -1,759 +0,0 @@ -/* ----------------------------------------------------------------------- - win32.S - Copyright (c) 1996, 1998, 2001, 2002, 2009 Red Hat, Inc. - Copyright (c) 2001 John Beniton - Copyright (c) 2002 Ranjit Mathew - Copyright (c) 2009 Daniel Witte - - - X86 Foreign Function Interface - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files (the - ``Software''), to deal in the Software without restriction, including - without limitation the rights to use, copy, modify, merge, publish, - distribute, sublicense, and/or sell copies of the Software, and to - permit persons to whom the Software is furnished to do so, subject to - the following conditions: - - The above copyright notice and this permission notice shall be included - in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - DEALINGS IN THE SOFTWARE. - ----------------------------------------------------------------------- - */ - -#define LIBFFI_ASM -#include -#include -#include - - .text - - // This assumes we are using gas. - .balign 16 - .globl _ffi_call_win32 -#ifndef __OS2__ - .def _ffi_call_win32; .scl 2; .type 32; .endef -#endif -_ffi_call_win32: -.LFB1: - pushl %ebp -.LCFI0: - movl %esp,%ebp -.LCFI1: - // Make room for all of the new args. - movl 20(%ebp),%ecx - subl %ecx,%esp - - movl %esp,%eax - - // Place all of the ffi_prep_args in position - pushl 12(%ebp) - pushl %eax - call *8(%ebp) - - // Return stack to previous state and call the function - addl $8,%esp - - // Handle fastcall and thiscall - cmpl $3, 16(%ebp) // FFI_THISCALL - jz .do_thiscall - cmpl $4, 16(%ebp) // FFI_FASTCALL - jnz .do_fncall - movl (%esp), %ecx - movl 4(%esp), %edx - addl $8, %esp - jmp .do_fncall -.do_thiscall: - movl (%esp), %ecx - addl $4, %esp - -.do_fncall: - - // FIXME: Align the stack to a 128-bit boundary to avoid - // potential performance hits. - - call *32(%ebp) - - // stdcall functions pop arguments off the stack themselves - - // Load %ecx with the return type code - movl 24(%ebp),%ecx - - // If the return value pointer is NULL, assume no return value. - cmpl $0,28(%ebp) - jne 0f - - // Even if there is no space for the return value, we are - // obliged to handle floating-point values. - cmpl $FFI_TYPE_FLOAT,%ecx - jne .Lnoretval - fstp %st(0) - - jmp .Lepilogue - -0: - call 1f - // Do not insert anything here between the call and the jump table. -.Lstore_table: - .long .Lnoretval /* FFI_TYPE_VOID */ - .long .Lretint /* FFI_TYPE_INT */ - .long .Lretfloat /* FFI_TYPE_FLOAT */ - .long .Lretdouble /* FFI_TYPE_DOUBLE */ - .long .Lretlongdouble /* FFI_TYPE_LONGDOUBLE */ - .long .Lretuint8 /* FFI_TYPE_UINT8 */ - .long .Lretsint8 /* FFI_TYPE_SINT8 */ - .long .Lretuint16 /* FFI_TYPE_UINT16 */ - .long .Lretsint16 /* FFI_TYPE_SINT16 */ - .long .Lretint /* FFI_TYPE_UINT32 */ - .long .Lretint /* FFI_TYPE_SINT32 */ - .long .Lretint64 /* FFI_TYPE_UINT64 */ - .long .Lretint64 /* FFI_TYPE_SINT64 */ - .long .Lretstruct /* FFI_TYPE_STRUCT */ - .long .Lretint /* FFI_TYPE_POINTER */ - .long .Lretstruct1b /* FFI_TYPE_SMALL_STRUCT_1B */ - .long .Lretstruct2b /* FFI_TYPE_SMALL_STRUCT_2B */ - .long .Lretstruct4b /* FFI_TYPE_SMALL_STRUCT_4B */ - .long .Lretstruct /* FFI_TYPE_MS_STRUCT */ -1: - add %ecx, %ecx - add %ecx, %ecx - add (%esp),%ecx - add $4, %esp - jmp *(%ecx) - - /* Sign/zero extend as appropriate. */ -.Lretsint8: - movsbl %al, %eax - jmp .Lretint - -.Lretsint16: - movswl %ax, %eax - jmp .Lretint - -.Lretuint8: - movzbl %al, %eax - jmp .Lretint - -.Lretuint16: - movzwl %ax, %eax - jmp .Lretint - -.Lretint: - // Load %ecx with the pointer to storage for the return value - movl 28(%ebp),%ecx - movl %eax,0(%ecx) - jmp .Lepilogue - -.Lretfloat: - // Load %ecx with the pointer to storage for the return value - movl 28(%ebp),%ecx - fstps (%ecx) - jmp .Lepilogue - -.Lretdouble: - // Load %ecx with the pointer to storage for the return value - movl 28(%ebp),%ecx - fstpl (%ecx) - jmp .Lepilogue - -.Lretlongdouble: - // Load %ecx with the pointer to storage for the return value - movl 28(%ebp),%ecx - fstpt (%ecx) - jmp .Lepilogue - -.Lretint64: - // Load %ecx with the pointer to storage for the return value - movl 28(%ebp),%ecx - movl %eax,0(%ecx) - movl %edx,4(%ecx) - jmp .Lepilogue - -.Lretstruct1b: - // Load %ecx with the pointer to storage for the return value - movl 28(%ebp),%ecx - movb %al,0(%ecx) - jmp .Lepilogue - -.Lretstruct2b: - // Load %ecx with the pointer to storage for the return value - movl 28(%ebp),%ecx - movw %ax,0(%ecx) - jmp .Lepilogue - -.Lretstruct4b: - // Load %ecx with the pointer to storage for the return value - movl 28(%ebp),%ecx - movl %eax,0(%ecx) - jmp .Lepilogue - -.Lretstruct: - // Nothing to do! - -.Lnoretval: -.Lepilogue: - movl %ebp,%esp - popl %ebp - ret -.ffi_call_win32_end: - .balign 16 - .globl _ffi_closure_THISCALL -#ifndef __OS2__ - .def _ffi_closure_THISCALL; .scl 2; .type 32; .endef -#endif -_ffi_closure_THISCALL: - pushl %ebp - movl %esp, %ebp - subl $40, %esp - leal -24(%ebp), %edx - movl %edx, -12(%ebp) /* resp */ - leal 12(%ebp), %edx /* account for stub return address on stack */ - jmp .stub -.LFE1: - - // This assumes we are using gas. - .balign 16 - .globl _ffi_closure_SYSV -#ifndef __OS2__ - .def _ffi_closure_SYSV; .scl 2; .type 32; .endef -#endif -_ffi_closure_SYSV: -.LFB3: - pushl %ebp -.LCFI4: - movl %esp, %ebp -.LCFI5: - subl $40, %esp - leal -24(%ebp), %edx - movl %edx, -12(%ebp) /* resp */ - leal 8(%ebp), %edx -.stub: - movl %edx, 4(%esp) /* args = __builtin_dwarf_cfa () */ - leal -12(%ebp), %edx - movl %edx, (%esp) /* &resp */ - call _ffi_closure_SYSV_inner - movl -12(%ebp), %ecx - -0: - call 1f - // Do not insert anything here between the call and the jump table. -.Lcls_store_table: - .long .Lcls_noretval /* FFI_TYPE_VOID */ - .long .Lcls_retint /* FFI_TYPE_INT */ - .long .Lcls_retfloat /* FFI_TYPE_FLOAT */ - .long .Lcls_retdouble /* FFI_TYPE_DOUBLE */ - .long .Lcls_retldouble /* FFI_TYPE_LONGDOUBLE */ - .long .Lcls_retuint8 /* FFI_TYPE_UINT8 */ - .long .Lcls_retsint8 /* FFI_TYPE_SINT8 */ - .long .Lcls_retuint16 /* FFI_TYPE_UINT16 */ - .long .Lcls_retsint16 /* FFI_TYPE_SINT16 */ - .long .Lcls_retint /* FFI_TYPE_UINT32 */ - .long .Lcls_retint /* FFI_TYPE_SINT32 */ - .long .Lcls_retllong /* FFI_TYPE_UINT64 */ - .long .Lcls_retllong /* FFI_TYPE_SINT64 */ - .long .Lcls_retstruct /* FFI_TYPE_STRUCT */ - .long .Lcls_retint /* FFI_TYPE_POINTER */ - .long .Lcls_retstruct1 /* FFI_TYPE_SMALL_STRUCT_1B */ - .long .Lcls_retstruct2 /* FFI_TYPE_SMALL_STRUCT_2B */ - .long .Lcls_retstruct4 /* FFI_TYPE_SMALL_STRUCT_4B */ - .long .Lcls_retmsstruct /* FFI_TYPE_MS_STRUCT */ - -1: - add %eax, %eax - add %eax, %eax - add (%esp),%eax - add $4, %esp - jmp *(%eax) - - /* Sign/zero extend as appropriate. */ -.Lcls_retsint8: - movsbl (%ecx), %eax - jmp .Lcls_epilogue - -.Lcls_retsint16: - movswl (%ecx), %eax - jmp .Lcls_epilogue - -.Lcls_retuint8: - movzbl (%ecx), %eax - jmp .Lcls_epilogue - -.Lcls_retuint16: - movzwl (%ecx), %eax - jmp .Lcls_epilogue - -.Lcls_retint: - movl (%ecx), %eax - jmp .Lcls_epilogue - -.Lcls_retfloat: - flds (%ecx) - jmp .Lcls_epilogue - -.Lcls_retdouble: - fldl (%ecx) - jmp .Lcls_epilogue - -.Lcls_retldouble: - fldt (%ecx) - jmp .Lcls_epilogue - -.Lcls_retllong: - movl (%ecx), %eax - movl 4(%ecx), %edx - jmp .Lcls_epilogue - -.Lcls_retstruct1: - movsbl (%ecx), %eax - jmp .Lcls_epilogue - -.Lcls_retstruct2: - movswl (%ecx), %eax - jmp .Lcls_epilogue - -.Lcls_retstruct4: - movl (%ecx), %eax - jmp .Lcls_epilogue - -.Lcls_retstruct: - // Caller expects us to pop struct return value pointer hidden arg. - movl %ebp, %esp - popl %ebp - ret $0x4 - -.Lcls_retmsstruct: - // Caller expects us to return a pointer to the real return value. - mov %ecx, %eax - // Caller doesn't expects us to pop struct return value pointer hidden arg. - jmp .Lcls_epilogue - -.Lcls_noretval: -.Lcls_epilogue: - movl %ebp, %esp - popl %ebp - ret -.ffi_closure_SYSV_end: -.LFE3: - -#if !FFI_NO_RAW_API - -#define RAW_CLOSURE_CIF_OFFSET ((FFI_TRAMPOLINE_SIZE + 3) & ~3) -#define RAW_CLOSURE_FUN_OFFSET (RAW_CLOSURE_CIF_OFFSET + 4) -#define RAW_CLOSURE_USER_DATA_OFFSET (RAW_CLOSURE_FUN_OFFSET + 4) -#define CIF_FLAGS_OFFSET 20 - .balign 16 - .globl _ffi_closure_raw_THISCALL -#ifndef __OS2__ - .def _ffi_closure_raw_THISCALL; .scl 2; .type 32; .endef -#endif -_ffi_closure_raw_THISCALL: - pushl %ebp - movl %esp, %ebp - pushl %esi - subl $36, %esp - movl RAW_CLOSURE_CIF_OFFSET(%eax), %esi /* closure->cif */ - movl RAW_CLOSURE_USER_DATA_OFFSET(%eax), %edx /* closure->user_data */ - movl %edx, 12(%esp) /* user_data */ - leal 12(%ebp), %edx /* __builtin_dwarf_cfa () */ - jmp .stubraw - // This assumes we are using gas. - .balign 16 - .globl _ffi_closure_raw_SYSV -#ifndef __OS2__ - .def _ffi_closure_raw_SYSV; .scl 2; .type 32; .endef -#endif -_ffi_closure_raw_SYSV: -.LFB4: - pushl %ebp -.LCFI6: - movl %esp, %ebp -.LCFI7: - pushl %esi -.LCFI8: - subl $36, %esp - movl RAW_CLOSURE_CIF_OFFSET(%eax), %esi /* closure->cif */ - movl RAW_CLOSURE_USER_DATA_OFFSET(%eax), %edx /* closure->user_data */ - movl %edx, 12(%esp) /* user_data */ - leal 8(%ebp), %edx /* __builtin_dwarf_cfa () */ -.stubraw: - movl %edx, 8(%esp) /* raw_args */ - leal -24(%ebp), %edx - movl %edx, 4(%esp) /* &res */ - movl %esi, (%esp) /* cif */ - call *RAW_CLOSURE_FUN_OFFSET(%eax) /* closure->fun */ - movl CIF_FLAGS_OFFSET(%esi), %eax /* rtype */ -0: - call 1f - // Do not insert anything here between the call and the jump table. -.Lrcls_store_table: - .long .Lrcls_noretval /* FFI_TYPE_VOID */ - .long .Lrcls_retint /* FFI_TYPE_INT */ - .long .Lrcls_retfloat /* FFI_TYPE_FLOAT */ - .long .Lrcls_retdouble /* FFI_TYPE_DOUBLE */ - .long .Lrcls_retldouble /* FFI_TYPE_LONGDOUBLE */ - .long .Lrcls_retuint8 /* FFI_TYPE_UINT8 */ - .long .Lrcls_retsint8 /* FFI_TYPE_SINT8 */ - .long .Lrcls_retuint16 /* FFI_TYPE_UINT16 */ - .long .Lrcls_retsint16 /* FFI_TYPE_SINT16 */ - .long .Lrcls_retint /* FFI_TYPE_UINT32 */ - .long .Lrcls_retint /* FFI_TYPE_SINT32 */ - .long .Lrcls_retllong /* FFI_TYPE_UINT64 */ - .long .Lrcls_retllong /* FFI_TYPE_SINT64 */ - .long .Lrcls_retstruct /* FFI_TYPE_STRUCT */ - .long .Lrcls_retint /* FFI_TYPE_POINTER */ - .long .Lrcls_retstruct1 /* FFI_TYPE_SMALL_STRUCT_1B */ - .long .Lrcls_retstruct2 /* FFI_TYPE_SMALL_STRUCT_2B */ - .long .Lrcls_retstruct4 /* FFI_TYPE_SMALL_STRUCT_4B */ - .long .Lrcls_retstruct /* FFI_TYPE_MS_STRUCT */ -1: - add %eax, %eax - add %eax, %eax - add (%esp),%eax - add $4, %esp - jmp *(%eax) - - /* Sign/zero extend as appropriate. */ -.Lrcls_retsint8: - movsbl -24(%ebp), %eax - jmp .Lrcls_epilogue - -.Lrcls_retsint16: - movswl -24(%ebp), %eax - jmp .Lrcls_epilogue - -.Lrcls_retuint8: - movzbl -24(%ebp), %eax - jmp .Lrcls_epilogue - -.Lrcls_retuint16: - movzwl -24(%ebp), %eax - jmp .Lrcls_epilogue - -.Lrcls_retint: - movl -24(%ebp), %eax - jmp .Lrcls_epilogue - -.Lrcls_retfloat: - flds -24(%ebp) - jmp .Lrcls_epilogue - -.Lrcls_retdouble: - fldl -24(%ebp) - jmp .Lrcls_epilogue - -.Lrcls_retldouble: - fldt -24(%ebp) - jmp .Lrcls_epilogue - -.Lrcls_retllong: - movl -24(%ebp), %eax - movl -20(%ebp), %edx - jmp .Lrcls_epilogue - -.Lrcls_retstruct1: - movsbl -24(%ebp), %eax - jmp .Lrcls_epilogue - -.Lrcls_retstruct2: - movswl -24(%ebp), %eax - jmp .Lrcls_epilogue - -.Lrcls_retstruct4: - movl -24(%ebp), %eax - jmp .Lrcls_epilogue - -.Lrcls_retstruct: - // Nothing to do! - -.Lrcls_noretval: -.Lrcls_epilogue: - addl $36, %esp - popl %esi - popl %ebp - ret -.ffi_closure_raw_SYSV_end: -.LFE4: - -#endif /* !FFI_NO_RAW_API */ - - // This assumes we are using gas. - .balign 16 - .globl _ffi_closure_STDCALL -#ifndef __OS2__ - .def _ffi_closure_STDCALL; .scl 2; .type 32; .endef -#endif -_ffi_closure_STDCALL: -.LFB5: - pushl %ebp -.LCFI9: - movl %esp, %ebp -.LCFI10: - subl $40, %esp - leal -24(%ebp), %edx - movl %edx, -12(%ebp) /* resp */ - leal 12(%ebp), %edx /* account for stub return address on stack */ - movl %edx, 4(%esp) /* args */ - leal -12(%ebp), %edx - movl %edx, (%esp) /* &resp */ - call _ffi_closure_SYSV_inner - movl -12(%ebp), %ecx -0: - call 1f - // Do not insert anything here between the call and the jump table. -.Lscls_store_table: - .long .Lscls_noretval /* FFI_TYPE_VOID */ - .long .Lscls_retint /* FFI_TYPE_INT */ - .long .Lscls_retfloat /* FFI_TYPE_FLOAT */ - .long .Lscls_retdouble /* FFI_TYPE_DOUBLE */ - .long .Lscls_retldouble /* FFI_TYPE_LONGDOUBLE */ - .long .Lscls_retuint8 /* FFI_TYPE_UINT8 */ - .long .Lscls_retsint8 /* FFI_TYPE_SINT8 */ - .long .Lscls_retuint16 /* FFI_TYPE_UINT16 */ - .long .Lscls_retsint16 /* FFI_TYPE_SINT16 */ - .long .Lscls_retint /* FFI_TYPE_UINT32 */ - .long .Lscls_retint /* FFI_TYPE_SINT32 */ - .long .Lscls_retllong /* FFI_TYPE_UINT64 */ - .long .Lscls_retllong /* FFI_TYPE_SINT64 */ - .long .Lscls_retstruct /* FFI_TYPE_STRUCT */ - .long .Lscls_retint /* FFI_TYPE_POINTER */ - .long .Lscls_retstruct1 /* FFI_TYPE_SMALL_STRUCT_1B */ - .long .Lscls_retstruct2 /* FFI_TYPE_SMALL_STRUCT_2B */ - .long .Lscls_retstruct4 /* FFI_TYPE_SMALL_STRUCT_4B */ -1: - add %eax, %eax - add %eax, %eax - add (%esp),%eax - add $4, %esp - jmp *(%eax) - - /* Sign/zero extend as appropriate. */ -.Lscls_retsint8: - movsbl (%ecx), %eax - jmp .Lscls_epilogue - -.Lscls_retsint16: - movswl (%ecx), %eax - jmp .Lscls_epilogue - -.Lscls_retuint8: - movzbl (%ecx), %eax - jmp .Lscls_epilogue - -.Lscls_retuint16: - movzwl (%ecx), %eax - jmp .Lscls_epilogue - -.Lscls_retint: - movl (%ecx), %eax - jmp .Lscls_epilogue - -.Lscls_retfloat: - flds (%ecx) - jmp .Lscls_epilogue - -.Lscls_retdouble: - fldl (%ecx) - jmp .Lscls_epilogue - -.Lscls_retldouble: - fldt (%ecx) - jmp .Lscls_epilogue - -.Lscls_retllong: - movl (%ecx), %eax - movl 4(%ecx), %edx - jmp .Lscls_epilogue - -.Lscls_retstruct1: - movsbl (%ecx), %eax - jmp .Lscls_epilogue - -.Lscls_retstruct2: - movswl (%ecx), %eax - jmp .Lscls_epilogue - -.Lscls_retstruct4: - movl (%ecx), %eax - jmp .Lscls_epilogue - -.Lscls_retstruct: - // Nothing to do! - -.Lscls_noretval: -.Lscls_epilogue: - movl %ebp, %esp - popl %ebp - ret -.ffi_closure_STDCALL_end: -.LFE5: - -#ifndef __OS2__ - .section .eh_frame,"w" -#endif -.Lframe1: -.LSCIE1: - .long .LECIE1-.LASCIE1 /* Length of Common Information Entry */ -.LASCIE1: - .long 0x0 /* CIE Identifier Tag */ - .byte 0x1 /* CIE Version */ -#ifdef __PIC__ - .ascii "zR\0" /* CIE Augmentation */ -#else - .ascii "\0" /* CIE Augmentation */ -#endif - .byte 0x1 /* .uleb128 0x1; CIE Code Alignment Factor */ - .byte 0x7c /* .sleb128 -4; CIE Data Alignment Factor */ - .byte 0x8 /* CIE RA Column */ -#ifdef __PIC__ - .byte 0x1 /* .uleb128 0x1; Augmentation size */ - .byte 0x1b /* FDE Encoding (pcrel sdata4) */ -#endif - .byte 0xc /* DW_CFA_def_cfa CFA = r4 + 4 = 4(%esp) */ - .byte 0x4 /* .uleb128 0x4 */ - .byte 0x4 /* .uleb128 0x4 */ - .byte 0x88 /* DW_CFA_offset, column 0x8 %eip at CFA + 1 * -4 */ - .byte 0x1 /* .uleb128 0x1 */ - .align 4 -.LECIE1: - -.LSFDE1: - .long .LEFDE1-.LASFDE1 /* FDE Length */ -.LASFDE1: - .long .LASFDE1-.Lframe1 /* FDE CIE offset */ -#if defined __PIC__ && defined HAVE_AS_X86_PCREL - .long .LFB1-. /* FDE initial location */ -#else - .long .LFB1 -#endif - .long .LFE1-.LFB1 /* FDE address range */ -#ifdef __PIC__ - .byte 0x0 /* .uleb128 0x0; Augmentation size */ -#endif - /* DW_CFA_xxx CFI instructions go here. */ - - .byte 0x4 /* DW_CFA_advance_loc4 */ - .long .LCFI0-.LFB1 - .byte 0xe /* DW_CFA_def_cfa_offset CFA = r4 + 8 = 8(%esp) */ - .byte 0x8 /* .uleb128 0x8 */ - .byte 0x85 /* DW_CFA_offset, column 0x5 %ebp at CFA + 2 * -4 */ - .byte 0x2 /* .uleb128 0x2 */ - - .byte 0x4 /* DW_CFA_advance_loc4 */ - .long .LCFI1-.LCFI0 - .byte 0xd /* DW_CFA_def_cfa_register CFA = r5 = %ebp */ - .byte 0x5 /* .uleb128 0x5 */ - - /* End of DW_CFA_xxx CFI instructions. */ - .align 4 -.LEFDE1: - - -.LSFDE3: - .long .LEFDE3-.LASFDE3 /* FDE Length */ -.LASFDE3: - .long .LASFDE3-.Lframe1 /* FDE CIE offset */ -#if defined __PIC__ && defined HAVE_AS_X86_PCREL - .long .LFB3-. /* FDE initial location */ -#else - .long .LFB3 -#endif - .long .LFE3-.LFB3 /* FDE address range */ -#ifdef __PIC__ - .byte 0x0 /* .uleb128 0x0; Augmentation size */ -#endif - /* DW_CFA_xxx CFI instructions go here. */ - - .byte 0x4 /* DW_CFA_advance_loc4 */ - .long .LCFI4-.LFB3 - .byte 0xe /* DW_CFA_def_cfa_offset CFA = r4 + 8 = 8(%esp) */ - .byte 0x8 /* .uleb128 0x8 */ - .byte 0x85 /* DW_CFA_offset, column 0x5 %ebp at CFA + 2 * -4 */ - .byte 0x2 /* .uleb128 0x2 */ - - .byte 0x4 /* DW_CFA_advance_loc4 */ - .long .LCFI5-.LCFI4 - .byte 0xd /* DW_CFA_def_cfa_register CFA = r5 = %ebp */ - .byte 0x5 /* .uleb128 0x5 */ - - /* End of DW_CFA_xxx CFI instructions. */ - .align 4 -.LEFDE3: - -#if !FFI_NO_RAW_API - -.LSFDE4: - .long .LEFDE4-.LASFDE4 /* FDE Length */ -.LASFDE4: - .long .LASFDE4-.Lframe1 /* FDE CIE offset */ -#if defined __PIC__ && defined HAVE_AS_X86_PCREL - .long .LFB4-. /* FDE initial location */ -#else - .long .LFB4 -#endif - .long .LFE4-.LFB4 /* FDE address range */ -#ifdef __PIC__ - .byte 0x0 /* .uleb128 0x0; Augmentation size */ -#endif - /* DW_CFA_xxx CFI instructions go here. */ - - .byte 0x4 /* DW_CFA_advance_loc4 */ - .long .LCFI6-.LFB4 - .byte 0xe /* DW_CFA_def_cfa_offset CFA = r4 + 8 = 8(%esp) */ - .byte 0x8 /* .uleb128 0x8 */ - .byte 0x85 /* DW_CFA_offset, column 0x5 %ebp at CFA + 2 * -4 */ - .byte 0x2 /* .uleb128 0x2 */ - - .byte 0x4 /* DW_CFA_advance_loc4 */ - .long .LCFI7-.LCFI6 - .byte 0xd /* DW_CFA_def_cfa_register CFA = r5 = %ebp */ - .byte 0x5 /* .uleb128 0x5 */ - - .byte 0x4 /* DW_CFA_advance_loc4 */ - .long .LCFI8-.LCFI7 - .byte 0x86 /* DW_CFA_offset, column 0x6 %esi at CFA + 3 * -4 */ - .byte 0x3 /* .uleb128 0x3 */ - - /* End of DW_CFA_xxx CFI instructions. */ - .align 4 -.LEFDE4: - -#endif /* !FFI_NO_RAW_API */ - -.LSFDE5: - .long .LEFDE5-.LASFDE5 /* FDE Length */ -.LASFDE5: - .long .LASFDE5-.Lframe1 /* FDE CIE offset */ -#if defined __PIC__ && defined HAVE_AS_X86_PCREL - .long .LFB5-. /* FDE initial location */ -#else - .long .LFB5 -#endif - .long .LFE5-.LFB5 /* FDE address range */ -#ifdef __PIC__ - .byte 0x0 /* .uleb128 0x0; Augmentation size */ -#endif - /* DW_CFA_xxx CFI instructions go here. */ - - .byte 0x4 /* DW_CFA_advance_loc4 */ - .long .LCFI9-.LFB5 - .byte 0xe /* DW_CFA_def_cfa_offset CFA = r4 + 8 = 8(%esp) */ - .byte 0x8 /* .uleb128 0x8 */ - .byte 0x85 /* DW_CFA_offset, column 0x5 %ebp at CFA + 2 * -4 */ - .byte 0x2 /* .uleb128 0x2 */ - - .byte 0x4 /* DW_CFA_advance_loc4 */ - .long .LCFI10-.LCFI9 - .byte 0xd /* DW_CFA_def_cfa_register CFA = r5 = %ebp */ - .byte 0x5 /* .uleb128 0x5 */ - - /* End of DW_CFA_xxx CFI instructions. */ - .align 4 -.LEFDE5: diff --git a/lib/wrappers/libffi/gcc/win32_asm.s b/lib/wrappers/libffi/gcc/win32_asm.s deleted file mode 100644 index 7a3e7f16c..000000000 --- a/lib/wrappers/libffi/gcc/win32_asm.s +++ /dev/null @@ -1,736 +0,0 @@ -# 1 "gcc\\win32_asm.asm" -# 1 "" -# 1 "gcc\\win32_asm.asm" -# 33 "gcc\\win32_asm.asm" -# 1 "common/fficonfig.h" 1 -# 34 "gcc\\win32_asm.asm" 2 -# 1 "common/ffi.h" 1 -# 63 "common/ffi.h" -# 1 "common/ffitarget.h" 1 -# 64 "common/ffi.h" 2 -# 35 "gcc\\win32_asm.asm" 2 - - - .text - - - .balign 16 - .globl _ffi_call_win32 - - .def _ffi_call_win32; .scl 2; .type 32; .endef - -_ffi_call_win32: -.LFB1: - pushl %ebp -.LCFI0: - movl %esp,%ebp -.LCFI1: - - movl 20(%ebp),%ecx - subl %ecx,%esp - - movl %esp,%eax - - - pushl 12(%ebp) - pushl %eax - call *8(%ebp) - - - addl $8,%esp - - - cmpl $3, 16(%ebp) - jz .do_thiscall - cmpl $4, 16(%ebp) - jnz .do_fncall - movl (%esp), %ecx - movl 4(%esp), %edx - addl $8, %esp - jmp .do_fncall -.do_thiscall: - movl (%esp), %ecx - addl $4, %esp - -.do_fncall: - - - - - call *32(%ebp) - - - - - movl 24(%ebp),%ecx - - - cmpl $0,28(%ebp) - jne 0f - - - - cmpl $2,%ecx - jne .Lnoretval - fstp %st(0) - - jmp .Lepilogue - -0: - call 1f - -.Lstore_table: - .long .Lnoretval - .long .Lretint - .long .Lretfloat - .long .Lretdouble - .long .Lretlongdouble - .long .Lretuint8 - .long .Lretsint8 - .long .Lretuint16 - .long .Lretsint16 - .long .Lretint - .long .Lretint - .long .Lretint64 - .long .Lretint64 - .long .Lretstruct - .long .Lretint - .long .Lretstruct1b - .long .Lretstruct2b - .long .Lretstruct4b - .long .Lretstruct -1: - add %ecx, %ecx - add %ecx, %ecx - add (%esp),%ecx - add $4, %esp - jmp *(%ecx) - - -.Lretsint8: - movsbl %al, %eax - jmp .Lretint - -.Lretsint16: - movswl %ax, %eax - jmp .Lretint - -.Lretuint8: - movzbl %al, %eax - jmp .Lretint - -.Lretuint16: - movzwl %ax, %eax - jmp .Lretint - -.Lretint: - - movl 28(%ebp),%ecx - movl %eax,0(%ecx) - jmp .Lepilogue - -.Lretfloat: - - movl 28(%ebp),%ecx - fstps (%ecx) - jmp .Lepilogue - -.Lretdouble: - - movl 28(%ebp),%ecx - fstpl (%ecx) - jmp .Lepilogue - -.Lretlongdouble: - - movl 28(%ebp),%ecx - fstpt (%ecx) - jmp .Lepilogue - -.Lretint64: - - movl 28(%ebp),%ecx - movl %eax,0(%ecx) - movl %edx,4(%ecx) - jmp .Lepilogue - -.Lretstruct1b: - - movl 28(%ebp),%ecx - movb %al,0(%ecx) - jmp .Lepilogue - -.Lretstruct2b: - - movl 28(%ebp),%ecx - movw %ax,0(%ecx) - jmp .Lepilogue - -.Lretstruct4b: - - movl 28(%ebp),%ecx - movl %eax,0(%ecx) - jmp .Lepilogue - -.Lretstruct: - - -.Lnoretval: -.Lepilogue: - movl %ebp,%esp - popl %ebp - ret -.ffi_call_win32_end: - .balign 16 - .globl _ffi_closure_THISCALL - - .def _ffi_closure_THISCALL; .scl 2; .type 32; .endef - -_ffi_closure_THISCALL: - pushl %ebp - movl %esp, %ebp - subl $40, %esp - leal -24(%ebp), %edx - movl %edx, -12(%ebp) - leal 12(%ebp), %edx - jmp .stub -.LFE1: - - - .balign 16 - .globl _ffi_closure_SYSV - - .def _ffi_closure_SYSV; .scl 2; .type 32; .endef - -_ffi_closure_SYSV: -.LFB3: - pushl %ebp -.LCFI4: - movl %esp, %ebp -.LCFI5: - subl $40, %esp - leal -24(%ebp), %edx - movl %edx, -12(%ebp) - leal 8(%ebp), %edx -.stub: - movl %edx, 4(%esp) - leal -12(%ebp), %edx - movl %edx, (%esp) - call _ffi_closure_SYSV_inner - movl -12(%ebp), %ecx - -0: - call 1f - -.Lcls_store_table: - .long .Lcls_noretval - .long .Lcls_retint - .long .Lcls_retfloat - .long .Lcls_retdouble - .long .Lcls_retldouble - .long .Lcls_retuint8 - .long .Lcls_retsint8 - .long .Lcls_retuint16 - .long .Lcls_retsint16 - .long .Lcls_retint - .long .Lcls_retint - .long .Lcls_retllong - .long .Lcls_retllong - .long .Lcls_retstruct - .long .Lcls_retint - .long .Lcls_retstruct1 - .long .Lcls_retstruct2 - .long .Lcls_retstruct4 - .long .Lcls_retmsstruct - -1: - add %eax, %eax - add %eax, %eax - add (%esp),%eax - add $4, %esp - jmp *(%eax) - - -.Lcls_retsint8: - movsbl (%ecx), %eax - jmp .Lcls_epilogue - -.Lcls_retsint16: - movswl (%ecx), %eax - jmp .Lcls_epilogue - -.Lcls_retuint8: - movzbl (%ecx), %eax - jmp .Lcls_epilogue - -.Lcls_retuint16: - movzwl (%ecx), %eax - jmp .Lcls_epilogue - -.Lcls_retint: - movl (%ecx), %eax - jmp .Lcls_epilogue - -.Lcls_retfloat: - flds (%ecx) - jmp .Lcls_epilogue - -.Lcls_retdouble: - fldl (%ecx) - jmp .Lcls_epilogue - -.Lcls_retldouble: - fldt (%ecx) - jmp .Lcls_epilogue - -.Lcls_retllong: - movl (%ecx), %eax - movl 4(%ecx), %edx - jmp .Lcls_epilogue - -.Lcls_retstruct1: - movsbl (%ecx), %eax - jmp .Lcls_epilogue - -.Lcls_retstruct2: - movswl (%ecx), %eax - jmp .Lcls_epilogue - -.Lcls_retstruct4: - movl (%ecx), %eax - jmp .Lcls_epilogue - -.Lcls_retstruct: - - movl %ebp, %esp - popl %ebp - ret $0x4 - -.Lcls_retmsstruct: - - mov %ecx, %eax - - jmp .Lcls_epilogue - -.Lcls_noretval: -.Lcls_epilogue: - movl %ebp, %esp - popl %ebp - ret -.ffi_closure_SYSV_end: -.LFE3: - - - - - - - - .balign 16 - .globl _ffi_closure_raw_THISCALL - - .def _ffi_closure_raw_THISCALL; .scl 2; .type 32; .endef - -_ffi_closure_raw_THISCALL: - pushl %ebp - movl %esp, %ebp - pushl %esi - subl $36, %esp - movl ((52 + 3) & ~3)(%eax), %esi - movl ((((52 + 3) & ~3) + 4) + 4)(%eax), %edx - movl %edx, 12(%esp) - leal 12(%ebp), %edx - jmp .stubraw - - .balign 16 - .globl _ffi_closure_raw_SYSV - - .def _ffi_closure_raw_SYSV; .scl 2; .type 32; .endef - -_ffi_closure_raw_SYSV: -.LFB4: - pushl %ebp -.LCFI6: - movl %esp, %ebp -.LCFI7: - pushl %esi -.LCFI8: - subl $36, %esp - movl ((52 + 3) & ~3)(%eax), %esi - movl ((((52 + 3) & ~3) + 4) + 4)(%eax), %edx - movl %edx, 12(%esp) - leal 8(%ebp), %edx -.stubraw: - movl %edx, 8(%esp) - leal -24(%ebp), %edx - movl %edx, 4(%esp) - movl %esi, (%esp) - call *(((52 + 3) & ~3) + 4)(%eax) - movl 20(%esi), %eax -0: - call 1f - -.Lrcls_store_table: - .long .Lrcls_noretval - .long .Lrcls_retint - .long .Lrcls_retfloat - .long .Lrcls_retdouble - .long .Lrcls_retldouble - .long .Lrcls_retuint8 - .long .Lrcls_retsint8 - .long .Lrcls_retuint16 - .long .Lrcls_retsint16 - .long .Lrcls_retint - .long .Lrcls_retint - .long .Lrcls_retllong - .long .Lrcls_retllong - .long .Lrcls_retstruct - .long .Lrcls_retint - .long .Lrcls_retstruct1 - .long .Lrcls_retstruct2 - .long .Lrcls_retstruct4 - .long .Lrcls_retstruct -1: - add %eax, %eax - add %eax, %eax - add (%esp),%eax - add $4, %esp - jmp *(%eax) - - -.Lrcls_retsint8: - movsbl -24(%ebp), %eax - jmp .Lrcls_epilogue - -.Lrcls_retsint16: - movswl -24(%ebp), %eax - jmp .Lrcls_epilogue - -.Lrcls_retuint8: - movzbl -24(%ebp), %eax - jmp .Lrcls_epilogue - -.Lrcls_retuint16: - movzwl -24(%ebp), %eax - jmp .Lrcls_epilogue - -.Lrcls_retint: - movl -24(%ebp), %eax - jmp .Lrcls_epilogue - -.Lrcls_retfloat: - flds -24(%ebp) - jmp .Lrcls_epilogue - -.Lrcls_retdouble: - fldl -24(%ebp) - jmp .Lrcls_epilogue - -.Lrcls_retldouble: - fldt -24(%ebp) - jmp .Lrcls_epilogue - -.Lrcls_retllong: - movl -24(%ebp), %eax - movl -20(%ebp), %edx - jmp .Lrcls_epilogue - -.Lrcls_retstruct1: - movsbl -24(%ebp), %eax - jmp .Lrcls_epilogue - -.Lrcls_retstruct2: - movswl -24(%ebp), %eax - jmp .Lrcls_epilogue - -.Lrcls_retstruct4: - movl -24(%ebp), %eax - jmp .Lrcls_epilogue - -.Lrcls_retstruct: - - -.Lrcls_noretval: -.Lrcls_epilogue: - addl $36, %esp - popl %esi - popl %ebp - ret -.ffi_closure_raw_SYSV_end: -.LFE4: - - - - - .balign 16 - .globl _ffi_closure_STDCALL - - .def _ffi_closure_STDCALL; .scl 2; .type 32; .endef - -_ffi_closure_STDCALL: -.LFB5: - pushl %ebp -.LCFI9: - movl %esp, %ebp -.LCFI10: - subl $40, %esp - leal -24(%ebp), %edx - movl %edx, -12(%ebp) - leal 12(%ebp), %edx - movl %edx, 4(%esp) - leal -12(%ebp), %edx - movl %edx, (%esp) - call _ffi_closure_SYSV_inner - movl -12(%ebp), %ecx -0: - call 1f - -.Lscls_store_table: - .long .Lscls_noretval - .long .Lscls_retint - .long .Lscls_retfloat - .long .Lscls_retdouble - .long .Lscls_retldouble - .long .Lscls_retuint8 - .long .Lscls_retsint8 - .long .Lscls_retuint16 - .long .Lscls_retsint16 - .long .Lscls_retint - .long .Lscls_retint - .long .Lscls_retllong - .long .Lscls_retllong - .long .Lscls_retstruct - .long .Lscls_retint - .long .Lscls_retstruct1 - .long .Lscls_retstruct2 - .long .Lscls_retstruct4 -1: - add %eax, %eax - add %eax, %eax - add (%esp),%eax - add $4, %esp - jmp *(%eax) - - -.Lscls_retsint8: - movsbl (%ecx), %eax - jmp .Lscls_epilogue - -.Lscls_retsint16: - movswl (%ecx), %eax - jmp .Lscls_epilogue - -.Lscls_retuint8: - movzbl (%ecx), %eax - jmp .Lscls_epilogue - -.Lscls_retuint16: - movzwl (%ecx), %eax - jmp .Lscls_epilogue - -.Lscls_retint: - movl (%ecx), %eax - jmp .Lscls_epilogue - -.Lscls_retfloat: - flds (%ecx) - jmp .Lscls_epilogue - -.Lscls_retdouble: - fldl (%ecx) - jmp .Lscls_epilogue - -.Lscls_retldouble: - fldt (%ecx) - jmp .Lscls_epilogue - -.Lscls_retllong: - movl (%ecx), %eax - movl 4(%ecx), %edx - jmp .Lscls_epilogue - -.Lscls_retstruct1: - movsbl (%ecx), %eax - jmp .Lscls_epilogue - -.Lscls_retstruct2: - movswl (%ecx), %eax - jmp .Lscls_epilogue - -.Lscls_retstruct4: - movl (%ecx), %eax - jmp .Lscls_epilogue - -.Lscls_retstruct: - - -.Lscls_noretval: -.Lscls_epilogue: - movl %ebp, %esp - popl %ebp - ret -.ffi_closure_STDCALL_end: -.LFE5: - - - .section .eh_frame,"w" - -.Lframe1: -.LSCIE1: - .long .LECIE1-.LASCIE1 -.LASCIE1: - .long 0x0 - .byte 0x1 - - - - .ascii "\0" - - .byte 0x1 - .byte 0x7c - .byte 0x8 - - - - - .byte 0xc - .byte 0x4 - .byte 0x4 - .byte 0x88 - .byte 0x1 - .align 4 -.LECIE1: - -.LSFDE1: - .long .LEFDE1-.LASFDE1 -.LASFDE1: - .long .LASFDE1-.Lframe1 - - - - .long .LFB1 - - .long .LFE1-.LFB1 - - - - - - .byte 0x4 - .long .LCFI0-.LFB1 - .byte 0xe - .byte 0x8 - .byte 0x85 - .byte 0x2 - - .byte 0x4 - .long .LCFI1-.LCFI0 - .byte 0xd - .byte 0x5 - - - .align 4 -.LEFDE1: - - -.LSFDE3: - .long .LEFDE3-.LASFDE3 -.LASFDE3: - .long .LASFDE3-.Lframe1 - - - - .long .LFB3 - - .long .LFE3-.LFB3 - - - - - - .byte 0x4 - .long .LCFI4-.LFB3 - .byte 0xe - .byte 0x8 - .byte 0x85 - .byte 0x2 - - .byte 0x4 - .long .LCFI5-.LCFI4 - .byte 0xd - .byte 0x5 - - - .align 4 -.LEFDE3: - - - -.LSFDE4: - .long .LEFDE4-.LASFDE4 -.LASFDE4: - .long .LASFDE4-.Lframe1 - - - - .long .LFB4 - - .long .LFE4-.LFB4 - - - - - - .byte 0x4 - .long .LCFI6-.LFB4 - .byte 0xe - .byte 0x8 - .byte 0x85 - .byte 0x2 - - .byte 0x4 - .long .LCFI7-.LCFI6 - .byte 0xd - .byte 0x5 - - .byte 0x4 - .long .LCFI8-.LCFI7 - .byte 0x86 - .byte 0x3 - - - .align 4 -.LEFDE4: - - - -.LSFDE5: - .long .LEFDE5-.LASFDE5 -.LASFDE5: - .long .LASFDE5-.Lframe1 - - - - .long .LFB5 - - .long .LFE5-.LFB5 - - - - - - .byte 0x4 - .long .LCFI9-.LFB5 - .byte 0xe - .byte 0x8 - .byte 0x85 - .byte 0x2 - - .byte 0x4 - .long .LCFI10-.LCFI9 - .byte 0xd - .byte 0x5 - - - .align 4 -.LEFDE5: diff --git a/lib/wrappers/libffi/gcc/win64_asm.asm b/lib/wrappers/libffi/gcc/win64_asm.asm deleted file mode 100644 index 1dc98f99a..000000000 --- a/lib/wrappers/libffi/gcc/win64_asm.asm +++ /dev/null @@ -1,467 +0,0 @@ -#define LIBFFI_ASM -#include -#include - -/* Constants for ffi_call_win64 */ -#define STACK 0 -#define PREP_ARGS_FN 32 -#define ECIF 40 -#define CIF_BYTES 48 -#define CIF_FLAGS 56 -#define RVALUE 64 -#define FN 72 - -/* ffi_call_win64 (void (*prep_args_fn)(char *, extended_cif *), - extended_cif *ecif, unsigned bytes, unsigned flags, - unsigned *rvalue, void (*fn)()); - */ - -#ifdef _MSC_VER -PUBLIC ffi_call_win64 - -EXTRN __chkstk:NEAR -EXTRN ffi_closure_win64_inner:NEAR - -_TEXT SEGMENT - -;;; ffi_closure_win64 will be called with these registers set: -;;; rax points to 'closure' -;;; r11 contains a bit mask that specifies which of the -;;; first four parameters are float or double -;;; -;;; It must move the parameters passed in registers to their stack location, -;;; call ffi_closure_win64_inner for the actual work, then return the result. -;;; -ffi_closure_win64 PROC FRAME - ;; copy register arguments onto stack - test r11, 1 - jne first_is_float - mov QWORD PTR [rsp+8], rcx - jmp second -first_is_float: - movlpd QWORD PTR [rsp+8], xmm0 - -second: - test r11, 2 - jne second_is_float - mov QWORD PTR [rsp+16], rdx - jmp third -second_is_float: - movlpd QWORD PTR [rsp+16], xmm1 - -third: - test r11, 4 - jne third_is_float - mov QWORD PTR [rsp+24], r8 - jmp fourth -third_is_float: - movlpd QWORD PTR [rsp+24], xmm2 - -fourth: - test r11, 8 - jne fourth_is_float - mov QWORD PTR [rsp+32], r9 - jmp done -fourth_is_float: - movlpd QWORD PTR [rsp+32], xmm3 - -done: - .ALLOCSTACK 40 - sub rsp, 40 - .ENDPROLOG - mov rcx, rax ; context is first parameter - mov rdx, rsp ; stack is second parameter - add rdx, 48 ; point to start of arguments - mov rax, ffi_closure_win64_inner - call rax ; call the real closure function - add rsp, 40 - movd xmm0, rax ; If the closure returned a float, - ; ffi_closure_win64_inner wrote it to rax - ret 0 -ffi_closure_win64 ENDP - -ffi_call_win64 PROC FRAME - ;; copy registers onto stack - mov QWORD PTR [rsp+32], r9 - mov QWORD PTR [rsp+24], r8 - mov QWORD PTR [rsp+16], rdx - mov QWORD PTR [rsp+8], rcx - .PUSHREG rbp - push rbp - .ALLOCSTACK 48 - sub rsp, 48 ; 00000030H - .SETFRAME rbp, 32 - lea rbp, QWORD PTR [rsp+32] - .ENDPROLOG - - mov eax, DWORD PTR CIF_BYTES[rbp] - add rax, 15 - and rax, -16 - call __chkstk - sub rsp, rax - lea rax, QWORD PTR [rsp+32] - mov QWORD PTR STACK[rbp], rax - - mov rdx, QWORD PTR ECIF[rbp] - mov rcx, QWORD PTR STACK[rbp] - call QWORD PTR PREP_ARGS_FN[rbp] - - mov rsp, QWORD PTR STACK[rbp] - - movlpd xmm3, QWORD PTR [rsp+24] - movd r9, xmm3 - - movlpd xmm2, QWORD PTR [rsp+16] - movd r8, xmm2 - - movlpd xmm1, QWORD PTR [rsp+8] - movd rdx, xmm1 - - movlpd xmm0, QWORD PTR [rsp] - movd rcx, xmm0 - - call QWORD PTR FN[rbp] -ret_struct4b$: - cmp DWORD PTR CIF_FLAGS[rbp], FFI_TYPE_SMALL_STRUCT_4B - jne ret_struct2b$ - - mov rcx, QWORD PTR RVALUE[rbp] - mov DWORD PTR [rcx], eax - jmp ret_void$ - -ret_struct2b$: - cmp DWORD PTR CIF_FLAGS[rbp], FFI_TYPE_SMALL_STRUCT_2B - jne ret_struct1b$ - - mov rcx, QWORD PTR RVALUE[rbp] - mov WORD PTR [rcx], ax - jmp ret_void$ - -ret_struct1b$: - cmp DWORD PTR CIF_FLAGS[rbp], FFI_TYPE_SMALL_STRUCT_1B - jne ret_uint8$ - - mov rcx, QWORD PTR RVALUE[rbp] - mov BYTE PTR [rcx], al - jmp ret_void$ - -ret_uint8$: - cmp DWORD PTR CIF_FLAGS[rbp], FFI_TYPE_UINT8 - jne ret_sint8$ - - mov rcx, QWORD PTR RVALUE[rbp] - movzx rax, al - mov QWORD PTR [rcx], rax - jmp ret_void$ - -ret_sint8$: - cmp DWORD PTR CIF_FLAGS[rbp], FFI_TYPE_SINT8 - jne ret_uint16$ - - mov rcx, QWORD PTR RVALUE[rbp] - movsx rax, al - mov QWORD PTR [rcx], rax - jmp ret_void$ - -ret_uint16$: - cmp DWORD PTR CIF_FLAGS[rbp], FFI_TYPE_UINT16 - jne ret_sint16$ - - mov rcx, QWORD PTR RVALUE[rbp] - movzx rax, ax - mov QWORD PTR [rcx], rax - jmp SHORT ret_void$ - -ret_sint16$: - cmp DWORD PTR CIF_FLAGS[rbp], FFI_TYPE_SINT16 - jne ret_uint32$ - - mov rcx, QWORD PTR RVALUE[rbp] - movsx rax, ax - mov QWORD PTR [rcx], rax - jmp SHORT ret_void$ - -ret_uint32$: - cmp DWORD PTR CIF_FLAGS[rbp], FFI_TYPE_UINT32 - jne ret_sint32$ - - mov rcx, QWORD PTR RVALUE[rbp] - mov eax, eax - mov QWORD PTR [rcx], rax - jmp SHORT ret_void$ - -ret_sint32$: - cmp DWORD PTR CIF_FLAGS[rbp], FFI_TYPE_SINT32 - jne ret_float$ - - mov rcx, QWORD PTR RVALUE[rbp] - cdqe - mov QWORD PTR [rcx], rax - jmp SHORT ret_void$ - -ret_float$: - cmp DWORD PTR CIF_FLAGS[rbp], FFI_TYPE_FLOAT - jne SHORT ret_double$ - - mov rax, QWORD PTR RVALUE[rbp] - movss DWORD PTR [rax], xmm0 - jmp SHORT ret_void$ - -ret_double$: - cmp DWORD PTR CIF_FLAGS[rbp], FFI_TYPE_DOUBLE - jne SHORT ret_sint64$ - - mov rax, QWORD PTR RVALUE[rbp] - movlpd QWORD PTR [rax], xmm0 - jmp SHORT ret_void$ - -ret_sint64$: - cmp DWORD PTR CIF_FLAGS[rbp], FFI_TYPE_SINT64 - jne ret_void$ - - mov rcx, QWORD PTR RVALUE[rbp] - mov QWORD PTR [rcx], rax - jmp SHORT ret_void$ - -ret_void$: - xor rax, rax - - lea rsp, QWORD PTR [rbp+16] - pop rbp - ret 0 -ffi_call_win64 ENDP -_TEXT ENDS -END - -#else - -#ifdef SYMBOL_UNDERSCORE -#define SYMBOL_NAME(name) _##name -#else -#define SYMBOL_NAME(name) name -#endif - -.text - -.extern SYMBOL_NAME(ffi_closure_win64_inner) - -// ffi_closure_win64 will be called with these registers set: -// rax points to 'closure' -// r11 contains a bit mask that specifies which of the -// first four parameters are float or double -// // It must move the parameters passed in registers to their stack location, -// call ffi_closure_win64_inner for the actual work, then return the result. -// - .balign 16 - .globl SYMBOL_NAME(ffi_closure_win64) -SYMBOL_NAME(ffi_closure_win64): - // copy register arguments onto stack - test $1,%r11 - jne .Lfirst_is_float - mov %rcx, 8(%rsp) - jmp .Lsecond -.Lfirst_is_float: - movlpd %xmm0, 8(%rsp) - -.Lsecond: - test $2, %r11 - jne .Lsecond_is_float - mov %rdx, 16(%rsp) - jmp .Lthird -.Lsecond_is_float: - movlpd %xmm1, 16(%rsp) - -.Lthird: - test $4, %r11 - jne .Lthird_is_float - mov %r8,24(%rsp) - jmp .Lfourth -.Lthird_is_float: - movlpd %xmm2, 24(%rsp) - -.Lfourth: - test $8, %r11 - jne .Lfourth_is_float - mov %r9, 32(%rsp) - jmp .Ldone -.Lfourth_is_float: - movlpd %xmm3, 32(%rsp) - -.Ldone: -// ALLOCSTACK 40 - sub $40, %rsp -// ENDPROLOG - mov %rax, %rcx // context is first parameter - mov %rsp, %rdx // stack is second parameter - add $48, %rdx // point to start of arguments - mov $SYMBOL_NAME(ffi_closure_win64_inner), %rax - callq *%rax // call the real closure function - add $40, %rsp - movq %rax, %xmm0 // If the closure returned a float, - // ffi_closure_win64_inner wrote it to rax - retq -.ffi_closure_win64_end: - - .balign 16 - .globl SYMBOL_NAME(ffi_call_win64) -SYMBOL_NAME(ffi_call_win64): - // copy registers onto stack - mov %r9,32(%rsp) - mov %r8,24(%rsp) - mov %rdx,16(%rsp) - mov %rcx,8(%rsp) - // PUSHREG rbp - push %rbp - // ALLOCSTACK 48 - sub $48,%rsp - // SETFRAME rbp, 32 - lea 32(%rsp),%rbp - // ENDPROLOG - - mov CIF_BYTES(%rbp),%eax - add $15, %rax - and $-16, %rax - cmpq $0x1000, %rax - jb Lch_done -Lch_probe: - subq $0x1000,%rsp - orl $0x0, (%rsp) - subq $0x1000,%rax - cmpq $0x1000,%rax - ja Lch_probe -Lch_done: - subq %rax, %rsp - orl $0x0, (%rsp) - lea 32(%rsp), %rax - mov %rax, STACK(%rbp) - - mov ECIF(%rbp), %rdx - mov STACK(%rbp), %rcx - callq *PREP_ARGS_FN(%rbp) - - mov STACK(%rbp), %rsp - - movlpd 24(%rsp), %xmm3 - movd %xmm3, %r9 - - movlpd 16(%rsp), %xmm2 - movd %xmm2, %r8 - - movlpd 8(%rsp), %xmm1 - movd %xmm1, %rdx - - movlpd (%rsp), %xmm0 - movd %xmm0, %rcx - - callq *FN(%rbp) -.Lret_struct4b: - cmpl $FFI_TYPE_SMALL_STRUCT_4B, CIF_FLAGS(%rbp) - jne .Lret_struct2b - - mov RVALUE(%rbp), %rcx - mov %eax, (%rcx) - jmp .Lret_void - -.Lret_struct2b: - cmpl $FFI_TYPE_SMALL_STRUCT_2B, CIF_FLAGS(%rbp) - jne .Lret_struct1b - - mov RVALUE(%rbp), %rcx - mov %ax, (%rcx) - jmp .Lret_void - -.Lret_struct1b: - cmpl $FFI_TYPE_SMALL_STRUCT_1B, CIF_FLAGS(%rbp) - jne .Lret_uint8 - - mov RVALUE(%rbp), %rcx - mov %al, (%rcx) - jmp .Lret_void - -.Lret_uint8: - cmpl $FFI_TYPE_UINT8, CIF_FLAGS(%rbp) - jne .Lret_sint8 - - mov RVALUE(%rbp), %rcx - movzbq %al, %rax - movq %rax, (%rcx) - jmp .Lret_void - -.Lret_sint8: - cmpl $FFI_TYPE_SINT8, CIF_FLAGS(%rbp) - jne .Lret_uint16 - - mov RVALUE(%rbp), %rcx - movsbq %al, %rax - movq %rax, (%rcx) - jmp .Lret_void - -.Lret_uint16: - cmpl $FFI_TYPE_UINT16, CIF_FLAGS(%rbp) - jne .Lret_sint16 - - mov RVALUE(%rbp), %rcx - movzwq %ax, %rax - movq %rax, (%rcx) - jmp .Lret_void - -.Lret_sint16: - cmpl $FFI_TYPE_SINT16, CIF_FLAGS(%rbp) - jne .Lret_uint32 - - mov RVALUE(%rbp), %rcx - movswq %ax, %rax - movq %rax, (%rcx) - jmp .Lret_void - -.Lret_uint32: - cmpl $FFI_TYPE_UINT32, CIF_FLAGS(%rbp) - jne .Lret_sint32 - - mov RVALUE(%rbp), %rcx - movl %eax, %eax - movq %rax, (%rcx) - jmp .Lret_void - -.Lret_sint32: - cmpl $FFI_TYPE_SINT32, CIF_FLAGS(%rbp) - jne .Lret_float - - mov RVALUE(%rbp), %rcx - cltq - movq %rax, (%rcx) - jmp .Lret_void - -.Lret_float: - cmpl $FFI_TYPE_FLOAT, CIF_FLAGS(%rbp) - jne .Lret_double - - mov RVALUE(%rbp), %rax - movss %xmm0, (%rax) - jmp .Lret_void - -.Lret_double: - cmpl $FFI_TYPE_DOUBLE, CIF_FLAGS(%rbp) - jne .Lret_sint64 - - mov RVALUE(%rbp), %rax - movlpd %xmm0, (%rax) - jmp .Lret_void - -.Lret_sint64: - cmpl $FFI_TYPE_SINT64, CIF_FLAGS(%rbp) - jne .Lret_void - - mov RVALUE(%rbp), %rcx - mov %rax, (%rcx) - jmp .Lret_void - -.Lret_void: - xor %rax, %rax - - lea 16(%rbp), %rsp - pop %rbp - retq -.ffi_call_win64_end: -#endif /* !_MSC_VER */ - diff --git a/lib/wrappers/libffi/gcc/win64_asm.s b/lib/wrappers/libffi/gcc/win64_asm.s deleted file mode 100644 index f2c2df10d..000000000 --- a/lib/wrappers/libffi/gcc/win64_asm.s +++ /dev/null @@ -1,227 +0,0 @@ -# 1 "gcc\\win64_asm.asm" -# 1 "" -# 1 "gcc\\win64_asm.asm" - -# 1 "common/fficonfig.h" 1 -# 3 "gcc\\win64_asm.asm" 2 -# 1 "common/ffi.h" 1 -# 63 "common/ffi.h" -# 1 "common/ffitarget.h" 1 -# 64 "common/ffi.h" 2 -# 4 "gcc\\win64_asm.asm" 2 -# 244 "gcc\\win64_asm.asm" -.text - -.extern ffi_closure_win64_inner -# 255 "gcc\\win64_asm.asm" - .balign 16 - .globl ffi_closure_win64 -ffi_closure_win64: - - test $1,%r11 - jne .Lfirst_is_float - mov %rcx, 8(%rsp) - jmp .Lsecond -.Lfirst_is_float: - movlpd %xmm0, 8(%rsp) - -.Lsecond: - test $2, %r11 - jne .Lsecond_is_float - mov %rdx, 16(%rsp) - jmp .Lthird -.Lsecond_is_float: - movlpd %xmm1, 16(%rsp) - -.Lthird: - test $4, %r11 - jne .Lthird_is_float - mov %r8,24(%rsp) - jmp .Lfourth -.Lthird_is_float: - movlpd %xmm2, 24(%rsp) - -.Lfourth: - test $8, %r11 - jne .Lfourth_is_float - mov %r9, 32(%rsp) - jmp .Ldone -.Lfourth_is_float: - movlpd %xmm3, 32(%rsp) - -.Ldone: - - sub $40, %rsp - - mov %rax, %rcx - mov %rsp, %rdx - add $48, %rdx - mov $SYMBOL_NAME(ffi_closure_win64_inner), %rax - callq *%rax - add $40, %rsp - movq %rax, %xmm0 - - retq -.ffi_closure_win64_end: - - .balign 16 - .globl ffi_call_win64 -ffi_call_win64: - - mov %r9,32(%rsp) - mov %r8,24(%rsp) - mov %rdx,16(%rsp) - mov %rcx,8(%rsp) - - push %rbp - - sub $48,%rsp - - lea 32(%rsp),%rbp - - - mov 48(%rbp),%eax - add $15, %rax - and $-16, %rax - cmpq $0x1000, %rax - jb Lch_done -Lch_probe: - subq $0x1000,%rsp - orl $0x0, (%rsp) - subq $0x1000,%rax - cmpq $0x1000,%rax - ja Lch_probe -Lch_done: - subq %rax, %rsp - orl $0x0, (%rsp) - lea 32(%rsp), %rax - mov %rax, 0(%rbp) - - mov 40(%rbp), %rdx - mov 0(%rbp), %rcx - callq *32(%rbp) - - mov 0(%rbp), %rsp - - movlpd 24(%rsp), %xmm3 - movd %xmm3, %r9 - - movlpd 16(%rsp), %xmm2 - movd %xmm2, %r8 - - movlpd 8(%rsp), %xmm1 - movd %xmm1, %rdx - - movlpd (%rsp), %xmm0 - movd %xmm0, %rcx - - callq *72(%rbp) -.Lret_struct4b: - cmpl $FFI_TYPE_SMALL_STRUCT_4B, 56(%rbp) - jne .Lret_struct2b - - mov 64(%rbp), %rcx - mov %eax, (%rcx) - jmp .Lret_void - -.Lret_struct2b: - cmpl $FFI_TYPE_SMALL_STRUCT_2B, 56(%rbp) - jne .Lret_struct1b - - mov 64(%rbp), %rcx - mov %ax, (%rcx) - jmp .Lret_void - -.Lret_struct1b: - cmpl $FFI_TYPE_SMALL_STRUCT_1B, 56(%rbp) - jne .Lret_uint8 - - mov 64(%rbp), %rcx - mov %al, (%rcx) - jmp .Lret_void - -.Lret_uint8: - cmpl $FFI_TYPE_UINT8, 56(%rbp) - jne .Lret_sint8 - - mov 64(%rbp), %rcx - movzbq %al, %rax - movq %rax, (%rcx) - jmp .Lret_void - -.Lret_sint8: - cmpl $FFI_TYPE_SINT8, 56(%rbp) - jne .Lret_uint16 - - mov 64(%rbp), %rcx - movsbq %al, %rax - movq %rax, (%rcx) - jmp .Lret_void - -.Lret_uint16: - cmpl $FFI_TYPE_UINT16, 56(%rbp) - jne .Lret_sint16 - - mov 64(%rbp), %rcx - movzwq %ax, %rax - movq %rax, (%rcx) - jmp .Lret_void - -.Lret_sint16: - cmpl $FFI_TYPE_SINT16, 56(%rbp) - jne .Lret_uint32 - - mov 64(%rbp), %rcx - movswq %ax, %rax - movq %rax, (%rcx) - jmp .Lret_void - -.Lret_uint32: - cmpl $9, 56(%rbp) - jne .Lret_sint32 - - mov 64(%rbp), %rcx - movl %eax, %eax - movq %rax, (%rcx) - jmp .Lret_void - -.Lret_sint32: - cmpl $10, 56(%rbp) - jne .Lret_float - - mov 64(%rbp), %rcx - cltq - movq %rax, (%rcx) - jmp .Lret_void - -.Lret_float: - cmpl $2, 56(%rbp) - jne .Lret_double - - mov 64(%rbp), %rax - movss %xmm0, (%rax) - jmp .Lret_void - -.Lret_double: - cmpl $3, 56(%rbp) - jne .Lret_sint64 - - mov 64(%rbp), %rax - movlpd %xmm0, (%rax) - jmp .Lret_void - -.Lret_sint64: - cmpl $12, 56(%rbp) - jne .Lret_void - - mov 64(%rbp), %rcx - mov %rax, (%rcx) - jmp .Lret_void - -.Lret_void: - xor %rax, %rax - - lea 16(%rbp), %rsp - pop %rbp - retq -.ffi_call_win64_end: diff --git a/lib/wrappers/libffi/libffi.nim b/lib/wrappers/libffi/libffi.nim deleted file mode 100644 index 34b91f8c7..000000000 --- a/lib/wrappers/libffi/libffi.nim +++ /dev/null @@ -1,176 +0,0 @@ -# -----------------------------------------------------------------*-C-*- -# libffi 3.0.10 - Copyright (c) 2011 Anthony Green -# - Copyright (c) 1996-2003, 2007, 2008 Red Hat, Inc. -# -# Permission is hereby granted, free of charge, to any person -# obtaining a copy of this software and associated documentation -# files (the ``Software''), to deal in the Software without -# restriction, including without limitation the rights to use, copy, -# modify, merge, publish, distribute, sublicense, and/or sell copies -# of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be -# included in all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, -# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -# DEALINGS IN THE SOFTWARE. -# -# ----------------------------------------------------------------------- - -{.deadCodeElim: on.} - -when defined(windows): - # on Windows we don't use a DLL but instead embed libffi directly: - {.pragma: mylib, header: r"ffi.h".} - - #{.compile: r"common\malloc_closure.c".} - {.compile: r"common\raw_api.c".} - when defined(vcc): - {.compile: r"msvc\ffi.c".} - {.compile: r"msvc\prep_cif.c".} - {.compile: r"msvc\win32.c".} - {.compile: r"msvc\types.c".} - when defined(cpu64): - {.compile: r"msvc\win64_asm.asm".} - else: - {.compile: r"msvc\win32_asm.asm".} - else: - {.compile: r"gcc\ffi.c".} - {.compile: r"gcc\prep_cif.c".} - {.compile: r"gcc\types.c".} - {.compile: r"gcc\closures.c".} - when defined(cpu64): - {.compile: r"gcc\ffi64.c".} - {.compile: r"gcc\win64_asm.S".} - else: - {.compile: r"gcc\win32_asm.S".} - -elif defined(macosx): - {.pragma: mylib, dynlib: "libffi.dylib".} -else: - {.pragma: mylib, dynlib: "libffi.so".} - -type - Arg* = int - SArg* = int -{.deprecated: [TArg: Arg, TSArg: SArg].} - -when defined(windows) and defined(x86): - type - TABI* {.size: sizeof(cint).} = enum - FIRST_ABI, SYSV, STDCALL - - const DEFAULT_ABI* = SYSV -elif defined(amd64) and defined(windows): - type - TABI* {.size: sizeof(cint).} = enum - FIRST_ABI, WIN64 - const DEFAULT_ABI* = WIN64 -else: - type - TABI* {.size: sizeof(cint).} = enum - FIRST_ABI, SYSV, UNIX64 - - when defined(i386): - const DEFAULT_ABI* = SYSV - else: - const DEFAULT_ABI* = UNIX64 - -const - tkVOID* = 0 - tkINT* = 1 - tkFLOAT* = 2 - tkDOUBLE* = 3 - tkLONGDOUBLE* = 4 - tkUINT8* = 5 - tkSINT8* = 6 - tkUINT16* = 7 - tkSINT16* = 8 - tkUINT32* = 9 - tkSINT32* = 10 - tkUINT64* = 11 - tkSINT64* = 12 - tkSTRUCT* = 13 - tkPOINTER* = 14 - - tkLAST = tkPOINTER - tkSMALL_STRUCT_1B* = (tkLAST + 1) - tkSMALL_STRUCT_2B* = (tkLAST + 2) - tkSMALL_STRUCT_4B* = (tkLAST + 3) - -type - Type* = object - size*: int - alignment*: uint16 - typ*: uint16 - elements*: ptr ptr Type -{.deprecated: [TType: Type].} - -var - type_void* {.importc: "ffi_type_void", mylib.}: Type - type_uint8* {.importc: "ffi_type_uint8", mylib.}: Type - type_sint8* {.importc: "ffi_type_sint8", mylib.}: Type - type_uint16* {.importc: "ffi_type_uint16", mylib.}: Type - type_sint16* {.importc: "ffi_type_sint16", mylib.}: Type - type_uint32* {.importc: "ffi_type_uint32", mylib.}: Type - type_sint32* {.importc: "ffi_type_sint32", mylib.}: Type - type_uint64* {.importc: "ffi_type_uint64", mylib.}: Type - type_sint64* {.importc: "ffi_type_sint64", mylib.}: Type - type_float* {.importc: "ffi_type_float", mylib.}: Type - type_double* {.importc: "ffi_type_double", mylib.}: Type - type_pointer* {.importc: "ffi_type_pointer", mylib.}: Type - type_longdouble* {.importc: "ffi_type_longdouble", mylib.}: Type - -type - Status* {.size: sizeof(cint).} = enum - OK, BAD_TYPEDEF, BAD_ABI - TypeKind* = cuint - TCif* {.pure, final.} = object - abi*: TABI - nargs*: cuint - arg_types*: ptr ptr Type - rtype*: ptr Type - bytes*: cuint - flags*: cuint -{.deprecated: [Tstatus: Status].} - -type - Raw* = object - sint*: SArg -{.deprecated: [TRaw: Raw].} - -proc raw_call*(cif: var Tcif; fn: proc () {.cdecl.}; rvalue: pointer; - avalue: ptr Raw) {.cdecl, importc: "ffi_raw_call", mylib.} -proc ptrarray_to_raw*(cif: var Tcif; args: ptr pointer; raw: ptr Raw) {.cdecl, - importc: "ffi_ptrarray_to_raw", mylib.} -proc raw_to_ptrarray*(cif: var Tcif; raw: ptr Raw; args: ptr pointer) {.cdecl, - importc: "ffi_raw_to_ptrarray", mylib.} -proc raw_size*(cif: var Tcif): int {.cdecl, importc: "ffi_raw_size", mylib.} - -proc prep_cif*(cif: var Tcif; abi: TABI; nargs: cuint; rtype: ptr Type; - atypes: ptr ptr Type): Status {.cdecl, importc: "ffi_prep_cif", - mylib.} -proc call*(cif: var Tcif; fn: proc () {.cdecl.}; rvalue: pointer; - avalue: ptr pointer) {.cdecl, importc: "ffi_call", mylib.} - -# the same with an easier interface: -type - ParamList* = array[0..100, ptr Type] - ArgList* = array[0..100, pointer] -{.deprecated: [TParamList: ParamList, TArgList: ArgList].} - -proc prep_cif*(cif: var Tcif; abi: TABI; nargs: cuint; rtype: ptr Type; - atypes: ParamList): Status {.cdecl, importc: "ffi_prep_cif", - mylib.} -proc call*(cif: var Tcif; fn, rvalue: pointer; - avalue: ArgList) {.cdecl, importc: "ffi_call", mylib.} - -# Useful for eliminating compiler warnings -##define FFI_FN(f) ((void (*)(void))f) diff --git a/lib/wrappers/libffi/msvc/ffi.c b/lib/wrappers/libffi/msvc/ffi.c deleted file mode 100644 index 6e595e9fe..000000000 --- a/lib/wrappers/libffi/msvc/ffi.c +++ /dev/null @@ -1,457 +0,0 @@ -/* ----------------------------------------------------------------------- - ffi.c - Copyright (c) 1996, 1998, 1999, 2001 Red Hat, Inc. - Copyright (c) 2002 Ranjit Mathew - Copyright (c) 2002 Bo Thorsen - Copyright (c) 2002 Roger Sayle - - x86 Foreign Function Interface - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files (the - ``Software''), to deal in the Software without restriction, including - without limitation the rights to use, copy, modify, merge, publish, - distribute, sublicense, and/or sell copies of the Software, and to - permit persons to whom the Software is furnished to do so, subject to - the following conditions: - - The above copyright notice and this permission notice shall be included - in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. - ----------------------------------------------------------------------- */ - -#include -#include - -#include - -/* ffi_prep_args is called by the assembly routine once stack space - has been allocated for the function's arguments */ - -extern void Py_FatalError(const char *msg); - -/*@-exportheader@*/ -void ffi_prep_args(char *stack, extended_cif *ecif) -/*@=exportheader@*/ -{ - register unsigned int i; - register void **p_argv; - register char *argp; - register ffi_type **p_arg; - - argp = stack; - if (ecif->cif->rtype->type == FFI_TYPE_STRUCT) - { - *(void **) argp = ecif->rvalue; - argp += sizeof(void *); - } - - p_argv = ecif->avalue; - - for (i = ecif->cif->nargs, p_arg = ecif->cif->arg_types; - i != 0; - i--, p_arg++) - { - size_t z; - - /* Align if necessary */ - if ((sizeof(void *) - 1) & (size_t) argp) - argp = (char *) ALIGN(argp, sizeof(void *)); - - z = (*p_arg)->size; - if (z < sizeof(int)) - { - z = sizeof(int); - switch ((*p_arg)->type) - { - case FFI_TYPE_SINT8: - *(signed int *) argp = (signed int)*(SINT8 *)(* p_argv); - break; - - case FFI_TYPE_UINT8: - *(unsigned int *) argp = (unsigned int)*(UINT8 *)(* p_argv); - break; - - case FFI_TYPE_SINT16: - *(signed int *) argp = (signed int)*(SINT16 *)(* p_argv); - break; - - case FFI_TYPE_UINT16: - *(unsigned int *) argp = (unsigned int)*(UINT16 *)(* p_argv); - break; - - case FFI_TYPE_SINT32: - *(signed int *) argp = (signed int)*(SINT32 *)(* p_argv); - break; - - case FFI_TYPE_UINT32: - *(unsigned int *) argp = (unsigned int)*(UINT32 *)(* p_argv); - break; - - case FFI_TYPE_STRUCT: - *(unsigned int *) argp = (unsigned int)*(UINT32 *)(* p_argv); - break; - - default: - FFI_ASSERT(0); - } - } - else - { - memcpy(argp, *p_argv, z); - } - p_argv++; - argp += z; - } - - if (argp >= stack && (unsigned)(argp - stack) > ecif->cif->bytes) - { - Py_FatalError("FFI BUG: not enough stack space for arguments"); - } - return; -} - -/* Perform machine dependent cif processing */ -ffi_status ffi_prep_cif_machdep(ffi_cif *cif) -{ - /* Set the return type flag */ - switch (cif->rtype->type) - { - case FFI_TYPE_VOID: - case FFI_TYPE_STRUCT: - case FFI_TYPE_SINT64: - case FFI_TYPE_FLOAT: - case FFI_TYPE_DOUBLE: - case FFI_TYPE_LONGDOUBLE: - cif->flags = (unsigned) cif->rtype->type; - break; - - case FFI_TYPE_UINT64: -#ifdef _WIN64 - case FFI_TYPE_POINTER: -#endif - cif->flags = FFI_TYPE_SINT64; - break; - - default: - cif->flags = FFI_TYPE_INT; - break; - } - - return FFI_OK; -} - -#ifdef _WIN32 -extern int -ffi_call_x86(void (*)(char *, extended_cif *), - /*@out@*/ extended_cif *, - unsigned, unsigned, - /*@out@*/ unsigned *, - void (*fn)()); -#endif - -#ifdef _WIN64 -extern int -ffi_call_AMD64(void (*)(char *, extended_cif *), - /*@out@*/ extended_cif *, - unsigned, unsigned, - /*@out@*/ unsigned *, - void (*fn)()); -#endif - -int -ffi_call(/*@dependent@*/ ffi_cif *cif, - void (*fn)(), - /*@out@*/ void *rvalue, - /*@dependent@*/ void **avalue) -{ - extended_cif ecif; - - ecif.cif = cif; - ecif.avalue = avalue; - - /* If the return value is a struct and we don't have a return */ - /* value address then we need to make one */ - - if ((rvalue == NULL) && - (cif->rtype->type == FFI_TYPE_STRUCT)) - { - /*@-sysunrecog@*/ - ecif.rvalue = alloca(cif->rtype->size); - /*@=sysunrecog@*/ - } - else - ecif.rvalue = rvalue; - - - switch (cif->abi) - { -#if !defined(_WIN64) - case FFI_SYSV: - case FFI_STDCALL: - return ffi_call_x86(ffi_prep_args, &ecif, cif->bytes, - cif->flags, ecif.rvalue, fn); - break; -#else - case FFI_SYSV: - /*@-usedef@*/ - /* Function call needs at least 40 bytes stack size, on win64 AMD64 */ - return ffi_call_AMD64(ffi_prep_args, &ecif, cif->bytes ? cif->bytes : 40, - cif->flags, ecif.rvalue, fn); - /*@=usedef@*/ - break; -#endif - - default: - FFI_ASSERT(0); - break; - } - return -1; /* theller: Hrm. */ -} - - -/** private members **/ - -static void ffi_prep_incoming_args_SYSV (char *stack, void **ret, - void** args, ffi_cif* cif); -/* This function is jumped to by the trampoline */ - -#ifdef _WIN64 -void * -#else -static void __fastcall -#endif -ffi_closure_SYSV (ffi_closure *closure, int *argp) -{ - // this is our return value storage - long double res; - - // our various things... - ffi_cif *cif; - void **arg_area; - unsigned short rtype; - void *resp = (void*)&res; - void *args = &argp[1]; - - cif = closure->cif; - arg_area = (void**) alloca (cif->nargs * sizeof (void*)); - - /* this call will initialize ARG_AREA, such that each - * element in that array points to the corresponding - * value on the stack; and if the function returns - * a structure, it will re-set RESP to point to the - * structure return address. */ - - ffi_prep_incoming_args_SYSV(args, (void**)&resp, arg_area, cif); - - (closure->fun) (cif, resp, arg_area, closure->user_data); - - rtype = cif->flags; - -#if defined(_WIN32) && !defined(_WIN64) -#ifdef _MSC_VER - /* now, do a generic return based on the value of rtype */ - if (rtype == FFI_TYPE_INT) - { - _asm mov eax, resp ; - _asm mov eax, [eax] ; - } - else if (rtype == FFI_TYPE_FLOAT) - { - _asm mov eax, resp ; - _asm fld DWORD PTR [eax] ; -// asm ("flds (%0)" : : "r" (resp) : "st" ); - } - else if (rtype == FFI_TYPE_DOUBLE) - { - _asm mov eax, resp ; - _asm fld QWORD PTR [eax] ; -// asm ("fldl (%0)" : : "r" (resp) : "st", "st(1)" ); - } - else if (rtype == FFI_TYPE_LONGDOUBLE) - { -// asm ("fldt (%0)" : : "r" (resp) : "st", "st(1)" ); - } - else if (rtype == FFI_TYPE_SINT64) - { - _asm mov edx, resp ; - _asm mov eax, [edx] ; - _asm mov edx, [edx + 4] ; -// asm ("movl 0(%0),%%eax;" -// "movl 4(%0),%%edx" -// : : "r"(resp) -// : "eax", "edx"); - } -#else - /* now, do a generic return based on the value of rtype */ - if (rtype == FFI_TYPE_INT) - { - asm ("movl (%0),%%eax" : : "r" (resp) : "eax"); - } - else if (rtype == FFI_TYPE_FLOAT) - { - asm ("flds (%0)" : : "r" (resp) : "st" ); - } - else if (rtype == FFI_TYPE_DOUBLE) - { - asm ("fldl (%0)" : : "r" (resp) : "st", "st(1)" ); - } - else if (rtype == FFI_TYPE_LONGDOUBLE) - { - asm ("fldt (%0)" : : "r" (resp) : "st", "st(1)" ); - } - else if (rtype == FFI_TYPE_SINT64) - { - asm ("movl 0(%0),%%eax;" - "movl 4(%0),%%edx" - : : "r"(resp) - : "eax", "edx"); - } -#endif -#endif - -#ifdef _WIN64 - /* The result is returned in rax. This does the right thing for - result types except for floats; we have to 'mov xmm0, rax' in the - caller to correct this. - */ - return *(void **)resp; -#endif -} - -/*@-exportheader@*/ -static void -ffi_prep_incoming_args_SYSV(char *stack, void **rvalue, - void **avalue, ffi_cif *cif) -/*@=exportheader@*/ -{ - register unsigned int i; - register void **p_argv; - register char *argp; - register ffi_type **p_arg; - - argp = stack; - - if ( cif->rtype->type == FFI_TYPE_STRUCT ) { - *rvalue = *(void **) argp; - argp += 4; - } - - p_argv = avalue; - - for (i = cif->nargs, p_arg = cif->arg_types; (i != 0); i--, p_arg++) - { - size_t z; - - /* Align if necessary */ - if ((sizeof(char *) - 1) & (size_t) argp) { - argp = (char *) ALIGN(argp, sizeof(char*)); - } - - z = (*p_arg)->size; - - /* because we're little endian, this is what it turns into. */ - - *p_argv = (void*) argp; - - p_argv++; - argp += z; - } - - return; -} - -/* the cif must already be prep'ed */ -extern void ffi_closure_OUTER(); - -ffi_status -ffi_prep_closure_loc (ffi_closure* closure, - ffi_cif* cif, - void (*fun)(ffi_cif*,void*,void**,void*), - void *user_data, - void *codeloc) -{ - short bytes; - char *tramp; -#ifdef _WIN64 - int mask = 0; -#endif - FFI_ASSERT (cif->abi == FFI_SYSV); - - if (cif->abi == FFI_SYSV) - bytes = 0; -#if !defined(_WIN64) - else if (cif->abi == FFI_STDCALL) - bytes = cif->bytes; -#endif - else - return FFI_BAD_ABI; - - tramp = &closure->tramp[0]; - -#define BYTES(text) memcpy(tramp, text, sizeof(text)), tramp += sizeof(text)-1 -#define POINTER(x) *(void**)tramp = (void*)(x), tramp += sizeof(void*) -#define SHORT(x) *(short*)tramp = x, tramp += sizeof(short) -#define INT(x) *(int*)tramp = x, tramp += sizeof(int) - -#ifdef _WIN64 - if (cif->nargs >= 1 && - (cif->arg_types[0]->type == FFI_TYPE_FLOAT - || cif->arg_types[0]->type == FFI_TYPE_DOUBLE)) - mask |= 1; - if (cif->nargs >= 2 && - (cif->arg_types[1]->type == FFI_TYPE_FLOAT - || cif->arg_types[1]->type == FFI_TYPE_DOUBLE)) - mask |= 2; - if (cif->nargs >= 3 && - (cif->arg_types[2]->type == FFI_TYPE_FLOAT - || cif->arg_types[2]->type == FFI_TYPE_DOUBLE)) - mask |= 4; - if (cif->nargs >= 4 && - (cif->arg_types[3]->type == FFI_TYPE_FLOAT - || cif->arg_types[3]->type == FFI_TYPE_DOUBLE)) - mask |= 8; - - /* 41 BB ---- mov r11d,mask */ - BYTES("\x41\xBB"); INT(mask); - - /* 48 B8 -------- mov rax, closure */ - BYTES("\x48\xB8"); POINTER(closure); - - /* 49 BA -------- mov r10, ffi_closure_OUTER */ - BYTES("\x49\xBA"); POINTER(ffi_closure_OUTER); - - /* 41 FF E2 jmp r10 */ - BYTES("\x41\xFF\xE2"); - -#else - - /* mov ecx, closure */ - BYTES("\xb9"); POINTER(closure); - - /* mov edx, esp */ - BYTES("\x8b\xd4"); - - /* call ffi_closure_SYSV */ - BYTES("\xe8"); POINTER((char*)&ffi_closure_SYSV - (tramp + 4)); - - /* ret bytes */ - BYTES("\xc2"); - SHORT(bytes); - -#endif - - if (tramp - &closure->tramp[0] > FFI_TRAMPOLINE_SIZE) - Py_FatalError("FFI_TRAMPOLINE_SIZE too small in " __FILE__); - - closure->cif = cif; - closure->user_data = user_data; - closure->fun = fun; - return FFI_OK; -} diff --git a/lib/wrappers/libffi/msvc/prep_cif.c b/lib/wrappers/libffi/msvc/prep_cif.c deleted file mode 100644 index 2650fa052..000000000 --- a/lib/wrappers/libffi/msvc/prep_cif.c +++ /dev/null @@ -1,175 +0,0 @@ -/* ----------------------------------------------------------------------- - prep_cif.c - Copyright (c) 1996, 1998 Red Hat, Inc. - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files (the - ``Software''), to deal in the Software without restriction, including - without limitation the rights to use, copy, modify, merge, publish, - distribute, sublicense, and/or sell copies of the Software, and to - permit persons to whom the Software is furnished to do so, subject to - the following conditions: - - The above copyright notice and this permission notice shall be included - in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. - ----------------------------------------------------------------------- */ - -#include -#include -#include - - -/* Round up to FFI_SIZEOF_ARG. */ - -#define STACK_ARG_SIZE(x) ALIGN(x, FFI_SIZEOF_ARG) - -/* Perform machine independent initialization of aggregate type - specifications. */ - -static ffi_status initialize_aggregate(/*@out@*/ ffi_type *arg) -{ - ffi_type **ptr; - - FFI_ASSERT(arg != NULL); - - /*@-usedef@*/ - - FFI_ASSERT(arg->elements != NULL); - FFI_ASSERT(arg->size == 0); - FFI_ASSERT(arg->alignment == 0); - - ptr = &(arg->elements[0]); - - while ((*ptr) != NULL) - { - if (((*ptr)->size == 0) && (initialize_aggregate((*ptr)) != FFI_OK)) - return FFI_BAD_TYPEDEF; - - /* Perform a sanity check on the argument type */ - FFI_ASSERT_VALID_TYPE(*ptr); - - arg->size = ALIGN(arg->size, (*ptr)->alignment); - arg->size += (*ptr)->size; - - arg->alignment = (arg->alignment > (*ptr)->alignment) ? - arg->alignment : (*ptr)->alignment; - - ptr++; - } - - /* Structure size includes tail padding. This is important for - structures that fit in one register on ABIs like the PowerPC64 - Linux ABI that right justify small structs in a register. - It's also needed for nested structure layout, for example - struct A { long a; char b; }; struct B { struct A x; char y; }; - should find y at an offset of 2*sizeof(long) and result in a - total size of 3*sizeof(long). */ - arg->size = ALIGN (arg->size, arg->alignment); - - if (arg->size == 0) - return FFI_BAD_TYPEDEF; - else - return FFI_OK; - - /*@=usedef@*/ -} - -/* Perform machine independent ffi_cif preparation, then call - machine dependent routine. */ - -ffi_status ffi_prep_cif(/*@out@*/ /*@partial@*/ ffi_cif *cif, - ffi_abi abi, unsigned int nargs, - /*@dependent@*/ /*@out@*/ /*@partial@*/ ffi_type *rtype, - /*@dependent@*/ ffi_type **atypes) -{ - unsigned bytes = 0; - unsigned int i; - ffi_type **ptr; - - FFI_ASSERT(cif != NULL); - FFI_ASSERT((abi > FFI_FIRST_ABI) && (abi <= FFI_DEFAULT_ABI)); - - cif->abi = abi; - cif->arg_types = atypes; - cif->nargs = nargs; - cif->rtype = rtype; - - cif->flags = 0; - - /* Initialize the return type if necessary */ - /*@-usedef@*/ - if ((cif->rtype->size == 0) && (initialize_aggregate(cif->rtype) != FFI_OK)) - return FFI_BAD_TYPEDEF; - /*@=usedef@*/ - - /* Perform a sanity check on the return type */ - FFI_ASSERT_VALID_TYPE(cif->rtype); - - /* x86-64 and s390 stack space allocation is handled in prep_machdep. */ -#if !defined M68K && !defined __x86_64__ && !defined S390 - /* Make space for the return structure pointer */ - if (cif->rtype->type == FFI_TYPE_STRUCT - /* MSVC returns small structures in registers. But we have a different - workaround: pretend int32 or int64 return type, and converting to - structure afterwards. */ -#ifdef SPARC - && (cif->abi != FFI_V9 || cif->rtype->size > 32) -#endif - ) - bytes = STACK_ARG_SIZE(sizeof(void*)); -#endif - - for (ptr = cif->arg_types, i = cif->nargs; i > 0; i--, ptr++) - { - - /* Initialize any uninitialized aggregate type definitions */ - if (((*ptr)->size == 0) && (initialize_aggregate((*ptr)) != FFI_OK)) - return FFI_BAD_TYPEDEF; - - /* Perform a sanity check on the argument type, do this - check after the initialization. */ - FFI_ASSERT_VALID_TYPE(*ptr); - -#if !defined __x86_64__ && !defined S390 -#ifdef SPARC - if (((*ptr)->type == FFI_TYPE_STRUCT - && ((*ptr)->size > 16 || cif->abi != FFI_V9)) - || ((*ptr)->type == FFI_TYPE_LONGDOUBLE - && cif->abi != FFI_V9)) - bytes += sizeof(void*); - else -#endif - { -#if !defined(_MSC_VER) && !defined(__MINGW32__) - /* Don't know if this is a libffi bug or not. At least on - Windows with MSVC, function call parameters are *not* - aligned in the same way as structure fields are, they are - only aligned in integer boundaries. - - This doesn't do any harm for cdecl functions and closures, - since the caller cleans up the stack, but it is wrong for - stdcall functions where the callee cleans. - */ - - /* Add any padding if necessary */ - if (((*ptr)->alignment - 1) & bytes) - bytes = ALIGN(bytes, (*ptr)->alignment); - -#endif - bytes += STACK_ARG_SIZE((*ptr)->size); - } -#endif - } - - cif->bytes = bytes; - - /* Perform machine dependent cif processing */ - return ffi_prep_cif_machdep(cif); -} diff --git a/lib/wrappers/libffi/msvc/types.c b/lib/wrappers/libffi/msvc/types.c deleted file mode 100644 index df32190d1..000000000 --- a/lib/wrappers/libffi/msvc/types.c +++ /dev/null @@ -1,104 +0,0 @@ -/* ----------------------------------------------------------------------- - types.c - Copyright (c) 1996, 1998 Red Hat, Inc. - - Predefined ffi_types needed by libffi. - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files (the - ``Software''), to deal in the Software without restriction, including - without limitation the rights to use, copy, modify, merge, publish, - distribute, sublicense, and/or sell copies of the Software, and to - permit persons to whom the Software is furnished to do so, subject to - the following conditions: - - The above copyright notice and this permission notice shall be included - in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. - ----------------------------------------------------------------------- */ - -#include -#include - -/* Type definitions */ - -#define FFI_INTEGRAL_TYPEDEF(n, s, a, t) ffi_type ffi_type_##n = { s, a, t, NULL } -#define FFI_AGGREGATE_TYPEDEF(n, e) ffi_type ffi_type_##n = { 0, 0, FFI_TYPE_STRUCT, e } - -/* Size and alignment are fake here. They must not be 0. */ -FFI_INTEGRAL_TYPEDEF(void, 1, 1, FFI_TYPE_VOID); - -FFI_INTEGRAL_TYPEDEF(uint8, 1, 1, FFI_TYPE_UINT8); -FFI_INTEGRAL_TYPEDEF(sint8, 1, 1, FFI_TYPE_SINT8); -FFI_INTEGRAL_TYPEDEF(uint16, 2, 2, FFI_TYPE_UINT16); -FFI_INTEGRAL_TYPEDEF(sint16, 2, 2, FFI_TYPE_SINT16); -FFI_INTEGRAL_TYPEDEF(uint32, 4, 4, FFI_TYPE_UINT32); -FFI_INTEGRAL_TYPEDEF(sint32, 4, 4, FFI_TYPE_SINT32); -FFI_INTEGRAL_TYPEDEF(float, 4, 4, FFI_TYPE_FLOAT); - -#if defined ALPHA || defined SPARC64 || defined X86_64 || defined S390X \ - || defined IA64 - -FFI_INTEGRAL_TYPEDEF(pointer, 8, 8, FFI_TYPE_POINTER); - -#else - -FFI_INTEGRAL_TYPEDEF(pointer, 4, 4, FFI_TYPE_POINTER); - -#endif - -#if defined X86 || defined X86_WIN32 || defined ARM || defined M68K - -FFI_INTEGRAL_TYPEDEF(uint64, 8, 4, FFI_TYPE_UINT64); -FFI_INTEGRAL_TYPEDEF(sint64, 8, 4, FFI_TYPE_SINT64); - -#elif defined SH - -FFI_INTEGRAL_TYPEDEF(uint64, 8, 4, FFI_TYPE_UINT64); -FFI_INTEGRAL_TYPEDEF(sint64, 8, 4, FFI_TYPE_SINT64); - -#else - -FFI_INTEGRAL_TYPEDEF(uint64, 8, 8, FFI_TYPE_UINT64); -FFI_INTEGRAL_TYPEDEF(sint64, 8, 8, FFI_TYPE_SINT64); - -#endif - - -#if defined X86 || defined X86_WIN32 || defined M68K - -FFI_INTEGRAL_TYPEDEF(double, 8, 4, FFI_TYPE_DOUBLE); -FFI_INTEGRAL_TYPEDEF(longdouble, 12, 4, FFI_TYPE_LONGDOUBLE); - -#elif defined ARM || defined SH || defined POWERPC_AIX || defined POWERPC_DARWIN - -FFI_INTEGRAL_TYPEDEF(double, 8, 4, FFI_TYPE_DOUBLE); -FFI_INTEGRAL_TYPEDEF(longdouble, 8, 4, FFI_TYPE_LONGDOUBLE); - -#elif defined SPARC - -FFI_INTEGRAL_TYPEDEF(double, 8, 8, FFI_TYPE_DOUBLE); -#ifdef SPARC64 -FFI_INTEGRAL_TYPEDEF(longdouble, 16, 16, FFI_TYPE_LONGDOUBLE); -#else -FFI_INTEGRAL_TYPEDEF(longdouble, 16, 8, FFI_TYPE_LONGDOUBLE); -#endif - -#elif defined X86_64 - -FFI_INTEGRAL_TYPEDEF(double, 8, 8, FFI_TYPE_DOUBLE); -FFI_INTEGRAL_TYPEDEF(longdouble, 16, 16, FFI_TYPE_LONGDOUBLE); - -#else - -FFI_INTEGRAL_TYPEDEF(double, 8, 8, FFI_TYPE_DOUBLE); -FFI_INTEGRAL_TYPEDEF(longdouble, 8, 8, FFI_TYPE_LONGDOUBLE); - -#endif - diff --git a/lib/wrappers/libffi/msvc/win32.c b/lib/wrappers/libffi/msvc/win32.c deleted file mode 100644 index 2754fd35d..000000000 --- a/lib/wrappers/libffi/msvc/win32.c +++ /dev/null @@ -1,162 +0,0 @@ -/* ----------------------------------------------------------------------- - win32.S - Copyright (c) 1996, 1998, 2001, 2002 Red Hat, Inc. - Copyright (c) 2001 John Beniton - Copyright (c) 2002 Ranjit Mathew - - - X86 Foreign Function Interface - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files (the - ``Software''), to deal in the Software without restriction, including - without limitation the rights to use, copy, modify, merge, publish, - distribute, sublicense, and/or sell copies of the Software, and to - permit persons to whom the Software is furnished to do so, subject to - the following conditions: - - The above copyright notice and this permission notice shall be included - in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL CYGNUS SOLUTIONS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. - ----------------------------------------------------------------------- */ - -/* theller: almost verbatim translation from gas syntax to MSVC inline - assembler code. */ - -/* theller: ffi_call_x86 now returns an integer - the difference of the stack - pointer before and after the function call. If everything is ok, zero is - returned. If stdcall functions are passed the wrong number of arguments, - the difference will be nonzero. */ - -#include -#include - -__declspec(naked) int -ffi_call_x86(void (* prepfunc)(char *, extended_cif *), /* 8 */ - extended_cif *ecif, /* 12 */ - unsigned bytes, /* 16 */ - unsigned flags, /* 20 */ - unsigned *rvalue, /* 24 */ - void (*fn)()) /* 28 */ -{ - _asm { - push ebp - mov ebp, esp - - push esi // NEW: this register must be preserved across function calls -// XXX SAVE ESP NOW! - mov esi, esp // save stack pointer before the call - -// Make room for all of the new args. - mov ecx, [ebp+16] - sub esp, ecx // sub esp, bytes - - mov eax, esp - -// Place all of the ffi_prep_args in position - push [ebp + 12] // ecif - push eax - call [ebp + 8] // prepfunc - -// Return stack to previous state and call the function - add esp, 8 -// FIXME: Align the stack to a 128-bit boundary to avoid -// potential performance hits. - call [ebp + 28] - -// Load ecif->cif->abi - mov ecx, [ebp + 12] - mov ecx, [ecx]ecif.cif - mov ecx, [ecx]ecif.cif.abi - - cmp ecx, FFI_STDCALL - je noclean -// STDCALL: Remove the space we pushed for the args - mov ecx, [ebp + 16] - add esp, ecx -// CDECL: Caller has already cleaned the stack -noclean: -// Check that esp has the same value as before! - sub esi, esp - -// Load %ecx with the return type code - mov ecx, [ebp + 20] - -// If the return value pointer is NULL, assume no return value. -/* - Intel asm is weird. We have to explicitly specify 'DWORD PTR' in the nexr instruction, - otherwise only one BYTE will be compared (instead of a DWORD)! - */ - cmp DWORD PTR [ebp + 24], 0 - jne sc_retint - -// Even if there is no space for the return value, we are -// obliged to handle floating-point values. - cmp ecx, FFI_TYPE_FLOAT - jne sc_noretval -// fstp %st(0) - fstp st(0) - - jmp sc_epilogue - -sc_retint: - cmp ecx, FFI_TYPE_INT - jne sc_retfloat -// # Load %ecx with the pointer to storage for the return value - mov ecx, [ebp + 24] - mov [ecx + 0], eax - jmp sc_epilogue - -sc_retfloat: - cmp ecx, FFI_TYPE_FLOAT - jne sc_retdouble -// Load %ecx with the pointer to storage for the return value - mov ecx, [ebp+24] -// fstps (%ecx) - fstp DWORD PTR [ecx] - jmp sc_epilogue - -sc_retdouble: - cmp ecx, FFI_TYPE_DOUBLE - jne sc_retlongdouble -// movl 24(%ebp),%ecx - mov ecx, [ebp+24] - fstp QWORD PTR [ecx] - jmp sc_epilogue - - jmp sc_retlongdouble // avoid warning about unused label -sc_retlongdouble: - cmp ecx, FFI_TYPE_LONGDOUBLE - jne sc_retint64 -// Load %ecx with the pointer to storage for the return value - mov ecx, [ebp+24] -// fstpt (%ecx) - fstp QWORD PTR [ecx] /* XXX ??? */ - jmp sc_epilogue - -sc_retint64: - cmp ecx, FFI_TYPE_SINT64 - jne sc_retstruct -// Load %ecx with the pointer to storage for the return value - mov ecx, [ebp+24] - mov [ecx+0], eax - mov [ecx+4], edx - -sc_retstruct: -// Nothing to do! - -sc_noretval: -sc_epilogue: - mov eax, esi - pop esi // NEW restore: must be preserved across function calls - mov esp, ebp - pop ebp - ret - } -} diff --git a/lib/wrappers/libffi/msvc/win32_asm.asm b/lib/wrappers/libffi/msvc/win32_asm.asm deleted file mode 100644 index 407185e6a..000000000 --- a/lib/wrappers/libffi/msvc/win32_asm.asm +++ /dev/null @@ -1,470 +0,0 @@ -/* ----------------------------------------------------------------------- - win32.S - Copyright (c) 1996, 1998, 2001, 2002, 2009 Red Hat, Inc. - Copyright (c) 2001 John Beniton - Copyright (c) 2002 Ranjit Mathew - Copyright (c) 2009 Daniel Witte - - - X86 Foreign Function Interface - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files (the - ``Software''), to deal in the Software without restriction, including - without limitation the rights to use, copy, modify, merge, publish, - distribute, sublicense, and/or sell copies of the Software, and to - permit persons to whom the Software is furnished to do so, subject to - the following conditions: - - The above copyright notice and this permission notice shall be included - in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - DEALINGS IN THE SOFTWARE. - ----------------------------------------------------------------------- - */ - -#define LIBFFI_ASM -#include -#include - -.386 -.MODEL FLAT, C - -EXTRN ffi_closure_SYSV_inner:NEAR - -_TEXT SEGMENT - -ffi_call_win32 PROC NEAR, - ffi_prep_args : NEAR PTR DWORD, - ecif : NEAR PTR DWORD, - cif_abi : DWORD, - cif_bytes : DWORD, - cif_flags : DWORD, - rvalue : NEAR PTR DWORD, - fn : NEAR PTR DWORD - - ;; Make room for all of the new args. - mov ecx, cif_bytes - sub esp, ecx - - mov eax, esp - - ;; Place all of the ffi_prep_args in position - push ecif - push eax - call ffi_prep_args - - ;; Return stack to previous state and call the function - add esp, 8 - - ;; Handle thiscall and fastcall - cmp cif_abi, 3 ;; FFI_THISCALL - jz do_thiscall - cmp cif_abi, 4 ;; FFI_FASTCALL - jnz do_stdcall - mov ecx, DWORD PTR [esp] - mov edx, DWORD PTR [esp+4] - add esp, 8 - jmp do_stdcall -do_thiscall: - mov ecx, DWORD PTR [esp] - add esp, 4 -do_stdcall: - call fn - - ;; cdecl: we restore esp in the epilogue, so there's no need to - ;; remove the space we pushed for the args. - ;; stdcall: the callee has already cleaned the stack. - - ;; Load ecx with the return type code - mov ecx, cif_flags - - ;; If the return value pointer is NULL, assume no return value. - cmp rvalue, 0 - jne ca_jumptable - - ;; Even if there is no space for the return value, we are - ;; obliged to handle floating-point values. - cmp ecx, FFI_TYPE_FLOAT - jne ca_epilogue - fstp st(0) - - jmp ca_epilogue - -ca_jumptable: - jmp [ca_jumpdata + 4 * ecx] -ca_jumpdata: - ;; Do not insert anything here between label and jump table. - dd offset ca_epilogue ;; FFI_TYPE_VOID - dd offset ca_retint ;; FFI_TYPE_INT - dd offset ca_retfloat ;; FFI_TYPE_FLOAT - dd offset ca_retdouble ;; FFI_TYPE_DOUBLE - dd offset ca_retlongdouble ;; FFI_TYPE_LONGDOUBLE - dd offset ca_retuint8 ;; FFI_TYPE_UINT8 - dd offset ca_retsint8 ;; FFI_TYPE_SINT8 - dd offset ca_retuint16 ;; FFI_TYPE_UINT16 - dd offset ca_retsint16 ;; FFI_TYPE_SINT16 - dd offset ca_retint ;; FFI_TYPE_UINT32 - dd offset ca_retint ;; FFI_TYPE_SINT32 - dd offset ca_retint64 ;; FFI_TYPE_UINT64 - dd offset ca_retint64 ;; FFI_TYPE_SINT64 - dd offset ca_epilogue ;; FFI_TYPE_STRUCT - dd offset ca_retint ;; FFI_TYPE_POINTER - dd offset ca_retstruct1b ;; FFI_TYPE_SMALL_STRUCT_1B - dd offset ca_retstruct2b ;; FFI_TYPE_SMALL_STRUCT_2B - dd offset ca_retint ;; FFI_TYPE_SMALL_STRUCT_4B - dd offset ca_epilogue ;; FFI_TYPE_MS_STRUCT - - /* Sign/zero extend as appropriate. */ -ca_retuint8: - movzx eax, al - jmp ca_retint - -ca_retsint8: - movsx eax, al - jmp ca_retint - -ca_retuint16: - movzx eax, ax - jmp ca_retint - -ca_retsint16: - movsx eax, ax - jmp ca_retint - -ca_retint: - ;; Load %ecx with the pointer to storage for the return value - mov ecx, rvalue - mov [ecx + 0], eax - jmp ca_epilogue - -ca_retint64: - ;; Load %ecx with the pointer to storage for the return value - mov ecx, rvalue - mov [ecx + 0], eax - mov [ecx + 4], edx - jmp ca_epilogue - -ca_retfloat: - ;; Load %ecx with the pointer to storage for the return value - mov ecx, rvalue - fstp DWORD PTR [ecx] - jmp ca_epilogue - -ca_retdouble: - ;; Load %ecx with the pointer to storage for the return value - mov ecx, rvalue - fstp QWORD PTR [ecx] - jmp ca_epilogue - -ca_retlongdouble: - ;; Load %ecx with the pointer to storage for the return value - mov ecx, rvalue - fstp TBYTE PTR [ecx] - jmp ca_epilogue - -ca_retstruct1b: - ;; Load %ecx with the pointer to storage for the return value - mov ecx, rvalue - mov [ecx + 0], al - jmp ca_epilogue - -ca_retstruct2b: - ;; Load %ecx with the pointer to storage for the return value - mov ecx, rvalue - mov [ecx + 0], ax - jmp ca_epilogue - -ca_epilogue: - ;; Epilogue code is autogenerated. - ret -ffi_call_win32 ENDP - -ffi_closure_THISCALL PROC NEAR FORCEFRAME - sub esp, 40 - lea edx, [ebp -24] - mov [ebp - 12], edx /* resp */ - lea edx, [ebp + 12] /* account for stub return address on stack */ - jmp stub -ffi_closure_THISCALL ENDP - -ffi_closure_SYSV PROC NEAR FORCEFRAME - ;; the ffi_closure ctx is passed in eax by the trampoline. - - sub esp, 40 - lea edx, [ebp - 24] - mov [ebp - 12], edx ;; resp - lea edx, [ebp + 8] -stub:: - mov [esp + 8], edx ;; args - lea edx, [ebp - 12] - mov [esp + 4], edx ;; &resp - mov [esp], eax ;; closure - call ffi_closure_SYSV_inner - mov ecx, [ebp - 12] - -cs_jumptable: - jmp [cs_jumpdata + 4 * eax] -cs_jumpdata: - ;; Do not insert anything here between the label and jump table. - dd offset cs_epilogue ;; FFI_TYPE_VOID - dd offset cs_retint ;; FFI_TYPE_INT - dd offset cs_retfloat ;; FFI_TYPE_FLOAT - dd offset cs_retdouble ;; FFI_TYPE_DOUBLE - dd offset cs_retlongdouble ;; FFI_TYPE_LONGDOUBLE - dd offset cs_retuint8 ;; FFI_TYPE_UINT8 - dd offset cs_retsint8 ;; FFI_TYPE_SINT8 - dd offset cs_retuint16 ;; FFI_TYPE_UINT16 - dd offset cs_retsint16 ;; FFI_TYPE_SINT16 - dd offset cs_retint ;; FFI_TYPE_UINT32 - dd offset cs_retint ;; FFI_TYPE_SINT32 - dd offset cs_retint64 ;; FFI_TYPE_UINT64 - dd offset cs_retint64 ;; FFI_TYPE_SINT64 - dd offset cs_retstruct ;; FFI_TYPE_STRUCT - dd offset cs_retint ;; FFI_TYPE_POINTER - dd offset cs_retsint8 ;; FFI_TYPE_SMALL_STRUCT_1B - dd offset cs_retsint16 ;; FFI_TYPE_SMALL_STRUCT_2B - dd offset cs_retint ;; FFI_TYPE_SMALL_STRUCT_4B - dd offset cs_retmsstruct ;; FFI_TYPE_MS_STRUCT - -cs_retuint8: - movzx eax, BYTE PTR [ecx] - jmp cs_epilogue - -cs_retsint8: - movsx eax, BYTE PTR [ecx] - jmp cs_epilogue - -cs_retuint16: - movzx eax, WORD PTR [ecx] - jmp cs_epilogue - -cs_retsint16: - movsx eax, WORD PTR [ecx] - jmp cs_epilogue - -cs_retint: - mov eax, [ecx] - jmp cs_epilogue - -cs_retint64: - mov eax, [ecx + 0] - mov edx, [ecx + 4] - jmp cs_epilogue - -cs_retfloat: - fld DWORD PTR [ecx] - jmp cs_epilogue - -cs_retdouble: - fld QWORD PTR [ecx] - jmp cs_epilogue - -cs_retlongdouble: - fld TBYTE PTR [ecx] - jmp cs_epilogue - -cs_retstruct: - ;; Caller expects us to pop struct return value pointer hidden arg. - ;; Epilogue code is autogenerated. - ret 4 - -cs_retmsstruct: - ;; Caller expects us to return a pointer to the real return value. - mov eax, ecx - ;; Caller doesn't expects us to pop struct return value pointer hidden arg. - jmp cs_epilogue - -cs_epilogue: - ;; Epilogue code is autogenerated. - ret -ffi_closure_SYSV ENDP - -#if !FFI_NO_RAW_API - -#define RAW_CLOSURE_CIF_OFFSET ((FFI_TRAMPOLINE_SIZE + 3) AND NOT 3) -#define RAW_CLOSURE_FUN_OFFSET (RAW_CLOSURE_CIF_OFFSET + 4) -#define RAW_CLOSURE_USER_DATA_OFFSET (RAW_CLOSURE_FUN_OFFSET + 4) -#define CIF_FLAGS_OFFSET 20 - -ffi_closure_raw_THISCALL PROC NEAR USES esi FORCEFRAME - sub esp, 36 - mov esi, [eax + RAW_CLOSURE_CIF_OFFSET] ;; closure->cif - mov edx, [eax + RAW_CLOSURE_USER_DATA_OFFSET] ;; closure->user_data - mov [esp + 12], edx - lea edx, [ebp + 12] - jmp stubraw -ffi_closure_raw_THISCALL ENDP - -ffi_closure_raw_SYSV PROC NEAR USES esi FORCEFRAME - ;; the ffi_closure ctx is passed in eax by the trampoline. - - sub esp, 40 - mov esi, [eax + RAW_CLOSURE_CIF_OFFSET] ;; closure->cif - mov edx, [eax + RAW_CLOSURE_USER_DATA_OFFSET] ;; closure->user_data - mov [esp + 12], edx ;; user_data - lea edx, [ebp + 8] -stubraw:: - mov [esp + 8], edx ;; raw_args - lea edx, [ebp - 24] - mov [esp + 4], edx ;; &res - mov [esp], esi ;; cif - call DWORD PTR [eax + RAW_CLOSURE_FUN_OFFSET] ;; closure->fun - mov eax, [esi + CIF_FLAGS_OFFSET] ;; cif->flags - lea ecx, [ebp - 24] - -cr_jumptable: - jmp [cr_jumpdata + 4 * eax] -cr_jumpdata: - ;; Do not insert anything here between the label and jump table. - dd offset cr_epilogue ;; FFI_TYPE_VOID - dd offset cr_retint ;; FFI_TYPE_INT - dd offset cr_retfloat ;; FFI_TYPE_FLOAT - dd offset cr_retdouble ;; FFI_TYPE_DOUBLE - dd offset cr_retlongdouble ;; FFI_TYPE_LONGDOUBLE - dd offset cr_retuint8 ;; FFI_TYPE_UINT8 - dd offset cr_retsint8 ;; FFI_TYPE_SINT8 - dd offset cr_retuint16 ;; FFI_TYPE_UINT16 - dd offset cr_retsint16 ;; FFI_TYPE_SINT16 - dd offset cr_retint ;; FFI_TYPE_UINT32 - dd offset cr_retint ;; FFI_TYPE_SINT32 - dd offset cr_retint64 ;; FFI_TYPE_UINT64 - dd offset cr_retint64 ;; FFI_TYPE_SINT64 - dd offset cr_epilogue ;; FFI_TYPE_STRUCT - dd offset cr_retint ;; FFI_TYPE_POINTER - dd offset cr_retsint8 ;; FFI_TYPE_SMALL_STRUCT_1B - dd offset cr_retsint16 ;; FFI_TYPE_SMALL_STRUCT_2B - dd offset cr_retint ;; FFI_TYPE_SMALL_STRUCT_4B - dd offset cr_epilogue ;; FFI_TYPE_MS_STRUCT - -cr_retuint8: - movzx eax, BYTE PTR [ecx] - jmp cr_epilogue - -cr_retsint8: - movsx eax, BYTE PTR [ecx] - jmp cr_epilogue - -cr_retuint16: - movzx eax, WORD PTR [ecx] - jmp cr_epilogue - -cr_retsint16: - movsx eax, WORD PTR [ecx] - jmp cr_epilogue - -cr_retint: - mov eax, [ecx] - jmp cr_epilogue - -cr_retint64: - mov eax, [ecx + 0] - mov edx, [ecx + 4] - jmp cr_epilogue - -cr_retfloat: - fld DWORD PTR [ecx] - jmp cr_epilogue - -cr_retdouble: - fld QWORD PTR [ecx] - jmp cr_epilogue - -cr_retlongdouble: - fld TBYTE PTR [ecx] - jmp cr_epilogue - -cr_epilogue: - ;; Epilogue code is autogenerated. - ret -ffi_closure_raw_SYSV ENDP - -#endif /* !FFI_NO_RAW_API */ - -ffi_closure_STDCALL PROC NEAR FORCEFRAME - ;; the ffi_closure ctx is passed in eax by the trampoline. - - sub esp, 40 - lea edx, [ebp - 24] - mov [ebp - 12], edx ;; resp - lea edx, [ebp + 12] ;; account for stub return address on stack - mov [esp + 8], edx ;; args - lea edx, [ebp - 12] - mov [esp + 4], edx ;; &resp - mov [esp], eax ;; closure - call ffi_closure_SYSV_inner - mov ecx, [ebp - 12] - -cd_jumptable: - jmp [cd_jumpdata + 4 * eax] -cd_jumpdata: - ;; Do not insert anything here between the label and jump table. - dd offset cd_epilogue ;; FFI_TYPE_VOID - dd offset cd_retint ;; FFI_TYPE_INT - dd offset cd_retfloat ;; FFI_TYPE_FLOAT - dd offset cd_retdouble ;; FFI_TYPE_DOUBLE - dd offset cd_retlongdouble ;; FFI_TYPE_LONGDOUBLE - dd offset cd_retuint8 ;; FFI_TYPE_UINT8 - dd offset cd_retsint8 ;; FFI_TYPE_SINT8 - dd offset cd_retuint16 ;; FFI_TYPE_UINT16 - dd offset cd_retsint16 ;; FFI_TYPE_SINT16 - dd offset cd_retint ;; FFI_TYPE_UINT32 - dd offset cd_retint ;; FFI_TYPE_SINT32 - dd offset cd_retint64 ;; FFI_TYPE_UINT64 - dd offset cd_retint64 ;; FFI_TYPE_SINT64 - dd offset cd_epilogue ;; FFI_TYPE_STRUCT - dd offset cd_retint ;; FFI_TYPE_POINTER - dd offset cd_retsint8 ;; FFI_TYPE_SMALL_STRUCT_1B - dd offset cd_retsint16 ;; FFI_TYPE_SMALL_STRUCT_2B - dd offset cd_retint ;; FFI_TYPE_SMALL_STRUCT_4B - -cd_retuint8: - movzx eax, BYTE PTR [ecx] - jmp cd_epilogue - -cd_retsint8: - movsx eax, BYTE PTR [ecx] - jmp cd_epilogue - -cd_retuint16: - movzx eax, WORD PTR [ecx] - jmp cd_epilogue - -cd_retsint16: - movsx eax, WORD PTR [ecx] - jmp cd_epilogue - -cd_retint: - mov eax, [ecx] - jmp cd_epilogue - -cd_retint64: - mov eax, [ecx + 0] - mov edx, [ecx + 4] - jmp cd_epilogue - -cd_retfloat: - fld DWORD PTR [ecx] - jmp cd_epilogue - -cd_retdouble: - fld QWORD PTR [ecx] - jmp cd_epilogue - -cd_retlongdouble: - fld TBYTE PTR [ecx] - jmp cd_epilogue - -cd_epilogue: - ;; Epilogue code is autogenerated. - ret -ffi_closure_STDCALL ENDP - -_TEXT ENDS -END diff --git a/lib/wrappers/libffi/msvc/win64_asm.asm b/lib/wrappers/libffi/msvc/win64_asm.asm deleted file mode 100644 index 301188bc9..000000000 --- a/lib/wrappers/libffi/msvc/win64_asm.asm +++ /dev/null @@ -1,156 +0,0 @@ -PUBLIC ffi_call_AMD64 - -EXTRN __chkstk:NEAR -EXTRN ffi_closure_SYSV:NEAR - -_TEXT SEGMENT - -;;; ffi_closure_OUTER will be called with these registers set: -;;; rax points to 'closure' -;;; r11 contains a bit mask that specifies which of the -;;; first four parameters are float or double -;;; -;;; It must move the parameters passed in registers to their stack location, -;;; call ffi_closure_SYSV for the actual work, then return the result. -;;; -ffi_closure_OUTER PROC FRAME - ;; save actual arguments to their stack space. - test r11, 1 - jne first_is_float - mov QWORD PTR [rsp+8], rcx - jmp second -first_is_float: - movlpd QWORD PTR [rsp+8], xmm0 - -second: - test r11, 2 - jne second_is_float - mov QWORD PTR [rsp+16], rdx - jmp third -second_is_float: - movlpd QWORD PTR [rsp+16], xmm1 - -third: - test r11, 4 - jne third_is_float - mov QWORD PTR [rsp+24], r8 - jmp forth -third_is_float: - movlpd QWORD PTR [rsp+24], xmm2 - -forth: - test r11, 8 - jne forth_is_float - mov QWORD PTR [rsp+32], r9 - jmp done -forth_is_float: - movlpd QWORD PTR [rsp+32], xmm3 - -done: -.ALLOCSTACK 40 - sub rsp, 40 -.ENDPROLOG - mov rcx, rax ; context is first parameter - mov rdx, rsp ; stack is second parameter - add rdx, 40 ; correct our own area - mov rax, ffi_closure_SYSV - call rax ; call the real closure function - ;; Here, code is missing that handles float return values - add rsp, 40 - movd xmm0, rax ; In case the closure returned a float. - ret 0 -ffi_closure_OUTER ENDP - - -;;; ffi_call_AMD64 - -stack$ = 0 -prepfunc$ = 32 -ecif$ = 40 -bytes$ = 48 -flags$ = 56 -rvalue$ = 64 -fn$ = 72 - -ffi_call_AMD64 PROC FRAME - - mov QWORD PTR [rsp+32], r9 - mov QWORD PTR [rsp+24], r8 - mov QWORD PTR [rsp+16], rdx - mov QWORD PTR [rsp+8], rcx -.PUSHREG rbp - push rbp -.ALLOCSTACK 48 - sub rsp, 48 ; 00000030H -.SETFRAME rbp, 32 - lea rbp, QWORD PTR [rsp+32] -.ENDPROLOG - - mov eax, DWORD PTR bytes$[rbp] - add rax, 15 - and rax, -16 - call __chkstk - sub rsp, rax - lea rax, QWORD PTR [rsp+32] - mov QWORD PTR stack$[rbp], rax - - mov rdx, QWORD PTR ecif$[rbp] - mov rcx, QWORD PTR stack$[rbp] - call QWORD PTR prepfunc$[rbp] - - mov rsp, QWORD PTR stack$[rbp] - - movlpd xmm3, QWORD PTR [rsp+24] - movd r9, xmm3 - - movlpd xmm2, QWORD PTR [rsp+16] - movd r8, xmm2 - - movlpd xmm1, QWORD PTR [rsp+8] - movd rdx, xmm1 - - movlpd xmm0, QWORD PTR [rsp] - movd rcx, xmm0 - - call QWORD PTR fn$[rbp] -ret_int$: - cmp DWORD PTR flags$[rbp], 1 ; FFI_TYPE_INT - jne ret_float$ - - mov rcx, QWORD PTR rvalue$[rbp] - mov DWORD PTR [rcx], eax - jmp SHORT ret_nothing$ - -ret_float$: - cmp DWORD PTR flags$[rbp], 2 ; FFI_TYPE_FLOAT - jne SHORT ret_double$ - - mov rax, QWORD PTR rvalue$[rbp] - movlpd QWORD PTR [rax], xmm0 - jmp SHORT ret_nothing$ - -ret_double$: - cmp DWORD PTR flags$[rbp], 3 ; FFI_TYPE_DOUBLE - jne SHORT ret_int64$ - - mov rax, QWORD PTR rvalue$[rbp] - movlpd QWORD PTR [rax], xmm0 - jmp SHORT ret_nothing$ - -ret_int64$: - cmp DWORD PTR flags$[rbp], 12 ; FFI_TYPE_SINT64 - jne ret_nothing$ - - mov rcx, QWORD PTR rvalue$[rbp] - mov QWORD PTR [rcx], rax - jmp SHORT ret_nothing$ - -ret_nothing$: - xor eax, eax - - lea rsp, QWORD PTR [rbp+16] - pop rbp - ret 0 -ffi_call_AMD64 ENDP -_TEXT ENDS -END diff --git a/lib/wrappers/libuv.nim b/lib/wrappers/libuv.nim index 0cb14fb2b..3e28815ad 100644 --- a/lib/wrappers/libuv.nim +++ b/lib/wrappers/libuv.nim @@ -1,3 +1,12 @@ +# +# +# Nim's Runtime Library +# (c) Copyright 2015 Andreas Rumpf +# +# See the file "copying.txt", included in this +# distribution, for details about the copyright. +# + ## libuv is still fast moving target ## This file was last updated against a development HEAD revision of https://github.com/joyent/libuv/ @@ -136,7 +145,7 @@ type fs_event_init* {.importc: "fs_event_init".}: uint64 Loop* {.pure, final, importc: "uv_loop_t", header: "uv.h".} = object - # ares_handles_* {.importc: "uv_ares_handles_".}: pointer # XXX: This seems to be a private field? + # ares_handles_* {.importc: "uv_ares_handles_".}: pointer # XXX: This seems to be a private field? eio_want_poll_notifier* {.importc: "uv_eio_want_poll_notifier".}: TAsync eio_done_poll_notifier* {.importc: "uv_eio_done_poll_notifier".}: TAsync eio_poller* {.importc: "uv_eio_poller".}: TIdle diff --git a/lib/wrappers/odbcsql.nim b/lib/wrappers/odbcsql.nim index 22297497c..971861a6a 100644 --- a/lib/wrappers/odbcsql.nim +++ b/lib/wrappers/odbcsql.nim @@ -1,3 +1,11 @@ +# +# +# Nim's Runtime Library +# (c) Copyright 2015 Andreas Rumpf +# +# See the file "copying.txt", included in this +# distribution, for details about the copyright. +# {.deadCodeElim: on.} @@ -27,7 +35,7 @@ else: # ftMemo SQL_BINARY // SQL_VARCHAR # -type +type TSqlChar* = char TSqlSmallInt* = int16 SqlUSmallInt* = int16 @@ -64,7 +72,7 @@ type # TSqlFloat: TSqlFloat, # Name conflict if we drop `T` TSqlHWND: SqlHWND].} -const # SQL data type codes +const # SQL data type codes SQL_UNKNOWN_TYPE* = 0 SQL_LONGVARCHAR* = (- 1) SQL_BINARY* = (- 2) @@ -95,8 +103,8 @@ const # SQL data type codes SQL_INTERVAL* = 10 SQL_GUID* = - 11 # interval codes -when ODBCVER >= 0x0300: - const +when ODBCVER >= 0x0300: + const SQL_CODE_YEAR* = 1 SQL_CODE_MONTH* = 2 SQL_CODE_DAY* = 3 @@ -123,8 +131,8 @@ when ODBCVER >= 0x0300: SQL_INTERVAL_HOUR_TO_MINUTE* = 100 + SQL_CODE_HOUR_TO_MINUTE SQL_INTERVAL_HOUR_TO_SECOND* = 100 + SQL_CODE_HOUR_TO_SECOND SQL_INTERVAL_MINUTE_TO_SECOND* = 100 + SQL_CODE_MINUTE_TO_SECOND -else: - const +else: + const SQL_INTERVAL_YEAR* = - 80 SQL_INTERVAL_MONTH* = - 81 SQL_INTERVAL_YEAR_TO_MONTH* = - 82 @@ -140,20 +148,20 @@ else: SQL_INTERVAL_MINUTE_TO_SECOND* = - 92 -when ODBCVER < 0x0300: - const +when ODBCVER < 0x0300: + const SQL_UNICODE* = - 95 SQL_UNICODE_VARCHAR* = - 96 SQL_UNICODE_LONGVARCHAR* = - 97 SQL_UNICODE_CHAR* = SQL_UNICODE -else: - # The previous definitions for SQL_UNICODE_ are historical and obsolete - const +else: + # The previous definitions for SQL_UNICODE_ are historical and obsolete + const SQL_UNICODE* = SQL_WCHAR SQL_UNICODE_VARCHAR* = SQL_WVARCHAR SQL_UNICODE_LONGVARCHAR* = SQL_WLONGVARCHAR SQL_UNICODE_CHAR* = SQL_WCHAR -const # C datatype to SQL datatype mapping +const # C datatype to SQL datatype mapping SQL_C_CHAR* = SQL_CHAR SQL_C_LONG* = SQL_INTEGER SQL_C_SHORT* = SQL_SMALLINT @@ -197,30 +205,30 @@ const # C datatype to SQL datatype mapping SQL_C_GUID* = SQL_GUID SQL_TYPE_NULL* = 0 -when ODBCVER < 0x0300: - const +when ODBCVER < 0x0300: + const SQL_TYPE_MIN* = SQL_BIT SQL_TYPE_MAX* = SQL_VARCHAR -const +const SQL_C_VARBOOKMARK* = SQL_C_BINARY SQL_API_SQLDESCRIBEPARAM* = 58 SQL_NO_TOTAL* = - 4 -type - SQL_DATE_STRUCT* {.final, pure.} = object +type + SQL_DATE_STRUCT* {.final, pure.} = object Year*: TSqlSmallInt Month*: SqlUSmallInt Day*: SqlUSmallInt PSQL_DATE_STRUCT* = ptr SQL_DATE_STRUCT - SQL_TIME_STRUCT* {.final, pure.} = object + SQL_TIME_STRUCT* {.final, pure.} = object Hour*: SqlUSmallInt Minute*: SqlUSmallInt Second*: SqlUSmallInt PSQL_TIME_STRUCT* = ptr SQL_TIME_STRUCT - SQL_TIMESTAMP_STRUCT* {.final, pure.} = object + SQL_TIMESTAMP_STRUCT* {.final, pure.} = object Year*: SqlUSmallInt Month*: SqlUSmallInt Day*: SqlUSmallInt @@ -231,34 +239,34 @@ type PSQL_TIMESTAMP_STRUCT* = ptr SQL_TIMESTAMP_STRUCT -const +const SQL_NAME_LEN* = 128 SQL_OV_ODBC3* = 3 SQL_OV_ODBC2* = 2 - SQL_ATTR_ODBC_VERSION* = 200 # Options for SQLDriverConnect + SQL_ATTR_ODBC_VERSION* = 200 # Options for SQLDriverConnect SQL_DRIVER_NOPROMPT* = 0 SQL_DRIVER_COMPLETE* = 1 SQL_DRIVER_PROMPT* = 2 - SQL_DRIVER_COMPLETE_REQUIRED* = 3 - SQL_IS_POINTER* = (- 4) # whether an attribute is a pointer or not + SQL_DRIVER_COMPLETE_REQUIRED* = 3 + SQL_IS_POINTER* = (- 4) # whether an attribute is a pointer or not SQL_IS_UINTEGER* = (- 5) SQL_IS_INTEGER* = (- 6) SQL_IS_USMALLINT* = (- 7) - SQL_IS_SMALLINT* = (- 8) # SQLExtendedFetch "fFetchType" values + SQL_IS_SMALLINT* = (- 8) # SQLExtendedFetch "fFetchType" values SQL_FETCH_BOOKMARK* = 8 - SQL_SCROLL_OPTIONS* = 44 # SQL_USE_BOOKMARKS options + SQL_SCROLL_OPTIONS* = 44 # SQL_USE_BOOKMARKS options SQL_UB_OFF* = 0 SQL_UB_ON* = 1 SQL_UB_DEFAULT* = SQL_UB_OFF SQL_UB_FIXED* = SQL_UB_ON - SQL_UB_VARIABLE* = 2 # SQL_SCROLL_OPTIONS masks + SQL_UB_VARIABLE* = 2 # SQL_SCROLL_OPTIONS masks SQL_SO_FORWARD_ONLY* = 0x00000001 SQL_SO_KEYSET_DRIVEN* = 0x00000002 SQL_SO_DYNAMIC* = 0x00000004 SQL_SO_MIXED* = 0x00000008 SQL_SO_STATIC* = 0x00000010 SQL_BOOKMARK_PERSISTENCE* = 82 - SQL_STATIC_SENSITIVITY* = 83 # SQL_BOOKMARK_PERSISTENCE values + SQL_STATIC_SENSITIVITY* = 83 # SQL_BOOKMARK_PERSISTENCE values SQL_BP_CLOSE* = 0x00000001 SQL_BP_DELETE* = 0x00000002 SQL_BP_DROP* = 0x00000004 @@ -275,32 +283,32 @@ const SQL_KEYSET_CURSOR_ATTRIBUTES1* = 150 SQL_KEYSET_CURSOR_ATTRIBUTES2* = 151 SQL_STATIC_CURSOR_ATTRIBUTES1* = 167 - SQL_STATIC_CURSOR_ATTRIBUTES2* = 168 # supported SQLFetchScroll FetchOrientation's + SQL_STATIC_CURSOR_ATTRIBUTES2* = 168 # supported SQLFetchScroll FetchOrientation's SQL_CA1_NEXT* = 1 SQL_CA1_ABSOLUTE* = 2 SQL_CA1_RELATIVE* = 4 - SQL_CA1_BOOKMARK* = 8 # supported SQLSetPos LockType's + SQL_CA1_BOOKMARK* = 8 # supported SQLSetPos LockType's SQL_CA1_LOCK_NO_CHANGE* = 0x00000040 SQL_CA1_LOCK_EXCLUSIVE* = 0x00000080 - SQL_CA1_LOCK_UNLOCK* = 0x00000100 # supported SQLSetPos Operations + SQL_CA1_LOCK_UNLOCK* = 0x00000100 # supported SQLSetPos Operations SQL_CA1_POS_POSITION* = 0x00000200 SQL_CA1_POS_UPDATE* = 0x00000400 SQL_CA1_POS_DELETE* = 0x00000800 - SQL_CA1_POS_REFRESH* = 0x00001000 # positioned updates and deletes + SQL_CA1_POS_REFRESH* = 0x00001000 # positioned updates and deletes SQL_CA1_POSITIONED_UPDATE* = 0x00002000 SQL_CA1_POSITIONED_DELETE* = 0x00004000 - SQL_CA1_SELECT_FOR_UPDATE* = 0x00008000 # supported SQLBulkOperations operations + SQL_CA1_SELECT_FOR_UPDATE* = 0x00008000 # supported SQLBulkOperations operations SQL_CA1_BULK_ADD* = 0x00010000 SQL_CA1_BULK_UPDATE_BY_BOOKMARK* = 0x00020000 SQL_CA1_BULK_DELETE_BY_BOOKMARK* = 0x00040000 - SQL_CA1_BULK_FETCH_BY_BOOKMARK* = 0x00080000 # supported values for SQL_ATTR_SCROLL_CONCURRENCY + SQL_CA1_BULK_FETCH_BY_BOOKMARK* = 0x00080000 # supported values for SQL_ATTR_SCROLL_CONCURRENCY SQL_CA2_READ_ONLY_CONCURRENCY* = 1 SQL_CA2_LOCK_CONCURRENCY* = 2 SQL_CA2_OPT_ROWVER_CONCURRENCY* = 4 - SQL_CA2_OPT_VALUES_CONCURRENCY* = 8 # sensitivity of the cursor to its own inserts, deletes, and updates + SQL_CA2_OPT_VALUES_CONCURRENCY* = 8 # sensitivity of the cursor to its own inserts, deletes, and updates SQL_CA2_SENSITIVITY_ADDITIONS* = 0x00000010 SQL_CA2_SENSITIVITY_DELETIONS* = 0x00000020 - SQL_CA2_SENSITIVITY_UPDATES* = 0x00000040 # semantics of SQL_ATTR_MAX_ROWS + SQL_CA2_SENSITIVITY_UPDATES* = 0x00000040 # semantics of SQL_ATTR_MAX_ROWS SQL_CA2_MAX_ROWS_SELECT* = 0x00000080 SQL_CA2_MAX_ROWS_INSERT* = 0x00000100 SQL_CA2_MAX_ROWS_DELETE* = 0x00000200 @@ -308,25 +316,25 @@ const SQL_CA2_MAX_ROWS_CATALOG* = 0x00000800 SQL_CA2_MAX_ROWS_AFFECTS_ALL* = (SQL_CA2_MAX_ROWS_SELECT or SQL_CA2_MAX_ROWS_INSERT or SQL_CA2_MAX_ROWS_DELETE or - SQL_CA2_MAX_ROWS_UPDATE or SQL_CA2_MAX_ROWS_CATALOG) # semantics of - # SQL_DIAG_CURSOR_ROW_COUNT + SQL_CA2_MAX_ROWS_UPDATE or SQL_CA2_MAX_ROWS_CATALOG) # semantics of + # SQL_DIAG_CURSOR_ROW_COUNT SQL_CA2_CRC_EXACT* = 0x00001000 - SQL_CA2_CRC_APPROXIMATE* = 0x00002000 # the kinds of positioned statements that can be simulated + SQL_CA2_CRC_APPROXIMATE* = 0x00002000 # the kinds of positioned statements that can be simulated SQL_CA2_SIMULATE_NON_UNIQUE* = 0x00004000 SQL_CA2_SIMULATE_TRY_UNIQUE* = 0x00008000 - SQL_CA2_SIMULATE_UNIQUE* = 0x00010000 # Operations in SQLBulkOperations + SQL_CA2_SIMULATE_UNIQUE* = 0x00010000 # Operations in SQLBulkOperations SQL_ADD* = 4 SQL_SETPOS_MAX_OPTION_VALUE* = SQL_ADD SQL_UPDATE_BY_BOOKMARK* = 5 SQL_DELETE_BY_BOOKMARK* = 6 - SQL_FETCH_BY_BOOKMARK* = 7 # Operations in SQLSetPos + SQL_FETCH_BY_BOOKMARK* = 7 # Operations in SQLSetPos SQL_POSITION* = 0 SQL_REFRESH* = 1 SQL_UPDATE* = 2 - SQL_DELETE* = 3 # Lock options in SQLSetPos + SQL_DELETE* = 3 # Lock options in SQLSetPos SQL_LOCK_NO_CHANGE* = 0 SQL_LOCK_EXCLUSIVE* = 1 - SQL_LOCK_UNLOCK* = 2 # SQLExtendedFetch "rgfRowStatus" element values + SQL_LOCK_UNLOCK* = 2 # SQLExtendedFetch "rgfRowStatus" element values SQL_ROW_SUCCESS* = 0 SQL_ROW_DELETED* = 1 SQL_ROW_UPDATED* = 2 @@ -336,10 +344,10 @@ const SQL_ROW_SUCCESS_WITH_INFO* = 6 SQL_ROW_PROCEED* = 0 SQL_ROW_IGNORE* = 1 - SQL_MAX_DSN_LENGTH* = 32 # maximum data source name size + SQL_MAX_DSN_LENGTH* = 32 # maximum data source name size SQL_MAX_OPTION_STRING_LENGTH* = 256 SQL_ODBC_CURSORS* = 110 - SQL_ATTR_ODBC_CURSORS* = SQL_ODBC_CURSORS # SQL_ODBC_CURSORS options + SQL_ATTR_ODBC_CURSORS* = SQL_ODBC_CURSORS # SQL_ODBC_CURSORS options SQL_CUR_USE_IF_NEEDED* = 0 SQL_CUR_USE_ODBC* = 1 SQL_CUR_USE_DRIVER* = 2 @@ -349,7 +357,7 @@ const SQL_PARAM_INPUT_OUTPUT* = 2 SQL_RESULT_COL* = 3 SQL_PARAM_OUTPUT* = 4 - SQL_RETURN_VALUE* = 5 # special length/indicator values + SQL_RETURN_VALUE* = 5 # special length/indicator values SQL_NULL_DATA* = (- 1) SQL_DATA_AT_EXEC* = (- 2) SQL_SUCCESS* = 0 @@ -358,20 +366,20 @@ const SQL_ERROR* = (- 1) SQL_INVALID_HANDLE* = (- 2) SQL_STILL_EXECUTING* = 2 - SQL_NEED_DATA* = 99 # flags for null-terminated string - SQL_NTS* = (- 3) # maximum message length - SQL_MAX_MESSAGE_LENGTH* = 512 # date/time length constants + SQL_NEED_DATA* = 99 # flags for null-terminated string + SQL_NTS* = (- 3) # maximum message length + SQL_MAX_MESSAGE_LENGTH* = 512 # date/time length constants SQL_DATE_LEN* = 10 - SQL_TIME_LEN* = 8 # add P+1 if precision is nonzero - SQL_TIMESTAMP_LEN* = 19 # add P+1 if precision is nonzero - # handle type identifiers + SQL_TIME_LEN* = 8 # add P+1 if precision is nonzero + SQL_TIMESTAMP_LEN* = 19 # add P+1 if precision is nonzero + # handle type identifiers SQL_HANDLE_ENV* = 1 SQL_HANDLE_DBC* = 2 SQL_HANDLE_STMT* = 3 - SQL_HANDLE_DESC* = 4 # environment attribute - SQL_ATTR_OUTPUT_NTS* = 10001 # connection attributes + SQL_HANDLE_DESC* = 4 # environment attribute + SQL_ATTR_OUTPUT_NTS* = 10001 # connection attributes SQL_ATTR_AUTO_IPD* = 10001 - SQL_ATTR_METADATA_ID* = 10014 # statement attributes + SQL_ATTR_METADATA_ID* = 10014 # statement attributes SQL_ATTR_APP_ROW_DESC* = 10010 SQL_ATTR_APP_PARAM_DESC* = 10011 SQL_ATTR_IMP_ROW_DESC* = 10012 @@ -434,21 +442,21 @@ const SQL_MODE_DEFAULT* = SQL_MODE_READ_WRITE #* SQL_AUTOCOMMIT options */ SQL_AUTOCOMMIT_OFF* = 0 SQL_AUTOCOMMIT_ON* = 1 - SQL_AUTOCOMMIT_DEFAULT* = SQL_AUTOCOMMIT_ON # SQL_ATTR_CURSOR_SCROLLABLE values + SQL_AUTOCOMMIT_DEFAULT* = SQL_AUTOCOMMIT_ON # SQL_ATTR_CURSOR_SCROLLABLE values SQL_NONSCROLLABLE* = 0 - SQL_SCROLLABLE* = 1 # SQL_CURSOR_TYPE options + SQL_SCROLLABLE* = 1 # SQL_CURSOR_TYPE options SQL_CURSOR_FORWARD_ONLY* = 0 SQL_CURSOR_KEYSET_DRIVEN* = 1 SQL_CURSOR_DYNAMIC* = 2 SQL_CURSOR_STATIC* = 3 - SQL_CURSOR_TYPE_DEFAULT* = SQL_CURSOR_FORWARD_ONLY # Default value - # SQL_CONCURRENCY options + SQL_CURSOR_TYPE_DEFAULT* = SQL_CURSOR_FORWARD_ONLY # Default value + # SQL_CONCURRENCY options SQL_CONCUR_READ_ONLY* = 1 SQL_CONCUR_LOCK* = 2 SQL_CONCUR_ROWVER* = 3 SQL_CONCUR_VALUES* = 4 - SQL_CONCUR_DEFAULT* = SQL_CONCUR_READ_ONLY # Default value - # identifiers of fields in the SQL descriptor + SQL_CONCUR_DEFAULT* = SQL_CONCUR_READ_ONLY # Default value + # identifiers of fields in the SQL descriptor SQL_DESC_COUNT* = 1001 SQL_DESC_TYPE* = 1002 SQL_DESC_LENGTH* = 1003 @@ -462,7 +470,7 @@ const SQL_DESC_NAME* = 1011 SQL_DESC_UNNAMED* = 1012 SQL_DESC_OCTET_LENGTH* = 1013 - SQL_DESC_ALLOC_TYPE* = 1099 # identifiers of fields in the diagnostics area + SQL_DESC_ALLOC_TYPE* = 1099 # identifiers of fields in the diagnostics area SQL_DIAG_RETURNCODE* = 1 SQL_DIAG_NUMBER* = 2 SQL_DIAG_ROW_COUNT* = 3 @@ -474,7 +482,7 @@ const SQL_DIAG_SUBCLASS_ORIGIN* = 9 SQL_DIAG_CONNECTION_NAME* = 10 SQL_DIAG_SERVER_NAME* = 11 - SQL_DIAG_DYNAMIC_FUNCTION_CODE* = 12 # dynamic function codes + SQL_DIAG_DYNAMIC_FUNCTION_CODE* = 12 # dynamic function codes SQL_DIAG_ALTER_TABLE* = 4 SQL_DIAG_CREATE_INDEX* = (- 1) SQL_DIAG_CREATE_TABLE* = 77 @@ -490,36 +498,36 @@ const SQL_DIAG_REVOKE* = 59 SQL_DIAG_SELECT_CURSOR* = 85 SQL_DIAG_UNKNOWN_STATEMENT* = 0 - SQL_DIAG_UPDATE_WHERE* = 82 # Statement attribute values for cursor sensitivity + SQL_DIAG_UPDATE_WHERE* = 82 # Statement attribute values for cursor sensitivity SQL_UNSPECIFIED* = 0 SQL_INSENSITIVE* = 1 - SQL_SENSITIVE* = 2 # GetTypeInfo() request for all data types - SQL_ALL_TYPES* = 0 # Default conversion code for SQLBindCol(), SQLBindParam() and SQLGetData() + SQL_SENSITIVE* = 2 # GetTypeInfo() request for all data types + SQL_ALL_TYPES* = 0 # Default conversion code for SQLBindCol(), SQLBindParam() and SQLGetData() SQL_DEFAULT* = 99 # SQLGetData() code indicating that the application row descriptor - # specifies the data type - SQL_ARD_TYPE* = (- 99) # SQL date/time type subcodes + # specifies the data type + SQL_ARD_TYPE* = (- 99) # SQL date/time type subcodes SQL_CODE_DATE* = 1 SQL_CODE_TIME* = 2 - SQL_CODE_TIMESTAMP* = 3 # CLI option values + SQL_CODE_TIMESTAMP* = 3 # CLI option values SQL_FALSE* = 0 - SQL_TRUE* = 1 # values of NULLABLE field in descriptor + SQL_TRUE* = 1 # values of NULLABLE field in descriptor SQL_NO_NULLS* = 0 SQL_NULLABLE* = 1 # Value returned by SQLGetTypeInfo() to denote that it is - # not known whether or not a data type supports null values. - SQL_NULLABLE_UNKNOWN* = 2 + # not known whether or not a data type supports null values. + SQL_NULLABLE_UNKNOWN* = 2 SQL_CLOSE* = 0 SQL_DROP* = 1 SQL_UNBIND* = 2 SQL_RESET_PARAMS* = 3 # Codes used for FetchOrientation in SQLFetchScroll(), - # and in SQLDataSources() + # and in SQLDataSources() SQL_FETCH_NEXT* = 1 SQL_FETCH_FIRST* = 2 SQL_FETCH_FIRST_USER* = 31 - SQL_FETCH_FIRST_SYSTEM* = 32 # Other codes used for FetchOrientation in SQLFetchScroll() + SQL_FETCH_FIRST_SYSTEM* = 32 # Other codes used for FetchOrientation in SQLFetchScroll() SQL_FETCH_LAST* = 3 SQL_FETCH_PRIOR* = 4 SQL_FETCH_ABSOLUTE* = 5 - SQL_FETCH_RELATIVE* = 6 + SQL_FETCH_RELATIVE* = 6 SQL_NULL_HENV* = SqlHEnv(nil) SQL_NULL_HDBC* = SqlHDBC(nil) SQL_NULL_HSTMT* = SqlHStmt(nil) @@ -529,7 +537,7 @@ const SQL_SCOPE_TRANSACTION* = 1 SQL_SCOPE_SESSION* = 2 #* Column types and scopes in SQLSpecialColumns. */ SQL_BEST_ROWID* = 1 - SQL_ROWVER* = 2 + SQL_ROWVER* = 2 SQL_ROW_IDENTIFIER* = 1 #* Reserved values for UNIQUE argument of SQLStatistics() */ SQL_INDEX_UNIQUE* = 0 SQL_INDEX_ALL* = 1 #* Reserved values for RESERVED argument of SQLStatistics() */ @@ -538,13 +546,13 @@ const SQL_TABLE_STAT* = 0 SQL_INDEX_CLUSTERED* = 1 SQL_INDEX_HASHED* = 2 - SQL_INDEX_OTHER* = 3 + SQL_INDEX_OTHER* = 3 SQL_SCROLL_CONCURRENCY* = 43 SQL_TXN_CAPABLE* = 46 SQL_TRANSACTION_CAPABLE* = SQL_TXN_CAPABLE SQL_USER_NAME* = 47 SQL_TXN_ISOLATION_OPTION* = 72 - SQL_TRANSACTION_ISOLATION_OPTION* = SQL_TXN_ISOLATION_OPTION + SQL_TRANSACTION_ISOLATION_OPTION* = SQL_TXN_ISOLATION_OPTION SQL_OJ_CAPABILITIES* = 115 SQL_OUTER_JOIN_CAPABILITIES* = SQL_OJ_CAPABILITIES SQL_XOPEN_CLI_YEAR* = 10000 @@ -570,10 +578,10 @@ const SQL_TXN_REPEATABLE_READ* = 4 SQL_TRANSACTION_REPEATABLE_READ* = SQL_TXN_REPEATABLE_READ SQL_TXN_SERIALIZABLE* = 8 - SQL_TRANSACTION_SERIALIZABLE* = SQL_TXN_SERIALIZABLE + SQL_TRANSACTION_SERIALIZABLE* = SQL_TXN_SERIALIZABLE SQL_SS_ADDITIONS* = 1 SQL_SS_DELETIONS* = 2 - SQL_SS_UPDATES* = 4 # SQLColAttributes defines + SQL_SS_UPDATES* = 4 # SQLColAttributes defines SQL_COLUMN_COUNT* = 0 SQL_COLUMN_NAME* = 1 SQL_COLUMN_TYPE* = 2 @@ -633,166 +641,166 @@ const ODBC_CONFIG_SYS_DSN* = 5 ODBC_REMOVE_SYS_DSN* = 6 -proc SQLAllocHandle*(HandleType: TSqlSmallInt, InputHandle: SqlHandle, +proc SQLAllocHandle*(HandleType: TSqlSmallInt, InputHandle: SqlHandle, OutputHandlePtr: var SqlHandle): TSqlSmallInt{. dynlib: odbclib, importc.} -proc SQLSetEnvAttr*(EnvironmentHandle: SqlHEnv, Attribute: TSqlInteger, +proc SQLSetEnvAttr*(EnvironmentHandle: SqlHEnv, Attribute: TSqlInteger, Value: SqlPointer, StringLength: TSqlInteger): TSqlSmallInt{. dynlib: odbclib, importc.} -proc SQLGetEnvAttr*(EnvironmentHandle: SqlHEnv, Attribute: TSqlInteger, - Value: SqlPointer, BufferLength: TSqlInteger, - StringLength: PSQLINTEGER): TSqlSmallInt{.dynlib: odbclib, +proc SQLGetEnvAttr*(EnvironmentHandle: SqlHEnv, Attribute: TSqlInteger, + Value: SqlPointer, BufferLength: TSqlInteger, + StringLength: PSQLINTEGER): TSqlSmallInt{.dynlib: odbclib, importc.} proc SQLFreeHandle*(HandleType: TSqlSmallInt, Handle: SqlHandle): TSqlSmallInt{. dynlib: odbclib, importc.} -proc SQLGetDiagRec*(HandleType: TSqlSmallInt, Handle: SqlHandle, - RecNumber: TSqlSmallInt, Sqlstate: PSQLCHAR, - NativeError: var TSqlInteger, MessageText: PSQLCHAR, +proc SQLGetDiagRec*(HandleType: TSqlSmallInt, Handle: SqlHandle, + RecNumber: TSqlSmallInt, Sqlstate: PSQLCHAR, + NativeError: var TSqlInteger, MessageText: PSQLCHAR, BufferLength: TSqlSmallInt, TextLength: var TSqlSmallInt): TSqlSmallInt{. dynlib: odbclib, importc.} -proc SQLGetDiagField*(HandleType: TSqlSmallInt, Handle: SqlHandle, - RecNumber: TSqlSmallInt, DiagIdentifier: TSqlSmallInt, - DiagInfoPtr: SqlPointer, BufferLength: TSqlSmallInt, +proc SQLGetDiagField*(HandleType: TSqlSmallInt, Handle: SqlHandle, + RecNumber: TSqlSmallInt, DiagIdentifier: TSqlSmallInt, + DiagInfoPtr: SqlPointer, BufferLength: TSqlSmallInt, StringLengthPtr: var TSqlSmallInt): TSqlSmallInt{. dynlib: odbclib, importc.} -proc SQLConnect*(ConnectionHandle: SqlHDBC, ServerName: PSQLCHAR, - NameLength1: TSqlSmallInt, UserName: PSQLCHAR, - NameLength2: TSqlSmallInt, Authentication: PSQLCHAR, +proc SQLConnect*(ConnectionHandle: SqlHDBC, ServerName: PSQLCHAR, + NameLength1: TSqlSmallInt, UserName: PSQLCHAR, + NameLength2: TSqlSmallInt, Authentication: PSQLCHAR, NameLength3: TSqlSmallInt): TSqlSmallInt{.dynlib: odbclib, importc.} -proc SQLDisconnect*(ConnectionHandle: SqlHDBC): TSqlSmallInt{.dynlib: odbclib, +proc SQLDisconnect*(ConnectionHandle: SqlHDBC): TSqlSmallInt{.dynlib: odbclib, importc.} -proc SQLDriverConnect*(hdbc: SqlHDBC, hwnd: SqlHWND, szCsin: cstring, - szCLen: TSqlSmallInt, szCsout: cstring, - cbCSMax: TSqlSmallInt, cbCsOut: var TSqlSmallInt, +proc SQLDriverConnect*(hdbc: SqlHDBC, hwnd: SqlHWND, szCsin: cstring, + szCLen: TSqlSmallInt, szCsout: cstring, + cbCSMax: TSqlSmallInt, cbCsOut: var TSqlSmallInt, f: SqlUSmallInt): TSqlSmallInt{.dynlib: odbclib, importc.} -proc SQLBrowseConnect*(hdbc: SqlHDBC, szConnStrIn: PSQLCHAR, - cbConnStrIn: TSqlSmallInt, szConnStrOut: PSQLCHAR, - cbConnStrOutMax: TSqlSmallInt, +proc SQLBrowseConnect*(hdbc: SqlHDBC, szConnStrIn: PSQLCHAR, + cbConnStrIn: TSqlSmallInt, szConnStrOut: PSQLCHAR, + cbConnStrOutMax: TSqlSmallInt, cbConnStrOut: var TSqlSmallInt): TSqlSmallInt{. dynlib: odbclib, importc.} -proc SQLExecDirect*(StatementHandle: SqlHStmt, StatementText: PSQLCHAR, +proc SQLExecDirect*(StatementHandle: SqlHStmt, StatementText: PSQLCHAR, TextLength: TSqlInteger): TSqlSmallInt{.dynlib: odbclib, importc.} -proc SQLPrepare*(StatementHandle: SqlHStmt, StatementText: PSQLCHAR, +proc SQLPrepare*(StatementHandle: SqlHStmt, StatementText: PSQLCHAR, TextLength: TSqlInteger): TSqlSmallInt{.dynlib: odbclib, importc.} -proc SQLCloseCursor*(StatementHandle: SqlHStmt): TSqlSmallInt{.dynlib: odbclib, +proc SQLCloseCursor*(StatementHandle: SqlHStmt): TSqlSmallInt{.dynlib: odbclib, importc.} proc SQLExecute*(StatementHandle: SqlHStmt): TSqlSmallInt{.dynlib: odbclib, importc.} proc SQLFetch*(StatementHandle: SqlHStmt): TSqlSmallInt{.dynlib: odbclib, importc.} proc SQLNumResultCols*(StatementHandle: SqlHStmt, ColumnCount: var TSqlSmallInt): TSqlSmallInt{. dynlib: odbclib, importc.} -proc SQLDescribeCol*(StatementHandle: SqlHStmt, ColumnNumber: SqlUSmallInt, - ColumnName: PSQLCHAR, BufferLength: TSqlSmallInt, - NameLength: var TSqlSmallInt, DataType: var TSqlSmallInt, - ColumnSize: var SqlUInteger, +proc SQLDescribeCol*(StatementHandle: SqlHStmt, ColumnNumber: SqlUSmallInt, + ColumnName: PSQLCHAR, BufferLength: TSqlSmallInt, + NameLength: var TSqlSmallInt, DataType: var TSqlSmallInt, + ColumnSize: var SqlUInteger, DecimalDigits: var TSqlSmallInt, Nullable: var TSqlSmallInt): TSqlSmallInt{. dynlib: odbclib, importc.} -proc SQLFetchScroll*(StatementHandle: SqlHStmt, FetchOrientation: TSqlSmallInt, - FetchOffset: TSqlInteger): TSqlSmallInt{.dynlib: odbclib, +proc SQLFetchScroll*(StatementHandle: SqlHStmt, FetchOrientation: TSqlSmallInt, + FetchOffset: TSqlInteger): TSqlSmallInt{.dynlib: odbclib, importc.} -proc SQLExtendedFetch*(hstmt: SqlHStmt, fFetchType: SqlUSmallInt, - irow: TSqlInteger, pcrow: PSQLUINTEGER, - rgfRowStatus: PSQLUSMALLINT): TSqlSmallInt{.dynlib: odbclib, +proc SQLExtendedFetch*(hstmt: SqlHStmt, fFetchType: SqlUSmallInt, + irow: TSqlInteger, pcrow: PSQLUINTEGER, + rgfRowStatus: PSQLUSMALLINT): TSqlSmallInt{.dynlib: odbclib, importc.} -proc SQLGetData*(StatementHandle: SqlHStmt, ColumnNumber: SqlUSmallInt, - TargetType: TSqlSmallInt, TargetValue: SqlPointer, +proc SQLGetData*(StatementHandle: SqlHStmt, ColumnNumber: SqlUSmallInt, + TargetType: TSqlSmallInt, TargetValue: SqlPointer, BufferLength: TSqlInteger, StrLen_or_Ind: PSQLINTEGER): TSqlSmallInt{. dynlib: odbclib, importc.} -proc SQLSetStmtAttr*(StatementHandle: SqlHStmt, Attribute: TSqlInteger, +proc SQLSetStmtAttr*(StatementHandle: SqlHStmt, Attribute: TSqlInteger, Value: SqlPointer, StringLength: TSqlInteger): TSqlSmallInt{. dynlib: odbclib, importc.} -proc SQLGetStmtAttr*(StatementHandle: SqlHStmt, Attribute: TSqlInteger, - Value: SqlPointer, BufferLength: TSqlInteger, - StringLength: PSQLINTEGER): TSqlSmallInt{.dynlib: odbclib, +proc SQLGetStmtAttr*(StatementHandle: SqlHStmt, Attribute: TSqlInteger, + Value: SqlPointer, BufferLength: TSqlInteger, + StringLength: PSQLINTEGER): TSqlSmallInt{.dynlib: odbclib, importc.} -proc SQLGetInfo*(ConnectionHandle: SqlHDBC, InfoType: SqlUSmallInt, - InfoValue: SqlPointer, BufferLength: TSqlSmallInt, - StringLength: PSQLSMALLINT): TSqlSmallInt{.dynlib: odbclib, +proc SQLGetInfo*(ConnectionHandle: SqlHDBC, InfoType: SqlUSmallInt, + InfoValue: SqlPointer, BufferLength: TSqlSmallInt, + StringLength: PSQLSMALLINT): TSqlSmallInt{.dynlib: odbclib, importc.} proc SQLBulkOperations*(StatementHandle: SqlHStmt, Operation: TSqlSmallInt): TSqlSmallInt{. dynlib: odbclib, importc.} -proc SQLPutData*(StatementHandle: SqlHStmt, Data: SqlPointer, +proc SQLPutData*(StatementHandle: SqlHStmt, Data: SqlPointer, StrLen_or_Ind: TSqlInteger): TSqlSmallInt{.dynlib: odbclib, importc.} -proc SQLBindCol*(StatementHandle: SqlHStmt, ColumnNumber: SqlUSmallInt, - TargetType: TSqlSmallInt, TargetValue: SqlPointer, +proc SQLBindCol*(StatementHandle: SqlHStmt, ColumnNumber: SqlUSmallInt, + TargetType: TSqlSmallInt, TargetValue: SqlPointer, BufferLength: TSqlInteger, StrLen_or_Ind: PSQLINTEGER): TSqlSmallInt{. dynlib: odbclib, importc.} -proc SQLSetPos*(hstmt: SqlHStmt, irow: SqlUSmallInt, fOption: SqlUSmallInt, +proc SQLSetPos*(hstmt: SqlHStmt, irow: SqlUSmallInt, fOption: SqlUSmallInt, fLock: SqlUSmallInt): TSqlSmallInt{.dynlib: odbclib, importc.} -proc SQLDataSources*(EnvironmentHandle: SqlHEnv, Direction: SqlUSmallInt, - ServerName: PSQLCHAR, BufferLength1: TSqlSmallInt, - NameLength1: PSQLSMALLINT, Description: PSQLCHAR, +proc SQLDataSources*(EnvironmentHandle: SqlHEnv, Direction: SqlUSmallInt, + ServerName: PSQLCHAR, BufferLength1: TSqlSmallInt, + NameLength1: PSQLSMALLINT, Description: PSQLCHAR, BufferLength2: TSqlSmallInt, NameLength2: PSQLSMALLINT): TSqlSmallInt{. dynlib: odbclib, importc.} -proc SQLDrivers*(EnvironmentHandle: SqlHEnv, Direction: SqlUSmallInt, - DriverDescription: PSQLCHAR, BufferLength1: TSqlSmallInt, - DescriptionLength1: PSQLSMALLINT, DriverAttributes: PSQLCHAR, +proc SQLDrivers*(EnvironmentHandle: SqlHEnv, Direction: SqlUSmallInt, + DriverDescription: PSQLCHAR, BufferLength1: TSqlSmallInt, + DescriptionLength1: PSQLSMALLINT, DriverAttributes: PSQLCHAR, BufferLength2: TSqlSmallInt, AttributesLength2: PSQLSMALLINT): TSqlSmallInt{. dynlib: odbclib, importc.} -proc SQLSetConnectAttr*(ConnectionHandle: SqlHDBC, Attribute: TSqlInteger, +proc SQLSetConnectAttr*(ConnectionHandle: SqlHDBC, Attribute: TSqlInteger, Value: SqlPointer, StringLength: TSqlInteger): TSqlSmallInt{. dynlib: odbclib, importc.} -proc SQLGetCursorName*(StatementHandle: SqlHStmt, CursorName: PSQLCHAR, +proc SQLGetCursorName*(StatementHandle: SqlHStmt, CursorName: PSQLCHAR, BufferLength: TSqlSmallInt, NameLength: PSQLSMALLINT): TSqlSmallInt{. dynlib: odbclib, importc.} -proc SQLSetCursorName*(StatementHandle: SqlHStmt, CursorName: PSQLCHAR, - NameLength: TSqlSmallInt): TSqlSmallInt{.dynlib: odbclib, +proc SQLSetCursorName*(StatementHandle: SqlHStmt, CursorName: PSQLCHAR, + NameLength: TSqlSmallInt): TSqlSmallInt{.dynlib: odbclib, importc.} proc SQLRowCount*(StatementHandle: SqlHStmt, RowCount: var TSqlInteger): TSqlSmallInt{. dynlib: odbclib, importc.} -proc SQLBindParameter*(hstmt: SqlHStmt, ipar: SqlUSmallInt, - fParamType: TSqlSmallInt, fCType: TSqlSmallInt, - fSqlType: TSqlSmallInt, cbColDef: SqlUInteger, - ibScale: TSqlSmallInt, rgbValue: SqlPointer, +proc SQLBindParameter*(hstmt: SqlHStmt, ipar: SqlUSmallInt, + fParamType: TSqlSmallInt, fCType: TSqlSmallInt, + fSqlType: TSqlSmallInt, cbColDef: SqlUInteger, + ibScale: TSqlSmallInt, rgbValue: SqlPointer, cbValueMax: TSqlInteger, pcbValue: PSQLINTEGER): TSqlSmallInt{. dynlib: odbclib, importc.} proc SQLFreeStmt*(StatementHandle: SqlHStmt, Option: SqlUSmallInt): TSqlSmallInt{. dynlib: odbclib, importc.} -proc SQLColAttribute*(StatementHandle: SqlHStmt, ColumnNumber: SqlUSmallInt, - FieldIdentifier: SqlUSmallInt, - CharacterAttribute: PSQLCHAR, BufferLength: TSqlSmallInt, - StringLength: PSQLSMALLINT, +proc SQLColAttribute*(StatementHandle: SqlHStmt, ColumnNumber: SqlUSmallInt, + FieldIdentifier: SqlUSmallInt, + CharacterAttribute: PSQLCHAR, BufferLength: TSqlSmallInt, + StringLength: PSQLSMALLINT, NumericAttribute: SqlPointer): TSqlSmallInt{. dynlib: odbclib, importc.} -proc SQLEndTran*(HandleType: TSqlSmallInt, Handle: SqlHandle, - CompletionType: TSqlSmallInt): TSqlSmallInt{.dynlib: odbclib, +proc SQLEndTran*(HandleType: TSqlSmallInt, Handle: SqlHandle, + CompletionType: TSqlSmallInt): TSqlSmallInt{.dynlib: odbclib, importc.} -proc SQLTables*(hstmt: SqlHStmt, szTableQualifier: PSQLCHAR, - cbTableQualifier: TSqlSmallInt, szTableOwner: PSQLCHAR, - cbTableOwner: TSqlSmallInt, szTableName: PSQLCHAR, - cbTableName: TSqlSmallInt, szTableType: PSQLCHAR, +proc SQLTables*(hstmt: SqlHStmt, szTableQualifier: PSQLCHAR, + cbTableQualifier: TSqlSmallInt, szTableOwner: PSQLCHAR, + cbTableOwner: TSqlSmallInt, szTableName: PSQLCHAR, + cbTableName: TSqlSmallInt, szTableType: PSQLCHAR, cbTableType: TSqlSmallInt): TSqlSmallInt{.dynlib: odbclib, importc.} -proc SQLColumns*(hstmt: SqlHStmt, szTableQualifier: PSQLCHAR, - cbTableQualifier: TSqlSmallInt, szTableOwner: PSQLCHAR, - cbTableOwner: TSqlSmallInt, szTableName: PSQLCHAR, - cbTableName: TSqlSmallInt, szColumnName: PSQLCHAR, +proc SQLColumns*(hstmt: SqlHStmt, szTableQualifier: PSQLCHAR, + cbTableQualifier: TSqlSmallInt, szTableOwner: PSQLCHAR, + cbTableOwner: TSqlSmallInt, szTableName: PSQLCHAR, + cbTableName: TSqlSmallInt, szColumnName: PSQLCHAR, cbColumnName: TSqlSmallInt): TSqlSmallInt{.dynlib: odbclib, importc.} -proc SQLSpecialColumns*(StatementHandle: SqlHStmt, IdentifierType: SqlUSmallInt, - CatalogName: PSQLCHAR, NameLength1: TSqlSmallInt, - SchemaName: PSQLCHAR, NameLength2: TSqlSmallInt, - TableName: PSQLCHAR, NameLength3: TSqlSmallInt, - Scope: SqlUSmallInt, +proc SQLSpecialColumns*(StatementHandle: SqlHStmt, IdentifierType: SqlUSmallInt, + CatalogName: PSQLCHAR, NameLength1: TSqlSmallInt, + SchemaName: PSQLCHAR, NameLength2: TSqlSmallInt, + TableName: PSQLCHAR, NameLength3: TSqlSmallInt, + Scope: SqlUSmallInt, Nullable: SqlUSmallInt): TSqlSmallInt{. dynlib: odbclib, importc.} -proc SQLProcedures*(hstmt: SqlHStmt, szTableQualifier: PSQLCHAR, - cbTableQualifier: TSqlSmallInt, szTableOwner: PSQLCHAR, - cbTableOwner: TSqlSmallInt, szTableName: PSQLCHAR, - cbTableName: TSqlSmallInt): TSqlSmallInt{.dynlib: odbclib, +proc SQLProcedures*(hstmt: SqlHStmt, szTableQualifier: PSQLCHAR, + cbTableQualifier: TSqlSmallInt, szTableOwner: PSQLCHAR, + cbTableOwner: TSqlSmallInt, szTableName: PSQLCHAR, + cbTableName: TSqlSmallInt): TSqlSmallInt{.dynlib: odbclib, importc.} -proc SQLPrimaryKeys*(hstmt: SqlHStmt, CatalogName: PSQLCHAR, - NameLength1: TSqlSmallInt, SchemaName: PSQLCHAR, - NameLength2: TSqlSmallInt, TableName: PSQLCHAR, - NameLength3: TSqlSmallInt): TSqlSmallInt{.dynlib: odbclib, +proc SQLPrimaryKeys*(hstmt: SqlHStmt, CatalogName: PSQLCHAR, + NameLength1: TSqlSmallInt, SchemaName: PSQLCHAR, + NameLength2: TSqlSmallInt, TableName: PSQLCHAR, + NameLength3: TSqlSmallInt): TSqlSmallInt{.dynlib: odbclib, importc.} -proc SQLProcedureColumns*(hstmt: SqlHStmt, CatalogName: PSQLCHAR, - NameLength1: TSqlSmallInt, SchemaName: PSQLCHAR, - NameLength2: TSqlSmallInt, ProcName: PSQLCHAR, - NameLength3: TSqlSmallInt, ColumnName: PSQLCHAR, - NameLength4: TSqlSmallInt): TSqlSmallInt{.dynlib: odbclib, +proc SQLProcedureColumns*(hstmt: SqlHStmt, CatalogName: PSQLCHAR, + NameLength1: TSqlSmallInt, SchemaName: PSQLCHAR, + NameLength2: TSqlSmallInt, ProcName: PSQLCHAR, + NameLength3: TSqlSmallInt, ColumnName: PSQLCHAR, + NameLength4: TSqlSmallInt): TSqlSmallInt{.dynlib: odbclib, importc.} -proc SQLStatistics*(hstmt: SqlHStmt, CatalogName: PSQLCHAR, - NameLength1: TSqlSmallInt, SchemaName: PSQLCHAR, - NameLength2: TSqlSmallInt, TableName: PSQLCHAR, - NameLength3: TSqlSmallInt, Unique: SqlUSmallInt, +proc SQLStatistics*(hstmt: SqlHStmt, CatalogName: PSQLCHAR, + NameLength1: TSqlSmallInt, SchemaName: PSQLCHAR, + NameLength2: TSqlSmallInt, TableName: PSQLCHAR, + NameLength3: TSqlSmallInt, Unique: SqlUSmallInt, Reserved: SqlUSmallInt): TSqlSmallInt {. dynlib: odbclib, importc.} diff --git a/lib/wrappers/openssl.nim b/lib/wrappers/openssl.nim index 03729dbab..013f26943 100644 --- a/lib/wrappers/openssl.nim +++ b/lib/wrappers/openssl.nim @@ -1,41 +1,11 @@ -#==============================================================================# -# Project: Ararat Synapse | 003.004.001 # -#==============================================================================# -# Content: SSL support by OpenSSL # -#==============================================================================# -# Copyright (c)1999-2005, Lukas Gebauer # -# All rights reserved. # -# # -# Redistribution and use in source and binary forms, with or without # -# modification, are permitted provided that the following conditions are met: # -# # -# Redistributions of source code must retain the above copyright notice, this # -# list of conditions and the following disclaimer. # -# # -# Redistributions in binary form must reproduce the above copyright notice, # -# this list of conditions and the following disclaimer in the documentation # -# and/or other materials provided with the distribution. # -# # -# Neither the name of Lukas Gebauer nor the names of its contributors may # -# be used to endorse or promote products derived from this software without # -# specific prior written permission. # -# # -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # -# ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR # -# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # -# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # -# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # -# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # -# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # -# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH # -# DAMAGE. # -#==============================================================================# -# The Initial Developer of the Original Code is Lukas Gebauer (Czech Republic).# -# Portions created by Lukas Gebauer are Copyright (c)2002-2005. # -# All Rights Reserved. # -#==============================================================================# +# +# +# Nim's Runtime Library +# (c) Copyright 2015 Andreas Rumpf +# +# See the file "copying.txt", included in this +# distribution, for details about the copyright. +# ## OpenSSL support @@ -43,8 +13,8 @@ const useWinVersion = defined(Windows) or defined(nimdoc) -when useWinVersion: - const +when useWinVersion: + const DLLSSLName = "(ssleay32|libssl32).dll" DLLUtilName = "libeay32.dll" from winlean import SocketHandle @@ -56,12 +26,12 @@ else: DLLSSLName = "libssl" & versions & ".dylib" DLLUtilName = "libcrypto" & versions & ".dylib" else: - const + const DLLSSLName = "libssl.so" & versions DLLUtilName = "libcrypto.so" & versions from posix import SocketHandle -type +type SslStruct {.final, pure.} = object SslPtr* = ptr SslStruct PSslPtr* = ptr SslPtr @@ -80,7 +50,7 @@ type PFunction* = proc () {.cdecl.} DES_cblock* = array[0..7, int8] PDES_cblock* = ptr DES_cblock - des_ks_struct*{.final.} = object + des_ks_struct*{.final.} = object ks*: DES_cblock weak_key*: cInt @@ -88,7 +58,7 @@ type {.deprecated: [PSSL: SslPtr, PSSL_CTX: SslCtx, PBIO: BIO].} -const +const SSL_SENT_SHUTDOWN* = 1 SSL_RECEIVED_SHUTDOWN* = 2 EVP_MAX_MD_SIZE* = 16 + 20 @@ -116,8 +86,8 @@ const SSL_CTRL_GET_FLAGS* = 13 SSL_CTRL_EXTRA_CHAIN_CERT* = 14 SSL_CTRL_SET_MSG_CALLBACK* = 15 - SSL_CTRL_SET_MSG_CALLBACK_ARG* = 16 # only applies to datagram connections - SSL_CTRL_SET_MTU* = 17 # Stats + SSL_CTRL_SET_MSG_CALLBACK_ARG* = 16 # only applies to datagram connections + SSL_CTRL_SET_MTU* = 17 # Stats SSL_CTRL_SESS_NUMBER* = 20 SSL_CTRL_SESS_CONNECT* = 21 SSL_CTRL_SESS_CONNECT_GOOD* = 22 @@ -204,7 +174,7 @@ const SSL_FILETYPE_ASN1* = 2 SSL_FILETYPE_PEM* = 1 EVP_PKEY_RSA* = 6 # libssl.dll - + BIO_C_SET_CONNECT = 100 BIO_C_DO_STATE_MACHINE = 101 BIO_C_GET_SSL = 110 @@ -237,7 +207,7 @@ proc SSL_CTX_use_certificate_chain_file*(ctx: SslCtx, filename: cstring): cInt{. stdcall, dynlib: DLLSSLName, importc.} proc SSL_CTX_use_PrivateKey_file*(ctx: SslCtx, filename: cstring, typ: cInt): cInt{.cdecl, dynlib: DLLSSLName, importc.} -proc SSL_CTX_check_private_key*(ctx: SslCtx): cInt{.cdecl, dynlib: DLLSSLName, +proc SSL_CTX_check_private_key*(ctx: SslCtx): cInt{.cdecl, dynlib: DLLSSLName, importc.} proc SSL_set_fd*(ssl: SslPtr, fd: SocketHandle): cint{.cdecl, dynlib: DLLSSLName, importc.} @@ -256,7 +226,7 @@ proc BIO_new_ssl_connect*(ctx: SslCtx): BIO{.cdecl, dynlib: DLLSSLName, importc.} proc BIO_ctrl*(bio: BIO, cmd: cint, larg: int, arg: cstring): int{.cdecl, dynlib: DLLSSLName, importc.} -proc BIO_get_ssl*(bio: BIO, ssl: ptr SslPtr): int = +proc BIO_get_ssl*(bio: BIO, ssl: ptr SslPtr): int = return BIO_ctrl(bio, BIO_C_GET_SSL, 0, cast[cstring](ssl)) proc BIO_set_conn_hostname*(bio: BIO, name: cstring): int = return BIO_ctrl(bio, BIO_C_SET_CONNECT, 0, name) @@ -266,16 +236,16 @@ proc BIO_do_connect*(bio: BIO): int = return BIO_do_handshake(bio) when not defined(nimfix): - proc BIO_read*(b: BIO, data: cstring, length: cInt): cInt{.cdecl, + proc BIO_read*(b: BIO, data: cstring, length: cInt): cInt{.cdecl, dynlib: DLLUtilName, importc.} - proc BIO_write*(b: BIO, data: cstring, length: cInt): cInt{.cdecl, + proc BIO_write*(b: BIO, data: cstring, length: cInt): cInt{.cdecl, dynlib: DLLUtilName, importc.} proc BIO_free*(b: BIO): cInt{.cdecl, dynlib: DLLUtilName, importc.} proc ERR_print_errors_fp*(fp: File){.cdecl, dynlib: DLLSSLName, importc.} -proc ERR_error_string*(e: cInt, buf: cstring): cstring{.cdecl, +proc ERR_error_string*(e: cInt, buf: cstring): cstring{.cdecl, dynlib: DLLUtilName, importc.} proc ERR_get_error*(): cInt{.cdecl, dynlib: DLLUtilName, importc.} proc ERR_peek_last_error*(): cInt{.cdecl, dynlib: DLLUtilName, importc.} @@ -285,7 +255,7 @@ proc OpenSSL_add_all_algorithms*(){.cdecl, dynlib: DLLUtilName, importc: "OPENSS proc OPENSSL_config*(configName: cstring){.cdecl, dynlib: DLLSSLName, importc.} when not useWinVersion: - proc CRYPTO_set_mem_functions(a,b,c: pointer){.cdecl, + proc CRYPTO_set_mem_functions(a,b,c: pointer){.cdecl, dynlib: DLLUtilName, importc.} proc allocWrapper(size: int): pointer {.cdecl.} = alloc(size) @@ -375,7 +345,7 @@ proc ErrRemoveState*(pid: cInt){.cdecl, dynlib: DLLUtilName, importc: "ERR_remov when true: discard else: - proc SslCtxSetCipherList*(arg0: PSSL_CTX, str: cstring): cInt{.cdecl, + proc SslCtxSetCipherList*(arg0: PSSL_CTX, str: cstring): cInt{.cdecl, dynlib: DLLSSLName, importc.} proc SslCtxNew*(meth: PSSL_METHOD): PSSL_CTX{.cdecl, dynlib: DLLSSLName, importc.} @@ -391,12 +361,12 @@ else: proc SslMethodV3*(): PSSL_METHOD{.cdecl, dynlib: DLLSSLName, importc.} proc SslMethodTLSV1*(): PSSL_METHOD{.cdecl, dynlib: DLLSSLName, importc.} proc SslMethodV23*(): PSSL_METHOD{.cdecl, dynlib: DLLSSLName, importc.} - proc SslCtxUsePrivateKey*(ctx: PSSL_CTX, pkey: SslPtr): cInt{.cdecl, + proc SslCtxUsePrivateKey*(ctx: PSSL_CTX, pkey: SslPtr): cInt{.cdecl, dynlib: DLLSSLName, importc.} proc SslCtxUsePrivateKeyASN1*(pk: cInt, ctx: PSSL_CTX, d: cstring, length: int): cInt{.cdecl, dynlib: DLLSSLName, importc.} - proc SslCtxUseCertificate*(ctx: PSSL_CTX, x: SslPtr): cInt{.cdecl, + proc SslCtxUseCertificate*(ctx: PSSL_CTX, x: SslPtr): cInt{.cdecl, dynlib: DLLSSLName, importc.} proc SslCtxUseCertificateASN1*(ctx: PSSL_CTX, length: int, d: cstring): cInt{. cdecl, dynlib: DLLSSLName, importc.} @@ -404,9 +374,9 @@ else: # function SslCtxUseCertificateChainFile(ctx: PSSL_CTX; const filename: PChar):cInt; proc SslCtxUseCertificateChainFile*(ctx: PSSL_CTX, filename: cstring): cInt{. cdecl, dynlib: DLLSSLName, importc.} - proc SslCtxSetDefaultPasswdCb*(ctx: PSSL_CTX, cb: PPasswdCb){.cdecl, + proc SslCtxSetDefaultPasswdCb*(ctx: PSSL_CTX, cb: PPasswdCb){.cdecl, dynlib: DLLSSLName, importc.} - proc SslCtxSetDefaultPasswdCbUserdata*(ctx: PSSL_CTX, u: SslPtr){.cdecl, + proc SslCtxSetDefaultPasswdCbUserdata*(ctx: PSSL_CTX, u: SslPtr){.cdecl, dynlib: DLLSSLName, importc.} # function SslCtxLoadVerifyLocations(ctx: PSSL_CTX; const CAfile: PChar; const CApath: PChar):cInt; proc SslCtxLoadVerifyLocations*(ctx: PSSL_CTX, CAfile: cstring, CApath: cstring): cInt{. @@ -416,15 +386,15 @@ else: proc SslConnect*(ssl: PSSL): cInt{.cdecl, dynlib: DLLSSLName, importc.} - + proc SslGetVersion*(ssl: PSSL): cstring{.cdecl, dynlib: DLLSSLName, importc.} - proc SslGetPeerCertificate*(ssl: PSSL): PX509{.cdecl, dynlib: DLLSSLName, + proc SslGetPeerCertificate*(ssl: PSSL): PX509{.cdecl, dynlib: DLLSSLName, importc.} - proc SslCtxSetVerify*(ctx: PSSL_CTX, mode: cInt, arg2: PFunction){.cdecl, + proc SslCtxSetVerify*(ctx: PSSL_CTX, mode: cInt, arg2: PFunction){.cdecl, dynlib: DLLSSLName, importc.} proc SSLGetCurrentCipher*(s: PSSL): SslPtr{.cdecl, dynlib: DLLSSLName, importc.} proc SSLCipherGetName*(c: SslPtr): cstring{.cdecl, dynlib: DLLSSLName, importc.} - proc SSLCipherGetBits*(c: SslPtr, alg_bits: var cInt): cInt{.cdecl, + proc SSLCipherGetBits*(c: SslPtr, alg_bits: var cInt): cInt{.cdecl, dynlib: DLLSSLName, importc.} proc SSLGetVerifyResult*(ssl: PSSL): int{.cdecl, dynlib: DLLSSLName, importc.} # libeay.dll @@ -432,39 +402,39 @@ else: proc X509Free*(x: PX509){.cdecl, dynlib: DLLUtilName, importc.} proc X509NameOneline*(a: PX509_NAME, buf: cstring, size: cInt): cstring{. cdecl, dynlib: DLLUtilName, importc.} - proc X509GetSubjectName*(a: PX509): PX509_NAME{.cdecl, dynlib: DLLUtilName, + proc X509GetSubjectName*(a: PX509): PX509_NAME{.cdecl, dynlib: DLLUtilName, importc.} - proc X509GetIssuerName*(a: PX509): PX509_NAME{.cdecl, dynlib: DLLUtilName, + proc X509GetIssuerName*(a: PX509): PX509_NAME{.cdecl, dynlib: DLLUtilName, importc.} proc X509NameHash*(x: PX509_NAME): int{.cdecl, dynlib: DLLUtilName, importc.} # function SslX509Digest(data: PX509; typ: PEVP_MD; md: PChar; len: PcInt):cInt; proc X509Digest*(data: PX509, typ: PEVP_MD, md: cstring, length: var cInt): cInt{. cdecl, dynlib: DLLUtilName, importc.} proc X509print*(b: PBIO, a: PX509): cInt{.cdecl, dynlib: DLLUtilName, importc.} - proc X509SetVersion*(x: PX509, version: cInt): cInt{.cdecl, dynlib: DLLUtilName, + proc X509SetVersion*(x: PX509, version: cInt): cInt{.cdecl, dynlib: DLLUtilName, importc.} - proc X509SetPubkey*(x: PX509, pkey: EVP_PKEY): cInt{.cdecl, dynlib: DLLUtilName, + proc X509SetPubkey*(x: PX509, pkey: EVP_PKEY): cInt{.cdecl, dynlib: DLLUtilName, importc.} - proc X509SetIssuerName*(x: PX509, name: PX509_NAME): cInt{.cdecl, + proc X509SetIssuerName*(x: PX509, name: PX509_NAME): cInt{.cdecl, dynlib: DLLUtilName, importc.} - proc X509NameAddEntryByTxt*(name: PX509_NAME, field: cstring, typ: cInt, + proc X509NameAddEntryByTxt*(name: PX509_NAME, field: cstring, typ: cInt, bytes: cstring, length, loc, theSet: cInt): cInt{. cdecl, dynlib: DLLUtilName, importc.} - proc X509Sign*(x: PX509, pkey: EVP_PKEY, md: PEVP_MD): cInt{.cdecl, + proc X509Sign*(x: PX509, pkey: EVP_PKEY, md: PEVP_MD): cInt{.cdecl, dynlib: DLLUtilName, importc.} - proc X509GmtimeAdj*(s: PASN1_UTCTIME, adj: cInt): PASN1_UTCTIME{.cdecl, + proc X509GmtimeAdj*(s: PASN1_UTCTIME, adj: cInt): PASN1_UTCTIME{.cdecl, dynlib: DLLUtilName, importc.} - proc X509SetNotBefore*(x: PX509, tm: PASN1_UTCTIME): cInt{.cdecl, + proc X509SetNotBefore*(x: PX509, tm: PASN1_UTCTIME): cInt{.cdecl, dynlib: DLLUtilName, importc.} - proc X509SetNotAfter*(x: PX509, tm: PASN1_UTCTIME): cInt{.cdecl, + proc X509SetNotAfter*(x: PX509, tm: PASN1_UTCTIME): cInt{.cdecl, dynlib: DLLUtilName, importc.} - proc X509GetSerialNumber*(x: PX509): PASN1_cInt{.cdecl, dynlib: DLLUtilName, + proc X509GetSerialNumber*(x: PX509): PASN1_cInt{.cdecl, dynlib: DLLUtilName, importc.} proc EvpPkeyNew*(): EVP_PKEY{.cdecl, dynlib: DLLUtilName, importc.} proc EvpPkeyFree*(pk: EVP_PKEY){.cdecl, dynlib: DLLUtilName, importc.} - proc EvpPkeyAssign*(pkey: EVP_PKEY, typ: cInt, key: Prsa): cInt{.cdecl, + proc EvpPkeyAssign*(pkey: EVP_PKEY, typ: cInt, key: Prsa): cInt{.cdecl, dynlib: DLLUtilName, importc.} - proc EvpGetDigestByName*(Name: cstring): PEVP_MD{.cdecl, dynlib: DLLUtilName, + proc EvpGetDigestByName*(Name: cstring): PEVP_MD{.cdecl, dynlib: DLLUtilName, importc.} proc EVPcleanup*(){.cdecl, dynlib: DLLUtilName, importc.} # function ErrErrorString(e: cInt; buf: PChar): PChar; @@ -475,7 +445,7 @@ else: proc CRYPTOcleanupAllExData*(){.cdecl, dynlib: DLLUtilName, importc.} proc RandScreen*(){.cdecl, dynlib: DLLUtilName, importc.} - proc d2iPKCS12bio*(b: PBIO, Pkcs12: SslPtr): SslPtr{.cdecl, dynlib: DLLUtilName, + proc d2iPKCS12bio*(b: PBIO, Pkcs12: SslPtr): SslPtr{.cdecl, dynlib: DLLUtilName, importc.} proc PKCS12parse*(p12: SslPtr, pass: cstring, pkey, cert, ca: var SslPtr): cint{. dynlib: DLLUtilName, importc, cdecl.} @@ -485,37 +455,37 @@ else: cdecl, dynlib: DLLUtilName, importc.} proc Asn1UtctimeNew*(): PASN1_UTCTIME{.cdecl, dynlib: DLLUtilName, importc.} proc Asn1UtctimeFree*(a: PASN1_UTCTIME){.cdecl, dynlib: DLLUtilName, importc.} - proc Asn1cIntSet*(a: PASN1_cInt, v: cInt): cInt{.cdecl, dynlib: DLLUtilName, + proc Asn1cIntSet*(a: PASN1_cInt, v: cInt): cInt{.cdecl, dynlib: DLLUtilName, importc.} proc i2dX509bio*(b: PBIO, x: PX509): cInt{.cdecl, dynlib: DLLUtilName, importc.} - proc i2dPrivateKeyBio*(b: PBIO, pkey: EVP_PKEY): cInt{.cdecl, + proc i2dPrivateKeyBio*(b: PBIO, pkey: EVP_PKEY): cInt{.cdecl, dynlib: DLLUtilName, importc.} # 3DES functions proc DESsetoddparity*(Key: des_cblock){.cdecl, dynlib: DLLUtilName, importc.} proc DESsetkeychecked*(key: des_cblock, schedule: des_key_schedule): cInt{. cdecl, dynlib: DLLUtilName, importc.} - proc DESecbencrypt*(Input: des_cblock, output: des_cblock, ks: des_key_schedule, + proc DESecbencrypt*(Input: des_cblock, output: des_cblock, ks: des_key_schedule, enc: cInt){.cdecl, dynlib: DLLUtilName, importc.} # implementation - proc SSLSetMode(s: PSSL, mode: int): int = + proc SSLSetMode(s: PSSL, mode: int): int = result = SSLctrl(s, SSL_CTRL_MODE, mode, nil) - proc SSLCTXGetMode(ctx: PSSL_CTX): int = + proc SSLCTXGetMode(ctx: PSSL_CTX): int = result = SSLCTXctrl(ctx, SSL_CTRL_MODE, 0, nil) - proc SSLGetMode(s: PSSL): int = + proc SSLGetMode(s: PSSL): int = result = SSLctrl(s, SSL_CTRL_MODE, 0, nil) # -type +type MD5_LONG* = cuint -const +const MD5_CBLOCK* = 64 MD5_LBLOCK* = int(MD5_CBLOCK div 4) MD5_DIGEST_LENGTH* = 16 -type - MD5_CTX* = object +type + MD5_CTX* = object A,B,C,D,Nl,Nh: MD5_LONG data: array[MD5_LBLOCK, MD5_LONG] num: cuint @@ -532,7 +502,7 @@ proc md5_Transform*(c: var MD5_CTX; b: ptr cuchar){.ic.} from strutils import toHex,toLower proc hexStr (buf:cstring): string = - # turn md5s output into a nice hex str + # turn md5s output into a nice hex str result = newStringOfCap(32) for i in 0 .. <16: result.add toHex(buf[i].ord, 2).toLower @@ -554,13 +524,13 @@ proc md5_File* (file: string): string {.raises: [IOError,Exception].} = discard md5_final( buf[0].addr, ctx ) f.close - + result = hexStr(buf) proc md5_Str* (str:string): string {.raises:[IOError].} = ##Generate MD5 hash for a string. Result is a 32 character #hex string with lowercase characters - var + var ctx: MD5_CTX res: array[MD5_DIGEST_LENGTH,char] input = str.cstring diff --git a/lib/wrappers/pcre.nim b/lib/wrappers/pcre.nim index 67436f026..4b6acce01 100644 --- a/lib/wrappers/pcre.nim +++ b/lib/wrappers/pcre.nim @@ -1,38 +1,11 @@ -#************************************************ -# Perl-Compatible Regular Expressions * -#************************************************ -# This is the public header file for the PCRE library, to be #included by -# applications that call the PCRE functions. # -# Copyright (c) 1997-2014 University of Cambridge # -#----------------------------------------------------------------------------- -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: +# Nim's Runtime Library +# (c) Copyright 2015 Andreas Rumpf # -# * Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. +# See the file "copying.txt", included in this +# distribution, for details about the copyright. # -# * Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# -# * Neither the name of the University of Cambridge nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. -#----------------------------------------------------------------------------- {.deadCodeElim: on.} @@ -77,9 +50,9 @@ const # C4 Affects compile, exec, dfa_exec, study # C5 Affects compile, exec, study # -# Options that can be set for pcre_exec() and/or pcre_dfa_exec() are flagged -# with E and D, respectively. They take precedence over C3, C4, and C5 settings -# passed from pcre_compile(). Those that are compatible with JIT execution are +# Options that can be set for pcre_exec() and/or pcre_dfa_exec() are flagged +# with E and D, respectively. They take precedence over C3, C4, and C5 settings +# passed from pcre_compile(). Those that are compatible with JIT execution are # flagged with J. const diff --git a/lib/wrappers/pdcurses.nim b/lib/wrappers/pdcurses.nim index 7e7a6c47f..74993c515 100644 --- a/lib/wrappers/pdcurses.nim +++ b/lib/wrappers/pdcurses.nim @@ -1,3 +1,12 @@ +# +# +# Nim's Runtime Library +# (c) Copyright 2015 Andreas Rumpf +# +# See the file "copying.txt", included in this +# distribution, for details about the copyright. +# + {.deadCodeElim: on.} discard """ @@ -32,7 +41,7 @@ pdcwin.h: when defined(windows): import windows - + const pdcursesdll = "pdcurses.dll" unixOS = false @@ -47,13 +56,13 @@ type cunsignedchar = char cunsignedlong = uint32 -const +const BUILD* = 3401 - PDCURSES* = 1 # PDCurses-only routines - XOPEN* = 1 # X/Open Curses routines - SYSVcurses* = 1 # System V Curses routines - BSDcurses* = 1 # BSD Curses routines - CHTYPE_LONG* = 1 # size of chtype; long + PDCURSES* = 1 # PDCurses-only routines + XOPEN* = 1 # X/Open Curses routines + SYSVcurses* = 1 # System V Curses routines + BSDcurses* = 1 # BSD Curses routines + CHTYPE_LONG* = 1 # size of chtype; long ERR* = (- 1) OK* = 0 BUTTON_RELEASED* = 0x00000000 @@ -61,10 +70,10 @@ const BUTTON_CLICKED* = 0x00000002 BUTTON_DOUBLE_CLICKED* = 0x00000003 BUTTON_TRIPLE_CLICKED* = 0x00000004 - BUTTON_MOVED* = 0x00000005 # PDCurses - WHEEL_SCROLLED* = 0x00000006 # PDCurses - BUTTON_ACTION_MASK* = 0x00000007 # PDCurses - BUTTON_MODIFIER_MASK* = 0x00000038 # PDCurses + BUTTON_MOVED* = 0x00000005 # PDCurses + WHEEL_SCROLLED* = 0x00000006 # PDCurses + BUTTON_ACTION_MASK* = 0x00000007 # PDCurses + BUTTON_MODIFIER_MASK* = 0x00000038 # PDCurses MOUSE_MOVED* = 0x00000008 MOUSE_POSITION* = 0x00000010 MOUSE_WHEEL_UP* = 0x00000020 @@ -74,19 +83,19 @@ const BUTTON1_CLICKED* = 0x00000004 BUTTON1_DOUBLE_CLICKED* = 0x00000008 BUTTON1_TRIPLE_CLICKED* = 0x00000010 - BUTTON1_MOVED* = 0x00000010 # PDCurses + BUTTON1_MOVED* = 0x00000010 # PDCurses BUTTON2_RELEASED* = 0x00000020 BUTTON2_PRESSED* = 0x00000040 BUTTON2_CLICKED* = 0x00000080 BUTTON2_DOUBLE_CLICKED* = 0x00000100 BUTTON2_TRIPLE_CLICKED* = 0x00000200 - BUTTON2_MOVED* = 0x00000200 # PDCurses + BUTTON2_MOVED* = 0x00000200 # PDCurses BUTTON3_RELEASED* = 0x00000400 BUTTON3_PRESSED* = 0x00000800 BUTTON3_CLICKED* = 0x00001000 BUTTON3_DOUBLE_CLICKED* = 0x00002000 BUTTON3_TRIPLE_CLICKED* = 0x00004000 - BUTTON3_MOVED* = 0x00004000 # PDCurses + BUTTON3_MOVED* = 0x00004000 # PDCurses BUTTON4_RELEASED* = 0x00008000 BUTTON4_PRESSED* = 0x00010000 BUTTON4_CLICKED* = 0x00020000 @@ -97,10 +106,10 @@ const BUTTON5_CLICKED* = 0x00400000 BUTTON5_DOUBLE_CLICKED* = 0x00800000 BUTTON5_TRIPLE_CLICKED* = 0x01000000 - MOUSE_WHEEL_SCROLL* = 0x02000000 # PDCurses - BUTTON_MODIFIER_SHIFT* = 0x04000000 # PDCurses - BUTTON_MODIFIER_CONTROL* = 0x08000000 # PDCurses - BUTTON_MODIFIER_ALT* = 0x10000000 # PDCurses + MOUSE_WHEEL_SCROLL* = 0x02000000 # PDCurses + BUTTON_MODIFIER_SHIFT* = 0x04000000 # PDCurses + BUTTON_MODIFIER_CONTROL* = 0x08000000 # PDCurses + BUTTON_MODIFIER_ALT* = 0x10000000 # PDCurses ALL_MOUSE_EVENTS* = 0x1FFFFFFF REPORT_MOUSE_POSITION* = 0x20000000 A_NORMAL* = 0 @@ -119,11 +128,11 @@ const A_PROTECT* = (A_UNDERLINE or A_LEFTLINE or A_RIGHTLINE) ATTR_SHIFT* = 19 COLOR_SHIFT* = 24 - A_STANDOUT* = (A_REVERSE or A_BOLD) # X/Open + A_STANDOUT* = (A_REVERSE or A_BOLD) # X/Open A_DIM* = A_NORMAL - CHR_MSK* = A_CHARTEXT # Obsolete - ATR_MSK* = A_ATTRIBUTES # Obsolete - ATR_NRM* = A_NORMAL # Obsolete + CHR_MSK* = A_CHARTEXT # Obsolete + ATR_MSK* = A_ATTRIBUTES # Obsolete + ATR_NRM* = A_NORMAL # Obsolete WA_ALTCHARSET* = A_ALTCHARSET WA_BLINK* = A_BLINK WA_BOLD* = A_BOLD @@ -147,93 +156,93 @@ const COLOR_MAGENTA* = (COLOR_RED or COLOR_BLUE) COLOR_YELLOW* = (COLOR_RED or COLOR_GREEN) COLOR_WHITE* = 7 - KEY_CODE_YES* = 0x00000100 # If get_wch() gives a key code - KEY_BREAK* = 0x00000101 # Not on PC KBD - KEY_DOWN* = 0x00000102 # Down arrow key - KEY_UP* = 0x00000103 # Up arrow key - KEY_LEFT* = 0x00000104 # Left arrow key - KEY_RIGHT* = 0x00000105 # Right arrow key - KEY_HOME* = 0x00000106 # home key - KEY_BACKSPACE* = 0x00000107 # not on pc - KEY_F0* = 0x00000108 # function keys; 64 reserved - KEY_DL* = 0x00000148 # delete line - KEY_IL* = 0x00000149 # insert line - KEY_DC* = 0x0000014A # delete character - KEY_IC* = 0x0000014B # insert char or enter ins mode - KEY_EIC* = 0x0000014C # exit insert char mode - KEY_CLEAR* = 0x0000014D # clear screen - KEY_EOS* = 0x0000014E # clear to end of screen - KEY_EOL* = 0x0000014F # clear to end of line - KEY_SF* = 0x00000150 # scroll 1 line forward - KEY_SR* = 0x00000151 # scroll 1 line back (reverse) - KEY_NPAGE* = 0x00000152 # next page - KEY_PPAGE* = 0x00000153 # previous page - KEY_STAB* = 0x00000154 # set tab - KEY_CTAB* = 0x00000155 # clear tab - KEY_CATAB* = 0x00000156 # clear all tabs - KEY_ENTER* = 0x00000157 # enter or send (unreliable) - KEY_SRESET* = 0x00000158 # soft/reset (partial/unreliable) - KEY_RESET* = 0x00000159 # reset/hard reset (unreliable) - KEY_PRINT* = 0x0000015A # print/copy - KEY_LL* = 0x0000015B # home down/bottom (lower left) - KEY_ABORT* = 0x0000015C # abort/terminate key (any) - KEY_SHELP* = 0x0000015D # short help - KEY_LHELP* = 0x0000015E # long help - KEY_BTAB* = 0x0000015F # Back tab key - KEY_BEG* = 0x00000160 # beg(inning) key - KEY_CANCEL* = 0x00000161 # cancel key - KEY_CLOSE* = 0x00000162 # close key - KEY_COMMAND* = 0x00000163 # cmd (command) key - KEY_COPY* = 0x00000164 # copy key - KEY_CREATE* = 0x00000165 # create key - KEY_END* = 0x00000166 # end key - KEY_EXIT* = 0x00000167 # exit key - KEY_FIND* = 0x00000168 # find key - KEY_HELP* = 0x00000169 # help key - KEY_MARK* = 0x0000016A # mark key - KEY_MESSAGE* = 0x0000016B # message key - KEY_MOVE* = 0x0000016C # move key - KEY_NEXT* = 0x0000016D # next object key - KEY_OPEN* = 0x0000016E # open key - KEY_OPTIONS* = 0x0000016F # options key - KEY_PREVIOUS* = 0x00000170 # previous object key - KEY_REDO* = 0x00000171 # redo key - KEY_REFERENCE* = 0x00000172 # ref(erence) key - KEY_REFRESH* = 0x00000173 # refresh key - KEY_REPLACE* = 0x00000174 # replace key - KEY_RESTART* = 0x00000175 # restart key - KEY_RESUME* = 0x00000176 # resume key - KEY_SAVE* = 0x00000177 # save key - KEY_SBEG* = 0x00000178 # shifted beginning key - KEY_SCANCEL* = 0x00000179 # shifted cancel key - KEY_SCOMMAND* = 0x0000017A # shifted command key - KEY_SCOPY* = 0x0000017B # shifted copy key - KEY_SCREATE* = 0x0000017C # shifted create key - KEY_SDC* = 0x0000017D # shifted delete char key - KEY_SDL* = 0x0000017E # shifted delete line key - KEY_SELECT* = 0x0000017F # select key - KEY_SEND* = 0x00000180 # shifted end key - KEY_SEOL* = 0x00000181 # shifted clear line key - KEY_SEXIT* = 0x00000182 # shifted exit key - KEY_SFIND* = 0x00000183 # shifted find key - KEY_SHOME* = 0x00000184 # shifted home key - KEY_SIC* = 0x00000185 # shifted input key - KEY_SLEFT* = 0x00000187 # shifted left arrow key - KEY_SMESSAGE* = 0x00000188 # shifted message key - KEY_SMOVE* = 0x00000189 # shifted move key - KEY_SNEXT* = 0x0000018A # shifted next key - KEY_SOPTIONS* = 0x0000018B # shifted options key - KEY_SPREVIOUS* = 0x0000018C # shifted prev key - KEY_SPRINT* = 0x0000018D # shifted print key - KEY_SREDO* = 0x0000018E # shifted redo key - KEY_SREPLACE* = 0x0000018F # shifted replace key - KEY_SRIGHT* = 0x00000190 # shifted right arrow - KEY_SRSUME* = 0x00000191 # shifted resume key - KEY_SSAVE* = 0x00000192 # shifted save key - KEY_SSUSPEND* = 0x00000193 # shifted suspend key - KEY_SUNDO* = 0x00000194 # shifted undo key - KEY_SUSPEND* = 0x00000195 # suspend key - KEY_UNDO* = 0x00000196 # undo key + KEY_CODE_YES* = 0x00000100 # If get_wch() gives a key code + KEY_BREAK* = 0x00000101 # Not on PC KBD + KEY_DOWN* = 0x00000102 # Down arrow key + KEY_UP* = 0x00000103 # Up arrow key + KEY_LEFT* = 0x00000104 # Left arrow key + KEY_RIGHT* = 0x00000105 # Right arrow key + KEY_HOME* = 0x00000106 # home key + KEY_BACKSPACE* = 0x00000107 # not on pc + KEY_F0* = 0x00000108 # function keys; 64 reserved + KEY_DL* = 0x00000148 # delete line + KEY_IL* = 0x00000149 # insert line + KEY_DC* = 0x0000014A # delete character + KEY_IC* = 0x0000014B # insert char or enter ins mode + KEY_EIC* = 0x0000014C # exit insert char mode + KEY_CLEAR* = 0x0000014D # clear screen + KEY_EOS* = 0x0000014E # clear to end of screen + KEY_EOL* = 0x0000014F # clear to end of line + KEY_SF* = 0x00000150 # scroll 1 line forward + KEY_SR* = 0x00000151 # scroll 1 line back (reverse) + KEY_NPAGE* = 0x00000152 # next page + KEY_PPAGE* = 0x00000153 # previous page + KEY_STAB* = 0x00000154 # set tab + KEY_CTAB* = 0x00000155 # clear tab + KEY_CATAB* = 0x00000156 # clear all tabs + KEY_ENTER* = 0x00000157 # enter or send (unreliable) + KEY_SRESET* = 0x00000158 # soft/reset (partial/unreliable) + KEY_RESET* = 0x00000159 # reset/hard reset (unreliable) + KEY_PRINT* = 0x0000015A # print/copy + KEY_LL* = 0x0000015B # home down/bottom (lower left) + KEY_ABORT* = 0x0000015C # abort/terminate key (any) + KEY_SHELP* = 0x0000015D # short help + KEY_LHELP* = 0x0000015E # long help + KEY_BTAB* = 0x0000015F # Back tab key + KEY_BEG* = 0x00000160 # beg(inning) key + KEY_CANCEL* = 0x00000161 # cancel key + KEY_CLOSE* = 0x00000162 # close key + KEY_COMMAND* = 0x00000163 # cmd (command) key + KEY_COPY* = 0x00000164 # copy key + KEY_CREATE* = 0x00000165 # create key + KEY_END* = 0x00000166 # end key + KEY_EXIT* = 0x00000167 # exit key + KEY_FIND* = 0x00000168 # find key + KEY_HELP* = 0x00000169 # help key + KEY_MARK* = 0x0000016A # mark key + KEY_MESSAGE* = 0x0000016B # message key + KEY_MOVE* = 0x0000016C # move key + KEY_NEXT* = 0x0000016D # next object key + KEY_OPEN* = 0x0000016E # open key + KEY_OPTIONS* = 0x0000016F # options key + KEY_PREVIOUS* = 0x00000170 # previous object key + KEY_REDO* = 0x00000171 # redo key + KEY_REFERENCE* = 0x00000172 # ref(erence) key + KEY_REFRESH* = 0x00000173 # refresh key + KEY_REPLACE* = 0x00000174 # replace key + KEY_RESTART* = 0x00000175 # restart key + KEY_RESUME* = 0x00000176 # resume key + KEY_SAVE* = 0x00000177 # save key + KEY_SBEG* = 0x00000178 # shifted beginning key + KEY_SCANCEL* = 0x00000179 # shifted cancel key + KEY_SCOMMAND* = 0x0000017A # shifted command key + KEY_SCOPY* = 0x0000017B # shifted copy key + KEY_SCREATE* = 0x0000017C # shifted create key + KEY_SDC* = 0x0000017D # shifted delete char key + KEY_SDL* = 0x0000017E # shifted delete line key + KEY_SELECT* = 0x0000017F # select key + KEY_SEND* = 0x00000180 # shifted end key + KEY_SEOL* = 0x00000181 # shifted clear line key + KEY_SEXIT* = 0x00000182 # shifted exit key + KEY_SFIND* = 0x00000183 # shifted find key + KEY_SHOME* = 0x00000184 # shifted home key + KEY_SIC* = 0x00000185 # shifted input key + KEY_SLEFT* = 0x00000187 # shifted left arrow key + KEY_SMESSAGE* = 0x00000188 # shifted message key + KEY_SMOVE* = 0x00000189 # shifted move key + KEY_SNEXT* = 0x0000018A # shifted next key + KEY_SOPTIONS* = 0x0000018B # shifted options key + KEY_SPREVIOUS* = 0x0000018C # shifted prev key + KEY_SPRINT* = 0x0000018D # shifted print key + KEY_SREDO* = 0x0000018E # shifted redo key + KEY_SREPLACE* = 0x0000018F # shifted replace key + KEY_SRIGHT* = 0x00000190 # shifted right arrow + KEY_SRSUME* = 0x00000191 # shifted resume key + KEY_SSAVE* = 0x00000192 # shifted save key + KEY_SSUSPEND* = 0x00000193 # shifted suspend key + KEY_SUNDO* = 0x00000194 # shifted undo key + KEY_SUSPEND* = 0x00000195 # suspend key + KEY_UNDO* = 0x00000196 # undo key ALT_0* = 0x00000197 ALT_1* = 0x00000198 ALT_2* = 0x00000199 @@ -270,46 +279,46 @@ const ALT_X* = 0x000001B8 ALT_Y* = 0x000001B9 ALT_Z* = 0x000001BA - CTL_LEFT* = 0x000001BB # Control-Left-Arrow + CTL_LEFT* = 0x000001BB # Control-Left-Arrow CTL_RIGHT* = 0x000001BC CTL_PGUP* = 0x000001BD CTL_PGDN* = 0x000001BE CTL_HOME* = 0x000001BF CTL_END* = 0x000001C0 - KEY_A1* = 0x000001C1 # upper left on Virtual keypad - KEY_A2* = 0x000001C2 # upper middle on Virt. keypad - KEY_A3* = 0x000001C3 # upper right on Vir. keypad - KEY_B1* = 0x000001C4 # middle left on Virt. keypad - KEY_B2* = 0x000001C5 # center on Virt. keypad - KEY_B3* = 0x000001C6 # middle right on Vir. keypad - KEY_C1* = 0x000001C7 # lower left on Virt. keypad - KEY_C2* = 0x000001C8 # lower middle on Virt. keypad - KEY_C3* = 0x000001C9 # lower right on Vir. keypad - PADSLASH* = 0x000001CA # slash on keypad - PADENTER* = 0x000001CB # enter on keypad - CTL_PADENTER* = 0x000001CC # ctl-enter on keypad - ALT_PADENTER* = 0x000001CD # alt-enter on keypad - PADSTOP* = 0x000001CE # stop on keypad - PADSTAR* = 0x000001CF # star on keypad - PADMINUS* = 0x000001D0 # minus on keypad - PADPLUS* = 0x000001D1 # plus on keypad - CTL_PADSTOP* = 0x000001D2 # ctl-stop on keypad - CTL_PADCENTER* = 0x000001D3 # ctl-enter on keypad - CTL_PADPLUS* = 0x000001D4 # ctl-plus on keypad - CTL_PADMINUS* = 0x000001D5 # ctl-minus on keypad - CTL_PADSLASH* = 0x000001D6 # ctl-slash on keypad - CTL_PADSTAR* = 0x000001D7 # ctl-star on keypad - ALT_PADPLUS* = 0x000001D8 # alt-plus on keypad - ALT_PADMINUS* = 0x000001D9 # alt-minus on keypad - ALT_PADSLASH* = 0x000001DA # alt-slash on keypad - ALT_PADSTAR* = 0x000001DB # alt-star on keypad - ALT_PADSTOP* = 0x000001DC # alt-stop on keypad - CTL_INS* = 0x000001DD # ctl-insert - ALT_DEL* = 0x000001DE # alt-delete - ALT_INS* = 0x000001DF # alt-insert - CTL_UP* = 0x000001E0 # ctl-up arrow - CTL_DOWN* = 0x000001E1 # ctl-down arrow - CTL_TAB* = 0x000001E2 # ctl-tab + KEY_A1* = 0x000001C1 # upper left on Virtual keypad + KEY_A2* = 0x000001C2 # upper middle on Virt. keypad + KEY_A3* = 0x000001C3 # upper right on Vir. keypad + KEY_B1* = 0x000001C4 # middle left on Virt. keypad + KEY_B2* = 0x000001C5 # center on Virt. keypad + KEY_B3* = 0x000001C6 # middle right on Vir. keypad + KEY_C1* = 0x000001C7 # lower left on Virt. keypad + KEY_C2* = 0x000001C8 # lower middle on Virt. keypad + KEY_C3* = 0x000001C9 # lower right on Vir. keypad + PADSLASH* = 0x000001CA # slash on keypad + PADENTER* = 0x000001CB # enter on keypad + CTL_PADENTER* = 0x000001CC # ctl-enter on keypad + ALT_PADENTER* = 0x000001CD # alt-enter on keypad + PADSTOP* = 0x000001CE # stop on keypad + PADSTAR* = 0x000001CF # star on keypad + PADMINUS* = 0x000001D0 # minus on keypad + PADPLUS* = 0x000001D1 # plus on keypad + CTL_PADSTOP* = 0x000001D2 # ctl-stop on keypad + CTL_PADCENTER* = 0x000001D3 # ctl-enter on keypad + CTL_PADPLUS* = 0x000001D4 # ctl-plus on keypad + CTL_PADMINUS* = 0x000001D5 # ctl-minus on keypad + CTL_PADSLASH* = 0x000001D6 # ctl-slash on keypad + CTL_PADSTAR* = 0x000001D7 # ctl-star on keypad + ALT_PADPLUS* = 0x000001D8 # alt-plus on keypad + ALT_PADMINUS* = 0x000001D9 # alt-minus on keypad + ALT_PADSLASH* = 0x000001DA # alt-slash on keypad + ALT_PADSTAR* = 0x000001DB # alt-star on keypad + ALT_PADSTOP* = 0x000001DC # alt-stop on keypad + CTL_INS* = 0x000001DD # ctl-insert + ALT_DEL* = 0x000001DE # alt-delete + ALT_INS* = 0x000001DF # alt-insert + CTL_UP* = 0x000001E0 # ctl-up arrow + CTL_DOWN* = 0x000001E1 # ctl-down arrow + CTL_TAB* = 0x000001E2 # ctl-tab ALT_TAB* = 0x000001E3 ALT_MINUS* = 0x000001E4 ALT_EQUAL* = 0x000001E5 @@ -317,24 +326,24 @@ const ALT_PGUP* = 0x000001E7 ALT_PGDN* = 0x000001E8 ALT_END* = 0x000001E9 - ALT_UP* = 0x000001EA # alt-up arrow - ALT_DOWN* = 0x000001EB # alt-down arrow - ALT_RIGHT* = 0x000001EC # alt-right arrow - ALT_LEFT* = 0x000001ED # alt-left arrow - ALT_ENTER* = 0x000001EE # alt-enter - ALT_ESC* = 0x000001EF # alt-escape - ALT_BQUOTE* = 0x000001F0 # alt-back quote - ALT_LBRACKET* = 0x000001F1 # alt-left bracket - ALT_RBRACKET* = 0x000001F2 # alt-right bracket - ALT_SEMICOLON* = 0x000001F3 # alt-semi-colon - ALT_FQUOTE* = 0x000001F4 # alt-forward quote - ALT_COMMA* = 0x000001F5 # alt-comma - ALT_STOP* = 0x000001F6 # alt-stop - ALT_FSLASH* = 0x000001F7 # alt-forward slash - ALT_BKSP* = 0x000001F8 # alt-backspace - CTL_BKSP* = 0x000001F9 # ctl-backspace - PAD0* = 0x000001FA # keypad 0 - CTL_PAD0* = 0x000001FB # ctl-keypad 0 + ALT_UP* = 0x000001EA # alt-up arrow + ALT_DOWN* = 0x000001EB # alt-down arrow + ALT_RIGHT* = 0x000001EC # alt-right arrow + ALT_LEFT* = 0x000001ED # alt-left arrow + ALT_ENTER* = 0x000001EE # alt-enter + ALT_ESC* = 0x000001EF # alt-escape + ALT_BQUOTE* = 0x000001F0 # alt-back quote + ALT_LBRACKET* = 0x000001F1 # alt-left bracket + ALT_RBRACKET* = 0x000001F2 # alt-right bracket + ALT_SEMICOLON* = 0x000001F3 # alt-semi-colon + ALT_FQUOTE* = 0x000001F4 # alt-forward quote + ALT_COMMA* = 0x000001F5 # alt-comma + ALT_STOP* = 0x000001F6 # alt-stop + ALT_FSLASH* = 0x000001F7 # alt-forward slash + ALT_BKSP* = 0x000001F8 # alt-backspace + CTL_BKSP* = 0x000001F9 # ctl-backspace + PAD0* = 0x000001FA # keypad 0 + CTL_PAD0* = 0x000001FB # ctl-keypad 0 CTL_PAD1* = 0x000001FC CTL_PAD2* = 0x000001FD CTL_PAD3* = 0x000001FE @@ -344,7 +353,7 @@ const CTL_PAD7* = 0x00000202 CTL_PAD8* = 0x00000203 CTL_PAD9* = 0x00000204 - ALT_PAD0* = 0x00000205 # alt-keypad 0 + ALT_PAD0* = 0x00000205 # alt-keypad 0 ALT_PAD1* = 0x00000206 ALT_PAD2* = 0x00000207 ALT_PAD3* = 0x00000208 @@ -354,30 +363,30 @@ const ALT_PAD7* = 0x0000020C ALT_PAD8* = 0x0000020D ALT_PAD9* = 0x0000020E - CTL_DEL* = 0x0000020F # clt-delete - ALT_BSLASH* = 0x00000210 # alt-back slash - CTL_ENTER* = 0x00000211 # ctl-enter - SHF_PADENTER* = 0x00000212 # shift-enter on keypad - SHF_PADSLASH* = 0x00000213 # shift-slash on keypad - SHF_PADSTAR* = 0x00000214 # shift-star on keypad - SHF_PADPLUS* = 0x00000215 # shift-plus on keypad - SHF_PADMINUS* = 0x00000216 # shift-minus on keypad - SHF_UP* = 0x00000217 # shift-up on keypad - SHF_DOWN* = 0x00000218 # shift-down on keypad - SHF_IC* = 0x00000219 # shift-insert on keypad - SHF_DC* = 0x0000021A # shift-delete on keypad - KEY_MOUSE* = 0x0000021B # "mouse" key - KEY_SHIFT_L* = 0x0000021C # Left-shift - KEY_SHIFT_R* = 0x0000021D # Right-shift - KEY_CONTROL_L* = 0x0000021E # Left-control - KEY_CONTROL_R* = 0x0000021F # Right-control - KEY_ALT_L* = 0x00000220 # Left-alt - KEY_ALT_R* = 0x00000221 # Right-alt - KEY_RESIZE* = 0x00000222 # Window resize - KEY_SUP* = 0x00000223 # Shifted up arrow - KEY_SDOWN* = 0x00000224 # Shifted down arrow - KEY_MIN* = KEY_BREAK # Minimum curses key value - KEY_MAX* = KEY_SDOWN # Maximum curses key + CTL_DEL* = 0x0000020F # clt-delete + ALT_BSLASH* = 0x00000210 # alt-back slash + CTL_ENTER* = 0x00000211 # ctl-enter + SHF_PADENTER* = 0x00000212 # shift-enter on keypad + SHF_PADSLASH* = 0x00000213 # shift-slash on keypad + SHF_PADSTAR* = 0x00000214 # shift-star on keypad + SHF_PADPLUS* = 0x00000215 # shift-plus on keypad + SHF_PADMINUS* = 0x00000216 # shift-minus on keypad + SHF_UP* = 0x00000217 # shift-up on keypad + SHF_DOWN* = 0x00000218 # shift-down on keypad + SHF_IC* = 0x00000219 # shift-insert on keypad + SHF_DC* = 0x0000021A # shift-delete on keypad + KEY_MOUSE* = 0x0000021B # "mouse" key + KEY_SHIFT_L* = 0x0000021C # Left-shift + KEY_SHIFT_R* = 0x0000021D # Right-shift + KEY_CONTROL_L* = 0x0000021E # Left-control + KEY_CONTROL_R* = 0x0000021F # Right-control + KEY_ALT_L* = 0x00000220 # Left-alt + KEY_ALT_R* = 0x00000221 # Right-alt + KEY_RESIZE* = 0x00000222 # Window resize + KEY_SUP* = 0x00000223 # Shifted up arrow + KEY_SDOWN* = 0x00000224 # Shifted down arrow + KEY_MIN* = KEY_BREAK # Minimum curses key value + KEY_MAX* = KEY_SDOWN # Maximum curses key CLIP_SUCCESS* = 0 CLIP_ACCESS_ERROR* = 1 CLIP_EMPTY* = 2 @@ -394,58 +403,58 @@ when appType == "gui": BUTTON_CTRL* = BUTTON_MODIFIER_CONTROL BUTTON_ALT* = BUTTON_MODIFIER_ALT else: - const + const BUTTON_SHIFT* = 0x00000008 BUTTON_CONTROL* = 0x00000010 BUTTON_ALT* = 0x00000020 -type - TMOUSE_STATUS*{.pure, final.} = object - x*: cint # absolute column, 0 based, measured in characters - y*: cint # absolute row, 0 based, measured in characters - button*: array[0..3 - 1, cshort] # state of each button - changes*: cint # flags indicating what has changed with the mouse - - MEVENT*{.pure, final.} = object - id*: cshort # unused, always 0 +type + TMOUSE_STATUS*{.pure, final.} = object + x*: cint # absolute column, 0 based, measured in characters + y*: cint # absolute row, 0 based, measured in characters + button*: array[0..3 - 1, cshort] # state of each button + changes*: cint # flags indicating what has changed with the mouse + + MEVENT*{.pure, final.} = object + id*: cshort # unused, always 0 x*: cint y*: cint - z*: cint # x, y same as TMOUSE_STATUS; z unused + z*: cint # x, y same as TMOUSE_STATUS; z unused bstate*: cunsignedlong # equivalent to changes + button[], but - # in the same format as used for mousemask() - - WINDOW*{.pure, final.} = object - cury*: cint # current pseudo-cursor + # in the same format as used for mousemask() + + WINDOW*{.pure, final.} = object + cury*: cint # current pseudo-cursor curx*: cint - maxy*: cint # max window coordinates + maxy*: cint # max window coordinates maxx*: cint - begy*: cint # origin on screen + begy*: cint # origin on screen begx*: cint - flags*: cint # window properties - attrs*: cunsignedlong # standard attributes and colors - bkgd*: cunsignedlong # background, normally blank - clear*: cunsignedchar # causes clear at next refresh - leaveit*: cunsignedchar # leaves cursor where it is - scroll*: cunsignedchar # allows window scrolling - nodelay*: cunsignedchar # input character wait flag - immed*: cunsignedchar # immediate update flag - sync*: cunsignedchar # synchronise window ancestors - use_keypad*: cunsignedchar # flags keypad key mode active - y*: ptr ptr cunsignedlong # pointer to line pointer array - firstch*: ptr cint # first changed character in line - lastch*: ptr cint # last changed character in line - tmarg*: cint # top of scrolling region - bmarg*: cint # bottom of scrolling region - delayms*: cint # milliseconds of delay for getch() + flags*: cint # window properties + attrs*: cunsignedlong # standard attributes and colors + bkgd*: cunsignedlong # background, normally blank + clear*: cunsignedchar # causes clear at next refresh + leaveit*: cunsignedchar # leaves cursor where it is + scroll*: cunsignedchar # allows window scrolling + nodelay*: cunsignedchar # input character wait flag + immed*: cunsignedchar # immediate update flag + sync*: cunsignedchar # synchronise window ancestors + use_keypad*: cunsignedchar # flags keypad key mode active + y*: ptr ptr cunsignedlong # pointer to line pointer array + firstch*: ptr cint # first changed character in line + lastch*: ptr cint # last changed character in line + tmarg*: cint # top of scrolling region + bmarg*: cint # bottom of scrolling region + delayms*: cint # milliseconds of delay for getch() parx*: cint - pary*: cint # coords relative to parent (0,0) - parent*: ptr WINDOW # subwin's pointer to parent win - - PANELOBS*{.pure, final.} = object + pary*: cint # coords relative to parent (0,0) + parent*: ptr WINDOW # subwin's pointer to parent win + + PANELOBS*{.pure, final.} = object above*: ptr PANELOBS pan*: ptr PANEL - PANEL*{.pure, final.} = object + PANEL*{.pure, final.} = object win*: ptr WINDOW wstarty*: cint wendy*: cint @@ -462,39 +471,39 @@ type when unixOS: type - SCREEN*{.pure, final.} = object - alive*: cunsignedchar # if initscr() called, and not endwin() - autocr*: cunsignedchar # if cr -> lf - cbreak*: cunsignedchar # if terminal unbuffered - echo*: cunsignedchar # if terminal echo - raw_inp*: cunsignedchar # raw input mode (v. cooked input) - raw_out*: cunsignedchar # raw output mode (7 v. 8 bits) - audible*: cunsignedchar # FALSE if the bell is visual - mono*: cunsignedchar # TRUE if current screen is mono - resized*: cunsignedchar # TRUE if TERM has been resized - orig_attr*: cunsignedchar # TRUE if we have the original colors - orig_fore*: cshort # original screen foreground color - orig_back*: cshort # original screen foreground color - cursrow*: cint # position of physical cursor - curscol*: cint # position of physical cursor - visibility*: cint # visibility of cursor - orig_cursor*: cint # original cursor size - lines*: cint # new value for LINES - cols*: cint # new value for COLS - trap_mbe*: cunsignedlong # trap these mouse button events - map_mbe_to_key*: cunsignedlong # map mouse buttons to slk + SCREEN*{.pure, final.} = object + alive*: cunsignedchar # if initscr() called, and not endwin() + autocr*: cunsignedchar # if cr -> lf + cbreak*: cunsignedchar # if terminal unbuffered + echo*: cunsignedchar # if terminal echo + raw_inp*: cunsignedchar # raw input mode (v. cooked input) + raw_out*: cunsignedchar # raw output mode (7 v. 8 bits) + audible*: cunsignedchar # FALSE if the bell is visual + mono*: cunsignedchar # TRUE if current screen is mono + resized*: cunsignedchar # TRUE if TERM has been resized + orig_attr*: cunsignedchar # TRUE if we have the original colors + orig_fore*: cshort # original screen foreground color + orig_back*: cshort # original screen foreground color + cursrow*: cint # position of physical cursor + curscol*: cint # position of physical cursor + visibility*: cint # visibility of cursor + orig_cursor*: cint # original cursor size + lines*: cint # new value for LINES + cols*: cint # new value for COLS + trap_mbe*: cunsignedlong # trap these mouse button events + map_mbe_to_key*: cunsignedlong # map mouse buttons to slk mouse_wait*: cint # time to wait (in ms) for a button release after a press - slklines*: cint # lines in use by slk_init() - slk_winptr*: ptr WINDOW # window for slk - linesrippedoff*: cint # lines ripped off via ripoffline() - linesrippedoffontop*: cint # lines ripped off on top via ripoffline() - delaytenths*: cint # 1/10ths second to wait block getch() for - preserve*: cunsignedchar # TRUE if screen background to be preserved - restore*: cint # specifies if screen background to be restored, and how - save_key_modifiers*: cunsignedchar # TRUE if each key modifiers saved with each key press - return_key_modifiers*: cunsignedchar # TRUE if modifier keys are returned as "real" keys + slklines*: cint # lines in use by slk_init() + slk_winptr*: ptr WINDOW # window for slk + linesrippedoff*: cint # lines ripped off via ripoffline() + linesrippedoffontop*: cint # lines ripped off on top via ripoffline() + delaytenths*: cint # 1/10ths second to wait block getch() for + preserve*: cunsignedchar # TRUE if screen background to be preserved + restore*: cint # specifies if screen background to be restored, and how + save_key_modifiers*: cunsignedchar # TRUE if each key modifiers saved with each key press + return_key_modifiers*: cunsignedchar # TRUE if modifier keys are returned as "real" keys key_code*: cunsignedchar # TRUE if last key is a special key; - XcurscrSize*: cint # size of Xcurscr shared memory block + XcurscrSize*: cint # size of Xcurscr shared memory block sb_on*: cunsignedchar sb_viewport_y*: cint sb_viewport_x*: cint @@ -502,43 +511,43 @@ when unixOS: sb_total_x*: cint sb_cur_y*: cint sb_cur_x*: cint - line_color*: cshort # color of line attributes - default -1 + line_color*: cshort # color of line attributes - default -1 {.deprecated: [TSCREEN: SCREEN].} else: type - SCREEN*{.pure, final.} = object - alive*: cunsignedchar # if initscr() called, and not endwin() - autocr*: cunsignedchar # if cr -> lf - cbreak*: cunsignedchar # if terminal unbuffered - echo*: cunsignedchar # if terminal echo - raw_inp*: cunsignedchar # raw input mode (v. cooked input) - raw_out*: cunsignedchar # raw output mode (7 v. 8 bits) - audible*: cunsignedchar # FALSE if the bell is visual - mono*: cunsignedchar # TRUE if current screen is mono - resized*: cunsignedchar # TRUE if TERM has been resized - orig_attr*: cunsignedchar # TRUE if we have the original colors - orig_fore*: cshort # original screen foreground color - orig_back*: cshort # original screen foreground color - cursrow*: cint # position of physical cursor - curscol*: cint # position of physical cursor - visibility*: cint # visibility of cursor - orig_cursor*: cint # original cursor size - lines*: cint # new value for LINES - cols*: cint # new value for COLS - trap_mbe*: cunsignedlong # trap these mouse button events - map_mbe_to_key*: cunsignedlong # map mouse buttons to slk + SCREEN*{.pure, final.} = object + alive*: cunsignedchar # if initscr() called, and not endwin() + autocr*: cunsignedchar # if cr -> lf + cbreak*: cunsignedchar # if terminal unbuffered + echo*: cunsignedchar # if terminal echo + raw_inp*: cunsignedchar # raw input mode (v. cooked input) + raw_out*: cunsignedchar # raw output mode (7 v. 8 bits) + audible*: cunsignedchar # FALSE if the bell is visual + mono*: cunsignedchar # TRUE if current screen is mono + resized*: cunsignedchar # TRUE if TERM has been resized + orig_attr*: cunsignedchar # TRUE if we have the original colors + orig_fore*: cshort # original screen foreground color + orig_back*: cshort # original screen foreground color + cursrow*: cint # position of physical cursor + curscol*: cint # position of physical cursor + visibility*: cint # visibility of cursor + orig_cursor*: cint # original cursor size + lines*: cint # new value for LINES + cols*: cint # new value for COLS + trap_mbe*: cunsignedlong # trap these mouse button events + map_mbe_to_key*: cunsignedlong # map mouse buttons to slk mouse_wait*: cint # time to wait (in ms) for a button release after a press - slklines*: cint # lines in use by slk_init() - slk_winptr*: ptr WINDOW # window for slk - linesrippedoff*: cint # lines ripped off via ripoffline() - linesrippedoffontop*: cint # lines ripped off on top via ripoffline() - delaytenths*: cint # 1/10ths second to wait block getch() for - preserve*: cunsignedchar # TRUE if screen background to be preserved - restore*: cint # specifies if screen background to be restored, and how - save_key_modifiers*: cunsignedchar # TRUE if each key modifiers saved with each key press - return_key_modifiers*: cunsignedchar # TRUE if modifier keys are returned as "real" keys + slklines*: cint # lines in use by slk_init() + slk_winptr*: ptr WINDOW # window for slk + linesrippedoff*: cint # lines ripped off via ripoffline() + linesrippedoffontop*: cint # lines ripped off on top via ripoffline() + delaytenths*: cint # 1/10ths second to wait block getch() for + preserve*: cunsignedchar # TRUE if screen background to be preserved + restore*: cint # specifies if screen background to be restored, and how + save_key_modifiers*: cunsignedchar # TRUE if each key modifiers saved with each key press + return_key_modifiers*: cunsignedchar # TRUE if modifier keys are returned as "real" keys key_code*: cunsignedchar # TRUE if last key is a special key; - line_color*: cshort # color of line attributes - default -1 + line_color*: cshort # color of line attributes - default -1 {.deprecated: [TSCREEN: SCREEN].} var @@ -554,20 +563,20 @@ var acs_map*{.importc: "acs_map", dynlib: pdcursesdll.}: ptr cunsignedlong ttytype*{.importc: "ttytype", dynlib: pdcursesdll.}: cstring -template BUTTON_CHANGED*(x: expr): expr = +template BUTTON_CHANGED*(x: expr): expr = (Mouse_status.changes and (1 shl ((x) - 1))) -template BUTTON_STATUS*(x: expr): expr = +template BUTTON_STATUS*(x: expr): expr = (Mouse_status.button[(x) - 1]) template ACS_PICK*(w, n: expr): expr = int32(w) or A_ALTCHARSET template KEY_F*(n: expr): expr = KEY_F0 + n -template COLOR_PAIR*(n: expr): expr = +template COLOR_PAIR*(n: expr): expr = ((cunsignedlong(n) shl COLOR_SHIFT) and A_COLOR) -template PAIR_NUMBER*(n: expr): expr = +template PAIR_NUMBER*(n: expr): expr = (((n) and A_COLOR) shr COLOR_SHIFT) const @@ -665,75 +674,75 @@ discard """WACS_ULCORNER* = (addr((acs_map['l']))) WACS_SBSB* = WACS_VLINE WACS_SSSS* = WACS_PLUS""" -proc addch*(a2: cunsignedlong): cint{.extdecl, importc: "addch", +proc addch*(a2: cunsignedlong): cint{.extdecl, importc: "addch", dynlib: pdcursesdll.} -proc addchnstr*(a2: ptr cunsignedlong; a3: cint): cint{.extdecl, +proc addchnstr*(a2: ptr cunsignedlong; a3: cint): cint{.extdecl, importc: "addchnstr", dynlib: pdcursesdll.} -proc addchstr*(a2: ptr cunsignedlong): cint{.extdecl, importc: "addchstr", +proc addchstr*(a2: ptr cunsignedlong): cint{.extdecl, importc: "addchstr", dynlib: pdcursesdll.} -proc addnstr*(a2: cstring; a3: cint): cint{.extdecl, importc: "addnstr", +proc addnstr*(a2: cstring; a3: cint): cint{.extdecl, importc: "addnstr", dynlib: pdcursesdll.} proc addstr*(a2: cstring): cint{.extdecl, importc: "addstr", dynlib: pdcursesdll.} -proc attroff*(a2: cunsignedlong): cint{.extdecl, importc: "attroff", +proc attroff*(a2: cunsignedlong): cint{.extdecl, importc: "attroff", dynlib: pdcursesdll.} -proc attron*(a2: cunsignedlong): cint{.extdecl, importc: "attron", +proc attron*(a2: cunsignedlong): cint{.extdecl, importc: "attron", dynlib: pdcursesdll.} -proc attrset*(a2: cunsignedlong): cint{.extdecl, importc: "attrset", +proc attrset*(a2: cunsignedlong): cint{.extdecl, importc: "attrset", dynlib: pdcursesdll.} -proc attr_get*(a2: ptr cunsignedlong; a3: ptr cshort; a4: pointer): cint{.extdecl, +proc attr_get*(a2: ptr cunsignedlong; a3: ptr cshort; a4: pointer): cint{.extdecl, importc: "attr_get", dynlib: pdcursesdll.} -proc attr_off*(a2: cunsignedlong; a3: pointer): cint{.extdecl, +proc attr_off*(a2: cunsignedlong; a3: pointer): cint{.extdecl, importc: "attr_off", dynlib: pdcursesdll.} -proc attr_on*(a2: cunsignedlong; a3: pointer): cint{.extdecl, importc: "attr_on", +proc attr_on*(a2: cunsignedlong; a3: pointer): cint{.extdecl, importc: "attr_on", dynlib: pdcursesdll.} -proc attr_set*(a2: cunsignedlong; a3: cshort; a4: pointer): cint{.extdecl, +proc attr_set*(a2: cunsignedlong; a3: cshort; a4: pointer): cint{.extdecl, importc: "attr_set", dynlib: pdcursesdll.} proc baudrate*(): cint{.extdecl, importc: "baudrate", dynlib: pdcursesdll.} proc beep*(): cint{.extdecl, importc: "beep", dynlib: pdcursesdll.} proc bkgd*(a2: cunsignedlong): cint{.extdecl, importc: "bkgd", dynlib: pdcursesdll.} proc bkgdset*(a2: cunsignedlong){.extdecl, importc: "bkgdset", dynlib: pdcursesdll.} -proc border*(a2: cunsignedlong; a3: cunsignedlong; a4: cunsignedlong; - a5: cunsignedlong; a6: cunsignedlong; a7: cunsignedlong; - a8: cunsignedlong; a9: cunsignedlong): cint{.extdecl, +proc border*(a2: cunsignedlong; a3: cunsignedlong; a4: cunsignedlong; + a5: cunsignedlong; a6: cunsignedlong; a7: cunsignedlong; + a8: cunsignedlong; a9: cunsignedlong): cint{.extdecl, importc: "border", dynlib: pdcursesdll.} -proc box*(a2: ptr WINDOW; a3: cunsignedlong; a4: cunsignedlong): cint{.extdecl, +proc box*(a2: ptr WINDOW; a3: cunsignedlong; a4: cunsignedlong): cint{.extdecl, importc: "box", dynlib: pdcursesdll.} -proc can_change_color*(): cunsignedchar{.extdecl, importc: "can_change_color", +proc can_change_color*(): cunsignedchar{.extdecl, importc: "can_change_color", dynlib: pdcursesdll.} proc cbreak*(): cint{.extdecl, importc: "cbreak", dynlib: pdcursesdll.} -proc chgat*(a2: cint; a3: cunsignedlong; a4: cshort; a5: pointer): cint{.extdecl, +proc chgat*(a2: cint; a3: cunsignedlong; a4: cshort; a5: pointer): cint{.extdecl, importc: "chgat", dynlib: pdcursesdll.} -proc clearok*(a2: ptr WINDOW; a3: cunsignedchar): cint{.extdecl, +proc clearok*(a2: ptr WINDOW; a3: cunsignedchar): cint{.extdecl, importc: "clearok", dynlib: pdcursesdll.} proc clear*(): cint{.extdecl, importc: "clear", dynlib: pdcursesdll.} proc clrtobot*(): cint{.extdecl, importc: "clrtobot", dynlib: pdcursesdll.} proc clrtoeol*(): cint{.extdecl, importc: "clrtoeol", dynlib: pdcursesdll.} proc color_content*(a2: cshort; a3: ptr cshort; a4: ptr cshort; a5: ptr cshort): cint{. extdecl, importc: "color_content", dynlib: pdcursesdll.} -proc color_set*(a2: cshort; a3: pointer): cint{.extdecl, importc: "color_set", +proc color_set*(a2: cshort; a3: pointer): cint{.extdecl, importc: "color_set", dynlib: pdcursesdll.} -proc copywin*(a2: ptr WINDOW; a3: ptr WINDOW; a4: cint; a5: cint; a6: cint; - a7: cint; a8: cint; a9: cint; a10: cint): cint{.extdecl, +proc copywin*(a2: ptr WINDOW; a3: ptr WINDOW; a4: cint; a5: cint; a6: cint; + a7: cint; a8: cint; a9: cint; a10: cint): cint{.extdecl, importc: "copywin", dynlib: pdcursesdll.} proc curs_set*(a2: cint): cint{.extdecl, importc: "curs_set", dynlib: pdcursesdll.} -proc def_prog_mode*(): cint{.extdecl, importc: "def_prog_mode", +proc def_prog_mode*(): cint{.extdecl, importc: "def_prog_mode", dynlib: pdcursesdll.} -proc def_shell_mode*(): cint{.extdecl, importc: "def_shell_mode", +proc def_shell_mode*(): cint{.extdecl, importc: "def_shell_mode", dynlib: pdcursesdll.} -proc delay_output*(a2: cint): cint{.extdecl, importc: "delay_output", +proc delay_output*(a2: cint): cint{.extdecl, importc: "delay_output", dynlib: pdcursesdll.} proc delch*(): cint{.extdecl, importc: "delch", dynlib: pdcursesdll.} proc deleteln*(): cint{.extdecl, importc: "deleteln", dynlib: pdcursesdll.} -proc delscreen*(a2: ptr SCREEN){.extdecl, importc: "delscreen", +proc delscreen*(a2: ptr SCREEN){.extdecl, importc: "delscreen", dynlib: pdcursesdll.} -proc delwin*(a2: ptr WINDOW): cint{.extdecl, importc: "delwin", +proc delwin*(a2: ptr WINDOW): cint{.extdecl, importc: "delwin", dynlib: pdcursesdll.} proc derwin*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cint; a6: cint): ptr WINDOW{. extdecl, importc: "derwin", dynlib: pdcursesdll.} proc doupdate*(): cint{.extdecl, importc: "doupdate", dynlib: pdcursesdll.} -proc dupwin*(a2: ptr WINDOW): ptr WINDOW{.extdecl, importc: "dupwin", +proc dupwin*(a2: ptr WINDOW): ptr WINDOW{.extdecl, importc: "dupwin", dynlib: pdcursesdll.} -proc echochar*(a2: cunsignedlong): cint{.extdecl, importc: "echochar", +proc echochar*(a2: cunsignedlong): cint{.extdecl, importc: "echochar", dynlib: pdcursesdll.} proc echo*(): cint{.extdecl, importc: "echo", dynlib: pdcursesdll.} proc endwin*(): cint{.extdecl, importc: "endwin", dynlib: pdcursesdll.} @@ -742,115 +751,115 @@ proc erase*(): cint{.extdecl, importc: "erase", dynlib: pdcursesdll.} proc filter*(){.extdecl, importc: "filter", dynlib: pdcursesdll.} proc flash*(): cint{.extdecl, importc: "flash", dynlib: pdcursesdll.} proc flushinp*(): cint{.extdecl, importc: "flushinp", dynlib: pdcursesdll.} -proc getbkgd*(a2: ptr WINDOW): cunsignedlong{.extdecl, importc: "getbkgd", +proc getbkgd*(a2: ptr WINDOW): cunsignedlong{.extdecl, importc: "getbkgd", dynlib: pdcursesdll.} -proc getnstr*(a2: cstring; a3: cint): cint{.extdecl, importc: "getnstr", +proc getnstr*(a2: cstring; a3: cint): cint{.extdecl, importc: "getnstr", dynlib: pdcursesdll.} proc getstr*(a2: cstring): cint{.extdecl, importc: "getstr", dynlib: pdcursesdll.} -proc getwin*(a2: File): ptr WINDOW{.extdecl, importc: "getwin", +proc getwin*(a2: File): ptr WINDOW{.extdecl, importc: "getwin", dynlib: pdcursesdll.} -proc halfdelay*(a2: cint): cint{.extdecl, importc: "halfdelay", +proc halfdelay*(a2: cint): cint{.extdecl, importc: "halfdelay", dynlib: pdcursesdll.} -proc has_colors*(): cunsignedchar{.extdecl, importc: "has_colors", +proc has_colors*(): cunsignedchar{.extdecl, importc: "has_colors", dynlib: pdcursesdll.} proc has_ic*(): cunsignedchar{.extdecl, importc: "has_ic", dynlib: pdcursesdll.} proc has_il*(): cunsignedchar{.extdecl, importc: "has_il", dynlib: pdcursesdll.} -proc hline*(a2: cunsignedlong; a3: cint): cint{.extdecl, importc: "hline", +proc hline*(a2: cunsignedlong; a3: cint): cint{.extdecl, importc: "hline", dynlib: pdcursesdll.} -proc idcok*(a2: ptr WINDOW; a3: cunsignedchar){.extdecl, importc: "idcok", +proc idcok*(a2: ptr WINDOW; a3: cunsignedchar){.extdecl, importc: "idcok", dynlib: pdcursesdll.} -proc idlok*(a2: ptr WINDOW; a3: cunsignedchar): cint{.extdecl, importc: "idlok", +proc idlok*(a2: ptr WINDOW; a3: cunsignedchar): cint{.extdecl, importc: "idlok", dynlib: pdcursesdll.} -proc immedok*(a2: ptr WINDOW; a3: cunsignedchar){.extdecl, importc: "immedok", +proc immedok*(a2: ptr WINDOW; a3: cunsignedchar){.extdecl, importc: "immedok", dynlib: pdcursesdll.} -proc inchnstr*(a2: ptr cunsignedlong; a3: cint): cint{.extdecl, +proc inchnstr*(a2: ptr cunsignedlong; a3: cint): cint{.extdecl, importc: "inchnstr", dynlib: pdcursesdll.} -proc inchstr*(a2: ptr cunsignedlong): cint{.extdecl, importc: "inchstr", +proc inchstr*(a2: ptr cunsignedlong): cint{.extdecl, importc: "inchstr", dynlib: pdcursesdll.} proc inch*(): cunsignedlong{.extdecl, importc: "inch", dynlib: pdcursesdll.} -proc init_color*(a2: cshort; a3: cshort; a4: cshort; a5: cshort): cint{.extdecl, +proc init_color*(a2: cshort; a3: cshort; a4: cshort; a5: cshort): cint{.extdecl, importc: "init_color", dynlib: pdcursesdll.} -proc init_pair*(a2: cshort; a3: cshort; a4: cshort): cint{.extdecl, +proc init_pair*(a2: cshort; a3: cshort; a4: cshort): cint{.extdecl, importc: "init_pair", dynlib: pdcursesdll.} proc initscr*(): ptr WINDOW{.extdecl, importc: "initscr", dynlib: pdcursesdll.} -proc innstr*(a2: cstring; a3: cint): cint{.extdecl, importc: "innstr", +proc innstr*(a2: cstring; a3: cint): cint{.extdecl, importc: "innstr", dynlib: pdcursesdll.} -proc insch*(a2: cunsignedlong): cint{.extdecl, importc: "insch", +proc insch*(a2: cunsignedlong): cint{.extdecl, importc: "insch", dynlib: pdcursesdll.} proc insdelln*(a2: cint): cint{.extdecl, importc: "insdelln", dynlib: pdcursesdll.} proc insertln*(): cint{.extdecl, importc: "insertln", dynlib: pdcursesdll.} -proc insnstr*(a2: cstring; a3: cint): cint{.extdecl, importc: "insnstr", +proc insnstr*(a2: cstring; a3: cint): cint{.extdecl, importc: "insnstr", dynlib: pdcursesdll.} proc insstr*(a2: cstring): cint{.extdecl, importc: "insstr", dynlib: pdcursesdll.} proc instr*(a2: cstring): cint{.extdecl, importc: "instr", dynlib: pdcursesdll.} -proc intrflush*(a2: ptr WINDOW; a3: cunsignedchar): cint{.extdecl, +proc intrflush*(a2: ptr WINDOW; a3: cunsignedchar): cint{.extdecl, importc: "intrflush", dynlib: pdcursesdll.} proc isendwin*(): cunsignedchar{.extdecl, importc: "isendwin", dynlib: pdcursesdll.} -proc is_linetouched*(a2: ptr WINDOW; a3: cint): cunsignedchar{.extdecl, +proc is_linetouched*(a2: ptr WINDOW; a3: cint): cunsignedchar{.extdecl, importc: "is_linetouched", dynlib: pdcursesdll.} -proc is_wintouched*(a2: ptr WINDOW): cunsignedchar{.extdecl, +proc is_wintouched*(a2: ptr WINDOW): cunsignedchar{.extdecl, importc: "is_wintouched", dynlib: pdcursesdll.} proc keyname*(a2: cint): cstring{.extdecl, importc: "keyname", dynlib: pdcursesdll.} -proc keypad*(a2: ptr WINDOW; a3: cunsignedchar): cint{.extdecl, importc: "keypad", +proc keypad*(a2: ptr WINDOW; a3: cunsignedchar): cint{.extdecl, importc: "keypad", dynlib: pdcursesdll.} proc killchar*(): char{.extdecl, importc: "killchar", dynlib: pdcursesdll.} -proc leaveok*(a2: ptr WINDOW; a3: cunsignedchar): cint{.extdecl, +proc leaveok*(a2: ptr WINDOW; a3: cunsignedchar): cint{.extdecl, importc: "leaveok", dynlib: pdcursesdll.} proc longname*(): cstring{.extdecl, importc: "longname", dynlib: pdcursesdll.} -proc meta*(a2: ptr WINDOW; a3: cunsignedchar): cint{.extdecl, importc: "meta", +proc meta*(a2: ptr WINDOW; a3: cunsignedchar): cint{.extdecl, importc: "meta", dynlib: pdcursesdll.} -proc move*(a2: cint; a3: cint): cint{.extdecl, importc: "move", +proc move*(a2: cint; a3: cint): cint{.extdecl, importc: "move", dynlib: pdcursesdll.} -proc mvaddch*(a2: cint; a3: cint; a4: cunsignedlong): cint{.extdecl, +proc mvaddch*(a2: cint; a3: cint; a4: cunsignedlong): cint{.extdecl, importc: "mvaddch", dynlib: pdcursesdll.} proc mvaddchnstr*(a2: cint; a3: cint; a4: ptr cunsignedlong; a5: cint): cint{. extdecl, importc: "mvaddchnstr", dynlib: pdcursesdll.} -proc mvaddchstr*(a2: cint; a3: cint; a4: ptr cunsignedlong): cint{.extdecl, +proc mvaddchstr*(a2: cint; a3: cint; a4: ptr cunsignedlong): cint{.extdecl, importc: "mvaddchstr", dynlib: pdcursesdll.} -proc mvaddnstr*(a2: cint; a3: cint; a4: cstring; a5: cint): cint{.extdecl, +proc mvaddnstr*(a2: cint; a3: cint; a4: cstring; a5: cint): cint{.extdecl, importc: "mvaddnstr", dynlib: pdcursesdll.} -proc mvaddstr*(a2: cint; a3: cint; a4: cstring): cint{.extdecl, +proc mvaddstr*(a2: cint; a3: cint; a4: cstring): cint{.extdecl, importc: "mvaddstr", dynlib: pdcursesdll.} -proc mvchgat*(a2: cint; a3: cint; a4: cint; a5: cunsignedlong; a6: cshort; +proc mvchgat*(a2: cint; a3: cint; a4: cint; a5: cunsignedlong; a6: cshort; a7: pointer): cint{.extdecl, importc: "mvchgat", dynlib: pdcursesdll.} -proc mvcur*(a2: cint; a3: cint; a4: cint; a5: cint): cint{.extdecl, +proc mvcur*(a2: cint; a3: cint; a4: cint; a5: cint): cint{.extdecl, importc: "mvcur", dynlib: pdcursesdll.} -proc mvdelch*(a2: cint; a3: cint): cint{.extdecl, importc: "mvdelch", +proc mvdelch*(a2: cint; a3: cint): cint{.extdecl, importc: "mvdelch", dynlib: pdcursesdll.} -proc mvderwin*(a2: ptr WINDOW; a3: cint; a4: cint): cint{.extdecl, +proc mvderwin*(a2: ptr WINDOW; a3: cint; a4: cint): cint{.extdecl, importc: "mvderwin", dynlib: pdcursesdll.} -proc mvgetch*(a2: cint; a3: cint): cint{.extdecl, importc: "mvgetch", +proc mvgetch*(a2: cint; a3: cint): cint{.extdecl, importc: "mvgetch", dynlib: pdcursesdll.} -proc mvgetnstr*(a2: cint; a3: cint; a4: cstring; a5: cint): cint{.extdecl, +proc mvgetnstr*(a2: cint; a3: cint; a4: cstring; a5: cint): cint{.extdecl, importc: "mvgetnstr", dynlib: pdcursesdll.} -proc mvgetstr*(a2: cint; a3: cint; a4: cstring): cint{.extdecl, +proc mvgetstr*(a2: cint; a3: cint; a4: cstring): cint{.extdecl, importc: "mvgetstr", dynlib: pdcursesdll.} -proc mvhline*(a2: cint; a3: cint; a4: cunsignedlong; a5: cint): cint{.extdecl, +proc mvhline*(a2: cint; a3: cint; a4: cunsignedlong; a5: cint): cint{.extdecl, importc: "mvhline", dynlib: pdcursesdll.} -proc mvinch*(a2: cint; a3: cint): cunsignedlong{.extdecl, importc: "mvinch", +proc mvinch*(a2: cint; a3: cint): cunsignedlong{.extdecl, importc: "mvinch", dynlib: pdcursesdll.} proc mvinchnstr*(a2: cint; a3: cint; a4: ptr cunsignedlong; a5: cint): cint{. extdecl, importc: "mvinchnstr", dynlib: pdcursesdll.} -proc mvinchstr*(a2: cint; a3: cint; a4: ptr cunsignedlong): cint{.extdecl, +proc mvinchstr*(a2: cint; a3: cint; a4: ptr cunsignedlong): cint{.extdecl, importc: "mvinchstr", dynlib: pdcursesdll.} -proc mvinnstr*(a2: cint; a3: cint; a4: cstring; a5: cint): cint{.extdecl, +proc mvinnstr*(a2: cint; a3: cint; a4: cstring; a5: cint): cint{.extdecl, importc: "mvinnstr", dynlib: pdcursesdll.} -proc mvinsch*(a2: cint; a3: cint; a4: cunsignedlong): cint{.extdecl, +proc mvinsch*(a2: cint; a3: cint; a4: cunsignedlong): cint{.extdecl, importc: "mvinsch", dynlib: pdcursesdll.} -proc mvinsnstr*(a2: cint; a3: cint; a4: cstring; a5: cint): cint{.extdecl, +proc mvinsnstr*(a2: cint; a3: cint; a4: cstring; a5: cint): cint{.extdecl, importc: "mvinsnstr", dynlib: pdcursesdll.} -proc mvinsstr*(a2: cint; a3: cint; a4: cstring): cint{.extdecl, +proc mvinsstr*(a2: cint; a3: cint; a4: cstring): cint{.extdecl, importc: "mvinsstr", dynlib: pdcursesdll.} -proc mvinstr*(a2: cint; a3: cint; a4: cstring): cint{.extdecl, importc: "mvinstr", +proc mvinstr*(a2: cint; a3: cint; a4: cstring): cint{.extdecl, importc: "mvinstr", dynlib: pdcursesdll.} -proc mvprintw*(a2: cint; a3: cint; a4: cstring): cint{.varargs, extdecl, +proc mvprintw*(a2: cint; a3: cint; a4: cstring): cint{.varargs, extdecl, importc: "mvprintw", dynlib: pdcursesdll.} -proc mvscanw*(a2: cint; a3: cint; a4: cstring): cint{.varargs, extdecl, +proc mvscanw*(a2: cint; a3: cint; a4: cstring): cint{.varargs, extdecl, importc: "mvscanw", dynlib: pdcursesdll.} -proc mvvline*(a2: cint; a3: cint; a4: cunsignedlong; a5: cint): cint{.extdecl, +proc mvvline*(a2: cint; a3: cint; a4: cunsignedlong; a5: cint): cint{.extdecl, importc: "mvvline", dynlib: pdcursesdll.} -proc mvwaddchnstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong; - a6: cint): cint{.extdecl, importc: "mvwaddchnstr", +proc mvwaddchnstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong; + a6: cint): cint{.extdecl, importc: "mvwaddchnstr", dynlib: pdcursesdll.} proc mvwaddchstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong): cint{. extdecl, importc: "mvwaddchstr", dynlib: pdcursesdll.} @@ -858,27 +867,27 @@ proc mvwaddch*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cunsignedlong): cint{. extdecl, importc: "mvwaddch", dynlib: pdcursesdll.} proc mvwaddnstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cstring; a6: cint): cint{. extdecl, importc: "mvwaddnstr", dynlib: pdcursesdll.} -proc mvwaddstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cstring): cint{.extdecl, +proc mvwaddstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cstring): cint{.extdecl, importc: "mvwaddstr", dynlib: pdcursesdll.} -proc mvwchgat*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cint; a6: cunsignedlong; - a7: cshort; a8: pointer): cint{.extdecl, importc: "mvwchgat", +proc mvwchgat*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cint; a6: cunsignedlong; + a7: cshort; a8: pointer): cint{.extdecl, importc: "mvwchgat", dynlib: pdcursesdll.} -proc mvwdelch*(a2: ptr WINDOW; a3: cint; a4: cint): cint{.extdecl, +proc mvwdelch*(a2: ptr WINDOW; a3: cint; a4: cint): cint{.extdecl, importc: "mvwdelch", dynlib: pdcursesdll.} -proc mvwgetch*(a2: ptr WINDOW; a3: cint; a4: cint): cint{.extdecl, +proc mvwgetch*(a2: ptr WINDOW; a3: cint; a4: cint): cint{.extdecl, importc: "mvwgetch", dynlib: pdcursesdll.} proc mvwgetnstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cstring; a6: cint): cint{. extdecl, importc: "mvwgetnstr", dynlib: pdcursesdll.} -proc mvwgetstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cstring): cint{.extdecl, +proc mvwgetstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cstring): cint{.extdecl, importc: "mvwgetstr", dynlib: pdcursesdll.} proc mvwhline*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cunsignedlong; a6: cint): cint{. extdecl, importc: "mvwhline", dynlib: pdcursesdll.} -proc mvwinchnstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong; - a6: cint): cint{.extdecl, importc: "mvwinchnstr", +proc mvwinchnstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong; + a6: cint): cint{.extdecl, importc: "mvwinchnstr", dynlib: pdcursesdll.} proc mvwinchstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong): cint{. extdecl, importc: "mvwinchstr", dynlib: pdcursesdll.} -proc mvwinch*(a2: ptr WINDOW; a3: cint; a4: cint): cunsignedlong{.extdecl, +proc mvwinch*(a2: ptr WINDOW; a3: cint; a4: cint): cunsignedlong{.extdecl, importc: "mvwinch", dynlib: pdcursesdll.} proc mvwinnstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cstring; a6: cint): cint{. extdecl, importc: "mvwinnstr", dynlib: pdcursesdll.} @@ -886,105 +895,105 @@ proc mvwinsch*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cunsignedlong): cint{. extdecl, importc: "mvwinsch", dynlib: pdcursesdll.} proc mvwinsnstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cstring; a6: cint): cint{. extdecl, importc: "mvwinsnstr", dynlib: pdcursesdll.} -proc mvwinsstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cstring): cint{.extdecl, +proc mvwinsstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cstring): cint{.extdecl, importc: "mvwinsstr", dynlib: pdcursesdll.} -proc mvwinstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cstring): cint{.extdecl, +proc mvwinstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cstring): cint{.extdecl, importc: "mvwinstr", dynlib: pdcursesdll.} -proc mvwin*(a2: ptr WINDOW; a3: cint; a4: cint): cint{.extdecl, importc: "mvwin", +proc mvwin*(a2: ptr WINDOW; a3: cint; a4: cint): cint{.extdecl, importc: "mvwin", dynlib: pdcursesdll.} -proc mvwprintw*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cstring): cint{.varargs, +proc mvwprintw*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cstring): cint{.varargs, extdecl, importc: "mvwprintw", dynlib: pdcursesdll.} -proc mvwscanw*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cstring): cint{.varargs, +proc mvwscanw*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cstring): cint{.varargs, extdecl, importc: "mvwscanw", dynlib: pdcursesdll.} proc mvwvline*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cunsignedlong; a6: cint): cint{. extdecl, importc: "mvwvline", dynlib: pdcursesdll.} proc napms*(a2: cint): cint{.extdecl, importc: "napms", dynlib: pdcursesdll.} -proc newpad*(a2: cint; a3: cint): ptr WINDOW{.extdecl, importc: "newpad", +proc newpad*(a2: cint; a3: cint): ptr WINDOW{.extdecl, importc: "newpad", dynlib: pdcursesdll.} -proc newterm*(a2: cstring; a3: File; a4: File): ptr SCREEN{.extdecl, +proc newterm*(a2: cstring; a3: File; a4: File): ptr SCREEN{.extdecl, importc: "newterm", dynlib: pdcursesdll.} -proc newwin*(a2: cint; a3: cint; a4: cint; a5: cint): ptr WINDOW{.extdecl, +proc newwin*(a2: cint; a3: cint; a4: cint; a5: cint): ptr WINDOW{.extdecl, importc: "newwin", dynlib: pdcursesdll.} proc nl*(): cint{.extdecl, importc: "nl", dynlib: pdcursesdll.} proc nocbreak*(): cint{.extdecl, importc: "nocbreak", dynlib: pdcursesdll.} -proc nodelay*(a2: ptr WINDOW; a3: cunsignedchar): cint{.extdecl, +proc nodelay*(a2: ptr WINDOW; a3: cunsignedchar): cint{.extdecl, importc: "nodelay", dynlib: pdcursesdll.} proc noecho*(): cint{.extdecl, importc: "noecho", dynlib: pdcursesdll.} proc nonl*(): cint{.extdecl, importc: "nonl", dynlib: pdcursesdll.} proc noqiflush*(){.extdecl, importc: "noqiflush", dynlib: pdcursesdll.} proc noraw*(): cint{.extdecl, importc: "noraw", dynlib: pdcursesdll.} -proc notimeout*(a2: ptr WINDOW; a3: cunsignedchar): cint{.extdecl, +proc notimeout*(a2: ptr WINDOW; a3: cunsignedchar): cint{.extdecl, importc: "notimeout", dynlib: pdcursesdll.} -proc overlay*(a2: ptr WINDOW; a3: ptr WINDOW): cint{.extdecl, importc: "overlay", +proc overlay*(a2: ptr WINDOW; a3: ptr WINDOW): cint{.extdecl, importc: "overlay", dynlib: pdcursesdll.} -proc overwrite*(a2: ptr WINDOW; a3: ptr WINDOW): cint{.extdecl, +proc overwrite*(a2: ptr WINDOW; a3: ptr WINDOW): cint{.extdecl, importc: "overwrite", dynlib: pdcursesdll.} -proc pair_content*(a2: cshort; a3: ptr cshort; a4: ptr cshort): cint{.extdecl, +proc pair_content*(a2: cshort; a3: ptr cshort; a4: ptr cshort): cint{.extdecl, importc: "pair_content", dynlib: pdcursesdll.} -proc pechochar*(a2: ptr WINDOW; a3: cunsignedlong): cint{.extdecl, +proc pechochar*(a2: ptr WINDOW; a3: cunsignedlong): cint{.extdecl, importc: "pechochar", dynlib: pdcursesdll.} -proc pnoutrefresh*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cint; a6: cint; - a7: cint; a8: cint): cint{.extdecl, importc: "pnoutrefresh", +proc pnoutrefresh*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cint; a6: cint; + a7: cint; a8: cint): cint{.extdecl, importc: "pnoutrefresh", dynlib: pdcursesdll.} -proc prefresh*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cint; a6: cint; a7: cint; +proc prefresh*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cint; a6: cint; a7: cint; a8: cint): cint{.extdecl, importc: "prefresh", dynlib: pdcursesdll.} -proc printw*(a2: cstring): cint{.varargs, extdecl, importc: "printw", +proc printw*(a2: cstring): cint{.varargs, extdecl, importc: "printw", dynlib: pdcursesdll.} -proc putwin*(a2: ptr WINDOW; a3: File): cint{.extdecl, importc: "putwin", +proc putwin*(a2: ptr WINDOW; a3: File): cint{.extdecl, importc: "putwin", dynlib: pdcursesdll.} proc qiflush*(){.extdecl, importc: "qiflush", dynlib: pdcursesdll.} proc raw*(): cint{.extdecl, importc: "raw", dynlib: pdcursesdll.} -proc redrawwin*(a2: ptr WINDOW): cint{.extdecl, importc: "redrawwin", +proc redrawwin*(a2: ptr WINDOW): cint{.extdecl, importc: "redrawwin", dynlib: pdcursesdll.} proc refresh*(): cint{.extdecl, importc: "refresh", dynlib: pdcursesdll.} -proc reset_prog_mode*(): cint{.extdecl, importc: "reset_prog_mode", +proc reset_prog_mode*(): cint{.extdecl, importc: "reset_prog_mode", dynlib: pdcursesdll.} -proc reset_shell_mode*(): cint{.extdecl, importc: "reset_shell_mode", +proc reset_shell_mode*(): cint{.extdecl, importc: "reset_shell_mode", dynlib: pdcursesdll.} proc resetty*(): cint{.extdecl, importc: "resetty", dynlib: pdcursesdll.} #int ripoffline(int, int (*)(WINDOW *, int)); proc savetty*(): cint{.extdecl, importc: "savetty", dynlib: pdcursesdll.} -proc scanw*(a2: cstring): cint{.varargs, extdecl, importc: "scanw", +proc scanw*(a2: cstring): cint{.varargs, extdecl, importc: "scanw", dynlib: pdcursesdll.} -proc scr_dump*(a2: cstring): cint{.extdecl, importc: "scr_dump", +proc scr_dump*(a2: cstring): cint{.extdecl, importc: "scr_dump", dynlib: pdcursesdll.} -proc scr_init*(a2: cstring): cint{.extdecl, importc: "scr_init", +proc scr_init*(a2: cstring): cint{.extdecl, importc: "scr_init", dynlib: pdcursesdll.} -proc scr_restore*(a2: cstring): cint{.extdecl, importc: "scr_restore", +proc scr_restore*(a2: cstring): cint{.extdecl, importc: "scr_restore", dynlib: pdcursesdll.} proc scr_set*(a2: cstring): cint{.extdecl, importc: "scr_set", dynlib: pdcursesdll.} proc scrl*(a2: cint): cint{.extdecl, importc: "scrl", dynlib: pdcursesdll.} -proc scroll*(a2: ptr WINDOW): cint{.extdecl, importc: "scroll", +proc scroll*(a2: ptr WINDOW): cint{.extdecl, importc: "scroll", dynlib: pdcursesdll.} -proc scrollok*(a2: ptr WINDOW; a3: cunsignedchar): cint{.extdecl, +proc scrollok*(a2: ptr WINDOW; a3: cunsignedchar): cint{.extdecl, importc: "scrollok", dynlib: pdcursesdll.} -proc set_term*(a2: ptr SCREEN): ptr SCREEN{.extdecl, importc: "set_term", +proc set_term*(a2: ptr SCREEN): ptr SCREEN{.extdecl, importc: "set_term", dynlib: pdcursesdll.} -proc setscrreg*(a2: cint; a3: cint): cint{.extdecl, importc: "setscrreg", +proc setscrreg*(a2: cint; a3: cint): cint{.extdecl, importc: "setscrreg", dynlib: pdcursesdll.} -proc slk_attroff*(a2: cunsignedlong): cint{.extdecl, importc: "slk_attroff", +proc slk_attroff*(a2: cunsignedlong): cint{.extdecl, importc: "slk_attroff", dynlib: pdcursesdll.} -proc slk_attr_off*(a2: cunsignedlong; a3: pointer): cint{.extdecl, +proc slk_attr_off*(a2: cunsignedlong; a3: pointer): cint{.extdecl, importc: "slk_attr_off", dynlib: pdcursesdll.} -proc slk_attron*(a2: cunsignedlong): cint{.extdecl, importc: "slk_attron", +proc slk_attron*(a2: cunsignedlong): cint{.extdecl, importc: "slk_attron", dynlib: pdcursesdll.} -proc slk_attr_on*(a2: cunsignedlong; a3: pointer): cint{.extdecl, +proc slk_attr_on*(a2: cunsignedlong; a3: pointer): cint{.extdecl, importc: "slk_attr_on", dynlib: pdcursesdll.} -proc slk_attrset*(a2: cunsignedlong): cint{.extdecl, importc: "slk_attrset", +proc slk_attrset*(a2: cunsignedlong): cint{.extdecl, importc: "slk_attrset", dynlib: pdcursesdll.} -proc slk_attr_set*(a2: cunsignedlong; a3: cshort; a4: pointer): cint{.extdecl, +proc slk_attr_set*(a2: cunsignedlong; a3: cshort; a4: pointer): cint{.extdecl, importc: "slk_attr_set", dynlib: pdcursesdll.} proc slk_clear*(): cint{.extdecl, importc: "slk_clear", dynlib: pdcursesdll.} -proc slk_color*(a2: cshort): cint{.extdecl, importc: "slk_color", +proc slk_color*(a2: cshort): cint{.extdecl, importc: "slk_color", dynlib: pdcursesdll.} proc slk_init*(a2: cint): cint{.extdecl, importc: "slk_init", dynlib: pdcursesdll.} -proc slk_label*(a2: cint): cstring{.extdecl, importc: "slk_label", +proc slk_label*(a2: cint): cstring{.extdecl, importc: "slk_label", dynlib: pdcursesdll.} -proc slk_noutrefresh*(): cint{.extdecl, importc: "slk_noutrefresh", +proc slk_noutrefresh*(): cint{.extdecl, importc: "slk_noutrefresh", dynlib: pdcursesdll.} proc slk_refresh*(): cint{.extdecl, importc: "slk_refresh", dynlib: pdcursesdll.} proc slk_restore*(): cint{.extdecl, importc: "slk_restore", dynlib: pdcursesdll.} -proc slk_set*(a2: cint; a3: cstring; a4: cint): cint{.extdecl, importc: "slk_set", +proc slk_set*(a2: cint; a3: cstring; a4: cint): cint{.extdecl, importc: "slk_set", dynlib: pdcursesdll.} proc slk_touch*(): cint{.extdecl, importc: "slk_touch", dynlib: pdcursesdll.} proc standend*(): cint{.extdecl, importc: "standend", dynlib: pdcursesdll.} @@ -994,30 +1003,30 @@ proc subpad*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cint; a6: cint): ptr WINDOW extdecl, importc: "subpad", dynlib: pdcursesdll.} proc subwin*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cint; a6: cint): ptr WINDOW{. extdecl, importc: "subwin", dynlib: pdcursesdll.} -proc syncok*(a2: ptr WINDOW; a3: cunsignedchar): cint{.extdecl, importc: "syncok", +proc syncok*(a2: ptr WINDOW; a3: cunsignedchar): cint{.extdecl, importc: "syncok", dynlib: pdcursesdll.} -proc termattrs*(): cunsignedlong{.extdecl, importc: "termattrs", +proc termattrs*(): cunsignedlong{.extdecl, importc: "termattrs", dynlib: pdcursesdll.} -proc termattrs2*(): cunsignedlong{.extdecl, importc: "term_attrs", +proc termattrs2*(): cunsignedlong{.extdecl, importc: "term_attrs", dynlib: pdcursesdll.} proc termname*(): cstring{.extdecl, importc: "termname", dynlib: pdcursesdll.} proc timeout*(a2: cint){.extdecl, importc: "timeout", dynlib: pdcursesdll.} -proc touchline*(a2: ptr WINDOW; a3: cint; a4: cint): cint{.extdecl, +proc touchline*(a2: ptr WINDOW; a3: cint; a4: cint): cint{.extdecl, importc: "touchline", dynlib: pdcursesdll.} -proc touchwin*(a2: ptr WINDOW): cint{.extdecl, importc: "touchwin", +proc touchwin*(a2: ptr WINDOW): cint{.extdecl, importc: "touchwin", dynlib: pdcursesdll.} -proc typeahead*(a2: cint): cint{.extdecl, importc: "typeahead", +proc typeahead*(a2: cint): cint{.extdecl, importc: "typeahead", dynlib: pdcursesdll.} -proc untouchwin*(a2: ptr WINDOW): cint{.extdecl, importc: "untouchwin", +proc untouchwin*(a2: ptr WINDOW): cint{.extdecl, importc: "untouchwin", dynlib: pdcursesdll.} proc use_env*(a2: cunsignedchar){.extdecl, importc: "use_env", dynlib: pdcursesdll.} -proc vidattr*(a2: cunsignedlong): cint{.extdecl, importc: "vidattr", +proc vidattr*(a2: cunsignedlong): cint{.extdecl, importc: "vidattr", dynlib: pdcursesdll.} -proc vid_attr*(a2: cunsignedlong; a3: cshort; a4: pointer): cint{.extdecl, +proc vid_attr*(a2: cunsignedlong; a3: cshort; a4: pointer): cint{.extdecl, importc: "vid_attr", dynlib: pdcursesdll.} #int vidputs(chtype, int (*)(int)); #int vid_puts(attr_t, short, void *, int (*)(int)); -proc vline*(a2: cunsignedlong; a3: cint): cint{.extdecl, importc: "vline", +proc vline*(a2: cunsignedlong; a3: cint): cint{.extdecl, importc: "vline", dynlib: pdcursesdll.} proc vwprintw*(a2: ptr WINDOW; a3: cstring): cint{.extdecl, varargs, importc: "vw_printw", dynlib: pdcursesdll.} @@ -1027,203 +1036,203 @@ proc vwscanw*(a2: ptr WINDOW; a3: cstring): cint{.extdecl, varargs, importc: "vw_scanw", dynlib: pdcursesdll.} proc vwscanw2*(a2: ptr WINDOW; a3: cstring): cint{.extdecl, varargs, importc: "vwscanw", dynlib: pdcursesdll.} -proc waddchnstr*(a2: ptr WINDOW; a3: ptr cunsignedlong; a4: cint): cint{.extdecl, +proc waddchnstr*(a2: ptr WINDOW; a3: ptr cunsignedlong; a4: cint): cint{.extdecl, importc: "waddchnstr", dynlib: pdcursesdll.} -proc waddchstr*(a2: ptr WINDOW; a3: ptr cunsignedlong): cint{.extdecl, +proc waddchstr*(a2: ptr WINDOW; a3: ptr cunsignedlong): cint{.extdecl, importc: "waddchstr", dynlib: pdcursesdll.} -proc waddch*(a2: ptr WINDOW; a3: cunsignedlong): cint{.extdecl, importc: "waddch", +proc waddch*(a2: ptr WINDOW; a3: cunsignedlong): cint{.extdecl, importc: "waddch", dynlib: pdcursesdll.} -proc waddnstr*(a2: ptr WINDOW; a3: cstring; a4: cint): cint{.extdecl, +proc waddnstr*(a2: ptr WINDOW; a3: cstring; a4: cint): cint{.extdecl, importc: "waddnstr", dynlib: pdcursesdll.} -proc waddstr*(a2: ptr WINDOW; a3: cstring): cint{.extdecl, importc: "waddstr", +proc waddstr*(a2: ptr WINDOW; a3: cstring): cint{.extdecl, importc: "waddstr", dynlib: pdcursesdll.} -proc wattroff*(a2: ptr WINDOW; a3: cunsignedlong): cint{.extdecl, +proc wattroff*(a2: ptr WINDOW; a3: cunsignedlong): cint{.extdecl, importc: "wattroff", dynlib: pdcursesdll.} -proc wattron*(a2: ptr WINDOW; a3: cunsignedlong): cint{.extdecl, +proc wattron*(a2: ptr WINDOW; a3: cunsignedlong): cint{.extdecl, importc: "wattron", dynlib: pdcursesdll.} -proc wattrset*(a2: ptr WINDOW; a3: cunsignedlong): cint{.extdecl, +proc wattrset*(a2: ptr WINDOW; a3: cunsignedlong): cint{.extdecl, importc: "wattrset", dynlib: pdcursesdll.} -proc wattr_get*(a2: ptr WINDOW; a3: ptr cunsignedlong; a4: ptr cshort; - a5: pointer): cint{.extdecl, importc: "wattr_get", +proc wattr_get*(a2: ptr WINDOW; a3: ptr cunsignedlong; a4: ptr cshort; + a5: pointer): cint{.extdecl, importc: "wattr_get", dynlib: pdcursesdll.} -proc wattr_off*(a2: ptr WINDOW; a3: cunsignedlong; a4: pointer): cint{.extdecl, +proc wattr_off*(a2: ptr WINDOW; a3: cunsignedlong; a4: pointer): cint{.extdecl, importc: "wattr_off", dynlib: pdcursesdll.} -proc wattr_on*(a2: ptr WINDOW; a3: cunsignedlong; a4: pointer): cint{.extdecl, +proc wattr_on*(a2: ptr WINDOW; a3: cunsignedlong; a4: pointer): cint{.extdecl, importc: "wattr_on", dynlib: pdcursesdll.} proc wattr_set*(a2: ptr WINDOW; a3: cunsignedlong; a4: cshort; a5: pointer): cint{. extdecl, importc: "wattr_set", dynlib: pdcursesdll.} -proc wbkgdset*(a2: ptr WINDOW; a3: cunsignedlong){.extdecl, importc: "wbkgdset", +proc wbkgdset*(a2: ptr WINDOW; a3: cunsignedlong){.extdecl, importc: "wbkgdset", dynlib: pdcursesdll.} -proc wbkgd*(a2: ptr WINDOW; a3: cunsignedlong): cint{.extdecl, importc: "wbkgd", +proc wbkgd*(a2: ptr WINDOW; a3: cunsignedlong): cint{.extdecl, importc: "wbkgd", dynlib: pdcursesdll.} -proc wborder*(a2: ptr WINDOW; a3: cunsignedlong; a4: cunsignedlong; - a5: cunsignedlong; a6: cunsignedlong; a7: cunsignedlong; +proc wborder*(a2: ptr WINDOW; a3: cunsignedlong; a4: cunsignedlong; + a5: cunsignedlong; a6: cunsignedlong; a7: cunsignedlong; a8: cunsignedlong; a9: cunsignedlong; a10: cunsignedlong): cint{. extdecl, importc: "wborder", dynlib: pdcursesdll.} -proc wchgat*(a2: ptr WINDOW; a3: cint; a4: cunsignedlong; a5: cshort; +proc wchgat*(a2: ptr WINDOW; a3: cint; a4: cunsignedlong; a5: cshort; a6: pointer): cint{.extdecl, importc: "wchgat", dynlib: pdcursesdll.} -proc wclear*(a2: ptr WINDOW): cint{.extdecl, importc: "wclear", +proc wclear*(a2: ptr WINDOW): cint{.extdecl, importc: "wclear", dynlib: pdcursesdll.} -proc wclrtobot*(a2: ptr WINDOW): cint{.extdecl, importc: "wclrtobot", +proc wclrtobot*(a2: ptr WINDOW): cint{.extdecl, importc: "wclrtobot", dynlib: pdcursesdll.} -proc wclrtoeol*(a2: ptr WINDOW): cint{.extdecl, importc: "wclrtoeol", +proc wclrtoeol*(a2: ptr WINDOW): cint{.extdecl, importc: "wclrtoeol", dynlib: pdcursesdll.} -proc wcolor_set*(a2: ptr WINDOW; a3: cshort; a4: pointer): cint{.extdecl, +proc wcolor_set*(a2: ptr WINDOW; a3: cshort; a4: pointer): cint{.extdecl, importc: "wcolor_set", dynlib: pdcursesdll.} -proc wcursyncup*(a2: ptr WINDOW){.extdecl, importc: "wcursyncup", +proc wcursyncup*(a2: ptr WINDOW){.extdecl, importc: "wcursyncup", dynlib: pdcursesdll.} -proc wdelch*(a2: ptr WINDOW): cint{.extdecl, importc: "wdelch", +proc wdelch*(a2: ptr WINDOW): cint{.extdecl, importc: "wdelch", dynlib: pdcursesdll.} -proc wdeleteln*(a2: ptr WINDOW): cint{.extdecl, importc: "wdeleteln", +proc wdeleteln*(a2: ptr WINDOW): cint{.extdecl, importc: "wdeleteln", dynlib: pdcursesdll.} -proc wechochar*(a2: ptr WINDOW; a3: cunsignedlong): cint{.extdecl, +proc wechochar*(a2: ptr WINDOW; a3: cunsignedlong): cint{.extdecl, importc: "wechochar", dynlib: pdcursesdll.} -proc werase*(a2: ptr WINDOW): cint{.extdecl, importc: "werase", +proc werase*(a2: ptr WINDOW): cint{.extdecl, importc: "werase", dynlib: pdcursesdll.} -proc wgetch*(a2: ptr WINDOW): cint{.extdecl, importc: "wgetch", +proc wgetch*(a2: ptr WINDOW): cint{.extdecl, importc: "wgetch", dynlib: pdcursesdll.} -proc wgetnstr*(a2: ptr WINDOW; a3: cstring; a4: cint): cint{.extdecl, +proc wgetnstr*(a2: ptr WINDOW; a3: cstring; a4: cint): cint{.extdecl, importc: "wgetnstr", dynlib: pdcursesdll.} -proc wgetstr*(a2: ptr WINDOW; a3: cstring): cint{.extdecl, importc: "wgetstr", +proc wgetstr*(a2: ptr WINDOW; a3: cstring): cint{.extdecl, importc: "wgetstr", dynlib: pdcursesdll.} -proc whline*(a2: ptr WINDOW; a3: cunsignedlong; a4: cint): cint{.extdecl, +proc whline*(a2: ptr WINDOW; a3: cunsignedlong; a4: cint): cint{.extdecl, importc: "whline", dynlib: pdcursesdll.} -proc winchnstr*(a2: ptr WINDOW; a3: ptr cunsignedlong; a4: cint): cint{.extdecl, +proc winchnstr*(a2: ptr WINDOW; a3: ptr cunsignedlong; a4: cint): cint{.extdecl, importc: "winchnstr", dynlib: pdcursesdll.} -proc winchstr*(a2: ptr WINDOW; a3: ptr cunsignedlong): cint{.extdecl, +proc winchstr*(a2: ptr WINDOW; a3: ptr cunsignedlong): cint{.extdecl, importc: "winchstr", dynlib: pdcursesdll.} -proc winch*(a2: ptr WINDOW): cunsignedlong{.extdecl, importc: "winch", +proc winch*(a2: ptr WINDOW): cunsignedlong{.extdecl, importc: "winch", dynlib: pdcursesdll.} -proc winnstr*(a2: ptr WINDOW; a3: cstring; a4: cint): cint{.extdecl, +proc winnstr*(a2: ptr WINDOW; a3: cstring; a4: cint): cint{.extdecl, importc: "winnstr", dynlib: pdcursesdll.} -proc winsch*(a2: ptr WINDOW; a3: cunsignedlong): cint{.extdecl, importc: "winsch", +proc winsch*(a2: ptr WINDOW; a3: cunsignedlong): cint{.extdecl, importc: "winsch", dynlib: pdcursesdll.} -proc winsdelln*(a2: ptr WINDOW; a3: cint): cint{.extdecl, importc: "winsdelln", +proc winsdelln*(a2: ptr WINDOW; a3: cint): cint{.extdecl, importc: "winsdelln", dynlib: pdcursesdll.} -proc winsertln*(a2: ptr WINDOW): cint{.extdecl, importc: "winsertln", +proc winsertln*(a2: ptr WINDOW): cint{.extdecl, importc: "winsertln", dynlib: pdcursesdll.} -proc winsnstr*(a2: ptr WINDOW; a3: cstring; a4: cint): cint{.extdecl, +proc winsnstr*(a2: ptr WINDOW; a3: cstring; a4: cint): cint{.extdecl, importc: "winsnstr", dynlib: pdcursesdll.} -proc winsstr*(a2: ptr WINDOW; a3: cstring): cint{.extdecl, importc: "winsstr", +proc winsstr*(a2: ptr WINDOW; a3: cstring): cint{.extdecl, importc: "winsstr", dynlib: pdcursesdll.} -proc winstr*(a2: ptr WINDOW; a3: cstring): cint{.extdecl, importc: "winstr", +proc winstr*(a2: ptr WINDOW; a3: cstring): cint{.extdecl, importc: "winstr", dynlib: pdcursesdll.} -proc wmove*(a2: ptr WINDOW; a3: cint; a4: cint): cint{.extdecl, importc: "wmove", +proc wmove*(a2: ptr WINDOW; a3: cint; a4: cint): cint{.extdecl, importc: "wmove", dynlib: pdcursesdll.} -proc wnoutrefresh*(a2: ptr WINDOW): cint{.extdecl, importc: "wnoutrefresh", +proc wnoutrefresh*(a2: ptr WINDOW): cint{.extdecl, importc: "wnoutrefresh", dynlib: pdcursesdll.} -proc wprintw*(a2: ptr WINDOW; a3: cstring): cint{.varargs, extdecl, +proc wprintw*(a2: ptr WINDOW; a3: cstring): cint{.varargs, extdecl, importc: "wprintw", dynlib: pdcursesdll.} -proc wredrawln*(a2: ptr WINDOW; a3: cint; a4: cint): cint{.extdecl, +proc wredrawln*(a2: ptr WINDOW; a3: cint; a4: cint): cint{.extdecl, importc: "wredrawln", dynlib: pdcursesdll.} -proc wrefresh*(a2: ptr WINDOW): cint{.extdecl, importc: "wrefresh", +proc wrefresh*(a2: ptr WINDOW): cint{.extdecl, importc: "wrefresh", dynlib: pdcursesdll.} -proc wscanw*(a2: ptr WINDOW; a3: cstring): cint{.varargs, extdecl, +proc wscanw*(a2: ptr WINDOW; a3: cstring): cint{.varargs, extdecl, importc: "wscanw", dynlib: pdcursesdll.} -proc wscrl*(a2: ptr WINDOW; a3: cint): cint{.extdecl, importc: "wscrl", +proc wscrl*(a2: ptr WINDOW; a3: cint): cint{.extdecl, importc: "wscrl", dynlib: pdcursesdll.} -proc wsetscrreg*(a2: ptr WINDOW; a3: cint; a4: cint): cint{.extdecl, +proc wsetscrreg*(a2: ptr WINDOW; a3: cint; a4: cint): cint{.extdecl, importc: "wsetscrreg", dynlib: pdcursesdll.} -proc wstandend*(a2: ptr WINDOW): cint{.extdecl, importc: "wstandend", +proc wstandend*(a2: ptr WINDOW): cint{.extdecl, importc: "wstandend", dynlib: pdcursesdll.} -proc wstandout*(a2: ptr WINDOW): cint{.extdecl, importc: "wstandout", +proc wstandout*(a2: ptr WINDOW): cint{.extdecl, importc: "wstandout", dynlib: pdcursesdll.} -proc wsyncdown*(a2: ptr WINDOW){.extdecl, importc: "wsyncdown", +proc wsyncdown*(a2: ptr WINDOW){.extdecl, importc: "wsyncdown", dynlib: pdcursesdll.} proc wsyncup*(a2: ptr WINDOW){.extdecl, importc: "wsyncup", dynlib: pdcursesdll.} -proc wtimeout*(a2: ptr WINDOW; a3: cint){.extdecl, importc: "wtimeout", +proc wtimeout*(a2: ptr WINDOW; a3: cint){.extdecl, importc: "wtimeout", dynlib: pdcursesdll.} -proc wtouchln*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cint): cint{.extdecl, +proc wtouchln*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cint): cint{.extdecl, importc: "wtouchln", dynlib: pdcursesdll.} -proc wvline*(a2: ptr WINDOW; a3: cunsignedlong; a4: cint): cint{.extdecl, +proc wvline*(a2: ptr WINDOW; a3: cunsignedlong; a4: cint): cint{.extdecl, importc: "wvline", dynlib: pdcursesdll.} -proc addnwstr*(a2: cstring; a3: cint): cint{.extdecl, importc: "addnwstr", +proc addnwstr*(a2: cstring; a3: cint): cint{.extdecl, importc: "addnwstr", dynlib: pdcursesdll.} -proc addwstr*(a2: cstring): cint{.extdecl, importc: "addwstr", +proc addwstr*(a2: cstring): cint{.extdecl, importc: "addwstr", dynlib: pdcursesdll.} -proc add_wch*(a2: ptr cunsignedlong): cint{.extdecl, importc: "add_wch", +proc add_wch*(a2: ptr cunsignedlong): cint{.extdecl, importc: "add_wch", dynlib: pdcursesdll.} -proc add_wchnstr*(a2: ptr cunsignedlong; a3: cint): cint{.extdecl, +proc add_wchnstr*(a2: ptr cunsignedlong; a3: cint): cint{.extdecl, importc: "add_wchnstr", dynlib: pdcursesdll.} -proc add_wchstr*(a2: ptr cunsignedlong): cint{.extdecl, importc: "add_wchstr", +proc add_wchstr*(a2: ptr cunsignedlong): cint{.extdecl, importc: "add_wchstr", dynlib: pdcursesdll.} -proc border_set*(a2: ptr cunsignedlong; a3: ptr cunsignedlong; - a4: ptr cunsignedlong; a5: ptr cunsignedlong; - a6: ptr cunsignedlong; a7: ptr cunsignedlong; - a8: ptr cunsignedlong; a9: ptr cunsignedlong): cint{.extdecl, +proc border_set*(a2: ptr cunsignedlong; a3: ptr cunsignedlong; + a4: ptr cunsignedlong; a5: ptr cunsignedlong; + a6: ptr cunsignedlong; a7: ptr cunsignedlong; + a8: ptr cunsignedlong; a9: ptr cunsignedlong): cint{.extdecl, importc: "border_set", dynlib: pdcursesdll.} proc box_set*(a2: ptr WINDOW; a3: ptr cunsignedlong; a4: ptr cunsignedlong): cint{. extdecl, importc: "box_set", dynlib: pdcursesdll.} -proc echo_wchar*(a2: ptr cunsignedlong): cint{.extdecl, importc: "echo_wchar", +proc echo_wchar*(a2: ptr cunsignedlong): cint{.extdecl, importc: "echo_wchar", dynlib: pdcursesdll.} -proc erasewchar*(a2: cstring): cint{.extdecl, importc: "erasewchar", +proc erasewchar*(a2: cstring): cint{.extdecl, importc: "erasewchar", dynlib: pdcursesdll.} -proc getbkgrnd*(a2: ptr cunsignedlong): cint{.extdecl, importc: "getbkgrnd", +proc getbkgrnd*(a2: ptr cunsignedlong): cint{.extdecl, importc: "getbkgrnd", dynlib: pdcursesdll.} -proc getcchar*(a2: ptr cunsignedlong; a3: cstring; a4: ptr cunsignedlong; - a5: ptr cshort; a6: pointer): cint{.extdecl, importc: "getcchar", +proc getcchar*(a2: ptr cunsignedlong; a3: cstring; a4: ptr cunsignedlong; + a5: ptr cshort; a6: pointer): cint{.extdecl, importc: "getcchar", dynlib: pdcursesdll.} -proc getn_wstr*(a2: ptr cint; a3: cint): cint{.extdecl, importc: "getn_wstr", +proc getn_wstr*(a2: ptr cint; a3: cint): cint{.extdecl, importc: "getn_wstr", dynlib: pdcursesdll.} -proc get_wch*(a2: ptr cint): cint{.extdecl, importc: "get_wch", +proc get_wch*(a2: ptr cint): cint{.extdecl, importc: "get_wch", dynlib: pdcursesdll.} -proc get_wstr*(a2: ptr cint): cint{.extdecl, importc: "get_wstr", +proc get_wstr*(a2: ptr cint): cint{.extdecl, importc: "get_wstr", dynlib: pdcursesdll.} -proc hline_set*(a2: ptr cunsignedlong; a3: cint): cint{.extdecl, +proc hline_set*(a2: ptr cunsignedlong; a3: cint): cint{.extdecl, importc: "hline_set", dynlib: pdcursesdll.} -proc innwstr*(a2: cstring; a3: cint): cint{.extdecl, importc: "innwstr", +proc innwstr*(a2: cstring; a3: cint): cint{.extdecl, importc: "innwstr", dynlib: pdcursesdll.} -proc ins_nwstr*(a2: cstring; a3: cint): cint{.extdecl, importc: "ins_nwstr", +proc ins_nwstr*(a2: cstring; a3: cint): cint{.extdecl, importc: "ins_nwstr", dynlib: pdcursesdll.} -proc ins_wch*(a2: ptr cunsignedlong): cint{.extdecl, importc: "ins_wch", +proc ins_wch*(a2: ptr cunsignedlong): cint{.extdecl, importc: "ins_wch", dynlib: pdcursesdll.} -proc ins_wstr*(a2: cstring): cint{.extdecl, importc: "ins_wstr", +proc ins_wstr*(a2: cstring): cint{.extdecl, importc: "ins_wstr", dynlib: pdcursesdll.} -proc inwstr*(a2: cstring): cint{.extdecl, importc: "inwstr", +proc inwstr*(a2: cstring): cint{.extdecl, importc: "inwstr", dynlib: pdcursesdll.} -proc in_wch*(a2: ptr cunsignedlong): cint{.extdecl, importc: "in_wch", +proc in_wch*(a2: ptr cunsignedlong): cint{.extdecl, importc: "in_wch", dynlib: pdcursesdll.} -proc in_wchnstr*(a2: ptr cunsignedlong; a3: cint): cint{.extdecl, +proc in_wchnstr*(a2: ptr cunsignedlong; a3: cint): cint{.extdecl, importc: "in_wchnstr", dynlib: pdcursesdll.} -proc in_wchstr*(a2: ptr cunsignedlong): cint{.extdecl, importc: "in_wchstr", +proc in_wchstr*(a2: ptr cunsignedlong): cint{.extdecl, importc: "in_wchstr", dynlib: pdcursesdll.} -proc key_name*(a2: char): cstring{.extdecl, importc: "key_name", +proc key_name*(a2: char): cstring{.extdecl, importc: "key_name", dynlib: pdcursesdll.} -proc killwchar*(a2: cstring): cint{.extdecl, importc: "killwchar", +proc killwchar*(a2: cstring): cint{.extdecl, importc: "killwchar", dynlib: pdcursesdll.} -proc mvaddnwstr*(a2: cint; a3: cint; a4: cstring; a5: cint): cint{.extdecl, +proc mvaddnwstr*(a2: cint; a3: cint; a4: cstring; a5: cint): cint{.extdecl, importc: "mvaddnwstr", dynlib: pdcursesdll.} -proc mvaddwstr*(a2: cint; a3: cint; a4: cstring): cint{.extdecl, +proc mvaddwstr*(a2: cint; a3: cint; a4: cstring): cint{.extdecl, importc: "mvaddwstr", dynlib: pdcursesdll.} -proc mvadd_wch*(a2: cint; a3: cint; a4: ptr cunsignedlong): cint{.extdecl, +proc mvadd_wch*(a2: cint; a3: cint; a4: ptr cunsignedlong): cint{.extdecl, importc: "mvadd_wch", dynlib: pdcursesdll.} proc mvadd_wchnstr*(a2: cint; a3: cint; a4: ptr cunsignedlong; a5: cint): cint{. extdecl, importc: "mvadd_wchnstr", dynlib: pdcursesdll.} -proc mvadd_wchstr*(a2: cint; a3: cint; a4: ptr cunsignedlong): cint{.extdecl, +proc mvadd_wchstr*(a2: cint; a3: cint; a4: ptr cunsignedlong): cint{.extdecl, importc: "mvadd_wchstr", dynlib: pdcursesdll.} -proc mvgetn_wstr*(a2: cint; a3: cint; a4: ptr cint; a5: cint): cint{.extdecl, +proc mvgetn_wstr*(a2: cint; a3: cint; a4: ptr cint; a5: cint): cint{.extdecl, importc: "mvgetn_wstr", dynlib: pdcursesdll.} -proc mvget_wch*(a2: cint; a3: cint; a4: ptr cint): cint{.extdecl, +proc mvget_wch*(a2: cint; a3: cint; a4: ptr cint): cint{.extdecl, importc: "mvget_wch", dynlib: pdcursesdll.} -proc mvget_wstr*(a2: cint; a3: cint; a4: ptr cint): cint{.extdecl, +proc mvget_wstr*(a2: cint; a3: cint; a4: ptr cint): cint{.extdecl, importc: "mvget_wstr", dynlib: pdcursesdll.} proc mvhline_set*(a2: cint; a3: cint; a4: ptr cunsignedlong; a5: cint): cint{. extdecl, importc: "mvhline_set", dynlib: pdcursesdll.} -proc mvinnwstr*(a2: cint; a3: cint; a4: cstring; a5: cint): cint{.extdecl, +proc mvinnwstr*(a2: cint; a3: cint; a4: cstring; a5: cint): cint{.extdecl, importc: "mvinnwstr", dynlib: pdcursesdll.} -proc mvins_nwstr*(a2: cint; a3: cint; a4: cstring; a5: cint): cint{.extdecl, +proc mvins_nwstr*(a2: cint; a3: cint; a4: cstring; a5: cint): cint{.extdecl, importc: "mvins_nwstr", dynlib: pdcursesdll.} -proc mvins_wch*(a2: cint; a3: cint; a4: ptr cunsignedlong): cint{.extdecl, +proc mvins_wch*(a2: cint; a3: cint; a4: ptr cunsignedlong): cint{.extdecl, importc: "mvins_wch", dynlib: pdcursesdll.} -proc mvins_wstr*(a2: cint; a3: cint; a4: cstring): cint{.extdecl, +proc mvins_wstr*(a2: cint; a3: cint; a4: cstring): cint{.extdecl, importc: "mvins_wstr", dynlib: pdcursesdll.} -proc mvinwstr*(a2: cint; a3: cint; a4: cstring): cint{.extdecl, +proc mvinwstr*(a2: cint; a3: cint; a4: cstring): cint{.extdecl, importc: "mvinwstr", dynlib: pdcursesdll.} -proc mvin_wch*(a2: cint; a3: cint; a4: ptr cunsignedlong): cint{.extdecl, +proc mvin_wch*(a2: cint; a3: cint; a4: ptr cunsignedlong): cint{.extdecl, importc: "mvin_wch", dynlib: pdcursesdll.} proc mvin_wchnstr*(a2: cint; a3: cint; a4: ptr cunsignedlong; a5: cint): cint{. extdecl, importc: "mvin_wchnstr", dynlib: pdcursesdll.} -proc mvin_wchstr*(a2: cint; a3: cint; a4: ptr cunsignedlong): cint{.extdecl, +proc mvin_wchstr*(a2: cint; a3: cint; a4: ptr cunsignedlong): cint{.extdecl, importc: "mvin_wchstr", dynlib: pdcursesdll.} proc mvvline_set*(a2: cint; a3: cint; a4: ptr cunsignedlong; a5: cint): cint{. extdecl, importc: "mvvline_set", dynlib: pdcursesdll.} @@ -1233,8 +1242,8 @@ proc mvwaddwstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cstring): cint{. extdecl, importc: "mvwaddwstr", dynlib: pdcursesdll.} proc mvwadd_wch*(a2: ptr WINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong): cint{. extdecl, importc: "mvwadd_wch", dynlib: pdcursesdll.} -proc mvwadd_wchnstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong; - a6: cint): cint{.extdecl, importc: "mvwadd_wchnstr", +proc mvwadd_wchnstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong; + a6: cint): cint{.extdecl, importc: "mvwadd_wchnstr", dynlib: pdcursesdll.} proc mvwadd_wchstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong): cint{. extdecl, importc: "mvwadd_wchstr", dynlib: pdcursesdll.} @@ -1244,8 +1253,8 @@ proc mvwget_wch*(a2: ptr WINDOW; a3: cint; a4: cint; a5: ptr cint): cint{. extdecl, importc: "mvwget_wch", dynlib: pdcursesdll.} proc mvwget_wstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: ptr cint): cint{. extdecl, importc: "mvwget_wstr", dynlib: pdcursesdll.} -proc mvwhline_set*(a2: ptr WINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong; - a6: cint): cint{.extdecl, importc: "mvwhline_set", +proc mvwhline_set*(a2: ptr WINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong; + a6: cint): cint{.extdecl, importc: "mvwhline_set", dynlib: pdcursesdll.} proc mvwinnwstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cstring; a6: cint): cint{. extdecl, importc: "mvwinnwstr", dynlib: pdcursesdll.} @@ -1257,99 +1266,99 @@ proc mvwins_wstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cstring): cint{. extdecl, importc: "mvwins_wstr", dynlib: pdcursesdll.} proc mvwin_wch*(a2: ptr WINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong): cint{. extdecl, importc: "mvwin_wch", dynlib: pdcursesdll.} -proc mvwin_wchnstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong; - a6: cint): cint{.extdecl, importc: "mvwin_wchnstr", +proc mvwin_wchnstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong; + a6: cint): cint{.extdecl, importc: "mvwin_wchnstr", dynlib: pdcursesdll.} proc mvwin_wchstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong): cint{. extdecl, importc: "mvwin_wchstr", dynlib: pdcursesdll.} proc mvwinwstr*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cstring): cint{. extdecl, importc: "mvwinwstr", dynlib: pdcursesdll.} -proc mvwvline_set*(a2: ptr WINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong; - a6: cint): cint{.extdecl, importc: "mvwvline_set", +proc mvwvline_set*(a2: ptr WINDOW; a3: cint; a4: cint; a5: ptr cunsignedlong; + a6: cint): cint{.extdecl, importc: "mvwvline_set", dynlib: pdcursesdll.} -proc pecho_wchar*(a2: ptr WINDOW; a3: ptr cunsignedlong): cint{.extdecl, +proc pecho_wchar*(a2: ptr WINDOW; a3: ptr cunsignedlong): cint{.extdecl, importc: "pecho_wchar", dynlib: pdcursesdll.} -proc setcchar*(a2: ptr cunsignedlong; a3: cstring; a4: cunsignedlong; - a5: cshort; a6: pointer): cint{.extdecl, importc: "setcchar", +proc setcchar*(a2: ptr cunsignedlong; a3: cstring; a4: cunsignedlong; + a5: cshort; a6: pointer): cint{.extdecl, importc: "setcchar", dynlib: pdcursesdll.} -proc slk_wset*(a2: cint; a3: cstring; a4: cint): cint{.extdecl, +proc slk_wset*(a2: cint; a3: cstring; a4: cint): cint{.extdecl, importc: "slk_wset", dynlib: pdcursesdll.} -proc unget_wch*(a2: char): cint{.extdecl, importc: "unget_wch", +proc unget_wch*(a2: char): cint{.extdecl, importc: "unget_wch", dynlib: pdcursesdll.} -proc vline_set*(a2: ptr cunsignedlong; a3: cint): cint{.extdecl, +proc vline_set*(a2: ptr cunsignedlong; a3: cint): cint{.extdecl, importc: "vline_set", dynlib: pdcursesdll.} -proc waddnwstr*(a2: ptr WINDOW; a3: cstring; a4: cint): cint{.extdecl, +proc waddnwstr*(a2: ptr WINDOW; a3: cstring; a4: cint): cint{.extdecl, importc: "waddnwstr", dynlib: pdcursesdll.} -proc waddwstr*(a2: ptr WINDOW; a3: cstring): cint{.extdecl, +proc waddwstr*(a2: ptr WINDOW; a3: cstring): cint{.extdecl, importc: "waddwstr", dynlib: pdcursesdll.} -proc wadd_wch*(a2: ptr WINDOW; a3: ptr cunsignedlong): cint{.extdecl, +proc wadd_wch*(a2: ptr WINDOW; a3: ptr cunsignedlong): cint{.extdecl, importc: "wadd_wch", dynlib: pdcursesdll.} proc wadd_wchnstr*(a2: ptr WINDOW; a3: ptr cunsignedlong; a4: cint): cint{. extdecl, importc: "wadd_wchnstr", dynlib: pdcursesdll.} -proc wadd_wchstr*(a2: ptr WINDOW; a3: ptr cunsignedlong): cint{.extdecl, +proc wadd_wchstr*(a2: ptr WINDOW; a3: ptr cunsignedlong): cint{.extdecl, importc: "wadd_wchstr", dynlib: pdcursesdll.} -proc wbkgrnd*(a2: ptr WINDOW; a3: ptr cunsignedlong): cint{.extdecl, +proc wbkgrnd*(a2: ptr WINDOW; a3: ptr cunsignedlong): cint{.extdecl, importc: "wbkgrnd", dynlib: pdcursesdll.} -proc wbkgrndset*(a2: ptr WINDOW; a3: ptr cunsignedlong){.extdecl, +proc wbkgrndset*(a2: ptr WINDOW; a3: ptr cunsignedlong){.extdecl, importc: "wbkgrndset", dynlib: pdcursesdll.} -proc wborder_set*(a2: ptr WINDOW; a3: ptr cunsignedlong; a4: ptr cunsignedlong; - a5: ptr cunsignedlong; a6: ptr cunsignedlong; - a7: ptr cunsignedlong; a8: ptr cunsignedlong; - a9: ptr cunsignedlong; a10: ptr cunsignedlong): cint{.extdecl, +proc wborder_set*(a2: ptr WINDOW; a3: ptr cunsignedlong; a4: ptr cunsignedlong; + a5: ptr cunsignedlong; a6: ptr cunsignedlong; + a7: ptr cunsignedlong; a8: ptr cunsignedlong; + a9: ptr cunsignedlong; a10: ptr cunsignedlong): cint{.extdecl, importc: "wborder_set", dynlib: pdcursesdll.} -proc wecho_wchar*(a2: ptr WINDOW; a3: ptr cunsignedlong): cint{.extdecl, +proc wecho_wchar*(a2: ptr WINDOW; a3: ptr cunsignedlong): cint{.extdecl, importc: "wecho_wchar", dynlib: pdcursesdll.} -proc wgetbkgrnd*(a2: ptr WINDOW; a3: ptr cunsignedlong): cint{.extdecl, +proc wgetbkgrnd*(a2: ptr WINDOW; a3: ptr cunsignedlong): cint{.extdecl, importc: "wgetbkgrnd", dynlib: pdcursesdll.} -proc wgetn_wstr*(a2: ptr WINDOW; a3: ptr cint; a4: cint): cint{.extdecl, +proc wgetn_wstr*(a2: ptr WINDOW; a3: ptr cint; a4: cint): cint{.extdecl, importc: "wgetn_wstr", dynlib: pdcursesdll.} -proc wget_wch*(a2: ptr WINDOW; a3: ptr cint): cint{.extdecl, +proc wget_wch*(a2: ptr WINDOW; a3: ptr cint): cint{.extdecl, importc: "wget_wch", dynlib: pdcursesdll.} -proc wget_wstr*(a2: ptr WINDOW; a3: ptr cint): cint{.extdecl, +proc wget_wstr*(a2: ptr WINDOW; a3: ptr cint): cint{.extdecl, importc: "wget_wstr", dynlib: pdcursesdll.} -proc whline_set*(a2: ptr WINDOW; a3: ptr cunsignedlong; a4: cint): cint{.extdecl, +proc whline_set*(a2: ptr WINDOW; a3: ptr cunsignedlong; a4: cint): cint{.extdecl, importc: "whline_set", dynlib: pdcursesdll.} -proc winnwstr*(a2: ptr WINDOW; a3: cstring; a4: cint): cint{.extdecl, +proc winnwstr*(a2: ptr WINDOW; a3: cstring; a4: cint): cint{.extdecl, importc: "winnwstr", dynlib: pdcursesdll.} -proc wins_nwstr*(a2: ptr WINDOW; a3: cstring; a4: cint): cint{.extdecl, +proc wins_nwstr*(a2: ptr WINDOW; a3: cstring; a4: cint): cint{.extdecl, importc: "wins_nwstr", dynlib: pdcursesdll.} -proc wins_wch*(a2: ptr WINDOW; a3: ptr cunsignedlong): cint{.extdecl, +proc wins_wch*(a2: ptr WINDOW; a3: ptr cunsignedlong): cint{.extdecl, importc: "wins_wch", dynlib: pdcursesdll.} -proc wins_wstr*(a2: ptr WINDOW; a3: cstring): cint{.extdecl, +proc wins_wstr*(a2: ptr WINDOW; a3: cstring): cint{.extdecl, importc: "wins_wstr", dynlib: pdcursesdll.} -proc winwstr*(a2: ptr WINDOW; a3: cstring): cint{.extdecl, importc: "winwstr", +proc winwstr*(a2: ptr WINDOW; a3: cstring): cint{.extdecl, importc: "winwstr", dynlib: pdcursesdll.} -proc win_wch*(a2: ptr WINDOW; a3: ptr cunsignedlong): cint{.extdecl, +proc win_wch*(a2: ptr WINDOW; a3: ptr cunsignedlong): cint{.extdecl, importc: "win_wch", dynlib: pdcursesdll.} -proc win_wchnstr*(a2: ptr WINDOW; a3: ptr cunsignedlong; a4: cint): cint{.extdecl, +proc win_wchnstr*(a2: ptr WINDOW; a3: ptr cunsignedlong; a4: cint): cint{.extdecl, importc: "win_wchnstr", dynlib: pdcursesdll.} -proc win_wchstr*(a2: ptr WINDOW; a3: ptr cunsignedlong): cint{.extdecl, +proc win_wchstr*(a2: ptr WINDOW; a3: ptr cunsignedlong): cint{.extdecl, importc: "win_wchstr", dynlib: pdcursesdll.} -proc wunctrl*(a2: ptr cunsignedlong): cstring{.extdecl, importc: "wunctrl", +proc wunctrl*(a2: ptr cunsignedlong): cstring{.extdecl, importc: "wunctrl", dynlib: pdcursesdll.} -proc wvline_set*(a2: ptr WINDOW; a3: ptr cunsignedlong; a4: cint): cint{.extdecl, +proc wvline_set*(a2: ptr WINDOW; a3: ptr cunsignedlong; a4: cint): cint{.extdecl, importc: "wvline_set", dynlib: pdcursesdll.} -proc getattrs*(a2: ptr WINDOW): cunsignedlong{.extdecl, importc: "getattrs", +proc getattrs*(a2: ptr WINDOW): cunsignedlong{.extdecl, importc: "getattrs", dynlib: pdcursesdll.} -proc getbegx*(a2: ptr WINDOW): cint{.extdecl, importc: "getbegx", +proc getbegx*(a2: ptr WINDOW): cint{.extdecl, importc: "getbegx", dynlib: pdcursesdll.} -proc getbegy*(a2: ptr WINDOW): cint{.extdecl, importc: "getbegy", +proc getbegy*(a2: ptr WINDOW): cint{.extdecl, importc: "getbegy", dynlib: pdcursesdll.} -proc getmaxx*(a2: ptr WINDOW): cint{.extdecl, importc: "getmaxx", +proc getmaxx*(a2: ptr WINDOW): cint{.extdecl, importc: "getmaxx", dynlib: pdcursesdll.} -proc getmaxy*(a2: ptr WINDOW): cint{.extdecl, importc: "getmaxy", +proc getmaxy*(a2: ptr WINDOW): cint{.extdecl, importc: "getmaxy", dynlib: pdcursesdll.} -proc getparx*(a2: ptr WINDOW): cint{.extdecl, importc: "getparx", +proc getparx*(a2: ptr WINDOW): cint{.extdecl, importc: "getparx", dynlib: pdcursesdll.} -proc getpary*(a2: ptr WINDOW): cint{.extdecl, importc: "getpary", +proc getpary*(a2: ptr WINDOW): cint{.extdecl, importc: "getpary", dynlib: pdcursesdll.} -proc getcurx*(a2: ptr WINDOW): cint{.extdecl, importc: "getcurx", +proc getcurx*(a2: ptr WINDOW): cint{.extdecl, importc: "getcurx", dynlib: pdcursesdll.} -proc getcury*(a2: ptr WINDOW): cint{.extdecl, importc: "getcury", +proc getcury*(a2: ptr WINDOW): cint{.extdecl, importc: "getcury", dynlib: pdcursesdll.} proc traceoff*(){.extdecl, importc: "traceoff", dynlib: pdcursesdll.} proc traceon*(){.extdecl, importc: "traceon", dynlib: pdcursesdll.} -proc unctrl*(a2: cunsignedlong): cstring{.extdecl, importc: "unctrl", +proc unctrl*(a2: cunsignedlong): cstring{.extdecl, importc: "unctrl", dynlib: pdcursesdll.} proc crmode*(): cint{.extdecl, importc: "crmode", dynlib: pdcursesdll.} proc nocrmode*(): cint{.extdecl, importc: "nocrmode", dynlib: pdcursesdll.} @@ -1357,156 +1366,156 @@ proc draino*(a2: cint): cint{.extdecl, importc: "draino", dynlib: pdcursesdll.} proc resetterm*(): cint{.extdecl, importc: "resetterm", dynlib: pdcursesdll.} proc fixterm*(): cint{.extdecl, importc: "fixterm", dynlib: pdcursesdll.} proc saveterm*(): cint{.extdecl, importc: "saveterm", dynlib: pdcursesdll.} -proc setsyx*(a2: cint; a3: cint): cint{.extdecl, importc: "setsyx", +proc setsyx*(a2: cint; a3: cint): cint{.extdecl, importc: "setsyx", dynlib: pdcursesdll.} -proc mouse_set*(a2: cunsignedlong): cint{.extdecl, importc: "mouse_set", +proc mouse_set*(a2: cunsignedlong): cint{.extdecl, importc: "mouse_set", dynlib: pdcursesdll.} -proc mouse_on*(a2: cunsignedlong): cint{.extdecl, importc: "mouse_on", +proc mouse_on*(a2: cunsignedlong): cint{.extdecl, importc: "mouse_on", dynlib: pdcursesdll.} -proc mouse_off*(a2: cunsignedlong): cint{.extdecl, importc: "mouse_off", +proc mouse_off*(a2: cunsignedlong): cint{.extdecl, importc: "mouse_off", dynlib: pdcursesdll.} -proc request_mouse_pos*(): cint{.extdecl, importc: "request_mouse_pos", +proc request_mouse_pos*(): cint{.extdecl, importc: "request_mouse_pos", dynlib: pdcursesdll.} -proc map_button*(a2: cunsignedlong): cint{.extdecl, importc: "map_button", +proc map_button*(a2: cunsignedlong): cint{.extdecl, importc: "map_button", dynlib: pdcursesdll.} -proc wmouse_position*(a2: ptr WINDOW; a3: ptr cint; a4: ptr cint){.extdecl, +proc wmouse_position*(a2: ptr WINDOW; a3: ptr cint; a4: ptr cint){.extdecl, importc: "wmouse_position", dynlib: pdcursesdll.} proc getmouse*(): cunsignedlong{.extdecl, importc: "getmouse", dynlib: pdcursesdll.} proc getbmap*(): cunsignedlong{.extdecl, importc: "getbmap", dynlib: pdcursesdll.} -proc assume_default_colors*(a2: cint; a3: cint): cint{.extdecl, +proc assume_default_colors*(a2: cint; a3: cint): cint{.extdecl, importc: "assume_default_colors", dynlib: pdcursesdll.} -proc curses_version*(): cstring{.extdecl, importc: "curses_version", +proc curses_version*(): cstring{.extdecl, importc: "curses_version", dynlib: pdcursesdll.} -proc has_key*(a2: cint): cunsignedchar{.extdecl, importc: "has_key", +proc has_key*(a2: cint): cunsignedchar{.extdecl, importc: "has_key", dynlib: pdcursesdll.} -proc use_default_colors*(): cint{.extdecl, importc: "use_default_colors", +proc use_default_colors*(): cint{.extdecl, importc: "use_default_colors", dynlib: pdcursesdll.} -proc wresize*(a2: ptr WINDOW; a3: cint; a4: cint): cint{.extdecl, +proc wresize*(a2: ptr WINDOW; a3: cint; a4: cint): cint{.extdecl, importc: "wresize", dynlib: pdcursesdll.} -proc mouseinterval*(a2: cint): cint{.extdecl, importc: "mouseinterval", +proc mouseinterval*(a2: cint): cint{.extdecl, importc: "mouseinterval", dynlib: pdcursesdll.} -proc mousemask*(a2: cunsignedlong; a3: ptr cunsignedlong): cunsignedlong{.extdecl, +proc mousemask*(a2: cunsignedlong; a3: ptr cunsignedlong): cunsignedlong{.extdecl, importc: "mousemask", dynlib: pdcursesdll.} proc mouse_trafo*(a2: ptr cint; a3: ptr cint; a4: cunsignedchar): cunsignedchar{. extdecl, importc: "mouse_trafo", dynlib: pdcursesdll.} -proc nc_getmouse*(a2: ptr MEVENT): cint{.extdecl, importc: "nc_getmouse", +proc nc_getmouse*(a2: ptr MEVENT): cint{.extdecl, importc: "nc_getmouse", dynlib: pdcursesdll.} -proc ungetmouse*(a2: ptr MEVENT): cint{.extdecl, importc: "ungetmouse", +proc ungetmouse*(a2: ptr MEVENT): cint{.extdecl, importc: "ungetmouse", dynlib: pdcursesdll.} -proc wenclose*(a2: ptr WINDOW; a3: cint; a4: cint): cunsignedchar{.extdecl, +proc wenclose*(a2: ptr WINDOW; a3: cint; a4: cint): cunsignedchar{.extdecl, importc: "wenclose", dynlib: pdcursesdll.} proc wmouse_trafo*(a2: ptr WINDOW; a3: ptr cint; a4: ptr cint; a5: cunsignedchar): cunsignedchar{. extdecl, importc: "wmouse_trafo", dynlib: pdcursesdll.} -proc addrawch*(a2: cunsignedlong): cint{.extdecl, importc: "addrawch", +proc addrawch*(a2: cunsignedlong): cint{.extdecl, importc: "addrawch", dynlib: pdcursesdll.} -proc insrawch*(a2: cunsignedlong): cint{.extdecl, importc: "insrawch", +proc insrawch*(a2: cunsignedlong): cint{.extdecl, importc: "insrawch", dynlib: pdcursesdll.} -proc is_termresized*(): cunsignedchar{.extdecl, importc: "is_termresized", +proc is_termresized*(): cunsignedchar{.extdecl, importc: "is_termresized", dynlib: pdcursesdll.} -proc mvaddrawch*(a2: cint; a3: cint; a4: cunsignedlong): cint{.extdecl, +proc mvaddrawch*(a2: cint; a3: cint; a4: cunsignedlong): cint{.extdecl, importc: "mvaddrawch", dynlib: pdcursesdll.} -proc mvdeleteln*(a2: cint; a3: cint): cint{.extdecl, importc: "mvdeleteln", +proc mvdeleteln*(a2: cint; a3: cint): cint{.extdecl, importc: "mvdeleteln", dynlib: pdcursesdll.} -proc mvinsertln*(a2: cint; a3: cint): cint{.extdecl, importc: "mvinsertln", +proc mvinsertln*(a2: cint; a3: cint): cint{.extdecl, importc: "mvinsertln", dynlib: pdcursesdll.} -proc mvinsrawch*(a2: cint; a3: cint; a4: cunsignedlong): cint{.extdecl, +proc mvinsrawch*(a2: cint; a3: cint; a4: cunsignedlong): cint{.extdecl, importc: "mvinsrawch", dynlib: pdcursesdll.} proc mvwaddrawch*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cunsignedlong): cint{. extdecl, importc: "mvwaddrawch", dynlib: pdcursesdll.} -proc mvwdeleteln*(a2: ptr WINDOW; a3: cint; a4: cint): cint{.extdecl, +proc mvwdeleteln*(a2: ptr WINDOW; a3: cint; a4: cint): cint{.extdecl, importc: "mvwdeleteln", dynlib: pdcursesdll.} -proc mvwinsertln*(a2: ptr WINDOW; a3: cint; a4: cint): cint{.extdecl, +proc mvwinsertln*(a2: ptr WINDOW; a3: cint; a4: cint): cint{.extdecl, importc: "mvwinsertln", dynlib: pdcursesdll.} proc mvwinsrawch*(a2: ptr WINDOW; a3: cint; a4: cint; a5: cunsignedlong): cint{. extdecl, importc: "mvwinsrawch", dynlib: pdcursesdll.} -proc raw_output*(a2: cunsignedchar): cint{.extdecl, importc: "raw_output", +proc raw_output*(a2: cunsignedchar): cint{.extdecl, importc: "raw_output", dynlib: pdcursesdll.} -proc resize_term*(a2: cint; a3: cint): cint{.extdecl, importc: "resize_term", +proc resize_term*(a2: cint; a3: cint): cint{.extdecl, importc: "resize_term", dynlib: pdcursesdll.} -proc resize_window*(a2: ptr WINDOW; a3: cint; a4: cint): ptr WINDOW{.extdecl, +proc resize_window*(a2: ptr WINDOW; a3: cint; a4: cint): ptr WINDOW{.extdecl, importc: "resize_window", dynlib: pdcursesdll.} -proc waddrawch*(a2: ptr WINDOW; a3: cunsignedlong): cint{.extdecl, +proc waddrawch*(a2: ptr WINDOW; a3: cunsignedlong): cint{.extdecl, importc: "waddrawch", dynlib: pdcursesdll.} -proc winsrawch*(a2: ptr WINDOW; a3: cunsignedlong): cint{.extdecl, +proc winsrawch*(a2: ptr WINDOW; a3: cunsignedlong): cint{.extdecl, importc: "winsrawch", dynlib: pdcursesdll.} proc wordchar*(): char{.extdecl, importc: "wordchar", dynlib: pdcursesdll.} -proc slk_wlabel*(a2: cint): cstring{.extdecl, importc: "slk_wlabel", +proc slk_wlabel*(a2: cint): cstring{.extdecl, importc: "slk_wlabel", dynlib: pdcursesdll.} -proc debug*(a2: cstring){.varargs, extdecl, importc: "PDC_debug", +proc debug*(a2: cstring){.varargs, extdecl, importc: "PDC_debug", dynlib: pdcursesdll.} -proc ungetch*(a2: cint): cint{.extdecl, importc: "PDC_ungetch", +proc ungetch*(a2: cint): cint{.extdecl, importc: "PDC_ungetch", dynlib: pdcursesdll.} -proc set_blink*(a2: cunsignedchar): cint{.extdecl, importc: "PDC_set_blink", +proc set_blink*(a2: cunsignedchar): cint{.extdecl, importc: "PDC_set_blink", dynlib: pdcursesdll.} -proc set_line_color*(a2: cshort): cint{.extdecl, importc: "PDC_set_line_color", +proc set_line_color*(a2: cshort): cint{.extdecl, importc: "PDC_set_line_color", dynlib: pdcursesdll.} -proc set_title*(a2: cstring){.extdecl, importc: "PDC_set_title", +proc set_title*(a2: cstring){.extdecl, importc: "PDC_set_title", dynlib: pdcursesdll.} -proc clearclipboard*(): cint{.extdecl, importc: "PDC_clearclipboard", +proc clearclipboard*(): cint{.extdecl, importc: "PDC_clearclipboard", dynlib: pdcursesdll.} -proc freeclipboard*(a2: cstring): cint{.extdecl, importc: "PDC_freeclipboard", +proc freeclipboard*(a2: cstring): cint{.extdecl, importc: "PDC_freeclipboard", dynlib: pdcursesdll.} -proc getclipboard*(a2: cstringArray; a3: ptr clong): cint{.extdecl, +proc getclipboard*(a2: cstringArray; a3: ptr clong): cint{.extdecl, importc: "PDC_getclipboard", dynlib: pdcursesdll.} -proc setclipboard*(a2: cstring; a3: clong): cint{.extdecl, +proc setclipboard*(a2: cstring; a3: clong): cint{.extdecl, importc: "PDC_setclipboard", dynlib: pdcursesdll.} -proc get_input_fd*(): cunsignedlong{.extdecl, importc: "PDC_get_input_fd", +proc get_input_fd*(): cunsignedlong{.extdecl, importc: "PDC_get_input_fd", dynlib: pdcursesdll.} -proc get_key_modifiers*(): cunsignedlong{.extdecl, +proc get_key_modifiers*(): cunsignedlong{.extdecl, importc: "PDC_get_key_modifiers", dynlib: pdcursesdll.} -proc return_key_modifiers*(a2: cunsignedchar): cint{.extdecl, +proc return_key_modifiers*(a2: cunsignedchar): cint{.extdecl, importc: "PDC_return_key_modifiers", dynlib: pdcursesdll.} -proc save_key_modifiers*(a2: cunsignedchar): cint{.extdecl, +proc save_key_modifiers*(a2: cunsignedchar): cint{.extdecl, importc: "PDC_save_key_modifiers", dynlib: pdcursesdll.} -proc bottom_panel*(pan: ptr PANEL): cint{.extdecl, importc: "bottom_panel", +proc bottom_panel*(pan: ptr PANEL): cint{.extdecl, importc: "bottom_panel", dynlib: pdcursesdll.} -proc del_panel*(pan: ptr PANEL): cint{.extdecl, importc: "del_panel", +proc del_panel*(pan: ptr PANEL): cint{.extdecl, importc: "del_panel", dynlib: pdcursesdll.} -proc hide_panel*(pan: ptr PANEL): cint{.extdecl, importc: "hide_panel", +proc hide_panel*(pan: ptr PANEL): cint{.extdecl, importc: "hide_panel", dynlib: pdcursesdll.} -proc move_panel*(pan: ptr PANEL; starty: cint; startx: cint): cint{.extdecl, +proc move_panel*(pan: ptr PANEL; starty: cint; startx: cint): cint{.extdecl, importc: "move_panel", dynlib: pdcursesdll.} -proc new_panel*(win: ptr WINDOW): ptr PANEL{.extdecl, importc: "new_panel", +proc new_panel*(win: ptr WINDOW): ptr PANEL{.extdecl, importc: "new_panel", dynlib: pdcursesdll.} -proc panel_above*(pan: ptr PANEL): ptr PANEL{.extdecl, importc: "panel_above", +proc panel_above*(pan: ptr PANEL): ptr PANEL{.extdecl, importc: "panel_above", dynlib: pdcursesdll.} -proc panel_below*(pan: ptr PANEL): ptr PANEL{.extdecl, importc: "panel_below", +proc panel_below*(pan: ptr PANEL): ptr PANEL{.extdecl, importc: "panel_below", dynlib: pdcursesdll.} -proc panel_hidden*(pan: ptr PANEL): cint{.extdecl, importc: "panel_hidden", +proc panel_hidden*(pan: ptr PANEL): cint{.extdecl, importc: "panel_hidden", dynlib: pdcursesdll.} -proc panel_userptr*(pan: ptr PANEL): pointer{.extdecl, importc: "panel_userptr", +proc panel_userptr*(pan: ptr PANEL): pointer{.extdecl, importc: "panel_userptr", dynlib: pdcursesdll.} -proc panel_window*(pan: ptr PANEL): ptr WINDOW{.extdecl, importc: "panel_window", +proc panel_window*(pan: ptr PANEL): ptr WINDOW{.extdecl, importc: "panel_window", dynlib: pdcursesdll.} -proc replace_panel*(pan: ptr PANEL; win: ptr WINDOW): cint{.extdecl, +proc replace_panel*(pan: ptr PANEL; win: ptr WINDOW): cint{.extdecl, importc: "replace_panel", dynlib: pdcursesdll.} -proc set_panel_userptr*(pan: ptr PANEL; uptr: pointer): cint{.extdecl, +proc set_panel_userptr*(pan: ptr PANEL; uptr: pointer): cint{.extdecl, importc: "set_panel_userptr", dynlib: pdcursesdll.} -proc show_panel*(pan: ptr PANEL): cint{.extdecl, importc: "show_panel", +proc show_panel*(pan: ptr PANEL): cint{.extdecl, importc: "show_panel", dynlib: pdcursesdll.} -proc top_panel*(pan: ptr PANEL): cint{.extdecl, importc: "top_panel", +proc top_panel*(pan: ptr PANEL): cint{.extdecl, importc: "top_panel", dynlib: pdcursesdll.} proc update_panels*(){.extdecl, importc: "update_panels", dynlib: pdcursesdll.} when unixOS: - proc Xinitscr*(a2: cint; a3: cstringArray): ptr WINDOW{.extdecl, + proc Xinitscr*(a2: cint; a3: cstringArray): ptr WINDOW{.extdecl, importc: "Xinitscr", dynlib: pdcursesdll.} proc XCursesExit*(){.extdecl, importc: "XCursesExit", dynlib: pdcursesdll.} proc sb_init*(): cint{.extdecl, importc: "sb_init", dynlib: pdcursesdll.} - proc sb_set_horz*(a2: cint; a3: cint; a4: cint): cint{.extdecl, + proc sb_set_horz*(a2: cint; a3: cint; a4: cint): cint{.extdecl, importc: "sb_set_horz", dynlib: pdcursesdll.} - proc sb_set_vert*(a2: cint; a3: cint; a4: cint): cint{.extdecl, + proc sb_set_vert*(a2: cint; a3: cint; a4: cint): cint{.extdecl, importc: "sb_set_vert", dynlib: pdcursesdll.} - proc sb_get_horz*(a2: ptr cint; a3: ptr cint; a4: ptr cint): cint{.extdecl, + proc sb_get_horz*(a2: ptr cint; a3: ptr cint; a4: ptr cint): cint{.extdecl, importc: "sb_get_horz", dynlib: pdcursesdll.} - proc sb_get_vert*(a2: ptr cint; a3: ptr cint; a4: ptr cint): cint{.extdecl, + proc sb_get_vert*(a2: ptr cint; a3: ptr cint; a4: ptr cint): cint{.extdecl, importc: "sb_get_vert", dynlib: pdcursesdll.} proc sb_refresh*(): cint{.extdecl, importc: "sb_refresh", dynlib: pdcursesdll.} -template getch*(): expr = +template getch*(): expr = wgetch(stdscr) -template ungetch*(ch: expr): expr = +template ungetch*(ch: expr): expr = ungetch(ch) template getbegyx*(w, y, x: expr): expr = @@ -1525,13 +1534,13 @@ template getyx*(w, y, x: expr): expr = y = getcury(w) x = getcurx(w) -template getsyx*(y, x: expr): stmt = +template getsyx*(y, x: expr): stmt = if curscr.leaveit: (x) = - 1 (y) = (x) else: getyx(curscr, (y), (x)) - -template getmouse*(x: expr): expr = + +template getmouse*(x: expr): expr = nc_getmouse(x) when defined(windows): @@ -1541,5 +1550,5 @@ when defined(windows): con_in*{.importc: "pdc_con_in", dynlib: pdcursesdll.}: HANDLE quick_edit*{.importc: "pdc_quick_edit", dynlib: pdcursesdll.}: DWORD - proc get_buffer_rows*(): cint{.extdecl, importc: "PDC_get_buffer_rows", + proc get_buffer_rows*(): cint{.extdecl, importc: "PDC_get_buffer_rows", dynlib: pdcursesdll.} diff --git a/lib/wrappers/postgres.nim b/lib/wrappers/postgres.nim index 3c35bc590..f9a10dccb 100644 --- a/lib/wrappers/postgres.nim +++ b/lib/wrappers/postgres.nim @@ -1,3 +1,12 @@ +# +# +# Nim's Runtime Library +# (c) Copyright 2015 Andreas Rumpf +# +# See the file "copying.txt", included in this +# distribution, for details about the copyright. +# + # This module contains the definitions for structures and externs for # functions used by frontend postgres applications. It is based on # Postgresql's libpq-fe.h. @@ -8,43 +17,43 @@ {.deadCodeElim: on.} -when defined(windows): - const +when defined(windows): + const dllName = "libpq.dll" -elif defined(macosx): - const +elif defined(macosx): + const dllName = "libpq.dylib" -else: - const +else: + const dllName = "libpq.so(.5|)" -type +type POid* = ptr Oid Oid* = int32 -const +const ERROR_MSG_LENGTH* = 4096 CMDSTATUS_LEN* = 40 -type +type SockAddr* = array[1..112, int8] - PGresAttDesc*{.pure, final.} = object + PGresAttDesc*{.pure, final.} = object name*: cstring adtid*: Oid adtsize*: int PPGresAttDesc* = ptr PGresAttDesc PPPGresAttDesc* = ptr PPGresAttDesc - PGresAttValue*{.pure, final.} = object + PGresAttValue*{.pure, final.} = object length*: int32 value*: cstring PPGresAttValue* = ptr PGresAttValue PPPGresAttValue* = ptr PPGresAttValue PExecStatusType* = ptr ExecStatusType - ExecStatusType* = enum - PGRES_EMPTY_QUERY = 0, PGRES_COMMAND_OK, PGRES_TUPLES_OK, PGRES_COPY_OUT, + ExecStatusType* = enum + PGRES_EMPTY_QUERY = 0, PGRES_COMMAND_OK, PGRES_TUPLES_OK, PGRES_COPY_OUT, PGRES_COPY_IN, PGRES_BAD_RESPONSE, PGRES_NONFATAL_ERROR, PGRES_FATAL_ERROR - PGlobjfuncs*{.pure, final.} = object + PGlobjfuncs*{.pure, final.} = object fn_lo_open*: Oid fn_lo_close*: Oid fn_lo_creat*: Oid @@ -56,11 +65,11 @@ type PPGlobjfuncs* = ptr PGlobjfuncs PConnStatusType* = ptr ConnStatusType - ConnStatusType* = enum - CONNECTION_OK, CONNECTION_BAD, CONNECTION_STARTED, CONNECTION_MADE, - CONNECTION_AWAITING_RESPONSE, CONNECTION_AUTH_OK, CONNECTION_SETENV, + ConnStatusType* = enum + CONNECTION_OK, CONNECTION_BAD, CONNECTION_STARTED, CONNECTION_MADE, + CONNECTION_AWAITING_RESPONSE, CONNECTION_AUTH_OK, CONNECTION_SETENV, CONNECTION_SSL_STARTUP, CONNECTION_NEEDED - PGconn*{.pure, final.} = object + PGconn*{.pure, final.} = object pghost*: cstring pgtty*: cstring pgport*: cstring @@ -82,7 +91,7 @@ type lobjfuncs*: PPGlobjfuncs PPGconn* = ptr PGconn - PGresult*{.pure, final.} = object + PGresult*{.pure, final.} = object ntups*: int32 numAttributes*: int32 attDescs*: PPGresAttDesc @@ -95,18 +104,18 @@ type PPGresult* = ptr PGresult PPostgresPollingStatusType* = ptr PostgresPollingStatusType - PostgresPollingStatusType* = enum - PGRES_POLLING_FAILED = 0, PGRES_POLLING_READING, PGRES_POLLING_WRITING, + PostgresPollingStatusType* = enum + PGRES_POLLING_FAILED = 0, PGRES_POLLING_READING, PGRES_POLLING_WRITING, PGRES_POLLING_OK, PGRES_POLLING_ACTIVE PPGTransactionStatusType* = ptr PGTransactionStatusType - PGTransactionStatusType* = enum - PQTRANS_IDLE, PQTRANS_ACTIVE, PQTRANS_INTRANS, PQTRANS_INERROR, + PGTransactionStatusType* = enum + PQTRANS_IDLE, PQTRANS_ACTIVE, PQTRANS_INTRANS, PQTRANS_INERROR, PQTRANS_UNKNOWN PPGVerbosity* = ptr PGVerbosity - PGVerbosity* = enum + PGVerbosity* = enum PQERRORS_TERSE, PQERRORS_DEFAULT, PQERRORS_VERBOSE PpgNotify* = ptr pgNotify - pgNotify*{.pure, final.} = object + pgNotify*{.pure, final.} = object relname*: cstring be_pid*: int32 extra*: cstring @@ -116,7 +125,7 @@ type Ppqbool* = ptr pqbool pqbool* = char P_PQprintOpt* = ptr PQprintOpt - PQprintOpt*{.pure, final.} = object + PQprintOpt*{.pure, final.} = object header*: pqbool align*: pqbool standard*: pqbool @@ -129,7 +138,7 @@ type fieldName*: ptr cstring P_PQconninfoOption* = ptr PQconninfoOption - PQconninfoOption*{.pure, final.} = object + PQconninfoOption*{.pure, final.} = object keyword*: cstring envvar*: cstring compiled*: cstring @@ -139,7 +148,7 @@ type dispsize*: int32 PPQArgBlock* = ptr PQArgBlock - PQArgBlock*{.pure, final.} = object + PQArgBlock*{.pure, final.} = object length*: int32 isint*: int32 p*: pointer @@ -148,27 +157,27 @@ type TPGlobjfuncs: Pglobjfuncs, TConnStatusType: ConnStatusType, TPGconn: Pgconn, TPGresult: PGresult].} -proc pqconnectStart*(conninfo: cstring): PPGconn{.cdecl, dynlib: dllName, +proc pqconnectStart*(conninfo: cstring): PPGconn{.cdecl, dynlib: dllName, importc: "PQconnectStart".} -proc pqconnectPoll*(conn: PPGconn): PostgresPollingStatusType{.cdecl, +proc pqconnectPoll*(conn: PPGconn): PostgresPollingStatusType{.cdecl, dynlib: dllName, importc: "PQconnectPoll".} -proc pqconnectdb*(conninfo: cstring): PPGconn{.cdecl, dynlib: dllName, +proc pqconnectdb*(conninfo: cstring): PPGconn{.cdecl, dynlib: dllName, importc: "PQconnectdb".} -proc pqsetdbLogin*(pghost: cstring, pgport: cstring, pgoptions: cstring, +proc pqsetdbLogin*(pghost: cstring, pgport: cstring, pgoptions: cstring, pgtty: cstring, dbName: cstring, login: cstring, pwd: cstring): PPGconn{. cdecl, dynlib: dllName, importc: "PQsetdbLogin".} proc pqsetdb*(M_PGHOST, M_PGPORT, M_PGOPT, M_PGTTY, M_DBNAME: cstring): Ppgconn proc pqfinish*(conn: PPGconn){.cdecl, dynlib: dllName, importc: "PQfinish".} -proc pqconndefaults*(): PPQconninfoOption{.cdecl, dynlib: dllName, +proc pqconndefaults*(): PPQconninfoOption{.cdecl, dynlib: dllName, importc: "PQconndefaults".} -proc pqconninfoFree*(connOptions: PPQconninfoOption){.cdecl, dynlib: dllName, +proc pqconninfoFree*(connOptions: PPQconninfoOption){.cdecl, dynlib: dllName, importc: "PQconninfoFree".} -proc pqresetStart*(conn: PPGconn): int32{.cdecl, dynlib: dllName, +proc pqresetStart*(conn: PPGconn): int32{.cdecl, dynlib: dllName, importc: "PQresetStart".} -proc pqresetPoll*(conn: PPGconn): PostgresPollingStatusType{.cdecl, +proc pqresetPoll*(conn: PPGconn): PostgresPollingStatusType{.cdecl, dynlib: dllName, importc: "PQresetPoll".} proc pqreset*(conn: PPGconn){.cdecl, dynlib: dllName, importc: "PQreset".} -proc pqrequestCancel*(conn: PPGconn): int32{.cdecl, dynlib: dllName, +proc pqrequestCancel*(conn: PPGconn): int32{.cdecl, dynlib: dllName, importc: "PQrequestCancel".} proc pqdb*(conn: PPGconn): cstring{.cdecl, dynlib: dllName, importc: "PQdb".} proc pquser*(conn: PPGconn): cstring{.cdecl, dynlib: dllName, importc: "PQuser".} @@ -176,44 +185,44 @@ proc pqpass*(conn: PPGconn): cstring{.cdecl, dynlib: dllName, importc: "PQpass". proc pqhost*(conn: PPGconn): cstring{.cdecl, dynlib: dllName, importc: "PQhost".} proc pqport*(conn: PPGconn): cstring{.cdecl, dynlib: dllName, importc: "PQport".} proc pqtty*(conn: PPGconn): cstring{.cdecl, dynlib: dllName, importc: "PQtty".} -proc pqoptions*(conn: PPGconn): cstring{.cdecl, dynlib: dllName, +proc pqoptions*(conn: PPGconn): cstring{.cdecl, dynlib: dllName, importc: "PQoptions".} -proc pqstatus*(conn: PPGconn): ConnStatusType{.cdecl, dynlib: dllName, +proc pqstatus*(conn: PPGconn): ConnStatusType{.cdecl, dynlib: dllName, importc: "PQstatus".} -proc pqtransactionStatus*(conn: PPGconn): PGTransactionStatusType{.cdecl, +proc pqtransactionStatus*(conn: PPGconn): PGTransactionStatusType{.cdecl, dynlib: dllName, importc: "PQtransactionStatus".} -proc pqparameterStatus*(conn: PPGconn, paramName: cstring): cstring{.cdecl, +proc pqparameterStatus*(conn: PPGconn, paramName: cstring): cstring{.cdecl, dynlib: dllName, importc: "PQparameterStatus".} -proc pqprotocolVersion*(conn: PPGconn): int32{.cdecl, dynlib: dllName, +proc pqprotocolVersion*(conn: PPGconn): int32{.cdecl, dynlib: dllName, importc: "PQprotocolVersion".} -proc pqerrorMessage*(conn: PPGconn): cstring{.cdecl, dynlib: dllName, +proc pqerrorMessage*(conn: PPGconn): cstring{.cdecl, dynlib: dllName, importc: "PQerrorMessage".} -proc pqsocket*(conn: PPGconn): int32{.cdecl, dynlib: dllName, +proc pqsocket*(conn: PPGconn): int32{.cdecl, dynlib: dllName, importc: "PQsocket".} -proc pqbackendPID*(conn: PPGconn): int32{.cdecl, dynlib: dllName, +proc pqbackendPID*(conn: PPGconn): int32{.cdecl, dynlib: dllName, importc: "PQbackendPID".} -proc pqclientEncoding*(conn: PPGconn): int32{.cdecl, dynlib: dllName, +proc pqclientEncoding*(conn: PPGconn): int32{.cdecl, dynlib: dllName, importc: "PQclientEncoding".} -proc pqsetClientEncoding*(conn: PPGconn, encoding: cstring): int32{.cdecl, +proc pqsetClientEncoding*(conn: PPGconn, encoding: cstring): int32{.cdecl, dynlib: dllName, importc: "PQsetClientEncoding".} -when defined(USE_SSL): - # Get the SSL structure associated with a connection - proc pqgetssl*(conn: PPGconn): PSSL{.cdecl, dynlib: dllName, +when defined(USE_SSL): + # Get the SSL structure associated with a connection + proc pqgetssl*(conn: PPGconn): PSSL{.cdecl, dynlib: dllName, importc: "PQgetssl".} proc pqsetErrorVerbosity*(conn: PPGconn, verbosity: PGVerbosity): PGVerbosity{. cdecl, dynlib: dllName, importc: "PQsetErrorVerbosity".} -proc pqtrace*(conn: PPGconn, debug_port: File){.cdecl, dynlib: dllName, +proc pqtrace*(conn: PPGconn, debug_port: File){.cdecl, dynlib: dllName, importc: "PQtrace".} proc pquntrace*(conn: PPGconn){.cdecl, dynlib: dllName, importc: "PQuntrace".} proc pqsetNoticeReceiver*(conn: PPGconn, theProc: PQnoticeReceiver, arg: pointer): PQnoticeReceiver{. cdecl, dynlib: dllName, importc: "PQsetNoticeReceiver".} -proc pqsetNoticeProcessor*(conn: PPGconn, theProc: PQnoticeProcessor, - arg: pointer): PQnoticeProcessor{.cdecl, +proc pqsetNoticeProcessor*(conn: PPGconn, theProc: PQnoticeProcessor, + arg: pointer): PQnoticeProcessor{.cdecl, dynlib: dllName, importc: "PQsetNoticeProcessor".} -proc pqexec*(conn: PPGconn, query: cstring): PPGresult{.cdecl, dynlib: dllName, +proc pqexec*(conn: PPGconn, query: cstring): PPGresult{.cdecl, dynlib: dllName, importc: "PQexec".} -proc pqexecParams*(conn: PPGconn, command: cstring, nParams: int32, - paramTypes: POid, paramValues: cstringArray, +proc pqexecParams*(conn: PPGconn, command: cstring, nParams: int32, + paramTypes: POid, paramValues: cstringArray, paramLengths, paramFormats: ptr int32, resultFormat: int32): PPGresult{. cdecl, dynlib: dllName, importc: "PQexecParams".} proc pqprepare*(conn: PPGconn, stmtName, query: cstring, nParams: int32, @@ -222,87 +231,87 @@ proc pqexecPrepared*(conn: PPGconn, stmtName: cstring, nParams: int32, paramValues: cstringArray, paramLengths, paramFormats: ptr int32, resultFormat: int32): PPGresult{. cdecl, dynlib: dllName, importc: "PQexecPrepared".} -proc pqsendQuery*(conn: PPGconn, query: cstring): int32{.cdecl, dynlib: dllName, +proc pqsendQuery*(conn: PPGconn, query: cstring): int32{.cdecl, dynlib: dllName, importc: "PQsendQuery".} -proc pqsendQueryParams*(conn: PPGconn, command: cstring, nParams: int32, - paramTypes: POid, paramValues: cstringArray, - paramLengths, paramFormats: ptr int32, - resultFormat: int32): int32{.cdecl, dynlib: dllName, +proc pqsendQueryParams*(conn: PPGconn, command: cstring, nParams: int32, + paramTypes: POid, paramValues: cstringArray, + paramLengths, paramFormats: ptr int32, + resultFormat: int32): int32{.cdecl, dynlib: dllName, importc: "PQsendQueryParams".} -proc pqsendQueryPrepared*(conn: PPGconn, stmtName: cstring, nParams: int32, - paramValues: cstringArray, - paramLengths, paramFormats: ptr int32, - resultFormat: int32): int32{.cdecl, dynlib: dllName, +proc pqsendQueryPrepared*(conn: PPGconn, stmtName: cstring, nParams: int32, + paramValues: cstringArray, + paramLengths, paramFormats: ptr int32, + resultFormat: int32): int32{.cdecl, dynlib: dllName, importc: "PQsendQueryPrepared".} -proc pqgetResult*(conn: PPGconn): PPGresult{.cdecl, dynlib: dllName, +proc pqgetResult*(conn: PPGconn): PPGresult{.cdecl, dynlib: dllName, importc: "PQgetResult".} -proc pqisBusy*(conn: PPGconn): int32{.cdecl, dynlib: dllName, +proc pqisBusy*(conn: PPGconn): int32{.cdecl, dynlib: dllName, importc: "PQisBusy".} -proc pqconsumeInput*(conn: PPGconn): int32{.cdecl, dynlib: dllName, +proc pqconsumeInput*(conn: PPGconn): int32{.cdecl, dynlib: dllName, importc: "PQconsumeInput".} -proc pqnotifies*(conn: PPGconn): PPGnotify{.cdecl, dynlib: dllName, +proc pqnotifies*(conn: PPGconn): PPGnotify{.cdecl, dynlib: dllName, importc: "PQnotifies".} proc pqputCopyData*(conn: PPGconn, buffer: cstring, nbytes: int32): int32{. cdecl, dynlib: dllName, importc: "PQputCopyData".} -proc pqputCopyEnd*(conn: PPGconn, errormsg: cstring): int32{.cdecl, +proc pqputCopyEnd*(conn: PPGconn, errormsg: cstring): int32{.cdecl, dynlib: dllName, importc: "PQputCopyEnd".} proc pqgetCopyData*(conn: PPGconn, buffer: cstringArray, async: int32): int32{. cdecl, dynlib: dllName, importc: "PQgetCopyData".} -proc pqgetline*(conn: PPGconn, str: cstring, len: int32): int32{.cdecl, +proc pqgetline*(conn: PPGconn, str: cstring, len: int32): int32{.cdecl, dynlib: dllName, importc: "PQgetline".} -proc pqputline*(conn: PPGconn, str: cstring): int32{.cdecl, dynlib: dllName, +proc pqputline*(conn: PPGconn, str: cstring): int32{.cdecl, dynlib: dllName, importc: "PQputline".} proc pqgetlineAsync*(conn: PPGconn, buffer: cstring, bufsize: int32): int32{. cdecl, dynlib: dllName, importc: "PQgetlineAsync".} -proc pqputnbytes*(conn: PPGconn, buffer: cstring, nbytes: int32): int32{.cdecl, +proc pqputnbytes*(conn: PPGconn, buffer: cstring, nbytes: int32): int32{.cdecl, dynlib: dllName, importc: "PQputnbytes".} -proc pqendcopy*(conn: PPGconn): int32{.cdecl, dynlib: dllName, +proc pqendcopy*(conn: PPGconn): int32{.cdecl, dynlib: dllName, importc: "PQendcopy".} -proc pqsetnonblocking*(conn: PPGconn, arg: int32): int32{.cdecl, +proc pqsetnonblocking*(conn: PPGconn, arg: int32): int32{.cdecl, dynlib: dllName, importc: "PQsetnonblocking".} -proc pqisnonblocking*(conn: PPGconn): int32{.cdecl, dynlib: dllName, +proc pqisnonblocking*(conn: PPGconn): int32{.cdecl, dynlib: dllName, importc: "PQisnonblocking".} proc pqflush*(conn: PPGconn): int32{.cdecl, dynlib: dllName, importc: "PQflush".} -proc pqfn*(conn: PPGconn, fnid: int32, result_buf, result_len: ptr int32, +proc pqfn*(conn: PPGconn, fnid: int32, result_buf, result_len: ptr int32, result_is_int: int32, args: PPQArgBlock, nargs: int32): PPGresult{. cdecl, dynlib: dllName, importc: "PQfn".} -proc pqresultStatus*(res: PPGresult): ExecStatusType{.cdecl, dynlib: dllName, +proc pqresultStatus*(res: PPGresult): ExecStatusType{.cdecl, dynlib: dllName, importc: "PQresultStatus".} -proc pqresStatus*(status: ExecStatusType): cstring{.cdecl, dynlib: dllName, +proc pqresStatus*(status: ExecStatusType): cstring{.cdecl, dynlib: dllName, importc: "PQresStatus".} -proc pqresultErrorMessage*(res: PPGresult): cstring{.cdecl, dynlib: dllName, +proc pqresultErrorMessage*(res: PPGresult): cstring{.cdecl, dynlib: dllName, importc: "PQresultErrorMessage".} -proc pqresultErrorField*(res: PPGresult, fieldcode: int32): cstring{.cdecl, +proc pqresultErrorField*(res: PPGresult, fieldcode: int32): cstring{.cdecl, dynlib: dllName, importc: "PQresultErrorField".} -proc pqntuples*(res: PPGresult): int32{.cdecl, dynlib: dllName, +proc pqntuples*(res: PPGresult): int32{.cdecl, dynlib: dllName, importc: "PQntuples".} -proc pqnfields*(res: PPGresult): int32{.cdecl, dynlib: dllName, +proc pqnfields*(res: PPGresult): int32{.cdecl, dynlib: dllName, importc: "PQnfields".} -proc pqbinaryTuples*(res: PPGresult): int32{.cdecl, dynlib: dllName, +proc pqbinaryTuples*(res: PPGresult): int32{.cdecl, dynlib: dllName, importc: "PQbinaryTuples".} -proc pqfname*(res: PPGresult, field_num: int32): cstring{.cdecl, +proc pqfname*(res: PPGresult, field_num: int32): cstring{.cdecl, dynlib: dllName, importc: "PQfname".} -proc pqfnumber*(res: PPGresult, field_name: cstring): int32{.cdecl, +proc pqfnumber*(res: PPGresult, field_name: cstring): int32{.cdecl, dynlib: dllName, importc: "PQfnumber".} -proc pqftable*(res: PPGresult, field_num: int32): Oid{.cdecl, dynlib: dllName, +proc pqftable*(res: PPGresult, field_num: int32): Oid{.cdecl, dynlib: dllName, importc: "PQftable".} -proc pqftablecol*(res: PPGresult, field_num: int32): int32{.cdecl, +proc pqftablecol*(res: PPGresult, field_num: int32): int32{.cdecl, dynlib: dllName, importc: "PQftablecol".} -proc pqfformat*(res: PPGresult, field_num: int32): int32{.cdecl, +proc pqfformat*(res: PPGresult, field_num: int32): int32{.cdecl, dynlib: dllName, importc: "PQfformat".} -proc pqftype*(res: PPGresult, field_num: int32): Oid{.cdecl, dynlib: dllName, +proc pqftype*(res: PPGresult, field_num: int32): Oid{.cdecl, dynlib: dllName, importc: "PQftype".} -proc pqfsize*(res: PPGresult, field_num: int32): int32{.cdecl, dynlib: dllName, +proc pqfsize*(res: PPGresult, field_num: int32): int32{.cdecl, dynlib: dllName, importc: "PQfsize".} -proc pqfmod*(res: PPGresult, field_num: int32): int32{.cdecl, dynlib: dllName, +proc pqfmod*(res: PPGresult, field_num: int32): int32{.cdecl, dynlib: dllName, importc: "PQfmod".} -proc pqcmdStatus*(res: PPGresult): cstring{.cdecl, dynlib: dllName, +proc pqcmdStatus*(res: PPGresult): cstring{.cdecl, dynlib: dllName, importc: "PQcmdStatus".} -proc pqoidStatus*(res: PPGresult): cstring{.cdecl, dynlib: dllName, +proc pqoidStatus*(res: PPGresult): cstring{.cdecl, dynlib: dllName, importc: "PQoidStatus".} -proc pqoidValue*(res: PPGresult): Oid{.cdecl, dynlib: dllName, +proc pqoidValue*(res: PPGresult): Oid{.cdecl, dynlib: dllName, importc: "PQoidValue".} -proc pqcmdTuples*(res: PPGresult): cstring{.cdecl, dynlib: dllName, +proc pqcmdTuples*(res: PPGresult): cstring{.cdecl, dynlib: dllName, importc: "PQcmdTuples".} proc pqgetvalue*(res: PPGresult, tup_num: int32, field_num: int32): cstring{. cdecl, dynlib: dllName, importc: "PQgetvalue".} @@ -314,23 +323,23 @@ proc pqclear*(res: PPGresult){.cdecl, dynlib: dllName, importc: "PQclear".} proc pqfreemem*(p: pointer){.cdecl, dynlib: dllName, importc: "PQfreemem".} proc pqmakeEmptyPGresult*(conn: PPGconn, status: ExecStatusType): PPGresult{. cdecl, dynlib: dllName, importc: "PQmakeEmptyPGresult".} -proc pqescapeString*(till, `from`: cstring, len: int): int{.cdecl, +proc pqescapeString*(till, `from`: cstring, len: int): int{.cdecl, dynlib: dllName, importc: "PQescapeString".} proc pqescapeBytea*(bintext: cstring, binlen: int, bytealen: var int): cstring{. cdecl, dynlib: dllName, importc: "PQescapeBytea".} -proc pqunescapeBytea*(strtext: cstring, retbuflen: var int): cstring{.cdecl, +proc pqunescapeBytea*(strtext: cstring, retbuflen: var int): cstring{.cdecl, dynlib: dllName, importc: "PQunescapeBytea".} -proc pqprint*(fout: File, res: PPGresult, ps: PPQprintOpt){.cdecl, +proc pqprint*(fout: File, res: PPGresult, ps: PPQprintOpt){.cdecl, dynlib: dllName, importc: "PQprint".} -proc pqdisplayTuples*(res: PPGresult, fp: File, fillAlign: int32, +proc pqdisplayTuples*(res: PPGresult, fp: File, fillAlign: int32, fieldSep: cstring, printHeader: int32, quiet: int32){. cdecl, dynlib: dllName, importc: "PQdisplayTuples".} -proc pqprintTuples*(res: PPGresult, fout: File, printAttName: int32, - terseOutput: int32, width: int32){.cdecl, dynlib: dllName, +proc pqprintTuples*(res: PPGresult, fout: File, printAttName: int32, + terseOutput: int32, width: int32){.cdecl, dynlib: dllName, importc: "PQprintTuples".} -proc lo_open*(conn: PPGconn, lobjId: Oid, mode: int32): int32{.cdecl, +proc lo_open*(conn: PPGconn, lobjId: Oid, mode: int32): int32{.cdecl, dynlib: dllName, importc: "lo_open".} -proc lo_close*(conn: PPGconn, fd: int32): int32{.cdecl, dynlib: dllName, +proc lo_close*(conn: PPGconn, fd: int32): int32{.cdecl, dynlib: dllName, importc: "lo_close".} proc lo_read*(conn: PPGconn, fd: int32, buf: cstring, length: int): int32{. cdecl, dynlib: dllName, importc: "lo_read".} @@ -338,18 +347,18 @@ proc lo_write*(conn: PPGconn, fd: int32, buf: cstring, length: int): int32{. cdecl, dynlib: dllName, importc: "lo_write".} proc lo_lseek*(conn: PPGconn, fd: int32, offset: int32, whence: int32): int32{. cdecl, dynlib: dllName, importc: "lo_lseek".} -proc lo_creat*(conn: PPGconn, mode: int32): Oid{.cdecl, dynlib: dllName, +proc lo_creat*(conn: PPGconn, mode: int32): Oid{.cdecl, dynlib: dllName, importc: "lo_creat".} -proc lo_tell*(conn: PPGconn, fd: int32): int32{.cdecl, dynlib: dllName, +proc lo_tell*(conn: PPGconn, fd: int32): int32{.cdecl, dynlib: dllName, importc: "lo_tell".} -proc lo_unlink*(conn: PPGconn, lobjId: Oid): int32{.cdecl, dynlib: dllName, +proc lo_unlink*(conn: PPGconn, lobjId: Oid): int32{.cdecl, dynlib: dllName, importc: "lo_unlink".} -proc lo_import*(conn: PPGconn, filename: cstring): Oid{.cdecl, dynlib: dllName, +proc lo_import*(conn: PPGconn, filename: cstring): Oid{.cdecl, dynlib: dllName, importc: "lo_import".} -proc lo_export*(conn: PPGconn, lobjId: Oid, filename: cstring): int32{.cdecl, +proc lo_export*(conn: PPGconn, lobjId: Oid, filename: cstring): int32{.cdecl, dynlib: dllName, importc: "lo_export".} -proc pqmblen*(s: cstring, encoding: int32): int32{.cdecl, dynlib: dllName, +proc pqmblen*(s: cstring, encoding: int32): int32{.cdecl, dynlib: dllName, importc: "PQmblen".} proc pqenv2encoding*(): int32{.cdecl, dynlib: dllName, importc: "PQenv2encoding".} -proc pqsetdb(M_PGHOST, M_PGPORT, M_PGOPT, M_PGTTY, M_DBNAME: cstring): PPgConn = +proc pqsetdb(M_PGHOST, M_PGPORT, M_PGOPT, M_PGTTY, M_DBNAME: cstring): PPgConn = result = pqSetdbLogin(M_PGHOST, M_PGPORT, M_PGOPT, M_PGTTY, M_DBNAME, "", "") diff --git a/lib/wrappers/readline/history.nim b/lib/wrappers/readline/history.nim deleted file mode 100644 index 610c76a62..000000000 --- a/lib/wrappers/readline/history.nim +++ /dev/null @@ -1,279 +0,0 @@ -# history.h -- the names of functions that you can call in history. -# Copyright (C) 1989-2009 Free Software Foundation, Inc. -# -# This file contains the GNU History Library (History), a set of -# routines for managing the text of previously typed lines. -# -# History is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# History is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with History. If not, see . -# - -{.deadCodeElim: on.} - -import readline - -const - historyDll = readlineDll - -import times, rltypedefs - -type - Histdata* = pointer -{.deprecated: [Thistdata: Histdata].} - -# The structure used to store a history entry. - -type - HIST_ENTRY*{.pure, final.} = object - line*: cstring - timestamp*: cstring # char * rather than time_t for read/write - data*: Histdata -{.deprecated: [THIST_ENTRY: HIST_ENTRY].} - -# Size of the history-library-managed space in history entry HS. - -template HISTENT_BYTES*(hs: expr): expr = - (strlen(hs.line) + strlen(hs.timestamp)) - -# A structure used to pass the current state of the history stuff around. - -type - HISTORY_STATE*{.pure, final.} = object - entries*: ptr ptr HIST_ENTRY # Pointer to the entries themselves. - offset*: cint # The location pointer within this array. - length*: cint # Number of elements within this array. - size*: cint # Number of slots allocated to this array. - flags*: cint -{.deprecated: [THISTORY_STATE: HISTORY_STATE].} - - -# Flag values for the `flags' member of HISTORY_STATE. - -const - HS_STIFLED* = 0x00000001 - -# Initialization and state management. -# Begin a session in which the history functions might be used. This -# just initializes the interactive variables. - -proc using_history*(){.cdecl, importc: "using_history", dynlib: historyDll.} -# Return the current HISTORY_STATE of the history. - -proc history_get_history_state*(): ptr HISTORY_STATE{.cdecl, - importc: "history_get_history_state", dynlib: historyDll.} -# Set the state of the current history array to STATE. - -proc history_set_history_state*(a2: ptr HISTORY_STATE){.cdecl, - importc: "history_set_history_state", dynlib: historyDll.} -# Manage the history list. -# Place STRING at the end of the history list. -# The associated data field (if any) is set to NULL. - -proc add_history*(a2: cstring){.cdecl, importc: "add_history", - dynlib: historyDll.} -# Change the timestamp associated with the most recent history entry to -# STRING. - -proc add_history_time*(a2: cstring){.cdecl, importc: "add_history_time", - dynlib: historyDll.} -# A reasonably useless function, only here for completeness. WHICH -# is the magic number that tells us which element to delete. The -# elements are numbered from 0. - -proc remove_history*(a2: cint): ptr HIST_ENTRY{.cdecl, - importc: "remove_history", dynlib: historyDll.} -# Free the history entry H and return any application-specific data -# associated with it. - -proc free_history_entry*(a2: ptr HIST_ENTRY): Histdata{.cdecl, - importc: "free_history_entry", dynlib: historyDll.} -# Make the history entry at WHICH have LINE and DATA. This returns -# the old entry so you can dispose of the data. In the case of an -# invalid WHICH, a NULL pointer is returned. - -proc replace_history_entry*(a2: cint, a3: cstring, a4: Histdata): ptr HIST_ENTRY{. - cdecl, importc: "replace_history_entry", dynlib: historyDll.} -# Clear the history list and start over. - -proc clear_history*(){.cdecl, importc: "clear_history", dynlib: historyDll.} -# Stifle the history list, remembering only MAX number of entries. - -proc stifle_history*(a2: cint){.cdecl, importc: "stifle_history", - dynlib: historyDll.} -# Stop stifling the history. This returns the previous amount the -# history was stifled by. The value is positive if the history was -# stifled, negative if it wasn't. - -proc unstifle_history*(): cint{.cdecl, importc: "unstifle_history", - dynlib: historyDll.} -# Return 1 if the history is stifled, 0 if it is not. - -proc history_is_stifled*(): cint{.cdecl, importc: "history_is_stifled", - dynlib: historyDll.} -# Information about the history list. -# Return a NULL terminated array of HIST_ENTRY which is the current input -# history. Element 0 of this list is the beginning of time. If there -# is no history, return NULL. - -proc history_list*(): ptr ptr HIST_ENTRY{.cdecl, importc: "history_list", - dynlib: historyDll.} -# Returns the number which says what history element we are now -# looking at. - -proc where_history*(): cint{.cdecl, importc: "where_history", dynlib: historyDll.} -# Return the history entry at the current position, as determined by -# history_offset. If there is no entry there, return a NULL pointer. - -proc current_history*(): ptr HIST_ENTRY{.cdecl, importc: "current_history", - dynlib: historyDll.} -# Return the history entry which is logically at OFFSET in the history -# array. OFFSET is relative to history_base. - -proc history_get*(a2: cint): ptr HIST_ENTRY{.cdecl, importc: "history_get", - dynlib: historyDll.} -# Return the timestamp associated with the HIST_ENTRY * passed as an -# argument - -proc history_get_time*(a2: ptr HIST_ENTRY): Time{.cdecl, - importc: "history_get_time", dynlib: historyDll.} -# Return the number of bytes that the primary history entries are using. -# This just adds up the lengths of the_history->lines. - -proc history_total_bytes*(): cint{.cdecl, importc: "history_total_bytes", - dynlib: historyDll.} -# Moving around the history list. -# Set the position in the history list to POS. - -proc history_set_pos*(a2: cint): cint{.cdecl, importc: "history_set_pos", - dynlib: historyDll.} -# Back up history_offset to the previous history entry, and return -# a pointer to that entry. If there is no previous entry, return -# a NULL pointer. - -proc previous_history*(): ptr HIST_ENTRY{.cdecl, importc: "previous_history", - dynlib: historyDll.} -# Move history_offset forward to the next item in the input_history, -# and return the a pointer to that entry. If there is no next entry, -# return a NULL pointer. - -proc next_history*(): ptr HIST_ENTRY{.cdecl, importc: "next_history", - dynlib: historyDll.} -# Searching the history list. -# Search the history for STRING, starting at history_offset. -# If DIRECTION < 0, then the search is through previous entries, -# else through subsequent. If the string is found, then -# current_history () is the history entry, and the value of this function -# is the offset in the line of that history entry that the string was -# found in. Otherwise, nothing is changed, and a -1 is returned. - -proc history_search*(a2: cstring, a3: cint): cint{.cdecl, - importc: "history_search", dynlib: historyDll.} -# Search the history for STRING, starting at history_offset. -# The search is anchored: matching lines must begin with string. -# DIRECTION is as in history_search(). - -proc history_search_prefix*(a2: cstring, a3: cint): cint{.cdecl, - importc: "history_search_prefix", dynlib: historyDll.} -# Search for STRING in the history list, starting at POS, an -# absolute index into the list. DIR, if negative, says to search -# backwards from POS, else forwards. -# Returns the absolute index of the history element where STRING -# was found, or -1 otherwise. - -proc history_search_pos*(a2: cstring, a3: cint, a4: cint): cint{.cdecl, - importc: "history_search_pos", dynlib: historyDll.} -# Managing the history file. -# Add the contents of FILENAME to the history list, a line at a time. -# If FILENAME is NULL, then read from ~/.history. Returns 0 if -# successful, or errno if not. - -proc read_history*(a2: cstring): cint{.cdecl, importc: "read_history", - dynlib: historyDll.} -# Read a range of lines from FILENAME, adding them to the history list. -# Start reading at the FROM'th line and end at the TO'th. If FROM -# is zero, start at the beginning. If TO is less than FROM, read -# until the end of the file. If FILENAME is NULL, then read from -# ~/.history. Returns 0 if successful, or errno if not. - -proc read_history_range*(a2: cstring, a3: cint, a4: cint): cint{.cdecl, - importc: "read_history_range", dynlib: historyDll.} -# Write the current history to FILENAME. If FILENAME is NULL, -# then write the history list to ~/.history. Values returned -# are as in read_history (). - -proc write_history*(a2: cstring): cint{.cdecl, importc: "write_history", - dynlib: historyDll.} -# Append NELEMENT entries to FILENAME. The entries appended are from -# the end of the list minus NELEMENTs up to the end of the list. - -proc append_history*(a2: cint, a3: cstring): cint{.cdecl, - importc: "append_history", dynlib: historyDll.} -# Truncate the history file, leaving only the last NLINES lines. - -proc history_truncate_file*(a2: cstring, a3: cint): cint{.cdecl, - importc: "history_truncate_file", dynlib: historyDll.} -# History expansion. -# Expand the string STRING, placing the result into OUTPUT, a pointer -# to a string. Returns: -# -# 0) If no expansions took place (or, if the only change in -# the text was the de-slashifying of the history expansion -# character) -# 1) If expansions did take place -# -1) If there was an error in expansion. -# 2) If the returned line should just be printed. -# -# If an error occurred in expansion, then OUTPUT contains a descriptive -# error message. - -proc history_expand*(a2: cstring, a3: cstringArray): cint{.cdecl, - importc: "history_expand", dynlib: historyDll.} -# Extract a string segment consisting of the FIRST through LAST -# arguments present in STRING. Arguments are broken up as in -# the shell. - -proc history_arg_extract*(a2: cint, a3: cint, a4: cstring): cstring{.cdecl, - importc: "history_arg_extract", dynlib: historyDll.} -# Return the text of the history event beginning at the current -# offset into STRING. Pass STRING with *INDEX equal to the -# history_expansion_char that begins this specification. -# DELIMITING_QUOTE is a character that is allowed to end the string -# specification for what to search for in addition to the normal -# characters `:', ` ', `\t', `\n', and sometimes `?'. - -proc get_history_event*(a2: cstring, a3: ptr cint, a4: cint): cstring{.cdecl, - importc: "get_history_event", dynlib: historyDll.} -# Return an array of tokens, much as the shell might. The tokens are -# parsed out of STRING. - -proc history_tokenize*(a2: cstring): cstringArray{.cdecl, - importc: "history_tokenize", dynlib: historyDll.} -when false: - # Exported history variables. - var history_base*{.importc: "history_base", dynlib: historyDll.}: cint - var history_length*{.importc: "history_length", dynlib: historyDll.}: cint - var history_max_entries*{.importc: "history_max_entries", dynlib: historyDll.}: cint - var history_expansion_char*{.importc: "history_expansion_char", - dynlib: historyDll.}: char - var history_subst_char*{.importc: "history_subst_char", dynlib: historyDll.}: char - var history_word_delimiters*{.importc: "history_word_delimiters", - dynlib: historyDll.}: cstring - var history_comment_char*{.importc: "history_comment_char", dynlib: historyDll.}: char - var history_no_expand_chars*{.importc: "history_no_expand_chars", - dynlib: historyDll.}: cstring - var history_search_delimiter_chars*{.importc: "history_search_delimiter_chars", - dynlib: historyDll.}: cstring - var history_quotes_inhibit_expansion*{. - importc: "history_quotes_inhibit_expansion", dynlib: historyDll.}: cint - var history_write_timestamps*{.importc: "history_write_timestamps", - dynlib: historyDll.}: cint diff --git a/lib/wrappers/readline/readline.nim b/lib/wrappers/readline/readline.nim deleted file mode 100644 index 652808576..000000000 --- a/lib/wrappers/readline/readline.nim +++ /dev/null @@ -1,1209 +0,0 @@ -# Readline.h -- the names of functions callable from within readline. -# Copyright (C) 1987-2009 Free Software Foundation, Inc. -# -# This file is part of the GNU Readline Library (Readline), a library -# for reading lines of text with interactive input and history editing. -# -# Readline is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# Readline is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with Readline. If not, see . -# - -{.deadCodeElim: on.} -when defined(windows): - const - readlineDll* = "readline.dll" -elif defined(macosx): - # Mac OS X ships with 'libedit' - const - readlineDll* = "libedit(.2|.1|).dylib" -else: - const - readlineDll* = "libreadline.so.6(|.0)" -# mangle "'CommandFunc'" CommandFunc -# mangle TvcpFunc TvcpFunc - -import rltypedefs - -# Some character stuff. - -const - control_character_threshold* = 0x00000020 # Smaller than this is control. - control_character_mask* = 0x0000001F # 0x20 - 1 - meta_character_threshold* = 0x0000007F # Larger than this is Meta. - control_character_bit* = 0x00000040 # 0x000000, must be off. - meta_character_bit* = 0x00000080 # x0000000, must be on. - largest_char* = 255 # Largest character value. - -template CTRL_CHAR*(c: expr): expr = - (c < control_character_threshold and ((c and 0x00000080) == 0)) - -template META_CHAR*(c: expr): expr = - (c > meta_character_threshold and c <= largest_char) - -template CTRL*(c: expr): expr = - (c and control_character_mask) - -template META*(c: expr): expr = - (c or meta_character_bit) - -template UNMETA*(c: expr): expr = - (c and not meta_character_bit) - -template UNCTRL*(c: expr): expr = - (c or 32 or control_character_bit) - -# Beware: these only work with single-byte ASCII characters. - -const - RETURN_CHAR* = CTRL('M'.ord) - RUBOUT_CHAR* = 0x0000007F - ABORT_CHAR* = CTRL('G'.ord) - PAGE_CHAR* = CTRL('L'.ord) - ESC_CHAR* = CTRL('['.ord) - -# A keymap contains one entry for each key in the ASCII set. -# Each entry consists of a type and a pointer. -# FUNCTION is the address of a function to run, or the -# address of a keymap to indirect through. -# TYPE says which kind of thing FUNCTION is. - -type - KEYMAP_ENTRY*{.pure, final.} = object - typ*: char - function*: CommandFunc -{.deprecated: [TKEYMAP_ENTRY: KEYMAP_ENTRY].} - - -# This must be large enough to hold bindings for all of the characters -# in a desired character set (e.g, 128 for ASCII, 256 for ISO Latin-x, -# and so on) plus one for subsequence matching. - -const - KEYMAP_SIZE* = 257 - ANYOTHERKEY* = KEYMAP_SIZE - 1 - -# I wanted to make the above structure contain a union of: -# union { rl_TCommandFunc_t *function; struct _keymap_entry *keymap; } value; -# but this made it impossible for me to create a static array. -# Maybe I need C lessons. - -type - KEYMAP_ENTRY_ARRAY* = array[0..KEYMAP_SIZE - 1, KEYMAP_ENTRY] - PKeymap* = ptr KEYMAP_ENTRY -{.deprecated: [TKEYMAP_ENTRY_ARRAY: KEYMAP_ENTRY_ARRAY].} - -# The values that TYPE can have in a keymap entry. - -const - ISFUNC* = 0 - ISKMAP* = 1 - ISMACR* = 2 - -when false: - var - emacs_standard_keymap*{.importc: "emacs_standard_keymap", - dynlib: readlineDll.}: KEYMAP_ENTRY_ARRAY - emacs_meta_keymap*{.importc: "emacs_meta_keymap", dynlib: readlineDll.}: KEYMAP_ENTRY_ARRAY - emacs_ctlx_keymap*{.importc: "emacs_ctlx_keymap", dynlib: readlineDll.}: KEYMAP_ENTRY_ARRAY - var - vi_insertion_keymap*{.importc: "vi_insertion_keymap", dynlib: readlineDll.}: KEYMAP_ENTRY_ARRAY - vi_movement_keymap*{.importc: "vi_movement_keymap", dynlib: readlineDll.}: KEYMAP_ENTRY_ARRAY -# Return a new, empty keymap. -# Free it with free() when you are done. - -proc make_bare_keymap*(): PKeymap{.cdecl, importc: "rl_make_bare_keymap", - dynlib: readlineDll.} -# Return a new keymap which is a copy of MAP. - -proc copy_keymap*(a2: PKeymap): PKeymap{.cdecl, importc: "rl_copy_keymap", - dynlib: readlineDll.} -# Return a new keymap with the printing characters bound to rl_insert, -# the lowercase Meta characters bound to run their equivalents, and -# the Meta digits bound to produce numeric arguments. - -proc make_keymap*(): PKeymap{.cdecl, importc: "rl_make_keymap", - dynlib: readlineDll.} -# Free the storage associated with a keymap. - -proc discard_keymap*(a2: PKeymap){.cdecl, importc: "rl_discard_keymap", - dynlib: readlineDll.} -# These functions actually appear in bind.c -# Return the keymap corresponding to a given name. Names look like -# `emacs' or `emacs-meta' or `vi-insert'. - -proc get_keymap_by_name*(a2: cstring): PKeymap{.cdecl, - importc: "rl_get_keymap_by_name", dynlib: readlineDll.} -# Return the current keymap. - -proc get_keymap*(): PKeymap{.cdecl, importc: "rl_get_keymap", - dynlib: readlineDll.} -# Set the current keymap to MAP. - -proc set_keymap*(a2: PKeymap){.cdecl, importc: "rl_set_keymap", - dynlib: readlineDll.} - -const - tildeDll = readlineDll - -type - Hook_func* = proc (a2: cstring): cstring{.cdecl.} -{.deprecated: [Thook_func: Hook_func].} - -when not defined(macosx): - # If non-null, this contains the address of a function that the application - # wants called before trying the standard tilde expansions. The function - # is called with the text sans tilde, and returns a malloc()'ed string - # which is the expansion, or a NULL pointer if the expansion fails. - - var expansion_preexpansion_hook*{.importc: "tilde_expansion_preexpansion_hook", - dynlib: tildeDll.}: Hook_func - - # If non-null, this contains the address of a function to call if the - # standard meaning for expanding a tilde fails. The function is called - # with the text (sans tilde, as in "foo"), and returns a malloc()'ed string - # which is the expansion, or a NULL pointer if there is no expansion. - - var expansion_failure_hook*{.importc: "tilde_expansion_failure_hook", - dynlib: tildeDll.}: Hook_func - - # When non-null, this is a NULL terminated array of strings which - # are duplicates for a tilde prefix. Bash uses this to expand - # `=~' and `:~'. - - var additional_prefixes*{.importc: "tilde_additional_prefixes", dynlib: tildeDll.}: cstringArray - - # When non-null, this is a NULL terminated array of strings which match - # the end of a username, instead of just "/". Bash sets this to - # `:' and `=~'. - - var additional_suffixes*{.importc: "tilde_additional_suffixes", dynlib: tildeDll.}: cstringArray - -# Return a new string which is the result of tilde expanding STRING. - -proc expand*(a2: cstring): cstring{.cdecl, importc: "tilde_expand", - dynlib: tildeDll.} -# Do the work of tilde expansion on FILENAME. FILENAME starts with a -# tilde. If there is no expansion, call tilde_expansion_failure_hook. - -proc expand_word*(a2: cstring): cstring{.cdecl, importc: "tilde_expand_word", - dynlib: tildeDll.} -# Find the portion of the string beginning with ~ that should be expanded. - -proc find_word*(a2: cstring, a3: cint, a4: ptr cint): cstring{.cdecl, - importc: "tilde_find_word", dynlib: tildeDll.} - -# Hex-encoded Readline version number. - -const - READLINE_VERSION* = 0x00000600 # Readline 6.0 - VERSION_MAJOR* = 6 - VERSION_MINOR* = 0 - -# Readline data structures. -# Maintaining the state of undo. We remember individual deletes and inserts -# on a chain of things to do. -# The actions that undo knows how to undo. Notice that UNDO_DELETE means -# to insert some text, and UNDO_INSERT means to delete some text. I.e., -# the code tells undo what to undo, not how to undo it. - -type - Undo_code* = enum - UNDO_DELETE, UNDO_INSERT, UNDO_BEGIN, UNDO_END -{.deprecated: [Tundo_code: Undo_code].} - -# What an element of THE_UNDO_LIST looks like. - -type - UNDO_LIST*{.pure, final.} = object - next*: ptr UNDO_LIST - start*: cint - theEnd*: cint # Where the change took place. - text*: cstring # The text to insert, if undoing a delete. - what*: Undo_code # Delete, Insert, Begin, End. -{.deprecated: [TUNDO_LIST: UNDO_LIST].} - - -# The current undo list for RL_LINE_BUFFER. - -when not defined(macosx): - var undo_list*{.importc: "rl_undo_list", dynlib: readlineDll.}: ptr UNDO_LIST - -# The data structure for mapping textual names to code addresses. - -type - FUNMAP*{.pure, final.} = object - name*: cstring - function*: CommandFunc -{.deprecated: [TFUNMAP: FUNMAP].} - - -when not defined(macosx): - var funmap*{.importc: "funmap", dynlib: readlineDll.}: ptr ptr FUNMAP - -# **************************************************************** -# -# Functions available to bind to key sequences -# -# **************************************************************** -# Bindable commands for numeric arguments. - -proc digit_argument*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_digit_argument", dynlib: readlineDll.} -proc universal_argument*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_universal_argument", dynlib: readlineDll.} -# Bindable commands for moving the cursor. - -proc forward_byte*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_forward_byte", - dynlib: readlineDll.} -proc forward_char*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_forward_char", - dynlib: readlineDll.} -proc forward*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_forward", - dynlib: readlineDll.} -proc backward_byte*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_backward_byte", dynlib: readlineDll.} -proc backward_char*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_backward_char", dynlib: readlineDll.} -proc backward*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_backward", - dynlib: readlineDll.} -proc beg_of_line*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_beg_of_line", - dynlib: readlineDll.} -proc end_of_line*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_end_of_line", - dynlib: readlineDll.} -proc forward_word*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_forward_word", - dynlib: readlineDll.} -proc backward_word*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_backward_word", dynlib: readlineDll.} -proc refresh_line*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_refresh_line", - dynlib: readlineDll.} -proc clear_screen*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_clear_screen", - dynlib: readlineDll.} -proc skip_csi_sequence*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_skip_csi_sequence", dynlib: readlineDll.} -proc arrow_keys*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_arrow_keys", - dynlib: readlineDll.} -# Bindable commands for inserting and deleting text. - -proc insert*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_insert", - dynlib: readlineDll.} -proc quoted_insert*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_quoted_insert", dynlib: readlineDll.} -proc tab_insert*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_tab_insert", - dynlib: readlineDll.} -proc newline*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_newline", - dynlib: readlineDll.} -proc do_lowercase_version*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_do_lowercase_version", dynlib: readlineDll.} -proc rubout*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_rubout", - dynlib: readlineDll.} -proc delete*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_delete", - dynlib: readlineDll.} -proc rubout_or_delete*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_rubout_or_delete", dynlib: readlineDll.} -proc delete_horizontal_space*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_delete_horizontal_space", dynlib: readlineDll.} -proc delete_or_show_completions*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_delete_or_show_completions", dynlib: readlineDll.} -proc insert_comment*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_insert_comment", dynlib: readlineDll.} -# Bindable commands for changing case. - -proc upcase_word*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_upcase_word", - dynlib: readlineDll.} -proc downcase_word*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_downcase_word", dynlib: readlineDll.} -proc capitalize_word*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_capitalize_word", dynlib: readlineDll.} -# Bindable commands for transposing characters and words. - -proc transpose_words*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_transpose_words", dynlib: readlineDll.} -proc transpose_chars*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_transpose_chars", dynlib: readlineDll.} -# Bindable commands for searching within a line. - -proc char_search*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_char_search", - dynlib: readlineDll.} -proc backward_char_search*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_backward_char_search", dynlib: readlineDll.} -# Bindable commands for readline's interface to the command history. - -proc beginning_of_history*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_beginning_of_history", dynlib: readlineDll.} -proc end_of_history*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_end_of_history", dynlib: readlineDll.} -proc get_next_history*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_get_next_history", dynlib: readlineDll.} -proc get_previous_history*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_get_previous_history", dynlib: readlineDll.} -# Bindable commands for managing the mark and region. - -proc set_mark*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_set_mark", - dynlib: readlineDll.} -proc exchange_point_and_mark*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_exchange_point_and_mark", dynlib: readlineDll.} -# Bindable commands to set the editing mode (emacs or vi). - -proc vi_editing_mode*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_vi_editing_mode", dynlib: readlineDll.} -proc emacs_editing_mode*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_emacs_editing_mode", dynlib: readlineDll.} -# Bindable commands to change the insert mode (insert or overwrite) - -proc overwrite_mode*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_overwrite_mode", dynlib: readlineDll.} -# Bindable commands for managing key bindings. - -proc re_read_init_file*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_re_read_init_file", dynlib: readlineDll.} -proc dump_functions*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_dump_functions", dynlib: readlineDll.} -proc dump_macros*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_dump_macros", - dynlib: readlineDll.} -proc dump_variables*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_dump_variables", dynlib: readlineDll.} -# Bindable commands for word completion. - -proc complete*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_complete", - dynlib: readlineDll.} -proc possible_completions*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_possible_completions", dynlib: readlineDll.} -proc insert_completions*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_insert_completions", dynlib: readlineDll.} -proc old_menu_complete*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_old_menu_complete", dynlib: readlineDll.} -proc menu_complete*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_menu_complete", dynlib: readlineDll.} -proc backward_menu_complete*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_backward_menu_complete", dynlib: readlineDll.} -# Bindable commands for killing and yanking text, and managing the kill ring. - -proc kill_word*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_kill_word", - dynlib: readlineDll.} -proc backward_kill_word*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_backward_kill_word", dynlib: readlineDll.} -proc kill_line*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_kill_line", - dynlib: readlineDll.} -proc backward_kill_line*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_backward_kill_line", dynlib: readlineDll.} -proc kill_full_line*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_kill_full_line", dynlib: readlineDll.} -proc unix_word_rubout*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_unix_word_rubout", dynlib: readlineDll.} -proc unix_filename_rubout*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_unix_filename_rubout", dynlib: readlineDll.} -proc unix_line_discard*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_unix_line_discard", dynlib: readlineDll.} -proc copy_region_to_kill*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_copy_region_to_kill", dynlib: readlineDll.} -proc kill_region*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_kill_region", - dynlib: readlineDll.} -proc copy_forward_word*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_copy_forward_word", dynlib: readlineDll.} -proc copy_backward_word*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_copy_backward_word", dynlib: readlineDll.} -proc yank*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_yank", - dynlib: readlineDll.} -proc yank_pop*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_yank_pop", - dynlib: readlineDll.} -proc yank_nth_arg*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_yank_nth_arg", - dynlib: readlineDll.} -proc yank_last_arg*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_yank_last_arg", dynlib: readlineDll.} -when defined(Windows): - proc paste_from_clipboard*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_paste_from_clipboard", dynlib: readlineDll.} -# Bindable commands for incremental searching. - -proc reverse_search_history*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_reverse_search_history", dynlib: readlineDll.} -proc forward_search_history*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_forward_search_history", dynlib: readlineDll.} -# Bindable keyboard macro commands. - -proc start_kbd_macro*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_start_kbd_macro", dynlib: readlineDll.} -proc end_kbd_macro*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_end_kbd_macro", dynlib: readlineDll.} -proc call_last_kbd_macro*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_call_last_kbd_macro", dynlib: readlineDll.} -# Bindable undo commands. - -proc revert_line*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_revert_line", - dynlib: readlineDll.} -proc undo_command*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_undo_command", - dynlib: readlineDll.} -# Bindable tilde expansion commands. - -proc tilde_expand*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_tilde_expand", - dynlib: readlineDll.} -# Bindable terminal control commands. - -proc restart_output*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_restart_output", dynlib: readlineDll.} -proc stop_output*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_stop_output", - dynlib: readlineDll.} -# Miscellaneous bindable commands. - -proc abort*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_abort", - dynlib: readlineDll.} -proc tty_status*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_tty_status", - dynlib: readlineDll.} -# Bindable commands for incremental and non-incremental history searching. - -proc history_search_forward*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_history_search_forward", dynlib: readlineDll.} -proc history_search_backward*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_history_search_backward", dynlib: readlineDll.} -proc noninc_forward_search*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_noninc_forward_search", dynlib: readlineDll.} -proc noninc_reverse_search*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_noninc_reverse_search", dynlib: readlineDll.} -proc noninc_forward_search_again*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_noninc_forward_search_again", dynlib: readlineDll.} -proc noninc_reverse_search_again*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_noninc_reverse_search_again", dynlib: readlineDll.} -# Bindable command used when inserting a matching close character. - -proc insert_close*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_insert_close", - dynlib: readlineDll.} -# Not available unless READLINE_CALLBACKS is defined. - -proc callback_handler_install*(a2: cstring, a3: TvcpFunc){.cdecl, - importc: "rl_callback_handler_install", dynlib: readlineDll.} -proc callback_read_char*(){.cdecl, importc: "rl_callback_read_char", - dynlib: readlineDll.} -proc callback_handler_remove*(){.cdecl, importc: "rl_callback_handler_remove", - dynlib: readlineDll.} -# Things for vi mode. Not available unless readline is compiled -DVI_MODE. -# VI-mode bindable commands. - -proc vi_redo*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_vi_redo", - dynlib: readlineDll.} -proc vi_undo*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_vi_undo", - dynlib: readlineDll.} -proc vi_yank_arg*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_vi_yank_arg", - dynlib: readlineDll.} -proc vi_fetch_history*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_vi_fetch_history", dynlib: readlineDll.} -proc vi_search_again*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_vi_search_again", dynlib: readlineDll.} -proc vi_search*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_vi_search", - dynlib: readlineDll.} -proc vi_complete*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_vi_complete", - dynlib: readlineDll.} -proc vi_tilde_expand*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_vi_tilde_expand", dynlib: readlineDll.} -proc vi_prev_word*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_vi_prev_word", - dynlib: readlineDll.} -proc vi_next_word*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_vi_next_word", - dynlib: readlineDll.} -proc vi_end_word*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_vi_end_word", - dynlib: readlineDll.} -proc vi_insert_beg*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_vi_insert_beg", dynlib: readlineDll.} -proc vi_append_mode*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_vi_append_mode", dynlib: readlineDll.} -proc vi_append_eol*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_vi_append_eol", dynlib: readlineDll.} -proc vi_eof_maybe*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_vi_eof_maybe", - dynlib: readlineDll.} -proc vi_insertion_mode*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_vi_insertion_mode", dynlib: readlineDll.} -proc vi_insert_mode*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_vi_insert_mode", dynlib: readlineDll.} -proc vi_movement_mode*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_vi_movement_mode", dynlib: readlineDll.} -proc vi_arg_digit*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_vi_arg_digit", - dynlib: readlineDll.} -proc vi_change_case*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_vi_change_case", dynlib: readlineDll.} -proc vi_put*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_vi_put", - dynlib: readlineDll.} -proc vi_column*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_vi_column", - dynlib: readlineDll.} -proc vi_delete_to*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_vi_delete_to", - dynlib: readlineDll.} -proc vi_change_to*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_vi_change_to", - dynlib: readlineDll.} -proc vi_yank_to*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_vi_yank_to", - dynlib: readlineDll.} -proc vi_rubout*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_vi_rubout", - dynlib: readlineDll.} -proc vi_delete*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_vi_delete", - dynlib: readlineDll.} -proc vi_back_to_indent*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_vi_back_to_indent", dynlib: readlineDll.} -proc vi_first_print*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_vi_first_print", dynlib: readlineDll.} -proc vi_char_search*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_vi_char_search", dynlib: readlineDll.} -proc vi_match*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_vi_match", - dynlib: readlineDll.} -proc vi_change_char*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_vi_change_char", dynlib: readlineDll.} -proc vi_subst*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_vi_subst", - dynlib: readlineDll.} -proc vi_overstrike*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_vi_overstrike", dynlib: readlineDll.} -proc vi_overstrike_delete*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_vi_overstrike_delete", dynlib: readlineDll.} -proc vi_replace*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_vi_replace", - dynlib: readlineDll.} -proc vi_set_mark*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_vi_set_mark", - dynlib: readlineDll.} -proc vi_goto_mark*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_vi_goto_mark", - dynlib: readlineDll.} -# VI-mode utility functions. - -proc vi_check*(): cint{.cdecl, importc: "rl_vi_check", dynlib: readlineDll.} -proc vi_domove*(a2: cint, a3: ptr cint): cint{.cdecl, importc: "rl_vi_domove", - dynlib: readlineDll.} -proc vi_bracktype*(a2: cint): cint{.cdecl, importc: "rl_vi_bracktype", - dynlib: readlineDll.} -proc vi_start_inserting*(a2: cint, a3: cint, a4: cint){.cdecl, - importc: "rl_vi_start_inserting", dynlib: readlineDll.} -# VI-mode pseudo-bindable commands, used as utility functions. - -proc vi_fXWord*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_vi_fWord", - dynlib: readlineDll.} -proc vi_bXWord*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_vi_bWord", - dynlib: readlineDll.} -proc vi_eXWord*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_vi_eWord", - dynlib: readlineDll.} -proc vi_fword*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_vi_fword", - dynlib: readlineDll.} -proc vi_bword*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_vi_bword", - dynlib: readlineDll.} -proc vi_eword*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_vi_eword", - dynlib: readlineDll.} -# **************************************************************** -# -# Well Published Functions -# -# **************************************************************** -# Readline functions. -# Read a line of input. Prompt with PROMPT. A NULL PROMPT means none. - -proc readline*(a2: cstring): cstring{.cdecl, importc: "readline", - dynlib: readlineDll.} -proc free*(mem: cstring) {.importc: "free", nodecl.} - ## free the buffer that `readline` returned. - -proc set_prompt*(a2: cstring): cint{.cdecl, importc: "rl_set_prompt", - dynlib: readlineDll.} -proc expand_prompt*(a2: cstring): cint{.cdecl, importc: "rl_expand_prompt", - dynlib: readlineDll.} -proc initialize*(): cint{.cdecl, importc: "rl_initialize", dynlib: readlineDll.} -# Undocumented; unused by readline - -proc discard_argument*(): cint{.cdecl, importc: "rl_discard_argument", - dynlib: readlineDll.} -# Utility functions to bind keys to readline commands. - -proc add_defun*(a2: cstring, a3: CommandFunc, a4: cint): cint{.cdecl, - importc: "rl_add_defun", dynlib: readlineDll.} -proc bind_key*(a2: cint, a3: CommandFunc): cint{.cdecl, - importc: "rl_bind_key", dynlib: readlineDll.} -proc bind_key_in_map*(a2: cint, a3: CommandFunc, a4: PKeymap): cint{.cdecl, - importc: "rl_bind_key_in_map", dynlib: readlineDll.} -proc unbind_key*(a2: cint): cint{.cdecl, importc: "rl_unbind_key", - dynlib: readlineDll.} -proc unbind_key_in_map*(a2: cint, a3: PKeymap): cint{.cdecl, - importc: "rl_unbind_key_in_map", dynlib: readlineDll.} -proc bind_key_if_unbound*(a2: cint, a3: CommandFunc): cint{.cdecl, - importc: "rl_bind_key_if_unbound", dynlib: readlineDll.} -proc bind_key_if_unbound_in_map*(a2: cint, a3: CommandFunc, a4: PKeymap): cint{. - cdecl, importc: "rl_bind_key_if_unbound_in_map", dynlib: readlineDll.} -proc unbind_function_in_map*(a2: CommandFunc, a3: PKeymap): cint{.cdecl, - importc: "rl_unbind_function_in_map", dynlib: readlineDll.} -proc unbind_command_in_map*(a2: cstring, a3: PKeymap): cint{.cdecl, - importc: "rl_unbind_command_in_map", dynlib: readlineDll.} -proc bind_keyseq*(a2: cstring, a3: CommandFunc): cint{.cdecl, - importc: "rl_bind_keyseq", dynlib: readlineDll.} -proc bind_keyseq_in_map*(a2: cstring, a3: CommandFunc, a4: PKeymap): cint{. - cdecl, importc: "rl_bind_keyseq_in_map", dynlib: readlineDll.} -proc bind_keyseq_if_unbound*(a2: cstring, a3: CommandFunc): cint{.cdecl, - importc: "rl_bind_keyseq_if_unbound", dynlib: readlineDll.} -proc bind_keyseq_if_unbound_in_map*(a2: cstring, a3: CommandFunc, - a4: PKeymap): cint{.cdecl, - importc: "rl_bind_keyseq_if_unbound_in_map", dynlib: readlineDll.} -proc generic_bind*(a2: cint, a3: cstring, a4: cstring, a5: PKeymap): cint{. - cdecl, importc: "rl_generic_bind", dynlib: readlineDll.} -proc variable_value*(a2: cstring): cstring{.cdecl, importc: "rl_variable_value", - dynlib: readlineDll.} -proc variable_bind*(a2: cstring, a3: cstring): cint{.cdecl, - importc: "rl_variable_bind", dynlib: readlineDll.} -# Backwards compatibility, use rl_bind_keyseq_in_map instead. - -proc set_key*(a2: cstring, a3: CommandFunc, a4: PKeymap): cint{.cdecl, - importc: "rl_set_key", dynlib: readlineDll.} -# Backwards compatibility, use rl_generic_bind instead. - -proc macro_bind*(a2: cstring, a3: cstring, a4: PKeymap): cint{.cdecl, - importc: "rl_macro_bind", dynlib: readlineDll.} -# Undocumented in the texinfo manual; not really useful to programs. - -proc translate_keyseq*(a2: cstring, a3: cstring, a4: ptr cint): cint{.cdecl, - importc: "rl_translate_keyseq", dynlib: readlineDll.} -proc untranslate_keyseq*(a2: cint): cstring{.cdecl, - importc: "rl_untranslate_keyseq", dynlib: readlineDll.} -proc named_function*(a2: cstring): CommandFunc{.cdecl, - importc: "rl_named_function", dynlib: readlineDll.} -proc function_of_keyseq*(a2: cstring, a3: PKeymap, a4: ptr cint): CommandFunc{. - cdecl, importc: "rl_function_of_keyseq", dynlib: readlineDll.} -proc list_funmap_names*(){.cdecl, importc: "rl_list_funmap_names", - dynlib: readlineDll.} -proc invoking_keyseqs_in_map*(a2: CommandFunc, a3: PKeymap): cstringArray{. - cdecl, importc: "rl_invoking_keyseqs_in_map", dynlib: readlineDll.} -proc invoking_keyseqs*(a2: CommandFunc): cstringArray{.cdecl, - importc: "rl_invoking_keyseqs", dynlib: readlineDll.} -proc function_dumper*(a2: cint){.cdecl, importc: "rl_function_dumper", - dynlib: readlineDll.} -proc macro_dumper*(a2: cint){.cdecl, importc: "rl_macro_dumper", - dynlib: readlineDll.} -proc variable_dumper*(a2: cint){.cdecl, importc: "rl_variable_dumper", - dynlib: readlineDll.} -proc read_init_file*(a2: cstring): cint{.cdecl, importc: "rl_read_init_file", - dynlib: readlineDll.} -proc parse_and_bind*(a2: cstring): cint{.cdecl, importc: "rl_parse_and_bind", - dynlib: readlineDll.} - -proc get_keymap_name*(a2: PKeymap): cstring{.cdecl, - importc: "rl_get_keymap_name", dynlib: readlineDll.} - -proc set_keymap_from_edit_mode*(){.cdecl, - importc: "rl_set_keymap_from_edit_mode", - dynlib: readlineDll.} -proc get_keymap_name_from_edit_mode*(): cstring{.cdecl, - importc: "rl_get_keymap_name_from_edit_mode", dynlib: readlineDll.} -# Functions for manipulating the funmap, which maps command names to functions. - -proc add_funmap_entry*(a2: cstring, a3: CommandFunc): cint{.cdecl, - importc: "rl_add_funmap_entry", dynlib: readlineDll.} -proc funmap_names*(): cstringArray{.cdecl, importc: "rl_funmap_names", - dynlib: readlineDll.} -# Undocumented, only used internally -- there is only one funmap, and this -# function may be called only once. - -proc initialize_funmap*(){.cdecl, importc: "rl_initialize_funmap", - dynlib: readlineDll.} -# Utility functions for managing keyboard macros. - -proc push_macro_input*(a2: cstring){.cdecl, importc: "rl_push_macro_input", - dynlib: readlineDll.} -# Functions for undoing, from undo.c - -proc add_undo*(a2: Undo_code, a3: cint, a4: cint, a5: cstring){.cdecl, - importc: "rl_add_undo", dynlib: readlineDll.} -proc free_undo_list*(){.cdecl, importc: "rl_free_undo_list", dynlib: readlineDll.} -proc do_undo*(): cint{.cdecl, importc: "rl_do_undo", dynlib: readlineDll.} -proc begin_undo_group*(): cint{.cdecl, importc: "rl_begin_undo_group", - dynlib: readlineDll.} -proc end_undo_group*(): cint{.cdecl, importc: "rl_end_undo_group", - dynlib: readlineDll.} -proc modifying*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_modifying", - dynlib: readlineDll.} -# Functions for redisplay. - -proc redisplay*(){.cdecl, importc: "rl_redisplay", dynlib: readlineDll.} -proc on_new_line*(): cint{.cdecl, importc: "rl_on_new_line", dynlib: readlineDll.} -proc on_new_line_with_prompt*(): cint{.cdecl, - importc: "rl_on_new_line_with_prompt", - dynlib: readlineDll.} -proc forced_update_display*(): cint{.cdecl, importc: "rl_forced_update_display", - dynlib: readlineDll.} -proc clear_message*(): cint{.cdecl, importc: "rl_clear_message", - dynlib: readlineDll.} -proc reset_line_state*(): cint{.cdecl, importc: "rl_reset_line_state", - dynlib: readlineDll.} -proc crlf*(): cint{.cdecl, importc: "rl_crlf", dynlib: readlineDll.} -proc message*(a2: cstring): cint{.varargs, cdecl, importc: "rl_message", - dynlib: readlineDll.} -proc show_char*(a2: cint): cint{.cdecl, importc: "rl_show_char", - dynlib: readlineDll.} -# Undocumented in texinfo manual. - -proc character_len*(a2: cint, a3: cint): cint{.cdecl, - importc: "rl_character_len", dynlib: readlineDll.} -# Save and restore internal prompt redisplay information. - -proc save_prompt*(){.cdecl, importc: "rl_save_prompt", dynlib: readlineDll.} -proc restore_prompt*(){.cdecl, importc: "rl_restore_prompt", dynlib: readlineDll.} -# Modifying text. - -proc replace_line*(a2: cstring, a3: cint){.cdecl, importc: "rl_replace_line", - dynlib: readlineDll.} -proc insert_text*(a2: cstring): cint{.cdecl, importc: "rl_insert_text", - dynlib: readlineDll.} -proc delete_text*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_delete_text", - dynlib: readlineDll.} -proc kill_text*(a2: cint, a3: cint): cint{.cdecl, importc: "rl_kill_text", - dynlib: readlineDll.} -proc copy_text*(a2: cint, a3: cint): cstring{.cdecl, importc: "rl_copy_text", - dynlib: readlineDll.} -# Terminal and tty mode management. - -proc prep_terminal*(a2: cint){.cdecl, importc: "rl_prep_terminal", - dynlib: readlineDll.} -proc deprep_terminal*(){.cdecl, importc: "rl_deprep_terminal", - dynlib: readlineDll.} -proc tty_set_default_bindings*(a2: PKeymap){.cdecl, - importc: "rl_tty_set_default_bindings", dynlib: readlineDll.} -proc tty_unset_default_bindings*(a2: PKeymap){.cdecl, - importc: "rl_tty_unset_default_bindings", dynlib: readlineDll.} -proc reset_terminal*(a2: cstring): cint{.cdecl, importc: "rl_reset_terminal", - dynlib: readlineDll.} -proc resize_terminal*(){.cdecl, importc: "rl_resize_terminal", - dynlib: readlineDll.} -proc set_screen_size*(a2: cint, a3: cint){.cdecl, importc: "rl_set_screen_size", - dynlib: readlineDll.} -proc get_screen_size*(a2: ptr cint, a3: ptr cint){.cdecl, - importc: "rl_get_screen_size", dynlib: readlineDll.} -proc reset_screen_size*(){.cdecl, importc: "rl_reset_screen_size", - dynlib: readlineDll.} -proc get_termcap*(a2: cstring): cstring{.cdecl, importc: "rl_get_termcap", - dynlib: readlineDll.} -# Functions for character input. - -proc stuff_char*(a2: cint): cint{.cdecl, importc: "rl_stuff_char", - dynlib: readlineDll.} -proc execute_next*(a2: cint): cint{.cdecl, importc: "rl_execute_next", - dynlib: readlineDll.} -proc clear_pending_input*(): cint{.cdecl, importc: "rl_clear_pending_input", - dynlib: readlineDll.} -proc read_key*(): cint{.cdecl, importc: "rl_read_key", dynlib: readlineDll.} -proc getc*(a2: File): cint{.cdecl, importc: "rl_getc", dynlib: readlineDll.} -proc set_keyboard_input_timeout*(a2: cint): cint{.cdecl, - importc: "rl_set_keyboard_input_timeout", dynlib: readlineDll.} -# `Public' utility functions . - -proc extend_line_buffer*(a2: cint){.cdecl, importc: "rl_extend_line_buffer", - dynlib: readlineDll.} -proc ding*(): cint{.cdecl, importc: "rl_ding", dynlib: readlineDll.} -proc alphabetic*(a2: cint): cint{.cdecl, importc: "rl_alphabetic", - dynlib: readlineDll.} -proc free*(a2: pointer){.cdecl, importc: "rl_free", dynlib: readlineDll.} -# Readline signal handling, from signals.c - -proc set_signals*(): cint{.cdecl, importc: "rl_set_signals", dynlib: readlineDll.} -proc clear_signals*(): cint{.cdecl, importc: "rl_clear_signals", - dynlib: readlineDll.} -proc cleanup_after_signal*(){.cdecl, importc: "rl_cleanup_after_signal", - dynlib: readlineDll.} -proc reset_after_signal*(){.cdecl, importc: "rl_reset_after_signal", - dynlib: readlineDll.} -proc free_line_state*(){.cdecl, importc: "rl_free_line_state", - dynlib: readlineDll.} -proc echo_signal_char*(a2: cint){.cdecl, importc: "rl_echo_signal_char", - dynlib: readlineDll.} -proc set_paren_blink_timeout*(a2: cint): cint{.cdecl, - importc: "rl_set_paren_blink_timeout", dynlib: readlineDll.} -# Undocumented. - -proc maybe_save_line*(): cint{.cdecl, importc: "rl_maybe_save_line", - dynlib: readlineDll.} -proc maybe_unsave_line*(): cint{.cdecl, importc: "rl_maybe_unsave_line", - dynlib: readlineDll.} -proc maybe_replace_line*(): cint{.cdecl, importc: "rl_maybe_replace_line", - dynlib: readlineDll.} -# Completion functions. - -proc complete_internal*(a2: cint): cint{.cdecl, importc: "rl_complete_internal", - dynlib: readlineDll.} -proc display_match_list*(a2: cstringArray, a3: cint, a4: cint){.cdecl, - importc: "rl_display_match_list", dynlib: readlineDll.} -proc completion_matches*(a2: cstring, a3: Compentry_func): cstringArray{. - cdecl, importc: "rl_completion_matches", dynlib: readlineDll.} -proc username_completion_function*(a2: cstring, a3: cint): cstring{.cdecl, - importc: "rl_username_completion_function", dynlib: readlineDll.} -proc filename_completion_function*(a2: cstring, a3: cint): cstring{.cdecl, - importc: "rl_filename_completion_function", dynlib: readlineDll.} -proc completion_mode*(a2: CommandFunc): cint{.cdecl, - importc: "rl_completion_mode", dynlib: readlineDll.} -# **************************************************************** -# -# Well Published Variables -# -# **************************************************************** - -when false: - # The version of this incarnation of the readline library. - var library_version*{.importc: "rl_library_version", dynlib: readlineDll.}: cstring - # e.g., "4.2" - var readline_version*{.importc: "rl_readline_version", dynlib: readlineDll.}: cint - # e.g., 0x0402 - # True if this is real GNU readline. - var gnu_readline_p*{.importc: "rl_gnu_readline_p", dynlib: readlineDll.}: cint - # Flags word encapsulating the current readline state. - var readline_state*{.importc: "rl_readline_state", dynlib: readlineDll.}: cint - # Says which editing mode readline is currently using. 1 means emacs mode; - # 0 means vi mode. - var editing_mode*{.importc: "rl_editing_mode", dynlib: readlineDll.}: cint - # Insert or overwrite mode for emacs mode. 1 means insert mode; 0 means - # overwrite mode. Reset to insert mode on each input line. - var insert_mode*{.importc: "rl_insert_mode", dynlib: readlineDll.}: cint - # The name of the calling program. You should initialize this to - # whatever was in argv[0]. It is used when parsing conditionals. - var readline_name*{.importc: "rl_readline_name", dynlib: readlineDll.}: cstring - # The prompt readline uses. This is set from the argument to - # readline (), and should not be assigned to directly. - var prompt*{.importc: "rl_prompt", dynlib: readlineDll.}: cstring - # The prompt string that is actually displayed by rl_redisplay. Public so - # applications can more easily supply their own redisplay functions. - var display_prompt*{.importc: "rl_display_prompt", dynlib: readlineDll.}: cstring - # The line buffer that is in use. - var line_buffer*{.importc: "rl_line_buffer", dynlib: readlineDll.}: cstring - # The location of point, and end. - var point*{.importc: "rl_point", dynlib: readlineDll.}: cint - var theEnd*{.importc: "rl_end", dynlib: readlineDll.}: cint - # The mark, or saved cursor position. - var mark*{.importc: "rl_mark", dynlib: readlineDll.}: cint - # Flag to indicate that readline has finished with the current input - # line and should return it. - var done*{.importc: "rl_done", dynlib: readlineDll.}: cint - # If set to a character value, that will be the next keystroke read. - var pending_input*{.importc: "rl_pending_input", dynlib: readlineDll.}: cint - # Non-zero if we called this function from _rl_dispatch(). It's present - # so functions can find out whether they were called from a key binding - # or directly from an application. - var dispatching*{.importc: "rl_dispatching", dynlib: readlineDll.}: cint - # Non-zero if the user typed a numeric argument before executing the - # current function. - var explicit_arg*{.importc: "rl_explicit_arg", dynlib: readlineDll.}: cint - # The current value of the numeric argument specified by the user. - var numeric_arg*{.importc: "rl_numeric_arg", dynlib: readlineDll.}: cint - # The address of the last command function Readline executed. - var last_func*{.importc: "rl_last_func", dynlib: readlineDll.}: CommandFunc - # The name of the terminal to use. - var terminal_name*{.importc: "rl_terminal_name", dynlib: readlineDll.}: cstring - # The input and output streams. - var instream*{.importc: "rl_instream", dynlib: readlineDll.}: File - var outstream*{.importc: "rl_outstream", dynlib: readlineDll.}: File - # If non-zero, Readline gives values of LINES and COLUMNS from the environment - # greater precedence than values fetched from the kernel when computing the - # screen dimensions. - var prefer_env_winsize*{.importc: "rl_prefer_env_winsize", dynlib: readlineDll.}: cint - # If non-zero, then this is the address of a function to call just - # before readline_internal () prints the first prompt. - var startup_hook*{.importc: "rl_startup_hook", dynlib: readlineDll.}: hook_func - # If non-zero, this is the address of a function to call just before - # readline_internal_setup () returns and readline_internal starts - # reading input characters. - var pre_input_hook*{.importc: "rl_pre_input_hook", dynlib: readlineDll.}: hook_func - # The address of a function to call periodically while Readline is - # awaiting character input, or NULL, for no event handling. - var event_hook*{.importc: "rl_event_hook", dynlib: readlineDll.}: hook_func - # The address of the function to call to fetch a character from the current - # Readline input stream - var getc_function*{.importc: "rl_getc_function", dynlib: readlineDll.}: getc_func - var redisplay_function*{.importc: "rl_redisplay_function", dynlib: readlineDll.}: voidfunc - var prep_term_function*{.importc: "rl_prep_term_function", dynlib: readlineDll.}: vintfunc - var deprep_term_function*{.importc: "rl_deprep_term_function", - dynlib: readlineDll.}: voidfunc - # Dispatch variables. - var executing_keymap*{.importc: "rl_executing_keymap", dynlib: readlineDll.}: PKeymap - var binding_keymap*{.importc: "rl_binding_keymap", dynlib: readlineDll.}: PKeymap - # Display variables. - # If non-zero, readline will erase the entire line, including any prompt, - # if the only thing typed on an otherwise-blank line is something bound to - # rl_newline. - var erase_empty_line*{.importc: "rl_erase_empty_line", dynlib: readlineDll.}: cint - # If non-zero, the application has already printed the prompt (rl_prompt) - # before calling readline, so readline should not output it the first time - # redisplay is done. - var already_prompted*{.importc: "rl_already_prompted", dynlib: readlineDll.}: cint - # A non-zero value means to read only this many characters rather than - # up to a character bound to accept-line. - var num_chars_to_read*{.importc: "rl_num_chars_to_read", dynlib: readlineDll.}: cint - # The text of a currently-executing keyboard macro. - var executing_macro*{.importc: "rl_executing_macro", dynlib: readlineDll.}: cstring - # Variables to control readline signal handling. - # If non-zero, readline will install its own signal handlers for - # SIGINT, SIGTERM, SIGQUIT, SIGALRM, SIGTSTP, SIGTTIN, and SIGTTOU. - var catch_signals*{.importc: "rl_catch_signals", dynlib: readlineDll.}: cint - # If non-zero, readline will install a signal handler for SIGWINCH - # that also attempts to call any calling application's SIGWINCH signal - # handler. Note that the terminal is not cleaned up before the - # application's signal handler is called; use rl_cleanup_after_signal() - # to do that. - var catch_sigwinch*{.importc: "rl_catch_sigwinch", dynlib: readlineDll.}: cint - # Completion variables. - # Pointer to the generator function for completion_matches (). - # NULL means to use rl_filename_completion_function (), the default - # filename completer. - var completion_entry_function*{.importc: "rl_completion_entry_function", - dynlib: readlineDll.}: compentry_func - # Optional generator for menu completion. Default is - # rl_completion_entry_function (rl_filename_completion_function). - var menu_completion_entry_function*{.importc: "rl_menu_completion_entry_function", - dynlib: readlineDll.}: compentry_func - # If rl_ignore_some_completions_function is non-NULL it is the address - # of a function to call after all of the possible matches have been - # generated, but before the actual completion is done to the input line. - # The function is called with one argument; a NULL terminated array - # of (char *). If your function removes any of the elements, they - # must be free()'ed. - var ignore_some_completions_function*{. - importc: "rl_ignore_some_completions_function", dynlib: readlineDll.}: compignore_func - # Pointer to alternative function to create matches. - # Function is called with TEXT, START, and END. - # START and END are indices in RL_LINE_BUFFER saying what the boundaries - # of TEXT are. - # If this function exists and returns NULL then call the value of - # rl_completion_entry_function to try to match, otherwise use the - # array of strings returned. - var attempted_completion_function*{.importc: "rl_attempted_completion_function", - dynlib: readlineDll.}: completion_func - # The basic list of characters that signal a break between words for the - # completer routine. The initial contents of this variable is what - # breaks words in the shell, i.e. "n\"\\'`@$>". - var basic_word_break_characters*{.importc: "rl_basic_word_break_characters", - dynlib: readlineDll.}: cstring - # The list of characters that signal a break between words for - # rl_complete_internal. The default list is the contents of - # rl_basic_word_break_characters. - var completer_word_break_characters*{.importc: "rl_completer_word_break_characters", - dynlib: readlineDll.}: cstring - # Hook function to allow an application to set the completion word - # break characters before readline breaks up the line. Allows - # position-dependent word break characters. - var completion_word_break_hook*{.importc: "rl_completion_word_break_hook", - dynlib: readlineDll.}: cpvfunc - # List of characters which can be used to quote a substring of the line. - # Completion occurs on the entire substring, and within the substring - # rl_completer_word_break_characters are treated as any other character, - # unless they also appear within this list. - var completer_quote_characters*{.importc: "rl_completer_quote_characters", - dynlib: readlineDll.}: cstring - # List of quote characters which cause a word break. - var basic_quote_characters*{.importc: "rl_basic_quote_characters", - dynlib: readlineDll.}: cstring - # List of characters that need to be quoted in filenames by the completer. - var filename_quote_characters*{.importc: "rl_filename_quote_characters", - dynlib: readlineDll.}: cstring - # List of characters that are word break characters, but should be left - # in TEXT when it is passed to the completion function. The shell uses - # this to help determine what kind of completing to do. - var special_prefixes*{.importc: "rl_special_prefixes", dynlib: readlineDll.}: cstring - # If non-zero, then this is the address of a function to call when - # completing on a directory name. The function is called with - # the address of a string (the current directory name) as an arg. It - # changes what is displayed when the possible completions are printed - # or inserted. - var directory_completion_hook*{.importc: "rl_directory_completion_hook", - dynlib: readlineDll.}: icppfunc - # If non-zero, this is the address of a function to call when completing - # a directory name. This function takes the address of the directory name - # to be modified as an argument. Unlike rl_directory_completion_hook, it - # only modifies the directory name used in opendir(2), not what is displayed - # when the possible completions are printed or inserted. It is called - # before rl_directory_completion_hook. I'm not happy with how this works - # yet, so it's undocumented. - var directory_rewrite_hook*{.importc: "rl_directory_rewrite_hook", - dynlib: readlineDll.}: icppfunc - # If non-zero, this is the address of a function to call when reading - # directory entries from the filesystem for completion and comparing - # them to the partial word to be completed. The function should - # either return its first argument (if no conversion takes place) or - # newly-allocated memory. This can, for instance, convert filenames - # between character sets for comparison against what's typed at the - # keyboard. The returned value is what is added to the list of - # matches. The second argument is the length of the filename to be - # converted. - var filename_rewrite_hook*{.importc: "rl_filename_rewrite_hook", - dynlib: readlineDll.}: dequote_func - # If non-zero, then this is the address of a function to call when - # completing a word would normally display the list of possible matches. - # This function is called instead of actually doing the display. - # It takes three arguments: (char **matches, int num_matches, int max_length) - # where MATCHES is the array of strings that matched, NUM_MATCHES is the - # number of strings in that array, and MAX_LENGTH is the length of the - # longest string in that array. - var completion_display_matches_hook*{.importc: "rl_completion_display_matches_hook", - dynlib: readlineDll.}: compdisp_func - # Non-zero means that the results of the matches are to be treated - # as filenames. This is ALWAYS zero on entry, and can only be changed - # within a completion entry finder function. - var filename_completion_desired*{.importc: "rl_filename_completion_desired", - dynlib: readlineDll.}: cint - # Non-zero means that the results of the matches are to be quoted using - # double quotes (or an application-specific quoting mechanism) if the - # filename contains any characters in rl_word_break_chars. This is - # ALWAYS non-zero on entry, and can only be changed within a completion - # entry finder function. - var filename_quoting_desired*{.importc: "rl_filename_quoting_desired", - dynlib: readlineDll.}: cint - # Set to a function to quote a filename in an application-specific fashion. - # Called with the text to quote, the type of match found (single or multiple) - # and a pointer to the quoting character to be used, which the function can - # reset if desired. - var filename_quoting_function*{.importc: "rl_filename_quoting_function", - dynlib: readlineDll.}: quote_func - # Function to call to remove quoting characters from a filename. Called - # before completion is attempted, so the embedded quotes do not interfere - # with matching names in the file system. - var filename_dequoting_function*{.importc: "rl_filename_dequoting_function", - dynlib: readlineDll.}: dequote_func - # Function to call to decide whether or not a word break character is - # quoted. If a character is quoted, it does not break words for the - # completer. - var char_is_quoted_p*{.importc: "rl_char_is_quoted_p", dynlib: readlineDll.}: linebuf_func - # Non-zero means to suppress normal filename completion after the - # user-specified completion function has been called. - var attempted_completion_over*{.importc: "rl_attempted_completion_over", - dynlib: readlineDll.}: cint - # Set to a character describing the type of completion being attempted by - # rl_complete_internal; available for use by application completion - # functions. - var completion_type*{.importc: "rl_completion_type", dynlib: readlineDll.}: cint - # Set to the last key used to invoke one of the completion functions - var completion_invoking_key*{.importc: "rl_completion_invoking_key", - dynlib: readlineDll.}: cint - # Up to this many items will be displayed in response to a - # possible-completions call. After that, we ask the user if she - # is sure she wants to see them all. The default value is 100. - var completion_query_items*{.importc: "rl_completion_query_items", - dynlib: readlineDll.}: cint - # Character appended to completed words when at the end of the line. The - # default is a space. Nothing is added if this is '\0'. - var completion_append_character*{.importc: "rl_completion_append_character", - dynlib: readlineDll.}: cint - # If set to non-zero by an application completion function, - # rl_completion_append_character will not be appended. - var completion_suppress_append*{.importc: "rl_completion_suppress_append", - dynlib: readlineDll.}: cint - # Set to any quote character readline thinks it finds before any application - # completion function is called. - var completion_quote_character*{.importc: "rl_completion_quote_character", - dynlib: readlineDll.}: cint - # Set to a non-zero value if readline found quoting anywhere in the word to - # be completed; set before any application completion function is called. - var completion_found_quote*{.importc: "rl_completion_found_quote", - dynlib: readlineDll.}: cint - # If non-zero, the completion functions don't append any closing quote. - # This is set to 0 by rl_complete_internal and may be changed by an - # application-specific completion function. - var completion_suppress_quote*{.importc: "rl_completion_suppress_quote", - dynlib: readlineDll.}: cint - # If non-zero, readline will sort the completion matches. On by default. - var sort_completion_matches*{.importc: "rl_sort_completion_matches", - dynlib: readlineDll.}: cint - # If non-zero, a slash will be appended to completed filenames that are - # symbolic links to directory names, subject to the value of the - # mark-directories variable (which is user-settable). This exists so - # that application completion functions can override the user's preference - # (set via the mark-symlinked-directories variable) if appropriate. - # It's set to the value of _rl_complete_mark_symlink_dirs in - # rl_complete_internal before any application-specific completion - # function is called, so without that function doing anything, the user's - # preferences are honored. - var completion_mark_symlink_dirs*{.importc: "rl_completion_mark_symlink_dirs", - dynlib: readlineDll.}: cint - # If non-zero, then disallow duplicates in the matches. - var ignore_completion_duplicates*{.importc: "rl_ignore_completion_duplicates", - dynlib: readlineDll.}: cint - # If this is non-zero, completion is (temporarily) inhibited, and the - # completion character will be inserted as any other. - var inhibit_completion*{.importc: "rl_inhibit_completion", dynlib: readlineDll.}: cint -# Input error; can be returned by (*rl_getc_function) if readline is reading -# a top-level command (RL_ISSTATE (RL_STATE_READCMD)). - -const - READERR* = (- 2) - -# Definitions available for use by readline clients. - -const - PROMPT_START_IGNORE* = '\x01' - PROMPT_END_IGNORE* = '\x02' - -# Possible values for do_replace argument to rl_filename_quoting_function, -# called by rl_complete_internal. - -const - NO_MATCH* = 0 - SINGLE_MATCH* = 1 - MULT_MATCH* = 2 - -# Possible state values for rl_readline_state - -const - STATE_NONE* = 0x00000000 # no state; before first call - STATE_INITIALIZING* = 0x00000001 # initializing - STATE_INITIALIZED* = 0x00000002 # initialization done - STATE_TERMPREPPED* = 0x00000004 # terminal is prepped - STATE_READCMD* = 0x00000008 # reading a command key - STATE_METANEXT* = 0x00000010 # reading input after ESC - STATE_DISPATCHING* = 0x00000020 # dispatching to a command - STATE_MOREINPUT* = 0x00000040 # reading more input in a command function - STATE_ISEARCH* = 0x00000080 # doing incremental search - STATE_NSEARCH* = 0x00000100 # doing non-inc search - STATE_SEARCH* = 0x00000200 # doing a history search - STATE_NUMERICARG* = 0x00000400 # reading numeric argument - STATE_MACROINPUT* = 0x00000800 # getting input from a macro - STATE_MACRODEF* = 0x00001000 # defining keyboard macro - STATE_OVERWRITE* = 0x00002000 # overwrite mode - STATE_COMPLETING* = 0x00004000 # doing completion - STATE_SIGHANDLER* = 0x00008000 # in readline sighandler - STATE_UNDOING* = 0x00010000 # doing an undo - STATE_INPUTPENDING* = 0x00020000 # rl_execute_next called - STATE_TTYCSAVED* = 0x00040000 # tty special chars saved - STATE_CALLBACK* = 0x00080000 # using the callback interface - STATE_VIMOTION* = 0x00100000 # reading vi motion arg - STATE_MULTIKEY* = 0x00200000 # reading multiple-key command - STATE_VICMDONCE* = 0x00400000 # entered vi command mode at least once - STATE_REDISPLAYING* = 0x00800000 # updating terminal display - STATE_DONE* = 0x01000000 # done; accepted line - -template SETSTATE*(x: expr): stmt = - readline_state = readline_state or (x) - -template UNSETSTATE*(x: expr): stmt = - readline_state = readline_state and not (x) - -template ISSTATE*(x: expr): expr = - (readline_state and x) != 0 - -type - Readline_state*{.pure, final.} = object - point*: cint # line state - theEnd*: cint - mark*: cint - buffer*: cstring - buflen*: cint - ul*: ptr UNDO_LIST - prompt*: cstring # global state - rlstate*: cint - done*: cint - kmap*: PKeymap # input state - lastfunc*: CommandFunc - insmode*: cint - edmode*: cint - kseqlen*: cint - inf*: File - outf*: File - pendingin*: cint - theMacro*: cstring # signal state - catchsigs*: cint - catchsigwinch*: cint # search state - # completion state - # options state - # reserved for future expansion, so the struct size doesn't change - reserved*: array[0..64 - 1, char] -{.deprecated: [Treadline_state: Readline_state].} - - -proc save_state*(a2: ptr Readline_state): cint{.cdecl, - importc: "rl_save_state", dynlib: readlineDll.} -proc restore_state*(a2: ptr Readline_state): cint{.cdecl, - importc: "rl_restore_state", dynlib: readlineDll.} diff --git a/lib/wrappers/readline/rltypedefs.nim b/lib/wrappers/readline/rltypedefs.nim deleted file mode 100644 index 759b81297..000000000 --- a/lib/wrappers/readline/rltypedefs.nim +++ /dev/null @@ -1,79 +0,0 @@ -# rltypedefs.h -- Type declarations for readline functions. -# Copyright (C) 2000-2009 Free Software Foundation, Inc. -# -# This file is part of the GNU Readline Library (Readline), a library -# for reading lines of text with interactive input and history editing. -# -# Readline is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# Readline is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with Readline. If not, see . -# - -type - Function* = proc (): cint{.cdecl.} - VFunction* = proc (){.cdecl.} - CPFunction* = proc (): cstring{.cdecl.} - CPPFunction* = proc (): cstringArray{.cdecl.} -{.deprecated: [TFunction: Function, TVFunction: VFunction, - TCPFunction: CPFunction, TCPPFunction: CPPFunction].} - -# Bindable functions - -type - Command_func* = proc (a2: cint, a3: cint): cint{.cdecl.} -{.deprecated: [Tcommand_func: Command_func].} - -# Typedefs for the completion system - -type - Compentry_func* = proc (a2: cstring, a3: cint): cstring{.cdecl.} - Completion_func* = proc (a2: cstring, a3: cint, a4: cint): cstringArray{. - cdecl.} - Quote_func* = proc (a2: cstring, a3: cint, a4: cstring): cstring{.cdecl.} - Dequote_func* = proc (a2: cstring, a3: cint): cstring{.cdecl.} - Compignore_func* = proc (a2: cstringArray): cint{.cdecl.} - Compdisp_func* = proc (a2: cstringArray, a3: cint, a4: cint){.cdecl.} -{.deprecated: [Tcompentry_func: Compentry_func,Tcompletion_func: Completion_func, - Tquote_func: Quote_func, Tdequote_func: Dequote_func, - Tcompignore_func: Compignore_func, Tcompdisp_func: Compdisp_func].} -# Type for input and pre-read hook functions like rl_event_hook - -type - Thook_func* = proc (): cint{.cdecl.} - -# Input function type - -type - Tgetc_func* = proc (a2: File): cint{.cdecl.} - -# Generic function that takes a character buffer (which could be the readline -# line buffer) and an index into it (which could be rl_point) and returns -# an int. - -type - Tlinebuf_func* = proc (a2: cstring, a3: cint): cint{.cdecl.} - -# `Generic' function pointer typedefs - -type - Tintfunc* = proc (a2: cint): cint{.cdecl.} - Tivoidfunc* = proc (): cint{.cdecl.} - Ticpfunc* = proc (a2: cstring): cint{.cdecl.} - Ticppfunc* = proc (a2: cstringArray): cint{.cdecl.} - Tvoidfunc* = proc (){.cdecl.} - Tvintfunc* = proc (a2: cint){.cdecl.} - Tvcpfunc* = proc (a2: cstring){.cdecl.} - Tvcppfunc* = proc (a2: cstringArray){.cdecl.} - Tcpvfunc* = proc (): cstring{.cdecl.} - Tcpifunc* = proc (a2: cint): cstring{.cdecl.} - Tcpcpfunc* = proc (a2: cstring): cstring{.cdecl.} - Tcpcppfunc* = proc (a2: cstringArray): cstring{.cdecl.} diff --git a/lib/wrappers/readline/tweaked/history.h b/lib/wrappers/readline/tweaked/history.h deleted file mode 100644 index b79123790..000000000 --- a/lib/wrappers/readline/tweaked/history.h +++ /dev/null @@ -1,257 +0,0 @@ -/* history.h -- the names of functions that you can call in history. */ - -/* Copyright (C) 1989-2009 Free Software Foundation, Inc. - - This file contains the GNU History Library (History), a set of - routines for managing the text of previously typed lines. - - History is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - History is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with History. If not, see . -*/ - -#ifdef C2NIM -# private historyDll -# dynlib historyDll -# cdecl -# if defined(windows) -# define historyDll "history.dll" -# elif defined(macosx) -# define historyDll "libhistory.dynlib" -# else -# define historyDll "libhistory.so.6(|.0)" -# endif -# prefix rl_ -# prefix RL_ -# suffix _t -# typeprefixes -# def PARAMS(x) x -# def time_t TTime -#endif - -# include "times" -# include "rltypedefs.h" - -typedef void *histdata_t; - -/* The structure used to store a history entry. */ -typedef struct _hist_entry { - char *line; - char *timestamp; /* char * rather than time_t for read/write */ - histdata_t data; -} HIST_ENTRY; - -/* Size of the history-library-managed space in history entry HS. */ -#define HISTENT_BYTES(hs) (strlen(hs.line) + strlen(hs.timestamp)) - -/* A structure used to pass the current state of the history stuff around. */ -typedef struct _hist_state { - HIST_ENTRY **entries; /* Pointer to the entries themselves. */ - int offset; /* The location pointer within this array. */ - int length; /* Number of elements within this array. */ - int size; /* Number of slots allocated to this array. */ - int flags; -} HISTORY_STATE; - -/* Flag values for the `flags' member of HISTORY_STATE. */ -#define HS_STIFLED 0x01 - -/* Initialization and state management. */ - -/* Begin a session in which the history functions might be used. This - just initializes the interactive variables. */ -extern void using_history PARAMS((void)); - -/* Return the current HISTORY_STATE of the history. */ -extern HISTORY_STATE *history_get_history_state PARAMS((void)); - -/* Set the state of the current history array to STATE. */ -extern void history_set_history_state PARAMS((HISTORY_STATE *)); - -/* Manage the history list. */ - -/* Place STRING at the end of the history list. - The associated data field (if any) is set to NULL. */ -extern void add_history PARAMS((const char *)); - -/* Change the timestamp associated with the most recent history entry to - STRING. */ -extern void add_history_time PARAMS((const char *)); - -/* A reasonably useless function, only here for completeness. WHICH - is the magic number that tells us which element to delete. The - elements are numbered from 0. */ -extern HIST_ENTRY *remove_history PARAMS((int)); - -/* Free the history entry H and return any application-specific data - associated with it. */ -extern histdata_t free_history_entry PARAMS((HIST_ENTRY *)); - -/* Make the history entry at WHICH have LINE and DATA. This returns - the old entry so you can dispose of the data. In the case of an - invalid WHICH, a NULL pointer is returned. */ -extern HIST_ENTRY *replace_history_entry PARAMS((int, const char *, histdata_t)); - -/* Clear the history list and start over. */ -extern void clear_history PARAMS((void)); - -/* Stifle the history list, remembering only MAX number of entries. */ -extern void stifle_history PARAMS((int)); - -/* Stop stifling the history. This returns the previous amount the - history was stifled by. The value is positive if the history was - stifled, negative if it wasn't. */ -extern int unstifle_history PARAMS((void)); - -/* Return 1 if the history is stifled, 0 if it is not. */ -extern int history_is_stifled PARAMS((void)); - -/* Information about the history list. */ - -/* Return a NULL terminated array of HIST_ENTRY which is the current input - history. Element 0 of this list is the beginning of time. If there - is no history, return NULL. */ -extern HIST_ENTRY **history_list PARAMS((void)); - -/* Returns the number which says what history element we are now - looking at. */ -extern int where_history PARAMS((void)); - -/* Return the history entry at the current position, as determined by - history_offset. If there is no entry there, return a NULL pointer. */ -extern HIST_ENTRY *current_history PARAMS((void)); - -/* Return the history entry which is logically at OFFSET in the history - array. OFFSET is relative to history_base. */ -extern HIST_ENTRY *history_get PARAMS((int)); - -/* Return the timestamp associated with the HIST_ENTRY * passed as an - argument */ -extern time_t history_get_time PARAMS((HIST_ENTRY *)); - -/* Return the number of bytes that the primary history entries are using. - This just adds up the lengths of the_history->lines. */ -extern int history_total_bytes PARAMS((void)); - -/* Moving around the history list. */ - -/* Set the position in the history list to POS. */ -extern int history_set_pos PARAMS((int)); - -/* Back up history_offset to the previous history entry, and return - a pointer to that entry. If there is no previous entry, return - a NULL pointer. */ -extern HIST_ENTRY *previous_history PARAMS((void)); - -/* Move history_offset forward to the next item in the input_history, - and return the a pointer to that entry. If there is no next entry, - return a NULL pointer. */ -extern HIST_ENTRY *next_history PARAMS((void)); - -/* Searching the history list. */ - -/* Search the history for STRING, starting at history_offset. - If DIRECTION < 0, then the search is through previous entries, - else through subsequent. If the string is found, then - current_history () is the history entry, and the value of this function - is the offset in the line of that history entry that the string was - found in. Otherwise, nothing is changed, and a -1 is returned. */ -extern int history_search PARAMS((const char *, int)); - -/* Search the history for STRING, starting at history_offset. - The search is anchored: matching lines must begin with string. - DIRECTION is as in history_search(). */ -extern int history_search_prefix PARAMS((const char *, int)); - -/* Search for STRING in the history list, starting at POS, an - absolute index into the list. DIR, if negative, says to search - backwards from POS, else forwards. - Returns the absolute index of the history element where STRING - was found, or -1 otherwise. */ -extern int history_search_pos PARAMS((const char *, int, int)); - -/* Managing the history file. */ - -/* Add the contents of FILENAME to the history list, a line at a time. - If FILENAME is NULL, then read from ~/.history. Returns 0 if - successful, or errno if not. */ -extern int read_history PARAMS((const char *)); - -/* Read a range of lines from FILENAME, adding them to the history list. - Start reading at the FROM'th line and end at the TO'th. If FROM - is zero, start at the beginning. If TO is less than FROM, read - until the end of the file. If FILENAME is NULL, then read from - ~/.history. Returns 0 if successful, or errno if not. */ -extern int read_history_range PARAMS((const char *, int, int)); - -/* Write the current history to FILENAME. If FILENAME is NULL, - then write the history list to ~/.history. Values returned - are as in read_history (). */ -extern int write_history PARAMS((const char *)); - -/* Append NELEMENT entries to FILENAME. The entries appended are from - the end of the list minus NELEMENTs up to the end of the list. */ -extern int append_history PARAMS((int, const char *)); - -/* Truncate the history file, leaving only the last NLINES lines. */ -extern int history_truncate_file PARAMS((const char *, int)); - -/* History expansion. */ - -/* Expand the string STRING, placing the result into OUTPUT, a pointer - to a string. Returns: - - 0) If no expansions took place (or, if the only change in - the text was the de-slashifying of the history expansion - character) - 1) If expansions did take place - -1) If there was an error in expansion. - 2) If the returned line should just be printed. - - If an error occurred in expansion, then OUTPUT contains a descriptive - error message. */ -extern int history_expand PARAMS((char *, char **)); - -/* Extract a string segment consisting of the FIRST through LAST - arguments present in STRING. Arguments are broken up as in - the shell. */ -extern char *history_arg_extract PARAMS((int, int, const char *)); - -/* Return the text of the history event beginning at the current - offset into STRING. Pass STRING with *INDEX equal to the - history_expansion_char that begins this specification. - DELIMITING_QUOTE is a character that is allowed to end the string - specification for what to search for in addition to the normal - characters `:', ` ', `\t', `\n', and sometimes `?'. */ -extern char *get_history_event PARAMS((const char *, int *, int)); - -/* Return an array of tokens, much as the shell might. The tokens are - parsed out of STRING. */ -extern char **history_tokenize PARAMS((const char *)); - -#if false -/* Exported history variables. */ -extern int history_base; -extern int history_length; -extern int history_max_entries; -extern char history_expansion_char; -extern char history_subst_char; -extern char *history_word_delimiters; -extern char history_comment_char; -extern char *history_no_expand_chars; -extern char *history_search_delimiter_chars; -extern int history_quotes_inhibit_expansion; - -extern int history_write_timestamps; - -#endif - diff --git a/lib/wrappers/readline/tweaked/readline.h b/lib/wrappers/readline/tweaked/readline.h deleted file mode 100644 index b13fbdbbe..000000000 --- a/lib/wrappers/readline/tweaked/readline.h +++ /dev/null @@ -1,956 +0,0 @@ -/* Readline.h -- the names of functions callable from within readline. */ - -/* Copyright (C) 1987-2009 Free Software Foundation, Inc. - - This file is part of the GNU Readline Library (Readline), a library - for reading lines of text with interactive input and history editing. - - Readline is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - Readline is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with Readline. If not, see . -*/ - -#ifdef C2NIM -# private readlineDll -# dynlib readlineDll -# cdecl -# if defined(windows) -# define readlineDll "readline.dll" -# elif defined(macosx) -# define readlineDll "libreadline.dynlib" -# else -# define readlineDll "libreadline.so.6(|.0)" -# endif -# prefix rl_ -# prefix RL_ -# suffix _t -# typeprefixes -# def PARAMS(x) x -# mangle end theEnd -# mangle type typ -# mangle macro theMacro -/*# mangle "'command_func'" TCommandFunc -# mangle vcpfunc TvcpFunc*/ -#endif - -# include "rltypedefs.h" - - -/* Some character stuff. */ -#define control_character_threshold 0x020 /* Smaller than this is control. */ -#define control_character_mask 0x1f /* 0x20 - 1 */ -#define meta_character_threshold 0x07f /* Larger than this is Meta. */ -#define control_character_bit 0x40 /* 0x000000, must be off. */ -#define meta_character_bit 0x080 /* x0000000, must be on. */ -#define largest_char 255 /* Largest character value. */ - -#define CTRL_CHAR(c) (c < control_character_threshold && ((c & 0x80) == 0)) -#define META_CHAR(c) (c > meta_character_threshold && c <= largest_char) - -#define CTRL(c) (c & control_character_mask) -#define META(c) (c | meta_character_bit) - -#define UNMETA(c) (c & ~meta_character_bit) -#define UNCTRL(c) (c|32|control_character_bit) - -/* Beware: these only work with single-byte ASCII characters. */ - -#define RETURN_CHAR CTRL('M'.ord) -#define RUBOUT_CHAR 0x7f -#define ABORT_CHAR CTRL('G'.ord) -#define PAGE_CHAR CTRL('L'.ord) -#define ESC_CHAR CTRL('['.ord) - -/* A keymap contains one entry for each key in the ASCII set. - Each entry consists of a type and a pointer. - FUNCTION is the address of a function to run, or the - address of a keymap to indirect through. - TYPE says which kind of thing FUNCTION is. */ -typedef struct _keymap_entry { - char type; - rl_command_func_t *function; -} KEYMAP_ENTRY; - -/* This must be large enough to hold bindings for all of the characters - in a desired character set (e.g, 128 for ASCII, 256 for ISO Latin-x, - and so on) plus one for subsequence matching. */ -#define KEYMAP_SIZE 257 -#define ANYOTHERKEY KEYMAP_SIZE-1 - -/* I wanted to make the above structure contain a union of: - union { rl_command_func_t *function; struct _keymap_entry *keymap; } value; - but this made it impossible for me to create a static array. - Maybe I need C lessons. */ - -typedef KEYMAP_ENTRY KEYMAP_ENTRY_ARRAY[KEYMAP_SIZE]; -typedef KEYMAP_ENTRY *Keymap; - -/* The values that TYPE can have in a keymap entry. */ -#define ISFUNC 0 -#define ISKMAP 1 -#define ISMACR 2 - -#if false -extern KEYMAP_ENTRY_ARRAY emacs_standard_keymap, emacs_meta_keymap, emacs_ctlx_keymap; -extern KEYMAP_ENTRY_ARRAY vi_insertion_keymap, vi_movement_keymap; -#endif - -/* Return a new, empty keymap. - Free it with free() when you are done. */ -extern Keymap rl_make_bare_keymap PARAMS((void)); - -/* Return a new keymap which is a copy of MAP. */ -extern Keymap rl_copy_keymap PARAMS((Keymap)); - -/* Return a new keymap with the printing characters bound to rl_insert, - the lowercase Meta characters bound to run their equivalents, and - the Meta digits bound to produce numeric arguments. */ -extern Keymap rl_make_keymap PARAMS((void)); - -/* Free the storage associated with a keymap. */ -extern void rl_discard_keymap PARAMS((Keymap)); - -/* These functions actually appear in bind.c */ - -/* Return the keymap corresponding to a given name. Names look like - `emacs' or `emacs-meta' or `vi-insert'. */ -extern Keymap rl_get_keymap_by_name PARAMS((const char *)); - -/* Return the current keymap. */ -extern Keymap rl_get_keymap PARAMS((void)); - -/* Set the current keymap to MAP. */ -extern void rl_set_keymap PARAMS((Keymap)); - -# include "tilde.h" - -/* Hex-encoded Readline version number. */ -#define RL_READLINE_VERSION 0x0600 /* Readline 6.0 */ -#define RL_VERSION_MAJOR 6 -#define RL_VERSION_MINOR 0 - -/* Readline data structures. */ - -/* Maintaining the state of undo. We remember individual deletes and inserts - on a chain of things to do. */ - -/* The actions that undo knows how to undo. Notice that UNDO_DELETE means - to insert some text, and UNDO_INSERT means to delete some text. I.e., - the code tells undo what to undo, not how to undo it. */ -enum undo_code { UNDO_DELETE, UNDO_INSERT, UNDO_BEGIN, UNDO_END }; - -/* What an element of THE_UNDO_LIST looks like. */ -typedef struct undo_list { - struct undo_list *next; - int start, end; /* Where the change took place. */ - char *text; /* The text to insert, if undoing a delete. */ - enum undo_code what; /* Delete, Insert, Begin, End. */ -} UNDO_LIST; - -/* The current undo list for RL_LINE_BUFFER. */ -extern UNDO_LIST *rl_undo_list; - -/* The data structure for mapping textual names to code addresses. */ -typedef struct _funmap { - const char *name; - rl_command_func_t *function; -} FUNMAP; - -extern FUNMAP **funmap; - -/* **************************************************************** */ -/* */ -/* Functions available to bind to key sequences */ -/* */ -/* **************************************************************** */ - -/* Bindable commands for numeric arguments. */ -extern int rl_digit_argument PARAMS((int, int)); -extern int rl_universal_argument PARAMS((int, int)); - -/* Bindable commands for moving the cursor. */ -extern int rl_forward_byte PARAMS((int, int)); -extern int rl_forward_char PARAMS((int, int)); -extern int rl_forward PARAMS((int, int)); -extern int rl_backward_byte PARAMS((int, int)); -extern int rl_backward_char PARAMS((int, int)); -extern int rl_backward PARAMS((int, int)); -extern int rl_beg_of_line PARAMS((int, int)); -extern int rl_end_of_line PARAMS((int, int)); -extern int rl_forward_word PARAMS((int, int)); -extern int rl_backward_word PARAMS((int, int)); -extern int rl_refresh_line PARAMS((int, int)); -extern int rl_clear_screen PARAMS((int, int)); -extern int rl_skip_csi_sequence PARAMS((int, int)); -extern int rl_arrow_keys PARAMS((int, int)); - -/* Bindable commands for inserting and deleting text. */ -extern int rl_insert PARAMS((int, int)); -extern int rl_quoted_insert PARAMS((int, int)); -extern int rl_tab_insert PARAMS((int, int)); -extern int rl_newline PARAMS((int, int)); -extern int rl_do_lowercase_version PARAMS((int, int)); -extern int rl_rubout PARAMS((int, int)); -extern int rl_delete PARAMS((int, int)); -extern int rl_rubout_or_delete PARAMS((int, int)); -extern int rl_delete_horizontal_space PARAMS((int, int)); -extern int rl_delete_or_show_completions PARAMS((int, int)); -extern int rl_insert_comment PARAMS((int, int)); - -/* Bindable commands for changing case. */ -extern int rl_upcase_word PARAMS((int, int)); -extern int rl_downcase_word PARAMS((int, int)); -extern int rl_capitalize_word PARAMS((int, int)); - -/* Bindable commands for transposing characters and words. */ -extern int rl_transpose_words PARAMS((int, int)); -extern int rl_transpose_chars PARAMS((int, int)); - -/* Bindable commands for searching within a line. */ -extern int rl_char_search PARAMS((int, int)); -extern int rl_backward_char_search PARAMS((int, int)); - -/* Bindable commands for readline's interface to the command history. */ -extern int rl_beginning_of_history PARAMS((int, int)); -extern int rl_end_of_history PARAMS((int, int)); -extern int rl_get_next_history PARAMS((int, int)); -extern int rl_get_previous_history PARAMS((int, int)); - -/* Bindable commands for managing the mark and region. */ -extern int rl_set_mark PARAMS((int, int)); -extern int rl_exchange_point_and_mark PARAMS((int, int)); - -/* Bindable commands to set the editing mode (emacs or vi). */ -extern int rl_vi_editing_mode PARAMS((int, int)); -extern int rl_emacs_editing_mode PARAMS((int, int)); - -/* Bindable commands to change the insert mode (insert or overwrite) */ -extern int rl_overwrite_mode PARAMS((int, int)); - -/* Bindable commands for managing key bindings. */ -extern int rl_re_read_init_file PARAMS((int, int)); -extern int rl_dump_functions PARAMS((int, int)); -extern int rl_dump_macros PARAMS((int, int)); -extern int rl_dump_variables PARAMS((int, int)); - -/* Bindable commands for word completion. */ -extern int rl_complete PARAMS((int, int)); -extern int rl_possible_completions PARAMS((int, int)); -extern int rl_insert_completions PARAMS((int, int)); -extern int rl_old_menu_complete PARAMS((int, int)); -extern int rl_menu_complete PARAMS((int, int)); -extern int rl_backward_menu_complete PARAMS((int, int)); - -/* Bindable commands for killing and yanking text, and managing the kill ring. */ -extern int rl_kill_word PARAMS((int, int)); -extern int rl_backward_kill_word PARAMS((int, int)); -extern int rl_kill_line PARAMS((int, int)); -extern int rl_backward_kill_line PARAMS((int, int)); -extern int rl_kill_full_line PARAMS((int, int)); -extern int rl_unix_word_rubout PARAMS((int, int)); -extern int rl_unix_filename_rubout PARAMS((int, int)); -extern int rl_unix_line_discard PARAMS((int, int)); -extern int rl_copy_region_to_kill PARAMS((int, int)); -extern int rl_kill_region PARAMS((int, int)); -extern int rl_copy_forward_word PARAMS((int, int)); -extern int rl_copy_backward_word PARAMS((int, int)); -extern int rl_yank PARAMS((int, int)); -extern int rl_yank_pop PARAMS((int, int)); -extern int rl_yank_nth_arg PARAMS((int, int)); -extern int rl_yank_last_arg PARAMS((int, int)); - -#ifdef Windows -extern int rl_paste_from_clipboard PARAMS((int, int)); -#endif - -/* Bindable commands for incremental searching. */ -extern int rl_reverse_search_history PARAMS((int, int)); -extern int rl_forward_search_history PARAMS((int, int)); - -/* Bindable keyboard macro commands. */ -extern int rl_start_kbd_macro PARAMS((int, int)); -extern int rl_end_kbd_macro PARAMS((int, int)); -extern int rl_call_last_kbd_macro PARAMS((int, int)); - -/* Bindable undo commands. */ -extern int rl_revert_line PARAMS((int, int)); -extern int rl_undo_command PARAMS((int, int)); - -/* Bindable tilde expansion commands. */ -extern int rl_tilde_expand PARAMS((int, int)); - -/* Bindable terminal control commands. */ -extern int rl_restart_output PARAMS((int, int)); -extern int rl_stop_output PARAMS((int, int)); - -/* Miscellaneous bindable commands. */ -extern int rl_abort PARAMS((int, int)); -extern int rl_tty_status PARAMS((int, int)); - -/* Bindable commands for incremental and non-incremental history searching. */ -extern int rl_history_search_forward PARAMS((int, int)); -extern int rl_history_search_backward PARAMS((int, int)); -extern int rl_noninc_forward_search PARAMS((int, int)); -extern int rl_noninc_reverse_search PARAMS((int, int)); -extern int rl_noninc_forward_search_again PARAMS((int, int)); -extern int rl_noninc_reverse_search_again PARAMS((int, int)); - -/* Bindable command used when inserting a matching close character. */ -extern int rl_insert_close PARAMS((int, int)); - -/* Not available unless READLINE_CALLBACKS is defined. */ -extern void rl_callback_handler_install PARAMS((const char *, rl_vcpfunc_t *)); -extern void rl_callback_read_char PARAMS((void)); -extern void rl_callback_handler_remove PARAMS((void)); - -/* Things for vi mode. Not available unless readline is compiled -DVI_MODE. */ -/* VI-mode bindable commands. */ -extern int rl_vi_redo PARAMS((int, int)); -extern int rl_vi_undo PARAMS((int, int)); -extern int rl_vi_yank_arg PARAMS((int, int)); -extern int rl_vi_fetch_history PARAMS((int, int)); -extern int rl_vi_search_again PARAMS((int, int)); -extern int rl_vi_search PARAMS((int, int)); -extern int rl_vi_complete PARAMS((int, int)); -extern int rl_vi_tilde_expand PARAMS((int, int)); -extern int rl_vi_prev_word PARAMS((int, int)); -extern int rl_vi_next_word PARAMS((int, int)); -extern int rl_vi_end_word PARAMS((int, int)); -extern int rl_vi_insert_beg PARAMS((int, int)); -extern int rl_vi_append_mode PARAMS((int, int)); -extern int rl_vi_append_eol PARAMS((int, int)); -extern int rl_vi_eof_maybe PARAMS((int, int)); -extern int rl_vi_insertion_mode PARAMS((int, int)); -extern int rl_vi_insert_mode PARAMS((int, int)); -extern int rl_vi_movement_mode PARAMS((int, int)); -extern int rl_vi_arg_digit PARAMS((int, int)); -extern int rl_vi_change_case PARAMS((int, int)); -extern int rl_vi_put PARAMS((int, int)); -extern int rl_vi_column PARAMS((int, int)); -extern int rl_vi_delete_to PARAMS((int, int)); -extern int rl_vi_change_to PARAMS((int, int)); -extern int rl_vi_yank_to PARAMS((int, int)); -extern int rl_vi_rubout PARAMS((int, int)); -extern int rl_vi_delete PARAMS((int, int)); -extern int rl_vi_back_to_indent PARAMS((int, int)); -extern int rl_vi_first_print PARAMS((int, int)); -extern int rl_vi_char_search PARAMS((int, int)); -extern int rl_vi_match PARAMS((int, int)); -extern int rl_vi_change_char PARAMS((int, int)); -extern int rl_vi_subst PARAMS((int, int)); -extern int rl_vi_overstrike PARAMS((int, int)); -extern int rl_vi_overstrike_delete PARAMS((int, int)); -extern int rl_vi_replace PARAMS((int, int)); -extern int rl_vi_set_mark PARAMS((int, int)); -extern int rl_vi_goto_mark PARAMS((int, int)); - -/* VI-mode utility functions. */ -extern int rl_vi_check PARAMS((void)); -extern int rl_vi_domove PARAMS((int, int *)); -extern int rl_vi_bracktype PARAMS((int)); - -extern void rl_vi_start_inserting PARAMS((int, int, int)); - -/* VI-mode pseudo-bindable commands, used as utility functions. */ -extern int rl_vi_fWord PARAMS((int, int)); -extern int rl_vi_bWord PARAMS((int, int)); -extern int rl_vi_eWord PARAMS((int, int)); -extern int rl_vi_fword PARAMS((int, int)); -extern int rl_vi_bword PARAMS((int, int)); -extern int rl_vi_eword PARAMS((int, int)); - -/* **************************************************************** */ -/* */ -/* Well Published Functions */ -/* */ -/* **************************************************************** */ - -/* Readline functions. */ -/* Read a line of input. Prompt with PROMPT. A NULL PROMPT means none. */ -extern char *readline PARAMS((const char *)); - -extern int rl_set_prompt PARAMS((const char *)); -extern int rl_expand_prompt PARAMS((char *)); - -extern int rl_initialize PARAMS((void)); - -/* Undocumented; unused by readline */ -extern int rl_discard_argument PARAMS((void)); - -/* Utility functions to bind keys to readline commands. */ -extern int rl_add_defun PARAMS((const char *, rl_command_func_t *, int)); -extern int rl_bind_key PARAMS((int, rl_command_func_t *)); -extern int rl_bind_key_in_map PARAMS((int, rl_command_func_t *, Keymap)); -extern int rl_unbind_key PARAMS((int)); -extern int rl_unbind_key_in_map PARAMS((int, Keymap)); -extern int rl_bind_key_if_unbound PARAMS((int, rl_command_func_t *)); -extern int rl_bind_key_if_unbound_in_map PARAMS((int, rl_command_func_t *, Keymap)); -extern int rl_unbind_function_in_map PARAMS((rl_command_func_t *, Keymap)); -extern int rl_unbind_command_in_map PARAMS((const char *, Keymap)); -extern int rl_bind_keyseq PARAMS((const char *, rl_command_func_t *)); -extern int rl_bind_keyseq_in_map PARAMS((const char *, rl_command_func_t *, Keymap)); -extern int rl_bind_keyseq_if_unbound PARAMS((const char *, rl_command_func_t *)); -extern int rl_bind_keyseq_if_unbound_in_map PARAMS((const char *, rl_command_func_t *, Keymap)); -extern int rl_generic_bind PARAMS((int, const char *, char *, Keymap)); - -extern char *rl_variable_value PARAMS((const char *)); -extern int rl_variable_bind PARAMS((const char *, const char *)); - -/* Backwards compatibility, use rl_bind_keyseq_in_map instead. */ -extern int rl_set_key PARAMS((const char *, rl_command_func_t *, Keymap)); - -/* Backwards compatibility, use rl_generic_bind instead. */ -extern int rl_macro_bind PARAMS((const char *, const char *, Keymap)); - -/* Undocumented in the texinfo manual; not really useful to programs. */ -extern int rl_translate_keyseq PARAMS((const char *, char *, int *)); -extern char *rl_untranslate_keyseq PARAMS((int)); - -extern rl_command_func_t *rl_named_function PARAMS((const char *)); -extern rl_command_func_t *rl_function_of_keyseq PARAMS((const char *, Keymap, int *)); - -extern void rl_list_funmap_names PARAMS((void)); -extern char **rl_invoking_keyseqs_in_map PARAMS((rl_command_func_t *, Keymap)); -extern char **rl_invoking_keyseqs PARAMS((rl_command_func_t *)); - -extern void rl_function_dumper PARAMS((int)); -extern void rl_macro_dumper PARAMS((int)); -extern void rl_variable_dumper PARAMS((int)); - -extern int rl_read_init_file PARAMS((const char *)); -extern int rl_parse_and_bind PARAMS((char *)); - -/* Functions for manipulating keymaps. */ -extern Keymap rl_make_bare_keymap PARAMS((void)); -extern Keymap rl_copy_keymap PARAMS((Keymap)); -extern Keymap rl_make_keymap PARAMS((void)); -extern void rl_discard_keymap PARAMS((Keymap)); - -extern Keymap rl_get_keymap_by_name PARAMS((const char *)); -extern char *rl_get_keymap_name PARAMS((Keymap)); -extern void rl_set_keymap PARAMS((Keymap)); -extern Keymap rl_get_keymap PARAMS((void)); -/* Undocumented; used internally only. */ -extern void rl_set_keymap_from_edit_mode PARAMS((void)); -extern char *rl_get_keymap_name_from_edit_mode PARAMS((void)); - -/* Functions for manipulating the funmap, which maps command names to functions. */ -extern int rl_add_funmap_entry PARAMS((const char *, rl_command_func_t *)); -extern const char **rl_funmap_names PARAMS((void)); -/* Undocumented, only used internally -- there is only one funmap, and this - function may be called only once. */ -extern void rl_initialize_funmap PARAMS((void)); - -/* Utility functions for managing keyboard macros. */ -extern void rl_push_macro_input PARAMS((char *)); - -/* Functions for undoing, from undo.c */ -extern void rl_add_undo PARAMS((enum undo_code, int, int, char *)); -extern void rl_free_undo_list PARAMS((void)); -extern int rl_do_undo PARAMS((void)); -extern int rl_begin_undo_group PARAMS((void)); -extern int rl_end_undo_group PARAMS((void)); -extern int rl_modifying PARAMS((int, int)); - -/* Functions for redisplay. */ -extern void rl_redisplay PARAMS((void)); -extern int rl_on_new_line PARAMS((void)); -extern int rl_on_new_line_with_prompt PARAMS((void)); -extern int rl_forced_update_display PARAMS((void)); -extern int rl_clear_message PARAMS((void)); -extern int rl_reset_line_state PARAMS((void)); -extern int rl_crlf PARAMS((void)); - -extern int rl_message (const char *, ...); - -extern int rl_show_char PARAMS((int)); - -/* Undocumented in texinfo manual. */ -extern int rl_character_len PARAMS((int, int)); - -/* Save and restore internal prompt redisplay information. */ -extern void rl_save_prompt PARAMS((void)); -extern void rl_restore_prompt PARAMS((void)); - -/* Modifying text. */ -extern void rl_replace_line PARAMS((const char *, int)); -extern int rl_insert_text PARAMS((const char *)); -extern int rl_delete_text PARAMS((int, int)); -extern int rl_kill_text PARAMS((int, int)); -extern char *rl_copy_text PARAMS((int, int)); - -/* Terminal and tty mode management. */ -extern void rl_prep_terminal PARAMS((int)); -extern void rl_deprep_terminal PARAMS((void)); -extern void rl_tty_set_default_bindings PARAMS((Keymap)); -extern void rl_tty_unset_default_bindings PARAMS((Keymap)); - -extern int rl_reset_terminal PARAMS((const char *)); -extern void rl_resize_terminal PARAMS((void)); -extern void rl_set_screen_size PARAMS((int, int)); -extern void rl_get_screen_size PARAMS((int *, int *)); -extern void rl_reset_screen_size PARAMS((void)); - -extern char *rl_get_termcap PARAMS((const char *)); - -/* Functions for character input. */ -extern int rl_stuff_char PARAMS((int)); -extern int rl_execute_next PARAMS((int)); -extern int rl_clear_pending_input PARAMS((void)); -extern int rl_read_key PARAMS((void)); -extern int rl_getc PARAMS((TFile)); -extern int rl_set_keyboard_input_timeout PARAMS((int)); - -/* `Public' utility functions . */ -extern void rl_extend_line_buffer PARAMS((int)); -extern int rl_ding PARAMS((void)); -extern int rl_alphabetic PARAMS((int)); -extern void rl_free PARAMS((void *)); - -/* Readline signal handling, from signals.c */ -extern int rl_set_signals PARAMS((void)); -extern int rl_clear_signals PARAMS((void)); -extern void rl_cleanup_after_signal PARAMS((void)); -extern void rl_reset_after_signal PARAMS((void)); -extern void rl_free_line_state PARAMS((void)); - -extern void rl_echo_signal_char PARAMS((int)); - -extern int rl_set_paren_blink_timeout PARAMS((int)); - -/* Undocumented. */ -extern int rl_maybe_save_line PARAMS((void)); -extern int rl_maybe_unsave_line PARAMS((void)); -extern int rl_maybe_replace_line PARAMS((void)); - -/* Completion functions. */ -extern int rl_complete_internal PARAMS((int)); -extern void rl_display_match_list PARAMS((char **, int, int)); - -extern char **rl_completion_matches PARAMS((const char *, rl_compentry_func_t *)); -extern char *rl_username_completion_function PARAMS((const char *, int)); -extern char *rl_filename_completion_function PARAMS((const char *, int)); - -extern int rl_completion_mode PARAMS((rl_command_func_t *)); - -/* **************************************************************** */ -/* */ -/* Well Published Variables */ -/* */ -/* **************************************************************** */ - -#if false - -/* The version of this incarnation of the readline library. */ -extern const char *rl_library_version; /* e.g., "4.2" */ -extern int rl_readline_version; /* e.g., 0x0402 */ - -/* True if this is real GNU readline. */ -extern int rl_gnu_readline_p; - -/* Flags word encapsulating the current readline state. */ -extern int rl_readline_state; - -/* Says which editing mode readline is currently using. 1 means emacs mode; - 0 means vi mode. */ -extern int rl_editing_mode; - -/* Insert or overwrite mode for emacs mode. 1 means insert mode; 0 means - overwrite mode. Reset to insert mode on each input line. */ -extern int rl_insert_mode; - -/* The name of the calling program. You should initialize this to - whatever was in argv[0]. It is used when parsing conditionals. */ -extern const char *rl_readline_name; - -/* The prompt readline uses. This is set from the argument to - readline (), and should not be assigned to directly. */ -extern char *rl_prompt; - -/* The prompt string that is actually displayed by rl_redisplay. Public so - applications can more easily supply their own redisplay functions. */ -extern char *rl_display_prompt; - -/* The line buffer that is in use. */ -extern char *rl_line_buffer; - -/* The location of point, and end. */ -extern int rl_point; -extern int rl_end; - -/* The mark, or saved cursor position. */ -extern int rl_mark; - -/* Flag to indicate that readline has finished with the current input - line and should return it. */ -extern int rl_done; - -/* If set to a character value, that will be the next keystroke read. */ -extern int rl_pending_input; - -/* Non-zero if we called this function from _rl_dispatch(). It's present - so functions can find out whether they were called from a key binding - or directly from an application. */ -extern int rl_dispatching; - -/* Non-zero if the user typed a numeric argument before executing the - current function. */ -extern int rl_explicit_arg; - -/* The current value of the numeric argument specified by the user. */ -extern int rl_numeric_arg; - -/* The address of the last command function Readline executed. */ -extern rl_command_func_t *rl_last_func; - -/* The name of the terminal to use. */ -extern const char *rl_terminal_name; - -/* The input and output streams. */ -extern FILE *rl_instream; -extern FILE *rl_outstream; - -/* If non-zero, Readline gives values of LINES and COLUMNS from the environment - greater precedence than values fetched from the kernel when computing the - screen dimensions. */ -extern int rl_prefer_env_winsize; - -/* If non-zero, then this is the address of a function to call just - before readline_internal () prints the first prompt. */ -extern rl_hook_func_t *rl_startup_hook; - -/* If non-zero, this is the address of a function to call just before - readline_internal_setup () returns and readline_internal starts - reading input characters. */ -extern rl_hook_func_t *rl_pre_input_hook; - -/* The address of a function to call periodically while Readline is - awaiting character input, or NULL, for no event handling. */ -extern rl_hook_func_t *rl_event_hook; - -/* The address of the function to call to fetch a character from the current - Readline input stream */ -extern rl_getc_func_t *rl_getc_function; - -extern rl_voidfunc_t *rl_redisplay_function; - -extern rl_vintfunc_t *rl_prep_term_function; -extern rl_voidfunc_t *rl_deprep_term_function; - -/* Dispatch variables. */ -extern Keymap rl_executing_keymap; -extern Keymap rl_binding_keymap; - -/* Display variables. */ -/* If non-zero, readline will erase the entire line, including any prompt, - if the only thing typed on an otherwise-blank line is something bound to - rl_newline. */ -extern int rl_erase_empty_line; - -/* If non-zero, the application has already printed the prompt (rl_prompt) - before calling readline, so readline should not output it the first time - redisplay is done. */ -extern int rl_already_prompted; - -/* A non-zero value means to read only this many characters rather than - up to a character bound to accept-line. */ -extern int rl_num_chars_to_read; - -/* The text of a currently-executing keyboard macro. */ -extern char *rl_executing_macro; - -/* Variables to control readline signal handling. */ -/* If non-zero, readline will install its own signal handlers for - SIGINT, SIGTERM, SIGQUIT, SIGALRM, SIGTSTP, SIGTTIN, and SIGTTOU. */ -extern int rl_catch_signals; - -/* If non-zero, readline will install a signal handler for SIGWINCH - that also attempts to call any calling application's SIGWINCH signal - handler. Note that the terminal is not cleaned up before the - application's signal handler is called; use rl_cleanup_after_signal() - to do that. */ -extern int rl_catch_sigwinch; - -/* Completion variables. */ -/* Pointer to the generator function for completion_matches (). - NULL means to use rl_filename_completion_function (), the default - filename completer. */ -extern rl_compentry_func_t *rl_completion_entry_function; - -/* Optional generator for menu completion. Default is - rl_completion_entry_function (rl_filename_completion_function). */ - extern rl_compentry_func_t *rl_menu_completion_entry_function; - -/* If rl_ignore_some_completions_function is non-NULL it is the address - of a function to call after all of the possible matches have been - generated, but before the actual completion is done to the input line. - The function is called with one argument; a NULL terminated array - of (char *). If your function removes any of the elements, they - must be free()'ed. */ -extern rl_compignore_func_t *rl_ignore_some_completions_function; - -/* Pointer to alternative function to create matches. - Function is called with TEXT, START, and END. - START and END are indices in RL_LINE_BUFFER saying what the boundaries - of TEXT are. - If this function exists and returns NULL then call the value of - rl_completion_entry_function to try to match, otherwise use the - array of strings returned. */ -extern rl_completion_func_t *rl_attempted_completion_function; - -/* The basic list of characters that signal a break between words for the - completer routine. The initial contents of this variable is what - breaks words in the shell, i.e. "n\"\\'`@$>". */ -extern const char *rl_basic_word_break_characters; - -/* The list of characters that signal a break between words for - rl_complete_internal. The default list is the contents of - rl_basic_word_break_characters. */ -extern /*const*/ char *rl_completer_word_break_characters; - -/* Hook function to allow an application to set the completion word - break characters before readline breaks up the line. Allows - position-dependent word break characters. */ -extern rl_cpvfunc_t *rl_completion_word_break_hook; - -/* List of characters which can be used to quote a substring of the line. - Completion occurs on the entire substring, and within the substring - rl_completer_word_break_characters are treated as any other character, - unless they also appear within this list. */ -extern const char *rl_completer_quote_characters; - -/* List of quote characters which cause a word break. */ -extern const char *rl_basic_quote_characters; - -/* List of characters that need to be quoted in filenames by the completer. */ -extern const char *rl_filename_quote_characters; - -/* List of characters that are word break characters, but should be left - in TEXT when it is passed to the completion function. The shell uses - this to help determine what kind of completing to do. */ -extern const char *rl_special_prefixes; - -/* If non-zero, then this is the address of a function to call when - completing on a directory name. The function is called with - the address of a string (the current directory name) as an arg. It - changes what is displayed when the possible completions are printed - or inserted. */ -extern rl_icppfunc_t *rl_directory_completion_hook; - -/* If non-zero, this is the address of a function to call when completing - a directory name. This function takes the address of the directory name - to be modified as an argument. Unlike rl_directory_completion_hook, it - only modifies the directory name used in opendir(2), not what is displayed - when the possible completions are printed or inserted. It is called - before rl_directory_completion_hook. I'm not happy with how this works - yet, so it's undocumented. */ -extern rl_icppfunc_t *rl_directory_rewrite_hook; - -/* If non-zero, this is the address of a function to call when reading - directory entries from the filesystem for completion and comparing - them to the partial word to be completed. The function should - either return its first argument (if no conversion takes place) or - newly-allocated memory. This can, for instance, convert filenames - between character sets for comparison against what's typed at the - keyboard. The returned value is what is added to the list of - matches. The second argument is the length of the filename to be - converted. */ -extern rl_dequote_func_t *rl_filename_rewrite_hook; - -/* If non-zero, then this is the address of a function to call when - completing a word would normally display the list of possible matches. - This function is called instead of actually doing the display. - It takes three arguments: (char **matches, int num_matches, int max_length) - where MATCHES is the array of strings that matched, NUM_MATCHES is the - number of strings in that array, and MAX_LENGTH is the length of the - longest string in that array. */ -extern rl_compdisp_func_t *rl_completion_display_matches_hook; - -/* Non-zero means that the results of the matches are to be treated - as filenames. This is ALWAYS zero on entry, and can only be changed - within a completion entry finder function. */ -extern int rl_filename_completion_desired; - -/* Non-zero means that the results of the matches are to be quoted using - double quotes (or an application-specific quoting mechanism) if the - filename contains any characters in rl_word_break_chars. This is - ALWAYS non-zero on entry, and can only be changed within a completion - entry finder function. */ -extern int rl_filename_quoting_desired; - -/* Set to a function to quote a filename in an application-specific fashion. - Called with the text to quote, the type of match found (single or multiple) - and a pointer to the quoting character to be used, which the function can - reset if desired. */ -extern rl_quote_func_t *rl_filename_quoting_function; - -/* Function to call to remove quoting characters from a filename. Called - before completion is attempted, so the embedded quotes do not interfere - with matching names in the file system. */ -extern rl_dequote_func_t *rl_filename_dequoting_function; - -/* Function to call to decide whether or not a word break character is - quoted. If a character is quoted, it does not break words for the - completer. */ -extern rl_linebuf_func_t *rl_char_is_quoted_p; - -/* Non-zero means to suppress normal filename completion after the - user-specified completion function has been called. */ -extern int rl_attempted_completion_over; - -/* Set to a character describing the type of completion being attempted by - rl_complete_internal; available for use by application completion - functions. */ -extern int rl_completion_type; - -/* Set to the last key used to invoke one of the completion functions */ -extern int rl_completion_invoking_key; - -/* Up to this many items will be displayed in response to a - possible-completions call. After that, we ask the user if she - is sure she wants to see them all. The default value is 100. */ -extern int rl_completion_query_items; - -/* Character appended to completed words when at the end of the line. The - default is a space. Nothing is added if this is '\0'. */ -extern int rl_completion_append_character; - -/* If set to non-zero by an application completion function, - rl_completion_append_character will not be appended. */ -extern int rl_completion_suppress_append; - -/* Set to any quote character readline thinks it finds before any application - completion function is called. */ -extern int rl_completion_quote_character; - -/* Set to a non-zero value if readline found quoting anywhere in the word to - be completed; set before any application completion function is called. */ -extern int rl_completion_found_quote; - -/* If non-zero, the completion functions don't append any closing quote. - This is set to 0 by rl_complete_internal and may be changed by an - application-specific completion function. */ -extern int rl_completion_suppress_quote; - -/* If non-zero, readline will sort the completion matches. On by default. */ -extern int rl_sort_completion_matches; - -/* If non-zero, a slash will be appended to completed filenames that are - symbolic links to directory names, subject to the value of the - mark-directories variable (which is user-settable). This exists so - that application completion functions can override the user's preference - (set via the mark-symlinked-directories variable) if appropriate. - It's set to the value of _rl_complete_mark_symlink_dirs in - rl_complete_internal before any application-specific completion - function is called, so without that function doing anything, the user's - preferences are honored. */ -extern int rl_completion_mark_symlink_dirs; - -/* If non-zero, then disallow duplicates in the matches. */ -extern int rl_ignore_completion_duplicates; - -/* If this is non-zero, completion is (temporarily) inhibited, and the - completion character will be inserted as any other. */ -extern int rl_inhibit_completion; - -#endif - -/* Input error; can be returned by (*rl_getc_function) if readline is reading - a top-level command (RL_ISSTATE (RL_STATE_READCMD)). */ -#define READERR (-2) - -/* Definitions available for use by readline clients. */ -#define RL_PROMPT_START_IGNORE '\001' -#define RL_PROMPT_END_IGNORE '\002' - -/* Possible values for do_replace argument to rl_filename_quoting_function, - called by rl_complete_internal. */ -#define NO_MATCH 0 -#define SINGLE_MATCH 1 -#define MULT_MATCH 2 - -/* Possible state values for rl_readline_state */ -#define RL_STATE_NONE 0x000000 /* no state; before first call */ - -#define RL_STATE_INITIALIZING 0x000001 /* initializing */ -#define RL_STATE_INITIALIZED 0x000002 /* initialization done */ -#define RL_STATE_TERMPREPPED 0x000004 /* terminal is prepped */ -#define RL_STATE_READCMD 0x000008 /* reading a command key */ -#define RL_STATE_METANEXT 0x000010 /* reading input after ESC */ -#define RL_STATE_DISPATCHING 0x000020 /* dispatching to a command */ -#define RL_STATE_MOREINPUT 0x000040 /* reading more input in a command function */ -#define RL_STATE_ISEARCH 0x000080 /* doing incremental search */ -#define RL_STATE_NSEARCH 0x000100 /* doing non-inc search */ -#define RL_STATE_SEARCH 0x000200 /* doing a history search */ -#define RL_STATE_NUMERICARG 0x000400 /* reading numeric argument */ -#define RL_STATE_MACROINPUT 0x000800 /* getting input from a macro */ -#define RL_STATE_MACRODEF 0x001000 /* defining keyboard macro */ -#define RL_STATE_OVERWRITE 0x002000 /* overwrite mode */ -#define RL_STATE_COMPLETING 0x004000 /* doing completion */ -#define RL_STATE_SIGHANDLER 0x008000 /* in readline sighandler */ -#define RL_STATE_UNDOING 0x010000 /* doing an undo */ -#define RL_STATE_INPUTPENDING 0x020000 /* rl_execute_next called */ -#define RL_STATE_TTYCSAVED 0x040000 /* tty special chars saved */ -#define RL_STATE_CALLBACK 0x080000 /* using the callback interface */ -#define RL_STATE_VIMOTION 0x100000 /* reading vi motion arg */ -#define RL_STATE_MULTIKEY 0x200000 /* reading multiple-key command */ -#define RL_STATE_VICMDONCE 0x400000 /* entered vi command mode at least once */ -#define RL_STATE_REDISPLAYING 0x800000 /* updating terminal display */ - -#define RL_STATE_DONE 0x1000000 /* done; accepted line */ - -#define RL_SETSTATE(x) (rl_readline_state |= (x)) -#define RL_UNSETSTATE(x) (rl_readline_state &= ~(x)) -#define RL_ISSTATE(x) (rl_readline_state & (x)) - -struct readline_state { - /* line state */ - int point; - int end; - int mark; - char *buffer; - int buflen; - UNDO_LIST *ul; - char *prompt; - - /* global state */ - int rlstate; - int done; - Keymap kmap; - - /* input state */ - rl_command_func_t *lastfunc; - int insmode; - int edmode; - int kseqlen; - FILE *inf; - FILE *outf; - int pendingin; - char *macro; - - /* signal state */ - int catchsigs; - int catchsigwinch; - - /* search state */ - - /* completion state */ - - /* options state */ - - /* reserved for future expansion, so the struct size doesn't change */ - char reserved[64]; -}; - -extern int rl_save_state PARAMS((struct readline_state *)); -extern int rl_restore_state PARAMS((struct readline_state *)); - diff --git a/lib/wrappers/readline/tweaked/rltypedefs.h b/lib/wrappers/readline/tweaked/rltypedefs.h deleted file mode 100644 index 46bb42567..000000000 --- a/lib/wrappers/readline/tweaked/rltypedefs.h +++ /dev/null @@ -1,78 +0,0 @@ -/* rltypedefs.h -- Type declarations for readline functions. */ - -/* Copyright (C) 2000-2009 Free Software Foundation, Inc. - - This file is part of the GNU Readline Library (Readline), a library - for reading lines of text with interactive input and history editing. - - Readline is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - Readline is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with Readline. If not, see . -*/ - -#ifdef C2NIM -# cdecl -# prefix rl_ -# prefix RL_ -# suffix _t -# typeprefixes -# def PARAMS(x) x -#endif - -typedef int (*Function) (); -typedef void VFunction (); -typedef char *CPFunction (); -typedef char **CPPFunction (); - -/* Bindable functions */ -typedef int rl_command_func_t PARAMS((int, int)); - -/* Typedefs for the completion system */ -typedef char *rl_compentry_func_t PARAMS((const char *, int)); -typedef char **rl_completion_func_t PARAMS((const char *, int, int)); - -typedef char *rl_quote_func_t PARAMS((char *, int, char *)); -typedef char *rl_dequote_func_t PARAMS((char *, int)); - -typedef int rl_compignore_func_t PARAMS((char **)); - -typedef void rl_compdisp_func_t PARAMS((char **, int, int)); - -/* Type for input and pre-read hook functions like rl_event_hook */ -typedef int rl_hook_func_t PARAMS((void)); - -/* Input function type */ -typedef int rl_getc_func_t PARAMS((TFile)); - -/* Generic function that takes a character buffer (which could be the readline - line buffer) and an index into it (which could be rl_point) and returns - an int. */ -typedef int rl_linebuf_func_t PARAMS((char *, int)); - -/* `Generic' function pointer typedefs */ -typedef int rl_intfunc_t PARAMS((int)); -typedef int rl_ivoidfunc_t PARAMS((void)); - -typedef int rl_icpfunc_t PARAMS((char *)); -typedef int rl_icppfunc_t PARAMS((char **)); - -typedef void rl_voidfunc_t PARAMS((void)); -typedef void rl_vintfunc_t PARAMS((int)); -typedef void rl_vcpfunc_t PARAMS((char *)); -typedef void rl_vcppfunc_t PARAMS((char **)); - -typedef char *rl_cpvfunc_t PARAMS((void)); -typedef char *rl_cpifunc_t PARAMS((int)); -typedef char *rl_cpcpfunc_t PARAMS((char *)); -typedef char *rl_cpcppfunc_t PARAMS((char **)); - - diff --git a/lib/wrappers/readline/tweaked/tilde.h b/lib/wrappers/readline/tweaked/tilde.h deleted file mode 100644 index d91d0418d..000000000 --- a/lib/wrappers/readline/tweaked/tilde.h +++ /dev/null @@ -1,77 +0,0 @@ -/* tilde.h: Externally available variables and function in libtilde.a. */ - -/* Copyright (C) 1992-2009 Free Software Foundation, Inc. - - This file contains the Readline Library (Readline), a set of - routines for providing Emacs style line input to programs that ask - for it. - - Readline is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - Readline is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with Readline. If not, see . -*/ - -#ifdef C2NIM -# private tildeDll -# dynlib tildeDll -# cdecl -# if defined(windows) -# define tildeDll "tilde.dll" -# elif defined(macosx) -# define tildeDll "libtilde.dynlib" -# else -# define tildeDll "libtilde.so.6(|.0)" -# endif -# prefix tilde_ -# suffix _t -# typeprefixes -# def PARAMS(x) x -#endif - -typedef char *tilde_hook_func_t PARAMS((char *)); - -#if false - -/* If non-null, this contains the address of a function that the application - wants called before trying the standard tilde expansions. The function - is called with the text sans tilde, and returns a malloc()'ed string - which is the expansion, or a NULL pointer if the expansion fails. */ -extern tilde_hook_func_t *tilde_expansion_preexpansion_hook; - -/* If non-null, this contains the address of a function to call if the - standard meaning for expanding a tilde fails. The function is called - with the text (sans tilde, as in "foo"), and returns a malloc()'ed string - which is the expansion, or a NULL pointer if there is no expansion. */ -extern tilde_hook_func_t *tilde_expansion_failure_hook; - -/* When non-null, this is a NULL terminated array of strings which - are duplicates for a tilde prefix. Bash uses this to expand - `=~' and `:~'. */ -extern char **tilde_additional_prefixes; - -/* When non-null, this is a NULL terminated array of strings which match - the end of a username, instead of just "/". Bash sets this to - `:' and `=~'. */ -extern char **tilde_additional_suffixes; - -/* Return a new string which is the result of tilde expanding STRING. */ -extern char *tilde_expand PARAMS((const char *)); - -/* Do the work of tilde expansion on FILENAME. FILENAME starts with a - tilde. If there is no expansion, call tilde_expansion_failure_hook. */ -extern char *tilde_expand_word PARAMS((const char *)); - -/* Find the portion of the string beginning with ~ that should be expanded. */ -extern char *tilde_find_word PARAMS((const char *, int, int *)); - -#endif - diff --git a/lib/wrappers/sdl/sdl.nim b/lib/wrappers/sdl/sdl.nim deleted file mode 100644 index 376de8e08..000000000 --- a/lib/wrappers/sdl/sdl.nim +++ /dev/null @@ -1,2579 +0,0 @@ -#****************************************************************************** -# -# JEDI-SDL : Pascal units for SDL - Simple DirectMedia Layer -# Conversion of the Simple DirectMedia Layer Headers -# -# Portions created by Sam Lantinga are -# Copyright (C) 1997-2004 Sam Lantinga -# 5635-34 Springhouse Dr. -# Pleasanton, CA 94588 (USA) -# -# All Rights Reserved. -# -# The original files are : SDL.h -# SDL_main.h -# SDL_types.h -# SDL_rwops.h -# SDL_timer.h -# SDL_audio.h -# SDL_cdrom.h -# SDL_joystick.h -# SDL_mouse.h -# SDL_keyboard.h -# SDL_events.h -# SDL_video.h -# SDL_byteorder.h -# SDL_version.h -# SDL_active.h -# SDL_thread.h -# SDL_mutex .h -# SDL_getenv.h -# SDL_loadso.h -# -# The initial developer of this Pascal code was : -# Dominique Louis -# -# Portions created by Dominique Louis are -# Copyright (C) 2000 - 2004 Dominique Louis. -# -# -# Contributor(s) -# -------------- -# Tom Jones His Project inspired this conversion -# Matthias Thoma -# -# Obtained through: -# Joint Endeavour of Delphi Innovators ( Project JEDI ) -# -# You may retrieve the latest version of this file at the Project -# JEDI home page, located at http://delphi-jedi.org -# -# The contents of this file are used with permission, subject to -# the Mozilla Public License Version 1.1 (the "License"); you may -# not use this file except in compliance with the License. You may -# obtain a copy of the License at -# http://www.mozilla.org/MPL/MPL-1.1.html -# -# Software distributed under the License is distributed on an -# "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# Description -# ----------- -# -# -# -# -# -# -# -# Requires -# -------- -# The SDL Runtime libraris on Win32 : SDL.dll on Linux : libSDL.so -# They are available from... -# http://www.libsdl.org . -# -# Programming Notes -# ----------------- -# -# -# -# -# Revision History -# ---------------- -# May 08 2001 - DL : Added Keyboard State Array ( See demos for how to -# use ) -# PKeyStateArr = ^TKeyStateArr; -# TKeyStateArr = array[0..65000] of byte; -# As most games will need it. -# -# April 02 2001 - DL : Added SDL_getenv.h definitions and tested version -# 1.2.0 compatibility. -# -# March 13 2001 - MT : Added Linux compatibility. -# -# March 10 2001 - MT : Added externalsyms for DEFINES -# Changed the license header -# -# March 09 2001 - MT : Added Kylix Ifdefs/Deleted the uses mmsystem -# -# March 01 2001 - DL : Update conversion of version 1.1.8 -# -# July 22 2001 - DL : Added TUInt8Array and PUIntArray after suggestions -# from Matthias Thoma and Eric Grange. -# -# October 12 2001 - DL : Various changes as suggested by Matthias Thoma and -# David Acklam -# -# October 24 2001 - DL : Added FreePascal support as per suggestions from -# Dean Ellis. -# -# October 27 2001 - DL : Added SDL_BUTTON macro -# -# November 08 2001 - DL : Bug fix as pointed out by Puthoon. -# -# November 29 2001 - DL : Bug fix of SDL_SetGammaRamp as pointed out by Simon -# Rushton. -# -# November 30 2001 - DL : SDL_NOFRAME added as pointed out by Simon Rushton. -# -# December 11 2001 - DL : Added $WEAKPACKAGEUNIT ON to facilitate usage in -# Components -# -# January 05 2002 - DL : Added SDL_Swap32 function as suggested by Matthias -# Thoma and also made sure the _getenv from -# MSVCRT.DLL uses the right calling convention -# -# January 25 2002 - DL : Updated conversion of SDL_AddTimer & -# SDL_RemoveTimer as per suggestions from Matthias -# Thoma. -# -# January 27 2002 - DL : Commented out exported function putenv and getenv -# So that developers get used to using SDL_putenv -# SDL_getenv, as they are more portable -# -# March 05 2002 - DL : Added FreeAnNil procedure for Delphi 4 users. -# -# October 23 2002 - DL : Added Delphi 3 Define of Win32. -# If you intend to you Delphi 3... -# ( which is officially unsupported ) make sure you -# remove references to $EXTERNALSYM in this and other -# SDL files. -# -# November 29 2002 - DL : Fixed bug in Declaration of SDL_GetRGBA that was -# pointed out by Todd Lang -# -# April 03 2003 - DL : Added jedi-sdl.inc include file to support more -# Pascal compilers. Initial support is now included -# for GnuPascal, VirtualPascal, TMT and obviously -# continue support for Delphi Kylix and FreePascal. -# -# April 08 2003 - MK : Aka Mr Kroket - Added Better FPC support -# -# April 24 2003 - DL : under instruction from Alexey Barkovoy, I have added -# better TMT Pascal support and under instruction -# from Prof. Abimbola Olowofoyeku (The African Chief), -# I have added better Gnu Pascal support -# -# April 30 2003 - DL : under instruction from David Mears AKA -# Jason Siletto, I have added FPC Linux support. -# This was compiled with fpc 1.1, so remember to set -# include file path. ie. -Fi/usr/share/fpcsrc/rtl/* -# -# -# -# Revision 1.31 2007/05/29 21:30:48 savage -# Changes as suggested by Almindor for 64bit compatibility. -# -# Revision 1.30 2007/05/29 19:31:03 savage -# Fix to TSDL_Overlay structure - thanks David Pethes (aka imcold) -# -# Revision 1.29 2007/05/20 20:29:11 savage -# Initial Changes to Handle 64 Bits -# -# Revision 1.26 2007/02/11 13:38:04 savage -# Added Nintendo DS support - Thanks Dean. -# -# Revision 1.25 2006/12/02 00:12:52 savage -# Updated to latest version -# -# Revision 1.24 2006/05/18 21:10:04 savage -# Added 1.2.10 Changes -# -# Revision 1.23 2005/12/04 23:17:52 drellis -# Added declaration of SInt8 and PSInt8 -# -# Revision 1.22 2005/05/24 21:59:03 savage -# Re-arranged uses clause to work on Win32 and Linux, Thanks again Michalis. -# -# Revision 1.21 2005/05/22 18:42:31 savage -# Changes as suggested by Michalis Kamburelis. Thanks again. -# -# Revision 1.20 2005/04/10 11:48:33 savage -# Changes as suggested by Michalis, thanks. -# -# Revision 1.19 2005/01/05 01:47:06 savage -# Changed LibName to reflect what MacOS X should have. ie libSDL*-1.2.0.dylib respectively. -# -# Revision 1.18 2005/01/04 23:14:41 savage -# Changed LibName to reflect what most Linux distros will have. ie libSDL*-1.2.so.0 respectively. -# -# Revision 1.17 2005/01/03 18:40:59 savage -# Updated Version number to reflect latest one -# -# Revision 1.16 2005/01/01 02:02:06 savage -# Updated to v1.2.8 -# -# Revision 1.15 2004/12/24 18:57:11 savage -# forgot to apply Michalis Kamburelis' patch to the implementation section. now fixed -# -# Revision 1.14 2004/12/23 23:42:18 savage -# Applied Patches supplied by Michalis Kamburelis ( THANKS! ), for greater FreePascal compatibility. -# -# Revision 1.13 2004/09/30 22:31:59 savage -# Updated with slightly different header comments -# -# Revision 1.12 2004/09/12 21:52:58 savage -# Slight changes to fix some issues with the sdl classes. -# -# Revision 1.11 2004/08/14 22:54:30 savage -# Updated so that Library name defines are correctly defined for MacOS X. -# -# Revision 1.10 2004/07/20 23:57:33 savage -# Thanks to Paul Toth for spotting an error in the SDL Audio Conversion structures. -# In TSDL_AudioCVT the filters variable should point to and array of pointers and not what I had there previously. -# -# Revision 1.9 2004/07/03 22:07:22 savage -# Added Bitwise Manipulation Functions for TSDL_VideoInfo struct. -# -# Revision 1.8 2004/05/10 14:10:03 savage -# Initial MacOS X support. Fixed defines for MACOS ( Classic ) and DARWIN ( MacOS X ). -# -# Revision 1.7 2004/04/13 09:32:08 savage -# Changed Shared object names back to just the .so extension to avoid conflicts on various Linux/Unix distros. Therefore developers will need to create Symbolic links to the actual Share Objects if necessary. -# -# Revision 1.6 2004/04/01 20:53:23 savage -# Changed Linux Shared Object names so they reflect the Symbolic Links that are created when installing the RPMs from the SDL site. -# -# Revision 1.5 2004/02/22 15:32:10 savage -# SDL_GetEnv Fix so it also works on FPC/Linux. Thanks to Rodrigo for pointing this out. -# -# Revision 1.4 2004/02/21 23:24:29 savage -# SDL_GetEnv Fix so that it is not define twice for FPC. Thanks to Rene Hugentobler for pointing out this bug, -# -# Revision 1.3 2004/02/18 22:35:51 savage -# Brought sdl.pas up to 1.2.7 compatibility -# Thus... -# Added SDL_GL_STEREO, -# SDL_GL_MULTISAMPLEBUFFERS, -# SDL_GL_MULTISAMPLESAMPLES -# -# Add DLL/Shared object functions -# function SDL_LoadObject( const sofile : PChar ) : pointer; -# -# function SDL_LoadFunction( handle : pointer; const name : PChar ) : pointer; -# -# procedure SDL_UnloadObject( handle : pointer ); -# -# Added function to create RWops from const memory: SDL_RWFromConstMem() -# function SDL_RWFromConstMem(const mem: pointer; size: Integer) : PSDL_RWops; -# -# Ported SDL_cpuinfo.h so Now you can test for Specific CPU types. -# -# Revision 1.2 2004/02/17 21:37:12 savage -# Tidying up of units -# -# Revision 1.1 2004/02/05 00:08:20 savage -# Module 1.0 release -# -# - -{.deadCodeElim: on.} -import unsigned -when defined(windows): - const - LibName = "SDL.dll" -elif defined(macosx): - const - LibName = "libSDL-1.2.0.dylib" -else: - const - LibName = "libSDL.so(|.1|.0)" -const - MAJOR_VERSION* = 1 - MINOR_VERSION* = 2 - PATCHLEVEL* = 11 # SDL.h constants - INIT_TIMER* = 0x00000001 - INIT_AUDIO* = 0x00000010 - INIT_VIDEO* = 0x00000020 - INIT_CDROM* = 0x00000100 - INIT_JOYSTICK* = 0x00000200 - INIT_NOPARACHUTE* = 0x00100000 # Don't catch fatal signals - INIT_EVENTTHREAD* = 0x01000000 # Not supported on all OS's - INIT_EVERYTHING* = 0x0000FFFF # SDL_error.h constants - ERR_MAX_STRLEN* = 128 - ERR_MAX_ARGS* = 5 # SDL_types.h constants - PRESSED* = 0x00000001 - RELEASED* = 0x00000000 # SDL_timer.h constants - # This is the OS scheduler timeslice, in milliseconds - TIMESLICE* = 10 # This is the maximum resolution of the SDL timer on all platforms - TIMER_RESOLUTION* = 10 # Experimentally determined - # SDL_audio.h constants - AUDIO_U8* = 0x00000008 # Unsigned 8-bit samples - AUDIO_S8* = 0x00008008 # Signed 8-bit samples - AUDIO_U16LSB* = 0x00000010 # Unsigned 16-bit samples - AUDIO_S16LSB* = 0x00008010 # Signed 16-bit samples - AUDIO_U16MSB* = 0x00001010 # As above, but big-endian byte order - AUDIO_S16MSB* = 0x00009010 # As above, but big-endian byte order - AUDIO_U16* = AUDIO_U16LSB - AUDIO_S16* = AUDIO_S16LSB # SDL_cdrom.h constants - # The maximum number of CD-ROM tracks on a disk - MAX_TRACKS* = 99 # The types of CD-ROM track possible - AUDIO_TRACK* = 0x00000000 - DATA_TRACK* = 0x00000004 # Conversion functions from frames to Minute/Second/Frames and vice versa - CD_FPS* = 75 # SDL_byteorder.h constants - # The two types of endianness - LIL_ENDIAN* = 1234 - BIG_ENDIAN* = 4321 - -when cpuEndian == littleEndian: - const - BYTEORDER* = LIL_ENDIAN # Native audio byte ordering - AUDIO_U16SYS* = AUDIO_U16LSB - AUDIO_S16SYS* = AUDIO_S16LSB -else: - const - BYTEORDER* = BIG_ENDIAN # Native audio byte ordering - AUDIO_U16SYS* = AUDIO_U16MSB - AUDIO_S16SYS* = AUDIO_S16MSB -const - MIX_MAXVOLUME* = 128 # SDL_joystick.h constants - MAX_JOYSTICKS* = 2 # only 2 are supported in the multimedia API - MAX_AXES* = 6 # each joystick can have up to 6 axes - MAX_BUTTONS* = 32 # and 32 buttons - AXIS_MIN* = - 32768 # minimum value for axis coordinate - AXIS_MAX* = 32767 # maximum value for axis coordinate - JOY_AXIS_THRESHOLD* = (toFloat((AXIS_MAX) - (AXIS_MIN)) / 100.000) # 1% motion - HAT_CENTERED* = 0x00000000 - HAT_UP* = 0x00000001 - HAT_RIGHT* = 0x00000002 - HAT_DOWN* = 0x00000004 - HAT_LEFT* = 0x00000008 - HAT_RIGHTUP* = HAT_RIGHT or HAT_UP - HAT_RIGHTDOWN* = HAT_RIGHT or HAT_DOWN - HAT_LEFTUP* = HAT_LEFT or HAT_UP - HAT_LEFTDOWN* = HAT_LEFT or HAT_DOWN # SDL_events.h constants - -type - EventKind* = enum # kind of an SDL event - NOEVENT = 0, # Unused (do not remove) - ACTIVEEVENT = 1, # Application loses/gains visibility - KEYDOWN = 2, # Keys pressed - KEYUP = 3, # Keys released - MOUSEMOTION = 4, # Mouse moved - MOUSEBUTTONDOWN = 5, # Mouse button pressed - MOUSEBUTTONUP = 6, # Mouse button released - JOYAXISMOTION = 7, # Joystick axis motion - JOYBALLMOTION = 8, # Joystick trackball motion - JOYHATMOTION = 9, # Joystick hat position change - JOYBUTTONDOWN = 10, # Joystick button pressed - JOYBUTTONUP = 11, # Joystick button released - QUITEV = 12, # User-requested quit ( Changed due to procedure conflict ) - SYSWMEVENT = 13, # System specific event - EVENT_RESERVEDA = 14, # Reserved for future use.. - EVENT_RESERVED = 15, # Reserved for future use.. - VIDEORESIZE = 16, # User resized video mode - VIDEOEXPOSE = 17, # Screen needs to be redrawn - EVENT_RESERVED2 = 18, # Reserved for future use.. - EVENT_RESERVED3 = 19, # Reserved for future use.. - EVENT_RESERVED4 = 20, # Reserved for future use.. - EVENT_RESERVED5 = 21, # Reserved for future use.. - EVENT_RESERVED6 = 22, # Reserved for future use.. - EVENT_RESERVED7 = 23, # Reserved for future use.. - # Events SDL_USEREVENT through SDL_MAXEVENTS-1 are for your use - USEREVENT = 24 # This last event is only for bounding internal arrays - # It is the number of bits in the event mask datatype -- int32 -{.deprecated: [TEventKind: EventKind].} - -const - NUMEVENTS* = 32 - ALLEVENTS* = 0xFFFFFFFF - ACTIVEEVENTMASK* = 1 shl ord(ACTIVEEVENT) - KEYDOWNMASK* = 1 shl ord(KEYDOWN) - KEYUPMASK* = 1 shl ord(KEYUP) - MOUSEMOTIONMASK* = 1 shl ord(MOUSEMOTION) - MOUSEBUTTONDOWNMASK* = 1 shl ord(MOUSEBUTTONDOWN) - MOUSEBUTTONUPMASK* = 1 shl ord(MOUSEBUTTONUP) - MOUSEEVENTMASK* = 1 shl ord(MOUSEMOTION) or 1 shl ord(MOUSEBUTTONDOWN) or - 1 shl ord(MOUSEBUTTONUP) - JOYAXISMOTIONMASK* = 1 shl ord(JOYAXISMOTION) - JOYBALLMOTIONMASK* = 1 shl ord(JOYBALLMOTION) - JOYHATMOTIONMASK* = 1 shl ord(JOYHATMOTION) - JOYBUTTONDOWNMASK* = 1 shl ord(JOYBUTTONDOWN) - JOYBUTTONUPMASK* = 1 shl ord(JOYBUTTONUP) - JOYEVENTMASK* = 1 shl ord(JOYAXISMOTION) or 1 shl ord(JOYBALLMOTION) or - 1 shl ord(JOYHATMOTION) or 1 shl ord(JOYBUTTONDOWN) or - 1 shl ord(JOYBUTTONUP) - VIDEORESIZEMASK* = 1 shl ord(VIDEORESIZE) - QUITMASK* = 1 shl ord(QUITEV) - SYSWMEVENTMASK* = 1 shl ord(SYSWMEVENT) - QUERY* = - 1 - IGNORE* = 0 - DISABLE* = 0 - ENABLE* = 1 #SDL_keyboard.h constants - # This is the mask which refers to all hotkey bindings - ALL_HOTKEYS* = 0xFFFFFFFF # Enable/Disable keyboard repeat. Keyboard repeat defaults to off. - # 'delay' is the initial delay in ms between the time when a key is - # pressed, and keyboard repeat begins. - # 'interval' is the time in ms between keyboard repeat events. - DEFAULT_REPEAT_DELAY* = 500 - DEFAULT_REPEAT_INTERVAL* = 30 # The keyboard syms have been cleverly chosen to map to ASCII - K_UNKNOWN* = 0 - K_FIRST* = 0 - K_BACKSPACE* = 8 - K_TAB* = 9 - K_CLEAR* = 12 - K_RETURN* = 13 - K_PAUSE* = 19 - K_ESCAPE* = 27 - K_SPACE* = 32 - K_EXCLAIM* = 33 - K_QUOTEDBL* = 34 - K_HASH* = 35 - K_DOLLAR* = 36 - K_AMPERSAND* = 38 - K_QUOTE* = 39 - K_LEFTPAREN* = 40 - K_RIGHTPAREN* = 41 - K_ASTERISK* = 42 - K_PLUS* = 43 - K_COMMA* = 44 - K_MINUS* = 45 - K_PERIOD* = 46 - K_SLASH* = 47 - K_0* = 48 - K_1* = 49 - K_2* = 50 - K_3* = 51 - K_4* = 52 - K_5* = 53 - K_6* = 54 - K_7* = 55 - K_8* = 56 - K_9* = 57 - K_COLON* = 58 - K_SEMICOLON* = 59 - K_LESS* = 60 - K_EQUALS* = 61 - K_GREATER* = 62 - K_QUESTION* = 63 - K_AT* = 64 # Skip uppercase letters - K_LEFTBRACKET* = 91 - K_BACKSLASH* = 92 - K_RIGHTBRACKET* = 93 - K_CARET* = 94 - K_UNDERSCORE* = 95 - K_BACKQUOTE* = 96 - K_a* = 97 - K_b* = 98 - K_c* = 99 - K_d* = 100 - K_e* = 101 - K_f* = 102 - K_g* = 103 - K_h* = 104 - K_i* = 105 - K_j* = 106 - K_k* = 107 - K_l* = 108 - K_m* = 109 - K_n* = 110 - K_o* = 111 - K_p* = 112 - K_q* = 113 - K_r* = 114 - K_s* = 115 - K_t* = 116 - K_u* = 117 - K_v* = 118 - K_w* = 119 - K_x* = 120 - K_y* = 121 - K_z* = 122 - K_DELETE* = 127 # End of ASCII mapped keysyms - # International keyboard syms - K_WORLD_0* = 160 # 0xA0 - K_WORLD_1* = 161 - K_WORLD_2* = 162 - K_WORLD_3* = 163 - K_WORLD_4* = 164 - K_WORLD_5* = 165 - K_WORLD_6* = 166 - K_WORLD_7* = 167 - K_WORLD_8* = 168 - K_WORLD_9* = 169 - K_WORLD_10* = 170 - K_WORLD_11* = 171 - K_WORLD_12* = 172 - K_WORLD_13* = 173 - K_WORLD_14* = 174 - K_WORLD_15* = 175 - K_WORLD_16* = 176 - K_WORLD_17* = 177 - K_WORLD_18* = 178 - K_WORLD_19* = 179 - K_WORLD_20* = 180 - K_WORLD_21* = 181 - K_WORLD_22* = 182 - K_WORLD_23* = 183 - K_WORLD_24* = 184 - K_WORLD_25* = 185 - K_WORLD_26* = 186 - K_WORLD_27* = 187 - K_WORLD_28* = 188 - K_WORLD_29* = 189 - K_WORLD_30* = 190 - K_WORLD_31* = 191 - K_WORLD_32* = 192 - K_WORLD_33* = 193 - K_WORLD_34* = 194 - K_WORLD_35* = 195 - K_WORLD_36* = 196 - K_WORLD_37* = 197 - K_WORLD_38* = 198 - K_WORLD_39* = 199 - K_WORLD_40* = 200 - K_WORLD_41* = 201 - K_WORLD_42* = 202 - K_WORLD_43* = 203 - K_WORLD_44* = 204 - K_WORLD_45* = 205 - K_WORLD_46* = 206 - K_WORLD_47* = 207 - K_WORLD_48* = 208 - K_WORLD_49* = 209 - K_WORLD_50* = 210 - K_WORLD_51* = 211 - K_WORLD_52* = 212 - K_WORLD_53* = 213 - K_WORLD_54* = 214 - K_WORLD_55* = 215 - K_WORLD_56* = 216 - K_WORLD_57* = 217 - K_WORLD_58* = 218 - K_WORLD_59* = 219 - K_WORLD_60* = 220 - K_WORLD_61* = 221 - K_WORLD_62* = 222 - K_WORLD_63* = 223 - K_WORLD_64* = 224 - K_WORLD_65* = 225 - K_WORLD_66* = 226 - K_WORLD_67* = 227 - K_WORLD_68* = 228 - K_WORLD_69* = 229 - K_WORLD_70* = 230 - K_WORLD_71* = 231 - K_WORLD_72* = 232 - K_WORLD_73* = 233 - K_WORLD_74* = 234 - K_WORLD_75* = 235 - K_WORLD_76* = 236 - K_WORLD_77* = 237 - K_WORLD_78* = 238 - K_WORLD_79* = 239 - K_WORLD_80* = 240 - K_WORLD_81* = 241 - K_WORLD_82* = 242 - K_WORLD_83* = 243 - K_WORLD_84* = 244 - K_WORLD_85* = 245 - K_WORLD_86* = 246 - K_WORLD_87* = 247 - K_WORLD_88* = 248 - K_WORLD_89* = 249 - K_WORLD_90* = 250 - K_WORLD_91* = 251 - K_WORLD_92* = 252 - K_WORLD_93* = 253 - K_WORLD_94* = 254 - K_WORLD_95* = 255 # 0xFF - # Numeric keypad - K_KP0* = 256 - K_KP1* = 257 - K_KP2* = 258 - K_KP3* = 259 - K_KP4* = 260 - K_KP5* = 261 - K_KP6* = 262 - K_KP7* = 263 - K_KP8* = 264 - K_KP9* = 265 - K_KP_PERIOD* = 266 - K_KP_DIVIDE* = 267 - K_KP_MULTIPLY* = 268 - K_KP_MINUS* = 269 - K_KP_PLUS* = 270 - K_KP_ENTER* = 271 - K_KP_EQUALS* = 272 # Arrows + Home/End pad - K_UP* = 273 - K_DOWN* = 274 - K_RIGHT* = 275 - K_LEFT* = 276 - K_INSERT* = 277 - K_HOME* = 278 - K_END* = 279 - K_PAGEUP* = 280 - K_PAGEDOWN* = 281 # Function keys - K_F1* = 282 - K_F2* = 283 - K_F3* = 284 - K_F4* = 285 - K_F5* = 286 - K_F6* = 287 - K_F7* = 288 - K_F8* = 289 - K_F9* = 290 - K_F10* = 291 - K_F11* = 292 - K_F12* = 293 - K_F13* = 294 - K_F14* = 295 - K_F15* = 296 # Key state modifier keys - K_NUMLOCK* = 300 - K_CAPSLOCK* = 301 - K_SCROLLOCK* = 302 - K_RSHIFT* = 303 - K_LSHIFT* = 304 - K_RCTRL* = 305 - K_LCTRL* = 306 - K_RALT* = 307 - K_LALT* = 308 - K_RMETA* = 309 - K_LMETA* = 310 - K_LSUPER* = 311 # Left "Windows" key - K_RSUPER* = 312 # Right "Windows" key - K_MODE* = 313 # "Alt Gr" key - K_COMPOSE* = 314 # Multi-key compose key - # Miscellaneous function keys - K_HELP* = 315 - K_PRINT* = 316 - K_SYSREQ* = 317 - K_BREAK* = 318 - K_MENU* = 319 - K_POWER* = 320 # Power Macintosh power key - K_EURO* = 321 # Some european keyboards - K_GP2X_UP* = 0 - K_GP2X_UPLEFT* = 1 - K_GP2X_LEFT* = 2 - K_GP2X_DOWNLEFT* = 3 - K_GP2X_DOWN* = 4 - K_GP2X_DOWNRIGHT* = 5 - K_GP2X_RIGHT* = 6 - K_GP2X_UPRIGHT* = 7 - K_GP2X_START* = 8 - K_GP2X_SELECT* = 9 - K_GP2X_L* = 10 - K_GP2X_R* = 11 - K_GP2X_A* = 12 - K_GP2X_B* = 13 - K_GP2X_Y* = 14 - K_GP2X_X* = 15 - K_GP2X_VOLUP* = 16 - K_GP2X_VOLDOWN* = 17 - K_GP2X_CLICK* = 18 - -const # Enumeration of valid key mods (possibly OR'd together) - KMOD_NONE* = 0x00000000 - KMOD_LSHIFT* = 0x00000001 - KMOD_RSHIFT* = 0x00000002 - KMOD_LCTRL* = 0x00000040 - KMOD_RCTRL* = 0x00000080 - KMOD_LALT* = 0x00000100 - KMOD_RALT* = 0x00000200 - KMOD_LMETA* = 0x00000400 - KMOD_RMETA* = 0x00000800 - KMOD_NUM* = 0x00001000 - KMOD_CAPS* = 0x00002000 - KMOD_MODE* = 44000 - KMOD_RESERVED* = 0x00008000 - KMOD_CTRL* = (KMOD_LCTRL or KMOD_RCTRL) - KMOD_SHIFT* = (KMOD_LSHIFT or KMOD_RSHIFT) - KMOD_ALT* = (KMOD_LALT or KMOD_RALT) - KMOD_META* = (KMOD_LMETA or KMOD_RMETA) #SDL_video.h constants - # Transparency definitions: These define alpha as the opacity of a surface */ - ALPHA_OPAQUE* = 255 - ALPHA_TRANSPARENT* = 0 # These are the currently supported flags for the SDL_surface - # Available for SDL_CreateRGBSurface() or SDL_SetVideoMode() - SWSURFACE* = 0x00000000 # Surface is in system memory - HWSURFACE* = 0x00000001 # Surface is in video memory - ASYNCBLIT* = 0x00000004 # Use asynchronous blits if possible - # Available for SDL_SetVideoMode() - ANYFORMAT* = 0x10000000 # Allow any video depth/pixel-format - HWPALETTE* = 0x20000000 # Surface has exclusive palette - DOUBLEBUF* = 0x40000000 # Set up double-buffered video mode - FULLSCREEN* = 0x80000000 # Surface is a full screen display - OPENGL* = 0x00000002 # Create an OpenGL rendering context - OPENGLBLIT* = 0x00000002 # Create an OpenGL rendering context - RESIZABLE* = 0x00000010 # This video mode may be resized - NOFRAME* = 0x00000020 # No window caption or edge frame - # Used internally (read-only) - HWACCEL* = 0x00000100 # Blit uses hardware acceleration - SRCCOLORKEY* = 0x00001000 # Blit uses a source color key - RLEACCELOK* = 0x00002000 # Private flag - RLEACCEL* = 0x00004000 # Colorkey blit is RLE accelerated - SRCALPHA* = 0x00010000 # Blit uses source alpha blending - SRCCLIPPING* = 0x00100000 # Blit uses source clipping - PREALLOC* = 0x01000000 # Surface uses preallocated memory - # The most common video overlay formats. - # For an explanation of these pixel formats, see: - # http://www.webartz.com/fourcc/indexyuv.htm - # - # For information on the relationship between color spaces, see: - # - # - # http://www.neuro.sfc.keio.ac.jp/~aly/polygon/info/color-space-faq.html - YV12_OVERLAY* = 0x32315659 # Planar mode: Y + V + U (3 planes) - IYUV_OVERLAY* = 0x56555949 # Planar mode: Y + U + V (3 planes) - YUY2_OVERLAY* = 0x32595559 # Packed mode: Y0+U0+Y1+V0 (1 plane) - UYVY_OVERLAY* = 0x59565955 # Packed mode: U0+Y0+V0+Y1 (1 plane) - YVYU_OVERLAY* = 0x55595659 # Packed mode: Y0+V0+Y1+U0 (1 plane) - # flags for SDL_SetPalette() - LOGPAL* = 0x00000001 - PHYSPAL* = 0x00000002 #SDL_mouse.h constants - # Used as a mask when testing buttons in buttonstate - # Button 1: Left mouse button - # Button 2: Middle mouse button - # Button 3: Right mouse button - # Button 4: Mouse Wheel Up - # Button 5: Mouse Wheel Down - # - BUTTON_LEFT* = 1 - BUTTON_MIDDLE* = 2 - BUTTON_RIGHT* = 3 - BUTTON_WHEELUP* = 4 - BUTTON_WHEELDOWN* = 5 - BUTTON_LMASK* = PRESSED shl (BUTTON_LEFT - 1) - BUTTON_MMASK* = PRESSED shl (BUTTON_MIDDLE - 1) - BUTTON_RMask* = PRESSED shl (BUTTON_RIGHT - 1) # SDL_active.h constants - # The available application states - APPMOUSEFOCUS* = 0x00000001 # The app has mouse coverage - APPINPUTFOCUS* = 0x00000002 # The app has input focus - APPACTIVE* = 0x00000004 # The application is active - # SDL_mutex.h constants - # Synchronization functions which can time out return this value - # they time out. - MUTEX_TIMEDOUT* = 1 # This is the timeout value which corresponds to never time out - MUTEX_MAXWAIT* = not int(0) - GRAB_QUERY* = - 1 - GRAB_OFF* = 0 - GRAB_ON* = 1 #SDL_GRAB_FULLSCREEN // Used internally - -type - Handle* = int #SDL_types.h types - # Basic data types - Bool* = enum - sdlFALSE, sdlTRUE - PUInt8Array* = ptr UInt8Array - UInt8Array* = array[0..high(int) shr 1, byte] - PUInt16* = ptr uint16 - PUInt32* = ptr uint32 - PUInt64* = ptr UInt64 - UInt64*{.final.} = object - hi*: int32 - lo*: int32 - - PSInt64* = ptr SInt64 - SInt64*{.final.} = object - hi*: int32 - lo*: int32 - - GrabMode* = int32 # SDL_error.h types - ErrorCode* = enum - ENOMEM, EFREAD, EFWRITE, EFSEEK, LASTERROR - Arg*{.final.} = object - buf*: array[0..ERR_MAX_STRLEN - 1, int8] - - Perror* = ptr Error - Error*{.final.} = object # This is a numeric value corresponding to the current error - # SDL_rwops.h types - # This is the read/write operation structure -- very basic - # some helper types to handle the unions - # "packed" is only guessed - error*: int # This is a key used to index into a language hashtable containing - # internationalized versions of the SDL error messages. If the key - # is not in the hashtable, or no hashtable is available, the key is - # used directly as an error message format string. - key*: array[0..ERR_MAX_STRLEN - 1, int8] # These are the arguments for the error functions - argc*: int - args*: array[0..ERR_MAX_ARGS - 1, Arg] - - Stdio*{.final.} = object - autoclose*: int # FILE * is only defined in Kylix so we use a simple pointer - fp*: pointer - - Mem*{.final.} = object - base*: ptr byte - here*: ptr byte - stop*: ptr byte - - PRWops* = ptr RWops # now the pointer to function types - Seek* = proc (context: PRWops, offset: int, whence: int): int{.cdecl.} - Read* = proc (context: PRWops, thePtr: pointer, size: int, maxnum: int): int{. - cdecl.} - Write* = proc (context: PRWops, thePtr: pointer, size: int, num: int): int{. - cdecl.} - Close* = proc (context: PRWops): int{.cdecl.} # the variant record itself - RWops*{.final.} = object - seek*: Seek - read*: Read - write*: Write - closeFile*: Close # a keyword as name is not allowed - # be warned! structure alignment may arise at this point - theType*: cint - mem*: Mem - - # SDL_timer.h types - # Function prototype for the timer callback function - TimerCallback* = proc (interval: int32): int32{.cdecl.} - NewTimerCallback* = proc (interval: int32, param: pointer): int32{.cdecl.} - - PTimerID* = ptr TimerID - TimerID*{.final.} = object - interval*: int32 - callback*: NewTimerCallback - param*: pointer - lastAlarm*: int32 - next*: PTimerID - - AudioSpecCallback* = proc (userdata: pointer, stream: ptr byte, length: int){. - cdecl.} # SDL_audio.h types - # The calculated values in this structure are calculated by SDL_OpenAudio() - PAudioSpec* = ptr AudioSpec - AudioSpec*{.final.} = object # A structure to hold a set of audio conversion filters and buffers - freq*: int # DSP frequency -- samples per second - format*: uint16 # Audio data format - channels*: byte # Number of channels: 1 mono, 2 stereo - silence*: byte # Audio buffer silence value (calculated) - samples*: uint16 # Audio buffer size in samples - padding*: uint16 # Necessary for some compile environments - size*: int32 # Audio buffer size in bytes (calculated) - # This function is called when the audio device needs more data. - # 'stream' is a pointer to the audio data buffer - # 'len' is the length of that buffer in bytes. - # Once the callback returns, the buffer will no longer be valid. - # Stereo samples are stored in a LRLRLR ordering. - callback*: AudioSpecCallback - userdata*: pointer - - PAudioCVT* = ptr AudioCVT - PAudioCVTFilter* = ptr AudioCVTFilter - AudioCVTFilter*{.final.} = object - cvt*: PAudioCVT - format*: uint16 - - PAudioCVTFilterArray* = ptr AudioCVTFilterArray - AudioCVTFilterArray* = array[0..9, PAudioCVTFilter] - AudioCVT*{.final.} = object - needed*: int # Set to 1 if conversion possible - srcFormat*: uint16 # Source audio format - dstFormat*: uint16 # Target audio format - rateIncr*: float64 # Rate conversion increment - buf*: ptr byte # Buffer to hold entire audio data - length*: int # Length of original audio buffer - lenCvt*: int # Length of converted audio buffer - lenMult*: int # buffer must be len*len_mult big - lenRatio*: float64 # Given len, final size is len*len_ratio - filters*: AudioCVTFilterArray - filterIndex*: int # Current audio conversion function - - AudioStatus* = enum # SDL_cdrom.h types - AUDIO_STOPPED, AUDIO_PLAYING, AUDIO_PAUSED - CDStatus* = enum - CD_ERROR, CD_TRAYEMPTY, CD_STOPPED, CD_PLAYING, CD_PAUSED - PCDTrack* = ptr CDTrack - CDTrack*{.final.} = object # This structure is only current as of the last call to SDL_CDStatus() - id*: byte # Track number - theType*: byte # Data or audio track - unused*: uint16 - len*: int32 # Length, in frames, of this track - offset*: int32 # Offset, in frames, from start of disk - - PCD* = ptr CD - CD*{.final.} = object #SDL_joystick.h types - id*: int # Private drive identifier - status*: CDStatus # Current drive status - # The rest of this structure is only valid if there's a CD in drive - numtracks*: int # Number of tracks on disk - curTrack*: int # Current track position - curFrame*: int # Current frame offset within current track - track*: array[0..MAX_TRACKS, CDTrack] - - PTransAxis* = ptr TransAxis - TransAxis*{.final.} = object # The private structure used to keep track of a joystick - offset*: int - scale*: float32 - - PJoystickHwdata* = ptr JoystickHwdata - Joystick_hwdata*{.final.} = object # joystick ID - id*: int # values used to translate device-specific coordinates into SDL-standard ranges - transaxis*: array[0..5, TransAxis] - - PBallDelta* = ptr BallDelta - BallDelta*{.final.} = object # Current ball motion deltas - # The SDL joystick structure - dx*: int - dy*: int - - PJoystick* = ptr Joystick - Joystick*{.final.} = object # SDL_verion.h types - index*: byte # Device index - name*: cstring # Joystick name - system dependent - naxes*: int # Number of axis controls on the joystick - axes*: PUInt16 # Current axis states - nhats*: int # Number of hats on the joystick - hats*: ptr byte # Current hat states - nballs*: int # Number of trackballs on the joystick - balls*: PBallDelta # Current ball motion deltas - nbuttons*: int # Number of buttons on the joystick - buttons*: ptr byte # Current button states - hwdata*: PJoystickHwdata # Driver dependent information - refCount*: int # Reference count for multiple opens - - Pversion* = ptr Version - Version*{.final.} = object # SDL_keyboard.h types - major*: byte - minor*: byte - patch*: byte - - Key* = int32 - Mod* = int32 - PKeySym* = ptr KeySym - KeySym*{.final.} = object # SDL_events.h types - #Checks the event queue for messages and optionally returns them. - # If 'action' is SDL_ADDEVENT, up to 'numevents' events will be added to - # the back of the event queue. - # If 'action' is SDL_PEEKEVENT, up to 'numevents' events at the front - # of the event queue, matching 'mask', will be returned and will not - # be removed from the queue. - # If 'action' is SDL_GETEVENT, up to 'numevents' events at the front - # of the event queue, matching 'mask', will be returned and will be - # removed from the queue. - # This function returns the number of events actually stored, or -1 - # if there was an error. This function is thread-safe. - scancode*: byte # hardware specific scancode - sym*: Key # SDL virtual keysym - modifier*: Mod # current key modifiers - unicode*: uint16 # translated character - - EventAction* = enum # Application visibility event structure - ADDEVENT, PEEKEVENT, GETEVENT - - PActiveEvent* = ptr TActiveEvent - TActiveEvent*{.final.} = object # SDL_ACTIVEEVENT - # Keyboard event structure - kind*: EventKind - gain*: byte # Whether given states were gained or lost (1/0) - state*: byte # A mask of the focus states - - PKeyboardEvent* = ptr KeyboardEvent - KeyboardEvent*{.final.} = object # SDL_KEYDOWN or SDL_KEYUP - # Mouse motion event structure - kind*: EventKind - which*: byte # The keyboard device index - state*: byte # SDL_PRESSED or SDL_RELEASED - keysym*: KeySym - - PMouseMotionEvent* = ptr MouseMotionEvent - MouseMotionEvent*{.final.} = object # SDL_MOUSEMOTION - # Mouse button event structure - kind*: EventKind - which*: byte # The mouse device index - state*: byte # The current button state - x*, y*: uint16 # The X/Y coordinates of the mouse - xrel*: int16 # The relative motion in the X direction - yrel*: int16 # The relative motion in the Y direction - - PMouseButtonEvent* = ptr MouseButtonEvent - MouseButtonEvent*{.final.} = object # SDL_MOUSEBUTTONDOWN or SDL_MOUSEBUTTONUP - # Joystick axis motion event structure - kind*: EventKind - which*: byte # The mouse device index - button*: byte # The mouse button index - state*: byte # SDL_PRESSED or SDL_RELEASED - x*: uint16 # The X coordinates of the mouse at press time - y*: uint16 # The Y coordinates of the mouse at press time - - PJoyAxisEvent* = ptr JoyAxisEvent - JoyAxisEvent*{.final.} = object # SDL_JOYAXISMOTION - # Joystick trackball motion event structure - kind*: EventKind - which*: byte # The joystick device index - axis*: byte # The joystick axis index - value*: int16 # The axis value (range: -32768 to 32767) - - PJoyBallEvent* = ptr JoyBallEvent - JoyBallEvent*{.final.} = object # SDL_JOYAVBALLMOTION - # Joystick hat position change event structure - kind*: EventKind - which*: byte # The joystick device index - ball*: byte # The joystick trackball index - xrel*: int16 # The relative motion in the X direction - yrel*: int16 # The relative motion in the Y direction - - PJoyHatEvent* = ptr JoyHatEvent - JoyHatEvent*{.final.} = object # SDL_JOYHATMOTION */ - # Joystick button event structure - kind*: EventKind - which*: byte # The joystick device index */ - hat*: byte # The joystick hat index */ - value*: byte # The hat position value: - # 8 1 2 - # 7 0 3 - # 6 5 4 - # Note that zero means the POV is centered. - - PJoyButtonEvent* = ptr JoyButtonEvent - JoyButtonEvent*{.final.} = object # SDL_JOYBUTTONDOWN or SDL_JOYBUTTONUP - # The "window resized" event - # When you get this event, you are - # responsible for setting a new video - # mode with the new width and height. - kind*: EventKind - which*: byte # The joystick device index - button*: byte # The joystick button index - state*: byte # SDL_PRESSED or SDL_RELEASED - - PResizeEvent* = ptr ResizeEvent - ResizeEvent*{.final.} = object # SDL_VIDEORESIZE - # A user-defined event type - kind*: EventKind - w*: cint # New width - h*: cint # New height - - PUserEvent* = ptr TUserEvent - TUserEvent*{.final.} = object # SDL_USEREVENT through SDL_NUMEVENTS-1 - kind*: EventKind - code*: cint # User defined event code - data1*: pointer # User defined data pointer - data2*: pointer # User defined data pointer - -{.deprecated: [THandle: Handle, TEventAction: EventAction, TKey: Key, TArg: Arg, - TKeySym: KeySym, TKeyboardEvent: KeyboardEvent, TError: Error, - TWrite: Write, TBool: Bool, TUInt8Array: UInt8Array, - TGrabMode: GrabMode, Terrorcode: Errorcode, TStdio: Stdio, - TMem: Mem, TSeek: Seek, TRead: Read, TClose: Close, - TTimerCallback: TimerCallback, TNewTimerCallback: NewTimerCallback, - TTimerID: TimerID, TAudioSpecCallback: AudioSpecCallback, - TAudioSpec: AudioSpec, TAudioCVTFilter: AudioCVTFilter, - TAudioCVTFilterArray: AudioCVTFilterArray, TAudioCVT: AudioCVT, - TAudioStatus: AudioStatus, TCDStatus: CDStatus, TCDTrack: CDTrack, - TCD: CD, TTransAxis: TransAxis, TJoystick_hwdata: Joystick_hwdata, - TJoystick: Joystick, TJoyAxisEvent: JoyAxisEvent, TRWops: RWops, - TJoyBallEvent: JoyBallEvent, TJoyHatEvent: JoyHatEvent, - TJoyButtonEvent: JoyButtonEvent, TBallDelta: BallDelta, - Tversion: Version, TMod: Mod, - # TActiveEvent: ActiveEvent, # Naming conflict when we drop the `T` - TMouseMotionEvent: MouseMotionEvent, TMouseButtonEvent: MouseButtonEvent, - TResizeEvent: ResizeEvent, - # TUserEvent: UserEvent # Naming conflict when we drop the `T` - ].} - -when defined(Unix): - type #These are the various supported subsystems under UNIX - SysWm* = enum - SYSWM_X11 - {.deprecated: [TSysWm: SysWm].} -when defined(WINDOWS): - type - PSysWMmsg* = ptr SysWMmsg - SysWMmsg*{.final.} = object - version*: Version - hwnd*: Handle # The window for the message - msg*: int # The type of message - wParam*: int32 # WORD message parameter - lParam*: int32 # LONG message parameter - {.deprecated: [TSysWMmsg: SysWMmsg].} - -elif defined(Unix): - type # The Linux custom event structure - PSysWMmsg* = ptr SysWMmsg - SysWMmsg*{.final.} = object - version*: Version - subsystem*: SysWm - when false: - event*: TXEvent - {.deprecated: [TSysWMmsg: SysWMmsg].} - - -else: - type # The generic custom event structure - PSysWMmsg* = ptr SysWMmsg - SysWMmsg*{.final.} = object - version*: Version - data*: int - {.deprecated: [TSysWMmsg: SysWMmsg].} - -# The Windows custom window manager information structure - -when defined(WINDOWS): - type - PSysWMinfo* = ptr SysWMinfo - SysWMinfo*{.final.} = object - version*: Version - window*: Handle # The display window - {.deprecated: [TSysWMinfo: SysWMinfo].} - -elif defined(Unix): - type - X11*{.final.} = object - when false: - display*: PDisplay # The X11 display - window*: Window # The X11 display window - # These locking functions should be called around - # any X11 functions using the display variable. - # They lock the event thread, so should not be - # called around event functions or from event filters. - lock_func*: pointer - unlock_func*: pointer # Introduced in SDL 1.0.2 - fswindow*: Window # The X11 fullscreen window - wmwindow*: Window # The X11 managed input window - {.deprecated: [TX11: X11].} - - - type - PSysWMinfo* = ptr SysWMinfo - SysWMinfo*{.final.} = object - version*: Version - subsystem*: SysWm - X11*: X11 - {.deprecated: [TSysWMinfo: SysWMinfo].} - -else: - type # The generic custom window manager information structure - PSysWMinfo* = ptr SysWMinfo - SysWMinfo*{.final.} = object - version*: Version - data*: int - {.deprecated: [TSysWMinfo: SysWMinfo].} - -type - PSysWMEvent* = ptr TSysWMEvent - TSysWMEvent*{.final.} = object - kind*: EventKind - msg*: PSysWMmsg - - PExposeEvent* = ptr ExposeEvent - ExposeEvent*{.final.} = object - kind*: EventKind - - PQuitEvent* = ptr QuitEvent - QuitEvent*{.final.} = object - kind*: EventKind - - PEvent* = ptr Event - Event*{.final.} = object - kind*: EventKind - pad: array[0..19, byte] - - EventFilter* = proc (event: PEvent): int{.cdecl.} # SDL_video.h types - # Useful data types - PPSDL_Rect* = ptr PRect - PRect* = ptr Rect - Rect*{.final.} = object - x*, y*: int16 - w*, h*: uint16 - -# Rect* = TRect - PColor* = ptr Color - Color*{.final.} = object - r*: byte - g*: byte - b*: byte - unused*: byte - - PColorArray* = ptr ColorArray - ColorArray* = array[0..65000, Color] - PPalette* = ptr Palette - Palette*{.final.} = object # Everything in the pixel format structure is read-only - ncolors*: int - colors*: PColorArray - - PPixelFormat* = ptr PixelFormat - PixelFormat*{.final.} = object # The structure passed to the low level blit functions - palette*: PPalette - bitsPerPixel*: byte - bytesPerPixel*: byte - rloss*: byte - gloss*: byte - bloss*: byte - aloss*: byte - rshift*: byte - gshift*: byte - bshift*: byte - ashift*: byte - rMask*: int32 - gMask*: int32 - bMask*: int32 - aMask*: int32 - colorkey*: int32 # RGB color key information - alpha*: byte # Alpha value information (per-surface alpha) - - PBlitInfo* = ptr BlitInfo - BlitInfo*{.final.} = object # typedef for private surface blitting functions - sPixels*: ptr byte - sWidth*: int - sHeight*: int - sSkip*: int - dPixels*: ptr byte - dWidth*: int - dHeight*: int - dSkip*: int - auxData*: pointer - src*: PPixelFormat - table*: ptr byte - dst*: PPixelFormat - - PSurface* = ptr Surface - Blit* = proc (src: PSurface, srcrect: PRect, - dst: PSurface, dstrect: PRect): int{.cdecl.} - Surface*{.final.} = object # Useful for determining the video hardware capabilities - flags*: int32 # Read-only - format*: PPixelFormat # Read-only - w*, h*: cint # Read-only - pitch*: uint16 # Read-only - pixels*: pointer # Read-write - offset*: cint # Private - hwdata*: pointer #TPrivate_hwdata; Hardware-specific surface info - # clipping information: - clipRect*: Rect # Read-only - unused1*: int32 # for binary compatibility - # Allow recursive locks - locked*: int32 # Private - # info for fast blit mapping to other surfaces - blitmap*: pointer # PSDL_BlitMap; // Private - # format version, bumped at every change to invalidate blit maps - formatVersion*: cint # Private - refcount*: cint - - PVideoInfo* = ptr VideoInfo - VideoInfo*{.final.} = object # The YUV hardware video overlay - hwAvailable*: byte - blitHw*: byte - unusedBits3*: byte # Unused at this point - videoMem*: int32 # The total amount of video memory (in K) - vfmt*: PPixelFormat # Value: The format of the video surface - currentW*: int32 # Value: The current video mode width - currentH*: int32 # Value: The current video mode height - - POverlay* = ptr Overlay - Overlay*{.final.} = object # Public enumeration for setting the OpenGL window attributes. - format*: int32 # Overlay format - w*, h*: int # Width and height of overlay - planes*: int # Number of planes in the overlay. Usually either 1 or 3 - pitches*: PUInt16 # An array of pitches, one for each plane. Pitch is the length of a row in bytes. - pixels*: ptr ptr byte # An array of pointers to the data of each plane. The overlay should be locked before these pointers are used. - hwOverlay*: int32 # This will be set to 1 if the overlay is hardware accelerated. - - GLAttr* = enum - GL_RED_SIZE, GL_GREEN_SIZE, GL_BLUE_SIZE, GL_ALPHA_SIZE, GL_BUFFER_SIZE, - GL_DOUBLEBUFFER, GL_DEPTH_SIZE, GL_STENCIL_SIZE, GL_ACCUM_RED_SIZE, - GL_ACCUM_GREEN_SIZE, GL_ACCUM_BLUE_SIZE, GL_ACCUM_ALPHA_SIZE, GL_STEREO, - GL_MULTISAMPLEBUFFERS, GL_MULTISAMPLESAMPLES, GL_ACCELERATED_VISUAL, - GL_SWAP_CONTROL - PCursor* = ptr Cursor - Cursor*{.final.} = object # SDL_mutex.h types - area*: Rect # The area of the mouse cursor - hotX*, hot_y*: int16 # The "tip" of the cursor - data*: ptr byte # B/W cursor data - mask*: ptr byte # B/W cursor mask - save*: array[1..2, ptr byte] # Place to save cursor area - wmCursor*: pointer # Window-manager cursor -{.deprecated: [TRect: Rect, TSurface: Surface, TEvent: Event, TColor: Color, - TEventFilter: EventFilter, TColorArray: ColorArray, - # TSysWMEvent: SysWMEvent, # Naming conflict when we drop the `T` - TExposeEvent: ExposeEvent, - TQuitEvent: QuitEvent, TPalette: Palette, TPixelFormat: PixelFormat, - TBlitInfo: BlitInfo, TBlit: Blit, TVideoInfo: VideoInfo, - TOverlay: Overlay, TGLAttr: GLAttr, TCursor: Cursor].} - -type - PMutex* = ptr Mutex - Mutex*{.final.} = object - Psemaphore* = ptr Semaphore - Semaphore*{.final.} = object - PSem* = ptr Sem - Sem* = Semaphore - PCond* = ptr Cond - Cond*{.final.} = object # SDL_thread.h types -{.deprecated: [TCond: Cond, TSem: Sem, TMutex: Mutex, Tsemaphore: Semaphore].} - -when defined(WINDOWS): - type - SYS_ThreadHandle* = Handle - {.deprecated: [TSYS_ThreadHandle: SYS_ThreadHandle].} -when defined(Unix): - type - SYS_ThreadHandle* = pointer - {.deprecated: [TSYS_ThreadHandle: SYS_ThreadHandle].} -type # This is the system-independent thread info structure - PThread* = ptr Thread - Thread*{.final.} = object # Helper Types - # Keyboard State Array ( See demos for how to use ) - threadid*: int32 - handle*: SYS_ThreadHandle - status*: int - errbuf*: Error - data*: pointer - - PKeyStateArr* = ptr KeyStateArr - KeyStateArr* = array[0..65000, byte] # Types required so we don't need to use Windows.pas - PInteger* = ptr int - PByte* = ptr int8 - PWord* = ptr int16 - PLongWord* = ptr int32 # General arrays - PByteArray* = ptr ByteArray - ByteArray* = array[0..32767, int8] - PWordArray* = ptr WordArray - WordArray* = array[0..16383, int16] # Generic procedure pointer -{.deprecated: [TKeyStateArr: KeyStateArr, TByteArray: ByteArray, TThread: Thread, - TWordArray: WordArray].} - -type EventSeq = set[EventKind] -{.deprecated: [TEventSeq: EventSeq].} - -template evconv(procName: expr, ptrName: typedesc, assertions: EventSeq): stmt {.immediate.} = - proc `procName`*(event: PEvent): ptrName = - assert(contains(assertions, event.kind)) - result = cast[ptrName](event) - -evconv(evActive, PActiveEvent, {ACTIVEEVENT}) -evconv(evKeyboard, PKeyboardEvent, {KEYDOWN, KEYUP}) -evconv(evMouseMotion, PMouseMotionEvent, {MOUSEMOTION}) -evconv(evMouseButton, PMouseButtonEvent, {MOUSEBUTTONDOWN, MOUSEBUTTONUP}) -evconv(evJoyAxis, PJoyAxisEvent,{JOYAXISMOTION}) -evconv(evJoyBall, PJoyBallEvent, {JOYBALLMOTION}) -evconv(evJoyHat, PJoyHatEvent, {JOYHATMOTION}) -evconv(evJoyButton, PJoyButtonEvent, {JOYBUTTONDOWN, JOYBUTTONUP}) -evconv(evResize, PResizeEvent, {VIDEORESIZE}) -evconv(evExpose, PExposeEvent, {VIDEOEXPOSE}) -evconv(evQuit, PQuitEvent, {QUITEV}) -evconv(evUser, PUserEvent, {USEREVENT}) -evconv(evSysWM, PSysWMEvent, {SYSWMEVENT}) - -#------------------------------------------------------------------------------ -# initialization -#------------------------------------------------------------------------------ -# This function loads the SDL dynamically linked library and initializes -# the subsystems specified by 'flags' (and those satisfying dependencies) -# Unless the SDL_INIT_NOPARACHUTE flag is set, it will install cleanup -# signal handlers for some commonly ignored fatal signals (like SIGSEGV) - -proc init*(flags: int32): int{.cdecl, importc: "SDL_Init", dynlib: LibName.} - # This function initializes specific SDL subsystems -proc initSubSystem*(flags: int32): int{.cdecl, importc: "SDL_InitSubSystem", - dynlib: LibName.} - # This function cleans up specific SDL subsystems -proc quitSubSystem*(flags: int32){.cdecl, importc: "SDL_QuitSubSystem", - dynlib: LibName.} - # This function returns mask of the specified subsystems which have - # been initialized. - # If 'flags' is 0, it returns a mask of all initialized subsystems. -proc wasInit*(flags: int32): int32{.cdecl, importc: "SDL_WasInit", - dynlib: LibName.} - # This function cleans up all initialized subsystems and unloads the - # dynamically linked library. You should call it upon all exit conditions. -proc quit*(){.cdecl, importc: "SDL_Quit", dynlib: LibName.} -when defined(WINDOWS): - # This should be called from your WinMain() function, if any - proc registerApp*(name: cstring, style: int32, hInst: pointer): int{.cdecl, - importc: "SDL_RegisterApp", dynlib: LibName.} -proc tableSize*(table: cstring): int - #------------------------------------------------------------------------------ - # error-handling - #------------------------------------------------------------------------------ - # Public functions -proc getError*(): cstring{.cdecl, importc: "SDL_GetError", dynlib: LibName.} -proc setError*(fmt: cstring){.cdecl, importc: "SDL_SetError", dynlib: LibName.} -proc clearError*(){.cdecl, importc: "SDL_ClearError", dynlib: LibName.} -when not (defined(WINDOWS)): - proc error*(Code: ErrorCode){.cdecl, importc: "SDL_Error", dynlib: LibName.} - #------------------------------------------------------------------------------ - # io handling - #------------------------------------------------------------------------------ - # Functions to create SDL_RWops structures from various data sources -proc rwFromFile*(filename, mode: cstring): PRWops{.cdecl, - importc: "SDL_RWFromFile", dynlib: LibName.} -proc freeRW*(area: PRWops){.cdecl, importc: "SDL_FreeRW", dynlib: LibName.} - #fp is FILE *fp ??? -proc rwFromFP*(fp: pointer, autoclose: int): PRWops{.cdecl, - importc: "SDL_RWFromFP", dynlib: LibName.} -proc rwFromMem*(mem: pointer, size: int): PRWops{.cdecl, - importc: "SDL_RWFromMem", dynlib: LibName.} -proc rwFromConstMem*(mem: pointer, size: int): PRWops{.cdecl, - importc: "SDL_RWFromConstMem", dynlib: LibName.} -proc allocRW*(): PRWops{.cdecl, importc: "SDL_AllocRW", dynlib: LibName.} -proc rwSeek*(context: PRWops, offset: int, whence: int): int -proc rwTell*(context: PRWops): int -proc rwRead*(context: PRWops, theptr: pointer, size: int, n: int): int -proc rwWrite*(context: PRWops, theptr: pointer, size: int, n: int): int -proc rwClose*(context: PRWops): int - #------------------------------------------------------------------------------ - # time-handling - #------------------------------------------------------------------------------ - # Get the number of milliseconds since the SDL library initialization. - # Note that this value wraps if the program runs for more than ~49 days. -proc getTicks*(): int32{.cdecl, importc: "SDL_GetTicks", dynlib: LibName.} - # Wait a specified number of milliseconds before returning -proc delay*(msec: int32){.cdecl, importc: "SDL_Delay", dynlib: LibName.} - # Add a new timer to the pool of timers already running. - # Returns a timer ID, or NULL when an error occurs. -proc addTimer*(interval: int32, callback: NewTimerCallback, param: pointer): PTimerID{. - cdecl, importc: "SDL_AddTimer", dynlib: LibName.} - # Remove one of the multiple timers knowing its ID. - # Returns a boolean value indicating success. -proc removeTimer*(t: PTimerID): Bool{.cdecl, importc: "SDL_RemoveTimer", - dynlib: LibName.} -proc setTimer*(interval: int32, callback: TimerCallback): int{.cdecl, - importc: "SDL_SetTimer", dynlib: LibName.} - #------------------------------------------------------------------------------ - # audio-routines - #------------------------------------------------------------------------------ - # These functions are used internally, and should not be used unless you - # have a specific need to specify the audio driver you want to use. - # You should normally use SDL_Init() or SDL_InitSubSystem(). -proc audioInit*(driverName: cstring): int{.cdecl, importc: "SDL_AudioInit", - dynlib: LibName.} -proc audioQuit*(){.cdecl, importc: "SDL_AudioQuit", dynlib: LibName.} - # This function fills the given character buffer with the name of the - # current audio driver, and returns a pointer to it if the audio driver has - # been initialized. It returns NULL if no driver has been initialized. -proc audioDriverName*(namebuf: cstring, maxlen: int): cstring{.cdecl, - importc: "SDL_AudioDriverName", dynlib: LibName.} - # This function opens the audio device with the desired parameters, and - # returns 0 if successful, placing the actual hardware parameters in the - # structure pointed to by 'obtained'. If 'obtained' is NULL, the audio - # data passed to the callback function will be guaranteed to be in the - # requested format, and will be automatically converted to the hardware - # audio format if necessary. This function returns -1 if it failed - # to open the audio device, or couldn't set up the audio thread. - # - # When filling in the desired audio spec structure, - # 'desired->freq' should be the desired audio frequency in samples-per-second. - # 'desired->format' should be the desired audio format. - # 'desired->samples' is the desired size of the audio buffer, in samples. - # This number should be a power of two, and may be adjusted by the audio - # driver to a value more suitable for the hardware. Good values seem to - # range between 512 and 8096 inclusive, depending on the application and - # CPU speed. Smaller values yield faster response time, but can lead - # to underflow if the application is doing heavy processing and cannot - # fill the audio buffer in time. A stereo sample consists of both right - # and left channels in LR ordering. - # Note that the number of samples is directly related to time by the - # following formula: ms = (samples*1000)/freq - # 'desired->size' is the size in bytes of the audio buffer, and is - # calculated by SDL_OpenAudio(). - # 'desired->silence' is the value used to set the buffer to silence, - # and is calculated by SDL_OpenAudio(). - # 'desired->callback' should be set to a function that will be called - # when the audio device is ready for more data. It is passed a pointer - # to the audio buffer, and the length in bytes of the audio buffer. - # This function usually runs in a separate thread, and so you should - # protect data structures that it accesses by calling SDL_LockAudio() - # and SDL_UnlockAudio() in your code. - # 'desired->userdata' is passed as the first parameter to your callback - # function. - # - # The audio device starts out playing silence when it's opened, and should - # be enabled for playing by calling SDL_PauseAudio(0) when you are ready - # for your audio callback function to be called. Since the audio driver - # may modify the requested size of the audio buffer, you should allocate - # any local mixing buffers after you open the audio device. -proc openAudio*(desired, obtained: PAudioSpec): int{.cdecl, - importc: "SDL_OpenAudio", dynlib: LibName.} - # Get the current audio state: -proc getAudioStatus*(): Audiostatus{.cdecl, importc: "SDL_GetAudioStatus", - dynlib: LibName.} - # This function pauses and unpauses the audio callback processing. - # It should be called with a parameter of 0 after opening the audio - # device to start playing sound. This is so you can safely initialize - # data for your callback function after opening the audio device. - # Silence will be written to the audio device during the pause. -proc pauseAudio*(pauseOn: int){.cdecl, importc: "SDL_PauseAudio", - dynlib: LibName.} - # This function loads a WAVE from the data source, automatically freeing - # that source if 'freesrc' is non-zero. For example, to load a WAVE file, - # you could do: - # SDL_LoadWAV_RW(SDL_RWFromFile("sample.wav", "rb"), 1, ...); - # - # If this function succeeds, it returns the given SDL_AudioSpec, - # filled with the audio data format of the wave data, and sets - # 'audio_buf' to a malloc()'d buffer containing the audio data, - # and sets 'audio_len' to the length of that audio buffer, in bytes. - # You need to free the audio buffer with SDL_FreeWAV() when you are - # done with it. - # - # This function returns NULL and sets the SDL error message if the - # wave file cannot be opened, uses an unknown data format, or is - # corrupt. Currently raw and MS-ADPCM WAVE files are supported. -proc loadWAV_RW*(src: PRWops, freesrc: int, spec: PAudioSpec, audioBuf: ptr byte, - audiolen: PUInt32): PAudioSpec{.cdecl, - importc: "SDL_LoadWAV_RW", dynlib: LibName.} - # Compatibility convenience function -- loads a WAV from a file -proc loadWAV*(filename: cstring, spec: PAudioSpec, audioBuf: ptr byte, - audiolen: PUInt32): PAudioSpec - # This function frees data previously allocated with SDL_LoadWAV_RW() -proc freeWAV*(audioBuf: ptr byte){.cdecl, importc: "SDL_FreeWAV", dynlib: LibName.} - # This function takes a source format and rate and a destination format - # and rate, and initializes the 'cvt' structure with information needed - # by SDL_ConvertAudio() to convert a buffer of audio data from one format - # to the other. - # This function returns 0, or -1 if there was an error. -proc buildAudioCVT*(cvt: PAudioCVT, srcFormat: uint16, srcChannels: byte, - srcRate: int, dstFormat: uint16, dstChannels: byte, - dstRate: int): int{.cdecl, importc: "SDL_BuildAudioCVT", - dynlib: LibName.} - # Once you have initialized the 'cvt' structure using SDL_BuildAudioCVT(), - # created an audio buffer cvt->buf, and filled it with cvt->len bytes of - # audio data in the source format, this function will convert it in-place - # to the desired format. - # The data conversion may expand the size of the audio data, so the buffer - # cvt->buf should be allocated after the cvt structure is initialized by - # SDL_BuildAudioCVT(), and should be cvt->len*cvt->len_mult bytes long. -proc convertAudio*(cvt: PAudioCVT): int{.cdecl, importc: "SDL_ConvertAudio", - dynlib: LibName.} - # This takes two audio buffers of the playing audio format and mixes - # them, performing addition, volume adjustment, and overflow clipping. - # The volume ranges from 0 - 128, and should be set to SDL_MIX_MAXVOLUME - # for full audio volume. Note this does not change hardware volume. - # This is provided for convenience -- you can mix your own audio data. -proc mixAudio*(dst, src: ptr byte, length: int32, volume: int){.cdecl, - importc: "SDL_MixAudio", dynlib: LibName.} - # The lock manipulated by these functions protects the callback function. - # During a LockAudio/UnlockAudio pair, you can be guaranteed that the - # callback function is not running. Do not call these from the callback - # function or you will cause deadlock. -proc lockAudio*(){.cdecl, importc: "SDL_LockAudio", dynlib: LibName.} -proc unlockAudio*(){.cdecl, importc: "SDL_UnlockAudio", dynlib: LibName.} - # This function shuts down audio processing and closes the audio device. -proc closeAudio*(){.cdecl, importc: "SDL_CloseAudio", dynlib: LibName.} - #------------------------------------------------------------------------------ - # CD-routines - #------------------------------------------------------------------------------ - # Returns the number of CD-ROM drives on the system, or -1 if - # SDL_Init() has not been called with the SDL_INIT_CDROM flag. -proc cdNumDrives*(): int{.cdecl, importc: "SDL_CDNumDrives", dynlib: LibName.} - # Returns a human-readable, system-dependent identifier for the CD-ROM. - # Example: - # "/dev/cdrom" - # "E:" - # "/dev/disk/ide/1/master" -proc cdName*(drive: int): cstring{.cdecl, importc: "SDL_CDName", dynlib: LibName.} - # Opens a CD-ROM drive for access. It returns a drive handle on success, - # or NULL if the drive was invalid or busy. This newly opened CD-ROM - # becomes the default CD used when other CD functions are passed a NULL - # CD-ROM handle. - # Drives are numbered starting with 0. Drive 0 is the system default CD-ROM. -proc cdOpen*(drive: int): PCD{.cdecl, importc: "SDL_CDOpen", dynlib: LibName.} - # This function returns the current status of the given drive. - # If the drive has a CD in it, the table of contents of the CD and current - # play position of the CD will be stored in the SDL_CD structure. -proc cdStatus*(cdrom: PCD): CDStatus{.cdecl, importc: "SDL_CDStatus", - dynlib: LibName.} - # Play the given CD starting at 'start_track' and 'start_frame' for 'ntracks' - # tracks and 'nframes' frames. If both 'ntrack' and 'nframe' are 0, play - # until the end of the CD. This function will skip data tracks. - # This function should only be called after calling SDL_CDStatus() to - # get track information about the CD. - # - # For example: - # // Play entire CD: - # if ( CD_INDRIVE(SDL_CDStatus(cdrom)) ) then - # SDL_CDPlayTracks(cdrom, 0, 0, 0, 0); - # // Play last track: - # if ( CD_INDRIVE(SDL_CDStatus(cdrom)) ) then - # begin - # SDL_CDPlayTracks(cdrom, cdrom->numtracks-1, 0, 0, 0); - # end; - # - # // Play first and second track and 10 seconds of third track: - # if ( CD_INDRIVE(SDL_CDStatus(cdrom)) ) - # SDL_CDPlayTracks(cdrom, 0, 0, 2, 10); - # - # This function returns 0, or -1 if there was an error. -proc cdPlayTracks*(cdrom: PCD, startTrack: int, startFrame: int, ntracks: int, - nframes: int): int{.cdecl, importc: "SDL_CDPlayTracks", - dynlib: LibName.} - # Play the given CD starting at 'start' frame for 'length' frames. - # It returns 0, or -1 if there was an error. -proc cdPlay*(cdrom: PCD, start: int, len: int): int{.cdecl, - importc: "SDL_CDPlay", dynlib: LibName.} - # Pause play -- returns 0, or -1 on error -proc cdPause*(cdrom: PCD): int{.cdecl, importc: "SDL_CDPause", dynlib: LibName.} - # Resume play -- returns 0, or -1 on error -proc cdResume*(cdrom: PCD): int{.cdecl, importc: "SDL_CDResume", dynlib: LibName.} - # Stop play -- returns 0, or -1 on error -proc cdStop*(cdrom: PCD): int{.cdecl, importc: "SDL_CDStop", dynlib: LibName.} - # Eject CD-ROM -- returns 0, or -1 on error -proc cdEject*(cdrom: PCD): int{.cdecl, importc: "SDL_CDEject", dynlib: LibName.} - # Closes the handle for the CD-ROM drive -proc cdClose*(cdrom: PCD){.cdecl, importc: "SDL_CDClose", dynlib: LibName.} - # Given a status, returns true if there's a disk in the drive -proc cdInDrive*(status: CDStatus): bool - -proc numJoysticks*(): int{.cdecl, importc: "SDL_NumJoysticks", dynlib: LibName.} - # Get the implementation dependent name of a joystick. - # This can be called before any joysticks are opened. - # If no name can be found, this function returns NULL. -proc joystickName*(index: int): cstring{.cdecl, importc: "SDL_JoystickName", - dynlib: LibName.} - # Open a joystick for use - the index passed as an argument refers to - # the N'th joystick on the system. This index is the value which will - # identify this joystick in future joystick events. - # - # This function returns a joystick identifier, or NULL if an error occurred. -proc joystickOpen*(index: int): PJoystick{.cdecl, importc: "SDL_JoystickOpen", - dynlib: LibName.} - # Returns 1 if the joystick has been opened, or 0 if it has not. -proc joystickOpened*(index: int): int{.cdecl, importc: "SDL_JoystickOpened", - dynlib: LibName.} - # Get the device index of an opened joystick. -proc joystickIndex*(joystick: PJoystick): int{.cdecl, - importc: "SDL_JoystickIndex", dynlib: LibName.} - # Get the number of general axis controls on a joystick -proc joystickNumAxes*(joystick: PJoystick): int{.cdecl, - importc: "SDL_JoystickNumAxes", dynlib: LibName.} - # Get the number of trackballs on a joystick - # Joystick trackballs have only relative motion events associated - # with them and their state cannot be polled. -proc joystickNumBalls*(joystick: PJoystick): int{.cdecl, - importc: "SDL_JoystickNumBalls", dynlib: LibName.} - # Get the number of POV hats on a joystick -proc joystickNumHats*(joystick: PJoystick): int{.cdecl, - importc: "SDL_JoystickNumHats", dynlib: LibName.} - # Get the number of buttons on a joystick -proc joystickNumButtons*(joystick: PJoystick): int{.cdecl, - importc: "SDL_JoystickNumButtons", dynlib: LibName.} - # Update the current state of the open joysticks. - # This is called automatically by the event loop if any joystick - # events are enabled. -proc joystickUpdate*(){.cdecl, importc: "SDL_JoystickUpdate", dynlib: LibName.} - # Enable/disable joystick event polling. - # If joystick events are disabled, you must call SDL_JoystickUpdate() - # yourself and check the state of the joystick when you want joystick - # information. - # The state can be one of SDL_QUERY, SDL_ENABLE or SDL_IGNORE. -proc joystickEventState*(state: int): int{.cdecl, - importc: "SDL_JoystickEventState", dynlib: LibName.} - # Get the current state of an axis control on a joystick - # The state is a value ranging from -32768 to 32767. - # The axis indices start at index 0. -proc joystickGetAxis*(joystick: PJoystick, axis: int): int16{.cdecl, - importc: "SDL_JoystickGetAxis", dynlib: LibName.} - # The hat indices start at index 0. -proc joystickGetHat*(joystick: PJoystick, hat: int): byte{.cdecl, - importc: "SDL_JoystickGetHat", dynlib: LibName.} - # Get the ball axis change since the last poll - # This returns 0, or -1 if you passed it invalid parameters. - # The ball indices start at index 0. -proc joystickGetBall*(joystick: PJoystick, ball: int, dx: var int, dy: var int): int{. - cdecl, importc: "SDL_JoystickGetBall", dynlib: LibName.} - # Get the current state of a button on a joystick - # The button indices start at index 0. -proc joystickGetButton*(joystick: PJoystick, button: int): byte{.cdecl, - importc: "SDL_JoystickGetButton", dynlib: LibName.} - # Close a joystick previously opened with SDL_JoystickOpen() -proc joystickClose*(joystick: PJoystick){.cdecl, importc: "SDL_JoystickClose", - dynlib: LibName.} - #------------------------------------------------------------------------------ - # event-handling - #------------------------------------------------------------------------------ - # Pumps the event loop, gathering events from the input devices. - # This function updates the event queue and internal input device state. - # This should only be run in the thread that sets the video mode. -proc pumpEvents*(){.cdecl, importc: "SDL_PumpEvents", dynlib: LibName.} - # Checks the event queue for messages and optionally returns them. - # If 'action' is SDL_ADDEVENT, up to 'numevents' events will be added to - # the back of the event queue. - # If 'action' is SDL_PEEKEVENT, up to 'numevents' events at the front - # of the event queue, matching 'mask', will be returned and will not - # be removed from the queue. - # If 'action' is SDL_GETEVENT, up to 'numevents' events at the front - # of the event queue, matching 'mask', will be returned and will be - # removed from the queue. - # This function returns the number of events actually stored, or -1 - # if there was an error. This function is thread-safe. -proc peepEvents*(events: PEvent, numevents: int, action: EventAction, - mask: int32): int{.cdecl, importc: "SDL_PeepEvents", - dynlib: LibName.} - # Polls for currently pending events, and returns 1 if there are any pending - # events, or 0 if there are none available. If 'event' is not NULL, the next - # event is removed from the queue and stored in that area. -proc pollEvent*(event: PEvent): int{.cdecl, importc: "SDL_PollEvent", - dynlib: LibName.} - # Waits indefinitely for the next available event, returning 1, or 0 if there - # was an error while waiting for events. If 'event' is not NULL, the next - # event is removed from the queue and stored in that area. -proc waitEvent*(event: PEvent): int{.cdecl, importc: "SDL_WaitEvent", - dynlib: LibName.} -proc pushEvent*(event: PEvent): int{.cdecl, importc: "SDL_PushEvent", - dynlib: LibName.} - # If the filter returns 1, then the event will be added to the internal queue. - # If it returns 0, then the event will be dropped from the queue, but the - # internal state will still be updated. This allows selective filtering of - # dynamically arriving events. - # - # WARNING: Be very careful of what you do in the event filter function, as - # it may run in a different thread! - # - # There is one caveat when dealing with the SDL_QUITEVENT event type. The - # event filter is only called when the window manager desires to close the - # application window. If the event filter returns 1, then the window will - # be closed, otherwise the window will remain open if possible. - # If the quit event is generated by an interrupt signal, it will bypass the - # internal queue and be delivered to the application at the next event poll. -proc setEventFilter*(filter: EventFilter){.cdecl, - importc: "SDL_SetEventFilter", dynlib: LibName.} - # Return the current event filter - can be used to "chain" filters. - # If there is no event filter set, this function returns NULL. -proc getEventFilter*(): EventFilter{.cdecl, importc: "SDL_GetEventFilter", - dynlib: LibName.} - # This function allows you to set the state of processing certain events. - # If 'state' is set to SDL_IGNORE, that event will be automatically dropped - # from the event queue and will not event be filtered. - # If 'state' is set to SDL_ENABLE, that event will be processed normally. - # If 'state' is set to SDL_QUERY, SDL_EventState() will return the - # current processing state of the specified event. -proc eventState*(theType: byte, state: int): byte{.cdecl, - importc: "SDL_EventState", dynlib: LibName.} - #------------------------------------------------------------------------------ - # Version Routines - #------------------------------------------------------------------------------ - # This macro can be used to fill a version structure with the compile-time - # version of the SDL library. -proc version*(x: var Version) - # This macro turns the version numbers into a numeric value: - # (1,2,3) -> (1203) - # This assumes that there will never be more than 100 patchlevels -proc versionnum*(x, y, z: int): int - # This is the version number macro for the current SDL version -proc compiledversion*(): int - # This macro will evaluate to true if compiled with SDL at least X.Y.Z -proc versionAtleast*(x, y, z: int): bool - # This function gets the version of the dynamically linked SDL library. - # it should NOT be used to fill a version structure, instead you should - # use the SDL_Version() macro. -proc linkedVersion*(): PVersion{.cdecl, importc: "SDL_Linked_Version", - dynlib: LibName.} - #------------------------------------------------------------------------------ - # video - #------------------------------------------------------------------------------ - # These functions are used internally, and should not be used unless you - # have a specific need to specify the video driver you want to use. - # You should normally use SDL_Init() or SDL_InitSubSystem(). - # - # SDL_VideoInit() initializes the video subsystem -- sets up a connection - # to the window manager, etc, and determines the current video mode and - # pixel format, but does not initialize a window or graphics mode. - # Note that event handling is activated by this routine. - # - # If you use both sound and video in your application, you need to call - # SDL_Init() before opening the sound device, otherwise under Win32 DirectX, - # you won't be able to set full-screen display modes. -proc videoInit*(driverName: cstring, flags: int32): int{.cdecl, - importc: "SDL_VideoInit", dynlib: LibName.} -proc videoQuit*(){.cdecl, importc: "SDL_VideoQuit", dynlib: LibName.} - # This function fills the given character buffer with the name of the - # video driver, and returns a pointer to it if the video driver has - # been initialized. It returns NULL if no driver has been initialized. -proc videoDriverName*(namebuf: cstring, maxlen: int): cstring{.cdecl, - importc: "SDL_VideoDriverName", dynlib: LibName.} - # This function returns a pointer to the current display surface. - # If SDL is doing format conversion on the display surface, this - # function returns the publicly visible surface, not the real video - # surface. -proc getVideoSurface*(): PSurface{.cdecl, importc: "SDL_GetVideoSurface", - dynlib: LibName.} - # This function returns a read-only pointer to information about the - # video hardware. If this is called before SDL_SetVideoMode(), the 'vfmt' - # member of the returned structure will contain the pixel format of the - # "best" video mode. -proc getVideoInfo*(): PVideoInfo{.cdecl, importc: "SDL_GetVideoInfo", - dynlib: LibName.} - # Check to see if a particular video mode is supported. - # It returns 0 if the requested mode is not supported under any bit depth, - # or returns the bits-per-pixel of the closest available mode with the - # given width and height. If this bits-per-pixel is different from the - # one used when setting the video mode, SDL_SetVideoMode() will succeed, - # but will emulate the requested bits-per-pixel with a shadow surface. - # - # The arguments to SDL_VideoModeOK() are the same ones you would pass to - # SDL_SetVideoMode() -proc videoModeOK*(width, height, bpp: int, flags: int32): int{.cdecl, - importc: "SDL_VideoModeOK", importc: "SDL_VideoModeOK", dynlib: LibName.} - # Return a pointer to an array of available screen dimensions for the - # given format and video flags, sorted largest to smallest. Returns - # NULL if there are no dimensions available for a particular format, - # or (SDL_Rect **)-1 if any dimension is okay for the given format. - # - # if 'format' is NULL, the mode list will be for the format given - # by SDL_GetVideoInfo( ) - > vfmt -proc listModes*(format: PPixelFormat, flags: int32): PPSDL_Rect{.cdecl, - importc: "SDL_ListModes", dynlib: LibName.} - # Set up a video mode with the specified width, height and bits-per-pixel. - # - # If 'bpp' is 0, it is treated as the current display bits per pixel. - # - # If SDL_ANYFORMAT is set in 'flags', the SDL library will try to set the - # requested bits-per-pixel, but will return whatever video pixel format is - # available. The default is to emulate the requested pixel format if it - # is not natively available. - # - # If SDL_HWSURFACE is set in 'flags', the video surface will be placed in - # video memory, if possible, and you may have to call SDL_LockSurface() - # in order to access the raw framebuffer. Otherwise, the video surface - # will be created in system memory. - # - # If SDL_ASYNCBLIT is set in 'flags', SDL will try to perform rectangle - # updates asynchronously, but you must always lock before accessing pixels. - # SDL will wait for updates to complete before returning from the lock. - # - # If SDL_HWPALETTE is set in 'flags', the SDL library will guarantee - # that the colors set by SDL_SetColors() will be the colors you get. - # Otherwise, in 8-bit mode, SDL_SetColors() may not be able to set all - # of the colors exactly the way they are requested, and you should look - # at the video surface structure to determine the actual palette. - # If SDL cannot guarantee that the colors you request can be set, - # i.e. if the colormap is shared, then the video surface may be created - # under emulation in system memory, overriding the SDL_HWSURFACE flag. - # - # If SDL_FULLSCREEN is set in 'flags', the SDL library will try to set - # a fullscreen video mode. The default is to create a windowed mode - # if the current graphics system has a window manager. - # If the SDL library is able to set a fullscreen video mode, this flag - # will be set in the surface that is returned. - # - # If SDL_DOUBLEBUF is set in 'flags', the SDL library will try to set up - # two surfaces in video memory and swap between them when you call - # SDL_Flip(). This is usually slower than the normal single-buffering - # scheme, but prevents "tearing" artifacts caused by modifying video - # memory while the monitor is refreshing. It should only be used by - # applications that redraw the entire screen on every update. - # - # This function returns the video framebuffer surface, or NULL if it fails. -proc setVideoMode*(width, height, bpp: int, flags: uint32): PSurface{.cdecl, - importc: "SDL_SetVideoMode", dynlib: LibName.} - # Makes sure the given list of rectangles is updated on the given screen. - # If 'x', 'y', 'w' and 'h' are all 0, SDL_UpdateRect will update the entire - # screen. - # These functions should not be called while 'screen' is locked. -proc updateRects*(screen: PSurface, numrects: int, rects: PRect){.cdecl, - importc: "SDL_UpdateRects", dynlib: LibName.} -proc updateRect*(screen: PSurface, x, y: int32, w, h: int32){.cdecl, - importc: "SDL_UpdateRect", dynlib: LibName.} - # On hardware that supports double-buffering, this function sets up a flip - # and returns. The hardware will wait for vertical retrace, and then swap - # video buffers before the next video surface blit or lock will return. - # On hardware that doesn not support double-buffering, this is equivalent - # to calling SDL_UpdateRect(screen, 0, 0, 0, 0); - # The SDL_DOUBLEBUF flag must have been passed to SDL_SetVideoMode() when - # setting the video mode for this function to perform hardware flipping. - # This function returns 0 if successful, or -1 if there was an error. -proc flip*(screen: PSurface): int{.cdecl, importc: "SDL_Flip", dynlib: LibName.} - # Set the gamma correction for each of the color channels. - # The gamma values range (approximately) between 0.1 and 10.0 - # - # If this function isn't supported directly by the hardware, it will - # be emulated using gamma ramps, if available. If successful, this - # function returns 0, otherwise it returns -1. -proc setGamma*(redgamma: float32, greengamma: float32, bluegamma: float32): int{. - cdecl, importc: "SDL_SetGamma", dynlib: LibName.} - # Set the gamma translation table for the red, green, and blue channels - # of the video hardware. Each table is an array of 256 16-bit quantities, - # representing a mapping between the input and output for that channel. - # The input is the index into the array, and the output is the 16-bit - # gamma value at that index, scaled to the output color precision. - # - # You may pass NULL for any of the channels to leave it unchanged. - # If the call succeeds, it will return 0. If the display driver or - # hardware does not support gamma translation, or otherwise fails, - # this function will return -1. -proc setGammaRamp*(redtable: PUInt16, greentable: PUInt16, bluetable: PUInt16): int{. - cdecl, importc: "SDL_SetGammaRamp", dynlib: LibName.} - # Retrieve the current values of the gamma translation tables. - # - # You must pass in valid pointers to arrays of 256 16-bit quantities. - # Any of the pointers may be NULL to ignore that channel. - # If the call succeeds, it will return 0. If the display driver or - # hardware does not support gamma translation, or otherwise fails, - # this function will return -1. -proc getGammaRamp*(redtable: PUInt16, greentable: PUInt16, bluetable: PUInt16): int{. - cdecl, importc: "SDL_GetGammaRamp", dynlib: LibName.} - # Sets a portion of the colormap for the given 8-bit surface. If 'surface' - # is not a palettized surface, this function does nothing, returning 0. - # If all of the colors were set as passed to SDL_SetColors(), it will - # return 1. If not all the color entries were set exactly as given, - # it will return 0, and you should look at the surface palette to - # determine the actual color palette. - # - # When 'surface' is the surface associated with the current display, the - # display colormap will be updated with the requested colors. If - # SDL_HWPALETTE was set in SDL_SetVideoMode() flags, SDL_SetColors() - # will always return 1, and the palette is guaranteed to be set the way - # you desire, even if the window colormap has to be warped or run under - # emulation. -proc setColors*(surface: PSurface, colors: PColor, firstcolor: int, ncolors: int): int{. - cdecl, importc: "SDL_SetColors", dynlib: LibName.} - # Sets a portion of the colormap for a given 8-bit surface. - # 'flags' is one or both of: - # SDL_LOGPAL -- set logical palette, which controls how blits are mapped - # to/from the surface, - # SDL_PHYSPAL -- set physical palette, which controls how pixels look on - # the screen - # Only screens have physical palettes. Separate change of physical/logical - # palettes is only possible if the screen has SDL_HWPALETTE set. - # - # The return value is 1 if all colours could be set as requested, and 0 - # otherwise. - # - # SDL_SetColors() is equivalent to calling this function with - # flags = (SDL_LOGPAL or SDL_PHYSPAL). -proc setPalette*(surface: PSurface, flags: int, colors: PColor, firstcolor: int, - ncolors: int): int{.cdecl, importc: "SDL_SetPalette", - dynlib: LibName.} - # Maps an RGB triple to an opaque pixel value for a given pixel format -proc mapRGB*(format: PPixelFormat, r: byte, g: byte, b: byte): int32{.cdecl, - importc: "SDL_MapRGB", dynlib: LibName.} - # Maps an RGBA quadruple to a pixel value for a given pixel format -proc mapRGBA*(format: PPixelFormat, r: byte, g: byte, b: byte, a: byte): int32{. - cdecl, importc: "SDL_MapRGBA", dynlib: LibName.} - # Maps a pixel value into the RGB components for a given pixel format -proc getRGB*(pixel: int32, fmt: PPixelFormat, r: ptr byte, g: ptr byte, b: ptr byte){. - cdecl, importc: "SDL_GetRGB", dynlib: LibName.} - # Maps a pixel value into the RGBA components for a given pixel format -proc getRGBA*(pixel: int32, fmt: PPixelFormat, r: ptr byte, g: ptr byte, b: ptr byte, - a: ptr byte){.cdecl, importc: "SDL_GetRGBA", dynlib: LibName.} - # Allocate and free an RGB surface (must be called after SDL_SetVideoMode) - # If the depth is 4 or 8 bits, an empty palette is allocated for the surface. - # If the depth is greater than 8 bits, the pixel format is set using the - # flags '[RGB]mask'. - # If the function runs out of memory, it will return NULL. - # - # The 'flags' tell what kind of surface to create. - # SDL_SWSURFACE means that the surface should be created in system memory. - # SDL_HWSURFACE means that the surface should be created in video memory, - # with the same format as the display surface. This is useful for surfaces - # that will not change much, to take advantage of hardware acceleration - # when being blitted to the display surface. - # SDL_ASYNCBLIT means that SDL will try to perform asynchronous blits with - # this surface, but you must always lock it before accessing the pixels. - # SDL will wait for current blits to finish before returning from the lock. - # SDL_SRCCOLORKEY indicates that the surface will be used for colorkey blits. - # If the hardware supports acceleration of colorkey blits between - # two surfaces in video memory, SDL will try to place the surface in - # video memory. If this isn't possible or if there is no hardware - # acceleration available, the surface will be placed in system memory. - # SDL_SRCALPHA means that the surface will be used for alpha blits and - # if the hardware supports hardware acceleration of alpha blits between - # two surfaces in video memory, to place the surface in video memory - # if possible, otherwise it will be placed in system memory. - # If the surface is created in video memory, blits will be _much_ faster, - # but the surface format must be identical to the video surface format, - # and the only way to access the pixels member of the surface is to use - # the SDL_LockSurface() and SDL_UnlockSurface() calls. - # If the requested surface actually resides in video memory, SDL_HWSURFACE - # will be set in the flags member of the returned surface. If for some - # reason the surface could not be placed in video memory, it will not have - # the SDL_HWSURFACE flag set, and will be created in system memory instead. -proc allocSurface*(flags: int32, width, height, depth: int, - rMask, gMask, bMask, aMask: int32): PSurface -proc createRGBSurface*(flags: int32, width, height, depth: int, - rMask, gMask, bMask, aMask: int32): PSurface{.cdecl, - importc: "SDL_CreateRGBSurface", dynlib: LibName.} -proc createRGBSurfaceFrom*(pixels: pointer, width, height, depth, pitch: int, - rMask, gMask, bMask, aMask: int32): PSurface{.cdecl, - importc: "SDL_CreateRGBSurfaceFrom", dynlib: LibName.} -proc freeSurface*(surface: PSurface){.cdecl, importc: "SDL_FreeSurface", - dynlib: LibName.} -proc mustLock*(surface: PSurface): bool - # SDL_LockSurface() sets up a surface for directly accessing the pixels. - # Between calls to SDL_LockSurface()/SDL_UnlockSurface(), you can write - # to and read from 'surface->pixels', using the pixel format stored in - # 'surface->format'. Once you are done accessing the surface, you should - # use SDL_UnlockSurface() to release it. - # - # Not all surfaces require locking. If SDL_MUSTLOCK(surface) evaluates - # to 0, then you can read and write to the surface at any time, and the - # pixel format of the surface will not change. In particular, if the - # SDL_HWSURFACE flag is not given when calling SDL_SetVideoMode(), you - # will not need to lock the display surface before accessing it. - # - # No operating system or library calls should be made between lock/unlock - # pairs, as critical system locks may be held during this time. - # - # SDL_LockSurface() returns 0, or -1 if the surface couldn't be locked. -proc lockSurface*(surface: PSurface): int{.cdecl, importc: "SDL_LockSurface", - dynlib: LibName.} -proc unlockSurface*(surface: PSurface){.cdecl, importc: "SDL_UnlockSurface", - dynlib: LibName.} - # Load a surface from a seekable SDL data source (memory or file.) - # If 'freesrc' is non-zero, the source will be closed after being read. - # Returns the new surface, or NULL if there was an error. - # The new surface should be freed with SDL_FreeSurface(). -proc loadBMP_RW*(src: PRWops, freesrc: int): PSurface{.cdecl, - importc: "SDL_LoadBMP_RW", dynlib: LibName.} - # Convenience macro -- load a surface from a file -proc loadBMP*(filename: cstring): PSurface - # Save a surface to a seekable SDL data source (memory or file.) - # If 'freedst' is non-zero, the source will be closed after being written. - # Returns 0 if successful or -1 if there was an error. -proc saveBMP_RW*(surface: PSurface, dst: PRWops, freedst: int): int{.cdecl, - importc: "SDL_SaveBMP_RW", dynlib: LibName.} - # Convenience macro -- save a surface to a file -proc saveBMP*(surface: PSurface, filename: cstring): int - # Sets the color key (transparent pixel) in a blittable surface. - # If 'flag' is SDL_SRCCOLORKEY (optionally OR'd with SDL_RLEACCEL), - # 'key' will be the transparent pixel in the source image of a blit. - # SDL_RLEACCEL requests RLE acceleration for the surface if present, - # and removes RLE acceleration if absent. - # If 'flag' is 0, this function clears any current color key. - # This function returns 0, or -1 if there was an error. -proc setColorKey*(surface: PSurface, flag, key: int32): int{.cdecl, - importc: "SDL_SetColorKey", dynlib: LibName.} - # This function sets the alpha value for the entire surface, as opposed to - # using the alpha component of each pixel. This value measures the range - # of transparency of the surface, 0 being completely transparent to 255 - # being completely opaque. An 'alpha' value of 255 causes blits to be - # opaque, the source pixels copied to the destination (the default). Note - # that per-surface alpha can be combined with colorkey transparency. - # - # If 'flag' is 0, alpha blending is disabled for the surface. - # If 'flag' is SDL_SRCALPHA, alpha blending is enabled for the surface. - # OR:ing the flag with SDL_RLEACCEL requests RLE acceleration for the - # surface; if SDL_RLEACCEL is not specified, the RLE accel will be removed. -proc setAlpha*(surface: PSurface, flag: int32, alpha: byte): int{.cdecl, - importc: "SDL_SetAlpha", dynlib: LibName.} - # Sets the clipping rectangle for the destination surface in a blit. - # - # If the clip rectangle is NULL, clipping will be disabled. - # If the clip rectangle doesn't intersect the surface, the function will - # return SDL_FALSE and blits will be completely clipped. Otherwise the - # function returns SDL_TRUE and blits to the surface will be clipped to - # the intersection of the surface area and the clipping rectangle. - # - # Note that blits are automatically clipped to the edges of the source - # and destination surfaces. -proc setClipRect*(surface: PSurface, rect: PRect){.cdecl, - importc: "SDL_SetClipRect", dynlib: LibName.} - # Gets the clipping rectangle for the destination surface in a blit. - # 'rect' must be a pointer to a valid rectangle which will be filled - # with the correct values. -proc getClipRect*(surface: PSurface, rect: PRect){.cdecl, - importc: "SDL_GetClipRect", dynlib: LibName.} - # Creates a new surface of the specified format, and then copies and maps - # the given surface to it so the blit of the converted surface will be as - # fast as possible. If this function fails, it returns NULL. - # - # The 'flags' parameter is passed to SDL_CreateRGBSurface() and has those - # semantics. You can also pass SDL_RLEACCEL in the flags parameter and - # SDL will try to RLE accelerate colorkey and alpha blits in the resulting - # surface. - # - # This function is used internally by SDL_DisplayFormat(). -proc convertSurface*(src: PSurface, fmt: PPixelFormat, flags: int32): PSurface{. - cdecl, importc: "SDL_ConvertSurface", dynlib: LibName.} - # - # This performs a fast blit from the source surface to the destination - # surface. It assumes that the source and destination rectangles are - # the same size. If either 'srcrect' or 'dstrect' are NULL, the entire - # surface (src or dst) is copied. The final blit rectangles are saved - # in 'srcrect' and 'dstrect' after all clipping is performed. - # If the blit is successful, it returns 0, otherwise it returns -1. - # - # The blit function should not be called on a locked surface. - # - # The blit semantics for surfaces with and without alpha and colorkey - # are defined as follows: - # - # RGBA->RGB: - # SDL_SRCALPHA set: - # alpha-blend (using alpha-channel). - # SDL_SRCCOLORKEY ignored. - # SDL_SRCALPHA not set: - # copy RGB. - # if SDL_SRCCOLORKEY set, only copy the pixels matching the - # RGB values of the source colour key, ignoring alpha in the - # comparison. - # - # RGB->RGBA: - # SDL_SRCALPHA set: - # alpha-blend (using the source per-surface alpha value); - # set destination alpha to opaque. - # SDL_SRCALPHA not set: - # copy RGB, set destination alpha to opaque. - # both: - # if SDL_SRCCOLORKEY set, only copy the pixels matching the - # source colour key. - # - # RGBA->RGBA: - # SDL_SRCALPHA set: - # alpha-blend (using the source alpha channel) the RGB values; - # leave destination alpha untouched. [Note: is this correct?] - # SDL_SRCCOLORKEY ignored. - # SDL_SRCALPHA not set: - # copy all of RGBA to the destination. - # if SDL_SRCCOLORKEY set, only copy the pixels matching the - # RGB values of the source colour key, ignoring alpha in the - # comparison. - # - # RGB->RGB: - # SDL_SRCALPHA set: - # alpha-blend (using the source per-surface alpha value). - # SDL_SRCALPHA not set: - # copy RGB. - # both: - # if SDL_SRCCOLORKEY set, only copy the pixels matching the - # source colour key. - # - # If either of the surfaces were in video memory, and the blit returns -2, - # the video memory was lost, so it should be reloaded with artwork and - # re-blitted: - # while ( SDL_BlitSurface(image, imgrect, screen, dstrect) = -2 ) do - # begin - # while ( SDL_LockSurface(image) < 0 ) do - # Sleep(10); - # -- Write image pixels to image->pixels -- - # SDL_UnlockSurface(image); - # end; - # - # This happens under DirectX 5.0 when the system switches away from your - # fullscreen application. The lock will also fail until you have access - # to the video memory again. - # You should call SDL_BlitSurface() unless you know exactly how SDL - # blitting works internally and how to use the other blit functions. -proc blitSurface*(src: PSurface, srcrect: PRect, dst: PSurface, dstrect: PRect): int - # This is the public blit function, SDL_BlitSurface(), and it performs - # rectangle validation and clipping before passing it to SDL_LowerBlit() -proc upperBlit*(src: PSurface, srcrect: PRect, dst: PSurface, dstrect: PRect): int{. - cdecl, importc: "SDL_UpperBlit", dynlib: LibName.} - # This is a semi-private blit function and it performs low-level surface - # blitting only. -proc lowerBlit*(src: PSurface, srcrect: PRect, dst: PSurface, dstrect: PRect): int{. - cdecl, importc: "SDL_LowerBlit", dynlib: LibName.} - # This function performs a fast fill of the given rectangle with 'color' - # The given rectangle is clipped to the destination surface clip area - # and the final fill rectangle is saved in the passed in pointer. - # If 'dstrect' is NULL, the whole surface will be filled with 'color' - # The color should be a pixel of the format used by the surface, and - # can be generated by the SDL_MapRGB() function. - # This function returns 0 on success, or -1 on error. -proc fillRect*(dst: PSurface, dstrect: PRect, color: int32): int{.cdecl, - importc: "SDL_FillRect", dynlib: LibName.} - # This function takes a surface and copies it to a new surface of the - # pixel format and colors of the video framebuffer, suitable for fast - # blitting onto the display surface. It calls SDL_ConvertSurface() - # - # If you want to take advantage of hardware colorkey or alpha blit - # acceleration, you should set the colorkey and alpha value before - # calling this function. - # - # If the conversion fails or runs out of memory, it returns NULL -proc displayFormat*(surface: PSurface): PSurface{.cdecl, - importc: "SDL_DisplayFormat", dynlib: LibName.} - # This function takes a surface and copies it to a new surface of the - # pixel format and colors of the video framebuffer (if possible), - # suitable for fast alpha blitting onto the display surface. - # The new surface will always have an alpha channel. - # - # If you want to take advantage of hardware colorkey or alpha blit - # acceleration, you should set the colorkey and alpha value before - # calling this function. - # - # If the conversion fails or runs out of memory, it returns NULL -proc displayFormatAlpha*(surface: PSurface): PSurface{.cdecl, - importc: "SDL_DisplayFormatAlpha", dynlib: LibName.} - #* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ - #* YUV video surface overlay functions */ - #* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ - # This function creates a video output overlay - # Calling the returned surface an overlay is something of a misnomer because - # the contents of the display surface underneath the area where the overlay - # is shown is undefined - it may be overwritten with the converted YUV data. -proc createYUVOverlay*(width: int, height: int, format: int32, - display: PSurface): POverlay{.cdecl, - importc: "SDL_CreateYUVOverlay", dynlib: LibName.} - # Lock an overlay for direct access, and unlock it when you are done -proc lockYUVOverlay*(overlay: POverlay): int{.cdecl, - importc: "SDL_LockYUVOverlay", dynlib: LibName.} -proc unlockYUVOverlay*(overlay: POverlay){.cdecl, - importc: "SDL_UnlockYUVOverlay", dynlib: LibName.} - # Blit a video overlay to the display surface. - # The contents of the video surface underneath the blit destination are - # not defined. - # The width and height of the destination rectangle may be different from - # that of the overlay, but currently only 2x scaling is supported. -proc displayYUVOverlay*(overlay: POverlay, dstrect: PRect): int{.cdecl, - importc: "SDL_DisplayYUVOverlay", dynlib: LibName.} - # Free a video overlay -proc freeYUVOverlay*(overlay: POverlay){.cdecl, importc: "SDL_FreeYUVOverlay", - dynlib: LibName.} - #------------------------------------------------------------------------------ - # OpenGL Routines - #------------------------------------------------------------------------------ - # Dynamically load a GL driver, if SDL is built with dynamic GL. - # - # SDL links normally with the OpenGL library on your system by default, - # but you can compile it to dynamically load the GL driver at runtime. - # If you do this, you need to retrieve all of the GL functions used in - # your program from the dynamic library using SDL_GL_GetProcAddress(). - # - # This is disabled in default builds of SDL. -proc glLoadLibrary*(filename: cstring): int{.cdecl, - importc: "SDL_GL_LoadLibrary", dynlib: LibName.} - # Get the address of a GL function (for extension functions) -proc glGetProcAddress*(procname: cstring): pointer{.cdecl, - importc: "SDL_GL_GetProcAddress", dynlib: LibName.} - # Set an attribute of the OpenGL subsystem before intialization. -proc glSetAttribute*(attr: GLAttr, value: int): int{.cdecl, - importc: "SDL_GL_SetAttribute", dynlib: LibName.} - # Get an attribute of the OpenGL subsystem from the windowing - # interface, such as glX. This is of course different from getting - # the values from SDL's internal OpenGL subsystem, which only - # stores the values you request before initialization. - # - # Developers should track the values they pass into SDL_GL_SetAttribute - # themselves if they want to retrieve these values. -proc glGetAttribute*(attr: GLAttr, value: var int): int{.cdecl, - importc: "SDL_GL_GetAttribute", dynlib: LibName.} - # Swap the OpenGL buffers, if double-buffering is supported. -proc glSwapBuffers*(){.cdecl, importc: "SDL_GL_SwapBuffers", dynlib: LibName.} - # Internal functions that should not be called unless you have read - # and understood the source code for these functions. -proc glUpdateRects*(numrects: int, rects: PRect){.cdecl, - importc: "SDL_GL_UpdateRects", dynlib: LibName.} -proc glLock*(){.cdecl, importc: "SDL_GL_Lock", dynlib: LibName.} -proc glUnlock*(){.cdecl, importc: "SDL_GL_Unlock", dynlib: LibName.} - #* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * - #* These functions allow interaction with the window manager, if any. * - #* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * - # Sets/Gets the title and icon text of the display window -proc wmGetCaption*(title: var cstring, icon: var cstring){.cdecl, - importc: "SDL_WM_GetCaption", dynlib: LibName.} -proc wmSetCaption*(title: cstring, icon: cstring){.cdecl, - importc: "SDL_WM_SetCaption", dynlib: LibName.} - # Sets the icon for the display window. - # This function must be called before the first call to SDL_SetVideoMode(). - # It takes an icon surface, and a mask in MSB format. - # If 'mask' is NULL, the entire icon surface will be used as the icon. -proc wmSetIcon*(icon: PSurface, mask: byte){.cdecl, importc: "SDL_WM_SetIcon", - dynlib: LibName.} - # This function iconifies the window, and returns 1 if it succeeded. - # If the function succeeds, it generates an SDL_APPACTIVE loss event. - # This function is a noop and returns 0 in non-windowed environments. -proc wmIconifyWindow*(): int{.cdecl, importc: "SDL_WM_IconifyWindow", - dynlib: LibName.} - # Toggle fullscreen mode without changing the contents of the screen. - # If the display surface does not require locking before accessing - # the pixel information, then the memory pointers will not change. - # - # If this function was able to toggle fullscreen mode (change from - # running in a window to fullscreen, or vice-versa), it will return 1. - # If it is not implemented, or fails, it returns 0. - # - # The next call to SDL_SetVideoMode() will set the mode fullscreen - # attribute based on the flags parameter - if SDL_FULLSCREEN is not - # set, then the display will be windowed by default where supported. - # - # This is currently only implemented in the X11 video driver. -proc wmToggleFullScreen*(surface: PSurface): int{.cdecl, - importc: "SDL_WM_ToggleFullScreen", dynlib: LibName.} - # Grabbing means that the mouse is confined to the application window, - # and nearly all keyboard input is passed directly to the application, - # and not interpreted by a window manager, if any. -proc wmGrabInput*(mode: GrabMode): GrabMode{.cdecl, - importc: "SDL_WM_GrabInput", dynlib: LibName.} - #------------------------------------------------------------------------------ - # mouse-routines - #------------------------------------------------------------------------------ - # Retrieve the current state of the mouse. - # The current button state is returned as a button bitmask, which can - # be tested using the SDL_BUTTON(X) macros, and x and y are set to the - # current mouse cursor position. You can pass NULL for either x or y. -proc getMouseState*(x: var int, y: var int): byte{.cdecl, - importc: "SDL_GetMouseState", dynlib: LibName.} - # Retrieve the current state of the mouse. - # The current button state is returned as a button bitmask, which can - # be tested using the SDL_BUTTON(X) macros, and x and y are set to the - # mouse deltas since the last call to SDL_GetRelativeMouseState(). -proc getRelativeMouseState*(x: var int, y: var int): byte{.cdecl, - importc: "SDL_GetRelativeMouseState", dynlib: LibName.} - # Set the position of the mouse cursor (generates a mouse motion event) -proc warpMouse*(x, y: uint16){.cdecl, importc: "SDL_WarpMouse", dynlib: LibName.} - # Create a cursor using the specified data and mask (in MSB format). - # The cursor width must be a multiple of 8 bits. - # - # The cursor is created in black and white according to the following: - # data mask resulting pixel on screen - # 0 1 White - # 1 1 Black - # 0 0 Transparent - # 1 0 Inverted color if possible, black if not. - # - # Cursors created with this function must be freed with SDL_FreeCursor(). -proc createCursor*(data, mask: ptr byte, w, h, hotX, hotY: int): PCursor{.cdecl, - importc: "SDL_CreateCursor", dynlib: LibName.} - # Set the currently active cursor to the specified one. - # If the cursor is currently visible, the change will be immediately - # represented on the display. -proc setCursor*(cursor: PCursor){.cdecl, importc: "SDL_SetCursor", - dynlib: LibName.} - # Returns the currently active cursor. -proc getCursor*(): PCursor{.cdecl, importc: "SDL_GetCursor", dynlib: LibName.} - # Deallocates a cursor created with SDL_CreateCursor(). -proc freeCursor*(cursor: PCursor){.cdecl, importc: "SDL_FreeCursor", - dynlib: LibName.} - # Toggle whether or not the cursor is shown on the screen. - # The cursor start off displayed, but can be turned off. - # SDL_ShowCursor() returns 1 if the cursor was being displayed - # before the call, or 0 if it was not. You can query the current - # state by passing a 'toggle' value of -1. -proc showCursor*(toggle: int): int{.cdecl, importc: "SDL_ShowCursor", - dynlib: LibName.} -proc button*(b: int): int - #------------------------------------------------------------------------------ - # Keyboard-routines - #------------------------------------------------------------------------------ - # Enable/Disable UNICODE translation of keyboard input. - # This translation has some overhead, so translation defaults off. - # If 'enable' is 1, translation is enabled. - # If 'enable' is 0, translation is disabled. - # If 'enable' is -1, the translation state is not changed. - # It returns the previous state of keyboard translation. -proc enableUNICODE*(enable: int): int{.cdecl, importc: "SDL_EnableUNICODE", - dynlib: LibName.} - # If 'delay' is set to 0, keyboard repeat is disabled. -proc enableKeyRepeat*(delay: int, interval: int): int{.cdecl, - importc: "SDL_EnableKeyRepeat", dynlib: LibName.} -proc getKeyRepeat*(delay: PInteger, interval: PInteger){.cdecl, - importc: "SDL_GetKeyRepeat", dynlib: LibName.} - # Get a snapshot of the current state of the keyboard. - # Returns an array of keystates, indexed by the SDLK_* syms. - # Used: - # - # byte *keystate = SDL_GetKeyState(NULL); - # if ( keystate[SDLK_RETURN] ) ... is pressed -proc getKeyState*(numkeys: pointer): ptr byte{.cdecl, importc: "SDL_GetKeyState", - dynlib: LibName.} - # Get the current key modifier state -proc getModState*(): Mod{.cdecl, importc: "SDL_GetModState", dynlib: LibName.} - # Set the current key modifier state - # This does not change the keyboard state, only the key modifier flags. -proc setModState*(modstate: Mod){.cdecl, importc: "SDL_SetModState", - dynlib: LibName.} - # Get the name of an SDL virtual keysym -proc getKeyName*(key: Key): cstring{.cdecl, importc: "SDL_GetKeyName", - dynlib: LibName.} - #------------------------------------------------------------------------------ - # Active Routines - #------------------------------------------------------------------------------ - # This function returns the current state of the application, which is a - # bitwise combination of SDL_APPMOUSEFOCUS, SDL_APPINPUTFOCUS, and - # SDL_APPACTIVE. If SDL_APPACTIVE is set, then the user is able to - # see your application, otherwise it has been iconified or disabled. -proc getAppState*(): byte{.cdecl, importc: "SDL_GetAppState", dynlib: LibName.} - # Mutex functions - # Create a mutex, initialized unlocked -proc createMutex*(): PMutex{.cdecl, importc: "SDL_CreateMutex", dynlib: LibName.} - # Lock the mutex (Returns 0, or -1 on error) -proc mutexP*(mutex: PMutex): int{.cdecl, importc: "SDL_mutexP", dynlib: LibName.} -proc lockMutex*(mutex: PMutex): int - # Unlock the mutex (Returns 0, or -1 on error) -proc mutexV*(mutex: PMutex): int{.cdecl, importc: "SDL_mutexV", dynlib: LibName.} -proc unlockMutex*(mutex: PMutex): int - # Destroy a mutex -proc destroyMutex*(mutex: PMutex){.cdecl, importc: "SDL_DestroyMutex", - dynlib: LibName.} - # * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * - # Semaphore functions - # * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * - # Create a semaphore, initialized with value, returns NULL on failure. -proc createSemaphore*(initialValue: int32): PSem{.cdecl, - importc: "SDL_CreateSemaphore", dynlib: LibName.} - # Destroy a semaphore -proc destroySemaphore*(sem: PSem){.cdecl, importc: "SDL_DestroySemaphore", - dynlib: LibName.} - # This function suspends the calling thread until the semaphore pointed - # to by sem has a positive count. It then atomically decreases the semaphore - # count. -proc semWait*(sem: PSem): int{.cdecl, importc: "SDL_SemWait", dynlib: LibName.} - # Non-blocking variant of SDL_SemWait(), returns 0 if the wait succeeds, - # SDL_MUTEX_TIMEDOUT if the wait would block, and -1 on error. -proc semTryWait*(sem: PSem): int{.cdecl, importc: "SDL_SemTryWait", - dynlib: LibName.} - # Variant of SDL_SemWait() with a timeout in milliseconds, returns 0 if - # the wait succeeds, SDL_MUTEX_TIMEDOUT if the wait does not succeed in - # the allotted time, and -1 on error. - # On some platforms this function is implemented by looping with a delay - # of 1 ms, and so should be avoided if possible. -proc semWaitTimeout*(sem: PSem, ms: int32): int{.cdecl, - importc: "SDL_SemWaitTimeout", dynlib: LibName.} - # Atomically increases the semaphore's count (not blocking), returns 0, - # or -1 on error. -proc semPost*(sem: PSem): int{.cdecl, importc: "SDL_SemPost", dynlib: LibName.} - # Returns the current count of the semaphore -proc semValue*(sem: PSem): int32{.cdecl, importc: "SDL_SemValue", - dynlib: LibName.} - # * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * - # Condition variable functions - # * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * - # Create a condition variable -proc createCond*(): PCond{.cdecl, importc: "SDL_CreateCond", dynlib: LibName.} - # Destroy a condition variable -proc destroyCond*(cond: PCond){.cdecl, importc: "SDL_DestroyCond", - dynlib: LibName.} - # Restart one of the threads that are waiting on the condition variable, - # returns 0 or -1 on error. -proc condSignal*(cond: PCond): int{.cdecl, importc: "SDL_CondSignal", - dynlib: LibName.} - # Restart all threads that are waiting on the condition variable, - # returns 0 or -1 on error. -proc condBroadcast*(cond: PCond): int{.cdecl, importc: "SDL_CondBroadcast", - dynlib: LibName.} - # Wait on the condition variable, unlocking the provided mutex. - # The mutex must be locked before entering this function! - # Returns 0 when it is signaled, or -1 on error. -proc condWait*(cond: PCond, mut: PMutex): int{.cdecl, importc: "SDL_CondWait", - dynlib: LibName.} - # Waits for at most 'ms' milliseconds, and returns 0 if the condition - # variable is signaled, SDL_MUTEX_TIMEDOUT if the condition is not - # signaled in the allotted time, and -1 on error. - # On some platforms this function is implemented by looping with a delay - # of 1 ms, and so should be avoided if possible. -proc condWaitTimeout*(cond: PCond, mut: PMutex, ms: int32): int{.cdecl, - importc: "SDL_CondWaitTimeout", dynlib: LibName.} - # * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * - # Condition variable functions - # * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * - # Create a thread -proc createThread*(fn, data: pointer): PThread{.cdecl, - importc: "SDL_CreateThread", dynlib: LibName.} - # Get the 32-bit thread identifier for the current thread -proc threadID*(): int32{.cdecl, importc: "SDL_ThreadID", dynlib: LibName.} - # Get the 32-bit thread identifier for the specified thread, - # equivalent to SDL_ThreadID() if the specified thread is NULL. -proc getThreadID*(thread: PThread): int32{.cdecl, importc: "SDL_GetThreadID", - dynlib: LibName.} - # Wait for a thread to finish. - # The return code for the thread function is placed in the area - # pointed to by 'status', if 'status' is not NULL. -proc waitThread*(thread: PThread, status: var int){.cdecl, - importc: "SDL_WaitThread", dynlib: LibName.} - # Forcefully kill a thread without worrying about its state -proc killThread*(thread: PThread){.cdecl, importc: "SDL_KillThread", - dynlib: LibName.} - #------------------------------------------------------------------------------ - # Get Environment Routines - #------------------------------------------------------------------------------ - #* - # * This function gives you custom hooks into the window manager information. - # * It fills the structure pointed to by 'info' with custom information and - # * returns 1 if the function is implemented. If it's not implemented, or - # * the version member of the 'info' structure is invalid, it returns 0. - # * -proc getWMInfo*(info: PSysWMinfo): int{.cdecl, importc: "SDL_GetWMInfo", - dynlib: LibName.} - #------------------------------------------------------------------------------ - #SDL_loadso.h - #* This function dynamically loads a shared object and returns a pointer - # * to the object handle (or NULL if there was an error). - # * The 'sofile' parameter is a system dependent name of the object file. - # * -proc loadObject*(sofile: cstring): pointer{.cdecl, importc: "SDL_LoadObject", - dynlib: LibName.} - #* Given an object handle, this function looks up the address of the - # * named function in the shared object and returns it. This address - # * is no longer valid after calling SDL_UnloadObject(). - # * -proc loadFunction*(handle: pointer, name: cstring): pointer{.cdecl, - importc: "SDL_LoadFunction", dynlib: LibName.} - #* Unload a shared object from memory * -proc unloadObject*(handle: pointer){.cdecl, importc: "SDL_UnloadObject", - dynlib: LibName.} - #------------------------------------------------------------------------------ -proc swap32*(d: int32): int32 - # Bitwise Checking functions -proc isBitOn*(value: int, bit: int8): bool -proc turnBitOn*(value: int, bit: int8): int -proc turnBitOff*(value: int, bit: int8): int -# implementation - -proc tablesize(table: cstring): int = - result = sizeOf(table) div sizeOf(table[0]) - -proc rwSeek(context: PRWops, offset: int, whence: int): int = - result = context.seek(context, offset, whence) - -proc rwTell(context: PRWops): int = - result = context.seek(context, 0, 1) - -proc rwRead(context: PRWops, theptr: pointer, size: int, n: int): int = - result = context.read(context, theptr, size, n) - -proc rwWrite(context: PRWops, theptr: pointer, size: int, n: int): int = - result = context.write(context, theptr, size, n) - -proc rwClose(context: PRWops): int = - result = context.closeFile(context) - -proc loadWAV(filename: cstring, spec: PAudioSpec, audioBuf: ptr byte, - audiolen: PUInt32): PAudioSpec = - result = loadWAV_RW(rWFromFile(filename, "rb"), 1, spec, audioBuf, audiolen) - -proc cdInDrive(status: CDStatus): bool = - result = ord(status) > ord(CD_ERROR) - -proc framesToMsf*(frames: int; m, s, f: var int) = - var value = frames - f = value mod CD_FPS - value = value div CD_FPS - s = value mod 60 - value = value div 60 - m = value - -proc msfToFrames*(m, s, f: int): int = - result = m * 60 * CD_FPS + s * CD_FPS + f - -proc version(x: var Version) = - x.major = MAJOR_VERSION - x.minor = MINOR_VERSION - x.patch = PATCHLEVEL - -proc versionnum(x, y, z: int): int = - result = x * 1000 + y * 100 + z - -proc compiledversion(): int = - result = versionnum(MAJOR_VERSION, MINOR_VERSION, PATCHLEVEL) - -proc versionAtleast(x, y, z: int): bool = - result = (compiledversion() >= versionnum(x, y, z)) - -proc loadBMP(filename: cstring): PSurface = - result = loadBMP_RW(rWFromFile(filename, "rb"), 1) - -proc saveBMP(surface: PSurface, filename: cstring): int = - result = saveBMP_RW(surface, rWFromFile(filename, "wb"), 1) - -proc blitSurface(src: PSurface, srcrect: PRect, dst: PSurface, dstrect: PRect): int = - result = upperBlit(src, srcrect, dst, dstrect) - -proc allocSurface(flags: int32, width, height, depth: int, - rMask, gMask, bMask, aMask: int32): PSurface = - result = createRGBSurface(flags, width, height, depth, rMask, gMask, bMask, - aMask) - -proc mustLock(surface: PSurface): bool = - result = ((surface.offset != 0) or - ((surface.flags and (HWSURFACE or ASYNCBLIT or RLEACCEL)) != 0)) - -proc lockMutex(mutex: PMutex): int = - result = mutexP(mutex) - -proc unlockMutex(mutex: PMutex): int = - result = mutexV(mutex) - -proc button(b: int): int = - result = PRESSED shl (b - 1) - -proc swap32(d: int32): int32 = - result = ((d shl 24) or ((d shl 8) and 0x00FF0000) or - ((d shr 8) and 0x0000FF00) or (d shr 24)) - -proc isBitOn(value: int, bit: int8): bool = - result = ((value and (1 shl ze(bit))) != 0) - -proc turnBitOn(value: int, bit: int8): int = - result = (value or (1 shl ze(bit))) - -proc turnBitOff(value: int, bit: int8): int = - result = (value and not (1 shl ze(bit))) diff --git a/lib/wrappers/sdl/sdl_gfx.nim b/lib/wrappers/sdl/sdl_gfx.nim deleted file mode 100644 index 0f5afaa9b..000000000 --- a/lib/wrappers/sdl/sdl_gfx.nim +++ /dev/null @@ -1,452 +0,0 @@ -# -# $Id: sdl_gfx.pas,v 1.3 2007/05/29 21:31:04 savage Exp $ -# -# -# -# $Log: sdl_gfx.pas,v $ -# Revision 1.3 2007/05/29 21:31:04 savage -# Changes as suggested by Almindor for 64bit compatibility. -# -# Revision 1.2 2007/05/20 20:30:18 savage -# Initial Changes to Handle 64 Bits -# -# Revision 1.1 2005/01/03 19:08:32 savage -# Header for the SDL_Gfx library. -# -# -# -# - -import - sdl - -when defined(windows): - const - gfxLibName = "SDL_gfx.dll" -elif defined(macosx): - const - gfxLibName = "libSDL_gfx.dylib" -else: - const - gfxLibName = "libSDL_gfx.so" -const # Some rates in Hz - FPS_UPPER_LIMIT* = 200 - FPS_LOWER_LIMIT* = 1 - FPS_DEFAULT* = 30 # ---- Defines - SMOOTHING_OFF* = 0 - SMOOTHING_ON* = 1 - -type - PFPSmanager* = ptr FPSmanager - FPSmanager*{.final.} = object # ---- Structures - framecount*: uint32 - rateticks*: float32 - lastticks*: uint32 - rate*: uint32 - - PColorRGBA* = ptr ColorRGBA - ColorRGBA*{.final.} = object - r*: byte - g*: byte - b*: byte - a*: byte - - PColorY* = ptr ColorY - ColorY*{.final.} = object # - # - # SDL_framerate: framerate manager - # - # LGPL (c) A. Schiffler - # - # - y*: byte -{.deprecated: [TFPSmanager: FPSmanager, TColorRGBA: ColorRGBA, TColorY: ColorY].} - -proc initFramerate*(manager: PFPSmanager){.cdecl, importc: "SDL_initFramerate", - dynlib: gfxLibName.} -proc setFramerate*(manager: PFPSmanager, rate: cint): cint{.cdecl, - importc: "SDL_setFramerate", dynlib: gfxLibName.} -proc getFramerate*(manager: PFPSmanager): cint{.cdecl, - importc: "SDL_getFramerate", dynlib: gfxLibName.} -proc framerateDelay*(manager: PFPSmanager){.cdecl, - importc: "SDL_framerateDelay", dynlib: gfxLibName.} - # - # - # SDL_gfxPrimitives: graphics primitives for SDL - # - # LGPL (c) A. Schiffler - # - # - # Note: all ___Color routines expect the color to be in format 0xRRGGBBAA - # Pixel -proc pixelColor*(dst: PSurface, x: int16, y: int16, color: uint32): cint{. - cdecl, importc: "pixelColor", dynlib: gfxLibName.} -proc pixelRGBA*(dst: PSurface, x: int16, y: int16, r: byte, g: byte, - b: byte, a: byte): cint{.cdecl, importc: "pixelRGBA", - dynlib: gfxLibName.} - # Horizontal line -proc hlineColor*(dst: PSurface, x1: int16, x2: int16, y: int16, color: uint32): cint{. - cdecl, importc: "hlineColor", dynlib: gfxLibName.} -proc hlineRGBA*(dst: PSurface, x1: int16, x2: int16, y: int16, r: byte, - g: byte, b: byte, a: byte): cint{.cdecl, importc: "hlineRGBA", - dynlib: gfxLibName.} - # Vertical line -proc vlineColor*(dst: PSurface, x: int16, y1: int16, y2: int16, color: uint32): cint{. - cdecl, importc: "vlineColor", dynlib: gfxLibName.} -proc vlineRGBA*(dst: PSurface, x: int16, y1: int16, y2: int16, r: byte, - g: byte, b: byte, a: byte): cint{.cdecl, importc: "vlineRGBA", - dynlib: gfxLibName.} - # Rectangle -proc rectangleColor*(dst: PSurface, x1: int16, y1: int16, x2: int16, - y2: int16, color: uint32): cint{.cdecl, - importc: "rectangleColor", dynlib: gfxLibName.} -proc rectangleRGBA*(dst: PSurface, x1: int16, y1: int16, x2: int16, - y2: int16, r: byte, g: byte, b: byte, a: byte): cint{. - cdecl, importc: "rectangleRGBA", dynlib: gfxLibName.} - # Filled rectangle (Box) -proc boxColor*(dst: PSurface, x1: int16, y1: int16, x2: int16, y2: int16, - color: uint32): cint{.cdecl, importc: "boxColor", - dynlib: gfxLibName.} -proc boxRGBA*(dst: PSurface, x1: int16, y1: int16, x2: int16, y2: int16, - r: byte, g: byte, b: byte, a: byte): cint{.cdecl, - importc: "boxRGBA", dynlib: gfxLibName.} - # Line -proc lineColor*(dst: PSurface, x1: int16, y1: int16, x2: int16, y2: int16, - color: uint32): cint{.cdecl, importc: "lineColor", - dynlib: gfxLibName.} -proc lineRGBA*(dst: PSurface, x1: int16, y1: int16, x2: int16, y2: int16, - r: byte, g: byte, b: byte, a: byte): cint{.cdecl, - importc: "lineRGBA", dynlib: gfxLibName.} - # AA Line -proc aalineColor*(dst: PSurface, x1: int16, y1: int16, x2: int16, y2: int16, - color: uint32): cint{.cdecl, importc: "aalineColor", - dynlib: gfxLibName.} -proc aalineRGBA*(dst: PSurface, x1: int16, y1: int16, x2: int16, y2: int16, - r: byte, g: byte, b: byte, a: byte): cint{.cdecl, - importc: "aalineRGBA", dynlib: gfxLibName.} - # Circle -proc circleColor*(dst: PSurface, x: int16, y: int16, r: int16, color: uint32): cint{. - cdecl, importc: "circleColor", dynlib: gfxLibName.} -proc circleRGBA*(dst: PSurface, x: int16, y: int16, rad: int16, r: byte, - g: byte, b: byte, a: byte): cint{.cdecl, - importc: "circleRGBA", dynlib: gfxLibName.} - # AA Circle -proc aacircleColor*(dst: PSurface, x: int16, y: int16, r: int16, - color: uint32): cint{.cdecl, importc: "aacircleColor", - dynlib: gfxLibName.} -proc aacircleRGBA*(dst: PSurface, x: int16, y: int16, rad: int16, r: byte, - g: byte, b: byte, a: byte): cint{.cdecl, - importc: "aacircleRGBA", dynlib: gfxLibName.} - # Filled Circle -proc filledCircleColor*(dst: PSurface, x: int16, y: int16, r: int16, - color: uint32): cint{.cdecl, - importc: "filledCircleColor", dynlib: gfxLibName.} -proc filledCircleRGBA*(dst: PSurface, x: int16, y: int16, rad: int16, - r: byte, g: byte, b: byte, a: byte): cint{.cdecl, - importc: "filledCircleRGBA", dynlib: gfxLibName.} - # Ellipse -proc ellipseColor*(dst: PSurface, x: int16, y: int16, rx: int16, ry: int16, - color: uint32): cint{.cdecl, importc: "ellipseColor", - dynlib: gfxLibName.} -proc ellipseRGBA*(dst: PSurface, x: int16, y: int16, rx: int16, ry: int16, - r: byte, g: byte, b: byte, a: byte): cint{.cdecl, - importc: "ellipseRGBA", dynlib: gfxLibName.} - # AA Ellipse -proc aaellipseColor*(dst: PSurface, xc: int16, yc: int16, rx: int16, - ry: int16, color: uint32): cint{.cdecl, - importc: "aaellipseColor", dynlib: gfxLibName.} -proc aaellipseRGBA*(dst: PSurface, x: int16, y: int16, rx: int16, ry: int16, - r: byte, g: byte, b: byte, a: byte): cint{.cdecl, - importc: "aaellipseRGBA", dynlib: gfxLibName.} - # Filled Ellipse -proc filledEllipseColor*(dst: PSurface, x: int16, y: int16, rx: int16, - ry: int16, color: uint32): cint{.cdecl, - importc: "filledEllipseColor", dynlib: gfxLibName.} -proc filledEllipseRGBA*(dst: PSurface, x: int16, y: int16, rx: int16, - ry: int16, r: byte, g: byte, b: byte, a: byte): cint{. - cdecl, importc: "filledEllipseRGBA", dynlib: gfxLibName.} - # Pie -proc pieColor*(dst: PSurface, x: int16, y: int16, rad: int16, start: int16, - finish: int16, color: uint32): cint{.cdecl, importc: "pieColor", - dynlib: gfxLibName.} -proc pieRGBA*(dst: PSurface, x: int16, y: int16, rad: int16, start: int16, - finish: int16, r: byte, g: byte, b: byte, a: byte): cint{. - cdecl, importc: "pieRGBA", dynlib: gfxLibName.} - # Filled Pie -proc filledPieColor*(dst: PSurface, x: int16, y: int16, rad: int16, - start: int16, finish: int16, color: uint32): cint{.cdecl, - importc: "filledPieColor", dynlib: gfxLibName.} -proc filledPieRGBA*(dst: PSurface, x: int16, y: int16, rad: int16, - start: int16, finish: int16, r: byte, g: byte, b: byte, - a: byte): cint{.cdecl, importc: "filledPieRGBA", - dynlib: gfxLibName.} - # Trigon -proc trigonColor*(dst: PSurface, x1: int16, y1: int16, x2: int16, y2: int16, - x3: int16, y3: int16, color: uint32): cint{.cdecl, - importc: "trigonColor", dynlib: gfxLibName.} -proc trigonRGBA*(dst: PSurface, x1: int16, y1: int16, x2: int16, y2: int16, - x3: int16, y3: int16, r: byte, g: byte, b: byte, a: byte): cint{. - cdecl, importc: "trigonRGBA", dynlib: gfxLibName.} - # AA-Trigon -proc aatrigonColor*(dst: PSurface, x1: int16, y1: int16, x2: int16, - y2: int16, x3: int16, y3: int16, color: uint32): cint{. - cdecl, importc: "aatrigonColor", dynlib: gfxLibName.} -proc aatrigonRGBA*(dst: PSurface, x1: int16, y1: int16, x2: int16, - y2: int16, x3: int16, y3: int16, r: byte, g: byte, - b: byte, a: byte): cint{.cdecl, importc: "aatrigonRGBA", - dynlib: gfxLibName.} - # Filled Trigon -proc filledTrigonColor*(dst: PSurface, x1: int16, y1: int16, x2: int16, - y2: int16, x3: int16, y3: int16, color: uint32): cint{. - cdecl, importc: "filledTrigonColor", dynlib: gfxLibName.} -proc filledTrigonRGBA*(dst: PSurface, x1: int16, y1: int16, x2: int16, - y2: int16, x3: int16, y3: int16, r: byte, g: byte, - b: byte, a: byte): cint{.cdecl, - importc: "filledTrigonRGBA", dynlib: gfxLibName.} - # Polygon -proc polygonColor*(dst: PSurface, vx: ptr int16, vy: ptr int16, n: cint, - color: uint32): cint{.cdecl, importc: "polygonColor", - dynlib: gfxLibName.} -proc polygonRGBA*(dst: PSurface, vx: ptr int16, vy: ptr int16, n: cint, r: byte, - g: byte, b: byte, a: byte): cint{.cdecl, - importc: "polygonRGBA", dynlib: gfxLibName.} - # AA-Polygon -proc aapolygonColor*(dst: PSurface, vx: ptr int16, vy: ptr int16, n: cint, - color: uint32): cint{.cdecl, importc: "aapolygonColor", - dynlib: gfxLibName.} -proc aapolygonRGBA*(dst: PSurface, vx: ptr int16, vy: ptr int16, n: cint, r: byte, - g: byte, b: byte, a: byte): cint{.cdecl, - importc: "aapolygonRGBA", dynlib: gfxLibName.} - # Filled Polygon -proc filledPolygonColor*(dst: PSurface, vx: ptr int16, vy: ptr int16, n: cint, - color: uint32): cint{.cdecl, - importc: "filledPolygonColor", dynlib: gfxLibName.} -proc filledPolygonRGBA*(dst: PSurface, vx: ptr int16, vy: ptr int16, n: cint, - r: byte, g: byte, b: byte, a: byte): cint{.cdecl, - importc: "filledPolygonRGBA", dynlib: gfxLibName.} - # Bezier - # s = number of steps -proc bezierColor*(dst: PSurface, vx: ptr int16, vy: ptr int16, n: cint, s: cint, - color: uint32): cint{.cdecl, importc: "bezierColor", - dynlib: gfxLibName.} -proc bezierRGBA*(dst: PSurface, vx: ptr int16, vy: ptr int16, n: cint, s: cint, - r: byte, g: byte, b: byte, a: byte): cint{.cdecl, - importc: "bezierRGBA", dynlib: gfxLibName.} - # Characters/Strings -proc characterColor*(dst: PSurface, x: int16, y: int16, c: char, color: uint32): cint{. - cdecl, importc: "characterColor", dynlib: gfxLibName.} -proc characterRGBA*(dst: PSurface, x: int16, y: int16, c: char, r: byte, - g: byte, b: byte, a: byte): cint{.cdecl, - importc: "characterRGBA", dynlib: gfxLibName.} -proc stringColor*(dst: PSurface, x: int16, y: int16, c: cstring, color: uint32): cint{. - cdecl, importc: "stringColor", dynlib: gfxLibName.} -proc stringRGBA*(dst: PSurface, x: int16, y: int16, c: cstring, r: byte, - g: byte, b: byte, a: byte): cint{.cdecl, - importc: "stringRGBA", dynlib: gfxLibName.} -proc gfxPrimitivesSetFont*(fontdata: pointer, cw: cint, ch: cint){.cdecl, - importc: "gfxPrimitivesSetFont", dynlib: gfxLibName.} - # - # - # SDL_imageFilter - bytes-image "filter" routines - # (uses inline x86 MMX optimizations if available) - # - # LGPL (c) A. Schiffler - # - # - # Comments: - # 1.) MMX functions work best if all data blocks are aligned on a 32 bytes boundary. - # 2.) Data that is not within an 8 byte boundary is processed using the C routine. - # 3.) Convolution routines do not have C routines at this time. - # Detect MMX capability in CPU -proc imageFilterMMXdetect*(): cint{.cdecl, importc: "SDL_imageFilterMMXdetect", - dynlib: gfxLibName.} - # Force use of MMX off (or turn possible use back on) -proc imageFilterMMXoff*(){.cdecl, importc: "SDL_imageFilterMMXoff", - dynlib: gfxLibName.} -proc imageFilterMMXon*(){.cdecl, importc: "SDL_imageFilterMMXon", - dynlib: gfxLibName.} - # - # All routines return: - # 0 OK - # -1 Error (internal error, parameter error) - # - # SDL_imageFilterAdd: D = saturation255(S1 + S2) -proc imageFilterAdd*(src1: cstring, src2: cstring, dest: cstring, len: cint): cint{. - cdecl, importc: "SDL_imageFilterAdd", dynlib: gfxLibName.} - # SDL_imageFilterMean: D = S1/2 + S2/2 -proc imageFilterMean*(src1: cstring, src2: cstring, dest: cstring, len: cint): cint{. - cdecl, importc: "SDL_imageFilterMean", dynlib: gfxLibName.} - # SDL_imageFilterSub: D = saturation0(S1 - S2) -proc imageFilterSub*(src1: cstring, src2: cstring, dest: cstring, len: cint): cint{. - cdecl, importc: "SDL_imageFilterSub", dynlib: gfxLibName.} - # SDL_imageFilterAbsDiff: D = | S1 - S2 | -proc imageFilterAbsDiff*(src1: cstring, src2: cstring, dest: cstring, len: cint): cint{. - cdecl, importc: "SDL_imageFilterAbsDiff", dynlib: gfxLibName.} - # SDL_imageFilterMult: D = saturation(S1 * S2) -proc imageFilterMult*(src1: cstring, src2: cstring, dest: cstring, len: cint): cint{. - cdecl, importc: "SDL_imageFilterMult", dynlib: gfxLibName.} - # SDL_imageFilterMultNor: D = S1 * S2 (non-MMX) -proc imageFilterMultNor*(src1: cstring, src2: cstring, dest: cstring, len: cint): cint{. - cdecl, importc: "SDL_imageFilterMultNor", dynlib: gfxLibName.} - # SDL_imageFilterMultDivby2: D = saturation255(S1/2 * S2) -proc imageFilterMultDivby2*(src1: cstring, src2: cstring, dest: cstring, - len: cint): cint{.cdecl, - importc: "SDL_imageFilterMultDivby2", dynlib: gfxLibName.} - # SDL_imageFilterMultDivby4: D = saturation255(S1/2 * S2/2) -proc imageFilterMultDivby4*(src1: cstring, src2: cstring, dest: cstring, - len: cint): cint{.cdecl, - importc: "SDL_imageFilterMultDivby4", dynlib: gfxLibName.} - # SDL_imageFilterBitAnd: D = S1 & S2 -proc imageFilterBitAnd*(src1: cstring, src2: cstring, dest: cstring, len: cint): cint{. - cdecl, importc: "SDL_imageFilterBitAnd", dynlib: gfxLibName.} - # SDL_imageFilterBitOr: D = S1 | S2 -proc imageFilterBitOr*(src1: cstring, src2: cstring, dest: cstring, len: cint): cint{. - cdecl, importc: "SDL_imageFilterBitOr", dynlib: gfxLibName.} - # SDL_imageFilterDiv: D = S1 / S2 (non-MMX) -proc imageFilterDiv*(src1: cstring, src2: cstring, dest: cstring, len: cint): cint{. - cdecl, importc: "SDL_imageFilterDiv", dynlib: gfxLibName.} - # SDL_imageFilterBitNegation: D = !S -proc imageFilterBitNegation*(src1: cstring, dest: cstring, len: cint): cint{. - cdecl, importc: "SDL_imageFilterBitNegation", dynlib: gfxLibName.} - # SDL_imageFilterAddByte: D = saturation255(S + C) -proc imageFilterAddByte*(src1: cstring, dest: cstring, len: cint, c: char): cint{. - cdecl, importc: "SDL_imageFilterAddByte", dynlib: gfxLibName.} - # SDL_imageFilterAddUint: D = saturation255(S + (uint)C) -proc imageFilterAddUint*(src1: cstring, dest: cstring, len: cint, c: cint): cint{. - cdecl, importc: "SDL_imageFilterAddUint", dynlib: gfxLibName.} - # SDL_imageFilterAddByteToHalf: D = saturation255(S/2 + C) -proc imageFilterAddByteToHalf*(src1: cstring, dest: cstring, len: cint, c: char): cint{. - cdecl, importc: "SDL_imageFilterAddByteToHalf", dynlib: gfxLibName.} - # SDL_imageFilterSubByte: D = saturation0(S - C) -proc imageFilterSubByte*(src1: cstring, dest: cstring, len: cint, c: char): cint{. - cdecl, importc: "SDL_imageFilterSubByte", dynlib: gfxLibName.} - # SDL_imageFilterSubUint: D = saturation0(S - (uint)C) -proc imageFilterSubUint*(src1: cstring, dest: cstring, len: cint, c: cint): cint{. - cdecl, importc: "SDL_imageFilterSubUint", dynlib: gfxLibName.} - # SDL_imageFilterShiftRight: D = saturation0(S >> N) -proc imageFilterShiftRight*(src1: cstring, dest: cstring, len: cint, n: char): cint{. - cdecl, importc: "SDL_imageFilterShiftRight", dynlib: gfxLibName.} - # SDL_imageFilterShiftRightUint: D = saturation0((uint)S >> N) -proc imageFilterShiftRightUint*(src1: cstring, dest: cstring, len: cint, n: char): cint{. - cdecl, importc: "SDL_imageFilterShiftRightUint", dynlib: gfxLibName.} - # SDL_imageFilterMultByByte: D = saturation255(S * C) -proc imageFilterMultByByte*(src1: cstring, dest: cstring, len: cint, c: char): cint{. - cdecl, importc: "SDL_imageFilterMultByByte", dynlib: gfxLibName.} - # SDL_imageFilterShiftRightAndMultByByte: D = saturation255((S >> N) * C) -proc imageFilterShiftRightAndMultByByte*(src1: cstring, dest: cstring, len: cint, - n: char, c: char): cint{.cdecl, - importc: "SDL_imageFilterShiftRightAndMultByByte", - dynlib: gfxLibName.} - # SDL_imageFilterShiftLeftByte: D = (S << N) -proc imageFilterShiftLeftByte*(src1: cstring, dest: cstring, len: cint, n: char): cint{. - cdecl, importc: "SDL_imageFilterShiftLeftByte", dynlib: gfxLibName.} - # SDL_imageFilterShiftLeftUint: D = ((uint)S << N) -proc imageFilterShiftLeftUint*(src1: cstring, dest: cstring, len: cint, n: char): cint{. - cdecl, importc: "SDL_imageFilterShiftLeftUint", dynlib: gfxLibName.} - # SDL_imageFilterShiftLeft: D = saturation255(S << N) -proc imageFilterShiftLeft*(src1: cstring, dest: cstring, len: cint, n: char): cint{. - cdecl, importc: "SDL_imageFilterShiftLeft", dynlib: gfxLibName.} - # SDL_imageFilterBinarizeUsingThreshold: D = S >= T ? 255:0 -proc imageFilterBinarizeUsingThreshold*(src1: cstring, dest: cstring, len: cint, - t: char): cint{.cdecl, - importc: "SDL_imageFilterBinarizeUsingThreshold", dynlib: gfxLibName.} - # SDL_imageFilterClipToRange: D = (S >= Tmin) & (S <= Tmax) 255:0 -proc imageFilterClipToRange*(src1: cstring, dest: cstring, len: cint, tmin: int8, - tmax: int8): cint{.cdecl, - importc: "SDL_imageFilterClipToRange", dynlib: gfxLibName.} - # SDL_imageFilterNormalizeLinear: D = saturation255((Nmax - Nmin)/(Cmax - Cmin)*(S - Cmin) + Nmin) -proc imageFilterNormalizeLinear*(src1: cstring, dest: cstring, len: cint, - cmin: cint, cmax: cint, nmin: cint, nmax: cint): cint{. - cdecl, importc: "SDL_imageFilterNormalizeLinear", dynlib: gfxLibName.} - # !!! NO C-ROUTINE FOR THESE FUNCTIONS YET !!! - # SDL_imageFilterConvolveKernel3x3Divide: Dij = saturation0and255( ... ) -proc imageFilterConvolveKernel3x3Divide*(src: cstring, dest: cstring, rows: cint, - columns: cint, kernel: pointer, divisor: int8): cint{.cdecl, - importc: "SDL_imageFilterConvolveKernel3x3Divide", dynlib: gfxLibName.} - # SDL_imageFilterConvolveKernel5x5Divide: Dij = saturation0and255( ... ) -proc imageFilterConvolveKernel5x5Divide*(src: cstring, dest: cstring, rows: cint, - columns: cint, kernel: pointer, divisor: int8): cint{.cdecl, - importc: "SDL_imageFilterConvolveKernel5x5Divide", dynlib: gfxLibName.} - # SDL_imageFilterConvolveKernel7x7Divide: Dij = saturation0and255( ... ) -proc imageFilterConvolveKernel7x7Divide*(src: cstring, dest: cstring, rows: cint, - columns: cint, kernel: pointer, divisor: int8): cint{.cdecl, - importc: "SDL_imageFilterConvolveKernel7x7Divide", dynlib: gfxLibName.} - # SDL_imageFilterConvolveKernel9x9Divide: Dij = saturation0and255( ... ) -proc imageFilterConvolveKernel9x9Divide*(src: cstring, dest: cstring, rows: cint, - columns: cint, kernel: pointer, divisor: int8): cint{.cdecl, - importc: "SDL_imageFilterConvolveKernel9x9Divide", dynlib: gfxLibName.} - # SDL_imageFilterConvolveKernel3x3ShiftRight: Dij = saturation0and255( ... ) -proc imageFilterConvolveKernel3x3ShiftRight*(src: cstring, dest: cstring, - rows: cint, columns: cint, kernel: pointer, nRightShift: char): cint{.cdecl, - importc: "SDL_imageFilterConvolveKernel3x3ShiftRight", dynlib: gfxLibName.} - # SDL_imageFilterConvolveKernel5x5ShiftRight: Dij = saturation0and255( ... ) -proc imageFilterConvolveKernel5x5ShiftRight*(src: cstring, dest: cstring, - rows: cint, columns: cint, kernel: pointer, nRightShift: char): cint{.cdecl, - importc: "SDL_imageFilterConvolveKernel5x5ShiftRight", dynlib: gfxLibName.} - # SDL_imageFilterConvolveKernel7x7ShiftRight: Dij = saturation0and255( ... ) -proc imageFilterConvolveKernel7x7ShiftRight*(src: cstring, dest: cstring, - rows: cint, columns: cint, kernel: pointer, nRightShift: char): cint{.cdecl, - importc: "SDL_imageFilterConvolveKernel7x7ShiftRight", dynlib: gfxLibName.} - # SDL_imageFilterConvolveKernel9x9ShiftRight: Dij = saturation0and255( ... ) -proc imageFilterConvolveKernel9x9ShiftRight*(src: cstring, dest: cstring, - rows: cint, columns: cint, kernel: pointer, nRightShift: char): cint{.cdecl, - importc: "SDL_imageFilterConvolveKernel9x9ShiftRight", dynlib: gfxLibName.} - # SDL_imageFilterSobelX: Dij = saturation255( ... ) -proc imageFilterSobelX*(src: cstring, dest: cstring, rows: cint, columns: cint): cint{. - cdecl, importc: "SDL_imageFilterSobelX", dynlib: gfxLibName.} - # SDL_imageFilterSobelXShiftRight: Dij = saturation255( ... ) -proc imageFilterSobelXShiftRight*(src: cstring, dest: cstring, rows: cint, - columns: cint, nRightShift: char): cint{.cdecl, - importc: "SDL_imageFilterSobelXShiftRight", dynlib: gfxLibName.} - # Align/restore stack to 32 byte boundary -- Functionality untested! -- -proc imageFilterAlignStack*(){.cdecl, importc: "SDL_imageFilterAlignStack", - dynlib: gfxLibName.} -proc imageFilterRestoreStack*(){.cdecl, importc: "SDL_imageFilterRestoreStack", - dynlib: gfxLibName.} - # - # - # SDL_rotozoom - rotozoomer - # - # LGPL (c) A. Schiffler - # - # - # - # - # rotozoomSurface() - # - # Rotates and zoomes a 32bit or 8bit 'src' surface to newly created 'dst' surface. - # 'angle' is the rotation in degrees. 'zoom' a scaling factor. If 'smooth' is 1 - # then the destination 32bit surface is anti-aliased. If the surface is not 8bit - # or 32bit RGBA/ABGR it will be converted into a 32bit RGBA format on the fly. - # - # -proc rotozoomSurface*(src: PSurface, angle: float64, zoom: float64, smooth: cint): PSurface{. - cdecl, importc: "rotozoomSurface", dynlib: gfxLibName.} -proc rotozoomSurfaceXY*(src: PSurface, angle: float64, zoomx: float64, - zoomy: float64, smooth: cint): PSurface{.cdecl, - importc: "rotozoomSurfaceXY", dynlib: gfxLibName.} - # Returns the size of the target surface for a rotozoomSurface() call -proc rotozoomSurfaceSize*(width: cint, height: cint, angle: float64, - zoom: float64, dstwidth: var cint, dstheight: var cint){. - cdecl, importc: "rotozoomSurfaceSize", dynlib: gfxLibName.} -proc rotozoomSurfaceSizeXY*(width: cint, height: cint, angle: float64, - zoomx: float64, zoomy: float64, dstwidth: var cint, - dstheight: var cint){.cdecl, - importc: "rotozoomSurfaceSizeXY", dynlib: gfxLibName.} - # - # - # zoomSurface() - # - # Zoomes a 32bit or 8bit 'src' surface to newly created 'dst' surface. - # 'zoomx' and 'zoomy' are scaling factors for width and height. If 'smooth' is 1 - # then the destination 32bit surface is anti-aliased. If the surface is not 8bit - # or 32bit RGBA/ABGR it will be converted into a 32bit RGBA format on the fly. - # - # -proc zoomSurface*(src: PSurface, zoomx: float64, zoomy: float64, smooth: cint): PSurface{. - cdecl, importc: "zoomSurface", dynlib: gfxLibName.} - # Returns the size of the target surface for a zoomSurface() call -proc zoomSurfaceSize*(width: cint, height: cint, zoomx: float64, zoomy: float64, - dstwidth: var cint, dstheight: var cint){.cdecl, - importc: "zoomSurfaceSize", dynlib: gfxLibName.} -# implementation diff --git a/lib/wrappers/sdl/sdl_image.nim b/lib/wrappers/sdl/sdl_image.nim deleted file mode 100644 index 7f99c8069..000000000 --- a/lib/wrappers/sdl/sdl_image.nim +++ /dev/null @@ -1,243 +0,0 @@ -# -# $Id: sdl_image.pas,v 1.14 2007/05/29 21:31:13 savage Exp $ -# -# -#****************************************************************************** -# -# Borland Delphi SDL_Image - An example image loading library for use -# with SDL -# Conversion of the Simple DirectMedia Layer Image Headers -# -# Portions created by Sam Lantinga are -# Copyright (C) 1997, 1998, 1999, 2000, 2001 Sam Lantinga -# 5635-34 Springhouse Dr. -# Pleasanton, CA 94588 (USA) -# -# All Rights Reserved. -# -# The original files are : SDL_image.h -# -# The initial developer of this Pascal code was : -# Matthias Thoma -# -# Portions created by Matthias Thoma are -# Copyright (C) 2000 - 2001 Matthias Thoma. -# -# -# Contributor(s) -# -------------- -# Dominique Louis -# -# Obtained through: -# Joint Endeavour of Delphi Innovators ( Project JEDI ) -# -# You may retrieve the latest version of this file at the Project -# JEDI home page, located at http://delphi-jedi.org -# -# The contents of this file are used with permission, subject to -# the Mozilla Public License Version 1.1 (the "License"); you may -# not use this file except in compliance with the License. You may -# obtain a copy of the License at -# http://www.mozilla.org/MPL/MPL-1.1.html -# -# Software distributed under the License is distributed on an -# "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# Description -# ----------- -# A simple library to load images of various formats as SDL surfaces -# -# Requires -# -------- -# SDL.pas in your search path. -# -# Programming Notes -# ----------------- -# See the Aliens Demo on how to make use of this libaray -# -# Revision History -# ---------------- -# April 02 2001 - MT : Initial Translation -# -# May 08 2001 - DL : Added ExternalSym derectives and copyright header -# -# April 03 2003 - DL : Added jedi-sdl.inc include file to support more -# Pascal compilers. Initial support is now included -# for GnuPascal, VirtualPascal, TMT and obviously -# continue support for Delphi Kylix and FreePascal. -# -# April 08 2003 - MK : Aka Mr Kroket - Added Better FPC support -# -# April 24 2003 - DL : under instruction from Alexey Barkovoy, I have added -# better TMT Pascal support and under instruction -# from Prof. Abimbola Olowofoyeku (The African Chief), -# I have added better Gnu Pascal support -# -# April 30 2003 - DL : under instruction from David Mears AKA -# Jason Siletto, I have added FPC Linux support. -# This was compiled with fpc 1.1, so remember to set -# include file path. ie. -Fi/usr/share/fpcsrc/rtl/* -# -# -# $Log: sdl_image.pas,v $ -# Revision 1.14 2007/05/29 21:31:13 savage -# Changes as suggested by Almindor for 64bit compatibility. -# -# Revision 1.13 2007/05/20 20:30:54 savage -# Initial Changes to Handle 64 Bits -# -# Revision 1.12 2006/12/02 00:14:40 savage -# Updated to latest version -# -# Revision 1.11 2005/04/10 18:22:59 savage -# Changes as suggested by Michalis, thanks. -# -# Revision 1.10 2005/04/10 11:48:33 savage -# Changes as suggested by Michalis, thanks. -# -# Revision 1.9 2005/01/05 01:47:07 savage -# Changed LibName to reflect what MacOS X should have. ie libSDL*-1.2.0.dylib respectively. -# -# Revision 1.8 2005/01/04 23:14:44 savage -# Changed LibName to reflect what most Linux distros will have. ie libSDL*-1.2.so.0 respectively. -# -# Revision 1.7 2005/01/01 02:03:12 savage -# Updated to v1.2.4 -# -# Revision 1.6 2004/08/14 22:54:30 savage -# Updated so that Library name defines are correctly defined for MacOS X. -# -# Revision 1.5 2004/05/10 14:10:04 savage -# Initial MacOS X support. Fixed defines for MACOS ( Classic ) and DARWIN ( MacOS X ). -# -# Revision 1.4 2004/04/13 09:32:08 savage -# Changed Shared object names back to just the .so extension to avoid conflicts on various Linux/Unix distros. Therefore developers will need to create Symbolic links to the actual Share Objects if necessary. -# -# Revision 1.3 2004/04/01 20:53:23 savage -# Changed Linux Shared Object names so they reflect the Symbolic Links that are created when installing the RPMs from the SDL site. -# -# Revision 1.2 2004/03/30 20:23:28 savage -# Tidied up use of UNIX compiler directive. -# -# Revision 1.1 2004/02/14 23:35:42 savage -# version 1 of sdl_image, sdl_mixer and smpeg. -# -# -# -#****************************************************************************** - -import - sdl - -when defined(windows): - const - ImageLibName = "SDL_Image.dll" -elif defined(macosx): - const - ImageLibName = "libSDL_image-1.2.0.dylib" -else: - const - ImageLibName = "libSDL_image(.so|-1.2.so.0)" -const - IMAGE_MAJOR_VERSION* = 1 - IMAGE_MINOR_VERSION* = 2 - IMAGE_PATCHLEVEL* = 5 - -# This macro can be used to fill a version structure with the compile-time -# version of the SDL_image library. - -proc imageVersion*(x: var Version) - # This function gets the version of the dynamically linked SDL_image library. - # it should NOT be used to fill a version structure, instead you should - # use the SDL_IMAGE_VERSION() macro. - # -proc imgLinkedVersion*(): Pversion{.importc: "IMG_Linked_Version", - dynlib: ImageLibName.} - # Load an image from an SDL data source. - # The 'type' may be one of: "BMP", "GIF", "PNG", etc. - # - # If the image format supports a transparent pixel, SDL will set the - # colorkey for the surface. You can enable RLE acceleration on the - # surface afterwards by calling: - # SDL_SetColorKey(image, SDL_RLEACCEL, image.format.colorkey); - # - -const - IMG_INIT_JPG* = 0x00000001 - IMG_INIT_PNG* = 0x00000002 - IMG_INIT_TIF* = 0x00000004 - IMG_INIT_WEBP* = 0x00000008 - -proc imgInit*(flags: cint): int {.cdecl, importc: "IMG_Init", - dynlib: ImageLibName.} -proc imgQuit*() {.cdecl, importc: "IMG_Quit", - dynlib: ImageLibName.} -proc imgLoadTypedRW*(src: PRWops, freesrc: cint, theType: cstring): PSurface{. - cdecl, importc: "IMG_LoadTyped_RW", dynlib: ImageLibName.} - # Convenience functions -proc imgLoad*(theFile: cstring): PSurface{.cdecl, importc: "IMG_Load", - dynlib: ImageLibName.} -proc imgLoadRW*(src: PRWops, freesrc: cint): PSurface{.cdecl, - importc: "IMG_Load_RW", dynlib: ImageLibName.} - # Invert the alpha of a surface for use with OpenGL - # This function is now a no-op, and only provided for backwards compatibility. -proc imgInvertAlpha*(theOn: cint): cint{.cdecl, importc: "IMG_InvertAlpha", - dynlib: ImageLibName.} - # Functions to detect a file type, given a seekable source -proc imgIsBMP*(src: PRWops): cint{.cdecl, importc: "IMG_isBMP", - dynlib: ImageLibName.} -proc imgIsGIF*(src: PRWops): cint{.cdecl, importc: "IMG_isGIF", - dynlib: ImageLibName.} -proc imgIsJPG*(src: PRWops): cint{.cdecl, importc: "IMG_isJPG", - dynlib: ImageLibName.} -proc imgIsLBM*(src: PRWops): cint{.cdecl, importc: "IMG_isLBM", - dynlib: ImageLibName.} -proc imgIsPCX*(src: PRWops): cint{.cdecl, importc: "IMG_isPCX", - dynlib: ImageLibName.} -proc imgIsPNG*(src: PRWops): cint{.cdecl, importc: "IMG_isPNG", - dynlib: ImageLibName.} -proc imgIsPNM*(src: PRWops): cint{.cdecl, importc: "IMG_isPNM", - dynlib: ImageLibName.} -proc imgIsTIF*(src: PRWops): cint{.cdecl, importc: "IMG_isTIF", - dynlib: ImageLibName.} -proc imgIsXCF*(src: PRWops): cint{.cdecl, importc: "IMG_isXCF", - dynlib: ImageLibName.} -proc imgIsXPM*(src: PRWops): cint{.cdecl, importc: "IMG_isXPM", - dynlib: ImageLibName.} -proc imgIsXV*(src: PRWops): cint{.cdecl, importc: "IMG_isXV", - dynlib: ImageLibName.} - # Individual loading functions -proc imgLoadBMP_RW*(src: PRWops): PSurface{.cdecl, importc: "IMG_LoadBMP_RW", - dynlib: ImageLibName.} -proc imgLoadGIF_RW*(src: PRWops): PSurface{.cdecl, importc: "IMG_LoadGIF_RW", - dynlib: ImageLibName.} -proc imgLoadJPG_RW*(src: PRWops): PSurface{.cdecl, importc: "IMG_LoadJPG_RW", - dynlib: ImageLibName.} -proc imgLoadLBM_RW*(src: PRWops): PSurface{.cdecl, importc: "IMG_LoadLBM_RW", - dynlib: ImageLibName.} -proc imgLoadPCX_RW*(src: PRWops): PSurface{.cdecl, importc: "IMG_LoadPCX_RW", - dynlib: ImageLibName.} -proc imgLoadPNM_RW*(src: PRWops): PSurface{.cdecl, importc: "IMG_LoadPNM_RW", - dynlib: ImageLibName.} -proc imgLoadPNG_RW*(src: PRWops): PSurface{.cdecl, importc: "IMG_LoadPNG_RW", - dynlib: ImageLibName.} -proc imgLoadTGA_RW*(src: PRWops): PSurface{.cdecl, importc: "IMG_LoadTGA_RW", - dynlib: ImageLibName.} -proc imgLoadTIF_RW*(src: PRWops): PSurface{.cdecl, importc: "IMG_LoadTIF_RW", - dynlib: ImageLibName.} -proc imgLoadXCF_RW*(src: PRWops): PSurface{.cdecl, importc: "IMG_LoadXCF_RW", - dynlib: ImageLibName.} -proc imgLoadXPM_RW*(src: PRWops): PSurface{.cdecl, importc: "IMG_LoadXPM_RW", - dynlib: ImageLibName.} -proc imgLoadXV_RW*(src: PRWops): PSurface{.cdecl, importc: "IMG_LoadXV_RW", - dynlib: ImageLibName.} -proc imgReadXPMFromArray*(xpm: cstringArray): PSurface{.cdecl, - importc: "IMG_ReadXPMFromArray", dynlib: ImageLibName.} - -proc imageVersion(x: var Version) = - x.major = IMAGE_MAJOR_VERSION - x.minor = IMAGE_MINOR_VERSION - x.patch = IMAGE_PATCHLEVEL - diff --git a/lib/wrappers/sdl/sdl_mixer.nim b/lib/wrappers/sdl/sdl_mixer.nim deleted file mode 100644 index b8f013a4a..000000000 --- a/lib/wrappers/sdl/sdl_mixer.nim +++ /dev/null @@ -1,489 +0,0 @@ -#****************************************************************************** -# -# $Id: sdl_mixer.pas,v 1.18 2007/05/29 21:31:44 savage Exp $ -# -# -# -# Borland Delphi SDL_Mixer - Simple DirectMedia Layer Mixer Library -# Conversion of the Simple DirectMedia Layer Headers -# -# Portions created by Sam Lantinga are -# Copyright (C) 1997, 1998, 1999, 2000, 2001 Sam Lantinga -# 5635-34 Springhouse Dr. -# Pleasanton, CA 94588 (USA) -# -# All Rights Reserved. -# -# The original files are : SDL_mixer.h -# music_cmd.h -# wavestream.h -# timidity.h -# playmidi.h -# music_ogg.h -# mikmod.h -# -# The initial developer of this Pascal code was : -# Dominqiue Louis -# -# Portions created by Dominqiue Louis are -# Copyright (C) 2000 - 2001 Dominqiue Louis. -# -# -# Contributor(s) -# -------------- -# Matthias Thoma -# -# Obtained through: -# Joint Endeavour of Delphi Innovators ( Project JEDI ) -# -# You may retrieve the latest version of this file at the Project -# JEDI home page, located at http://delphi-jedi.org -# -# The contents of this file are used with permission, subject to -# the Mozilla Public License Version 1.1 (the "License"); you may -# not use this file except in compliance with the License. You may -# obtain a copy of the License at -# http://www.mozilla.org/MPL/MPL-1.1.html -# -# Software distributed under the License is distributed on an -# "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# Description -# ----------- -# -# -# -# -# -# -# -# Requires -# -------- -# SDL.pas & SMPEG.pas somewhere within your search path. -# -# Programming Notes -# ----------------- -# See the Aliens Demo to see how this library is used -# -# Revision History -# ---------------- -# April 02 2001 - DL : Initial Translation -# -# February 02 2002 - DL : Update to version 1.2.1 -# -# April 03 2003 - DL : Added jedi-sdl.inc include file to support more -# Pascal compilers. Initial support is now included -# for GnuPascal, VirtualPascal, TMT and obviously -# continue support for Delphi Kylix and FreePascal. -# -# April 24 2003 - DL : under instruction from Alexey Barkovoy, I have added -# better TMT Pascal support and under instruction -# from Prof. Abimbola Olowofoyeku (The African Chief), -# I have added better Gnu Pascal support -# -# April 30 2003 - DL : under instruction from David Mears AKA -# Jason Siletto, I have added FPC Linux support. -# This was compiled with fpc 1.1, so remember to set -# include file path. ie. -Fi/usr/share/fpcsrc/rtl/* -# -# -# $Log: sdl_mixer.pas,v $ -# Revision 1.18 2007/05/29 21:31:44 savage -# Changes as suggested by Almindor for 64bit compatibility. -# -# Revision 1.17 2007/05/20 20:31:17 savage -# Initial Changes to Handle 64 Bits -# -# Revision 1.16 2006/12/02 00:16:17 savage -# Updated to latest version -# -# Revision 1.15 2005/04/10 11:48:33 savage -# Changes as suggested by Michalis, thanks. -# -# Revision 1.14 2005/02/24 20:20:07 savage -# Changed definition of MusicType and added GetMusicType function -# -# Revision 1.13 2005/01/05 01:47:09 savage -# Changed LibName to reflect what MacOS X should have. ie libSDL*-1.2.0.dylib respectively. -# -# Revision 1.12 2005/01/04 23:14:56 savage -# Changed LibName to reflect what most Linux distros will have. ie libSDL*-1.2.so.0 respectively. -# -# Revision 1.11 2005/01/01 02:05:19 savage -# Updated to v1.2.6 -# -# Revision 1.10 2004/09/12 21:45:17 savage -# Robert Reed spotted that Mix_SetMusicPosition was missing from the conversion, so this has now been added. -# -# Revision 1.9 2004/08/27 21:48:24 savage -# IFDEFed out Smpeg support on MacOS X -# -# Revision 1.8 2004/08/14 22:54:30 savage -# Updated so that Library name defines are correctly defined for MacOS X. -# -# Revision 1.7 2004/05/10 14:10:04 savage -# Initial MacOS X support. Fixed defines for MACOS ( Classic ) and DARWIN ( MacOS X ). -# -# Revision 1.6 2004/04/13 09:32:08 savage -# Changed Shared object names back to just the .so extension to avoid conflicts on various Linux/Unix distros. Therefore developers will need to create Symbolic links to the actual Share Objects if necessary. -# -# Revision 1.5 2004/04/01 20:53:23 savage -# Changed Linux Shared Object names so they reflect the Symbolic Links that are created when installing the RPMs from the SDL site. -# -# Revision 1.4 2004/03/31 22:20:02 savage -# Windows unit not used in this file, so it was removed to keep the code tidy. -# -# Revision 1.3 2004/03/31 10:05:08 savage -# Better defines for Endianness under FreePascal and Borland compilers. -# -# Revision 1.2 2004/03/30 20:23:28 savage -# Tidied up use of UNIX compiler directive. -# -# Revision 1.1 2004/02/14 23:35:42 savage -# version 1 of sdl_image, sdl_mixer and smpeg. -# -# -# -#****************************************************************************** - -import - sdl, smpeg - -when defined(windows): - const - MixerLibName = "SDL_mixer.dll" -elif defined(macosx): - const - MixerLibName = "libSDL_mixer-1.2.0.dylib" -else: - const - MixerLibName = "libSDL_mixer.so" -const - MAJOR_VERSION* = 1 - MINOR_VERSION* = 2 - PATCHLEVEL* = 7 # Backwards compatibility - - CHANNELS* = 8 # Good default values for a PC soundcard - DEFAULT_FREQUENCY* = 22050 - -when defined(IA32): - const - DEFAULT_FORMAT* = AUDIO_S16LSB -else: - const - DEFAULT_FORMAT* = AUDIO_S16MSB -const - DEFAULT_CHANNELS* = 2 - MAX_VOLUME* = 128 # Volume of a chunk - PATH_MAX* = 255 # mikmod.h constants - #* - # * Library version - # * - LIBMIKMOD_VERSION_MAJOR* = 3 - LIBMIKMOD_VERSION_MINOR* = 1 - LIBMIKMOD_REVISION* = 8 - LIBMIKMOD_VERSION* = ((LIBMIKMOD_VERSION_MAJOR shl 16) or - (LIBMIKMOD_VERSION_MINOR shl 8) or (LIBMIKMOD_REVISION)) - -type #music_cmd.h types - PMusicCMD* = ptr MusicCMD - MusicCMD*{.final.} = object #wavestream.h types - filename*: array[0..PATH_MAX - 1, char] - cmd*: array[0..PATH_MAX - 1, char] - pid*: TSYS_ThreadHandle - - PWAVStream* = ptr WAVStream - WAVStream*{.final.} = object #playmidi.h types - wavefp*: pointer - start*: int32 - stop*: int32 - cvt*: TAudioCVT - - PMidiEvent* = ptr MidiEvent - MidiEvent*{.final.} = object - time*: int32 - channel*: byte - typ*: byte - a*: byte - b*: byte - - PMidiSong* = ptr MidiSong - MidiSong*{.final.} = object #music_ogg.h types - samples*: int32 - events*: PMidiEvent - - POGG_Music* = ptr OGG_Music - OGG_Music*{.final.} = object # mikmod.h types - #* - # * Error codes - # * - playing*: int32 - volume*: int32 #vf: OggVorbis_File; - section*: int32 - cvt*: TAudioCVT - lenAvailable*: int32 - sndAvailable*: pointer - - ErrorEnum* = enum - MMERR_OPENING_FILE, MMERR_OUT_OF_MEMORY, MMERR_DYNAMIC_LINKING, - MMERR_SAMPLE_TOO_BIG, MMERR_OUT_OF_HANDLES, MMERR_UNKNOWN_WAVE_TYPE, - MMERR_LOADING_PATTERN, MMERR_LOADING_TRACK, MMERR_LOADING_HEADER, - MMERR_LOADING_SAMPLEINFO, MMERR_NOT_A_MODULE, MMERR_NOT_A_STREAM, - MMERR_MED_SYNTHSAMPLES, MMERR_ITPACK_INVALID_DATA, MMERR_DETECTING_DEVICE, - MMERR_INVALID_DEVICE, MMERR_INITIALIZING_MIXER, MMERR_OPENING_AUDIO, - MMERR_8BIT_ONLY, MMERR_16BIT_ONLY, MMERR_STEREO_ONLY, MMERR_ULAW, - MMERR_NON_BLOCK, MMERR_AF_AUDIO_PORT, MMERR_AIX_CONFIG_INIT, - MMERR_AIX_CONFIG_CONTROL, MMERR_AIX_CONFIG_START, MMERR_GUS_SETTINGS, - MMERR_GUS_RESET, MMERR_GUS_TIMER, MMERR_HP_SETSAMPLESIZE, MMERR_HP_SETSPEED, - MMERR_HP_CHANNELS, MMERR_HP_AUDIO_OUTPUT, MMERR_HP_AUDIO_DESC, - MMERR_HP_BUFFERSIZE, MMERR_OSS_SETFRAGMENT, MMERR_OSS_SETSAMPLESIZE, - MMERR_OSS_SETSTEREO, MMERR_OSS_SETSPEED, MMERR_SGI_SPEED, MMERR_SGI_16BIT, - MMERR_SGI_8BIT, MMERR_SGI_STEREO, MMERR_SGI_MONO, MMERR_SUN_INIT, - MMERR_OS2_MIXSETUP, MMERR_OS2_SEMAPHORE, MMERR_OS2_TIMER, MMERR_OS2_THREAD, - MMERR_DS_PRIORITY, MMERR_DS_BUFFER, MMERR_DS_FORMAT, MMERR_DS_NOTIFY, - MMERR_DS_EVENT, MMERR_DS_THREAD, MMERR_DS_UPDATE, MMERR_WINMM_HANDLE, - MMERR_WINMM_ALLOCATED, MMERR_WINMM_DEVICEID, MMERR_WINMM_FORMAT, - MMERR_WINMM_UNKNOWN, MMERR_MAC_SPEED, MMERR_MAC_START, MMERR_MAX - PMODULE* = ptr MODULE - MODULE*{.final.} = object - PUNIMOD* = ptr UNIMOD - UNIMOD* = MODULE #SDL_mixer.h types - # The internal format for an audio chunk - PChunk* = ptr Chunk - Chunk*{.final.} = object - allocated*: cint - abuf*: pointer - alen*: uint32 - volume*: byte # Per-sample volume, 0-128 - - Fading* = enum - MIX_NO_FADING, MIX_FADING_OUT, MIX_FADING_IN - MusicType* = enum - MUS_NONE, MUS_CMD, MUS_WAV, MUS_MOD, MUS_MID, MUS_OGG, MUS_MP3 - PMusic* = ptr Music - Music*{.final.} = object # The internal format for a music chunk interpreted via mikmod - mixtype*: MusicType # other fields are not aviable - # data : MusicUnion; - # fading : TMix_Fading; - # fade_volume : integer; - # fade_step : integer; - # fade_steps : integer; - # error : integer; - - MixFunction* = proc (udata, stream: pointer, length: cint): pointer{. - cdecl.} # This macro can be used to fill a version structure with the compile-time - # version of the SDL_mixer library. -{.deprecated: [TMusicCMD: MusicCMD, TWAVStream: WAVStream, TMidiEvent: MidiEvent, - TMidiSong: MidiSong, TOGG_Music: OGG_Music, TErrorEnum: ErrorEnum, - TMODULE: MODULE, TUNIMOD: UNIMOD, TChunk: Chunk, TFading: Fading, - TMusicType: MusicType, TMusic: Music, TMixFunction: MixFunction].} - -proc version*(x: var sdl.Version) - # This function gets the version of the dynamically linked SDL_mixer library. - # It should NOT be used to fill a version structure, instead you should use the - # SDL_MIXER_VERSION() macro. -proc linkedVersion*(): sdl.Pversion{.cdecl, importc: "Mix_Linked_Version", - dynlib: MixerLibName.} - # Open the mixer with a certain audio format -proc openAudio*(frequency: cint, format: uint16, channels: cint, - chunksize: cint): cint{.cdecl, importc: "Mix_OpenAudio", - dynlib: MixerLibName.} - # Dynamically change the number of channels managed by the mixer. - # If decreasing the number of channels, the upper channels are - # stopped. - # This function returns the new number of allocated channels. - # -proc allocateChannels*(numchannels: cint): cint{.cdecl, - importc: "Mix_AllocateChannels", dynlib: MixerLibName.} - # Find out what the actual audio device parameters are. - # This function returns 1 if the audio has been opened, 0 otherwise. - # -proc querySpec*(frequency: var cint, format: var uint16, channels: var cint): cint{. - cdecl, importc: "Mix_QuerySpec", dynlib: MixerLibName.} - # Load a wave file or a music (.mod .s3m .it .xm) file -proc loadWAV_RW*(src: PRWops, freesrc: cint): PChunk{.cdecl, - importc: "Mix_LoadWAV_RW", dynlib: MixerLibName.} -proc loadWAV*(filename: cstring): PChunk -proc loadMUS*(filename: cstring): PMusic{.cdecl, importc: "Mix_LoadMUS", - dynlib: MixerLibName.} - # Load a wave file of the mixer format from a memory buffer -proc quickLoadWAV*(mem: pointer): PChunk{.cdecl, - importc: "Mix_QuickLoad_WAV", dynlib: MixerLibName.} - # Free an audio chunk previously loaded -proc freeChunk*(chunk: PChunk){.cdecl, importc: "Mix_FreeChunk", - dynlib: MixerLibName.} -proc freeMusic*(music: PMusic){.cdecl, importc: "Mix_FreeMusic", - dynlib: MixerLibName.} - # Find out the music format of a mixer music, or the currently playing - # music, if 'music' is NULL. -proc getMusicType*(music: PMusic): MusicType{.cdecl, - importc: "Mix_GetMusicType", dynlib: MixerLibName.} - # Set a function that is called after all mixing is performed. - # This can be used to provide real-time visual display of the audio stream - # or add a custom mixer filter for the stream data. - # -proc setPostMix*(mixFunc: MixFunction, arg: pointer){.cdecl, - importc: "Mix_SetPostMix", dynlib: MixerLibName.} - # Add your own music player or additional mixer function. - # If 'mix_func' is NULL, the default music player is re-enabled. - # -proc hookMusic*(mixFunc: MixFunction, arg: pointer){.cdecl, - importc: "Mix_HookMusic", dynlib: MixerLibName.} - # Add your own callback when the music has finished playing. - # -proc hookMusicFinished*(musicFinished: pointer){.cdecl, - importc: "Mix_HookMusicFinished", dynlib: MixerLibName.} - # Get a pointer to the user data for the current music hook -proc getMusicHookData*(): pointer{.cdecl, importc: "Mix_GetMusicHookData", - dynlib: MixerLibName.} - #* Add your own callback when a channel has finished playing. NULL - # * to disable callback.* -type - ChannelFinished* = proc (channel: cint){.cdecl.} -{.deprecated: [TChannelFinished: ChannelFinished].} - -proc channelFinished*(channelFinished: ChannelFinished){.cdecl, - importc: "Mix_ChannelFinished", dynlib: MixerLibName.} -const - CHANNEL_POST* = - 2 - -type - TEffectFunc* = proc (chan: cint, stream: pointer, length: cint, - udata: pointer): pointer{.cdecl.} - TEffectDone* = proc (chan: cint, udata: pointer): pointer{.cdecl.} -proc registerEffect*(chan: cint, f: TEffectFunc, d: TEffectDone, - arg: pointer): cint{.cdecl, - importc: "Mix_RegisterEffect", dynlib: MixerLibName.} - -proc unregisterEffect*(channel: cint, f: TEffectFunc): cint{.cdecl, - importc: "Mix_UnregisterEffect", dynlib: MixerLibName.} - -proc unregisterAllEffects*(channel: cint): cint{.cdecl, - importc: "Mix_UnregisterAllEffects", dynlib: MixerLibName.} -const - EFFECTSMAXSPEED* = "MIX_EFFECTSMAXSPEED" - -proc setPanning*(channel: cint, left: byte, right: byte): cint{.cdecl, - importc: "Mix_SetPanning", dynlib: MixerLibName.} - -proc setPosition*(channel: cint, angle: int16, distance: byte): cint{.cdecl, - importc: "Mix_SetPosition", dynlib: MixerLibName.} - -proc setDistance*(channel: cint, distance: byte): cint{.cdecl, - importc: "Mix_SetDistance", dynlib: MixerLibName.} - -proc setReverseStereo*(channel: cint, flip: cint): cint{.cdecl, - importc: "Mix_SetReverseStereo", dynlib: MixerLibName.} - -proc reserveChannels*(num: cint): cint{.cdecl, importc: "Mix_ReserveChannels", - dynlib: MixerLibName.} - -proc groupChannel*(which: cint, tag: cint): cint{.cdecl, - importc: "Mix_GroupChannel", dynlib: MixerLibName.} -proc groupChannels*(`from`: cint, `to`: cint, tag: cint): cint{.cdecl, - importc: "Mix_GroupChannels", dynlib: MixerLibName.} -proc groupAvailable*(tag: cint): cint{.cdecl, importc: "Mix_GroupAvailable", - dynlib: MixerLibName.} -proc groupCount*(tag: cint): cint{.cdecl, importc: "Mix_GroupCount", - dynlib: MixerLibName.} -proc groupOldest*(tag: cint): cint{.cdecl, importc: "Mix_GroupOldest", - dynlib: MixerLibName.} -proc groupNewer*(tag: cint): cint{.cdecl, importc: "Mix_GroupNewer", - dynlib: MixerLibName.} -proc playChannelTimed*(channel: cint, chunk: PChunk, loops: cint, - ticks: cint): cint{.cdecl, - importc: "Mix_PlayChannelTimed", dynlib: MixerLibName.} -proc playChannel*(channel: cint, chunk: PChunk, loops: cint): cint -proc playMusic*(music: PMusic, loops: cint): cint{.cdecl, - importc: "Mix_PlayMusic", dynlib: MixerLibName.} -proc fadeInMusic*(music: PMusic, loops: cint, ms: cint): cint{.cdecl, - importc: "Mix_FadeInMusic", dynlib: MixerLibName.} -proc fadeInChannelTimed*(channel: cint, chunk: PChunk, loops: cint, - ms: cint, ticks: cint): cint{.cdecl, - importc: "Mix_FadeInChannelTimed", dynlib: MixerLibName.} -proc fadeInChannel*(channel: cint, chunk: PChunk, loops: cint, ms: cint): cint - -proc volume*(channel: cint, volume: cint): cint{.cdecl, importc: "Mix_Volume", - dynlib: MixerLibName.} -proc volumeChunk*(chunk: PChunk, volume: cint): cint{.cdecl, - importc: "Mix_VolumeChunk", dynlib: MixerLibName.} -proc volumeMusic*(volume: cint): cint{.cdecl, importc: "Mix_VolumeMusic", - dynlib: MixerLibName.} - -proc haltChannel*(channel: cint): cint{.cdecl, importc: "Mix_HaltChannel", - dynlib: MixerLibName.} -proc haltGroup*(tag: cint): cint{.cdecl, importc: "Mix_HaltGroup", - dynlib: MixerLibName.} -proc haltMusic*(): cint{.cdecl, importc: "Mix_HaltMusic", - dynlib: MixerLibName.} - # Change the expiration delay for a particular channel. - # The sample will stop playing after the 'ticks' milliseconds have elapsed, - # or remove the expiration if 'ticks' is -1 - # -proc expireChannel*(channel: cint, ticks: cint): cint{.cdecl, - importc: "Mix_ExpireChannel", dynlib: MixerLibName.} - # Halt a channel, fading it out progressively till it's silent - # The ms parameter indicates the number of milliseconds the fading - # will take. - # -proc fadeOutChannel*(which: cint, ms: cint): cint{.cdecl, - importc: "Mix_FadeOutChannel", dynlib: MixerLibName.} -proc fadeOutGroup*(tag: cint, ms: cint): cint{.cdecl, - importc: "Mix_FadeOutGroup", dynlib: MixerLibName.} -proc fadeOutMusic*(ms: cint): cint{.cdecl, importc: "Mix_FadeOutMusic", - dynlib: MixerLibName.} - # Query the fading status of a channel -proc fadingMusic*(): Fading{.cdecl, importc: "Mix_FadingMusic", - dynlib: MixerLibName.} -proc fadingChannel*(which: cint): Fading{.cdecl, - importc: "Mix_FadingChannel", dynlib: MixerLibName.} - -proc pause*(channel: cint){.cdecl, importc: "Mix_Pause", dynlib: MixerLibName.} -proc resume*(channel: cint){.cdecl, importc: "Mix_Resume", - dynlib: MixerLibName.} -proc paused*(channel: cint): cint{.cdecl, importc: "Mix_Paused", - dynlib: MixerLibName.} - -proc pauseMusic*(){.cdecl, importc: "Mix_PauseMusic", dynlib: MixerLibName.} -proc resumeMusic*(){.cdecl, importc: "Mix_ResumeMusic", dynlib: MixerLibName.} -proc rewindMusic*(){.cdecl, importc: "Mix_RewindMusic", dynlib: MixerLibName.} -proc pausedMusic*(): cint{.cdecl, importc: "Mix_PausedMusic", - dynlib: MixerLibName.} - -proc setMusicPosition*(position: float64): cint{.cdecl, - importc: "Mix_SetMusicPosition", dynlib: MixerLibName.} - -proc playing*(channel: cint): cint{.cdecl, importc: "Mix_Playing", - dynlib: MixerLibName.} -proc playingMusic*(): cint{.cdecl, importc: "Mix_PlayingMusic", - dynlib: MixerLibName.} - -proc setMusicCMD*(command: cstring): cint{.cdecl, importc: "Mix_SetMusicCMD", - dynlib: MixerLibName.} - -proc setSynchroValue*(value: cint): cint{.cdecl, - importc: "Mix_SetSynchroValue", dynlib: MixerLibName.} -proc getSynchroValue*(): cint{.cdecl, importc: "Mix_GetSynchroValue", - dynlib: MixerLibName.} - -proc getChunk*(channel: cint): PChunk{.cdecl, importc: "Mix_GetChunk", - dynlib: MixerLibName.} - -proc closeAudio*(){.cdecl, importc: "Mix_CloseAudio", dynlib: MixerLibName.} - -proc version(x: var sdl.Version) = - x.major = MAJOR_VERSION - x.minor = MINOR_VERSION - x.patch = PATCHLEVEL - -proc loadWAV(filename: cstring): PChunk = - result = loadWAV_RW(rWFromFile(filename, "rb"), 1) - -proc playChannel(channel: cint, chunk: PChunk, loops: cint): cint = - result = playChannelTimed(channel, chunk, loops, - 1) - -proc fadeInChannel(channel: cint, chunk: PChunk, loops: cint, ms: cint): cint = - result = fadeInChannelTimed(channel, chunk, loops, ms, - 1) - diff --git a/lib/wrappers/sdl/sdl_mixer_nosmpeg.nim b/lib/wrappers/sdl/sdl_mixer_nosmpeg.nim deleted file mode 100644 index 670cf1643..000000000 --- a/lib/wrappers/sdl/sdl_mixer_nosmpeg.nim +++ /dev/null @@ -1,357 +0,0 @@ -#****************************************************************************** -# Copy of SDL_Mixer without smpeg dependency and mp3 support -#****************************************************************************** - -import - sdl - -when defined(windows): - const - MixerLibName = "SDL_mixer.dll" -elif defined(macosx): - const - MixerLibName = "libSDL_mixer-1.2.0.dylib" -else: - const - MixerLibName = "libSDL_mixer.so" -const - MAJOR_VERSION* = 1 - MINOR_VERSION* = 2 - PATCHLEVEL* = 7 # Backwards compatibility - - CHANNELS* = 8 # Good default values for a PC soundcard - DEFAULT_FREQUENCY* = 22050 - -when defined(IA32): - const - DEFAULT_FORMAT* = AUDIO_S16LSB -else: - const - DEFAULT_FORMAT* = AUDIO_S16MSB -const - DEFAULT_CHANNELS* = 2 - MAX_VOLUME* = 128 # Volume of a chunk - PATH_MAX* = 255 - - LIBMIKMOD_VERSION_MAJOR* = 3 - LIBMIKMOD_VERSION_MINOR* = 1 - LIBMIKMOD_REVISION* = 8 - LIBMIKMOD_VERSION* = ((LIBMIKMOD_VERSION_MAJOR shl 16) or - (LIBMIKMOD_VERSION_MINOR shl 8) or (LIBMIKMOD_REVISION)) - -type #music_cmd.h types - PMusicCMD* = ptr MusicCMD - MusicCMD*{.final.} = object #wavestream.h types - filename*: array[0..PATH_MAX - 1, char] - cmd*: array[0..PATH_MAX - 1, char] - pid*: TSYS_ThreadHandle - - PWAVStream* = ptr WAVStream - WAVStream*{.final.} = object #playmidi.h types - wavefp*: pointer - start*: int32 - stop*: int32 - cvt*: TAudioCVT - - PMidiEvent* = ptr MidiEvent - MidiEvent*{.final.} = object - time*: int32 - channel*: byte - typ*: byte - a*: byte - b*: byte - - PMidiSong* = ptr MidiSong - MidiSong*{.final.} = object #music_ogg.h types - samples*: int32 - events*: PMidiEvent - - POGG_Music* = ptr OGG_Music - OGG_Music*{.final.} = object # mikmod.h types - #* - # * Error codes - # * - playing*: cint - volume*: cint #vf: OggVorbis_File; - section*: cint - cvt*: TAudioCVT - lenAvailable*: cint - sndAvailable*: pointer - - ErrorEnum* = enum - MMERR_OPENING_FILE, MMERR_OUT_OF_MEMORY, MMERR_DYNAMIC_LINKING, - MMERR_SAMPLE_TOO_BIG, MMERR_OUT_OF_HANDLES, MMERR_UNKNOWN_WAVE_TYPE, - MMERR_LOADING_PATTERN, MMERR_LOADING_TRACK, MMERR_LOADING_HEADER, - MMERR_LOADING_SAMPLEINFO, MMERR_NOT_A_MODULE, MMERR_NOT_A_STREAM, - MMERR_MED_SYNTHSAMPLES, MMERR_ITPACK_INVALID_DATA, MMERR_DETECTING_DEVICE, - MMERR_INVALID_DEVICE, MMERR_INITIALIZING_MIXER, MMERR_OPENING_AUDIO, - MMERR_8BIT_ONLY, MMERR_16BIT_ONLY, MMERR_STEREO_ONLY, MMERR_ULAW, - MMERR_NON_BLOCK, MMERR_AF_AUDIO_PORT, MMERR_AIX_CONFIG_INIT, - MMERR_AIX_CONFIG_CONTROL, MMERR_AIX_CONFIG_START, MMERR_GUS_SETTINGS, - MMERR_GUS_RESET, MMERR_GUS_TIMER, MMERR_HP_SETSAMPLESIZE, MMERR_HP_SETSPEED, - MMERR_HP_CHANNELS, MMERR_HP_AUDIO_OUTPUT, MMERR_HP_AUDIO_DESC, - MMERR_HP_BUFFERSIZE, MMERR_OSS_SETFRAGMENT, MMERR_OSS_SETSAMPLESIZE, - MMERR_OSS_SETSTEREO, MMERR_OSS_SETSPEED, MMERR_SGI_SPEED, MMERR_SGI_16BIT, - MMERR_SGI_8BIT, MMERR_SGI_STEREO, MMERR_SGI_MONO, MMERR_SUN_INIT, - MMERR_OS2_MIXSETUP, MMERR_OS2_SEMAPHORE, MMERR_OS2_TIMER, MMERR_OS2_THREAD, - MMERR_DS_PRIORITY, MMERR_DS_BUFFER, MMERR_DS_FORMAT, MMERR_DS_NOTIFY, - MMERR_DS_EVENT, MMERR_DS_THREAD, MMERR_DS_UPDATE, MMERR_WINMM_HANDLE, - MMERR_WINMM_ALLOCATED, MMERR_WINMM_DEVICEID, MMERR_WINMM_FORMAT, - MMERR_WINMM_UNKNOWN, MMERR_MAC_SPEED, MMERR_MAC_START, MMERR_MAX - PMODULE* = ptr MODULE - MODULE*{.final.} = object - PUNIMOD* = ptr UNIMOD - UNIMOD* = MODULE #SDL_mixer.h types - # The internal format for an audio chunk - PChunk* = ptr Chunk - Chunk*{.final.} = object - allocated*: cint - abuf*: pointer - alen*: uint32 - volume*: byte # Per-sample volume, 0-128 - - Fading* = enum - MIX_NO_FADING, MIX_FADING_OUT, MIX_FADING_IN - MusicType* = enum - MUS_NONE, MUS_CMD, MUS_WAV, MUS_MOD, MUS_MID, MUS_OGG - PMusic* = ptr Music - Music*{.final.} = object - typ*: MusicType - - MixFunction* = proc (udata, stream: pointer, length: cint): pointer{. - cdecl.} # This macro can be used to fill a version structure with the compile-time - # version of the SDL_mixer library. -{.deprecated: [TMusicCMD: MusicCMD, TWAVStream: WAVStream, TMidiEvent: MidiEvent, - TMidiSong: MidiSong, TOGG_Music: OGG_Music, TErrorEnum: ErrorEnum, - TMODULE: MODULE, TUNIMOD: UNIMOD, TChunk: Chunk, TFading: Fading, - TMusicType: MusicType, TMusic: Music, TMixFunction: MixFunction].} - - -proc version*(x: var sdl.Version) - # This function gets the version of the dynamically linked SDL_mixer library. - # It should NOT be used to fill a version structure, instead you should use the - # SDL_MIXER_VERSION() macro. -proc linkedVersion*(): sdl.Pversion{.cdecl, importc: "Mix_Linked_Version", - dynlib: MixerLibName.} - # Open the mixer with a certain audio format -proc openAudio*(frequency: cint, format: uint16, channels: cint, - chunksize: cint): cint{.cdecl, importc: "Mix_OpenAudio", - dynlib: MixerLibName.} - # Dynamically change the number of channels managed by the mixer. - # If decreasing the number of channels, the upper channels are - # stopped. - # This function returns the new number of allocated channels. - # -proc allocateChannels*(numchannels: cint): cint{.cdecl, - importc: "Mix_AllocateChannels", dynlib: MixerLibName.} - # Find out what the actual audio device parameters are. - # This function returns 1 if the audio has been opened, 0 otherwise. - # -proc querySpec*(frequency: var cint, format: var uint16, channels: var cint): cint{. - cdecl, importc: "Mix_QuerySpec", dynlib: MixerLibName.} - # Load a wave file or a music (.mod .s3m .it .xm) file -proc LoadWAV_RW*(src: PRWops, freesrc: cint): PChunk{.cdecl, - importc: "Mix_LoadWAV_RW", dynlib: MixerLibName.} -proc loadWAV*(filename: cstring): PChunk -proc loadMUS*(filename: cstring): PMusic{.cdecl, importc: "Mix_LoadMUS", - dynlib: MixerLibName.} - # Load a wave file of the mixer format from a memory buffer -proc quickLoadWAV*(mem: pointer): PChunk{.cdecl, - importc: "Mix_QuickLoad_WAV", dynlib: MixerLibName.} - # Free an audio chunk previously loaded -proc freeChunk*(chunk: PChunk){.cdecl, importc: "Mix_FreeChunk", - dynlib: MixerLibName.} -proc freeMusic*(music: PMusic){.cdecl, importc: "Mix_FreeMusic", - dynlib: MixerLibName.} - # Find out the music format of a mixer music, or the currently playing - # music, if 'music' is NULL. -proc getMusicType*(music: PMusic): MusicType{.cdecl, - importc: "Mix_GetMusicType", dynlib: MixerLibName.} - # Set a function that is called after all mixing is performed. - # This can be used to provide real-time visual display of the audio stream - # or add a custom mixer filter for the stream data. - # -proc setPostMix*(mixfunc: MixFunction, arg: pointer){.cdecl, - importc: "Mix_SetPostMix", dynlib: MixerLibName.} - # Add your own music player or additional mixer function. - # If 'mix_func' is NULL, the default music player is re-enabled. - # -proc hookMusic*(mixFunc: MixFunction, arg: pointer){.cdecl, - importc: "Mix_HookMusic", dynlib: MixerLibName.} - # Add your own callback when the music has finished playing. - # -proc hookMusicFinished*(musicFinished: pointer){.cdecl, - importc: "Mix_HookMusicFinished", dynlib: MixerLibName.} - # Get a pointer to the user data for the current music hook -proc getMusicHookData*(): pointer{.cdecl, importc: "Mix_GetMusicHookData", - dynlib: MixerLibName.} - #* Add your own callback when a channel has finished playing. NULL - # * to disable callback.* -type - ChannelFinished* = proc (channel: cint){.cdecl.} -{.deprecated: [TChannelFinished: ChannelFinished].} - -proc channelFinished*(channelFinished: ChannelFinished){.cdecl, - importc: "Mix_ChannelFinished", dynlib: MixerLibName.} -const - CHANNEL_POST* = - 2 - -type - TEffectFunc* = proc (chan: cint, stream: pointer, length: cint, - udata: pointer): pointer{.cdecl.} - TEffectDone* = proc (chan: cint, udata: pointer): pointer{.cdecl.} - -proc registerEffect*(chan: cint, f: TEffectFunc, d: TEffectDone, - arg: pointer): cint{.cdecl, - importc: "Mix_RegisterEffect", dynlib: MixerLibName.} - -proc unregisterEffect*(channel: cint, f: TEffectFunc): cint{.cdecl, - importc: "Mix_UnregisterEffect", dynlib: MixerLibName.} - -proc unregisterAllEffects*(channel: cint): cint{.cdecl, - importc: "Mix_UnregisterAllEffects", dynlib: MixerLibName.} - -const - EFFECTSMAXSPEED* = "MIX_EFFECTSMAXSPEED" - -proc setPanning*(channel: cint, left: byte, right: byte): cint{.cdecl, - importc: "Mix_SetPanning", dynlib: MixerLibName.} - -proc setPosition*(channel: cint, angle: int16, distance: byte): cint{.cdecl, - importc: "Mix_SetPosition", dynlib: MixerLibName.} - -proc setDistance*(channel: cint, distance: byte): cint{.cdecl, - importc: "Mix_SetDistance", dynlib: MixerLibName.} - -proc setReverseStereo*(channel: cint, flip: cint): cint{.cdecl, - importc: "Mix_SetReverseStereo", dynlib: MixerLibName.} - -proc reserveChannels*(num: cint): cint{.cdecl, importc: "Mix_ReserveChannels", - dynlib: MixerLibName.} - -proc groupChannel*(which: cint, tag: cint): cint{.cdecl, - importc: "Mix_GroupChannel", dynlib: MixerLibName.} - # Assign several consecutive channels to a group -proc groupChannels*(`from`: cint, `to`: cint, tag: cint): cint{.cdecl, - importc: "Mix_GroupChannels", dynlib: MixerLibName.} - # Finds the first available channel in a group of channels -proc groupAvailable*(tag: cint): cint{.cdecl, importc: "Mix_GroupAvailable", - dynlib: MixerLibName.} - # Returns the number of channels in a group. This is also a subtle - # way to get the total number of channels when 'tag' is -1 - # -proc groupCount*(tag: cint): cint{.cdecl, importc: "Mix_GroupCount", - dynlib: MixerLibName.} - # Finds the "oldest" sample playing in a group of channels -proc groupOldest*(tag: cint): cint{.cdecl, importc: "Mix_GroupOldest", - dynlib: MixerLibName.} - # Finds the "most recent" (i.e. last) sample playing in a group of channels -proc groupNewer*(tag: cint): cint{.cdecl, importc: "Mix_GroupNewer", - dynlib: MixerLibName.} - # The same as above, but the sound is played at most 'ticks' milliseconds -proc playChannelTimed*(channel: cint, chunk: PChunk, loops: cint, - ticks: cint): cint{.cdecl, - importc: "Mix_PlayChannelTimed", dynlib: MixerLibName.} - -proc playChannel*(channel: cint, chunk: PChunk, loops: cint): cint -proc playMusic*(music: PMusic, loops: cint): cint{.cdecl, - importc: "Mix_PlayMusic", dynlib: MixerLibName.} - # Fade in music or a channel over "ms" milliseconds, same semantics as the "Play" functions -proc fadeInMusic*(music: PMusic, loops: cint, ms: cint): cint{.cdecl, - importc: "Mix_FadeInMusic", dynlib: MixerLibName.} -proc fadeInChannelTimed*(channel: cint, chunk: PChunk, loops: cint, - ms: cint, ticks: cint): cint{.cdecl, - importc: "Mix_FadeInChannelTimed", dynlib: MixerLibName.} -proc fadeInChannel*(channel: cint, chunk: PChunk, loops: cint, ms: cint): cint - # Set the volume in the range of 0-128 of a specific channel or chunk. - # If the specified channel is -1, set volume for all channels. - # Returns the original volume. - # If the specified volume is -1, just return the current volume. - # -proc volume*(channel: cint, volume: cint): cint{.cdecl, importc: "Mix_Volume", - dynlib: MixerLibName.} -proc volumeChunk*(chunk: PChunk, volume: cint): cint{.cdecl, - importc: "Mix_VolumeChunk", dynlib: MixerLibName.} -proc volumeMusic*(volume: cint): cint{.cdecl, importc: "Mix_VolumeMusic", - dynlib: MixerLibName.} - # Halt playing of a particular channel -proc haltChannel*(channel: cint): cint{.cdecl, importc: "Mix_HaltChannel", - dynlib: MixerLibName.} -proc haltGroup*(tag: cint): cint{.cdecl, importc: "Mix_HaltGroup", - dynlib: MixerLibName.} -proc haltMusic*(): cint{.cdecl, importc: "Mix_HaltMusic", - dynlib: MixerLibName.} - -proc expireChannel*(channel: cint, ticks: cint): cint{.cdecl, - importc: "Mix_ExpireChannel", dynlib: MixerLibName.} - -proc fadeOutChannel*(which: cint, ms: cint): cint{.cdecl, - importc: "Mix_FadeOutChannel", dynlib: MixerLibName.} -proc fadeOutGroup*(tag: cint, ms: cint): cint{.cdecl, - importc: "Mix_FadeOutGroup", dynlib: MixerLibName.} -proc fadeOutMusic*(ms: cint): cint{.cdecl, importc: "Mix_FadeOutMusic", - dynlib: MixerLibName.} - # Query the fading status of a channel -proc fadingMusic*(): Fading{.cdecl, importc: "Mix_FadingMusic", - dynlib: MixerLibName.} -proc fadingChannel*(which: cint): Fading{.cdecl, - importc: "Mix_FadingChannel", dynlib: MixerLibName.} - # Pause/Resume a particular channel -proc pause*(channel: cint){.cdecl, importc: "Mix_Pause", dynlib: MixerLibName.} -proc resume*(channel: cint){.cdecl, importc: "Mix_Resume", - dynlib: MixerLibName.} -proc paused*(channel: cint): cint{.cdecl, importc: "Mix_Paused", - dynlib: MixerLibName.} - # Pause/Resume the music stream -proc pauseMusic*(){.cdecl, importc: "Mix_PauseMusic", dynlib: MixerLibName.} -proc resumeMusic*(){.cdecl, importc: "Mix_ResumeMusic", dynlib: MixerLibName.} -proc rewindMusic*(){.cdecl, importc: "Mix_RewindMusic", dynlib: MixerLibName.} -proc pausedMusic*(): cint{.cdecl, importc: "Mix_PausedMusic", - dynlib: MixerLibName.} - # Set the current position in the music stream. - # This returns 0 if successful, or -1 if it failed or isn't implemented. - # This function is only implemented for MOD music formats (set pattern - # order number) and for OGG music (set position in seconds), at the - # moment. - # -proc setMusicPosition*(position: float64): cint{.cdecl, - importc: "Mix_SetMusicPosition", dynlib: MixerLibName.} - # Check the status of a specific channel. - # If the specified channel is -1, check all channels. - # -proc playing*(channel: cint): cint{.cdecl, importc: "Mix_Playing", - dynlib: MixerLibName.} -proc playingMusic*(): cint{.cdecl, importc: "Mix_PlayingMusic", - dynlib: MixerLibName.} - # Stop music and set external music playback command -proc setMusicCMD*(command: cstring): cint{.cdecl, importc: "Mix_SetMusicCMD", - dynlib: MixerLibName.} - # Synchro value is set by MikMod from modules while playing -proc setSynchroValue*(value: cint): cint{.cdecl, - importc: "Mix_SetSynchroValue", dynlib: MixerLibName.} -proc getSynchroValue*(): cint{.cdecl, importc: "Mix_GetSynchroValue", - dynlib: MixerLibName.} - # - # Get the Mix_Chunk currently associated with a mixer channel - # Returns nil if it's an invalid channel, or there's no chunk associated. - # -proc getChunk*(channel: cint): PChunk{.cdecl, importc: "Mix_GetChunk", - dynlib: MixerLibName.} - # Close the mixer, halting all playing audio -proc closeAudio*(){.cdecl, importc: "Mix_CloseAudio", dynlib: MixerLibName.} - # We'll use SDL for reporting errors - -proc version(x: var Version) = - x.major = MAJOR_VERSION - x.minor = MINOR_VERSION - x.patch = PATCHLEVEL - -proc loadWAV(filename: cstring): PChunk = - result = LoadWAV_RW(rWFromFile(filename, "rb"), 1) - -proc playChannel(channel: cint, chunk: PChunk, loops: cint): cint = - result = playChannelTimed(channel, chunk, loops, - 1) - -proc fadeInChannel(channel: cint, chunk: PChunk, loops: cint, ms: cint): cint = - result = fadeInChannelTimed(channel, chunk, loops, ms, - 1) - diff --git a/lib/wrappers/sdl/sdl_net.nim b/lib/wrappers/sdl/sdl_net.nim deleted file mode 100644 index 5bde607f7..000000000 --- a/lib/wrappers/sdl/sdl_net.nim +++ /dev/null @@ -1,428 +0,0 @@ -#****************************************************************************** -# -# $Id: sdl_net.pas,v 1.7 2005/01/01 02:14:21 savage Exp $ -# -# -# -# Borland Delphi SDL_Net - A x-platform network library for use with SDL. -# Conversion of the Simple DirectMedia Layer Network Headers -# -# Portions created by Sam Lantinga are -# Copyright (C) 1997, 1998, 1999, 2000, 2001 Sam Lantinga -# 5635-34 Springhouse Dr. -# Pleasanton, CA 94588 (USA) -# -# All Rights Reserved. -# -# The original files are : SDL_net.h -# -# The initial developer of this Pascal code was : -# Dominqiue Louis -# -# Portions created by Dominqiue Louis are -# Copyright (C) 2000 - 2001 Dominqiue Louis. -# -# -# Contributor(s) -# -------------- -# Matthias Thoma -# -# Obtained through: -# Joint Endeavour of Delphi Innovators ( Project JEDI ) -# -# You may retrieve the latest version of this file at the Project -# JEDI home page, located at http://delphi-jedi.org -# -# The contents of this file are used with permission, subject to -# the Mozilla Public License Version 1.1 (the "License"); you may -# not use this file except in compliance with the License. You may -# obtain a copy of the License at -# http://www.mozilla.org/MPL/MPL-1.1.html -# -# Software distributed under the License is distributed on an -# "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# Description -# ----------- -# -# -# -# -# -# -# -# Requires -# -------- -# SDL.pas somehere in your search path -# -# Programming Notes -# ----------------- -# -# -# -# -# Revision History -# ---------------- -# April 09 2001 - DL : Initial Translation -# -# April 03 2003 - DL : Added jedi-sdl.inc include file to support more -# Pascal compilers. Initial support is now included -# for GnuPascal, VirtualPascal, TMT and obviously -# continue support for Delphi Kylix and FreePascal. -# -# April 24 2003 - DL : under instruction from Alexey Barkovoy, I have added -# better TMT Pascal support and under instruction -# from Prof. Abimbola Olowofoyeku (The African Chief), -# I have added better Gnu Pascal support -# -# April 30 2003 - DL : under instruction from David Mears AKA -# Jason Siletto, I have added FPC Linux support. -# This was compiled with fpc 1.1, so remember to set -# include file path. ie. -Fi/usr/share/fpcsrc/rtl/* -# -# -# $Log: sdl_net.pas,v $ -# Revision 1.7 2005/01/01 02:14:21 savage -# Updated to v1.2.5 -# -# Revision 1.6 2004/08/14 22:54:30 savage -# Updated so that Library name defines are correctly defined for MacOS X. -# -# Revision 1.5 2004/05/10 14:10:04 savage -# Initial MacOS X support. Fixed defines for MACOS ( Classic ) and DARWIN ( MacOS X ). -# -# Revision 1.4 2004/04/13 09:32:08 savage -# Changed Shared object names back to just the .so extension to avoid conflicts on various Linux/Unix distros. Therefore developers will need to create Symbolic links to the actual Share Objects if necessary. -# -# Revision 1.3 2004/04/01 20:53:23 savage -# Changed Linux Shared Object names so they reflect the Symbolic Links that are created when installing the RPMs from the SDL site. -# -# Revision 1.2 2004/03/30 20:23:28 savage -# Tidied up use of UNIX compiler directive. -# -# Revision 1.1 2004/02/16 22:16:40 savage -# v1.0 changes -# -# -# -#****************************************************************************** - -import - sdl - -when defined(windows): - const - NetLibName = "SDL_net.dll" -elif defined(macosx): - const - NetLibName = "libSDL_net.dylib" -else: - const - NetLibName = "libSDL_net.so" -const #* Printable format: "%d.%d.%d", MAJOR, MINOR, PATCHLEVEL * - MAJOR_VERSION* = 1 - MINOR_VERSION* = 2 - PATCHLEVEL* = 5 # SDL_Net.h constants - #* Resolve a host name and port to an IP address in network form. - # If the function succeeds, it will return 0. - # If the host couldn't be resolved, the host portion of the returned - # address will be INADDR_NONE, and the function will return -1. - # If 'host' is NULL, the resolved host will be set to INADDR_ANY. - # * - INADDR_ANY* = 0x00000000 - INADDR_NONE* = 0xFFFFFFFF #*********************************************************************** - #* UDP network API * - #*********************************************************************** - #* The maximum channels on a a UDP socket * - MAX_UDPCHANNELS* = 32 #* The maximum addresses bound to a single UDP socket channel * - MAX_UDPADDRESSES* = 4 - -type # SDL_net.h types - #*********************************************************************** - #* IPv4 hostname resolution API * - #*********************************************************************** - PIPAddress* = ptr IPAddress - IPAddress*{.final.} = object #* TCP network API - host*: uint32 # 32-bit IPv4 host address */ - port*: uint16 # 16-bit protocol port */ - - PTCPSocket* = ptr TCPSocket - TCPSocket*{.final.} = object # UDP network API - ready*: int - channel*: int - remoteAddress*: IPAddress - localAddress*: IPAddress - sflag*: int - - PUDP_Channel* = ptr UDP_Channel - UDP_Channel*{.final.} = object - numbound*: int - address*: array[0..MAX_UDPADDRESSES - 1, IPAddress] - - PUDPSocket* = ptr UDPSocket - UDPSocket*{.final.} = object - ready*: int - channel*: int - address*: IPAddress - binding*: array[0..MAX_UDPCHANNELS - 1, UDP_Channel] - - PUDPpacket* = ptr UDPpacket - PPUDPpacket* = ptr PUDPpacket - UDPpacket*{.final.} = object #*********************************************************************** - #* Hooks for checking sockets for available data * - #*********************************************************************** - channel*: int #* The src/dst channel of the packet * - data*: pointer #* The packet data * - length*: int #* The length of the packet data * - maxlen*: int #* The size of the data buffer * - status*: int #* packet status after sending * - address*: IPAddress #* The source/dest address of an incoming/outgoing packet * - - PSocket* = ptr Socket - Socket*{.final.} = object - ready*: int - channel*: int - - PSocketSet* = ptr SocketSet - SocketSet*{.final.} = object # Any network socket can be safely cast to this socket type * - numsockets*: int - maxsockets*: int - sockets*: PSocket - - PGenericSocket* = ptr GenericSocket - GenericSocket*{.final.} = object - ready*: int -{.deprecated: [TSocket: Socket, TSocketSet: SocketSet, TIPAddress: IpAddress, - TTCPSocket: TCPSocket, TUDP_Channel: UDP_Channel, TUDPSocket: UDPSocket, - TUDPpacket: UDPpacket, TGenericSocket: GenericSocket].} - -proc version*(x: var Version) - #* Initialize/Cleanup the network API - # SDL must be initialized before calls to functions in this library, - # because this library uses utility functions from the SDL library. - #* -proc init*(): int{.cdecl, importc: "SDLNet_Init", dynlib: NetLibName.} -proc quit*(){.cdecl, importc: "SDLNet_Quit", dynlib: NetLibName.} - #* Resolve a host name and port to an IP address in network form. - # If the function succeeds, it will return 0. - # If the host couldn't be resolved, the host portion of the returned - # address will be INADDR_NONE, and the function will return -1. - # If 'host' is NULL, the resolved host will be set to INADDR_ANY. - # * -proc resolveHost*(address: var IPAddress, host: cstring, port: uint16): int{. - cdecl, importc: "SDLNet_ResolveHost", dynlib: NetLibName.} - #* Resolve an ip address to a host name in canonical form. - # If the ip couldn't be resolved, this function returns NULL, - # otherwise a pointer to a static buffer containing the hostname - # is returned. Note that this function is not thread-safe. - #* -proc resolveIP*(ip: var IPAddress): cstring{.cdecl, - importc: "SDLNet_ResolveIP", dynlib: NetLibName.} - #*********************************************************************** - #* TCP network API * - #*********************************************************************** - #* Open a TCP network socket - # If ip.host is INADDR_NONE, this creates a local server socket on the - # given port, otherwise a TCP connection to the remote host and port is - # attempted. The address passed in should already be swapped to network - # byte order (addresses returned from SDLNet_ResolveHost() are already - # in the correct form). - # The newly created socket is returned, or NULL if there was an error. - #* -proc tcpOpen*(ip: var IPAddress): PTCPSocket{.cdecl, - importc: "SDLNet_TCP_Open", dynlib: NetLibName.} - #* Accept an incoming connection on the given server socket. - # The newly created socket is returned, or NULL if there was an error. - #* -proc tcpAccept*(server: PTCPSocket): PTCPSocket{.cdecl, - importc: "SDLNet_TCP_Accept", dynlib: NetLibName.} - #* Get the IP address of the remote system associated with the socket. - # If the socket is a server socket, this function returns NULL. - #* -proc tcpGetPeerAddress*(sock: PTCPSocket): PIPAddress{.cdecl, - importc: "SDLNet_TCP_GetPeerAddress", dynlib: NetLibName.} - #* Send 'len' bytes of 'data' over the non-server socket 'sock' - # This function returns the actual amount of data sent. If the return value - # is less than the amount of data sent, then either the remote connection was - # closed, or an unknown socket error occurred. - #* -proc tcpSend*(sock: PTCPSocket, data: pointer, length: int): int{.cdecl, - importc: "SDLNet_TCP_Send", dynlib: NetLibName.} - #* Receive up to 'maxlen' bytes of data over the non-server socket 'sock', - # and store them in the buffer pointed to by 'data'. - # This function returns the actual amount of data received. If the return - # value is less than or equal to zero, then either the remote connection was - # closed, or an unknown socket error occurred. - #* -proc tcpRecv*(sock: PTCPSocket, data: pointer, maxlen: int): int{.cdecl, - importc: "SDLNet_TCP_Recv", dynlib: NetLibName.} - #* Close a TCP network socket * -proc tcpClose*(sock: PTCPSocket){.cdecl, importc: "SDLNet_TCP_Close", - dynlib: NetLibName.} - #*********************************************************************** - #* UDP network API * - #*********************************************************************** - #* Allocate/resize/free a single UDP packet 'size' bytes long. - # The new packet is returned, or NULL if the function ran out of memory. - # * -proc allocPacket*(size: int): PUDPpacket{.cdecl, - importc: "SDLNet_AllocPacket", dynlib: NetLibName.} -proc resizePacket*(packet: PUDPpacket, newsize: int): int{.cdecl, - importc: "SDLNet_ResizePacket", dynlib: NetLibName.} -proc freePacket*(packet: PUDPpacket){.cdecl, importc: "SDLNet_FreePacket", - dynlib: NetLibName.} - #* Allocate/Free a UDP packet vector (array of packets) of 'howmany' packets, - # each 'size' bytes long. - # A pointer to the first packet in the array is returned, or NULL if the - # function ran out of memory. - # * -proc allocPacketV*(howmany: int, size: int): PUDPpacket{.cdecl, - importc: "SDLNet_AllocPacketV", dynlib: NetLibName.} -proc freePacketV*(packetV: PUDPpacket){.cdecl, - importc: "SDLNet_FreePacketV", dynlib: NetLibName.} - #* Open a UDP network socket - # If 'port' is non-zero, the UDP socket is bound to a local port. - # This allows other systems to send to this socket via a known port. - #* -proc udpOpen*(port: uint16): PUDPSocket{.cdecl, importc: "SDLNet_UDP_Open", - dynlib: NetLibName.} - #* Bind the address 'address' to the requested channel on the UDP socket. - # If the channel is -1, then the first unbound channel will be bound with - # the given address as it's primary address. - # If the channel is already bound, this new address will be added to the - # list of valid source addresses for packets arriving on the channel. - # If the channel is not already bound, then the address becomes the primary - # address, to which all outbound packets on the channel are sent. - # This function returns the channel which was bound, or -1 on error. - #* -proc udpBind*(sock: PUDPSocket, channel: int, address: var IPAddress): int{. - cdecl, importc: "SDLNet_UDP_Bind", dynlib: NetLibName.} - #* Unbind all addresses from the given channel * -proc udpUnbind*(sock: PUDPSocket, channel: int){.cdecl, - importc: "SDLNet_UDP_Unbind", dynlib: NetLibName.} - #* Get the primary IP address of the remote system associated with the - # socket and channel. If the channel is -1, then the primary IP port - # of the UDP socket is returned -- this is only meaningful for sockets - # opened with a specific port. - # If the channel is not bound and not -1, this function returns NULL. - # * -proc udpGetPeerAddress*(sock: PUDPSocket, channel: int): PIPAddress{.cdecl, - importc: "SDLNet_UDP_GetPeerAddress", dynlib: NetLibName.} - #* Send a vector of packets to the the channels specified within the packet. - # If the channel specified in the packet is -1, the packet will be sent to - # the address in the 'src' member of the packet. - # Each packet will be updated with the status of the packet after it has - # been sent, -1 if the packet send failed. - # This function returns the number of packets sent. - #* -proc udpSendV*(sock: PUDPSocket, packets: PPUDPpacket, npackets: int): int{. - cdecl, importc: "SDLNet_UDP_SendV", dynlib: NetLibName.} - #* Send a single packet to the specified channel. - # If the channel specified in the packet is -1, the packet will be sent to - # the address in the 'src' member of the packet. - # The packet will be updated with the status of the packet after it has - # been sent. - # This function returns 1 if the packet was sent, or 0 on error. - #* -proc udpSend*(sock: PUDPSocket, channel: int, packet: PUDPpacket): int{. - cdecl, importc: "SDLNet_UDP_Send", dynlib: NetLibName.} - #* Receive a vector of pending packets from the UDP socket. - # The returned packets contain the source address and the channel they arrived - # on. If they did not arrive on a bound channel, the the channel will be set - # to -1. - # The channels are checked in highest to lowest order, so if an address is - # bound to multiple channels, the highest channel with the source address - # bound will be returned. - # This function returns the number of packets read from the network, or -1 - # on error. This function does not block, so can return 0 packets pending. - #* -proc udpRecvV*(sock: PUDPSocket, packets: PPUDPpacket): int{.cdecl, - importc: "SDLNet_UDP_RecvV", dynlib: NetLibName.} - #* Receive a single packet from the UDP socket. - # The returned packet contains the source address and the channel it arrived - # on. If it did not arrive on a bound channel, the the channel will be set - # to -1. - # The channels are checked in highest to lowest order, so if an address is - # bound to multiple channels, the highest channel with the source address - # bound will be returned. - # This function returns the number of packets read from the network, or -1 - # on error. This function does not block, so can return 0 packets pending. - #* -proc udpRecv*(sock: PUDPSocket, packet: PUDPpacket): int{.cdecl, - importc: "SDLNet_UDP_Recv", dynlib: NetLibName.} - #* Close a UDP network socket * -proc udpClose*(sock: PUDPSocket){.cdecl, importc: "SDLNet_UDP_Close", - dynlib: NetLibName.} - #*********************************************************************** - #* Hooks for checking sockets for available data * - #*********************************************************************** - #* Allocate a socket set for use with SDLNet_CheckSockets() - # This returns a socket set for up to 'maxsockets' sockets, or NULL if - # the function ran out of memory. - # * -proc allocSocketSet*(maxsockets: int): PSocketSet{.cdecl, - importc: "SDLNet_AllocSocketSet", dynlib: NetLibName.} - #* Add a socket to a set of sockets to be checked for available data * -proc addSocket*(theSet: PSocketSet, sock: PGenericSocket): int{. - cdecl, importc: "SDLNet_AddSocket", dynlib: NetLibName.} -proc tcpAddSocket*(theSet: PSocketSet, sock: PTCPSocket): int -proc udpAddSocket*(theSet: PSocketSet, sock: PUDPSocket): int - #* Remove a socket from a set of sockets to be checked for available data * -proc delSocket*(theSet: PSocketSet, sock: PGenericSocket): int{. - cdecl, importc: "SDLNet_DelSocket", dynlib: NetLibName.} -proc tcpDelSocket*(theSet: PSocketSet, sock: PTCPSocket): int - # SDLNet_DelSocket(set, (SDLNet_GenericSocket)sock) -proc udpDelSocket*(theSet: PSocketSet, sock: PUDPSocket): int - #SDLNet_DelSocket(set, (SDLNet_GenericSocket)sock) - #* This function checks to see if data is available for reading on the - # given set of sockets. If 'timeout' is 0, it performs a quick poll, - # otherwise the function returns when either data is available for - # reading, or the timeout in milliseconds has elapsed, which ever occurs - # first. This function returns the number of sockets ready for reading, - # or -1 if there was an error with the select() system call. - #* -proc checkSockets*(theSet: PSocketSet, timeout: int32): int{.cdecl, - importc: "SDLNet_CheckSockets", dynlib: NetLibName.} - #* After calling SDLNet_CheckSockets(), you can use this function on a - # socket that was in the socket set, to find out if data is available - # for reading. - #* -proc socketReady*(sock: PGenericSocket): bool - #* Free a set of sockets allocated by SDL_NetAllocSocketSet() * -proc freeSocketSet*(theSet: PSocketSet){.cdecl, - importc: "SDLNet_FreeSocketSet", dynlib: NetLibName.} - #*********************************************************************** - #* Platform-independent data conversion functions * - #*********************************************************************** - #* Write a 16/32 bit value to network packet buffer * -proc write16*(value: uint16, area: pointer){.cdecl, - importc: "SDLNet_Write16", dynlib: NetLibName.} -proc write32*(value: uint32, area: pointer){.cdecl, - importc: "SDLNet_Write32", dynlib: NetLibName.} - #* Read a 16/32 bit value from network packet buffer * -proc read16*(area: pointer): uint16{.cdecl, importc: "SDLNet_Read16", - dynlib: NetLibName.} -proc read32*(area: pointer): uint32{.cdecl, importc: "SDLNet_Read32", - dynlib: NetLibName.} - -proc version(x: var Version) = - x.major = MAJOR_VERSION - x.minor = MINOR_VERSION - x.patch = PATCHLEVEL - -proc tcpAddSocket(theSet: PSocketSet, sock: PTCPSocket): int = - result = addSocket(theSet, cast[PGenericSocket](sock)) - -proc udpAddSocket(theSet: PSocketSet, sock: PUDPSocket): int = - result = addSocket(theSet, cast[PGenericSocket](sock)) - -proc tcpDelSocket(theSet: PSocketSet, sock: PTCPSocket): int = - result = delSocket(theSet, cast[PGenericSocket](sock)) - -proc udpDelSocket(theSet: PSocketSet, sock: PUDPSocket): int = - result = delSocket(theSet, cast[PGenericSocket](sock)) - -proc socketReady(sock: PGenericSocket): bool = - result = sock != nil and sock.ready == 1 diff --git a/lib/wrappers/sdl/sdl_ttf.nim b/lib/wrappers/sdl/sdl_ttf.nim deleted file mode 100644 index 06604f96e..000000000 --- a/lib/wrappers/sdl/sdl_ttf.nim +++ /dev/null @@ -1,338 +0,0 @@ -# -# $Id: sdl_ttf.pas,v 1.18 2007/06/01 11:16:33 savage Exp $ -# -# -#****************************************************************************** -# -# JEDI-SDL : Pascal units for SDL - Simple DirectMedia Layer -# Conversion of the Simple DirectMedia Layer Headers -# -# Portions created by Sam Lantinga are -# Copyright (C) 1997, 1998, 1999, 2000, 2001 Sam Lantinga -# 5635-34 Springhouse Dr. -# Pleasanton, CA 94588 (USA) -# -# All Rights Reserved. -# -# The original files are : SDL_ttf.h -# -# The initial developer of this Pascal code was : -# Dominqiue Louis -# -# Portions created by Dominqiue Louis are -# Copyright (C) 2000 - 2001 Dominqiue Louis. -# -# -# Contributor(s) -# -------------- -# Tom Jones His Project inspired this conversion -# -# Obtained through: -# Joint Endeavour of Delphi Innovators ( Project JEDI ) -# -# You may retrieve the latest version of this file at the Project -# JEDI home page, located at http://delphi-jedi.org -# -# The contents of this file are used with permission, subject to -# the Mozilla Public License Version 1.1 (the "License"); you may -# not use this file except in compliance with the License. You may -# obtain a copy of the License at -# http://www.mozilla.org/MPL/MPL-1.1.html -# -# Software distributed under the License is distributed on an -# "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# Description -# ----------- -# -# -# -# -# -# -# -# Requires -# -------- -# The SDL Runtime libraris on Win32 : SDL.dll on Linux : libSDL.so -# They are available from... -# http://www.libsdl.org . -# -# Programming Notes -# ----------------- -# -# -# -# -# Revision History -# ---------------- -# December 08 2002 - DL : Fixed definition of TTF_RenderUnicode_Solid -# -# April 03 2003 - DL : Added jedi-sdl.inc include file to support more -# Pascal compilers. Initial support is now included -# for GnuPascal, VirtualPascal, TMT and obviously -# continue support for Delphi Kylix and FreePascal. -# -# April 24 2003 - DL : under instruction from Alexey Barkovoy, I have added -# better TMT Pascal support and under instruction -# from Prof. Abimbola Olowofoyeku (The African Chief), -# I have added better Gnu Pascal support -# -# April 30 2003 - DL : under instruction from David Mears AKA -# Jason Siletto, I have added FPC Linux support. -# This was compiled with fpc 1.1, so remember to set -# include file path. ie. -Fi/usr/share/fpcsrc/rtl/* -# -# -# $Log: sdl_ttf.pas,v $ -# Revision 1.18 2007/06/01 11:16:33 savage -# Added IFDEF UNIX for Workaround. -# -# Revision 1.17 2007/06/01 08:38:21 savage -# Added TTF_RenderText_Solid workaround as suggested by Michalis Kamburelis -# -# Revision 1.16 2007/05/29 21:32:14 savage -# Changes as suggested by Almindor for 64bit compatibility. -# -# Revision 1.15 2007/05/20 20:32:45 savage -# Initial Changes to Handle 64 Bits -# -# Revision 1.14 2006/12/02 00:19:01 savage -# Updated to latest version -# -# Revision 1.13 2005/04/10 11:48:33 savage -# Changes as suggested by Michalis, thanks. -# -# Revision 1.12 2005/01/05 01:47:14 savage -# Changed LibName to reflect what MacOS X should have. ie libSDL*-1.2.0.dylib respectively. -# -# Revision 1.11 2005/01/04 23:14:57 savage -# Changed LibName to reflect what most Linux distros will have. ie libSDL*-1.2.so.0 respectively. -# -# Revision 1.10 2005/01/02 19:07:32 savage -# Slight bug fix to use LongInt instead of Long ( Thanks Michalis Kamburelis ) -# -# Revision 1.9 2005/01/01 02:15:20 savage -# Updated to v2.0.7 -# -# Revision 1.8 2004/10/07 21:02:32 savage -# Fix for FPC -# -# Revision 1.7 2004/09/30 22:39:50 savage -# Added a true type font class which contains a wrap text function. -# Changed the sdl_ttf.pas header to reflect the future of jedi-sdl. -# -# Revision 1.6 2004/08/14 22:54:30 savage -# Updated so that Library name defines are correctly defined for MacOS X. -# -# Revision 1.5 2004/05/10 14:10:04 savage -# Initial MacOS X support. Fixed defines for MACOS ( Classic ) and DARWIN ( MacOS X ). -# -# Revision 1.4 2004/04/13 09:32:08 savage -# Changed Shared object names back to just the .so extension to avoid conflicts on various Linux/Unix distros. Therefore developers will need to create Symbolic links to the actual Share Objects if necessary. -# -# Revision 1.3 2004/04/01 20:53:24 savage -# Changed Linux Shared Object names so they reflect the Symbolic Links that are created when installing the RPMs from the SDL site. -# -# Revision 1.2 2004/03/30 20:23:28 savage -# Tidied up use of UNIX compiler directive. -# -# Revision 1.1 2004/02/16 22:16:40 savage -# v1.0 changes -# -# -# -#****************************************************************************** -# -# Define this to workaround a known bug in some freetype versions. -# The error manifests as TTF_RenderGlyph_Solid returning nil (error) -# and error message (in SDL_Error) is -# "Failed loading DPMSDisable: /usr/lib/libX11.so.6: undefined symbol: DPMSDisable" -# See [http://lists.libsdl.org/pipermail/sdl-libsdl.org/2007-March/060459.html] -# - -import - sdl - -when defined(windows): - const - ttfLibName = "SDL_ttf.dll" -elif defined(macosx): - const - ttfLibName = "libSDL_ttf-2.0.0.dylib" -else: - const - ttfLibName = "libSDL_ttf(|-2.0).so(|.1|.0)" -const - MAJOR_VERSION* = 2 - MINOR_VERSION* = 0 - PATCHLEVEL* = 8 # Backwards compatibility - - STYLE_NORMAL* = 0x00000000 - STYLE_BOLD* = 0x00000001 - STYLE_ITALIC* = 0x00000002 - STYLE_UNDERLINE* = 0x00000004 # ZERO WIDTH NO-BREAKSPACE (Unicode byte order mark) - UNICODE_BOM_NATIVE* = 0x0000FEFF - UNICODE_BOM_SWAPPED* = 0x0000FFFE - -type - PFont* = ptr Font - Font = object -{.deprecated: [TFont: Font].} - - -# This macro can be used to fill a version structure with the compile-time -# version of the SDL_ttf library. - -proc linkedVersion*(): sdl.Pversion{.cdecl, importc: "TTF_Linked_Version", - dynlib: ttfLibName.} - # This function tells the library whether UNICODE text is generally - # byteswapped. A UNICODE BOM character in a string will override - # this setting for the remainder of that string. - # -proc byteSwappedUNICODE*(swapped: cint){.cdecl, - importc: "TTF_ByteSwappedUNICODE", dynlib: ttfLibName.} - #returns 0 on succes, -1 if error occurs -proc init*(): cint{.cdecl, importc: "TTF_Init", dynlib: ttfLibName.} - # - # Open a font file and create a font of the specified point size. - # Some .fon fonts will have several sizes embedded in the file, so the - # point size becomes the index of choosing which size. If the value - # is too high, the last indexed size will be the default. - # -proc openFont*(filename: cstring, ptsize: cint): PFont{.cdecl, - importc: "TTF_OpenFont", dynlib: ttfLibName.} -proc openFontIndex*(filename: cstring, ptsize: cint, index: int32): PFont{. - cdecl, importc: "TTF_OpenFontIndex", dynlib: ttfLibName.} -proc openFontRW*(src: PRWops, freesrc: cint, ptsize: cint): PFont{.cdecl, - importc: "TTF_OpenFontRW", dynlib: ttfLibName.} -proc openFontIndexRW*(src: PRWops, freesrc: cint, ptsize: cint, index: int32): PFont{. - cdecl, importc: "TTF_OpenFontIndexRW", dynlib: ttfLibName.} -proc getFontStyle*(font: PFont): cint{.cdecl, - importc: "TTF_GetFontStyle", dynlib: ttfLibName.} -proc setFontStyle*(font: PFont, style: cint){.cdecl, - importc: "TTF_SetFontStyle", dynlib: ttfLibName.} - # Get the total height of the font - usually equal to point size -proc fontHeight*(font: PFont): cint{.cdecl, importc: "TTF_FontHeight", - dynlib: ttfLibName.} - # Get the offset from the baseline to the top of the font - # This is a positive value, relative to the baseline. - # -proc fontAscent*(font: PFont): cint{.cdecl, importc: "TTF_FontAscent", - dynlib: ttfLibName.} - # Get the offset from the baseline to the bottom of the font - # This is a negative value, relative to the baseline. - # -proc fontDescent*(font: PFont): cint{.cdecl, importc: "TTF_FontDescent", - dynlib: ttfLibName.} - # Get the recommended spacing between lines of text for this font -proc fontLineSkip*(font: PFont): cint{.cdecl, - importc: "TTF_FontLineSkip", dynlib: ttfLibName.} - # Get the number of faces of the font -proc fontFaces*(font: PFont): int32{.cdecl, importc: "TTF_FontFaces", - dynlib: ttfLibName.} - # Get the font face attributes, if any -proc fontFaceIsFixedWidth*(font: PFont): cint{.cdecl, - importc: "TTF_FontFaceIsFixedWidth", dynlib: ttfLibName.} -proc fontFaceFamilyName*(font: PFont): cstring{.cdecl, - importc: "TTF_FontFaceFamilyName", dynlib: ttfLibName.} -proc fontFaceStyleName*(font: PFont): cstring{.cdecl, - importc: "TTF_FontFaceStyleName", dynlib: ttfLibName.} - # Get the metrics (dimensions) of a glyph -proc glyphMetrics*(font: PFont, ch: uint16, minx: var cint, - maxx: var cint, miny: var cint, maxy: var cint, - advance: var cint): cint{.cdecl, - importc: "TTF_GlyphMetrics", dynlib: ttfLibName.} - # Get the dimensions of a rendered string of text -proc sizeText*(font: PFont, text: cstring, w: var cint, y: var cint): cint{. - cdecl, importc: "TTF_SizeText", dynlib: ttfLibName.} -proc sizeUTF8*(font: PFont, text: cstring, w: var cint, y: var cint): cint{. - cdecl, importc: "TTF_SizeUTF8", dynlib: ttfLibName.} -proc sizeUNICODE*(font: PFont, text: PUInt16, w: var cint, y: var cint): cint{. - cdecl, importc: "TTF_SizeUNICODE", dynlib: ttfLibName.} - # Create an 8-bit palettized surface and render the given text at - # fast quality with the given font and color. The 0 pixel is the - # colorkey, giving a transparent background, and the 1 pixel is set - # to the text color. - # This function returns the new surface, or NULL if there was an error. - # -proc renderUTF8Solid*(font: PFont, text: cstring, fg: Color): PSurface{. - cdecl, importc: "TTF_RenderUTF8_Solid", dynlib: ttfLibName.} -proc renderUNICODE_Solid*(font: PFont, text: PUInt16, fg: Color): PSurface{. - cdecl, importc: "TTF_RenderUNICODE_Solid", dynlib: ttfLibName.} - # - #Create an 8-bit palettized surface and render the given glyph at - # fast quality with the given font and color. The 0 pixel is the - # colorkey, giving a transparent background, and the 1 pixel is set - # to the text color. The glyph is rendered without any padding or - # centering in the X direction, and aligned normally in the Y direction. - # This function returns the new surface, or NULL if there was an error. - # -proc renderGlyphSolid*(font: PFont, ch: uint16, fg: Color): PSurface{. - cdecl, importc: "TTF_RenderGlyph_Solid", dynlib: ttfLibName.} - # Create an 8-bit palettized surface and render the given text at - # high quality with the given font and colors. The 0 pixel is background, - # while other pixels have varying degrees of the foreground color. - # This function returns the new surface, or NULL if there was an error. - # -proc renderTextShaded*(font: PFont, text: cstring, fg: Color, - bg: Color): PSurface{.cdecl, - importc: "TTF_RenderText_Shaded", dynlib: ttfLibName.} -proc renderUTF8Shaded*(font: PFont, text: cstring, fg: Color, - bg: Color): PSurface{.cdecl, - importc: "TTF_RenderUTF8_Shaded", dynlib: ttfLibName.} -proc renderUNICODE_Shaded*(font: PFont, text: PUInt16, fg: Color, - bg: Color): PSurface{.cdecl, - importc: "TTF_RenderUNICODE_Shaded", dynlib: ttfLibName.} - # Create an 8-bit palettized surface and render the given glyph at - # high quality with the given font and colors. The 0 pixel is background, - # while other pixels have varying degrees of the foreground color. - # The glyph is rendered without any padding or centering in the X - # direction, and aligned normally in the Y direction. - # This function returns the new surface, or NULL if there was an error. - # -proc renderGlyphShaded*(font: PFont, ch: uint16, fg: Color, bg: Color): PSurface{. - cdecl, importc: "TTF_RenderGlyph_Shaded", dynlib: ttfLibName.} - # Create a 32-bit ARGB surface and render the given text at high quality, - # using alpha blending to dither the font with the given color. - # This function returns the new surface, or NULL if there was an error. - # -proc renderTextBlended*(font: PFont, text: cstring, fg: Color): PSurface{. - cdecl, importc: "TTF_RenderText_Blended", dynlib: ttfLibName.} -proc renderUTF8Blended*(font: PFont, text: cstring, fg: Color): PSurface{. - cdecl, importc: "TTF_RenderUTF8_Blended", dynlib: ttfLibName.} -proc RenderUNICODE_Blended*(font: PFont, text: PUInt16, fg: Color): PSurface{. - cdecl, importc: "TTF_RenderUNICODE_Blended", dynlib: ttfLibName.} - # Create a 32-bit ARGB surface and render the given glyph at high quality, - # using alpha blending to dither the font with the given color. - # The glyph is rendered without any padding or centering in the X - # direction, and aligned normally in the Y direction. - # This function returns the new surface, or NULL if there was an error. - # -proc renderGlyphBlended*(font: PFont, ch: uint16, fg: Color): PSurface{. - cdecl, importc: "TTF_RenderGlyph_Blended", dynlib: ttfLibName.} - # For compatibility with previous versions, here are the old functions - # #define TTF_RenderText(font, text, fg, bg) - # TTF_RenderText_Shaded(font, text, fg, bg) - # #define TTF_RenderUTF8(font, text, fg, bg) - # TTF_RenderUTF8_Shaded(font, text, fg, bg) - # #define TTF_RenderUNICODE(font, text, fg, bg) - # TTF_RenderUNICODE_Shaded(font, text, fg, bg) - # Close an opened font file -proc closeFont*(font: PFont){.cdecl, importc: "TTF_CloseFont", - dynlib: ttfLibName.} - # De-initialize TTF engine -proc quit*(){.cdecl, importc: "TTF_Quit", dynlib: ttfLibName.} - # Check if the TTF engine is initialized -proc wasInit*(): cint{.cdecl, importc: "TTF_WasInit", dynlib: ttfLibName.} - - -proc version*(x: var sdl.Version) = - x.major = MAJOR_VERSION - x.minor = MINOR_VERSION - x.patch = PATCHLEVEL - - -proc renderTextSolid*(font: PFont, text: cstring, fg: Color): PSurface{. - cdecl, importc: "TTF_RenderText_Solid", dynlib: ttfLibName.} diff --git a/lib/wrappers/sdl/smpeg.nim b/lib/wrappers/sdl/smpeg.nim deleted file mode 100644 index 57c16fa47..000000000 --- a/lib/wrappers/sdl/smpeg.nim +++ /dev/null @@ -1,335 +0,0 @@ -#****************************************************************************** -# -# $Id: smpeg.pas,v 1.7 2004/08/14 22:54:30 savage Exp $ -# -# -# -# Borland Delphi SMPEG - SDL MPEG Player Library -# Conversion of the SMPEG - SDL MPEG Player Library -# -# Portions created by Sam Lantinga are -# Copyright (C) 1997, 1998, 1999, 2000, 2001 Sam Lantinga -# 5635-34 Springhouse Dr. -# Pleasanton, CA 94588 (USA) -# -# All Rights Reserved. -# -# The original files are : smpeg.h -# -# The initial developer of this Pascal code was : -# Matthias Thoma -# -# Portions created by Matthias Thoma are -# Copyright (C) 2000 - 2001 Matthias Thoma. -# -# -# Contributor(s) -# -------------- -# Tom Jones His Project inspired this conversion -# Matthias Thoma -# -# Obtained through: -# Joint Endeavour of Delphi Innovators ( Project JEDI ) -# -# You may retrieve the latest version of this file at the Project -# JEDI home page, located at http://delphi-jedi.org -# -# The contents of this file are used with permission, subject to -# the Mozilla Public License Version 1.1 (the "License"); you may -# not use this file except in compliance with the License. You may -# obtain a copy of the License at -# http://www.mozilla.org/MPL/MPL-1.1.html -# -# Software distributed under the License is distributed on an -# "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or -# implied. See the License for the specific language governing -# rights and limitations under the License. -# -# Description -# ----------- -# -# -# -# -# -# -# -# Requires -# -------- -# The SDL Runtime libraris on Win32 : SDL.dll on Linux : libSDL-1.2.so.0 -# They are available from... -# http://www.libsdl.org . -# -# Programming Notes -# ----------------- -# -# -# -# -# Revision History -# ---------------- -# May 08 2001 - MT : Initial conversion -# -# October 12 2001 - DA : Various changes as suggested by David Acklam -# -# April 03 2003 - DL : Added jedi-sdl.inc include file to support more -# Pascal compilers. Initial support is now included -# for GnuPascal, VirtualPascal, TMT and obviously -# continue support for Delphi Kylix and FreePascal. -# -# April 08 2003 - MK : Aka Mr Kroket - Added Better FPC support -# Fixed all invalid calls to DLL. -# Changed constant names to: -# const -# STATUS_SMPEG_ERROR = -1; -# STATUS_SMPEG_STOPPED = 0; -# STATUS_SMPEG_PLAYING = 1; -# because SMPEG_ERROR is a function (_SMPEG_error -# isn't correct), and cannot be two elements with the -# same name -# -# April 24 2003 - DL : under instruction from Alexey Barkovoy, I have added -# better TMT Pascal support and under instruction -# from Prof. Abimbola Olowofoyeku (The African Chief), -# I have added better Gnu Pascal support -# -# April 30 2003 - DL : under instruction from David Mears AKA -# Jason Siletto, I have added FPC Linux support. -# This was compiled with fpc 1.1, so remember to set -# include file path. ie. -Fi/usr/share/fpcsrc/rtl/* -# -# -# $Log: smpeg.pas,v $ -# Revision 1.7 2004/08/14 22:54:30 savage -# Updated so that Library name defines are correctly defined for MacOS X. -# -# Revision 1.6 2004/05/10 14:10:04 savage -# Initial MacOS X support. Fixed defines for MACOS ( Classic ) and DARWIN ( MacOS X ). -# -# Revision 1.5 2004/04/13 09:32:08 savage -# Changed Shared object names back to just the .so extension to avoid conflicts on various Linux/Unix distros. Therefore developers will need to create Symbolic links to the actual Share Objects if necessary. -# -# Revision 1.4 2004/04/02 10:40:55 savage -# Changed Linux Shared Object name so they reflect the Symbolic Links that are created when installing the RPMs from the SDL site. -# -# Revision 1.3 2004/03/31 22:20:02 savage -# Windows unit not used in this file, so it was removed to keep the code tidy. -# -# Revision 1.2 2004/03/30 20:23:28 savage -# Tidied up use of UNIX compiler directive. -# -# Revision 1.1 2004/02/14 23:35:42 savage -# version 1 of sdl_image, sdl_mixer and smpeg. -# -# -# -#****************************************************************************** - -import - sdl - -when defined(windows): - const - SmpegLibName = "smpeg.dll" -elif defined(macosx): - const - SmpegLibName = "libsmpeg.dylib" -else: - const - SmpegLibName = "libsmpeg.so" -const - FILTER_INFO_MB_ERROR* = 1 - FILTER_INFO_PIXEL_ERROR* = 2 # Filter info from SMPEG - -type - FilterInfo*{.final.} = object - yuvMbSquareError*: PUInt16 - yuvPixelSquareError*: PUInt16 - - PFilterInfo* = ptr FilterInfo # MPEG filter definition - PFilter* = ptr Filter # Callback functions for the filter - FilterCallback* = proc (dest, source: POverlay, region: PRect, - filterInfo: PFilterInfo, data: pointer): pointer{. - cdecl.} - FilterDestroy* = proc (filter: PFilter): pointer{.cdecl.} # The filter definition itself - Filter*{.final.} = object # The null filter (default). It simply copies the source rectangle to the video overlay. - flags*: uint32 - data*: pointer - callback*: FilterCallback - destroy*: FilterDestroy -{.deprecated: [TFilterInfo: FilterInfo, TFilterCallback: FilterCallback, - TFilterDestroy: FilterDestroy, TFilter: Filter].} - -proc filterNull*(): PFilter{.cdecl, importc: "SMPEGfilter_null", - dynlib: SmpegLibName.} - # The bilinear filter. A basic low-pass filter that will produce a smoother image. -proc filterBilinear*(): PFilter{.cdecl, - importc: "SMPEGfilter_bilinear", dynlib: SmpegLibName.} - # The deblocking filter. It filters block borders and non-intra coded blocks to reduce blockiness -proc filterDeblocking*(): PFilter{.cdecl, - importc: "SMPEGfilter_deblocking", dynlib: SmpegLibName.} - #------------------------------------------------------------------------------ - # SMPEG.h - #------------------------------------------------------------------------------ -const - MAJOR_VERSION* = 0 - MINOR_VERSION* = 4 - PATCHLEVEL* = 2 - -type - TVersion* = object - major*: byte - minor*: byte - patch*: byte - - Pversion* = ptr TVersion # This is the actual SMPEG object - TSMPEG* = object - PSMPEG* = ptr TSMPEG # Used to get information about the SMPEG object - Info* = object - hasAudio*: int32 - hasVideo*: int32 - width*: int32 - height*: int32 - currentFrame*: int32 - currentFps*: float64 - audioString*: array[0..79, char] - audioCurrentFrame*: int32 - currentOffset*: uint32 - totalSize*: uint32 - currentTime*: float64 - totalTime*: float64 - - PInfo* = ptr Info # Possible MPEG status codes -{.deprecated: [TInfo: Info].} - -const - STATUS_ERROR* = - 1 - STATUS_STOPPED* = 0 - STATUS_PLAYING* = 1 - -type - Status* = int32 - Pstatus* = ptr int32 # Matches the declaration of SDL_UpdateRect() - TDisplayCallback* = proc (dst: PSurface, x, y: int, w, h: int): pointer{. - cdecl.} # Create a new SMPEG object from an MPEG file. - # On return, if 'info' is not NULL, it will be filled with information - # about the MPEG object. - # This function returns a new SMPEG object. Use error() to find out - # whether or not there was a problem building the MPEG stream. - # The sdl_audio parameter indicates if SMPEG should initialize the SDL audio - # subsystem. If not, you will have to use the playaudio() function below - # to extract the decoded data. -{.deprecated: [Tstatus: Status].} - -proc new*(theFile: cstring, info: PInfo, audio: int): PSMPEG{.cdecl, - importc: "SMPEG_new", dynlib: SmpegLibName.} - # The same as above for a file descriptor -proc newDescr*(theFile: int, info: PInfo, audio: int): PSMPEG{. - cdecl, importc: "SMPEG_new_descr", dynlib: SmpegLibName.} - # The same as above but for a raw chunk of data. SMPEG makes a copy of the - # data, so the application is free to delete after a successful call to this - # function. -proc newData*(data: pointer, size: int, info: PInfo, audio: int): PSMPEG{. - cdecl, importc: "SMPEG_new_data", dynlib: SmpegLibName.} - # Get current information about an SMPEG object -proc getinfo*(mpeg: PSMPEG, info: PInfo){.cdecl, - importc: "SMPEG_getinfo", dynlib: SmpegLibName.} - #procedure getinfo(mpeg: PSMPEG; info: Pointer); - #cdecl; external SmpegLibName; - # Enable or disable audio playback in MPEG stream -proc enableaudio*(mpeg: PSMPEG, enable: int){.cdecl, - importc: "SMPEG_enableaudio", dynlib: SmpegLibName.} - # Enable or disable video playback in MPEG stream -proc enablevideo*(mpeg: PSMPEG, enable: int){.cdecl, - importc: "SMPEG_enablevideo", dynlib: SmpegLibName.} - # Delete an SMPEG object -proc delete*(mpeg: PSMPEG){.cdecl, importc: "SMPEG_delete", - dynlib: SmpegLibName.} - # Get the current status of an SMPEG object -proc status*(mpeg: PSMPEG): Status{.cdecl, importc: "SMPEG_status", - dynlib: SmpegLibName.} - # status - # Set the audio volume of an MPEG stream, in the range 0-100 -proc setVolume*(mpeg: PSMPEG, volume: int){.cdecl, - importc: "SMPEG_setvolume", dynlib: SmpegLibName.} - # Set the destination surface for MPEG video playback - # 'surfLock' is a mutex used to synchronize access to 'dst', and can be NULL. - # 'callback' is a function called when an area of 'dst' needs to be updated. - # If 'callback' is NULL, the default function (SDL_UpdateRect) will be used. -proc setDisplay*(mpeg: PSMPEG, dst: PSurface, surfLock: PMutex, - callback: TDisplayCallback){.cdecl, - importc: "SMPEG_setdisplay", dynlib: SmpegLibName.} - # Set or clear looping play on an SMPEG object -proc loop*(mpeg: PSMPEG, repeat: int){.cdecl, importc: "SMPEG_loop", - dynlib: SmpegLibName.} - # Scale pixel display on an SMPEG object -proc scaleXY*(mpeg: PSMPEG, width, height: int){.cdecl, - importc: "SMPEG_scaleXY", dynlib: SmpegLibName.} -proc scale*(mpeg: PSMPEG, scale: int){.cdecl, importc: "SMPEG_scale", - dynlib: SmpegLibName.} -proc double*(mpeg: PSMPEG, doubleit: bool) - # Move the video display area within the destination surface -proc move*(mpeg: PSMPEG, x, y: int){.cdecl, importc: "SMPEG_move", - dynlib: SmpegLibName.} - # Set the region of the video to be shown -proc setDisplayRegion*(mpeg: PSMPEG, x, y, w, h: int){.cdecl, - importc: "SMPEG_setdisplayregion", dynlib: SmpegLibName.} - # Play an SMPEG object -proc play*(mpeg: PSMPEG){.cdecl, importc: "SMPEG_play", - dynlib: SmpegLibName.} - # Pause/Resume playback of an SMPEG object -proc pause*(mpeg: PSMPEG){.cdecl, importc: "SMPEG_pause", - dynlib: SmpegLibName.} - # Stop playback of an SMPEG object -proc stop*(mpeg: PSMPEG){.cdecl, importc: "SMPEG_stop", - dynlib: SmpegLibName.} - # Rewind the play position of an SMPEG object to the beginning of the MPEG -proc rewind*(mpeg: PSMPEG){.cdecl, importc: "SMPEG_rewind", - dynlib: SmpegLibName.} - # Seek 'bytes' bytes in the MPEG stream -proc seek*(mpeg: PSMPEG, bytes: int){.cdecl, importc: "SMPEG_seek", - dynlib: SmpegLibName.} - # Skip 'seconds' seconds in the MPEG stream -proc skip*(mpeg: PSMPEG, seconds: float32){.cdecl, importc: "SMPEG_skip", - dynlib: SmpegLibName.} - # Render a particular frame in the MPEG video - # API CHANGE: This function no longer takes a target surface and position. - # Use setdisplay() and move() to set this information. -proc renderFrame*(mpeg: PSMPEG, framenum: int){.cdecl, - importc: "SMPEG_renderFrame", dynlib: SmpegLibName.} - # Render the last frame of an MPEG video -proc renderFinal*(mpeg: PSMPEG, dst: PSurface, x, y: int){.cdecl, - importc: "SMPEG_renderFinal", dynlib: SmpegLibName.} - # Set video filter -proc filter*(mpeg: PSMPEG, filter: PFilter): PFilter{.cdecl, - importc: "SMPEG_filter", dynlib: SmpegLibName.} - # Return NULL if there is no error in the MPEG stream, or an error message - # if there was a fatal error in the MPEG stream for the SMPEG object. -proc error*(mpeg: PSMPEG): cstring{.cdecl, importc: "SMPEG_error", - dynlib: SmpegLibName.} - # Exported callback function for audio playback. - # The function takes a buffer and the amount of data to fill, and returns - # the amount of data in bytes that was actually written. This will be the - # amount requested unless the MPEG audio has finished. - # -proc playAudio*(mpeg: PSMPEG, stream: pointer, length: int): int{.cdecl, - importc: "SMPEG_playAudio", dynlib: SmpegLibName.} - # Wrapper for playAudio() that can be passed to SDL and SDL_mixer -proc playAudioSDL*(mpeg: pointer, stream: pointer, length: int){.cdecl, - importc: "SMPEG_playAudioSDL", dynlib: SmpegLibName.} - # Get the best SDL audio spec for the audio stream -proc wantedSpec*(mpeg: PSMPEG, wanted: PAudioSpec): int{.cdecl, - importc: "SMPEG_wantedSpec", dynlib: SmpegLibName.} - # Inform SMPEG of the actual SDL audio spec used for sound playback -proc actualSpec*(mpeg: PSMPEG, spec: PAudioSpec){.cdecl, - importc: "SMPEG_actualSpec", dynlib: SmpegLibName.} - # This macro can be used to fill a version structure with the compile-time - # version of the SDL library. -proc getversion*(x: var TVersion) = - x.major = MAJOR_VERSION - x.minor = MINOR_VERSION - x.patch = PATCHLEVEL - -proc double(mpeg: PSMPEG, doubleit: bool) = - if doubleit: scale(mpeg, 2) - else: scale(mpeg, 1) diff --git a/lib/wrappers/sphinx.nim b/lib/wrappers/sphinx.nim deleted file mode 100644 index d9e98faa8..000000000 --- a/lib/wrappers/sphinx.nim +++ /dev/null @@ -1,263 +0,0 @@ -# -# $Id: sphinxclient.h 2654 2011-01-31 01:20:58Z kevg $ -# -# -# Copyright (c) 2001-2011, Andrew Aksyonoff -# Copyright (c) 2008-2011, Sphinx Technologies Inc -# All rights reserved -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU Library General Public License. You should -# have received a copy of the LGPL license along with this program; if you -# did not, you can find it at http://www.gnu.org/ -# - -## Nim wrapper for ``sphinx``. - -{.deadCodeElim: on.} -when defined(windows): - const - sphinxDll* = "spinx.dll" -elif defined(macosx): - const - sphinxDll* = "libspinx.dylib" -else: - const - sphinxDll* = "libspinxclient.so" - -#/ known searchd status codes: -const - SEARCHD_OK* = 0 - SEARCHD_ERROR* = 1 - SEARCHD_RETRY* = 2 - SEARCHD_WARNING* = 3 - -#/ known match modes - -const - SPH_MATCH_ALL* = 0 - SPH_MATCH_ANY* = 1 - SPH_MATCH_PHRASE* = 2 - SPH_MATCH_BOOLEAN* = 3 - SPH_MATCH_EXTENDED* = 4 - SPH_MATCH_FULLSCAN* = 5 - SPH_MATCH_EXTENDED2* = 6 - -#/ known ranking modes (ext2 only) - -const - SPH_RANK_PROXIMITY_BM25* = 0 - SPH_RANK_BM25* = 1 - SPH_RANK_NONE* = 2 - SPH_RANK_WORDCOUNT* = 3 - SPH_RANK_PROXIMITY* = 4 - SPH_RANK_MATCHANY* = 5 - SPH_RANK_FIELDMASK* = 6 - SPH_RANK_SPH04* = 7 - SPH_RANK_DEFAULT* = SPH_RANK_PROXIMITY_BM25 - -#/ known sort modes - -const - SPH_SORT_RELEVANCE* = 0 - SPH_SORT_ATTR_DESC* = 1 - SPH_SORT_ATTR_ASC* = 2 - SPH_SORT_TIME_SEGMENTS* = 3 - SPH_SORT_EXTENDED* = 4 - SPH_SORT_EXPR* = 5 - -#/ known filter types - -const - SPH_FILTER_VALUES* = 0 - SPH_FILTER_RANGE* = 1 - SPH_FILTER_FLOATRANGE* = 2 - -#/ known attribute types - -const - SPH_ATTR_INTEGER* = 1 - SPH_ATTR_TIMESTAMP* = 2 - SPH_ATTR_ORDINAL* = 3 - SPH_ATTR_BOOL* = 4 - SPH_ATTR_FLOAT* = 5 - SPH_ATTR_BIGINT* = 6 - SPH_ATTR_STRING* = 7 - SPH_ATTR_MULTI* = 0x40000000 - -#/ known grouping functions - -const - SPH_GROUPBY_DAY* = 0 - SPH_GROUPBY_WEEK* = 1 - SPH_GROUPBY_MONTH* = 2 - SPH_GROUPBY_YEAR* = 3 - SPH_GROUPBY_ATTR* = 4 - SPH_GROUPBY_ATTRPAIR* = 5 - -type - SphinxBool* {.size: sizeof(cint).} = enum - SPH_FALSE = 0, - SPH_TRUE = 1 - - Client {.pure, final.} = object - PClient* = ptr Client - Wordinfo*{.pure, final.} = object - word*: cstring - docs*: cint - hits*: cint - - Result*{.pure, final.} = object - error*: cstring - warning*: cstring - status*: cint - num_fields*: cint - fields*: cstringArray - num_attrs*: cint - attr_names*: cstringArray - attr_types*: ptr array [0..100_000, cint] - num_matches*: cint - values_pool*: pointer - total*: cint - total_found*: cint - time_msec*: cint - num_words*: cint - words*: ptr array [0..100_000, Wordinfo] - - Excerpt_options*{.pure, final.} = object - before_match*: cstring - after_match*: cstring - chunk_separator*: cstring - html_strip_mode*: cstring - passage_boundary*: cstring - limit*: cint - limit_passages*: cint - limit_words*: cint - around*: cint - start_passage_id*: cint - exact_phrase*: SphinxBool - single_passage*: SphinxBool - use_boundaries*: SphinxBool - weight_order*: SphinxBool - query_mode*: SphinxBool - force_all_words*: SphinxBool - load_files*: SphinxBool - allow_empty*: SphinxBool - emit_zones*: SphinxBool - - Keyword_info*{.pure, final.} = object - tokenized*: cstring - normalized*: cstring - num_docs*: cint - num_hits*: cint -{.deprecated: [TSphinxBool: SphinxBool, - Tclient: Client, Twordinfo: Wordinfo, Tresult: Result, - Texcerpt_options: Excerpt_options, Tkeyword_info: Keyword_info].} - -proc create*(copy_args: SphinxBool): PClient{.cdecl, importc: "sphinx_create", - dynlib: sphinxDll.} -proc cleanup*(client: PClient){.cdecl, importc: "sphinx_cleanup", - dynlib: sphinxDll.} -proc destroy*(client: PClient){.cdecl, importc: "sphinx_destroy", - dynlib: sphinxDll.} -proc error*(client: PClient): cstring{.cdecl, importc: "sphinx_error", - dynlib: sphinxDll.} -proc warning*(client: PClient): cstring{.cdecl, importc: "sphinx_warning", - dynlib: sphinxDll.} -proc set_server*(client: PClient, host: cstring, port: cint): SphinxBool{.cdecl, - importc: "sphinx_set_server", dynlib: sphinxDll.} -proc set_connect_timeout*(client: PClient, seconds: float32): SphinxBool{.cdecl, - importc: "sphinx_set_connect_timeout", dynlib: sphinxDll.} -proc open*(client: PClient): SphinxBool{.cdecl, importc: "sphinx_open", - dynlib: sphinxDll.} -proc close*(client: PClient): SphinxBool{.cdecl, importc: "sphinx_close", - dynlib: sphinxDll.} -proc set_limits*(client: PClient, offset: cint, limit: cint, - max_matches: cint, cutoff: cint): SphinxBool{.cdecl, - importc: "sphinx_set_limits", dynlib: sphinxDll.} -proc set_max_query_time*(client: PClient, max_query_time: cint): SphinxBool{. - cdecl, importc: "sphinx_set_max_query_time", dynlib: sphinxDll.} -proc set_match_mode*(client: PClient, mode: cint): SphinxBool{.cdecl, - importc: "sphinx_set_match_mode", dynlib: sphinxDll.} -proc set_ranking_mode*(client: PClient, ranker: cint): SphinxBool{.cdecl, - importc: "sphinx_set_ranking_mode", dynlib: sphinxDll.} -proc set_sort_mode*(client: PClient, mode: cint, sortby: cstring): SphinxBool{. - cdecl, importc: "sphinx_set_sort_mode", dynlib: sphinxDll.} -proc set_field_weights*(client: PClient, num_weights: cint, - field_names: cstringArray, field_weights: ptr cint): SphinxBool{. - cdecl, importc: "sphinx_set_field_weights", dynlib: sphinxDll.} -proc set_index_weights*(client: PClient, num_weights: cint, - index_names: cstringArray, index_weights: ptr cint): SphinxBool{. - cdecl, importc: "sphinx_set_index_weights", dynlib: sphinxDll.} -proc set_id_range*(client: PClient, minid: int64, maxid: int64): SphinxBool{. - cdecl, importc: "sphinx_set_id_range", dynlib: sphinxDll.} -proc add_filter*(client: PClient, attr: cstring, num_values: cint, - values: ptr int64, exclude: SphinxBool): SphinxBool{.cdecl, - importc: "sphinx_add_filter", dynlib: sphinxDll.} -proc add_filter_range*(client: PClient, attr: cstring, umin: int64, - umax: int64, exclude: SphinxBool): SphinxBool{.cdecl, - importc: "sphinx_add_filter_range", dynlib: sphinxDll.} -proc add_filter_float_range*(client: PClient, attr: cstring, fmin: float32, - fmax: float32, exclude: SphinxBool): SphinxBool{.cdecl, - importc: "sphinx_add_filter_float_range", dynlib: sphinxDll.} -proc set_geoanchor*(client: PClient, attr_latitude: cstring, - attr_longitude: cstring, latitude: float32, longitude: float32): SphinxBool{. - cdecl, importc: "sphinx_set_geoanchor", dynlib: sphinxDll.} -proc set_groupby*(client: PClient, attr: cstring, groupby_func: cint, - group_sort: cstring): SphinxBool{.cdecl, - importc: "sphinx_set_groupby", dynlib: sphinxDll.} -proc set_groupby_distinct*(client: PClient, attr: cstring): SphinxBool{.cdecl, - importc: "sphinx_set_groupby_distinct", dynlib: sphinxDll.} -proc set_retries*(client: PClient, count: cint, delay: cint): SphinxBool{.cdecl, - importc: "sphinx_set_retries", dynlib: sphinxDll.} -proc add_override*(client: PClient, attr: cstring, docids: ptr int64, - num_values: cint, values: ptr cint): SphinxBool{.cdecl, - importc: "sphinx_add_override", dynlib: sphinxDll.} -proc set_select*(client: PClient, select_list: cstring): SphinxBool{.cdecl, - importc: "sphinx_set_select", dynlib: sphinxDll.} -proc reset_filters*(client: PClient){.cdecl, - importc: "sphinx_reset_filters", dynlib: sphinxDll.} -proc reset_groupby*(client: PClient){.cdecl, - importc: "sphinx_reset_groupby", dynlib: sphinxDll.} -proc query*(client: PClient, query: cstring, index_list: cstring, - comment: cstring): ptr Result{.cdecl, importc: "sphinx_query", - dynlib: sphinxDll.} -proc add_query*(client: PClient, query: cstring, index_list: cstring, - comment: cstring): cint{.cdecl, importc: "sphinx_add_query", - dynlib: sphinxDll.} -proc run_queries*(client: PClient): ptr Result{.cdecl, - importc: "sphinx_run_queries", dynlib: sphinxDll.} -proc get_num_results*(client: PClient): cint{.cdecl, - importc: "sphinx_get_num_results", dynlib: sphinxDll.} -proc get_id*(result: ptr Result, match: cint): int64{.cdecl, - importc: "sphinx_get_id", dynlib: sphinxDll.} -proc get_weight*(result: ptr Result, match: cint): cint{.cdecl, - importc: "sphinx_get_weight", dynlib: sphinxDll.} -proc get_int*(result: ptr Result, match: cint, attr: cint): int64{.cdecl, - importc: "sphinx_get_int", dynlib: sphinxDll.} -proc get_float*(result: ptr Result, match: cint, attr: cint): float32{.cdecl, - importc: "sphinx_get_float", dynlib: sphinxDll.} -proc get_mva*(result: ptr Result, match: cint, attr: cint): ptr cint{. - cdecl, importc: "sphinx_get_mva", dynlib: sphinxDll.} -proc get_string*(result: ptr Result, match: cint, attr: cint): cstring{.cdecl, - importc: "sphinx_get_string", dynlib: sphinxDll.} -proc init_excerpt_options*(opts: ptr Excerpt_options){.cdecl, - importc: "sphinx_init_excerpt_options", dynlib: sphinxDll.} -proc build_excerpts*(client: PClient, num_docs: cint, docs: cstringArray, - index: cstring, words: cstring, opts: ptr Excerpt_options): cstringArray{. - cdecl, importc: "sphinx_build_excerpts", dynlib: sphinxDll.} -proc update_attributes*(client: PClient, index: cstring, num_attrs: cint, - attrs: cstringArray, num_docs: cint, - docids: ptr int64, values: ptr int64): cint{. - cdecl, importc: "sphinx_update_attributes", dynlib: sphinxDll.} -proc update_attributes_mva*(client: PClient, index: cstring, attr: cstring, - docid: int64, num_values: cint, - values: ptr cint): cint{.cdecl, - importc: "sphinx_update_attributes_mva", dynlib: sphinxDll.} -proc build_keywords*(client: PClient, query: cstring, index: cstring, - hits: SphinxBool, out_num_keywords: ptr cint): ptr Keyword_info{. - cdecl, importc: "sphinx_build_keywords", dynlib: sphinxDll.} -proc status*(client: PClient, num_rows: ptr cint, num_cols: ptr cint): cstringArray{. - cdecl, importc: "sphinx_status", dynlib: sphinxDll.} -proc status_destroy*(status: cstringArray, num_rows: cint, num_cols: cint){. - cdecl, importc: "sphinx_status_destroy", dynlib: sphinxDll.} diff --git a/lib/wrappers/tre.nim b/lib/wrappers/tre.nim deleted file mode 100644 index 36bf3cb69..000000000 --- a/lib/wrappers/tre.nim +++ /dev/null @@ -1,188 +0,0 @@ -# -# tre.h - TRE public API definitions -# -# This software is released under a BSD-style license. -# See the file LICENSE for details and copyright. -# -# - -when not defined(treDll): - when hostOS == "windows": - const treDll = "tre.dll" - elif hostOS == "macosx": - const treDll = "libtre.dylib" - else: - const treDll = "libtre.so(.5|)" - -const - APPROX* = 1 ## approximate matching functionality - MULTIBYTE* = 1 ## multibyte character set support. - VERSION* = "0.8.0" ## TRE version string. - VERSION_1* = 0 ## TRE version level 1. - VERSION_2* = 8 ## TRE version level 2. - VERSION_3* = 0 ## TRE version level 3. - - -# If the we're not using system regex.h, we need to define the -# structs and enums ourselves. - -type - Regoff* = cint - Regex*{.pure, final.} = object - re_nsub*: int ## Number of parenthesized subexpressions. - value*: pointer ## For internal use only. - - Regmatch*{.pure, final.} = object - rm_so*: Regoff - rm_eo*: Regoff - - Reg_errcode*{.size: 4.} = enum ## POSIX tre_regcomp() return error codes. - ## (In the order listed in the standard.) - REG_OK = 0, ## No error. - REG_NOMATCH, ## No match. - REG_BADPAT, ## Invalid regexp. - REG_ECOLLATE, ## Unknown collating element. - REG_ECTYPE, ## Unknown character class name. - REG_EESCAPE, ## Trailing backslash. - REG_ESUBREG, ## Invalid back reference. - REG_EBRACK, ## "[]" imbalance - REG_EPAREN, ## "\(\)" or "()" imbalance - REG_EBRACE, ## "\{\}" or "{}" imbalance - REG_BADBR, ## Invalid content of {} - REG_ERANGE, ## Invalid use of range operator - REG_ESPACE, ## Out of memory. - REG_BADRPT ## Invalid use of repetition operators. -{.deprecated: [TRegoff: Regoff, TRegex: Regex, TRegmatch: Regmatch, - TReg_errcode: Reg_errcode].} - -# POSIX tre_regcomp() flags. - -const - REG_EXTENDED* = 1 - REG_ICASE* = (REG_EXTENDED shl 1) - REG_NEWLINE* = (REG_ICASE shl 1) - REG_NOSUB* = (REG_NEWLINE shl 1) - -# Extra tre_regcomp() flags. - -const - REG_BASIC* = 0 - REG_LITERAL* = (REG_NOSUB shl 1) - REG_RIGHT_ASSOC* = (REG_LITERAL shl 1) - REG_UNGREEDY* = (REG_RIGHT_ASSOC shl 1) - -# POSIX tre_regexec() flags. - -const - REG_NOTBOL* = 1 - REG_NOTEOL* = (REG_NOTBOL shl 1) - -# Extra tre_regexec() flags. - -const - REG_APPROX_MATCHER* = (REG_NOTEOL shl 1) - REG_BACKTRACKING_MATCHER* = (REG_APPROX_MATCHER shl 1) - -# The maximum number of iterations in a bound expression. - -const - RE_DUP_MAX* = 255 - -# The POSIX.2 regexp functions - -proc regcomp*(preg: var Regex, regex: cstring, cflags: cint): cint{.cdecl, - importc: "tre_regcomp", dynlib: treDll.} -proc regexec*(preg: var Regex, string: cstring, nmatch: int, - pmatch: ptr Regmatch, eflags: cint): cint{.cdecl, - importc: "tre_regexec", dynlib: treDll.} -proc regerror*(errcode: cint, preg: var Regex, errbuf: cstring, - errbuf_size: int): int{.cdecl, importc: "tre_regerror", - dynlib: treDll.} -proc regfree*(preg: var Regex){.cdecl, importc: "tre_regfree", dynlib: treDll.} -# Versions with a maximum length argument and therefore the capability to -# handle null characters in the middle of the strings (not in POSIX.2). - -proc regncomp*(preg: var Regex, regex: cstring, len: int, cflags: cint): cint{. - cdecl, importc: "tre_regncomp", dynlib: treDll.} -proc regnexec*(preg: var Regex, string: cstring, len: int, nmatch: int, - pmatch: ptr Regmatch, eflags: cint): cint{.cdecl, - importc: "tre_regnexec", dynlib: treDll.} -# Approximate matching parameter struct. - -type - TRegaparams*{.pure, final.} = object - cost_ins*: cint ## Default cost of an inserted character. - cost_del*: cint ## Default cost of a deleted character. - cost_subst*: cint ## Default cost of a substituted character. - max_cost*: cint ## Maximum allowed cost of a match. - max_ins*: cint ## Maximum allowed number of inserts. - max_del*: cint ## Maximum allowed number of deletes. - max_subst*: cint ## Maximum allowed number of substitutes. - max_err*: cint ## Maximum allowed number of errors total. - - -# Approximate matching result struct. - -type - TRegamatch*{.pure, final.} = object - nmatch*: int ## Length of pmatch[] array. - pmatch*: ptr Regmatch ## Submatch data. - cost*: cint ## Cost of the match. - num_ins*: cint ## Number of inserts in the match. - num_del*: cint ## Number of deletes in the match. - num_subst*: cint ## Number of substitutes in the match. - - -# Approximate matching functions. - -proc regaexec*(preg: var Regex, string: cstring, match: ptr TRegamatch, - params: TRegaparams, eflags: cint): cint{.cdecl, - importc: "tre_regaexec", dynlib: treDll.} -proc reganexec*(preg: var Regex, string: cstring, len: int, - match: ptr TRegamatch, params: TRegaparams, - eflags: cint): cint{. - cdecl, importc: "tre_reganexec", dynlib: treDll.} -# Sets the parameters to default values. - -proc regaparams_default*(params: ptr TRegaparams){.cdecl, - importc: "tre_regaparams_default", dynlib: treDll.} - -type - TStrSource*{.pure, final.} = object - get_next_char*: proc (c: cstring, pos_add: ptr cint, - context: pointer): cint{.cdecl.} - rewind*: proc (pos: int, context: pointer){.cdecl.} - compare*: proc (pos1: int, pos2: int, len: int, context: pointer): cint{. - cdecl.} - context*: pointer - - -proc reguexec*(preg: var Regex, string: ptr TStrSource, nmatch: int, - pmatch: ptr Regmatch, eflags: cint): cint{.cdecl, - importc: "tre_reguexec", dynlib: treDll.} - -proc runtimeVersion*(): cstring{.cdecl, importc: "tre_version", dynlib: treDll.} - # Returns the version string. The returned string is static. - -proc config*(query: cint, result: pointer): cint{.cdecl, importc: "tre_config", - dynlib: treDll.} - # Returns the value for a config parameter. The type to which `result` - # must point to depends of the value of `query`, see documentation for - # more details. - -const - CONFIG_APPROX* = 0 - CONFIG_WCHAR* = 1 - CONFIG_MULTIBYTE* = 2 - CONFIG_SYSTEM_ABI* = 3 - CONFIG_VERSION* = 4 - -# Returns 1 if the compiled pattern has back references, 0 if not. - -proc have_backrefs*(preg: var Regex): cint{.cdecl, - importc: "tre_have_backrefs", dynlib: treDll.} -# Returns 1 if the compiled pattern uses approximate matching features, -# 0 if not. - -proc have_approx*(preg: var Regex): cint{.cdecl, importc: "tre_have_approx", - dynlib: treDll.} diff --git a/lib/wrappers/zip/libzip.nim b/lib/wrappers/zip/libzip.nim deleted file mode 100644 index 076965d46..000000000 --- a/lib/wrappers/zip/libzip.nim +++ /dev/null @@ -1,251 +0,0 @@ -# -# -# Nim's Runtime Library -# (c) Copyright 2013 Andreas Rumpf -# -# See the file "copying.txt", included in this -# distribution, for details about the copyright. -# - -## Interface to the `libzip `_ library by -## Dieter Baron and Thomas Klausner. This version links -## against ``libzip2.so.2`` unless you define the symbol ``useLibzipSrc``; then -## it is compiled against some old ``libizp_all.c`` file. - -# -# zip.h -- exported declarations. -# Copyright (C) 1999-2008 Dieter Baron and Thomas Klausner -# -# This file is part of libzip, a library to manipulate ZIP archives. -# The authors can be contacted at -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in -# the documentation and/or other materials provided with the -# distribution. -# 3. The names of the authors may not be used to endorse or promote -# products derived from this software without specific prior -# written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS -# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY -# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE -# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER -# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR -# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -# IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# - -import times - -when defined(unix) and not defined(useLibzipSrc): - when defined(macosx): - {.pragma: mydll, dynlib: "libzip2.dylib".} - else: - {.pragma: mydll, dynlib: "libzip(|2).so(|.2|.1|.0)".} -else: - when defined(unix): - {.passl: "-lz".} - {.compile: "libzip_all.c".} - {.pragma: mydll.} - -type - ZipSourceCmd* = int32 - - ZipSourceCallback* = proc (state: pointer, data: pointer, length: int, - cmd: ZipSourceCmd): int {.cdecl.} - PZipStat* = ptr ZipStat - ZipStat* = object ## the 'zip_stat' struct - name*: cstring ## name of the file - index*: int32 ## index within archive - crc*: int32 ## crc of file data - mtime*: Time ## modification time - size*: int ## size of file (uncompressed) - compSize*: int ## size of file (compressed) - compMethod*: int16 ## compression method used - encryptionMethod*: int16 ## encryption method used - - Zip = object - ZipSource = object - ZipFile = object - - PZip* = ptr Zip ## represents a zip archive - PZipFile* = ptr ZipFile ## represents a file within an archive - PZipSource* = ptr ZipSource ## represents a source for an archive -{.deprecated: [TZipSourceCmd: ZipSourceCmd, TZipStat: ZipStat, TZip: Zip, - TZipSourceCallback: ZipSourceCallback, TZipSource: ZipSource, - TZipFile: ZipFile].} - -# flags for zip_name_locate, zip_fopen, zip_stat, ... -const - ZIP_CREATE* = 1'i32 - ZIP_EXCL* = 2'i32 - ZIP_CHECKCONS* = 4'i32 - ZIP_FL_NOCASE* = 1'i32 ## ignore case on name lookup - ZIP_FL_NODIR* = 2'i32 ## ignore directory component - ZIP_FL_COMPRESSED* = 4'i32 ## read compressed data - ZIP_FL_UNCHANGED* = 8'i32 ## use original data, ignoring changes - ZIP_FL_RECOMPRESS* = 16'i32 ## force recompression of data - -const # archive global flags flags - ZIP_AFL_TORRENT* = 1'i32 ## torrent zipped - -const # libzip error codes - ZIP_ER_OK* = 0'i32 ## N No error - ZIP_ER_MULTIDISK* = 1'i32 ## N Multi-disk zip archives not supported - ZIP_ER_RENAME* = 2'i32 ## S Renaming temporary file failed - ZIP_ER_CLOSE* = 3'i32 ## S Closing zip archive failed - ZIP_ER_SEEK* = 4'i32 ## S Seek error - ZIP_ER_READ* = 5'i32 ## S Read error - ZIP_ER_WRITE* = 6'i32 ## S Write error - ZIP_ER_CRC* = 7'i32 ## N CRC error - ZIP_ER_ZIPCLOSED* = 8'i32 ## N Containing zip archive was closed - ZIP_ER_NOENT* = 9'i32 ## N No such file - ZIP_ER_EXISTS* = 10'i32 ## N File already exists - ZIP_ER_OPEN* = 11'i32 ## S Can't open file - ZIP_ER_TMPOPEN* = 12'i32 ## S Failure to create temporary file - ZIP_ER_ZLIB* = 13'i32 ## Z Zlib error - ZIP_ER_MEMORY* = 14'i32 ## N Malloc failure - ZIP_ER_CHANGED* = 15'i32 ## N Entry has been changed - ZIP_ER_COMPNOTSUPP* = 16'i32 ## N Compression method not supported - ZIP_ER_EOF* = 17'i32 ## N Premature EOF - ZIP_ER_INVAL* = 18'i32 ## N Invalid argument - ZIP_ER_NOZIP* = 19'i32 ## N Not a zip archive - ZIP_ER_INTERNAL* = 20'i32 ## N Internal error - ZIP_ER_INCONS* = 21'i32 ## N Zip archive inconsistent - ZIP_ER_REMOVE* = 22'i32 ## S Can't remove file - ZIP_ER_DELETED* = 23'i32 ## N Entry has been deleted - -const # type of system error value - ZIP_ET_NONE* = 0'i32 ## sys_err unused - ZIP_ET_SYS* = 1'i32 ## sys_err is errno - ZIP_ET_ZLIB* = 2'i32 ## sys_err is zlib error code - -const # compression methods - ZIP_CM_DEFAULT* = -1'i32 ## better of deflate or store - ZIP_CM_STORE* = 0'i32 ## stored (uncompressed) - ZIP_CM_SHRINK* = 1'i32 ## shrunk - ZIP_CM_REDUCE_1* = 2'i32 ## reduced with factor 1 - ZIP_CM_REDUCE_2* = 3'i32 ## reduced with factor 2 - ZIP_CM_REDUCE_3* = 4'i32 ## reduced with factor 3 - ZIP_CM_REDUCE_4* = 5'i32 ## reduced with factor 4 - ZIP_CM_IMPLODE* = 6'i32 ## imploded - ## 7 - Reserved for Tokenizing compression algorithm - ZIP_CM_DEFLATE* = 8'i32 ## deflated - ZIP_CM_DEFLATE64* = 9'i32 ## deflate64 - ZIP_CM_PKWARE_IMPLODE* = 10'i32 ## PKWARE imploding - ## 11 - Reserved by PKWARE - ZIP_CM_BZIP2* = 12'i32 ## compressed using BZIP2 algorithm - ## 13 - Reserved by PKWARE - ZIP_CM_LZMA* = 14'i32 ## LZMA (EFS) - ## 15-17 - Reserved by PKWARE - ZIP_CM_TERSE* = 18'i32 ## compressed using IBM TERSE (new) - ZIP_CM_LZ77* = 19'i32 ## IBM LZ77 z Architecture (PFS) - ZIP_CM_WAVPACK* = 97'i32 ## WavPack compressed data - ZIP_CM_PPMD* = 98'i32 ## PPMd version I, Rev 1 - -const # encryption methods - ZIP_EM_NONE* = 0'i32 ## not encrypted - ZIP_EM_TRAD_PKWARE* = 1'i32 ## traditional PKWARE encryption - -const - ZIP_EM_UNKNOWN* = 0x0000FFFF'i32 ## unknown algorithm - -const - ZIP_SOURCE_OPEN* = 0'i32 ## prepare for reading - ZIP_SOURCE_READ* = 1'i32 ## read data - ZIP_SOURCE_CLOSE* = 2'i32 ## reading is done - ZIP_SOURCE_STAT* = 3'i32 ## get meta information - ZIP_SOURCE_ERROR* = 4'i32 ## get error information - constZIP_SOURCE_FREE* = 5'i32 ## cleanup and free resources - -proc zip_add*(para1: PZip, para2: cstring, para3: PZipSource): int32 {.cdecl, - importc: "zip_add", mydll.} -proc zip_add_dir*(para1: PZip, para2: cstring): int32 {.cdecl, - importc: "zip_add_dir", mydll.} -proc zip_close*(para1: PZip) {.cdecl, importc: "zip_close", mydll.} -proc zip_delete*(para1: PZip, para2: int32): int32 {.cdecl, mydll, - importc: "zip_delete".} -proc zip_error_clear*(para1: PZip) {.cdecl, importc: "zip_error_clear", mydll.} -proc zip_error_get*(para1: PZip, para2: ptr int32, para3: ptr int32) {.cdecl, - importc: "zip_error_get", mydll.} -proc zip_error_get_sys_type*(para1: int32): int32 {.cdecl, mydll, - importc: "zip_error_get_sys_type".} -proc zip_error_to_str*(para1: cstring, para2: int, para3: int32, - para4: int32): int32 {.cdecl, mydll, - importc: "zip_error_to_str".} -proc zip_fclose*(para1: PZipFile) {.cdecl, mydll, - importc: "zip_fclose".} -proc zip_file_error_clear*(para1: PZipFile) {.cdecl, mydll, - importc: "zip_file_error_clear".} -proc zip_file_error_get*(para1: PZipFile, para2: ptr int32, para3: ptr int32) {. - cdecl, mydll, importc: "zip_file_error_get".} -proc zip_file_strerror*(para1: PZipFile): cstring {.cdecl, mydll, - importc: "zip_file_strerror".} -proc zip_fopen*(para1: PZip, para2: cstring, para3: int32): PZipFile {.cdecl, - mydll, importc: "zip_fopen".} -proc zip_fopen_index*(para1: PZip, para2: int32, para3: int32): PZipFile {. - cdecl, mydll, importc: "zip_fopen_index".} -proc zip_fread*(para1: PZipFile, para2: pointer, para3: int): int {. - cdecl, mydll, importc: "zip_fread".} -proc zip_get_archive_comment*(para1: PZip, para2: ptr int32, para3: int32): cstring {. - cdecl, mydll, importc: "zip_get_archive_comment".} -proc zip_get_archive_flag*(para1: PZip, para2: int32, para3: int32): int32 {. - cdecl, mydll, importc: "zip_get_archive_flag".} -proc zip_get_file_comment*(para1: PZip, para2: int32, para3: ptr int32, - para4: int32): cstring {.cdecl, mydll, - importc: "zip_get_file_comment".} -proc zip_get_name*(para1: PZip, para2: int32, para3: int32): cstring {.cdecl, - mydll, importc: "zip_get_name".} -proc zip_get_num_files*(para1: PZip): int32 {.cdecl, - mydll, importc: "zip_get_num_files".} -proc zip_name_locate*(para1: PZip, para2: cstring, para3: int32): int32 {.cdecl, - mydll, importc: "zip_name_locate".} -proc zip_open*(para1: cstring, para2: int32, para3: ptr int32): PZip {.cdecl, - mydll, importc: "zip_open".} -proc zip_rename*(para1: PZip, para2: int32, para3: cstring): int32 {.cdecl, - mydll, importc: "zip_rename".} -proc zip_replace*(para1: PZip, para2: int32, para3: PZipSource): int32 {.cdecl, - mydll, importc: "zip_replace".} -proc zip_set_archive_comment*(para1: PZip, para2: cstring, para3: int32): int32 {. - cdecl, mydll, importc: "zip_set_archive_comment".} -proc zip_set_archive_flag*(para1: PZip, para2: int32, para3: int32): int32 {. - cdecl, mydll, importc: "zip_set_archive_flag".} -proc zip_set_file_comment*(para1: PZip, para2: int32, para3: cstring, - para4: int32): int32 {.cdecl, mydll, - importc: "zip_set_file_comment".} -proc zip_source_buffer*(para1: PZip, para2: pointer, para3: int, para4: int32): PZipSource {. - cdecl, mydll, importc: "zip_source_buffer".} -proc zip_source_file*(para1: PZip, para2: cstring, para3: int, para4: int): PZipSource {. - cdecl, mydll, importc: "zip_source_file".} -proc zip_source_filep*(para1: PZip, para2: File, para3: int, para4: int): PZipSource {. - cdecl, mydll, importc: "zip_source_filep".} -proc zip_source_free*(para1: PZipSource) {.cdecl, mydll, - importc: "zip_source_free".} -proc zip_source_function*(para1: PZip, para2: ZipSourceCallback, - para3: pointer): PZipSource {.cdecl, mydll, - importc: "zip_source_function".} -proc zip_source_zip*(para1: PZip, para2: PZip, para3: int32, para4: int32, - para5: int, para6: int): PZipSource {.cdecl, mydll, - importc: "zip_source_zip".} -proc zip_stat*(para1: PZip, para2: cstring, para3: int32, para4: PZipStat): int32 {. - cdecl, mydll, importc: "zip_stat".} -proc zip_stat_index*(para1: PZip, para2: int32, para3: int32, para4: PZipStat): int32 {. - cdecl, mydll, importc: "zip_stat_index".} -proc zip_stat_init*(para1: PZipStat) {.cdecl, mydll, importc: "zip_stat_init".} -proc zip_strerror*(para1: PZip): cstring {.cdecl, mydll, importc: "zip_strerror".} -proc zip_unchange*(para1: PZip, para2: int32): int32 {.cdecl, mydll, - importc: "zip_unchange".} -proc zip_unchange_all*(para1: PZip): int32 {.cdecl, mydll, - importc: "zip_unchange_all".} -proc zip_unchange_archive*(para1: PZip): int32 {.cdecl, mydll, - importc: "zip_unchange_archive".} diff --git a/lib/wrappers/zip/libzip_all.c b/lib/wrappers/zip/libzip_all.c deleted file mode 100644 index 797374b29..000000000 --- a/lib/wrappers/zip/libzip_all.c +++ /dev/null @@ -1,4189 +0,0 @@ -/* - zipint.h -- internal declarations. - Copyright (C) 1999-2008 Dieter Baron and Thomas Klausner - - This file is part of libzip, a library to manipulate ZIP archives. - The authors can be contacted at - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the - distribution. - 3. The names of the authors may not be used to endorse or promote - products derived from this software without specific prior - written permission. - - THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS - OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE - GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER - IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN - IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#include - -/* -#ifdef _MSC_VER -#define ZIP_EXTERN __declspec(dllimport) -#endif -*/ - -/* - zip.h -- exported declarations. - Copyright (C) 1999-2008 Dieter Baron and Thomas Klausner - - This file is part of libzip, a library to manipulate ZIP archives. - The authors can be contacted at - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the - distribution. - 3. The names of the authors may not be used to endorse or promote - products derived from this software without specific prior - written permission. - - THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS - OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE - GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER - IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN - IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - - -#ifndef ZIP_EXTERN -#define ZIP_EXTERN -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -#include -#include -#include - -/* flags for zip_open */ - -#define ZIP_CREATE 1 -#define ZIP_EXCL 2 -#define ZIP_CHECKCONS 4 - - -/* flags for zip_name_locate, zip_fopen, zip_stat, ... */ - -#define ZIP_FL_NOCASE 1 /* ignore case on name lookup */ -#define ZIP_FL_NODIR 2 /* ignore directory component */ -#define ZIP_FL_COMPRESSED 4 /* read compressed data */ -#define ZIP_FL_UNCHANGED 8 /* use original data, ignoring changes */ -#define ZIP_FL_RECOMPRESS 16 /* force recompression of data */ - -/* archive global flags flags */ - -#define ZIP_AFL_TORRENT 1 /* torrent zipped */ - -/* libzip error codes */ - -#define ZIP_ER_OK 0 /* N No error */ -#define ZIP_ER_MULTIDISK 1 /* N Multi-disk zip archives not supported */ -#define ZIP_ER_RENAME 2 /* S Renaming temporary file failed */ -#define ZIP_ER_CLOSE 3 /* S Closing zip archive failed */ -#define ZIP_ER_SEEK 4 /* S Seek error */ -#define ZIP_ER_READ 5 /* S Read error */ -#define ZIP_ER_WRITE 6 /* S Write error */ -#define ZIP_ER_CRC 7 /* N CRC error */ -#define ZIP_ER_ZIPCLOSED 8 /* N Containing zip archive was closed */ -#define ZIP_ER_NOENT 9 /* N No such file */ -#define ZIP_ER_EXISTS 10 /* N File already exists */ -#define ZIP_ER_OPEN 11 /* S Can't open file */ -#define ZIP_ER_TMPOPEN 12 /* S Failure to create temporary file */ -#define ZIP_ER_ZLIB 13 /* Z Zlib error */ -#define ZIP_ER_MEMORY 14 /* N Malloc failure */ -#define ZIP_ER_CHANGED 15 /* N Entry has been changed */ -#define ZIP_ER_COMPNOTSUPP 16 /* N Compression method not supported */ -#define ZIP_ER_EOF 17 /* N Premature EOF */ -#define ZIP_ER_INVAL 18 /* N Invalid argument */ -#define ZIP_ER_NOZIP 19 /* N Not a zip archive */ -#define ZIP_ER_INTERNAL 20 /* N Internal error */ -#define ZIP_ER_INCONS 21 /* N Zip archive inconsistent */ -#define ZIP_ER_REMOVE 22 /* S Can't remove file */ -#define ZIP_ER_DELETED 23 /* N Entry has been deleted */ - - -/* type of system error value */ - -#define ZIP_ET_NONE 0 /* sys_err unused */ -#define ZIP_ET_SYS 1 /* sys_err is errno */ -#define ZIP_ET_ZLIB 2 /* sys_err is zlib error code */ - -/* compression methods */ - -#define ZIP_CM_DEFAULT -1 /* better of deflate or store */ -#define ZIP_CM_STORE 0 /* stored (uncompressed) */ -#define ZIP_CM_SHRINK 1 /* shrunk */ -#define ZIP_CM_REDUCE_1 2 /* reduced with factor 1 */ -#define ZIP_CM_REDUCE_2 3 /* reduced with factor 2 */ -#define ZIP_CM_REDUCE_3 4 /* reduced with factor 3 */ -#define ZIP_CM_REDUCE_4 5 /* reduced with factor 4 */ -#define ZIP_CM_IMPLODE 6 /* imploded */ -/* 7 - Reserved for Tokenizing compression algorithm */ -#define ZIP_CM_DEFLATE 8 /* deflated */ -#define ZIP_CM_DEFLATE64 9 /* deflate64 */ -#define ZIP_CM_PKWARE_IMPLODE 10 /* PKWARE imploding */ -/* 11 - Reserved by PKWARE */ -#define ZIP_CM_BZIP2 12 /* compressed using BZIP2 algorithm */ -/* 13 - Reserved by PKWARE */ -#define ZIP_CM_LZMA 14 /* LZMA (EFS) */ -/* 15-17 - Reserved by PKWARE */ -#define ZIP_CM_TERSE 18 /* compressed using IBM TERSE (new) */ -#define ZIP_CM_LZ77 19 /* IBM LZ77 z Architecture (PFS) */ -#define ZIP_CM_WAVPACK 97 /* WavPack compressed data */ -#define ZIP_CM_PPMD 98 /* PPMd version I, Rev 1 */ - -/* encryption methods */ - -#define ZIP_EM_NONE 0 /* not encrypted */ -#define ZIP_EM_TRAD_PKWARE 1 /* traditional PKWARE encryption */ -#if 0 /* Strong Encryption Header not parsed yet */ -#define ZIP_EM_DES 0x6601 /* strong encryption: DES */ -#define ZIP_EM_RC2_OLD 0x6602 /* strong encryption: RC2, version < 5.2 */ -#define ZIP_EM_3DES_168 0x6603 -#define ZIP_EM_3DES_112 0x6609 -#define ZIP_EM_AES_128 0x660e -#define ZIP_EM_AES_192 0x660f -#define ZIP_EM_AES_256 0x6610 -#define ZIP_EM_RC2 0x6702 /* strong encryption: RC2, version >= 5.2 */ -#define ZIP_EM_RC4 0x6801 -#endif -#define ZIP_EM_UNKNOWN 0xffff /* unknown algorithm */ - -typedef long myoff_t; /* XXX: 64 bit support */ - -enum zip_source_cmd { - ZIP_SOURCE_OPEN, /* prepare for reading */ - ZIP_SOURCE_READ, /* read data */ - ZIP_SOURCE_CLOSE, /* reading is done */ - ZIP_SOURCE_STAT, /* get meta information */ - ZIP_SOURCE_ERROR, /* get error information */ - ZIP_SOURCE_FREE /* cleanup and free resources */ -}; - -typedef ssize_t (*zip_source_callback)(void *state, void *data, - size_t len, enum zip_source_cmd cmd); - -struct zip_stat { - const char *name; /* name of the file */ - int index; /* index within archive */ - unsigned int crc; /* crc of file data */ - time_t mtime; /* modification time */ - myoff_t size; /* size of file (uncompressed) */ - myoff_t comp_size; /* size of file (compressed) */ - unsigned short comp_method; /* compression method used */ - unsigned short encryption_method; /* encryption method used */ -}; - -struct zip; -struct zip_file; -struct zip_source; - - -ZIP_EXTERN int zip_add(struct zip *, const char *, struct zip_source *); -ZIP_EXTERN int zip_add_dir(struct zip *, const char *); -ZIP_EXTERN int zip_close(struct zip *); -ZIP_EXTERN int zip_delete(struct zip *, int); -ZIP_EXTERN void zip_error_clear(struct zip *); -ZIP_EXTERN void zip_error_get(struct zip *, int *, int *); -ZIP_EXTERN int zip_error_get_sys_type(int); -ZIP_EXTERN int zip_error_to_str(char *, size_t, int, int); -ZIP_EXTERN int zip_fclose(struct zip_file *); -ZIP_EXTERN void zip_file_error_clear(struct zip_file *); -ZIP_EXTERN void zip_file_error_get(struct zip_file *, int *, int *); -ZIP_EXTERN const char *zip_file_strerror(struct zip_file *); -ZIP_EXTERN struct zip_file *zip_fopen(struct zip *, const char *, int); -ZIP_EXTERN struct zip_file *zip_fopen_index(struct zip *, int, int); -ZIP_EXTERN ssize_t zip_fread(struct zip_file *, void *, size_t); -ZIP_EXTERN const char *zip_get_archive_comment(struct zip *, int *, int); -ZIP_EXTERN int zip_get_archive_flag(struct zip *, int, int); -ZIP_EXTERN const char *zip_get_file_comment(struct zip *, int, int *, int); -ZIP_EXTERN const char *zip_get_name(struct zip *, int, int); -ZIP_EXTERN int zip_get_num_files(struct zip *); -ZIP_EXTERN int zip_name_locate(struct zip *, const char *, int); -ZIP_EXTERN struct zip *zip_open(const char *, int, int *); -ZIP_EXTERN int zip_rename(struct zip *, int, const char *); -ZIP_EXTERN int zip_replace(struct zip *, int, struct zip_source *); -ZIP_EXTERN int zip_set_archive_comment(struct zip *, const char *, int); -ZIP_EXTERN int zip_set_archive_flag(struct zip *, int, int); -ZIP_EXTERN int zip_set_file_comment(struct zip *, int, const char *, int); -ZIP_EXTERN struct zip_source *zip_source_buffer(struct zip *, const void *, - myoff_t, int); -ZIP_EXTERN struct zip_source *zip_source_file(struct zip *, const char *, - myoff_t, myoff_t); -ZIP_EXTERN struct zip_source *zip_source_filep(struct zip *, FILE *, - myoff_t, myoff_t); -ZIP_EXTERN void zip_source_free(struct zip_source *); -ZIP_EXTERN struct zip_source *zip_source_function(struct zip *, - zip_source_callback, void *); -ZIP_EXTERN struct zip_source *zip_source_zip(struct zip *, struct zip *, - int, int, myoff_t, myoff_t); -ZIP_EXTERN int zip_stat(struct zip *, const char *, int, struct zip_stat *); -ZIP_EXTERN int zip_stat_index(struct zip *, int, int, struct zip_stat *); -ZIP_EXTERN void zip_stat_init(struct zip_stat *); -ZIP_EXTERN const char *zip_strerror(struct zip *); -ZIP_EXTERN int zip_unchange(struct zip *, int); -ZIP_EXTERN int zip_unchange_all(struct zip *); -ZIP_EXTERN int zip_unchange_archive(struct zip *); - -#ifdef __cplusplus -} -#endif - - -/* config.h. Generated from config.h.in by configure. */ -/* config.h.in. Generated from configure.ac by autoheader. */ - -/* Define to 1 if you have the declaration of `tzname', and to 0 if you don't. - */ -/* #undef HAVE_DECL_TZNAME */ - -#define HAVE_CONFIG_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_DLFCN_H 1 - -/* Define to 1 if you have the `fseeko' function. */ -#define HAVE_FSEEKO 1 - -/* Define to 1 if you have the `ftello' function. */ -#define HAVE_FTELLO 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_INTTYPES_H 1 - -/* Define to 1 if you have the `z' library (-lz). */ -#define HAVE_LIBZ 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_MEMORY_H 1 - -/* Define to 1 if you have the `mkstemp' function. */ -#define HAVE_MKSTEMP 1 - -/* Define to 1 if you have the `MoveFileExA' function. */ -/* #undef HAVE_MOVEFILEEXA */ - -/* Define to 1 if you have the header file. */ -#define HAVE_STDINT_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_STDLIB_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_STRINGS_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_STRING_H 1 - -/* Define to 1 if `tm_zone' is member of `struct tm'. */ -#define HAVE_STRUCT_TM_TM_ZONE 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_SYS_STAT_H 1 - -/* Define to 1 if you have the header file. */ -#define HAVE_SYS_TYPES_H 1 - -/* Define to 1 if your `struct tm' has `tm_zone'. Deprecated, use - `HAVE_STRUCT_TM_TM_ZONE' instead. */ -#define HAVE_TM_ZONE 1 - -/* Define to 1 if you don't have `tm_zone' but do have the external array - `tzname'. */ -/* #undef HAVE_TZNAME */ - -/* Define to 1 if you have the header file. */ -#define HAVE_UNISTD_H 1 - -/* Define to 1 if your C compiler doesn't accept -c and -o together. */ -/* #undef NO_MINUS_C_MINUS_O */ - -/* Name of package */ -#define PACKAGE "libzip" - -/* Define to the address where bug reports for this package should be sent. */ -#define PACKAGE_BUGREPORT "libzip@nih.at" - -/* Define to the full name of this package. */ -#define PACKAGE_NAME "libzip" - -/* Define to the full name and version of this package. */ -#define PACKAGE_STRING "libzip 0.9" - -/* Define to the one symbol short name of this package. */ -#define PACKAGE_TARNAME "libzip" - -/* Define to the version of this package. */ -#define PACKAGE_VERSION "0.9" - -/* Define to 1 if you have the ANSI C header files. */ -#define STDC_HEADERS 1 - -/* Define to 1 if your declares `struct tm'. */ -/* #undef TM_IN_SYS_TIME */ - -/* Version number of package */ -#define VERSION "0.9" - - -#ifndef HAVE_MKSTEMP -int _zip_mkstemp(char *); -#define mkstemp _zip_mkstemp -#endif - -#ifdef HAVE_MOVEFILEEXA -#include -#define _zip_rename(s, t) \ - (!MoveFileExA((s), (t), \ - MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING)) -#else -#define _zip_rename rename -#endif - -#ifndef HAVE_FSEEKO -#define fseeko(s, o, w) (fseek((s), (long int)(o), (w))) -#endif -#ifndef HAVE_FTELLO -#define ftello(s) ((long)ftell((s))) -#endif - - -#define CENTRAL_MAGIC "PK\1\2" -#define LOCAL_MAGIC "PK\3\4" -#define EOCD_MAGIC "PK\5\6" -#define DATADES_MAGIC "PK\7\8" -#define TORRENT_SIG "TORRENTZIPPED-" -#define TORRENT_SIG_LEN 14 -#define TORRENT_CRC_LEN 8 -#define TORRENT_MEM_LEVEL 8 -#define CDENTRYSIZE 46u -#define LENTRYSIZE 30 -#define MAXCOMLEN 65536 -#define EOCDLEN 22 -#define CDBUFSIZE (MAXCOMLEN+EOCDLEN) -#define BUFSIZE 8192 - - -/* state of change of a file in zip archive */ - -enum zip_state { ZIP_ST_UNCHANGED, ZIP_ST_DELETED, ZIP_ST_REPLACED, - ZIP_ST_ADDED, ZIP_ST_RENAMED }; - -/* constants for struct zip_file's member flags */ - -#define ZIP_ZF_EOF 1 /* EOF reached */ -#define ZIP_ZF_DECOMP 2 /* decompress data */ -#define ZIP_ZF_CRC 4 /* compute and compare CRC */ - -/* directory entry: general purpose bit flags */ - -#define ZIP_GPBF_ENCRYPTED 0x0001 /* is encrypted */ -#define ZIP_GPBF_DATA_DESCRIPTOR 0x0008 /* crc/size after file data */ -#define ZIP_GPBF_STRONG_ENCRYPTION 0x0040 /* uses strong encryption */ - -/* error information */ - -struct zip_error { - int zip_err; /* libzip error code (ZIP_ER_*) */ - int sys_err; /* copy of errno (E*) or zlib error code */ - char *str; /* string representation or NULL */ -}; - -/* zip archive, part of API */ - -struct zip { - char *zn; /* file name */ - FILE *zp; /* file */ - struct zip_error error; /* error information */ - - unsigned int flags; /* archive global flags */ - unsigned int ch_flags; /* changed archive global flags */ - - struct zip_cdir *cdir; /* central directory */ - char *ch_comment; /* changed archive comment */ - int ch_comment_len; /* length of changed zip archive - * comment, -1 if unchanged */ - int nentry; /* number of entries */ - int nentry_alloc; /* number of entries allocated */ - struct zip_entry *entry; /* entries */ - int nfile; /* number of opened files within archive */ - int nfile_alloc; /* number of files allocated */ - struct zip_file **file; /* opened files within archive */ -}; - -/* file in zip archive, part of API */ - -struct zip_file { - struct zip *za; /* zip archive containing this file */ - struct zip_error error; /* error information */ - int flags; /* -1: eof, >0: error */ - - int method; /* compression method */ - myoff_t fpos; /* position within zip file (fread/fwrite) */ - unsigned long bytes_left; /* number of bytes left to read */ - unsigned long cbytes_left; /* number of bytes of compressed data left */ - - unsigned long crc; /* CRC so far */ - unsigned long crc_orig; /* CRC recorded in archive */ - - char *buffer; - z_stream *zstr; -}; - -/* zip archive directory entry (central or local) */ - -struct zip_dirent { - unsigned short version_madeby; /* (c) version of creator */ - unsigned short version_needed; /* (cl) version needed to extract */ - unsigned short bitflags; /* (cl) general purpose bit flag */ - unsigned short comp_method; /* (cl) compression method used */ - time_t last_mod; /* (cl) time of last modification */ - unsigned int crc; /* (cl) CRC-32 of uncompressed data */ - unsigned int comp_size; /* (cl) size of commpressed data */ - unsigned int uncomp_size; /* (cl) size of uncommpressed data */ - char *filename; /* (cl) file name (NUL-terminated) */ - unsigned short filename_len; /* (cl) length of filename (w/o NUL) */ - char *extrafield; /* (cl) extra field */ - unsigned short extrafield_len; /* (cl) length of extra field */ - char *comment; /* (c) file comment */ - unsigned short comment_len; /* (c) length of file comment */ - unsigned short disk_number; /* (c) disk number start */ - unsigned short int_attrib; /* (c) internal file attributes */ - unsigned int ext_attrib; /* (c) external file attributes */ - unsigned int offset; /* (c) offset of local header */ -}; - -/* zip archive central directory */ - -struct zip_cdir { - struct zip_dirent *entry; /* directory entries */ - int nentry; /* number of entries */ - - unsigned int size; /* size of central direcotry */ - unsigned int offset; /* offset of central directory in file */ - char *comment; /* zip archive comment */ - unsigned short comment_len; /* length of zip archive comment */ -}; - - - -struct zip_source { - zip_source_callback f; - void *ud; -}; - -/* entry in zip archive directory */ - -struct zip_entry { - enum zip_state state; - struct zip_source *source; - char *ch_filename; - char *ch_comment; - int ch_comment_len; -}; - - - -extern const char * const _zip_err_str[]; -extern const int _zip_nerr_str; -extern const int _zip_err_type[]; - - - -#define ZIP_ENTRY_DATA_CHANGED(x) \ - ((x)->state == ZIP_ST_REPLACED \ - || (x)->state == ZIP_ST_ADDED) - - - -int _zip_cdir_compute_crc(struct zip *, uLong *); -void _zip_cdir_free(struct zip_cdir *); -struct zip_cdir *_zip_cdir_new(int, struct zip_error *); -int _zip_cdir_write(struct zip_cdir *, FILE *, struct zip_error *); - -void _zip_dirent_finalize(struct zip_dirent *); -void _zip_dirent_init(struct zip_dirent *); -int _zip_dirent_read(struct zip_dirent *, FILE *, - unsigned char **, unsigned int, int, struct zip_error *); -void _zip_dirent_torrent_normalize(struct zip_dirent *); -int _zip_dirent_write(struct zip_dirent *, FILE *, int, struct zip_error *); - -void _zip_entry_free(struct zip_entry *); -void _zip_entry_init(struct zip *, int); -struct zip_entry *_zip_entry_new(struct zip *); - -void _zip_error_clear(struct zip_error *); -void _zip_error_copy(struct zip_error *, struct zip_error *); -void _zip_error_fini(struct zip_error *); -void _zip_error_get(struct zip_error *, int *, int *); -void _zip_error_init(struct zip_error *); -void _zip_error_set(struct zip_error *, int, int); -const char *_zip_error_strerror(struct zip_error *); - -int _zip_file_fillbuf(void *, size_t, struct zip_file *); -unsigned int _zip_file_get_offset(struct zip *, int); - -int _zip_filerange_crc(FILE *, myoff_t, myoff_t, uLong *, struct zip_error *); - -struct zip_source *_zip_source_file_or_p(struct zip *, const char *, FILE *, - myoff_t, myoff_t); - -void _zip_free(struct zip *); -const char *_zip_get_name(struct zip *, int, int, struct zip_error *); -int _zip_local_header_read(struct zip *, int); -void *_zip_memdup(const void *, size_t, struct zip_error *); -int _zip_name_locate(struct zip *, const char *, int, struct zip_error *); -struct zip *_zip_new(struct zip_error *); -unsigned short _zip_read2(unsigned char **); -unsigned int _zip_read4(unsigned char **); -int _zip_replace(struct zip *, int, const char *, struct zip_source *); -int _zip_set_name(struct zip *, int, const char *); -int _zip_unchange(struct zip *, int, int); -void _zip_unchange_data(struct zip_entry *); - - -#include -#include -#include -#include - -const char * -_zip_error_strerror(struct zip_error *err) -{ - const char *zs, *ss; - char buf[128], *s; - - _zip_error_fini(err); - - if (err->zip_err < 0 || err->zip_err >= _zip_nerr_str) { - sprintf(buf, "Unknown error %d", err->zip_err); - zs = NULL; - ss = buf; - } - else { - zs = _zip_err_str[err->zip_err]; - - switch (_zip_err_type[err->zip_err]) { - case ZIP_ET_SYS: - ss = strerror(err->sys_err); - break; - - case ZIP_ET_ZLIB: - ss = zError(err->sys_err); - break; - - default: - ss = NULL; - } - } - - if (ss == NULL) - return zs; - else { - if ((s=(char *)malloc(strlen(ss) - + (zs ? strlen(zs)+2 : 0) + 1)) == NULL) - return _zip_err_str[ZIP_ER_MEMORY]; - - sprintf(s, "%s%s%s", - (zs ? zs : ""), - (zs ? ": " : ""), - ss); - err->str = s; - - return s; - } -} - -#include - - - -void -_zip_error_clear(struct zip_error *err) -{ - err->zip_err = ZIP_ER_OK; - err->sys_err = 0; -} - - - -void -_zip_error_copy(struct zip_error *dst, struct zip_error *src) -{ - dst->zip_err = src->zip_err; - dst->sys_err = src->sys_err; -} - - - -void -_zip_error_fini(struct zip_error *err) -{ - free(err->str); - err->str = NULL; -} - - - -void -_zip_error_get(struct zip_error *err, int *zep, int *sep) -{ - if (zep) - *zep = err->zip_err; - if (sep) { - if (zip_error_get_sys_type(err->zip_err) != ZIP_ET_NONE) - *sep = err->sys_err; - else - *sep = 0; - } -} - - - -void -_zip_error_init(struct zip_error *err) -{ - err->zip_err = ZIP_ER_OK; - err->sys_err = 0; - err->str = NULL; -} - - - -void -_zip_error_set(struct zip_error *err, int ze, int se) -{ - if (err) { - err->zip_err = ze; - err->sys_err = se; - } -} - - -#include -#include - -#include -#include -#include -#include -#include -#include - -#ifndef O_BINARY -#define O_BINARY 0 -#endif - - - -int -_zip_mkstemp(char *path) -{ - int fd; - char *start, *trv; - struct stat sbuf; - pid_t pid; - - /* To guarantee multiple calls generate unique names even if - the file is not created. 676 different possibilities with 7 - or more X's, 26 with 6 or less. */ - static char xtra[2] = "aa"; - int xcnt = 0; - - pid = getpid(); - - /* Move to end of path and count trailing X's. */ - for (trv = path; *trv; ++trv) - if (*trv == 'X') - xcnt++; - else - xcnt = 0; - - /* Use at least one from xtra. Use 2 if more than 6 X's. */ - if (*(trv - 1) == 'X') - *--trv = xtra[0]; - if (xcnt > 6 && *(trv - 1) == 'X') - *--trv = xtra[1]; - - /* Set remaining X's to pid digits with 0's to the left. */ - while (*--trv == 'X') { - *trv = (pid % 10) + '0'; - pid /= 10; - } - - /* update xtra for next call. */ - if (xtra[0] != 'z') - xtra[0]++; - else { - xtra[0] = 'a'; - if (xtra[1] != 'z') - xtra[1]++; - else - xtra[1] = 'a'; - } - - /* - * check the target directory; if you have six X's and it - * doesn't exist this runs for a *very* long time. - */ - for (start = trv + 1;; --trv) { - if (trv <= path) - break; - if (*trv == '/') { - *trv = '\0'; - if (stat(path, &sbuf)) - return (0); - if (!S_ISDIR(sbuf.st_mode)) { - errno = ENOTDIR; - return (0); - } - *trv = '/'; - break; - } - } - - for (;;) { - if ((fd=open(path, O_CREAT|O_EXCL|O_RDWR|O_BINARY, 0600)) >= 0) - return (fd); - if (errno != EEXIST) - return (0); - - /* tricky little algorithm for backward compatibility */ - for (trv = start;;) { - if (!*trv) - return (0); - if (*trv == 'z') - *trv++ = 'a'; - else { - if (isdigit((unsigned char)*trv)) - *trv = 'a'; - else - ++*trv; - break; - } - } - } - /*NOTREACHED*/ -} - - -#include -#include -#include -#include -#include -#include - -static time_t _zip_d2u_time(int, int); -static char *_zip_readfpstr(FILE *, unsigned int, int, struct zip_error *); -static char *_zip_readstr(unsigned char **, int, int, struct zip_error *); -static void _zip_u2d_time(time_t, unsigned short *, unsigned short *); -static void _zip_write2(unsigned short, FILE *); -static void _zip_write4(unsigned int, FILE *); - - - -void -_zip_cdir_free(struct zip_cdir *cd) -{ - int i; - - if (!cd) - return; - - for (i=0; inentry; i++) - _zip_dirent_finalize(cd->entry+i); - free(cd->comment); - free(cd->entry); - free(cd); -} - - - -struct zip_cdir * -_zip_cdir_new(int nentry, struct zip_error *error) -{ - struct zip_cdir *cd; - - if ((cd=(struct zip_cdir *)malloc(sizeof(*cd))) == NULL) { - _zip_error_set(error, ZIP_ER_MEMORY, 0); - return NULL; - } - - if ((cd->entry=(struct zip_dirent *)malloc(sizeof(*(cd->entry))*nentry)) - == NULL) { - _zip_error_set(error, ZIP_ER_MEMORY, 0); - free(cd); - return NULL; - } - - /* entries must be initialized by caller */ - - cd->nentry = nentry; - cd->size = cd->offset = 0; - cd->comment = NULL; - cd->comment_len = 0; - - return cd; -} - - - -int -_zip_cdir_write(struct zip_cdir *cd, FILE *fp, struct zip_error *error) -{ - int i; - - cd->offset = ftello(fp); - - for (i=0; inentry; i++) { - if (_zip_dirent_write(cd->entry+i, fp, 0, error) != 0) - return -1; - } - - cd->size = ftello(fp) - cd->offset; - - /* clearerr(fp); */ - fwrite(EOCD_MAGIC, 1, 4, fp); - _zip_write4(0, fp); - _zip_write2((unsigned short)cd->nentry, fp); - _zip_write2((unsigned short)cd->nentry, fp); - _zip_write4(cd->size, fp); - _zip_write4(cd->offset, fp); - _zip_write2(cd->comment_len, fp); - fwrite(cd->comment, 1, cd->comment_len, fp); - - if (ferror(fp)) { - _zip_error_set(error, ZIP_ER_WRITE, errno); - return -1; - } - - return 0; -} - - - -void -_zip_dirent_finalize(struct zip_dirent *zde) -{ - free(zde->filename); - zde->filename = NULL; - free(zde->extrafield); - zde->extrafield = NULL; - free(zde->comment); - zde->comment = NULL; -} - - - -void -_zip_dirent_init(struct zip_dirent *de) -{ - de->version_madeby = 0; - de->version_needed = 20; /* 2.0 */ - de->bitflags = 0; - de->comp_method = 0; - de->last_mod = 0; - de->crc = 0; - de->comp_size = 0; - de->uncomp_size = 0; - de->filename = NULL; - de->filename_len = 0; - de->extrafield = NULL; - de->extrafield_len = 0; - de->comment = NULL; - de->comment_len = 0; - de->disk_number = 0; - de->int_attrib = 0; - de->ext_attrib = 0; - de->offset = 0; -} - - - -/* _zip_dirent_read(zde, fp, bufp, left, localp, error): - Fills the zip directory entry zde. - - If bufp is non-NULL, data is taken from there and bufp is advanced - by the amount of data used; no more than left bytes are used. - Otherwise data is read from fp as needed. - - If localp != 0, it reads a local header instead of a central - directory entry. - - Returns 0 if successful. On error, error is filled in and -1 is - returned. -*/ - -int -_zip_dirent_read(struct zip_dirent *zde, FILE *fp, - unsigned char **bufp, unsigned int left, int localp, - struct zip_error *error) -{ - unsigned char buf[CDENTRYSIZE]; - unsigned char *cur; - unsigned short dostime, dosdate; - unsigned int size; - - if (localp) - size = LENTRYSIZE; - else - size = CDENTRYSIZE; - - if (bufp) { - /* use data from buffer */ - cur = *bufp; - if (left < size) { - _zip_error_set(error, ZIP_ER_NOZIP, 0); - return -1; - } - } - else { - /* read entry from disk */ - if ((fread(buf, 1, size, fp)version_madeby = _zip_read2(&cur); - else - zde->version_madeby = 0; - zde->version_needed = _zip_read2(&cur); - zde->bitflags = _zip_read2(&cur); - zde->comp_method = _zip_read2(&cur); - - /* convert to time_t */ - dostime = _zip_read2(&cur); - dosdate = _zip_read2(&cur); - zde->last_mod = _zip_d2u_time(dostime, dosdate); - - zde->crc = _zip_read4(&cur); - zde->comp_size = _zip_read4(&cur); - zde->uncomp_size = _zip_read4(&cur); - - zde->filename_len = _zip_read2(&cur); - zde->extrafield_len = _zip_read2(&cur); - - if (localp) { - zde->comment_len = 0; - zde->disk_number = 0; - zde->int_attrib = 0; - zde->ext_attrib = 0; - zde->offset = 0; - } else { - zde->comment_len = _zip_read2(&cur); - zde->disk_number = _zip_read2(&cur); - zde->int_attrib = _zip_read2(&cur); - zde->ext_attrib = _zip_read4(&cur); - zde->offset = _zip_read4(&cur); - } - - zde->filename = NULL; - zde->extrafield = NULL; - zde->comment = NULL; - - if (bufp) { - if (left < CDENTRYSIZE + (zde->filename_len+zde->extrafield_len - +zde->comment_len)) { - _zip_error_set(error, ZIP_ER_NOZIP, 0); - return -1; - } - - if (zde->filename_len) { - zde->filename = _zip_readstr(&cur, zde->filename_len, 1, error); - if (!zde->filename) - return -1; - } - - if (zde->extrafield_len) { - zde->extrafield = _zip_readstr(&cur, zde->extrafield_len, 0, - error); - if (!zde->extrafield) - return -1; - } - - if (zde->comment_len) { - zde->comment = _zip_readstr(&cur, zde->comment_len, 0, error); - if (!zde->comment) - return -1; - } - } - else { - if (zde->filename_len) { - zde->filename = _zip_readfpstr(fp, zde->filename_len, 1, error); - if (!zde->filename) - return -1; - } - - if (zde->extrafield_len) { - zde->extrafield = _zip_readfpstr(fp, zde->extrafield_len, 0, - error); - if (!zde->extrafield) - return -1; - } - - if (zde->comment_len) { - zde->comment = _zip_readfpstr(fp, zde->comment_len, 0, error); - if (!zde->comment) - return -1; - } - } - - if (bufp) - *bufp = cur; - - return 0; -} - - - -/* _zip_dirent_torrent_normalize(de); - Set values suitable for torrentzip. -*/ - -void -_zip_dirent_torrent_normalize(struct zip_dirent *de) -{ - static struct tm torrenttime; - static time_t last_mod = 0; - - if (last_mod == 0) { -#ifdef HAVE_STRUCT_TM_TM_ZONE - time_t now; - struct tm *l; -#endif - - torrenttime.tm_sec = 0; - torrenttime.tm_min = 32; - torrenttime.tm_hour = 23; - torrenttime.tm_mday = 24; - torrenttime.tm_mon = 11; - torrenttime.tm_year = 96; - torrenttime.tm_wday = 0; - torrenttime.tm_yday = 0; - torrenttime.tm_isdst = 0; - -#ifdef HAVE_STRUCT_TM_TM_ZONE - time(&now); - l = localtime(&now); - torrenttime.tm_gmtoff = l->tm_gmtoff; - torrenttime.tm_zone = l->tm_zone; -#endif - - last_mod = mktime(&torrenttime); - } - - de->version_madeby = 0; - de->version_needed = 20; /* 2.0 */ - de->bitflags = 2; /* maximum compression */ - de->comp_method = ZIP_CM_DEFLATE; - de->last_mod = last_mod; - - de->disk_number = 0; - de->int_attrib = 0; - de->ext_attrib = 0; - de->offset = 0; - - free(de->extrafield); - de->extrafield = NULL; - de->extrafield_len = 0; - free(de->comment); - de->comment = NULL; - de->comment_len = 0; -} - - - -/* _zip_dirent_write(zde, fp, localp, error): - Writes zip directory entry zde to file fp. - - If localp != 0, it writes a local header instead of a central - directory entry. - - Returns 0 if successful. On error, error is filled in and -1 is - returned. -*/ - -int -_zip_dirent_write(struct zip_dirent *zde, FILE *fp, int localp, - struct zip_error *error) -{ - unsigned short dostime, dosdate; - - fwrite(localp ? LOCAL_MAGIC : CENTRAL_MAGIC, 1, 4, fp); - - if (!localp) - _zip_write2(zde->version_madeby, fp); - _zip_write2(zde->version_needed, fp); - _zip_write2(zde->bitflags, fp); - _zip_write2(zde->comp_method, fp); - - _zip_u2d_time(zde->last_mod, &dostime, &dosdate); - _zip_write2(dostime, fp); - _zip_write2(dosdate, fp); - - _zip_write4(zde->crc, fp); - _zip_write4(zde->comp_size, fp); - _zip_write4(zde->uncomp_size, fp); - - _zip_write2(zde->filename_len, fp); - _zip_write2(zde->extrafield_len, fp); - - if (!localp) { - _zip_write2(zde->comment_len, fp); - _zip_write2(zde->disk_number, fp); - _zip_write2(zde->int_attrib, fp); - _zip_write4(zde->ext_attrib, fp); - _zip_write4(zde->offset, fp); - } - - if (zde->filename_len) - fwrite(zde->filename, 1, zde->filename_len, fp); - - if (zde->extrafield_len) - fwrite(zde->extrafield, 1, zde->extrafield_len, fp); - - if (!localp) { - if (zde->comment_len) - fwrite(zde->comment, 1, zde->comment_len, fp); - } - - if (ferror(fp)) { - _zip_error_set(error, ZIP_ER_WRITE, errno); - return -1; - } - - return 0; -} - - - -static time_t -_zip_d2u_time(int dtime, int ddate) -{ - struct tm *tm; - time_t now; - - now = time(NULL); - tm = localtime(&now); - /* let mktime decide if DST is in effect */ - tm->tm_isdst = -1; - - tm->tm_year = ((ddate>>9)&127) + 1980 - 1900; - tm->tm_mon = ((ddate>>5)&15) - 1; - tm->tm_mday = ddate&31; - - tm->tm_hour = (dtime>>11)&31; - tm->tm_min = (dtime>>5)&63; - tm->tm_sec = (dtime<<1)&62; - - return mktime(tm); -} - - - -unsigned short -_zip_read2(unsigned char **a) -{ - unsigned short ret; - - ret = (*a)[0]+((*a)[1]<<8); - *a += 2; - - return ret; -} - - - -unsigned int -_zip_read4(unsigned char **a) -{ - unsigned int ret; - - ret = ((((((*a)[3]<<8)+(*a)[2])<<8)+(*a)[1])<<8)+(*a)[0]; - *a += 4; - - return ret; -} - - - -static char * -_zip_readfpstr(FILE *fp, unsigned int len, int nulp, struct zip_error *error) -{ - char *r, *o; - - r = (char *)malloc(nulp ? len+1 : len); - if (!r) { - _zip_error_set(error, ZIP_ER_MEMORY, 0); - return NULL; - } - - if (fread(r, 1, len, fp)>8)&0xff, fp); - - return; -} - - - -static void -_zip_write4(unsigned int i, FILE *fp) -{ - putc(i&0xff, fp); - putc((i>>8)&0xff, fp); - putc((i>>16)&0xff, fp); - putc((i>>24)&0xff, fp); - - return; -} - - - -static void -_zip_u2d_time(time_t time, unsigned short *dtime, unsigned short *ddate) -{ - struct tm *tm; - - tm = localtime(&time); - *ddate = ((tm->tm_year+1900-1980)<<9) + ((tm->tm_mon+1)<<5) - + tm->tm_mday; - *dtime = ((tm->tm_hour)<<11) + ((tm->tm_min)<<5) - + ((tm->tm_sec)>>1); - - return; -} - - - -ZIP_EXTERN int -zip_delete(struct zip *za, int idx) -{ - if (idx < 0 || idx >= za->nentry) { - _zip_error_set(&za->error, ZIP_ER_INVAL, 0); - return -1; - } - - /* allow duplicate file names, because the file will - * be removed directly afterwards */ - if (_zip_unchange(za, idx, 1) != 0) - return -1; - - za->entry[idx].state = ZIP_ST_DELETED; - - return 0; -} - - - -ZIP_EXTERN void -zip_error_clear(struct zip *za) -{ - _zip_error_clear(&za->error); -} - - -ZIP_EXTERN int -zip_add(struct zip *za, const char *name, struct zip_source *source) -{ - if (name == NULL || source == NULL) { - _zip_error_set(&za->error, ZIP_ER_INVAL, 0); - return -1; - } - - return _zip_replace(za, -1, name, source); -} - - -ZIP_EXTERN int -zip_error_get_sys_type(int ze) -{ - if (ze < 0 || ze >= _zip_nerr_str) - return 0; - - return _zip_err_type[ze]; -} - - -ZIP_EXTERN void -zip_error_get(struct zip *za, int *zep, int *sep) -{ - _zip_error_get(&za->error, zep, sep); -} - - -const char * const _zip_err_str[] = { - "No error", - "Multi-disk zip archives not supported", - "Renaming temporary file failed", - "Closing zip archive failed", - "Seek error", - "Read error", - "Write error", - "CRC error", - "Containing zip archive was closed", - "No such file", - "File already exists", - "Can't open file", - "Failure to create temporary file", - "Zlib error", - "Malloc failure", - "Entry has been changed", - "Compression method not supported", - "Premature EOF", - "Invalid argument", - "Not a zip archive", - "Internal error", - "Zip archive inconsistent", - "Can't remove file", - "Entry has been deleted", -}; - -const int _zip_nerr_str = sizeof(_zip_err_str)/sizeof(_zip_err_str[0]); - -#define N ZIP_ET_NONE -#define S ZIP_ET_SYS -#define Z ZIP_ET_ZLIB - -const int _zip_err_type[] = { - N, - N, - S, - S, - S, - S, - S, - N, - N, - N, - N, - S, - S, - Z, - N, - N, - N, - N, - N, - N, - N, - N, - S, - N, -}; - - -struct zip_entry * -_zip_entry_new(struct zip *za) -{ - struct zip_entry *ze; - if (!za) { - ze = (struct zip_entry *)malloc(sizeof(struct zip_entry)); - if (!ze) { - _zip_error_set(&za->error, ZIP_ER_MEMORY, 0); - return NULL; - } - } - else { - if (za->nentry >= za->nentry_alloc-1) { - za->nentry_alloc += 16; - za->entry = (struct zip_entry *)realloc(za->entry, - sizeof(struct zip_entry) - * za->nentry_alloc); - if (!za->entry) { - _zip_error_set(&za->error, ZIP_ER_MEMORY, 0); - return NULL; - } - } - ze = za->entry+za->nentry; - } - - ze->state = ZIP_ST_UNCHANGED; - - ze->ch_filename = NULL; - ze->ch_comment = NULL; - ze->ch_comment_len = -1; - ze->source = NULL; - - if (za) - za->nentry++; - - return ze; -} - - -void -_zip_entry_free(struct zip_entry *ze) -{ - free(ze->ch_filename); - ze->ch_filename = NULL; - free(ze->ch_comment); - ze->ch_comment = NULL; - ze->ch_comment_len = -1; - - _zip_unchange_data(ze); -} - - -static int add_data(struct zip *, struct zip_source *, struct zip_dirent *, - FILE *); -static int add_data_comp(zip_source_callback, void *, struct zip_stat *, - FILE *, struct zip_error *); -static int add_data_uncomp(struct zip *, zip_source_callback, void *, - struct zip_stat *, FILE *); -static void ch_set_error(struct zip_error *, zip_source_callback, void *); -static int copy_data(FILE *, myoff_t, FILE *, struct zip_error *); -static int write_cdir(struct zip *, struct zip_cdir *, FILE *); -static int _zip_cdir_set_comment(struct zip_cdir *, struct zip *); -static int _zip_changed(struct zip *, int *); -static char *_zip_create_temp_output(struct zip *, FILE **); -static int _zip_torrentzip_cmp(const void *, const void *); - - - -struct filelist { - int idx; - const char *name; -}; - - - -ZIP_EXTERN int -zip_close(struct zip *za) -{ - int survivors; - int i, j, error; - char *temp; - FILE *out; - mode_t mask; - struct zip_cdir *cd; - struct zip_dirent de; - struct filelist *filelist; - int reopen_on_error; - int new_torrentzip; - - reopen_on_error = 0; - - if (za == NULL) - return -1; - - if (!_zip_changed(za, &survivors)) { - _zip_free(za); - return 0; - } - - /* don't create zip files with no entries */ - if (survivors == 0) { - if (za->zn && za->zp) { - if (remove(za->zn) != 0) { - _zip_error_set(&za->error, ZIP_ER_REMOVE, errno); - return -1; - } - } - _zip_free(za); - return 0; - } - - if ((filelist=(struct filelist *)malloc(sizeof(filelist[0])*survivors)) - == NULL) - return -1; - - if ((cd=_zip_cdir_new(survivors, &za->error)) == NULL) { - free(filelist); - return -1; - } - - for (i=0; ientry[i]); - - /* archive comment is special for torrentzip */ - if (zip_get_archive_flag(za, ZIP_AFL_TORRENT, 0)) { - cd->comment = _zip_memdup(TORRENT_SIG "XXXXXXXX", - TORRENT_SIG_LEN + TORRENT_CRC_LEN, - &za->error); - if (cd->comment == NULL) { - _zip_cdir_free(cd); - free(filelist); - return -1; - } - cd->comment_len = TORRENT_SIG_LEN + TORRENT_CRC_LEN; - } - else if (zip_get_archive_flag(za, ZIP_AFL_TORRENT, ZIP_FL_UNCHANGED) == 0) { - if (_zip_cdir_set_comment(cd, za) == -1) { - _zip_cdir_free(cd); - free(filelist); - return -1; - } - } - - if ((temp=_zip_create_temp_output(za, &out)) == NULL) { - _zip_cdir_free(cd); - return -1; - } - - - /* create list of files with index into original archive */ - for (i=j=0; inentry; i++) { - if (za->entry[i].state == ZIP_ST_DELETED) - continue; - - filelist[j].idx = i; - filelist[j].name = zip_get_name(za, i, 0); - j++; - } - if (zip_get_archive_flag(za, ZIP_AFL_TORRENT, 0)) - qsort(filelist, survivors, sizeof(filelist[0]), - _zip_torrentzip_cmp); - - new_torrentzip = (zip_get_archive_flag(za, ZIP_AFL_TORRENT, 0) == 1 - && zip_get_archive_flag(za, ZIP_AFL_TORRENT, - ZIP_FL_UNCHANGED) == 0); - error = 0; - for (j=0; jentry+i) || new_torrentzip) { - _zip_dirent_init(&de); - - if (zip_get_archive_flag(za, ZIP_AFL_TORRENT, 0)) - _zip_dirent_torrent_normalize(&de); - - /* use it as central directory entry */ - memcpy(cd->entry+j, &de, sizeof(cd->entry[j])); - - /* set/update file name */ - if (za->entry[i].ch_filename == NULL) { - if (za->entry[i].state == ZIP_ST_ADDED) { - de.filename = strdup("-"); - de.filename_len = 1; - cd->entry[j].filename = "-"; - } - else { - de.filename = strdup(za->cdir->entry[i].filename); - de.filename_len = strlen(de.filename); - cd->entry[j].filename = za->cdir->entry[i].filename; - cd->entry[j].filename_len = de.filename_len; - } - } - } - else { - /* copy existing directory entries */ - if (fseeko(za->zp, za->cdir->entry[i].offset, SEEK_SET) != 0) { - _zip_error_set(&za->error, ZIP_ER_SEEK, errno); - error = 1; - break; - } - if (_zip_dirent_read(&de, za->zp, NULL, 0, 1, &za->error) != 0) { - error = 1; - break; - } - if (de.bitflags & ZIP_GPBF_DATA_DESCRIPTOR) { - de.crc = za->cdir->entry[i].crc; - de.comp_size = za->cdir->entry[i].comp_size; - de.uncomp_size = za->cdir->entry[i].uncomp_size; - de.bitflags &= ~ZIP_GPBF_DATA_DESCRIPTOR; - } - memcpy(cd->entry+j, za->cdir->entry+i, sizeof(cd->entry[j])); - } - - if (za->entry[i].ch_filename) { - free(de.filename); - if ((de.filename=strdup(za->entry[i].ch_filename)) == NULL) { - error = 1; - break; - } - de.filename_len = strlen(de.filename); - cd->entry[j].filename = za->entry[i].ch_filename; - cd->entry[j].filename_len = de.filename_len; - } - - if (zip_get_archive_flag(za, ZIP_AFL_TORRENT, 0) == 0 - && za->entry[i].ch_comment_len != -1) { - /* as the rest of cd entries, its malloc/free is done by za */ - cd->entry[j].comment = za->entry[i].ch_comment; - cd->entry[j].comment_len = za->entry[i].ch_comment_len; - } - - cd->entry[j].offset = ftello(out); - - if (ZIP_ENTRY_DATA_CHANGED(za->entry+i) || new_torrentzip) { - struct zip_source *zs; - - zs = NULL; - if (!ZIP_ENTRY_DATA_CHANGED(za->entry+i)) { - if ((zs=zip_source_zip(za, za, i, ZIP_FL_RECOMPRESS, 0, -1)) - == NULL) { - error = 1; - break; - } - } - - if (add_data(za, zs ? zs : za->entry[i].source, &de, out) < 0) { - error = 1; - break; - } - cd->entry[j].last_mod = de.last_mod; - cd->entry[j].comp_method = de.comp_method; - cd->entry[j].comp_size = de.comp_size; - cd->entry[j].uncomp_size = de.uncomp_size; - cd->entry[j].crc = de.crc; - } - else { - if (_zip_dirent_write(&de, out, 1, &za->error) < 0) { - error = 1; - break; - } - /* we just read the local dirent, file is at correct position */ - if (copy_data(za->zp, cd->entry[j].comp_size, out, - &za->error) < 0) { - error = 1; - break; - } - } - - _zip_dirent_finalize(&de); - } - - if (!error) { - if (write_cdir(za, cd, out) < 0) - error = 1; - } - - /* pointers in cd entries are owned by za */ - cd->nentry = 0; - _zip_cdir_free(cd); - - if (error) { - _zip_dirent_finalize(&de); - fclose(out); - remove(temp); - free(temp); - return -1; - } - - if (fclose(out) != 0) { - _zip_error_set(&za->error, ZIP_ER_CLOSE, errno); - remove(temp); - free(temp); - return -1; - } - - if (za->zp) { - fclose(za->zp); - za->zp = NULL; - reopen_on_error = 1; - } - if (_zip_rename(temp, za->zn) != 0) { - _zip_error_set(&za->error, ZIP_ER_RENAME, errno); - remove(temp); - free(temp); - if (reopen_on_error) { - /* ignore errors, since we're already in an error case */ - za->zp = fopen(za->zn, "rb"); - } - return -1; - } - mask = umask(0); - umask(mask); - chmod(za->zn, 0666&~mask); - - _zip_free(za); - free(temp); - - return 0; -} - - - -static int -add_data(struct zip *za, struct zip_source *zs, struct zip_dirent *de, FILE *ft) -{ - myoff_t offstart, offend; - zip_source_callback cb; - void *ud; - struct zip_stat st; - - cb = zs->f; - ud = zs->ud; - - if (cb(ud, &st, sizeof(st), ZIP_SOURCE_STAT) < (ssize_t)sizeof(st)) { - ch_set_error(&za->error, cb, ud); - return -1; - } - - if (cb(ud, NULL, 0, ZIP_SOURCE_OPEN) < 0) { - ch_set_error(&za->error, cb, ud); - return -1; - } - - offstart = ftello(ft); - - if (_zip_dirent_write(de, ft, 1, &za->error) < 0) - return -1; - - if (st.comp_method != ZIP_CM_STORE) { - if (add_data_comp(cb, ud, &st, ft, &za->error) < 0) - return -1; - } - else { - if (add_data_uncomp(za, cb, ud, &st, ft) < 0) - return -1; - } - - if (cb(ud, NULL, 0, ZIP_SOURCE_CLOSE) < 0) { - ch_set_error(&za->error, cb, ud); - return -1; - } - - offend = ftello(ft); - - if (fseeko(ft, offstart, SEEK_SET) < 0) { - _zip_error_set(&za->error, ZIP_ER_SEEK, errno); - return -1; - } - - - de->last_mod = st.mtime; - de->comp_method = st.comp_method; - de->crc = st.crc; - de->uncomp_size = st.size; - de->comp_size = st.comp_size; - - if (zip_get_archive_flag(za, ZIP_AFL_TORRENT, 0)) - _zip_dirent_torrent_normalize(de); - - if (_zip_dirent_write(de, ft, 1, &za->error) < 0) - return -1; - - if (fseeko(ft, offend, SEEK_SET) < 0) { - _zip_error_set(&za->error, ZIP_ER_SEEK, errno); - return -1; - } - - return 0; -} - - - -static int -add_data_comp(zip_source_callback cb, void *ud, struct zip_stat *st,FILE *ft, - struct zip_error *error) -{ - char buf[BUFSIZE]; - ssize_t n; - - st->comp_size = 0; - while ((n=cb(ud, buf, sizeof(buf), ZIP_SOURCE_READ)) > 0) { - if (fwrite(buf, 1, n, ft) != (size_t)n) { - _zip_error_set(error, ZIP_ER_WRITE, errno); - return -1; - } - - st->comp_size += n; - } - if (n < 0) { - ch_set_error(error, cb, ud); - return -1; - } - - return 0; -} - - - -static int -add_data_uncomp(struct zip *za, zip_source_callback cb, void *ud, - struct zip_stat *st, FILE *ft) -{ - char b1[BUFSIZE], b2[BUFSIZE]; - int end, flush, ret; - ssize_t n; - size_t n2; - z_stream zstr; - int mem_level; - - st->comp_method = ZIP_CM_DEFLATE; - st->comp_size = st->size = 0; - st->crc = crc32(0, NULL, 0); - - zstr.zalloc = Z_NULL; - zstr.zfree = Z_NULL; - zstr.opaque = NULL; - zstr.avail_in = 0; - zstr.avail_out = 0; - - if (zip_get_archive_flag(za, ZIP_AFL_TORRENT, 0)) - mem_level = TORRENT_MEM_LEVEL; - else - mem_level = MAX_MEM_LEVEL; - - /* -MAX_WBITS: undocumented feature of zlib to _not_ write a zlib header */ - deflateInit2(&zstr, Z_BEST_COMPRESSION, Z_DEFLATED, -MAX_WBITS, mem_level, - Z_DEFAULT_STRATEGY); - - zstr.next_out = (Bytef *)b2; - zstr.avail_out = sizeof(b2); - zstr.avail_in = 0; - - flush = 0; - end = 0; - while (!end) { - if (zstr.avail_in == 0 && !flush) { - if ((n=cb(ud, b1, sizeof(b1), ZIP_SOURCE_READ)) < 0) { - ch_set_error(&za->error, cb, ud); - deflateEnd(&zstr); - return -1; - } - if (n > 0) { - zstr.avail_in = n; - zstr.next_in = (Bytef *)b1; - st->size += n; - st->crc = crc32(st->crc, (Bytef *)b1, n); - } - else - flush = Z_FINISH; - } - - ret = deflate(&zstr, flush); - if (ret != Z_OK && ret != Z_STREAM_END) { - _zip_error_set(&za->error, ZIP_ER_ZLIB, ret); - return -1; - } - - if (zstr.avail_out != sizeof(b2)) { - n2 = sizeof(b2) - zstr.avail_out; - - if (fwrite(b2, 1, n2, ft) != n2) { - _zip_error_set(&za->error, ZIP_ER_WRITE, errno); - return -1; - } - - zstr.next_out = (Bytef *)b2; - zstr.avail_out = sizeof(b2); - st->comp_size += n2; - } - - if (ret == Z_STREAM_END) { - deflateEnd(&zstr); - end = 1; - } - } - - return 0; -} - - - -static void -ch_set_error(struct zip_error *error, zip_source_callback cb, void *ud) -{ - int e[2]; - - if ((cb(ud, e, sizeof(e), ZIP_SOURCE_ERROR)) < (ssize_t)sizeof(e)) { - error->zip_err = ZIP_ER_INTERNAL; - error->sys_err = 0; - } - else { - error->zip_err = e[0]; - error->sys_err = e[1]; - } -} - - - -static int -copy_data(FILE *fs, myoff_t len, FILE *ft, struct zip_error *error) -{ - char buf[BUFSIZE]; - int n, nn; - - if (len == 0) - return 0; - - while (len > 0) { - nn = len > sizeof(buf) ? sizeof(buf) : len; - if ((n=fread(buf, 1, nn, fs)) < 0) { - _zip_error_set(error, ZIP_ER_READ, errno); - return -1; - } - else if (n == 0) { - _zip_error_set(error, ZIP_ER_EOF, 0); - return -1; - } - - if (fwrite(buf, 1, n, ft) != (size_t)n) { - _zip_error_set(error, ZIP_ER_WRITE, errno); - return -1; - } - - len -= n; - } - - return 0; -} - - - -static int -write_cdir(struct zip *za, struct zip_cdir *cd, FILE *out) -{ - myoff_t offset; - uLong crc; - char buf[TORRENT_CRC_LEN+1]; - - if (_zip_cdir_write(cd, out, &za->error) < 0) - return -1; - - if (zip_get_archive_flag(za, ZIP_AFL_TORRENT, 0) == 0) - return 0; - - - /* fix up torrentzip comment */ - - offset = ftello(out); - - if (_zip_filerange_crc(out, cd->offset, cd->size, &crc, &za->error) < 0) - return -1; - - snprintf(buf, sizeof(buf), "%08lX", (long)crc); - - if (fseeko(out, offset-TORRENT_CRC_LEN, SEEK_SET) < 0) { - _zip_error_set(&za->error, ZIP_ER_SEEK, errno); - return -1; - } - - if (fwrite(buf, TORRENT_CRC_LEN, 1, out) != 1) { - _zip_error_set(&za->error, ZIP_ER_WRITE, errno); - return -1; - } - - return 0; -} - - - -static int -_zip_cdir_set_comment(struct zip_cdir *dest, struct zip *src) -{ - if (src->ch_comment_len != -1) { - dest->comment = _zip_memdup(src->ch_comment, - src->ch_comment_len, &src->error); - if (dest->comment == NULL) - return -1; - dest->comment_len = src->ch_comment_len; - } else { - if (src->cdir && src->cdir->comment) { - dest->comment = _zip_memdup(src->cdir->comment, - src->cdir->comment_len, &src->error); - if (dest->comment == NULL) - return -1; - dest->comment_len = src->cdir->comment_len; - } - } - - return 0; -} - - - -static int -_zip_changed(struct zip *za, int *survivorsp) -{ - int changed, i, survivors; - - changed = survivors = 0; - - if (za->ch_comment_len != -1 - || za->ch_flags != za->flags) - changed = 1; - - for (i=0; inentry; i++) { - if ((za->entry[i].state != ZIP_ST_UNCHANGED) - || (za->entry[i].ch_comment_len != -1)) - changed = 1; - if (za->entry[i].state != ZIP_ST_DELETED) - survivors++; - } - - *survivorsp = survivors; - - return changed; -} - - - -static char * -_zip_create_temp_output(struct zip *za, FILE **outp) -{ - char *temp; - int tfd; - FILE *tfp; - - if ((temp=(char *)malloc(strlen(za->zn)+8)) == NULL) { - _zip_error_set(&za->error, ZIP_ER_MEMORY, 0); - return NULL; - } - - sprintf(temp, "%s.XXXXXX", za->zn); - - if ((tfd=mkstemp(temp)) == -1) { - _zip_error_set(&za->error, ZIP_ER_TMPOPEN, errno); - free(temp); - return NULL; - } - - if ((tfp=fdopen(tfd, "r+b")) == NULL) { - _zip_error_set(&za->error, ZIP_ER_TMPOPEN, errno); - close(tfd); - remove(temp); - free(temp); - return NULL; - } - - *outp = tfp; - return temp; -} - - - -static int -_zip_torrentzip_cmp(const void *a, const void *b) -{ - return strcasecmp(((const struct filelist *)a)->name, - ((const struct filelist *)b)->name); -} - - - -ZIP_EXTERN int -zip_add_dir(struct zip *za, const char *name) -{ - int len, ret; - char *s; - struct zip_source *source; - - if (name == NULL) { - _zip_error_set(&za->error, ZIP_ER_INVAL, 0); - return -1; - } - - s = NULL; - len = strlen(name); - - if (name[len-1] != '/') { - if ((s=(char *)malloc(len+2)) == NULL) { - _zip_error_set(&za->error, ZIP_ER_MEMORY, 0); - return -1; - } - strcpy(s, name); - s[len] = '/'; - s[len+1] = '\0'; - } - - if ((source=zip_source_buffer(za, NULL, 0, 0)) == NULL) { - free(s); - return -1; - } - - ret = _zip_replace(za, -1, s ? s : name, source); - - free(s); - if (ret < 0) - zip_source_free(source); - - return ret; -} - - -ZIP_EXTERN int -zip_error_to_str(char *buf, size_t len, int ze, int se) -{ - const char *zs, *ss; - - if (ze < 0 || ze >= _zip_nerr_str) - return snprintf(buf, len, "Unknown error %d", ze); - - zs = _zip_err_str[ze]; - - switch (_zip_err_type[ze]) { - case ZIP_ET_SYS: - ss = strerror(se); - break; - - case ZIP_ET_ZLIB: - ss = zError(se); - break; - - default: - ss = NULL; - } - - return snprintf(buf, len, "%s%s%s", - zs, (ss ? ": " : ""), (ss ? ss : "")); -} - - -ZIP_EXTERN void -zip_file_error_clear(struct zip_file *zf) -{ - _zip_error_clear(&zf->error); -} - - -ZIP_EXTERN int -zip_fclose(struct zip_file *zf) -{ - int i, ret; - - if (zf->zstr) - inflateEnd(zf->zstr); - free(zf->buffer); - free(zf->zstr); - - for (i=0; iza->nfile; i++) { - if (zf->za->file[i] == zf) { - zf->za->file[i] = zf->za->file[zf->za->nfile-1]; - zf->za->nfile--; - break; - } - } - - ret = 0; - if (zf->error.zip_err) - ret = zf->error.zip_err; - else if ((zf->flags & ZIP_ZF_CRC) && (zf->flags & ZIP_ZF_EOF)) { - /* if EOF, compare CRC */ - if (zf->crc_orig != zf->crc) - ret = ZIP_ER_CRC; - } - - free(zf); - return ret; -} - - -int -_zip_filerange_crc(FILE *fp, myoff_t start, myoff_t len, uLong *crcp, - struct zip_error *errp) -{ - Bytef buf[BUFSIZE]; - size_t n; - - *crcp = crc32(0L, Z_NULL, 0); - - if (fseeko(fp, start, SEEK_SET) != 0) { - _zip_error_set(errp, ZIP_ER_SEEK, errno); - return -1; - } - - while (len > 0) { - n = len > BUFSIZE ? BUFSIZE : len; - if ((n=fread(buf, 1, n, fp)) <= 0) { - _zip_error_set(errp, ZIP_ER_READ, errno); - return -1; - } - - *crcp = crc32(*crcp, buf, n); - - len-= n; - } - - return 0; -} - - -ZIP_EXTERN const char * -zip_file_strerror(struct zip_file *zf) -{ - return _zip_error_strerror(&zf->error); -} - - -/* _zip_file_get_offset(za, ze): - Returns the offset of the file data for entry ze. - - On error, fills in za->error and returns 0. -*/ - -unsigned int -_zip_file_get_offset(struct zip *za, int idx) -{ - struct zip_dirent de; - unsigned int offset; - - offset = za->cdir->entry[idx].offset; - - if (fseeko(za->zp, offset, SEEK_SET) != 0) { - _zip_error_set(&za->error, ZIP_ER_SEEK, errno); - return 0; - } - - if (_zip_dirent_read(&de, za->zp, NULL, 0, 1, &za->error) != 0) - return 0; - - offset += LENTRYSIZE + de.filename_len + de.extrafield_len; - - _zip_dirent_finalize(&de); - - return offset; -} - - -ZIP_EXTERN void -zip_file_error_get(struct zip_file *zf, int *zep, int *sep) -{ - _zip_error_get(&zf->error, zep, sep); -} - - -static struct zip_file *_zip_file_new(struct zip *za); - - - -ZIP_EXTERN struct zip_file * -zip_fopen_index(struct zip *za, int fileno, int flags) -{ - int len, ret; - int zfflags; - struct zip_file *zf; - - if ((fileno < 0) || (fileno >= za->nentry)) { - _zip_error_set(&za->error, ZIP_ER_INVAL, 0); - return NULL; - } - - if ((flags & ZIP_FL_UNCHANGED) == 0 - && ZIP_ENTRY_DATA_CHANGED(za->entry+fileno)) { - _zip_error_set(&za->error, ZIP_ER_CHANGED, 0); - return NULL; - } - - if (fileno >= za->cdir->nentry) { - _zip_error_set(&za->error, ZIP_ER_INVAL, 0); - return NULL; - } - - zfflags = 0; - switch (za->cdir->entry[fileno].comp_method) { - case ZIP_CM_STORE: - zfflags |= ZIP_ZF_CRC; - break; - - case ZIP_CM_DEFLATE: - if ((flags & ZIP_FL_COMPRESSED) == 0) - zfflags |= ZIP_ZF_CRC | ZIP_ZF_DECOMP; - break; - default: - if ((flags & ZIP_FL_COMPRESSED) == 0) { - _zip_error_set(&za->error, ZIP_ER_COMPNOTSUPP, 0); - return NULL; - } - break; - } - - zf = _zip_file_new(za); - - zf->flags = zfflags; - /* zf->name = za->cdir->entry[fileno].filename; */ - zf->method = za->cdir->entry[fileno].comp_method; - zf->bytes_left = za->cdir->entry[fileno].uncomp_size; - zf->cbytes_left = za->cdir->entry[fileno].comp_size; - zf->crc_orig = za->cdir->entry[fileno].crc; - - if ((zf->fpos=_zip_file_get_offset(za, fileno)) == 0) { - zip_fclose(zf); - return NULL; - } - - if ((zf->flags & ZIP_ZF_DECOMP) == 0) - zf->bytes_left = zf->cbytes_left; - else { - if ((zf->buffer=(char *)malloc(BUFSIZE)) == NULL) { - _zip_error_set(&za->error, ZIP_ER_MEMORY, 0); - zip_fclose(zf); - return NULL; - } - - len = _zip_file_fillbuf(zf->buffer, BUFSIZE, zf); - if (len <= 0) { - _zip_error_copy(&za->error, &zf->error); - zip_fclose(zf); - return NULL; - } - - if ((zf->zstr = (z_stream *)malloc(sizeof(z_stream))) == NULL) { - _zip_error_set(&za->error, ZIP_ER_MEMORY, 0); - zip_fclose(zf); - return NULL; - } - zf->zstr->zalloc = Z_NULL; - zf->zstr->zfree = Z_NULL; - zf->zstr->opaque = NULL; - zf->zstr->next_in = (Bytef *)zf->buffer; - zf->zstr->avail_in = len; - - /* negative value to tell zlib that there is no header */ - if ((ret=inflateInit2(zf->zstr, -MAX_WBITS)) != Z_OK) { - _zip_error_set(&za->error, ZIP_ER_ZLIB, ret); - zip_fclose(zf); - return NULL; - } - } - - return zf; -} - - - -int -_zip_file_fillbuf(void *buf, size_t buflen, struct zip_file *zf) -{ - int i, j; - - if (zf->error.zip_err != ZIP_ER_OK) - return -1; - - if ((zf->flags & ZIP_ZF_EOF) || zf->cbytes_left <= 0 || buflen <= 0) - return 0; - - if (fseeko(zf->za->zp, zf->fpos, SEEK_SET) < 0) { - _zip_error_set(&zf->error, ZIP_ER_SEEK, errno); - return -1; - } - if (buflen < zf->cbytes_left) - i = buflen; - else - i = zf->cbytes_left; - - j = fread(buf, 1, i, zf->za->zp); - if (j == 0) { - _zip_error_set(&zf->error, ZIP_ER_EOF, 0); - j = -1; - } - else if (j < 0) - _zip_error_set(&zf->error, ZIP_ER_READ, errno); - else { - zf->fpos += j; - zf->cbytes_left -= j; - } - - return j; -} - - - -static struct zip_file * -_zip_file_new(struct zip *za) -{ - struct zip_file *zf, **file; - int n; - - if ((zf=(struct zip_file *)malloc(sizeof(struct zip_file))) == NULL) { - _zip_error_set(&za->error, ZIP_ER_MEMORY, 0); - return NULL; - } - - if (za->nfile >= za->nfile_alloc-1) { - n = za->nfile_alloc + 10; - file = (struct zip_file **)realloc(za->file, - n*sizeof(struct zip_file *)); - if (file == NULL) { - _zip_error_set(&za->error, ZIP_ER_MEMORY, 0); - free(zf); - return NULL; - } - za->nfile_alloc = n; - za->file = file; - } - - za->file[za->nfile++] = zf; - - zf->za = za; - _zip_error_init(&zf->error); - zf->flags = 0; - zf->crc = crc32(0L, Z_NULL, 0); - zf->crc_orig = 0; - zf->method = -1; - zf->bytes_left = zf->cbytes_left = 0; - zf->fpos = 0; - zf->buffer = NULL; - zf->zstr = NULL; - - return zf; -} - - -ZIP_EXTERN struct zip_file * -zip_fopen(struct zip *za, const char *fname, int flags) -{ - int idx; - - if ((idx=zip_name_locate(za, fname, flags)) < 0) - return NULL; - - return zip_fopen_index(za, idx, flags); -} - - -ZIP_EXTERN int -zip_set_file_comment(struct zip *za, int idx, const char *comment, int len) -{ - char *tmpcom; - - if (idx < 0 || idx >= za->nentry - || len < 0 || len > MAXCOMLEN - || (len > 0 && comment == NULL)) { - _zip_error_set(&za->error, ZIP_ER_INVAL, 0); - return -1; - } - - if (len > 0) { - if ((tmpcom=(char *)_zip_memdup(comment, len, &za->error)) == NULL) - return -1; - } - else - tmpcom = NULL; - - free(za->entry[idx].ch_comment); - za->entry[idx].ch_comment = tmpcom; - za->entry[idx].ch_comment_len = len; - - return 0; -} - - -ZIP_EXTERN struct zip_source * -zip_source_file(struct zip *za, const char *fname, myoff_t start, myoff_t len) -{ - if (za == NULL) - return NULL; - - if (fname == NULL || start < 0 || len < -1) { - _zip_error_set(&za->error, ZIP_ER_INVAL, 0); - return NULL; - } - - return _zip_source_file_or_p(za, fname, NULL, start, len); -} - - -struct read_data { - const char *buf, *data, *end; - time_t mtime; - int freep; -}; - -static ssize_t read_data(void *state, void *data, size_t len, - enum zip_source_cmd cmd); - - - -ZIP_EXTERN struct zip_source * -zip_source_buffer(struct zip *za, const void *data, myoff_t len, int freep) -{ - struct read_data *f; - struct zip_source *zs; - - if (za == NULL) - return NULL; - - if (len < 0 || (data == NULL && len > 0)) { - _zip_error_set(&za->error, ZIP_ER_INVAL, 0); - return NULL; - } - - if ((f=(struct read_data *)malloc(sizeof(*f))) == NULL) { - _zip_error_set(&za->error, ZIP_ER_MEMORY, 0); - return NULL; - } - - f->data = (const char *)data; - f->end = ((const char *)data)+len; - f->freep = freep; - f->mtime = time(NULL); - - if ((zs=zip_source_function(za, read_data, f)) == NULL) { - free(f); - return NULL; - } - - return zs; -} - - - -static ssize_t -read_data(void *state, void *data, size_t len, enum zip_source_cmd cmd) -{ - struct read_data *z; - char *buf; - size_t n; - - z = (struct read_data *)state; - buf = (char *)data; - - switch (cmd) { - case ZIP_SOURCE_OPEN: - z->buf = z->data; - return 0; - - case ZIP_SOURCE_READ: - n = z->end - z->buf; - if (n > len) - n = len; - - if (n) { - memcpy(buf, z->buf, n); - z->buf += n; - } - - return n; - - case ZIP_SOURCE_CLOSE: - return 0; - - case ZIP_SOURCE_STAT: - { - struct zip_stat *st; - - if (len < sizeof(*st)) - return -1; - - st = (struct zip_stat *)data; - - zip_stat_init(st); - st->mtime = z->mtime; - st->size = z->end - z->data; - - return sizeof(*st); - } - - case ZIP_SOURCE_ERROR: - { - int *e; - - if (len < sizeof(int)*2) - return -1; - - e = (int *)data; - e[0] = e[1] = 0; - } - return sizeof(int)*2; - - case ZIP_SOURCE_FREE: - if (z->freep) { - free((void *)z->data); - z->data = NULL; - } - free(z); - return 0; - - default: - ; - } - - return -1; -} - - -int -_zip_set_name(struct zip *za, int idx, const char *name) -{ - char *s; - int i; - - if (idx < 0 || idx >= za->nentry || name == NULL) { - _zip_error_set(&za->error, ZIP_ER_INVAL, 0); - return -1; - } - - if ((i=_zip_name_locate(za, name, 0, NULL)) != -1 && i != idx) { - _zip_error_set(&za->error, ZIP_ER_EXISTS, 0); - return -1; - } - - /* no effective name change */ - if (i == idx) - return 0; - - if ((s=strdup(name)) == NULL) { - _zip_error_set(&za->error, ZIP_ER_MEMORY, 0); - return -1; - } - - if (za->entry[idx].state == ZIP_ST_UNCHANGED) - za->entry[idx].state = ZIP_ST_RENAMED; - - free(za->entry[idx].ch_filename); - za->entry[idx].ch_filename = s; - - return 0; -} - - -ZIP_EXTERN int -zip_set_archive_flag(struct zip *za, int flag, int value) -{ - if (value) - za->ch_flags |= flag; - else - za->ch_flags &= ~flag; - - return 0; -} - - -void -_zip_unchange_data(struct zip_entry *ze) -{ - if (ze->source) { - (void)ze->source->f(ze->source->ud, NULL, 0, ZIP_SOURCE_FREE); - free(ze->source); - ze->source = NULL; - } - - ze->state = ze->ch_filename ? ZIP_ST_RENAMED : ZIP_ST_UNCHANGED; -} - - -ZIP_EXTERN int -zip_unchange_archive(struct zip *za) -{ - free(za->ch_comment); - za->ch_comment = NULL; - za->ch_comment_len = -1; - - za->ch_flags = za->flags; - - return 0; -} - -ZIP_EXTERN int -zip_unchange(struct zip *za, int idx) -{ - return _zip_unchange(za, idx, 0); -} - - - -int -_zip_unchange(struct zip *za, int idx, int allow_duplicates) -{ - int i; - - if (idx < 0 || idx >= za->nentry) { - _zip_error_set(&za->error, ZIP_ER_INVAL, 0); - return -1; - } - - if (za->entry[idx].ch_filename) { - if (!allow_duplicates) { - i = _zip_name_locate(za, - _zip_get_name(za, idx, ZIP_FL_UNCHANGED, NULL), - 0, NULL); - if (i != -1 && i != idx) { - _zip_error_set(&za->error, ZIP_ER_EXISTS, 0); - return -1; - } - } - - free(za->entry[idx].ch_filename); - za->entry[idx].ch_filename = NULL; - } - - free(za->entry[idx].ch_comment); - za->entry[idx].ch_comment = NULL; - za->entry[idx].ch_comment_len = -1; - - _zip_unchange_data(za->entry+idx); - - return 0; -} - -ZIP_EXTERN int -zip_unchange_all(struct zip *za) -{ - int ret, i; - - ret = 0; - for (i=0; inentry; i++) - ret |= _zip_unchange(za, i, 1); - - ret |= zip_unchange_archive(za); - - return ret; -} - - -ZIP_EXTERN int -zip_set_archive_comment(struct zip *za, const char *comment, int len) -{ - char *tmpcom; - - if (len < 0 || len > MAXCOMLEN - || (len > 0 && comment == NULL)) { - _zip_error_set(&za->error, ZIP_ER_INVAL, 0); - return -1; - } - - if (len > 0) { - if ((tmpcom=(char *)_zip_memdup(comment, len, &za->error)) == NULL) - return -1; - } - else - tmpcom = NULL; - - free(za->ch_comment); - za->ch_comment = tmpcom; - za->ch_comment_len = len; - - return 0; -} - - -ZIP_EXTERN int -zip_replace(struct zip *za, int idx, struct zip_source *source) -{ - if (idx < 0 || idx >= za->nentry || source == NULL) { - _zip_error_set(&za->error, ZIP_ER_INVAL, 0); - return -1; - } - - if (_zip_replace(za, idx, NULL, source) == -1) - return -1; - - return 0; -} - - - - -int -_zip_replace(struct zip *za, int idx, const char *name, - struct zip_source *source) -{ - if (idx == -1) { - if (_zip_entry_new(za) == NULL) - return -1; - - idx = za->nentry - 1; - } - - _zip_unchange_data(za->entry+idx); - - if (name && _zip_set_name(za, idx, name) != 0) - return -1; - - za->entry[idx].state = ((za->cdir == NULL || idx >= za->cdir->nentry) - ? ZIP_ST_ADDED : ZIP_ST_REPLACED); - za->entry[idx].source = source; - - return idx; -} - - -ZIP_EXTERN int -zip_rename(struct zip *za, int idx, const char *name) -{ - const char *old_name; - int old_is_dir, new_is_dir; - - if (idx >= za->nentry || idx < 0 || name[0] == '\0') { - _zip_error_set(&za->error, ZIP_ER_INVAL, 0); - return -1; - } - - if ((old_name=zip_get_name(za, idx, 0)) == NULL) - return -1; - - new_is_dir = (name[strlen(name)-1] == '/'); - old_is_dir = (old_name[strlen(old_name)-1] == '/'); - - if (new_is_dir != old_is_dir) { - _zip_error_set(&za->error, ZIP_ER_INVAL, 0); - return -1; - } - - return _zip_set_name(za, idx, name); -} - -#include -#include -#include -#include -#include -#include - -static void set_error(int *, struct zip_error *, int); -static struct zip *_zip_allocate_new(const char *, int *); -static int _zip_checkcons(FILE *, struct zip_cdir *, struct zip_error *); -static void _zip_check_torrentzip(struct zip *); -static struct zip_cdir *_zip_find_central_dir(FILE *, int, int *, myoff_t); -static int _zip_file_exists(const char *, int, int *); -static int _zip_headercomp(struct zip_dirent *, int, - struct zip_dirent *, int); -static unsigned char *_zip_memmem(const unsigned char *, int, - const unsigned char *, int); -static struct zip_cdir *_zip_readcdir(FILE *, unsigned char *, unsigned char *, - int, int, struct zip_error *); - - - -ZIP_EXTERN struct zip * -zip_open(const char *fn, int flags, int *zep) -{ - FILE *fp; - struct zip *za; - struct zip_cdir *cdir; - int i; - myoff_t len; - - switch (_zip_file_exists(fn, flags, zep)) { - case -1: - return NULL; - case 0: - return _zip_allocate_new(fn, zep); - default: - break; - } - - if ((fp=fopen(fn, "rb")) == NULL) { - set_error(zep, NULL, ZIP_ER_OPEN); - return NULL; - } - - fseeko(fp, 0, SEEK_END); - len = ftello(fp); - - /* treat empty files as empty archives */ - if (len == 0) { - if ((za=_zip_allocate_new(fn, zep)) == NULL) - fclose(fp); - else - za->zp = fp; - return za; - } - - cdir = _zip_find_central_dir(fp, flags, zep, len); - if (cdir == NULL) { - fclose(fp); - return NULL; - } - - if ((za=_zip_allocate_new(fn, zep)) == NULL) { - _zip_cdir_free(cdir); - fclose(fp); - return NULL; - } - - za->cdir = cdir; - za->zp = fp; - - if ((za->entry=(struct zip_entry *)malloc(sizeof(*(za->entry)) - * cdir->nentry)) == NULL) { - set_error(zep, NULL, ZIP_ER_MEMORY); - _zip_free(za); - return NULL; - } - for (i=0; inentry; i++) - _zip_entry_new(za); - - _zip_check_torrentzip(za); - za->ch_flags = za->flags; - - return za; -} - - - -static void -set_error(int *zep, struct zip_error *err, int ze) -{ - int se; - - if (err) { - _zip_error_get(err, &ze, &se); - if (zip_error_get_sys_type(ze) == ZIP_ET_SYS) - errno = se; - } - - if (zep) - *zep = ze; -} - - - -/* _zip_readcdir: - tries to find a valid end-of-central-directory at the beginning of - buf, and then the corresponding central directory entries. - Returns a struct zip_cdir which contains the central directory - entries, or NULL if unsuccessful. */ - -static struct zip_cdir * -_zip_readcdir(FILE *fp, unsigned char *buf, unsigned char *eocd, int buflen, - int flags, struct zip_error *error) -{ - struct zip_cdir *cd; - unsigned char *cdp, **bufp; - int i, comlen, nentry; - - comlen = buf + buflen - eocd - EOCDLEN; - if (comlen < 0) { - /* not enough bytes left for comment */ - _zip_error_set(error, ZIP_ER_NOZIP, 0); - return NULL; - } - - /* check for end-of-central-dir magic */ - if (memcmp(eocd, EOCD_MAGIC, 4) != 0) { - _zip_error_set(error, ZIP_ER_NOZIP, 0); - return NULL; - } - - if (memcmp(eocd+4, "\0\0\0\0", 4) != 0) { - _zip_error_set(error, ZIP_ER_MULTIDISK, 0); - return NULL; - } - - cdp = eocd + 8; - /* number of cdir-entries on this disk */ - i = _zip_read2(&cdp); - /* number of cdir-entries */ - nentry = _zip_read2(&cdp); - - if ((cd=_zip_cdir_new(nentry, error)) == NULL) - return NULL; - - cd->size = _zip_read4(&cdp); - cd->offset = _zip_read4(&cdp); - cd->comment = NULL; - cd->comment_len = _zip_read2(&cdp); - - if ((comlen < cd->comment_len) || (cd->nentry != i)) { - _zip_error_set(error, ZIP_ER_NOZIP, 0); - free(cd); - return NULL; - } - if ((flags & ZIP_CHECKCONS) && comlen != cd->comment_len) { - _zip_error_set(error, ZIP_ER_INCONS, 0); - free(cd); - return NULL; - } - - if (cd->comment_len) { - if ((cd->comment=(char *)_zip_memdup(eocd+EOCDLEN, - cd->comment_len, error)) - == NULL) { - free(cd); - return NULL; - } - } - - cdp = eocd; - if (cd->size < (unsigned int)(eocd-buf)) { - /* if buffer already read in, use it */ - cdp = eocd - cd->size; - bufp = &cdp; - } - else { - /* go to start of cdir and read it entry by entry */ - bufp = NULL; - clearerr(fp); - fseeko(fp, cd->offset, SEEK_SET); - /* possible consistency check: cd->offset = - len-(cd->size+cd->comment_len+EOCDLEN) ? */ - if (ferror(fp) || ((unsigned long)ftello(fp) != cd->offset)) { - /* seek error or offset of cdir wrong */ - if (ferror(fp)) - _zip_error_set(error, ZIP_ER_SEEK, errno); - else - _zip_error_set(error, ZIP_ER_NOZIP, 0); - free(cd); - return NULL; - } - } - - for (i=0; inentry; i++) { - if ((_zip_dirent_read(cd->entry+i, fp, bufp, eocd-cdp, 0, - error)) < 0) { - cd->nentry = i; - _zip_cdir_free(cd); - return NULL; - } - } - - return cd; -} - - - -/* _zip_checkcons: - Checks the consistency of the central directory by comparing central - directory entries with local headers and checking for plausible - file and header offsets. Returns -1 if not plausible, else the - difference between the lowest and the highest fileposition reached */ - -static int -_zip_checkcons(FILE *fp, struct zip_cdir *cd, struct zip_error *error) -{ - int i; - unsigned int min, max, j; - struct zip_dirent temp; - - if (cd->nentry) { - max = cd->entry[0].offset; - min = cd->entry[0].offset; - } - else - min = max = 0; - - for (i=0; inentry; i++) { - if (cd->entry[i].offset < min) - min = cd->entry[i].offset; - if (min > cd->offset) { - _zip_error_set(error, ZIP_ER_NOZIP, 0); - return -1; - } - - j = cd->entry[i].offset + cd->entry[i].comp_size - + cd->entry[i].filename_len + LENTRYSIZE; - if (j > max) - max = j; - if (max > cd->offset) { - _zip_error_set(error, ZIP_ER_NOZIP, 0); - return -1; - } - - if (fseeko(fp, cd->entry[i].offset, SEEK_SET) != 0) { - _zip_error_set(error, ZIP_ER_SEEK, 0); - return -1; - } - - if (_zip_dirent_read(&temp, fp, NULL, 0, 1, error) == -1) - return -1; - - if (_zip_headercomp(cd->entry+i, 0, &temp, 1) != 0) { - _zip_error_set(error, ZIP_ER_INCONS, 0); - _zip_dirent_finalize(&temp); - return -1; - } - _zip_dirent_finalize(&temp); - } - - return max - min; -} - - - -/* _zip_check_torrentzip: - check wether ZA has a valid TORRENTZIP comment, i.e. is torrentzipped */ - -static void -_zip_check_torrentzip(struct zip *za) -{ - uLong crc_got, crc_should; - char buf[8+1]; - char *end; - - if (za->zp == NULL || za->cdir == NULL) - return; - - if (za->cdir->comment_len != TORRENT_SIG_LEN+8 - || strncmp(za->cdir->comment, TORRENT_SIG, TORRENT_SIG_LEN) != 0) - return; - - memcpy(buf, za->cdir->comment+TORRENT_SIG_LEN, 8); - buf[8] = '\0'; - errno = 0; - crc_should = strtoul(buf, &end, 16); - if ((crc_should == UINT_MAX && errno != 0) || (end && *end)) - return; - - if (_zip_filerange_crc(za->zp, za->cdir->offset, za->cdir->size, - &crc_got, NULL) < 0) - return; - - if (crc_got == crc_should) - za->flags |= ZIP_AFL_TORRENT; -} - - - - -/* _zip_headercomp: - compares two headers h1 and h2; if they are local headers, set - local1p or local2p respectively to 1, else 0. Return 0 if they - are identical, -1 if not. */ - -static int -_zip_headercomp(struct zip_dirent *h1, int local1p, struct zip_dirent *h2, - int local2p) -{ - if ((h1->version_needed != h2->version_needed) -#if 0 - /* some zip-files have different values in local - and global headers for the bitflags */ - || (h1->bitflags != h2->bitflags) -#endif - || (h1->comp_method != h2->comp_method) - || (h1->last_mod != h2->last_mod) - || (h1->filename_len != h2->filename_len) - || !h1->filename || !h2->filename - || strcmp(h1->filename, h2->filename)) - return -1; - - /* check that CRC and sizes are zero if data descriptor is used */ - if ((h1->bitflags & ZIP_GPBF_DATA_DESCRIPTOR) && local1p - && (h1->crc != 0 - || h1->comp_size != 0 - || h1->uncomp_size != 0)) - return -1; - if ((h2->bitflags & ZIP_GPBF_DATA_DESCRIPTOR) && local2p - && (h2->crc != 0 - || h2->comp_size != 0 - || h2->uncomp_size != 0)) - return -1; - - /* check that CRC and sizes are equal if no data descriptor is used */ - if (((h1->bitflags & ZIP_GPBF_DATA_DESCRIPTOR) == 0 || local1p == 0) - && ((h2->bitflags & ZIP_GPBF_DATA_DESCRIPTOR) == 0 || local2p == 0)) { - if ((h1->crc != h2->crc) - || (h1->comp_size != h2->comp_size) - || (h1->uncomp_size != h2->uncomp_size)) - return -1; - } - - if ((local1p == local2p) - && ((h1->extrafield_len != h2->extrafield_len) - || (h1->extrafield_len && h2->extrafield - && memcmp(h1->extrafield, h2->extrafield, - h1->extrafield_len)))) - return -1; - - /* if either is local, nothing more to check */ - if (local1p || local2p) - return 0; - - if ((h1->version_madeby != h2->version_madeby) - || (h1->disk_number != h2->disk_number) - || (h1->int_attrib != h2->int_attrib) - || (h1->ext_attrib != h2->ext_attrib) - || (h1->offset != h2->offset) - || (h1->comment_len != h2->comment_len) - || (h1->comment_len && h2->comment - && memcmp(h1->comment, h2->comment, h1->comment_len))) - return -1; - - return 0; -} - - - -static struct zip * -_zip_allocate_new(const char *fn, int *zep) -{ - struct zip *za; - struct zip_error error; - - if ((za=_zip_new(&error)) == NULL) { - set_error(zep, &error, 0); - return NULL; - } - - za->zn = strdup(fn); - if (!za->zn) { - _zip_free(za); - set_error(zep, NULL, ZIP_ER_MEMORY); - return NULL; - } - return za; -} - - - -static int -_zip_file_exists(const char *fn, int flags, int *zep) -{ - struct stat st; - - if (fn == NULL) { - set_error(zep, NULL, ZIP_ER_INVAL); - return -1; - } - - if (stat(fn, &st) != 0) { - if (flags & ZIP_CREATE) - return 0; - else { - set_error(zep, NULL, ZIP_ER_OPEN); - return -1; - } - } - else if ((flags & ZIP_EXCL)) { - set_error(zep, NULL, ZIP_ER_EXISTS); - return -1; - } - /* ZIP_CREATE gets ignored if file exists and not ZIP_EXCL, - just like open() */ - - return 1; -} - - - -static struct zip_cdir * -_zip_find_central_dir(FILE *fp, int flags, int *zep, myoff_t len) -{ - struct zip_cdir *cdir, *cdirnew; - unsigned char *buf, *match; - int a, best, buflen, i; - struct zip_error zerr; - - i = fseeko(fp, -(len < CDBUFSIZE ? len : CDBUFSIZE), SEEK_END); - if (i == -1 && errno != EFBIG) { - /* seek before start of file on my machine */ - set_error(zep, NULL, ZIP_ER_SEEK); - return NULL; - } - - /* 64k is too much for stack */ - if ((buf=(unsigned char *)malloc(CDBUFSIZE)) == NULL) { - set_error(zep, NULL, ZIP_ER_MEMORY); - return NULL; - } - - clearerr(fp); - buflen = fread(buf, 1, CDBUFSIZE, fp); - - if (ferror(fp)) { - set_error(zep, NULL, ZIP_ER_READ); - free(buf); - return NULL; - } - - best = -1; - cdir = NULL; - match = buf; - _zip_error_set(&zerr, ZIP_ER_NOZIP, 0); - - while ((match=_zip_memmem(match, buflen-(match-buf)-18, - (const unsigned char *)EOCD_MAGIC, 4))!=NULL) { - /* found match -- check, if good */ - /* to avoid finding the same match all over again */ - match++; - if ((cdirnew=_zip_readcdir(fp, buf, match-1, buflen, flags, - &zerr)) == NULL) - continue; - - if (cdir) { - if (best <= 0) - best = _zip_checkcons(fp, cdir, &zerr); - a = _zip_checkcons(fp, cdirnew, &zerr); - if (best < a) { - _zip_cdir_free(cdir); - cdir = cdirnew; - best = a; - } - else - _zip_cdir_free(cdirnew); - } - else { - cdir = cdirnew; - if (flags & ZIP_CHECKCONS) - best = _zip_checkcons(fp, cdir, &zerr); - else - best = 0; - } - cdirnew = NULL; - } - - free(buf); - - if (best < 0) { - set_error(zep, &zerr, 0); - _zip_cdir_free(cdir); - return NULL; - } - - return cdir; -} - - - -static unsigned char * -_zip_memmem(const unsigned char *big, int biglen, const unsigned char *little, - int littlelen) -{ - const unsigned char *p; - - if ((biglen < littlelen) || (littlelen == 0)) - return NULL; - p = big-1; - while ((p=(const unsigned char *) - memchr(p+1, little[0], (size_t)(big-(p+1)+biglen-littlelen+1))) - != NULL) { - if (memcmp(p+1, little+1, littlelen-1)==0) - return (unsigned char *)p; - } - - return NULL; -} - - -/* _zip_new: - creates a new zipfile struct, and sets the contents to zero; returns - the new struct. */ - -struct zip * -_zip_new(struct zip_error *error) -{ - struct zip *za; - - za = (struct zip *)malloc(sizeof(struct zip)); - if (!za) { - _zip_error_set(error, ZIP_ER_MEMORY, 0); - return NULL; - } - - za->zn = NULL; - za->zp = NULL; - _zip_error_init(&za->error); - za->cdir = NULL; - za->ch_comment = NULL; - za->ch_comment_len = -1; - za->nentry = za->nentry_alloc = 0; - za->entry = NULL; - za->nfile = za->nfile_alloc = 0; - za->file = NULL; - za->flags = za->ch_flags = 0; - - return za; -} - - -void * -_zip_memdup(const void *mem, size_t len, struct zip_error *error) -{ - void *ret; - - ret = malloc(len); - if (!ret) { - _zip_error_set(error, ZIP_ER_MEMORY, 0); - return NULL; - } - - memcpy(ret, mem, len); - - return ret; -} - - -ZIP_EXTERN int -zip_get_num_files(struct zip *za) -{ - if (za == NULL) - return -1; - - return za->nentry; -} - -ZIP_EXTERN const char * -zip_get_name(struct zip *za, int idx, int flags) -{ - return _zip_get_name(za, idx, flags, &za->error); -} - - - -const char * -_zip_get_name(struct zip *za, int idx, int flags, struct zip_error *error) -{ - if (idx < 0 || idx >= za->nentry) { - _zip_error_set(error, ZIP_ER_INVAL, 0); - return NULL; - } - - if ((flags & ZIP_FL_UNCHANGED) == 0) { - if (za->entry[idx].state == ZIP_ST_DELETED) { - _zip_error_set(error, ZIP_ER_DELETED, 0); - return NULL; - } - if (za->entry[idx].ch_filename) - return za->entry[idx].ch_filename; - } - - if (za->cdir == NULL || idx >= za->cdir->nentry) { - _zip_error_set(error, ZIP_ER_INVAL, 0); - return NULL; - } - - return za->cdir->entry[idx].filename; -} - - -ZIP_EXTERN const char * -zip_get_file_comment(struct zip *za, int idx, int *lenp, int flags) -{ - if (idx < 0 || idx >= za->nentry) { - _zip_error_set(&za->error, ZIP_ER_INVAL, 0); - return NULL; - } - - if ((flags & ZIP_FL_UNCHANGED) - || (za->entry[idx].ch_comment_len == -1)) { - if (lenp != NULL) - *lenp = za->cdir->entry[idx].comment_len; - return za->cdir->entry[idx].comment; - } - - if (lenp != NULL) - *lenp = za->entry[idx].ch_comment_len; - return za->entry[idx].ch_comment; -} - - -ZIP_EXTERN int -zip_get_archive_flag(struct zip *za, int flag, int flags) -{ - int fl; - - fl = (flags & ZIP_FL_UNCHANGED) ? za->flags : za->ch_flags; - - return (fl & flag) ? 1 : 0; -} - - -ZIP_EXTERN const char * -zip_get_archive_comment(struct zip *za, int *lenp, int flags) -{ - if ((flags & ZIP_FL_UNCHANGED) - || (za->ch_comment_len == -1)) { - if (za->cdir) { - if (lenp != NULL) - *lenp = za->cdir->comment_len; - return za->cdir->comment; - } - else { - if (lenp != NULL) - *lenp = -1; - return NULL; - } - } - - if (lenp != NULL) - *lenp = za->ch_comment_len; - return za->ch_comment; -} - - -/* _zip_free: - frees the space allocated to a zipfile struct, and closes the - corresponding file. */ - -void -_zip_free(struct zip *za) -{ - int i; - - if (za == NULL) - return; - - if (za->zn) - free(za->zn); - - if (za->zp) - fclose(za->zp); - - _zip_cdir_free(za->cdir); - - if (za->entry) { - for (i=0; inentry; i++) { - _zip_entry_free(za->entry+i); - } - free(za->entry); - } - - for (i=0; infile; i++) { - if (za->file[i]->error.zip_err == ZIP_ER_OK) { - _zip_error_set(&za->file[i]->error, ZIP_ER_ZIPCLOSED, 0); - za->file[i]->za = NULL; - } - } - - free(za->file); - - free(za); - - return; -} - - -ZIP_EXTERN ssize_t -zip_fread(struct zip_file *zf, void *outbuf, size_t toread) -{ - int ret; - size_t out_before, len; - int i; - - if (!zf) - return -1; - - if (zf->error.zip_err != 0) - return -1; - - if ((zf->flags & ZIP_ZF_EOF) || (toread == 0)) - return 0; - - if (zf->bytes_left == 0) { - zf->flags |= ZIP_ZF_EOF; - if (zf->flags & ZIP_ZF_CRC) { - if (zf->crc != zf->crc_orig) { - _zip_error_set(&zf->error, ZIP_ER_CRC, 0); - return -1; - } - } - return 0; - } - - if ((zf->flags & ZIP_ZF_DECOMP) == 0) { - ret = _zip_file_fillbuf(outbuf, toread, zf); - if (ret > 0) { - if (zf->flags & ZIP_ZF_CRC) - zf->crc = crc32(zf->crc, (Bytef *)outbuf, ret); - zf->bytes_left -= ret; - } - return ret; - } - - zf->zstr->next_out = (Bytef *)outbuf; - zf->zstr->avail_out = toread; - out_before = zf->zstr->total_out; - - /* endless loop until something has been accomplished */ - for (;;) { - ret = inflate(zf->zstr, Z_SYNC_FLUSH); - - switch (ret) { - case Z_OK: - case Z_STREAM_END: - /* all ok */ - /* Z_STREAM_END probably won't happen, since we didn't - have a header */ - len = zf->zstr->total_out - out_before; - if (len >= zf->bytes_left || len >= toread) { - if (zf->flags & ZIP_ZF_CRC) - zf->crc = crc32(zf->crc, (Bytef *)outbuf, len); - zf->bytes_left -= len; - return len; - } - break; - - case Z_BUF_ERROR: - if (zf->zstr->avail_in == 0) { - i = _zip_file_fillbuf(zf->buffer, BUFSIZE, zf); - if (i == 0) { - _zip_error_set(&zf->error, ZIP_ER_INCONS, 0); - return -1; - } - else if (i < 0) - return -1; - zf->zstr->next_in = (Bytef *)zf->buffer; - zf->zstr->avail_in = i; - continue; - } - /* fallthrough */ - case Z_NEED_DICT: - case Z_DATA_ERROR: - case Z_STREAM_ERROR: - case Z_MEM_ERROR: - _zip_error_set(&zf->error, ZIP_ER_ZLIB, ret); - return -1; - } - } -} - - -ZIP_EXTERN const char * -zip_strerror(struct zip *za) -{ - return _zip_error_strerror(&za->error); -} - - -ZIP_EXTERN void -zip_stat_init(struct zip_stat *st) -{ - st->name = NULL; - st->index = -1; - st->crc = 0; - st->mtime = (time_t)-1; - st->size = -1; - st->comp_size = -1; - st->comp_method = ZIP_CM_STORE; - st->encryption_method = ZIP_EM_NONE; -} - - -ZIP_EXTERN int -zip_stat_index(struct zip *za, int index, int flags, struct zip_stat *st) -{ - const char *name; - - if (index < 0 || index >= za->nentry) { - _zip_error_set(&za->error, ZIP_ER_INVAL, 0); - return -1; - } - - if ((name=zip_get_name(za, index, flags)) == NULL) - return -1; - - - if ((flags & ZIP_FL_UNCHANGED) == 0 - && ZIP_ENTRY_DATA_CHANGED(za->entry+index)) { - if (za->entry[index].source->f(za->entry[index].source->ud, - st, sizeof(*st), ZIP_SOURCE_STAT) < 0) { - _zip_error_set(&za->error, ZIP_ER_CHANGED, 0); - return -1; - } - } - else { - if (za->cdir == NULL || index >= za->cdir->nentry) { - _zip_error_set(&za->error, ZIP_ER_INVAL, 0); - return -1; - } - - st->crc = za->cdir->entry[index].crc; - st->size = za->cdir->entry[index].uncomp_size; - st->mtime = za->cdir->entry[index].last_mod; - st->comp_size = za->cdir->entry[index].comp_size; - st->comp_method = za->cdir->entry[index].comp_method; - if (za->cdir->entry[index].bitflags & ZIP_GPBF_ENCRYPTED) { - if (za->cdir->entry[index].bitflags & ZIP_GPBF_STRONG_ENCRYPTION) { - /* XXX */ - st->encryption_method = ZIP_EM_UNKNOWN; - } - else - st->encryption_method = ZIP_EM_TRAD_PKWARE; - } - else - st->encryption_method = ZIP_EM_NONE; - /* st->bitflags = za->cdir->entry[index].bitflags; */ - } - - st->index = index; - st->name = name; - - return 0; -} - - -ZIP_EXTERN int -zip_stat(struct zip *za, const char *fname, int flags, struct zip_stat *st) -{ - int idx; - - if ((idx=zip_name_locate(za, fname, flags)) < 0) - return -1; - - return zip_stat_index(za, idx, flags, st); -} - - -struct read_zip { - struct zip_file *zf; - struct zip_stat st; - myoff_t off, len; -}; - -static ssize_t read_zip(void *st, void *data, size_t len, - enum zip_source_cmd cmd); - - - -ZIP_EXTERN struct zip_source * -zip_source_zip(struct zip *za, struct zip *srcza, int srcidx, int flags, - myoff_t start, myoff_t len) -{ - struct zip_error error; - struct zip_source *zs; - struct read_zip *p; - - /* XXX: ZIP_FL_RECOMPRESS */ - - if (za == NULL) - return NULL; - - if (srcza == NULL || start < 0 || len < -1 || srcidx < 0 || srcidx >= srcza->nentry) { - _zip_error_set(&za->error, ZIP_ER_INVAL, 0); - return NULL; - } - - if ((flags & ZIP_FL_UNCHANGED) == 0 - && ZIP_ENTRY_DATA_CHANGED(srcza->entry+srcidx)) { - _zip_error_set(&za->error, ZIP_ER_CHANGED, 0); - return NULL; - } - - if (len == 0) - len = -1; - - if (start == 0 && len == -1 && (flags & ZIP_FL_RECOMPRESS) == 0) - flags |= ZIP_FL_COMPRESSED; - else - flags &= ~ZIP_FL_COMPRESSED; - - if ((p=(struct read_zip *)malloc(sizeof(*p))) == NULL) { - _zip_error_set(&za->error, ZIP_ER_MEMORY, 0); - return NULL; - } - - _zip_error_copy(&error, &srcza->error); - - if (zip_stat_index(srcza, srcidx, flags, &p->st) < 0 - || (p->zf=zip_fopen_index(srcza, srcidx, flags)) == NULL) { - free(p); - _zip_error_copy(&za->error, &srcza->error); - _zip_error_copy(&srcza->error, &error); - - return NULL; - } - p->off = start; - p->len = len; - - if ((flags & ZIP_FL_COMPRESSED) == 0) { - p->st.size = p->st.comp_size = len; - p->st.comp_method = ZIP_CM_STORE; - p->st.crc = 0; - } - - if ((zs=zip_source_function(za, read_zip, p)) == NULL) { - free(p); - return NULL; - } - - return zs; -} - - - -static ssize_t -read_zip(void *state, void *data, size_t len, enum zip_source_cmd cmd) -{ - struct read_zip *z; - char b[8192], *buf; - int i, n; - - z = (struct read_zip *)state; - buf = (char *)data; - - switch (cmd) { - case ZIP_SOURCE_OPEN: - for (n=0; noff; n+= i) { - i = (z->off-n > sizeof(b) ? sizeof(b) : z->off-n); - if ((i=zip_fread(z->zf, b, i)) < 0) { - zip_fclose(z->zf); - z->zf = NULL; - return -1; - } - } - return 0; - - case ZIP_SOURCE_READ: - if (z->len != -1) - n = len > z->len ? z->len : len; - else - n = len; - - - if ((i=zip_fread(z->zf, buf, n)) < 0) - return -1; - - if (z->len != -1) - z->len -= i; - - return i; - - case ZIP_SOURCE_CLOSE: - return 0; - - case ZIP_SOURCE_STAT: - if (len < sizeof(z->st)) - return -1; - len = sizeof(z->st); - - memcpy(data, &z->st, len); - return len; - - case ZIP_SOURCE_ERROR: - { - int *e; - - if (len < sizeof(int)*2) - return -1; - - e = (int *)data; - zip_file_error_get(z->zf, e, e+1); - } - return sizeof(int)*2; - - case ZIP_SOURCE_FREE: - zip_fclose(z->zf); - free(z); - return 0; - - default: - ; - } - - return -1; -} - - -ZIP_EXTERN struct zip_source * -zip_source_function(struct zip *za, zip_source_callback zcb, void *ud) -{ - struct zip_source *zs; - - if (za == NULL) - return NULL; - - if ((zs=(struct zip_source *)malloc(sizeof(*zs))) == NULL) { - _zip_error_set(&za->error, ZIP_ER_MEMORY, 0); - return NULL; - } - - zs->f = zcb; - zs->ud = ud; - - return zs; -} - - -ZIP_EXTERN void -zip_source_free(struct zip_source *source) -{ - if (source == NULL) - return; - - (void)source->f(source->ud, NULL, 0, ZIP_SOURCE_FREE); - - free(source); -} - - -struct read_file { - char *fname; /* name of file to copy from */ - FILE *f; /* file to copy from */ - myoff_t off; /* start offset of */ - myoff_t len; /* lengt of data to copy */ - myoff_t remain; /* bytes remaining to be copied */ - int e[2]; /* error codes */ -}; - -static ssize_t read_file(void *state, void *data, size_t len, - enum zip_source_cmd cmd); - - - -ZIP_EXTERN struct zip_source * -zip_source_filep(struct zip *za, FILE *file, myoff_t start, myoff_t len) -{ - if (za == NULL) - return NULL; - - if (file == NULL || start < 0 || len < -1) { - _zip_error_set(&za->error, ZIP_ER_INVAL, 0); - return NULL; - } - - return _zip_source_file_or_p(za, NULL, file, start, len); -} - - - -struct zip_source * -_zip_source_file_or_p(struct zip *za, const char *fname, FILE *file, - myoff_t start, myoff_t len) -{ - struct read_file *f; - struct zip_source *zs; - - if (file == NULL && fname == NULL) { - _zip_error_set(&za->error, ZIP_ER_INVAL, 0); - return NULL; - } - - if ((f=(struct read_file *)malloc(sizeof(struct read_file))) == NULL) { - _zip_error_set(&za->error, ZIP_ER_MEMORY, 0); - return NULL; - } - - f->fname = NULL; - if (fname) { - if ((f->fname=strdup(fname)) == NULL) { - _zip_error_set(&za->error, ZIP_ER_MEMORY, 0); - free(f); - return NULL; - } - } - f->f = file; - f->off = start; - f->len = (len ? len : -1); - - if ((zs=zip_source_function(za, read_file, f)) == NULL) { - free(f); - return NULL; - } - - return zs; -} - - - -static ssize_t -read_file(void *state, void *data, size_t len, enum zip_source_cmd cmd) -{ - struct read_file *z; - char *buf; - int i, n; - - z = (struct read_file *)state; - buf = (char *)data; - - switch (cmd) { - case ZIP_SOURCE_OPEN: - if (z->fname) { - if ((z->f=fopen(z->fname, "rb")) == NULL) { - z->e[0] = ZIP_ER_OPEN; - z->e[1] = errno; - return -1; - } - } - - if (fseeko(z->f, z->off, SEEK_SET) < 0) { - z->e[0] = ZIP_ER_SEEK; - z->e[1] = errno; - return -1; - } - z->remain = z->len; - return 0; - - case ZIP_SOURCE_READ: - if (z->remain != -1) - n = len > z->remain ? z->remain : len; - else - n = len; - - if ((i=fread(buf, 1, n, z->f)) < 0) { - z->e[0] = ZIP_ER_READ; - z->e[1] = errno; - return -1; - } - - if (z->remain != -1) - z->remain -= i; - - return i; - - case ZIP_SOURCE_CLOSE: - if (z->fname) { - fclose(z->f); - z->f = NULL; - } - return 0; - - case ZIP_SOURCE_STAT: - { - struct zip_stat *st; - struct stat fst; - int err; - - if (len < sizeof(*st)) - return -1; - - if (z->f) - err = fstat(fileno(z->f), &fst); - else - err = stat(z->fname, &fst); - - if (err != 0) { - z->e[0] = ZIP_ER_READ; /* best match */ - z->e[1] = errno; - return -1; - } - - st = (struct zip_stat *)data; - - zip_stat_init(st); - st->mtime = fst.st_mtime; - if (z->len != -1) - st->size = z->len; - else if ((fst.st_mode&S_IFMT) == S_IFREG) - st->size = fst.st_size; - - return sizeof(*st); - } - - case ZIP_SOURCE_ERROR: - if (len < sizeof(int)*2) - return -1; - - memcpy(data, z->e, sizeof(int)*2); - return sizeof(int)*2; - - case ZIP_SOURCE_FREE: - free(z->fname); - if (z->f) - fclose(z->f); - free(z); - return 0; - - default: - ; - } - - return -1; -} - - -ZIP_EXTERN int -zip_name_locate(struct zip *za, const char *fname, int flags) -{ - return _zip_name_locate(za, fname, flags, &za->error); -} - - - -int -_zip_name_locate(struct zip *za, const char *fname, int flags, - struct zip_error *error) -{ - int (*cmp)(const char *, const char *); - const char *fn, *p; - int i, n; - - if (fname == NULL) { - _zip_error_set(error, ZIP_ER_INVAL, 0); - return -1; - } - - cmp = (flags & ZIP_FL_NOCASE) ? strcasecmp : strcmp; - - n = (flags & ZIP_FL_UNCHANGED) ? za->cdir->nentry : za->nentry; - for (i=0; icdir->entry[i].filename; - else - fn = _zip_get_name(za, i, flags, error); - - /* newly added (partially filled) entry */ - if (fn == NULL) - continue; - - if (flags & ZIP_FL_NODIR) { - p = strrchr(fn, '/'); - if (p) - fn = p+1; - } - - if (cmp(fname, fn) == 0) - return i; - } - - _zip_error_set(error, ZIP_ER_NOENT, 0); - return -1; -} - diff --git a/lib/wrappers/zip/zlib.nim b/lib/wrappers/zip/zlib.nim deleted file mode 100644 index 6bb582b79..000000000 --- a/lib/wrappers/zip/zlib.nim +++ /dev/null @@ -1,312 +0,0 @@ -# Converted from Pascal - -## Interface to the zlib http://www.zlib.net/ compression library. - -when defined(windows): - const libz = "zlib1.dll" -elif defined(macosx): - const libz = "libz.dylib" -else: - const libz = "libz.so.1" - -type - Uint* = int32 - Ulong* = int - Ulongf* = int - Pulongf* = ptr Ulongf - ZOffT* = int32 - Pbyte* = cstring - Pbytef* = cstring - Allocfunc* = proc (p: pointer, items: Uint, size: Uint): pointer{.cdecl.} - FreeFunc* = proc (p: pointer, address: pointer){.cdecl.} - InternalState*{.final, pure.} = object - PInternalState* = ptr InternalState - ZStream*{.final, pure.} = object - nextIn*: Pbytef - availIn*: Uint - totalIn*: Ulong - nextOut*: Pbytef - availOut*: Uint - totalOut*: Ulong - msg*: Pbytef - state*: PInternalState - zalloc*: Allocfunc - zfree*: FreeFunc - opaque*: pointer - dataType*: int32 - adler*: Ulong - reserved*: Ulong - - ZStreamRec* = ZStream - PZstream* = ptr ZStream - GzFile* = pointer -{.deprecated: [TInternalState: InternalState, TAllocfunc: Allocfunc, - TFreeFunc: FreeFunc, TZStream: ZStream, TZStreamRec: ZStreamRec].} - -const - Z_NO_FLUSH* = 0 - Z_PARTIAL_FLUSH* = 1 - Z_SYNC_FLUSH* = 2 - Z_FULL_FLUSH* = 3 - Z_FINISH* = 4 - Z_OK* = 0 - Z_STREAM_END* = 1 - Z_NEED_DICT* = 2 - Z_ERRNO* = -1 - Z_STREAM_ERROR* = -2 - Z_DATA_ERROR* = -3 - Z_MEM_ERROR* = -4 - Z_BUF_ERROR* = -5 - Z_VERSION_ERROR* = -6 - Z_NO_COMPRESSION* = 0 - Z_BEST_SPEED* = 1 - Z_BEST_COMPRESSION* = 9 - Z_DEFAULT_COMPRESSION* = -1 - Z_FILTERED* = 1 - Z_HUFFMAN_ONLY* = 2 - Z_DEFAULT_STRATEGY* = 0 - Z_BINARY* = 0 - Z_ASCII* = 1 - Z_UNKNOWN* = 2 - Z_DEFLATED* = 8 - Z_NULL* = 0 - -proc zlibVersion*(): cstring{.cdecl, dynlib: libz, importc: "zlibVersion".} -proc deflate*(strm: var ZStream, flush: int32): int32{.cdecl, dynlib: libz, - importc: "deflate".} -proc deflateEnd*(strm: var ZStream): int32{.cdecl, dynlib: libz, - importc: "deflateEnd".} -proc inflate*(strm: var ZStream, flush: int32): int32{.cdecl, dynlib: libz, - importc: "inflate".} -proc inflateEnd*(strm: var ZStream): int32{.cdecl, dynlib: libz, - importc: "inflateEnd".} -proc deflateSetDictionary*(strm: var ZStream, dictionary: Pbytef, - dictLength: Uint): int32{.cdecl, dynlib: libz, - importc: "deflateSetDictionary".} -proc deflateCopy*(dest, source: var ZStream): int32{.cdecl, dynlib: libz, - importc: "deflateCopy".} -proc deflateReset*(strm: var ZStream): int32{.cdecl, dynlib: libz, - importc: "deflateReset".} -proc deflateParams*(strm: var ZStream, level: int32, strategy: int32): int32{. - cdecl, dynlib: libz, importc: "deflateParams".} -proc inflateSetDictionary*(strm: var ZStream, dictionary: Pbytef, - dictLength: Uint): int32{.cdecl, dynlib: libz, - importc: "inflateSetDictionary".} -proc inflateSync*(strm: var ZStream): int32{.cdecl, dynlib: libz, - importc: "inflateSync".} -proc inflateReset*(strm: var ZStream): int32{.cdecl, dynlib: libz, - importc: "inflateReset".} -proc compress*(dest: Pbytef, destLen: Pulongf, source: Pbytef, sourceLen: Ulong): cint{. - cdecl, dynlib: libz, importc: "compress".} -proc compress2*(dest: Pbytef, destLen: Pulongf, source: Pbytef, - sourceLen: Ulong, level: cint): cint{.cdecl, dynlib: libz, - importc: "compress2".} -proc uncompress*(dest: Pbytef, destLen: Pulongf, source: Pbytef, - sourceLen: Ulong): cint{.cdecl, dynlib: libz, - importc: "uncompress".} -proc compressBound*(sourceLen: Ulong): Ulong {.cdecl, dynlib: libz, importc.} -proc gzopen*(path: cstring, mode: cstring): GzFile{.cdecl, dynlib: libz, - importc: "gzopen".} -proc gzdopen*(fd: int32, mode: cstring): GzFile{.cdecl, dynlib: libz, - importc: "gzdopen".} -proc gzsetparams*(thefile: GzFile, level: int32, strategy: int32): int32{.cdecl, - dynlib: libz, importc: "gzsetparams".} -proc gzread*(thefile: GzFile, buf: pointer, length: int): int32{.cdecl, - dynlib: libz, importc: "gzread".} -proc gzwrite*(thefile: GzFile, buf: pointer, length: int): int32{.cdecl, - dynlib: libz, importc: "gzwrite".} -proc gzprintf*(thefile: GzFile, format: Pbytef): int32{.varargs, cdecl, - dynlib: libz, importc: "gzprintf".} -proc gzputs*(thefile: GzFile, s: Pbytef): int32{.cdecl, dynlib: libz, - importc: "gzputs".} -proc gzgets*(thefile: GzFile, buf: Pbytef, length: int32): Pbytef{.cdecl, - dynlib: libz, importc: "gzgets".} -proc gzputc*(thefile: GzFile, c: char): char{.cdecl, dynlib: libz, - importc: "gzputc".} -proc gzgetc*(thefile: GzFile): char{.cdecl, dynlib: libz, importc: "gzgetc".} -proc gzflush*(thefile: GzFile, flush: int32): int32{.cdecl, dynlib: libz, - importc: "gzflush".} -proc gzseek*(thefile: GzFile, offset: ZOffT, whence: int32): ZOffT{.cdecl, - dynlib: libz, importc: "gzseek".} -proc gzrewind*(thefile: GzFile): int32{.cdecl, dynlib: libz, importc: "gzrewind".} -proc gztell*(thefile: GzFile): ZOffT{.cdecl, dynlib: libz, importc: "gztell".} -proc gzeof*(thefile: GzFile): int {.cdecl, dynlib: libz, importc: "gzeof".} -proc gzclose*(thefile: GzFile): int32{.cdecl, dynlib: libz, importc: "gzclose".} -proc gzerror*(thefile: GzFile, errnum: var int32): Pbytef{.cdecl, dynlib: libz, - importc: "gzerror".} -proc adler32*(adler: Ulong, buf: Pbytef, length: Uint): Ulong{.cdecl, - dynlib: libz, importc: "adler32".} - ## **Warning**: Adler-32 requires at least a few hundred bytes to get rolling. -proc crc32*(crc: Ulong, buf: Pbytef, length: Uint): Ulong{.cdecl, dynlib: libz, - importc: "crc32".} -proc deflateInitu*(strm: var ZStream, level: int32, version: cstring, - streamSize: int32): int32{.cdecl, dynlib: libz, - importc: "deflateInit_".} -proc inflateInitu*(strm: var ZStream, version: cstring, - streamSize: int32): int32 {. - cdecl, dynlib: libz, importc: "inflateInit_".} -proc deflateInit*(strm: var ZStream, level: int32): int32 -proc inflateInit*(strm: var ZStream): int32 -proc deflateInit2u*(strm: var ZStream, level: int32, `method`: int32, - windowBits: int32, memLevel: int32, strategy: int32, - version: cstring, streamSize: int32): int32 {.cdecl, - dynlib: libz, importc: "deflateInit2_".} -proc inflateInit2u*(strm: var ZStream, windowBits: int32, version: cstring, - streamSize: int32): int32{.cdecl, dynlib: libz, - importc: "inflateInit2_".} -proc deflateInit2*(strm: var ZStream, - level, `method`, windowBits, memLevel, - strategy: int32): int32 -proc inflateInit2*(strm: var ZStream, windowBits: int32): int32 -proc zError*(err: int32): cstring{.cdecl, dynlib: libz, importc: "zError".} -proc inflateSyncPoint*(z: PZstream): int32{.cdecl, dynlib: libz, - importc: "inflateSyncPoint".} -proc getCrcTable*(): pointer{.cdecl, dynlib: libz, importc: "get_crc_table".} - -proc deflateInit(strm: var ZStream, level: int32): int32 = - result = deflateInitu(strm, level, zlibVersion(), sizeof(ZStream).cint) - -proc inflateInit(strm: var ZStream): int32 = - result = inflateInitu(strm, zlibVersion(), sizeof(ZStream).cint) - -proc deflateInit2(strm: var ZStream, - level, `method`, windowBits, memLevel, - strategy: int32): int32 = - result = deflateInit2u(strm, level, `method`, windowBits, memLevel, - strategy, zlibVersion(), sizeof(ZStream).cint) - -proc inflateInit2(strm: var ZStream, windowBits: int32): int32 = - result = inflateInit2u(strm, windowBits, zlibVersion(), - sizeof(ZStream).cint) - -proc zlibAllocMem*(appData: pointer, items, size: int): pointer {.cdecl.} = - result = alloc(items * size) - -proc zlibFreeMem*(appData, `block`: pointer) {.cdecl.} = - dealloc(`block`) - -proc uncompress*(sourceBuf: cstring, sourceLen: int): string = - ## Given a deflated cstring returns its inflated version. - ## - ## Passing a nil cstring will crash this proc in release mode and assert in - ## debug mode. - ## - ## Returns nil on problems. Failure is a very loose concept, it could be you - ## passing a non deflated string, or it could mean not having enough memory - ## for the inflated version. - ## - ## The uncompression algorithm is based on - ## http://stackoverflow.com/questions/17820664 but does ignore some of the - ## original signed/unsigned checks, so may fail with big chunks of data - ## exceeding the positive size of an int32. The algorithm can deal with - ## concatenated deflated values properly. - assert (not sourceBuf.isNil) - - var z: ZStream - # Initialize input. - z.nextIn = sourceBuf - - # Input left to decompress. - var left = zlib.Uint(sourceLen) - if left < 1: - # Incomplete gzip stream, or overflow? - return - - # Create starting space for output (guess double the input size, will grow if - # needed -- in an extreme case, could end up needing more than 1000 times the - # input size) - var space = zlib.Uint(left shl 1) - if space < left: - space = left - - var decompressed = newStringOfCap(space) - - # Initialize output. - z.nextOut = addr(decompressed[0]) - # Output generated so far. - var have = 0 - - # Set up for gzip decoding. - z.availIn = 0; - var status = inflateInit2(z, (15+16)) - if status != Z_OK: - # Out of memory. - return - - # Make sure memory allocated by inflateInit2() is freed eventually. - defer: discard inflateEnd(z) - - # Decompress all of self. - while true: - # Allow for concatenated gzip streams (per RFC 1952). - if status == Z_STREAM_END: - discard inflateReset(z) - - # Provide input for inflate. - if z.availIn == 0: - # This only makes sense in the C version using unsigned values. - z.availIn = left - left -= z.availIn - - # Decompress the available input. - while true: - # Allocate more output space if none left. - if space == have: - # Double space, handle overflow. - space = space shl 1 - if space < have: - # Space was likely already maxed out. - discard inflateEnd(z) - return - - # Increase space. - decompressed.setLen(space) - # Update output pointer (might have moved). - z.nextOut = addr(decompressed[have]) - - # Provide output space for inflate. - z.availOut = zlib.Uint(space - have) - have += z.availOut; - - # Inflate and update the decompressed size. - status = inflate(z, Z_SYNC_FLUSH); - have -= z.availOut; - - # Bail out if any errors. - if status != Z_OK and status != Z_BUF_ERROR and status != Z_STREAM_END: - # Invalid gzip stream. - discard inflateEnd(z) - return - - # Repeat until all output is generated from provided input (note - # that even if z.avail_in is zero, there may still be pending - # output -- we're not done until the output buffer isn't filled) - if z.availOut != 0: - break - # Continue until all input consumed. - if left == 0 and z.availIn == 0: - break - - # Verify that the input is a valid gzip stream. - if status != Z_STREAM_END: - # Incomplete gzip stream. - return - - decompressed.setLen(have) - swap(result, decompressed) - - -proc inflate*(buffer: var string): bool {.discardable.} = - ## Convenience proc which inflates a string containing compressed data. - ## - ## Passing a nil string will crash this proc in release mode and assert in - ## debug mode. It is ok to pass a buffer which doesn't contain deflated data, - ## in this case the proc won't modify the buffer. - ## - ## Returns true if `buffer` was successfully inflated. - assert (not buffer.isNil) - if buffer.len < 1: return - var temp = uncompress(addr(buffer[0]), buffer.len) - if not temp.isNil: - swap(buffer, temp) - result = true diff --git a/lib/wrappers/zip/zzip.nim b/lib/wrappers/zip/zzip.nim deleted file mode 100644 index fab7d55b3..000000000 --- a/lib/wrappers/zip/zzip.nim +++ /dev/null @@ -1,176 +0,0 @@ -# -# -# Nim's Runtime Library -# (c) Copyright 2008 Andreas Rumpf -# -# See the file "copying.txt", included in this -# distribution, for details about the copyright. -# - -## This module is an interface to the zzip library. - -# Author: -# Guido Draheim -# Tomi Ollila -# Copyright (c) 1999,2000,2001,2002,2003,2004 Guido Draheim -# All rights reserved, -# usage allowed under the restrictions of the -# Lesser GNU General Public License -# or alternatively the restrictions -# of the Mozilla Public License 1.1 - -when defined(windows): - const - dllname = "zzip.dll" -else: - const - dllname = "libzzip.so" - -type - TZZipError* = int32 # Name conflict if we drop the `T` - -const - ZZIP_ERROR* = -4096'i32 - ZZIP_NO_ERROR* = 0'i32 # no error, may be used if user sets it. - ZZIP_OUTOFMEM* = ZZIP_ERROR - 20'i32 # out of memory - ZZIP_DIR_OPEN* = ZZIP_ERROR - 21'i32 # failed to open zipfile, see errno for details - ZZIP_DIR_STAT* = ZZIP_ERROR - 22'i32 # failed to fstat zipfile, see errno for details - ZZIP_DIR_SEEK* = ZZIP_ERROR - 23'i32 # failed to lseek zipfile, see errno for details - ZZIP_DIR_READ* = ZZIP_ERROR - 24'i32 # failed to read zipfile, see errno for details - ZZIP_DIR_TOO_SHORT* = ZZIP_ERROR - 25'i32 - ZZIP_DIR_EDH_MISSING* = ZZIP_ERROR - 26'i32 - ZZIP_DIRSIZE* = ZZIP_ERROR - 27'i32 - ZZIP_ENOENT* = ZZIP_ERROR - 28'i32 - ZZIP_UNSUPP_COMPR* = ZZIP_ERROR - 29'i32 - ZZIP_CORRUPTED* = ZZIP_ERROR - 31'i32 - ZZIP_UNDEF* = ZZIP_ERROR - 32'i32 - ZZIP_DIR_LARGEFILE* = ZZIP_ERROR - 33'i32 - - ZZIP_CASELESS* = 1'i32 shl 12'i32 - ZZIP_NOPATHS* = 1'i32 shl 13'i32 - ZZIP_PREFERZIP* = 1'i32 shl 14'i32 - ZZIP_ONLYZIP* = 1'i32 shl 16'i32 - ZZIP_FACTORY* = 1'i32 shl 17'i32 - ZZIP_ALLOWREAL* = 1'i32 shl 18'i32 - ZZIP_THREADED* = 1'i32 shl 19'i32 - -type - ZZipDir* {.final, pure.} = object - ZZipFile* {.final, pure.} = object - ZZipPluginIO* {.final, pure.} = object - - ZZipDirent* {.final, pure.} = object - d_compr*: int32 ## compression method - d_csize*: int32 ## compressed size - st_size*: int32 ## file size / decompressed size - d_name*: cstring ## file name / strdupped name - - ZZipStat* = ZZipDirent -{.deprecated: [TZZipDir: ZzipDir, TZZipFile: ZzipFile, - TZZipPluginIO: ZzipPluginIO, TZZipDirent: ZzipDirent, - TZZipStat: ZZipStat].} - -proc zzip_strerror*(errcode: int32): cstring {.cdecl, dynlib: dllname, - importc: "zzip_strerror".} -proc zzip_strerror_of*(dir: ptr ZZipDir): cstring {.cdecl, dynlib: dllname, - importc: "zzip_strerror_of".} -proc zzip_errno*(errcode: int32): int32 {.cdecl, dynlib: dllname, - importc: "zzip_errno".} - -proc zzip_geterror*(dir: ptr ZZipDir): int32 {.cdecl, dynlib: dllname, - importc: "zzip_error".} -proc zzip_seterror*(dir: ptr ZZipDir, errcode: int32) {.cdecl, dynlib: dllname, - importc: "zzip_seterror".} -proc zzip_compr_str*(compr: int32): cstring {.cdecl, dynlib: dllname, - importc: "zzip_compr_str".} -proc zzip_dirhandle*(fp: ptr ZZipFile): ptr ZZipDir {.cdecl, dynlib: dllname, - importc: "zzip_dirhandle".} -proc zzip_dirfd*(dir: ptr ZZipDir): int32 {.cdecl, dynlib: dllname, - importc: "zzip_dirfd".} -proc zzip_dir_real*(dir: ptr ZZipDir): int32 {.cdecl, dynlib: dllname, - importc: "zzip_dir_real".} -proc zzip_file_real*(fp: ptr ZZipFile): int32 {.cdecl, dynlib: dllname, - importc: "zzip_file_real".} -proc zzip_realdir*(dir: ptr ZZipDir): pointer {.cdecl, dynlib: dllname, - importc: "zzip_realdir".} -proc zzip_realfd*(fp: ptr ZZipFile): int32 {.cdecl, dynlib: dllname, - importc: "zzip_realfd".} - -proc zzip_dir_alloc*(fileext: cstringArray): ptr ZZipDir {.cdecl, - dynlib: dllname, importc: "zzip_dir_alloc".} -proc zzip_dir_free*(para1: ptr ZZipDir): int32 {.cdecl, dynlib: dllname, - importc: "zzip_dir_free".} - -proc zzip_dir_fdopen*(fd: int32, errcode_p: ptr TZZipError): ptr ZZipDir {.cdecl, - dynlib: dllname, importc: "zzip_dir_fdopen".} -proc zzip_dir_open*(filename: cstring, errcode_p: ptr TZZipError): ptr ZZipDir {. - cdecl, dynlib: dllname, importc: "zzip_dir_open".} -proc zzip_dir_close*(dir: ptr ZZipDir) {.cdecl, dynlib: dllname, - importc: "zzip_dir_close".} -proc zzip_dir_read*(dir: ptr ZZipDir, dirent: ptr ZZipDirent): int32 {.cdecl, - dynlib: dllname, importc: "zzip_dir_read".} - -proc zzip_opendir*(filename: cstring): ptr ZZipDir {.cdecl, dynlib: dllname, - importc: "zzip_opendir".} -proc zzip_closedir*(dir: ptr ZZipDir) {.cdecl, dynlib: dllname, - importc: "zzip_closedir".} -proc zzip_readdir*(dir: ptr ZZipDir): ptr ZZipDirent {.cdecl, dynlib: dllname, - importc: "zzip_readdir".} -proc zzip_rewinddir*(dir: ptr ZZipDir) {.cdecl, dynlib: dllname, - importc: "zzip_rewinddir".} -proc zzip_telldir*(dir: ptr ZZipDir): int {.cdecl, dynlib: dllname, - importc: "zzip_telldir".} -proc zzip_seekdir*(dir: ptr ZZipDir, offset: int) {.cdecl, dynlib: dllname, - importc: "zzip_seekdir".} - -proc zzip_file_open*(dir: ptr ZZipDir, name: cstring, flags: int32): ptr ZZipFile {. - cdecl, dynlib: dllname, importc: "zzip_file_open".} -proc zzip_file_close*(fp: ptr ZZipFile) {.cdecl, dynlib: dllname, - importc: "zzip_file_close".} -proc zzip_file_read*(fp: ptr ZZipFile, buf: pointer, length: int): int {. - cdecl, dynlib: dllname, importc: "zzip_file_read".} -proc zzip_open*(name: cstring, flags: int32): ptr ZZipFile {.cdecl, - dynlib: dllname, importc: "zzip_open".} -proc zzip_close*(fp: ptr ZZipFile) {.cdecl, dynlib: dllname, - importc: "zzip_close".} -proc zzip_read*(fp: ptr ZZipFile, buf: pointer, length: int): int {. - cdecl, dynlib: dllname, importc: "zzip_read".} - -proc zzip_freopen*(name: cstring, mode: cstring, para3: ptr ZZipFile): ptr ZZipFile {. - cdecl, dynlib: dllname, importc: "zzip_freopen".} -proc zzip_fopen*(name: cstring, mode: cstring): ptr ZZipFile {.cdecl, - dynlib: dllname, importc: "zzip_fopen".} -proc zzip_fread*(p: pointer, size: int, nmemb: int, - file: ptr ZZipFile): int {.cdecl, dynlib: dllname, - importc: "zzip_fread".} -proc zzip_fclose*(fp: ptr ZZipFile) {.cdecl, dynlib: dllname, - importc: "zzip_fclose".} - -proc zzip_rewind*(fp: ptr ZZipFile): int32 {.cdecl, dynlib: dllname, - importc: "zzip_rewind".} -proc zzip_seek*(fp: ptr ZZipFile, offset: int, whence: int32): int {. - cdecl, dynlib: dllname, importc: "zzip_seek".} -proc zzip_tell*(fp: ptr ZZipFile): int {.cdecl, dynlib: dllname, - importc: "zzip_tell".} - -proc zzip_dir_stat*(dir: ptr ZZipDir, name: cstring, zs: ptr ZZipStat, - flags: int32): int32 {.cdecl, dynlib: dllname, - importc: "zzip_dir_stat".} -proc zzip_file_stat*(fp: ptr ZZipFile, zs: ptr ZZipStat): int32 {.cdecl, - dynlib: dllname, importc: "zzip_file_stat".} -proc zzip_fstat*(fp: ptr ZZipFile, zs: ptr ZZipStat): int32 {.cdecl, dynlib: dllname, - importc: "zzip_fstat".} - -proc zzip_open_shared_io*(stream: ptr ZZipFile, name: cstring, - o_flags: int32, o_modes: int32, ext: cstringArray, - io: ptr ZZipPluginIO): ptr ZZipFile {.cdecl, - dynlib: dllname, importc: "zzip_open_shared_io".} -proc zzip_open_ext_io*(name: cstring, o_flags: int32, o_modes: int32, - ext: cstringArray, io: ptr ZZipPluginIO): ptr ZZipFile {. - cdecl, dynlib: dllname, importc: "zzip_open_ext_io".} -proc zzip_opendir_ext_io*(name: cstring, o_modes: int32, - ext: cstringArray, io: ptr ZZipPluginIO): ptr ZZipDir {. - cdecl, dynlib: dllname, importc: "zzip_opendir_ext_io".} -proc zzip_dir_open_ext_io*(filename: cstring, errcode_p: ptr TZZipError, - ext: cstringArray, io: ptr ZZipPluginIO): ptr ZZipDir {. - cdecl, dynlib: dllname, importc: "zzip_dir_open_ext_io".} diff --git a/tests/generics/tcan_alias_generic.nim b/tests/generics/tcan_alias_generic.nim index 780a47841..b357b33e9 100644 --- a/tests/generics/tcan_alias_generic.nim +++ b/tests/generics/tcan_alias_generic.nim @@ -2,10 +2,9 @@ ## can_alias_generic Nim Module ## ## Created by Eric Doughty-Papassideris on 2011-02-16. -## Copyright (c) 2011 FWA. All rights reserved. type TGen[T] = object TGen2[T] = TGen[T] - + diff --git a/tests/generics/tcan_alias_specialised_generic.nim b/tests/generics/tcan_alias_specialised_generic.nim index a737d3580..c94edd611 100644 --- a/tests/generics/tcan_alias_specialised_generic.nim +++ b/tests/generics/tcan_alias_specialised_generic.nim @@ -6,12 +6,11 @@ discard """ ## can_alias_specialised_generic Nim Module ## ## Created by Eric Doughty-Papassideris on 2011-02-16. -## Copyright (c) 2011 FWA. All rights reserved. type TGen[T] = object TSpef = TGen[string] - + var s: TSpef diff --git a/tests/generics/tcan_inherit_generic.nim b/tests/generics/tcan_inherit_generic.nim index ce2b6452f..331fcfd5c 100644 --- a/tests/generics/tcan_inherit_generic.nim +++ b/tests/generics/tcan_inherit_generic.nim @@ -2,12 +2,11 @@ ## can_inherit_generic Nim Module ## ## Created by Eric Doughty-Papassideris on 2011-02-16. -## Copyright (c) 2011 FWA. All rights reserved. type TGen[T] = object of TObject x, y: T - + TSpef[T] = object of TGen[T] diff --git a/tests/generics/tcan_specialise_generic.nim b/tests/generics/tcan_specialise_generic.nim index c510910e8..78896db38 100644 --- a/tests/generics/tcan_specialise_generic.nim +++ b/tests/generics/tcan_specialise_generic.nim @@ -2,10 +2,9 @@ ## can_specialise_generic Nim Module ## ## Created by Eric Doughty-Papassideris on 2011-02-16. -## Copyright (c) 2011 FWA. All rights reserved. type TGen[T] = object {.inheritable.} TSpef = object of TGen[string] - + diff --git a/tests/generics/tspecialised_is_equivalent.nim b/tests/generics/tspecialised_is_equivalent.nim index ace562862..56fd72630 100644 --- a/tests/generics/tspecialised_is_equivalent.nim +++ b/tests/generics/tspecialised_is_equivalent.nim @@ -2,7 +2,6 @@ ## specialised_is_equivalent Nim Module ## ## Created by Eric Doughty-Papassideris on 2011-02-16. -## Copyright (c) 2011 FWA. All rights reserved. type TGen[T] = tuple[a: T] diff --git a/tools/niminst/niminst.nim b/tools/niminst/niminst.nim index 253543a50..d1216701f 100644 --- a/tools/niminst/niminst.nim +++ b/tools/niminst/niminst.nim @@ -8,7 +8,7 @@ # const - haveZipLib = defined(unix) + haveZipLib = false # zip not in stdlib anymore when haveZipLib: import zipfiles diff --git a/web/website.ini b/web/website.ini index bb9f1b204..fb98d639a 100644 --- a/web/website.ini +++ b/web/website.ini @@ -43,13 +43,12 @@ srcdoc2: "pure/complex;pure/times;pure/osproc;pure/pegs;pure/dynlib" srcdoc2: "pure/parseopt;pure/parseopt2;pure/hashes;pure/strtabs;pure/lexbase" srcdoc2: "pure/parsecfg;pure/parsexml;pure/parsecsv;pure/parsesql" srcdoc2: "pure/streams;pure/terminal;pure/cgi;pure/unicode" -srcdoc2: "impure/zipfiles;pure/htmlgen;pure/parseutils;pure/browsers" +srcdoc2: "pure/htmlgen;pure/parseutils;pure/browsers" srcdoc2: "impure/db_postgres;impure/db_mysql;impure/db_sqlite" srcdoc2: "pure/httpserver;pure/httpclient;pure/smtp;impure/ssl;pure/fsmonitor" srcdoc2: "pure/ropes;pure/unidecode/unidecode;pure/xmldom;pure/xmldomparser" srcdoc2: "pure/xmlparser;pure/htmlparser;pure/xmltree;pure/colors;pure/mimetypes" -srcdoc2: "pure/json;pure/base64;pure/scgi;pure/redis;impure/graphics" -srcdoc2: "impure/rdstdin;impure/dialogs" +srcdoc2: "pure/json;pure/base64;pure/scgi" srcdoc2: "pure/collections/tables;pure/collections/sets;pure/collections/lists" srcdoc2: "pure/collections/intsets;pure/collections/queues;pure/encodings" srcdoc2: "pure/events;pure/collections/sequtils;pure/cookies" @@ -68,17 +67,13 @@ srcdoc2: "pure/basic2d;pure/basic3d" ; Note: everything under 'webdoc' doesn't get listed in the index, so wrappers ; should live here -webdoc: "wrappers/mysql;wrappers/iup;wrappers/sphinx" +webdoc: "wrappers/mysql;wrappers/iup" webdoc: "wrappers/sqlite3;wrappers/postgres;wrappers/tinyc;wrappers/odbcsql" -webdoc: "wrappers/expat;wrappers/pcre" -webdoc: "wrappers/tre;wrappers/openssl" +webdoc: "wrappers/pcre" +webdoc: "wrappers/openssl" webdoc: "wrappers/libuv;wrappers/joyent_http_parser" webdoc: "posix/posix;wrappers/odbcsql" -webdoc: "wrappers/zip/zlib;wrappers/zip/libzip" webdoc: "wrappers/libsvm.nim" -webdoc: "windows" -webdoc: "wrappers/readline/readline;wrappers/readline/history" -webdoc: "wrappers/readline/rltypedefs" From aa8b470cf6101b1394711866b0ee4c4ad8363104 Mon Sep 17 00:00:00 2001 From: Araq Date: Sun, 21 Jun 2015 10:04:26 +0200 Subject: [PATCH 0525/1263] use linenoise instead of GNU readline --- compiler/commands.nim | 2 +- compiler/llstream.nim | 95 +- config/nim.cfg | 2 +- koch.nim | 4 +- lib/impure/rdstdin.nim | 24 +- lib/wrappers/linenoise/LICENSE.txt | 25 + lib/wrappers/linenoise/README.markdown | 52 ++ lib/wrappers/linenoise/linenoise.c | 1107 ++++++++++++++++++++++++ lib/wrappers/linenoise/linenoise.h | 68 ++ lib/wrappers/linenoise/linenoise.nim | 38 + 10 files changed, 1351 insertions(+), 66 deletions(-) create mode 100644 lib/wrappers/linenoise/LICENSE.txt create mode 100644 lib/wrappers/linenoise/README.markdown create mode 100644 lib/wrappers/linenoise/linenoise.c create mode 100644 lib/wrappers/linenoise/linenoise.h create mode 100644 lib/wrappers/linenoise/linenoise.nim diff --git a/compiler/commands.nim b/compiler/commands.nim index 7c8abd9b8..922cda3c6 100644 --- a/compiler/commands.nim +++ b/compiler/commands.nim @@ -17,7 +17,7 @@ template bootSwitch(name, expr, userString: expr): expr = const name = if expr: " " & userString else: "" bootSwitch(usedRelease, defined(release), "-d:release") -bootSwitch(usedGnuReadline, defined(useGnuReadline), "-d:useGnuReadline") +bootSwitch(usedGnuReadline, defined(useLinenoise), "-d:useLinenoise") bootSwitch(usedNoCaas, defined(noCaas), "-d:noCaas") bootSwitch(usedBoehm, defined(boehmgc), "--gc:boehm") bootSwitch(usedMarkAndSweep, defined(gcmarkandsweep), "--gc:markAndSweep") diff --git a/compiler/llstream.nim b/compiler/llstream.nim index 18ca4aec7..0a1e09fc8 100644 --- a/compiler/llstream.nim +++ b/compiler/llstream.nim @@ -9,13 +9,14 @@ ## Low-level streams for high performance. -import +import strutils -when not defined(windows) and defined(useGnuReadline): +# support '-d:useGnuReadline' for backwards compatibility: +when not defined(windows) and (defined(useGnuReadline) or defined(useLinenoise)): import rdstdin -type +type TLLStreamKind* = enum # enum of different stream implementations llsNone, # null stream: reading and writing has no effect llsString, # stream encapsulates a string @@ -27,42 +28,42 @@ type s*: string rd*, wr*: int # for string streams lineOffset*: int # for fake stdin line numbers - + PLLStream* = ref TLLStream -proc llStreamOpen*(data: string): PLLStream = +proc llStreamOpen*(data: string): PLLStream = new(result) result.s = data result.kind = llsString -proc llStreamOpen*(f: File): PLLStream = +proc llStreamOpen*(f: File): PLLStream = new(result) result.f = f result.kind = llsFile -proc llStreamOpen*(filename: string, mode: FileMode): PLLStream = +proc llStreamOpen*(filename: string, mode: FileMode): PLLStream = new(result) result.kind = llsFile if not open(result.f, filename, mode): result = nil - -proc llStreamOpen*(): PLLStream = + +proc llStreamOpen*(): PLLStream = new(result) result.kind = llsNone -proc llStreamOpenStdIn*(): PLLStream = +proc llStreamOpenStdIn*(): PLLStream = new(result) result.kind = llsStdIn result.s = "" result.lineOffset = -1 -proc llStreamClose*(s: PLLStream) = +proc llStreamClose*(s: PLLStream) = case s.kind - of llsNone, llsString, llsStdIn: + of llsNone, llsString, llsStdIn: discard - of llsFile: + of llsFile: close(s.f) -when not declared(readLineFromStdin): +when not declared(readLineFromStdin): # fallback implementation: proc readLineFromStdin(prompt: string, line: var string): bool = stdout.write(prompt) @@ -77,7 +78,7 @@ proc endsWith*(x: string, s: set[char]): bool = if i >= 0 and x[i] in s: result = true -const +const LineContinuationOprs = {'+', '-', '*', '/', '\\', '<', '>', '!', '?', '^', '|', '%', '&', '$', '@', '~', ','} AdditionalLineContinuationOprs = {'#', ':', '='} @@ -104,31 +105,31 @@ proc llReadFromStdin(s: PLLStream, buf: pointer, bufLen: int): int = s.rd = 0 var line = newStringOfCap(120) var triples = 0 - while readLineFromStdin(if s.s.len == 0: ">>> " else: "... ", line): + while readLineFromStdin(if s.s.len == 0: ">>> " else: "... ", line): add(s.s, line) add(s.s, "\n") inc triples, countTriples(line) if not continueLine(line, (triples and 1) == 1): break inc(s.lineOffset) result = min(bufLen, len(s.s) - s.rd) - if result > 0: + if result > 0: copyMem(buf, addr(s.s[s.rd]), result) inc(s.rd, result) -proc llStreamRead*(s: PLLStream, buf: pointer, bufLen: int): int = +proc llStreamRead*(s: PLLStream, buf: pointer, bufLen: int): int = case s.kind - of llsNone: + of llsNone: result = 0 - of llsString: + of llsString: result = min(bufLen, len(s.s) - s.rd) - if result > 0: + if result > 0: copyMem(buf, addr(s.s[0 + s.rd]), result) inc(s.rd, result) - of llsFile: + of llsFile: result = readBuffer(s.f, buf, bufLen) - of llsStdIn: + of llsStdIn: result = llReadFromStdin(s, buf, bufLen) - + proc llStreamReadLine*(s: PLLStream, line: var string): bool = setLen(line, 0) case s.kind @@ -152,60 +153,60 @@ proc llStreamReadLine*(s: PLLStream, line: var string): bool = result = readLine(s.f, line) of llsStdIn: result = readLine(stdin, line) - -proc llStreamWrite*(s: PLLStream, data: string) = + +proc llStreamWrite*(s: PLLStream, data: string) = case s.kind - of llsNone, llsStdIn: + of llsNone, llsStdIn: discard - of llsString: + of llsString: add(s.s, data) inc(s.wr, len(data)) - of llsFile: + of llsFile: write(s.f, data) - -proc llStreamWriteln*(s: PLLStream, data: string) = + +proc llStreamWriteln*(s: PLLStream, data: string) = llStreamWrite(s, data) llStreamWrite(s, "\n") -proc llStreamWrite*(s: PLLStream, data: char) = +proc llStreamWrite*(s: PLLStream, data: char) = var c: char case s.kind - of llsNone, llsStdIn: + of llsNone, llsStdIn: discard - of llsString: + of llsString: add(s.s, data) inc(s.wr) - of llsFile: + of llsFile: c = data discard writeBuffer(s.f, addr(c), sizeof(c)) -proc llStreamWrite*(s: PLLStream, buf: pointer, buflen: int) = +proc llStreamWrite*(s: PLLStream, buf: pointer, buflen: int) = case s.kind - of llsNone, llsStdIn: + of llsNone, llsStdIn: discard - of llsString: - if buflen > 0: + of llsString: + if buflen > 0: setLen(s.s, len(s.s) + buflen) copyMem(addr(s.s[0 + s.wr]), buf, buflen) inc(s.wr, buflen) - of llsFile: + of llsFile: discard writeBuffer(s.f, buf, buflen) - -proc llStreamReadAll*(s: PLLStream): string = - const + +proc llStreamReadAll*(s: PLLStream): string = + const bufSize = 2048 case s.kind - of llsNone, llsStdIn: + of llsNone, llsStdIn: result = "" - of llsString: + of llsString: if s.rd == 0: result = s.s else: result = substr(s.s, s.rd) s.rd = len(s.s) - of llsFile: + of llsFile: result = newString(bufSize) var bytes = readBuffer(s.f, addr(result[0]), bufSize) var i = bytes - while bytes == bufSize: + while bytes == bufSize: setLen(result, i + bufSize) bytes = readBuffer(s.f, addr(result[i + 0]), bufSize) inc(i, bytes) diff --git a/config/nim.cfg b/config/nim.cfg index 0c3ffef4e..09864e0e5 100644 --- a/config/nim.cfg +++ b/config/nim.cfg @@ -39,7 +39,7 @@ path="$lib/wrappers" # path="$lib/wrappers/lua" # path="$lib/wrappers/opengl" path="$lib/wrappers/pcre" -path="$lib/wrappers/readline" +path="$lib/wrappers/linenoise" path="$lib/wrappers/sdl" # path="$lib/wrappers/x11" path="$lib/wrappers/zip" diff --git a/koch.nim b/koch.nim index 83f363b1a..8992271bf 100644 --- a/koch.nim +++ b/koch.nim @@ -57,7 +57,7 @@ Possible Commands: Boot options: -d:release produce a release version of the compiler -d:tinyc include the Tiny C backend (not supported on Windows) - -d:useGnuReadline use the GNU readline library for interactive mode + -d:useLinenoise use the linenoise library for interactive mode (not needed on Windows) -d:nativeStacktrace use native stack traces (only for Mac OS X or Linux) -d:noCaas build Nim without CAAS support @@ -333,7 +333,7 @@ proc tests(args: string) = # we compile the tester with taintMode:on to have a basic # taint mode test :-) exec "nim cc --taintMode:on tests/testament/tester" - # Since tests take a long time (on my machine), and we want to defy Murhpys + # Since tests take a long time (on my machine), and we want to defy Murhpys # law - lets make sure the compiler really is freshly compiled! exec "nim c --lib:lib -d:release --opt:speed compiler/nim.nim" let tester = quoteShell(getCurrentDir() / "tests/testament/tester".exe) diff --git a/lib/impure/rdstdin.nim b/lib/impure/rdstdin.nim index dfe3e22eb..14aefb315 100644 --- a/lib/impure/rdstdin.nim +++ b/lib/impure/rdstdin.nim @@ -7,8 +7,8 @@ # distribution, for details about the copyright. # -## This module contains code for reading from `stdin`:idx:. On UNIX the GNU -## readline library is wrapped and set up to provide default key bindings +## This module contains code for reading from `stdin`:idx:. On UNIX the +## linenoise library is wrapped and set up to provide default key bindings ## (e.g. you can navigate with the arrow keys). On Windows ``system.readLine`` ## is used. This suffices because Windows' console already provides the ## wanted functionality. @@ -100,34 +100,28 @@ when defined(Windows): stdout.write "\n" else: - import readline, history, termios, unsigned + import linenoise, termios, unsigned proc readLineFromStdin*(prompt: string): TaintedString {. tags: [ReadIOEffect, WriteIOEffect].} = - var buffer = readline.readLine(prompt) + var buffer = linenoise.readLine(prompt) if isNil(buffer): quit(0) result = TaintedString($buffer) if result.string.len > 0: - add_history(buffer) - readline.free(buffer) + historyAdd(buffer) + linenoise.free(buffer) proc readLineFromStdin*(prompt: string, line: var TaintedString): bool {. tags: [ReadIOEffect, WriteIOEffect].} = - var buffer = readline.readLine(prompt) + var buffer = linenoise.readLine(prompt) if isNil(buffer): quit(0) line = TaintedString($buffer) if line.string.len > 0: - add_history(buffer) - readline.free(buffer) + historyAdd(buffer) + linenoise.free(buffer) # XXX how to determine CTRL+D? result = true - # initialization: - # disable auto-complete: - proc doNothing(a, b: cint): cint {.cdecl, procvar.} = discard - - discard readline.bind_key('\t'.ord, doNothing) - proc readPasswordFromStdin*(prompt: string, password: var TaintedString): bool {.tags: [ReadIOEffect, WriteIOEffect].} = password.setLen(0) diff --git a/lib/wrappers/linenoise/LICENSE.txt b/lib/wrappers/linenoise/LICENSE.txt new file mode 100644 index 000000000..18e814865 --- /dev/null +++ b/lib/wrappers/linenoise/LICENSE.txt @@ -0,0 +1,25 @@ +Copyright (c) 2010-2014, Salvatore Sanfilippo +Copyright (c) 2010-2013, Pieter Noordhuis + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/lib/wrappers/linenoise/README.markdown b/lib/wrappers/linenoise/README.markdown new file mode 100644 index 000000000..c845673cd --- /dev/null +++ b/lib/wrappers/linenoise/README.markdown @@ -0,0 +1,52 @@ +# Linenoise + +A minimal, zero-config, BSD licensed, readline replacement used in Redis, +MongoDB, and Android. + +* Single and multi line editing mode with the usual key bindings implemented. +* History handling. +* Completion. +* About 1,100 lines of BSD license source code. +* Only uses a subset of VT100 escapes (ANSI.SYS compatible). + +## Can a line editing library be 20k lines of code? + +Line editing with some support for history is a really important feature for command line utilities. Instead of retyping almost the same stuff again and again it's just much better to hit the up arrow and edit on syntax errors, or in order to try a slightly different command. But apparently code dealing with terminals is some sort of Black Magic: readline is 30k lines of code, libedit 20k. Is it reasonable to link small utilities to huge libraries just to get a minimal support for line editing? + +So what usually happens is either: + + * Large programs with configure scripts disabling line editing if readline is not present in the system, or not supporting it at all since readline is GPL licensed and libedit (the BSD clone) is not as known and available as readline is (Real world example of this problem: Tclsh). + * Smaller programs not using a configure script not supporting line editing at all (A problem we had with Redis-cli for instance). + +The result is a pollution of binaries without line editing support. + +So I spent more or less two hours doing a reality check resulting in this little library: is it *really* needed for a line editing library to be 20k lines of code? Apparently not, it is possibe to get a very small, zero configuration, trivial to embed library, that solves the problem. Smaller programs will just include this, supporing line editing out of the box. Larger programs may use this little library or just checking with configure if readline/libedit is available and resorting to linenoise if not. + +## Terminals, in 2010. + +Apparently almost every terminal you can happen to use today has some kind of support for basic VT100 escape sequences. So I tried to write a lib using just very basic VT100 features. The resulting library appears to work everywhere I tried to use it, and now can work even on ANSI.SYS compatible terminals, since no +VT220 specific sequences are used anymore. + +The library is currently about 1100 lines of code. In order to use it in your project just look at the *example.c* file in the source distribution, it is trivial. Linenoise is BSD code, so you can use both in free software and commercial software. + +## Tested with... + + * Linux text only console ($TERM = linux) + * Linux KDE terminal application ($TERM = xterm) + * Linux xterm ($TERM = xterm) + * Linux Buildroot ($TERM = vt100) + * Mac OS X iTerm ($TERM = xterm) + * Mac OS X default Terminal.app ($TERM = xterm) + * OpenBSD 4.5 through an OSX Terminal.app ($TERM = screen) + * IBM AIX 6.1 + * FreeBSD xterm ($TERM = xterm) + * ANSI.SYS + +Please test it everywhere you can and report back! + +## Let's push this forward! + +Patches should be provided in the respect of linenoise sensibility for small +easy to understand code. + +Send feedbacks to antirez at gmail diff --git a/lib/wrappers/linenoise/linenoise.c b/lib/wrappers/linenoise/linenoise.c new file mode 100644 index 000000000..c10557d0e --- /dev/null +++ b/lib/wrappers/linenoise/linenoise.c @@ -0,0 +1,1107 @@ +/* linenoise.c -- VERSION 1.0 + * + * Guerrilla line editing library against the idea that a line editing lib + * needs to be 20,000 lines of C code. + * + * You can find the latest source code at: + * + * http://github.com/antirez/linenoise + * + * Does a number of crazy assumptions that happen to be true in 99.9999% of + * the 2010 UNIX computers around. + * + * ------------------------------------------------------------------------ + * + * Copyright (c) 2010-2014, Salvatore Sanfilippo + * Copyright (c) 2010-2013, Pieter Noordhuis + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * ------------------------------------------------------------------------ + * + * References: + * - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html + * - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html + * + * Todo list: + * - Filter bogus Ctrl+ combinations. + * - Win32 support + * + * Bloat: + * - History search like Ctrl+r in readline? + * + * List of escape sequences used by this program, we do everything just + * with three sequences. In order to be so cheap we may have some + * flickering effect with some slow terminal, but the lesser sequences + * the more compatible. + * + * EL (Erase Line) + * Sequence: ESC [ n K + * Effect: if n is 0 or missing, clear from cursor to end of line + * Effect: if n is 1, clear from beginning of line to cursor + * Effect: if n is 2, clear entire line + * + * CUF (CUrsor Forward) + * Sequence: ESC [ n C + * Effect: moves cursor forward n chars + * + * CUB (CUrsor Backward) + * Sequence: ESC [ n D + * Effect: moves cursor backward n chars + * + * The following is used to get the terminal width if getting + * the width with the TIOCGWINSZ ioctl fails + * + * DSR (Device Status Report) + * Sequence: ESC [ 6 n + * Effect: reports the current cusor position as ESC [ n ; m R + * where n is the row and m is the column + * + * When multi line mode is enabled, we also use an additional escape + * sequence. However multi line editing is disabled by default. + * + * CUU (Cursor Up) + * Sequence: ESC [ n A + * Effect: moves cursor up of n chars. + * + * CUD (Cursor Down) + * Sequence: ESC [ n B + * Effect: moves cursor down of n chars. + * + * When linenoiseClearScreen() is called, two additional escape sequences + * are used in order to clear the screen and position the cursor at home + * position. + * + * CUP (Cursor position) + * Sequence: ESC [ H + * Effect: moves the cursor to upper left corner + * + * ED (Erase display) + * Sequence: ESC [ 2 J + * Effect: clear the whole screen + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "linenoise.h" + +#define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100 +#define LINENOISE_MAX_LINE 4096 +static char *unsupported_term[] = {"dumb","cons25","emacs",NULL}; +static linenoiseCompletionCallback *completionCallback = NULL; + +static struct termios orig_termios; /* In order to restore at exit.*/ +static int rawmode = 0; /* For atexit() function to check if restore is needed*/ +static int mlmode = 0; /* Multi line mode. Default is single line. */ +static int atexit_registered = 0; /* Register atexit just 1 time. */ +static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN; +static int history_len = 0; +static char **history = NULL; + +/* The linenoiseState structure represents the state during line editing. + * We pass this state to functions implementing specific editing + * functionalities. */ +struct linenoiseState { + int ifd; /* Terminal stdin file descriptor. */ + int ofd; /* Terminal stdout file descriptor. */ + char *buf; /* Edited line buffer. */ + size_t buflen; /* Edited line buffer size. */ + const char *prompt; /* Prompt to display. */ + size_t plen; /* Prompt length. */ + size_t pos; /* Current cursor position. */ + size_t oldpos; /* Previous refresh cursor position. */ + size_t len; /* Current edited line length. */ + size_t cols; /* Number of columns in terminal. */ + size_t maxrows; /* Maximum num of rows used so far (multiline mode) */ + int history_index; /* The history index we are currently editing. */ +}; + +enum KEY_ACTION{ + KEY_NULL = 0, /* NULL */ + CTRL_A = 1, /* Ctrl+a */ + CTRL_B = 2, /* Ctrl-b */ + CTRL_C = 3, /* Ctrl-c */ + CTRL_D = 4, /* Ctrl-d */ + CTRL_E = 5, /* Ctrl-e */ + CTRL_F = 6, /* Ctrl-f */ + CTRL_H = 8, /* Ctrl-h */ + TAB = 9, /* Tab */ + CTRL_K = 11, /* Ctrl+k */ + CTRL_L = 12, /* Ctrl+l */ + ENTER = 13, /* Enter */ + CTRL_N = 14, /* Ctrl-n */ + CTRL_P = 16, /* Ctrl-p */ + CTRL_T = 20, /* Ctrl-t */ + CTRL_U = 21, /* Ctrl+u */ + CTRL_W = 23, /* Ctrl+w */ + ESC = 27, /* Escape */ + BACKSPACE = 127 /* Backspace */ +}; + +static void linenoiseAtExit(void); +int linenoiseHistoryAdd(const char *line); +static void refreshLine(struct linenoiseState *l); + +/* Debugging macro. */ +#if 0 +FILE *lndebug_fp = NULL; +#define lndebug(...) \ + do { \ + if (lndebug_fp == NULL) { \ + lndebug_fp = fopen("/tmp/lndebug.txt","a"); \ + fprintf(lndebug_fp, \ + "[%d %d %d] p: %d, rows: %d, rpos: %d, max: %d, oldmax: %d\n", \ + (int)l->len,(int)l->pos,(int)l->oldpos,plen,rows,rpos, \ + (int)l->maxrows,old_rows); \ + } \ + fprintf(lndebug_fp, ", " __VA_ARGS__); \ + fflush(lndebug_fp); \ + } while (0) +#else +#define lndebug(fmt, ...) +#endif + +/* ======================= Low level terminal handling ====================== */ + +/* Set if to use or not the multi line mode. */ +void linenoiseSetMultiLine(int ml) { + mlmode = ml; +} + +/* Return true if the terminal name is in the list of terminals we know are + * not able to understand basic escape sequences. */ +static int isUnsupportedTerm(void) { + char *term = getenv("TERM"); + int j; + + if (term == NULL) return 0; + for (j = 0; unsupported_term[j]; j++) + if (!strcasecmp(term,unsupported_term[j])) return 1; + return 0; +} + +/* Raw mode: 1960 magic shit. */ +static int enableRawMode(int fd) { + struct termios raw; + + if (!isatty(STDIN_FILENO)) goto fatal; + if (!atexit_registered) { + atexit(linenoiseAtExit); + atexit_registered = 1; + } + if (tcgetattr(fd,&orig_termios) == -1) goto fatal; + + raw = orig_termios; /* modify the original mode */ + /* input modes: no break, no CR to NL, no parity check, no strip char, + * no start/stop output control. */ + raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON); + /* output modes - disable post processing */ + raw.c_oflag &= ~(OPOST); + /* control modes - set 8 bit chars */ + raw.c_cflag |= (CS8); + /* local modes - choing off, canonical off, no extended functions, + * no signal chars (^Z,^C) */ + raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG); + /* control chars - set return condition: min number of bytes and timer. + * We want read to return every single byte, without timeout. */ + raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */ + + /* put terminal in raw mode after flushing */ + if (tcsetattr(fd,TCSAFLUSH,&raw) < 0) goto fatal; + rawmode = 1; + return 0; + +fatal: + errno = ENOTTY; + return -1; +} + +static void disableRawMode(int fd) { + /* Don't even check the return value as it's too late. */ + if (rawmode && tcsetattr(fd,TCSAFLUSH,&orig_termios) != -1) + rawmode = 0; +} + +/* Use the ESC [6n escape sequence to query the horizontal cursor position + * and return it. On error -1 is returned, on success the position of the + * cursor. */ +static int getCursorPosition(int ifd, int ofd) { + char buf[32]; + int cols, rows; + unsigned int i = 0; + + /* Report cursor location */ + if (write(ofd, "\x1b[6n", 4) != 4) return -1; + + /* Read the response: ESC [ rows ; cols R */ + while (i < sizeof(buf)-1) { + if (read(ifd,buf+i,1) != 1) break; + if (buf[i] == 'R') break; + i++; + } + buf[i] = '\0'; + + /* Parse it. */ + if (buf[0] != ESC || buf[1] != '[') return -1; + if (sscanf(buf+2,"%d;%d",&rows,&cols) != 2) return -1; + return cols; +} + +/* Try to get the number of columns in the current terminal, or assume 80 + * if it fails. */ +static int getColumns(int ifd, int ofd) { + struct winsize ws; + + if (ioctl(1, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0) { + /* ioctl() failed. Try to query the terminal itself. */ + int start, cols; + + /* Get the initial position so we can restore it later. */ + start = getCursorPosition(ifd,ofd); + if (start == -1) goto failed; + + /* Go to right margin and get position. */ + if (write(ofd,"\x1b[999C",6) != 6) goto failed; + cols = getCursorPosition(ifd,ofd); + if (cols == -1) goto failed; + + /* Restore position. */ + if (cols > start) { + char seq[32]; + snprintf(seq,32,"\x1b[%dD",cols-start); + if (write(ofd,seq,strlen(seq)) == -1) { + /* Can't recover... */ + } + } + return cols; + } else { + return ws.ws_col; + } + +failed: + return 80; +} + +/* Clear the screen. Used to handle ctrl+l */ +void linenoiseClearScreen(void) { + if (write(STDOUT_FILENO,"\x1b[H\x1b[2J",7) <= 0) { + /* nothing to do, just to avoid warning. */ + } +} + +/* Beep, used for completion when there is nothing to complete or when all + * the choices were already shown. */ +static void linenoiseBeep(void) { + fprintf(stderr, "\x7"); + fflush(stderr); +} + +/* ============================== Completion ================================ */ + +/* Free a list of completion option populated by linenoiseAddCompletion(). */ +static void freeCompletions(linenoiseCompletions *lc) { + size_t i; + for (i = 0; i < lc->len; i++) + free(lc->cvec[i]); + if (lc->cvec != NULL) + free(lc->cvec); +} + +/* This is an helper function for linenoiseEdit() and is called when the + * user types the key in order to complete the string currently in the + * input. + * + * The state of the editing is encapsulated into the pointed linenoiseState + * structure as described in the structure definition. */ +static int completeLine(struct linenoiseState *ls) { + linenoiseCompletions lc = { 0, NULL }; + int nread, nwritten; + char c = 0; + + completionCallback(ls->buf,&lc); + if (lc.len == 0) { + linenoiseBeep(); + } else { + size_t stop = 0, i = 0; + + while(!stop) { + /* Show completion or original buffer */ + if (i < lc.len) { + struct linenoiseState saved = *ls; + + ls->len = ls->pos = strlen(lc.cvec[i]); + ls->buf = lc.cvec[i]; + refreshLine(ls); + ls->len = saved.len; + ls->pos = saved.pos; + ls->buf = saved.buf; + } else { + refreshLine(ls); + } + + nread = read(ls->ifd,&c,1); + if (nread <= 0) { + freeCompletions(&lc); + return -1; + } + + switch(c) { + case 9: /* tab */ + i = (i+1) % (lc.len+1); + if (i == lc.len) linenoiseBeep(); + break; + case 27: /* escape */ + /* Re-show original buffer */ + if (i < lc.len) refreshLine(ls); + stop = 1; + break; + default: + /* Update buffer and return */ + if (i < lc.len) { + nwritten = snprintf(ls->buf,ls->buflen,"%s",lc.cvec[i]); + ls->len = ls->pos = nwritten; + } + stop = 1; + break; + } + } + } + + freeCompletions(&lc); + return c; /* Return last read character */ +} + +/* Register a callback function to be called for tab-completion. */ +void linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn) { + completionCallback = fn; +} + +/* This function is used by the callback function registered by the user + * in order to add completion options given the input string when the + * user typed . See the example.c source code for a very easy to + * understand example. */ +void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) { + size_t len = strlen(str); + char *copy, **cvec; + + copy = malloc(len+1); + if (copy == NULL) return; + memcpy(copy,str,len+1); + cvec = realloc(lc->cvec,sizeof(char*)*(lc->len+1)); + if (cvec == NULL) { + free(copy); + return; + } + lc->cvec = cvec; + lc->cvec[lc->len++] = copy; +} + +/* =========================== Line editing ================================= */ + +/* We define a very simple "append buffer" structure, that is an heap + * allocated string where we can append to. This is useful in order to + * write all the escape sequences in a buffer and flush them to the standard + * output in a single call, to avoid flickering effects. */ +struct abuf { + char *b; + int len; +}; + +static void abInit(struct abuf *ab) { + ab->b = NULL; + ab->len = 0; +} + +static void abAppend(struct abuf *ab, const char *s, int len) { + char *new = realloc(ab->b,ab->len+len); + + if (new == NULL) return; + memcpy(new+ab->len,s,len); + ab->b = new; + ab->len += len; +} + +static void abFree(struct abuf *ab) { + free(ab->b); +} + +/* Single line low level line refresh. + * + * Rewrite the currently edited line accordingly to the buffer content, + * cursor position, and number of columns of the terminal. */ +static void refreshSingleLine(struct linenoiseState *l) { + char seq[64]; + size_t plen = strlen(l->prompt); + int fd = l->ofd; + char *buf = l->buf; + size_t len = l->len; + size_t pos = l->pos; + struct abuf ab; + + while((plen+pos) >= l->cols) { + buf++; + len--; + pos--; + } + while (plen+len > l->cols) { + len--; + } + + abInit(&ab); + /* Cursor to left edge */ + snprintf(seq,64,"\r"); + abAppend(&ab,seq,strlen(seq)); + /* Write the prompt and the current buffer content */ + abAppend(&ab,l->prompt,strlen(l->prompt)); + abAppend(&ab,buf,len); + /* Erase to right */ + snprintf(seq,64,"\x1b[0K"); + abAppend(&ab,seq,strlen(seq)); + /* Move cursor to original position. */ + snprintf(seq,64,"\r\x1b[%dC", (int)(pos+plen)); + abAppend(&ab,seq,strlen(seq)); + if (write(fd,ab.b,ab.len) == -1) {} /* Can't recover from write error. */ + abFree(&ab); +} + +/* Multi line low level line refresh. + * + * Rewrite the currently edited line accordingly to the buffer content, + * cursor position, and number of columns of the terminal. */ +static void refreshMultiLine(struct linenoiseState *l) { + char seq[64]; + int plen = strlen(l->prompt); + int rows = (plen+l->len+l->cols-1)/l->cols; /* rows used by current buf. */ + int rpos = (plen+l->oldpos+l->cols)/l->cols; /* cursor relative row. */ + int rpos2; /* rpos after refresh. */ + int col; /* colum position, zero-based. */ + int old_rows = l->maxrows; + int fd = l->ofd, j; + struct abuf ab; + + /* Update maxrows if needed. */ + if (rows > (int)l->maxrows) l->maxrows = rows; + + /* First step: clear all the lines used before. To do so start by + * going to the last row. */ + abInit(&ab); + if (old_rows-rpos > 0) { + lndebug("go down %d", old_rows-rpos); + snprintf(seq,64,"\x1b[%dB", old_rows-rpos); + abAppend(&ab,seq,strlen(seq)); + } + + /* Now for every row clear it, go up. */ + for (j = 0; j < old_rows-1; j++) { + lndebug("clear+up"); + snprintf(seq,64,"\r\x1b[0K\x1b[1A"); + abAppend(&ab,seq,strlen(seq)); + } + + /* Clean the top line. */ + lndebug("clear"); + snprintf(seq,64,"\r\x1b[0K"); + abAppend(&ab,seq,strlen(seq)); + + /* Write the prompt and the current buffer content */ + abAppend(&ab,l->prompt,strlen(l->prompt)); + abAppend(&ab,l->buf,l->len); + + /* If we are at the very end of the screen with our prompt, we need to + * emit a newline and move the prompt to the first column. */ + if (l->pos && + l->pos == l->len && + (l->pos+plen) % l->cols == 0) + { + lndebug(""); + abAppend(&ab,"\n",1); + snprintf(seq,64,"\r"); + abAppend(&ab,seq,strlen(seq)); + rows++; + if (rows > (int)l->maxrows) l->maxrows = rows; + } + + /* Move cursor to right position. */ + rpos2 = (plen+l->pos+l->cols)/l->cols; /* current cursor relative row. */ + lndebug("rpos2 %d", rpos2); + + /* Go up till we reach the expected positon. */ + if (rows-rpos2 > 0) { + lndebug("go-up %d", rows-rpos2); + snprintf(seq,64,"\x1b[%dA", rows-rpos2); + abAppend(&ab,seq,strlen(seq)); + } + + /* Set column. */ + col = (plen+(int)l->pos) % (int)l->cols; + lndebug("set col %d", 1+col); + if (col) + snprintf(seq,64,"\r\x1b[%dC", col); + else + snprintf(seq,64,"\r"); + abAppend(&ab,seq,strlen(seq)); + + lndebug("\n"); + l->oldpos = l->pos; + + if (write(fd,ab.b,ab.len) == -1) {} /* Can't recover from write error. */ + abFree(&ab); +} + +/* Calls the two low level functions refreshSingleLine() or + * refreshMultiLine() according to the selected mode. */ +static void refreshLine(struct linenoiseState *l) { + if (mlmode) + refreshMultiLine(l); + else + refreshSingleLine(l); +} + +/* Insert the character 'c' at cursor current position. + * + * On error writing to the terminal -1 is returned, otherwise 0. */ +int linenoiseEditInsert(struct linenoiseState *l, char c) { + if (l->len < l->buflen) { + if (l->len == l->pos) { + l->buf[l->pos] = c; + l->pos++; + l->len++; + l->buf[l->len] = '\0'; + if ((!mlmode && l->plen+l->len < l->cols) /* || mlmode */) { + /* Avoid a full update of the line in the + * trivial case. */ + if (write(l->ofd,&c,1) == -1) return -1; + } else { + refreshLine(l); + } + } else { + memmove(l->buf+l->pos+1,l->buf+l->pos,l->len-l->pos); + l->buf[l->pos] = c; + l->len++; + l->pos++; + l->buf[l->len] = '\0'; + refreshLine(l); + } + } + return 0; +} + +/* Move cursor on the left. */ +void linenoiseEditMoveLeft(struct linenoiseState *l) { + if (l->pos > 0) { + l->pos--; + refreshLine(l); + } +} + +/* Move cursor on the right. */ +void linenoiseEditMoveRight(struct linenoiseState *l) { + if (l->pos != l->len) { + l->pos++; + refreshLine(l); + } +} + +/* Move cursor to the start of the line. */ +void linenoiseEditMoveHome(struct linenoiseState *l) { + if (l->pos != 0) { + l->pos = 0; + refreshLine(l); + } +} + +/* Move cursor to the end of the line. */ +void linenoiseEditMoveEnd(struct linenoiseState *l) { + if (l->pos != l->len) { + l->pos = l->len; + refreshLine(l); + } +} + +/* Substitute the currently edited line with the next or previous history + * entry as specified by 'dir'. */ +#define LINENOISE_HISTORY_NEXT 0 +#define LINENOISE_HISTORY_PREV 1 +void linenoiseEditHistoryNext(struct linenoiseState *l, int dir) { + if (history_len > 1) { + /* Update the current history entry before to + * overwrite it with the next one. */ + free(history[history_len - 1 - l->history_index]); + history[history_len - 1 - l->history_index] = strdup(l->buf); + /* Show the new entry */ + l->history_index += (dir == LINENOISE_HISTORY_PREV) ? 1 : -1; + if (l->history_index < 0) { + l->history_index = 0; + return; + } else if (l->history_index >= history_len) { + l->history_index = history_len-1; + return; + } + strncpy(l->buf,history[history_len - 1 - l->history_index],l->buflen); + l->buf[l->buflen-1] = '\0'; + l->len = l->pos = strlen(l->buf); + refreshLine(l); + } +} + +/* Delete the character at the right of the cursor without altering the cursor + * position. Basically this is what happens with the "Delete" keyboard key. */ +void linenoiseEditDelete(struct linenoiseState *l) { + if (l->len > 0 && l->pos < l->len) { + memmove(l->buf+l->pos,l->buf+l->pos+1,l->len-l->pos-1); + l->len--; + l->buf[l->len] = '\0'; + refreshLine(l); + } +} + +/* Backspace implementation. */ +void linenoiseEditBackspace(struct linenoiseState *l) { + if (l->pos > 0 && l->len > 0) { + memmove(l->buf+l->pos-1,l->buf+l->pos,l->len-l->pos); + l->pos--; + l->len--; + l->buf[l->len] = '\0'; + refreshLine(l); + } +} + +/* Delete the previosu word, maintaining the cursor at the start of the + * current word. */ +void linenoiseEditDeletePrevWord(struct linenoiseState *l) { + size_t old_pos = l->pos; + size_t diff; + + while (l->pos > 0 && l->buf[l->pos-1] == ' ') + l->pos--; + while (l->pos > 0 && l->buf[l->pos-1] != ' ') + l->pos--; + diff = old_pos - l->pos; + memmove(l->buf+l->pos,l->buf+old_pos,l->len-old_pos+1); + l->len -= diff; + refreshLine(l); +} + +/* This function is the core of the line editing capability of linenoise. + * It expects 'fd' to be already in "raw mode" so that every key pressed + * will be returned ASAP to read(). + * + * The resulting string is put into 'buf' when the user type enter, or + * when ctrl+d is typed. + * + * The function returns the length of the current buffer. */ +static int linenoiseEdit(int stdin_fd, int stdout_fd, char *buf, size_t buflen, const char *prompt) +{ + struct linenoiseState l; + + /* Populate the linenoise state that we pass to functions implementing + * specific editing functionalities. */ + l.ifd = stdin_fd; + l.ofd = stdout_fd; + l.buf = buf; + l.buflen = buflen; + l.prompt = prompt; + l.plen = strlen(prompt); + l.oldpos = l.pos = 0; + l.len = 0; + l.cols = getColumns(stdin_fd, stdout_fd); + l.maxrows = 0; + l.history_index = 0; + + /* Buffer starts empty. */ + l.buf[0] = '\0'; + l.buflen--; /* Make sure there is always space for the nulterm */ + + /* The latest history entry is always our current buffer, that + * initially is just an empty string. */ + linenoiseHistoryAdd(""); + + if (write(l.ofd,prompt,l.plen) == -1) return -1; + while(1) { + char c; + int nread; + char seq[3]; + + nread = read(l.ifd,&c,1); + if (nread <= 0) return l.len; + + /* Only autocomplete when the callback is set. It returns < 0 when + * there was an error reading from fd. Otherwise it will return the + * character that should be handled next. */ + if (c == 9 && completionCallback != NULL) { + c = completeLine(&l); + /* Return on errors */ + if (c < 0) return l.len; + /* Read next character when 0 */ + if (c == 0) continue; + } + + switch(c) { + case ENTER: /* enter */ + history_len--; + free(history[history_len]); + if (mlmode) linenoiseEditMoveEnd(&l); + return (int)l.len; + case CTRL_C: /* ctrl-c */ + errno = EAGAIN; + return -1; + case BACKSPACE: /* backspace */ + case 8: /* ctrl-h */ + linenoiseEditBackspace(&l); + break; + case CTRL_D: /* ctrl-d, remove char at right of cursor, or if the + line is empty, act as end-of-file. */ + if (l.len > 0) { + linenoiseEditDelete(&l); + } else { + history_len--; + free(history[history_len]); + return -1; + } + break; + case CTRL_T: /* ctrl-t, swaps current character with previous. */ + if (l.pos > 0 && l.pos < l.len) { + int aux = buf[l.pos-1]; + buf[l.pos-1] = buf[l.pos]; + buf[l.pos] = aux; + if (l.pos != l.len-1) l.pos++; + refreshLine(&l); + } + break; + case CTRL_B: /* ctrl-b */ + linenoiseEditMoveLeft(&l); + break; + case CTRL_F: /* ctrl-f */ + linenoiseEditMoveRight(&l); + break; + case CTRL_P: /* ctrl-p */ + linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_PREV); + break; + case CTRL_N: /* ctrl-n */ + linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_NEXT); + break; + case ESC: /* escape sequence */ + /* Read the next two bytes representing the escape sequence. + * Use two calls to handle slow terminals returning the two + * chars at different times. */ + if (read(l.ifd,seq,1) == -1) break; + if (read(l.ifd,seq+1,1) == -1) break; + + /* ESC [ sequences. */ + if (seq[0] == '[') { + if (seq[1] >= '0' && seq[1] <= '9') { + /* Extended escape, read additional byte. */ + if (read(l.ifd,seq+2,1) == -1) break; + if (seq[2] == '~') { + switch(seq[1]) { + case '3': /* Delete key. */ + linenoiseEditDelete(&l); + break; + } + } + } else { + switch(seq[1]) { + case 'A': /* Up */ + linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_PREV); + break; + case 'B': /* Down */ + linenoiseEditHistoryNext(&l, LINENOISE_HISTORY_NEXT); + break; + case 'C': /* Right */ + linenoiseEditMoveRight(&l); + break; + case 'D': /* Left */ + linenoiseEditMoveLeft(&l); + break; + case 'H': /* Home */ + linenoiseEditMoveHome(&l); + break; + case 'F': /* End*/ + linenoiseEditMoveEnd(&l); + break; + } + } + } + + /* ESC O sequences. */ + else if (seq[0] == 'O') { + switch(seq[1]) { + case 'H': /* Home */ + linenoiseEditMoveHome(&l); + break; + case 'F': /* End*/ + linenoiseEditMoveEnd(&l); + break; + } + } + break; + default: + if (linenoiseEditInsert(&l,c)) return -1; + break; + case CTRL_U: /* Ctrl+u, delete the whole line. */ + buf[0] = '\0'; + l.pos = l.len = 0; + refreshLine(&l); + break; + case CTRL_K: /* Ctrl+k, delete from current to end of line. */ + buf[l.pos] = '\0'; + l.len = l.pos; + refreshLine(&l); + break; + case CTRL_A: /* Ctrl+a, go to the start of the line */ + linenoiseEditMoveHome(&l); + break; + case CTRL_E: /* ctrl+e, go to the end of the line */ + linenoiseEditMoveEnd(&l); + break; + case CTRL_L: /* ctrl+l, clear screen */ + linenoiseClearScreen(); + refreshLine(&l); + break; + case CTRL_W: /* ctrl+w, delete previous word */ + linenoiseEditDeletePrevWord(&l); + break; + } + } + return l.len; +} + +/* This special mode is used by linenoise in order to print scan codes + * on screen for debugging / development purposes. It is implemented + * by the linenoise_example program using the --keycodes option. */ +void linenoisePrintKeyCodes(void) { + char quit[4]; + + printf("Linenoise key codes debugging mode.\n" + "Press keys to see scan codes. Type 'quit' at any time to exit.\n"); + if (enableRawMode(STDIN_FILENO) == -1) return; + memset(quit,' ',4); + while(1) { + char c; + int nread; + + nread = read(STDIN_FILENO,&c,1); + if (nread <= 0) continue; + memmove(quit,quit+1,sizeof(quit)-1); /* shift string to left. */ + quit[sizeof(quit)-1] = c; /* Insert current char on the right. */ + if (memcmp(quit,"quit",sizeof(quit)) == 0) break; + + printf("'%c' %02x (%d) (type quit to exit)\n", + isprint(c) ? c : '?', (int)c, (int)c); + printf("\r"); /* Go left edge manually, we are in raw mode. */ + fflush(stdout); + } + disableRawMode(STDIN_FILENO); +} + +/* This function calls the line editing function linenoiseEdit() using + * the STDIN file descriptor set in raw mode. */ +static int linenoiseRaw(char *buf, size_t buflen, const char *prompt) { + int count; + + if (buflen == 0) { + errno = EINVAL; + return -1; + } + if (!isatty(STDIN_FILENO)) { + /* Not a tty: read from file / pipe. */ + if (fgets(buf, buflen, stdin) == NULL) return -1; + count = strlen(buf); + if (count && buf[count-1] == '\n') { + count--; + buf[count] = '\0'; + } + } else { + /* Interactive editing. */ + if (enableRawMode(STDIN_FILENO) == -1) return -1; + count = linenoiseEdit(STDIN_FILENO, STDOUT_FILENO, buf, buflen, prompt); + disableRawMode(STDIN_FILENO); + printf("\n"); + } + return count; +} + +/* The high level function that is the main API of the linenoise library. + * This function checks if the terminal has basic capabilities, just checking + * for a blacklist of stupid terminals, and later either calls the line + * editing function or uses dummy fgets() so that you will be able to type + * something even in the most desperate of the conditions. */ +char *linenoise(const char *prompt) { + char buf[LINENOISE_MAX_LINE]; + int count; + + if (isUnsupportedTerm()) { + size_t len; + + printf("%s",prompt); + fflush(stdout); + if (fgets(buf,LINENOISE_MAX_LINE,stdin) == NULL) return NULL; + len = strlen(buf); + while(len && (buf[len-1] == '\n' || buf[len-1] == '\r')) { + len--; + buf[len] = '\0'; + } + return strdup(buf); + } else { + count = linenoiseRaw(buf,LINENOISE_MAX_LINE,prompt); + if (count == -1) return NULL; + return strdup(buf); + } +} + +/* ================================ History ================================= */ + +/* Free the history, but does not reset it. Only used when we have to + * exit() to avoid memory leaks are reported by valgrind & co. */ +static void freeHistory(void) { + if (history) { + int j; + + for (j = 0; j < history_len; j++) + free(history[j]); + free(history); + } +} + +/* At exit we'll try to fix the terminal to the initial conditions. */ +static void linenoiseAtExit(void) { + disableRawMode(STDIN_FILENO); + freeHistory(); +} + +/* This is the API call to add a new entry in the linenoise history. + * It uses a fixed array of char pointers that are shifted (memmoved) + * when the history max length is reached in order to remove the older + * entry and make room for the new one, so it is not exactly suitable for huge + * histories, but will work well for a few hundred of entries. + * + * Using a circular buffer is smarter, but a bit more complex to handle. */ +int linenoiseHistoryAdd(const char *line) { + char *linecopy; + + if (history_max_len == 0) return 0; + + /* Initialization on first call. */ + if (history == NULL) { + history = malloc(sizeof(char*)*history_max_len); + if (history == NULL) return 0; + memset(history,0,(sizeof(char*)*history_max_len)); + } + + /* Don't add duplicated lines. */ + if (history_len && !strcmp(history[history_len-1], line)) return 0; + + /* Add an heap allocated copy of the line in the history. + * If we reached the max length, remove the older line. */ + linecopy = strdup(line); + if (!linecopy) return 0; + if (history_len == history_max_len) { + free(history[0]); + memmove(history,history+1,sizeof(char*)*(history_max_len-1)); + history_len--; + } + history[history_len] = linecopy; + history_len++; + return 1; +} + +/* Set the maximum length for the history. This function can be called even + * if there is already some history, the function will make sure to retain + * just the latest 'len' elements if the new history length value is smaller + * than the amount of items already inside the history. */ +int linenoiseHistorySetMaxLen(int len) { + char **new; + + if (len < 1) return 0; + if (history) { + int tocopy = history_len; + + new = malloc(sizeof(char*)*len); + if (new == NULL) return 0; + + /* If we can't copy everything, free the elements we'll not use. */ + if (len < tocopy) { + int j; + + for (j = 0; j < tocopy-len; j++) free(history[j]); + tocopy = len; + } + memset(new,0,sizeof(char*)*len); + memcpy(new,history+(history_len-tocopy), sizeof(char*)*tocopy); + free(history); + history = new; + } + history_max_len = len; + if (history_len > history_max_len) + history_len = history_max_len; + return 1; +} + +/* Save the history in the specified file. On success 0 is returned + * otherwise -1 is returned. */ +int linenoiseHistorySave(const char *filename) { + FILE *fp = fopen(filename,"w"); + int j; + + if (fp == NULL) return -1; + for (j = 0; j < history_len; j++) + fprintf(fp,"%s\n",history[j]); + fclose(fp); + return 0; +} + +/* Load the history from the specified file. If the file does not exist + * zero is returned and no operation is performed. + * + * If the file exists and the operation succeeded 0 is returned, otherwise + * on error -1 is returned. */ +int linenoiseHistoryLoad(const char *filename) { + FILE *fp = fopen(filename,"r"); + char buf[LINENOISE_MAX_LINE]; + + if (fp == NULL) return -1; + + while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) { + char *p; + + p = strchr(buf,'\r'); + if (!p) p = strchr(buf,'\n'); + if (p) *p = '\0'; + linenoiseHistoryAdd(buf); + } + fclose(fp); + return 0; +} diff --git a/lib/wrappers/linenoise/linenoise.h b/lib/wrappers/linenoise/linenoise.h new file mode 100644 index 000000000..5b64c0407 --- /dev/null +++ b/lib/wrappers/linenoise/linenoise.h @@ -0,0 +1,68 @@ +/* linenoise.h -- VERSION 1.0 + * + * Guerrilla line editing library against the idea that a line editing lib + * needs to be 20,000 lines of C code. + * + * See linenoise.c for more information. + * + * ------------------------------------------------------------------------ + * + * Copyright (c) 2010-2014, Salvatore Sanfilippo + * Copyright (c) 2010-2013, Pieter Noordhuis + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef __LINENOISE_H +#define __LINENOISE_H + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct linenoiseCompletions { + size_t len; + char **cvec; +} linenoiseCompletions; + +typedef void(*linenoiseCompletionCallback)(const char *, linenoiseCompletions *); +void linenoiseSetCompletionCallback(linenoiseCompletionCallback *); +void linenoiseAddCompletion(linenoiseCompletions *, const char *); + +char *linenoise(const char *prompt); +int linenoiseHistoryAdd(const char *line); +int linenoiseHistorySetMaxLen(int len); +int linenoiseHistorySave(const char *filename); +int linenoiseHistoryLoad(const char *filename); +void linenoiseClearScreen(void); +void linenoiseSetMultiLine(int ml); +void linenoisePrintKeyCodes(void); + +#ifdef __cplusplus +} +#endif + +#endif /* __LINENOISE_H */ diff --git a/lib/wrappers/linenoise/linenoise.nim b/lib/wrappers/linenoise/linenoise.nim new file mode 100644 index 000000000..865e3478b --- /dev/null +++ b/lib/wrappers/linenoise/linenoise.nim @@ -0,0 +1,38 @@ +# +# +# Nim's Runtime Library +# (c) Copyright 2010 Andreas Rumpf +# +# See the file "copying.txt", included in this +# distribution, for details about the copyright. +# + +type + Completions* {.importc: "linenoiseCompletions", header: "linenoise.h".} = object + len* {.importc: "len".}: csize + cvec* {.importc: "cvec".}: cstringArray + + CompletionCallback* = proc (a2: cstring; a3: ptr Completions) {.cdecl.} + +{.compile: "linenoise.c".} + +proc setCompletionCallback*(a2: ptr CompletionCallback) {. + importc: "linenoiseSetCompletionCallback", header: "linenoise.h".} +proc addCompletion*(a2: ptr Completions; a3: cstring) {. + importc: "linenoiseAddCompletion", header: "linenoise.h".} +proc readLine*(prompt: cstring): cstring {.importc: "linenoise", header: "linenoise.h".} +proc historyAdd*(line: cstring): cint {.importc: "linenoiseHistoryAdd", + header: "linenoise.h", discardable.} +proc historySetMaxLen*(len: cint): cint {.importc: "linenoiseHistorySetMaxLen", + header: "linenoise.h".} +proc historySave*(filename: cstring): cint {.importc: "linenoiseHistorySave", + header: "linenoise.h".} +proc historyLoad*(filename: cstring): cint {.importc: "linenoiseHistoryLoad", + header: "linenoise.h".} +proc clearScreen*() {.importc: "linenoiseClearScreen", header: "linenoise.h".} +proc setMultiLine*(ml: cint) {.importc: "linenoiseSetMultiLine", + header: "linenoise.h".} +proc printKeyCodes*() {.importc: "linenoisePrintKeyCodes", + header: "linenoise.h".} + +proc free*(s: cstring) {.importc: "free", header: "".} From e85aa3db0736535d7e1ecc14707f7c8f6c858078 Mon Sep 17 00:00:00 2001 From: Araq Date: Sun, 21 Jun 2015 10:56:56 +0200 Subject: [PATCH 0526/1263] Unix line endings for linenoise.nim --- lib/wrappers/linenoise/linenoise.nim | 72 +++++++++++++--------------- 1 file changed, 34 insertions(+), 38 deletions(-) diff --git a/lib/wrappers/linenoise/linenoise.nim b/lib/wrappers/linenoise/linenoise.nim index 865e3478b..a6260eb12 100644 --- a/lib/wrappers/linenoise/linenoise.nim +++ b/lib/wrappers/linenoise/linenoise.nim @@ -1,38 +1,34 @@ -# -# -# Nim's Runtime Library -# (c) Copyright 2010 Andreas Rumpf -# -# See the file "copying.txt", included in this -# distribution, for details about the copyright. -# - -type - Completions* {.importc: "linenoiseCompletions", header: "linenoise.h".} = object - len* {.importc: "len".}: csize - cvec* {.importc: "cvec".}: cstringArray - - CompletionCallback* = proc (a2: cstring; a3: ptr Completions) {.cdecl.} - -{.compile: "linenoise.c".} - -proc setCompletionCallback*(a2: ptr CompletionCallback) {. - importc: "linenoiseSetCompletionCallback", header: "linenoise.h".} -proc addCompletion*(a2: ptr Completions; a3: cstring) {. - importc: "linenoiseAddCompletion", header: "linenoise.h".} -proc readLine*(prompt: cstring): cstring {.importc: "linenoise", header: "linenoise.h".} -proc historyAdd*(line: cstring): cint {.importc: "linenoiseHistoryAdd", - header: "linenoise.h", discardable.} -proc historySetMaxLen*(len: cint): cint {.importc: "linenoiseHistorySetMaxLen", - header: "linenoise.h".} -proc historySave*(filename: cstring): cint {.importc: "linenoiseHistorySave", - header: "linenoise.h".} -proc historyLoad*(filename: cstring): cint {.importc: "linenoiseHistoryLoad", - header: "linenoise.h".} -proc clearScreen*() {.importc: "linenoiseClearScreen", header: "linenoise.h".} -proc setMultiLine*(ml: cint) {.importc: "linenoiseSetMultiLine", - header: "linenoise.h".} -proc printKeyCodes*() {.importc: "linenoisePrintKeyCodes", - header: "linenoise.h".} - -proc free*(s: cstring) {.importc: "free", header: "".} +# +# +# Nim's Runtime Library +# (c) Copyright 2015 Andreas Rumpf +# +# See the file "copying.txt", included in this +# distribution, for details about the copyright. +# + +type + Completions* = object + len*: csize + cvec*: cstringArray + + CompletionCallback* = proc (a2: cstring; a3: ptr Completions) {.cdecl.} + +{.compile: "linenoise.c".} + +proc setCompletionCallback*(a2: ptr CompletionCallback) {. + importc: "linenoiseSetCompletionCallback".} +proc addCompletion*(a2: ptr Completions; a3: cstring) {. + importc: "linenoiseAddCompletion".} +proc readLine*(prompt: cstring): cstring {.importc: "linenoise".} +proc historyAdd*(line: cstring): cint {.importc: "linenoiseHistoryAdd", + discardable.} +proc historySetMaxLen*(len: cint): cint {.importc: "linenoiseHistorySetMaxLen".} +proc historySave*(filename: cstring): cint {.importc: "linenoiseHistorySave".} +proc historyLoad*(filename: cstring): cint {.importc: "linenoiseHistoryLoad".} +proc clearScreen*() {.importc: "linenoiseClearScreen".} +proc setMultiLine*(ml: cint) {.importc: "linenoiseSetMultiLine".} +proc printKeyCodes*() {.importc: "linenoisePrintKeyCodes".} + +proc free*(s: cstring) {.importc: "free", header: "".} + From 3444b8707907a7d7a9d22fde022cba55a1e2206a Mon Sep 17 00:00:00 2001 From: Araq Date: Sun, 21 Jun 2015 10:57:26 +0200 Subject: [PATCH 0527/1263] fixed indentation --- compiler/options.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/options.nim b/compiler/options.nim index 398d3171d..bc70cd657 100644 --- a/compiler/options.nim +++ b/compiler/options.nim @@ -302,7 +302,7 @@ proc completeGeneratedFilePath*(f: string, createSubDir: bool = true): string = try: createDir(subdir) when noTimeMachine: - excludeDirFromTimeMachine(subdir) + excludeDirFromTimeMachine(subdir) except OSError: writeLine(stdout, "cannot create directory: " & subdir) quit(1) From 9173b66cb750326a51a1d14e71004b7c27df1d44 Mon Sep 17 00:00:00 2001 From: Araq Date: Sun, 21 Jun 2015 10:57:43 +0200 Subject: [PATCH 0528/1263] linenoise support now works --- lib/wrappers/linenoise/linenoise.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/wrappers/linenoise/linenoise.h b/lib/wrappers/linenoise/linenoise.h index 5b64c0407..fbb01cfaa 100644 --- a/lib/wrappers/linenoise/linenoise.h +++ b/lib/wrappers/linenoise/linenoise.h @@ -48,7 +48,7 @@ typedef struct linenoiseCompletions { char **cvec; } linenoiseCompletions; -typedef void(*linenoiseCompletionCallback)(const char *, linenoiseCompletions *); +typedef void(linenoiseCompletionCallback)(const char *, linenoiseCompletions *); void linenoiseSetCompletionCallback(linenoiseCompletionCallback *); void linenoiseAddCompletion(linenoiseCompletions *, const char *); From a7f03e8d46b25ef9210a75d1c09bccbebb9e3842 Mon Sep 17 00:00:00 2001 From: def Date: Sun, 21 Jun 2015 21:25:19 +0200 Subject: [PATCH 0529/1263] Use gender neutral language in documentation --- doc/manual/ffi.txt | 2 +- doc/tut1.txt | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/doc/manual/ffi.txt b/doc/manual/ffi.txt index 4a4e0316f..bc402b570 100644 --- a/doc/manual/ffi.txt +++ b/doc/manual/ffi.txt @@ -107,7 +107,7 @@ Unchecked pragma ---------------- The ``unchecked`` pragma can be used to mark a named array as ``unchecked`` meaning its bounds are not checked. This is often useful when one wishes to -implement his own flexibly sized arrays. Additionally an unchecked array is +implement their own flexibly sized arrays. Additionally an unchecked array is translated into a C array of undetermined size: .. code-block:: nim diff --git a/doc/tut1.txt b/doc/tut1.txt index 500480cf0..11a4d6adc 100644 --- a/doc/tut1.txt +++ b/doc/tut1.txt @@ -333,8 +333,8 @@ The while statement is a simple looping construct: name = readLine(stdin) # no ``var``, because we do not declare a new variable here -The example uses a while loop to keep asking the user for his name, as long as -he types in nothing (only presses RETURN). +The example uses a while loop to keep asking the user for their name, as long +as the user types in nothing (only presses RETURN). For statement @@ -545,9 +545,9 @@ procedures are defined with the ``proc`` keyword: echo("I think you know what the problem is just as well as I do.") This example shows a procedure named ``yes`` that asks the user a ``question`` -and returns true if he answered "yes" (or something similar) and returns -false if he answered "no" (or something similar). A ``return`` statement leaves -the procedure (and therefore the while loop) immediately. The +and returns true if they answered "yes" (or something similar) and returns +false if they answered "no" (or something similar). A ``return`` statement +leaves the procedure (and therefore the while loop) immediately. The ``(question: string): bool`` syntax describes that the procedure expects a parameter named ``question`` of type ``string`` and returns a value of type ``bool``. ``Bool`` is a built-in type: the only valid values for ``bool`` are From e7132767a19fae1c20bfe49d764b628f3da6e8c8 Mon Sep 17 00:00:00 2001 From: def Date: Sun, 21 Jun 2015 21:25:38 +0200 Subject: [PATCH 0530/1263] Fix typos in comments --- lib/system/alloc.nim | 2 +- lib/system/hti.nim | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/lib/system/alloc.nim b/lib/system/alloc.nim index 76232499e..d877cda2c 100644 --- a/lib/system/alloc.nim +++ b/lib/system/alloc.nim @@ -210,7 +210,7 @@ proc getMaxMem(a: var MemRegion): int = proc llAlloc(a: var MemRegion, size: int): pointer = # *low-level* alloc for the memory managers data structures. Deallocation - # is done at he end of the allocator's life time. + # is done at the end of the allocator's life time. if a.llmem == nil or size > a.llmem.size: # the requested size is ``roundup(size+sizeof(LLChunk), PageSize)``, but # since we know ``size`` is a (small) constant, we know the requested size diff --git a/lib/system/hti.nim b/lib/system/hti.nim index aff0c0e6f..bfb13059e 100644 --- a/lib/system/hti.nim +++ b/lib/system/hti.nim @@ -7,14 +7,14 @@ # distribution, for details about the copyright. # -when declared(NimString): +when declared(NimString): # we are in system module: {.pragma: codegenType, compilerproc.} else: {.pragma: codegenType, importc.} -type - # This should be he same as ast.TTypeKind +type + # This should be the same as ast.TTypeKind # many enum fields are not used at runtime TNimKind = enum tyNone, @@ -73,7 +73,7 @@ type len: int sons: ptr array [0..0x7fff, ptr TNimNode] - TNimTypeFlag = enum + TNimTypeFlag = enum ntfNoRefs = 0, # type contains no tyRef, tySequence, tyString ntfAcyclic = 1, # type cannot form a cycle ntfEnumHole = 2 # enum has holes and thus `$` for them needs the slow @@ -88,5 +88,5 @@ type marker: proc (p: pointer, op: int) {.nimcall, benign.} # marker proc for GC deepcopy: proc (p: pointer): pointer {.nimcall, benign.} PNimType = ptr TNimType - + # node.len may be the ``first`` element of a set From 68f583ddb7a3e1a9fe8d004fef199d3e1c0bb342 Mon Sep 17 00:00:00 2001 From: Dominik Picheta Date: Mon, 22 Jun 2015 21:40:38 +0100 Subject: [PATCH 0531/1263] Adjustments to #2610. --- lib/pure/asyncnet.nim | 11 ++++++++++- lib/pure/net.nim | 9 +++++---- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/lib/pure/asyncnet.nim b/lib/pure/asyncnet.nim index 4b221eb72..712bba33b 100644 --- a/lib/pure/asyncnet.nim +++ b/lib/pure/asyncnet.nim @@ -472,7 +472,16 @@ when defined(ssl): socket.bioOut = bioNew(bio_s_mem()) sslSetBio(socket.sslHandle, socket.bioIn, socket.bioOut) - proc wrapSocket*(ctx: SslContext, socket: AsyncSocket, handshake: SslHandshakeType) = + proc wrapConnectedSocket*(ctx: SslContext, socket: AsyncSocket, + handshake: SslHandshakeType) = + ## Wraps a connected socket in an SSL context. This function effectively + ## turns ``socket`` into an SSL socket. + ## + ## This should be called on a connected socket, and will perform + ## an SSL handshake immediately. + ## + ## **Disclaimer**: This code is not well tested, may be very unsafe and + ## prone to security vulnerabilities. wrapSocket(ctx, socket) case handshake diff --git a/lib/pure/net.nim b/lib/pure/net.nim index 7dcc35495..29e115da1 100644 --- a/lib/pure/net.nim +++ b/lib/pure/net.nim @@ -102,7 +102,7 @@ type proc isIpAddress*(address_str: string): bool {.tags: [].} proc parseIpAddress*(address_str: string): IpAddress proc socketError*(socket: Socket, err: int = -1, async = false, -lastError = (-1).OSErrorCode): void + lastError = (-1).OSErrorCode): void proc isDisconnectionError*(flags: set[SocketFlag], lastError: OSErrorCode): bool = @@ -259,9 +259,10 @@ when defined(ssl): if SSLSetFd(socket.sslHandle, socket.fd) != 1: raiseSSLError() - proc wrapSocket*(ctx: SSLContext, socket: Socket, handshake: SslHandshakeType) = - ## Wraps a socket in an SSL context. This function effectively turns - ## ``socket`` into an SSL socket. + proc wrapConnectedSocket*(ctx: SSLContext, socket: Socket, + handshake: SslHandshakeType) = + ## Wraps a connected socket in an SSL context. This function effectively + ## turns ``socket`` into an SSL socket. ## ## This should be called on a connected socket, and will perform ## an SSL handshake immediately. From 571aaae1f79bc463fc02a64b9d746fa24c000e5e Mon Sep 17 00:00:00 2001 From: Adam Strzelecki Date: Sun, 21 Jun 2015 13:12:16 +0200 Subject: [PATCH 0532/1263] Contributing: Introduce some general commit rules Due some latest changes that introduced some substantial noise in the project history I hereby propose some general commit rules that have proven to work in many other projects. Both contributors and maintainers (accepting PRs) are obliged to follow this rules, for sake of the Nim project and good collaboration. --- contributing.rst | 47 +++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 45 insertions(+), 2 deletions(-) diff --git a/contributing.rst b/contributing.rst index 8e669c614..dc77f0dbd 100644 --- a/contributing.rst +++ b/contributing.rst @@ -1,7 +1,50 @@ -The git stuff +The Git stuff ============= -`Guide by github, scroll down a bit `_ +General commit rules +-------------------- + +1. All changes introduced by the commit (diff lines) must be related to the + subject of the commit. + + If you change some other unrelated to the subject parts of the file, because + your editor reformatted automatically the code or whatever different reason, + this should be excluded from the commit. + + *Tip:* Never commit everything as is using ``git commit -a``, but review + carefully your changes with ``git add -p``. + +2. Changes should not introduce any trailing whitespace. + + Always check your changes for whitespace errors using ``git diff --check`` + or add following ``pre-commit`` hook: + + .. code-block:: sh + + #!/bin/sh + git diff --check --cached || exit $? + + No sane programming or markup language cares about trailing whitespace, so + tailing whitespace is just a noise you should not introduce to the + repository. + +3. Describe your commit well following the 50/72 rule on commit messages: + + Start with the commit subject as single line maximum of 50 characters, + without trailing period, briefly describing the change. + + Optionally put the detailed description as a blocks of text wrapped to 72 + characters, separated by single blank line from the other parts (including + the subject). + +More information +---------------- + +For more information on how to produce great commits and describe them well read: + +* `How to Write a Git Commit Message `_ +* `A Note About Git Commit Messages `_ +* `Guide by github, scroll down a bit `_ Deprecation =========== From 0069308b22d8754627a74478062870edc7d51ab4 Mon Sep 17 00:00:00 2001 From: yglukhov Date: Tue, 23 Jun 2015 14:46:38 +0300 Subject: [PATCH 0533/1263] JS object initializer fix. --- compiler/jsgen.nim | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/compiler/jsgen.nim b/compiler/jsgen.nim index ede759426..87408f395 100644 --- a/compiler/jsgen.nim +++ b/compiler/jsgen.nim @@ -1435,23 +1435,22 @@ proc genTupleConstr(p: PProc, n: PNode, r: var TCompRes) = r.res.add("}") proc genObjConstr(p: PProc, n: PNode, r: var TCompRes) = - # XXX inheritance? var a: TCompRes - r.res = rope("{") r.kind = resExpr + var initList : Rope var fieldIDs = initIntSet() for i in countup(1, sonsLen(n) - 1): - if i > 1: add(r.res, ", ") + if i > 1: add(initList, ", ") var it = n.sons[i] internalAssert it.kind == nkExprColonExpr gen(p, it.sons[1], a) var f = it.sons[0].sym if f.loc.r == nil: f.loc.r = mangleName(f) fieldIDs.incl(f.id) - addf(r.res, "$#: $#" | "$# = $#" , [f.loc.r, a.res]) + addf(initList, "$#: $#" | "$# = $#" , [f.loc.r, a.res]) let t = skipTypes(n.typ, abstractInst + skipPtrs) - createObjInitList(p, t, fieldIDs, r.res) - r.res.add("}") + createObjInitList(p, t, fieldIDs, initList) + r.res = "{$1}" % [initList] proc genConv(p: PProc, n: PNode, r: var TCompRes) = var dest = skipTypes(n.typ, abstractVarRange) From f340f76f45170535effa959543f4a458e1964815 Mon Sep 17 00:00:00 2001 From: Andrew Yourtchenko Date: Tue, 23 Jun 2015 22:59:48 +0200 Subject: [PATCH 0534/1263] Add getSockDomain to return AF_INET or AF_INET6 of a SocketHandle. --- lib/pure/rawsockets.nim | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/lib/pure/rawsockets.nim b/lib/pure/rawsockets.nim index 6d656c983..c99f9a7a9 100644 --- a/lib/pure/rawsockets.nim +++ b/lib/pure/rawsockets.nim @@ -315,6 +315,21 @@ proc getHostByName*(name: string): Hostent {.tags: [ReadIOEffect].} = result.addrList = cstringArrayToSeq(s.h_addr_list) result.length = int(s.h_length) +proc getSockDomain*(socket: SocketHandle): Domain = + ## returns the socket's domain (AF_INET or AF_INET6). + var name: SockAddr + var namelen = sizeof(name).SockLen + if getsockname(socket, cast[ptr SockAddr](addr(name)), + addr(namelen)) == -1'i32: + raiseOSError(osLastError()) + if name.sa_family == posix.AF_INET: + result = AF_INET + elif name.sa_family == posix.AF_INET6: + result = AF_INET6 + else: + raise newException(OSError, "unknown socket family in getSockFamily") + + proc getSockName*(socket: SocketHandle): Port = ## returns the socket's associated port number. var name: Sockaddr_in From 93e2d9f9794c637352a167eba2364e2ee7154954 Mon Sep 17 00:00:00 2001 From: Andrew Yourtchenko Date: Tue, 23 Jun 2015 23:02:10 +0200 Subject: [PATCH 0535/1263] Make asyncnet.bindAddr IPv4+IPv6 compatible. --- lib/pure/asyncnet.nim | 27 ++++++++++++--------------- 1 file changed, 12 insertions(+), 15 deletions(-) diff --git a/lib/pure/asyncnet.nim b/lib/pure/asyncnet.nim index 712bba33b..2921de681 100644 --- a/lib/pure/asyncnet.nim +++ b/lib/pure/asyncnet.nim @@ -423,24 +423,21 @@ proc bindAddr*(socket: AsyncSocket, port = Port(0), address = "") {. ## Binds ``address``:``port`` to the socket. ## ## If ``address`` is "" then ADDR_ANY will be bound. + var sockDomain = getSockDomain(socket.fd) - if address == "": - var name: Sockaddr_in - when defined(Windows) or defined(nimdoc): - name.sin_family = toInt(AF_INET).int16 + var realaddr = address + if realaddr == "": + case sockDomain + of AF_INET6: realaddr = "::" + of AF_INET: realaddr = "0.0.0.0" else: - name.sin_family = toInt(AF_INET) - name.sin_port = htons(int16(port)) - name.sin_addr.s_addr = htonl(INADDR_ANY) - if bindAddr(socket.fd, cast[ptr SockAddr](addr(name)), - sizeof(name).Socklen) < 0'i32: - raiseOSError(osLastError()) - else: - var aiList = getAddrInfo(address, port, AF_INET) - if bindAddr(socket.fd, aiList.ai_addr, aiList.ai_addrlen.Socklen) < 0'i32: - dealloc(aiList) - raiseOSError(osLastError()) + raiseOSError("Unknown socket address family and no address specified to bindAddr") + + var aiList = getAddrInfo(realaddr, port, sockDomain) + if bindAddr(socket.fd, aiList.ai_addr, aiList.ai_addrlen.Socklen) < 0'i32: dealloc(aiList) + raiseOSError(osLastError()) + dealloc(aiList) proc close*(socket: AsyncSocket) = ## Closes the socket. From c42b08988c8ff9b64af94329d61dc97efe261265 Mon Sep 17 00:00:00 2001 From: Andrew Yourtchenko Date: Tue, 23 Jun 2015 23:03:35 +0200 Subject: [PATCH 0536/1263] Make newAsyncSocket AF_INET6 the default domain. --- lib/pure/asyncnet.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/pure/asyncnet.nim b/lib/pure/asyncnet.nim index 2921de681..d7ac60147 100644 --- a/lib/pure/asyncnet.nim +++ b/lib/pure/asyncnet.nim @@ -100,7 +100,7 @@ proc newAsyncSocket*(fd: AsyncFD, buffered = true): AsyncSocket = if buffered: result.currPos = 0 -proc newAsyncSocket*(domain: Domain = AF_INET, typ: SockType = SOCK_STREAM, +proc newAsyncSocket*(domain: Domain = AF_INET6, typ: SockType = SOCK_STREAM, protocol: Protocol = IPPROTO_TCP, buffered = true): AsyncSocket = ## Creates a new asynchronous socket. ## From ec33471aeec1e54d3f6ec79762f2f63307d12496 Mon Sep 17 00:00:00 2001 From: Andrew Yourtchenko Date: Wed, 24 Jun 2015 01:23:09 +0200 Subject: [PATCH 0537/1263] Update posix.Sockaddr_in6 and posix.Sockaddr_storage, deprecate old T* types. --- lib/posix/posix.nim | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lib/posix/posix.nim b/lib/posix/posix.nim index dba79cbf6..92bafe07d 100644 --- a/lib/posix/posix.nim +++ b/lib/posix/posix.nim @@ -448,7 +448,7 @@ type sa_family*: TSa_Family ## Address family. sa_data*: array [0..255, char] ## Socket address (variable-length data). - Tsockaddr_storage* {.importc: "struct sockaddr_storage", + Sockaddr_storage* {.importc: "struct sockaddr_storage", header: "", pure, final.} = object ## struct sockaddr_storage ss_family*: TSa_Family ## Address family. @@ -506,7 +506,7 @@ type header: "".} = object ## struct in6_addr s6_addr*: array [0..15, char] - Tsockaddr_in6* {.importc: "struct sockaddr_in6", pure, final, + Sockaddr_in6* {.importc: "struct sockaddr_in6", pure, final, header: "".} = object ## struct sockaddr_in6 sin6_family*: TSa_Family ## AF_INET6. sin6_port*: InPort ## Port number. @@ -581,6 +581,7 @@ type {.deprecated: [TSockaddr_in: Sockaddr_in, TAddrinfo: AddrInfo, TSockAddr: SockAddr, TSockLen: SockLen, TTimeval: Timeval, + Tsockaddr_storage: Sockaddr_storage, Tsockaddr_in6: Sockaddr_in6, Thostent: Hostent, TServent: Servent, TInAddr: InAddr, TIOVec: IOVec, TInPort: InPort, TInAddrT: InAddrT, TIn6Addr: In6Addr, TInAddrScalar: InAddrScalar, TProtoent: Protoent].} From 61336b2404c7b09b7ddb73d17426e6b291b15c9c Mon Sep 17 00:00:00 2001 From: Andrew Yourtchenko Date: Wed, 24 Jun 2015 01:36:09 +0200 Subject: [PATCH 0538/1263] Expose INET6_ADDRSTRLEN. --- lib/posix/posix.nim | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/posix/posix.nim b/lib/posix/posix.nim index 92bafe07d..9b9bf390a 100644 --- a/lib/posix/posix.nim +++ b/lib/posix/posix.nim @@ -1663,6 +1663,8 @@ var INET_ADDRSTRLEN* {.importc, header: "".}: cint ## 16. Length of the string form for IP. + INET6_ADDRSTRLEN* {.importc, header: "".}: cint + ## Length of the string form for IPv6. IPV6_JOIN_GROUP* {.importc, header: "".}: cint ## Join a multicast group. From 48ff0d84d0719045d0d5fd907ff11789ce82dd10 Mon Sep 17 00:00:00 2001 From: Andrew Yourtchenko Date: Wed, 24 Jun 2015 01:37:57 +0200 Subject: [PATCH 0539/1263] Add getAddrString which returns string representing the address within SockAddr. --- lib/pure/rawsockets.nim | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/lib/pure/rawsockets.nim b/lib/pure/rawsockets.nim index c99f9a7a9..d1922de65 100644 --- a/lib/pure/rawsockets.nim +++ b/lib/pure/rawsockets.nim @@ -330,6 +330,18 @@ proc getSockDomain*(socket: SocketHandle): Domain = raise newException(OSError, "unknown socket family in getSockFamily") +proc getAddrString*(sockAddr: ptr SockAddr): string = + ## return the string representation of address within sockAddr + if sockAddr.sa_family == posix.AF_INET: + result = $inet_ntoa(cast[ptr Sockaddr_in](sockAddr).sin_addr) + elif sockAddr.sa_family == posix.AF_INET6: + var v6addr = cast[ptr Sockaddr_in6](sockAddr).sin6_addr + result = newString(posix.INET6_ADDRSTRLEN) + discard posix.inet_ntop(posix.AF_INET6, addr cast[ptr Sockaddr_in6](sockAddr).sin6_addr, result.cstring, result.len.int32) + else: + raise newException(OSError, "unknown socket family in getAddrString") + + proc getSockName*(socket: SocketHandle): Port = ## returns the socket's associated port number. var name: Sockaddr_in From 0d3e2277e96abecaa1ca83cff1fae4d22066dc3d Mon Sep 17 00:00:00 2001 From: Andrew Yourtchenko Date: Wed, 24 Jun 2015 01:38:46 +0200 Subject: [PATCH 0540/1263] Export Sockaddr_in6, Sockaddr_storage. --- lib/pure/rawsockets.nim | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/pure/rawsockets.nim b/lib/pure/rawsockets.nim index d1922de65..12ec50ec6 100644 --- a/lib/pure/rawsockets.nim +++ b/lib/pure/rawsockets.nim @@ -29,6 +29,7 @@ else: EINTR, EINPROGRESS, ECONNRESET, EPIPE, ENETRESET export SocketHandle, Sockaddr_in, Addrinfo, INADDR_ANY, SockAddr, SockLen, + Sockaddr_in6, Sockaddr_storage, inet_ntoa, recv, `==`, connect, send, accept, recvfrom, sendto export From 37f50695eed1059089ea069b263b5fbeaa51ed79 Mon Sep 17 00:00:00 2001 From: Andrew Yourtchenko Date: Wed, 24 Jun 2015 01:39:58 +0200 Subject: [PATCH 0541/1263] Make asyncdispatch.connectAddr IPv6-aware. --- lib/pure/asyncdispatch.nim | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/pure/asyncdispatch.nim b/lib/pure/asyncdispatch.nim index 550b82f49..3e9e5ac30 100644 --- a/lib/pure/asyncdispatch.nim +++ b/lib/pure/asyncdispatch.nim @@ -1135,7 +1135,7 @@ else: client: AsyncFD]]("acceptAddr") proc cb(sock: AsyncFD): bool = result = true - var sockAddress: SockAddr_in + var sockAddress: Sockaddr_storage var addrLen = sizeof(sockAddress).Socklen var client = accept(sock.SocketHandle, cast[ptr SockAddr](addr(sockAddress)), addr(addrLen)) @@ -1151,7 +1151,7 @@ else: retFuture.fail(newException(OSError, osErrorMsg(lastError))) else: register(client.AsyncFD) - retFuture.complete(($inet_ntoa(sockAddress.sin_addr), client.AsyncFD)) + retFuture.complete((getAddrString(cast[ptr SockAddr](addr sockAddress)), client.AsyncFD)) addRead(socket, cb) return retFuture From 21ee21cc2374bef7de57932f2eadcd82667022cf Mon Sep 17 00:00:00 2001 From: Andrew Yourtchenko Date: Wed, 24 Jun 2015 02:07:06 +0200 Subject: [PATCH 0542/1263] Return address in pure IPv4 notation by getAddrString if IPv6 address is IPv4-mapped. --- lib/pure/rawsockets.nim | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/pure/rawsockets.nim b/lib/pure/rawsockets.nim index 12ec50ec6..c97718b0a 100644 --- a/lib/pure/rawsockets.nim +++ b/lib/pure/rawsockets.nim @@ -339,6 +339,8 @@ proc getAddrString*(sockAddr: ptr SockAddr): string = var v6addr = cast[ptr Sockaddr_in6](sockAddr).sin6_addr result = newString(posix.INET6_ADDRSTRLEN) discard posix.inet_ntop(posix.AF_INET6, addr cast[ptr Sockaddr_in6](sockAddr).sin6_addr, result.cstring, result.len.int32) + if posix.IN6_IS_ADDR_V4MAPPED(addr cast[ptr Sockaddr_in6](sockAddr).sin6_addr) != 0: + result = result.substr("::ffff:".len) else: raise newException(OSError, "unknown socket family in getAddrString") From 41be1c6c4dfe99989d746175dbb1904152302e8e Mon Sep 17 00:00:00 2001 From: Andrew Yourtchenko Date: Wed, 24 Jun 2015 02:08:17 +0200 Subject: [PATCH 0543/1263] Allow to connect to IPv4-mapped addresses for IPv6 sockets - thus full IPv4 compatibility. --- lib/pure/rawsockets.nim | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/pure/rawsockets.nim b/lib/pure/rawsockets.nim index c97718b0a..9bfe9dab5 100644 --- a/lib/pure/rawsockets.nim +++ b/lib/pure/rawsockets.nim @@ -195,6 +195,7 @@ proc getAddrInfo*(address: string, port: Port, af: Domain = AF_INET, typ: SockTy hints.ai_family = toInt(af) hints.ai_socktype = toInt(typ) hints.ai_protocol = toInt(prot) + hints.ai_flags = posix.AI_V4MAPPED var gaiResult = getaddrinfo(address, $port, addr(hints), result) if gaiResult != 0'i32: when useWinVersion: From c4a25d23b6220cd5740b40d8c20e8dcde45310bc Mon Sep 17 00:00:00 2001 From: Andrew Yourtchenko Date: Wed, 24 Jun 2015 02:09:21 +0200 Subject: [PATCH 0544/1263] Match the AF of the socket in connect(). --- lib/pure/asyncdispatch.nim | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lib/pure/asyncdispatch.nim b/lib/pure/asyncdispatch.nim index 3e9e5ac30..5a059ec8e 100644 --- a/lib/pure/asyncdispatch.nim +++ b/lib/pure/asyncdispatch.nim @@ -1009,7 +1009,7 @@ else: processTimers(p) proc connect*(socket: AsyncFD, address: string, port: Port, - af = AF_INET): Future[void] = + af_unused = AF_INET): Future[void] = var retFuture = newFuture[void]("connect") proc cb(fd: AsyncFD): bool = @@ -1017,7 +1017,8 @@ else: retFuture.complete() return true - var aiList = getAddrInfo(address, port, af) + var sockDomain = getSockDomain(socket.SocketHandle) + var aiList = getAddrInfo(address, port, sockDomain) var success = false var lastError: OSErrorCode var it = aiList From edbd191f74996e6469cf5d45171046c38851e208 Mon Sep 17 00:00:00 2001 From: apense Date: Wed, 24 Jun 2015 03:22:04 -0400 Subject: [PATCH 0545/1263] Conversion between radians and degrees.Fixes #2881 provides a new constant for conversion (not public, but that can be changed if it's wanted). the functions are pretty simple, honestly. top-level comment so documentation for each function could remain. Fixes #2881 --- lib/pure/math.nim | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/lib/pure/math.nim b/lib/pure/math.nim index 494dfc4c8..2dc66bc25 100644 --- a/lib/pure/math.nim +++ b/lib/pure/math.nim @@ -12,6 +12,14 @@ ## Basic math routines for Nim. ## This module is available for the `JavaScript target ## `_. +## +## Note that the trigonometric functions naturally operate on radians. +## The helper functions `degToRad` and `radToDeg` provide conversion +## between radians and degrees. +## +## Note that the trigonometric functions naturally operate on radians. +## The helper functions `degToRad` and `radToDeg` provide conversion +## between radians and degrees. include "system/inclrtl" {.push debugger:off .} # the user does not want to trace a part @@ -38,6 +46,7 @@ const ## meaningful digits ## after the decimal point ## for Nim's ``float`` type. + RadPerDeg = PI / 180.0 ## number of radians per degree type FloatClass* = enum ## describes the class a floating point value belongs to. @@ -317,6 +326,14 @@ else: {.pop.} +proc degToRad*[T](d: T): float {.inline.} = + ## Convert from degrees to radians + result = float(d) * RadPerDeg + +proc radToDeg*[T](d: T): float {.inline.} = + ## Convert from radians to degrees + result = float(d) / RadPerDeg + proc `mod`*(x, y: float): float = result = if y == 0.0: x else: x - y * (x/y).floor From 67b3c4b31f10845d0713c3891c77f07f70ffe04c Mon Sep 17 00:00:00 2001 From: apense Date: Wed, 24 Jun 2015 03:33:48 -0400 Subject: [PATCH 0546/1263] Added documentation for mod Along with a brief example for sign demonstration --- lib/pure/math.nim | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/lib/pure/math.nim b/lib/pure/math.nim index 494dfc4c8..7a88694b5 100644 --- a/lib/pure/math.nim +++ b/lib/pure/math.nim @@ -318,6 +318,12 @@ else: {.pop.} proc `mod`*(x, y: float): float = + ## Computes the modulo operation for float operators. Equivalent + ## to ``x - y * floor(x/y)``. Note that the remainder will always + ## have the same sign as the divisor. + ## + ## .. code-block:: nim + ## echo (4.0 mod -3.1) # -2.2 result = if y == 0.0: x else: x - y * (x/y).floor proc random*[T](x: Slice[T]): T = From 67fac7f1e7f40d49a985970e67a90dcfaf6ea433 Mon Sep 17 00:00:00 2001 From: Adam Strzelecki Date: Wed, 24 Jun 2015 19:50:51 +0200 Subject: [PATCH 0547/1263] Change --useColors to --colors:on|off and add help Since we introduced automatic colors on terminals (via isatty) there is no way to turn it off, since (undocumented) --useColors just turns them on. This replaces --useColors with --colors:on|off, so anyone who prefers non-colored compiler messages may now turn it off now. --- compiler/commands.nim | 4 +--- doc/advopt.txt | 1 + 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/compiler/commands.nim b/compiler/commands.nim index 922cda3c6..e3d3bc432 100644 --- a/compiler/commands.nim +++ b/compiler/commands.nim @@ -537,9 +537,7 @@ proc processSwitch(switch, arg: string, pass: TCmdLinePass, info: TLineInfo) = of "genscript": expectNoArg(switch, arg, pass, info) incl(gGlobalOptions, optGenScript) - of "usecolors": - expectNoArg(switch, arg, pass, info) - incl(gGlobalOptions, optUseColors) + of "colors": processOnOffSwitchG({optUseColors}, arg, pass, info) of "lib": expectArg(switch, arg, pass, info) libpath = processPath(arg, notRelativeToProj=true) diff --git a/doc/advopt.txt b/doc/advopt.txt index a4f72e2d8..04ffce5b5 100644 --- a/doc/advopt.txt +++ b/doc/advopt.txt @@ -16,6 +16,7 @@ Advanced commands: Advanced options: -o, --out:FILE set the output filename --stdout output to stdout + --colors:on|off turn compiler messages coloring on|off --listFullPaths list full paths in messages -w, --warnings:on|off turn all warnings on|off --warning[X]:on|off turn specific warning X on|off From bfcbe64778f5bd9580aac9a2ae8c735257a2bade Mon Sep 17 00:00:00 2001 From: apense Date: Wed, 24 Jun 2015 14:49:15 -0400 Subject: [PATCH 0548/1263] Specific float32/float64 procs I still used generics, but made them choose from `float32` or `float64`. I can rewrite in separate, explicit procs if is wanted --- lib/pure/math.nim | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/lib/pure/math.nim b/lib/pure/math.nim index 2dc66bc25..f83ca6064 100644 --- a/lib/pure/math.nim +++ b/lib/pure/math.nim @@ -16,10 +16,6 @@ ## Note that the trigonometric functions naturally operate on radians. ## The helper functions `degToRad` and `radToDeg` provide conversion ## between radians and degrees. -## -## Note that the trigonometric functions naturally operate on radians. -## The helper functions `degToRad` and `radToDeg` provide conversion -## between radians and degrees. include "system/inclrtl" {.push debugger:off .} # the user does not want to trace a part @@ -326,13 +322,13 @@ else: {.pop.} -proc degToRad*[T](d: T): float {.inline.} = +proc degToRad*[T: float32|float64](d: T): T {.inline.} = ## Convert from degrees to radians - result = float(d) * RadPerDeg + result = T(d) * RadPerDeg -proc radToDeg*[T](d: T): float {.inline.} = +proc radToDeg*[T: float32|float64](d: T): T {.inline.} = ## Convert from radians to degrees - result = float(d) / RadPerDeg + result = T(d) / RadPerDeg proc `mod`*(x, y: float): float = result = if y == 0.0: x else: x - y * (x/y).floor From eef0e1bde1baebca9384f13a52e7fc8fca9a32fc Mon Sep 17 00:00:00 2001 From: Araq Date: Sun, 21 Jun 2015 22:27:45 +0200 Subject: [PATCH 0549/1263] fix grammar --- doc/manual/ffi.txt | 40 ++++++++++++++++++++-------------------- doc/tut1.txt | 4 ++-- 2 files changed, 22 insertions(+), 22 deletions(-) diff --git a/doc/manual/ffi.txt b/doc/manual/ffi.txt index bc402b570..f9056b159 100644 --- a/doc/manual/ffi.txt +++ b/doc/manual/ffi.txt @@ -70,8 +70,8 @@ the compiler to pass the type by reference (hidden pointer) to procs. Varargs pragma -------------- -The ``varargs`` pragma can be applied to procedures only (and procedure -types). It tells Nim that the proc can take a variable number of parameters +The ``varargs`` pragma can be applied to procedures only (and procedure +types). It tells Nim that the proc can take a variable number of parameters after the last specified parameter. Nim string values will be converted to C strings automatically: @@ -94,20 +94,20 @@ should scan unions conservatively. Packed pragma ------------- -The ``packed`` pragma can be applied to any ``object`` type. It ensures -that the fields of an object are packed back-to-back in memory. It is useful -to store packets or messages from/to network or hardware drivers, and for -interoperability with C. Combining packed pragma with inheritance is not -defined, and it should not be used with GC'ed memory (ref's). +The ``packed`` pragma can be applied to any ``object`` type. It ensures +that the fields of an object are packed back-to-back in memory. It is useful +to store packets or messages from/to network or hardware drivers, and for +interoperability with C. Combining packed pragma with inheritance is not +defined, and it should not be used with GC'ed memory (ref's). -**Future directions**: Using GC'ed memory in packed pragma will result in +**Future directions**: Using GC'ed memory in packed pragma will result in compile-time error. Usage with inheritance should be defined and documented. Unchecked pragma ---------------- The ``unchecked`` pragma can be used to mark a named array as ``unchecked`` -meaning its bounds are not checked. This is often useful when one wishes to -implement their own flexibly sized arrays. Additionally an unchecked array is +meaning its bounds are not checked. This is often useful to +implement customized flexibly sized arrays. Additionally an unchecked array is translated into a C array of undetermined size: .. code-block:: nim @@ -141,7 +141,7 @@ runtime size of the array. Dynlib pragma for import ------------------------ With the ``dynlib`` pragma a procedure or a variable can be imported from -a dynamic library (``.dll`` files for Windows, ``lib*.so`` files for UNIX). +a dynamic library (``.dll`` files for Windows, ``lib*.so`` files for UNIX). The non-optional argument has to be the name of the dynamic library: .. code-block:: Nim @@ -152,17 +152,17 @@ In general, importing a dynamic library does not require any special linker options or linking with import libraries. This also implies that no *devel* packages need to be installed. -The ``dynlib`` import mechanism supports a versioning scheme: +The ``dynlib`` import mechanism supports a versioning scheme: -.. code-block:: nim - proc Tcl_Eval(interp: pTcl_Interp, script: cstring): int {.cdecl, +.. code-block:: nim + proc Tcl_Eval(interp: pTcl_Interp, script: cstring): int {.cdecl, importc, dynlib: "libtcl(|8.5|8.4|8.3).so.(1|0)".} At runtime the dynamic library is searched for (in this order):: - + libtcl.so.1 libtcl.so.0 - libtcl8.5.so.1 + libtcl8.5.so.1 libtcl8.5.so.0 libtcl8.4.so.1 libtcl8.4.so.0 @@ -175,22 +175,22 @@ string expressions in general: .. code-block:: nim import os - proc getDllName: string = + proc getDllName: string = result = "mylib.dll" if existsFile(result): return result = "mylib2.dll" if existsFile(result): return quit("could not load dynamic library") - + proc myImport(s: cstring) {.cdecl, importc, dynlib: getDllName().} **Note**: Patterns like ``libtcl(|8.5|8.4).so`` are only supported in constant strings, because they are precompiled. -**Note**: Passing variables to the ``dynlib`` pragma will fail at runtime +**Note**: Passing variables to the ``dynlib`` pragma will fail at runtime because of order of initialization problems. -**Note**: A ``dynlib`` import can be overriden with +**Note**: A ``dynlib`` import can be overriden with the ``--dynlibOverride:name`` command line option. The Compiler User Guide contains further information. diff --git a/doc/tut1.txt b/doc/tut1.txt index 11a4d6adc..2dc2c1d86 100644 --- a/doc/tut1.txt +++ b/doc/tut1.txt @@ -333,7 +333,7 @@ The while statement is a simple looping construct: name = readLine(stdin) # no ``var``, because we do not declare a new variable here -The example uses a while loop to keep asking the user for their name, as long +The example uses a while loop to keep asking the users for their name, as long as the user types in nothing (only presses RETURN). @@ -774,7 +774,7 @@ proc even(n: int): bool = Here ``odd`` depends on ``even`` and vice versa. Thus ``even`` needs to be introduced to the compiler before it is completely defined. The syntax for such a forward declaration is simple: just omit the ``=`` and the -procedure's body. The ``assert`` just adds border conditions, and will be +procedure's body. The ``assert`` just adds border conditions, and will be covered later in `Modules`_ section. Later versions of the language will weaken the requirements for forward From 2a1620490c43694bfdd433f0c940490d65b24a53 Mon Sep 17 00:00:00 2001 From: Araq Date: Wed, 24 Jun 2015 20:34:42 +0200 Subject: [PATCH 0550/1263] protect against new stupid setlen that doesn't accept -1 anymore --- compiler/vmdeps.nim | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/compiler/vmdeps.nim b/compiler/vmdeps.nim index 21ee4967b..88bb7ae24 100644 --- a/compiler/vmdeps.nim +++ b/compiler/vmdeps.nim @@ -15,7 +15,8 @@ proc readOutput(p: Process): string = while not output.atEnd: result.add(output.readLine) result.add("\n") - result.setLen(result.len - "\n".len) + if result.len > 0: + result.setLen(result.len - "\n".len) discard p.waitForExit proc opGorge*(cmd, input: string): string = From ce9fa80b92700a0ce36817a360d235ff024a3708 Mon Sep 17 00:00:00 2001 From: Araq Date: Wed, 24 Jun 2015 21:11:24 +0200 Subject: [PATCH 0551/1263] fixes #2979 --- compiler/ccgexprs.nim | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/compiler/ccgexprs.nim b/compiler/ccgexprs.nim index 55fa7564c..10b5b1251 100644 --- a/compiler/ccgexprs.nim +++ b/compiler/ccgexprs.nim @@ -1582,7 +1582,8 @@ proc genRangeChck(p: BProc, n: PNode, d: var TLoc, magic: string) = var a: TLoc var dest = skipTypes(n.typ, abstractVar) # range checks for unsigned turned out to be buggy and annoying: - if optRangeCheck notin p.options or dest.kind in {tyUInt..tyUInt64}: + if optRangeCheck notin p.options or dest.skipTypes({tyRange}).kind in + {tyUInt..tyUInt64}: initLocExpr(p, n.sons[0], a) putIntoDest(p, d, n.typ, "(($1) ($2))" % [getTypeDesc(p.module, dest), rdCharLoc(a)]) From bdd5a8c05ed1a92a4eb3056b4852df695d622285 Mon Sep 17 00:00:00 2001 From: Araq Date: Thu, 25 Jun 2015 02:08:39 +0200 Subject: [PATCH 0552/1263] updated news.txt --- todo.txt | 2 +- web/news.txt | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/todo.txt b/todo.txt index 4972015a7..1d9d1c8d6 100644 --- a/todo.txt +++ b/todo.txt @@ -1,4 +1,4 @@ -version 0.11.2 +version 0.11.4 ============== - The remaining bugs of the lambda lifting pass that is responsible to enable diff --git a/web/news.txt b/web/news.txt index bf21dff8d..be27d83e5 100644 --- a/web/news.txt +++ b/web/news.txt @@ -21,6 +21,8 @@ News and ``2f`` (float32) which means imports like ``import scene/2d/sprite`` do not work anymore. Instead quotes have to be used: ``import "scene/2d/sprite"``. The former code never was valid Nim. + - The Windows API wrapper (``windows.nim``) is now not part of the official + distribution anymore. Instead use the ``oldwinapi`` Nimble package. Library additions From f8870280d7d0661da7187ee6be48c3c6419515f6 Mon Sep 17 00:00:00 2001 From: apense Date: Wed, 24 Jun 2015 23:30:03 -0400 Subject: [PATCH 0553/1263] Added example for associativity Hopefully this change makes this neat feature more apparent --- doc/manual/syntax.txt | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/doc/manual/syntax.txt b/doc/manual/syntax.txt index 24644bce2..99af15948 100644 --- a/doc/manual/syntax.txt +++ b/doc/manual/syntax.txt @@ -15,15 +15,22 @@ Associativity Binary operators whose first character is ``^`` are right-associative, all other binary operators are left-associative. - +.. code-block:: nim + proc `^/`(x, y: float): float = + # a right-associative division operator + result = x / y + echo 12 ^/ 4 ^/ 8 # 24.0 (4 / 8 = 0.5, then + 12 / 0.5 = 24.0) + echo 12 / 4 / 8 # 0.375 (12 / 4 = 3.0, then + 3 / 8 = 0.375) Precedence ---------- -Unary operators always bind stronger than any binary +Unary operators always bind stronger than any binary operator: ``$a + b`` is ``($a) + b`` and not ``$(a + b)``. -If an unary operator's first character is ``@`` it is a `sigil-like`:idx: +If an unary operator's first character is ``@`` it is a `sigil-like`:idx: operator which binds stronger than a ``primarySuffix``: ``@x.abc`` is parsed as ``(@x).abc`` whereas ``$x.abc`` is parsed as ``$(x.abc)``. @@ -34,7 +41,7 @@ following rules: Operators ending in either ``->``, ``~>`` or ``=>`` are called `arrow like`:idx:, and have the lowest precedence of all operators. -If the operator ends with ``=`` and its first character is none of +If the operator ends with ``=`` and its first character is none of ``<``, ``>``, ``!``, ``=``, ``~``, ``?``, it is an *assignment operator* which has the second lowest precedence. @@ -76,7 +83,7 @@ is still parsed as ``1 + (3 * 4)``, but ``1+3 * 4`` is parsed as ``(1+3) * 4``: Furthermore whether an operator is used a prefix operator is affected by the -number of spaces: +number of spaces: .. code-block:: nim #! strongSpaces From 4e129324f61bfff97fafc019e54809a84d85e9fe Mon Sep 17 00:00:00 2001 From: apense Date: Wed, 24 Jun 2015 23:56:35 -0400 Subject: [PATCH 0554/1263] Added example for var overloading Simple example to demonstrate overloading in case technical lingo is confusing --- doc/manual/type_rel.txt | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/doc/manual/type_rel.txt b/doc/manual/type_rel.txt index 5c8372e1e..97f7090b4 100644 --- a/doc/manual/type_rel.txt +++ b/doc/manual/type_rel.txt @@ -294,6 +294,21 @@ If the formal parameter ``f`` is of type ``var T`` in addition to the ordinary type checking, the argument is checked to be an `l-value`:idx:. ``var T`` matches better than just ``T`` then. +.. code-block:: nim + proc sayHi(x: int): string = + # matches a non-var int + result = $x + proc sayHi(x: var int): string = + # matches a var int + result = $(x + 10) + + proc sayHello(x: int) = + var m = x # a mutable version of x + echo sayHi(x) # matches the non-var version of sayHi + echo sayHi(m) # matches the var version of sayHi + + sayHello(3) # 3 + # 13 Automatic dereferencing ----------------------- From 1349687756ca1d43e03401868c870338d1090a26 Mon Sep 17 00:00:00 2001 From: apense Date: Thu, 25 Jun 2015 01:23:31 -0400 Subject: [PATCH 0555/1263] Minor object documentation additions --- doc/manual/types.txt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/doc/manual/types.txt b/doc/manual/types.txt index 81ae9d6b4..c8923bd44 100644 --- a/doc/manual/types.txt +++ b/doc/manual/types.txt @@ -575,6 +575,7 @@ the ``of`` operator can be used to determine the object's type. student: Student person: Person assert(student of Student) # is true + assert(student of Person) # also true Object fields that should be visible from outside the defining module, have to be marked by ``*``. In contrast to tuples, different object types are @@ -593,6 +594,7 @@ an ``object`` type or a ``ref object`` type: .. code-block:: nim var student = Student(name: "Anton", age: 5, id: 3) +Note that, unlike tuples, objects require the field names along with their values. For a ``ref object`` type ``system.new`` is invoked implicitly. From 47dce2688633fad840a2f5e4073c531f1cd640ca Mon Sep 17 00:00:00 2001 From: Araq Date: Thu, 25 Jun 2015 11:15:36 +0200 Subject: [PATCH 0556/1263] fixes #2985 --- compiler/semfold.nim | 3 +++ compiler/trees.nim | 12 ++++++++---- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/compiler/semfold.nim b/compiler/semfold.nim index b83641706..9a0c856dc 100644 --- a/compiler/semfold.nim +++ b/compiler/semfold.nim @@ -437,6 +437,9 @@ proc evalOp(m: TMagic, n, a, b, c: PNode): PNode = mNLen..mNError, mEqRef, mSlurp, mStaticExec, mNGenSym, mSpawn, mParallel, mPlugin: discard + of mEqProc: + result = newIntNodeT(ord( + exprStructuralEquivalent(a, b, strictSymEquality=true)), n) else: internalError(a.info, "evalOp(" & $m & ')') proc getConstIfExpr(c: PSym, n: PNode): PNode = diff --git a/compiler/trees.nim b/compiler/trees.nim index 2c631af99..659df334b 100644 --- a/compiler/trees.nim +++ b/compiler/trees.nim @@ -36,15 +36,18 @@ proc cyclicTree*(n: PNode): bool = var s = newNodeI(nkEmpty, n.info) result = cyclicTreeAux(n, s) -proc exprStructuralEquivalent*(a, b: PNode): bool = +proc exprStructuralEquivalent*(a, b: PNode; strictSymEquality=false): bool = result = false if a == b: result = true elif (a != nil) and (b != nil) and (a.kind == b.kind): case a.kind of nkSym: - # don't go nuts here: same symbol as string is enough: - result = a.sym.name.id == b.sym.name.id + if strictSymEquality: + result = a.sym == b.sym + else: + # don't go nuts here: same symbol as string is enough: + result = a.sym.name.id == b.sym.name.id of nkIdent: result = a.ident.id == b.ident.id of nkCharLit..nkInt64Lit: result = a.intVal == b.intVal of nkFloatLit..nkFloat64Lit: result = a.floatVal == b.floatVal @@ -53,7 +56,8 @@ proc exprStructuralEquivalent*(a, b: PNode): bool = else: if sonsLen(a) == sonsLen(b): for i in countup(0, sonsLen(a) - 1): - if not exprStructuralEquivalent(a.sons[i], b.sons[i]): return + if not exprStructuralEquivalent(a.sons[i], b.sons[i], + strictSymEquality): return result = true proc sameTree*(a, b: PNode): bool = From 2236a5be61632213025da37dda5cadb3d325fd8d Mon Sep 17 00:00:00 2001 From: Araq Date: Thu, 25 Jun 2015 11:17:01 +0200 Subject: [PATCH 0557/1263] VM: use stricter notion of equality for NimNode --- compiler/vm.nim | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/compiler/vm.nim b/compiler/vm.nim index 826356c68..23fd6c8b1 100644 --- a/compiler/vm.nim +++ b/compiler/vm.nim @@ -690,7 +690,8 @@ proc rawExecute(c: PCtx, start: int, tos: PStackFrame): TFullReg = of opcEqNimrodNode: decodeBC(rkInt) regs[ra].intVal = - ord(exprStructuralEquivalent(regs[rb].node, regs[rc].node)) + ord(exprStructuralEquivalent(regs[rb].node, regs[rc].node, + strictSymEquality=true)) of opcXor: decodeBC(rkInt) regs[ra].intVal = ord(regs[rb].intVal != regs[rc].intVal) From 396e69e39c339a02fcc57e9496db0907269d081d Mon Sep 17 00:00:00 2001 From: Araq Date: Thu, 25 Jun 2015 11:19:15 +0200 Subject: [PATCH 0558/1263] sorted contributing differently: most important stuff comes first; corrected its contents --- contributing.rst | 158 +++++++++++++++++++++-------------------------- 1 file changed, 72 insertions(+), 86 deletions(-) diff --git a/contributing.rst b/contributing.rst index dc77f0dbd..10f779cc1 100644 --- a/contributing.rst +++ b/contributing.rst @@ -1,73 +1,3 @@ -The Git stuff -============= - -General commit rules --------------------- - -1. All changes introduced by the commit (diff lines) must be related to the - subject of the commit. - - If you change some other unrelated to the subject parts of the file, because - your editor reformatted automatically the code or whatever different reason, - this should be excluded from the commit. - - *Tip:* Never commit everything as is using ``git commit -a``, but review - carefully your changes with ``git add -p``. - -2. Changes should not introduce any trailing whitespace. - - Always check your changes for whitespace errors using ``git diff --check`` - or add following ``pre-commit`` hook: - - .. code-block:: sh - - #!/bin/sh - git diff --check --cached || exit $? - - No sane programming or markup language cares about trailing whitespace, so - tailing whitespace is just a noise you should not introduce to the - repository. - -3. Describe your commit well following the 50/72 rule on commit messages: - - Start with the commit subject as single line maximum of 50 characters, - without trailing period, briefly describing the change. - - Optionally put the detailed description as a blocks of text wrapped to 72 - characters, separated by single blank line from the other parts (including - the subject). - -More information ----------------- - -For more information on how to produce great commits and describe them well read: - -* `How to Write a Git Commit Message `_ -* `A Note About Git Commit Messages `_ -* `Guide by github, scroll down a bit `_ - -Deprecation -=========== - -Backward compatibility is important, so if you are renaming a proc or -a type, you can use - - -.. code-block:: nim - - {.deprecated [oldName: new_name].} - -Or you can simply use - -.. code-block:: nim - - proc oldProc() {.deprecated.} - -to mark a symbol as deprecated. Works for procs/types/vars/consts, -etc. - -`Deprecated pragma in the manual. `_ - Writing tests ============= @@ -94,7 +24,8 @@ Sample test: seq2D[0][0] = true seq2D[1][0] = true seq2D[0][1] = true - doAssert seq2D == @[@[true, true], @[true, false], @[false, false], @[false, false]] + doAssert seq2D == @[@[true, true], @[true, false], + @[false, false], @[false, false]] Compiler -------- @@ -131,22 +62,20 @@ Running tests You can run the tests with -.. code-block:: bash - +:: ./koch tests which will run a good subset of tests. Some tests may fail. If you -only want to run failing tests, go for - -.. code-block:: bash +only want to see the output of failing tests, go for +:: ./koch tests --failing all -You can also run only a single category of tests. For a list of -categories, see ``tests/testament/categories.nim``, at the bottom. - -.. code-block:: bash +You can also run only a single category of tests. A category is a subdirectory +in the ``tests`` directory. There are a couple of special categories; for a +list of these, see ``tests/testament/categories.nim``, at the bottom. +:: ./koch tests c lib Comparing tests @@ -159,22 +88,79 @@ The tester can compare two test runs. First, you need to create the reference test. You'll also need to the commit id, because that's what the tester needs to know in order to compare the two. -.. code-block:: bash - +:: git checkout devel DEVEL_COMMIT=$(git rev-parse HEAD) ./koch tests Then switch over to your changes and run the tester again. -.. code-block:: bash - +:: git checkout your-changes ./koch tests Then you can ask the tester to create a ``testresults.html`` which will tell you if any new tests passed/failed. -.. code-block:: bash - +:: ./koch --print html $DEVEL_COMMIT + + +Deprecation +=========== + +Backward compatibility is important, so if you are renaming a proc or +a type, you can use + + +.. code-block:: nim + + {.deprecated: [oldName: new_name].} + +Or you can simply use + +.. code-block:: nim + + proc oldProc() {.deprecated.} + +to mark a symbol as deprecated. Works for procs/types/vars/consts, +etc. Note that currently the ``deprecated`` statement does not work well with +overloading so for routines the latter variant is better. + + +`Deprecated `_ +pragma in the manual. + + + +The Git stuff +============= + +General commit rules +-------------------- + +1. All changes introduced by the commit (diff lines) must be related to the + subject of the commit. + + If you change some other unrelated to the subject parts of the file, because + your editor reformatted automatically the code or whatever different reason, + this should be excluded from the commit. + + *Tip:* Never commit everything as is using ``git commit -a``, but review + carefully your changes with ``git add -p``. + +2. Changes should not introduce any trailing whitespace. + + Always check your changes for whitespace errors using ``git diff --check`` + or add following ``pre-commit`` hook: + + .. code-block:: sh + + #!/bin/sh + git diff --check --cached || exit $? + + No sane programming or markup language cares about trailing whitespace, so + tailing whitespace is just a noise you should not introduce to the + repository. + +3. Describe your commit and use your common sense. From 47658cd4263a41889540ebffa809e01cafe36eb5 Mon Sep 17 00:00:00 2001 From: Araq Date: Thu, 25 Jun 2015 11:30:03 +0200 Subject: [PATCH 0559/1263] fixes #2974 --- compiler/sigmatch.nim | 2 ++ contributing.rst => doc/contributing.rst | 0 2 files changed, 2 insertions(+) rename contributing.rst => doc/contributing.rst (100%) diff --git a/compiler/sigmatch.nim b/compiler/sigmatch.nim index cd6e1ff9a..40836a94d 100644 --- a/compiler/sigmatch.nim +++ b/compiler/sigmatch.nim @@ -1300,6 +1300,8 @@ proc paramTypesMatchAux(m: var TCandidate, f, argType: PType, of isInferred, isInferredConvertible: if arg.kind in {nkProcDef, nkIteratorDef} + nkLambdaKinds: result = c.semInferredLambda(c, m.bindings, arg) + elif arg.kind != nkSym: + return nil else: let inferred = c.semGenerateInstance(c, arg.sym, m.bindings, arg.info) result = newSymNode(inferred, arg.info) diff --git a/contributing.rst b/doc/contributing.rst similarity index 100% rename from contributing.rst rename to doc/contributing.rst From 6de5c1e86da46c9a1a5daaa7f5bbdccaf4b78542 Mon Sep 17 00:00:00 2001 From: Araq Date: Thu, 25 Jun 2015 13:13:33 +0200 Subject: [PATCH 0560/1263] fixes #2992 --- lib/system/repr.nim | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/system/repr.nim b/lib/system/repr.nim index 37056af3a..74396f424 100644 --- a/lib/system/repr.nim +++ b/lib/system/repr.nim @@ -142,7 +142,7 @@ when not defined(useNimRtl): proc deinitReprClosure(cl: var ReprClosure) = when declared(CellSet): deinit(cl.marked) - when hasThreadSupport and hasSharedHeap and declared(heapLock): + when hasThreadSupport and hasSharedHeap and declared(heapLock): ReleaseSys(HeapLock) proc reprBreak(result: var string, cl: ReprClosure) = @@ -196,7 +196,7 @@ when not defined(useNimRtl): add result, "[" var curTyp = typ var first = true - while curTyp.base != nil: + while curTyp != nil: var part = "" reprRecordAux(part, p, curTyp.node, cl) if part.len > 0: @@ -232,7 +232,7 @@ when not defined(useNimRtl): of tySet: reprSetAux(result, p, typ) of tyArray, tyArrayConstr: reprArray(result, p, typ, cl) of tyTuple: reprRecord(result, p, typ, cl) - of tyObject: + of tyObject: var t = cast[ptr PNimType](p)[] reprRecord(result, p, t, cl) of tyRef, tyPtr: @@ -248,7 +248,7 @@ when not defined(useNimRtl): of tyInt64: add result, $(cast[ptr int64](p)[]) of tyUInt8: add result, $ze(cast[ptr int8](p)[]) of tyUInt16: add result, $ze(cast[ptr int16](p)[]) - + of tyFloat: add result, $(cast[ptr float](p)[]) of tyFloat32: add result, $(cast[ptr float32](p)[]) of tyFloat64: add result, $(cast[ptr float64](p)[]) From db42813a9f62743ee61a768e94dcb2f0fcf89466 Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Thu, 25 Jun 2015 16:33:21 -0500 Subject: [PATCH 0561/1263] symlinked contributing guide to root for github --- contributing.rst | 1 + 1 file changed, 1 insertion(+) create mode 120000 contributing.rst diff --git a/contributing.rst b/contributing.rst new file mode 120000 index 000000000..fc66fcc90 --- /dev/null +++ b/contributing.rst @@ -0,0 +1 @@ +doc/contributing.rst \ No newline at end of file From 6109e6a999c0f70b22e84b5ac412f97efc153367 Mon Sep 17 00:00:00 2001 From: Dominik Picheta Date: Thu, 25 Jun 2015 22:36:53 +0100 Subject: [PATCH 0562/1263] Fixes net/asyncdispatch on Windows. Ref #2976. Fixes #2996. --- lib/pure/asyncdispatch.nim | 4 +- lib/pure/rawsockets.nim | 99 +++++++++++++++++++++----------------- lib/windows/winlean.nim | 3 ++ 3 files changed, 59 insertions(+), 47 deletions(-) diff --git a/lib/pure/asyncdispatch.nim b/lib/pure/asyncdispatch.nim index 5a059ec8e..547880f06 100644 --- a/lib/pure/asyncdispatch.nim +++ b/lib/pure/asyncdispatch.nim @@ -483,7 +483,7 @@ when defined(windows) or defined(nimdoc): RemoteSockaddr, RemoteSockaddrLength) proc connect*(socket: AsyncFD, address: string, port: Port, - af = AF_INET): Future[void] = + af = rawsockets.AF_INET): Future[void] = ## Connects ``socket`` to server at ``address:port``. ## ## Returns a ``Future`` which will complete when the connection succeeds @@ -861,7 +861,7 @@ when defined(windows) or defined(nimdoc): result.SocketHandle.setBlocking(false) register(result) - proc newAsyncRawSocket*(domain: Domain = AF_INET, + proc newAsyncRawSocket*(domain: Domain = rawsockets.AF_INET, typ: SockType = SOCK_STREAM, protocol: Protocol = IPPROTO_TCP): AsyncFD = ## Creates a new socket and registers it with the dispatcher implicitly. diff --git a/lib/pure/rawsockets.nim b/lib/pure/rawsockets.nim index 9bfe9dab5..bd22af2d1 100644 --- a/lib/pure/rawsockets.nim +++ b/lib/pure/rawsockets.nim @@ -27,9 +27,10 @@ else: import posix export fcntl, F_GETFL, O_NONBLOCK, F_SETFL, EAGAIN, EWOULDBLOCK, MSG_NOSIGNAL, EINTR, EINPROGRESS, ECONNRESET, EPIPE, ENETRESET + export Sockaddr_storage export SocketHandle, Sockaddr_in, Addrinfo, INADDR_ANY, SockAddr, SockLen, - Sockaddr_in6, Sockaddr_storage, + Sockaddr_in6, inet_ntoa, recv, `==`, connect, send, accept, recvfrom, sendto export @@ -45,7 +46,7 @@ when defined(macosx): type Port* = distinct uint16 ## port type - + Domain* = enum ## domain, which specifies the protocol family of the ## created socket. Other domains than those that are listed ## here are unsupported. @@ -60,7 +61,7 @@ type SOCK_SEQPACKET = 5 ## reliable sequenced packet service Protocol* = enum ## third argument to `socket` proc - IPPROTO_TCP = 6, ## Transmission control protocol. + IPPROTO_TCP = 6, ## Transmission control protocol. IPPROTO_UDP = 17, ## User datagram protocol. IPPROTO_IP, ## Internet protocol. Unsupported on Windows. IPPROTO_IPV6, ## Internet Protocol Version 6. Unsupported on Windows. @@ -90,15 +91,19 @@ when useWinVersion: const IOCPARM_MASK* = 127 IOC_IN* = int(-2147483648) - FIONBIO* = IOC_IN.int32 or ((sizeof(int32) and IOCPARM_MASK) shl 16) or + FIONBIO* = IOC_IN.int32 or ((sizeof(int32) and IOCPARM_MASK) shl 16) or (102 shl 8) or 126 + rawAfInet = winlean.AF_INET + rawAfInet6 = winlean.AF_INET6 - proc ioctlsocket*(s: SocketHandle, cmd: clong, + proc ioctlsocket*(s: SocketHandle, cmd: clong, argptr: ptr clong): cint {. stdcall, importc: "ioctlsocket", dynlib: "ws2_32.dll".} else: let osInvalidSocket* = posix.INVALID_SOCKET + rawAfInet = posix.AF_INET + rawAfInet6 = posix.AF_INET6 proc `==`*(a, b: Port): bool {.borrow.} ## ``==`` for ports. @@ -142,12 +147,12 @@ when not useWinVersion: else: discard else: - proc toInt(domain: Domain): cint = + proc toInt(domain: Domain): cint = result = toU16(ord(domain)) proc toInt(typ: SockType): cint = result = cint(ord(typ)) - + proc toInt(p: Protocol): cint = result = cint(ord(p)) @@ -177,8 +182,8 @@ proc bindAddr*(socket: SocketHandle, name: ptr SockAddr, namelen: SockLen): cint result = bindSocket(socket, name, namelen) proc listen*(socket: SocketHandle, backlog = SOMAXCONN): cint {.tags: [ReadIOEffect].} = - ## Marks ``socket`` as accepting connections. - ## ``Backlog`` specifies the maximum length of the + ## Marks ``socket`` as accepting connections. + ## ``Backlog`` specifies the maximum length of the ## queue of pending connections. when useWinVersion: result = winlean.listen(socket, cint(backlog)) @@ -195,7 +200,7 @@ proc getAddrInfo*(address: string, port: Port, af: Domain = AF_INET, typ: SockTy hints.ai_family = toInt(af) hints.ai_socktype = toInt(typ) hints.ai_protocol = toInt(prot) - hints.ai_flags = posix.AI_V4MAPPED + hints.ai_flags = AI_V4MAPPED var gaiResult = getaddrinfo(address, $port, addr(hints), result) if gaiResult != 0'i32: when useWinVersion: @@ -206,7 +211,7 @@ proc getAddrInfo*(address: string, port: Port, af: Domain = AF_INET, typ: SockTy proc dealloc*(ai: ptr AddrInfo) = freeaddrinfo(ai) -proc ntohl*(x: int32): int32 = +proc ntohl*(x: int32): int32 = ## Converts 32-bit integers from network to host byte order. ## On machines where the host byte order is the same as network byte order, ## this is a no-op; otherwise, it performs a 4-byte swap operation. @@ -236,7 +241,7 @@ proc htons*(x: int16): int16 = result = rawsockets.ntohs(x) proc getServByName*(name, proto: string): Servent {.tags: [ReadIOEffect].} = - ## Searches the database from the beginning and finds the first entry for + ## Searches the database from the beginning and finds the first entry for ## which the service name specified by ``name`` matches the s_name member ## and the protocol name specified by ``proto`` matches the s_proto member. ## @@ -250,10 +255,10 @@ proc getServByName*(name, proto: string): Servent {.tags: [ReadIOEffect].} = result.aliases = cstringArrayToSeq(s.s_aliases) result.port = Port(s.s_port) result.proto = $s.s_proto - -proc getServByPort*(port: Port, proto: string): Servent {.tags: [ReadIOEffect].} = - ## Searches the database from the beginning and finds the first entry for - ## which the port specified by ``port`` matches the s_port member and the + +proc getServByPort*(port: Port, proto: string): Servent {.tags: [ReadIOEffect].} = + ## Searches the database from the beginning and finds the first entry for + ## which the port specified by ``port`` matches the s_port member and the ## protocol name specified by ``proto`` matches the s_proto member. ## ## On posix this will search through the ``/etc/services`` file. @@ -271,17 +276,17 @@ proc getHostByAddr*(ip: string): Hostent {.tags: [ReadIOEffect].} = ## This function will lookup the hostname of an IP Address. var myaddr: InAddr myaddr.s_addr = inet_addr(ip) - + when useWinVersion: var s = winlean.gethostbyaddr(addr(myaddr), sizeof(myaddr).cuint, cint(rawsockets.AF_INET)) if s == nil: raiseOSError(osLastError()) else: - var s = posix.gethostbyaddr(addr(myaddr), sizeof(myaddr).Socklen, + var s = posix.gethostbyaddr(addr(myaddr), sizeof(myaddr).Socklen, cint(posix.AF_INET)) if s == nil: raise newException(OSError, $hstrerror(h_errno)) - + result.name = $s.h_name result.aliases = cstringArrayToSeq(s.h_aliases) when useWinVersion: @@ -296,7 +301,7 @@ proc getHostByAddr*(ip: string): Hostent {.tags: [ReadIOEffect].} = result.addrList = cstringArrayToSeq(s.h_addr_list) result.length = int(s.h_length) -proc getHostByName*(name: string): Hostent {.tags: [ReadIOEffect].} = +proc getHostByName*(name: string): Hostent {.tags: [ReadIOEffect].} = ## This function will lookup the IP address of a hostname. when useWinVersion: var s = winlean.gethostbyname(name) @@ -324,9 +329,9 @@ proc getSockDomain*(socket: SocketHandle): Domain = if getsockname(socket, cast[ptr SockAddr](addr(name)), addr(namelen)) == -1'i32: raiseOSError(osLastError()) - if name.sa_family == posix.AF_INET: + if name.sa_family == rawAfInet: result = AF_INET - elif name.sa_family == posix.AF_INET6: + elif name.sa_family == rawAfInet6: result = AF_INET6 else: raise newException(OSError, "unknown socket family in getSockFamily") @@ -334,19 +339,23 @@ proc getSockDomain*(socket: SocketHandle): Domain = proc getAddrString*(sockAddr: ptr SockAddr): string = ## return the string representation of address within sockAddr - if sockAddr.sa_family == posix.AF_INET: + if sockAddr.sa_family == rawAfInet: result = $inet_ntoa(cast[ptr Sockaddr_in](sockAddr).sin_addr) - elif sockAddr.sa_family == posix.AF_INET6: - var v6addr = cast[ptr Sockaddr_in6](sockAddr).sin6_addr - result = newString(posix.INET6_ADDRSTRLEN) - discard posix.inet_ntop(posix.AF_INET6, addr cast[ptr Sockaddr_in6](sockAddr).sin6_addr, result.cstring, result.len.int32) - if posix.IN6_IS_ADDR_V4MAPPED(addr cast[ptr Sockaddr_in6](sockAddr).sin6_addr) != 0: - result = result.substr("::ffff:".len) + elif sockAddr.sa_family == rawAfInet6: + when not useWinVersion: + # TODO: Windows + var v6addr = cast[ptr Sockaddr_in6](sockAddr).sin6_addr + result = newString(posix.INET6_ADDRSTRLEN) + let addr6 = addr cast[ptr Sockaddr_in6](sockAddr).sin6_addr + discard posix.inet_ntop(posix.AF_INET6, addr6, result.cstring, + result.len.int32) + if posix.IN6_IS_ADDR_V4MAPPED(addr6) != 0: + result = result.substr("::ffff:".len) else: raise newException(OSError, "unknown socket family in getAddrString") -proc getSockName*(socket: SocketHandle): Port = +proc getSockName*(socket: SocketHandle): Port = ## returns the socket's associated port number. var name: Sockaddr_in when useWinVersion: @@ -362,11 +371,11 @@ proc getSockName*(socket: SocketHandle): Port = result = Port(rawsockets.ntohs(name.sin_port)) proc getSockOptInt*(socket: SocketHandle, level, optname: int): int {. - tags: [ReadIOEffect].} = + tags: [ReadIOEffect].} = ## getsockopt for integer options. var res: cint var size = sizeof(res).SockLen - if getsockopt(socket, cint(level), cint(optname), + if getsockopt(socket, cint(level), cint(optname), addr(res), addr(size)) < 0'i32: raiseOSError(osLastError()) result = int(res) @@ -375,7 +384,7 @@ proc setSockOptInt*(socket: SocketHandle, level, optname, optval: int) {. tags: [WriteIOEffect].} = ## setsockopt for integer options. var value = cint(optval) - if setsockopt(socket, cint(level), cint(optname), addr(value), + if setsockopt(socket, cint(level), cint(optname), addr(value), sizeof(value).SockLen) < 0'i32: raiseOSError(osLastError()) @@ -402,13 +411,13 @@ proc timeValFromMilliseconds(timeout = 500): Timeval = result.tv_sec = seconds.int32 result.tv_usec = ((timeout - seconds * 1000) * 1000).int32 -proc createFdSet(fd: var TFdSet, s: seq[SocketHandle], m: var int) = +proc createFdSet(fd: var TFdSet, s: seq[SocketHandle], m: var int) = FD_ZERO(fd) - for i in items(s): + for i in items(s): m = max(m, int(i)) FD_SET(i, fd) - -proc pruneSocketSet(s: var seq[SocketHandle], fd: var TFdSet) = + +proc pruneSocketSet(s: var seq[SocketHandle], fd: var TFdSet) = var i = 0 var L = s.len while i < L: @@ -422,22 +431,22 @@ proc pruneSocketSet(s: var seq[SocketHandle], fd: var TFdSet) = proc select*(readfds: var seq[SocketHandle], timeout = 500): int = ## Traditional select function. This function will return the number of ## sockets that are ready to be read from, written to, or which have errors. - ## If there are none; 0 is returned. + ## If there are none; 0 is returned. ## ``Timeout`` is in milliseconds and -1 can be specified for no timeout. - ## + ## ## A socket is removed from the specific ``seq`` when it has data waiting to ## be read/written to or has errors (``exceptfds``). var tv {.noInit.}: Timeval = timeValFromMilliseconds(timeout) - + var rd: TFdSet var m = 0 createFdSet((rd), readfds, m) - + if timeout != -1: result = int(select(cint(m+1), addr(rd), nil, nil, addr(tv))) else: result = int(select(cint(m+1), addr(rd), nil, nil, nil)) - + pruneSocketSet(readfds, (rd)) proc selectWrite*(writefds: var seq[SocketHandle], @@ -450,16 +459,16 @@ proc selectWrite*(writefds: var seq[SocketHandle], ## ``timeout`` is specified in milliseconds and ``-1`` can be specified for ## an unlimited time. var tv {.noInit.}: Timeval = timeValFromMilliseconds(timeout) - + var wr: TFdSet var m = 0 createFdSet((wr), writefds, m) - + if timeout != -1: result = int(select(cint(m+1), nil, addr(wr), nil, addr(tv))) else: result = int(select(cint(m+1), nil, addr(wr), nil, nil)) - + pruneSocketSet(writefds, (wr)) when defined(Windows): diff --git a/lib/windows/winlean.nim b/lib/windows/winlean.nim index 9f04bab35..24015dd3a 100644 --- a/lib/windows/winlean.nim +++ b/lib/windows/winlean.nim @@ -723,6 +723,9 @@ template WSAIORW*(x,y): expr = (IOC_INOUT or x or y) const SIO_GET_EXTENSION_FUNCTION_POINTER* = WSAIORW(IOC_WS2,6).DWORD SO_UPDATE_ACCEPT_CONTEXT* = 0x700B + AI_V4MAPPED* = 0x0008 + AF_INET* = 2 + AF_INET6* = 23 var WSAID_CONNECTEX*: GUID = GUID(D1: 0x25a207b9, D2: 0xddf3'i16, D3: 0x4660, D4: [ From 57964a0ef2da9457783f6a4ea728dcea80df9a12 Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Thu, 25 Jun 2015 16:39:27 -0500 Subject: [PATCH 0563/1263] moved contributing guide back to root "I don't want symlinks, symlinks suck, they turn an acylic tree into an acyclic graph." --- contributing.rst | 167 ++++++++++++++++++++++++++++++++++++++++++- doc/contributing.rst | 166 ------------------------------------------ 2 files changed, 166 insertions(+), 167 deletions(-) mode change 120000 => 100644 contributing.rst delete mode 100644 doc/contributing.rst diff --git a/contributing.rst b/contributing.rst deleted file mode 120000 index fc66fcc90..000000000 --- a/contributing.rst +++ /dev/null @@ -1 +0,0 @@ -doc/contributing.rst \ No newline at end of file diff --git a/contributing.rst b/contributing.rst new file mode 100644 index 000000000..10f779cc1 --- /dev/null +++ b/contributing.rst @@ -0,0 +1,166 @@ +Writing tests +============= + +Not all the tests follow this scheme, feel free to change the ones +that don't. Always leave the code cleaner than you found it. + +Stdlib +------ + +If you change the stdlib (anything under ``lib/``), put a test in the +file you changed. Add the tests under an ``when isMainModule:`` +condition so they only get executed when the tester is building the +file. Each test should be in a separate ``block:`` statement, such that +each has its own scope. Use boolean conditions and ``doAssert`` for the +testing by itself, don't rely on echo statements or similar. + +Sample test: + +.. code-block:: nim + + when isMainModule: + block: # newSeqWith tests + var seq2D = newSeqWith(4, newSeq[bool](2)) + seq2D[0][0] = true + seq2D[1][0] = true + seq2D[0][1] = true + doAssert seq2D == @[@[true, true], @[true, false], + @[false, false], @[false, false]] + +Compiler +-------- + +The tests for the compiler work differently, they are all located in +``tests/``. Each test has its own file, which is different from the +stdlib tests. At the beginning of every test is the expected side of +the test. Possible keys are: + +- output: The expected output, most likely via ``echo`` +- exitcode: Exit code of the test (via ``exit(number)``) +- errormsg: The expected error message +- file: The file the errormsg +- line: The line the errormsg was produced at + +An example for a test: + +.. code-block:: nim + + discard """ + errormsg: "type mismatch: got (PTest)" + """ + + type + PTest = ref object + + proc test(x: PTest, y: int) = nil + + var buf: PTest + buf.test() + +Running tests +============= + +You can run the tests with + +:: + ./koch tests + +which will run a good subset of tests. Some tests may fail. If you +only want to see the output of failing tests, go for + +:: + ./koch tests --failing all + +You can also run only a single category of tests. A category is a subdirectory +in the ``tests`` directory. There are a couple of special categories; for a +list of these, see ``tests/testament/categories.nim``, at the bottom. + +:: + ./koch tests c lib + +Comparing tests +=============== + +Because some tests fail in the current ``devel`` branch, not every fail +after your change is necessarily caused by your changes. + +The tester can compare two test runs. First, you need to create the +reference test. You'll also need to the commit id, because that's what +the tester needs to know in order to compare the two. + +:: + git checkout devel + DEVEL_COMMIT=$(git rev-parse HEAD) + ./koch tests + +Then switch over to your changes and run the tester again. + +:: + git checkout your-changes + ./koch tests + +Then you can ask the tester to create a ``testresults.html`` which will +tell you if any new tests passed/failed. + +:: + ./koch --print html $DEVEL_COMMIT + + +Deprecation +=========== + +Backward compatibility is important, so if you are renaming a proc or +a type, you can use + + +.. code-block:: nim + + {.deprecated: [oldName: new_name].} + +Or you can simply use + +.. code-block:: nim + + proc oldProc() {.deprecated.} + +to mark a symbol as deprecated. Works for procs/types/vars/consts, +etc. Note that currently the ``deprecated`` statement does not work well with +overloading so for routines the latter variant is better. + + +`Deprecated `_ +pragma in the manual. + + + +The Git stuff +============= + +General commit rules +-------------------- + +1. All changes introduced by the commit (diff lines) must be related to the + subject of the commit. + + If you change some other unrelated to the subject parts of the file, because + your editor reformatted automatically the code or whatever different reason, + this should be excluded from the commit. + + *Tip:* Never commit everything as is using ``git commit -a``, but review + carefully your changes with ``git add -p``. + +2. Changes should not introduce any trailing whitespace. + + Always check your changes for whitespace errors using ``git diff --check`` + or add following ``pre-commit`` hook: + + .. code-block:: sh + + #!/bin/sh + git diff --check --cached || exit $? + + No sane programming or markup language cares about trailing whitespace, so + tailing whitespace is just a noise you should not introduce to the + repository. + +3. Describe your commit and use your common sense. diff --git a/doc/contributing.rst b/doc/contributing.rst deleted file mode 100644 index 10f779cc1..000000000 --- a/doc/contributing.rst +++ /dev/null @@ -1,166 +0,0 @@ -Writing tests -============= - -Not all the tests follow this scheme, feel free to change the ones -that don't. Always leave the code cleaner than you found it. - -Stdlib ------- - -If you change the stdlib (anything under ``lib/``), put a test in the -file you changed. Add the tests under an ``when isMainModule:`` -condition so they only get executed when the tester is building the -file. Each test should be in a separate ``block:`` statement, such that -each has its own scope. Use boolean conditions and ``doAssert`` for the -testing by itself, don't rely on echo statements or similar. - -Sample test: - -.. code-block:: nim - - when isMainModule: - block: # newSeqWith tests - var seq2D = newSeqWith(4, newSeq[bool](2)) - seq2D[0][0] = true - seq2D[1][0] = true - seq2D[0][1] = true - doAssert seq2D == @[@[true, true], @[true, false], - @[false, false], @[false, false]] - -Compiler --------- - -The tests for the compiler work differently, they are all located in -``tests/``. Each test has its own file, which is different from the -stdlib tests. At the beginning of every test is the expected side of -the test. Possible keys are: - -- output: The expected output, most likely via ``echo`` -- exitcode: Exit code of the test (via ``exit(number)``) -- errormsg: The expected error message -- file: The file the errormsg -- line: The line the errormsg was produced at - -An example for a test: - -.. code-block:: nim - - discard """ - errormsg: "type mismatch: got (PTest)" - """ - - type - PTest = ref object - - proc test(x: PTest, y: int) = nil - - var buf: PTest - buf.test() - -Running tests -============= - -You can run the tests with - -:: - ./koch tests - -which will run a good subset of tests. Some tests may fail. If you -only want to see the output of failing tests, go for - -:: - ./koch tests --failing all - -You can also run only a single category of tests. A category is a subdirectory -in the ``tests`` directory. There are a couple of special categories; for a -list of these, see ``tests/testament/categories.nim``, at the bottom. - -:: - ./koch tests c lib - -Comparing tests -=============== - -Because some tests fail in the current ``devel`` branch, not every fail -after your change is necessarily caused by your changes. - -The tester can compare two test runs. First, you need to create the -reference test. You'll also need to the commit id, because that's what -the tester needs to know in order to compare the two. - -:: - git checkout devel - DEVEL_COMMIT=$(git rev-parse HEAD) - ./koch tests - -Then switch over to your changes and run the tester again. - -:: - git checkout your-changes - ./koch tests - -Then you can ask the tester to create a ``testresults.html`` which will -tell you if any new tests passed/failed. - -:: - ./koch --print html $DEVEL_COMMIT - - -Deprecation -=========== - -Backward compatibility is important, so if you are renaming a proc or -a type, you can use - - -.. code-block:: nim - - {.deprecated: [oldName: new_name].} - -Or you can simply use - -.. code-block:: nim - - proc oldProc() {.deprecated.} - -to mark a symbol as deprecated. Works for procs/types/vars/consts, -etc. Note that currently the ``deprecated`` statement does not work well with -overloading so for routines the latter variant is better. - - -`Deprecated `_ -pragma in the manual. - - - -The Git stuff -============= - -General commit rules --------------------- - -1. All changes introduced by the commit (diff lines) must be related to the - subject of the commit. - - If you change some other unrelated to the subject parts of the file, because - your editor reformatted automatically the code or whatever different reason, - this should be excluded from the commit. - - *Tip:* Never commit everything as is using ``git commit -a``, but review - carefully your changes with ``git add -p``. - -2. Changes should not introduce any trailing whitespace. - - Always check your changes for whitespace errors using ``git diff --check`` - or add following ``pre-commit`` hook: - - .. code-block:: sh - - #!/bin/sh - git diff --check --cached || exit $? - - No sane programming or markup language cares about trailing whitespace, so - tailing whitespace is just a noise you should not introduce to the - repository. - -3. Describe your commit and use your common sense. From e273c00431dcbe78374d9a625dc4010367919d40 Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Thu, 25 Jun 2015 16:50:37 -0500 Subject: [PATCH 0564/1263] trimmed the contributing guide --- contributing.rst | 4 ---- 1 file changed, 4 deletions(-) diff --git a/contributing.rst b/contributing.rst index 10f779cc1..3a028fae6 100644 --- a/contributing.rst +++ b/contributing.rst @@ -159,8 +159,4 @@ General commit rules #!/bin/sh git diff --check --cached || exit $? - No sane programming or markup language cares about trailing whitespace, so - tailing whitespace is just a noise you should not introduce to the - repository. - 3. Describe your commit and use your common sense. From afad61c220280ef6ab6362dc5cadbab8ab0b20fc Mon Sep 17 00:00:00 2001 From: Araq Date: Fri, 26 Jun 2015 00:05:14 +0200 Subject: [PATCH 0565/1263] fixes #2731 --- compiler/semexprs.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/semexprs.nim b/compiler/semexprs.nim index cd6ba3753..45f6f04f9 100644 --- a/compiler/semexprs.nim +++ b/compiler/semexprs.nim @@ -474,7 +474,7 @@ proc changeType(n: PNode, newType: PType, check: bool) = addSon(a, m) changeType(m, tup.sons[i], check) of nkCharLit..nkUInt64Lit: - if check: + if check and n.kind != nkUInt64Lit: let value = n.intVal if value < firstOrd(newType) or value > lastOrd(newType): localError(n.info, errGenerated, "cannot convert " & $value & From db369cf65d689d1f1eec4524f154c897332dc2ba Mon Sep 17 00:00:00 2001 From: apense Date: Thu, 25 Jun 2015 20:32:10 -0400 Subject: [PATCH 0566/1263] Slight documentation addition Added a few type explanations Also docs for `==` and some examples. I'm not sure my explanation of `Ordinal[T]` is correct. It sounds the same as `SomeOrdinal` would be. --- lib/system.nim | 41 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 38 insertions(+), 3 deletions(-) diff --git a/lib/system.nim b/lib/system.nim index 34531eb46..efe557359 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -65,7 +65,11 @@ const {.push hints: off.} type - Ordinal* {.magic: Ordinal.}[T] + Ordinal* {.magic: Ordinal.}[T] ## Generic ordinal type. Includes integer, + ## bool, character, and enumeration types + ## as well as their subtypes. Note `uint` + ## and `uint64` are not ordinal types for + ## implementation reasons `ptr`* {.magic: Pointer.}[T] ## built-in generic untraced pointer type `ref`* {.magic: Pointer.}[T] ## built-in generic traced pointer type @@ -74,8 +78,8 @@ type stmt* {.magic: Stmt.} ## meta type to denote a statement (for templates) typedesc* {.magic: TypeDesc.} ## meta type to denote a type description void* {.magic: "VoidType".} ## meta type to denote the absence of any type - auto* = expr - any* = distinct auto + auto* = expr ## meta type for automatic type determination + any* = distinct auto ## meta type for any supported type untyped* {.magic: Expr.} ## meta type to denote an expression that ## is not resolved (for templates) typed* {.magic: Stmt.} ## meta type to denote an expression that @@ -250,15 +254,46 @@ when defined(nimNewShared): # comparison operators: proc `==` *[Enum: enum](x, y: Enum): bool {.magic: "EqEnum", noSideEffect.} + ## Checks whether values within the *same enum* have the same underlying value + ## + ## .. code-block:: nim + ## type + ## Enum1 = enum + ## Field1 = 3, Field2 + ## Enum2 = enum + ## Place1, Place2 = 3 + ## var + ## e1 = Field1 + ## e2 = Enum1(Place2) + ## echo (e1 == e2) # true + ## echo (e1 == Place2) # raises error proc `==` *(x, y: pointer): bool {.magic: "EqRef", noSideEffect.} + ## .. code-block:: nim + ## var # this is a wildly dangerous example + ## a = cast[pointer](0) + ## b = cast[pointer](nil) + ## echo (a == b) # true due to the special meaning of `nil`/0 as a pointer proc `==` *(x, y: string): bool {.magic: "EqStr", noSideEffect.} + ## Checks for equality between two `string` variables proc `==` *(x, y: cstring): bool {.magic: "EqCString", noSideEffect.} + ## Checks for equality between two `cstring` variables proc `==` *(x, y: char): bool {.magic: "EqCh", noSideEffect.} + ## Checks for equality between two `char` variables proc `==` *(x, y: bool): bool {.magic: "EqB", noSideEffect.} + ## Checks for equality between two `bool` variables proc `==` *[T](x, y: set[T]): bool {.magic: "EqSet", noSideEffect.} + ## Checks for equality between two variables of type `set1 + ## + ## .. code-block:: nim + ## var a = {1, 2, 2, 3} # duplication in sets is ignored + ## var b = {1, 2, 3} + ## echo (a == b) # true proc `==` *[T](x, y: ref T): bool {.magic: "EqRef", noSideEffect.} + ## Checks that two `ref` variables refer to the same item proc `==` *[T](x, y: ptr T): bool {.magic: "EqRef", noSideEffect.} + ## Checks that two `ptr` variables refer to the same item proc `==` *[T: proc](x, y: T): bool {.magic: "EqProc", noSideEffect.} + ## Checks that two `proc` variables refer to the same procedure proc `<=` *[Enum: enum](x, y: Enum): bool {.magic: "LeEnum", noSideEffect.} proc `<=` *(x, y: string): bool {.magic: "LeStr", noSideEffect.} From 8a042d8458d22c21f9015098046fa5278638ec58 Mon Sep 17 00:00:00 2001 From: apense Date: Thu, 25 Jun 2015 21:04:34 -0400 Subject: [PATCH 0567/1263] Added `$` documentation to the manual It's mentioned for enums, for exmplae, but it should probably be explicit in the string section --- doc/manual/types.txt | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/doc/manual/types.txt b/doc/manual/types.txt index c8923bd44..1d120c607 100644 --- a/doc/manual/types.txt +++ b/doc/manual/types.txt @@ -342,6 +342,34 @@ builtin ``len`` procedure; the length never counts the terminating zero. The assignment operator for strings always copies the string. The ``&`` operator concatenates strings. +Most native Nim types support conversion to strings with the special ``$`` proc. +When calling the ``echo`` proc, for example, the built-in stringify operation +for the parameter is called: + +.. code-block:: nim + + echo 3 # calls `$` for `int` + +Whenever a user creates a specialized object, implementation of this procedure +provides for ``string`` representation. + +.. code-block:: nim + type + Person = object + name: string + age: int + + proc `$`(p: Person): string = # `$` always returns a string + result = p.name & " is " & + $p.age & # we *need* the `$` in front of p.age, which + # is natively an integer, to convert it to + # a string + " years old." + +While ``$p.name`` can also be used, the ``$`` operation on a string does +nothing. Note that we cannot rely on automatic conversion from an ``int`` to +a ``string`` like we can for the ``echo`` proc. + Strings are compared by their lexicographical order. All comparison operators are available. Strings can be indexed like arrays (lower bound is 0). Unlike arrays, they can be used in case statements: From f9d8d6ce09ac345e0c1194b12031944a3949c7dd Mon Sep 17 00:00:00 2001 From: Sergey Avseyev Date: Thu, 25 Jun 2015 21:17:57 +0300 Subject: [PATCH 0568/1263] Trim trailling spaces --- lib/pure/dynlib.nim | 12 +++---- lib/system/dyncalls.nim | 5 ++- lib/system/threads.nim | 71 ++++++++++++++++++++--------------------- 3 files changed, 43 insertions(+), 45 deletions(-) diff --git a/lib/pure/dynlib.nim b/lib/pure/dynlib.nim index c6794be67..80fdc9dbc 100644 --- a/lib/pure/dynlib.nim +++ b/lib/pure/dynlib.nim @@ -8,8 +8,8 @@ # ## This module implements the ability to access symbols from shared -## libraries. On POSIX this uses the ``dlsym`` mechanism, on -## Windows ``LoadLibrary``. +## libraries. On POSIX this uses the ``dlsym`` mechanism, on +## Windows ``LoadLibrary``. type LibHandle* = pointer ## a handle to a dynamically loaded library @@ -17,11 +17,11 @@ type {.deprecated: [TLibHandle: LibHandle].} proc loadLib*(path: string, global_symbols=false): LibHandle - ## loads a library from `path`. Returns nil if the library could not + ## loads a library from `path`. Returns nil if the library could not ## be loaded. proc loadLib*(): LibHandle - ## gets the handle from the current executable. Returns nil if the + ## gets the handle from the current executable. Returns nil if the ## library could not be loaded. proc unloadLib*(lib: LibHandle) @@ -63,13 +63,13 @@ when defined(posix): proc dlsym(lib: LibHandle, name: cstring): pointer {. importc, header: "".} - proc loadLib(path: string, global_symbols=false): LibHandle = + proc loadLib(path: string, global_symbols=false): LibHandle = var flags = RTLD_NOW if global_symbols: flags = flags or RTLD_GLOBAL return dlopen(path, flags) proc loadLib(): LibHandle = return dlopen(nil, RTLD_NOW) proc unloadLib(lib: LibHandle) = dlclose(lib) - proc symAddr(lib: LibHandle, name: cstring): pointer = + proc symAddr(lib: LibHandle, name: cstring): pointer = return dlsym(lib, name) elif defined(windows) or defined(dos): diff --git a/lib/system/dyncalls.nim b/lib/system/dyncalls.nim index 8ef583482..fe98b1e6f 100644 --- a/lib/system/dyncalls.nim +++ b/lib/system/dyncalls.nim @@ -17,7 +17,7 @@ const NilLibHandle: LibHandle = nil -proc rawWrite(f: File, s: string) = +proc rawWrite(f: File, s: string) = # we cannot throw an exception here! discard writeBuffer(f, cstring(s), s.len) @@ -145,6 +145,5 @@ elif defined(mac): else: {.error: "no implementation for dyncalls".} - -{.pop.} +{.pop.} diff --git a/lib/system/threads.nim b/lib/system/threads.nim index d77059f68..1ec9aadf1 100644 --- a/lib/system/threads.nim +++ b/lib/system/threads.nim @@ -11,7 +11,7 @@ ## Do not import it directly. To activate thread support you need to compile ## with the ``--threads:on`` command line switch. ## -## Nim's memory model for threads is quite different from other common +## Nim's memory model for threads is quite different from other common ## programming languages (C, Pascal): Each thread has its own ## (garbage collected) heap and sharing of memory is restricted. This helps ## to prevent race conditions and improves efficiency. See `the manual for @@ -26,7 +26,7 @@ ## var ## thr: array [0..4, Thread[tuple[a,b: int]]] ## L: Lock -## +## ## proc threadFunc(interval: tuple[a,b: int]) {.thread.} = ## for i in interval.a..interval.b: ## acquire(L) # lock stdout @@ -38,8 +38,8 @@ ## for i in 0..high(thr): ## createThread(thr[i], threadFunc, (i*10, i*10+5)) ## joinThreads(thr) - -when not declared(NimString): + +when not declared(NimString): {.error: "You must not import this module explicitly".} const @@ -56,15 +56,15 @@ when defined(windows): {.deprecated: [TSysThread: SysThread, TWinThreadProc: WinThreadProc].} proc createThread(lpThreadAttributes: pointer, dwStackSize: int32, - lpStartAddress: WinThreadProc, + lpStartAddress: WinThreadProc, lpParameter: pointer, - dwCreationFlags: int32, + dwCreationFlags: int32, lpThreadId: var int32): SysThread {. stdcall, dynlib: "kernel32", importc: "CreateThread".} proc winSuspendThread(hThread: SysThread): int32 {. stdcall, dynlib: "kernel32", importc: "SuspendThread".} - + proc winResumeThread(hThread: SysThread): int32 {. stdcall, dynlib: "kernel32", importc: "ResumeThread".} @@ -76,7 +76,7 @@ when defined(windows): proc terminateThread(hThread: SysThread, dwExitCode: int32): int32 {. stdcall, dynlib: "kernel32", importc: "TerminateThread".} - + type ThreadVarSlot = distinct int32 @@ -104,7 +104,7 @@ when defined(windows): importc: "TlsSetValue", stdcall, dynlib: "kernel32".} proc threadVarGetValue(dwTlsIndex: ThreadVarSlot): pointer {. importc: "TlsGetValue", stdcall, dynlib: "kernel32".} - + else: when not defined(macosx): {.passL: "-pthread".} @@ -116,7 +116,7 @@ else: final, pure.} = object Pthread_attr {.importc: "pthread_attr_t", header: "", final, pure.} = object - + Timespec {.importc: "struct timespec", header: "", final, pure.} = object tv_sec: int @@ -130,8 +130,8 @@ else: importc, header: "".} proc pthread_create(a1: var SysThread, a2: var PthreadAttr, - a3: proc (x: pointer): pointer {.noconv.}, - a4: pointer): cint {.importc: "pthread_create", + a3: proc (x: pointer): pointer {.noconv.}, + a4: pointer): cint {.importc: "pthread_create", header: "".} proc pthread_join(a1: SysThread, a2: ptr pointer): cint {. importc, header: "".} @@ -146,7 +146,7 @@ else: proc pthread_getspecific(a1: ThreadVarSlot): pointer {. importc: "pthread_getspecific", header: "".} - proc pthread_key_create(a1: ptr ThreadVarSlot, + proc pthread_key_create(a1: ptr ThreadVarSlot, destruct: proc (x: pointer) {.noconv.}): int32 {. importc: "pthread_key_create", header: "".} proc pthread_key_delete(a1: ThreadVarSlot): int32 {. @@ -154,7 +154,7 @@ else: proc pthread_setspecific(a1: ThreadVarSlot, a2: pointer): int32 {. importc: "pthread_setspecific", header: "".} - + proc threadVarAlloc(): ThreadVarSlot {.inline.} = discard pthread_key_create(addr(result), nil) proc threadVarSetValue(s: ThreadVarSlot, value: pointer) {.inline.} = @@ -196,7 +196,7 @@ type nil {.deprecated: [TThreadLocalStorage: ThreadLocalStorage, TGcThread: GcThread].} -# XXX it'd be more efficient to not use a global variable for the +# XXX it'd be more efficient to not use a global variable for the # thread storage slot, but to rely on the implementation to assign slot X # for us... ;-) var globalsSlot: ThreadVarSlot @@ -222,7 +222,7 @@ when useStackMaskHack: proc maskStackPointer(offset: int): pointer {.compilerRtl, inl.} = var x {.volatile.}: pointer x = addr(x) - result = cast[pointer]((cast[int](x) and not ThreadStackMask) +% + result = cast[pointer]((cast[int](x) and not ThreadStackMask) +% (0) +% offset) # create for the main thread. Note: do not insert this data into the list @@ -231,27 +231,27 @@ when not defined(useNimRtl): when not useStackMaskHack: #when not defined(createNimRtl): initStackBottom() initGC() - + when emulatedThreadVars: if nimThreadVarsSize() > sizeof(ThreadLocalStorage): echo "too large thread local storage size requested" quit 1 - + when hasSharedHeap and not defined(boehmgc) and not defined(gogc) and not defined(nogc): var threadList: PGcThread - - proc registerThread(t: PGcThread) = + + proc registerThread(t: PGcThread) = # we need to use the GC global lock here! acquireSys(HeapLock) t.prev = nil t.next = threadList - if threadList != nil: + if threadList != nil: sysAssert(threadList.prev == nil, "threadList.prev == nil") threadList.prev = t threadList = t releaseSys(HeapLock) - + proc unregisterThread(t: PGcThread) = # we need to use the GC global lock here! acquireSys(HeapLock) @@ -263,13 +263,13 @@ when not defined(useNimRtl): t.next = nil t.prev = nil releaseSys(HeapLock) - + # on UNIX, the GC uses ``SIGFREEZE`` to tell every thread to stop so that # the GC can examine the stacks? proc stopTheWord() = discard - + # We jump through some hops here to ensure that Nim thread procs can have -# the Nim calling convention. This is needed because thread procs are +# the Nim calling convention. This is needed because thread procs are # ``stdcall`` on Windows and ``noconv`` on UNIX. Alternative would be to just # use ``stdcall`` since it is mapped to ``noconv`` on UNIX anyway. @@ -311,30 +311,30 @@ template threadProcWrapperBody(closure: expr) {.immediate.} = # exception is tried to be re-raised by the code-gen after the ``finally``! # However this is doomed to fail, because we already unmapped every heap # page! - + # mark as not running anymore: t.dataFn = nil - + {.push stack_trace:off.} when defined(windows): - proc threadProcWrapper[TArg](closure: pointer): int32 {.stdcall.} = + proc threadProcWrapper[TArg](closure: pointer): int32 {.stdcall.} = threadProcWrapperBody(closure) # implicitly return 0 else: - proc threadProcWrapper[TArg](closure: pointer): pointer {.noconv.} = + proc threadProcWrapper[TArg](closure: pointer): pointer {.noconv.} = threadProcWrapperBody(closure) {.pop.} -proc running*[TArg](t: Thread[TArg]): bool {.inline.} = +proc running*[TArg](t: Thread[TArg]): bool {.inline.} = ## returns true if `t` is running. result = t.dataFn != nil when hostOS == "windows": - proc joinThread*[TArg](t: Thread[TArg]) {.inline.} = + proc joinThread*[TArg](t: Thread[TArg]) {.inline.} = ## waits for the thread `t` to finish. discard waitForSingleObject(t.sys, -1'i32) - proc joinThreads*[TArg](t: varargs[Thread[TArg]]) = + proc joinThreads*[TArg](t: varargs[Thread[TArg]]) = ## waits for every thread in `t` to finish. var a: array[0..255, SysThread] sysAssert a.len >= t.len, "a.len >= t.len" @@ -365,7 +365,7 @@ when false: when hostOS == "windows": proc createThread*[TArg](t: var Thread[TArg], - tp: proc (arg: TArg) {.thread.}, + tp: proc (arg: TArg) {.thread.}, param: TArg) = ## creates a new thread `t` and starts its execution. Entry point is the ## proc `tp`. `param` is passed to `tp`. `TArg` can be ``void`` if you @@ -379,8 +379,8 @@ when hostOS == "windows": if t.sys <= 0: raise newException(ResourceExhaustedError, "cannot create thread") else: - proc createThread*[TArg](t: var Thread[TArg], - tp: proc (arg: TArg) {.thread.}, + proc createThread*[TArg](t: var Thread[TArg], + tp: proc (arg: TArg) {.thread.}, param: TArg) = ## creates a new thread `t` and starts its execution. Entry point is the ## proc `tp`. `param` is passed to `tp`. `TArg` can be ``void`` if you @@ -413,4 +413,3 @@ when useStackMaskHack: var mainThread: Thread[pointer] createThread(mainThread, tp) joinThread(mainThread) - From 70ce8695e703f9bc92868226421f8b9d69c005d9 Mon Sep 17 00:00:00 2001 From: Sergey Avseyev Date: Fri, 26 Jun 2015 00:15:08 +0300 Subject: [PATCH 0569/1263] Fix #2672. Do not define globalsSlot for native TLS Motivation ---------- globalsSlot is always defined so threading code works incorrectly when native TLS supported. Modification ------------ Defined globalsSlot only in TLS emulation mode. Remove myThreadId, which based on broken behavior. It might be reimplemented later Result ------ No segfaults. --- lib/system/threads.nim | 27 +++++++++++---------------- 1 file changed, 11 insertions(+), 16 deletions(-) diff --git a/lib/system/threads.nim b/lib/system/threads.nim index 1ec9aadf1..180e0410b 100644 --- a/lib/system/threads.nim +++ b/lib/system/threads.nim @@ -196,28 +196,28 @@ type nil {.deprecated: [TThreadLocalStorage: ThreadLocalStorage, TGcThread: GcThread].} -# XXX it'd be more efficient to not use a global variable for the -# thread storage slot, but to rely on the implementation to assign slot X -# for us... ;-) -var globalsSlot: ThreadVarSlot - when not defined(useNimRtl): when not useStackMaskHack: var mainThread: GcThread -proc initThreadVarsEmulation() {.compilerProc, inline.} = - when not defined(useNimRtl): - globalsSlot = threadVarAlloc() - when declared(mainThread): - threadVarSetValue(globalsSlot, addr(mainThread)) - #const globalsSlot = ThreadVarSlot(0) #sysAssert checkSlot.int == globalsSlot.int when emulatedThreadVars: + # XXX it'd be more efficient to not use a global variable for the + # thread storage slot, but to rely on the implementation to assign slot X + # for us... ;-) + var globalsSlot: ThreadVarSlot + proc GetThreadLocalVars(): pointer {.compilerRtl, inl.} = result = addr(cast[PGcThread](threadVarGetValue(globalsSlot)).tls) + proc initThreadVarsEmulation() {.compilerProc, inline.} = + when not defined(useNimRtl): + globalsSlot = threadVarAlloc() + when declared(mainThread): + threadVarSetValue(globalsSlot, addr(mainThread)) + when useStackMaskHack: proc maskStackPointer(offset: int): pointer {.compilerRtl, inl.} = var x {.volatile.}: pointer @@ -398,11 +398,6 @@ proc threadId*[TArg](t: var Thread[TArg]): ThreadId[TArg] {.inline.} = ## returns the thread ID of `t`. result = addr(t) -proc myThreadId*[TArg](): ThreadId[TArg] = - ## returns the thread ID of the thread that calls this proc. This is unsafe - ## because the type ``TArg`` is not checked for consistency! - result = cast[ThreadId[TArg]](threadVarGetValue(globalsSlot)) - when false: proc mainThreadId*[TArg](): ThreadId[TArg] = ## returns the thread ID of the main thread. From 0e06a72c64e09af1367f9e0adb4b5ff91a3e0251 Mon Sep 17 00:00:00 2001 From: apense Date: Fri, 26 Jun 2015 01:11:27 -0400 Subject: [PATCH 0570/1263] Updated nnkRange docs Addresses #2929 --- doc/astspec.txt | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/doc/astspec.txt b/doc/astspec.txt index 9bedb00fc..72cd22cc6 100644 --- a/doc/astspec.txt +++ b/doc/astspec.txt @@ -397,6 +397,8 @@ Ranges ------ Ranges occur in set constructors, case statement branches, or array slices. +Internally, the node kind ``nnkRange`` is used, but when constructing the +AST, construction with ``..`` as an infix operator should be used instead. Concrete syntax: @@ -406,7 +408,33 @@ Concrete syntax: AST: .. code-block:: nim - nnkRange(nnkIntLit(1), nnkIntLit(3)) + nnkInfix( + nnkIdent(!".."), + nnkIntLit(1), + nnkIntLit(3) + ) + +Example code: + +.. code-block:: nim + macro genRepeatEcho(): stmt = + result = newNimNode(nnkStmtList) + + var forStmt = newNimNode(nnkForStmt) # generate a for statement + forStmt.add(ident("i")) # use the variable `i` for iteration + + var rangeDef = newNimNode(nnkInfix).add( + ident("..")).add( + newIntLitNode(3),newIntLitNode(5)) # iterate over the range 3..5 + + forStmt.add(rangeDef) + forStmt.add(newCall(ident("echo"), newIntLitNode(3))) # meat of the loop + result.add(forStmt) + + genRepeatEcho() # gives: + # 3 + # 3 + # 3 If expression From 4198e88fb08daf49eb32c6bcc3674cccfe659921 Mon Sep 17 00:00:00 2001 From: apense Date: Fri, 26 Jun 2015 01:16:56 -0400 Subject: [PATCH 0571/1263] Clarified nnkFloat64Lit Fixes #2939 --- doc/astspec.txt | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/doc/astspec.txt b/doc/astspec.txt index 9bedb00fc..9b14bc3b9 100644 --- a/doc/astspec.txt +++ b/doc/astspec.txt @@ -51,7 +51,8 @@ a child can never be nil. Leaf nodes/Atoms ================ A leaf of the AST often corresponds to a terminal symbol in the concrete -syntax. +syntax. Note that the default ``float`` in Nim maps to ``float64`` such that +the default AST for a float is ``nnkFloat64Lit`` as below. ----------------- --------------------------------------------- Nim expression Corresponding AST @@ -65,7 +66,7 @@ Nim expression Corresponding AST ``42'u16`` ``nnkUInt16Lit(intVal = 42)`` ``42'u32`` ``nnkUInt32Lit(intVal = 42)`` ``42'u64`` ``nnkUInt64Lit(intVal = 42)`` -``42.0`` ``nnkFloatLit(floatVal = 42.0)`` +``42.0`` ``nnkFloat64Lit(floatVal = 42.0)`` ``42.0'f32`` ``nnkFloat32Lit(floatVal = 42.0)`` ``42.0'f64`` ``nnkFloat64Lit(floatVal = 42.0)`` ``"abc"`` ``nnkStrLit(strVal = "abc")`` From 32ec7f2f5fb3e777fcb9730571c34633bfa5bcfb Mon Sep 17 00:00:00 2001 From: Luca Date: Fri, 26 Jun 2015 09:18:40 +0200 Subject: [PATCH 0572/1263] Allow AsyncFtpClient and ftpclient to check 220 messages As many ftp servers can answer with multiple 220 messages these two libraries have to handle multiline 220 messages before send user and pass messages. --- lib/pure/asyncftpclient.nim | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/lib/pure/asyncftpclient.nim b/lib/pure/asyncftpclient.nim index daf69d59f..c3545ada8 100644 --- a/lib/pure/asyncftpclient.nim +++ b/lib/pure/asyncftpclient.nim @@ -79,7 +79,13 @@ proc connect*(ftp: AsyncFtpClient) {.async.} = # 120 Service ready in nnn minutes. # We wait until we receive 220. reply = await ftp.expectReply() - assertReply(reply, "220") + + # Handle 220 messages from the server + if reply.startsWith("220"): + assertReply(reply, "220") + while reply.continuesWith("-", 3): # handle multiline 220 message + assertReply(reply, "220") + reply = await ftp.expectReply() if ftp.user != "": assertReply(await(ftp.send("USER " & ftp.user)), "230", "331") From c687e2b9d2fefa362990f6f608c59c92a2575a3d Mon Sep 17 00:00:00 2001 From: Luca Date: Fri, 26 Jun 2015 09:24:58 +0200 Subject: [PATCH 0573/1263] Allow ftp client to handle 220 multiline messages --- lib/pure/ftpclient.nim | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/lib/pure/ftpclient.nim b/lib/pure/ftpclient.nim index dd141eb01..7ede6b479 100644 --- a/lib/pure/ftpclient.nim +++ b/lib/pure/ftpclient.nim @@ -263,8 +263,18 @@ proc connect*[T](ftp: FtpBase[T]) = else: {.fatal: "Incorrect socket instantiation".} - # TODO: Handle 120? or let user handle it. - assertReply ftp.expectReply(), "220" + var reply = ftp.expectReply() + if reply.startsWith("120"): + # 120 Service ready in nnn minutes. + # We wait until we receive 220. + reply = ftp.expectReply() + + # Handle 220 messages from the server + if reply.startsWith("220"): + assertReply(reply, "220") + while reply.continuesWith("-", 3): # handle multiline 220 message + assertReply(reply, "220") + reply = await ftp.expectReply() if ftp.user != "": assertReply(ftp.send("USER " & ftp.user), "230", "331") From 96e5c7c3b960fd617428cea3e64236dc8f430547 Mon Sep 17 00:00:00 2001 From: Luca Date: Fri, 26 Jun 2015 09:26:51 +0200 Subject: [PATCH 0574/1263] Fix remove async call --- lib/pure/ftpclient.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/pure/ftpclient.nim b/lib/pure/ftpclient.nim index 7ede6b479..522f42cf8 100644 --- a/lib/pure/ftpclient.nim +++ b/lib/pure/ftpclient.nim @@ -274,7 +274,7 @@ proc connect*[T](ftp: FtpBase[T]) = assertReply(reply, "220") while reply.continuesWith("-", 3): # handle multiline 220 message assertReply(reply, "220") - reply = await ftp.expectReply() + reply = ftp.expectReply() if ftp.user != "": assertReply(ftp.send("USER " & ftp.user), "230", "331") From 04f64fde855c83671fa0a36271253f66121cb2e6 Mon Sep 17 00:00:00 2001 From: Luca Date: Fri, 26 Jun 2015 09:35:35 +0200 Subject: [PATCH 0575/1263] Fix no async code --- lib/pure/ftpclient.nim | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/pure/ftpclient.nim b/lib/pure/ftpclient.nim index 522f42cf8..eaa8c82b2 100644 --- a/lib/pure/ftpclient.nim +++ b/lib/pure/ftpclient.nim @@ -271,9 +271,9 @@ proc connect*[T](ftp: FtpBase[T]) = # Handle 220 messages from the server if reply.startsWith("220"): - assertReply(reply, "220") + assertReply ftp.expectReply(), "220" while reply.continuesWith("-", 3): # handle multiline 220 message - assertReply(reply, "220") + assertReply ftp.expectReply(), "220" reply = ftp.expectReply() if ftp.user != "": From 40a4a393740e3cf72dd37a243d5b72d7cde7f721 Mon Sep 17 00:00:00 2001 From: Luca Date: Sat, 27 Jun 2015 14:40:12 +0200 Subject: [PATCH 0576/1263] Remove redundant 220 check --- lib/pure/ftpclient.nim | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/lib/pure/ftpclient.nim b/lib/pure/ftpclient.nim index eaa8c82b2..301ca227a 100644 --- a/lib/pure/ftpclient.nim +++ b/lib/pure/ftpclient.nim @@ -270,11 +270,10 @@ proc connect*[T](ftp: FtpBase[T]) = reply = ftp.expectReply() # Handle 220 messages from the server - if reply.startsWith("220"): + assertReply ftp.expectReply(), "220" + while reply.continuesWith("-", 3): # handle multiline 220 message assertReply ftp.expectReply(), "220" - while reply.continuesWith("-", 3): # handle multiline 220 message - assertReply ftp.expectReply(), "220" - reply = ftp.expectReply() + reply = ftp.expectReply() if ftp.user != "": assertReply(ftp.send("USER " & ftp.user), "230", "331") From 88ae4c18593c61ed1c67d074cee373226c41ab32 Mon Sep 17 00:00:00 2001 From: Luca Date: Sat, 27 Jun 2015 14:40:44 +0200 Subject: [PATCH 0577/1263] Remove redundant 220 check --- lib/pure/asyncftpclient.nim | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/lib/pure/asyncftpclient.nim b/lib/pure/asyncftpclient.nim index c3545ada8..979b0d649 100644 --- a/lib/pure/asyncftpclient.nim +++ b/lib/pure/asyncftpclient.nim @@ -81,11 +81,10 @@ proc connect*(ftp: AsyncFtpClient) {.async.} = reply = await ftp.expectReply() # Handle 220 messages from the server - if reply.startsWith("220"): + assertReply(reply, "220") + while reply.continuesWith("-", 3): # handle multiline 220 message assertReply(reply, "220") - while reply.continuesWith("-", 3): # handle multiline 220 message - assertReply(reply, "220") - reply = await ftp.expectReply() + reply = await ftp.expectReply() if ftp.user != "": assertReply(await(ftp.send("USER " & ftp.user)), "230", "331") From 110d84a9167ad077bb8ca983c43c8febc5780cc6 Mon Sep 17 00:00:00 2001 From: Luca Date: Sat, 27 Jun 2015 17:06:11 +0200 Subject: [PATCH 0578/1263] remove unnecessary function --- lib/pure/asyncftpclient.nim | 2 +- lib/pure/ftpclient.nim | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/pure/asyncftpclient.nim b/lib/pure/asyncftpclient.nim index 979b0d649..ff98d94c1 100644 --- a/lib/pure/asyncftpclient.nim +++ b/lib/pure/asyncftpclient.nim @@ -82,7 +82,7 @@ proc connect*(ftp: AsyncFtpClient) {.async.} = # Handle 220 messages from the server assertReply(reply, "220") - while reply.continuesWith("-", 3): # handle multiline 220 message + while reply[3] == "-": # handle multiline 220 message assertReply(reply, "220") reply = await ftp.expectReply() diff --git a/lib/pure/ftpclient.nim b/lib/pure/ftpclient.nim index 301ca227a..2644fc010 100644 --- a/lib/pure/ftpclient.nim +++ b/lib/pure/ftpclient.nim @@ -271,7 +271,7 @@ proc connect*[T](ftp: FtpBase[T]) = # Handle 220 messages from the server assertReply ftp.expectReply(), "220" - while reply.continuesWith("-", 3): # handle multiline 220 message + while reply[3] == "-": # handle multiline 220 message assertReply ftp.expectReply(), "220" reply = ftp.expectReply() From fd41293c06d5f0a4b4866c0257c80d4a66e83a60 Mon Sep 17 00:00:00 2001 From: Sergey Avseyev Date: Sun, 28 Jun 2015 20:12:17 +0300 Subject: [PATCH 0579/1263] Fix doc typo --- lib/system.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/system.nim b/lib/system.nim index efe557359..3d92c6f05 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -282,7 +282,7 @@ proc `==` *(x, y: char): bool {.magic: "EqCh", noSideEffect.} proc `==` *(x, y: bool): bool {.magic: "EqB", noSideEffect.} ## Checks for equality between two `bool` variables proc `==` *[T](x, y: set[T]): bool {.magic: "EqSet", noSideEffect.} - ## Checks for equality between two variables of type `set1 + ## Checks for equality between two variables of type `set` ## ## .. code-block:: nim ## var a = {1, 2, 2, 3} # duplication in sets is ignored From d46407caf3f5ca8287463da71afe6b39d2c872ae Mon Sep 17 00:00:00 2001 From: Araq Date: Fri, 26 Jun 2015 02:29:58 +0200 Subject: [PATCH 0580/1263] disable vcc specific code which doesn't work --- lib/pure/math.nim | 78 +++++++++++++++++++++++------------------------ 1 file changed, 39 insertions(+), 39 deletions(-) diff --git a/lib/pure/math.nim b/lib/pure/math.nim index c345d9d51..d3f1f3814 100644 --- a/lib/pure/math.nim +++ b/lib/pure/math.nim @@ -8,11 +8,11 @@ # ## Constructive mathematics is naturally typed. -- Simon Thompson -## +## ## Basic math routines for Nim. ## This module is available for the `JavaScript target ## `_. -## +## ## Note that the trigonometric functions naturally operate on radians. ## The helper functions `degToRad` and `radToDeg` provide conversion ## between radians and degrees. @@ -38,9 +38,9 @@ const MaxFloat32Precision* = 8 ## maximum number of meaningful digits ## after the decimal point for Nim's ## ``float32`` type. - MaxFloatPrecision* = MaxFloat64Precision ## maximum number of + MaxFloatPrecision* = MaxFloat64Precision ## maximum number of ## meaningful digits - ## after the decimal point + ## after the decimal point ## for Nim's ``float`` type. RadPerDeg = PI / 180.0 ## number of radians per degree @@ -55,10 +55,10 @@ type fcInf, ## value is positive infinity fcNegInf ## value is negative infinity -proc classify*(x: float): FloatClass = +proc classify*(x: float): FloatClass = ## classifies a floating point value. Returns `x`'s class as specified by ## `FloatClass`. - + # JavaScript and most C compilers have no classify: if x == 0.0: if 1.0/x == Inf: @@ -73,15 +73,15 @@ proc classify*(x: float): FloatClass = # XXX: fcSubnormal is not detected! -proc binom*(n, k: int): int {.noSideEffect.} = +proc binom*(n, k: int): int {.noSideEffect.} = ## computes the binomial coefficient if k <= 0: return 1 if 2*k > n: return binom(n, n-k) result = n for i in countup(2, k): result = (result * (n + 1 - i)) div i - -proc fac*(n: int): int {.noSideEffect.} = + +proc fac*(n: int): int {.noSideEffect.} = ## computes the faculty/factorial function. result = 1 for i in countup(2, n): @@ -95,7 +95,7 @@ proc isPowerOfTwo*(x: int): bool {.noSideEffect.} = proc nextPowerOfTwo*(x: int): int {.noSideEffect.} = ## returns `x` rounded up to the nearest power of two. ## Zero and negative numbers get rounded up to 1. - result = x - 1 + result = x - 1 when defined(cpu64): result = result or (result shr 32) when sizeof(int) > 2: @@ -114,8 +114,8 @@ proc countBits32*(n: int32): int {.noSideEffect.} = v = (v and 0x33333333'i32) +% ((v shr 2'i32) and 0x33333333'i32) result = ((v +% (v shr 4'i32) and 0xF0F0F0F'i32) *% 0x1010101'i32) shr 24'i32 -proc sum*[T](x: openArray[T]): T {.noSideEffect.} = - ## computes the sum of the elements in `x`. +proc sum*[T](x: openArray[T]): T {.noSideEffect.} = + ## computes the sum of the elements in `x`. ## If `x` is empty, 0 is returned. for i in items(x): result = result + i @@ -129,7 +129,7 @@ proc mean*[T](x: openArray[T]): float {.noSideEffect.} = result = result / toFloat(len(x)) proc variance*[T](x: openArray[T]): float {.noSideEffect.} = - ## computes the variance of the elements in `x`. + ## computes the variance of the elements in `x`. ## If `x` is empty, NaN is returned. ## ``toFloat(x: T): float`` must be defined. result = 0.0 @@ -156,7 +156,7 @@ proc randomize*() {.benign.} ## initializes the random number generator with a "random" ## number, i.e. a tickcount. Note: Does nothing for the JavaScript target, ## as JavaScript does not support this. - + proc randomize*(seed: int) {.benign.} ## initializes the random number generator with a specific seed. ## Note: Does nothing for the JavaScript target, @@ -168,14 +168,14 @@ when not defined(JS): ## computes the square root of `x`. proc cbrt*(x: float): float {.importc: "cbrt", header: "".} ## computes the cubic root of `x` - + proc ln*(x: float): float {.importc: "log", header: "".} ## computes ln(x). proc log10*(x: float): float {.importc: "log10", header: "".} proc log2*(x: float): float = return ln(x) / ln(2.0) proc exp*(x: float): float {.importc: "exp", header: "".} ## computes e**x. - + proc frexp*(x: float, exponent: var int): float {. importc: "frexp", header: "".} ## Split a number into mantissa and exponent. @@ -183,10 +183,10 @@ when not defined(JS): ## and less than 1) and the integer value n such that `x` (the original ## float value) equals m * 2**n. frexp stores n in `exponent` and returns ## m. - + proc round*(x: float): int {.importc: "lrint", header: "".} - ## converts a float to an int by rounding. - + ## converts a float to an int by rounding. + proc arccos*(x: float): float {.importc: "acos", header: "".} proc arcsin*(x: float): float {.importc: "asin", header: "".} proc arctan*(x: float): float {.importc: "atan", header: "".} @@ -195,31 +195,31 @@ when not defined(JS): ## `atan2` returns the arc tangent of `y` / `x`; it produces correct ## results even when the resulting angle is near pi/2 or -pi/2 ## (`x` near 0). - + proc cos*(x: float): float {.importc: "cos", header: "".} proc cosh*(x: float): float {.importc: "cosh", header: "".} proc hypot*(x, y: float): float {.importc: "hypot", header: "".} ## same as ``sqrt(x*x + y*y)``. - + proc sinh*(x: float): float {.importc: "sinh", header: "".} proc sin*(x: float): float {.importc: "sin", header: "".} proc tan*(x: float): float {.importc: "tan", header: "".} proc tanh*(x: float): float {.importc: "tanh", header: "".} proc pow*(x, y: float): float {.importc: "pow", header: "".} ## computes x to power raised of y. - + proc erf*(x: float): float {.importc: "erf", header: "".} ## The error function proc erfc*(x: float): float {.importc: "erfc", header: "".} ## The complementary error function - + proc lgamma*(x: float): float {.importc: "lgamma", header: "".} ## Natural log of the gamma function proc tgamma*(x: float): float {.importc: "tgamma", header: "".} ## The gamma function - + # C procs: - when defined(vcc): + when defined(vcc) and false: # The "secure" random, available from Windows XP # https://msdn.microsoft.com/en-us/library/sxtz2fa8.aspx # Present in some variants of MinGW but not enough to justify @@ -230,7 +230,7 @@ when not defined(JS): else: proc srand(seed: cint) {.importc: "srand", header: "".} proc rand(): cint {.importc: "rand", header: "".} - + when not defined(windows): proc srand48(seed: clong) {.importc: "srand48", header: "".} proc drand48(): float {.importc: "drand48", header: "".} @@ -256,7 +256,7 @@ when not defined(JS): # on MSDN and very unlikely to change const rand_max = 32767 result = (float(rand()) / float(rand_max)) * max - + when not defined(vcc): # the above code for vcc uses `discard` instead # this is either not Windows or is Windows without vcc proc randomize() = @@ -264,7 +264,7 @@ when not defined(JS): proc randomize(seed: int) = srand(cint(seed)) # rand_s doesn't use srand when declared(srand48): srand48(seed) - + proc random(max: int): int = result = int(rand()) mod max @@ -284,7 +284,7 @@ else: result = float(mathrandom() * float(max)) proc randomize() = discard proc randomize(seed: int) = discard - + proc sqrt*(x: float): float {.importc: "Math.sqrt", nodecl.} proc ln*(x: float): float {.importc: "Math.log", nodecl.} proc log10*(x: float): float = return ln(x) / ln(10.0) @@ -293,7 +293,7 @@ else: proc exp*(x: float): float {.importc: "Math.exp", nodecl.} proc round*(x: float): int {.importc: "Math.round", nodecl.} proc pow*(x, y: float): float {.importc: "Math.pow", nodecl.} - + proc frexp*(x: float, exponent: var int): float = if x == 0.0: exponent = 0 @@ -309,7 +309,7 @@ else: proc arcsin*(x: float): float {.importc: "Math.asin", nodecl.} proc arctan*(x: float): float {.importc: "Math.atan", nodecl.} proc arctan2*(y, x: float): float {.importc: "Math.atan2", nodecl.} - + proc cos*(x: float): float {.importc: "Math.cos", nodecl.} proc cosh*(x: float): float = return (exp(x)+exp(-x))*0.5 proc hypot*(x, y: float): float = return sqrt(x*x + y*y) @@ -334,7 +334,7 @@ proc `mod`*(x, y: float): float = ## Computes the modulo operation for float operators. Equivalent ## to ``x - y * floor(x/y)``. Note that the remainder will always ## have the same sign as the divisor. - ## + ## ## .. code-block:: nim ## echo (4.0 mod -3.1) # -2.2 result = if y == 0.0: x else: x - y * (x/y).floor @@ -355,7 +355,7 @@ type {.deprecated: [TFloatClass: FloatClass, TRunningStat: RunningStat].} -proc push*(s: var RunningStat, x: float) = +proc push*(s: var RunningStat, x: float) = ## pushes a value `x` for processing inc(s.n) # See Knuth TAOCP vol 2, 3rd edition, page 232 @@ -375,17 +375,17 @@ proc push*(s: var RunningStat, x: float) = s.oldM = s.mean s.oldS = s.newS s.sum = s.sum + x - -proc push*(s: var RunningStat, x: int) = + +proc push*(s: var RunningStat, x: int) = ## pushes a value `x` for processing. `x` is simply converted to ``float`` ## and the other push operation is called. push(s, toFloat(x)) - -proc variance*(s: RunningStat): float = + +proc variance*(s: RunningStat): float = ## computes the current variance of `s` if s.n > 1: result = s.newS / (toFloat(s.n - 1)) -proc standardDeviation*(s: RunningStat): float = +proc standardDeviation*(s: RunningStat): float = ## computes the current standard deviation of `s` result = sqrt(variance(s)) @@ -442,7 +442,7 @@ when isMainModule and not defined(JS): # Check for no side effect annotation proc mySqrt(num: float): float {.noSideEffect.} = return sqrt(num) - + # check gamma function assert(tgamma(5.0) == 24.0) # 4! assert(lgamma(1.0) == 0.0) # ln(1.0) == 0.0 From ace9299a32d09bd25f9ccb8e8d77efca0185fb26 Mon Sep 17 00:00:00 2001 From: Araq Date: Fri, 26 Jun 2015 02:30:21 +0200 Subject: [PATCH 0581/1263] added /*INCLUDESECTION*/ section for .emit pragma --- compiler/ccgstmts.nim | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/compiler/ccgstmts.nim b/compiler/ccgstmts.nim index 6d29b1684..5129c8023 100644 --- a/compiler/ccgstmts.nim +++ b/compiler/ccgstmts.nim @@ -1002,8 +1002,10 @@ proc genAsmStmt(p: BProc, t: PNode) = proc determineSection(n: PNode): TCFileSection = result = cfsProcHeaders if n.len >= 1 and n.sons[0].kind in {nkStrLit..nkTripleStrLit}: - if n.sons[0].strVal.startsWith("/*TYPESECTION*/"): result = cfsTypes - elif n.sons[0].strVal.startsWith("/*VARSECTION*/"): result = cfsVars + let sec = n.sons[0].strVal + if sec.startsWith("/*TYPESECTION*/"): result = cfsTypes + elif sec.startsWith("/*VARSECTION*/"): result = cfsVars + elif sec.startsWith("/*INCLUDESECTION*/"): result = cfsHeaders proc genEmit(p: BProc, t: PNode) = var s = genAsmOrEmitStmt(p, t.sons[1]) From 2297a1aa6048fcbcffca4e2c2e4ede275261e83d Mon Sep 17 00:00:00 2001 From: Araq Date: Sat, 27 Jun 2015 23:35:02 +0200 Subject: [PATCH 0582/1263] much better error message if an exe cannot be found --- lib/pure/os.nim | 7 +++++-- lib/pure/osproc.nim | 2 +- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/lib/pure/os.nim b/lib/pure/os.nim index f29505590..6f8d923e3 100644 --- a/lib/pure/os.nim +++ b/lib/pure/os.nim @@ -261,7 +261,7 @@ proc osErrorMsg*(errorCode: OSErrorCode): string = if errorCode != OSErrorCode(0'i32): result = $os.strerror(errorCode.int32) -proc raiseOSError*(errorCode: OSErrorCode) = +proc raiseOSError*(errorCode: OSErrorCode; additionalInfo = "") {.noinline.} = ## Raises an ``OSError`` exception. The ``errorCode`` will determine the ## message, ``osErrorMsg`` will be used to get this message. ## @@ -271,7 +271,10 @@ proc raiseOSError*(errorCode: OSErrorCode) = ## the message ``unknown OS error`` will be used. var e: ref OSError; new(e) e.errorCode = errorCode.int32 - e.msg = osErrorMsg(errorCode) + if additionalInfo.len == 0: + e.msg = osErrorMsg(errorCode) + else: + e.msg = additionalInfo & " " & osErrorMsg(errorCode) if e.msg == "": e.msg = "unknown OS error" raise e diff --git a/lib/pure/osproc.nim b/lib/pure/osproc.nim index 33f5419d5..add4bc0a8 100644 --- a/lib/pure/osproc.nim +++ b/lib/pure/osproc.nim @@ -468,7 +468,7 @@ when defined(Windows) and not defined(useNimRtl): fileClose(si.hStdError) if e != nil: dealloc(e) - if success == 0: raiseOSError(lastError) + if success == 0: raiseOSError(lastError, command) # Close the handle now so anyone waiting is woken: discard closeHandle(procInfo.hThread) result.fProcessHandle = procInfo.hProcess From 8f58ab99eb69e2d03a66d4d9401edb87d13e2492 Mon Sep 17 00:00:00 2001 From: Araq Date: Sat, 27 Jun 2015 23:35:34 +0200 Subject: [PATCH 0583/1263] nimrepl compiles again (but doesn't work) --- tools/nimrepl.nim | 178 +++++++++++++++++++++++----------------------- 1 file changed, 89 insertions(+), 89 deletions(-) diff --git a/tools/nimrepl.nim b/tools/nimrepl.nim index 3d818a556..ac82d8b75 100644 --- a/tools/nimrepl.nim +++ b/tools/nimrepl.nim @@ -15,10 +15,10 @@ else: const runCmd = "c -r" var nimExe = findExe("nim") -if nimExe.len == 0: nimExe = "../bin" / addFileExt("nim", os.exeExt) +if nimExe.len == 0: nimExe = "../bin" / addFileExt("nim", os.ExeExt) proc execCode(code: string): string = - var f: TFile + var f: File if open(f, "temp.nim", fmWrite): f.write(code) f.close() @@ -28,145 +28,145 @@ proc execCode(code: string): string = else: result = "cannot open file 'temp.nim'" -var shiftPressed = False +var shiftPressed = false var w: gtk2.PWindow -var InputTextBuffer: PTextBuffer -var OutputTextBuffer: PTextBuffer +var inputTextBuffer: PTextBuffer +var outputTextBuffer: PTextBuffer -proc destroy(widget: PWidget, data: pgpointer){.cdecl.} = +proc destroy(widget: PWidget, data: pointer){.cdecl.} = main_quit() -proc fileOpenClicked(menuitem: PMenuItem, userdata: pgpointer) {.cdecl.} = - var path = ChooseFileToOpen(w) +proc fileOpenClicked(menuitem: PMenuItem, userdata: pointer) {.cdecl.} = + var path = chooseFileToOpen(w) if path != "": var file = readFile(path) if file != nil: - set_text(InputTextBuffer, file, len(file).gint) + set_text(inputTextBuffer, file, len(file).gint) else: error(w, "Unable to read from file") -proc fileSaveClicked(menuitem: PMenuItem, userdata: pgpointer) {.cdecl.} = - var path = ChooseFileToSave(w) - +proc fileSaveClicked(menuitem: PMenuItem, userdata: pointer) {.cdecl.} = + var path = chooseFileToSave(w) + if path == "": return var startIter: TTextIter var endIter: TTextIter - get_start_iter(InputTextBuffer, addr(startIter)) - get_end_iter(InputTextBuffer, addr(endIter)) - var InputText = get_text(InputTextBuffer, addr(startIter), - addr(endIter), False) - var f: TFile + get_start_iter(inputTextBuffer, addr(startIter)) + get_end_iter(inputTextBuffer, addr(endIter)) + var inputText = get_text(inputTextBuffer, addr(startIter), + addr(endIter), false) + var f: File if open(f, path, fmWrite): - f.write(InputText) + f.write(inputText) f.close() else: error(w, "Unable to write to file") -proc inputKeyPressed(widget: PWidget, event: PEventKey, - userdata: pgpointer): bool {.cdecl.} = +proc inputKeyPressed(widget: PWidget, event: PEventKey, + userdata: pointer): bool {.cdecl.} = if ($keyval_name(event.keyval)).tolower() == "shift_l": # SHIFT is pressed - shiftPressed = True - -proc setError(msg: string) = + shiftPressed = true + +proc setError(msg: string) = outputTextBuffer.setText(msg, msg.len.gint) - -proc inputKeyReleased(widget: PWidget, event: PEventKey, - userdata: pgpointer): bool {.cdecl.} = + +proc inputKeyReleased(widget: PWidget, event: PEventKey, + userdata: pointer): bool {.cdecl.} = #echo(keyval_name(event.keyval)) if ($keyval_name(event.keyval)).tolower() == "shift_l": # SHIFT is released - shiftPressed = False - + shiftPressed = false + if ($keyval_name(event.keyval)).tolower() == "return": #echo($keyval_name(event.keyval), "Shift_L") # Enter pressed - if shiftPressed == False: + if not shiftPressed: var startIter: TTextIter var endIter: TTextIter - get_start_iter(InputTextBuffer, addr(startIter)) - get_end_iter(InputTextBuffer, addr(endIter)) - var InputText = get_text(InputTextBuffer, addr(startIter), - addr(endIter), False) + get_start_iter(inputTextBuffer, addr(startIter)) + get_end_iter(inputTextBuffer, addr(endIter)) + var inputText = get_text(inputTextBuffer, addr(startIter), + addr(endIter), false) try: - var r = execCode($InputText) - set_text(OutputTextBuffer, r, len(r).gint) - except EIO: + var r = execCode($inputText) + set_text(outputTextBuffer, r, len(r).gint) + except IOError: setError("Error: Could not open file temp.nim") proc initControls() = w = window_new(gtk2.WINDOW_TOPLEVEL) set_default_size(w, 500, 600) - set_title(w, "Nimrod REPL") + set_title(w, "Nim REPL") discard signal_connect(w, "destroy", SIGNAL_FUNC(nimrepl.destroy), nil) - - # MainBox (vbox) - var MainBox = vbox_new(False, 0) - add(w, MainBox) - - # TopMenu (MenuBar) - var TopMenu = menu_bar_new() - show(TopMenu) - - var FileMenu = menu_new() - var OpenMenuItem = menu_item_new("Open") - append(FileMenu, OpenMenuItem) - show(OpenMenuItem) - discard signal_connect(OpenMenuItem, "activate", - SIGNAL_FUNC(fileOpenClicked), nil) - var SaveMenuItem = menu_item_new("Save...") - append(FileMenu, SaveMenuItem) - show(SaveMenuItem) - discard signal_connect(SaveMenuItem, "activate", - SIGNAL_FUNC(fileSaveClicked), nil) - var FileMenuItem = menu_item_new("File") - - set_submenu(FileMenuItem, FileMenu) - show(FileMenuItem) - append(TopMenu, FileMenuItem) - - pack_start(MainBox, TopMenu, False, False, 0) + # MainBox (vbox) + var mainBox = vbox_new(false, 0) + add(w, mainBox) + + # TopMenu (MenuBar) + var topMenu = menu_bar_new() + show(topMenu) + + var fileMenu = menu_new() + var openMenuItem = menu_item_new("Open") + append(fileMenu, openMenuItem) + show(openMenuItem) + discard signal_connect(openMenuItem, "activate", + SIGNAL_FUNC(fileOpenClicked), nil) + var saveMenuItem = menu_item_new("Save...") + append(fileMenu, saveMenuItem) + show(saveMenuItem) + discard signal_connect(saveMenuItem, "activate", + SIGNAL_FUNC(fileSaveClicked), nil) + var fileMenuItem = menu_item_new("File") + + + set_submenu(fileMenuItem, fileMenu) + show(fileMenuItem) + append(topMenu, fileMenuItem) + + pack_start(mainBox, topMenu, false, false, 0) # VPaned - Separates the InputTextView and the OutputTextView var paned = vpaned_new() set_position(paned, 450) - pack_start(MainBox, paned, True, True, 0) + pack_start(mainBox, paned, true, true, 0) show(paned) # Init the TextBuffers - InputTextBuffer = text_buffer_new(nil) - OutputTextBuffer = text_buffer_new(nil) + inputTextBuffer = text_buffer_new(nil) + outputTextBuffer = text_buffer_new(nil) # InputTextView (TextView) - var InputScrolledWindow = scrolled_window_new(nil, nil) - set_policy(InputScrolledWindow, POLICY_AUTOMATIC, POLICY_AUTOMATIC) - var InputTextView = text_view_new(InputTextBuffer) - add_with_viewport(InputScrolledWindow, InputTextView) - add1(paned, InputScrolledWindow) - show(InputScrolledWindow) - show(InputTextView) - - discard signal_connect(InputTextView, "key-release-event", + var inputScrolledWindow = scrolled_window_new(nil, nil) + set_policy(inputScrolledWindow, POLICY_AUTOMATIC, POLICY_AUTOMATIC) + var inputTextView = text_view_new(inputTextBuffer) + add_with_viewport(inputScrolledWindow, inputTextView) + add1(paned, inputScrolledWindow) + show(inputScrolledWindow) + show(inputTextView) + + discard signal_connect(inputTextView, "key-release-event", SIGNAL_FUNC(inputKeyReleased), nil) - discard signal_connect(InputTextView, "key-press-event", + discard signal_connect(inputTextView, "key-press-event", SIGNAL_FUNC(inputKeyPressed), nil) - + # OutputTextView (TextView) - var OutputScrolledWindow = scrolled_window_new(nil, nil) - set_policy(OutputScrolledWindow, POLICY_AUTOMATIC, POLICY_AUTOMATIC) - var OutputTextView = text_view_new(OutputTextBuffer) - add_with_viewport(OutputScrolledWindow, OutputTextView) - add2(paned, OutputScrolledWindow) - show(OutputScrolledWindow) - show(OutputTextView) - + var outputScrolledWindow = scrolled_window_new(nil, nil) + set_policy(outputScrolledWindow, POLICY_AUTOMATIC, POLICY_AUTOMATIC) + var outputTextView = text_view_new(outputTextBuffer) + add_with_viewport(outputScrolledWindow, outputTextView) + add2(paned, outputScrolledWindow) + show(outputScrolledWindow) + show(outputTextView) + show(w) - show(MainBox) - -nimrod_init() + show(mainBox) + +nim_init() initControls() main() From a1caef474bb6e49baed811ea2a3038cd08c9d86c Mon Sep 17 00:00:00 2001 From: Araq Date: Sun, 28 Jun 2015 01:39:39 +0200 Subject: [PATCH 0584/1263] proper distinction between --gc:none and --os:standalone --- lib/impure/dialogs.nim | 226 ---------------------- lib/system.nim | 44 +++-- lib/system/alloc.nim | 33 +++- lib/system/cgprocs.nim | 5 - lib/system/mmdisp.nim | 9 +- tests/manyloc/standalone/barebone.nim.cfg | 1 + web/news.txt | 5 + 7 files changed, 62 insertions(+), 261 deletions(-) delete mode 100644 lib/impure/dialogs.nim diff --git a/lib/impure/dialogs.nim b/lib/impure/dialogs.nim deleted file mode 100644 index 4ea66a6e6..000000000 --- a/lib/impure/dialogs.nim +++ /dev/null @@ -1,226 +0,0 @@ -# -# -# Nim's Runtime Library -# (c) Copyright 2012 Andreas Rumpf -# -# See the file "copying.txt", included in this -# distribution, for details about the copyright. -# - - -## This module implements portable dialogs for Nim; the implementation -## builds on the GTK interface. On Windows, native dialogs are shown instead. - -import - glib2, gtk2 - -when defined(Windows): - import windows, ShellAPI, os - -proc info*(window: PWindow, msg: string) = - ## Shows an information message to the user. The process waits until the - ## user presses the OK button. - when defined(Windows): - discard MessageBoxA(0, msg, "Information", MB_OK or MB_ICONINFORMATION) - else: - var dialog = message_dialog_new(window, - DIALOG_MODAL or DIALOG_DESTROY_WITH_PARENT, - MESSAGE_INFO, BUTTONS_OK, "%s", cstring(msg)) - setTitle(dialog, "Information") - discard run(dialog) - destroy(PWidget(dialog)) - -proc warning*(window: PWindow, msg: string) = - ## Shows a warning message to the user. The process waits until the user - ## presses the OK button. - when defined(Windows): - discard MessageBoxA(0, msg, "Warning", MB_OK or MB_ICONWARNING) - else: - var dialog = DIALOG(message_dialog_new(window, - DIALOG_MODAL or DIALOG_DESTROY_WITH_PARENT, - MESSAGE_WARNING, BUTTONS_OK, "%s", cstring(msg))) - setTitle(dialog, "Warning") - discard run(dialog) - destroy(PWidget(dialog)) - -proc error*(window: PWindow, msg: string) = - ## Shows an error message to the user. The process waits until the user - ## presses the OK button. - when defined(Windows): - discard MessageBoxA(0, msg, "Error", MB_OK or MB_ICONERROR) - else: - var dialog = DIALOG(message_dialog_new(window, - DIALOG_MODAL or DIALOG_DESTROY_WITH_PARENT, - MESSAGE_ERROR, BUTTONS_OK, "%s", cstring(msg))) - setTitle(dialog, "Error") - discard run(dialog) - destroy(PWidget(dialog)) - - -proc chooseFileToOpen*(window: PWindow, root: string = ""): string = - ## Opens a dialog that requests a filename from the user. Returns "" - ## if the user closed the dialog without selecting a file. On Windows, - ## the native dialog is used, else the GTK dialog is used. - when defined(Windows): - var - opf: TOPENFILENAME - buf: array [0..2047, char] - opf.lStructSize = sizeof(opf).int32 - if root.len > 0: - opf.lpstrInitialDir = root - opf.lpstrFilter = "All Files\0*.*\0\0" - opf.flags = OFN_FILEMUSTEXIST - opf.lpstrFile = buf - opf.nMaxFile = sizeof(buf).int32 - var res = GetOpenFileName(addr(opf)) - if res != 0: - result = $buf - else: - result = "" - else: - var chooser = file_chooser_dialog_new("Open File", window, - FILE_CHOOSER_ACTION_OPEN, - STOCK_CANCEL, RESPONSE_CANCEL, - STOCK_OPEN, RESPONSE_OK, nil) - if root.len > 0: - discard set_current_folder(chooser, root) - if run(chooser) == cint(RESPONSE_OK): - var x = get_filename(chooser) - result = $x - g_free(x) - else: - result = "" - destroy(PWidget(chooser)) - -proc chooseFilesToOpen*(window: PWindow, root: string = ""): seq[string] = - ## Opens a dialog that requests filenames from the user. Returns ``@[]`` - ## if the user closed the dialog without selecting a file. On Windows, - ## the native dialog is used, else the GTK dialog is used. - when defined(Windows): - var - opf: TOPENFILENAME - buf: array [0..2047*4, char] - opf.lStructSize = sizeof(opf).int32 - if root.len > 0: - opf.lpstrInitialDir = root - opf.lpstrFilter = "All Files\0*.*\0\0" - opf.flags = OFN_FILEMUSTEXIST or OFN_ALLOWMULTISELECT or OFN_EXPLORER - opf.lpstrFile = buf - opf.nMaxFile = sizeof(buf).int32 - var res = GetOpenFileName(addr(opf)) - result = @[] - if res != 0: - # parsing the result is horrible: - var - i = 0 - s: string - path = "" - while buf[i] != '\0': - add(path, buf[i]) - inc(i) - inc(i) - if buf[i] != '\0': - while true: - s = "" - while buf[i] != '\0': - add(s, buf[i]) - inc(i) - add(result, s) - inc(i) - if buf[i] == '\0': break - for i in 0..result.len-1: result[i] = os.joinPath(path, result[i]) - else: - # only one file selected --> gosh, what an ungly thing - # the windows API is - add(result, path) - else: - var chooser = file_chooser_dialog_new("Open Files", window, - FILE_CHOOSER_ACTION_OPEN, - STOCK_CANCEL, RESPONSE_CANCEL, - STOCK_OPEN, RESPONSE_OK, nil) - if root.len > 0: - discard set_current_folder(chooser, root) - set_select_multiple(chooser, true) - result = @[] - if run(chooser) == cint(RESPONSE_OK): - var L = get_filenames(chooser) - var it = L - while it != nil: - add(result, $cast[cstring](it.data)) - g_free(it.data) - it = it.next - free(L) - destroy(PWidget(chooser)) - - -proc chooseFileToSave*(window: PWindow, root: string = ""): string = - ## Opens a dialog that requests a filename to save to from the user. - ## Returns "" if the user closed the dialog without selecting a file. - ## On Windows, the native dialog is used, else the GTK dialog is used. - when defined(Windows): - var - opf: TOPENFILENAME - buf: array [0..2047, char] - opf.lStructSize = sizeof(opf).int32 - if root.len > 0: - opf.lpstrInitialDir = root - opf.lpstrFilter = "All Files\0*.*\0\0" - opf.flags = OFN_OVERWRITEPROMPT - opf.lpstrFile = buf - opf.nMaxFile = sizeof(buf).int32 - var res = GetSaveFileName(addr(opf)) - if res != 0: - result = $buf - else: - result = "" - else: - var chooser = file_chooser_dialog_new("Save File", window, - FILE_CHOOSER_ACTION_SAVE, - STOCK_CANCEL, RESPONSE_CANCEL, - STOCK_SAVE, RESPONSE_OK, nil) - if root.len > 0: - discard set_current_folder(chooser, root) - set_do_overwrite_confirmation(chooser, true) - if run(chooser) == cint(RESPONSE_OK): - var x = get_filename(chooser) - result = $x - g_free(x) - else: - result = "" - destroy(PWidget(chooser)) - - -proc chooseDir*(window: PWindow, root: string = ""): string = - ## Opens a dialog that requests a directory from the user. - ## Returns "" if the user closed the dialog without selecting a directory. - ## On Windows, the native dialog is used, else the GTK dialog is used. - when defined(Windows): - var - lpItemID: PItemIDList - BrowseInfo: TBrowseInfo - DisplayName: array [0..MAX_PATH, char] - TempPath: array [0..MAX_PATH, char] - result = "" - #BrowseInfo.hwndOwner = Application.Handle - BrowseInfo.pszDisplayName = DisplayName - BrowseInfo.ulFlags = 1 #BIF_RETURNONLYFSDIRS - lpItemID = SHBrowseForFolder(cast[LPBrowseInfo](addr(BrowseInfo))) - if lpItemId != nil: - discard SHGetPathFromIDList(lpItemID, TempPath) - result = $TempPath - discard GlobalFreePtr(lpItemID) - else: - var chooser = file_chooser_dialog_new("Select Directory", window, - FILE_CHOOSER_ACTION_SELECT_FOLDER, - STOCK_CANCEL, RESPONSE_CANCEL, - STOCK_OPEN, RESPONSE_OK, nil) - if root.len > 0: - discard set_current_folder(chooser, root) - if run(chooser) == cint(RESPONSE_OK): - var x = get_filename(chooser) - result = $x - g_free(x) - else: - result = "" - destroy(PWidget(chooser)) - diff --git a/lib/system.nim b/lib/system.nim index 3d92c6f05..e11722ae0 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -1196,8 +1196,13 @@ template sysAssert(cond: bool, msg: string) = echo "[SYSASSERT] ", msg quit 1 +const hasAlloc = hostOS != "standalone" or not defined(nogc) + when not defined(JS) and not defined(nimrodVm) and hostOS != "standalone": include "system/cgprocs" +when not defined(JS) and not defined(nimrodVm) and hasAlloc: + proc setStackBottom(theStackBottom: pointer) {.compilerRtl, noinline, benign.} + proc addChar(s: NimString, c: char): NimString {.compilerProc, benign.} proc add *[T](x: var seq[T], y: T) {.magic: "AppendSeqElem", noSideEffect.} proc add *[T](x: var seq[T], y: openArray[T]) {.noSideEffect.} = @@ -1404,7 +1409,7 @@ when not defined(nimrodVM): ## otherwise. Like any procedure dealing with raw memory this is ## *unsafe*. - when hostOS != "standalone": + when hasAlloc: proc alloc*(size: Natural): pointer {.noconv, rtl, tags: [], benign.} ## allocates a new memory block with at least ``size`` bytes. The ## block has to be freed with ``realloc(block, 0)`` or @@ -1540,7 +1545,7 @@ proc `$`*(x: int64): string {.magic: "Int64ToStr", noSideEffect.} ## converted to a decimal string. when not defined(NimrodVM): - when not defined(JS) and hostOS != "standalone": + when not defined(JS) and hasAlloc: proc `$` *(x: uint64): string {.noSideEffect.} ## The stringify operator for an unsigned integer argument. Returns `x` ## converted to a decimal string. @@ -1607,7 +1612,7 @@ const # GC interface: -when not defined(nimrodVM) and hostOS != "standalone": +when not defined(nimrodVM) and hasAlloc: proc getOccupiedMem*(): int {.rtl.} ## returns the number of bytes that are owned by the process and hold data. @@ -2163,7 +2168,7 @@ when false: # ----------------- GC interface --------------------------------------------- -when not defined(nimrodVM) and hostOS != "standalone": +when not defined(nimrodVM) and hasAlloc: proc GC_disable*() {.rtl, inl, benign.} ## disables the GC. If called n-times, n calls to `GC_enable` are needed to ## reactivate the GC. Note that in most circumstances one should only disable @@ -2288,7 +2293,7 @@ when defined(JS): """ proc add*(x: var cstring, y: cstring) {.magic: "AppendStrStr".} -elif hostOS != "standalone": +elif hasAlloc: {.push stack_trace:off, profiler:off.} proc add*(x: var string, y: cstring) = var i = 0 @@ -2382,7 +2387,7 @@ else: when not defined(JS): #and not defined(NimrodVM): {.push stack_trace: off, profiler:off.} - when not defined(NimrodVM) and hostOS != "standalone": + when not defined(NimrodVM) and not defined(nogc): proc initGC() when not defined(boehmgc) and not defined(useMalloc) and not defined(gogc): proc initAllocator() {.inline.} @@ -2402,6 +2407,7 @@ when not defined(JS): #and not defined(NimrodVM): when declared(setStackBottom): setStackBottom(locals) + when hasAlloc: var strDesc: TNimType @@ -2625,6 +2631,7 @@ when not defined(JS): #and not defined(NimrodVM): when not defined(nimfix): {.deprecated: [fileHandle: getFileHandle].} + when declared(newSeq): proc cstringArrayToSeq*(a: cstringArray, len: Natural): seq[string] = ## converts a ``cstringArray`` to a ``seq[string]``. `a` is supposed to be ## of length ``len``. @@ -2640,12 +2647,12 @@ when not defined(JS): #and not defined(NimrodVM): # ------------------------------------------------------------------------- - when not defined(NimrodVM) and hostOS != "standalone": + when declared(alloc0) and declared(dealloc): proc allocCStringArray*(a: openArray[string]): cstringArray = ## creates a NULL terminated cstringArray from `a`. The result has to ## be freed with `deallocCStringArray` after it's not needed anymore. result = cast[cstringArray](alloc0((a.len+1) * sizeof(cstring))) - let x = cast[ptr array[0..20_000, string]](a) + let x = cast[ptr array[0..ArrayDummySize, string]](a) for i in 0 .. a.high: result[i] = cast[cstring](alloc0(x[i].len+1)) copyMem(result[i], addr(x[i][0]), x[i].len) @@ -2685,9 +2692,9 @@ when not defined(JS): #and not defined(NimrodVM): when hasThreadSupport: include "system/syslocks" when hostOS != "standalone": include "system/threads" - elif not defined(nogc) and not defined(NimrodVM) and hostOS != "standalone": + elif not defined(nogc) and not defined(NimrodVM): when not defined(useNimRtl) and not defined(createNimRtl): initStackBottom() - initGC() + when declared(initGC): initGC() when not defined(NimrodVM): proc setControlCHook*(hook: proc () {.noconv.} not nil) @@ -2748,9 +2755,9 @@ when not defined(JS): #and not defined(NimrodVM): else: result = n.sons[n.len] - when hostOS != "standalone": include "system/mmdisp" + when hasAlloc: include "system/mmdisp" {.push stack_trace: off, profiler:off.} - when hostOS != "standalone": include "system/sysstr" + when hasAlloc: include "system/sysstr" {.pop.} when hostOS != "standalone": include "system/sysio" @@ -2759,7 +2766,7 @@ when not defined(JS): #and not defined(NimrodVM): else: include "system/sysio" - when hostOS != "standalone": + when declared(open) and declared(close) and declared(readline): iterator lines*(filename: string): TaintedString {.tags: [ReadIOEffect].} = ## Iterates over any line in the file named `filename`. ## @@ -2795,10 +2802,11 @@ when not defined(JS): #and not defined(NimrodVM): var res = TaintedString(newStringOfCap(80)) while f.readLine(res): yield res - when hostOS != "standalone" and not defined(NimrodVM): + when not defined(NimrodVM) and hasAlloc: include "system/assign" include "system/repr" + when hostOS != "standalone" and not defined(NimrodVM): proc getCurrentException*(): ref Exception {.compilerRtl, inl, benign.} = ## retrieves the current exception; if there is none, nil is returned. result = currException @@ -2949,7 +2957,7 @@ template spliceImpl(s, a, L, b: expr): stmt {.immediate.} = # fill the hole: for i in 0 .. B is 1 discard -when hostOS != "standalone" and not defined(NimrodVM) and not defined(JS): +when hasAlloc and not defined(NimrodVM) and not defined(JS): proc deepCopy*[T](x: var T, y: T) {.noSideEffect, magic: "DeepCopy".} = ## performs a deep copy of `x`. This is also used by the code generator ## for the implementation of ``spawn``. diff --git a/lib/system/alloc.nim b/lib/system/alloc.nim index d877cda2c..13a10e46f 100644 --- a/lib/system/alloc.nim +++ b/lib/system/alloc.nim @@ -13,6 +13,15 @@ # - make searching for block O(1) {.push profiler:off.} +proc roundup(x, v: int): int {.inline.} = + result = (x + (v-1)) and not (v-1) + sysAssert(result >= x, "roundup: result < x") + #return ((-x) and (v-1)) +% x + +sysAssert(roundup(14, PageSize) == PageSize, "invalid PageSize") +sysAssert(roundup(15, 8) == 16, "roundup broken") +sysAssert(roundup(65, 8) == 72, "roundup broken 2") + # ------------ platform specific chunk allocation code ----------------------- # some platforms have really weird unmap behaviour: unmap(blockStart, PageSize) @@ -82,6 +91,21 @@ elif defined(windows): when reallyOsDealloc: virtualFree(p, 0, MEM_RELEASE) #VirtualFree(p, size, MEM_DECOMMIT) +elif hostOS == "standalone": + var + theHeap: array[1024*PageSize, float64] # 'float64' for alignment + bumpPointer = cast[int](addr theHeap) + + proc osAllocPages(size: int): pointer {.inline.} = + if size+bumpPointer < cast[int](addr theHeap) + sizeof(theHeap): + result = cast[pointer](bumpPointer) + inc bumpPointer, size + else: + raiseOutOfMem() + + proc osDeallocPages(p: pointer, size: int) {.inline.} = + if bumpPointer-size == cast[int](p): + dec bumpPointer, size else: {.error: "Port memory manager to your platform".} @@ -142,15 +166,6 @@ type template smallChunkOverhead(): expr = sizeof(SmallChunk)-sizeof(AlignType) template bigChunkOverhead(): expr = sizeof(BigChunk)-sizeof(AlignType) -proc roundup(x, v: int): int {.inline.} = - result = (x + (v-1)) and not (v-1) - sysAssert(result >= x, "roundup: result < x") - #return ((-x) and (v-1)) +% x - -sysAssert(roundup(14, PageSize) == PageSize, "invalid PageSize") -sysAssert(roundup(15, 8) == 16, "roundup broken") -sysAssert(roundup(65, 8) == 72, "roundup broken 2") - # ------------- chunk table --------------------------------------------------- # We use a PtrSet of chunk starts and a table[Page, chunksize] for chunk # endings of big chunks. This is needed by the merging operation. The only diff --git a/lib/system/cgprocs.nim b/lib/system/cgprocs.nim index 6cd2ef08c..660c68116 100644 --- a/lib/system/cgprocs.nim +++ b/lib/system/cgprocs.nim @@ -9,8 +9,6 @@ # Headers for procs that the code generator depends on ("compilerprocs") -proc addChar(s: NimString, c: char): NimString {.compilerProc, benign.} - type LibHandle = pointer # private type ProcAddr = pointer # library loading and loading of procs: @@ -21,6 +19,3 @@ proc nimUnloadLibrary(lib: LibHandle) {.compilerproc.} proc nimGetProcAddr(lib: LibHandle, name: cstring): ProcAddr {.compilerproc.} proc nimLoadLibraryError(path: string) {.compilerproc, noinline.} - -proc setStackBottom(theStackBottom: pointer) {.compilerRtl, noinline, benign.} - diff --git a/lib/system/mmdisp.nim b/lib/system/mmdisp.nim index 50f4cb4dc..8a946716d 100644 --- a/lib/system/mmdisp.nim +++ b/lib/system/mmdisp.nim @@ -34,7 +34,7 @@ const type PPointer = ptr pointer - ByteArray = array[0..1000_0000, byte] + ByteArray = array[0..ArrayDummySize, byte] PByte = ptr ByteArray PString = ptr string {.deprecated: [TByteArray: ByteArray].} @@ -42,7 +42,7 @@ type # Page size of the system; in most cases 4096 bytes. For exotic OS or # CPU this needs to be changed: const - PageShift = 12 + PageShift = when defined(cpu16): 8 else: 12 PageSize = 1 shl PageShift PageMask = PageSize-1 @@ -270,7 +270,10 @@ elif defined(gogc): # Statistics about allocation size classes. by_size: array[goNumSizeClasses, goMStats_inner_struct] - proc goRuntime_ReadMemStats(a2: ptr goMStats) {.cdecl, importc: "runtime_ReadMemStats", codegenDecl: "$1 $2$3 __asm__ (\"runtime.ReadMemStats\");\n$1 $2$3", dynlib: goLib.} + proc goRuntime_ReadMemStats(a2: ptr goMStats) {.cdecl, + importc: "runtime_ReadMemStats", + codegenDecl: "$1 $2$3 __asm__ (\"runtime.ReadMemStats\");\n$1 $2$3", + dynlib: goLib.} proc GC_getStatistics(): string = var mstats: goMStats diff --git a/tests/manyloc/standalone/barebone.nim.cfg b/tests/manyloc/standalone/barebone.nim.cfg index 52ec64e3f..bb350ff55 100644 --- a/tests/manyloc/standalone/barebone.nim.cfg +++ b/tests/manyloc/standalone/barebone.nim.cfg @@ -1,2 +1,3 @@ --os:standalone --deadCodeElim:on +--gc:none diff --git a/web/news.txt b/web/news.txt index be27d83e5..2d5b75207 100644 --- a/web/news.txt +++ b/web/news.txt @@ -23,6 +23,11 @@ News used: ``import "scene/2d/sprite"``. The former code never was valid Nim. - The Windows API wrapper (``windows.nim``) is now not part of the official distribution anymore. Instead use the ``oldwinapi`` Nimble package. + - There is now a clear distinction between ``--os:standalone`` + and ``--gc:none``. So if you use ``--os:standalone`` ensure you also use + ``--gc:none``. ``--os:standalone`` without ``--gc:none`` is now a version + that doesn't depend on any OS but includes the GC. However this version + is currently untested! Library additions From 63c537b233c1e7148b80c0bfc4e667b95117dc5a Mon Sep 17 00:00:00 2001 From: Araq Date: Mon, 29 Jun 2015 02:48:08 +0200 Subject: [PATCH 0585/1263] fixes #3014 --- lib/system/excpt.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/system/excpt.nim b/lib/system/excpt.nim index f157f428c..5d2faa2d6 100644 --- a/lib/system/excpt.nim +++ b/lib/system/excpt.nim @@ -63,7 +63,7 @@ proc pushCurrentException(e: ref Exception) {.compilerRtl, inl.} = currException = e proc popCurrentException {.compilerRtl, inl.} = - currException = currException.parent + currException = nil # currException.parent # some platforms have native support for stack traces: const From c16d153ff53732331e7a017a29fc13ccb681a402 Mon Sep 17 00:00:00 2001 From: Araq Date: Mon, 29 Jun 2015 15:10:29 +0200 Subject: [PATCH 0586/1263] fixes #3005 --- lib/pure/rawsockets.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/pure/rawsockets.nim b/lib/pure/rawsockets.nim index bd22af2d1..d0e3b4cf1 100644 --- a/lib/pure/rawsockets.nim +++ b/lib/pure/rawsockets.nim @@ -41,7 +41,7 @@ export SO_KEEPALIVE, SO_OOBINLINE, SO_REUSEADDR, MSG_PEEK -when defined(macosx): +when defined(macosx) and not defined(nimdoc): export SO_NOSIGPIPE type From 615defb1a9f4739f365ff56321cec0b1a0d1fde2 Mon Sep 17 00:00:00 2001 From: Dominik Picheta Date: Mon, 29 Jun 2015 20:11:21 +0100 Subject: [PATCH 0587/1263] Fixes socket problems on Windows and normalises some names. Ref #2976. Ref #2003. See news.txt for details. --- lib/pure/asyncdispatch.nim | 33 +++++++++++++++++---------------- lib/pure/asyncnet.nim | 37 ++++++++++++++++++++++--------------- lib/pure/net.nim | 37 +++++++++++++++++++++++-------------- lib/pure/rawsockets.nim | 19 ++++++++++--------- web/news.txt | 7 ++++++- 5 files changed, 78 insertions(+), 55 deletions(-) diff --git a/lib/pure/asyncdispatch.nim b/lib/pure/asyncdispatch.nim index 547880f06..3d1992244 100644 --- a/lib/pure/asyncdispatch.nim +++ b/lib/pure/asyncdispatch.nim @@ -483,7 +483,7 @@ when defined(windows) or defined(nimdoc): RemoteSockaddr, RemoteSockaddrLength) proc connect*(socket: AsyncFD, address: string, port: Port, - af = rawsockets.AF_INET): Future[void] = + domain = rawsockets.AF_INET): Future[void] = ## Connects ``socket`` to server at ``address:port``. ## ## Returns a ``Future`` which will complete when the connection succeeds @@ -492,14 +492,14 @@ when defined(windows) or defined(nimdoc): var retFuture = newFuture[void]("connect") # Apparently ``ConnectEx`` expects the socket to be initially bound: var saddr: Sockaddr_in - saddr.sin_family = int16(toInt(af)) + saddr.sin_family = int16(toInt(domain)) saddr.sin_port = 0 saddr.sin_addr.s_addr = INADDR_ANY if bindAddr(socket.SocketHandle, cast[ptr SockAddr](addr(saddr)), sizeof(saddr).SockLen) < 0'i32: raiseOSError(osLastError()) - var aiList = getAddrInfo(address, port, af) + var aiList = getAddrInfo(address, port, domain) var success = false var lastError: OSErrorCode var it = aiList @@ -855,17 +855,17 @@ when defined(windows) or defined(nimdoc): return retFuture - proc newAsyncRawSocket*(domain, typ, protocol: cint): AsyncFD = + proc newAsyncRawSocket*(domain, sockType, protocol: cint): AsyncFD = ## Creates a new socket and registers it with the dispatcher implicitly. - result = newRawSocket(domain, typ, protocol).AsyncFD + result = newRawSocket(domain, sockType, protocol).AsyncFD result.SocketHandle.setBlocking(false) register(result) proc newAsyncRawSocket*(domain: Domain = rawsockets.AF_INET, - typ: SockType = SOCK_STREAM, + sockType: SockType = SOCK_STREAM, protocol: Protocol = IPPROTO_TCP): AsyncFD = ## Creates a new socket and registers it with the dispatcher implicitly. - result = newRawSocket(domain, typ, protocol).AsyncFD + result = newRawSocket(domain, sockType, protocol).AsyncFD result.SocketHandle.setBlocking(false) register(result) @@ -928,17 +928,18 @@ else: var data = PData(fd: fd, readCBs: @[], writeCBs: @[]) p.selector.register(fd.SocketHandle, {}, data.RootRef) - proc newAsyncRawSocket*(domain: cint, typ: cint, protocol: cint): AsyncFD = - result = newRawSocket(domain, typ, protocol).AsyncFD + proc newAsyncRawSocket*(domain: cint, sockType: cint, + protocol: cint): AsyncFD = + result = newRawSocket(domain, sockType, protocol).AsyncFD result.SocketHandle.setBlocking(false) when defined(macosx): result.SocketHandle.setSockOptInt(SOL_SOCKET, SO_NOSIGPIPE, 1) register(result) proc newAsyncRawSocket*(domain: Domain = AF_INET, - typ: SockType = SOCK_STREAM, + sockType: SockType = SOCK_STREAM, protocol: Protocol = IPPROTO_TCP): AsyncFD = - result = newRawSocket(domain, typ, protocol).AsyncFD + result = newRawSocket(domain, sockType, protocol).AsyncFD result.SocketHandle.setBlocking(false) when defined(macosx): result.SocketHandle.setSockOptInt(SOL_SOCKET, SO_NOSIGPIPE, 1) @@ -1009,7 +1010,7 @@ else: processTimers(p) proc connect*(socket: AsyncFD, address: string, port: Port, - af_unused = AF_INET): Future[void] = + domain = AF_INET): Future[void] = var retFuture = newFuture[void]("connect") proc cb(fd: AsyncFD): bool = @@ -1017,8 +1018,8 @@ else: retFuture.complete() return true - var sockDomain = getSockDomain(socket.SocketHandle) - var aiList = getAddrInfo(address, port, sockDomain) + assert getSockDomain(socket.SocketHandle) == domain + var aiList = getAddrInfo(address, port, domain) var success = false var lastError: OSErrorCode var it = aiList @@ -1496,8 +1497,8 @@ macro async*(prc: stmt): stmt {.immediate.} = result[6] = outerProcBody #echo(treeRepr(result)) - #if prc[0].getName == "test": - # echo(toStrLit(result)) + if prc[0].getName == "getAsync": + echo(toStrLit(result)) proc recvLine*(socket: AsyncFD): Future[string] {.async.} = ## Reads a line of data from ``socket``. Returned future will complete once diff --git a/lib/pure/asyncnet.nim b/lib/pure/asyncnet.nim index d7ac60147..cfd3d7666 100644 --- a/lib/pure/asyncnet.nim +++ b/lib/pure/asyncnet.nim @@ -85,35 +85,44 @@ type bioIn: BIO bioOut: BIO of false: nil + domain: Domain + sockType: SockType + protocol: Protocol AsyncSocket* = ref AsyncSocketDesc {.deprecated: [PAsyncSocket: AsyncSocket].} -# TODO: Save AF, domain etc info and reuse it in procs which need it like connect. - -proc newAsyncSocket*(fd: AsyncFD, buffered = true): AsyncSocket = +proc newAsyncSocket*(fd: AsyncFD, domain: Domain = AF_INET, + sockType: SockType = SOCK_STREAM, + protocol: Protocol = IPPROTO_TCP, buffered = true): AsyncSocket = ## Creates a new ``AsyncSocket`` based on the supplied params. assert fd != osInvalidSocket.AsyncFD new(result) result.fd = fd.SocketHandle result.isBuffered = buffered + result.domain = domain + result.sockType = sockType + result.protocol = protocol if buffered: result.currPos = 0 -proc newAsyncSocket*(domain: Domain = AF_INET6, typ: SockType = SOCK_STREAM, +proc newAsyncSocket*(domain: Domain = AF_INET, sockType: SockType = SOCK_STREAM, protocol: Protocol = IPPROTO_TCP, buffered = true): AsyncSocket = ## Creates a new asynchronous socket. ## ## This procedure will also create a brand new file descriptor for ## this socket. - result = newAsyncSocket(newAsyncRawSocket(domain, typ, protocol), buffered) + result = newAsyncSocket(newAsyncRawSocket(domain, sockType, protocol), domain, + sockType, protocol, buffered) -proc newAsyncSocket*(domain, typ, protocol: cint, buffered = true): AsyncSocket = +proc newAsyncSocket*(domain, sockType, protocol: cint, + buffered = true): AsyncSocket = ## Creates a new asynchronous socket. ## ## This procedure will also create a brand new file descriptor for ## this socket. - result = newAsyncSocket(newAsyncRawSocket(domain, typ, protocol), buffered) + result = newAsyncSocket(newAsyncRawSocket(domain, sockType, protocol), + Domain(domain), SockType(sockType), Protocol(protocol), buffered) when defined(ssl): proc getSslError(handle: SslPtr, err: cint): cint = @@ -169,13 +178,12 @@ when defined(ssl): let err = getSslError(socket.sslHandle, opResult.cint) yield appeaseSsl(socket, flags, err.cint) -proc connect*(socket: AsyncSocket, address: string, port: Port, - af = AF_INET) {.async.} = +proc connect*(socket: AsyncSocket, address: string, port: Port) {.async.} = ## Connects ``socket`` to server at ``address:port``. ## ## Returns a ``Future`` which will complete when the connection succeeds ## or an error occurs. - await connect(socket.fd.AsyncFD, address, port, af) + await connect(socket.fd.AsyncFD, address, port, socket.domain) if socket.isSsl: when defined(ssl): let flags = {SocketFlag.SafeDisconn} @@ -287,7 +295,8 @@ proc acceptAddr*(socket: AsyncSocket, flags = {SocketFlag.SafeDisconn}): retFuture.fail(future.readError) else: let resultTup = (future.read.address, - newAsyncSocket(future.read.client, socket.isBuffered)) + newAsyncSocket(future.read.client, socket.domain, + socket.sockType, socket.protocol, socket.isBuffered)) retFuture.complete(resultTup) return retFuture @@ -423,17 +432,15 @@ proc bindAddr*(socket: AsyncSocket, port = Port(0), address = "") {. ## Binds ``address``:``port`` to the socket. ## ## If ``address`` is "" then ADDR_ANY will be bound. - var sockDomain = getSockDomain(socket.fd) - var realaddr = address if realaddr == "": - case sockDomain + case socket.domain of AF_INET6: realaddr = "::" of AF_INET: realaddr = "0.0.0.0" else: raiseOSError("Unknown socket address family and no address specified to bindAddr") - var aiList = getAddrInfo(realaddr, port, sockDomain) + var aiList = getAddrInfo(realaddr, port, socket.domain) if bindAddr(socket.fd, aiList.ai_addr, aiList.ai_addrlen.Socklen) < 0'i32: dealloc(aiList) raiseOSError(osLastError()) diff --git a/lib/pure/net.nim b/lib/pure/net.nim index 29e115da1..d9f4845f3 100644 --- a/lib/pure/net.nim +++ b/lib/pure/net.nim @@ -64,6 +64,9 @@ type sslPeekChar: char of false: nil lastError: OSErrorCode ## stores the last error on this socket + domain: Domain + sockType: SockType + protocol: Protocol Socket* = ref SocketImpl @@ -124,33 +127,39 @@ proc toOSFlags*(socketFlags: set[SocketFlag]): cint = result = result or MSG_PEEK of SocketFlag.SafeDisconn: continue -proc newSocket*(fd: SocketHandle, buffered = true): Socket = +proc newSocket*(fd: SocketHandle, domain: Domain = AF_INET, + sockType: SockType = SOCK_STREAM, + protocol: Protocol = IPPROTO_TCP, buffered = true): Socket = ## Creates a new socket as specified by the params. assert fd != osInvalidSocket new(result) result.fd = fd result.isBuffered = buffered + result.domain = domain + result.sockType = sockType + result.protocol = protocol if buffered: result.currPos = 0 -proc newSocket*(domain, typ, protocol: cint, buffered = true): Socket = +proc newSocket*(domain, sockType, protocol: cint, buffered = true): Socket = ## Creates a new socket. ## ## If an error occurs EOS will be raised. - let fd = newRawSocket(domain, typ, protocol) + let fd = newRawSocket(domain, sockType, protocol) if fd == osInvalidSocket: raiseOSError(osLastError()) - result = newSocket(fd, buffered) + result = newSocket(fd, domain.Domain, sockType.SockType, protocol.Protocol, + buffered) -proc newSocket*(domain: Domain = AF_INET, typ: SockType = SOCK_STREAM, +proc newSocket*(domain: Domain = AF_INET, sockType: SockType = SOCK_STREAM, protocol: Protocol = IPPROTO_TCP, buffered = true): Socket = ## Creates a new socket. ## ## If an error occurs EOS will be raised. - let fd = newRawSocket(domain, typ, protocol) + let fd = newRawSocket(domain, sockType, protocol) if fd == osInvalidSocket: raiseOSError(osLastError()) - result = newSocket(fd, buffered) + result = newSocket(fd, domain, sockType, protocol, buffered) when defined(ssl): CRYPTO_malloc_init() @@ -371,7 +380,7 @@ proc bindAddr*(socket: Socket, port = Port(0), address = "") {. sizeof(name).SockLen) < 0'i32: raiseOSError(osLastError()) else: - var aiList = getAddrInfo(address, port, AF_INET) + var aiList = getAddrInfo(address, port, socket.domain) if bindAddr(socket.fd, aiList.ai_addr, aiList.ai_addrlen.SockLen) < 0'i32: dealloc(aiList) raiseOSError(osLastError()) @@ -532,15 +541,15 @@ proc setSockOpt*(socket: Socket, opt: SOBool, value: bool, level = SOL_SOCKET) { var valuei = cint(if value: 1 else: 0) setSockOptInt(socket.fd, cint(level), toCInt(opt), valuei) -proc connect*(socket: Socket, address: string, port = Port(0), - af: Domain = AF_INET) {.tags: [ReadIOEffect].} = +proc connect*(socket: Socket, address: string, + port = Port(0)) {.tags: [ReadIOEffect].} = ## Connects socket to ``address``:``port``. ``Address`` can be an IP address or a ## host name. If ``address`` is a host name, this function will try each IP ## of that host name. ``htons`` is already performed on ``port`` so you must ## not do it. ## ## If ``socket`` is an SSL socket a handshake will be automatically performed. - var aiList = getAddrInfo(address, port, af) + var aiList = getAddrInfo(address, port, socket.domain) # try all possibilities: var success = false var lastError: OSErrorCode @@ -992,15 +1001,15 @@ proc connectAsync(socket: Socket, name: string, port = Port(0), dealloc(aiList) if not success: raiseOSError(lastError) -proc connect*(socket: Socket, address: string, port = Port(0), timeout: int, - af: Domain = AF_INET) {.tags: [ReadIOEffect, WriteIOEffect].} = +proc connect*(socket: Socket, address: string, port = Port(0), + timeout: int) {.tags: [ReadIOEffect, WriteIOEffect].} = ## Connects to server as specified by ``address`` on port specified by ``port``. ## ## The ``timeout`` paremeter specifies the time in milliseconds to allow for ## the connection to the server to be made. socket.fd.setBlocking(false) - socket.connectAsync(address, port, af) + socket.connectAsync(address, port, socket.domain) var s = @[socket.fd] if selectWrite(s, timeout) != 1: raise newException(TimeoutError, "Call to 'connect' timed out.") diff --git a/lib/pure/rawsockets.nim b/lib/pure/rawsockets.nim index d0e3b4cf1..349b0d97a 100644 --- a/lib/pure/rawsockets.nim +++ b/lib/pure/rawsockets.nim @@ -157,17 +157,17 @@ else: result = cint(ord(p)) -proc newRawSocket*(domain: Domain = AF_INET, typ: SockType = SOCK_STREAM, +proc newRawSocket*(domain: Domain = AF_INET, sockType: SockType = SOCK_STREAM, protocol: Protocol = IPPROTO_TCP): SocketHandle = ## Creates a new socket; returns `InvalidSocket` if an error occurs. - socket(toInt(domain), toInt(typ), toInt(protocol)) + socket(toInt(domain), toInt(sockType), toInt(protocol)) -proc newRawSocket*(domain: cint, typ: cint, protocol: cint): SocketHandle = +proc newRawSocket*(domain: cint, sockType: cint, protocol: cint): SocketHandle = ## Creates a new socket; returns `InvalidSocket` if an error occurs. ## ## Use this overload if one of the enums specified above does ## not contain what you need. - socket(domain, typ, protocol) + socket(domain, sockType, protocol) proc close*(socket: SocketHandle) = ## closes a socket. @@ -190,16 +190,17 @@ proc listen*(socket: SocketHandle, backlog = SOMAXCONN): cint {.tags: [ReadIOEff else: result = posix.listen(socket, cint(backlog)) -proc getAddrInfo*(address: string, port: Port, af: Domain = AF_INET, typ: SockType = SOCK_STREAM, - prot: Protocol = IPPROTO_TCP): ptr AddrInfo = +proc getAddrInfo*(address: string, port: Port, domain: Domain = AF_INET, + sockType: SockType = SOCK_STREAM, + protocol: Protocol = IPPROTO_TCP): ptr AddrInfo = ## ## ## **Warning**: The resulting ``ptr TAddrInfo`` must be freed using ``dealloc``! var hints: AddrInfo result = nil - hints.ai_family = toInt(af) - hints.ai_socktype = toInt(typ) - hints.ai_protocol = toInt(prot) + hints.ai_family = toInt(domain) + hints.ai_socktype = toInt(sockType) + hints.ai_protocol = toInt(protocol) hints.ai_flags = AI_V4MAPPED var gaiResult = getaddrinfo(address, $port, addr(hints), result) if gaiResult != 0'i32: diff --git a/web/news.txt b/web/news.txt index 2d5b75207..639ebe946 100644 --- a/web/news.txt +++ b/web/news.txt @@ -28,7 +28,12 @@ News ``--gc:none``. ``--os:standalone`` without ``--gc:none`` is now a version that doesn't depend on any OS but includes the GC. However this version is currently untested! - + - All procedures which construct a ``Socket``/``AsyncSocket`` now need to + specify the socket domain, type and protocol. The param name + ``typ: SockType`` (in ``newSocket``/``newAsyncSocket`` procs) was also + renamed to ``sockType``. The param ``af`` in the ``connect`` procs was + removed. This affects ``asyncnet``, ``asyncdispatch``, ``net``, and + ``rawsockets``. Library additions ----------------- From 8ef0d9386bba0e3b94a20746c61c62fa8d28e160 Mon Sep 17 00:00:00 2001 From: Dominik Picheta Date: Mon, 29 Jun 2015 21:39:45 +0100 Subject: [PATCH 0588/1263] Implements ``os.expandSymlink``. Ref #3015. --- lib/pure/os.nim | 16 ++++++++++++++++ web/news.txt | 1 + 2 files changed, 17 insertions(+) diff --git a/lib/pure/os.nim b/lib/pure/os.nim index 6f8d923e3..f4796433d 100644 --- a/lib/pure/os.nim +++ b/lib/pure/os.nim @@ -1645,6 +1645,22 @@ proc getTempDir*(): string {.rtl, extern: "nos$1", tags: [ReadEnvEffect].} = when defined(windows): return string(getEnv("TEMP")) & "\\" else: return "/tmp/" +proc expandSymlink*(symlinkPath: string): string = + ## Returns a string representing the path to which the symbolic link points. + ## + ## On Windows this is a noop, ``symlinkPath`` is simply returned. + when defined(windows): + result = symlinkPath + else: + result = newString(256) + var len = readlink(symlinkPath, result, 256) + if len < 0: + raiseOSError(osLastError()) + if len > 256: + result = newString(len+1) + len = readlink(symlinkPath, result, len) + setLen(result, len) + when defined(nimdoc): # Common forward declaration docstring block for parameter retrieval procs. proc paramCount*(): int {.tags: [ReadIOEffect].} = diff --git a/web/news.txt b/web/news.txt index 639ebe946..0e137a805 100644 --- a/web/news.txt +++ b/web/news.txt @@ -40,6 +40,7 @@ News - The nre module has been added, providing a better interface to PCRE than re. + - The ``expandSymlink`` procedure has been added to the ``os`` module. Language Additions ------------------ From 6aae246ef156ed7716b6df79365220afa6267fc0 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Mon, 29 Jun 2015 16:52:47 -0400 Subject: [PATCH 0589/1263] Fix #3018 Looks like the problem is that the compiler expected the hash to be a certain number of characters, but the file actually contained a (shorter) crc hash. --- compiler/extccomp.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/extccomp.nim b/compiler/extccomp.nim index 2c6e5294f..8d3260275 100644 --- a/compiler/extccomp.nim +++ b/compiler/extccomp.nim @@ -585,7 +585,7 @@ proc externalFileChanged(filename: string): bool = if gCmd notin {cmdCompileToC, cmdCompileToCpp, cmdCompileToOC, cmdCompileToLLVM}: return false - var crcFile = toGeneratedFile(filename.withPackageName, "crc") + var crcFile = toGeneratedFile(filename.withPackageName, "sha1") var currentCrc = footprint(filename) var f: File if open(f, crcFile, fmRead): From 9e8c8f473bfeaab482c4342e9756a108b6d5803b Mon Sep 17 00:00:00 2001 From: apense Date: Mon, 29 Jun 2015 22:48:38 -0400 Subject: [PATCH 0590/1263] Added some documentation and examples I think I remember reading that the documentation is generated from the normal targets (not javascript), so that's where I put the docs --- lib/pure/math.nim | 67 +++++++++++++++++++++++++++++++++-------------- 1 file changed, 47 insertions(+), 20 deletions(-) diff --git a/lib/pure/math.nim b/lib/pure/math.nim index d3f1f3814..e36e509be 100644 --- a/lib/pure/math.nim +++ b/lib/pure/math.nim @@ -56,7 +56,7 @@ type fcNegInf ## value is negative infinity proc classify*(x: float): FloatClass = - ## classifies a floating point value. Returns `x`'s class as specified by + ## Classifies a floating point value. Returns `x`'s class as specified by ## `FloatClass`. # JavaScript and most C compilers have no classify: @@ -74,7 +74,7 @@ proc classify*(x: float): FloatClass = proc binom*(n, k: int): int {.noSideEffect.} = - ## computes the binomial coefficient + ## Computes the binomial coefficient if k <= 0: return 1 if 2*k > n: return binom(n, n-k) result = n @@ -82,18 +82,18 @@ proc binom*(n, k: int): int {.noSideEffect.} = result = (result * (n + 1 - i)) div i proc fac*(n: int): int {.noSideEffect.} = - ## computes the faculty/factorial function. + ## Computes the faculty/factorial function. result = 1 for i in countup(2, n): result = result * i proc isPowerOfTwo*(x: int): bool {.noSideEffect.} = - ## returns true, if `x` is a power of two, false otherwise. + ## Returns true, if `x` is a power of two, false otherwise. ## Zero and negative numbers are not a power of two. return (x > 0) and ((x and (x - 1)) == 0) proc nextPowerOfTwo*(x: int): int {.noSideEffect.} = - ## returns `x` rounded up to the nearest power of two. + ## Returns `x` rounded up to the nearest power of two. ## Zero and negative numbers get rounded up to 1. result = x - 1 when defined(cpu64): @@ -108,28 +108,28 @@ proc nextPowerOfTwo*(x: int): int {.noSideEffect.} = result += 1 + ord(x<=0) proc countBits32*(n: int32): int {.noSideEffect.} = - ## counts the set bits in `n`. + ## Counts the set bits in `n`. var v = n v = v -% ((v shr 1'i32) and 0x55555555'i32) v = (v and 0x33333333'i32) +% ((v shr 2'i32) and 0x33333333'i32) result = ((v +% (v shr 4'i32) and 0xF0F0F0F'i32) *% 0x1010101'i32) shr 24'i32 proc sum*[T](x: openArray[T]): T {.noSideEffect.} = - ## computes the sum of the elements in `x`. + ## Computes the sum of the elements in `x`. ## If `x` is empty, 0 is returned. for i in items(x): result = result + i template toFloat(f: float): float = f proc mean*[T](x: openArray[T]): float {.noSideEffect.} = - ## computes the mean of the elements in `x`, which are first converted to floats. + ## Computes the mean of the elements in `x`, which are first converted to floats. ## If `x` is empty, NaN is returned. ## ``toFloat(x: T): float`` must be defined. for i in items(x): result = result + toFloat(i) result = result / toFloat(len(x)) proc variance*[T](x: openArray[T]): float {.noSideEffect.} = - ## computes the variance of the elements in `x`. + ## Computes the variance of the elements in `x`. ## If `x` is empty, NaN is returned. ## ``toFloat(x: T): float`` must be defined. result = 0.0 @@ -140,41 +140,43 @@ proc variance*[T](x: openArray[T]): float {.noSideEffect.} = result = result / toFloat(len(x)) proc random*(max: int): int {.benign.} - ## returns a random number in the range 0..max-1. The sequence of + ## Returns a random number in the range 0..max-1. The sequence of ## random number is always the same, unless `randomize` is called ## which initializes the random number generator with a "random" ## number, i.e. a tickcount. proc random*(max: float): float {.benign.} - ## returns a random number in the range 0..".} - ## computes the square root of `x`. + ## Computes the square root of `x`. proc cbrt*(x: float): float {.importc: "cbrt", header: "".} - ## computes the cubic root of `x` + ## Computes the cubic root of `x` proc ln*(x: float): float {.importc: "log", header: "".} - ## computes ln(x). + ## Computes the natural log of `x` proc log10*(x: float): float {.importc: "log10", header: "".} + ## Computes the common logarithm (base 10) of `x` proc log2*(x: float): float = return ln(x) / ln(2.0) + ## Computes the binary logarithm (base 2) of `x` proc exp*(x: float): float {.importc: "exp", header: "".} - ## computes e**x. + ## Computes the exponential function of `x` (pow(E, x)) proc frexp*(x: float, exponent: var int): float {. importc: "frexp", header: "".} @@ -185,11 +187,14 @@ when not defined(JS): ## m. proc round*(x: float): int {.importc: "lrint", header: "".} - ## converts a float to an int by rounding. + ## Converts a float to an int by rounding. proc arccos*(x: float): float {.importc: "acos", header: "".} + ## Computes the arc cosine of `x` proc arcsin*(x: float): float {.importc: "asin", header: "".} + ## Computes the arc sine of `x` proc arctan*(x: float): float {.importc: "atan", header: "".} + ## Calculate the arc tangent of `y` / `x` proc arctan2*(y, x: float): float {.importc: "atan2", header: "".} ## Calculate the arc tangent of `y` / `x`. ## `atan2` returns the arc tangent of `y` / `x`; it produces correct @@ -197,16 +202,22 @@ when not defined(JS): ## (`x` near 0). proc cos*(x: float): float {.importc: "cos", header: "".} + ## Computes the cosine of `x` proc cosh*(x: float): float {.importc: "cosh", header: "".} + ## Computes the hyperbolic cosine of `x` proc hypot*(x, y: float): float {.importc: "hypot", header: "".} - ## same as ``sqrt(x*x + y*y)``. + ## Computes the distance between `x` and `y`. Equivalent to ``sqrt(x*x + y*y)``. proc sinh*(x: float): float {.importc: "sinh", header: "".} + ## Computes the hyperbolic sine of `x` proc sin*(x: float): float {.importc: "sin", header: "".} + ## Computes the sine of `x` proc tan*(x: float): float {.importc: "tan", header: "".} + ## Computes the tangent of `x` proc tanh*(x: float): float {.importc: "tanh", header: "".} + ## Computes the hyperbolic tangent of `x` proc pow*(x, y: float): float {.importc: "pow", header: "".} - ## computes x to power raised of y. + ## Computes `x` to power of `y`. proc erf*(x: float): float {.importc: "erf", header: "".} ## The error function @@ -269,10 +280,26 @@ when not defined(JS): result = int(rand()) mod max proc trunc*(x: float): float {.importc: "trunc", header: "".} + ## Truncates `x` to the decimal point + ## + ## .. code-block:: nim + ## echo trunc(PI) # 3.0 proc floor*(x: float): float {.importc: "floor", header: "".} + ## Computes the floor function (i.e., the largest integer not greater than `x`) + ## + ## .. code-block:: nim + ## echo floor(-3.5) ## -4.0 proc ceil*(x: float): float {.importc: "ceil", header: "".} + ## Computes the ceiling function (i.e., the smallest integer not less than `x`) + ## + ## .. code-block:: nim + ## echo ceil(-2.1) ## -2.0 proc fmod*(x, y: float): float {.importc: "fmod", header: "".} + ## Computes the remainder of `x` divided by `y` + ## + ## .. code-block:: nim + ## echo fmod(-2.5, 0.3) ## -0.1 else: proc mathrandom(): float {.importc: "Math.random", nodecl.} From c3e6fb0e385bdd57ffd040f8e619375bce46318d Mon Sep 17 00:00:00 2001 From: apense Date: Mon, 29 Jun 2015 23:07:06 -0400 Subject: [PATCH 0591/1263] Corrected erroneous description Hypotenuse is really just the euclidean norm --- lib/pure/math.nim | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/pure/math.nim b/lib/pure/math.nim index e36e509be..821ab738b 100644 --- a/lib/pure/math.nim +++ b/lib/pure/math.nim @@ -206,7 +206,8 @@ when not defined(JS): proc cosh*(x: float): float {.importc: "cosh", header: "".} ## Computes the hyperbolic cosine of `x` proc hypot*(x, y: float): float {.importc: "hypot", header: "".} - ## Computes the distance between `x` and `y`. Equivalent to ``sqrt(x*x + y*y)``. + ## Computes the hypotenuse of a right-angle triangle with `x` and + ## `y` as its base and height. Equivalent to ``sqrt(x*x + y*y)``. proc sinh*(x: float): float {.importc: "sinh", header: "".} ## Computes the hyperbolic sine of `x` From 5fcb7ca3134e0b584d9514e580b5a900e5c3af69 Mon Sep 17 00:00:00 2001 From: Araq Date: Tue, 30 Jun 2015 12:08:09 +0200 Subject: [PATCH 0592/1263] True is true --- lib/pure/os.nim | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/pure/os.nim b/lib/pure/os.nim index f4796433d..7ba48651e 100644 --- a/lib/pure/os.nim +++ b/lib/pure/os.nim @@ -81,7 +81,7 @@ when defined(Nimdoc): # only for proper documentation: ## Windows. FileSystemCaseSensitive* = true - ## True if the file system is case sensitive, false otherwise. Used by + ## true if the file system is case sensitive, false otherwise. Used by ## `cmpPaths` to compare filenames properly. ExeExt* = "" @@ -817,7 +817,7 @@ when defined(Windows): proc sameFile*(path1, path2: string): bool {.rtl, extern: "nos$1", tags: [ReadDirEffect].} = - ## Returns True if both pathname arguments refer to the same physical + ## Returns true if both pathname arguments refer to the same physical ## file or directory. Raises an exception if any of the files does not ## exist or information about it can not be obtained. ## @@ -857,7 +857,7 @@ proc sameFile*(path1, path2: string): bool {.rtl, extern: "nos$1", proc sameFileContent*(path1, path2: string): bool {.rtl, extern: "nos$1", tags: [ReadIOEffect].} = - ## Returns True if both pathname arguments refer to files with identical + ## Returns true if both pathname arguments refer to files with identical ## binary content. const bufSize = 8192 # 8K buffer From 1af20535d8105287aa8c73ff1a90e102c4590ffb Mon Sep 17 00:00:00 2001 From: Araq Date: Tue, 30 Jun 2015 12:19:24 +0200 Subject: [PATCH 0593/1263] updated links to source code --- tools/nimweb.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/nimweb.nim b/tools/nimweb.nim index 852b43092..1aef20dcc 100644 --- a/tools/nimweb.nim +++ b/tools/nimweb.nim @@ -48,7 +48,7 @@ proc initConfigData(c: var TConfigData) = c.logo = "" c.ticker = "" c.vars = newStringTable(modeStyleInsensitive) - c.gitRepo = "https://github.com/Araq/Nim/tree" + c.gitRepo = "https://github.com/nim-lang/Nim/tree" c.gitCommit = "master" c.numProcessors = countProcessors() # Attempts to obtain the git current commit. From 4cfe216a776ffef61380c1c5f2d61aff7315c122 Mon Sep 17 00:00:00 2001 From: Araq Date: Tue, 30 Jun 2015 12:19:47 +0200 Subject: [PATCH 0594/1263] fixes #2880 --- compiler/ccgexprs.nim | 10 +- tests/ccgbugs/twrong_setconstr.nim | 146 +++++++++++++++++++++++++++++ 2 files changed, 151 insertions(+), 5 deletions(-) create mode 100644 tests/ccgbugs/twrong_setconstr.nim diff --git a/compiler/ccgexprs.nim b/compiler/ccgexprs.nim index 10b5b1251..493749848 100644 --- a/compiler/ccgexprs.nim +++ b/compiler/ccgexprs.nim @@ -1483,11 +1483,11 @@ proc genSetOp(p: BProc, e: PNode, d: var TLoc, op: TMagic) = of 1, 2, 4, 8: case op of mIncl: - var ts = "NI" & $(size * 8) + var ts = "NU" & $(size * 8) binaryStmtInExcl(p, e, d, "$1 |= ((" & ts & ")1)<<(($2)%(sizeof(" & ts & ")*8));$n") of mExcl: - var ts = "NI" & $(size * 8) + var ts = "NU" & $(size * 8) binaryStmtInExcl(p, e, d, "$1 &= ~(((" & ts & ")1) << (($2) % (sizeof(" & ts & ")*8)));$n") of mCard: @@ -1799,7 +1799,7 @@ proc genSetConstr(p: BProc, e: PNode, d: var TLoc) = [rdLoc(d), rdSetElemLoc(a, e.typ)]) else: # small set - var ts = "NI" & $(getSize(e.typ) * 8) + var ts = "NU" & $(getSize(e.typ) * 8) lineF(p, cpsStmts, "$1 = 0;$n", [rdLoc(d)]) for i in countup(0, sonsLen(e) - 1): if e.sons[i].kind == nkRange: @@ -1807,13 +1807,13 @@ proc genSetConstr(p: BProc, e: PNode, d: var TLoc) = initLocExpr(p, e.sons[i].sons[0], a) initLocExpr(p, e.sons[i].sons[1], b) lineF(p, cpsStmts, "for ($1 = $3; $1 <= $4; $1++) $n" & - "$2 |=(1<<((" & ts & ")($1)%(sizeof(" & ts & ")*8)));$n", [ + "$2 |=((" & ts & ")(1)<<(($1)%(sizeof(" & ts & ")*8)));$n", [ rdLoc(idx), rdLoc(d), rdSetElemLoc(a, e.typ), rdSetElemLoc(b, e.typ)]) else: initLocExpr(p, e.sons[i], a) lineF(p, cpsStmts, - "$1 |=(1<<((" & ts & ")($2)%(sizeof(" & ts & ")*8)));$n", + "$1 |=((" & ts & ")(1)<<(($2)%(sizeof(" & ts & ")*8)));$n", [rdLoc(d), rdSetElemLoc(a, e.typ)]) proc genTupleConstr(p: BProc, n: PNode, d: var TLoc) = diff --git a/tests/ccgbugs/twrong_setconstr.nim b/tests/ccgbugs/twrong_setconstr.nim new file mode 100644 index 000000000..f03ffd928 --- /dev/null +++ b/tests/ccgbugs/twrong_setconstr.nim @@ -0,0 +1,146 @@ +discard """ + output: "" +""" + +# bug #2880 + +type + TMsgKind* = enum + errUnknown, errIllFormedAstX, errInternal, errCannotOpenFile, errGenerated, + errXCompilerDoesNotSupportCpp, errStringLiteralExpected, + errIntLiteralExpected, errInvalidCharacterConstant, + errClosingTripleQuoteExpected, errClosingQuoteExpected, + errTabulatorsAreNotAllowed, errInvalidToken, errLineTooLong, + errInvalidNumber, errInvalidNumberOctalCode, errNumberOutOfRange, + errNnotAllowedInCharacter, errClosingBracketExpected, errMissingFinalQuote, + errIdentifierExpected, errNewlineExpected, errInvalidModuleName, + errOperatorExpected, errTokenExpected, errStringAfterIncludeExpected, + errRecursiveDependencyX, errOnOrOffExpected, errNoneSpeedOrSizeExpected, + errInvalidPragma, errUnknownPragma, errInvalidDirectiveX, + errAtPopWithoutPush, errEmptyAsm, errInvalidIndentation, + errExceptionExpected, errExceptionAlreadyHandled, + errYieldNotAllowedHere, errYieldNotAllowedInTryStmt, + errInvalidNumberOfYieldExpr, errCannotReturnExpr, errAttemptToRedefine, + errStmtInvalidAfterReturn, errStmtExpected, errInvalidLabel, + errInvalidCmdLineOption, errCmdLineArgExpected, errCmdLineNoArgExpected, + errInvalidVarSubstitution, errUnknownVar, errUnknownCcompiler, + errOnOrOffExpectedButXFound, errOnOffOrListExpectedButXFound, + errNoneBoehmRefcExpectedButXFound, + errNoneSpeedOrSizeExpectedButXFound, errGuiConsoleOrLibExpectedButXFound, + errUnknownOS, errUnknownCPU, errGenOutExpectedButXFound, + errArgsNeedRunOption, errInvalidMultipleAsgn, errColonOrEqualsExpected, + errExprExpected, errUndeclaredIdentifier, errUseQualifier, errTypeExpected, + errSystemNeeds, errExecutionOfProgramFailed, errNotOverloadable, + errInvalidArgForX, errStmtHasNoEffect, errXExpectsTypeOrValue, + errXExpectsArrayType, errIteratorCannotBeInstantiated, errExprXAmbiguous, + errConstantDivisionByZero, errOrdinalTypeExpected, + errOrdinalOrFloatTypeExpected, errOverOrUnderflow, + errCannotEvalXBecauseIncompletelyDefined, errChrExpectsRange0_255, + errDynlibRequiresExportc, errUndeclaredFieldX, errNilAccess, + errIndexOutOfBounds, errIndexTypesDoNotMatch, errBracketsInvalidForType, + errValueOutOfSetBounds, errFieldInitTwice, errFieldNotInit, + errExprXCannotBeCalled, errExprHasNoType, errExprXHasNoType, + errCastNotInSafeMode, errExprCannotBeCastedToX, errCommaOrParRiExpected, + errCurlyLeOrParLeExpected, errSectionExpected, errRangeExpected, + errMagicOnlyInSystem, errPowerOfTwoExpected, + errStringMayNotBeEmpty, errCallConvExpected, errProcOnlyOneCallConv, + errSymbolMustBeImported, errExprMustBeBool, errConstExprExpected, + errDuplicateCaseLabel, errRangeIsEmpty, errSelectorMustBeOfCertainTypes, + errSelectorMustBeOrdinal, errOrdXMustNotBeNegative, errLenXinvalid, + errWrongNumberOfVariables, errExprCannotBeRaised, errBreakOnlyInLoop, + errTypeXhasUnknownSize, errConstNeedsConstExpr, errConstNeedsValue, + errResultCannotBeOpenArray, errSizeTooBig, errSetTooBig, + errBaseTypeMustBeOrdinal, errInheritanceOnlyWithNonFinalObjects, + errInheritanceOnlyWithEnums, errIllegalRecursionInTypeX, + errCannotInstantiateX, errExprHasNoAddress, errXStackEscape, + errVarForOutParamNeeded, + errPureTypeMismatch, errTypeMismatch, errButExpected, errButExpectedX, + errAmbiguousCallXYZ, errWrongNumberOfArguments, + errXCannotBePassedToProcVar, + errXCannotBeInParamDecl, errPragmaOnlyInHeaderOfProc, errImplOfXNotAllowed, + errImplOfXexpected, errNoSymbolToBorrowFromFound, errDiscardValueX, + errInvalidDiscard, errIllegalConvFromXtoY, errCannotBindXTwice, + errInvalidOrderInArrayConstructor, + errInvalidOrderInEnumX, errEnumXHasHoles, errExceptExpected, errInvalidTry, + errOptionExpected, errXisNoLabel, errNotAllCasesCovered, + errUnknownSubstitionVar, errComplexStmtRequiresInd, errXisNotCallable, + errNoPragmasAllowedForX, errNoGenericParamsAllowedForX, + errInvalidParamKindX, errDefaultArgumentInvalid, errNamedParamHasToBeIdent, + errNoReturnTypeForX, errConvNeedsOneArg, errInvalidPragmaX, + errXNotAllowedHere, errInvalidControlFlowX, + errXisNoType, errCircumNeedsPointer, errInvalidExpression, + errInvalidExpressionX, errEnumHasNoValueX, errNamedExprExpected, + errNamedExprNotAllowed, errXExpectsOneTypeParam, + errArrayExpectsTwoTypeParams, errInvalidVisibilityX, errInitHereNotAllowed, + errXCannotBeAssignedTo, errIteratorNotAllowed, errXNeedsReturnType, + errNoReturnTypeDeclared, + errInvalidCommandX, errXOnlyAtModuleScope, + errXNeedsParamObjectType, + errTemplateInstantiationTooNested, errInstantiationFrom, + errInvalidIndexValueForTuple, errCommandExpectsFilename, + errMainModuleMustBeSpecified, + errXExpected, + errTIsNotAConcreteType, + errInvalidSectionStart, errGridTableNotImplemented, errGeneralParseError, + errNewSectionExpected, errWhitespaceExpected, errXisNoValidIndexFile, + errCannotRenderX, errVarVarTypeNotAllowed, errInstantiateXExplicitly, + errOnlyACallOpCanBeDelegator, errUsingNoSymbol, + errMacroBodyDependsOnGenericTypes, + errDestructorNotGenericEnough, + errInlineIteratorsAsProcParams, + errXExpectsTwoArguments, + errXExpectsObjectTypes, errXcanNeverBeOfThisSubtype, errTooManyIterations, + errCannotInterpretNodeX, errFieldXNotFound, errInvalidConversionFromTypeX, + errAssertionFailed, errCannotGenerateCodeForX, errXRequiresOneArgument, + errUnhandledExceptionX, errCyclicTree, errXisNoMacroOrTemplate, + errXhasSideEffects, errIteratorExpected, errLetNeedsInit, + errThreadvarCannotInit, errWrongSymbolX, errIllegalCaptureX, + errXCannotBeClosure, errXMustBeCompileTime, + errCannotInferTypeOfTheLiteral, + errCannotInferReturnType, + errGenericLambdaNotAllowed, + errCompilerDoesntSupportTarget, + errUser, + warnCannotOpenFile, + warnOctalEscape, warnXIsNeverRead, warnXmightNotBeenInit, + warnDeprecated, warnConfigDeprecated, + warnSmallLshouldNotBeUsed, warnUnknownMagic, warnRedefinitionOfLabel, + warnUnknownSubstitutionX, warnLanguageXNotSupported, + warnFieldXNotSupported, warnCommentXIgnored, + warnNilStatement, warnTypelessParam, + warnDifferentHeaps, warnWriteToForeignHeap, warnUnsafeCode, + warnEachIdentIsTuple, warnShadowIdent, + warnProveInit, warnProveField, warnProveIndex, warnGcUnsafe, warnGcUnsafe2, + warnUninit, warnGcMem, warnDestructor, warnLockLevel, warnResultShadowed, + warnUser, + hintSuccess, hintSuccessX, + hintLineTooLong, hintXDeclaredButNotUsed, hintConvToBaseNotNeeded, + hintConvFromXtoItselfNotNeeded, hintExprAlwaysX, hintQuitCalled, + hintProcessing, hintCodeBegin, hintCodeEnd, hintConf, hintPath, + hintConditionAlwaysTrue, hintName, hintPattern, + hintExecuting, hintLinking, hintDependency, + hintSource, hintStackTrace, hintGCStats, + hintUser + +const + warnMin = warnCannotOpenFile + hintMax = high(TMsgKind) + +type + TNoteKind = range[warnMin..hintMax] # "notes" are warnings or hints + TNoteKinds = set[TNoteKind] + +const + NotesVerbosityConst: array[0..0, TNoteKinds] = [ + {low(TNoteKind)..high(TNoteKind)} - {hintGCStats}] + fuckyou = NotesVerbosityConst[0] + +var + gNotesFromConst: TNoteKinds = NotesVerbosityConst[0] + gNotesFromConst2: TNoteKinds = fuckyou + +if hintGCStats in gNotesFromConst: + echo "hintGCStats in gNotesFromConst A" + +if hintGCStats in gNotesFromConst2: + echo "hintGCStats in gNotesFromConst B" From 62cea4e29cdb6632a16e9afec24b414aefee4201 Mon Sep 17 00:00:00 2001 From: Araq Date: Tue, 30 Jun 2015 13:39:14 +0200 Subject: [PATCH 0595/1263] prepared selectors module for multi threading --- lib/pure/collections/sharedtables.nim | 6 +- lib/pure/selectors.nim | 92 +++++++++++++++++---------- 2 files changed, 61 insertions(+), 37 deletions(-) diff --git a/lib/pure/collections/sharedtables.nim b/lib/pure/collections/sharedtables.nim index 2abc314d7..20e1bb7a9 100644 --- a/lib/pure/collections/sharedtables.nim +++ b/lib/pure/collections/sharedtables.nim @@ -16,12 +16,12 @@ import hashes, math, locks type - KeyValuePair[A, B] = tuple[hcode: THash, key: A, val: B] + KeyValuePair[A, B] = tuple[hcode: Hash, key: A, val: B] KeyValuePairSeq[A, B] = ptr array[10_000_000, KeyValuePair[A, B]] SharedTable* [A, B] = object ## generic hash SharedTable data: KeyValuePairSeq[A, B] counter, dataLen: int - lock: TLock + lock: Lock template maxHash(t): expr = t.dataLen-1 @@ -49,7 +49,7 @@ proc mget*[A, B](t: var SharedTable[A, B], key: A): var B = ## retrieves the value at ``t[key]``. The value can be modified. ## If `key` is not in `t`, the ``KeyError`` exception is raised. withLock t: - var hc: THash + var hc: Hash var index = rawGet(t, key, hc) let hasKey = index >= 0 if hasKey: result = t.data[index].val diff --git a/lib/pure/selectors.nim b/lib/pure/selectors.nim index 9802684fd..aa8ad39d1 100644 --- a/lib/pure/selectors.nim +++ b/lib/pure/selectors.nim @@ -9,7 +9,7 @@ # TODO: Docs. -import tables, os, unsigned, hashes +import os, unsigned, hashes when defined(linux): import posix, epoll @@ -18,6 +18,17 @@ elif defined(windows): else: import posix +const MultiThreaded = defined(useStdlibThreading) + +when MultiThreaded: + import sharedtables + + type SelectorData = pointer +else: + import tables + + type SelectorData = RootRef + proc hash*(x: SocketHandle): Hash {.borrow.} proc `$`*(x: SocketHandle): string {.borrow.} @@ -28,12 +39,10 @@ type SelectorKey* = object fd*: SocketHandle events*: set[Event] ## The events which ``fd`` listens for. - data*: pointer ## User object. + data*: SelectorData ## User object. ReadyInfo* = tuple[key: SelectorKey, events: set[Event]] - - when defined(nimdoc): type Selector* = ref object @@ -41,7 +50,7 @@ when defined(nimdoc): ## status. proc register*(s: Selector, fd: SocketHandle, events: set[Event], - data: RootRef): SelectorKey {.discardable.} = + data: SelectorData): SelectorKey {.discardable.} = ## Registers file descriptor ``fd`` to selector ``s`` with a set of Event ## ``events``. @@ -76,7 +85,10 @@ elif defined(linux): Selector* = object epollFD: cint events: array[64, epoll_event] - fds: SharedTable[SocketHandle, SelectorKey] + when MultiThreaded: + fds: SharedTable[SocketHandle, SelectorKey] + else: + fds: Table[SocketHandle, SelectorKey] proc createEventStruct(events: set[Event], fd: SocketHandle): epoll_event = if EvRead in events: @@ -86,8 +98,8 @@ elif defined(linux): result.events = result.events or EPOLLRDHUP result.data.fd = fd.cint - proc register*(s: Selector, fd: SocketHandle, events: set[Event], - data: pointer) = + proc register*(s: var Selector, fd: SocketHandle, events: set[Event], + data: SelectorData) = var event = createEventStruct(events, fd) if events != {}: if epoll_ctl(s.epollFD, EPOLL_CTL_ADD, fd, addr(event)) != 0: @@ -129,7 +141,7 @@ elif defined(linux): s.fds.del(fd) proc close*(s: var Selector) = - deinitSharedTable(s.fds) + when MultiThreaded: deinitSharedTable(s.fds) if s.epollFD.close() != 0: raiseOSError(osLastError()) proc epollHasFd(s: Selector, fd: SocketHandle): bool = @@ -163,7 +175,7 @@ elif defined(linux): if (s.events[i].events and EPOLLIN) != 0: evSet = evSet + {EvRead} if (s.events[i].events and EPOLLOUT) != 0: evSet = evSet + {EvWrite} let selectorKey = s.fds[fd] - assert selectorKey != nil + assert selectorKey.fd != 0.SocketHandle result.add((selectorKey, evSet)) #echo("Epoll: ", result[i].key.fd, " ", result[i].events, " ", result[i].key.events) @@ -172,7 +184,10 @@ elif defined(linux): result.epollFD = epoll_create(64) if result.epollFD < 0: raiseOSError(osLastError()) - result.fds = initSharedTable[SocketHandle, SelectorKey]() + when MultiThreaded: + result.fds = initSharedTable[SocketHandle, SelectorKey]() + else: + result.fds = initTable[SocketHandle, SelectorKey]() proc contains*(s: Selector, fd: SocketHandle): bool = ## Determines whether selector contains a file descriptor. @@ -191,14 +206,15 @@ elif defined(linux): elif not defined(nimdoc): # TODO: kqueue for bsd/mac os x. - import sharedtables - type Selector* = object - fds: SharedTable[SocketHandle, SelectorKey] + when MultiThreaded: + fds: SharedTable[SocketHandle, SelectorKey] + else: + fds: Table[SocketHandle, SelectorKey] proc register*(s: var Selector, fd: SocketHandle, events: set[Event], - data: pointer) = + data: SelectorData) = let result = SelectorKey(fd: fd, events: events, data: data) if s.fds.hasKeyOrPut(fd, result): raise newException(ValueError, "File descriptor already exists.") @@ -211,7 +227,8 @@ elif not defined(nimdoc): proc unregister*(s: var Selector, fd: SocketHandle) = s.fds.del(fd) - proc close*(s: var Selector) = deinitSharedTable(s.fds) + proc close*(s: var Selector) = + when MultiThreaded: deinitSharedTable(s.fds) proc timeValFromMilliseconds(timeout: int): TimeVal = if timeout != -1: @@ -219,10 +236,9 @@ elif not defined(nimdoc): result.tv_sec = seconds.int32 result.tv_usec = ((timeout - seconds * 1000) * 1000).int32 - proc createFdSet(rd, wr: var TFdSet, fds: SharedTable[SocketHandle, SelectorKey], - m: var int) = + proc createFdSet(rd, wr: var TFdSet, s: Selector, m: var int) = FD_ZERO(rd); FD_ZERO(wr) - for k, v in pairs(fds): + for k, v in pairs(s.fds): if EvRead in v.events: m = max(m, int(k)) FD_SET(k, rd) @@ -231,9 +247,9 @@ elif not defined(nimdoc): FD_SET(k, wr) proc getReadyFDs(rd, wr: var TFdSet, - fds: SharedTable[SocketHandle, SelectorKey]): seq[ReadyInfo] = + s: var Selector): seq[ReadyInfo] = result = @[] - for k, v in pairs(fds): + for k, v in pairs(s.fds): var events: set[Event] = {} if FD_ISSET(k, rd) != 0'i32: events = events + {EvRead} @@ -241,13 +257,12 @@ elif not defined(nimdoc): events = events + {EvWrite} result.add((v, events)) - proc select(fds: var SharedTable[SocketHandle, SelectorKey], - timeout = 500): seq[ReadyInfo] = + proc select*(s: var Selector, timeout: int): seq[ReadyInfo] = var tv {.noInit.}: TimeVal = timeValFromMilliseconds(timeout) var rd, wr: TFdSet var m = 0 - createFdSet(rd, wr, fds, m) + createFdSet(rd, wr, s, m) var retCode = 0 if timeout != -1: @@ -260,13 +275,13 @@ elif not defined(nimdoc): elif retCode == 0: return @[] else: - return getReadyFDs(rd, wr, fds) - - proc select*(s: Selector, timeout: int): seq[ReadyInfo] = - result = select(s.fds, timeout) + return getReadyFDs(rd, wr, s) proc newSelector*(): Selector = - result.fds = initSharedTable[SocketHandle, SelectorKey]() + when MultiThreaded: + result.fds = initSharedTable[SocketHandle, SelectorKey]() + else: + result.fds = initTable[SocketHandle, SelectorKey]() proc contains*(s: Selector, fd: SocketHandle): bool = return s.fds.hasKey(fd) @@ -289,9 +304,15 @@ proc contains*(s: Selector, key: SelectorKey): bool = when not defined(testing) and isMainModule and not defined(nimdoc): # Select() import sockets - type - SockWrapper = object - sock: Socket + + when MultiThreaded: + type + SockWrapper = object + sock: Socket + else: + type + SockWrapper = ref object of RootObj + sock: Socket var sock = socket() if sock == sockets.invalidSocket: raiseOSError(osLastError()) @@ -300,7 +321,10 @@ when not defined(testing) and isMainModule and not defined(nimdoc): var selector = newSelector() var data = SockWrapper(sock: sock) - let key = selector.register(sock.getFD, {EvWrite}, addr data) + when MultiThreaded: + selector.register(sock.getFD, {EvWrite}, addr data) + else: + selector.register(sock.getFD, {EvWrite}, data) var i = 0 while true: let ready = selector.select(1000) @@ -308,6 +332,6 @@ when not defined(testing) and isMainModule and not defined(nimdoc): if ready.len > 0: echo ready[0].events i.inc if i == 6: - assert selector.unregister(sock.getFD).fd == sock.getFD + selector.unregister(sock.getFD) selector.close() break From 1a14e9d366799181f7d04ea3572c8b9052607584 Mon Sep 17 00:00:00 2001 From: r-ku Date: Tue, 30 Jun 2015 14:32:52 +0300 Subject: [PATCH 0596/1263] Fixes #3022 --- compiler/sigmatch.nim | 6 +++++- tests/generics/mgenericprocmatcher.nim | 11 +++++++++++ tests/generics/tgenericprocmatcher.nim | 23 +++++++++++++++++++++++ 3 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 tests/generics/mgenericprocmatcher.nim create mode 100644 tests/generics/tgenericprocmatcher.nim diff --git a/compiler/sigmatch.nim b/compiler/sigmatch.nim index 40836a94d..97a059dbe 100644 --- a/compiler/sigmatch.nim +++ b/compiler/sigmatch.nim @@ -158,11 +158,15 @@ proc sumGeneric(t: PType): int = t = t.sons[0] inc result inc isvar + of tyTypeDesc: + t = t.lastSon + if t.kind == tyEmpty: break + inc result of tyGenericInvocation, tyTuple: result += ord(t.kind == tyGenericInvocation) for i in 0 .. Date: Tue, 30 Jun 2015 10:49:31 -0500 Subject: [PATCH 0597/1263] added test file naming convention Via https://github.com/nim-lang/Nim/pull/3025#issuecomment-117191789 "Don't name the import with 't'. Convention is to replace the 't' with an 'm' prefix." --- contributing.rst | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/contributing.rst b/contributing.rst index 3a028fae6..48f0dbf00 100644 --- a/contributing.rst +++ b/contributing.rst @@ -32,8 +32,11 @@ Compiler The tests for the compiler work differently, they are all located in ``tests/``. Each test has its own file, which is different from the -stdlib tests. At the beginning of every test is the expected side of -the test. Possible keys are: +stdlib tests. All test files are prefixed with ``t``. If you want to +create a file for import into another test only, use the prefix ``m``. + +At the beginning of every test is the expected side of the test. +Possible keys are: - output: The expected output, most likely via ``echo`` - exitcode: Exit code of the test (via ``exit(number)``) From 507062f1bf0a1bdbd82243e18ea321230b8156a7 Mon Sep 17 00:00:00 2001 From: Reimer Behrends Date: Tue, 30 Jun 2015 23:27:16 +0200 Subject: [PATCH 0598/1263] Fix SQLite3 dynlib on OS X. The old dynlib name referenced an ancient version of SQLite3 and could not be overridden with --dynlibOverride. --- lib/wrappers/sqlite3.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/wrappers/sqlite3.nim b/lib/wrappers/sqlite3.nim index 8dacb15e7..bd107b0bc 100644 --- a/lib/wrappers/sqlite3.nim +++ b/lib/wrappers/sqlite3.nim @@ -13,7 +13,7 @@ when defined(windows): Lib = "sqlite3.dll" elif defined(macosx): const - Lib = "(libsqlite3(|.0).dylib|sqlite-3.6.13.dylib)" + Lib = "libsqlite3(|.0).dylib" else: const Lib = "libsqlite3.so(|.0)" From cc57a0430bd1aeedc9b58a9e0e5fe50d108bf256 Mon Sep 17 00:00:00 2001 From: Araq Date: Wed, 1 Jul 2015 00:58:02 +0200 Subject: [PATCH 0599/1263] fixes #3028 --- compiler/vm.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/vm.nim b/compiler/vm.nim index 23fd6c8b1..a8972f420 100644 --- a/compiler/vm.nim +++ b/compiler/vm.nim @@ -351,7 +351,7 @@ proc opConv*(dest: var TFullReg, src: TFullReg, desttyp, srctyp: PType): bool = myreset(dest); dest.kind = rkFloat case skipTypes(srctyp, abstractRange).kind of tyInt..tyInt64, tyUInt..tyUInt64, tyEnum, tyBool, tyChar: - dest.floatVal = toFloat(src.intVal.int) + dest.floatVal = toBiggestFloat(src.intVal) else: dest.floatVal = src.floatVal else: From 4afb8b8043ab4c92c3ac69da3f6b5fc0a136e41a Mon Sep 17 00:00:00 2001 From: Araq Date: Wed, 1 Jul 2015 01:18:28 +0200 Subject: [PATCH 0600/1263] fixes #2935 --- compiler/ast.nim | 3 +++ 1 file changed, 3 insertions(+) diff --git a/compiler/ast.nim b/compiler/ast.nim index 167f58d0b..95aae035d 100644 --- a/compiler/ast.nim +++ b/compiler/ast.nim @@ -1486,6 +1486,9 @@ proc getFloat*(a: PNode): BiggestFloat = proc getStr*(a: PNode): string = case a.kind of nkStrLit..nkTripleStrLit: result = a.strVal + of nkNilLit: + # let's hope this fixes more problems than it creates: + result = nil else: internalError(a.info, "getStr") result = "" From 54a374a8285a3a3387bcf0d31bbca0946ed28d51 Mon Sep 17 00:00:00 2001 From: Araq Date: Wed, 1 Jul 2015 01:29:28 +0200 Subject: [PATCH 0601/1263] .header pragma now supports preprocessor directives --- compiler/cgen.nim | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/compiler/cgen.nim b/compiler/cgen.nim index 390150cf7..f4854c988 100644 --- a/compiler/cgen.nim +++ b/compiler/cgen.nim @@ -610,10 +610,12 @@ proc generateHeaders(m: BModule) = add(m.s[cfsHeaders], tnl & "#include \"nimbase.h\"" & tnl) var it = PStrEntry(m.headerFiles.head) while it != nil: - if it.data[0] notin {'\"', '<'}: - addf(m.s[cfsHeaders], "$N#include \"$1\"$N", [rope(it.data)]) + if it.data[0] == '#': + add(m.s[cfsHeaders], rope(it.data.replace('`', '"') & tnl)) + elif it.data[0] notin {'\"', '<'}: + addf(m.s[cfsHeaders], "#include \"$1\"$N", [rope(it.data)]) else: - addf(m.s[cfsHeaders], "$N#include $1$N", [rope(it.data)]) + addf(m.s[cfsHeaders], "#include $1$N", [rope(it.data)]) it = PStrEntry(it.next) proc retIsNotVoid(s: PSym): bool = @@ -814,7 +816,7 @@ proc genVarPrototype(m: BModule, sym: PSym) = genVarPrototypeAux(m, sym) proc addIntTypes(result: var Rope) {.inline.} = - addf(result, "#define NIM_INTBITS $1", [ + addf(result, "#define NIM_INTBITS $1" & tnl, [ platform.CPU[targetCPU].intSize.rope]) proc getCopyright(cfile: string): Rope = From 70fe773bbe0021862232dff8eda0d027eb882067 Mon Sep 17 00:00:00 2001 From: Araq Date: Wed, 1 Jul 2015 02:15:07 +0200 Subject: [PATCH 0602/1263] implemented system.pinToCpu --- lib/system/threads.nim | 50 +++++++++++++++++++++++++++++++++--------- 1 file changed, 40 insertions(+), 10 deletions(-) diff --git a/lib/system/threads.nim b/lib/system/threads.nim index 180e0410b..315a70af5 100644 --- a/lib/system/threads.nim +++ b/lib/system/threads.nim @@ -105,11 +105,17 @@ when defined(windows): proc threadVarGetValue(dwTlsIndex: ThreadVarSlot): pointer {. importc: "TlsGetValue", stdcall, dynlib: "kernel32".} + proc setThreadAffinityMask(hThread: SysThread, dwThreadAffinityMask: uint) {. + importc: "SetThreadAffinityMask", stdcall, header: "".} + else: when not defined(macosx): {.passL: "-pthread".} {.passC: "-pthread".} + const + schedh = "#define _GNU_SOURCE\n#include " + pthreadh = "#define _GNU_SOURCE\n#include " type SysThread {.importc: "pthread_t", header: "", @@ -125,19 +131,19 @@ else: Ttimespec: Timespec].} proc pthread_attr_init(a1: var PthreadAttr) {. - importc, header: "".} + importc, header: pthreadh.} proc pthread_attr_setstacksize(a1: var PthreadAttr, a2: int) {. - importc, header: "".} + importc, header: pthreadh.} proc pthread_create(a1: var SysThread, a2: var PthreadAttr, a3: proc (x: pointer): pointer {.noconv.}, a4: pointer): cint {.importc: "pthread_create", - header: "".} + header: pthreadh.} proc pthread_join(a1: SysThread, a2: ptr pointer): cint {. - importc, header: "".} + importc, header: pthreadh.} proc pthread_cancel(a1: SysThread): cint {. - importc: "pthread_cancel", header: "".} + importc: "pthread_cancel", header: pthreadh.} type ThreadVarSlot {.importc: "pthread_key_t", pure, final, @@ -145,15 +151,15 @@ else: {.deprecated: [TThreadVarSlot: ThreadVarSlot].} proc pthread_getspecific(a1: ThreadVarSlot): pointer {. - importc: "pthread_getspecific", header: "".} + importc: "pthread_getspecific", header: pthreadh.} proc pthread_key_create(a1: ptr ThreadVarSlot, destruct: proc (x: pointer) {.noconv.}): int32 {. - importc: "pthread_key_create", header: "".} + importc: "pthread_key_create", header: pthreadh.} proc pthread_key_delete(a1: ThreadVarSlot): int32 {. - importc: "pthread_key_delete", header: "".} + importc: "pthread_key_delete", header: pthreadh.} proc pthread_setspecific(a1: ThreadVarSlot, a2: pointer): int32 {. - importc: "pthread_setspecific", header: "".} + importc: "pthread_setspecific", header: pthreadh.} proc threadVarAlloc(): ThreadVarSlot {.inline.} = discard pthread_key_create(addr(result), nil) @@ -165,7 +171,15 @@ else: when useStackMaskHack: proc pthread_attr_setstack(attr: var PthreadAttr, stackaddr: pointer, size: int): cint {. - importc: "pthread_attr_setstack", header: "".} + importc: "pthread_attr_setstack", header: pthreadh.} + + type CpuSet {.importc: "cpu_set_t", header: schedh.} = object + proc cpusetZero(s: var CpuSet) {.importc: "CPU_ZERO", header: schedh.} + proc cpusetIncl(cpu: cint; s: var CpuSet) {. + importc: "CPU_SET", header: schedh.} + + proc setAffinity(thread: SysThread; setsize: csize; s: var CpuSet) {. + importc: "pthread_setaffinity_np", header: pthreadh.} const emulatedThreadVars = compileOption("tlsEmulation") @@ -378,6 +392,13 @@ when hostOS == "windows": addr(t), 0'i32, dummyThreadId) if t.sys <= 0: raise newException(ResourceExhaustedError, "cannot create thread") + + proc pinToCpu*[Arg](t: var Thread[Arg]; cpu: Natural) = + ## pins a thread to a `CPU`:idx:. In other words sets a + ## thread's `affinity`:idx:. If you don't know what this means, you + ## shouldn't use this proc. + setThreadAffinityMask(t.sys, uint(1 shl cpu)) + else: proc createThread*[TArg](t: var Thread[TArg], tp: proc (arg: TArg) {.thread.}, @@ -394,6 +415,15 @@ else: if pthread_create(t.sys, a, threadProcWrapper[TArg], addr(t)) != 0: raise newException(ResourceExhaustedError, "cannot create thread") + proc pinToCpu*[Arg](t: var Thread[Arg]; cpu: Natural) = + ## pins a thread to a `CPU`:idx:. In other words sets a + ## thread's `affinity`:idx:. If you don't know what this means, you + ## shouldn't use this proc. + var s {.noinit.}: CpuSet + cpusetZero(s) + cpusetIncl(cpu.cint, s) + setAffinity(t.sys, sizeof(s), s) + proc threadId*[TArg](t: var Thread[TArg]): ThreadId[TArg] {.inline.} = ## returns the thread ID of `t`. result = addr(t) From b3455d281b360926ad18fbbe1f54608835be79d2 Mon Sep 17 00:00:00 2001 From: Reimer Behrends Date: Wed, 1 Jul 2015 02:39:45 +0200 Subject: [PATCH 0603/1263] Add popen()/pclose() support to posix.nim --- lib/posix/posix.nim | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/posix/posix.nim b/lib/posix/posix.nim index 9b9bf390a..d264dc02a 100644 --- a/lib/posix/posix.nim +++ b/lib/posix/posix.nim @@ -2156,7 +2156,9 @@ proc nice*(a1: cint): cint {.importc, header: "".} proc pathconf*(a1: cstring, a2: cint): int {.importc, header: "".} proc pause*(): cint {.importc, header: "".} +proc pclose*(a: File): cint {.importc, header: "".} proc pipe*(a: array[0..1, cint]): cint {.importc, header: "".} +proc popen*(a1, a2: cstring): File {.importc, header: "".} proc pread*(a1: cint, a2: pointer, a3: int, a4: Off): int {. importc, header: "".} proc pwrite*(a1: cint, a2: pointer, a3: int, a4: Off): int {. From 039da42401c15799e98afdcb041e1cd5e47af801 Mon Sep 17 00:00:00 2001 From: Araq Date: Wed, 1 Jul 2015 03:23:23 +0200 Subject: [PATCH 0604/1263] fixes #1463 --- compiler/semfold.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/semfold.nim b/compiler/semfold.nim index 9a0c856dc..23666656e 100644 --- a/compiler/semfold.nim +++ b/compiler/semfold.nim @@ -543,7 +543,7 @@ proc foldConv*(n, a: PNode; check = false): PNode = of tyFloat..tyFloat64: case skipTypes(a.typ, abstractRange).kind of tyInt..tyInt64, tyEnum, tyBool, tyChar: - result = newFloatNodeT(toFloat(int(getOrdValue(a))), n) + result = newFloatNodeT(toBiggestFloat(getOrdValue(a)), n) else: result = a result.typ = n.typ From f315b0619c6ca8d207d517970be9fb98126904f5 Mon Sep 17 00:00:00 2001 From: Araq Date: Wed, 1 Jul 2015 11:28:18 +0200 Subject: [PATCH 0605/1263] asyncdispatch compiles again on Linux --- lib/pure/asyncdispatch.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/pure/asyncdispatch.nim b/lib/pure/asyncdispatch.nim index 5723a7871..0b312d4d4 100644 --- a/lib/pure/asyncdispatch.nim +++ b/lib/pure/asyncdispatch.nim @@ -920,7 +920,7 @@ else: proc update(fd: AsyncFD, events: set[Event]) = let p = getGlobalDispatcher() assert fd.SocketHandle in p.selector - discard p.selector.update(fd.SocketHandle, events) + p.selector.update(fd.SocketHandle, events) proc register*(fd: AsyncFD) = let p = getGlobalDispatcher() From 1555f41796e3da42c269329884d1847ed2a3854b Mon Sep 17 00:00:00 2001 From: Araq Date: Wed, 1 Jul 2015 13:35:58 +0200 Subject: [PATCH 0606/1263] fixes #3032 --- compiler/sempass2.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/sempass2.nim b/compiler/sempass2.nim index 0358ed51a..3431ee2ff 100644 --- a/compiler/sempass2.nim +++ b/compiler/sempass2.nim @@ -753,7 +753,7 @@ proc track(tracked: PEffects, n: PNode) = for i in 1 .. Date: Wed, 1 Jul 2015 15:02:13 +0200 Subject: [PATCH 0607/1263] fixes 'instantiation from here' highlighting --- compiler/msgs.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/msgs.nim b/compiler/msgs.nim index 3d5edaf40..937b4bd61 100644 --- a/compiler/msgs.nim +++ b/compiler/msgs.nim @@ -789,7 +789,7 @@ proc writeContext(lastinfo: TLineInfo) = PosFormat % [toMsgFilename(msgContext[i]), coordToStr(msgContext[i].line), coordToStr(msgContext[i].col+1)], - styleDim, + resetStyle, getMessageStr(errInstantiationFrom, "")) info = msgContext[i] From 13259c669dc1dcdd72c88aedfe8689fd333288d3 Mon Sep 17 00:00:00 2001 From: Araq Date: Wed, 1 Jul 2015 15:40:29 +0200 Subject: [PATCH 0608/1263] minor doc updates --- lib/pure/htmlparser.nim | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/pure/htmlparser.nim b/lib/pure/htmlparser.nim index ff1cd7d8d..d620e816e 100644 --- a/lib/pure/htmlparser.nim +++ b/lib/pure/htmlparser.nim @@ -19,7 +19,7 @@ ## ## Every tag in the resulting tree is in lower case. ## -## **Note:** The resulting ``PXmlNode`` already uses the ``clientData`` field, +## **Note:** The resulting ``XmlNode`` already uses the ``clientData`` field, ## so it cannot be used by clients of this library. ## ## Example: Transforming hyperlinks @@ -32,8 +32,8 @@ ## .. code-block:: Nim ## ## import htmlparser -## import xmltree # To use '$' for PXmlNode -## import strtabs # To access PXmlAttributes +## import xmltree # To use '$' for XmlNode +## import strtabs # To access XmlAttributes ## import os # To use splitFile ## import strutils # To use cmpIgnoreCase ## From 0d7e0e1b4fb9e99259eb9f2a1ad42a7c0136e48b Mon Sep 17 00:00:00 2001 From: Araq Date: Wed, 1 Jul 2015 15:47:15 +0200 Subject: [PATCH 0609/1263] fixes #2429 --- lib/pure/lexbase.nim | 62 +++++----- lib/pure/parsexml.nim | 272 +++++++++++++++++++++++------------------- 2 files changed, 178 insertions(+), 156 deletions(-) diff --git a/lib/pure/lexbase.nim b/lib/pure/lexbase.nim index 585ba87f5..bfecf6a58 100644 --- a/lib/pure/lexbase.nim +++ b/lib/pure/lexbase.nim @@ -34,37 +34,15 @@ type lineNumber*: int ## the current line number sentinel: int lineStart: int # index of last line start in buffer - fileOpened: bool + refillChars: set[char] {.deprecated: [TBaseLexer: BaseLexer].} -proc open*(L: var BaseLexer, input: Stream, bufLen: int = 8192) - ## inits the BaseLexer with a stream to read from - -proc close*(L: var BaseLexer) - ## closes the base lexer. This closes `L`'s associated stream too. - -proc getCurrentLine*(L: BaseLexer, marker: bool = true): string - ## retrieves the current line. - -proc getColNumber*(L: BaseLexer, pos: int): int - ## retrieves the current column. - -proc handleCR*(L: var BaseLexer, pos: int): int - ## Call this if you scanned over '\c' in the buffer; it returns the the - ## position to continue the scanning from. `pos` must be the position - ## of the '\c'. -proc handleLF*(L: var BaseLexer, pos: int): int - ## Call this if you scanned over '\L' in the buffer; it returns the the - ## position to continue the scanning from. `pos` must be the position - ## of the '\L'. - -# implementation - const chrSize = sizeof(char) -proc close(L: var BaseLexer) = +proc close*(L: var BaseLexer) = + ## closes the base lexer. This closes `L`'s associated stream too. dealloc(L.buf) close(L.input) @@ -80,7 +58,7 @@ proc fillBuffer(L: var BaseLexer) = toCopy = L.bufLen - L.sentinel - 1 assert(toCopy >= 0) if toCopy > 0: - moveMem(L.buf, addr(L.buf[L.sentinel + 1]), toCopy * chrSize) + moveMem(L.buf, addr(L.buf[L.sentinel + 1]), toCopy * chrSize) # "moveMem" handles overlapping regions charsRead = readData(L.input, addr(L.buf[toCopy]), (L.sentinel + 1) * chrSize) div chrSize @@ -93,7 +71,7 @@ proc fillBuffer(L: var BaseLexer) = dec(s) # BUGFIX (valgrind) while true: assert(s < L.bufLen) - while (s >= 0) and not (L.buf[s] in NewLines): dec(s) + while s >= 0 and L.buf[s] notin L.refillChars: dec(s) if s >= 0: # we found an appropriate character for a sentinel: L.sentinel = s @@ -121,31 +99,46 @@ proc fillBaseLexer(L: var BaseLexer, pos: int): int = fillBuffer(L) L.bufpos = 0 # XXX: is this really correct? result = 0 - L.lineStart = result -proc handleCR(L: var BaseLexer, pos: int): int = +proc handleCR*(L: var BaseLexer, pos: int): int = + ## Call this if you scanned over '\c' in the buffer; it returns the the + ## position to continue the scanning from. `pos` must be the position + ## of the '\c'. assert(L.buf[pos] == '\c') inc(L.lineNumber) result = fillBaseLexer(L, pos) if L.buf[result] == '\L': result = fillBaseLexer(L, result) + L.lineStart = result -proc handleLF(L: var BaseLexer, pos: int): int = +proc handleLF*(L: var BaseLexer, pos: int): int = + ## Call this if you scanned over '\L' in the buffer; it returns the the + ## position to continue the scanning from. `pos` must be the position + ## of the '\L'. assert(L.buf[pos] == '\L') inc(L.lineNumber) result = fillBaseLexer(L, pos) #L.lastNL := result-1; // BUGFIX: was: result; + L.lineStart = result + +proc handleRefillChar*(L: var BaseLexer, pos: int): int = + ## To be documented. + assert(L.buf[pos] in L.refillChars) + result = fillBaseLexer(L, pos) #L.lastNL := result-1; // BUGFIX: was: result; proc skipUtf8Bom(L: var BaseLexer) = if (L.buf[0] == '\xEF') and (L.buf[1] == '\xBB') and (L.buf[2] == '\xBF'): inc(L.bufpos, 3) inc(L.lineStart, 3) -proc open(L: var BaseLexer, input: Stream, bufLen: int = 8192) = +proc open*(L: var BaseLexer, input: Stream, bufLen: int = 8192; + refillChars: set[char] = NewLines) = + ## inits the BaseLexer with a stream to read from. assert(bufLen > 0) assert(input != nil) L.input = input L.bufpos = 0 L.bufLen = bufLen + L.refillChars = refillChars L.buf = cast[cstring](alloc(bufLen * chrSize)) L.sentinel = bufLen - 1 L.lineStart = 0 @@ -153,10 +146,12 @@ proc open(L: var BaseLexer, input: Stream, bufLen: int = 8192) = fillBuffer(L) skipUtf8Bom(L) -proc getColNumber(L: BaseLexer, pos: int): int = +proc getColNumber*(L: BaseLexer, pos: int): int = + ## retrieves the current column. result = abs(pos - L.lineStart) -proc getCurrentLine(L: BaseLexer, marker: bool = true): string = +proc getCurrentLine*(L: BaseLexer, marker: bool = true): string = + ## retrieves the current line. var i: int result = "" i = L.lineStart @@ -166,4 +161,3 @@ proc getCurrentLine(L: BaseLexer, marker: bool = true): string = add(result, "\n") if marker: add(result, spaces(getColNumber(L, L.bufpos)) & "^\n") - diff --git a/lib/pure/parsexml.nim b/lib/pure/parsexml.nim index eb792f086..e1abb0a4f 100644 --- a/lib/pure/parsexml.nim +++ b/lib/pure/parsexml.nim @@ -8,19 +8,19 @@ # ## This module implements a simple high performance `XML`:idx: / `HTML`:idx: -## parser. +## parser. ## The only encoding that is supported is UTF-8. The parser has been designed -## to be somewhat error correcting, so that even most "wild HTML" found on the +## to be somewhat error correcting, so that even most "wild HTML" found on the ## web can be parsed with it. **Note:** This parser does not check that each -## ```` has a corresponding ````! These checks have do be -## implemented by the client code for various reasons: +## ```` has a corresponding ````! These checks have do be +## implemented by the client code for various reasons: ## ## * Old HTML contains tags that have no end tag: ``
    `` for example. ## * HTML tags are case insensitive, XML tags are case sensitive. Since this ## library can parse both, only the client knows which comparison is to be ## used. ## * Thus the checks would have been very difficult to implement properly with -## little benefit, especially since they are simple to implement in the +## little benefit, especially since they are simple to implement in the ## client. The client should use the `errorMsgExpected` proc to generate ## a nice error message that fits the other error messages this library ## creates. @@ -29,7 +29,7 @@ ## Example 1: Retrieve HTML title ## ============================== ## -## The file ``examples/htmltitle.nim`` demonstrates how to use the +## The file ``examples/htmltitle.nim`` demonstrates how to use the ## XML parser to accomplish a simple task: To determine the title of an HTML ## document. ## @@ -40,22 +40,22 @@ ## Example 2: Retrieve all HTML links ## ================================== ## -## The file ``examples/htmlrefs.nim`` demonstrates how to use the -## XML parser to accomplish another simple task: To determine all the links +## The file ``examples/htmlrefs.nim`` demonstrates how to use the +## XML parser to accomplish another simple task: To determine all the links ## an HTML document contains. ## ## .. code-block:: nim ## :file: examples/htmlrefs.nim ## -import +import hashes, strutils, lexbase, streams, unicode # the parser treats ``
    `` as ``

    `` -# xmlElementCloseEnd, ## ``/>`` +# xmlElementCloseEnd, ## ``/>`` -type +type XmlEventKind* = enum ## enumation of all events that may occur when parsing xmlError, ## an error occurred during parsing xmlEof, ## end of file reached @@ -65,13 +65,13 @@ type xmlPI, ## processing instruction (````) xmlElementStart, ## ```` xmlElementEnd, ## ```` - xmlElementOpen, ## ```` + xmlElementClose, ## ``>`` xmlCData, ## ```` xmlEntity, ## &entity; xmlSpecial ## ```` - + XmlErrorKind* = enum ## enumeration that lists all errors that can occur errNone, ## no error errEndOfCDataExpected, ## ``]]>`` expected @@ -82,8 +82,8 @@ type errEqExpected, ## ``=`` expected errQuoteExpected, ## ``"`` or ``'`` expected errEndOfCommentExpected ## ``-->`` expected - - ParserState = enum + + ParserState = enum stateStart, stateNormal, stateAttr, stateEmptyElementTag, stateError XmlParseOption* = enum ## options for the XML parser @@ -121,8 +121,8 @@ proc open*(my: var XmlParser, input: Stream, filename: string, ## the `options` parameter: If `options` contains ``reportWhitespace`` ## a whitespace token is reported as an ``xmlWhitespace`` event. ## If `options` contains ``reportComments`` a comment token is reported as an - ## ``xmlComment`` event. - lexbase.open(my, input) + ## ``xmlComment`` event. + lexbase.open(my, input, 8192, {'\c', '\L', '/'}) my.filename = filename my.state = stateStart my.kind = xmlError @@ -130,24 +130,24 @@ proc open*(my: var XmlParser, input: Stream, filename: string, my.b = "" my.c = nil my.options = options - -proc close*(my: var XmlParser) {.inline.} = + +proc close*(my: var XmlParser) {.inline.} = ## closes the parser `my` and its associated input stream. lexbase.close(my) -proc kind*(my: XmlParser): XmlEventKind {.inline.} = +proc kind*(my: XmlParser): XmlEventKind {.inline.} = ## returns the current event type for the XML parser return my.kind template charData*(my: XmlParser): string = - ## returns the character data for the events: ``xmlCharData``, + ## returns the character data for the events: ``xmlCharData``, ## ``xmlWhitespace``, ``xmlComment``, ``xmlCData``, ``xmlSpecial`` - assert(my.kind in {xmlCharData, xmlWhitespace, xmlComment, xmlCData, + assert(my.kind in {xmlCharData, xmlWhitespace, xmlComment, xmlCData, xmlSpecial}) my.a template elementName*(my: XmlParser): string = - ## returns the element name for the events: ``xmlElementStart``, + ## returns the element name for the events: ``xmlElementStart``, ## ``xmlElementEnd``, ``xmlElementOpen`` assert(my.kind in {xmlElementStart, xmlElementEnd, xmlElementOpen}) my.a @@ -156,12 +156,12 @@ template entityName*(my: XmlParser): string = ## returns the entity name for the event: ``xmlEntity`` assert(my.kind == xmlEntity) my.a - + template attrKey*(my: XmlParser): string = ## returns the attribute key for the event ``xmlAttribute`` assert(my.kind == xmlAttribute) my.a - + template attrValue*(my: XmlParser): string = ## returns the attribute value for the event ``xmlAttribute`` assert(my.kind == xmlAttribute) @@ -187,110 +187,118 @@ proc rawData2*(my: XmlParser): string {.inline.} = ## This is only used for speed hacks. shallowCopy(result, my.b) -proc getColumn*(my: XmlParser): int {.inline.} = +proc getColumn*(my: XmlParser): int {.inline.} = ## get the current column the parser has arrived at. result = getColNumber(my, my.bufpos) -proc getLine*(my: XmlParser): int {.inline.} = +proc getLine*(my: XmlParser): int {.inline.} = ## get the current line the parser has arrived at. result = my.lineNumber -proc getFilename*(my: XmlParser): string {.inline.} = +proc getFilename*(my: XmlParser): string {.inline.} = ## get the filename of the file that the parser processes. result = my.filename - -proc errorMsg*(my: XmlParser): string = + +proc errorMsg*(my: XmlParser): string = ## returns a helpful error message for the event ``xmlError`` assert(my.kind == xmlError) result = "$1($2, $3) Error: $4" % [ my.filename, $getLine(my), $getColumn(my), errorMessages[my.err]] -proc errorMsgExpected*(my: XmlParser, tag: string): string = +proc errorMsgExpected*(my: XmlParser, tag: string): string = ## returns an error message " expected" in the same format as the - ## other error messages + ## other error messages result = "$1($2, $3) Error: $4" % [ my.filename, $getLine(my), $getColumn(my), "<$1> expected" % tag] -proc errorMsg*(my: XmlParser, msg: string): string = +proc errorMsg*(my: XmlParser, msg: string): string = ## returns an error message with text `msg` in the same format as the - ## other error messages + ## other error messages result = "$1($2, $3) Error: $4" % [ my.filename, $getLine(my), $getColumn(my), msg] - -proc markError(my: var XmlParser, kind: XmlErrorKind) {.inline.} = + +proc markError(my: var XmlParser, kind: XmlErrorKind) {.inline.} = my.err = kind my.state = stateError -proc parseCDATA(my: var XmlParser) = +proc parseCDATA(my: var XmlParser) = var pos = my.bufpos + len("': inc(pos, 3) break add(my.a, ']') inc(pos) - of '\0': + of '\0': markError(my, errEndOfCDataExpected) break - of '\c': + of '\c': pos = lexbase.handleCR(my, pos) buf = my.buf add(my.a, '\L') - of '\L': + of '\L': pos = lexbase.handleLF(my, pos) buf = my.buf add(my.a, '\L') + of '/': + pos = lexbase.handleRefillChar(my, pos) + buf = my.buf + add(my.a, '/') else: add(my.a, buf[pos]) - inc(pos) + inc(pos) my.bufpos = pos # store back my.kind = xmlCData -proc parseComment(my: var XmlParser) = +proc parseComment(my: var XmlParser) = var pos = my.bufpos + len(" `$`. --- lib/pure/memfiles.nim | 2 +- tests/misc/tmemslices.nim | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/pure/memfiles.nim b/lib/pure/memfiles.nim index f1bd7d11c..c646c31a1 100644 --- a/lib/pure/memfiles.nim +++ b/lib/pure/memfiles.nim @@ -254,7 +254,7 @@ type MemSlice* = object ## represent slice of a MemFile for iteration over deli proc c_memcpy(a, b: pointer, n: int) {.importc: "memcpy", header: "".} -proc toString*(ms: MemSlice): string {.inline.} = +proc `$`*(ms: MemSlice): string {.inline.} = ## Return a Nim string built from a MemSlice. var buf = newString(ms.size) c_memcpy(addr(buf[0]), ms.data, ms.size) diff --git a/tests/misc/tmemslices.nim b/tests/misc/tmemslices.nim index 8c658ad28..951807cc4 100644 --- a/tests/misc/tmemslices.nim +++ b/tests/misc/tmemslices.nim @@ -2,5 +2,5 @@ import memfiles var inp = memfiles.open("readme.txt") for mem in memSlices(inp): if mem.size > 3: - echo("#" & toString(mem) & "#") + echo("#" & $mem & "#") close(inp) From 9e8b4475e25adbe76331e6ab799443b1e2b62f7f Mon Sep 17 00:00:00 2001 From: Charles Blake Date: Mon, 3 Aug 2015 12:34:03 -0400 Subject: [PATCH 0789/1263] Spruce up doc comments as per dom96 suggestions. --- lib/pure/memfiles.nim | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/lib/pure/memfiles.nim b/lib/pure/memfiles.nim index c646c31a1..f78cd8766 100644 --- a/lib/pure/memfiles.nim +++ b/lib/pure/memfiles.nim @@ -263,12 +263,12 @@ proc `$`*(ms: MemSlice): string {.inline.} = iterator memSlices*(mfile: MemFile, delim='\l', eat='\r'): MemSlice {.inline.} = ## Iterates over [optional eat]delim-delimited slices in a MemFile. - ## Default delimiting is [\\r]\\l which parse Unix or Windows text file lines. + ## Default delimiting is [\\r]\\l which parses Unix/Windows text file lines. ## Pass eat='\\0' to be strictly delim-delimited. ## This zero copy, memchr-limited method is probably the fastest way to - ## iterate through lines in a file, however the returned (data,size) objects - ## are NOT Nim strings or even terminated C strings. So, be careful how data - ## is accessed (e.g., use C mem* functions, not str* functions). Example: + ## iterate through lines in a file. The returned (data,size) objects are + ## NOT Nim strings or even terminated C strings. So, be careful how data + ## is accessed (e.g., think C mem* functions, not str* functions). Example: ## ## .. code-block:: nim ## var count = 0 @@ -298,8 +298,13 @@ iterator memSlices*(mfile: MemFile, delim='\l', eat='\r'): MemSlice {.inline.} = iterator lines*(mfile: MemFile, buf: var TaintedString, delim='\l', eat='\r'): TaintedString {.inline.} = ## Replace contents of passed buffer with each new line, like readLine(File). - ## Default delimiting is [\\r]\\l which parse Unix or Windows text file lines. - ## Pass eat='\\0' to be strictly delim-delimited. + ## Default delimiting is [\\r]\\l which parses Unix/Windows text file lines. + ## Pass eat='\\0' to be strictly delim-delimited. Example: + ## + ## .. code-block:: nim + ## var buffer: TaintedString = "" + ## for line in lines(memfiles.open("foo"), buffer): + ## echo line for ms in memSlices(mfile, delim, eat): buf.setLen(ms.size) c_memcpy(addr(buf[0]), ms.data, ms.size) @@ -308,7 +313,7 @@ iterator lines*(mfile: MemFile, buf: var TaintedString, delim='\l', eat='\r'): T iterator lines*(mfile: MemFile, delim='\l', eat='\r'): TaintedString {.inline.} = ## Return each line in a file as a Nim string, like lines(File). - ## Default delimiting is [\\r]\\l which parse Unix or Windows text file lines. + ## Default delimiting is [\\r]\\l which parses Unix/Windows text file lines. ## Pass eat='\0' to be strictly delim-delimited. Example: ## ## .. code-block:: nim From 5497c964d0aaf3fa0a9b3c33b6b6691e3cc5b985 Mon Sep 17 00:00:00 2001 From: Charles Blake Date: Mon, 3 Aug 2015 12:35:57 -0400 Subject: [PATCH 0790/1263] Move tests to stdlib. --- tests/{misc => stdlib}/tmemlines.nim | 0 tests/{misc => stdlib}/tmemlinesBuf.nim | 0 tests/{misc => stdlib}/tmemslices.nim | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename tests/{misc => stdlib}/tmemlines.nim (100%) rename tests/{misc => stdlib}/tmemlinesBuf.nim (100%) rename tests/{misc => stdlib}/tmemslices.nim (100%) diff --git a/tests/misc/tmemlines.nim b/tests/stdlib/tmemlines.nim similarity index 100% rename from tests/misc/tmemlines.nim rename to tests/stdlib/tmemlines.nim diff --git a/tests/misc/tmemlinesBuf.nim b/tests/stdlib/tmemlinesBuf.nim similarity index 100% rename from tests/misc/tmemlinesBuf.nim rename to tests/stdlib/tmemlinesBuf.nim diff --git a/tests/misc/tmemslices.nim b/tests/stdlib/tmemslices.nim similarity index 100% rename from tests/misc/tmemslices.nim rename to tests/stdlib/tmemslices.nim From b9c1dd007279876f2f1d8a4085ffbfb0c9a27bb3 Mon Sep 17 00:00:00 2001 From: Dominik Picheta Date: Mon, 3 Aug 2015 18:42:02 +0100 Subject: [PATCH 0791/1263] Fixed macros.nim not compiling. Iterator aliases are not possible. --- lib/core/macros.nim | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/lib/core/macros.nim b/lib/core/macros.nim index 5d852cdb1..d371a92cf 100644 --- a/lib/core/macros.nim +++ b/lib/core/macros.nim @@ -724,7 +724,10 @@ iterator items*(n: NimNode): NimNode {.inline.} = for i in 0 ..< n.len: yield n[i] -iterator children*(n: NimNode): NimNode {.inline.} = items +iterator children*(n: NimNode): NimNode {.inline.} = + ## Iterates over the children of the NimNode ``n``. + for i in 0 ..< n.len: + yield n[i] template findChild*(n: NimNode; cond: expr): NimNode {. immediate, dirty.} = From 202cc489034f6e4f41140d7af82e93b112fcd3dd Mon Sep 17 00:00:00 2001 From: Dominik Picheta Date: Mon, 3 Aug 2015 21:28:33 +0100 Subject: [PATCH 0792/1263] The async macro now supports transforming multiple async procs. This is a workaround for #3182, no forward declarations. You can now do this: ```nim async: proc bar(): Future[T] proc foo() = await bar() proc bar() {.async.} = echo(123); await foo() ``` --- lib/pure/asyncdispatch.nim | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/lib/pure/asyncdispatch.nim b/lib/pure/asyncdispatch.nim index 7523b29d5..f49388b17 100644 --- a/lib/pure/asyncdispatch.nim +++ b/lib/pure/asyncdispatch.nim @@ -124,7 +124,8 @@ export Port, SocketFlag ## ## * The effect system (``raises: []``) does not work with async procedures. ## * Can't await in a ``except`` body - +## * Forward declarations for async procs are broken, +## link includes workaround: https://github.com/nim-lang/Nim/issues/3182. # TODO: Check if yielded future is nil and throw a more meaningful exception @@ -1412,12 +1413,12 @@ proc getName(node: NimNode): string {.compileTime.} = else: error("Unknown name.") -macro async*(prc: stmt): stmt {.immediate.} = - ## Macro which processes async procedures into the appropriate - ## iterators and yield statements. +proc asyncSingleProc(prc: NimNode): NimNode {.compileTime.} = + ## This macro transforms a single procedure into a closure iterator. + ## The ``async`` macro supports a stmtList holding multiple async procedures. if prc.kind notin {nnkProcDef, nnkLambda}: - error("Cannot transform this node kind into an async proc." & - " Proc definition or lambda node expected.") + error("Cannot transform this node kind into an async proc." & + " Proc definition or lambda node expected.") hint("Processing " & prc[0].getName & " as an async proc.") @@ -1504,9 +1505,19 @@ macro async*(prc: stmt): stmt {.immediate.} = result[6] = outerProcBody #echo(treeRepr(result)) - if prc[0].getName == "getAsync": + if prc[0].getName == "hubConnectionLoop": echo(toStrLit(result)) +macro async*(prc: stmt): stmt {.immediate.} = + ## Macro which processes async procedures into the appropriate + ## iterators and yield statements. + if prc.kind == nnkStmtList: + for oneProc in prc: + result = newStmtList() + result.add asyncSingleProc(oneProc) + else: + result = asyncSingleProc(prc) + proc recvLine*(socket: AsyncFD): Future[string] {.async.} = ## Reads a line of data from ``socket``. Returned future will complete once ## a full line is read or an error occurs. From f8f967720598ad75ec0e0db68a983cbcdd39145d Mon Sep 17 00:00:00 2001 From: Dominik Picheta Date: Tue, 4 Aug 2015 09:06:47 +0100 Subject: [PATCH 0793/1263] Updated documentation of system.new. Ref #2699. --- lib/system.nim | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/lib/system.nim b/lib/system.nim index 383002fcf..93d76e78b 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -178,7 +178,10 @@ proc new*[T](a: var ref T) {.magic: "New", noSideEffect.} proc new*(T: typedesc): auto = ## creates a new object of type ``T`` and returns a safe (traced) - ## reference to it as result value + ## reference to it as result value. + ## + ## When ``T`` is a ref type then the resulting type will be ``T``, + ## otherwise it will be ``ref T``. when (T is ref): var r: T else: From c03502943153a164ff8ccbe58c45117cb4eecd5b Mon Sep 17 00:00:00 2001 From: Erik Michaels-Ober Date: Tue, 4 Aug 2015 13:15:30 +0200 Subject: [PATCH 0794/1263] Fix documentation style reference The documentation style guide was renamed from styleguide to docstyle in a98f609ae215d1fcf9922329b5d87bd1b9242800 but this reference was not updated in that comment. --- contributing.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contributing.rst b/contributing.rst index 3b495f01f..e6d34dcb0 100644 --- a/contributing.rst +++ b/contributing.rst @@ -217,4 +217,4 @@ General commit rules 3. Describe your commit and use your common sense. -.. include:: styleguide.rst +.. include:: docstyle.rst From ab26298a035ed794fc73724a6ae06eefd6c764d3 Mon Sep 17 00:00:00 2001 From: Araq Date: Tue, 4 Aug 2015 17:31:00 +0200 Subject: [PATCH 0795/1263] added system.unsafeAddr --- compiler/parampatterns.nim | 20 +++++++++++--------- compiler/semexprs.nim | 6 +++--- compiler/semmagic.nim | 6 +++--- lib/system.nim | 7 +++++++ tests/ccgbugs/tunsafeaddr.nim | 19 +++++++++++++++++++ todo.txt | 1 - web/news.txt | 5 +++++ 7 files changed, 48 insertions(+), 16 deletions(-) create mode 100644 tests/ccgbugs/tunsafeaddr.nim diff --git a/compiler/parampatterns.nim b/compiler/parampatterns.nim index b7fe269df..ae391945a 100644 --- a/compiler/parampatterns.nim +++ b/compiler/parampatterns.nim @@ -178,13 +178,14 @@ type arDiscriminant, # is a discriminant arStrange # it is a strange beast like 'typedesc[var T]' -proc isAssignable*(owner: PSym, n: PNode): TAssignableResult = +proc isAssignable*(owner: PSym, n: PNode; isUnsafeAddr=false): TAssignableResult = ## 'owner' can be nil! result = arNone case n.kind of nkSym: - # don't list 'skLet' here: - if n.sym.kind in {skVar, skResult, skTemp}: + let kinds = if isUnsafeAddr: {skVar, skResult, skTemp, skParam, skLet} + else: {skVar, skResult, skTemp} + if n.sym.kind in kinds: if owner != nil and owner.id == n.sym.owner.id and sfGlobal notin n.sym.flags: result = arLocalLValue @@ -200,7 +201,7 @@ proc isAssignable*(owner: PSym, n: PNode): TAssignableResult = {tyVar, tyPtr, tyRef}: result = arLValue else: - result = isAssignable(owner, n.sons[0]) + result = isAssignable(owner, n.sons[0], isUnsafeAddr) if result != arNone and sfDiscriminant in n.sons[1].sym.flags: result = arDiscriminant of nkBracketExpr: @@ -208,23 +209,24 @@ proc isAssignable*(owner: PSym, n: PNode): TAssignableResult = {tyVar, tyPtr, tyRef}: result = arLValue else: - result = isAssignable(owner, n.sons[0]) + result = isAssignable(owner, n.sons[0], isUnsafeAddr) of nkHiddenStdConv, nkHiddenSubConv, nkConv: # Object and tuple conversions are still addressable, so we skip them # XXX why is 'tyOpenArray' allowed here? if skipTypes(n.typ, abstractPtrs-{tyTypeDesc}).kind in {tyOpenArray, tyTuple, tyObject}: - result = isAssignable(owner, n.sons[1]) + result = isAssignable(owner, n.sons[1], isUnsafeAddr) elif compareTypes(n.typ, n.sons[1].typ, dcEqIgnoreDistinct): # types that are equal modulo distinction preserve l-value: - result = isAssignable(owner, n.sons[1]) + result = isAssignable(owner, n.sons[1], isUnsafeAddr) of nkHiddenDeref, nkDerefExpr, nkHiddenAddr: result = arLValue of nkObjUpConv, nkObjDownConv, nkCheckedFieldExpr: - result = isAssignable(owner, n.sons[0]) + result = isAssignable(owner, n.sons[0], isUnsafeAddr) of nkCallKinds: # builtin slice keeps lvalue-ness: - if getMagic(n) == mSlice: result = isAssignable(owner, n.sons[1]) + if getMagic(n) == mSlice: + result = isAssignable(owner, n.sons[1], isUnsafeAddr) else: discard diff --git a/compiler/semexprs.nim b/compiler/semexprs.nim index fba64776d..b4308def3 100644 --- a/compiler/semexprs.nim +++ b/compiler/semexprs.nim @@ -597,8 +597,8 @@ proc skipObjConv(n: PNode): PNode = of nkObjUpConv, nkObjDownConv: result = n.sons[0] else: result = n -proc isAssignable(c: PContext, n: PNode): TAssignableResult = - result = parampatterns.isAssignable(c.p.owner, n) +proc isAssignable(c: PContext, n: PNode; isUnsafeAddr=false): TAssignableResult = + result = parampatterns.isAssignable(c.p.owner, n, isUnsafeAddr) proc newHiddenAddrTaken(c: PContext, n: PNode): PNode = if n.kind == nkHiddenDeref and not (gCmd == cmdCompileToCpp or @@ -1700,7 +1700,7 @@ proc semMagic(c: PContext, n: PNode, s: PSym, flags: TExprFlags): PNode = case s.magic # magics that need special treatment of mAddr: checkSonsLen(n, 2) - result = semAddr(c, n.sons[1]) + result = semAddr(c, n.sons[1], s.name.s == "unsafeAddr") of mTypeOf: checkSonsLen(n, 2) result = semTypeOf(c, n.sons[1]) diff --git a/compiler/semmagic.nim b/compiler/semmagic.nim index 0a7846f1d..0afbf1f07 100644 --- a/compiler/semmagic.nim +++ b/compiler/semmagic.nim @@ -10,10 +10,10 @@ # This include file implements the semantic checking for magics. # included from sem.nim -proc semAddr(c: PContext; n: PNode): PNode = +proc semAddr(c: PContext; n: PNode; isUnsafeAddr=false): PNode = result = newNodeI(nkAddr, n.info) let x = semExprWithType(c, n) - if isAssignable(c, x) notin {arLValue, arLocalLValue}: + if isAssignable(c, x, isUnsafeAddr) notin {arLValue, arLocalLValue}: localError(n.info, errExprHasNoAddress) result.add x result.typ = makePtrType(c, x.typ) @@ -119,7 +119,7 @@ proc magicsAfterOverloadResolution(c: PContext, n: PNode, case n[0].sym.magic of mAddr: checkSonsLen(n, 2) - result = semAddr(c, n.sons[1]) + result = semAddr(c, n.sons[1], n[0].sym.name.s == "unsafeAddr") of mTypeOf: checkSonsLen(n, 2) result = semTypeOf(c, n.sons[1]) diff --git a/lib/system.nim b/lib/system.nim index 93d76e78b..e5cae1336 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -153,6 +153,13 @@ proc `addr`*[T](x: var T): ptr T {.magic: "Addr", noSideEffect.} = ## Cannot be overloaded. discard +proc unsafeAddr*[T](x: var T): ptr T {.magic: "Addr", noSideEffect.} = + ## Builtin 'addr' operator for taking the address of a memory location. + ## This works even for ``let`` variables or parameters for better interop + ## with C and so it is considered even more unsafe than the ordinary ``addr``. + ## Cannot be overloaded. + discard + proc `type`*(x: expr): typeDesc {.magic: "TypeOf", noSideEffect.} = ## Builtin 'type' operator for accessing the type of an expression. ## Cannot be overloaded. diff --git a/tests/ccgbugs/tunsafeaddr.nim b/tests/ccgbugs/tunsafeaddr.nim new file mode 100644 index 000000000..4f05c7c21 --- /dev/null +++ b/tests/ccgbugs/tunsafeaddr.nim @@ -0,0 +1,19 @@ +discard """ + output: '''12''' +""" + +{.emit: """ +long sum(long* a, long len) { + long i, result = 0; + for (i = 0; i < len; ++i) result += a[i]; + return result; +} +""".} + +proc sum(a: ptr int; len: int): int {.importc, nodecl.} + +proc main = + let foo = [8, 3, 1] + echo sum(unsafeAddr foo[0], foo.len) + +main() diff --git a/todo.txt b/todo.txt index 8734b8f19..2955f2917 100644 --- a/todo.txt +++ b/todo.txt @@ -1,7 +1,6 @@ version 0.11.4 ============== -- ``unsafeAddr`` - document special cased varargs[untyped] and varargs[typed] - The remaining bugs of the lambda lifting pass that is responsible to enable diff --git a/web/news.txt b/web/news.txt index b72ae56d2..518793a4a 100644 --- a/web/news.txt +++ b/web/news.txt @@ -57,6 +57,11 @@ News Language Additions ------------------ + - ``system.unsafeAddr`` can be used to access the address of a ``let`` + variable or parameter for C interoperability. Since technically this + makes parameters and ``let`` variables mutable, it is considered even more + unsafe than the ordinary ``addr`` builtin. + Bugfixes -------- From abf15ec6ceb99bed8bf79a1a7a566596d32097bc Mon Sep 17 00:00:00 2001 From: Charles Blake Date: Tue, 4 Aug 2015 12:11:33 -0400 Subject: [PATCH 0796/1263] Expand memSlices doc comment & use better example. Have lines() iterators docs point back to memSlices() for details. --- lib/pure/memfiles.nim | 41 +++++++++++++++++++++++++++-------------- 1 file changed, 27 insertions(+), 14 deletions(-) diff --git a/lib/pure/memfiles.nim b/lib/pure/memfiles.nim index f78cd8766..a506d2c24 100644 --- a/lib/pure/memfiles.nim +++ b/lib/pure/memfiles.nim @@ -12,8 +12,8 @@ ## This module provides support for `memory mapped files`:idx: ## (Posix's `mmap`:idx:) on the different operating systems. ## -## It also provides some fast iterators over lines in text files -## delimited in Unix or Windows styles (or similarly delimited records). +## It also provides some fast iterators over lines in text files (or +## other "line-like", variable length, delimited records). when defined(windows): import winlean @@ -262,18 +262,30 @@ proc `$`*(ms: MemSlice): string {.inline.} = result = buf iterator memSlices*(mfile: MemFile, delim='\l', eat='\r'): MemSlice {.inline.} = - ## Iterates over [optional eat]delim-delimited slices in a MemFile. - ## Default delimiting is [\\r]\\l which parses Unix/Windows text file lines. - ## Pass eat='\\0' to be strictly delim-delimited. - ## This zero copy, memchr-limited method is probably the fastest way to - ## iterate through lines in a file. The returned (data,size) objects are - ## NOT Nim strings or even terminated C strings. So, be careful how data - ## is accessed (e.g., think C mem* functions, not str* functions). Example: + ## Iterates over [optional `eat`] `delim`-delimited slices in MemFile `mfile`. + ## + ## Default parameters parse lines ending in either Unix(\\l) or Windows(\\r\\l) + ## style on on a line-by-line basis. I.e., not every line needs the same ending. + ## Unlike readLine(File) & lines(File), archaic MacOS9 \\r-delimited lines + ## are not supported as a third option for each line. Such archaic MacOS9 + ## files can be handled by passing delim='\\r', eat='\\0', though. + ## + ## Non-default delimiters can be passed to allow iteration over other sorts + ## of "line-like" variable length records. Pass eat='\\0' to be strictly + ## `delim`-delimited. (Eating an optional prefix equal to '\\0' is not + ## supported.) + ## + ## This zero copy, memchr-limited interface is probably the fastest way to + ## iterate over line-like records in a file. However, returned (data,size) + ## objects are not Nim strings, bounds checked Nim arrays, or even terminated + ## C strings. So, care is required to access the data (e.g., think C mem* + ## functions, not str* functions). Example: ## ## .. code-block:: nim ## var count = 0 ## for slice in memSlices(memfiles.open("foo")): - ## inc(count) + ## if slice.size > 0 and cast[cstring](slice.data)[0] != '#': + ## inc(count) ## echo count proc c_memchr(cstr: pointer, c: char, n: csize): pointer {. @@ -298,13 +310,14 @@ iterator memSlices*(mfile: MemFile, delim='\l', eat='\r'): MemSlice {.inline.} = iterator lines*(mfile: MemFile, buf: var TaintedString, delim='\l', eat='\r'): TaintedString {.inline.} = ## Replace contents of passed buffer with each new line, like readLine(File). - ## Default delimiting is [\\r]\\l which parses Unix/Windows text file lines. - ## Pass eat='\\0' to be strictly delim-delimited. Example: + ## `delim`, `eat`, and delimiting logic is exactly as for memSlices, but Nim + ## strings are returned. Example: ## ## .. code-block:: nim ## var buffer: TaintedString = "" ## for line in lines(memfiles.open("foo"), buffer): ## echo line + for ms in memSlices(mfile, delim, eat): buf.setLen(ms.size) c_memcpy(addr(buf[0]), ms.data, ms.size) @@ -313,8 +326,8 @@ iterator lines*(mfile: MemFile, buf: var TaintedString, delim='\l', eat='\r'): T iterator lines*(mfile: MemFile, delim='\l', eat='\r'): TaintedString {.inline.} = ## Return each line in a file as a Nim string, like lines(File). - ## Default delimiting is [\\r]\\l which parses Unix/Windows text file lines. - ## Pass eat='\0' to be strictly delim-delimited. Example: + ## `delim`, `eat`, and delimiting logic is exactly as for memSlices, but Nim + ## strings are returned. Example: ## ## .. code-block:: nim ## for line in lines(memfiles.open("foo")): From 0487ad418040b0512603ec7f640307ab34895400 Mon Sep 17 00:00:00 2001 From: Charles Blake Date: Tue, 4 Aug 2015 13:16:27 -0400 Subject: [PATCH 0797/1263] Use hyperlinks to refer to other procs. --- lib/pure/memfiles.nim | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/lib/pure/memfiles.nim b/lib/pure/memfiles.nim index a506d2c24..15fa4c65e 100644 --- a/lib/pure/memfiles.nim +++ b/lib/pure/memfiles.nim @@ -309,9 +309,10 @@ iterator memSlices*(mfile: MemFile, delim='\l', eat='\r'): MemSlice {.inline.} = remaining = mfile.size - (ms.data -! mfile.mem) iterator lines*(mfile: MemFile, buf: var TaintedString, delim='\l', eat='\r'): TaintedString {.inline.} = - ## Replace contents of passed buffer with each new line, like readLine(File). - ## `delim`, `eat`, and delimiting logic is exactly as for memSlices, but Nim - ## strings are returned. Example: + ## Replace contents of passed buffer with each new line, like + ## `readLine(File) `_. + ## `delim`, `eat`, and delimiting logic is exactly as for + ## `memSlices <#memSlices>`_, but Nim strings are returned. Example: ## ## .. code-block:: nim ## var buffer: TaintedString = "" @@ -325,9 +326,10 @@ iterator lines*(mfile: MemFile, buf: var TaintedString, delim='\l', eat='\r'): T yield buf iterator lines*(mfile: MemFile, delim='\l', eat='\r'): TaintedString {.inline.} = - ## Return each line in a file as a Nim string, like lines(File). - ## `delim`, `eat`, and delimiting logic is exactly as for memSlices, but Nim - ## strings are returned. Example: + ## Return each line in a file as a Nim string, like + ## `lines(File) `_. + ## `delim`, `eat`, and delimiting logic is exactly as for + ## `memSlices <#memSlices>`_, but Nim strings are returned. Example: ## ## .. code-block:: nim ## for line in lines(memfiles.open("foo")): From 5ec4b7946fd8c916ac0cf0d94b42837a571adc68 Mon Sep 17 00:00:00 2001 From: Charles Blake Date: Tue, 4 Aug 2015 13:25:41 -0400 Subject: [PATCH 0798/1263] Add note about what is included. --- lib/pure/memfiles.nim | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lib/pure/memfiles.nim b/lib/pure/memfiles.nim index 15fa4c65e..00929eaa2 100644 --- a/lib/pure/memfiles.nim +++ b/lib/pure/memfiles.nim @@ -270,6 +270,9 @@ iterator memSlices*(mfile: MemFile, delim='\l', eat='\r'): MemSlice {.inline.} = ## are not supported as a third option for each line. Such archaic MacOS9 ## files can be handled by passing delim='\\r', eat='\\0', though. ## + ## Delimiters are not part of the returned slice. A final, unterminated line + ## or record is returned just like any other. + ## ## Non-default delimiters can be passed to allow iteration over other sorts ## of "line-like" variable length records. Pass eat='\\0' to be strictly ## `delim`-delimited. (Eating an optional prefix equal to '\\0' is not From 0d8942d45e5d477224d486ab66adfcf38230aa8b Mon Sep 17 00:00:00 2001 From: Araq Date: Wed, 5 Aug 2015 21:27:53 +0200 Subject: [PATCH 0799/1263] destructors now work with overloaded assignment operators; fixes #2811; fixes #1632 --- compiler/semdestruct.nim | 9 ++ compiler/semexprs.nim | 5 +- compiler/semstmts.nim | 20 +++-- compiler/transf.nim | 83 ++++++++++++++++++- tests/destructor/tdestructor3.nim | 47 +++++++++++ tests/exception/tdefer1.nim | 26 +++++- .../tdictdestruct.nim | 0 7 files changed, 175 insertions(+), 15 deletions(-) create mode 100644 tests/destructor/tdestructor3.nim rename tests/{destructor => generics}/tdictdestruct.nim (100%) diff --git a/compiler/semdestruct.nim b/compiler/semdestruct.nim index aaab49a10..af671f6e0 100644 --- a/compiler/semdestruct.nim +++ b/compiler/semdestruct.nim @@ -177,6 +177,15 @@ proc instantiateDestructor(c: PContext, typ: PType): PType = else: return nil +proc createDestructorCall(c: PContext, s: PSym): PNode = + let varTyp = s.typ + if varTyp == nil or sfGlobal in s.flags: return + let destructableT = instantiateDestructor(c, varTyp) + if destructableT != nil: + let call = semStmt(c, newNode(nkCall, s.info, @[ + useSym(destructableT.destructor), useSym(s)])) + result = newNode(nkDefer, s.info, @[call]) + proc insertDestructors(c: PContext, varSection: PNode): tuple[outer, inner: PNode] = # Accepts a var or let section. diff --git a/compiler/semexprs.nim b/compiler/semexprs.nim index b4308def3..af6919d97 100644 --- a/compiler/semexprs.nim +++ b/compiler/semexprs.nim @@ -2259,7 +2259,10 @@ proc semExpr(c: PContext, n: PNode, flags: TExprFlags = {}): PNode = of nkStaticStmt: result = semStaticStmt(c, n) of nkDefer: - localError(n.info, errGenerated, "'defer' not allowed in this context") + n.sons[0] = semExpr(c, n.sons[0]) + if not n.sons[0].typ.isEmptyType: + localError(n.info, errGenerated, "'defer' takes a 'void' expression") + #localError(n.info, errGenerated, "'defer' not allowed in this context") else: localError(n.info, errInvalidExpressionX, renderTree(n, {renderNoComments})) diff --git a/compiler/semstmts.nim b/compiler/semstmts.nim index 84a09a7e6..b9b175962 100644 --- a/compiler/semstmts.nim +++ b/compiler/semstmts.nim @@ -369,6 +369,15 @@ proc addToVarSection(c: PContext; result: var PNode; orig, identDefs: PNode) = else: result.add identDefs +proc addDefer(c: PContext; result: var PNode; s: PSym) = + let deferDestructorCall = createDestructorCall(c, s) + if deferDestructorCall != nil: + if result.kind != nkStmtList: + let oldResult = result + result = newNodeI(nkStmtList, result.info) + result.add oldResult + result.add deferDestructorCall + proc isDiscardUnderscore(v: PSym): bool = if v.name.s == "_": v.flags.incl(sfGenSym) @@ -469,6 +478,7 @@ proc semVarOrLet(c: PContext, n: PNode, symkind: TSymKind): PNode = if def.kind == nkPar: v.ast = def[j] v.typ = tup.sons[j] b.sons[j] = newSymNode(v) + addDefer(c, result, v) checkNilable(v) if sfCompileTime in v.flags: hasCompileTime = true if hasCompileTime: vm.setupCompileTimeVar(c.module, result) @@ -1371,7 +1381,7 @@ proc semStmtList(c: PContext, n: PNode, flags: TExprFlags): PNode = for i in countup(0, length - 1): let k = n.sons[i].kind case k - of nkFinally, nkExceptBranch, nkDefer: + of nkFinally, nkExceptBranch: # stand-alone finally and except blocks are # transformed into regular try blocks: # @@ -1424,14 +1434,6 @@ proc semStmtList(c: PContext, n: PNode, flags: TExprFlags): PNode = n.typ = n.sons[i].typ if not isEmptyType(n.typ): n.kind = nkStmtListExpr case n.sons[i].kind - of nkVarSection, nkLetSection: - let (outer, inner) = insertDestructors(c, n.sons[i]) - if outer != nil: - n.sons[i] = outer - var rest = newNode(nkStmtList, n.info, n.sons[i+1 .. length-1]) - inner.addSon(semStmtList(c, rest, flags)) - n.sons.setLen(i+1) - return of LastBlockStmts: for j in countup(i + 1, length - 1): case n.sons[j].kind diff --git a/compiler/transf.nim b/compiler/transf.nim index dddbd51c4..2ac5e1f39 100644 --- a/compiler/transf.nim +++ b/compiler/transf.nim @@ -16,6 +16,7 @@ # * converts "continue" to "break"; disambiguates "break" # * introduces method dispatchers # * performs lambda lifting for closure support +# * transforms 'defer' into a 'try finally' statement import intsets, strutils, lists, options, ast, astalgo, trees, treetab, msgs, os, @@ -44,6 +45,7 @@ type inlining: int # > 0 if we are in inlining context (copy vars) nestedProcs: int # > 0 if we are in a nested proc contSyms, breakSyms: seq[PSym] # to transform 'continue' and 'break' + deferDetected: bool PTransf = ref TTransfContext proc newTransNode(a: PNode): PTransNode {.inline.} = @@ -680,6 +682,14 @@ proc commonOptimizations*(c: PSym, n: PNode): PNode = result = n proc transform(c: PTransf, n: PNode): PTransNode = + when false: + var oldDeferAnchor: PNode + if n.kind in {nkElifBranch, nkOfBranch, nkExceptBranch, nkElifExpr, + nkElseExpr, nkElse, nkForStmt, nkWhileStmt, nkFinally, + nkBlockStmt, nkBlockExpr}: + oldDeferAnchor = c.deferAnchor + c.deferAnchor = n + case n.kind of nkSym: result = transformSym(c, n) @@ -712,13 +722,36 @@ proc transform(c: PTransf, n: PNode): PTransNode = result = transformFor(c, n) of nkParForStmt: result = transformSons(c, n) - of nkCaseStmt: result = transformCase(c, n) + of nkCaseStmt: + result = transformCase(c, n) + of nkWhileStmt: result = transformWhile(c, n) + of nkBlockStmt, nkBlockExpr: + result = transformBlock(c, n) + of nkDefer: + c.deferDetected = true + result = transformSons(c, n) + when false: + let deferPart = newNodeI(nkFinally, n.info) + deferPart.add n.sons[0] + let tryStmt = newNodeI(nkTryStmt, n.info) + if c.deferAnchor.isNil: + tryStmt.add c.root + c.root = tryStmt + result = PTransNode(tryStmt) + else: + # modify the corresponding *action*, don't rely on nkStmtList: + let L = c.deferAnchor.len-1 + tryStmt.add c.deferAnchor.sons[L] + c.deferAnchor.sons[L] = tryStmt + result = newTransNode(nkCommentStmt, n.info, 0) + tryStmt.addSon(deferPart) + # disable the original 'defer' statement: + n.kind = nkCommentStmt of nkContinueStmt: result = PTransNode(newNodeI(nkBreakStmt, n.info)) var labl = c.contSyms[c.contSyms.high] add(result, PTransNode(newSymNode(labl))) of nkBreakStmt: result = transformBreak(c, n) - of nkWhileStmt: result = transformWhile(c, n) of nkCallKinds: result = transformCall(c, n) of nkAddr, nkHiddenAddr: @@ -754,8 +787,6 @@ proc transform(c: PTransf, n: PNode): PTransNode = result = transformYield(c, n) else: result = transformSons(c, n) - of nkBlockStmt, nkBlockExpr: - result = transformBlock(c, n) of nkIdentDefs, nkConstDef: result = transformSons(c, n) # XXX comment handling really sucks: @@ -764,6 +795,8 @@ proc transform(c: PTransf, n: PNode): PTransNode = of nkClosure: return PTransNode(n) else: result = transformSons(c, n) + when false: + if oldDeferAnchor != nil: c.deferAnchor = oldDeferAnchor var cnst = getConstExpr(c.module, PNode(result)) # we inline constants if they are not complex constants: if cnst != nil and not dontInlineConstant(n, cnst): @@ -785,12 +818,52 @@ proc openTransf(module: PSym, filename: string): PTransf = result.breakSyms = @[] result.module = module +proc flattenStmts(n: PNode) = + var goOn = true + while goOn: + goOn = false + for i in 0.. Date: Wed, 5 Aug 2015 21:42:59 +0200 Subject: [PATCH 0800/1263] fix regressions --- compiler/transf.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/transf.nim b/compiler/transf.nim index 2ac5e1f39..5c7472a39 100644 --- a/compiler/transf.nim +++ b/compiler/transf.nim @@ -840,7 +840,7 @@ proc liftDeferAux(n: PNode) = let deferPart = newNodeI(nkFinally, n.sons[i].info) deferPart.add n.sons[i].sons[0] var tryStmt = newNodeI(nkTryStmt, n.sons[i].info) - var body = newNodeI(nkStmtList, n.sons[i].info) + var body = newNodeI(n.kind, n.sons[i].info) if i < last: body.sons = n.sons[(i+1)..last] tryStmt.addSon(body) From 41a2a9f00bd7e823223ce4b0830d6c9d8d6bc294 Mon Sep 17 00:00:00 2001 From: Yuriy Glukhov Date: Thu, 6 Aug 2015 22:19:33 +0300 Subject: [PATCH 0801/1263] Fixes #3185 --- compiler/semexprs.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/semexprs.nim b/compiler/semexprs.nim index af6919d97..0e9b9ae5f 100644 --- a/compiler/semexprs.nim +++ b/compiler/semexprs.nim @@ -2260,7 +2260,7 @@ proc semExpr(c: PContext, n: PNode, flags: TExprFlags = {}): PNode = result = semStaticStmt(c, n) of nkDefer: n.sons[0] = semExpr(c, n.sons[0]) - if not n.sons[0].typ.isEmptyType: + if not n.sons[0].typ.isEmptyType and not implicitlyDiscardable(n.sons[0]): localError(n.info, errGenerated, "'defer' takes a 'void' expression") #localError(n.info, errGenerated, "'defer' not allowed in this context") else: From 4a7c1d5fd7b0ed37fb4cd9b968f282ac48b53a4b Mon Sep 17 00:00:00 2001 From: Dominik Picheta Date: Thu, 6 Aug 2015 21:45:52 +0100 Subject: [PATCH 0802/1263] Don't crash on `nil` in get* procs in the JSON module. --- lib/pure/json.nim | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/lib/pure/json.nim b/lib/pure/json.nim index 49915b7e9..540a1a8eb 100644 --- a/lib/pure/json.nim +++ b/lib/pure/json.nim @@ -608,29 +608,29 @@ proc newJArray*(): JsonNode = proc getStr*(n: JsonNode, default: string = ""): string = ## Retrieves the string value of a `JString JsonNode`. ## - ## Returns ``default`` if ``n`` is not a ``JString``. - if n.kind != JString: return default + ## Returns ``default`` if ``n`` is not a ``JString``, or if ``n`` is nil. + if n.isNil or n.kind != JString: return default else: return n.str proc getNum*(n: JsonNode, default: BiggestInt = 0): BiggestInt = ## Retrieves the int value of a `JInt JsonNode`. ## - ## Returns ``default`` if ``n`` is not a ``JInt``. - if n.kind != JInt: return default + ## Returns ``default`` if ``n`` is not a ``JInt``, or if ``n`` is nil. + if n.isNil or n.kind != JInt: return default else: return n.num proc getFNum*(n: JsonNode, default: float = 0.0): float = ## Retrieves the float value of a `JFloat JsonNode`. ## - ## Returns ``default`` if ``n`` is not a ``JFloat``. - if n.kind != JFloat: return default + ## Returns ``default`` if ``n`` is not a ``JFloat``, or if ``n`` is nil. + if n.isNil or n.kind != JFloat: return default else: return n.fnum proc getBVal*(n: JsonNode, default: bool = false): bool = ## Retrieves the bool value of a `JBool JsonNode`. ## - ## Returns ``default`` if ``n`` is not a ``JBool``. - if n.kind != JBool: return default + ## Returns ``default`` if ``n`` is not a ``JBool``, or if ``n`` is nil. + if n.isNil or n.kind != JBool: return default else: return n.bval proc getFields*(n: JsonNode, @@ -638,15 +638,15 @@ proc getFields*(n: JsonNode, seq[tuple[key: string, val: JsonNode]] = ## Retrieves the key, value pairs of a `JObject JsonNode`. ## - ## Returns ``default`` if ``n`` is not a ``JObject``. - if n.kind != JObject: return default + ## Returns ``default`` if ``n`` is not a ``JObject``, or if ``n`` is nil. + if n.isNil or n.kind != JObject: return default else: return n.fields proc getElems*(n: JsonNode, default: seq[JsonNode] = @[]): seq[JsonNode] = ## Retrieves the int value of a `JArray JsonNode`. ## - ## Returns ``default`` if ``n`` is not a ``JArray``. - if n.kind != JArray: return default + ## Returns ``default`` if ``n`` is not a ``JArray``, or if ``n`` is nil. + if n.isNil or n.kind != JArray: return default else: return n.elems proc `%`*(s: string): JsonNode = From 842a26317cf23859d7dd9ca44818d3fbf872899e Mon Sep 17 00:00:00 2001 From: Yuriy Glukhov Date: Fri, 7 Aug 2015 00:20:40 +0300 Subject: [PATCH 0803/1263] Fixed defer test. --- tests/exception/tdefer1.nim | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/exception/tdefer1.nim b/tests/exception/tdefer1.nim index d7c691713..cb3d09b01 100644 --- a/tests/exception/tdefer1.nim +++ b/tests/exception/tdefer1.nim @@ -3,6 +3,7 @@ discard """ hi 1 hi +2 B A''' """ From 7bc3d7da75c0d3b504c90842016e887407e6ed40 Mon Sep 17 00:00:00 2001 From: Yuriy Glukhov Date: Fri, 7 Aug 2015 17:22:28 +0300 Subject: [PATCH 0804/1263] Fixes #3186 --- compiler/semstmts.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/semstmts.nim b/compiler/semstmts.nim index b9b175962..3d9363d77 100644 --- a/compiler/semstmts.nim +++ b/compiler/semstmts.nim @@ -1440,7 +1440,7 @@ proc semStmtList(c: PContext, n: PNode, flags: TExprFlags): PNode = of nkPragma, nkCommentStmt, nkNilLit, nkEmpty: discard else: localError(n.sons[j].info, errStmtInvalidAfterReturn) else: discard - if result.len == 1: + if result.len == 1 and result.sons[0].kind != nkDefer: result = result.sons[0] when defined(nimfix): if result.kind == nkCommentStmt and not result.comment.isNil and From 94e504113edfb93ac4eaf59cc78213323fa8a4c0 Mon Sep 17 00:00:00 2001 From: Araq Date: Fri, 7 Aug 2015 19:40:58 +0200 Subject: [PATCH 0805/1263] fixes #3193 --- lib/system.nim | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/system.nim b/lib/system.nim index 8cae7c5db..78769208c 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -188,7 +188,7 @@ proc new*(T: typedesc): auto = ## reference to it as result value. ## ## When ``T`` is a ref type then the resulting type will be ``T``, - ## otherwise it will be ``ref T``. + ## otherwise it will be ``ref T``. when (T is ref): var r: T else: @@ -572,6 +572,7 @@ proc unsafeNew*[T](a: var ref T, size: Natural) {.magic: "New", noSideEffect.} ## purposes when you know what you're doing! proc sizeof*[T](x: T): int {.magic: "SizeOf", noSideEffect.} +proc sizeof*(x: typedesc): int {.magic: "SizeOf", noSideEffect.} ## returns the size of ``x`` in bytes. Since this is a low-level proc, ## its usage is discouraged - using ``new`` for the most cases suffices ## that one never needs to know ``x``'s size. As a special semantic rule, From 2e4b59f3d3fc1ac99601988a482bad86a7ef7f53 Mon Sep 17 00:00:00 2001 From: Araq Date: Fri, 7 Aug 2015 20:29:38 +0200 Subject: [PATCH 0806/1263] fixes #3192 --- compiler/lambdalifting.nim | 2 +- compiler/vm.nim | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/compiler/lambdalifting.nim b/compiler/lambdalifting.nim index d11776cf6..c669fc745 100644 --- a/compiler/lambdalifting.nim +++ b/compiler/lambdalifting.nim @@ -184,7 +184,7 @@ proc addHiddenParam(routine: PSym, param: PSym) = var params = routine.ast.sons[paramsPos] # -1 is correct here as param.position is 0 based but we have at position 0 # some nkEffect node: - param.position = params.len-1 + param.position = routine.typ.n.len-1 addSon(params, newSymNode(param)) incl(routine.typ.flags, tfCapturesEnv) assert sfFromGeneric in param.flags diff --git a/compiler/vm.nim b/compiler/vm.nim index d7495d77f..e381af97f 100644 --- a/compiler/vm.nim +++ b/compiler/vm.nim @@ -432,7 +432,7 @@ proc rawExecute(c: PCtx, start: int, tos: PStackFrame): TFullReg = assert regs[rb].kind == rkNode let nb = regs[rb].node case nb.kind - of nkCharLit..nkInt64Lit: + of nkCharLit..nkUInt64Lit: ensureKind(rkInt) regs[ra].intVal = nb.intVal of nkFloatLit..nkFloat64Lit: From c733b3181ea21144fe485a5af3c78543a45d0564 Mon Sep 17 00:00:00 2001 From: Araq Date: Fri, 7 Aug 2015 21:28:45 +0200 Subject: [PATCH 0807/1263] breaking change: symbol lookups in generics follows spec more closely; fixes #2664 --- compiler/semgnrc.nim | 124 ++++++++++++++++---------------- lib/pure/collections/tables.nim | 8 +-- tests/generics/mclosed_sym.nim | 10 +++ tests/generics/tclosed_sym.nim | 11 +++ 4 files changed, 88 insertions(+), 65 deletions(-) create mode 100644 tests/generics/mclosed_sym.nim create mode 100644 tests/generics/tclosed_sym.nim diff --git a/compiler/semgnrc.nim b/compiler/semgnrc.nim index db910600b..205af36a8 100644 --- a/compiler/semgnrc.nim +++ b/compiler/semgnrc.nim @@ -39,9 +39,9 @@ type proc semGenericStmt(c: PContext, n: PNode, flags: TSemGenericFlags, ctx: var GenericCtx): PNode -proc semGenericStmtScope(c: PContext, n: PNode, +proc semGenericStmtScope(c: PContext, n: PNode, flags: TSemGenericFlags, - ctx: var GenericCtx): PNode = + ctx: var GenericCtx): PNode = openScope(c) result = semGenericStmt(c, n, flags, ctx) closeScope(c) @@ -73,7 +73,7 @@ proc semGenericStmtSymbol(c: PContext, n: PNode, s: PSym, result = semGenericStmt(c, result, {}, ctx) else: result = symChoice(c, n, s, scOpen) - of skGenericParam: + of skGenericParam: if s.typ != nil and s.typ.kind == tyStatic: if s.typ.n != nil: result = s.typ.n @@ -85,18 +85,18 @@ proc semGenericStmtSymbol(c: PContext, n: PNode, s: PSym, of skParam: result = n styleCheckUse(n.info, s) - of skType: + of skType: if (s.typ != nil) and (s.typ.flags * {tfGenericTypeParam, tfImplicitTypeParam} == {}): result = newSymNodeTypeDesc(s, n.info) - else: + else: result = n styleCheckUse(n.info, s) else: result = newSymNode(s, n.info) styleCheckUse(n.info, s) -proc lookup(c: PContext, n: PNode, flags: TSemGenericFlags, +proc lookup(c: PContext, n: PNode, flags: TSemGenericFlags, ctx: var GenericCtx): PNode = result = n let ident = considerQuotedIdent(n) @@ -118,13 +118,13 @@ proc newDot(n, b: PNode): PNode = result.add(n.sons[0]) result.add(b) -proc fuzzyLookup(c: PContext, n: PNode, flags: TSemGenericFlags, +proc fuzzyLookup(c: PContext, n: PNode, flags: TSemGenericFlags, ctx: var GenericCtx; isMacro: var bool): PNode = assert n.kind == nkDotExpr semIdeForTemplateOrGenericCheck(n, ctx.cursorInBody) let luf = if withinMixin notin flags: {checkUndeclared} else: {} - + var s = qualifiedLookUp(c, n, luf) if s != nil: result = semGenericStmtSymbol(c, n, s, ctx) @@ -141,18 +141,20 @@ proc fuzzyLookup(c: PContext, n: PNode, flags: TSemGenericFlags, elif s.name.id in ctx.toMixin: result = newDot(result, symChoice(c, n, s, scForceOpen)) else: - let sym = semGenericStmtSymbol(c, n, s, ctx) - if sym.kind == nkSym: - result = newDot(result, symChoice(c, n, s, scForceOpen)) + let syms = semGenericStmtSymbol(c, n, s, ctx) + if syms.kind == nkSym: + let choice = symChoice(c, n, s, scForceOpen) + choice.kind = nkClosedSymChoice + result = newDot(result, choice) else: - result = newDot(result, sym) + result = newDot(result, syms) proc addTempDecl(c: PContext; n: PNode; kind: TSymKind) = let s = newSymS(skUnknown, getIdentNode(n), c) addPrelimDecl(c, s) styleCheckDef(n.info, s, kind) -proc semGenericStmt(c: PContext, n: PNode, +proc semGenericStmt(c: PContext, n: PNode, flags: TSemGenericFlags, ctx: var GenericCtx): PNode = result = n #if gCmd == cmdIdeTools: suggestStmt(c, n) @@ -181,16 +183,16 @@ proc semGenericStmt(c: PContext, n: PNode, result = semGenericStmt(c, n.sons[0], flags+{withinBind}, ctx) of nkMixinStmt: result = semMixinStmt(c, n, ctx.toMixin) - of nkCall, nkHiddenCallConv, nkInfix, nkPrefix, nkCommand, nkCallStrLit: + of nkCall, nkHiddenCallConv, nkInfix, nkPrefix, nkCommand, nkCallStrLit: # check if it is an expression macro: checkMinSonsLen(n, 1) let fn = n.sons[0] var s = qualifiedLookUp(c, fn, {}) if s == nil and withinMixin notin flags and - fn.kind in {nkIdent, nkAccQuoted} and + fn.kind in {nkIdent, nkAccQuoted} and considerQuotedIdent(fn).id notin ctx.toMixin: localError(n.info, errUndeclaredIdentifier, fn.renderTree) - + var first = 0 var mixinContext = false if s != nil: @@ -220,7 +222,7 @@ proc semGenericStmt(c: PContext, n: PNode, # we need to put the ``c`` in ``t(c)`` in a mixin context to prevent # the famous "undeclared identifier: it" bug: mixinContext = true - of skUnknown, skParam: + of skUnknown, skParam: # Leave it as an identifier. discard of skProc, skMethod, skIterators, skConverter: @@ -230,9 +232,9 @@ proc semGenericStmt(c: PContext, n: PNode, result.sons[0] = newSymNodeTypeDesc(s, fn.info) styleCheckUse(fn.info, s) first = 1 - of skType: + of skType: # bad hack for generics: - if (s.typ != nil) and (s.typ.kind != tyGenericParam): + if (s.typ != nil) and (s.typ.kind != tyGenericParam): result.sons[0] = newSymNodeTypeDesc(s, fn.info) styleCheckUse(fn.info, s) first = 1 @@ -244,34 +246,34 @@ proc semGenericStmt(c: PContext, n: PNode, result.sons[0] = fuzzyLookup(c, fn, flags, ctx, mixinContext) first = 1 # Consider 'when declared(globalsSlot): ThreadVarSetValue(globalsSlot, ...)' - # in threads.nim: the subtle preprocessing here binds 'globalsSlot' which + # in threads.nim: the subtle preprocessing here binds 'globalsSlot' which # is not exported and yet the generic 'threadProcWrapper' works correctly. let flags = if mixinContext: flags+{withinMixin} else: flags for i in countup(first, sonsLen(result) - 1): result.sons[i] = semGenericStmt(c, result.sons[i], flags, ctx) - of nkIfStmt: - for i in countup(0, sonsLen(n)-1): + of nkIfStmt: + for i in countup(0, sonsLen(n)-1): n.sons[i] = semGenericStmtScope(c, n.sons[i], flags, ctx) of nkWhenStmt: for i in countup(0, sonsLen(n)-1): n.sons[i] = semGenericStmt(c, n.sons[i], flags+{withinMixin}, ctx) - of nkWhileStmt: + of nkWhileStmt: openScope(c) - for i in countup(0, sonsLen(n)-1): + for i in countup(0, sonsLen(n)-1): n.sons[i] = semGenericStmt(c, n.sons[i], flags, ctx) closeScope(c) - of nkCaseStmt: + of nkCaseStmt: openScope(c) n.sons[0] = semGenericStmt(c, n.sons[0], flags, ctx) - for i in countup(1, sonsLen(n)-1): + for i in countup(1, sonsLen(n)-1): var a = n.sons[i] checkMinSonsLen(a, 1) var L = sonsLen(a) - for j in countup(0, L-2): + for j in countup(0, L-2): a.sons[j] = semGenericStmt(c, a.sons[j], flags, ctx) a.sons[L - 1] = semGenericStmtScope(c, a.sons[L-1], flags, ctx) closeScope(c) - of nkForStmt, nkParForStmt: + of nkForStmt, nkParForStmt: var L = sonsLen(n) openScope(c) n.sons[L - 2] = semGenericStmt(c, n.sons[L-2], flags, ctx) @@ -279,27 +281,27 @@ proc semGenericStmt(c: PContext, n: PNode, addTempDecl(c, n.sons[i], skForVar) n.sons[L - 1] = semGenericStmt(c, n.sons[L-1], flags, ctx) closeScope(c) - of nkBlockStmt, nkBlockExpr, nkBlockType: + of nkBlockStmt, nkBlockExpr, nkBlockType: checkSonsLen(n, 2) openScope(c) - if n.sons[0].kind != nkEmpty: + if n.sons[0].kind != nkEmpty: addTempDecl(c, n.sons[0], skLabel) n.sons[1] = semGenericStmt(c, n.sons[1], flags, ctx) closeScope(c) - of nkTryStmt: + of nkTryStmt: checkMinSonsLen(n, 2) n.sons[0] = semGenericStmtScope(c, n.sons[0], flags, ctx) - for i in countup(1, sonsLen(n)-1): + for i in countup(1, sonsLen(n)-1): var a = n.sons[i] checkMinSonsLen(a, 1) var L = sonsLen(a) - for j in countup(0, L-2): + for j in countup(0, L-2): a.sons[j] = semGenericStmt(c, a.sons[j], flags+{withinTypeDesc}, ctx) a.sons[L-1] = semGenericStmtScope(c, a.sons[L-1], flags, ctx) - of nkVarSection, nkLetSection: - for i in countup(0, sonsLen(n) - 1): + of nkVarSection, nkLetSection: + for i in countup(0, sonsLen(n) - 1): var a = n.sons[i] - if a.kind == nkCommentStmt: continue + if a.kind == nkCommentStmt: continue if (a.kind != nkIdentDefs) and (a.kind != nkVarTuple): illFormedAst(a) checkMinSonsLen(a, 3) var L = sonsLen(a) @@ -307,49 +309,49 @@ proc semGenericStmt(c: PContext, n: PNode, a.sons[L-1] = semGenericStmt(c, a.sons[L-1], flags, ctx) for j in countup(0, L-3): addTempDecl(c, getIdentNode(a.sons[j]), skVar) - of nkGenericParams: - for i in countup(0, sonsLen(n) - 1): + of nkGenericParams: + for i in countup(0, sonsLen(n) - 1): var a = n.sons[i] if (a.kind != nkIdentDefs): illFormedAst(a) checkMinSonsLen(a, 3) var L = sonsLen(a) - a.sons[L-2] = semGenericStmt(c, a.sons[L-2], flags+{withinTypeDesc}, ctx) - # do not perform symbol lookup for default expressions - for j in countup(0, L-3): + a.sons[L-2] = semGenericStmt(c, a.sons[L-2], flags+{withinTypeDesc}, ctx) + # do not perform symbol lookup for default expressions + for j in countup(0, L-3): addTempDecl(c, getIdentNode(a.sons[j]), skType) - of nkConstSection: - for i in countup(0, sonsLen(n) - 1): + of nkConstSection: + for i in countup(0, sonsLen(n) - 1): var a = n.sons[i] - if a.kind == nkCommentStmt: continue + if a.kind == nkCommentStmt: continue if (a.kind != nkConstDef): illFormedAst(a) checkSonsLen(a, 3) addTempDecl(c, getIdentNode(a.sons[0]), skConst) a.sons[1] = semGenericStmt(c, a.sons[1], flags+{withinTypeDesc}, ctx) a.sons[2] = semGenericStmt(c, a.sons[2], flags, ctx) of nkTypeSection: - for i in countup(0, sonsLen(n) - 1): + for i in countup(0, sonsLen(n) - 1): var a = n.sons[i] - if a.kind == nkCommentStmt: continue + if a.kind == nkCommentStmt: continue if (a.kind != nkTypeDef): illFormedAst(a) checkSonsLen(a, 3) addTempDecl(c, getIdentNode(a.sons[0]), skType) - for i in countup(0, sonsLen(n) - 1): + for i in countup(0, sonsLen(n) - 1): var a = n.sons[i] - if a.kind == nkCommentStmt: continue + if a.kind == nkCommentStmt: continue if (a.kind != nkTypeDef): illFormedAst(a) checkSonsLen(a, 3) - if a.sons[1].kind != nkEmpty: + if a.sons[1].kind != nkEmpty: openScope(c) a.sons[1] = semGenericStmt(c, a.sons[1], flags, ctx) a.sons[2] = semGenericStmt(c, a.sons[2], flags+{withinTypeDesc}, ctx) closeScope(c) - else: + else: a.sons[2] = semGenericStmt(c, a.sons[2], flags+{withinTypeDesc}, ctx) - of nkEnumTy: + of nkEnumTy: if n.sonsLen > 0: - if n.sons[0].kind != nkEmpty: + if n.sons[0].kind != nkEmpty: n.sons[0] = semGenericStmt(c, n.sons[0], flags+{withinTypeDesc}, ctx) - for i in countup(1, sonsLen(n) - 1): + for i in countup(1, sonsLen(n) - 1): var a: PNode case n.sons[i].kind of nkEnumFieldDef: a = n.sons[i].sons[0] @@ -360,26 +362,26 @@ proc semGenericStmt(c: PContext, n: PNode, discard of nkFormalParams: checkMinSonsLen(n, 1) - if n.sons[0].kind != nkEmpty: + if n.sons[0].kind != nkEmpty: n.sons[0] = semGenericStmt(c, n.sons[0], flags+{withinTypeDesc}, ctx) - for i in countup(1, sonsLen(n) - 1): + for i in countup(1, sonsLen(n) - 1): var a = n.sons[i] if (a.kind != nkIdentDefs): illFormedAst(a) checkMinSonsLen(a, 3) var L = sonsLen(a) a.sons[L-2] = semGenericStmt(c, a.sons[L-2], flags+{withinTypeDesc}, ctx) a.sons[L-1] = semGenericStmt(c, a.sons[L-1], flags, ctx) - for j in countup(0, L-3): + for j in countup(0, L-3): addTempDecl(c, getIdentNode(a.sons[j]), skParam) - of nkProcDef, nkMethodDef, nkConverterDef, nkMacroDef, nkTemplateDef, - nkIteratorDef, nkLambdaKinds: + of nkProcDef, nkMethodDef, nkConverterDef, nkMacroDef, nkTemplateDef, + nkIteratorDef, nkLambdaKinds: checkSonsLen(n, bodyPos + 1) if n.sons[namePos].kind != nkEmpty: addTempDecl(c, getIdentNode(n.sons[0]), skProc) openScope(c) - n.sons[genericParamsPos] = semGenericStmt(c, n.sons[genericParamsPos], + n.sons[genericParamsPos] = semGenericStmt(c, n.sons[genericParamsPos], flags, ctx) - if n.sons[paramsPos].kind != nkEmpty: + if n.sons[paramsPos].kind != nkEmpty: if n.sons[paramsPos].sons[0].kind != nkEmpty: addPrelimDecl(c, newSym(skUnknown, getIdent("result"), nil, n.info)) n.sons[paramsPos] = semGenericStmt(c, n.sons[paramsPos], flags, ctx) @@ -394,7 +396,7 @@ proc semGenericStmt(c: PContext, n: PNode, checkMinSonsLen(n, 2) result.sons[1] = semGenericStmt(c, n.sons[1], flags, ctx) else: - for i in countup(0, sonsLen(n) - 1): + for i in countup(0, sonsLen(n) - 1): result.sons[i] = semGenericStmt(c, n.sons[i], flags, ctx) proc semGenericStmt(c: PContext, n: PNode): PNode = diff --git a/lib/pure/collections/tables.nim b/lib/pure/collections/tables.nim index ec0d9623f..be6b755ed 100644 --- a/lib/pure/collections/tables.nim +++ b/lib/pure/collections/tables.nim @@ -226,6 +226,10 @@ proc `$`*[A, B](t: Table[A, B]): string = ## The `$` operator for hash tables. dollarImpl() +proc hasKey*[A, B](t: TableRef[A, B], key: A): bool = + ## returns true iff `key` is in the table `t`. + result = t[].hasKey(key) + template equalsImpl() = if s.counter == t.counter: # different insertion orders mean different 'data' seqs, so we have @@ -293,10 +297,6 @@ proc hasKeyOrPut*[A, B](t: var TableRef[A, B], key: A, val: B): bool = ## returns true iff `key` is in the table, otherwise inserts `value`. t[].hasKeyOrPut(key, val) -proc hasKey*[A, B](t: TableRef[A, B], key: A): bool = - ## returns true iff `key` is in the table `t`. - result = t[].hasKey(key) - proc contains*[A, B](t: TableRef[A, B], key: A): bool = ## alias of `hasKey` for use with the `in` operator. return hasKey[A, B](t, key) diff --git a/tests/generics/mclosed_sym.nim b/tests/generics/mclosed_sym.nim new file mode 100644 index 000000000..bcccd9a85 --- /dev/null +++ b/tests/generics/mclosed_sym.nim @@ -0,0 +1,10 @@ + +type R* = object + +type Data*[T] = object + d*: T + +proc same(r:R, d:int) = echo "TEST2" + +proc doIt*(d:Data, r:R) = + r.same(1) # Expecting this to invoke the local `same()` method diff --git a/tests/generics/tclosed_sym.nim b/tests/generics/tclosed_sym.nim new file mode 100644 index 000000000..ff620c267 --- /dev/null +++ b/tests/generics/tclosed_sym.nim @@ -0,0 +1,11 @@ +discard """ + output: "TEST2" +""" + +# bug #2664 + +import mclosed_sym + +proc same(r:R, d:int) = echo "TEST1" + +doIt(Data[int](d:123), R()) From 87815cbdf76a7aa7c414d0fb82b46778fa1d8b92 Mon Sep 17 00:00:00 2001 From: Araq Date: Fri, 7 Aug 2015 22:32:06 +0200 Subject: [PATCH 0808/1263] attempt to fix bootstrapping; refs #3139 --- compiler/condsyms.nim | 1 + lib/system.nim | 4 +++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/compiler/condsyms.nim b/compiler/condsyms.nim index aecbde66e..297b865b2 100644 --- a/compiler/condsyms.nim +++ b/compiler/condsyms.nim @@ -90,3 +90,4 @@ proc initDefines*() = defineSymbol("nimnode") defineSymbol("nimnomagic64") defineSymbol("nimvarargstyped") + defineSymbol("nimtypedescfixed") diff --git a/lib/system.nim b/lib/system.nim index 78769208c..7dae074f3 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -572,12 +572,14 @@ proc unsafeNew*[T](a: var ref T, size: Natural) {.magic: "New", noSideEffect.} ## purposes when you know what you're doing! proc sizeof*[T](x: T): int {.magic: "SizeOf", noSideEffect.} -proc sizeof*(x: typedesc): int {.magic: "SizeOf", noSideEffect.} ## returns the size of ``x`` in bytes. Since this is a low-level proc, ## its usage is discouraged - using ``new`` for the most cases suffices ## that one never needs to know ``x``'s size. As a special semantic rule, ## ``x`` may also be a type identifier (``sizeof(int)`` is valid). +when defined(nimtypedescfixed): + proc sizeof*(x: typedesc): int {.magic: "SizeOf", noSideEffect.} + proc `<`*[T](x: Ordinal[T]): T {.magic: "UnaryLt", noSideEffect.} ## unary ``<`` that can be used for nice looking excluding ranges: ## From 4f8d982d5b0944f7f2bfc905c428ed81c3bd75bd Mon Sep 17 00:00:00 2001 From: Araq Date: Sat, 8 Aug 2015 14:39:32 +0200 Subject: [PATCH 0809/1263] fixes #2670 --- compiler/semtempl.nim | 23 +++++++++++++++++++---- tests/template/twhen_gensym.nim | 13 +++++++++++++ 2 files changed, 32 insertions(+), 4 deletions(-) create mode 100644 tests/template/twhen_gensym.nim diff --git a/compiler/semtempl.nim b/compiler/semtempl.nim index a138981b7..4d1eae48f 100644 --- a/compiler/semtempl.nim +++ b/compiler/semtempl.nim @@ -184,10 +184,25 @@ proc addLocalDecl(c: var TemplCtx, n: var PNode, k: TSymKind) = else: let ident = getIdentNode(c, n) if not isTemplParam(c, ident): - let local = newGenSym(k, ident, c) - addPrelimDecl(c.c, local) - styleCheckDef(n.info, local) - replaceIdentBySym(n, newSymNode(local, n.info)) + # fix #2670, consider: + # + # when b: + # var a = "hi" + # else: + # var a = 5 + # echo a + # + # We need to ensure that both 'a' produce the same gensym'ed symbol. + # So we need only check the *current* scope. + let s = localSearchInScope(c.c, considerQuotedIdent ident) + if s != nil and s.owner == c.owner and sfGenSym in s.flags: + styleCheckUse(n.info, s) + replaceIdentBySym(n, newSymNode(s, n.info)) + else: + let local = newGenSym(k, ident, c) + addPrelimDecl(c.c, local) + styleCheckDef(n.info, local) + replaceIdentBySym(n, newSymNode(local, n.info)) else: replaceIdentBySym(n, ident) diff --git a/tests/template/twhen_gensym.nim b/tests/template/twhen_gensym.nim new file mode 100644 index 000000000..d84ee6f03 --- /dev/null +++ b/tests/template/twhen_gensym.nim @@ -0,0 +1,13 @@ +discard """ + output: "hi" +""" + +# bug #2670 +template testTemplate(b: bool): stmt = + when b: + var a = "hi" + else: + var a = 5 + echo a + +testTemplate(true) From 930e90a73058b4ae51364f4c8c4f83a04149a645 Mon Sep 17 00:00:00 2001 From: tulayang Date: Sun, 9 Aug 2015 20:35:23 +0800 Subject: [PATCH 0810/1263] Modify proc parseHeader --- lib/pure/asynchttpserver.nim | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/lib/pure/asynchttpserver.nim b/lib/pure/asynchttpserver.nim index 9e036443c..d9480475a 100644 --- a/lib/pure/asynchttpserver.nim +++ b/lib/pure/asynchttpserver.nim @@ -126,8 +126,11 @@ proc parseHeader(line: string): tuple[key, value: string] = var i = 0 i = line.parseUntil(result.key, ':') inc(i) # skip : - i += line.skipWhiteSpace(i) - i += line.parseUntil(result.value, {'\c', '\L'}, i) + if i < len(line): + i += line.skipWhiteSpace(i) + i += line.parseUntil(result.value, {'\c', '\L'}, i) + else: + result.value = "" proc parseProtocol(protocol: string): tuple[orig: string, major, minor: int] = var i = protocol.skipIgnoreCase("HTTP/") From 35f8cc0bdde8e923eaca8830676f1b2ad6ffe300 Mon Sep 17 00:00:00 2001 From: Araq Date: Sun, 9 Aug 2015 20:18:49 +0200 Subject: [PATCH 0811/1263] fixes #2752 --- compiler/seminst.nim | 7 +++--- tests/generics/tdont_use_inner_scope.nim | 27 ++++++++++++++++++++++++ todo.txt | 4 ---- 3 files changed, 31 insertions(+), 7 deletions(-) create mode 100644 tests/generics/tdont_use_inner_scope.nim diff --git a/compiler/seminst.nim b/compiler/seminst.nim index b2aef63a8..df5865b6b 100644 --- a/compiler/seminst.nim +++ b/compiler/seminst.nim @@ -226,13 +226,14 @@ proc generateInstance(c: PContext, fn: PSym, pt: TIdTable, # NOTE: for access of private fields within generics from a different module # we set the friend module: c.friendModules.add(getModule(fn)) - #let oldScope = c.currentScope - #c.currentScope = fn.scope + let oldScope = c.currentScope + while not isTopLevel(c): c.currentScope = c.currentScope.parent result = copySym(fn, false) incl(result.flags, sfFromGeneric) result.owner = fn result.ast = n pushOwner(result) + openScope(c) internalAssert n.sons[genericParamsPos].kind != nkEmpty n.sons[namePos] = newSymNode(result) @@ -264,7 +265,7 @@ proc generateInstance(c: PContext, fn: PSym, pt: TIdTable, popInfoContext() closeScope(c) # close scope for parameters popOwner() - #c.currentScope = oldScope + c.currentScope = oldScope discard c.friendModules.pop() dec(c.instCounter) if result.kind == skMethod: finishMethod(c, result) diff --git a/tests/generics/tdont_use_inner_scope.nim b/tests/generics/tdont_use_inner_scope.nim new file mode 100644 index 000000000..45b11fc22 --- /dev/null +++ b/tests/generics/tdont_use_inner_scope.nim @@ -0,0 +1,27 @@ + +# bug #2752 + +import future, sequtils + +proc myFilter[T](it: (iterator(): T), f: (proc(anything: T):bool)): (iterator(): T) = + iterator aNameWhichWillConflict(): T {.closure.}= + for x in it(): + if f(x): + yield x + result = aNameWhichWillConflict + + +iterator testIt():int {.closure.}= + yield -1 + yield 2 + +#let unusedVariable = myFilter(testIt, (x: int) => x > 0) + +proc onlyPos(it: (iterator(): int)): (iterator(): int)= + iterator aNameWhichWillConflict(): int {.closure.}= + var filtered = onlyPos(myFilter(it, (x:int) => x > 0)) + for x in filtered(): + yield x + result = aNameWhichWillConflict + +let x = onlyPos(testIt) diff --git a/todo.txt b/todo.txt index 2955f2917..d7e1f3504 100644 --- a/todo.txt +++ b/todo.txt @@ -61,10 +61,8 @@ Bugs - VM: Pegs do not work at compile-time - VM: ptr/ref T cannot work in general -- scopes are still broken for generic instantiation! - blocks can "export" an identifier but the CCG generates {} for them ... - ConcreteTypes in a 'case' means we don't check for duplicated case branches -- typedesc matches a generic type T! version 0.9.x @@ -79,8 +77,6 @@ version 0.9.x - implement 'bits' pragmas - we need a magic thisModule symbol - optimize 'genericReset'; 'newException' leads to code bloat -- The 'do' notation might be trimmed so that its only purpose is to pass - multiple multi line constructs to a macro. version 0.9.X From cf4879bc48f39a7fbdd030431be4ffe968e2a555 Mon Sep 17 00:00:00 2001 From: Araq Date: Sun, 9 Aug 2015 20:28:49 +0200 Subject: [PATCH 0812/1263] added sequtils.reversed; refs #3148 --- lib/pure/collections/sequtils.nim | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/lib/pure/collections/sequtils.nim b/lib/pure/collections/sequtils.nim index 5fac1f0af..1e75376df 100644 --- a/lib/pure/collections/sequtils.nim +++ b/lib/pure/collections/sequtils.nim @@ -451,6 +451,21 @@ template newSeqWith*(len: int, init: expr): expr = result[i] = init result +proc reversed*[T](s: seq[T]): seq[T] = + ## Takes a sequences and returns a new reversed one + ## + ## Example: + ## + ## .. code-block:: + ## + ## let s1 = @[1, 2, 3, 4, 5] + ## let s2 = @[5, 4, 3, 2, 1] + ## assert s2 == s1.reversed() + ## + result = s + let ln = result.len + for i in 0..(ln div 2)-1: swap(result[i], result[ln-i-1]) + when isMainModule: import strutils block: # concat test @@ -615,5 +630,13 @@ when isMainModule: #doAssert a.repeat(-1) == @[] # will not compile! doAssert b.repeat(3) == @[] + block: # reversed tests: + let + a = @[1, 2, 3] + b: seq[int] = @[] + + doAssert a.reversed == @[3, 2, 1] + doAssert b.reversed == @[] + when not defined(testing): echo "Finished doc tests" From 0fc43d3d950714d779221382bbb08775c508b4e9 Mon Sep 17 00:00:00 2001 From: Araq Date: Sun, 9 Aug 2015 23:07:33 +0200 Subject: [PATCH 0813/1263] updated todo.txt --- todo.txt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/todo.txt b/todo.txt index d7e1f3504..ee1d6fa87 100644 --- a/todo.txt +++ b/todo.txt @@ -1,6 +1,9 @@ version 0.11.4 ============== +- deprecate toplevel .closure procs +- deprecate closure iterator construction via ``var cl = foo`` + - document special cased varargs[untyped] and varargs[typed] - The remaining bugs of the lambda lifting pass that is responsible to enable From 50861792f447d1a5213fcc9ebbfefae6ee146830 Mon Sep 17 00:00:00 2001 From: Araq Date: Sun, 9 Aug 2015 23:07:53 +0200 Subject: [PATCH 0814/1263] fixes #1329 --- compiler/vmgen.nim | 2 ++ tests/vm/tstaticprintseq.nim | 12 +++++++++++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/compiler/vmgen.nim b/compiler/vmgen.nim index 1bee9788a..6a59b3384 100644 --- a/compiler/vmgen.nim +++ b/compiler/vmgen.nim @@ -1105,6 +1105,8 @@ proc genAddrDeref(c: PCtx; n: PNode; dest: var TDest; opc: TOpcode; # nkAddr we must not use 'unneededIndirection', but for deref we use it. if not isAddr and unneededIndirection(n.sons[0]): gen(c, n.sons[0], dest, newflags) + if gfAddrOf notin flags and fitsRegister(n.typ): + c.gABC(n, opcNodeToReg, dest, dest) elif isAddr and isGlobal(n.sons[0]): gen(c, n.sons[0], dest, flags+{gfAddrOf}) else: diff --git a/tests/vm/tstaticprintseq.nim b/tests/vm/tstaticprintseq.nim index b002d366c..e4a6aa081 100644 --- a/tests/vm/tstaticprintseq.nim +++ b/tests/vm/tstaticprintseq.nim @@ -18,7 +18,8 @@ bb aa bb 24 -2147483647 2147483647''' +2147483647 2147483647 +5''' """ const s = @[1,2,3] @@ -80,3 +81,12 @@ static: static: var foo2 = int32.high echo foo2, " ", int32.high + +# bug #1329 + +static: + var a: ref int + new(a) + a[] = 5 + + echo a[] From bbf9757b4e70c7a11701656bc7755d7d76669dad Mon Sep 17 00:00:00 2001 From: Araq Date: Sun, 9 Aug 2015 23:21:44 +0200 Subject: [PATCH 0815/1263] refs #2377 --- compiler/rodread.nim | 2 ++ 1 file changed, 2 insertions(+) diff --git a/compiler/rodread.nim b/compiler/rodread.nim index 92ce00240..e4530c2cc 100644 --- a/compiler/rodread.nim +++ b/compiler/rodread.nim @@ -898,6 +898,8 @@ proc getBody*(s: PSym): PNode = ## it may perform an expensive reload operation. Otherwise it's a simple ## accessor. assert s.kind in routineKinds + # prevent crashes due to incorrect macro transformations (bug #2377) + if s.ast.isNil or bodyPos >= s.ast.len: return ast.emptyNode result = s.ast.sons[bodyPos] if result == nil: assert s.offset != 0 From f934c9213220bbb4f0ac13aa804ab14c3393202e Mon Sep 17 00:00:00 2001 From: Araq Date: Sun, 9 Aug 2015 23:37:13 +0200 Subject: [PATCH 0816/1263] fixes #3096 --- compiler/semtypes.nim | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/compiler/semtypes.nim b/compiler/semtypes.nim index 3bb1284fc..5ae3d16c0 100644 --- a/compiler/semtypes.nim +++ b/compiler/semtypes.nim @@ -508,8 +508,9 @@ proc semRecordCase(c: PContext, n: PNode, check: var IntSet, pos: var int, var typ = skipTypes(a.sons[0].typ, abstractVar-{tyTypeDesc}) if not isOrdinalType(typ): localError(n.info, errSelectorMustBeOrdinal) - elif firstOrd(typ) < 0: - localError(n.info, errOrdXMustNotBeNegative, a.sons[0].sym.name.s) + elif firstOrd(typ) != 0: + localError(n.info, errGenerated, "low(" & $a.sons[0].sym.name.s & + ") must be 0 for discriminant") elif lengthOrd(typ) > 0x00007FFF: localError(n.info, errLenXinvalid, a.sons[0].sym.name.s) var chckCovered = true From 799e0f3274edd9d0fadcc58640afa32b3bdc6da1 Mon Sep 17 00:00:00 2001 From: Araq Date: Sun, 9 Aug 2015 23:53:22 +0200 Subject: [PATCH 0817/1263] fixes #3066 --- compiler/vmgen.nim | 3 +++ tests/vm/tforwardproc.nim | 17 +++++++++++++++++ 2 files changed, 20 insertions(+) create mode 100644 tests/vm/tforwardproc.nim diff --git a/compiler/vmgen.nim b/compiler/vmgen.nim index 6a59b3384..73fcc5a27 100644 --- a/compiler/vmgen.nim +++ b/compiler/vmgen.nim @@ -1184,6 +1184,9 @@ proc checkCanEval(c: PCtx; n: PNode) = if s.kind in {skVar, skTemp, skLet, skParam, skResult} and not s.isOwnedBy(c.prc.sym) and s.owner != c.module: cannotEval(n) + elif s.kind in {skProc, skConverter, skMethod, + skIterator, skClosureIterator} and sfForward in s.flags: + cannotEval(n) proc isTemp(c: PCtx; dest: TDest): bool = result = dest >= 0 and c.prc.slots[dest].kind >= slotTempUnknown diff --git a/tests/vm/tforwardproc.nim b/tests/vm/tforwardproc.nim new file mode 100644 index 000000000..727ac6641 --- /dev/null +++ b/tests/vm/tforwardproc.nim @@ -0,0 +1,17 @@ +discard """ + errormsg: "cannot evaluate at compile time: initArray" + line: 11 +""" + +# bug #3066 + +proc initArray(): array[10, int] + +const + someTable = initArray() + +proc initArray(): array[10, int] = + for f in 0..<10: + result[f] = 3 + +when isMainModule: echo repr(someTable) From 36a90c6044ecc1b5e193766b62ae4ea58aadf45d Mon Sep 17 00:00:00 2001 From: Araq Date: Mon, 10 Aug 2015 01:31:42 +0200 Subject: [PATCH 0818/1263] fixes #1965 --- compiler/semgnrc.nim | 4 ++-- tests/generics/mmodule_same_as_proc.nim | 2 ++ tests/generics/tmodule_same_as_proc.nim | 9 +++++++++ 3 files changed, 13 insertions(+), 2 deletions(-) create mode 100644 tests/generics/mmodule_same_as_proc.nim create mode 100644 tests/generics/tmodule_same_as_proc.nim diff --git a/compiler/semgnrc.nim b/compiler/semgnrc.nim index 205af36a8..e3b598919 100644 --- a/compiler/semgnrc.nim +++ b/compiler/semgnrc.nim @@ -57,7 +57,7 @@ proc semGenericStmtSymbol(c: PContext, n: PNode, s: PSym, of skUnknown: # Introduced in this pass! Leave it as an identifier. result = n - of skProc, skMethod, skIterators, skConverter: + of skProc, skMethod, skIterators, skConverter, skModule: result = symChoice(c, n, s, scOpen) of skTemplate: if macroToExpand(s): @@ -225,7 +225,7 @@ proc semGenericStmt(c: PContext, n: PNode, of skUnknown, skParam: # Leave it as an identifier. discard - of skProc, skMethod, skIterators, skConverter: + of skProc, skMethod, skIterators, skConverter, skModule: result.sons[0] = symChoice(c, fn, s, scOption) first = 1 of skGenericParam: diff --git a/tests/generics/mmodule_same_as_proc.nim b/tests/generics/mmodule_same_as_proc.nim new file mode 100644 index 000000000..048b98336 --- /dev/null +++ b/tests/generics/mmodule_same_as_proc.nim @@ -0,0 +1,2 @@ + +proc mmodule_same_as_proc*(x: string) = discard diff --git a/tests/generics/tmodule_same_as_proc.nim b/tests/generics/tmodule_same_as_proc.nim new file mode 100644 index 000000000..113ca1bc3 --- /dev/null +++ b/tests/generics/tmodule_same_as_proc.nim @@ -0,0 +1,9 @@ + +# bug #1965 + +import mmodule_same_as_proc + +proc test[T](t: T) = + mmodule_same_as_proc"a" + +test(0) From d230b75e0a7cd49cf5c4e4f687515c296cd2ce5b Mon Sep 17 00:00:00 2001 From: Araq Date: Mon, 10 Aug 2015 01:49:56 +0200 Subject: [PATCH 0819/1263] removed sequtils.reversed again since it's already in algorithm.nim --- lib/pure/collections/sequtils.nim | 23 ----------------------- 1 file changed, 23 deletions(-) diff --git a/lib/pure/collections/sequtils.nim b/lib/pure/collections/sequtils.nim index 1e75376df..5fac1f0af 100644 --- a/lib/pure/collections/sequtils.nim +++ b/lib/pure/collections/sequtils.nim @@ -451,21 +451,6 @@ template newSeqWith*(len: int, init: expr): expr = result[i] = init result -proc reversed*[T](s: seq[T]): seq[T] = - ## Takes a sequences and returns a new reversed one - ## - ## Example: - ## - ## .. code-block:: - ## - ## let s1 = @[1, 2, 3, 4, 5] - ## let s2 = @[5, 4, 3, 2, 1] - ## assert s2 == s1.reversed() - ## - result = s - let ln = result.len - for i in 0..(ln div 2)-1: swap(result[i], result[ln-i-1]) - when isMainModule: import strutils block: # concat test @@ -630,13 +615,5 @@ when isMainModule: #doAssert a.repeat(-1) == @[] # will not compile! doAssert b.repeat(3) == @[] - block: # reversed tests: - let - a = @[1, 2, 3] - b: seq[int] = @[] - - doAssert a.reversed == @[3, 2, 1] - doAssert b.reversed == @[] - when not defined(testing): echo "Finished doc tests" From 6a7a44bbf248fad96ed0eed115e3b3c77a77bf89 Mon Sep 17 00:00:00 2001 From: rku Date: Mon, 10 Aug 2015 12:02:49 +0300 Subject: [PATCH 0820/1263] cValidAssemblers -> const set Added assembler validity check --- compiler/extccomp.nim | 6 +++++- compiler/msgs.nim | 2 ++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/compiler/extccomp.nim b/compiler/extccomp.nim index 541927f55..683de67e0 100644 --- a/compiler/extccomp.nim +++ b/compiler/extccomp.nim @@ -368,7 +368,9 @@ var cIncludes*: seq[string] = @[] # directories to search for included files cLibs*: seq[string] = @[] # directories to search for lib files cLinkedLibs*: seq[string] = @[] # libraries to link - cValidAssemblers* = @[asmFasm] + +const + cValidAssemblers* = {asmFasm} # implementation @@ -567,6 +569,8 @@ proc getCompileCFileCmd*(cfilename: string, isExternal = false): string = if c == ccNone: rawMessage(errExternalAssemblerNotFound, "") + elif c notin cValidAssemblers: + rawMessage(errExternalAssemblerNotValid, customAssembler) var options = cFileSpecificOptions(cfilename) var exe = getConfigVar(c, ".exe") diff --git a/compiler/msgs.nim b/compiler/msgs.nim index 3dea30964..e739bb4b9 100644 --- a/compiler/msgs.nim +++ b/compiler/msgs.nim @@ -109,6 +109,7 @@ type errGenericLambdaNotAllowed, errCompilerDoesntSupportTarget, errExternalAssemblerNotFound, + errExternalAssemblerNotValid, errUser, warnCannotOpenFile, warnOctalEscape, warnXIsNeverRead, warnXmightNotBeenInit, @@ -372,6 +373,7 @@ const "of the generic paramers can be inferred from the expected signature.", errCompilerDoesntSupportTarget: "The current compiler \'$1\' doesn't support the requested compilation target", errExternalAssemblerNotFound: "External assembler not found", + errExternalAssemblerNotValid: "External assembler '$1' is not a valid assembler", errUser: "$1", warnCannotOpenFile: "cannot open \'$1\'", warnOctalEscape: "octal escape sequences do not exist; leading zero is ignored", From c42b05adb46e846cf56efedf44d1f02da769b2b7 Mon Sep 17 00:00:00 2001 From: Yuriy Glukhov Date: Wed, 12 Aug 2015 12:04:26 +0300 Subject: [PATCH 0821/1263] Fixed --debugger:on option. Removed c_line from termios. --- compiler/ccgstmts.nim | 4 ++-- compiler/cgen.nim | 9 ++++----- lib/nimbase.h | 2 +- lib/posix/termios.nim | 1 - lib/system/debugger.nim | 12 ++++++------ 5 files changed, 13 insertions(+), 15 deletions(-) diff --git a/compiler/ccgstmts.nim b/compiler/ccgstmts.nim index f12a24fa2..f4a7c4400 100644 --- a/compiler/ccgstmts.nim +++ b/compiler/ccgstmts.nim @@ -102,7 +102,7 @@ proc assignLabel(b: var TBlock): Rope {.inline.} = proc blockBody(b: var TBlock): Rope = result = b.sections[cpsLocals] if b.frameLen > 0: - result.addf("F.len+=$1;$n", [b.frameLen.rope]) + result.addf("FR.len+=$1;$n", [b.frameLen.rope]) result.add(b.sections[cpsInit]) result.add(b.sections[cpsStmts]) @@ -123,7 +123,7 @@ proc endBlock(p: BProc) = ~"}$n" let frameLen = p.blocks[topBlock].frameLen if frameLen > 0: - blockEnd.addf("F.len-=$1;$n", [frameLen.rope]) + blockEnd.addf("FR.len-=$1;$n", [frameLen.rope]) endBlock(p, blockEnd) proc genSimpleBlock(p: BProc, stmts: PNode) {.inline.} = diff --git a/compiler/cgen.nim b/compiler/cgen.nim index 2e95918cc..13514818e 100644 --- a/compiler/cgen.nim +++ b/compiler/cgen.nim @@ -375,7 +375,7 @@ proc localDebugInfo(p: BProc, s: PSym) = var a = "&" & s.loc.r if s.kind == skParam and ccgIntroducedPtr(s): a = s.loc.r lineF(p, cpsInit, - "F.s[$1].address = (void*)$3; F.s[$1].typ = $4; F.s[$1].name = $2;$n", + "FR.s[$1].address = (void*)$3; FR.s[$1].typ = $4; FR.s[$1].name = $2;$n", [p.maxFrameLen.rope, makeCString(normalize(s.name.s)), a, genTypeInfo(p.module, s.loc.t)]) inc(p.maxFrameLen) @@ -597,7 +597,7 @@ proc cgsym(m: BModule, name: string): Rope = of skProc, skMethod, skConverter, skIterators: genProc(m, sym) of skVar, skResult, skLet: genVarPrototype(m, sym) of skType: discard getTypeDesc(m, sym.typ) - else: internalError("cgsym: " & name) + else: internalError("cgsym: " & name & ": " & $sym.kind) else: # we used to exclude the system module from this check, but for DLL # generation support this sloppyness leads to hard to detect bugs, so @@ -623,7 +623,7 @@ proc retIsNotVoid(s: PSym): bool = proc initFrame(p: BProc, procname, filename: Rope): Rope = discard cgsym(p.module, "nimFrame") if p.maxFrameLen > 0: - discard cgsym(p.module, "TVarSlot") + discard cgsym(p.module, "VarSlot") result = rfmt(nil, "\tnimfrs($1, $2, $3, $4)$N", procname, filename, p.maxFrameLen.rope, p.blocks[0].frameLen.rope) @@ -1017,7 +1017,7 @@ proc genInitCode(m: BModule) = var procname = makeCString(m.module.name.s) add(prc, initFrame(m.initProc, procname, m.module.info.quotedFilename)) else: - add(prc, ~"\tTFrame F; F.len = 0;$N") + add(prc, ~"\tTFrame F; FR.len = 0;$N") add(prc, genSectionStart(cpsInit)) add(prc, m.preInitProc.s(cpsInit)) @@ -1329,4 +1329,3 @@ proc cgenWriteModules* = if generatedHeader != nil: writeHeader(generatedHeader) const cgenPass* = makePass(myOpen, myOpenCached, myProcess, myClose) - diff --git a/lib/nimbase.h b/lib/nimbase.h index e796ba735..d3108812c 100644 --- a/lib/nimbase.h +++ b/lib/nimbase.h @@ -347,7 +347,7 @@ struct TFrame { FR.procname = proc; FR.filename = file; FR.line = 0; FR.len = 0; nimFrame(&FR); #define nimfrs(proc, file, slots, length) \ - struct {TFrame* prev;NCSTRING procname;NI line;NCSTRING filename; NI len; TVarSlot s[slots];} FR; \ + struct {TFrame* prev;NCSTRING procname;NI line;NCSTRING filename; NI len; VarSlot s[slots];} FR; \ FR.procname = proc; FR.filename = file; FR.line = 0; FR.len = length; nimFrame((TFrame*)&FR); #define nimln(n, file) \ diff --git a/lib/posix/termios.nim b/lib/posix/termios.nim index 44f029039..c3934c6a9 100644 --- a/lib/posix/termios.nim +++ b/lib/posix/termios.nim @@ -24,7 +24,6 @@ type c_oflag*: Cflag # output mode flags c_cflag*: Cflag # control mode flags c_lflag*: Cflag # local mode flags - c_line*: cuchar # line discipline c_cc*: array[NCCS, cuchar] # control characters # cc characters diff --git a/lib/system/debugger.nim b/lib/system/debugger.nim index 63ccd770b..b18c61755 100644 --- a/lib/system/debugger.nim +++ b/lib/system/debugger.nim @@ -21,7 +21,7 @@ type # only slots that are # needed are allocated and not 10_000, # except for the global data description. - f: Frame + f: TFrame slots: array[0..10_000, VarSlot] {.deprecated: [TVarSlot: VarSlot, TExtendedFrame: ExtendedFrame].} @@ -66,7 +66,7 @@ var dbgBP: array[0..127, Breakpoint] # breakpoints dbgBPlen: int dbgBPbloom: int64 # we use a bloom filter to speed up breakpoint checking - + dbgFilenames*: array[0..300, cstring] ## registered filenames; ## 'nil' terminated dbgFilenameLen: int @@ -197,7 +197,7 @@ proc genericHashAux(dest: pointer, n: ptr TNimNode, shallow: bool, result = genericHashAux(cast[pointer](d +% n.offset), n.typ, shallow, h) of nkList: result = h - for i in 0..n.len-1: + for i in 0..n.len-1: result = result !& genericHashAux(dest, n.sons[i], shallow, result) of nkCase: result = h !& hash(cast[pointer](d +% n.offset), n.typ.size) @@ -205,7 +205,7 @@ proc genericHashAux(dest: pointer, n: ptr TNimNode, shallow: bool, if m != nil: result = genericHashAux(dest, m, shallow, result) of nkNone: sysAssert(false, "genericHashAux") -proc genericHashAux(dest: pointer, mt: PNimType, shallow: bool, +proc genericHashAux(dest: pointer, mt: PNimType, shallow: bool, h: Hash): Hash = sysAssert(mt != nil, "genericHashAux 2") case mt.kind @@ -257,7 +257,7 @@ proc genericHashAux(dest: pointer, mt: PNimType, shallow: bool, proc genericHash(dest: pointer, mt: PNimType): int = result = genericHashAux(dest, mt, false, 0) - + proc dbgRegisterWatchpoint(address: pointer, name: cstring, typ: PNimType) {.compilerproc.} = let L = watchPointsLen @@ -285,7 +285,7 @@ var ## Only code compiled with the ``debugger:on`` switch calls this hook. dbgWatchpointHook*: proc (watchpointName: cstring) {.nimcall.} - + proc checkWatchpoints = let L = watchPointsLen for i in 0.. Date: Wed, 12 Aug 2015 08:26:40 -0400 Subject: [PATCH 0822/1263] failed unittest check causes identifiers and calls to be printed out --- lib/pure/unittest.nim | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) mode change 100644 => 100755 lib/pure/unittest.nim diff --git a/lib/pure/unittest.nim b/lib/pure/unittest.nim old mode 100644 new mode 100755 index 064937ad8..3f36ed5a7 --- a/lib/pure/unittest.nim +++ b/lib/pure/unittest.nim @@ -92,8 +92,8 @@ template suite*(name: expr, body: stmt): stmt {.immediate, dirty.} = ## test "2 + 2 = 4": ## check(2+2 == result) ## - ## test "2 + -2 != 4": - ## check(2+2 != result) + ## test "(2 + -2) != 4": + ## check(2 + -2 != result) ## ## # No teardown needed ## @@ -234,41 +234,48 @@ macro check*(conditions: stmt): stmt {.immediate.} = when compiles(string($value)): checkpoint(name & " was " & $value) - proc inspectArgs(exp: NimNode) = + proc inspectArgs(exp: NimNode): NimNode = + result = copyNimTree(exp) for i in countup(1, exp.len - 1): if exp[i].kind notin nnkLiterals: inc counter var arg = newIdentNode(":p" & $counter) var argStr = exp[i].toStrLit var paramAst = exp[i] - if exp[i].kind in nnkCallKinds: inspectArgs(exp[i]) + if exp[i].kind == nnkIdent: + argsPrintOuts.add getAst(print(argStr, paramAst)) + if exp[i].kind in nnkCallKinds: + var callVar = newIdentNode(":c" & $counter) + argsAsgns.add getAst(asgn(callVar, paramAst)) + result[i] = callVar + argsPrintOuts.add getAst(print(argStr, callVar)) if exp[i].kind == nnkExprEqExpr: # ExprEqExpr # Ident !"v" # IntLit 2 - paramAst = exp[i][1] + result[i] = exp[i][1] if exp[i].typekind notin {ntyTypeDesc}: argsAsgns.add getAst(asgn(arg, paramAst)) argsPrintOuts.add getAst(print(argStr, arg)) if exp[i].kind != nnkExprEqExpr: - exp[i] = arg + result[i] = arg else: - exp[i][1] = arg + result[i][1] = arg case checked.kind of nnkCallKinds: template rewrite(call, lineInfoLit: expr, callLit: string, argAssgs, argPrintOuts: stmt): stmt = block: - argAssgs + argAssgs #all callables (and assignments) are run here if not call: checkpoint(lineInfoLit & ": Check failed: " & callLit) argPrintOuts fail() var checkedStr = checked.toStrLit - inspectArgs(checked) - result = getAst(rewrite(checked, checked.lineinfo, checkedStr, + let parameterizedCheck = inspectArgs(checked) + result = getAst(rewrite(parameterizedCheck, checked.lineinfo, checkedStr, argsAsgns, argsPrintOuts)) of nnkStmtList: From c62698b2969f67cdfdcf18c6416bdba9e5b50197 Mon Sep 17 00:00:00 2001 From: fenekku Date: Wed, 12 Aug 2015 10:30:36 -0400 Subject: [PATCH 0823/1263] make testSetupIMPL and testTeardownIMPL non-public --- lib/pure/unittest.nim | 9 ++++---- tests/stdlib/tunittest.nim | 45 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 5 deletions(-) diff --git a/lib/pure/unittest.nim b/lib/pure/unittest.nim index 3f36ed5a7..a0f7b955e 100755 --- a/lib/pure/unittest.nim +++ b/lib/pure/unittest.nim @@ -70,9 +70,6 @@ var ## Global unittest settings! checkpoints = @[] -template testSetupIMPL*: stmt {.immediate, dirty.} = discard #Should this be public or even exist? -template testTeardownIMPL*: stmt {.immediate, dirty.} = discard - proc shouldRun(testName: string): bool = result = true @@ -106,9 +103,11 @@ template suite*(name: expr, body: stmt): stmt {.immediate, dirty.} = ## [OK] (2 + -2) != 4 block: template setup(setupBody: stmt): stmt {.immediate, dirty.} = + var testSetupIMPLFlag = true template testSetupIMPL: stmt {.immediate, dirty.} = setupBody template teardown(teardownBody: stmt): stmt {.immediate, dirty.} = + var testTeardownIMPLFlag = true template testTeardownIMPL: stmt {.immediate, dirty.} = teardownBody body @@ -149,7 +148,7 @@ template test*(name: expr, body: stmt): stmt {.immediate, dirty.} = var testStatusIMPL {.inject.} = OK try: - testSetupIMPL() + when declared(testSetupIMPLFlag): testSetupIMPL() body except: @@ -159,7 +158,7 @@ template test*(name: expr, body: stmt): stmt {.immediate, dirty.} = fail() finally: - testTeardownIMPL() + when declared(testTeardownIMPLFlag): testTeardownIMPL() testDone name, testStatusIMPL proc checkpoint*(msg: string) = diff --git a/tests/stdlib/tunittest.nim b/tests/stdlib/tunittest.nim index 1389214ea..4d2a2a340 100644 --- a/tests/stdlib/tunittest.nim +++ b/tests/stdlib/tunittest.nim @@ -38,3 +38,48 @@ proc defectiveRobot() = test "unittest expect": expect IOError, OSError, ValueError, AssertionError: defectiveRobot() + +var + a = 1 + b = -1 + c = 1 + +#unittests are sequential right now +suite "suite with only teardown": + teardown: + b = 2 + + test "unittest with only teardown 1": + check a == c + + test "unittest with only teardown 2": + check b > a + +suite "suite with only setup": + setup: + var testVar = "from setup" + + test "unittest with only setup 1": + check testVar == "from setup" + check b > a + b = -1 + + test "unittest with only setup 2": + check b < a + +suite "suite with none": + test "unittest with none": + check b < a + +suite "suite with both": + setup: + a = -2 + + teardown: + c = 2 + + test "unittest with both 1": + check b > a + + test "unittest with both 2": + check c == 2 From ad98877584943bcbb9c08154fcfe516e2b0d75dc Mon Sep 17 00:00:00 2001 From: Yuriy Glukhov Date: Wed, 12 Aug 2015 18:31:38 +0300 Subject: [PATCH 0824/1263] Fixed fromSeconds function JS variant --- lib/pure/times.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/pure/times.nim b/lib/pure/times.nim index d9abbed1a..f7c3b59c5 100644 --- a/lib/pure/times.nim +++ b/lib/pure/times.nim @@ -550,7 +550,7 @@ elif defined(JS): proc valueOf(time: Time): float {.importcpp: "getTime", tags:[]} - proc fromSeconds(since1970: float): Time = result = newDate(since1970) + proc fromSeconds(since1970: float): Time = result = newDate(since1970 * 1000) proc toSeconds(time: Time): float = result = time.valueOf() / 1000 From 2f721f0d9928a4ae25b2f2b3761d8861a13e877d Mon Sep 17 00:00:00 2001 From: Araq Date: Mon, 10 Aug 2015 02:50:15 +0200 Subject: [PATCH 0825/1263] 'parallel' now requires --experimental mode --- compiler/semexprs.nim | 2 ++ tests/parallel/nim.cfg | 1 + todo.txt | 1 - web/news.txt | 3 +++ 4 files changed, 6 insertions(+), 1 deletion(-) diff --git a/compiler/semexprs.nim b/compiler/semexprs.nim index 0e9b9ae5f..bb3ec9df0 100644 --- a/compiler/semexprs.nim +++ b/compiler/semexprs.nim @@ -1720,6 +1720,8 @@ proc semMagic(c: PContext, n: PNode, s: PSym, flags: TExprFlags): PNode = result = newStrNodeT(renderTree(n[1], {renderNoComments}), n) result.typ = getSysType(tyString) of mParallel: + if not experimentalMode(c): + localError(n.info, "use the {.experimental.} pragma to enable 'parallel'") result = setMs(n, s) var x = n.lastSon if x.kind == nkDo: x = x.sons[bodyPos] diff --git a/tests/parallel/nim.cfg b/tests/parallel/nim.cfg index b81c89721..d0d2a9305 100644 --- a/tests/parallel/nim.cfg +++ b/tests/parallel/nim.cfg @@ -1 +1,2 @@ threads:on +--experimental diff --git a/todo.txt b/todo.txt index ee1d6fa87..f9abed891 100644 --- a/todo.txt +++ b/todo.txt @@ -13,7 +13,6 @@ version 0.11.4 - make '--implicitStatic:on' the default; then we can also clean up the 'static[T]' mess in the compiler! -- Mark the 'parallel' statement as experimental. - add "all threads are blocked" detection to 'spawn' - Deprecate ``immediate`` for templates and macros - make 'nil' work for 'add': diff --git a/web/news.txt b/web/news.txt index 518793a4a..16ac286ae 100644 --- a/web/news.txt +++ b/web/news.txt @@ -44,6 +44,9 @@ News been removed. - ``macros.high`` never worked and the manual says ``high`` cannot be overloaded, so we removed it with no deprecation cycle. + - To use the ``parallel`` statement you now have to + use the ``--experimental`` mode. + Library additions From 2299318d1e303ffdf5a9a79663e2c3b126bb5352 Mon Sep 17 00:00:00 2001 From: Araq Date: Wed, 12 Aug 2015 10:11:58 +0200 Subject: [PATCH 0826/1263] toplevel .closure procs are deprecated --- compiler/semstmts.nim | 3 +++ todo.txt | 1 - web/news.txt | 4 ++++ 3 files changed, 7 insertions(+), 1 deletion(-) diff --git a/compiler/semstmts.nim b/compiler/semstmts.nim index 3d9363d77..ffda6a1bb 100644 --- a/compiler/semstmts.nim +++ b/compiler/semstmts.nim @@ -1220,6 +1220,9 @@ proc semProcAux(c: PContext, n: PNode, kind: TSymKind, if n.sons[patternPos].kind != nkEmpty: c.patterns.add(s) if isAnon: result.typ = s.typ + if isTopLevel(c) and s.kind != skClosureIterator and + s.typ.callConv == ccClosure: + message(s.info, warnDeprecated, "top level '.closure' calling convention") proc determineType(c: PContext, s: PSym) = if s.typ != nil: return diff --git a/todo.txt b/todo.txt index f9abed891..57cbc83bf 100644 --- a/todo.txt +++ b/todo.txt @@ -1,7 +1,6 @@ version 0.11.4 ============== -- deprecate toplevel .closure procs - deprecate closure iterator construction via ``var cl = foo`` - document special cased varargs[untyped] and varargs[typed] diff --git a/web/news.txt b/web/news.txt index 16ac286ae..c93bb821f 100644 --- a/web/news.txt +++ b/web/news.txt @@ -46,6 +46,10 @@ News overloaded, so we removed it with no deprecation cycle. - To use the ``parallel`` statement you now have to use the ``--experimental`` mode. + - Toplevel procs of calling convention ``closure`` never worked reliably + and are now deprecated and will be removed from the language. Instead you + have to insert type conversions + like ``(proc (a, b: int) {.closure.})(myToplevelProc)`` if necessary. From dd0acfdf375b45a226f44feb4f04aef2c0aa0ac3 Mon Sep 17 00:00:00 2001 From: Araq Date: Fri, 14 Aug 2015 02:16:12 +0200 Subject: [PATCH 0827/1263] todo.txt update --- todo.txt | 2 -- 1 file changed, 2 deletions(-) diff --git a/todo.txt b/todo.txt index 57cbc83bf..0d4dbd2ad 100644 --- a/todo.txt +++ b/todo.txt @@ -1,8 +1,6 @@ version 0.11.4 ============== -- deprecate closure iterator construction via ``var cl = foo`` - - document special cased varargs[untyped] and varargs[typed] - The remaining bugs of the lambda lifting pass that is responsible to enable From 134c44f3be373a94fd5ee144d98cd296ee967107 Mon Sep 17 00:00:00 2001 From: Araq Date: Fri, 14 Aug 2015 02:18:12 +0200 Subject: [PATCH 0828/1263] refs #2973; manual contains almost all pragmas now, few are left in the compiler guide --- doc/manual/pragmas.txt | 464 +++++++++++++++++++++++++++++++++++++++++ doc/nimc.txt | 457 ---------------------------------------- 2 files changed, 464 insertions(+), 457 deletions(-) diff --git a/doc/manual/pragmas.txt b/doc/manual/pragmas.txt index 51125f576..8166994a9 100644 --- a/doc/manual/pragmas.txt +++ b/doc/manual/pragmas.txt @@ -511,3 +511,467 @@ Example: add "foo" add "bar" + +Implementation Specific Pragmas +=============================== + +This section describes additional pragmas that the current Nim implementation +supports but which should not be seen as part of the language specification. + + +Volatile pragma +--------------- +The ``volatile`` pragma is for variables only. It declares the variable as +``volatile``, whatever that means in C/C++ (its semantics are not well defined +in C/C++). + +**Note**: This pragma will not exist for the LLVM backend. + + +NoDecl pragma +------------- +The ``noDecl`` pragma can be applied to almost any symbol (variable, proc, +type, etc.) and is sometimes useful for interoperability with C: +It tells Nim that it should not generate a declaration for the symbol in +the C code. For example: + +.. code-block:: Nim + var + EACCES {.importc, noDecl.}: cint # pretend EACCES was a variable, as + # Nim does not know its value + +However, the ``header`` pragma is often the better alternative. + +**Note**: This will not work for the LLVM backend. + + +Header pragma +------------- +The ``header`` pragma is very similar to the ``noDecl`` pragma: It can be +applied to almost any symbol and specifies that it should not be declared +and instead the generated code should contain an ``#include``: + +.. code-block:: Nim + type + PFile {.importc: "FILE*", header: "".} = distinct pointer + # import C's FILE* type; Nim will treat it as a new pointer type + +The ``header`` pragma always expects a string constant. The string contant +contains the header file: As usual for C, a system header file is enclosed +in angle brackets: ``<>``. If no angle brackets are given, Nim +encloses the header file in ``""`` in the generated C code. + +**Note**: This will not work for the LLVM backend. + + +IncompleteStruct pragma +----------------------- +The ``incompleteStruct`` pragma tells the compiler to not use the +underlying C ``struct`` in a ``sizeof`` expression: + +.. code-block:: Nim + type + DIR* {.importc: "DIR", header: "", + final, pure, incompleteStruct.} = object + + +Compile pragma +-------------- +The ``compile`` pragma can be used to compile and link a C/C++ source file +with the project: + +.. code-block:: Nim + {.compile: "myfile.cpp".} + +**Note**: Nim computes a SHA1 checksum and only recompiles the file if it +has changed. You can use the ``-f`` command line option to force recompilation +of the file. + + +Link pragma +----------- +The ``link`` pragma can be used to link an additional file with the project: + +.. code-block:: Nim + {.link: "myfile.o".} + + +PassC pragma +------------ +The ``passC`` pragma can be used to pass additional parameters to the C +compiler like you would using the commandline switch ``--passC``: + +.. code-block:: Nim + {.passC: "-Wall -Werror".} + +Note that you can use ``gorge`` from the `system module `_ to +embed parameters from an external command at compile time: + +.. code-block:: Nim + {.passC: gorge("pkg-config --cflags sdl").} + +PassL pragma +------------ +The ``passL`` pragma can be used to pass additional parameters to the linker +like you would using the commandline switch ``--passL``: + +.. code-block:: Nim + {.passL: "-lSDLmain -lSDL".} + +Note that you can use ``gorge`` from the `system module `_ to +embed parameters from an external command at compile time: + +.. code-block:: Nim + {.passL: gorge("pkg-config --libs sdl").} + + +Emit pragma +----------- +The ``emit`` pragma can be used to directly affect the output of the +compiler's code generator. So it makes your code unportable to other code +generators/backends. Its usage is highly discouraged! However, it can be +extremely useful for interfacing with `C++`:idx: or `Objective C`:idx: code. + +Example: + +.. code-block:: Nim + {.emit: """ + static int cvariable = 420; + """.} + + {.push stackTrace:off.} + proc embedsC() = + var nimVar = 89 + # use backticks to access Nim symbols within an emit section: + {.emit: """fprintf(stdout, "%d\n", cvariable + (int)`nimVar`);""".} + {.pop.} + + embedsC() + +As can be seen from the example, to Nim symbols can be referred via backticks. +Use two backticks to produce a single verbatim backtick. + +For a toplevel emit statement the section where in the generated C/C++ file +the code should be emitted can be influenced via the +prefixes ``/*TYPESECTION*/`` or ``/*VARSECTION*/`` or ``/*INCLUDESECTION*/``: + +.. code-block:: Nim + {.emit: """/*TYPESECTION*/ + struct Vector3 { + public: + Vector3(): x(5) {} + Vector3(float x_): x(x_) {} + float x; + }; + """.} + + type Vector3 {.importcpp: "Vector3", nodecl} = object + x: cfloat + + proc constructVector3(a: cfloat): Vector3 {.importcpp: "Vector3(@)", nodecl} + + +ImportCpp pragma +---------------- + +**Note**: `c2nim `_ can parse a large subset of C++ and knows +about the ``importcpp`` pragma pattern language. It is not necessary +to know all the details described here. + + +Similar to the `importc pragma for C `_, the +``importcpp`` pragma can be used to import `C++`:idx: methods or C++ symbols +in general. The generated code then uses the C++ method calling +syntax: ``obj->method(arg)``. In combination with the ``header`` and ``emit`` +pragmas this allows *sloppy* interfacing with libraries written in C++: + +.. code-block:: Nim + # Horrible example of how to interface with a C++ engine ... ;-) + + {.link: "/usr/lib/libIrrlicht.so".} + + {.emit: """ + using namespace irr; + using namespace core; + using namespace scene; + using namespace video; + using namespace io; + using namespace gui; + """.} + + const + irr = "" + + type + IrrlichtDeviceObj {.final, header: irr, + importcpp: "IrrlichtDevice".} = object + IrrlichtDevice = ptr IrrlichtDeviceObj + + proc createDevice(): IrrlichtDevice {. + header: irr, importcpp: "createDevice(@)".} + proc run(device: IrrlichtDevice): bool {. + header: irr, importcpp: "#.run(@)".} + +The compiler needs to be told to generate C++ (command ``cpp``) for +this to work. The conditional symbol ``cpp`` is defined when the compiler +emits C++ code. + + +Namespaces +~~~~~~~~~~ + +The *sloppy interfacing* example uses ``.emit`` to produce ``using namespace`` +declarations. It is usually much better to instead refer to the imported name +via the ``namespace::identifier`` notation: + +.. code-block:: nim + type + IrrlichtDeviceObj {.final, header: irr, + importcpp: "irr::IrrlichtDevice".} = object + + +Importcpp for enums +~~~~~~~~~~~~~~~~~~~ + +When ``importcpp`` is applied to an enum type the numerical enum values are +annotated with the C++ enum type, like in this example: ``((TheCppEnum)(3))``. +(This turned out to be the simplest way to implement it.) + + +Importcpp for procs +~~~~~~~~~~~~~~~~~~~ + +Note that the ``importcpp`` variant for procs uses a somewhat cryptic pattern +language for maximum flexibility: + +- A hash ``#`` symbol is replaced by the first or next argument. +- A dot following the hash ``#.`` indicates that the call should use C++'s dot + or arrow notation. +- An at symbol ``@`` is replaced by the remaining arguments, separated by + commas. + +For example: + +.. code-block:: nim + proc cppMethod(this: CppObj, a, b, c: cint) {.importcpp: "#.CppMethod(@)".} + var x: ptr CppObj + cppMethod(x[], 1, 2, 3) + +Produces: + +.. code-block:: C + x->CppMethod(1, 2, 3) + +As a special rule to keep backwards compatibility with older versions of the +``importcpp`` pragma, if there is no special pattern +character (any of ``# ' @``) at all, C++'s +dot or arrow notation is assumed, so the above example can also be written as: + +.. code-block:: nim + proc cppMethod(this: CppObj, a, b, c: cint) {.importcpp: "CppMethod".} + +Note that the pattern language naturally also covers C++'s operator overloading +capabilities: + +.. code-block:: nim + proc vectorAddition(a, b: Vec3): Vec3 {.importcpp: "# + #".} + proc dictLookup(a: Dict, k: Key): Value {.importcpp: "#[#]".} + + +- An apostrophe ``'`` followed by an integer ``i`` in the range 0..9 + is replaced by the i'th parameter *type*. The 0th position is the result + type. This can be used to pass types to C++ function templates. Between + the ``'`` and the digit an asterisk can be used to get to the base type + of the type. (So it "takes away a star" from the type; ``T*`` becomes ``T``.) + Two stars can be used to get to the element type of the element type etc. + +For example: + +.. code-block:: nim + + type Input {.importcpp: "System::Input".} = object + proc getSubsystem*[T](): ptr T {.importcpp: "SystemManager::getSubsystem<'*0>()", nodecl.} + + let x: ptr Input = getSubsystem[Input]() + +Produces: + +.. code-block:: C + x = SystemManager::getSubsystem() + + +- ``#@`` is a special case to support a ``cnew`` operation. It is required so + that the call expression is inlined directly, without going through a + temporary location. This is only required to circumvent a limitation of the + current code generator. + +For example C++'s ``new`` operator can be "imported" like this: + +.. code-block:: nim + proc cnew*[T](x: T): ptr T {.importcpp: "(new '*0#@)", nodecl.} + + # constructor of 'Foo': + proc constructFoo(a, b: cint): Foo {.importcpp: "Foo(@)".} + + let x = cnew constructFoo(3, 4) + +Produces: + +.. code-block:: C + x = new Foo(3, 4) + +However, depending on the use case ``new Foo`` can also be wrapped like this +instead: + +.. code-block:: nim + proc newFoo(a, b: cint): ptr Foo {.importcpp: "new Foo(@)".} + + let x = newFoo(3, 4) + + +Wrapping constructors +~~~~~~~~~~~~~~~~~~~~~ + +Sometimes a C++ class has a private copy constructor and so code like +``Class c = Class(1,2);`` must not be generated but instead ``Class c(1,2);``. +For this purpose the Nim proc that wraps a C++ constructor needs to be +annotated with the `constructor`:idx: pragma. This pragma also helps to generate +faster C++ code since construction then doesn't invoke the copy constructor: + +.. code-block:: nim + # a better constructor of 'Foo': + proc constructFoo(a, b: cint): Foo {.importcpp: "Foo(@)", constructor.} + + +Wrapping destructors +~~~~~~~~~~~~~~~~~~~~ + +Since Nim generates C++ directly, any destructor is called implicitly by the +C++ compiler at the scope exits. This means that often one can get away with +not wrapping the destructor at all! However when it needs to be invoked +explicitly, it needs to be wrapped. But the pattern language already provides +everything that is required for that: + +.. code-block:: nim + proc destroyFoo(this: var Foo) {.importcpp: "#.~Foo()".} + + +Importcpp for objects +~~~~~~~~~~~~~~~~~~~~~ + +Generic ``importcpp``'ed objects are mapped to C++ templates. This means that +you can import C++'s templates rather easily without the need for a pattern +language for object types: + +.. code-block:: nim + type + StdMap {.importcpp: "std::map", header: "".} [K, V] = object + proc `[]=`[K, V](this: var StdMap[K, V]; key: K; val: V) {. + importcpp: "#[#] = #", header: "".} + + var x: StdMap[cint, cdouble] + x[6] = 91.4 + + +Produces: + +.. code-block:: C + std::map x; + x[6] = 91.4; + + +- If more precise control is needed, the apostrophe ``'`` can be used in the + supplied pattern to denote the concrete type parameters of the generic type. + See the usage of the apostrophe operator in proc patterns for more details. + +.. code-block:: nim + + type + VectorIterator {.importcpp: "std::vector<'0>::iterator".} [T] = object + + var x: VectorIterator[cint] + + +Produces: + +.. code-block:: C + + std::vector::iterator x; + + +ImportObjC pragma +----------------- +Similar to the `importc pragma for C `_, the +``importobjc`` pragma can be used to import `Objective C`:idx: methods. The +generated code then uses the Objective C method calling syntax: ``[obj method +param1: arg]``. In addition with the ``header`` and ``emit`` pragmas this +allows *sloppy* interfacing with libraries written in Objective C: + +.. code-block:: Nim + # horrible example of how to interface with GNUStep ... + + {.passL: "-lobjc".} + {.emit: """ + #include + @interface Greeter:Object + { + } + + - (void)greet:(long)x y:(long)dummy; + @end + + #include + @implementation Greeter + + - (void)greet:(long)x y:(long)dummy + { + printf("Hello, World!\n"); + } + @end + + #include + """.} + + type + Id {.importc: "id", header: "", final.} = distinct int + + proc newGreeter: Id {.importobjc: "Greeter new", nodecl.} + proc greet(self: Id, x, y: int) {.importobjc: "greet", nodecl.} + proc free(self: Id) {.importobjc: "free", nodecl.} + + var g = newGreeter() + g.greet(12, 34) + g.free() + +The compiler needs to be told to generate Objective C (command ``objc``) for +this to work. The conditional symbol ``objc`` is defined when the compiler +emits Objective C code. + + +CodegenDecl pragma +------------------ + +The ``codegenDecl`` pragma can be used to directly influence Nim's code +generator. It receives a format string that determines how the variable or +proc is declared in the generated code: + +.. code-block:: nim + var + a {.codegenDecl: "$# progmem $#".}: int + + proc myinterrupt() {.codegenDecl: "__interrupt $# $#$#".} = + echo "realistic interrupt handler" + + +InjectStmt pragma +----------------- + +The ``injectStmt`` pragma can be used to inject a statement before every +other statement in the current module. It is only supposed to be used for +debugging: + +.. code-block:: nim + {.injectStmt: gcInvariants().} + + # ... complex code here that produces crashes ... + diff --git a/doc/nimc.txt b/doc/nimc.txt index 15c9f2955..95449d060 100644 --- a/doc/nimc.txt +++ b/doc/nimc.txt @@ -263,454 +263,6 @@ Nim manual. Some of the features here only make sense for the C code generator and are subject to change. -NoDecl pragma -------------- -The ``noDecl`` pragma can be applied to almost any symbol (variable, proc, -type, etc.) and is sometimes useful for interoperability with C: -It tells Nim that it should not generate a declaration for the symbol in -the C code. For example: - -.. code-block:: Nim - var - EACCES {.importc, noDecl.}: cint # pretend EACCES was a variable, as - # Nim does not know its value - -However, the ``header`` pragma is often the better alternative. - -**Note**: This will not work for the LLVM backend. - - -Header pragma -------------- -The ``header`` pragma is very similar to the ``noDecl`` pragma: It can be -applied to almost any symbol and specifies that it should not be declared -and instead the generated code should contain an ``#include``: - -.. code-block:: Nim - type - PFile {.importc: "FILE*", header: "".} = distinct pointer - # import C's FILE* type; Nim will treat it as a new pointer type - -The ``header`` pragma always expects a string constant. The string contant -contains the header file: As usual for C, a system header file is enclosed -in angle brackets: ``<>``. If no angle brackets are given, Nim -encloses the header file in ``""`` in the generated C code. - -**Note**: This will not work for the LLVM backend. - - -IncompleteStruct pragma ------------------------ -The ``incompleteStruct`` pragma tells the compiler to not use the -underlying C ``struct`` in a ``sizeof`` expression: - -.. code-block:: Nim - type - DIR* {.importc: "DIR", header: "", - final, pure, incompleteStruct.} = object - - -Compile pragma --------------- -The ``compile`` pragma can be used to compile and link a C/C++ source file -with the project: - -.. code-block:: Nim - {.compile: "myfile.cpp".} - -**Note**: Nim computes a SHA1 checksum and only recompiles the file if it -has changed. You can use the ``-f`` command line option to force recompilation -of the file. - - -Link pragma ------------ -The ``link`` pragma can be used to link an additional file with the project: - -.. code-block:: Nim - {.link: "myfile.o".} - - -PassC pragma ------------- -The ``passC`` pragma can be used to pass additional parameters to the C -compiler like you would using the commandline switch ``--passC``: - -.. code-block:: Nim - {.passC: "-Wall -Werror".} - -Note that you can use ``gorge`` from the `system module `_ to -embed parameters from an external command at compile time: - -.. code-block:: Nim - {.passC: gorge("pkg-config --cflags sdl").} - -PassL pragma ------------- -The ``passL`` pragma can be used to pass additional parameters to the linker -like you would using the commandline switch ``--passL``: - -.. code-block:: Nim - {.passL: "-lSDLmain -lSDL".} - -Note that you can use ``gorge`` from the `system module `_ to -embed parameters from an external command at compile time: - -.. code-block:: Nim - {.passL: gorge("pkg-config --libs sdl").} - - -Emit pragma ------------ -The ``emit`` pragma can be used to directly affect the output of the -compiler's code generator. So it makes your code unportable to other code -generators/backends. Its usage is highly discouraged! However, it can be -extremely useful for interfacing with `C++`:idx: or `Objective C`:idx: code. - -Example: - -.. code-block:: Nim - {.emit: """ - static int cvariable = 420; - """.} - - {.push stackTrace:off.} - proc embedsC() = - var nimVar = 89 - # use backticks to access Nim symbols within an emit section: - {.emit: """fprintf(stdout, "%d\n", cvariable + (int)`nimVar`);""".} - {.pop.} - - embedsC() - -As can be seen from the example, to Nim symbols can be referred via backticks. -Use two backticks to produce a single verbatim backtick. - -For a toplevel emit statement the section where in the generated C/C++ file -the code should be emitted can be influenced via the -prefixes ``/*TYPESECTION*/`` or ``/*VARSECTION*/`` or ``/*INCLUDESECTION*/``: - -.. code-block:: Nim - {.emit: """/*TYPESECTION*/ - struct Vector3 { - public: - Vector3(): x(5) {} - Vector3(float x_): x(x_) {} - float x; - }; - """.} - - type Vector3 {.importcpp: "Vector3", nodecl} = object - x: cfloat - - proc constructVector3(a: cfloat): Vector3 {.importcpp: "Vector3(@)", nodecl} - - -ImportCpp pragma ----------------- - -**Note**: `c2nim `_ can parse a large subset of C++ and knows -about the ``importcpp`` pragma pattern language. It is not necessary -to know all the details described here. - - -Similar to the `importc pragma for C `_, the -``importcpp`` pragma can be used to import `C++`:idx: methods or C++ symbols -in general. The generated code then uses the C++ method calling -syntax: ``obj->method(arg)``. In combination with the ``header`` and ``emit`` -pragmas this allows *sloppy* interfacing with libraries written in C++: - -.. code-block:: Nim - # Horrible example of how to interface with a C++ engine ... ;-) - - {.link: "/usr/lib/libIrrlicht.so".} - - {.emit: """ - using namespace irr; - using namespace core; - using namespace scene; - using namespace video; - using namespace io; - using namespace gui; - """.} - - const - irr = "" - - type - IrrlichtDeviceObj {.final, header: irr, - importcpp: "IrrlichtDevice".} = object - IrrlichtDevice = ptr IrrlichtDeviceObj - - proc createDevice(): IrrlichtDevice {. - header: irr, importcpp: "createDevice(@)".} - proc run(device: IrrlichtDevice): bool {. - header: irr, importcpp: "#.run(@)".} - -The compiler needs to be told to generate C++ (command ``cpp``) for -this to work. The conditional symbol ``cpp`` is defined when the compiler -emits C++ code. - - -Namespaces -~~~~~~~~~~ - -The *sloppy interfacing* example uses ``.emit`` to produce ``using namespace`` -declarations. It is usually much better to instead refer to the imported name -via the ``namespace::identifier`` notation: - -.. code-block:: nim - type - IrrlichtDeviceObj {.final, header: irr, - importcpp: "irr::IrrlichtDevice".} = object - - -Importcpp for enums -~~~~~~~~~~~~~~~~~~~ - -When ``importcpp`` is applied to an enum type the numerical enum values are -annotated with the C++ enum type, like in this example: ``((TheCppEnum)(3))``. -(This turned out to be the simplest way to implement it.) - - -Importcpp for procs -~~~~~~~~~~~~~~~~~~~ - -Note that the ``importcpp`` variant for procs uses a somewhat cryptic pattern -language for maximum flexibility: - -- A hash ``#`` symbol is replaced by the first or next argument. -- A dot following the hash ``#.`` indicates that the call should use C++'s dot - or arrow notation. -- An at symbol ``@`` is replaced by the remaining arguments, separated by - commas. - -For example: - -.. code-block:: nim - proc cppMethod(this: CppObj, a, b, c: cint) {.importcpp: "#.CppMethod(@)".} - var x: ptr CppObj - cppMethod(x[], 1, 2, 3) - -Produces: - -.. code-block:: C - x->CppMethod(1, 2, 3) - -As a special rule to keep backwards compatibility with older versions of the -``importcpp`` pragma, if there is no special pattern -character (any of ``# ' @``) at all, C++'s -dot or arrow notation is assumed, so the above example can also be written as: - -.. code-block:: nim - proc cppMethod(this: CppObj, a, b, c: cint) {.importcpp: "CppMethod".} - -Note that the pattern language naturally also covers C++'s operator overloading -capabilities: - -.. code-block:: nim - proc vectorAddition(a, b: Vec3): Vec3 {.importcpp: "# + #".} - proc dictLookup(a: Dict, k: Key): Value {.importcpp: "#[#]".} - - -- An apostrophe ``'`` followed by an integer ``i`` in the range 0..9 - is replaced by the i'th parameter *type*. The 0th position is the result - type. This can be used to pass types to C++ function templates. Between - the ``'`` and the digit an asterisk can be used to get to the base type - of the type. (So it "takes away a star" from the type; ``T*`` becomes ``T``.) - Two stars can be used to get to the element type of the element type etc. - -For example: - -.. code-block:: nim - - type Input {.importcpp: "System::Input".} = object - proc getSubsystem*[T](): ptr T {.importcpp: "SystemManager::getSubsystem<'*0>()", nodecl.} - - let x: ptr Input = getSubsystem[Input]() - -Produces: - -.. code-block:: C - x = SystemManager::getSubsystem() - - -- ``#@`` is a special case to support a ``cnew`` operation. It is required so - that the call expression is inlined directly, without going through a - temporary location. This is only required to circumvent a limitation of the - current code generator. - -For example C++'s ``new`` operator can be "imported" like this: - -.. code-block:: nim - proc cnew*[T](x: T): ptr T {.importcpp: "(new '*0#@)", nodecl.} - - # constructor of 'Foo': - proc constructFoo(a, b: cint): Foo {.importcpp: "Foo(@)".} - - let x = cnew constructFoo(3, 4) - -Produces: - -.. code-block:: C - x = new Foo(3, 4) - -However, depending on the use case ``new Foo`` can also be wrapped like this -instead: - -.. code-block:: nim - proc newFoo(a, b: cint): ptr Foo {.importcpp: "new Foo(@)".} - - let x = newFoo(3, 4) - - -Wrapping constructors -~~~~~~~~~~~~~~~~~~~~~ - -Sometimes a C++ class has a private copy constructor and so code like -``Class c = Class(1,2);`` must not be generated but instead ``Class c(1,2);``. -For this purpose the Nim proc that wraps a C++ constructor needs to be -annotated with the `constructor`:idx: pragma. This pragma also helps to generate -faster C++ code since construction then doesn't invoke the copy constructor: - -.. code-block:: nim - # a better constructor of 'Foo': - proc constructFoo(a, b: cint): Foo {.importcpp: "Foo(@)", constructor.} - - -Wrapping destructors -~~~~~~~~~~~~~~~~~~~~ - -Since Nim generates C++ directly, any destructor is called implicitly by the -C++ compiler at the scope exits. This means that often one can get away with -not wrapping the destructor at all! However when it needs to be invoked -explicitly, it needs to be wrapped. But the pattern language already provides -everything that is required for that: - -.. code-block:: nim - proc destroyFoo(this: var Foo) {.importcpp: "#.~Foo()".} - - -Importcpp for objects -~~~~~~~~~~~~~~~~~~~~~ - -Generic ``importcpp``'ed objects are mapped to C++ templates. This means that -you can import C++'s templates rather easily without the need for a pattern -language for object types: - -.. code-block:: nim - type - StdMap {.importcpp: "std::map", header: "".} [K, V] = object - proc `[]=`[K, V](this: var StdMap[K, V]; key: K; val: V) {. - importcpp: "#[#] = #", header: "".} - - var x: StdMap[cint, cdouble] - x[6] = 91.4 - - -Produces: - -.. code-block:: C - std::map x; - x[6] = 91.4; - - -- If more precise control is needed, the apostrophe ``'`` can be used in the - supplied pattern to denote the concrete type parameters of the generic type. - See the usage of the apostrophe operator in proc patterns for more details. - -.. code-block:: nim - - type - VectorIterator {.importcpp: "std::vector<'0>::iterator".} [T] = object - - var x: VectorIterator[cint] - - -Produces: - -.. code-block:: C - - std::vector::iterator x; - - -ImportObjC pragma ------------------ -Similar to the `importc pragma for C `_, the -``importobjc`` pragma can be used to import `Objective C`:idx: methods. The -generated code then uses the Objective C method calling syntax: ``[obj method -param1: arg]``. In addition with the ``header`` and ``emit`` pragmas this -allows *sloppy* interfacing with libraries written in Objective C: - -.. code-block:: Nim - # horrible example of how to interface with GNUStep ... - - {.passL: "-lobjc".} - {.emit: """ - #include - @interface Greeter:Object - { - } - - - (void)greet:(long)x y:(long)dummy; - @end - - #include - @implementation Greeter - - - (void)greet:(long)x y:(long)dummy - { - printf("Hello, World!\n"); - } - @end - - #include - """.} - - type - Id {.importc: "id", header: "", final.} = distinct int - - proc newGreeter: Id {.importobjc: "Greeter new", nodecl.} - proc greet(self: Id, x, y: int) {.importobjc: "greet", nodecl.} - proc free(self: Id) {.importobjc: "free", nodecl.} - - var g = newGreeter() - g.greet(12, 34) - g.free() - -The compiler needs to be told to generate Objective C (command ``objc``) for -this to work. The conditional symbol ``objc`` is defined when the compiler -emits Objective C code. - - -CodegenDecl pragma ------------------- - -The ``codegenDecl`` pragma can be used to directly influence Nim's code -generator. It receives a format string that determines how the variable or -proc is declared in the generated code: - -.. code-block:: nim - var - a {.codegenDecl: "$# progmem $#".}: int - - proc myinterrupt() {.codegenDecl: "__interrupt $# $#$#".} = - echo "realistic interrupt handler" - - -InjectStmt pragma ------------------ - -The ``injectStmt`` pragma can be used to inject a statement before every -other statement in the current module. It is only supposed to be used for -debugging: - -.. code-block:: nim - {.injectStmt: gcInvariants().} - - # ... complex code here that produces crashes ... - - LineDir option -------------- The ``lineDir`` option can be turned on or off. If turned on the @@ -744,15 +296,6 @@ The *breakpoint* pragma was specially added for the sake of debugging with ENDB. See the documentation of `endb `_ for further information. -Volatile pragma ---------------- -The ``volatile`` pragma is for variables only. It declares the variable as -``volatile``, whatever that means in C/C++ (its semantics are not well defined -in C/C++). - -**Note**: This pragma will not exist for the LLVM backend. - - DynlibOverride ============== From 2f8d4c17d85357c8d7760f830f4da0e675da8fd0 Mon Sep 17 00:00:00 2001 From: Yuriy Glukhov Date: Fri, 14 Aug 2015 12:57:07 +0300 Subject: [PATCH 0829/1263] Fixed compilation of times module with JS. --- lib/pure/times.nim | 34 ++++++++++++++++++---------------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/lib/pure/times.nim b/lib/pure/times.nim index f7c3b59c5..6d45dc7f1 100644 --- a/lib/pure/times.nim +++ b/lib/pure/times.nim @@ -70,7 +70,7 @@ elif defined(windows): type Time* = distinct TimeImpl - + elif defined(JS): type @@ -548,11 +548,9 @@ elif defined(JS): ## get the milliseconds from the start of the program return int(getTime() - startMilsecs) - proc valueOf(time: Time): float {.importcpp: "getTime", tags:[]} - proc fromSeconds(since1970: float): Time = result = newDate(since1970 * 1000) - proc toSeconds(time: Time): float = result = time.valueOf() / 1000 + proc toSeconds(time: Time): float = result = time.getTime() / 1000 proc getTimezone(): int = result = newDate().getTimezoneOffset() @@ -1109,9 +1107,10 @@ proc getDayOfWeekJulian*(day, month, year: int): WeekDay = proc timeToTimeInfo*(t: Time): TimeInfo = ## Converts a Time to TimeInfo. let - daysSinceEpoch = t.int div secondsInDay + secs = t.toSeconds().int + daysSinceEpoch = secs div secondsInDay (yearsSinceEpoch, daysRemaining) = countYearsAndDays(daysSinceEpoch) - daySeconds = t.int mod secondsInDay + daySeconds = secs mod secondsInDay y = yearsSinceEpoch + epochStartYear @@ -1137,12 +1136,14 @@ proc timeToTimeInfo*(t: Time): TimeInfo = s = daySeconds mod secondsInMin result = TimeInfo(year: y, yearday: yd, month: m, monthday: md, weekday: wd, hour: h, minute: mi, second: s) -proc timetoTimeInterval*(t: Time): TimeInterval = +proc timeToTimeInterval*(t: Time): TimeInterval = ## Converts a Time to a TimeInterval. - var - daysSinceEpoch = t.int div secondsInDay + + let + secs = t.toSeconds().int + daysSinceEpoch = secs div secondsInDay (yearsSinceEpoch, daysRemaining) = countYearsAndDays(daysSinceEpoch) - daySeconds = t.int mod secondsInDay + daySeconds = secs mod secondsInDay result.years = yearsSinceEpoch + epochStartYear @@ -1183,12 +1184,13 @@ when isMainModule: " ss t tt y yy yyy yyyy yyyyy z zz zzz ZZZ") == "27 27 Mon Monday 4 04 16 16 6 06 1 01 Jan January 29 29 P PM 5 75 975 1975 01975 0 00 00:00 UTC" - when not defined(JS) and sizeof(Time) == 8: - var t3 = getGMTime(fromSeconds(889067643645)) # Fri 7 Jun 19:20:45 BST 30143 - assert t3.format("d dd ddd dddd h hh H HH m mm M MM MMM MMMM s" & - " ss t tt y yy yyy yyyy yyyyy z zz zzz ZZZ") == - "7 07 Fri Friday 6 06 18 18 20 20 6 06 Jun June 45 45 P PM 3 43 143 0143 30143 0 00 00:00 UTC" - assert t3.format(":,[]()-/") == ":,[]()-/" + when not defined(JS): + when sizeof(Time) == 8: + var t3 = getGMTime(fromSeconds(889067643645)) # Fri 7 Jun 19:20:45 BST 30143 + assert t3.format("d dd ddd dddd h hh H HH m mm M MM MMM MMMM s" & + " ss t tt y yy yyy yyyy yyyyy z zz zzz ZZZ") == + "7 07 Fri Friday 6 06 18 18 20 20 6 06 Jun June 45 45 P PM 3 43 143 0143 30143 0 00 00:00 UTC" + assert t3.format(":,[]()-/") == ":,[]()-/" var t4 = getGMTime(fromSeconds(876124714)) # Mon 6 Oct 08:58:34 BST 1997 assert t4.format("M MM MMM MMMM") == "10 10 Oct October" From 22789a827571009b836fa20801961bedeea9f7ae Mon Sep 17 00:00:00 2001 From: Reimer Behrends Date: Fri, 14 Aug 2015 14:32:30 +0200 Subject: [PATCH 0830/1263] Fix exponentiation operation to avoid overflow. The exponentation implementation unnecessarily multiplied the result with itself at the end if the exponent was an even number. This led to overflow if result*result > high(int). --- lib/pure/math.nim | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/pure/math.nim b/lib/pure/math.nim index 821ab738b..8d95ea9c0 100644 --- a/lib/pure/math.nim +++ b/lib/pure/math.nim @@ -427,10 +427,12 @@ proc `^`*[T](x, y: T): T = var (x, y) = (x, y) result = 1 - while y != 0: + while true: if (y and 1) != 0: result *= x y = y shr 1 + if y == 0: + break x *= x proc gcd*[T](x, y: T): T = From 4e222a15064846946b18d0aa3c5279924b6bad7f Mon Sep 17 00:00:00 2001 From: Reimer Behrends Date: Fri, 14 Aug 2015 15:14:56 +0200 Subject: [PATCH 0831/1263] Fixed algorithm.reversed to work for empty seq's. --- lib/pure/algorithm.nim | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/pure/algorithm.nim b/lib/pure/algorithm.nim index 3671a9e09..c0acae138 100644 --- a/lib/pure/algorithm.nim +++ b/lib/pure/algorithm.nim @@ -48,8 +48,9 @@ proc reverse*[T](a: var openArray[T]) = ## reverses the array `a`. reverse(a, 0, a.high) -proc reversed*[T](a: openArray[T], first, last: Natural): seq[T] = +proc reversed*[T](a: openArray[T], first: Natural, last: int): seq[T] = ## returns the reverse of the array `a[first..last]`. + assert last >= first-1 var i = last - first var x = first.int result = newSeq[T](i + 1) From ac756935c1f5cb422884eaa54bb320bfc122c37f Mon Sep 17 00:00:00 2001 From: Ryan Gonzalez Date: Sat, 15 Aug 2015 12:43:05 -0500 Subject: [PATCH 0832/1263] Mention Howl's Nim support --- web/question.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/web/question.txt b/web/question.txt index c4d997922..46ea7161c 100644 --- a/web/question.txt +++ b/web/question.txt @@ -113,6 +113,7 @@ General FAQ - TextMate: Available in bundle installer (`Repository `_) - Sublime Text: Available via Package Control (`Repository `_) - LiClipse: http://www.liclipse.com/ (Eclipse based plugin) + - Howl: Included .. container:: standout From d66cc007502d62133603189f73fb53bc0a81ef5c Mon Sep 17 00:00:00 2001 From: Ryan Gonzalez Date: Sat, 15 Aug 2015 17:13:18 -0500 Subject: [PATCH 0833/1263] Give a nice error when no command is given --- compiler/msgs.nim | 3 ++- compiler/nim.nim | 2 ++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/compiler/msgs.nim b/compiler/msgs.nim index bb247ea54..9bff6c123 100644 --- a/compiler/msgs.nim +++ b/compiler/msgs.nim @@ -82,7 +82,7 @@ type errArrayExpectsTwoTypeParams, errInvalidVisibilityX, errInitHereNotAllowed, errXCannotBeAssignedTo, errIteratorNotAllowed, errXNeedsReturnType, errNoReturnTypeDeclared, - errInvalidCommandX, errXOnlyAtModuleScope, + errNoCommand, errInvalidCommandX, errXOnlyAtModuleScope, errXNeedsParamObjectType, errTemplateInstantiationTooNested, errInstantiationFrom, errInvalidIndexValueForTuple, errCommandExpectsFilename, @@ -316,6 +316,7 @@ const errIteratorNotAllowed: "iterators can only be defined at the module\'s top level", errXNeedsReturnType: "$1 needs a return type", errNoReturnTypeDeclared: "no return type declared", + errNoCommand: "no command given", errInvalidCommandX: "invalid command: \'$1\'", errXOnlyAtModuleScope: "\'$1\' is only allowed at top level", errXNeedsParamObjectType: "'$1' needs a parameter that has an object type", diff --git a/compiler/nim.nim b/compiler/nim.nim index 5da87dfa3..ce9028d53 100644 --- a/compiler/nim.nim +++ b/compiler/nim.nim @@ -58,6 +58,8 @@ proc handleCmdLine() = # command line can overwite the config file's settings extccomp.initVars() processCmdLine(passCmd2, "") + if options.command == "": + rawMessage(errNoCommand, command) mainCommand() if optHints in gOptions and hintGCStats in gNotes: echo(GC_getStatistics()) #echo(GC_getStatistics()) From 2552a0f4b0f80bf3fcfea1edc37d30f921450650 Mon Sep 17 00:00:00 2001 From: Araq Date: Sun, 16 Aug 2015 11:01:20 +0200 Subject: [PATCH 0834/1263] fixed test instruction --- contributing.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contributing.rst b/contributing.rst index 65b0d0975..31f04a5e0 100644 --- a/contributing.rst +++ b/contributing.rst @@ -112,7 +112,7 @@ tell you if any new tests passed/failed. :: - ./koch --print html $DEVEL_COMMIT + ./koch tests --print html $DEVEL_COMMIT Deprecation From cd2fbb5f86809c36e4ef1e72259446f0aefaf2b7 Mon Sep 17 00:00:00 2001 From: Araq Date: Sun, 16 Aug 2015 11:15:04 +0200 Subject: [PATCH 0835/1263] staticExec: redirect stderr to stdout so stderr is returned too --- compiler/vmdeps.nim | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/compiler/vmdeps.nim b/compiler/vmdeps.nim index 73016108d..2cc4a107b 100644 --- a/compiler/vmdeps.nim +++ b/compiler/vmdeps.nim @@ -30,7 +30,7 @@ proc opGorge*(cmd, input, cache: string): string = return var readSuccessful = false try: - var p = startProcess(cmd, options={poEvalCommand}) + var p = startProcess(cmd, options={poEvalCommand, poStderrToStdout}) if input.len != 0: p.inputStream.write(input) p.inputStream.close() @@ -41,7 +41,7 @@ proc opGorge*(cmd, input, cache: string): string = if not readSuccessful: result = "" else: try: - var p = startProcess(cmd, options={poEvalCommand}) + var p = startProcess(cmd, options={poEvalCommand, poStderrToStdout}) if input.len != 0: p.inputStream.write(input) p.inputStream.close() From cc934a1a1bdbe896d1d9d2f2f1a6acccb249ed33 Mon Sep 17 00:00:00 2001 From: Araq Date: Sun, 16 Aug 2015 11:25:30 +0200 Subject: [PATCH 0836/1263] VM: repl supports global variables properly" --- compiler/vmgen.nim | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/compiler/vmgen.nim b/compiler/vmgen.nim index 858ec203e..919c38e08 100644 --- a/compiler/vmgen.nim +++ b/compiler/vmgen.nim @@ -1183,7 +1183,7 @@ proc checkCanEval(c: PCtx; n: PNode) = let s = n.sym if {sfCompileTime, sfGlobal} <= s.flags: return if s.kind in {skVar, skTemp, skLet, skParam, skResult} and - not s.isOwnedBy(c.prc.sym) and s.owner != c.module: + not s.isOwnedBy(c.prc.sym) and s.owner != c.module and c.mode != emRepl: cannotEval(n) elif s.kind in {skProc, skConverter, skMethod, skIterator, skClosureIterator} and sfForward in s.flags: @@ -1850,13 +1850,13 @@ proc genProc(c: PCtx; s: PSym): int = c.prc = p # iterate over the parameters and allocate space for them: genParams(c, s.typ.n) - + # allocate additional space for any generically bound parameters if s.kind == skMacro and sfImmediate notin s.flags and s.ast[genericParamsPos].kind != nkEmpty: genGenericParams(c, s.ast[genericParamsPos]) - + if tfCapturesEnv in s.typ.flags: #let env = s.ast.sons[paramsPos].lastSon.sym #assert env.position == 2 From d81578cb9b4776356d610e2329ffc7f3323d13db Mon Sep 17 00:00:00 2001 From: Araq Date: Sun, 16 Aug 2015 13:33:05 +0200 Subject: [PATCH 0837/1263] workaround windows 'findNextFile' bug --- lib/pure/os.nim | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/lib/pure/os.nim b/lib/pure/os.nim index 48d255dca..c2c28c2b1 100644 --- a/lib/pure/os.nim +++ b/lib/pure/os.nim @@ -1244,7 +1244,14 @@ iterator walkFiles*(pattern: string): string {.tags: [ReadDirEffect].} = while true: if not skipFindData(f) and (f.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) == 0'i32: - yield splitFile(pattern).dir / extractFilename(getFilename(f)) + # Windows bug/gotcha: 't*.nim' matches 'tfoo.nims' -.- so we check + # that the file extensions have the same length ... + let ff = getFilename(f) + let dotPos = searchExtPos(pattern) + let idx = ff.len - pattern.len + dotPos + if dotPos < 0 or idx >= ff.len or ff[idx] == '.' or + pattern[dotPos+1] == '*': + yield splitFile(pattern).dir / extractFilename(ff) if findNextFile(res, f) == 0'i32: break findClose(res) else: # here we use glob From 69b32637b1f12000b64fa4db452323dc30b3567f Mon Sep 17 00:00:00 2001 From: Araq Date: Sun, 16 Aug 2015 13:40:52 +0200 Subject: [PATCH 0838/1263] implements experimental new config system based on NimScript --- compiler/commands.nim | 2 +- compiler/main.nim | 3 +- compiler/modules.nim | 20 +++-- compiler/nim.nim | 9 ++- compiler/options.nim | 6 +- compiler/scriptconfig.nim | 119 +++++++++++++++++++++++++++++ compiler/vm.nim | 4 +- compiler/vmhooks.nim | 12 ++- lib/system.nim | 108 +++++++++++++++------------ lib/system/nimscript.nim | 152 ++++++++++++++++++++++++++++++++++++++ lib/system/sysio.nim | 11 ++- tests/newconfig/tfoo.nim | 7 ++ tests/newconfig/tfoo.nims | 14 ++++ 13 files changed, 398 insertions(+), 69 deletions(-) create mode 100644 compiler/scriptconfig.nim create mode 100644 lib/system/nimscript.nim create mode 100644 tests/newconfig/tfoo.nim create mode 100644 tests/newconfig/tfoo.nims diff --git a/compiler/commands.nim b/compiler/commands.nim index 7a908b270..fc28577aa 100644 --- a/compiler/commands.nim +++ b/compiler/commands.nim @@ -641,7 +641,7 @@ proc processSwitch*(pass: TCmdLinePass; p: OptParser) = proc processArgument*(pass: TCmdLinePass; p: OptParser; argsCount: var int): bool = if argsCount == 0: - options.command = p.key + if pass != passCmd2: options.command = p.key else: if pass == passCmd1: options.commandArgs.add p.key if argsCount == 1: diff --git a/compiler/main.nim b/compiler/main.nim index 47fae7fa7..014605cc9 100644 --- a/compiler/main.nim +++ b/compiler/main.nim @@ -116,7 +116,7 @@ proc interactivePasses = #incl(gGlobalOptions, optSafeCode) #setTarget(osNimrodVM, cpuNimrodVM) initDefines() - defineSymbol("nimrodvm") + defineSymbol("nimscript") when hasFFI: defineSymbol("nimffi") registerPass(verbosePass) registerPass(semPass) @@ -356,6 +356,7 @@ proc mainCommand* = gGlobalOptions.incl(optCaasEnabled) msgs.gErrorMax = high(int) # do not stop after first error serve(mainCommand) + of "nop": discard else: rawMessage(errInvalidCommandX, command) diff --git a/compiler/modules.nim b/compiler/modules.nim index 2d0267c93..ad68e6315 100644 --- a/compiler/modules.nim +++ b/compiler/modules.nim @@ -85,6 +85,15 @@ proc resetAllModules* = resetPackageCache() # for m in cgenModules(): echo "CGEN MODULE FOUND" +proc resetAllModulesHard* = + resetPackageCache() + gCompiledModules.setLen 0 + gMemCacheData.setLen 0 + magicsys.resetSysTypes() + # XXX + #gOwners = @[] + #rangeDestructorProc = nil + proc checkDepMem(fileIdx: int32): TNeedRecompile = template markDirty = resetModule(fileIdx) @@ -205,9 +214,8 @@ proc compileProject*(projectFileIdx = -1'i32) = compileSystemModule() discard compileModule(projectFile, {sfMainModule}) -var stdinModule: PSym -proc makeStdinModule*(): PSym = - if stdinModule == nil: - stdinModule = newModule(fileInfoIdx"stdin") - stdinModule.id = getID() - result = stdinModule +proc makeModule*(filename: string): PSym = + result = newModule(fileInfoIdx filename) + result.id = getID() + +proc makeStdinModule*(): PSym = makeModule"stdin" diff --git a/compiler/nim.nim b/compiler/nim.nim index ce9028d53..51f4cae92 100644 --- a/compiler/nim.nim +++ b/compiler/nim.nim @@ -1,7 +1,7 @@ # # # The Nim Compiler -# (c) Copyright 2013 Andreas Rumpf +# (c) Copyright 2015 Andreas Rumpf # # See the file "copying.txt", included in this # distribution, for details about the copyright. @@ -16,7 +16,7 @@ when defined(gcc) and defined(windows): import commands, lexer, condsyms, options, msgs, nversion, nimconf, ropes, extccomp, strutils, os, osproc, platform, main, parseopt, service, - nodejs + nodejs, scriptconfig when hasTinyCBackend: import tccgen @@ -54,6 +54,11 @@ proc handleCmdLine() = else: gProjectPath = getCurrentDir() loadConfigs(DefaultConfig) # load all config files + let scriptFile = gProjectFull.changeFileExt("nims") + if fileExists(scriptFile): + runNimScript(scriptFile) + # 'nim foo.nims' means to just run the NimScript file and do nothing more: + if scriptFile == gProjectFull: return # now process command line arguments again, because some options in the # command line can overwite the config file's settings extccomp.initVars() diff --git a/compiler/options.nim b/compiler/options.nim index af1e21e60..adf2017d6 100644 --- a/compiler/options.nim +++ b/compiler/options.nim @@ -210,7 +210,7 @@ proc removeTrailingDirSep*(path: string): string = else: result = path -proc getGeneratedPath: string = +proc getNimcacheDir*: string = result = if nimcacheDir.len > 0: nimcacheDir else: gProjectPath.shortenDir / genSubDir @@ -266,7 +266,7 @@ proc toGeneratedFile*(path, ext: string): string = ## converts "/home/a/mymodule.nim", "rod" to "/home/a/nimcache/mymodule.rod" var (head, tail) = splitPath(path) #if len(head) > 0: head = shortenDir(head & dirSep) - result = joinPath([getGeneratedPath(), changeFileExt(tail, ext)]) + result = joinPath([getNimcacheDir(), changeFileExt(tail, ext)]) #echo "toGeneratedFile(", path, ", ", ext, ") = ", result when noTimeMachine: @@ -294,7 +294,7 @@ when noTimeMachine: proc completeGeneratedFilePath*(f: string, createSubDir: bool = true): string = var (head, tail) = splitPath(f) #if len(head) > 0: head = removeTrailingDirSep(shortenDir(head & dirSep)) - var subdir = getGeneratedPath() # / head + var subdir = getNimcacheDir() # / head if createSubDir: try: createDir(subdir) diff --git a/compiler/scriptconfig.nim b/compiler/scriptconfig.nim new file mode 100644 index 000000000..1e4fc25af --- /dev/null +++ b/compiler/scriptconfig.nim @@ -0,0 +1,119 @@ +# +# +# The Nim Compiler +# (c) Copyright 2015 Andreas Rumpf +# +# See the file "copying.txt", included in this +# distribution, for details about the copyright. +# + +## Implements the new configuration system for Nim. Uses Nim as a scripting +## language. + +import + ast, modules, passes, passaux, condsyms, + options, nimconf, lists, sem, semdata, llstream, vm, vmdef, commands, msgs, + os, times + +# we support 'cmpIgnoreStyle' natively for efficiency: +from strutils import cmpIgnoreStyle + +proc listDirs(a: VmArgs, filter: set[PathComponent]) = + let dir = getString(a, 0) + var result: seq[string] = @[] + for kind, path in walkDir(dir): + if kind in filter: result.add path + setResult(a, result) + +proc setupVM(module: PSym; scriptName: string): PEvalContext = + result = newCtx(module) + result.mode = emRepl + registerAdditionalOps(result) + + # captured vars: + var errorMsg: string + var vthisDir = scriptName.splitFile.dir + + template cbconf(name, body) {.dirty.} = + result.registerCallback "stdlib.system." & astToStr(name), + proc (a: VmArgs) = + body + + template cbos(name, body) {.dirty.} = + result.registerCallback "stdlib.system." & astToStr(name), + proc (a: VmArgs) = + try: + body + except OSError: + errorMsg = getCurrentExceptionMsg() + + # Idea: Treat link to file as a file, but ignore link to directory to prevent + # endless recursions out of the box. + cbos listFiles: + listDirs(a, {pcFile, pcLinkToFile}) + cbos listDirs: + listDirs(a, {pcDir}) + cbos removeDir: + os.removeDir getString(a, 0) + cbos removeFile: + os.removeFile getString(a, 0) + cbos createDir: + os.createDir getString(a, 0) + cbos getOsError: + setResult(a, errorMsg) + cbos setCurrentDir: + os.setCurrentDir getString(a, 0) + cbos getCurrentDir: + setResult(a, os.getCurrentDir()) + cbos moveFile: + os.moveFile(getString(a, 0), getString(a, 1)) + cbos getLastModificationTime: + setResult(a, toSeconds(getLastModificationTime(getString(a, 0)))) + + cbconf thisDir: + setResult(a, vthisDir) + cbconf put: + options.setConfigVar(getString(a, 0), getString(a, 1)) + cbconf get: + setResult(a, options.getConfigVar(a.getString 0)) + cbconf exists: + setResult(a, options.existsConfigVar(a.getString 0)) + cbconf nimcacheDir: + setResult(a, options.getNimcacheDir()) + cbconf paramStr: + setResult(a, os.paramStr(int a.getInt 0)) + cbconf paramCount: + setResult(a, os.paramCount()) + cbconf cmpIgnoreStyle: + setResult(a, strutils.cmpIgnoreStyle(a.getString 0, a.getString 1)) + cbconf setCommand: + options.command = a.getString 0 + cbconf getCommand: + setResult(a, options.command) + cbconf switch: + processSwitch(a.getString 0, a.getString 1, passPP, unknownLineInfo()) + + +proc runNimScript*(scriptName: string) = + passes.gIncludeFile = includeModule + passes.gImportModule = importModule + initDefines() + + defineSymbol("nimscript") + defineSymbol("nimconfig") + registerPass(semPass) + registerPass(evalPass) + + appendStr(searchPaths, options.libpath) + + var m = makeModule(scriptName) + incl(m.flags, sfMainModule) + vm.globalCtx = setupVM(m, scriptName) + + compileSystemModule() + processModule(m, llStreamOpen(scriptName, fmRead), nil) + + # ensure we load 'system.nim' again for the real non-config stuff! + resetAllModulesHard() + vm.globalCtx = nil + initDefines() diff --git a/compiler/vm.nim b/compiler/vm.nim index b1d71d73b..57ed8397c 100644 --- a/compiler/vm.nim +++ b/compiler/vm.nim @@ -1407,7 +1407,7 @@ include vmops # storing&loading the 'globals' environment to get what a component system # requires. var - globalCtx: PCtx + globalCtx*: PCtx proc setupGlobalCtx(module: PSym) = if globalCtx.isNil: @@ -1516,7 +1516,7 @@ proc evalMacroCall*(module: PSym, n, nOrig: PNode, sym: PSym): PNode = # return value: tos.slots[0].kind = rkNode tos.slots[0].node = newNodeIT(nkEmpty, n.info, sym.typ.sons[0]) - + # setup parameters: for i in 1.. y: result = 1 + else: result = 0 const pccHack = if defined(pcc): "_" else: "" # Hack for PCC - when not defined(NimrodVM): + when not defined(nimscript): when defined(windows): # work-around C's sucking abstraction: # BUGFIX: stdin and stdout should be binary files! @@ -2536,14 +2542,15 @@ when not defined(JS): #and not defined(NimrodVM): {.deprecated: [TFile: File, TFileHandle: FileHandle, TFileMode: FileMode].} - # text file handling: - var - stdin* {.importc: "stdin", header: "".}: File - ## The standard input stream. - stdout* {.importc: "stdout", header: "".}: File - ## The standard output stream. - stderr* {.importc: "stderr", header: "".}: File - ## The standard error stream. + when not defined(nimscript): + # text file handling: + var + stdin* {.importc: "stdin", header: "".}: File + ## The standard input stream. + stdout* {.importc: "stdout", header: "".}: File + ## The standard output stream. + stderr* {.importc: "stderr", header: "".}: File + ## The standard error stream. when defined(useStdoutAsStdmsg): template stdmsg*: File = stdout @@ -2738,7 +2745,7 @@ when not defined(JS): #and not defined(NimrodVM): inc(i) dealloc(a) - when not defined(NimrodVM): + when not defined(nimscript): proc atomicInc*(memLoc: var int, x: int = 1): int {.inline, discardable, benign.} ## atomic increment of `memLoc`. Returns the value after the operation. @@ -2749,27 +2756,27 @@ when not defined(JS): #and not defined(NimrodVM): include "system/atomics" - type - PSafePoint = ptr TSafePoint - TSafePoint {.compilerproc, final.} = object - prev: PSafePoint # points to next safe point ON THE STACK - status: int - context: C_JmpBuf - hasRaiseAction: bool - raiseAction: proc (e: ref Exception): bool {.closure.} - SafePoint = TSafePoint -# {.deprecated: [TSafePoint: SafePoint].} + type + PSafePoint = ptr TSafePoint + TSafePoint {.compilerproc, final.} = object + prev: PSafePoint # points to next safe point ON THE STACK + status: int + context: C_JmpBuf + hasRaiseAction: bool + raiseAction: proc (e: ref Exception): bool {.closure.} + SafePoint = TSafePoint + # {.deprecated: [TSafePoint: SafePoint].} when declared(initAllocator): initAllocator() when hasThreadSupport: include "system/syslocks" when hostOS != "standalone": include "system/threads" - elif not defined(nogc) and not defined(NimrodVM): + elif not defined(nogc) and not defined(nimscript): when not defined(useNimRtl) and not defined(createNimRtl): initStackBottom() when declared(initGC): initGC() - when not defined(NimrodVM): + when not defined(nimscript): proc setControlCHook*(hook: proc () {.noconv.} not nil) ## allows you to override the behaviour of your application when CTRL+C ## is pressed. Only one such hook is supported. @@ -2798,9 +2805,9 @@ when not defined(JS): #and not defined(NimrodVM): {.pop.} # stack trace {.pop.} # stack trace - when hostOS != "standalone" and not defined(NimrodVM): + when hostOS != "standalone" and not defined(nimscript): include "system/dyncalls" - when not defined(NimrodVM): + when not defined(nimscript): include "system/sets" when defined(gogc): @@ -2875,11 +2882,11 @@ when not defined(JS): #and not defined(NimrodVM): var res = TaintedString(newStringOfCap(80)) while f.readLine(res): yield res - when not defined(NimrodVM) and hasAlloc: + when not defined(nimscript) and hasAlloc: include "system/assign" include "system/repr" - when hostOS != "standalone" and not defined(NimrodVM): + when hostOS != "standalone" and not defined(nimscript): proc getCurrentException*(): ref Exception {.compilerRtl, inl, benign.} = ## retrieves the current exception; if there is none, nil is returned. result = currException @@ -2907,14 +2914,14 @@ when not defined(JS): #and not defined(NimrodVM): currException = exc {.push stack_trace: off, profiler:off.} - when defined(endb) and not defined(NimrodVM): + when defined(endb) and not defined(nimscript): include "system/debugger" when defined(profiler) or defined(memProfiler): include "system/profiler" {.pop.} # stacktrace - when not defined(NimrodVM): + when not defined(nimscript): proc likely*(val: bool): bool {.importc: "likely", nodecl, nosideeffect.} ## Hints the optimizer that `val` is likely going to be true. ## @@ -2992,7 +2999,7 @@ elif defined(JS): when defined(JS): include "system/jssys" include "system/reprjs" - elif defined(NimrodVM): + elif defined(nimscript): proc cmp(x, y: string): int = if x == y: return 0 if x < y: return -1 @@ -3305,7 +3312,7 @@ proc shallow*[T](s: var seq[T]) {.noSideEffect, inline.} = ## marks a sequence `s` as `shallow`:idx:. Subsequent assignments will not ## perform deep copies of `s`. This is only useful for optimization ## purposes. - when not defined(JS) and not defined(NimrodVM): + when not defined(JS) and not defined(nimscript): var s = cast[PGenericSeq](s) s.reserved = s.reserved or seqShallowFlag @@ -3313,7 +3320,7 @@ proc shallow*(s: var string) {.noSideEffect, inline.} = ## marks a string `s` as `shallow`:idx:. Subsequent assignments will not ## perform deep copies of `s`. This is only useful for optimization ## purposes. - when not defined(JS) and not defined(NimrodVM): + when not defined(JS) and not defined(nimscript): var s = cast[PGenericSeq](s) s.reserved = s.reserved or seqShallowFlag @@ -3402,7 +3409,7 @@ proc locals*(): RootObj {.magic: "Plugin", noSideEffect.} = ## # -> B is 1 discard -when hasAlloc and not defined(NimrodVM) and not defined(JS): +when hasAlloc and not defined(nimscript) and not defined(JS): proc deepCopy*[T](x: var T, y: T) {.noSideEffect, magic: "DeepCopy".} = ## performs a deep copy of `x`. This is also used by the code generator ## for the implementation of ``spawn``. @@ -3444,3 +3451,6 @@ proc xlen*[T](x: seq[T]): int {.magic: "XLenSeq", noSideEffect.} = discard {.pop.} #{.push warning[GcMem]: off, warning[Uninit]: off.} + +when defined(nimconfig): + include "system/nimscript" diff --git a/lib/system/nimscript.nim b/lib/system/nimscript.nim new file mode 100644 index 000000000..6f5977869 --- /dev/null +++ b/lib/system/nimscript.nim @@ -0,0 +1,152 @@ +# +# +# Nim's Runtime Library +# (c) Copyright 2015 Andreas Rumpf +# +# See the file "copying.txt", included in this +# distribution, for details about the copyright. +# + + +# Nim's configuration system now uses Nim for scripting. This module provides +# a few things that are required for this to work. + +template builtin = discard + +proc listDirs*(dir: string): seq[string] = builtin +proc listFiles*(dir: string): seq[string] = builtin + +proc removeDir(dir: string) = builtin +proc removeFile(dir: string) = builtin +proc moveFile(src, dest: string) = builtin +proc createDir(dir: string) = builtin +proc getOsError: string = builtin +proc setCurrentDir(dir: string) = builtin +proc getCurrentDir(): string = builtin +proc paramStr*(i: int): string = builtin +proc paramCount*(): int = builtin + +proc switch*(key: string, val="") = builtin +proc getCommand*(): string = builtin +proc setCommand*(cmd: string) = builtin +proc cmpIgnoreStyle(a, b: string): int = builtin + +proc strip(s: string): string = + var i = 0 + while s[i] in {' ', '\c', '\L'}: inc i + result = s.substr(i) + +template `--`*(key, val: untyped) = switch(astToStr(key), strip astToStr(val)) +template `--`*(key: untyped) = switch(astToStr(key), "") + +type + ScriptMode* {.pure.} = enum + Silent, + Verbose, + Whatif + +var + mode*: ScriptMode ## Set this to influence how mkDir, rmDir, rmFile etc. + ## behave + +template checkOsError = + let err = getOsError() + if err.len > 0: raise newException(OSError, err) + +template log(msg: string, body: untyped) = + if mode == ScriptMode.Verbose or mode == ScriptMode.Whatif: + echo "[NimScript] ", msg + if mode != ScriptMode.WhatIf: + body + +proc rmDir*(dir: string) {.raises: [OSError].} = + log "rmDir: " & dir: + removeDir dir + checkOsError() + +proc rmFile*(dir: string) {.raises: [OSError].} = + log "rmFile: " & dir: + removeFile dir + checkOsError() + +proc mkDir*(dir: string) {.raises: [OSError].} = + log "mkDir: " & dir: + createDir dir + checkOsError() + +proc mvFile*(`from`, to: string) {.raises: [OSError].} = + log "mvFile: " & `from` & ", " & to: + moveFile `from`, to + checkOsError() + +proc exec*(command: string, input = "", cache = "") = + ## Executes an external process. + log "exec: " & command: + echo staticExec(command, input, cache) + +proc put*(key, value: string) = + ## Sets a configuration 'key' like 'gcc.options.always' to its value. + builtin + +proc get*(key: string): string = + ## Retrieves a configuration 'key' like 'gcc.options.always'. + builtin + +proc exists*(key: string): bool = + ## Checks for the existance of a configuration 'key' + ## like 'gcc.options.always'. + builtin + +proc nimcacheDir*(): string = + ## Retrieves the location of 'nimcache'. + builtin + +proc thisDir*(): string = + ## Retrieves the location of the current ``nims`` script file. + builtin + +proc cd*(dir: string) {.raises: [OSError].} = + ## Changes the current directory. + ## + ## The change is permanent for the rest of the execution, since this is just + ## a shortcut for `os.setCurrentDir() + ## `_ . Use the `withDir() + ## <#withDir>`_ template if you want to perform a temporary change only. + setCurrentDir(dir) + checkOsError() + +template withDir*(dir: string; body: untyped): untyped = + ## Changes the current directory temporarily. + ## + ## If you need a permanent change, use the `cd() <#cd>`_ proc. Usage example: + ## + ## .. code-block:: nimrod + ## withDir "foo": + ## # inside foo + ## #back to last dir + var curDir = getCurrentDir() + try: + cd(dir) + body + finally: + cd(curDir) + +template `==?`(a, b: string): bool = cmpIgnoreStyle(a, b) == 0 + +proc writeTask(name, desc: string) = + if desc.len > 0: + var spaces = " " + for i in 0 ..< 20 - name.len: spaces.add ' ' + echo name, spaces, desc + +template task*(name: untyped; description: string; body: untyped): untyped = + ## Defines a task. Hidden tasks are supported via an empty description. + proc `name Task`() = body + + let cmd = getCommand() + if cmd.len == 0 or cmd ==? "help" or cmd == "nop": + setCommand "nop" + writeTask(astToStr(name), description) + elif cmd ==? astToStr(name): + setCommand "nop" + `name Task`() diff --git a/lib/system/sysio.nim b/lib/system/sysio.nim index 5464ee126..b3316920e 100644 --- a/lib/system/sysio.nim +++ b/lib/system/sysio.nim @@ -182,7 +182,10 @@ proc readAllFile(file: File): string = proc readAll(file: File): TaintedString = # Separate handling needed because we need to buffer when we # don't know the overall length of the File. - let len = if file != stdin: rawFileSize(file) else: -1 + when declared(stdin): + let len = if file != stdin: rawFileSize(file) else: -1 + else: + let len = rawFileSize(file) if len > 0: result = readAllFile(file, len).TaintedString else: @@ -216,9 +219,9 @@ proc writeLine[Ty](f: File, x: varargs[Ty, `$`]) = for i in items(x): write(f, i) write(f, "\n") - -proc rawEcho(x: string) {.inline, compilerproc.} = write(stdout, x) -proc rawEchoNL() {.inline, compilerproc.} = write(stdout, "\n") +when declared(stdout): + proc rawEcho(x: string) {.inline, compilerproc.} = write(stdout, x) + proc rawEchoNL() {.inline, compilerproc.} = write(stdout, "\n") # interface to the C procs: diff --git a/tests/newconfig/tfoo.nim b/tests/newconfig/tfoo.nim new file mode 100644 index 000000000..0ace7c88a --- /dev/null +++ b/tests/newconfig/tfoo.nim @@ -0,0 +1,7 @@ +discard """ + cmd: "nim default $file" + output: '''hello world!''' + msg: '''[NimScript] exec: gcc -v''' +""" + +echo "hello world!" diff --git a/tests/newconfig/tfoo.nims b/tests/newconfig/tfoo.nims new file mode 100644 index 000000000..90205cddb --- /dev/null +++ b/tests/newconfig/tfoo.nims @@ -0,0 +1,14 @@ + +mode = ScriptMode.Whatif + +exec "gcc -v" + +--forceBuild + +task listDirs, "lists every subdirectory": + for x in listDirs("."): + echo "DIR ", x + +task default, "default target": + setCommand "c" + From fc235833d44e20f8901fe5ef80c5e85725fedfe8 Mon Sep 17 00:00:00 2001 From: Grzegorz Adam Hankiewicz Date: Mon, 17 Aug 2015 23:30:36 +0200 Subject: [PATCH 0839/1263] Removes dead references. --- examples/cross_calculator/android/readme.txt | 6 ------ examples/cross_calculator/ios/readme.txt | 4 ---- examples/cross_todo/readme.txt | 2 -- 3 files changed, 12 deletions(-) diff --git a/examples/cross_calculator/android/readme.txt b/examples/cross_calculator/android/readme.txt index 51fa9c6fd..96bd403ca 100644 --- a/examples/cross_calculator/android/readme.txt +++ b/examples/cross_calculator/android/readme.txt @@ -20,11 +20,5 @@ installed on your system, you can simply run "ant debug" to build everything. Once the apk is built you can install it on your device or emulator with the command "adb install bin/CrossCalculator-debug.apk". -You can use this example as a starting point for your project or look at the -history of the github project at https://github.com/gradha/nimrod-on-android. -That repository documents the individual integration steps you would take for -any Android project (note it uses Eclipse rather than ant to build and -therefore the build process requires more manual fiddling). - This example runs against the Android level 3 API, meaning devices from Android 1.5 and above should be able to run the generated binary. diff --git a/examples/cross_calculator/ios/readme.txt b/examples/cross_calculator/ios/readme.txt index 83538aad7..3ea03a367 100644 --- a/examples/cross_calculator/ios/readme.txt +++ b/examples/cross_calculator/ios/readme.txt @@ -8,10 +8,6 @@ When the calculate button is used the view controller calls the Nim code to delegate the logic of the operation and puts the result in a label for display. All interface error checks are implemented in the view controller. -You can use this as a starting point for your project or look at the history of -the github project at https://github.com/gradha/nimrod-on-ios. That repository -documents the individual integration steps you would take for any iOS project. - This version of the iOS project is known to work with Xcode 4.2 and Xcode 4.4.1. The final binary can be deployed on iOS 3.x to 5.x supporting all iOS platforms and versions available at the moment. diff --git a/examples/cross_todo/readme.txt b/examples/cross_todo/readme.txt index 2e648a35a..dfc21d861 100644 --- a/examples/cross_todo/readme.txt +++ b/examples/cross_todo/readme.txt @@ -3,5 +3,3 @@ called by different native user interfaces. This example builds on the knowledge learned from the cross_calculator example. Check it out first to learn how to set up Nim on different platforms. -Additional implementations are provided at the external -https://github.com/gradha/nimrod-crossplatform-todo github repository. From d634da775db3ee28b075b60c6c898a24167e0ce0 Mon Sep 17 00:00:00 2001 From: Araq Date: Tue, 18 Aug 2015 13:57:37 +0200 Subject: [PATCH 0840/1263] cleanup destructor building for arrays; still doesn't work --- compiler/main.nim | 3 +-- compiler/semdestruct.nim | 5 +---- lib/system/assign.nim | 34 +++++++++++++--------------------- 3 files changed, 15 insertions(+), 27 deletions(-) diff --git a/compiler/main.nim b/compiler/main.nim index 014605cc9..baf1c5208 100644 --- a/compiler/main.nim +++ b/compiler/main.nim @@ -190,7 +190,6 @@ proc resetMemory = resetRopeCache() resetSysTypes() gOwners = @[] - rangeDestructorProc = nil for i in low(buckets)..high(buckets): buckets[i] = nil idAnon = nil @@ -237,7 +236,7 @@ proc mainCommand* = when SimulateCaasMemReset: gGlobalOptions.incl(optCaasEnabled) - # In "nimrod serve" scenario, each command must reset the registered passes + # In "nim serve" scenario, each command must reset the registered passes clearPasses() gLastCmdTime = epochTime() appendStr(searchPaths, options.libpath) diff --git a/compiler/semdestruct.nim b/compiler/semdestruct.nim index af671f6e0..1261dd460 100644 --- a/compiler/semdestruct.nim +++ b/compiler/semdestruct.nim @@ -24,7 +24,6 @@ var destructorName = getIdent"destroy_" destructorParam = getIdent"this_" destructorPragma = newIdentNode(getIdent"destructor", unknownLineInfo()) - rangeDestructorProc*: PSym proc instantiateDestructor(c: PContext, typ: PType): PType @@ -141,9 +140,7 @@ proc instantiateDestructor(c: PContext, typ: PType): PType = case t.kind of tySequence, tyArray, tyArrayConstr, tyOpenArray, tyVarargs: if instantiateDestructor(c, t.sons[0]) != nil: - if rangeDestructorProc == nil: - rangeDestructorProc = searchInScopes(c, getIdent"nimDestroyRange") - t.destructor = rangeDestructorProc + t.destructor = getCompilerProc"nimDestroyRange" return t else: return nil diff --git a/lib/system/assign.nim b/lib/system/assign.nim index 78995954f..55d7572e2 100644 --- a/lib/system/assign.nim +++ b/lib/system/assign.nim @@ -17,7 +17,7 @@ proc genericAssignAux(dest, src: pointer, n: ptr TNimNode, s = cast[ByteAddress](src) case n.kind of nkSlot: - genericAssignAux(cast[pointer](d +% n.offset), + genericAssignAux(cast[pointer](d +% n.offset), cast[pointer](s +% n.offset), n.typ, shallow) of nkList: for i in 0..n.len-1: @@ -54,7 +54,7 @@ proc genericAssignAux(dest, src: pointer, mt: PNimType, shallow: bool) = unsureAsgnRef(x, copyString(cast[NimString](s2))) of tySequence: var s2 = cast[PPointer](src)[] - var seq = cast[PGenericSeq](s2) + var seq = cast[PGenericSeq](s2) var x = cast[PPointer](dest) if s2 == nil or shallow or (seq.reserved and seqShallowFlag) != 0: # this can happen! nil sequences are allowed @@ -100,7 +100,7 @@ proc genericShallowAssign(dest, src: pointer, mt: PNimType) {.compilerProc.} = when false: proc debugNimType(t: PNimType) = - if t.isNil: + if t.isNil: cprintf("nil!") return var k: cstring @@ -170,21 +170,13 @@ proc objectInit(dest: pointer, typ: PNimType) = for i in 0..(typ.size div typ.base.size)-1: objectInit(cast[pointer](d +% i * typ.base.size), typ.base) else: discard # nothing to do - + # ---------------------- assign zero ----------------------------------------- -when not defined(nimmixin): - proc destroy(x: int) = discard - proc nimDestroyRange*[T](r: T) = - # internal proc used for destroying sequences and arrays - for i in countup(0, r.len - 1): destroy(r[i]) -else: - # XXX Why is this exported and no compilerproc? -> compilerprocs cannot be - # generic for now - proc nimDestroyRange*[T](r: T) = - # internal proc used for destroying sequences and arrays - mixin destroy - for i in countup(0, r.len - 1): destroy(r[i]) +proc nimDestroyRange[T](r: T) {.compilerProc.} = + # internal proc used for destroying sequences and arrays + mixin `=destroy` + for i in countup(0, r.len - 1): `=destroy`(r[i]) proc genericReset(dest: pointer, mt: PNimType) {.compilerProc, benign.} proc genericResetAux(dest: pointer, n: ptr TNimNode) = @@ -198,7 +190,7 @@ proc genericResetAux(dest: pointer, n: ptr TNimNode) = var m = selectBranch(dest, n) if m != nil: genericResetAux(dest, m) zeroMem(cast[pointer](d +% n.offset), n.typ.size) - + proc genericReset(dest: pointer, mt: PNimType) = var d = cast[ByteAddress](dest) sysAssert(mt != nil, "genericReset 2") @@ -218,15 +210,15 @@ proc genericReset(dest: pointer, mt: PNimType) = else: zeroMem(dest, mt.size) # set raw bits to zero -proc selectBranch(discVal, L: int, +proc selectBranch(discVal, L: int, a: ptr array [0..0x7fff, ptr TNimNode]): ptr TNimNode = result = a[L] # a[L] contains the ``else`` part (but may be nil) if discVal <% L: var x = a[discVal] if x != nil: result = x - -proc FieldDiscriminantCheck(oldDiscVal, newDiscVal: int, - a: ptr array [0..0x7fff, ptr TNimNode], + +proc FieldDiscriminantCheck(oldDiscVal, newDiscVal: int, + a: ptr array [0..0x7fff, ptr TNimNode], L: int) {.compilerProc.} = var oldBranch = selectBranch(oldDiscVal, L, a) var newBranch = selectBranch(newDiscVal, L, a) From 10a7830ba2b5e26f8a37c160f7425a3130d67ae0 Mon Sep 17 00:00:00 2001 From: Araq Date: Tue, 18 Aug 2015 13:58:57 +0200 Subject: [PATCH 0841/1263] fixes Windows version of readPasswordFromStdin (setLen doesn't accept negative values anymore) --- lib/impure/rdstdin.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/impure/rdstdin.nim b/lib/impure/rdstdin.nim index 14aefb315..b373859f4 100644 --- a/lib/impure/rdstdin.nim +++ b/lib/impure/rdstdin.nim @@ -94,7 +94,7 @@ when defined(Windows): while i < password.len: x = runeLenAt(password, i) inc i, x - password.setLen(password.len - x) + password.setLen(max(password.len - x, 0)) else: password.add(toUTF8(c.Rune)) stdout.write "\n" From 9659540b18b9bd76ea027c83a10077103fcc6318 Mon Sep 17 00:00:00 2001 From: Araq Date: Tue, 18 Aug 2015 14:01:40 +0200 Subject: [PATCH 0842/1263] preparations for Nimble NimScript integrations; minor cleanups --- compiler/modules.nim | 1 - compiler/nim.cfg | 1 - compiler/scriptconfig.nim | 3 ++- compiler/vm.nim | 4 ++++ config/nim.cfg | 1 - lib/system/nimscript.nim | 27 ++++++++++++++++++++++++ todo.txt | 43 +++++++++++++++++++++++++++++++++++++-- 7 files changed, 74 insertions(+), 6 deletions(-) diff --git a/compiler/modules.nim b/compiler/modules.nim index ad68e6315..85c99c4ec 100644 --- a/compiler/modules.nim +++ b/compiler/modules.nim @@ -92,7 +92,6 @@ proc resetAllModulesHard* = magicsys.resetSysTypes() # XXX #gOwners = @[] - #rangeDestructorProc = nil proc checkDepMem(fileIdx: int32): TNeedRecompile = template markDirty = diff --git a/compiler/nim.cfg b/compiler/nim.cfg index 64631a437..4f9962ea8 100644 --- a/compiler/nim.cfg +++ b/compiler/nim.cfg @@ -17,5 +17,4 @@ define:useStdoutAsStdmsg cs:partial #define:useNodeIds -symbol:nimfix #gc:markAndSweep diff --git a/compiler/scriptconfig.nim b/compiler/scriptconfig.nim index 1e4fc25af..148a382c2 100644 --- a/compiler/scriptconfig.nim +++ b/compiler/scriptconfig.nim @@ -25,7 +25,8 @@ proc listDirs(a: VmArgs, filter: set[PathComponent]) = if kind in filter: result.add path setResult(a, result) -proc setupVM(module: PSym; scriptName: string): PEvalContext = +proc setupVM*(module: PSym; scriptName: string): PEvalContext = + # For Nimble we need to export 'setupVM'. result = newCtx(module) result.mode = emRepl registerAdditionalOps(result) diff --git a/compiler/vm.nim b/compiler/vm.nim index 57ed8397c..b15c55565 100644 --- a/compiler/vm.nim +++ b/compiler/vm.nim @@ -1401,6 +1401,10 @@ proc evalExpr*(c: PCtx, n: PNode): PNode = assert c.code[start].opcode != opcEof result = execute(c, start) +proc getGlobalValue*(c: PCtx; s: PSym): PNode = + internalAssert s.kind in {skLet, skVar} and sfGlobal in s.flags + result = c.globals.sons[s.position-1] + include vmops # for now we share the 'globals' environment. XXX Coming soon: An API for diff --git a/config/nim.cfg b/config/nim.cfg index 09864e0e5..a854a30ef 100644 --- a/config/nim.cfg +++ b/config/nim.cfg @@ -50,7 +50,6 @@ path="$lib/js" path="$lib/pure/unidecode" @if nimbabel: - babelpath="$home/.babel/pkgs/" nimblepath="$home/.nimble/pkgs/" @end diff --git a/lib/system/nimscript.nim b/lib/system/nimscript.nim index 6f5977869..013b2cbc0 100644 --- a/lib/system/nimscript.nim +++ b/lib/system/nimscript.nim @@ -150,3 +150,30 @@ template task*(name: untyped; description: string; body: untyped): untyped = elif cmd ==? astToStr(name): setCommand "nop" `name Task`() + +type + VersionReq* = distinct string ## Describes a version requirement. + +template v*(name: string{lit}): VersionReq = VersionReq(name) +template special*(name: string): VersionReq = VersionReq(name) +template `<`*(v: VersionReq): VersionReq = VersionReq("<" & string(v)) +template `<=`*(v: VersionReq): VersionReq = VersionReq("<=" & string(v)) +template `>`*(v: VersionReq): VersionReq = VersionReq(">" & string(v)) +template `>=`*(v: VersionReq): VersionReq = VersionReq(">=" & string(v)) +template `&`*(a, b: VersionReq): VersionReq = + VersionReq(string(a) & " & " & string(b)) + +const + anyVersion* = VersionReq("*") + +var + packageName* = "" + version*, author*, description*, license*, srcdir*, + binDir*, backend*: string + + skipDirs*, skipFiles*, skipExt*, installDirs*, installFiles*, + installExt*, bin*: seq[string] + requiresData*: seq[(string, VersionReq)] + +proc requires*(name: string; v: VersionReq) = + requiresData.add((name, v)) diff --git a/todo.txt b/todo.txt index 0d4dbd2ad..ee30894da 100644 --- a/todo.txt +++ b/todo.txt @@ -1,6 +1,9 @@ version 0.11.4 ============== +- make tuple unpacking work in a non-var/let context +- built-in 'getImpl' + - document special cased varargs[untyped] and varargs[typed] - The remaining bugs of the lambda lifting pass that is responsible to enable @@ -50,14 +53,50 @@ Low priority: Misc ---- -- make tuple unpacking work in a non-var/let context -- built-in 'getImpl' - prevent 'alloc(TypeWithGCedMemory)' Bugs ==== +- Can lead to wrong C code: + +template cd*(dir: string, body: stmt) = + ## Sets the current dir to ``dir``, executes ``body`` and restores the + ## previous working dir. + let lastDir = getCurrentDir() + setCurrentDir(dir) + try: + body + finally: + setCurrentDir(lastDir) + +proc test = + cd dir: + var output = execProcess("git tag") + case meth + of DownloadMethod.git: + output = execProcess("git tag") + of DownloadMethod.hg: + output = execProcess("hg tags") + if output.len > 0: + case meth + of DownloadMethod.git: + result = @[] + for i in output.splitLines(): + if i == "": continue + result.add(i) + of DownloadMethod.hg: + result = @[] + for i in output.splitLines(): + if i == "": continue + var tag = "" + discard parseUntil(i, tag, ' ') + if tag != "tip": + result.add(tag) + else: + result = @[] + - VM: Pegs do not work at compile-time - VM: ptr/ref T cannot work in general - blocks can "export" an identifier but the CCG generates {} for them ... From 493dbc8932326c5f830c0396b528d433a0bdf314 Mon Sep 17 00:00:00 2001 From: jangko Date: Thu, 20 Aug 2015 14:17:46 +0700 Subject: [PATCH 0843/1263] fixed UTF-16 to UTF-8 conversion in widestrs.nim the source of problem for issue #3228 --- lib/system/widestrs.nim | 44 +++++++++++++++++------------------------ 1 file changed, 18 insertions(+), 26 deletions(-) diff --git a/lib/system/widestrs.nim b/lib/system/widestrs.nim index e7b7f3972..e782e2452 100644 --- a/lib/system/widestrs.nim +++ b/lib/system/widestrs.nim @@ -119,36 +119,28 @@ proc `$`*(w: WideCString, estimate: int): string = var i = 0 while w[i].int16 != 0'i16: - var ch = w[i].int + var ch = uint32(cast[uint16](w[i])) inc i - if ch >=% UNI_SUR_HIGH_START and ch <=% UNI_SUR_HIGH_END: + if ch >= uint32(UNI_SUR_HIGH_START) and ch <= uint32(UNI_SUR_HIGH_END): # If the 16 bits following the high surrogate are in the source buffer... - let ch2 = w[i].int - # If it's a low surrogate, convert to UTF32: - if ch2 >=% UNI_SUR_LOW_START and ch2 <=% UNI_SUR_LOW_END: - ch = ((ch -% UNI_SUR_HIGH_START) shr halfShift) +% - (ch2 -% UNI_SUR_LOW_START) +% halfBase - inc i - - if ch <=% 127: + let ch2 = uint32(cast[uint16](w[i])) + ch = (ch shl halfShift) + ch2 + halfBase + inc i + + if ch < 0x80'u32: result.add chr(ch) - elif ch <=% 0x07FF: - result.add chr((ch shr 6) or 0b110_00000) - result.add chr((ch and ones(6)) or 0b10_000000) - elif ch <=% 0xFFFF: - result.add chr(ch shr 12 or 0b1110_0000) - result.add chr(ch shr 6 and ones(6) or 0b10_0000_00) - result.add chr(ch and ones(6) or 0b10_0000_00) - elif ch <=% 0x0010FFFF: - result.add chr(ch shr 18 or 0b1111_0000) - result.add chr(ch shr 12 and ones(6) or 0b10_0000_00) - result.add chr(ch shr 6 and ones(6) or 0b10_0000_00) - result.add chr(ch and ones(6) or 0b10_0000_00) + elif ch < 0x800'u32: + result.add chr((ch shr 6) or 0xc0) + result.add chr((ch and 0x3f) or 0x80) + elif ch < 0x10000'u32: + result.add chr((ch shr 12) or 0xe0) + result.add chr(((ch shr 6) and 0x3f) or 0x80) + result.add chr((ch and 0x3f) or 0x80) else: - # replacement char: - result.add chr(0xFFFD shr 12 or 0b1110_0000) - result.add chr(0xFFFD shr 6 and ones(6) or 0b10_0000_00) - result.add chr(0xFFFD and ones(6) or 0b10_0000_00) + result.add chr((ch shr 18) or 0xf0) + result.add chr(((ch shr 12) and 0x3f) or 0x80) + result.add chr(((ch shr 6) and 0x3f) or 0x80) + result.add chr((ch and 0x3f) or 0x80) proc `$`*(s: WideCString): string = result = s $ 80 From c103eddc737a48d3de04e64c2086549b7ec33d6d Mon Sep 17 00:00:00 2001 From: jangko Date: Thu, 20 Aug 2015 20:30:14 +0700 Subject: [PATCH 0844/1263] fixed UTF-16 to UTF-8 conversion in widestrs.nim the source of problem for issue #3228 also add test for entire range of valid UTF-16 --- lib/system/widestrs.nim | 14 +++---- tests/stdlib/twchartoutf8.nim | 78 +++++++++++++++++++++++++++++++++++ 2 files changed, 85 insertions(+), 7 deletions(-) create mode 100644 tests/stdlib/twchartoutf8.nim diff --git a/lib/system/widestrs.nim b/lib/system/widestrs.nim index e782e2452..94ae3e26b 100644 --- a/lib/system/widestrs.nim +++ b/lib/system/widestrs.nim @@ -119,20 +119,20 @@ proc `$`*(w: WideCString, estimate: int): string = var i = 0 while w[i].int16 != 0'i16: - var ch = uint32(cast[uint16](w[i])) + var ch = int(cast[uint16](w[i])) inc i - if ch >= uint32(UNI_SUR_HIGH_START) and ch <= uint32(UNI_SUR_HIGH_END): + if ch >= UNI_SUR_HIGH_START and ch <= UNI_SUR_HIGH_END: # If the 16 bits following the high surrogate are in the source buffer... - let ch2 = uint32(cast[uint16](w[i])) - ch = (ch shl halfShift) + ch2 + halfBase + let ch2 = int(cast[uint16](w[i])) + ch = (((ch and halfMask) shl halfShift) + (ch2 and halfMask)) + halfBase inc i - if ch < 0x80'u32: + if ch < 0x80: result.add chr(ch) - elif ch < 0x800'u32: + elif ch < 0x800: result.add chr((ch shr 6) or 0xc0) result.add chr((ch and 0x3f) or 0x80) - elif ch < 0x10000'u32: + elif ch < 0x10000: result.add chr((ch shr 12) or 0xe0) result.add chr(((ch shr 6) and 0x3f) or 0x80) result.add chr((ch and 0x3f) or 0x80) diff --git a/tests/stdlib/twchartoutf8.nim b/tests/stdlib/twchartoutf8.nim new file mode 100644 index 000000000..806a222b6 --- /dev/null +++ b/tests/stdlib/twchartoutf8.nim @@ -0,0 +1,78 @@ +#assume WideCharToMultiByte always produce correct result +#windows only + +when not defined(windows): + {.error: "windows only".} + +{.push gcsafe.} + +const CP_UTF8 = 65001'i32 + +type + LPBOOL = ptr int32 + LPWCSTR = ptr uint16 + +proc WideCharToMultiByte*(CodePage: int32, dwFlags: int32, + lpWideCharStr: LPWCSTR, cchWideChar: int32, + lpMultiByteStr: cstring, cchMultiByte: int32, + lpDefaultChar: cstring, lpUsedDefaultChar: LPBOOL): int32{. + stdcall, dynlib: "kernel32", importc: "WideCharToMultiByte".} + +{.pop.} + +proc convertToUTF8(wc: WideCString, wclen: int32): string = + let size = WideCharToMultiByte(CP_UTF8, 0'i32, cast[LPWCSTR](addr(wc[0])), wclen, + cstring(nil), 0'i32, cstring(nil), LPBOOL(nil)) + result = newString(size) + let res = WideCharToMultiByte(CP_UTF8, 0'i32, cast[LPWCSTR](addr(wc[0])), wclen, + cstring(result), size, cstring(nil), LPBOOL(nil)) + result[size] = chr(0) + assert size == res + +proc testCP(wc: WideCString, lo, hi: int) = + var x = 0 + let chunk = 1024 + for i in lo..hi: + wc[x] = cast[TUtf16Char](i) + if (x >= chunk) or (i >= hi): + wc[x] = TUtf16Char(0) + var a = convertToUTF8(wc, int32(x)) + var b = wc $ chunk + assert a == b + x = 0 + inc x + +proc testCP2(wc: WideCString, lo, hi: int) = + assert ((lo >=0x10000) and (hi <= 0x10FFFF)) + var x = 0 + let chunk = 1024 + for i in lo..hi: + let ch = i - 0x10000 + let W1 = 0xD800 or (ch shr 10) + let W2 = 0xDC00 or (0x3FF and ch) + wc[x] = cast[TUtf16Char](W1) + wc[x+1] = cast[TUtf16Char](W2) + inc(x, 2) + + if (x >= chunk) or (i >= hi): + wc[x] = TUtf16Char(0) + var a = convertToUTF8(wc, int32(x)) + var b = wc $ chunk + assert a == b + x = 0 + +#RFC-2781 "UTF-16, an encoding of ISO 10646" + +var wc: WideCString +unsafeNew(wc, 1024 * 4 + 2) + +#U+0000 to U+D7FF +#skip the U+0000 +wc.testCP(1, 0xD7FF) + +#U+E000 to U+FFFF +wc.testCP(0xE000, 0xFFFF) + +#U+10000 to U+10FFFF +wc.testCP2(0x10000, 0x10FFFF) +echo "OK" \ No newline at end of file From a2bb7d4c71e0804dd57c8e4d7ba16cf61ab184f1 Mon Sep 17 00:00:00 2001 From: Araq Date: Fri, 21 Aug 2015 01:34:46 +0200 Subject: [PATCH 0845/1263] simplify nimscript.nim --- compiler/main.nim | 2 +- lib/system/nimscript.nim | 25 +++++-------------------- todo.txt | 8 ++++---- 3 files changed, 10 insertions(+), 25 deletions(-) diff --git a/compiler/main.nim b/compiler/main.nim index baf1c5208..7c043eb72 100644 --- a/compiler/main.nim +++ b/compiler/main.nim @@ -355,7 +355,7 @@ proc mainCommand* = gGlobalOptions.incl(optCaasEnabled) msgs.gErrorMax = high(int) # do not stop after first error serve(mainCommand) - of "nop": discard + of "nop", "help": discard else: rawMessage(errInvalidCommandX, command) diff --git a/lib/system/nimscript.nim b/lib/system/nimscript.nim index 013b2cbc0..c714f88ee 100644 --- a/lib/system/nimscript.nim +++ b/lib/system/nimscript.nim @@ -144,28 +144,13 @@ template task*(name: untyped; description: string; body: untyped): untyped = proc `name Task`() = body let cmd = getCommand() - if cmd.len == 0 or cmd ==? "help" or cmd == "nop": - setCommand "nop" + if cmd.len == 0 or cmd ==? "help": + setCommand "help" writeTask(astToStr(name), description) elif cmd ==? astToStr(name): setCommand "nop" `name Task`() -type - VersionReq* = distinct string ## Describes a version requirement. - -template v*(name: string{lit}): VersionReq = VersionReq(name) -template special*(name: string): VersionReq = VersionReq(name) -template `<`*(v: VersionReq): VersionReq = VersionReq("<" & string(v)) -template `<=`*(v: VersionReq): VersionReq = VersionReq("<=" & string(v)) -template `>`*(v: VersionReq): VersionReq = VersionReq(">" & string(v)) -template `>=`*(v: VersionReq): VersionReq = VersionReq(">=" & string(v)) -template `&`*(a, b: VersionReq): VersionReq = - VersionReq(string(a) & " & " & string(b)) - -const - anyVersion* = VersionReq("*") - var packageName* = "" version*, author*, description*, license*, srcdir*, @@ -173,7 +158,7 @@ var skipDirs*, skipFiles*, skipExt*, installDirs*, installFiles*, installExt*, bin*: seq[string] - requiresData*: seq[(string, VersionReq)] + requiresData*: seq[string] -proc requires*(name: string; v: VersionReq) = - requiresData.add((name, v)) +proc requires*(deps: varargs[string]) = + for d in deps: requiresData.add(d) diff --git a/todo.txt b/todo.txt index ee30894da..3089dfbbe 100644 --- a/todo.txt +++ b/todo.txt @@ -15,10 +15,6 @@ version 0.11.4 - add "all threads are blocked" detection to 'spawn' - Deprecate ``immediate`` for templates and macros -- make 'nil' work for 'add': - - resizeString - - incrSeq - - addChar version 1.0 @@ -36,6 +32,10 @@ version 1.0 - split docgen into separate tool - special rule for ``[]=``, items, pairs - BUG: echo with template `$`*(info: TLineInfo): expr = toFileLineCol(info) +- make 'nil' work for 'add': + - resizeString + - incrSeq + - addChar Concurrency From 695e2e970e5ee560d324d6775c202f9b808f97fa Mon Sep 17 00:00:00 2001 From: Araq Date: Fri, 21 Aug 2015 02:34:34 +0200 Subject: [PATCH 0846/1263] implemented macros.getImpl --- compiler/ast.nim | 2 +- compiler/vm.nim | 8 ++++++++ compiler/vmdef.nim | 1 + compiler/vmgen.nim | 1 + lib/core/macros.nim | 4 ++++ tests/macros/tgetimpl.nim | 20 ++++++++++++++++++++ todo.txt | 1 - web/news.txt | 4 ++++ 8 files changed, 39 insertions(+), 2 deletions(-) create mode 100644 tests/macros/tgetimpl.nim diff --git a/compiler/ast.nim b/compiler/ast.nim index 3a4158204..a0a5d204a 100644 --- a/compiler/ast.nim +++ b/compiler/ast.nim @@ -602,7 +602,7 @@ type mNSetFloatVal, mNSetSymbol, mNSetIdent, mNSetType, mNSetStrVal, mNLineInfo, mNNewNimNode, mNCopyNimNode, mNCopyNimTree, mStrToIdent, mIdentToStr, mNBindSym, mLocals, mNCallSite, - mEqIdent, mEqNimrodNode, mSameNodeType, + mEqIdent, mEqNimrodNode, mSameNodeType, mGetImpl, mNHint, mNWarning, mNError, mInstantiationInfo, mGetTypeInfo, mNGenSym diff --git a/compiler/vm.nim b/compiler/vm.nim index b15c55565..b7b09f4a3 100644 --- a/compiler/vm.nim +++ b/compiler/vm.nim @@ -781,6 +781,14 @@ proc rawExecute(c: PCtx, start: int, tos: PStackFrame): TFullReg = regs[ra].node.add(copyTree(regs[rb].regToNode)) else: stackTrace(c, tos, pc, errNilAccess) + of opcGetImpl: + decodeB(rkNode) + let a = regs[rb].node + if a.kind == nkSym: + regs[ra].node = if a.sym.ast.isNil: newNode(nkNilLit) + else: copyTree(a.sym.ast) + else: + stackTrace(c, tos, pc, errFieldXNotFound, "symbol") of opcEcho: let rb = instr.regB if rb == 1: diff --git a/compiler/vmdef.nim b/compiler/vmdef.nim index 6900b17c2..337e4ec8f 100644 --- a/compiler/vmdef.nim +++ b/compiler/vmdef.nim @@ -102,6 +102,7 @@ type opcEqIdent, opcStrToIdent, opcIdentToStr, + opcGetImpl, opcEcho, opcIndCall, # dest = call regStart, n; where regStart = fn, arg1, ... diff --git a/compiler/vmgen.nim b/compiler/vmgen.nim index 919c38e08..237a44e18 100644 --- a/compiler/vmgen.nim +++ b/compiler/vmgen.nim @@ -948,6 +948,7 @@ proc genMagic(c: PCtx; n: PNode; dest: var TDest; m: TMagic) = of mSlurp: genUnaryABC(c, n, dest, opcSlurp) of mStaticExec: genBinaryABCD(c, n, dest, opcGorge) of mNLen: genUnaryABI(c, n, dest, opcLenSeq) + of mGetImpl: genUnaryABC(c, n, dest, opcGetImpl) of mNChild: genBinaryABC(c, n, dest, opcNChild) of mNSetChild, mNDel: unused(n, dest) diff --git a/lib/core/macros.nim b/lib/core/macros.nim index d371a92cf..2058229a1 100644 --- a/lib/core/macros.nim +++ b/lib/core/macros.nim @@ -213,6 +213,10 @@ proc newNimNode*(kind: NimNodeKind, proc copyNimNode*(n: NimNode): NimNode {.magic: "NCopyNimNode", noSideEffect.} proc copyNimTree*(n: NimNode): NimNode {.magic: "NCopyNimTree", noSideEffect.} +proc getImpl*(s: NimSym): NimNode {.magic: "GetImpl", noSideEffect.} + ## retrieve the implementation of a symbol `s`. `s` can be a routine or a + ## const. + proc error*(msg: string) {.magic: "NError", benign.} ## writes an error message at compile time diff --git a/tests/macros/tgetimpl.nim b/tests/macros/tgetimpl.nim new file mode 100644 index 000000000..d38492934 --- /dev/null +++ b/tests/macros/tgetimpl.nim @@ -0,0 +1,20 @@ +discard """ + msg: '''"muhaha" +proc poo(x, y: int) = + echo ["poo"]''' +""" + +import macros + +const + foo = "muhaha" + +proc poo(x, y: int) = + echo "poo" + +macro m(x: typed): untyped = + echo repr x.symbol.getImpl + result = x + +discard m foo +discard m poo diff --git a/todo.txt b/todo.txt index 3089dfbbe..37e82e230 100644 --- a/todo.txt +++ b/todo.txt @@ -2,7 +2,6 @@ version 0.11.4 ============== - make tuple unpacking work in a non-var/let context -- built-in 'getImpl' - document special cased varargs[untyped] and varargs[typed] diff --git a/web/news.txt b/web/news.txt index c93bb821f..fce77a0bf 100644 --- a/web/news.txt +++ b/web/news.txt @@ -61,6 +61,7 @@ News - The ``expandSymlink`` proc has been added to the ``os`` module. - The ``tailDir`` proc has been added to the ``os`` module. + Language Additions ------------------ @@ -68,6 +69,9 @@ News variable or parameter for C interoperability. Since technically this makes parameters and ``let`` variables mutable, it is considered even more unsafe than the ordinary ``addr`` builtin. + - Added ``macros.getImpl`` that can be used to access the implementation of + a routine or a constant. This allows for example for user-defined inlining + of function calls. Bugfixes From 7c757599f1c9157a65e8e2238d4b11eedeeb01bf Mon Sep 17 00:00:00 2001 From: jangko Date: Fri, 21 Aug 2015 10:43:31 +0700 Subject: [PATCH 0847/1263] fixed UTF-16 to UTF-8 conversion in widestrs.nim the source of problem for issue #3228 also add test for entire range of valid UTF-16 and test for invalid UTF-16 sequence --- lib/system/widestrs.nim | 26 +++++++++++++++++----- tests/stdlib/twchartoutf8.nim | 42 +++++++++++++++++++++++++++++------ 2 files changed, 55 insertions(+), 13 deletions(-) diff --git a/lib/system/widestrs.nim b/lib/system/widestrs.nim index 94ae3e26b..77310b289 100644 --- a/lib/system/widestrs.nim +++ b/lib/system/widestrs.nim @@ -114,7 +114,7 @@ proc newWideCString*(s: cstring): WideCString = proc newWideCString*(s: string): WideCString = result = newWideCString(s, s.len) -proc `$`*(w: WideCString, estimate: int): string = +proc `$`*(w: WideCString, estimate: int, replacement: int = 0xFFFD): string = result = newStringOfCap(estimate + estimate shr 2) var i = 0 @@ -124,9 +124,18 @@ proc `$`*(w: WideCString, estimate: int): string = if ch >= UNI_SUR_HIGH_START and ch <= UNI_SUR_HIGH_END: # If the 16 bits following the high surrogate are in the source buffer... let ch2 = int(cast[uint16](w[i])) - ch = (((ch and halfMask) shl halfShift) + (ch2 and halfMask)) + halfBase - inc i - + + # If it's a low surrogate, convert to UTF32: + if ch2 >= UNI_SUR_LOW_START and ch2 <= UNI_SUR_LOW_END: + ch = (((ch and halfMask) shl halfShift) + (ch2 and halfMask)) + halfBase + inc i + else: + #invalid UTF-16 + ch = replacement + elif ch >= UNI_SUR_LOW_START and ch <= UNI_SUR_LOW_END: + #invalid UTF-16 + ch = replacement + if ch < 0x80: result.add chr(ch) elif ch < 0x800: @@ -136,11 +145,16 @@ proc `$`*(w: WideCString, estimate: int): string = result.add chr((ch shr 12) or 0xe0) result.add chr(((ch shr 6) and 0x3f) or 0x80) result.add chr((ch and 0x3f) or 0x80) - else: + elif ch <= 0x10FFFF: result.add chr((ch shr 18) or 0xf0) result.add chr(((ch shr 12) and 0x3f) or 0x80) result.add chr(((ch shr 6) and 0x3f) or 0x80) result.add chr((ch and 0x3f) or 0x80) - + else: + # replacement char(in case user give very large number): + result.add chr(0xFFFD shr 12 or 0b1110_0000) + result.add chr(0xFFFD shr 6 and ones(6) or 0b10_0000_00) + result.add chr(0xFFFD and ones(6) or 0b10_0000_00) + proc `$`*(s: WideCString): string = result = s $ 80 diff --git a/tests/stdlib/twchartoutf8.nim b/tests/stdlib/twchartoutf8.nim index 806a222b6..9838bbfe7 100644 --- a/tests/stdlib/twchartoutf8.nim +++ b/tests/stdlib/twchartoutf8.nim @@ -33,9 +33,9 @@ proc testCP(wc: WideCString, lo, hi: int) = var x = 0 let chunk = 1024 for i in lo..hi: - wc[x] = cast[TUtf16Char](i) + wc[x] = cast[Utf16Char](i) if (x >= chunk) or (i >= hi): - wc[x] = TUtf16Char(0) + wc[x] = Utf16Char(0) var a = convertToUTF8(wc, int32(x)) var b = wc $ chunk assert a == b @@ -43,26 +43,26 @@ proc testCP(wc: WideCString, lo, hi: int) = inc x proc testCP2(wc: WideCString, lo, hi: int) = - assert ((lo >=0x10000) and (hi <= 0x10FFFF)) + assert((lo >= 0x10000) and (hi <= 0x10FFFF)) var x = 0 let chunk = 1024 for i in lo..hi: let ch = i - 0x10000 let W1 = 0xD800 or (ch shr 10) let W2 = 0xDC00 or (0x3FF and ch) - wc[x] = cast[TUtf16Char](W1) - wc[x+1] = cast[TUtf16Char](W2) + wc[x] = cast[Utf16Char](W1) + wc[x+1] = cast[Utf16Char](W2) inc(x, 2) if (x >= chunk) or (i >= hi): - wc[x] = TUtf16Char(0) + wc[x] = Utf16Char(0) var a = convertToUTF8(wc, int32(x)) var b = wc $ chunk assert a == b x = 0 #RFC-2781 "UTF-16, an encoding of ISO 10646" - + var wc: WideCString unsafeNew(wc, 1024 * 4 + 2) @@ -75,4 +75,32 @@ wc.testCP(0xE000, 0xFFFF) #U+10000 to U+10FFFF wc.testCP2(0x10000, 0x10FFFF) + +#invalid UTF-16 +const + b = "\xEF\xBF\xBD" + c = "\xEF\xBF\xBF" + +wc[0] = cast[Utf16Char](0xDC00) +wc[1] = Utf16Char(0) +var a = $wc +assert a == b + +wc[0] = cast[Utf16Char](0xFFFF) +wc[1] = cast[Utf16Char](0xDC00) +wc[2] = Utf16Char(0) +a = $wc +assert a == c & b + +wc[0] = cast[Utf16Char](0xD800) +wc[1] = Utf16Char(0) +a = $wc +assert a == b + +wc[0] = cast[Utf16Char](0xD800) +wc[1] = cast[Utf16Char](0xFFFF) +wc[2] = Utf16Char(0) +a = $wc +assert a == b & c + echo "OK" \ No newline at end of file From 0cc662d8b854335bc31d7739ed41dd222c0cfca8 Mon Sep 17 00:00:00 2001 From: Araq Date: Fri, 21 Aug 2015 12:18:04 +0200 Subject: [PATCH 0848/1263] fixes bootstrapping --- lib/core/macros.nim | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/core/macros.nim b/lib/core/macros.nim index 2058229a1..552c0dbff 100644 --- a/lib/core/macros.nim +++ b/lib/core/macros.nim @@ -213,9 +213,10 @@ proc newNimNode*(kind: NimNodeKind, proc copyNimNode*(n: NimNode): NimNode {.magic: "NCopyNimNode", noSideEffect.} proc copyNimTree*(n: NimNode): NimNode {.magic: "NCopyNimTree", noSideEffect.} -proc getImpl*(s: NimSym): NimNode {.magic: "GetImpl", noSideEffect.} +proc getImpl*(s: NimSym): NimNode {.magic: "GetImpl", noSideEffect.} = ## retrieve the implementation of a symbol `s`. `s` can be a routine or a ## const. + discard proc error*(msg: string) {.magic: "NError", benign.} ## writes an error message at compile time From a5be556a4cd58371f21cab6bffc8b333a9aa5c51 Mon Sep 17 00:00:00 2001 From: Yuriy Glukhov Date: Fri, 21 Aug 2015 13:29:25 +0300 Subject: [PATCH 0849/1263] Untyped pointers godegen changed. addr expression fixed. --- compiler/jsgen.nim | 2 +- compiler/semmagic.nim | 2 ++ lib/system/jssys.nim | 19 ++++++++++--------- tests/js/taddr.nim | 8 ++++++++ 4 files changed, 21 insertions(+), 10 deletions(-) diff --git a/compiler/jsgen.nim b/compiler/jsgen.nim index 89a1b84a2..774f6501a 100644 --- a/compiler/jsgen.nim +++ b/compiler/jsgen.nim @@ -136,7 +136,7 @@ proc mapType(typ: PType): TJSTypeKind = result = etyBaseIndex of tyPointer: # treat a tyPointer like a typed pointer to an array of bytes - result = etyInt + result = etyBaseIndex of tyRange, tyDistinct, tyOrdinal, tyConst, tyMutable, tyIter, tyProxy: result = mapType(t.sons[0]) of tyInt..tyInt64, tyUInt..tyUInt64, tyEnum, tyChar: result = etyInt diff --git a/compiler/semmagic.nim b/compiler/semmagic.nim index 0afbf1f07..5d16470b0 100644 --- a/compiler/semmagic.nim +++ b/compiler/semmagic.nim @@ -13,6 +13,8 @@ proc semAddr(c: PContext; n: PNode; isUnsafeAddr=false): PNode = result = newNodeI(nkAddr, n.info) let x = semExprWithType(c, n) + if x.kind == nkSym: + x.sym.flags.incl(sfAddrTaken) if isAssignable(c, x, isUnsafeAddr) notin {arLValue, arLocalLValue}: localError(n.info, errExprHasNoAddress) result.add x diff --git a/lib/system/jssys.nim b/lib/system/jssys.nim index 242f42c16..a6839c48e 100644 --- a/lib/system/jssys.nim +++ b/lib/system/jssys.nim @@ -532,15 +532,17 @@ proc nimMax(a, b: int): int {.compilerproc.} = return if a >= b: a else: b type NimString = string # hack for hti.nim include "system/hti" +type JSRef = int # Fake type. + proc isFatPointer(ti: PNimType): bool = # This has to be consistent with the code generator! return ti.base.kind notin {tyObject, tyArray, tyArrayConstr, tyTuple, tyOpenArray, tySet, tyVar, tyRef, tyPtr} -proc nimCopy(dest, src: pointer, ti: PNimType): pointer {.compilerproc.} +proc nimCopy(dest, src: JSRef, ti: PNimType): JSRef {.compilerproc.} -proc nimCopyAux(dest, src: pointer, n: ptr TNimNode) {.compilerproc.} = +proc nimCopyAux(dest, src: JSRef, n: ptr TNimNode) {.compilerproc.} = case n.kind of nkNone: sysAssert(false, "nimCopyAux") of nkSlot: @@ -562,7 +564,7 @@ proc nimCopyAux(dest, src: pointer, n: ptr TNimNode) {.compilerproc.} = } """ -proc nimCopy(dest, src: pointer, ti: PNimType): pointer = +proc nimCopy(dest, src: JSRef, ti: PNimType): JSRef = case ti.kind of tyPtr, tyRef, tyVar, tyNil: if not isFatPointer(ti): @@ -603,12 +605,11 @@ proc nimCopy(dest, src: pointer, ti: PNimType): pointer = else: result = src -proc genericReset(x: pointer, ti: PNimType): pointer {.compilerproc.} = +proc genericReset(x: JSRef, ti: PNimType): JSRef {.compilerproc.} = + asm "`result` = null;" case ti.kind of tyPtr, tyRef, tyVar, tyNil: - if not isFatPointer(ti): - result = nil - else: + if isFatPointer(ti): asm """ `result` = [null, 0]; """ @@ -633,9 +634,9 @@ proc genericReset(x: pointer, ti: PNimType): pointer {.compilerproc.} = } """ else: - result = nil + discard -proc arrayConstr(len: int, value: pointer, typ: PNimType): pointer {. +proc arrayConstr(len: int, value: JSRef, typ: PNimType): JSRef {. asmNoStackFrame, compilerproc.} = # types are fake asm """ diff --git a/tests/js/taddr.nim b/tests/js/taddr.nim index e5c8d0881..1fba30d55 100644 --- a/tests/js/taddr.nim +++ b/tests/js/taddr.nim @@ -62,3 +62,11 @@ var t : tuple[a, b: int] var pt = addr t[1] pt[] = 123 doAssert(t.b == 123) + +#block: # Test "untyped" pointer. +proc testPtr(p: pointer, a: int) = + doAssert(a == 5) + (cast[ptr int](p))[] = 124 +var i = 123 +testPtr(addr i, 5) +doAssert(i == 124) From dadf036a702f29f9fdedcb1bf406b9ef85e52e31 Mon Sep 17 00:00:00 2001 From: Yuriy Glukhov Date: Fri, 21 Aug 2015 21:31:00 +0300 Subject: [PATCH 0850/1263] Fixed nimParseBiggestFloat magic in JS --- compiler/jsgen.nim | 3 +++ 1 file changed, 3 insertions(+) diff --git a/compiler/jsgen.nim b/compiler/jsgen.nim index 89a1b84a2..c608ea727 100644 --- a/compiler/jsgen.nim +++ b/compiler/jsgen.nim @@ -1398,6 +1398,9 @@ proc genMagic(p: PProc, n: PNode, r: var TCompRes) = of mDotDot: genProcForSymIfNeeded(p, n.sons[0].sym) genCall(p, n, r) + of mParseBiggestFloat: + useMagic(p, "nimParseBiggestFloat") + genCall(p, n, r) else: genCall(p, n, r) #else internalError(e.info, 'genMagic: ' + magicToStr[op]); From 6da8c7857e41cc21dd3a0685417ac7e2f0465561 Mon Sep 17 00:00:00 2001 From: Peter Mora Date: Fri, 21 Aug 2015 21:15:08 +0200 Subject: [PATCH 0851/1263] extending metatype matching in sigmatch.nim --- compiler/sigmatch.nim | 65 +++++++++++++++++++++++++++++--- tests/metatype/tprocbothmeta.nim | 10 +++++ 2 files changed, 70 insertions(+), 5 deletions(-) create mode 100644 tests/metatype/tprocbothmeta.nim diff --git a/compiler/sigmatch.nim b/compiler/sigmatch.nim index ef1c01b7a..357c6cf32 100644 --- a/compiler/sigmatch.nim +++ b/compiler/sigmatch.nim @@ -58,6 +58,10 @@ type isSubtype, isSubrange, # subrange of the wanted type; no type conversion # but apart from that counts as ``isSubtype`` + isBothMetaConvertible # generic proc parameter was matched against + # generic type, e.g., map(mySeq, x=>x+1), + # maybe recoverable by rerun if the parameter is + # the proc's return value isInferred, # generic proc was matched against a concrete type isInferredConvertible, # same as above, but requiring proc CC conversion isGeneric, @@ -389,8 +393,29 @@ proc inconsistentVarTypes(f, a: PType): bool {.inline.} = result = f.kind != a.kind and (f.kind == tyVar or a.kind == tyVar) proc procParamTypeRel(c: var TCandidate, f, a: PType): TTypeRelation = - var f = f + ## For example we have: + ## .. code-block:: nim + ## proc myMap[T,S](sIn: seq[T], f: proc(x: T): S): seq[S] = ... + ## proc innerProc[Q,W](q: Q): W = ... + ## And we want to match: myMap(@[1,2,3], innerProc) + ## This proc (procParamTypeRel) will do the following steps in + ## three different calls: + ## - matches f=T to a=Q. Since f is metatype, we resolve it + ## to int (which is already known at this point). So in this case + ## Q=int mapping will be saved to c.bindings. + ## - matches f=S to a=W. Both of these metatypes are unknown, so we + ## return with isBothMetaConvertible to ask for rerun. + ## - matches f=S to a=W. At this point the return type of innerProc + ## is known (we get it from c.bindings). We can use that value + ## to match with f, and save back to c.bindings. + var + f = f + a = a + if a.isMetaType: + let aResolved = PType(idTableGet(c.bindings, a)) + if aResolved != nil: + a = aResolved if a.isMetaType: if f.isMetaType: # We are matching a generic proc (as proc param) @@ -401,12 +426,15 @@ proc procParamTypeRel(c: var TCandidate, f, a: PType): TTypeRelation = f = generateTypeInstance(c.c, c.bindings, c.call.info, f) if f == nil or f.isMetaType: # no luck resolving the type, so the inference fails - return isNone + return isBothMetaConvertible + # Note that this typeRel call will save a's resolved type into c.bindings let reverseRel = typeRel(c, a, f) if reverseRel >= isGeneric: result = isInferred #inc c.genericMatches else: + # Note that this typeRel call will save f's resolved type into c.bindings + # if f is metatype. result = typeRel(c, f, a) if result <= isSubtype or inconsistentVarTypes(f, a): @@ -450,8 +478,9 @@ proc procTypeRel(c: var TCandidate, f, a: PType): TTypeRelation = elif f.callConv != a.callConv: # valid to pass a 'nimcall' thingie to 'closure': if f.callConv == ccClosure and a.callConv == ccDefault: - result = if result != isInferred: isConvertible - else: isInferredConvertible + result = if result == isInferred: isInferredConvertible + elif result == isBothMetaConvertible: isBothMetaConvertible + else: isConvertible else: return isNone when useEffectSystem: @@ -1225,7 +1254,7 @@ proc incMatches(m: var TCandidate; r: TTypeRelation; convMatch = 1) = case r of isConvertible, isIntConv: inc(m.convMatches, convMatch) of isSubtype, isSubrange: inc(m.subtypeMatches) - of isGeneric, isInferred: inc(m.genericMatches) + of isGeneric, isInferred, isBothMetaConvertible: inc(m.genericMatches) of isFromIntLit: inc(m.intConvMatches, 256) of isInferredConvertible: inc(m.convMatches) @@ -1291,6 +1320,29 @@ proc paramTypesMatchAux(m: var TCandidate, f, argType: PType, put(m.bindings, f, inlined) return argSemantized + # If r == isBothMetaConvertible then we rerun typeRel. + # bothMetaCounter is for safety to avoid any infinite loop, + # I don't have any example when it is needed. + # lastBindingsLenth is used to check whether m.bindings remains the same, + # because in that case there is no point in continuing. + var bothMetaCounter = 0 + var lastBindingsLength = -1 + while r == isBothMetaConvertible and + lastBindingsLength != m.bindings.counter and + bothMetaCounter < 100: + lastBindingsLength = m.bindings.counter + inc(bothMetaCounter) + if arg.kind in {nkProcDef, nkIteratorDef} + nkLambdaKinds: + result = c.semInferredLambda(c, m.bindings, arg) + elif arg.kind != nkSym: + return nil + else: + let inferred = c.semGenerateInstance(c, arg.sym, m.bindings, arg.info) + result = newSymNode(inferred, arg.info) + inc(m.convMatches) + arg = result + r = typeRel(m, f, arg.typ) + case r of isConvertible: inc(m.convMatches) @@ -1336,6 +1388,9 @@ proc paramTypesMatchAux(m: var TCandidate, f, argType: PType, result.typ = getInstantiatedType(c, arg, m, f) else: result = arg + of isBothMetaConvertible: + # This is the result for the 101th time. + result = nil of isFromIntLit: # too lazy to introduce another ``*matches`` field, so we conflate # ``isIntConv`` and ``isIntLit`` here: diff --git a/tests/metatype/tprocbothmeta.nim b/tests/metatype/tprocbothmeta.nim new file mode 100644 index 000000000..ad12c5d26 --- /dev/null +++ b/tests/metatype/tprocbothmeta.nim @@ -0,0 +1,10 @@ + +proc myFun[A,B](x: A): B = + result = float(x+10) + +proc myMap[T,S](sIn: seq[T], f: proc (q: T): S): seq[S] = + result = newSeq[S](sIn.len) + for i in 0.. Date: Fri, 21 Aug 2015 12:31:55 +0200 Subject: [PATCH 0852/1263] tuple unpacking works in a non-var/let context --- compiler/lowerings.nim | 26 ++++++++++++++++++++++++++ compiler/semexprs.nim | 8 ++++++++ tests/tuples/tunpack_asgn.nim | 32 ++++++++++++++++++++++++++++++++ todo.txt | 2 -- web/news.txt | 3 +++ 5 files changed, 69 insertions(+), 2 deletions(-) create mode 100644 tests/tuples/tunpack_asgn.nim diff --git a/compiler/lowerings.nim b/compiler/lowerings.nim index 647ea59d6..20800b809 100644 --- a/compiler/lowerings.nim +++ b/compiler/lowerings.nim @@ -63,6 +63,32 @@ proc lowerTupleUnpacking*(n: PNode; owner: PSym): PNode = if n.sons[i].kind == nkSym: v.addVar(n.sons[i]) result.add newAsgnStmt(n.sons[i], newTupleAccess(tempAsNode, i)) +proc newTupleAccessRaw*(tup: PNode, i: int): PNode = + result = newNodeI(nkBracketExpr, tup.info) + addSon(result, copyTree(tup)) + var lit = newNodeI(nkIntLit, tup.info) + lit.intVal = i + addSon(result, lit) + +proc lowerTupleUnpackingForAsgn*(n: PNode; owner: PSym): PNode = + let value = n.lastSon + result = newNodeI(nkStmtList, n.info) + + var temp = newSym(skTemp, getIdent(genPrefix), owner, value.info) + var v = newNodeI(nkLetSection, value.info) + let tempAsNode = newIdentNode(getIdent(genPrefix & $temp.id), value.info) + + var vpart = newNodeI(nkIdentDefs, tempAsNode.info, 3) + vpart.sons[0] = tempAsNode + vpart.sons[1] = ast.emptyNode + vpart.sons[2] = value + addSon(v, vpart) + result.add(v) + + let lhs = n.sons[0] + for i in 0 .. lhs.len-1: + result.add newAsgnStmt(lhs.sons[i], newTupleAccessRaw(tempAsNode, i)) + proc lowerSwap*(n: PNode; owner: PSym): PNode = result = newNodeI(nkStmtList, n.info) # note: cannot use 'skTemp' here cause we really need the copy for the VM :-( diff --git a/compiler/semexprs.nim b/compiler/semexprs.nim index bb3ec9df0..d6f6e3a2c 100644 --- a/compiler/semexprs.nim +++ b/compiler/semexprs.nim @@ -1282,6 +1282,14 @@ proc semAsgn(c: PContext, n: PNode): PNode = result = buildOverloadedSubscripts(n.sons[0], getIdent"{}=") add(result, n[1]) return semExprNoType(c, result) + of nkPar: + if a.len >= 2: + # unfortunately we need to rewrite ``(x, y) = foo()`` already here so + # that overloading of the assignment operator still works. Usually we + # prefer to do these rewritings in transf.nim: + return semStmt(c, lowerTupleUnpackingForAsgn(n, c.p.owner)) + else: + a = semExprWithType(c, a, {efLValue}) else: a = semExprWithType(c, a, {efLValue}) n.sons[0] = a diff --git a/tests/tuples/tunpack_asgn.nim b/tests/tuples/tunpack_asgn.nim new file mode 100644 index 000000000..a48fcff5d --- /dev/null +++ b/tests/tuples/tunpack_asgn.nim @@ -0,0 +1,32 @@ +discard """ + output: '''2 4 +4 +2 0''' +""" + +proc foobar(): (int, int) = (2, 4) + +# test within a proc: +proc pp(x: var int) = + var y: int + (y, x) = foobar() + +template pt(x) = + var y: int + (x, y) = foobar() + +# test within a generic: +proc pg[T](x, y: var T) = + pt(x) + +# test as a top level statement: +var x, y, a, b: int +(x, y) = fooBar() + +echo x, " ", y + +pp(a) +echo a + +pg(a, b) +echo a, " ", b diff --git a/todo.txt b/todo.txt index 37e82e230..8962e3ca0 100644 --- a/todo.txt +++ b/todo.txt @@ -1,8 +1,6 @@ version 0.11.4 ============== -- make tuple unpacking work in a non-var/let context - - document special cased varargs[untyped] and varargs[typed] - The remaining bugs of the lambda lifting pass that is responsible to enable diff --git a/web/news.txt b/web/news.txt index fce77a0bf..46867ac4c 100644 --- a/web/news.txt +++ b/web/news.txt @@ -72,6 +72,9 @@ News - Added ``macros.getImpl`` that can be used to access the implementation of a routine or a constant. This allows for example for user-defined inlining of function calls. + - Tuple unpacking finally works in a non-var/let context: ``(x, y) == f()`` + is allowed. Note that this doesn't declare ``x`` and ``y`` variables, for + this ``let (x, y) == f()`` still needs to be used. Bugfixes From c56a1f8266bfbaf18e2c0287ad48c7e5cb4b4468 Mon Sep 17 00:00:00 2001 From: Araq Date: Fri, 21 Aug 2015 12:46:30 +0200 Subject: [PATCH 0853/1263] math.nim works with NimScript --- lib/pure/math.nim | 16 +++++++++------- todo.txt | 1 + 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/lib/pure/math.nim b/lib/pure/math.nim index 8d95ea9c0..c1d5c9439 100644 --- a/lib/pure/math.nim +++ b/lib/pure/math.nim @@ -25,7 +25,7 @@ include "system/inclrtl" when defined(Posix) and not defined(haiku): {.passl: "-lm".} -when not defined(js): +when not defined(js) and not defined(nimscript): import times const @@ -152,10 +152,11 @@ proc random*(max: float): float {.benign.} ## number, i.e. a tickcount. This has a 16-bit resolution on windows ## and a 48-bit resolution on other platforms. -proc randomize*() {.benign.} - ## Initializes the random number generator with a "random" - ## number, i.e. a tickcount. Note: Does nothing for the JavaScript target, - ## as JavaScript does not support this. +when not defined(nimscript): + proc randomize*() {.benign.} + ## Initializes the random number generator with a "random" + ## number, i.e. a tickcount. Note: Does nothing for the JavaScript target, + ## as JavaScript does not support this. Nor does it work for NimScript. proc randomize*(seed: int) {.benign.} ## Initializes the random number generator with a specific seed. @@ -271,8 +272,9 @@ when not defined(JS): when not defined(vcc): # the above code for vcc uses `discard` instead # this is either not Windows or is Windows without vcc - proc randomize() = - randomize(cast[int](epochTime())) + when not defined(nimscript): + proc randomize() = + randomize(cast[int](epochTime())) proc randomize(seed: int) = srand(cint(seed)) # rand_s doesn't use srand when declared(srand48): srand48(seed) diff --git a/todo.txt b/todo.txt index 8962e3ca0..82d1f32db 100644 --- a/todo.txt +++ b/todo.txt @@ -1,6 +1,7 @@ version 0.11.4 ============== +- make ``os`` and ``math`` work with NimScript - document special cased varargs[untyped] and varargs[typed] - The remaining bugs of the lambda lifting pass that is responsible to enable From dd2a0ec431c17f165c18b976d01195b93b69b5e8 Mon Sep 17 00:00:00 2001 From: Araq Date: Fri, 21 Aug 2015 21:40:24 +0200 Subject: [PATCH 0854/1263] cleaned up twchartoutf8 test --- tests/stdlib/twchartoutf8.nim | 178 +++++++++++++++++----------------- 1 file changed, 91 insertions(+), 87 deletions(-) diff --git a/tests/stdlib/twchartoutf8.nim b/tests/stdlib/twchartoutf8.nim index 9838bbfe7..b2f68ee32 100644 --- a/tests/stdlib/twchartoutf8.nim +++ b/tests/stdlib/twchartoutf8.nim @@ -1,106 +1,110 @@ +discard """ + output: '''OK''' +""" + #assume WideCharToMultiByte always produce correct result #windows only when not defined(windows): - {.error: "windows only".} - -{.push gcsafe.} + echo "OK" +else: + {.push gcsafe.} -const CP_UTF8 = 65001'i32 + const CP_UTF8 = 65001'i32 -type - LPBOOL = ptr int32 - LPWCSTR = ptr uint16 - -proc WideCharToMultiByte*(CodePage: int32, dwFlags: int32, - lpWideCharStr: LPWCSTR, cchWideChar: int32, - lpMultiByteStr: cstring, cchMultiByte: int32, - lpDefaultChar: cstring, lpUsedDefaultChar: LPBOOL): int32{. - stdcall, dynlib: "kernel32", importc: "WideCharToMultiByte".} + type + LPBOOL = ptr int32 + LPWCSTR = ptr uint16 -{.pop.} + proc WideCharToMultiByte*(CodePage: int32, dwFlags: int32, + lpWideCharStr: LPWCSTR, cchWideChar: int32, + lpMultiByteStr: cstring, cchMultiByte: int32, + lpDefaultChar: cstring, lpUsedDefaultChar: LPBOOL): int32{. + stdcall, dynlib: "kernel32", importc: "WideCharToMultiByte".} -proc convertToUTF8(wc: WideCString, wclen: int32): string = - let size = WideCharToMultiByte(CP_UTF8, 0'i32, cast[LPWCSTR](addr(wc[0])), wclen, - cstring(nil), 0'i32, cstring(nil), LPBOOL(nil)) - result = newString(size) - let res = WideCharToMultiByte(CP_UTF8, 0'i32, cast[LPWCSTR](addr(wc[0])), wclen, - cstring(result), size, cstring(nil), LPBOOL(nil)) - result[size] = chr(0) - assert size == res - -proc testCP(wc: WideCString, lo, hi: int) = - var x = 0 - let chunk = 1024 - for i in lo..hi: - wc[x] = cast[Utf16Char](i) - if (x >= chunk) or (i >= hi): - wc[x] = Utf16Char(0) - var a = convertToUTF8(wc, int32(x)) - var b = wc $ chunk - assert a == b - x = 0 - inc x + {.pop.} -proc testCP2(wc: WideCString, lo, hi: int) = - assert((lo >= 0x10000) and (hi <= 0x10FFFF)) - var x = 0 - let chunk = 1024 - for i in lo..hi: - let ch = i - 0x10000 - let W1 = 0xD800 or (ch shr 10) - let W2 = 0xDC00 or (0x3FF and ch) - wc[x] = cast[Utf16Char](W1) - wc[x+1] = cast[Utf16Char](W2) - inc(x, 2) - - if (x >= chunk) or (i >= hi): - wc[x] = Utf16Char(0) - var a = convertToUTF8(wc, int32(x)) - var b = wc $ chunk - assert a == b - x = 0 + proc convertToUTF8(wc: WideCString, wclen: int32): string = + let size = WideCharToMultiByte(CP_UTF8, 0'i32, cast[LPWCSTR](addr(wc[0])), wclen, + cstring(nil), 0'i32, cstring(nil), LPBOOL(nil)) + result = newString(size) + let res = WideCharToMultiByte(CP_UTF8, 0'i32, cast[LPWCSTR](addr(wc[0])), wclen, + cstring(result), size, cstring(nil), LPBOOL(nil)) + result[size] = chr(0) + doAssert size == res -#RFC-2781 "UTF-16, an encoding of ISO 10646" - -var wc: WideCString -unsafeNew(wc, 1024 * 4 + 2) + proc testCP(wc: WideCString, lo, hi: int) = + var x = 0 + let chunk = 1024 + for i in lo..hi: + wc[x] = cast[Utf16Char](i) + if (x >= chunk) or (i >= hi): + wc[x] = Utf16Char(0) + var a = convertToUTF8(wc, int32(x)) + var b = wc $ chunk + doAssert a == b + x = 0 + inc x -#U+0000 to U+D7FF -#skip the U+0000 -wc.testCP(1, 0xD7FF) + proc testCP2(wc: WideCString, lo, hi: int) = + doAssert((lo >= 0x10000) and (hi <= 0x10FFFF)) + var x = 0 + let chunk = 1024 + for i in lo..hi: + let ch = i - 0x10000 + let W1 = 0xD800 or (ch shr 10) + let W2 = 0xDC00 or (0x3FF and ch) + wc[x] = cast[Utf16Char](W1) + wc[x+1] = cast[Utf16Char](W2) + inc(x, 2) -#U+E000 to U+FFFF -wc.testCP(0xE000, 0xFFFF) + if (x >= chunk) or (i >= hi): + wc[x] = Utf16Char(0) + var a = convertToUTF8(wc, int32(x)) + var b = wc $ chunk + doAssert a == b + x = 0 -#U+10000 to U+10FFFF -wc.testCP2(0x10000, 0x10FFFF) + #RFC-2781 "UTF-16, an encoding of ISO 10646" -#invalid UTF-16 -const - b = "\xEF\xBF\xBD" - c = "\xEF\xBF\xBF" + var wc: WideCString + unsafeNew(wc, 1024 * 4 + 2) -wc[0] = cast[Utf16Char](0xDC00) -wc[1] = Utf16Char(0) -var a = $wc -assert a == b + #U+0000 to U+D7FF + #skip the U+0000 + wc.testCP(1, 0xD7FF) -wc[0] = cast[Utf16Char](0xFFFF) -wc[1] = cast[Utf16Char](0xDC00) -wc[2] = Utf16Char(0) -a = $wc -assert a == c & b + #U+E000 to U+FFFF + wc.testCP(0xE000, 0xFFFF) -wc[0] = cast[Utf16Char](0xD800) -wc[1] = Utf16Char(0) -a = $wc -assert a == b + #U+10000 to U+10FFFF + wc.testCP2(0x10000, 0x10FFFF) -wc[0] = cast[Utf16Char](0xD800) -wc[1] = cast[Utf16Char](0xFFFF) -wc[2] = Utf16Char(0) -a = $wc -assert a == b & c + #invalid UTF-16 + const + b = "\xEF\xBF\xBD" + c = "\xEF\xBF\xBF" -echo "OK" \ No newline at end of file + wc[0] = cast[Utf16Char](0xDC00) + wc[1] = Utf16Char(0) + var a = $wc + doAssert a == b + + wc[0] = cast[Utf16Char](0xFFFF) + wc[1] = cast[Utf16Char](0xDC00) + wc[2] = Utf16Char(0) + a = $wc + doAssert a == c & b + + wc[0] = cast[Utf16Char](0xD800) + wc[1] = Utf16Char(0) + a = $wc + doAssert a == b + + wc[0] = cast[Utf16Char](0xD800) + wc[1] = cast[Utf16Char](0xFFFF) + wc[2] = Utf16Char(0) + a = $wc + doAssert a == b & c + + echo "OK" From dc6c0559e962a0df40be2258bf920827dbe9e304 Mon Sep 17 00:00:00 2001 From: xyz Date: Sat, 22 Aug 2015 10:59:20 -0400 Subject: [PATCH 0855/1263] When reading files, check if the eof flag is set before throwing. --- lib/system.nim | 5 ++++- lib/system/sysio.nim | 23 +++++++++++++++++++---- 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/lib/system.nim b/lib/system.nim index 2a3f72f3b..ee94f85d2 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -2594,7 +2594,10 @@ when not defined(JS): #and not defined(nimscript): ## Closes the file. proc endOfFile*(f: File): bool {.tags: [], benign.} - ## Returns true iff `f` is at the end. + ## Returns true if `f` is at the end. + + proc fileError*(f: File): bool {.tags: [], benign.} + ## Returns true if the error indicator of `f` is set. proc readChar*(f: File): char {. importc: "fgetc", header: "", tags: [ReadIOEffect].} diff --git a/lib/system/sysio.nim b/lib/system/sysio.nim index 58ad8ace0..7918569e1 100644 --- a/lib/system/sysio.nim +++ b/lib/system/sysio.nim @@ -37,6 +37,8 @@ proc fread(buf: pointer, size, n: int, f: File): int {. proc fseek(f: File, offset: clong, whence: int): int {. importc: "fseek", header: "", tags: [].} proc ftell(f: File): int {.importc: "ftell", header: "", tags: [].} +proc ferror(f: File): int {.importc: "ferror", header: "", tags: [].} +proc feof(f: File): int {.importc: "feof", header: "", tags: [].} proc setvbuf(stream: File, buf: pointer, typ, size: cint): cint {. importc, header: "", tags: [].} proc memchr(s: pointer, c: cint, n: csize): pointer {. @@ -147,9 +149,17 @@ proc rawFileSize(file: File): int = proc readAllFile(file: File, len: int): string = # We acquire the filesize beforehand and hope it doesn't change. # Speeds things up. - result = newString(int(len)) - if readBuffer(file, addr(result[0]), int(len)) != len: + result = newString(len) + let bytes = readBuffer(file, addr(result[0]), len) + if endOfFile(file): + if bytes < len: + result = substr(result, 0 , bytes - 1) + elif fileError(file): raiseEIO("error while reading from file") + else: + # We red all the bytes but did not reach the EOF + # Try to read it as a buffer + result = readAllBuffer(file) proc readAllFile(file: File): string = var len = rawFileSize(file) @@ -187,12 +197,17 @@ proc endOfFile(f: File): bool = ungetc(c, f) return c < 0'i32 +proc fileError(f: File): bool = + result = (ferror(f) != 0) + proc writeLn[Ty](f: File, x: varargs[Ty, `$`]) = - for i in items(x): write(f, i) + for i in items(x): + write(f, i) write(f, "\n") proc writeLine[Ty](f: File, x: varargs[Ty, `$`]) = - for i in items(x): write(f, i) + for i in items(x): + write(f, i) write(f, "\n") when declared(stdout): From 193f248ea0d510171b69e8e690eaaa05509be47f Mon Sep 17 00:00:00 2001 From: Dominik Picheta Date: Sun, 23 Aug 2015 18:22:37 +0100 Subject: [PATCH 0856/1263] Fixes parsing of URIs that begin with '//'. --- lib/pure/uri.nim | 27 ++++++++++++++++++++------- 1 file changed, 20 insertions(+), 7 deletions(-) diff --git a/lib/pure/uri.nim b/lib/pure/uri.nim index 1890a9bf4..492de3b46 100644 --- a/lib/pure/uri.nim +++ b/lib/pure/uri.nim @@ -14,7 +14,7 @@ type Url* = distinct string Uri* = object - scheme*, username*, password*: string + scheme*, username*, password*: string hostname*, port*, path*, query*, anchor*: string opaque*: bool @@ -69,7 +69,7 @@ proc parseAuthority(authority: string, result: var Uri) = i.inc proc parsePath(uri: string, i: var int, result: var Uri) = - + i.inc parseUntil(uri, result.path, {'?', '#'}, i) # The 'mailto' scheme's PATH actually contains the hostname/username @@ -104,19 +104,23 @@ proc parseUri*(uri: string, result: var Uri) = var i = 0 # Check if this is a reference URI (relative URI) + let doubleSlash = uri.len > 1 and uri[1] == '/' if uri[i] == '/': - parsePath(uri, i, result) - return + # Make sure ``uri`` doesn't begin with '//'. + if not doubleSlash: + parsePath(uri, i, result) + return # Scheme i.inc parseWhile(uri, result.scheme, Letters + Digits + {'+', '-', '.'}, i) - if uri[i] != ':': + if uri[i] != ':' and not doubleSlash: # Assume this is a reference URI (relative URI) i = 0 result.scheme.setLen(0) parsePath(uri, i, result) return - i.inc # Skip ':' + if not doubleSlash: + i.inc # Skip ':' # Authority if uri[i] == '/' and uri[i+1] == '/': @@ -201,7 +205,7 @@ proc combine*(base: Uri, reference: Uri): Uri = ## ## let bar = combine(parseUri("http://example.com/foo/bar/"), parseUri("baz")) ## assert bar.path == "/foo/bar/baz" - + template setAuthority(dest, src: expr): stmt = dest.hostname = src.hostname dest.username = src.username @@ -369,6 +373,15 @@ when isMainModule: doAssert test.path == "test/no/slash" doAssert($test == str) + block: + let str = "//git@github.com:dom96/packages" + let test = parseUri(str) + doAssert test.scheme == "" + doAssert test.username == "git" + doAssert test.hostname == "github.com" + doAssert test.port == "dom96" + doAssert test.path == "/packages" + # Remove dot segments tests block: doAssert removeDotSegments("/foo/bar/baz") == "/foo/bar/baz" From fe190ee83f2d0d1f2ee4c7e6e0c01cbb73504688 Mon Sep 17 00:00:00 2001 From: Dominik Picheta Date: Sun, 23 Aug 2015 19:57:23 +0100 Subject: [PATCH 0857/1263] Better docs for os.getCreationTime(). Fixes #1058. --- lib/pure/os.nim | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/lib/pure/os.nim b/lib/pure/os.nim index c2c28c2b1..3d592a526 100644 --- a/lib/pure/os.nim +++ b/lib/pure/os.nim @@ -461,8 +461,10 @@ proc getLastAccessTime*(file: string): Time {.rtl, extern: "nos$1".} = proc getCreationTime*(file: string): Time {.rtl, extern: "nos$1".} = ## Returns the `file`'s creation time. - ## Note that under posix OS's, the returned time may actually be the time at - ## which the file's attribute's were last modified. + ## + ## **Note:** Under POSIX OS's, the returned time may actually be the time at + ## which the file's attribute's were last modified. See + ## `here `_ for details. when defined(posix): var res: Stat if stat(file, res) < 0'i32: raiseOSError(osLastError()) From 1b73cd41bf71a76800a4da3e8c35f18e83b264c9 Mon Sep 17 00:00:00 2001 From: Dominik Picheta Date: Sun, 23 Aug 2015 21:57:45 +0100 Subject: [PATCH 0858/1263] Improves osproc.startProcess error message. Fixes #2183. --- lib/pure/osproc.nim | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/lib/pure/osproc.nim b/lib/pure/osproc.nim index add4bc0a8..671e69a49 100644 --- a/lib/pure/osproc.nim +++ b/lib/pure/osproc.nim @@ -468,7 +468,14 @@ when defined(Windows) and not defined(useNimRtl): fileClose(si.hStdError) if e != nil: dealloc(e) - if success == 0: raiseOSError(lastError, command) + if success == 0: + const errInvalidParameter = 87.int + const errFileNotFound = 2.int + if lastError.int in {errInvalidParameter, errFileNotFound}: + raiseOSError(lastError, + "Requested command not found: '$1'. OS error:" % command) + else: + raiseOSError(lastError, command) # Close the handle now so anyone waiting is woken: discard closeHandle(procInfo.hThread) result.fProcessHandle = procInfo.hProcess From 9b0ac8afa88272b03247199844018758fada6958 Mon Sep 17 00:00:00 2001 From: Dominik Picheta Date: Sun, 23 Aug 2015 22:07:37 +0100 Subject: [PATCH 0859/1263] Improves osproc.startProcess error message on POSIX. Ref #2183. --- lib/pure/osproc.nim | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/pure/osproc.nim b/lib/pure/osproc.nim index 671e69a49..81befccff 100644 --- a/lib/pure/osproc.nim +++ b/lib/pure/osproc.nim @@ -785,7 +785,8 @@ elif not defined(useNimRtl): var error: cint let sizeRead = read(data.pErrorPipe[readIdx], addr error, sizeof(error)) if sizeRead == sizeof(error): - raiseOSError($strerror(error)) + raiseOSError("Could not find command: '$1'. OS error: $2" % + [$data.sysCommand, $strerror(error)]) return pid From 385a883e1425e511bb593332c0e53f72ab9146a1 Mon Sep 17 00:00:00 2001 From: xyz Date: Sun, 23 Aug 2015 18:29:38 -0400 Subject: [PATCH 0860/1263] Use seLen as sugested, and fix typos --- lib/system.nim | 4 ++-- lib/system/sysio.nim | 5 ++--- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/lib/system.nim b/lib/system.nim index ee94f85d2..80aedaa8c 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -2594,10 +2594,10 @@ when not defined(JS): #and not defined(nimscript): ## Closes the file. proc endOfFile*(f: File): bool {.tags: [], benign.} - ## Returns true if `f` is at the end. + ## Returns true iff `f` is at the end. proc fileError*(f: File): bool {.tags: [], benign.} - ## Returns true if the error indicator of `f` is set. + ## Returns true iff the error indicator of `f` is set. proc readChar*(f: File): char {. importc: "fgetc", header: "", tags: [ReadIOEffect].} diff --git a/lib/system/sysio.nim b/lib/system/sysio.nim index 7918569e1..edf3d347a 100644 --- a/lib/system/sysio.nim +++ b/lib/system/sysio.nim @@ -38,7 +38,6 @@ proc fseek(f: File, offset: clong, whence: int): int {. importc: "fseek", header: "", tags: [].} proc ftell(f: File): int {.importc: "ftell", header: "", tags: [].} proc ferror(f: File): int {.importc: "ferror", header: "", tags: [].} -proc feof(f: File): int {.importc: "feof", header: "", tags: [].} proc setvbuf(stream: File, buf: pointer, typ, size: cint): cint {. importc, header: "", tags: [].} proc memchr(s: pointer, c: cint, n: csize): pointer {. @@ -153,11 +152,11 @@ proc readAllFile(file: File, len: int): string = let bytes = readBuffer(file, addr(result[0]), len) if endOfFile(file): if bytes < len: - result = substr(result, 0 , bytes - 1) + result.setLen(bytes) elif fileError(file): raiseEIO("error while reading from file") else: - # We red all the bytes but did not reach the EOF + # We read all the bytes but did not reach the EOF # Try to read it as a buffer result = readAllBuffer(file) From 88247e6857beb73666b7bc763bd897b26806dd9f Mon Sep 17 00:00:00 2001 From: xyz Date: Sun, 23 Aug 2015 18:54:15 -0400 Subject: [PATCH 0861/1263] Append the readAllBuffer to what was read already --- lib/system/sysio.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/system/sysio.nim b/lib/system/sysio.nim index edf3d347a..6db92ddf9 100644 --- a/lib/system/sysio.nim +++ b/lib/system/sysio.nim @@ -158,7 +158,7 @@ proc readAllFile(file: File, len: int): string = else: # We read all the bytes but did not reach the EOF # Try to read it as a buffer - result = readAllBuffer(file) + result.add(readAllBuffer(file)) proc readAllFile(file: File): string = var len = rawFileSize(file) From 2130e9e38f6054744cc4c6dcb55da54a5fcc9845 Mon Sep 17 00:00:00 2001 From: Yuriy Glukhov Date: Mon, 24 Aug 2015 15:28:11 +0300 Subject: [PATCH 0862/1263] Don't access GCed field in finalizer. Fixes #2305 --- tests/gc/gctest.nim | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/tests/gc/gctest.nim b/tests/gc/gctest.nim index a634a47f2..b3b9af608 100644 --- a/tests/gc/gctest.nim +++ b/tests/gc/gctest.nim @@ -22,7 +22,7 @@ type data: string sons: seq[TBNode] # directly embedded! t: TTable - + TCaseKind = enum nkStr, nkWhole, nkList PCaseNode = ref TCaseNode TCaseNode {.final.} = object @@ -33,7 +33,7 @@ type TIdObj* = object of TObject id*: int # unique id; use this for comparisons and not the pointers - + PIdObj* = ref TIdObj PIdent* = ref TIdent TIdent*{.acyclic.} = object of TIdObj @@ -53,22 +53,21 @@ proc newCaseNode(data: string): PCaseNode = result.kind = nkWhole result.unused = @["", "abc", "abdc"] flip = 1 - flip - + proc newCaseNode(a, b: PCaseNode): PCaseNode = new(result) result.kind = nkList result.sons = @[a, b] - + proc caseTree(lvl: int = 0): PCaseNode = if lvl == 3: result = newCaseNode("data item") else: result = newCaseNode(caseTree(lvl+1), caseTree(lvl+1)) -proc finalizeBNode(n: TBNode) = writeLine(stdout, n.data) proc finalizeNode(n: PNode) = assert(n != nil) write(stdout, "finalizing: ") if isNil(n.data): writeLine(stdout, "nil!") - else: writeLine(stdout, n.data) + else: writeLine(stdout, "not nil") var id: int = 1 @@ -147,7 +146,7 @@ proc buildBTree(father: var TBNode) = father.t.data = @["ha", "lets", "stress", "it"] setSons(father) -proc getIdent(identifier: cstring, length: int, h: int): PIdent = +proc getIdent(identifier: cstring, length: int, h: int): PIdent = new(result) result.h = h result.s = newString(length) @@ -157,7 +156,7 @@ proc main() = discard getIdent("hall", 4, 0) discard getIdent("echo", 4, 0) discard getIdent("huch", 4, 0) - + var father: TBNode for i in 1..1_00: From e703afdb3bcdf251be8d2f930a2bb3450f192809 Mon Sep 17 00:00:00 2001 From: Araq Date: Mon, 24 Aug 2015 17:11:00 +0200 Subject: [PATCH 0863/1263] fixes sysio regression for nimscript support --- lib/system/sysio.nim | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/lib/system/sysio.nim b/lib/system/sysio.nim index 58ad8ace0..f51354da8 100644 --- a/lib/system/sysio.nim +++ b/lib/system/sysio.nim @@ -73,7 +73,10 @@ proc raiseEIO(msg: string) {.noinline, noreturn.} = proc readLine(f: File, line: var TaintedString): bool = var pos = 0 # Use the currently reserved space for a first try - var space = cast[PGenericSeq](line.string).space + when defined(nimscript): + var space = 80 + else: + var space = cast[PGenericSeq](line.string).space line.string.setLen(space) while true: From 646af76c873f46875e91390f50dc3a2efb5e6d4d Mon Sep 17 00:00:00 2001 From: Araq Date: Mon, 24 Aug 2015 17:59:29 +0200 Subject: [PATCH 0864/1263] implemented nimPinToCpu threadpool feature --- lib/pure/concurrency/threadpool.nim | 10 +++++++++- web/news.txt | 6 ++++-- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/lib/pure/concurrency/threadpool.nim b/lib/pure/concurrency/threadpool.nim index 7c9d8adfd..0079cf302 100644 --- a/lib/pure/concurrency/threadpool.nim +++ b/lib/pure/concurrency/threadpool.nim @@ -322,6 +322,9 @@ var distinguished: array[MaxDistinguishedThread, TThread[ptr Worker]] distinguishedData: array[MaxDistinguishedThread, Worker] +when defined(nimPinToCpu): + var gCpus: Natural + proc setMinPoolSize*(size: range[1..MaxThreadPoolSize]) = ## sets the minimal thread pool size. The default value of this is 4. minPoolSize = size @@ -342,6 +345,8 @@ proc activateWorkerThread(i: int) {.noinline.} = workersData[i].q.empty = createSemaphore() initLock(workersData[i].q.lock) createThread(workers[i], slave, addr(workersData[i])) + when defined(nimPinToCpu): + if gCpus > 0: pinToCpu(workers[i], i mod gCpus) proc activateDistinguishedThread(i: int) {.noinline.} = distinguishedData[i].taskArrived = createSemaphore() @@ -353,7 +358,10 @@ proc activateDistinguishedThread(i: int) {.noinline.} = createThread(distinguished[i], distinguishedSlave, addr(distinguishedData[i])) proc setup() = - currentPoolSize = min(countProcessors(), MaxThreadPoolSize) + let p = countProcessors() + when defined(nimPinToCpu): + gCpus = p + currentPoolSize = min(p, MaxThreadPoolSize) readyWorker = addr(workersData[0]) for i in 0.. Date: Tue, 25 Aug 2015 11:21:07 +0300 Subject: [PATCH 0865/1263] Corrected lib name for macos. --- lib/system/inclrtl.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/system/inclrtl.nim b/lib/system/inclrtl.nim index dbc961402..d0dc38284 100644 --- a/lib/system/inclrtl.nim +++ b/lib/system/inclrtl.nim @@ -33,7 +33,7 @@ elif defined(useNimRtl): when defined(windows): const nimrtl* = "nimrtl.dll" elif defined(macosx): - const nimrtl* = "nimrtl.dylib" + const nimrtl* = "libnimrtl.dylib" else: const nimrtl* = "libnimrtl.so" {.pragma: rtl, importc: "nimrtl_$1", dynlib: nimrtl, gcsafe.} From 1def8ec9f9e3042dd765d29f21954b504b0a8c46 Mon Sep 17 00:00:00 2001 From: xyz Date: Tue, 25 Aug 2015 06:48:58 -0400 Subject: [PATCH 0866/1263] remove fileError --- lib/system.nim | 3 --- lib/system/sysio.nim | 5 +---- 2 files changed, 1 insertion(+), 7 deletions(-) diff --git a/lib/system.nim b/lib/system.nim index 80aedaa8c..2a3f72f3b 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -2596,9 +2596,6 @@ when not defined(JS): #and not defined(nimscript): proc endOfFile*(f: File): bool {.tags: [], benign.} ## Returns true iff `f` is at the end. - proc fileError*(f: File): bool {.tags: [], benign.} - ## Returns true iff the error indicator of `f` is set. - proc readChar*(f: File): char {. importc: "fgetc", header: "", tags: [ReadIOEffect].} ## Reads a single character from the stream `f`. diff --git a/lib/system/sysio.nim b/lib/system/sysio.nim index 6db92ddf9..8ad48d368 100644 --- a/lib/system/sysio.nim +++ b/lib/system/sysio.nim @@ -153,7 +153,7 @@ proc readAllFile(file: File, len: int): string = if endOfFile(file): if bytes < len: result.setLen(bytes) - elif fileError(file): + elif ferror(file) != 0: raiseEIO("error while reading from file") else: # We read all the bytes but did not reach the EOF @@ -196,9 +196,6 @@ proc endOfFile(f: File): bool = ungetc(c, f) return c < 0'i32 -proc fileError(f: File): bool = - result = (ferror(f) != 0) - proc writeLn[Ty](f: File, x: varargs[Ty, `$`]) = for i in items(x): write(f, i) From a66b968d3bc278a669e2350762eda894b100c511 Mon Sep 17 00:00:00 2001 From: Yuriy Glukhov Date: Tue, 25 Aug 2015 15:47:34 +0300 Subject: [PATCH 0867/1263] Fixed passing byvar --- compiler/jsgen.nim | 28 +++++++++++++++++++++++----- tests/js/tbyvar.nim | 10 ++++++++++ 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/compiler/jsgen.nim b/compiler/jsgen.nim index 4a0e22db7..c72365cce 100644 --- a/compiler/jsgen.nim +++ b/compiler/jsgen.nim @@ -1032,7 +1032,7 @@ proc genDeref(p: PProc, n: PNode, r: var TCompRes) = if a.typ != etyBaseIndex: internalError(n.info, "genDeref") r.res = "$1[$2]" % [a.address, a.res] -proc genArg(p: PProc, n: PNode, r: var TCompRes) = +proc genArgNoParam(p: PProc, n: PNode, r: var TCompRes) = var a: TCompRes gen(p, n, a) if a.typ == etyBaseIndex: @@ -1042,6 +1042,20 @@ proc genArg(p: PProc, n: PNode, r: var TCompRes) = else: add(r.res, a.res) +proc genArg(p: PProc, n: PNode, param: PSym, r: var TCompRes) = + var a: TCompRes + gen(p, n, a) + if skipTypes(param.typ, abstractVar).kind in {tyOpenArray, tyVarargs} and + a.typ == etyBaseIndex: + add(r.res, "$1[$2]" % [a.address, a.res]) + elif a.typ == etyBaseIndex: + add(r.res, a.address) + add(r.res, ", ") + add(r.res, a.res) + else: + add(r.res, a.res) + + proc genArgs(p: PProc, n: PNode, r: var TCompRes) = add(r.res, "(") var hasArgs = false @@ -1052,13 +1066,17 @@ proc genArgs(p: PProc, n: PNode, r: var TCompRes) = for i in countup(1, sonsLen(n) - 1): let it = n.sons[i] + var paramType : PNode = nil if i < sonsLen(typ): assert(typ.n.sons[i].kind == nkSym) - let paramType = typ.n.sons[i] + paramType = typ.n.sons[i] if paramType.typ.isCompileTimeOnly: continue if hasArgs: add(r.res, ", ") - genArg(p, it, r) + if paramType.isNil: + genArgNoParam(p, it, r) + else: + genArg(p, it, paramType.sym, r) hasArgs = true add(r.res, ")") r.kind = resExpr @@ -1083,7 +1101,7 @@ proc genInfixCall(p: PProc, n: PNode, r: var TCompRes) = add(r.res, "(") for i in countup(2, sonsLen(n) - 1): if i > 2: add(r.res, ", ") - genArg(p, n.sons[i], r) + genArgNoParam(p, n.sons[i], r) add(r.res, ")") r.kind = resExpr @@ -1097,7 +1115,7 @@ proc genEcho(p: PProc, n: PNode, r: var TCompRes) = let it = n.sons[i] if it.typ.isCompileTimeOnly: continue if i > 0: add(r.res, ", ") - genArg(p, it, r) + genArgNoParam(p, it, r) add(r.res, ")") r.kind = resExpr diff --git a/tests/js/tbyvar.nim b/tests/js/tbyvar.nim index 1269e6f66..9714cd56b 100644 --- a/tests/js/tbyvar.nim +++ b/tests/js/tbyvar.nim @@ -31,3 +31,13 @@ proc main = echo y main() + +# Test: pass var seq to var openarray +var s = @[2, 1] +proc foo(a: var openarray[int]) = a[0] = 123 + +proc bar(s: var seq[int], a: int) = + doAssert(a == 5) + foo(s) +s.bar(5) +doAssert(s == @[123, 1]) From 999c107c52f69b06e697db72af8c31a61d804193 Mon Sep 17 00:00:00 2001 From: Araq Date: Tue, 25 Aug 2015 15:13:39 +0200 Subject: [PATCH 0868/1263] fixes #3245 --- lib/system/gc.nim | 3 ++- lib/system/gc_ms.nim | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/lib/system/gc.nim b/lib/system/gc.nim index df7864cff..0c632aeb1 100644 --- a/lib/system/gc.nim +++ b/lib/system/gc.nim @@ -17,7 +17,8 @@ # stack overflows when traversing deep datastructures. It is well-suited # for soft real time applications (like games). -import arch +when defined(nimCoroutines): + import arch {.push profiler:off.} diff --git a/lib/system/gc_ms.nim b/lib/system/gc_ms.nim index 2973d1b9a..d1aecb7a2 100644 --- a/lib/system/gc_ms.nim +++ b/lib/system/gc_ms.nim @@ -10,7 +10,8 @@ # A simple mark&sweep garbage collector for Nim. Define the # symbol ``gcUseBitvectors`` to generate a variant of this GC. -import arch +when defined(nimCoroutines): + import arch {.push profiler:off.} From 7d9a748fcdb97ace2c30fb8a8b65a3ac4a8661a0 Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Tue, 25 Aug 2015 16:33:44 +0200 Subject: [PATCH 0869/1263] removed coro prefixes from coro.nim --- lib/pure/coro.nim | 36 +++++++++++++++++++----------------- 1 file changed, 19 insertions(+), 17 deletions(-) diff --git a/lib/pure/coro.nim b/lib/pure/coro.nim index 6ef5f6f54..239700c3c 100644 --- a/lib/pure/coro.nim +++ b/lib/pure/coro.nim @@ -15,7 +15,7 @@ import macros import arch import lists -const coroDefaultStackSize = 512 * 1024 +const defaultStackSize = 512 * 1024 type Coroutine = ref object @@ -38,8 +38,7 @@ proc GC_addStack(starts: pointer) {.cdecl, importc.} proc GC_removeStack(starts: pointer) {.cdecl, importc.} proc GC_setCurrentStack(starts, pos: pointer) {.cdecl, importc.} - -proc coroStart*(c: proc(), stacksize: int=coroDefaultStackSize) = +proc start*(c: proc(), stacksize: int=defaultStackSize) = ## Adds coroutine to event loop. It does not run immediately. var coro = Coroutine() coro.fn = c @@ -47,9 +46,10 @@ proc coroStart*(c: proc(), stacksize: int=coroDefaultStackSize) = coro.stack = alloc0(stacksize) coro.stacksize = stacksize coroutines.append(coro) +{.deprecated: [coroStart: start].} {.push stackTrace: off.} -proc coroYield*(sleepTime: float=0) = +proc sleep*(sleepTime: float=0) = ## Stops coroutine execution and resumes no sooner than after ``sleeptime`` seconds. ## Until then other coroutines are executed. var oldFrame = getFrame() @@ -61,8 +61,9 @@ proc coroYield*(sleepTime: float=0) = longjmp(mainCtx, 1) setFrame(oldFrame) {.pop.} +{.deprecated: [coroYield: sleep].} -proc coroRun*() = +proc run*() = ## Starts main event loop which exits when all coroutines exit. Calling this proc ## starts execution of first coroutine. var node = coroutines.head @@ -107,19 +108,20 @@ proc coroRun*() = node = coroutines.head else: node = node.next +{.deprecated: [coroRun: run].} - -proc coroAlive*(c: proc()): bool = +proc alive*(c: proc()): bool = ## Returns ``true`` if coroutine has not returned, ``false`` otherwise. for coro in items(coroutines): if coro.fn == c: return true +{.deprecated: [coroAlive: alive].} -proc coroWait*(c: proc(), interval=0.01) = +proc wait*(c: proc(), interval=0.01) = ## Returns only after coroutine ``c`` has returned. ``interval`` is time in seconds how often. - while coroAlive(c): - coroYield interval - + while alive(c): + sleep interval +{.deprecated: [coroWait: wait].} when isMainModule: var stackCheckValue = 1100220033 @@ -128,18 +130,18 @@ when isMainModule: proc c1() = for i in 0 .. 3: echo "c1" - coroYield 0.05 + sleep 0.05 echo "c1 exits" proc c2() = for i in 0 .. 3: echo "c2" - coroYield 0.025 - coroWait(c1) + sleep 0.025 + wait(c1) echo "c2 exits" - coroStart(c1) - coroStart(c2) - coroRun() + start(c1) + start(c2) + run() echo "done ", stackCheckValue From c0ad9a96cef4793b3c2f2ce24f02da076ea887dc Mon Sep 17 00:00:00 2001 From: Araq Date: Tue, 25 Aug 2015 22:44:30 +0200 Subject: [PATCH 0870/1263] fixes #3237 --- lib/nimbase.h | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/lib/nimbase.h b/lib/nimbase.h index 2828eaff2..0946b9a1f 100644 --- a/lib/nimbase.h +++ b/lib/nimbase.h @@ -160,9 +160,15 @@ __clang__ #if defined(__BORLANDC__) || defined(__WATCOMC__) || \ defined(__POCC__) || defined(_MSC_VER) || defined(WIN32) || defined(_WIN32) /* these compilers have a fastcall so use it: */ -# define N_NIMCALL(rettype, name) rettype __fastcall name -# define N_NIMCALL_PTR(rettype, name) rettype (__fastcall *name) -# define N_RAW_NIMCALL __fastcall +# ifdef __TINYC__ +# define N_NIMCALL(rettype, name) rettype __attribute((__fastcall)) name +# define N_NIMCALL_PTR(rettype, name) rettype (__attribute((__fastcall)) *name) +# define N_RAW_NIMCALL __attribute((__fastcall)) +# else +# define N_NIMCALL(rettype, name) rettype __fastcall name +# define N_NIMCALL_PTR(rettype, name) rettype (__fastcall *name) +# define N_RAW_NIMCALL __fastcall +# endif #else # define N_NIMCALL(rettype, name) rettype name /* no modifier */ # define N_NIMCALL_PTR(rettype, name) rettype (*name) From d876960b9d56144ff6ee9cdabd5af3686b02c920 Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Tue, 25 Aug 2015 23:52:14 +0200 Subject: [PATCH 0871/1263] removed coro deprecations --- lib/pure/coro.nim | 6 ------ 1 file changed, 6 deletions(-) diff --git a/lib/pure/coro.nim b/lib/pure/coro.nim index 239700c3c..f3780a24c 100644 --- a/lib/pure/coro.nim +++ b/lib/pure/coro.nim @@ -17,7 +17,6 @@ import lists const defaultStackSize = 512 * 1024 - type Coroutine = ref object # prev: ptr Coroutine # next: ptr Coroutine @@ -46,7 +45,6 @@ proc start*(c: proc(), stacksize: int=defaultStackSize) = coro.stack = alloc0(stacksize) coro.stacksize = stacksize coroutines.append(coro) -{.deprecated: [coroStart: start].} {.push stackTrace: off.} proc sleep*(sleepTime: float=0) = @@ -61,7 +59,6 @@ proc sleep*(sleepTime: float=0) = longjmp(mainCtx, 1) setFrame(oldFrame) {.pop.} -{.deprecated: [coroYield: sleep].} proc run*() = ## Starts main event loop which exits when all coroutines exit. Calling this proc @@ -108,20 +105,17 @@ proc run*() = node = coroutines.head else: node = node.next -{.deprecated: [coroRun: run].} proc alive*(c: proc()): bool = ## Returns ``true`` if coroutine has not returned, ``false`` otherwise. for coro in items(coroutines): if coro.fn == c: return true -{.deprecated: [coroAlive: alive].} proc wait*(c: proc(), interval=0.01) = ## Returns only after coroutine ``c`` has returned. ``interval`` is time in seconds how often. while alive(c): sleep interval -{.deprecated: [coroWait: wait].} when isMainModule: var stackCheckValue = 1100220033 From 66ff1792fa803b305d66edc3e520c3a5e8d8d470 Mon Sep 17 00:00:00 2001 From: Keerthan Jaic Date: Wed, 26 Aug 2015 00:00:46 -0400 Subject: [PATCH 0872/1263] add msp430 cpu support --- compiler/platform.nim | 5 +++-- lib/system/platforms.nim | 2 ++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/compiler/platform.nim b/compiler/platform.nim index c4e7d453a..8376c2b32 100644 --- a/compiler/platform.nim +++ b/compiler/platform.nim @@ -159,7 +159,7 @@ type # alias conditionals to condsyms (end of module). cpuNone, cpuI386, cpuM68k, cpuAlpha, cpuPowerpc, cpuPowerpc64, cpuPowerpc64el, cpuSparc, cpuVm, cpuIa64, cpuAmd64, cpuMips, cpuMipsel, - cpuArm, cpuArm64, cpuJS, cpuNimrodVM, cpuAVR + cpuArm, cpuArm64, cpuJS, cpuNimrodVM, cpuAVR, cpuMSP430 type TEndian* = enum @@ -186,7 +186,8 @@ const (name: "arm64", intSize: 64, endian: littleEndian, floatSize: 64, bit: 64), (name: "js", intSize: 32, endian: bigEndian,floatSize: 64,bit: 32), (name: "nimrodvm", intSize: 32, endian: bigEndian, floatSize: 64, bit: 32), - (name: "avr", intSize: 16, endian: littleEndian, floatSize: 32, bit: 16)] + (name: "avr", intSize: 16, endian: littleEndian, floatSize: 32, bit: 16), + (name: "msp430", intSize: 16, endian: littleEndian, floatSize: 32, bit: 16)] var targetCPU*, hostCPU*: TSystemCPU diff --git a/lib/system/platforms.nim b/lib/system/platforms.nim index 0a7045fae..eeada5c51 100644 --- a/lib/system/platforms.nim +++ b/lib/system/platforms.nim @@ -28,6 +28,7 @@ type arm64, ## ARM64 based processor vm, ## Some Virtual machine: Nim's VM or JavaScript avr ## AVR based processor + msp430 ## TI MSP430 microcontroller OsPlatform* {.pure.} = enum ## the OS this program will run on. none, dos, windows, os2, linux, morphos, skyos, solaris, @@ -76,5 +77,6 @@ const elif defined(arm64): CpuPlatform.arm64 elif defined(vm): CpuPlatform.vm elif defined(avr): CpuPlatform.avr + elif defined(msp430): CpuPlatform.msp430 else: CpuPlatform.none ## the CPU this program will run on. From 20c2b008227028c52d4ba2349c69dd76d9ed65ab Mon Sep 17 00:00:00 2001 From: Araq Date: Wed, 26 Aug 2015 23:59:00 +0200 Subject: [PATCH 0873/1263] make --gc:none work with --threads:on --- lib/system/threads.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/system/threads.nim b/lib/system/threads.nim index 315a70af5..c7cb8d9df 100644 --- a/lib/system/threads.nim +++ b/lib/system/threads.nim @@ -244,7 +244,7 @@ when useStackMaskHack: when not defined(useNimRtl): when not useStackMaskHack: #when not defined(createNimRtl): initStackBottom() - initGC() + when declared(initGC): initGC() when emulatedThreadVars: if nimThreadVarsSize() > sizeof(ThreadLocalStorage): From 370781b773739b2a580b661b5e444548dbf48411 Mon Sep 17 00:00:00 2001 From: Araq Date: Thu, 27 Aug 2015 01:01:43 +0200 Subject: [PATCH 0874/1263] update Visual Studio command line flags --- compiler/extccomp.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/extccomp.nim b/compiler/extccomp.nim index 683de67e0..02198d06e 100644 --- a/compiler/extccomp.nim +++ b/compiler/extccomp.nim @@ -123,7 +123,7 @@ compiler vcc: includeCmd: " /I", linkDirCmd: " /LIBPATH:", linkLibCmd: " $1.lib", - debug: " /GZ /Zi ", + debug: " /RTC1 /Z7 ", pic: "", asmStmtFrmt: "__asm{$n$1$n}$n", structStmtFmt: "$3$n$1 $2", From 1b47941b01c69ef2accf11622887de3a27d26c1c Mon Sep 17 00:00:00 2001 From: JamesP Date: Fri, 28 Aug 2015 22:51:35 +1000 Subject: [PATCH 0875/1263] fixes #3220 lib/impure/db_mysql.nim getValue() mysql connector command out of sync error due to breaking the fastRows iterator loop --- lib/impure/db_mysql.nim | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/lib/impure/db_mysql.nim b/lib/impure/db_mysql.nim index 7c2901efd..197286f29 100644 --- a/lib/impure/db_mysql.nim +++ b/lib/impure/db_mysql.nim @@ -206,10 +206,7 @@ proc getValue*(db: DbConn, query: SqlQuery, ## executes the query and returns the first column of the first row of the ## result dataset. Returns "" if the dataset contains no rows or the database ## value is NULL. - result = "" - for row in fastRows(db, query, args): - result = row[0] - break + result = getRow(db, query, args)[0] proc tryInsertId*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]): int64 {.tags: [FWriteDb].} = From f089d7001052634cfee4d439ec052445c49d9ffc Mon Sep 17 00:00:00 2001 From: coffeepots Date: Fri, 28 Aug 2015 14:10:30 +0100 Subject: [PATCH 0876/1263] Add widestring versions of SQLPrepare and SQLExecDirect SQLPrepareW and SQLExecDirectW are needed to use unicode as otherwise ODBC only recognises ansi codepages. --- lib/wrappers/odbcsql.nim | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/lib/wrappers/odbcsql.nim b/lib/wrappers/odbcsql.nim index 971861a6a..43ad80f76 100644 --- a/lib/wrappers/odbcsql.nim +++ b/lib/wrappers/odbcsql.nim @@ -680,8 +680,12 @@ proc SQLBrowseConnect*(hdbc: SqlHDBC, szConnStrIn: PSQLCHAR, dynlib: odbclib, importc.} proc SQLExecDirect*(StatementHandle: SqlHStmt, StatementText: PSQLCHAR, TextLength: TSqlInteger): TSqlSmallInt{.dynlib: odbclib, importc.} +proc SQLExecDirectW*(StatementHandle: SqlHStmt, StatementText: WideCString, + TextLength: TSqlInteger): TSqlSmallInt{.dynlib: odbclib, importc.} proc SQLPrepare*(StatementHandle: SqlHStmt, StatementText: PSQLCHAR, TextLength: TSqlInteger): TSqlSmallInt{.dynlib: odbclib, importc.} +proc SQLPrepareW*(StatementHandle: SqlHStmt, StatementText: WideCString, + TextLength: TSqlInteger): TSqlSmallInt{.dynlib: odbclib, importc.} proc SQLCloseCursor*(StatementHandle: SqlHStmt): TSqlSmallInt{.dynlib: odbclib, importc.} proc SQLExecute*(StatementHandle: SqlHStmt): TSqlSmallInt{.dynlib: odbclib, importc.} From 7dd263f506453a849b585d586b27606235123277 Mon Sep 17 00:00:00 2001 From: Reimer Behrends Date: Fri, 28 Aug 2015 17:21:03 +0200 Subject: [PATCH 0877/1263] Fix readLine handling of long lines. --- lib/system/sysio.nim | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/lib/system/sysio.nim b/lib/system/sysio.nim index 265f92fa2..3d0b2aa8a 100644 --- a/lib/system/sysio.nim +++ b/lib/system/sysio.nim @@ -90,12 +90,21 @@ proc readLine(f: File, line: var TaintedString): bool = let m = memchr(addr line.string[pos], '\l'.ord, space) if m != nil: # \l found: Could be our own or the one by fgets, in any case, we're done - let last = cast[ByteAddress](m) - cast[ByteAddress](addr line.string[0]) + var last = cast[ByteAddress](m) - cast[ByteAddress](addr line.string[0]) if last > 0 and line.string[last-1] == '\c': line.string.setLen(last-1) return true + # We have to distinguish between two possible cases: + # \0\l\0 => line ending in a null character. + # \0\l\l => last line without newline, null was put there by fgets. + elif last > 0 and line.string[last-1] == '\0': + if last < pos + space - 1 and line.string[last+1] != '\0': + dec last line.string.setLen(last) return true + else: + # fgets will have inserted a null byte at the end of the string. + dec space # No \l found: Increase buffer and read more inc pos, space space = 128 # read in 128 bytes at a time From da2d0845b8d4725888a58aaf0741d9227a380f3b Mon Sep 17 00:00:00 2001 From: JamesP Date: Sat, 29 Aug 2015 07:50:14 +1000 Subject: [PATCH 0878/1263] lib/impure/db_mysql add example code-block --- lib/impure/db_mysql.nim | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/lib/impure/db_mysql.nim b/lib/impure/db_mysql.nim index 197286f29..34537c7f7 100644 --- a/lib/impure/db_mysql.nim +++ b/lib/impure/db_mysql.nim @@ -9,6 +9,37 @@ ## A higher level `mySQL`:idx: database wrapper. The same interface is ## implemented for other databases too. +## +## Example: +## +## .. code-block:: Nim +## +## import db_mysql, math +## +## let theDb = open("localhost", "nim", "nim", "test") +## +## theDb.exec(sql"Drop table if exists myTestTbl") +## theDb.exec(sql("create table myTestTbl (" & +## " Id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, " & +## " Name VARCHAR(50) NOT NULL, " & +## " i INT(11), " & +## " f DECIMAL(18,10))")) +## +## theDb.exec(sql"START TRANSACTION") +## for i in 1..1000: +## theDb.exec(sql"INSERT INTO myTestTbl (name,i,f) VALUES (?,?,?)", +## "Item#" & $i, i, sqrt(i.float)) +## theDb.exec(sql"COMMIT") +## +## for x in theDb.fastRows(sql"select * from myTestTbl"): +## echo x +## +## let id = theDb.tryInsertId(sql"INSERT INTO myTestTbl (name,i,f) VALUES (?,?,?)", +## "Item#1001", 1001, sqrt(1001.0)) +## echo "Inserted item: ", theDb.getValue(sql"SELECT name FROM myTestTbl WHERE id=?", id) +## +## theDb.close() + import strutils, mysql From 755d86ff3db795dc16221186b4c206ae1f5374aa Mon Sep 17 00:00:00 2001 From: xland <412588801@qq.com> Date: Sun, 30 Aug 2015 08:30:22 +0800 Subject: [PATCH 0879/1263] Add link button for IUP wrapper Add link button for IUP wrapper --- lib/wrappers/iup.nim | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/wrappers/iup.nim b/lib/wrappers/iup.nim index cbd9b5ae9..d910173ca 100644 --- a/lib/wrappers/iup.nim +++ b/lib/wrappers/iup.nim @@ -307,6 +307,8 @@ proc menuv*(children: ptr PIhandle): PIhandle {. proc button*(title, action: cstring): PIhandle {. importc: "IupButton", cdecl, dynlib: dllname.} +proc link*(url, title: cstring): PIhandle {. + importc: "IupLink", cdecl, dynlib: dllname.} proc canvas*(action: cstring): PIhandle {. importc: "IupCanvas", cdecl, dynlib: dllname.} proc dialog*(child: PIhandle): PIhandle {. From 24655ecd52b9d68bfc9123f3883f7e2951db8aac Mon Sep 17 00:00:00 2001 From: Simon Hafner Date: Sun, 30 Aug 2015 10:24:13 +0200 Subject: [PATCH 0880/1263] coro.sleep -> suspend --- lib/pure/coro.nim | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/lib/pure/coro.nim b/lib/pure/coro.nim index f3780a24c..b2a7692bb 100644 --- a/lib/pure/coro.nim +++ b/lib/pure/coro.nim @@ -47,13 +47,13 @@ proc start*(c: proc(), stacksize: int=defaultStackSize) = coroutines.append(coro) {.push stackTrace: off.} -proc sleep*(sleepTime: float=0) = +proc suspend*(sleepTime: float=0) = ## Stops coroutine execution and resumes no sooner than after ``sleeptime`` seconds. ## Until then other coroutines are executed. var oldFrame = getFrame() var sp {.volatile.}: pointer GC_setCurrentStack(current.stack, cast[pointer](addr sp)) - current.sleepTime = sleep_time + current.sleepTime = sleepTime current.lastRun = epochTime() if setjmp(current.ctx) == 0: longjmp(mainCtx, 1) @@ -115,7 +115,7 @@ proc alive*(c: proc()): bool = proc wait*(c: proc(), interval=0.01) = ## Returns only after coroutine ``c`` has returned. ``interval`` is time in seconds how often. while alive(c): - sleep interval + suspend interval when isMainModule: var stackCheckValue = 1100220033 @@ -124,14 +124,14 @@ when isMainModule: proc c1() = for i in 0 .. 3: echo "c1" - sleep 0.05 + suspend 0.05 echo "c1 exits" proc c2() = for i in 0 .. 3: echo "c2" - sleep 0.025 + suspend 0.025 wait(c1) echo "c2 exits" From c60728326ed926255800fe3064f818a4aeaff8c5 Mon Sep 17 00:00:00 2001 From: Dominik Picheta Date: Sun, 30 Aug 2015 13:11:27 +0100 Subject: [PATCH 0881/1263] Add :idx: for `suspend` in coro module. --- lib/pure/coro.nim | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/pure/coro.nim b/lib/pure/coro.nim index b2a7692bb..8fa529474 100644 --- a/lib/pure/coro.nim +++ b/lib/pure/coro.nim @@ -50,6 +50,8 @@ proc start*(c: proc(), stacksize: int=defaultStackSize) = proc suspend*(sleepTime: float=0) = ## Stops coroutine execution and resumes no sooner than after ``sleeptime`` seconds. ## Until then other coroutines are executed. + ## + ## This is similar to a `yield`:idx:, or a `yieldFrom`:idx in Python. var oldFrame = getFrame() var sp {.volatile.}: pointer GC_setCurrentStack(current.stack, cast[pointer](addr sp)) From 02214d8d1ba4410402f571889bfb39bc00591d11 Mon Sep 17 00:00:00 2001 From: Yuriy Glukhov Date: Mon, 31 Aug 2015 21:44:07 +0300 Subject: [PATCH 0882/1263] Fixed JS copying. --- lib/system/jssys.nim | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/lib/system/jssys.nim b/lib/system/jssys.nim index a6839c48e..eb6080d38 100644 --- a/lib/system/jssys.nim +++ b/lib/system/jssys.nim @@ -547,18 +547,14 @@ proc nimCopyAux(dest, src: JSRef, n: ptr TNimNode) {.compilerproc.} = of nkNone: sysAssert(false, "nimCopyAux") of nkSlot: asm """ - var ddest = `dest`[`n`.offset]; - if (ddest === undefined) ddest = null; - `dest`[`n`.offset] = nimCopy(ddest, `src`[`n`.offset], `n`.typ); + `dest`[`n`.offset] = nimCopy(`dest`[`n`.offset], `src`[`n`.offset], `n`.typ); """ of nkList: for i in 0..n.len-1: nimCopyAux(dest, src, n.sons[i]) of nkCase: asm """ - var ddest = `dest`[`n`.offset]; - if (ddest === undefined) ddest = null; - `dest`[`n`.offset] = nimCopy(ddest, `src`[`n`.offset], `n`.typ); + `dest`[`n`.offset] = nimCopy(`dest`[`n`.offset], `src`[`n`.offset], `n`.typ); for (var i = 0; i < `n`.sons.length; ++i) { nimCopyAux(`dest`, `src`, `n`.sons[i][1]); } @@ -579,13 +575,13 @@ proc nimCopy(dest, src: JSRef, ti: PNimType): JSRef = of tyTuple, tyObject: if ti.base != nil: result = nimCopy(dest, src, ti.base) elif ti.kind == tyObject: - asm "`result` = (`dest` === null) ? {m_type: `ti`} : `dest`;" + asm "`result` = (`dest` === null || `dest` === undefined) ? {m_type: `ti`} : `dest`;" else: - asm "`result` = (`dest` === null) ? {} : `dest`;" + asm "`result` = (`dest` === null || `dest` === undefined) ? {} : `dest`;" nimCopyAux(result, src, ti.node) of tySequence, tyArrayConstr, tyOpenArray, tyArray: asm """ - if (`dest` === null) { + if (`dest` === null || `dest` === undefined) { `dest` = new Array(`src`.length); } else { From e733debec706b8449b8bc000b1695b7df5e9839c Mon Sep 17 00:00:00 2001 From: Araq Date: Mon, 31 Aug 2015 11:09:12 +0200 Subject: [PATCH 0883/1263] first implementation of write tracking and escape analysis; still disabled --- compiler/ast.nim | 5 +- compiler/options.nim | 1 + compiler/sempass2.nim | 46 +++--- compiler/transf.nim | 2 +- compiler/writetracking.nim | 286 +++++++++++++++++++++++++++++++++++++ 5 files changed, 319 insertions(+), 21 deletions(-) create mode 100644 compiler/writetracking.nim diff --git a/compiler/ast.nim b/compiler/ast.nim index a0a5d204a..0ad0a0718 100644 --- a/compiler/ast.nim +++ b/compiler/ast.nim @@ -291,12 +291,12 @@ const sfNoForward* = sfRegister # forward declarations are not required (per module) - sfNoRoot* = sfBorrow # a local variable is provably no root so it doesn't - # require RC ops sfCompileToCpp* = sfInfixCall # compile the module as C++ code sfCompileToObjc* = sfNamedParamCall # compile the module as Objective-C code sfExperimental* = sfOverriden # module uses the .experimental switch sfGoto* = sfOverriden # var is used for 'goto' code generation + sfWrittenTo* = sfBorrow # param is assigned to + sfEscapes* = sfProcvar # param escapes const # getting ready for the future expr/stmt merge @@ -527,6 +527,7 @@ const # deprecated and this mess can be cleaned up. tfVoid* = tfVarargs # for historical reasons we conflated 'void' with # 'empty' ('@[]' has the type 'seq[empty]'). + tfReturnsNew* = tfInheritable skError* = skUnknown # type flags that are essential for type equality: diff --git a/compiler/options.nim b/compiler/options.nim index adf2017d6..1f167e2a6 100644 --- a/compiler/options.nim +++ b/compiler/options.nim @@ -13,6 +13,7 @@ import const hasTinyCBackend* = defined(tinyc) useEffectSystem* = true + useWriteTracking* = false hasFFI* = defined(useFFI) newScopeForIf* = true useCaas* = not defined(noCaas) diff --git a/compiler/sempass2.nim b/compiler/sempass2.nim index 3431ee2ff..d363eee77 100644 --- a/compiler/sempass2.nim +++ b/compiler/sempass2.nim @@ -9,7 +9,7 @@ import intsets, ast, astalgo, msgs, renderer, magicsys, types, idents, trees, - wordrecg, strutils, options, guards + wordrecg, strutils, options, guards, writetracking # Second semantic checking pass over the AST. Necessary because the old # way had some inherent problems. Performs: @@ -17,7 +17,7 @@ import # * effect+exception tracking # * "usage before definition" checking # * checks for invalid usages of compiletime magics (not implemented) -# * checks for invalid usages of PNimNode (not implemented) +# * checks for invalid usages of NimNode (not implemented) # * later: will do an escape analysis for closures at least # Predefined effects: @@ -29,21 +29,6 @@ import # --> a TR macro can annotate the proc with user defined annotations # --> the effect system can access these -# Load&Store analysis is performed on *paths*. A path is an access like -# obj.x.y[i].z; splitting paths up causes some problems: -# -# var x = obj.x -# var z = x.y[i].z -# -# Alias analysis is affected by this too! A good solution is *type splitting*: -# T becomes T1 and T2 if it's known that T1 and T2 can't alias. -# -# An aliasing problem and a race condition are effectively the same problem. -# Type based alias analysis is nice but not sufficient; especially splitting -# an array and filling it in parallel should be supported but is not easily -# done: It essentially requires a built-in 'indexSplit' operation and dependent -# typing. - # ------------------------ exception and tag tracking ------------------------- discard """ @@ -438,17 +423,41 @@ proc documentEffect(n, x: PNode, effectType: TSpecialWord, idx: int): PNode = result = newNode(nkExprColonExpr, n.info, @[ newIdentNode(getIdent(specialWords[effectType]), n.info), effects]) +proc documentWriteEffect(n: PNode; flag: TSymFlag; pragmaName: string): PNode = + let s = n.sons[namePos].sym + let params = s.typ.n + + var effects = newNodeI(nkBracket, n.info) + for i in 1 ..< params.len: + if params[i].kind == nkSym and flag in params[i].sym.flags: + effects.add params[i] + + if effects.len > 0: + result = newNode(nkExprColonExpr, n.info, @[ + newIdentNode(getIdent(pragmaName), n.info), effects]) + +proc documentNewEffect(n: PNode): PNode = + let s = n.sons[namePos].sym + if tfReturnsNew in s.typ.flags: + result = newIdentNode(getIdent("new"), n.info) + proc documentRaises*(n: PNode) = if n.sons[namePos].kind != nkSym: return let pragmas = n.sons[pragmasPos] let p1 = documentEffect(n, pragmas, wRaises, exceptionEffects) let p2 = documentEffect(n, pragmas, wTags, tagEffects) + let p3 = documentWriteEffect(n, sfWrittenTo, "writes") + let p4 = documentNewEffect(n) + let p5 = documentWriteEffect(n, sfEscapes, "escapes") - if p1 != nil or p2 != nil: + if p1 != nil or p2 != nil or p3 != nil or p4 != nil or p5 != nil: if pragmas.kind == nkEmpty: n.sons[pragmasPos] = newNodeI(nkPragma, n.info) if p1 != nil: n.sons[pragmasPos].add p1 if p2 != nil: n.sons[pragmasPos].add p2 + if p3 != nil: n.sons[pragmasPos].add p3 + if p4 != nil: n.sons[pragmasPos].add p4 + if p5 != nil: n.sons[pragmasPos].add p5 template notGcSafe(t): expr = {tfGcSafe, tfNoSideEffect} * t.flags == {} @@ -900,6 +909,7 @@ proc trackProc*(s: PSym, body: PNode) = message(s.info, warnLockLevel, "declared lock level is $1, but real lock level is $2" % [$s.typ.lockLevel, $t.maxLockLevel]) + when useWriteTracking: trackWrites(s, body) proc trackTopLevelStmt*(module: PSym; n: PNode) = if n.kind in {nkPragma, nkMacroDef, nkTemplateDef, nkProcDef, diff --git a/compiler/transf.nim b/compiler/transf.nim index 5c7472a39..4ca40ab74 100644 --- a/compiler/transf.nim +++ b/compiler/transf.nim @@ -115,7 +115,7 @@ proc transformSymAux(c: PTransf, n: PNode): PNode = # return liftIterSym(n) var b: PNode var tc = c.transCon - if sfBorrow in n.sym.flags: + if sfBorrow in n.sym.flags and n.sym.kind in routineKinds: # simply exchange the symbol: b = n.sym.getBody if b.kind != nkSym: internalError(n.info, "wrong AST for borrowed symbol") diff --git a/compiler/writetracking.nim b/compiler/writetracking.nim new file mode 100644 index 000000000..cf9ad91cc --- /dev/null +++ b/compiler/writetracking.nim @@ -0,0 +1,286 @@ +# +# +# The Nim Compiler +# (c) Copyright 2015 Andreas Rumpf +# +# See the file "copying.txt", included in this +# distribution, for details about the copyright. +# + +## This module implements the write tracking analysis. Read my block post for +## a basic description of the algorithm and ideas. + +import idents, ast, astalgo, trees, renderer, msgs, types + +const + debug = false + +type + AssignToResult = enum + asgnNil, # 'nil' is fine + asgnNew, # 'new(result)' + asgnOther # result = fooBar # not a 'new' --> 'result' might not 'new' + NewLocation = enum + newNone, + newLit, + newCall + W = object # WriteTrackContext + owner: PSym + returnsNew: AssignToResult # assignments to 'result' + markAsWrittenTo, markAsEscaping: PNode + assignments: seq[(PNode, PNode)] # list of all assignments in this proc + +proc returnsNewExpr*(n: PNode): NewLocation = + case n.kind + of nkCharLit..nkInt64Lit, nkStrLit..nkTripleStrLit, + nkFloatLit..nkFloat64Lit, nkNilLit: + result = newLit + of nkExprEqExpr, nkExprColonExpr, nkHiddenStdConv, nkHiddenSubConv, + nkStmtList, nkStmtListExpr, nkBlockStmt, nkBlockExpr, nkOfBranch, + nkElifBranch, nkElse, nkExceptBranch, nkFinally, nkCast: + result = returnsNewExpr(n.lastSon) + of nkCurly, nkBracket, nkPar, nkObjConstr, nkClosure, + nkIfExpr, nkIfStmt, nkWhenStmt, nkCaseStmt, nkTryStmt: + result = newLit + for i in 0 .. treat as 'let tmp = p(); tmp.foo = x' + result = newSym(skTemp, getIdent(":tmp"), owner, n.sons[0].info) + #result.typ = n.sons[0].typ.sons[0] + #result.ast = n.sons[0] + # XXX + of nkPar: + localError(n.info, "writeSetAnalysis: too implement") + else: + discard + +proc deps(w: var W; dest, src: PNode) = + # let x = (localA, localB) + # compute 'returnsNew' property: + let retNew = returnsNewExpr(src) + if dest.kind == nkSym and dest.sym.kind == skResult: + if retNew != newNone: + if w.returnsNew != asgnOther: w.returnsNew = asgnNew + else: + w.returnsNew = asgnOther + # mark the dependency, but + # rule out obviously innocent assignments like 'somebool = true' + if dest.kind == nkSym and retNew == newLit: discard + else: w.assignments.add((dest, src)) + +proc depsArgs(w: var W; n: PNode) = + if n.sons[0].typ.isNil: return + var typ = skipTypes(n.sons[0].typ, abstractInst) + if typ.kind != tyProc: return + # echo n.info, " ", n, " ", w.owner.name.s, " ", typeToString(typ) + assert(sonsLen(typ) == sonsLen(typ.n)) + for i in 1 ..< n.len: + let it = n.sons[i] + if i < sonsLen(typ): + assert(typ.n.sons[i].kind == nkSym) + let paramType = typ.n.sons[i] + if paramType.typ.isCompileTimeOnly: continue + if sfWrittenTo in paramType.sym.flags or paramType.typ.kind == tyVar: + # p(f(x, y), X, g(h, z)) + deps(w, it, w.markAsWrittenTo) + if sfEscapes in paramType.sym.flags or paramType.typ.kind == tyVar: + deps(w, it, w.markAsEscaping) + +proc deps(w: var W; n: PNode) = + case n.kind + of nkLetSection, nkVarSection: + for child in n: + let last = lastSon(child) + if last.kind == nkEmpty: continue + if child.kind == nkVarTuple and last.kind == nkPar: + internalAssert child.len-2 == last.len + for i in 0 .. child.len-3: + deps(w, child.sons[i], last.sons[i]) + else: + for i in 0 .. child.len-3: + deps(w, child.sons[i], last) + of nkAsgn, nkFastAsgn: + deps(w, n.sons[0], n.sons[1]) + else: + for i in 0 ..< n.safeLen: + deps(w, n.sons[i]) + if n.kind in nkCallKinds: + if getMagic(n) in {mNew, mNewFinalize, mNewSeq}: + # may not look like an assignment, but it is: + deps(w, n.sons[1], newNodeIT(nkObjConstr, n.info, n.sons[1].typ)) + else: + depsArgs(w, n) + +proc allRoots(n: PNode; result: var seq[PSym]) = + case n.kind + of nkSym: + if n.sym notin result: result.add n.sym + of nkDotExpr, nkBracketExpr, nkHiddenDeref, nkDerefExpr, nkCheckedFieldExpr, + nkHiddenAddr, nkObjUpConv, nkObjDownConv: + allRoots(n.sons[0], result) + of nkExprEqExpr, nkExprColonExpr, nkHiddenStdConv, nkHiddenSubConv, nkConv, + nkStmtList, nkStmtListExpr, nkBlockStmt, nkBlockExpr, nkOfBranch, + nkElifBranch, nkElse, nkExceptBranch, nkFinally, nkCast: + allRoots(n.lastSon, result) + of nkCallKinds: + if getMagic(n) == mSlice: + allRoots(n.sons[1], result) + else: + # we do significantly better here by using the available escape + # information: + if n.sons[0].typ.isNil: return + var typ = n.sons[0].typ + if typ != nil: + typ = skipTypes(typ, abstractInst) + if typ.kind != tyProc: typ = nil + else: assert(sonsLen(typ) == sonsLen(typ.n)) + + for i in 1 ..< n.len: + let it = n.sons[i] + if typ != nil and i < sonsLen(typ): + assert(typ.n.sons[i].kind == nkSym) + let paramType = typ.n.sons[i] + if paramType.typ.isCompileTimeOnly: continue + if sfEscapes in paramType.sym.flags or paramType.typ.kind == tyVar: + allRoots(it, result) + else: + allRoots(it, result) + else: + for i in 0.. check which parameter it may alias and mark these parameters + # as dirty: + let aliases = possibleAliases(w, r) + for a in aliases: + if a.kind == skParam and a.owner == w.owner: + incl(a.flags, sfWrittenTo) + else: + internalError(dest.info, "dunno what to do " & $r.kind) + +proc markEscaping(w: W) = + # let p1 = p + # let p2 = q + # p2.x = call(..., p1, ...) + for dest, src in items(w.assignments): + var heapAccess = src == w.markAsEscaping + let r = root(w.owner, dest, heapAccess) + if r != nil and (heapAccess or r.kind == skResult): + if r.kind in {skParam, skVar, skTemp, skLet, skResult, skForVar}: + let aliases = possibleAliases(w, r) + var destIsParam = false + for a in aliases: + if a.kind in {skResult, skParam} and a.owner == w.owner: + destIsParam = true + break + if destIsParam: + var victims: seq[PSym] = @[] + allRoots(src, victims) + possibleAliases(w, victims) + for v in victims: + if v.kind == skParam and v.owner == w.owner: + incl(v.flags, sfEscapes) + else: + internalError(dest.info, "dunno what to do " & $r.kind) + +proc trackWrites*(owner: PSym; body: PNode) = + var w: W + w.owner = owner + w.markAsWrittenTo = newNodeI(nkArgList, body.info) + w.markAsEscaping = newNodeI(nkArgList, body.info) + w.assignments = @[] + deps(w, body) + markDirty(w) + markEscaping(w) + if w.returnsNew != asgnOther and not isEmptyType(owner.typ.sons[0]) and + containsGarbageCollectedRef(owner.typ.sons[0]): + incl(owner.typ.flags, tfReturnsNew) + From 940b3ceca8562e677f2527e705b24c1a4af8f860 Mon Sep 17 00:00:00 2001 From: Araq Date: Mon, 31 Aug 2015 15:07:39 +0200 Subject: [PATCH 0884/1263] write tracking: leaner code; minor bug fixes (still unusable) --- compiler/writetracking.nim | 146 ++++++++++++++++--------------------- 1 file changed, 61 insertions(+), 85 deletions(-) diff --git a/compiler/writetracking.nim b/compiler/writetracking.nim index cf9ad91cc..2589959e8 100644 --- a/compiler/writetracking.nim +++ b/compiler/writetracking.nim @@ -42,7 +42,7 @@ proc returnsNewExpr*(n: PNode): NewLocation = of nkCurly, nkBracket, nkPar, nkObjConstr, nkClosure, nkIfExpr, nkIfStmt, nkWhenStmt, nkCaseStmt, nkTryStmt: result = newLit - for i in 0 .. treat as 'let tmp = p(); tmp.foo = x' - result = newSym(skTemp, getIdent(":tmp"), owner, n.sons[0].info) - #result.typ = n.sons[0].typ.sons[0] - #result.ast = n.sons[0] - # XXX - of nkPar: - localError(n.info, "writeSetAnalysis: too implement") - else: - discard - proc deps(w: var W; dest, src: PNode) = # let x = (localA, localB) # compute 'returnsNew' property: @@ -141,20 +111,32 @@ proc deps(w: var W; n: PNode) = else: depsArgs(w, n) -proc allRoots(n: PNode; result: var seq[PSym]) = +type + RootInfo = enum + rootIsResultOrParam, + rootIsHeapAccess + +proc allRoots(n: PNode; result: var seq[PSym]; info: var set[RootInfo]) = case n.kind of nkSym: - if n.sym notin result: result.add n.sym - of nkDotExpr, nkBracketExpr, nkHiddenDeref, nkDerefExpr, nkCheckedFieldExpr, + if n.sym.kind in {skParam, skVar, skTemp, skLet, skResult, skForVar}: + if result.isNil: result = @[] + if n.sym notin result: + if n.sym.kind in {skResult, skParam}: incl(info, rootIsResultOrParam) + result.add n.sym + of nkHiddenDeref, nkDerefExpr: + incl(info, rootIsHeapAccess) + allRoots(n.sons[0], result, info) + of nkDotExpr, nkBracketExpr, nkCheckedFieldExpr, nkHiddenAddr, nkObjUpConv, nkObjDownConv: - allRoots(n.sons[0], result) + allRoots(n.sons[0], result, info) of nkExprEqExpr, nkExprColonExpr, nkHiddenStdConv, nkHiddenSubConv, nkConv, nkStmtList, nkStmtListExpr, nkBlockStmt, nkBlockExpr, nkOfBranch, nkElifBranch, nkElse, nkExceptBranch, nkFinally, nkCast: - allRoots(n.lastSon, result) + allRoots(n.lastSon, result, info) of nkCallKinds: if getMagic(n) == mSlice: - allRoots(n.sons[1], result) + allRoots(n.sons[1], result, info) else: # we do significantly better here by using the available escape # information: @@ -172,12 +154,16 @@ proc allRoots(n: PNode; result: var seq[PSym]) = let paramType = typ.n.sons[i] if paramType.typ.isCompileTimeOnly: continue if sfEscapes in paramType.sym.flags or paramType.typ.kind == tyVar: - allRoots(it, result) + allRoots(it, result, info) else: - allRoots(it, result) + allRoots(it, result, info) else: for i in 0.. check which parameter it may alias and mark these parameters - # as dirty: - let aliases = possibleAliases(w, r) - for a in aliases: - if a.kind == skParam and a.owner == w.owner: - incl(a.flags, sfWrittenTo) - else: - internalError(dest.info, "dunno what to do " & $r.kind) + if rootIsHeapAccess in info or src == w.markAsWrittenTo: + # we have an assignment like: + # local.foo = bar + # --> check which parameter it may alias and mark these parameters + # as dirty: + possibleAliases(w, r) + for a in r: + if a.kind == skParam and a.owner == w.owner: + incl(a.flags, sfWrittenTo) proc markEscaping(w: W) = # let p1 = p # let p2 = q # p2.x = call(..., p1, ...) for dest, src in items(w.assignments): - var heapAccess = src == w.markAsEscaping - let r = root(w.owner, dest, heapAccess) - if r != nil and (heapAccess or r.kind == skResult): - if r.kind in {skParam, skVar, skTemp, skLet, skResult, skForVar}: - let aliases = possibleAliases(w, r) - var destIsParam = false - for a in aliases: - if a.kind in {skResult, skParam} and a.owner == w.owner: - destIsParam = true - break - if destIsParam: - var victims: seq[PSym] = @[] - allRoots(src, victims) - possibleAliases(w, victims) - for v in victims: - if v.kind == skParam and v.owner == w.owner: - incl(v.flags, sfEscapes) - else: - internalError(dest.info, "dunno what to do " & $r.kind) + var r: seq[PSym] = nil + var info: set[RootInfo] + allRoots(dest, r, info) + + if (r.len > 0) and (info != {} or src == w.markAsEscaping): + possibleAliases(w, r) + var destIsParam = false + for a in r: + if a.kind in {skResult, skParam} and a.owner == w.owner: + destIsParam = true + break + if destIsParam: + var victims: seq[PSym] = @[] + allRoots(src, victims) + possibleAliases(w, victims) + for v in victims: + if v.kind == skParam and v.owner == w.owner: + incl(v.flags, sfEscapes) proc trackWrites*(owner: PSym; body: PNode) = var w: W From 1e597c6332e41a9633ba42918b0e1797065a7f6e Mon Sep 17 00:00:00 2001 From: Araq Date: Tue, 1 Sep 2015 23:41:03 +0200 Subject: [PATCH 0885/1263] formatFloat takes an optional decimalSep parameter --- lib/pure/strutils.nim | 27 +++++++++++++++++---------- web/news.txt | 2 ++ 2 files changed, 19 insertions(+), 10 deletions(-) diff --git a/lib/pure/strutils.nim b/lib/pure/strutils.nim index e3f99b895..ae3bd7f63 100644 --- a/lib/pure/strutils.nim +++ b/lib/pure/strutils.nim @@ -1197,8 +1197,8 @@ proc editDistance*(a, b: string): int {.noSideEffect, # floating point formating: -proc c_sprintf(buf, frmt: cstring) {.header: "", importc: "sprintf", - varargs, noSideEffect.} +proc c_sprintf(buf, frmt: cstring): cint {.header: "", + importc: "sprintf", varargs, noSideEffect.} type FloatFormatMode* = enum ## the different modes of floating point formating @@ -1209,7 +1209,8 @@ type {.deprecated: [TFloatFormat: FloatFormatMode].} proc formatBiggestFloat*(f: BiggestFloat, format: FloatFormatMode = ffDefault, - precision: range[0..32] = 16): string {. + precision: range[0..32] = 16; + decimalSep = '.'): string {. noSideEffect, rtl, extern: "nsu$1".} = ## Converts a floating point value `f` to a string. ## @@ -1225,6 +1226,7 @@ proc formatBiggestFloat*(f: BiggestFloat, format: FloatFormatMode = ffDefault, var frmtstr {.noinit.}: array[0..5, char] buf {.noinit.}: array[0..2500, char] + L: cint frmtstr[0] = '%' if precision > 0: frmtstr[1] = '#' @@ -1232,15 +1234,20 @@ proc formatBiggestFloat*(f: BiggestFloat, format: FloatFormatMode = ffDefault, frmtstr[3] = '*' frmtstr[4] = floatFormatToChar[format] frmtstr[5] = '\0' - c_sprintf(buf, frmtstr, precision, f) + L = c_sprintf(buf, frmtstr, precision, f) else: frmtstr[1] = floatFormatToChar[format] frmtstr[2] = '\0' - c_sprintf(buf, frmtstr, f) - result = $buf + L = c_sprintf(buf, frmtstr, f) + result = newString(L) + for i in 0 ..< L: + # Depending on the locale either dot or comma is produced, + # but nothing else is possible: + if buf[i] in {'.', ','}: result[i] = decimalsep + else: result[i] = buf[i] proc formatFloat*(f: float, format: FloatFormatMode = ffDefault, - precision: range[0..32] = 16): string {. + precision: range[0..32] = 16; decimalSep = '.'): string {. noSideEffect, rtl, extern: "nsu$1".} = ## Converts a floating point value `f` to a string. ## @@ -1250,7 +1257,7 @@ proc formatFloat*(f: float, format: FloatFormatMode = ffDefault, ## of significant digits to be printed. ## `precision`'s default value is the maximum number of meaningful digits ## after the decimal point for Nim's ``float`` type. - result = formatBiggestFloat(f, format, precision) + result = formatBiggestFloat(f, format, precision, decimalSep) proc formatSize*(bytes: BiggestInt, decimalSep = '.'): string = ## Rounds and formats `bytes`. Examples: @@ -1464,8 +1471,8 @@ when isMainModule: doAssert wordWrap(inp, 10, false) == outp doAssert formatBiggestFloat(0.00000000001, ffDecimal, 11) == "0.00000000001" - doAssert formatBiggestFloat(0.00000000001, ffScientific, 1) in - ["1.0e-11", "1.0e-011"] + doAssert formatBiggestFloat(0.00000000001, ffScientific, 1, ',') in + ["1,0e-11", "1,0e-011"] doAssert "$# $3 $# $#" % ["a", "b", "c"] == "a c b c" when not defined(testing): diff --git a/web/news.txt b/web/news.txt index 040442695..a13334e3f 100644 --- a/web/news.txt +++ b/web/news.txt @@ -62,6 +62,8 @@ News - Define ``nimPinToCpu`` to make the ``threadpool`` use explicit thread affinities. This can speed up or slow down the thread pool; it's up to you to benchmark it. + - ``strutils.formatFloat`` and ``formatBiggestFloat`` do not depend on the C + locale anymore and now take an optional ``decimalSep = '.'`` parameter. Language Additions From 6fc01d1501fdda38477734ac713e52ba3852f56a Mon Sep 17 00:00:00 2001 From: Araq Date: Wed, 2 Sep 2015 00:55:31 +0200 Subject: [PATCH 0886/1263] 'var T' doesn't imply escaping --- compiler/writetracking.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/writetracking.nim b/compiler/writetracking.nim index 2589959e8..db3e6c53a 100644 --- a/compiler/writetracking.nim +++ b/compiler/writetracking.nim @@ -83,7 +83,7 @@ proc depsArgs(w: var W; n: PNode) = if sfWrittenTo in paramType.sym.flags or paramType.typ.kind == tyVar: # p(f(x, y), X, g(h, z)) deps(w, it, w.markAsWrittenTo) - if sfEscapes in paramType.sym.flags or paramType.typ.kind == tyVar: + if sfEscapes in paramType.sym.flags: deps(w, it, w.markAsEscaping) proc deps(w: var W; n: PNode) = From a3cc519ea9584ba0a26d0387a3e98e8a396a8424 Mon Sep 17 00:00:00 2001 From: JamesP Date: Thu, 3 Sep 2015 09:21:25 +1000 Subject: [PATCH 0887/1263] bug fix: Switch state to dbgSkipCurrent for Eval, Local & Global commands. This avoids stepping into the endb code if previous command was single step. Other two changes are trailing spaces removed. --- lib/system/endb.nim | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/lib/system/endb.nim b/lib/system/endb.nim index cba11ac5e..b2cc5624b 100644 --- a/lib/system/endb.nim +++ b/lib/system/endb.nim @@ -298,7 +298,7 @@ proc dbgEvaluate(stream: File, s: cstring, start: int, f: PFrame) = for i in 0 .. f.len-1: let v = getLocal(f, i) if c_strcmp(v.name, dbgTemp.data) == 0: - writeVariable(stream, v) + writeVariable(stream, v) proc dbgOut(s: cstring, start: int, currFrame: PFrame) = var dbgTemp: StaticStr @@ -396,7 +396,13 @@ proc commandPrompt() = again = false quit(1) # BUGFIX: quit with error code > 0 elif ?"e" or ?"eval": + var + prevState = dbgState + prevSkipFrame = dbgSkipToFrame + dbgState = dbSkipCurrent dbgEvaluate(stdout, dbgUser.data, i, dbgFramePtr) + dbgState = prevState + dbgSkipToFrame = prevSkipFrame elif ?"o" or ?"out": dbgOut(dbgUser.data, i, dbgFramePtr) elif ?"stackframe": @@ -404,9 +410,21 @@ proc commandPrompt() = elif ?"w" or ?"where": dbgShowExecutionPoint() elif ?"l" or ?"locals": + var + prevState = dbgState + prevSkipFrame = dbgSkipToFrame + dbgState = dbSkipCurrent listLocals(stdout, dbgFramePtr) + dbgState = prevState + dbgSkipToFrame = prevSkipFrame elif ?"g" or ?"globals": + var + prevState = dbgState + prevSkipFrame = dbgSkipToFrame + dbgState = dbSkipCurrent listGlobals(stdout) + dbgState = prevState + dbgSkipToFrame = prevSkipFrame elif ?"u" or ?"up": if dbgDown <= 0: debugOut("[Warning] cannot go up any further ") @@ -484,7 +502,7 @@ proc dbgWriteStackTrace(f: PFrame) = inc(i) b = b.prev for j in countdown(i-1, 0): - if tempFrames[j] == nil: + if tempFrames[j] == nil: write(stdout, "(") write(stdout, skipped) write(stdout, " calls omitted) ...") From ef5f0b1ac971c0d3ce00d7c839812c6065a81334 Mon Sep 17 00:00:00 2001 From: Adam Strzelecki Date: Thu, 3 Sep 2015 10:34:55 +0200 Subject: [PATCH 0888/1263] times: Export & document countLeapYears/Years/Days Previously countYears & countDays procs were not public, but there were unused, causing unnecessary warnings generated by standard library. Since these procs seems to be useful it is better to just export them than remove them completely. Also turning inline comments into proper documentation. --- lib/pure/times.nim | 30 +++++++++++++++++------------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/lib/pure/times.nim b/lib/pure/times.nim index 6d45dc7f1..aa4ae5ace 100644 --- a/lib/pure/times.nim +++ b/lib/pure/times.nim @@ -1051,26 +1051,30 @@ proc parse*(value, layout: string): TimeInfo = return info # Leap year calculations are adapted from: -# from http://www.codeproject.com/Articles/7358/Ultra-fast-Algorithms-for-Working-with-Leap-Years +# http://www.codeproject.com/Articles/7358/Ultra-fast-Algorithms-for-Working-with-Leap-Years # The dayOfTheWeek procs are adapated from: -# from http://stason.org/TULARC/society/calendars/2-5-What-day-of-the-week-was-2-August-1953.html +# http://stason.org/TULARC/society/calendars/2-5-What-day-of-the-week-was-2-August-1953.html -# Note: for leap years, start date is assumed to be 1 AD. -# counts the number of leap years up to January 1st of a given year. -# Keep in mind that if specified year is a leap year, the leap day -# has not happened before January 1st of that year. -proc countLeapYears(yearSpan: int): int = - (((yearSpan - 1) / 4) - ((yearSpan - 1) / 100) + ((yearSpan - 1)/400)).int +proc countLeapYears*(yearSpan: int): int = + ## Returns the number of leap years spanned by a given number of years. + ## + ## Note: for leap years, start date is assumed to be 1 AD. + ## counts the number of leap years up to January 1st of a given year. + ## Keep in mind that if specified year is a leap year, the leap day + ## has not happened before January 1st of that year. + (((yearSpan - 1) / 4) - ((yearSpan - 1) / 100) + ((yearSpan - 1) / 400)).int -proc countDays(yearSpan: int): int = +proc countDays*(yearSpan: int): int = + ## Returns the number of days spanned by a given number of years. (yearSpan - 1) * 365 + countLeapYears(yearSpan) -proc countYears(daySpan: int): int = - # counts the number of years spanned by a given number of days. +proc countYears*(daySpan: int): int = + ## Returns the number of years spanned by a given number of days. ((daySpan - countLeapYears(daySpan div 365)) div 365) -proc countYearsAndDays(daySpan: int): tuple[years: int, days: int] = - # counts the number of years spanned by a given number of days and the remainder as days. +proc countYearsAndDays*(daySpan: int): tuple[years: int, days: int] = + ## Returns the number of years spanned by a given number of days and the + ## remainder as days. let days = daySpan - countLeapYears(daySpan div 365) result.years = days div 365 result.days = days mod 365 From aa8da7f0316b5894bde9d12d11eb20c92ab197fc Mon Sep 17 00:00:00 2001 From: Araq Date: Wed, 2 Sep 2015 14:33:28 +0200 Subject: [PATCH 0889/1263] optimized writetracking --- compiler/writetracking.nim | 344 +++++++++++++++++++------------------ 1 file changed, 177 insertions(+), 167 deletions(-) diff --git a/compiler/writetracking.nim b/compiler/writetracking.nim index db3e6c53a..38258b07a 100644 --- a/compiler/writetracking.nim +++ b/compiler/writetracking.nim @@ -9,8 +9,13 @@ ## This module implements the write tracking analysis. Read my block post for ## a basic description of the algorithm and ideas. +## The algorithm operates in 2 phases: +## +## * Collecting information about assignments (and pass-by-var calls). +## * Computing an aliasing relation based on the assignments. This relation +## is then used to compute the 'writes' and 'escapes' effects. -import idents, ast, astalgo, trees, renderer, msgs, types +import intsets, idents, ast, astalgo, trees, renderer, msgs, types const debug = false @@ -24,106 +29,33 @@ type newNone, newLit, newCall + RootInfo = enum + rootIsResultOrParam, + rootIsHeapAccess, + rootIsSym, + markAsWrittenTo, + markAsEscaping + + Assignment = object # \ + # Note that the transitive closures MUST be computed in + # phase 2 of the algorithm. + dest, src: seq[ptr TSym] # we use 'ptr' here to save RC ops and GC cycles + destNoTc, srcNoTc: int # length of 'dest', 'src' without the + # transitive closure + destInfo: set[RootInfo] + info: TLineInfo + W = object # WriteTrackContext owner: PSym returnsNew: AssignToResult # assignments to 'result' - markAsWrittenTo, markAsEscaping: PNode - assignments: seq[(PNode, PNode)] # list of all assignments in this proc + assignments: seq[Assignment] # list of all assignments in this proc -proc returnsNewExpr*(n: PNode): NewLocation = - case n.kind - of nkCharLit..nkInt64Lit, nkStrLit..nkTripleStrLit, - nkFloatLit..nkFloat64Lit, nkNilLit: - result = newLit - of nkExprEqExpr, nkExprColonExpr, nkHiddenStdConv, nkHiddenSubConv, - nkStmtList, nkStmtListExpr, nkBlockStmt, nkBlockExpr, nkOfBranch, - nkElifBranch, nkElse, nkExceptBranch, nkFinally, nkCast: - result = returnsNewExpr(n.lastSon) - of nkCurly, nkBracket, nkPar, nkObjConstr, nkClosure, - nkIfExpr, nkIfStmt, nkWhenStmt, nkCaseStmt, nkTryStmt: - result = newLit - for i in ord(n.kind == nkObjConstr) .. 0 and a.dest[0] == x and rootIsSym in a.destInfo: + # x = f(..., y, ....) + for i in 0 ..< a.srcNoTc: addNoDup a.src[i] -proc markDirty(w: W) = - for dest, src in items(w.assignments): - var r: seq[PSym] = nil - var info: set[RootInfo] - allRoots(dest, r, info) - when debug: - if w.owner.info ?? "temp18": - echo "ASGN ", dest, " = ", src, " |", heapAccess, " ", r.name.s - if rootIsHeapAccess in info or src == w.markAsWrittenTo: - # we have an assignment like: - # local.foo = bar - # --> check which parameter it may alias and mark these parameters - # as dirty: - possibleAliases(w, r) - for a in r: - if a.kind == skParam and a.owner == w.owner: - incl(a.flags, sfWrittenTo) +proc markWriteOrEscape(w: var W) = + ## Both 'writes' and 'escapes' effects ultimately only care + ## about *parameters*. + ## However, due to aliasing, even locals that might not look as parameters + ## have to count as parameters if they can alias a parameter: + ## + ## .. code-block:: nim + ## proc modifies(n: Node) {.writes: [n].} = + ## let x = n + ## x.data = "abc" + ## + ## We call a symbol *parameter-like* if it is a parameter or can alias a + ## parameter. + ## Let ``p``, ``q`` be *parameter-like* and ``x``, ``y`` be general + ## expressions. + ## + ## A write then looks like ``p[] = x``. + ## An escape looks like ``p[] = q`` or more generally + ## like ``p[] = f(q)`` where ``f`` can forward ``q``. + for a in mitems(w.assignments): + if a.destInfo != {}: + possibleAliases(w, a.dest) -proc markEscaping(w: W) = - # let p1 = p - # let p2 = q - # p2.x = call(..., p1, ...) - for dest, src in items(w.assignments): - var r: seq[PSym] = nil - var info: set[RootInfo] - allRoots(dest, r, info) + if {rootIsHeapAccess, markAsWrittenTo} * a.destInfo != {}: + for p in a.dest: + if p.kind == skParam and p.owner == w.owner: + incl(p.flags, sfWrittenTo) - if (r.len > 0) and (info != {} or src == w.markAsEscaping): - possibleAliases(w, r) + if {rootIsResultOrParam, rootIsHeapAccess, markAsEscaping}*a.destInfo != {}: var destIsParam = false - for a in r: - if a.kind in {skResult, skParam} and a.owner == w.owner: + for p in a.dest: + if p.kind in {skResult, skParam} and p.owner == w.owner: destIsParam = true break if destIsParam: - var victims: seq[PSym] = @[] - allRoots(src, victims) - possibleAliases(w, victims) - for v in victims: - if v.kind == skParam and v.owner == w.owner: - incl(v.flags, sfEscapes) + possibleAliases(w, a.src) + for p in a.src: + if p.kind == skParam and p.owner == w.owner: + incl(p.flags, sfEscapes) proc trackWrites*(owner: PSym; body: PNode) = var w: W w.owner = owner - w.markAsWrittenTo = newNodeI(nkArgList, body.info) - w.markAsEscaping = newNodeI(nkArgList, body.info) w.assignments = @[] + # Phase 1: Collect and preprocess any assignments in the proc body: deps(w, body) - markDirty(w) - markEscaping(w) + # Phase 2: Compute the 'writes' and 'escapes' effects: + markWriteOrEscape(w) if w.returnsNew != asgnOther and not isEmptyType(owner.typ.sons[0]) and containsGarbageCollectedRef(owner.typ.sons[0]): incl(owner.typ.flags, tfReturnsNew) - From e90c15526082d0b5f644c3d92b0f34353eb884b7 Mon Sep 17 00:00:00 2001 From: Araq Date: Thu, 3 Sep 2015 14:11:14 +0200 Subject: [PATCH 0890/1263] fixes 'line too long' warnings --- lib/system.nim | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/lib/system.nim b/lib/system.nim index 2a3f72f3b..042813ae1 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -1375,7 +1375,8 @@ type # these work for most platforms: culonglong* {.importc: "unsigned long long", nodecl.} = uint64 ## This is the same as the type ``unsigned long long`` in *C*. - cstringArray* {.importc: "char**", nodecl.} = ptr array [0..ArrayDummySize, cstring] + cstringArray* {.importc: "char**", nodecl.} = ptr + array [0..ArrayDummySize, cstring] ## This is binary compatible to the type ``char**`` in *C*. The array's ## high value is large enough to disable bounds checking in practice. ## Use `cstringArrayToSeq` to convert it into a ``seq[string]``. @@ -1886,7 +1887,7 @@ iterator pairs*[T](a: openArray[T]): tuple[key: int, val: T] {.inline.} = yield (i, a[i]) inc(i) -iterator mpairs*[T](a: var openArray[T]): tuple[key: int, val: var T] {.inline.} = +iterator mpairs*[T](a: var openArray[T]): tuple[key:int, val:var T]{.inline.} = ## iterates over each item of `a`. Yields ``(index, a[index])`` pairs. ## ``a[index]`` can be modified. var i = 0 @@ -1903,7 +1904,7 @@ iterator pairs*[IX, T](a: array[IX, T]): tuple[key: IX, val: T] {.inline.} = if i >= high(IX): break inc(i) -iterator mpairs*[IX, T](a: var array[IX, T]): tuple[key: IX, val: var T] {.inline.} = +iterator mpairs*[IX, T](a:var array[IX, T]):tuple[key:IX,val:var T] {.inline.} = ## iterates over each item of `a`. Yields ``(index, a[index])`` pairs. ## ``a[index]`` can be modified. var i = low(IX) @@ -3149,25 +3150,31 @@ proc staticExec*(command: string, input = "", cache = ""): string {. ## .. code-block:: nim ## const stateMachine = staticExec("dfaoptimizer", "input", "0.8.0") -proc `+=`*[T: SomeOrdinal|uint|uint64](x: var T, y: T) {.magic: "Inc", noSideEffect.} +proc `+=`*[T: SomeOrdinal|uint|uint64](x: var T, y: T) {. + magic: "Inc", noSideEffect.} ## Increments an ordinal -proc `-=`*[T: SomeOrdinal|uint|uint64](x: var T, y: T) {.magic: "Dec", noSideEffect.} +proc `-=`*[T: SomeOrdinal|uint|uint64](x: var T, y: T) {. + magic: "Dec", noSideEffect.} ## Decrements an ordinal -proc `*=`*[T: SomeOrdinal|uint|uint64](x: var T, y: T) {.inline, noSideEffect.} = +proc `*=`*[T: SomeOrdinal|uint|uint64](x: var T, y: T) {. + inline, noSideEffect.} = ## Binary `*=` operator for ordinals x = x * y -proc `+=`*[T: float|float32|float64] (x: var T, y: T) {.inline, noSideEffect.} = +proc `+=`*[T: float|float32|float64] (x: var T, y: T) {. + inline, noSideEffect.} = ## Increments in placee a floating point number x = x + y -proc `-=`*[T: float|float32|float64] (x: var T, y: T) {.inline, noSideEffect.} = +proc `-=`*[T: float|float32|float64] (x: var T, y: T) {. + inline, noSideEffect.} = ## Decrements in place a floating point number x = x - y -proc `*=`*[T: float|float32|float64] (x: var T, y: T) {.inline, noSideEffect.} = +proc `*=`*[T: float|float32|float64] (x: var T, y: T) {. + inline, noSideEffect.} = ## Multiplies in place a floating point number x = x * y @@ -3380,8 +3387,8 @@ when hasAlloc: x.add(y) proc safeAdd*(x: var string, y: string) = - ## Adds ``y`` to ``x`` unless ``x`` is not yet initalized; in that case, ``x`` - ## becomes ``y`` + ## Adds ``y`` to ``x`` unless ``x`` is not yet initalized; in that + ## case, ``x`` becomes ``y`` if x == nil: x = y else: x.add(y) From a373bdd0c973fd1db2ab988aea8bcfc3d8dd4245 Mon Sep 17 00:00:00 2001 From: Araq Date: Thu, 3 Sep 2015 14:11:33 +0200 Subject: [PATCH 0891/1263] improvements for NimScript support --- compiler/nimconf.nim | 106 ++++++++++++++++++--------------------- compiler/options.nim | 11 ++++ lib/system/nimscript.nim | 4 +- 3 files changed, 62 insertions(+), 59 deletions(-) diff --git a/compiler/nimconf.nim b/compiler/nimconf.nim index b9c78cecc..496bd0123 100644 --- a/compiler/nimconf.nim +++ b/compiler/nimconf.nim @@ -9,106 +9,106 @@ # This module handles the reading of the config file. -import - llstream, nversion, commands, os, strutils, msgs, platform, condsyms, lexer, +import + llstream, nversion, commands, os, strutils, msgs, platform, condsyms, lexer, options, idents, wordrecg, strtabs # ---------------- configuration file parser ----------------------------- # we use Nim's scanner here to save space and work -proc ppGetTok(L: var TLexer, tok: var TToken) = +proc ppGetTok(L: var TLexer, tok: var TToken) = # simple filter rawGetTok(L, tok) while tok.tokType in {tkComment}: rawGetTok(L, tok) - + proc parseExpr(L: var TLexer, tok: var TToken): bool -proc parseAtom(L: var TLexer, tok: var TToken): bool = - if tok.tokType == tkParLe: +proc parseAtom(L: var TLexer, tok: var TToken): bool = + if tok.tokType == tkParLe: ppGetTok(L, tok) result = parseExpr(L, tok) if tok.tokType == tkParRi: ppGetTok(L, tok) else: lexMessage(L, errTokenExpected, "\')\'") - elif tok.ident.id == ord(wNot): + elif tok.ident.id == ord(wNot): ppGetTok(L, tok) result = not parseAtom(L, tok) else: result = isDefined(tok.ident) ppGetTok(L, tok) -proc parseAndExpr(L: var TLexer, tok: var TToken): bool = +proc parseAndExpr(L: var TLexer, tok: var TToken): bool = result = parseAtom(L, tok) - while tok.ident.id == ord(wAnd): + while tok.ident.id == ord(wAnd): ppGetTok(L, tok) # skip "and" var b = parseAtom(L, tok) result = result and b -proc parseExpr(L: var TLexer, tok: var TToken): bool = +proc parseExpr(L: var TLexer, tok: var TToken): bool = result = parseAndExpr(L, tok) - while tok.ident.id == ord(wOr): + while tok.ident.id == ord(wOr): ppGetTok(L, tok) # skip "or" var b = parseAndExpr(L, tok) result = result or b -proc evalppIf(L: var TLexer, tok: var TToken): bool = +proc evalppIf(L: var TLexer, tok: var TToken): bool = ppGetTok(L, tok) # skip 'if' or 'elif' result = parseExpr(L, tok) if tok.tokType == tkColon: ppGetTok(L, tok) else: lexMessage(L, errTokenExpected, "\':\'") - + var condStack: seq[bool] = @[] -proc doEnd(L: var TLexer, tok: var TToken) = +proc doEnd(L: var TLexer, tok: var TToken) = if high(condStack) < 0: lexMessage(L, errTokenExpected, "@if") ppGetTok(L, tok) # skip 'end' setLen(condStack, high(condStack)) -type - TJumpDest = enum +type + TJumpDest = enum jdEndif, jdElseEndif proc jumpToDirective(L: var TLexer, tok: var TToken, dest: TJumpDest) -proc doElse(L: var TLexer, tok: var TToken) = +proc doElse(L: var TLexer, tok: var TToken) = if high(condStack) < 0: lexMessage(L, errTokenExpected, "@if") ppGetTok(L, tok) if tok.tokType == tkColon: ppGetTok(L, tok) if condStack[high(condStack)]: jumpToDirective(L, tok, jdEndif) - -proc doElif(L: var TLexer, tok: var TToken) = + +proc doElif(L: var TLexer, tok: var TToken) = if high(condStack) < 0: lexMessage(L, errTokenExpected, "@if") var res = evalppIf(L, tok) if condStack[high(condStack)] or not res: jumpToDirective(L, tok, jdElseEndif) else: condStack[high(condStack)] = true - -proc jumpToDirective(L: var TLexer, tok: var TToken, dest: TJumpDest) = + +proc jumpToDirective(L: var TLexer, tok: var TToken, dest: TJumpDest) = var nestedIfs = 0 - while true: + while true: if tok.ident != nil and tok.ident.s == "@": ppGetTok(L, tok) case whichKeyword(tok.ident) - of wIf: + of wIf: inc(nestedIfs) - of wElse: + of wElse: if dest == jdElseEndif and nestedIfs == 0: doElse(L, tok) - break - of wElif: + break + of wElif: if dest == jdElseEndif and nestedIfs == 0: doElif(L, tok) - break - of wEnd: - if nestedIfs == 0: + break + of wEnd: + if nestedIfs == 0: doEnd(L, tok) - break + break if nestedIfs > 0: dec(nestedIfs) - else: + else: discard ppGetTok(L, tok) elif tok.tokType == tkEof: lexMessage(L, errTokenExpected, "@end") else: ppGetTok(L, tok) - -proc parseDirective(L: var TLexer, tok: var TToken) = + +proc parseDirective(L: var TLexer, tok: var TToken) = ppGetTok(L, tok) # skip @ case whichKeyword(tok.ident) of wIf: @@ -126,13 +126,13 @@ proc parseDirective(L: var TLexer, tok: var TToken) = ppGetTok(L, tok) else: case tok.ident.s.normalize - of "putenv": + of "putenv": ppGetTok(L, tok) var key = tokToStr(tok) ppGetTok(L, tok) os.putEnv(key, tokToStr(tok)) ppGetTok(L, tok) - of "prependenv": + of "prependenv": ppGetTok(L, tok) var key = tokToStr(tok) ppGetTok(L, tok) @@ -145,17 +145,17 @@ proc parseDirective(L: var TLexer, tok: var TToken) = os.putEnv(key, os.getEnv(key) & tokToStr(tok)) ppGetTok(L, tok) else: lexMessage(L, errInvalidDirectiveX, tokToStr(tok)) - -proc confTok(L: var TLexer, tok: var TToken) = + +proc confTok(L: var TLexer, tok: var TToken) = ppGetTok(L, tok) - while tok.ident != nil and tok.ident.s == "@": + while tok.ident != nil and tok.ident.s == "@": parseDirective(L, tok) # else: give the token to the parser - -proc checkSymbol(L: TLexer, tok: TToken) = - if tok.tokType notin {tkSymbol..pred(tkIntLit), tkStrLit..tkTripleStrLit}: + +proc checkSymbol(L: TLexer, tok: TToken) = + if tok.tokType notin {tkSymbol..pred(tkIntLit), tkStrLit..tkTripleStrLit}: lexMessage(L, errIdentifierExpected, tokToStr(tok)) - -proc parseAssignment(L: var TLexer, tok: var TToken) = + +proc parseAssignment(L: var TLexer, tok: var TToken) = if tok.ident.id == getIdent("-").id or tok.ident.id == getIdent("--").id: confTok(L, tok) # skip unnecessary prefix var info = getLineInfo(L, tok) # save for later in case of an error @@ -163,13 +163,13 @@ proc parseAssignment(L: var TLexer, tok: var TToken) = var s = tokToStr(tok) confTok(L, tok) # skip symbol var val = "" - while tok.tokType == tkDot: + while tok.tokType == tkDot: add(s, '.') confTok(L, tok) checkSymbol(L, tok) add(s, tokToStr(tok)) confTok(L, tok) - if tok.tokType == tkBracketLe: + if tok.tokType == tkBracketLe: # BUGFIX: val, not s! # BUGFIX: do not copy '['! confTok(L, tok) @@ -180,7 +180,7 @@ proc parseAssignment(L: var TLexer, tok: var TToken) = else: lexMessage(L, errTokenExpected, "']'") add(val, ']') let percent = tok.ident.id == getIdent("%=").id - if tok.tokType in {tkColon, tkEquals} or percent: + if tok.tokType in {tkColon, tkEquals} or percent: if len(val) > 0: add(val, ':') confTok(L, tok) # skip ':' or '=' or '%' checkSymbol(L, tok) @@ -226,15 +226,7 @@ proc getSystemConfigPath(filename: string): string = if not existsFile(result): result = "/etc/" & filename proc loadConfigs*(cfg: string) = - # set default value (can be overwritten): - if libpath == "": - # choose default libpath: - var prefix = getPrefixDir() - when defined(posix): - if prefix == "/usr": libpath = "/usr/lib/nim" - elif prefix == "/usr/local": libpath = "/usr/local/lib/nim" - else: libpath = joinPath(prefix, "lib") - else: libpath = joinPath(prefix, "lib") + setDefaultLibpath() if optSkipConfigFile notin gGlobalOptions: readConfigFile(getSystemConfigPath(cfg)) @@ -246,10 +238,10 @@ proc loadConfigs*(cfg: string) = if optSkipParentConfigFiles notin gGlobalOptions: for dir in parentDirs(pd, fromRoot=true, inclusive=false): readConfigFile(dir / cfg) - + if optSkipProjConfigFile notin gGlobalOptions: readConfigFile(pd / cfg) - + if gProjectName.len != 0: # new project wide config file: var projectConfig = changeFileExt(gProjectFull, "nimcfg") diff --git a/compiler/options.nim b/compiler/options.nim index 1f167e2a6..adb340fea 100644 --- a/compiler/options.nim +++ b/compiler/options.nim @@ -191,6 +191,17 @@ proc getPrefixDir*(): string = else: result = splitPath(getAppDir()).head +proc setDefaultLibpath*() = + # set default value (can be overwritten): + if libpath == "": + # choose default libpath: + var prefix = getPrefixDir() + when defined(posix): + if prefix == "/usr": libpath = "/usr/lib/nim" + elif prefix == "/usr/local": libpath = "/usr/local/lib/nim" + else: libpath = joinPath(prefix, "lib") + else: libpath = joinPath(prefix, "lib") + proc canonicalizePath*(path: string): string = when not FileSystemCaseSensitive: result = path.expandFilename.toLower else: result = path.expandFilename diff --git a/lib/system/nimscript.nim b/lib/system/nimscript.nim index c714f88ee..a1a653cf5 100644 --- a/lib/system/nimscript.nim +++ b/lib/system/nimscript.nim @@ -157,8 +157,8 @@ var binDir*, backend*: string skipDirs*, skipFiles*, skipExt*, installDirs*, installFiles*, - installExt*, bin*: seq[string] - requiresData*: seq[string] + installExt*, bin*: seq[string] = @[] + requiresData*: seq[string] = @[] proc requires*(deps: varargs[string]) = for d in deps: requiresData.add(d) From a9f114cf13abf8eddb4c15743600d2bb2edad7b0 Mon Sep 17 00:00:00 2001 From: Adam Strzelecki Date: Thu, 3 Sep 2015 18:00:15 +0200 Subject: [PATCH 0892/1263] osproc: Define and select spawn/fork same way Previously startProcessAuxFork was defined even when it was unused, also the compile time condition to select spawn vs fork was not always the same for definitions and calls. This change just defines the condition in one place as constant, then in other places we just check for `when useProcessAuxSpawn`. --- lib/pure/osproc.nim | 75 +++++++++++++++++++++++---------------------- 1 file changed, 38 insertions(+), 37 deletions(-) diff --git a/lib/pure/osproc.nim b/lib/pure/osproc.nim index 81befccff..7431be702 100644 --- a/lib/pure/osproc.nim +++ b/lib/pure/osproc.nim @@ -614,11 +614,14 @@ elif not defined(useNimRtl): optionPoStdErrToStdOut: bool {.deprecated: [TStartProcessData: StartProcessData].} - when not defined(useFork): + const useProcessAuxSpawn = declared(posix_spawn) and not defined(useFork) and + not defined(useClone) and not defined(linux) + when useProcessAuxSpawn: proc startProcessAuxSpawn(data: StartProcessData): Pid {. tags: [ExecIOEffect, ReadEnvEffect], gcsafe.} - proc startProcessAuxFork(data: StartProcessData): Pid {. - tags: [ExecIOEffect, ReadEnvEffect], gcsafe.} + else: + proc startProcessAuxFork(data: StartProcessData): Pid {. + tags: [ExecIOEffect, ReadEnvEffect], gcsafe.} {.push stacktrace: off, profiler: off.} proc startProcessAfterFork(data: ptr StartProcessData) {. tags: [ExecIOEffect, ReadEnvEffect], cdecl, gcsafe.} @@ -674,9 +677,7 @@ elif not defined(useNimRtl): data.optionPoStdErrToStdOut = poStdErrToStdOut in options data.workingDir = workingDir - - when declared(posix_spawn) and not defined(useFork) and - not defined(useClone) and not defined(linux): + when useProcessAuxSpawn: pid = startProcessAuxSpawn(data) else: pid = startProcessAuxFork(data) @@ -706,7 +707,7 @@ elif not defined(useNimRtl): discard close(pStdin[readIdx]) discard close(pStdout[writeIdx]) - when not defined(useFork): + when useProcessAuxSpawn: proc startProcessAuxSpawn(data: StartProcessData): Pid = var attr: Tposix_spawnattr var fops: Tposix_spawn_file_actions @@ -752,43 +753,43 @@ elif not defined(useNimRtl): discard posix_spawnattr_destroy(attr) chck res return pid + else: + proc startProcessAuxFork(data: StartProcessData): Pid = + if pipe(data.pErrorPipe) != 0: + raiseOSError(osLastError()) - proc startProcessAuxFork(data: StartProcessData): Pid = - if pipe(data.pErrorPipe) != 0: - raiseOSError(osLastError()) + defer: + discard close(data.pErrorPipe[readIdx]) - defer: - discard close(data.pErrorPipe[readIdx]) + var pid: Pid + var dataCopy = data - var pid: Pid - var dataCopy = data + when defined(useClone): + const stackSize = 65536 + let stackEnd = cast[clong](alloc(stackSize)) + let stack = cast[pointer](stackEnd + stackSize) + let fn: pointer = startProcessAfterFork + pid = clone(fn, stack, + cint(CLONE_VM or CLONE_VFORK or SIGCHLD), + pointer(addr dataCopy), nil, nil, nil) + discard close(data.pErrorPipe[writeIdx]) + dealloc(stack) + else: + pid = fork() + if pid == 0: + startProcessAfterFork(addr(dataCopy)) + exitnow(1) - when defined(useClone): - const stackSize = 65536 - let stackEnd = cast[clong](alloc(stackSize)) - let stack = cast[pointer](stackEnd + stackSize) - let fn: pointer = startProcessAfterFork - pid = clone(fn, stack, - cint(CLONE_VM or CLONE_VFORK or SIGCHLD), - pointer(addr dataCopy), nil, nil, nil) discard close(data.pErrorPipe[writeIdx]) - dealloc(stack) - else: - pid = fork() - if pid == 0: - startProcessAfterFork(addr(dataCopy)) - exitnow(1) + if pid < 0: raiseOSError(osLastError()) - discard close(data.pErrorPipe[writeIdx]) - if pid < 0: raiseOSError(osLastError()) + var error: cint + let sizeRead = read(data.pErrorPipe[readIdx], addr error, sizeof(error)) + if sizeRead == sizeof(error): + raiseOSError("Could not find command: '$1'. OS error: $2" % + [$data.sysCommand, $strerror(error)]) - var error: cint - let sizeRead = read(data.pErrorPipe[readIdx], addr error, sizeof(error)) - if sizeRead == sizeof(error): - raiseOSError("Could not find command: '$1'. OS error: $2" % - [$data.sysCommand, $strerror(error)]) - - return pid + return pid {.push stacktrace: off, profiler: off.} proc startProcessFail(data: ptr StartProcessData) = From 178275f49403012ca3d774f8cadcc2836eea9508 Mon Sep 17 00:00:00 2001 From: Araq Date: Fri, 4 Sep 2015 12:22:12 +0200 Subject: [PATCH 0893/1263] split os into os and ospaths parts; ospaths is available for NimScript; better NimScript support --- compiler/main.nim | 4 +- compiler/scriptconfig.nim | 13 + lib/pure/os.nim | 526 +---------------------------------- lib/pure/ospaths.nim | 560 ++++++++++++++++++++++++++++++++++++++ lib/system/nimscript.nim | 27 +- todo.txt | 2 +- 6 files changed, 605 insertions(+), 527 deletions(-) create mode 100644 lib/pure/ospaths.nim diff --git a/compiler/main.nim b/compiler/main.nim index 7c043eb72..3bb6fc343 100644 --- a/compiler/main.nim +++ b/compiler/main.nim @@ -355,7 +355,9 @@ proc mainCommand* = gGlobalOptions.incl(optCaasEnabled) msgs.gErrorMax = high(int) # do not stop after first error serve(mainCommand) - of "nop", "help": discard + of "nop", "help": + # prevent the "success" message: + gCmd = cmdDump else: rawMessage(errInvalidCommandX, command) diff --git a/compiler/scriptconfig.nim b/compiler/scriptconfig.nim index 148a382c2..115ce940d 100644 --- a/compiler/scriptconfig.nim +++ b/compiler/scriptconfig.nim @@ -68,9 +68,20 @@ proc setupVM*(module: PSym; scriptName: string): PEvalContext = setResult(a, os.getCurrentDir()) cbos moveFile: os.moveFile(getString(a, 0), getString(a, 1)) + cbos copyFile: + os.copyFile(getString(a, 0), getString(a, 1)) cbos getLastModificationTime: setResult(a, toSeconds(getLastModificationTime(getString(a, 0)))) + cbconf getEnv: + setResult(a, os.getEnv(a.getString 0)) + cbconf existsEnv: + setResult(a, os.existsEnv(a.getString 0)) + cbconf dirExists: + setResult(a, os.dirExists(a.getString 0)) + cbconf fileExists: + setResult(a, os.fileExists(a.getString 0)) + cbconf thisDir: setResult(a, vthisDir) cbconf put: @@ -87,6 +98,8 @@ proc setupVM*(module: PSym; scriptName: string): PEvalContext = setResult(a, os.paramCount()) cbconf cmpIgnoreStyle: setResult(a, strutils.cmpIgnoreStyle(a.getString 0, a.getString 1)) + cbconf cmpIgnoreCase: + setResult(a, strutils.cmpIgnoreCase(a.getString 0, a.getString 1)) cbconf setCommand: options.command = a.getString 0 cbconf getCommand: diff --git a/lib/pure/os.nim b/lib/pure/os.nim index 3d592a526..f413371cb 100644 --- a/lib/pure/os.nim +++ b/lib/pure/os.nim @@ -27,147 +27,7 @@ else: {.error: "OS module not ported to your operating system!".} include "system/ansi_c" - -type - ReadEnvEffect* = object of ReadIOEffect ## effect that denotes a read - ## from an environment variable - WriteEnvEffect* = object of WriteIOEffect ## effect that denotes a write - ## to an environment variable - - ReadDirEffect* = object of ReadIOEffect ## effect that denotes a write - ## operation to the directory structure - WriteDirEffect* = object of WriteIOEffect ## effect that denotes a write operation to - ## the directory structure - - OSErrorCode* = distinct int32 ## Specifies an OS Error Code. - -{.deprecated: [FReadEnv: ReadEnvEffect, FWriteEnv: WriteEnvEffect, - FReadDir: ReadDirEffect, - FWriteDir: WriteDirEffect, - TOSErrorCode: OSErrorCode -].} -const - doslike = defined(windows) or defined(OS2) or defined(DOS) - # DOS-like filesystem - -when defined(Nimdoc): # only for proper documentation: - const - CurDir* = '.' - ## The constant string used by the operating system to refer to the - ## current directory. - ## - ## For example: '.' for POSIX or ':' for the classic Macintosh. - - ParDir* = ".." - ## The constant string used by the operating system to refer to the - ## parent directory. - ## - ## For example: ".." for POSIX or "::" for the classic Macintosh. - - DirSep* = '/' - ## The character used by the operating system to separate pathname - ## components, for example, '/' for POSIX or ':' for the classic - ## Macintosh. - - AltSep* = '/' - ## An alternative character used by the operating system to separate - ## pathname components, or the same as `DirSep` if only one separator - ## character exists. This is set to '/' on Windows systems where `DirSep` - ## is a backslash. - - PathSep* = ':' - ## The character conventionally used by the operating system to separate - ## search patch components (as in PATH), such as ':' for POSIX or ';' for - ## Windows. - - FileSystemCaseSensitive* = true - ## true if the file system is case sensitive, false otherwise. Used by - ## `cmpPaths` to compare filenames properly. - - ExeExt* = "" - ## The file extension of native executables. For example: - ## "" for POSIX, "exe" on Windows. - - ScriptExt* = "" - ## The file extension of a script file. For example: "" for POSIX, - ## "bat" on Windows. - - DynlibFormat* = "lib$1.so" - ## The format string to turn a filename into a `DLL`:idx: file (also - ## called `shared object`:idx: on some operating systems). - -elif defined(macos): - const - CurDir* = ':' - ParDir* = "::" - DirSep* = ':' - AltSep* = Dirsep - PathSep* = ',' - FileSystemCaseSensitive* = false - ExeExt* = "" - ScriptExt* = "" - DynlibFormat* = "$1.dylib" - - # MacOS paths - # =========== - # MacOS directory separator is a colon ":" which is the only character not - # allowed in filenames. - # - # A path containing no colon or which begins with a colon is a partial path. - # E.g. ":kalle:petter" ":kalle" "kalle" - # - # All other paths are full (absolute) paths. E.g. "HD:kalle:" "HD:" - # When generating paths, one is safe if one ensures that all partial paths - # begin with a colon, and all full paths end with a colon. - # In full paths the first name (e g HD above) is the name of a mounted - # volume. - # These names are not unique, because, for instance, two diskettes with the - # same names could be inserted. This means that paths on MacOS are not - # waterproof. In case of equal names the first volume found will do. - # Two colons "::" are the relative path to the parent. Three is to the - # grandparent etc. -elif doslike: - const - CurDir* = '.' - ParDir* = ".." - DirSep* = '\\' # seperator within paths - AltSep* = '/' - PathSep* = ';' # seperator between paths - FileSystemCaseSensitive* = false - ExeExt* = "exe" - ScriptExt* = "bat" - DynlibFormat* = "$1.dll" -elif defined(PalmOS) or defined(MorphOS): - const - DirSep* = '/' - AltSep* = Dirsep - PathSep* = ';' - ParDir* = ".." - FileSystemCaseSensitive* = false - ExeExt* = "" - ScriptExt* = "" - DynlibFormat* = "$1.prc" -elif defined(RISCOS): - const - DirSep* = '.' - AltSep* = '.' - ParDir* = ".." # is this correct? - PathSep* = ',' - FileSystemCaseSensitive* = true - ExeExt* = "" - ScriptExt* = "" - DynlibFormat* = "lib$1.so" -else: # UNIX-like operating system - const - CurDir* = '.' - ParDir* = ".." - DirSep* = '/' - AltSep* = DirSep - PathSep* = ':' - FileSystemCaseSensitive* = true - ExeExt* = "" - ScriptExt* = "" - DynlibFormat* = when defined(macosx): "lib$1.dylib" else: "lib$1.so" +include ospaths when defined(posix): when NoFakeVars: @@ -177,11 +37,6 @@ when defined(posix): var pathMax {.importc: "PATH_MAX", header: "".}: cint -const - ExtSep* = '.' - ## The character which separates the base filename from the extension; - ## for example, the '.' in ``os.nim``. - proc osErrorMsg*(): string {.rtl, extern: "nos$1", deprecated.} = ## Retrieves the operating system's error flag, ``errno``. ## On Windows ``GetLastError`` is checked before ``errno``. @@ -300,61 +155,6 @@ proc osLastError*(): OSErrorCode = result = OSErrorCode(errno) {.pop.} -proc unixToNativePath*(path: string, drive=""): string {. - noSideEffect, rtl, extern: "nos$1".} = - ## Converts an UNIX-like path to a native one. - ## - ## On an UNIX system this does nothing. Else it converts - ## '/', '.', '..' to the appropriate things. - ## - ## On systems with a concept of "drives", `drive` is used to determine - ## which drive label to use during absolute path conversion. - ## `drive` defaults to the drive of the current working directory, and is - ## ignored on systems that do not have a concept of "drives". - - when defined(unix): - result = path - else: - var start: int - if path[0] == '/': - # an absolute path - when doslike: - if drive != "": - result = drive & ":" & DirSep - else: - result = $DirSep - elif defined(macos): - result = "" # must not start with ':' - else: - result = $DirSep - start = 1 - elif path[0] == '.' and path[1] == '/': - # current directory - result = $CurDir - start = 2 - else: - result = "" - start = 0 - - var i = start - while i < len(path): # ../../../ --> :::: - if path[i] == '.' and path[i+1] == '.' and path[i+2] == '/': - # parent directory - when defined(macos): - if result[high(result)] == ':': - add result, ':' - else: - add result, ParDir - else: - add result, ParDir & DirSep - inc(i, 3) - elif path[i] == '/': - add result, DirSep - inc(i) - else: - add result, path[i] - inc(i) - when defined(windows): when useWinUnicode: template wrapUnary(varname, winApiProc, arg: expr) {.immediate.} = @@ -518,220 +318,6 @@ proc setCurrentDir*(newDir: string) {.inline, tags: [].} = else: if chdir(newDir) != 0'i32: raiseOSError(osLastError()) -proc joinPath*(head, tail: string): string {. - noSideEffect, rtl, extern: "nos$1".} = - ## Joins two directory names to one. - ## - ## For example on Unix: - ## - ## .. code-block:: nim - ## joinPath("usr", "lib") - ## - ## results in: - ## - ## .. code-block:: nim - ## "usr/lib" - ## - ## If head is the empty string, tail is returned. If tail is the empty - ## string, head is returned with a trailing path separator. If tail starts - ## with a path separator it will be removed when concatenated to head. Other - ## path separators not located on boundaries won't be modified. More - ## examples on Unix: - ## - ## .. code-block:: nim - ## assert joinPath("usr", "") == "usr/" - ## assert joinPath("", "lib") == "lib" - ## assert joinPath("", "/lib") == "/lib" - ## assert joinPath("usr/", "/lib") == "usr/lib" - if len(head) == 0: - result = tail - elif head[len(head)-1] in {DirSep, AltSep}: - if tail[0] in {DirSep, AltSep}: - result = head & substr(tail, 1) - else: - result = head & tail - else: - if tail[0] in {DirSep, AltSep}: - result = head & tail - else: - result = head & DirSep & tail - -proc joinPath*(parts: varargs[string]): string {.noSideEffect, - rtl, extern: "nos$1OpenArray".} = - ## The same as `joinPath(head, tail)`, but works with any number of directory - ## parts. You need to pass at least one element or the proc will assert in - ## debug builds and crash on release builds. - result = parts[0] - for i in 1..high(parts): - result = joinPath(result, parts[i]) - -proc `/` * (head, tail: string): string {.noSideEffect.} = - ## The same as ``joinPath(head, tail)`` - ## - ## Here are some examples for Unix: - ## - ## .. code-block:: nim - ## assert "usr" / "" == "usr/" - ## assert "" / "lib" == "lib" - ## assert "" / "/lib" == "/lib" - ## assert "usr/" / "/lib" == "usr/lib" - return joinPath(head, tail) - -proc splitPath*(path: string): tuple[head, tail: string] {. - noSideEffect, rtl, extern: "nos$1".} = - ## Splits a directory into (head, tail), so that - ## ``head / tail == path`` (except for edge cases like "/usr"). - ## - ## Examples: - ## - ## .. code-block:: nim - ## splitPath("usr/local/bin") -> ("usr/local", "bin") - ## splitPath("usr/local/bin/") -> ("usr/local/bin", "") - ## splitPath("bin") -> ("", "bin") - ## splitPath("/bin") -> ("", "bin") - ## splitPath("") -> ("", "") - var sepPos = -1 - for i in countdown(len(path)-1, 0): - if path[i] in {DirSep, AltSep}: - sepPos = i - break - if sepPos >= 0: - result.head = substr(path, 0, sepPos-1) - result.tail = substr(path, sepPos+1) - else: - result.head = "" - result.tail = path - -proc parentDirPos(path: string): int = - var q = 1 - if len(path) >= 1 and path[len(path)-1] in {DirSep, AltSep}: q = 2 - for i in countdown(len(path)-q, 0): - if path[i] in {DirSep, AltSep}: return i - result = -1 - -proc parentDir*(path: string): string {. - noSideEffect, rtl, extern: "nos$1".} = - ## Returns the parent directory of `path`. - ## - ## This is often the same as the ``head`` result of ``splitPath``. - ## If there is no parent, "" is returned. - ## | Example: ``parentDir("/usr/local/bin") == "/usr/local"``. - ## | Example: ``parentDir("/usr/local/bin/") == "/usr/local"``. - let sepPos = parentDirPos(path) - if sepPos >= 0: - result = substr(path, 0, sepPos-1) - else: - result = "" - -proc tailDir*(path: string): string {. - noSideEffect, rtl, extern: "nos$1".} = - ## Returns the tail part of `path`.. - ## - ## | Example: ``tailDir("/usr/local/bin") == "local/bin"``. - ## | Example: ``tailDir("usr/local/bin/") == "local/bin"``. - ## | Example: ``tailDir("bin") == ""``. - var q = 1 - if len(path) >= 1 and path[len(path)-1] in {DirSep, AltSep}: q = 2 - for i in 0..len(path)-q: - if path[i] in {DirSep, AltSep}: - return substr(path, i+1) - result = "" - -proc isRootDir*(path: string): bool {. - noSideEffect, rtl, extern: "nos$1".} = - ## Checks whether a given `path` is a root directory - result = parentDirPos(path) < 0 - -iterator parentDirs*(path: string, fromRoot=false, inclusive=true): string = - ## Walks over all parent directories of a given `path` - ## - ## If `fromRoot` is set, the traversal will start from the file system root - ## diretory. If `inclusive` is set, the original argument will be included - ## in the traversal. - ## - ## Relative paths won't be expanded by this proc. Instead, it will traverse - ## only the directories appearing in the relative path. - if not fromRoot: - var current = path - if inclusive: yield path - while true: - if current.isRootDir: break - current = current.parentDir - yield current - else: - for i in countup(0, path.len - 2): # ignore the last / - # deal with non-normalized paths such as /foo//bar//baz - if path[i] in {DirSep, AltSep} and - (i == 0 or path[i-1] notin {DirSep, AltSep}): - yield path.substr(0, i) - - if inclusive: yield path - -proc `/../` * (head, tail: string): string {.noSideEffect.} = - ## The same as ``parentDir(head) / tail`` unless there is no parent directory. - ## Then ``head / tail`` is performed instead. - let sepPos = parentDirPos(head) - if sepPos >= 0: - result = substr(head, 0, sepPos-1) / tail - else: - result = head / tail - -proc normExt(ext: string): string = - if ext == "" or ext[0] == ExtSep: result = ext # no copy needed here - else: result = ExtSep & ext - -proc searchExtPos(s: string): int = - # BUGFIX: do not search until 0! .DS_Store is no file extension! - result = -1 - for i in countdown(len(s)-1, 1): - if s[i] == ExtSep: - result = i - break - elif s[i] in {DirSep, AltSep}: - break # do not skip over path - -proc splitFile*(path: string): tuple[dir, name, ext: string] {. - noSideEffect, rtl, extern: "nos$1".} = - ## Splits a filename into (dir, filename, extension). - ## `dir` does not end in `DirSep`. - ## `extension` includes the leading dot. - ## - ## Example: - ## - ## .. code-block:: nim - ## var (dir, name, ext) = splitFile("usr/local/nimc.html") - ## assert dir == "usr/local" - ## assert name == "nimc" - ## assert ext == ".html" - ## - ## If `path` has no extension, `ext` is the empty string. - ## If `path` has no directory component, `dir` is the empty string. - ## If `path` has no filename component, `name` and `ext` are empty strings. - if path.len == 0 or path[path.len-1] in {DirSep, AltSep}: - result = (path, "", "") - else: - var sepPos = -1 - var dotPos = path.len - for i in countdown(len(path)-1, 0): - if path[i] == ExtSep: - if dotPos == path.len and i > 0 and - path[i-1] notin {DirSep, AltSep}: dotPos = i - elif path[i] in {DirSep, AltSep}: - sepPos = i - break - result.dir = substr(path, 0, sepPos-1) - result.name = substr(path, sepPos+1, dotPos-1) - result.ext = substr(path, dotPos) - -proc extractFilename*(path: string): string {. - noSideEffect, rtl, extern: "nos$1".} = - ## Extracts the filename of a given `path`. This is the same as - ## ``name & ext`` from ``splitFile(path)``. - if path.len == 0 or path[path.len-1] in {DirSep, AltSep}: - result = "" - else: - result = splitPath(path).tail - proc expandFilename*(filename: string): string {.rtl, extern: "nos$1", tags: [ReadDirEffect].} = ## Returns the full path of `filename`, raises OSError in case of an error. @@ -757,61 +343,6 @@ proc expandFilename*(filename: string): string {.rtl, extern: "nos$1", if r.isNil: raiseOSError(osLastError()) setLen(result, c_strlen(result)) -proc changeFileExt*(filename, ext: string): string {. - noSideEffect, rtl, extern: "nos$1".} = - ## Changes the file extension to `ext`. - ## - ## If the `filename` has no extension, `ext` will be added. - ## If `ext` == "" then any extension is removed. - ## `Ext` should be given without the leading '.', because some - ## filesystems may use a different character. (Although I know - ## of none such beast.) - var extPos = searchExtPos(filename) - if extPos < 0: result = filename & normExt(ext) - else: result = substr(filename, 0, extPos-1) & normExt(ext) - -proc addFileExt*(filename, ext: string): string {. - noSideEffect, rtl, extern: "nos$1".} = - ## Adds the file extension `ext` to `filename`, unless - ## `filename` already has an extension. - ## - ## `Ext` should be given without the leading '.', because some - ## filesystems may use a different character. - ## (Although I know of none such beast.) - var extPos = searchExtPos(filename) - if extPos < 0: result = filename & normExt(ext) - else: result = filename - -proc cmpPaths*(pathA, pathB: string): int {. - noSideEffect, rtl, extern: "nos$1".} = - ## Compares two paths. - ## - ## On a case-sensitive filesystem this is done - ## case-sensitively otherwise case-insensitively. Returns: - ## - ## | 0 iff pathA == pathB - ## | < 0 iff pathA < pathB - ## | > 0 iff pathA > pathB - if FileSystemCaseSensitive: - result = cmp(pathA, pathB) - else: - result = cmpIgnoreCase(pathA, pathB) - -proc isAbsolute*(path: string): bool {.rtl, noSideEffect, extern: "nos$1".} = - ## Checks whether a given `path` is absolute. - ## - ## On Windows, network paths are considered absolute too. - when doslike: - var len = len(path) - result = (len > 1 and path[0] in {'/', '\\'}) or - (len > 2 and path[0] in Letters and path[1] == ':') - elif defined(macos): - result = path.len > 0 and path[0] != ':' - elif defined(RISCOS): - result = path[0] == '$' - elif defined(posix): - result = path[0] == '/' - when defined(Windows): proc openHandle(path: string, followSymlink=true): Handle = var flags = FILE_FLAG_BACKUP_SEMANTICS or FILE_ATTRIBUTE_NORMAL @@ -1649,24 +1180,7 @@ proc exclFilePermissions*(filename: string, ## setFilePermissions(filename, getFilePermissions(filename)-permissions) setFilePermissions(filename, getFilePermissions(filename)-permissions) -proc getHomeDir*(): string {.rtl, extern: "nos$1", tags: [ReadEnvEffect].} = - ## Returns the home directory of the current user. - ## - ## This proc is wrapped by the expandTilde proc for the convenience of - ## processing paths coming from user configuration files. - when defined(windows): return string(getEnv("USERPROFILE")) & "\\" - else: return string(getEnv("HOME")) & "/" - -proc getConfigDir*(): string {.rtl, extern: "nos$1", tags: [ReadEnvEffect].} = - ## Returns the config directory of the current user for applications. - when defined(windows): return string(getEnv("APPDATA")) & "\\" - else: return string(getEnv("HOME")) & "/.config/" - -proc getTempDir*(): string {.rtl, extern: "nos$1", tags: [ReadEnvEffect].} = - ## Returns the temporary directory of the current user for applications to - ## save temporary files in. - when defined(windows): return string(getEnv("TEMP")) & "\\" - else: return "/tmp/" +include ospaths proc expandSymlink*(symlinkPath: string): string = ## Returns a string representing the path to which the symbolic link points. @@ -1907,42 +1421,6 @@ proc getFileSize*(file: string): BiggestInt {.rtl, extern: "nos$1", close(f) else: raiseOSError(osLastError()) -proc expandTilde*(path: string): string {.tags: [ReadEnvEffect].} = - ## Expands a path starting with ``~/`` to a full path. - ## - ## If `path` starts with the tilde character and is followed by `/` or `\\` - ## this proc will return the reminder of the path appended to the result of - ## the getHomeDir() proc, otherwise the input path will be returned without - ## modification. - ## - ## The behaviour of this proc is the same on the Windows platform despite not - ## having this convention. Example: - ## - ## .. code-block:: nim - ## let configFile = expandTilde("~" / "appname.cfg") - ## echo configFile - ## # --> C:\Users\amber\appname.cfg - if len(path) > 1 and path[0] == '~' and (path[1] == '/' or path[1] == '\\'): - result = getHomeDir() / path[2..len(path)-1] - else: - result = path - -proc findExe*(exe: string): string {.tags: [ReadDirEffect, ReadEnvEffect].} = - ## Searches for `exe` in the current working directory and then - ## in directories listed in the ``PATH`` environment variable. - ## Returns "" if the `exe` cannot be found. On DOS-like platforms, `exe` - ## is added the `ExeExt <#ExeExt>`_ file extension if it has none. - result = addFileExt(exe, os.ExeExt) - if existsFile(result): return - var path = string(os.getEnv("PATH")) - for candidate in split(path, PathSep): - when defined(windows): - var x = candidate / result - else: - var x = expandTilde(candidate) / result - if existsFile(x): return x - result = "" - when defined(Windows): type DeviceId* = int32 diff --git a/lib/pure/ospaths.nim b/lib/pure/ospaths.nim new file mode 100644 index 000000000..55962a6a5 --- /dev/null +++ b/lib/pure/ospaths.nim @@ -0,0 +1,560 @@ +# +# +# Nim's Runtime Library +# (c) Copyright 2015 Andreas Rumpf +# +# See the file "copying.txt", included in this +# distribution, for details about the copyright. +# + +# Included by the ``os`` module but a module in its own right for NimScript +# support. + +when defined(nimscript): + {.pragma: rtl.} + {.push hint[ConvFromXtoItselfNotNeeded]:off.} + +when not declared(getEnv) or defined(nimscript): + type + ReadEnvEffect* = object of ReadIOEffect ## effect that denotes a read + ## from an environment variable + WriteEnvEffect* = object of WriteIOEffect ## effect that denotes a write + ## to an environment variable + + ReadDirEffect* = object of ReadIOEffect ## effect that denotes a write + ## operation to the directory structure + WriteDirEffect* = object of WriteIOEffect ## effect that denotes a write operation to + ## the directory structure + + OSErrorCode* = distinct int32 ## Specifies an OS Error Code. + + {.deprecated: [FReadEnv: ReadEnvEffect, FWriteEnv: WriteEnvEffect, + FReadDir: ReadDirEffect, + FWriteDir: WriteDirEffect, + TOSErrorCode: OSErrorCode + ].} + const + doslike = defined(windows) or defined(OS2) or defined(DOS) + # DOS-like filesystem + + when defined(Nimdoc): # only for proper documentation: + const + CurDir* = '.' + ## The constant string used by the operating system to refer to the + ## current directory. + ## + ## For example: '.' for POSIX or ':' for the classic Macintosh. + + ParDir* = ".." + ## The constant string used by the operating system to refer to the + ## parent directory. + ## + ## For example: ".." for POSIX or "::" for the classic Macintosh. + + DirSep* = '/' + ## The character used by the operating system to separate pathname + ## components, for example, '/' for POSIX or ':' for the classic + ## Macintosh. + + AltSep* = '/' + ## An alternative character used by the operating system to separate + ## pathname components, or the same as `DirSep` if only one separator + ## character exists. This is set to '/' on Windows systems where `DirSep` + ## is a backslash. + + PathSep* = ':' + ## The character conventionally used by the operating system to separate + ## search patch components (as in PATH), such as ':' for POSIX or ';' for + ## Windows. + + FileSystemCaseSensitive* = true + ## true if the file system is case sensitive, false otherwise. Used by + ## `cmpPaths` to compare filenames properly. + + ExeExt* = "" + ## The file extension of native executables. For example: + ## "" for POSIX, "exe" on Windows. + + ScriptExt* = "" + ## The file extension of a script file. For example: "" for POSIX, + ## "bat" on Windows. + + DynlibFormat* = "lib$1.so" + ## The format string to turn a filename into a `DLL`:idx: file (also + ## called `shared object`:idx: on some operating systems). + + elif defined(macos): + const + CurDir* = ':' + ParDir* = "::" + DirSep* = ':' + AltSep* = Dirsep + PathSep* = ',' + FileSystemCaseSensitive* = false + ExeExt* = "" + ScriptExt* = "" + DynlibFormat* = "$1.dylib" + + # MacOS paths + # =========== + # MacOS directory separator is a colon ":" which is the only character not + # allowed in filenames. + # + # A path containing no colon or which begins with a colon is a partial path. + # E.g. ":kalle:petter" ":kalle" "kalle" + # + # All other paths are full (absolute) paths. E.g. "HD:kalle:" "HD:" + # When generating paths, one is safe if one ensures that all partial paths + # begin with a colon, and all full paths end with a colon. + # In full paths the first name (e g HD above) is the name of a mounted + # volume. + # These names are not unique, because, for instance, two diskettes with the + # same names could be inserted. This means that paths on MacOS are not + # waterproof. In case of equal names the first volume found will do. + # Two colons "::" are the relative path to the parent. Three is to the + # grandparent etc. + elif doslike: + const + CurDir* = '.' + ParDir* = ".." + DirSep* = '\\' # seperator within paths + AltSep* = '/' + PathSep* = ';' # seperator between paths + FileSystemCaseSensitive* = false + ExeExt* = "exe" + ScriptExt* = "bat" + DynlibFormat* = "$1.dll" + elif defined(PalmOS) or defined(MorphOS): + const + DirSep* = '/' + AltSep* = Dirsep + PathSep* = ';' + ParDir* = ".." + FileSystemCaseSensitive* = false + ExeExt* = "" + ScriptExt* = "" + DynlibFormat* = "$1.prc" + elif defined(RISCOS): + const + DirSep* = '.' + AltSep* = '.' + ParDir* = ".." # is this correct? + PathSep* = ',' + FileSystemCaseSensitive* = true + ExeExt* = "" + ScriptExt* = "" + DynlibFormat* = "lib$1.so" + else: # UNIX-like operating system + const + CurDir* = '.' + ParDir* = ".." + DirSep* = '/' + AltSep* = DirSep + PathSep* = ':' + FileSystemCaseSensitive* = true + ExeExt* = "" + ScriptExt* = "" + DynlibFormat* = when defined(macosx): "lib$1.dylib" else: "lib$1.so" + + const + ExtSep* = '.' + ## The character which separates the base filename from the extension; + ## for example, the '.' in ``os.nim``. + + + proc joinPath*(head, tail: string): string {. + noSideEffect, rtl, extern: "nos$1".} = + ## Joins two directory names to one. + ## + ## For example on Unix: + ## + ## .. code-block:: nim + ## joinPath("usr", "lib") + ## + ## results in: + ## + ## .. code-block:: nim + ## "usr/lib" + ## + ## If head is the empty string, tail is returned. If tail is the empty + ## string, head is returned with a trailing path separator. If tail starts + ## with a path separator it will be removed when concatenated to head. Other + ## path separators not located on boundaries won't be modified. More + ## examples on Unix: + ## + ## .. code-block:: nim + ## assert joinPath("usr", "") == "usr/" + ## assert joinPath("", "lib") == "lib" + ## assert joinPath("", "/lib") == "/lib" + ## assert joinPath("usr/", "/lib") == "usr/lib" + if len(head) == 0: + result = tail + elif head[len(head)-1] in {DirSep, AltSep}: + if tail[0] in {DirSep, AltSep}: + result = head & substr(tail, 1) + else: + result = head & tail + else: + if tail[0] in {DirSep, AltSep}: + result = head & tail + else: + result = head & DirSep & tail + + proc joinPath*(parts: varargs[string]): string {.noSideEffect, + rtl, extern: "nos$1OpenArray".} = + ## The same as `joinPath(head, tail)`, but works with any number of directory + ## parts. You need to pass at least one element or the proc will assert in + ## debug builds and crash on release builds. + result = parts[0] + for i in 1..high(parts): + result = joinPath(result, parts[i]) + + proc `/` * (head, tail: string): string {.noSideEffect.} = + ## The same as ``joinPath(head, tail)`` + ## + ## Here are some examples for Unix: + ## + ## .. code-block:: nim + ## assert "usr" / "" == "usr/" + ## assert "" / "lib" == "lib" + ## assert "" / "/lib" == "/lib" + ## assert "usr/" / "/lib" == "usr/lib" + return joinPath(head, tail) + + proc splitPath*(path: string): tuple[head, tail: string] {. + noSideEffect, rtl, extern: "nos$1".} = + ## Splits a directory into (head, tail), so that + ## ``head / tail == path`` (except for edge cases like "/usr"). + ## + ## Examples: + ## + ## .. code-block:: nim + ## splitPath("usr/local/bin") -> ("usr/local", "bin") + ## splitPath("usr/local/bin/") -> ("usr/local/bin", "") + ## splitPath("bin") -> ("", "bin") + ## splitPath("/bin") -> ("", "bin") + ## splitPath("") -> ("", "") + var sepPos = -1 + for i in countdown(len(path)-1, 0): + if path[i] in {DirSep, AltSep}: + sepPos = i + break + if sepPos >= 0: + result.head = substr(path, 0, sepPos-1) + result.tail = substr(path, sepPos+1) + else: + result.head = "" + result.tail = path + + proc parentDirPos(path: string): int = + var q = 1 + if len(path) >= 1 and path[len(path)-1] in {DirSep, AltSep}: q = 2 + for i in countdown(len(path)-q, 0): + if path[i] in {DirSep, AltSep}: return i + result = -1 + + proc parentDir*(path: string): string {. + noSideEffect, rtl, extern: "nos$1".} = + ## Returns the parent directory of `path`. + ## + ## This is often the same as the ``head`` result of ``splitPath``. + ## If there is no parent, "" is returned. + ## | Example: ``parentDir("/usr/local/bin") == "/usr/local"``. + ## | Example: ``parentDir("/usr/local/bin/") == "/usr/local"``. + let sepPos = parentDirPos(path) + if sepPos >= 0: + result = substr(path, 0, sepPos-1) + else: + result = "" + + proc tailDir*(path: string): string {. + noSideEffect, rtl, extern: "nos$1".} = + ## Returns the tail part of `path`.. + ## + ## | Example: ``tailDir("/usr/local/bin") == "local/bin"``. + ## | Example: ``tailDir("usr/local/bin/") == "local/bin"``. + ## | Example: ``tailDir("bin") == ""``. + var q = 1 + if len(path) >= 1 and path[len(path)-1] in {DirSep, AltSep}: q = 2 + for i in 0..len(path)-q: + if path[i] in {DirSep, AltSep}: + return substr(path, i+1) + result = "" + + proc isRootDir*(path: string): bool {. + noSideEffect, rtl, extern: "nos$1".} = + ## Checks whether a given `path` is a root directory + result = parentDirPos(path) < 0 + + iterator parentDirs*(path: string, fromRoot=false, inclusive=true): string = + ## Walks over all parent directories of a given `path` + ## + ## If `fromRoot` is set, the traversal will start from the file system root + ## diretory. If `inclusive` is set, the original argument will be included + ## in the traversal. + ## + ## Relative paths won't be expanded by this proc. Instead, it will traverse + ## only the directories appearing in the relative path. + if not fromRoot: + var current = path + if inclusive: yield path + while true: + if current.isRootDir: break + current = current.parentDir + yield current + else: + for i in countup(0, path.len - 2): # ignore the last / + # deal with non-normalized paths such as /foo//bar//baz + if path[i] in {DirSep, AltSep} and + (i == 0 or path[i-1] notin {DirSep, AltSep}): + yield path.substr(0, i) + + if inclusive: yield path + + proc `/../` * (head, tail: string): string {.noSideEffect.} = + ## The same as ``parentDir(head) / tail`` unless there is no parent directory. + ## Then ``head / tail`` is performed instead. + let sepPos = parentDirPos(head) + if sepPos >= 0: + result = substr(head, 0, sepPos-1) / tail + else: + result = head / tail + + proc normExt(ext: string): string = + if ext == "" or ext[0] == ExtSep: result = ext # no copy needed here + else: result = ExtSep & ext + + proc searchExtPos(s: string): int = + # BUGFIX: do not search until 0! .DS_Store is no file extension! + result = -1 + for i in countdown(len(s)-1, 1): + if s[i] == ExtSep: + result = i + break + elif s[i] in {DirSep, AltSep}: + break # do not skip over path + + proc splitFile*(path: string): tuple[dir, name, ext: string] {. + noSideEffect, rtl, extern: "nos$1".} = + ## Splits a filename into (dir, filename, extension). + ## `dir` does not end in `DirSep`. + ## `extension` includes the leading dot. + ## + ## Example: + ## + ## .. code-block:: nim + ## var (dir, name, ext) = splitFile("usr/local/nimc.html") + ## assert dir == "usr/local" + ## assert name == "nimc" + ## assert ext == ".html" + ## + ## If `path` has no extension, `ext` is the empty string. + ## If `path` has no directory component, `dir` is the empty string. + ## If `path` has no filename component, `name` and `ext` are empty strings. + if path.len == 0 or path[path.len-1] in {DirSep, AltSep}: + result = (path, "", "") + else: + var sepPos = -1 + var dotPos = path.len + for i in countdown(len(path)-1, 0): + if path[i] == ExtSep: + if dotPos == path.len and i > 0 and + path[i-1] notin {DirSep, AltSep}: dotPos = i + elif path[i] in {DirSep, AltSep}: + sepPos = i + break + result.dir = substr(path, 0, sepPos-1) + result.name = substr(path, sepPos+1, dotPos-1) + result.ext = substr(path, dotPos) + + proc extractFilename*(path: string): string {. + noSideEffect, rtl, extern: "nos$1".} = + ## Extracts the filename of a given `path`. This is the same as + ## ``name & ext`` from ``splitFile(path)``. + if path.len == 0 or path[path.len-1] in {DirSep, AltSep}: + result = "" + else: + result = splitPath(path).tail + + + proc changeFileExt*(filename, ext: string): string {. + noSideEffect, rtl, extern: "nos$1".} = + ## Changes the file extension to `ext`. + ## + ## If the `filename` has no extension, `ext` will be added. + ## If `ext` == "" then any extension is removed. + ## `Ext` should be given without the leading '.', because some + ## filesystems may use a different character. (Although I know + ## of none such beast.) + var extPos = searchExtPos(filename) + if extPos < 0: result = filename & normExt(ext) + else: result = substr(filename, 0, extPos-1) & normExt(ext) + + proc addFileExt*(filename, ext: string): string {. + noSideEffect, rtl, extern: "nos$1".} = + ## Adds the file extension `ext` to `filename`, unless + ## `filename` already has an extension. + ## + ## `Ext` should be given without the leading '.', because some + ## filesystems may use a different character. + ## (Although I know of none such beast.) + var extPos = searchExtPos(filename) + if extPos < 0: result = filename & normExt(ext) + else: result = filename + + proc cmpPaths*(pathA, pathB: string): int {. + noSideEffect, rtl, extern: "nos$1".} = + ## Compares two paths. + ## + ## On a case-sensitive filesystem this is done + ## case-sensitively otherwise case-insensitively. Returns: + ## + ## | 0 iff pathA == pathB + ## | < 0 iff pathA < pathB + ## | > 0 iff pathA > pathB + if FileSystemCaseSensitive: + result = cmp(pathA, pathB) + else: + when defined(nimscript): + result = cmpic(pathA, pathB) + else: + result = cmpIgnoreCase(pathA, pathB) + + proc isAbsolute*(path: string): bool {.rtl, noSideEffect, extern: "nos$1".} = + ## Checks whether a given `path` is absolute. + ## + ## On Windows, network paths are considered absolute too. + when doslike: + var len = len(path) + result = (len > 1 and path[0] in {'/', '\\'}) or + (len > 2 and path[0] in {'a'..'z', 'A'..'Z'} and path[1] == ':') + elif defined(macos): + result = path.len > 0 and path[0] != ':' + elif defined(RISCOS): + result = path[0] == '$' + elif defined(posix): + result = path[0] == '/' + + proc unixToNativePath*(path: string, drive=""): string {. + noSideEffect, rtl, extern: "nos$1".} = + ## Converts an UNIX-like path to a native one. + ## + ## On an UNIX system this does nothing. Else it converts + ## '/', '.', '..' to the appropriate things. + ## + ## On systems with a concept of "drives", `drive` is used to determine + ## which drive label to use during absolute path conversion. + ## `drive` defaults to the drive of the current working directory, and is + ## ignored on systems that do not have a concept of "drives". + + when defined(unix): + result = path + else: + var start: int + if path[0] == '/': + # an absolute path + when doslike: + if drive != "": + result = drive & ":" & DirSep + else: + result = $DirSep + elif defined(macos): + result = "" # must not start with ':' + else: + result = $DirSep + start = 1 + elif path[0] == '.' and path[1] == '/': + # current directory + result = $CurDir + start = 2 + else: + result = "" + start = 0 + + var i = start + while i < len(path): # ../../../ --> :::: + if path[i] == '.' and path[i+1] == '.' and path[i+2] == '/': + # parent directory + when defined(macos): + if result[high(result)] == ':': + add result, ':' + else: + add result, ParDir + else: + add result, ParDir & DirSep + inc(i, 3) + elif path[i] == '/': + add result, DirSep + inc(i) + else: + add result, path[i] + inc(i) + +when declared(getEnv) or defined(nimscript): + proc getHomeDir*(): string {.rtl, extern: "nos$1", tags: [ReadEnvEffect].} = + ## Returns the home directory of the current user. + ## + ## This proc is wrapped by the expandTilde proc for the convenience of + ## processing paths coming from user configuration files. + when defined(windows): return string(getEnv("USERPROFILE")) & "\\" + else: return string(getEnv("HOME")) & "/" + + proc getConfigDir*(): string {.rtl, extern: "nos$1", tags: [ReadEnvEffect].} = + ## Returns the config directory of the current user for applications. + when defined(windows): return string(getEnv("APPDATA")) & "\\" + else: return string(getEnv("HOME")) & "/.config/" + + proc getTempDir*(): string {.rtl, extern: "nos$1", tags: [ReadEnvEffect].} = + ## Returns the temporary directory of the current user for applications to + ## save temporary files in. + when defined(windows): return string(getEnv("TEMP")) & "\\" + else: return "/tmp/" + + proc expandTilde*(path: string): string {.tags: [ReadEnvEffect].} = + ## Expands a path starting with ``~/`` to a full path. + ## + ## If `path` starts with the tilde character and is followed by `/` or `\\` + ## this proc will return the reminder of the path appended to the result of + ## the getHomeDir() proc, otherwise the input path will be returned without + ## modification. + ## + ## The behaviour of this proc is the same on the Windows platform despite not + ## having this convention. Example: + ## + ## .. code-block:: nim + ## let configFile = expandTilde("~" / "appname.cfg") + ## echo configFile + ## # --> C:\Users\amber\appname.cfg + if len(path) > 1 and path[0] == '~' and (path[1] == '/' or path[1] == '\\'): + result = getHomeDir() / path.substr(2) + else: + result = path + + when not declared(split): + iterator split(s: string, sep: char): string = + var last = 0 + if len(s) > 0: + while last <= len(s): + var first = last + while last < len(s) and s[last] != sep: inc(last) + yield substr(s, first, last-1) + inc(last) + + proc findExe*(exe: string): string {.tags: [ReadDirEffect, ReadEnvEffect].} = + ## Searches for `exe` in the current working directory and then + ## in directories listed in the ``PATH`` environment variable. + ## Returns "" if the `exe` cannot be found. On DOS-like platforms, `exe` + ## is added the `ExeExt <#ExeExt>`_ file extension if it has none. + result = addFileExt(exe, ExeExt) + if existsFile(result): return + var path = string(getEnv("PATH")) + for candidate in split(path, PathSep): + when defined(windows): + var x = candidate / result + else: + var x = expandTilde(candidate) / result + if existsFile(x): return x + result = "" + +when defined(nimscript): + {.pop.} # hint[ConvFromXtoItselfNotNeeded]:off diff --git a/lib/system/nimscript.nim b/lib/system/nimscript.nim index a1a653cf5..38e1f81a7 100644 --- a/lib/system/nimscript.nim +++ b/lib/system/nimscript.nim @@ -19,6 +19,7 @@ proc listFiles*(dir: string): seq[string] = builtin proc removeDir(dir: string) = builtin proc removeFile(dir: string) = builtin proc moveFile(src, dest: string) = builtin +proc copyFile(src, dest: string) = builtin proc createDir(dir: string) = builtin proc getOsError: string = builtin proc setCurrentDir(dir: string) = builtin @@ -30,6 +31,25 @@ proc switch*(key: string, val="") = builtin proc getCommand*(): string = builtin proc setCommand*(cmd: string) = builtin proc cmpIgnoreStyle(a, b: string): int = builtin +proc cmpIgnoreCase(a, b: string): int = builtin + +proc cmpic*(a, b: string): int = cmpIgnoreCase(a, b) + +proc getEnv*(key: string): string = builtin +proc existsEnv*(key: string): bool = builtin +proc fileExists*(filename: string): bool = builtin +proc dirExists*(dir: string): bool = builtin + +proc existsFile*(filename: string): bool = fileExists(filename) +proc existsDir*(dir: string): bool = dirExists(dir) + +proc toExe*(filename: string): string = + ## On Windows adds ".exe" to `filename`, else returns `filename` unmodified. + (when defined(windows): filename & ".exe" else: filename) + +proc toDll*(filename: string): string = + ## On Windows adds ".dll" to `filename`, on Posix produces "lib$filename.so". + (when defined(windows): filename & ".dll" else: "lib" & filename & ".so") proc strip(s: string): string = var i = 0 @@ -79,6 +99,11 @@ proc mvFile*(`from`, to: string) {.raises: [OSError].} = moveFile `from`, to checkOsError() +proc cpFile*(`from`, to: string) {.raises: [OSError].} = + log "mvFile: " & `from` & ", " & to: + copyFile `from`, to + checkOsError() + proc exec*(command: string, input = "", cache = "") = ## Executes an external process. log "exec: " & command: @@ -120,7 +145,7 @@ template withDir*(dir: string; body: untyped): untyped = ## ## If you need a permanent change, use the `cd() <#cd>`_ proc. Usage example: ## - ## .. code-block:: nimrod + ## .. code-block:: nim ## withDir "foo": ## # inside foo ## #back to last dir diff --git a/todo.txt b/todo.txt index 82d1f32db..463ffc3b1 100644 --- a/todo.txt +++ b/todo.txt @@ -1,7 +1,7 @@ version 0.11.4 ============== -- make ``os`` and ``math`` work with NimScript +- document NimScript - document special cased varargs[untyped] and varargs[typed] - The remaining bugs of the lambda lifting pass that is responsible to enable From 49869a2b10d73dac719690f3796a0584be38c0bb Mon Sep 17 00:00:00 2001 From: Yuriy Glukhov Date: Thu, 3 Sep 2015 19:20:23 +0300 Subject: [PATCH 0894/1263] when nimvm stmt proof of concept --- compiler/ccgexprs.nim | 3 +++ compiler/jsgen.nim | 3 +++ compiler/semexprs.nim | 41 ++++++++++++++++++++++++++++++---------- compiler/semparallel.nim | 2 +- compiler/sempass2.nim | 2 +- compiler/vmgen.nim | 5 ++++- 6 files changed, 43 insertions(+), 13 deletions(-) diff --git a/compiler/ccgexprs.nim b/compiler/ccgexprs.nim index c237eeffa..ba8ced52a 100644 --- a/compiler/ccgexprs.nim +++ b/compiler/ccgexprs.nim @@ -2069,6 +2069,9 @@ proc expr(p: BProc, n: PNode, d: var TLoc) = of nkStmtList: for i in countup(0, sonsLen(n) - 1): genStmts(p, n.sons[i]) of nkIfExpr, nkIfStmt: genIf(p, n, d) + of nkWhen: + # This should be a "when nimvm" node. + expr(p, n.sons[1].sons[0], d) of nkObjDownConv: downConv(p, n, d) of nkObjUpConv: upConv(p, n, d) of nkChckRangeF: genRangeChck(p, n, d, "chckRangeF") diff --git a/compiler/jsgen.nim b/compiler/jsgen.nim index c72365cce..36caf5e3e 100644 --- a/compiler/jsgen.nim +++ b/compiler/jsgen.nim @@ -1687,6 +1687,9 @@ proc gen(p: PProc, n: PNode, r: var TCompRes) = gen(p, lastSon(n), r) of nkBlockStmt, nkBlockExpr: genBlock(p, n, r) of nkIfStmt, nkIfExpr: genIf(p, n, r) + of nkWhen: + # This is "when nimvm" node + gen(p, n.sons[1].sons[0], r) of nkWhileStmt: genWhileStmt(p, n) of nkVarSection, nkLetSection: genVarStmt(p, n) of nkConstSection: discard diff --git a/compiler/semexprs.nim b/compiler/semexprs.nim index d6f6e3a2c..fe74e75dd 100644 --- a/compiler/semexprs.nim +++ b/compiler/semexprs.nim @@ -1764,22 +1764,39 @@ proc semWhen(c: PContext, n: PNode, semCheck = true): PNode = if semCheck: result = semStmt(c, e) # do not open a new scope! else: result = e + # Check if the node is "when nimvm" + # when nimvm: + # ... + # else: + # ... + let whenNimvm = n.sons.len == 2 and n.sons[0].kind == nkElifBranch and + n.sons[1].kind == nkElse and n.sons[0].sons[0].kind == nkIdent and + lookUp(c, n.sons[0].sons[0]).magic == mNimvm + for i in countup(0, sonsLen(n) - 1): var it = n.sons[i] case it.kind of nkElifBranch, nkElifExpr: checkSonsLen(it, 2) - var e = semConstExpr(c, it.sons[0]) - if e.kind != nkIntLit: - # can happen for cascading errors, assume false - # InternalError(n.info, "semWhen") - discard - elif e.intVal != 0 and result == nil: - setResult(it.sons[1]) + if whenNimvm: + if semCheck: + it.sons[1] = semStmt(c, it.sons[1]) + result = n # when nimvm is not elimited until codegen + else: + var e = semConstExpr(c, it.sons[0]) + if e.kind != nkIntLit: + # can happen for cascading errors, assume false + # InternalError(n.info, "semWhen") + discard + elif e.intVal != 0 and result == nil: + setResult(it.sons[1]) of nkElse, nkElseExpr: checkSonsLen(it, 1) - if result == nil: - setResult(it.sons[0]) + if result == nil or whenNimvm: + if semCheck: + it.sons[0] = semStmt(c, it.sons[0]) + if result == nil: + result = it.sons[0] else: illFormedAst(n) if result == nil: result = newNodeI(nkEmpty, n.info) @@ -2162,7 +2179,11 @@ proc semExpr(c: PContext, n: PNode, flags: TExprFlags = {}): PNode = result = semWhen(c, n, true) else: result = semWhen(c, n, false) - result = semExpr(c, result, flags) + if result == n: + # This is a "when nimvm" stmt. + result = semWhen(c, n, true) + else: + result = semExpr(c, result, flags) of nkBracketExpr: checkMinSonsLen(n, 1) var s = qualifiedLookUp(c, n.sons[0], {checkUndeclared}) diff --git a/compiler/semparallel.nim b/compiler/semparallel.nim index fbcd6b6da..36c63d038 100644 --- a/compiler/semparallel.nim +++ b/compiler/semparallel.nim @@ -363,7 +363,7 @@ proc analyse(c: var AnalysisCtx; n: PNode) = else: internalError(it.info, "slot already has a lower bound") if not isSpawned: analyse(c, value) of nkCaseStmt: analyseCase(c, n) - of nkIfStmt, nkIfExpr: analyseIf(c, n) + of nkWhen, nkIfStmt, nkIfExpr: analyseIf(c, n) of nkWhileStmt: analyse(c, n.sons[0]) # 'while true' loop? diff --git a/compiler/sempass2.nim b/compiler/sempass2.nim index d363eee77..272412b04 100644 --- a/compiler/sempass2.nim +++ b/compiler/sempass2.nim @@ -735,7 +735,7 @@ proc track(tracked: PEffects, n: PNode) = # since 'var (a, b): T = ()' is not even allowed, there is always type # inference for (a, b) and thus no nil checking is necessary. of nkCaseStmt: trackCase(tracked, n) - of nkIfStmt, nkIfExpr: trackIf(tracked, n) + of nkWhen, nkIfStmt, nkIfExpr: trackIf(tracked, n) of nkBlockStmt, nkBlockExpr: trackBlock(tracked, n.sons[1]) of nkWhileStmt: track(tracked, n.sons[0]) diff --git a/compiler/vmgen.nim b/compiler/vmgen.nim index 237a44e18..64a18a731 100644 --- a/compiler/vmgen.nim +++ b/compiler/vmgen.nim @@ -1664,7 +1664,10 @@ proc gen(c: PCtx; n: PNode; dest: var TDest; flags: TGenFlags = {}) = of nkBracketExpr: genArrAccess(c, n, dest, flags) of nkDerefExpr, nkHiddenDeref: genAddrDeref(c, n, dest, opcLdDeref, flags) of nkAddr, nkHiddenAddr: genAddrDeref(c, n, dest, opcAddrNode, flags) - of nkWhenStmt, nkIfStmt, nkIfExpr: genIf(c, n, dest) + of nkIfStmt, nkIfExpr: genIf(c, n, dest) + of nkWhenStmt: + # This is "when nimvm" node. Chose the first branch. + gen(c, n.sons[0].sons[1], dest) of nkCaseStmt: genCase(c, n, dest) of nkWhileStmt: unused(n, dest) From 790ef23c48329f0d0a5841aed3913b5a87119ca9 Mon Sep 17 00:00:00 2001 From: Yuriy Glukhov Date: Fri, 4 Sep 2015 19:23:58 +0300 Subject: [PATCH 0895/1263] nimvm is magic --- compiler/ast.nim | 3 ++- compiler/semfold.nim | 2 ++ lib/system.nim | 4 ++++ 3 files changed, 8 insertions(+), 1 deletion(-) diff --git a/compiler/ast.nim b/compiler/ast.nim index 0ad0a0718..aafe503dc 100644 --- a/compiler/ast.nim +++ b/compiler/ast.nim @@ -605,7 +605,8 @@ type mNBindSym, mLocals, mNCallSite, mEqIdent, mEqNimrodNode, mSameNodeType, mGetImpl, mNHint, mNWarning, mNError, - mInstantiationInfo, mGetTypeInfo, mNGenSym + mInstantiationInfo, mGetTypeInfo, mNGenSym, + mNimvm # things that we can evaluate safely at compile time, even if not asked for it: const diff --git a/compiler/semfold.nim b/compiler/semfold.nim index 2ab43a9c9..22cf05aa8 100644 --- a/compiler/semfold.nim +++ b/compiler/semfold.nim @@ -640,6 +640,8 @@ proc getConstExpr(m: PSym, n: PNode): PNode = of mNaN: result = newFloatNodeT(NaN, n) of mInf: result = newFloatNodeT(Inf, n) of mNegInf: result = newFloatNodeT(NegInf, n) + of mNimvm: + localError(n.info, "illegal context for 'nimvm' magic") else: if sfFakeConst notin s.flags: result = copyTree(s.ast) of {skProc, skMethod}: diff --git a/lib/system.nim b/lib/system.nim index 042813ae1..5bd8c56c7 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -1173,6 +1173,10 @@ const ## "i386", "alpha", "powerpc", "powerpc64", "powerpc64el", "sparc", ## "amd64", "mips", "mipsel", "arm", "arm64". + nimvm* {.magic: "Nimvm".}: bool = false + ## may be used only in "when" expression. + ## It is true in Nim VM context and false otherwise + seqShallowFlag = low(int) proc compileOption*(option: string): bool {. From 619ab0bcf0d4d56a86af88715117aed472edfe70 Mon Sep 17 00:00:00 2001 From: Doran Date: Fri, 4 Sep 2015 02:30:17 -0400 Subject: [PATCH 0896/1263] Include port in host header as expected --- lib/pure/httpclient.nim | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/lib/pure/httpclient.nim b/lib/pure/httpclient.nim index 98687359b..30b838b7e 100644 --- a/lib/pure/httpclient.nim +++ b/lib/pure/httpclient.nim @@ -402,7 +402,11 @@ proc request*(url: string, httpMethod: string, extraHeaders = "", headers.add(" HTTP/1.1\c\L") - add(headers, "Host: " & parseUri(url).hostname & "\c\L") + if r.port == "": + add(headers, "Host: " & r.hostname & "\c\L") + else: + add(headers, "Host: " & r.hostname & ":" & r.port & "\c\L") + if userAgent != "": add(headers, "User-Agent: " & userAgent & "\c\L") if proxy != nil and proxy.auth != "": @@ -580,7 +584,11 @@ proc generateHeaders(r: Uri, httpMethod: string, result.add("?" & r.query) result.add(" HTTP/1.1\c\L") - add(result, "Host: " & r.hostname & "\c\L") + if r.port == "": + add(result, "Host: " & r.hostname & "\c\L") + else: + add(result, "Host: " & r.hostname & ":" & r.port & "\c\L") + add(result, "Connection: Keep-Alive\c\L") if body.len > 0 and not headers.hasKey("Content-Length"): add(result, "Content-Length: " & $body.len & "\c\L") From d68181246571de5799059cf6402f1c578cd9421c Mon Sep 17 00:00:00 2001 From: Adam Strzelecki Date: Fri, 4 Sep 2015 23:02:43 +0200 Subject: [PATCH 0897/1263] compiler: Trim .nim files trailing whitespace via OSX: find . -name '*.nim' -exec sed -i '' -E 's/[[:space:]]+$//' {} + --- compiler/aliases.nim | 60 ++++++++--------- compiler/bitsets.nim | 40 +++++------ compiler/canonicalizer.nim | 132 ++++++++++++++++++------------------- compiler/cgmeth.nim | 84 +++++++++++------------ compiler/docgen2.nim | 10 +-- compiler/evaltempl.nim | 6 +- compiler/filter_tmpl.nim | 98 +++++++++++++-------------- compiler/filters.nim | 38 +++++------ compiler/forloops.nim | 10 +-- compiler/hlo.nim | 4 +- compiler/idents.nim | 34 +++++----- compiler/lists.nim | 48 +++++++------- compiler/magicsys.nim | 26 ++++---- compiler/nimblecmd.nim | 6 +- compiler/nimeval.nim | 2 +- compiler/nimlexbase.nim | 70 ++++++++++---------- compiler/nimsets.nim | 82 +++++++++++------------ compiler/nversion.nim | 2 +- compiler/passaux.nim | 24 +++---- compiler/patterns.nim | 10 +-- compiler/pbraces.nim | 6 +- compiler/procfind.nim | 22 +++---- compiler/rodutils.nim | 34 +++++----- compiler/ropes.nim | 2 +- compiler/saturate.nim | 2 +- compiler/semcall.nim | 2 +- compiler/semfields.nim | 10 +-- compiler/sigmatch.nim | 2 +- compiler/suggest.nim | 74 ++++++++++----------- compiler/syntaxes.nim | 102 ++++++++++++++-------------- compiler/tccgen.nim | 22 +++---- compiler/treetab.nim | 76 ++++++++++----------- 32 files changed, 570 insertions(+), 570 deletions(-) diff --git a/compiler/aliases.nim b/compiler/aliases.nim index 3f3d45ff7..3d3fc9a79 100644 --- a/compiler/aliases.nim +++ b/compiler/aliases.nim @@ -11,7 +11,7 @@ import ast, astalgo, types, trees, intsets, msgs - + type TAnalysisResult* = enum arNo, arMaybe, arYes @@ -21,42 +21,42 @@ proc isPartOfAux(a, b: PType, marker: var IntSet): TAnalysisResult proc isPartOfAux(n: PNode, b: PType, marker: var IntSet): TAnalysisResult = result = arNo case n.kind - of nkRecList: - for i in countup(0, sonsLen(n) - 1): + of nkRecList: + for i in countup(0, sonsLen(n) - 1): result = isPartOfAux(n.sons[i], b, marker) if result == arYes: return of nkRecCase: assert(n.sons[0].kind == nkSym) result = isPartOfAux(n.sons[0], b, marker) if result == arYes: return - for i in countup(1, sonsLen(n) - 1): + for i in countup(1, sonsLen(n) - 1): case n.sons[i].kind - of nkOfBranch, nkElse: + of nkOfBranch, nkElse: result = isPartOfAux(lastSon(n.sons[i]), b, marker) if result == arYes: return else: internalError("isPartOfAux(record case branch)") of nkSym: result = isPartOfAux(n.sym.typ, b, marker) else: internalError(n.info, "isPartOfAux()") - -proc isPartOfAux(a, b: PType, marker: var IntSet): TAnalysisResult = + +proc isPartOfAux(a, b: PType, marker: var IntSet): TAnalysisResult = result = arNo - if a == nil or b == nil: return - if containsOrIncl(marker, a.id): return + if a == nil or b == nil: return + if containsOrIncl(marker, a.id): return if compareTypes(a, b, dcEqIgnoreDistinct): return arYes case a.kind - of tyObject: + of tyObject: result = isPartOfAux(a.sons[0], b, marker) if result == arNo: result = isPartOfAux(a.n, b, marker) of tyGenericInst, tyDistinct: result = isPartOfAux(lastSon(a), b, marker) - of tyArray, tyArrayConstr, tySet, tyTuple: - for i in countup(0, sonsLen(a) - 1): + of tyArray, tyArrayConstr, tySet, tyTuple: + for i in countup(0, sonsLen(a) - 1): result = isPartOfAux(a.sons[i], b, marker) - if result == arYes: return + if result == arYes: return else: discard -proc isPartOf(a, b: PType): TAnalysisResult = +proc isPartOf(a, b: PType): TAnalysisResult = ## checks iff 'a' can be part of 'b'. Iterates over VALUE types! var marker = initIntSet() # watch out: parameters reversed because I'm too lazy to change the code... @@ -70,14 +70,14 @@ proc isPartOf*(a, b: PNode): TAnalysisResult = ## type. Since however type analysis is more expensive, we perform it only ## if necessary. ## - ## cases: + ## cases: ## ## YES-cases: ## x <| x # for general trees ## x[] <| x ## x[i] <| x ## x.f <| x - ## + ## ## NO-cases: ## x !<| y # depending on type and symbol kind ## x[constA] !<| x[constB] @@ -88,16 +88,16 @@ proc isPartOf*(a, b: PNode): TAnalysisResult = ## ## x[] ?<| y[] iff compatible type ## - ## + ## ## x[] ?<| y depending on type - ## + ## if a.kind == b.kind: case a.kind of nkSym: const varKinds = {skVar, skTemp, skProc} # same symbol: aliasing: if a.sym.id == b.sym.id: result = arYes - elif a.sym.kind in varKinds or b.sym.kind in varKinds: + elif a.sym.kind in varKinds or b.sym.kind in varKinds: # actually, a param could alias a var but we know that cannot happen # here. XXX make this more generic result = arNo @@ -110,11 +110,11 @@ proc isPartOf*(a, b: PNode): TAnalysisResult = if len(a) >= 2 and len(b) >= 2: # array accesses: if result == arYes and isDeepConstExpr(a[1]) and isDeepConstExpr(b[1]): - # we know it's the same array and we have 2 constant indexes; - # if they are + # we know it's the same array and we have 2 constant indexes; + # if they are var x = if a[1].kind == nkHiddenStdConv: a[1][1] else: a[1] var y = if b[1].kind == nkHiddenStdConv: b[1][1] else: b[1] - + if sameValue(x, y): result = arYes else: result = arNo # else: maybe and no are accurate @@ -122,7 +122,7 @@ proc isPartOf*(a, b: PNode): TAnalysisResult = # pointer derefs: if result != arYes: if isPartOf(a.typ, b.typ) != arNo: result = arMaybe - + of nkDotExpr: result = isPartOf(a[0], b[0]) if result != arNo: @@ -135,7 +135,7 @@ proc isPartOf*(a, b: PNode): TAnalysisResult = # weaken because of indirection: if result != arYes: if isPartOf(a.typ, b.typ) != arNo: result = arMaybe - + of nkHiddenStdConv, nkHiddenSubConv, nkConv: result = isPartOf(a[1], b[1]) of nkObjUpConv, nkObjDownConv, nkCheckedFieldExpr: @@ -144,7 +144,7 @@ proc isPartOf*(a, b: PNode): TAnalysisResult = # Calls return a new location, so a default of ``arNo`` is fine. else: # go down recursively; this is quite demanding: - const + const Ix0Kinds = {nkDotExpr, nkBracketExpr, nkObjUpConv, nkObjDownConv, nkCheckedFieldExpr} Ix1Kinds = {nkHiddenStdConv, nkHiddenSubConv, nkConv} @@ -153,17 +153,17 @@ proc isPartOf*(a, b: PNode): TAnalysisResult = of Ix0Kinds: # a* !<| b.f iff a* !<| b result = isPartOf(a, b[0]) - + of DerefKinds: - # a* !<| b[] iff + # a* !<| b[] iff if isPartOf(a.typ, b.typ) != arNo: result = isPartOf(a, b[0]) if result == arNo: result = arMaybe - + of Ix1Kinds: # a* !<| T(b) iff a* !<| b result = isPartOf(a, b[1]) - + of nkSym: # b is an atom, so we have to check a: case a.kind @@ -172,7 +172,7 @@ proc isPartOf*(a, b: PNode): TAnalysisResult = result = isPartOf(a[0], b) of Ix1Kinds: result = isPartOf(a[1], b) - + of DerefKinds: if isPartOf(a.typ, b.typ) != arNo: result = isPartOf(a[0], b) diff --git a/compiler/bitsets.nim b/compiler/bitsets.nim index a2324f4e2..5454ef5e7 100644 --- a/compiler/bitsets.nim +++ b/compiler/bitsets.nim @@ -10,12 +10,12 @@ # this unit handles Nim sets; it implements bit sets # the code here should be reused in the Nim standard library -type +type TBitSet* = seq[int8] # we use byte here to avoid issues with # cross-compiling; uint would be more efficient # however -const +const ElemSize* = sizeof(int8) * 8 proc bitSetInit*(b: var TBitSet, length: int) @@ -30,42 +30,42 @@ proc bitSetEquals*(x, y: TBitSet): bool proc bitSetContains*(x, y: TBitSet): bool # implementation -proc bitSetIn(x: TBitSet, e: BiggestInt): bool = +proc bitSetIn(x: TBitSet, e: BiggestInt): bool = result = (x[int(e div ElemSize)] and toU8(int(1 shl (e mod ElemSize)))) != toU8(0) -proc bitSetIncl(x: var TBitSet, elem: BiggestInt) = +proc bitSetIncl(x: var TBitSet, elem: BiggestInt) = assert(elem >= 0) x[int(elem div ElemSize)] = x[int(elem div ElemSize)] or toU8(int(1 shl (elem mod ElemSize))) -proc bitSetExcl(x: var TBitSet, elem: BiggestInt) = +proc bitSetExcl(x: var TBitSet, elem: BiggestInt) = x[int(elem div ElemSize)] = x[int(elem div ElemSize)] and not toU8(int(1 shl (elem mod ElemSize))) -proc bitSetInit(b: var TBitSet, length: int) = +proc bitSetInit(b: var TBitSet, length: int) = newSeq(b, length) -proc bitSetUnion(x: var TBitSet, y: TBitSet) = +proc bitSetUnion(x: var TBitSet, y: TBitSet) = for i in countup(0, high(x)): x[i] = x[i] or y[i] - -proc bitSetDiff(x: var TBitSet, y: TBitSet) = + +proc bitSetDiff(x: var TBitSet, y: TBitSet) = for i in countup(0, high(x)): x[i] = x[i] and not y[i] - -proc bitSetSymDiff(x: var TBitSet, y: TBitSet) = + +proc bitSetSymDiff(x: var TBitSet, y: TBitSet) = for i in countup(0, high(x)): x[i] = x[i] xor y[i] - -proc bitSetIntersect(x: var TBitSet, y: TBitSet) = + +proc bitSetIntersect(x: var TBitSet, y: TBitSet) = for i in countup(0, high(x)): x[i] = x[i] and y[i] - -proc bitSetEquals(x, y: TBitSet): bool = - for i in countup(0, high(x)): - if x[i] != y[i]: + +proc bitSetEquals(x, y: TBitSet): bool = + for i in countup(0, high(x)): + if x[i] != y[i]: return false result = true -proc bitSetContains(x, y: TBitSet): bool = - for i in countup(0, high(x)): - if (x[i] and not y[i]) != int8(0): +proc bitSetContains(x, y: TBitSet): bool = + for i in countup(0, high(x)): + if (x[i] and not y[i]) != int8(0): return false result = true diff --git a/compiler/canonicalizer.nim b/compiler/canonicalizer.nim index 6fcc57a91..dc6445035 100644 --- a/compiler/canonicalizer.nim +++ b/compiler/canonicalizer.nim @@ -30,39 +30,39 @@ type # # This is a good compromise between correctness and brevity. ;-) -const +const cb64 = [ "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", - "O", "P", "Q", "R", "S", "T" "U", "V", "W", "X", "Y", "Z", - "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", - "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", + "O", "P", "Q", "R", "S", "T" "U", "V", "W", "X", "Y", "Z", + "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", + "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", - "_A", "_B"] - -proc toBase64a(s: cstring, len: int): string = - ## encodes `s` into base64 representation. After `lineLen` characters, a - ## `newline` is added. - result = newStringOfCap(((len + 2) div 3) * 4) - var i = 0 - while i < s.len - 2: - let a = ord(s[i]) - let b = ord(s[i+1]) - let c = ord(s[i+2]) - result.add cb64[a shr 2] - result.add cb64[((a and 3) shl 4) or ((b and 0xF0) shr 4)] - result.add cb64[((b and 0x0F) shl 2) or ((c and 0xC0) shr 6)] - result.add cb64[c and 0x3F] - inc(i, 3) - if i < s.len-1: - let a = ord(s[i]) - let b = ord(s[i+1]) - result.add cb64[a shr 2] - result.add cb64[((a and 3) shl 4) or ((b and 0xF0) shr 4)] - result.add cb64[((b and 0x0F) shl 2)] - elif i < s.len: - let a = ord(s[i]) - result.add cb64[a shr 2] - result.add cb64[(a and 3) shl 4] + "_A", "_B"] + +proc toBase64a(s: cstring, len: int): string = + ## encodes `s` into base64 representation. After `lineLen` characters, a + ## `newline` is added. + result = newStringOfCap(((len + 2) div 3) * 4) + var i = 0 + while i < s.len - 2: + let a = ord(s[i]) + let b = ord(s[i+1]) + let c = ord(s[i+2]) + result.add cb64[a shr 2] + result.add cb64[((a and 3) shl 4) or ((b and 0xF0) shr 4)] + result.add cb64[((b and 0x0F) shl 2) or ((c and 0xC0) shr 6)] + result.add cb64[c and 0x3F] + inc(i, 3) + if i < s.len-1: + let a = ord(s[i]) + let b = ord(s[i+1]) + result.add cb64[a shr 2] + result.add cb64[((a and 3) shl 4) or ((b and 0xF0) shr 4)] + result.add cb64[((b and 0x0F) shl 2)] + elif i < s.len: + let a = ord(s[i]) + result.add cb64[a shr 2] + result.add cb64[(a and 3) shl 4] proc toBase64a(u: TUid): string = toBase64a(cast[cstring](u), sizeof(u)) @@ -73,7 +73,7 @@ proc hashSym(c: var MD5Context, s: PSym) = c &= ":anon" else: var it = s.owner - while it != nil: + while it != nil: hashSym(c, it) c &= "." it = s.owner @@ -106,18 +106,18 @@ proc hashTree(c: var MD5Context, n: PNode) = proc hashType(c: var MD5Context, t: PType) = # modelled after 'typeToString' - if t == nil: + if t == nil: c &= "\254" return var k = t.kind md5Update(c, cast[cstring](addr(k)), 1) - + if t.sym != nil and sfAnon notin t.sym.flags: # t.n for literals, but not for e.g. objects! if t.kind in {tyFloat, tyInt}: c.hashNode(t.n) c.hashSym(t.sym) - + case t.kind of tyGenericBody, tyGenericInst, tyGenericInvocation: for i in countup(0, sonsLen(t) -1 -ord(t.kind != tyGenericInvocation)): @@ -135,10 +135,10 @@ proc hashType(c: var MD5Context, t: PType) = of tyArrayConstr: c.hashTree(t.sons[0].n) c.hashType(t.sons[1]) - of tyTuple: + of tyTuple: if t.n != nil: assert(sonsLen(t.n) == sonsLen(t)) - for i in countup(0, sonsLen(t.n) - 1): + for i in countup(0, sonsLen(t.n) - 1): assert(t.n.sons[i].kind == nkSym) c &= t.n.sons[i].sym.name.s c &= ":" @@ -184,18 +184,18 @@ proc pushSym(w: PRodWriter, s: PSym) = if iiTableGet(w.index.tab, s.id) == InvalidKey: w.sstack.add(s) -proc encodeNode(w: PRodWriter, fInfo: TLineInfo, n: PNode, - result: var string) = - if n == nil: +proc encodeNode(w: PRodWriter, fInfo: TLineInfo, n: PNode, + result: var string) = + if n == nil: # nil nodes have to be stored too: result.add("()") return result.add('(') - encodeVInt(ord(n.kind), result) + encodeVInt(ord(n.kind), result) # we do not write comments for now # Line information takes easily 20% or more of the filesize! Therefore we # omit line information if it is the same as the father's line information: - if fInfo.fileIndex != n.info.fileIndex: + if fInfo.fileIndex != n.info.fileIndex: result.add('?') encodeVInt(n.info.col, result) result.add(',') @@ -211,7 +211,7 @@ proc encodeNode(w: PRodWriter, fInfo: TLineInfo, n: PNode, result.add('?') encodeVInt(n.info.col, result) var f = n.flags * PersistentNodeFlags - if f != {}: + if f != {}: result.add('$') encodeVInt(cast[int32](f), result) if n.typ != nil: @@ -219,16 +219,16 @@ proc encodeNode(w: PRodWriter, fInfo: TLineInfo, n: PNode, encodeVInt(n.typ.id, result) pushType(w, n.typ) case n.kind - of nkCharLit..nkInt64Lit: + of nkCharLit..nkInt64Lit: if n.intVal != 0: result.add('!') encodeVBiggestInt(n.intVal, result) - of nkFloatLit..nkFloat64Lit: - if n.floatVal != 0.0: + of nkFloatLit..nkFloat64Lit: + if n.floatVal != 0.0: result.add('!') encodeStr($n.floatVal, result) of nkStrLit..nkTripleStrLit: - if n.strVal != "": + if n.strVal != "": result.add('!') encodeStr(n.strVal, result) of nkIdent: @@ -239,7 +239,7 @@ proc encodeNode(w: PRodWriter, fInfo: TLineInfo, n: PNode, encodeVInt(n.sym.id, result) pushSym(w, n.sym) else: - for i in countup(0, sonsLen(n) - 1): + for i in countup(0, sonsLen(n) - 1): encodeNode(w, n.info, n.sons[i], result) add(result, ')') @@ -268,9 +268,9 @@ proc encodeLoc(w: PRodWriter, loc: TLoc, result: var string) = setLen(result, oldLen) else: add(result, '>') - -proc encodeType(w: PRodWriter, t: PType, result: var string) = - if t == nil: + +proc encodeType(w: PRodWriter, t: PType, result: var string) = + if t == nil: # nil nodes have to be stored too: result.add("[]") return @@ -282,38 +282,38 @@ proc encodeType(w: PRodWriter, t: PType, result: var string) = encodeVInt(ord(t.kind), result) add(result, '+') encodeVInt(t.id, result) - if t.n != nil: + if t.n != nil: encodeNode(w, unknownLineInfo(), t.n, result) - if t.flags != {}: + if t.flags != {}: add(result, '$') encodeVInt(cast[int32](t.flags), result) - if t.callConv != low(t.callConv): + if t.callConv != low(t.callConv): add(result, '?') encodeVInt(ord(t.callConv), result) - if t.owner != nil: + if t.owner != nil: add(result, '*') encodeVInt(t.owner.id, result) pushSym(w, t.owner) - if t.sym != nil: + if t.sym != nil: add(result, '&') encodeVInt(t.sym.id, result) pushSym(w, t.sym) - if t.size != - 1: + if t.size != - 1: add(result, '/') encodeVBiggestInt(t.size, result) - if t.align != 2: + if t.align != 2: add(result, '=') encodeVInt(t.align, result) encodeLoc(w, t.loc, result) - for i in countup(0, sonsLen(t) - 1): - if t.sons[i] == nil: + for i in countup(0, sonsLen(t) - 1): + if t.sons[i] == nil: add(result, "^()") - else: - add(result, '^') + else: + add(result, '^') encodeVInt(t.sons[i].id, result) pushType(w, t.sons[i]) -proc encodeLib(w: PRodWriter, lib: PLib, info: TLineInfo, result: var string) = +proc encodeLib(w: PRodWriter, lib: PLib, info: TLineInfo, result: var string) = add(result, '|') encodeVInt(ord(lib.kind), result) add(result, '|') @@ -352,10 +352,10 @@ proc encodeSym(w: PRodWriter, s: PSym, result: var string) = if s.magic != mNone: result.add('@') encodeVInt(ord(s.magic), result) - if s.options != w.options: + if s.options != w.options: result.add('!') encodeVInt(cast[int32](s.options), result) - if s.position != 0: + if s.position != 0: result.add('%') encodeVInt(s.position, result) if s.offset != - 1: @@ -383,7 +383,7 @@ proc createDb() = fullpath varchar(256) not null, interfHash varchar(256) not null, fullHash varchar(256) not null, - + created timestamp not null default (DATETIME('now')), );""") @@ -397,7 +397,7 @@ proc createDb() = foreign key (module) references module(id) );""") - + db.exec(sql""" create table if not exists Type( id integer primary key, diff --git a/compiler/cgmeth.nim b/compiler/cgmeth.nim index 6c997b983..adb4f1f92 100644 --- a/compiler/cgmeth.nim +++ b/compiler/cgmeth.nim @@ -9,33 +9,33 @@ ## This module implements code generation for multi methods. -import +import intsets, options, ast, astalgo, msgs, idents, renderer, types, magicsys, sempass2, strutils -proc genConv(n: PNode, d: PType, downcast: bool): PNode = +proc genConv(n: PNode, d: PType, downcast: bool): PNode = var dest = skipTypes(d, abstractPtrs) var source = skipTypes(n.typ, abstractPtrs) - if (source.kind == tyObject) and (dest.kind == tyObject): + if (source.kind == tyObject) and (dest.kind == tyObject): var diff = inheritanceDiff(dest, source) if diff == high(int): internalError(n.info, "cgmeth.genConv") - if diff < 0: + if diff < 0: result = newNodeIT(nkObjUpConv, n.info, d) addSon(result, n) if downcast: internalError(n.info, "cgmeth.genConv: no upcast allowed") - elif diff > 0: + elif diff > 0: result = newNodeIT(nkObjDownConv, n.info, d) addSon(result, n) - if not downcast: + if not downcast: internalError(n.info, "cgmeth.genConv: no downcast allowed") - else: + else: result = n - else: + else: result = n - -proc methodCall*(n: PNode): PNode = + +proc methodCall*(n: PNode): PNode = result = n - # replace ordinary method by dispatcher method: + # replace ordinary method by dispatcher method: var disp = lastSon(result.sons[0].sym.ast).sym assert sfDispatcher in disp.flags result.sons[0].sym = disp @@ -47,23 +47,23 @@ proc methodCall*(n: PNode): PNode = var gMethods: seq[tuple[methods: TSymSeq, dispatcher: PSym]] = @[] -proc sameMethodBucket(a, b: PSym): bool = +proc sameMethodBucket(a, b: PSym): bool = result = false - if a.name.id != b.name.id: return - if sonsLen(a.typ) != sonsLen(b.typ): + if a.name.id != b.name.id: return + if sonsLen(a.typ) != sonsLen(b.typ): return # check for return type: - if not sameTypeOrNil(a.typ.sons[0], b.typ.sons[0]): return - for i in countup(1, sonsLen(a.typ) - 1): + if not sameTypeOrNil(a.typ.sons[0], b.typ.sons[0]): return + for i in countup(1, sonsLen(a.typ) - 1): var aa = a.typ.sons[i] var bb = b.typ.sons[i] - while true: + while true: aa = skipTypes(aa, {tyGenericInst}) bb = skipTypes(bb, {tyGenericInst}) - if (aa.kind == bb.kind) and (aa.kind in {tyVar, tyPtr, tyRef}): + if (aa.kind == bb.kind) and (aa.kind in {tyVar, tyPtr, tyRef}): aa = aa.lastSon bb = bb.lastSon - else: - break + else: + break if sameType(aa, bb) or (aa.kind == tyObject) and (bb.kind == tyObject) and (inheritanceDiff(bb, aa) < 0): @@ -140,7 +140,7 @@ proc methodDef*(s: PSym, fromCache: bool) = attachDispatcher(s, lastSon(disp.ast)) fixupDispatcher(s, disp) when useEffectSystem: checkMethodEffects(disp, s) - return + return # create a new dispatcher: add(gMethods, (methods: @[s], dispatcher: createDispatcher(s))) if fromCache: @@ -154,35 +154,35 @@ proc relevantCol(methods: TSymSeq, col: int): bool = let t2 = skipTypes(methods[i].typ.sons[col], skipPtrs) if not sameType(t2, t): return true - -proc cmpSignatures(a, b: PSym, relevantCols: IntSet): int = - for col in countup(1, sonsLen(a.typ) - 1): - if contains(relevantCols, col): + +proc cmpSignatures(a, b: PSym, relevantCols: IntSet): int = + for col in countup(1, sonsLen(a.typ) - 1): + if contains(relevantCols, col): var aa = skipTypes(a.typ.sons[col], skipPtrs) var bb = skipTypes(b.typ.sons[col], skipPtrs) var d = inheritanceDiff(aa, bb) - if (d != high(int)): + if (d != high(int)): return d - -proc sortBucket(a: var TSymSeq, relevantCols: IntSet) = + +proc sortBucket(a: var TSymSeq, relevantCols: IntSet) = # we use shellsort here; fast and simple var n = len(a) var h = 1 - while true: + while true: h = 3 * h + 1 - if h > n: break - while true: + if h > n: break + while true: h = h div 3 - for i in countup(h, n - 1): + for i in countup(h, n - 1): var v = a[i] var j = i - while cmpSignatures(a[j - h], v, relevantCols) >= 0: + while cmpSignatures(a[j - h], v, relevantCols) >= 0: a[j] = a[j - h] j = j - h - if j < h: break + if j < h: break a[j] = v - if h == 1: break - + if h == 1: break + proc genDispatcher(methods: TSymSeq, relevantCols: IntSet): PSym = var base = lastSon(methods[0].ast).sym result = base @@ -199,7 +199,7 @@ proc genDispatcher(methods: TSymSeq, relevantCols: IntSet): PSym = addSon(isn, newSymNode(iss)) addSon(isn, newSymNode(base.typ.n.sons[col].sym)) addSon(isn, newNodeIT(nkType, base.info, curr.typ.sons[col])) - if cond != nil: + if cond != nil: var a = newNodeIT(nkCall, base.info, getSysType(tyBool)) addSon(a, newSymNode(ands)) addSon(a, cond) @@ -209,8 +209,8 @@ proc genDispatcher(methods: TSymSeq, relevantCols: IntSet): PSym = cond = isn var call = newNodeI(nkCall, base.info) addSon(call, newSymNode(curr)) - for col in countup(1, paramLen - 1): - addSon(call, genConv(newSymNode(base.typ.n.sons[col].sym), + for col in countup(1, paramLen - 1): + addSon(call, genConv(newSymNode(base.typ.n.sons[col].sym), curr.typ.sons[col], false)) var ret: PNode if base.typ.sons[0] != nil: @@ -230,11 +230,11 @@ proc genDispatcher(methods: TSymSeq, relevantCols: IntSet): PSym = disp = ret result.ast.sons[bodyPos] = disp -proc generateMethodDispatchers*(): PNode = +proc generateMethodDispatchers*(): PNode = result = newNode(nkStmtList) - for bucket in countup(0, len(gMethods) - 1): + for bucket in countup(0, len(gMethods) - 1): var relevantCols = initIntSet() - for col in countup(1, sonsLen(gMethods[bucket].methods[0].typ) - 1): + for col in countup(1, sonsLen(gMethods[bucket].methods[0].typ) - 1): if relevantCol(gMethods[bucket].methods, col): incl(relevantCols, col) sortBucket(gMethods[bucket].methods, relevantCols) addSon(result, diff --git a/compiler/docgen2.nim b/compiler/docgen2.nim index aa832b6df..27de06811 100644 --- a/compiler/docgen2.nim +++ b/compiler/docgen2.nim @@ -10,10 +10,10 @@ # This module implements a new documentation generator that runs after # semantic checking. -import +import os, options, ast, astalgo, msgs, ropes, idents, passes, docgen -type +type TGen = object of TPassContext doc: PDoc module: PSym @@ -29,12 +29,12 @@ proc close(p: PPassContext, n: PNode): PNode = except IOError: discard -proc processNode(c: PPassContext, n: PNode): PNode = +proc processNode(c: PPassContext, n: PNode): PNode = result = n var g = PGen(c) generateDoc(g.doc, n) -proc myOpen(module: PSym): PPassContext = +proc myOpen(module: PSym): PPassContext = var g: PGen new(g) g.module = module @@ -45,5 +45,5 @@ proc myOpen(module: PSym): PPassContext = const docgen2Pass* = makePass(open = myOpen, process = processNode, close = close) -proc finishDoc2Pass*(project: string) = +proc finishDoc2Pass*(project: string) = discard diff --git a/compiler/evaltempl.nim b/compiler/evaltempl.nim index 82c4e8f57..58594a8b7 100644 --- a/compiler/evaltempl.nim +++ b/compiler/evaltempl.nim @@ -31,7 +31,7 @@ proc evalTemplateAux(templ, actual: PNode, c: var TemplCtx, result: PNode) = for y in items(x): result.add(y) else: result.add copyTree(x) - + case templ.kind of nkSym: var s = templ.sym @@ -81,7 +81,7 @@ proc evalTemplateArgs(n: PNode, s: PSym): PNode = if totalParams > expectedRegularParams + genericParams: globalError(n.info, errWrongNumberOfArguments) - + result = newNodeI(nkArgList, n.info) for i in 1 .. givenRegularParams: result.addSon n.sons[i] @@ -96,7 +96,7 @@ proc evalTemplateArgs(n: PNode, s: PSym): PNode = addSon(result, ast.emptyNode) else: addSon(result, default.copyTree) - + # add any generic paramaters for i in 1 .. genericParams: result.addSon n.sons[givenRegularParams + i] diff --git a/compiler/filter_tmpl.nim b/compiler/filter_tmpl.nim index 5d1f73be4..d3ab1728c 100644 --- a/compiler/filter_tmpl.nim +++ b/compiler/filter_tmpl.nim @@ -9,18 +9,18 @@ # This module implements Nim's standard template filter. -import - llstream, os, wordrecg, idents, strutils, ast, astalgo, msgs, options, +import + llstream, os, wordrecg, idents, strutils, ast, astalgo, msgs, options, renderer, filters proc filterTmpl*(stdin: PLLStream, filename: string, call: PNode): PLLStream # #! template(subsChar='$', metaChar='#') | standard(version="0.7.2") # implementation -type - TParseState = enum +type + TParseState = enum psDirective, psTempl - TTmplParser{.final.} = object + TTmplParser{.final.} = object inp: PLLStream state: TParseState info: TLineInfo @@ -33,18 +33,18 @@ type pendingExprLine: bool -const +const PatternChars = {'a'..'z', 'A'..'Z', '0'..'9', '\x80'..'\xFF', '.', '_'} -proc newLine(p: var TTmplParser) = +proc newLine(p: var TTmplParser) = llStreamWrite(p.outp, repeat(')', p.emitPar)) p.emitPar = 0 if p.info.line > int16(1): llStreamWrite(p.outp, "\n") if p.pendingExprLine: llStreamWrite(p.outp, spaces(2)) p.pendingExprLine = false - -proc scanPar(p: var TTmplParser, d: int) = + +proc scanPar(p: var TTmplParser, d: int) = var i = d while true: case p.x[i] @@ -58,44 +58,44 @@ proc scanPar(p: var TTmplParser, d: int) = else: discard inc(i) -proc withInExpr(p: TTmplParser): bool {.inline.} = +proc withInExpr(p: TTmplParser): bool {.inline.} = result = p.par > 0 or p.bracket > 0 or p.curly > 0 - -proc parseLine(p: var TTmplParser) = - var + +proc parseLine(p: var TTmplParser) = + var d, j, curly: int keyw: string j = 0 while p.x[j] == ' ': inc(j) - if (p.x[0] == p.nimDirective) and (p.x[0 + 1] == '!'): + if (p.x[0] == p.nimDirective) and (p.x[0 + 1] == '!'): newLine(p) - elif (p.x[j] == p.nimDirective): + elif (p.x[j] == p.nimDirective): newLine(p) inc(j) while p.x[j] == ' ': inc(j) d = j keyw = "" - while p.x[j] in PatternChars: + while p.x[j] in PatternChars: add(keyw, p.x[j]) inc(j) - + scanPar(p, j) p.pendingExprLine = withInExpr(p) or llstream.endsWithOpr(p.x) case whichKeyword(keyw) - of wEnd: - if p.indent >= 2: + of wEnd: + if p.indent >= 2: dec(p.indent, 2) - else: + else: p.info.col = int16(j) localError(p.info, errXNotAllowedHere, "end") llStreamWrite(p.outp, spaces(p.indent)) llStreamWrite(p.outp, "#end") - of wIf, wWhen, wTry, wWhile, wFor, wBlock, wCase, wProc, wIterator, - wConverter, wMacro, wTemplate, wMethod: + of wIf, wWhen, wTry, wWhile, wFor, wBlock, wCase, wProc, wIterator, + wConverter, wMacro, wTemplate, wMethod: llStreamWrite(p.outp, spaces(p.indent)) llStreamWrite(p.outp, substr(p.x, d)) inc(p.indent, 2) - of wElif, wOf, wElse, wExcept, wFinally: + of wElif, wOf, wElse, wExcept, wFinally: llStreamWrite(p.outp, spaces(p.indent - 2)) llStreamWrite(p.outp, substr(p.x, d)) of wLet, wVar, wConst, wType: @@ -108,7 +108,7 @@ proc parseLine(p: var TTmplParser) = llStreamWrite(p.outp, spaces(p.indent)) llStreamWrite(p.outp, substr(p.x, d)) p.state = psDirective - else: + else: # data line # reset counters p.par = 0 @@ -116,42 +116,42 @@ proc parseLine(p: var TTmplParser) = p.bracket = 0 j = 0 case p.state - of psTempl: + of psTempl: # next line of string literal: llStreamWrite(p.outp, p.conc) llStreamWrite(p.outp, "\n") llStreamWrite(p.outp, spaces(p.indent + 2)) llStreamWrite(p.outp, "\"") - of psDirective: + of psDirective: newLine(p) llStreamWrite(p.outp, spaces(p.indent)) llStreamWrite(p.outp, p.emit) llStreamWrite(p.outp, "(\"") inc(p.emitPar) p.state = psTempl - while true: + while true: case p.x[j] - of '\0': - break - of '\x01'..'\x1F', '\x80'..'\xFF': + of '\0': + break + of '\x01'..'\x1F', '\x80'..'\xFF': llStreamWrite(p.outp, "\\x") llStreamWrite(p.outp, toHex(ord(p.x[j]), 2)) inc(j) - of '\\': + of '\\': llStreamWrite(p.outp, "\\\\") inc(j) - of '\'': + of '\'': llStreamWrite(p.outp, "\\\'") inc(j) - of '\"': + of '\"': llStreamWrite(p.outp, "\\\"") inc(j) - else: - if p.x[j] == p.subsChar: + else: + if p.x[j] == p.subsChar: # parse Nim expression: inc(j) case p.x[j] - of '{': + of '{': p.info.col = int16(j) llStreamWrite(p.outp, '\"') llStreamWrite(p.outp, p.conc) @@ -159,50 +159,50 @@ proc parseLine(p: var TTmplParser) = llStreamWrite(p.outp, '(') inc(j) curly = 0 - while true: + while true: case p.x[j] - of '\0': + of '\0': localError(p.info, errXExpected, "}") break - of '{': + of '{': inc(j) inc(curly) llStreamWrite(p.outp, '{') - of '}': + of '}': inc(j) - if curly == 0: break + if curly == 0: break if curly > 0: dec(curly) llStreamWrite(p.outp, '}') - else: + else: llStreamWrite(p.outp, p.x[j]) inc(j) llStreamWrite(p.outp, ')') llStreamWrite(p.outp, p.conc) llStreamWrite(p.outp, '\"') - of 'a'..'z', 'A'..'Z', '\x80'..'\xFF': + of 'a'..'z', 'A'..'Z', '\x80'..'\xFF': llStreamWrite(p.outp, '\"') llStreamWrite(p.outp, p.conc) llStreamWrite(p.outp, p.toStr) llStreamWrite(p.outp, '(') - while p.x[j] in PatternChars: + while p.x[j] in PatternChars: llStreamWrite(p.outp, p.x[j]) inc(j) llStreamWrite(p.outp, ')') llStreamWrite(p.outp, p.conc) llStreamWrite(p.outp, '\"') - else: - if p.x[j] == p.subsChar: + else: + if p.x[j] == p.subsChar: llStreamWrite(p.outp, p.subsChar) inc(j) - else: + else: p.info.col = int16(j) localError(p.info, errInvalidExpression, "$") - else: + else: llStreamWrite(p.outp, p.x[j]) inc(j) llStreamWrite(p.outp, "\\n\"") -proc filterTmpl(stdin: PLLStream, filename: string, call: PNode): PLLStream = +proc filterTmpl(stdin: PLLStream, filename: string, call: PNode): PLLStream = var p: TTmplParser p.info = newLineInfo(filename, 0, 0) p.outp = llStreamOpen("") diff --git a/compiler/filters.nim b/compiler/filters.nim index 783a320a4..adafe464e 100644 --- a/compiler/filters.nim +++ b/compiler/filters.nim @@ -10,7 +10,7 @@ # This module implements Nim's simple filters and helpers for filters. import - llstream, os, wordrecg, idents, strutils, ast, astalgo, msgs, options, + llstream, os, wordrecg, idents, strutils, ast, astalgo, msgs, options, renderer proc filterReplace*(stdin: PLLStream, filename: string, call: PNode): PLLStream @@ -21,40 +21,40 @@ proc strArg*(n: PNode, name: string, pos: int, default: string): string proc boolArg*(n: PNode, name: string, pos: int, default: bool): bool # implementation -proc invalidPragma(n: PNode) = +proc invalidPragma(n: PNode) = localError(n.info, errXNotAllowedHere, renderTree(n, {renderNoComments})) -proc getArg(n: PNode, name: string, pos: int): PNode = +proc getArg(n: PNode, name: string, pos: int): PNode = result = nil - if n.kind in {nkEmpty..nkNilLit}: return - for i in countup(1, sonsLen(n) - 1): - if n.sons[i].kind == nkExprEqExpr: + if n.kind in {nkEmpty..nkNilLit}: return + for i in countup(1, sonsLen(n) - 1): + if n.sons[i].kind == nkExprEqExpr: if n.sons[i].sons[0].kind != nkIdent: invalidPragma(n) - if identEq(n.sons[i].sons[0].ident, name): + if identEq(n.sons[i].sons[0].ident, name): return n.sons[i].sons[1] - elif i == pos: + elif i == pos: return n.sons[i] - -proc charArg(n: PNode, name: string, pos: int, default: char): char = + +proc charArg(n: PNode, name: string, pos: int, default: char): char = var x = getArg(n, name, pos) if x == nil: result = default elif x.kind == nkCharLit: result = chr(int(x.intVal)) else: invalidPragma(n) - -proc strArg(n: PNode, name: string, pos: int, default: string): string = + +proc strArg(n: PNode, name: string, pos: int, default: string): string = var x = getArg(n, name, pos) if x == nil: result = default elif x.kind in {nkStrLit..nkTripleStrLit}: result = x.strVal else: invalidPragma(n) - -proc boolArg(n: PNode, name: string, pos: int, default: bool): bool = + +proc boolArg(n: PNode, name: string, pos: int, default: bool): bool = var x = getArg(n, name, pos) if x == nil: result = default elif (x.kind == nkIdent) and identEq(x.ident, "true"): result = true elif (x.kind == nkIdent) and identEq(x.ident, "false"): result = false else: invalidPragma(n) - -proc filterStrip(stdin: PLLStream, filename: string, call: PNode): PLLStream = + +proc filterStrip(stdin: PLLStream, filename: string, call: PNode): PLLStream = var pattern = strArg(call, "startswith", 1, "") var leading = boolArg(call, "leading", 2, true) var trailing = boolArg(call, "trailing", 3, true) @@ -62,13 +62,13 @@ proc filterStrip(stdin: PLLStream, filename: string, call: PNode): PLLStream = var line = newStringOfCap(80) while llStreamReadLine(stdin, line): var stripped = strip(line, leading, trailing) - if (len(pattern) == 0) or startsWith(stripped, pattern): + if (len(pattern) == 0) or startsWith(stripped, pattern): llStreamWriteln(result, stripped) - else: + else: llStreamWriteln(result, line) llStreamClose(stdin) -proc filterReplace(stdin: PLLStream, filename: string, call: PNode): PLLStream = +proc filterReplace(stdin: PLLStream, filename: string, call: PNode): PLLStream = var sub = strArg(call, "sub", 1, "") if len(sub) == 0: invalidPragma(call) var by = strArg(call, "by", 2, "") diff --git a/compiler/forloops.nim b/compiler/forloops.nim index 949b7d8c6..5074d79d5 100644 --- a/compiler/forloops.nim +++ b/compiler/forloops.nim @@ -14,11 +14,11 @@ import ast, astalgo const someCmp = {mEqI, mEqF64, mEqEnum, mEqCh, mEqB, mEqRef, mEqProc, mEqUntracedRef, mLeI, mLeF64, mLeU, mLeU64, mLeEnum, - mLeCh, mLeB, mLePtr, mLtI, mLtF64, mLtU, mLtU64, mLtEnum, + mLeCh, mLeB, mLePtr, mLtI, mLtF64, mLtU, mLtU64, mLtEnum, mLtCh, mLtB, mLtPtr} proc isCounter(s: PSym): bool {.inline.} = - s.kind in {skResult, skVar, skLet, skTemp} and + s.kind in {skResult, skVar, skLet, skTemp} and {sfGlobal, sfAddrTaken} * s.flags == {} proc isCall(n: PNode): bool {.inline.} = @@ -29,7 +29,7 @@ proc fromSystem(op: PSym): bool = sfSystemModule in getModule(op).flags proc getCounter(lastStmt: PNode): PSym = if lastStmt.isCall: let op = lastStmt.sym - if op.magic in {mDec, mInc} or + if op.magic in {mDec, mInc} or ((op.name.s == "+=" or op.name.s == "-=") and op.fromSystem): if op[1].kind == nkSym and isCounter(op[1].sym): result = op[1].sym @@ -67,7 +67,7 @@ proc extractForLoop*(loop, fullTree: PNode): ForLoop = if not cond.isCall: return if cond[0].sym.magic notin someCmp: return - + var lastStmt = loop[1] while lastStmt.kind in {nkStmtList, nkStmtListExpr}: lastStmt = lastStmt.lastSon @@ -76,7 +76,7 @@ proc extractForLoop*(loop, fullTree: PNode): ForLoop = if counter.isNil or counter.ast.isNil: return template `=~`(a, b): expr = a.kind == nkSym and a.sym == b - + if cond[1] =~ counter or cond[2] =~ counter: # ok, now check 'counter' is not used *after* the loop if counterInTree(fullTree, loop, counter): return diff --git a/compiler/hlo.nim b/compiler/hlo.nim index 363d100be..6cc9567af 100644 --- a/compiler/hlo.nim +++ b/compiler/hlo.nim @@ -28,7 +28,7 @@ proc evalPattern(c: PContext, n, orig: PNode): PNode = else: result = semDirectOp(c, n, {}) if optHints in gOptions and hintPattern in gNotes: - message(orig.info, hintPattern, rule & " --> '" & + message(orig.info, hintPattern, rule & " --> '" & renderTree(result, {renderNoComments}) & "'") proc applyPatterns(c: PContext, n: PNode): PNode = @@ -68,7 +68,7 @@ proc hlo(c: PContext, n: PNode): PNode = result = n else: if n.kind in {nkFastAsgn, nkAsgn, nkIdentDefs, nkVarTuple} and - n.sons[0].kind == nkSym and + n.sons[0].kind == nkSym and {sfGlobal, sfPure} * n.sons[0].sym.flags == {sfGlobal, sfPure}: # do not optimize 'var g {.global} = re(...)' again! return n diff --git a/compiler/idents.nim b/compiler/idents.nim index 6986800cf..d9b72baf0 100644 --- a/compiler/idents.nim +++ b/compiler/idents.nim @@ -11,13 +11,13 @@ # An identifier is a shared immutable string that can be compared by its # id. This module is essential for the compiler's performance. -import +import hashes, strutils, etcpriv -type +type TIdObj* = object of RootObj id*: int # unique id; use this for comparisons and not the pointers - + PIdObj* = ref TIdObj PIdent* = ref TIdent TIdent*{.acyclic.} = object of TIdObj @@ -45,12 +45,12 @@ proc cmpIgnoreStyle(a, b: cstring, blen: int): int = if aa >= 'A' and aa <= 'Z': aa = chr(ord(aa) + (ord('a') - ord('A'))) if bb >= 'A' and bb <= 'Z': bb = chr(ord(bb) + (ord('a') - ord('A'))) result = ord(aa) - ord(bb) - if (result != 0) or (aa == '\0'): break + if (result != 0) or (aa == '\0'): break inc(i) inc(j) if result == 0: if a[i] != '\0': result = 1 - + proc cmpExact(a, b: cstring, blen: int): int = var i = 0 var j = 0 @@ -59,10 +59,10 @@ proc cmpExact(a, b: cstring, blen: int): int = var aa = a[i] var bb = b[j] result = ord(aa) - ord(bb) - if (result != 0) or (aa == '\0'): break + if (result != 0) or (aa == '\0'): break inc(i) inc(j) - if result == 0: + if result == 0: if a[i] != '\0': result = 1 var wordCounter = 1 @@ -72,14 +72,14 @@ proc getIdent*(identifier: cstring, length: int, h: Hash): PIdent = result = buckets[idx] var last: PIdent = nil var id = 0 - while result != nil: - if cmpExact(cstring(result.s), identifier, length) == 0: - if last != nil: + while result != nil: + if cmpExact(cstring(result.s), identifier, length) == 0: + if last != nil: # make access to last looked up identifier faster: last.next = result.next result.next = buckets[idx] buckets[idx] = result - return + return elif cmpIgnoreStyle(cstring(result.s), identifier, length) == 0: assert((id == 0) or (id == result.id)) id = result.id @@ -91,20 +91,20 @@ proc getIdent*(identifier: cstring, length: int, h: Hash): PIdent = for i in countup(0, length - 1): result.s[i] = identifier[i] result.next = buckets[idx] buckets[idx] = result - if id == 0: + if id == 0: inc(wordCounter) result.id = -wordCounter - else: + else: result.id = id -proc getIdent*(identifier: string): PIdent = - result = getIdent(cstring(identifier), len(identifier), +proc getIdent*(identifier: string): PIdent = + result = getIdent(cstring(identifier), len(identifier), hashIgnoreStyle(identifier)) -proc getIdent*(identifier: string, h: Hash): PIdent = +proc getIdent*(identifier: string, h: Hash): PIdent = result = getIdent(cstring(identifier), len(identifier), h) -proc identEq*(id: PIdent, name: string): bool = +proc identEq*(id: PIdent, name: string): bool = result = id.id == getIdent(name).id var idAnon* = getIdent":anonymous" diff --git a/compiler/lists.nim b/compiler/lists.nim index 1b2b91bff..27e373342 100644 --- a/compiler/lists.nim +++ b/compiler/lists.nim @@ -10,7 +10,7 @@ # This module implements a generic doubled linked list. # TODO Remove this and replace it with something sensible import os -type +type PListEntry* = ref TListEntry TListEntry* = object of RootObj prev*, next*: PListEntry @@ -25,68 +25,68 @@ type TCompareProc* = proc (entry: PListEntry, closure: pointer): bool {.nimcall.} -proc initLinkedList*(list: var TLinkedList) = +proc initLinkedList*(list: var TLinkedList) = list.counter = 0 list.head = nil list.tail = nil -proc append*(list: var TLinkedList, entry: PListEntry) = +proc append*(list: var TLinkedList, entry: PListEntry) = inc(list.counter) entry.next = nil entry.prev = list.tail - if list.tail != nil: + if list.tail != nil: assert(list.tail.next == nil) list.tail.next = entry list.tail = entry if list.head == nil: list.head = entry - -proc contains*(list: TLinkedList, data: string): bool = + +proc contains*(list: TLinkedList, data: string): bool = var it = list.head - while it != nil: - if PStrEntry(it).data == data: + while it != nil: + if PStrEntry(it).data == data: return true it = it.next - -proc newStrEntry(data: string): PStrEntry = + +proc newStrEntry(data: string): PStrEntry = new(result) result.data = data -proc appendStr*(list: var TLinkedList, data: string) = +proc appendStr*(list: var TLinkedList, data: string) = append(list, newStrEntry(data)) -proc includeStr*(list: var TLinkedList, data: string): bool = +proc includeStr*(list: var TLinkedList, data: string): bool = if contains(list, data): return true appendStr(list, data) # else: add to list -proc prepend*(list: var TLinkedList, entry: PListEntry) = +proc prepend*(list: var TLinkedList, entry: PListEntry) = inc(list.counter) entry.prev = nil entry.next = list.head - if list.head != nil: + if list.head != nil: assert(list.head.prev == nil) list.head.prev = entry list.head = entry if list.tail == nil: list.tail = entry -proc prependStr*(list: var TLinkedList, data: string) = +proc prependStr*(list: var TLinkedList, data: string) = prepend(list, newStrEntry(data)) -proc insertBefore*(list: var TLinkedList, pos, entry: PListEntry) = +proc insertBefore*(list: var TLinkedList, pos, entry: PListEntry) = assert(pos != nil) - if pos == list.head: + if pos == list.head: prepend(list, entry) - else: + else: inc(list.counter) entry.next = pos entry.prev = pos.prev if pos.prev != nil: pos.prev.next = entry pos.prev = entry - -proc remove*(list: var TLinkedList, entry: PListEntry) = + +proc remove*(list: var TLinkedList, entry: PListEntry) = dec(list.counter) - if entry == list.tail: + if entry == list.tail: list.tail = entry.prev - if entry == list.head: + if entry == list.head: list.head = entry.next if entry.next != nil: entry.next.prev = entry.prev if entry.prev != nil: entry.prev.next = entry.next @@ -112,8 +112,8 @@ proc excludePath*(list: var TLinkedList, data: string) = remove(list, it) it = nxt -proc find*(list: TLinkedList, fn: TCompareProc, closure: pointer): PListEntry = +proc find*(list: TLinkedList, fn: TCompareProc, closure: pointer): PListEntry = result = list.head while result != nil: - if fn(result, closure): return + if fn(result, closure): return result = result.next diff --git a/compiler/magicsys.nim b/compiler/magicsys.nim index 6d4c65268..98a4b08bf 100644 --- a/compiler/magicsys.nim +++ b/compiler/magicsys.nim @@ -9,7 +9,7 @@ # Built-in types and compilerprocs are registered here. -import +import ast, astalgo, hashes, msgs, platform, nversion, times, idents, rodread var systemModule*: PSym @@ -29,23 +29,23 @@ var proc nilOrSysInt*: PType = gSysTypes[tyInt] -proc registerSysType(t: PType) = +proc registerSysType(t: PType) = if gSysTypes[t.kind] == nil: gSysTypes[t.kind] = t - -proc newSysType(kind: TTypeKind, size: int): PType = + +proc newSysType(kind: TTypeKind, size: int): PType = result = newType(kind, systemModule) result.size = size result.align = size.int16 -proc getSysSym(name: string): PSym = +proc getSysSym(name: string): PSym = result = strTableGet(systemModule.tab, getIdent(name)) - if result == nil: + if result == nil: rawMessage(errSystemNeeds, name) result = newSym(skError, getIdent(name), systemModule, systemModule.info) result.typ = newType(tyError, systemModule) if result.kind == skStub: loadStub(result) if result.kind == skAlias: result = result.owner - + proc getSysMagic*(name: string, m: TMagic): PSym = var ti: TIdentIter let id = getIdent(name) @@ -57,13 +57,13 @@ proc getSysMagic*(name: string, m: TMagic): PSym = rawMessage(errSystemNeeds, name) result = newSym(skError, id, systemModule, systemModule.info) result.typ = newType(tyError, systemModule) - -proc sysTypeFromName*(name: string): PType = + +proc sysTypeFromName*(name: string): PType = result = getSysSym(name).typ -proc getSysType(kind: TTypeKind): PType = +proc getSysType(kind: TTypeKind): PType = result = gSysTypes[kind] - if result == nil: + if result == nil: case kind of tyInt: result = sysTypeFromName("int") of tyInt8: result = sysTypeFromName("int8") @@ -87,7 +87,7 @@ proc getSysType(kind: TTypeKind): PType = of tyNil: result = newSysType(tyNil, ptrSize) else: internalError("request for typekind: " & $kind) gSysTypes[kind] = result - if result.kind != kind: + if result.kind != kind: internalError("wanted: " & $kind & " got: " & $result.kind) if result == nil: internalError("type not found: " & $kind) @@ -163,7 +163,7 @@ proc setIntLitType*(result: PNode) = result.typ = getSysType(tyInt64) else: internalError(result.info, "invalid int size") -proc getCompilerProc(name: string): PSym = +proc getCompilerProc(name: string): PSym = var ident = getIdent(name, hashIgnoreStyle(name)) result = strTableGet(compilerprocs, ident) if result == nil: diff --git a/compiler/nimblecmd.nim b/compiler/nimblecmd.nim index 2044f104f..9b647e67d 100644 --- a/compiler/nimblecmd.nim +++ b/compiler/nimblecmd.nim @@ -11,8 +11,8 @@ import parseutils, strutils, strtabs, os, options, msgs, lists -proc addPath*(path: string, info: TLineInfo) = - if not contains(options.searchPaths, path): +proc addPath*(path: string, info: TLineInfo) = + if not contains(options.searchPaths, path): lists.prependStr(options.searchPaths, path) proc versionSplitPos(s: string): int = @@ -23,7 +23,7 @@ proc versionSplitPos(s: string): int = const latest = "head" -proc `<.`(a, b: string): bool = +proc `<.`(a, b: string): bool = # wether a has a smaller version than b: if a == latest: return false var i = 0 diff --git a/compiler/nimeval.nim b/compiler/nimeval.nim index 197e8bf86..2bddb76e7 100644 --- a/compiler/nimeval.nim +++ b/compiler/nimeval.nim @@ -10,7 +10,7 @@ ## exposes the Nim VM to clients. import - ast, modules, passes, passaux, condsyms, + ast, modules, passes, passaux, condsyms, options, nimconf, lists, sem, semdata, llstream, vm proc execute*(program: string) = diff --git a/compiler/nimlexbase.nim b/compiler/nimlexbase.nim index f5db5ca4f..047890c44 100644 --- a/compiler/nimlexbase.nim +++ b/compiler/nimlexbase.nim @@ -12,10 +12,10 @@ # handling that exists! Only at line endings checks are necessary # if the buffer needs refilling. -import +import llstream, strutils -const +const Lrz* = ' ' Apo* = '\'' Tabulator* = '\x09' @@ -27,7 +27,7 @@ const BACKSPACE* = '\x08' VT* = '\x0B' -const +const EndOfFile* = '\0' # end of file marker # A little picture makes everything clear :-) # buf: @@ -36,7 +36,7 @@ const # NewLines* = {CR, LF} -type +type TBaseLexer* = object of RootObj bufpos*: int buf*: cstring @@ -46,9 +46,9 @@ type # private data: sentinel*: int lineStart*: int # index of last line start in buffer - -proc openBaseLexer*(L: var TBaseLexer, inputstream: PLLStream, + +proc openBaseLexer*(L: var TBaseLexer, inputstream: PLLStream, bufLen: int = 8192) # 8K is a reasonable buffer size proc closeBaseLexer*(L: var TBaseLexer) @@ -64,15 +64,15 @@ proc handleLF*(L: var TBaseLexer, pos: int): int # of the LF. # implementation -const +const chrSize = sizeof(char) -proc closeBaseLexer(L: var TBaseLexer) = +proc closeBaseLexer(L: var TBaseLexer) = dealloc(L.buf) llStreamClose(L.stream) -proc fillBuffer(L: var TBaseLexer) = - var +proc fillBuffer(L: var TBaseLexer) = + var charsRead, toCopy, s: int # all are in characters, # not bytes (in case this # is not the same) @@ -82,68 +82,68 @@ proc fillBuffer(L: var TBaseLexer) = assert(L.sentinel < L.bufLen) toCopy = L.bufLen - L.sentinel - 1 assert(toCopy >= 0) - if toCopy > 0: - moveMem(L.buf, addr(L.buf[L.sentinel + 1]), toCopy * chrSize) + if toCopy > 0: + moveMem(L.buf, addr(L.buf[L.sentinel + 1]), toCopy * chrSize) # "moveMem" handles overlapping regions - charsRead = llStreamRead(L.stream, addr(L.buf[toCopy]), + charsRead = llStreamRead(L.stream, addr(L.buf[toCopy]), (L.sentinel + 1) * chrSize) div chrSize s = toCopy + charsRead - if charsRead < L.sentinel + 1: + if charsRead < L.sentinel + 1: L.buf[s] = EndOfFile # set end marker L.sentinel = s - else: + else: # compute sentinel: dec(s) # BUGFIX (valgrind) - while true: + while true: assert(s < L.bufLen) while (s >= 0) and not (L.buf[s] in NewLines): dec(s) - if s >= 0: + if s >= 0: # we found an appropriate character for a sentinel: L.sentinel = s - break - else: + break + else: # rather than to give up here because the line is too long, # double the buffer's size and try again: oldBufLen = L.bufLen L.bufLen = L.bufLen * 2 L.buf = cast[cstring](realloc(L.buf, L.bufLen * chrSize)) assert(L.bufLen - oldBufLen == oldBufLen) - charsRead = llStreamRead(L.stream, addr(L.buf[oldBufLen]), + charsRead = llStreamRead(L.stream, addr(L.buf[oldBufLen]), oldBufLen * chrSize) div chrSize - if charsRead < oldBufLen: + if charsRead < oldBufLen: L.buf[oldBufLen + charsRead] = EndOfFile L.sentinel = oldBufLen + charsRead - break + break s = L.bufLen - 1 -proc fillBaseLexer(L: var TBaseLexer, pos: int): int = +proc fillBaseLexer(L: var TBaseLexer, pos: int): int = assert(pos <= L.sentinel) - if pos < L.sentinel: + if pos < L.sentinel: result = pos + 1 # nothing to do - else: + else: fillBuffer(L) L.bufpos = 0 # XXX: is this really correct? result = 0 L.lineStart = result -proc handleCR(L: var TBaseLexer, pos: int): int = +proc handleCR(L: var TBaseLexer, pos: int): int = assert(L.buf[pos] == CR) inc(L.lineNumber) result = fillBaseLexer(L, pos) - if L.buf[result] == LF: + if L.buf[result] == LF: result = fillBaseLexer(L, result) -proc handleLF(L: var TBaseLexer, pos: int): int = +proc handleLF(L: var TBaseLexer, pos: int): int = assert(L.buf[pos] == LF) inc(L.lineNumber) result = fillBaseLexer(L, pos) #L.lastNL := result-1; // BUGFIX: was: result; - -proc skipUTF8BOM(L: var TBaseLexer) = + +proc skipUTF8BOM(L: var TBaseLexer) = if L.buf[0] == '\xEF' and L.buf[1] == '\xBB' and L.buf[2] == '\xBF': inc(L.bufpos, 3) inc(L.lineStart, 3) -proc openBaseLexer(L: var TBaseLexer, inputstream: PLLStream, bufLen = 8192) = +proc openBaseLexer(L: var TBaseLexer, inputstream: PLLStream, bufLen = 8192) = assert(bufLen > 0) L.bufpos = 0 L.bufLen = bufLen @@ -155,15 +155,15 @@ proc openBaseLexer(L: var TBaseLexer, inputstream: PLLStream, bufLen = 8192) = fillBuffer(L) skipUTF8BOM(L) -proc getColNumber(L: TBaseLexer, pos: int): int = +proc getColNumber(L: TBaseLexer, pos: int): int = result = abs(pos - L.lineStart) -proc getCurrentLine(L: TBaseLexer, marker: bool = true): string = +proc getCurrentLine(L: TBaseLexer, marker: bool = true): string = result = "" var i = L.lineStart - while not (L.buf[i] in {CR, LF, EndOfFile}): + while not (L.buf[i] in {CR, LF, EndOfFile}): add(result, L.buf[i]) inc(i) result.add("\n") - if marker: + if marker: result.add(spaces(getColNumber(L, L.bufpos)) & '^' & "\n") diff --git a/compiler/nimsets.nim b/compiler/nimsets.nim index aa7686d30..055bae909 100644 --- a/compiler/nimsets.nim +++ b/compiler/nimsets.nim @@ -9,7 +9,7 @@ # this unit handles Nim sets; it implements symbolic sets -import +import ast, astalgo, trees, nversion, msgs, platform, bitsets, types, renderer proc toBitSet*(s: PNode, b: var TBitSet) @@ -30,17 +30,17 @@ proc equalSets*(a, b: PNode): bool proc cardSet*(s: PNode): BiggestInt # implementation -proc inSet(s: PNode, elem: PNode): bool = - if s.kind != nkCurly: +proc inSet(s: PNode, elem: PNode): bool = + if s.kind != nkCurly: internalError(s.info, "inSet") return false - for i in countup(0, sonsLen(s) - 1): - if s.sons[i].kind == nkRange: + for i in countup(0, sonsLen(s) - 1): + if s.sons[i].kind == nkRange: if leValue(s.sons[i].sons[0], elem) and - leValue(elem, s.sons[i].sons[1]): + leValue(elem, s.sons[i].sons[1]): return true - else: - if sameValue(s.sons[i], elem): + else: + if sameValue(s.sons[i], elem): return true result = false @@ -58,37 +58,37 @@ proc overlap(a, b: PNode): bool = else: result = sameValue(a, b) -proc someInSet(s: PNode, a, b: PNode): bool = +proc someInSet(s: PNode, a, b: PNode): bool = # checks if some element of a..b is in the set s if s.kind != nkCurly: internalError(s.info, "SomeInSet") return false - for i in countup(0, sonsLen(s) - 1): - if s.sons[i].kind == nkRange: + for i in countup(0, sonsLen(s) - 1): + if s.sons[i].kind == nkRange: if leValue(s.sons[i].sons[0], b) and leValue(b, s.sons[i].sons[1]) or - leValue(s.sons[i].sons[0], a) and leValue(a, s.sons[i].sons[1]): + leValue(s.sons[i].sons[0], a) and leValue(a, s.sons[i].sons[1]): return true - else: + else: # a <= elem <= b - if leValue(a, s.sons[i]) and leValue(s.sons[i], b): + if leValue(a, s.sons[i]) and leValue(s.sons[i], b): return true result = false -proc toBitSet(s: PNode, b: var TBitSet) = +proc toBitSet(s: PNode, b: var TBitSet) = var first, j: BiggestInt first = firstOrd(s.typ.sons[0]) bitSetInit(b, int(getSize(s.typ))) - for i in countup(0, sonsLen(s) - 1): - if s.sons[i].kind == nkRange: + for i in countup(0, sonsLen(s) - 1): + if s.sons[i].kind == nkRange: j = getOrdValue(s.sons[i].sons[0]) - while j <= getOrdValue(s.sons[i].sons[1]): + while j <= getOrdValue(s.sons[i].sons[1]): bitSetIncl(b, j - first) inc(j) - else: + else: bitSetIncl(b, getOrdValue(s.sons[i]) - first) - -proc toTreeSet(s: TBitSet, settype: PType, info: TLineInfo): PNode = - var + +proc toTreeSet(s: TBitSet, settype: PType, info: TLineInfo): PNode = + var a, b, e, first: BiggestInt # a, b are interval borders elemType: PType n: PNode @@ -98,17 +98,17 @@ proc toTreeSet(s: TBitSet, settype: PType, info: TLineInfo): PNode = result.typ = settype result.info = info e = 0 - while e < len(s) * ElemSize: - if bitSetIn(s, e): + while e < len(s) * ElemSize: + if bitSetIn(s, e): a = e b = e - while true: + while true: inc(b) - if (b >= len(s) * ElemSize) or not bitSetIn(s, b): break + if (b >= len(s) * ElemSize) or not bitSetIn(s, b): break dec(b) - if a == b: + if a == b: addSon(result, newIntTypeNode(nkIntLit, a + first, elemType)) - else: + else: n = newNodeI(nkRange, info) n.typ = elemType addSon(n, newIntTypeNode(nkIntLit, a + first, elemType)) @@ -117,7 +117,7 @@ proc toTreeSet(s: TBitSet, settype: PType, info: TLineInfo): PNode = e = b inc(e) -template nodeSetOp(a, b: PNode, op: expr) {.dirty.} = +template nodeSetOp(a, b: PNode, op: expr) {.dirty.} = var x, y: TBitSet toBitSet(a, x) toBitSet(b, y) @@ -129,13 +129,13 @@ proc diffSets(a, b: PNode): PNode = nodeSetOp(a, b, bitSetDiff) proc intersectSets(a, b: PNode): PNode = nodeSetOp(a, b, bitSetIntersect) proc symdiffSets(a, b: PNode): PNode = nodeSetOp(a, b, bitSetSymDiff) -proc containsSets(a, b: PNode): bool = +proc containsSets(a, b: PNode): bool = var x, y: TBitSet toBitSet(a, x) toBitSet(b, y) result = bitSetContains(x, y) -proc equalSets(a, b: PNode): bool = +proc equalSets(a, b: PNode): bool = var x, y: TBitSet toBitSet(a, x) toBitSet(b, y) @@ -147,26 +147,26 @@ proc complement*(a: PNode): PNode = for i in countup(0, high(x)): x[i] = not x[i] result = toTreeSet(x, a.typ, a.info) -proc cardSet(s: PNode): BiggestInt = +proc cardSet(s: PNode): BiggestInt = # here we can do better than converting it into a compact set # we just count the elements directly result = 0 - for i in countup(0, sonsLen(s) - 1): - if s.sons[i].kind == nkRange: + for i in countup(0, sonsLen(s) - 1): + if s.sons[i].kind == nkRange: result = result + getOrdValue(s.sons[i].sons[1]) - getOrdValue(s.sons[i].sons[0]) + 1 - else: + else: inc(result) - -proc setHasRange(s: PNode): bool = + +proc setHasRange(s: PNode): bool = if s.kind != nkCurly: internalError(s.info, "SetHasRange") return false - for i in countup(0, sonsLen(s) - 1): - if s.sons[i].kind == nkRange: + for i in countup(0, sonsLen(s) - 1): + if s.sons[i].kind == nkRange: return true result = false -proc emptyRange(a, b: PNode): bool = +proc emptyRange(a, b: PNode): bool = result = not leValue(a, b) # a > b iff not (a <= b) - + diff --git a/compiler/nversion.nim b/compiler/nversion.nim index 4dea62876..adeb0fb6d 100644 --- a/compiler/nversion.nim +++ b/compiler/nversion.nim @@ -10,7 +10,7 @@ # This module contains Nim's version. It is the only place where it needs # to be changed. -const +const MaxSetElements* = 1 shl 16 # (2^16) to support unicode character sets? VersionAsString* = system.NimVersion RodFileVersion* = "1215" # modify this if the rod-format changes! diff --git a/compiler/passaux.nim b/compiler/passaux.nim index c3bafe7df..9b9fdca4e 100644 --- a/compiler/passaux.nim +++ b/compiler/passaux.nim @@ -9,38 +9,38 @@ ## implements some little helper passes -import +import strutils, ast, astalgo, passes, msgs, options, idgen proc verboseOpen(s: PSym): PPassContext = #MessageOut('compiling ' + s.name.s); result = nil # we don't need a context rawMessage(hintProcessing, s.name.s) - -proc verboseProcess(context: PPassContext, n: PNode): PNode = + +proc verboseProcess(context: PPassContext, n: PNode): PNode = result = n if context != nil: internalError("logpass: context is not nil") - if gVerbosity == 3: + if gVerbosity == 3: # system.nim deactivates all hints, for verbosity:3 we want the processing # messages nonetheless, so we activate them again unconditionally: incl(msgs.gNotes, hintProcessing) message(n.info, hintProcessing, $idgen.gBackendId) - + const verbosePass* = makePass(open = verboseOpen, process = verboseProcess) -proc cleanUp(c: PPassContext, n: PNode): PNode = +proc cleanUp(c: PPassContext, n: PNode): PNode = result = n # we cannot clean up if dead code elimination is activated - if optDeadCodeElim in gGlobalOptions or n == nil: return + if optDeadCodeElim in gGlobalOptions or n == nil: return case n.kind - of nkStmtList: + of nkStmtList: for i in countup(0, sonsLen(n) - 1): discard cleanUp(c, n.sons[i]) - of nkProcDef, nkMethodDef: - if n.sons[namePos].kind == nkSym: + of nkProcDef, nkMethodDef: + if n.sons[namePos].kind == nkSym: var s = n.sons[namePos].sym - if sfDeadCodeElim notin getModule(s).flags and not astNeeded(s): + if sfDeadCodeElim notin getModule(s).flags and not astNeeded(s): s.ast.sons[bodyPos] = ast.emptyNode # free the memory - else: + else: discard const cleanupPass* = makePass(process = cleanUp, close = cleanUp) diff --git a/compiler/patterns.nim b/compiler/patterns.nim index 3f8b05940..604d3521d 100644 --- a/compiler/patterns.nim +++ b/compiler/patterns.nim @@ -68,7 +68,7 @@ proc inSymChoice(sc, x: PNode): bool = elif sc.kind == nkOpenSymChoice: # same name suffices for open sym choices! result = sc.sons[0].sym.name.id == x.sym.name.id - + proc checkTypes(c: PPatternContext, p: PSym, n: PNode): bool = # check param constraints first here as this is quite optimized: if p.constraint != nil: @@ -115,13 +115,13 @@ proc matchNested(c: PPatternContext, p, n: PNode, rpn: bool): bool = if rpn: arglist.add(n.sons[0]) elif n.kind == nkHiddenStdConv and n.sons[1].kind == nkBracket: let n = n.sons[1] - for i in 0.. ", nodecl, varargs.} -proc toStrMaxPrecision*(f: BiggestFloat): string = +proc toStrMaxPrecision*(f: BiggestFloat): string = if f != f: result = "NAN" elif f == 0.0: @@ -21,17 +21,17 @@ proc toStrMaxPrecision*(f: BiggestFloat): string = if f > 0.0: result = "INF" else: result = "-INF" else: - var buf: array [0..80, char] - c_sprintf(buf, "%#.16e", f) + var buf: array [0..80, char] + c_sprintf(buf, "%#.16e", f) result = $buf proc encodeStr*(s: string, result: var string) = - for i in countup(0, len(s) - 1): + for i in countup(0, len(s) - 1): case s[i] of 'a'..'z', 'A'..'Z', '0'..'9', '_': add(result, s[i]) else: add(result, '\\' & toHex(ord(s[i]), 2)) -proc hexChar(c: char, xi: var int) = +proc hexChar(c: char, xi: var int) = case c of '0'..'9': xi = (xi shl 4) or (ord(c) - ord('0')) of 'a'..'f': xi = (xi shl 4) or (ord(c) - ord('a') + 10) @@ -41,18 +41,18 @@ proc hexChar(c: char, xi: var int) = proc decodeStr*(s: cstring, pos: var int): string = var i = pos result = "" - while true: + while true: case s[i] - of '\\': + of '\\': inc(i, 3) var xi = 0 hexChar(s[i-2], xi) hexChar(s[i-1], xi) add(result, chr(xi)) - of 'a'..'z', 'A'..'Z', '0'..'9', '_': + of 'a'..'z', 'A'..'Z', '0'..'9', '_': add(result, s[i]) inc(i) - else: break + else: break pos = i const @@ -68,11 +68,11 @@ template encodeIntImpl(self: expr) = var d: char var v = x var rem = v mod 190 - if rem < 0: + if rem < 0: add(result, '-') v = - (v div 190) rem = - rem - else: + else: v = v div 190 var idx = int(rem) if idx < 62: d = chars[idx] @@ -89,11 +89,11 @@ proc encodeVBiggestInt*(x: BiggestInt, result: var string) = encodeVBiggestIntAux(x +% vintDelta, result) # encodeIntImpl(encodeVBiggestInt) -proc encodeVIntAux(x: int, result: var string) = +proc encodeVIntAux(x: int, result: var string) = ## encode an int as a variable length base 190 int. encodeIntImpl(encodeVIntAux) - -proc encodeVInt*(x: int, result: var string) = + +proc encodeVInt*(x: int, result: var string) = ## encode an int as a variable length base 190 int. encodeVIntAux(x +% vintDelta, result) @@ -101,11 +101,11 @@ template decodeIntImpl() = var i = pos var sign = - 1 assert(s[i] in {'a'..'z', 'A'..'Z', '0'..'9', '-', '\x80'..'\xFF'}) - if s[i] == '-': + if s[i] == '-': inc(i) sign = 1 result = 0 - while true: + while true: case s[i] of '0'..'9': result = result * 190 - (ord(s[i]) - ord('0')) of 'a'..'z': result = result * 190 - (ord(s[i]) - ord('a') + 10) @@ -116,7 +116,7 @@ template decodeIntImpl() = result = result * sign -% vintDelta pos = i -proc decodeVInt*(s: cstring, pos: var int): int = +proc decodeVInt*(s: cstring, pos: var int): int = decodeIntImpl() proc decodeVBiggestInt*(s: cstring, pos: var int): BiggestInt = diff --git a/compiler/ropes.nim b/compiler/ropes.nim index edac8e9d0..bfae7aaa4 100644 --- a/compiler/ropes.nim +++ b/compiler/ropes.nim @@ -306,7 +306,7 @@ const proc equalsFile*(r: Rope, f: File): bool = ## returns true if the contents of the file `f` equal `r`. - var + var buf: array[bufSize, char] bpos = buf.len blen = buf.len diff --git a/compiler/saturate.nim b/compiler/saturate.nim index f4fe29a20..065cb5128 100644 --- a/compiler/saturate.nim +++ b/compiler/saturate.nim @@ -72,7 +72,7 @@ proc `|*|`*(a, b: BiggestInt): BiggestInt = # 32 * abs(diff) <= abs(prod) -- 5 good bits is "close enough" if 32.0 * abs(resAsFloat - floatProd) <= abs(floatProd): return result - + if floatProd >= 0.0: result = high(result) else: diff --git a/compiler/semcall.nim b/compiler/semcall.nim index e2ff16c6e..2f181b5f3 100644 --- a/compiler/semcall.nim +++ b/compiler/semcall.nim @@ -320,7 +320,7 @@ proc semResolvedCall(c: PContext, n: PNode, x: TCandidate): PNode = x.call.add newSymNode(s, n.info) else: internalAssert false - + result = x.call instGenericConvertersSons(c, result, x) result.sons[0] = newSymNode(finalCallee, result.sons[0].info) diff --git a/compiler/semfields.nim b/compiler/semfields.nim index e086e73f8..2e6c6c3ea 100644 --- a/compiler/semfields.nim +++ b/compiler/semfields.nim @@ -76,7 +76,7 @@ proc semForObjectFields(c: TFieldsCtx, typ, forLoop, father: PNode) = let L = forLoop.len let call = forLoop.sons[L-2] if call.len > 2: - localError(forLoop.info, errGenerated, + localError(forLoop.info, errGenerated, "parallel 'fields' iterator does not work for 'case' objects") return # iterate over the selector: @@ -106,7 +106,7 @@ proc semForFields(c: PContext, n: PNode, m: TMagic): PNode = # a 'while true: stmt; break' loop ... result = newNodeI(nkWhileStmt, n.info, 2) var trueSymbol = strTableGet(magicsys.systemModule.tab, getIdent"true") - if trueSymbol == nil: + if trueSymbol == nil: localError(n.info, errSystemNeeds, "true") trueSymbol = newSym(skUnknown, getIdent"true", getCurrOwner(), n.info) trueSymbol.typ = getSysType(tyBool) @@ -114,13 +114,13 @@ proc semForFields(c: PContext, n: PNode, m: TMagic): PNode = result.sons[0] = newSymNode(trueSymbol, n.info) var stmts = newNodeI(nkStmtList, n.info) result.sons[1] = stmts - + var length = sonsLen(n) var call = n.sons[length-2] if length-2 != sonsLen(call)-1 + ord(m==mFieldPairs): localError(n.info, errWrongNumberOfVariables) return result - + var tupleTypeA = skipTypes(call.sons[1].typ, abstractVar-{tyTypeDesc}) if tupleTypeA.kind notin {tyTuple, tyObject}: localError(n.info, errGenerated, "no object or tuple type") @@ -129,7 +129,7 @@ proc semForFields(c: PContext, n: PNode, m: TMagic): PNode = var tupleTypeB = skipTypes(call.sons[i].typ, abstractVar-{tyTypeDesc}) if not sameType(tupleTypeA, tupleTypeB): typeMismatch(call.sons[i], tupleTypeA, tupleTypeB) - + inc(c.p.nestedLoopCounter) if tupleTypeA.kind == tyTuple: var loopBody = n.sons[length-1] diff --git a/compiler/sigmatch.nim b/compiler/sigmatch.nim index 357c6cf32..61f1a7444 100644 --- a/compiler/sigmatch.nim +++ b/compiler/sigmatch.nim @@ -1327,7 +1327,7 @@ proc paramTypesMatchAux(m: var TCandidate, f, argType: PType, # because in that case there is no point in continuing. var bothMetaCounter = 0 var lastBindingsLength = -1 - while r == isBothMetaConvertible and + while r == isBothMetaConvertible and lastBindingsLength != m.bindings.counter and bothMetaCounter < 100: lastBindingsLength = m.bindings.counter diff --git a/compiler/suggest.nim b/compiler/suggest.nim index 659f1fa16..c15a56c54 100644 --- a/compiler/suggest.nim +++ b/compiler/suggest.nim @@ -34,7 +34,7 @@ var template origModuleName(m: PSym): string = m.name.s -proc symToSuggest(s: PSym, isLocal: bool, section: string, li: TLineInfo): Suggest = +proc symToSuggest(s: PSym, isLocal: bool, section: string, li: TLineInfo): Suggest = result.section = parseIdeCmd(section) if optIdeTerse in gGlobalOptions: result.symkind = s.kind @@ -52,7 +52,7 @@ proc symToSuggest(s: PSym, isLocal: bool, section: string, li: TLineInfo): Sugge result.qualifiedPath.add(ow.origModuleName) result.qualifiedPath.add(s.name.s) - if s.typ != nil: + if s.typ != nil: result.forth = typeToString(s.typ) else: result.forth = "" @@ -62,7 +62,7 @@ proc symToSuggest(s: PSym, isLocal: bool, section: string, li: TLineInfo): Sugge when not defined(noDocgen): result.doc = s.extractDocComment -proc `$`(suggest: Suggest): string = +proc `$`(suggest: Suggest): string = result = $suggest.section result.add(sep) result.add($suggest.symkind) @@ -80,7 +80,7 @@ proc `$`(suggest: Suggest): string = when not defined(noDocgen): result.add(suggest.doc.escape) -proc symToSuggest(s: PSym, isLocal: bool, section: string): Suggest = +proc symToSuggest(s: PSym, isLocal: bool, section: string): Suggest = result = symToSuggest(s, isLocal, section, s.info) proc suggestResult(s: Suggest) = @@ -104,7 +104,7 @@ proc fieldVisible*(c: PContext, f: PSym): bool {.inline.} = result = true break -proc suggestField(c: PContext, s: PSym, outputs: var int) = +proc suggestField(c: PContext, s: PSym, outputs: var int) = if filterSym(s) and fieldVisible(c, s): suggestResult(symToSuggest(s, isLocal=true, $ideSug)) inc outputs @@ -122,17 +122,17 @@ template wholeSymTab(cond, section: expr) {.immediate.} = suggestResult(symToSuggest(it, isLocal = isLocal, section)) inc outputs -proc suggestSymList(c: PContext, list: PNode, outputs: var int) = - for i in countup(0, sonsLen(list) - 1): +proc suggestSymList(c: PContext, list: PNode, outputs: var int) = + for i in countup(0, sonsLen(list) - 1): if list.sons[i].kind == nkSym: suggestField(c, list.sons[i].sym, outputs) #else: InternalError(list.info, "getSymFromList") -proc suggestObject(c: PContext, n: PNode, outputs: var int) = +proc suggestObject(c: PContext, n: PNode, outputs: var int) = case n.kind - of nkRecList: + of nkRecList: for i in countup(0, sonsLen(n)-1): suggestObject(c, n.sons[i], outputs) - of nkRecCase: + of nkRecCase: var L = sonsLen(n) if L > 0: suggestObject(c, n.sons[0], outputs) @@ -140,7 +140,7 @@ proc suggestObject(c: PContext, n: PNode, outputs: var int) = of nkSym: suggestField(c, n.sym, outputs) else: discard -proc nameFits(c: PContext, s: PSym, n: PNode): bool = +proc nameFits(c: PContext, s: PSym, n: PNode): bool = var op = n.sons[0] if op.kind in {nkOpenSymChoice, nkClosedSymChoice}: op = op.sons[0] var opr: PIdent @@ -150,8 +150,8 @@ proc nameFits(c: PContext, s: PSym, n: PNode): bool = else: return false result = opr.id == s.name.id -proc argsFit(c: PContext, candidate: PSym, n, nOrig: PNode): bool = - case candidate.kind +proc argsFit(c: PContext, candidate: PSym, n, nOrig: PNode): bool = + case candidate.kind of OverloadableSyms: var m: TCandidate initCandidate(c, m, candidate, nil) @@ -160,11 +160,11 @@ proc argsFit(c: PContext, candidate: PSym, n, nOrig: PNode): bool = else: result = false -proc suggestCall(c: PContext, n, nOrig: PNode, outputs: var int) = +proc suggestCall(c: PContext, n, nOrig: PNode, outputs: var int) = wholeSymTab(filterSym(it) and nameFits(c, it, n) and argsFit(c, it, n, nOrig), $ideCon) -proc typeFits(c: PContext, s: PSym, firstArg: PType): bool {.inline.} = +proc typeFits(c: PContext, s: PSym, firstArg: PType): bool {.inline.} = if s.typ != nil and sonsLen(s.typ) > 1 and s.typ.sons[1] != nil: # special rule: if system and some weird generic match via 'tyExpr' # or 'tyGenericParam' we won't list it either to reduce the noise (nobody @@ -198,48 +198,48 @@ proc suggestFieldAccess(c: PContext, n: PNode, outputs: var int) = var typ = n.typ if typ == nil: # a module symbol has no type for example: - if n.kind == nkSym and n.sym.kind == skModule: - if n.sym == c.module: + if n.kind == nkSym and n.sym.kind == skModule: + if n.sym == c.module: # all symbols accessible, because we are in the current module: for it in items(c.topLevelScope.symbols): - if filterSym(it): + if filterSym(it): suggestResult(symToSuggest(it, isLocal=false, $ideSug)) inc outputs - else: - for it in items(n.sym.tab): - if filterSym(it): + else: + for it in items(n.sym.tab): + if filterSym(it): suggestResult(symToSuggest(it, isLocal=false, $ideSug)) inc outputs else: # fallback: suggestEverything(c, n, outputs) - elif typ.kind == tyEnum and n.kind == nkSym and n.sym.kind == skType: + elif typ.kind == tyEnum and n.kind == nkSym and n.sym.kind == skType: # look up if the identifier belongs to the enum: var t = typ - while t != nil: + while t != nil: suggestSymList(c, t.n, outputs) t = t.sons[0] suggestOperations(c, n, typ, outputs) else: typ = skipTypes(typ, {tyGenericInst, tyVar, tyPtr, tyRef}) - if typ.kind == tyObject: + if typ.kind == tyObject: var t = typ - while true: + while true: suggestObject(c, t.n, outputs) - if t.sons[0] == nil: break + if t.sons[0] == nil: break t = skipTypes(t.sons[0], {tyGenericInst}) suggestOperations(c, n, typ, outputs) - elif typ.kind == tyTuple and typ.n != nil: + elif typ.kind == tyTuple and typ.n != nil: suggestSymList(c, typ.n, outputs) suggestOperations(c, n, typ, outputs) else: suggestOperations(c, n, typ, outputs) type - TCheckPointResult = enum + TCheckPointResult = enum cpNone, cpFuzzy, cpExact -proc inCheckpoint(current: TLineInfo): TCheckPointResult = +proc inCheckpoint(current: TLineInfo): TCheckPointResult = if current.fileIndex == gTrackPos.fileIndex: if current.line == gTrackPos.line and abs(current.col-gTrackPos.col) < 4: @@ -255,8 +255,8 @@ proc findClosestDot(n: PNode): PNode = result = findClosestDot(n.sons[i]) if result != nil: return -proc findClosestCall(n: PNode): PNode = - if n.kind in nkCallKinds and inCheckpoint(n.info) == cpExact: +proc findClosestCall(n: PNode): PNode = + if n.kind in nkCallKinds and inCheckpoint(n.info) == cpExact: result = n else: for i in 0.. = current.col and col <= current.col+tokenLen-1: return true -proc findClosestSym(n: PNode): PNode = - if n.kind == nkSym and inCheckpoint(n.info) == cpExact: +proc findClosestSym(n: PNode): PNode = + if n.kind == nkSym and inCheckpoint(n.info) == cpExact: result = n elif n.kind notin {nkNone..nkNilLit}: for i in 0.. 0 and gIdeCmd != ideUse: suggestQuit() -proc suggestStmt*(c: PContext, n: PNode) = +proc suggestStmt*(c: PContext, n: PNode) = suggestExpr(c, n) diff --git a/compiler/syntaxes.nim b/compiler/syntaxes.nim index 5fd81d87e..91cfdbefd 100644 --- a/compiler/syntaxes.nim +++ b/compiler/syntaxes.nim @@ -9,24 +9,24 @@ ## Implements the dispatcher for the different parsers. -import - strutils, llstream, ast, astalgo, idents, lexer, options, msgs, parser, +import + strutils, llstream, ast, astalgo, idents, lexer, options, msgs, parser, pbraces, filters, filter_tmpl, renderer -type - TFilterKind* = enum +type + TFilterKind* = enum filtNone, filtTemplate, filtReplace, filtStrip - TParserKind* = enum + TParserKind* = enum skinStandard, skinStrongSpaces, skinBraces, skinEndX -const +const parserNames*: array[TParserKind, string] = ["standard", "strongspaces", "braces", "endx"] filterNames*: array[TFilterKind, string] = ["none", "stdtmpl", "replace", "strip"] type - TParsers*{.final.} = object + TParsers*{.final.} = object skin*: TParserKind parser*: TParser @@ -42,53 +42,53 @@ proc parseTopLevelStmt*(p: var TParsers): PNode # implementation proc parseFile(fileIdx: int32): PNode = - var + var p: TParsers f: File let filename = fileIdx.toFullPathConsiderDirty if not open(f, filename): rawMessage(errCannotOpenFile, filename) - return + return openParsers(p, fileIdx, llStreamOpen(f)) result = parseAll(p) closeParsers(p) -proc parseAll(p: var TParsers): PNode = +proc parseAll(p: var TParsers): PNode = case p.skin of skinStandard, skinStrongSpaces: result = parser.parseAll(p.parser) - of skinBraces: + of skinBraces: result = pbraces.parseAll(p.parser) - of skinEndX: - internalError("parser to implement") + of skinEndX: + internalError("parser to implement") result = ast.emptyNode - -proc parseTopLevelStmt(p: var TParsers): PNode = + +proc parseTopLevelStmt(p: var TParsers): PNode = case p.skin of skinStandard, skinStrongSpaces: result = parser.parseTopLevelStmt(p.parser) - of skinBraces: + of skinBraces: result = pbraces.parseTopLevelStmt(p.parser) - of skinEndX: - internalError("parser to implement") + of skinEndX: + internalError("parser to implement") result = ast.emptyNode - -proc utf8Bom(s: string): int = - if (s[0] == '\xEF') and (s[1] == '\xBB') and (s[2] == '\xBF'): + +proc utf8Bom(s: string): int = + if (s[0] == '\xEF') and (s[1] == '\xBB') and (s[2] == '\xBF'): result = 3 - else: + else: result = 0 - -proc containsShebang(s: string, i: int): bool = - if (s[i] == '#') and (s[i + 1] == '!'): + +proc containsShebang(s: string, i: int): bool = + if (s[i] == '#') and (s[i + 1] == '!'): var j = i + 2 while s[j] in Whitespace: inc(j) result = s[j] == '/' -proc parsePipe(filename: string, inputStream: PLLStream): PNode = +proc parsePipe(filename: string, inputStream: PLLStream): PNode = result = ast.emptyNode var s = llStreamOpen(filename, fmRead) - if s != nil: + if s != nil: var line = newStringOfCap(80) discard llStreamReadLine(s, line) var i = utf8Bom(line) @@ -104,50 +104,50 @@ proc parsePipe(filename: string, inputStream: PLLStream): PNode = closeParser(q) llStreamClose(s) -proc getFilter(ident: PIdent): TFilterKind = - for i in countup(low(TFilterKind), high(TFilterKind)): - if identEq(ident, filterNames[i]): +proc getFilter(ident: PIdent): TFilterKind = + for i in countup(low(TFilterKind), high(TFilterKind)): + if identEq(ident, filterNames[i]): return i result = filtNone -proc getParser(ident: PIdent): TParserKind = - for i in countup(low(TParserKind), high(TParserKind)): - if identEq(ident, parserNames[i]): +proc getParser(ident: PIdent): TParserKind = + for i in countup(low(TParserKind), high(TParserKind)): + if identEq(ident, parserNames[i]): return i rawMessage(errInvalidDirectiveX, ident.s) -proc getCallee(n: PNode): PIdent = - if n.kind in nkCallKinds and n.sons[0].kind == nkIdent: +proc getCallee(n: PNode): PIdent = + if n.kind in nkCallKinds and n.sons[0].kind == nkIdent: result = n.sons[0].ident - elif n.kind == nkIdent: + elif n.kind == nkIdent: result = n.ident - else: + else: rawMessage(errXNotAllowedHere, renderTree(n)) - -proc applyFilter(p: var TParsers, n: PNode, filename: string, - stdin: PLLStream): PLLStream = + +proc applyFilter(p: var TParsers, n: PNode, filename: string, + stdin: PLLStream): PLLStream = var ident = getCallee(n) var f = getFilter(ident) case f - of filtNone: + of filtNone: p.skin = getParser(ident) result = stdin - of filtTemplate: + of filtTemplate: result = filterTmpl(stdin, filename, n) - of filtStrip: + of filtStrip: result = filterStrip(stdin, filename, n) - of filtReplace: + of filtReplace: result = filterReplace(stdin, filename, n) - if f != filtNone: + if f != filtNone: if hintCodeBegin in gNotes: rawMessage(hintCodeBegin, []) msgWriteln(result.s) rawMessage(hintCodeEnd, []) -proc evalPipe(p: var TParsers, n: PNode, filename: string, - start: PLLStream): PLLStream = +proc evalPipe(p: var TParsers, n: PNode, filename: string, + start: PLLStream): PLLStream = result = start - if n.kind == nkEmpty: return + if n.kind == nkEmpty: return if n.kind == nkInfix and n.sons[0].kind == nkIdent and identEq(n.sons[0].ident, "|"): for i in countup(1, 2): @@ -159,8 +159,8 @@ proc evalPipe(p: var TParsers, n: PNode, filename: string, result = evalPipe(p, n.sons[0], filename, result) else: result = applyFilter(p, n, filename, result) - -proc openParsers(p: var TParsers, fileIdx: int32, inputstream: PLLStream) = + +proc openParsers(p: var TParsers, fileIdx: int32, inputstream: PLLStream) = var s: PLLStream p.skin = skinStandard let filename = fileIdx.toFullPathConsiderDirty @@ -172,6 +172,6 @@ proc openParsers(p: var TParsers, fileIdx: int32, inputstream: PLLStream) = parser.openParser(p.parser, fileIdx, s, false) of skinStrongSpaces: parser.openParser(p.parser, fileIdx, s, true) - + proc closeParsers(p: var TParsers) = parser.closeParser(p.parser) diff --git a/compiler/tccgen.nim b/compiler/tccgen.nim index 0082dfcbb..7616641fc 100644 --- a/compiler/tccgen.nim +++ b/compiler/tccgen.nim @@ -12,10 +12,10 @@ import {.compile: "../tinyc/libtcc.c".} -proc tinyCErrorHandler(closure: pointer, msg: cstring) {.cdecl.} = +proc tinyCErrorHandler(closure: pointer, msg: cstring) {.cdecl.} = rawMessage(errGenerated, $msg) - -proc initTinyCState: PccState = + +proc initTinyCState: PccState = result = openCCState() setErrorFunc(result, nil, tinyCErrorHandler) @@ -23,25 +23,25 @@ var gTinyC = initTinyCState() libIncluded = false -proc addFile(filename: string) = +proc addFile(filename: string) = if addFile(gTinyC, filename) != 0'i32: rawMessage(errCannotOpenFile, filename) -proc setupEnvironment = +proc setupEnvironment = when defined(amd64): defineSymbol(gTinyC, "__x86_64__", nil) elif defined(i386): - defineSymbol(gTinyC, "__i386__", nil) + defineSymbol(gTinyC, "__i386__", nil) when defined(linux): defineSymbol(gTinyC, "__linux__", nil) defineSymbol(gTinyC, "__linux", nil) var nimrodDir = getPrefixDir() addIncludePath(gTinyC, libpath) - when defined(windows): + when defined(windows): addSysincludePath(gTinyC, nimrodDir / "tinyc/win32/include") addSysincludePath(gTinyC, nimrodDir / "tinyc/include") - when defined(windows): + when defined(windows): defineSymbol(gTinyC, "_WIN32", nil) # we need Mingw's headers too: var gccbin = getConfigVar("gcc.path") % ["nimrod", nimrodDir] @@ -54,7 +54,7 @@ proc setupEnvironment = #addFile(nimrodDir / r"tinyc\win32\dllcrt1.o") #addFile(nimrodDir / r"tinyc\win32\dllmain.o") addFile(nimrodDir / r"tinyc\win32\libtcc1.o") - + #addFile(nimrodDir / r"tinyc\win32\lib\crt1.c") #addFile(nimrodDir / r"tinyc\lib\libtcc1.c") else: @@ -62,12 +62,12 @@ proc setupEnvironment = when defined(amd64): addSysincludePath(gTinyC, "/usr/include/x86_64-linux-gnu") -proc compileCCode*(ccode: string) = +proc compileCCode*(ccode: string) = if not libIncluded: libIncluded = true setupEnvironment() discard compileString(gTinyC, ccode) - + proc run*(args: string) = var s = @[cstring(gProjectName)] & map(split(args), proc(x: string): cstring = cstring(x)) var err = tinyc.run(gTinyC, cint(len(s)), cast[cstringArray](addr(s[0]))) != 0'i32 diff --git a/compiler/treetab.nim b/compiler/treetab.nim index adfc7b2ce..e6eb8c666 100644 --- a/compiler/treetab.nim +++ b/compiler/treetab.nim @@ -9,36 +9,36 @@ # Implements a table from trees to trees. Does structural equivalence checking. -import +import hashes, ast, astalgo, types -proc hashTree(n: PNode): Hash = - if n == nil: return +proc hashTree(n: PNode): Hash = + if n == nil: return result = ord(n.kind) case n.kind - of nkEmpty, nkNilLit, nkType: + of nkEmpty, nkNilLit, nkType: discard - of nkIdent: + of nkIdent: result = result !& n.ident.h of nkSym: result = result !& n.sym.name.h - of nkCharLit..nkUInt64Lit: - if (n.intVal >= low(int)) and (n.intVal <= high(int)): + of nkCharLit..nkUInt64Lit: + if (n.intVal >= low(int)) and (n.intVal <= high(int)): result = result !& int(n.intVal) of nkFloatLit..nkFloat64Lit: - if (n.floatVal >= - 1000000.0) and (n.floatVal <= 1000000.0): + if (n.floatVal >= - 1000000.0) and (n.floatVal <= 1000000.0): result = result !& toInt(n.floatVal) of nkStrLit..nkTripleStrLit: if not n.strVal.isNil: result = result !& hash(n.strVal) - else: - for i in countup(0, sonsLen(n) - 1): + else: + for i in countup(0, sonsLen(n) - 1): result = result !& hashTree(n.sons[i]) - -proc treesEquivalent(a, b: PNode): bool = - if a == b: + +proc treesEquivalent(a, b: PNode): bool = + if a == b: result = true - elif (a != nil) and (b != nil) and (a.kind == b.kind): + elif (a != nil) and (b != nil) and (a.kind == b.kind): case a.kind of nkEmpty, nkNilLit, nkType: result = true of nkSym: result = a.sym.id == b.sym.id @@ -46,28 +46,28 @@ proc treesEquivalent(a, b: PNode): bool = of nkCharLit..nkUInt64Lit: result = a.intVal == b.intVal of nkFloatLit..nkFloat64Lit: result = a.floatVal == b.floatVal of nkStrLit..nkTripleStrLit: result = a.strVal == b.strVal - else: - if sonsLen(a) == sonsLen(b): - for i in countup(0, sonsLen(a) - 1): - if not treesEquivalent(a.sons[i], b.sons[i]): return + else: + if sonsLen(a) == sonsLen(b): + for i in countup(0, sonsLen(a) - 1): + if not treesEquivalent(a.sons[i], b.sons[i]): return result = true if result: result = sameTypeOrNil(a.typ, b.typ) - -proc nodeTableRawGet(t: TNodeTable, k: Hash, key: PNode): int = + +proc nodeTableRawGet(t: TNodeTable, k: Hash, key: PNode): int = var h: Hash = k and high(t.data) - while t.data[h].key != nil: - if (t.data[h].h == k) and treesEquivalent(t.data[h].key, key): + while t.data[h].key != nil: + if (t.data[h].h == k) and treesEquivalent(t.data[h].key, key): return h h = nextTry(h, high(t.data)) result = -1 -proc nodeTableGet*(t: TNodeTable, key: PNode): int = +proc nodeTableGet*(t: TNodeTable, key: PNode): int = var index = nodeTableRawGet(t, hashTree(key), key) if index >= 0: result = t.data[index].val else: result = low(int) - -proc nodeTableRawInsert(data: var TNodePairSeq, k: Hash, key: PNode, - val: int) = + +proc nodeTableRawInsert(data: var TNodePairSeq, k: Hash, key: PNode, + val: int) = var h: Hash = k and high(data) while data[h].key != nil: h = nextTry(h, high(data)) assert(data[h].key == nil) @@ -75,35 +75,35 @@ proc nodeTableRawInsert(data: var TNodePairSeq, k: Hash, key: PNode, data[h].key = key data[h].val = val -proc nodeTablePut*(t: var TNodeTable, key: PNode, val: int) = +proc nodeTablePut*(t: var TNodeTable, key: PNode, val: int) = var n: TNodePairSeq var k: Hash = hashTree(key) var index = nodeTableRawGet(t, k, key) - if index >= 0: + if index >= 0: assert(t.data[index].key != nil) t.data[index].val = val - else: - if mustRehash(len(t.data), t.counter): + else: + if mustRehash(len(t.data), t.counter): newSeq(n, len(t.data) * GrowthFactor) - for i in countup(0, high(t.data)): - if t.data[i].key != nil: + for i in countup(0, high(t.data)): + if t.data[i].key != nil: nodeTableRawInsert(n, t.data[i].h, t.data[i].key, t.data[i].val) swap(t.data, n) nodeTableRawInsert(t.data, k, key, val) inc(t.counter) -proc nodeTableTestOrSet*(t: var TNodeTable, key: PNode, val: int): int = +proc nodeTableTestOrSet*(t: var TNodeTable, key: PNode, val: int): int = var n: TNodePairSeq var k: Hash = hashTree(key) var index = nodeTableRawGet(t, k, key) - if index >= 0: + if index >= 0: assert(t.data[index].key != nil) result = t.data[index].val - else: - if mustRehash(len(t.data), t.counter): + else: + if mustRehash(len(t.data), t.counter): newSeq(n, len(t.data) * GrowthFactor) - for i in countup(0, high(t.data)): - if t.data[i].key != nil: + for i in countup(0, high(t.data)): + if t.data[i].key != nil: nodeTableRawInsert(n, t.data[i].h, t.data[i].key, t.data[i].val) swap(t.data, n) nodeTableRawInsert(t.data, k, key, val) From 43bddf62dd982e64cd7350eabbbc5d04c5adab21 Mon Sep 17 00:00:00 2001 From: Adam Strzelecki Date: Fri, 4 Sep 2015 23:03:56 +0200 Subject: [PATCH 0898/1263] lib: Trim .nim files trailing whitespace via OSX: find . -name '*.nim' -exec sed -i '' -E 's/[[:space:]]+$//' {} + --- lib/impure/db_mysql.nim | 70 ++-- lib/impure/db_postgres.nim | 36 +- lib/impure/db_sqlite.nim | 84 ++-- lib/impure/graphics.nim | 110 +++--- lib/impure/re.nim | 6 +- lib/impure/ssl.nim | 26 +- lib/nimrtl.nim | 8 +- lib/posix/epoll.nim | 36 +- lib/posix/inotify.nim | 94 ++--- lib/posix/linux.nim | 2 +- lib/pure/actors.nim | 10 +- lib/pure/asyncfile.nim | 10 +- lib/pure/base64.nim | 42 +- lib/pure/basic2d.nim | 234 ++++++------ lib/pure/collections/LockFreeHash.nim | 364 +++++++++--------- lib/pure/collections/critbits.nim | 16 +- lib/pure/collections/lists.nim | 94 ++--- lib/pure/collections/queues.nim | 4 +- lib/pure/colors.nim | 44 +-- lib/pure/complex.nim | 8 +- lib/pure/concurrency/cpuinfo.nim | 2 +- lib/pure/cookies.nim | 10 +- lib/pure/encodings.nim | 366 +++++++++--------- lib/pure/endians.nim | 6 +- lib/pure/etcpriv.nim | 2 +- lib/pure/events.nim | 12 +- lib/pure/fsmonitor.nim | 30 +- lib/pure/httpserver.nim | 48 +-- lib/pure/matchers.nim | 12 +- lib/pure/memfiles.nim | 10 +- lib/pure/mersenne.nim | 2 +- lib/pure/numeric.nim | 20 +- lib/pure/oids.nim | 18 +- lib/pure/parsecfg.nim | 200 +++++----- lib/pure/parsecsv.nim | 40 +- lib/pure/parsesql.nim | 218 +++++------ lib/pure/parseurl.nim | 22 +- lib/pure/poly.nim | 90 ++--- lib/pure/rationals.nim | 2 +- lib/pure/redis.nim | 146 +++---- lib/pure/romans.nim | 4 +- lib/pure/ropes.nim | 20 +- lib/pure/scgi.nim | 68 ++-- lib/pure/smtp.nim | 60 +-- lib/pure/sockets.nim | 240 ++++++------ lib/pure/subexes.nim | 48 +-- lib/pure/unicode.nim | 2 +- lib/pure/unidecode/unidecode.nim | 22 +- lib/pure/xmldomparser.nim | 44 +-- lib/pure/xmlparser.nim | 38 +- lib/system/ansi_c.nim | 22 +- lib/system/avltree.nim | 4 +- lib/system/cellsets.nim | 10 +- lib/system/channels.nim | 522 ++++++++++++------------- lib/system/deepcopy.nim | 10 +- lib/system/gc2.nim | 140 +++---- lib/system/gc_common.nim | 4 +- lib/system/inclrtl.nim | 8 +- lib/system/profiler.nim | 2 +- lib/system/syslocks.nim | 20 +- lib/system/sysspawn.nim | 2 +- lib/system/timers.nim | 24 +- lib/system/widestrs.nim | 6 +- lib/wrappers/libsvm.nim | 108 +++--- lib/wrappers/mysql.nim | 530 +++++++++++++------------- lib/wrappers/sqlite3.nim | 334 ++++++++-------- lib/wrappers/tinyc.nim | 24 +- 67 files changed, 2435 insertions(+), 2435 deletions(-) diff --git a/lib/impure/db_mysql.nim b/lib/impure/db_mysql.nim index 197286f29..d61d951ba 100644 --- a/lib/impure/db_mysql.nim +++ b/lib/impure/db_mysql.nim @@ -7,7 +7,7 @@ # distribution, for details about the copyright. # -## A higher level `mySQL`:idx: database wrapper. The same interface is +## A higher level `mySQL`:idx: database wrapper. The same interface is ## implemented for other databases too. import strutils, mysql @@ -29,22 +29,22 @@ type {.deprecated: [TRow: Row, TSqlQuery: SqlQuery, TDbConn: DbConn].} proc sql*(query: string): SqlQuery {.noSideEffect, inline.} = - ## constructs a SqlQuery from the string `query`. This is supposed to be + ## constructs a SqlQuery from the string `query`. This is supposed to be ## used as a raw-string-literal modifier: ## ``sql"update user set counter = counter + 1"`` ## - ## If assertions are turned off, it does nothing. If assertions are turned + ## If assertions are turned off, it does nothing. If assertions are turned ## on, later versions will check the string for valid syntax. result = SqlQuery(query) -proc dbError(db: DbConn) {.noreturn.} = +proc dbError(db: DbConn) {.noreturn.} = ## raises an EDb exception. var e: ref EDb new(e) e.msg = $mysql.error(db) raise e -proc dbError*(msg: string) {.noreturn.} = +proc dbError*(msg: string) {.noreturn.} = ## raises an EDb exception with message `msg`. var e: ref EDb new(e) @@ -55,9 +55,9 @@ when false: proc dbQueryOpt*(db: DbConn, query: string, args: varargs[string, `$`]) = var stmt = mysql_stmt_init(db) if stmt == nil: dbError(db) - if mysql_stmt_prepare(stmt, query, len(query)) != 0: + if mysql_stmt_prepare(stmt, query, len(query)) != 0: dbError(db) - var + var binding: seq[MYSQL_BIND] discard mysql_stmt_close(stmt) @@ -79,9 +79,9 @@ proc dbFormat(formatstr: SqlQuery, args: varargs[string]): string = else: add(result, dbQuote(args[a])) inc(a) - else: + else: add(result, c) - + proc tryExec*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]): bool {. tags: [FReadDB, FWriteDb].} = ## tries to execute the query and returns true if successful, false otherwise. @@ -97,19 +97,19 @@ proc exec*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]) {. ## executes the query and raises EDB if not successful. var q = dbFormat(query, args) if mysql.realQuery(db, q, q.len) != 0'i32: dbError(db) - -proc newRow(L: int): Row = + +proc newRow(L: int): Row = newSeq(result, L) for i in 0..L-1: result[i] = "" - -proc properFreeResult(sqlres: mysql.PRES, row: cstringArray) = + +proc properFreeResult(sqlres: mysql.PRES, row: cstringArray) = if row != nil: while mysql.fetchRow(sqlres) != nil: discard mysql.freeResult(sqlres) - + iterator fastRows*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]): Row {.tags: [FReadDB].} = - ## executes the query and iterates over the result dataset. This is very + ## executes the query and iterates over the result dataset. This is very ## fast, but potenially dangerous: If the for-loop-body executes another ## query, the results can be undefined. For MySQL this is the case!. rawExec(db, query, args) @@ -121,7 +121,7 @@ iterator fastRows*(db: DbConn, query: SqlQuery, while true: row = mysql.fetchRow(sqlres) if row == nil: break - for i in 0..L-1: + for i in 0..L-1: setLen(result[i], 0) if row[i] == nil: result[i] = nil @@ -164,8 +164,8 @@ proc getRow*(db: DbConn, query: SqlQuery, var L = int(mysql.numFields(sqlres)) result = newRow(L) var row = mysql.fetchRow(sqlres) - if row != nil: - for i in 0..L-1: + if row != nil: + for i in 0..L-1: setLen(result[i], 0) if row[i] == nil: result[i] = nil @@ -173,7 +173,7 @@ proc getRow*(db: DbConn, query: SqlQuery, add(result[i], row[i]) properFreeResult(sqlres, row) -proc getAllRows*(db: DbConn, query: SqlQuery, +proc getAllRows*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]): seq[Row] {.tags: [FReadDB].} = ## executes the query and returns the whole result dataset. result = @[] @@ -196,44 +196,44 @@ proc getAllRows*(db: DbConn, query: SqlQuery, inc(j) mysql.freeResult(sqlres) -iterator rows*(db: DbConn, query: SqlQuery, +iterator rows*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]): Row {.tags: [FReadDB].} = ## same as `fastRows`, but slower and safe. for r in items(getAllRows(db, query, args)): yield r -proc getValue*(db: DbConn, query: SqlQuery, - args: varargs[string, `$`]): string {.tags: [FReadDB].} = +proc getValue*(db: DbConn, query: SqlQuery, + args: varargs[string, `$`]): string {.tags: [FReadDB].} = ## executes the query and returns the first column of the first row of the ## result dataset. Returns "" if the dataset contains no rows or the database ## value is NULL. result = getRow(db, query, args)[0] -proc tryInsertId*(db: DbConn, query: SqlQuery, +proc tryInsertId*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]): int64 {.tags: [FWriteDb].} = - ## executes the query (typically "INSERT") and returns the + ## executes the query (typically "INSERT") and returns the ## generated ID for the row or -1 in case of an error. var q = dbFormat(query, args) - if mysql.realQuery(db, q, q.len) != 0'i32: + if mysql.realQuery(db, q, q.len) != 0'i32: result = -1'i64 else: result = mysql.insertId(db) - -proc insertId*(db: DbConn, query: SqlQuery, - args: varargs[string, `$`]): int64 {.tags: [FWriteDb].} = - ## executes the query (typically "INSERT") and returns the + +proc insertId*(db: DbConn, query: SqlQuery, + args: varargs[string, `$`]): int64 {.tags: [FWriteDb].} = + ## executes the query (typically "INSERT") and returns the ## generated ID for the row. result = tryInsertID(db, query, args) if result < 0: dbError(db) -proc execAffectedRows*(db: DbConn, query: SqlQuery, +proc execAffectedRows*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]): int64 {. - tags: [FReadDB, FWriteDb].} = + tags: [FReadDB, FWriteDb].} = ## runs the query (typically "UPDATE") and returns the ## number of affected rows rawExec(db, query, args) result = mysql.affectedRows(db) -proc close*(db: DbConn) {.tags: [FDb].} = +proc close*(db: DbConn) {.tags: [FDb].} = ## closes the database connection. if db != nil: mysql.close(db) @@ -242,14 +242,14 @@ proc open*(connection, user, password, database: string): DbConn {. ## opens a database connection. Raises `EDb` if the connection could not ## be established. result = mysql.init(nil) - if result == nil: dbError("could not open database connection") + if result == nil: dbError("could not open database connection") let colonPos = connection.find(':') host = if colonPos < 0: connection else: substr(connection, 0, colonPos-1) port: int32 = if colonPos < 0: 0'i32 else: substr(connection, colonPos+1).parseInt.int32 - if mysql.realConnect(result, host, user, password, database, + if mysql.realConnect(result, host, user, password, database, port, nil, 0) == nil: var errmsg = $mysql.error(result) db_mysql.close(result) @@ -257,6 +257,6 @@ proc open*(connection, user, password, database: string): DbConn {. proc setEncoding*(connection: DbConn, encoding: string): bool {. tags: [FDb].} = - ## sets the encoding of a database connection, returns true for + ## sets the encoding of a database connection, returns true for ## success, false for failure. result = mysql.set_character_set(connection, encoding) == 0 diff --git a/lib/impure/db_postgres.nim b/lib/impure/db_postgres.nim index c88e660f4..b75915a72 100644 --- a/lib/impure/db_postgres.nim +++ b/lib/impure/db_postgres.nim @@ -7,7 +7,7 @@ # distribution, for details about the copyright. # -## A higher level `PostgreSQL`:idx: database wrapper. This interface +## A higher level `PostgreSQL`:idx: database wrapper. This interface ## is implemented for other databases too. import strutils, postgres @@ -20,7 +20,7 @@ type ## used to get a row's ## column text on demand EDb* = object of IOError ## exception that is raised if a database error occurs - + SqlQuery* = distinct string ## an SQL query string SqlPrepared* = distinct string ## a identifier for the prepared queries @@ -30,15 +30,15 @@ type {.deprecated: [TRow: Row, TSqlQuery: SqlQuery, TDbConn: DbConn, TSqlPrepared: SqlPrepared].} -proc sql*(query: string): SqlQuery {.noSideEffect, inline.} = - ## constructs a SqlQuery from the string `query`. This is supposed to be +proc sql*(query: string): SqlQuery {.noSideEffect, inline.} = + ## constructs a SqlQuery from the string `query`. This is supposed to be ## used as a raw-string-literal modifier: ## ``sql"update user set counter = counter + 1"`` ## - ## If assertions are turned off, it does nothing. If assertions are turned + ## If assertions are turned off, it does nothing. If assertions are turned ## on, later versions will check the string for valid syntax. result = SqlQuery(query) - + proc dbError*(db: DbConn) {.noreturn.} = ## raises an EDb exception. var e: ref EDb @@ -73,7 +73,7 @@ proc dbFormat(formatstr: SqlQuery, args: varargs[string]): string = inc(a) else: add(result, c) - + proc tryExec*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]): bool {.tags: [FReadDB, FWriteDb].} = ## tries to execute the query and returns true if successful, false otherwise. @@ -106,7 +106,7 @@ proc exec*(db: DbConn, stmtName: SqlPrepared, proc newRow(L: int): Row = newSeq(result, L) for i in 0..L-1: result[i] = "" - + proc setupQuery(db: DbConn, query: SqlQuery, args: varargs[string]): PPGresult = var arr = allocCStringArray(args) @@ -128,7 +128,7 @@ proc prepare*(db: DbConn; stmtName: string, query: SqlQuery; var res = pqprepare(db, stmtName, query.string, int32(nParams), nil) if pqResultStatus(res) != PGRES_COMMAND_OK: dbError(db) return SqlPrepared(stmtName) - + proc setRow(res: PPGresult, r: var Row, line, cols: int32) = for col in 0..cols-1: setLen(r[col], 0) @@ -140,7 +140,7 @@ proc setRow(res: PPGresult, r: var Row, line, cols: int32) = iterator fastRows*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]): Row {.tags: [FReadDB].} = - ## executes the query and iterates over the result dataset. This is very + ## executes the query and iterates over the result dataset. This is very ## fast, but potenially dangerous: If the for-loop-body executes another ## query, the results can be undefined. For Postgres it is safe though. var res = setupQuery(db, query, args) @@ -224,14 +224,14 @@ proc getValue*(db: DbConn, query: SqlQuery, ## value is NULL. var x = pqgetvalue(setupQuery(db, query, args), 0, 0) result = if isNil(x): "" else: $x - + proc tryInsertID*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]): int64 {.tags: [FWriteDb].}= - ## executes the query (typically "INSERT") and returns the + ## executes the query (typically "INSERT") and returns the ## generated ID for the row or -1 in case of an error. For Postgre this adds ## ``RETURNING id`` to the query, so it only works if your primary key is - ## named ``id``. - var x = pqgetvalue(setupQuery(db, SqlQuery(string(query) & " RETURNING id"), + ## named ``id``. + var x = pqgetvalue(setupQuery(db, SqlQuery(string(query) & " RETURNING id"), args), 0, 0) if not isNil(x): result = parseBiggestInt($x) @@ -240,13 +240,13 @@ proc tryInsertID*(db: DbConn, query: SqlQuery, proc insertID*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]): int64 {.tags: [FWriteDb].} = - ## executes the query (typically "INSERT") and returns the + ## executes the query (typically "INSERT") and returns the ## generated ID for the row. For Postgre this adds ## ``RETURNING id`` to the query, so it only works if your primary key is - ## named ``id``. + ## named ``id``. result = tryInsertID(db, query, args) if result < 0: dbError(db) - + proc execAffectedRows*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]): int64 {.tags: [ FReadDB, FWriteDb].} = @@ -286,6 +286,6 @@ proc open*(connection, user, password, database: string): DbConn {. proc setEncoding*(connection: DbConn, encoding: string): bool {. tags: [FDb].} = - ## sets the encoding of a database connection, returns true for + ## sets the encoding of a database connection, returns true for ## success, false for failure. return pqsetClientEncoding(connection, encoding) == 0 diff --git a/lib/impure/db_sqlite.nim b/lib/impure/db_sqlite.nim index 1a037becc..66276e9a4 100644 --- a/lib/impure/db_sqlite.nim +++ b/lib/impure/db_sqlite.nim @@ -7,7 +7,7 @@ # distribution, for details about the copyright. # -## A higher level `SQLite`:idx: database wrapper. This interface +## A higher level `SQLite`:idx: database wrapper. This interface ## is implemented for other databases too. import strutils, sqlite3 @@ -19,31 +19,31 @@ type InstantRow* = Pstmt ## a handle that can be used to get a row's column ## text on demand EDb* = object of IOError ## exception that is raised if a database error occurs - + SqlQuery* = distinct string ## an SQL query string - + FDb* = object of IOEffect ## effect that denotes a database operation FReadDb* = object of FDb ## effect that denotes a read operation FWriteDb* = object of FDb ## effect that denotes a write operation {.deprecated: [TRow: Row, TSqlQuery: SqlQuery, TDbConn: DbConn].} - -proc sql*(query: string): SqlQuery {.noSideEffect, inline.} = - ## constructs a SqlQuery from the string `query`. This is supposed to be + +proc sql*(query: string): SqlQuery {.noSideEffect, inline.} = + ## constructs a SqlQuery from the string `query`. This is supposed to be ## used as a raw-string-literal modifier: ## ``sql"update user set counter = counter + 1"`` ## - ## If assertions are turned off, it does nothing. If assertions are turned + ## If assertions are turned off, it does nothing. If assertions are turned ## on, later versions will check the string for valid syntax. result = SqlQuery(query) - -proc dbError(db: DbConn) {.noreturn.} = + +proc dbError(db: DbConn) {.noreturn.} = ## raises an EDb exception. var e: ref EDb new(e) e.msg = $sqlite3.errmsg(db) raise e -proc dbError*(msg: string) {.noreturn.} = +proc dbError*(msg: string) {.noreturn.} = ## raises an EDb exception with message `msg`. var e: ref EDb new(e) @@ -67,8 +67,8 @@ proc dbFormat(formatstr: SqlQuery, args: varargs[string]): string = inc(a) else: add(result, c) - -proc tryExec*(db: DbConn, query: SqlQuery, + +proc tryExec*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]): bool {.tags: [FReadDb, FWriteDb].} = ## tries to execute the query and returns true if successful, false otherwise. var q = dbFormat(query, args) @@ -81,32 +81,32 @@ proc exec*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]) {. tags: [FReadDb, FWriteDb].} = ## executes the query and raises EDB if not successful. if not tryExec(db, query, args): dbError(db) - + proc newRow(L: int): Row = newSeq(result, L) for i in 0..L-1: result[i] = "" - -proc setupQuery(db: DbConn, query: SqlQuery, - args: varargs[string]): Pstmt = + +proc setupQuery(db: DbConn, query: SqlQuery, + args: varargs[string]): Pstmt = var q = dbFormat(query, args) if prepare_v2(db, q, q.len.cint, result, nil) != SQLITE_OK: dbError(db) - + proc setRow(stmt: Pstmt, r: var Row, cols: cint) = for col in 0..cols-1: setLen(r[col], column_bytes(stmt, col)) # set capacity setLen(r[col], 0) let x = column_text(stmt, col) if not isNil(x): add(r[col], x) - + iterator fastRows*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]): Row {.tags: [FReadDb].} = - ## executes the query and iterates over the result dataset. This is very + ## executes the query and iterates over the result dataset. This is very ## fast, but potenially dangerous: If the for-loop-body executes another ## query, the results can be undefined. For Sqlite it is safe though. var stmt = setupQuery(db, query, args) var L = (column_count(stmt)) var result = newRow(L) - while step(stmt) == SQLITE_ROW: + while step(stmt) == SQLITE_ROW: setRow(stmt, result, L) yield result if finalize(stmt) != SQLITE_OK: dbError(db) @@ -136,31 +136,31 @@ proc getRow*(db: DbConn, query: SqlQuery, var stmt = setupQuery(db, query, args) var L = (column_count(stmt)) result = newRow(L) - if step(stmt) == SQLITE_ROW: + if step(stmt) == SQLITE_ROW: setRow(stmt, result, L) if finalize(stmt) != SQLITE_OK: dbError(db) -proc getAllRows*(db: DbConn, query: SqlQuery, +proc getAllRows*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]): seq[Row] {.tags: [FReadDb].} = ## executes the query and returns the whole result dataset. result = @[] for r in fastRows(db, query, args): result.add(r) -iterator rows*(db: DbConn, query: SqlQuery, +iterator rows*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]): Row {.tags: [FReadDb].} = ## same as `FastRows`, but slower and safe. for r in fastRows(db, query, args): yield r -proc getValue*(db: DbConn, query: SqlQuery, - args: varargs[string, `$`]): string {.tags: [FReadDb].} = +proc getValue*(db: DbConn, query: SqlQuery, + args: varargs[string, `$`]): string {.tags: [FReadDb].} = ## executes the query and returns the first column of the first row of the ## result dataset. Returns "" if the dataset contains no rows or the database ## value is NULL. var stmt = setupQuery(db, query, args) if step(stmt) == SQLITE_ROW: let cb = column_bytes(stmt, 0) - if cb == 0: + if cb == 0: result = "" else: result = newStringOfCap(cb) @@ -168,12 +168,12 @@ proc getValue*(db: DbConn, query: SqlQuery, else: result = "" if finalize(stmt) != SQLITE_OK: dbError(db) - -proc tryInsertID*(db: DbConn, query: SqlQuery, + +proc tryInsertID*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]): int64 {.tags: [FWriteDb], raises: [].} = - ## executes the query (typically "INSERT") and returns the - ## generated ID for the row or -1 in case of an error. + ## executes the query (typically "INSERT") and returns the + ## generated ID for the row or -1 in case of an error. var q = dbFormat(query, args) var stmt: sqlite3.Pstmt result = -1 @@ -183,27 +183,27 @@ proc tryInsertID*(db: DbConn, query: SqlQuery, if finalize(stmt) != SQLITE_OK: result = -1 -proc insertID*(db: DbConn, query: SqlQuery, - args: varargs[string, `$`]): int64 {.tags: [FWriteDb].} = - ## executes the query (typically "INSERT") and returns the +proc insertID*(db: DbConn, query: SqlQuery, + args: varargs[string, `$`]): int64 {.tags: [FWriteDb].} = + ## executes the query (typically "INSERT") and returns the ## generated ID for the row. For Postgre this adds ## ``RETURNING id`` to the query, so it only works if your primary key is - ## named ``id``. + ## named ``id``. result = tryInsertID(db, query, args) if result < 0: dbError(db) - -proc execAffectedRows*(db: DbConn, query: SqlQuery, + +proc execAffectedRows*(db: DbConn, query: SqlQuery, args: varargs[string, `$`]): int64 {. - tags: [FReadDb, FWriteDb].} = + tags: [FReadDb, FWriteDb].} = ## executes the query (typically "UPDATE") and returns the ## number of affected rows. exec(db, query, args) result = changes(db) -proc close*(db: DbConn) {.tags: [FDb].} = +proc close*(db: DbConn) {.tags: [FDb].} = ## closes the database connection. if sqlite3.close(db) != SQLITE_OK: dbError(db) - + proc open*(connection, user, password, database: string): DbConn {. tags: [FDb].} = ## opens a database connection. Raises `EDb` if the connection could not @@ -216,12 +216,12 @@ proc open*(connection, user, password, database: string): DbConn {. proc setEncoding*(connection: DbConn, encoding: string): bool {. tags: [FDb].} = - ## sets the encoding of a database connection, returns true for + ## sets the encoding of a database connection, returns true for ## success, false for failure. ## ## Note that the encoding cannot be changed once it's been set. - ## According to SQLite3 documentation, any attempt to change - ## the encoding after the database is created will be silently + ## According to SQLite3 documentation, any attempt to change + ## the encoding after the database is created will be silently ## ignored. exec(connection, sql"PRAGMA encoding = ?", [encoding]) result = connection.getValue(sql"PRAGMA encoding") == encoding diff --git a/lib/impure/graphics.nim b/lib/impure/graphics.nim index 1b3d1d5b6..8bd769fd8 100644 --- a/lib/impure/graphics.nim +++ b/lib/impure/graphics.nim @@ -9,7 +9,7 @@ ## This module implements graphical output for Nim; the current ## implementation uses SDL but the interface is meant to support multiple -## backends some day. There is no need to init SDL as this module does that +## backends some day. There is no need to init SDL as this module does that ## implicitly. import colors, math @@ -24,7 +24,7 @@ type Surface* {.pure, final.} = object w*, h*: Natural s*: sdl.PSurface - + EGraphics* = object of IOError Font {.pure, final.} = object @@ -35,7 +35,7 @@ type proc toSdlColor*(c: Color): sdl.Color = ## Convert colors.Color to sdl.Color - var x = c.extractRGB + var x = c.extractRGB result.r = x.r and 0xff result.g = x.g and 0xff result.b = x.b and 0xff @@ -43,7 +43,7 @@ proc toSdlColor*(c: Color): sdl.Color = proc createSdlColor*(sur: PSurface, c: Color, alpha: int = 0): int32 = ## Creates a color using ``sdl.MapRGBA``. var x = c.extractRGB - return sdl.mapRGBA(sur.s.format, x.r and 0xff, x.g and 0xff, + return sdl.mapRGBA(sur.s.format, x.r and 0xff, x.g and 0xff, x.b and 0xff, alpha and 0xff) proc toSdlRect*(r: Rect): sdl.Rect = @@ -53,26 +53,26 @@ proc toSdlRect*(r: Rect): sdl.Rect = result.w = uint16(r.width) result.h = uint16(r.height) -proc raiseEGraphics = +proc raiseEGraphics = raise newException(EGraphics, $sdl.getError()) - + proc surfaceFinalizer(s: PSurface) = sdl.freeSurface(s.s) - + proc newSurface*(width, height: int): PSurface = ## creates a new surface. new(result, surfaceFinalizer) result.w = width result.h = height - result.s = sdl.createRGBSurface(sdl.SWSURFACE, width, height, + result.s = sdl.createRGBSurface(sdl.SWSURFACE, width, height, 32, 0x00FF0000, 0x0000FF00, 0x000000FF, 0) if result.s == nil: raiseEGraphics() - + assert(not sdl.mustLock(result.s)) proc fontFinalizer(f: PFont) = closeFont(f.f) -proc newFont*(name = "VeraMono.ttf", size = 9, color = colBlack): PFont = +proc newFont*(name = "VeraMono.ttf", size = 9, color = colBlack): PFont = ## Creates a new font object. Raises ``EIO`` if the font cannot be loaded. new(result, fontFinalizer) result.f = openFont(name, size.cint) @@ -84,7 +84,7 @@ var defaultFont*: PFont ## default font that is used; this needs to initialized ## by the client! -proc initDefaultFont*(name = "VeraMono.ttf", size = 9, color = colBlack) = +proc initDefaultFont*(name = "VeraMono.ttf", size = 9, color = colBlack) = ## initializes the `defaultFont` var. defaultFont = newFont(name, size, color) @@ -98,7 +98,7 @@ proc newScreenSurface*(width, height: int): PSurface = raiseEGraphics() proc writeToBMP*(sur: PSurface, filename: string) = - ## Saves the contents of the surface `sur` to the file `filename` as a + ## Saves the contents of the surface `sur` to the file `filename` as a ## BMP file. if sdl.saveBMP(sur.s, filename) != 0: raise newException(IOError, "cannot write: " & filename) @@ -111,7 +111,7 @@ type template setPix(video, pitch, x, y, col: expr): stmt = video[y * pitch + x] = int32(col) -template getPix(video, pitch, x, y: expr): expr = +template getPix(video, pitch, x, y: expr): expr = colors.Color(video[y * pitch + x]) const @@ -120,7 +120,7 @@ const proc getPixel(sur: PSurface, x, y: Natural): colors.Color {.inline.} = assert x <% sur.w assert y <% sur.h - result = getPix(cast[PPixels](sur.s.pixels), sur.s.pitch.int div ColSize, + result = getPix(cast[PPixels](sur.s.pixels), sur.s.pitch.int div ColSize, x, y) proc setPixel(sur: PSurface, x, y: Natural, col: colors.Color) {.inline.} = @@ -146,7 +146,7 @@ proc `[]=`*(sur: PSurface, x, y: int, col: Color) = ## set the pixel at position ``(x, y)``. No range checking is done! setPixel(sur, x, y, col) -proc blit*(destSurf: PSurface, destRect: Rect, srcSurf: PSurface, +proc blit*(destSurf: PSurface, destRect: Rect, srcSurf: PSurface, srcRect: Rect) = ## Copies ``srcSurf`` into ``destSurf`` var destTRect, srcTRect: sdl.Rect @@ -175,7 +175,7 @@ proc drawText*(sur: PSurface, p: Point, text: string, font = defaultFont) = ## font. var textSur: PSurface # This surface will have the text drawn on it new(textSur, surfaceFinalizer) - + # Render the text textSur.s = sdl_ttf.renderTextBlended(font.f, text, font.color) # Merge the text surface with sur @@ -183,14 +183,14 @@ proc drawText*(sur: PSurface, p: Point, text: string, font = defaultFont) = proc drawText*(sur: PSurface, p: Point, text: string, bg: Color, font = defaultFont) = - ## Draws text, at location ``p`` with font ``font``. ``bg`` + ## Draws text, at location ``p`` with font ``font``. ``bg`` ## is the background color. var textSur: PSurface # This surface will have the text drawn on it new(textSur, surfaceFinalizer) textSur.s = sdl_ttf.renderTextShaded(font.f, text, font.color, toSdlColor(bg)) # Merge the text surface with sur sur.blit((p.x, p.y, sur.w, sur.h), textSur, (0, 0, sur.w, sur.h)) - + proc drawCircle*(sur: PSurface, p: Point, r: Natural, color: Color) = ## draws a circle with center `p` and radius `r` with the given color ## onto the surface `sur`. @@ -205,7 +205,7 @@ proc drawCircle*(sur: PSurface, p: Point, r: Natural, color: Color) = if x+px <% sur.w: if y+py <% sur.h: setPix(video, pitch, x+px, y+py, color) if y-py <% sur.h: setPix(video, pitch, x+px, y-py, color) - + if x-px <% sur.w: if y+py <% sur.h: setPix(video, pitch, x-px, y+py, color) if y-py <% sur.h: setPix(video, pitch, x-px, y-py, color) @@ -213,7 +213,7 @@ proc drawCircle*(sur: PSurface, p: Point, r: Natural, color: Color) = if x+py <% sur.w: if y+px <% sur.h: setPix(video, pitch, x+py, y+px, color) if y-px <% sur.h: setPix(video, pitch, x+py, y-px, color) - + if x-py <% sur.w: if y+px <% sur.h: setPix(video, pitch, x-py, y+px, color) if y-px <% sur.h: setPix(video, pitch, x-py, y-px, color) @@ -225,10 +225,10 @@ proc drawCircle*(sur: PSurface, p: Point, r: Natural, color: Color) = py = py - 1 px = px + 1 -proc `>-<`(val: int, s: PSurface): int {.inline.} = +proc `>-<`(val: int, s: PSurface): int {.inline.} = return if val < 0: 0 elif val >= s.w: s.w-1 else: val -proc `>|<`(val: int, s: PSurface): int {.inline.} = +proc `>|<`(val: int, s: PSurface): int {.inline.} = return if val < 0: 0 elif val >= s.h: s.h-1 else: val proc drawLine*(sur: PSurface, p1, p2: Point, color: Color) = @@ -242,7 +242,7 @@ proc drawLine*(sur: PSurface, p1, p2: Point, color: Color) = var dy = y1 - y0 var dx = x1 - x0 if dy < 0: - dy = -dy + dy = -dy stepy = -1 else: stepy = 1 @@ -251,7 +251,7 @@ proc drawLine*(sur: PSurface, p1, p2: Point, color: Color) = stepx = -1 else: stepx = 1 - dy = dy * 2 + dy = dy * 2 dx = dx * 2 var video = cast[PPixels](sur.s.pixels) var pitch = sur.s.pitch.int div ColSize @@ -328,17 +328,17 @@ proc drawRect*(sur: PSurface, r: Rect, color: Color) = if (r.x >= 0 and r.x <= sur.s.w) and (r.y >= 0 and r.y <= sur.s.h): var minW = min(sur.s.w - r.x, r.width) var minH = min(sur.s.h - r.y, r.height) - + # Draw Top for i in 0 .. minW - 1: setPix(video, pitch, r.x + i, r.y, color) setPix(video, pitch, r.x + i, r.y + minH - 1, color) # Draw bottom - + # Draw left side for i in 0 .. minH - 1: setPix(video, pitch, r.x, r.y + i, color) setPix(video, pitch, r.x + minW - 1, r.y + i, color) # Draw right side - + proc fillRect*(sur: PSurface, r: Rect, col: Color) = ## Fills a rectangle using sdl's ``FillRect`` function. var rect = toSdlRect(r) @@ -350,23 +350,23 @@ proc plot4EllipsePoints(sur: PSurface, cx, cy, x, y: Natural, col: Color) = var pitch = sur.s.pitch.int div ColSize if cx+x <= sur.s.w-1: if cy+y <= sur.s.h-1: setPix(video, pitch, cx+x, cy+y, col) - if cy-y <= sur.s.h-1: setPix(video, pitch, cx+x, cy-y, col) + if cy-y <= sur.s.h-1: setPix(video, pitch, cx+x, cy-y, col) if cx-x <= sur.s.w-1: if cy+y <= sur.s.h-1: setPix(video, pitch, cx-x, cy+y, col) if cy-y <= sur.s.h-1: setPix(video, pitch, cx-x, cy-y, col) -proc drawEllipse*(sur: PSurface, cx, cy, xRadius, yRadius: Natural, +proc drawEllipse*(sur: PSurface, cx, cy, xRadius, yRadius: Natural, col: Color) = - ## Draws an ellipse, ``CX`` and ``CY`` specify the center X and Y of the + ## Draws an ellipse, ``CX`` and ``CY`` specify the center X and Y of the ## ellipse, ``XRadius`` and ``YRadius`` specify half the width and height ## of the ellipse. - var + var x, y: Natural xChange, yChange: int ellipseError: Natural twoASquare, twoBSquare: Natural stoppingX, stoppingY: Natural - + twoASquare = 2 * xRadius * xRadius twoBSquare = 2 * yRadius * yRadius x = xRadius @@ -376,7 +376,7 @@ proc drawEllipse*(sur: PSurface, cx, cy, xRadius, yRadius: Natural, ellipseError = 0 stoppingX = twoBSquare * xRadius stoppingY = 0 - + while stoppingX >= stoppingY: # 1st set of points, y` > - 1 sur.plot4EllipsePoints(cx, cy, x, y, col) inc(y) @@ -388,7 +388,7 @@ proc drawEllipse*(sur: PSurface, cx, cy, xRadius, yRadius: Natural, dec(stoppingX, twoBSquare) inc(ellipseError, xChange) inc(xChange, twoBSquare) - + # 1st point set is done; start the 2nd set of points x = 0 y = yRadius @@ -408,7 +408,7 @@ proc drawEllipse*(sur: PSurface, cx, cy, xRadius, yRadius: Natural, dec(stoppingY, twoASquare) inc(ellipseError, yChange) inc(yChange,twoASquare) - + proc plotAA(sur: PSurface, x, y: int, c: float, color: Color) = if (x > 0 and x < sur.s.w) and (y > 0 and y < sur.s.h): @@ -419,43 +419,43 @@ proc plotAA(sur: PSurface, x, y: int, c: float, color: Color) = setPix(video, pitch, x, y, pixColor.intensity(1.0 - c) + color.intensity(c)) - -template ipart(x: expr): expr = floor(x) + +template ipart(x: expr): expr = floor(x) template cround(x: expr): expr = ipart(x + 0.5) template fpart(x: expr): expr = x - ipart(x) template rfpart(x: expr): expr = 1.0 - fpart(x) proc drawLineAA*(sur: PSurface, p1, p2: Point, color: Color) = - ## Draws a anti-aliased line from ``p1`` to ``p2``, using Xiaolin Wu's + ## Draws a anti-aliased line from ``p1`` to ``p2``, using Xiaolin Wu's ## line algorithm - var (x1, x2, y1, y2) = (p1.x.toFloat(), p2.x.toFloat(), + var (x1, x2, y1, y2) = (p1.x.toFloat(), p2.x.toFloat(), p1.y.toFloat(), p2.y.toFloat()) var dx = x2 - x1 var dy = y2 - y1 - + var ax = dx if ax < 0'f64: ax = 0'f64 - ax var ay = dy if ay < 0'f64: ay = 0'f64 - ay - + if ax < ay: swap(x1, y1) swap(x2, y2) swap(dx, dy) - + template doPlot(x, y: int, c: float, color: Color): stmt = if ax < ay: sur.plotAA(y, x, c, color) else: sur.plotAA(x, y, c, color) - + if x2 < x1: swap(x1, x2) swap(y1, y2) - + var gradient = dy / dx # handle first endpoint var xend = cround(x1) @@ -509,19 +509,19 @@ when not defined(testing) and isMainModule: # Draw the shapes surf.drawLineAA((150, 170), (400, 471), colTan) surf.drawLine((100, 170), (400, 471), colRed) - + surf.drawEllipse(200, 300, 200, 30, colSeaGreen) - surf.drawHorLine(1, 300, 400, colViolet) + surf.drawHorLine(1, 300, 400, colViolet) # Check if the ellipse is the size it's suppose to be. surf.drawVerLine(200, 300 - 30 + 1, 60, colViolet) # ^^ | i suppose it is - + surf.drawEllipse(400, 300, 300, 300, colOrange) surf.drawEllipse(5, 5, 5, 5, colGreen) - + surf.drawHorLine(5, 5, 900, colRed) surf.drawVerLine(5, 60, 800, colRed) surf.drawCircle((600, 500), 60, colRed) - + surf.fillRect((50, 50, 100, 100), colFuchsia) surf.fillRect((150, 50, 100, 100), colGreen) surf.drawRect((50, 150, 100, 100), colGreen) @@ -530,12 +530,12 @@ when not defined(testing) and isMainModule: surf.drawHorLine(250, 150, 100, colRed) surf.drawLineAA((592, 160), (592, 280), colPurple) - + #surf.drawText((300, 300), "TEST", colMidnightBlue) #var textSize = textBounds("TEST") #surf.drawText((300, 300 + textSize.height), $textSize.width & ", " & # $textSize.height, colDarkGreen) - + var mouseStartX = -1 var mouseStartY = -1 withEvents(surf, event): @@ -561,17 +561,17 @@ when not defined(testing) and isMainModule: surf.drawLineAA((mouseStartX, mouseStartY), (int(mbd.x), int(mbd.y)), colPurple) mouseStartX = -1 mouseStartY = -1 - + of sdl.MOUSEMOTION: var mm = sdl.evMouseMotion(eventp) if mouseStartX != -1 and mouseStartY != -1: surf.drawLineAA((mouseStartX, mouseStartY), (int(mm.x), int(mm.y)), colPurple) #echo(mm.x, " ", mm.y, " ", mm.yrel) - + else: discard "echo(event.kind)" - + sdl.updateRect(surf.s, 0, 0, 800, 600) - + surf.writeToBMP("test.bmp") sdl.quit() diff --git a/lib/impure/re.nim b/lib/impure/re.nim index 0df8d4a9c..30081bb19 100644 --- a/lib/impure/re.nim +++ b/lib/impure/re.nim @@ -41,11 +41,11 @@ type reExtended = 3, ## ignore whitespace and ``#`` comments reStudy = 4 ## study the expression (may be omitted if the ## expression will be used only once) - - RegexDesc = object + + RegexDesc = object h: ptr Pcre e: ptr ExtraData - + Regex* {.deprecated.} = ref RegexDesc ## a compiled regular expression RegexError* = object of ValueError diff --git a/lib/impure/ssl.nim b/lib/impure/ssl.nim index 079a2c3a2..721e5ce51 100644 --- a/lib/impure/ssl.nim +++ b/lib/impure/ssl.nim @@ -7,7 +7,7 @@ # distribution, for details about the copyright. # -## This module provides an easy to use sockets-style +## This module provides an easy to use sockets-style ## nim interface to the OpenSSL library. {.deprecated.} @@ -20,37 +20,37 @@ type bio: BIO {.deprecated: [TSecureSocket: SecureSocket].} -proc connect*(sock: var SecureSocket, address: string, +proc connect*(sock: var SecureSocket, address: string, port: int): int = ## Connects to the specified `address` on the specified `port`. ## Returns the result of the certificate validation. SslLoadErrorStrings() ERR_load_BIO_strings() - + if SSL_library_init() != 1: raiseOSError(osLastError()) - + var ctx = SSL_CTX_new(SSLv23_client_method()) if ctx == nil: ERR_print_errors_fp(stderr) raiseOSError(osLastError()) - - #if SSL_CTX_load_verify_locations(ctx, + + #if SSL_CTX_load_verify_locations(ctx, # "/tmp/openssl-0.9.8e/certs/vsign1.pem", NIL) == 0: # echo("Failed load verify locations") # ERR_print_errors_fp(stderr) - + sock.bio = BIO_new_ssl_connect(ctx) if BIO_get_ssl(sock.bio, addr(sock.ssl)) == 0: raiseOSError(osLastError()) if BIO_set_conn_hostname(sock.bio, address & ":" & $port) != 1: raiseOSError(osLastError()) - + if BIO_do_connect(sock.bio) <= 0: ERR_print_errors_fp(stderr) raiseOSError(osLastError()) - + result = SSL_get_verify_result(sock.ssl) proc recvLine*(sock: SecureSocket, line: var TaintedString): bool = @@ -86,12 +86,12 @@ proc close*(sock: SecureSocket) = when not defined(testing) and isMainModule: var s: SecureSocket echo connect(s, "smtp.gmail.com", 465) - + #var buffer: array[0..255, char] #echo BIO_read(bio, buffer, buffer.len) var buffer: string = "" - + echo s.recvLine(buffer) - echo buffer + echo buffer echo buffer.len - + diff --git a/lib/nimrtl.nim b/lib/nimrtl.nim index 96dab1284..4e4cf7e0e 100644 --- a/lib/nimrtl.nim +++ b/lib/nimrtl.nim @@ -7,8 +7,8 @@ # distribution, for details about the copyright. # -## Main file to generate a DLL from the standard library. -## The default Nimrtl does not only contain the ``system`` module, but these +## Main file to generate a DLL from the standard library. +## The default Nimrtl does not only contain the ``system`` module, but these ## too: ## ## * parseutils @@ -22,12 +22,12 @@ ## * unicode ## * pegs ## * ropes -## +## when system.appType != "lib": {.error: "This file has to be compiled as a library!".} -when not defined(createNimRtl): +when not defined(createNimRtl): {.error: "This file has to be compiled with '-d:createNimRtl'".} import diff --git a/lib/posix/epoll.nim b/lib/posix/epoll.nim index bc84611a6..276dd812d 100644 --- a/lib/posix/epoll.nim +++ b/lib/posix/epoll.nim @@ -29,34 +29,34 @@ const # Valid opcodes ( "op" parameter ) to issue to epoll_ctl(). -const - EPOLL_CTL_ADD* = 1 # Add a file descriptor to the interface. - EPOLL_CTL_DEL* = 2 # Remove a file descriptor from the interface. - EPOLL_CTL_MOD* = 3 # Change file descriptor epoll_event structure. +const + EPOLL_CTL_ADD* = 1 # Add a file descriptor to the interface. + EPOLL_CTL_DEL* = 2 # Remove a file descriptor from the interface. + EPOLL_CTL_MOD* = 3 # Change file descriptor epoll_event structure. -type - epoll_data* {.importc: "union epoll_data", +type + epoll_data* {.importc: "union epoll_data", header: "", pure, final.} = object # TODO: This is actually a union. #thePtr* {.importc: "ptr".}: pointer fd* {.importc: "fd".}: cint # \ #u32*: uint32 #u64*: uint64 - epoll_event* {.importc: "struct epoll_event", header: "", pure, final.} = object - events*: uint32 # Epoll events - data*: epoll_data # User data variable + epoll_event* {.importc: "struct epoll_event", header: "", pure, final.} = object + events*: uint32 # Epoll events + data*: epoll_data # User data variable -proc epoll_create*(size: cint): cint {.importc: "epoll_create", +proc epoll_create*(size: cint): cint {.importc: "epoll_create", header: "".} ## Creates an epoll instance. Returns an fd for the new instance. ## The "size" parameter is a hint specifying the number of file ## descriptors to be associated with the new instance. The fd - ## returned by epoll_create() should be closed with close(). + ## returned by epoll_create() should be closed with close(). -proc epoll_create1*(flags: cint): cint {.importc: "epoll_create1", +proc epoll_create1*(flags: cint): cint {.importc: "epoll_create1", header: "".} ## Same as epoll_create but with an FLAGS parameter. The unused SIZE - ## parameter has been dropped. + ## parameter has been dropped. proc epoll_ctl*(epfd: cint; op: cint; fd: cint | SocketHandle; event: ptr epoll_event): cint {. importc: "epoll_ctl", header: "".} @@ -65,10 +65,10 @@ proc epoll_ctl*(epfd: cint; op: cint; fd: cint | SocketHandle; event: ptr epoll_ ## specific error code ) The "op" parameter is one of the EPOLL_CTL_* ## constants defined above. The "fd" parameter is the target of the ## operation. The "event" parameter describes which events the caller - ## is interested in and any associated user data. + ## is interested in and any associated user data. -proc epoll_wait*(epfd: cint; events: ptr epoll_event; maxevents: cint; - timeout: cint): cint {.importc: "epoll_wait", +proc epoll_wait*(epfd: cint; events: ptr epoll_event; maxevents: cint; + timeout: cint): cint {.importc: "epoll_wait", header: "".} ## Wait for events on an epoll instance "epfd". Returns the number of ## triggered events returned in "events" buffer. Or -1 in case of @@ -82,11 +82,11 @@ proc epoll_wait*(epfd: cint; events: ptr epoll_event; maxevents: cint; ## __THROW. -#proc epoll_pwait*(epfd: cint; events: ptr epoll_event; maxevents: cint; +#proc epoll_pwait*(epfd: cint; events: ptr epoll_event; maxevents: cint; # timeout: cint; ss: ptr sigset_t): cint {. # importc: "epoll_pwait", header: "".} # Same as epoll_wait, but the thread's signal mask is temporarily # and atomically replaced with the one provided as parameter. # # This function is a cancellation point and therefore not marked with -# __THROW. +# __THROW. diff --git a/lib/posix/inotify.nim b/lib/posix/inotify.nim index 14cac4d72..a206f8067 100644 --- a/lib/posix/inotify.nim +++ b/lib/posix/inotify.nim @@ -9,65 +9,65 @@ {.deadCodeElim:on.} -# Get the platform-dependent flags. -# Structure describing an inotify event. -type - InotifyEvent*{.pure, final, importc: "struct inotify_event", - header: "".} = object - wd*{.importc: "wd".}: cint # Watch descriptor. - mask*{.importc: "mask".}: uint32 # Watch mask. - cookie*{.importc: "cookie".}: uint32 # Cookie to synchronize two events. - len*{.importc: "len".}: uint32 # Length (including NULs) of name. - name*{.importc: "name".}: char # Name. +# Get the platform-dependent flags. +# Structure describing an inotify event. +type + InotifyEvent*{.pure, final, importc: "struct inotify_event", + header: "".} = object + wd*{.importc: "wd".}: cint # Watch descriptor. + mask*{.importc: "mask".}: uint32 # Watch mask. + cookie*{.importc: "cookie".}: uint32 # Cookie to synchronize two events. + len*{.importc: "len".}: uint32 # Length (including NULs) of name. + name*{.importc: "name".}: char # Name. {.deprecated: [Tinotify_event: InotifyEvent].} -# Supported events suitable for MASK parameter of INOTIFY_ADD_WATCH. -const - IN_ACCESS* = 0x00000001 # File was accessed. - IN_MODIFY* = 0x00000002 # File was modified. - IN_ATTRIB* = 0x00000004 # Metadata changed. - IN_CLOSE_WRITE* = 0x00000008 # Writtable file was closed. - IN_CLOSE_NOWRITE* = 0x00000010 # Unwrittable file closed. - IN_CLOSE* = (IN_CLOSE_WRITE or IN_CLOSE_NOWRITE) # Close. - IN_OPEN* = 0x00000020 # File was opened. - IN_MOVED_FROM* = 0x00000040 # File was moved from X. - IN_MOVED_TO* = 0x00000080 # File was moved to Y. - IN_MOVE* = (IN_MOVED_FROM or IN_MOVED_TO) # Moves. - IN_CREATE* = 0x00000100 # Subfile was created. - IN_DELETE* = 0x00000200 # Subfile was deleted. - IN_DELETE_SELF* = 0x00000400 # Self was deleted. - IN_MOVE_SELF* = 0x00000800 # Self was moved. -# Events sent by the kernel. -const - IN_UNMOUNT* = 0x00002000 # Backing fs was unmounted. - IN_Q_OVERFLOW* = 0x00004000 # Event queued overflowed. - IN_IGNORED* = 0x00008000 # File was ignored. -# Special flags. -const +# Supported events suitable for MASK parameter of INOTIFY_ADD_WATCH. +const + IN_ACCESS* = 0x00000001 # File was accessed. + IN_MODIFY* = 0x00000002 # File was modified. + IN_ATTRIB* = 0x00000004 # Metadata changed. + IN_CLOSE_WRITE* = 0x00000008 # Writtable file was closed. + IN_CLOSE_NOWRITE* = 0x00000010 # Unwrittable file closed. + IN_CLOSE* = (IN_CLOSE_WRITE or IN_CLOSE_NOWRITE) # Close. + IN_OPEN* = 0x00000020 # File was opened. + IN_MOVED_FROM* = 0x00000040 # File was moved from X. + IN_MOVED_TO* = 0x00000080 # File was moved to Y. + IN_MOVE* = (IN_MOVED_FROM or IN_MOVED_TO) # Moves. + IN_CREATE* = 0x00000100 # Subfile was created. + IN_DELETE* = 0x00000200 # Subfile was deleted. + IN_DELETE_SELF* = 0x00000400 # Self was deleted. + IN_MOVE_SELF* = 0x00000800 # Self was moved. +# Events sent by the kernel. +const + IN_UNMOUNT* = 0x00002000 # Backing fs was unmounted. + IN_Q_OVERFLOW* = 0x00004000 # Event queued overflowed. + IN_IGNORED* = 0x00008000 # File was ignored. +# Special flags. +const IN_ONLYDIR* = 0x01000000 # Only watch the path if it is a - # directory. - IN_DONT_FOLLOW* = 0x02000000 # Do not follow a sym link. + # directory. + IN_DONT_FOLLOW* = 0x02000000 # Do not follow a sym link. IN_EXCL_UNLINK* = 0x04000000 # Exclude events on unlinked - # objects. + # objects. IN_MASK_ADD* = 0x20000000 # Add to the mask of an already - # existing watch. - IN_ISDIR* = 0x40000000 # Event occurred against dir. - IN_ONESHOT* = 0x80000000 # Only send event once. -# All events which a program can wait on. -const + # existing watch. + IN_ISDIR* = 0x40000000 # Event occurred against dir. + IN_ONESHOT* = 0x80000000 # Only send event once. +# All events which a program can wait on. +const IN_ALL_EVENTS* = (IN_ACCESS or IN_MODIFY or IN_ATTRIB or IN_CLOSE_WRITE or IN_CLOSE_NOWRITE or IN_OPEN or IN_MOVED_FROM or IN_MOVED_TO or IN_CREATE or IN_DELETE or IN_DELETE_SELF or IN_MOVE_SELF) # Create and initialize inotify instance. -proc inotify_init*(): cint{.cdecl, importc: "inotify_init", +proc inotify_init*(): cint{.cdecl, importc: "inotify_init", header: "".} -# Create and initialize inotify instance. -proc inotify_init1*(flags: cint): cint{.cdecl, importc: "inotify_init1", +# Create and initialize inotify instance. +proc inotify_init1*(flags: cint): cint{.cdecl, importc: "inotify_init1", header: "".} # Add watch of object NAME to inotify instance FD. Notify about -# events specified by MASK. +# events specified by MASK. proc inotify_add_watch*(fd: cint; name: cstring; mask: uint32): cint{. cdecl, importc: "inotify_add_watch", header: "".} -# Remove the watch specified by WD from the inotify instance FD. -proc inotify_rm_watch*(fd: cint; wd: cint): cint{.cdecl, +# Remove the watch specified by WD from the inotify instance FD. +proc inotify_rm_watch*(fd: cint; wd: cint): cint{.cdecl, importc: "inotify_rm_watch", header: "".} diff --git a/lib/posix/linux.nim b/lib/posix/linux.nim index 05eab52bc..01d5e57de 100644 --- a/lib/posix/linux.nim +++ b/lib/posix/linux.nim @@ -24,5 +24,5 @@ const # fn should be of type proc (a2: pointer): void {.cdecl.} proc clone*(fn: pointer; child_stack: pointer; flags: cint; - arg: pointer; ptid: ptr Pid; tls: pointer; + arg: pointer; ptid: ptr Pid; tls: pointer; ctid: ptr Pid): cint {.importc, header: "".} diff --git a/lib/pure/actors.nim b/lib/pure/actors.nim index da9037285..f0791f954 100644 --- a/lib/pure/actors.nim +++ b/lib/pure/actors.nim @@ -41,7 +41,7 @@ type Actor[In, Out] = object{.pure, final.} i: Channel[Task[In, Out]] t: TThread[ptr Actor[In, Out]] - + PActor*[In, Out] = ptr Actor[In, Out] ## an actor {.deprecated: [TTask: Task, TActor: Actor].} @@ -83,7 +83,7 @@ proc send*[In, Out, X, Y](receiver: PActor[In, Out], msg: In, shallowCopy(t.data, msg) send(receiver.i, t) -proc send*[In, Out](receiver: PActor[In, Out], msg: In, +proc send*[In, Out](receiver: PActor[In, Out], msg: In, sender: ptr Channel[Out] = nil) = ## sends a message to `receiver`'s inbox. var t: Task[In, Out] @@ -138,7 +138,7 @@ proc createActorPool*[In, Out](a: var ActorPool[In, Out], poolSize = 4) = proc sync*[In, Out](a: var ActorPool[In, Out], polling=50) = ## waits for every actor of `a` to finish with its work. Currently this is - ## implemented as polling every `polling` ms and has a slight chance + ## implemented as polling every `polling` ms and has a slight chance ## of failing since we check for every actor to be in `ready` state and not ## for messages still in ether. This will change in a later ## version, however. @@ -146,7 +146,7 @@ proc sync*[In, Out](a: var ActorPool[In, Out], polling=50) = while true: var wait = false for i in 0..high(a.actors): - if not a.actors[i].i.ready: + if not a.actors[i].i.ready: wait = true allReadyCount = 0 break @@ -222,7 +222,7 @@ proc spawn*[In](p: var ActorPool[In, void], input: In, var t: Task[In, void] setupTask() schedule() - + when not defined(testing) and isMainModule: var a: ActorPool[int, void] diff --git a/lib/pure/asyncfile.nim b/lib/pure/asyncfile.nim index ece9b4dfb..c7b9fac18 100644 --- a/lib/pure/asyncfile.nim +++ b/lib/pure/asyncfile.nim @@ -195,10 +195,10 @@ proc read*(f: AsyncFile, size: int): Future[string] = readBuffer.setLen(res) f.offset.inc(res) retFuture.complete(readBuffer) - + if not cb(f.fd): addRead(f.fd, cb) - + return retFuture proc readLine*(f: AsyncFile): Future[string] {.async.} = @@ -222,7 +222,7 @@ proc getFilePos*(f: AsyncFile): int64 = proc setFilePos*(f: AsyncFile, pos: int64) = ## Sets the position of the file pointer that is used for read/write - ## operations. The file's first byte has the index zero. + ## operations. The file's first byte has the index zero. f.offset = pos when not defined(windows) and not defined(nimdoc): let ret = lseek(f.fd.cint, pos, SEEK_SET) @@ -291,7 +291,7 @@ proc write*(f: AsyncFile, data: string): Future[void] = retFuture.complete() else: var written = 0 - + proc cb(fd: AsyncFD): bool = result = true let remainderSize = data.len-written @@ -309,7 +309,7 @@ proc write*(f: AsyncFile, data: string): Future[void] = result = false # We still have data to write. else: retFuture.complete() - + if not cb(f.fd): addWrite(f.fd, cb) return retFuture diff --git a/lib/pure/base64.nim b/lib/pure/base64.nim index 41d19dc0f..deab39c7c 100644 --- a/lib/pure/base64.nim +++ b/lib/pure/base64.nim @@ -9,11 +9,11 @@ ## This module implements a base64 encoder and decoder. -const +const cb64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" -template encodeInternal(s: expr, lineLen: int, newLine: string): stmt {.immediate.} = - ## encodes `s` into base64 representation. After `lineLen` characters, a +template encodeInternal(s: expr, lineLen: int, newLine: string): stmt {.immediate.} = + ## encodes `s` into base64 representation. After `lineLen` characters, a ## `newline` is added. var total = ((len(s) + 2) div 3) * 4 var numLines = (total + lineLen - 1) div lineLen @@ -29,13 +29,13 @@ template encodeInternal(s: expr, lineLen: int, newLine: string): stmt {.immediat var c = ord(s[i+2]) result[r] = cb64[a shr 2] result[r+1] = cb64[((a and 3) shl 4) or ((b and 0xF0) shr 4)] - result[r+2] = cb64[((b and 0x0F) shl 2) or ((c and 0xC0) shr 6)] - result[r+3] = cb64[c and 0x3F] + result[r+2] = cb64[((b and 0x0F) shl 2) or ((c and 0xC0) shr 6)] + result[r+3] = cb64[c and 0x3F] inc(r, 4) inc(i, 3) inc(currLine, 4) - if currLine >= lineLen and i != s.len-2: - for x in items(newLine): + if currLine >= lineLen and i != s.len-2: + for x in items(newLine): result[r] = x inc(r) currLine = 0 @@ -45,7 +45,7 @@ template encodeInternal(s: expr, lineLen: int, newLine: string): stmt {.immediat var b = ord(s[i+1]) result[r] = cb64[a shr 2] result[r+1] = cb64[((a and 3) shl 4) or ((b and 0xF0) shr 4)] - result[r+2] = cb64[((b and 0x0F) shl 2)] + result[r+2] = cb64[((b and 0x0F) shl 2)] result[r+3] = '=' if r+4 != result.len: setLen(result, r+4) @@ -61,17 +61,17 @@ template encodeInternal(s: expr, lineLen: int, newLine: string): stmt {.immediat #assert(r == result.len) discard -proc encode*[T:SomeInteger|char](s: openarray[T], lineLen = 75, newLine="\13\10"): string = - ## encodes `s` into base64 representation. After `lineLen` characters, a +proc encode*[T:SomeInteger|char](s: openarray[T], lineLen = 75, newLine="\13\10"): string = + ## encodes `s` into base64 representation. After `lineLen` characters, a ## `newline` is added. encodeInternal(s, lineLen, newLine) - -proc encode*(s: string, lineLen = 75, newLine="\13\10"): string = - ## encodes `s` into base64 representation. After `lineLen` characters, a + +proc encode*(s: string, lineLen = 75, newLine="\13\10"): string = + ## encodes `s` into base64 representation. After `lineLen` characters, a ## `newline` is added. encodeInternal(s, lineLen, newLine) - -proc decodeByte(b: char): int {.inline.} = + +proc decodeByte(b: char): int {.inline.} = case b of '+': result = ord('>') of '0'..'9': result = ord(b) + 4 @@ -79,7 +79,7 @@ proc decodeByte(b: char): int {.inline.} = of 'a'..'z': result = ord(b) - 71 else: result = 63 -proc decode*(s: string): string = +proc decode*(s: string): string = ## decodes a string in base64 representation back into its original form. ## Whitespace is skipped. const Whitespace = {' ', '\t', '\v', '\r', '\l', '\f'} @@ -96,7 +96,7 @@ proc decode*(s: string): string = var b = s[i+1].decodeByte var c = s[i+2].decodeByte var d = s[i+3].decodeByte - + result[r] = chr((a shl 2) and 0xff or ((b shr 4) and 0x03)) result[r+1] = chr((b shl 4) and 0xff or ((c shr 2) and 0x0F)) result[r+2] = chr((c shl 6) and 0xff or (d and 0x3F)) @@ -105,19 +105,19 @@ proc decode*(s: string): string = else: break assert i == s.len # adjust the length: - if i > 0 and s[i-1] == '=': + if i > 0 and s[i-1] == '=': dec(r) if i > 1 and s[i-2] == '=': dec(r) setLen(result, r) - + when isMainModule: assert encode("leasure.") == "bGVhc3VyZS4=" assert encode("easure.") == "ZWFzdXJlLg==" assert encode("asure.") == "YXN1cmUu" assert encode("sure.") == "c3VyZS4=" - + const longText = """Man is distinguished, not only by his reason, but by this - singular passion from other animals, which is a lust of the mind, + singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.""" diff --git a/lib/pure/basic2d.nim b/lib/pure/basic2d.nim index 1392fdeba..ad8f8653d 100644 --- a/lib/pure/basic2d.nim +++ b/lib/pure/basic2d.nim @@ -13,26 +13,26 @@ import strutils ## Basic 2d support with vectors, points, matrices and some basic utilities. ## Vectors are implemented as direction vectors, ie. when transformed with a matrix -## the translation part of matrix is ignored. +## the translation part of matrix is ignored. ## Operators `+` , `-` , `*` , `/` , `+=` , `-=` , `*=` and `/=` are implemented for vectors and scalars. ## ## Quick start example: -## +## ## # Create a matrix which first rotates, then scales and at last translates -## +## ## var m:Matrix2d=rotate(DEG90) & scale(2.0) & move(100.0,200.0) -## +## ## # Create a 2d point at (100,0) and a vector (5,2) -## -## var pt:Point2d=point2d(100.0,0.0) -## +## +## var pt:Point2d=point2d(100.0,0.0) +## ## var vec:Vector2d=vector2d(5.0,2.0) -## -## +## +## ## pt &= m # transforms pt in place -## +## ## var pt2:Point2d=pt & m #concatenates pt with m and returns a new point -## +## ## var vec2:Vector2d=vec & m #concatenates vec with m and returns a new vector @@ -64,12 +64,12 @@ type ## not used for geometric transformations in 2d. ax*,ay*,bx*,by*,tx*,ty*:float Point2d* = object - ## Implements a non-homogeneous 2d point stored as + ## Implements a non-homogeneous 2d point stored as ## an `x` coordinate and an `y` coordinate. x*,y*:float - Vector2d* = object - ## Implements a 2d **direction vector** stored as - ## an `x` coordinate and an `y` coordinate. Direction vector means, + Vector2d* = object + ## Implements a 2d **direction vector** stored as + ## an `x` coordinate and an `y` coordinate. Direction vector means, ## that when transforming a vector with a matrix, the translational ## part of the matrix is ignored. x*,y*:float @@ -78,7 +78,7 @@ type # Some forward declarations... proc matrix2d*(ax,ay,bx,by,tx,ty:float):Matrix2d {.noInit.} - ## Creates a new matrix. + ## Creates a new matrix. ## `ax`,`ay` is the local x axis ## `bx`,`by` is the local y axis ## `tx`,`ty` is the translation @@ -99,7 +99,7 @@ let YAXIS*:Vector2d=vector2d(0.0,1.0) ## Quick acces to an 2d y-axis unit vector - + # *************************************** # Private utils # *************************************** @@ -114,13 +114,13 @@ proc safeArccos(v:float):float= return arccos(clamp(v,-1.0,1.0)) -template makeBinOpVector(s:expr)= +template makeBinOpVector(s:expr)= ## implements binary operators + , - , * and / for vectors proc s*(a,b:Vector2d):Vector2d {.inline,noInit.} = vector2d(s(a.x,b.x),s(a.y,b.y)) proc s*(a:Vector2d,b:float):Vector2d {.inline,noInit.} = vector2d(s(a.x,b),s(a.y,b)) proc s*(a:float,b:Vector2d):Vector2d {.inline,noInit.} = vector2d(s(a,b.x),s(a,b.y)) - -template makeBinOpAssignVector(s:expr)= + +template makeBinOpAssignVector(s:expr)= ## implements inplace binary operators += , -= , /= and *= for vectors proc s*(a:var Vector2d,b:Vector2d) {.inline.} = s(a.x,b.x) ; s(a.y,b.y) proc s*(a:var Vector2d,b:float) {.inline.} = s(a.x,b) ; s(a.y,b) @@ -144,7 +144,7 @@ proc matrix2d*(ax,ay,bx,by,tx,ty:float):Matrix2d = proc `&`*(a,b:Matrix2d):Matrix2d {.noInit.} = #concatenate matrices ## Concatenates matrices returning a new matrix. - + # | a.AX a.AY 0 | | b.AX b.AY 0 | # | a.BX a.BY 0 | * | b.BX b.BY 0 | # | a.TX a.TY 1 | | b.TX b.TY 1 | @@ -153,7 +153,7 @@ proc `&`*(a,b:Matrix2d):Matrix2d {.noInit.} = #concatenate matrices a.ax * b.ay + a.ay * b.by, a.bx * b.ax + a.by * b.bx, a.bx * b.ay + a.by * b.by, - a.tx * b.ax + a.ty * b.bx + b.tx, + a.tx * b.ax + a.ty * b.bx + b.tx, a.tx * b.ay + a.ty * b.by + b.ty) @@ -169,13 +169,13 @@ proc stretch*(sx,sy:float):Matrix2d {.noInit.} = ## Returns new a stretch matrix, which is a ## scale matrix with non uniform scale in x and y. result.setElements(sx,0,0,sy,0,0) - + proc stretch*(sx,sy:float,org:Point2d):Matrix2d {.noInit.} = ## Returns a new stretch matrix, which is a ## scale matrix with non uniform scale in x and y. ## `org` is used as stretch origin. result.setElements(sx,0,0,sy,org.x-sx*org.x,org.y-sy*org.y) - + proc move*(dx,dy:float):Matrix2d {.noInit.} = ## Returns a new translation matrix. result.setElements(1,0,0,1,dx,dy) @@ -187,7 +187,7 @@ proc move*(v:Vector2d):Matrix2d {.noInit.} = proc rotate*(rad:float):Matrix2d {.noInit.} = ## Returns a new rotation matrix, which ## represents a rotation by `rad` radians - let + let s=sin(rad) c=cos(rad) result.setElements(c,s,-s,c,0,0) @@ -200,7 +200,7 @@ proc rotate*(rad:float,org:Point2d):Matrix2d {.noInit.} = s=sin(rad) c=cos(rad) result.setElements(c,s,-s,c,org.x+s*org.y-c*org.x,org.y-c*org.y-s*org.x) - + proc mirror*(v:Vector2d):Matrix2d {.noInit.} = ## Returns a new mirror matrix, mirroring ## around the line that passes through origo and @@ -211,7 +211,7 @@ proc mirror*(v:Vector2d):Matrix2d {.noInit.} = nd=1.0/(sqx+sqy) #used to normalize invector xy2=v.x*v.y*2.0*nd sqd=nd*(sqx-sqy) - + if nd==Inf or nd==NegInf: return IDMATRIX #mirroring around a zero vector is arbitrary=>just use identity @@ -230,7 +230,7 @@ proc mirror*(org:Point2d,v:Vector2d):Matrix2d {.noInit.} = nd=1.0/(sqx+sqy) #used to normalize invector xy2=v.x*v.y*2.0*nd sqd=nd*(sqx-sqy) - + if nd==Inf or nd==NegInf: return IDMATRIX #mirroring around a zero vector is arbitrary=>just use identity @@ -238,47 +238,47 @@ proc mirror*(org:Point2d,v:Vector2d):Matrix2d {.noInit.} = sqd,xy2, xy2,-sqd, org.x-org.y*xy2-org.x*sqd,org.y-org.x*xy2+org.y*sqd) - + proc skew*(xskew,yskew:float):Matrix2d {.noInit.} = - ## Returns a new skew matrix, which has its + ## Returns a new skew matrix, which has its ## x axis rotated `xskew` radians from the local x axis, and ## y axis rotated `yskew` radians from the local y axis result.setElements(cos(yskew),sin(yskew),-sin(xskew),cos(xskew),0,0) - + proc `$`* (t:Matrix2d):string {.noInit.} = ## Returns a string representation of the matrix return rtos(t.ax) & "," & rtos(t.ay) & - "," & rtos(t.bx) & "," & rtos(t.by) & + "," & rtos(t.bx) & "," & rtos(t.by) & "," & rtos(t.tx) & "," & rtos(t.ty) proc isUniform*(t:Matrix2d,tol=1.0e-6):bool= - ## Checks if the transform is uniform, that is + ## Checks if the transform is uniform, that is ## perpendicular axes of equal length, which means (for example) ## it cannot transform a circle into an ellipse. - ## `tol` is used as tolerance for both equal length comparison + ## `tol` is used as tolerance for both equal length comparison ## and perp. comparison. - + #dot product=0 means perpendicular coord. system: - if abs(t.ax*t.bx+t.ay*t.by)<=tol: + if abs(t.ax*t.bx+t.ay*t.by)<=tol: #subtract squared lengths of axes to check if uniform scaling: if abs((t.ax*t.ax+t.ay*t.ay)-(t.bx*t.bx+t.by*t.by))<=tol: return true return false - + proc determinant*(t:Matrix2d):float= ## Computes the determinant of the matrix. - + #NOTE: equivalent with perp.dot product for two 2d vectors - return t.ax*t.by-t.bx*t.ay + return t.ax*t.by-t.bx*t.ay proc isMirroring* (m:Matrix2d):bool= ## Checks if the `m` is a mirroring matrix, ## which means it will reverse direction of a curve transformed with it return m.determinant<0.0 - + proc inverse*(m:Matrix2d):Matrix2d {.noInit.} = ## Returns a new matrix, which is the inverse of the matrix ## If the matrix is not invertible (determinant=0), an EDivByZero @@ -286,7 +286,7 @@ proc inverse*(m:Matrix2d):Matrix2d {.noInit.} = let d=m.determinant if d==0.0: raise newException(DivByZeroError,"Cannot invert a zero determinant matrix") - + result.setElements( m.by/d,-m.ay/d, -m.bx/d,m.ax/d, @@ -296,14 +296,14 @@ proc inverse*(m:Matrix2d):Matrix2d {.noInit.} = proc equals*(m1:Matrix2d,m2:Matrix2d,tol=1.0e-6):bool= ## Checks if all elements of `m1`and `m2` is equal within ## a given tolerance `tol`. - return + return abs(m1.ax-m2.ax)<=tol and abs(m1.ay-m2.ay)<=tol and abs(m1.bx-m2.bx)<=tol and abs(m1.by-m2.by)<=tol and abs(m1.tx-m2.tx)<=tol and abs(m1.ty-m2.ty)<=tol - + proc `=~`*(m1,m2:Matrix2d):bool= ## Checks if `m1`and `m2` is approximately equal, using a ## tolerance of 1e-6. @@ -350,16 +350,16 @@ proc slopeVector2d*(slope:float,len:float):Vector2d {.noInit.} = proc len*(v:Vector2d):float {.inline.}= ## Returns the length of the vector. sqrt(v.x*v.x+v.y*v.y) - + proc `len=`*(v:var Vector2d,newlen:float) {.noInit.} = ## Sets the length of the vector, keeping its angle. let fac=newlen/v.len - + if newlen==0.0: v.x=0.0 v.y=0.0 return - + if fac==Inf or fac==NegInf: #to short for float accuracy #do as good as possible: @@ -368,30 +368,30 @@ proc `len=`*(v:var Vector2d,newlen:float) {.noInit.} = else: v.x*=fac v.y*=fac - + proc sqrLen*(v:Vector2d):float {.inline.}= ## Computes the squared length of the vector, which is ## faster than computing the absolute length. v.x*v.x+v.y*v.y - + proc angle*(v:Vector2d):float= - ## Returns the angle of the vector. + ## Returns the angle of the vector. ## (The counter clockwise plane angle between posetive x axis and `v`) result=arctan2(v.y,v.x) if result<0.0: result+=DEG360 - + proc `$` *(v:Vector2d):string= ## String representation of `v` result=rtos(v.x) result.add(",") result.add(rtos(v.y)) - - + + proc `&` *(v:Vector2d,m:Matrix2d):Vector2d {.noInit.} = ## Concatenate vector `v` with a transformation matrix. ## Transforming a vector ignores the translational part ## of the matrix. - + # | AX AY 0 | # | X Y 1 | * | BX BY 0 | # | 0 0 1 | @@ -403,7 +403,7 @@ proc `&=`*(v:var Vector2d,m:Matrix2d) {.inline.}= ## Applies transformation `m` onto `v` in place. ## Transforming a vector ignores the translational part ## of the matrix. - + # | AX AY 0 | # | X Y 1 | * | BX BY 0 | # | 0 0 1 | @@ -412,31 +412,31 @@ proc `&=`*(v:var Vector2d,m:Matrix2d) {.inline.}= v.x=newx -proc tryNormalize*(v:var Vector2d):bool= +proc tryNormalize*(v:var Vector2d):bool= ## Modifies `v` to have a length of 1.0, keeping its angle. - ## If `v` has zero length (and thus no angle), it is left unmodified and + ## If `v` has zero length (and thus no angle), it is left unmodified and ## false is returned, otherwise true is returned. let mag=v.len if mag==0.0: return false - + v.x/=mag v.y/=mag return true -proc normalize*(v:var Vector2d) {.inline.}= +proc normalize*(v:var Vector2d) {.inline.}= ## Modifies `v` to have a length of 1.0, keeping its angle. ## If `v` has zero length, an EDivByZero will be raised. if not tryNormalize(v): raise newException(DivByZeroError,"Cannot normalize zero length vector") - + proc transformNorm*(v:var Vector2d,t:Matrix2d)= ## Applies a normal direction transformation `t` onto `v` in place. - ## The resulting vector is *not* normalized. Transforming a vector ignores the - ## translational part of the matrix. If the matrix is not invertible + ## The resulting vector is *not* normalized. Transforming a vector ignores the + ## translational part of the matrix. If the matrix is not invertible ## (determinant=0), an EDivByZero will be raised. # transforming a normal is done by transforming @@ -469,16 +469,16 @@ proc transformInv*(v:var Vector2d,t:Matrix2d)= proc transformNormInv*(v:var Vector2d,t:Matrix2d)= ## Applies an inverse normal direction transformation `t` onto `v` in place. - ## This is faster than creating an inverse - ## matrix and transformNorm(...) it. Transforming a vector ignores the + ## This is faster than creating an inverse + ## matrix and transformNorm(...) it. Transforming a vector ignores the ## translational part of the matrix. # normal inverse transform is done by transforming # by the inverse of the transpose of the inverse of the org. matrix # which is equivalent with transforming with the transpose. # | | | AX AY 0 |^-1|^T|^-1 | AX BX 0 | - # | X Y 1 | * | | | BX BY 0 | | | = | X Y 1 | * | AY BY 0 | - # | | | 0 0 1 | | | | 0 0 1 | + # | X Y 1 | * | | | BX BY 0 | | | = | X Y 1 | * | AY BY 0 | + # | | | 0 0 1 | | | | 0 0 1 | # This can be heavily reduced to: let newx=t.ay*v.y+t.ax*v.x v.y=t.by*v.y+t.bx*v.x @@ -489,19 +489,19 @@ proc rotate90*(v:var Vector2d) {.inline.}= ## without using any trigonometrics. swap(v.x,v.y) v.x= -v.x - + proc rotate180*(v:var Vector2d){.inline.}= ## Quickly rotates vector `v` 180 degrees counter clockwise, ## without using any trigonometrics. v.x= -v.x v.y= -v.y - + proc rotate270*(v:var Vector2d) {.inline.}= ## Quickly rotates vector `v` 270 degrees counter clockwise, ## without using any trigonometrics. swap(v.x,v.y) v.y= -v.y - + proc rotate*(v:var Vector2d,rad:float) = ## Rotates vector `v` `rad` radians in place. let @@ -510,18 +510,18 @@ proc rotate*(v:var Vector2d,rad:float) = newx=c*v.x-s*v.y v.y=c*v.y+s*v.x v.x=newx - + proc scale*(v:var Vector2d,fac:float){.inline.}= ## Scales vector `v` `rad` radians in place. v.x*=fac v.y*=fac - + proc stretch*(v:var Vector2d,facx,facy:float){.inline.}= ## Stretches vector `v` `facx` times horizontally, ## and `facy` times vertically. v.x*=facx v.y*=facy - + proc mirror*(v:var Vector2d,mirrvec:Vector2d)= ## Mirrors vector `v` using `mirrvec` as mirror direction. let @@ -530,20 +530,20 @@ proc mirror*(v:var Vector2d,mirrvec:Vector2d)= nd=1.0/(sqx+sqy) #used to normalize invector xy2=mirrvec.x*mirrvec.y*2.0*nd sqd=nd*(sqx-sqy) - + if nd==Inf or nd==NegInf: return #mirroring around a zero vector is arbitrary=>keep as is is fastest - + let newx=xy2*v.y+sqd*v.x v.y=v.x*xy2-sqd*v.y v.x=newx - - + + proc `-` *(v:Vector2d):Vector2d= ## Negates a vector result.x= -v.x result.y= -v.y - + # declare templated binary operators makeBinOpVector(`+`) makeBinOpVector(`-`) @@ -556,27 +556,27 @@ makeBinOpAssignVector(`/=`) proc dot*(v1,v2:Vector2d):float= - ## Computes the dot product of two vectors. + ## Computes the dot product of two vectors. ## Returns 0.0 if the vectors are perpendicular. return v1.x*v2.x+v1.y*v2.y - + proc cross*(v1,v2:Vector2d):float= ## Computes the cross product of two vectors, also called ## the 'perpendicular dot product' in 2d. Returns 0.0 if the vectors ## are parallel. return v1.x*v2.y-v1.y*v2.x - + proc equals*(v1,v2:Vector2d,tol=1.0e-6):bool= ## Checks if two vectors approximately equals with a tolerance. return abs(v2.x-v1.x)<=tol and abs(v2.y-v1.y)<=tol - + proc `=~` *(v1,v2:Vector2d):bool= - ## Checks if two vectors approximately equals with a + ## Checks if two vectors approximately equals with a ## hardcoded tolerance 1e-6 equals(v1,v2) - + proc angleTo*(v1,v2:Vector2d):float= - ## Returns the smallest of the two possible angles + ## Returns the smallest of the two possible angles ## between `v1` and `v2` in radians. var nv1=v1 @@ -584,7 +584,7 @@ proc angleTo*(v1,v2:Vector2d):float= if not nv1.tryNormalize or not nv2.tryNormalize: return 0.0 # zero length vector has zero angle to any other vector return safeArccos(dot(nv1,nv2)) - + proc angleCCW*(v1,v2:Vector2d):float= ## Returns the counter clockwise plane angle from `v1` to `v2`, ## in range 0 - 2*PI @@ -592,7 +592,7 @@ proc angleCCW*(v1,v2:Vector2d):float= if v1.cross(v2)>=0.0: return a return DEG360-a - + proc angleCW*(v1,v2:Vector2d):float= ## Returns the clockwise plane angle from `v1` to `v2`, ## in range 0 - 2*PI @@ -612,32 +612,32 @@ proc turnAngle*(v1,v2:Vector2d):float= proc bisect*(v1,v2:Vector2d):Vector2d {.noInit.}= ## Computes the bisector between v1 and v2 as a normalized vector. ## If one of the input vectors has zero length, a normalized version - ## of the other is returned. If both input vectors has zero length, + ## of the other is returned. If both input vectors has zero length, ## an arbitrary normalized vector is returned. var vmag1=v1.len vmag2=v2.len - + # zero length vector equals arbitrary vector, just change to magnitude to one to # avoid zero division - if vmag1==0.0: + if vmag1==0.0: if vmag2==0: #both are zero length return any normalized vector return XAXIS vmag1=1.0 - if vmag2==0.0: vmag2=1.0 - + if vmag2==0.0: vmag2=1.0 + let x1=v1.x/vmag1 y1=v1.y/vmag1 x2=v2.x/vmag2 y2=v2.y/vmag2 - + result.x=(x1 + x2) * 0.5 result.y=(y1 + y2) * 0.5 - + if not result.tryNormalize(): # This can happen if vectors are colinear. In this special case - # there are actually two bisectors, we select just + # there are actually two bisectors, we select just # one of them (x1,y1 rotated 90 degrees ccw). result.x = -y1 result.y = x1 @@ -651,13 +651,13 @@ proc bisect*(v1,v2:Vector2d):Vector2d {.noInit.}= proc point2d*(x,y:float):Point2d = result.x=x result.y=y - + proc sqrDist*(a,b:Point2d):float= ## Computes the squared distance between `a` and `b` let dx=b.x-a.x let dy=b.y-a.y result=dx*dx+dy*dy - + proc dist*(a,b:Point2d):float {.inline.}= ## Computes the absolute distance between `a` and `b` result=sqrt(sqrDist(a,b)) @@ -675,11 +675,11 @@ proc `$` *(p:Point2d):string= result=rtos(p.x) result.add(",") result.add(rtos(p.y)) - + proc `&`*(p:Point2d,t:Matrix2d):Point2d {.noInit,inline.} = ## Concatenates a point `p` with a transform `t`, ## resulting in a new, transformed point. - + # | AX AY 0 | # | X Y 1 | * | BX BY 0 | # | TX TY 1 | @@ -697,21 +697,21 @@ proc transformInv*(p:var Point2d,t:Matrix2d){.inline.}= ## Applies the inverse of transformation `t` onto `p` in place. ## If the matrix is not invertable (determinant=0) , EDivByZero will ## be raised. - + # | AX AY 0 | ^-1 # | X Y 1 | * | BX BY 0 | # | TX TY 1 | let d=t.determinant if d==0.0: raise newException(DivByZeroError,"Cannot invert a zero determinant matrix") - let + let newx= (t.bx*t.ty-t.by*t.tx+p.x*t.by-p.y*t.bx)/d p.y = -(t.ax*t.ty-t.ay*t.tx+p.x*t.ay-p.y*t.ax)/d p.x=newx - - + + proc `+`*(p:Point2d,v:Vector2d):Point2d {.noInit,inline.} = - ## Adds a vector `v` to a point `p`, resulting + ## Adds a vector `v` to a point `p`, resulting ## in a new point. result.x=p.x+v.x result.y=p.y+v.y @@ -722,7 +722,7 @@ proc `+=`*(p:var Point2d,v:Vector2d) {.noInit,inline.} = p.y+=v.y proc `-`*(p:Point2d,v:Vector2d):Point2d {.noInit,inline.} = - ## Subtracts a vector `v` from a point `p`, resulting + ## Subtracts a vector `v` from a point `p`, resulting ## in a new point. result.x=p.x-v.x result.y=p.y-v.y @@ -736,13 +736,13 @@ proc `-=`*(p:var Point2d,v:Vector2d) {.noInit,inline.} = ## Subtracts a vector `v` from a point `p` in place. p.x-=v.x p.y-=v.y - + proc equals(p1,p2:Point2d,tol=1.0e-6):bool {.inline.}= ## Checks if two points approximately equals with a tolerance. return abs(p2.x-p1.x)<=tol and abs(p2.y-p1.y)<=tol proc `=~`*(p1,p2:Point2d):bool {.inline.}= - ## Checks if two vectors approximately equals with a + ## Checks if two vectors approximately equals with a ## hardcoded tolerance 1e-6 equals(p1,p2) @@ -759,7 +759,7 @@ proc rotate*(p:var Point2d,rad:float)= newx=p.x*c-p.y*s p.y=p.y*c+p.x*s p.x=newx - + proc rotate*(p:var Point2d,rad:float,org:Point2d)= ## Rotates a point in place `rad` radians using `org` as ## center of rotation. @@ -769,25 +769,25 @@ proc rotate*(p:var Point2d,rad:float,org:Point2d)= newx=(p.x - org.x) * c - (p.y - org.y) * s + org.x p.y=(p.y - org.y) * c + (p.x - org.x) * s + org.y p.x=newx - + proc scale*(p:var Point2d,fac:float) {.inline.}= ## Scales a point in place `fac` times with world origo as origin. p.x*=fac p.y*=fac - + proc scale*(p:var Point2d,fac:float,org:Point2d){.inline.}= ## Scales the point in place `fac` times with `org` as origin. p.x=(p.x - org.x) * fac + org.x p.y=(p.y - org.y) * fac + org.y proc stretch*(p:var Point2d,facx,facy:float){.inline.}= - ## Scales a point in place non uniformly `facx` and `facy` times with + ## Scales a point in place non uniformly `facx` and `facy` times with ## world origo as origin. p.x*=facx p.y*=facy proc stretch*(p:var Point2d,facx,facy:float,org:Point2d){.inline.}= - ## Scales the point in place non uniformly `facx` and `facy` times with + ## Scales the point in place non uniformly `facx` and `facy` times with ## `org` as origin. p.x=(p.x - org.x) * facx + org.x p.y=(p.y - org.y) * facy + org.y @@ -814,21 +814,21 @@ proc area*(a,b,c:Point2d):float= return abs(sgnArea(a,b,c)) proc closestPoint*(p:Point2d,pts:varargs[Point2d]):Point2d= - ## Returns a point selected from `pts`, that has the closest + ## Returns a point selected from `pts`, that has the closest ## euclidean distance to `p` assert(pts.len>0) # must have at least one point - - var + + var bestidx=0 bestdist=p.sqrDist(pts[0]) curdist:float - + for idx in 1..high(pts): curdist=p.sqrDist(pts[idx]) if curdist ", result) -# Pop the flags off returning a 4 byte aligned ptr to our Key or Val +# Pop the flags off returning a 4 byte aligned ptr to our Key or Val proc pop(x: int): int {.inline.} = result = x and 0xFFFFFFFC'i32 -# Pop the raw value off of our Key or Val +# Pop the raw value off of our Key or Val proc popRaw(x: int): int {.inline.} = - result = x shr 2 + result = x shr 2 -# Pop the flags off returning a 4 byte aligned ptr to our Key or Val +# Pop the flags off returning a 4 byte aligned ptr to our Key or Val proc popPtr[V](x: int): ptr V {.inline.} = result = cast[ptr V](pop(x)) #echo("popPtr " & $x & " -> " & $cast[int](result)) @@ -136,34 +136,34 @@ proc popPtr[V](x: int): ptr V {.inline.} = # K or V is no longer valid use new table const Ghost = 0xFFFFFFFC proc isGhost(x: int): bool {.inline.} = - result = x == 0xFFFFFFFC + result = x == 0xFFFFFFFC -# Tombstone -# applied to V = K is dead -proc isTomb(x: int): bool {.inline.} = +# Tombstone +# applied to V = K is dead +proc isTomb(x: int): bool {.inline.} = result = (x and 0x00000002) != 0 proc setTomb(x: int): int {.inline.} = result = x or 0x00000002 # Prime -# K or V is in new table copied from old -proc isPrime(x: int): bool {.inline.} = +# K or V is in new table copied from old +proc isPrime(x: int): bool {.inline.} = result = (x and 0x00000001) != 0 proc setPrime(x: int): int {.inline.} = result = x or 0x00000001 -#------------------------------------------------------------------------------ +#------------------------------------------------------------------------------ ##This is for i32 only need to override for i64 -proc hashInt(x: int):int {.inline.} = - var h = uint32(x) #shr 2'u32 +proc hashInt(x: int):int {.inline.} = + var h = uint32(x) #shr 2'u32 h = h xor (h shr 16'u32) h *= 0x85ebca6b'u32 h = h xor (h shr 13'u32) h *= 0xc2b2ae35'u32 - h = h xor (h shr 16'u32) + h = h xor (h shr 16'u32) result = int(h) #------------------------------------------------------------------------------ @@ -175,31 +175,31 @@ proc resize[K,V](self: PConcTable[K,V]): PConcTable[K,V] = #echo("A new table already exists, copy in progress") return next var - oldLen = atomic_load_n(self.len.addr, ATOMIC_RELAXED) + oldLen = atomic_load_n(self.len.addr, ATOMIC_RELAXED) newTable = newLFTable[K,V](oldLen*2) success = atomic_compare_exchange_n(self.next.addr, next.addr, newTable, false, ATOMIC_RELAXED, ATOMIC_RELAXED) if not success: echo("someone beat us to it! delete table we just created and return his " & $cast[int](next)) - deleteConcTable(newTable) - return next + deleteConcTable(newTable) + return next else: echo("Created New Table! " & $cast[int](newTable) & " Size = " & $newTable.len) return newTable - + #------------------------------------------------------------------------------ -#proc keyEQ[K](key1: ptr K, key2: ptr K): bool {.inline.} = -proc keyEQ[K](key1: int, key2: int): bool {.inline.} = +#proc keyEQ[K](key1: ptr K, key2: ptr K): bool {.inline.} = +proc keyEQ[K](key1: int, key2: int): bool {.inline.} = result = false when K is Raw: - if key1 == key2: + if key1 == key2: result = true else: - var + var p1 = popPtr[K](key1) p2 = popPtr[K](key2) - if p1 != nil and p2 != nil: + if p1 != nil and p2 != nil: if cast[int](p1) == cast[int](p2): return true if p1[] == p2[]: @@ -214,53 +214,53 @@ proc keyEQ[K](key1: int, key2: int): bool {.inline.} = proc copySlot[K,V](idx: int, oldTbl: var PConcTable[K,V], newTbl: var PConcTable[K,V]): bool = #echo("Copy idx " & $idx) - var + var oldVal = 0 - oldkey = 0 + oldkey = 0 ok = false result = false #Block the key so no other threads waste time here while not ok: - ok = atomic_compare_exchange_n(oldTbl[idx].key.addr, oldKey.addr, + ok = atomic_compare_exchange_n(oldTbl[idx].key.addr, oldKey.addr, setTomb(oldKey), false, ATOMIC_RELAXED, ATOMIC_RELAXED) - #echo("oldKey was = " & $oldKey & " set it to tomb " & $setTomb(oldKey)) - #Prevent new values from appearing in the old table by priming + #echo("oldKey was = " & $oldKey & " set it to tomb " & $setTomb(oldKey)) + #Prevent new values from appearing in the old table by priming oldVal = atomic_load_n(oldTbl[idx].value.addr, ATOMIC_RELAXED) while not isPrime(oldVal): - var box = if oldVal == 0 or isTomb(oldVal) : oldVal.setTomb.setPrime - else: oldVal.setPrime - if atomic_compare_exchange_n(oldTbl[idx].value.addr, oldVal.addr, + var box = if oldVal == 0 or isTomb(oldVal) : oldVal.setTomb.setPrime + else: oldVal.setPrime + if atomic_compare_exchange_n(oldTbl[idx].value.addr, oldVal.addr, box, false, ATOMIC_RELAXED, ATOMIC_RELAXED): - if isPrime(box) and isTomb(box): + if isPrime(box) and isTomb(box): return true oldVal = box break #echo("oldVal was = ", oldVal, " set it to prime ", box) - if isPrime(oldVal) and isTomb(oldVal): + if isPrime(oldVal) and isTomb(oldVal): #when not (K is Raw): - # deallocShared(popPtr[K](oldKey)) + # deallocShared(popPtr[K](oldKey)) return false - if isTomb(oldVal): + if isTomb(oldVal): echo("oldVal is Tomb!!!, should not happen") - if pop(oldVal) != 0: + if pop(oldVal) != 0: result = setVal(newTbl, pop(oldKey), pop(oldVal), 0, true) == 0 - if result: - #echo("Copied a Slot! idx= " & $idx & " key= " & $oldKey & " val= " & $oldVal) - else: - #echo("copy slot failed") + if result: + #echo("Copied a Slot! idx= " & $idx & " key= " & $oldKey & " val= " & $oldVal) + else: + #echo("copy slot failed") # Our copy is done so we disable the old slot while not ok: - ok = atomic_compare_exchange_n(oldTbl[idx].value.addr, oldVal.addr, + ok = atomic_compare_exchange_n(oldTbl[idx].value.addr, oldVal.addr, oldVal.setTomb.setPrime , false, ATOMIC_RELAXED, ATOMIC_RELAXED) - #echo("disabled old slot") - #echo"---------------------" + #echo("disabled old slot") + #echo"---------------------" #------------------------------------------------------------------------------ proc promote[K,V](table: var PConcTable[K,V]) = var newData = atomic_load_n(table.next.data.addr, ATOMIC_RELAXED) - newLen = atomic_load_n(table.next.len.addr, ATOMIC_RELAXED) + newLen = atomic_load_n(table.next.len.addr, ATOMIC_RELAXED) newUsed = atomic_load_n(table.next.used.addr, ATOMIC_RELAXED) deallocShared(table.data) @@ -270,52 +270,52 @@ proc promote[K,V](table: var PConcTable[K,V]) = atomic_store_n(table.copyIdx.addr, 0, ATOMIC_RELAXED) atomic_store_n(table.copyDone.addr, 0, ATOMIC_RELAXED) deallocShared(table.next) - atomic_store_n(table.next.addr, nil, ATOMIC_RELAXED) + atomic_store_n(table.next.addr, nil, ATOMIC_RELAXED) echo("new table swapped!") #------------------------------------------------------------------------------ - -proc checkAndPromote[K,V](table: var PConcTable[K,V], workDone: int): bool = - var + +proc checkAndPromote[K,V](table: var PConcTable[K,V], workDone: int): bool = + var oldLen = atomic_load_n(table.len.addr, ATOMIC_RELAXED) copyDone = atomic_load_n(table.copyDone.addr, ATOMIC_RELAXED) ok: bool - result = false + result = false if workDone > 0: #echo("len to copy =" & $oldLen) - #echo("copyDone + workDone = " & $copyDone & " + " & $workDone) + #echo("copyDone + workDone = " & $copyDone & " + " & $workDone) while not ok: - ok = atomic_compare_exchange_n(table.copyDone.addr, copyDone.addr, + ok = atomic_compare_exchange_n(table.copyDone.addr, copyDone.addr, copyDone + workDone, false, ATOMIC_RELAXED, ATOMIC_RELAXED) - #if ok: echo("set copyDone") - # If the copy is done we can promote this table + #if ok: echo("set copyDone") + # If the copy is done we can promote this table if copyDone + workDone >= oldLen: # Swap new data - #echo("work is done!") + #echo("work is done!") table.promote result = true - + #------------------------------------------------------------------------------ proc copySlotAndCheck[K,V](table: var PConcTable[K,V], idx: int): PConcTable[K,V] = var newTable = cast[PConcTable[K,V]](atomic_load_n(table.next.addr, ATOMIC_RELAXED)) - result = newTable - if newTable != nil and copySlot(idx, table, newTable): - #echo("copied a single slot, idx = " & $idx) + result = newTable + if newTable != nil and copySlot(idx, table, newTable): + #echo("copied a single slot, idx = " & $idx) if checkAndPromote(table, 1): return table - + #------------------------------------------------------------------------------ - + proc helpCopy[K,V](table: var PConcTable[K,V]): PConcTable[K,V] = var - newTable = cast[PConcTable[K,V]](atomic_load_n(table.next.addr, ATOMIC_RELAXED)) - result = newTable - if newTable != nil: - var - oldLen = atomic_load_n(table.len.addr, ATOMIC_RELAXED) + newTable = cast[PConcTable[K,V]](atomic_load_n(table.next.addr, ATOMIC_RELAXED)) + result = newTable + if newTable != nil: + var + oldLen = atomic_load_n(table.len.addr, ATOMIC_RELAXED) copyDone = atomic_load_n(table.copyDone.addr, ATOMIC_RELAXED) copyIdx = 0 work = min(oldLen, minCopyWork) @@ -324,54 +324,54 @@ proc helpCopy[K,V](table: var PConcTable[K,V]): PConcTable[K,V] = if copyDone < oldLen: var ok: bool while not ok: - ok = atomic_compare_exchange_n(table.copyIdx.addr, copyIdx.addr, + ok = atomic_compare_exchange_n(table.copyIdx.addr, copyIdx.addr, copyIdx + work, false, ATOMIC_RELAXED, ATOMIC_RELAXED) - #echo("copy idx = ", copyIdx) + #echo("copy idx = ", copyIdx) for i in 0..work-1: - var idx = (copyIdx + i) and (oldLen - 1) + var idx = (copyIdx + i) and (oldLen - 1) if copySlot(idx, table, newTable): workDone += 1 if workDone > 0: #echo("did work ", workDone, " on thread ", cast[int](myThreadID[pointer]())) if checkAndPromote(table, workDone): return table - # In case a thread finished all the work then got stalled before promotion + # In case a thread finished all the work then got stalled before promotion if checkAndPromote(table, 0): return table - - + + #------------------------------------------------------------------------------ proc setVal[K,V](table: var PConcTable[K,V], key: int, val: int, expVal: int, match: bool): int = - #echo("-try set- in table ", " key = ", (popPtr[K](key)[]), " val = ", val) - when K is Raw: - var idx = hashInt(key) + #echo("-try set- in table ", " key = ", (popPtr[K](key)[]), " val = ", val) + when K is Raw: + var idx = hashInt(key) else: - var idx = popPtr[K](key)[].hash - var - nextTable: PConcTable[K,V] + var idx = popPtr[K](key)[].hash + var + nextTable: PConcTable[K,V] probes = 1 - # spin until we find a key slot or build and jump to next table - while true: - idx = idx and (table.len - 1) + # spin until we find a key slot or build and jump to next table + while true: + idx = idx and (table.len - 1) #echo("try set idx = " & $idx & "for" & $key) var - probedKey = 0 - openKey = atomic_compare_exchange_n(table[idx].key.addr, probedKey.addr, - key, false, ATOMIC_RELAXED, ATOMIC_RELAXED) + probedKey = 0 + openKey = atomic_compare_exchange_n(table[idx].key.addr, probedKey.addr, + key, false, ATOMIC_RELAXED, ATOMIC_RELAXED) if openKey: if val.isTomb: #echo("val was tomb, bail, no reason to set an open slot to tomb") return val - #increment used slots - #echo("found an open slot, total used = " & + #increment used slots + #echo("found an open slot, total used = " & #$atomic_add_fetch(table.used.addr, 1, ATOMIC_RELAXED)) discard atomic_add_fetch(table.used.addr, 1, ATOMIC_RELAXED) - break # We found an open slot - #echo("set idx ", idx, " key = ", key, " probed = ", probedKey) + break # We found an open slot + #echo("set idx ", idx, " key = ", key, " probed = ", probedKey) if keyEQ[K](probedKey, key): - #echo("we found the matching slot") - break # We found a matching slot + #echo("we found the matching slot") + break # We found a matching slot if (not(expVal != 0 and match)) and (probes >= reProbeLimit or key.isTomb): if key.isTomb: echo("Key is Tombstone") #if probes >= reProbeLimit: echo("Too much probing " & $probes) @@ -379,22 +379,22 @@ proc setVal[K,V](table: var PConcTable[K,V], key: int, val: int, #create next bigger table nextTable = resize(table) #help do some copying - #echo("help copy old table to new") - nextTable = helpCopy(table) + #echo("help copy old table to new") + nextTable = helpCopy(table) #now setVal in the new table instead - #echo("jumping to next table to set val") - return setVal(nextTable, key, val, expVal, match) + #echo("jumping to next table to set val") + return setVal(nextTable, key, val, expVal, match) else: idx += 1 probes += 1 # Done spinning for a new slot - var oldVal = atomic_load_n(table[idx].value.addr, ATOMIC_RELAXED) + var oldVal = atomic_load_n(table[idx].value.addr, ATOMIC_RELAXED) if val == oldVal: - #echo("this val is alredy in the slot") + #echo("this val is alredy in the slot") return oldVal - nextTable = atomic_load_n(table.next.addr, ATOMIC_SEQ_CST) - if nextTable == nil and - ((oldVal == 0 and + nextTable = atomic_load_n(table.next.addr, ATOMIC_SEQ_CST) + if nextTable == nil and + ((oldVal == 0 and (probes >= reProbeLimit or table.used / table.len > 0.8)) or (isPrime(oldVal))): if table.used / table.len > 0.8: echo("resize because usage ratio = " & @@ -402,7 +402,7 @@ proc setVal[K,V](table: var PConcTable[K,V], key: int, val: int, if isPrime(oldVal): echo("old val isPrime, should be a rare mem ordering event") nextTable = resize(table) if nextTable != nil: - #echo("tomb old slot then set in new table") + #echo("tomb old slot then set in new table") nextTable = copySlotAndCheck(table,idx) return setVal(nextTable, key, val, expVal, match) # Finally ready to add new val to table @@ -410,7 +410,7 @@ proc setVal[K,V](table: var PConcTable[K,V], key: int, val: int, if match and oldVal != expVal: #echo("set failed, no match oldVal= " & $oldVal & " expVal= " & $expVal) return oldVal - if atomic_compare_exchange_n(table[idx].value.addr, oldVal.addr, + if atomic_compare_exchange_n(table[idx].value.addr, oldVal.addr, val, false, ATOMIC_RELEASE, ATOMIC_RELAXED): #echo("val set at table " & $cast[int](table)) if expVal != 0: @@ -427,48 +427,48 @@ proc setVal[K,V](table: var PConcTable[K,V], key: int, val: int, #------------------------------------------------------------------------------ -proc getVal[K,V](table: var PConcTable[K,V], key: int): int = +proc getVal[K,V](table: var PConcTable[K,V], key: int): int = #echo("-try get- key = " & $key) - when K is Raw: + when K is Raw: var idx = hashInt(key) else: - var idx = popPtr[K](key)[].hash - #echo("get idx ", idx) - var + var idx = popPtr[K](key)[].hash + #echo("get idx ", idx) + var probes = 0 - val: int + val: int while true: - idx = idx and (table.len - 1) - var + idx = idx and (table.len - 1) + var newTable: PConcTable[K,V] # = atomic_load_n(table.next.addr, ATOMIC_ACQUIRE) - probedKey = atomic_load_n(table[idx].key.addr, ATOMIC_SEQ_CST) + probedKey = atomic_load_n(table[idx].key.addr, ATOMIC_SEQ_CST) if keyEQ[K](probedKey, key): #echo("found key after ", probes+1) val = atomic_load_n(table[idx].value.addr, ATOMIC_ACQUIRE) if not isPrime(val): if isTomb(val): - #echo("val was tomb but not prime") + #echo("val was tomb but not prime") return 0 else: - #echo("-GotIt- idx = ", idx, " key = ", key, " val ", val ) + #echo("-GotIt- idx = ", idx, " key = ", key, " val ", val ) return val else: newTable = copySlotAndCheck(table, idx) - return getVal(newTable, key) + return getVal(newTable, key) else: - #echo("probe ", probes, " idx = ", idx, " key = ", key, " found ", probedKey ) + #echo("probe ", probes, " idx = ", idx, " key = ", key, " found ", probedKey ) if probes >= reProbeLimit*4 or key.isTomb: if newTable == nil: #echo("too many probes and no new table ", key, " ", idx ) return 0 - else: + else: newTable = helpCopy(table) return getVal(newTable, key) idx += 1 probes += 1 #------------------------------------------------------------------------------ - + #proc set*(table: var PConcTable[Raw,Raw], key: Raw, val: Raw) = # discard setVal(table, pack(key), pack(key), 0, false) @@ -476,33 +476,34 @@ proc getVal[K,V](table: var PConcTable[K,V], key: int): int = # discard setVal(table, pack(key), cast[int](val), 0, false) proc set*[K,V](table: var PConcTable[K,V], key: var K, val: var V) = - when not (K is Raw): + when not (K is Raw): var newKey = cast[int](copyShared(key)) - else: + else: var newKey = pack(key) - when not (V is Raw): + when not (V is Raw): var newVal = cast[int](copyShared(val)) - else: + else: var newVal = pack(val) var oldPtr = pop(setVal(table, newKey, newVal, 0, false)) #echo("oldPtr = ", cast[int](oldPtr), " newPtr = ", cast[int](newPtr)) - when not (V is Raw): - if newVal != oldPtr and oldPtr != 0: + when not (V is Raw): + if newVal != oldPtr and oldPtr != 0: deallocShared(cast[ptr V](oldPtr)) - - + + proc get*[K,V](table: var PConcTable[K,V], key: var K): V = when not (V is Raw): when not (K is Raw): return popPtr[V](getVal(table, cast[int](key.addr)))[] - else: + else: return popPtr[V](getVal(table, pack(key)))[] else: when not (K is Raw): return popRaw(getVal(table, cast[int](key.addr))) - else: - return popRaw(getVal(table, pack(key))) + else: + return popRaw(getVal(table, pack(key))) + @@ -512,7 +513,6 @@ proc get*[K,V](table: var PConcTable[K,V], key: var K): V = - #proc `[]`[K,V](table: var PConcTable[K,V], key: K): PEntry[K,V] {.inline.} = # getVal(table, key) @@ -528,16 +528,16 @@ proc get*[K,V](table: var PConcTable[K,V], key: var K): V = #Tests ---------------------------- when not defined(testing) and isMainModule: import locks, times, mersenne - - const + + const numTests = 100000 numThreads = 10 - + type TestObj = tuple - thr: int + thr: int f0: int f1: int @@ -545,63 +545,63 @@ when not defined(testing) and isMainModule: PDataArr = array[0..numTests-1, Data] Dict = PConcTable[string,TestObj] {.deprecated: [TTestObj: TestObj, TData: Data].} - - var + + var thr: array[0..numThreads-1, Thread[Dict]] - - table = newLFTable[string,TestObj](8) + + table = newLFTable[string,TestObj](8) rand = newMersenneTwister(2525) - proc createSampleData(len: int): PDataArr = - #result = cast[PDataArr](allocShared0(sizeof(Data)*numTests)) + proc createSampleData(len: int): PDataArr = + #result = cast[PDataArr](allocShared0(sizeof(Data)*numTests)) for i in 0..len-1: result[i].k = "mark" & $(i+1) - #echo("mark" & $(i+1), " ", hash("mark" & $(i+1))) + #echo("mark" & $(i+1), " ", hash("mark" & $(i+1))) result[i].v.thr = 0 - result[i].v.f0 = i+1 - result[i].v.f1 = 0 + result[i].v.f0 = i+1 + result[i].v.f1 = 0 #echo("key = " & $(i+1) & " Val ptr = " & $cast[int](result[i].v.addr)) - proc threadProc(tp: Dict) {.thread.} = - var t = cpuTime(); + proc threadProc(tp: Dict) {.thread.} = + var t = cpuTime(); for i in 1..numTests: var key = "mark" & $(i) - var got = table.get(key) + var got = table.get(key) got.thr = cast[int](myThreadID[pointer]()) - got.f1 = got.f1 + 1 + got.f1 = got.f1 + 1 table.set(key, got) t = cpuTime() - t - echo t - + echo t + var testData = createSampleData(numTests) for i in 0..numTests-1: table.set(testData[i].k, testData[i].v) - + var i = 0 while i < numThreads: createThread(thr[i], threadProc, table) i += 1 - joinThreads(thr) + joinThreads(thr) + - var fails = 0 - for i in 0..numTests-1: - var got = table.get(testData[i].k) + for i in 0..numTests-1: + var got = table.get(testData[i].k) if got.f0 != i+1 or got.f1 != numThreads: fails += 1 echo(got) echo("Failed read or write = ", fails) - + #for i in 1..numTests: # echo(i, " = ", hashInt(i) and 8191) diff --git a/lib/pure/collections/critbits.nim b/lib/pure/collections/critbits.nim index 7e3f23851..424bcdcca 100644 --- a/lib/pure/collections/critbits.nim +++ b/lib/pure/collections/critbits.nim @@ -17,11 +17,11 @@ type otherbits: char case isLeaf: bool of false: child: array[0..1, ref NodeObj[T]] - of true: + of true: key: string when T isnot void: val: T - + Node[T] = ref NodeObj[T] CritBitTree*[T] = object ## The crit bit tree can either be used ## as a mapping from strings to @@ -66,7 +66,7 @@ proc rawInsert[T](c: var CritBitTree[T], key: string): Node[T] = let ch = if it.byte < key.len: key[it.byte] else: '\0' let dir = (1 + (ch.ord or it.otherBits.ord)) shr 8 it = it.child[dir] - + var newOtherBits = 0 var newByte = 0 block blockX: @@ -84,7 +84,7 @@ proc rawInsert[T](c: var CritBitTree[T], key: string): Node[T] = newOtherBits = newOtherBits xor 255 let ch = it.key[newByte] let dir = (1 + (ord(ch) or newOtherBits)) shr 8 - + var inner: Node[T] new inner new result @@ -93,7 +93,7 @@ proc rawInsert[T](c: var CritBitTree[T], key: string): Node[T] = inner.otherBits = chr(newOtherBits) inner.byte = newByte inner.child[1 - dir] = result - + var wherep = addr(c.root) while true: var p = wherep[] @@ -176,7 +176,7 @@ iterator leaves[T](n: Node[T]): Node[T] = # XXX actually we could compute the necessary stack size in advance: # it's roughly log2(c.count). var stack = @[n] - while stack.len > 0: + while stack.len > 0: var it = stack.pop while not it.isLeaf: stack.add(it.child[1]) @@ -205,7 +205,7 @@ iterator items*[T](c: CritBitTree[T]): string = iterator pairs*[T](c: CritBitTree[T]): tuple[key: string, val: T] = ## yields all (key, value)-pairs of `c`. for x in leaves(c.root): yield (x.key, x.val) - + iterator mpairs*[T](c: var CritBitTree[T]): tuple[key: string, val: var T] = ## yields all (key, value)-pairs of `c`. The yielded values can be modified. for x in leaves(c.root): yield (x.key, x.val) @@ -251,7 +251,7 @@ iterator pairsWithPrefix*[T](c: CritBitTree[T], ## yields all (key, value)-pairs of `c` starting with `prefix`. let top = allprefixedAux(c, prefix) for x in leaves(top): yield (x.key, x.val) - + iterator mpairsWithPrefix*[T](c: var CritBitTree[T], prefix: string): tuple[key: string, val: var T] = ## yields all (key, value)-pairs of `c` starting with `prefix`. diff --git a/lib/pure/collections/lists.nim b/lib/pure/collections/lists.nim index 535d5e21d..f847ddd58 100644 --- a/lib/pure/collections/lists.nim +++ b/lib/pure/collections/lists.nim @@ -27,18 +27,18 @@ type SinglyLinkedList*[T] = object ## a singly linked list head*, tail*: SinglyLinkedNode[T] - + DoublyLinkedList*[T] = object ## a doubly linked list head*, tail*: DoublyLinkedNode[T] SinglyLinkedRing*[T] = object ## a singly linked ring head*, tail*: SinglyLinkedNode[T] - + DoublyLinkedRing*[T] = object ## a doubly linked ring head*: DoublyLinkedNode[T] {.deprecated: [TDoublyLinkedNode: DoublyLinkedNodeObj, - PDoublyLinkedNode: DoublyLinkedNode, + PDoublyLinkedNode: DoublyLinkedNode, TSinglyLinkedNode: SinglyLinkedNodeObj, PSinglyLinkedNode: SinglyLinkedNode, TDoublyLinkedList: DoublyLinkedList, @@ -106,19 +106,19 @@ template findImpl() {.dirty.} = for x in nodes(L): if x.value == value: return x -iterator items*[T](L: DoublyLinkedList[T]): T = +iterator items*[T](L: DoublyLinkedList[T]): T = ## yields every value of `L`. itemsListImpl() -iterator items*[T](L: SinglyLinkedList[T]): T = +iterator items*[T](L: SinglyLinkedList[T]): T = ## yields every value of `L`. itemsListImpl() -iterator items*[T](L: SinglyLinkedRing[T]): T = +iterator items*[T](L: SinglyLinkedRing[T]): T = ## yields every value of `L`. itemsRingImpl() -iterator items*[T](L: DoublyLinkedRing[T]): T = +iterator items*[T](L: DoublyLinkedRing[T]): T = ## yields every value of `L`. itemsRingImpl() @@ -138,22 +138,22 @@ iterator mitems*[T](L: var DoublyLinkedRing[T]): var T = ## yields every value of `L` so that you can modify it. itemsRingImpl() -iterator nodes*[T](L: SinglyLinkedList[T]): SinglyLinkedNode[T] = +iterator nodes*[T](L: SinglyLinkedList[T]): SinglyLinkedNode[T] = ## iterates over every node of `x`. Removing the current node from the ## list during traversal is supported. nodesListImpl() -iterator nodes*[T](L: DoublyLinkedList[T]): DoublyLinkedNode[T] = +iterator nodes*[T](L: DoublyLinkedList[T]): DoublyLinkedNode[T] = ## iterates over every node of `x`. Removing the current node from the ## list during traversal is supported. nodesListImpl() -iterator nodes*[T](L: SinglyLinkedRing[T]): SinglyLinkedNode[T] = +iterator nodes*[T](L: SinglyLinkedRing[T]): SinglyLinkedNode[T] = ## iterates over every node of `x`. Removing the current node from the ## list during traversal is supported. nodesRingImpl() -iterator nodes*[T](L: DoublyLinkedRing[T]): DoublyLinkedNode[T] = +iterator nodes*[T](L: DoublyLinkedRing[T]): DoublyLinkedNode[T] = ## iterates over every node of `x`. Removing the current node from the ## list during traversal is supported. nodesRingImpl() @@ -165,87 +165,87 @@ template dollarImpl() {.dirty.} = result.add($x.value) result.add("]") -proc `$`*[T](L: SinglyLinkedList[T]): string = +proc `$`*[T](L: SinglyLinkedList[T]): string = ## turns a list into its string representation. dollarImpl() -proc `$`*[T](L: DoublyLinkedList[T]): string = +proc `$`*[T](L: DoublyLinkedList[T]): string = ## turns a list into its string representation. dollarImpl() -proc `$`*[T](L: SinglyLinkedRing[T]): string = +proc `$`*[T](L: SinglyLinkedRing[T]): string = ## turns a list into its string representation. dollarImpl() -proc `$`*[T](L: DoublyLinkedRing[T]): string = +proc `$`*[T](L: DoublyLinkedRing[T]): string = ## turns a list into its string representation. dollarImpl() -proc find*[T](L: SinglyLinkedList[T], value: T): SinglyLinkedNode[T] = +proc find*[T](L: SinglyLinkedList[T], value: T): SinglyLinkedNode[T] = ## searches in the list for a value. Returns nil if the value does not ## exist. findImpl() -proc find*[T](L: DoublyLinkedList[T], value: T): DoublyLinkedNode[T] = +proc find*[T](L: DoublyLinkedList[T], value: T): DoublyLinkedNode[T] = ## searches in the list for a value. Returns nil if the value does not ## exist. findImpl() -proc find*[T](L: SinglyLinkedRing[T], value: T): SinglyLinkedNode[T] = +proc find*[T](L: SinglyLinkedRing[T], value: T): SinglyLinkedNode[T] = ## searches in the list for a value. Returns nil if the value does not ## exist. findImpl() -proc find*[T](L: DoublyLinkedRing[T], value: T): DoublyLinkedNode[T] = +proc find*[T](L: DoublyLinkedRing[T], value: T): DoublyLinkedNode[T] = ## searches in the list for a value. Returns nil if the value does not ## exist. findImpl() -proc contains*[T](L: SinglyLinkedList[T], value: T): bool {.inline.} = +proc contains*[T](L: SinglyLinkedList[T], value: T): bool {.inline.} = ## searches in the list for a value. Returns false if the value does not ## exist, true otherwise. result = find(L, value) != nil -proc contains*[T](L: DoublyLinkedList[T], value: T): bool {.inline.} = +proc contains*[T](L: DoublyLinkedList[T], value: T): bool {.inline.} = ## searches in the list for a value. Returns false if the value does not ## exist, true otherwise. result = find(L, value) != nil -proc contains*[T](L: SinglyLinkedRing[T], value: T): bool {.inline.} = +proc contains*[T](L: SinglyLinkedRing[T], value: T): bool {.inline.} = ## searches in the list for a value. Returns false if the value does not ## exist, true otherwise. result = find(L, value) != nil -proc contains*[T](L: DoublyLinkedRing[T], value: T): bool {.inline.} = +proc contains*[T](L: DoublyLinkedRing[T], value: T): bool {.inline.} = ## searches in the list for a value. Returns false if the value does not ## exist, true otherwise. result = find(L, value) != nil -proc prepend*[T](L: var SinglyLinkedList[T], - n: SinglyLinkedNode[T]) {.inline.} = +proc prepend*[T](L: var SinglyLinkedList[T], + n: SinglyLinkedNode[T]) {.inline.} = ## prepends a node to `L`. Efficiency: O(1). n.next = L.head L.head = n -proc prepend*[T](L: var SinglyLinkedList[T], value: T) {.inline.} = +proc prepend*[T](L: var SinglyLinkedList[T], value: T) {.inline.} = ## prepends a node to `L`. Efficiency: O(1). prepend(L, newSinglyLinkedNode(value)) - -proc append*[T](L: var DoublyLinkedList[T], n: DoublyLinkedNode[T]) = + +proc append*[T](L: var DoublyLinkedList[T], n: DoublyLinkedNode[T]) = ## appends a node `n` to `L`. Efficiency: O(1). n.next = nil n.prev = L.tail - if L.tail != nil: + if L.tail != nil: assert(L.tail.next == nil) L.tail.next = n L.tail = n if L.head == nil: L.head = n -proc append*[T](L: var DoublyLinkedList[T], value: T) = +proc append*[T](L: var DoublyLinkedList[T], value: T) = ## appends a value to `L`. Efficiency: O(1). append(L, newDoublyLinkedNode(value)) -proc prepend*[T](L: var DoublyLinkedList[T], n: DoublyLinkedNode[T]) = +proc prepend*[T](L: var DoublyLinkedList[T], n: DoublyLinkedNode[T]) = ## prepends a node `n` to `L`. Efficiency: O(1). n.prev = nil n.next = L.head @@ -255,11 +255,11 @@ proc prepend*[T](L: var DoublyLinkedList[T], n: DoublyLinkedNode[T]) = L.head = n if L.tail == nil: L.tail = n -proc prepend*[T](L: var DoublyLinkedList[T], value: T) = +proc prepend*[T](L: var DoublyLinkedList[T], value: T) = ## prepends a value to `L`. Efficiency: O(1). prepend(L, newDoublyLinkedNode(value)) - -proc remove*[T](L: var DoublyLinkedList[T], n: DoublyLinkedNode[T]) = + +proc remove*[T](L: var DoublyLinkedList[T], n: DoublyLinkedNode[T]) = ## removes `n` from `L`. Efficiency: O(1). if n == L.tail: L.tail = n.prev if n == L.head: L.head = n.next @@ -267,7 +267,7 @@ proc remove*[T](L: var DoublyLinkedList[T], n: DoublyLinkedNode[T]) = if n.prev != nil: n.prev.next = n.next -proc append*[T](L: var SinglyLinkedRing[T], n: SinglyLinkedNode[T]) = +proc append*[T](L: var SinglyLinkedRing[T], n: SinglyLinkedNode[T]) = ## appends a node `n` to `L`. Efficiency: O(1). if L.head != nil: n.next = L.head @@ -279,11 +279,11 @@ proc append*[T](L: var SinglyLinkedRing[T], n: SinglyLinkedNode[T]) = L.head = n L.tail = n -proc append*[T](L: var SinglyLinkedRing[T], value: T) = +proc append*[T](L: var SinglyLinkedRing[T], value: T) = ## appends a value to `L`. Efficiency: O(1). append(L, newSinglyLinkedNode(value)) -proc prepend*[T](L: var SinglyLinkedRing[T], n: SinglyLinkedNode[T]) = +proc prepend*[T](L: var SinglyLinkedRing[T], n: SinglyLinkedNode[T]) = ## prepends a node `n` to `L`. Efficiency: O(1). if L.head != nil: n.next = L.head @@ -294,11 +294,11 @@ proc prepend*[T](L: var SinglyLinkedRing[T], n: SinglyLinkedNode[T]) = L.tail = n L.head = n -proc prepend*[T](L: var SinglyLinkedRing[T], value: T) = +proc prepend*[T](L: var SinglyLinkedRing[T], value: T) = ## prepends a value to `L`. Efficiency: O(1). prepend(L, newSinglyLinkedNode(value)) -proc append*[T](L: var DoublyLinkedRing[T], n: DoublyLinkedNode[T]) = +proc append*[T](L: var DoublyLinkedRing[T], n: DoublyLinkedNode[T]) = ## appends a node `n` to `L`. Efficiency: O(1). if L.head != nil: n.next = L.head @@ -310,13 +310,13 @@ proc append*[T](L: var DoublyLinkedRing[T], n: DoublyLinkedNode[T]) = n.next = n L.head = n -proc append*[T](L: var DoublyLinkedRing[T], value: T) = +proc append*[T](L: var DoublyLinkedRing[T], value: T) = ## appends a value to `L`. Efficiency: O(1). append(L, newDoublyLinkedNode(value)) -proc prepend*[T](L: var DoublyLinkedRing[T], n: DoublyLinkedNode[T]) = +proc prepend*[T](L: var DoublyLinkedRing[T], n: DoublyLinkedNode[T]) = ## prepends a node `n` to `L`. Efficiency: O(1). - if L.head != nil: + if L.head != nil: n.next = L.head n.prev = L.head.prev L.head.prev.next = n @@ -326,17 +326,17 @@ proc prepend*[T](L: var DoublyLinkedRing[T], n: DoublyLinkedNode[T]) = n.next = n L.head = n -proc prepend*[T](L: var DoublyLinkedRing[T], value: T) = +proc prepend*[T](L: var DoublyLinkedRing[T], value: T) = ## prepends a value to `L`. Efficiency: O(1). prepend(L, newDoublyLinkedNode(value)) - -proc remove*[T](L: var DoublyLinkedRing[T], n: DoublyLinkedNode[T]) = + +proc remove*[T](L: var DoublyLinkedRing[T], n: DoublyLinkedNode[T]) = ## removes `n` from `L`. Efficiency: O(1). n.next.prev = n.prev n.prev.next = n.next - if n == L.head: + if n == L.head: var p = L.head.prev - if p == L.head: + if p == L.head: # only one element left: L.head = nil else: diff --git a/lib/pure/collections/queues.nim b/lib/pure/collections/queues.nim index af5e7b6cd..c35a2dc29 100644 --- a/lib/pure/collections/queues.nim +++ b/lib/pure/collections/queues.nim @@ -77,7 +77,7 @@ proc dequeue*[T](q: var Queue[T]): T = result = q.data[q.rd] q.rd = (q.rd + 1) and q.mask -proc `$`*[T](q: Queue[T]): string = +proc `$`*[T](q: Queue[T]): string = ## turns a queue into its string representation. result = "[" for x in items(q): @@ -95,7 +95,7 @@ when isMainModule: q.add(6) var second = q.dequeue q.add(789) - + assert first == 123 assert second == 9 assert($q == "[4, 56, 6, 789]") diff --git a/lib/pure/colors.nim b/lib/pure/colors.nim index f24cc0072..7328f7c24 100644 --- a/lib/pure/colors.nim +++ b/lib/pure/colors.nim @@ -6,7 +6,7 @@ # distribution, for details about the copyright. # -## This module implements color handling for Nimrod. It is used by +## This module implements color handling for Nimrod. It is used by ## the ``graphics`` module. import strutils @@ -18,15 +18,15 @@ type proc `==` *(a, b: Color): bool {.borrow.} ## compares two colors. - + template extract(a: Color, r, g, b: expr) {.immediate.}= var r = a.int shr 16 and 0xff var g = a.int shr 8 and 0xff var b = a.int and 0xff - + template rawRGB(r, g, b: int): expr = Color(r shl 16 or g shl 8 or b) - + template colorOp(op: expr) {.immediate.} = extract(a, ar, ag, ab) extract(b, br, bg, bb) @@ -39,24 +39,24 @@ proc satPlus(a, b: int): int {.inline.} = proc satMinus(a, b: int): int {.inline.} = result = a -% b if result < 0: result = 0 - + proc `+`*(a, b: Color): Color = ## adds two colors: This uses saturated artithmetic, so that each color ## component cannot overflow (255 is used as a maximum). colorOp(satPlus) - + proc `-`*(a, b: Color): Color = ## subtracts two colors: This uses saturated artithmetic, so that each color ## component cannot overflow (255 is used as a maximum). colorOp(satMinus) - + proc extractRGB*(a: Color): tuple[r, g, b: range[0..255]] = ## extracts the red/green/blue components of the color `a`. result.r = a.int shr 16 and 0xff result.g = a.int shr 8 and 0xff result.b = a.int and 0xff - -proc intensity*(a: Color, f: float): Color = + +proc intensity*(a: Color, f: float): Color = ## returns `a` with intensity `f`. `f` should be a float from 0.0 (completely ## dark) to 1.0 (full color intensity). var r = toInt(toFloat(a.int shr 16 and 0xff) * f) @@ -66,7 +66,7 @@ proc intensity*(a: Color, f: float): Color = if g >% 255: g = 255 if b >% 255: b = 255 result = rawRGB(r, g, b) - + template mix*(a, b: Color, fn: expr): expr = ## uses `fn` to mix the colors `a` and `b`. `fn` is invoked for each component ## R, G, and B. This is a template because `fn` should be inlined and the @@ -79,7 +79,7 @@ template mix*(a, b: Color, fn: expr): expr = if y >% 255: y = if y < 0: 0 else: 255 y - + (bind extract)(a, ar, ag, ab) (bind extract)(b, br, bg, bb) (bind rawRGB)(> 0: b = mid - 1 else: return mid result = - 1 - -proc parseColor*(name: string): Color = - ## parses `name` to a color value. If no valid color could be + +proc parseColor*(name: string): Color = + ## parses `name` to a color value. If no valid color could be ## parsed ``EInvalidValue`` is raised. if name[0] == '#': result = Color(parseHexInt(name)) @@ -396,10 +396,10 @@ proc parseColor*(name: string): Color = result = colorNames[idx][1] proc isColor*(name: string): bool = - ## returns true if `name` is a known color name or a hexadecimal color + ## returns true if `name` is a known color name or a hexadecimal color ## prefixed with ``#``. - if name[0] == '#': - for i in 1 .. name.len-1: + if name[0] == '#': + for i in 1 .. name.len-1: if name[i] notin {'0'..'9', 'a'..'f', 'A'..'F'}: return false result = true else: diff --git a/lib/pure/complex.nim b/lib/pure/complex.nim index 8577bf7a1..ccde5ee0a 100644 --- a/lib/pure/complex.nim +++ b/lib/pure/complex.nim @@ -17,7 +17,7 @@ import math - + const EPS = 1.0e-7 ## Epsilon used for float comparisons. @@ -248,7 +248,7 @@ proc pow*(x, y: Complex): Complex = var r = y.re*theta + y.im*ln(rho) result.re = s*cos(r) result.im = s*sin(r) - + proc sin*(z: Complex): Complex = ## Returns the sine of `z`. @@ -387,7 +387,7 @@ when isMainModule: var one = (1.0,0.0) var tt = (10.0, 20.0) var ipi = (0.0, -PI) - + assert( a == a ) assert( (a-a) == z ) assert( (a+b) == z ) @@ -403,7 +403,7 @@ when isMainModule: assert( conjugate(a) == (1.0, -2.0) ) assert( sqrt(m1) == i ) assert( exp(ipi) =~ m1 ) - + assert( pow(a,b) =~ (-3.72999124927876, -1.68815826725068) ) assert( pow(z,a) =~ (0.0, 0.0) ) assert( pow(z,z) =~ (1.0, 0.0) ) diff --git a/lib/pure/concurrency/cpuinfo.nim b/lib/pure/concurrency/cpuinfo.nim index 6f2bc4491..8c87c77df 100644 --- a/lib/pure/concurrency/cpuinfo.nim +++ b/lib/pure/concurrency/cpuinfo.nim @@ -18,7 +18,7 @@ when not defined(windows): when defined(linux): import linux - + when defined(freebsd) or defined(macosx): {.emit:"#include ".} diff --git a/lib/pure/cookies.nim b/lib/pure/cookies.nim index 9983c4a04..8090cd49d 100644 --- a/lib/pure/cookies.nim +++ b/lib/pure/cookies.nim @@ -11,7 +11,7 @@ import strtabs, times -proc parseCookies*(s: string): StringTableRef = +proc parseCookies*(s: string): StringTableRef = ## parses cookies into a string table. result = newStringTable(modeCaseInsensitive) var i = 0 @@ -31,7 +31,7 @@ proc parseCookies*(s: string): StringTableRef = proc setCookie*(key, value: string, domain = "", path = "", expires = "", noName = false, secure = false, httpOnly = false): string = - ## Creates a command in the format of + ## Creates a command in the format of ## ``Set-Cookie: key=value; Domain=...; ...`` result = "" if not noName: result.add("Set-Cookie: ") @@ -45,10 +45,10 @@ proc setCookie*(key, value: string, domain = "", path = "", proc setCookie*(key, value: string, expires: TimeInfo, domain = "", path = "", noName = false, secure = false, httpOnly = false): string = - ## Creates a command in the format of + ## Creates a command in the format of ## ``Set-Cookie: key=value; Domain=...; ...`` ## - ## **Note:** UTC is assumed as the timezone for ``expires``. + ## **Note:** UTC is assumed as the timezone for ``expires``. return setCookie(key, value, domain, path, format(expires, "ddd',' dd MMM yyyy HH:mm:ss 'UTC'"), noname, secure, httpOnly) @@ -61,7 +61,7 @@ when isMainModule: echo cookie let start = "Set-Cookie: test=value; Expires=" assert cookie[0..start.high] == start - + let table = parseCookies("uid=1; kp=2") assert table["uid"] == "1" assert table["kp"] == "2" diff --git a/lib/pure/encodings.nim b/lib/pure/encodings.nim index e427b585d..2d305ea42 100644 --- a/lib/pure/encodings.nim +++ b/lib/pure/encodings.nim @@ -7,7 +7,7 @@ # distribution, for details about the copyright. # -## Converts between different character encodings. On UNIX, this uses +## Converts between different character encodings. On UNIX, this uses ## the `iconv`:idx: library, on Windows the Windows API. import os, parseutils, strutils @@ -41,173 +41,173 @@ when defined(windows): inc j result = i == a.len and j == b.len - const + const winEncodings = [ (1, "OEMCP"), # current OEM codepage - (037, "IBM037"), # IBM EBCDIC US-Canada - (437, "IBM437"), # OEM United States - (500, "IBM500"), # IBM EBCDIC International - (708, "ASMO-708"), # Arabic (ASMO 708) - (709, "ASMO_449"), # Arabic (ASMO-449+, BCON V4) - (710, ""), # Arabic - Transparent Arabic - (720, "DOS-720"), # Arabic (Transparent ASMO); Arabic (DOS) - (737, "ibm737"), # OEM Greek (formerly 437G); Greek (DOS) - (775, "ibm775"), # OEM Baltic; Baltic (DOS) - (850, "ibm850"), # OEM Multilingual Latin 1; Western European (DOS) - (852, "ibm852"), # OEM Latin 2; Central European (DOS) - (855, "IBM855"), # OEM Cyrillic (primarily Russian) - (857, "ibm857"), # OEM Turkish; Turkish (DOS) - (858, "IBM00858"), # OEM Multilingual Latin 1 + Euro symbol - (860, "IBM860"), # OEM Portuguese; Portuguese (DOS) - (861, "ibm861"), # OEM Icelandic; Icelandic (DOS) - (862, "DOS-862"), # OEM Hebrew; Hebrew (DOS) - (863, "IBM863"), # OEM French Canadian; French Canadian (DOS) - (864, "IBM864"), # OEM Arabic; Arabic (864) - (865, "IBM865"), # OEM Nordic; Nordic (DOS) - (866, "cp866"), # OEM Russian; Cyrillic (DOS) - (869, "ibm869"), # OEM Modern Greek; Greek, Modern (DOS) - (870, "IBM870"), # IBM EBCDIC Multilingual/ROECE (Latin 2); IBM EBCDIC Multilingual Latin 2 - (874, "windows-874"), # ANSI/OEM Thai (same as 28605, ISO 8859-15); Thai (Windows) - (875, "cp875"), # IBM EBCDIC Greek Modern - (932, "shift_jis"), # ANSI/OEM Japanese; Japanese (Shift-JIS) - (936, "gb2312"), # ANSI/OEM Simplified Chinese (PRC, Singapore); Chinese Simplified (GB2312) - (949, "ks_c_5601-1987"), # ANSI/OEM Korean (Unified Hangul Code) - (950, "big5"), # ANSI/OEM Traditional Chinese (Taiwan; Hong Kong SAR, PRC); Chinese Traditional (Big5) - (1026, "IBM1026"), # IBM EBCDIC Turkish (Latin 5) - (1047, "IBM01047"), # IBM EBCDIC Latin 1/Open System - (1140, "IBM01140"), # IBM EBCDIC US-Canada (037 + Euro symbol); IBM EBCDIC (US-Canada-Euro) - (1141, "IBM01141"), # IBM EBCDIC Germany (20273 + Euro symbol); IBM EBCDIC (Germany-Euro) - (1142, "IBM01142"), # IBM EBCDIC Denmark-Norway (20277 + Euro symbol); IBM EBCDIC (Denmark-Norway-Euro) - (1143, "IBM01143"), # IBM EBCDIC Finland-Sweden (20278 + Euro symbol); IBM EBCDIC (Finland-Sweden-Euro) - (1144, "IBM01144"), # IBM EBCDIC Italy (20280 + Euro symbol); IBM EBCDIC (Italy-Euro) - (1145, "IBM01145"), # IBM EBCDIC Latin America-Spain (20284 + Euro symbol); IBM EBCDIC (Spain-Euro) - (1146, "IBM01146"), # IBM EBCDIC United Kingdom (20285 + Euro symbol); IBM EBCDIC (UK-Euro) - (1147, "IBM01147"), # IBM EBCDIC France (20297 + Euro symbol); IBM EBCDIC (France-Euro) - (1148, "IBM01148"), # IBM EBCDIC International (500 + Euro symbol); IBM EBCDIC (International-Euro) - (1149, "IBM01149"), # IBM EBCDIC Icelandic (20871 + Euro symbol); IBM EBCDIC (Icelandic-Euro) - (1200, "utf-16"), # Unicode UTF-16, little endian byte order (BMP of ISO 10646); available only to managed applications - (1201, "unicodeFFFE"), # Unicode UTF-16, big endian byte order; available only to managed applications - (1250, "windows-1250"), # ANSI Central European; Central European (Windows) - (1251, "windows-1251"), # ANSI Cyrillic; Cyrillic (Windows) - (1252, "windows-1252"), # ANSI Latin 1; Western European (Windows) - (1253, "windows-1253"), # ANSI Greek; Greek (Windows) - (1254, "windows-1254"), # ANSI Turkish; Turkish (Windows) - (1255, "windows-1255"), # ANSI Hebrew; Hebrew (Windows) - (1256, "windows-1256"), # ANSI Arabic; Arabic (Windows) - (1257, "windows-1257"), # ANSI Baltic; Baltic (Windows) - (1258, "windows-1258"), # ANSI/OEM Vietnamese; Vietnamese (Windows) + (037, "IBM037"), # IBM EBCDIC US-Canada + (437, "IBM437"), # OEM United States + (500, "IBM500"), # IBM EBCDIC International + (708, "ASMO-708"), # Arabic (ASMO 708) + (709, "ASMO_449"), # Arabic (ASMO-449+, BCON V4) + (710, ""), # Arabic - Transparent Arabic + (720, "DOS-720"), # Arabic (Transparent ASMO); Arabic (DOS) + (737, "ibm737"), # OEM Greek (formerly 437G); Greek (DOS) + (775, "ibm775"), # OEM Baltic; Baltic (DOS) + (850, "ibm850"), # OEM Multilingual Latin 1; Western European (DOS) + (852, "ibm852"), # OEM Latin 2; Central European (DOS) + (855, "IBM855"), # OEM Cyrillic (primarily Russian) + (857, "ibm857"), # OEM Turkish; Turkish (DOS) + (858, "IBM00858"), # OEM Multilingual Latin 1 + Euro symbol + (860, "IBM860"), # OEM Portuguese; Portuguese (DOS) + (861, "ibm861"), # OEM Icelandic; Icelandic (DOS) + (862, "DOS-862"), # OEM Hebrew; Hebrew (DOS) + (863, "IBM863"), # OEM French Canadian; French Canadian (DOS) + (864, "IBM864"), # OEM Arabic; Arabic (864) + (865, "IBM865"), # OEM Nordic; Nordic (DOS) + (866, "cp866"), # OEM Russian; Cyrillic (DOS) + (869, "ibm869"), # OEM Modern Greek; Greek, Modern (DOS) + (870, "IBM870"), # IBM EBCDIC Multilingual/ROECE (Latin 2); IBM EBCDIC Multilingual Latin 2 + (874, "windows-874"), # ANSI/OEM Thai (same as 28605, ISO 8859-15); Thai (Windows) + (875, "cp875"), # IBM EBCDIC Greek Modern + (932, "shift_jis"), # ANSI/OEM Japanese; Japanese (Shift-JIS) + (936, "gb2312"), # ANSI/OEM Simplified Chinese (PRC, Singapore); Chinese Simplified (GB2312) + (949, "ks_c_5601-1987"), # ANSI/OEM Korean (Unified Hangul Code) + (950, "big5"), # ANSI/OEM Traditional Chinese (Taiwan; Hong Kong SAR, PRC); Chinese Traditional (Big5) + (1026, "IBM1026"), # IBM EBCDIC Turkish (Latin 5) + (1047, "IBM01047"), # IBM EBCDIC Latin 1/Open System + (1140, "IBM01140"), # IBM EBCDIC US-Canada (037 + Euro symbol); IBM EBCDIC (US-Canada-Euro) + (1141, "IBM01141"), # IBM EBCDIC Germany (20273 + Euro symbol); IBM EBCDIC (Germany-Euro) + (1142, "IBM01142"), # IBM EBCDIC Denmark-Norway (20277 + Euro symbol); IBM EBCDIC (Denmark-Norway-Euro) + (1143, "IBM01143"), # IBM EBCDIC Finland-Sweden (20278 + Euro symbol); IBM EBCDIC (Finland-Sweden-Euro) + (1144, "IBM01144"), # IBM EBCDIC Italy (20280 + Euro symbol); IBM EBCDIC (Italy-Euro) + (1145, "IBM01145"), # IBM EBCDIC Latin America-Spain (20284 + Euro symbol); IBM EBCDIC (Spain-Euro) + (1146, "IBM01146"), # IBM EBCDIC United Kingdom (20285 + Euro symbol); IBM EBCDIC (UK-Euro) + (1147, "IBM01147"), # IBM EBCDIC France (20297 + Euro symbol); IBM EBCDIC (France-Euro) + (1148, "IBM01148"), # IBM EBCDIC International (500 + Euro symbol); IBM EBCDIC (International-Euro) + (1149, "IBM01149"), # IBM EBCDIC Icelandic (20871 + Euro symbol); IBM EBCDIC (Icelandic-Euro) + (1200, "utf-16"), # Unicode UTF-16, little endian byte order (BMP of ISO 10646); available only to managed applications + (1201, "unicodeFFFE"), # Unicode UTF-16, big endian byte order; available only to managed applications + (1250, "windows-1250"), # ANSI Central European; Central European (Windows) + (1251, "windows-1251"), # ANSI Cyrillic; Cyrillic (Windows) + (1252, "windows-1252"), # ANSI Latin 1; Western European (Windows) + (1253, "windows-1253"), # ANSI Greek; Greek (Windows) + (1254, "windows-1254"), # ANSI Turkish; Turkish (Windows) + (1255, "windows-1255"), # ANSI Hebrew; Hebrew (Windows) + (1256, "windows-1256"), # ANSI Arabic; Arabic (Windows) + (1257, "windows-1257"), # ANSI Baltic; Baltic (Windows) + (1258, "windows-1258"), # ANSI/OEM Vietnamese; Vietnamese (Windows) - (1250, "cp-1250"), # ANSI Central European; Central European (Windows) - (1251, "cp-1251"), # ANSI Cyrillic; Cyrillic (Windows) - (1252, "cp-1252"), # ANSI Latin 1; Western European (Windows) - (1253, "cp-1253"), # ANSI Greek; Greek (Windows) - (1254, "cp-1254"), # ANSI Turkish; Turkish (Windows) - (1255, "cp-1255"), # ANSI Hebrew; Hebrew (Windows) - (1256, "cp-1256"), # ANSI Arabic; Arabic (Windows) - (1257, "cp-1257"), # ANSI Baltic; Baltic (Windows) - (1258, "cp-1258"), # ANSI/OEM Vietnamese; Vietnamese (Windows) + (1250, "cp-1250"), # ANSI Central European; Central European (Windows) + (1251, "cp-1251"), # ANSI Cyrillic; Cyrillic (Windows) + (1252, "cp-1252"), # ANSI Latin 1; Western European (Windows) + (1253, "cp-1253"), # ANSI Greek; Greek (Windows) + (1254, "cp-1254"), # ANSI Turkish; Turkish (Windows) + (1255, "cp-1255"), # ANSI Hebrew; Hebrew (Windows) + (1256, "cp-1256"), # ANSI Arabic; Arabic (Windows) + (1257, "cp-1257"), # ANSI Baltic; Baltic (Windows) + (1258, "cp-1258"), # ANSI/OEM Vietnamese; Vietnamese (Windows) + + (1361, "Johab"), # Korean (Johab) + (10000, "macintosh"), # MAC Roman; Western European (Mac) + (10001, "x-mac-japanese"), # Japanese (Mac) + (10002, "x-mac-chinesetrad"), # MAC Traditional Chinese (Big5); Chinese Traditional (Mac) + (10003, "x-mac-korean"), # Korean (Mac) + (10004, "x-mac-arabic"), # Arabic (Mac) + (10005, "x-mac-hebrew"), # Hebrew (Mac) + (10006, "x-mac-greek"), # Greek (Mac) + (10007, "x-mac-cyrillic"), # Cyrillic (Mac) + (10008, "x-mac-chinesesimp"), # MAC Simplified Chinese (GB 2312); Chinese Simplified (Mac) + (10010, "x-mac-romanian"), # Romanian (Mac) + (10017, "x-mac-ukrainian"), # Ukrainian (Mac) + (10021, "x-mac-thai"), # Thai (Mac) + (10029, "x-mac-ce"), # MAC Latin 2; Central European (Mac) + (10079, "x-mac-icelandic"), # Icelandic (Mac) + (10081, "x-mac-turkish"), # Turkish (Mac) + (10082, "x-mac-croatian"), # Croatian (Mac) + (12000, "utf-32"), # Unicode UTF-32, little endian byte order; available only to managed applications + (12001, "utf-32BE"), # Unicode UTF-32, big endian byte order; available only to managed applications + (20000, "x-Chinese_CNS"), # CNS Taiwan; Chinese Traditional (CNS) + (20001, "x-cp20001"), # TCA Taiwan + (20002, "x_Chinese-Eten"), # Eten Taiwan; Chinese Traditional (Eten) + (20003, "x-cp20003"), # IBM5550 Taiwan + (20004, "x-cp20004"), # TeleText Taiwan + (20005, "x-cp20005"), # Wang Taiwan + (20105, "x-IA5"), # IA5 (IRV International Alphabet No. 5, 7-bit); Western European (IA5) + (20106, "x-IA5-German"), # IA5 German (7-bit) + (20107, "x-IA5-Swedish"), # IA5 Swedish (7-bit) + (20108, "x-IA5-Norwegian"), # IA5 Norwegian (7-bit) + (20127, "us-ascii"), # US-ASCII (7-bit) + (20261, "x-cp20261"), # T.61 + (20269, "x-cp20269"), # ISO 6937 Non-Spacing Accent + (20273, "IBM273"), # IBM EBCDIC Germany + (20277, "IBM277"), # IBM EBCDIC Denmark-Norway + (20278, "IBM278"), # IBM EBCDIC Finland-Sweden + (20280, "IBM280"), # IBM EBCDIC Italy + (20284, "IBM284"), # IBM EBCDIC Latin America-Spain + (20285, "IBM285"), # IBM EBCDIC United Kingdom + (20290, "IBM290"), # IBM EBCDIC Japanese Katakana Extended + (20297, "IBM297"), # IBM EBCDIC France + (20420, "IBM420"), # IBM EBCDIC Arabic + (20423, "IBM423"), # IBM EBCDIC Greek + (20424, "IBM424"), # IBM EBCDIC Hebrew + (20833, "x-EBCDIC-KoreanExtended"), # IBM EBCDIC Korean Extended + (20838, "IBM-Thai"), # IBM EBCDIC Thai + (20866, "koi8-r"), # Russian (KOI8-R); Cyrillic (KOI8-R) + (20871, "IBM871"), # IBM EBCDIC Icelandic + (20880, "IBM880"), # IBM EBCDIC Cyrillic Russian + (20905, "IBM905"), # IBM EBCDIC Turkish + (20924, "IBM00924"), # IBM EBCDIC Latin 1/Open System (1047 + Euro symbol) + (20932, "EUC-JP"), # Japanese (JIS 0208-1990 and 0121-1990) + (20936, "x-cp20936"), # Simplified Chinese (GB2312); Chinese Simplified (GB2312-80) + (20949, "x-cp20949"), # Korean Wansung + (21025, "cp1025"), # IBM EBCDIC Cyrillic Serbian-Bulgarian + (21027, ""), # (deprecated) + (21866, "koi8-u"), # Ukrainian (KOI8-U); Cyrillic (KOI8-U) + (28591, "iso-8859-1"), # ISO 8859-1 Latin 1; Western European (ISO) + (28592, "iso-8859-2"), # ISO 8859-2 Central European; Central European (ISO) + (28593, "iso-8859-3"), # ISO 8859-3 Latin 3 + (28594, "iso-8859-4"), # ISO 8859-4 Baltic + (28595, "iso-8859-5"), # ISO 8859-5 Cyrillic + (28596, "iso-8859-6"), # ISO 8859-6 Arabic + (28597, "iso-8859-7"), # ISO 8859-7 Greek + (28598, "iso-8859-8"), # ISO 8859-8 Hebrew; Hebrew (ISO-Visual) + (28599, "iso-8859-9"), # ISO 8859-9 Turkish + (28603, "iso-8859-13"), # ISO 8859-13 Estonian + (28605, "iso-8859-15"), # ISO 8859-15 Latin 9 + (29001, "x-Europa"), # Europa 3 + (38598, "iso-8859-8-i"), # ISO 8859-8 Hebrew; Hebrew (ISO-Logical) + (50220, "iso-2022-jp"), # ISO 2022 Japanese with no halfwidth Katakana; Japanese (JIS) + (50221, "csISO2022JP"), # ISO 2022 Japanese with halfwidth Katakana; Japanese (JIS-Allow 1 byte Kana) + (50222, "iso-2022-jp"), # ISO 2022 Japanese JIS X 0201-1989; Japanese (JIS-Allow 1 byte Kana - SO/SI) + (50225, "iso-2022-kr"), # ISO 2022 Korean + (50227, "x-cp50227"), # ISO 2022 Simplified Chinese; Chinese Simplified (ISO 2022) + (50229, ""), # ISO 2022 Traditional Chinese + (50930, ""), # EBCDIC Japanese (Katakana) Extended + (50931, ""), # EBCDIC US-Canada and Japanese + (50933, ""), # EBCDIC Korean Extended and Korean + (50935, ""), # EBCDIC Simplified Chinese Extended and Simplified Chinese + (50936, ""), # EBCDIC Simplified Chinese + (50937, ""), # EBCDIC US-Canada and Traditional Chinese + (50939, ""), # EBCDIC Japanese (Latin) Extended and Japanese + (51932, "euc-jp"), # EUC Japanese + (51936, "EUC-CN"), # EUC Simplified Chinese; Chinese Simplified (EUC) + (51949, "euc-kr"), # EUC Korean + (51950, ""), # EUC Traditional Chinese + (52936, "hz-gb-2312"), # HZ-GB2312 Simplified Chinese; Chinese Simplified (HZ) + (54936, "GB18030"), # Windows XP and later: GB18030 Simplified Chinese (4 byte); Chinese Simplified (GB18030) + (57002, "x-iscii-de"), # ISCII Devanagari + (57003, "x-iscii-be"), # ISCII Bengali + (57004, "x-iscii-ta"), # ISCII Tamil + (57005, "x-iscii-te"), # ISCII Telugu + (57006, "x-iscii-as"), # ISCII Assamese + (57007, "x-iscii-or"), # ISCII Oriya + (57008, "x-iscii-ka"), # ISCII Kannada + (57009, "x-iscii-ma"), # ISCII Malayalam + (57010, "x-iscii-gu"), # ISCII Gujarati + (57011, "x-iscii-pa"), # ISCII Punjabi + (65000, "utf-7"), # Unicode (UTF-7) + (65001, "utf-8")] # Unicode (UTF-8) - (1361, "Johab"), # Korean (Johab) - (10000, "macintosh"), # MAC Roman; Western European (Mac) - (10001, "x-mac-japanese"), # Japanese (Mac) - (10002, "x-mac-chinesetrad"), # MAC Traditional Chinese (Big5); Chinese Traditional (Mac) - (10003, "x-mac-korean"), # Korean (Mac) - (10004, "x-mac-arabic"), # Arabic (Mac) - (10005, "x-mac-hebrew"), # Hebrew (Mac) - (10006, "x-mac-greek"), # Greek (Mac) - (10007, "x-mac-cyrillic"), # Cyrillic (Mac) - (10008, "x-mac-chinesesimp"), # MAC Simplified Chinese (GB 2312); Chinese Simplified (Mac) - (10010, "x-mac-romanian"), # Romanian (Mac) - (10017, "x-mac-ukrainian"), # Ukrainian (Mac) - (10021, "x-mac-thai"), # Thai (Mac) - (10029, "x-mac-ce"), # MAC Latin 2; Central European (Mac) - (10079, "x-mac-icelandic"), # Icelandic (Mac) - (10081, "x-mac-turkish"), # Turkish (Mac) - (10082, "x-mac-croatian"), # Croatian (Mac) - (12000, "utf-32"), # Unicode UTF-32, little endian byte order; available only to managed applications - (12001, "utf-32BE"), # Unicode UTF-32, big endian byte order; available only to managed applications - (20000, "x-Chinese_CNS"), # CNS Taiwan; Chinese Traditional (CNS) - (20001, "x-cp20001"), # TCA Taiwan - (20002, "x_Chinese-Eten"), # Eten Taiwan; Chinese Traditional (Eten) - (20003, "x-cp20003"), # IBM5550 Taiwan - (20004, "x-cp20004"), # TeleText Taiwan - (20005, "x-cp20005"), # Wang Taiwan - (20105, "x-IA5"), # IA5 (IRV International Alphabet No. 5, 7-bit); Western European (IA5) - (20106, "x-IA5-German"), # IA5 German (7-bit) - (20107, "x-IA5-Swedish"), # IA5 Swedish (7-bit) - (20108, "x-IA5-Norwegian"), # IA5 Norwegian (7-bit) - (20127, "us-ascii"), # US-ASCII (7-bit) - (20261, "x-cp20261"), # T.61 - (20269, "x-cp20269"), # ISO 6937 Non-Spacing Accent - (20273, "IBM273"), # IBM EBCDIC Germany - (20277, "IBM277"), # IBM EBCDIC Denmark-Norway - (20278, "IBM278"), # IBM EBCDIC Finland-Sweden - (20280, "IBM280"), # IBM EBCDIC Italy - (20284, "IBM284"), # IBM EBCDIC Latin America-Spain - (20285, "IBM285"), # IBM EBCDIC United Kingdom - (20290, "IBM290"), # IBM EBCDIC Japanese Katakana Extended - (20297, "IBM297"), # IBM EBCDIC France - (20420, "IBM420"), # IBM EBCDIC Arabic - (20423, "IBM423"), # IBM EBCDIC Greek - (20424, "IBM424"), # IBM EBCDIC Hebrew - (20833, "x-EBCDIC-KoreanExtended"), # IBM EBCDIC Korean Extended - (20838, "IBM-Thai"), # IBM EBCDIC Thai - (20866, "koi8-r"), # Russian (KOI8-R); Cyrillic (KOI8-R) - (20871, "IBM871"), # IBM EBCDIC Icelandic - (20880, "IBM880"), # IBM EBCDIC Cyrillic Russian - (20905, "IBM905"), # IBM EBCDIC Turkish - (20924, "IBM00924"), # IBM EBCDIC Latin 1/Open System (1047 + Euro symbol) - (20932, "EUC-JP"), # Japanese (JIS 0208-1990 and 0121-1990) - (20936, "x-cp20936"), # Simplified Chinese (GB2312); Chinese Simplified (GB2312-80) - (20949, "x-cp20949"), # Korean Wansung - (21025, "cp1025"), # IBM EBCDIC Cyrillic Serbian-Bulgarian - (21027, ""), # (deprecated) - (21866, "koi8-u"), # Ukrainian (KOI8-U); Cyrillic (KOI8-U) - (28591, "iso-8859-1"), # ISO 8859-1 Latin 1; Western European (ISO) - (28592, "iso-8859-2"), # ISO 8859-2 Central European; Central European (ISO) - (28593, "iso-8859-3"), # ISO 8859-3 Latin 3 - (28594, "iso-8859-4"), # ISO 8859-4 Baltic - (28595, "iso-8859-5"), # ISO 8859-5 Cyrillic - (28596, "iso-8859-6"), # ISO 8859-6 Arabic - (28597, "iso-8859-7"), # ISO 8859-7 Greek - (28598, "iso-8859-8"), # ISO 8859-8 Hebrew; Hebrew (ISO-Visual) - (28599, "iso-8859-9"), # ISO 8859-9 Turkish - (28603, "iso-8859-13"), # ISO 8859-13 Estonian - (28605, "iso-8859-15"), # ISO 8859-15 Latin 9 - (29001, "x-Europa"), # Europa 3 - (38598, "iso-8859-8-i"), # ISO 8859-8 Hebrew; Hebrew (ISO-Logical) - (50220, "iso-2022-jp"), # ISO 2022 Japanese with no halfwidth Katakana; Japanese (JIS) - (50221, "csISO2022JP"), # ISO 2022 Japanese with halfwidth Katakana; Japanese (JIS-Allow 1 byte Kana) - (50222, "iso-2022-jp"), # ISO 2022 Japanese JIS X 0201-1989; Japanese (JIS-Allow 1 byte Kana - SO/SI) - (50225, "iso-2022-kr"), # ISO 2022 Korean - (50227, "x-cp50227"), # ISO 2022 Simplified Chinese; Chinese Simplified (ISO 2022) - (50229, ""), # ISO 2022 Traditional Chinese - (50930, ""), # EBCDIC Japanese (Katakana) Extended - (50931, ""), # EBCDIC US-Canada and Japanese - (50933, ""), # EBCDIC Korean Extended and Korean - (50935, ""), # EBCDIC Simplified Chinese Extended and Simplified Chinese - (50936, ""), # EBCDIC Simplified Chinese - (50937, ""), # EBCDIC US-Canada and Traditional Chinese - (50939, ""), # EBCDIC Japanese (Latin) Extended and Japanese - (51932, "euc-jp"), # EUC Japanese - (51936, "EUC-CN"), # EUC Simplified Chinese; Chinese Simplified (EUC) - (51949, "euc-kr"), # EUC Korean - (51950, ""), # EUC Traditional Chinese - (52936, "hz-gb-2312"), # HZ-GB2312 Simplified Chinese; Chinese Simplified (HZ) - (54936, "GB18030"), # Windows XP and later: GB18030 Simplified Chinese (4 byte); Chinese Simplified (GB18030) - (57002, "x-iscii-de"), # ISCII Devanagari - (57003, "x-iscii-be"), # ISCII Bengali - (57004, "x-iscii-ta"), # ISCII Tamil - (57005, "x-iscii-te"), # ISCII Telugu - (57006, "x-iscii-as"), # ISCII Assamese - (57007, "x-iscii-or"), # ISCII Oriya - (57008, "x-iscii-ka"), # ISCII Kannada - (57009, "x-iscii-ma"), # ISCII Malayalam - (57010, "x-iscii-gu"), # ISCII Gujarati - (57011, "x-iscii-pa"), # ISCII Punjabi - (65000, "utf-7"), # Unicode (UTF-7) - (65001, "utf-8")] # Unicode (UTF-8) - when false: # not needed yet: type @@ -219,22 +219,22 @@ when defined(windows): proc getCPInfo(codePage: CodePage, lpCPInfo: var CpInfo): int32 {. stdcall, importc: "GetCPInfo", dynlib: "kernel32".} - + proc nameToCodePage(name: string): CodePage = var nameAsInt: int if parseInt(name, nameAsInt) == 0: nameAsInt = -1 for no, na in items(winEncodings): if no == nameAsInt or eqEncodingNames(na, name): return CodePage(no) result = CodePage(-1) - + proc codePageToName(c: CodePage): string = for no, na in items(winEncodings): if no == int(c): return if na.len != 0: na else: $no result = "" - + proc getACP(): CodePage {.stdcall, importc: "GetACP", dynlib: "kernel32".} - + proc multiByteToWideChar( codePage: CodePage, dwFlags: int32, @@ -254,7 +254,7 @@ when defined(windows): lpDefaultChar: cstring=nil, lpUsedDefaultChar: pointer=nil): cint {. stdcall, importc: "WideCharToMultiByte", dynlib: "kernel32".} - + else: when defined(haiku): const iconvDll = "(libc.so.6|libiconv.so|libtextencoding.so)" @@ -292,31 +292,31 @@ else: proc iconv(c: EncodingConverter, inbuf: pointer, inbytesLeft: pointer, outbuf: var cstring, outbytesLeft: var int): int {. importc: prefix & "iconv", cdecl, dynlib: iconvDll.} - + proc getCurrentEncoding*(): string = ## retrieves the current encoding. On Unix, always "UTF-8" is returned. when defined(windows): result = codePageToName(getACP()) else: result = "UTF-8" - + proc open*(destEncoding = "UTF-8", srcEncoding = "CP1252"): EncodingConverter = ## opens a converter that can convert from `srcEncoding` to `destEncoding`. ## Raises `EIO` if it cannot fulfill the request. when not defined(windows): result = iconvOpen(destEncoding, srcEncoding) if result == nil: - raise newException(EncodingError, - "cannot create encoding converter from " & + raise newException(EncodingError, + "cannot create encoding converter from " & srcEncoding & " to " & destEncoding) else: result.dest = nameToCodePage(destEncoding) result.src = nameToCodePage(srcEncoding) if int(result.dest) == -1: - raise newException(EncodingError, + raise newException(EncodingError, "cannot find encoding " & destEncoding) if int(result.src) == -1: - raise newException(EncodingError, + raise newException(EncodingError, "cannot find encoding " & srcEncoding) proc close*(c: EncodingConverter) = @@ -328,7 +328,7 @@ when defined(windows): proc convert*(c: EncodingConverter, s: string): string = ## converts `s` to `destEncoding` that was given to the converter `c`. It ## assumed that `s` is in `srcEncoding`. - + # special case: empty string: needed because MultiByteToWideChar # return 0 in case of error: if s.len == 0: return "" @@ -336,21 +336,21 @@ when defined(windows): var cap = s.len + s.len shr 2 result = newStringOfCap(cap*2) # convert to utf-16 LE - var m = multiByteToWideChar(codePage = c.src, dwFlags = 0'i32, + var m = multiByteToWideChar(codePage = c.src, dwFlags = 0'i32, lpMultiByteStr = cstring(s), cbMultiByte = cint(s.len), lpWideCharStr = cstring(result), cchWideChar = cint(cap)) - if m == 0: + if m == 0: # try again; ask for capacity: - cap = multiByteToWideChar(codePage = c.src, dwFlags = 0'i32, + cap = multiByteToWideChar(codePage = c.src, dwFlags = 0'i32, lpMultiByteStr = cstring(s), cbMultiByte = cint(s.len), lpWideCharStr = nil, cchWideChar = cint(0)) # and do the conversion properly: result = newStringOfCap(cap*2) - m = multiByteToWideChar(codePage = c.src, dwFlags = 0'i32, + m = multiByteToWideChar(codePage = c.src, dwFlags = 0'i32, lpMultiByteStr = cstring(s), cbMultiByte = cint(s.len), lpWideCharStr = cstring(result), @@ -361,7 +361,7 @@ when defined(windows): setLen(result, m*2) else: assert(false) # cannot happen - + # if already utf-16 LE, no further need to do something: if int(c.dest) == 1200: return # otherwise the fun starts again: @@ -428,7 +428,7 @@ else: outLen = len(result) - offset else: raiseOSError(lerr.OSErrorCode) - # iconv has a buffer that needs flushing, specially if the last char is + # iconv has a buffer that needs flushing, specially if the last char is # not '\0' discard iconv(c, nil, nil, dst, outLen) if iconvres == cint(-1) and errno == E2BIG: @@ -441,7 +441,7 @@ else: # trim output buffer setLen(result, len(result) - outLen) -proc convert*(s: string, destEncoding = "UTF-8", +proc convert*(s: string, destEncoding = "UTF-8", srcEncoding = "CP1252"): string = ## converts `s` to `destEncoding`. It assumed that `s` is in `srcEncoding`. ## This opens a converter, uses it and closes it again and is thus more diff --git a/lib/pure/endians.nim b/lib/pure/endians.nim index 6e33d4624..5a23169d4 100644 --- a/lib/pure/endians.nim +++ b/lib/pure/endians.nim @@ -24,7 +24,7 @@ proc swapEndian64*(outp, inp: pointer) = o[6] = i[1] o[7] = i[0] -proc swapEndian32*(outp, inp: pointer) = +proc swapEndian32*(outp, inp: pointer) = ## copies `inp` to `outp` swapping bytes. Both buffers are supposed to ## contain at least 4 bytes. var i = cast[cstring](inp) @@ -34,7 +34,7 @@ proc swapEndian32*(outp, inp: pointer) = o[2] = i[1] o[3] = i[0] -proc swapEndian16*(outp, inp: pointer) = +proc swapEndian16*(outp, inp: pointer) = ## copies `inp` to `outp` swapping bytes. Both buffers are supposed to ## contain at least 2 bytes. var @@ -50,7 +50,7 @@ when system.cpuEndian == bigEndian: proc bigEndian64*(outp, inp: pointer) {.inline.} = copyMem(outp, inp, 8) proc bigEndian32*(outp, inp: pointer) {.inline.} = copyMem(outp, inp, 4) proc bigEndian16*(outp, inp: pointer) {.inline.} = copyMem(outp, inp, 2) -else: +else: proc littleEndian64*(outp, inp: pointer) {.inline.} = copyMem(outp, inp, 8) proc littleEndian32*(outp, inp: pointer) {.inline.} = copyMem(outp, inp, 4) proc littleEndian16*(outp, inp: pointer){.inline.} = copyMem(outp, inp, 2) diff --git a/lib/pure/etcpriv.nim b/lib/pure/etcpriv.nim index e7a525e4d..5b785b051 100644 --- a/lib/pure/etcpriv.nim +++ b/lib/pure/etcpriv.nim @@ -18,6 +18,6 @@ const magicIdentSeparatorRuneByteWidth* = 3 # Used by pure/hashes.nim, and the compiler parsing proc isMagicIdentSeparatorRune*(cs: cstring, i: int): bool {. inline } = - result = cs[i] == '\226' and + result = cs[i] == '\226' and cs[i + 1] == '\128' and cs[i + 2] == '\147' # en-dash # 145 = nb-hyphen diff --git a/lib/pure/events.nim b/lib/pure/events.nim index 44e9ed286..01b64c545 100644 --- a/lib/pure/events.nim +++ b/lib/pure/events.nim @@ -10,7 +10,7 @@ ## :Author: Alex Mitchell ## ## This module implements an event system that is not dependent on external -## graphical toolkits. It was originally called ``NimEE`` because +## graphical toolkits. It was originally called ``NimEE`` because ## it was inspired by Python's PyEE module. There are two ways you can use ## events: one is a python-inspired way; the other is more of a C-style way. ## @@ -23,7 +23,7 @@ ## # Python way ## ee.on("EventName", handleevent) ## ee.emit("EventName", genericargs) -## +## ## # C/Java way ## # Declare a type ## type @@ -45,7 +45,7 @@ type {.deprecated: [TEventArgs: EventArgs, TEventHandler: EventHandler, TEventEmitter: EventEmitter, EInvalidEvent: EventError].} - + proc initEventHandler*(name: string): EventHandler = ## Initializes an EventHandler with the specified name and returns it. result.handlers = @[] @@ -61,7 +61,7 @@ proc removeHandler*(handler: var EventHandler, fn: proc(e: EventArgs) {.closure. if fn == handler.handlers[i]: handler.handlers.del(i) break - + proc containsHandler*(handler: var EventHandler, fn: proc(e: EventArgs) {.closure.}): bool = ## Checks if a callback is registered to this event handler. return handler.handlers.contains(fn) @@ -86,8 +86,8 @@ proc on*(emitter: var EventEmitter, event: string, fn: proc(e: EventArgs) {.clos emitter.s.add(eh) else: addHandler(emitter.s[i], fn) - -proc emit*(emitter: var EventEmitter, eventhandler: var EventHandler, + +proc emit*(emitter: var EventEmitter, eventhandler: var EventHandler, args: EventArgs) = ## Fires an event handler with specified event arguments. for fn in items(eventhandler.handlers): fn(args) diff --git a/lib/pure/fsmonitor.nim b/lib/pure/fsmonitor.nim index 229df80b5..787acb5d4 100644 --- a/lib/pure/fsmonitor.nim +++ b/lib/pure/fsmonitor.nim @@ -30,7 +30,7 @@ type fd: cint handleEvent: proc (m: FSMonitor, ev: MonitorEvent) {.closure.} targets: Table[cint, string] - + MonitorEventType* = enum ## Monitor event type MonitorAccess, ## File was accessed. MonitorAttrib, ## Metadata changed. @@ -44,7 +44,7 @@ type MonitorMoved, ## File was moved. MonitorOpen, ## File was opened. MonitorAll ## Filter for all event types. - + MonitorEvent* = object case kind*: MonitorEventType ## Type of the event. of MonitorMoveSelf, MonitorMoved: @@ -77,7 +77,7 @@ proc add*(monitor: FSMonitor, target: string, ## Adds ``target`` which may be a directory or a file to the list of ## watched paths of ``monitor``. ## You can specify the events to report using the ``filters`` parameter. - + var INFilter = -1 for f in filters: case f @@ -93,7 +93,7 @@ proc add*(monitor: FSMonitor, target: string, of MonitorMoved: INFilter = INFilter and IN_MOVED_FROM and IN_MOVED_TO of MonitorOpen: INFilter = INFilter and IN_OPEN of MonitorAll: INFilter = INFilter and IN_ALL_EVENTS - + result = inotifyAddWatch(monitor.fd, target, INFilter.uint32) if result < 0: raiseOSError(osLastError()) @@ -125,13 +125,13 @@ proc getEvent(m: FSMonitor, fd: cint): seq[MonitorEvent] = mev.name = $cstr else: mev.name = "" - - if (event.mask.int and IN_MOVED_FROM) != 0: + + if (event.mask.int and IN_MOVED_FROM) != 0: # Moved from event, add to m's collection movedFrom.add(event.cookie.cint, (mev.wd, mev.name)) inc(i, sizeof(INotifyEvent) + event.len.int) continue - elif (event.mask.int and IN_MOVED_TO) != 0: + elif (event.mask.int and IN_MOVED_TO) != 0: mev.kind = MonitorMoved assert movedFrom.hasKey(event.cookie.cint) # Find the MovedFrom event. @@ -141,23 +141,23 @@ proc getEvent(m: FSMonitor, fd: cint): seq[MonitorEvent] = movedFrom.del(event.cookie.cint) elif (event.mask.int and IN_ACCESS) != 0: mev.kind = MonitorAccess elif (event.mask.int and IN_ATTRIB) != 0: mev.kind = MonitorAttrib - elif (event.mask.int and IN_CLOSE_WRITE) != 0: + elif (event.mask.int and IN_CLOSE_WRITE) != 0: mev.kind = MonitorCloseWrite - elif (event.mask.int and IN_CLOSE_NOWRITE) != 0: + elif (event.mask.int and IN_CLOSE_NOWRITE) != 0: mev.kind = MonitorCloseNoWrite elif (event.mask.int and IN_CREATE) != 0: mev.kind = MonitorCreate - elif (event.mask.int and IN_DELETE) != 0: + elif (event.mask.int and IN_DELETE) != 0: mev.kind = MonitorDelete - elif (event.mask.int and IN_DELETE_SELF) != 0: + elif (event.mask.int and IN_DELETE_SELF) != 0: mev.kind = MonitorDeleteSelf elif (event.mask.int and IN_MODIFY) != 0: mev.kind = MonitorModify - elif (event.mask.int and IN_MOVE_SELF) != 0: + elif (event.mask.int and IN_MOVE_SELF) != 0: mev.kind = MonitorMoveSelf elif (event.mask.int and IN_OPEN) != 0: mev.kind = MonitorOpen - + if mev.kind != MonitorMoved: mev.fullname = "" - + result.add(mev) inc(i, sizeof(INotifyEvent) + event.len.int) @@ -211,7 +211,7 @@ when not defined(testing) and isMainModule: echo("Name is ", ev.name) else: echo("Name ", ev.name, " fullname ", ev.fullName)) - + while true: if not disp.poll(): break main() diff --git a/lib/pure/httpserver.nim b/lib/pure/httpserver.nim index 981891227..71ba04991 100644 --- a/lib/pure/httpserver.nim +++ b/lib/pure/httpserver.nim @@ -142,7 +142,7 @@ when false: if meth == reqPost: # get from client and post to CGI program: var buf = alloc(contentLength) - if recv(client, buf, contentLength) != contentLength: + if recv(client, buf, contentLength) != contentLength: dealloc(buf) raiseOSError() var inp = process.inputStream @@ -177,7 +177,7 @@ when false: else: path = "." & data[1] # path starts with "/", by adding "." in front of it we serve files from cwd - + if cmpIgnoreCase(data[0], "GET") == 0: if q >= 0: cgi = true @@ -218,12 +218,12 @@ type headers*: StringTableRef ## headers with which the client made the request body*: string ## only set with POST requests ip*: string ## ip address of the requesting client - + PAsyncHTTPServer* = ref AsyncHTTPServer AsyncHTTPServer = object of Server asyncSocket: AsyncSocket {.deprecated: [TAsyncHTTPServer: AsyncHTTPServer, TServer: Server].} - + proc open*(s: var Server, port = Port(80), reuseAddr = false) = ## creates a new server at port `port`. If ``port == 0`` a free port is ## acquired that can be accessed later by the ``port`` proc. @@ -262,7 +262,7 @@ proc next*(s: var Server) = var data = "" s.client.readLine(data) if data == "": - # Socket disconnected + # Socket disconnected s.client.close() next(s) return @@ -283,9 +283,9 @@ proc next*(s: var Server) = s.client.close() next(s) return - + var i = skipWhitespace(data) - if skipIgnoreCase(data, "GET") > 0: + if skipIgnoreCase(data, "GET") > 0: s.reqMethod = "GET" inc(i, 3) elif skipIgnoreCase(data, "POST") > 0: @@ -296,7 +296,7 @@ proc next*(s: var Server) = s.client.close() next(s) return - + if s.reqMethod == "POST": # Check for Expect header if s.headers.hasKey("Expect"): @@ -304,7 +304,7 @@ proc next*(s: var Server) = s.client.sendStatus("100 Continue") else: s.client.sendStatus("417 Expectation Failed") - + # Read the body # - Check for Content-length header if s.headers.hasKey("Content-Length"): @@ -340,13 +340,13 @@ proc next*(s: var Server) = s.client.close() next(s) return - + var L = skipWhitespace(data, i) inc(i, L) # XXX we ignore "HTTP/1.1" etc. for now here var query = 0 var last = i - while last < data.len and data[last] notin Whitespace: + while last < data.len and data[last] notin Whitespace: if data[last] == '?' and query == 0: query = last inc(last) if query > 0: @@ -360,7 +360,7 @@ proc close*(s: Server) = ## closes the server (and the socket the server uses). close(s.socket) -proc run*(handleRequest: proc (client: Socket, +proc run*(handleRequest: proc (client: Socket, path, query: string): bool {.closure.}, port = Port(80)) = ## encapsulates the server object and main loop @@ -388,7 +388,7 @@ proc nextAsync(s: PAsyncHTTPServer) = var data = "" s.client.readLine(data) if data == "": - # Socket disconnected + # Socket disconnected s.client.close() return var header = "" @@ -408,9 +408,9 @@ proc nextAsync(s: PAsyncHTTPServer) = else: s.client.close() return - + var i = skipWhitespace(data) - if skipIgnoreCase(data, "GET") > 0: + if skipIgnoreCase(data, "GET") > 0: s.reqMethod = "GET" inc(i, 3) elif skipIgnoreCase(data, "POST") > 0: @@ -420,7 +420,7 @@ proc nextAsync(s: PAsyncHTTPServer) = unimplemented(s.client) s.client.close() return - + if s.reqMethod == "POST": # Check for Expect header if s.headers.hasKey("Expect"): @@ -428,7 +428,7 @@ proc nextAsync(s: PAsyncHTTPServer) = s.client.sendStatus("100 Continue") else: s.client.sendStatus("417 Expectation Failed") - + # Read the body # - Check for Content-length header if s.headers.hasKey("Content-Length"): @@ -460,13 +460,13 @@ proc nextAsync(s: PAsyncHTTPServer) = badRequest(s.client) s.client.close() return - + var L = skipWhitespace(data, i) inc(i, L) # XXX we ignore "HTTP/1.1" etc. for now here var query = 0 var last = i - while last < data.len and data[last] notin Whitespace: + while last < data.len and data[last] notin Whitespace: if data[last] == '?' and query == 0: query = last inc(last) if query > 0: @@ -476,7 +476,7 @@ proc nextAsync(s: PAsyncHTTPServer) = s.query = "" s.path = data.substr(i, last-1) -proc asyncHTTPServer*(handleRequest: proc (server: PAsyncHTTPServer, client: Socket, +proc asyncHTTPServer*(handleRequest: proc (server: PAsyncHTTPServer, client: Socket, path, query: string): bool {.closure, gcsafe.}, port = Port(80), address = "", reuseAddr = false): PAsyncHTTPServer = @@ -492,14 +492,14 @@ proc asyncHTTPServer*(handleRequest: proc (server: PAsyncHTTPServer, client: Soc if quit: capturedRet.asyncSocket.close() if reuseAddr: capturedRet.asyncSocket.setSockOpt(OptReuseAddr, true) - + capturedRet.asyncSocket.bindAddr(port, address) capturedRet.asyncSocket.listen() if port == Port(0): capturedRet.port = getSockName(capturedRet.asyncSocket) else: capturedRet.port = port - + capturedRet.client = invalidSocket capturedRet.reqMethod = "" capturedRet.body = "" @@ -524,11 +524,11 @@ when not defined(testing) and isMainModule: echo("httpserver running on port ", s.port) while true: next(s) - + inc(counter) s.client.send("Hello, Andreas, for the $#th time. $# ? $#" % [ $counter, s.path, s.query] & wwwNL) - + close(s.client) close(s) diff --git a/lib/pure/matchers.nim b/lib/pure/matchers.nim index d55963c15..5c28f65a0 100644 --- a/lib/pure/matchers.nim +++ b/lib/pure/matchers.nim @@ -18,15 +18,15 @@ include "system/inclrtl" import parseutils, strutils proc validEmailAddress*(s: string): bool {.noSideEffect, - rtl, extern: "nsuValidEmailAddress".} = - ## returns true if `s` seems to be a valid e-mail address. + rtl, extern: "nsuValidEmailAddress".} = + ## returns true if `s` seems to be a valid e-mail address. ## The checking also uses a domain list. const chars = Letters + Digits + {'!','#','$','%','&', '\'','*','+','/','=','?','^','_','`','{','}','|','~','-','.'} var i = 0 if s[i] notin chars or s[i] == '.': return false - while s[i] in chars: + while s[i] in chars: if s[i] == '.' and s[i+1] == '.': return false inc(i) if s[i] != '@': return false @@ -34,9 +34,9 @@ proc validEmailAddress*(s: string): bool {.noSideEffect, if s[j] notin Letters: return false while j >= i and s[j] in Letters: dec(j) inc(i) # skip '@' - while s[i] in {'0'..'9', 'a'..'z', '-', '.'}: inc(i) + while s[i] in {'0'..'9', 'a'..'z', '-', '.'}: inc(i) if s[i] != '\0': return false - + var x = substr(s, j+1) if len(x) == 2 and x[0] in Letters and x[1] in Letters: return true case toLower(x) @@ -59,6 +59,6 @@ proc parseInt*(s: string, value: var int, validRange: Slice[int]) {. when isMainModule: doAssert "wuseldusel@codehome.com".validEmailAddress - + {.pop.} diff --git a/lib/pure/memfiles.nim b/lib/pure/memfiles.nim index 00929eaa2..27b989597 100644 --- a/lib/pure/memfiles.nim +++ b/lib/pure/memfiles.nim @@ -33,7 +33,7 @@ type when defined(windows): fHandle: int - mapHandle: int + mapHandle: int else: handle: cint @@ -131,7 +131,7 @@ proc open*(filename: string, mode: FileMode = fmRead, fail(osLastError(), "error opening file") if newFileSize != -1: - var + var sizeHigh = int32(newFileSize shr 32) sizeLow = int32(newFileSize and 0xffffffff) @@ -177,7 +177,7 @@ proc open*(filename: string, mode: FileMode = fmRead, rollback() if result.handle != 0: discard close(result.handle) raiseOSError(errCode) - + var flags = if readonly: O_RDONLY else: O_RDWR if newFileSize != -1: @@ -221,7 +221,7 @@ proc open*(filename: string, mode: FileMode = fmRead, proc close*(f: var MemFile) = ## closes the memory mapped file `f`. All changes are written back to the ## file system, if `f` was opened with write access. - + var error = false var lastErr: OSErrorCode @@ -245,7 +245,7 @@ proc close*(f: var MemFile) = f.mapHandle = 0 else: f.handle = 0 - + if error: raiseOSError(lastErr) type MemSlice* = object ## represent slice of a MemFile for iteration over delimited lines/records diff --git a/lib/pure/mersenne.nim b/lib/pure/mersenne.nim index 74112e304..c8090dc6a 100644 --- a/lib/pure/mersenne.nim +++ b/lib/pure/mersenne.nim @@ -7,7 +7,7 @@ type {.deprecated: [TMersenneTwister: MersenneTwister].} -proc newMersenneTwister*(seed: int): MersenneTwister = +proc newMersenneTwister*(seed: int): MersenneTwister = result.index = 0 result.mt[0]= uint32(seed) for i in 1..623'u32: diff --git a/lib/pure/numeric.nim b/lib/pure/numeric.nim index 9b298c0a0..71adf19b3 100644 --- a/lib/pure/numeric.nim +++ b/lib/pure/numeric.nim @@ -11,23 +11,23 @@ type OneVarFunction* = proc (x: float): float {.deprecated: [TOneVarFunction: OneVarFunction].} -proc brent*(xmin,xmax:float, function:OneVarFunction, tol:float,maxiter=1000): +proc brent*(xmin,xmax:float, function:OneVarFunction, tol:float,maxiter=1000): tuple[rootx, rooty: float, success: bool]= - ## Searches `function` for a root between `xmin` and `xmax` + ## Searches `function` for a root between `xmin` and `xmax` ## using brents method. If the function value at `xmin`and `xmax` has the ## same sign, `rootx`/`rooty` is set too the extrema value closest to x-axis ## and succes is set to false. ## Otherwise there exists at least one root and success is set to true. ## This root is searched for at most `maxiter` iterations. - ## If `tol` tolerance is reached within `maxiter` iterations + ## If `tol` tolerance is reached within `maxiter` iterations ## the root refinement stops and success=true. # see http://en.wikipedia.org/wiki/Brent%27s_method - var + var a=xmin b=xmax c=a - d=1.0e308 + d=1.0e308 fa=function(a) fb=function(b) fc=fa @@ -42,19 +42,19 @@ proc brent*(xmin,xmax:float, function:OneVarFunction, tol:float,maxiter=1000): return (a,fa,false) else: return (b,fb,false) - + if abs(fa)tol: if fa!=fc and fb!=fc: # inverse quadratic interpolation s = a * fb * fc / (fa - fb) / (fa - fc) + b * fa * fc / (fb - fa) / (fb - fc) + c * fa * fb / (fc - fa) / (fc - fb) else: #secant rule s = b - fb * (b - a) / (fb - fa) tmp2 = (3.0 * a + b) / 4.0 - if not((s > tmp2 and s < b) or (s < tmp2 and s > b)) or - (mflag and abs(s - b) >= (abs(b - c) / 2.0)) or + if not((s > tmp2 and s < b) or (s < tmp2 and s > b)) or + (mflag and abs(s - b) >= (abs(b - c) / 2.0)) or (not mflag and abs(s - b) >= abs(c - d) / 2.0): s=(a+b)/2.0 mflag=true @@ -80,5 +80,5 @@ proc brent*(xmin,xmax:float, function:OneVarFunction, tol:float,maxiter=1000): inc i if i>maxiter: break - + return (b,fb,true) diff --git a/lib/pure/oids.nim b/lib/pure/oids.nim index ac90dd16b..174922223 100644 --- a/lib/pure/oids.nim +++ b/lib/pure/oids.nim @@ -8,7 +8,7 @@ # ## Nim OID support. An OID is a global ID that consists of a timestamp, -## a unique counter and a random value. This combination should suffice to +## a unique counter and a random value. This combination should suffice to ## produce a globally distributed unique ID. This implementation was extracted ## from the Mongodb interface and it thus binary compatible with a Mongo OID. ## @@ -19,13 +19,13 @@ import times, endians type Oid* = object ## an OID - time: int32 ## - fuzz: int32 ## - count: int32 ## + time: int32 ## + fuzz: int32 ## + count: int32 ## {.deprecated: [Toid: Oid].} -proc hexbyte*(hex: char): int = +proc hexbyte*(hex: char): int = case hex of '0'..'9': result = (ord(hex) - ord('0')) of 'a'..'f': result = (ord(hex) - ord('a') + 10) @@ -40,7 +40,7 @@ proc parseOid*(str: cstring): Oid = bytes[i] = chr((hexbyte(str[2 * i]) shl 4) or hexbyte(str[2 * i + 1])) inc(i) -proc oidToString*(oid: Oid, str: cstring) = +proc oidToString*(oid: Oid, str: cstring) = const hex = "0123456789abcdef" # work around a compiler bug: var str = str @@ -59,7 +59,7 @@ proc `$`*(oid: Oid): string = oidToString(oid, result) var - incr: int + incr: int fuzz: int32 proc genOid*(): Oid = @@ -69,10 +69,10 @@ proc genOid*(): Oid = proc srand(seed: cint) {.importc: "srand", header: "", nodecl.} var t = gettime(nil) - + var i = int32(incr) atomicInc(incr) - + if fuzz == 0: # racy, but fine semantically: srand(t) diff --git a/lib/pure/parsecfg.nim b/lib/pure/parsecfg.nim index bb64c8134..f680d4fef 100644 --- a/lib/pure/parsecfg.nim +++ b/lib/pure/parsecfg.nim @@ -7,17 +7,17 @@ # distribution, for details about the copyright. # -## The ``parsecfg`` module implements a high performance configuration file -## parser. The configuration file's syntax is similar to the Windows ``.ini`` -## format, but much more powerful, as it is not a line based parser. String -## literals, raw string literals and triple quoted string literals are supported +## The ``parsecfg`` module implements a high performance configuration file +## parser. The configuration file's syntax is similar to the Windows ``.ini`` +## format, but much more powerful, as it is not a line based parser. String +## literals, raw string literals and triple quoted string literals are supported ## as in the Nim programming language. ## This is an example of how a configuration file may look like: ## ## .. include:: doc/mytest.cfg ## :literal: -## The file ``examples/parsecfgex.nim`` demonstrates how to use the +## The file ``examples/parsecfgex.nim`` demonstrates how to use the ## configuration file parser: ## ## .. code-block:: nim @@ -36,14 +36,14 @@ type cfgKeyValuePair, ## a ``key=value`` pair has been detected cfgOption, ## a ``--key=value`` command line option cfgError ## an error occurred during parsing - + CfgEvent* = object of RootObj ## describes a parsing event case kind*: CfgEventKind ## the kind of the event of cfgEof: nil - of cfgSectionStart: - section*: string ## `section` contains the name of the + of cfgSectionStart: + section*: string ## `section` contains the name of the ## parsed section start (syntax: ``[section]``) - of cfgKeyValuePair, cfgOption: + of cfgKeyValuePair, cfgOption: key*, value*: string ## contains the (key, value) pair if an option ## of the form ``--key: value`` or an ordinary ## ``key= value`` pair has been parsed. @@ -52,14 +52,14 @@ type of cfgError: ## the parser encountered an error: `msg` msg*: string ## contains the error message. No exceptions ## are thrown if a parse error occurs. - - TokKind = enum - tkInvalid, tkEof, + + TokKind = enum + tkInvalid, tkEof, tkSymbol, tkEquals, tkColon, tkBracketLe, tkBracketRi, tkDashDash Token = object # a token kind: TokKind # the type of the token literal: string # the parsed (string) literal - + CfgParser* = object of BaseLexer ## the parser object. tok: Token filename: string @@ -69,12 +69,12 @@ type # implementation -const - SymChars = {'a'..'z', 'A'..'Z', '0'..'9', '_', '\x80'..'\xFF', '.', '/', '\\'} - +const + SymChars = {'a'..'z', 'A'..'Z', '0'..'9', '_', '\x80'..'\xFF', '.', '/', '\\'} + proc rawGetTok(c: var CfgParser, tok: var Token) {.gcsafe.} -proc open*(c: var CfgParser, input: Stream, filename: string, +proc open*(c: var CfgParser, input: Stream, filename: string, lineOffset = 0) {.rtl, extern: "npc$1".} = ## initializes the parser with an input stream. `Filename` is only used ## for nice error messages. `lineOffset` can be used to influence the line @@ -85,7 +85,7 @@ proc open*(c: var CfgParser, input: Stream, filename: string, c.tok.literal = "" inc(c.lineNumber, lineOffset) rawGetTok(c, c.tok) - + proc close*(c: var CfgParser) {.rtl, extern: "npc$1".} = ## closes the parser `c` and its associated input stream. lexbase.close(c) @@ -102,260 +102,260 @@ proc getFilename*(c: CfgParser): string {.rtl, extern: "npc$1".} = ## get the filename of the file that the parser processes. result = c.filename -proc handleHexChar(c: var CfgParser, xi: var int) = +proc handleHexChar(c: var CfgParser, xi: var int) = case c.buf[c.bufpos] - of '0'..'9': + of '0'..'9': xi = (xi shl 4) or (ord(c.buf[c.bufpos]) - ord('0')) inc(c.bufpos) - of 'a'..'f': + of 'a'..'f': xi = (xi shl 4) or (ord(c.buf[c.bufpos]) - ord('a') + 10) inc(c.bufpos) - of 'A'..'F': + of 'A'..'F': xi = (xi shl 4) or (ord(c.buf[c.bufpos]) - ord('A') + 10) inc(c.bufpos) - else: + else: discard -proc handleDecChars(c: var CfgParser, xi: var int) = - while c.buf[c.bufpos] in {'0'..'9'}: +proc handleDecChars(c: var CfgParser, xi: var int) = + while c.buf[c.bufpos] in {'0'..'9'}: xi = (xi * 10) + (ord(c.buf[c.bufpos]) - ord('0')) inc(c.bufpos) -proc getEscapedChar(c: var CfgParser, tok: var Token) = +proc getEscapedChar(c: var CfgParser, tok: var Token) = inc(c.bufpos) # skip '\' case c.buf[c.bufpos] - of 'n', 'N': + of 'n', 'N': add(tok.literal, "\n") inc(c.bufpos) - of 'r', 'R', 'c', 'C': + of 'r', 'R', 'c', 'C': add(tok.literal, '\c') inc(c.bufpos) - of 'l', 'L': + of 'l', 'L': add(tok.literal, '\L') inc(c.bufpos) - of 'f', 'F': + of 'f', 'F': add(tok.literal, '\f') inc(c.bufpos) - of 'e', 'E': + of 'e', 'E': add(tok.literal, '\e') inc(c.bufpos) - of 'a', 'A': + of 'a', 'A': add(tok.literal, '\a') inc(c.bufpos) - of 'b', 'B': + of 'b', 'B': add(tok.literal, '\b') inc(c.bufpos) - of 'v', 'V': + of 'v', 'V': add(tok.literal, '\v') inc(c.bufpos) - of 't', 'T': + of 't', 'T': add(tok.literal, '\t') inc(c.bufpos) - of '\'', '"': + of '\'', '"': add(tok.literal, c.buf[c.bufpos]) inc(c.bufpos) - of '\\': + of '\\': add(tok.literal, '\\') inc(c.bufpos) - of 'x', 'X': + of 'x', 'X': inc(c.bufpos) var xi = 0 handleHexChar(c, xi) handleHexChar(c, xi) add(tok.literal, chr(xi)) - of '0'..'9': + of '0'..'9': var xi = 0 handleDecChars(c, xi) if (xi <= 255): add(tok.literal, chr(xi)) else: tok.kind = tkInvalid else: tok.kind = tkInvalid - -proc handleCRLF(c: var CfgParser, pos: int): int = + +proc handleCRLF(c: var CfgParser, pos: int): int = case c.buf[pos] of '\c': result = lexbase.handleCR(c, pos) of '\L': result = lexbase.handleLF(c, pos) else: result = pos - -proc getString(c: var CfgParser, tok: var Token, rawMode: bool) = + +proc getString(c: var CfgParser, tok: var Token, rawMode: bool) = var pos = c.bufpos + 1 # skip " var buf = c.buf # put `buf` in a register tok.kind = tkSymbol - if (buf[pos] == '"') and (buf[pos + 1] == '"'): + if (buf[pos] == '"') and (buf[pos + 1] == '"'): # long string literal: inc(pos, 2) # skip "" # skip leading newline: pos = handleCRLF(c, pos) buf = c.buf - while true: + while true: case buf[pos] - of '"': - if (buf[pos + 1] == '"') and (buf[pos + 2] == '"'): break + of '"': + if (buf[pos + 1] == '"') and (buf[pos + 2] == '"'): break add(tok.literal, '"') inc(pos) - of '\c', '\L': + of '\c', '\L': pos = handleCRLF(c, pos) buf = c.buf add(tok.literal, "\n") - of lexbase.EndOfFile: + of lexbase.EndOfFile: tok.kind = tkInvalid - break - else: + break + else: add(tok.literal, buf[pos]) inc(pos) c.bufpos = pos + 3 # skip the three """ - else: + else: # ordinary string literal - while true: + while true: var ch = buf[pos] - if ch == '"': + if ch == '"': inc(pos) # skip '"' - break - if ch in {'\c', '\L', lexbase.EndOfFile}: + break + if ch in {'\c', '\L', lexbase.EndOfFile}: tok.kind = tkInvalid - break - if (ch == '\\') and not rawMode: + break + if (ch == '\\') and not rawMode: c.bufpos = pos getEscapedChar(c, tok) pos = c.bufpos - else: + else: add(tok.literal, ch) inc(pos) c.bufpos = pos -proc getSymbol(c: var CfgParser, tok: var Token) = +proc getSymbol(c: var CfgParser, tok: var Token) = var pos = c.bufpos var buf = c.buf - while true: + while true: add(tok.literal, buf[pos]) inc(pos) - if not (buf[pos] in SymChars): break + if not (buf[pos] in SymChars): break c.bufpos = pos tok.kind = tkSymbol -proc skip(c: var CfgParser) = +proc skip(c: var CfgParser) = var pos = c.bufpos var buf = c.buf - while true: + while true: case buf[pos] - of ' ', '\t': + of ' ', '\t': inc(pos) - of '#', ';': + of '#', ';': while not (buf[pos] in {'\c', '\L', lexbase.EndOfFile}): inc(pos) - of '\c', '\L': + of '\c', '\L': pos = handleCRLF(c, pos) buf = c.buf - else: + else: break # EndOfFile also leaves the loop c.bufpos = pos -proc rawGetTok(c: var CfgParser, tok: var Token) = +proc rawGetTok(c: var CfgParser, tok: var Token) = tok.kind = tkInvalid setLen(tok.literal, 0) skip(c) case c.buf[c.bufpos] - of '=': + of '=': tok.kind = tkEquals inc(c.bufpos) tok.literal = "=" - of '-': + of '-': inc(c.bufpos) if c.buf[c.bufpos] == '-': inc(c.bufpos) tok.kind = tkDashDash tok.literal = "--" - of ':': + of ':': tok.kind = tkColon inc(c.bufpos) tok.literal = ":" - of 'r', 'R': - if c.buf[c.bufpos + 1] == '\"': + of 'r', 'R': + if c.buf[c.bufpos + 1] == '\"': inc(c.bufpos) getString(c, tok, true) - else: + else: getSymbol(c, tok) - of '[': + of '[': tok.kind = tkBracketLe inc(c.bufpos) tok.literal = "]" - of ']': + of ']': tok.kind = tkBracketRi inc(c.bufpos) tok.literal = "]" - of '"': + of '"': getString(c, tok, false) - of lexbase.EndOfFile: + of lexbase.EndOfFile: tok.kind = tkEof tok.literal = "[EOF]" else: getSymbol(c, tok) - + proc errorStr*(c: CfgParser, msg: string): string {.rtl, extern: "npc$1".} = ## returns a properly formated error message containing current line and ## column information. - result = `%`("$1($2, $3) Error: $4", + result = `%`("$1($2, $3) Error: $4", [c.filename, $getLine(c), $getColumn(c), msg]) - + proc warningStr*(c: CfgParser, msg: string): string {.rtl, extern: "npc$1".} = ## returns a properly formated warning message containing current line and ## column information. - result = `%`("$1($2, $3) Warning: $4", + result = `%`("$1($2, $3) Warning: $4", [c.filename, $getLine(c), $getColumn(c), msg]) proc ignoreMsg*(c: CfgParser, e: CfgEvent): string {.rtl, extern: "npc$1".} = ## returns a properly formated warning message containing that ## an entry is ignored. - case e.kind + case e.kind of cfgSectionStart: result = c.warningStr("section ignored: " & e.section) of cfgKeyValuePair: result = c.warningStr("key ignored: " & e.key) - of cfgOption: + of cfgOption: result = c.warningStr("command ignored: " & e.key & ": " & e.value) of cfgError: result = e.msg of cfgEof: result = "" -proc getKeyValPair(c: var CfgParser, kind: CfgEventKind): CfgEvent = - if c.tok.kind == tkSymbol: +proc getKeyValPair(c: var CfgParser, kind: CfgEventKind): CfgEvent = + if c.tok.kind == tkSymbol: result.kind = kind result.key = c.tok.literal result.value = "" rawGetTok(c, c.tok) - if c.tok.kind in {tkEquals, tkColon}: + if c.tok.kind in {tkEquals, tkColon}: rawGetTok(c, c.tok) - if c.tok.kind == tkSymbol: + if c.tok.kind == tkSymbol: result.value = c.tok.literal - else: + else: reset result result.kind = cfgError result.msg = errorStr(c, "symbol expected, but found: " & c.tok.literal) rawGetTok(c, c.tok) - else: + else: result.kind = cfgError result.msg = errorStr(c, "symbol expected, but found: " & c.tok.literal) rawGetTok(c, c.tok) proc next*(c: var CfgParser): CfgEvent {.rtl, extern: "npc$1".} = ## retrieves the first/next event. This controls the parser. - case c.tok.kind - of tkEof: + case c.tok.kind + of tkEof: result.kind = cfgEof - of tkDashDash: + of tkDashDash: rawGetTok(c, c.tok) result = getKeyValPair(c, cfgOption) - of tkSymbol: + of tkSymbol: result = getKeyValPair(c, cfgKeyValuePair) - of tkBracketLe: + of tkBracketLe: rawGetTok(c, c.tok) - if c.tok.kind == tkSymbol: + if c.tok.kind == tkSymbol: result.kind = cfgSectionStart result.section = c.tok.literal - else: + else: result.kind = cfgError result.msg = errorStr(c, "symbol expected, but found: " & c.tok.literal) rawGetTok(c, c.tok) - if c.tok.kind == tkBracketRi: + if c.tok.kind == tkBracketRi: rawGetTok(c, c.tok) else: reset(result) result.kind = cfgError result.msg = errorStr(c, "']' expected, but found: " & c.tok.literal) - of tkInvalid, tkEquals, tkColon, tkBracketRi: + of tkInvalid, tkEquals, tkColon, tkBracketRi: result.kind = cfgError result.msg = errorStr(c, "invalid token: " & c.tok.literal) rawGetTok(c, c.tok) diff --git a/lib/pure/parsecsv.nim b/lib/pure/parsecsv.nim index 117d75cfa..af51e1201 100644 --- a/lib/pure/parsecsv.nim +++ b/lib/pure/parsecsv.nim @@ -8,7 +8,7 @@ # ## This module implements a simple high performance `CSV`:idx: -## (`comma separated value`:idx:) parser. +## (`comma separated value`:idx:) parser. ## ## Example: How to use the parser ## ============================== @@ -43,7 +43,7 @@ type {.deprecated: [TCsvRow: CsvRow, TCsvParser: CsvParser, EInvalidCsv: CsvError].} -proc raiseEInvalidCsv(filename: string, line, col: int, +proc raiseEInvalidCsv(filename: string, line, col: int, msg: string) {.noreturn.} = var e: ref CsvError new(e) @@ -60,13 +60,13 @@ proc open*(my: var CsvParser, input: Stream, filename: string, ## for nice error messages. The parser's behaviour can be controlled by ## the diverse optional parameters: ## - `separator`: character used to separate fields - ## - `quote`: Used to quote fields containing special characters like + ## - `quote`: Used to quote fields containing special characters like ## `separator`, `quote` or new-line characters. '\0' disables the parsing ## of quotes. - ## - `escape`: removes any special meaning from the following character; + ## - `escape`: removes any special meaning from the following character; ## '\0' disables escaping; if escaping is disabled and `quote` is not '\0', ## two `quote` characters are parsed one literal `quote` character. - ## - `skipInitialSpace`: If true, whitespace immediately following the + ## - `skipInitialSpace`: If true, whitespace immediately following the ## `separator` is ignored. lexbase.open(my, input) my.filename = filename @@ -77,13 +77,13 @@ proc open*(my: var CsvParser, input: Stream, filename: string, my.row = @[] my.currRow = 0 -proc parseField(my: var CsvParser, a: var string) = +proc parseField(my: var CsvParser, a: var string) = var pos = my.bufpos var buf = my.buf if my.skipWhite: while buf[pos] in {' ', '\t'}: inc(pos) setLen(a, 0) # reuse memory - if buf[pos] == my.quote and my.quote != '\0': + if buf[pos] == my.quote and my.quote != '\0': inc(pos) while true: var c = buf[pos] @@ -91,7 +91,7 @@ proc parseField(my: var CsvParser, a: var string) = my.bufpos = pos # can continue after exception? error(my, pos, my.quote & " expected") break - elif c == my.quote: + elif c == my.quote: if my.esc == '\0' and buf[pos+1] == my.quote: add(a, my.quote) inc(pos, 2) @@ -103,11 +103,11 @@ proc parseField(my: var CsvParser, a: var string) = inc(pos, 2) else: case c - of '\c': + of '\c': pos = handleCR(my, pos) buf = my.buf add(a, "\n") - of '\l': + of '\l': pos = handleLF(my, pos) buf = my.buf add(a, "\n") @@ -123,11 +123,11 @@ proc parseField(my: var CsvParser, a: var string) = inc(pos) my.bufpos = pos -proc processedRows*(my: var CsvParser): int = +proc processedRows*(my: var CsvParser): int = ## returns number of the processed rows return my.currRow -proc readRow*(my: var CsvParser, columns = 0): bool = +proc readRow*(my: var CsvParser, columns = 0): bool = ## reads the next row; if `columns` > 0, it expects the row to have ## exactly this many columns. Returns false if the end of the file ## has been encountered else true. @@ -140,13 +140,13 @@ proc readRow*(my: var CsvParser, columns = 0): bool = my.row[col] = "" parseField(my, my.row[col]) inc(col) - if my.buf[my.bufpos] == my.sep: + if my.buf[my.bufpos] == my.sep: inc(my.bufpos) else: case my.buf[my.bufpos] - of '\c', '\l': + of '\c', '\l': # skip empty lines: - while true: + while true: case my.buf[my.bufpos] of '\c': my.bufpos = handleCR(my, my.bufpos) of '\l': my.bufpos = handleLF(my, my.bufpos) @@ -154,15 +154,15 @@ proc readRow*(my: var CsvParser, columns = 0): bool = of '\0': discard else: error(my, my.bufpos, my.sep & " expected") break - + setLen(my.row, col) result = col > 0 - if result and col != columns and columns > 0: - error(my, oldpos+1, $columns & " columns expected, but found " & + if result and col != columns and columns > 0: + error(my, oldpos+1, $columns & " columns expected, but found " & $col & " columns") inc(my.currRow) - -proc close*(my: var CsvParser) {.inline.} = + +proc close*(my: var CsvParser) {.inline.} = ## closes the parser `my` and its associated input stream. lexbase.close(my) diff --git a/lib/pure/parsesql.nim b/lib/pure/parsesql.nim index cfa60094d..d6fafec08 100644 --- a/lib/pure/parsesql.nim +++ b/lib/pure/parsesql.nim @@ -7,7 +7,7 @@ # distribution, for details about the copyright. # -## The ``parsesql`` module implements a high performance SQL file +## The ``parsesql`` module implements a high performance SQL file ## parser. It parses PostgreSQL syntax and the SQL ANSI standard. import @@ -37,11 +37,11 @@ type tkBracketLe, ## '[' tkBracketRi, ## ']' tkDot ## '.' - + Token = object # a token kind: TokKind # the type of the token literal: string # the parsed (string) literal - + SqlLexer* = object of BaseLexer ## the parser object. filename: string @@ -55,82 +55,82 @@ const ";", ":", ",", "(", ")", "[", "]", "." ] -proc open(L: var SqlLexer, input: Stream, filename: string) = +proc open(L: var SqlLexer, input: Stream, filename: string) = lexbase.open(L, input) L.filename = filename - -proc close(L: var SqlLexer) = + +proc close(L: var SqlLexer) = lexbase.close(L) -proc getColumn(L: SqlLexer): int = +proc getColumn(L: SqlLexer): int = ## get the current column the parser has arrived at. result = getColNumber(L, L.bufpos) -proc getLine(L: SqlLexer): int = +proc getLine(L: SqlLexer): int = result = L.lineNumber -proc handleHexChar(c: var SqlLexer, xi: var int) = +proc handleHexChar(c: var SqlLexer, xi: var int) = case c.buf[c.bufpos] - of '0'..'9': + of '0'..'9': xi = (xi shl 4) or (ord(c.buf[c.bufpos]) - ord('0')) inc(c.bufpos) - of 'a'..'f': + of 'a'..'f': xi = (xi shl 4) or (ord(c.buf[c.bufpos]) - ord('a') + 10) inc(c.bufpos) - of 'A'..'F': + of 'A'..'F': xi = (xi shl 4) or (ord(c.buf[c.bufpos]) - ord('A') + 10) inc(c.bufpos) - else: + else: discard -proc handleOctChar(c: var SqlLexer, xi: var int) = +proc handleOctChar(c: var SqlLexer, xi: var int) = if c.buf[c.bufpos] in {'0'..'7'}: xi = (xi shl 3) or (ord(c.buf[c.bufpos]) - ord('0')) inc(c.bufpos) -proc getEscapedChar(c: var SqlLexer, tok: var Token) = +proc getEscapedChar(c: var SqlLexer, tok: var Token) = inc(c.bufpos) case c.buf[c.bufpos] - of 'n', 'N': + of 'n', 'N': add(tok.literal, '\L') inc(c.bufpos) - of 'r', 'R', 'c', 'C': + of 'r', 'R', 'c', 'C': add(tok.literal, '\c') inc(c.bufpos) - of 'l', 'L': + of 'l', 'L': add(tok.literal, '\L') inc(c.bufpos) - of 'f', 'F': + of 'f', 'F': add(tok.literal, '\f') inc(c.bufpos) - of 'e', 'E': + of 'e', 'E': add(tok.literal, '\e') inc(c.bufpos) - of 'a', 'A': + of 'a', 'A': add(tok.literal, '\a') inc(c.bufpos) - of 'b', 'B': + of 'b', 'B': add(tok.literal, '\b') inc(c.bufpos) - of 'v', 'V': + of 'v', 'V': add(tok.literal, '\v') inc(c.bufpos) - of 't', 'T': + of 't', 'T': add(tok.literal, '\t') inc(c.bufpos) - of '\'', '\"': + of '\'', '\"': add(tok.literal, c.buf[c.bufpos]) inc(c.bufpos) - of '\\': + of '\\': add(tok.literal, '\\') inc(c.bufpos) - of 'x', 'X': + of 'x', 'X': inc(c.bufpos) var xi = 0 handleHexChar(c, xi) handleHexChar(c, xi) add(tok.literal, chr(xi)) - of '0'..'7': + of '0'..'7': var xi = 0 handleOctChar(c, xi) handleOctChar(c, xi) @@ -138,20 +138,20 @@ proc getEscapedChar(c: var SqlLexer, tok: var Token) = if (xi <= 255): add(tok.literal, chr(xi)) else: tok.kind = tkInvalid else: tok.kind = tkInvalid - -proc handleCRLF(c: var SqlLexer, pos: int): int = + +proc handleCRLF(c: var SqlLexer, pos: int): int = case c.buf[pos] of '\c': result = lexbase.handleCR(c, pos) of '\L': result = lexbase.handleLF(c, pos) else: result = pos -proc skip(c: var SqlLexer) = +proc skip(c: var SqlLexer) = var pos = c.bufpos var buf = c.buf var nested = 0 - while true: + while true: case buf[pos] - of ' ', '\t': + of ' ', '\t': inc(pos) of '-': if buf[pos+1] == '-': @@ -164,7 +164,7 @@ proc skip(c: var SqlLexer) = while true: case buf[pos] of '\0': break - of '\c', '\L': + of '\c', '\L': pos = handleCRLF(c, pos) buf = c.buf of '*': @@ -182,20 +182,20 @@ proc skip(c: var SqlLexer) = inc(pos) else: inc(pos) else: break - of '\c', '\L': + of '\c', '\L': pos = handleCRLF(c, pos) buf = c.buf - else: + else: break # EndOfFile also leaves the loop c.bufpos = pos - -proc getString(c: var SqlLexer, tok: var Token, kind: TokKind) = + +proc getString(c: var SqlLexer, tok: var Token, kind: TokKind) = var pos = c.bufpos + 1 var buf = c.buf tok.kind = kind block parseLoop: while true: - while true: + while true: var ch = buf[pos] if ch == '\'': if buf[pos+1] == '\'': @@ -203,15 +203,15 @@ proc getString(c: var SqlLexer, tok: var Token, kind: TokKind) = add(tok.literal, '\'') else: inc(pos) - break - elif ch in {'\c', '\L', lexbase.EndOfFile}: + break + elif ch in {'\c', '\L', lexbase.EndOfFile}: tok.kind = tkInvalid break parseLoop - elif (ch == '\\') and kind == tkEscapeConstant: + elif (ch == '\\') and kind == tkEscapeConstant: c.bufpos = pos getEscapedChar(c, tok) pos = c.bufpos - else: + else: add(tok.literal, ch) inc(pos) c.bufpos = pos @@ -227,7 +227,7 @@ proc getString(c: var SqlLexer, tok: var Token, kind: TokKind) = else: break parseLoop c.bufpos = pos -proc getDollarString(c: var SqlLexer, tok: var Token) = +proc getDollarString(c: var SqlLexer, tok: var Token) = var pos = c.bufpos + 1 var buf = c.buf tok.kind = tkDollarQuotedConstant @@ -241,7 +241,7 @@ proc getDollarString(c: var SqlLexer, tok: var Token) = return while true: case buf[pos] - of '\c', '\L': + of '\c', '\L': pos = handleCRLF(c, pos) buf = c.buf add(tok.literal, "\L") @@ -263,10 +263,10 @@ proc getDollarString(c: var SqlLexer, tok: var Token) = inc(pos) c.bufpos = pos -proc getSymbol(c: var SqlLexer, tok: var Token) = +proc getSymbol(c: var SqlLexer, tok: var Token) = var pos = c.bufpos var buf = c.buf - while true: + while true: add(tok.literal, buf[pos]) inc(pos) if buf[pos] notin {'a'..'z','A'..'Z','0'..'9','_','$', '\128'..'\255'}: @@ -274,7 +274,7 @@ proc getSymbol(c: var SqlLexer, tok: var Token) = c.bufpos = pos tok.kind = tkIdentifier -proc getQuotedIdentifier(c: var SqlLexer, tok: var Token) = +proc getQuotedIdentifier(c: var SqlLexer, tok: var Token) = var pos = c.bufpos + 1 var buf = c.buf tok.kind = tkQuotedIdentifier @@ -287,7 +287,7 @@ proc getQuotedIdentifier(c: var SqlLexer, tok: var Token) = else: inc(pos) break - elif ch in {'\c', '\L', lexbase.EndOfFile}: + elif ch in {'\c', '\L', lexbase.EndOfFile}: tok.kind = tkInvalid break else: @@ -300,15 +300,15 @@ proc getBitHexString(c: var SqlLexer, tok: var Token, validChars: set[char]) = var buf = c.buf block parseLoop: while true: - while true: + while true: var ch = buf[pos] if ch in validChars: add(tok.literal, ch) - inc(pos) + inc(pos) elif ch == '\'': inc(pos) break - else: + else: tok.kind = tkInvalid break parseLoop c.bufpos = pos @@ -353,7 +353,7 @@ proc getNumeric(c: var SqlLexer, tok: var Token) = inc(pos) else: tok.kind = tkInvalid - c.bufpos = pos + c.bufpos = pos proc getOperator(c: var SqlLexer, tok: var Token) = const operators = {'+', '-', '*', '/', '<', '>', '=', '~', '!', '@', '#', '%', @@ -381,12 +381,12 @@ proc getOperator(c: var SqlLexer, tok: var Token) = inc(pos) c.bufpos = pos -proc getTok(c: var SqlLexer, tok: var Token) = +proc getTok(c: var SqlLexer, tok: var Token) = tok.kind = tkInvalid setLen(tok.literal, 0) skip(c) case c.buf[c.bufpos] - of ';': + of ';': tok.kind = tkSemicolon inc(c.bufpos) add(tok.literal, ';') @@ -394,15 +394,15 @@ proc getTok(c: var SqlLexer, tok: var Token) = tok.kind = tkComma inc(c.bufpos) add(tok.literal, ',') - of ':': + of ':': tok.kind = tkColon inc(c.bufpos) add(tok.literal, ':') - of 'e', 'E': - if c.buf[c.bufpos + 1] == '\'': + of 'e', 'E': + if c.buf[c.bufpos + 1] == '\'': inc(c.bufpos) getString(c, tok, tkEscapeConstant) - else: + else: getSymbol(c, tok) of 'b', 'B': if c.buf[c.bufpos + 1] == '\'': @@ -417,11 +417,11 @@ proc getTok(c: var SqlLexer, tok: var Token) = else: getSymbol(c, tok) of '$': getDollarString(c, tok) - of '[': + of '[': tok.kind = tkBracketLe inc(c.bufpos) add(tok.literal, '[') - of ']': + of ']': tok.kind = tkBracketRi inc(c.bufpos) add(tok.literal, ']') @@ -433,7 +433,7 @@ proc getTok(c: var SqlLexer, tok: var Token) = tok.kind = tkParRi inc(c.bufpos) add(tok.literal, ')') - of '.': + of '.': if c.buf[c.bufpos + 1] in Digits: getNumeric(c, tok) else: @@ -443,7 +443,7 @@ proc getTok(c: var SqlLexer, tok: var Token) = of '0'..'9': getNumeric(c, tok) of '\'': getString(c, tok, tkStringConstant) of '"': getQuotedIdentifier(c, tok) - of lexbase.EndOfFile: + of lexbase.EndOfFile: tok.kind = tkEof tok.literal = "[EOF]" of 'a', 'c', 'd', 'f'..'w', 'y', 'z', 'A', 'C', 'D', 'F'..'W', 'Y', 'Z', '_', @@ -455,8 +455,8 @@ proc getTok(c: var SqlLexer, tok: var Token) = else: add(tok.literal, c.buf[c.bufpos]) inc(c.bufpos) - -proc errorStr(L: SqlLexer, msg: string): string = + +proc errorStr(L: SqlLexer, msg: string): string = result = "$1($2, $3) Error: $4" % [L.filename, $getLine(L), $getColumn(L), msg] @@ -496,7 +496,7 @@ type nkPrimaryKey, nkForeignKey, nkNotNull, - + nkStmtList, nkDot, nkDotDot, @@ -530,13 +530,13 @@ type nkValueList, nkWhere, nkCreateTable, - nkCreateTableIfNotExists, + nkCreateTableIfNotExists, nkCreateType, nkCreateTypeIfNotExists, nkCreateIndex, nkCreateIndexIfNotExists, nkEnumDef - + type SqlParseError* = object of ValueError ## Invalid SQL encountered SqlNode* = ref SqlNodeObj ## an SQL abstract syntax tree node @@ -563,11 +563,11 @@ proc newNode(k: SqlNodeKind, s: string): SqlNode = new(result) result.kind = k result.strVal = s - + proc len*(n: SqlNode): int = if isNil(n.sons): result = 0 else: result = n.sons.len - + proc add*(father, n: SqlNode) = if isNil(father.sons): father.sons = @[] add(father.sons, n) @@ -641,11 +641,11 @@ proc parseDataType(p: var SqlParser): SqlNode = getTok(p) eat(p, tkParRi) -proc getPrecedence(p: SqlParser): int = +proc getPrecedence(p: SqlParser): int = if isOpr(p, "*") or isOpr(p, "/") or isOpr(p, "%"): result = 6 elif isOpr(p, "+") or isOpr(p, "-"): - result = 5 + result = 5 elif isOpr(p, "=") or isOpr(p, "<") or isOpr(p, ">") or isOpr(p, ">=") or isOpr(p, "<=") or isOpr(p, "<>") or isOpr(p, "!=") or isKeyw(p, "is") or isKeyw(p, "like"): @@ -664,7 +664,7 @@ proc parseExpr(p: var SqlParser): SqlNode proc identOrLiteral(p: var SqlParser): SqlNode = case p.tok.kind - of tkIdentifier, tkQuotedIdentifier: + of tkIdentifier, tkQuotedIdentifier: result = newNode(nkIdent, p.tok.literal) getTok(p) of tkStringConstant, tkEscapeConstant, tkDollarQuotedConstant: @@ -686,21 +686,21 @@ proc identOrLiteral(p: var SqlParser): SqlNode = getTok(p) result = parseExpr(p) eat(p, tkParRi) - else: + else: sqlError(p, "expression expected") getTok(p) # we must consume a token here to prevend endless loops! -proc primary(p: var SqlParser): SqlNode = - if p.tok.kind == tkOperator or isKeyw(p, "not"): +proc primary(p: var SqlParser): SqlNode = + if p.tok.kind == tkOperator or isKeyw(p, "not"): result = newNode(nkPrefix) result.add(newNode(nkIdent, p.tok.literal)) getTok(p) result.add(primary(p)) return result = identOrLiteral(p) - while true: + while true: case p.tok.kind - of tkParLe: + of tkParLe: var a = result result = newNode(nkCall) result.add(a) @@ -710,7 +710,7 @@ proc primary(p: var SqlParser): SqlNode = if p.tok.kind == tkComma: getTok(p) else: break eat(p, tkParRi) - of tkDot: + of tkDot: getTok(p) var a = result if p.tok.kind == tkDot: @@ -727,14 +727,14 @@ proc primary(p: var SqlParser): SqlNode = sqlError(p, "identifier expected") getTok(p) else: break - -proc lowestExprAux(p: var SqlParser, v: var SqlNode, limit: int): int = + +proc lowestExprAux(p: var SqlParser, v: var SqlNode, limit: int): int = var v2, node, opNode: SqlNode v = primary(p) # expand while operators have priorities higher than 'limit' var opPred = getPrecedence(p) result = opPred - while opPred > limit: + while opPred > limit: node = newNode(nkInfix) opNode = newNode(nkIdent, p.tok.literal) getTok(p) @@ -744,8 +744,8 @@ proc lowestExprAux(p: var SqlParser, v: var SqlNode, limit: int): int = node.add(v2) v = node opPred = getPrecedence(p) - -proc parseExpr(p: var SqlParser): SqlNode = + +proc parseExpr(p: var SqlParser): SqlNode = discard lowestExprAux(p, result, - 1) proc parseTableName(p: var SqlParser): SqlNode = @@ -765,7 +765,7 @@ proc parseColumnReference(p: var SqlParser): SqlNode = result.add(parseTableName(p)) eat(p, tkParRi) -proc parseCheck(p: var SqlParser): SqlNode = +proc parseCheck(p: var SqlParser): SqlNode = getTok(p) result = newNode(nkCheck) result.add(parseExpr(p)) @@ -817,9 +817,9 @@ proc parseColumnDef(p: var SqlParser): SqlNode = result.add(newNode(nkIdent, p.tok.literal)) getTok(p) result.add(parseDataType(p)) - parseColumnConstraints(p, result) + parseColumnConstraints(p, result) -proc parseIfNotExists(p: var SqlParser, k: SqlNodeKind): SqlNode = +proc parseIfNotExists(p: var SqlParser, k: SqlNodeKind): SqlNode = getTok(p) if isKeyw(p, "if"): getTok(p) @@ -880,7 +880,7 @@ proc parseTableDef(p: var SqlParser): SqlNode = result.add(parseTableConstraint(p)) if p.tok.kind != tkComma: break eat(p, tkParRi) - + proc parseTypeDef(p: var SqlParser): SqlNode = result = parseIfNotExists(p, nkCreateType) expectIdent(p) @@ -966,7 +966,7 @@ proc parseUpdate(p: var SqlParser): SqlNode = result.add(parseWhere(p)) else: result.add(nil) - + proc parseDelete(p: var SqlParser): SqlNode = getTok(p) result = newNode(nkDelete) @@ -1018,14 +1018,14 @@ proc parseSelect(p: var SqlParser): SqlNode = while true: getTok(p) h.add(parseExpr(p)) - if p.tok.kind != tkComma: break + if p.tok.kind != tkComma: break result.add(h) if isKeyw(p, "union"): result.add(newNode(nkUnion)) getTok(p) elif isKeyw(p, "intersect"): result.add(newNode(nkIntersect)) - getTok(p) + getTok(p) elif isKeyw(p, "except"): result.add(newNode(nkExcept)) getTok(p) @@ -1083,7 +1083,7 @@ proc open(p: var SqlParser, input: Stream, filename: string) = p.tok.kind = tkInvalid p.tok.literal = "" getTok(p) - + proc parse(p: var SqlParser): SqlNode = ## parses the content of `p`'s input stream and returns the SQL AST. ## Syntax errors raise an `EInvalidSql` exception. @@ -1094,13 +1094,13 @@ proc parse(p: var SqlParser): SqlNode = result.add(s) if result.len == 1: result = result.sons[0] - + proc close(p: var SqlParser) = ## closes the parser `p`. The associated input stream is closed too. close(SqlLexer(p)) proc parseSQL*(input: Stream, filename: string): SqlNode = - ## parses the SQL from `input` into an AST and returns the AST. + ## parses the SQL from `input` into an AST and returns the AST. ## `filename` is only used for error messages. ## Syntax errors raise an `EInvalidSql` exception. var p: SqlParser @@ -1114,7 +1114,7 @@ proc ra(n: SqlNode, s: var string, indent: int) proc rs(n: SqlNode, s: var string, indent: int, prefix = "(", suffix = ")", - sep = ", ") = + sep = ", ") = if n.len > 0: s.add(prefix) for i in 0 .. n.len-1: @@ -1162,7 +1162,7 @@ proc ra(n: SqlNode, s: var string, indent: int) = ra(n.sons[1], s, indent) s.add(')') of nkInfix: - s.add('(') + s.add('(') ra(n.sons[1], s, indent) s.add(' ') ra(n.sons[0], s, indent) @@ -1207,13 +1207,13 @@ proc ra(n: SqlNode, s: var string, indent: int) = s.add("insert into ") ra(n.sons[0], s, indent) ra(n.sons[1], s, indent) - if n.sons[2].kind == nkDefault: + if n.sons[2].kind == nkDefault: s.add("default values") else: s.add("\nvalues ") ra(n.sons[2], s, indent) s.add(';') - of nkUpdate: + of nkUpdate: s.add("update ") ra(n.sons[0], s, indent) s.add(" set ") @@ -1225,7 +1225,7 @@ proc ra(n: SqlNode, s: var string, indent: int) = ra(it, s, indent) ra(n.sons[L-1], s, indent) s.add(';') - of nkDelete: + of nkDelete: s.add("delete from ") ra(n.sons[0], s, indent) ra(n.sons[1], s, indent) @@ -1237,12 +1237,12 @@ proc ra(n: SqlNode, s: var string, indent: int) = rs(n.sons[0], s, indent, "", "", ", ") for i in 1 .. n.len-1: ra(n.sons[i], s, indent) s.add(';') - of nkSelectColumns: + of nkSelectColumns: assert(false) of nkAsgn: ra(n.sons[0], s, indent) s.add(" = ") - ra(n.sons[1], s, indent) + ra(n.sons[1], s, indent) of nkFrom: s.add("\nfrom ") rs(n, s, indent, "", "", ", ") @@ -1306,23 +1306,23 @@ proc ra(n: SqlNode, s: var string, indent: int) = s.add("enum ") rs(n, s, indent) -# What I want: +# What I want: # -#select(columns = [T1.all, T2.name], +#select(columns = [T1.all, T2.name], # fromm = [T1, T2], # where = T1.name ==. T2.name, # orderby = [name]): -# -#for row in dbQuery(db, """select x, y, z -# from a, b +# +#for row in dbQuery(db, """select x, y, z +# from a, b # where a.name = b.name"""): -# +# #select x, y, z: # fromm: Table1, Table2 # where: x.name == y.name #db.select(fromm = [t1, t2], where = t1.name == t2.name): -#for x, y, z in db.select(fromm = a, b where = a.name == b.name): +#for x, y, z in db.select(fromm = a, b where = a.name == b.name): # writeLine x, y, z proc renderSQL*(n: SqlNode): string = @@ -1338,7 +1338,7 @@ when not defined(testing) and isMainModule: happiness happiness ); CREATE INDEX table1_attr1 ON table1(attr1); - + SELECT * FROM myTab WHERE col1 = 'happy'; """), "stdin"))) diff --git a/lib/pure/parseurl.nim b/lib/pure/parseurl.nim index 56bf10768..6d58e8a73 100644 --- a/lib/pure/parseurl.nim +++ b/lib/pure/parseurl.nim @@ -19,7 +19,7 @@ import strutils type Url* = tuple[ ## represents a *Uniform Resource Locator* (URL) ## any optional component is "" if it does not exist - scheme, username, password, + scheme, username, password, hostname, port, path, query, anchor: string] {.deprecated: [TUrl: Url].} @@ -31,7 +31,7 @@ proc parseUrl*(url: string): Url {.deprecated.} = var hostname, port, path, query, anchor: string = "" var temp = "" - + if url[i] != '/': # url isn't a relative path while true: # Scheme @@ -48,7 +48,7 @@ proc parseUrl*(url: string): Url {.deprecated.} = password = username.substr(colon+1) username = username.substr(0, colon-1) temp.setLen(0) - inc(i) #Skip the @ + inc(i) #Skip the @ # hostname(subdomain, domain, port) if url[i] == '/' or url[i] == '\0': hostname = temp @@ -56,10 +56,10 @@ proc parseUrl*(url: string): Url {.deprecated.} = if colon >= 0: port = hostname.substr(colon+1) hostname = hostname.substr(0, colon-1) - + temp.setLen(0) break - + temp.add(url[i]) inc(i) @@ -75,7 +75,7 @@ proc parseUrl*(url: string): Url {.deprecated.} = else: path = temp temp.setLen(0) - + if url[i] == '\0': if temp[0] == '?': query = temp @@ -84,10 +84,10 @@ proc parseUrl*(url: string): Url {.deprecated.} = else: path = temp break - + temp.add(url[i]) inc(i) - + return (scheme, username, password, hostname, port, path, query, anchor) proc `$`*(u: Url): string {.deprecated.} = @@ -103,12 +103,12 @@ proc `$`*(u: Url): string {.deprecated.} = result.add(u.password) result.add("@") result.add(u.hostname) - if u.port.len > 0: + if u.port.len > 0: result.add(":") result.add(u.port) - if u.path.len > 0: + if u.path.len > 0: result.add("/") result.add(u.path) result.add(u.query) result.add(u.anchor) - + diff --git a/lib/pure/poly.nim b/lib/pure/poly.nim index 58dcdc1ad..c52300400 100644 --- a/lib/pure/poly.nim +++ b/lib/pure/poly.nim @@ -11,7 +11,7 @@ import math import strutils import numeric -type +type Poly* = object cofs:seq[float] @@ -40,7 +40,7 @@ proc `[]` *(p:Poly;idx:int):float= if idx<0 or idx>p.degree: return 0.0 return p.cofs[idx] - + proc `[]=` *(p:var Poly;idx:int,v:float)= ## Sets an coefficient of the polynomial by index. ## p[2] set the quadric term, p[3] the cubic etc. @@ -55,15 +55,15 @@ proc `[]=` *(p:var Poly;idx:int,v:float)= p.cofs[q]=0.0 #new-grown coefficients set to zero p.cofs[idx]=v - - + + iterator items*(p:Poly):float= ## Iterates through the coefficients of the polynomial. var i=p.degree while i>=0: yield p[i] - dec i - + dec i + proc clean*(p:var Poly;zerotol=0.0)= ## Removes leading zero coefficients of the polynomial. ## An optional tolerance can be given for what's considered zero. @@ -77,19 +77,19 @@ proc clean*(p:var Poly;zerotol=0.0)= if relen: p.cofs.setLen(n+1) -proc `$` *(p:Poly):string = +proc `$` *(p:Poly):string = ## Gets a somewhat reasonable string representation of the polynomial ## The format should be compatible with most online function plotters, ## for example directly in google search result="" var first=true #might skip + sign if first coefficient - + for idx in countdown(p.degree,0): let a=p[idx] - + if a==0.0: continue - + if a>= 0.0 and not first: result.add('+') first=false @@ -103,14 +103,14 @@ proc `$` *(p:Poly):string = if result=="": result="0" - + proc derivative*(p: Poly): Poly= ## Returns a new polynomial, which is the derivative of `p` newSeq[float](result.cofs,p.degree) for idx in 0..high(result.cofs): result.cofs[idx]=p.cofs[idx+1]*float(idx+1) - + proc diff*(p:Poly,x:float):float= ## Evaluates the differentiation of a polynomial with ## respect to `x` quickly using a modifed Horners method @@ -128,7 +128,7 @@ proc integral*(p:Poly):Poly= result.cofs[0]=0.0 #constant arbitrary term, use 0.0 for i in 1..high(result.cofs): result.cofs[i]=p.cofs[i-1]/float(i) - + proc integrate*(p:Poly;xmin,xmax:float):float= ## Computes the definite integral of `p` between `xmin` and `xmax` @@ -145,9 +145,9 @@ proc integrate*(p:Poly;xmin,xmax:float):float= s1 = s1*xmin+fac s2 = s2*xmax+fac dec n - + result=s2*xmax-s1*xmin - + proc initPoly*(cofs:varargs[float]):Poly= ## Initializes a polynomial with given coefficients. ## The most significant coefficient is first, so to create x^2-2x+3: @@ -158,7 +158,7 @@ proc initPoly*(cofs:varargs[float]):Poly= # reverse order of coefficients so indexing matches degree of # coefficient... result.cofs= @[] - for idx in countdown(cofs.len-1,0): + for idx in countdown(cofs.len-1,0): result.cofs.add(cofs[idx]) result.clean #remove leading zero terms @@ -167,49 +167,49 @@ proc initPoly*(cofs:varargs[float]):Poly= proc divMod*(p,d:Poly;q,r:var Poly)= ## Divides `p` with `d`, and stores the quotinent in `q` and ## the remainder in `d` - var + var pdeg=p.degree ddeg=d.degree power=p.degree-d.degree ratio:float - + r.cofs = p.cofs #initial remainder=numerator if power<0: #denominator is larger than numerator q.cofs= @ [0.0] #quotinent is 0.0 return # keep remainder as numerator - + q.cofs=newSeq[float](power+1) - + for i in countdown(pdeg,ddeg): ratio=r.cofs[i]/d.cofs[ddeg] - + q.cofs[i-ddeg]=ratio r.cofs[i]=0.0 - + for j in countup(0,=res[high(res)]+mergetol: #dont add equal roots. - res.add(br.rootx) + res.add(br.rootx) else: #this might be a 'touching' case, check function value against #zero tolerance if abs(br.rooty)<=zerotol: if res.len==0 or br.rootx>=res[high(res)]+mergetol: #dont add equal roots. - res.add(br.rootx) + res.add(br.rootx) proc roots*(p:Poly,tol=1.0e-9,zerotol=1.0e-6,mergetol=1.0e-12,maxiter=1000):seq[float]= diff --git a/lib/pure/rationals.nim b/lib/pure/rationals.nim index 8e1dbe464..60d09c71a 100644 --- a/lib/pure/rationals.nim +++ b/lib/pure/rationals.nim @@ -216,7 +216,7 @@ proc hash*[T](x: Rational[T]): Hash = h = h !& hash(copy.num) h = h !& hash(copy.den) result = !$h - + when isMainModule: var z = Rational[int](num: 0, den: 1) diff --git a/lib/pure/redis.nim b/lib/pure/redis.nim index b738e4094..e3f18a496 100644 --- a/lib/pure/redis.nim +++ b/lib/pure/redis.nim @@ -11,7 +11,7 @@ ## redis-server instance, send commands and receive replies. ## ## **Beware**: Most (if not all) functions that return a ``RedisString`` may -## return ``redisNil``, and functions which return a ``RedisList`` +## return ``redisNil``, and functions which return a ``RedisList`` ## may return ``nil``. import sockets, os, strutils, parseutils @@ -19,7 +19,7 @@ import sockets, os, strutils, parseutils const redisNil* = "\0\0" -type +type Pipeline = ref object enabled: bool buffer: string @@ -34,7 +34,7 @@ type socket: Socket connected: bool pipeline: Pipeline - + RedisStatus* = string RedisInteger* = BiggestInt RedisString* = string ## Bulk reply @@ -59,10 +59,10 @@ proc open*(host = "localhost", port = 6379.Port): Redis = if result.socket == invalidSocket: raiseOSError(osLastError()) result.socket.connect(host, port) - result.pipeline = newPipeline() + result.pipeline = newPipeline() proc raiseInvalidReply(expected, got: char) = - raise newException(ReplyError, + raise newException(ReplyError, "Expected '$1' at the beginning of a status reply got '$2'" % [$expected, $got]) @@ -90,16 +90,16 @@ proc parseStatus(r: Redis, line: string = ""): RedisStatus = raise newException(RedisError, strip(line)) if line[0] != '+': raiseInvalidReply('+', line[0]) - + return line.substr(1) # Strip '+' proc readStatus(r:Redis): RedisStatus = r.readSocket("PIPELINED") return r.parseStatus(line) - + proc parseInteger(r: Redis, line: string = ""): RedisInteger = if r.pipeline.enabled: return -1 - + #if line == "+QUEUED": # inside of multi # return -1 @@ -110,10 +110,10 @@ proc parseInteger(r: Redis, line: string = ""): RedisInteger = raise newException(RedisError, strip(line)) if line[0] != ':': raiseInvalidReply(':', line[0]) - + # Strip ':' if parseBiggestInt(line, result, 1) == 0: - raise newException(ReplyError, "Unable to parse integer.") + raise newException(ReplyError, "Unable to parse integer.") proc readInteger(r: Redis): RedisInteger = r.readSocket(-1) @@ -126,19 +126,19 @@ proc recv(sock: Socket, size: int): TaintedString = proc parseSingleString(r: Redis, line:string, allowMBNil = false): RedisString = if r.pipeline.enabled: return "" - + # Error. if line[0] == '-': raise newException(RedisError, strip(line)) - + # Some commands return a /bulk/ value or a /multi-bulk/ nil. Odd. if allowMBNil: if line == "*-1": return redisNil - + if line[0] != '$': raiseInvalidReply('$', line[0]) - + var numBytes = parseInt(line.substr(1)) if numBytes == -1: return redisNil @@ -168,7 +168,7 @@ proc parseArrayLines(r: Redis, countLine:string): RedisList = proc readArrayLines(r: Redis): RedisList = r.readSocket(nil) - return r.parseArrayLines(line) + return r.parseArrayLines(line) proc parseBulkString(r: Redis, allowMBNil = false, line:string = ""): RedisString = if r.pipeline.enabled: return "" @@ -191,7 +191,7 @@ proc readNext(r: Redis): RedisList = of ':': @[$(r.parseInteger(line))] of '$': @[r.parseBulkString(true,line)] of '*': r.parseArrayLines(line) - else: + else: raise newException(ReplyError, "readNext failed on line: " & line) nil r.pipeline.expected -= 1 @@ -202,10 +202,10 @@ proc flushPipeline*(r: Redis, wasMulti = false): RedisList = if r.pipeline.buffer.len > 0: r.socket.send(r.pipeline.buffer) r.pipeline.buffer = "" - + r.pipeline.enabled = false result = @[] - + var tot = r.pipeline.expected for i in 0..tot-1: @@ -232,7 +232,7 @@ proc sendCommand(r: Redis, cmd: string, args: varargs[string]) = for i in items(args): request.add("$" & $i.len() & "\c\L") request.add(i & "\c\L") - + if r.pipeline.enabled: r.pipeline.buffer.add(request) r.pipeline.expected += 1 @@ -249,7 +249,7 @@ proc sendCommand(r: Redis, cmd: string, arg1: string, for i in items(args): request.add("$" & $i.len() & "\c\L") request.add(i & "\c\L") - + if r.pipeline.enabled: r.pipeline.expected += 1 r.pipeline.buffer.add(request) @@ -275,7 +275,7 @@ proc expire*(r: Redis, key: string, seconds: int): bool = return r.readInteger() == 1 proc expireAt*(r: Redis, key: string, timestamp: int): bool = - ## Set the expiration for a key as a UNIX timestamp. Returns `false` + ## Set the expiration for a key as a UNIX timestamp. Returns `false` ## if the key could not be found or the timeout could not be set. r.sendCommand("EXPIREAT", key, $timestamp) return r.readInteger() == 1 @@ -301,7 +301,7 @@ proc scan*(r: Redis, cursor: var BiggestInt, pattern: string): RedisList = cursor = strutils.parseBiggestInt(reply[0]) return reply[1..high(reply)] -proc scan*(r: Redis, cursor: var BiggestInt, pattern: string, count: int): RedisList = +proc scan*(r: Redis, cursor: var BiggestInt, pattern: string, count: int): RedisList = ## Find all keys matching the given pattern and yield it to client in portions ## using cursor as a client query identifier. r.sendCommand("SCAN", $cursor, ["MATCH", pattern, "COUNT", $count]) @@ -315,11 +315,11 @@ proc move*(r: Redis, key: string, db: int): bool = return r.readInteger() == 1 proc persist*(r: Redis, key: string): bool = - ## Remove the expiration from a key. + ## Remove the expiration from a key. ## Returns `true` when the timeout was removed. r.sendCommand("PERSIST", key) return r.readInteger() == 1 - + proc randomKey*(r: Redis): RedisString = ## Return a random key from the keyspace r.sendCommand("RANDOMKEY") @@ -327,11 +327,11 @@ proc randomKey*(r: Redis): RedisString = proc rename*(r: Redis, key, newkey: string): RedisStatus = ## Rename a key. - ## + ## ## **WARNING:** Overwrites `newkey` if it exists! r.sendCommand("RENAME", key, newkey) raiseNoOK(r.readStatus(), r.pipeline.enabled) - + proc renameNX*(r: Redis, key, newkey: string): bool = ## Same as ``rename`` but doesn't continue if `newkey` exists. ## Returns `true` if key was renamed. @@ -342,12 +342,12 @@ proc ttl*(r: Redis, key: string): RedisInteger = ## Get the time to live for a key r.sendCommand("TTL", key) return r.readInteger() - + proc keyType*(r: Redis, key: string): RedisStatus = ## Determine the type stored at key r.sendCommand("TYPE", key) return r.readStatus() - + # Strings @@ -360,12 +360,12 @@ proc decr*(r: Redis, key: string): RedisInteger = ## Decrement the integer value of a key by one r.sendCommand("DECR", key) return r.readInteger() - + proc decrBy*(r: Redis, key: string, decrement: int): RedisInteger = ## Decrement the integer value of a key by the given number r.sendCommand("DECRBY", key, $decrement) return r.readInteger() - + proc get*(r: Redis, key: string): RedisString = ## Get the value of a key. Returns `redisNil` when `key` doesn't exist. r.sendCommand("GET", key) @@ -397,7 +397,7 @@ proc incrBy*(r: Redis, key: string, increment: int): RedisInteger = r.sendCommand("INCRBY", key, $increment) return r.readInteger() -proc setk*(r: Redis, key, value: string) = +proc setk*(r: Redis, key, value: string) = ## Set the string value of a key. ## ## NOTE: This function had to be renamed due to a clash with the `set` type. @@ -410,18 +410,18 @@ proc setNX*(r: Redis, key, value: string): bool = r.sendCommand("SETNX", key, value) return r.readInteger() == 1 -proc setBit*(r: Redis, key: string, offset: int, +proc setBit*(r: Redis, key: string, offset: int, value: string): RedisInteger = ## Sets or clears the bit at offset in the string value stored at key r.sendCommand("SETBIT", key, $offset, value) return r.readInteger() - + proc setEx*(r: Redis, key: string, seconds: int, value: string): RedisStatus = ## Set the value and expiration of a key r.sendCommand("SETEX", key, $seconds, value) raiseNoOK(r.readStatus(), r.pipeline.enabled) -proc setRange*(r: Redis, key: string, offset: int, +proc setRange*(r: Redis, key: string, offset: int, value: string): RedisInteger = ## Overwrite part of a string at key starting at the specified offset r.sendCommand("SETRANGE", key, $offset, value) @@ -474,7 +474,7 @@ proc hMGet*(r: Redis, key: string, fields: varargs[string]): RedisList = r.sendCommand("HMGET", key, fields) return r.readArray() -proc hMSet*(r: Redis, key: string, +proc hMSet*(r: Redis, key: string, fieldValues: openArray[tuple[field, value: string]]) = ## Set multiple hash fields to multiple values var args = @[key] @@ -488,7 +488,7 @@ proc hSet*(r: Redis, key, field, value: string): RedisInteger = ## Set the string value of a hash field r.sendCommand("HSET", key, field, value) return r.readInteger() - + proc hSetNX*(r: Redis, key, field, value: string): RedisInteger = ## Set the value of a hash field, only if the field does **not** exist r.sendCommand("HSETNX", key, field, value) @@ -498,11 +498,11 @@ proc hVals*(r: Redis, key: string): RedisList = ## Get all the values in a hash r.sendCommand("HVALS", key) return r.readArray() - + # Lists proc bLPop*(r: Redis, keys: varargs[string], timeout: int): RedisList = - ## Remove and get the *first* element in a list, or block until + ## Remove and get the *first* element in a list, or block until ## one is available var args: seq[string] = @[] for i in items(keys): args.add(i) @@ -511,7 +511,7 @@ proc bLPop*(r: Redis, keys: varargs[string], timeout: int): RedisList = return r.readArray() proc bRPop*(r: Redis, keys: varargs[string], timeout: int): RedisList = - ## Remove and get the *last* element in a list, or block until one + ## Remove and get the *last* element in a list, or block until one ## is available. var args: seq[string] = @[] for i in items(keys): args.add(i) @@ -539,7 +539,7 @@ proc lInsert*(r: Redis, key: string, before: bool, pivot, value: string): var pos = if before: "BEFORE" else: "AFTER" r.sendCommand("LINSERT", key, pos, pivot, value) return r.readInteger() - + proc lLen*(r: Redis, key: string): RedisInteger = ## Get the length of a list r.sendCommand("LLEN", key) @@ -553,7 +553,7 @@ proc lPop*(r: Redis, key: string): RedisString = proc lPush*(r: Redis, key, value: string, create: bool = true): RedisInteger = ## Prepend a value to a list. Returns the length of the list after the push. ## The ``create`` param specifies whether a list should be created if it - ## doesn't exist at ``key``. More specifically if ``create`` is true, `LPUSH` + ## doesn't exist at ``key``. More specifically if ``create`` is true, `LPUSH` ## will be used, otherwise `LPUSHX`. if create: r.sendCommand("LPUSH", key, value) @@ -562,7 +562,7 @@ proc lPush*(r: Redis, key, value: string, create: bool = true): RedisInteger = return r.readInteger() proc lRange*(r: Redis, key: string, start, stop: int): RedisList = - ## Get a range of elements from a list. Returns `nil` when `key` + ## Get a range of elements from a list. Returns `nil` when `key` ## doesn't exist. r.sendCommand("LRANGE", key, $start, $stop) return r.readArray() @@ -587,16 +587,16 @@ proc rPop*(r: Redis, key: string): RedisString = ## Remove and get the last element in a list r.sendCommand("RPOP", key) return r.readBulkString() - + proc rPopLPush*(r: Redis, source, destination: string): RedisString = ## Remove the last element in a list, append it to another list and return it r.sendCommand("RPOPLPUSH", source, destination) return r.readBulkString() - + proc rPush*(r: Redis, key, value: string, create: bool = true): RedisInteger = ## Append a value to a list. Returns the length of the list after the push. ## The ``create`` param specifies whether a list should be created if it - ## doesn't exist at ``key``. More specifically if ``create`` is true, `RPUSH` + ## doesn't exist at ``key``. More specifically if ``create`` is true, `RPUSH` ## will be used, otherwise `RPUSHX`. if create: r.sendCommand("RPUSH", key, value) @@ -676,7 +676,7 @@ proc sunion*(r: Redis, keys: varargs[string]): RedisList = proc sunionstore*(r: Redis, destination: string, key: varargs[string]): RedisInteger = - ## Add multiple sets and store the resulting set in a key + ## Add multiple sets and store the resulting set in a key r.sendCommand("SUNIONSTORE", destination, key) return r.readInteger() @@ -710,16 +710,16 @@ proc zinterstore*(r: Redis, destination: string, numkeys: string, ## a new key var args = @[destination, numkeys] for i in items(keys): args.add(i) - + if weights.len != 0: args.add("WITHSCORE") for i in items(weights): args.add(i) if aggregate.len != 0: args.add("AGGREGATE") args.add(aggregate) - + r.sendCommand("ZINTERSTORE", args) - + return r.readInteger() proc zrange*(r: Redis, key: string, start: string, stop: string, @@ -731,18 +731,18 @@ proc zrange*(r: Redis, key: string, start: string, stop: string, r.sendCommand("ZRANGE", "WITHSCORES", key, start, stop) return r.readArray() -proc zrangebyscore*(r: Redis, key: string, min: string, max: string, +proc zrangebyscore*(r: Redis, key: string, min: string, max: string, withScore: bool = false, limit: bool = false, limitOffset: int = 0, limitCount: int = 0): RedisList = ## Return a range of members in a sorted set, by score var args = @[key, min, max] - + if withScore: args.add("WITHSCORE") - if limit: + if limit: args.add("LIMIT") args.add($limitOffset) args.add($limitCount) - + r.sendCommand("ZRANGEBYSCORE", args) return r.readArray() @@ -770,26 +770,26 @@ proc zremrangebyscore*(r: Redis, key: string, min: string, proc zrevrange*(r: Redis, key: string, start: string, stop: string, withScore: bool): RedisList = - ## Return a range of members in a sorted set, by index, + ## Return a range of members in a sorted set, by index, ## with scores ordered from high to low if withScore: r.sendCommand("ZREVRANGE", "WITHSCORE", key, start, stop) else: r.sendCommand("ZREVRANGE", key, start, stop) return r.readArray() -proc zrevrangebyscore*(r: Redis, key: string, min: string, max: string, +proc zrevrangebyscore*(r: Redis, key: string, min: string, max: string, withScore: bool = false, limit: bool = false, limitOffset: int = 0, limitCount: int = 0): RedisList = ## Return a range of members in a sorted set, by score, with ## scores ordered from high to low var args = @[key, min, max] - + if withScore: args.add("WITHSCORE") - if limit: + if limit: args.add("LIMIT") args.add($limitOffset) args.add($limitCount) - + r.sendCommand("ZREVRANGEBYSCORE", args) return r.readArray() @@ -807,24 +807,24 @@ proc zscore*(r: Redis, key: string, member: string): RedisString = proc zunionstore*(r: Redis, destination: string, numkeys: string, keys: openArray[string], weights: openArray[string] = [], aggregate: string = ""): RedisInteger = - ## Add multiple sorted sets and store the resulting sorted set in a new key + ## Add multiple sorted sets and store the resulting sorted set in a new key var args = @[destination, numkeys] for i in items(keys): args.add(i) - + if weights.len != 0: args.add("WEIGHTS") for i in items(weights): args.add(i) if aggregate.len != 0: args.add("AGGREGATE") args.add(aggregate) - + r.sendCommand("ZUNIONSTORE", args) - + return r.readInteger() # HyperLogLog -proc pfadd*(r: Redis, key: string, elements: varargs[string]): RedisInteger = +proc pfadd*(r: Redis, key: string, elements: varargs[string]): RedisInteger = ## Add variable number of elements into special 'HyperLogLog' set type r.sendCommand("PFADD", key, elements) return r.readInteger() @@ -864,7 +864,7 @@ proc subscribe*(r: Redis, channel: openarray[string]): ???? = return ??? proc unsubscribe*(r: Redis, [channel: openarray[string], : string): ???? = - ## Stop listening for messages posted to the given channels + ## Stop listening for messages posted to the given channels r.socket.send("UNSUBSCRIBE $# $#\c\L" % [[channel.join(), ]) return ??? @@ -879,12 +879,12 @@ proc discardMulti*(r: Redis) = proc exec*(r: Redis): RedisList = ## Execute all commands issued after MULTI - r.sendCommand("EXEC") + r.sendCommand("EXEC") r.pipeline.enabled = false # Will reply with +OK for MULTI/EXEC and +QUEUED for every command # between, then with the results return r.flushPipeline(true) - + proc multi*(r: Redis) = ## Mark the start of a transaction block @@ -898,7 +898,7 @@ proc unwatch*(r: Redis) = raiseNoOK(r.readStatus(), r.pipeline.enabled) proc watch*(r: Redis, key: varargs[string]) = - ## Watch the given keys to determine execution of the MULTI/EXEC block + ## Watch the given keys to determine execution of the MULTI/EXEC block r.sendCommand("WATCH", key) raiseNoOK(r.readStatus(), r.pipeline.enabled) @@ -925,7 +925,7 @@ proc quit*(r: Redis) = raiseNoOK(r.readStatus(), r.pipeline.enabled) proc select*(r: Redis, index: int): RedisStatus = - ## Change the selected database for the current connection + ## Change the selected database for the current connection r.sendCommand("SELECT", $index) return r.readStatus() @@ -1016,7 +1016,7 @@ proc slaveof*(r: Redis, host: string, port: string) = iterator hPairs*(r: Redis, key: string): tuple[key, value: string] = ## Iterator for keys and values in a hash. - var + var contents = r.hGetAll(key) k = "" for i in items(contents): @@ -1031,9 +1031,9 @@ proc someTests(r: Redis, how: SendMode):seq[string] = if how == pipelined: r.startPipelining() - elif how == multiple: + elif how == multiple: r.multi() - + r.setk("nim:test", "Testing something.") r.setk("nim:utf8", "こんにちは") r.setk("nim:esc", "\\ths ągt\\") @@ -1054,7 +1054,7 @@ proc someTests(r: Redis, how: SendMode):seq[string] = for i in items(p): if not isNil(i): - list.add(i) + list.add(i) list.add(r.debugObject("mylist")) @@ -1079,7 +1079,7 @@ proc assertListsIdentical(listA, listB: seq[string]) = for item in listA: assert(item == listB[i]) i = i + 1 - + when not defined(testing) and isMainModule: when false: var r = open() diff --git a/lib/pure/romans.nim b/lib/pure/romans.nim index 0c182843a..18c04ef58 100644 --- a/lib/pure/romans.nim +++ b/lib/pure/romans.nim @@ -11,7 +11,7 @@ ## See http://en.wikipedia.org/wiki/Roman_numerals for reference. const - RomanNumeralDigits* = {'I', 'i', 'V', 'v', 'X', 'x', 'L', 'l', 'C', 'c', + RomanNumeralDigits* = {'I', 'i', 'V', 'v', 'X', 'x', 'L', 'l', 'C', 'c', 'D', 'd', 'M', 'm'} ## set of all characters a Roman numeral may consist of proc romanToDecimal*(romanVal: string): int = @@ -28,7 +28,7 @@ proc romanToDecimal*(romanVal: string): int = of 'C', 'c': val = 100 of 'D', 'd': val = 500 of 'M', 'm': val = 1000 - else: + else: raise newException(EInvalidValue, "invalid roman numeral: " & $romanVal) if val >= prevVal: inc(result, val) diff --git a/lib/pure/ropes.nim b/lib/pure/ropes.nim index 5c7fedfe3..df7071642 100644 --- a/lib/pure/ropes.nim +++ b/lib/pure/ropes.nim @@ -29,7 +29,7 @@ const var cacheEnabled = false -type +type Rope* = ref RopeObj ## empty rope is represented by nil RopeObj {.acyclic.} = object left, right: Rope @@ -59,7 +59,7 @@ proc newRope(data: string): Rope = result.length = len(data) result.data = data -var +var cache {.threadvar.}: Rope # the root of the cache tree N {.threadvar.}: Rope # dummy rope needed for splay algorithm @@ -81,7 +81,7 @@ proc splay(s: string, tree: Rope, cmpres: var int): Rope = t.left = y.right y.right = t t = y - if t.left == nil: break + if t.left == nil: break r.left = t r = t t = t.left @@ -91,7 +91,7 @@ proc splay(s: string, tree: Rope, cmpres: var int): Rope = t.right = y.left y.left = t t = y - if t.right == nil: break + if t.right == nil: break le.right = t le = t t = t.right @@ -109,7 +109,7 @@ proc insertInCache(s: string, tree: Rope): Rope = if t == nil: result = newRope(s) when countCacheMisses: inc(misses) - return + return var cmp: int t = splay(s, t, cmp) if cmp == 0: @@ -197,7 +197,7 @@ proc add*(a: var Rope, b: Rope) {.rtl, extern: "nro$1Rope".} = proc add*(a: var Rope, b: string) {.rtl, extern: "nro$1Str".} = ## adds `b` to the rope `a`. a = a & b - + proc `[]`*(r: Rope, i: int): char {.rtl, extern: "nroCharAt".} = ## returns the character at position `i` in the rope `r`. This is quite ## expensive! Worst-case: O(n). If ``i >= r.len``, ``\0`` is returned. @@ -250,7 +250,7 @@ when false: proc compiledArg(idx: int): Rope = new(result) result.length = -idx - + proc compileFrmt(frmt: string): Rope = var i = 0 var length = len(frmt) @@ -272,7 +272,7 @@ when false: while true: j = j * 10 + ord(frmt[i]) - ord('0') inc(i) - if frmt[i] notin {'0'..'9'}: break + if frmt[i] notin {'0'..'9'}: break add(s, compiledArg(j)) of '{': inc(i) @@ -345,7 +345,7 @@ const proc equalsFile*(r: Rope, f: File): bool {.rtl, extern: "nro$1File".} = ## returns true if the contents of the file `f` equal `r`. - var + var buf: array[bufSize, char] bpos = buf.len blen = buf.len @@ -363,7 +363,7 @@ proc equalsFile*(r: Rope, f: File): bool {.rtl, extern: "nro$1File".} = return let n = min(blen - bpos, slen - spos) # TODO There's gotta be a better way of comparing here... - if not equalMem(addr(buf[bpos]), + if not equalMem(addr(buf[bpos]), cast[pointer](cast[int](cstring(s))+spos), n): result = false return diff --git a/lib/pure/scgi.nim b/lib/pure/scgi.nim index 3de422c87..1d54b4591 100644 --- a/lib/pure/scgi.nim +++ b/lib/pure/scgi.nim @@ -8,13 +8,13 @@ # ## This module implements helper procs for SCGI applications. Example: -## +## ## .. code-block:: Nim ## ## import strtabs, sockets, scgi ## ## var counter = 0 -## proc handleRequest(client: Socket, input: string, +## proc handleRequest(client: Socket, input: string, ## headers: StringTableRef): bool {.procvar.} = ## inc(counter) ## client.writeStatusOkTextContent() @@ -37,19 +37,19 @@ import sockets, strutils, os, strtabs, asyncio type ScgiError* = object of IOError ## the exception that is raised, if a SCGI error occurs -proc raiseScgiError*(msg: string) {.noreturn.} = +proc raiseScgiError*(msg: string) {.noreturn.} = ## raises an ScgiError exception with message `msg`. var e: ref ScgiError new(e) e.msg = msg raise e -proc parseWord(inp: string, outp: var string, start: int): int = +proc parseWord(inp: string, outp: var string, start: int): int = result = start while inp[result] != '\0': inc(result) outp = substr(inp, start, result-1) -proc parseHeaders(s: string, L: int): StringTableRef = +proc parseHeaders(s: string, L: int): StringTableRef = result = newStringTable() var i = 0 while i < L: @@ -59,12 +59,12 @@ proc parseHeaders(s: string, L: int): StringTableRef = result[key] = val if s[i] == ',': inc(i) else: raiseScgiError("',' after netstring expected") - -proc recvChar(s: Socket): char = + +proc recvChar(s: Socket): char = var c: char - if recv(s, addr(c), sizeof(c)) == sizeof(c): + if recv(s, addr(c), sizeof(c)) == sizeof(c): result = c - + type ScgiState* = object of RootObj ## SCGI state object server: Socket @@ -72,22 +72,22 @@ type client*: Socket ## the client socket to send data to headers*: StringTableRef ## the parsed headers input*: string ## the input buffer - - + + # Async - + ClientMode = enum ClientReadChar, ClientReadHeaders, ClientReadContent - + AsyncClient = ref object c: AsyncSocket mode: ClientMode dataLen: int headers: StringTableRef ## the parsed headers input: string ## the input buffer - + AsyncScgiStateObj = object - handleRequest: proc (client: AsyncSocket, + handleRequest: proc (client: AsyncSocket, input: string, headers: StringTableRef) {.closure, gcsafe.} asyncServer: AsyncSocket @@ -98,19 +98,19 @@ type PAsyncScgiState: AsyncScgiState, scgiError: raiseScgiError].} proc recvBuffer(s: var ScgiState, L: int) = - if L > s.bufLen: + if L > s.bufLen: s.bufLen = L s.input = newString(L) - if L > 0 and recv(s.client, cstring(s.input), L) != L: + if L > 0 and recv(s.client, cstring(s.input), L) != L: raiseScgiError("could not read all data") setLen(s.input, L) - + proc open*(s: var ScgiState, port = Port(4000), address = "127.0.0.1", - reuseAddr = false) = + reuseAddr = false) = ## opens a connection. s.bufLen = 4000 s.input = newString(s.bufLen) # will be reused - + s.server = socket() if s.server == invalidSocket: raiseOSError(osLastError()) new(s.client) # Initialise s.client for `next` @@ -120,12 +120,12 @@ proc open*(s: var ScgiState, port = Port(4000), address = "127.0.0.1", s.server.setSockOpt(OptReuseAddr, true) bindAddr(s.server, port, address) listen(s.server) - -proc close*(s: var ScgiState) = + +proc close*(s: var ScgiState) = ## closes the connection. s.server.close() -proc next*(s: var ScgiState, timeout: int = -1): bool = +proc next*(s: var ScgiState, timeout: int = -1): bool = ## proceed to the first/next request. Waits ``timeout`` milliseconds for a ## request, if ``timeout`` is `-1` then this function will never time out. ## Returns `true` if a new request has been processed. @@ -139,18 +139,18 @@ proc next*(s: var ScgiState, timeout: int = -1): bool = if d == '\0': s.client.close() return false - if d notin strutils.Digits: + if d notin strutils.Digits: if d != ':': raiseScgiError("':' after length expected") break - L = L * 10 + ord(d) - ord('0') + L = L * 10 + ord(d) - ord('0') recvBuffer(s, L+1) s.headers = parseHeaders(s.input, L) if s.headers["SCGI"] != "1": raiseScgiError("SCGI Version 1 expected") L = parseInt(s.headers["CONTENT_LENGTH"]) recvBuffer(s, L) return true - -proc writeStatusOkTextContent*(c: Socket, contentType = "text/html") = + +proc writeStatusOkTextContent*(c: Socket, contentType = "text/html") = ## sends the following string to the socket `c`:: ## ## Status: 200 OK\r\LContent-Type: text/html\r\L\r\L @@ -159,9 +159,9 @@ proc writeStatusOkTextContent*(c: Socket, contentType = "text/html") = c.send("Status: 200 OK\r\L" & "Content-Type: $1\r\L\r\L" % contentType) -proc run*(handleRequest: proc (client: Socket, input: string, +proc run*(handleRequest: proc (client: Socket, input: string, headers: StringTableRef): bool {.nimcall,gcsafe.}, - port = Port(4000)) = + port = Port(4000)) = ## encapsulates the SCGI object and main loop. var s: ScgiState s.open(port) @@ -197,7 +197,7 @@ proc checkCloseSocket(client: AsyncClient) = s.close() s.delHandleWrite() else: client.c.close() - + proc handleClientRead(client: AsyncClient, s: AsyncScgiState) = case client.mode of ClientReadChar: @@ -223,7 +223,7 @@ proc handleClientRead(client: AsyncClient, s: AsyncScgiState) = client.headers = parseHeaders(client.input, client.input.len-1) if client.headers["SCGI"] != "1": raiseScgiError("SCGI Version 1 expected") client.input = "" # For next part - + let contentLen = parseInt(client.headers["CONTENT_LENGTH"]) if contentLen > 0: client.mode = ClientReadContent @@ -250,12 +250,12 @@ proc handleAccept(sock: AsyncSocket, s: AsyncScgiState) = accept(s.asyncServer, client) var asyncClient = AsyncClient(c: client, mode: ClientReadChar, dataLen: 0, headers: newStringTable(), input: "") - client.handleRead = + client.handleRead = proc (sock: AsyncSocket) = handleClientRead(asyncClient, s) s.disp.register(client) -proc open*(handleRequest: proc (client: AsyncSocket, +proc open*(handleRequest: proc (client: AsyncSocket, input: string, headers: StringTableRef) {. closure, gcsafe.}, port = Port(4000), address = "127.0.0.1", @@ -286,7 +286,7 @@ proc close*(s: AsyncScgiState) = when false: var counter = 0 - proc handleRequest(client: Socket, input: string, + proc handleRequest(client: Socket, input: string, headers: StringTableRef): bool {.procvar.} = inc(counter) client.writeStatusOkTextContent() diff --git a/lib/pure/smtp.nim b/lib/pure/smtp.nim index c1bc259a5..b2adac2f3 100644 --- a/lib/pure/smtp.nim +++ b/lib/pure/smtp.nim @@ -7,25 +7,25 @@ # distribution, for details about the copyright. # -## This module implements the SMTP client protocol as specified by RFC 5321, +## This module implements the SMTP client protocol as specified by RFC 5321, ## this can be used to send mail to any SMTP Server. -## -## This module also implements the protocol used to format messages, +## +## This module also implements the protocol used to format messages, ## as specified by RFC 2822. -## +## ## Example gmail use: -## -## +## +## ## .. code-block:: Nim -## var msg = createMessage("Hello from Nim's SMTP", -## "Hello!.\n Is this awesome or what?", +## var msg = createMessage("Hello from Nim's SMTP", +## "Hello!.\n Is this awesome or what?", ## @["foo@gmail.com"]) ## var smtp = connect("smtp.gmail.com", 465, true, true) ## smtp.auth("username", "password") ## smtp.sendmail("username@gmail.com", @["foo@gmail.com"], $msg) -## -## -## For SSL support this module relies on OpenSSL. If you want to +## +## +## For SSL support this module relies on OpenSSL. If you want to ## enable SSL, compile with ``-d:ssl``. import net, strutils, strtabs, base64, os @@ -35,14 +35,14 @@ type Smtp* = object sock: Socket debug: bool - + Message* = object msgTo: seq[string] msgCc: seq[string] msgSubject: string msgOtherHeaders: StringTableRef msgBody: string - + ReplyError* = object of IOError AsyncSmtp* = ref object @@ -84,7 +84,7 @@ when not defined(ssl): else: let defaultSSLContext = newContext(verifyMode = CVerifyNone) -proc connect*(address: string, port = Port(25), +proc connect*(address: string, port = Port(25), ssl = false, debug = false, sslContext = defaultSSLContext): Smtp = ## Establishes a connection with a SMTP server. @@ -94,17 +94,17 @@ proc connect*(address: string, port = Port(25), when compiledWithSsl: sslContext.wrapSocket(result.sock) else: - raise newException(ESystem, + raise newException(ESystem, "SMTP module compiled without SSL support") result.sock.connect(address, port) result.debug = debug - + result.checkReply("220") result.debugSend("HELO " & address & "\c\L") result.checkReply("250") proc auth*(smtp: var Smtp, username, password: string) = - ## Sends an AUTH command to the server to login as the `username` + ## Sends an AUTH command to the server to login as the `username` ## using `password`. ## May fail with ReplyError. @@ -113,13 +113,13 @@ proc auth*(smtp: var Smtp, username, password: string) = # i.e "334 VXNlcm5hbWU6" smtp.debugSend(encode(username) & "\c\L") smtp.checkReply("334") # TODO: Same as above, only "Password:" (I think?) - + smtp.debugSend(encode(password) & "\c\L") smtp.checkReply("235") # Check whether the authentification was successful. proc sendmail*(smtp: var Smtp, fromaddr: string, toaddrs: seq[string], msg: string) = - ## Sends `msg` from `fromaddr` to `toaddr`. + ## Sends `msg` from `fromaddr` to `toaddr`. ## Messages may be formed using ``createMessage`` by converting the ## Message into a string. @@ -128,7 +128,7 @@ proc sendmail*(smtp: var Smtp, fromaddr: string, for address in items(toaddrs): smtp.debugSend("RCPT TO:<" & address & ">\c\L") smtp.checkReply("250") - + # Send the message smtp.debugSend("DATA " & "\c\L") smtp.checkReply("354") @@ -175,7 +175,7 @@ proc `$`*(msg: Message): string = result.add("\c\L") result.add(msg.msgBody) - + proc newAsyncSmtp*(address: string, port: Port, useSsl = false, sslContext = defaultSslContext): AsyncSmtp = ## Creates a new ``AsyncSmtp`` instance. @@ -189,7 +189,7 @@ proc newAsyncSmtp*(address: string, port: Port, useSsl = false, when compiledWithSsl: sslContext.wrapSocket(result.sock) else: - raise newException(ESystem, + raise newException(ESystem, "SMTP module compiled without SSL support") proc quitExcpt(smtp: AsyncSmtp, msg: string): Future[void] = @@ -216,7 +216,7 @@ proc connect*(smtp: AsyncSmtp) {.async.} = await smtp.checkReply("250") proc auth*(smtp: AsyncSmtp, username, password: string) {.async.} = - ## Sends an AUTH command to the server to login as the `username` + ## Sends an AUTH command to the server to login as the `username` ## using `password`. ## May fail with ReplyError. @@ -225,7 +225,7 @@ proc auth*(smtp: AsyncSmtp, username, password: string) {.async.} = # i.e "334 VXNlcm5hbWU6" await smtp.sock.send(encode(username) & "\c\L") await smtp.checkReply("334") # TODO: Same as above, only "Password:" (I think?) - + await smtp.sock.send(encode(password) & "\c\L") await smtp.checkReply("235") # Check whether the authentification was successful. @@ -240,7 +240,7 @@ proc sendMail*(smtp: AsyncSmtp, fromAddr: string, for address in items(toAddrs): await smtp.sock.send("RCPT TO:<" & address & ">\c\L") await smtp.checkReply("250") - + # Send the message await smtp.sock.send("DATA " & "\c\L") await smtp.checkReply("354") @@ -254,24 +254,24 @@ proc close*(smtp: AsyncSmtp) {.async.} = smtp.sock.close() when not defined(testing) and isMainModule: - #var msg = createMessage("Test subject!", + #var msg = createMessage("Test subject!", # "Hello, my name is dom96.\n What\'s yours?", @["dominik@localhost"]) #echo(msg) #var smtp = connect("localhost", 25, False, True) #smtp.sendmail("root@localhost", @["dominik@localhost"], $msg) - + #echo(decode("a17sm3701420wbe.12")) proc main() {.async.} = var client = newAsyncSmtp("smtp.gmail.com", Port(465), true) await client.connect() await client.auth("johndoe", "foo") - var msg = createMessage("Hello from Nim's SMTP!", - "Hello!!!!.\n Is this awesome or what?", + var msg = createMessage("Hello from Nim's SMTP!", + "Hello!!!!.\n Is this awesome or what?", @["blah@gmail.com"]) echo(msg) await client.sendMail("blah@gmail.com", @["blah@gmail.com"], $msg) await client.close() - + waitFor main() diff --git a/lib/pure/sockets.nim b/lib/pure/sockets.nim index 18b2ab1e9..29f0bf87d 100644 --- a/lib/pure/sockets.nim +++ b/lib/pure/sockets.nim @@ -51,17 +51,17 @@ else: # Note: The enumerations are mapped to Window's constants. -when defined(ssl): +when defined(ssl): type SSLError* = object of Exception SSLCVerifyMode* = enum CVerifyNone, CVerifyPeer - + SSLProtVersion* = enum protSSLv2, protSSLv3, protTLSv1, protSSLv23 - + SSLContext* = distinct SSLCTX SSLAcceptResult* = enum @@ -93,11 +93,11 @@ type sslPeekChar: char of false: nil nonblocking: bool - + Socket* = ref SocketImpl - + Port* = distinct uint16 ## port type - + Domain* = enum ## domain, which specifies the protocol family of the ## created socket. Other domains than those that are listed ## here are unsupported. @@ -112,7 +112,7 @@ type SOCK_SEQPACKET = 5 ## reliable sequenced packet service Protocol* = enum ## third argument to `socket` proc - IPPROTO_TCP = 6, ## Transmission control protocol. + IPPROTO_TCP = 6, ## Transmission control protocol. IPPROTO_UDP = 17, ## User datagram protocol. IPPROTO_IP, ## Internet protocol. Unsupported on Windows. IPPROTO_IPV6, ## Internet Protocol Version 6. Unsupported on Windows. @@ -178,7 +178,7 @@ proc `==`*(a, b: Port): bool {.borrow.} proc `$`*(p: Port): string {.borrow.} ## returns the port number as a string -proc ntohl*(x: int32): int32 = +proc ntohl*(x: int32): int32 = ## Converts 32-bit integers from network to host byte order. ## On machines where the host byte order is the same as network byte order, ## this is a no-op; otherwise, it performs a 4-byte swap operation. @@ -206,7 +206,7 @@ proc htons*(x: int16): int16 = ## On machines where the host byte order is the same as network byte ## order, this is a no-op; otherwise, it performs a 2-byte swap operation. result = sockets.ntohs(x) - + when defined(Posix): proc toInt(domain: Domain): cint = case domain @@ -234,19 +234,19 @@ when defined(Posix): else: discard else: - proc toInt(domain: Domain): cint = + proc toInt(domain: Domain): cint = result = toU16(ord(domain)) proc toInt(typ: SockType): cint = result = cint(ord(typ)) - + proc toInt(p: Protocol): cint = result = cint(ord(p)) proc socket*(domain: Domain = AF_INET, typ: SockType = SOCK_STREAM, protocol: Protocol = IPPROTO_TCP, buffered = true): Socket = ## Creates a new socket; returns `InvalidSocket` if an error occurs. - + # TODO: Perhaps this should just raise EOS when an error occurs. when defined(Windows): result = newTSocket(winlean.socket(ord(domain), ord(typ), ord(protocol)), buffered) @@ -277,27 +277,27 @@ when defined(ssl): raise newException(system.IOError, "Certificate file could not be found: " & certFile) if keyFile != "" and not existsFile(keyFile): raise newException(system.IOError, "Key file could not be found: " & keyFile) - + if certFile != "": var ret = SSLCTXUseCertificateChainFile(ctx, certFile) if ret != 1: raiseSslError() - + # TODO: Password? www.rtfm.com/openssl-examples/part1.pdf if keyFile != "": if SSL_CTX_use_PrivateKey_file(ctx, keyFile, SSL_FILETYPE_PEM) != 1: raiseSslError() - + if SSL_CTX_check_private_key(ctx) != 1: raiseSslError("Verification of private key file failed.") proc newContext*(protVersion = protSSLv23, verifyMode = CVerifyPeer, certFile = "", keyFile = ""): SSLContext = ## Creates an SSL context. - ## - ## Protocol version specifies the protocol to use. SSLv2, SSLv3, TLSv1 are - ## are available with the addition of ``ProtSSLv23`` which allows for + ## + ## Protocol version specifies the protocol to use. SSLv2, SSLv3, TLSv1 are + ## are available with the addition of ``ProtSSLv23`` which allows for ## compatibility with all of them. ## ## There are currently only two options for verify mode; @@ -322,7 +322,7 @@ when defined(ssl): newCTX = SSL_CTX_new(SSLv3_method()) of protTLSv1: newCTX = SSL_CTX_new(TLSv1_method()) - + if newCTX.SSLCTXSetCipherList("ALL") != 1: raiseSslError() case verifyMode @@ -343,7 +343,7 @@ when defined(ssl): ## ## **Disclaimer**: This code is not well tested, may be very unsafe and ## prone to security vulnerabilities. - + socket.isSSL = true socket.sslContext = ctx socket.sslHandle = SSLNew(SSLCTX(socket.sslContext)) @@ -351,7 +351,7 @@ when defined(ssl): socket.sslHasPeekChar = false if socket.sslHandle == nil: raiseSslError() - + if SSLSetFd(socket.sslHandle, socket.fd) != 1: raiseSslError() @@ -382,7 +382,7 @@ proc raiseSocketError*(socket: Socket, err: int = -1, async = false) = of SSL_ERROR_SYSCALL, SSL_ERROR_SSL: raiseSslError() else: raiseSslError("Unknown Error") - + if err == -1 and not (when defined(ssl): socket.isSSL else: false): let lastError = osLastError() if async: @@ -397,15 +397,15 @@ proc raiseSocketError*(socket: Socket, err: int = -1, async = false) = else: raiseOSError(lastError) proc listen*(socket: Socket, backlog = SOMAXCONN) {.tags: [ReadIOEffect].} = - ## Marks ``socket`` as accepting connections. - ## ``Backlog`` specifies the maximum length of the + ## Marks ``socket`` as accepting connections. + ## ``Backlog`` specifies the maximum length of the ## queue of pending connections. if listen(socket.fd, cint(backlog)) < 0'i32: raiseOSError(osLastError()) proc invalidIp4(s: string) {.noreturn, noinline.} = raise newException(ValueError, "invalid ip4 address: " & s) -proc parseIp4*(s: string): BiggestInt = +proc parseIp4*(s: string): BiggestInt = ## parses an IP version 4 in dotted decimal form like "a.b.c.d". ## ## This is equivalent to `inet_ntoa`:idx:. @@ -469,8 +469,8 @@ proc bindAddr*(socket: Socket, port = Port(0), address = "") {. gaiNim(address, port, hints, aiList) if bindSocket(socket.fd, aiList.ai_addr, aiList.ai_addrlen.SockLen) < 0'i32: raiseOSError(osLastError()) - -proc getSockName*(socket: Socket): Port = + +proc getSockName*(socket: Socket): Port = ## returns the socket's associated port number. var name: Sockaddr_in when defined(Windows): @@ -485,14 +485,14 @@ proc getSockName*(socket: Socket): Port = raiseOSError(osLastError()) result = Port(sockets.ntohs(name.sin_port)) -template acceptAddrPlain(noClientRet, successRet: expr, +template acceptAddrPlain(noClientRet, successRet: expr, sslImplementation: stmt): stmt {.immediate.} = assert(client != nil) var sockAddress: Sockaddr_in var addrLen = sizeof(sockAddress).SockLen var sock = accept(server.fd, cast[ptr SockAddr](addr(sockAddress)), addr(addrLen)) - + if sock == osInvalidSocket: let err = osLastError() when defined(windows): @@ -537,7 +537,7 @@ proc acceptAddr*(server: Socket, client: var Socket, address: var string) {. ## The resulting client will inherit any properties of the server socket. For ## example: whether the socket is buffered or not. ## - ## **Note**: ``client`` must be initialised (with ``new``), this function + ## **Note**: ``client`` must be initialised (with ``new``), this function ## makes no effort to initialise the ``client`` variable. ## ## **Warning:** When using SSL with non-blocking sockets, it is best to use @@ -546,7 +546,7 @@ proc acceptAddr*(server: Socket, client: var Socket, address: var string) {. when defined(ssl): if server.isSSL: # We must wrap the client sock in a ssl context. - + server.sslContext.wrapSocket(client) let ret = SSLAccept(client.sslHandle) while ret <= 0: @@ -572,9 +572,9 @@ when defined(ssl): proc acceptAddrSSL*(server: Socket, client: var Socket, address: var string): SSLAcceptResult {. tags: [ReadIOEffect].} = - ## This procedure should only be used for non-blocking **SSL** sockets. + ## This procedure should only be used for non-blocking **SSL** sockets. ## It will immediately return with one of the following values: - ## + ## ## ``AcceptSuccess`` will be returned when a client has been successfully ## accepted and the handshake has been successfully performed between ## ``server`` and the newly connected client. @@ -591,7 +591,7 @@ when defined(ssl): if server.isSSL: client.setBlocking(false) # We must wrap the client sock in a ssl context. - + if not client.isSSL or client.sslHandle == nil: server.sslContext.wrapSocket(client) let ret = SSLAccept(client.sslHandle) @@ -623,10 +623,10 @@ when defined(ssl): proc accept*(server: Socket, client: var Socket) {.tags: [ReadIOEffect].} = ## Equivalent to ``acceptAddr`` but doesn't return the address, only the ## socket. - ## + ## ## **Note**: ``client`` must be initialised (with ``new``), this function ## makes no effort to initialise the ``client`` variable. - + var addrDummy = "" acceptAddr(server, client, addrDummy) @@ -662,7 +662,7 @@ proc close*(socket: Socket) = socket.sslHandle = nil proc getServByName*(name, proto: string): Servent {.tags: [ReadIOEffect].} = - ## Searches the database from the beginning and finds the first entry for + ## Searches the database from the beginning and finds the first entry for ## which the service name specified by ``name`` matches the s_name member ## and the protocol name specified by ``proto`` matches the s_proto member. ## @@ -676,10 +676,10 @@ proc getServByName*(name, proto: string): Servent {.tags: [ReadIOEffect].} = result.aliases = cstringArrayToSeq(s.s_aliases) result.port = Port(s.s_port) result.proto = $s.s_proto - -proc getServByPort*(port: Port, proto: string): Servent {.tags: [ReadIOEffect].} = - ## Searches the database from the beginning and finds the first entry for - ## which the port specified by ``port`` matches the s_port member and the + +proc getServByPort*(port: Port, proto: string): Servent {.tags: [ReadIOEffect].} = + ## Searches the database from the beginning and finds the first entry for + ## which the port specified by ``port`` matches the s_port member and the ## protocol name specified by ``proto`` matches the s_proto member. ## ## On posix this will search through the ``/etc/services`` file. @@ -697,20 +697,20 @@ proc getHostByAddr*(ip: string): Hostent {.tags: [ReadIOEffect].} = ## This function will lookup the hostname of an IP Address. var myaddr: InAddr myaddr.s_addr = inet_addr(ip) - + when defined(windows): var s = winlean.gethostbyaddr(addr(myaddr), sizeof(myaddr).cuint, cint(sockets.AF_INET)) if s == nil: raiseOSError(osLastError()) else: - var s = posix.gethostbyaddr(addr(myaddr), sizeof(myaddr).Socklen, + var s = posix.gethostbyaddr(addr(myaddr), sizeof(myaddr).Socklen, cint(posix.AF_INET)) if s == nil: raiseOSError(osLastError(), $hstrerror(h_errno)) - + result.name = $s.h_name result.aliases = cstringArrayToSeq(s.h_aliases) - when defined(windows): + when defined(windows): result.addrtype = Domain(s.h_addrtype) else: if s.h_addrtype == posix.AF_INET: @@ -722,7 +722,7 @@ proc getHostByAddr*(ip: string): Hostent {.tags: [ReadIOEffect].} = result.addrList = cstringArrayToSeq(s.h_addr_list) result.length = int(s.h_length) -proc getHostByName*(name: string): Hostent {.tags: [ReadIOEffect].} = +proc getHostByName*(name: string): Hostent {.tags: [ReadIOEffect].} = ## This function will lookup the IP address of a hostname. when defined(Windows): var s = winlean.gethostbyname(name) @@ -731,7 +731,7 @@ proc getHostByName*(name: string): Hostent {.tags: [ReadIOEffect].} = if s == nil: raiseOSError(osLastError()) result.name = $s.h_name result.aliases = cstringArrayToSeq(s.h_aliases) - when defined(windows): + when defined(windows): result.addrtype = Domain(s.h_addrtype) else: if s.h_addrtype == posix.AF_INET: @@ -744,11 +744,11 @@ proc getHostByName*(name: string): Hostent {.tags: [ReadIOEffect].} = result.length = int(s.h_length) proc getSockOptInt*(socket: Socket, level, optname: int): int {. - tags: [ReadIOEffect].} = + tags: [ReadIOEffect].} = ## getsockopt for integer options. var res: cint var size = sizeof(res).SockLen - if getsockopt(socket.fd, cint(level), cint(optname), + if getsockopt(socket.fd, cint(level), cint(optname), addr(res), addr(size)) < 0'i32: raiseOSError(osLastError()) result = int(res) @@ -757,7 +757,7 @@ proc setSockOptInt*(socket: Socket, level, optname, optval: int) {. tags: [WriteIOEffect].} = ## setsockopt for integer options. var value = cint(optval) - if setsockopt(socket.fd, cint(level), cint(optname), addr(value), + if setsockopt(socket.fd, cint(level), cint(optname), addr(value), sizeof(value).SockLen) < 0'i32: raiseOSError(osLastError()) @@ -776,7 +776,7 @@ proc getSockOpt*(socket: Socket, opt: SOBool, level = SOL_SOCKET): bool {. ## Retrieves option ``opt`` as a boolean value. var res: cint var size = sizeof(res).SockLen - if getsockopt(socket.fd, cint(level), toCInt(opt), + if getsockopt(socket.fd, cint(level), toCInt(opt), addr(res), addr(size)) < 0'i32: raiseOSError(osLastError()) result = res != 0 @@ -785,11 +785,11 @@ proc setSockOpt*(socket: Socket, opt: SOBool, value: bool, level = SOL_SOCKET) { tags: [WriteIOEffect].} = ## Sets option ``opt`` to a boolean value specified by ``value``. var valuei = cint(if value: 1 else: 0) - if setsockopt(socket.fd, cint(level), toCInt(opt), addr(valuei), + if setsockopt(socket.fd, cint(level), toCInt(opt), addr(valuei), sizeof(valuei).SockLen) < 0'i32: raiseOSError(osLastError()) -proc connect*(socket: Socket, address: string, port = Port(0), +proc connect*(socket: Socket, address: string, port = Port(0), af: Domain = AF_INET) {.tags: [ReadIOEffect].} = ## Connects socket to ``address``:``port``. ``Address`` can be an IP address or a ## host name. If ``address`` is a host name, this function will try each IP @@ -816,7 +816,7 @@ proc connect*(socket: Socket, address: string, port = Port(0), freeaddrinfo(aiList) if not success: raiseOSError(lastError) - + when defined(ssl): if socket.isSSL: let ret = SSLConnect(socket.sslHandle) @@ -825,7 +825,7 @@ proc connect*(socket: Socket, address: string, port = Port(0), case err of SSL_ERROR_ZERO_RETURN: raiseSslError("TLS/SSL connection failed to initiate, socket closed prematurely.") - of SSL_ERROR_WANT_READ, SSL_ERROR_WANT_WRITE, SSL_ERROR_WANT_CONNECT, + of SSL_ERROR_WANT_READ, SSL_ERROR_WANT_WRITE, SSL_ERROR_WANT_CONNECT, SSL_ERROR_WANT_ACCEPT: raiseSslError("The operation did not complete. Perhaps you should use connectAsync?") of SSL_ERROR_WANT_X509_LOOKUP: @@ -834,7 +834,7 @@ proc connect*(socket: Socket, address: string, port = Port(0), raiseSslError() else: raiseSslError("Unknown error") - + when false: var s: TSockAddrIn s.sin_addr.s_addr = inet_addr(address) @@ -842,7 +842,7 @@ proc connect*(socket: Socket, address: string, port = Port(0), when defined(windows): s.sin_family = toU16(ord(af)) else: - case af + case af of AF_UNIX: s.sin_family = posix.AF_UNIX of AF_INET: s.sin_family = posix.AF_INET of AF_INET6: s.sin_family = posix.AF_INET6 @@ -886,7 +886,7 @@ proc connectAsync*(socket: Socket, name: string, port = Port(0), if lastError.int32 == EINTR or lastError.int32 == EINPROGRESS: success = true break - + it = it.ai_next freeaddrinfo(aiList) @@ -942,12 +942,12 @@ proc timeValFromMilliseconds(timeout = 500): Timeval = result.tv_sec = seconds.int32 result.tv_usec = ((timeout - seconds * 1000) * 1000).int32 -proc createFdSet(fd: var TFdSet, s: seq[Socket], m: var int) = +proc createFdSet(fd: var TFdSet, s: seq[Socket], m: var int) = FD_ZERO(fd) - for i in items(s): + for i in items(s): m = max(m, int(i.fd)) FD_SET(i.fd, fd) - + proc pruneSocketSet(s: var seq[Socket], fd: var TFdSet) = var i = 0 var L = s.len @@ -982,13 +982,13 @@ proc checkBuffer(readfds: var seq[Socket]): int = if result > 0: readfds = res -proc select*(readfds, writefds, exceptfds: var seq[Socket], - timeout = 500): int {.tags: [ReadIOEffect].} = +proc select*(readfds, writefds, exceptfds: var seq[Socket], + timeout = 500): int {.tags: [ReadIOEffect].} = ## Traditional select function. This function will return the number of ## sockets that are ready to be read from, written to, or which have errors. - ## If there are none; 0 is returned. + ## If there are none; 0 is returned. ## ``Timeout`` is in milliseconds and -1 can be specified for no timeout. - ## + ## ## Sockets which are **not** ready for reading, writing or which don't have ## errors waiting on them are removed from the ``readfds``, ``writefds``, ## ``exceptfds`` sequences respectively. @@ -997,44 +997,44 @@ proc select*(readfds, writefds, exceptfds: var seq[Socket], return buffersFilled var tv {.noInit.}: Timeval = timeValFromMilliseconds(timeout) - + var rd, wr, ex: TFdSet var m = 0 createFdSet((rd), readfds, m) createFdSet((wr), writefds, m) createFdSet((ex), exceptfds, m) - + if timeout != -1: result = int(select(cint(m+1), addr(rd), addr(wr), addr(ex), addr(tv))) else: result = int(select(cint(m+1), addr(rd), addr(wr), addr(ex), nil)) - + pruneSocketSet(readfds, (rd)) pruneSocketSet(writefds, (wr)) pruneSocketSet(exceptfds, (ex)) -proc select*(readfds, writefds: var seq[Socket], +proc select*(readfds, writefds: var seq[Socket], timeout = 500): int {.tags: [ReadIOEffect].} = ## Variant of select with only a read and write list. let buffersFilled = checkBuffer(readfds) if buffersFilled > 0: return buffersFilled var tv {.noInit.}: Timeval = timeValFromMilliseconds(timeout) - + var rd, wr: TFdSet var m = 0 createFdSet((rd), readfds, m) createFdSet((wr), writefds, m) - + if timeout != -1: result = int(select(cint(m+1), addr(rd), addr(wr), nil, addr(tv))) else: result = int(select(cint(m+1), addr(rd), addr(wr), nil, nil)) - + pruneSocketSet(readfds, (rd)) pruneSocketSet(writefds, (wr)) -proc selectWrite*(writefds: var seq[Socket], +proc selectWrite*(writefds: var seq[Socket], timeout = 500): int {.tags: [ReadIOEffect].} = ## When a socket in ``writefds`` is ready to be written to then a non-zero ## value will be returned specifying the count of the sockets which can be @@ -1044,16 +1044,16 @@ proc selectWrite*(writefds: var seq[Socket], ## ``timeout`` is specified in milliseconds and ``-1`` can be specified for ## an unlimited time. var tv {.noInit.}: Timeval = timeValFromMilliseconds(timeout) - + var wr: TFdSet var m = 0 createFdSet((wr), writefds, m) - + if timeout != -1: result = int(select(cint(m+1), nil, addr(wr), nil, addr(tv))) else: result = int(select(cint(m+1), nil, addr(wr), nil, nil)) - + pruneSocketSet(writefds, (wr)) proc select*(readfds: var seq[Socket], timeout = 500): int = @@ -1062,16 +1062,16 @@ proc select*(readfds: var seq[Socket], timeout = 500): int = if buffersFilled > 0: return buffersFilled var tv {.noInit.}: Timeval = timeValFromMilliseconds(timeout) - + var rd: TFdSet var m = 0 createFdSet((rd), readfds, m) - + if timeout != -1: result = int(select(cint(m+1), addr(rd), nil, nil, addr(tv))) else: result = int(select(cint(m+1), addr(rd), nil, nil, nil)) - + pruneSocketSet(readfds, (rd)) proc readIntoBuf(socket: Socket, flags: int32): int = @@ -1107,12 +1107,12 @@ proc recv*(socket: Socket, data: pointer, size: int): int {.tags: [ReadIOEffect] if socket.isBuffered: if socket.bufLen == 0: retRead(0'i32, 0) - + var read = 0 while read < size: if socket.currPos >= socket.bufLen: retRead(0'i32, read) - + let chunk = min(socket.bufLen-socket.currPos, size-read) var d = cast[cstring](data) copyMem(addr(d[read]), addr(socket.buffer[socket.currPos]), chunk) @@ -1155,7 +1155,7 @@ proc waitFor(socket: Socket, waited: var float, timeout, size: int, else: if timeout - int(waited * 1000.0) < 1: raise newException(TimeoutError, "Call to '" & funcName & "' timed out.") - + when defined(ssl): if socket.isSSL: if socket.hasDataBuffered: @@ -1164,7 +1164,7 @@ proc waitFor(socket: Socket, waited: var float, timeout, size: int, let sslPending = SSLPending(socket.sslHandle) if sslPending != 0: return sslPending - + var s = @[socket] var startTime = epochTime() let selRet = select(s, timeout - int(waited * 1000.0)) @@ -1176,8 +1176,8 @@ proc waitFor(socket: Socket, waited: var float, timeout, size: int, proc recv*(socket: Socket, data: pointer, size: int, timeout: int): int {. tags: [ReadIOEffect, TimeEffect].} = ## overload with a ``timeout`` parameter in milliseconds. - var waited = 0.0 # number of seconds already waited - + var waited = 0.0 # number of seconds already waited + var read = 0 while read < size: let avail = waitFor(socket, waited, timeout, size-read, "recv") @@ -1187,7 +1187,7 @@ proc recv*(socket: Socket, data: pointer, size: int, timeout: int): int {. if result < 0: return result inc(read, result) - + result = read proc recv*(socket: Socket, data: var string, size: int, timeout = -1): int = @@ -1231,7 +1231,7 @@ proc peekChar(socket: Socket, c: var char): int {.tags: [ReadIOEffect].} = var res = socket.readIntoBuf(0'i32) if res <= 0: result = res - + c = socket.buffer[socket.currPos] else: when defined(ssl): @@ -1239,7 +1239,7 @@ proc peekChar(socket: Socket, c: var char): int {.tags: [ReadIOEffect].} = if not socket.sslHasPeekChar: result = SSLRead(socket.sslHandle, addr(socket.sslPeekChar), 1) socket.sslHasPeekChar = true - + c = socket.sslPeekChar return result = recv(socket.fd, addr(c), 1, MSG_PEEK) @@ -1251,11 +1251,11 @@ proc recvLine*(socket: Socket, line: var TaintedString, timeout = -1): bool {. ## If a full line is received ``\r\L`` is not ## added to ``line``, however if solely ``\r\L`` is received then ``line`` ## will be set to it. - ## + ## ## ``True`` is returned if data is available. ``False`` suggests an ## error, EOS exceptions are not raised and ``False`` is simply returned ## instead. - ## + ## ## If the socket is disconnected, ``line`` will be set to ``""`` and ``True`` ## will be returned. ## @@ -1264,7 +1264,7 @@ proc recvLine*(socket: Socket, line: var TaintedString, timeout = -1): bool {. ## ## **Deprecated since version 0.9.2**: This function has been deprecated in ## favour of readLine. - + template addNLIfEmpty(): stmt = if line.len == 0: line.add("\c\L") @@ -1286,7 +1286,7 @@ proc recvLine*(socket: Socket, line: var TaintedString, timeout = -1): bool {. elif n <= 0: return false addNLIfEmpty() return true - elif c == '\L': + elif c == '\L': addNLIfEmpty() return true add(line.string, c) @@ -1298,14 +1298,14 @@ proc readLine*(socket: Socket, line: var TaintedString, timeout = -1) {. ## If a full line is read ``\r\L`` is not ## added to ``line``, however if solely ``\r\L`` is read then ``line`` ## will be set to it. - ## + ## ## If the socket is disconnected, ``line`` will be set to ``""``. ## ## An EOS exception will be raised in the case of a socket error. ## ## A timeout can be specified in milliseconds, if data is not received within ## the specified time an ETimeout exception will be raised. - + template addNLIfEmpty(): stmt = if line.len == 0: line.add("\c\L") @@ -1327,12 +1327,12 @@ proc readLine*(socket: Socket, line: var TaintedString, timeout = -1) {. elif n <= 0: socket.raiseSocketError() addNLIfEmpty() return - elif c == '\L': + elif c == '\L': addNLIfEmpty() return add(line.string, c) -proc recvLineAsync*(socket: Socket, +proc recvLineAsync*(socket: Socket, line: var TaintedString): RecvLineResult {.tags: [ReadIOEffect], deprecated.} = ## Similar to ``recvLine`` but designed for non-blocking sockets. ## @@ -1350,21 +1350,21 @@ proc recvLineAsync*(socket: Socket, while true: var c: char var n = recv(socket, addr(c), 1) - if n < 0: + if n < 0: return (if line.len == 0: RecvFail else: RecvPartialLine) - elif n == 0: + elif n == 0: return (if line.len == 0: RecvDisconnected else: RecvPartialLine) if c == '\r': n = peekChar(socket, c) if n > 0 and c == '\L': discard recv(socket, addr(c), 1) - elif n <= 0: + elif n <= 0: return (if line.len == 0: RecvFail else: RecvPartialLine) return RecvFullLine elif c == '\L': return RecvFullLine add(line.string, c) -proc readLineAsync*(socket: Socket, +proc readLineAsync*(socket: Socket, line: var TaintedString): ReadLineResult {.tags: [ReadIOEffect].} = ## Similar to ``recvLine`` but designed for non-blocking sockets. ## @@ -1376,24 +1376,24 @@ proc readLineAsync*(socket: Socket, ## * If no data could be retrieved; ``ReadNone`` is returned. ## * If call to ``recv`` failed; **an EOS exception is raised.** setLen(line.string, 0) - + template errorOrNone = socket.raiseSocketError(async = true) return ReadNone - + while true: var c: char var n = recv(socket, addr(c), 1) #echo(n) if n < 0: if line.len == 0: errorOrNone else: return ReadPartialLine - elif n == 0: + elif n == 0: return (if line.len == 0: ReadDisconnected else: ReadPartialLine) if c == '\r': n = peekChar(socket, c) if n > 0 and c == '\L': discard recv(socket, addr(c), 1) - elif n <= 0: + elif n <= 0: if line.len == 0: errorOrNone else: return ReadPartialLine return ReadFullLine elif c == '\L': return ReadFullLine @@ -1424,7 +1424,7 @@ proc recv*(socket: Socket): TaintedString {.tags: [ReadIOEffect], deprecated.} = var bytesRead = recv(socket, cstring(buf), bufSize-1) # Error if bytesRead == -1: OSError(osLastError()) - + buf[bytesRead] = '\0' # might not be necessary setLen(buf, bytesRead) add(result.string, buf) @@ -1442,13 +1442,13 @@ proc recvTimeout*(socket: Socket, timeout: int): TaintedString {. var s = @[socket] if s.select(timeout) != 1: raise newException(TimeoutError, "Call to recv() timed out.") - + return socket.recv {.pop.} proc recvAsync*(socket: Socket, s: var TaintedString): bool {. tags: [ReadIOEffect], deprecated.} = - ## receives all the data from a non-blocking socket. If socket is non-blocking + ## receives all the data from a non-blocking socket. If socket is non-blocking ## and there are no messages available, `False` will be returned. ## Other socket errors will result in an ``EOS`` error. ## If socket is not a connectionless socket and socket is not connected @@ -1478,7 +1478,7 @@ proc recvAsync*(socket: Socket, s: var TaintedString): bool {. of SSL_ERROR_SYSCALL, SSL_ERROR_SSL: raiseSslError() else: raiseSslError("Unknown Error") - + if bytesRead == -1 and not (when defined(ssl): socket.isSSL else: false): let err = osLastError() when defined(windows): @@ -1510,7 +1510,7 @@ proc recvFrom*(socket: Socket, data: var string, length: int, ## so when ``socket`` is buffered the non-buffered implementation will be ## used. Therefore if ``socket`` contains something in its buffer this ## function will make no effort to return it. - + # TODO: Buffered sockets data.setLen(length) var sockAddress: Sockaddr_in @@ -1524,7 +1524,7 @@ proc recvFrom*(socket: Socket, data: var string, length: int, port = ntohs(sockAddress.sin_port).Port proc recvFromAsync*(socket: Socket, data: var string, length: int, - address: var string, port: var Port, + address: var string, port: var Port, flags = 0'i32): bool {.tags: [ReadIOEffect].} = ## Variant of ``recvFrom`` for non-blocking sockets. Unlike ``recvFrom``, ## this function will raise an EOS error whenever a socket error occurs. @@ -1573,11 +1573,11 @@ proc send*(socket: Socket, data: pointer, size: int): int {. when defined(ssl): if socket.isSSL: return SSLWrite(socket.sslHandle, cast[cstring](data), size) - + when defined(windows) or defined(macosx): result = send(socket.fd, data, size.cint, 0'i32) else: - when defined(solaris): + when defined(solaris): const MSG_NOSIGNAL = 0 result = send(socket.fd, data, size, int32(MSG_NOSIGNAL)) @@ -1590,7 +1590,7 @@ proc send*(socket: Socket, data: string) {.tags: [WriteIOEffect].} = when defined(ssl): if socket.isSSL: raiseSslError() - + raiseOSError(osLastError()) if sent != data.len: @@ -1633,7 +1633,7 @@ proc sendAsync*(socket: Socket, data: string): int {.tags: [WriteIOEffect].} = if err.int32 == EAGAIN or err.int32 == EWOULDBLOCK: return 0 else: raiseOSError(err) - + proc trySend*(socket: Socket, data: string): bool {.tags: [WriteIOEffect].} = ## safe alternative to ``send``. Does not raise an EOS when an error occurs, @@ -1644,7 +1644,7 @@ proc sendTo*(socket: Socket, address: string, port: Port, data: pointer, size: int, af: Domain = AF_INET, flags = 0'i32): int {. tags: [WriteIOEffect].} = ## low-level sendTo proc. This proc sends ``data`` to the specified ``address``, - ## which may be an IP address or a hostname, if a hostname is specified + ## which may be an IP address or a hostname, if a hostname is specified ## this function will try each IP of that hostname. ## ## **Note:** This proc is not available for SSL sockets. @@ -1654,7 +1654,7 @@ proc sendTo*(socket: Socket, address: string, port: Port, data: pointer, hints.ai_socktype = toInt(SOCK_STREAM) hints.ai_protocol = toInt(IPPROTO_TCP) gaiNim(address, port, hints, aiList) - + # try all possibilities: var success = false var it = aiList @@ -1668,7 +1668,7 @@ proc sendTo*(socket: Socket, address: string, port: Port, data: pointer, freeaddrinfo(aiList) -proc sendTo*(socket: Socket, address: string, port: Port, +proc sendTo*(socket: Socket, address: string, port: Port, data: string): int {.tags: [WriteIOEffect].} = ## Friendlier version of the low-level ``sendTo``. result = socket.sendTo(address, port, cstring(data), data.len) @@ -1677,10 +1677,10 @@ when defined(Windows): const IOCPARM_MASK = 127 IOC_IN = int(-2147483648) - FIONBIO = IOC_IN.int32 or ((sizeof(int32) and IOCPARM_MASK) shl 16) or + FIONBIO = IOC_IN.int32 or ((sizeof(int32) and IOCPARM_MASK) shl 16) or (102 shl 8) or 126 - proc ioctlsocket(s: SocketHandle, cmd: clong, + proc ioctlsocket(s: SocketHandle, cmd: clong, argptr: ptr clong): cint {. stdcall, importc:"ioctlsocket", dynlib: "ws2_32.dll".} @@ -1713,7 +1713,7 @@ proc connect*(socket: Socket, address: string, port = Port(0), timeout: int, ## the connection to the server to be made. let originalStatus = not socket.nonblocking socket.setBlocking(false) - + socket.connectAsync(address, port, af) var s: seq[Socket] = @[socket] if selectWrite(s, timeout) != 1: diff --git a/lib/pure/subexes.nim b/lib/pure/subexes.nim index 46824645d..2d1adc0eb 100644 --- a/lib/pure/subexes.nim +++ b/lib/pure/subexes.nim @@ -77,7 +77,7 @@ proc getFormatArg(p: var FormatParser, a: openArray[string]): int = result = if not negative: j-1 else: a.len-j of 'a'..'z', 'A'..'Z', '\128'..'\255', '_': var name = "" - while f[i] in PatternChars: + while f[i] in PatternChars: name.add(f[i]) inc(i) result = findNormalized(name, a)+1 @@ -131,7 +131,7 @@ proc scanBranch(p: var FormatParser, a: openArray[string], while true: case f[i] of ']': break - of '|': + of '|': inc i elsePart = i inc c @@ -172,7 +172,7 @@ proc scanSlice(p: var FormatParser, a: openarray[string]): tuple[x, y: int] = var slice = false var i = p.i var f = p.f - + if f[i] == '{': inc i else: raiseInvalidFormat("'{' expected") if f[i] == '.' and f[i+1] == '.': @@ -193,12 +193,12 @@ proc scanSlice(p: var FormatParser, a: openarray[string]): tuple[x, y: int] = if f[i] != '}': raiseInvalidFormat("'}' expected") inc i p.i = i - + proc scanDollar(p: var FormatParser, a: openarray[string], s: var string) = var i = p.i var f = p.f case f[i] - of '$': + of '$': emitChar p, s, '$' inc i of '*': @@ -232,7 +232,7 @@ proc scanDollar(p: var FormatParser, a: openarray[string], s: var string) = # $' '~{1..3} # insert space followed by 1..3 if not empty inc i - call: + call: let (x, y) = scanSlice(p, a) var L = 0 for j in x..y: inc L, a[j].len @@ -258,7 +258,7 @@ proc scanDollar(p: var FormatParser, a: openarray[string], s: var string) = of 'i': inc i callNoLineLenTracking: scanQuote(p, indent, true) - + call: let (x, y) = scanSlice(p, a) if maxLen < 1: emitStrLinear(p, s, indent) @@ -266,7 +266,7 @@ proc scanDollar(p: var FormatParser, a: openarray[string], s: var string) = emitStr p, s, a[x] for j in x+1..y: emitStr p, s, sep - if items >= maxLen: + if items >= maxLen: emitStrLinear p, s, indent items = 0 emitStr p, s, a[j] @@ -274,7 +274,7 @@ proc scanDollar(p: var FormatParser, a: openarray[string], s: var string) = of 'c': inc i callNoLineLenTracking: scanQuote(p, indent, true) - + call: let (x, y) = scanSlice(p, a) if p.lineLen + a[x].len > maxLen: emitStrLinear(p, s, indent) @@ -283,7 +283,7 @@ proc scanDollar(p: var FormatParser, a: openarray[string], s: var string) = emitStr p, s, sep if p.lineLen + a[j].len > maxLen: emitStrLinear(p, s, indent) emitStr p, s, a[j] - + else: raiseInvalidFormat("unit 'c' (chars) or 'i' (items) expected") break StringJoin @@ -294,7 +294,7 @@ proc scanDollar(p: var FormatParser, a: openarray[string], s: var string) = emitStr p, s, sep emitStr p, s, a[j] else: - call: + call: var x = getFormatArg(p, a) emitStr p, s, a[x] p.i = i @@ -375,38 +375,38 @@ when isMainModule: doAssert "$1($', '{2..})" % ["f", "a", "b"] == "f(a, b)" doAssert "$[$1($', '{2..})|''''|fg'$3']1" % ["7", "a", "b"] == "fg$3" - + doAssert "$[$#($', '{#..})|''''|$3]1" % ["0", "a", "b"] == "0(a, b)" doAssert "$' '~{..}" % "" == "" doAssert "$' '~{..}" % "P0" == " P0" doAssert "${$1}" % "1" == "1" doAssert "${$$-1} $$1" % "1" == "1 $1" - + doAssert "$#($', '10c'\n '{#..})" % ["doAssert", "longishA", "longish"] == """doAssert( - longishA, + longishA, longish)""" - + assert "type MyEnum* = enum\n $', '2i'\n '{..}" % ["fieldA", "fieldB", "FiledClkad", "fieldD", "fieldE", "longishFieldName"] == strutils.unindent """ type MyEnum* = enum - fieldA, fieldB, - FiledClkad, fieldD, + fieldA, fieldB, + FiledClkad, fieldD, fieldE, longishFieldName""" - + doAssert subex"$1($', '{2..})" % ["f", "a", "b", "c"] == "f(a, b, c)" - + doAssert subex"$1 $[files|file|files]{1} copied" % ["1"] == "1 file copied" - + doAssert subex"$['''|'|''''|']']#" % "0" == "'|" - + assert subex("type\n Enum = enum\n $', '40c'\n '{..}") % [ "fieldNameA", "fieldNameB", "fieldNameC", "fieldNameD"] == strutils.unindent """ type Enum = enum - fieldNameA, fieldNameB, fieldNameC, + fieldNameA, fieldNameB, fieldNameC, fieldNameD""" - - + + diff --git a/lib/pure/unicode.nim b/lib/pure/unicode.nim index 5e20db32b..396957f6c 100644 --- a/lib/pure/unicode.nim +++ b/lib/pure/unicode.nim @@ -1285,7 +1285,7 @@ proc cmpRunesIgnoreCase*(a, b: string): int {.rtl, extern: "nuc$1", procvar.} = result = a.len - b.len proc reversed*(s: string): string = - ## Returns the reverse of ``s``, interpreting it as Unicode characters. + ## Returns the reverse of ``s``, interpreting it as Unicode characters. ## Unicode combining characters are correctly interpreted as well: ## ## .. code-block:: nim diff --git a/lib/pure/unidecode/unidecode.nim b/lib/pure/unidecode/unidecode.nim index a83b9be0f..9d8843f06 100644 --- a/lib/pure/unidecode/unidecode.nim +++ b/lib/pure/unidecode/unidecode.nim @@ -7,19 +7,19 @@ # distribution, for details about the copyright. # -## This module is based on Python's Unidecode module by Tomaz Solc, -## which in turn is based on the ``Text::Unidecode`` Perl module by -## Sean M. Burke +## This module is based on Python's Unidecode module by Tomaz Solc, +## which in turn is based on the ``Text::Unidecode`` Perl module by +## Sean M. Burke ## (http://search.cpan.org/~sburke/Text-Unidecode-0.04/lib/Text/Unidecode.pm ). ## ## It provides a single proc that does Unicode to ASCII transliterations: ## It finds the sequence of ASCII characters that is the closest approximation ## to the Unicode string. ## -## For example, the closest to string "Äußerst" in ASCII is "Ausserst". Some -## information is lost in this transformation, of course, since several Unicode +## For example, the closest to string "Äußerst" in ASCII is "Ausserst". Some +## information is lost in this transformation, of course, since several Unicode ## strings can be transformed in the same ASCII representation. So this is a -## strictly one-way transformation. However a human reader will probably +## strictly one-way transformation. However a human reader will probably ## still be able to guess what original string was meant from the context. ## ## This module needs the data file "unidecode.dat" to work: You can either @@ -31,7 +31,7 @@ import unicode when defined(embedUnidecodeTable): import strutils - + const translationTable = splitLines(slurp"unidecode/unidecode.dat") else: # shared is fine for threading: @@ -49,12 +49,12 @@ proc loadUnidecodeTable*(datafile = "unidecode.dat") = translationTable[i] = line.string inc(i) -proc unidecode*(s: string): string = +proc unidecode*(s: string): string = ## Finds the sequence of ASCII characters that is the closest approximation ## to the UTF-8 string `s`. ## - ## Example: - ## + ## Example: + ## ## ..code-block:: nim ## ## unidecode("\x53\x17\x4E\xB0") @@ -63,7 +63,7 @@ proc unidecode*(s: string): string = ## assert(not isNil(translationTable)) result = "" - for r in runes(s): + for r in runes(s): var c = int(r) if c <=% 127: add(result, chr(c)) elif c <% translationTable.len: add(result, translationTable[c-128]) diff --git a/lib/pure/xmldomparser.nim b/lib/pure/xmldomparser.nim index 050362435..7c7f7b99c 100644 --- a/lib/pure/xmldomparser.nim +++ b/lib/pure/xmldomparser.nim @@ -30,19 +30,19 @@ proc getNS(prefix: string): string = if ":" in key: if key.split(':')[1] == prefix: return value - + if key == "xmlns": defaultNS.add(value) - + # Don't return the default namespaces # in the loop, because then they would have a precedence # over normal namespaces if defaultNS.len() > 0: return defaultNS[0] # Return the first found default namespace # if none are specified for this prefix - + return "" - + proc parseText(x: var XmlParser, doc: var PDocument): PText = result = doc.createTextNode(x.charData()) @@ -58,19 +58,19 @@ proc parseElement(x: var XmlParser, doc: var PDocument): PElement = n.appendChild(parseElement(x, doc)) else: n = doc.createElementNS("", x.elementName) - + of xmlElementEnd: if x.elementName == n.nodeName: # n.normalize() # Remove any whitespace etc. - + var ns: string if x.elementName.contains(':'): ns = getNS(x.elementName.split(':')[0]) else: ns = getNS("") - + n.namespaceURI = ns - + # Remove any namespaces this element declared var count = 0 # Variable which keeps the index # We need to edit it.. @@ -82,15 +82,15 @@ proc parseElement(x: var XmlParser, doc: var PDocument): PElement = return n else: #The wrong element is ended - raise newException(EMismatchedTag, "Mismatched tag at line " & + raise newException(EMismatchedTag, "Mismatched tag at line " & $x.getLine() & " column " & $x.getColumn) - + of xmlCharData: n.appendChild(parseText(x, doc)) of xmlAttribute: if x.attrKey == "xmlns" or x.attrKey.startsWith("xmlns:"): nsList.add((x.attrKey, x.attrValue, n)) - + if x.attrKey.contains(':'): var ns = getNS(x.attrKey) n.setAttributeNS(ns, x.attrKey, x.attrValue) @@ -103,7 +103,7 @@ proc parseElement(x: var XmlParser, doc: var PDocument): PElement = n.appendChild(doc.createComment(x.charData())) of xmlPI: n.appendChild(doc.createProcessingInstruction(x.piName(), x.piRest())) - + of xmlWhitespace, xmlElementClose, xmlEntity, xmlSpecial: discard " Unused \'events\'" @@ -111,19 +111,19 @@ proc parseElement(x: var XmlParser, doc: var PDocument): PElement = raise newException(EParserError, "Unexpected XML Parser event") x.next() - raise newException(EMismatchedTag, + raise newException(EMismatchedTag, "Mismatched tag at line " & $x.getLine() & " column " & $x.getColumn) proc loadXMLStream*(stream: Stream): PDocument = - ## Loads and parses XML from a stream specified by ``stream``, and returns + ## Loads and parses XML from a stream specified by ``stream``, and returns ## a ``PDocument`` var x: XmlParser open(x, stream, nil, {reportComments}) - + var xmlDoc: PDocument var dom: PDOMImplementation = getDOM() - + while true: x.next() case x.kind() @@ -140,16 +140,16 @@ proc loadXMLStream*(stream: Stream): PDocument = return xmlDoc proc loadXML*(xml: string): PDocument = - ## Loads and parses XML from a string specified by ``xml``, and returns + ## Loads and parses XML from a string specified by ``xml``, and returns ## a ``PDocument`` var s = newStringStream(xml) return loadXMLStream(s) - - + + proc loadXMLFile*(path: string): PDocument = - ## Loads and parses XML from a file specified by ``path``, and returns + ## Loads and parses XML from a file specified by ``path``, and returns ## a ``PDocument`` - + var s = newFileStream(path, fmRead) if s == nil: raise newException(IOError, "Unable to read file " & path) return loadXMLStream(s) @@ -164,5 +164,5 @@ when not defined(testing) and isMainModule: if i.namespaceURI != nil: echo(i.nodeName, "=", i.namespaceURI) - + echo($xml) diff --git a/lib/pure/xmlparser.nim b/lib/pure/xmlparser.nim index 840cae734..56b122000 100644 --- a/lib/pure/xmlparser.nim +++ b/lib/pure/xmlparser.nim @@ -18,24 +18,24 @@ type {.deprecated: [EInvalidXml: XmlError].} -proc raiseInvalidXml(errors: seq[string]) = +proc raiseInvalidXml(errors: seq[string]) = var e: ref XmlError new(e) e.msg = errors[0] e.errors = errors raise e -proc addNode(father, son: XmlNode) = +proc addNode(father, son: XmlNode) = if son != nil: add(father, son) proc parse(x: var XmlParser, errors: var seq[string]): XmlNode -proc untilElementEnd(x: var XmlParser, result: XmlNode, +proc untilElementEnd(x: var XmlParser, result: XmlNode, errors: var seq[string]) = while true: case x.kind - of xmlElementEnd: - if x.elementName == result.tag: + of xmlElementEnd: + if x.elementName == result.tag: next(x) else: errors.add(errorMsg(x, " expected")) @@ -49,7 +49,7 @@ proc untilElementEnd(x: var XmlParser, result: XmlNode, proc parse(x: var XmlParser, errors: var seq[string]): XmlNode = case x.kind - of xmlComment: + of xmlComment: result = newComment(x.charData) next(x) of xmlCharData, xmlWhitespace: @@ -67,11 +67,11 @@ proc parse(x: var XmlParser, errors: var seq[string]): XmlNode = untilElementEnd(x, result, errors) of xmlElementEnd: errors.add(errorMsg(x, "unexpected ending tag: " & x.elementName)) - of xmlElementOpen: + of xmlElementOpen: result = newElement(x.elementName) next(x) result.attrs = newStringTable() - while true: + while true: case x.kind of xmlAttribute: result.attrs[x.attrKey] = x.attrValue @@ -91,7 +91,7 @@ proc parse(x: var XmlParser, errors: var seq[string]): XmlNode = of xmlAttribute, xmlElementClose: errors.add(errorMsg(x, " expected")) next(x) - of xmlCData: + of xmlCData: result = newCData(x.charData) next(x) of xmlEntity: @@ -100,8 +100,8 @@ proc parse(x: var XmlParser, errors: var seq[string]): XmlNode = next(x) of xmlEof: discard -proc parseXml*(s: Stream, filename: string, - errors: var seq[string]): XmlNode = +proc parseXml*(s: Stream, filename: string, + errors: var seq[string]): XmlNode = ## parses the XML from stream `s` and returns a ``PXmlNode``. Every ## occurred parsing error is added to the `errors` sequence. var x: XmlParser @@ -109,7 +109,7 @@ proc parseXml*(s: Stream, filename: string, while true: x.next() case x.kind - of xmlElementOpen, xmlElementStart: + of xmlElementOpen, xmlElementStart: result = parse(x, errors) break of xmlComment, xmlWhitespace, xmlSpecial, xmlPI: discard # just skip it @@ -120,7 +120,7 @@ proc parseXml*(s: Stream, filename: string, break close(x) -proc parseXml*(s: Stream): XmlNode = +proc parseXml*(s: Stream): XmlNode = ## parses the XTML from stream `s` and returns a ``PXmlNode``. All parsing ## errors are turned into an ``EInvalidXML`` exception. var errors: seq[string] = @[] @@ -128,7 +128,7 @@ proc parseXml*(s: Stream): XmlNode = if errors.len > 0: raiseInvalidXml(errors) proc loadXml*(path: string, errors: var seq[string]): XmlNode = - ## Loads and parses XML from file specified by ``path``, and returns + ## Loads and parses XML from file specified by ``path``, and returns ## a ``PXmlNode``. Every occurred parsing error is added to the `errors` ## sequence. var s = newFileStream(path, fmRead) @@ -136,9 +136,9 @@ proc loadXml*(path: string, errors: var seq[string]): XmlNode = result = parseXml(s, path, errors) proc loadXml*(path: string): XmlNode = - ## Loads and parses XML from file specified by ``path``, and returns + ## Loads and parses XML from file specified by ``path``, and returns ## a ``PXmlNode``. All parsing errors are turned into an ``EInvalidXML`` - ## exception. + ## exception. var errors: seq[string] = @[] result = loadXml(path, errors) if errors.len > 0: raiseInvalidXml(errors) @@ -146,14 +146,14 @@ proc loadXml*(path: string): XmlNode = when not defined(testing) and isMainModule: import os - var errors: seq[string] = @[] + var errors: seq[string] = @[] var x = loadXml(paramStr(1), errors) for e in items(errors): echo e - + var f: File if open(f, "xmltest.txt", fmWrite): f.write($x) f.close() else: quit("cannot write test.txt") - + diff --git a/lib/system/ansi_c.nim b/lib/system/ansi_c.nim index 9406f26c9..702559034 100644 --- a/lib/system/ansi_c.nim +++ b/lib/system/ansi_c.nim @@ -13,20 +13,20 @@ {.push hints:off} -proc c_strcmp(a, b: cstring): cint {.header: "", +proc c_strcmp(a, b: cstring): cint {.header: "", noSideEffect, importc: "strcmp".} -proc c_memcmp(a, b: cstring, size: int): cint {.header: "", +proc c_memcmp(a, b: cstring, size: int): cint {.header: "", noSideEffect, importc: "memcmp".} proc c_memcpy(a, b: cstring, size: int) {.header: "", importc: "memcpy".} -proc c_strlen(a: cstring): int {.header: "", +proc c_strlen(a: cstring): int {.header: "", noSideEffect, importc: "strlen".} proc c_memset(p: pointer, value: cint, size: int) {. header: "", importc: "memset".} type - C_TextFile {.importc: "FILE", header: "", + C_TextFile {.importc: "FILE", header: "", final, incompleteStruct.} = object - C_BinaryFile {.importc: "FILE", header: "", + C_BinaryFile {.importc: "FILE", header: "", final, incompleteStruct.} = object C_TextFileStar = ptr C_TextFile C_BinaryFileStar = ptr C_BinaryFile @@ -101,15 +101,15 @@ proc c_signal(sig: cint, handler: proc (a: cint) {.noconv.}) {. importc: "signal", header: "".} proc c_raise(sig: cint) {.importc: "raise", header: "".} -proc c_fputs(c: cstring, f: C_TextFileStar) {.importc: "fputs", +proc c_fputs(c: cstring, f: C_TextFileStar) {.importc: "fputs", header: "".} proc c_fgets(c: cstring, n: int, f: C_TextFileStar): cstring {. importc: "fgets", header: "".} -proc c_fgetc(stream: C_TextFileStar): int {.importc: "fgetc", +proc c_fgetc(stream: C_TextFileStar): int {.importc: "fgetc", header: "".} -proc c_ungetc(c: int, f: C_TextFileStar) {.importc: "ungetc", +proc c_ungetc(c: int, f: C_TextFileStar) {.importc: "ungetc", header: "".} -proc c_putc(c: char, stream: C_TextFileStar) {.importc: "putc", +proc c_putc(c: char, stream: C_TextFileStar) {.importc: "putc", header: "".} proc c_fprintf(f: C_TextFileStar, frmt: cstring) {. importc: "fprintf", header: "", varargs.} @@ -120,7 +120,7 @@ proc c_fopen(filename, mode: cstring): C_TextFileStar {. importc: "fopen", header: "".} proc c_fclose(f: C_TextFileStar) {.importc: "fclose", header: "".} -proc c_sprintf(buf, frmt: cstring): cint {.header: "", +proc c_sprintf(buf, frmt: cstring): cint {.header: "", importc: "sprintf", varargs, noSideEffect.} # we use it only in a way that cannot lead to security issues @@ -149,7 +149,7 @@ when hostOS != "standalone": when not declared(errno): when defined(NimrodVM): var vmErrnoWrapper {.importc.}: ptr cint - template errno: expr = + template errno: expr = bind vmErrnoWrapper vmErrnoWrapper[] else: diff --git a/lib/system/avltree.nim b/lib/system/avltree.nim index 5ee37d3eb..d5c901542 100644 --- a/lib/system/avltree.nim +++ b/lib/system/avltree.nim @@ -16,7 +16,7 @@ proc lowGauge(n: PAvlNode): int = while not isBottom(it): result = it.key it = it.link[0] - + proc highGauge(n: PAvlNode): int = result = -1 var it = n @@ -24,7 +24,7 @@ proc highGauge(n: PAvlNode): int = result = it.upperBound it = it.link[1] -proc find(root: PAvlNode, key: int): PAvlNode = +proc find(root: PAvlNode, key: int): PAvlNode = var it = root while not isBottom(it): if it.key == key: return it diff --git a/lib/system/cellsets.nim b/lib/system/cellsets.nim index 93c49483b..bb5de6f42 100644 --- a/lib/system/cellsets.nim +++ b/lib/system/cellsets.nim @@ -65,7 +65,7 @@ proc init(s: var CellSeq, cap: int = 1024) = s.cap = cap s.d = cast[PCellArray](alloc0(cap * sizeof(PCell))) -proc deinit(s: var CellSeq) = +proc deinit(s: var CellSeq) = dealloc(s.d) s.d = nil s.len = 0 @@ -98,7 +98,7 @@ proc nextTry(h, maxHash: int): int {.inline.} = # For any initial h in range(maxHash), repeating that maxHash times # generates each int in range(maxHash) exactly once (see any text on # random-number generation for proof). - + proc cellSetGet(t: CellSet, key: ByteAddress): PPageDesc = var h = cast[int](key) and t.max while t.data[h] != nil: @@ -170,16 +170,16 @@ proc excl(s: var CellSet, cell: PCell) = t.bits[u shr IntShift] = (t.bits[u shr IntShift] and not (1 shl (u and IntMask))) -proc containsOrIncl(s: var CellSet, cell: PCell): bool = +proc containsOrIncl(s: var CellSet, cell: PCell): bool = var u = cast[ByteAddress](cell) var t = cellSetGet(s, u shr PageShift) if t != nil: u = (u %% PageSize) /% MemAlign result = (t.bits[u shr IntShift] and (1 shl (u and IntMask))) != 0 - if not result: + if not result: t.bits[u shr IntShift] = t.bits[u shr IntShift] or (1 shl (u and IntMask)) - else: + else: incl(s, cell) result = false diff --git a/lib/system/channels.nim b/lib/system/channels.nim index 6739fb83e..68c0e32d2 100644 --- a/lib/system/channels.nim +++ b/lib/system/channels.nim @@ -1,267 +1,267 @@ -# -# -# Nim's Runtime Library +# +# +# Nim's Runtime Library # (c) Copyright 2015 Andreas Rumpf -# -# See the file "copying.txt", included in this -# distribution, for details about the copyright. -# - -## Channel support for threads. **Note**: This is part of the system module. -## Do not import it directly. To activate thread support you need to compile -## with the ``--threads:on`` command line switch. -## -## **Note:** The current implementation of message passing is slow and does -## not work with cyclic data structures. - -when not declared(NimString): - {.error: "You must not import this module explicitly".} - -type - pbytes = ptr array[0.. 0xffff, byte] - RawChannel {.pure, final.} = object ## msg queue for a thread - rd, wr, count, mask: int - data: pbytes - lock: SysLock - cond: SysCond - elemType: PNimType - ready: bool - region: MemRegion - PRawChannel = ptr RawChannel - LoadStoreMode = enum mStore, mLoad +# +# See the file "copying.txt", included in this +# distribution, for details about the copyright. +# + +## Channel support for threads. **Note**: This is part of the system module. +## Do not import it directly. To activate thread support you need to compile +## with the ``--threads:on`` command line switch. +## +## **Note:** The current implementation of message passing is slow and does +## not work with cyclic data structures. + +when not declared(NimString): + {.error: "You must not import this module explicitly".} + +type + pbytes = ptr array[0.. 0xffff, byte] + RawChannel {.pure, final.} = object ## msg queue for a thread + rd, wr, count, mask: int + data: pbytes + lock: SysLock + cond: SysCond + elemType: PNimType + ready: bool + region: MemRegion + PRawChannel = ptr RawChannel + LoadStoreMode = enum mStore, mLoad Channel* {.gcsafe.}[TMsg] = RawChannel ## a channel for thread communication {.deprecated: [TRawChannel: RawChannel, TLoadStoreMode: LoadStoreMode, TChannel: Channel].} -const ChannelDeadMask = -2 - -proc initRawChannel(p: pointer) = - var c = cast[PRawChannel](p) - initSysLock(c.lock) - initSysCond(c.cond) - c.mask = -1 - -proc deinitRawChannel(p: pointer) = - var c = cast[PRawChannel](p) - # we need to grab the lock to be safe against sending threads! - acquireSys(c.lock) - c.mask = ChannelDeadMask - deallocOsPages(c.region) - deinitSys(c.lock) - deinitSysCond(c.cond) - -proc storeAux(dest, src: pointer, mt: PNimType, t: PRawChannel, - mode: LoadStoreMode) {.benign.} -proc storeAux(dest, src: pointer, n: ptr TNimNode, t: PRawChannel, - mode: LoadStoreMode) {.benign.} = - var - d = cast[ByteAddress](dest) - s = cast[ByteAddress](src) - case n.kind - of nkSlot: storeAux(cast[pointer](d +% n.offset), - cast[pointer](s +% n.offset), n.typ, t, mode) - of nkList: - for i in 0..n.len-1: storeAux(dest, src, n.sons[i], t, mode) - of nkCase: - copyMem(cast[pointer](d +% n.offset), cast[pointer](s +% n.offset), - n.typ.size) - var m = selectBranch(src, n) - if m != nil: storeAux(dest, src, m, t, mode) - of nkNone: sysAssert(false, "storeAux") - -proc storeAux(dest, src: pointer, mt: PNimType, t: PRawChannel, - mode: LoadStoreMode) = - var - d = cast[ByteAddress](dest) - s = cast[ByteAddress](src) - sysAssert(mt != nil, "mt == nil") - case mt.kind - of tyString: - if mode == mStore: - var x = cast[PPointer](dest) - var s2 = cast[PPointer](s)[] - if s2 == nil: - x[] = nil - else: - var ss = cast[NimString](s2) - var ns = cast[NimString](alloc(t.region, ss.len+1 + GenericSeqSize)) - copyMem(ns, ss, ss.len+1 + GenericSeqSize) - x[] = ns - else: - var x = cast[PPointer](dest) - var s2 = cast[PPointer](s)[] - if s2 == nil: - unsureAsgnRef(x, s2) - else: - unsureAsgnRef(x, copyString(cast[NimString](s2))) - dealloc(t.region, s2) - of tySequence: - var s2 = cast[PPointer](src)[] - var seq = cast[PGenericSeq](s2) - var x = cast[PPointer](dest) - if s2 == nil: - if mode == mStore: - x[] = nil - else: - unsureAsgnRef(x, nil) - else: - sysAssert(dest != nil, "dest == nil") - if mode == mStore: - x[] = alloc(t.region, seq.len *% mt.base.size +% GenericSeqSize) - else: - unsureAsgnRef(x, newObj(mt, seq.len * mt.base.size + GenericSeqSize)) - var dst = cast[ByteAddress](cast[PPointer](dest)[]) - for i in 0..seq.len-1: - storeAux( - cast[pointer](dst +% i*% mt.base.size +% GenericSeqSize), - cast[pointer](cast[ByteAddress](s2) +% i *% mt.base.size +% - GenericSeqSize), - mt.base, t, mode) - var dstseq = cast[PGenericSeq](dst) - dstseq.len = seq.len - dstseq.reserved = seq.len - if mode != mStore: dealloc(t.region, s2) - of tyObject: - # copy type field: - var pint = cast[ptr PNimType](dest) - # XXX use dynamic type here! - pint[] = mt - if mt.base != nil: - storeAux(dest, src, mt.base, t, mode) - storeAux(dest, src, mt.node, t, mode) - of tyTuple: - storeAux(dest, src, mt.node, t, mode) - of tyArray, tyArrayConstr: - for i in 0..(mt.size div mt.base.size)-1: - storeAux(cast[pointer](d +% i*% mt.base.size), - cast[pointer](s +% i*% mt.base.size), mt.base, t, mode) - of tyRef: - var s = cast[PPointer](src)[] - var x = cast[PPointer](dest) - if s == nil: - if mode == mStore: - x[] = nil - else: - unsureAsgnRef(x, nil) - else: - if mode == mStore: - x[] = alloc(t.region, mt.base.size) - else: - # XXX we should use the dynamic type here too, but that is not stored - # in the inbox at all --> use source[]'s object type? but how? we need - # a tyRef to the object! - var obj = newObj(mt, mt.base.size) - unsureAsgnRef(x, obj) - storeAux(x[], s, mt.base, t, mode) - if mode != mStore: dealloc(t.region, s) - else: - copyMem(dest, src, mt.size) # copy raw bits - -proc rawSend(q: PRawChannel, data: pointer, typ: PNimType) = - ## adds an `item` to the end of the queue `q`. - var cap = q.mask+1 - if q.count >= cap: - # start with capacity for 2 entries in the queue: - if cap == 0: cap = 1 - var n = cast[pbytes](alloc0(q.region, cap*2*typ.size)) - var z = 0 - var i = q.rd - var c = q.count - while c > 0: - dec c - copyMem(addr(n[z*typ.size]), addr(q.data[i*typ.size]), typ.size) - i = (i + 1) and q.mask - inc z - if q.data != nil: dealloc(q.region, q.data) - q.data = n - q.mask = cap*2 - 1 - q.wr = q.count - q.rd = 0 - storeAux(addr(q.data[q.wr * typ.size]), data, typ, q, mStore) - inc q.count - q.wr = (q.wr + 1) and q.mask - -proc rawRecv(q: PRawChannel, data: pointer, typ: PNimType) = - sysAssert q.count > 0, "rawRecv" - dec q.count - storeAux(data, addr(q.data[q.rd * typ.size]), typ, q, mLoad) - q.rd = (q.rd + 1) and q.mask - -template lockChannel(q: expr, action: stmt) {.immediate.} = - acquireSys(q.lock) - action - releaseSys(q.lock) - -template sendImpl(q: expr) {.immediate.} = - if q.mask == ChannelDeadMask: - sysFatal(DeadThreadError, "cannot send message; thread died") - acquireSys(q.lock) - var m: TMsg - shallowCopy(m, msg) - var typ = cast[PNimType](getTypeInfo(msg)) - rawSend(q, addr(m), typ) - q.elemType = typ - releaseSys(q.lock) - signalSysCond(q.cond) - -proc send*[TMsg](c: var Channel[TMsg], msg: TMsg) = - ## sends a message to a thread. `msg` is deeply copied. - var q = cast[PRawChannel](addr(c)) - sendImpl(q) - -proc llRecv(q: PRawChannel, res: pointer, typ: PNimType) = - # to save space, the generic is as small as possible - q.ready = true - while q.count <= 0: - waitSysCond(q.cond, q.lock) - q.ready = false - if typ != q.elemType: - releaseSys(q.lock) - sysFatal(ValueError, "cannot receive message of wrong type") - rawRecv(q, res, typ) - -proc recv*[TMsg](c: var Channel[TMsg]): TMsg = - ## receives a message from the channel `c`. This blocks until - ## a message has arrived! You may use ``peek`` to avoid the blocking. - var q = cast[PRawChannel](addr(c)) - acquireSys(q.lock) - llRecv(q, addr(result), cast[PNimType](getTypeInfo(result))) - releaseSys(q.lock) - -proc tryRecv*[TMsg](c: var Channel[TMsg]): tuple[dataAvailable: bool, - msg: TMsg] = - ## try to receives a message from the channel `c` if available. Otherwise - ## it returns ``(false, default(msg))``. - var q = cast[PRawChannel](addr(c)) - if q.mask != ChannelDeadMask: +const ChannelDeadMask = -2 + +proc initRawChannel(p: pointer) = + var c = cast[PRawChannel](p) + initSysLock(c.lock) + initSysCond(c.cond) + c.mask = -1 + +proc deinitRawChannel(p: pointer) = + var c = cast[PRawChannel](p) + # we need to grab the lock to be safe against sending threads! + acquireSys(c.lock) + c.mask = ChannelDeadMask + deallocOsPages(c.region) + deinitSys(c.lock) + deinitSysCond(c.cond) + +proc storeAux(dest, src: pointer, mt: PNimType, t: PRawChannel, + mode: LoadStoreMode) {.benign.} +proc storeAux(dest, src: pointer, n: ptr TNimNode, t: PRawChannel, + mode: LoadStoreMode) {.benign.} = + var + d = cast[ByteAddress](dest) + s = cast[ByteAddress](src) + case n.kind + of nkSlot: storeAux(cast[pointer](d +% n.offset), + cast[pointer](s +% n.offset), n.typ, t, mode) + of nkList: + for i in 0..n.len-1: storeAux(dest, src, n.sons[i], t, mode) + of nkCase: + copyMem(cast[pointer](d +% n.offset), cast[pointer](s +% n.offset), + n.typ.size) + var m = selectBranch(src, n) + if m != nil: storeAux(dest, src, m, t, mode) + of nkNone: sysAssert(false, "storeAux") + +proc storeAux(dest, src: pointer, mt: PNimType, t: PRawChannel, + mode: LoadStoreMode) = + var + d = cast[ByteAddress](dest) + s = cast[ByteAddress](src) + sysAssert(mt != nil, "mt == nil") + case mt.kind + of tyString: + if mode == mStore: + var x = cast[PPointer](dest) + var s2 = cast[PPointer](s)[] + if s2 == nil: + x[] = nil + else: + var ss = cast[NimString](s2) + var ns = cast[NimString](alloc(t.region, ss.len+1 + GenericSeqSize)) + copyMem(ns, ss, ss.len+1 + GenericSeqSize) + x[] = ns + else: + var x = cast[PPointer](dest) + var s2 = cast[PPointer](s)[] + if s2 == nil: + unsureAsgnRef(x, s2) + else: + unsureAsgnRef(x, copyString(cast[NimString](s2))) + dealloc(t.region, s2) + of tySequence: + var s2 = cast[PPointer](src)[] + var seq = cast[PGenericSeq](s2) + var x = cast[PPointer](dest) + if s2 == nil: + if mode == mStore: + x[] = nil + else: + unsureAsgnRef(x, nil) + else: + sysAssert(dest != nil, "dest == nil") + if mode == mStore: + x[] = alloc(t.region, seq.len *% mt.base.size +% GenericSeqSize) + else: + unsureAsgnRef(x, newObj(mt, seq.len * mt.base.size + GenericSeqSize)) + var dst = cast[ByteAddress](cast[PPointer](dest)[]) + for i in 0..seq.len-1: + storeAux( + cast[pointer](dst +% i*% mt.base.size +% GenericSeqSize), + cast[pointer](cast[ByteAddress](s2) +% i *% mt.base.size +% + GenericSeqSize), + mt.base, t, mode) + var dstseq = cast[PGenericSeq](dst) + dstseq.len = seq.len + dstseq.reserved = seq.len + if mode != mStore: dealloc(t.region, s2) + of tyObject: + # copy type field: + var pint = cast[ptr PNimType](dest) + # XXX use dynamic type here! + pint[] = mt + if mt.base != nil: + storeAux(dest, src, mt.base, t, mode) + storeAux(dest, src, mt.node, t, mode) + of tyTuple: + storeAux(dest, src, mt.node, t, mode) + of tyArray, tyArrayConstr: + for i in 0..(mt.size div mt.base.size)-1: + storeAux(cast[pointer](d +% i*% mt.base.size), + cast[pointer](s +% i*% mt.base.size), mt.base, t, mode) + of tyRef: + var s = cast[PPointer](src)[] + var x = cast[PPointer](dest) + if s == nil: + if mode == mStore: + x[] = nil + else: + unsureAsgnRef(x, nil) + else: + if mode == mStore: + x[] = alloc(t.region, mt.base.size) + else: + # XXX we should use the dynamic type here too, but that is not stored + # in the inbox at all --> use source[]'s object type? but how? we need + # a tyRef to the object! + var obj = newObj(mt, mt.base.size) + unsureAsgnRef(x, obj) + storeAux(x[], s, mt.base, t, mode) + if mode != mStore: dealloc(t.region, s) + else: + copyMem(dest, src, mt.size) # copy raw bits + +proc rawSend(q: PRawChannel, data: pointer, typ: PNimType) = + ## adds an `item` to the end of the queue `q`. + var cap = q.mask+1 + if q.count >= cap: + # start with capacity for 2 entries in the queue: + if cap == 0: cap = 1 + var n = cast[pbytes](alloc0(q.region, cap*2*typ.size)) + var z = 0 + var i = q.rd + var c = q.count + while c > 0: + dec c + copyMem(addr(n[z*typ.size]), addr(q.data[i*typ.size]), typ.size) + i = (i + 1) and q.mask + inc z + if q.data != nil: dealloc(q.region, q.data) + q.data = n + q.mask = cap*2 - 1 + q.wr = q.count + q.rd = 0 + storeAux(addr(q.data[q.wr * typ.size]), data, typ, q, mStore) + inc q.count + q.wr = (q.wr + 1) and q.mask + +proc rawRecv(q: PRawChannel, data: pointer, typ: PNimType) = + sysAssert q.count > 0, "rawRecv" + dec q.count + storeAux(data, addr(q.data[q.rd * typ.size]), typ, q, mLoad) + q.rd = (q.rd + 1) and q.mask + +template lockChannel(q: expr, action: stmt) {.immediate.} = + acquireSys(q.lock) + action + releaseSys(q.lock) + +template sendImpl(q: expr) {.immediate.} = + if q.mask == ChannelDeadMask: + sysFatal(DeadThreadError, "cannot send message; thread died") + acquireSys(q.lock) + var m: TMsg + shallowCopy(m, msg) + var typ = cast[PNimType](getTypeInfo(msg)) + rawSend(q, addr(m), typ) + q.elemType = typ + releaseSys(q.lock) + signalSysCond(q.cond) + +proc send*[TMsg](c: var Channel[TMsg], msg: TMsg) = + ## sends a message to a thread. `msg` is deeply copied. + var q = cast[PRawChannel](addr(c)) + sendImpl(q) + +proc llRecv(q: PRawChannel, res: pointer, typ: PNimType) = + # to save space, the generic is as small as possible + q.ready = true + while q.count <= 0: + waitSysCond(q.cond, q.lock) + q.ready = false + if typ != q.elemType: + releaseSys(q.lock) + sysFatal(ValueError, "cannot receive message of wrong type") + rawRecv(q, res, typ) + +proc recv*[TMsg](c: var Channel[TMsg]): TMsg = + ## receives a message from the channel `c`. This blocks until + ## a message has arrived! You may use ``peek`` to avoid the blocking. + var q = cast[PRawChannel](addr(c)) + acquireSys(q.lock) + llRecv(q, addr(result), cast[PNimType](getTypeInfo(result))) + releaseSys(q.lock) + +proc tryRecv*[TMsg](c: var Channel[TMsg]): tuple[dataAvailable: bool, + msg: TMsg] = + ## try to receives a message from the channel `c` if available. Otherwise + ## it returns ``(false, default(msg))``. + var q = cast[PRawChannel](addr(c)) + if q.mask != ChannelDeadMask: if tryAcquireSys(q.lock): - if q.count > 0: - llRecv(q, addr(result.msg), cast[PNimType](getTypeInfo(result.msg))) - result.dataAvailable = true - releaseSys(q.lock) - -proc peek*[TMsg](c: var Channel[TMsg]): int = - ## returns the current number of messages in the channel `c`. Returns -1 - ## if the channel has been closed. **Note**: This is dangerous to use - ## as it encourages races. It's much better to use ``tryRecv`` instead. - var q = cast[PRawChannel](addr(c)) - if q.mask != ChannelDeadMask: - lockChannel(q): - result = q.count - else: - result = -1 - -proc open*[TMsg](c: var Channel[TMsg]) = - ## opens a channel `c` for inter thread communication. - initRawChannel(addr(c)) - -proc close*[TMsg](c: var Channel[TMsg]) = - ## closes a channel `c` and frees its associated resources. - deinitRawChannel(addr(c)) - -proc ready*[TMsg](c: var Channel[TMsg]): bool = - ## returns true iff some thread is waiting on the channel `c` for - ## new messages. - var q = cast[PRawChannel](addr(c)) - result = q.ready - + if q.count > 0: + llRecv(q, addr(result.msg), cast[PNimType](getTypeInfo(result.msg))) + result.dataAvailable = true + releaseSys(q.lock) + +proc peek*[TMsg](c: var Channel[TMsg]): int = + ## returns the current number of messages in the channel `c`. Returns -1 + ## if the channel has been closed. **Note**: This is dangerous to use + ## as it encourages races. It's much better to use ``tryRecv`` instead. + var q = cast[PRawChannel](addr(c)) + if q.mask != ChannelDeadMask: + lockChannel(q): + result = q.count + else: + result = -1 + +proc open*[TMsg](c: var Channel[TMsg]) = + ## opens a channel `c` for inter thread communication. + initRawChannel(addr(c)) + +proc close*[TMsg](c: var Channel[TMsg]) = + ## closes a channel `c` and frees its associated resources. + deinitRawChannel(addr(c)) + +proc ready*[TMsg](c: var Channel[TMsg]): bool = + ## returns true iff some thread is waiting on the channel `c` for + ## new messages. + var q = cast[PRawChannel](addr(c)) + result = q.ready + diff --git a/lib/system/deepcopy.nim b/lib/system/deepcopy.nim index 093c0f3a7..03230e541 100644 --- a/lib/system/deepcopy.nim +++ b/lib/system/deepcopy.nim @@ -14,7 +14,7 @@ proc genericDeepCopyAux(dest, src: pointer, n: ptr TNimNode) {.benign.} = s = cast[ByteAddress](src) case n.kind of nkSlot: - genericDeepCopyAux(cast[pointer](d +% n.offset), + genericDeepCopyAux(cast[pointer](d +% n.offset), cast[pointer](s +% n.offset), n.typ) of nkList: for i in 0..n.len-1: @@ -24,7 +24,7 @@ proc genericDeepCopyAux(dest, src: pointer, n: ptr TNimNode) {.benign.} = var m = selectBranch(src, n) # reset if different branches are in use; note different branches also # imply that's not self-assignment (``x = x``)! - if m != dd and dd != nil: + if m != dd and dd != nil: genericResetAux(dest, dd) copyMem(cast[pointer](d +% n.offset), cast[pointer](s +% n.offset), n.typ.size) @@ -103,16 +103,16 @@ proc genericDeepCopyAux(dest, src: pointer, mt: PNimType) = else: let realType = x.typ let z = newObj(realType, realType.base.size) - + unsureAsgnRef(cast[PPointer](dest), z) x.typ = cast[PNimType](cast[int](z) or 1) genericDeepCopyAux(z, s2, realType.base) x.typ = realType else: let realType = mt - let z = newObj(realType, realType.base.size) + let z = newObj(realType, realType.base.size) unsureAsgnRef(cast[PPointer](dest), z) - genericDeepCopyAux(z, s2, realType.base) + genericDeepCopyAux(z, s2, realType.base) of tyPtr: # no cycle check here, but also not really required let s2 = cast[PPointer](src)[] diff --git a/lib/system/gc2.nim b/lib/system/gc2.nim index 015e08c9e..4ca0d144f 100644 --- a/lib/system/gc2.nim +++ b/lib/system/gc2.nim @@ -37,19 +37,19 @@ const rcAlive = 0b00000 # object is reachable. # color *black* in the original paper - + rcCycleCandidate = 0b00001 # possible root of a cycle. *purple* rcDecRefApplied = 0b00010 # the first dec-ref phase of the # collector was already applied to this # object. *gray* - + rcMaybeDead = 0b00011 # this object is a candidate for deletion # during the collect cycles algorithm. # *white*. - + rcReallyDead = 0b00100 # this is proved to be garbage - + rcRetiredBuffer = 0b00101 # this is a seq or string buffer that # was replaced by a resize operation. # see growObj for details @@ -80,14 +80,14 @@ const # The bit must also be set for new objects that are not rc1 and it must be # examined in the decref loop in collectCycles. # XXX: not implemented yet as tests didn't show any improvement from this - + MarkingSkipsAcyclicObjects = true - # Acyclic objects can be safely ignored in the mark and scan phases, + # Acyclic objects can be safely ignored in the mark and scan phases, # because they cannot contribute to the internal count. # XXX: if we generate specialized `markCyclic` and `markAcyclic` # procs we can further optimize this as there won't be need for any # checks in the code - + MinimumStackMarking = false # Try to scan only the user stack and ignore the part of the stack # belonging to the GC itself. see setStackTop for further info. @@ -110,9 +110,9 @@ type maxThreshold: int # max threshold that has been set maxStackSize: int # max stack size maxStackCells: int # max stack cells in ``decStack`` - cycleTableSize: int # max entries in cycle table + cycleTableSize: int # max entries in cycle table maxPause: int64 # max measured GC pause in nanoseconds - + GcHeap {.final, pure.} = object # this contains the zero count and # non-zero count table stackBottom: pointer @@ -124,7 +124,7 @@ type tempStack: CellSeq # temporary stack for recursion elimination freeStack: CellSeq # objects ready to be freed recGcLock: int # prevent recursion via finalizers; no thread lock - cycleRootsTrimIdx: int # Trimming is a light-weight collection of the + cycleRootsTrimIdx: int # Trimming is a light-weight collection of the # cycle roots table that uses a cheap linear scan # to find only possitively dead objects. # One strategy is to perform it only for new objects @@ -143,11 +143,11 @@ var when not defined(useNimRtl): instantiateForRegion(gch.region) -template acquire(gch: GcHeap) = +template acquire(gch: GcHeap) = when hasThreadSupport and hasSharedHeap: AcquireSys(HeapLock) -template release(gch: GcHeap) = +template release(gch: GcHeap) = when hasThreadSupport and hasSharedHeap: releaseSys(HeapLock) @@ -185,7 +185,7 @@ when debugGC: of rcRetiredBuffer: return "retired" of rcReallyDead: return "dead" else: return "unknown?" - + proc inCycleRootsStr(c: PCell): cstring = if c.isBitUp(rcInCycleRoots): result = "cycleroot" else: result = "" @@ -225,7 +225,7 @@ template setStackTop(gch) = template addCycleRoot(cycleRoots: var CellSeq, c: PCell) = if c.color != rcCycleCandidate: c.setColor rcCycleCandidate - + # the object may be buffered already. for example, consider: # decref; incref; decref if c.isBitDown(rcInCycleRoots): @@ -307,7 +307,7 @@ when traceGC: let startLen = gch.tempStack.len c.forAllChildren waPush - + while startLen != gch.tempStack.len: dec gch.tempStack.len var c = gch.tempStack.d[gch.tempStack.len] @@ -331,7 +331,7 @@ when traceGC: if c.isBitUp(rcMarkBit) and not isMarked: writecell("cyclic cell", cell) cprintf "Weight %d\n", cell.computeCellWeight - + proc writeLeakage(onlyRoots: bool) = if onlyRoots: for c in elements(states[csAllocated]): @@ -356,7 +356,7 @@ template WithHeapLock(blk: stmt): stmt = blk when hasThreadSupport and hasSharedHeap: ReleaseSys(HeapLock) -proc rtlAddCycleRoot(c: PCell) {.rtl, inl.} = +proc rtlAddCycleRoot(c: PCell) {.rtl, inl.} = # we MUST access gch as a global here, because this crosses DLL boundaries! WithHeapLock: addCycleRoot(gch.cycleRoots, c) @@ -423,7 +423,7 @@ template doIncRef(cc: PCell, elif IncRefRemovesCandidates: c.setColor rcAlive # XXX: this is not really atomic enough! - + proc nimGCref(p: pointer) {.compilerProc, inline.} = doIncRef(usrToCell(p)) proc nimGCunref(p: pointer) {.compilerProc, inline.} = doDecRef(usrToCell(p)) @@ -449,7 +449,7 @@ proc asgnRef(dest: PPointer, src: pointer) {.compilerProc, inline.} = doAsgnRef(dest, src, LocalHeap, MaybeCyclic) proc asgnRefNoCycle(dest: PPointer, src: pointer) {.compilerProc, inline.} = - # the code generator calls this proc if it is known at compile time that no + # the code generator calls this proc if it is known at compile time that no # cycle is possible. doAsgnRef(dest, src, LocalHeap, Acyclic) @@ -509,7 +509,7 @@ proc forAllSlotsAux(dest: pointer, n: ptr TNimNode, op: WalkOp) = if n.sons[i].typ.kind in {tyRef, tyString, tySequence}: doOperation(cast[PPointer](d +% n.sons[i].offset)[], op) else: - forAllChildrenAux(cast[pointer](d +% n.sons[i].offset), + forAllChildrenAux(cast[pointer](d +% n.sons[i].offset), n.sons[i].typ, op) else: forAllSlotsAux(dest, n.sons[i], op) @@ -557,7 +557,7 @@ proc addNewObjToZCT(res: PCell, gch: var GcHeap) {.inline.} = # we check the last 8 entries (cache line) for a slot that could be reused. # In 63% of all cases we succeed here! But we have to optimize the heck # out of this small linear search so that ``newObj`` is not slowed down. - # + # # Slots to try cache hit # 1 32% # 4 59% @@ -602,7 +602,7 @@ proc rawNewObj(typ: PNimType, size: int, gch: var GcHeap, rc1 = false): pointer acquire(gch) sysAssert(allocInv(gch.region), "rawNewObj begin") sysAssert(typ.kind in {tyRef, tyString, tySequence}, "newObj: 1") - + collectCT(gch) sysAssert(allocInv(gch.region), "rawNewObj after collect") @@ -610,16 +610,16 @@ proc rawNewObj(typ: PNimType, size: int, gch: var GcHeap, rc1 = false): pointer sysAssert(allocInv(gch.region), "rawNewObj after rawAlloc") sysAssert((cast[ByteAddress](res) and (MemAlign-1)) == 0, "newObj: 2") - + res.typ = typ - + when trackAllocationSource and not hasThreadSupport: if framePtr != nil and framePtr.prev != nil and framePtr.prev.prev != nil: res.filename = framePtr.prev.prev.filename res.line = framePtr.prev.prev.line else: res.filename = "nofile" - + if rc1: res.refcount = rcIncrement # refcount is 1 else: @@ -631,9 +631,9 @@ proc rawNewObj(typ: PNimType, size: int, gch: var GcHeap, rc1 = false): pointer res.setBit(rcInCycleRoots) res.setColor rcCycleCandidate gch.cycleRoots.add res - + sysAssert(isAllocatedPtr(gch.region, res), "newObj: 3") - + when logGC: writeCell("new cell", res) gcTrace(res, csAllocated) release(gch) @@ -711,9 +711,9 @@ proc growObj(old: pointer, newsize: int, gch: var GcHeap): pointer = var res = cast[PCell](rawAlloc(gch.region, newsize + sizeof(Cell))) var elemSize = if ol.typ.kind != tyString: ol.typ.base.size else: 1 - + var oldsize = cast[PGenericSeq](old).len*elemSize + GenericSeqSize - + # XXX: This should happen outside # call user-defined move code # call user-defined default constructor @@ -723,24 +723,24 @@ proc growObj(old: pointer, newsize: int, gch: var GcHeap): pointer = sysAssert((cast[ByteAddress](res) and (MemAlign-1)) == 0, "growObj: 3") sysAssert(res.refcount shr rcShift <=% 1, "growObj: 4") - + when false: if ol.isBitUp(rcZct): var j = gch.zct.len-1 var d = gch.zct.d - while j >= 0: + while j >= 0: if d[j] == ol: d[j] = res break dec(j) - + if ol.isBitUp(rcInCycleRoots): for i in 0 .. 0: repeat @@ -1030,12 +1030,12 @@ proc gcMark(gch: var GcHeap, p: pointer) {.inline.} = add(gch.decStack, cell) sysAssert(allocInv(gch.region), "gcMark end") -proc markThreadStacks(gch: var GcHeap) = +proc markThreadStacks(gch: var GcHeap) = when hasThreadSupport and hasSharedHeap: {.error: "not fully implemented".} var it = threadList while it != nil: - # mark registers: + # mark registers: for i in 0 .. high(it.registers): gcMark(gch, it.registers[i]) var sp = cast[ByteAddress](it.stackBottom) var max = cast[ByteAddress](it.stackTop) @@ -1121,7 +1121,7 @@ elif stackIncreases: var b = cast[ByteAddress](stackTop) var x = cast[ByteAddress](p) result = a <=% x and x <=% b - + proc markStackAndRegisters(gch: var GcHeap) {.noinline, cdecl.} = var registers: C_JmpBuf if c_setjmp(registers) == 0'i32: # To fill the C stack with registers. @@ -1156,7 +1156,7 @@ else: # mark the registers var jmpbufPtr = cast[ByteAddress](addr(registers)) var jmpbufEnd = jmpbufPtr +% jmpbufSize - + while jmpbufPtr <=% jmpbufEnd: gcMark(gch, cast[PPointer](jmpbufPtr)[]) jmpbufPtr = jmpbufPtr +% sizeof(pointer) @@ -1218,18 +1218,18 @@ proc releaseCell(gch: var GcHeap, cell: PCell) = proc collectZCT(gch: var GcHeap): bool = const workPackage = 100 var L = addr(gch.zct.len) - + when withRealtime: var steps = workPackage var t0: Ticks if gch.maxPause > 0: t0 = getticks() - + while L[] > 0: var c = gch.zct.d[0] sysAssert c.isBitUp(rcZct), "collectZCT: rcZct missing!" sysAssert(isAllocatedPtr(gch.region, c), "collectZCT: isAllocatedPtr") - - # remove from ZCT: + + # remove from ZCT: c.clearBit(rcZct) gch.zct.d[0] = gch.zct.d[L[] - 1] dec(L[]) @@ -1237,7 +1237,7 @@ proc collectZCT(gch: var GcHeap): bool = if c.refcount <% rcIncrement: # It may have a RC > 0, if it is in the hardware stack or # it has not been removed yet from the ZCT. This is because - # ``incref`` does not bother to remove the cell from the ZCT + # ``incref`` does not bother to remove the cell from the ZCT # as this might be too slow. # In any case, it should be removed from the ZCT. But not # freed. **KEEP THIS IN MIND WHEN MAKING THIS INCREMENTAL!** @@ -1252,7 +1252,7 @@ proc collectZCT(gch: var GcHeap): bool = steps = workPackage if gch.maxPause > 0: let duration = getticks() - t0 - # the GC's measuring is not accurate and needs some cleanup actions + # the GC's measuring is not accurate and needs some cleanup actions # (stack unmarking), so subtract some short amount of time in to # order to miss deadlines less often: if duration >= gch.maxPause - 50_000: @@ -1269,7 +1269,7 @@ proc unmarkStackAndRegisters(gch: var GcHeap) = # XXX: just call doDecRef? var c = d[i] sysAssert c.typ != nil, "unmarkStackAndRegisters 2" - + if c.color == rcRetiredBuffer: continue @@ -1278,7 +1278,7 @@ proc unmarkStackAndRegisters(gch: var GcHeap) = # the object survived only because of a stack reference # it still doesn't have heap references addZCT(gch.zct, c) - + if canbeCycleRoot(c): # any cyclic object reachable from the stack can be turned into # a leak if it's orphaned through the stack reference @@ -1293,7 +1293,7 @@ proc collectCTBody(gch: var GcHeap) = let t0 = getticks() when debugGC: inc gcCollectionIdx sysAssert(allocInv(gch.region), "collectCT: begin") - + gch.stat.maxStackSize = max(gch.stat.maxStackSize, stackSize()) sysAssert(gch.decStack.len == 0, "collectCT") prepareForInteriorPointerChecking(gch.region) @@ -1312,7 +1312,7 @@ proc collectCTBody(gch: var GcHeap) = gch.stat.maxThreshold = max(gch.stat.maxThreshold, gch.cycleThreshold) unmarkStackAndRegisters(gch) sysAssert(allocInv(gch.region), "collectCT: end") - + when withRealtime: let duration = getticks() - t0 gch.stat.maxPause = max(gch.stat.maxPause, duration) @@ -1322,7 +1322,7 @@ proc collectCTBody(gch: var GcHeap) = proc collectCT(gch: var GcHeap) = if (gch.zct.len >= ZctThreshold or (cycleGC and - getOccupiedMem(gch.region)>=gch.cycleThreshold) or alwaysGC) and + getOccupiedMem(gch.region)>=gch.cycleThreshold) or alwaysGC) and gch.recGcLock == 0: collectCTBody(gch) @@ -1337,7 +1337,7 @@ when withRealtime: acquire(gch) gch.maxPause = us.toNano if (gch.zct.len >= ZctThreshold or (cycleGC and - getOccupiedMem(gch.region)>=gch.cycleThreshold) or alwaysGC) or + getOccupiedMem(gch.region)>=gch.cycleThreshold) or alwaysGC) or strongAdvice: collectCTBody(gch) release(gch) @@ -1345,13 +1345,13 @@ when withRealtime: proc GC_step*(us: int, strongAdvice = false) = GC_step(gch, us, strongAdvice) when not defined(useNimRtl): - proc GC_disable() = + proc GC_disable() = when hasThreadSupport and hasSharedHeap: discard atomicInc(gch.recGcLock, 1) else: inc(gch.recGcLock) proc GC_enable() = - if gch.recGcLock > 0: + if gch.recGcLock > 0: when hasThreadSupport and hasSharedHeap: discard atomicDec(gch.recGcLock, 1) else: diff --git a/lib/system/gc_common.nim b/lib/system/gc_common.nim index c7dd667e4..ceb362378 100644 --- a/lib/system/gc_common.nim +++ b/lib/system/gc_common.nim @@ -197,7 +197,7 @@ else: var x = cast[ByteAddress](p) if a <=% x and x <=% b: return true - + template forEachStackSlot(gch, gcMark: expr) {.immediate, dirty.} = # We use a jmp_buf buffer that is in the C stack. # Used to traverse the stack and registers assuming @@ -207,7 +207,7 @@ else: getRegisters(registers) for i in registers.low .. registers.high: gcMark(gch, cast[PPointer](registers[i])) - + for stack in items(gch.stack): stack.maxStackSize = max(stack.maxStackSize, stackSize(stack.starts)) var max = cast[ByteAddress](stack.starts) diff --git a/lib/system/inclrtl.nim b/lib/system/inclrtl.nim index d0dc38284..201a99ca7 100644 --- a/lib/system/inclrtl.nim +++ b/lib/system/inclrtl.nim @@ -20,21 +20,21 @@ when not defined(nimNewShared): {.pragma: gcsafe.} when defined(createNimRtl): - when defined(useNimRtl): + when defined(useNimRtl): {.error: "Cannot create and use nimrtl at the same time!".} elif appType != "lib": {.error: "nimrtl must be built as a library!".} -when defined(createNimRtl): +when defined(createNimRtl): {.pragma: rtl, exportc: "nimrtl_$1", dynlib, gcsafe.} {.pragma: inl.} {.pragma: compilerRtl, compilerproc, exportc: "nimrtl_$1", dynlib.} elif defined(useNimRtl): - when defined(windows): + when defined(windows): const nimrtl* = "nimrtl.dll" elif defined(macosx): const nimrtl* = "libnimrtl.dylib" - else: + else: const nimrtl* = "libnimrtl.so" {.pragma: rtl, importc: "nimrtl_$1", dynlib: nimrtl, gcsafe.} {.pragma: inl.} diff --git a/lib/system/profiler.nim b/lib/system/profiler.nim index c93456fb3..4f600417e 100644 --- a/lib/system/profiler.nim +++ b/lib/system/profiler.nim @@ -40,7 +40,7 @@ proc captureStackTrace(f: PFrame, st: var StackTrace) = while it != nil: inc(total) it = it.prev - for j in 1..total-i-(firstCalls-1): + for j in 1..total-i-(firstCalls-1): if b != nil: b = b.prev if total != i: st[i] = "..." diff --git a/lib/system/syslocks.nim b/lib/system/syslocks.nim index ec8c26275..7a113b9d4 100644 --- a/lib/system/syslocks.nim +++ b/lib/system/syslocks.nim @@ -23,7 +23,7 @@ when defined(Windows): SysCond = Handle {.deprecated: [THandle: Handle, TSysLock: SysLock, TSysCond: SysCond].} - + proc initSysLock(L: var SysLock) {.stdcall, noSideEffect, dynlib: "kernel32", importc: "InitializeCriticalSection".} ## Initializes the lock `L`. @@ -31,14 +31,14 @@ when defined(Windows): proc tryAcquireSysAux(L: var SysLock): int32 {.stdcall, noSideEffect, dynlib: "kernel32", importc: "TryEnterCriticalSection".} ## Tries to acquire the lock `L`. - - proc tryAcquireSys(L: var SysLock): bool {.inline.} = + + proc tryAcquireSys(L: var SysLock): bool {.inline.} = result = tryAcquireSysAux(L) != 0'i32 proc acquireSys(L: var SysLock) {.stdcall, noSideEffect, dynlib: "kernel32", importc: "EnterCriticalSection".} ## Acquires the lock `L`. - + proc releaseSys(L: var SysLock) {.stdcall, noSideEffect, dynlib: "kernel32", importc: "LeaveCriticalSection".} ## Releases the lock `L`. @@ -46,11 +46,11 @@ when defined(Windows): proc deinitSys(L: var SysLock) {.stdcall, noSideEffect, dynlib: "kernel32", importc: "DeleteCriticalSection".} - proc createEvent(lpEventAttributes: pointer, + proc createEvent(lpEventAttributes: pointer, bManualReset, bInitialState: int32, lpName: cstring): SysCond {.stdcall, noSideEffect, dynlib: "kernel32", importc: "CreateEventA".} - + proc closeHandle(hObject: Handle) {.stdcall, noSideEffect, dynlib: "kernel32", importc: "CloseHandle".} proc waitForSingleObject(hHandle: Handle, dwMilliseconds: int32): int32 {. @@ -58,7 +58,7 @@ when defined(Windows): proc signalSysCond(hEvent: SysCond) {.stdcall, noSideEffect, dynlib: "kernel32", importc: "SetEvent".} - + proc initSysCond(cond: var SysCond) {.inline.} = cond = createEvent(nil, 0'i32, 0'i32, nil) proc deinitSysCond(cond: var SysCond) {.inline.} = @@ -86,7 +86,7 @@ else: proc tryAcquireSysAux(L: var SysLock): cint {.noSideEffect, importc: "pthread_mutex_trylock", header: "".} - proc tryAcquireSys(L: var SysLock): bool {.inline.} = + proc tryAcquireSys(L: var SysLock): bool {.inline.} = result = tryAcquireSysAux(L) == 0'i32 proc releaseSys(L: var SysLock) {.noSideEffect, @@ -100,7 +100,7 @@ else: importc: "pthread_cond_wait", header: "", noSideEffect.} proc signalSysCond(cond: var SysCond) {. importc: "pthread_cond_signal", header: "", noSideEffect.} - + proc deinitSysCond(cond: var SysCond) {.noSideEffect, importc: "pthread_cond_destroy", header: "".} - + diff --git a/lib/system/sysspawn.nim b/lib/system/sysspawn.nim index 5f8f2b2c5..7aef86df9 100644 --- a/lib/system/sysspawn.nim +++ b/lib/system/sysspawn.nim @@ -9,7 +9,7 @@ ## Implements Nim's 'spawn'. -when not declared(NimString): +when not declared(NimString): {.error: "You must not import this module explicitly".} {.push stackTrace:off.} diff --git a/lib/system/timers.nim b/lib/system/timers.nim index 74748c541..ac8418824 100644 --- a/lib/system/timers.nim +++ b/lib/system/timers.nim @@ -34,8 +34,8 @@ when defined(windows): elif defined(macosx): type - MachTimebaseInfoData {.pure, final, - importc: "mach_timebase_info_data_t", + MachTimebaseInfoData {.pure, final, + importc: "mach_timebase_info_data_t", header: "".} = object numer, denom: int32 {.deprecated: [TMachTimebaseInfoData: MachTimebaseInfoData].} @@ -46,10 +46,10 @@ elif defined(macosx): proc getTicks(): Ticks {.inline.} = result = Ticks(mach_absolute_time()) - + var timeBaseInfo: MachTimebaseInfoData mach_timebase_info(timeBaseInfo) - + proc `-`(a, b: Ticks): Nanos = result = (a.int64 - b.int64) * timeBaseInfo.numer div timeBaseInfo.denom @@ -57,10 +57,10 @@ elif defined(posixRealtime): type Clockid {.importc: "clockid_t", header: "", final.} = object - TimeSpec {.importc: "struct timespec", header: "", + TimeSpec {.importc: "struct timespec", header: "", final, pure.} = object ## struct timespec - tv_sec: int ## Seconds. - tv_nsec: int ## Nanoseconds. + tv_sec: int ## Seconds. + tv_nsec: int ## Nanoseconds. {.deprecated: [TClockid: Clickid, TTimeSpec: TimeSpec].} var @@ -77,12 +77,12 @@ elif defined(posixRealtime): proc `-`(a, b: Ticks): Nanos {.borrow.} else: - # fallback Posix implementation: + # fallback Posix implementation: type - Timeval {.importc: "struct timeval", header: "", + Timeval {.importc: "struct timeval", header: "", final, pure.} = object ## struct timeval - tv_sec: int ## Seconds. - tv_usec: int ## Microseconds. + tv_sec: int ## Seconds. + tv_usec: int ## Microseconds. {.deprecated: [Ttimeval: Timeval].} proc posix_gettimeofday(tp: var Timeval, unused: pointer = nil) {. importc: "gettimeofday", header: "".} @@ -90,7 +90,7 @@ else: proc getTicks(): Ticks = var t: Timeval posix_gettimeofday(t) - result = Ticks(int64(t.tv_sec) * 1000_000_000'i64 + + result = Ticks(int64(t.tv_sec) * 1000_000_000'i64 + int64(t.tv_usec) * 1000'i64) proc `-`(a, b: Ticks): Nanos {.borrow.} diff --git a/lib/system/widestrs.nim b/lib/system/widestrs.nim index 77310b289..5a30a7c0f 100644 --- a/lib/system/widestrs.nim +++ b/lib/system/widestrs.nim @@ -124,7 +124,7 @@ proc `$`*(w: WideCString, estimate: int, replacement: int = 0xFFFD): string = if ch >= UNI_SUR_HIGH_START and ch <= UNI_SUR_HIGH_END: # If the 16 bits following the high surrogate are in the source buffer... let ch2 = int(cast[uint16](w[i])) - + # If it's a low surrogate, convert to UTF32: if ch2 >= UNI_SUR_LOW_START and ch2 <= UNI_SUR_LOW_END: ch = (((ch and halfMask) shl halfShift) + (ch2 and halfMask)) + halfBase @@ -135,7 +135,7 @@ proc `$`*(w: WideCString, estimate: int, replacement: int = 0xFFFD): string = elif ch >= UNI_SUR_LOW_START and ch <= UNI_SUR_LOW_END: #invalid UTF-16 ch = replacement - + if ch < 0x80: result.add chr(ch) elif ch < 0x800: @@ -155,6 +155,6 @@ proc `$`*(w: WideCString, estimate: int, replacement: int = 0xFFFD): string = result.add chr(0xFFFD shr 12 or 0b1110_0000) result.add chr(0xFFFD shr 6 and ones(6) or 0b10_0000_00) result.add chr(0xFFFD and ones(6) or 0b10_0000_00) - + proc `$`*(s: WideCString): string = result = s $ 80 diff --git a/lib/wrappers/libsvm.nim b/lib/wrappers/libsvm.nim index 8cc314412..ac5889410 100644 --- a/lib/wrappers/libsvm.nim +++ b/lib/wrappers/libsvm.nim @@ -10,9 +10,9 @@ ## This module is a low level wrapper for `libsvm`:idx:. {.deadCodeElim: on.} -const +const LIBSVM_VERSION* = 312 - + when defined(windows): const svmdll* = "libsvm.dll" elif defined(macosx): @@ -20,97 +20,97 @@ elif defined(macosx): else: const svmdll* = "libsvm.so" -type - Node*{.pure, final.} = object +type + Node*{.pure, final.} = object index*: cint value*: cdouble - Problem*{.pure, final.} = object + Problem*{.pure, final.} = object L*: cint y*: ptr cdouble x*: ptr ptr Node - Type*{.size: sizeof(cint).} = enum + Type*{.size: sizeof(cint).} = enum C_SVC, NU_SVC, ONE_CLASS, EPSILON_SVR, NU_SVR - - KernelType*{.size: sizeof(cint).} = enum + + KernelType*{.size: sizeof(cint).} = enum LINEAR, POLY, RBF, SIGMOID, PRECOMPUTED - - Parameter*{.pure, final.} = object + + Parameter*{.pure, final.} = object typ*: Type kernelType*: KernelType - degree*: cint # for poly - gamma*: cdouble # for poly/rbf/sigmoid - coef0*: cdouble # for poly/sigmoid - # these are for training only - cache_size*: cdouble # in MB - eps*: cdouble # stopping criteria - C*: cdouble # for C_SVC, EPSILON_SVR and NU_SVR - nr_weight*: cint # for C_SVC - weight_label*: ptr cint # for C_SVC - weight*: ptr cdouble # for C_SVC - nu*: cdouble # for NU_SVC, ONE_CLASS, and NU_SVR - p*: cdouble # for EPSILON_SVR - shrinking*: cint # use the shrinking heuristics - probability*: cint # do probability estimates + degree*: cint # for poly + gamma*: cdouble # for poly/rbf/sigmoid + coef0*: cdouble # for poly/sigmoid + # these are for training only + cache_size*: cdouble # in MB + eps*: cdouble # stopping criteria + C*: cdouble # for C_SVC, EPSILON_SVR and NU_SVR + nr_weight*: cint # for C_SVC + weight_label*: ptr cint # for C_SVC + weight*: ptr cdouble # for C_SVC + nu*: cdouble # for NU_SVC, ONE_CLASS, and NU_SVR + p*: cdouble # for EPSILON_SVR + shrinking*: cint # use the shrinking heuristics + probability*: cint # do probability estimates {.deprecated: [Tnode: Node, Tproblem: Problem, Ttype: Type, TKernelType: KernelType, Tparameter: Parameter].} # # svm_model -# +# -type - Model*{.pure, final.} = object - param*: Parameter # parameter - nr_class*: cint # number of classes, = 2 in regression/one class svm - L*: cint # total #SV +type + Model*{.pure, final.} = object + param*: Parameter # parameter + nr_class*: cint # number of classes, = 2 in regression/one class svm + L*: cint # total #SV SV*: ptr ptr Node # SVs (SV[l]) - sv_coef*: ptr ptr cdouble # coefficients for SVs in decision functions (sv_coef[k-1][l]) - rho*: ptr cdouble # constants in decision functions (rho[k*(k-1)/2]) - probA*: ptr cdouble # pariwise probability information - probB*: ptr cdouble # for classification only - label*: ptr cint # label of each class (label[k]) - nSV*: ptr cint # number of SVs for each class (nSV[k]) - # nSV[0] + nSV[1] + ... + nSV[k-1] = l - # XXX + sv_coef*: ptr ptr cdouble # coefficients for SVs in decision functions (sv_coef[k-1][l]) + rho*: ptr cdouble # constants in decision functions (rho[k*(k-1)/2]) + probA*: ptr cdouble # pariwise probability information + probB*: ptr cdouble # for classification only + label*: ptr cint # label of each class (label[k]) + nSV*: ptr cint # number of SVs for each class (nSV[k]) + # nSV[0] + nSV[1] + ... + nSV[k-1] = l + # XXX free_sv*: cint # 1 if svm_model is created by svm_load_model # 0 if svm_model is created by svm_train {.deprecated: [TModel: Model].} -proc train*(prob: ptr Problem, param: ptr Parameter): ptr Model{.cdecl, +proc train*(prob: ptr Problem, param: ptr Parameter): ptr Model{.cdecl, importc: "svm_train", dynlib: svmdll.} -proc cross_validation*(prob: ptr Problem, param: ptr Parameter, nr_fold: cint, - target: ptr cdouble){.cdecl, +proc cross_validation*(prob: ptr Problem, param: ptr Parameter, nr_fold: cint, + target: ptr cdouble){.cdecl, importc: "svm_cross_validation", dynlib: svmdll.} -proc save_model*(model_file_name: cstring, model: ptr Model): cint{.cdecl, +proc save_model*(model_file_name: cstring, model: ptr Model): cint{.cdecl, importc: "svm_save_model", dynlib: svmdll.} -proc load_model*(model_file_name: cstring): ptr Model{.cdecl, +proc load_model*(model_file_name: cstring): ptr Model{.cdecl, importc: "svm_load_model", dynlib: svmdll.} -proc get_svm_type*(model: ptr Model): cint{.cdecl, importc: "svm_get_svm_type", +proc get_svm_type*(model: ptr Model): cint{.cdecl, importc: "svm_get_svm_type", dynlib: svmdll.} -proc get_nr_class*(model: ptr Model): cint{.cdecl, importc: "svm_get_nr_class", +proc get_nr_class*(model: ptr Model): cint{.cdecl, importc: "svm_get_nr_class", dynlib: svmdll.} -proc get_labels*(model: ptr Model, label: ptr cint){.cdecl, +proc get_labels*(model: ptr Model, label: ptr cint){.cdecl, importc: "svm_get_labels", dynlib: svmdll.} -proc get_svr_probability*(model: ptr Model): cdouble{.cdecl, +proc get_svr_probability*(model: ptr Model): cdouble{.cdecl, importc: "svm_get_svr_probability", dynlib: svmdll.} proc predict_values*(model: ptr Model, x: ptr Node, dec_values: ptr cdouble): cdouble{. cdecl, importc: "svm_predict_values", dynlib: svmdll.} -proc predict*(model: ptr Model, x: ptr Node): cdouble{.cdecl, +proc predict*(model: ptr Model, x: ptr Node): cdouble{.cdecl, importc: "svm_predict", dynlib: svmdll.} -proc predict_probability*(model: ptr Model, x: ptr Node, - prob_estimates: ptr cdouble): cdouble{.cdecl, +proc predict_probability*(model: ptr Model, x: ptr Node, + prob_estimates: ptr cdouble): cdouble{.cdecl, importc: "svm_predict_probability", dynlib: svmdll.} -proc free_model_content*(model_ptr: ptr Model){.cdecl, +proc free_model_content*(model_ptr: ptr Model){.cdecl, importc: "svm_free_model_content", dynlib: svmdll.} -proc free_and_destroy_model*(model_ptr_ptr: ptr ptr Model){.cdecl, +proc free_and_destroy_model*(model_ptr_ptr: ptr ptr Model){.cdecl, importc: "svm_free_and_destroy_model", dynlib: svmdll.} -proc destroy_param*(param: ptr Parameter){.cdecl, importc: "svm_destroy_param", +proc destroy_param*(param: ptr Parameter){.cdecl, importc: "svm_destroy_param", dynlib: svmdll.} proc check_parameter*(prob: ptr Problem, param: ptr Parameter): cstring{. cdecl, importc: "svm_check_parameter", dynlib: svmdll.} -proc check_probability_model*(model: ptr Model): cint{.cdecl, +proc check_probability_model*(model: ptr Model): cint{.cdecl, importc: "svm_check_probability_model", dynlib: svmdll.} proc set_print_string_function*(print_func: proc (arg: cstring) {.cdecl.}){. diff --git a/lib/wrappers/mysql.nim b/lib/wrappers/mysql.nim index 73b82b5c6..8253e53a5 100644 --- a/lib/wrappers/mysql.nim +++ b/lib/wrappers/mysql.nim @@ -20,7 +20,7 @@ when defined(Unix): when defined(Windows): const lib = "libmysql.dll" -type +type my_bool* = bool Pmy_bool* = ptr my_bool PVIO* = pointer @@ -31,13 +31,13 @@ type PPByte* = pointer cuint* = cint -# ------------ Start of declaration in "mysql_com.h" --------------------- +# ------------ Start of declaration in "mysql_com.h" --------------------- # # ** Common definition between mysql server & client -# +# # Field/table name length -const +const NAME_LEN* = 64 HOSTNAME_LENGTH* = 60 USERNAME_LENGTH* = 16 @@ -46,27 +46,27 @@ const LOCAL_HOST* = "localhost" LOCAL_HOST_NAMEDPIPE* = '.' -const +const NAMEDPIPE* = "MySQL" SERVICENAME* = "MySQL" -type - Enum_server_command* = enum - COM_SLEEP, COM_QUIT, COM_INIT_DB, COM_QUERY, COM_FIELD_LIST, COM_CREATE_DB, - COM_DROP_DB, COM_REFRESH, COM_SHUTDOWN, COM_STATISTICS, COM_PROCESS_INFO, - COM_CONNECT, COM_PROCESS_KILL, COM_DEBUG, COM_PING, COM_TIME, - COM_DELAYED_INSERT, COM_CHANGE_USER, COM_BINLOG_DUMP, COM_TABLE_DUMP, - COM_CONNECT_OUT, COM_REGISTER_SLAVE, COM_STMT_PREPARE, COM_STMT_EXECUTE, - COM_STMT_SEND_LONG_DATA, COM_STMT_CLOSE, COM_STMT_RESET, COM_SET_OPTION, +type + Enum_server_command* = enum + COM_SLEEP, COM_QUIT, COM_INIT_DB, COM_QUERY, COM_FIELD_LIST, COM_CREATE_DB, + COM_DROP_DB, COM_REFRESH, COM_SHUTDOWN, COM_STATISTICS, COM_PROCESS_INFO, + COM_CONNECT, COM_PROCESS_KILL, COM_DEBUG, COM_PING, COM_TIME, + COM_DELAYED_INSERT, COM_CHANGE_USER, COM_BINLOG_DUMP, COM_TABLE_DUMP, + COM_CONNECT_OUT, COM_REGISTER_SLAVE, COM_STMT_PREPARE, COM_STMT_EXECUTE, + COM_STMT_SEND_LONG_DATA, COM_STMT_CLOSE, COM_STMT_RESET, COM_SET_OPTION, COM_STMT_FETCH, COM_END {.deprecated: [Tenum_server_command: Enum_server_command].} -const - SCRAMBLE_LENGTH* = 20 # Length of random string sent by server on handshake; - # this is also length of obfuscated password, +const + SCRAMBLE_LENGTH* = 20 # Length of random string sent by server on handshake; + # this is also length of obfuscated password, # received from client - SCRAMBLE_LENGTH_323* = 8 # length of password stored in the db: - # new passwords are preceded with '*' + SCRAMBLE_LENGTH_323* = 8 # length of password stored in the db: + # new passwords are preceded with '*' SCRAMBLED_PASSWORD_CHAR_LENGTH* = SCRAMBLE_LENGTH * 2 + 1 SCRAMBLED_PASSWORD_CHAR_LENGTH_323* = SCRAMBLE_LENGTH_323 * 2 NOT_NULL_FLAG* = 1 # Field can't be NULL @@ -77,7 +77,7 @@ const UNSIGNED_FLAG* = 32 # Field is unsigned ZEROFILL_FLAG* = 64 # Field is zerofill BINARY_FLAG* = 128 # Field is binary - # The following are only sent to new clients + # The following are only sent to new clients ENUM_FLAG* = 256 # field is an enum AUTO_INCREMENT_FLAG* = 512 # field is a autoincrement field TIMESTAMP_FLAG* = 1024 # Field is a timestamp @@ -96,7 +96,7 @@ const REFRESH_THREADS* = 32 # Flush thread cache REFRESH_SLAVE* = 64 # Reset master info and restart slave thread REFRESH_MASTER* = 128 # Remove all bin logs in the index and truncate the index - # The following can't be set with mysql_refresh() + # The following can't be set with mysql_refresh() REFRESH_READ_LOCK* = 16384 # Lock tables for read REFRESH_FAST* = 32768 # Intern flag REFRESH_QUERY_CACHE* = 65536 # RESET (remove all queries) from query cache @@ -129,9 +129,9 @@ const SERVER_QUERY_NO_GOOD_INDEX_USED* = 16 SERVER_QUERY_NO_INDEX_USED* = 32 # The server was able to fulfill the clients request and opened a # read-only non-scrollable cursor for a query. This flag comes - # in reply to COM_STMT_EXECUTE and COM_STMT_FETCH commands. + # in reply to COM_STMT_EXECUTE and COM_STMT_FETCH commands. SERVER_STATUS_CURSOR_EXISTS* = 64 # This flag is sent when a read-only cursor is exhausted, in reply to - # COM_STMT_FETCH command. + # COM_STMT_FETCH command. SERVER_STATUS_LAST_ROW_SENT* = 128 SERVER_STATUS_DB_DROPPED* = 256 # A database was dropped SERVER_STATUS_NO_BACKSLASH_ESCAPES* = 512 @@ -141,7 +141,7 @@ const NET_WAIT_TIMEOUT* = 8 * 60 * 60 # Wait for new query ONLY_KILL_QUERY* = 1 -const +const MAX_TINYINT_WIDTH* = 3 # Max width for a TINY w.o. sign MAX_SMALLINT_WIDTH* = 5 # Max width for a SHORT w.o. sign MAX_MEDIUMINT_WIDTH* = 8 # Max width for a INT24 w.o. sign @@ -150,9 +150,9 @@ const MAX_CHAR_WIDTH* = 255 # Max length for a CHAR column MAX_BLOB_WIDTH* = 8192 # Default width for blob -type +type Pst_net* = ptr St_net - St_net*{.final.} = object + St_net*{.final.} = object vio*: PVio buff*: cstring buff_end*: cstring @@ -169,7 +169,7 @@ type fcntl*: cint compress*: my_bool # The following variable is set if we are doing several queries in one # command ( as in LOAD TABLE ... FROM MASTER ), - # and do not want to confuse the client with OK at the wrong time + # and do not want to confuse the client with OK at the wrong time remain_in_buf*: int len*: int buf_length*: int @@ -182,7 +182,7 @@ type no_send_error*: my_bool # Set if OK packet is already sent, and # we do not need to send error messages # Pointer to query object in query cache, do not equal NULL (0) for - # queries in cache that have not stored its results yet + # queries in cache that have not stored its results yet # $endif last_error*: array[0..(ERRMSG_SIZE) - 1, char] sqlstate*: array[0..(SQLSTATE_LENGTH + 1) - 1, char] @@ -196,21 +196,21 @@ type PNET* = ptr NET {.deprecated: [Tst_net: St_net, TNET: NET].} -const +const packet_error* = - 1 -type - Enum_field_types* = enum # For backward compatibility - TYPE_DECIMAL, TYPE_TINY, TYPE_SHORT, TYPE_LONG, TYPE_FLOAT, TYPE_DOUBLE, - TYPE_NULL, TYPE_TIMESTAMP, TYPE_LONGLONG, TYPE_INT24, TYPE_DATE, TYPE_TIME, - TYPE_DATETIME, TYPE_YEAR, TYPE_NEWDATE, TYPE_VARCHAR, TYPE_BIT, - TYPE_NEWDECIMAL = 246, TYPE_ENUM = 247, TYPE_SET = 248, - TYPE_TINY_BLOB = 249, TYPE_MEDIUM_BLOB = 250, TYPE_LONG_BLOB = 251, - TYPE_BLOB = 252, TYPE_VAR_STRING = 253, TYPE_STRING = 254, +type + Enum_field_types* = enum # For backward compatibility + TYPE_DECIMAL, TYPE_TINY, TYPE_SHORT, TYPE_LONG, TYPE_FLOAT, TYPE_DOUBLE, + TYPE_NULL, TYPE_TIMESTAMP, TYPE_LONGLONG, TYPE_INT24, TYPE_DATE, TYPE_TIME, + TYPE_DATETIME, TYPE_YEAR, TYPE_NEWDATE, TYPE_VARCHAR, TYPE_BIT, + TYPE_NEWDECIMAL = 246, TYPE_ENUM = 247, TYPE_SET = 248, + TYPE_TINY_BLOB = 249, TYPE_MEDIUM_BLOB = 250, TYPE_LONG_BLOB = 251, + TYPE_BLOB = 252, TYPE_VAR_STRING = 253, TYPE_STRING = 254, TYPE_GEOMETRY = 255 {.deprecated: [Tenum_field_types: Enum_field_types].} -const +const CLIENT_MULTI_QUERIES* = CLIENT_MULTI_STATEMENTS FIELD_TYPE_DECIMAL* = TYPE_DECIMAL FIELD_TYPE_NEWDECIMAL* = TYPE_NEWDECIMAL @@ -239,67 +239,67 @@ const FIELD_TYPE_CHAR* = TYPE_TINY FIELD_TYPE_INTERVAL* = TYPE_ENUM FIELD_TYPE_GEOMETRY* = TYPE_GEOMETRY - FIELD_TYPE_BIT* = TYPE_BIT # Shutdown/kill enums and constants - # Bits for THD::killable. + FIELD_TYPE_BIT* = TYPE_BIT # Shutdown/kill enums and constants + # Bits for THD::killable. SHUTDOWN_KILLABLE_CONNECT* = chr(1 shl 0) SHUTDOWN_KILLABLE_TRANS* = chr(1 shl 1) SHUTDOWN_KILLABLE_LOCK_TABLE* = chr(1 shl 2) SHUTDOWN_KILLABLE_UPDATE* = chr(1 shl 3) -type - Enum_shutdown_level* = enum - SHUTDOWN_DEFAULT = 0, SHUTDOWN_WAIT_CONNECTIONS = 1, - SHUTDOWN_WAIT_TRANSACTIONS = 2, SHUTDOWN_WAIT_UPDATES = 8, - SHUTDOWN_WAIT_ALL_BUFFERS = 16, SHUTDOWN_WAIT_CRITICAL_BUFFERS = 17, +type + Enum_shutdown_level* = enum + SHUTDOWN_DEFAULT = 0, SHUTDOWN_WAIT_CONNECTIONS = 1, + SHUTDOWN_WAIT_TRANSACTIONS = 2, SHUTDOWN_WAIT_UPDATES = 8, + SHUTDOWN_WAIT_ALL_BUFFERS = 16, SHUTDOWN_WAIT_CRITICAL_BUFFERS = 17, KILL_QUERY = 254, KILL_CONNECTION = 255 - Enum_cursor_type* = enum # options for mysql_set_option - CURSOR_TYPE_NO_CURSOR = 0, CURSOR_TYPE_READ_ONLY = 1, + Enum_cursor_type* = enum # options for mysql_set_option + CURSOR_TYPE_NO_CURSOR = 0, CURSOR_TYPE_READ_ONLY = 1, CURSOR_TYPE_FOR_UPDATE = 2, CURSOR_TYPE_SCROLLABLE = 4 - Enum_mysql_set_option* = enum + Enum_mysql_set_option* = enum OPTION_MULTI_STATEMENTS_ON, OPTION_MULTI_STATEMENTS_OFF {.deprecated: [Tenum_shutdown_level: Enum_shutdown_level, Tenum_cursor_type: Enum_cursor_type, Tenum_mysql_set_option: Enum_mysql_set_option].} -proc my_net_init*(net: PNET, vio: PVio): my_bool{.cdecl, dynlib: lib, +proc my_net_init*(net: PNET, vio: PVio): my_bool{.cdecl, dynlib: lib, importc: "my_net_init".} -proc my_net_local_init*(net: PNET){.cdecl, dynlib: lib, +proc my_net_local_init*(net: PNET){.cdecl, dynlib: lib, importc: "my_net_local_init".} proc net_end*(net: PNET){.cdecl, dynlib: lib, importc: "net_end".} proc net_clear*(net: PNET){.cdecl, dynlib: lib, importc: "net_clear".} -proc net_realloc*(net: PNET, len: int): my_bool{.cdecl, dynlib: lib, +proc net_realloc*(net: PNET, len: int): my_bool{.cdecl, dynlib: lib, importc: "net_realloc".} proc net_flush*(net: PNET): my_bool{.cdecl, dynlib: lib, importc: "net_flush".} -proc my_net_write*(net: PNET, packet: cstring, length: int): my_bool{.cdecl, +proc my_net_write*(net: PNET, packet: cstring, length: int): my_bool{.cdecl, dynlib: lib, importc: "my_net_write".} -proc net_write_command*(net: PNET, command: char, header: cstring, +proc net_write_command*(net: PNET, command: char, header: cstring, head_len: int, packet: cstring, length: int): my_bool{. cdecl, dynlib: lib, importc: "net_write_command".} -proc net_real_write*(net: PNET, packet: cstring, length: int): cint{.cdecl, +proc net_real_write*(net: PNET, packet: cstring, length: int): cint{.cdecl, dynlib: lib, importc: "net_real_write".} proc my_net_read*(net: PNET): int{.cdecl, dynlib: lib, importc: "my_net_read".} # The following function is not meant for normal usage - # Currently it's used internally by manager.c -type + # Currently it's used internally by manager.c +type Psockaddr* = ptr Sockaddr Sockaddr*{.final.} = object # undefined structure {.deprecated: [Tsockaddr: Sockaddr].} proc my_connect*(s: my_socket, name: Psockaddr, namelen: cuint, timeout: cuint): cint{. cdecl, dynlib: lib, importc: "my_connect".} -type +type Prand_struct* = ptr Rand_struct - Rand_struct*{.final.} = object # The following is for user defined functions + Rand_struct*{.final.} = object # The following is for user defined functions seed1*: int seed2*: int max_value*: int max_value_dbl*: cdouble - Item_result* = enum + Item_result* = enum STRING_RESULT, REAL_RESULT, INT_RESULT, ROW_RESULT, DECIMAL_RESULT PItem_result* = ptr Item_result Pst_udf_args* = ptr St_udf_args - St_udf_args*{.final.} = object + St_udf_args*{.final.} = object arg_count*: cuint # Number of arguments arg_type*: PItem_result # Pointer to item_results args*: cstringArray # Pointer to item_results @@ -307,82 +307,82 @@ type maybe_null*: cstring # Length of string arguments attributes*: cstringArray # Pointer to attribute name attribute_lengths*: ptr int # Length of attribute arguments - + UDF_ARGS* = St_udf_args - PUDF_ARGS* = ptr UDF_ARGS # This holds information about the result + PUDF_ARGS* = ptr UDF_ARGS # This holds information about the result Pst_udf_init* = ptr St_udf_init - St_udf_init*{.final.} = object + St_udf_init*{.final.} = object maybe_null*: my_bool # 1 if function can return NULL decimals*: cuint # for real functions max_length*: int # For string functions theptr*: cstring # free pointer for function data const_item*: my_bool # free pointer for function data - + UDF_INIT* = St_udf_init - PUDF_INIT* = ptr UDF_INIT # Constants when using compression + PUDF_INIT* = ptr UDF_INIT # Constants when using compression {.deprecated: [Trand_stuct: Rand_struct, TItem_result: Item_result, Tst_udf_args: St_udf_args, TUDF_ARGS: UDF_ARGS, Tst_udf_init: St_udf_init, TUDF_INIT: UDF_INIT].} -const +const NET_HEADER_SIZE* = 4 # standard header size COMP_HEADER_SIZE* = 3 # compression header extra size - # Prototypes to password functions + # Prototypes to password functions # These functions are used for authentication by client and server and - # implemented in sql/password.c + # implemented in sql/password.c -proc randominit*(para1: Prand_struct, seed1: int, seed2: int){.cdecl, +proc randominit*(para1: Prand_struct, seed1: int, seed2: int){.cdecl, dynlib: lib, importc: "randominit".} -proc my_rnd*(para1: Prand_struct): cdouble{.cdecl, dynlib: lib, +proc my_rnd*(para1: Prand_struct): cdouble{.cdecl, dynlib: lib, importc: "my_rnd".} proc create_random_string*(fto: cstring, len: cuint, rand_st: Prand_struct){. cdecl, dynlib: lib, importc: "create_random_string".} -proc hash_password*(fto: int, password: cstring, password_len: cuint){.cdecl, +proc hash_password*(fto: int, password: cstring, password_len: cuint){.cdecl, dynlib: lib, importc: "hash_password".} -proc make_scrambled_password_323*(fto: cstring, password: cstring){.cdecl, +proc make_scrambled_password_323*(fto: cstring, password: cstring){.cdecl, dynlib: lib, importc: "make_scrambled_password_323".} -proc scramble_323*(fto: cstring, message: cstring, password: cstring){.cdecl, +proc scramble_323*(fto: cstring, message: cstring, password: cstring){.cdecl, dynlib: lib, importc: "scramble_323".} proc check_scramble_323*(para1: cstring, message: cstring, salt: int): my_bool{. cdecl, dynlib: lib, importc: "check_scramble_323".} -proc get_salt_from_password_323*(res: ptr int, password: cstring){.cdecl, +proc get_salt_from_password_323*(res: ptr int, password: cstring){.cdecl, dynlib: lib, importc: "get_salt_from_password_323".} -proc make_password_from_salt_323*(fto: cstring, salt: ptr int){.cdecl, +proc make_password_from_salt_323*(fto: cstring, salt: ptr int){.cdecl, dynlib: lib, importc: "make_password_from_salt_323".} -proc octet2hex*(fto: cstring, str: cstring, length: cuint): cstring{.cdecl, +proc octet2hex*(fto: cstring, str: cstring, length: cuint): cstring{.cdecl, dynlib: lib, importc: "octet2hex".} -proc make_scrambled_password*(fto: cstring, password: cstring){.cdecl, +proc make_scrambled_password*(fto: cstring, password: cstring){.cdecl, dynlib: lib, importc: "make_scrambled_password".} -proc scramble*(fto: cstring, message: cstring, password: cstring){.cdecl, +proc scramble*(fto: cstring, message: cstring, password: cstring){.cdecl, dynlib: lib, importc: "scramble".} proc check_scramble*(reply: cstring, message: cstring, hash_stage2: pointer): my_bool{. cdecl, dynlib: lib, importc: "check_scramble".} -proc get_salt_from_password*(res: pointer, password: cstring){.cdecl, +proc get_salt_from_password*(res: pointer, password: cstring){.cdecl, dynlib: lib, importc: "get_salt_from_password".} -proc make_password_from_salt*(fto: cstring, hash_stage2: pointer){.cdecl, +proc make_password_from_salt*(fto: cstring, hash_stage2: pointer){.cdecl, dynlib: lib, importc: "make_password_from_salt".} - # end of password.c -proc get_tty_password*(opt_message: cstring): cstring{.cdecl, dynlib: lib, + # end of password.c +proc get_tty_password*(opt_message: cstring): cstring{.cdecl, dynlib: lib, importc: "get_tty_password".} -proc errno_to_sqlstate*(errno: cuint): cstring{.cdecl, dynlib: lib, +proc errno_to_sqlstate*(errno: cuint): cstring{.cdecl, dynlib: lib, importc: "mysql_errno_to_sqlstate".} - # Some other useful functions -proc modify_defaults_file*(file_location: cstring, option: cstring, - option_value: cstring, section_name: cstring, - remove_option: cint): cint{.cdecl, dynlib: lib, + # Some other useful functions +proc modify_defaults_file*(file_location: cstring, option: cstring, + option_value: cstring, section_name: cstring, + remove_option: cint): cint{.cdecl, dynlib: lib, importc: "load_defaults".} -proc load_defaults*(conf_file: cstring, groups: cstringArray, argc: ptr cint, - argv: ptr cstringArray): cint{.cdecl, dynlib: lib, +proc load_defaults*(conf_file: cstring, groups: cstringArray, argc: ptr cint, + argv: ptr cstringArray): cint{.cdecl, dynlib: lib, importc: "load_defaults".} proc my_init*(): my_bool{.cdecl, dynlib: lib, importc: "my_init".} proc my_thread_init*(): my_bool{.cdecl, dynlib: lib, importc: "my_thread_init".} proc my_thread_end*(){.cdecl, dynlib: lib, importc: "my_thread_end".} -const +const NULL_LENGTH*: int = int(not (0)) # For net_store_length -const +const STMT_HEADER* = 4 - LONG_DATA_HEADER* = 6 # ------------ Stop of declaration in "mysql_com.h" ----------------------- + LONG_DATA_HEADER* = 6 # ------------ Stop of declaration in "mysql_com.h" ----------------------- # $include "mysql_time.h" # $include "mysql_version.h" # $include "typelib.h" @@ -391,13 +391,13 @@ const # mysql_port : cuint;cvar;external; # mysql_unix_port : Pchar;cvar;external; -const +const CLIENT_NET_READ_TIMEOUT* = 365 * 24 * 3600 # Timeout on read CLIENT_NET_WRITE_TIMEOUT* = 365 * 24 * 3600 # Timeout on write -type +type Pst_mysql_field* = ptr St_mysql_field - St_mysql_field*{.final.} = object + St_mysql_field*{.final.} = object name*: cstring # Name of column org_name*: cstring # Original column name, if an alias table*: cstring # Table of column if column was a field @@ -418,7 +418,7 @@ type decimals*: cuint # Number of decimals in field charsetnr*: cuint # Character set ftype*: Enum_field_types # Type of field. See mysql_com.h for types - + FIELD* = St_mysql_field PFIELD* = ptr FIELD PROW* = ptr ROW # return data as array of strings @@ -434,16 +434,16 @@ proc IS_BLOB*(n: int32): bool proc IS_NUM*(t: Enum_field_types): bool proc INTERNAL_NUM_FIELD*(f: Pst_mysql_field): bool proc IS_NUM_FIELD*(f: Pst_mysql_field): bool -type +type my_ulonglong* = int64 Pmy_ulonglong* = ptr my_ulonglong -const +const COUNT_ERROR* = not (my_ulonglong(0)) -type +type Pst_mysql_rows* = ptr St_mysql_rows - St_mysql_rows*{.final.} = object + St_mysql_rows*{.final.} = object next*: Pst_mysql_rows # list of rows data*: ROW len*: int @@ -451,25 +451,25 @@ type ROWS* = St_mysql_rows PROWS* = ptr ROWS PROW_OFFSET* = ptr ROW_OFFSET # offset to current row - ROW_OFFSET* = ROWS + ROW_OFFSET* = ROWS {.deprecated: [Tst_mysql_rows: St_mysql_rows, TROWS: ROWS, TROW_OFFSET: ROW_OFFSET].} - -const - ALLOC_MAX_BLOCK_TO_DROP* = 4096 - ALLOC_MAX_BLOCK_USAGE_BEFORE_DROP* = 10 # struct for once_alloc (block) -type +const + ALLOC_MAX_BLOCK_TO_DROP* = 4096 + ALLOC_MAX_BLOCK_USAGE_BEFORE_DROP* = 10 # struct for once_alloc (block) + +type Pst_used_mem* = ptr St_used_mem - St_used_mem*{.final.} = object + St_used_mem*{.final.} = object next*: Pst_used_mem # Next block in use left*: cuint # memory left in block size*: cuint # size of block - + USED_MEM* = St_used_mem PUSED_MEM* = ptr USED_MEM Pst_mem_root* = ptr St_mem_root - St_mem_root*{.final.} = object + St_mem_root*{.final.} = object free*: PUSED_MEM # blocks with free memory in it used*: PUSED_MEM # blocks almost without free memory pre_alloc*: PUSED_MEM # preallocated block @@ -477,18 +477,18 @@ type block_size*: cuint # initial block size block_num*: cuint # allocated blocks counter # first free block in queue test counter (if it exceed - # MAX_BLOCK_USAGE_BEFORE_DROP block will be dropped in 'used' list) + # MAX_BLOCK_USAGE_BEFORE_DROP block will be dropped in 'used' list) first_block_usage*: cuint error_handler*: proc (){.cdecl.} MEM_ROOT* = St_mem_root - PMEM_ROOT* = ptr MEM_ROOT # ------------ Stop of declaration in "my_alloc.h" ---------------------- + PMEM_ROOT* = ptr MEM_ROOT # ------------ Stop of declaration in "my_alloc.h" ---------------------- {.deprecated: [Tst_used_mem: St_used_mem, TUSED_MEM: USED_MEM, Tst_mem_root: St_mem_root, TMEM_ROOT: MEM_ROOT].} -type +type Pst_mysql_data* = ptr St_mysql_data - St_mysql_data*{.final.} = object + St_mysql_data*{.final.} = object rows*: my_ulonglong fields*: cuint data*: PROWS @@ -497,16 +497,16 @@ type DATA* = St_mysql_data PDATA* = ptr DATA - Option* = enum - OPT_CONNECT_TIMEOUT, OPT_COMPRESS, OPT_NAMED_PIPE, INIT_COMMAND, - READ_DEFAULT_FILE, READ_DEFAULT_GROUP, SET_CHARSET_DIR, SET_CHARSET_NAME, - OPT_LOCAL_INFILE, OPT_PROTOCOL, SHARED_MEMORY_BASE_NAME, OPT_READ_TIMEOUT, - OPT_WRITE_TIMEOUT, OPT_USE_RESULT, OPT_USE_REMOTE_CONNECTION, - OPT_USE_EMBEDDED_CONNECTION, OPT_GUESS_CONNECTION, SET_CLIENT_IP, + Option* = enum + OPT_CONNECT_TIMEOUT, OPT_COMPRESS, OPT_NAMED_PIPE, INIT_COMMAND, + READ_DEFAULT_FILE, READ_DEFAULT_GROUP, SET_CHARSET_DIR, SET_CHARSET_NAME, + OPT_LOCAL_INFILE, OPT_PROTOCOL, SHARED_MEMORY_BASE_NAME, OPT_READ_TIMEOUT, + OPT_WRITE_TIMEOUT, OPT_USE_RESULT, OPT_USE_REMOTE_CONNECTION, + OPT_USE_EMBEDDED_CONNECTION, OPT_GUESS_CONNECTION, SET_CLIENT_IP, SECURE_AUTH, REPORT_DATA_TRUNCATION, OPT_RECONNECT {.deprecated: [Tst_mysql_data: St_mysql_data, TDATA: DATA, Toption: Option].} -const +const MAX_MYSQL_MANAGER_ERR* = 256 MAX_MYSQL_MANAGER_MSG* = 256 MANAGER_OK* = 200 @@ -515,8 +515,8 @@ const MANAGER_CLIENT_ERR* = 450 MANAGER_INTERNAL_ERR* = 500 -type - St_dynamic_array*{.final.} = object +type + St_dynamic_array*{.final.} = object buffer*: cstring elements*: cuint max_element*: cuint @@ -526,7 +526,7 @@ type DYNAMIC_ARRAY* = St_dynamic_array Pst_dynamic_array* = ptr St_dynamic_array Pst_mysql_options* = ptr St_mysql_options - St_mysql_options*{.final.} = object + St_mysql_options*{.final.} = object connect_timeout*: cuint read_timeout*: cuint write_timeout*: cuint @@ -553,18 +553,18 @@ type use_ssl*: my_bool # if to use SSL or not compress*: my_bool named_pipe*: my_bool # On connect, find out the replication role of the server, and - # establish connections to all the peers + # establish connections to all the peers rpl_probe*: my_bool # Each call to mysql_real_query() will parse it to tell if it is a read - # or a write, and direct it to the slave or the master + # or a write, and direct it to the slave or the master rpl_parse*: my_bool # If set, never read from a master, only from slave, when doing - # a read that is replication-aware + # a read that is replication-aware no_master_reads*: my_bool separate_thread*: my_bool methods_to_use*: Option client_ip*: cstring secure_auth*: my_bool # Refuse client connecting to server if it uses old (pre-4.1.1) protocol report_data_truncation*: my_bool # 0 - never report, 1 - always report (default) - # function pointers for local infile support + # function pointers for local infile support local_infile_init*: proc (para1: var pointer, para2: cstring, para3: pointer): cint{. cdecl.} local_infile_read*: proc (para1: pointer, para2: cstring, para3: cuint): cint @@ -572,16 +572,16 @@ type local_infile_error*: proc (para1: pointer, para2: cstring, para3: cuint): cint local_infile_userdata*: pointer - Status* = enum + Status* = enum STATUS_READY, STATUS_GET_RESULT, STATUS_USE_RESULT Protocol_type* = enum # There are three types of queries - the ones that have to go to # the master, the ones that go to a slave, and the administrative - # type which must happen on the pivot connectioin - PROTOCOL_DEFAULT, PROTOCOL_TCP, PROTOCOL_SOCKET, PROTOCOL_PIPE, + # type which must happen on the pivot connectioin + PROTOCOL_DEFAULT, PROTOCOL_TCP, PROTOCOL_SOCKET, PROTOCOL_PIPE, PROTOCOL_MEMORY - Rpl_type* = enum + Rpl_type* = enum RPL_MASTER, RPL_SLAVE, RPL_ADMIN - Charset_info_st*{.final.} = object + Charset_info_st*{.final.} = object number*: cuint primary_number*: cuint binary_number*: cuint @@ -608,11 +608,11 @@ type escape_with_backslash_is_dangerous*: my_bool cset*: pointer # was ^MY_CHARSET_HANDLER coll*: pointer # was ^MY_COLLATION_HANDLER; - + CHARSET_INFO* = Charset_info_st Pcharset_info_st* = ptr Charset_info_st Pcharacter_set* = ptr Character_set - Character_set*{.final.} = object + Character_set*{.final.} = object number*: cuint state*: cuint csname*: cstring @@ -626,7 +626,7 @@ type PMY_CHARSET_INFO* = ptr MY_CHARSET_INFO Pst_mysql_methods* = ptr St_mysql_methods Pst_mysql* = ptr St_mysql - St_mysql*{.final.} = object + St_mysql*{.final.} = object net*: NET # Communication parameters connector_fd*: gptr # ConnectorFd for SSL host*: cstring @@ -659,9 +659,9 @@ type reconnect*: my_bool # set to 1 if automatic reconnect scramble*: array[0..(SCRAMBLE_LENGTH + 1) - 1, char] # session-wide random string # Set if this is the original connection, not a master or a slave we have - # added though mysql_rpl_probe() or mysql_set_master()/ mysql_add_slave() + # added though mysql_rpl_probe() or mysql_set_master()/ mysql_add_slave() rpl_pivot*: my_bool # Pointers to the master, and the next slave connections, points to - # itself if lone connection. + # itself if lone connection. master*: Pst_mysql next_slave*: Pst_mysql last_used_slave*: Pst_mysql # needed for round-robin slave pick @@ -669,13 +669,13 @@ type stmts*: pointer # was PList, list of all statements methods*: Pst_mysql_methods thd*: pointer # Points to boolean flag in MYSQL_RES or MYSQL_STMT. We set this flag - # from mysql_stmt_close if close had to cancel result set of this object. + # from mysql_stmt_close if close had to cancel result set of this object. unbuffered_fetch_owner*: Pmy_bool MySQL* = St_mysql PMySQL* = ptr MySQL Pst_mysql_res* = ptr St_mysql_res - St_mysql_res*{.final.} = object + St_mysql_res*{.final.} = object row_count*: my_ulonglong fields*: PFIELD data*: PDATA @@ -695,10 +695,10 @@ type PRES* = ptr RES Pst_mysql_stmt* = ptr St_mysql_stmt PSTMT* = ptr STMT - St_mysql_methods*{.final.} = object + St_mysql_methods*{.final.} = object read_query_result*: proc (MySQL: PMySQL): my_bool{.cdecl.} - advanced_command*: proc (MySQL: PMySQL, command: Enum_server_command, header: cstring, - header_length: int, arg: cstring, arg_length: int, + advanced_command*: proc (MySQL: PMySQL, command: Enum_server_command, header: cstring, + header_length: int, arg: cstring, arg_length: int, skip_check: my_bool): my_bool read_rows*: proc (MySQL: PMySQL, fields: PFIELD, fields_count: cuint): PDATA use_result*: proc (MySQL: PMySQL): PRES @@ -718,7 +718,7 @@ type METHODS* = St_mysql_methods PMETHODS* = ptr METHODS Pst_mysql_manager* = ptr St_mysql_manager - St_mysql_manager*{.final.} = object + St_mysql_manager*{.final.} = object net*: NET host*: cstring user*: cstring @@ -737,23 +737,23 @@ type MANAGER* = St_mysql_manager PMANAGER* = ptr MANAGER Pst_mysql_parameters* = ptr St_mysql_parameters - St_mysql_parameters*{.final.} = object + St_mysql_parameters*{.final.} = object p_max_allowed_packet*: ptr int p_net_buffer_length*: ptr int PARAMETERS* = St_mysql_parameters PPARAMETERS* = ptr PARAMETERS - Enum_mysql_stmt_state* = enum + Enum_mysql_stmt_state* = enum STMT_INIT_DONE = 1, STMT_PREPARE_DONE, STMT_EXECUTE_DONE, STMT_FETCH_DONE Pst_mysql_bind* = ptr St_mysql_bind - St_mysql_bind*{.final.} = object + St_mysql_bind*{.final.} = object len*: int # output length pointer is_null*: Pmy_bool # Pointer to null indicator buffer*: pointer # buffer to get/put data error*: PMy_bool # set this if you want to track data truncations happened during fetch buffer_type*: Enum_field_types # buffer type buffer_length*: int # buffer length, must be set for str/binary - # Following are for internal use. Set by mysql_stmt_bind_param + # Following are for internal use. Set by mysql_stmt_bind_param row_ptr*: ptr byte # for the current data position offset*: int # offset position for char/binary fetch length_value*: int # Used if length is 0 @@ -768,8 +768,8 @@ type skip_result*: proc (para1: Pst_mysql_bind, para2: PFIELD, row: PPbyte) BIND* = St_mysql_bind - PBIND* = ptr BIND # statement handler - St_mysql_stmt*{.final.} = object + PBIND* = ptr BIND # statement handler + St_mysql_stmt*{.final.} = object mem_root*: MEM_ROOT # root allocations mysql*: PMySQL # connection handle params*: PBIND # input parameters @@ -797,9 +797,9 @@ type unbuffered_fetch_cancelled*: my_bool update_max_length*: my_bool - STMT* = St_mysql_stmt - - Enum_stmt_attr_type* = enum + STMT* = St_mysql_stmt + + Enum_stmt_attr_type* = enum STMT_ATTR_UPDATE_MAX_LENGTH, STMT_ATTR_CURSOR_TYPE, STMT_ATTR_PREFETCH_ROWS {.deprecated: [Tst_dynamic_array: St_dynamic_array, Tst_mysql_options: St_mysql_options, TDYNAMIC_ARRAY: DYNAMIC_ARRAY, Tprotocol_type: Protocol_type, @@ -824,283 +824,283 @@ proc server_end*(){.cdecl, dynlib: lib, importc: "mysql_server_end".} # mysql_server_end() to free memory). The names are a bit misleading # (mysql_SERVER* to be used when using libmysqlCLIENT). So we add more general # names which suit well whether you're using libmysqld or libmysqlclient. We - # intend to promote these aliases over the mysql_server* ones. + # intend to promote these aliases over the mysql_server* ones. proc library_init*(argc: cint, argv: cstringArray, groups: cstringArray): cint{. cdecl, dynlib: lib, importc: "mysql_server_init".} proc library_end*(){.cdecl, dynlib: lib, importc: "mysql_server_end".} -proc get_parameters*(): PPARAMETERS{.stdcall, dynlib: lib, +proc get_parameters*(): PPARAMETERS{.stdcall, dynlib: lib, importc: "mysql_get_parameters".} # Set up and bring down a thread; these function should be called # for each thread in an application which opens at least one MySQL # connection. All uses of the connection(s) should be between these - # function calls. + # function calls. proc thread_init*(): my_bool{.stdcall, dynlib: lib, importc: "mysql_thread_init".} proc thread_end*(){.stdcall, dynlib: lib, importc: "mysql_thread_end".} # Functions to get information from the MYSQL and MYSQL_RES structures - # Should definitely be used if one uses shared libraries. -proc num_rows*(res: PRES): my_ulonglong{.stdcall, dynlib: lib, + # Should definitely be used if one uses shared libraries. +proc num_rows*(res: PRES): my_ulonglong{.stdcall, dynlib: lib, importc: "mysql_num_rows".} -proc num_fields*(res: PRES): cuint{.stdcall, dynlib: lib, +proc num_fields*(res: PRES): cuint{.stdcall, dynlib: lib, importc: "mysql_num_fields".} proc eof*(res: PRES): my_bool{.stdcall, dynlib: lib, importc: "mysql_eof".} -proc fetch_field_direct*(res: PRES, fieldnr: cuint): PFIELD{.stdcall, +proc fetch_field_direct*(res: PRES, fieldnr: cuint): PFIELD{.stdcall, dynlib: lib, importc: "mysql_fetch_field_direct".} -proc fetch_fields*(res: PRES): PFIELD{.stdcall, dynlib: lib, +proc fetch_fields*(res: PRES): PFIELD{.stdcall, dynlib: lib, importc: "mysql_fetch_fields".} -proc row_tell*(res: PRES): ROW_OFFSET{.stdcall, dynlib: lib, +proc row_tell*(res: PRES): ROW_OFFSET{.stdcall, dynlib: lib, importc: "mysql_row_tell".} -proc field_tell*(res: PRES): FIELD_OFFSET{.stdcall, dynlib: lib, +proc field_tell*(res: PRES): FIELD_OFFSET{.stdcall, dynlib: lib, importc: "mysql_field_tell".} -proc field_count*(MySQL: PMySQL): cuint{.stdcall, dynlib: lib, +proc field_count*(MySQL: PMySQL): cuint{.stdcall, dynlib: lib, importc: "mysql_field_count".} -proc affected_rows*(MySQL: PMySQL): my_ulonglong{.stdcall, dynlib: lib, +proc affected_rows*(MySQL: PMySQL): my_ulonglong{.stdcall, dynlib: lib, importc: "mysql_affected_rows".} -proc insert_id*(MySQL: PMySQL): my_ulonglong{.stdcall, dynlib: lib, +proc insert_id*(MySQL: PMySQL): my_ulonglong{.stdcall, dynlib: lib, importc: "mysql_insert_id".} proc errno*(MySQL: PMySQL): cuint{.stdcall, dynlib: lib, importc: "mysql_errno".} proc error*(MySQL: PMySQL): cstring{.stdcall, dynlib: lib, importc: "mysql_error".} proc sqlstate*(MySQL: PMySQL): cstring{.stdcall, dynlib: lib, importc: "mysql_sqlstate".} -proc warning_count*(MySQL: PMySQL): cuint{.stdcall, dynlib: lib, +proc warning_count*(MySQL: PMySQL): cuint{.stdcall, dynlib: lib, importc: "mysql_warning_count".} proc info*(MySQL: PMySQL): cstring{.stdcall, dynlib: lib, importc: "mysql_info".} proc thread_id*(MySQL: PMySQL): int{.stdcall, dynlib: lib, importc: "mysql_thread_id".} -proc character_set_name*(MySQL: PMySQL): cstring{.stdcall, dynlib: lib, +proc character_set_name*(MySQL: PMySQL): cstring{.stdcall, dynlib: lib, importc: "mysql_character_set_name".} -proc set_character_set*(MySQL: PMySQL, csname: cstring): int32{.stdcall, dynlib: lib, +proc set_character_set*(MySQL: PMySQL, csname: cstring): int32{.stdcall, dynlib: lib, importc: "mysql_set_character_set".} proc init*(MySQL: PMySQL): PMySQL{.stdcall, dynlib: lib, importc: "mysql_init".} -proc ssl_set*(MySQL: PMySQL, key: cstring, cert: cstring, ca: cstring, capath: cstring, - cipher: cstring): my_bool{.stdcall, dynlib: lib, +proc ssl_set*(MySQL: PMySQL, key: cstring, cert: cstring, ca: cstring, capath: cstring, + cipher: cstring): my_bool{.stdcall, dynlib: lib, importc: "mysql_ssl_set".} proc change_user*(MySQL: PMySQL, user: cstring, passwd: cstring, db: cstring): my_bool{. stdcall, dynlib: lib, importc: "mysql_change_user".} -proc real_connect*(MySQL: PMySQL, host: cstring, user: cstring, passwd: cstring, - db: cstring, port: cuint, unix_socket: cstring, - clientflag: int): PMySQL{.stdcall, dynlib: lib, +proc real_connect*(MySQL: PMySQL, host: cstring, user: cstring, passwd: cstring, + db: cstring, port: cuint, unix_socket: cstring, + clientflag: int): PMySQL{.stdcall, dynlib: lib, importc: "mysql_real_connect".} -proc select_db*(MySQL: PMySQL, db: cstring): cint{.stdcall, dynlib: lib, +proc select_db*(MySQL: PMySQL, db: cstring): cint{.stdcall, dynlib: lib, importc: "mysql_select_db".} proc query*(MySQL: PMySQL, q: cstring): cint{.stdcall, dynlib: lib, importc: "mysql_query".} -proc send_query*(MySQL: PMySQL, q: cstring, len: int): cint{.stdcall, dynlib: lib, +proc send_query*(MySQL: PMySQL, q: cstring, len: int): cint{.stdcall, dynlib: lib, importc: "mysql_send_query".} -proc real_query*(MySQL: PMySQL, q: cstring, len: int): cint{.stdcall, dynlib: lib, +proc real_query*(MySQL: PMySQL, q: cstring, len: int): cint{.stdcall, dynlib: lib, importc: "mysql_real_query".} -proc store_result*(MySQL: PMySQL): PRES{.stdcall, dynlib: lib, +proc store_result*(MySQL: PMySQL): PRES{.stdcall, dynlib: lib, importc: "mysql_store_result".} proc use_result*(MySQL: PMySQL): PRES{.stdcall, dynlib: lib, importc: "mysql_use_result".} - # perform query on master -proc master_query*(MySQL: PMySQL, q: cstring, len: int): my_bool{.stdcall, dynlib: lib, + # perform query on master +proc master_query*(MySQL: PMySQL, q: cstring, len: int): my_bool{.stdcall, dynlib: lib, importc: "mysql_master_query".} -proc master_send_query*(MySQL: PMySQL, q: cstring, len: int): my_bool{.stdcall, +proc master_send_query*(MySQL: PMySQL, q: cstring, len: int): my_bool{.stdcall, dynlib: lib, importc: "mysql_master_send_query".} - # perform query on slave -proc slave_query*(MySQL: PMySQL, q: cstring, len: int): my_bool{.stdcall, dynlib: lib, + # perform query on slave +proc slave_query*(MySQL: PMySQL, q: cstring, len: int): my_bool{.stdcall, dynlib: lib, importc: "mysql_slave_query".} -proc slave_send_query*(MySQL: PMySQL, q: cstring, len: int): my_bool{.stdcall, +proc slave_send_query*(MySQL: PMySQL, q: cstring, len: int): my_bool{.stdcall, dynlib: lib, importc: "mysql_slave_send_query".} -proc get_character_set_info*(MySQL: PMySQL, charset: PMY_CHARSET_INFO){.stdcall, +proc get_character_set_info*(MySQL: PMySQL, charset: PMY_CHARSET_INFO){.stdcall, dynlib: lib, importc: "mysql_get_character_set_info".} - # local infile support -const + # local infile support +const LOCAL_INFILE_ERROR_LEN* = 512 # procedure mysql_set_local_infile_handler(mysql:PMYSQL; local_infile_init:function (para1:Ppointer; para2:Pchar; para3:pointer):longint; local_infile_read:function (para1:pointer; para2:Pchar; para3:dword):longint; local_infile_end:procedure (_pa # para6:pointer);cdecl;external mysqllib name 'mysql_set_local_infile_handler'; -proc set_local_infile_default*(MySQL: PMySQL){.cdecl, dynlib: lib, +proc set_local_infile_default*(MySQL: PMySQL){.cdecl, dynlib: lib, importc: "mysql_set_local_infile_default".} # enable/disable parsing of all queries to decide if they go on master or - # slave -proc enable_rpl_parse*(MySQL: PMySQL){.stdcall, dynlib: lib, + # slave +proc enable_rpl_parse*(MySQL: PMySQL){.stdcall, dynlib: lib, importc: "mysql_enable_rpl_parse".} -proc disable_rpl_parse*(MySQL: PMySQL){.stdcall, dynlib: lib, +proc disable_rpl_parse*(MySQL: PMySQL){.stdcall, dynlib: lib, importc: "mysql_disable_rpl_parse".} - # get the value of the parse flag -proc rpl_parse_enabled*(MySQL: PMySQL): cint{.stdcall, dynlib: lib, + # get the value of the parse flag +proc rpl_parse_enabled*(MySQL: PMySQL): cint{.stdcall, dynlib: lib, importc: "mysql_rpl_parse_enabled".} - # enable/disable reads from master -proc enable_reads_from_master*(MySQL: PMySQL){.stdcall, dynlib: lib, + # enable/disable reads from master +proc enable_reads_from_master*(MySQL: PMySQL){.stdcall, dynlib: lib, importc: "mysql_enable_reads_from_master".} proc disable_reads_from_master*(MySQL: PMySQL){.stdcall, dynlib: lib, importc: "mysql_disable_reads_from_master".} - # get the value of the master read flag -proc reads_from_master_enabled*(MySQL: PMySQL): my_bool{.stdcall, dynlib: lib, + # get the value of the master read flag +proc reads_from_master_enabled*(MySQL: PMySQL): my_bool{.stdcall, dynlib: lib, importc: "mysql_reads_from_master_enabled".} -proc rpl_query_type*(q: cstring, length: cint): Rpl_type{.stdcall, dynlib: lib, +proc rpl_query_type*(q: cstring, length: cint): Rpl_type{.stdcall, dynlib: lib, importc: "mysql_rpl_query_type".} - # discover the master and its slaves + # discover the master and its slaves proc rpl_probe*(MySQL: PMySQL): my_bool{.stdcall, dynlib: lib, importc: "mysql_rpl_probe".} - # set the master, close/free the old one, if it is not a pivot + # set the master, close/free the old one, if it is not a pivot proc set_master*(MySQL: PMySQL, host: cstring, port: cuint, user: cstring, passwd: cstring): cint{. stdcall, dynlib: lib, importc: "mysql_set_master".} proc add_slave*(MySQL: PMySQL, host: cstring, port: cuint, user: cstring, passwd: cstring): cint{. stdcall, dynlib: lib, importc: "mysql_add_slave".} -proc shutdown*(MySQL: PMySQL, shutdown_level: Enum_shutdown_level): cint{.stdcall, +proc shutdown*(MySQL: PMySQL, shutdown_level: Enum_shutdown_level): cint{.stdcall, dynlib: lib, importc: "mysql_shutdown".} -proc dump_debug_info*(MySQL: PMySQL): cint{.stdcall, dynlib: lib, +proc dump_debug_info*(MySQL: PMySQL): cint{.stdcall, dynlib: lib, importc: "mysql_dump_debug_info".} -proc refresh*(sql: PMySQL, refresh_options: cuint): cint{.stdcall, dynlib: lib, +proc refresh*(sql: PMySQL, refresh_options: cuint): cint{.stdcall, dynlib: lib, importc: "mysql_refresh".} proc kill*(MySQL: PMySQL, pid: int): cint{.stdcall, dynlib: lib, importc: "mysql_kill".} -proc set_server_option*(MySQL: PMySQL, option: Enum_mysql_set_option): cint{.stdcall, +proc set_server_option*(MySQL: PMySQL, option: Enum_mysql_set_option): cint{.stdcall, dynlib: lib, importc: "mysql_set_server_option".} proc ping*(MySQL: PMySQL): cint{.stdcall, dynlib: lib, importc: "mysql_ping".} proc stat*(MySQL: PMySQL): cstring{.stdcall, dynlib: lib, importc: "mysql_stat".} -proc get_server_info*(MySQL: PMySQL): cstring{.stdcall, dynlib: lib, +proc get_server_info*(MySQL: PMySQL): cstring{.stdcall, dynlib: lib, importc: "mysql_get_server_info".} -proc get_client_info*(): cstring{.stdcall, dynlib: lib, +proc get_client_info*(): cstring{.stdcall, dynlib: lib, importc: "mysql_get_client_info".} -proc get_client_version*(): int{.stdcall, dynlib: lib, +proc get_client_version*(): int{.stdcall, dynlib: lib, importc: "mysql_get_client_version".} -proc get_host_info*(MySQL: PMySQL): cstring{.stdcall, dynlib: lib, +proc get_host_info*(MySQL: PMySQL): cstring{.stdcall, dynlib: lib, importc: "mysql_get_host_info".} -proc get_server_version*(MySQL: PMySQL): int{.stdcall, dynlib: lib, +proc get_server_version*(MySQL: PMySQL): int{.stdcall, dynlib: lib, importc: "mysql_get_server_version".} -proc get_proto_info*(MySQL: PMySQL): cuint{.stdcall, dynlib: lib, +proc get_proto_info*(MySQL: PMySQL): cuint{.stdcall, dynlib: lib, importc: "mysql_get_proto_info".} -proc list_dbs*(MySQL: PMySQL, wild: cstring): PRES{.stdcall, dynlib: lib, +proc list_dbs*(MySQL: PMySQL, wild: cstring): PRES{.stdcall, dynlib: lib, importc: "mysql_list_dbs".} -proc list_tables*(MySQL: PMySQL, wild: cstring): PRES{.stdcall, dynlib: lib, +proc list_tables*(MySQL: PMySQL, wild: cstring): PRES{.stdcall, dynlib: lib, importc: "mysql_list_tables".} -proc list_processes*(MySQL: PMySQL): PRES{.stdcall, dynlib: lib, +proc list_processes*(MySQL: PMySQL): PRES{.stdcall, dynlib: lib, importc: "mysql_list_processes".} -proc options*(MySQL: PMySQL, option: Option, arg: cstring): cint{.stdcall, dynlib: lib, +proc options*(MySQL: PMySQL, option: Option, arg: cstring): cint{.stdcall, dynlib: lib, importc: "mysql_options".} -proc free_result*(result: PRES){.stdcall, dynlib: lib, +proc free_result*(result: PRES){.stdcall, dynlib: lib, importc: "mysql_free_result".} -proc data_seek*(result: PRES, offset: my_ulonglong){.stdcall, dynlib: lib, +proc data_seek*(result: PRES, offset: my_ulonglong){.stdcall, dynlib: lib, importc: "mysql_data_seek".} -proc row_seek*(result: PRES, offset: ROW_OFFSET): ROW_OFFSET{.stdcall, +proc row_seek*(result: PRES, offset: ROW_OFFSET): ROW_OFFSET{.stdcall, dynlib: lib, importc: "mysql_row_seek".} -proc field_seek*(result: PRES, offset: FIELD_OFFSET): FIELD_OFFSET{.stdcall, +proc field_seek*(result: PRES, offset: FIELD_OFFSET): FIELD_OFFSET{.stdcall, dynlib: lib, importc: "mysql_field_seek".} -proc fetch_row*(result: PRES): ROW{.stdcall, dynlib: lib, +proc fetch_row*(result: PRES): ROW{.stdcall, dynlib: lib, importc: "mysql_fetch_row".} -proc fetch_lengths*(result: PRES): ptr int{.stdcall, dynlib: lib, +proc fetch_lengths*(result: PRES): ptr int{.stdcall, dynlib: lib, importc: "mysql_fetch_lengths".} -proc fetch_field*(result: PRES): PFIELD{.stdcall, dynlib: lib, +proc fetch_field*(result: PRES): PFIELD{.stdcall, dynlib: lib, importc: "mysql_fetch_field".} -proc list_fields*(MySQL: PMySQL, table: cstring, wild: cstring): PRES{.stdcall, +proc list_fields*(MySQL: PMySQL, table: cstring, wild: cstring): PRES{.stdcall, dynlib: lib, importc: "mysql_list_fields".} proc escape_string*(fto: cstring, `from`: cstring, from_length: int): int{. stdcall, dynlib: lib, importc: "mysql_escape_string".} -proc hex_string*(fto: cstring, `from`: cstring, from_length: int): int{.stdcall, +proc hex_string*(fto: cstring, `from`: cstring, from_length: int): int{.stdcall, dynlib: lib, importc: "mysql_hex_string".} proc real_escape_string*(MySQL: PMySQL, fto: cstring, `from`: cstring, len: int): int{. stdcall, dynlib: lib, importc: "mysql_real_escape_string".} proc debug*(debug: cstring){.stdcall, dynlib: lib, importc: "mysql_debug".} # function mysql_odbc_escape_string(mysql:PMYSQL; fto:Pchar; to_length:dword; from:Pchar; from_length:dword; # param:pointer; extend_buffer:function (para1:pointer; to:Pchar; length:Pdword):Pchar):Pchar;stdcall;external mysqllib name 'mysql_odbc_escape_string'; -proc myodbc_remove_escape*(MySQL: PMySQL, name: cstring){.stdcall, dynlib: lib, +proc myodbc_remove_escape*(MySQL: PMySQL, name: cstring){.stdcall, dynlib: lib, importc: "myodbc_remove_escape".} proc thread_safe*(): cuint{.stdcall, dynlib: lib, importc: "mysql_thread_safe".} proc embedded*(): my_bool{.stdcall, dynlib: lib, importc: "mysql_embedded".} -proc manager_init*(con: PMANAGER): PMANAGER{.stdcall, dynlib: lib, +proc manager_init*(con: PMANAGER): PMANAGER{.stdcall, dynlib: lib, importc: "mysql_manager_init".} -proc manager_connect*(con: PMANAGER, host: cstring, user: cstring, - passwd: cstring, port: cuint): PMANAGER{.stdcall, +proc manager_connect*(con: PMANAGER, host: cstring, user: cstring, + passwd: cstring, port: cuint): PMANAGER{.stdcall, dynlib: lib, importc: "mysql_manager_connect".} -proc manager_close*(con: PMANAGER){.stdcall, dynlib: lib, +proc manager_close*(con: PMANAGER){.stdcall, dynlib: lib, importc: "mysql_manager_close".} proc manager_command*(con: PMANAGER, cmd: cstring, cmd_len: cint): cint{. stdcall, dynlib: lib, importc: "mysql_manager_command".} proc manager_fetch_line*(con: PMANAGER, res_buf: cstring, res_buf_size: cint): cint{. stdcall, dynlib: lib, importc: "mysql_manager_fetch_line".} -proc read_query_result*(MySQL: PMySQL): my_bool{.stdcall, dynlib: lib, +proc read_query_result*(MySQL: PMySQL): my_bool{.stdcall, dynlib: lib, importc: "mysql_read_query_result".} proc stmt_init*(MySQL: PMySQL): PSTMT{.stdcall, dynlib: lib, importc: "mysql_stmt_init".} -proc stmt_prepare*(stmt: PSTMT, query: cstring, len: int): cint{.stdcall, +proc stmt_prepare*(stmt: PSTMT, query: cstring, len: int): cint{.stdcall, dynlib: lib, importc: "mysql_stmt_prepare".} -proc stmt_execute*(stmt: PSTMT): cint{.stdcall, dynlib: lib, +proc stmt_execute*(stmt: PSTMT): cint{.stdcall, dynlib: lib, importc: "mysql_stmt_execute".} -proc stmt_fetch*(stmt: PSTMT): cint{.stdcall, dynlib: lib, +proc stmt_fetch*(stmt: PSTMT): cint{.stdcall, dynlib: lib, importc: "mysql_stmt_fetch".} proc stmt_fetch_column*(stmt: PSTMT, `bind`: PBIND, column: cuint, offset: int): cint{. stdcall, dynlib: lib, importc: "mysql_stmt_fetch_column".} -proc stmt_store_result*(stmt: PSTMT): cint{.stdcall, dynlib: lib, +proc stmt_store_result*(stmt: PSTMT): cint{.stdcall, dynlib: lib, importc: "mysql_stmt_store_result".} -proc stmt_param_count*(stmt: PSTMT): int{.stdcall, dynlib: lib, +proc stmt_param_count*(stmt: PSTMT): int{.stdcall, dynlib: lib, importc: "mysql_stmt_param_count".} proc stmt_attr_set*(stmt: PSTMT, attr_type: Enum_stmt_attr_type, attr: pointer): my_bool{. stdcall, dynlib: lib, importc: "mysql_stmt_attr_set".} proc stmt_attr_get*(stmt: PSTMT, attr_type: Enum_stmt_attr_type, attr: pointer): my_bool{. stdcall, dynlib: lib, importc: "mysql_stmt_attr_get".} -proc stmt_bind_param*(stmt: PSTMT, bnd: PBIND): my_bool{.stdcall, dynlib: lib, +proc stmt_bind_param*(stmt: PSTMT, bnd: PBIND): my_bool{.stdcall, dynlib: lib, importc: "mysql_stmt_bind_param".} -proc stmt_bind_result*(stmt: PSTMT, bnd: PBIND): my_bool{.stdcall, dynlib: lib, +proc stmt_bind_result*(stmt: PSTMT, bnd: PBIND): my_bool{.stdcall, dynlib: lib, importc: "mysql_stmt_bind_result".} -proc stmt_close*(stmt: PSTMT): my_bool{.stdcall, dynlib: lib, +proc stmt_close*(stmt: PSTMT): my_bool{.stdcall, dynlib: lib, importc: "mysql_stmt_close".} -proc stmt_reset*(stmt: PSTMT): my_bool{.stdcall, dynlib: lib, +proc stmt_reset*(stmt: PSTMT): my_bool{.stdcall, dynlib: lib, importc: "mysql_stmt_reset".} -proc stmt_free_result*(stmt: PSTMT): my_bool{.stdcall, dynlib: lib, +proc stmt_free_result*(stmt: PSTMT): my_bool{.stdcall, dynlib: lib, importc: "mysql_stmt_free_result".} -proc stmt_send_long_data*(stmt: PSTMT, param_number: cuint, data: cstring, - len: int): my_bool{.stdcall, dynlib: lib, +proc stmt_send_long_data*(stmt: PSTMT, param_number: cuint, data: cstring, + len: int): my_bool{.stdcall, dynlib: lib, importc: "mysql_stmt_send_long_data".} -proc stmt_result_metadata*(stmt: PSTMT): PRES{.stdcall, dynlib: lib, +proc stmt_result_metadata*(stmt: PSTMT): PRES{.stdcall, dynlib: lib, importc: "mysql_stmt_result_metadata".} -proc stmt_param_metadata*(stmt: PSTMT): PRES{.stdcall, dynlib: lib, +proc stmt_param_metadata*(stmt: PSTMT): PRES{.stdcall, dynlib: lib, importc: "mysql_stmt_param_metadata".} -proc stmt_errno*(stmt: PSTMT): cuint{.stdcall, dynlib: lib, +proc stmt_errno*(stmt: PSTMT): cuint{.stdcall, dynlib: lib, importc: "mysql_stmt_errno".} -proc stmt_error*(stmt: PSTMT): cstring{.stdcall, dynlib: lib, +proc stmt_error*(stmt: PSTMT): cstring{.stdcall, dynlib: lib, importc: "mysql_stmt_error".} -proc stmt_sqlstate*(stmt: PSTMT): cstring{.stdcall, dynlib: lib, +proc stmt_sqlstate*(stmt: PSTMT): cstring{.stdcall, dynlib: lib, importc: "mysql_stmt_sqlstate".} -proc stmt_row_seek*(stmt: PSTMT, offset: ROW_OFFSET): ROW_OFFSET{.stdcall, +proc stmt_row_seek*(stmt: PSTMT, offset: ROW_OFFSET): ROW_OFFSET{.stdcall, dynlib: lib, importc: "mysql_stmt_row_seek".} -proc stmt_row_tell*(stmt: PSTMT): ROW_OFFSET{.stdcall, dynlib: lib, +proc stmt_row_tell*(stmt: PSTMT): ROW_OFFSET{.stdcall, dynlib: lib, importc: "mysql_stmt_row_tell".} -proc stmt_data_seek*(stmt: PSTMT, offset: my_ulonglong){.stdcall, dynlib: lib, +proc stmt_data_seek*(stmt: PSTMT, offset: my_ulonglong){.stdcall, dynlib: lib, importc: "mysql_stmt_data_seek".} -proc stmt_num_rows*(stmt: PSTMT): my_ulonglong{.stdcall, dynlib: lib, +proc stmt_num_rows*(stmt: PSTMT): my_ulonglong{.stdcall, dynlib: lib, importc: "mysql_stmt_num_rows".} -proc stmt_affected_rows*(stmt: PSTMT): my_ulonglong{.stdcall, dynlib: lib, +proc stmt_affected_rows*(stmt: PSTMT): my_ulonglong{.stdcall, dynlib: lib, importc: "mysql_stmt_affected_rows".} -proc stmt_insert_id*(stmt: PSTMT): my_ulonglong{.stdcall, dynlib: lib, +proc stmt_insert_id*(stmt: PSTMT): my_ulonglong{.stdcall, dynlib: lib, importc: "mysql_stmt_insert_id".} -proc stmt_field_count*(stmt: PSTMT): cuint{.stdcall, dynlib: lib, +proc stmt_field_count*(stmt: PSTMT): cuint{.stdcall, dynlib: lib, importc: "mysql_stmt_field_count".} proc commit*(MySQL: PMySQL): my_bool{.stdcall, dynlib: lib, importc: "mysql_commit".} proc rollback*(MySQL: PMySQL): my_bool{.stdcall, dynlib: lib, importc: "mysql_rollback".} -proc autocommit*(MySQL: PMySQL, auto_mode: my_bool): my_bool{.stdcall, dynlib: lib, +proc autocommit*(MySQL: PMySQL, auto_mode: my_bool): my_bool{.stdcall, dynlib: lib, importc: "mysql_autocommit".} -proc more_results*(MySQL: PMySQL): my_bool{.stdcall, dynlib: lib, +proc more_results*(MySQL: PMySQL): my_bool{.stdcall, dynlib: lib, importc: "mysql_more_results".} proc next_result*(MySQL: PMySQL): cint{.stdcall, dynlib: lib, importc: "mysql_next_result".} proc close*(sock: PMySQL){.stdcall, dynlib: lib, importc: "mysql_close".} - # status return codes -const + # status return codes +const NO_DATA* = 100 DATA_TRUNCATED* = 101 proc reload*(x: PMySQL): cint -when defined(USE_OLD_FUNCTIONS): - proc connect*(MySQL: PMySQL, host: cstring, user: cstring, passwd: cstring): PMySQL{.stdcall, +when defined(USE_OLD_FUNCTIONS): + proc connect*(MySQL: PMySQL, host: cstring, user: cstring, passwd: cstring): PMySQL{.stdcall, dynlib: lib, importc: "mysql_connect".} - proc create_db*(MySQL: PMySQL, DB: cstring): cint{.stdcall, dynlib: lib, + proc create_db*(MySQL: PMySQL, DB: cstring): cint{.stdcall, dynlib: lib, importc: "mysql_create_db".} - proc drop_db*(MySQL: PMySQL, DB: cstring): cint{.stdcall, dynlib: lib, + proc drop_db*(MySQL: PMySQL, DB: cstring): cint{.stdcall, dynlib: lib, importc: "mysql_drop_db".} proc net_safe_read*(MySQL: PMySQL): cuint{.cdecl, dynlib: lib, importc: "net_safe_read".} -proc IS_PRI_KEY(n: int32): bool = +proc IS_PRI_KEY(n: int32): bool = result = (n and PRI_KEY_FLAG) != 0 -proc IS_NOT_NULL(n: int32): bool = +proc IS_NOT_NULL(n: int32): bool = result = (n and NOT_NULL_FLAG) != 0 -proc IS_BLOB(n: int32): bool = +proc IS_BLOB(n: int32): bool = result = (n and BLOB_FLAG) != 0 -proc IS_NUM_FIELD(f: Pst_mysql_field): bool = +proc IS_NUM_FIELD(f: Pst_mysql_field): bool = result = (f.flags and NUM_FLAG) != 0 -proc IS_NUM(t: Enum_field_types): bool = +proc IS_NUM(t: Enum_field_types): bool = result = (t <= FIELD_TYPE_INT24) or (t == FIELD_TYPE_YEAR) or (t == FIELD_TYPE_NEWDECIMAL) -proc INTERNAL_NUM_FIELD(f: Pst_mysql_field): bool = +proc INTERNAL_NUM_FIELD(f: Pst_mysql_field): bool = result = (f.ftype <= FIELD_TYPE_INT24) and ((f.ftype != FIELD_TYPE_TIMESTAMP) or (f.len == 14) or (f.len == 8)) or (f.ftype == FIELD_TYPE_YEAR) diff --git a/lib/wrappers/sqlite3.nim b/lib/wrappers/sqlite3.nim index bd107b0bc..24c271ab7 100644 --- a/lib/wrappers/sqlite3.nim +++ b/lib/wrappers/sqlite3.nim @@ -8,17 +8,17 @@ # {.deadCodeElim: on.} -when defined(windows): - const +when defined(windows): + const Lib = "sqlite3.dll" -elif defined(macosx): - const +elif defined(macosx): + const Lib = "libsqlite3(|.0).dylib" -else: - const +else: + const Lib = "libsqlite3.so(|.0)" - -const + +const SQLITE_INTEGER* = 1 SQLITE_FLOAT* = 2 SQLITE_BLOB* = 4 @@ -26,38 +26,38 @@ const SQLITE_TEXT* = 3 SQLITE_UTF8* = 1 SQLITE_UTF16LE* = 2 - SQLITE_UTF16BE* = 3 # Use native byte order - SQLITE_UTF16* = 4 # sqlite3_create_function only + SQLITE_UTF16BE* = 3 # Use native byte order + SQLITE_UTF16* = 4 # sqlite3_create_function only SQLITE_ANY* = 5 #sqlite_exec return values SQLITE_OK* = 0 - SQLITE_ERROR* = 1 # SQL error or missing database - SQLITE_INTERNAL* = 2 # An internal logic error in SQLite - SQLITE_PERM* = 3 # Access permission denied - SQLITE_ABORT* = 4 # Callback routine requested an abort - SQLITE_BUSY* = 5 # The database file is locked - SQLITE_LOCKED* = 6 # A table in the database is locked - SQLITE_NOMEM* = 7 # A malloc() failed - SQLITE_READONLY* = 8 # Attempt to write a readonly database - SQLITE_INTERRUPT* = 9 # Operation terminated by sqlite3_interrupt() - SQLITE_IOERR* = 10 # Some kind of disk I/O error occurred - SQLITE_CORRUPT* = 11 # The database disk image is malformed - SQLITE_NOTFOUND* = 12 # (Internal Only) Table or record not found - SQLITE_FULL* = 13 # Insertion failed because database is full - SQLITE_CANTOPEN* = 14 # Unable to open the database file - SQLITE_PROTOCOL* = 15 # Database lock protocol error - SQLITE_EMPTY* = 16 # Database is empty - SQLITE_SCHEMA* = 17 # The database schema changed - SQLITE_TOOBIG* = 18 # Too much data for one row of a table - SQLITE_CONSTRAINT* = 19 # Abort due to contraint violation - SQLITE_MISMATCH* = 20 # Data type mismatch - SQLITE_MISUSE* = 21 # Library used incorrectly - SQLITE_NOLFS* = 22 # Uses OS features not supported on host - SQLITE_AUTH* = 23 # Authorization denied - SQLITE_FORMAT* = 24 # Auxiliary database format error - SQLITE_RANGE* = 25 # 2nd parameter to sqlite3_bind out of range - SQLITE_NOTADB* = 26 # File opened that is not a database file - SQLITE_ROW* = 100 # sqlite3_step() has another row ready - SQLITE_DONE* = 101 # sqlite3_step() has finished executing + SQLITE_ERROR* = 1 # SQL error or missing database + SQLITE_INTERNAL* = 2 # An internal logic error in SQLite + SQLITE_PERM* = 3 # Access permission denied + SQLITE_ABORT* = 4 # Callback routine requested an abort + SQLITE_BUSY* = 5 # The database file is locked + SQLITE_LOCKED* = 6 # A table in the database is locked + SQLITE_NOMEM* = 7 # A malloc() failed + SQLITE_READONLY* = 8 # Attempt to write a readonly database + SQLITE_INTERRUPT* = 9 # Operation terminated by sqlite3_interrupt() + SQLITE_IOERR* = 10 # Some kind of disk I/O error occurred + SQLITE_CORRUPT* = 11 # The database disk image is malformed + SQLITE_NOTFOUND* = 12 # (Internal Only) Table or record not found + SQLITE_FULL* = 13 # Insertion failed because database is full + SQLITE_CANTOPEN* = 14 # Unable to open the database file + SQLITE_PROTOCOL* = 15 # Database lock protocol error + SQLITE_EMPTY* = 16 # Database is empty + SQLITE_SCHEMA* = 17 # The database schema changed + SQLITE_TOOBIG* = 18 # Too much data for one row of a table + SQLITE_CONSTRAINT* = 19 # Abort due to contraint violation + SQLITE_MISMATCH* = 20 # Data type mismatch + SQLITE_MISUSE* = 21 # Library used incorrectly + SQLITE_NOLFS* = 22 # Uses OS features not supported on host + SQLITE_AUTH* = 23 # Authorization denied + SQLITE_FORMAT* = 24 # Auxiliary database format error + SQLITE_RANGE* = 25 # 2nd parameter to sqlite3_bind out of range + SQLITE_NOTADB* = 26 # File opened that is not a database file + SQLITE_ROW* = 100 # sqlite3_step() has another row ready + SQLITE_DONE* = 101 # sqlite3_step() has finished executing SQLITE_COPY* = 0 SQLITE_CREATE_INDEX* = 1 SQLITE_CREATE_TABLE* = 2 @@ -87,39 +87,39 @@ const SQLITE_ALTER_TABLE* = 26 SQLITE_REINDEX* = 27 SQLITE_DENY* = 1 - SQLITE_IGNORE* = 2 # Original from sqlite3.h: + SQLITE_IGNORE* = 2 # Original from sqlite3.h: #define SQLITE_STATIC ((void(*)(void *))0) #define SQLITE_TRANSIENT ((void(*)(void *))-1) SQLITE_DETERMINISTIC* = 0x800 -const +const SQLITE_STATIC* = nil SQLITE_TRANSIENT* = cast[pointer](- 1) -type - Sqlite3 {.pure, final.} = object +type + Sqlite3 {.pure, final.} = object PSqlite3* = ptr Sqlite3 PPSqlite3* = ptr PSqlite3 - Context{.pure, final.} = object + Context{.pure, final.} = object Pcontext* = ptr Context - Tstmt{.pure, final.} = object + Tstmt{.pure, final.} = object Pstmt* = ptr Tstmt - Value{.pure, final.} = object + Value{.pure, final.} = object Pvalue* = ptr Value PValueArg* = array[0..127, Pvalue] - - Callback* = proc (para1: pointer, para2: int32, para3, + + Callback* = proc (para1: pointer, para2: int32, para3, para4: cstringArray): int32{.cdecl.} Tbind_destructor_func* = proc (para1: pointer){.cdecl.} - Create_function_step_func* = proc (para1: Pcontext, para2: int32, + Create_function_step_func* = proc (para1: Pcontext, para2: int32, para3: PValueArg){.cdecl.} - Create_function_func_func* = proc (para1: Pcontext, para2: int32, + Create_function_func_func* = proc (para1: Pcontext, para2: int32, para3: PValueArg){.cdecl.} Create_function_final_func* = proc (para1: Pcontext){.cdecl.} Result_func* = proc (para1: pointer){.cdecl.} - Create_collation_func* = proc (para1: pointer, para2: int32, para3: pointer, + Create_collation_func* = proc (para1: pointer, para2: int32, para3: pointer, para4: int32, para5: pointer): int32{.cdecl.} - Collation_needed_func* = proc (para1: pointer, para2: PSqlite3, eTextRep: int32, + Collation_needed_func* = proc (para1: pointer, para2: PSqlite3, eTextRep: int32, para4: cstring){.cdecl.} {.deprecated: [TSqlite3: Sqlite3, TContext: Context, Tvalue: Value, Tcallback: Callback, Tcreate_function_step_func: Create_function_step_func, @@ -129,220 +129,220 @@ type Tcollation_needed_func: Collation_needed_func].} proc close*(para1: PSqlite3): int32{.cdecl, dynlib: Lib, importc: "sqlite3_close".} -proc exec*(para1: PSqlite3, sql: cstring, para3: Callback, para4: pointer, - errmsg: var cstring): int32{.cdecl, dynlib: Lib, +proc exec*(para1: PSqlite3, sql: cstring, para3: Callback, para4: pointer, + errmsg: var cstring): int32{.cdecl, dynlib: Lib, importc: "sqlite3_exec".} -proc last_insert_rowid*(para1: PSqlite3): int64{.cdecl, dynlib: Lib, +proc last_insert_rowid*(para1: PSqlite3): int64{.cdecl, dynlib: Lib, importc: "sqlite3_last_insert_rowid".} proc changes*(para1: PSqlite3): int32{.cdecl, dynlib: Lib, importc: "sqlite3_changes".} -proc total_changes*(para1: PSqlite3): int32{.cdecl, dynlib: Lib, +proc total_changes*(para1: PSqlite3): int32{.cdecl, dynlib: Lib, importc: "sqlite3_total_changes".} proc interrupt*(para1: PSqlite3){.cdecl, dynlib: Lib, importc: "sqlite3_interrupt".} -proc complete*(sql: cstring): int32{.cdecl, dynlib: Lib, +proc complete*(sql: cstring): int32{.cdecl, dynlib: Lib, importc: "sqlite3_complete".} -proc complete16*(sql: pointer): int32{.cdecl, dynlib: Lib, +proc complete16*(sql: pointer): int32{.cdecl, dynlib: Lib, importc: "sqlite3_complete16".} -proc busy_handler*(para1: PSqlite3, - para2: proc (para1: pointer, para2: int32): int32{.cdecl.}, - para3: pointer): int32{.cdecl, dynlib: Lib, +proc busy_handler*(para1: PSqlite3, + para2: proc (para1: pointer, para2: int32): int32{.cdecl.}, + para3: pointer): int32{.cdecl, dynlib: Lib, importc: "sqlite3_busy_handler".} -proc busy_timeout*(para1: PSqlite3, ms: int32): int32{.cdecl, dynlib: Lib, +proc busy_timeout*(para1: PSqlite3, ms: int32): int32{.cdecl, dynlib: Lib, importc: "sqlite3_busy_timeout".} -proc get_table*(para1: PSqlite3, sql: cstring, resultp: var cstringArray, - nrow, ncolumn: var cint, errmsg: ptr cstring): int32{.cdecl, +proc get_table*(para1: PSqlite3, sql: cstring, resultp: var cstringArray, + nrow, ncolumn: var cint, errmsg: ptr cstring): int32{.cdecl, dynlib: Lib, importc: "sqlite3_get_table".} -proc free_table*(result: cstringArray){.cdecl, dynlib: Lib, +proc free_table*(result: cstringArray){.cdecl, dynlib: Lib, importc: "sqlite3_free_table".} # Todo: see how translate sqlite3_mprintf, sqlite3_vmprintf, sqlite3_snprintf # function sqlite3_mprintf(_para1:Pchar; args:array of const):Pchar;cdecl; external Sqlite3Lib name 'sqlite3_mprintf'; -proc mprintf*(para1: cstring): cstring{.cdecl, varargs, dynlib: Lib, +proc mprintf*(para1: cstring): cstring{.cdecl, varargs, dynlib: Lib, importc: "sqlite3_mprintf".} #function sqlite3_vmprintf(_para1:Pchar; _para2:va_list):Pchar;cdecl; external Sqlite3Lib name 'sqlite3_vmprintf'; proc free*(z: cstring){.cdecl, dynlib: Lib, importc: "sqlite3_free".} #function sqlite3_snprintf(_para1:longint; _para2:Pchar; _para3:Pchar; args:array of const):Pchar;cdecl; external Sqlite3Lib name 'sqlite3_snprintf'; -proc snprintf*(para1: int32, para2: cstring, para3: cstring): cstring{.cdecl, +proc snprintf*(para1: int32, para2: cstring, para3: cstring): cstring{.cdecl, dynlib: Lib, varargs, importc: "sqlite3_snprintf".} -proc set_authorizer*(para1: PSqlite3, xAuth: proc (para1: pointer, para2: int32, +proc set_authorizer*(para1: PSqlite3, xAuth: proc (para1: pointer, para2: int32, para3: cstring, para4: cstring, para5: cstring, para6: cstring): int32{. - cdecl.}, pUserData: pointer): int32{.cdecl, dynlib: Lib, + cdecl.}, pUserData: pointer): int32{.cdecl, dynlib: Lib, importc: "sqlite3_set_authorizer".} -proc trace*(para1: PSqlite3, xTrace: proc (para1: pointer, para2: cstring){.cdecl.}, - para3: pointer): pointer{.cdecl, dynlib: Lib, +proc trace*(para1: PSqlite3, xTrace: proc (para1: pointer, para2: cstring){.cdecl.}, + para3: pointer): pointer{.cdecl, dynlib: Lib, importc: "sqlite3_trace".} -proc progress_handler*(para1: PSqlite3, para2: int32, - para3: proc (para1: pointer): int32{.cdecl.}, - para4: pointer){.cdecl, dynlib: Lib, +proc progress_handler*(para1: PSqlite3, para2: int32, + para3: proc (para1: pointer): int32{.cdecl.}, + para4: pointer){.cdecl, dynlib: Lib, importc: "sqlite3_progress_handler".} -proc commit_hook*(para1: PSqlite3, para2: proc (para1: pointer): int32{.cdecl.}, - para3: pointer): pointer{.cdecl, dynlib: Lib, +proc commit_hook*(para1: PSqlite3, para2: proc (para1: pointer): int32{.cdecl.}, + para3: pointer): pointer{.cdecl, dynlib: Lib, importc: "sqlite3_commit_hook".} -proc open*(filename: cstring, ppDb: var PSqlite3): int32{.cdecl, dynlib: Lib, +proc open*(filename: cstring, ppDb: var PSqlite3): int32{.cdecl, dynlib: Lib, importc: "sqlite3_open".} -proc open16*(filename: pointer, ppDb: var PSqlite3): int32{.cdecl, dynlib: Lib, +proc open16*(filename: pointer, ppDb: var PSqlite3): int32{.cdecl, dynlib: Lib, importc: "sqlite3_open16".} proc errcode*(db: PSqlite3): int32{.cdecl, dynlib: Lib, importc: "sqlite3_errcode".} proc errmsg*(para1: PSqlite3): cstring{.cdecl, dynlib: Lib, importc: "sqlite3_errmsg".} -proc errmsg16*(para1: PSqlite3): pointer{.cdecl, dynlib: Lib, +proc errmsg16*(para1: PSqlite3): pointer{.cdecl, dynlib: Lib, importc: "sqlite3_errmsg16".} -proc prepare*(db: PSqlite3, zSql: cstring, nBytes: int32, ppStmt: var Pstmt, - pzTail: ptr cstring): int32{.cdecl, dynlib: Lib, +proc prepare*(db: PSqlite3, zSql: cstring, nBytes: int32, ppStmt: var Pstmt, + pzTail: ptr cstring): int32{.cdecl, dynlib: Lib, importc: "sqlite3_prepare".} - + proc prepare_v2*(db: PSqlite3, zSql: cstring, nByte: cint, ppStmt: var Pstmt, pzTail: ptr cstring): cint {. importc: "sqlite3_prepare_v2", cdecl, dynlib: Lib.} - -proc prepare16*(db: PSqlite3, zSql: pointer, nBytes: int32, ppStmt: var Pstmt, - pzTail: var pointer): int32{.cdecl, dynlib: Lib, + +proc prepare16*(db: PSqlite3, zSql: pointer, nBytes: int32, ppStmt: var Pstmt, + pzTail: var pointer): int32{.cdecl, dynlib: Lib, importc: "sqlite3_prepare16".} -proc bind_blob*(para1: Pstmt, para2: int32, para3: pointer, n: int32, - para5: Tbind_destructor_func): int32{.cdecl, dynlib: Lib, +proc bind_blob*(para1: Pstmt, para2: int32, para3: pointer, n: int32, + para5: Tbind_destructor_func): int32{.cdecl, dynlib: Lib, importc: "sqlite3_bind_blob".} -proc bind_double*(para1: Pstmt, para2: int32, para3: float64): int32{.cdecl, +proc bind_double*(para1: Pstmt, para2: int32, para3: float64): int32{.cdecl, dynlib: Lib, importc: "sqlite3_bind_double".} -proc bind_int*(para1: Pstmt, para2: int32, para3: int32): int32{.cdecl, +proc bind_int*(para1: Pstmt, para2: int32, para3: int32): int32{.cdecl, dynlib: Lib, importc: "sqlite3_bind_int".} -proc bind_int64*(para1: Pstmt, para2: int32, para3: int64): int32{.cdecl, +proc bind_int64*(para1: Pstmt, para2: int32, para3: int64): int32{.cdecl, dynlib: Lib, importc: "sqlite3_bind_int64".} -proc bind_null*(para1: Pstmt, para2: int32): int32{.cdecl, dynlib: Lib, +proc bind_null*(para1: Pstmt, para2: int32): int32{.cdecl, dynlib: Lib, importc: "sqlite3_bind_null".} -proc bind_text*(para1: Pstmt, para2: int32, para3: cstring, n: int32, - para5: Tbind_destructor_func): int32{.cdecl, dynlib: Lib, +proc bind_text*(para1: Pstmt, para2: int32, para3: cstring, n: int32, + para5: Tbind_destructor_func): int32{.cdecl, dynlib: Lib, importc: "sqlite3_bind_text".} -proc bind_text16*(para1: Pstmt, para2: int32, para3: pointer, para4: int32, - para5: Tbind_destructor_func): int32{.cdecl, dynlib: Lib, +proc bind_text16*(para1: Pstmt, para2: int32, para3: pointer, para4: int32, + para5: Tbind_destructor_func): int32{.cdecl, dynlib: Lib, importc: "sqlite3_bind_text16".} #function sqlite3_bind_value(_para1:Psqlite3_stmt; _para2:longint; _para3:Psqlite3_value):longint;cdecl; external Sqlite3Lib name 'sqlite3_bind_value'; #These overloaded functions were introduced to allow the use of SQLITE_STATIC and SQLITE_TRANSIENT #It's the c world man ;-) -proc bind_blob*(para1: Pstmt, para2: int32, para3: pointer, n: int32, - para5: int32): int32{.cdecl, dynlib: Lib, +proc bind_blob*(para1: Pstmt, para2: int32, para3: pointer, n: int32, + para5: int32): int32{.cdecl, dynlib: Lib, importc: "sqlite3_bind_blob".} -proc bind_text*(para1: Pstmt, para2: int32, para3: cstring, n: int32, - para5: int32): int32{.cdecl, dynlib: Lib, +proc bind_text*(para1: Pstmt, para2: int32, para3: cstring, n: int32, + para5: int32): int32{.cdecl, dynlib: Lib, importc: "sqlite3_bind_text".} -proc bind_text16*(para1: Pstmt, para2: int32, para3: pointer, para4: int32, - para5: int32): int32{.cdecl, dynlib: Lib, +proc bind_text16*(para1: Pstmt, para2: int32, para3: pointer, para4: int32, + para5: int32): int32{.cdecl, dynlib: Lib, importc: "sqlite3_bind_text16".} -proc bind_parameter_count*(para1: Pstmt): int32{.cdecl, dynlib: Lib, +proc bind_parameter_count*(para1: Pstmt): int32{.cdecl, dynlib: Lib, importc: "sqlite3_bind_parameter_count".} -proc bind_parameter_name*(para1: Pstmt, para2: int32): cstring{.cdecl, +proc bind_parameter_name*(para1: Pstmt, para2: int32): cstring{.cdecl, dynlib: Lib, importc: "sqlite3_bind_parameter_name".} -proc bind_parameter_index*(para1: Pstmt, zName: cstring): int32{.cdecl, +proc bind_parameter_index*(para1: Pstmt, zName: cstring): int32{.cdecl, dynlib: Lib, importc: "sqlite3_bind_parameter_index".} #function sqlite3_clear_bindings(_para1:Psqlite3_stmt):longint;cdecl; external Sqlite3Lib name 'sqlite3_clear_bindings'; -proc column_count*(pStmt: Pstmt): int32{.cdecl, dynlib: Lib, +proc column_count*(pStmt: Pstmt): int32{.cdecl, dynlib: Lib, importc: "sqlite3_column_count".} -proc column_name*(para1: Pstmt, para2: int32): cstring{.cdecl, dynlib: Lib, +proc column_name*(para1: Pstmt, para2: int32): cstring{.cdecl, dynlib: Lib, importc: "sqlite3_column_name".} -proc column_name16*(para1: Pstmt, para2: int32): pointer{.cdecl, dynlib: Lib, +proc column_name16*(para1: Pstmt, para2: int32): pointer{.cdecl, dynlib: Lib, importc: "sqlite3_column_name16".} -proc column_decltype*(para1: Pstmt, i: int32): cstring{.cdecl, dynlib: Lib, +proc column_decltype*(para1: Pstmt, i: int32): cstring{.cdecl, dynlib: Lib, importc: "sqlite3_column_decltype".} -proc column_decltype16*(para1: Pstmt, para2: int32): pointer{.cdecl, +proc column_decltype16*(para1: Pstmt, para2: int32): pointer{.cdecl, dynlib: Lib, importc: "sqlite3_column_decltype16".} proc step*(para1: Pstmt): int32{.cdecl, dynlib: Lib, importc: "sqlite3_step".} -proc data_count*(pStmt: Pstmt): int32{.cdecl, dynlib: Lib, +proc data_count*(pStmt: Pstmt): int32{.cdecl, dynlib: Lib, importc: "sqlite3_data_count".} -proc column_blob*(para1: Pstmt, iCol: int32): pointer{.cdecl, dynlib: Lib, +proc column_blob*(para1: Pstmt, iCol: int32): pointer{.cdecl, dynlib: Lib, importc: "sqlite3_column_blob".} -proc column_bytes*(para1: Pstmt, iCol: int32): int32{.cdecl, dynlib: Lib, +proc column_bytes*(para1: Pstmt, iCol: int32): int32{.cdecl, dynlib: Lib, importc: "sqlite3_column_bytes".} -proc column_bytes16*(para1: Pstmt, iCol: int32): int32{.cdecl, dynlib: Lib, +proc column_bytes16*(para1: Pstmt, iCol: int32): int32{.cdecl, dynlib: Lib, importc: "sqlite3_column_bytes16".} -proc column_double*(para1: Pstmt, iCol: int32): float64{.cdecl, dynlib: Lib, +proc column_double*(para1: Pstmt, iCol: int32): float64{.cdecl, dynlib: Lib, importc: "sqlite3_column_double".} -proc column_int*(para1: Pstmt, iCol: int32): int32{.cdecl, dynlib: Lib, +proc column_int*(para1: Pstmt, iCol: int32): int32{.cdecl, dynlib: Lib, importc: "sqlite3_column_int".} -proc column_int64*(para1: Pstmt, iCol: int32): int64{.cdecl, dynlib: Lib, +proc column_int64*(para1: Pstmt, iCol: int32): int64{.cdecl, dynlib: Lib, importc: "sqlite3_column_int64".} -proc column_text*(para1: Pstmt, iCol: int32): cstring{.cdecl, dynlib: Lib, +proc column_text*(para1: Pstmt, iCol: int32): cstring{.cdecl, dynlib: Lib, importc: "sqlite3_column_text".} -proc column_text16*(para1: Pstmt, iCol: int32): pointer{.cdecl, dynlib: Lib, +proc column_text16*(para1: Pstmt, iCol: int32): pointer{.cdecl, dynlib: Lib, importc: "sqlite3_column_text16".} -proc column_type*(para1: Pstmt, iCol: int32): int32{.cdecl, dynlib: Lib, +proc column_type*(para1: Pstmt, iCol: int32): int32{.cdecl, dynlib: Lib, importc: "sqlite3_column_type".} -proc finalize*(pStmt: Pstmt): int32{.cdecl, dynlib: Lib, +proc finalize*(pStmt: Pstmt): int32{.cdecl, dynlib: Lib, importc: "sqlite3_finalize".} proc reset*(pStmt: Pstmt): int32{.cdecl, dynlib: Lib, importc: "sqlite3_reset".} -proc create_function*(para1: PSqlite3, zFunctionName: cstring, nArg: int32, - eTextRep: int32, para5: pointer, - xFunc: Create_function_func_func, - xStep: Create_function_step_func, - xFinal: Create_function_final_func): int32{.cdecl, +proc create_function*(para1: PSqlite3, zFunctionName: cstring, nArg: int32, + eTextRep: int32, para5: pointer, + xFunc: Create_function_func_func, + xStep: Create_function_step_func, + xFinal: Create_function_final_func): int32{.cdecl, dynlib: Lib, importc: "sqlite3_create_function".} -proc create_function16*(para1: PSqlite3, zFunctionName: pointer, nArg: int32, - eTextRep: int32, para5: pointer, - xFunc: Create_function_func_func, - xStep: Create_function_step_func, - xFinal: Create_function_final_func): int32{.cdecl, +proc create_function16*(para1: PSqlite3, zFunctionName: pointer, nArg: int32, + eTextRep: int32, para5: pointer, + xFunc: Create_function_func_func, + xStep: Create_function_step_func, + xFinal: Create_function_final_func): int32{.cdecl, dynlib: Lib, importc: "sqlite3_create_function16".} -proc aggregate_count*(para1: Pcontext): int32{.cdecl, dynlib: Lib, +proc aggregate_count*(para1: Pcontext): int32{.cdecl, dynlib: Lib, importc: "sqlite3_aggregate_count".} -proc value_blob*(para1: Pvalue): pointer{.cdecl, dynlib: Lib, +proc value_blob*(para1: Pvalue): pointer{.cdecl, dynlib: Lib, importc: "sqlite3_value_blob".} -proc value_bytes*(para1: Pvalue): int32{.cdecl, dynlib: Lib, +proc value_bytes*(para1: Pvalue): int32{.cdecl, dynlib: Lib, importc: "sqlite3_value_bytes".} -proc value_bytes16*(para1: Pvalue): int32{.cdecl, dynlib: Lib, +proc value_bytes16*(para1: Pvalue): int32{.cdecl, dynlib: Lib, importc: "sqlite3_value_bytes16".} -proc value_double*(para1: Pvalue): float64{.cdecl, dynlib: Lib, +proc value_double*(para1: Pvalue): float64{.cdecl, dynlib: Lib, importc: "sqlite3_value_double".} -proc value_int*(para1: Pvalue): int32{.cdecl, dynlib: Lib, +proc value_int*(para1: Pvalue): int32{.cdecl, dynlib: Lib, importc: "sqlite3_value_int".} -proc value_int64*(para1: Pvalue): int64{.cdecl, dynlib: Lib, +proc value_int64*(para1: Pvalue): int64{.cdecl, dynlib: Lib, importc: "sqlite3_value_int64".} -proc value_text*(para1: Pvalue): cstring{.cdecl, dynlib: Lib, +proc value_text*(para1: Pvalue): cstring{.cdecl, dynlib: Lib, importc: "sqlite3_value_text".} -proc value_text16*(para1: Pvalue): pointer{.cdecl, dynlib: Lib, +proc value_text16*(para1: Pvalue): pointer{.cdecl, dynlib: Lib, importc: "sqlite3_value_text16".} -proc value_text16le*(para1: Pvalue): pointer{.cdecl, dynlib: Lib, +proc value_text16le*(para1: Pvalue): pointer{.cdecl, dynlib: Lib, importc: "sqlite3_value_text16le".} -proc value_text16be*(para1: Pvalue): pointer{.cdecl, dynlib: Lib, +proc value_text16be*(para1: Pvalue): pointer{.cdecl, dynlib: Lib, importc: "sqlite3_value_text16be".} -proc value_type*(para1: Pvalue): int32{.cdecl, dynlib: Lib, +proc value_type*(para1: Pvalue): int32{.cdecl, dynlib: Lib, importc: "sqlite3_value_type".} -proc aggregate_context*(para1: Pcontext, nBytes: int32): pointer{.cdecl, +proc aggregate_context*(para1: Pcontext, nBytes: int32): pointer{.cdecl, dynlib: Lib, importc: "sqlite3_aggregate_context".} -proc user_data*(para1: Pcontext): pointer{.cdecl, dynlib: Lib, +proc user_data*(para1: Pcontext): pointer{.cdecl, dynlib: Lib, importc: "sqlite3_user_data".} -proc get_auxdata*(para1: Pcontext, para2: int32): pointer{.cdecl, dynlib: Lib, +proc get_auxdata*(para1: Pcontext, para2: int32): pointer{.cdecl, dynlib: Lib, importc: "sqlite3_get_auxdata".} -proc set_auxdata*(para1: Pcontext, para2: int32, para3: pointer, - para4: proc (para1: pointer){.cdecl.}){.cdecl, dynlib: Lib, +proc set_auxdata*(para1: Pcontext, para2: int32, para3: pointer, + para4: proc (para1: pointer){.cdecl.}){.cdecl, dynlib: Lib, importc: "sqlite3_set_auxdata".} -proc result_blob*(para1: Pcontext, para2: pointer, para3: int32, - para4: Result_func){.cdecl, dynlib: Lib, +proc result_blob*(para1: Pcontext, para2: pointer, para3: int32, + para4: Result_func){.cdecl, dynlib: Lib, importc: "sqlite3_result_blob".} -proc result_double*(para1: Pcontext, para2: float64){.cdecl, dynlib: Lib, +proc result_double*(para1: Pcontext, para2: float64){.cdecl, dynlib: Lib, importc: "sqlite3_result_double".} -proc result_error*(para1: Pcontext, para2: cstring, para3: int32){.cdecl, +proc result_error*(para1: Pcontext, para2: cstring, para3: int32){.cdecl, dynlib: Lib, importc: "sqlite3_result_error".} -proc result_error16*(para1: Pcontext, para2: pointer, para3: int32){.cdecl, +proc result_error16*(para1: Pcontext, para2: pointer, para3: int32){.cdecl, dynlib: Lib, importc: "sqlite3_result_error16".} -proc result_int*(para1: Pcontext, para2: int32){.cdecl, dynlib: Lib, +proc result_int*(para1: Pcontext, para2: int32){.cdecl, dynlib: Lib, importc: "sqlite3_result_int".} -proc result_int64*(para1: Pcontext, para2: int64){.cdecl, dynlib: Lib, +proc result_int64*(para1: Pcontext, para2: int64){.cdecl, dynlib: Lib, importc: "sqlite3_result_int64".} -proc result_null*(para1: Pcontext){.cdecl, dynlib: Lib, +proc result_null*(para1: Pcontext){.cdecl, dynlib: Lib, importc: "sqlite3_result_null".} -proc result_text*(para1: Pcontext, para2: cstring, para3: int32, - para4: Result_func){.cdecl, dynlib: Lib, +proc result_text*(para1: Pcontext, para2: cstring, para3: int32, + para4: Result_func){.cdecl, dynlib: Lib, importc: "sqlite3_result_text".} -proc result_text16*(para1: Pcontext, para2: pointer, para3: int32, - para4: Result_func){.cdecl, dynlib: Lib, +proc result_text16*(para1: Pcontext, para2: pointer, para3: int32, + para4: Result_func){.cdecl, dynlib: Lib, importc: "sqlite3_result_text16".} -proc result_text16le*(para1: Pcontext, para2: pointer, para3: int32, - para4: Result_func){.cdecl, dynlib: Lib, +proc result_text16le*(para1: Pcontext, para2: pointer, para3: int32, + para4: Result_func){.cdecl, dynlib: Lib, importc: "sqlite3_result_text16le".} -proc result_text16be*(para1: Pcontext, para2: pointer, para3: int32, - para4: Result_func){.cdecl, dynlib: Lib, +proc result_text16be*(para1: Pcontext, para2: pointer, para3: int32, + para4: Result_func){.cdecl, dynlib: Lib, importc: "sqlite3_result_text16be".} -proc result_value*(para1: Pcontext, para2: Pvalue){.cdecl, dynlib: Lib, +proc result_value*(para1: Pcontext, para2: Pvalue){.cdecl, dynlib: Lib, importc: "sqlite3_result_value".} -proc create_collation*(para1: PSqlite3, zName: cstring, eTextRep: int32, +proc create_collation*(para1: PSqlite3, zName: cstring, eTextRep: int32, para4: pointer, xCompare: Create_collation_func): int32{. cdecl, dynlib: Lib, importc: "sqlite3_create_collation".} -proc create_collation16*(para1: PSqlite3, zName: cstring, eTextRep: int32, +proc create_collation16*(para1: PSqlite3, zName: cstring, eTextRep: int32, para4: pointer, xCompare: Create_collation_func): int32{. cdecl, dynlib: Lib, importc: "sqlite3_create_collation16".} proc collation_needed*(para1: PSqlite3, para2: pointer, para3: Collation_needed_func): int32{. @@ -350,10 +350,10 @@ proc collation_needed*(para1: PSqlite3, para2: pointer, para3: Collation_needed_ proc collation_needed16*(para1: PSqlite3, para2: pointer, para3: Collation_needed_func): int32{. cdecl, dynlib: Lib, importc: "sqlite3_collation_needed16".} proc libversion*(): cstring{.cdecl, dynlib: Lib, importc: "sqlite3_libversion".} - #Alias for allowing better code portability (win32 is not working with external variables) + #Alias for allowing better code portability (win32 is not working with external variables) proc version*(): cstring{.cdecl, dynlib: Lib, importc: "sqlite3_libversion".} # Not published functions -proc libversion_number*(): int32{.cdecl, dynlib: Lib, +proc libversion_number*(): int32{.cdecl, dynlib: Lib, importc: "sqlite3_libversion_number".} #function sqlite3_key(db:Psqlite3; pKey:pointer; nKey:longint):longint;cdecl; external Sqlite3Lib name 'sqlite3_key'; #function sqlite3_rekey(db:Psqlite3; pKey:pointer; nKey:longint):longint;cdecl; external Sqlite3Lib name 'sqlite3_rekey'; diff --git a/lib/wrappers/tinyc.nim b/lib/wrappers/tinyc.nim index 05c65b12f..47b505abc 100644 --- a/lib/wrappers/tinyc.nim +++ b/lib/wrappers/tinyc.nim @@ -10,7 +10,7 @@ type CcState {.pure, final.} = object PccState* = ptr CcState - + ErrorFunc* = proc (opaque: pointer, msg: cstring) {.cdecl.} {.deprecated: [TccState: CcState, TErrorFunc: ErrorFunc].} @@ -31,33 +31,33 @@ proc setWarning*(s: PccState, warningName: cstring, value: int) {.cdecl, importc: "tcc_set_warning".} ## set/reset a warning -# preprocessor +# preprocessor -proc addIncludePath*(s: PccState, pathname: cstring) {.cdecl, +proc addIncludePath*(s: PccState, pathname: cstring) {.cdecl, importc: "tcc_add_include_path".} ## add include path -proc addSysincludePath*(s: PccState, pathname: cstring) {.cdecl, +proc addSysincludePath*(s: PccState, pathname: cstring) {.cdecl, importc: "tcc_add_sysinclude_path".} ## add in system include path -proc defineSymbol*(s: PccState, sym, value: cstring) {.cdecl, +proc defineSymbol*(s: PccState, sym, value: cstring) {.cdecl, importc: "tcc_define_symbol".} ## define preprocessor symbol 'sym'. Can put optional value -proc undefineSymbol*(s: PccState, sym: cstring) {.cdecl, +proc undefineSymbol*(s: PccState, sym: cstring) {.cdecl, importc: "tcc_undefine_symbol".} ## undefine preprocess symbol 'sym' -# compiling +# compiling -proc addFile*(s: PccState, filename: cstring): cint {.cdecl, +proc addFile*(s: PccState, filename: cstring): cint {.cdecl, importc: "tcc_add_file".} ## add a file (either a C file, dll, an object, a library or an ld ## script). Return -1 if error. -proc compileString*(s: PccState, buf: cstring): cint {.cdecl, +proc compileString*(s: PccState, buf: cstring): cint {.cdecl, importc: "tcc_compile_string".} ## compile a string containing a C source. Return non zero if error. @@ -71,12 +71,12 @@ const OutputDll*: cint = 2 ## dynamic library OutputObj*: cint = 3 ## object file OutputPreprocess*: cint = 4 ## preprocessed file (used internally) - + OutputFormatElf*: cint = 0 ## default output format: ELF OutputFormatBinary*: cint = 1 ## binary image output OutputFormatCoff*: cint = 2 ## COFF -proc setOutputType*(s: PCCState, outputType: cint): cint {.cdecl, +proc setOutputType*(s: PCCState, outputType: cint): cint {.cdecl, importc: "tcc_set_output_type".} ## set output type. MUST BE CALLED before any compilation @@ -115,5 +115,5 @@ proc getSymbol*(s: PccState, name: cstring): pointer {.cdecl, proc setLibPath*(s: PccState, path: cstring) {.cdecl, importc: "tcc_set_lib_path".} ## set CONFIG_TCCDIR at runtime - + From ac9c1cd6b980d4f00eeb52d1109d8e2c8cd21213 Mon Sep 17 00:00:00 2001 From: Adam Strzelecki Date: Fri, 4 Sep 2015 23:04:17 +0200 Subject: [PATCH 0899/1263] tools: Trim .nim files trailing whitespace via OSX: find . -name '*.nim' -exec sed -i '' -E 's/[[:space:]]+$//' {} + --- tools/cmerge.nim | 2 +- tools/detect/detect.nim | 230 +++++++++++++-------------- tools/detect/windows_i386_consts.nim | 192 +++++++++++----------- tools/fakedeps.nim | 2 +- tools/niminst/debcreation.nim | 60 +++---- tools/noprefix.nim | 4 +- tools/restorecc.nim | 12 +- 7 files changed, 251 insertions(+), 251 deletions(-) diff --git a/tools/cmerge.nim b/tools/cmerge.nim index 13bf8b64c..15fbd8a76 100644 --- a/tools/cmerge.nim +++ b/tools/cmerge.nim @@ -5,7 +5,7 @@ import os, sets, pegs type ProcessResult = enum prSkipIncludeDir, prAddIncludeDir -proc process(dir, infile: string, outfile: File, +proc process(dir, infile: string, outfile: File, processed: var HashSet[string]): ProcessResult = if processed.containsOrIncl(infile): return prSkipIncludeDir let toProcess = dir / infile diff --git a/tools/detect/detect.nim b/tools/detect/detect.nim index 77efdaacd..0470257ee 100644 --- a/tools/detect/detect.nim +++ b/tools/detect/detect.nim @@ -29,18 +29,18 @@ int main() { """ type - TTypeKind = enum + TTypeKind = enum cint, cshort, clong, cstring, pointer var hd = "" tl = "" -proc myExec(cmd: string): bool = +proc myExec(cmd: string): bool = echo "CMD ", cmd return execShellCmd(cmd) == 0 -proc header(s: string): bool = +proc header(s: string): bool = const testh = "testh" var f: TFile if open(f, addFileExt(testh, "c"), fmWrite): @@ -55,10 +55,10 @@ proc header(s: string): bool = else: echo("Not found: ", s) -proc main = +proc main = const gen = "genconsts" var f: TFile - if open(f, addFileExt(gen, "c"), fmWrite): + if open(f, addFileExt(gen, "c"), fmWrite): f.write(cfile % [hd, tl, system.hostOS, system.hostCPU]) close(f) if not myExec(cc % [gen.addFileExt(ExeExt), gen]): quit(1) @@ -69,26 +69,26 @@ proc main = #removeFile(addFileExt(gen, "c")) echo("Success") -proc v(name: string, typ: TTypeKind=cint) = +proc v(name: string, typ: TTypeKind=cint) = var n = if name[0] == '_': substr(name, 1) else: name var t = $typ case typ - of pointer: - addf(tl, - "#ifdef $3\n fprintf(f, \" $1* = cast[$2](%p)\\n\", $3);\n#endif\n", + of pointer: + addf(tl, + "#ifdef $3\n fprintf(f, \" $1* = cast[$2](%p)\\n\", $3);\n#endif\n", n, t, name) - + of cstring: - addf(tl, + addf(tl, "#ifdef $3\n fprintf(f, \" $1* = $2(\\\"%s\\\")\\n\", $3);\n#endif\n", n, t, name) of clong: - addf(tl, - "#ifdef $3\n fprintf(f, \" $1* = $2(%ld)\\n\", $3);\n#endif\n", - n, t, name) - else: - addf(tl, - "#ifdef $3\n fprintf(f, \" $1* = $2(%d)\\n\", $3);\n#endif\n", + addf(tl, + "#ifdef $3\n fprintf(f, \" $1* = $2(%ld)\\n\", $3);\n#endif\n", + n, t, name) + else: + addf(tl, + "#ifdef $3\n fprintf(f, \" $1* = $2(%d)\\n\", $3);\n#endif\n", n, t, name) if header(""): @@ -187,7 +187,7 @@ if header(""): v("ETXTBSY") v("EWOULDBLOCK") v("EXDEV") - + if header(""): v("F_DUPFD") v("F_GETFD") @@ -346,7 +346,7 @@ if header(""): v("YESEXPR") v("NOEXPR") v("CRNCYSTR") - + if header(""): v("LC_ALL") #{.importc, header: .}: cint v("LC_COLLATE") #{.importc, header: "".}: cint @@ -358,20 +358,20 @@ if header(""): if header(""): v("PTHREAD_BARRIER_SERIAL_THREAD") - v("PTHREAD_CANCEL_ASYNCHRONOUS") - v("PTHREAD_CANCEL_ENABLE") + v("PTHREAD_CANCEL_ASYNCHRONOUS") + v("PTHREAD_CANCEL_ENABLE") v("PTHREAD_CANCEL_DEFERRED") - v("PTHREAD_CANCEL_DISABLE") + v("PTHREAD_CANCEL_DISABLE") #v("PTHREAD_CANCELED") - #v("PTHREAD_COND_INITIALIZER") + #v("PTHREAD_COND_INITIALIZER") v("PTHREAD_CREATE_DETACHED") v("PTHREAD_CREATE_JOINABLE") v("PTHREAD_EXPLICIT_SCHED") - v("PTHREAD_INHERIT_SCHED") - v("PTHREAD_MUTEX_DEFAULT") + v("PTHREAD_INHERIT_SCHED") + v("PTHREAD_MUTEX_DEFAULT") v("PTHREAD_MUTEX_ERRORCHECK") - #v("PTHREAD_MUTEX_INITIALIZER") - v("PTHREAD_MUTEX_NORMAL") + #v("PTHREAD_MUTEX_INITIALIZER") + v("PTHREAD_MUTEX_NORMAL") v("PTHREAD_MUTEX_RECURSIVE") #{.importc, header: "".}: cint #v("PTHREAD_ONCE_INIT") #{.importc, header: "".}: cint v("PTHREAD_PRIO_INHERIT") #{.importc, header: "".}: cint @@ -392,28 +392,28 @@ if header(""): v("X_OK") v("_CS_PATH") - v("_CS_POSIX_V6_ILP32_OFF32_CFLAGS") - v("_CS_POSIX_V6_ILP32_OFF32_LDFLAGS") - v("_CS_POSIX_V6_ILP32_OFF32_LIBS") - v("_CS_POSIX_V6_ILP32_OFFBIG_CFLAGS") - v("_CS_POSIX_V6_ILP32_OFFBIG_LDFLAGS") - v("_CS_POSIX_V6_ILP32_OFFBIG_LIBS") - v("_CS_POSIX_V6_LP64_OFF64_CFLAGS") + v("_CS_POSIX_V6_ILP32_OFF32_CFLAGS") + v("_CS_POSIX_V6_ILP32_OFF32_LDFLAGS") + v("_CS_POSIX_V6_ILP32_OFF32_LIBS") + v("_CS_POSIX_V6_ILP32_OFFBIG_CFLAGS") + v("_CS_POSIX_V6_ILP32_OFFBIG_LDFLAGS") + v("_CS_POSIX_V6_ILP32_OFFBIG_LIBS") + v("_CS_POSIX_V6_LP64_OFF64_CFLAGS") v("_CS_POSIX_V6_LP64_OFF64_LDFLAGS") - v("_CS_POSIX_V6_LP64_OFF64_LIBS") - v("_CS_POSIX_V6_LPBIG_OFFBIG_CFLAGS") - v("_CS_POSIX_V6_LPBIG_OFFBIG_LDFLAGS") - v("_CS_POSIX_V6_LPBIG_OFFBIG_LIBS") + v("_CS_POSIX_V6_LP64_OFF64_LIBS") + v("_CS_POSIX_V6_LPBIG_OFFBIG_CFLAGS") + v("_CS_POSIX_V6_LPBIG_OFFBIG_LDFLAGS") + v("_CS_POSIX_V6_LPBIG_OFFBIG_LIBS") v("_CS_POSIX_V6_WIDTH_RESTRICTED_ENVS") - v("F_LOCK") + v("F_LOCK") v("F_TEST") #{.importc: "F_TEST", header: "".}: cint v("F_TLOCK") #{.importc: "F_TLOCK", header: "".}: cint v("F_ULOCK") #{.importc: "F_ULOCK", header: "".}: cint v("_PC_2_SYMLINKS") #{.importc: "_PC_2_SYMLINKS", header: "".}: cint - v("_PC_ALLOC_SIZE_MIN") + v("_PC_ALLOC_SIZE_MIN") v("_PC_ASYNC_IO") #{.importc: "_PC_ASYNC_IO", header: "".}: cint - v("_PC_CHOWN_RESTRICTED") + v("_PC_CHOWN_RESTRICTED") v("_PC_FILESIZEBITS") #{.importc: "_PC_FILESIZEBITS", header: "".}: cint v("_PC_LINK_MAX") #{.importc: "_PC_LINK_MAX", header: "".}: cint v("_PC_MAX_CANON") #{.importc: "_PC_MAX_CANON", header: "".}: cint @@ -423,9 +423,9 @@ if header(""): v("_PC_PATH_MAX") #{.importc: "_PC_PATH_MAX", header: "".}: cint v("_PC_PIPE_BUF") #{.importc: "_PC_PIPE_BUF", header: "".}: cint v("_PC_PRIO_IO") #{.importc: "_PC_PRIO_IO", header: "".}: cint - v("_PC_REC_INCR_XFER_SIZE") - v("_PC_REC_MIN_XFER_SIZE") - v("_PC_REC_XFER_ALIGN") + v("_PC_REC_INCR_XFER_SIZE") + v("_PC_REC_MIN_XFER_SIZE") + v("_PC_REC_XFER_ALIGN") v("_PC_SYMLINK_MAX") #{.importc: "_PC_SYMLINK_MAX", header: "".}: cint v("_PC_SYNC_IO") #{.importc: "_PC_SYNC_IO", header: "".}: cint v("_PC_VDISABLE") #{.importc: "_PC_VDISABLE", header: "".}: cint @@ -436,8 +436,8 @@ if header(""): v("_SC_2_FORT_RUN") #{.importc: "_SC_2_FORT_RUN", header: "".}: cint v("_SC_2_LOCALEDEF") #{.importc: "_SC_2_LOCALEDEF", header: "".}: cint v("_SC_2_PBS") #{.importc: "_SC_2_PBS", header: "".}: cint - v("_SC_2_PBS_ACCOUNTING") - v("_SC_2_PBS_CHECKPOINT") + v("_SC_2_PBS_ACCOUNTING") + v("_SC_2_PBS_CHECKPOINT") v("_SC_2_PBS_LOCATE") #{.importc: "_SC_2_PBS_LOCATE", header: "".}: cint v("_SC_2_PBS_MESSAGE") #{.importc: "_SC_2_PBS_MESSAGE", header: "".}: cint v("_SC_2_PBS_TRACK") #{.importc: "_SC_2_PBS_TRACK", header: "".}: cint @@ -445,11 +445,11 @@ if header(""): v("_SC_2_UPE") #{.importc: "_SC_2_UPE", header: "".}: cint v("_SC_2_VERSION") #{.importc: "_SC_2_VERSION", header: "".}: cint v("_SC_ADVISORY_INFO") #{.importc: "_SC_ADVISORY_INFO", header: "".}: cint - v("_SC_AIO_LISTIO_MAX") + v("_SC_AIO_LISTIO_MAX") v("_SC_AIO_MAX") #{.importc: "_SC_AIO_MAX", header: "".}: cint - v("_SC_AIO_PRIO_DELTA_MAX") + v("_SC_AIO_PRIO_DELTA_MAX") v("_SC_ARG_MAX") #{.importc: "_SC_ARG_MAX", header: "".}: cint - v("_SC_ASYNCHRONOUS_IO") + v("_SC_ASYNCHRONOUS_IO") v("_SC_ATEXIT_MAX") #{.importc: "_SC_ATEXIT_MAX", header: "".}: cint v("_SC_BARRIERS") #{.importc: "_SC_BARRIERS", header: "".}: cint v("_SC_BC_BASE_MAX") #{.importc: "_SC_BC_BASE_MAX", header: "".}: cint @@ -458,10 +458,10 @@ if header(""): v("_SC_BC_STRING_MAX") #{.importc: "_SC_BC_STRING_MAX", header: "".}: cint v("_SC_CHILD_MAX") #{.importc: "_SC_CHILD_MAX", header: "".}: cint v("_SC_CLK_TCK") #{.importc: "_SC_CLK_TCK", header: "".}: cint - v("_SC_CLOCK_SELECTION") + v("_SC_CLOCK_SELECTION") v("_SC_COLL_WEIGHTS_MAX") v("_SC_CPUTIME") #{.importc: "_SC_CPUTIME", header: "".}: cint - v("_SC_DELAYTIMER_MAX") + v("_SC_DELAYTIMER_MAX") v("_SC_EXPR_NEST_MAX") #{.importc: "_SC_EXPR_NEST_MAX", header: "".}: cint v("_SC_FSYNC") #{.importc: "_SC_FSYNC", header: "".}: cint v("_SC_GETGR_R_SIZE_MAX") @@ -471,82 +471,82 @@ if header(""): v("_SC_IPV6") #{.importc: "_SC_IPV6", header: "".}: cint v("_SC_JOB_CONTROL") #{.importc: "_SC_JOB_CONTROL", header: "".}: cint v("_SC_LINE_MAX") #{.importc: "_SC_LINE_MAX", header: "".}: cint - v("_SC_LOGIN_NAME_MAX") + v("_SC_LOGIN_NAME_MAX") v("_SC_MAPPED_FILES") #{.importc: "_SC_MAPPED_FILES", header: "".}: cint v("_SC_MEMLOCK") #{.importc: "_SC_MEMLOCK", header: "".}: cint v("_SC_MEMLOCK_RANGE") #{.importc: "_SC_MEMLOCK_RANGE", header: "".}: cint v("_SC_MEMORY_PROTECTION") - v("_SC_MESSAGE_PASSING") - v("_SC_MONOTONIC_CLOCK") + v("_SC_MESSAGE_PASSING") + v("_SC_MONOTONIC_CLOCK") v("_SC_MQ_OPEN_MAX") #{.importc: "_SC_MQ_OPEN_MAX", header: "".}: cint v("_SC_MQ_PRIO_MAX") #{.importc: "_SC_MQ_PRIO_MAX", header: "".}: cint v("_SC_NGROUPS_MAX") #{.importc: "_SC_NGROUPS_MAX", header: "".}: cint v("_SC_OPEN_MAX") #{.importc: "_SC_OPEN_MAX", header: "".}: cint v("_SC_PAGE_SIZE") #{.importc: "_SC_PAGE_SIZE", header: "".}: cint - v("_SC_PRIORITIZED_IO") - v("_SC_PRIORITY_SCHEDULING") + v("_SC_PRIORITIZED_IO") + v("_SC_PRIORITY_SCHEDULING") v("_SC_RAW_SOCKETS") #{.importc: "_SC_RAW_SOCKETS", header: "".}: cint v("_SC_RE_DUP_MAX") #{.importc: "_SC_RE_DUP_MAX", header: "".}: cint - v("_SC_READER_WRITER_LOCKS") - v("_SC_REALTIME_SIGNALS") + v("_SC_READER_WRITER_LOCKS") + v("_SC_REALTIME_SIGNALS") v("_SC_REGEXP") #{.importc: "_SC_REGEXP", header: "".}: cint v("_SC_RTSIG_MAX") #{.importc: "_SC_RTSIG_MAX", header: "".}: cint v("_SC_SAVED_IDS") #{.importc: "_SC_SAVED_IDS", header: "".}: cint v("_SC_SEM_NSEMS_MAX") #{.importc: "_SC_SEM_NSEMS_MAX", header: "".}: cint v("_SC_SEM_VALUE_MAX") #{.importc: "_SC_SEM_VALUE_MAX", header: "".}: cint v("_SC_SEMAPHORES") #{.importc: "_SC_SEMAPHORES", header: "".}: cint - v("_SC_SHARED_MEMORY_OBJECTS") + v("_SC_SHARED_MEMORY_OBJECTS") v("_SC_SHELL") #{.importc: "_SC_SHELL", header: "".}: cint v("_SC_SIGQUEUE_MAX") #{.importc: "_SC_SIGQUEUE_MAX", header: "".}: cint v("_SC_SPAWN") #{.importc: "_SC_SPAWN", header: "".}: cint v("_SC_SPIN_LOCKS") #{.importc: "_SC_SPIN_LOCKS", header: "".}: cint - v("_SC_SPORADIC_SERVER") + v("_SC_SPORADIC_SERVER") v("_SC_SS_REPL_MAX") #{.importc: "_SC_SS_REPL_MAX", header: "".}: cint v("_SC_STREAM_MAX") #{.importc: "_SC_STREAM_MAX", header: "".}: cint v("_SC_SYMLOOP_MAX") #{.importc: "_SC_SYMLOOP_MAX", header: "".}: cint - v("_SC_SYNCHRONIZED_IO") - v("_SC_THREAD_ATTR_STACKADDR") - v("_SC_THREAD_ATTR_STACKSIZE") - v("_SC_THREAD_CPUTIME") - v("_SC_THREAD_DESTRUCTOR_ITERATIONS") - v("_SC_THREAD_KEYS_MAX") - v("_SC_THREAD_PRIO_INHERIT") - v("_SC_THREAD_PRIO_PROTECT") - v("_SC_THREAD_PRIORITY_SCHEDULING") - v("_SC_THREAD_PROCESS_SHARED") - v("_SC_THREAD_SAFE_FUNCTIONS") + v("_SC_SYNCHRONIZED_IO") + v("_SC_THREAD_ATTR_STACKADDR") + v("_SC_THREAD_ATTR_STACKSIZE") + v("_SC_THREAD_CPUTIME") + v("_SC_THREAD_DESTRUCTOR_ITERATIONS") + v("_SC_THREAD_KEYS_MAX") + v("_SC_THREAD_PRIO_INHERIT") + v("_SC_THREAD_PRIO_PROTECT") + v("_SC_THREAD_PRIORITY_SCHEDULING") + v("_SC_THREAD_PROCESS_SHARED") + v("_SC_THREAD_SAFE_FUNCTIONS") v("_SC_THREAD_SPORADIC_SERVER") - v("_SC_THREAD_STACK_MIN") - v("_SC_THREAD_THREADS_MAX") + v("_SC_THREAD_STACK_MIN") + v("_SC_THREAD_THREADS_MAX") v("_SC_THREADS") #{.importc: "_SC_THREADS", header: "".}: cint v("_SC_TIMEOUTS") #{.importc: "_SC_TIMEOUTS", header: "".}: cint v("_SC_TIMER_MAX") #{.importc: "_SC_TIMER_MAX", header: "".}: cint v("_SC_TIMERS") #{.importc: "_SC_TIMERS", header: "".}: cint v("_SC_TRACE") #{.importc: "_SC_TRACE", header: "".}: cint - v("_SC_TRACE_EVENT_FILTER") + v("_SC_TRACE_EVENT_FILTER") v("_SC_TRACE_EVENT_NAME_MAX") v("_SC_TRACE_INHERIT") #{.importc: "_SC_TRACE_INHERIT", header: "".}: cint v("_SC_TRACE_LOG") #{.importc: "_SC_TRACE_LOG", header: "".}: cint - v("_SC_TRACE_NAME_MAX") + v("_SC_TRACE_NAME_MAX") v("_SC_TRACE_SYS_MAX") #{.importc: "_SC_TRACE_SYS_MAX", header: "".}: cint - v("_SC_TRACE_USER_EVENT_MAX") + v("_SC_TRACE_USER_EVENT_MAX") v("_SC_TTY_NAME_MAX") #{.importc: "_SC_TTY_NAME_MAX", header: "".}: cint - v("_SC_TYPED_MEMORY_OBJECTS") + v("_SC_TYPED_MEMORY_OBJECTS") v("_SC_TZNAME_MAX") #{.importc: "_SC_TZNAME_MAX", header: "".}: cint - v("_SC_V6_ILP32_OFF32") - v("_SC_V6_ILP32_OFFBIG") + v("_SC_V6_ILP32_OFF32") + v("_SC_V6_ILP32_OFFBIG") v("_SC_V6_LP64_OFF64") #{.importc: "_SC_V6_LP64_OFF64", header: "".}: cint - v("_SC_V6_LPBIG_OFFBIG") + v("_SC_V6_LPBIG_OFFBIG") v("_SC_VERSION") #{.importc: "_SC_VERSION", header: "".}: cint - v("_SC_XBS5_ILP32_OFF32") - v("_SC_XBS5_ILP32_OFFBIG") - v("_SC_XBS5_LP64_OFF64") - v("_SC_XBS5_LPBIG_OFFBIG") + v("_SC_XBS5_ILP32_OFF32") + v("_SC_XBS5_ILP32_OFFBIG") + v("_SC_XBS5_LP64_OFF64") + v("_SC_XBS5_LPBIG_OFFBIG") v("_SC_XOPEN_CRYPT") #{.importc: "_SC_XOPEN_CRYPT", header: "".}: cint - v("_SC_XOPEN_ENH_I18N") + v("_SC_XOPEN_ENH_I18N") v("_SC_XOPEN_LEGACY") #{.importc: "_SC_XOPEN_LEGACY", header: "".}: cint - v("_SC_XOPEN_REALTIME") - v("_SC_XOPEN_REALTIME_THREADS") + v("_SC_XOPEN_REALTIME") + v("_SC_XOPEN_REALTIME_THREADS") v("_SC_XOPEN_SHM") #{.importc: "_SC_XOPEN_SHM", header: "".}: cint v("_SC_XOPEN_STREAMS") #{.importc: "_SC_XOPEN_STREAMS", header: "".}: cint v("_SC_XOPEN_UNIX") #{.importc: "_SC_XOPEN_UNIX", header: "".}: cint @@ -597,7 +597,7 @@ if header(""): if header(""): v("ST_RDONLY") #{.importc, header: .}: cint v("ST_NOSUID") #{.importc, header: "".}: cint - + if header(""): v("PROT_READ") #{.importc, header: .}: cint v("PROT_WRITE") #{.importc, header: "".}: cint @@ -623,31 +623,31 @@ if header(""): v("POSIX_TYPED_MEM_MAP_ALLOCATABLE") #{.importc, header: "".}: cint if header(""): - v("CLOCKS_PER_SEC", clong) + v("CLOCKS_PER_SEC", clong) v("CLOCK_PROCESS_CPUTIME_ID") v("CLOCK_THREAD_CPUTIME_ID") v("CLOCK_REALTIME") - v("TIMER_ABSTIME") - v("CLOCK_MONOTONIC") + v("TIMER_ABSTIME") + v("CLOCK_MONOTONIC") if header(""): v("WNOHANG") #{.importc, header: .}: cint v("WUNTRACED") #{.importc, header: "".}: cint - #v("WEXITSTATUS") - #v("WIFCONTINUED") - #v("WIFEXITED") + #v("WEXITSTATUS") + #v("WIFCONTINUED") + #v("WIFEXITED") #v("WIFSIGNALED") - #v("WIFSTOPPED") - #v("WSTOPSIG") - #v("WTERMSIG") + #v("WIFSTOPPED") + #v("WSTOPSIG") + #v("WTERMSIG") v("WEXITED") #{.importc, header: "".}: cint v("WSTOPPED") #{.importc, header: "".}: cint v("WCONTINUED") #{.importc, header: "".}: cint v("WNOWAIT") #{.importc, header: "".}: cint - v("P_ALL") #{.importc, header: "".}: cint - v("P_PID") #{.importc, header: "".}: cint + v("P_ALL") #{.importc, header: "".}: cint + v("P_PID") #{.importc, header: "".}: cint v("P_PGID") #{.importc, header: "".}: cint - + if header(""): v("SIGEV_NONE") #{.importc, header: "".}: cint v("SIGEV_SIGNAL") #{.importc, header: "".}: cint @@ -776,23 +776,23 @@ if header(""): v("HOST_NOT_FOUND") v("NO_DATA") - v("NO_RECOVERY") - v("TRY_AGAIN") + v("NO_RECOVERY") + v("TRY_AGAIN") - v("AI_PASSIVE") - v("AI_CANONNAME") - v("AI_NUMERICHOST") - v("AI_NUMERICSERV") - v("AI_V4MAPPED") - v("AI_ALL") - v("AI_ADDRCONFIG") + v("AI_PASSIVE") + v("AI_CANONNAME") + v("AI_NUMERICHOST") + v("AI_NUMERICSERV") + v("AI_V4MAPPED") + v("AI_ALL") + v("AI_ADDRCONFIG") - v("NI_NOFQDN") - v("NI_NUMERICHOST") - v("NI_NAMEREQD") - v("NI_NUMERICSERV") - v("NI_NUMERICSCOPE") - v("NI_DGRAM") + v("NI_NOFQDN") + v("NI_NUMERICHOST") + v("NI_NAMEREQD") + v("NI_NUMERICSERV") + v("NI_NUMERICSCOPE") + v("NI_DGRAM") v("EAI_AGAIN") v("EAI_BADFLAGS") v("EAI_FAIL") diff --git a/tools/detect/windows_i386_consts.nim b/tools/detect/windows_i386_consts.nim index cd6c475f4..221251f81 100644 --- a/tools/detect/windows_i386_consts.nim +++ b/tools/detect/windows_i386_consts.nim @@ -1,96 +1,96 @@ -# Generated by detect.nim -const - E2BIG* = cint(7) - EACCES* = cint(13) - EAGAIN* = cint(11) - EBADF* = cint(9) - EBUSY* = cint(16) - ECHILD* = cint(10) - EDEADLK* = cint(36) - EDOM* = cint(33) - EEXIST* = cint(17) - EFAULT* = cint(14) - EFBIG* = cint(27) - EILSEQ* = cint(42) - EINTR* = cint(4) - EINVAL* = cint(22) - EIO* = cint(5) - EISDIR* = cint(21) - EMFILE* = cint(24) - EMLINK* = cint(31) - ENAMETOOLONG* = cint(38) - ENFILE* = cint(23) - ENODEV* = cint(19) - ENOENT* = cint(2) - ENOEXEC* = cint(8) - ENOLCK* = cint(39) - ENOMEM* = cint(12) - ENOSPC* = cint(28) - ENOSYS* = cint(40) - ENOTDIR* = cint(20) - ENOTEMPTY* = cint(41) - ENOTSUP* = cint(48) - ENOTTY* = cint(25) - ENXIO* = cint(6) - EPERM* = cint(1) - EPIPE* = cint(32) - ERANGE* = cint(34) - EROFS* = cint(30) - ESPIPE* = cint(29) - ESRCH* = cint(3) - ETIMEDOUT* = cint(10060) - EXDEV* = cint(18) - O_CREAT* = cint(256) - O_EXCL* = cint(1024) - O_TRUNC* = cint(512) - O_APPEND* = cint(8) - O_ACCMODE* = cint(3) - O_RDONLY* = cint(0) - O_RDWR* = cint(2) - O_WRONLY* = cint(1) - FE_DIVBYZERO* = cint(4) - FE_INEXACT* = cint(32) - FE_INVALID* = cint(1) - FE_OVERFLOW* = cint(8) - FE_UNDERFLOW* = cint(16) - FE_ALL_EXCEPT* = cint(63) - FE_DOWNWARD* = cint(1024) - FE_TONEAREST* = cint(0) - FE_TOWARDZERO* = cint(3072) - FE_UPWARD* = cint(2048) - FE_DFL_ENV* = pointer(nil) - LC_ALL* = cint(0) - LC_COLLATE* = cint(1) - LC_CTYPE* = cint(2) - LC_MONETARY* = cint(3) - LC_NUMERIC* = cint(4) - LC_TIME* = cint(5) - F_OK* = cint(0) - R_OK* = cint(4) - W_OK* = cint(2) - X_OK* = cint(1) - SEEK_SET* = cint(0) - SEEK_CUR* = cint(1) - SEEK_END* = cint(2) - S_IFMT* = cint(61440) - S_IFBLK* = cint(12288) - S_IFCHR* = cint(8192) - S_IFIFO* = cint(4096) - S_IFREG* = cint(32768) - S_IFDIR* = cint(16384) - S_IRWXU* = cint(448) - S_IRUSR* = cint(256) - S_IWUSR* = cint(128) - S_IXUSR* = cint(64) - CLOCKS_PER_SEC* = clong(1000) - SIGABRT* = cint(22) - SIGFPE* = cint(8) - SIGILL* = cint(4) - SIGINT* = cint(2) - SIGSEGV* = cint(11) - SIGTERM* = cint(15) - SIG_BLOCK* = cint(0) - SIG_UNBLOCK* = cint(1) - SIG_SETMASK* = cint(2) - IOFBF* = cint(0) - IONBF* = cint(4) +# Generated by detect.nim +const + E2BIG* = cint(7) + EACCES* = cint(13) + EAGAIN* = cint(11) + EBADF* = cint(9) + EBUSY* = cint(16) + ECHILD* = cint(10) + EDEADLK* = cint(36) + EDOM* = cint(33) + EEXIST* = cint(17) + EFAULT* = cint(14) + EFBIG* = cint(27) + EILSEQ* = cint(42) + EINTR* = cint(4) + EINVAL* = cint(22) + EIO* = cint(5) + EISDIR* = cint(21) + EMFILE* = cint(24) + EMLINK* = cint(31) + ENAMETOOLONG* = cint(38) + ENFILE* = cint(23) + ENODEV* = cint(19) + ENOENT* = cint(2) + ENOEXEC* = cint(8) + ENOLCK* = cint(39) + ENOMEM* = cint(12) + ENOSPC* = cint(28) + ENOSYS* = cint(40) + ENOTDIR* = cint(20) + ENOTEMPTY* = cint(41) + ENOTSUP* = cint(48) + ENOTTY* = cint(25) + ENXIO* = cint(6) + EPERM* = cint(1) + EPIPE* = cint(32) + ERANGE* = cint(34) + EROFS* = cint(30) + ESPIPE* = cint(29) + ESRCH* = cint(3) + ETIMEDOUT* = cint(10060) + EXDEV* = cint(18) + O_CREAT* = cint(256) + O_EXCL* = cint(1024) + O_TRUNC* = cint(512) + O_APPEND* = cint(8) + O_ACCMODE* = cint(3) + O_RDONLY* = cint(0) + O_RDWR* = cint(2) + O_WRONLY* = cint(1) + FE_DIVBYZERO* = cint(4) + FE_INEXACT* = cint(32) + FE_INVALID* = cint(1) + FE_OVERFLOW* = cint(8) + FE_UNDERFLOW* = cint(16) + FE_ALL_EXCEPT* = cint(63) + FE_DOWNWARD* = cint(1024) + FE_TONEAREST* = cint(0) + FE_TOWARDZERO* = cint(3072) + FE_UPWARD* = cint(2048) + FE_DFL_ENV* = pointer(nil) + LC_ALL* = cint(0) + LC_COLLATE* = cint(1) + LC_CTYPE* = cint(2) + LC_MONETARY* = cint(3) + LC_NUMERIC* = cint(4) + LC_TIME* = cint(5) + F_OK* = cint(0) + R_OK* = cint(4) + W_OK* = cint(2) + X_OK* = cint(1) + SEEK_SET* = cint(0) + SEEK_CUR* = cint(1) + SEEK_END* = cint(2) + S_IFMT* = cint(61440) + S_IFBLK* = cint(12288) + S_IFCHR* = cint(8192) + S_IFIFO* = cint(4096) + S_IFREG* = cint(32768) + S_IFDIR* = cint(16384) + S_IRWXU* = cint(448) + S_IRUSR* = cint(256) + S_IWUSR* = cint(128) + S_IXUSR* = cint(64) + CLOCKS_PER_SEC* = clong(1000) + SIGABRT* = cint(22) + SIGFPE* = cint(8) + SIGILL* = cint(4) + SIGINT* = cint(2) + SIGSEGV* = cint(11) + SIGTERM* = cint(15) + SIG_BLOCK* = cint(0) + SIG_UNBLOCK* = cint(1) + SIG_SETMASK* = cint(2) + IOFBF* = cint(0) + IONBF* = cint(4) diff --git a/tools/fakedeps.nim b/tools/fakedeps.nim index 80623fafb..6963579dc 100644 --- a/tools/fakedeps.nim +++ b/tools/fakedeps.nim @@ -15,4 +15,4 @@ proc fakedeps() = proc main = fakedeps() when isMainModule: - main() \ No newline at end of file + main() diff --git a/tools/niminst/debcreation.nim b/tools/niminst/debcreation.nim index bbd997981..36b2a29ec 100644 --- a/tools/niminst/debcreation.nim +++ b/tools/niminst/debcreation.nim @@ -38,33 +38,33 @@ proc createControl(pkgName, maintainer, shortDesc, desc: string, ## Multiple dependencies should be separated by commas. ## pkgDepends: Same as buildDepends except that this specifies the ## dependencies that the compiled application depends on. - - + + result = "" - + addN("Source: " & pkgName) addN("Maintainer: " & maintainer) addN("Section: misc") addN("Priority: optional") addN("Standards-Version: 3.9.2") - addN("Build-Depends: debhelper (>= 8)" & + addN("Build-Depends: debhelper (>= 8)" & (if buildDepends != "": ", " & buildDepends else: "")) addN("\n") addN("Package: " & pkgName) addN("Architecture: any") addN("Depends: ${shlibs:Depends}, ${misc:Depends}" & (if pkgDepends != "": ", " & pkgDepends else: "")) - + var formattedDesc = "" for line in splitLines(desc): if line == "": formattedDesc.add(" .\n") else: formattedDesc.add(" " & line & "\n") - + addN("Description: " & shortDesc & "\n" & formattedDesc) -proc createCopyright(pkgName, mtnName, mtnEmail, version: string, +proc createCopyright(pkgName, mtnName, mtnEmail, version: string, licenses: seq[tuple[files, license: string]]): string = ## pkgName: Package name ## mtnName: Maintainer name @@ -73,7 +73,7 @@ proc createCopyright(pkgName, mtnName, mtnEmail, version: string, ## licenses: files: This specifies the files that the `license` covers, ## for example, it might be ``lib/*`` to cover the whole ``lib`` dir ## license: This specifies the license, for example gpl2, or lgpl. - + result = "" addN("Maintainer name: " & mtnName) addN("Email-Address: " & mtnEmail) @@ -86,7 +86,7 @@ proc createCopyright(pkgName, mtnName, mtnEmail, version: string, proc formatDateTime(t: TimeInfo, timezone: string): string = var day = ($t.weekday)[0..2] & ", " - + return "$1$2 $3 $4 $5:$6:$7 $8" % [day, intToStr(t.monthday, 2), ($t.month)[0..2], $t.year, intToStr(t.hour, 2), intToStr(t.minute, 2), intToStr(t.second, 2), timezone] @@ -147,41 +147,41 @@ proc prepDeb*(packName, version, mtnName, mtnEmail, shortDesc, desc: string, buildDepends, pkgDepends = "") = ## binaries/config/docs/lib: files relative to nim's root, that need to ## be installed. - + let pkgName = packName.toLower() - + var workingDir = getTempDir() / "niminst" / "deb" var upstreamSource = (pkgName & "-" & version) - + echo("Making sure build.sh and install.sh are +x") - assertSuccess execCmd("chmod +x \"" & + assertSuccess execCmd("chmod +x \"" & (workingDir / upstreamSource / "build.sh") & "\"") - assertSuccess execCmd("chmod +x \"" & + assertSuccess execCmd("chmod +x \"" & (workingDir / upstreamSource / "install.sh") & "\"") - - var tarCmd = "tar pczf \"" & + + var tarCmd = "tar pczf \"" & (pkgName & "_" & version & ".orig.tar.gz") & - "\" \"" & upstreamSource & "\"" + "\" \"" & upstreamSource & "\"" echo(tarCmd) assertSuccess execCmd("cd \"" & workingDir & "\" && " & tarCmd) - + echo("Creating necessary files in debian/") createDir(workingDir / upstreamSource / "debian") - + template writeDebian(f, s: string): expr = writeFile(workingDir / upstreamSource / "debian" / f, s) - + var controlFile = createControl(pkgName, makeMtn(mtnName, mtnEmail), shortDesc, desc, buildDepends, pkgDepends) echo("debian/control") writeDebian("control", controlFile) - + var copyrightFile = createCopyright(pkgName, mtnName, mtnEmail, version, licenses) echo("debian/copyright") writeDebian("copyright", copyrightFile) - var changelogFile = createChangelog(pkgName, version, + var changelogFile = createChangelog(pkgName, version, makeMtn(mtnName, mtnEmail)) echo("debian/changelog") writeDebian("changelog", changelogFile) @@ -206,7 +206,7 @@ proc prepDeb*(packName, version, mtnName, mtnEmail, shortDesc, desc: string, createIncludeBinaries(binaries)) echo("All done, you can now build.") - echo("Before you do however, make sure the files in " & + echo("Before you do however, make sure the files in " & workingDir / upstreamSource / "debian" & " are correct.") echo("Change your directory to: " & workingDir / upstreamSource) echo("And execute `debuild -us -uc` to build the .deb") @@ -214,22 +214,22 @@ proc prepDeb*(packName, version, mtnName, mtnEmail, shortDesc, desc: string, when isMainModule: #var controlFile = createControl("nim", "Dominik Picheta ", # "The Nim compiler", "Compiler for the Nim programming language", "gcc (>= 4:4.3.2)", "gcc (>= 4:4.3.2)") - + #echo(controlFile) - + #var copyrightFile = createCopyright("nim", "Dominik Picheta", "morfeusz8@a.b", "0.8.14", # @[("bin/nim", "gpl2"), ("lib/*", "lgpl")]) - + #echo copyrightFile - + #var changelogFile = createChangelog("nim", "0.8.14", "Dom P ") #echo(changelogFile) - + #echo(createRules()) - prepDeb("nim", "0.9.2", "Dominik Picheta", "morfeusz8@gmail.com", + prepDeb("nim", "0.9.2", "Dominik Picheta", "morfeusz8@gmail.com", "The Nim compiler", "Compiler for the Nim programming language", - @[("bin/nim", "MIT"), ("lib/*", "MIT")], + @[("bin/nim", "MIT"), ("lib/*", "MIT")], @["bin/nim"], @["config/*"], @["doc/*"], @["lib/*"], "gcc (>= 4:4.3.2)", "gcc (>= 4:4.3.2)") diff --git a/tools/noprefix.nim b/tools/noprefix.nim index fe03a9efc..d16c2b520 100644 --- a/tools/noprefix.nim +++ b/tools/noprefix.nim @@ -13,12 +13,12 @@ const ("sdl/sdl_mixer", "sdl"), ("sdl/sdl_ttf", "sdl"), ("sdl/smpeg", "sdl"), - + ("libcurl", "curl"), ("mysql", "mysql"), ("postgres", ""), ("sqlite3", "sqlite3"), - + ("pcre/pcre", "pcre") ] diff --git a/tools/restorecc.nim b/tools/restorecc.nim index f5d8f0bb3..ff95427d8 100644 --- a/tools/restorecc.nim +++ b/tools/restorecc.nim @@ -1,16 +1,16 @@ import os, strutils -proc main(dir: string, wanted: string) = - for kind, path in walkDir(dir): - case kind +proc main(dir: string, wanted: string) = + for kind, path in walkDir(dir): + case kind of pcFile: let name = extractFilename(path) if name == wanted: let newLoc = path.replace("mingw_backup", "mingw") echo "creating ", newLoc - copyFile(path, newLoc) - of pcDir: main(path, wanted) - else: discard + copyFile(path, newLoc) + of pcDir: main(path, wanted) + else: discard main("dist/mingw_backup", paramStr(1)) From e80465dacf50f260abec30ae57d37b298c93fd83 Mon Sep 17 00:00:00 2001 From: Adam Strzelecki Date: Fri, 4 Sep 2015 23:04:32 +0200 Subject: [PATCH 0900/1263] tests: Trim .nim files trailing whitespace via OSX: find . -name '*.nim' -exec sed -i '' -E 's/[[:space:]]+$//' {} + --- tests/actiontable/tactiontable.nim | 14 +- tests/alias/talias.nim | 14 +- tests/ambsym/mambsym1.nim | 20 +- tests/ambsym/mambsym2.nim | 6 +- tests/ambsym/mambsys1.nim | 14 +- tests/ambsym/mambsys2.nim | 8 +- tests/ambsym/tambsym.nim | 16 +- tests/ambsym/tambsym2.nim | 4 +- tests/ambsym/tambsym3.nim | 16 +- tests/array/tarray.nim | 54 +- tests/array/tarray2.nim | 2 +- tests/array/tarray3.nim | 4 +- tests/array/tarraycons.nim | 2 +- tests/array/tarraycons2.nim | 2 +- tests/array/tarrayplus.nim | 2 +- tests/array/tarrindx.nim | 26 +- tests/assert/tuserassert.nim | 4 +- tests/assign/tassign.nim | 62 +- tests/assign/tgenericassign.nim | 2 +- tests/assign/tgenericassigntuples.nim | 2 +- tests/assign/tobjasgn.nim | 2 +- tests/async/tasyncawait.nim | 2 +- tests/async/tasynceverror.nim | 2 +- tests/async/tasyncfile.nim | 6 +- tests/async/tasynciossl.nim | 4 +- tests/async/tasyncudp.nim | 10 +- tests/benchmark.nim | 2 +- tests/benchmarks/fannkuch.nim | 6 +- tests/benchmarks/quicksort.nim | 2 +- tests/bind/mbind3.nim | 2 +- tests/bind/tbind1.nim | 8 +- tests/bind/tbind2.nim | 2 +- tests/bind/tdatabind.nim | 12 +- tests/borrow/tborrow.nim | 4 +- tests/casestmt/tcaseoverlaprange.nim | 4 +- tests/casestmt/tcaseoverlaprange2.nim | 2 +- tests/casestmt/tcasestm.nim | 2 +- tests/casestmt/tlinearscanend.nim | 8 +- tests/ccgbugs/tccgen1.nim | 22 +- tests/ccgbugs/tcgbug.nim | 2 +- tests/ccgbugs/tcodegenbug1.nim | 4 +- tests/closure/tclosure.nim | 2 +- tests/closure/tclosure2.nim | 16 +- tests/closure/tclosure3.nim | 2 +- tests/closure/tclosurebug2.nim | 12 +- tests/closure/tinterf.nim | 4 +- tests/closure/tinvalidclosure2.nim | 4 +- tests/closure/tjester.nim | 2 +- tests/closure/tnestedclosure.nim | 2 +- tests/closure/tnestedproc.nim | 4 +- tests/closure/uclosures.nim | 2 +- tests/cnstseq/tcnstseq.nim | 4 +- tests/cnstseq/tcnstseq2.nim | 4 +- tests/collections/tindexby.nim | 4 +- tests/collections/ttableconstr.nim | 2 +- tests/constr/tconstr1.nim | 46 +- tests/constr/tconstr2.nim | 40 +- tests/constraints/tconstraints.nim | 2 +- tests/controlflow/tblock1.nim | 22 +- tests/controlflow/tcontinue.nim | 4 +- tests/controlflow/tnestif.nim | 36 +- tests/controlflow/tstatret.nim | 10 +- tests/converter/ttypeconverter1.nim | 2 +- tests/cpp/tthread_createthread.nim | 2 +- tests/dir with space/tspace.nim | 2 +- tests/discard/tdiscardable.nim | 4 +- tests/discard/tneedsdiscard.nim | 4 +- tests/distinct/tcurrncy.nim | 4 +- tests/dll/client.nim | 6 +- tests/dll/server.nim | 10 +- tests/effects/teffects1.nim | 6 +- tests/effects/teffects2.nim | 4 +- tests/effects/teffects3.nim | 4 +- tests/effects/teffects4.nim | 4 +- tests/effects/teffects5.nim | 2 +- tests/effects/teffects6.nim | 4 +- tests/effects/tsidee1.nim | 4 +- tests/effects/tsidee2.nim | 4 +- tests/effects/tsidee3.nim | 4 +- tests/effects/tsidee4.nim | 4 +- tests/enum/tenum.nim | 16 +- tests/enum/tenum2.nim | 6 +- tests/enum/tenum3.nim | 6 +- tests/enum/tenumhole.nim | 4 +- tests/enum/tenummix.nim | 2 +- tests/enum/toptions.nim | 36 +- tests/exception/tcontinuexc.nim | 2 +- tests/exception/tfinally.nim | 4 +- tests/exception/tfinally2.nim | 6 +- tests/exception/tfinally3.nim | 2 +- tests/exception/tnestedreturn2.nim | 2 +- tests/exception/tunhandledexc.nim | 2 +- tests/exception/twrongexc.nim | 2 +- tests/exprs/tstmtexprs.nim | 8 +- tests/fields/tfieldindex.nim | 2 +- tests/fields/tfielditerator.nim | 2 +- tests/fields/tfielditerator2.nim | 4 +- tests/float/tfloat3.nim | 2 +- tests/friends/mfriends.nim | 6 +- tests/gc/closureleak.nim | 4 +- tests/gc/gcbench.nim | 330 +-- tests/gc/gcleak2.nim | 2 +- tests/gc/gcleak4.nim | 4 +- tests/gc/gcleak5.nim | 4 +- tests/gc/refarrayleak.nim | 2 +- tests/generics/t1056.nim | 2 +- tests/generics/t1789.nim | 2 +- tests/generics/tconfusing_arrow.nim | 2 +- tests/generics/tdictdestruct.nim | 4 +- tests/generics/texplicitgeneric1.nim | 24 +- tests/generics/texplicitgeneric2.nim | 22 +- tests/generics/tgeneric1.nim | 4 +- tests/generics/tgenericdefaults.nim | 4 +- tests/generics/tgenericmatcher.nim | 2 +- tests/generics/tgenericmatcher2.nim | 2 +- tests/generics/tgenericrefs.nim | 8 +- tests/generics/tgenericshardcases.nim | 4 +- tests/generics/tgenericvariant.nim | 2 +- tests/generics/tinferredgenericprocs.nim | 2 +- tests/generics/tthread_generic.nim | 4 +- tests/generics/twrong_field_caching.nim | 10 +- tests/generics/twrong_floatlit_type.nim | 46 +- tests/global/globalaux.nim | 2 +- tests/init/tuninit1.nim | 8 +- tests/iter/tcountup.nim | 6 +- tests/iter/titer.nim | 88 +- tests/iter/titer6.nim | 8 +- tests/iter/titer8.nim | 4 +- tests/iter/titer_no_tuple_unpack.nim | 14 +- tests/js.nim | 2 +- tests/js/test2.nim | 4 +- tests/lexer/thexlit.nim | 2 +- tests/lexer/thexrange.nim | 2 +- tests/lexer/tident.nim | 18 +- tests/lexer/tind1.nim | 2 +- tests/lexer/tlexer.nim | 120 +- tests/lexer/tstrlits.nim | 4 +- tests/lexer/tunderscores.nim | 2 +- tests/lookups/tkoeniglookup.nim | 2 +- tests/lookups/tredef.nim | 4 +- tests/macros/tclosuremacro.nim | 2 +- tests/macros/tmacro2.nim | 4 +- tests/macros/tmacrogenerics.nim | 2 +- tests/macros/tmacrostmt.nim | 2 +- tests/macros/tprintf.nim | 20 +- tests/macros/tquotewords.nim | 4 +- tests/macros/tstaticparamsmacro.nim | 4 +- tests/macros/tvtable.nim | 2 +- tests/magics/tlowhigh.nim | 36 +- .../dependencies/chipmunk/chipmunk.nim | 336 +-- .../keineschweine/dependencies/enet/enet.nim | 226 +- .../dependencies/enet/testserver.nim | 12 +- .../dependencies/genpacket/streams_enh.nim | 12 +- .../keineschweine/dependencies/nake/nake.nim | 8 +- .../keineschweine/dependencies/sfml/sfml.nim | 76 +- .../dependencies/sfml/sfml_audio.nim | 24 +- .../dependencies/sfml/sfml_colors.nim | 2 +- .../keineschweine/enet_server/enet_client.nim | 30 +- .../keineschweine/enet_server/enet_server.nim | 86 +- .../enet_server/server_utils.nim | 10 +- tests/manyloc/keineschweine/keineschweine.nim | 110 +- .../keineschweine/lib/client_helpers.nim | 10 +- tests/manyloc/keineschweine/lib/estreams.nim | 8 +- tests/manyloc/keineschweine/lib/gl.nim | 346 +-- tests/manyloc/keineschweine/lib/glext.nim | 2334 ++++++++--------- tests/manyloc/keineschweine/lib/glu.nim | 134 +- tests/manyloc/keineschweine/lib/glut.nim | 140 +- tests/manyloc/keineschweine/lib/glx.nim | 60 +- tests/manyloc/keineschweine/lib/idgen.nim | 2 +- .../keineschweine/lib/input_helpers.nim | 24 +- .../manyloc/keineschweine/lib/map_filter.nim | 6 +- .../keineschweine/lib/math_helpers.nim | 2 +- .../manyloc/keineschweine/lib/sfml_stuff.nim | 2 +- tests/manyloc/keineschweine/lib/sg_assets.nim | 70 +- tests/manyloc/keineschweine/lib/sg_gui.nim | 34 +- .../manyloc/keineschweine/lib/sg_packets.nim | 10 +- tests/manyloc/keineschweine/lib/vehicles.nim | 2 +- tests/manyloc/keineschweine/lib/wingl.nim | 148 +- .../keineschweine/lib/zlib_helpers.nim | 4 +- .../keineschweine/server/old_dirserver.nim | 16 +- .../keineschweine/server/old_server_utils.nim | 4 +- .../keineschweine/server/old_sg_server.nim | 56 +- .../manyloc/keineschweine/server/sg_lobby.nim | 48 +- tests/manyloc/nake/nake.nim | 8 +- tests/manyloc/nake/nakefile.nim | 14 +- tests/metatype/tbindtypedesc.nim | 4 +- tests/metatype/tconstraints.nim | 2 +- tests/metatype/tmatrix.nim | 4 +- tests/metatype/tmatrix1.nim | 4 +- tests/metatype/tmatrix2.nim | 4 +- tests/metatype/tstaticparammacro.nim | 4 +- tests/metatype/tstaticparams.nim | 4 +- tests/metatype/ttypedesc1.nim | 10 +- tests/metatype/ttypeselectors.nim | 2 +- tests/metatype/ttypetraits.nim | 6 +- tests/method/tmethods1.nim | 2 +- tests/method/tmultim1.nim | 4 +- tests/method/tmultim2.nim | 4 +- tests/method/tmultim4.nim | 2 +- tests/method/tmultim6.nim | 4 +- tests/misc/minit.nim | 4 +- tests/misc/mvarious.nim | 12 +- tests/misc/t99bott.nim | 2 +- tests/misc/tack.nim | 30 +- tests/misc/tatomic.nim | 4 +- tests/misc/tcolonisproc.nim | 2 +- tests/misc/tdllvar.nim | 2 +- tests/misc/temit.nim | 4 +- tests/misc/teventemitter.nim | 6 +- tests/misc/tevents.nim | 4 +- tests/misc/tfib.nim | 4 +- tests/misc/tgetstartmilsecs.nim | 2 +- tests/misc/theaproots.nim | 6 +- tests/misc/thintoff.nim | 2 +- tests/misc/tinit.nim | 12 +- tests/misc/tinout.nim | 18 +- tests/misc/tinvalidnewseq.nim | 8 +- tests/misc/tlastmod.nim | 36 +- tests/misc/tlocals.nim | 4 +- tests/misc/tloops.nim | 2 +- tests/misc/tmissingnilcheck.nim | 2 +- tests/misc/tnew.nim | 98 +- tests/misc/tnewderef.nim | 2 +- tests/misc/tnewsets.nim | 12 +- tests/misc/tnewuns.nim | 24 +- tests/misc/tnoinst.nim | 2 +- tests/misc/tnot.nim | 4 +- tests/misc/tparedef.nim | 8 +- tests/misc/tpos.nim | 58 +- tests/misc/tquicksort.nim | 8 +- tests/misc/tradix.nim | 168 +- tests/misc/trawstr.nim | 10 +- tests/misc/tromans.nim | 6 +- tests/misc/tsimplesort.nim | 6 +- tests/misc/tsimtych.nim | 10 +- tests/misc/tsizeof.nim | 20 +- tests/misc/tsortdev.nim | 8 +- tests/misc/tstrace.nim | 32 +- tests/misc/tstrange.nim | 34 +- tests/misc/tstrdesc.nim | 28 +- tests/misc/tvarious1.nim | 6 +- tests/mmaptest.nim | 18 +- tests/modules/mnamspc1.nim | 4 +- tests/modules/mnamspc2.nim | 6 +- tests/modules/mopaque.nim | 10 +- tests/modules/mrecmod.nim | 2 +- tests/modules/mrecmod2.nim | 4 +- tests/modules/texport.nim | 2 +- tests/modules/tnamspc.nim | 10 +- tests/modules/trecmod.nim | 4 +- tests/namedparams/tnamedparams.nim | 6 +- tests/namedparams/tnamedparams2.nim | 6 +- tests/notnil/tnotnil.nim | 2 +- tests/notnil/tnotnil1.nim | 4 +- tests/notnil/tnotnil_in_generic.nim | 6 +- tests/objects/tobjcov.nim | 4 +- tests/objects/tobject.nim | 2 +- tests/objects/tobject3.nim | 2 +- tests/objects/tobjects.nim | 2 +- tests/objects/tobjpragma.nim | 10 +- tests/objects/tofopr.nim | 8 +- tests/objects/toop.nim | 6 +- tests/objvariant/tcheckedfield1.nim | 4 +- tests/osproc/ta.nim | 2 +- tests/overflw/tovfint.nim | 34 +- tests/overload/toverl2.nim | 6 +- tests/overload/toverl3.nim | 6 +- tests/overload/toverl4.nim | 2 +- tests/overload/toverwr.nim | 26 +- tests/parallel/treadafterwrite.nim | 2 +- tests/parallel/tuseafterdef.nim | 4 +- tests/parser/tdomulttest.nim | 2 +- tests/parser/tinvwhen.nim | 16 +- tests/parser/toprprec.nim | 8 +- tests/pragmas/tpush.nim | 30 +- tests/proc/tnestprc.nim | 8 +- tests/procvar/tprocvar.nim | 2 +- tests/procvar/tprocvar2.nim | 28 +- tests/range/tbug499771.nim | 4 +- tests/range/tcolors.nim | 28 +- tests/range/tmatrix3.nim | 8 +- tests/range/tsubrange.nim | 6 +- tests/range/tsubrange2.nim | 6 +- tests/range/tsubrange3.nim | 4 +- tests/rectest.nim | 12 +- tests/rodfiles/amethods.nim | 2 +- tests/rodfiles/bmethods.nim | 2 +- tests/rodfiles/bmethods2.nim | 2 +- tests/rodfiles/deadg.nim | 4 +- tests/rodfiles/gtkex1.nim | 28 +- tests/rodfiles/gtkex2.nim | 8 +- tests/rodfiles/hallo2.nim | 2 +- tests/seq/tseq2.nim | 4 +- tests/seq/tseqcon.nim | 90 +- tests/seq/tseqtuple.nim | 2 +- tests/seq/ttoseq.nim | 4 +- tests/sets/tsets.nim | 408 +-- tests/sets/tsets2.nim | 10 +- tests/showoff/thtml1.nim | 2 +- tests/stckovfl.nim | 4 +- tests/stdlib/nre/captures.nim | 2 +- tests/stdlib/talgorithm.nim | 2 +- tests/stdlib/tcritbits.nim | 2 +- tests/stdlib/tformat.nim | 12 +- tests/stdlib/tio.nim | 14 +- tests/stdlib/tlists.nim | 12 +- tests/stdlib/tmarshal.nim | 2 +- tests/stdlib/tmath.nim | 6 +- tests/stdlib/tmath2.nim | 170 +- tests/stdlib/tos.nim | 4 +- tests/stdlib/tosprocterminate.nim | 2 +- tests/stdlib/tparscfg.nim | 4 +- tests/stdlib/tquit.nim | 12 +- tests/stdlib/tregex.nim | 40 +- tests/stdlib/treguse.nim | 42 +- tests/stdlib/trepr.nim | 2 +- tests/stdlib/trepr2.nim | 64 +- tests/stdlib/tsplit.nim | 2 +- tests/stdlib/tstrset.nim | 6 +- tests/stdlib/tstrtabs.nim | 2 +- tests/stdlib/ttime.nim | 12 +- tests/stdlib/twalker.nim | 26 +- tests/system/io.nim | 2 +- tests/template/annotate.nim | 2 +- tests/template/mtempl5.nim | 6 +- tests/template/otests.nim | 438 ++-- tests/template/thygienictempl.nim | 4 +- tests/template/tmodulealias.nim | 4 +- tests/template/tstempl.nim | 2 +- tests/template/ttempl.nim | 4 +- tests/template/ttempl3.nim | 12 +- tests/template/twrongopensymchoice.nim | 6 +- tests/testament/backend.nim | 20 +- tests/testament/tester.nim | 4 +- tests/threads/tactors2.nim | 2 +- tests/threads/threadex.nim | 2 +- tests/threads/tthreadanalysis.nim | 4 +- tests/threads/tthreadanalysis2.nim | 4 +- tests/threads/tthreadheapviolation1.nim | 2 +- tests/threads/ttryrecv.nim | 2 +- tests/trmacros/tcse.nim | 2 +- tests/trmacros/tmatrix.nim | 2 +- tests/trmacros/tstar.nim | 2 +- tests/typerel/tno_int_in_bool_context.nim | 4 +- tests/typerel/trectuples.nim | 2 +- tests/typerel/trefs.nim | 32 +- tests/typerel/tregionptrs.nim | 2 +- tests/typerel/tregionptrs2.nim | 4 +- tests/typerel/tsecondarrayproperty.nim | 2 +- tests/typerel/ttuple1.nim | 2 +- tests/typerel/ttypenoval.nim | 4 +- tests/typerel/tvoid.nim | 4 +- tests/typerel/typalias.nim | 6 +- tests/types/tfinalobj.nim | 4 +- tests/types/tforwty.nim | 18 +- tests/types/tforwty2.nim | 44 +- tests/types/tillegaltyperecursion.nim | 16 +- tests/types/tinheritref.nim | 2 +- tests/types/tisop.nim | 2 +- tests/varres/tvarres1.nim | 4 +- tests/varres/tvarres2.nim | 4 +- tests/varres/tvarres3.nim | 4 +- tests/varres/tvartup.nim | 2 +- tests/varstmt/tlet.nim | 2 +- tests/varstmt/tvardecl.nim | 18 +- tests/vm/tarrayboundeval.nim | 4 +- tests/vm/tasmparser.nim | 12 +- tests/vm/tconsteval.nim | 2 +- tests/vm/teval1.nim | 2 +- tests/vm/tldconst.nim | 2 +- tests/vm/trgba.nim | 26 +- tests/vm/tslurp.nim | 2 +- 372 files changed, 4486 insertions(+), 4486 deletions(-) diff --git a/tests/actiontable/tactiontable.nim b/tests/actiontable/tactiontable.nim index e2f19a099..18b0fd388 100644 --- a/tests/actiontable/tactiontable.nim +++ b/tests/actiontable/tactiontable.nim @@ -4,23 +4,23 @@ discard """ import tables -proc action1(arg: string) = +proc action1(arg: string) = echo "action 1 ", arg -proc action2(arg: string) = +proc action2(arg: string) = echo "action 2 ", arg -proc action3(arg: string) = +proc action3(arg: string) = echo "action 3 ", arg -proc action4(arg: string) = +proc action4(arg: string) = echo "action 4 ", arg var actionTable = { - "A": action1, - "B": action2, - "C": action3, + "A": action1, + "B": action2, + "C": action3, "D": action4}.toTable actionTable["C"]("arg") diff --git a/tests/alias/talias.nim b/tests/alias/talias.nim index 819289c2e..6addc4704 100644 --- a/tests/alias/talias.nim +++ b/tests/alias/talias.nim @@ -6,7 +6,7 @@ type proc isPartOf*[S, T](a: S, b: T): TAnalysisResult {. magic: "IsPartOf", noSideEffect.} - ## not yet exported properly. + ## not yet exported properly. template compileTimeAssert(cond: expr) = when not cond: @@ -35,30 +35,30 @@ proc p(param1, param2: TC): TC = local: TC plocal: ptr TC plocal2: ptr TA - + local.arr <| local local.arr[0] <| local local.arr[2] !<| local.arr[1] - + plocal2[] ?<| local param1 ?<| param2 - + local.arr[0] !<| param1 local.arr !<| param1 local.le[] ?<| param1 - + param1 !<| local.arr[0] param1 !<| local.arr param1 ?<| local.le[] - + result !<| local result <| result var a, b: int x: TC - + a <| a a !<| b diff --git a/tests/ambsym/mambsym1.nim b/tests/ambsym/mambsym1.nim index d9d57b5e5..c4902b1b4 100644 --- a/tests/ambsym/mambsym1.nim +++ b/tests/ambsym/mambsym1.nim @@ -1,10 +1,10 @@ -import mambsym2 # import TExport - -type - TExport* = enum x, y, z - TOtherEnum* = enum mDec, mInc, mAssign - -proc ha() = - var - x: TExport # no error - discard +import mambsym2 # import TExport + +type + TExport* = enum x, y, z + TOtherEnum* = enum mDec, mInc, mAssign + +proc ha() = + var + x: TExport # no error + discard diff --git a/tests/ambsym/mambsym2.nim b/tests/ambsym/mambsym2.nim index eac8de6ba..21d980073 100644 --- a/tests/ambsym/mambsym2.nim +++ b/tests/ambsym/mambsym2.nim @@ -1,3 +1,3 @@ -type - TExport* = enum a, b, c - +type + TExport* = enum a, b, c + diff --git a/tests/ambsym/mambsys1.nim b/tests/ambsym/mambsys1.nim index 04f9561d3..22e54cb94 100644 --- a/tests/ambsym/mambsys1.nim +++ b/tests/ambsym/mambsys1.nim @@ -1,7 +1,7 @@ -import mambsys2 # import TExport - -type - TExport* = enum x, y, z - -proc foo*(x: int) = - discard +import mambsys2 # import TExport + +type + TExport* = enum x, y, z + +proc foo*(x: int) = + discard diff --git a/tests/ambsym/mambsys2.nim b/tests/ambsym/mambsys2.nim index d59706865..ef63e4f7e 100644 --- a/tests/ambsym/mambsys2.nim +++ b/tests/ambsym/mambsys2.nim @@ -1,4 +1,4 @@ -type - TExport* = enum x, y, z # exactly the same type! - -proc foo*(x: int) = discard +type + TExport* = enum x, y, z # exactly the same type! + +proc foo*(x: int) = discard diff --git a/tests/ambsym/tambsym.nim b/tests/ambsym/tambsym.nim index 902274648..d9115e16d 100644 --- a/tests/ambsym/tambsym.nim +++ b/tests/ambsym/tambsym.nim @@ -3,13 +3,13 @@ discard """ line: 11 errormsg: "ambiguous identifier" """ -# Test ambiguous symbols - -import mambsym1, mambsym2 - -var - v: TExport #ERROR_MSG ambiguous identifier - -v = y +# Test ambiguous symbols + +import mambsym1, mambsym2 + +var + v: TExport #ERROR_MSG ambiguous identifier + +v = y diff --git a/tests/ambsym/tambsym2.nim b/tests/ambsym/tambsym2.nim index c3b997549..8e288e73a 100644 --- a/tests/ambsym/tambsym2.nim +++ b/tests/ambsym/tambsym2.nim @@ -8,12 +8,12 @@ type TMyType = object len: int data: string - + proc len(x: TMyType): int {.inline.} = return x.len proc x(s: TMyType, len: int) = writeLine(stdout, len(s)) - + var m: TMyType m.len = 7 diff --git a/tests/ambsym/tambsym3.nim b/tests/ambsym/tambsym3.nim index ed8a3058a..b25dadfd6 100644 --- a/tests/ambsym/tambsym3.nim +++ b/tests/ambsym/tambsym3.nim @@ -3,13 +3,13 @@ discard """ line: 11 errormsg: "ambiguous identifier" """ -# Test ambiguous symbols - -import mambsym1, times - -var - v = mDec #ERROR_MSG ambiguous identifier - -writeLine(stdout, ord(v)) +# Test ambiguous symbols + +import mambsym1, times + +var + v = mDec #ERROR_MSG ambiguous identifier + +writeLine(stdout, ord(v)) diff --git a/tests/array/tarray.nim b/tests/array/tarray.nim index 01fbdf422..9cfb758e2 100644 --- a/tests/array/tarray.nim +++ b/tests/array/tarray.nim @@ -2,33 +2,33 @@ discard """ file: "tarray.nim" output: "100124" """ -# simple check for one dimensional arrays - -type - TMyArray = array[0..2, int] - TMyRecord = tuple[x, y: int] - -proc sum(a: TMyarray): int = - result = 0 - var i = 0 - while i < len(a): - inc(result, a[i]) - inc(i) - -proc sum(a: openarray[int]): int = - result = 0 - var i = 0 - while i < len(a): - inc(result, a[i]) - inc(i) - -proc getPos(r: TMyRecord): int = - result = r.x + r.y - -write(stdout, sum([1, 2, 3, 4])) -write(stdout, sum([])) -write(stdout, getPos( (x: 5, y: 7) )) -#OUT 10012 +# simple check for one dimensional arrays + +type + TMyArray = array[0..2, int] + TMyRecord = tuple[x, y: int] + +proc sum(a: TMyarray): int = + result = 0 + var i = 0 + while i < len(a): + inc(result, a[i]) + inc(i) + +proc sum(a: openarray[int]): int = + result = 0 + var i = 0 + while i < len(a): + inc(result, a[i]) + inc(i) + +proc getPos(r: TMyRecord): int = + result = r.x + r.y + +write(stdout, sum([1, 2, 3, 4])) +write(stdout, sum([])) +write(stdout, getPos( (x: 5, y: 7) )) +#OUT 10012 # bug #1669 let filesToCreate = ["tempdir/fl1.a", "tempdir/fl2.b", diff --git a/tests/array/tarray2.nim b/tests/array/tarray2.nim index b6adabb45..1951e6e97 100644 --- a/tests/array/tarray2.nim +++ b/tests/array/tarray2.nim @@ -9,7 +9,7 @@ type TObj = object arr: TMyarray - + proc mul(a, b: TMyarray): TMyArray = result = a for i in 0..len(a)-1: diff --git a/tests/array/tarray3.nim b/tests/array/tarray3.nim index d28778357..24bf26fda 100644 --- a/tests/array/tarray3.nim +++ b/tests/array/tarray3.nim @@ -2,9 +2,9 @@ discard """ file: "tarray3.nim" output: "3" """ -# simple check for two dimensional arrays +# simple check for two dimensional arrays -const +const myData = [[1,2,3], [4, 5, 6]] echo myData[0][2] #OUT 3 diff --git a/tests/array/tarraycons.nim b/tests/array/tarraycons.nim index 7de518b6e..9f09fd405 100644 --- a/tests/array/tarraycons.nim +++ b/tests/array/tarraycons.nim @@ -7,7 +7,7 @@ discard """ type TEnum = enum eA, eB, eC, eD, eE, eF - + const myMapping: array[TEnum, array[0..1, int]] = [ eA: [1, 2], diff --git a/tests/array/tarraycons2.nim b/tests/array/tarraycons2.nim index 0b2a42c2f..72d9e374e 100644 --- a/tests/array/tarraycons2.nim +++ b/tests/array/tarraycons2.nim @@ -6,7 +6,7 @@ discard """ type TEnum = enum eA, eB, eC, eD, eE, eF - + const myMapping: array[TEnum, array[0..1, int]] = [ eA: [1, 2], diff --git a/tests/array/tarrayplus.nim b/tests/array/tarrayplus.nim index 0ea349f4f..33921c0e1 100644 --- a/tests/array/tarrayplus.nim +++ b/tests/array/tarrayplus.nim @@ -6,7 +6,7 @@ proc `+`*[R, T] (v1, v2: array[R, T]): array[R, T] = for i in low(v1)..high(v1): result[i] = v1[i] + v2[i] -var +var v1: array[0..2, float] = [3.0, 1.2, 3.0] v2: array[0..1, float] = [2.0, 1.0] v3 = v1 + v2 diff --git a/tests/array/tarrindx.nim b/tests/array/tarrindx.nim index 13919cc2c..a8d72b338 100644 --- a/tests/array/tarrindx.nim +++ b/tests/array/tarrindx.nim @@ -1,13 +1,13 @@ -# test another strange bug ... (I hate this compiler; it is much too buggy!) - -proc putEnv(key, val: string) = - # XXX: we have to leak memory here, as we cannot - # free it before the program ends (says Borland's - # documentation) - var - env: ptr array[0..500000, char] - env = cast[ptr array[0..500000, char]](alloc(len(key) + len(val) + 2)) - for i in 0..len(key)-1: env[i] = key[i] - env[len(key)] = '=' - for i in 0..len(val)-1: - env[len(key)+1+i] = val[i] +# test another strange bug ... (I hate this compiler; it is much too buggy!) + +proc putEnv(key, val: string) = + # XXX: we have to leak memory here, as we cannot + # free it before the program ends (says Borland's + # documentation) + var + env: ptr array[0..500000, char] + env = cast[ptr array[0..500000, char]](alloc(len(key) + len(val) + 2)) + for i in 0..len(key)-1: env[i] = key[i] + env[len(key)] = '=' + for i in 0..len(val)-1: + env[len(key)+1+i] = val[i] diff --git a/tests/assert/tuserassert.nim b/tests/assert/tuserassert.nim index 57b229ca9..7bb0a7fc0 100644 --- a/tests/assert/tuserassert.nim +++ b/tests/assert/tuserassert.nim @@ -2,12 +2,12 @@ discard """ output: "x == 45ugh" """ -template myAssert(cond: expr) = +template myAssert(cond: expr) = when 3 <= 3: let c = cond.astToStr if not cond: echo c, "ugh" - + var x = 454 myAssert(x == 45) diff --git a/tests/assign/tassign.nim b/tests/assign/tassign.nim index 9a4c1543b..4c173d04f 100644 --- a/tests/assign/tassign.nim +++ b/tests/assign/tassign.nim @@ -1,31 +1,31 @@ -# Test the assignment operator for complex types which need RTTI - -type - TRec = object - x, y: int - s: string - seq: seq[string] - arr: seq[seq[array[0..3, string]]] - TRecSeq = seq[TRec] - -proc test() = - var - a, b: TRec - a.x = 1 - a.y = 2 - a.s = "Hallo!" - a.seq = @["abc", "def", "ghi", "jkl"] - a.arr = @[] - setLen(a.arr, 4) - a.arr[0] = @[] - a.arr[1] = @[] - - b = a # perform a deep copy here! - b.seq = @["xyz", "huch", "was", "soll"] - writeLine(stdout, len(a.seq)) - writeLine(stdout, a.seq[3]) - writeLine(stdout, len(b.seq)) - writeLine(stdout, b.seq[3]) - writeLine(stdout, b.y) - -test() +# Test the assignment operator for complex types which need RTTI + +type + TRec = object + x, y: int + s: string + seq: seq[string] + arr: seq[seq[array[0..3, string]]] + TRecSeq = seq[TRec] + +proc test() = + var + a, b: TRec + a.x = 1 + a.y = 2 + a.s = "Hallo!" + a.seq = @["abc", "def", "ghi", "jkl"] + a.arr = @[] + setLen(a.arr, 4) + a.arr[0] = @[] + a.arr[1] = @[] + + b = a # perform a deep copy here! + b.seq = @["xyz", "huch", "was", "soll"] + writeLine(stdout, len(a.seq)) + writeLine(stdout, a.seq[3]) + writeLine(stdout, len(b.seq)) + writeLine(stdout, b.seq[3]) + writeLine(stdout, b.y) + +test() diff --git a/tests/assign/tgenericassign.nim b/tests/assign/tgenericassign.nim index 654b0ab8f..bd9c6c21b 100644 --- a/tests/assign/tgenericassign.nim +++ b/tests/assign/tgenericassign.nim @@ -6,7 +6,7 @@ type TAny* = object {.pure.} value*: pointer rawType: pointer - + proc newAny(value, rawType: pointer): TAny = result.value = value result.rawType = rawType diff --git a/tests/assign/tgenericassigntuples.nim b/tests/assign/tgenericassigntuples.nim index 6dd63a984..cca244577 100644 --- a/tests/assign/tgenericassigntuples.nim +++ b/tests/assign/tgenericassigntuples.nim @@ -4,7 +4,7 @@ discard """ var t, s: tuple[x: string, c: int] -proc ugh: seq[tuple[x: string, c: int]] = +proc ugh: seq[tuple[x: string, c: int]] = result = @[("abc", 232)] t = ugh()[0] diff --git a/tests/assign/tobjasgn.nim b/tests/assign/tobjasgn.nim index 23a31252d..e731d9e93 100644 --- a/tests/assign/tobjasgn.nim +++ b/tests/assign/tobjasgn.nim @@ -12,7 +12,7 @@ type a, b: int PSomeObj = ref object a, b: int - + var a = TSomeObj(a: 8) var b = PSomeObj(a: 5) echo a.a, " ", b.a, " ", a.b, " ", b.b diff --git a/tests/async/tasyncawait.nim b/tests/async/tasyncawait.nim index 13d531387..e5895abe1 100644 --- a/tests/async/tasyncawait.nim +++ b/tests/async/tasyncawait.nim @@ -50,7 +50,7 @@ proc createServer(port: TPort) {.async.} = if bindAddr(server.SocketHandle, cast[ptr SockAddr](addr(name)), sizeof(name).Socklen) < 0'i32: raiseOSError(osLastError()) - + discard server.SocketHandle.listen() while true: asyncCheck readMessages(await accept(server)) diff --git a/tests/async/tasynceverror.nim b/tests/async/tasynceverror.nim index 3b81680cb..5575cfe82 100644 --- a/tests/async/tasynceverror.nim +++ b/tests/async/tasynceverror.nim @@ -40,7 +40,7 @@ else: s = newAsyncSocket() await s.connect(testHost, testPort) - + var ps = await ls.accept() SocketHandle(ls).close() diff --git a/tests/async/tasyncfile.nim b/tests/async/tasyncfile.nim index c3cf33512..05cda5e5f 100644 --- a/tests/async/tasyncfile.nim +++ b/tests/async/tasyncfile.nim @@ -18,7 +18,7 @@ proc main() {.async.} = let data = await file.readAll() doAssert data == "foot" file.close() - + # Append test block: var file = openAsync(fn, fmAppend) @@ -29,8 +29,8 @@ proc main() {.async.} = file.close() file = openAsync(fn, fmRead) let data = await file.readAll() - + doAssert data == "foot\ntest2" file.close() - + waitFor main() diff --git a/tests/async/tasynciossl.nim b/tests/async/tasynciossl.nim index 118b9e74d..ba856760e 100644 --- a/tests/async/tasynciossl.nim +++ b/tests/async/tasynciossl.nim @@ -10,12 +10,12 @@ disp = newDispatcher() var msgCount = 0 when defined(ssl): - var ctx = newContext(verifyMode = CVerifyNone, + var ctx = newContext(verifyMode = CVerifyNone, certFile = "tests/testdata/mycert.pem", keyFile = "tests/testdata/mycert.pem") var ctx1 = newContext(verifyMode = CVerifyNone) -const +const swarmSize = 50 messagesToSend = 100 diff --git a/tests/async/tasyncudp.nim b/tests/async/tasyncudp.nim index 2a7ed40bf..57e2be85d 100644 --- a/tests/async/tasyncudp.nim +++ b/tests/async/tasyncudp.nim @@ -20,12 +20,12 @@ proc serverRead(s: PAsyncSocket) = if s.recvFromAsync(data, 9, address, port): assert address == "127.0.0.1" msgCount.inc() - + discard """ - + var line = "" assert s.recvLine(line) - + if line == "": assert(false) else: @@ -66,11 +66,11 @@ while true: if not disp.poll(): break - + if (msgCount div messagesToSend) * serverCount == currentClient: createClient(disp, TPort(10335), false) createClient(disp, TPort(10336), true) - + if msgCount == messagesToSend * serverCount * swarmSize: break diff --git a/tests/benchmark.nim b/tests/benchmark.nim index 0613d1bf9..69c9a3927 100644 --- a/tests/benchmark.nim +++ b/tests/benchmark.nim @@ -44,4 +44,4 @@ when isMainModule: var b = doBench() var output = genOutput(b) writeFile("benchmarkResults.json", pretty(output)) - \ No newline at end of file + diff --git a/tests/benchmarks/fannkuch.nim b/tests/benchmarks/fannkuch.nim index 15f78f50c..55405b3c9 100644 --- a/tests/benchmarks/fannkuch.nim +++ b/tests/benchmarks/fannkuch.nim @@ -2,7 +2,7 @@ import os import strutils proc fannkuch (n: int): int = - var + var count: seq[int] maxFlips = 0 m = n-1 @@ -58,7 +58,7 @@ proc fannkuch (n: int): int = for i in 0 .. r-1: perm1[i] = perm1[i+1] perm1[r] = tmp - + dec (count[r]) if count[r] > 0: break makePerm @@ -66,4 +66,4 @@ proc fannkuch (n: int): int = return maxFlips var n = 10 -echo ("Pfannkuchen(" & $n & ") = " & $fannkuch (n)) \ No newline at end of file +echo ("Pfannkuchen(" & $n & ") = " & $fannkuch (n)) diff --git a/tests/benchmarks/quicksort.nim b/tests/benchmarks/quicksort.nim index 599e3674c..6a1222b9a 100644 --- a/tests/benchmarks/quicksort.nim +++ b/tests/benchmarks/quicksort.nim @@ -51,4 +51,4 @@ proc sort (start, stop: int) = sort (0, data.len) echo (data[n div 2 - 1] and 0xFFFF_FFFF'i64, ", ", data[n div 2] and 0xFFFF_FFFF'i64, ", ", - data[n div 2 + 1] and 0xFFFF_FFFF'i64) \ No newline at end of file + data[n div 2 + 1] and 0xFFFF_FFFF'i64) diff --git a/tests/bind/mbind3.nim b/tests/bind/mbind3.nim index d02bc79d0..aad080223 100644 --- a/tests/bind/mbind3.nim +++ b/tests/bind/mbind3.nim @@ -1,5 +1,5 @@ # Module A -var +var lastId = 0 template genId*: expr = diff --git a/tests/bind/tbind1.nim b/tests/bind/tbind1.nim index 6593b2307..2665d0b5c 100644 --- a/tests/bind/tbind1.nim +++ b/tests/bind/tbind1.nim @@ -6,14 +6,14 @@ discard """ proc p1(x: int8, y: int): int = return x + y -template tempBind(x, y: expr): expr = +template tempBind(x, y: expr): expr = bind p1 - p1(x, y) + p1(x, y) proc p1(x: int, y: int8): int = return x - y -# This is tricky: the call to ``p1(1'i8, 2'i8)`` should not fail in line 6, -# because it is not ambiguous there. But it is ambiguous after line 8. +# This is tricky: the call to ``p1(1'i8, 2'i8)`` should not fail in line 6, +# because it is not ambiguous there. But it is ambiguous after line 8. echo tempBind(1'i8, 2'i8) #OUT 3 diff --git a/tests/bind/tbind2.nim b/tests/bind/tbind2.nim index e8e21ad02..d2219765d 100644 --- a/tests/bind/tbind2.nim +++ b/tests/bind/tbind2.nim @@ -8,7 +8,7 @@ discard """ proc p1(x: int8, y: int): int = return x + y proc p1(x: int, y: int8): int = return x - y -template tempBind(x, y: expr): expr = +template tempBind(x, y: expr): expr = (bind p1(x, y)) #ERROR_MSG ambiguous call echo tempBind(1'i8, 2'i8) diff --git a/tests/bind/tdatabind.nim b/tests/bind/tdatabind.nim index afa8aa47b..124faee6f 100644 --- a/tests/bind/tdatabind.nim +++ b/tests/bind/tdatabind.nim @@ -31,14 +31,14 @@ proc newProperty*[T](value: T): TProperty[T] = proc setter(property: var TProperty[T], v: T) = property.value = v - + # fire event here var args: TValueEventArgs[T] args.Property = property property.EEmitter.emit(property.ValueChanged, args) - + prop.setProc = setter - + return prop proc `prop`[T] (p: TProperty[T]): T = @@ -56,7 +56,7 @@ proc `$`[T] (p: TProperty[T]): string = proc propertyBind*[T](p1: var TProperty[T], p2: var TProperty[T]) = p1.Binders.add(p2) - + # make handler -> handler[T] so trigger even more generics bugs ... proc handler(e: TEventArgs) = type TEA = TValueEventArgs[T] @@ -77,9 +77,9 @@ proc `->`[T](p1: var TProperty[T], p2: var TProperty[T]) = when isMainModule: # Initial value testing var myProp = newProperty(5) - + echo(myProp) - + myProp ~= 7 # Temp operator until overloading of '=' is implemented. echo(myProp) diff --git a/tests/borrow/tborrow.nim b/tests/borrow/tborrow.nim index d4df5f524..ee0d0194d 100644 --- a/tests/borrow/tborrow.nim +++ b/tests/borrow/tborrow.nim @@ -6,12 +6,12 @@ discard """ proc `++`*[T: int | float](a, b: T): T = result = a + b - + type DI = distinct int DF = distinct float DS = distinct string - + proc `++`(x, y: DI): DI {.borrow.} proc `++`(x, y: DF): DF {.borrow.} diff --git a/tests/casestmt/tcaseoverlaprange.nim b/tests/casestmt/tcaseoverlaprange.nim index 5f24c3ca9..3527c9385 100644 --- a/tests/casestmt/tcaseoverlaprange.nim +++ b/tests/casestmt/tcaseoverlaprange.nim @@ -8,8 +8,8 @@ type var e: TE - + case e -of A..D, B..C: +of A..D, B..C: echo "redundant" else: nil diff --git a/tests/casestmt/tcaseoverlaprange2.nim b/tests/casestmt/tcaseoverlaprange2.nim index d6e301508..4a9479a5f 100644 --- a/tests/casestmt/tcaseoverlaprange2.nim +++ b/tests/casestmt/tcaseoverlaprange2.nim @@ -6,7 +6,7 @@ discard """ -proc checkDuplicates(myval: int32): bool = +proc checkDuplicates(myval: int32): bool = case myval of 0x7B: echo "this should not compile" diff --git a/tests/casestmt/tcasestm.nim b/tests/casestmt/tcasestm.nim index a21b6be0d..7ac20bf2f 100644 --- a/tests/casestmt/tcasestm.nim +++ b/tests/casestmt/tcasestm.nim @@ -25,7 +25,7 @@ of "will", "it", "finally", "be", "generated": discard var z = case i of 1..5, 8, 9: "aa" of 6, 7: "bb" - elif x == "Ha": + elif x == "Ha": "cc" elif x == "yyy": write(stdout, x) diff --git a/tests/casestmt/tlinearscanend.nim b/tests/casestmt/tlinearscanend.nim index 15fd0c70a..9a984e039 100644 --- a/tests/casestmt/tlinearscanend.nim +++ b/tests/casestmt/tlinearscanend.nim @@ -4,13 +4,13 @@ import strutils var x = 343 case stdin.readline.parseInt -of 0: +of 0: echo "most common case" -of 1: +of 1: {.linearScanEnd.} echo "second most common case" of 2: echo "unlikely: use branch table" -else: +else: echo "unlikely too: use branch table" @@ -18,7 +18,7 @@ case x of 23: echo "23" of 343: echo "343" of 21: echo "21" -else: +else: {.linearScanEnd.} echo "default" diff --git a/tests/ccgbugs/tccgen1.nim b/tests/ccgbugs/tccgen1.nim index 9234bbd6c..4917c9848 100644 --- a/tests/ccgbugs/tccgen1.nim +++ b/tests/ccgbugs/tccgen1.nim @@ -18,21 +18,21 @@ type FOwnerDocument: PDocument # Read-Only FParentNode: PNode # Read-Only prefix*: string # Setting this should change some values... TODO! - + PElement* = ref Element Element = object of Node FTagName: string # Read-only - + PCharacterData = ref CharacterData CharacterData = object of Node data*: string - + PDocument* = ref Document Document = object of Node FImplementation: PDOMImplementation # Read-only FDocumentElement: PElement # Read-only - - PAttr* = ref Attr + + PAttr* = ref Attr Attr = object of Node FName: string # Read-only FSpecified: bool # Read-only @@ -44,22 +44,22 @@ type PText* = ref Text Text = object of CharacterData - + PComment* = ref Comment Comment = object of CharacterData - + PCDataSection* = ref CDataSection CDataSection = object of Text - + PProcessingInstruction* = ref ProcessingInstruction ProcessingInstruction = object of Node data*: string FTarget: string # Read-only -proc `namespaceURI=`*(n: var PNode, value: string) = +proc `namespaceURI=`*(n: var PNode, value: string) = n.FNamespaceURI = value - -proc main = + +proc main = var n: PNode new(n) n.namespaceURI = "test" diff --git a/tests/ccgbugs/tcgbug.nim b/tests/ccgbugs/tcgbug.nim index 92e7b3a66..1c6466c87 100644 --- a/tests/ccgbugs/tcgbug.nim +++ b/tests/ccgbugs/tcgbug.nim @@ -14,7 +14,7 @@ proc p(a: PObj) = proc q(a: var PObj) = a.p() -var +var a: PObj new(a) q(a) diff --git a/tests/ccgbugs/tcodegenbug1.nim b/tests/ccgbugs/tcodegenbug1.nim index 9b9771485..a5cfc77cc 100644 --- a/tests/ccgbugs/tcodegenbug1.nim +++ b/tests/ccgbugs/tcodegenbug1.nim @@ -11,7 +11,7 @@ type status*: TStatusEnum desc*: string hash*: string - + proc initStatus*(): TStatus = result.status = sUnknown result.desc = "" @@ -49,7 +49,7 @@ proc `$`*(status: TStatusEnum): string = return "csource generation succeeded" of sUnknown: return "unknown" - + proc makeCommitPath*(platform, hash: string): string = return platform / "nim_" & hash.substr(0, 11) # 11 Chars. diff --git a/tests/closure/tclosure.nim b/tests/closure/tclosure.nim index 445a99b6d..09d48436e 100644 --- a/tests/closure/tclosure.nim +++ b/tests/closure/tclosure.nim @@ -41,7 +41,7 @@ type proc getInterf(): ITest = var shared: int - + return (setter: proc (x: int) = shared = x, getter: proc (): int = return shared) diff --git a/tests/closure/tclosure2.nim b/tests/closure/tclosure2.nim index d2c16eac9..d331388cf 100644 --- a/tests/closure/tclosure2.nim +++ b/tests/closure/tclosure2.nim @@ -33,13 +33,13 @@ when true: for xxxx in 0..9: var i = 0 proc bx = - if i > 10: + if i > 10: echo xxxx return i += 1 #for j in 0 .. 0: echo i bx() - + bx() echo i @@ -50,11 +50,11 @@ when true: var x = start-1 #let dummy = proc = # discard start - - result = proc (): int = + + result = proc (): int = #var x = 9 for i in 0 .. 0: x = x + 1 - + return x var a = accumulator(3) @@ -69,7 +69,7 @@ when true: for i in 0..3: echo "py" py() - + outer() @@ -80,7 +80,7 @@ when true: if n < 0: result = errorValue elif n <= 1: result = 1 else: result = n * fac(n-1) - + proc px() {.closure.} = echo "px" @@ -93,7 +93,7 @@ when true: "xyz": py } mapping[0][1]() - + echo fac(3) diff --git a/tests/closure/tclosure3.nim b/tests/closure/tclosure3.nim index bb217387f..8f6f4a70f 100644 --- a/tests/closure/tclosure3.nim +++ b/tests/closure/tclosure3.nim @@ -13,7 +13,7 @@ proc main = for i in 0 .. n-1: let val = s[i]() if val != $(i*i): echo "bug ", val - + if getOccupiedMem() > 3000_000: quit("still a leak!") echo "success" diff --git a/tests/closure/tclosurebug2.nim b/tests/closure/tclosurebug2.nim index 12e4e3509..581b735bf 100644 --- a/tests/closure/tclosurebug2.nim +++ b/tests/closure/tclosurebug2.nim @@ -111,7 +111,7 @@ proc hasKey*[A, B](t: TOrderedTable[A, B], key: A): bool = ## returns true iff `key` is in the table `t`. result = rawGet(t, key) >= 0 -proc rawInsert[A, B](t: var TOrderedTable[A, B], +proc rawInsert[A, B](t: var TOrderedTable[A, B], data: var TOrderedKeyValuePairSeq[A, B], key: A, val: B) = rawInsertImpl() @@ -128,7 +128,7 @@ proc enlarge[A, B](t: var TOrderedTable[A, B]) = t.last = -1 while h >= 0: var nxt = t.data[h].next - if t.data[h].slot == seFilled: + if t.data[h].slot == seFilled: rawInsert(t, n, t.data[h].key, t.data[h].val) h = nxt swap(t.data, n) @@ -150,16 +150,16 @@ proc initOrderedTable*[A, B](initialSize=64): TOrderedTable[A, B] = result.last = -1 newSeq(result.data, initialSize) -proc toOrderedTable*[A, B](pairs: openarray[tuple[key: A, +proc toOrderedTable*[A, B](pairs: openarray[tuple[key: A, val: B]]): TOrderedTable[A, B] = ## creates a new ordered hash table that contains the given `pairs`. result = initOrderedTable[A, B](nextPowerOfTwo(pairs.len+10)) for key, val in items(pairs): result[key] = val -proc sort*[A, B](t: var TOrderedTable[A,B], +proc sort*[A, B](t: var TOrderedTable[A,B], cmp: proc (x, y: tuple[key: A, val: B]): int {.closure.}) = ## sorts the ordered table so that the entry with the highest counter comes - ## first. This is destructive (with the advantage of being efficient)! + ## first. This is destructive (with the advantage of being efficient)! ## You must not modify `t` afterwards! ## You can use the iterators `pairs`, `keys`, and `values` to iterate over ## `t` in the sorted order. @@ -186,7 +186,7 @@ proc sort*[A, B](t: var TOrderedTable[A,B], let item1 = (x.key, x.val) let item2 = (y.key, y.val) return cmp(item1, item2) - + while rawCmp(t.data[j-h], t.data[j]) <= 0: swap(t.data[j], t.data[j-h]) j = j-h diff --git a/tests/closure/tinterf.nim b/tests/closure/tinterf.nim index 726fac9f6..1ac6da945 100644 --- a/tests/closure/tinterf.nim +++ b/tests/closure/tinterf.nim @@ -10,8 +10,8 @@ type proc getInterf(): ITest = var shared1, shared2: int - - return (setter: proc (x: int) = + + return (setter: proc (x: int) = shared1 = x shared2 = x + 10, getter1: proc (): int = result = shared1, diff --git a/tests/closure/tinvalidclosure2.nim b/tests/closure/tinvalidclosure2.nim index 20e465c12..845559309 100644 --- a/tests/closure/tinvalidclosure2.nim +++ b/tests/closure/tinvalidclosure2.nim @@ -3,12 +3,12 @@ discard """ errormsg: "illegal capture 'A'" """ -proc outer() = +proc outer() = var A: int proc ugh[T](x: T) {.cdecl.} = echo "ugha", A, x - + ugh[int](12) outer() diff --git a/tests/closure/tjester.nim b/tests/closure/tjester.nim index 48e5186f0..3bd10120a 100644 --- a/tests/closure/tjester.nim +++ b/tests/closure/tjester.nim @@ -17,7 +17,7 @@ proc cbOuter(response: string) {.closure, discardable.} = var iterVar = fooIter iterVar().data yield Future[int](data: foo()) - + var iterVar2 = cbIter proc cb2() {.closure.} = try: diff --git a/tests/closure/tnestedclosure.nim b/tests/closure/tnestedclosure.nim index c8f1e231b..67e196f66 100644 --- a/tests/closure/tnestedclosure.nim +++ b/tests/closure/tnestedclosure.nim @@ -45,7 +45,7 @@ proc cbOuter() = proc fooIter() = echo response fooIter() - + cbIter() cbOuter() diff --git a/tests/closure/tnestedproc.nim b/tests/closure/tnestedproc.nim index 49ec6f9a7..7eeeff198 100644 --- a/tests/closure/tnestedproc.nim +++ b/tests/closure/tnestedproc.nim @@ -2,10 +2,10 @@ discard """ output: "11" """ -proc p(x, y: int): int = +proc p(x, y: int): int = result = x + y -echo p((proc (): int = +echo p((proc (): int = var x = 7 return x)(), (proc (): int = return 4)()) diff --git a/tests/closure/uclosures.nim b/tests/closure/uclosures.nim index 6eea29ca1..817bfec6b 100644 --- a/tests/closure/uclosures.nim +++ b/tests/closure/uclosures.nim @@ -2,7 +2,7 @@ import unittest test "loop variables are captured by copy": var funcs: seq[proc (): int {.closure.}] = @[] - + for i in 0..10: let ii = i funcs.add do -> int: return ii * ii diff --git a/tests/cnstseq/tcnstseq.nim b/tests/cnstseq/tcnstseq.nim index e7d2333b4..ad0527f10 100644 --- a/tests/cnstseq/tcnstseq.nim +++ b/tests/cnstseq/tcnstseq.nim @@ -9,8 +9,8 @@ import strutils const myWords = "Angelika Anne Anna Anka Anja".split() - -for x in items(myWords): + +for x in items(myWords): write(stdout, x) #OUT AngelikaAnneAnnaAnkaAnja diff --git a/tests/cnstseq/tcnstseq2.nim b/tests/cnstseq/tcnstseq2.nim index 1a27b2ba7..2f364d278 100644 --- a/tests/cnstseq/tcnstseq2.nim +++ b/tests/cnstseq/tcnstseq2.nim @@ -4,8 +4,8 @@ discard """ const myWords = @["Angelika", "Anne", "Anna", "Anka", "Anja"] - -for i in 0 .. high(myWords): + +for i in 0 .. high(myWords): write(stdout, myWords[i]) #OUT AngelikaAnneAnnaAnkaAnja diff --git a/tests/collections/tindexby.nim b/tests/collections/tindexby.nim index f374d5504..88c0b263e 100644 --- a/tests/collections/tindexby.nim +++ b/tests/collections/tindexby.nim @@ -11,11 +11,11 @@ type TElem = object foo: int bar: string - + let elem1 = TElem(foo: 1, bar: "bar") elem2 = TElem(foo: 2, bar: "baz") - + var tbl2 = initTable[string, TElem]() tbl2.add("bar", elem1) tbl2.add("baz", elem2) diff --git a/tests/collections/ttableconstr.nim b/tests/collections/ttableconstr.nim index 1a21a18d1..a9262e70e 100644 --- a/tests/collections/ttableconstr.nim +++ b/tests/collections/ttableconstr.nim @@ -3,7 +3,7 @@ template ignoreExpr(e: expr): stmt {.immediate.} = discard -# test first class '..' syntactical citizen: +# test first class '..' syntactical citizen: ignoreExpr x <> 2..4 # test table constructor: ignoreExpr({:}) diff --git a/tests/constr/tconstr1.nim b/tests/constr/tconstr1.nim index 45e303554..28431287c 100644 --- a/tests/constr/tconstr1.nim +++ b/tests/constr/tconstr1.nim @@ -3,28 +3,28 @@ discard """ line: 25 errormsg: "type mismatch" """ -# Test array, record constructors - -type - TComplexRecord = tuple[ - s: string, - x, y: int, - z: float, - chars: set[char]] - -proc testSem = - var - things: array [0..1, TComplexRecord] = [ - (s: "hi", x: 69, y: 45, z: 0.0, chars: {'a', 'b', 'c'}), - (s: "hi", x: 69, y: 45, z: 1.0, chars: {'a', 'b', 'c'})] - write(stdout, things[0].x) - -const - things: array [0..1, TComplexRecord] = [ - (s: "hi", x: 69, y: 45, z: 0.0, chars: {'a', 'b', 'c'}), - (s: "hi", x: 69, y: 45, z: 1.0)] #ERROR - otherThings = [ # the same - (s: "hi", x: 69, y: 45, z: 0.0, chars: {'a', 'b', 'c'}), - (s: "hi", x: 69, y: 45, z: 1.0, chars: {'a'})] +# Test array, record constructors + +type + TComplexRecord = tuple[ + s: string, + x, y: int, + z: float, + chars: set[char]] + +proc testSem = + var + things: array [0..1, TComplexRecord] = [ + (s: "hi", x: 69, y: 45, z: 0.0, chars: {'a', 'b', 'c'}), + (s: "hi", x: 69, y: 45, z: 1.0, chars: {'a', 'b', 'c'})] + write(stdout, things[0].x) + +const + things: array [0..1, TComplexRecord] = [ + (s: "hi", x: 69, y: 45, z: 0.0, chars: {'a', 'b', 'c'}), + (s: "hi", x: 69, y: 45, z: 1.0)] #ERROR + otherThings = [ # the same + (s: "hi", x: 69, y: 45, z: 0.0, chars: {'a', 'b', 'c'}), + (s: "hi", x: 69, y: 45, z: 1.0, chars: {'a'})] diff --git a/tests/constr/tconstr2.nim b/tests/constr/tconstr2.nim index 30cec5cb8..cd00681b8 100644 --- a/tests/constr/tconstr2.nim +++ b/tests/constr/tconstr2.nim @@ -2,25 +2,25 @@ discard """ file: "tconstr2.nim" output: "69" """ -# Test array, record constructors - -type - TComplexRecord = tuple[ - s: string, - x, y: int, - z: float, - chars: set[char]] - -const - things: array [0..1, TComplexRecord] = [ - (s: "hi", x: 69, y: 45, z: 0.0, chars: {'a', 'b', 'c'}), - (s: "hi", x: 69, y: 45, z: 1.0, chars: {})] - otherThings = [ # the same - (s: "hi", x: 69, y: 45, z: 0.0, chars: {'a', 'b', 'c'}), - (s: "hi", x: 69, y: 45, z: 1.0, chars: {'a'})] - -write(stdout, things[0].x) -#OUT 69 - +# Test array, record constructors + +type + TComplexRecord = tuple[ + s: string, + x, y: int, + z: float, + chars: set[char]] + +const + things: array [0..1, TComplexRecord] = [ + (s: "hi", x: 69, y: 45, z: 0.0, chars: {'a', 'b', 'c'}), + (s: "hi", x: 69, y: 45, z: 1.0, chars: {})] + otherThings = [ # the same + (s: "hi", x: 69, y: 45, z: 0.0, chars: {'a', 'b', 'c'}), + (s: "hi", x: 69, y: 45, z: 1.0, chars: {'a'})] + +write(stdout, things[0].x) +#OUT 69 + diff --git a/tests/constraints/tconstraints.nim b/tests/constraints/tconstraints.nim index e61095fff..ea3f68fd4 100644 --- a/tests/constraints/tconstraints.nim +++ b/tests/constraints/tconstraints.nim @@ -3,7 +3,7 @@ discard """ errormsg: "type mismatch: got (int literal(232))" """ -proc myGenericProc[T: object|tuple|ptr|ref|distinct](x: T): string = +proc myGenericProc[T: object|tuple|ptr|ref|distinct](x: T): string = result = $x type diff --git a/tests/controlflow/tblock1.nim b/tests/controlflow/tblock1.nim index 5c41aaf82..e3a780dfe 100644 --- a/tests/controlflow/tblock1.nim +++ b/tests/controlflow/tblock1.nim @@ -3,16 +3,16 @@ discard """ line: 14 errormsg: "undeclared identifier: \'ha\'" """ -# check for forward label and -# for failure when label is not declared - -proc main = - block endLess: - write(stdout, "Muaahh!\N") - break endLess - - break ha #ERROR - -main() +# check for forward label and +# for failure when label is not declared + +proc main = + block endLess: + write(stdout, "Muaahh!\N") + break endLess + + break ha #ERROR + +main() diff --git a/tests/controlflow/tcontinue.nim b/tests/controlflow/tcontinue.nim index 092026e8c..ac4fdc2de 100644 --- a/tests/controlflow/tcontinue.nim +++ b/tests/controlflow/tcontinue.nim @@ -6,7 +6,7 @@ var i = 0 while i < 400: if i == 10: break - elif i == 3: + elif i == 3: inc i continue inc i @@ -16,7 +16,7 @@ var j = 0 while j < 300: for x in 0..34: if j < 300: continue - if x == 10: + if x == 10: echo "failure: should never happen" break f = "came here" diff --git a/tests/controlflow/tnestif.nim b/tests/controlflow/tnestif.nim index bfcd8751c..3d8adb337 100644 --- a/tests/controlflow/tnestif.nim +++ b/tests/controlflow/tnestif.nim @@ -2,23 +2,23 @@ discard """ file: "tnestif.nim" output: "i == 2" """ -# test nested ifs - -var - x, y: int -x = 2 -if x == 0: - write(stdout, "i == 0") - if y == 0: - write(stdout, x) - else: - write(stdout, y) -elif x == 1: - write(stdout, "i == 1") -elif x == 2: - write(stdout, "i == 2") -else: - write(stdout, "looks like Python") -#OUT i == 2 +# test nested ifs + +var + x, y: int +x = 2 +if x == 0: + write(stdout, "i == 0") + if y == 0: + write(stdout, x) + else: + write(stdout, y) +elif x == 1: + write(stdout, "i == 1") +elif x == 2: + write(stdout, "i == 2") +else: + write(stdout, "looks like Python") +#OUT i == 2 diff --git a/tests/controlflow/tstatret.nim b/tests/controlflow/tstatret.nim index bf90255a0..d655f5595 100644 --- a/tests/controlflow/tstatret.nim +++ b/tests/controlflow/tstatret.nim @@ -3,10 +3,10 @@ discard """ line: 9 errormsg: "statement not allowed after" """ -# no statement after return -proc main() = - return - echo("huch?") #ERROR_MSG statement not allowed after - +# no statement after return +proc main() = + return + echo("huch?") #ERROR_MSG statement not allowed after + diff --git a/tests/converter/ttypeconverter1.nim b/tests/converter/ttypeconverter1.nim index 510b84700..39eb6eff1 100644 --- a/tests/converter/ttypeconverter1.nim +++ b/tests/converter/ttypeconverter1.nim @@ -7,7 +7,7 @@ converter p(i: int): bool = return i != 0 if 1: echo if 4: "foo" else: "barr" -while 0: +while 0: echo "bar" var a: array[3, bool] diff --git a/tests/cpp/tthread_createthread.nim b/tests/cpp/tthread_createthread.nim index 0dc081268..2c239005f 100644 --- a/tests/cpp/tthread_createthread.nim +++ b/tests/cpp/tthread_createthread.nim @@ -11,4 +11,4 @@ proc main() = thread.createThread(threadMain, 0) thread.joinThreads() -main() \ No newline at end of file +main() diff --git a/tests/dir with space/tspace.nim b/tests/dir with space/tspace.nim index 8db4b52f2..2b74fa629 100644 --- a/tests/dir with space/tspace.nim +++ b/tests/dir with space/tspace.nim @@ -1,3 +1,3 @@ # Test for the compiler to be able to compile a Nim file with spaces in it. -echo("Successful") \ No newline at end of file +echo("Successful") diff --git a/tests/discard/tdiscardable.nim b/tests/discard/tdiscardable.nim index a806ccdce..99adcfd30 100644 --- a/tests/discard/tdiscardable.nim +++ b/tests/discard/tdiscardable.nim @@ -1,10 +1,10 @@ # Test the discardable pragma -proc p(x, y: int): int {.discardable.} = +proc p(x, y: int): int {.discardable.} = return x + y # test that it is inherited from generic procs too: -proc q[T](x, y: T): T {.discardable.} = +proc q[T](x, y: T): T {.discardable.} = return x + y diff --git a/tests/discard/tneedsdiscard.nim b/tests/discard/tneedsdiscard.nim index 2a7856b4a..2df3531e7 100644 --- a/tests/discard/tneedsdiscard.nim +++ b/tests/discard/tneedsdiscard.nim @@ -6,7 +6,7 @@ discard """ proc p = var f: TFile echo "hi" - + open(f, "arg.txt") - + p() diff --git a/tests/distinct/tcurrncy.nim b/tests/distinct/tcurrncy.nim index 78dbc2a89..7ad4caea4 100644 --- a/tests/distinct/tcurrncy.nim +++ b/tests/distinct/tcurrncy.nim @@ -5,7 +5,7 @@ discard """ template Additive(typ: typeDesc): stmt = proc `+` *(x, y: typ): typ {.borrow.} proc `-` *(x, y: typ): typ {.borrow.} - + # unary operators: proc `+` *(x: typ): typ {.borrow.} proc `-` *(x: typ): typ {.borrow.} @@ -27,7 +27,7 @@ template DefineCurrency(typ, base: expr): stmt {.immediate.} = Additive(typ) Multiplicative(typ, base) Comparable(typ) - + proc `$` * (t: typ): string {.borrow.} DefineCurrency(TDollar, int) diff --git a/tests/dll/client.nim b/tests/dll/client.nim index d535e8750..150af3a17 100644 --- a/tests/dll/client.nim +++ b/tests/dll/client.nim @@ -22,8 +22,8 @@ else: proc newLit(x: int): PNode {.importc: "newLit", dynlib: dllname.} proc newOp(k: TNodeKind, a, b: PNode): PNode {. - importc: "newOp", dynlib: dllname.} -proc buildTree(x: int): PNode {.importc: "buildTree", dynlib: dllname.} + importc: "newOp", dynlib: dllname.} +proc buildTree(x: int): PNode {.importc: "buildTree", dynlib: dllname.} proc eval(n: PNode): int = case n.k @@ -36,6 +36,6 @@ proc eval(n: PNode): int = # Test the GC: for i in 0..100_000: discard eval(buildTree(2)) - + echo "Done" diff --git a/tests/dll/server.nim b/tests/dll/server.nim index df3223444..e6b80df88 100644 --- a/tests/dll/server.nim +++ b/tests/dll/server.nim @@ -10,11 +10,11 @@ type else: a, b: ref TNode PNode = ref TNode - + proc newLit(x: int): PNode {.exportc: "newLit", dynlib.} = new(result) result.x = x - + proc newOp(k: TNodeKind, a, b: PNode): PNode {.exportc: "newOp", dynlib.} = assert a != nil assert b != nil @@ -22,13 +22,13 @@ proc newOp(k: TNodeKind, a, b: PNode): PNode {.exportc: "newOp", dynlib.} = result.k = k result.a = a result.b = b - -proc buildTree(x: int): PNode {.exportc: "buildTree", dynlib.} = + +proc buildTree(x: int): PNode {.exportc: "buildTree", dynlib.} = result = newOp(nkMul, newOp(nkAdd, newLit(x), newLit(x)), newLit(x)) when false: # Test the GC: for i in 0..100_000: discard buildTree(2) - + echo "Done" diff --git a/tests/effects/teffects1.nim b/tests/effects/teffects1.nim index fad26a8d6..ef76c9130 100644 --- a/tests/effects/teffects1.nim +++ b/tests/effects/teffects1.nim @@ -7,11 +7,11 @@ type TObj = object {.pure, inheritable.} TObjB = object of TObj a, b, c: string - + IO2Error = ref object of IOError - + proc forw: int {. .} - + proc lier(): int {.raises: [IO2Error].} = writeLine stdout, "arg" diff --git a/tests/effects/teffects2.nim b/tests/effects/teffects2.nim index a97eacca6..0fa789869 100644 --- a/tests/effects/teffects2.nim +++ b/tests/effects/teffects2.nim @@ -7,9 +7,9 @@ type TObj = object {.pure, inheritable.} TObjB = object of TObj a, b, c: string - + EIO2 = ref object of IOError - + proc forw: int {.raises: [].} proc lier(): int {.raises: [IOError].} = diff --git a/tests/effects/teffects3.nim b/tests/effects/teffects3.nim index 3d597560f..1b18f7b6d 100644 --- a/tests/effects/teffects3.nim +++ b/tests/effects/teffects3.nim @@ -8,9 +8,9 @@ type TObjB = object of TObj a, b, c: string fn: proc (): int {.tags: [].} - + EIO2 = ref object of EIO - + proc raiser(): int {.tags: [TObj, FWriteIO].} = writeLine stdout, "arg" diff --git a/tests/effects/teffects4.nim b/tests/effects/teffects4.nim index e2aa440a9..fd5dd49e2 100644 --- a/tests/effects/teffects4.nim +++ b/tests/effects/teffects4.nim @@ -8,12 +8,12 @@ type TObjB = object of TObj a, b, c: string fn: proc (): int {.tags: [FReadIO].} - + EIO2 = ref object of EIO proc q() {.tags: [FIO].} = nil - + proc raiser(): int = writeLine stdout, "arg" if true: diff --git a/tests/effects/teffects5.nim b/tests/effects/teffects5.nim index d630a6fc4..779b4662c 100644 --- a/tests/effects/teffects5.nim +++ b/tests/effects/teffects5.nim @@ -6,7 +6,7 @@ discard """ proc p(q: proc() ): proc() {.tags: [], raises: [], closure.} = return proc () = q() - + let yay = p(proc () = raise newException(EIO, "IO")) proc main() {.raises: [], tags: [].} = yay() diff --git a/tests/effects/teffects6.nim b/tests/effects/teffects6.nim index 47c85c160..e69fe73b6 100644 --- a/tests/effects/teffects6.nim +++ b/tests/effects/teffects6.nim @@ -3,7 +3,7 @@ type PMenu = ref object PMenuItem = ref object -proc createMenuItem*(menu: PMenu, label: string, +proc createMenuItem*(menu: PMenu, label: string, action: proc (i: PMenuItem, p: pointer) {.cdecl.}) = discard var s: PMenu @@ -19,7 +19,7 @@ createMenuItem(s, "Go to definition...", proc noRaise(x: proc()) {.raises: [].} = # unknown call that might raise anything, but valid: x() - + proc doRaise() {.raises: [EIO].} = raise newException(EIO, "IO") diff --git a/tests/effects/tsidee1.nim b/tests/effects/tsidee1.nim index bd5b32dd7..e486d32e7 100644 --- a/tests/effects/tsidee1.nim +++ b/tests/effects/tsidee1.nim @@ -11,8 +11,8 @@ proc dontcare(x: int): int = return x + global proc SideEffectLyer(x, y: int): int {.noSideEffect.} = #ERROR_MSG 'SideEffectLyer' can have side effects return x + y + dontcare(x) - -echo SideEffectLyer(1, 3) + +echo SideEffectLyer(1, 3) diff --git a/tests/effects/tsidee2.nim b/tests/effects/tsidee2.nim index e73c89608..5ed541300 100644 --- a/tests/effects/tsidee2.nim +++ b/tests/effects/tsidee2.nim @@ -8,9 +8,9 @@ var proc dontcare(x: int): int = return x -proc SideEffectLyer(x, y: int): int {.noSideEffect.} = +proc SideEffectLyer(x, y: int): int {.noSideEffect.} = return x + y + dontcare(x) - + echo SideEffectLyer(1, 3) #OUT 5 diff --git a/tests/effects/tsidee3.nim b/tests/effects/tsidee3.nim index e0c427ab6..e15fbc3d1 100644 --- a/tests/effects/tsidee3.nim +++ b/tests/effects/tsidee3.nim @@ -8,9 +8,9 @@ var proc dontcare(x: int): int {.noSideEffect.} = return x -proc noSideEffect(x, y: int, p: proc (a: int): int {.noSideEffect.}): int {.noSideEffect.} = +proc noSideEffect(x, y: int, p: proc (a: int): int {.noSideEffect.}): int {.noSideEffect.} = return x + y + dontcare(x) - + echo noSideEffect(1, 3, dontcare) #OUT 5 diff --git a/tests/effects/tsidee4.nim b/tests/effects/tsidee4.nim index cbebfbd36..2cb88a23e 100644 --- a/tests/effects/tsidee4.nim +++ b/tests/effects/tsidee4.nim @@ -9,9 +9,9 @@ var proc dontcare(x: int): int = return x -proc noSideEffect(x, y: int, p: proc (a: int): int {.noSideEffect.}): int {.noSideEffect.} = +proc noSideEffect(x, y: int, p: proc (a: int): int {.noSideEffect.}): int {.noSideEffect.} = return x + y + dontcare(x) - + echo noSideEffect(1, 3, dontcare) #ERROR_MSG type mismatch diff --git a/tests/enum/tenum.nim b/tests/enum/tenum.nim index 6e53b9c08..b081212e6 100644 --- a/tests/enum/tenum.nim +++ b/tests/enum/tenum.nim @@ -1,8 +1,8 @@ -# Test enums - -type - E = enum a, b, c, x, y, z - -var - en: E -en = a +# Test enums + +type + E = enum a, b, c, x, y, z + +var + en: E +en = a diff --git a/tests/enum/tenum2.nim b/tests/enum/tenum2.nim index feba36dd6..3e34a21ce 100644 --- a/tests/enum/tenum2.nim +++ b/tests/enum/tenum2.nim @@ -1,14 +1,14 @@ # Test that enum with holes is handled correctly by case statement type - TEnumHole = enum + TEnumHole = enum eA = 0, eB = 4, eC = 5 - + var e: TEnumHole = eB - + case e of eA: echo "A" of eB: echo "B" diff --git a/tests/enum/tenum3.nim b/tests/enum/tenum3.nim index 09a516932..49cbf04d5 100644 --- a/tests/enum/tenum3.nim +++ b/tests/enum/tenum3.nim @@ -1,14 +1,14 @@ # Test enum with explicit size type - TEnumHole {.size: sizeof(int).} = enum + TEnumHole {.size: sizeof(int).} = enum eA = 0, eB = 4, eC = 5 - + var e: TEnumHole = eB - + case e of eA: echo "A" of eB: echo "B" diff --git a/tests/enum/tenumhole.nim b/tests/enum/tenumhole.nim index a35526378..68b82e283 100644 --- a/tests/enum/tenumhole.nim +++ b/tests/enum/tenumhole.nim @@ -12,10 +12,10 @@ type valueB = strValB & "conc", valueC, valueD = (4, "abc") - + # test the new "proc body can be an expr" feature: proc getValue: TMyEnum = valueD - + # trick the optimizer with a variable: var x = getValue() echo valueA, ord(valueA), valueB, ord(valueB), valueC, valueD, ord(valueD), x diff --git a/tests/enum/tenummix.nim b/tests/enum/tenummix.nim index aaf0be2cb..4352cdd81 100644 --- a/tests/enum/tenummix.nim +++ b/tests/enum/tenummix.nim @@ -7,5 +7,5 @@ discard """ type TE1 = enum eA, eB TE2 = enum eC, eD - + assert eA != eC diff --git a/tests/enum/toptions.nim b/tests/enum/toptions.nim index 3c841de2c..e53acb2b3 100644 --- a/tests/enum/toptions.nim +++ b/tests/enum/toptions.nim @@ -1,18 +1,18 @@ - -type - # please make sure we have under 32 options (improves code efficiency!) - TOption = enum - optNone, optForceFullMake, optBoehmGC, optRefcGC, optRangeCheck, - optBoundsCheck, optOverflowCheck, optNilCheck, optAssert, optLineDir, - optWarns, optHints, optDeadCodeElim, optListCmd, optCompileOnly, - optSafeCode, # only allow safe code - optStyleCheck, optOptimizeSpeed, optOptimizeSize, optGenDynLib, - optGenGuiApp, optStackTrace - - TOptionset = set[TOption] - -var - gOptions: TOptionset = {optRefcGC, optRangeCheck, optBoundsCheck, - optOverflowCheck, optAssert, optWarns, optHints, optLineDir, optStackTrace} - compilerArgs: int - gExitcode: int8 + +type + # please make sure we have under 32 options (improves code efficiency!) + TOption = enum + optNone, optForceFullMake, optBoehmGC, optRefcGC, optRangeCheck, + optBoundsCheck, optOverflowCheck, optNilCheck, optAssert, optLineDir, + optWarns, optHints, optDeadCodeElim, optListCmd, optCompileOnly, + optSafeCode, # only allow safe code + optStyleCheck, optOptimizeSpeed, optOptimizeSize, optGenDynLib, + optGenGuiApp, optStackTrace + + TOptionset = set[TOption] + +var + gOptions: TOptionset = {optRefcGC, optRangeCheck, optBoundsCheck, + optOverflowCheck, optAssert, optWarns, optHints, optLineDir, optStackTrace} + compilerArgs: int + gExitcode: int8 diff --git a/tests/exception/tcontinuexc.nim b/tests/exception/tcontinuexc.nim index f618abc14..fb9b523d7 100644 --- a/tests/exception/tcontinuexc.nim +++ b/tests/exception/tcontinuexc.nim @@ -21,7 +21,7 @@ try: stdout.write("E") stdout.write("C") raise newException(EsomeotherErr, "bla") -finally: +finally: echo "caught" #OUT ECcaught diff --git a/tests/exception/tfinally.nim b/tests/exception/tfinally.nim index 16fb3e7da..aa469d9c0 100644 --- a/tests/exception/tfinally.nim +++ b/tests/exception/tfinally.nim @@ -4,14 +4,14 @@ discard """ """ # Test return in try statement: -proc main: int = +proc main: int = try: try: return 1 finally: echo("came") return 2 - finally: + finally: echo("here") return 3 diff --git a/tests/exception/tfinally2.nim b/tests/exception/tfinally2.nim index e1e8d4c7e..f1acf2774 100644 --- a/tests/exception/tfinally2.nim +++ b/tests/exception/tfinally2.nim @@ -7,7 +7,7 @@ D''' """ # Test break in try statement: -proc main: int = +proc main: int = try: block AB: try: @@ -16,14 +16,14 @@ proc main: int = finally: echo("A") echo("skipped") - finally: + finally: block B: echo("B") echo("skipped") echo("C") finally: echo("D") - + discard main() #OUT ABCD diff --git a/tests/exception/tfinally3.nim b/tests/exception/tfinally3.nim index e65661cd0..8bccd1a7f 100644 --- a/tests/exception/tfinally3.nim +++ b/tests/exception/tfinally3.nim @@ -4,7 +4,7 @@ discard """ """ # Test break in try statement: -proc main: bool = +proc main: bool = while true: try: return true diff --git a/tests/exception/tnestedreturn2.nim b/tests/exception/tnestedreturn2.nim index 4bd2d535d..79523a883 100644 --- a/tests/exception/tnestedreturn2.nim +++ b/tests/exception/tnestedreturn2.nim @@ -14,7 +14,7 @@ proc test4() = discard # Should cause unhandled exception error, -# but could cause segmentation fault if +# but could cause segmentation fault if # exceptions are not handled properly. test4() raise newException(OSError, "Problem") diff --git a/tests/exception/tunhandledexc.nim b/tests/exception/tunhandledexc.nim index aa9d61236..63a402414 100644 --- a/tests/exception/tunhandledexc.nim +++ b/tests/exception/tunhandledexc.nim @@ -18,6 +18,6 @@ when true: genErrors("errssor!") except ESomething: echo("Error happened") - + diff --git a/tests/exception/twrongexc.nim b/tests/exception/twrongexc.nim index 4e921b8a3..b224d4c83 100644 --- a/tests/exception/twrongexc.nim +++ b/tests/exception/twrongexc.nim @@ -7,7 +7,7 @@ try: raise newException(ValueError, "") except OverflowError: echo("Error caught") - + diff --git a/tests/exprs/tstmtexprs.nim b/tests/exprs/tstmtexprs.nim index d6b827b6d..b2d5db408 100644 --- a/tests/exprs/tstmtexprs.nim +++ b/tests/exprs/tstmtexprs.nim @@ -26,16 +26,16 @@ when true: result.bar = "bar" echo($newfoo()) - - proc retInt(x, y: int): int = + + proc retInt(x, y: int): int = if (var yy = 0; yy != 0): echo yy else: echo(try: parseInt("1244") except EINvalidValue: -1) result = case x of 23: 3 - of 64: + of 64: case y of 1: 2 of 2: 3 @@ -79,7 +79,7 @@ semiProblem() # bug #844 -import json +import json proc parseResponse(): PJsonNode = result = % { "key1": % { "key2": % "value" } } for key, val in result["key1"]: diff --git a/tests/fields/tfieldindex.nim b/tests/fields/tfieldindex.nim index f0674af54..d11c1a8b2 100644 --- a/tests/fields/tfieldindex.nim +++ b/tests/fields/tfieldindex.nim @@ -14,7 +14,7 @@ proc indexOf*(t: typedesc, name: string): int = for n, x in fieldPairs(d): if n == name: return i i.inc - raise newException(EInvalidValue, "No field " & name & " in type " & + raise newException(EInvalidValue, "No field " & name & " in type " & astToStr(t)) echo TMyTuple.indexOf("b") diff --git a/tests/fields/tfielditerator.nim b/tests/fields/tfielditerator.nim index 2919aab41..6d15ea05d 100644 --- a/tests/fields/tfielditerator.nim +++ b/tests/fields/tfielditerator.nim @@ -28,7 +28,7 @@ proc p(x: string) = echo "a string: ", x var x: TMyTuple = ('a', 'b', 5, 6, "abc") var y: TMyTuple = ('A', 'b', 5, 9, "abc") -for f in fields(x): +for f in fields(x): p f for a, b in fields(x, y): diff --git a/tests/fields/tfielditerator2.nim b/tests/fields/tfielditerator2.nim index 70ab9e2ab..c8e230cf5 100644 --- a/tests/fields/tfielditerator2.nim +++ b/tests/fields/tfielditerator2.nim @@ -32,7 +32,7 @@ type a, b: char x, y: int z: string - + TEnum = enum enA, enB, enC TMyCaseObj = object case myDisc: TEnum @@ -51,7 +51,7 @@ proc myobj(a, b: char, x, y: int, z: string): TMyObj = var x = myobj('a', 'b', 5, 6, "abc") var y = myobj('A', 'b', 5, 9, "abc") -for f in fields(x): +for f in fields(x): p f for a, b in fields(x, y): diff --git a/tests/float/tfloat3.nim b/tests/float/tfloat3.nim index a3f5a2fc7..a14c6c396 100644 --- a/tests/float/tfloat3.nim +++ b/tests/float/tfloat3.nim @@ -8,7 +8,7 @@ import math, strutils {.emit: """ void printFloats(void) { double y = 1.234567890123456789; - + printf("C double: %.10f, %.10f ", exp(y), cos(y)); } """.} diff --git a/tests/friends/mfriends.nim b/tests/friends/mfriends.nim index f1c663655..19672289e 100644 --- a/tests/friends/mfriends.nim +++ b/tests/friends/mfriends.nim @@ -1,9 +1,9 @@ type - TMyObj = object + TMyObj = object x: int - -proc gen*[T](): T = + +proc gen*[T](): T = var d: TMyObj # access private field here d.x = 3 diff --git a/tests/gc/closureleak.nim b/tests/gc/closureleak.nim index 1c39f43d5..18d320bdf 100644 --- a/tests/gc/closureleak.nim +++ b/tests/gc/closureleak.nim @@ -16,7 +16,7 @@ proc free*(some: ref TFoo) = alive_foos.del alive_foos.find(some.id) proc newFoo*(): ref TFoo = new result, free - + result.id = foo_counter alive_foos.add result.id inc foo_counter @@ -26,7 +26,7 @@ for i in 0 .. <10: for i in 0 .. <10: let f = newFoo() - f.fn = proc = + f.fn = proc = echo f.id GC_fullcollect() diff --git a/tests/gc/gcbench.nim b/tests/gc/gcbench.nim index 44d952baa..72337911d 100644 --- a/tests/gc/gcbench.nim +++ b/tests/gc/gcbench.nim @@ -1,168 +1,168 @@ -discard """ - outputsub: "Success!" -""" - -# This is adapted from a benchmark written by John Ellis and Pete Kovac -# of Post Communications. -# It was modified by Hans Boehm of Silicon Graphics. -# -# This is no substitute for real applications. No actual application -# is likely to behave in exactly this way. However, this benchmark was -# designed to be more representative of real applications than other -# Java GC benchmarks of which we are aware. -# It attempts to model those properties of allocation requests that -# are important to current GC techniques. -# It is designed to be used either to obtain a single overall performance -# number, or to give a more detailed estimate of how collector -# performance varies with object lifetimes. It prints the time -# required to allocate and collect balanced binary trees of various -# sizes. Smaller trees result in shorter object lifetimes. Each cycle -# allocates roughly the same amount of memory. -# Two data structures are kept around during the entire process, so -# that the measured performance is representative of applications -# that maintain some live in-memory data. One of these is a tree -# containing many pointers. The other is a large array containing -# double precision floating point numbers. Both should be of comparable -# size. -# -# The results are only really meaningful together with a specification -# of how much memory was used. It is possible to trade memory for -# better time performance. This benchmark should be run in a 32 MB -# heap, though we don't currently know how to enforce that uniformly. -# -# Unlike the original Ellis and Kovac benchmark, we do not attempt -# measure pause times. This facility should eventually be added back -# in. There are several reasons for omitting it for now. The original -# implementation depended on assumptions about the thread scheduler -# that don't hold uniformly. The results really measure both the -# scheduler and GC. Pause time measurements tend to not fit well with -# current benchmark suites. As far as we know, none of the current -# commercial Java implementations seriously attempt to minimize GC pause -# times. -# -# Known deficiencies: -# - No way to check on memory use -# - No cyclic data structures -# - No attempt to measure variation with object size -# - Results are sensitive to locking cost, but we dont -# check for proper locking -# - -import - strutils, times - -type - PNode = ref TNode - TNode {.final.} = object - left, right: PNode - i, j: int - -proc newNode(L, r: PNode): PNode = - new(result) - result.left = L - result.right = r - -const - kStretchTreeDepth = 18 # about 16Mb - kLongLivedTreeDepth = 16 # about 4Mb - kArraySize = 500000 # about 4Mb - kMinTreeDepth = 4 - kMaxTreeDepth = 16 - -# Nodes used by a tree of a given size -proc TreeSize(i: int): int = return ((1 shl (i + 1)) - 1) - -# Number of iterations to use for a given tree depth -proc NumIters(i: int): int = - return 2 * TreeSize(kStretchTreeDepth) div TreeSize(i) - -# Build tree top down, assigning to older objects. -proc Populate(iDepth: int, thisNode: PNode) = - if iDepth <= 0: - return - else: - new(thisNode.left) - new(thisNode.right) - Populate(iDepth-1, thisNode.left) - Populate(iDepth-1, thisNode.right) - -# Build tree bottom-up -proc MakeTree(iDepth: int): PNode = - if iDepth <= 0: - new(result) - else: - return newNode(MakeTree(iDepth-1), MakeTree(iDepth-1)) - -proc PrintDiagnostics() = - echo("Total memory available: " & $getTotalMem() & " bytes") - echo("Free memory: " & $getFreeMem() & " bytes") - -proc TimeConstruction(depth: int) = - var - root, tempTree: PNode - iNumIters: int - - iNumIters = NumIters(depth) - - echo("Creating " & $iNumIters & " trees of depth " & $depth) - var t = epochTime() - for i in 0..iNumIters-1: - new(tempTree) - Populate(depth, tempTree) - tempTree = nil - echo("\tTop down construction took " & $(epochTime() - t) & "msecs") - t = epochTime() - for i in 0..iNumIters-1: - tempTree = MakeTree(depth) - tempTree = nil - echo("\tBottom up construction took " & $(epochTime() - t) & "msecs") - -type - tMyArray = seq[float] - -proc main() = - var - root, longLivedTree, tempTree: PNode - myarray: tMyArray - - echo("Garbage Collector Test") - echo(" Stretching memory with a binary tree of depth " & $kStretchTreeDepth) - PrintDiagnostics() - var t = epochTime() - - # Stretch the memory space quickly - tempTree = MakeTree(kStretchTreeDepth) - tempTree = nil - - # Create a long lived object - echo(" Creating a long-lived binary tree of depth " & - $kLongLivedTreeDepth) - new(longLivedTree) - Populate(kLongLivedTreeDepth, longLivedTree) - - # Create long-lived array, filling half of it - echo(" Creating a long-lived array of " & $kArraySize & " doubles") - newSeq(myarray, kArraySize) - for i in 0..kArraySize div 2 -1: - myarray[i] = 1.0 / toFloat(i) - - PrintDiagnostics() - - var d = kMinTreeDepth - while d <= kMaxTreeDepth: - TimeConstruction(d) - inc(d, 2) - - if longLivedTree == nil or myarray[1000] != 1.0/1000.0: - echo("Failed") - # fake reference to LongLivedTree - # and array to keep them from being optimized away - - var elapsed = epochTime() - t - PrintDiagnostics() - echo("Completed in " & $elapsed & "ms. Success!") +discard """ + outputsub: "Success!" +""" + +# This is adapted from a benchmark written by John Ellis and Pete Kovac +# of Post Communications. +# It was modified by Hans Boehm of Silicon Graphics. +# +# This is no substitute for real applications. No actual application +# is likely to behave in exactly this way. However, this benchmark was +# designed to be more representative of real applications than other +# Java GC benchmarks of which we are aware. +# It attempts to model those properties of allocation requests that +# are important to current GC techniques. +# It is designed to be used either to obtain a single overall performance +# number, or to give a more detailed estimate of how collector +# performance varies with object lifetimes. It prints the time +# required to allocate and collect balanced binary trees of various +# sizes. Smaller trees result in shorter object lifetimes. Each cycle +# allocates roughly the same amount of memory. +# Two data structures are kept around during the entire process, so +# that the measured performance is representative of applications +# that maintain some live in-memory data. One of these is a tree +# containing many pointers. The other is a large array containing +# double precision floating point numbers. Both should be of comparable +# size. +# +# The results are only really meaningful together with a specification +# of how much memory was used. It is possible to trade memory for +# better time performance. This benchmark should be run in a 32 MB +# heap, though we don't currently know how to enforce that uniformly. +# +# Unlike the original Ellis and Kovac benchmark, we do not attempt +# measure pause times. This facility should eventually be added back +# in. There are several reasons for omitting it for now. The original +# implementation depended on assumptions about the thread scheduler +# that don't hold uniformly. The results really measure both the +# scheduler and GC. Pause time measurements tend to not fit well with +# current benchmark suites. As far as we know, none of the current +# commercial Java implementations seriously attempt to minimize GC pause +# times. +# +# Known deficiencies: +# - No way to check on memory use +# - No cyclic data structures +# - No attempt to measure variation with object size +# - Results are sensitive to locking cost, but we dont +# check for proper locking +# + +import + strutils, times + +type + PNode = ref TNode + TNode {.final.} = object + left, right: PNode + i, j: int + +proc newNode(L, r: PNode): PNode = + new(result) + result.left = L + result.right = r + +const + kStretchTreeDepth = 18 # about 16Mb + kLongLivedTreeDepth = 16 # about 4Mb + kArraySize = 500000 # about 4Mb + kMinTreeDepth = 4 + kMaxTreeDepth = 16 + +# Nodes used by a tree of a given size +proc TreeSize(i: int): int = return ((1 shl (i + 1)) - 1) + +# Number of iterations to use for a given tree depth +proc NumIters(i: int): int = + return 2 * TreeSize(kStretchTreeDepth) div TreeSize(i) + +# Build tree top down, assigning to older objects. +proc Populate(iDepth: int, thisNode: PNode) = + if iDepth <= 0: + return + else: + new(thisNode.left) + new(thisNode.right) + Populate(iDepth-1, thisNode.left) + Populate(iDepth-1, thisNode.right) + +# Build tree bottom-up +proc MakeTree(iDepth: int): PNode = + if iDepth <= 0: + new(result) + else: + return newNode(MakeTree(iDepth-1), MakeTree(iDepth-1)) + +proc PrintDiagnostics() = + echo("Total memory available: " & $getTotalMem() & " bytes") + echo("Free memory: " & $getFreeMem() & " bytes") + +proc TimeConstruction(depth: int) = + var + root, tempTree: PNode + iNumIters: int + + iNumIters = NumIters(depth) + + echo("Creating " & $iNumIters & " trees of depth " & $depth) + var t = epochTime() + for i in 0..iNumIters-1: + new(tempTree) + Populate(depth, tempTree) + tempTree = nil + echo("\tTop down construction took " & $(epochTime() - t) & "msecs") + t = epochTime() + for i in 0..iNumIters-1: + tempTree = MakeTree(depth) + tempTree = nil + echo("\tBottom up construction took " & $(epochTime() - t) & "msecs") + +type + tMyArray = seq[float] + +proc main() = + var + root, longLivedTree, tempTree: PNode + myarray: tMyArray + + echo("Garbage Collector Test") + echo(" Stretching memory with a binary tree of depth " & $kStretchTreeDepth) + PrintDiagnostics() + var t = epochTime() + + # Stretch the memory space quickly + tempTree = MakeTree(kStretchTreeDepth) + tempTree = nil + + # Create a long lived object + echo(" Creating a long-lived binary tree of depth " & + $kLongLivedTreeDepth) + new(longLivedTree) + Populate(kLongLivedTreeDepth, longLivedTree) + + # Create long-lived array, filling half of it + echo(" Creating a long-lived array of " & $kArraySize & " doubles") + newSeq(myarray, kArraySize) + for i in 0..kArraySize div 2 -1: + myarray[i] = 1.0 / toFloat(i) + + PrintDiagnostics() + + var d = kMinTreeDepth + while d <= kMaxTreeDepth: + TimeConstruction(d) + inc(d, 2) + + if longLivedTree == nil or myarray[1000] != 1.0/1000.0: + echo("Failed") + # fake reference to LongLivedTree + # and array to keep them from being optimized away + + var elapsed = epochTime() - t + PrintDiagnostics() + echo("Completed in " & $elapsed & "ms. Success!") when defined(GC_setMaxPause): GC_setMaxPause 2_000 - -main() + +main() diff --git a/tests/gc/gcleak2.nim b/tests/gc/gcleak2.nim index 41d149bed..101421683 100644 --- a/tests/gc/gcleak2.nim +++ b/tests/gc/gcleak2.nim @@ -14,7 +14,7 @@ proc MakeObj(): TTestObj = result.x = "Hello" result.s = @[1,2,3] -proc inProc() = +proc inProc() = for i in 1 .. 1_000_000: when defined(gcMarkAndSweep): GC_fullcollect() diff --git a/tests/gc/gcleak4.nim b/tests/gc/gcleak4.nim index 54e74ac7b..d93a13854 100644 --- a/tests/gc/gcleak4.nim +++ b/tests/gc/gcleak4.nim @@ -14,7 +14,7 @@ type TPlusExpr = object of TExpr a, b: ref TExpr op2: string - + method eval(e: ref TExpr): int = # override this base method quit "to override!" @@ -30,7 +30,7 @@ proc newLit(x: int): ref TLiteral = {.watchpoint: result.} result.x = x result.op1 = $getOccupiedMem() - + proc newPlus(a, b: ref TExpr): ref TPlusExpr = new(result) {.watchpoint: result.} diff --git a/tests/gc/gcleak5.nim b/tests/gc/gcleak5.nim index 9e2948729..6ab50e19e 100644 --- a/tests/gc/gcleak5.nim +++ b/tests/gc/gcleak5.nim @@ -11,12 +11,12 @@ proc main = var t = getTime() var g = t.getGMTime() #echo isOnStack(addr g) - + if i mod 100 == 0: let om = getOccupiedMem() #echo "memory: ", om if om > 100_000: quit "leak" - + inc(i) sleep(1) diff --git a/tests/gc/refarrayleak.nim b/tests/gc/refarrayleak.nim index 12c9145f8..57b489721 100644 --- a/tests/gc/refarrayleak.nim +++ b/tests/gc/refarrayleak.nim @@ -28,7 +28,7 @@ proc newArrayHolder: ref TArrayHolder = proc loop = for i in 0..10000: discard newArrayHolder() - + if getOccupiedMem() > 300_000: echo "still a leak! ", getOccupiedMem() quit 1 diff --git a/tests/generics/t1056.nim b/tests/generics/t1056.nim index b1fe25894..de8bde8ef 100644 --- a/tests/generics/t1056.nim +++ b/tests/generics/t1056.nim @@ -17,7 +17,7 @@ proc echoMatrix(a: TMatrix) = proc echoMat2(a: TMat2) = echo TMat2.M - + var m = TMatrix[3,3,int](data: [1,2,3,4,5,6,7,8,9]) echoMatrix m diff --git a/tests/generics/t1789.nim b/tests/generics/t1789.nim index 188db88f6..c3fe336af 100644 --- a/tests/generics/t1789.nim +++ b/tests/generics/t1789.nim @@ -38,7 +38,7 @@ type proc `[]`*[N, T](f: Bar[N, T], n: range[0..(N - 1)]): T = assert high(n) == N-1 result = f.bar[n] - + var b: Bar[3, int] echo b[2] diff --git a/tests/generics/tconfusing_arrow.nim b/tests/generics/tconfusing_arrow.nim index 6a5a9d682..f63a874e0 100644 --- a/tests/generics/tconfusing_arrow.nim +++ b/tests/generics/tconfusing_arrow.nim @@ -5,7 +5,7 @@ type Deck = object proc sort(h: var seq[Deck]) = # works: - h.sort(proc (x, y: Deck): auto = + h.sort(proc (x, y: Deck): auto = cmp(x.value, y.value)) # fails: h.sort((x, y: Deck) => cmp(ord(x.value), ord(y.value))) diff --git a/tests/generics/tdictdestruct.nim b/tests/generics/tdictdestruct.nim index 17ded4853..228d93e66 100644 --- a/tests/generics/tdictdestruct.nim +++ b/tests/generics/tdictdestruct.nim @@ -13,8 +13,8 @@ proc destroyDict[TK, TV](a: PDict[TK, TV]) = proc newDict[TK, TV](a: TK, b: TV): PDict[TK, TV] = fakeNew(result, destroyDict[TK, TV]) -# Problem: destroyDict is not instantiated when newDict is instantiated! +# Problem: destroyDict is not instantiated when newDict is instantiated! -discard newDict("a", "b") +discard newDict("a", "b") diff --git a/tests/generics/texplicitgeneric1.nim b/tests/generics/texplicitgeneric1.nim index d54044368..ac0197c1a 100644 --- a/tests/generics/texplicitgeneric1.nim +++ b/tests/generics/texplicitgeneric1.nim @@ -5,33 +5,33 @@ discard """ # test explicit type instantiation type - TDict*[TKey, TValue] = object + TDict*[TKey, TValue] = object data: seq[tuple[k: TKey, v: TValue]] PDict*[TKey, #with `==`(a, b: TKey): bool - # hash(a: TKey): int, + # hash(a: TKey): int, TValue] = ref TDict[TKey, TValue] - -proc newDict*[TKey, TValue](): PDict[TKey, TValue] = + +proc newDict*[TKey, TValue](): PDict[TKey, TValue] = new(result) result.data = @[] - -proc add*[TKey, TValue](d: PDict[TKey, TValue], k: TKey, v: TValue) = + +proc add*[TKey, TValue](d: PDict[TKey, TValue], k: TKey, v: TValue) = d.data.add((k, v)) - -iterator items*[Tkey, TValue](d: PDict[TKey, TValue]): tuple[k: TKey, - v: TValue] = + +iterator items*[Tkey, TValue](d: PDict[TKey, TValue]): tuple[k: TKey, + v: TValue] = for k, v in items(d.data): yield (k, v) - + var d = newDict[int, string]() d.add(12, "12") d.add(13, "13") -for k, v in items(d): +for k, v in items(d): stdout.write("Key: ", $k, " value: ", v) var c = newDict[char, string]() c.add('A', "12") c.add('B', "13") -for k, v in items(c): +for k, v in items(c): stdout.write(" Key: ", $k, " value: ", v) diff --git a/tests/generics/texplicitgeneric2.nim b/tests/generics/texplicitgeneric2.nim index 95461d023..c4af17b7b 100644 --- a/tests/generics/texplicitgeneric2.nim +++ b/tests/generics/texplicitgeneric2.nim @@ -6,30 +6,30 @@ discard """ # test explicit type instantiation type - TDict*[TKey, TValue] = object + TDict*[TKey, TValue] = object data: seq[tuple[k: TKey, v: TValue]] PDict*[TKey, TValue] = ref TDict[TKey, TValue] - -proc newDict*[TKey, TValue](): PDict[TKey, TValue] = + +proc newDict*[TKey, TValue](): PDict[TKey, TValue] = new(result) result.data = @[] - -proc add*(d: PDict, k: TKey, v: TValue) = - d.data.add((k, v)) - -#iterator items*(d: PDict): tuple[k: TKey, v: TValue] = +proc add*(d: PDict, k: TKey, v: TValue) = + d.data.add((k, v)) + + +#iterator items*(d: PDict): tuple[k: TKey, v: TValue] = # for k, v in items(d.data): yield (k, v) - + var d = newDict[int, string]() d.add(12, "12") d.add(13, "13") -for k, v in items(d): +for k, v in items(d): stdout.write("Key: ", $k, " value: ", v) var c = newDict[char, string]() c.add('A', "12") c.add('B', "13") -for k, v in items(c): +for k, v in items(c): stdout.write(" Key: ", $k, " value: ", v) diff --git a/tests/generics/tgeneric1.nim b/tests/generics/tgeneric1.nim index 5d20a864b..5349f8f1d 100644 --- a/tests/generics/tgeneric1.nim +++ b/tests/generics/tgeneric1.nim @@ -9,7 +9,7 @@ type TBinHeap[T] = object heap: seq[TNode[T]] last: int - + PBinHeap[T] = ref TBinHeap[T] proc newBinHeap*[T](heap: var PBinHeap[T], size: int) = @@ -17,7 +17,7 @@ proc newBinHeap*[T](heap: var PBinHeap[T], size: int) = heap.last = 0 newSeq(heap.heap, size) #newSeq(heap.seq, size) - + proc parent(elem: int): int {.inline.} = return (elem-1) div 2 diff --git a/tests/generics/tgenericdefaults.nim b/tests/generics/tgenericdefaults.nim index ad96f1851..a4c90a884 100644 --- a/tests/generics/tgenericdefaults.nim +++ b/tests/generics/tgenericdefaults.nim @@ -1,4 +1,4 @@ -type +type TFoo[T, U, R = int] = object x: T y: U @@ -12,7 +12,7 @@ static: assert type(x1.x) is int assert type(x1.y) is float assert type(x1.z) is int - + var x2: TFoo[string, R = float, U = seq[int]] static: diff --git a/tests/generics/tgenericmatcher.nim b/tests/generics/tgenericmatcher.nim index edd0c4cf1..2edf46187 100644 --- a/tests/generics/tgenericmatcher.nim +++ b/tests/generics/tgenericmatcher.nim @@ -16,7 +16,7 @@ type min, max: int PMatcher[T] = ref TMatcher[T] -var +var m: PMatcher[int] diff --git a/tests/generics/tgenericmatcher2.nim b/tests/generics/tgenericmatcher2.nim index aa2f9dbb3..6832f80b7 100644 --- a/tests/generics/tgenericmatcher2.nim +++ b/tests/generics/tgenericmatcher2.nim @@ -12,7 +12,7 @@ type matcher: ref TMatcher[T] min, max: int -var +var m: ref TMatcher[int] diff --git a/tests/generics/tgenericrefs.nim b/tests/generics/tgenericrefs.nim index a44b96af9..245789caf 100644 --- a/tests/generics/tgenericrefs.nim +++ b/tests/generics/tgenericrefs.nim @@ -1,4 +1,4 @@ -type +type PA[T] = ref TA[T] TA[T] = object field: T @@ -20,18 +20,18 @@ foo 23 when false: # Compiles unless you use var a: PA[string] - type + type PA = ref TA TA[T] = object # Cannot instantiate: - type + type TA[T] = object a: PA[T] PA[T] = ref TA[T] - type + type PA[T] = ref TA[T] TA[T] = object diff --git a/tests/generics/tgenericshardcases.nim b/tests/generics/tgenericshardcases.nim index e3b805db6..72a2f4ec2 100644 --- a/tests/generics/tgenericshardcases.nim +++ b/tests/generics/tgenericshardcases.nim @@ -7,7 +7,7 @@ import typetraits proc typeNameLen(x: typedesc): int {.compileTime.} = result = x.name.len - + macro selectType(a, b: typedesc): typedesc = result = a @@ -33,7 +33,7 @@ static: assert high(f1.data2) == 5 # length of MyEnum minus one, because we used T.high assert high(f2.data1) == 126 - assert high(f2.data2) == 3 + assert high(f2.data2) == 3 assert high(f1.data3) == 6 # length of MyEnum assert high(f2.data3) == 4 # length of int8 diff --git a/tests/generics/tgenericvariant.nim b/tests/generics/tgenericvariant.nim index 0150cda8d..348d3da6e 100644 --- a/tests/generics/tgenericvariant.nim +++ b/tests/generics/tgenericvariant.nim @@ -1,4 +1,4 @@ -type +type TMaybe[T] = object case empty: bool of false: value: T diff --git a/tests/generics/tinferredgenericprocs.nim b/tests/generics/tinferredgenericprocs.nim index 12adfe965..5cbeabb94 100644 --- a/tests/generics/tinferredgenericprocs.nim +++ b/tests/generics/tinferredgenericprocs.nim @@ -8,7 +8,7 @@ discard """ # https://github.com/Araq/Nim/issues/797 proc foo[T](s:T):string = $s -type IntStringProc = proc(x: int): string +type IntStringProc = proc(x: int): string var f1 = IntStringProc(foo) var f2: proc(x: int): string = foo diff --git a/tests/generics/tthread_generic.nim b/tests/generics/tthread_generic.nim index fdd11d9d1..d34b24628 100644 --- a/tests/generics/tthread_generic.nim +++ b/tests/generics/tthread_generic.nim @@ -13,7 +13,7 @@ proc handleThreadFunc(arg: TThreadFuncArgs[int]){.thread.} = var output = fn() callback(output) -proc `@||->`*[T](fn: proc(): T {.thread.}, +proc `@||->`*[T](fn: proc(): T {.thread.}, callback: proc(val: T){.thread.}): TThread[TThreadFuncArgs[T]] = var thr: TThread[TThreadFuncArgs[T]] var args: TThreadFuncArgs[T] @@ -31,7 +31,7 @@ when isMainModule: return 1 proc callbackFunc(val: int) {.thread.} = echo($(val)) - + var thr = (testFunc @||-> callbackFunc) echo("test") joinThread(thr) diff --git a/tests/generics/twrong_field_caching.nim b/tests/generics/twrong_field_caching.nim index 595c58eb7..667ffbbe5 100644 --- a/tests/generics/twrong_field_caching.nim +++ b/tests/generics/twrong_field_caching.nim @@ -13,10 +13,10 @@ x32: 3x2 (3x2)''' type RectArray*[R, C: static[int], T] = distinct array[R * C, T] - + var a23: RectArray[2, 3, int] var a32: RectArray[3, 2, int] - + echo "a23: ", a23.R, "x", a23.C echo "a32: ", a32.R, "x", a32.C @@ -34,8 +34,8 @@ echo "t32: ", t32.R, "x", t32.C # Output: # t32: 3x2 - - + + # Everything is still OK. Now let's use the rectangular array inside another # generic type: type @@ -62,7 +62,7 @@ var x32 = x23.transpose echo "x23: ", x23.R, "x", x23.C, " (", x23.theArray.R, "x", x23.theArray.C, ")" echo "x32: ", x32.R, "x", x32.C, " (", x32.theArray.R, "x", x32.theArray.C, ")" - + # Output: # x23: 2x3 (2x3) # x32: 3x2 (3x2) <--- this is incorrect. R and C do not match! diff --git a/tests/generics/twrong_floatlit_type.nim b/tests/generics/twrong_floatlit_type.nim index 2db8b4353..c1830cd5a 100644 --- a/tests/generics/twrong_floatlit_type.nim +++ b/tests/generics/twrong_floatlit_type.nim @@ -35,48 +35,48 @@ proc translation*[T](p: Vector2D[T]): Matrix2x3[T] = proc scale*[T](v: Vector2D[T]): Matrix2x3[T] = Matrix2x3[T]([v.x, T(0.0), T(0.0), T(0.0), v.y, T(0.0)]) -proc rotation*[T](th: T): Matrix2x3[T] = - let +proc rotation*[T](th: T): Matrix2x3[T] = + let c = T(cos(th.float)) s = T(sin(th.float)) - + Matrix2x3[T]([c, -s, T(0.0), s, c, T(0.0)]) - -proc `*`*[T](a, b: Matrix2x3[T]): Matrix2x3[T] = + +proc `*`*[T](a, b: Matrix2x3[T]): Matrix2x3[T] = # Here we pretend that row 3 is [0,0,0,1] without # actually storing it in the matrix. - Matrix2x3[T]([a.M11*b.M11 + a.M12*b.M21, - a.M11*b.M12 + a.M12*b.M22, - a.M11*b.M13 + a.M12*b.M23 + a.M13, - + Matrix2x3[T]([a.M11*b.M11 + a.M12*b.M21, + a.M11*b.M12 + a.M12*b.M22, + a.M11*b.M13 + a.M12*b.M23 + a.M13, + a.M21*b.M11 + a.M22*b.M21, a.M21*b.M12 + a.M22*b.M22, a.M21*b.M13 + a.M22*b.M23 + a.M23]) - -proc `*`*[T](a: Matrix2x3[T], p: Point2D[T]): Point2D[T] = - let + +proc `*`*[T](a: Matrix2x3[T], p: Point2D[T]): Point2D[T] = + let x = a.M11*p.x + a.M12*p.y + a.M13 y = a.M21*p.x + a.M22*p.y + a.M23 - + Point2D[T](x: x, y: y) - + # making these so things like "line" that need a constructor don't stick out. # 2x2 determinant: |a b| # |c d| = ad - bc - + # String rendering # -template ff[S](x: S): string = +template ff[S](x: S): string = formatFloat(float(x), ffDefault, 0) - -proc `$`*[S](p: Point2D[S]): string = + +proc `$`*[S](p: Point2D[S]): string = "P($1, $2)" % [ff(p.x), ff(p.y)] - -proc `$`*[S](p: Vector2D[S]): string = + +proc `$`*[S](p: Vector2D[S]): string = "V($1, $2)" % [ff(p.x), ff(p.y)] - + proc `$`*[S](m: Matrix2x3[S]): string = - "M($1 $2 $3/$4 $5 $6)" % [ff(m.M11), ff(m.M12), ff(m.M13), + "M($1 $2 $3/$4 $5 $6)" % [ff(m.M11), ff(m.M12), ff(m.M13), ff(m.M21), ff(m.M22), ff(m.M23)] # @@ -102,7 +102,7 @@ proc `/`*[S](v: Vector2D[S], sc: S): Vector2D[S] = proc `/`*[S](sc: S; v: Vector2D[S]): Vector2D[S] = Vector2D[S](x: sc/v.x, y: sc/v.y) -proc `/`*[S](a, b: Vector2D[S]): Vector2D[S] = +proc `/`*[S](a, b: Vector2D[S]): Vector2D[S] = Vector2D[S](x: a.x/b.x, y: a.y/b.y) #proc vec[S](x, y: S): Vector2D[S] proc vec[S](x, y: S): Vector2D[S] = diff --git a/tests/global/globalaux.nim b/tests/global/globalaux.nim index 5f6f72721..951472695 100644 --- a/tests/global/globalaux.nim +++ b/tests/global/globalaux.nim @@ -1,4 +1,4 @@ -type +type TObj*[T] = object val*: T diff --git a/tests/init/tuninit1.nim b/tests/init/tuninit1.nim index 57443a7d3..886a1d766 100644 --- a/tests/init/tuninit1.nim +++ b/tests/init/tuninit1.nim @@ -11,15 +11,15 @@ proc p = var x, y, z: int if stdin.readLine == "true": x = 34 - + while false: y = 999 break - + while true: if x == 12: break y = 9999 - + try: z = parseInt("1233") except E_Base: @@ -32,5 +32,5 @@ proc p = x = 3111 z = 0 echo x, y, z - + p() diff --git a/tests/iter/tcountup.nim b/tests/iter/tcountup.nim index e68a614b0..1559041aa 100644 --- a/tests/iter/tcountup.nim +++ b/tests/iter/tcountup.nim @@ -3,11 +3,11 @@ discard """ output: "0123456789" """ -# Test new countup and unary < +# Test new countup and unary < -for i in 0 .. < 10'i64: +for i in 0 .. < 10'i64: stdout.write(i) - + #OUT 0123456789 diff --git a/tests/iter/titer.nim b/tests/iter/titer.nim index 19a11dc4e..c4143ae4f 100644 --- a/tests/iter/titer.nim +++ b/tests/iter/titer.nim @@ -1,44 +1,44 @@ -# Test the new iterators - -iterator xrange(fromm, to: int, step = 1): int = - var a = fromm - while a <= to: - yield a - inc(a, step) - -iterator interval[T](a, b: T): T = - var x = a - while x <= b: - yield x - inc(x) - -# -#iterator lines(filename: string): (line: string) = -# var -# f: tTextfile -# shouldClose = open(f, filename) -# if shouldClose: -# setSpace(line, 256) -# while readTextLine(f, line): -# yield line -# finally: -# if shouldClose: close(f) -# - -for i in xrange(0, 5): - for k in xrange(1, 7): - write(stdout, "test") - -for j in interval(45, 45): - write(stdout, "test2!") - write(stdout, "test3?") - -for x in items(["hi", "what's", "your", "name"]): - echo(x) - -const - stringArray = ["hi", "what's", "your", "name"] - -for i in 0..len(stringArray)-1: - echo(stringArray[i]) - +# Test the new iterators + +iterator xrange(fromm, to: int, step = 1): int = + var a = fromm + while a <= to: + yield a + inc(a, step) + +iterator interval[T](a, b: T): T = + var x = a + while x <= b: + yield x + inc(x) + +# +#iterator lines(filename: string): (line: string) = +# var +# f: tTextfile +# shouldClose = open(f, filename) +# if shouldClose: +# setSpace(line, 256) +# while readTextLine(f, line): +# yield line +# finally: +# if shouldClose: close(f) +# + +for i in xrange(0, 5): + for k in xrange(1, 7): + write(stdout, "test") + +for j in interval(45, 45): + write(stdout, "test2!") + write(stdout, "test3?") + +for x in items(["hi", "what's", "your", "name"]): + echo(x) + +const + stringArray = ["hi", "what's", "your", "name"] + +for i in 0..len(stringArray)-1: + echo(stringArray[i]) + diff --git a/tests/iter/titer6.nim b/tests/iter/titer6.nim index 2abfa0860..b7c8fee80 100644 --- a/tests/iter/titer6.nim +++ b/tests/iter/titer6.nim @@ -22,16 +22,16 @@ iterator tokenize2(s: string, seps: set[char] = Whitespace): tuple[ i = j for word, isSep in tokenize2("ta da", WhiteSpace): - var titer2TestVar = 0 + var titer2TestVar = 0 stdout.write(titer2TestVar) -proc wordWrap2(s: string, maxLineWidth = 80, +proc wordWrap2(s: string, maxLineWidth = 80, splitLongWords = true, seps: set[char] = Whitespace, - newLine = "\n"): string = + newLine = "\n"): string = result = "" for word, isSep in tokenize2(s, seps): - var w = 0 + var w = 0 diff --git a/tests/iter/titer8.nim b/tests/iter/titer8.nim index 3bc01122f..7b6d7b6de 100644 --- a/tests/iter/titer8.nim +++ b/tests/iter/titer8.nim @@ -55,7 +55,7 @@ echo "" proc inProc() = for c in count3(): echo c - + for word, isSep in tokenize2("ta da", WhiteSpace): stdout.write(word) @@ -69,7 +69,7 @@ inProc() iterator count0(): int {.closure.} = # note: doesn't require anything in its closure (except 'state') yield 0 - + iterator count2(): int {.closure.} = # note: requires 'x' in its closure var x = 1 diff --git a/tests/iter/titer_no_tuple_unpack.nim b/tests/iter/titer_no_tuple_unpack.nim index da5e1bc46..13ec11bd6 100644 --- a/tests/iter/titer_no_tuple_unpack.nim +++ b/tests/iter/titer_no_tuple_unpack.nim @@ -1,13 +1,13 @@ - -iterator xrange(fromm, to: int, step = 1): tuple[x, y: int] = - var a = fromm - while a <= to: - yield (a, a+1) - inc(a, step) + +iterator xrange(fromm, to: int, step = 1): tuple[x, y: int] = + var a = fromm + while a <= to: + yield (a, a+1) + inc(a, step) for a, b in xrange(3, 7): echo a, " ", b - + for tup in xrange(3, 7): echo tup diff --git a/tests/js.nim b/tests/js.nim index e5e432366..92cb130bd 100644 --- a/tests/js.nim +++ b/tests/js.nim @@ -20,5 +20,5 @@ proc OnButtonClick() {.exportc.} = var x = parseInt(v) echo x*x -proc OnLoad() {.exportc.} = +proc OnLoad() {.exportc.} = echo "Welcome! Please take your time to fill in this formular!" diff --git a/tests/js/test2.nim b/tests/js/test2.nim index 1a42fbfda..f6976d058 100644 --- a/tests/js/test2.nim +++ b/tests/js/test2.nim @@ -6,14 +6,14 @@ js 3.14 # This file tests the JavaScript generator -# #335 +# #335 proc foo() = var bar = "foo" proc baz() = echo bar baz() foo() - + # #376 when not defined(JS): proc foo(val: float): string = "no js " & $val diff --git a/tests/lexer/thexlit.nim b/tests/lexer/thexlit.nim index 04a530c9c..2b7f0a40e 100644 --- a/tests/lexer/thexlit.nim +++ b/tests/lexer/thexlit.nim @@ -9,4 +9,4 @@ if t==0x950412DE: echo "equal" else: echo "not equal" - + diff --git a/tests/lexer/thexrange.nim b/tests/lexer/thexrange.nim index e5e4c10c6..461e41dfd 100644 --- a/tests/lexer/thexrange.nim +++ b/tests/lexer/thexrange.nim @@ -1,7 +1,7 @@ type TArray = array[0x0012..0x0013, int] - + var a: TArray echo a[0x0012] #OUT 0 diff --git a/tests/lexer/tident.nim b/tests/lexer/tident.nim index 1ed9894c6..68cc01e70 100644 --- a/tests/lexer/tident.nim +++ b/tests/lexer/tident.nim @@ -1,12 +1,12 @@ type - TIdObj* = object of TObject - id*: int # unique id; use this for comparisons and not the pointers - - PIdObj* = ref TIdObj - PIdent* = ref TIdent - TIdent*{.acyclic.} = object - s*: string + TIdObj* = object of TObject + id*: int # unique id; use this for comparisons and not the pointers + + PIdObj* = ref TIdObj + PIdent* = ref TIdent + TIdent*{.acyclic.} = object + s*: string proc myNewString(L: int): string {.inline.} = result = newString(L) @@ -15,8 +15,8 @@ proc myNewString(L: int): string {.inline.} = for i in 0..L-1: if result[i] == '\0': echo("Correct") - else: + else: echo("Wrong") - + var s = myNewString(8) diff --git a/tests/lexer/tind1.nim b/tests/lexer/tind1.nim index f3fd952cc..6a975d5be 100644 --- a/tests/lexer/tind1.nim +++ b/tests/lexer/tind1.nim @@ -17,7 +17,7 @@ mymacro: echo "test" else: echo "else part" - + if 4 == 3: echo "bug" diff --git a/tests/lexer/tlexer.nim b/tests/lexer/tlexer.nim index 1dca6d9d0..e36220e7a 100644 --- a/tests/lexer/tlexer.nim +++ b/tests/lexer/tlexer.nim @@ -1,60 +1,60 @@ -discard """ - disabled: true -""" - -# We start with a comment -# This is the same comment - -# This is a new one! - -import - lexbase, os, strutils - -type - TMyRec {.final.} = object - x, y: int # coordinates - c: char # a character - a: int32 # an integer - - PMyRec = ref TMyRec # a reference to `TMyRec` - -proc splitText(txt: string): seq[string] # splits a text into several lines - # the comment continues here - # this is not easy to parse! - -proc anotherSplit(txt: string): seq[string] = - # the comment should belong to `anotherSplit`! - # another problem: comments are statements! - -const - x = 0B0_10001110100_0000101001000111101011101111111011000101001101001001'f64 # x ~~ 1.72826e35 - myNan = 0B01111111100000101100000000001000'f32 # NAN - y = """ - a rather long text. - Over many - lines. - """ - s = "\xff" - a = {0..234} - b = {0..high(int)} - v = 0'i32 - z = 6767566'f32 - -# small test program for lexbase - -proc main*(infile: string, a, b: int, someverylongnamewithtype = 0, - anotherlongthingie = 3) = - var - myInt: int = 0 - s: seq[string] - # this should be an error! - if initBaseLexer(L, infile, 30): nil - else: - writeLine(stdout, "could not open: " & infile) - writeLine(stdout, "Success!") - call(3, # we use 3 - 12, # we use 12 - 43) # we use 43 - - -main(ParamStr(1), 9, 0) +discard """ + disabled: true +""" + +# We start with a comment +# This is the same comment + +# This is a new one! + +import + lexbase, os, strutils + +type + TMyRec {.final.} = object + x, y: int # coordinates + c: char # a character + a: int32 # an integer + + PMyRec = ref TMyRec # a reference to `TMyRec` + +proc splitText(txt: string): seq[string] # splits a text into several lines + # the comment continues here + # this is not easy to parse! + +proc anotherSplit(txt: string): seq[string] = + # the comment should belong to `anotherSplit`! + # another problem: comments are statements! + +const + x = 0B0_10001110100_0000101001000111101011101111111011000101001101001001'f64 # x ~~ 1.72826e35 + myNan = 0B01111111100000101100000000001000'f32 # NAN + y = """ + a rather long text. + Over many + lines. + """ + s = "\xff" + a = {0..234} + b = {0..high(int)} + v = 0'i32 + z = 6767566'f32 + +# small test program for lexbase + +proc main*(infile: string, a, b: int, someverylongnamewithtype = 0, + anotherlongthingie = 3) = + var + myInt: int = 0 + s: seq[string] + # this should be an error! + if initBaseLexer(L, infile, 30): nil + else: + writeLine(stdout, "could not open: " & infile) + writeLine(stdout, "Success!") + call(3, # we use 3 + 12, # we use 12 + 43) # we use 43 + + +main(ParamStr(1), 9, 0) diff --git a/tests/lexer/tstrlits.nim b/tests/lexer/tstrlits.nim index 1cd43975a..f5b7ce937 100644 --- a/tests/lexer/tstrlits.nim +++ b/tests/lexer/tstrlits.nim @@ -6,9 +6,9 @@ discard """ const tripleEmpty = """"long string"""""""" # "long string """"" - + rawQuote = r"a""" - + raw = r"abc""def" stdout.write(rawQuote) diff --git a/tests/lexer/tunderscores.nim b/tests/lexer/tunderscores.nim index 8075fdae4..e718fb40a 100644 --- a/tests/lexer/tunderscores.nim +++ b/tests/lexer/tunderscores.nim @@ -3,7 +3,7 @@ discard """ line: 8 errormsg: "invalid token: _" """ -# Bug #502670 +# Bug #502670 var ef_ = 3 #ERROR_MSG invalid token: _ var a__b = 1 diff --git a/tests/lookups/tkoeniglookup.nim b/tests/lookups/tkoeniglookup.nim index 6c42798ae..8b140cceb 100644 --- a/tests/lookups/tkoeniglookup.nim +++ b/tests/lookups/tkoeniglookup.nim @@ -9,7 +9,7 @@ type TMyObj = object x, y: int -proc `$`*(a: TMyObj): string = +proc `$`*(a: TMyObj): string = result = "x: " & $a.x & " y: " & $a.y var a: TMyObj diff --git a/tests/lookups/tredef.nim b/tests/lookups/tredef.nim index a1647000c..8f1b38bd1 100644 --- a/tests/lookups/tredef.nim +++ b/tests/lookups/tredef.nim @@ -12,13 +12,13 @@ block: template foo(a: int, b: string) = discard foo(1, "test") bar(1, "test") - + proc baz = proc foo(a: int, b: string) = discard proc foo(b: string) = template bar(a: int, b: string) = discard bar(1, "test") - + foo("test") block: diff --git a/tests/macros/tclosuremacro.nim b/tests/macros/tclosuremacro.nim index d5d9b656c..cf51949ed 100644 --- a/tests/macros/tclosuremacro.nim +++ b/tests/macros/tclosuremacro.nim @@ -29,7 +29,7 @@ proc doWithOneAndTwo(f: (int, int) -> int): int = echo twoParams(proc (a, b): auto = a + b) echo twoParams((x, y) => x + y) -echo oneParam(x => x+5) +echo oneParam(x => x+5) echo noParams(() => 3) diff --git a/tests/macros/tmacro2.nim b/tests/macros/tmacro2.nim index 8515322d5..17f312925 100644 --- a/tests/macros/tmacro2.nim +++ b/tests/macros/tmacro2.nim @@ -4,7 +4,7 @@ discard """ import macros, strutils -proc testBlock(): string {.compileTime.} = +proc testBlock(): string {.compileTime.} = block myBlock: while true: echo "inner block" @@ -21,7 +21,7 @@ macro mac(n: expr): expr = s = s.replace("l", "!!") result = newStrLitNode("Your value sir: '$#'" % [s]) -const s = testBlock() +const s = testBlock() const t = mac("HEllo World") echo s, " ", t diff --git a/tests/macros/tmacrogenerics.nim b/tests/macros/tmacrogenerics.nim index b886f4fa5..919a15b46 100644 --- a/tests/macros/tmacrogenerics.nim +++ b/tests/macros/tmacrogenerics.nim @@ -16,7 +16,7 @@ macro makeBar(A, B: typedesc): typedesc = echo "instantiation ", counter, " with ", A.name, " and ", B.name result = A -type +type Bar[T, U] = makeBar(T, U) var bb1: Bar[int, float] diff --git a/tests/macros/tmacrostmt.nim b/tests/macros/tmacrostmt.nim index d9c70197d..23e2f358c 100644 --- a/tests/macros/tmacrostmt.nim +++ b/tests/macros/tmacrostmt.nim @@ -13,7 +13,7 @@ of r"[\+\-\*\?]+": return tkOperator else: return tkUnknown - + case_token: inc i #bug #488 diff --git a/tests/macros/tprintf.nim b/tests/macros/tprintf.nim index c8fb51cdc..94cbfbc2b 100644 --- a/tests/macros/tprintf.nim +++ b/tests/macros/tprintf.nim @@ -2,15 +2,15 @@ discard """ file: "tprintf.nim" output: "Andreas Rumpf" """ -# Test a printf proc - -proc printf(file: TFile, args: openarray[string]) = - var i = 0 - while i < args.len: - write(file, args[i]) - inc(i) - -printf(stdout, ["Andreas ", "Rumpf\n"]) -#OUT Andreas Rumpf +# Test a printf proc + +proc printf(file: TFile, args: openarray[string]) = + var i = 0 + while i < args.len: + write(file, args[i]) + inc(i) + +printf(stdout, ["Andreas ", "Rumpf\n"]) +#OUT Andreas Rumpf diff --git a/tests/macros/tquotewords.nim b/tests/macros/tquotewords.nim index 76b8d8af7..7a575f541 100644 --- a/tests/macros/tquotewords.nim +++ b/tests/macros/tquotewords.nim @@ -6,13 +6,13 @@ discard """ import macros -macro quoteWords(n: expr): expr {.immediate.} = +macro quoteWords(n: expr): expr {.immediate.} = let n = callsite() result = newNimNode(nnkBracket, n) for i in 1..n.len-1: expectKind(n[i], nnkIdent) result.add(toStrLit(n[i])) - + const myWordList = quoteWords(this, an, example) diff --git a/tests/macros/tstaticparamsmacro.nim b/tests/macros/tstaticparamsmacro.nim index 1ab638396..f6ecb3a9f 100644 --- a/tests/macros/tstaticparamsmacro.nim +++ b/tests/macros/tstaticparamsmacro.nim @@ -5,9 +5,9 @@ bb numbers 11 22 -AST a +AST a [(11, 22), (33, 44)] -AST b +AST b (e: [55, 66], f: [77, 88]) 55 10 diff --git a/tests/macros/tvtable.nim b/tests/macros/tvtable.nim index 3e3b9c0e6..cc5d7a5d9 100644 --- a/tests/macros/tvtable.nim +++ b/tests/macros/tvtable.nim @@ -17,7 +17,7 @@ type # an untyped table to store the proc pointers # it's also possible to use a strongly typed tuple here VTable = array[0..1, pointer] - + TBase = object {.inheritable.} vtbl: ptr VTable diff --git a/tests/magics/tlowhigh.nim b/tests/magics/tlowhigh.nim index d1cbd3272..4998b73dc 100644 --- a/tests/magics/tlowhigh.nim +++ b/tests/magics/tlowhigh.nim @@ -2,23 +2,23 @@ discard """ file: "tlowhigh.nim" output: "10" """ -# Test the magic low() and high() procs - -type - myEnum = enum e1, e2, e3, e4, e5 - -var - a: array [myEnum, int] - -for i in low(a) .. high(a): - a[i] = 0 - -proc sum(a: openarray[int]): int = - result = 0 - for i in low(a)..high(a): - inc(result, a[i]) - -write(stdout, sum([1, 2, 3, 4])) -#OUT 10 +# Test the magic low() and high() procs + +type + myEnum = enum e1, e2, e3, e4, e5 + +var + a: array [myEnum, int] + +for i in low(a) .. high(a): + a[i] = 0 + +proc sum(a: openarray[int]): int = + result = 0 + for i in low(a)..high(a): + inc(result, a[i]) + +write(stdout, sum([1, 2, 3, 4])) +#OUT 10 diff --git a/tests/manyloc/keineschweine/dependencies/chipmunk/chipmunk.nim b/tests/manyloc/keineschweine/dependencies/chipmunk/chipmunk.nim index 493a2106c..56d3edec4 100644 --- a/tests/manyloc/keineschweine/dependencies/chipmunk/chipmunk.nim +++ b/tests/manyloc/keineschweine/dependencies/chipmunk/chipmunk.nim @@ -1,15 +1,15 @@ # Copyright (c) 2007 Scott Lembcke -# +# # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: -# +# # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. -# +# # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -17,7 +17,7 @@ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -# +# const Lib = "libchipmunk.so.6.1.1" @@ -30,12 +30,12 @@ when defined(CpUseFloat): type CpFloat* = cfloat else: type CpFloat* = cdouble -const - CP_BUFFER_BYTES* = (32 * 1024) +const + CP_BUFFER_BYTES* = (32 * 1024) CP_MAX_CONTACTS_PER_ARBITER* = 4 CpInfinity*: CpFloat = 1.0/0 {.pragma: pf, pure, final.} -type +type Bool32* = cint #replace one day with cint-compatible bool CpDataPointer* = pointer TVector* {.final, pure.} = object @@ -44,12 +44,12 @@ type TBodyVelocityFunc* = proc(body: PBody, gravity: TVector, damping: CpFloat; dt: CpFloat){.cdecl.} TBodyPositionFunc* = proc(body: PBody; dt: CpFloat){.cdecl.} - TComponentNode*{.pf.} = object + TComponentNode*{.pf.} = object root*: PBody next*: PBody idleTime*: CpFloat - - THashValue = cuint # uintptr_t + + THashValue = cuint # uintptr_t TCollisionType* = cuint #uintptr_t TGroup * = cuint #uintptr_t TLayers* = cuint @@ -60,9 +60,9 @@ type PContact* = ptr TContact TContact*{.pure,final.} = object PArbiter* = ptr TArbiter - TArbiter*{.pf.} = object + TArbiter*{.pf.} = object e*: CpFloat - u*: CpFloat + u*: CpFloat surface_vr*: TVector a*: PShape b*: PShape @@ -77,7 +77,7 @@ type swappedColl*: Bool32 state*: TArbiterState PCollisionHandler* = ptr TCollisionHandler - TCollisionHandler*{.pf.} = object + TCollisionHandler*{.pf.} = object a*: TCollisionType b*: TCollisionType begin*: TCollisionBeginFunc @@ -85,26 +85,26 @@ type postSolve*: TCollisionPostSolveFunc separate*: TCollisionSeparateFunc data*: pointer - TArbiterState*{.size: sizeof(cint).} = enum + TArbiterState*{.size: sizeof(cint).} = enum ArbiterStateFirstColl, # Arbiter is active and its not the first collision. ArbiterStateNormal, # Collision has been explicitly ignored. # Either by returning false from a begin collision handler or calling cpArbiterIgnore(). ArbiterStateIgnore, # Collison is no longer active. A space will cache an arbiter for up to cpSpace.collisionPersistence more steps. ArbiterStateCached - TArbiterThread*{.pf.} = object + TArbiterThread*{.pf.} = object next*: PArbiter # Links to next and previous arbiters in the contact graph. prev*: PArbiter - - TContactPoint*{.pf.} = object + + TContactPoint*{.pf.} = object point*: TVector #/ The position of the contact point. normal*: TVector #/ The normal of the contact point. dist*: CpFloat #/ The depth of the contact point. #/ A struct that wraps up the important collision data for an arbiter. PContactPointSet* = ptr TContactPointSet - TContactPointSet*{.pf.} = object + TContactPointSet*{.pf.} = object count*: cint #/ The number of contact points in the set. points*: array[0..CP_MAX_CONTACTS_PER_ARBITER - 1, TContactPoint] #/ The array of contact points. - + #/ Collision begin event function callback type. #/ Returning false from a begin callback causes the collision to be ignored until #/ the the separate callback is called when the objects stop colliding. @@ -112,35 +112,35 @@ type cdecl.} #/ Collision pre-solve event function callback type. #/ Returning false from a pre-step callback causes the collision to be ignored until the next step. - TCollisionPreSolveFunc* = proc (arb: PArbiter; space: PSpace; + TCollisionPreSolveFunc* = proc (arb: PArbiter; space: PSpace; data: pointer): bool {.cdecl.} #/ Collision post-solve event function callback type. - TCollisionPostSolveFunc* = proc (arb: PArbiter; space: PSpace; + TCollisionPostSolveFunc* = proc (arb: PArbiter; space: PSpace; data: pointer){.cdecl.} #/ Collision separate event function callback type. - TCollisionSeparateFunc* = proc (arb: PArbiter; space: PSpace; + TCollisionSeparateFunc* = proc (arb: PArbiter; space: PSpace; data: pointer){.cdecl.} - + #/ Chipmunk's axis-aligned 2D bounding box type. (left, bottom, right, top) PBB* = ptr TBB - TBB* {.pf.} = object + TBB* {.pf.} = object l*, b*, r*, t*: CpFloat - + #/ Spatial index bounding box callback function type. #/ The spatial index calls this function and passes you a pointer to an object you added #/ when it needs to get the bounding box associated with that object. TSpatialIndexBBFunc* = proc (obj: pointer): TBB{.cdecl.} #/ Spatial index/object iterator callback function type. TSpatialIndexIteratorFunc* = proc (obj: pointer; data: pointer){.cdecl.} - #/ Spatial query callback function type. + #/ Spatial query callback function type. TSpatialIndexQueryFunc* = proc (obj1: pointer; obj2: pointer; data: pointer){. cdecl.} #/ Spatial segment query callback function type. - TSpatialIndexSegmentQueryFunc* = proc (obj1: pointer; obj2: pointer; + TSpatialIndexSegmentQueryFunc* = proc (obj1: pointer; obj2: pointer; data: pointer): CpFloat {.cdecl.} #/ private PSpatialIndex = ptr TSpatialIndex - TSpatialIndex{.pf.} = object + TSpatialIndex{.pf.} = object klass: PSpatialIndexClass bbfun: TSpatialIndexBBFunc staticIndex: PSpatialIndex @@ -148,31 +148,31 @@ type TSpatialIndexDestroyImpl* = proc (index: PSpatialIndex){.cdecl.} TSpatialIndexCountImpl* = proc (index: PSpatialIndex): cint{.cdecl.} - TSpatialIndexEachImpl* = proc (index: PSpatialIndex; + TSpatialIndexEachImpl* = proc (index: PSpatialIndex; fun: TSpatialIndexIteratorFunc; data: pointer){. cdecl.} - TSpatialIndexContainsImpl* = proc (index: PSpatialIndex; obj: pointer; + TSpatialIndexContainsImpl* = proc (index: PSpatialIndex; obj: pointer; hashid: THashValue): Bool32 {.cdecl.} - TSpatialIndexInsertImpl* = proc (index: PSpatialIndex; obj: pointer; + TSpatialIndexInsertImpl* = proc (index: PSpatialIndex; obj: pointer; hashid: THashValue){.cdecl.} - TSpatialIndexRemoveImpl* = proc (index: PSpatialIndex; obj: pointer; + TSpatialIndexRemoveImpl* = proc (index: PSpatialIndex; obj: pointer; hashid: THashValue){.cdecl.} TSpatialIndexReindexImpl* = proc (index: PSpatialIndex){.cdecl.} - TSpatialIndexReindexObjectImpl* = proc (index: PSpatialIndex; + TSpatialIndexReindexObjectImpl* = proc (index: PSpatialIndex; obj: pointer; hashid: THashValue){.cdecl.} - TSpatialIndexReindexQueryImpl* = proc (index: PSpatialIndex; + TSpatialIndexReindexQueryImpl* = proc (index: PSpatialIndex; fun: TSpatialIndexQueryFunc; data: pointer){.cdecl.} - TSpatialIndexPointQueryImpl* = proc (index: PSpatialIndex; point: TVector; - fun: TSpatialIndexQueryFunc; + TSpatialIndexPointQueryImpl* = proc (index: PSpatialIndex; point: TVector; + fun: TSpatialIndexQueryFunc; data: pointer){.cdecl.} - TSpatialIndexSegmentQueryImpl* = proc (index: PSpatialIndex; obj: pointer; - a: TVector; b: TVector; t_exit: CpFloat; fun: TSpatialIndexSegmentQueryFunc; + TSpatialIndexSegmentQueryImpl* = proc (index: PSpatialIndex; obj: pointer; + a: TVector; b: TVector; t_exit: CpFloat; fun: TSpatialIndexSegmentQueryFunc; data: pointer){.cdecl.} - TSpatialIndexQueryImpl* = proc (index: PSpatialIndex; obj: pointer; - bb: TBB; fun: TSpatialIndexQueryFunc; + TSpatialIndexQueryImpl* = proc (index: PSpatialIndex; obj: pointer; + bb: TBB; fun: TSpatialIndexQueryFunc; data: pointer){.cdecl.} PSpatialIndexClass* = ptr TSpatialIndexClass - TSpatialIndexClass*{.pf.} = object + TSpatialIndexClass*{.pf.} = object destroy*: TSpatialIndexDestroyImpl count*: TSpatialIndexCountImpl each*: TSpatialIndexEachImpl @@ -185,32 +185,32 @@ type pointQuery*: TSpatialIndexPointQueryImpl segmentQuery*: TSpatialIndexSegmentQueryImpl query*: TSpatialIndexQueryImpl - + PSpaceHash* = ptr TSpaceHash TSpaceHash* {.pf.} = object PBBTree* = ptr TBBTree TBBTree* {.pf.} = object PSweep1D* = ptr TSweep1D TSweep1D* {.pf.} = object - + #/ Bounding box tree velocity callback function. #/ This function should return an estimate for the object's velocity. TBBTreeVelocityFunc* = proc (obj: pointer): TVector {.cdecl.} - + PContactBufferHeader* = ptr TContentBufferHeader TContentBufferHeader* {.pf.} = object TSpaceArbiterApplyImpulseFunc* = proc (arb: PArbiter){.cdecl.} - + PSpace* = ptr TSpace TSpace* {.pf.} = object - iterations*: cint + iterations*: cint gravity*: TVector damping*: CpFloat - idleSpeedThreshold*: CpFloat - sleepTimeThreshold*: CpFloat - collisionSlop*: CpFloat + idleSpeedThreshold*: CpFloat + sleepTimeThreshold*: CpFloat + collisionSlop*: CpFloat collisionBias*: CpFloat - collisionPersistence*: TTimestamp + collisionPersistence*: TTimestamp enableContactGraph*: cint ##BOOL data*: pointer staticBody*: PBody @@ -232,24 +232,24 @@ type defaultHandler: TCollisionHandler postStepCallbacks: PHashSet arbiterApplyImpulse: TSpaceArbiterApplyImpulseFunc - staticBody2: TBody #_staticBody + staticBody2: TBody #_staticBody PBody* = ptr TBody - TBody*{.pf.} = object - velocityFunc*: TBodyVelocityFunc - positionFunc*: TBodyPositionFunc - m*: CpFloat - mInv*: CpFloat - i*: CpFloat - iInv*: CpFloat - p*: TVector - v*: TVector - f*: TVector - a*: CpFloat - w*: CpFloat - t*: CpFloat - rot*: TVector + TBody*{.pf.} = object + velocityFunc*: TBodyVelocityFunc + positionFunc*: TBodyPositionFunc + m*: CpFloat + mInv*: CpFloat + i*: CpFloat + iInv*: CpFloat + p*: TVector + v*: TVector + f*: TVector + a*: CpFloat + w*: CpFloat + t*: CpFloat + rot*: TVector data*: pointer - vLimit*: CpFloat + vLimit*: CpFloat wLimit*: CpFloat vBias*: TVector wBias*: CpFloat @@ -258,51 +258,51 @@ type arbiterList*: PArbiter constraintList*: PConstraint node*: TComponentNode - #/ Body/shape iterator callback function type. - TBodyShapeIteratorFunc* = proc (body: PBody; shape: PShape; + #/ Body/shape iterator callback function type. + TBodyShapeIteratorFunc* = proc (body: PBody; shape: PShape; data: pointer) {.cdecl.} - #/ Body/constraint iterator callback function type. - TBodyConstraintIteratorFunc* = proc (body: PBody; - constraint: PConstraint; + #/ Body/constraint iterator callback function type. + TBodyConstraintIteratorFunc* = proc (body: PBody; + constraint: PConstraint; data: pointer) {.cdecl.} - #/ Body/arbiter iterator callback function type. - TBodyArbiterIteratorFunc* = proc (body: PBody; arbiter: PArbiter; + #/ Body/arbiter iterator callback function type. + TBodyArbiterIteratorFunc* = proc (body: PBody; arbiter: PArbiter; data: pointer) {.cdecl.} - + PNearestPointQueryInfo* = ptr TNearestPointQueryInfo #/ Nearest point query info struct. TNearestPointQueryInfo*{.pf.} = object shape: PShape #/ The nearest shape, NULL if no shape was within range. p: TVector #/ The closest point on the shape's surface. (in world space coordinates) d: CpFloat #/ The distance to the point. The distance is negative if the point is inside the shape. - + PSegmentQueryInfo* = ptr TSegmentQueryInfo #/ Segment query info struct. - TSegmentQueryInfo*{.pf.} = object + TSegmentQueryInfo*{.pf.} = object shape*: PShape #/ The shape that was hit, NULL if no collision occurred. t*: CpFloat #/ The normalized distance along the query segment in the range [0, 1]. n*: TVector #/ The normal of the surface hit. - TShapeType*{.size: sizeof(cint).} = enum + TShapeType*{.size: sizeof(cint).} = enum CP_CIRCLE_SHAPE, CP_SEGMENT_SHAPE, CP_POLY_SHAPE, CP_NUM_SHAPES TShapeCacheDataImpl* = proc (shape: PShape; p: TVector; rot: TVector): TBB{.cdecl.} TShapeDestroyImpl* = proc (shape: PShape){.cdecl.} TShapePointQueryImpl* = proc (shape: PShape; p: TVector): Bool32 {.cdecl.} - TShapeSegmentQueryImpl* = proc (shape: PShape; a: TVector; b: TVector; + TShapeSegmentQueryImpl* = proc (shape: PShape; a: TVector; b: TVector; info: PSegmentQueryInfo){.cdecl.} PShapeClass* = ptr TShapeClass - TShapeClass*{.pf.} = object + TShapeClass*{.pf.} = object kind*: TShapeType cacheData*: TShapeCacheDataImpl destroy*: TShapeDestroyImpl pointQuery*: TShapePointQueryImpl segmentQuery*: TShapeSegmentQueryImpl PShape* = ptr TShape - TShape*{.pf.} = object + TShape*{.pf.} = object klass: PShapeClass #/ PRIVATE body*: PBody #/ The rigid body this collision shape is attached to. - bb*: TBB #/ The current bounding box of the shape. + bb*: TBB #/ The current bounding box of the shape. sensor*: Bool32 #/ Sensor flag. - #/ Sensor shapes call collision callbacks but don't produce collisions. + #/ Sensor shapes call collision callbacks but don't produce collisions. e*: CpFloat #/ Coefficient of restitution. (elasticity) u*: CpFloat #/ Coefficient of friction. surface_v*: TVector #/ Surface velocity used when solving for friction. @@ -336,29 +336,29 @@ type TSplittingPlane*{.pf.} = object n: TVector d: CpFloat - + #/ Post Step callback function type. TPostStepFunc* = proc (space: PSpace; obj: pointer; data: pointer){.cdecl.} #/ Point query callback function type. TSpacePointQueryFunc* = proc (shape: PShape; data: pointer){.cdecl.} #/ Segment query callback function type. - TSpaceSegmentQueryFunc* = proc (shape: PShape; t: CpFloat; n: TVector; + TSpaceSegmentQueryFunc* = proc (shape: PShape; t: CpFloat; n: TVector; data: pointer){.cdecl.} #/ Rectangle Query callback function type. TSpaceBBQueryFunc* = proc (shape: PShape; data: pointer){.cdecl.} #/ Shape query callback function type. - TSpaceShapeQueryFunc* = proc (shape: PShape; points: PContactPointSet; + TSpaceShapeQueryFunc* = proc (shape: PShape; points: PContactPointSet; data: pointer){.cdecl.} #/ Space/body iterator callback function type. TSpaceBodyIteratorFunc* = proc (body: PBody; data: pointer){.cdecl.} #/ Space/body iterator callback function type. TSpaceShapeIteratorFunc* = proc (shape: PShape; data: pointer){.cdecl.} #/ Space/constraint iterator callback function type. - TSpaceConstraintIteratorFunc* = proc (constraint: PConstraint; + TSpaceConstraintIteratorFunc* = proc (constraint: PConstraint; data: pointer){.cdecl.} #/ Opaque cpConstraint struct. PConstraint* = ptr TConstraint - TConstraint*{.pf.} = object + TConstraint*{.pf.} = object klass: PConstraintClass #/PRIVATE a*: PBody #/ The first body connected to this constraint. b*: PBody #/ The second body connected to this constraint. @@ -367,7 +367,7 @@ type next_b: PConstraint #/PRIVATE maxForce*: CpFloat #/ The maximum force that this constraint is allowed to use. Defaults to infinity. errorBias*: CpFloat #/ The rate at which joint error is corrected. Defaults to pow(1.0 - 0.1, 60.0) meaning that it will correct 10% of the error every 1/60th of a second. - maxBias*: CpFloat #/ The maximum rate at which joint error is corrected. Defaults to infinity. + maxBias*: CpFloat #/ The maximum rate at which joint error is corrected. Defaults to infinity. preSolve*: TConstraintPreSolveFunc #/ Function called before the solver runs. Animate your joint anchors, update your motor torque, etc. postSolve*: TConstraintPostSolveFunc #/ Function called after the solver runs. Use the applied impulse to perform effects like breakable joints. data*: CpDataPointer # User definable data pointer. Generally this points to your the game object class so you can access it when given a cpConstraint reference in a callback. @@ -376,7 +376,7 @@ type TConstraintApplyImpulseImpl = proc (constraint: PConstraint){.cdecl.} TConstraintGetImpulseImpl = proc (constraint: PConstraint): CpFloat{.cdecl.} PConstraintClass = ptr TConstraintClass - TConstraintClass{.pf.} = object + TConstraintClass{.pf.} = object preStep*: TConstraintPreStepImpl applyCachedImpulse*: TConstraintApplyCachedImpulseImpl applyImpulse*: TConstraintApplyImpulseImpl @@ -427,29 +427,29 @@ defGetter(PSpace, CpFloat, currDt, CurrentTimeStep) #/ returns true from inside a callback and objects cannot be added/removed. -proc isLocked*(space: PSpace): bool{.inline.} = +proc isLocked*(space: PSpace): bool{.inline.} = result = space.locked.bool #/ Set a default collision handler for this space. #/ The default collision handler is invoked for each colliding pair of shapes #/ that isn't explicitly handled by a specific collision handler. #/ You can pass NULL for any function you don't want to implement. -proc setDefaultCollisionHandler*(space: PSpace; begin: TCollisionBeginFunc; - preSolve: TCollisionPreSolveFunc; - postSolve: TCollisionPostSolveFunc; - separate: TCollisionSeparateFunc; +proc setDefaultCollisionHandler*(space: PSpace; begin: TCollisionBeginFunc; + preSolve: TCollisionPreSolveFunc; + postSolve: TCollisionPostSolveFunc; + separate: TCollisionSeparateFunc; data: pointer){. cdecl, importc: "cpSpaceSetDefaultCollisionHandler", dynlib: Lib.} #/ Set a collision handler to be used whenever the two shapes with the given collision types collide. #/ You can pass NULL for any function you don't want to implement. -proc addCollisionHandler*(space: PSpace; a, b: TCollisionType; - begin: TCollisionBeginFunc; - preSolve: TCollisionPreSolveFunc; - postSolve: TCollisionPostSolveFunc; +proc addCollisionHandler*(space: PSpace; a, b: TCollisionType; + begin: TCollisionBeginFunc; + preSolve: TCollisionPreSolveFunc; + postSolve: TCollisionPostSolveFunc; separate: TCollisionSeparateFunc; data: pointer){. cdecl, importc: "cpSpaceAddCollisionHandler", dynlib: Lib.} #/ Unset a collision handler. -proc removeCollisionHandler*(space: PSpace; a: TCollisionType; +proc removeCollisionHandler*(space: PSpace; a: TCollisionType; b: TCollisionType){. cdecl, importc: "cpSpaceRemoveCollisionHandler", dynlib: Lib.} #/ Add a collision shape to the simulation. @@ -489,34 +489,34 @@ proc containsConstraint*(space: PSpace; constraint: PConstraint): bool{. cdecl, importc: "cpSpaceContainsConstraint", dynlib: Lib.} #/ Schedule a post-step callback to be called when cpSpaceStep() finishes. #/ @c obj is used a key, you can only register one callback per unique value for @c obj -proc addPostStepCallback*(space: PSpace; fun: TPostStepFunc; +proc addPostStepCallback*(space: PSpace; fun: TPostStepFunc; obj: pointer; data: pointer){. cdecl, importc: "cpSpaceAddPostStepCallback", dynlib: Lib.} - + #/ Query the space at a point and call @c func for each shape found. -proc pointQuery*(space: PSpace; point: TVector; layers: TLayers; +proc pointQuery*(space: PSpace; point: TVector; layers: TLayers; group: TGroup; fun: TSpacePointQueryFunc; data: pointer){. cdecl, importc: "cpSpacePointQuery", dynlib: Lib.} #/ Query the space at a point and return the first shape found. Returns NULL if no shapes were found. -proc pointQueryFirst*(space: PSpace; point: TVector; layers: TLayers; +proc pointQueryFirst*(space: PSpace; point: TVector; layers: TLayers; group: TGroup): PShape{. cdecl, importc: "cpSpacePointQueryFirst", dynlib: Lib.} #/ Perform a directed line segment query (like a raycast) against the space calling @c func for each shape intersected. -proc segmentQuery*(space: PSpace; start: TVector; to: TVector; - layers: TLayers; group: TGroup; +proc segmentQuery*(space: PSpace; start: TVector; to: TVector; + layers: TLayers; group: TGroup; fun: TSpaceSegmentQueryFunc; data: pointer){. cdecl, importc: "cpSpaceSegmentQuery", dynlib: Lib.} #/ Perform a directed line segment query (like a raycast) against the space and return the first shape hit. Returns NULL if no shapes were hit. -proc segmentQueryFirst*(space: PSpace; start: TVector; to: TVector; - layers: TLayers; group: TGroup; +proc segmentQueryFirst*(space: PSpace; start: TVector; to: TVector; + layers: TLayers; group: TGroup; res: PSegmentQueryInfo): PShape{. cdecl, importc: "cpSpaceSegmentQueryFirst", dynlib: Lib.} #/ Perform a fast rectangle query on the space calling @c func for each shape found. #/ Only the shape's bounding boxes are checked for overlap, not their full shape. -proc BBQuery*(space: PSpace; bb: TBB; layers: TLayers; group: TGroup; +proc BBQuery*(space: PSpace; bb: TBB; layers: TLayers; group: TGroup; fun: TSpaceBBQueryFunc; data: pointer){. cdecl, importc: "cpSpaceBBQuery", dynlib: Lib.} @@ -532,11 +532,11 @@ proc eachBody*(space: PSpace; fun: TSpaceBodyIteratorFunc; data: pointer){. cdecl, importc: "cpSpaceEachBody", dynlib: Lib.} #/ Call @c func for each shape in the space. -proc eachShape*(space: PSpace; fun: TSpaceShapeIteratorFunc; +proc eachShape*(space: PSpace; fun: TSpaceShapeIteratorFunc; data: pointer){. cdecl, importc: "cpSpaceEachShape", dynlib: Lib.} #/ Call @c func for each shape in the space. -proc eachConstraint*(space: PSpace; fun: TSpaceConstraintIteratorFunc; +proc eachConstraint*(space: PSpace; fun: TSpaceConstraintIteratorFunc; data: pointer){. cdecl, importc: "cpSpaceEachConstraint", dynlib: Lib.} #/ Update the collision detection info for the static shapes in the space. @@ -566,7 +566,7 @@ proc newVector*(x, y: CpFloat): TVector {.inline.} = var VectorZero* = newVector(0.0, 0.0) #/ Vector dot product. -proc dot*(v1, v2: TVector): CpFloat {.inline.} = +proc dot*(v1, v2: TVector): CpFloat {.inline.} = result = v1.x * v2.x + v1.y * v2.y #/ Returns the length of v. @@ -613,7 +613,7 @@ proc `-=`*(v1: var TVector; v2: TVector) = v1.y = v1.y - v2.y #/ Negate a vector. -proc `-`*(v: TVector): TVector {.inline.} = +proc `-`*(v: TVector): TVector {.inline.} = result = newVector(- v.x, - v.y) #/ Scalar multiplication. @@ -627,54 +627,54 @@ proc `*=`*(v: var TVector; s: CpFloat) = #/ 2D vector cross product analog. #/ The cross product of 2D vectors results in a 3D vector with only a z component. #/ This function returns the magnitude of the z value. -proc cross*(v1, v2: TVector): CpFloat {.inline.} = +proc cross*(v1, v2: TVector): CpFloat {.inline.} = result = v1.x * v2.y - v1.y * v2.x #/ Returns a perpendicular vector. (90 degree rotation) -proc perp*(v: TVector): TVector {.inline.} = +proc perp*(v: TVector): TVector {.inline.} = result = newVector(- v.y, v.x) #/ Returns a perpendicular vector. (-90 degree rotation) -proc rperp*(v: TVector): TVector {.inline.} = +proc rperp*(v: TVector): TVector {.inline.} = result = newVector(v.y, - v.x) #/ Returns the vector projection of v1 onto v2. -proc project*(v1,v2: TVector): TVector {.inline.} = +proc project*(v1,v2: TVector): TVector {.inline.} = result = v2 * (v1.dot(v2) / v2.dot(v2)) #/ Uses complex number multiplication to rotate v1 by v2. Scaling will occur if v1 is not a unit vector. -proc rotate*(v1, v2: TVector): TVector {.inline.} = +proc rotate*(v1, v2: TVector): TVector {.inline.} = result = newVector(v1.x * v2.x - v1.y * v2.y, v1.x * v2.y + v1.y * v2.x) #/ Inverse of cpvrotate(). -proc unrotate*(v1, v2: TVector): TVector {.inline.} = +proc unrotate*(v1, v2: TVector): TVector {.inline.} = result = newVector(v1.x * v2.x + v1.y * v2.y, v1.y * v2.x - v1.x * v2.y) #/ Returns the squared length of v. Faster than cpvlength() when you only need to compare lengths. -proc lenSq*(v: TVector): CpFloat {.inline.} = +proc lenSq*(v: TVector): CpFloat {.inline.} = result = v.dot(v) #/ Linearly interpolate between v1 and v2. -proc lerp*(v1, v2: TVector; t: CpFloat): TVector {.inline.} = +proc lerp*(v1, v2: TVector; t: CpFloat): TVector {.inline.} = result = (v1 * (1.0 - t)) + (v2 * t) #/ Returns a normalized copy of v. -proc normalize*(v: TVector): TVector {.inline.} = +proc normalize*(v: TVector): TVector {.inline.} = result = v * (1.0 / v.len) #/ Returns a normalized copy of v or cpvzero if v was already cpvzero. Protects against divide by zero errors. -proc normalizeSafe*(v: TVector): TVector {.inline.} = +proc normalizeSafe*(v: TVector): TVector {.inline.} = result = if v.x == 0.0 and v.y == 0.0: VectorZero else: v.normalize #/ Clamp v to length len. -proc clamp*(v: TVector; len: CpFloat): TVector {.inline.} = +proc clamp*(v: TVector; len: CpFloat): TVector {.inline.} = result = if v.dot(v) > len * len: v.normalize * len else: v #/ Linearly interpolate between v1 towards v2 by distance d. -proc lerpconst*(v1, v2: TVector; d: CpFloat): TVector {.inline.} = +proc lerpconst*(v1, v2: TVector; d: CpFloat): TVector {.inline.} = result = v1 + clamp(v2 - v1, d) #vadd(v1 + vclamp(vsub(v2, v1), d)) #/ Returns the distance between v1 and v2. -proc dist*(v1, v2: TVector): CpFloat {.inline.} = +proc dist*(v1, v2: TVector): CpFloat {.inline.} = result = (v1 - v2).len #vlength(vsub(v1, v2)) #/ Returns the squared distance between v1 and v2. Faster than cpvdist() when you only need to compare distances. -proc distsq*(v1, v2: TVector): CpFloat {.inline.} = +proc distsq*(v1, v2: TVector): CpFloat {.inline.} = result = (v1 - v2).lenSq #vlengthsq(vsub(v1, v2)) #/ Returns true if the distance between v1 and v2 is less than dist. -proc near*(v1, v2: TVector; dist: CpFloat): bool{.inline.} = +proc near*(v1, v2: TVector; dist: CpFloat): bool{.inline.} = result = v1.distSq(v2) < dist * dist @@ -706,13 +706,13 @@ proc Sleep*(body: PBody){.importc: "cpBodySleep", dynlib: Lib.} proc SleepWithGroup*(body: PBody; group: PBody){. importc: "cpBodySleepWithGroup", dynlib: Lib.} #/ Returns true if the body is sleeping. -proc isSleeping*(body: PBody): bool {.inline.} = +proc isSleeping*(body: PBody): bool {.inline.} = return body.node.root != nil #/ Returns true if the body is static. -proc isStatic*(body: PBody): bool {.inline.} = +proc isStatic*(body: PBody): bool {.inline.} = return body.node.idleTime == CpInfinity #/ Returns true if the body has not been added to a space. -proc isRogue*(body: PBody): bool {.inline.} = +proc isRogue*(body: PBody): bool {.inline.} = return body.space == nil # #define CP_DefineBodyStructGetter(type, member, name) \ @@ -740,7 +740,7 @@ defGetter(PBody, CpFloat, i, Moment) #/ Set the moment of a body. when defined(MoreNim): defSetter(PBody, CpFloat, i, Moment) -else: +else: proc SetMoment*(body: PBody; i: CpFloat) {. cdecl, importc: "cpBodySetMoment", dynlib: Lib.} @@ -775,10 +775,10 @@ proc UpdateVelocity*(body: PBody; gravity: TVector; damping: CpFloat; dt: CpFloa proc UpdatePosition*(body: PBody; dt: CpFloat){. cdecl, importc: "cpBodyUpdatePosition", dynlib: Lib.} #/ Convert body relative/local coordinates to absolute/world coordinates. -proc Local2World*(body: PBody; v: TVector): TVector{.inline.} = +proc Local2World*(body: PBody; v: TVector): TVector{.inline.} = result = body.p + v.rotate(body.rot) ##return cpvadd(body.p, cpvrotate(v, body.rot)) #/ Convert body absolute/world coordinates to relative/local coordinates. -proc world2Local*(body: PBody; v: TVector): TVector{.inline.} = +proc world2Local*(body: PBody; v: TVector): TVector{.inline.} = result = (v - body.p).unrotate(body.rot) #/ Set the forces and torque or a body to zero. proc resetForces*(body: PBody){. @@ -808,26 +808,26 @@ proc kineticEnergy*(body: PBOdy): CpFloat = result = (body.v.dot(body.v) * body.m) + (body.w * body.w * body.i) #/ Call @c func once for each shape attached to @c body and added to the space. -proc eachShape*(body: PBody; fun: TBodyShapeIteratorFunc; +proc eachShape*(body: PBody; fun: TBodyShapeIteratorFunc; data: pointer){. cdecl, importc: "cpBodyEachShape", dynlib: Lib.} #/ Call @c func once for each constraint attached to @c body and added to the space. -proc eachConstraint*(body: PBody; fun: TBodyConstraintIteratorFunc; +proc eachConstraint*(body: PBody; fun: TBodyConstraintIteratorFunc; data: pointer) {. cdecl, importc: "cpBodyEachConstraint", dynlib: Lib.} #/ Call @c func once for each arbiter that is currently active on the body. -proc eachArbiter*(body: PBody; fun: TBodyArbiterIteratorFunc; +proc eachArbiter*(body: PBody; fun: TBodyArbiterIteratorFunc; data: pointer){. cdecl, importc: "cpBodyEachArbiter", dynlib: Lib.} #/ Allocate a spatial hash. proc SpaceHashAlloc*(): PSpaceHash{. cdecl, importc: "cpSpaceHashAlloc", dynlib: Lib.} -#/ Initialize a spatial hash. -proc SpaceHashInit*(hash: PSpaceHash; celldim: CpFloat; numcells: cint; +#/ Initialize a spatial hash. +proc SpaceHashInit*(hash: PSpaceHash; celldim: CpFloat; numcells: cint; bbfun: TSpatialIndexBBFunc; staticIndex: PSpatialIndex): PSpatialIndex{. cdecl, importc: "cpSpaceHashInit", dynlib: Lib.} #/ Allocate and initialize a spatial hash. -proc SpaceHashNew*(celldim: CpFloat; cells: cint; bbfun: TSpatialIndexBBFunc; +proc SpaceHashNew*(celldim: CpFloat; cells: cint; bbfun: TSpatialIndexBBFunc; staticIndex: PSpatialIndex): PSpatialIndex{. cdecl, importc: "cpSpaceHashNew", dynlib: Lib.} #/ Change the cell dimensions and table size of the spatial hash to tune it. @@ -842,8 +842,8 @@ proc SpaceHashResize*(hash: PSpaceHash; celldim: CpFloat; numcells: cint){. #/ Allocate a bounding box tree. proc BBTreeAlloc*(): PBBTree{.cdecl, importc: "cpBBTreeAlloc", dynlib: Lib.} #/ Initialize a bounding box tree. -proc BBTreeInit*(tree: PBBTree; bbfun: TSpatialIndexBBFunc; - staticIndex: ptr TSpatialIndex): ptr TSpatialIndex{.cdecl, +proc BBTreeInit*(tree: PBBTree; bbfun: TSpatialIndexBBFunc; + staticIndex: ptr TSpatialIndex): ptr TSpatialIndex{.cdecl, importc: "cpBBTreeInit", dynlib: Lib.} #/ Allocate and initialize a bounding box tree. proc BBTreeNew*(bbfun: TSpatialIndexBBFunc; staticIndex: PSpatialIndex): PSpatialIndex{. @@ -860,12 +860,12 @@ proc BBTreeSetVelocityFunc*(index: PSpatialIndex; fun: TBBTreeVelocityFunc){. #/ Allocate a 1D sort and sweep broadphase. -proc Sweep1DAlloc*(): ptr TSweep1D{.cdecl, importc: "cpSweep1DAlloc", +proc Sweep1DAlloc*(): ptr TSweep1D{.cdecl, importc: "cpSweep1DAlloc", dynlib: Lib.} #/ Initialize a 1D sort and sweep broadphase. -proc Sweep1DInit*(sweep: ptr TSweep1D; bbfun: TSpatialIndexBBFunc; - staticIndex: ptr TSpatialIndex): ptr TSpatialIndex{.cdecl, +proc Sweep1DInit*(sweep: ptr TSweep1D; bbfun: TSpatialIndexBBFunc; + staticIndex: ptr TSpatialIndex): ptr TSpatialIndex{.cdecl, importc: "cpSweep1DInit", dynlib: Lib.} #/ Allocate and initialize a 1D sort and sweep broadphase. @@ -878,7 +878,7 @@ defProp(PArbiter, CpFloat, e, Elasticity) defProp(PArbiter, CpFloat, u, Friction) defProp(PArbiter, TVector, surface_vr, SurfaceVelocity) -#/ Calculate the total impulse that was applied by this +#/ Calculate the total impulse that was applied by this #/ This function should only be called from a post-solve, post-step or cpBodyEachArbiter callback. proc totalImpulse*(obj: PArbiter): TVector {.cdecl, importc: "cpArbiterTotalImpulse", dynlib: Lib.} @@ -917,7 +917,7 @@ template getShapes*(arb: PArbiter, name1, name2: expr): stmt {.immediate.} = #/ Return the colliding bodies involved for this arbiter. #/ The order of the cpSpace.collision_type the bodies are associated with values will match #/ the order set when the collision handler was registered. -#proc getBodies*(arb: PArbiter, a, b: var PBody) {.inline.} = +#proc getBodies*(arb: PArbiter, a, b: var PBody) {.inline.} = # getShapes(arb, shape1, shape2) # a = shape1.body # b = shape2.body @@ -981,7 +981,7 @@ proc segmentQuery*(shape: PShape, a, b: TVector, info: PSegmentQueryInfo): bool cdecl, importc: "cpShapeSegmentQuery", dynlib: Lib.} #/ Get the hit point for a segment query. -## Possibly change; info to PSegmentQueryInfo +## Possibly change; info to PSegmentQueryInfo proc queryHitPoint*(start, to: TVector, info: TSegmentQueryInfo): TVector {.inline.} = result = start.lerp(to, info.t) @@ -1035,7 +1035,7 @@ proc init*(poly: PPolyShape; body: PBody, numVerts: cint; cdecl, importc: "cpPolyShapeInit", dynlib: Lib.} #/ Allocate and initialize a polygon shape. #/ A convex hull will be created from the vertexes. -proc newPolyShape*(body: PBody; numVerts: cint; verts: ptr TVector; +proc newPolyShape*(body: PBody; numVerts: cint; verts: ptr TVector; offset: TVector): PShape {. cdecl, importc: "cpPolyShapeNew", dynlib: Lib.} #/ Initialize a box shaped polygon shape. @@ -1129,11 +1129,11 @@ proc MomentForBox2*(m: CpFloat; box: TBB): CpFloat {. ##constraints -type +type #TODO: all these are private #TODO: defConstraintProp() PPinJoint = ptr TPinJoint - TPinJoint{.pf.} = object + TPinJoint{.pf.} = object constraint: PConstraint anchr1: TVector anchr2: TVector @@ -1146,7 +1146,7 @@ type jnMax: CpFloat bias: CpFloat PSlideJoint = ptr TSlideJoint - TSlideJoint{.pf.} = object + TSlideJoint{.pf.} = object constraint: PConstraint anchr1: TVector anchr2: TVector @@ -1160,7 +1160,7 @@ type jnMax: CpFloat bias: CpFloat PPivotJoint = ptr TPivotJoint - TPivotJoint{.pf.} = object + TPivotJoint{.pf.} = object constraint: PConstraint anchr1: TVector anchr2: TVector @@ -1172,7 +1172,7 @@ type jMaxLen: CpFloat bias: TVector PGrooveJoint = ptr TGrooveJoint - TGrooveJoint{.pf.} = object + TGrooveJoint{.pf.} = object constraint: PConstraint grv_n: TVector grv_a: TVector @@ -1188,7 +1188,7 @@ type jMaxLen: CpFloat bias: TVector PDampedSpring = ptr TDampedSpring - TDampedSpring{.pf.} = object + TDampedSpring{.pf.} = object constraint: PConstraint anchr1: TVector anchr2: TVector @@ -1203,7 +1203,7 @@ type nMass: CpFloat n: TVector PDampedRotarySpring = ptr TDampedRotarySpring - TDampedRotarySpring{.pf.} = object + TDampedRotarySpring{.pf.} = object constraint: PConstraint restAngle: CpFloat stiffness: CpFloat @@ -1213,7 +1213,7 @@ type w_coef: CpFloat iSum: CpFloat PRotaryLimitJoint = ptr TRotaryLimitJoint - TRotaryLimitJoint{.pf.} = object + TRotaryLimitJoint{.pf.} = object constraint: PConstraint min: CpFloat max: CpFloat @@ -1222,7 +1222,7 @@ type jAcc: CpFloat jMax: CpFloat PRatchetJoint = ptr TRatchetJoint - TRatchetJoint{.pf.} = object + TRatchetJoint{.pf.} = object constraint: PConstraint angle: CpFloat phase: CpFloat @@ -1232,7 +1232,7 @@ type jAcc: CpFloat jMax: CpFloat PGearJoint = ptr TGearJoint - TGearJoint{.pf.} = object + TGearJoint{.pf.} = object constraint: PConstraint phase: CpFloat ratio: CpFloat @@ -1242,7 +1242,7 @@ type jAcc: CpFloat jMax: CpFloat PSimpleMotor = ptr TSimpleMotor - TSimpleMotor{.pf.} = object + TSimpleMotor{.pf.} = object constraint: PConstraint rate: CpFloat iSum: CpFloat @@ -1250,7 +1250,7 @@ type jMax: CpFloat TDampedSpringForceFunc* = proc (spring: PConstraint; dist: CpFloat): CpFloat{. cdecl.} - TDampedRotarySpringTorqueFunc* = proc (spring: PConstraint; + TDampedRotarySpringTorqueFunc* = proc (spring: PConstraint; relativeAngle: CpFloat): CpFloat {.cdecl.} #/ Destroy a constraint. proc destroy*(constraint: PConstraint){. @@ -1260,7 +1260,7 @@ proc free*(constraint: PConstraint){. cdecl, importc: "cpConstraintFree", dynlib: Lib.} #/ @private -proc activateBodies(constraint: PConstraint) {.inline.} = +proc activateBodies(constraint: PConstraint) {.inline.} = if not constraint.a.isNil: constraint.a.activate() if not constraint.b.isNil: constraint.b.activate() @@ -1291,7 +1291,7 @@ defGetter(PConstraint, TConstraintPreSolveFunc, preSolve, PreSolveFunc) defGetter(PConstraint, TConstraintPostSolveFunc, postSolve, PostSolveFunc) defGetter(PConstraint, CpDataPointer, data, UserData) # Get the last impulse applied by this constraint. -proc getImpulse*(constraint: PConstraint): CpFloat {.inline.} = +proc getImpulse*(constraint: PConstraint): CpFloat {.inline.} = return constraint.klass.getImpulse(constraint) # #define cpConstraintCheckCast(constraint, struct) \ @@ -1309,7 +1309,7 @@ proc getImpulse*(constraint: PConstraint): CpFloat {.inline.} = # } template constraintCheckCast(constraint: PConstraint, ctype: expr): stmt {.immediate.} = assert(constraint.klass == `ctype getClass`(), "Constraint is the wrong class") -template defCGetter(ctype: expr, memberType: typedesc, member: expr, name: expr): stmt {.immediate.} = +template defCGetter(ctype: expr, memberType: typedesc, member: expr, name: expr): stmt {.immediate.} = proc `get ctype name`*(constraint: PConstraint): memberType {.cdecl.} = constraintCheckCast(constraint, ctype) result = cast[`P ctype`](constraint).member @@ -1330,7 +1330,7 @@ proc PinJointGetClass*(): PConstraintClass{. proc AllocPinJoint*(): PPinJoint{. cdecl, importc: "cpPinJointAlloc", dynlib: Lib.} #/ Initialize a pin joint. -proc PinJointInit*(joint: PPinJoint; a: PBody; b: PBody; anchr1: TVector; +proc PinJointInit*(joint: PPinJoint; a: PBody; b: PBody; anchr1: TVector; anchr2: TVector): PPinJoint{. cdecl, importc: "cpPinJointInit", dynlib: Lib.} #/ Allocate and initialize a pin joint. @@ -1411,7 +1411,7 @@ proc init*(joint: PDampedSpring; a, b: PBody; anchr1, anchr2: TVector; restLength, stiffness, damping: CpFloat): PDampedSpring{. cdecl, importc: "cpDampedSpringInit", dynlib: Lib.} #/ Allocate and initialize a damped spring. -proc newDampedSpring*(a, b: PBody; anchr1, anchr2: TVector; +proc newDampedSpring*(a, b: PBody; anchr1, anchr2: TVector; restLength, stiffness, damping: CpFloat): PConstraint{. cdecl, importc: "cpDampedSpringNew", dynlib: Lib.} @@ -1431,7 +1431,7 @@ proc DampedRotarySpringGetClass*(): PConstraintClass{. proc DampedRotarySpringAlloc*(): PDampedRotarySpring{. cdecl, importc: "cpDampedRotarySpringAlloc", dynlib: Lib.} #/ Initialize a damped rotary spring. -proc init*(joint: PDampedRotarySpring; a, b: PBody; +proc init*(joint: PDampedRotarySpring; a, b: PBody; restAngle, stiffness, damping: CpFloat): PDampedRotarySpring{. cdecl, importc: "cpDampedRotarySpringInit", dynlib: Lib.} #/ Allocate and initialize a damped rotary spring. @@ -1477,7 +1477,7 @@ defCProp(RatchetJoint, CpFloat, phase, Phase) defCProp(RatchetJoint, CpFloat, ratchet, Ratchet) -proc GearJointGetClass*(): PConstraintClass{.cdecl, +proc GearJointGetClass*(): PConstraintClass{.cdecl, importc: "cpGearJointGetClass", dynlib: Lib.} #/ Allocate a gear joint. proc AllocGearJoint*(): PGearJoint{. @@ -1502,7 +1502,7 @@ proc SimpleMotorGetClass*(): PConstraintClass{. proc AllocSimpleMotor*(): PSimpleMotor{. cdecl, importc: "cpSimpleMotorAlloc", dynlib: Lib.} #/ initialize a simple motor. -proc init*(joint: PSimpleMotor; a, b: PBody; +proc init*(joint: PSimpleMotor; a, b: PBody; rate: CpFloat): PSimpleMotor{. cdecl, importc: "cpSimpleMotorInit", dynlib: Lib.} #/ Allocate and initialize a simple motor. diff --git a/tests/manyloc/keineschweine/dependencies/enet/enet.nim b/tests/manyloc/keineschweine/dependencies/enet/enet.nim index 93857207a..3c4ce2017 100644 --- a/tests/manyloc/keineschweine/dependencies/enet/enet.nim +++ b/tests/manyloc/keineschweine/dependencies/enet/enet.nim @@ -1,52 +1,52 @@ discard """Copyright (c) 2002-2012 Lee Salzman -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ const Lib = "libenet.so.1(|.0.3)" {.deadCodeElim: on.} -const +const ENET_VERSION_MAJOR* = 1 ENET_VERSION_MINOR* = 3 ENET_VERSION_PATCH* = 3 -template ENET_VERSION_CREATE(major, minor, patch: expr): expr = +template ENET_VERSION_CREATE(major, minor, patch: expr): expr = (((major) shl 16) or ((minor) shl 8) or (patch)) -const - ENET_VERSION* = ENET_VERSION_CREATE(ENET_VERSION_MAJOR, ENET_VERSION_MINOR, +const + ENET_VERSION* = ENET_VERSION_CREATE(ENET_VERSION_MAJOR, ENET_VERSION_MINOR, ENET_VERSION_PATCH) -type +type TVersion* = cuint - TSocketType*{.size: sizeof(cint).} = enum + TSocketType*{.size: sizeof(cint).} = enum ENET_SOCKET_TYPE_STREAM = 1, ENET_SOCKET_TYPE_DATAGRAM = 2 - TSocketWait*{.size: sizeof(cint).} = enum - ENET_SOCKET_WAIT_NONE = 0, ENET_SOCKET_WAIT_SEND = (1 shl 0), + TSocketWait*{.size: sizeof(cint).} = enum + ENET_SOCKET_WAIT_NONE = 0, ENET_SOCKET_WAIT_SEND = (1 shl 0), ENET_SOCKET_WAIT_RECEIVE = (1 shl 1) - TSocketOption*{.size: sizeof(cint).} = enum - ENET_SOCKOPT_NONBLOCK = 1, ENET_SOCKOPT_BROADCAST = 2, - ENET_SOCKOPT_RCVBUF = 3, ENET_SOCKOPT_SNDBUF = 4, + TSocketOption*{.size: sizeof(cint).} = enum + ENET_SOCKOPT_NONBLOCK = 1, ENET_SOCKOPT_BROADCAST = 2, + ENET_SOCKOPT_RCVBUF = 3, ENET_SOCKOPT_SNDBUF = 4, ENET_SOCKOPT_REUSEADDR = 5 -const +const ENET_HOST_ANY* = 0 ENET_HOST_BROADCAST* = 0xFFFFFFFF ENET_PORT_ANY* = 0 - + ENET_PROTOCOL_MINIMUM_MTU* = 576 ENET_PROTOCOL_MAXIMUM_MTU* = 4096 ENET_PROTOCOL_MAXIMUM_PACKET_COMMANDS* = 32 @@ -57,29 +57,29 @@ const ENET_PROTOCOL_MAXIMUM_PEER_ID* = 0x00000FFF type PAddress* = ptr TAddress - TAddress*{.pure, final.} = object + TAddress*{.pure, final.} = object host*: cuint port*: cushort - - TPacketFlag*{.size: sizeof(cint).} = enum - FlagReliable = (1 shl 0), - FlagUnsequenced = (1 shl 1), - NoAllocate = (1 shl 2), + + TPacketFlag*{.size: sizeof(cint).} = enum + FlagReliable = (1 shl 0), + FlagUnsequenced = (1 shl 1), + NoAllocate = (1 shl 2), UnreliableFragment = (1 shl 3) - - TENetListNode*{.pure, final.} = object + + TENetListNode*{.pure, final.} = object next*: ptr T_ENetListNode previous*: ptr T_ENetListNode PENetListIterator* = ptr TENetListNode - TENetList*{.pure, final.} = object + TENetList*{.pure, final.} = object sentinel*: TENetListNode - - T_ENetPacket*{.pure, final.} = object + + T_ENetPacket*{.pure, final.} = object TPacketFreeCallback* = proc (a2: ptr T_ENetPacket){.cdecl.} - + PPacket* = ptr TPacket - TPacket*{.pure, final.} = object + TPacket*{.pure, final.} = object referenceCount: csize flags*: cint data*: cstring#ptr cuchar @@ -87,13 +87,13 @@ type freeCallback*: TPacketFreeCallback PAcknowledgement* = ptr TAcknowledgement - TAcknowledgement*{.pure, final.} = object + TAcknowledgement*{.pure, final.} = object acknowledgementList*: TEnetListNode sentTime*: cuint command*: TEnetProtocol POutgoingCommand* = ptr TOutgoingCommand - TOutgoingCommand*{.pure, final.} = object + TOutgoingCommand*{.pure, final.} = object outgoingCommandList*: TEnetListNode reliableSequenceNumber*: cushort unreliableSequenceNumber*: cushort @@ -107,7 +107,7 @@ type packet*: PPacket PIncomingCommand* = ptr TIncomingCommand - TIncomingCommand*{.pure, final.} = object + TIncomingCommand*{.pure, final.} = object incomingCommandList*: TEnetListNode reliableSequenceNumber*: cushort unreliableSequenceNumber*: cushort @@ -117,52 +117,52 @@ type fragments*: ptr cuint packet*: ptr TPacket - TPeerState*{.size: sizeof(cint).} = enum - ENET_PEER_STATE_DISCONNECTED = 0, ENET_PEER_STATE_CONNECTING = 1, - ENET_PEER_STATE_ACKNOWLEDGING_CONNECT = 2, - ENET_PEER_STATE_CONNECTION_PENDING = 3, - ENET_PEER_STATE_CONNECTION_SUCCEEDED = 4, ENET_PEER_STATE_CONNECTED = 5, - ENET_PEER_STATE_DISCONNECT_LATER = 6, ENET_PEER_STATE_DISCONNECTING = 7, + TPeerState*{.size: sizeof(cint).} = enum + ENET_PEER_STATE_DISCONNECTED = 0, ENET_PEER_STATE_CONNECTING = 1, + ENET_PEER_STATE_ACKNOWLEDGING_CONNECT = 2, + ENET_PEER_STATE_CONNECTION_PENDING = 3, + ENET_PEER_STATE_CONNECTION_SUCCEEDED = 4, ENET_PEER_STATE_CONNECTED = 5, + ENET_PEER_STATE_DISCONNECT_LATER = 6, ENET_PEER_STATE_DISCONNECTING = 7, ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT = 8, ENET_PEER_STATE_ZOMBIE = 9 - - TENetProtocolCommand*{.size: sizeof(cint).} = enum - ENET_PROTOCOL_COMMAND_NONE = 0, ENET_PROTOCOL_COMMAND_ACKNOWLEDGE = 1, - ENET_PROTOCOL_COMMAND_CONNECT = 2, - ENET_PROTOCOL_COMMAND_VERIFY_CONNECT = 3, - ENET_PROTOCOL_COMMAND_DISCONNECT = 4, ENET_PROTOCOL_COMMAND_PING = 5, - ENET_PROTOCOL_COMMAND_SEND_RELIABLE = 6, - ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE = 7, - ENET_PROTOCOL_COMMAND_SEND_FRAGMENT = 8, - ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED = 9, - ENET_PROTOCOL_COMMAND_BANDWIDTH_LIMIT = 10, - ENET_PROTOCOL_COMMAND_THROTTLE_CONFIGURE = 11, - ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE_FRAGMENT = 12, + + TENetProtocolCommand*{.size: sizeof(cint).} = enum + ENET_PROTOCOL_COMMAND_NONE = 0, ENET_PROTOCOL_COMMAND_ACKNOWLEDGE = 1, + ENET_PROTOCOL_COMMAND_CONNECT = 2, + ENET_PROTOCOL_COMMAND_VERIFY_CONNECT = 3, + ENET_PROTOCOL_COMMAND_DISCONNECT = 4, ENET_PROTOCOL_COMMAND_PING = 5, + ENET_PROTOCOL_COMMAND_SEND_RELIABLE = 6, + ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE = 7, + ENET_PROTOCOL_COMMAND_SEND_FRAGMENT = 8, + ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED = 9, + ENET_PROTOCOL_COMMAND_BANDWIDTH_LIMIT = 10, + ENET_PROTOCOL_COMMAND_THROTTLE_CONFIGURE = 11, + ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE_FRAGMENT = 12, ENET_PROTOCOL_COMMAND_COUNT = 13, ENET_PROTOCOL_COMMAND_MASK = 0x0000000F - TENetProtocolFlag*{.size: sizeof(cint).} = enum + TENetProtocolFlag*{.size: sizeof(cint).} = enum ENET_PROTOCOL_HEADER_SESSION_SHIFT = 12, - ENET_PROTOCOL_COMMAND_FLAG_UNSEQUENCED = (1 shl 6), - ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE = (1 shl 7), - ENET_PROTOCOL_HEADER_SESSION_MASK = (3 shl 12), - ENET_PROTOCOL_HEADER_FLAG_COMPRESSED = (1 shl 14), + ENET_PROTOCOL_COMMAND_FLAG_UNSEQUENCED = (1 shl 6), + ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE = (1 shl 7), + ENET_PROTOCOL_HEADER_SESSION_MASK = (3 shl 12), + ENET_PROTOCOL_HEADER_FLAG_COMPRESSED = (1 shl 14), ENET_PROTOCOL_HEADER_FLAG_SENT_TIME = (1 shl 15), ENET_PROTOCOL_HEADER_FLAG_MASK = ENET_PROTOCOL_HEADER_FLAG_COMPRESSED.cint or ENET_PROTOCOL_HEADER_FLAG_SENT_TIME.cint - - TENetProtocolHeader*{.pure, final.} = object + + TENetProtocolHeader*{.pure, final.} = object peerID*: cushort sentTime*: cushort - TENetProtocolCommandHeader*{.pure, final.} = object + TENetProtocolCommandHeader*{.pure, final.} = object command*: cuchar channelID*: cuchar reliableSequenceNumber*: cushort - TENetProtocolAcknowledge*{.pure, final.} = object + TENetProtocolAcknowledge*{.pure, final.} = object header*: TENetProtocolCommandHeader receivedReliableSequenceNumber*: cushort receivedSentTime*: cushort - TENetProtocolConnect*{.pure, final.} = object + TENetProtocolConnect*{.pure, final.} = object header*: TENetProtocolCommandHeader outgoingPeerID*: cushort incomingSessionID*: cuchar @@ -178,7 +178,7 @@ type connectID*: cuint data*: cuint - TENetProtocolVerifyConnect*{.pure, final.} = object + TENetProtocolVerifyConnect*{.pure, final.} = object header*: TENetProtocolCommandHeader outgoingPeerID*: cushort incomingSessionID*: cuchar @@ -193,39 +193,39 @@ type packetThrottleDeceleration*: cuint connectID*: cuint - TENetProtocolBandwidthLimit*{.pure, final.} = object + TENetProtocolBandwidthLimit*{.pure, final.} = object header*: TENetProtocolCommandHeader incomingBandwidth*: cuint outgoingBandwidth*: cuint - TENetProtocolThrottleConfigure*{.pure, final.} = object + TENetProtocolThrottleConfigure*{.pure, final.} = object header*: TENetProtocolCommandHeader packetThrottleInterval*: cuint packetThrottleAcceleration*: cuint packetThrottleDeceleration*: cuint - TENetProtocolDisconnect*{.pure, final.} = object + TENetProtocolDisconnect*{.pure, final.} = object header*: TENetProtocolCommandHeader data*: cuint - TENetProtocolPing*{.pure, final.} = object + TENetProtocolPing*{.pure, final.} = object header*: TENetProtocolCommandHeader - TENetProtocolSendReliable*{.pure, final.} = object + TENetProtocolSendReliable*{.pure, final.} = object header*: TENetProtocolCommandHeader dataLength*: cushort - TENetProtocolSendUnreliable*{.pure, final.} = object + TENetProtocolSendUnreliable*{.pure, final.} = object header*: TENetProtocolCommandHeader unreliableSequenceNumber*: cushort dataLength*: cushort - TENetProtocolSendUnsequenced*{.pure, final.} = object + TENetProtocolSendUnsequenced*{.pure, final.} = object header*: TENetProtocolCommandHeader unsequencedGroup*: cushort dataLength*: cushort - TENetProtocolSendFragment*{.pure, final.} = object + TENetProtocolSendFragment*{.pure, final.} = object header*: TENetProtocolCommandHeader startSequenceNumber*: cushort dataLength*: cushort @@ -233,12 +233,12 @@ type fragmentNumber*: cuint totalLength*: cuint fragmentOffset*: cuint - + ## this is incomplete; need helper templates or something ## ENetProtocol - TENetProtocol*{.pure, final.} = object + TENetProtocol*{.pure, final.} = object header*: TENetProtocolCommandHeader -const +const ENET_BUFFER_MAXIMUM* = (1 + 2 * ENET_PROTOCOL_MAXIMUM_PACKET_COMMANDS) ENET_HOST_RECEIVE_BUFFER_SIZE = 256 * 1024 ENET_HOST_SEND_BUFFER_SIZE = 256 * 1024 @@ -270,39 +270,39 @@ when defined(Linux) or true: import posix const ENET_SOCKET_NULL*: cint = -1 - type + type TENetSocket* = cint PEnetBuffer* = ptr object - TENetBuffer*{.pure, final.} = object + TENetBuffer*{.pure, final.} = object data*: pointer dataLength*: csize TENetSocketSet* = Tfd_set ## see if these are different on win32, if not then get rid of these - template ENET_HOST_TO_NET_16*(value: expr): expr = + template ENET_HOST_TO_NET_16*(value: expr): expr = (htons(value)) - template ENET_HOST_TO_NET_32*(value: expr): expr = + template ENET_HOST_TO_NET_32*(value: expr): expr = (htonl(value)) - template ENET_NET_TO_HOST_16*(value: expr): expr = + template ENET_NET_TO_HOST_16*(value: expr): expr = (ntohs(value)) - template ENET_NET_TO_HOST_32*(value: expr): expr = + template ENET_NET_TO_HOST_32*(value: expr): expr = (ntohl(value)) - template ENET_SOCKETSET_EMPTY*(sockset: expr): expr = + template ENET_SOCKETSET_EMPTY*(sockset: expr): expr = FD_ZERO(addr((sockset))) - template ENET_SOCKETSET_ADD*(sockset, socket: expr): expr = + template ENET_SOCKETSET_ADD*(sockset, socket: expr): expr = FD_SET(socket, addr((sockset))) - template ENET_SOCKETSET_REMOVE*(sockset, socket: expr): expr = + template ENET_SOCKETSET_REMOVE*(sockset, socket: expr): expr = FD_CLEAR(socket, addr((sockset))) - template ENET_SOCKETSET_CHECK*(sockset, socket: expr): expr = + template ENET_SOCKETSET_CHECK*(sockset, socket: expr): expr = FD_ISSET(socket, addr((sockset))) when defined(Windows): ## put the content of win32.h in here -type +type PChannel* = ptr TChannel - TChannel*{.pure, final.} = object + TChannel*{.pure, final.} = object outgoingReliableSequenceNumber*: cushort outgoingUnreliableSequenceNumber*: cushort usedReliableWindows*: cushort @@ -313,7 +313,7 @@ type incomingUnreliableCommands*: TENetList PPeer* = ptr TPeer - TPeer*{.pure, final.} = object + TPeer*{.pure, final.} = object dispatchList*: TEnetListNode host*: ptr THost outgoingPeerID*: cushort @@ -367,25 +367,25 @@ type needsDispatch*: cint incomingUnsequencedGroup*: cushort outgoingUnsequencedGroup*: cushort - unsequencedWindow*: array[0..ENET_PEER_UNSEQUENCED_WINDOW_SIZE div 32 - 1, + unsequencedWindow*: array[0..ENET_PEER_UNSEQUENCED_WINDOW_SIZE div 32 - 1, cuint] eventData*: cuint PCompressor* = ptr TCompressor - TCompressor*{.pure, final.} = object + TCompressor*{.pure, final.} = object context*: pointer - compress*: proc (context: pointer; inBuffers: ptr TEnetBuffer; - inBufferCount: csize; inLimit: csize; + compress*: proc (context: pointer; inBuffers: ptr TEnetBuffer; + inBufferCount: csize; inLimit: csize; outData: ptr cuchar; outLimit: csize): csize{.cdecl.} - decompress*: proc (context: pointer; inData: ptr cuchar; inLimit: csize; + decompress*: proc (context: pointer; inData: ptr cuchar; inLimit: csize; outData: ptr cuchar; outLimit: csize): csize{.cdecl.} destroy*: proc (context: pointer){.cdecl.} TChecksumCallback* = proc (buffers: ptr TEnetBuffer; bufferCount: csize): cuint{. cdecl.} - + PHost* = ptr THost - THost*{.pure, final.} = object + THost*{.pure, final.} = object socket*: TEnetSocket address*: TAddress incomingBandwidth*: cuint @@ -402,14 +402,14 @@ type continueSending*: cint packetSize*: csize headerFlags*: cushort - commands*: array[0..ENET_PROTOCOL_MAXIMUM_PACKET_COMMANDS - 1, + commands*: array[0..ENET_PROTOCOL_MAXIMUM_PACKET_COMMANDS - 1, TEnetProtocol] commandCount*: csize buffers*: array[0..ENET_BUFFER_MAXIMUM - 1, TEnetBuffer] bufferCount*: csize checksum*: TChecksumCallback compressor*: TCompressor - packetData*: array[0..ENET_PROTOCOL_MAXIMUM_MTU - 1, + packetData*: array[0..ENET_PROTOCOL_MAXIMUM_MTU - 1, array[0..2 - 1, cuchar]] receivedAddress*: TAddress receivedData*: ptr cuchar @@ -418,19 +418,19 @@ type totalSentPackets*: cuint totalReceivedData*: cuint totalReceivedPackets*: cuint - - TEventType*{.size: sizeof(cint).} = enum - EvtNone = 0, EvtConnect = 1, + + TEventType*{.size: sizeof(cint).} = enum + EvtNone = 0, EvtConnect = 1, EvtDisconnect = 2, EvtReceive = 3 PEvent* = ptr TEvent - TEvent*{.pure, final.} = object + TEvent*{.pure, final.} = object kind*: TEventType peer*: ptr TPeer channelID*: cuchar data*: cuint packet*: ptr TPacket - TENetCallbacks*{.pure, final.} = object + TENetCallbacks*{.pure, final.} = object malloc*: proc (size: csize): pointer{.cdecl.} free*: proc (memory: pointer){.cdecl.} no_memory*: proc (){.cdecl.} @@ -473,10 +473,10 @@ proc send*(socket: TEnetSocket; address: var TAddress; buffer: ptr TEnetBuffer; importc: "enet_socket_send", dynlib: Lib.} proc send*(socket: TEnetSocket; address: ptr TAddress; buffer: ptr TEnetBuffer; size: csize): cint{. importc: "enet_socket_send", dynlib: Lib.} -proc receive*(socket: TEnetSocket; address: var TAddress; +proc receive*(socket: TEnetSocket; address: var TAddress; buffer: ptr TEnetBuffer; size: csize): cint{. importc: "enet_socket_receive", dynlib: Lib.} -proc receive*(socket: TEnetSocket; address: ptr TAddress; +proc receive*(socket: TEnetSocket; address: ptr TAddress; buffer: ptr TEnetBuffer; size: csize): cint{. importc: "enet_socket_receive", dynlib: Lib.} proc wait*(socket: TEnetSocket; a3: ptr cuint; a4: cuint): cint{. @@ -485,7 +485,7 @@ proc setOption*(socket: TEnetSocket; a3: TSocketOption; a4: cint): cint{. importc: "enet_socket_set_option", dynlib: Lib.} proc destroy*(socket: TEnetSocket){. importc: "enet_socket_destroy", dynlib: Lib.} -proc select*(socket: TEnetSocket; a3: ptr TENetSocketSet; +proc select*(socket: TEnetSocket; a3: ptr TENetSocketSet; a4: ptr TENetSocketSet; a5: cuint): cint{. importc: "enet_socketset_select", dynlib: Lib.} @@ -578,13 +578,13 @@ proc resetQueues*(peer: PPeer){. proc setupOutgoingCommand*(peer: PPeer; outgoingCommand: POutgoingCommand){. importc: "enet_peer_setup_outgoing_command", dynlib: Lib.} -proc queueOutgoingCommand*(peer: PPeer; command: ptr TEnetProtocol; +proc queueOutgoingCommand*(peer: PPeer; command: ptr TEnetProtocol; packet: PPacket; offset: cuint; length: cushort): POutgoingCommand{. importc: "enet_peer_queue_outgoing_command", dynlib: Lib.} -proc queueIncomingCommand*(peer: PPeer; command: ptr TEnetProtocol; +proc queueIncomingCommand*(peer: PPeer; command: ptr TEnetProtocol; packet: PPacket; fragmentCount: cuint): PIncomingCommand{. importc: "enet_peer_queue_incoming_command", dynlib: Lib.} -proc queueAcknowledgement*(peer: PPeer; command: ptr TEnetProtocol; +proc queueAcknowledgement*(peer: PPeer; command: ptr TEnetProtocol; sentTime: cushort): PAcknowledgement{. importc: "enet_peer_queue_acknowledgement", dynlib: Lib.} proc dispatchIncomingUnreliableCommands*(peer: PPeer; channel: PChannel){. @@ -596,10 +596,10 @@ proc createRangeCoder*(): pointer{. importc: "enet_range_coder_create", dynlib: Lib.} proc rangeCoderDestroy*(context: pointer){. importc: "enet_range_coder_destroy", dynlib: Lib.} -proc rangeCoderCompress*(context: pointer; inBuffers: PEnetBuffer; inLimit, +proc rangeCoderCompress*(context: pointer; inBuffers: PEnetBuffer; inLimit, bufferCount: csize; outData: cstring; outLimit: csize): csize{. importc: "enet_range_coder_compress", dynlib: Lib.} -proc rangeCoderDecompress*(context: pointer; inData: cstring; inLimit: csize; +proc rangeCoderDecompress*(context: pointer; inData: cstring; inLimit: csize; outData: cstring; outLimit: csize): csize{. importc: "enet_range_coder_decompress", dynlib: Lib.} proc protocolCommandSize*(commandNumber: cuchar): csize{. diff --git a/tests/manyloc/keineschweine/dependencies/enet/testserver.nim b/tests/manyloc/keineschweine/dependencies/enet/testserver.nim index 28a6bd1f7..6d6de90c1 100644 --- a/tests/manyloc/keineschweine/dependencies/enet/testserver.nim +++ b/tests/manyloc/keineschweine/dependencies/enet/testserver.nim @@ -19,11 +19,11 @@ while server.hostService(addr event, 2500) >= 0: case event.kind of EvtConnect: echo "New client from $1:$2".format(event.peer.address.host, event.peer.address.port) - + var - msg = "hello" + msg = "hello" resp = createPacket(cstring(msg), msg.len + 1, FlagReliable) - + if event.peer.send(0.cuchar, resp) < 0: echo "FAILED" else: @@ -32,9 +32,9 @@ while server.hostService(addr event, 2500) >= 0: echo "Recvd ($1) $2 ".format( event.packet.dataLength, event.packet.data) - + destroy(event.packet) - + of EvtDisconnect: echo "Disconnected" event.peer.data = nil @@ -42,4 +42,4 @@ while server.hostService(addr event, 2500) >= 0: discard server.destroy() -enetDeinit() \ No newline at end of file +enetDeinit() diff --git a/tests/manyloc/keineschweine/dependencies/genpacket/streams_enh.nim b/tests/manyloc/keineschweine/dependencies/genpacket/streams_enh.nim index 3c5a7835c..5a1dffc93 100644 --- a/tests/manyloc/keineschweine/dependencies/genpacket/streams_enh.nim +++ b/tests/manyloc/keineschweine/dependencies/genpacket/streams_enh.nim @@ -1,7 +1,7 @@ import streams from strutils import repeat -proc readPaddedStr*(s: PStream, length: int, padChar = '\0'): TaintedString = +proc readPaddedStr*(s: PStream, length: int, padChar = '\0'): TaintedString = var lastChr = length result = s.readStr(length) while lastChr >= 0 and result[lastChr - 1] == padChar: dec(lastChr) @@ -26,22 +26,22 @@ proc writeLEStr*(s: PStream, str: string) = when isMainModule: var testStream = newStringStream() - + testStream.writeLEStr("Hello") doAssert testStream.data == "\5\0Hello" - + testStream.setPosition 0 var res = testStream.readLEStr() doAssert res == "Hello" - + testStream.setPosition 0 testStream.writePaddedStr("Sup", 10) echo(repr(testStream), testStream.data.len) doAssert testStream.data == "Sup"&repeat('\0', 7) - + testStream.setPosition 0 res = testStream.readPaddedStr(10) doAssert res == "Sup" - + testStream.close() diff --git a/tests/manyloc/keineschweine/dependencies/nake/nake.nim b/tests/manyloc/keineschweine/dependencies/nake/nake.nim index 5828e400c..5341c1079 100644 --- a/tests/manyloc/keineschweine/dependencies/nake/nake.nim +++ b/tests/manyloc/keineschweine/dependencies/nake/nake.nim @@ -3,7 +3,7 @@ DO AS THOU WILST PUBLIC LICENSE Whoever should stumble upon this document is henceforth and forever entitled to DO AS THOU WILST with aforementioned document and the -contents thereof. +contents thereof. As said in the Olde Country, `Keepe it Gangster'.""" @@ -14,7 +14,7 @@ type desc*: string action*: TTaskFunction TTaskFunction* = proc() {.closure.} -var +var tasks* = initTable[string, PTask](16) proc newTask*(desc: string; action: TTaskFunction): PTask @@ -61,7 +61,7 @@ when isMainModule: quit(shell("nim", "c", "-r", "nakefile.nim", args)) else: addQuitProc(proc() {.noconv.} = - var + var task: string printTaskList: bool for kind, key, val in getOpt(): @@ -70,7 +70,7 @@ else: case key.tolower of "tasks", "t": printTaskList = true - else: + else: echo "Unknown option: ", key, ": ", val of cmdArgument: task = key diff --git a/tests/manyloc/keineschweine/dependencies/sfml/sfml.nim b/tests/manyloc/keineschweine/dependencies/sfml/sfml.nim index 1071ec767..1524f0eb4 100644 --- a/tests/manyloc/keineschweine/dependencies/sfml/sfml.nim +++ b/tests/manyloc/keineschweine/dependencies/sfml/sfml.nim @@ -1,4 +1,4 @@ -import +import strutils, math when defined(linux): const @@ -27,7 +27,7 @@ type x*, y*, z*: cfloat PInputStream* = ptr TInputStream - TInputStream* {.pf.} = object + TInputStream* {.pf.} = object read*: TInputStreamReadFunc seek*: TInputStreamSeekFunc tell*: TInputStreamTellFunc @@ -52,14 +52,14 @@ type width*: cint height*: cint bitsPerPixel*: cint - TEventType*{.size: sizeof(cint).} = enum - EvtClosed, EvtResized, EvtLostFocus, EvtGainedFocus, - EvtTextEntered, EvtKeyPressed, EvtKeyReleased, EvtMouseWheelMoved, - EvtMouseButtonPressed, EvtMouseButtonReleased, EvtMouseMoved, - EvtMouseEntered, EvtMouseLeft, EvtJoystickButtonPressed, - EvtJoystickButtonReleased, EvtJoystickMoved, EvtJoystickConnected, + TEventType*{.size: sizeof(cint).} = enum + EvtClosed, EvtResized, EvtLostFocus, EvtGainedFocus, + EvtTextEntered, EvtKeyPressed, EvtKeyReleased, EvtMouseWheelMoved, + EvtMouseButtonPressed, EvtMouseButtonReleased, EvtMouseMoved, + EvtMouseEntered, EvtMouseLeft, EvtJoystickButtonPressed, + EvtJoystickButtonReleased, EvtJoystickMoved, EvtJoystickConnected, EvtJoystickDisconnected - TKeyEvent*{.pf.} = object + TKeyEvent*{.pf.} = object code*: TKeyCode alt* : bool control*: bool @@ -74,7 +74,7 @@ type joystickId*: cint axis*: TJoystickAxis position*: cfloat - TMouseWheelEvent*{.pf.} = object + TMouseWheelEvent*{.pf.} = object delta*: cint x*: cint y*: cint @@ -90,7 +90,7 @@ type PEvent* = ptr TEvent TEvent*{.pf.} = object case kind*: TEventType - of EvtKeyPressed, EvtKeyReleased: + of EvtKeyPressed, EvtKeyReleased: key*: TKeyEvent of EvtMouseButtonPressed, EvtMouseButtonReleased: mouseButton*: TMouseButtonEvent @@ -109,16 +109,16 @@ type of EvtMouseWheelMoved: mouseWheel*: TMouseWheelEvent else: nil - TJoystickAxis*{.size: sizeof(cint).} = enum - JoystickX, JoystickY, JoystickZ, JoystickR, + TJoystickAxis*{.size: sizeof(cint).} = enum + JoystickX, JoystickY, JoystickZ, JoystickR, JoystickU, JoystickV, JoystickPovX, JoystickPovY TSizeEvent*{.pf.} = object width*: cint height*: cint - TMouseButton*{.size: sizeof(cint).} = enum - MouseLeft, MouseRight, MouseMiddle, + TMouseButton*{.size: sizeof(cint).} = enum + MouseLeft, MouseRight, MouseMiddle, MouseXButton1, MouseXButton2, MouseButtonCount - TKeyCode*{.size: sizeof(cint).} = enum + TKeyCode*{.size: sizeof(cint).} = enum KeyUnknown = - 1, KeyA, KeyB, KeyC, KeyD, KeyE, KeyF, KeyG, KeyH, KeyI, KeyJ, KeyK, KeyL, KeyM, #/< The M key KeyN, KeyO, KeyP, KeyQ, KeyR, KeyS, KeyT, KeyU, #/< The U key @@ -204,11 +204,11 @@ type PConvexShape* = ptr TConvexShape TConvexShape* {.pf.} = object - TTextStyle*{.size: sizeof(cint).} = enum - TextRegular = 0, TextBold = 1 shl 0, TextItalic = 1 shl 1, + TTextStyle*{.size: sizeof(cint).} = enum + TextRegular = 0, TextBold = 1 shl 0, TextItalic = 1 shl 1, TextUnderlined = 1 shl 2 - TBlendMode*{.size: sizeof(cint).} = enum + TBlendMode*{.size: sizeof(cint).} = enum BlendAlpha, BlendAdd, BlendMultiply, BlendNone PRenderStates* = ptr TRenderStates TRenderStates* {.pf.} = object @@ -220,19 +220,19 @@ type PTransform* = ptr TTransform TTransform* {.pf.} = object matrix*: array[0..8, cfloat] - TColor* {.pf.} = object + TColor* {.pf.} = object r*: uint8 g*: uint8 b*: uint8 a*: uint8 PFloatRect* = ptr TFloatRect - TFloatRect*{.pf.} = object + TFloatRect*{.pf.} = object left*: cfloat top*: cfloat width*: cfloat height*: cfloat PIntRect* = ptr TIntRect - TIntRect*{.pf.} = object + TIntRect*{.pf.} = object left*: cint top*: cint width*: cint @@ -246,7 +246,7 @@ type position*: TVector2f color*: TColor texCoords*: TVector2f - TPrimitiveType*{.size: sizeof(cint).} = enum + TPrimitiveType*{.size: sizeof(cint).} = enum Points, #/< List of individual points Lines, #/< List of individual lines LinesStrip, #/< List of connected lines, a point uses the previous point to form a line @@ -381,7 +381,7 @@ proc draw*(window: PRenderWindow, shape: PConvexShape, states: PRenderStates = n cdecl, importc: "sfRenderWindow_drawConvexShape", dynlib: LibG.} proc draw*(window: PRenderWindow, shape: PVertexArray, states: PRenderStates = nil) {. cdecl, importc: "sfRenderWindow_drawVertexArray", dynlib: LibG.} -proc draw*(window: PRenderWindow, vertices: PVertex, vertexCount: cint, +proc draw*(window: PRenderWindow, vertices: PVertex, vertexCount: cint, vertexType: TPrimitiveType, states: PRenderStates = nil) {. cdecl, importc: "sfRenderWindow_drawPrimitives", dynlib: LibG.} @@ -434,20 +434,20 @@ proc draw*(renderTexture: PRenderTexture; text: PText; states: PRenderStates){. cdecl, importc: "sfRenderTexture_drawText", dynlib: LibG.} proc draw*(renderTexture: PRenderTexture; shape: PShape; states: PRenderStates){. cdecl, importc: "sfRenderTexture_drawShape", dynlib: LibG.} -proc draw*(renderTexture: PRenderTexture; shape: PCircleShape; +proc draw*(renderTexture: PRenderTexture; shape: PCircleShape; states: PRenderStates){. cdecl, importc: "sfRenderTexture_drawCircleShape", dynlib: LibG.} -proc draw*(renderTexture: PRenderTexture; shape: PConvexShape; +proc draw*(renderTexture: PRenderTexture; shape: PConvexShape; states: PRenderStates){. cdecl, importc: "sfRenderTexture_drawConvexShape", dynlib: LibG.} -proc draw*(renderTexture: PRenderTexture; shape: PRectangleShape; +proc draw*(renderTexture: PRenderTexture; shape: PRectangleShape; states: PRenderStates){. cdecl, importc: "sfRenderTexture_drawRectangleShape", dynlib: LibG.} -proc draw*(renderTexture: PRenderTexture; va: PVertexArray; +proc draw*(renderTexture: PRenderTexture; va: PVertexArray; states: PRenderStates){. cdecl, importc: "sfRenderTexture_drawVertexArray", dynlib: LibG.} #Draw primitives defined by an array of vertices to a render texture -proc draw*(renderTexture: PRenderTexture; vertices: PVertex; vertexCount: cint; +proc draw*(renderTexture: PRenderTexture; vertices: PVertex; vertexCount: cint; primitiveType: TPrimitiveType; states: PRenderStates){. cdecl, importc: "sfRenderTexture_drawPrimitives", dynlib: LibG.} #Save the current OpenGL render states and matrices @@ -500,12 +500,12 @@ proc intRect*(left, top, width, height: cint): TIntRect = result.height = height proc floatRect*(left, top, width, height: cfloat): TFloatRect = result.left = left - result.top = top + result.top = top result.width = width result.height = height proc contains*(rect: PFloatRect, x, y: cfloat): bool {. cdecl, importc: "sfFloatRect_contains", dynlib: LibG.} -proc contains*(rect: PIntRect, x: cint, y: cint): bool{.cdecl, +proc contains*(rect: PIntRect, x: cint, y: cint): bool{.cdecl, importc: "sfIntRect_contains", dynlib: LibG.} proc intersects*(rect1, rect2, intersection: PFloatRect): bool {. cdecl, importc: "sfFloatRect_intersects", dynlib: LibG.} @@ -894,7 +894,7 @@ proc setColor*(text: PText, color: TColor) {. cdecl, importc: "sfText_setColor", dynlib: LibG.} proc getString*(text: PText): cstring {. cdecl, importc: "sfText_getString", dynlib: LibG.} -proc getUnicodeString*(text: PText): ptr uint32 {.cdecl, +proc getUnicodeString*(text: PText): ptr uint32 {.cdecl, importc: "sfText_getUnicodeString", dynlib: LibG.} proc getFont*(text: PText): PFont {. cdecl, importc: "sfText_getFont", dynlib: LibG.} @@ -985,7 +985,7 @@ proc `*`*(color1, color2: TColor): TColor {. cdecl, importc: "sfColor_modulate", dynlib: LibG.} proc newColor*(r,g,b: int): TColor {.inline.} = return color(r,g,b) -proc newColor*(r,g,b,a: int): TColor {.inline.} = +proc newColor*(r,g,b,a: int): TColor {.inline.} = return color(r,g,b,a) proc newClock*(): PClock {. @@ -1022,7 +1022,7 @@ proc newContextSettings*(depthBits: cint = 0, result.majorVersion = majorVersion result.minorVersion = minorVersion -proc newCircleShape*(radius: cfloat; pointCount: cint = 30): PCircleShape = +proc newCircleShape*(radius: cfloat; pointCount: cint = 30): PCircleShape = result = newCircleShape() result.setRadius radius result.setPointCount pointCount @@ -1047,13 +1047,13 @@ proc `[]`*(a: PVertexArray, index: int): PVertex = proc `$` *(a: TContextSettings): string = return "" % [ $a.stencilBits, $a.antialiasingLevel, $a.majorVersion, $a.minorVersion, $a.depthBits] -proc `$` *(a: TVideoMode): string = +proc `$` *(a: TVideoMode): string = return "" % [$a.width, $a.height, $a.bitsPerPixel] -proc `$` *(a: TFloatRect): string = +proc `$` *(a: TFloatRect): string = return "" % [$a.left, $a.top, $a.width, $a.height] -proc `$` *(a: PView): string = +proc `$` *(a: PView): string = return $a.getViewport() -proc `$` *(a: TVector2f): string = +proc `$` *(a: TVector2f): string = return "" % [$a.x, $a.y] proc vec2i*(x, y: int): TVector2i = diff --git a/tests/manyloc/keineschweine/dependencies/sfml/sfml_audio.nim b/tests/manyloc/keineschweine/dependencies/sfml/sfml_audio.nim index 5aa017ac4..6f81e50a3 100644 --- a/tests/manyloc/keineschweine/dependencies/sfml/sfml_audio.nim +++ b/tests/manyloc/keineschweine/dependencies/sfml/sfml_audio.nim @@ -294,7 +294,7 @@ proc newSoundBuffer*(stream: PInputStream): PSoundBuffer{. #/ \return A new sfSoundBuffer object (NULL if failed) #/ #////////////////////////////////////////////////////////// -proc createFromSamples*(samples: ptr int16; sampleCount: cuint; +proc createFromSamples*(samples: ptr int16; sampleCount: cuint; channelCount: cuint; sampleRate: cuint): PSoundBuffer{. cdecl, importc: "sfSoundBuffer_createFromSamples", dynlib: Lib.} #////////////////////////////////////////////////////////// @@ -437,10 +437,10 @@ proc listenerSetDirection*(orientation: TVector3f){. proc listenerGetDirection*(): TVector3f{. cdecl, importc: "sfListener_getDirection", dynlib: Lib.} -type +type TSoundRecorderStartCallback* = proc (a2: pointer): bool {.cdecl.} - #/< Type of the callback used when starting a capture - TSoundRecorderProcessCallback* = proc(a2: ptr int16; a3: cuint; + #/< Type of the callback used when starting a capture + TSoundRecorderProcessCallback* = proc(a2: ptr int16; a3: cuint; a4: pointer): bool {.cdecl.} #/< Type of the callback used to process audio data TSoundRecorderStopCallback* = proc (a2: pointer){.cdecl.} @@ -456,9 +456,9 @@ type #/ \return A new sfSoundRecorder object (NULL if failed) #/ #////////////////////////////////////////////////////////// -proc newSoundRecorder*(onStart: TSoundRecorderStartCallback; - onProcess: TSoundRecorderProcessCallback; - onStop: TSoundRecorderStopCallback; +proc newSoundRecorder*(onStart: TSoundRecorderStartCallback; + onProcess: TSoundRecorderProcessCallback; + onStop: TSoundRecorderStopCallback; userData: pointer = nil): PSoundRecorder{. cdecl, importc: "sfSoundRecorder_create", dynlib: Lib.} #////////////////////////////////////////////////////////// @@ -595,13 +595,13 @@ proc getBuffer*(soundBufferRecorder: PSoundBufferRecorder): PSoundBuffer{. #/ \brief defines the data to fill by the OnGetData callback #/ #////////////////////////////////////////////////////////// -type +type PSoundStreamChunk* = ptr TSoundStreamChunk - TSoundStreamChunk*{.pure, final.} = object + TSoundStreamChunk*{.pure, final.} = object samples*: ptr int16 #/< Pointer to the audio samples sampleCount*: cuint #/< Number of samples pointed by Samples - - TSoundStreamGetDataCallback* = proc (a2: PSoundStreamChunk; + + TSoundStreamGetDataCallback* = proc (a2: PSoundStreamChunk; a3: pointer): bool{.cdecl.} #/< Type of the callback used to get a sound stream data TSoundStreamSeekCallback* = proc (a2: TTime; a3: pointer){.cdecl.} @@ -618,7 +618,7 @@ type #/ \return A new sfSoundStream object #/ #////////////////////////////////////////////////////////// -proc create*(onGetData: TSoundStreamGetDataCallback; onSeek: TSoundStreamSeekCallback; +proc create*(onGetData: TSoundStreamGetDataCallback; onSeek: TSoundStreamSeekCallback; channelCount: cuint; sampleRate: cuint; userData: pointer): PSoundStream{. cdecl, importc: "sfSoundStream_create", dynlib: Lib.} #////////////////////////////////////////////////////////// diff --git a/tests/manyloc/keineschweine/dependencies/sfml/sfml_colors.nim b/tests/manyloc/keineschweine/dependencies/sfml/sfml_colors.nim index 31473b17a..95a760e1f 100644 --- a/tests/manyloc/keineschweine/dependencies/sfml/sfml_colors.nim +++ b/tests/manyloc/keineschweine/dependencies/sfml/sfml_colors.nim @@ -12,4 +12,4 @@ let Transparent*: TColor = color(0, 0, 0, 0) Gray* = color(84, 84, 84) RoyalBlue* = color(65, 105, 225) -##todo: define more colors lul \ No newline at end of file +##todo: define more colors lul diff --git a/tests/manyloc/keineschweine/enet_server/enet_client.nim b/tests/manyloc/keineschweine/enet_server/enet_client.nim index 5ebbdb88b..ac600c0af 100644 --- a/tests/manyloc/keineschweine/enet_server/enet_client.nim +++ b/tests/manyloc/keineschweine/enet_server/enet_client.nim @@ -78,11 +78,11 @@ proc poll(serv: PServer; timeout: cuint = 30) = case event.kind of EvtReceive: var buf = newBuffer(event.packet) - + serv.handlePackets(buf) - + event.packet.destroy() - of EvtDisconnect: + of EvtDisconnect: dispMessage "Disconnected" serv.connected = false event.peer.data = nil @@ -111,8 +111,8 @@ proc tryConnect*(b: PButton) = if not dirServer.connected: var error: string if not dirServer.connect( - clientSettings.dirServer.host, - clientSettings.dirServer.port, + clientSettings.dirServer.host, + clientSettings.dirServer.port, error): dispError(error) else: @@ -143,16 +143,16 @@ proc lobbyInit*() = clientSettings.website = s["website"].str zonelist.setPosition(vec2f(200.0, 100.0)) connectionButtons = @[] - + var pos = vec2f(10, 10) u_alias = gui.newTextEntry( - if s.hasKey("alias"): s["alias"].str else: "alias", + if s.hasKey("alias"): s["alias"].str else: "alias", pos) pos.y += 20 u_passwd = gui.newTextEntry("buzz", pos) pos.y += 20 connectionButtons.add(gui.newButton( - text = "Login", + text = "Login", position = pos, onClick = tryLogin, startEnabled = false)) @@ -171,16 +171,16 @@ proc lobbyInit*() = connectionButtons.add(gui.newButton( text = "Test Chat", position = pos, - onClick = (proc(b: PButton) = + onClick = (proc(b: PButton) = var pkt = newCsChat(text = "ohai") dirServer.send HChat, pkt), startEnabled = false)) pos.y += 20 - downloadProgress.setPosition(pos) + downloadProgress.setPosition(pos) downloadProgress.bg.setFillColor(color(34, 139, 34)) downloadProgress.bg.setSize(vec2f(0, 0)) gui.add(downloadProgress) - + playBtn = gui.newButton( text = "Play", position = vec2f(680.0, 8.0), @@ -193,20 +193,20 @@ proc lobbyInit*() = discard """gui.newButton(text = "Scrollback + 1", position = vec2f(185, 10), onClick = proc(b: PButton) = messageArea.scrollBack += 1 update(messageArea)) - gui.newButton(text = "Scrollback - 1", position = vec2f(185+160, 10), onClick = proc(b: PButton) = + gui.newButton(text = "Scrollback - 1", position = vec2f(185+160, 10), onClick = proc(b: PButton) = messageArea.scrollBack -= 1 update(messageArea)) gui.newButton(text = "Flood msg area", position = vec2f(185, 30), onClick = proc(b: PButton) = - for i in 0.. <30: + for i in 0.. <30: dispMessage($i))""" - dirServer = newServer() + dirServer = newServer() dirServer.addHandler HChat, handleChat dirServer.addHandler HLogin, handlePlayerLogin dirServer.addHandler HFileTransfer, client_helpers.handleFilePartRecv dirServer.addHandler HChallengeResult, client_helpers.handleFileChallengeResult dirServer.addHandler HFileChallenge, client_helpers.handleFileChallenge -proc lobbyReady*() = +proc lobbyReady*() = kc.setActive() gui.setActive(u_alias) diff --git a/tests/manyloc/keineschweine/enet_server/enet_server.nim b/tests/manyloc/keineschweine/enet_server/enet_server.nim index c2e893273..eae7c034e 100644 --- a/tests/manyloc/keineschweine/enet_server/enet_server.nim +++ b/tests/manyloc/keineschweine/enet_server/enet_server.nim @@ -1,4 +1,4 @@ -import enet, strutils, idgen, tables, math_helpers, +import enet, strutils, idgen, tables, math_helpers, estreams, sg_packets, server_utils, sg_assets, client_helpers when appType == "gui": import sfml, sfml_colors, sg_gui, @@ -14,7 +14,7 @@ var event: enet.TEvent clientID = newIDGen[int32]() clients = initTable[int32, PClient](64) - handlers = initTable[char, TCallback](32) + handlers = initTable[char, TCallback](32) when appType == "gui": var @@ -67,7 +67,7 @@ proc flushPubChat() = handlers[HChat] = proc(client: PClient; buffer: PBuffer) = var chat = readCsChat(buffer) - + if not client.auth: client.sendError("You are not logged in.") return @@ -75,7 +75,7 @@ handlers[HChat] = proc(client: PClient; buffer: PBuffer) = # if alias2client.hasKey(chat.target): # alias2client[chat.target].forwardPrivate(client, chat.text) #else: - + dispmessage("<", client.alias, "> ", chat.text) queuePub(client, chat) @@ -104,20 +104,20 @@ handlers[HZoneJoinReq] = proc(client: PClient; buffer: PBuffer) = when isMainModule: import parseopt, matchers, os, json - - + + if enetInit() != 0: quit "Could not initialize ENet" - + var address: enet.TAddress - + block: var zoneCfgFile = "./server_settings.json" for kind, key, val in getOpt(): case kind of cmdShortOption, cmdLongOption: case key - of "f", "file": + of "f", "file": if existsFile(val): zoneCfgFile = val else: @@ -127,45 +127,45 @@ when isMainModule: else: echo("Unknown option: ", key, " ", val) var jsonSettings = parseFile(zoneCfgFile) - let + let port = uint16(jsonSettings["port"].num) zoneFile = jsonSettings["settings"].str dirServerInfo = jsonSettings["dirserver"] - + address.host = EnetHostAny address.port = port - + var path = getAppDir()/../"data"/zoneFile if not existsFile(path): echo("Zone settings file does not exist: ../data/", zoneFile) echo(path) quit(1) - + discard """block: - var + var TestFile: FileChallengePair contents = repeat("abcdefghijklmnopqrstuvwxyz", 2) - testFile.challenge = newScFileChallenge("foobar.test", FZoneCfg, contents.len.int32) + testFile.challenge = newScFileChallenge("foobar.test", FZoneCfg, contents.len.int32) testFile.file = checksumStr(contents) myAssets.add testFile""" - + setCurrentDir getAppDir().parentDir() let zonesettings = readFile(path) - var + var errors: seq[string] = @[] if not loadSettings(zoneSettings, errors): echo("You have errors in your zone settings:") for e in errors: echo("**", e) quit(1) errors.setLen 0 - + var pair: FileChallengePair pair.challenge.file = zoneFile pair.challenge.assetType = FZoneCfg pair.challenge.fullLen = zoneSettings.len.int32 pair.file = checksumStr(zoneSettings) myAssets.add pair - + allAssets: if not load(asset): echo "Invalid or missing file ", file @@ -177,11 +177,11 @@ when isMainModule: expandPath(assetType, file)).int32 pair.file = asset.contents myAssets.add pair - + echo "Zone has ", myAssets.len, " associated assets" - + dirServer = newServer() - + dirServer.addHandler HDsMsg, proc(serv: PServer; buffer: PBuffer) = var m = readDsMsg(buffer) dispMessage(" ", m.msg) @@ -189,20 +189,20 @@ when isMainModule: let loggedIn = readDsZoneLogin(buffer).status if loggedIn: #dirServerConnected = true - + if dirServerInfo.kind == JArray: var error: string if not dirServer.connect(dirServerInfo[0].str, dirServerInfo[1].num.int16, error): dispError(" "&error) - - + + server = enet.createHost(address, 32, 2, 0, 0) if server == nil: quit "Could not create the server!" - + dispMessage("Listening on port ", address.port) - - var + + var serverRunning = true when appType == "gui": var frameRate = newClock() @@ -210,11 +210,11 @@ when isMainModule: else: var frameRate = epochTime() var pubChatDelay = frameRate - + while serverRunning: when appType == "gui": let dt = frameRate.restart.asMilliseconds().float / 1000.0 - + for event in window.filterEvents(): case event.kind of sfml.EvtClosed: @@ -225,7 +225,7 @@ when isMainModule: else: let dt = epochTime() - frameRate ##is this right? probably not frameRate = epochTime() - + while server.hostService(event, 10) > 0: case event.kind of EvtConnect: @@ -234,27 +234,27 @@ when isMainModule: event.peer.data = addr client.id client.peer = event.peer - + dispMessage("New client connected ", client) - + var - msg = "hello" + msg = "hello" resp = createPacket(cstring(msg), msg.len + 1, FlagReliable) - + if event.peer.send(0.cuchar, resp) < 0: echo "FAILED" else: echo "Replied" of EvtReceive: - let client = clients[cast[ptr int32](event.peer.data)[]] - + let client = clients[cast[ptr int32](event.peer.data)[]] + var buf = newBuffer(event.packet) let k = buf.readChar() if handlers.hasKey(k): handlers[k](client, buf) else: dispError("Unknown packet from ", client) - + destroy(event.packet) of EvtDisconnect: var @@ -267,11 +267,11 @@ when isMainModule: dispMessage(clients[id], " disconnected") GCUnref(clients[id]) clients.del id - + event.peer.data = nil else: discard - + when appType == "gui": fpsText.setString(ff(1.0/dt)) if pubChatDelay.getElapsedTime.asSeconds > 0.25: @@ -281,14 +281,14 @@ when isMainModule: pubChatDelay -= dt if frameRate - pubChatDelay > 0.25: flushPubChat() - + when appType == "gui": window.clear(Black) window.draw(GUI) window.draw chatbox window.draw mousePos window.draw fpstext - window.display() + window.display() server.destroy() - enetDeinit() \ No newline at end of file + enetDeinit() diff --git a/tests/manyloc/keineschweine/enet_server/server_utils.nim b/tests/manyloc/keineschweine/enet_server/server_utils.nim index 8e8141075..1fb8326ed 100644 --- a/tests/manyloc/keineschweine/enet_server/server_utils.nim +++ b/tests/manyloc/keineschweine/enet_server/server_utils.nim @@ -6,9 +6,9 @@ type auth*: bool alias*: string peer*: PPeer - + FileChallengePair* = tuple[challenge: ScFileChallenge; file: TChecksumFile] - PFileChallengeSequence* = ref TFileChallengeSequence + PFileChallengeSequence* = ref TFileChallengeSequence TFileChallengeSequence = object index: int #which file is active transfer: ScFileTransfer @@ -73,7 +73,7 @@ proc sendChunk*(challenge: PFileChallengeSequence, client: PClient) = let size = min(FileChunkSize, challenge.transfer.fileSize - challenge.transfer.pos) challenge.transfer.data.setLen size copyMem( - addr challenge.transfer.data[0], + addr challenge.transfer.data[0], addr challenge.file.file.compressed[challenge.transfer.pos], size) client.send HFileTransfer, challenge.transfer @@ -90,7 +90,7 @@ proc startSend*(challenge: PFileChallengeSequence, client: PClient) = ## HFileTransfer proc handleFilePartAck*(client: PClient; buffer: PBuffer) = echo "got filepartack" - var + var ftrans = readCsFilepartAck(buffer) fcSeq = fileChallenges[client.id] fcSeq.transfer.pos = ftrans.lastPos @@ -99,7 +99,7 @@ proc handleFilePartAck*(client: PClient; buffer: PBuffer) = ## HFileCHallenge proc handleFileChallengeResp*(client: PClient; buffer: PBuffer) = echo "got file challenge resp" - var + var fcResp = readCsFileChallenge(buffer) fcSeq = fileChallenges[client.id] let index = $(fcSeq.index + 1) / $(myAssets.len) diff --git a/tests/manyloc/keineschweine/keineschweine.nim b/tests/manyloc/keineschweine/keineschweine.nim index 525d8a054..49c0a2476 100644 --- a/tests/manyloc/keineschweine/keineschweine.nim +++ b/tests/manyloc/keineschweine/keineschweine.nim @@ -1,4 +1,4 @@ -import +import os, math, strutils, gl, tables, sfml, sfml_audio, sfml_colors, chipmunk, math_helpers, input_helpers, animations, game_objects, sfml_stuff, map_filter, @@ -29,7 +29,7 @@ type angle*: float PItem* = ref object record: PItemRecord - cooldown: float + cooldown: float PLiveBullet* = ref TLiveBullet ##represents a live bullet in the arena TLiveBullet* = object lifetime*: float @@ -80,7 +80,7 @@ var delObjects: seq[int] = @[] showShipSelect = false myPosition: array[0..1, TVector3f] ##for audio positioning -let +let nameTagOffset = vec2f(0.0, 1.0) when defined(escapeMenuTest): import browsers @@ -100,10 +100,10 @@ when defined(escapeMenuTest): when defined(foo): var mouseSprite: sfml.PCircleShape when defined(recordMode): - var + var snapshots: seq[PImage] = @[] isRecording = false - proc startRecording() = + proc startRecording() = if snapshots.len > 100: return echo "Started recording" isRecording = true @@ -142,26 +142,26 @@ proc mouseToSpace*(): TVector = proc explode*(b: PLiveBullet) ## TCollisionBeginFunc -proc collisionBulletPlayer(arb: PArbiter; space: PSpace; +proc collisionBulletPlayer(arb: PArbiter; space: PSpace; data: pointer): bool{.cdecl.} = - var + var bullet = cast[PLiveBullet](arb.a.data) target = cast[PVehicle](arb.b.data) if target.occupant.isNil or target.occupant == bullet.fromPlayer: return bullet.explode() proc angularDampingSim(body: PBody, gravity: TVector, damping, dt: CpFloat){.cdecl.} = - body.w -= (body.w * 0.98 * dt) + body.w -= (body.w * 0.98 * dt) body.UpdateVelocity(gravity, damping, dt) proc initLevel() = loadAllAssets() - + if not space.isNil: space.destroy() space = newSpace() space.addCollisionHandler CTBullet, CTVehicle, collisionBulletPlayer, nil, nil, nil, nil - + let levelSettings = getLevelSettings() levelArea.width = levelSettings.size.x levelArea.height= levelSettings.size.y @@ -171,8 +171,8 @@ proc initLevel() = for i in 0..3: var seg = space.addShape( newSegmentShape( - space.staticBody, - borderSeq[i], + space.staticBody, + borderSeq[i], borderSeq[(i + 1) mod 4], 8.0)) seg.setElasticity 0.96 @@ -188,8 +188,8 @@ proc initLevel() = for veh in playableVehicles(): shipSelect.newButton( veh.name, - position = pos, - onClick = proc(b: PButton) = + position = pos, + onClick = proc(b: PButton) = echo "-__-") pos.y += 18.0 @@ -199,7 +199,7 @@ proc newItem*(record: PItemRecord): PItem = result.record = record proc newItem*(name: string): PItem {.inline.} = return newItem(fetchItm(name)) -proc canUse*(itm: PItem): bool = +proc canUse*(itm: PItem): bool = if itm.cooldown > 0.0: return return true proc update*(itm: PItem; dt: float) = @@ -252,7 +252,7 @@ proc newBullet*(record: PBulletRecord; fromPlayer: PPlayer): PLiveBullet = result.shape.setLayers(LEnemyFire) result.shape.setCollisionType CTBullet result.shape.setUserData(cast[ptr TLiveBullet](result)) - let + let fireAngle = fromPlayer.vehicle.body.getAngle() fireAngleV = vectorForAngle(fireAngle) result.body.setAngle fireAngle @@ -341,14 +341,14 @@ proc update*(obj: PPlayer) = obj.nameTag.setPosition(obj.vehicle.body.getPos.floor + (nameTagOffset * (obj.vehicle.record.physics.radius + 5).cfloat)) proc draw(window: PRenderWindow, player: PPlayer) {.inline.} = - if not player.spectator: + if not player.spectator: if player.vehicle != nil: window.draw(player.vehicle.sprite) window.draw(player.nameTag) -proc setVehicle(p: PPlayer; v: PVehicle) = +proc setVehicle(p: PPlayer; v: PVehicle) = p.vehicle = v #sorry mom, this is just how things worked out ;( - if not v.isNil: + if not v.isNil: v.occupant = p proc createBot() = @@ -369,7 +369,7 @@ var inputCursor = newVertexArray(sfml.Lines, 2) inputCursor[0].position = vec2f(10.0, 10.0) inputCursor[1].position = vec2f(50.0, 90.0) -proc hasVehicle(p: PPlayer): bool {.inline.} = +proc hasVehicle(p: PPlayer): bool {.inline.} = result = not p.spectator and not p.vehicle.isNil proc setMyVehicle(v: PVehicle) {.inline.} = @@ -396,27 +396,27 @@ proc spec() = localPlayer.spectator = true specInputClient.setActive -var +var specLimiter = newClock() timeBetweenSpeccing = 1.0 #seconds proc toggleSpec() {.inline.} = if specLimiter.getElapsedTime.asSeconds < timeBetweenSpeccing: return specLimiter.restart() - if localPlayer.isNil: + if localPlayer.isNil: echo("OMG WTF PLAYER IS NILL!!") elif localPlayer.spectator: unspec() else: spec() proc addObject*(name: string) = var o = newObject(name) - if not o.isNil: + if not o.isNil: echo "Adding object ", o discard space.addBody(o.body) discard space.addShape(o.shape) o.shape.setLayers(LGrabbable) objects.add(o) -proc explode(obj: PGameObject) = +proc explode(obj: PGameObject) = echo obj, " exploded" let ind = objects.find(obj) if ind != -1: @@ -428,7 +428,7 @@ proc update(obj: PGameObject; dt: float) = obj.anim.setPos(obj.body.getPos) obj.anim.setAngle(obj.body.getAngle) -proc toggleShipSelect() = +proc toggleShipSelect() = showShipSelect = not showShipSelect proc handleLClick() = let pos = input_helpers.getMousePos() @@ -459,9 +459,9 @@ when defined(recordMode): snapshots[i].destroy() snapshots.setLen 0) when defined(DebugKeys): - ingameClient.registerHandler MouseRight, down, proc() = + ingameClient.registerHandler MouseRight, down, proc() = echo($activevehicle.body.getAngle.vectorForAngle()) - ingameClient.registerHandler KeyBackslash, down, proc() = + ingameClient.registerHandler KeyBackslash, down, proc() = createBot() ingameClient.registerHandler(KeyNum1, down, proc() = if localPlayer.items.len == 0: @@ -493,7 +493,7 @@ when defined(DebugKeys): for i, o in pairs(objects): echo i, " ", o) ingameClient.registerHandler(KeyLBracket, down, sound_buffer.report) - var + var mouseJoint: PConstraint mouseBody = space.addBody(newBody(CpInfinity, CpInfinity)) ingameClient.registerHandler(MouseMiddle, down, proc() = @@ -503,7 +503,7 @@ when defined(DebugKeys): space.removeConstraint mouseJoint mouseJoint.destroy() mouseJoint = nil - if shape.isNil: + if shape.isNil: return let body = shape.getBody() mouseJoint = space.addConstraint( @@ -564,42 +564,42 @@ proc mainUpdate(dt: float) = if keyPressed(KeyD): localPlayer.useItem 6 worldView.setCenter(activeVehicle.body.getPos.floor)#cp2sfml) - - if localPlayer != nil: + + if localPlayer != nil: localPlayer.update() localPlayer.updateItems(dt) for b in localBots: b.update() - + for o in items(objects): o.update(dt) for i in countdown(high(delObjects), 0): objects.del i delObjects.setLen 0 - + var i = 0 while i < len(liveBullets): if liveBullets[i].update(dt): liveBullets.del i - else: + else: inc i i = 0 while i < len(explosions): if explosions[i].next(dt): inc i else: explosions.del i - + when defined(DebugKeys): mouseBody.setPos(mouseToSpace()) - + space.step(dt) space.eachBody(resetForcesCB, nil) - + when defined(foo): var coords = window.convertCoords(vec2i(getMousePos()), worldView) mouseSprite.setPosition(coords) - + if localPlayer != nil and localPlayer.vehicle != nil: - let + let pos = localPlayer.vehicle.body.getPos() ang = localPlayer.vehicle.body.getAngle.vectorForAngle() myPosition[0].x = pos.x @@ -608,7 +608,7 @@ proc mainUpdate(dt: float) = myPosition[1].z = ang.y listenerSetPosition(myPosition[0]) listenerSetDirection(myPosition[1]) - + inc frameCount when defined(showFPS): if frameCount mod 60 == 0: @@ -620,25 +620,25 @@ proc mainUpdate(dt: float) = proc mainRender() = window.clear(Black) window.setView(worldView) - + if showStars: for star in stars: window.draw(star.sprite) window.draw(localPlayer) - + for b in localBots: window.draw(b) for o in objects: window.draw(o) - + for b in explosions: window.draw(b) for b in liveBullets: window.draw(b) - + when defined(Foo): window.draw(mouseSprite) - + window.setView(guiView) - + when defined(EscapeMenuTest): if escMenuOpen: window.draw escMenu @@ -646,12 +646,12 @@ proc mainRender() = window.draw(fpsText) when defined(recordMode): window.draw(recordButton) - + if localPlayer.spectator: window.draw(specGui) if showShipSelect: window.draw shipSelect window.display() - + when defined(recordMode): if isRecording: if snapshots.len < 100: @@ -664,30 +664,30 @@ proc readyMainState() = when isMainModule: import parseopt - + localPlayer = newPlayer() lobbyInit() - + videoMode = getClientSettings().resolution window = newRenderWindow(videoMode, "sup", sfDefaultStyle) window.setFrameRateLimit 60 - + worldView = window.getView.copy() guiView = worldView.copy() shipSelect.setPosition vec2f(665.0, 50.0) - + when defined(foo): mouseSprite = sfml.newCircleShape(14) mouseSprite.setFillColor Transparent mouseSprite.setOutlineColor RoyalBlue mouseSprite.setOutlineThickness 1.4 mouseSprite.setOrigin vec2f(14, 14) - + lobbyReady() playBtn = specGui.newButton( "Unspec - F12", position = vec2f(680.0, 8.0), onClick = proc(b: PButton) = toggleSpec()) - + block: var bPlayOffline = false for kind, key, val in getOpt(): @@ -698,7 +698,7 @@ when isMainModule: echo "Invalid argument ", key, " ", val if bPlayOffline: playoffline(nil) - + gameRunning = true while gameRunning: for event in window.filterEvents: diff --git a/tests/manyloc/keineschweine/lib/client_helpers.nim b/tests/manyloc/keineschweine/lib/client_helpers.nim index 84e42b62e..f2833fe14 100644 --- a/tests/manyloc/keineschweine/lib/client_helpers.nim +++ b/tests/manyloc/keineschweine/lib/client_helpers.nim @@ -1,4 +1,4 @@ -import +import tables, sg_packets, enet, estreams, sg_gui, sfml, zlib_helpers, md5, sg_assets, os type @@ -17,7 +17,7 @@ type pos: int32 data: string readyToSave: bool -var +var currentFileTransfer: TFileTransfer downloadProgress* = newButton(nil, "", vec2f(0,0), nil) currentFileTransfer.data = "" @@ -73,7 +73,7 @@ proc handleFilePartRecv*(serv: PServer; buffer: PBuffer) {.procvar.} = var f = readScFileTransfer(buffer) updateFileProgress() - if not(f.pos == currentFileTransfer.pos): + if not(f.pos == currentFileTransfer.pos): echo "returning early from filepartrecv" return ##issues, probably if currentFileTransfer.data.len == 0: @@ -100,7 +100,7 @@ proc handleFilePartRecv*(serv: PServer; buffer: PBuffer) {.procvar.} = proc saveCurrentFile() = if not currentFileTransfer.readyToSave: return - let + let path = expandPath(currentFileTransfer.assetType, currentFileTransfer.fileName) parent = parentDir(path) if not existsDir(parent): @@ -123,7 +123,7 @@ proc handleFileChallengeResult*(serv: PServer; buffer: PBuffer) {.procvar.} = ## HFileCHallenge proc handleFileChallenge*(serv: PServer; buffer: PBuffer) {.procvar.} = - var + var challenge = readScFileChallenge(buffer) path = expandPath(challenge) resp: CsFileChallenge diff --git a/tests/manyloc/keineschweine/lib/estreams.nim b/tests/manyloc/keineschweine/lib/estreams.nim index ecafaed89..bdf9b2bf0 100644 --- a/tests/manyloc/keineschweine/lib/estreams.nim +++ b/tests/manyloc/keineschweine/lib/estreams.nim @@ -1,6 +1,6 @@ import endians -proc swapEndian16*(outp, inp: pointer) = +proc swapEndian16*(outp, inp: pointer) = ## copies `inp` to `outp` swapping bytes. Both buffers are supposed to ## contain at least 2 bytes. var i = cast[cstring](inp) @@ -113,10 +113,10 @@ when isMainModule: echo(repr(b)) b.pos = 0 echo(repr(b.readStr())) - + b.flush() echo "flushed" b.writeC([1,2,3]) echo(repr(b)) - - + + diff --git a/tests/manyloc/keineschweine/lib/gl.nim b/tests/manyloc/keineschweine/lib/gl.nim index c577f3404..b634a96cf 100644 --- a/tests/manyloc/keineschweine/lib/gl.nim +++ b/tests/manyloc/keineschweine/lib/gl.nim @@ -5,24 +5,24 @@ # These units are free to use # #****************************************************************************** -# Converted to Delphi by Tom Nuydens (tom@delphi3d.net) -# For the latest updates, visit Delphi3D: http://www.delphi3d.net +# Converted to Delphi by Tom Nuydens (tom@delphi3d.net) +# For the latest updates, visit Delphi3D: http://www.delphi3d.net #****************************************************************************** -when defined(windows): +when defined(windows): {.push, callconv: stdcall.} -else: +else: {.push, callconv: cdecl.} -when defined(windows): - const +when defined(windows): + const dllname* = "opengl32.dll" -elif defined(macosx): - const +elif defined(macosx): + const dllname* = "/System/Library/Frameworks/OpenGL.framework/Libraries/libGL.dylib" -else: - const +else: + const dllname* = "libGL.so.1" -type +type PGLenum* = ptr TGLenum PGLboolean* = ptr TGLboolean PGLbitfield* = ptr TGLbitfield @@ -983,128 +983,128 @@ const # Version GL_TEXTURE_COMPONENTS* = GL_TEXTURE_INTERNAL_FORMAT proc glAccum*(op: TGLenum, value: TGLfloat){.dynlib: dllname, importc: "glAccum".} -proc glAlphaFunc*(fun: TGLenum, theref: TGLclampf){.dynlib: dllname, +proc glAlphaFunc*(fun: TGLenum, theref: TGLclampf){.dynlib: dllname, importc: "glAlphaFunc".} -proc glAreTexturesResident*(n: TGLsizei, textures: PGLuint, +proc glAreTexturesResident*(n: TGLsizei, textures: PGLuint, residences: PGLboolean): TGLboolean{. dynlib: dllname, importc: "glAreTexturesResident".} proc glArrayElement*(i: TGLint){.dynlib: dllname, importc: "glArrayElement".} proc glBegin*(mode: TGLenum){.dynlib: dllname, importc: "glBegin".} -proc glBindTexture*(target: TGLenum, texture: TGLuint){.dynlib: dllname, +proc glBindTexture*(target: TGLenum, texture: TGLuint){.dynlib: dllname, importc: "glBindTexture".} -proc glBitmap*(width, height: TGLsizei, xorig, yorig: TGLfloat, - xmove, ymove: TGLfloat, bitmap: PGLubyte){.dynlib: dllname, +proc glBitmap*(width, height: TGLsizei, xorig, yorig: TGLfloat, + xmove, ymove: TGLfloat, bitmap: PGLubyte){.dynlib: dllname, importc: "glBitmap".} -proc glBlendFunc*(sfactor, dfactor: TGLenum){.dynlib: dllname, +proc glBlendFunc*(sfactor, dfactor: TGLenum){.dynlib: dllname, importc: "glBlendFunc".} proc glCallList*(list: TGLuint){.dynlib: dllname, importc: "glCallList".} -proc glCallLists*(n: TGLsizei, atype: TGLenum, lists: pointer){.dynlib: dllname, +proc glCallLists*(n: TGLsizei, atype: TGLenum, lists: pointer){.dynlib: dllname, importc: "glCallLists".} proc glClear*(mask: TGLbitfield){.dynlib: dllname, importc: "glClear".} -proc glClearAccum*(red, green, blue, alpha: TGLfloat){.dynlib: dllname, +proc glClearAccum*(red, green, blue, alpha: TGLfloat){.dynlib: dllname, importc: "glClearAccum".} -proc glClearColor*(red, green, blue, alpha: TGLclampf){.dynlib: dllname, +proc glClearColor*(red, green, blue, alpha: TGLclampf){.dynlib: dllname, importc: "glClearColor".} proc glClearDepth*(depth: TGLclampd){.dynlib: dllname, importc: "glClearDepth".} proc glClearIndex*(c: TGLfloat){.dynlib: dllname, importc: "glClearIndex".} proc glClearStencil*(s: TGLint){.dynlib: dllname, importc: "glClearStencil".} -proc glClipPlane*(plane: TGLenum, equation: PGLdouble){.dynlib: dllname, +proc glClipPlane*(plane: TGLenum, equation: PGLdouble){.dynlib: dllname, importc: "glClipPlane".} -proc glColor3b*(red, green, blue: TGlbyte){.dynlib: dllname, +proc glColor3b*(red, green, blue: TGlbyte){.dynlib: dllname, importc: "glColor3b".} proc glColor3bv*(v: PGLbyte){.dynlib: dllname, importc: "glColor3bv".} -proc glColor3d*(red, green, blue: TGLdouble){.dynlib: dllname, +proc glColor3d*(red, green, blue: TGLdouble){.dynlib: dllname, importc: "glColor3d".} proc glColor3dv*(v: PGLdouble){.dynlib: dllname, importc: "glColor3dv".} -proc glColor3f*(red, green, blue: TGLfloat){.dynlib: dllname, +proc glColor3f*(red, green, blue: TGLfloat){.dynlib: dllname, importc: "glColor3f".} proc glColor3fv*(v: PGLfloat){.dynlib: dllname, importc: "glColor3fv".} proc glColor3i*(red, green, blue: TGLint){.dynlib: dllname, importc: "glColor3i".} proc glColor3iv*(v: PGLint){.dynlib: dllname, importc: "glColor3iv".} -proc glColor3s*(red, green, blue: TGLshort){.dynlib: dllname, +proc glColor3s*(red, green, blue: TGLshort){.dynlib: dllname, importc: "glColor3s".} proc glColor3sv*(v: PGLshort){.dynlib: dllname, importc: "glColor3sv".} -proc glColor3ub*(red, green, blue: TGLubyte){.dynlib: dllname, +proc glColor3ub*(red, green, blue: TGLubyte){.dynlib: dllname, importc: "glColor3ub".} proc glColor3ubv*(v: PGLubyte){.dynlib: dllname, importc: "glColor3ubv".} -proc glColor3ui*(red, green, blue: TGLuint){.dynlib: dllname, +proc glColor3ui*(red, green, blue: TGLuint){.dynlib: dllname, importc: "glColor3ui".} proc glColor3uiv*(v: PGLuint){.dynlib: dllname, importc: "glColor3uiv".} -proc glColor3us*(red, green, blue: TGLushort){.dynlib: dllname, +proc glColor3us*(red, green, blue: TGLushort){.dynlib: dllname, importc: "glColor3us".} proc glColor3usv*(v: PGLushort){.dynlib: dllname, importc: "glColor3usv".} -proc glColor4b*(red, green, blue, alpha: TGlbyte){.dynlib: dllname, +proc glColor4b*(red, green, blue, alpha: TGlbyte){.dynlib: dllname, importc: "glColor4b".} proc glColor4bv*(v: PGLbyte){.dynlib: dllname, importc: "glColor4bv".} -proc glColor4d*(red, green, blue, alpha: TGLdouble){.dynlib: dllname, +proc glColor4d*(red, green, blue, alpha: TGLdouble){.dynlib: dllname, importc: "glColor4d".} proc glColor4dv*(v: PGLdouble){.dynlib: dllname, importc: "glColor4dv".} -proc glColor4f*(red, green, blue, alpha: TGLfloat){.dynlib: dllname, +proc glColor4f*(red, green, blue, alpha: TGLfloat){.dynlib: dllname, importc: "glColor4f".} proc glColor4fv*(v: PGLfloat){.dynlib: dllname, importc: "glColor4fv".} -proc glColor4i*(red, green, blue, alpha: TGLint){.dynlib: dllname, +proc glColor4i*(red, green, blue, alpha: TGLint){.dynlib: dllname, importc: "glColor4i".} proc glColor4iv*(v: PGLint){.dynlib: dllname, importc: "glColor4iv".} -proc glColor4s*(red, green, blue, alpha: TGLshort){.dynlib: dllname, +proc glColor4s*(red, green, blue, alpha: TGLshort){.dynlib: dllname, importc: "glColor4s".} proc glColor4sv*(v: PGLshort){.dynlib: dllname, importc: "glColor4sv".} -proc glColor4ub*(red, green, blue, alpha: TGLubyte){.dynlib: dllname, +proc glColor4ub*(red, green, blue, alpha: TGLubyte){.dynlib: dllname, importc: "glColor4ub".} proc glColor4ubv*(v: PGLubyte){.dynlib: dllname, importc: "glColor4ubv".} -proc glColor4ui*(red, green, blue, alpha: TGLuint){.dynlib: dllname, +proc glColor4ui*(red, green, blue, alpha: TGLuint){.dynlib: dllname, importc: "glColor4ui".} proc glColor4uiv*(v: PGLuint){.dynlib: dllname, importc: "glColor4uiv".} -proc glColor4us*(red, green, blue, alpha: TGLushort){.dynlib: dllname, +proc glColor4us*(red, green, blue, alpha: TGLushort){.dynlib: dllname, importc: "glColor4us".} proc glColor4usv*(v: PGLushort){.dynlib: dllname, importc: "glColor4usv".} -proc glColorMask*(red, green, blue, alpha: TGLboolean){.dynlib: dllname, +proc glColorMask*(red, green, blue, alpha: TGLboolean){.dynlib: dllname, importc: "glColorMask".} -proc glColorMaterial*(face, mode: TGLenum){.dynlib: dllname, +proc glColorMaterial*(face, mode: TGLenum){.dynlib: dllname, importc: "glColorMaterial".} -proc glColorPointer*(size: TGLint, atype: TGLenum, stride: TGLsizei, - p: pointer){.dynlib: dllname, +proc glColorPointer*(size: TGLint, atype: TGLenum, stride: TGLsizei, + p: pointer){.dynlib: dllname, importc: "glColorPointer".} proc glCopyPixels*(x, y: TGLint, width, height: TGLsizei, atype: TGLenum){. dynlib: dllname, importc: "glCopyPixels".} -proc glCopyTexImage1D*(target: TGLenum, level: TGLint, internalFormat: TGLenum, +proc glCopyTexImage1D*(target: TGLenum, level: TGLint, internalFormat: TGLenum, x, y: TGLint, width: TGLsizei, border: TGLint){. dynlib: dllname, importc: "glCopyTexImage1D".} -proc glCopyTexImage2D*(target: TGLenum, level: TGLint, internalFormat: TGLenum, +proc glCopyTexImage2D*(target: TGLenum, level: TGLint, internalFormat: TGLenum, x, y: TGLint, width, height: TGLsizei, border: TGLint){. dynlib: dllname, importc: "glCopyTexImage2D".} -proc glCopyTexSubImage1D*(target: TGLenum, level, xoffset, x, y: TGLint, - width: TGLsizei){.dynlib: dllname, +proc glCopyTexSubImage1D*(target: TGLenum, level, xoffset, x, y: TGLint, + width: TGLsizei){.dynlib: dllname, importc: "glCopyTexSubImage1D".} -proc glCopyTexSubImage2D*(target: TGLenum, - level, xoffset, yoffset, x, y: TGLint, - width, height: TGLsizei){.dynlib: dllname, +proc glCopyTexSubImage2D*(target: TGLenum, + level, xoffset, yoffset, x, y: TGLint, + width, height: TGLsizei){.dynlib: dllname, importc: "glCopyTexSubImage2D".} proc glCullFace*(mode: TGLenum){.dynlib: dllname, importc: "glCullFace".} -proc glDeleteLists*(list: TGLuint, range: TGLsizei){.dynlib: dllname, +proc glDeleteLists*(list: TGLuint, range: TGLsizei){.dynlib: dllname, importc: "glDeleteLists".} -proc glDeleteTextures*(n: TGLsizei, textures: PGLuint){.dynlib: dllname, +proc glDeleteTextures*(n: TGLsizei, textures: PGLuint){.dynlib: dllname, importc: "glDeleteTextures".} proc glDepthFunc*(fun: TGLenum){.dynlib: dllname, importc: "glDepthFunc".} proc glDepthMask*(flag: TGLboolean){.dynlib: dllname, importc: "glDepthMask".} -proc glDepthRange*(zNear, zFar: TGLclampd){.dynlib: dllname, +proc glDepthRange*(zNear, zFar: TGLclampd){.dynlib: dllname, importc: "glDepthRange".} proc glDisable*(cap: TGLenum){.dynlib: dllname, importc: "glDisable".} -proc glDisableClientState*(aarray: TGLenum){.dynlib: dllname, +proc glDisableClientState*(aarray: TGLenum){.dynlib: dllname, importc: "glDisableClientState".} proc glDrawArrays*(mode: TGLenum, first: TGLint, count: TGLsizei){. dynlib: dllname, importc: "glDrawArrays".} proc glDrawBuffer*(mode: TGLenum){.dynlib: dllname, importc: "glDrawBuffer".} -proc glDrawElements*(mode: TGLenum, count: TGLsizei, atype: TGLenum, - indices: pointer){.dynlib: dllname, +proc glDrawElements*(mode: TGLenum, count: TGLsizei, atype: TGLenum, + indices: pointer){.dynlib: dllname, importc: "glDrawElements".} -proc glDrawPixels*(width, height: TGLsizei, format, atype: TGLenum, +proc glDrawPixels*(width, height: TGLsizei, format, atype: TGLenum, pixels: pointer){.dynlib: dllname, importc: "glDrawPixels".} proc glEdgeFlag*(flag: TGLboolean){.dynlib: dllname, importc: "glEdgeFlag".} -proc glEdgeFlagPointer*(stride: TGLsizei, p: pointer){.dynlib: dllname, +proc glEdgeFlagPointer*(stride: TGLsizei, p: pointer){.dynlib: dllname, importc: "glEdgeFlagPointer".} proc glEdgeFlagv*(flag: PGLboolean){.dynlib: dllname, importc: "glEdgeFlagv".} proc glEnable*(cap: TGLenum){.dynlib: dllname, importc: "glEnable".} -proc glEnableClientState*(aarray: TGLenum){.dynlib: dllname, +proc glEnableClientState*(aarray: TGLenum){.dynlib: dllname, importc: "glEnableClientState".} proc glEnd*(){.dynlib: dllname, importc: "glEnd".} proc glEndList*(){.dynlib: dllname, importc: "glEndList".} @@ -1116,9 +1116,9 @@ proc glEvalCoord2d*(u, v: TGLdouble){.dynlib: dllname, importc: "glEvalCoord2d". proc glEvalCoord2dv*(u: PGLdouble){.dynlib: dllname, importc: "glEvalCoord2dv".} proc glEvalCoord2f*(u, v: TGLfloat){.dynlib: dllname, importc: "glEvalCoord2f".} proc glEvalCoord2fv*(u: PGLfloat){.dynlib: dllname, importc: "glEvalCoord2fv".} -proc glEvalMesh1*(mode: TGLenum, i1, i2: TGLint){.dynlib: dllname, +proc glEvalMesh1*(mode: TGLenum, i1, i2: TGLint){.dynlib: dllname, importc: "glEvalMesh1".} -proc glEvalMesh2*(mode: TGLenum, i1, i2, j1, j2: TGLint){.dynlib: dllname, +proc glEvalMesh2*(mode: TGLenum, i1, i2, j1, j2: TGLint){.dynlib: dllname, importc: "glEvalMesh2".} proc glEvalPoint1*(i: TGLint){.dynlib: dllname, importc: "glEvalPoint1".} proc glEvalPoint2*(i, j: TGLint){.dynlib: dllname, importc: "glEvalPoint2".} @@ -1126,75 +1126,75 @@ proc glFeedbackBuffer*(size: TGLsizei, atype: TGLenum, buffer: PGLfloat){. dynlib: dllname, importc: "glFeedbackBuffer".} proc glFinish*(){.dynlib: dllname, importc: "glFinish".} proc glFlush*(){.dynlib: dllname, importc: "glFlush".} -proc glFogf*(pname: TGLenum, param: TGLfloat){.dynlib: dllname, +proc glFogf*(pname: TGLenum, param: TGLfloat){.dynlib: dllname, importc: "glFogf".} -proc glFogfv*(pname: TGLenum, params: PGLfloat){.dynlib: dllname, +proc glFogfv*(pname: TGLenum, params: PGLfloat){.dynlib: dllname, importc: "glFogfv".} proc glFogi*(pname: TGLenum, param: TGLint){.dynlib: dllname, importc: "glFogi".} -proc glFogiv*(pname: TGLenum, params: PGLint){.dynlib: dllname, +proc glFogiv*(pname: TGLenum, params: PGLint){.dynlib: dllname, importc: "glFogiv".} proc glFrontFace*(mode: TGLenum){.dynlib: dllname, importc: "glFrontFace".} proc glFrustum*(left, right, bottom, top, zNear, zFar: TGLdouble){. dynlib: dllname, importc: "glFrustum".} -proc glGenLists*(range: TGLsizei): TGLuint{.dynlib: dllname, +proc glGenLists*(range: TGLsizei): TGLuint{.dynlib: dllname, importc: "glGenLists".} -proc glGenTextures*(n: TGLsizei, textures: PGLuint){.dynlib: dllname, +proc glGenTextures*(n: TGLsizei, textures: PGLuint){.dynlib: dllname, importc: "glGenTextures".} -proc glGetBooleanv*(pname: TGLenum, params: PGLboolean){.dynlib: dllname, +proc glGetBooleanv*(pname: TGLenum, params: PGLboolean){.dynlib: dllname, importc: "glGetBooleanv".} -proc glGetClipPlane*(plane: TGLenum, equation: PGLdouble){.dynlib: dllname, +proc glGetClipPlane*(plane: TGLenum, equation: PGLdouble){.dynlib: dllname, importc: "glGetClipPlane".} -proc glGetDoublev*(pname: TGLenum, params: PGLdouble){.dynlib: dllname, +proc glGetDoublev*(pname: TGLenum, params: PGLdouble){.dynlib: dllname, importc: "glGetDoublev".} proc glGetError*(): TGLenum{.dynlib: dllname, importc: "glGetError".} -proc glGetFloatv*(pname: TGLenum, params: PGLfloat){.dynlib: dllname, +proc glGetFloatv*(pname: TGLenum, params: PGLfloat){.dynlib: dllname, importc: "glGetFloatv".} -proc glGetIntegerv*(pname: TGLenum, params: PGLint){.dynlib: dllname, +proc glGetIntegerv*(pname: TGLenum, params: PGLint){.dynlib: dllname, importc: "glGetIntegerv".} -proc glGetLightfv*(light, pname: TGLenum, params: PGLfloat){.dynlib: dllname, +proc glGetLightfv*(light, pname: TGLenum, params: PGLfloat){.dynlib: dllname, importc: "glGetLightfv".} -proc glGetLightiv*(light, pname: TGLenum, params: PGLint){.dynlib: dllname, +proc glGetLightiv*(light, pname: TGLenum, params: PGLint){.dynlib: dllname, importc: "glGetLightiv".} -proc glGetMapdv*(target, query: TGLenum, v: PGLdouble){.dynlib: dllname, +proc glGetMapdv*(target, query: TGLenum, v: PGLdouble){.dynlib: dllname, importc: "glGetMapdv".} -proc glGetMapfv*(target, query: TGLenum, v: PGLfloat){.dynlib: dllname, +proc glGetMapfv*(target, query: TGLenum, v: PGLfloat){.dynlib: dllname, importc: "glGetMapfv".} -proc glGetMapiv*(target, query: TGLenum, v: PGLint){.dynlib: dllname, +proc glGetMapiv*(target, query: TGLenum, v: PGLint){.dynlib: dllname, importc: "glGetMapiv".} -proc glGetMaterialfv*(face, pname: TGLenum, params: PGLfloat){.dynlib: dllname, +proc glGetMaterialfv*(face, pname: TGLenum, params: PGLfloat){.dynlib: dllname, importc: "glGetMaterialfv".} -proc glGetMaterialiv*(face, pname: TGLenum, params: PGLint){.dynlib: dllname, +proc glGetMaterialiv*(face, pname: TGLenum, params: PGLint){.dynlib: dllname, importc: "glGetMaterialiv".} -proc glGetPixelMapfv*(map: TGLenum, values: PGLfloat){.dynlib: dllname, +proc glGetPixelMapfv*(map: TGLenum, values: PGLfloat){.dynlib: dllname, importc: "glGetPixelMapfv".} -proc glGetPixelMapuiv*(map: TGLenum, values: PGLuint){.dynlib: dllname, +proc glGetPixelMapuiv*(map: TGLenum, values: PGLuint){.dynlib: dllname, importc: "glGetPixelMapuiv".} -proc glGetPixelMapusv*(map: TGLenum, values: PGLushort){.dynlib: dllname, +proc glGetPixelMapusv*(map: TGLenum, values: PGLushort){.dynlib: dllname, importc: "glGetPixelMapusv".} -proc glGetPointerv*(pname: TGLenum, params: pointer){.dynlib: dllname, +proc glGetPointerv*(pname: TGLenum, params: pointer){.dynlib: dllname, importc: "glGetPointerv".} -proc glGetPolygonStipple*(mask: PGLubyte){.dynlib: dllname, +proc glGetPolygonStipple*(mask: PGLubyte){.dynlib: dllname, importc: "glGetPolygonStipple".} -proc glGetString*(name: TGLenum): cstring{.dynlib: dllname, +proc glGetString*(name: TGLenum): cstring{.dynlib: dllname, importc: "glGetString".} -proc glGetTexEnvfv*(target, pname: TGLenum, params: PGLfloat){.dynlib: dllname, +proc glGetTexEnvfv*(target, pname: TGLenum, params: PGLfloat){.dynlib: dllname, importc: "glGetTexEnvfv".} -proc glGetTexEnviv*(target, pname: TGLenum, params: PGLint){.dynlib: dllname, +proc glGetTexEnviv*(target, pname: TGLenum, params: PGLint){.dynlib: dllname, importc: "glGetTexEnviv".} -proc glGetTexGendv*(coord, pname: TGLenum, params: PGLdouble){.dynlib: dllname, +proc glGetTexGendv*(coord, pname: TGLenum, params: PGLdouble){.dynlib: dllname, importc: "glGetTexGendv".} -proc glGetTexGenfv*(coord, pname: TGLenum, params: PGLfloat){.dynlib: dllname, +proc glGetTexGenfv*(coord, pname: TGLenum, params: PGLfloat){.dynlib: dllname, importc: "glGetTexGenfv".} -proc glGetTexGeniv*(coord, pname: TGLenum, params: PGLint){.dynlib: dllname, +proc glGetTexGeniv*(coord, pname: TGLenum, params: PGLint){.dynlib: dllname, importc: "glGetTexGeniv".} -proc glGetTexImage*(target: TGLenum, level: TGLint, format: TGLenum, - atype: TGLenum, pixels: pointer){.dynlib: dllname, +proc glGetTexImage*(target: TGLenum, level: TGLint, format: TGLenum, + atype: TGLenum, pixels: pointer){.dynlib: dllname, importc: "glGetTexImage".} -proc glGetTexLevelParameterfv*(target: TGLenum, level: TGLint, pname: TGLenum, - params: pointer){.dynlib: dllname, +proc glGetTexLevelParameterfv*(target: TGLenum, level: TGLint, pname: TGLenum, + params: pointer){.dynlib: dllname, importc: "glGetTexLevelParameterfv".} -proc glGetTexLevelParameteriv*(target: TGLenum, level: TGLint, pname: TGLenum, - params: PGLint){.dynlib: dllname, +proc glGetTexLevelParameteriv*(target: TGLenum, level: TGLint, pname: TGLenum, + params: PGLint){.dynlib: dllname, importc: "glGetTexLevelParameteriv".} proc glGetTexParameterfv*(target, pname: TGLenum, params: PGLfloat){. dynlib: dllname, importc: "glGetTexParameterfv".} @@ -1217,28 +1217,28 @@ proc glIndexubv*(c: PGLubyte){.dynlib: dllname, importc: "glIndexubv".} proc glInitNames*(){.dynlib: dllname, importc: "glInitNames".} proc glInterleavedArrays*(format: TGLenum, stride: TGLsizei, p: pointer){. dynlib: dllname, importc: "glInterleavedArrays".} -proc glIsEnabled*(cap: TGLenum): TGLboolean{.dynlib: dllname, +proc glIsEnabled*(cap: TGLenum): TGLboolean{.dynlib: dllname, importc: "glIsEnabled".} proc glIsList*(list: TGLuint): TGLboolean{.dynlib: dllname, importc: "glIsList".} -proc glIsTexture*(texture: TGLuint): TGLboolean{.dynlib: dllname, +proc glIsTexture*(texture: TGLuint): TGLboolean{.dynlib: dllname, importc: "glIsTexture".} -proc glLightModelf*(pname: TGLenum, param: TGLfloat){.dynlib: dllname, +proc glLightModelf*(pname: TGLenum, param: TGLfloat){.dynlib: dllname, importc: "glLightModelf".} -proc glLightModelfv*(pname: TGLenum, params: PGLfloat){.dynlib: dllname, +proc glLightModelfv*(pname: TGLenum, params: PGLfloat){.dynlib: dllname, importc: "glLightModelfv".} -proc glLightModeli*(pname: TGLenum, param: TGLint){.dynlib: dllname, +proc glLightModeli*(pname: TGLenum, param: TGLint){.dynlib: dllname, importc: "glLightModeli".} -proc glLightModeliv*(pname: TGLenum, params: PGLint){.dynlib: dllname, +proc glLightModeliv*(pname: TGLenum, params: PGLint){.dynlib: dllname, importc: "glLightModeliv".} -proc glLightf*(light, pname: TGLenum, param: TGLfloat){.dynlib: dllname, +proc glLightf*(light, pname: TGLenum, param: TGLfloat){.dynlib: dllname, importc: "glLightf".} -proc glLightfv*(light, pname: TGLenum, params: PGLfloat){.dynlib: dllname, +proc glLightfv*(light, pname: TGLenum, params: PGLfloat){.dynlib: dllname, importc: "glLightfv".} -proc glLighti*(light, pname: TGLenum, param: TGLint){.dynlib: dllname, +proc glLighti*(light, pname: TGLenum, param: TGLint){.dynlib: dllname, importc: "glLighti".} -proc glLightiv*(light, pname: TGLenum, params: PGLint){.dynlib: dllname, +proc glLightiv*(light, pname: TGLenum, params: PGLint){.dynlib: dllname, importc: "glLightiv".} -proc glLineStipple*(factor: TGLint, pattern: TGLushort){.dynlib: dllname, +proc glLineStipple*(factor: TGLint, pattern: TGLushort){.dynlib: dllname, importc: "glLineStipple".} proc glLineWidth*(width: TGLfloat){.dynlib: dllname, importc: "glLineWidth".} proc glListBase*(base: TGLuint){.dynlib: dllname, importc: "glListBase".} @@ -1247,36 +1247,36 @@ proc glLoadMatrixd*(m: PGLdouble){.dynlib: dllname, importc: "glLoadMatrixd".} proc glLoadMatrixf*(m: PGLfloat){.dynlib: dllname, importc: "glLoadMatrixf".} proc glLoadName*(name: TGLuint){.dynlib: dllname, importc: "glLoadName".} proc glLogicOp*(opcode: TGLenum){.dynlib: dllname, importc: "glLogicOp".} -proc glMap1d*(target: TGLenum, u1, u2: TGLdouble, stride, order: TGLint, +proc glMap1d*(target: TGLenum, u1, u2: TGLdouble, stride, order: TGLint, points: PGLdouble){.dynlib: dllname, importc: "glMap1d".} -proc glMap1f*(target: TGLenum, u1, u2: TGLfloat, stride, order: TGLint, +proc glMap1f*(target: TGLenum, u1, u2: TGLfloat, stride, order: TGLint, points: PGLfloat){.dynlib: dllname, importc: "glMap1f".} -proc glMap2d*(target: TGLenum, u1, u2: TGLdouble, ustride, uorder: TGLint, +proc glMap2d*(target: TGLenum, u1, u2: TGLdouble, ustride, uorder: TGLint, v1, v2: TGLdouble, vstride, vorder: TGLint, points: PGLdouble){. dynlib: dllname, importc: "glMap2d".} -proc glMap2f*(target: TGLenum, u1, u2: TGLfloat, ustride, uorder: TGLint, +proc glMap2f*(target: TGLenum, u1, u2: TGLfloat, ustride, uorder: TGLint, v1, v2: TGLfloat, vstride, vorder: TGLint, points: PGLfloat){. dynlib: dllname, importc: "glMap2f".} -proc glMapGrid1d*(un: TGLint, u1, u2: TGLdouble){.dynlib: dllname, +proc glMapGrid1d*(un: TGLint, u1, u2: TGLdouble){.dynlib: dllname, importc: "glMapGrid1d".} -proc glMapGrid1f*(un: TGLint, u1, u2: TGLfloat){.dynlib: dllname, +proc glMapGrid1f*(un: TGLint, u1, u2: TGLfloat){.dynlib: dllname, importc: "glMapGrid1f".} proc glMapGrid2d*(un: TGLint, u1, u2: TGLdouble, vn: TGLint, v1, v2: TGLdouble){. dynlib: dllname, importc: "glMapGrid2d".} proc glMapGrid2f*(un: TGLint, u1, u2: TGLfloat, vn: TGLint, v1, v2: TGLfloat){. dynlib: dllname, importc: "glMapGrid2f".} -proc glMaterialf*(face, pname: TGLenum, param: TGLfloat){.dynlib: dllname, +proc glMaterialf*(face, pname: TGLenum, param: TGLfloat){.dynlib: dllname, importc: "glMaterialf".} -proc glMaterialfv*(face, pname: TGLenum, params: PGLfloat){.dynlib: dllname, +proc glMaterialfv*(face, pname: TGLenum, params: PGLfloat){.dynlib: dllname, importc: "glMaterialfv".} -proc glMateriali*(face, pname: TGLenum, param: TGLint){.dynlib: dllname, +proc glMateriali*(face, pname: TGLenum, param: TGLint){.dynlib: dllname, importc: "glMateriali".} -proc glMaterialiv*(face, pname: TGLenum, params: PGLint){.dynlib: dllname, +proc glMaterialiv*(face, pname: TGLenum, params: PGLint){.dynlib: dllname, importc: "glMaterialiv".} proc glMatrixMode*(mode: TGLenum){.dynlib: dllname, importc: "glMatrixMode".} proc glMultMatrixd*(m: PGLdouble){.dynlib: dllname, importc: "glMultMatrixd".} proc glMultMatrixf*(m: PGLfloat){.dynlib: dllname, importc: "glMultMatrixf".} -proc glNewList*(list: TGLuint, mode: TGLenum){.dynlib: dllname, +proc glNewList*(list: TGLuint, mode: TGLenum){.dynlib: dllname, importc: "glNewList".} proc glNormal3b*(nx, ny, nz: TGlbyte){.dynlib: dllname, importc: "glNormal3b".} proc glNormal3bv*(v: PGLbyte){.dynlib: dllname, importc: "glNormal3bv".} @@ -1299,22 +1299,22 @@ proc glPixelMapuiv*(map: TGLenum, mapsize: TGLsizei, values: PGLuint){. dynlib: dllname, importc: "glPixelMapuiv".} proc glPixelMapusv*(map: TGLenum, mapsize: TGLsizei, values: PGLushort){. dynlib: dllname, importc: "glPixelMapusv".} -proc glPixelStoref*(pname: TGLenum, param: TGLfloat){.dynlib: dllname, +proc glPixelStoref*(pname: TGLenum, param: TGLfloat){.dynlib: dllname, importc: "glPixelStoref".} -proc glPixelStorei*(pname: TGLenum, param: TGLint){.dynlib: dllname, +proc glPixelStorei*(pname: TGLenum, param: TGLint){.dynlib: dllname, importc: "glPixelStorei".} -proc glPixelTransferf*(pname: TGLenum, param: TGLfloat){.dynlib: dllname, +proc glPixelTransferf*(pname: TGLenum, param: TGLfloat){.dynlib: dllname, importc: "glPixelTransferf".} -proc glPixelTransferi*(pname: TGLenum, param: TGLint){.dynlib: dllname, +proc glPixelTransferi*(pname: TGLenum, param: TGLint){.dynlib: dllname, importc: "glPixelTransferi".} -proc glPixelZoom*(xfactor, yfactor: TGLfloat){.dynlib: dllname, +proc glPixelZoom*(xfactor, yfactor: TGLfloat){.dynlib: dllname, importc: "glPixelZoom".} proc glPointSize*(size: TGLfloat){.dynlib: dllname, importc: "glPointSize".} -proc glPolygonMode*(face, mode: TGLenum){.dynlib: dllname, +proc glPolygonMode*(face, mode: TGLenum){.dynlib: dllname, importc: "glPolygonMode".} -proc glPolygonOffset*(factor, units: TGLfloat){.dynlib: dllname, +proc glPolygonOffset*(factor, units: TGLfloat){.dynlib: dllname, importc: "glPolygonOffset".} -proc glPolygonStipple*(mask: PGLubyte){.dynlib: dllname, +proc glPolygonStipple*(mask: PGLubyte){.dynlib: dllname, importc: "glPolygonStipple".} proc glPopAttrib*(){.dynlib: dllname, importc: "glPopAttrib".} proc glPopClientAttrib*(){.dynlib: dllname, importc: "glPopClientAttrib".} @@ -1323,7 +1323,7 @@ proc glPopName*(){.dynlib: dllname, importc: "glPopName".} proc glPrioritizeTextures*(n: TGLsizei, textures: PGLuint, priorities: PGLclampf){. dynlib: dllname, importc: "glPrioritizeTextures".} proc glPushAttrib*(mask: TGLbitfield){.dynlib: dllname, importc: "glPushAttrib".} -proc glPushClientAttrib*(mask: TGLbitfield){.dynlib: dllname, +proc glPushClientAttrib*(mask: TGLbitfield){.dynlib: dllname, importc: "glPushClientAttrib".} proc glPushMatrix*(){.dynlib: dllname, importc: "glPushMatrix".} proc glPushName*(name: TGLuint){.dynlib: dllname, importc: "glPushName".} @@ -1335,35 +1335,35 @@ proc glRasterPos2i*(x, y: TGLint){.dynlib: dllname, importc: "glRasterPos2i".} proc glRasterPos2iv*(v: PGLint){.dynlib: dllname, importc: "glRasterPos2iv".} proc glRasterPos2s*(x, y: TGLshort){.dynlib: dllname, importc: "glRasterPos2s".} proc glRasterPos2sv*(v: PGLshort){.dynlib: dllname, importc: "glRasterPos2sv".} -proc glRasterPos3d*(x, y, z: TGLdouble){.dynlib: dllname, +proc glRasterPos3d*(x, y, z: TGLdouble){.dynlib: dllname, importc: "glRasterPos3d".} proc glRasterPos3dv*(v: PGLdouble){.dynlib: dllname, importc: "glRasterPos3dv".} -proc glRasterPos3f*(x, y, z: TGLfloat){.dynlib: dllname, +proc glRasterPos3f*(x, y, z: TGLfloat){.dynlib: dllname, importc: "glRasterPos3f".} proc glRasterPos3fv*(v: PGLfloat){.dynlib: dllname, importc: "glRasterPos3fv".} proc glRasterPos3i*(x, y, z: TGLint){.dynlib: dllname, importc: "glRasterPos3i".} proc glRasterPos3iv*(v: PGLint){.dynlib: dllname, importc: "glRasterPos3iv".} -proc glRasterPos3s*(x, y, z: TGLshort){.dynlib: dllname, +proc glRasterPos3s*(x, y, z: TGLshort){.dynlib: dllname, importc: "glRasterPos3s".} proc glRasterPos3sv*(v: PGLshort){.dynlib: dllname, importc: "glRasterPos3sv".} -proc glRasterPos4d*(x, y, z, w: TGLdouble){.dynlib: dllname, +proc glRasterPos4d*(x, y, z, w: TGLdouble){.dynlib: dllname, importc: "glRasterPos4d".} proc glRasterPos4dv*(v: PGLdouble){.dynlib: dllname, importc: "glRasterPos4dv".} -proc glRasterPos4f*(x, y, z, w: TGLfloat){.dynlib: dllname, +proc glRasterPos4f*(x, y, z, w: TGLfloat){.dynlib: dllname, importc: "glRasterPos4f".} proc glRasterPos4fv*(v: PGLfloat){.dynlib: dllname, importc: "glRasterPos4fv".} -proc glRasterPos4i*(x, y, z, w: TGLint){.dynlib: dllname, +proc glRasterPos4i*(x, y, z, w: TGLint){.dynlib: dllname, importc: "glRasterPos4i".} proc glRasterPos4iv*(v: PGLint){.dynlib: dllname, importc: "glRasterPos4iv".} -proc glRasterPos4s*(x, y, z, w: TGLshort){.dynlib: dllname, +proc glRasterPos4s*(x, y, z, w: TGLshort){.dynlib: dllname, importc: "glRasterPos4s".} proc glRasterPos4sv*(v: PGLshort){.dynlib: dllname, importc: "glRasterPos4sv".} proc glReadBuffer*(mode: TGLenum){.dynlib: dllname, importc: "glReadBuffer".} -proc glReadPixels*(x, y: TGLint, width, height: TGLsizei, - format, atype: TGLenum, pixels: pointer){.dynlib: dllname, +proc glReadPixels*(x, y: TGLint, width, height: TGLsizei, + format, atype: TGLenum, pixels: pointer){.dynlib: dllname, importc: "glReadPixels".} proc glRectd*(x1, y1, x2, y2: TGLdouble){.dynlib: dllname, importc: "glRectd".} -proc glRectdv*(v1: PGLdouble, v2: PGLdouble){.dynlib: dllname, +proc glRectdv*(v1: PGLdouble, v2: PGLdouble){.dynlib: dllname, importc: "glRectdv".} proc glRectf*(x1, y1, x2, y2: TGLfloat){.dynlib: dllname, importc: "glRectf".} proc glRectfv*(v1: PGLfloat, v2: PGLfloat){.dynlib: dllname, importc: "glRectfv".} @@ -1371,22 +1371,22 @@ proc glRecti*(x1, y1, x2, y2: TGLint){.dynlib: dllname, importc: "glRecti".} proc glRectiv*(v1: PGLint, v2: PGLint){.dynlib: dllname, importc: "glRectiv".} proc glRects*(x1, y1, x2, y2: TGLshort){.dynlib: dllname, importc: "glRects".} proc glRectsv*(v1: PGLshort, v2: PGLshort){.dynlib: dllname, importc: "glRectsv".} -proc glRenderMode*(mode: TGLint): TGLint{.dynlib: dllname, +proc glRenderMode*(mode: TGLint): TGLint{.dynlib: dllname, importc: "glRenderMode".} -proc glRotated*(angle, x, y, z: TGLdouble){.dynlib: dllname, +proc glRotated*(angle, x, y, z: TGLdouble){.dynlib: dllname, importc: "glRotated".} proc glRotatef*(angle, x, y, z: TGLfloat){.dynlib: dllname, importc: "glRotatef".} proc glScaled*(x, y, z: TGLdouble){.dynlib: dllname, importc: "glScaled".} proc glScalef*(x, y, z: TGLfloat){.dynlib: dllname, importc: "glScalef".} -proc glScissor*(x, y: TGLint, width, height: TGLsizei){.dynlib: dllname, +proc glScissor*(x, y: TGLint, width, height: TGLsizei){.dynlib: dllname, importc: "glScissor".} -proc glSelectBuffer*(size: TGLsizei, buffer: PGLuint){.dynlib: dllname, +proc glSelectBuffer*(size: TGLsizei, buffer: PGLuint){.dynlib: dllname, importc: "glSelectBuffer".} proc glShadeModel*(mode: TGLenum){.dynlib: dllname, importc: "glShadeModel".} proc glStencilFunc*(fun: TGLenum, theref: TGLint, mask: TGLuint){. dynlib: dllname, importc: "glStencilFunc".} proc glStencilMask*(mask: TGLuint){.dynlib: dllname, importc: "glStencilMask".} -proc glStencilOp*(fail, zfail, zpass: TGLenum){.dynlib: dllname, +proc glStencilOp*(fail, zfail, zpass: TGLenum){.dynlib: dllname, importc: "glStencilOp".} proc glTexCoord1d*(s: TGLdouble){.dynlib: dllname, importc: "glTexCoord1d".} proc glTexCoord1dv*(v: PGLdouble){.dynlib: dllname, importc: "glTexCoord1dv".} @@ -1412,19 +1412,19 @@ proc glTexCoord3i*(s, t, r: TGLint){.dynlib: dllname, importc: "glTexCoord3i".} proc glTexCoord3iv*(v: PGLint){.dynlib: dllname, importc: "glTexCoord3iv".} proc glTexCoord3s*(s, t, r: TGLshort){.dynlib: dllname, importc: "glTexCoord3s".} proc glTexCoord3sv*(v: PGLshort){.dynlib: dllname, importc: "glTexCoord3sv".} -proc glTexCoord4d*(s, t, r, q: TGLdouble){.dynlib: dllname, +proc glTexCoord4d*(s, t, r, q: TGLdouble){.dynlib: dllname, importc: "glTexCoord4d".} proc glTexCoord4dv*(v: PGLdouble){.dynlib: dllname, importc: "glTexCoord4dv".} -proc glTexCoord4f*(s, t, r, q: TGLfloat){.dynlib: dllname, +proc glTexCoord4f*(s, t, r, q: TGLfloat){.dynlib: dllname, importc: "glTexCoord4f".} proc glTexCoord4fv*(v: PGLfloat){.dynlib: dllname, importc: "glTexCoord4fv".} proc glTexCoord4i*(s, t, r, q: TGLint){.dynlib: dllname, importc: "glTexCoord4i".} proc glTexCoord4iv*(v: PGLint){.dynlib: dllname, importc: "glTexCoord4iv".} -proc glTexCoord4s*(s, t, r, q: TGLshort){.dynlib: dllname, +proc glTexCoord4s*(s, t, r, q: TGLshort){.dynlib: dllname, importc: "glTexCoord4s".} proc glTexCoord4sv*(v: PGLshort){.dynlib: dllname, importc: "glTexCoord4sv".} -proc glTexCoordPointer*(size: TGLint, atype: TGLenum, stride: TGLsizei, - p: pointer){.dynlib: dllname, +proc glTexCoordPointer*(size: TGLint, atype: TGLenum, stride: TGLsizei, + p: pointer){.dynlib: dllname, importc: "glTexCoordPointer".} proc glTexEnvf*(target: TGLenum, pname: TGLenum, param: TGLfloat){. dynlib: dllname, importc: "glTexEnvf".} @@ -1442,16 +1442,16 @@ proc glTexGenf*(coord: TGLenum, pname: TGLenum, param: TGLfloat){. dynlib: dllname, importc: "glTexGenf".} proc glTexGenfv*(coord: TGLenum, pname: TGLenum, params: PGLfloat){. dynlib: dllname, importc: "glTexGenfv".} -proc glTexGeni*(coord: TGLenum, pname: TGLenum, param: TGLint){.dynlib: dllname, +proc glTexGeni*(coord: TGLenum, pname: TGLenum, param: TGLint){.dynlib: dllname, importc: "glTexGeni".} proc glTexGeniv*(coord: TGLenum, pname: TGLenum, params: PGLint){. dynlib: dllname, importc: "glTexGeniv".} -proc glTexImage1D*(target: TGLenum, level, internalformat: TGLint, - width: TGLsizei, border: TGLint, format, atype: TGLenum, +proc glTexImage1D*(target: TGLenum, level, internalformat: TGLint, + width: TGLsizei, border: TGLint, format, atype: TGLenum, pixels: pointer){.dynlib: dllname, importc: "glTexImage1D".} -proc glTexImage2D*(target: TGLenum, level, internalformat: TGLint, - width, height: TGLsizei, border: TGLint, - format, atype: TGLenum, pixels: pointer){.dynlib: dllname, +proc glTexImage2D*(target: TGLenum, level, internalformat: TGLint, + width, height: TGLsizei, border: TGLint, + format, atype: TGLenum, pixels: pointer){.dynlib: dllname, importc: "glTexImage2D".} proc glTexParameterf*(target: TGLenum, pname: TGLenum, param: TGLfloat){. dynlib: dllname, importc: "glTexParameterf".} @@ -1461,12 +1461,12 @@ proc glTexParameteri*(target: TGLenum, pname: TGLenum, param: TGLint){. dynlib: dllname, importc: "glTexParameteri".} proc glTexParameteriv*(target: TGLenum, pname: TGLenum, params: PGLint){. dynlib: dllname, importc: "glTexParameteriv".} -proc glTexSubImage1D*(target: TGLenum, level, xoffset: TGLint, width: TGLsizei, - format, atype: TGLenum, pixels: pointer){.dynlib: dllname, +proc glTexSubImage1D*(target: TGLenum, level, xoffset: TGLint, width: TGLsizei, + format, atype: TGLenum, pixels: pointer){.dynlib: dllname, importc: "glTexSubImage1D".} -proc glTexSubImage2D*(target: TGLenum, level, xoffset, yoffset: TGLint, - width, height: TGLsizei, format, atype: TGLenum, - pixels: pointer){.dynlib: dllname, +proc glTexSubImage2D*(target: TGLenum, level, xoffset, yoffset: TGLint, + width, height: TGLsizei, format, atype: TGLenum, + pixels: pointer){.dynlib: dllname, importc: "glTexSubImage2D".} proc glTranslated*(x, y, z: TGLdouble){.dynlib: dllname, importc: "glTranslated".} proc glTranslatef*(x, y, z: TGLfloat){.dynlib: dllname, importc: "glTranslatef".} @@ -1494,42 +1494,42 @@ proc glVertex4i*(x, y, z, w: TGLint){.dynlib: dllname, importc: "glVertex4i".} proc glVertex4iv*(v: PGLint){.dynlib: dllname, importc: "glVertex4iv".} proc glVertex4s*(x, y, z, w: TGLshort){.dynlib: dllname, importc: "glVertex4s".} proc glVertex4sv*(v: PGLshort){.dynlib: dllname, importc: "glVertex4sv".} -proc glVertexPointer*(size: TGLint, atype: TGLenum, stride: TGLsizei, - p: pointer){.dynlib: dllname, +proc glVertexPointer*(size: TGLint, atype: TGLenum, stride: TGLsizei, + p: pointer){.dynlib: dllname, importc: "glVertexPointer".} -proc glViewport*(x, y: TGLint, width, height: TGLsizei){.dynlib: dllname, +proc glViewport*(x, y: TGLint, width, height: TGLsizei){.dynlib: dllname, importc: "glViewport".} -type +type PFN_GLARRAY_ELEMENT_EXTPROC* = proc (i: TGLint) - PFN_GLDRAW_ARRAYS_EXTPROC* = proc (mode: TGLenum, first: TGLint, + PFN_GLDRAW_ARRAYS_EXTPROC* = proc (mode: TGLenum, first: TGLint, count: TGLsizei) - PFN_GLVERTEX_POINTER_EXTPROC* = proc (size: TGLint, atype: TGLenum, - stride, count: TGLsizei, + PFN_GLVERTEX_POINTER_EXTPROC* = proc (size: TGLint, atype: TGLenum, + stride, count: TGLsizei, p: pointer) - PFN_GLNORMAL_POINTER_EXTPROC* = proc (atype: TGLenum, stride, count: TGLsizei, + PFN_GLNORMAL_POINTER_EXTPROC* = proc (atype: TGLenum, stride, count: TGLsizei, p: pointer) - PFN_GLCOLOR_POINTER_EXTPROC* = proc (size: TGLint, atype: TGLenum, + PFN_GLCOLOR_POINTER_EXTPROC* = proc (size: TGLint, atype: TGLenum, stride, count: TGLsizei, p: pointer) - PFN_GLINDEX_POINTER_EXTPROC* = proc (atype: TGLenum, stride, count: TGLsizei, + PFN_GLINDEX_POINTER_EXTPROC* = proc (atype: TGLenum, stride, count: TGLsizei, p: pointer) - PFN_GLTEXCOORD_POINTER_EXTPROC* = proc (size: TGLint, atype: TGLenum, + PFN_GLTEXCOORD_POINTER_EXTPROC* = proc (size: TGLint, atype: TGLenum, stride, count: TGLsizei, p: pointer) - PFN_GLEDGEFLAG_POINTER_EXTPROC* = proc (stride, count: TGLsizei, + PFN_GLEDGEFLAG_POINTER_EXTPROC* = proc (stride, count: TGLsizei, pointer: PGLboolean) PFN_GLGET_POINTER_VEXT_PROC* = proc (pname: TGLenum, params: pointer) - PFN_GLARRAY_ELEMENT_ARRAY_EXTPROC* = proc (mode: TGLenum, count: TGLsizei, + PFN_GLARRAY_ELEMENT_ARRAY_EXTPROC* = proc (mode: TGLenum, count: TGLsizei, pi: pointer) # WIN_swap_hint PFN_GLADDSWAPHINT_RECT_WINPROC* = proc (x, y: TGLint, width, height: TGLsizei) - PFN_GLCOLOR_TABLE_EXTPROC* = proc (target, internalFormat: TGLenum, - width: TGLsizei, format, atype: TGLenum, + PFN_GLCOLOR_TABLE_EXTPROC* = proc (target, internalFormat: TGLenum, + width: TGLsizei, format, atype: TGLenum, data: pointer) - PFN_GLCOLOR_SUBTABLE_EXTPROC* = proc (target: TGLenum, start, count: TGLsizei, + PFN_GLCOLOR_SUBTABLE_EXTPROC* = proc (target: TGLenum, start, count: TGLsizei, format, atype: TGLenum, data: pointer) - PFN_GLGETCOLOR_TABLE_EXTPROC* = proc (target, format, atype: TGLenum, + PFN_GLGETCOLOR_TABLE_EXTPROC* = proc (target, format, atype: TGLenum, data: pointer) - PFN_GLGETCOLOR_TABLE_PARAMETER_IVEXTPROC* = proc (target, pname: TGLenum, + PFN_GLGETCOLOR_TABLE_PARAMETER_IVEXTPROC* = proc (target, pname: TGLenum, params: PGLint) - PFN_GLGETCOLOR_TABLE_PARAMETER_FVEXTPROC* = proc (target, pname: TGLenum, + PFN_GLGETCOLOR_TABLE_PARAMETER_FVEXTPROC* = proc (target, pname: TGLenum, params: PGLfloat) {.pop.} diff --git a/tests/manyloc/keineschweine/lib/glext.nim b/tests/manyloc/keineschweine/lib/glext.nim index 32871df0e..1e1bdb958 100644 --- a/tests/manyloc/keineschweine/lib/glext.nim +++ b/tests/manyloc/keineschweine/lib/glext.nim @@ -13,14 +13,14 @@ # ************************************************* #*** Generated on 10/11/2002 -when defined(windows): +when defined(windows): {.push, callconv: stdcall.} -else: +else: {.push, callconv: cdecl.} -import +import gl -type +type GLcharARB* = Char TGLcharARB* = GLcharARB PGLcharARB* = ptr GLcharARB @@ -37,7 +37,7 @@ type TGLchar* = GLchar PGLchar* = cstring #***** GL_version_1_2 *****// -const +const GL_UNSIGNED_BYTE_3_3_2* = 0x00008032 GL_UNSIGNED_SHORT_4_4_4_4* = 0x00008033 GL_UNSIGNED_SHORT_5_5_5_1* = 0x00008034 @@ -79,44 +79,44 @@ const GL_TEXTURE_WRAP_R* = 0x00008072 GL_MAX_3D_TEXTURE_SIZE* = 0x00008073 -proc glBlendColor*(red: TGLclampf, green: TGLclampf, blue: TGLclampf, +proc glBlendColor*(red: TGLclampf, green: TGLclampf, blue: TGLclampf, alpha: TGLclampf){.dynlib: dllname, importc: "glBlendColor".} -proc glBlendEquation*(mode: TGLenum){.dynlib: dllname, +proc glBlendEquation*(mode: TGLenum){.dynlib: dllname, importc: "glBlendEquation".} -proc glDrawRangeElements*(mode: TGLenum, start: TGLuint, theend: TGLuint, +proc glDrawRangeElements*(mode: TGLenum, start: TGLuint, theend: TGLuint, count: TGLsizei, thetype: TGLenum, indices: PGLvoid){. dynlib: dllname, importc: "glDrawRangeElements".} -proc glColorTable*(target: TGLenum, internalformat: TGLenum, width: TGLsizei, +proc glColorTable*(target: TGLenum, internalformat: TGLenum, width: TGLsizei, format: TGLenum, thetype: TGLenum, table: PGLvoid){. dynlib: dllname, importc: "glColorTable".} proc glColorTableParameterfv*(target: TGLenum, pname: TGLenum, params: PGLfloat){. dynlib: dllname, importc: "glColorTableParameterfv".} proc glColorTableParameteriv*(target: TGLenum, pname: TGLenum, params: PGLint){. dynlib: dllname, importc: "glColorTableParameteriv".} -proc glCopyColorTable*(target: TGLenum, internalformat: TGLenum, x: TGLint, - y: TGLint, width: TGLsizei){.dynlib: dllname, +proc glCopyColorTable*(target: TGLenum, internalformat: TGLenum, x: TGLint, + y: TGLint, width: TGLsizei){.dynlib: dllname, importc: "glCopyColorTable".} -proc glGetColorTable*(target: TGLenum, format: TGLenum, thetype: TGLenum, - table: PGLvoid){.dynlib: dllname, +proc glGetColorTable*(target: TGLenum, format: TGLenum, thetype: TGLenum, + table: PGLvoid){.dynlib: dllname, importc: "glGetColorTable".} -proc glGetColorTableParameterfv*(target: TGLenum, pname: TGLenum, - params: PGLfloat){.dynlib: dllname, +proc glGetColorTableParameterfv*(target: TGLenum, pname: TGLenum, + params: PGLfloat){.dynlib: dllname, importc: "glGetColorTableParameterfv".} proc glGetColorTableParameteriv*(target: TGLenum, pname: TGLenum, params: PGLint){. dynlib: dllname, importc: "glGetColorTableParameteriv".} -proc glColorSubTable*(target: TGLenum, start: TGLsizei, count: TGLsizei, +proc glColorSubTable*(target: TGLenum, start: TGLsizei, count: TGLsizei, format: TGLenum, thetype: TGLenum, data: PGLvoid){. dynlib: dllname, importc: "glColorSubTable".} -proc glCopyColorSubTable*(target: TGLenum, start: TGLsizei, x: TGLint, - y: TGLint, width: TGLsizei){.dynlib: dllname, +proc glCopyColorSubTable*(target: TGLenum, start: TGLsizei, x: TGLint, + y: TGLint, width: TGLsizei){.dynlib: dllname, importc: "glCopyColorSubTable".} -proc glConvolutionFilter1D*(target: TGLenum, internalformat: TGLenum, - width: TGLsizei, format: TGLenum, thetype: TGLenum, - image: PGLvoid){.dynlib: dllname, +proc glConvolutionFilter1D*(target: TGLenum, internalformat: TGLenum, + width: TGLsizei, format: TGLenum, thetype: TGLenum, + image: PGLvoid){.dynlib: dllname, importc: "glConvolutionFilter1D".} -proc glConvolutionFilter2D*(target: TGLenum, internalformat: TGLenum, - width: TGLsizei, height: TGLsizei, format: TGLenum, - thetype: TGLenum, image: PGLvoid){.dynlib: dllname, +proc glConvolutionFilter2D*(target: TGLenum, internalformat: TGLenum, + width: TGLsizei, height: TGLsizei, format: TGLenum, + thetype: TGLenum, image: PGLvoid){.dynlib: dllname, importc: "glConvolutionFilter2D".} proc glConvolutionParameterf*(target: TGLenum, pname: TGLenum, params: TGLfloat){. dynlib: dllname, importc: "glConvolutionParameterf".} @@ -126,170 +126,170 @@ proc glConvolutionParameteri*(target: TGLenum, pname: TGLenum, params: TGLint){. dynlib: dllname, importc: "glConvolutionParameteri".} proc glConvolutionParameteriv*(target: TGLenum, pname: TGLenum, params: PGLint){. dynlib: dllname, importc: "glConvolutionParameteriv".} -proc glCopyConvolutionFilter1D*(target: TGLenum, internalformat: TGLenum, +proc glCopyConvolutionFilter1D*(target: TGLenum, internalformat: TGLenum, x: TGLint, y: TGLint, width: TGLsizei){. dynlib: dllname, importc: "glCopyConvolutionFilter1D".} -proc glCopyConvolutionFilter2D*(target: TGLenum, internalformat: TGLenum, - x: TGLint, y: TGLint, width: TGLsizei, - height: TGLsizei){.dynlib: dllname, +proc glCopyConvolutionFilter2D*(target: TGLenum, internalformat: TGLenum, + x: TGLint, y: TGLint, width: TGLsizei, + height: TGLsizei){.dynlib: dllname, importc: "glCopyConvolutionFilter2D".} -proc glGetConvolutionFilter*(target: TGLenum, format: TGLenum, thetype: TGLenum, - image: PGLvoid){.dynlib: dllname, +proc glGetConvolutionFilter*(target: TGLenum, format: TGLenum, thetype: TGLenum, + image: PGLvoid){.dynlib: dllname, importc: "glGetConvolutionFilter".} -proc glGetConvolutionParameterfv*(target: TGLenum, pname: TGLenum, - params: PGLfloat){.dynlib: dllname, +proc glGetConvolutionParameterfv*(target: TGLenum, pname: TGLenum, + params: PGLfloat){.dynlib: dllname, importc: "glGetConvolutionParameterfv".} -proc glGetConvolutionParameteriv*(target: TGLenum, pname: TGLenum, - params: PGLint){.dynlib: dllname, +proc glGetConvolutionParameteriv*(target: TGLenum, pname: TGLenum, + params: PGLint){.dynlib: dllname, importc: "glGetConvolutionParameteriv".} -proc glGetSeparableFilter*(target: TGLenum, format: TGLenum, thetype: TGLenum, +proc glGetSeparableFilter*(target: TGLenum, format: TGLenum, thetype: TGLenum, row: PGLvoid, column: PGLvoid, span: PGLvoid){. dynlib: dllname, importc: "glGetSeparableFilter".} -proc glSeparableFilter2D*(target: TGLenum, internalformat: TGLenum, - width: TGLsizei, height: TGLsizei, format: TGLenum, +proc glSeparableFilter2D*(target: TGLenum, internalformat: TGLenum, + width: TGLsizei, height: TGLsizei, format: TGLenum, thetype: TGLenum, row: PGLvoid, column: PGLvoid){. dynlib: dllname, importc: "glSeparableFilter2D".} -proc glGetHistogram*(target: TGLenum, reset: TGLboolean, format: TGLenum, - thetype: TGLenum, values: PGLvoid){.dynlib: dllname, +proc glGetHistogram*(target: TGLenum, reset: TGLboolean, format: TGLenum, + thetype: TGLenum, values: PGLvoid){.dynlib: dllname, importc: "glGetHistogram".} -proc glGetHistogramParameterfv*(target: TGLenum, pname: TGLenum, - params: PGLfloat){.dynlib: dllname, +proc glGetHistogramParameterfv*(target: TGLenum, pname: TGLenum, + params: PGLfloat){.dynlib: dllname, importc: "glGetHistogramParameterfv".} proc glGetHistogramParameteriv*(target: TGLenum, pname: TGLenum, params: PGLint){. dynlib: dllname, importc: "glGetHistogramParameteriv".} -proc glGetMinmax*(target: TGLenum, reset: TGLboolean, format: TGLenum, - thetype: TGLenum, values: PGLvoid){.dynlib: dllname, +proc glGetMinmax*(target: TGLenum, reset: TGLboolean, format: TGLenum, + thetype: TGLenum, values: PGLvoid){.dynlib: dllname, importc: "glGetMinmax".} proc glGetMinmaxParameterfv*(target: TGLenum, pname: TGLenum, params: PGLfloat){. dynlib: dllname, importc: "glGetMinmaxParameterfv".} proc glGetMinmaxParameteriv*(target: TGLenum, pname: TGLenum, params: PGLint){. dynlib: dllname, importc: "glGetMinmaxParameteriv".} -proc glHistogram*(target: TGLenum, width: TGLsizei, internalformat: TGLenum, +proc glHistogram*(target: TGLenum, width: TGLsizei, internalformat: TGLenum, sink: TGLboolean){.dynlib: dllname, importc: "glHistogram".} proc glMinmax*(target: TGLenum, internalformat: TGLenum, sink: TGLboolean){. dynlib: dllname, importc: "glMinmax".} -proc glResetHistogram*(target: TGLenum){.dynlib: dllname, +proc glResetHistogram*(target: TGLenum){.dynlib: dllname, importc: "glResetHistogram".} proc glResetMinmax*(target: TGLenum){.dynlib: dllname, importc: "glResetMinmax".} -proc glTexImage3D*(target: TGLenum, level: TGLint, internalformat: TGLint, - width: TGLsizei, height: TGLsizei, depth: TGLsizei, - border: TGLint, format: TGLenum, thetype: TGLenum, +proc glTexImage3D*(target: TGLenum, level: TGLint, internalformat: TGLint, + width: TGLsizei, height: TGLsizei, depth: TGLsizei, + border: TGLint, format: TGLenum, thetype: TGLenum, pixels: PGLvoid){.dynlib: dllname, importc: "glTexImage3D".} -proc glTexSubImage3D*(target: TGLenum, level: TGLint, xoffset: TGLint, - yoffset: TGLint, zoffset: TGLint, width: TGLsizei, - height: TGLsizei, depth: TGLsizei, format: TGLenum, - thetype: TGLenum, pixels: PGLvoid){.dynlib: dllname, +proc glTexSubImage3D*(target: TGLenum, level: TGLint, xoffset: TGLint, + yoffset: TGLint, zoffset: TGLint, width: TGLsizei, + height: TGLsizei, depth: TGLsizei, format: TGLenum, + thetype: TGLenum, pixels: PGLvoid){.dynlib: dllname, importc: "glTexSubImage3D".} -proc glCopyTexSubImage3D*(target: TGLenum, level: TGLint, xoffset: TGLint, - yoffset: TGLint, zoffset: TGLint, x: TGLint, +proc glCopyTexSubImage3D*(target: TGLenum, level: TGLint, xoffset: TGLint, + yoffset: TGLint, zoffset: TGLint, x: TGLint, y: TGLint, width: TGLsizei, height: TGLsizei){. dynlib: dllname, importc: "glCopyTexSubImage3D".} -proc glActiveTextureARB*(texture: TGLenum){.dynlib: dllname, +proc glActiveTextureARB*(texture: TGLenum){.dynlib: dllname, importc: "glActiveTextureARB".} -proc glClientActiveTextureARB*(texture: TGLenum){.dynlib: dllname, +proc glClientActiveTextureARB*(texture: TGLenum){.dynlib: dllname, importc: "glClientActiveTextureARB".} -proc glMultiTexCoord1dARB*(target: TGLenum, s: TGLdouble){.dynlib: dllname, +proc glMultiTexCoord1dARB*(target: TGLenum, s: TGLdouble){.dynlib: dllname, importc: "glMultiTexCoord1dARB".} -proc glMultiTexCoord1dvARB*(target: TGLenum, v: PGLdouble){.dynlib: dllname, +proc glMultiTexCoord1dvARB*(target: TGLenum, v: PGLdouble){.dynlib: dllname, importc: "glMultiTexCoord1dvARB".} -proc glMultiTexCoord1fARB*(target: TGLenum, s: TGLfloat){.dynlib: dllname, +proc glMultiTexCoord1fARB*(target: TGLenum, s: TGLfloat){.dynlib: dllname, importc: "glMultiTexCoord1fARB".} -proc glMultiTexCoord1fvARB*(target: TGLenum, v: PGLfloat){.dynlib: dllname, +proc glMultiTexCoord1fvARB*(target: TGLenum, v: PGLfloat){.dynlib: dllname, importc: "glMultiTexCoord1fvARB".} -proc glMultiTexCoord1iARB*(target: TGLenum, s: TGLint){.dynlib: dllname, +proc glMultiTexCoord1iARB*(target: TGLenum, s: TGLint){.dynlib: dllname, importc: "glMultiTexCoord1iARB".} -proc glMultiTexCoord1ivARB*(target: TGLenum, v: PGLint){.dynlib: dllname, +proc glMultiTexCoord1ivARB*(target: TGLenum, v: PGLint){.dynlib: dllname, importc: "glMultiTexCoord1ivARB".} -proc glMultiTexCoord1sARB*(target: TGLenum, s: TGLshort){.dynlib: dllname, +proc glMultiTexCoord1sARB*(target: TGLenum, s: TGLshort){.dynlib: dllname, importc: "glMultiTexCoord1sARB".} -proc glMultiTexCoord1svARB*(target: TGLenum, v: PGLshort){.dynlib: dllname, +proc glMultiTexCoord1svARB*(target: TGLenum, v: PGLshort){.dynlib: dllname, importc: "glMultiTexCoord1svARB".} proc glMultiTexCoord2dARB*(target: TGLenum, s: TGLdouble, t: TGLdouble){. dynlib: dllname, importc: "glMultiTexCoord2dARB".} -proc glMultiTexCoord2dvARB*(target: TGLenum, v: PGLdouble){.dynlib: dllname, +proc glMultiTexCoord2dvARB*(target: TGLenum, v: PGLdouble){.dynlib: dllname, importc: "glMultiTexCoord2dvARB".} proc glMultiTexCoord2fARB*(target: TGLenum, s: TGLfloat, t: TGLfloat){. dynlib: dllname, importc: "glMultiTexCoord2fARB".} -proc glMultiTexCoord2fvARB*(target: TGLenum, v: PGLfloat){.dynlib: dllname, +proc glMultiTexCoord2fvARB*(target: TGLenum, v: PGLfloat){.dynlib: dllname, importc: "glMultiTexCoord2fvARB".} proc glMultiTexCoord2iARB*(target: TGLenum, s: TGLint, t: TGLint){. dynlib: dllname, importc: "glMultiTexCoord2iARB".} -proc glMultiTexCoord2ivARB*(target: TGLenum, v: PGLint){.dynlib: dllname, +proc glMultiTexCoord2ivARB*(target: TGLenum, v: PGLint){.dynlib: dllname, importc: "glMultiTexCoord2ivARB".} proc glMultiTexCoord2sARB*(target: TGLenum, s: TGLshort, t: TGLshort){. dynlib: dllname, importc: "glMultiTexCoord2sARB".} -proc glMultiTexCoord2svARB*(target: TGLenum, v: PGLshort){.dynlib: dllname, +proc glMultiTexCoord2svARB*(target: TGLenum, v: PGLshort){.dynlib: dllname, importc: "glMultiTexCoord2svARB".} -proc glMultiTexCoord3dARB*(target: TGLenum, s: TGLdouble, t: TGLdouble, - r: TGLdouble){.dynlib: dllname, +proc glMultiTexCoord3dARB*(target: TGLenum, s: TGLdouble, t: TGLdouble, + r: TGLdouble){.dynlib: dllname, importc: "glMultiTexCoord3dARB".} -proc glMultiTexCoord3dvARB*(target: TGLenum, v: PGLdouble){.dynlib: dllname, +proc glMultiTexCoord3dvARB*(target: TGLenum, v: PGLdouble){.dynlib: dllname, importc: "glMultiTexCoord3dvARB".} -proc glMultiTexCoord3fARB*(target: TGLenum, s: TGLfloat, t: TGLfloat, - r: TGLfloat){.dynlib: dllname, +proc glMultiTexCoord3fARB*(target: TGLenum, s: TGLfloat, t: TGLfloat, + r: TGLfloat){.dynlib: dllname, importc: "glMultiTexCoord3fARB".} -proc glMultiTexCoord3fvARB*(target: TGLenum, v: PGLfloat){.dynlib: dllname, +proc glMultiTexCoord3fvARB*(target: TGLenum, v: PGLfloat){.dynlib: dllname, importc: "glMultiTexCoord3fvARB".} proc glMultiTexCoord3iARB*(target: TGLenum, s: TGLint, t: TGLint, r: TGLint){. dynlib: dllname, importc: "glMultiTexCoord3iARB".} -proc glMultiTexCoord3ivARB*(target: TGLenum, v: PGLint){.dynlib: dllname, +proc glMultiTexCoord3ivARB*(target: TGLenum, v: PGLint){.dynlib: dllname, importc: "glMultiTexCoord3ivARB".} -proc glMultiTexCoord3sARB*(target: TGLenum, s: TGLshort, t: TGLshort, - r: TGLshort){.dynlib: dllname, +proc glMultiTexCoord3sARB*(target: TGLenum, s: TGLshort, t: TGLshort, + r: TGLshort){.dynlib: dllname, importc: "glMultiTexCoord3sARB".} -proc glMultiTexCoord3svARB*(target: TGLenum, v: PGLshort){.dynlib: dllname, +proc glMultiTexCoord3svARB*(target: TGLenum, v: PGLshort){.dynlib: dllname, importc: "glMultiTexCoord3svARB".} -proc glMultiTexCoord4dARB*(target: TGLenum, s: TGLdouble, t: TGLdouble, - r: TGLdouble, q: TGLdouble){.dynlib: dllname, +proc glMultiTexCoord4dARB*(target: TGLenum, s: TGLdouble, t: TGLdouble, + r: TGLdouble, q: TGLdouble){.dynlib: dllname, importc: "glMultiTexCoord4dARB".} -proc glMultiTexCoord4dvARB*(target: TGLenum, v: PGLdouble){.dynlib: dllname, +proc glMultiTexCoord4dvARB*(target: TGLenum, v: PGLdouble){.dynlib: dllname, importc: "glMultiTexCoord4dvARB".} -proc glMultiTexCoord4fARB*(target: TGLenum, s: TGLfloat, t: TGLfloat, - r: TGLfloat, q: TGLfloat){.dynlib: dllname, +proc glMultiTexCoord4fARB*(target: TGLenum, s: TGLfloat, t: TGLfloat, + r: TGLfloat, q: TGLfloat){.dynlib: dllname, importc: "glMultiTexCoord4fARB".} -proc glMultiTexCoord4fvARB*(target: TGLenum, v: PGLfloat){.dynlib: dllname, +proc glMultiTexCoord4fvARB*(target: TGLenum, v: PGLfloat){.dynlib: dllname, importc: "glMultiTexCoord4fvARB".} -proc glMultiTexCoord4iARB*(target: TGLenum, s: TGLint, t: TGLint, r: TGLint, - q: TGLint){.dynlib: dllname, +proc glMultiTexCoord4iARB*(target: TGLenum, s: TGLint, t: TGLint, r: TGLint, + q: TGLint){.dynlib: dllname, importc: "glMultiTexCoord4iARB".} -proc glMultiTexCoord4ivARB*(target: TGLenum, v: PGLint){.dynlib: dllname, +proc glMultiTexCoord4ivARB*(target: TGLenum, v: PGLint){.dynlib: dllname, importc: "glMultiTexCoord4ivARB".} -proc glMultiTexCoord4sARB*(target: TGLenum, s: TGLshort, t: TGLshort, - r: TGLshort, q: TGLshort){.dynlib: dllname, +proc glMultiTexCoord4sARB*(target: TGLenum, s: TGLshort, t: TGLshort, + r: TGLshort, q: TGLshort){.dynlib: dllname, importc: "glMultiTexCoord4sARB".} -proc glMultiTexCoord4svARB*(target: TGLenum, v: PGLshort){.dynlib: dllname, +proc glMultiTexCoord4svARB*(target: TGLenum, v: PGLshort){.dynlib: dllname, importc: "glMultiTexCoord4svARB".} proc glSampleCoverageARB*(value: TGLclampf, invert: TGLboolean){. dynlib: dllname, importc: "glSampleCoverageARB".} #***** GL_ARB_texture_env_add *****// -proc glWeightbvARB*(size: TGLint, weights: PGLbyte){.dynlib: dllname, +proc glWeightbvARB*(size: TGLint, weights: PGLbyte){.dynlib: dllname, importc: "glWeightbvARB".} -proc glWeightsvARB*(size: TGLint, weights: PGLshort){.dynlib: dllname, +proc glWeightsvARB*(size: TGLint, weights: PGLshort){.dynlib: dllname, importc: "glWeightsvARB".} -proc glWeightivARB*(size: TGLint, weights: PGLint){.dynlib: dllname, +proc glWeightivARB*(size: TGLint, weights: PGLint){.dynlib: dllname, importc: "glWeightivARB".} -proc glWeightfvARB*(size: TGLint, weights: PGLfloat){.dynlib: dllname, +proc glWeightfvARB*(size: TGLint, weights: PGLfloat){.dynlib: dllname, importc: "glWeightfvARB".} -proc glWeightdvARB*(size: TGLint, weights: PGLdouble){.dynlib: dllname, +proc glWeightdvARB*(size: TGLint, weights: PGLdouble){.dynlib: dllname, importc: "glWeightdvARB".} -proc glWeightvARB*(size: TGLint, weights: PGLdouble){.dynlib: dllname, +proc glWeightvARB*(size: TGLint, weights: PGLdouble){.dynlib: dllname, importc: "glWeightvARB".} -proc glWeightubvARB*(size: TGLint, weights: PGLubyte){.dynlib: dllname, +proc glWeightubvARB*(size: TGLint, weights: PGLubyte){.dynlib: dllname, importc: "glWeightubvARB".} -proc glWeightusvARB*(size: TGLint, weights: PGLushort){.dynlib: dllname, +proc glWeightusvARB*(size: TGLint, weights: PGLushort){.dynlib: dllname, importc: "glWeightusvARB".} -proc glWeightuivARB*(size: TGLint, weights: PGLuint){.dynlib: dllname, +proc glWeightuivARB*(size: TGLint, weights: PGLuint){.dynlib: dllname, importc: "glWeightuivARB".} -proc glWeightPointerARB*(size: TGLint, thetype: TGLenum, stride: TGLsizei, - pointer: PGLvoid){.dynlib: dllname, +proc glWeightPointerARB*(size: TGLint, thetype: TGLenum, stride: TGLsizei, + pointer: PGLvoid){.dynlib: dllname, importc: "glWeightPointerARB".} -proc glVertexBlendARB*(count: TGLint){.dynlib: dllname, +proc glVertexBlendARB*(count: TGLint){.dynlib: dllname, importc: "glVertexBlendARB".} -proc glVertexAttrib1sARB*(index: TGLuint, x: TGLshort){.dynlib: dllname, +proc glVertexAttrib1sARB*(index: TGLuint, x: TGLshort){.dynlib: dllname, importc: "glVertexAttrib1sARB".} -proc glVertexAttrib1fARB*(index: TGLuint, x: TGLfloat){.dynlib: dllname, +proc glVertexAttrib1fARB*(index: TGLuint, x: TGLfloat){.dynlib: dllname, importc: "glVertexAttrib1fARB".} -proc glVertexAttrib1dARB*(index: TGLuint, x: TGLdouble){.dynlib: dllname, +proc glVertexAttrib1dARB*(index: TGLuint, x: TGLdouble){.dynlib: dllname, importc: "glVertexAttrib1dARB".} proc glVertexAttrib2sARB*(index: TGLuint, x: TGLshort, y: TGLshort){. dynlib: dllname, importc: "glVertexAttrib2sARB".} @@ -301,120 +301,120 @@ proc glVertexAttrib3sARB*(index: TGLuint, x: TGLshort, y: TGLshort, z: TGLshort) dynlib: dllname, importc: "glVertexAttrib3sARB".} proc glVertexAttrib3fARB*(index: TGLuint, x: TGLfloat, y: TGLfloat, z: TGLfloat){. dynlib: dllname, importc: "glVertexAttrib3fARB".} -proc glVertexAttrib3dARB*(index: TGLuint, x: TGLdouble, y: TGLdouble, - z: TGLdouble){.dynlib: dllname, +proc glVertexAttrib3dARB*(index: TGLuint, x: TGLdouble, y: TGLdouble, + z: TGLdouble){.dynlib: dllname, importc: "glVertexAttrib3dARB".} -proc glVertexAttrib4sARB*(index: TGLuint, x: TGLshort, y: TGLshort, z: TGLshort, - w: TGLshort){.dynlib: dllname, +proc glVertexAttrib4sARB*(index: TGLuint, x: TGLshort, y: TGLshort, z: TGLshort, + w: TGLshort){.dynlib: dllname, importc: "glVertexAttrib4sARB".} -proc glVertexAttrib4fARB*(index: TGLuint, x: TGLfloat, y: TGLfloat, z: TGLfloat, - w: TGLfloat){.dynlib: dllname, +proc glVertexAttrib4fARB*(index: TGLuint, x: TGLfloat, y: TGLfloat, z: TGLfloat, + w: TGLfloat){.dynlib: dllname, importc: "glVertexAttrib4fARB".} -proc glVertexAttrib4dARB*(index: TGLuint, x: TGLdouble, y: TGLdouble, - z: TGLdouble, w: TGLdouble){.dynlib: dllname, +proc glVertexAttrib4dARB*(index: TGLuint, x: TGLdouble, y: TGLdouble, + z: TGLdouble, w: TGLdouble){.dynlib: dllname, importc: "glVertexAttrib4dARB".} -proc glVertexAttrib4NubARB*(index: TGLuint, x: TGLubyte, y: TGLubyte, - z: TGLubyte, w: TGLubyte){.dynlib: dllname, +proc glVertexAttrib4NubARB*(index: TGLuint, x: TGLubyte, y: TGLubyte, + z: TGLubyte, w: TGLubyte){.dynlib: dllname, importc: "glVertexAttrib4NubARB".} -proc glVertexAttrib1svARB*(index: TGLuint, v: PGLshort){.dynlib: dllname, +proc glVertexAttrib1svARB*(index: TGLuint, v: PGLshort){.dynlib: dllname, importc: "glVertexAttrib1svARB".} -proc glVertexAttrib1fvARB*(index: TGLuint, v: PGLfloat){.dynlib: dllname, +proc glVertexAttrib1fvARB*(index: TGLuint, v: PGLfloat){.dynlib: dllname, importc: "glVertexAttrib1fvARB".} -proc glVertexAttrib1dvARB*(index: TGLuint, v: PGLdouble){.dynlib: dllname, +proc glVertexAttrib1dvARB*(index: TGLuint, v: PGLdouble){.dynlib: dllname, importc: "glVertexAttrib1dvARB".} -proc glVertexAttrib2svARB*(index: TGLuint, v: PGLshort){.dynlib: dllname, +proc glVertexAttrib2svARB*(index: TGLuint, v: PGLshort){.dynlib: dllname, importc: "glVertexAttrib2svARB".} -proc glVertexAttrib2fvARB*(index: TGLuint, v: PGLfloat){.dynlib: dllname, +proc glVertexAttrib2fvARB*(index: TGLuint, v: PGLfloat){.dynlib: dllname, importc: "glVertexAttrib2fvARB".} -proc glVertexAttrib2dvARB*(index: TGLuint, v: PGLdouble){.dynlib: dllname, +proc glVertexAttrib2dvARB*(index: TGLuint, v: PGLdouble){.dynlib: dllname, importc: "glVertexAttrib2dvARB".} -proc glVertexAttrib3svARB*(index: TGLuint, v: PGLshort){.dynlib: dllname, +proc glVertexAttrib3svARB*(index: TGLuint, v: PGLshort){.dynlib: dllname, importc: "glVertexAttrib3svARB".} -proc glVertexAttrib3fvARB*(index: TGLuint, v: PGLfloat){.dynlib: dllname, +proc glVertexAttrib3fvARB*(index: TGLuint, v: PGLfloat){.dynlib: dllname, importc: "glVertexAttrib3fvARB".} -proc glVertexAttrib3dvARB*(index: TGLuint, v: PGLdouble){.dynlib: dllname, +proc glVertexAttrib3dvARB*(index: TGLuint, v: PGLdouble){.dynlib: dllname, importc: "glVertexAttrib3dvARB".} -proc glVertexAttrib4bvARB*(index: TGLuint, v: PGLbyte){.dynlib: dllname, +proc glVertexAttrib4bvARB*(index: TGLuint, v: PGLbyte){.dynlib: dllname, importc: "glVertexAttrib4bvARB".} -proc glVertexAttrib4svARB*(index: TGLuint, v: PGLshort){.dynlib: dllname, +proc glVertexAttrib4svARB*(index: TGLuint, v: PGLshort){.dynlib: dllname, importc: "glVertexAttrib4svARB".} -proc glVertexAttrib4ivARB*(index: TGLuint, v: PGLint){.dynlib: dllname, +proc glVertexAttrib4ivARB*(index: TGLuint, v: PGLint){.dynlib: dllname, importc: "glVertexAttrib4ivARB".} -proc glVertexAttrib4ubvARB*(index: TGLuint, v: PGLubyte){.dynlib: dllname, +proc glVertexAttrib4ubvARB*(index: TGLuint, v: PGLubyte){.dynlib: dllname, importc: "glVertexAttrib4ubvARB".} -proc glVertexAttrib4usvARB*(index: TGLuint, v: PGLushort){.dynlib: dllname, +proc glVertexAttrib4usvARB*(index: TGLuint, v: PGLushort){.dynlib: dllname, importc: "glVertexAttrib4usvARB".} -proc glVertexAttrib4uivARB*(index: TGLuint, v: PGLuint){.dynlib: dllname, +proc glVertexAttrib4uivARB*(index: TGLuint, v: PGLuint){.dynlib: dllname, importc: "glVertexAttrib4uivARB".} -proc glVertexAttrib4fvARB*(index: TGLuint, v: PGLfloat){.dynlib: dllname, +proc glVertexAttrib4fvARB*(index: TGLuint, v: PGLfloat){.dynlib: dllname, importc: "glVertexAttrib4fvARB".} -proc glVertexAttrib4dvARB*(index: TGLuint, v: PGLdouble){.dynlib: dllname, +proc glVertexAttrib4dvARB*(index: TGLuint, v: PGLdouble){.dynlib: dllname, importc: "glVertexAttrib4dvARB".} -proc glVertexAttrib4NbvARB*(index: TGLuint, v: PGLbyte){.dynlib: dllname, +proc glVertexAttrib4NbvARB*(index: TGLuint, v: PGLbyte){.dynlib: dllname, importc: "glVertexAttrib4NbvARB".} -proc glVertexAttrib4NsvARB*(index: TGLuint, v: PGLshort){.dynlib: dllname, +proc glVertexAttrib4NsvARB*(index: TGLuint, v: PGLshort){.dynlib: dllname, importc: "glVertexAttrib4NsvARB".} -proc glVertexAttrib4NivARB*(index: TGLuint, v: PGLint){.dynlib: dllname, +proc glVertexAttrib4NivARB*(index: TGLuint, v: PGLint){.dynlib: dllname, importc: "glVertexAttrib4NivARB".} -proc glVertexAttrib4NubvARB*(index: TGLuint, v: PGLubyte){.dynlib: dllname, +proc glVertexAttrib4NubvARB*(index: TGLuint, v: PGLubyte){.dynlib: dllname, importc: "glVertexAttrib4NubvARB".} -proc glVertexAttrib4NusvARB*(index: TGLuint, v: PGLushort){.dynlib: dllname, +proc glVertexAttrib4NusvARB*(index: TGLuint, v: PGLushort){.dynlib: dllname, importc: "glVertexAttrib4NusvARB".} -proc glVertexAttrib4NuivARB*(index: TGLuint, v: PGLuint){.dynlib: dllname, +proc glVertexAttrib4NuivARB*(index: TGLuint, v: PGLuint){.dynlib: dllname, importc: "glVertexAttrib4NuivARB".} -proc glVertexAttribPointerARB*(index: TGLuint, size: TGLint, thetype: TGLenum, - normalized: TGLboolean, stride: TGLsizei, - pointer: PGLvoid){.dynlib: dllname, +proc glVertexAttribPointerARB*(index: TGLuint, size: TGLint, thetype: TGLenum, + normalized: TGLboolean, stride: TGLsizei, + pointer: PGLvoid){.dynlib: dllname, importc: "glVertexAttribPointerARB".} -proc glEnableVertexAttribArrayARB*(index: TGLuint){.dynlib: dllname, +proc glEnableVertexAttribArrayARB*(index: TGLuint){.dynlib: dllname, importc: "glEnableVertexAttribArrayARB".} -proc glDisableVertexAttribArrayARB*(index: TGLuint){.dynlib: dllname, +proc glDisableVertexAttribArrayARB*(index: TGLuint){.dynlib: dllname, importc: "glDisableVertexAttribArrayARB".} -proc glProgramStringARB*(target: TGLenum, format: TGLenum, length: TGLsizei, - str: PGLvoid){.dynlib: dllname, +proc glProgramStringARB*(target: TGLenum, format: TGLenum, length: TGLsizei, + str: PGLvoid){.dynlib: dllname, importc: "glProgramStringARB".} -proc glBindProgramARB*(target: TGLenum, theProgram: TGLuint){.dynlib: dllname, +proc glBindProgramARB*(target: TGLenum, theProgram: TGLuint){.dynlib: dllname, importc: "glBindProgramARB".} -proc glDeleteProgramsARB*(n: TGLsizei, programs: PGLuint){.dynlib: dllname, +proc glDeleteProgramsARB*(n: TGLsizei, programs: PGLuint){.dynlib: dllname, importc: "glDeleteProgramsARB".} -proc glGenProgramsARB*(n: TGLsizei, programs: PGLuint){.dynlib: dllname, +proc glGenProgramsARB*(n: TGLsizei, programs: PGLuint){.dynlib: dllname, importc: "glGenProgramsARB".} -proc glProgramEnvParameter4dARB*(target: TGLenum, index: TGLuint, x: TGLdouble, +proc glProgramEnvParameter4dARB*(target: TGLenum, index: TGLuint, x: TGLdouble, y: TGLdouble, z: TGLdouble, w: TGLdouble){. dynlib: dllname, importc: "glProgramEnvParameter4dARB".} -proc glProgramEnvParameter4dvARB*(target: TGLenum, index: TGLuint, - params: PGLdouble){.dynlib: dllname, +proc glProgramEnvParameter4dvARB*(target: TGLenum, index: TGLuint, + params: PGLdouble){.dynlib: dllname, importc: "glProgramEnvParameter4dvARB".} -proc glProgramEnvParameter4fARB*(target: TGLenum, index: TGLuint, x: TGLfloat, +proc glProgramEnvParameter4fARB*(target: TGLenum, index: TGLuint, x: TGLfloat, y: TGLfloat, z: TGLfloat, w: TGLfloat){. dynlib: dllname, importc: "glProgramEnvParameter4fARB".} -proc glProgramEnvParameter4fvARB*(target: TGLenum, index: TGLuint, - params: PGLfloat){.dynlib: dllname, +proc glProgramEnvParameter4fvARB*(target: TGLenum, index: TGLuint, + params: PGLfloat){.dynlib: dllname, importc: "glProgramEnvParameter4fvARB".} -proc glProgramLocalParameter4dARB*(target: TGLenum, index: TGLuint, - x: TGLdouble, y: TGLdouble, z: TGLdouble, - w: TGLdouble){.dynlib: dllname, +proc glProgramLocalParameter4dARB*(target: TGLenum, index: TGLuint, + x: TGLdouble, y: TGLdouble, z: TGLdouble, + w: TGLdouble){.dynlib: dllname, importc: "glProgramLocalParameter4dARB".} -proc glProgramLocalParameter4dvARB*(target: TGLenum, index: TGLuint, - params: PGLdouble){.dynlib: dllname, +proc glProgramLocalParameter4dvARB*(target: TGLenum, index: TGLuint, + params: PGLdouble){.dynlib: dllname, importc: "glProgramLocalParameter4dvARB".} -proc glProgramLocalParameter4fARB*(target: TGLenum, index: TGLuint, x: TGLfloat, +proc glProgramLocalParameter4fARB*(target: TGLenum, index: TGLuint, x: TGLfloat, y: TGLfloat, z: TGLfloat, w: TGLfloat){. dynlib: dllname, importc: "glProgramLocalParameter4fARB".} -proc glProgramLocalParameter4fvARB*(target: TGLenum, index: TGLuint, - params: PGLfloat){.dynlib: dllname, +proc glProgramLocalParameter4fvARB*(target: TGLenum, index: TGLuint, + params: PGLfloat){.dynlib: dllname, importc: "glProgramLocalParameter4fvARB".} -proc glGetProgramEnvParameterdvARB*(target: TGLenum, index: TGLuint, - params: PGLdouble){.dynlib: dllname, +proc glGetProgramEnvParameterdvARB*(target: TGLenum, index: TGLuint, + params: PGLdouble){.dynlib: dllname, importc: "glGetProgramEnvParameterdvARB".} -proc glGetProgramEnvParameterfvARB*(target: TGLenum, index: TGLuint, - params: PGLfloat){.dynlib: dllname, +proc glGetProgramEnvParameterfvARB*(target: TGLenum, index: TGLuint, + params: PGLfloat){.dynlib: dllname, importc: "glGetProgramEnvParameterfvARB".} -proc glGetProgramLocalParameterdvARB*(target: TGLenum, index: TGLuint, - params: PGLdouble){.dynlib: dllname, +proc glGetProgramLocalParameterdvARB*(target: TGLenum, index: TGLuint, + params: PGLdouble){.dynlib: dllname, importc: "glGetProgramLocalParameterdvARB".} -proc glGetProgramLocalParameterfvARB*(target: TGLenum, index: TGLuint, - params: PGLfloat){.dynlib: dllname, +proc glGetProgramLocalParameterfvARB*(target: TGLenum, index: TGLuint, + params: PGLfloat){.dynlib: dllname, importc: "glGetProgramLocalParameterfvARB".} proc glGetProgramivARB*(target: TGLenum, pname: TGLenum, params: PGLint){. dynlib: dllname, importc: "glGetProgramivARB".} @@ -426,100 +426,100 @@ proc glGetVertexAttribfvARB*(index: TGLuint, pname: TGLenum, params: PGLfloat){. dynlib: dllname, importc: "glGetVertexAttribfvARB".} proc glGetVertexAttribivARB*(index: TGLuint, pname: TGLenum, params: PGLint){. dynlib: dllname, importc: "glGetVertexAttribivARB".} -proc glGetVertexAttribPointervARB*(index: TGLuint, pname: TGLenum, - pointer: PGLvoid){.dynlib: dllname, +proc glGetVertexAttribPointervARB*(index: TGLuint, pname: TGLenum, + pointer: PGLvoid){.dynlib: dllname, importc: "glGetVertexAttribPointervARB".} -proc glIsProgramARB*(theProgram: TGLuint): TGLboolean{.dynlib: dllname, +proc glIsProgramARB*(theProgram: TGLuint): TGLboolean{.dynlib: dllname, importc: "glIsProgramARB".} #***** GL_ARB_window_pos *****// -proc glWindowPos2dARB*(x: TGLdouble, y: TGLdouble){.dynlib: dllname, +proc glWindowPos2dARB*(x: TGLdouble, y: TGLdouble){.dynlib: dllname, importc: "glWindowPos2dARB".} -proc glWindowPos2fARB*(x: TGLfloat, y: TGLfloat){.dynlib: dllname, +proc glWindowPos2fARB*(x: TGLfloat, y: TGLfloat){.dynlib: dllname, importc: "glWindowPos2fARB".} -proc glWindowPos2iARB*(x: TGLint, y: TGLint){.dynlib: dllname, +proc glWindowPos2iARB*(x: TGLint, y: TGLint){.dynlib: dllname, importc: "glWindowPos2iARB".} -proc glWindowPos2sARB*(x: TGLshort, y: TGLshort){.dynlib: dllname, +proc glWindowPos2sARB*(x: TGLshort, y: TGLshort){.dynlib: dllname, importc: "glWindowPos2sARB".} -proc glWindowPos2dvARB*(p: PGLdouble){.dynlib: dllname, +proc glWindowPos2dvARB*(p: PGLdouble){.dynlib: dllname, importc: "glWindowPos2dvARB".} -proc glWindowPos2fvARB*(p: PGLfloat){.dynlib: dllname, +proc glWindowPos2fvARB*(p: PGLfloat){.dynlib: dllname, importc: "glWindowPos2fvARB".} -proc glWindowPos2ivARB*(p: PGLint){.dynlib: dllname, +proc glWindowPos2ivARB*(p: PGLint){.dynlib: dllname, importc: "glWindowPos2ivARB".} -proc glWindowPos2svARB*(p: PGLshort){.dynlib: dllname, +proc glWindowPos2svARB*(p: PGLshort){.dynlib: dllname, importc: "glWindowPos2svARB".} proc glWindowPos3dARB*(x: TGLdouble, y: TGLdouble, z: TGLdouble){. dynlib: dllname, importc: "glWindowPos3dARB".} -proc glWindowPos3fARB*(x: TGLfloat, y: TGLfloat, z: TGLfloat){.dynlib: dllname, +proc glWindowPos3fARB*(x: TGLfloat, y: TGLfloat, z: TGLfloat){.dynlib: dllname, importc: "glWindowPos3fARB".} -proc glWindowPos3iARB*(x: TGLint, y: TGLint, z: TGLint){.dynlib: dllname, +proc glWindowPos3iARB*(x: TGLint, y: TGLint, z: TGLint){.dynlib: dllname, importc: "glWindowPos3iARB".} -proc glWindowPos3sARB*(x: TGLshort, y: TGLshort, z: TGLshort){.dynlib: dllname, +proc glWindowPos3sARB*(x: TGLshort, y: TGLshort, z: TGLshort){.dynlib: dllname, importc: "glWindowPos3sARB".} -proc glWindowPos3dvARB*(p: PGLdouble){.dynlib: dllname, +proc glWindowPos3dvARB*(p: PGLdouble){.dynlib: dllname, importc: "glWindowPos3dvARB".} -proc glWindowPos3fvARB*(p: PGLfloat){.dynlib: dllname, +proc glWindowPos3fvARB*(p: PGLfloat){.dynlib: dllname, importc: "glWindowPos3fvARB".} -proc glWindowPos3ivARB*(p: PGLint){.dynlib: dllname, +proc glWindowPos3ivARB*(p: PGLint){.dynlib: dllname, importc: "glWindowPos3ivARB".} -proc glWindowPos3svARB*(p: PGLshort){.dynlib: dllname, +proc glWindowPos3svARB*(p: PGLshort){.dynlib: dllname, importc: "glWindowPos3svARB".} proc glBlendEquationSeparate*(modeRGB: TGLenum, modeAlpha: TGLenum){. dynlib: dllname, importc: "glBlendEquationSeparate".} -proc glDrawBuffers*(n: TGLsizei, bufs: PGLenum){.dynlib: dllname, +proc glDrawBuffers*(n: TGLsizei, bufs: PGLenum){.dynlib: dllname, importc: "glDrawBuffers".} -proc glStencilOpSeparate*(face: TGLenum, sfail: TGLenum, dpfail: TGLenum, - dppass: TGLenum){.dynlib: dllname, +proc glStencilOpSeparate*(face: TGLenum, sfail: TGLenum, dpfail: TGLenum, + dppass: TGLenum){.dynlib: dllname, importc: "glStencilOpSeparate".} -proc glStencilFuncSeparate*(frontfunc: TGLenum, backfunc: TGLenum, - theRef: TGLint, mask: TGLuint){.dynlib: dllname, +proc glStencilFuncSeparate*(frontfunc: TGLenum, backfunc: TGLenum, + theRef: TGLint, mask: TGLuint){.dynlib: dllname, importc: "glStencilFuncSeparate".} -proc glStencilMaskSeparate*(face: TGLenum, mask: TGLuint){.dynlib: dllname, +proc glStencilMaskSeparate*(face: TGLenum, mask: TGLuint){.dynlib: dllname, importc: "glStencilMaskSeparate".} -proc glAttachShader*(theProgram: TGLuint, shader: TGLuint){.dynlib: dllname, +proc glAttachShader*(theProgram: TGLuint, shader: TGLuint){.dynlib: dllname, importc: "glAttachShader".} proc glBindAttribLocation*(theProgram: TGLuint, index: TGLuint, name: PGLchar){. dynlib: dllname, importc: "glBindAttribLocation".} -proc glCompileShader*(shader: TGLuint){.dynlib: dllname, +proc glCompileShader*(shader: TGLuint){.dynlib: dllname, importc: "glCompileShader".} proc glCreateProgram*(): TGLuint{.dynlib: dllname, importc: "glCreateProgram".} -proc glCreateShader*(thetype: TGLenum): TGLuint{.dynlib: dllname, +proc glCreateShader*(thetype: TGLenum): TGLuint{.dynlib: dllname, importc: "glCreateShader".} -proc glDeleteProgram*(theProgram: TGLuint){.dynlib: dllname, +proc glDeleteProgram*(theProgram: TGLuint){.dynlib: dllname, importc: "glDeleteProgram".} -proc glDeleteShader*(shader: TGLuint){.dynlib: dllname, +proc glDeleteShader*(shader: TGLuint){.dynlib: dllname, importc: "glDeleteShader".} -proc glDetachShader*(theProgram: TGLuint, shader: TGLuint){.dynlib: dllname, +proc glDetachShader*(theProgram: TGLuint, shader: TGLuint){.dynlib: dllname, importc: "glDetachShader".} -proc glDisableVertexAttribArray*(index: TGLuint){.dynlib: dllname, +proc glDisableVertexAttribArray*(index: TGLuint){.dynlib: dllname, importc: "glDisableVertexAttribArray".} -proc glEnableVertexAttribArray*(index: TGLuint){.dynlib: dllname, +proc glEnableVertexAttribArray*(index: TGLuint){.dynlib: dllname, importc: "glEnableVertexAttribArray".} -proc glGetActiveAttrib*(theProgram: TGLuint, index: TGLuint, bufSize: TGLsizei, - len: PGLsizei, size: PGLint, thetype: PGLenum, - name: PGLchar){.dynlib: dllname, +proc glGetActiveAttrib*(theProgram: TGLuint, index: TGLuint, bufSize: TGLsizei, + len: PGLsizei, size: PGLint, thetype: PGLenum, + name: PGLchar){.dynlib: dllname, importc: "glGetActiveAttrib".} -proc glGetActiveUniform*(theProgram: TGLuint, index: TGLuint, bufSize: TGLsizei, - len: PGLsizei, size: PGLint, thetype: PGLenum, - name: PGLchar){.dynlib: dllname, +proc glGetActiveUniform*(theProgram: TGLuint, index: TGLuint, bufSize: TGLsizei, + len: PGLsizei, size: PGLint, thetype: PGLenum, + name: PGLchar){.dynlib: dllname, importc: "glGetActiveUniform".} -proc glGetAttachedShaders*(theProgram: TGLuint, maxCount: TGLsizei, - count: PGLsizei, obj: PGLuint){.dynlib: dllname, +proc glGetAttachedShaders*(theProgram: TGLuint, maxCount: TGLsizei, + count: PGLsizei, obj: PGLuint){.dynlib: dllname, importc: "glGetAttachedShaders".} proc glGetAttribLocation*(theProgram: TGLuint, name: PGLchar): TGLint{. dynlib: dllname, importc: "glGetAttribLocation".} proc glGetProgramiv*(theProgram: TGLuint, pname: TGLenum, params: PGLint){. dynlib: dllname, importc: "glGetProgramiv".} -proc glGetProgramInfoLog*(theProgram: TGLuint, bufSize: TGLsizei, len: PGLsizei, - infoLog: PGLchar){.dynlib: dllname, +proc glGetProgramInfoLog*(theProgram: TGLuint, bufSize: TGLsizei, len: PGLsizei, + infoLog: PGLchar){.dynlib: dllname, importc: "glGetProgramInfoLog".} proc glGetShaderiv*(shader: TGLuint, pname: TGLenum, params: PGLint){. dynlib: dllname, importc: "glGetShaderiv".} -proc glGetShaderInfoLog*(shader: TGLuint, bufSize: TGLsizei, len: PGLsizei, - infoLog: PGLchar){.dynlib: dllname, +proc glGetShaderInfoLog*(shader: TGLuint, bufSize: TGLsizei, len: PGLsizei, + infoLog: PGLchar){.dynlib: dllname, importc: "glGetShaderInfoLog".} -proc glGetShaderSource*(shader: TGLuint, bufSize: TGLsizei, len: PGLsizei, - source: PGLchar){.dynlib: dllname, +proc glGetShaderSource*(shader: TGLuint, bufSize: TGLsizei, len: PGLsizei, + source: PGLchar){.dynlib: dllname, importc: "glGetShaderSource".} proc glGetUniformLocation*(theProgram: TGLuint, name: PGLchar): TGLint{. dynlib: dllname, importc: "glGetUniformLocation".} @@ -535,31 +535,31 @@ proc glGetVertexAttribiv*(index: TGLuint, pname: TGLenum, params: PGLint){. dynlib: dllname, importc: "glGetVertexAttribiv".} proc glGetVertexAttribPointerv*(index: TGLuint, pname: TGLenum, pointer: PGLvoid){. dynlib: dllname, importc: "glGetVertexAttribPointerv".} -proc glIsProgram*(theProgram: TGLuint): TGLboolean{.dynlib: dllname, +proc glIsProgram*(theProgram: TGLuint): TGLboolean{.dynlib: dllname, importc: "glIsProgram".} -proc glIsShader*(shader: TGLuint): TGLboolean{.dynlib: dllname, +proc glIsShader*(shader: TGLuint): TGLboolean{.dynlib: dllname, importc: "glIsShader".} -proc glLinkProgram*(theProgram: TGLuint){.dynlib: dllname, +proc glLinkProgram*(theProgram: TGLuint){.dynlib: dllname, importc: "glLinkProgram".} proc glShaderSource*(shader: TGLuint, count: TGLsizei, str: PGLchar, len: PGLint){. dynlib: dllname, importc: "glShaderSource".} -proc glUseProgram*(theProgram: TGLuint){.dynlib: dllname, +proc glUseProgram*(theProgram: TGLuint){.dynlib: dllname, importc: "glUseProgram".} -proc glUniform1f*(location: TGLint, v0: TGLfloat){.dynlib: dllname, +proc glUniform1f*(location: TGLint, v0: TGLfloat){.dynlib: dllname, importc: "glUniform1f".} proc glUniform2f*(location: TGLint, v0: TGLfloat, v1: TGLfloat){. dynlib: dllname, importc: "glUniform2f".} proc glUniform3f*(location: TGLint, v0: TGLfloat, v1: TGLfloat, v2: TGLfloat){. dynlib: dllname, importc: "glUniform3f".} -proc glUniform4f*(location: TGLint, v0: TGLfloat, v1: TGLfloat, v2: TGLfloat, +proc glUniform4f*(location: TGLint, v0: TGLfloat, v1: TGLfloat, v2: TGLfloat, v3: TGLfloat){.dynlib: dllname, importc: "glUniform4f".} -proc glUniform1i*(location: TGLint, v0: TGLint){.dynlib: dllname, +proc glUniform1i*(location: TGLint, v0: TGLint){.dynlib: dllname, importc: "glUniform1i".} -proc glUniform2i*(location: TGLint, v0: TGLint, v1: TGLint){.dynlib: dllname, +proc glUniform2i*(location: TGLint, v0: TGLint, v1: TGLint){.dynlib: dllname, importc: "glUniform2i".} proc glUniform3i*(location: TGLint, v0: TGLint, v1: TGLint, v2: TGLint){. dynlib: dllname, importc: "glUniform3i".} -proc glUniform4i*(location: TGLint, v0: TGLint, v1: TGLint, v2: TGLint, +proc glUniform4i*(location: TGLint, v0: TGLint, v1: TGLint, v2: TGLint, v3: TGLint){.dynlib: dllname, importc: "glUniform4i".} proc glUniform1fv*(location: TGLint, count: TGLsizei, value: PGLfloat){. dynlib: dllname, importc: "glUniform1fv".} @@ -577,98 +577,98 @@ proc glUniform3iv*(location: TGLint, count: TGLsizei, value: PGLint){. dynlib: dllname, importc: "glUniform3iv".} proc glUniform4iv*(location: TGLint, count: TGLsizei, value: PGLint){. dynlib: dllname, importc: "glUniform4iv".} -proc glUniformMatrix2fv*(location: TGLint, count: TGLsizei, +proc glUniformMatrix2fv*(location: TGLint, count: TGLsizei, transpose: TGLboolean, value: PGLfloat){. dynlib: dllname, importc: "glUniformMatrix2fv".} -proc glUniformMatrix3fv*(location: TGLint, count: TGLsizei, +proc glUniformMatrix3fv*(location: TGLint, count: TGLsizei, transpose: TGLboolean, value: PGLfloat){. dynlib: dllname, importc: "glUniformMatrix3fv".} -proc glUniformMatrix4fv*(location: TGLint, count: TGLsizei, +proc glUniformMatrix4fv*(location: TGLint, count: TGLsizei, transpose: TGLboolean, value: PGLfloat){. dynlib: dllname, importc: "glUniformMatrix4fv".} -proc glValidateProgram*(theProgram: TGLuint){.dynlib: dllname, +proc glValidateProgram*(theProgram: TGLuint){.dynlib: dllname, importc: "glValidateProgram".} -proc glVertexAttrib1d*(index: TGLuint, x: TGLdouble){.dynlib: dllname, +proc glVertexAttrib1d*(index: TGLuint, x: TGLdouble){.dynlib: dllname, importc: "glVertexAttrib1d".} -proc glVertexAttrib1dv*(index: TGLuint, v: PGLdouble){.dynlib: dllname, +proc glVertexAttrib1dv*(index: TGLuint, v: PGLdouble){.dynlib: dllname, importc: "glVertexAttrib1dv".} -proc glVertexAttrib1f*(index: TGLuint, x: TGLfloat){.dynlib: dllname, +proc glVertexAttrib1f*(index: TGLuint, x: TGLfloat){.dynlib: dllname, importc: "glVertexAttrib1f".} -proc glVertexAttrib1fv*(index: TGLuint, v: PGLfloat){.dynlib: dllname, +proc glVertexAttrib1fv*(index: TGLuint, v: PGLfloat){.dynlib: dllname, importc: "glVertexAttrib1fv".} -proc glVertexAttrib1s*(index: TGLuint, x: TGLshort){.dynlib: dllname, +proc glVertexAttrib1s*(index: TGLuint, x: TGLshort){.dynlib: dllname, importc: "glVertexAttrib1s".} -proc glVertexAttrib1sv*(index: TGLuint, v: PGLshort){.dynlib: dllname, +proc glVertexAttrib1sv*(index: TGLuint, v: PGLshort){.dynlib: dllname, importc: "glVertexAttrib1sv".} proc glVertexAttrib2d*(index: TGLuint, x: TGLdouble, y: TGLdouble){. dynlib: dllname, importc: "glVertexAttrib2d".} -proc glVertexAttrib2dv*(index: TGLuint, v: PGLdouble){.dynlib: dllname, +proc glVertexAttrib2dv*(index: TGLuint, v: PGLdouble){.dynlib: dllname, importc: "glVertexAttrib2dv".} proc glVertexAttrib2f*(index: TGLuint, x: TGLfloat, y: TGLfloat){. dynlib: dllname, importc: "glVertexAttrib2f".} -proc glVertexAttrib2fv*(index: TGLuint, v: PGLfloat){.dynlib: dllname, +proc glVertexAttrib2fv*(index: TGLuint, v: PGLfloat){.dynlib: dllname, importc: "glVertexAttrib2fv".} proc glVertexAttrib2s*(index: TGLuint, x: TGLshort, y: TGLshort){. dynlib: dllname, importc: "glVertexAttrib2s".} -proc glVertexAttrib2sv*(index: TGLuint, v: PGLshort){.dynlib: dllname, +proc glVertexAttrib2sv*(index: TGLuint, v: PGLshort){.dynlib: dllname, importc: "glVertexAttrib2sv".} proc glVertexAttrib3d*(index: TGLuint, x: TGLdouble, y: TGLdouble, z: TGLdouble){. dynlib: dllname, importc: "glVertexAttrib3d".} -proc glVertexAttrib3dv*(index: TGLuint, v: PGLdouble){.dynlib: dllname, +proc glVertexAttrib3dv*(index: TGLuint, v: PGLdouble){.dynlib: dllname, importc: "glVertexAttrib3dv".} proc glVertexAttrib3f*(index: TGLuint, x: TGLfloat, y: TGLfloat, z: TGLfloat){. dynlib: dllname, importc: "glVertexAttrib3f".} -proc glVertexAttrib3fv*(index: TGLuint, v: PGLfloat){.dynlib: dllname, +proc glVertexAttrib3fv*(index: TGLuint, v: PGLfloat){.dynlib: dllname, importc: "glVertexAttrib3fv".} proc glVertexAttrib3s*(index: TGLuint, x: TGLshort, y: TGLshort, z: TGLshort){. dynlib: dllname, importc: "glVertexAttrib3s".} -proc glVertexAttrib3sv*(index: TGLuint, v: PGLshort){.dynlib: dllname, +proc glVertexAttrib3sv*(index: TGLuint, v: PGLshort){.dynlib: dllname, importc: "glVertexAttrib3sv".} -proc glVertexAttrib4Nbv*(index: TGLuint, v: PGLbyte){.dynlib: dllname, +proc glVertexAttrib4Nbv*(index: TGLuint, v: PGLbyte){.dynlib: dllname, importc: "glVertexAttrib4Nbv".} -proc glVertexAttrib4Niv*(index: TGLuint, v: PGLint){.dynlib: dllname, +proc glVertexAttrib4Niv*(index: TGLuint, v: PGLint){.dynlib: dllname, importc: "glVertexAttrib4Niv".} -proc glVertexAttrib4Nsv*(index: TGLuint, v: PGLshort){.dynlib: dllname, +proc glVertexAttrib4Nsv*(index: TGLuint, v: PGLshort){.dynlib: dllname, importc: "glVertexAttrib4Nsv".} -proc glVertexAttrib4Nub*(index: TGLuint, x: TGLubyte, y: TGLubyte, z: TGLubyte, - w: TGLubyte){.dynlib: dllname, +proc glVertexAttrib4Nub*(index: TGLuint, x: TGLubyte, y: TGLubyte, z: TGLubyte, + w: TGLubyte){.dynlib: dllname, importc: "glVertexAttrib4Nub".} -proc glVertexAttrib4Nubv*(index: TGLuint, v: PGLubyte){.dynlib: dllname, +proc glVertexAttrib4Nubv*(index: TGLuint, v: PGLubyte){.dynlib: dllname, importc: "glVertexAttrib4Nubv".} -proc glVertexAttrib4Nuiv*(index: TGLuint, v: PGLuint){.dynlib: dllname, +proc glVertexAttrib4Nuiv*(index: TGLuint, v: PGLuint){.dynlib: dllname, importc: "glVertexAttrib4Nuiv".} -proc glVertexAttrib4Nusv*(index: TGLuint, v: PGLushort){.dynlib: dllname, +proc glVertexAttrib4Nusv*(index: TGLuint, v: PGLushort){.dynlib: dllname, importc: "glVertexAttrib4Nusv".} -proc glVertexAttrib4bv*(index: TGLuint, v: PGLbyte){.dynlib: dllname, +proc glVertexAttrib4bv*(index: TGLuint, v: PGLbyte){.dynlib: dllname, importc: "glVertexAttrib4bv".} -proc glVertexAttrib4d*(index: TGLuint, x: TGLdouble, y: TGLdouble, z: TGLdouble, - w: TGLdouble){.dynlib: dllname, +proc glVertexAttrib4d*(index: TGLuint, x: TGLdouble, y: TGLdouble, z: TGLdouble, + w: TGLdouble){.dynlib: dllname, importc: "glVertexAttrib4d".} -proc glVertexAttrib4dv*(index: TGLuint, v: PGLdouble){.dynlib: dllname, +proc glVertexAttrib4dv*(index: TGLuint, v: PGLdouble){.dynlib: dllname, importc: "glVertexAttrib4dv".} -proc glVertexAttrib4f*(index: TGLuint, x: TGLfloat, y: TGLfloat, z: TGLfloat, - w: TGLfloat){.dynlib: dllname, +proc glVertexAttrib4f*(index: TGLuint, x: TGLfloat, y: TGLfloat, z: TGLfloat, + w: TGLfloat){.dynlib: dllname, importc: "glVertexAttrib4f".} -proc glVertexAttrib4fv*(index: TGLuint, v: PGLfloat){.dynlib: dllname, +proc glVertexAttrib4fv*(index: TGLuint, v: PGLfloat){.dynlib: dllname, importc: "glVertexAttrib4fv".} -proc glVertexAttrib4iv*(index: TGLuint, v: PGLint){.dynlib: dllname, +proc glVertexAttrib4iv*(index: TGLuint, v: PGLint){.dynlib: dllname, importc: "glVertexAttrib4iv".} -proc glVertexAttrib4s*(index: TGLuint, x: TGLshort, y: TGLshort, z: TGLshort, - w: TGLshort){.dynlib: dllname, +proc glVertexAttrib4s*(index: TGLuint, x: TGLshort, y: TGLshort, z: TGLshort, + w: TGLshort){.dynlib: dllname, importc: "glVertexAttrib4s".} -proc glVertexAttrib4sv*(index: TGLuint, v: PGLshort){.dynlib: dllname, +proc glVertexAttrib4sv*(index: TGLuint, v: PGLshort){.dynlib: dllname, importc: "glVertexAttrib4sv".} -proc glVertexAttrib4ubv*(index: TGLuint, v: PGLubyte){.dynlib: dllname, +proc glVertexAttrib4ubv*(index: TGLuint, v: PGLubyte){.dynlib: dllname, importc: "glVertexAttrib4ubv".} -proc glVertexAttrib4uiv*(index: TGLuint, v: PGLuint){.dynlib: dllname, +proc glVertexAttrib4uiv*(index: TGLuint, v: PGLuint){.dynlib: dllname, importc: "glVertexAttrib4uiv".} -proc glVertexAttrib4usv*(index: TGLuint, v: PGLushort){.dynlib: dllname, +proc glVertexAttrib4usv*(index: TGLuint, v: PGLushort){.dynlib: dllname, importc: "glVertexAttrib4usv".} -proc glVertexAttribPointer*(index: TGLuint, size: TGLint, thetype: TGLenum, - normalized: TGLboolean, stride: TGLsizei, - pointer: PGLvoid){.dynlib: dllname, +proc glVertexAttribPointer*(index: TGLuint, size: TGLint, thetype: TGLenum, + normalized: TGLboolean, stride: TGLsizei, + pointer: PGLvoid){.dynlib: dllname, importc: "glVertexAttribPointer".} -const +const GL_CONSTANT_COLOR* = 0x00008001 GL_ONE_MINUS_CONSTANT_COLOR* = 0x00008002 GL_CONSTANT_ALPHA* = 0x00008003 @@ -747,122 +747,122 @@ const GL_REPLICATE_BORDER* = 0x00008153 GL_CONVOLUTION_BORDER_COLOR* = 0x00008154 -proc glActiveTexture*(texture: TGLenum){.dynlib: dllname, +proc glActiveTexture*(texture: TGLenum){.dynlib: dllname, importc: "glActiveTexture".} -proc glClientActiveTexture*(texture: TGLenum){.dynlib: dllname, +proc glClientActiveTexture*(texture: TGLenum){.dynlib: dllname, importc: "glClientActiveTexture".} -proc glMultiTexCoord1d*(target: TGLenum, s: TGLdouble){.dynlib: dllname, +proc glMultiTexCoord1d*(target: TGLenum, s: TGLdouble){.dynlib: dllname, importc: "glMultiTexCoord1d".} -proc glMultiTexCoord1dv*(target: TGLenum, v: PGLdouble){.dynlib: dllname, +proc glMultiTexCoord1dv*(target: TGLenum, v: PGLdouble){.dynlib: dllname, importc: "glMultiTexCoord1dv".} -proc glMultiTexCoord1f*(target: TGLenum, s: TGLfloat){.dynlib: dllname, +proc glMultiTexCoord1f*(target: TGLenum, s: TGLfloat){.dynlib: dllname, importc: "glMultiTexCoord1f".} -proc glMultiTexCoord1fv*(target: TGLenum, v: PGLfloat){.dynlib: dllname, +proc glMultiTexCoord1fv*(target: TGLenum, v: PGLfloat){.dynlib: dllname, importc: "glMultiTexCoord1fv".} -proc glMultiTexCoord1i*(target: TGLenum, s: TGLint){.dynlib: dllname, +proc glMultiTexCoord1i*(target: TGLenum, s: TGLint){.dynlib: dllname, importc: "glMultiTexCoord1i".} -proc glMultiTexCoord1iv*(target: TGLenum, v: PGLint){.dynlib: dllname, +proc glMultiTexCoord1iv*(target: TGLenum, v: PGLint){.dynlib: dllname, importc: "glMultiTexCoord1iv".} -proc glMultiTexCoord1s*(target: TGLenum, s: TGLshort){.dynlib: dllname, +proc glMultiTexCoord1s*(target: TGLenum, s: TGLshort){.dynlib: dllname, importc: "glMultiTexCoord1s".} -proc glMultiTexCoord1sv*(target: TGLenum, v: PGLshort){.dynlib: dllname, +proc glMultiTexCoord1sv*(target: TGLenum, v: PGLshort){.dynlib: dllname, importc: "glMultiTexCoord1sv".} proc glMultiTexCoord2d*(target: TGLenum, s: TGLdouble, t: TGLdouble){. dynlib: dllname, importc: "glMultiTexCoord2d".} -proc glMultiTexCoord2dv*(target: TGLenum, v: PGLdouble){.dynlib: dllname, +proc glMultiTexCoord2dv*(target: TGLenum, v: PGLdouble){.dynlib: dllname, importc: "glMultiTexCoord2dv".} proc glMultiTexCoord2f*(target: TGLenum, s: TGLfloat, t: TGLfloat){. dynlib: dllname, importc: "glMultiTexCoord2f".} -proc glMultiTexCoord2fv*(target: TGLenum, v: PGLfloat){.dynlib: dllname, +proc glMultiTexCoord2fv*(target: TGLenum, v: PGLfloat){.dynlib: dllname, importc: "glMultiTexCoord2fv".} -proc glMultiTexCoord2i*(target: TGLenum, s: TGLint, t: TGLint){.dynlib: dllname, +proc glMultiTexCoord2i*(target: TGLenum, s: TGLint, t: TGLint){.dynlib: dllname, importc: "glMultiTexCoord2i".} -proc glMultiTexCoord2iv*(target: TGLenum, v: PGLint){.dynlib: dllname, +proc glMultiTexCoord2iv*(target: TGLenum, v: PGLint){.dynlib: dllname, importc: "glMultiTexCoord2iv".} proc glMultiTexCoord2s*(target: TGLenum, s: TGLshort, t: TGLshort){. dynlib: dllname, importc: "glMultiTexCoord2s".} -proc glMultiTexCoord2sv*(target: TGLenum, v: PGLshort){.dynlib: dllname, +proc glMultiTexCoord2sv*(target: TGLenum, v: PGLshort){.dynlib: dllname, importc: "glMultiTexCoord2sv".} -proc glMultiTexCoord3d*(target: TGLenum, s: TGLdouble, t: TGLdouble, - r: TGLdouble){.dynlib: dllname, +proc glMultiTexCoord3d*(target: TGLenum, s: TGLdouble, t: TGLdouble, + r: TGLdouble){.dynlib: dllname, importc: "glMultiTexCoord3d".} -proc glMultiTexCoord3dv*(target: TGLenum, v: PGLdouble){.dynlib: dllname, +proc glMultiTexCoord3dv*(target: TGLenum, v: PGLdouble){.dynlib: dllname, importc: "glMultiTexCoord3dv".} proc glMultiTexCoord3f*(target: TGLenum, s: TGLfloat, t: TGLfloat, r: TGLfloat){. dynlib: dllname, importc: "glMultiTexCoord3f".} -proc glMultiTexCoord3fv*(target: TGLenum, v: PGLfloat){.dynlib: dllname, +proc glMultiTexCoord3fv*(target: TGLenum, v: PGLfloat){.dynlib: dllname, importc: "glMultiTexCoord3fv".} proc glMultiTexCoord3i*(target: TGLenum, s: TGLint, t: TGLint, r: TGLint){. dynlib: dllname, importc: "glMultiTexCoord3i".} -proc glMultiTexCoord3iv*(target: TGLenum, v: PGLint){.dynlib: dllname, +proc glMultiTexCoord3iv*(target: TGLenum, v: PGLint){.dynlib: dllname, importc: "glMultiTexCoord3iv".} proc glMultiTexCoord3s*(target: TGLenum, s: TGLshort, t: TGLshort, r: TGLshort){. dynlib: dllname, importc: "glMultiTexCoord3s".} -proc glMultiTexCoord3sv*(target: TGLenum, v: PGLshort){.dynlib: dllname, +proc glMultiTexCoord3sv*(target: TGLenum, v: PGLshort){.dynlib: dllname, importc: "glMultiTexCoord3sv".} -proc glMultiTexCoord4d*(target: TGLenum, s: TGLdouble, t: TGLdouble, - r: TGLdouble, q: TGLdouble){.dynlib: dllname, +proc glMultiTexCoord4d*(target: TGLenum, s: TGLdouble, t: TGLdouble, + r: TGLdouble, q: TGLdouble){.dynlib: dllname, importc: "glMultiTexCoord4d".} -proc glMultiTexCoord4dv*(target: TGLenum, v: PGLdouble){.dynlib: dllname, +proc glMultiTexCoord4dv*(target: TGLenum, v: PGLdouble){.dynlib: dllname, importc: "glMultiTexCoord4dv".} -proc glMultiTexCoord4f*(target: TGLenum, s: TGLfloat, t: TGLfloat, r: TGLfloat, - q: TGLfloat){.dynlib: dllname, +proc glMultiTexCoord4f*(target: TGLenum, s: TGLfloat, t: TGLfloat, r: TGLfloat, + q: TGLfloat){.dynlib: dllname, importc: "glMultiTexCoord4f".} -proc glMultiTexCoord4fv*(target: TGLenum, v: PGLfloat){.dynlib: dllname, +proc glMultiTexCoord4fv*(target: TGLenum, v: PGLfloat){.dynlib: dllname, importc: "glMultiTexCoord4fv".} -proc glMultiTexCoord4i*(target: TGLenum, s: TGLint, t: TGLint, r: TGLint, - q: TGLint){.dynlib: dllname, +proc glMultiTexCoord4i*(target: TGLenum, s: TGLint, t: TGLint, r: TGLint, + q: TGLint){.dynlib: dllname, importc: "glMultiTexCoord4i".} -proc glMultiTexCoord4iv*(target: TGLenum, v: PGLint){.dynlib: dllname, +proc glMultiTexCoord4iv*(target: TGLenum, v: PGLint){.dynlib: dllname, importc: "glMultiTexCoord4iv".} -proc glMultiTexCoord4s*(target: TGLenum, s: TGLshort, t: TGLshort, r: TGLshort, - q: TGLshort){.dynlib: dllname, +proc glMultiTexCoord4s*(target: TGLenum, s: TGLshort, t: TGLshort, r: TGLshort, + q: TGLshort){.dynlib: dllname, importc: "glMultiTexCoord4s".} -proc glMultiTexCoord4sv*(target: TGLenum, v: PGLshort){.dynlib: dllname, +proc glMultiTexCoord4sv*(target: TGLenum, v: PGLshort){.dynlib: dllname, importc: "glMultiTexCoord4sv".} -proc glLoadTransposeMatrixf*(m: PGLfloat){.dynlib: dllname, +proc glLoadTransposeMatrixf*(m: PGLfloat){.dynlib: dllname, importc: "glLoadTransposeMatrixf".} -proc glLoadTransposeMatrixd*(m: PGLdouble){.dynlib: dllname, +proc glLoadTransposeMatrixd*(m: PGLdouble){.dynlib: dllname, importc: "glLoadTransposeMatrixd".} -proc glMultTransposeMatrixf*(m: PGLfloat){.dynlib: dllname, +proc glMultTransposeMatrixf*(m: PGLfloat){.dynlib: dllname, importc: "glMultTransposeMatrixf".} -proc glMultTransposeMatrixd*(m: PGLdouble){.dynlib: dllname, +proc glMultTransposeMatrixd*(m: PGLdouble){.dynlib: dllname, importc: "glMultTransposeMatrixd".} -proc glSampleCoverage*(value: TGLclampf, invert: TGLboolean){.dynlib: dllname, +proc glSampleCoverage*(value: TGLclampf, invert: TGLboolean){.dynlib: dllname, importc: "glSampleCoverage".} -proc glCompressedTexImage3D*(target: TGLenum, level: TGLint, - internalformat: TGLenum, width: TGLsizei, - height: TGLsizei, depth: TGLsizei, border: TGLint, +proc glCompressedTexImage3D*(target: TGLenum, level: TGLint, + internalformat: TGLenum, width: TGLsizei, + height: TGLsizei, depth: TGLsizei, border: TGLint, imageSize: TGLsizei, data: PGLvoid){. dynlib: dllname, importc: "glCompressedTexImage3D".} -proc glCompressedTexImage2D*(target: TGLenum, level: TGLint, - internalformat: TGLenum, width: TGLsizei, - height: TGLsizei, border: TGLint, +proc glCompressedTexImage2D*(target: TGLenum, level: TGLint, + internalformat: TGLenum, width: TGLsizei, + height: TGLsizei, border: TGLint, imageSize: TGLsizei, data: PGLvoid){. dynlib: dllname, importc: "glCompressedTexImage2D".} -proc glCompressedTexImage1D*(target: TGLenum, level: TGLint, - internalformat: TGLenum, width: TGLsizei, +proc glCompressedTexImage1D*(target: TGLenum, level: TGLint, + internalformat: TGLenum, width: TGLsizei, border: TGLint, imageSize: TGLsizei, data: PGLvoid){. dynlib: dllname, importc: "glCompressedTexImage1D".} -proc glCompressedTexSubImage3D*(target: TGLenum, level: TGLint, xoffset: TGLint, - yoffset: TGLint, zoffset: TGLint, - width: TGLsizei, height: TGLsizei, - depth: TGLsizei, format: TGLenum, +proc glCompressedTexSubImage3D*(target: TGLenum, level: TGLint, xoffset: TGLint, + yoffset: TGLint, zoffset: TGLint, + width: TGLsizei, height: TGLsizei, + depth: TGLsizei, format: TGLenum, imageSize: TGLsizei, data: PGLvoid){. dynlib: dllname, importc: "glCompressedTexSubImage3D".} -proc glCompressedTexSubImage2D*(target: TGLenum, level: TGLint, xoffset: TGLint, - yoffset: TGLint, width: TGLsizei, - height: TGLsizei, format: TGLenum, +proc glCompressedTexSubImage2D*(target: TGLenum, level: TGLint, xoffset: TGLint, + yoffset: TGLint, width: TGLsizei, + height: TGLsizei, format: TGLenum, imageSize: TGLsizei, data: PGLvoid){. dynlib: dllname, importc: "glCompressedTexSubImage2D".} -proc glCompressedTexSubImage1D*(target: TGLenum, level: TGLint, xoffset: TGLint, - width: TGLsizei, format: TGLenum, +proc glCompressedTexSubImage1D*(target: TGLenum, level: TGLint, xoffset: TGLint, + width: TGLsizei, format: TGLenum, imageSize: TGLsizei, data: PGLvoid){. dynlib: dllname, importc: "glCompressedTexSubImage1D".} proc glGetCompressedTexImage*(target: TGLenum, level: TGLint, img: PGLvoid){. dynlib: dllname, importc: "glGetCompressedTexImage".} #***** GL_version_1_3 *****// -const +const GL_TEXTURE0* = 0x000084C0 GL_TEXTURE1* = 0x000084C1 GL_TEXTURE2* = 0x000084C2 @@ -961,7 +961,7 @@ const GL_DOT3_RGB* = 0x000086AE GL_DOT3_RGBA* = 0x000086AF -const +const GL_TEXTURE0_ARB* = 0x000084C0 GL_TEXTURE1_ARB* = 0x000084C1 GL_TEXTURE2_ARB* = 0x000084C2 @@ -999,21 +999,21 @@ const GL_MAX_TEXTURE_UNITS_ARB* = 0x000084E2 #***** GL_ARB_transpose_matrix *****// -const +const GL_TRANSPOSE_MODELVIEW_MATRIX_ARB* = 0x000084E3 GL_TRANSPOSE_PROJECTION_MATRIX_ARB* = 0x000084E4 GL_TRANSPOSE_TEXTURE_MATRIX_ARB* = 0x000084E5 GL_TRANSPOSE_COLOR_MATRIX_ARB* = 0x000084E6 -proc glLoadTransposeMatrixfARB*(m: PGLfloat){.dynlib: dllname, +proc glLoadTransposeMatrixfARB*(m: PGLfloat){.dynlib: dllname, importc: "glLoadTransposeMatrixfARB".} -proc glLoadTransposeMatrixdARB*(m: PGLdouble){.dynlib: dllname, +proc glLoadTransposeMatrixdARB*(m: PGLdouble){.dynlib: dllname, importc: "glLoadTransposeMatrixdARB".} -proc glMultTransposeMatrixfARB*(m: PGLfloat){.dynlib: dllname, +proc glMultTransposeMatrixfARB*(m: PGLfloat){.dynlib: dllname, importc: "glMultTransposeMatrixfARB".} -proc glMultTransposeMatrixdARB*(m: PGLdouble){.dynlib: dllname, +proc glMultTransposeMatrixdARB*(m: PGLdouble){.dynlib: dllname, importc: "glMultTransposeMatrixdARB".} -const +const WGL_SAMPLE_BUFFERS_ARB* = 0x00002041 WGL_SAMPLES_ARB* = 0x00002042 GL_MULTISAMPLE_ARB* = 0x0000809D @@ -1026,7 +1026,7 @@ const GL_SAMPLE_COVERAGE_VALUE_ARB* = 0x000080AA GL_SAMPLE_COVERAGE_INVERT_ARB* = 0x000080AB -const +const GL_NORMAL_MAP_ARB* = 0x00008511 GL_REFLECTION_MAP_ARB* = 0x00008512 GL_TEXTURE_CUBE_MAP_ARB* = 0x00008513 @@ -1040,7 +1040,7 @@ const GL_PROXY_TEXTURE_CUBE_MAP_ARB* = 0x0000851B GL_MAX_CUBE_MAP_TEXTURE_SIZE_ARB* = 0x0000851C -const +const GL_DEPTH_COMPONENT16_ARB* = 0x000081A5 GL_DEPTH_COMPONENT24_ARB* = 0x000081A6 GL_DEPTH_COMPONENT32_ARB* = 0x000081A7 @@ -1048,26 +1048,26 @@ const GL_DEPTH_TEXTURE_MODE_ARB* = 0x0000884B #***** GL_ARB_point_parameters *****// -const +const GL_POINT_SIZE_MIN_ARB* = 0x00008126 GL_POINT_SIZE_MAX_ARB* = 0x00008127 GL_POINT_FADE_THRESHOLD_SIZE_ARB* = 0x00008128 GL_POINT_DISTANCE_ATTENUATION_ARB* = 0x00008129 -proc glPointParameterfARB*(pname: TGLenum, param: TGLfloat){.dynlib: dllname, +proc glPointParameterfARB*(pname: TGLenum, param: TGLfloat){.dynlib: dllname, importc: "glPointParameterfARB".} -proc glPointParameterfvARB*(pname: TGLenum, params: PGLfloat){.dynlib: dllname, +proc glPointParameterfvARB*(pname: TGLenum, params: PGLfloat){.dynlib: dllname, importc: "glPointParameterfvARB".} -const +const GL_TEXTURE_COMPARE_MODE_ARB* = 0x0000884C GL_TEXTURE_COMPARE_FUNC_ARB* = 0x0000884D GL_COMPARE_R_TO_TEXTURE_ARB* = 0x0000884E -const +const GL_TEXTURE_COMPARE_FAIL_VALUE_ARB* = 0x000080BF GL_CLAMP_TO_BORDER_ARB* = 0x0000812D -const +const GL_COMPRESSED_ALPHA_ARB* = 0x000084E9 GL_COMPRESSED_LUMINANCE_ARB* = 0x000084EA GL_COMPRESSED_LUMINANCE_ALPHA_ARB* = 0x000084EB @@ -1080,44 +1080,44 @@ const GL_NUM_COMPRESSED_TEXTURE_FORMATS_ARB* = 0x000086A2 GL_COMPRESSED_TEXTURE_FORMATS_ARB* = 0x000086A3 -proc glCompressedTexImage3DARB*(target: TGLenum, level: TGLint, - internalformat: TGLenum, width: TGLsizei, - height: TGLsizei, depth: TGLsizei, - border: TGLint, imageSize: TGLsizei, - data: PGLvoid){.dynlib: dllname, +proc glCompressedTexImage3DARB*(target: TGLenum, level: TGLint, + internalformat: TGLenum, width: TGLsizei, + height: TGLsizei, depth: TGLsizei, + border: TGLint, imageSize: TGLsizei, + data: PGLvoid){.dynlib: dllname, importc: "glCompressedTexImage3DARB".} -proc glCompressedTexImage2DARB*(target: TGLenum, level: TGLint, - internalformat: TGLenum, width: TGLsizei, - height: TGLsizei, border: TGLint, +proc glCompressedTexImage2DARB*(target: TGLenum, level: TGLint, + internalformat: TGLenum, width: TGLsizei, + height: TGLsizei, border: TGLint, imageSize: TGLsizei, data: PGLvoid){. dynlib: dllname, importc: "glCompressedTexImage2DARB".} -proc glCompressedTexImage1DARB*(target: TGLenum, level: TGLint, - internalformat: TGLenum, width: TGLsizei, - border: TGLint, imageSize: TGLsizei, - data: PGLvoid){.dynlib: dllname, +proc glCompressedTexImage1DARB*(target: TGLenum, level: TGLint, + internalformat: TGLenum, width: TGLsizei, + border: TGLint, imageSize: TGLsizei, + data: PGLvoid){.dynlib: dllname, importc: "glCompressedTexImage1DARB".} -proc glCompressedTexSubImage3DARB*(target: TGLenum, level: TGLint, - xoffset: TGLint, yoffset: TGLint, - zoffset: TGLint, width: TGLsizei, - height: TGLsizei, depth: TGLsizei, - format: TGLenum, imageSize: TGLsizei, - data: PGLvoid){.dynlib: dllname, +proc glCompressedTexSubImage3DARB*(target: TGLenum, level: TGLint, + xoffset: TGLint, yoffset: TGLint, + zoffset: TGLint, width: TGLsizei, + height: TGLsizei, depth: TGLsizei, + format: TGLenum, imageSize: TGLsizei, + data: PGLvoid){.dynlib: dllname, importc: "glCompressedTexSubImage3DARB".} -proc glCompressedTexSubImage2DARB*(target: TGLenum, level: TGLint, - xoffset: TGLint, yoffset: TGLint, - width: TGLsizei, height: TGLsizei, - format: TGLenum, imageSize: TGLsizei, - data: PGLvoid){.dynlib: dllname, +proc glCompressedTexSubImage2DARB*(target: TGLenum, level: TGLint, + xoffset: TGLint, yoffset: TGLint, + width: TGLsizei, height: TGLsizei, + format: TGLenum, imageSize: TGLsizei, + data: PGLvoid){.dynlib: dllname, importc: "glCompressedTexSubImage2DARB".} -proc glCompressedTexSubImage1DARB*(target: TGLenum, level: TGLint, - xoffset: TGLint, width: TGLsizei, - format: TGLenum, imageSize: TGLsizei, - data: PGLvoid){.dynlib: dllname, +proc glCompressedTexSubImage1DARB*(target: TGLenum, level: TGLint, + xoffset: TGLint, width: TGLsizei, + format: TGLenum, imageSize: TGLsizei, + data: PGLvoid){.dynlib: dllname, importc: "glCompressedTexSubImage1DARB".} proc glGetCompressedTexImageARB*(target: TGLenum, lod: TGLint, img: PGLvoid){. dynlib: dllname, importc: "glGetCompressedTexImageARB".} #***** GL_ARB_texture_env_combine *****// -const +const GL_COMBINE_ARB* = 0x00008570 GL_COMBINE_RGB_ARB* = 0x00008571 GL_COMBINE_ALPHA_ARB* = 0x00008572 @@ -1143,16 +1143,16 @@ const #***** GL_ARB_texture_env_crossbar *****// #***** GL_ARB_texture_env_dot3 *****// -const +const GL_DOT3_RGB_ARB* = 0x000086AE GL_DOT3_RGBA_ARB* = 0x000086AF #***** GL_ARB_texture_mirrored_repeat *****// -const +const GL_MIRRORED_REPEAT_ARB* = 0x00008370 #***** GL_ARB_vertex_blend *****// -const +const GL_MAX_VERTEX_UNITS_ARB* = 0x000086A4 GL_ACTIVE_VERTEX_UNITS_ARB* = 0x000086A5 GL_WEIGHT_SUM_UNITY_ARB* = 0x000086A6 @@ -1196,7 +1196,7 @@ const GL_WEIGHT_ARRAY_POINTER_ARB* = 0x000086AC GL_WEIGHT_ARRAY_ARB* = 0x000086AD -const +const GL_VERTEX_PROGRAM_ARB* = 0x00008620 GL_VERTEX_PROGRAM_POINT_SIZE_ARB* = 0x00008642 GL_VERTEX_PROGRAM_TWO_SIDE_ARB* = 0x00008643 @@ -1277,78 +1277,78 @@ const GL_MATRIX30_ARB* = 0x000088DE GL_MATRIX31_ARB* = 0x000088DF -const +const GL_422_EXT* = 0x000080CC GL_422_REV_EXT* = 0x000080CD GL_422_AVERAGE_EXT* = 0x000080CE GL_422_REV_AVERAGE_EXT* = 0x000080CF #***** GL_EXT_abgr *****// -const +const GL_ABGR_EXT* = 0x00008000 #***** GL_EXT_bgra *****// -const +const GL_BGR_EXT* = 0x000080E0 GL_BGRA_EXT* = 0x000080E1 #***** GL_EXT_blend_color *****// -const +const GL_CONSTANT_COLOR_EXT* = 0x00008001 GL_ONE_MINUS_CONSTANT_COLOR_EXT* = 0x00008002 GL_CONSTANT_ALPHA_EXT* = 0x00008003 GL_ONE_MINUS_CONSTANT_ALPHA_EXT* = 0x00008004 constGL_BLEND_COLOR_EXT* = 0x00008005 -proc glBlendColorEXT*(red: TGLclampf, green: TGLclampf, blue: TGLclampf, - alpha: TGLclampf){.dynlib: dllname, +proc glBlendColorEXT*(red: TGLclampf, green: TGLclampf, blue: TGLclampf, + alpha: TGLclampf){.dynlib: dllname, importc: "glBlendColorEXT".} #***** GL_EXT_blend_func_separate *****// -const +const GL_BLEND_DST_RGB_EXT* = 0x000080C8 GL_BLEND_SRC_RGB_EXT* = 0x000080C9 GL_BLEND_DST_ALPHA_EXT* = 0x000080CA GL_BLEND_SRC_ALPHA_EXT* = 0x000080CB -proc glBlendFuncSeparateEXT*(sfactorRGB: TGLenum, dfactorRGB: TGLenum, +proc glBlendFuncSeparateEXT*(sfactorRGB: TGLenum, dfactorRGB: TGLenum, sfactorAlpha: TGLenum, dfactorAlpha: TGLenum){. dynlib: dllname, importc: "glBlendFuncSeparateEXT".} #***** GL_EXT_blend_logic_op *****// #***** GL_EXT_blend_minmax *****// -const +const GL_FUNC_ADD_EXT* = 0x00008006 GL_MIN_EXT* = 0x00008007 GL_MAX_EXT* = 0x00008008 constGL_BLEND_EQUATION_EXT* = 0x00008009 -proc glBlendEquationEXT*(mode: TGLenum){.dynlib: dllname, +proc glBlendEquationEXT*(mode: TGLenum){.dynlib: dllname, importc: "glBlendEquationEXT".} #***** GL_EXT_blend_subtract *****// -const +const GL_FUNC_SUBTRACT_EXT* = 0x0000800A GL_FUNC_REVERSE_SUBTRACT_EXT* = 0x0000800B #***** GL_EXT_clip_volume_hint *****// -const +const GL_CLIP_VOLUME_CLIPPING_HINT_EXT* = 0x000080F0 #***** GL_EXT_color_subtable *****// -proc glColorSubTableEXT*(target: TGLenum, start: TGLsizei, count: TGLsizei, +proc glColorSubTableEXT*(target: TGLenum, start: TGLsizei, count: TGLsizei, format: TGLenum, thetype: TGLenum, data: PGLvoid){. dynlib: dllname, importc: "glColorSubTableEXT".} -proc glCopyColorSubTableEXT*(target: TGLenum, start: TGLsizei, x: TGLint, - y: TGLint, width: TGLsizei){.dynlib: dllname, +proc glCopyColorSubTableEXT*(target: TGLenum, start: TGLsizei, x: TGLint, + y: TGLint, width: TGLsizei){.dynlib: dllname, importc: "glCopyColorSubTableEXT".} #***** GL_EXT_compiled_vertex_array *****// -const +const GL_ARRAY_ELEMENT_LOCK_FIRST_EXT* = 0x000081A8 GL_ARRAY_ELEMENT_LOCK_COUNT_EXT* = 0x000081A9 -proc glLockArraysEXT*(first: TGLint, count: TGLsizei){.dynlib: dllname, +proc glLockArraysEXT*(first: TGLint, count: TGLsizei){.dynlib: dllname, importc: "glLockArraysEXT".} proc glUnlockArraysEXT*(){.dynlib: dllname, importc: "glUnlockArraysEXT".} #***** GL_EXT_convolution *****// -const +const GL_CONVOLUTION_1D_EXT* = 0x00008010 GL_CONVOLUTION_2D_EXT* = 0x00008011 GL_SEPARABLE_2D_EXT* = 0x00008012 @@ -1370,51 +1370,51 @@ const GL_POST_CONVOLUTION_BLUE_BIAS_EXT* = 0x00008022 GL_POST_CONVOLUTION_ALPHA_BIAS_EXT* = 0x00008023 -proc glConvolutionFilter1DEXT*(target: TGLenum, internalformat: TGLenum, - width: TGLsizei, format: TGLenum, +proc glConvolutionFilter1DEXT*(target: TGLenum, internalformat: TGLenum, + width: TGLsizei, format: TGLenum, thetype: TGLenum, image: PGLvoid){. dynlib: dllname, importc: "glConvolutionFilter1DEXT".} -proc glConvolutionFilter2DEXT*(target: TGLenum, internalformat: TGLenum, - width: TGLsizei, height: TGLsizei, +proc glConvolutionFilter2DEXT*(target: TGLenum, internalformat: TGLenum, + width: TGLsizei, height: TGLsizei, format: TGLenum, thetype: TGLenum, image: PGLvoid){. dynlib: dllname, importc: "glConvolutionFilter2DEXT".} -proc glCopyConvolutionFilter1DEXT*(target: TGLenum, internalformat: TGLenum, +proc glCopyConvolutionFilter1DEXT*(target: TGLenum, internalformat: TGLenum, x: TGLint, y: TGLint, width: TGLsizei){. dynlib: dllname, importc: "glCopyConvolutionFilter1DEXT".} -proc glCopyConvolutionFilter2DEXT*(target: TGLenum, internalformat: TGLenum, - x: TGLint, y: TGLint, width: TGLsizei, - height: TGLsizei){.dynlib: dllname, +proc glCopyConvolutionFilter2DEXT*(target: TGLenum, internalformat: TGLenum, + x: TGLint, y: TGLint, width: TGLsizei, + height: TGLsizei){.dynlib: dllname, importc: "glCopyConvolutionFilter2DEXT".} -proc glGetConvolutionFilterEXT*(target: TGLenum, format: TGLenum, +proc glGetConvolutionFilterEXT*(target: TGLenum, format: TGLenum, thetype: TGLenum, image: PGLvoid){. dynlib: dllname, importc: "glGetConvolutionFilterEXT".} -proc glSeparableFilter2DEXT*(target: TGLenum, internalformat: TGLenum, - width: TGLsizei, height: TGLsizei, format: TGLenum, +proc glSeparableFilter2DEXT*(target: TGLenum, internalformat: TGLenum, + width: TGLsizei, height: TGLsizei, format: TGLenum, thetype: TGLenum, row: PGLvoid, column: PGLvoid){. dynlib: dllname, importc: "glSeparableFilter2DEXT".} -proc glGetSeparableFilterEXT*(target: TGLenum, format: TGLenum, - thetype: TGLenum, row: PGLvoid, column: PGLvoid, - span: PGLvoid){.dynlib: dllname, +proc glGetSeparableFilterEXT*(target: TGLenum, format: TGLenum, + thetype: TGLenum, row: PGLvoid, column: PGLvoid, + span: PGLvoid){.dynlib: dllname, importc: "glGetSeparableFilterEXT".} proc glConvolutionParameteriEXT*(target: TGLenum, pname: TGLenum, param: TGLint){. dynlib: dllname, importc: "glConvolutionParameteriEXT".} -proc glConvolutionParameterivEXT*(target: TGLenum, pname: TGLenum, - params: PGLint){.dynlib: dllname, +proc glConvolutionParameterivEXT*(target: TGLenum, pname: TGLenum, + params: PGLint){.dynlib: dllname, importc: "glConvolutionParameterivEXT".} -proc glConvolutionParameterfEXT*(target: TGLenum, pname: TGLenum, - param: TGLfloat){.dynlib: dllname, +proc glConvolutionParameterfEXT*(target: TGLenum, pname: TGLenum, + param: TGLfloat){.dynlib: dllname, importc: "glConvolutionParameterfEXT".} -proc glConvolutionParameterfvEXT*(target: TGLenum, pname: TGLenum, - params: PGLfloat){.dynlib: dllname, +proc glConvolutionParameterfvEXT*(target: TGLenum, pname: TGLenum, + params: PGLfloat){.dynlib: dllname, importc: "glConvolutionParameterfvEXT".} -proc glGetConvolutionParameterivEXT*(target: TGLenum, pname: TGLenum, - params: PGLint){.dynlib: dllname, +proc glGetConvolutionParameterivEXT*(target: TGLenum, pname: TGLenum, + params: PGLint){.dynlib: dllname, importc: "glGetConvolutionParameterivEXT".} -proc glGetConvolutionParameterfvEXT*(target: TGLenum, pname: TGLenum, - params: PGLfloat){.dynlib: dllname, +proc glGetConvolutionParameterfvEXT*(target: TGLenum, pname: TGLenum, + params: PGLfloat){.dynlib: dllname, importc: "glGetConvolutionParameterfvEXT".} #***** GL_EXT_fog_coord *****// -const +const GL_FOG_COORDINATE_SOURCE_EXT* = 0x00008450 GL_FOG_COORDINATE_EXT* = 0x00008451 GL_FRAGMENT_DEPTH_EXT* = 0x00008452 @@ -1424,18 +1424,18 @@ const GL_FOG_COORDINATE_ARRAY_POINTER_EXT* = 0x00008456 GL_FOG_COORDINATE_ARRAY_EXT* = 0x00008457 -proc glFogCoordfEXfloat*(coord: TGLfloat){.dynlib: dllname, +proc glFogCoordfEXfloat*(coord: TGLfloat){.dynlib: dllname, importc: "glFogCoordfEXfloat".} -proc glFogCoorddEXdouble*(coord: TGLdouble){.dynlib: dllname, +proc glFogCoorddEXdouble*(coord: TGLdouble){.dynlib: dllname, importc: "glFogCoorddEXdouble".} -proc glFogCoordfvEXfloat*(coord: TGLfloat){.dynlib: dllname, +proc glFogCoordfvEXfloat*(coord: TGLfloat){.dynlib: dllname, importc: "glFogCoordfvEXfloat".} -proc glFogCoorddvEXdouble*(coord: TGLdouble){.dynlib: dllname, +proc glFogCoorddvEXdouble*(coord: TGLdouble){.dynlib: dllname, importc: "glFogCoorddvEXdouble".} proc glFogCoordPointerEXT*(thetype: TGLenum, stride: TGLsizei, pointer: PGLvoid){. dynlib: dllname, importc: "glFogCoordPointerEXT".} #***** GL_EXT_histogram *****// -const +const constGL_HISTOGRAM_EXT* = 0x00008024 GL_PROXY_HISTOGRAM_EXT* = 0x00008025 GL_HISTOGRAM_WIDTH_EXT* = 0x00008026 @@ -1450,41 +1450,41 @@ const GL_MINMAX_FORMAT_EXT* = 0x0000802F GL_MINMAX_SINK_EXT* = 0x00008030 -proc glHistogramEXT*(target: TGLenum, width: TGLsizei, internalformat: TGLenum, - sink: TGLboolean){.dynlib: dllname, +proc glHistogramEXT*(target: TGLenum, width: TGLsizei, internalformat: TGLenum, + sink: TGLboolean){.dynlib: dllname, importc: "glHistogramEXT".} -proc glResetHistogramEXT*(target: TGLenum){.dynlib: dllname, +proc glResetHistogramEXT*(target: TGLenum){.dynlib: dllname, importc: "glResetHistogramEXT".} -proc glGetHistogramEXT*(target: TGLenum, reset: TGLboolean, format: TGLenum, - thetype: TGLenum, values: PGLvoid){.dynlib: dllname, +proc glGetHistogramEXT*(target: TGLenum, reset: TGLboolean, format: TGLenum, + thetype: TGLenum, values: PGLvoid){.dynlib: dllname, importc: "glGetHistogramEXT".} -proc glGetHistogramParameterivEXT*(target: TGLenum, pname: TGLenum, - params: PGLint){.dynlib: dllname, +proc glGetHistogramParameterivEXT*(target: TGLenum, pname: TGLenum, + params: PGLint){.dynlib: dllname, importc: "glGetHistogramParameterivEXT".} -proc glGetHistogramParameterfvEXT*(target: TGLenum, pname: TGLenum, - params: PGLfloat){.dynlib: dllname, +proc glGetHistogramParameterfvEXT*(target: TGLenum, pname: TGLenum, + params: PGLfloat){.dynlib: dllname, importc: "glGetHistogramParameterfvEXT".} proc glMinmaxEXT*(target: TGLenum, internalformat: TGLenum, sink: TGLboolean){. dynlib: dllname, importc: "glMinmaxEXT".} -proc glResetMinmaxEXT*(target: TGLenum){.dynlib: dllname, +proc glResetMinmaxEXT*(target: TGLenum){.dynlib: dllname, importc: "glResetMinmaxEXT".} -proc glGetMinmaxEXT*(target: TGLenum, reset: TGLboolean, format: TGLenum, - thetype: TGLenum, values: PGLvoid){.dynlib: dllname, +proc glGetMinmaxEXT*(target: TGLenum, reset: TGLboolean, format: TGLenum, + thetype: TGLenum, values: PGLvoid){.dynlib: dllname, importc: "glGetMinmaxEXT".} proc glGetMinmaxParameterivEXT*(target: TGLenum, pname: TGLenum, params: PGLint){. dynlib: dllname, importc: "glGetMinmaxParameterivEXT".} -proc glGetMinmaxParameterfvEXT*(target: TGLenum, pname: TGLenum, - params: PGLfloat){.dynlib: dllname, +proc glGetMinmaxParameterfvEXT*(target: TGLenum, pname: TGLenum, + params: PGLfloat){.dynlib: dllname, importc: "glGetMinmaxParameterfvEXT".} #***** GL_EXT_multi_draw_arrays *****// -proc glMultiDrawArraysEXT*(mode: TGLenum, first: PGLint, count: PGLsizei, - primcount: TGLsizei){.dynlib: dllname, +proc glMultiDrawArraysEXT*(mode: TGLenum, first: PGLint, count: PGLsizei, + primcount: TGLsizei){.dynlib: dllname, importc: "glMultiDrawArraysEXT".} -proc glMultiDrawElementsEXT*(mode: TGLenum, count: PGLsizei, thetype: TGLenum, +proc glMultiDrawElementsEXT*(mode: TGLenum, count: PGLsizei, thetype: TGLenum, indices: PGLvoid, primcount: TGLsizei){. dynlib: dllname, importc: "glMultiDrawElementsEXT".} #***** GL_EXT_packed_pixels *****// -const +const GL_UNSIGNED_BYTE_3_3_2_EXT* = 0x00008032 GL_UNSIGNED_SHORT_4_4_4_4_EXT* = 0x00008033 GL_UNSIGNED_SHORT_5_5_5_1_EXT* = 0x00008034 @@ -1492,7 +1492,7 @@ const GL_UNSIGNED_INT_10_10_10_2_EXT* = 0x00008036 #***** GL_EXT_paletted_texture *****// -const +const GL_COLOR_INDEX1_EXT* = 0x000080E2 GL_COLOR_INDEX2_EXT* = 0x000080E3 GL_COLOR_INDEX4_EXT* = 0x000080E4 @@ -1519,40 +1519,40 @@ const # GL_TEXTURE_3D_EXT { already defined } # GL_TEXTURE_CUBE_MAP_ARB { already defined } -proc glColorTableEXT*(target: TGLenum, internalFormat: TGLenum, width: TGLsizei, +proc glColorTableEXT*(target: TGLenum, internalFormat: TGLenum, width: TGLsizei, format: TGLenum, thetype: TGLenum, data: PGLvoid){. dynlib: dllname, importc: "glColorTableEXT".} # glColorSubTableEXT { already defined } -proc glGetColorTableEXT*(target: TGLenum, format: TGLenum, thetype: TGLenum, - data: PGLvoid){.dynlib: dllname, +proc glGetColorTableEXT*(target: TGLenum, format: TGLenum, thetype: TGLenum, + data: PGLvoid){.dynlib: dllname, importc: "glGetColorTableEXT".} -proc glGetColorTableParameterivEXT*(target: TGLenum, pname: TGLenum, - params: PGLint){.dynlib: dllname, +proc glGetColorTableParameterivEXT*(target: TGLenum, pname: TGLenum, + params: PGLint){.dynlib: dllname, importc: "glGetColorTableParameterivEXT".} -proc glGetColorTableParameterfvEXT*(target: TGLenum, pname: TGLenum, - params: PGLfloat){.dynlib: dllname, +proc glGetColorTableParameterfvEXT*(target: TGLenum, pname: TGLenum, + params: PGLfloat){.dynlib: dllname, importc: "glGetColorTableParameterfvEXT".} #***** GL_EXT_point_parameters *****// -const +const GL_POINT_SIZE_MIN_EXT* = 0x00008126 GL_POINT_SIZE_MAX_EXT* = 0x00008127 GL_POINT_FADE_THRESHOLD_SIZE_EXT* = 0x00008128 GL_DISTANCE_ATTENUATION_EXT* = 0x00008129 -proc glPointParameterfEXT*(pname: TGLenum, param: TGLfloat){.dynlib: dllname, +proc glPointParameterfEXT*(pname: TGLenum, param: TGLfloat){.dynlib: dllname, importc: "glPointParameterfEXT".} -proc glPointParameterfvEXT*(pname: TGLenum, params: PGLfloat){.dynlib: dllname, +proc glPointParameterfvEXT*(pname: TGLenum, params: PGLfloat){.dynlib: dllname, importc: "glPointParameterfvEXT".} #***** GL_EXT_polygon_offset *****// -const +const constGL_POLYGON_OFFSET_EXT* = 0x00008037 GL_POLYGON_OFFSET_FACTOR_EXT* = 0x00008038 GL_POLYGON_OFFSET_BIAS_EXT* = 0x00008039 -proc glPolygonOffsetEXT*(factor: TGLfloat, bias: TGLfloat){.dynlib: dllname, +proc glPolygonOffsetEXT*(factor: TGLfloat, bias: TGLfloat){.dynlib: dllname, importc: "glPolygonOffsetEXT".} #***** GL_EXT_secondary_color *****// -const +const GL_COLOR_SUM_EXT* = 0x00008458 GL_CURRENT_SECONDARY_COLOR_EXT* = 0x00008459 GL_SECONDARY_COLOR_ARRAY_SIZE_EXT* = 0x0000845A @@ -1561,80 +1561,80 @@ const GL_SECONDARY_COLOR_ARRAY_POINTER_EXT* = 0x0000845D GL_SECONDARY_COLOR_ARRAY_EXT* = 0x0000845E -proc glSecondaryColor3bEXT*(components: TGLbyte){.dynlib: dllname, +proc glSecondaryColor3bEXT*(components: TGLbyte){.dynlib: dllname, importc: "glSecondaryColor3bEXT".} -proc glSecondaryColor3sEXT*(components: TGLshort){.dynlib: dllname, +proc glSecondaryColor3sEXT*(components: TGLshort){.dynlib: dllname, importc: "glSecondaryColor3sEXT".} -proc glSecondaryColor3iEXT*(components: TGLint){.dynlib: dllname, +proc glSecondaryColor3iEXT*(components: TGLint){.dynlib: dllname, importc: "glSecondaryColor3iEXT".} -proc glSecondaryColor3fEXT*(components: TGLfloat){.dynlib: dllname, +proc glSecondaryColor3fEXT*(components: TGLfloat){.dynlib: dllname, importc: "glSecondaryColor3fEXT".} -proc glSecondaryColor3dEXT*(components: TGLdouble){.dynlib: dllname, +proc glSecondaryColor3dEXT*(components: TGLdouble){.dynlib: dllname, importc: "glSecondaryColor3dEXT".} -proc glSecondaryColor3ubEXT*(components: TGLubyte){.dynlib: dllname, +proc glSecondaryColor3ubEXT*(components: TGLubyte){.dynlib: dllname, importc: "glSecondaryColor3ubEXT".} -proc glSecondaryColor3usEXT*(components: TGLushort){.dynlib: dllname, +proc glSecondaryColor3usEXT*(components: TGLushort){.dynlib: dllname, importc: "glSecondaryColor3usEXT".} -proc glSecondaryColor3uiEXT*(components: TGLuint){.dynlib: dllname, +proc glSecondaryColor3uiEXT*(components: TGLuint){.dynlib: dllname, importc: "glSecondaryColor3uiEXT".} -proc glSecondaryColor3bvEXT*(components: TGLbyte){.dynlib: dllname, +proc glSecondaryColor3bvEXT*(components: TGLbyte){.dynlib: dllname, importc: "glSecondaryColor3bvEXT".} -proc glSecondaryColor3svEXT*(components: TGLshort){.dynlib: dllname, +proc glSecondaryColor3svEXT*(components: TGLshort){.dynlib: dllname, importc: "glSecondaryColor3svEXT".} -proc glSecondaryColor3ivEXT*(components: TGLint){.dynlib: dllname, +proc glSecondaryColor3ivEXT*(components: TGLint){.dynlib: dllname, importc: "glSecondaryColor3ivEXT".} -proc glSecondaryColor3fvEXT*(components: TGLfloat){.dynlib: dllname, +proc glSecondaryColor3fvEXT*(components: TGLfloat){.dynlib: dllname, importc: "glSecondaryColor3fvEXT".} -proc glSecondaryColor3dvEXT*(components: TGLdouble){.dynlib: dllname, +proc glSecondaryColor3dvEXT*(components: TGLdouble){.dynlib: dllname, importc: "glSecondaryColor3dvEXT".} -proc glSecondaryColor3ubvEXT*(components: TGLubyte){.dynlib: dllname, +proc glSecondaryColor3ubvEXT*(components: TGLubyte){.dynlib: dllname, importc: "glSecondaryColor3ubvEXT".} -proc glSecondaryColor3usvEXT*(components: TGLushort){.dynlib: dllname, +proc glSecondaryColor3usvEXT*(components: TGLushort){.dynlib: dllname, importc: "glSecondaryColor3usvEXT".} -proc glSecondaryColor3uivEXT*(components: TGLuint){.dynlib: dllname, +proc glSecondaryColor3uivEXT*(components: TGLuint){.dynlib: dllname, importc: "glSecondaryColor3uivEXT".} -proc glSecondaryColorPointerEXT*(size: TGLint, thetype: TGLenum, +proc glSecondaryColorPointerEXT*(size: TGLint, thetype: TGLenum, stride: TGLsizei, pointer: PGLvoid){. dynlib: dllname, importc: "glSecondaryColorPointerEXT".} #***** GL_EXT_separate_specular_color *****// -const +const GL_LIGHT_MODEL_COLOR_CONTROL_EXT* = 0x000081F8 GL_SINGLE_COLOR_EXT* = 0x000081F9 GL_SEPARATE_SPECULAR_COLOR_EXT* = 0x000081FA #***** GL_EXT_shadow_funcs *****// #***** GL_EXT_shared_texture_palette *****// -const +const GL_SHARED_TEXTURE_PALETTE_EXT* = 0x000081FB #***** GL_EXT_stencil_two_side *****// -const +const GL_STENCIL_TEST_TWO_SIDE_EXT* = 0x00008910 constGL_ACTIVE_STENCIL_FACE_EXT* = 0x00008911 -proc glActiveStencilFaceEXT*(face: TGLenum){.dynlib: dllname, +proc glActiveStencilFaceEXT*(face: TGLenum){.dynlib: dllname, importc: "glActiveStencilFaceEXT".} #***** GL_EXT_stencil_wrap *****// -const +const GL_INCR_WRAP_EXT* = 0x00008507 GL_DECR_WRAP_EXT* = 0x00008508 #***** GL_EXT_subtexture *****// -proc glTexSubImage1DEXT*(target: TGLenum, level: TGLint, xoffset: TGLint, - width: TGLsizei, format: TGLenum, thetype: TGLenum, - pixels: PGLvoid){.dynlib: dllname, +proc glTexSubImage1DEXT*(target: TGLenum, level: TGLint, xoffset: TGLint, + width: TGLsizei, format: TGLenum, thetype: TGLenum, + pixels: PGLvoid){.dynlib: dllname, importc: "glTexSubImage1DEXT".} -proc glTexSubImage2DEXT*(target: TGLenum, level: TGLint, xoffset: TGLint, - yoffset: TGLint, width: TGLsizei, height: TGLsizei, +proc glTexSubImage2DEXT*(target: TGLenum, level: TGLint, xoffset: TGLint, + yoffset: TGLint, width: TGLsizei, height: TGLsizei, format: TGLenum, thetype: TGLenum, pixels: PGLvoid){. dynlib: dllname, importc: "glTexSubImage2DEXT".} -proc glTexSubImage3DEXT*(target: TGLenum, level: TGLint, xoffset: TGLint, - yoffset: TGLint, zoffset: TGLint, width: TGLsizei, - height: TGLsizei, depth: TGLsizei, format: TGLenum, - thetype: TGLenum, pixels: PGLvoid){.dynlib: dllname, +proc glTexSubImage3DEXT*(target: TGLenum, level: TGLint, xoffset: TGLint, + yoffset: TGLint, zoffset: TGLint, width: TGLsizei, + height: TGLsizei, depth: TGLsizei, format: TGLenum, + thetype: TGLenum, pixels: PGLvoid){.dynlib: dllname, importc: "glTexSubImage3DEXT".} #***** GL_EXT_texture3D *****// -const +const GL_PACK_SKIP_IMAGES_EXT* = 0x0000806B GL_PACK_IMAGE_HEIGHT_EXT* = 0x0000806C GL_UNPACK_SKIP_IMAGES_EXT* = 0x0000806D @@ -1644,13 +1644,13 @@ const GL_TEXTURE_WRAP_R_EXT* = 0x00008072 GL_MAX_3D_TEXTURE_SIZE_EXT* = 0x00008073 -proc glTexImage3DEXT*(target: TGLenum, level: TGLint, internalformat: TGLenum, - width: TGLsizei, height: TGLsizei, depth: TGLsizei, - border: TGLint, format: TGLenum, thetype: TGLenum, - pixels: PGLvoid){.dynlib: dllname, +proc glTexImage3DEXT*(target: TGLenum, level: TGLint, internalformat: TGLenum, + width: TGLsizei, height: TGLsizei, depth: TGLsizei, + border: TGLint, format: TGLenum, thetype: TGLenum, + pixels: PGLvoid){.dynlib: dllname, importc: "glTexImage3DEXT".} #***** GL_EXT_texture_compression_s3tc *****// -const +const GL_COMPRESSED_RGB_S3TC_DXT1_EXT* = 0x000083F0 GL_COMPRESSED_RGBA_S3TC_DXT1_EXT* = 0x000083F1 GL_COMPRESSED_RGBA_S3TC_DXT3_EXT* = 0x000083F2 @@ -1658,7 +1658,7 @@ const #***** GL_EXT_texture_env_add *****// #***** GL_EXT_texture_env_combine *****// -const +const GL_COMBINE_EXT* = 0x00008570 GL_COMBINE_RGB_EXT* = 0x00008571 GL_COMBINE_ALPHA_EXT* = 0x00008572 @@ -1682,45 +1682,45 @@ const GL_PREVIOUS_EXT* = 0x00008578 #***** GL_EXT_texture_env_dot3 *****// -const +const GL_DOT3_RGB_EXT* = 0x00008740 GL_DOT3_RGBA_EXT* = 0x00008741 #***** GL_EXT_texture_filter_anisotropic *****// -const +const GL_TEXTURE_MAX_ANISOTROPY_EXT* = 0x000084FE GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT* = 0x000084FF #***** GL_EXT_texture_lod_bias *****// -const +const GL_TEXTURE_FILTER_CONTROL_EXT* = 0x00008500 GL_TEXTURE_LOD_BIAS_EXT* = 0x00008501 GL_MAX_TEXTURE_LOD_BIAS_EXT* = 0x000084FD #***** GL_EXT_texture_object *****// -const +const GL_TEXTURE_PRIORITY_EXT* = 0x00008066 GL_TEXTURE_RESIDENT_EXT* = 0x00008067 GL_TEXTURE_1D_BINDING_EXT* = 0x00008068 GL_TEXTURE_2D_BINDING_EXT* = 0x00008069 GL_TEXTURE_3D_BINDING_EXT* = 0x0000806A -proc glGenTexturesEXT*(n: TGLsizei, textures: PGLuint){.dynlib: dllname, +proc glGenTexturesEXT*(n: TGLsizei, textures: PGLuint){.dynlib: dllname, importc: "glGenTexturesEXT".} -proc glDeleteTexturesEXT*(n: TGLsizei, textures: PGLuint){.dynlib: dllname, +proc glDeleteTexturesEXT*(n: TGLsizei, textures: PGLuint){.dynlib: dllname, importc: "glDeleteTexturesEXT".} -proc glBindTextureEXT*(target: TGLenum, texture: TGLuint){.dynlib: dllname, +proc glBindTextureEXT*(target: TGLenum, texture: TGLuint){.dynlib: dllname, importc: "glBindTextureEXT".} -proc glPrioritizeTexturesEXT*(n: TGLsizei, textures: PGLuint, - priorities: PGLclampf){.dynlib: dllname, +proc glPrioritizeTexturesEXT*(n: TGLsizei, textures: PGLuint, + priorities: PGLclampf){.dynlib: dllname, importc: "glPrioritizeTexturesEXT".} -proc glAreTexturesResidentEXT*(n: TGLsizei, textures: PGLuint, +proc glAreTexturesResidentEXT*(n: TGLsizei, textures: PGLuint, residences: PGLboolean): TGLboolean{. dynlib: dllname, importc: "glAreTexturesResidentEXT".} -proc glIsTextureEXT*(texture: TGLuint): TGLboolean{.dynlib: dllname, +proc glIsTextureEXT*(texture: TGLuint): TGLboolean{.dynlib: dllname, importc: "glIsTextureEXT".} #***** GL_EXT_vertex_array *****// -const +const GL_VERTEX_ARRAY_EXT* = 0x00008074 GL_NORMAL_ARRAY_EXT* = 0x00008075 GL_COLOR_ARRAY_EXT* = 0x00008076 @@ -1755,32 +1755,32 @@ const GL_TEXTURE_COORD_ARRAY_POINTER_EXT* = 0x00008092 GL_EDGE_FLAG_ARRAY_POINTER_EXT* = 0x00008093 -proc glArrayElementEXT*(i: TGLint){.dynlib: dllname, +proc glArrayElementEXT*(i: TGLint){.dynlib: dllname, importc: "glArrayElementEXT".} proc glDrawArraysEXT*(mode: TGLenum, first: TGLint, count: TGLsizei){. dynlib: dllname, importc: "glDrawArraysEXT".} -proc glVertexPointerEXT*(size: TGLint, thetype: TGLenum, stride: TGLsizei, - count: TGLsizei, pointer: PGLvoid){.dynlib: dllname, +proc glVertexPointerEXT*(size: TGLint, thetype: TGLenum, stride: TGLsizei, + count: TGLsizei, pointer: PGLvoid){.dynlib: dllname, importc: "glVertexPointerEXT".} -proc glNormalPointerEXT*(thetype: TGLenum, stride: TGLsizei, count: TGLsizei, - pointer: PGLvoid){.dynlib: dllname, +proc glNormalPointerEXT*(thetype: TGLenum, stride: TGLsizei, count: TGLsizei, + pointer: PGLvoid){.dynlib: dllname, importc: "glNormalPointerEXT".} -proc glColorPointerEXT*(size: TGLint, thetype: TGLenum, stride: TGLsizei, - count: TGLsizei, pointer: PGLvoid){.dynlib: dllname, +proc glColorPointerEXT*(size: TGLint, thetype: TGLenum, stride: TGLsizei, + count: TGLsizei, pointer: PGLvoid){.dynlib: dllname, importc: "glColorPointerEXT".} -proc glIndexPointerEXT*(thetype: TGLenum, stride: TGLsizei, count: TGLsizei, - pointer: PGLvoid){.dynlib: dllname, +proc glIndexPointerEXT*(thetype: TGLenum, stride: TGLsizei, count: TGLsizei, + pointer: PGLvoid){.dynlib: dllname, importc: "glIndexPointerEXT".} -proc glTexCoordPointerEXT*(size: TGLint, thetype: TGLenum, stride: TGLsizei, - count: TGLsizei, pointer: PGLvoid){.dynlib: dllname, +proc glTexCoordPointerEXT*(size: TGLint, thetype: TGLenum, stride: TGLsizei, + count: TGLsizei, pointer: PGLvoid){.dynlib: dllname, importc: "glTexCoordPointerEXT".} -proc glEdgeFlagPointerEXT*(stride: TGLsizei, count: TGLsizei, - pointer: PGLboolean){.dynlib: dllname, +proc glEdgeFlagPointerEXT*(stride: TGLsizei, count: TGLsizei, + pointer: PGLboolean){.dynlib: dllname, importc: "glEdgeFlagPointerEXT".} -proc glGetPointervEXT*(pname: TGLenum, params: PGLvoid){.dynlib: dllname, +proc glGetPointervEXT*(pname: TGLenum, params: PGLvoid){.dynlib: dllname, importc: "glGetPointervEXT".} #***** GL_EXT_vertex_shader *****// -const +const GL_VERTEX_SHADER_EXT* = 0x00008780 GL_VARIANT_VALUE_EXT* = 0x000087E4 GL_VARIANT_DATATYPE_EXT* = 0x000087E5 @@ -1892,60 +1892,60 @@ const GL_CURRENT_VERTEX_EXT* = 0x000087E2 GL_MVP_MATRIX_EXT* = 0x000087E3 -proc glBeginVertexShaderEXT*(){.dynlib: dllname, +proc glBeginVertexShaderEXT*(){.dynlib: dllname, importc: "glBeginVertexShaderEXT".} proc glEndVertexShaderEXT*(){.dynlib: dllname, importc: "glEndVertexShaderEXT".} -proc glBindVertexShaderEXT*(id: TGLuint){.dynlib: dllname, +proc glBindVertexShaderEXT*(id: TGLuint){.dynlib: dllname, importc: "glBindVertexShaderEXT".} -proc glGenVertexShadersEXT*(range: TGLuint): TGLuint{.dynlib: dllname, +proc glGenVertexShadersEXT*(range: TGLuint): TGLuint{.dynlib: dllname, importc: "glGenVertexShadersEXT".} -proc glDeleteVertexShaderEXT*(id: TGLuint){.dynlib: dllname, +proc glDeleteVertexShaderEXT*(id: TGLuint){.dynlib: dllname, importc: "glDeleteVertexShaderEXT".} -proc glShaderOp1EXT*(op: TGLenum, res: TGLuint, arg1: TGLuint){.dynlib: dllname, +proc glShaderOp1EXT*(op: TGLenum, res: TGLuint, arg1: TGLuint){.dynlib: dllname, importc: "glShaderOp1EXT".} proc glShaderOp2EXT*(op: TGLenum, res: TGLuint, arg1: TGLuint, arg2: TGLuint){. dynlib: dllname, importc: "glShaderOp2EXT".} -proc glShaderOp3EXT*(op: TGLenum, res: TGLuint, arg1: TGLuint, arg2: TGLuint, +proc glShaderOp3EXT*(op: TGLenum, res: TGLuint, arg1: TGLuint, arg2: TGLuint, arg3: TGLuint){.dynlib: dllname, importc: "glShaderOp3EXT".} -proc glSwizzleEXT*(res: TGLuint, theIn: TGLuint, outX: TGLenum, outY: TGLenum, - outZ: TGLenum, outW: TGLenum){.dynlib: dllname, +proc glSwizzleEXT*(res: TGLuint, theIn: TGLuint, outX: TGLenum, outY: TGLenum, + outZ: TGLenum, outW: TGLenum){.dynlib: dllname, importc: "glSwizzleEXT".} -proc glWriteMaskEXT*(res: TGLuint, theIn: TGLuint, outX: TGLenum, outY: TGLenum, - outZ: TGLenum, outW: TGLenum){.dynlib: dllname, +proc glWriteMaskEXT*(res: TGLuint, theIn: TGLuint, outX: TGLenum, outY: TGLenum, + outZ: TGLenum, outW: TGLenum){.dynlib: dllname, importc: "glWriteMaskEXT".} proc glInsertComponentEXT*(res: TGLuint, src: TGLuint, num: TGLuint){. dynlib: dllname, importc: "glInsertComponentEXT".} proc glExtractComponentEXT*(res: TGLuint, src: TGLuint, num: TGLuint){. dynlib: dllname, importc: "glExtractComponentEXT".} -proc glGenSymbolsEXT*(datatype: TGLenum, storagetype: TGLenum, range: TGLenum, - components: TGLuint): TGLuint{.dynlib: dllname, +proc glGenSymbolsEXT*(datatype: TGLenum, storagetype: TGLenum, range: TGLenum, + components: TGLuint): TGLuint{.dynlib: dllname, importc: "glGenSymbolsEXT".} proc glSetInvariantEXT*(id: TGLuint, thetype: TGLenum, address: PGLvoid){. dynlib: dllname, importc: "glSetInvariantEXT".} proc glSetLocalConstantEXT*(id: TGLuint, thetype: TGLenum, address: PGLvoid){. dynlib: dllname, importc: "glSetLocalConstantEXT".} -proc glVariantbvEXT*(id: TGLuint, address: PGLbyte){.dynlib: dllname, +proc glVariantbvEXT*(id: TGLuint, address: PGLbyte){.dynlib: dllname, importc: "glVariantbvEXT".} -proc glVariantsvEXT*(id: TGLuint, address: PGLshort){.dynlib: dllname, +proc glVariantsvEXT*(id: TGLuint, address: PGLshort){.dynlib: dllname, importc: "glVariantsvEXT".} -proc glVariantivEXT*(id: TGLuint, address: PGLint){.dynlib: dllname, +proc glVariantivEXT*(id: TGLuint, address: PGLint){.dynlib: dllname, importc: "glVariantivEXT".} -proc glVariantfvEXT*(id: TGLuint, address: PGLfloat){.dynlib: dllname, +proc glVariantfvEXT*(id: TGLuint, address: PGLfloat){.dynlib: dllname, importc: "glVariantfvEXT".} -proc glVariantdvEXT*(id: TGLuint, address: PGLdouble){.dynlib: dllname, +proc glVariantdvEXT*(id: TGLuint, address: PGLdouble){.dynlib: dllname, importc: "glVariantdvEXT".} -proc glVariantubvEXT*(id: TGLuint, address: PGLubyte){.dynlib: dllname, +proc glVariantubvEXT*(id: TGLuint, address: PGLubyte){.dynlib: dllname, importc: "glVariantubvEXT".} -proc glVariantusvEXT*(id: TGLuint, address: PGLushort){.dynlib: dllname, +proc glVariantusvEXT*(id: TGLuint, address: PGLushort){.dynlib: dllname, importc: "glVariantusvEXT".} -proc glVariantuivEXT*(id: TGLuint, address: PGLuint){.dynlib: dllname, +proc glVariantuivEXT*(id: TGLuint, address: PGLuint){.dynlib: dllname, importc: "glVariantuivEXT".} -proc glVariantPointerEXT*(id: TGLuint, thetype: TGLenum, stride: TGLuint, - address: PGLvoid){.dynlib: dllname, +proc glVariantPointerEXT*(id: TGLuint, thetype: TGLenum, stride: TGLuint, + address: PGLvoid){.dynlib: dllname, importc: "glVariantPointerEXT".} -proc glEnableVariantClientStateEXT*(id: TGLuint){.dynlib: dllname, +proc glEnableVariantClientStateEXT*(id: TGLuint){.dynlib: dllname, importc: "glEnableVariantClientStateEXT".} -proc glDisableVariantClientStateEXT*(id: TGLuint){.dynlib: dllname, +proc glDisableVariantClientStateEXT*(id: TGLuint){.dynlib: dllname, importc: "glDisableVariantClientStateEXT".} proc glBindLightParameterEXT*(light: TGLenum, value: TGLenum): TGLuint{. dynlib: dllname, importc: "glBindLightParameterEXT".} @@ -1955,7 +1955,7 @@ proc glBindTexGenParameterEXT*(theunit: TGLenum, coord: TGLenum, value: TGLenum) dynlib: dllname, importc: "glBindTexGenParameterEXT".} proc glBindTextureUnitParameterEXT*(theunit: TGLenum, value: TGLenum): TGLuint{. dynlib: dllname, importc: "glBindTextureUnitParameterEXT".} -proc glBindParameterEXT*(value: TGLenum): TGLuint{.dynlib: dllname, +proc glBindParameterEXT*(value: TGLenum): TGLuint{.dynlib: dllname, importc: "glBindParameterEXT".} proc glIsVariantEnabledEXT*(id: TGLuint, cap: TGLenum): TGLboolean{. dynlib: dllname, importc: "glIsVariantEnabledEXT".} @@ -1973,15 +1973,15 @@ proc glGetInvariantIntegervEXT*(id: TGLuint, value: TGLenum, data: PGLint){. dynlib: dllname, importc: "glGetInvariantIntegervEXT".} proc glGetInvariantFloatvEXT*(id: TGLuint, value: TGLenum, data: PGLfloat){. dynlib: dllname, importc: "glGetInvariantFloatvEXT".} -proc glGetLocalConstantBooleanvEXT*(id: TGLuint, value: TGLenum, - data: PGLboolean){.dynlib: dllname, +proc glGetLocalConstantBooleanvEXT*(id: TGLuint, value: TGLenum, + data: PGLboolean){.dynlib: dllname, importc: "glGetLocalConstantBooleanvEXT".} proc glGetLocalConstantIntegervEXT*(id: TGLuint, value: TGLenum, data: PGLint){. dynlib: dllname, importc: "glGetLocalConstantIntegervEXT".} proc glGetLocalConstantFloatvEXT*(id: TGLuint, value: TGLenum, data: PGLfloat){. dynlib: dllname, importc: "glGetLocalConstantFloatvEXT".} #***** GL_EXT_vertex_weighting *****// -const +const GL_VERTEX_WEIGHTING_EXT* = 0x00008509 GL_MODELVIEW0_EXT* = 0x00001700 GL_MODELVIEW1_EXT* = 0x0000850A @@ -1996,30 +1996,30 @@ const GL_MODELVIEW1_STACK_DEPTH_EXT* = 0x00008502 GL_VERTEX_WEIGHT_ARRAY_POINTER_EXT* = 0x00008510 -proc glVertexWeightfEXT*(weight: TGLfloat){.dynlib: dllname, +proc glVertexWeightfEXT*(weight: TGLfloat){.dynlib: dllname, importc: "glVertexWeightfEXT".} -proc glVertexWeightfvEXT*(weight: PGLfloat){.dynlib: dllname, +proc glVertexWeightfvEXT*(weight: PGLfloat){.dynlib: dllname, importc: "glVertexWeightfvEXT".} -proc glVertexWeightPointerEXT*(size: TGLint, thetype: TGLenum, stride: TGLsizei, - pointer: PGLvoid){.dynlib: dllname, +proc glVertexWeightPointerEXT*(size: TGLint, thetype: TGLenum, stride: TGLsizei, + pointer: PGLvoid){.dynlib: dllname, importc: "glVertexWeightPointerEXT".} #***** GL_HP_occlusion_test *****// -const +const GL_OCCLUSION_TEST_HP* = 0x00008165 GL_OCCLUSION_TEST_RESULT_HP* = 0x00008166 #***** GL_NV_blend_square *****// #***** GL_NV_copy_depth_to_color *****// -const +const GL_DEPTH_STENCIL_TO_RGBA_NV* = 0x0000886E GL_DEPTH_STENCIL_TO_BGRA_NV* = 0x0000886F #***** GL_NV_depth_clamp *****// -const +const GL_DEPTH_CLAMP_NV* = 0x0000864F #***** GL_NV_evaluators *****// -const +const GL_EVAL_2D_NV* = 0x000086C0 GL_EVAL_TRIANGULAR_2D_NV* = 0x000086C1 GL_MAP_TESSELLATION_NV* = 0x000086C2 @@ -2045,82 +2045,82 @@ const GL_MAX_MAP_TESSELLATION_NV* = 0x000086D6 GL_MAX_RATIONAL_EVAL_ORDER_NV* = 0x000086D7 -proc glMapControlPointsNV*(target: TGLenum, index: TGLuint, thetype: TGLenum, - ustride: TGLsizei, vstride: TGLsizei, uorder: TGLint, - vorder: TGLint, thepacked: TGLboolean, - points: PGLvoid){.dynlib: dllname, +proc glMapControlPointsNV*(target: TGLenum, index: TGLuint, thetype: TGLenum, + ustride: TGLsizei, vstride: TGLsizei, uorder: TGLint, + vorder: TGLint, thepacked: TGLboolean, + points: PGLvoid){.dynlib: dllname, importc: "glMapControlPointsNV".} proc glMapParameterivNV*(target: TGLenum, pname: TGLenum, params: PGLint){. dynlib: dllname, importc: "glMapParameterivNV".} proc glMapParameterfvNV*(target: TGLenum, pname: TGLenum, params: PGLfloat){. dynlib: dllname, importc: "glMapParameterfvNV".} -proc glGetMapControlPointsNV*(target: TGLenum, index: TGLuint, thetype: TGLenum, - ustride: TGLsizei, vstride: TGLsizei, +proc glGetMapControlPointsNV*(target: TGLenum, index: TGLuint, thetype: TGLenum, + ustride: TGLsizei, vstride: TGLsizei, thepacked: TGLboolean, points: PGLvoid){. dynlib: dllname, importc: "glGetMapControlPointsNV".} proc glGetMapParameterivNV*(target: TGLenum, pname: TGLenum, params: PGLint){. dynlib: dllname, importc: "glGetMapParameterivNV".} proc glGetMapParameterfvNV*(target: TGLenum, pname: TGLenum, params: PGLfloat){. dynlib: dllname, importc: "glGetMapParameterfvNV".} -proc glGetMapAttribParameterivNV*(target: TGLenum, index: TGLuint, +proc glGetMapAttribParameterivNV*(target: TGLenum, index: TGLuint, pname: TGLenum, params: PGLint){. dynlib: dllname, importc: "glGetMapAttribParameterivNV".} -proc glGetMapAttribParameterfvNV*(target: TGLenum, index: TGLuint, +proc glGetMapAttribParameterfvNV*(target: TGLenum, index: TGLuint, pname: TGLenum, params: PGLfloat){. dynlib: dllname, importc: "glGetMapAttribParameterfvNV".} -proc glEvalMapsNV*(target: TGLenum, mode: TGLenum){.dynlib: dllname, +proc glEvalMapsNV*(target: TGLenum, mode: TGLenum){.dynlib: dllname, importc: "glEvalMapsNV".} #***** GL_NV_fence *****// -const +const GL_ALL_COMPLETED_NV* = 0x000084F2 GL_FENCE_STATUS_NV* = 0x000084F3 GL_FENCE_CONDITION_NV* = 0x000084F4 -proc glGenFencesNV*(n: TGLsizei, fences: PGLuint){.dynlib: dllname, +proc glGenFencesNV*(n: TGLsizei, fences: PGLuint){.dynlib: dllname, importc: "glGenFencesNV".} -proc glDeleteFencesNV*(n: TGLsizei, fences: PGLuint){.dynlib: dllname, +proc glDeleteFencesNV*(n: TGLsizei, fences: PGLuint){.dynlib: dllname, importc: "glDeleteFencesNV".} -proc glSetFenceNV*(fence: TGLuint, condition: TGLenum){.dynlib: dllname, +proc glSetFenceNV*(fence: TGLuint, condition: TGLenum){.dynlib: dllname, importc: "glSetFenceNV".} -proc glTestFenceNV*(fence: TGLuint): TGLboolean{.dynlib: dllname, +proc glTestFenceNV*(fence: TGLuint): TGLboolean{.dynlib: dllname, importc: "glTestFenceNV".} -proc glFinishFenceNV*(fence: TGLuint){.dynlib: dllname, +proc glFinishFenceNV*(fence: TGLuint){.dynlib: dllname, importc: "glFinishFenceNV".} -proc glIsFenceNV*(fence: TGLuint): TGLboolean{.dynlib: dllname, +proc glIsFenceNV*(fence: TGLuint): TGLboolean{.dynlib: dllname, importc: "glIsFenceNV".} proc glGetFenceivNV*(fence: TGLuint, pname: TGLenum, params: PGLint){. dynlib: dllname, importc: "glGetFenceivNV".} #***** GL_NV_fog_distance *****// -const +const GL_FOG_DISTANCE_MODE_NV* = 0x0000855A GL_EYE_RADIAL_NV* = 0x0000855B GL_EYE_PLANE_ABSOLUTE_NV* = 0x0000855C #***** GL_NV_light_max_exponent *****// -const +const GL_MAX_SHININESS_NV* = 0x00008504 GL_MAX_SPOT_EXPONENT_NV* = 0x00008505 #***** GL_NV_multisample_filter_hint *****// -const +const GL_MULTISAMPLE_FILTER_HINT_NV* = 0x00008534 #***** GL_NV_occlusion_query *****// # GL_OCCLUSION_TEST_HP { already defined } # GL_OCCLUSION_TEST_RESULT_HP { already defined } -const +const GL_PIXEL_COUNTER_BITS_NV* = 0x00008864 GL_CURRENT_OCCLUSION_QUERY_ID_NV* = 0x00008865 GL_PIXEL_COUNT_NV* = 0x00008866 GL_PIXEL_COUNT_AVAILABLE_NV* = 0x00008867 -proc glGenOcclusionQueriesNV*(n: TGLsizei, ids: PGLuint){.dynlib: dllname, +proc glGenOcclusionQueriesNV*(n: TGLsizei, ids: PGLuint){.dynlib: dllname, importc: "glGenOcclusionQueriesNV".} -proc glDeleteOcclusionQueriesNV*(n: TGLsizei, ids: PGLuint){.dynlib: dllname, +proc glDeleteOcclusionQueriesNV*(n: TGLsizei, ids: PGLuint){.dynlib: dllname, importc: "glDeleteOcclusionQueriesNV".} -proc glIsOcclusionQueryNV*(id: TGLuint): TGLboolean{.dynlib: dllname, +proc glIsOcclusionQueryNV*(id: TGLuint): TGLboolean{.dynlib: dllname, importc: "glIsOcclusionQueryNV".} -proc glBeginOcclusionQueryNV*(id: TGLuint){.dynlib: dllname, +proc glBeginOcclusionQueryNV*(id: TGLuint){.dynlib: dllname, importc: "glBeginOcclusionQueryNV".} proc glEndOcclusionQueryNV*(){.dynlib: dllname, importc: "glEndOcclusionQueryNV".} proc glGetOcclusionQueryivNV*(id: TGLuint, pname: TGLenum, params: PGLint){. @@ -2128,22 +2128,22 @@ proc glGetOcclusionQueryivNV*(id: TGLuint, pname: TGLenum, params: PGLint){. proc glGetOcclusionQueryuivNV*(id: TGLuint, pname: TGLenum, params: PGLuint){. dynlib: dllname, importc: "glGetOcclusionQueryuivNV".} #***** GL_NV_packed_depth_stencil *****// -const +const GL_DEPTH_STENCIL_NV* = 0x000084F9 GL_UNSIGNED_INT_24_8_NV* = 0x000084FA #***** GL_NV_point_sprite *****// -const +const GL_POINT_SPRITE_NV* = 0x00008861 GL_COORD_REPLACE_NV* = 0x00008862 GL_POINT_SPRITE_R_MODE_NV* = 0x00008863 -proc glPointParameteriNV*(pname: TGLenum, param: TGLint){.dynlib: dllname, +proc glPointParameteriNV*(pname: TGLenum, param: TGLint){.dynlib: dllname, importc: "glPointParameteriNV".} -proc glPointParameterivNV*(pname: TGLenum, params: PGLint){.dynlib: dllname, +proc glPointParameterivNV*(pname: TGLenum, params: PGLint){.dynlib: dllname, importc: "glPointParameterivNV".} #***** GL_NV_register_combiners *****// -const +const GL_REGISTER_COMBINERS_NV* = 0x00008522 GL_COMBINER0_NV* = 0x00008550 GL_COMBINER1_NV* = 0x00008551 @@ -2198,62 +2198,62 @@ const proc glCombinerParameterfvNV*(pname: TGLenum, params: PGLfloat){. dynlib: dllname, importc: "glCombinerParameterfvNV".} -proc glCombinerParameterivNV*(pname: TGLenum, params: PGLint){.dynlib: dllname, +proc glCombinerParameterivNV*(pname: TGLenum, params: PGLint){.dynlib: dllname, importc: "glCombinerParameterivNV".} -proc glCombinerParameterfNV*(pname: TGLenum, param: TGLfloat){.dynlib: dllname, +proc glCombinerParameterfNV*(pname: TGLenum, param: TGLfloat){.dynlib: dllname, importc: "glCombinerParameterfNV".} -proc glCombinerParameteriNV*(pname: TGLenum, param: TGLint){.dynlib: dllname, +proc glCombinerParameteriNV*(pname: TGLenum, param: TGLint){.dynlib: dllname, importc: "glCombinerParameteriNV".} -proc glCombinerInputNV*(stage: TGLenum, portion: TGLenum, variable: TGLenum, - input: TGLenum, mapping: TGLenum, - componentUsage: TGLenum){.dynlib: dllname, +proc glCombinerInputNV*(stage: TGLenum, portion: TGLenum, variable: TGLenum, + input: TGLenum, mapping: TGLenum, + componentUsage: TGLenum){.dynlib: dllname, importc: "glCombinerInputNV".} -proc glCombinerOutputNV*(stage: TGLenum, portion: TGLenum, abOutput: TGLenum, - cdOutput: TGLenum, sumOutput: TGLenum, scale: TGLenum, - bias: TGLenum, abDotProduct: TGLboolean, +proc glCombinerOutputNV*(stage: TGLenum, portion: TGLenum, abOutput: TGLenum, + cdOutput: TGLenum, sumOutput: TGLenum, scale: TGLenum, + bias: TGLenum, abDotProduct: TGLboolean, cdDotProduct: TGLboolean, muxSum: TGLboolean){. dynlib: dllname, importc: "glCombinerOutputNV".} -proc glFinalCombinerInputNV*(variable: TGLenum, input: TGLenum, +proc glFinalCombinerInputNV*(variable: TGLenum, input: TGLenum, mapping: TGLenum, componentUsage: TGLenum){. dynlib: dllname, importc: "glFinalCombinerInputNV".} -proc glGetCombinerInputParameterfvNV*(stage: TGLenum, portion: TGLenum, - variable: TGLenum, pname: TGLenum, - params: PGLfloat){.dynlib: dllname, +proc glGetCombinerInputParameterfvNV*(stage: TGLenum, portion: TGLenum, + variable: TGLenum, pname: TGLenum, + params: PGLfloat){.dynlib: dllname, importc: "glGetCombinerInputParameterfvNV".} -proc glGetCombinerInputParameterivNV*(stage: TGLenum, portion: TGLenum, - variable: TGLenum, pname: TGLenum, - params: PGLint){.dynlib: dllname, +proc glGetCombinerInputParameterivNV*(stage: TGLenum, portion: TGLenum, + variable: TGLenum, pname: TGLenum, + params: PGLint){.dynlib: dllname, importc: "glGetCombinerInputParameterivNV".} -proc glGetCombinerOutputParameterfvNV*(stage: TGLenum, portion: TGLenum, +proc glGetCombinerOutputParameterfvNV*(stage: TGLenum, portion: TGLenum, pname: TGLenum, params: PGLfloat){. dynlib: dllname, importc: "glGetCombinerOutputParameterfvNV".} -proc glGetCombinerOutputParameterivNV*(stage: TGLenum, portion: TGLenum, +proc glGetCombinerOutputParameterivNV*(stage: TGLenum, portion: TGLenum, pname: TGLenum, params: PGLint){. dynlib: dllname, importc: "glGetCombinerOutputParameterivNV".} -proc glGetFinalCombinerInputParameterfvNV*(variable: TGLenum, pname: TGLenum, - params: PGLfloat){.dynlib: dllname, +proc glGetFinalCombinerInputParameterfvNV*(variable: TGLenum, pname: TGLenum, + params: PGLfloat){.dynlib: dllname, importc: "glGetFinalCombinerInputParameterfvNV".} -proc glGetFinalCombinerInputParameterivNV*(variable: TGLenum, pname: TGLenum, - params: PGLint){.dynlib: dllname, +proc glGetFinalCombinerInputParameterivNV*(variable: TGLenum, pname: TGLenum, + params: PGLint){.dynlib: dllname, importc: "glGetFinalCombinerInputParameterivNV".} #***** GL_NV_register_combiners2 *****// -const +const GL_PER_STAGE_CONSTANTS_NV* = 0x00008535 -proc glCombinerStageParameterfvNV*(stage: TGLenum, pname: TGLenum, - params: PGLfloat){.dynlib: dllname, +proc glCombinerStageParameterfvNV*(stage: TGLenum, pname: TGLenum, + params: PGLfloat){.dynlib: dllname, importc: "glCombinerStageParameterfvNV".} -proc glGetCombinerStageParameterfvNV*(stage: TGLenum, pname: TGLenum, - params: PGLfloat){.dynlib: dllname, +proc glGetCombinerStageParameterfvNV*(stage: TGLenum, pname: TGLenum, + params: PGLfloat){.dynlib: dllname, importc: "glGetCombinerStageParameterfvNV".} #***** GL_NV_texgen_emboss *****// -const +const GL_EMBOSS_MAP_NV* = 0x0000855F GL_EMBOSS_LIGHT_NV* = 0x0000855D GL_EMBOSS_CONSTANT_NV* = 0x0000855E #***** GL_NV_texgen_reflection *****// -const +const GL_NORMAL_MAP_NV* = 0x00008511 GL_REFLECTION_MAP_NV* = 0x00008512 #***** GL_NV_texture_compression_vtc *****// @@ -2263,7 +2263,7 @@ const # GL_COMPRESSED_RGBA_S3TC_DXT5_EXT { already defined } #***** GL_NV_texture_env_combine4 *****// -const +const GL_COMBINE4_NV* = 0x00008503 GL_SOURCE3_RGB_NV* = 0x00008583 GL_SOURCE3_ALPHA_NV* = 0x0000858B @@ -2271,14 +2271,14 @@ const GL_OPERAND3_ALPHA_NV* = 0x0000859B #***** GL_NV_texture_rectangle *****// -const +const GL_TEXTURE_RECTANGLE_NV* = 0x000084F5 GL_TEXTURE_BINDING_RECTANGLE_NV* = 0x000084F6 GL_PROXY_TEXTURE_RECTANGLE_NV* = 0x000084F7 GL_MAX_RECTANGLE_TEXTURE_SIZE_NV* = 0x000084F8 #***** GL_NV_texture_shader *****// -const +const GL_TEXTURE_SHADER_NV* = 0x000086DE GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV* = 0x000086D9 GL_SHADER_OPERATION_NV* = 0x000086DF @@ -2351,7 +2351,7 @@ const GL_TEXTURE_MAG_SIZE_NV* = 0x0000871F #***** GL_NV_texture_shader2 *****// -const +const GL_DOT_PRODUCT_TEXTURE_3D_NV* = 0x000086EF # GL_HILO_NV { already defined } # GL_DSDT_NV { already defined } # GL_DSDT_MAG_NV { already defined } @@ -2381,7 +2381,7 @@ const # GL_DSDT8_MAG8_INTENSITY8_NV { already defined } #***** GL_NV_texture_shader3 *****// -const +const GL_OFFSET_PROJECTIVE_TEXTURE_2D_NV* = 0x00008850 GL_OFFSET_PROJECTIVE_TEXTURE_2D_SCALE_NV* = 0x00008851 GL_OFFSET_PROJECTIVE_TEXTURE_RECTANGLE_NV* = 0x00008852 @@ -2401,23 +2401,23 @@ const GL_FORCE_BLUE_TO_ONE_NV* = 0x00008860 #***** GL_NV_vertex_array_range *****// -const +const constGL_VERTEX_ARRAY_RANGE_NV* = 0x0000851D GL_VERTEX_ARRAY_RANGE_LENGTH_NV* = 0x0000851E GL_VERTEX_ARRAY_RANGE_VALID_NV* = 0x0000851F GL_MAX_VERTEX_ARRAY_RANGE_ELEMENT_NV* = 0x00008520 GL_VERTEX_ARRAY_RANGE_POINTER_NV* = 0x00008521 -proc glVertexArrayRangeNV*(len: TGLsizei, pointer: PGLvoid){.dynlib: dllname, +proc glVertexArrayRangeNV*(len: TGLsizei, pointer: PGLvoid){.dynlib: dllname, importc: "glVertexArrayRangeNV".} -proc glFlushVertexArrayRangeNV*(){.dynlib: dllname, +proc glFlushVertexArrayRangeNV*(){.dynlib: dllname, importc: "glFlushVertexArrayRangeNV".} #***** GL_NV_vertex_array_range2 *****// -const +const GL_VERTEX_ARRAY_RANGE_WITHOUT_FLUSH_NV* = 0x00008533 #***** GL_NV_vertex_program *****// -const +const GL_VERTEX_PROGRAM_NV* = 0x00008620 GL_VERTEX_PROGRAM_POINT_SIZE_NV* = 0x00008642 GL_VERTEX_PROGRAM_TWO_SIDE_NV* = 0x00008643 @@ -2502,30 +2502,30 @@ const GL_MAP2_VERTEX_ATTRIB14_4_NV* = 0x0000867E GL_MAP2_VERTEX_ATTRIB15_4_NV* = 0x0000867F -proc glBindProgramNV*(target: TGLenum, id: TGLuint){.dynlib: dllname, +proc glBindProgramNV*(target: TGLenum, id: TGLuint){.dynlib: dllname, importc: "glBindProgramNV".} -proc glDeleteProgramsNV*(n: TGLsizei, ids: PGLuint){.dynlib: dllname, +proc glDeleteProgramsNV*(n: TGLsizei, ids: PGLuint){.dynlib: dllname, importc: "glDeleteProgramsNV".} proc glExecuteProgramNV*(target: TGLenum, id: TGLuint, params: PGLfloat){. dynlib: dllname, importc: "glExecuteProgramNV".} -proc glGenProgramsNV*(n: TGLsizei, ids: PGLuint){.dynlib: dllname, +proc glGenProgramsNV*(n: TGLsizei, ids: PGLuint){.dynlib: dllname, importc: "glGenProgramsNV".} proc glAreProgramsResidentNV*(n: TGLsizei, ids: PGLuint, residences: PGLboolean): TGLboolean{. dynlib: dllname, importc: "glAreProgramsResidentNV".} -proc glRequestResidentProgramsNV*(n: TGLsizei, ids: PGLuint){.dynlib: dllname, +proc glRequestResidentProgramsNV*(n: TGLsizei, ids: PGLuint){.dynlib: dllname, importc: "glRequestResidentProgramsNV".} -proc glGetProgramParameterfvNV*(target: TGLenum, index: TGLuint, pname: TGLenum, - params: PGLfloat){.dynlib: dllname, +proc glGetProgramParameterfvNV*(target: TGLenum, index: TGLuint, pname: TGLenum, + params: PGLfloat){.dynlib: dllname, importc: "glGetProgramParameterfvNV".} -proc glGetProgramParameterdvNV*(target: TGLenum, index: TGLuint, pname: TGLenum, - params: PGLdouble){.dynlib: dllname, +proc glGetProgramParameterdvNV*(target: TGLenum, index: TGLuint, pname: TGLenum, + params: PGLdouble){.dynlib: dllname, importc: "glGetProgramParameterdvNV".} proc glGetProgramivNV*(id: TGLuint, pname: TGLenum, params: PGLint){. dynlib: dllname, importc: "glGetProgramivNV".} proc glGetProgramStringNV*(id: TGLuint, pname: TGLenum, theProgram: PGLubyte){. dynlib: dllname, importc: "glGetProgramStringNV".} -proc glGetTrackMatrixivNV*(target: TGLenum, address: TGLuint, pname: TGLenum, - params: PGLint){.dynlib: dllname, +proc glGetTrackMatrixivNV*(target: TGLenum, address: TGLuint, pname: TGLenum, + params: PGLint){.dynlib: dllname, importc: "glGetTrackMatrixivNV".} proc glGetVertexAttribdvNV*(index: TGLuint, pname: TGLenum, params: PGLdouble){. dynlib: dllname, importc: "glGetVertexAttribdvNV".} @@ -2533,36 +2533,36 @@ proc glGetVertexAttribfvNV*(index: TGLuint, pname: TGLenum, params: PGLfloat){. dynlib: dllname, importc: "glGetVertexAttribfvNV".} proc glGetVertexAttribivNV*(index: TGLuint, pname: TGLenum, params: PGLint){. dynlib: dllname, importc: "glGetVertexAttribivNV".} -proc glGetVertexAttribPointervNV*(index: TGLuint, pname: TGLenum, - pointer: PGLvoid){.dynlib: dllname, +proc glGetVertexAttribPointervNV*(index: TGLuint, pname: TGLenum, + pointer: PGLvoid){.dynlib: dllname, importc: "glGetVertexAttribPointervNV".} -proc glIsProgramNV*(id: TGLuint): TGLboolean{.dynlib: dllname, +proc glIsProgramNV*(id: TGLuint): TGLboolean{.dynlib: dllname, importc: "glIsProgramNV".} -proc glLoadProgramNV*(target: TGLenum, id: TGLuint, length: TGLsizei, - theProgram: PGLubyte){.dynlib: dllname, +proc glLoadProgramNV*(target: TGLenum, id: TGLuint, length: TGLsizei, + theProgram: PGLubyte){.dynlib: dllname, importc: "glLoadProgramNV".} -proc glProgramParameter4fNV*(target: TGLenum, index: TGLuint, x: TGLfloat, +proc glProgramParameter4fNV*(target: TGLenum, index: TGLuint, x: TGLfloat, y: TGLfloat, z: TGLfloat, w: TGLfloat){. dynlib: dllname, importc: "glProgramParameter4fNV".} proc glProgramParameter4fvNV*(target: TGLenum, index: TGLuint, params: PGLfloat){. dynlib: dllname, importc: "glProgramParameter4fvNV".} -proc glProgramParameters4dvNV*(target: TGLenum, index: TGLuint, num: TGLuint, - params: PGLdouble){.dynlib: dllname, +proc glProgramParameters4dvNV*(target: TGLenum, index: TGLuint, num: TGLuint, + params: PGLdouble){.dynlib: dllname, importc: "glProgramParameters4dvNV".} -proc glProgramParameters4fvNV*(target: TGLenum, index: TGLuint, num: TGLuint, - params: PGLfloat){.dynlib: dllname, +proc glProgramParameters4fvNV*(target: TGLenum, index: TGLuint, num: TGLuint, + params: PGLfloat){.dynlib: dllname, importc: "glProgramParameters4fvNV".} -proc glTrackMatrixNV*(target: TGLenum, address: TGLuint, matrix: TGLenum, - transform: TGLenum){.dynlib: dllname, +proc glTrackMatrixNV*(target: TGLenum, address: TGLuint, matrix: TGLenum, + transform: TGLenum){.dynlib: dllname, importc: "glTrackMatrixNV".} -proc glVertexAttribPointerNV*(index: TGLuint, size: TGLint, thetype: TGLenum, +proc glVertexAttribPointerNV*(index: TGLuint, size: TGLint, thetype: TGLenum, stride: TGLsizei, pointer: PGLvoid){. dynlib: dllname, importc: "glVertexAttribPointerNV".} -proc glVertexAttrib1sNV*(index: TGLuint, x: TGLshort){.dynlib: dllname, +proc glVertexAttrib1sNV*(index: TGLuint, x: TGLshort){.dynlib: dllname, importc: "glVertexAttrib1sNV".} -proc glVertexAttrib1fNV*(index: TGLuint, x: TGLfloat){.dynlib: dllname, +proc glVertexAttrib1fNV*(index: TGLuint, x: TGLfloat){.dynlib: dllname, importc: "glVertexAttrib1fNV".} -proc glVertexAttrib1dNV*(index: TGLuint, x: TGLdouble){.dynlib: dllname, +proc glVertexAttrib1dNV*(index: TGLuint, x: TGLdouble){.dynlib: dllname, importc: "glVertexAttrib1dNV".} proc glVertexAttrib2sNV*(index: TGLuint, x: TGLshort, y: TGLshort){. dynlib: dllname, importc: "glVertexAttrib2sNV".} @@ -2574,46 +2574,46 @@ proc glVertexAttrib3sNV*(index: TGLuint, x: TGLshort, y: TGLshort, z: TGLshort){ dynlib: dllname, importc: "glVertexAttrib3sNV".} proc glVertexAttrib3fNV*(index: TGLuint, x: TGLfloat, y: TGLfloat, z: TGLfloat){. dynlib: dllname, importc: "glVertexAttrib3fNV".} -proc glVertexAttrib3dNV*(index: TGLuint, x: TGLdouble, y: TGLdouble, - z: TGLdouble){.dynlib: dllname, +proc glVertexAttrib3dNV*(index: TGLuint, x: TGLdouble, y: TGLdouble, + z: TGLdouble){.dynlib: dllname, importc: "glVertexAttrib3dNV".} -proc glVertexAttrib4sNV*(index: TGLuint, x: TGLshort, y: TGLshort, z: TGLshort, - w: TGLshort){.dynlib: dllname, +proc glVertexAttrib4sNV*(index: TGLuint, x: TGLshort, y: TGLshort, z: TGLshort, + w: TGLshort){.dynlib: dllname, importc: "glVertexAttrib4sNV".} -proc glVertexAttrib4fNV*(index: TGLuint, x: TGLfloat, y: TGLfloat, z: TGLfloat, - w: TGLfloat){.dynlib: dllname, +proc glVertexAttrib4fNV*(index: TGLuint, x: TGLfloat, y: TGLfloat, z: TGLfloat, + w: TGLfloat){.dynlib: dllname, importc: "glVertexAttrib4fNV".} -proc glVertexAttrib4dNV*(index: TGLuint, x: TGLdouble, y: TGLdouble, - z: TGLdouble, w: TGLdouble){.dynlib: dllname, +proc glVertexAttrib4dNV*(index: TGLuint, x: TGLdouble, y: TGLdouble, + z: TGLdouble, w: TGLdouble){.dynlib: dllname, importc: "glVertexAttrib4dNV".} -proc glVertexAttrib4ubNV*(index: TGLuint, x: TGLubyte, y: TGLubyte, z: TGLubyte, - w: TGLubyte){.dynlib: dllname, +proc glVertexAttrib4ubNV*(index: TGLuint, x: TGLubyte, y: TGLubyte, z: TGLubyte, + w: TGLubyte){.dynlib: dllname, importc: "glVertexAttrib4ubNV".} -proc glVertexAttrib1svNV*(index: TGLuint, v: PGLshort){.dynlib: dllname, +proc glVertexAttrib1svNV*(index: TGLuint, v: PGLshort){.dynlib: dllname, importc: "glVertexAttrib1svNV".} -proc glVertexAttrib1fvNV*(index: TGLuint, v: PGLfloat){.dynlib: dllname, +proc glVertexAttrib1fvNV*(index: TGLuint, v: PGLfloat){.dynlib: dllname, importc: "glVertexAttrib1fvNV".} -proc glVertexAttrib1dvNV*(index: TGLuint, v: PGLdouble){.dynlib: dllname, +proc glVertexAttrib1dvNV*(index: TGLuint, v: PGLdouble){.dynlib: dllname, importc: "glVertexAttrib1dvNV".} -proc glVertexAttrib2svNV*(index: TGLuint, v: PGLshort){.dynlib: dllname, +proc glVertexAttrib2svNV*(index: TGLuint, v: PGLshort){.dynlib: dllname, importc: "glVertexAttrib2svNV".} -proc glVertexAttrib2fvNV*(index: TGLuint, v: PGLfloat){.dynlib: dllname, +proc glVertexAttrib2fvNV*(index: TGLuint, v: PGLfloat){.dynlib: dllname, importc: "glVertexAttrib2fvNV".} -proc glVertexAttrib2dvNV*(index: TGLuint, v: PGLdouble){.dynlib: dllname, +proc glVertexAttrib2dvNV*(index: TGLuint, v: PGLdouble){.dynlib: dllname, importc: "glVertexAttrib2dvNV".} -proc glVertexAttrib3svNV*(index: TGLuint, v: PGLshort){.dynlib: dllname, +proc glVertexAttrib3svNV*(index: TGLuint, v: PGLshort){.dynlib: dllname, importc: "glVertexAttrib3svNV".} -proc glVertexAttrib3fvNV*(index: TGLuint, v: PGLfloat){.dynlib: dllname, +proc glVertexAttrib3fvNV*(index: TGLuint, v: PGLfloat){.dynlib: dllname, importc: "glVertexAttrib3fvNV".} -proc glVertexAttrib3dvNV*(index: TGLuint, v: PGLdouble){.dynlib: dllname, +proc glVertexAttrib3dvNV*(index: TGLuint, v: PGLdouble){.dynlib: dllname, importc: "glVertexAttrib3dvNV".} -proc glVertexAttrib4svNV*(index: TGLuint, v: PGLshort){.dynlib: dllname, +proc glVertexAttrib4svNV*(index: TGLuint, v: PGLshort){.dynlib: dllname, importc: "glVertexAttrib4svNV".} -proc glVertexAttrib4fvNV*(index: TGLuint, v: PGLfloat){.dynlib: dllname, +proc glVertexAttrib4fvNV*(index: TGLuint, v: PGLfloat){.dynlib: dllname, importc: "glVertexAttrib4fvNV".} -proc glVertexAttrib4dvNV*(index: TGLuint, v: PGLdouble){.dynlib: dllname, +proc glVertexAttrib4dvNV*(index: TGLuint, v: PGLdouble){.dynlib: dllname, importc: "glVertexAttrib4dvNV".} -proc glVertexAttrib4ubvNV*(index: TGLuint, v: PGLubyte){.dynlib: dllname, +proc glVertexAttrib4ubvNV*(index: TGLuint, v: PGLubyte){.dynlib: dllname, importc: "glVertexAttrib4ubvNV".} proc glVertexAttribs1svNV*(index: TGLuint, n: TGLsizei, v: PGLshort){. dynlib: dllname, importc: "glVertexAttribs1svNV".} @@ -2643,20 +2643,20 @@ proc glVertexAttribs4ubvNV*(index: TGLuint, n: TGLsizei, v: PGLubyte){. dynlib: dllname, importc: "glVertexAttribs4ubvNV".} #***** GL_NV_vertex_program1_1 *****// #***** GL_ATI_element_array *****// -const +const GL_ELEMENT_ARRAY_ATI* = 0x00008768 GL_ELEMENT_ARRAY_TYPE_ATI* = 0x00008769 GL_ELEMENT_ARRAY_POINTER_ATI* = 0x0000876A -proc glElementPointerATI*(thetype: TGLenum, pointer: PGLvoid){.dynlib: dllname, +proc glElementPointerATI*(thetype: TGLenum, pointer: PGLvoid){.dynlib: dllname, importc: "glElementPointerATI".} -proc glDrawElementArrayATI*(mode: TGLenum, count: TGLsizei){.dynlib: dllname, +proc glDrawElementArrayATI*(mode: TGLenum, count: TGLsizei){.dynlib: dllname, importc: "glDrawElementArrayATI".} -proc glDrawRangeElementArrayATI*(mode: TGLenum, start: TGLuint, theend: TGLuint, - count: TGLsizei){.dynlib: dllname, +proc glDrawRangeElementArrayATI*(mode: TGLenum, start: TGLuint, theend: TGLuint, + count: TGLsizei){.dynlib: dllname, importc: "glDrawRangeElementArrayATI".} #***** GL_ATI_envmap_bumpmap *****// -const +const GL_BUMP_ROT_MATRIX_ATI* = 0x00008775 GL_BUMP_ROT_MATRIX_SIZE_ATI* = 0x00008776 GL_BUMP_NUM_TEX_UNITS_ATI* = 0x00008777 @@ -2666,16 +2666,16 @@ const GL_BUMP_ENVMAP_ATI* = 0x0000877B GL_BUMP_TARGET_ATI* = 0x0000877C -proc glTexBumpParameterivATI*(pname: TGLenum, param: PGLint){.dynlib: dllname, +proc glTexBumpParameterivATI*(pname: TGLenum, param: PGLint){.dynlib: dllname, importc: "glTexBumpParameterivATI".} -proc glTexBumpParameterfvATI*(pname: TGLenum, param: PGLfloat){.dynlib: dllname, +proc glTexBumpParameterfvATI*(pname: TGLenum, param: PGLfloat){.dynlib: dllname, importc: "glTexBumpParameterfvATI".} proc glGetTexBumpParameterivATI*(pname: TGLenum, param: PGLint){. dynlib: dllname, importc: "glGetTexBumpParameterivATI".} proc glGetTexBumpParameterfvATI*(pname: TGLenum, param: PGLfloat){. dynlib: dllname, importc: "glGetTexBumpParameterfvATI".} #***** GL_ATI_fragment_shader *****// -const +const GL_FRAGMENT_SHADER_ATI* = 0x00008920 GL_REG_0_ATI* = 0x00008921 GL_REG_1_ATI* = 0x00008922 @@ -2721,51 +2721,51 @@ const GL_NEGATE_BIT_ATI* = 0x00000004 GL_BIAS_BIT_ATI* = 0x00000008 -proc glGenFragmentShadersATI*(range: TGLuint): TGLuint{.dynlib: dllname, +proc glGenFragmentShadersATI*(range: TGLuint): TGLuint{.dynlib: dllname, importc: "glGenFragmentShadersATI".} -proc glBindFragmentShaderATI*(id: TGLuint){.dynlib: dllname, +proc glBindFragmentShaderATI*(id: TGLuint){.dynlib: dllname, importc: "glBindFragmentShaderATI".} -proc glDeleteFragmentShaderATI*(id: TGLuint){.dynlib: dllname, +proc glDeleteFragmentShaderATI*(id: TGLuint){.dynlib: dllname, importc: "glDeleteFragmentShaderATI".} -proc glBeginFragmentShaderATI*(){.dynlib: dllname, +proc glBeginFragmentShaderATI*(){.dynlib: dllname, importc: "glBeginFragmentShaderATI".} -proc glEndFragmentShaderATI*(){.dynlib: dllname, +proc glEndFragmentShaderATI*(){.dynlib: dllname, importc: "glEndFragmentShaderATI".} proc glPassTexCoordATI*(dst: TGLuint, coord: TGLuint, swizzle: TGLenum){. dynlib: dllname, importc: "glPassTexCoordATI".} proc glSampleMapATI*(dst: TGLuint, interp: TGLuint, swizzle: TGLenum){. dynlib: dllname, importc: "glSampleMapATI".} -proc glColorFragmentOp1ATI*(op: TGLenum, dst: TGLuint, dstMask: TGLuint, - dstMod: TGLuint, arg1: TGLuint, arg1Rep: TGLuint, - arg1Mod: TGLuint){.dynlib: dllname, +proc glColorFragmentOp1ATI*(op: TGLenum, dst: TGLuint, dstMask: TGLuint, + dstMod: TGLuint, arg1: TGLuint, arg1Rep: TGLuint, + arg1Mod: TGLuint){.dynlib: dllname, importc: "glColorFragmentOp1ATI".} -proc glColorFragmentOp2ATI*(op: TGLenum, dst: TGLuint, dstMask: TGLuint, - dstMod: TGLuint, arg1: TGLuint, arg1Rep: TGLuint, - arg1Mod: TGLuint, arg2: TGLuint, arg2Rep: TGLuint, - arg2Mod: TGLuint){.dynlib: dllname, +proc glColorFragmentOp2ATI*(op: TGLenum, dst: TGLuint, dstMask: TGLuint, + dstMod: TGLuint, arg1: TGLuint, arg1Rep: TGLuint, + arg1Mod: TGLuint, arg2: TGLuint, arg2Rep: TGLuint, + arg2Mod: TGLuint){.dynlib: dllname, importc: "glColorFragmentOp2ATI".} -proc glColorFragmentOp3ATI*(op: TGLenum, dst: TGLuint, dstMask: TGLuint, - dstMod: TGLuint, arg1: TGLuint, arg1Rep: TGLuint, - arg1Mod: TGLuint, arg2: TGLuint, arg2Rep: TGLuint, - arg2Mod: TGLuint, arg3: TGLuint, arg3Rep: TGLuint, - arg3Mod: TGLuint){.dynlib: dllname, +proc glColorFragmentOp3ATI*(op: TGLenum, dst: TGLuint, dstMask: TGLuint, + dstMod: TGLuint, arg1: TGLuint, arg1Rep: TGLuint, + arg1Mod: TGLuint, arg2: TGLuint, arg2Rep: TGLuint, + arg2Mod: TGLuint, arg3: TGLuint, arg3Rep: TGLuint, + arg3Mod: TGLuint){.dynlib: dllname, importc: "glColorFragmentOp3ATI".} -proc glAlphaFragmentOp1ATI*(op: TGLenum, dst: TGLuint, dstMod: TGLuint, +proc glAlphaFragmentOp1ATI*(op: TGLenum, dst: TGLuint, dstMod: TGLuint, arg1: TGLuint, arg1Rep: TGLuint, arg1Mod: TGLuint){. dynlib: dllname, importc: "glAlphaFragmentOp1ATI".} -proc glAlphaFragmentOp2ATI*(op: TGLenum, dst: TGLuint, dstMod: TGLuint, - arg1: TGLuint, arg1Rep: TGLuint, arg1Mod: TGLuint, +proc glAlphaFragmentOp2ATI*(op: TGLenum, dst: TGLuint, dstMod: TGLuint, + arg1: TGLuint, arg1Rep: TGLuint, arg1Mod: TGLuint, arg2: TGLuint, arg2Rep: TGLuint, arg2Mod: TGLuint){. dynlib: dllname, importc: "glAlphaFragmentOp2ATI".} -proc glAlphaFragmentOp3ATI*(op: TGLenum, dst: TGLuint, dstMod: TGLuint, - arg1: TGLuint, arg1Rep: TGLuint, arg1Mod: TGLuint, - arg2: TGLuint, arg2Rep: TGLuint, arg2Mod: TGLuint, +proc glAlphaFragmentOp3ATI*(op: TGLenum, dst: TGLuint, dstMod: TGLuint, + arg1: TGLuint, arg1Rep: TGLuint, arg1Mod: TGLuint, + arg2: TGLuint, arg2Rep: TGLuint, arg2Mod: TGLuint, arg3: TGLuint, arg3Rep: TGLuint, arg3Mod: TGLuint){. dynlib: dllname, importc: "glAlphaFragmentOp3ATI".} proc glSetFragmentShaderConstantATI*(dst: TGLuint, value: PGLfloat){. dynlib: dllname, importc: "glSetFragmentShaderConstantATI".} #***** GL_ATI_pn_triangles *****// -const +const GL_PN_TRIANGLES_ATI* = 0x000087F0 GL_MAX_PN_TRIANGLES_TESSELATION_LEVEL_ATI* = 0x000087F1 GL_PN_TRIANGLES_POINT_MODE_ATI* = 0x000087F2 @@ -2776,17 +2776,17 @@ const GL_PN_TRIANGLES_NORMAL_MODE_LINEAR_ATI* = 0x000087F7 GL_PN_TRIANGLES_NORMAL_MODE_QUADRATIC_ATI* = 0x000087F8 -proc glPNTrianglesiATI*(pname: TGLenum, param: TGLint){.dynlib: dllname, +proc glPNTrianglesiATI*(pname: TGLenum, param: TGLint){.dynlib: dllname, importc: "glPNTrianglesiATI".} -proc glPNTrianglesfATI*(pname: TGLenum, param: TGLfloat){.dynlib: dllname, +proc glPNTrianglesfATI*(pname: TGLenum, param: TGLfloat){.dynlib: dllname, importc: "glPNTrianglesfATI".} #***** GL_ATI_texture_mirror_once *****// -const +const GL_MIRROR_CLAMP_ATI* = 0x00008742 GL_MIRROR_CLAMP_TO_EDGE_ATI* = 0x00008743 #***** GL_ATI_vertex_array_object *****// -const +const GL_STATIC_ATI* = 0x00008760 GL_DYNAMIC_ATI* = 0x00008761 GL_PRESERVE_ATI* = 0x00008762 @@ -2798,25 +2798,25 @@ const proc glNewObjectBufferATI*(size: TGLsizei, pointer: PGLvoid, usage: TGLenum): TGLuint{. dynlib: dllname, importc: "glNewObjectBufferATI".} -proc glIsObjectBufferATI*(buffer: TGLuint): TGLboolean{.dynlib: dllname, +proc glIsObjectBufferATI*(buffer: TGLuint): TGLboolean{.dynlib: dllname, importc: "glIsObjectBufferATI".} -proc glUpdateObjectBufferATI*(buffer: TGLuint, offset: TGLuint, size: TGLsizei, +proc glUpdateObjectBufferATI*(buffer: TGLuint, offset: TGLuint, size: TGLsizei, pointer: PGLvoid, preserve: TGLenum){. dynlib: dllname, importc: "glUpdateObjectBufferATI".} proc glGetObjectBufferfvATI*(buffer: TGLuint, pname: TGLenum, params: PGLfloat){. dynlib: dllname, importc: "glGetObjectBufferfvATI".} proc glGetObjectBufferivATI*(buffer: TGLuint, pname: TGLenum, params: PGLint){. dynlib: dllname, importc: "glGetObjectBufferivATI".} -proc glDeleteObjectBufferATI*(buffer: TGLuint){.dynlib: dllname, +proc glDeleteObjectBufferATI*(buffer: TGLuint){.dynlib: dllname, importc: "glDeleteObjectBufferATI".} -proc glArrayObjectATI*(thearray: TGLenum, size: TGLint, thetype: TGLenum, +proc glArrayObjectATI*(thearray: TGLenum, size: TGLint, thetype: TGLenum, stride: TGLsizei, buffer: TGLuint, offset: TGLuint){. dynlib: dllname, importc: "glArrayObjectATI".} proc glGetArrayObjectfvATI*(thearray: TGLenum, pname: TGLenum, params: PGLfloat){. dynlib: dllname, importc: "glGetArrayObjectfvATI".} proc glGetArrayObjectivATI*(thearray: TGLenum, pname: TGLenum, params: PGLint){. dynlib: dllname, importc: "glGetArrayObjectivATI".} -proc glVariantArrayObjectATI*(id: TGLuint, thetype: TGLenum, stride: TGLsizei, +proc glVariantArrayObjectATI*(id: TGLuint, thetype: TGLenum, stride: TGLsizei, buffer: TGLuint, offset: TGLuint){. dynlib: dllname, importc: "glVariantArrayObjectATI".} proc glGetVariantArrayObjectfvATI*(id: TGLuint, pname: TGLenum, params: PGLfloat){. @@ -2824,7 +2824,7 @@ proc glGetVariantArrayObjectfvATI*(id: TGLuint, pname: TGLenum, params: PGLfloat proc glGetVariantArrayObjectivATI*(id: TGLuint, pname: TGLenum, params: PGLint){. dynlib: dllname, importc: "glGetVariantArrayObjectivATI".} #***** GL_ATI_vertex_streams *****// -const +const GL_MAX_VERTEX_STREAMS_ATI* = 0x0000876B GL_VERTEX_STREAM0_ATI* = 0x0000876C GL_VERTEX_STREAM1_ATI* = 0x0000876D @@ -2836,123 +2836,123 @@ const GL_VERTEX_STREAM7_ATI* = 0x00008773 GL_VERTEX_SOURCE_ATI* = 0x00008774 -proc glVertexStream1s*(stream: TGLenum, coords: TGLshort){.dynlib: dllname, +proc glVertexStream1s*(stream: TGLenum, coords: TGLshort){.dynlib: dllname, importc: "glVertexStream1s".} -proc glVertexStream1i*(stream: TGLenum, coords: TGLint){.dynlib: dllname, +proc glVertexStream1i*(stream: TGLenum, coords: TGLint){.dynlib: dllname, importc: "glVertexStream1i".} -proc glVertexStream1f*(stream: TGLenum, coords: TGLfloat){.dynlib: dllname, +proc glVertexStream1f*(stream: TGLenum, coords: TGLfloat){.dynlib: dllname, importc: "glVertexStream1f".} -proc glVertexStream1d*(stream: TGLenum, coords: TGLdouble){.dynlib: dllname, +proc glVertexStream1d*(stream: TGLenum, coords: TGLdouble){.dynlib: dllname, importc: "glVertexStream1d".} -proc glVertexStream1sv*(stream: TGLenum, coords: TGLshort){.dynlib: dllname, +proc glVertexStream1sv*(stream: TGLenum, coords: TGLshort){.dynlib: dllname, importc: "glVertexStream1sv".} -proc glVertexStream1iv*(stream: TGLenum, coords: TGLint){.dynlib: dllname, +proc glVertexStream1iv*(stream: TGLenum, coords: TGLint){.dynlib: dllname, importc: "glVertexStream1iv".} -proc glVertexStream1fv*(stream: TGLenum, coords: TGLfloat){.dynlib: dllname, +proc glVertexStream1fv*(stream: TGLenum, coords: TGLfloat){.dynlib: dllname, importc: "glVertexStream1fv".} -proc glVertexStream1dv*(stream: TGLenum, coords: TGLdouble){.dynlib: dllname, +proc glVertexStream1dv*(stream: TGLenum, coords: TGLdouble){.dynlib: dllname, importc: "glVertexStream1dv".} -proc glVertexStream2s*(stream: TGLenum, coords: TGLshort){.dynlib: dllname, +proc glVertexStream2s*(stream: TGLenum, coords: TGLshort){.dynlib: dllname, importc: "glVertexStream2s".} -proc glVertexStream2i*(stream: TGLenum, coords: TGLint){.dynlib: dllname, +proc glVertexStream2i*(stream: TGLenum, coords: TGLint){.dynlib: dllname, importc: "glVertexStream2i".} -proc glVertexStream2f*(stream: TGLenum, coords: TGLfloat){.dynlib: dllname, +proc glVertexStream2f*(stream: TGLenum, coords: TGLfloat){.dynlib: dllname, importc: "glVertexStream2f".} -proc glVertexStream2d*(stream: TGLenum, coords: TGLdouble){.dynlib: dllname, +proc glVertexStream2d*(stream: TGLenum, coords: TGLdouble){.dynlib: dllname, importc: "glVertexStream2d".} -proc glVertexStream2sv*(stream: TGLenum, coords: TGLshort){.dynlib: dllname, +proc glVertexStream2sv*(stream: TGLenum, coords: TGLshort){.dynlib: dllname, importc: "glVertexStream2sv".} -proc glVertexStream2iv*(stream: TGLenum, coords: TGLint){.dynlib: dllname, +proc glVertexStream2iv*(stream: TGLenum, coords: TGLint){.dynlib: dllname, importc: "glVertexStream2iv".} -proc glVertexStream2fv*(stream: TGLenum, coords: TGLfloat){.dynlib: dllname, +proc glVertexStream2fv*(stream: TGLenum, coords: TGLfloat){.dynlib: dllname, importc: "glVertexStream2fv".} -proc glVertexStream2dv*(stream: TGLenum, coords: TGLdouble){.dynlib: dllname, +proc glVertexStream2dv*(stream: TGLenum, coords: TGLdouble){.dynlib: dllname, importc: "glVertexStream2dv".} -proc glVertexStream3s*(stream: TGLenum, coords: TGLshort){.dynlib: dllname, +proc glVertexStream3s*(stream: TGLenum, coords: TGLshort){.dynlib: dllname, importc: "glVertexStream3s".} -proc glVertexStream3i*(stream: TGLenum, coords: TGLint){.dynlib: dllname, +proc glVertexStream3i*(stream: TGLenum, coords: TGLint){.dynlib: dllname, importc: "glVertexStream3i".} -proc glVertexStream3f*(stream: TGLenum, coords: TGLfloat){.dynlib: dllname, +proc glVertexStream3f*(stream: TGLenum, coords: TGLfloat){.dynlib: dllname, importc: "glVertexStream3f".} -proc glVertexStream3d*(stream: TGLenum, coords: TGLdouble){.dynlib: dllname, +proc glVertexStream3d*(stream: TGLenum, coords: TGLdouble){.dynlib: dllname, importc: "glVertexStream3d".} -proc glVertexStream3sv*(stream: TGLenum, coords: TGLshort){.dynlib: dllname, +proc glVertexStream3sv*(stream: TGLenum, coords: TGLshort){.dynlib: dllname, importc: "glVertexStream3sv".} -proc glVertexStream3iv*(stream: TGLenum, coords: TGLint){.dynlib: dllname, +proc glVertexStream3iv*(stream: TGLenum, coords: TGLint){.dynlib: dllname, importc: "glVertexStream3iv".} -proc glVertexStream3fv*(stream: TGLenum, coords: TGLfloat){.dynlib: dllname, +proc glVertexStream3fv*(stream: TGLenum, coords: TGLfloat){.dynlib: dllname, importc: "glVertexStream3fv".} -proc glVertexStream3dv*(stream: TGLenum, coords: TGLdouble){.dynlib: dllname, +proc glVertexStream3dv*(stream: TGLenum, coords: TGLdouble){.dynlib: dllname, importc: "glVertexStream3dv".} -proc glVertexStream4s*(stream: TGLenum, coords: TGLshort){.dynlib: dllname, +proc glVertexStream4s*(stream: TGLenum, coords: TGLshort){.dynlib: dllname, importc: "glVertexStream4s".} -proc glVertexStream4i*(stream: TGLenum, coords: TGLint){.dynlib: dllname, +proc glVertexStream4i*(stream: TGLenum, coords: TGLint){.dynlib: dllname, importc: "glVertexStream4i".} -proc glVertexStream4f*(stream: TGLenum, coords: TGLfloat){.dynlib: dllname, +proc glVertexStream4f*(stream: TGLenum, coords: TGLfloat){.dynlib: dllname, importc: "glVertexStream4f".} -proc glVertexStream4d*(stream: TGLenum, coords: TGLdouble){.dynlib: dllname, +proc glVertexStream4d*(stream: TGLenum, coords: TGLdouble){.dynlib: dllname, importc: "glVertexStream4d".} -proc glVertexStream4sv*(stream: TGLenum, coords: TGLshort){.dynlib: dllname, +proc glVertexStream4sv*(stream: TGLenum, coords: TGLshort){.dynlib: dllname, importc: "glVertexStream4sv".} -proc glVertexStream4iv*(stream: TGLenum, coords: TGLint){.dynlib: dllname, +proc glVertexStream4iv*(stream: TGLenum, coords: TGLint){.dynlib: dllname, importc: "glVertexStream4iv".} -proc glVertexStream4fv*(stream: TGLenum, coords: TGLfloat){.dynlib: dllname, +proc glVertexStream4fv*(stream: TGLenum, coords: TGLfloat){.dynlib: dllname, importc: "glVertexStream4fv".} -proc glVertexStream4dv*(stream: TGLenum, coords: TGLdouble){.dynlib: dllname, +proc glVertexStream4dv*(stream: TGLenum, coords: TGLdouble){.dynlib: dllname, importc: "glVertexStream4dv".} -proc glNormalStream3b*(stream: TGLenum, coords: TGLByte){.dynlib: dllname, +proc glNormalStream3b*(stream: TGLenum, coords: TGLByte){.dynlib: dllname, importc: "glNormalStream3b".} -proc glNormalStream3s*(stream: TGLenum, coords: TGLshort){.dynlib: dllname, +proc glNormalStream3s*(stream: TGLenum, coords: TGLshort){.dynlib: dllname, importc: "glNormalStream3s".} -proc glNormalStream3i*(stream: TGLenum, coords: TGLint){.dynlib: dllname, +proc glNormalStream3i*(stream: TGLenum, coords: TGLint){.dynlib: dllname, importc: "glNormalStream3i".} -proc glNormalStream3f*(stream: TGLenum, coords: TGLfloat){.dynlib: dllname, +proc glNormalStream3f*(stream: TGLenum, coords: TGLfloat){.dynlib: dllname, importc: "glNormalStream3f".} -proc glNormalStream3d*(stream: TGLenum, coords: TGLdouble){.dynlib: dllname, +proc glNormalStream3d*(stream: TGLenum, coords: TGLdouble){.dynlib: dllname, importc: "glNormalStream3d".} -proc glNormalStream3bv*(stream: TGLenum, coords: TGLByte){.dynlib: dllname, +proc glNormalStream3bv*(stream: TGLenum, coords: TGLByte){.dynlib: dllname, importc: "glNormalStream3bv".} -proc glNormalStream3sv*(stream: TGLenum, coords: TGLshort){.dynlib: dllname, +proc glNormalStream3sv*(stream: TGLenum, coords: TGLshort){.dynlib: dllname, importc: "glNormalStream3sv".} -proc glNormalStream3iv*(stream: TGLenum, coords: TGLint){.dynlib: dllname, +proc glNormalStream3iv*(stream: TGLenum, coords: TGLint){.dynlib: dllname, importc: "glNormalStream3iv".} -proc glNormalStream3fv*(stream: TGLenum, coords: TGLfloat){.dynlib: dllname, +proc glNormalStream3fv*(stream: TGLenum, coords: TGLfloat){.dynlib: dllname, importc: "glNormalStream3fv".} -proc glNormalStream3dv*(stream: TGLenum, coords: TGLdouble){.dynlib: dllname, +proc glNormalStream3dv*(stream: TGLenum, coords: TGLdouble){.dynlib: dllname, importc: "glNormalStream3dv".} -proc glClientActiveVertexStream*(stream: TGLenum){.dynlib: dllname, +proc glClientActiveVertexStream*(stream: TGLenum){.dynlib: dllname, importc: "glClientActiveVertexStream".} -proc glVertexBlendEnvi*(pname: TGLenum, param: TGLint){.dynlib: dllname, +proc glVertexBlendEnvi*(pname: TGLenum, param: TGLint){.dynlib: dllname, importc: "glVertexBlendEnvi".} -proc glVertexBlendEnvf*(pname: TGLenum, param: TGLfloat){.dynlib: dllname, +proc glVertexBlendEnvf*(pname: TGLenum, param: TGLfloat){.dynlib: dllname, importc: "glVertexBlendEnvf".} #***** GL_3DFX_texture_compression_FXT1 *****// -const +const GL_COMPRESSED_RGB_FXT1_3DFX* = 0x000086B0 GL_COMPRESSED_RGBA_FXT1_3DFX* = 0x000086B1 #***** GL_IBM_cull_vertex *****// -const +const GL_CULL_VERTEX_IBM* = 0x0001928A #***** GL_IBM_multimode_draw_arrays *****// -proc glMultiModeDrawArraysIBM*(mode: PGLenum, first: PGLint, count: PGLsizei, +proc glMultiModeDrawArraysIBM*(mode: PGLenum, first: PGLint, count: PGLsizei, primcount: TGLsizei, modestride: TGLint){. dynlib: dllname, importc: "glMultiModeDrawArraysIBM".} -proc glMultiModeDrawElementsIBM*(mode: PGLenum, count: PGLsizei, - thetype: TGLenum, indices: PGLvoid, +proc glMultiModeDrawElementsIBM*(mode: PGLenum, count: PGLsizei, + thetype: TGLenum, indices: PGLvoid, primcount: TGLsizei, modestride: TGLint){. dynlib: dllname, importc: "glMultiModeDrawElementsIBM".} #***** GL_IBM_raster_pos_clip *****// -const +const GL_RASTER_POSITION_UNCLIPPED_IBM* = 0x00019262 #***** GL_IBM_texture_mirrored_repeat *****// -const +const GL_MIRRORED_REPEAT_IBM* = 0x00008370 #***** GL_IBM_vertex_array_lists *****// -const +const GL_VERTEX_ARRAY_LIST_IBM* = 0x0001929E GL_NORMAL_ARRAY_LIST_IBM* = 0x0001929F GL_COLOR_ARRAY_LIST_IBM* = 0x000192A0 @@ -2970,62 +2970,62 @@ const GL_FOG_COORDINATE_ARRAY_LIST_STRIDE_IBM* = 0x000192AE GL_SECONDARY_COLOR_ARRAY_LIST_STRIDE_IBM* = 0x000192AF -proc glColorPointerListIBM*(size: TGLint, thetype: TGLenum, stride: TGLint, +proc glColorPointerListIBM*(size: TGLint, thetype: TGLenum, stride: TGLint, pointer: PGLvoid, ptrstride: TGLint){. dynlib: dllname, importc: "glColorPointerListIBM".} -proc glSecondaryColorPointerListIBM*(size: TGLint, thetype: TGLenum, - stride: TGLint, pointer: PGLvoid, - ptrstride: TGLint){.dynlib: dllname, +proc glSecondaryColorPointerListIBM*(size: TGLint, thetype: TGLenum, + stride: TGLint, pointer: PGLvoid, + ptrstride: TGLint){.dynlib: dllname, importc: "glSecondaryColorPointerListIBM".} -proc glEdgeFlagPointerListIBM*(stride: TGLint, pointer: PGLboolean, - ptrstride: TGLint){.dynlib: dllname, +proc glEdgeFlagPointerListIBM*(stride: TGLint, pointer: PGLboolean, + ptrstride: TGLint){.dynlib: dllname, importc: "glEdgeFlagPointerListIBM".} -proc glFogCoordPointerListIBM*(thetype: TGLenum, stride: TGLint, +proc glFogCoordPointerListIBM*(thetype: TGLenum, stride: TGLint, pointer: PGLvoid, ptrstride: TGLint){. dynlib: dllname, importc: "glFogCoordPointerListIBM".} -proc glNormalPointerListIBM*(thetype: TGLenum, stride: TGLint, pointer: PGLvoid, - ptrstride: TGLint){.dynlib: dllname, +proc glNormalPointerListIBM*(thetype: TGLenum, stride: TGLint, pointer: PGLvoid, + ptrstride: TGLint){.dynlib: dllname, importc: "glNormalPointerListIBM".} -proc glTexCoordPointerListIBM*(size: TGLint, thetype: TGLenum, stride: TGLint, +proc glTexCoordPointerListIBM*(size: TGLint, thetype: TGLenum, stride: TGLint, pointer: PGLvoid, ptrstride: TGLint){. dynlib: dllname, importc: "glTexCoordPointerListIBM".} -proc glVertexPointerListIBM*(size: TGLint, thetype: TGLenum, stride: TGLint, +proc glVertexPointerListIBM*(size: TGLint, thetype: TGLenum, stride: TGLint, pointer: PGLvoid, ptrstride: TGLint){. dynlib: dllname, importc: "glVertexPointerListIBM".} #***** GL_MESA_resize_buffers *****// proc glResizeBuffersMESA*(){.dynlib: dllname, importc: "glResizeBuffersMESA".} #***** GL_MESA_window_pos *****// -proc glWindowPos2dMESA*(x: TGLdouble, y: TGLdouble){.dynlib: dllname, +proc glWindowPos2dMESA*(x: TGLdouble, y: TGLdouble){.dynlib: dllname, importc: "glWindowPos2dMESA".} -proc glWindowPos2fMESA*(x: TGLfloat, y: TGLfloat){.dynlib: dllname, +proc glWindowPos2fMESA*(x: TGLfloat, y: TGLfloat){.dynlib: dllname, importc: "glWindowPos2fMESA".} -proc glWindowPos2iMESA*(x: TGLint, y: TGLint){.dynlib: dllname, +proc glWindowPos2iMESA*(x: TGLint, y: TGLint){.dynlib: dllname, importc: "glWindowPos2iMESA".} -proc glWindowPos2sMESA*(x: TGLshort, y: TGLshort){.dynlib: dllname, +proc glWindowPos2sMESA*(x: TGLshort, y: TGLshort){.dynlib: dllname, importc: "glWindowPos2sMESA".} -proc glWindowPos2ivMESA*(p: PGLint){.dynlib: dllname, +proc glWindowPos2ivMESA*(p: PGLint){.dynlib: dllname, importc: "glWindowPos2ivMESA".} -proc glWindowPos2svMESA*(p: PGLshort){.dynlib: dllname, +proc glWindowPos2svMESA*(p: PGLshort){.dynlib: dllname, importc: "glWindowPos2svMESA".} -proc glWindowPos2fvMESA*(p: PGLfloat){.dynlib: dllname, +proc glWindowPos2fvMESA*(p: PGLfloat){.dynlib: dllname, importc: "glWindowPos2fvMESA".} -proc glWindowPos2dvMESA*(p: PGLdouble){.dynlib: dllname, +proc glWindowPos2dvMESA*(p: PGLdouble){.dynlib: dllname, importc: "glWindowPos2dvMESA".} -proc glWindowPos3iMESA*(x: TGLint, y: TGLint, z: TGLint){.dynlib: dllname, +proc glWindowPos3iMESA*(x: TGLint, y: TGLint, z: TGLint){.dynlib: dllname, importc: "glWindowPos3iMESA".} -proc glWindowPos3sMESA*(x: TGLshort, y: TGLshort, z: TGLshort){.dynlib: dllname, +proc glWindowPos3sMESA*(x: TGLshort, y: TGLshort, z: TGLshort){.dynlib: dllname, importc: "glWindowPos3sMESA".} -proc glWindowPos3fMESA*(x: TGLfloat, y: TGLfloat, z: TGLfloat){.dynlib: dllname, +proc glWindowPos3fMESA*(x: TGLfloat, y: TGLfloat, z: TGLfloat){.dynlib: dllname, importc: "glWindowPos3fMESA".} proc glWindowPos3dMESA*(x: TGLdouble, y: TGLdouble, z: TGLdouble){. dynlib: dllname, importc: "glWindowPos3dMESA".} -proc glWindowPos3ivMESA*(p: PGLint){.dynlib: dllname, +proc glWindowPos3ivMESA*(p: PGLint){.dynlib: dllname, importc: "glWindowPos3ivMESA".} -proc glWindowPos3svMESA*(p: PGLshort){.dynlib: dllname, +proc glWindowPos3svMESA*(p: PGLshort){.dynlib: dllname, importc: "glWindowPos3svMESA".} -proc glWindowPos3fvMESA*(p: PGLfloat){.dynlib: dllname, +proc glWindowPos3fvMESA*(p: PGLfloat){.dynlib: dllname, importc: "glWindowPos3fvMESA".} -proc glWindowPos3dvMESA*(p: PGLdouble){.dynlib: dllname, +proc glWindowPos3dvMESA*(p: PGLdouble){.dynlib: dllname, importc: "glWindowPos3dvMESA".} proc glWindowPos4iMESA*(x: TGLint, y: TGLint, z: TGLint, w: TGLint){. dynlib: dllname, importc: "glWindowPos4iMESA".} @@ -3035,21 +3035,21 @@ proc glWindowPos4fMESA*(x: TGLfloat, y: TGLfloat, z: TGLfloat, w: TGLfloat){. dynlib: dllname, importc: "glWindowPos4fMESA".} proc glWindowPos4dMESA*(x: TGLdouble, y: TGLdouble, z: TGLdouble, w: TGLdouble){. dynlib: dllname, importc: "glWindowPos4dMESA".} -proc glWindowPos4ivMESA*(p: PGLint){.dynlib: dllname, +proc glWindowPos4ivMESA*(p: PGLint){.dynlib: dllname, importc: "glWindowPos4ivMESA".} -proc glWindowPos4svMESA*(p: PGLshort){.dynlib: dllname, +proc glWindowPos4svMESA*(p: PGLshort){.dynlib: dllname, importc: "glWindowPos4svMESA".} -proc glWindowPos4fvMESA*(p: PGLfloat){.dynlib: dllname, +proc glWindowPos4fvMESA*(p: PGLfloat){.dynlib: dllname, importc: "glWindowPos4fvMESA".} -proc glWindowPos4dvMESA*(p: PGLdouble){.dynlib: dllname, +proc glWindowPos4dvMESA*(p: PGLdouble){.dynlib: dllname, importc: "glWindowPos4dvMESA".} #***** GL_OML_interlace *****// -const +const GL_INTERLACE_OML* = 0x00008980 GL_INTERLACE_READ_OML* = 0x00008981 #***** GL_OML_resample *****// -const +const GL_PACK_RESAMPLE_OML* = 0x00008984 GL_UNPACK_RESAMPLE_OML* = 0x00008985 GL_RESAMPLE_REPLICATE_OML* = 0x00008986 @@ -3058,17 +3058,17 @@ const GL_RESAMPLE_DECIMATE_OML* = 0x00008989 # GL_RESAMPLE_AVERAGE_OML { already defined } #***** GL_OML_subsample *****// -const +const GL_FORMAT_SUBSAMPLE_24_24_OML* = 0x00008982 GL_FORMAT_SUBSAMPLE_244_244_OML* = 0x00008983 #***** GL_SGIS_generate_mipmap *****// -const +const GL_GENERATE_MIPMAP_SGIS* = 0x00008191 GL_GENERATE_MIPMAP_HINT_SGIS* = 0x00008192 #***** GL_SGIS_multisample *****// -const +const GLX_SAMPLE_BUFFERS_SGIS* = 0x000186A0 GLX_SAMPLES_SGIS* = 0x000186A1 GL_MULTISAMPLE_SGIS* = 0x0000809D @@ -3089,12 +3089,12 @@ const GL_SAMPLE_MASK_INVERT_SGIS* = 0x000080AB constGL_SAMPLE_PATTERN_SGIS* = 0x000080AC -proc glSampleMaskSGIS*(value: TGLclampf, invert: TGLboolean){.dynlib: dllname, +proc glSampleMaskSGIS*(value: TGLclampf, invert: TGLboolean){.dynlib: dllname, importc: "glSampleMaskSGIS".} -proc glSamplePatternSGIS*(pattern: TGLenum){.dynlib: dllname, +proc glSamplePatternSGIS*(pattern: TGLenum){.dynlib: dllname, importc: "glSamplePatternSGIS".} #***** GL_SGIS_pixel_texture *****// -const +const GL_PIXEL_TEXTURE_SGIS* = 0x00008353 GL_PIXEL_FRAGMENT_RGB_SOURCE_SGIS* = 0x00008354 GL_PIXEL_FRAGMENT_ALPHA_SOURCE_SGIS* = 0x00008355 @@ -3111,44 +3111,44 @@ proc glGetPixelTexGenParameterfvSGIS*(pname: TGLenum, params: TGLfloat){. #***** GL_SGIS_texture_border_clamp *****// # GL_CLAMP_TO_BORDER_SGIS { already defined } #***** GL_SGIS_texture_color_mask *****// -const +const GL_TEXTURE_COLOR_WRITEMASK_SGIS* = 0x000081EF -proc glTextureColorMaskSGIS*(r: TGLboolean, g: TGLboolean, b: TGLboolean, - a: TGLboolean){.dynlib: dllname, +proc glTextureColorMaskSGIS*(r: TGLboolean, g: TGLboolean, b: TGLboolean, + a: TGLboolean){.dynlib: dllname, importc: "glTextureColorMaskSGIS".} #***** GL_SGIS_texture_edge_clamp *****// -const +const GL_CLAMP_TO_EDGE_SGIS* = 0x0000812F #***** GL_SGIS_texture_lod *****// -const +const GL_TEXTURE_MIN_LOD_SGIS* = 0x0000813A GL_TEXTURE_MAX_LOD_SGIS* = 0x0000813B GL_TEXTURE_BASE_LEVEL_SGIS* = 0x0000813C GL_TEXTURE_MAX_LEVEL_SGIS* = 0x0000813D #***** GL_SGIS_depth_texture *****// -const +const GL_DEPTH_COMPONENT16_SGIX* = 0x000081A5 GL_DEPTH_COMPONENT24_SGIX* = 0x000081A6 GL_DEPTH_COMPONENT32_SGIX* = 0x000081A7 #***** GL_SGIX_fog_offset *****// -const +const GL_FOG_OFFSET_SGIX* = 0x00008198 GL_FOG_OFFSET_VALUE_SGIX* = 0x00008199 #***** GL_SGIX_interlace *****// -const +const GL_INTERLACE_SGIX* = 0x00008094 #***** GL_SGIX_shadow_ambient *****// -const +const GL_SHADOW_AMBIENT_SGIX* = 0x000080BF #***** GL_SGI_color_matrix *****// -const +const GL_COLOR_MATRIX_SGI* = 0x000080B1 GL_COLOR_MATRIX_STACK_DEPTH_SGI* = 0x000080B2 GL_MAX_COLOR_MATRIX_STACK_DEPTH_SGI* = 0x000080B3 @@ -3162,7 +3162,7 @@ const GL_POST_COLOR_MATRIX_ALPHA_BIAS_SGI* = 0x000080BB #***** GL_SGI_color_table *****// -const +const constGL_COLOR_TABLE_SGI* = 0x000080D0 GL_POST_CONVOLUTION_COLOR_TABLE_SGI* = 0x000080D1 GL_POST_COLOR_MATRIX_COLOR_TABLE_SGI* = 0x000080D2 @@ -3180,151 +3180,151 @@ const GL_COLOR_TABLE_LUMINANCE_SIZE_SGI* = 0x000080DE GL_COLOR_TABLE_INTENSITY_SIZE_SGI* = 0x000080DF -proc glColorTableSGI*(target: TGLenum, internalformat: TGLenum, width: TGLsizei, +proc glColorTableSGI*(target: TGLenum, internalformat: TGLenum, width: TGLsizei, format: TGLenum, thetype: TGLenum, table: PGLvoid){. dynlib: dllname, importc: "glColorTableSGI".} -proc glCopyColorTableSGI*(target: TGLenum, internalformat: TGLenum, x: TGLint, - y: TGLint, width: TGLsizei){.dynlib: dllname, +proc glCopyColorTableSGI*(target: TGLenum, internalformat: TGLenum, x: TGLint, + y: TGLint, width: TGLsizei){.dynlib: dllname, importc: "glCopyColorTableSGI".} proc glColorTableParameterivSGI*(target: TGLenum, pname: TGLenum, params: PGLint){. dynlib: dllname, importc: "glColorTableParameterivSGI".} -proc glColorTableParameterfvSGI*(target: TGLenum, pname: TGLenum, - params: PGLfloat){.dynlib: dllname, +proc glColorTableParameterfvSGI*(target: TGLenum, pname: TGLenum, + params: PGLfloat){.dynlib: dllname, importc: "glColorTableParameterfvSGI".} -proc glGetColorTableSGI*(target: TGLenum, format: TGLenum, thetype: TGLenum, - table: PGLvoid){.dynlib: dllname, +proc glGetColorTableSGI*(target: TGLenum, format: TGLenum, thetype: TGLenum, + table: PGLvoid){.dynlib: dllname, importc: "glGetColorTableSGI".} -proc glGetColorTableParameterivSGI*(target: TGLenum, pname: TGLenum, - params: PGLint){.dynlib: dllname, +proc glGetColorTableParameterivSGI*(target: TGLenum, pname: TGLenum, + params: PGLint){.dynlib: dllname, importc: "glGetColorTableParameterivSGI".} -proc glGetColorTableParameterfvSGI*(target: TGLenum, pname: TGLenum, - params: PGLfloat){.dynlib: dllname, +proc glGetColorTableParameterfvSGI*(target: TGLenum, pname: TGLenum, + params: PGLfloat){.dynlib: dllname, importc: "glGetColorTableParameterfvSGI".} #***** GL_SGI_texture_color_table *****// -const +const GL_TEXTURE_COLOR_TABLE_SGI* = 0x000080BC GL_PROXY_TEXTURE_COLOR_TABLE_SGI* = 0x000080BD #***** GL_SUN_vertex *****// -proc glColor4ubVertex2fSUN*(r: TGLubyte, g: TGLubyte, b: TGLubyte, a: TGLubyte, - x: TGLfloat, y: TGLfloat){.dynlib: dllname, +proc glColor4ubVertex2fSUN*(r: TGLubyte, g: TGLubyte, b: TGLubyte, a: TGLubyte, + x: TGLfloat, y: TGLfloat){.dynlib: dllname, importc: "glColor4ubVertex2fSUN".} -proc glColor4ubVertex2fvSUN*(c: PGLubyte, v: PGLfloat){.dynlib: dllname, +proc glColor4ubVertex2fvSUN*(c: PGLubyte, v: PGLfloat){.dynlib: dllname, importc: "glColor4ubVertex2fvSUN".} -proc glColor4ubVertex3fSUN*(r: TGLubyte, g: TGLubyte, b: TGLubyte, a: TGLubyte, +proc glColor4ubVertex3fSUN*(r: TGLubyte, g: TGLubyte, b: TGLubyte, a: TGLubyte, x: TGLfloat, y: TGLfloat, z: TGLfloat){. dynlib: dllname, importc: "glColor4ubVertex3fSUN".} -proc glColor4ubVertex3fvSUN*(c: PGLubyte, v: PGLfloat){.dynlib: dllname, +proc glColor4ubVertex3fvSUN*(c: PGLubyte, v: PGLfloat){.dynlib: dllname, importc: "glColor4ubVertex3fvSUN".} -proc glColor3fVertex3fSUN*(r: TGLfloat, g: TGLfloat, b: TGLfloat, x: TGLfloat, - y: TGLfloat, z: TGLfloat){.dynlib: dllname, +proc glColor3fVertex3fSUN*(r: TGLfloat, g: TGLfloat, b: TGLfloat, x: TGLfloat, + y: TGLfloat, z: TGLfloat){.dynlib: dllname, importc: "glColor3fVertex3fSUN".} -proc glColor3fVertex3fvSUN*(c: PGLfloat, v: PGLfloat){.dynlib: dllname, +proc glColor3fVertex3fvSUN*(c: PGLfloat, v: PGLfloat){.dynlib: dllname, importc: "glColor3fVertex3fvSUN".} -proc glNormal3fVertex3fSUN*(nx: TGLfloat, ny: TGLfloat, nz: TGLfloat, +proc glNormal3fVertex3fSUN*(nx: TGLfloat, ny: TGLfloat, nz: TGLfloat, x: TGLfloat, y: TGLfloat, z: TGLfloat){. dynlib: dllname, importc: "glNormal3fVertex3fSUN".} -proc glNormal3fVertex3fvSUN*(n: PGLfloat, v: PGLfloat){.dynlib: dllname, +proc glNormal3fVertex3fvSUN*(n: PGLfloat, v: PGLfloat){.dynlib: dllname, importc: "glNormal3fVertex3fvSUN".} -proc glColor4fNormal3fVertex3fSUN*(r: TGLfloat, g: TGLfloat, b: TGLfloat, - a: TGLfloat, nx: TGLfloat, ny: TGLfloat, - nz: TGLfloat, x: TGLfloat, y: TGLfloat, - z: TGLfloat){.dynlib: dllname, +proc glColor4fNormal3fVertex3fSUN*(r: TGLfloat, g: TGLfloat, b: TGLfloat, + a: TGLfloat, nx: TGLfloat, ny: TGLfloat, + nz: TGLfloat, x: TGLfloat, y: TGLfloat, + z: TGLfloat){.dynlib: dllname, importc: "glColor4fNormal3fVertex3fSUN".} proc glColor4fNormal3fVertex3fvSUN*(c: PGLfloat, n: PGLfloat, v: PGLfloat){. dynlib: dllname, importc: "glColor4fNormal3fVertex3fvSUN".} -proc glTexCoord2fVertex3fSUN*(s: TGLfloat, t: TGLfloat, x: TGLfloat, - y: TGLfloat, z: TGLfloat){.dynlib: dllname, +proc glTexCoord2fVertex3fSUN*(s: TGLfloat, t: TGLfloat, x: TGLfloat, + y: TGLfloat, z: TGLfloat){.dynlib: dllname, importc: "glTexCoord2fVertex3fSUN".} -proc glTexCoord2fVertex3fvSUN*(tc: PGLfloat, v: PGLfloat){.dynlib: dllname, +proc glTexCoord2fVertex3fvSUN*(tc: PGLfloat, v: PGLfloat){.dynlib: dllname, importc: "glTexCoord2fVertex3fvSUN".} -proc glTexCoord4fVertex4fSUN*(s: TGLfloat, t: TGLfloat, p: TGLfloat, - q: TGLfloat, x: TGLfloat, y: TGLfloat, - z: TGLfloat, w: TGLfloat){.dynlib: dllname, +proc glTexCoord4fVertex4fSUN*(s: TGLfloat, t: TGLfloat, p: TGLfloat, + q: TGLfloat, x: TGLfloat, y: TGLfloat, + z: TGLfloat, w: TGLfloat){.dynlib: dllname, importc: "glTexCoord4fVertex4fSUN".} -proc glTexCoord4fVertex4fvSUN*(tc: PGLfloat, v: PGLfloat){.dynlib: dllname, +proc glTexCoord4fVertex4fvSUN*(tc: PGLfloat, v: PGLfloat){.dynlib: dllname, importc: "glTexCoord4fVertex4fvSUN".} -proc glTexCoord2fColor4ubVertex3fSUN*(s: TGLfloat, t: TGLfloat, r: TGLubyte, - g: TGLubyte, b: TGLubyte, a: TGLubyte, +proc glTexCoord2fColor4ubVertex3fSUN*(s: TGLfloat, t: TGLfloat, r: TGLubyte, + g: TGLubyte, b: TGLubyte, a: TGLubyte, x: TGLfloat, y: TGLfloat, z: TGLfloat){. dynlib: dllname, importc: "glTexCoord2fColor4ubVertex3fSUN".} proc glTexCoord2fColor4ubVertex3fvSUN*(tc: PGLfloat, c: PGLubyte, v: PGLfloat){. dynlib: dllname, importc: "glTexCoord2fColor4ubVertex3fvSUN".} -proc glTexCoord2fColor3fVertex3fSUN*(s: TGLfloat, t: TGLfloat, r: TGLfloat, - g: TGLfloat, b: TGLfloat, x: TGLfloat, - y: TGLfloat, z: TGLfloat){.dynlib: dllname, +proc glTexCoord2fColor3fVertex3fSUN*(s: TGLfloat, t: TGLfloat, r: TGLfloat, + g: TGLfloat, b: TGLfloat, x: TGLfloat, + y: TGLfloat, z: TGLfloat){.dynlib: dllname, importc: "glTexCoord2fColor3fVertex3fSUN".} proc glTexCoord2fColor3fVertex3fvSUN*(tc: PGLfloat, c: PGLfloat, v: PGLfloat){. dynlib: dllname, importc: "glTexCoord2fColor3fVertex3fvSUN".} -proc glTexCoord2fNormal3fVertex3fSUN*(s: TGLfloat, t: TGLfloat, nx: TGLfloat, - ny: TGLfloat, nz: TGLfloat, x: TGLfloat, +proc glTexCoord2fNormal3fVertex3fSUN*(s: TGLfloat, t: TGLfloat, nx: TGLfloat, + ny: TGLfloat, nz: TGLfloat, x: TGLfloat, y: TGLfloat, z: TGLfloat){. dynlib: dllname, importc: "glTexCoord2fNormal3fVertex3fSUN".} proc glTexCoord2fNormal3fVertex3fvSUN*(tc: PGLfloat, n: PGLfloat, v: PGLfloat){. dynlib: dllname, importc: "glTexCoord2fNormal3fVertex3fvSUN".} -proc glTexCoord2fColor4fNormal3fVertex3fSUN*(s: TGLfloat, t: TGLfloat, - r: TGLfloat, g: TGLfloat, b: TGLfloat, a: TGLfloat, nx: TGLfloat, +proc glTexCoord2fColor4fNormal3fVertex3fSUN*(s: TGLfloat, t: TGLfloat, + r: TGLfloat, g: TGLfloat, b: TGLfloat, a: TGLfloat, nx: TGLfloat, ny: TGLfloat, nz: TGLfloat, x: TGLfloat, y: TGLfloat, z: TGLfloat){. dynlib: dllname, importc: "glTexCoord2fColor4fNormal3fVertex3fSUN".} -proc glTexCoord2fColor4fNormal3fVertex3fvSUN*(tc: PGLfloat, c: PGLfloat, +proc glTexCoord2fColor4fNormal3fVertex3fvSUN*(tc: PGLfloat, c: PGLfloat, n: PGLfloat, v: PGLfloat){.dynlib: dllname, importc: "glTexCoord2fColor4fNormal3fVertex3fvSUN".} -proc glTexCoord4fColor4fNormal3fVertex4fSUN*(s: TGLfloat, t: TGLfloat, - p: TGLfloat, q: TGLfloat, r: TGLfloat, g: TGLfloat, b: TGLfloat, - a: TGLfloat, nx: TGLfloat, ny: TGLfloat, nz: TGLfloat, x: TGLfloat, - y: TGLfloat, z: TGLfloat, w: TGLfloat){.dynlib: dllname, +proc glTexCoord4fColor4fNormal3fVertex4fSUN*(s: TGLfloat, t: TGLfloat, + p: TGLfloat, q: TGLfloat, r: TGLfloat, g: TGLfloat, b: TGLfloat, + a: TGLfloat, nx: TGLfloat, ny: TGLfloat, nz: TGLfloat, x: TGLfloat, + y: TGLfloat, z: TGLfloat, w: TGLfloat){.dynlib: dllname, importc: "glTexCoord4fColor4fNormal3fVertex4fSUN".} -proc glTexCoord4fColor4fNormal3fVertex4fvSUN*(tc: PGLfloat, c: PGLfloat, +proc glTexCoord4fColor4fNormal3fVertex4fvSUN*(tc: PGLfloat, c: PGLfloat, n: PGLfloat, v: PGLfloat){.dynlib: dllname, importc: "glTexCoord4fColor4fNormal3fVertex4fvSUN".} -proc glReplacementCodeuiVertex3fSUN*(rc: TGLuint, x: TGLfloat, y: TGLfloat, - z: TGLfloat){.dynlib: dllname, +proc glReplacementCodeuiVertex3fSUN*(rc: TGLuint, x: TGLfloat, y: TGLfloat, + z: TGLfloat){.dynlib: dllname, importc: "glReplacementCodeuiVertex3fSUN".} proc glReplacementCodeuiVertex3fvSUN*(rc: PGLuint, v: PGLfloat){. dynlib: dllname, importc: "glReplacementCodeuiVertex3fvSUN".} -proc glReplacementCodeuiColor4ubVertex3fSUN*(rc: TGLuint, r: TGLubyte, +proc glReplacementCodeuiColor4ubVertex3fSUN*(rc: TGLuint, r: TGLubyte, g: TGLubyte, b: TGLubyte, a: TGLubyte, x: TGLfloat, y: TGLfloat, z: TGLfloat){. dynlib: dllname, importc: "glReplacementCodeuiColor4ubVertex3fSUN".} -proc glReplacementCodeuiColor4ubVertex3fvSUN*(rc: PGLuint, c: PGLubyte, - v: PGLfloat){.dynlib: dllname, +proc glReplacementCodeuiColor4ubVertex3fvSUN*(rc: PGLuint, c: PGLubyte, + v: PGLfloat){.dynlib: dllname, importc: "glReplacementCodeuiColor4ubVertex3fvSUN".} -proc glReplacementCodeuiColor3fVertex3fSUN*(rc: TGLuint, r: TGLfloat, +proc glReplacementCodeuiColor3fVertex3fSUN*(rc: TGLuint, r: TGLfloat, g: TGLfloat, b: TGLfloat, x: TGLfloat, y: TGLfloat, z: TGLfloat){. dynlib: dllname, importc: "glReplacementCodeuiColor3fVertex3fSUN".} -proc glReplacementCodeuiColor3fVertex3fvSUN*(rc: PGLuint, c: PGLfloat, - v: PGLfloat){.dynlib: dllname, +proc glReplacementCodeuiColor3fVertex3fvSUN*(rc: PGLuint, c: PGLfloat, + v: PGLfloat){.dynlib: dllname, importc: "glReplacementCodeuiColor3fVertex3fvSUN".} -proc glReplacementCodeuiNormal3fVertex3fSUN*(rc: TGLuint, nx: TGLfloat, +proc glReplacementCodeuiNormal3fVertex3fSUN*(rc: TGLuint, nx: TGLfloat, ny: TGLfloat, nz: TGLfloat, x: TGLfloat, y: TGLfloat, z: TGLfloat){. dynlib: dllname, importc: "glReplacementCodeuiNormal3fVertex3fSUN".} -proc glReplacementCodeuiNormal3fVertex3fvSUN*(rc: PGLuint, n: PGLfloat, - v: PGLfloat){.dynlib: dllname, +proc glReplacementCodeuiNormal3fVertex3fvSUN*(rc: PGLuint, n: PGLfloat, + v: PGLfloat){.dynlib: dllname, importc: "glReplacementCodeuiNormal3fVertex3fvSUN".} -proc glReplacementCodeuiColor4fNormal3fVertex3fSUN*(rc: TGLuint, r: TGLfloat, - g: TGLfloat, b: TGLfloat, a: TGLfloat, nx: TGLfloat, ny: TGLfloat, - nz: TGLfloat, x: TGLfloat, y: TGLfloat, z: TGLfloat){.dynlib: dllname, +proc glReplacementCodeuiColor4fNormal3fVertex3fSUN*(rc: TGLuint, r: TGLfloat, + g: TGLfloat, b: TGLfloat, a: TGLfloat, nx: TGLfloat, ny: TGLfloat, + nz: TGLfloat, x: TGLfloat, y: TGLfloat, z: TGLfloat){.dynlib: dllname, importc: "glReplacementCodeuiColor4fNormal3fVertex3fSUN".} -proc glReplacementCodeuiColor4fNormal3fVertex3fvSUN*(rc: PGLuint, c: PGLfloat, +proc glReplacementCodeuiColor4fNormal3fVertex3fvSUN*(rc: PGLuint, c: PGLfloat, n: PGLfloat, v: PGLfloat){.dynlib: dllname, importc: "glReplacementCodeuiColor4fNormal3fVertex3fvSUN".} -proc glReplacementCodeuiTexCoord2fVertex3fSUN*(rc: TGLuint, s: TGLfloat, - t: TGLfloat, x: TGLfloat, y: TGLfloat, z: TGLfloat){.dynlib: dllname, +proc glReplacementCodeuiTexCoord2fVertex3fSUN*(rc: TGLuint, s: TGLfloat, + t: TGLfloat, x: TGLfloat, y: TGLfloat, z: TGLfloat){.dynlib: dllname, importc: "glReplacementCodeuiTexCoord2fVertex3fSUN".} -proc glReplacementCodeuiTexCoord2fVertex3fvSUN*(rc: PGLuint, tc: PGLfloat, - v: PGLfloat){.dynlib: dllname, +proc glReplacementCodeuiTexCoord2fVertex3fvSUN*(rc: PGLuint, tc: PGLfloat, + v: PGLfloat){.dynlib: dllname, importc: "glReplacementCodeuiTexCoord2fVertex3fvSUN".} -proc glReplacementCodeuiTexCoord2fNormal3fVertex3fSUN*(rc: TGLuint, s: TGLfloat, - t: TGLfloat, nx: TGLfloat, ny: TGLfloat, nz: TGLfloat, x: TGLfloat, +proc glReplacementCodeuiTexCoord2fNormal3fVertex3fSUN*(rc: TGLuint, s: TGLfloat, + t: TGLfloat, nx: TGLfloat, ny: TGLfloat, nz: TGLfloat, x: TGLfloat, y: TGLfloat, z: TGLfloat){.dynlib: dllname, importc: "glReplacementCodeuiTexCoord2fNormal3fVertex3fSUN".} -proc glReplacementCodeuiTexCoord2fNormal3fVertex3fvSUN*(rc: PGLuint, - tc: PGLfloat, n: PGLfloat, v: PGLfloat){.dynlib: dllname, +proc glReplacementCodeuiTexCoord2fNormal3fVertex3fvSUN*(rc: PGLuint, + tc: PGLfloat, n: PGLfloat, v: PGLfloat){.dynlib: dllname, importc: "glReplacementCodeuiTexCoord2fNormal3fVertex3fvSUN".} -proc glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fSUN*(rc: TGLuint, - s: TGLfloat, t: TGLfloat, r: TGLfloat, g: TGLfloat, b: TGLfloat, - a: TGLfloat, nx: TGLfloat, ny: TGLfloat, nz: TGLfloat, x: TGLfloat, +proc glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fSUN*(rc: TGLuint, + s: TGLfloat, t: TGLfloat, r: TGLfloat, g: TGLfloat, b: TGLfloat, + a: TGLfloat, nx: TGLfloat, ny: TGLfloat, nz: TGLfloat, x: TGLfloat, y: TGLfloat, z: TGLfloat){.dynlib: dllname, importc: "glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fSUN".} -proc glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fvSUN*(rc: PGLuint, - tc: PGLfloat, c: PGLfloat, n: PGLfloat, v: PGLfloat){.dynlib: dllname, +proc glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fvSUN*(rc: PGLuint, + tc: PGLfloat, c: PGLfloat, n: PGLfloat, v: PGLfloat){.dynlib: dllname, importc: "glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fvSUN".} #***** GL_ARB_fragment_program *****// -const +const GL_FRAGMENT_PROGRAM_ARB* = 0x00008804 # GL_PROGRAM_FORMAT_ASCII_ARB { already defined } # GL_PROGRAM_LENGTH_ARB { already defined } # GL_PROGRAM_FORMAT_ARB { already defined } @@ -3360,21 +3360,21 @@ const GL_MAX_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB* = 0x0000880E GL_MAX_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB* = 0x0000880F GL_MAX_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB* = 0x00008810 # GL_PROGRAM_STRING_ARB { already defined } - # - # + # + # # GL_PROGRAM_ERROR_POSITION_ARB { already defined } # GL_CURRENT_MATRIX_ARB { already defined } - # - # + # + # # GL_TRANSPOSE_CURRENT_MATRIX_ARB { already defined } - # - # + # + # # GL_CURRENT_MATRIX_STACK_DEPTH_ARB { already defined } - # - # + # + # # GL_MAX_PROGRAM_MATRICES_ARB { already defined } - # - # + # + # # GL_MAX_PROGRAM_MATRIX_STACK_DEPTH_ARB { already defined } GL_MAX_TEXTURE_COORDS_ARB* = 0x00008871 GL_MAX_TEXTURE_IMAGE_UNITS_ARB* = 0x00008872 # GL_PROGRAM_ERROR_STRING_ARB { already defined } @@ -3431,10 +3431,10 @@ const # glIsProgramARB { already defined } #***** GL_ATI_text_fragment_shader ***** -const +const GL_TEXT_FRAGMENT_SHADER_ATI* = 0x00008200 #***** GL_ARB_vertex_buffer_object ***** -const +const GL_BUFFER_SIZE_ARB* = 0x00008764 GL_BUFFER_USAGE_ARB* = 0x00008765 GL_ARRAY_BUFFER_ARB* = 0x00008892 @@ -3467,37 +3467,37 @@ const GL_DYNAMIC_READ_ARB* = 0x000088E9 GL_DYNAMIC_COPY_ARB* = 0x000088EA -proc glBindBufferARB*(target: TGLenum, buffer: TGLuint){.dynlib: dllname, +proc glBindBufferARB*(target: TGLenum, buffer: TGLuint){.dynlib: dllname, importc: "glBindBufferARB".} -proc glDeleteBuffersARB*(n: TGLsizei, buffers: PGLuint){.dynlib: dllname, +proc glDeleteBuffersARB*(n: TGLsizei, buffers: PGLuint){.dynlib: dllname, importc: "glDeleteBuffersARB".} -proc glGenBuffersARB*(n: TGLsizei, buffers: PGLuint){.dynlib: dllname, +proc glGenBuffersARB*(n: TGLsizei, buffers: PGLuint){.dynlib: dllname, importc: "glGenBuffersARB".} -proc glIsBufferARB*(buffer: TGLuint): TGLboolean{.dynlib: dllname, +proc glIsBufferARB*(buffer: TGLuint): TGLboolean{.dynlib: dllname, importc: "glIsBufferARB".} -proc glBufferDataARB*(target: TGLenum, size: TGLsizei, data: PGLvoid, - usage: TGLenum){.dynlib: dllname, +proc glBufferDataARB*(target: TGLenum, size: TGLsizei, data: PGLvoid, + usage: TGLenum){.dynlib: dllname, importc: "glBufferDataARB".} -proc glBufferSubDataARB*(target: TGLenum, offset: TGLint, size: TGLsizei, - data: PGLvoid){.dynlib: dllname, +proc glBufferSubDataARB*(target: TGLenum, offset: TGLint, size: TGLsizei, + data: PGLvoid){.dynlib: dllname, importc: "glBufferSubDataARB".} -proc glGetBufferSubDataARB*(target: TGLenum, offset: TGLint, size: TGLsizei, - data: PGLvoid){.dynlib: dllname, +proc glGetBufferSubDataARB*(target: TGLenum, offset: TGLint, size: TGLsizei, + data: PGLvoid){.dynlib: dllname, importc: "glGetBufferSubDataARB".} proc glMapBufferARB*(target: TGLenum, access: TGLenum): PGLvoid{. dynlib: dllname, importc: "glMapBufferARB".} -proc glUnmapBufferARB*(target: TGLenum): TGLboolean{.dynlib: dllname, +proc glUnmapBufferARB*(target: TGLenum): TGLboolean{.dynlib: dllname, importc: "glUnmapBufferARB".} proc glGetBufferParameterivARB*(target: TGLenum, pname: TGLenum, params: PGLint){. dynlib: dllname, importc: "glGetBufferParameterivARB".} proc glGetBufferPointervARB*(target: TGLenum, pname: TGLenum, params: PPGLvoid){. dynlib: dllname, importc: "glGetBufferPointervARB".} #***** GL_APPLE_client_storage *****// -const +const GL_UNPACK_CLIENT_STORAGE_APPLE* = 0x000085B2 #***** GL_APPLE_element_array *****// -const +const GL_ELEMENT_ARRAY_APPLE* = 0x00008768 GL_ELEMENT_ARRAY_TYPE_APPLE* = 0x00008769 GL_ELEMENT_ARRAY_POINTER_APPLE* = 0x0000876A @@ -3506,52 +3506,52 @@ proc glElementPointerAPPLE*(thetype: TGLenum, pointer: PGLvoid){. dynlib: dllname, importc: "glElementPointerAPPLE".} proc glDrawElementArrayAPPLE*(mode: TGLenum, first: TGLint, count: TGLsizei){. dynlib: dllname, importc: "glDrawElementArrayAPPLE".} -proc glDrawRangeElementArrayAPPLE*(mode: TGLenum, start: TGLuint, - theend: TGLuint, first: TGLint, - count: TGLsizei){.dynlib: dllname, +proc glDrawRangeElementArrayAPPLE*(mode: TGLenum, start: TGLuint, + theend: TGLuint, first: TGLint, + count: TGLsizei){.dynlib: dllname, importc: "glDrawRangeElementArrayAPPLE".} -proc glMultiDrawElementArrayAPPLE*(mode: TGLenum, first: PGLint, +proc glMultiDrawElementArrayAPPLE*(mode: TGLenum, first: PGLint, count: PGLsizei, primcount: TGLsizei){. dynlib: dllname, importc: "glMultiDrawElementArrayAPPLE".} -proc glMultiDrawRangeElementArrayAPPLE*(mode: TGLenum, start: TGLuint, - theend: TGLuint, first: PGLint, +proc glMultiDrawRangeElementArrayAPPLE*(mode: TGLenum, start: TGLuint, + theend: TGLuint, first: PGLint, count: PGLsizei, primcount: TGLsizei){. dynlib: dllname, importc: "glMultiDrawRangeElementArrayAPPLE".} #***** GL_APPLE_fence *****// -const +const GL_DRAW_PIXELS_APPLE* = 0x00008A0A GL_FENCE_APPLE* = 0x00008A0B -proc glGenFencesAPPLE*(n: TGLsizei, fences: PGLuint){.dynlib: dllname, +proc glGenFencesAPPLE*(n: TGLsizei, fences: PGLuint){.dynlib: dllname, importc: "glGenFencesAPPLE".} -proc glDeleteFencesAPPLE*(n: TGLsizei, fences: PGLuint){.dynlib: dllname, +proc glDeleteFencesAPPLE*(n: TGLsizei, fences: PGLuint){.dynlib: dllname, importc: "glDeleteFencesAPPLE".} -proc glSetFenceAPPLE*(fence: TGLuint){.dynlib: dllname, +proc glSetFenceAPPLE*(fence: TGLuint){.dynlib: dllname, importc: "glSetFenceAPPLE".} -proc glIsFenceAPPLE*(fence: TGLuint): TGLboolean{.dynlib: dllname, +proc glIsFenceAPPLE*(fence: TGLuint): TGLboolean{.dynlib: dllname, importc: "glIsFenceAPPLE".} -proc glTestFenceAPPLE*(fence: TGLuint): TGLboolean{.dynlib: dllname, +proc glTestFenceAPPLE*(fence: TGLuint): TGLboolean{.dynlib: dllname, importc: "glTestFenceAPPLE".} -proc glFinishFenceAPPLE*(fence: TGLuint){.dynlib: dllname, +proc glFinishFenceAPPLE*(fence: TGLuint){.dynlib: dllname, importc: "glFinishFenceAPPLE".} proc glTestObjectAPPLE*(theobject: TGLenum, name: TGLuint): TGLboolean{. dynlib: dllname, importc: "glTestObjectAPPLE".} -proc glFinishObjectAPPLE*(theobject: TGLenum, name: TGLint){.dynlib: dllname, +proc glFinishObjectAPPLE*(theobject: TGLenum, name: TGLint){.dynlib: dllname, importc: "glFinishObjectAPPLE".} #***** GL_APPLE_vertex_array_object *****// -const +const GL_VERTEX_ARRAY_BINDING_APPLE* = 0x000085B5 -proc glBindVertexArrayAPPLE*(thearray: TGLuint){.dynlib: dllname, +proc glBindVertexArrayAPPLE*(thearray: TGLuint){.dynlib: dllname, importc: "glBindVertexArrayAPPLE".} -proc glDeleteVertexArraysAPPLE*(n: TGLsizei, arrays: PGLuint){.dynlib: dllname, +proc glDeleteVertexArraysAPPLE*(n: TGLsizei, arrays: PGLuint){.dynlib: dllname, importc: "glDeleteVertexArraysAPPLE".} -proc glGenVertexArraysAPPLE*(n: TGLsizei, arrays: PGLuint){.dynlib: dllname, +proc glGenVertexArraysAPPLE*(n: TGLsizei, arrays: PGLuint){.dynlib: dllname, importc: "glGenVertexArraysAPPLE".} -proc glIsVertexArrayAPPLE*(thearray: TGLuint): TGLboolean{.dynlib: dllname, +proc glIsVertexArrayAPPLE*(thearray: TGLuint): TGLboolean{.dynlib: dllname, importc: "glIsVertexArrayAPPLE".} #***** GL_APPLE_vertex_array_range *****// -const +const constGL_VERTEX_ARRAY_RANGE_APPLE* = 0x0000851D GL_VERTEX_ARRAY_RANGE_LENGTH_APPLE* = 0x0000851E GL_MAX_VERTEX_ARRAY_RANGE_ELEMENT_APPLE* = 0x00008520 @@ -3560,14 +3560,14 @@ const GL_STORAGE_CACHED_APPLE* = 0x000085BE GL_STORAGE_SHARED_APPLE* = 0x000085BF -proc glVertexArrayRangeAPPLE*(len: TGLsizei, pointer: PGLvoid){.dynlib: dllname, +proc glVertexArrayRangeAPPLE*(len: TGLsizei, pointer: PGLvoid){.dynlib: dllname, importc: "glVertexArrayRangeAPPLE".} proc glFlushVertexArrayRangeAPPLE*(len: TGLsizei, pointer: PGLvoid){. dynlib: dllname, importc: "glFlushVertexArrayRangeAPPLE".} proc glVertexArrayParameteriAPPLE*(pname: TGLenum, param: TGLint){. dynlib: dllname, importc: "glVertexArrayParameteriAPPLE".} #***** GL_ARB_matrix_palette *****// -const +const GL_MATRIX_PALETTE_ARB* = 0x00008840 GL_MAX_MATRIX_PALETTE_STACK_DEPTH_ARB* = 0x00008841 GL_MAX_PALETTE_MATRICES_ARB* = 0x00008842 @@ -3579,38 +3579,38 @@ const GL_MATRIX_INDEX_ARRAY_STRIDE_ARB* = 0x00008848 GL_MATRIX_INDEX_ARRAY_POINTER_ARB* = 0x00008849 -proc glCurrentPaletteMatrixARB*(index: TGLint){.dynlib: dllname, +proc glCurrentPaletteMatrixARB*(index: TGLint){.dynlib: dllname, importc: "glCurrentPaletteMatrixARB".} -proc glMatrixIndexubvARB*(size: TGLint, indices: PGLubyte){.dynlib: dllname, +proc glMatrixIndexubvARB*(size: TGLint, indices: PGLubyte){.dynlib: dllname, importc: "glMatrixIndexubvARB".} -proc glMatrixIndexusvARB*(size: TGLint, indices: PGLushort){.dynlib: dllname, +proc glMatrixIndexusvARB*(size: TGLint, indices: PGLushort){.dynlib: dllname, importc: "glMatrixIndexusvARB".} -proc glMatrixIndexuivARB*(size: TGLint, indices: PGLuint){.dynlib: dllname, +proc glMatrixIndexuivARB*(size: TGLint, indices: PGLuint){.dynlib: dllname, importc: "glMatrixIndexuivARB".} -proc glMatrixIndexPointerARB*(size: TGLint, thetype: TGLenum, stride: TGLsizei, - pointer: PGLvoid){.dynlib: dllname, +proc glMatrixIndexPointerARB*(size: TGLint, thetype: TGLenum, stride: TGLsizei, + pointer: PGLvoid){.dynlib: dllname, importc: "glMatrixIndexPointerARB".} #***** GL_NV_element_array *****// -const +const GL_ELEMENT_ARRAY_TYPE_NV* = 0x00008769 GL_ELEMENT_ARRAY_POINTER_NV* = 0x0000876A -proc glElementPointerNV*(thetype: TGLenum, pointer: PGLvoid){.dynlib: dllname, +proc glElementPointerNV*(thetype: TGLenum, pointer: PGLvoid){.dynlib: dllname, importc: "glElementPointerNV".} proc glDrawElementArrayNV*(mode: TGLenum, first: TGLint, count: TGLsizei){. dynlib: dllname, importc: "glDrawElementArrayNV".} -proc glDrawRangeElementArrayNV*(mode: TGLenum, start: TGLuint, theend: TGLuint, +proc glDrawRangeElementArrayNV*(mode: TGLenum, start: TGLuint, theend: TGLuint, first: TGLint, count: TGLsizei){. dynlib: dllname, importc: "glDrawRangeElementArrayNV".} -proc glMultiDrawElementArrayNV*(mode: TGLenum, first: PGLint, count: PGLsizei, - primcount: TGLsizei){.dynlib: dllname, +proc glMultiDrawElementArrayNV*(mode: TGLenum, first: PGLint, count: PGLsizei, + primcount: TGLsizei){.dynlib: dllname, importc: "glMultiDrawElementArrayNV".} -proc glMultiDrawRangeElementArrayNV*(mode: TGLenum, start: TGLuint, - theend: TGLuint, first: PGLint, +proc glMultiDrawRangeElementArrayNV*(mode: TGLenum, start: TGLuint, + theend: TGLuint, first: PGLint, count: PGLsizei, primcount: TGLsizei){. dynlib: dllname, importc: "glMultiDrawRangeElementArrayNV".} #***** GL_NV_float_buffer *****// -const +const GL_FLOAT_R_NV* = 0x00008880 GL_FLOAT_RG_NV* = 0x00008881 GL_FLOAT_RGB_NV* = 0x00008882 @@ -3628,7 +3628,7 @@ const GL_FLOAT_RGBA_MODE_NV* = 0x0000888E #***** GL_NV_fragment_program *****// -const +const GL_FRAGMENT_PROGRAM_NV* = 0x00008870 GL_MAX_TEXTURE_COORDS_NV* = 0x00008871 GL_MAX_TEXTURE_IMAGE_UNITS_NV* = 0x00008872 @@ -3636,18 +3636,18 @@ const GL_MAX_FRAGMENT_PROGRAM_LOCAL_PARAMETERS_NV* = 0x00008868 GL_PROGRAM_ERROR_STRING_NV* = 0x00008874 -proc glProgramNamedParameter4fNV*(id: TGLuint, length: TGLsizei, name: PGLubyte, - x: TGLfloat, y: TGLfloat, z: TGLfloat, - w: TGLfloat){.dynlib: dllname, +proc glProgramNamedParameter4fNV*(id: TGLuint, length: TGLsizei, name: PGLubyte, + x: TGLfloat, y: TGLfloat, z: TGLfloat, + w: TGLfloat){.dynlib: dllname, importc: "glProgramNamedParameter4fNV".} -proc glProgramNamedParameter4dNV*(id: TGLuint, length: TGLsizei, name: PGLubyte, - x: TGLdouble, y: TGLdouble, z: TGLdouble, - w: TGLdouble){.dynlib: dllname, +proc glProgramNamedParameter4dNV*(id: TGLuint, length: TGLsizei, name: PGLubyte, + x: TGLdouble, y: TGLdouble, z: TGLdouble, + w: TGLdouble){.dynlib: dllname, importc: "glProgramNamedParameter4dNV".} -proc glGetProgramNamedParameterfvNV*(id: TGLuint, length: TGLsizei, +proc glGetProgramNamedParameterfvNV*(id: TGLuint, length: TGLsizei, name: PGLubyte, params: PGLfloat){. dynlib: dllname, importc: "glGetProgramNamedParameterfvNV".} -proc glGetProgramNamedParameterdvNV*(id: TGLuint, length: TGLsizei, +proc glGetProgramNamedParameterdvNV*(id: TGLuint, length: TGLsizei, name: PGLubyte, params: PGLdouble){. dynlib: dllname, importc: "glGetProgramNamedParameterdvNV".} # glProgramLocalParameter4dARB { already defined } @@ -3657,16 +3657,16 @@ proc glGetProgramNamedParameterdvNV*(id: TGLuint, length: TGLsizei, # glGetProgramLocalParameterdvARB { already defined } # glGetProgramLocalParameterfvARB { already defined } #***** GL_NV_primitive_restart *****// -const +const constGL_PRIMITIVE_RESTART_NV* = 0x00008558 constGL_PRIMITIVE_RESTART_INDEX_NV* = 0x00008559 proc glPrimitiveRestartNV*(){.dynlib: dllname, importc: "glPrimitiveRestartNV".} -proc glPrimitiveRestartIndexNV*(index: TGLuint){.dynlib: dllname, +proc glPrimitiveRestartIndexNV*(index: TGLuint){.dynlib: dllname, importc: "glPrimitiveRestartIndexNV".} #***** GL_NV_vertex_program2 *****// #***** GL_NV_pixel_data_range *****// -const +const GL_WRITE_PIXEL_DATA_RANGE_NV* = 0x00008878 GL_READ_PIXEL_DATA_RANGE_NV* = 0x00008879 GL_WRITE_PIXEL_DATA_RANGE_LENGTH_NV* = 0x0000887A @@ -3676,26 +3676,26 @@ const proc glPixelDataRangeNV*(target: TGLenum, len: TGLsizei, pointer: PGLvoid){. dynlib: dllname, importc: "glPixelDataRangeNV".} -proc glFlushPixelDataRangeNV*(target: TGLenum){.dynlib: dllname, +proc glFlushPixelDataRangeNV*(target: TGLenum){.dynlib: dllname, importc: "glFlushPixelDataRangeNV".} # wglAllocateMemoryNV { already defined } # wglFreeMemoryNV { already defined } #***** GL_EXT_texture_rectangle *****// -const +const GL_TEXTURE_RECTANGLE_EXT* = 0x000084F5 GL_TEXTURE_BINDING_RECTANGLE_EXT* = 0x000084F6 GL_PROXY_TEXTURE_RECTANGLE_EXT* = 0x000084F7 GL_MAX_RECTANGLE_TEXTURE_SIZE_EXT* = 0x000084F8 #***** GL_S3_s3tc *****// -const +const GL_RGB_S3TC* = 0x000083A0 GL_RGB4_S3TC* = 0x000083A1 GL_RGBA_S3TC* = 0x000083A2 GL_RGBA4_S3TC* = 0x000083A3 #***** GL_ATI_draw_buffers *****// -const +const GL_MAX_DRAW_BUFFERS_ATI* = 0x00008824 GL_DRAW_BUFFER0_ATI* = 0x00008825 GL_DRAW_BUFFER1_ATI* = 0x00008826 @@ -3714,16 +3714,16 @@ const GL_DRAW_BUFFER14_ATI* = 0x00008833 GL_DRAW_BUFFER15_ATI* = 0x00008834 -proc glDrawBuffersATI*(n: TGLsizei, bufs: PGLenum){.dynlib: dllname, +proc glDrawBuffersATI*(n: TGLsizei, bufs: PGLenum){.dynlib: dllname, importc: "glDrawBuffersATI".} #***** GL_ATI_texture_env_combine3 *****// -const +const GL_MODULATE_ADD_ATI* = 0x00008744 GL_MODULATE_SIGNED_ADD_ATI* = 0x00008745 GL_MODULATE_SUBTRACT_ATI* = 0x00008746 #***** GL_ATI_texture_float *****// -const +const GL_RGBA_FLOAT32_ATI* = 0x00008814 GL_RGB_FLOAT32_ATI* = 0x00008815 GL_ALPHA_FLOAT32_ATI* = 0x00008816 @@ -3738,17 +3738,17 @@ const GL_LUMINANCE_ALPHA_FLOAT16_ATI* = 0x0000881F #***** GL_NV_texture_expand_normal *****// -const +const GL_TEXTURE_UNSIGNED_REMAP_MODE_NV* = 0x0000888F #***** GL_NV_half_float *****// -const +const GL_HALF_FLOAT_NV* = 0x0000140B -proc glVertex2hNV*(x: TGLushort, y: TGLushort){.dynlib: dllname, +proc glVertex2hNV*(x: TGLushort, y: TGLushort){.dynlib: dllname, importc: "glVertex2hNV".} proc glVertex2hvNV*(v: PGLushort){.dynlib: dllname, importc: "glVertex2hvNV".} -proc glVertex3hNV*(x: TGLushort, y: TGLushort, z: TGLushort){.dynlib: dllname, +proc glVertex3hNV*(x: TGLushort, y: TGLushort, z: TGLushort){.dynlib: dllname, importc: "glVertex3hNV".} proc glVertex3hvNV*(v: PGLushort){.dynlib: dllname, importc: "glVertex3hvNV".} proc glVertex4hNV*(x: TGLushort, y: TGLushort, z: TGLushort, w: TGLushort){. @@ -3760,65 +3760,65 @@ proc glNormal3hvNV*(v: PGLushort){.dynlib: dllname, importc: "glNormal3hvNV".} proc glColor3hNV*(red: TGLushort, green: TGLushort, blue: TGLushort){. dynlib: dllname, importc: "glColor3hNV".} proc glColor3hvNV*(v: PGLushort){.dynlib: dllname, importc: "glColor3hvNV".} -proc glColor4hNV*(red: TGLushort, green: TGLushort, blue: TGLushort, +proc glColor4hNV*(red: TGLushort, green: TGLushort, blue: TGLushort, alpha: TGLushort){.dynlib: dllname, importc: "glColor4hNV".} proc glColor4hvNV*(v: PGLushort){.dynlib: dllname, importc: "glColor4hvNV".} proc glTexCoord1hNV*(s: TGLushort){.dynlib: dllname, importc: "glTexCoord1hNV".} proc glTexCoord1hvNV*(v: PGLushort){.dynlib: dllname, importc: "glTexCoord1hvNV".} -proc glTexCoord2hNV*(s: TGLushort, t: TGLushort){.dynlib: dllname, +proc glTexCoord2hNV*(s: TGLushort, t: TGLushort){.dynlib: dllname, importc: "glTexCoord2hNV".} proc glTexCoord2hvNV*(v: PGLushort){.dynlib: dllname, importc: "glTexCoord2hvNV".} -proc glTexCoord3hNV*(s: TGLushort, t: TGLushort, r: TGLushort){.dynlib: dllname, +proc glTexCoord3hNV*(s: TGLushort, t: TGLushort, r: TGLushort){.dynlib: dllname, importc: "glTexCoord3hNV".} proc glTexCoord3hvNV*(v: PGLushort){.dynlib: dllname, importc: "glTexCoord3hvNV".} proc glTexCoord4hNV*(s: TGLushort, t: TGLushort, r: TGLushort, q: TGLushort){. dynlib: dllname, importc: "glTexCoord4hNV".} proc glTexCoord4hvNV*(v: PGLushort){.dynlib: dllname, importc: "glTexCoord4hvNV".} -proc glMultiTexCoord1hNV*(target: TGLenum, s: TGLushort){.dynlib: dllname, +proc glMultiTexCoord1hNV*(target: TGLenum, s: TGLushort){.dynlib: dllname, importc: "glMultiTexCoord1hNV".} -proc glMultiTexCoord1hvNV*(target: TGLenum, v: PGLushort){.dynlib: dllname, +proc glMultiTexCoord1hvNV*(target: TGLenum, v: PGLushort){.dynlib: dllname, importc: "glMultiTexCoord1hvNV".} proc glMultiTexCoord2hNV*(target: TGLenum, s: TGLushort, t: TGLushort){. dynlib: dllname, importc: "glMultiTexCoord2hNV".} -proc glMultiTexCoord2hvNV*(target: TGLenum, v: PGLushort){.dynlib: dllname, +proc glMultiTexCoord2hvNV*(target: TGLenum, v: PGLushort){.dynlib: dllname, importc: "glMultiTexCoord2hvNV".} -proc glMultiTexCoord3hNV*(target: TGLenum, s: TGLushort, t: TGLushort, - r: TGLushort){.dynlib: dllname, +proc glMultiTexCoord3hNV*(target: TGLenum, s: TGLushort, t: TGLushort, + r: TGLushort){.dynlib: dllname, importc: "glMultiTexCoord3hNV".} -proc glMultiTexCoord3hvNV*(target: TGLenum, v: PGLushort){.dynlib: dllname, +proc glMultiTexCoord3hvNV*(target: TGLenum, v: PGLushort){.dynlib: dllname, importc: "glMultiTexCoord3hvNV".} -proc glMultiTexCoord4hNV*(target: TGLenum, s: TGLushort, t: TGLushort, - r: TGLushort, q: TGLushort){.dynlib: dllname, +proc glMultiTexCoord4hNV*(target: TGLenum, s: TGLushort, t: TGLushort, + r: TGLushort, q: TGLushort){.dynlib: dllname, importc: "glMultiTexCoord4hNV".} -proc glMultiTexCoord4hvNV*(target: TGLenum, v: PGLushort){.dynlib: dllname, +proc glMultiTexCoord4hvNV*(target: TGLenum, v: PGLushort){.dynlib: dllname, importc: "glMultiTexCoord4hvNV".} proc glFogCoordhNV*(fog: TGLushort){.dynlib: dllname, importc: "glFogCoordhNV".} proc glFogCoordhvNV*(fog: PGLushort){.dynlib: dllname, importc: "glFogCoordhvNV".} proc glSecondaryColor3hNV*(red: TGLushort, green: TGLushort, blue: TGLushort){. dynlib: dllname, importc: "glSecondaryColor3hNV".} -proc glSecondaryColor3hvNV*(v: PGLushort){.dynlib: dllname, +proc glSecondaryColor3hvNV*(v: PGLushort){.dynlib: dllname, importc: "glSecondaryColor3hvNV".} -proc glVertexWeighthNV*(weight: TGLushort){.dynlib: dllname, +proc glVertexWeighthNV*(weight: TGLushort){.dynlib: dllname, importc: "glVertexWeighthNV".} -proc glVertexWeighthvNV*(weight: PGLushort){.dynlib: dllname, +proc glVertexWeighthvNV*(weight: PGLushort){.dynlib: dllname, importc: "glVertexWeighthvNV".} -proc glVertexAttrib1hNV*(index: TGLuint, x: TGLushort){.dynlib: dllname, +proc glVertexAttrib1hNV*(index: TGLuint, x: TGLushort){.dynlib: dllname, importc: "glVertexAttrib1hNV".} -proc glVertexAttrib1hvNV*(index: TGLuint, v: PGLushort){.dynlib: dllname, +proc glVertexAttrib1hvNV*(index: TGLuint, v: PGLushort){.dynlib: dllname, importc: "glVertexAttrib1hvNV".} proc glVertexAttrib2hNV*(index: TGLuint, x: TGLushort, y: TGLushort){. dynlib: dllname, importc: "glVertexAttrib2hNV".} -proc glVertexAttrib2hvNV*(index: TGLuint, v: PGLushort){.dynlib: dllname, +proc glVertexAttrib2hvNV*(index: TGLuint, v: PGLushort){.dynlib: dllname, importc: "glVertexAttrib2hvNV".} -proc glVertexAttrib3hNV*(index: TGLuint, x: TGLushort, y: TGLushort, - z: TGLushort){.dynlib: dllname, +proc glVertexAttrib3hNV*(index: TGLuint, x: TGLushort, y: TGLushort, + z: TGLushort){.dynlib: dllname, importc: "glVertexAttrib3hNV".} -proc glVertexAttrib3hvNV*(index: TGLuint, v: PGLushort){.dynlib: dllname, +proc glVertexAttrib3hvNV*(index: TGLuint, v: PGLushort){.dynlib: dllname, importc: "glVertexAttrib3hvNV".} -proc glVertexAttrib4hNV*(index: TGLuint, x: TGLushort, y: TGLushort, - z: TGLushort, w: TGLushort){.dynlib: dllname, +proc glVertexAttrib4hNV*(index: TGLuint, x: TGLushort, y: TGLushort, + z: TGLushort, w: TGLushort){.dynlib: dllname, importc: "glVertexAttrib4hNV".} -proc glVertexAttrib4hvNV*(index: TGLuint, v: PGLushort){.dynlib: dllname, +proc glVertexAttrib4hvNV*(index: TGLuint, v: PGLushort){.dynlib: dllname, importc: "glVertexAttrib4hvNV".} proc glVertexAttribs1hvNV*(index: TGLuint, n: TGLsizei, v: PGLushort){. dynlib: dllname, importc: "glVertexAttribs1hvNV".} @@ -3829,12 +3829,12 @@ proc glVertexAttribs3hvNV*(index: TGLuint, n: TGLsizei, v: PGLushort){. proc glVertexAttribs4hvNV*(index: TGLuint, n: TGLsizei, v: PGLushort){. dynlib: dllname, importc: "glVertexAttribs4hvNV".} #***** GL_ATI_map_object_buffer *****// -proc glMapObjectBufferATI*(buffer: TGLuint): PGLvoid{.dynlib: dllname, +proc glMapObjectBufferATI*(buffer: TGLuint): PGLvoid{.dynlib: dllname, importc: "glMapObjectBufferATI".} -proc glUnmapObjectBufferATI*(buffer: TGLuint){.dynlib: dllname, +proc glUnmapObjectBufferATI*(buffer: TGLuint){.dynlib: dllname, importc: "glUnmapObjectBufferATI".} #***** GL_ATI_separate_stencil *****// -const +const GL_KEEP* = 0x00001E00 GL_ZERO* = 0x00000000 GL_REPLACE* = 0x00001E01 @@ -3857,39 +3857,39 @@ const GL_STENCIL_BACK_PASS_DEPTH_FAIL_ATI* = 0x00008802 GL_STENCIL_BACK_PASS_DEPTH_PASS_ATI* = 0x00008803 -proc glStencilOpSeparateATI*(face: TGLenum, sfail: TGLenum, dpfail: TGLenum, - dppass: TGLenum){.dynlib: dllname, +proc glStencilOpSeparateATI*(face: TGLenum, sfail: TGLenum, dpfail: TGLenum, + dppass: TGLenum){.dynlib: dllname, importc: "glStencilOpSeparateATI".} -proc glStencilFuncSeparateATI*(frontfunc: TGLenum, backfunc: TGLenum, - theRef: TGLint, mask: TGLuint){.dynlib: dllname, +proc glStencilFuncSeparateATI*(frontfunc: TGLenum, backfunc: TGLenum, + theRef: TGLint, mask: TGLuint){.dynlib: dllname, importc: "glStencilFuncSeparateATI".} #***** GL_ATI_vertex_attrib_array_object *****// -proc glVertexAttribArrayObjectATI*(index: TGLuint, size: TGLint, - thetype: TGLenum, normalized: TGLboolean, - stride: TGLsizei, buffer: TGLuint, - offset: TGLuint){.dynlib: dllname, +proc glVertexAttribArrayObjectATI*(index: TGLuint, size: TGLint, + thetype: TGLenum, normalized: TGLboolean, + stride: TGLsizei, buffer: TGLuint, + offset: TGLuint){.dynlib: dllname, importc: "glVertexAttribArrayObjectATI".} -proc glGetVertexAttribArrayObjectfvATI*(index: TGLuint, pname: TGLenum, - params: PGLfloat){.dynlib: dllname, +proc glGetVertexAttribArrayObjectfvATI*(index: TGLuint, pname: TGLenum, + params: PGLfloat){.dynlib: dllname, importc: "glGetVertexAttribArrayObjectfvATI".} -proc glGetVertexAttribArrayObjectivATI*(index: TGLuint, pname: TGLenum, - params: PGLint){.dynlib: dllname, +proc glGetVertexAttribArrayObjectivATI*(index: TGLuint, pname: TGLenum, + params: PGLint){.dynlib: dllname, importc: "glGetVertexAttribArrayObjectivATI".} #***** GL_ARB_occlusion_query *****// -const +const GL_SAMPLES_PASSED_ARB* = 0x00008914 GL_QUERY_COUNTER_BITS_ARB* = 0x00008864 GL_CURRENT_QUERY_ARB* = 0x00008865 GL_QUERY_RESULT_ARB* = 0x00008866 GL_QUERY_RESULT_AVAILABLE_ARB* = 0x00008867 -proc glGenQueriesARB*(n: TGLsizei, ids: PGLuint){.dynlib: dllname, +proc glGenQueriesARB*(n: TGLsizei, ids: PGLuint){.dynlib: dllname, importc: "glGenQueriesARB".} -proc glDeleteQueriesARB*(n: TGLsizei, ids: PGLuint){.dynlib: dllname, +proc glDeleteQueriesARB*(n: TGLsizei, ids: PGLuint){.dynlib: dllname, importc: "glDeleteQueriesARB".} -proc glIsQueryARB*(id: TGLuint): TGLboolean{.dynlib: dllname, +proc glIsQueryARB*(id: TGLuint): TGLboolean{.dynlib: dllname, importc: "glIsQueryARB".} -proc glBeginQueryARB*(target: TGLenum, id: TGLuint){.dynlib: dllname, +proc glBeginQueryARB*(target: TGLenum, id: TGLuint){.dynlib: dllname, importc: "glBeginQueryARB".} proc glEndQueryARB*(target: TGLenum){.dynlib: dllname, importc: "glEndQueryARB".} proc glGetQueryivARB*(target: TGLenum, pname: TGLenum, params: PGLint){. @@ -3899,7 +3899,7 @@ proc glGetQueryObjectivARB*(id: TGLuint, pname: TGLenum, params: PGLint){. proc glGetQueryObjectuivARB*(id: TGLuint, pname: TGLenum, params: PGLuint){. dynlib: dllname, importc: "glGetQueryObjectuivARB".} #***** GL_ARB_shader_objects *****// -const +const GL_PROGRAM_OBJECT_ARB* = 0x00008B40 GL_OBJECT_TYPE_ARB* = 0x00008B4E GL_OBJECT_SUBTYPE_ARB* = 0x00008B4F @@ -3929,44 +3929,44 @@ const GL_FLOAT_MAT3_ARB* = 0x00008B5B GL_FLOAT_MAT4_ARB* = 0x00008B5C -proc glDeleteObjectARB*(obj: GLhandleARB){.dynlib: dllname, +proc glDeleteObjectARB*(obj: GLhandleARB){.dynlib: dllname, importc: "glDeleteObjectARB".} -proc glGetHandleARB*(pname: TGLenum): GLhandleARB{.dynlib: dllname, +proc glGetHandleARB*(pname: TGLenum): GLhandleARB{.dynlib: dllname, importc: "glGetHandleARB".} proc glDetachObjectARB*(containerObj: GLhandleARB, attachedObj: GLhandleARB){. dynlib: dllname, importc: "glDetachObjectARB".} proc glCreateShaderObjectARB*(shaderType: TGLenum): GLhandleARB{. dynlib: dllname, importc: "glCreateShaderObjectARB".} -proc glShaderSourceARB*(shaderObj: GLhandleARB, count: TGLsizei, str: PGLvoid, - len: PGLint){.dynlib: dllname, +proc glShaderSourceARB*(shaderObj: GLhandleARB, count: TGLsizei, str: PGLvoid, + len: PGLint){.dynlib: dllname, importc: "glShaderSourceARB".} -proc glCompileShaderARB*(shaderObj: GLhandleARB){.dynlib: dllname, +proc glCompileShaderARB*(shaderObj: GLhandleARB){.dynlib: dllname, importc: "glCompileShaderARB".} -proc glCreateProgramObjectARB*(): GLhandleARB{.dynlib: dllname, +proc glCreateProgramObjectARB*(): GLhandleARB{.dynlib: dllname, importc: "glCreateProgramObjectARB".} proc glAttachObjectARB*(containerObj: GLhandleARB, obj: GLhandleARB){. dynlib: dllname, importc: "glAttachObjectARB".} -proc glLinkProgramARB*(programObj: GLhandleARB){.dynlib: dllname, +proc glLinkProgramARB*(programObj: GLhandleARB){.dynlib: dllname, importc: "glLinkProgramARB".} -proc glUseProgramObjectARB*(programObj: GLhandleARB){.dynlib: dllname, +proc glUseProgramObjectARB*(programObj: GLhandleARB){.dynlib: dllname, importc: "glUseProgramObjectARB".} -proc glValidateProgramARB*(programObj: GLhandleARB){.dynlib: dllname, +proc glValidateProgramARB*(programObj: GLhandleARB){.dynlib: dllname, importc: "glValidateProgramARB".} -proc glUniform1fARB*(location: TGLint, v0: TGLfloat){.dynlib: dllname, +proc glUniform1fARB*(location: TGLint, v0: TGLfloat){.dynlib: dllname, importc: "glUniform1fARB".} proc glUniform2fARB*(location: TGLint, v0: TGLfloat, v1: TGLfloat){. dynlib: dllname, importc: "glUniform2fARB".} proc glUniform3fARB*(location: TGLint, v0: TGLfloat, v1: TGLfloat, v2: TGLfloat){. dynlib: dllname, importc: "glUniform3fARB".} -proc glUniform4fARB*(location: TGLint, v0: TGLfloat, v1: TGLfloat, v2: TGLfloat, +proc glUniform4fARB*(location: TGLint, v0: TGLfloat, v1: TGLfloat, v2: TGLfloat, v3: TGLfloat){.dynlib: dllname, importc: "glUniform4fARB".} -proc glUniform1iARB*(location: TGLint, v0: TGLint){.dynlib: dllname, +proc glUniform1iARB*(location: TGLint, v0: TGLint){.dynlib: dllname, importc: "glUniform1iARB".} -proc glUniform2iARB*(location: TGLint, v0: TGLint, v1: TGLint){.dynlib: dllname, +proc glUniform2iARB*(location: TGLint, v0: TGLint, v1: TGLint){.dynlib: dllname, importc: "glUniform2iARB".} proc glUniform3iARB*(location: TGLint, v0: TGLint, v1: TGLint, v2: TGLint){. dynlib: dllname, importc: "glUniform3iARB".} -proc glUniform4iARB*(location: TGLint, v0: TGLint, v1: TGLint, v2: TGLint, +proc glUniform4iARB*(location: TGLint, v0: TGLint, v1: TGLint, v2: TGLint, v3: TGLint){.dynlib: dllname, importc: "glUniform4iARB".} proc glUniform1fvARB*(location: TGLint, count: TGLsizei, value: PGLfloat){. dynlib: dllname, importc: "glUniform1fvARB".} @@ -3984,80 +3984,80 @@ proc glUniform3ivARB*(location: TGLint, count: TGLsizei, value: PGLint){. dynlib: dllname, importc: "glUniform3ivARB".} proc glUniform4ivARB*(location: TGLint, count: TGLsizei, value: PGLint){. dynlib: dllname, importc: "glUniform4ivARB".} -proc glUniformMatrix2fvARB*(location: TGLint, count: TGLsizei, +proc glUniformMatrix2fvARB*(location: TGLint, count: TGLsizei, transpose: TGLboolean, value: PGLfloat){. dynlib: dllname, importc: "glUniformMatrix2fvARB".} -proc glUniformMatrix3fvARB*(location: TGLint, count: TGLsizei, +proc glUniformMatrix3fvARB*(location: TGLint, count: TGLsizei, transpose: TGLboolean, value: PGLfloat){. dynlib: dllname, importc: "glUniformMatrix3fvARB".} -proc glUniformMatrix4fvARB*(location: TGLint, count: TGLsizei, +proc glUniformMatrix4fvARB*(location: TGLint, count: TGLsizei, transpose: TGLboolean, value: PGLfloat){. dynlib: dllname, importc: "glUniformMatrix4fvARB".} -proc glGetObjectParameterfvARB*(obj: GLhandleARB, pname: TGLenum, - params: PGLfloat){.dynlib: dllname, +proc glGetObjectParameterfvARB*(obj: GLhandleARB, pname: TGLenum, + params: PGLfloat){.dynlib: dllname, importc: "glGetObjectParameterfvARB".} proc glGetObjectParameterivARB*(obj: GLhandleARB, pname: TGLenum, params: PGLint){. dynlib: dllname, importc: "glGetObjectParameterivARB".} -proc glGetInfoLogARB*(obj: GLhandleARB, maxLength: TGLsizei, len: PGLsizei, - infoLog: PGLcharARB){.dynlib: dllname, +proc glGetInfoLogARB*(obj: GLhandleARB, maxLength: TGLsizei, len: PGLsizei, + infoLog: PGLcharARB){.dynlib: dllname, importc: "glGetInfoLogARB".} -proc glGetAttachedObjectsARB*(containerObj: GLhandleARB, maxCount: TGLsizei, +proc glGetAttachedObjectsARB*(containerObj: GLhandleARB, maxCount: TGLsizei, count: PGLsizei, obj: PGLhandleARB){. dynlib: dllname, importc: "glGetAttachedObjectsARB".} proc glGetUniformLocationARB*(programObj: GLhandleARB, name: PGLcharARB): TGLint{. dynlib: dllname, importc: "glGetUniformLocationARB".} -proc glGetActiveUniformARB*(programObj: GLhandleARB, index: TGLuint, - maxLength: TGLsizei, len: PGLsizei, size: PGLint, +proc glGetActiveUniformARB*(programObj: GLhandleARB, index: TGLuint, + maxLength: TGLsizei, len: PGLsizei, size: PGLint, thetype: PGLenum, name: PGLcharARB){. dynlib: dllname, importc: "glGetActiveUniformARB".} -proc glGetUniformfvARB*(programObj: GLhandleARB, location: TGLint, - params: PGLfloat){.dynlib: dllname, +proc glGetUniformfvARB*(programObj: GLhandleARB, location: TGLint, + params: PGLfloat){.dynlib: dllname, importc: "glGetUniformfvARB".} -proc glGetUniformivARB*(programObj: GLhandleARB, location: TGLint, - params: PGLint){.dynlib: dllname, +proc glGetUniformivARB*(programObj: GLhandleARB, location: TGLint, + params: PGLint){.dynlib: dllname, importc: "glGetUniformivARB".} -proc glGetShaderSourceARB*(obj: GLhandleARB, maxLength: TGLsizei, len: PGLsizei, - source: PGLcharARB){.dynlib: dllname, +proc glGetShaderSourceARB*(obj: GLhandleARB, maxLength: TGLsizei, len: PGLsizei, + source: PGLcharARB){.dynlib: dllname, importc: "glGetShaderSourceARB".} -const +const GL_VERTEX_SHADER_ARB* = 0x00008B31 GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB* = 0x00008B4A GL_MAX_VARYING_FLOATS_ARB* = 0x00008B4B # GL_MAX_VERTEX_ATTRIBS_ARB { already defined } # GL_MAX_TEXTURE_IMAGE_UNITS_ARB { already defined } GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB* = 0x00008B4C - GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB* = 0x00008B4D # - # + GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB* = 0x00008B4D # + # # GL_MAX_TEXTURE_COORDS_ARB { already defined } - # - # + # + # # GL_VERTEX_PROGRAM_POINT_SIZE_ARB { already defined } - # - # + # + # # GL_VERTEX_PROGRAM_TWO_SIDE_ARB { already defined } # GL_OBJECT_TYPE_ARB { already defined } # GL_OBJECT_SUBTYPE_ARB { already defined } GL_OBJECT_ACTIVE_ATTRIBUTES_ARB* = 0x00008B89 GL_OBJECT_ACTIVE_ATTRIBUTE_MAX_LENGTH_ARB* = 0x00008B8A # GL_SHADER_OBJECT_ARB { already defined } - # - # + # + # # GL_VERTEX_ATTRIB_ARRAY_ENABLED_ARB { already defined } - # - # + # + # # GL_VERTEX_ATTRIB_ARRAY_SIZE_ARB { already defined } - # - # + # + # # GL_VERTEX_ATTRIB_ARRAY_STRIDE_ARB { already defined } - # - # + # + # # GL_VERTEX_ATTRIB_ARRAY_TYPE_ARB { already defined } - # - # + # + # # GL_VERTEX_ATTRIB_ARRAY_NORMALIZED_ARB { already defined } - # - # + # + # # GL_CURRENT_VERTEX_ATTRIB_ARB { already defined } - # - # + # + # # GL_VERTEX_ATTRIB_ARRAY_POINTER_ARB { already defined } # GL_FLOAT { already defined } # GL_FLOAT_VEC2_ARB { already defined } @@ -4102,22 +4102,22 @@ const # glVertexAttrib4NubvARB { already defined } # glVertexAttrib4NusvARB { already defined } # glVertexAttrib4NuivARB { already defined } - # - # + # + # # glVertexAttribPointerARB { already defined } - # - # + # + # # glEnableVertexAttribArrayARB { already defined } - # - # + # + # # glDisableVertexAttribArrayARB { already defined } -proc glBindAttribLocationARB*(programObj: GLhandleARB, index: TGLuint, - name: PGLcharARB){.dynlib: dllname, +proc glBindAttribLocationARB*(programObj: GLhandleARB, index: TGLuint, + name: PGLcharARB){.dynlib: dllname, importc: "glBindAttribLocationARB".} -proc glGetActiveAttribARB*(programObj: GLhandleARB, index: TGLuint, - maxLength: TGLsizei, len: PGLsizei, size: PGLint, - thetype: PGLenum, name: PGLcharARB){.dynlib: dllname, +proc glGetActiveAttribARB*(programObj: GLhandleARB, index: TGLuint, + maxLength: TGLsizei, len: PGLsizei, size: PGLint, + thetype: PGLenum, name: PGLcharARB){.dynlib: dllname, importc: "glGetActiveAttribARB".} proc glGetAttribLocationARB*(programObj: GLhandleARB, name: PGLcharARB): TGLint{. dynlib: dllname, importc: "glGetAttribLocationARB".} @@ -4126,11 +4126,11 @@ proc glGetAttribLocationARB*(programObj: GLhandleARB, name: PGLcharARB): TGLint{ # glGetVertexAttribivARB { already defined } # glGetVertexAttribPointervARB { already defined } #***** GL_ARB_fragment_shader *****// -const +const GL_FRAGMENT_SHADER_ARB* = 0x00008B30 GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB* = 0x00008B49 # GL_MAX_TEXTURE_COORDS_ARB { already defined } - # - # + # + # # GL_MAX_TEXTURE_IMAGE_UNITS_ARB { already defined } # GL_OBJECT_TYPE_ARB { already defined } # GL_OBJECT_SUBTYPE_ARB { already defined } @@ -4139,36 +4139,36 @@ const #***** GL_ARB_texture_non_power_of_two *****// #***** GL_ARB_point_sprite *****// -const +const GL_POINT_SPRITE_ARB* = 0x00008861 GL_COORD_REPLACE_ARB* = 0x00008862 #***** GL_EXT_depth_bounds_test *****// -const +const constGL_DEPTH_BOUNDS_TEST_EXT* = 0x00008890 constGL_DEPTH_BOUNDS_EXT* = 0x00008891 -proc glDepthBoundsEXT*(zmin: TGLclampd, zmax: TGLclampd){.dynlib: dllname, +proc glDepthBoundsEXT*(zmin: TGLclampd, zmax: TGLclampd){.dynlib: dllname, importc: "glDepthBoundsEXT".} #***** GL_EXT_texture_mirror_clamp *****// -const +const GL_MIRROR_CLAMP_EXT* = 0x00008742 GL_MIRROR_CLAMP_TO_EDGE_EXT* = 0x00008743 GL_MIRROR_CLAMP_TO_BORDER_EXT* = 0x00008912 #***** GL_EXT_blend_equation_separate *****// -const +const GL_BLEND_EQUATION_RGB_EXT* = 0x00008009 GL_BLEND_EQUATION_ALPHA_EXT* = 0x0000883D proc glBlendEquationSeparateEXT*(modeRGB: TGLenum, modeAlpha: TGLenum){. dynlib: dllname, importc: "glBlendEquationSeparateEXT".} #***** GL_MESA_pack_invert *****// -const +const GL_PACK_INVERT_MESA* = 0x00008758 #***** GL_MESA_ycbcr_texture *****// -const +const GL_YCBCR_MESA* = 0x00008757 GL_UNSIGNED_SHORT_8_8_MESA* = 0x000085BA GL_UNSIGNED_SHORT_8_8_REV_MESA* = 0x000085BB @@ -4176,14 +4176,14 @@ const #***** GL_NV_fragment_program_option *****// #***** GL_EXT_pixel_buffer_object *****// -const +const GL_PIXEL_PACK_BUFFER_EXT* = 0x000088EB GL_PIXEL_UNPACK_BUFFER_EXT* = 0x000088EC GL_PIXEL_PACK_BUFFER_BINDING_EXT* = 0x000088ED GL_PIXEL_UNPACK_BUFFER_BINDING_EXT* = 0x000088EF #***** GL_NV_fragment_program2 *****// -const +const GL_MAX_PROGRAM_EXEC_INSTRUCTIONS_NV* = 0x000088F4 GL_MAX_PROGRAM_CALL_DEPTH_NV* = 0x000088F5 GL_MAX_PROGRAM_IF_DEPTH_NV* = 0x000088F6 @@ -4196,7 +4196,7 @@ const # GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB { already defined } #***** GL_ARB_draw_buffers *****// -const +const GL_MAX_DRAW_BUFFERS_ARB* = 0x00008824 GL_DRAW_BUFFER0_ARB* = 0x00008825 GL_DRAW_BUFFER1_ARB* = 0x00008826 @@ -4215,17 +4215,17 @@ const GL_DRAW_BUFFER14_ARB* = 0x00008833 GL_DRAW_BUFFER15_ARB* = 0x00008834 -proc glDrawBuffersARB*(n: TGLsizei, bufs: PGLenum){.dynlib: dllname, +proc glDrawBuffersARB*(n: TGLsizei, bufs: PGLenum){.dynlib: dllname, importc: "glDrawBuffersARB".} #***** GL_ARB_texture_rectangle *****// -const +const GL_TEXTURE_RECTANGLE_ARB* = 0x000084F5 GL_TEXTURE_BINDING_RECTANGLE_ARB* = 0x000084F6 GL_PROXY_TEXTURE_RECTANGLE_ARB* = 0x000084F7 GL_MAX_RECTANGLE_TEXTURE_SIZE_ARB* = 0x000084F8 #***** GL_ARB_color_buffer_float *****// -const +const GL_RGBA_FLOAT_MODE_ARB* = 0x00008820 GL_CLAMP_VERTEX_COLOR_ARB* = 0x0000891A GL_CLAMP_FRAGMENT_COLOR_ARB* = 0x0000891B @@ -4233,14 +4233,14 @@ const GL_FIXED_ONLY_ARB* = 0x0000891D WGL_TYPE_RGBA_FLOAT_ARB* = 0x000021A0 -proc glClampColorARB*(target: TGLenum, clamp: TGLenum){.dynlib: dllname, +proc glClampColorARB*(target: TGLenum, clamp: TGLenum){.dynlib: dllname, importc: "glClampColorARB".} #***** GL_ARB_half_float_pixel *****// -const +const GL_HALF_FLOAT_ARB* = 0x0000140B #***** GL_ARB_texture_float *****// -const +const GL_TEXTURE_RED_TYPE_ARB* = 0x00008C10 GL_TEXTURE_GREEN_TYPE_ARB* = 0x00008C11 GL_TEXTURE_BLUE_TYPE_ARB* = 0x00008C12 @@ -4266,14 +4266,14 @@ const # GL_COMPRESSED_RGBA_S3TC_DXT1_EXT { already defined } #***** GL_ARB_pixel_buffer_object *****// -const +const GL_PIXEL_PACK_BUFFER_ARB* = 0x000088EB GL_PIXEL_UNPACK_BUFFER_ARB* = 0x000088EC GL_PIXEL_PACK_BUFFER_BINDING_ARB* = 0x000088ED GL_PIXEL_UNPACK_BUFFER_BINDING_ARB* = 0x000088EF #***** GL_EXT_framebuffer_object *****// -const +const GL_FRAMEBUFFER_EXT* = 0x00008D40 GL_RENDERBUFFER_EXT* = 0x00008D41 GL_STENCIL_INDEX_EXT* = 0x00008D45 @@ -4323,7 +4323,7 @@ const GL_MAX_RENDERBUFFER_SIZE_EXT* = 0x000084E8 GL_INVALID_FRAMEBUFFER_OPERATION_EXT* = 0x00000506 -proc glIsRenderbufferEXT*(renderbuffer: TGLuint): TGLboolean{.dynlib: dllname, +proc glIsRenderbufferEXT*(renderbuffer: TGLuint): TGLboolean{.dynlib: dllname, importc: "glIsRenderbufferEXT".} proc glBindRenderbufferEXT*(target: TGLenum, renderbuffer: TGLuint){. dynlib: dllname, importc: "glBindRenderbufferEXT".} @@ -4331,45 +4331,45 @@ proc glDeleteRenderbuffersEXT*(n: TGLsizei, renderbuffers: PGLuint){. dynlib: dllname, importc: "glDeleteRenderbuffersEXT".} proc glGenRenderbuffersEXT*(n: TGLsizei, renderbuffers: PGLuint){. dynlib: dllname, importc: "glGenRenderbuffersEXT".} -proc glRenderbufferStorageEXT*(target: TGLenum, internalformat: TGLenum, +proc glRenderbufferStorageEXT*(target: TGLenum, internalformat: TGLenum, width: TGLsizei, height: TGLsizei){. dynlib: dllname, importc: "glRenderbufferStorageEXT".} -proc glGetRenderbufferParameterivEXT*(target: TGLenum, pname: TGLenum, - params: PGLint){.dynlib: dllname, +proc glGetRenderbufferParameterivEXT*(target: TGLenum, pname: TGLenum, + params: PGLint){.dynlib: dllname, importc: "glGetRenderbufferParameterivEXT".} -proc glIsFramebufferEXT*(framebuffer: TGLuint): TGLboolean{.dynlib: dllname, +proc glIsFramebufferEXT*(framebuffer: TGLuint): TGLboolean{.dynlib: dllname, importc: "glIsFramebufferEXT".} proc glBindFramebufferEXT*(target: TGLenum, framebuffer: TGLuint){. dynlib: dllname, importc: "glBindFramebufferEXT".} proc glDeleteFramebuffersEXT*(n: TGLsizei, framebuffers: PGLuint){. dynlib: dllname, importc: "glDeleteFramebuffersEXT".} -proc glGenFramebuffersEXT*(n: TGLsizei, framebuffers: PGLuint){.dynlib: dllname, +proc glGenFramebuffersEXT*(n: TGLsizei, framebuffers: PGLuint){.dynlib: dllname, importc: "glGenFramebuffersEXT".} -proc glCheckFramebufferStatusEXT*(target: TGLenum): TGLenum{.dynlib: dllname, +proc glCheckFramebufferStatusEXT*(target: TGLenum): TGLenum{.dynlib: dllname, importc: "glCheckFramebufferStatusEXT".} -proc glFramebufferTexture1DEXT*(target: TGLenum, attachment: TGLenum, - textarget: TGLenum, texture: TGLuint, - level: TGLint){.dynlib: dllname, +proc glFramebufferTexture1DEXT*(target: TGLenum, attachment: TGLenum, + textarget: TGLenum, texture: TGLuint, + level: TGLint){.dynlib: dllname, importc: "glFramebufferTexture1DEXT".} -proc glFramebufferTexture2DEXT*(target: TGLenum, attachment: TGLenum, - textarget: TGLenum, texture: TGLuint, - level: TGLint){.dynlib: dllname, +proc glFramebufferTexture2DEXT*(target: TGLenum, attachment: TGLenum, + textarget: TGLenum, texture: TGLuint, + level: TGLint){.dynlib: dllname, importc: "glFramebufferTexture2DEXT".} -proc glFramebufferTexture3DEXT*(target: TGLenum, attachment: TGLenum, - textarget: TGLenum, texture: TGLuint, +proc glFramebufferTexture3DEXT*(target: TGLenum, attachment: TGLenum, + textarget: TGLenum, texture: TGLuint, level: TGLint, zoffset: TGLint){. dynlib: dllname, importc: "glFramebufferTexture3DEXT".} -proc glFramebufferRenderbufferEXT*(target: TGLenum, attachment: TGLenum, - renderbuffertarget: TGLenum, - renderbuffer: TGLuint){.dynlib: dllname, +proc glFramebufferRenderbufferEXT*(target: TGLenum, attachment: TGLenum, + renderbuffertarget: TGLenum, + renderbuffer: TGLuint){.dynlib: dllname, importc: "glFramebufferRenderbufferEXT".} -proc glGetFramebufferAttachmentParameterivEXT*(target: TGLenum, - attachment: TGLenum, pname: TGLenum, params: PGLint){.dynlib: dllname, +proc glGetFramebufferAttachmentParameterivEXT*(target: TGLenum, + attachment: TGLenum, pname: TGLenum, params: PGLint){.dynlib: dllname, importc: "glGetFramebufferAttachmentParameterivEXT".} -proc glGenerateMipmapEXT*(target: TGLenum){.dynlib: dllname, +proc glGenerateMipmapEXT*(target: TGLenum){.dynlib: dllname, importc: "glGenerateMipmapEXT".} #***** GL_version_1_4 *****// -const +const GL_BLEND_DST_RGB* = 0x000080C8 GL_BLEND_SRC_RGB* = 0x000080C9 GL_BLEND_DST_ALPHA* = 0x000080CA @@ -4410,7 +4410,7 @@ const GL_TEXTURE_COMPARE_FUNC* = 0x0000884D GL_COMPARE_R_TO_TEXTURE* = 0x0000884E -proc glBlendFuncSeparate*(sfactorRGB: TGLenum, dfactorRGB: TGLenum, +proc glBlendFuncSeparate*(sfactorRGB: TGLenum, dfactorRGB: TGLenum, sfactorAlpha: TGLenum, dfactorAlpha: TGLenum){. dynlib: dllname, importc: "glBlendFuncSeparate".} proc glFogCoordf*(coord: TGLfloat){.dynlib: dllname, importc: "glFogCoordf".} @@ -4419,81 +4419,81 @@ proc glFogCoordd*(coord: TGLdouble){.dynlib: dllname, importc: "glFogCoordd".} proc glFogCoorddv*(coord: PGLdouble){.dynlib: dllname, importc: "glFogCoorddv".} proc glFogCoordPointer*(thetype: TGLenum, stride: TGLsizei, pointer: PGLvoid){. dynlib: dllname, importc: "glFogCoordPointer".} -proc glMultiDrawArrays*(mode: TGLenum, first: PGLint, count: PGLsizei, - primcount: TGLsizei){.dynlib: dllname, +proc glMultiDrawArrays*(mode: TGLenum, first: PGLint, count: PGLsizei, + primcount: TGLsizei){.dynlib: dllname, importc: "glMultiDrawArrays".} -proc glMultiDrawElements*(mode: TGLenum, count: PGLsizei, thetype: TGLenum, +proc glMultiDrawElements*(mode: TGLenum, count: PGLsizei, thetype: TGLenum, indices: PGLvoid, primcount: TGLsizei){. dynlib: dllname, importc: "glMultiDrawElements".} -proc glPointParameterf*(pname: TGLenum, param: TGLfloat){.dynlib: dllname, +proc glPointParameterf*(pname: TGLenum, param: TGLfloat){.dynlib: dllname, importc: "glPointParameterf".} -proc glPointParameterfv*(pname: TGLenum, params: PGLfloat){.dynlib: dllname, +proc glPointParameterfv*(pname: TGLenum, params: PGLfloat){.dynlib: dllname, importc: "glPointParameterfv".} -proc glPointParameteri*(pname: TGLenum, param: TGLint){.dynlib: dllname, +proc glPointParameteri*(pname: TGLenum, param: TGLint){.dynlib: dllname, importc: "glPointParameteri".} -proc glPointParameteriv*(pname: TGLenum, params: PGLint){.dynlib: dllname, +proc glPointParameteriv*(pname: TGLenum, params: PGLint){.dynlib: dllname, importc: "glPointParameteriv".} proc glSecondaryColor3b*(red: TGLByte, green: TGLByte, blue: TGLByte){. dynlib: dllname, importc: "glSecondaryColor3b".} -proc glSecondaryColor3bv*(v: PGLbyte){.dynlib: dllname, +proc glSecondaryColor3bv*(v: PGLbyte){.dynlib: dllname, importc: "glSecondaryColor3bv".} proc glSecondaryColor3d*(red: TGLdouble, green: TGLdouble, blue: TGLdouble){. dynlib: dllname, importc: "glSecondaryColor3d".} -proc glSecondaryColor3dv*(v: PGLdouble){.dynlib: dllname, +proc glSecondaryColor3dv*(v: PGLdouble){.dynlib: dllname, importc: "glSecondaryColor3dv".} proc glSecondaryColor3f*(red: TGLfloat, green: TGLfloat, blue: TGLfloat){. dynlib: dllname, importc: "glSecondaryColor3f".} -proc glSecondaryColor3fv*(v: PGLfloat){.dynlib: dllname, +proc glSecondaryColor3fv*(v: PGLfloat){.dynlib: dllname, importc: "glSecondaryColor3fv".} proc glSecondaryColor3i*(red: TGLint, green: TGLint, blue: TGLint){. dynlib: dllname, importc: "glSecondaryColor3i".} -proc glSecondaryColor3iv*(v: PGLint){.dynlib: dllname, +proc glSecondaryColor3iv*(v: PGLint){.dynlib: dllname, importc: "glSecondaryColor3iv".} proc glSecondaryColor3s*(red: TGLshort, green: TGLshort, blue: TGLshort){. dynlib: dllname, importc: "glSecondaryColor3s".} -proc glSecondaryColor3sv*(v: PGLshort){.dynlib: dllname, +proc glSecondaryColor3sv*(v: PGLshort){.dynlib: dllname, importc: "glSecondaryColor3sv".} proc glSecondaryColor3ub*(red: TGLubyte, green: TGLubyte, blue: TGLubyte){. dynlib: dllname, importc: "glSecondaryColor3ub".} -proc glSecondaryColor3ubv*(v: PGLubyte){.dynlib: dllname, +proc glSecondaryColor3ubv*(v: PGLubyte){.dynlib: dllname, importc: "glSecondaryColor3ubv".} proc glSecondaryColor3ui*(red: TGLuint, green: TGLuint, blue: TGLuint){. dynlib: dllname, importc: "glSecondaryColor3ui".} -proc glSecondaryColor3uiv*(v: PGLuint){.dynlib: dllname, +proc glSecondaryColor3uiv*(v: PGLuint){.dynlib: dllname, importc: "glSecondaryColor3uiv".} proc glSecondaryColor3us*(red: TGLushort, green: TGLushort, blue: TGLushort){. dynlib: dllname, importc: "glSecondaryColor3us".} -proc glSecondaryColor3usv*(v: PGLushort){.dynlib: dllname, +proc glSecondaryColor3usv*(v: PGLushort){.dynlib: dllname, importc: "glSecondaryColor3usv".} -proc glSecondaryColorPointer*(size: TGLint, thetype: TGLenum, stride: TGLsizei, - pointer: PGLvoid){.dynlib: dllname, +proc glSecondaryColorPointer*(size: TGLint, thetype: TGLenum, stride: TGLsizei, + pointer: PGLvoid){.dynlib: dllname, importc: "glSecondaryColorPointer".} -proc glWindowPos2d*(x: TGLdouble, y: TGLdouble){.dynlib: dllname, +proc glWindowPos2d*(x: TGLdouble, y: TGLdouble){.dynlib: dllname, importc: "glWindowPos2d".} proc glWindowPos2dv*(v: PGLdouble){.dynlib: dllname, importc: "glWindowPos2dv".} -proc glWindowPos2f*(x: TGLfloat, y: TGLfloat){.dynlib: dllname, +proc glWindowPos2f*(x: TGLfloat, y: TGLfloat){.dynlib: dllname, importc: "glWindowPos2f".} proc glWindowPos2fv*(v: PGLfloat){.dynlib: dllname, importc: "glWindowPos2fv".} -proc glWindowPos2i*(x: TGLint, y: TGLint){.dynlib: dllname, +proc glWindowPos2i*(x: TGLint, y: TGLint){.dynlib: dllname, importc: "glWindowPos2i".} proc glWindowPos2iv*(v: PGLint){.dynlib: dllname, importc: "glWindowPos2iv".} -proc glWindowPos2s*(x: TGLshort, y: TGLshort){.dynlib: dllname, +proc glWindowPos2s*(x: TGLshort, y: TGLshort){.dynlib: dllname, importc: "glWindowPos2s".} proc glWindowPos2sv*(v: PGLshort){.dynlib: dllname, importc: "glWindowPos2sv".} -proc glWindowPos3d*(x: TGLdouble, y: TGLdouble, z: TGLdouble){.dynlib: dllname, +proc glWindowPos3d*(x: TGLdouble, y: TGLdouble, z: TGLdouble){.dynlib: dllname, importc: "glWindowPos3d".} proc glWindowPos3dv*(v: PGLdouble){.dynlib: dllname, importc: "glWindowPos3dv".} -proc glWindowPos3f*(x: TGLfloat, y: TGLfloat, z: TGLfloat){.dynlib: dllname, +proc glWindowPos3f*(x: TGLfloat, y: TGLfloat, z: TGLfloat){.dynlib: dllname, importc: "glWindowPos3f".} proc glWindowPos3fv*(v: PGLfloat){.dynlib: dllname, importc: "glWindowPos3fv".} -proc glWindowPos3i*(x: TGLint, y: TGLint, z: TGLint){.dynlib: dllname, +proc glWindowPos3i*(x: TGLint, y: TGLint, z: TGLint){.dynlib: dllname, importc: "glWindowPos3i".} proc glWindowPos3iv*(v: PGLint){.dynlib: dllname, importc: "glWindowPos3iv".} -proc glWindowPos3s*(x: TGLshort, y: TGLshort, z: TGLshort){.dynlib: dllname, +proc glWindowPos3s*(x: TGLshort, y: TGLshort, z: TGLshort){.dynlib: dllname, importc: "glWindowPos3s".} proc glWindowPos3sv*(v: PGLshort){.dynlib: dllname, importc: "glWindowPos3sv".} #***** GL_version_1_5 *****// -const +const GL_BUFFER_SIZE* = 0x00008764 GL_BUFFER_USAGE* = 0x00008765 GL_QUERY_COUNTER_BITS* = 0x00008864 @@ -4545,12 +4545,12 @@ const GL_SRC1_ALPHA* = 0x00008589 GL_SRC2_ALPHA* = 0x0000858A -proc glGenQueries*(n: TGLsizei, ids: PGLuint){.dynlib: dllname, +proc glGenQueries*(n: TGLsizei, ids: PGLuint){.dynlib: dllname, importc: "glGenQueries".} -proc glDeleteQueries*(n: TGLsizei, ids: PGLuint){.dynlib: dllname, +proc glDeleteQueries*(n: TGLsizei, ids: PGLuint){.dynlib: dllname, importc: "glDeleteQueries".} proc glIsQuery*(id: TGLuint): TGLboolean{.dynlib: dllname, importc: "glIsQuery".} -proc glBeginQuery*(target: TGLenum, id: TGLuint){.dynlib: dllname, +proc glBeginQuery*(target: TGLenum, id: TGLuint){.dynlib: dllname, importc: "glBeginQuery".} proc glEndQuery*(target: TGLenum){.dynlib: dllname, importc: "glEndQuery".} proc glGetQueryiv*(target: TGLenum, pname: TGLenum, params: PGLint){. @@ -4559,32 +4559,32 @@ proc glGetQueryObjectiv*(id: TGLuint, pname: TGLenum, params: PGLint){. dynlib: dllname, importc: "glGetQueryObjectiv".} proc glGetQueryObjectuiv*(id: TGLuint, pname: TGLenum, params: PGLuint){. dynlib: dllname, importc: "glGetQueryObjectuiv".} -proc glBindBuffer*(target: TGLenum, buffer: TGLuint){.dynlib: dllname, +proc glBindBuffer*(target: TGLenum, buffer: TGLuint){.dynlib: dllname, importc: "glBindBuffer".} -proc glDeleteBuffers*(n: TGLsizei, buffers: PGLuint){.dynlib: dllname, +proc glDeleteBuffers*(n: TGLsizei, buffers: PGLuint){.dynlib: dllname, importc: "glDeleteBuffers".} -proc glGenBuffers*(n: TGLsizei, buffers: PGLuint){.dynlib: dllname, +proc glGenBuffers*(n: TGLsizei, buffers: PGLuint){.dynlib: dllname, importc: "glGenBuffers".} -proc glIsBuffer*(buffer: TGLuint): TGLboolean{.dynlib: dllname, +proc glIsBuffer*(buffer: TGLuint): TGLboolean{.dynlib: dllname, importc: "glIsBuffer".} -proc glBufferData*(target: TGLenum, size: GLsizeiptr, data: PGLvoid, +proc glBufferData*(target: TGLenum, size: GLsizeiptr, data: PGLvoid, usage: TGLenum){.dynlib: dllname, importc: "glBufferData".} -proc glBufferSubData*(target: TGLenum, offset: GLintptr, size: GLsizeiptr, - data: PGLvoid){.dynlib: dllname, +proc glBufferSubData*(target: TGLenum, offset: GLintptr, size: GLsizeiptr, + data: PGLvoid){.dynlib: dllname, importc: "glBufferSubData".} -proc glGetBufferSubData*(target: TGLenum, offset: GLintptr, size: GLsizeiptr, - data: PGLvoid){.dynlib: dllname, +proc glGetBufferSubData*(target: TGLenum, offset: GLintptr, size: GLsizeiptr, + data: PGLvoid){.dynlib: dllname, importc: "glGetBufferSubData".} -proc glMapBuffer*(target: TGLenum, access: TGLenum): PGLvoid{.dynlib: dllname, +proc glMapBuffer*(target: TGLenum, access: TGLenum): PGLvoid{.dynlib: dllname, importc: "glMapBuffer".} -proc glUnmapBuffer*(target: TGLenum): TGLboolean{.dynlib: dllname, +proc glUnmapBuffer*(target: TGLenum): TGLboolean{.dynlib: dllname, importc: "glUnmapBuffer".} proc glGetBufferParameteriv*(target: TGLenum, pname: TGLenum, params: PGLint){. dynlib: dllname, importc: "glGetBufferParameteriv".} proc glGetBufferPointerv*(target: TGLenum, pname: TGLenum, params: PGLvoid){. dynlib: dllname, importc: "glGetBufferPointerv".} #***** GL_version_2_0 *****// -const +const GL_BLEND_EQUATION_RGB* = 0x00008009 GL_VERTEX_ATTRIB_ARRAY_ENABLED* = 0x00008622 GL_VERTEX_ATTRIB_ARRAY_SIZE* = 0x00008623 @@ -4670,4 +4670,4 @@ const GL_STENCIL_BACK_VALUE_MASK* = 0x00008CA4 GL_STENCIL_BACK_WRITEMASK* = 0x00008CA5 -{.pop.} \ No newline at end of file +{.pop.} diff --git a/tests/manyloc/keineschweine/lib/glu.nim b/tests/manyloc/keineschweine/lib/glu.nim index e00120d83..867d0e47f 100644 --- a/tests/manyloc/keineschweine/lib/glu.nim +++ b/tests/manyloc/keineschweine/lib/glu.nim @@ -4,28 +4,28 @@ # Sebastian Guenther (sg@freepascal.org) in 2002 # These units are free to use #****************************************************************************** -# Converted to Delphi by Tom Nuydens (tom@delphi3d.net) -# For the latest updates, visit Delphi3D: http://www.delphi3d.net +# Converted to Delphi by Tom Nuydens (tom@delphi3d.net) +# For the latest updates, visit Delphi3D: http://www.delphi3d.net #****************************************************************************** -import +import GL -when defined(windows): +when defined(windows): {.push, callconv: stdcall.} -else: +else: {.push, callconv: cdecl.} -when defined(windows): - const +when defined(windows): + const dllname = "glu32.dll" -elif defined(macosx): - const +elif defined(macosx): + const dllname = "/System/Library/Frameworks/OpenGL.framework/Libraries/libGLU.dylib" -else: - const +else: + const dllname = "libGLU.so.1" -type +type TViewPortArray* = array[0..3, TGLint] T16dArray* = array[0..15, TGLdouble] TCallBack* = proc () @@ -34,12 +34,12 @@ type T4fArray* = array[0..3, TGLfloat] PPointer* = ptr Pointer -type - GLUnurbs*{.final.} = object +type + GLUnurbs*{.final.} = object PGLUnurbs* = ptr GLUnurbs - GLUquadric*{.final.} = object + GLUquadric*{.final.} = object PGLUquadric* = ptr GLUquadric - GLUtesselator*{.final.} = object + GLUtesselator*{.final.} = object PGLUtesselator* = ptr GLUtesselator # backwards compatibility: GLUnurbsObj* = GLUnurbs PGLUnurbsObj* = PGLUnurbs @@ -57,40 +57,40 @@ type TGLUtesselatorObj* = GLUtesselatorObj TGLUtriangulatorObj* = GLUtriangulatorObj -proc gluErrorString*(errCode: TGLenum): cstring{.dynlib: dllname, +proc gluErrorString*(errCode: TGLenum): cstring{.dynlib: dllname, importc: "gluErrorString".} -proc gluErrorUnicodeStringEXT*(errCode: TGLenum): ptr int16{.dynlib: dllname, +proc gluErrorUnicodeStringEXT*(errCode: TGLenum): ptr int16{.dynlib: dllname, importc: "gluErrorUnicodeStringEXT".} -proc gluGetString*(name: TGLenum): cstring{.dynlib: dllname, +proc gluGetString*(name: TGLenum): cstring{.dynlib: dllname, importc: "gluGetString".} -proc gluOrtho2D*(left, right, bottom, top: TGLdouble){.dynlib: dllname, +proc gluOrtho2D*(left, right, bottom, top: TGLdouble){.dynlib: dllname, importc: "gluOrtho2D".} -proc gluPerspective*(fovy, aspect, zNear, zFar: TGLdouble){.dynlib: dllname, +proc gluPerspective*(fovy, aspect, zNear, zFar: TGLdouble){.dynlib: dllname, importc: "gluPerspective".} proc gluPickMatrix*(x, y, width, height: TGLdouble, viewport: var TViewPortArray){. dynlib: dllname, importc: "gluPickMatrix".} proc gluLookAt*(eyex, eyey, eyez, centerx, centery, centerz, upx, upy, upz: TGLdouble){. dynlib: dllname, importc: "gluLookAt".} -proc gluProject*(objx, objy, objz: TGLdouble, - modelMatrix, projMatrix: var T16dArray, +proc gluProject*(objx, objy, objz: TGLdouble, + modelMatrix, projMatrix: var T16dArray, viewport: var TViewPortArray, winx, winy, winz: PGLdouble): int{. dynlib: dllname, importc: "gluProject".} -proc gluUnProject*(winx, winy, winz: TGLdouble, - modelMatrix, projMatrix: var T16dArray, +proc gluUnProject*(winx, winy, winz: TGLdouble, + modelMatrix, projMatrix: var T16dArray, viewport: var TViewPortArray, objx, objy, objz: PGLdouble): int{. dynlib: dllname, importc: "gluUnProject".} -proc gluScaleImage*(format: TGLenum, widthin, heightin: TGLint, typein: TGLenum, - datain: Pointer, widthout, heightout: TGLint, - typeout: TGLenum, dataout: Pointer): int{.dynlib: dllname, +proc gluScaleImage*(format: TGLenum, widthin, heightin: TGLint, typein: TGLenum, + datain: Pointer, widthout, heightout: TGLint, + typeout: TGLenum, dataout: Pointer): int{.dynlib: dllname, importc: "gluScaleImage".} -proc gluBuild1DMipmaps*(target: TGLenum, components, width: TGLint, +proc gluBuild1DMipmaps*(target: TGLenum, components, width: TGLint, format, atype: TGLenum, data: Pointer): int{. dynlib: dllname, importc: "gluBuild1DMipmaps".} -proc gluBuild2DMipmaps*(target: TGLenum, components, width, height: TGLint, +proc gluBuild2DMipmaps*(target: TGLenum, components, width, height: TGLint, format, atype: TGLenum, data: Pointer): int{. dynlib: dllname, importc: "gluBuild2DMipmaps".} proc gluNewQuadric*(): PGLUquadric{.dynlib: dllname, importc: "gluNewQuadric".} -proc gluDeleteQuadric*(state: PGLUquadric){.dynlib: dllname, +proc gluDeleteQuadric*(state: PGLUquadric){.dynlib: dllname, importc: "gluDeleteQuadric".} proc gluQuadricNormals*(quadObject: PGLUquadric, normals: TGLenum){. dynlib: dllname, importc: "gluQuadricNormals".} @@ -100,12 +100,12 @@ proc gluQuadricOrientation*(quadObject: PGLUquadric, orientation: TGLenum){. dynlib: dllname, importc: "gluQuadricOrientation".} proc gluQuadricDrawStyle*(quadObject: PGLUquadric, drawStyle: TGLenum){. dynlib: dllname, importc: "gluQuadricDrawStyle".} -proc gluCylinder*(qobj: PGLUquadric, baseRadius, topRadius, height: TGLdouble, - slices, stacks: TGLint){.dynlib: dllname, +proc gluCylinder*(qobj: PGLUquadric, baseRadius, topRadius, height: TGLdouble, + slices, stacks: TGLint){.dynlib: dllname, importc: "gluCylinder".} -proc gluDisk*(qobj: PGLUquadric, innerRadius, outerRadius: TGLdouble, +proc gluDisk*(qobj: PGLUquadric, innerRadius, outerRadius: TGLdouble, slices, loops: TGLint){.dynlib: dllname, importc: "gluDisk".} -proc gluPartialDisk*(qobj: PGLUquadric, innerRadius, outerRadius: TGLdouble, +proc gluPartialDisk*(qobj: PGLUquadric, innerRadius, outerRadius: TGLdouble, slices, loops: TGLint, startAngle, sweepAngle: TGLdouble){. dynlib: dllname, importc: "gluPartialDisk".} proc gluSphere*(qobj: PGLuquadric, radius: TGLdouble, slices, stacks: TGLint){. @@ -113,51 +113,51 @@ proc gluSphere*(qobj: PGLuquadric, radius: TGLdouble, slices, stacks: TGLint){. proc gluQuadricCallback*(qobj: PGLUquadric, which: TGLenum, fn: TCallBack){. dynlib: dllname, importc: "gluQuadricCallback".} proc gluNewTess*(): PGLUtesselator{.dynlib: dllname, importc: "gluNewTess".} -proc gluDeleteTess*(tess: PGLUtesselator){.dynlib: dllname, +proc gluDeleteTess*(tess: PGLUtesselator){.dynlib: dllname, importc: "gluDeleteTess".} proc gluTessBeginPolygon*(tess: PGLUtesselator, polygon_data: Pointer){. dynlib: dllname, importc: "gluTessBeginPolygon".} -proc gluTessBeginContour*(tess: PGLUtesselator){.dynlib: dllname, +proc gluTessBeginContour*(tess: PGLUtesselator){.dynlib: dllname, importc: "gluTessBeginContour".} proc gluTessVertex*(tess: PGLUtesselator, coords: var T3dArray, data: Pointer){. dynlib: dllname, importc: "gluTessVertex".} -proc gluTessEndContour*(tess: PGLUtesselator){.dynlib: dllname, +proc gluTessEndContour*(tess: PGLUtesselator){.dynlib: dllname, importc: "gluTessEndContour".} -proc gluTessEndPolygon*(tess: PGLUtesselator){.dynlib: dllname, +proc gluTessEndPolygon*(tess: PGLUtesselator){.dynlib: dllname, importc: "gluTessEndPolygon".} proc gluTessProperty*(tess: PGLUtesselator, which: TGLenum, value: TGLdouble){. dynlib: dllname, importc: "gluTessProperty".} -proc gluTessNormal*(tess: PGLUtesselator, x, y, z: TGLdouble){.dynlib: dllname, +proc gluTessNormal*(tess: PGLUtesselator, x, y, z: TGLdouble){.dynlib: dllname, importc: "gluTessNormal".} proc gluTessCallback*(tess: PGLUtesselator, which: TGLenum, fn: TCallBack){. dynlib: dllname, importc: "gluTessCallback".} proc gluGetTessProperty*(tess: PGLUtesselator, which: TGLenum, value: PGLdouble){. dynlib: dllname, importc: "gluGetTessProperty".} -proc gluNewNurbsRenderer*(): PGLUnurbs{.dynlib: dllname, +proc gluNewNurbsRenderer*(): PGLUnurbs{.dynlib: dllname, importc: "gluNewNurbsRenderer".} -proc gluDeleteNurbsRenderer*(nobj: PGLUnurbs){.dynlib: dllname, +proc gluDeleteNurbsRenderer*(nobj: PGLUnurbs){.dynlib: dllname, importc: "gluDeleteNurbsRenderer".} -proc gluBeginSurface*(nobj: PGLUnurbs){.dynlib: dllname, +proc gluBeginSurface*(nobj: PGLUnurbs){.dynlib: dllname, importc: "gluBeginSurface".} proc gluBeginCurve*(nobj: PGLUnurbs){.dynlib: dllname, importc: "gluBeginCurve".} proc gluEndCurve*(nobj: PGLUnurbs){.dynlib: dllname, importc: "gluEndCurve".} proc gluEndSurface*(nobj: PGLUnurbs){.dynlib: dllname, importc: "gluEndSurface".} proc gluBeginTrim*(nobj: PGLUnurbs){.dynlib: dllname, importc: "gluBeginTrim".} proc gluEndTrim*(nobj: PGLUnurbs){.dynlib: dllname, importc: "gluEndTrim".} -proc gluPwlCurve*(nobj: PGLUnurbs, count: TGLint, aarray: PGLfloat, - stride: TGLint, atype: TGLenum){.dynlib: dllname, +proc gluPwlCurve*(nobj: PGLUnurbs, count: TGLint, aarray: PGLfloat, + stride: TGLint, atype: TGLenum){.dynlib: dllname, importc: "gluPwlCurve".} -proc gluNurbsCurve*(nobj: PGLUnurbs, nknots: TGLint, knot: PGLfloat, - stride: TGLint, ctlarray: PGLfloat, order: TGLint, +proc gluNurbsCurve*(nobj: PGLUnurbs, nknots: TGLint, knot: PGLfloat, + stride: TGLint, ctlarray: PGLfloat, order: TGLint, atype: TGLenum){.dynlib: dllname, importc: "gluNurbsCurve".} -proc gluNurbsSurface*(nobj: PGLUnurbs, sknot_count: TGLint, sknot: PGLfloat, - tknot_count: TGLint, tknot: PGLfloat, - s_stride, t_stride: TGLint, ctlarray: PGLfloat, - sorder, torder: TGLint, atype: TGLenum){.dynlib: dllname, +proc gluNurbsSurface*(nobj: PGLUnurbs, sknot_count: TGLint, sknot: PGLfloat, + tknot_count: TGLint, tknot: PGLfloat, + s_stride, t_stride: TGLint, ctlarray: PGLfloat, + sorder, torder: TGLint, atype: TGLenum){.dynlib: dllname, importc: "gluNurbsSurface".} -proc gluLoadSamplingMatrices*(nobj: PGLUnurbs, - modelMatrix, projMatrix: var T16dArray, - viewport: var TViewPortArray){.dynlib: dllname, +proc gluLoadSamplingMatrices*(nobj: PGLUnurbs, + modelMatrix, projMatrix: var T16dArray, + viewport: var TViewPortArray){.dynlib: dllname, importc: "gluLoadSamplingMatrices".} proc gluNurbsProperty*(nobj: PGLUnurbs, aproperty: TGLenum, value: TGLfloat){. dynlib: dllname, importc: "gluNurbsProperty".} @@ -173,16 +173,16 @@ type # gluQuadricCallback GLUtessVertexProc* = proc (p: Pointer) GLUtessEndProc* = proc () GLUtessErrorProc* = proc (p: TGLenum) - GLUtessCombineProc* = proc (p1: var T3dArray, p2: T4pArray, p3: T4fArray, + GLUtessCombineProc* = proc (p1: var T3dArray, p2: T4pArray, p3: T4fArray, p4: PPointer) GLUtessBeginDataProc* = proc (p1: TGLenum, p2: Pointer) GLUtessEdgeFlagDataProc* = proc (p1: TGLboolean, p2: Pointer) GLUtessVertexDataProc* = proc (p1, p2: Pointer) GLUtessEndDataProc* = proc (p: Pointer) GLUtessErrorDataProc* = proc (p1: TGLenum, p2: Pointer) - GLUtessCombineDataProc* = proc (p1: var T3dArray, p2: var T4pArray, - p3: var T4fArray, p4: PPointer, p5: Pointer) # - # + GLUtessCombineDataProc* = proc (p1: var T3dArray, p2: var T4pArray, + p3: var T4fArray, p4: PPointer, p5: Pointer) # + # # gluNurbsCallback GLUnurbsErrorProc* = proc (p: TGLenum) #*** Generic constants ****/ @@ -226,21 +226,21 @@ const # Version GLU_TESS_COMBINE* = 100105 # void (CALLBACK*)(TGLdouble coords[3], # void *data[4], # TGLfloat weight[4], - # void **dataOut) + # void **dataOut) GLU_TESS_BEGIN_DATA* = 100106 # void (CALLBACK*)(TGLenum type, - # void *polygon_data) + # void *polygon_data) GLU_TESS_VERTEX_DATA* = 100107 # void (CALLBACK*)(void *data, - # void *polygon_data) + # void *polygon_data) GLU_TESS_END_DATA* = 100108 # void (CALLBACK*)(void *polygon_data) GLU_TESS_ERROR_DATA* = 100109 # void (CALLBACK*)(TGLenum errno, - # void *polygon_data) + # void *polygon_data) GLU_TESS_EDGE_FLAG_DATA* = 100110 # void (CALLBACK*)(TGLboolean boundaryEdge, - # void *polygon_data) + # void *polygon_data) GLU_TESS_COMBINE_DATA* = 100111 # void (CALLBACK*)(TGLdouble coords[3], # void *data[4], # TGLfloat weight[4], # void **dataOut, - # void *polygon_data) + # void *polygon_data) # TessError GLU_TESS_ERROR1* = 100151 GLU_TESS_ERROR2* = 100152 @@ -313,11 +313,11 @@ const # Version GLU_NURBS_ERROR36* = 100286 GLU_NURBS_ERROR37* = 100287 #*** Backwards compatibility for old tesselator ****/ -proc gluBeginPolygon*(tess: PGLUtesselator){.dynlib: dllname, +proc gluBeginPolygon*(tess: PGLUtesselator){.dynlib: dllname, importc: "gluBeginPolygon".} -proc gluNextContour*(tess: PGLUtesselator, atype: TGLenum){.dynlib: dllname, +proc gluNextContour*(tess: PGLUtesselator, atype: TGLenum){.dynlib: dllname, importc: "gluNextContour".} -proc gluEndPolygon*(tess: PGLUtesselator){.dynlib: dllname, +proc gluEndPolygon*(tess: PGLUtesselator){.dynlib: dllname, importc: "gluEndPolygon".} const # Contours types -- obsolete! GLU_CW* = 100120 diff --git a/tests/manyloc/keineschweine/lib/glut.nim b/tests/manyloc/keineschweine/lib/glut.nim index ff157c327..44a290728 100644 --- a/tests/manyloc/keineschweine/lib/glut.nim +++ b/tests/manyloc/keineschweine/lib/glut.nim @@ -15,17 +15,17 @@ # For the latest updates, visit Delphi3D: http://www.delphi3d.net #****************************************************************************** -import +import GL -when defined(windows): - const +when defined(windows): + const dllname = "glut32.dll" -elif defined(macosx): - const +elif defined(macosx): + const dllname = "/System/Library/Frameworks/GLUT.framework/GLUT" -else: - const +else: + const dllname = "libglut.so.3" type TGlutVoidCallback* = proc (){.cdecl.} @@ -36,7 +36,7 @@ type TGlut1Char2IntCallback* = proc (c: int8, v1, v2: cint){.cdecl.} TGlut1UInt3IntCallback* = proc (u, v1, v2, v3: cint){.cdecl.} -const +const GLUT_API_VERSION* = 3 GLUT_XLIB_IMPLEMENTATION* = 12 # Display mode bit masks. GLUT_RGB* = 0 @@ -93,7 +93,7 @@ const GLUT_NORMAL* = 0 GLUT_OVERLAY* = 1 -when defined(Windows): +when defined(Windows): const # Stroke font constants (use these in GLUT program). GLUT_STROKE_ROMAN* = cast[Pointer](0) GLUT_STROKE_MONO_ROMAN* = cast[Pointer](1) # Bitmap font constants (use these in GLUT program). @@ -104,7 +104,7 @@ when defined(Windows): GLUT_BITMAP_HELVETICA_10* = cast[Pointer](6) GLUT_BITMAP_HELVETICA_12* = cast[Pointer](7) GLUT_BITMAP_HELVETICA_18* = cast[Pointer](8) -else: +else: var # Stroke font constants (use these in GLUT program). GLUT_STROKE_ROMAN*: Pointer GLUT_STROKE_MONO_ROMAN*: Pointer # Bitmap font constants (use these in GLUT program). @@ -229,7 +229,7 @@ const # glutGet parameters. GLUT_GAME_MODE_REFRESH_RATE* = 5 GLUT_GAME_MODE_DISPLAY_CHANGED* = 6 # GLUT initialization sub-API. -proc glutInit*(argcp: ptr cint, argv: pointer){.dynlib: dllname, +proc glutInit*(argcp: ptr cint, argv: pointer){.dynlib: dllname, importc: "glutInit".} proc glutInit*() = @@ -239,34 +239,34 @@ proc glutInit*() = cmdCount {.importc: "cmdCount".}: cint glutInit(addr(cmdCount), addr(cmdLine)) -proc glutInitDisplayMode*(mode: int16){.dynlib: dllname, +proc glutInitDisplayMode*(mode: int16){.dynlib: dllname, importc: "glutInitDisplayMode".} -proc glutInitDisplayString*(str: cstring){.dynlib: dllname, +proc glutInitDisplayString*(str: cstring){.dynlib: dllname, importc: "glutInitDisplayString".} -proc glutInitWindowPosition*(x, y: int){.dynlib: dllname, +proc glutInitWindowPosition*(x, y: int){.dynlib: dllname, importc: "glutInitWindowPosition".} -proc glutInitWindowSize*(width, height: int){.dynlib: dllname, +proc glutInitWindowSize*(width, height: int){.dynlib: dllname, importc: "glutInitWindowSize".} proc glutMainLoop*(){.dynlib: dllname, importc: "glutMainLoop".} # GLUT window sub-API. -proc glutCreateWindow*(title: cstring): int{.dynlib: dllname, +proc glutCreateWindow*(title: cstring): int{.dynlib: dllname, importc: "glutCreateWindow".} -proc glutCreateSubWindow*(win, x, y, width, height: int): int{.dynlib: dllname, +proc glutCreateSubWindow*(win, x, y, width, height: int): int{.dynlib: dllname, importc: "glutCreateSubWindow".} proc glutDestroyWindow*(win: int){.dynlib: dllname, importc: "glutDestroyWindow".} proc glutPostRedisplay*(){.dynlib: dllname, importc: "glutPostRedisplay".} -proc glutPostWindowRedisplay*(win: int){.dynlib: dllname, +proc glutPostWindowRedisplay*(win: int){.dynlib: dllname, importc: "glutPostWindowRedisplay".} proc glutSwapBuffers*(){.dynlib: dllname, importc: "glutSwapBuffers".} proc glutGetWindow*(): int{.dynlib: dllname, importc: "glutGetWindow".} proc glutSetWindow*(win: int){.dynlib: dllname, importc: "glutSetWindow".} -proc glutSetWindowTitle*(title: cstring){.dynlib: dllname, +proc glutSetWindowTitle*(title: cstring){.dynlib: dllname, importc: "glutSetWindowTitle".} -proc glutSetIconTitle*(title: cstring){.dynlib: dllname, +proc glutSetIconTitle*(title: cstring){.dynlib: dllname, importc: "glutSetIconTitle".} -proc glutPositionWindow*(x, y: int){.dynlib: dllname, +proc glutPositionWindow*(x, y: int){.dynlib: dllname, importc: "glutPositionWindow".} -proc glutReshapeWindow*(width, height: int){.dynlib: dllname, +proc glutReshapeWindow*(width, height: int){.dynlib: dllname, importc: "glutReshapeWindow".} proc glutPopWindow*(){.dynlib: dllname, importc: "glutPopWindow".} proc glutPushWindow*(){.dynlib: dllname, importc: "glutPushWindow".} @@ -280,107 +280,107 @@ proc glutWarpPointer*(x, y: int){.dynlib: dllname, importc: "glutWarpPointer".} proc glutEstablishOverlay*(){.dynlib: dllname, importc: "glutEstablishOverlay".} proc glutRemoveOverlay*(){.dynlib: dllname, importc: "glutRemoveOverlay".} proc glutUseLayer*(layer: TGLenum){.dynlib: dllname, importc: "glutUseLayer".} -proc glutPostOverlayRedisplay*(){.dynlib: dllname, +proc glutPostOverlayRedisplay*(){.dynlib: dllname, importc: "glutPostOverlayRedisplay".} -proc glutPostWindowOverlayRedisplay*(win: int){.dynlib: dllname, +proc glutPostWindowOverlayRedisplay*(win: int){.dynlib: dllname, importc: "glutPostWindowOverlayRedisplay".} proc glutShowOverlay*(){.dynlib: dllname, importc: "glutShowOverlay".} proc glutHideOverlay*(){.dynlib: dllname, importc: "glutHideOverlay".} # GLUT menu sub-API. -proc glutCreateMenu*(callback: TGlut1IntCallback): int{.dynlib: dllname, +proc glutCreateMenu*(callback: TGlut1IntCallback): int{.dynlib: dllname, importc: "glutCreateMenu".} proc glutDestroyMenu*(menu: int){.dynlib: dllname, importc: "glutDestroyMenu".} proc glutGetMenu*(): int{.dynlib: dllname, importc: "glutGetMenu".} proc glutSetMenu*(menu: int){.dynlib: dllname, importc: "glutSetMenu".} -proc glutAddMenuEntry*(caption: cstring, value: int){.dynlib: dllname, +proc glutAddMenuEntry*(caption: cstring, value: int){.dynlib: dllname, importc: "glutAddMenuEntry".} -proc glutAddSubMenu*(caption: cstring, submenu: int){.dynlib: dllname, +proc glutAddSubMenu*(caption: cstring, submenu: int){.dynlib: dllname, importc: "glutAddSubMenu".} proc glutChangeToMenuEntry*(item: int, caption: cstring, value: int){. dynlib: dllname, importc: "glutChangeToMenuEntry".} proc glutChangeToSubMenu*(item: int, caption: cstring, submenu: int){. dynlib: dllname, importc: "glutChangeToSubMenu".} -proc glutRemoveMenuItem*(item: int){.dynlib: dllname, +proc glutRemoveMenuItem*(item: int){.dynlib: dllname, importc: "glutRemoveMenuItem".} proc glutAttachMenu*(button: int){.dynlib: dllname, importc: "glutAttachMenu".} proc glutDetachMenu*(button: int){.dynlib: dllname, importc: "glutDetachMenu".} # GLUT window callback sub-API. -proc glutDisplayFunc*(f: TGlutVoidCallback){.dynlib: dllname, +proc glutDisplayFunc*(f: TGlutVoidCallback){.dynlib: dllname, importc: "glutDisplayFunc".} -proc glutReshapeFunc*(f: TGlut2IntCallback){.dynlib: dllname, +proc glutReshapeFunc*(f: TGlut2IntCallback){.dynlib: dllname, importc: "glutReshapeFunc".} -proc glutKeyboardFunc*(f: TGlut1Char2IntCallback){.dynlib: dllname, +proc glutKeyboardFunc*(f: TGlut1Char2IntCallback){.dynlib: dllname, importc: "glutKeyboardFunc".} -proc glutMouseFunc*(f: TGlut4IntCallback){.dynlib: dllname, +proc glutMouseFunc*(f: TGlut4IntCallback){.dynlib: dllname, importc: "glutMouseFunc".} -proc glutMotionFunc*(f: TGlut2IntCallback){.dynlib: dllname, +proc glutMotionFunc*(f: TGlut2IntCallback){.dynlib: dllname, importc: "glutMotionFunc".} -proc glutPassiveMotionFunc*(f: TGlut2IntCallback){.dynlib: dllname, +proc glutPassiveMotionFunc*(f: TGlut2IntCallback){.dynlib: dllname, importc: "glutPassiveMotionFunc".} -proc glutEntryFunc*(f: TGlut1IntCallback){.dynlib: dllname, +proc glutEntryFunc*(f: TGlut1IntCallback){.dynlib: dllname, importc: "glutEntryFunc".} -proc glutVisibilityFunc*(f: TGlut1IntCallback){.dynlib: dllname, +proc glutVisibilityFunc*(f: TGlut1IntCallback){.dynlib: dllname, importc: "glutVisibilityFunc".} -proc glutIdleFunc*(f: TGlutVoidCallback){.dynlib: dllname, +proc glutIdleFunc*(f: TGlutVoidCallback){.dynlib: dllname, importc: "glutIdleFunc".} proc glutTimerFunc*(millis: int16, f: TGlut1IntCallback, value: int){. dynlib: dllname, importc: "glutTimerFunc".} -proc glutMenuStateFunc*(f: TGlut1IntCallback){.dynlib: dllname, +proc glutMenuStateFunc*(f: TGlut1IntCallback){.dynlib: dllname, importc: "glutMenuStateFunc".} -proc glutSpecialFunc*(f: TGlut3IntCallback){.dynlib: dllname, +proc glutSpecialFunc*(f: TGlut3IntCallback){.dynlib: dllname, importc: "glutSpecialFunc".} -proc glutSpaceballMotionFunc*(f: TGlut3IntCallback){.dynlib: dllname, +proc glutSpaceballMotionFunc*(f: TGlut3IntCallback){.dynlib: dllname, importc: "glutSpaceballMotionFunc".} -proc glutSpaceballRotateFunc*(f: TGlut3IntCallback){.dynlib: dllname, +proc glutSpaceballRotateFunc*(f: TGlut3IntCallback){.dynlib: dllname, importc: "glutSpaceballRotateFunc".} -proc glutSpaceballButtonFunc*(f: TGlut2IntCallback){.dynlib: dllname, +proc glutSpaceballButtonFunc*(f: TGlut2IntCallback){.dynlib: dllname, importc: "glutSpaceballButtonFunc".} -proc glutButtonBoxFunc*(f: TGlut2IntCallback){.dynlib: dllname, +proc glutButtonBoxFunc*(f: TGlut2IntCallback){.dynlib: dllname, importc: "glutButtonBoxFunc".} -proc glutDialsFunc*(f: TGlut2IntCallback){.dynlib: dllname, +proc glutDialsFunc*(f: TGlut2IntCallback){.dynlib: dllname, importc: "glutDialsFunc".} -proc glutTabletMotionFunc*(f: TGlut2IntCallback){.dynlib: dllname, +proc glutTabletMotionFunc*(f: TGlut2IntCallback){.dynlib: dllname, importc: "glutTabletMotionFunc".} -proc glutTabletButtonFunc*(f: TGlut4IntCallback){.dynlib: dllname, +proc glutTabletButtonFunc*(f: TGlut4IntCallback){.dynlib: dllname, importc: "glutTabletButtonFunc".} -proc glutMenuStatusFunc*(f: TGlut3IntCallback){.dynlib: dllname, +proc glutMenuStatusFunc*(f: TGlut3IntCallback){.dynlib: dllname, importc: "glutMenuStatusFunc".} -proc glutOverlayDisplayFunc*(f: TGlutVoidCallback){.dynlib: dllname, +proc glutOverlayDisplayFunc*(f: TGlutVoidCallback){.dynlib: dllname, importc: "glutOverlayDisplayFunc".} -proc glutWindowStatusFunc*(f: TGlut1IntCallback){.dynlib: dllname, +proc glutWindowStatusFunc*(f: TGlut1IntCallback){.dynlib: dllname, importc: "glutWindowStatusFunc".} -proc glutKeyboardUpFunc*(f: TGlut1Char2IntCallback){.dynlib: dllname, +proc glutKeyboardUpFunc*(f: TGlut1Char2IntCallback){.dynlib: dllname, importc: "glutKeyboardUpFunc".} -proc glutSpecialUpFunc*(f: TGlut3IntCallback){.dynlib: dllname, +proc glutSpecialUpFunc*(f: TGlut3IntCallback){.dynlib: dllname, importc: "glutSpecialUpFunc".} proc glutJoystickFunc*(f: TGlut1UInt3IntCallback, pollInterval: int){. dynlib: dllname, importc: "glutJoystickFunc".} # GLUT color index sub-API. -proc glutSetColor*(cell: int, red, green, blue: TGLfloat){.dynlib: dllname, +proc glutSetColor*(cell: int, red, green, blue: TGLfloat){.dynlib: dllname, importc: "glutSetColor".} -proc glutGetColor*(ndx, component: int): TGLfloat{.dynlib: dllname, +proc glutGetColor*(ndx, component: int): TGLfloat{.dynlib: dllname, importc: "glutGetColor".} proc glutCopyColormap*(win: int){.dynlib: dllname, importc: "glutCopyColormap".} # GLUT state retrieval sub-API. proc glutGet*(t: TGLenum): int{.dynlib: dllname, importc: "glutGet".} proc glutDeviceGet*(t: TGLenum): int{.dynlib: dllname, importc: "glutDeviceGet".} # GLUT extension support sub-API -proc glutExtensionSupported*(name: cstring): int{.dynlib: dllname, +proc glutExtensionSupported*(name: cstring): int{.dynlib: dllname, importc: "glutExtensionSupported".} proc glutGetModifiers*(): int{.dynlib: dllname, importc: "glutGetModifiers".} proc glutLayerGet*(t: TGLenum): int{.dynlib: dllname, importc: "glutLayerGet".} # GLUT font sub-API -proc glutBitmapCharacter*(font: pointer, character: int){.dynlib: dllname, +proc glutBitmapCharacter*(font: pointer, character: int){.dynlib: dllname, importc: "glutBitmapCharacter".} -proc glutBitmapWidth*(font: pointer, character: int): int{.dynlib: dllname, +proc glutBitmapWidth*(font: pointer, character: int): int{.dynlib: dllname, importc: "glutBitmapWidth".} -proc glutStrokeCharacter*(font: pointer, character: int){.dynlib: dllname, +proc glutStrokeCharacter*(font: pointer, character: int){.dynlib: dllname, importc: "glutStrokeCharacter".} -proc glutStrokeWidth*(font: pointer, character: int): int{.dynlib: dllname, +proc glutStrokeWidth*(font: pointer, character: int): int{.dynlib: dllname, importc: "glutStrokeWidth".} -proc glutBitmapLength*(font: pointer, str: cstring): int{.dynlib: dllname, +proc glutBitmapLength*(font: pointer, str: cstring): int{.dynlib: dllname, importc: "glutBitmapLength".} -proc glutStrokeLength*(font: pointer, str: cstring): int{.dynlib: dllname, +proc glutStrokeLength*(font: pointer, str: cstring): int{.dynlib: dllname, importc: "glutStrokeLength".} # GLUT pre-built models sub-API proc glutWireSphere*(radius: TGLdouble, slices, stacks: TGLint){. @@ -399,9 +399,9 @@ proc glutSolidTorus*(innerRadius, outerRadius: TGLdouble, sides, rings: TGLint){ dynlib: dllname, importc: "glutSolidTorus".} proc glutWireDodecahedron*(){.dynlib: dllname, importc: "glutWireDodecahedron".} proc glutSolidDodecahedron*(){.dynlib: dllname, importc: "glutSolidDodecahedron".} -proc glutWireTeapot*(size: TGLdouble){.dynlib: dllname, +proc glutWireTeapot*(size: TGLdouble){.dynlib: dllname, importc: "glutWireTeapot".} -proc glutSolidTeapot*(size: TGLdouble){.dynlib: dllname, +proc glutSolidTeapot*(size: TGLdouble){.dynlib: dllname, importc: "glutSolidTeapot".} proc glutWireOctahedron*(){.dynlib: dllname, importc: "glutWireOctahedron".} proc glutSolidOctahedron*(){.dynlib: dllname, importc: "glutSolidOctahedron".} @@ -410,29 +410,29 @@ proc glutSolidTetrahedron*(){.dynlib: dllname, importc: "glutSolidTetrahedron".} proc glutWireIcosahedron*(){.dynlib: dllname, importc: "glutWireIcosahedron".} proc glutSolidIcosahedron*(){.dynlib: dllname, importc: "glutSolidIcosahedron".} # GLUT video resize sub-API. -proc glutVideoResizeGet*(param: TGLenum): int{.dynlib: dllname, +proc glutVideoResizeGet*(param: TGLenum): int{.dynlib: dllname, importc: "glutVideoResizeGet".} -proc glutSetupVideoResizing*(){.dynlib: dllname, +proc glutSetupVideoResizing*(){.dynlib: dllname, importc: "glutSetupVideoResizing".} proc glutStopVideoResizing*(){.dynlib: dllname, importc: "glutStopVideoResizing".} -proc glutVideoResize*(x, y, width, height: int){.dynlib: dllname, +proc glutVideoResize*(x, y, width, height: int){.dynlib: dllname, importc: "glutVideoResize".} -proc glutVideoPan*(x, y, width, height: int){.dynlib: dllname, +proc glutVideoPan*(x, y, width, height: int){.dynlib: dllname, importc: "glutVideoPan".} # GLUT debugging sub-API. proc glutReportErrors*(){.dynlib: dllname, importc: "glutReportErrors".} # GLUT device control sub-API. -proc glutIgnoreKeyRepeat*(ignore: int){.dynlib: dllname, +proc glutIgnoreKeyRepeat*(ignore: int){.dynlib: dllname, importc: "glutIgnoreKeyRepeat".} -proc glutSetKeyRepeat*(repeatMode: int){.dynlib: dllname, +proc glutSetKeyRepeat*(repeatMode: int){.dynlib: dllname, importc: "glutSetKeyRepeat".} proc glutForceJoystickFunc*(){.dynlib: dllname, importc: "glutForceJoystickFunc".} # GLUT game mode sub-API. #example glutGameModeString('1280x1024:32@75'); -proc glutGameModeString*(AString: cstring){.dynlib: dllname, +proc glutGameModeString*(AString: cstring){.dynlib: dllname, importc: "glutGameModeString".} proc glutEnterGameMode*(): int{.dynlib: dllname, importc: "glutEnterGameMode".} proc glutLeaveGameMode*(){.dynlib: dllname, importc: "glutLeaveGameMode".} -proc glutGameModeGet*(mode: TGLenum): int{.dynlib: dllname, +proc glutGameModeGet*(mode: TGLenum): int{.dynlib: dllname, importc: "glutGameModeGet".} # implementation diff --git a/tests/manyloc/keineschweine/lib/glx.nim b/tests/manyloc/keineschweine/lib/glx.nim index 76c052d70..ce02835bd 100644 --- a/tests/manyloc/keineschweine/lib/glx.nim +++ b/tests/manyloc/keineschweine/lib/glx.nim @@ -23,19 +23,19 @@ # Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # -import +import X, XLib, XUtil, gl -when defined(windows): - const +when defined(windows): + const dllname = "GL.dll" -elif defined(macosx): - const +elif defined(macosx): + const dllname = "/usr/X11R6/lib/libGL.dylib" -else: - const +else: + const dllname = "libGL.so" -const +const GLX_USE_GL* = 1 GLX_BUFFER_SIZE* = 2 GLX_LEVEL* = 3 @@ -98,55 +98,55 @@ type # From XLib: proc glXChooseVisual*(dpy: PDisplay, screen: int, attribList: ptr int32): PXVisualInfo{. cdecl, dynlib: dllname, importc: "glXChooseVisual".} -proc glXCreateContext*(dpy: PDisplay, vis: PXVisualInfo, shareList: GLXContext, - direct: bool): GLXContext{.cdecl, dynlib: dllname, +proc glXCreateContext*(dpy: PDisplay, vis: PXVisualInfo, shareList: GLXContext, + direct: bool): GLXContext{.cdecl, dynlib: dllname, importc: "glXCreateContext".} -proc glXDestroyContext*(dpy: PDisplay, ctx: GLXContext){.cdecl, dynlib: dllname, +proc glXDestroyContext*(dpy: PDisplay, ctx: GLXContext){.cdecl, dynlib: dllname, importc: "glXDestroyContext".} proc glXMakeCurrent*(dpy: PDisplay, drawable: GLXDrawable, ctx: GLXContext): bool{. cdecl, dynlib: dllname, importc: "glXMakeCurrent".} -proc glXCopyContext*(dpy: PDisplay, src, dst: GLXContext, mask: int32){.cdecl, +proc glXCopyContext*(dpy: PDisplay, src, dst: GLXContext, mask: int32){.cdecl, dynlib: dllname, importc: "glXCopyContext".} -proc glXSwapBuffers*(dpy: PDisplay, drawable: GLXDrawable){.cdecl, +proc glXSwapBuffers*(dpy: PDisplay, drawable: GLXDrawable){.cdecl, dynlib: dllname, importc: "glXSwapBuffers".} proc glXCreateGLXPixmap*(dpy: PDisplay, visual: PXVisualInfo, pixmap: XPixmap): GLXPixmap{. cdecl, dynlib: dllname, importc: "glXCreateGLXPixmap".} -proc glXDestroyGLXPixmap*(dpy: PDisplay, pixmap: GLXPixmap){.cdecl, +proc glXDestroyGLXPixmap*(dpy: PDisplay, pixmap: GLXPixmap){.cdecl, dynlib: dllname, importc: "glXDestroyGLXPixmap".} -proc glXQueryExtension*(dpy: PDisplay, errorb, event: var int): bool{.cdecl, +proc glXQueryExtension*(dpy: PDisplay, errorb, event: var int): bool{.cdecl, dynlib: dllname, importc: "glXQueryExtension".} -proc glXQueryVersion*(dpy: PDisplay, maj, min: var int): bool{.cdecl, +proc glXQueryVersion*(dpy: PDisplay, maj, min: var int): bool{.cdecl, dynlib: dllname, importc: "glXQueryVersion".} -proc glXIsDirect*(dpy: PDisplay, ctx: GLXContext): bool{.cdecl, dynlib: dllname, +proc glXIsDirect*(dpy: PDisplay, ctx: GLXContext): bool{.cdecl, dynlib: dllname, importc: "glXIsDirect".} -proc glXGetConfig*(dpy: PDisplay, visual: PXVisualInfo, attrib: int, - value: var int): int{.cdecl, dynlib: dllname, +proc glXGetConfig*(dpy: PDisplay, visual: PXVisualInfo, attrib: int, + value: var int): int{.cdecl, dynlib: dllname, importc: "glXGetConfig".} -proc glXGetCurrentContext*(): GLXContext{.cdecl, dynlib: dllname, +proc glXGetCurrentContext*(): GLXContext{.cdecl, dynlib: dllname, importc: "glXGetCurrentContext".} -proc glXGetCurrentDrawable*(): GLXDrawable{.cdecl, dynlib: dllname, +proc glXGetCurrentDrawable*(): GLXDrawable{.cdecl, dynlib: dllname, importc: "glXGetCurrentDrawable".} proc glXWaitGL*(){.cdecl, dynlib: dllname, importc: "glXWaitGL".} proc glXWaitX*(){.cdecl, dynlib: dllname, importc: "glXWaitX".} -proc glXUseXFont*(font: XFont, first, count, list: int){.cdecl, dynlib: dllname, +proc glXUseXFont*(font: XFont, first, count, list: int){.cdecl, dynlib: dllname, importc: "glXUseXFont".} # GLX 1.1 and later -proc glXQueryExtensionsString*(dpy: PDisplay, screen: int): cstring{.cdecl, +proc glXQueryExtensionsString*(dpy: PDisplay, screen: int): cstring{.cdecl, dynlib: dllname, importc: "glXQueryExtensionsString".} -proc glXQueryServerString*(dpy: PDisplay, screen, name: int): cstring{.cdecl, +proc glXQueryServerString*(dpy: PDisplay, screen, name: int): cstring{.cdecl, dynlib: dllname, importc: "glXQueryServerString".} -proc glXGetClientString*(dpy: PDisplay, name: int): cstring{.cdecl, +proc glXGetClientString*(dpy: PDisplay, name: int): cstring{.cdecl, dynlib: dllname, importc: "glXGetClientString".} # Mesa GLX Extensions -proc glXCreateGLXPixmapMESA*(dpy: PDisplay, visual: PXVisualInfo, +proc glXCreateGLXPixmapMESA*(dpy: PDisplay, visual: PXVisualInfo, pixmap: XPixmap, cmap: XColormap): GLXPixmap{. cdecl, dynlib: dllname, importc: "glXCreateGLXPixmapMESA".} -proc glXReleaseBufferMESA*(dpy: PDisplay, d: GLXDrawable): bool{.cdecl, +proc glXReleaseBufferMESA*(dpy: PDisplay, d: GLXDrawable): bool{.cdecl, dynlib: dllname, importc: "glXReleaseBufferMESA".} -proc glXCopySubBufferMESA*(dpy: PDisplay, drawbale: GLXDrawable, - x, y, width, height: int){.cdecl, dynlib: dllname, +proc glXCopySubBufferMESA*(dpy: PDisplay, drawbale: GLXDrawable, + x, y, width, height: int){.cdecl, dynlib: dllname, importc: "glXCopySubBufferMESA".} -proc glXGetVideoSyncSGI*(counter: var int32): int{.cdecl, dynlib: dllname, +proc glXGetVideoSyncSGI*(counter: var int32): int{.cdecl, dynlib: dllname, importc: "glXGetVideoSyncSGI".} proc glXWaitVideoSyncSGI*(divisor, remainder: int, count: var int32): int{. cdecl, dynlib: dllname, importc: "glXWaitVideoSyncSGI".} diff --git a/tests/manyloc/keineschweine/lib/idgen.nim b/tests/manyloc/keineschweine/lib/idgen.nim index 8124ba9bd..1ed196d88 100644 --- a/tests/manyloc/keineschweine/lib/idgen.nim +++ b/tests/manyloc/keineschweine/lib/idgen.nim @@ -5,7 +5,7 @@ type freeIDs: seq[T] EOutOfIDs* = object of EInvalidKey -#proc free[T](idg: PIDgen[T]) = +#proc free[T](idg: PIDgen[T]) = # result.freeIDs = nil proc newIDGen*[T: Ordinal](): PIDGen[T] = new(result)#, free) diff --git a/tests/manyloc/keineschweine/lib/input_helpers.nim b/tests/manyloc/keineschweine/lib/input_helpers.nim index 120576dfb..1953cb58c 100644 --- a/tests/manyloc/keineschweine/lib/input_helpers.nim +++ b/tests/manyloc/keineschweine/lib/input_helpers.nim @@ -2,7 +2,7 @@ import sfml, tables, hashes type TKeyEventKind* = enum down, up - TInputFinishedProc* = proc() + TInputFinishedProc* = proc() TKeyCallback = proc() PKeyClient* = ref object onKeyDown: TTable[int32, TKeyCallback] @@ -18,7 +18,7 @@ var activeClient: PKeyClient = nil activeInput: PTextInput = nil -proc setActive*(client: PKeyClient) = +proc setActive*(client: PKeyClient) = activeClient = client echo("** set active client ", client.name) proc newKeyClient*(name: string = "unnamed", setactive = false): PKeyClient = @@ -43,28 +43,28 @@ proc addKeyEvent*(key: TKeyCode, ev: TKeyEventKind) {.inline.} = if activeClient.isNil: return let k = key.int32 case ev - of down: + of down: keyState[k] = true if activeClient.onKeyDown.hasKey(k): activeClient.onKeyDown[k]() - else: + else: keyState[k] = false if activeClient.onKeyUp.hasKey(k): activeClient.onKeyUp[k]() proc addButtonEvent*(btn: TMouseButton, ev: TKeyEventKind) {.inline.} = - if activeClient.isNil: return + if activeClient.isNil: return let b = -btn.int32 case ev - of down: - keyState[b] = true + of down: + keyState[b] = true if activeClient.onKeyDown.hasKey(b): activeClient.onKeyDown[b]() - else: + else: keyState[b] = false if activeClient.onKeyUp.hasKey(b): activeClient.onKeyUp[b]() proc registerHandler*(client: PKeyClient; key: TKeyCode; - ev: TKeyEventKind; fn: TKeyCallback) = + ev: TKeyEventKind; fn: TKeyCallback) = case ev of down: client.onKeyDown[key.int32] = fn of up: client.onKeyUp[key.int32] = fn @@ -90,7 +90,7 @@ proc recordText*(i: PTextInput; c: cint) = if c > 127 or i.isNil: return if c in 32..126: ##printable if i.cursor == i.text.len: i.text.add(c.int.chr) - else: + else: let rem = i.text.substr(i.cursor) i.text.setLen(i.cursor) i.text.add(chr(c.int)) @@ -104,7 +104,7 @@ proc recordText*(i: PTextInput; c: cint) = i.text.add(rem) elif c == 10 or c == 13:## \n, \r enter if not i.onEnter.isNil: i.onEnter() -proc recordText*(i: PTextInput; e: TTextEvent) {.inline.} = +proc recordText*(i: PTextInput; e: TTextEvent) {.inline.} = recordText(i, e.unicode) proc setMousePos*(x, y: cint) {.inline.} = @@ -135,4 +135,4 @@ iterator pollEvents*(window: PRenderWindow): PEvent = of EvtTextEntered: recordText(activeInput, event.text) of EvtMouseMoved: setMousePos(event.mouseMove.x, event.mouseMove.y) else: nil - yield(addr event) \ No newline at end of file + yield(addr event) diff --git a/tests/manyloc/keineschweine/lib/map_filter.nim b/tests/manyloc/keineschweine/lib/map_filter.nim index 5776c9225..42ef74ceb 100644 --- a/tests/manyloc/keineschweine/lib/map_filter.nim +++ b/tests/manyloc/keineschweine/lib/map_filter.nim @@ -19,7 +19,7 @@ template unless*(condition: expr; body: stmt): stmt {.dirty.} = when isMainModule: proc dumpSeq[T](x: seq[T]) = - for index, item in x.pairs: + for index, item in x.pairs: echo index, " ", item echo "-------" @@ -28,13 +28,13 @@ when isMainModule: dumpSeq res from strutils import toHex - var foocakes = t.map(proc(z: int): string = + var foocakes = t.map(proc(z: int): string = result = toHex((z * 23).BiggestInt, 4)) dumpSeq foocakes t.mapInPlace(proc(z: int): int = result = z * 30) dumpSeq t - + var someSeq = @[9,8,7,6,5,4,3,2,1] ## numbers < 6 or even filterIt2 someSeq, it < 6 or (it and 1) == 0: echo(it) diff --git a/tests/manyloc/keineschweine/lib/math_helpers.nim b/tests/manyloc/keineschweine/lib/math_helpers.nim index 8af56d1ed..5427dd80e 100644 --- a/tests/manyloc/keineschweine/lib/math_helpers.nim +++ b/tests/manyloc/keineschweine/lib/math_helpers.nim @@ -6,5 +6,5 @@ proc radians*(deg: float): float = return deg * PI / 180.0 ## V not math, sue me -proc ff*(f: float, precision = 2): string {.inline.} = +proc ff*(f: float, precision = 2): string {.inline.} = return formatFloat(f, ffDecimal, precision) diff --git a/tests/manyloc/keineschweine/lib/sfml_stuff.nim b/tests/manyloc/keineschweine/lib/sfml_stuff.nim index a5ac91195..5ff80b295 100644 --- a/tests/manyloc/keineschweine/lib/sfml_stuff.nim +++ b/tests/manyloc/keineschweine/lib/sfml_stuff.nim @@ -1,4 +1,4 @@ -import +import math, strutils, sfml, input_helpers when not defined(NoChipmunk): diff --git a/tests/manyloc/keineschweine/lib/sg_assets.nim b/tests/manyloc/keineschweine/lib/sg_assets.nim index c5a39550a..3b9781649 100644 --- a/tests/manyloc/keineschweine/lib/sg_assets.nim +++ b/tests/manyloc/keineschweine/lib/sg_assets.nim @@ -1,5 +1,5 @@ import - re, json, strutils, tables, math, os, math_helpers, + re, json, strutils, tables, math, os, math_helpers, sg_packets, md5, zlib_helpers when defined(NoSFML): @@ -56,9 +56,9 @@ type energyCost*: float useSound*: PSoundRecord case kind*: TItemKind - of Projectile: + of Projectile: bullet*: PBulletRecord - else: + else: nil PBulletRecord* = ref TBulletRecord TBulletRecord* = object @@ -84,7 +84,7 @@ type health*: int TExplosionRecord* = object anim*: PAnimationRecord - sound*: PSoundRecord + sound*: PSoundRecord PAnimationRecord* = ref TAnimationRecord TAnimationRecord* = object spriteSheet*: PSpriteSheet @@ -96,9 +96,9 @@ type when defined(NoSFML): contents*: TChecksumFile else: - soundBuf*: PSoundBuffer + soundBuf*: PSoundBuffer PSpriteSheet* = ref TSpriteSheet - TSpriteSheet* = object + TSpriteSheet* = object file*: string framew*,frameh*: int rows*, cols*: int @@ -112,7 +112,7 @@ type const TAU* = PI * 2.0 MomentMult* = 0.62 ## global moment of inertia multiplier -var +var cfg: PZoneSettings SpriteSheets* = initTable[string, PSpriteSheet](64) SoundCache * = initTable[string, PSoundRecord](64) @@ -151,7 +151,7 @@ proc importSound*(data: PJsonNode; errors: var seq[string]; fieldName: string = ## this is the only pipe between lobby and main.nim proc getActiveState*(): TGameState = result = activeState -proc transition*() = +proc transition*() = assert activeState == Lobby, "Transition() called from a state other than lobby!" activeState = Transitioning proc doneWithSaidTransition*() = @@ -179,7 +179,7 @@ proc free*(obj: PSoundRecord) = echo "Free'd ", obj.file proc loadAllAssets*() = - var + var loaded = 0 failed = 0 for name, ss in SpriteSheets.pairs(): @@ -205,7 +205,7 @@ iterator playableVehicles*(): PVehicleRecord = yield v template allAssets*(body: stmt) {.dirty.}= - block: + block: var assetType = FGraphics for file, asset in pairs(SpriteSheets): body @@ -230,7 +230,7 @@ cacheImpl newSprite, SpriteSheets, PSpriteSheet: if filename =~ re"\S+_(\d+)x(\d+)\.\S\S\S": result.framew = strutils.parseInt(matches[0]) result.frameh = strutils.parseInt(matches[1]) - checkFile("data/gfx"/result.file) + checkFile("data/gfx"/result.file) else: errors.add "Bad file: "&filename&" must be in format name_WxH.png" return @@ -260,7 +260,7 @@ when defined(NoSFML): result = true else: proc load*(ss: PSpriteSheet): bool = - if not ss.sprite.isNil: + if not ss.sprite.isNil: return var image = sfml.newImage("data/gfx/"/ss.file) if image == nil: @@ -335,7 +335,7 @@ proc loadSettings*(rawJson: string, errors: var seq[string]): bool = except EJsonParsingError: errors.add("JSON parsing error: "& getCurrentExceptionMsg()) return - except: + except: errors.add("Unknown exception: "& getCurrentExceptionMsg()) return if not validateSettings(settings, errors): @@ -354,7 +354,7 @@ proc loadSettings*(rawJson: string, errors: var seq[string]): bool = nameToItemID = initTable[string, int](32) nameToObjID = initTable[string, int](32) nameToBulletID = initTable[string, int](32) - var + var vID = 0'i16 bID = 0'i16 for vehicle in settings["vehicles"].items: @@ -382,7 +382,7 @@ proc loadSettings*(rawJson: string, errors: var seq[string]): bool = errors.add("Projectile #$1 has no bullet!"% $vID) elif itm.bullet.id == -1: ## this item has an anonymous bullet, fix the ID and name - itm.bullet.id = bID + itm.bullet.id = bID itm.bullet.name = itm.name cfg.bullets.add itm.bullet nameToBulletID[itm.bullet.name] = itm.bullet.id @@ -448,7 +448,7 @@ proc importLevel(data: PJsonNode; errors: var seq[string]): PLevelSettings = new(result) result.size = vec2i(5000, 5000) result.starfield = @[] - + checkKey(data, "level") var level = data["level"] if level.hasKey("size") and level["size"].kind == JArray and level["size"].len == 2: @@ -460,7 +460,7 @@ proc importLevel(data: PJsonNode; errors: var seq[string]): PLevelSettings = proc importPhys(data: PJsonNode): TPhysicsRecord = result.radius = 20.0 result.mass = 10.0 - + if data.hasKey("physics") and data["physics"].kind == JObject: let phys = data["physics"] phys.getField("radius", result.radius) @@ -473,11 +473,11 @@ proc importHandling(data: PJsonNode): THandlingRecord = result.reverse = 30.0 result.strafe = 30.0 result.rotation = 2200.0 - + checkKey(data, "handling") if data["handling"].kind != JObject: return - + let hand = data["handling"] hand.getField("thrust", result.thrust) hand.getField("top_speed", result.topSpeed) @@ -489,19 +489,19 @@ proc importAnim(data: PJsonNode, errors: var seq[string]): PAnimationRecord = result.angle = 0.0 result.delay = 1000.0 result.spriteSheet = nil - + if data.hasKey("anim"): let anim = data["anim"] if anim.kind == JObject: if anim.hasKey("file"): result.spriteSheet = newSprite(anim["file"].str, errors) - + anim.getField "angle", result.angle anim.getField "delay", result.delay elif data["anim"].kind == JString: result.spriteSheet = newSprite(anim.str, errors) - - result.angle = radians(result.angle) ## comes in as degrees + + result.angle = radians(result.angle) ## comes in as degrees result.delay /= 1000 ## delay comes in as milliseconds proc importSoul(data: PJsonNode): TSoulRecord = result.energy = 10000 @@ -525,8 +525,8 @@ proc importSound*(data: PJsonNode; errors: var seq[string]; fieldName: string = proc importVeh(data: PJsonNode; errors: var seq[string]): PVehicleRecord = new(result) result.playable = false - if data.kind != JArray or data.len != 2 or - (data.kind == JArray and + if data.kind != JArray or data.len != 2 or + (data.kind == JArray and (data[0].kind != JString or data[1].kind != JObject)): result.name = "(broken)" errors.add "Vehicle record is malformed" @@ -556,13 +556,13 @@ proc importItem(data: PJsonNode; errors: var seq[string]): PItemRecord = result.name = data[0].str result.anim = importAnim(data[2], errors) result.physics = importPhys(data[2]) - - result.cooldown = 100.0 + + result.cooldown = 100.0 data[2].getField("cooldown", result.cooldown) - result.cooldown /= 1000.0 ##cooldown is stored in ms - + result.cooldown /= 1000.0 ##cooldown is stored in ms + result.useSound = importSound(data[2], errors, "useSound") - + case data[1].str.toLower of "projectile": result.kind = Projectile @@ -570,7 +570,7 @@ proc importItem(data: PJsonNode; errors: var seq[string]): PItemRecord = result.bullet = fetchBullet(data[2]["bullet"].str) elif data[2]["bullet"].kind == JInt: result.bullet = cfg.bullets[data[2]["bullet"].num.int] - elif data[2]["bullet"].kind == JObject: + elif data[2]["bullet"].kind == JObject: result.bullet = importBullet(data[2]["bullet"], errors) else: errors.add "UNKNOWN BULLET TYPE for item "& result.name @@ -584,20 +584,20 @@ proc importItem(data: PJsonNode; errors: var seq[string]): PItemRecord = proc importBullet(data: PJsonNode; errors: var seq[string]): PBulletRecord = new(result) result.id = -1 - + var bdata: PJsonNode if data.kind == JArray: result.name = data[0].str bdata = data[1] elif data.kind == JObject: bdata = data - else: + else: errors.add "Malformed bullet record" return - + result.anim = importAnim(bdata, errors) result.physics = importPhys(bdata) - + result.lifetime = 2000.0 result.inheritVelocity = 1000.0 result.baseVelocity = 30.0 diff --git a/tests/manyloc/keineschweine/lib/sg_gui.nim b/tests/manyloc/keineschweine/lib/sg_gui.nim index 6741fe55e..aae51baec 100644 --- a/tests/manyloc/keineschweine/lib/sg_gui.nim +++ b/tests/manyloc/keineschweine/lib/sg_gui.nim @@ -1,5 +1,5 @@ import - sfml, sfml_colors, + sfml, sfml_colors, input_helpers, sg_packets from strutils import countlines {.deadCodeElim: on.} @@ -63,7 +63,7 @@ proc click*(b: PButton; p: TVector2f) proc setPosition*(b: PButton; p: TVector2f) proc setString*(b: PButton; s: string) {.inline.} -proc newButton*(container: PGuiContainer; text: string; position: TVector2f; +proc newButton*(container: PGuiContainer; text: string; position: TVector2f; onClick: TButtonClicked; startEnabled: bool = true): PButton {.discardable.} proc init(b: PButton; text: string; position: TVector2f; onClick: TButtonClicked) proc setEnabled*(b: PButton; enabled: bool) @@ -91,7 +91,7 @@ proc newGuiContainer*(): PGuiContainer = proc newGuiContainer*(pos: TVector2f): PGuiContainer = result = newGuiContainer() result.setPosition pos -proc free*(container: PGuiContainer) = +proc free*(container: PGuiContainer) = container.widgets = nil container.buttons = nil proc add*(container: PGuiContainer; widget: PGuiObject) = @@ -128,9 +128,9 @@ proc newButton*(container: PGuiContainer; text: string; position: TVector2f; onClick: TButtonClicked; startEnabled: bool = true): PButton = new(result, free) - init(result, - text, - if not container.isNil: position + container.position else: position, + init(result, + text, + if not container.isNil: position + container.position else: position, onClick) container.add result if not startEnabled: disable(result) @@ -168,13 +168,13 @@ proc setPosition*(b: PButton, p: TVector2f) = b.bounds = b.text.getGlobalBounds() proc setString*(b: PButton; s: string) = b.text.setString(s) -proc click*(b: PButton, p: TVector2f) = - if b.enabled and (addr b.bounds).contains(p.x, p.y): +proc click*(b: PButton, p: TVector2f) = + if b.enabled and (addr b.bounds).contains(p.x, p.y): b.onClick(b) proc free(obj: PTextEntry) = free(PButton(obj)) -proc newTextEntry*(container: PGuiContainer; text: string; +proc newTextEntry*(container: PGuiContainer; text: string; position: TVector2F; onEnter: TInputFinishedProc = nil): PTextEntry = new(result, free) init(PButton(result), text, position + container.position, proc(b: PButton) = @@ -210,7 +210,7 @@ proc add*(m: PMessageArea, text: string): PText = pos.y -= 16.0 proc draw*(window: PRenderWindow; m: PMessageArea) = - let nmsgs = len(m.messages) + let nmsgs = len(m.messages) if nmsgs == 0: return for i in countdown(nmsgs - 1, max(nmsgs - 30, 0)): window.draw(m.messages[i]) @@ -224,11 +224,11 @@ proc newMessageArea*(container: PGuiContainer; position: TVector2f): PMessageAre result.scrollBack = 0 result.direction = -1 ## to push old messages up container.add(result) - + proc add*(m: PMessageArea, msg: ScChat) = const prependName = {CPub, CPriv} var mmm: TMessage - if msg.kind in prependName: + if msg.kind in prependName: mmm.text = "<" mmm.text.add msg.fromPlayer mmm.text.add "> " @@ -239,9 +239,9 @@ proc add*(m: PMessageArea, msg: ScChat) = of CPub: mmm.color = RoyalBlue of CPriv, CSystem: mmm.color = Green of CError: mmm.color = Red - + mmm.lines = countLines(mmm.text)+1 - + m.messages.add mmm update m proc add*(m: PMessageArea, msg: string) {.inline.} = @@ -249,7 +249,7 @@ proc add*(m: PMessageArea, msg: string) {.inline.} = add(m, chat) proc proctor*(m: PText; msg: ptr TMessage; pos: ptr TVector2f) = - m.setString msg.text + m.setString msg.text m.setColor msg.color m.setPosition pos[] proc update*(m: PMessageArea) = @@ -263,7 +263,7 @@ proc update*(m: PMessageArea) = for i in m.sizeVisible.. < m.texts.len: m.texts.pop().destroy() let nmsgs = m.messages.len() - if m.sizeVisible == 0 or nmsgs == 0: + if m.sizeVisible == 0 or nmsgs == 0: echo "no messages? ", m.sizeVisible, ", ", nmsgs return var pos = vec2f(m.pos.x, m.pos.y) @@ -271,7 +271,7 @@ proc update*(m: PMessageArea) = ##echo nmsgs - i - 1 - m.scrollBack let msg = addr m.messages[nmsgs - i - 1 - m.scrollBack] proctor(m.texts[i], msg, addr pos) - pos.y += (16 * m.direction * msg.lines).cfloat + pos.y += (16 * m.direction * msg.lines).cfloat proc draw*(window: PRenderWindow; m: PMessageArea) = let nmsgs = len(m.texts) diff --git a/tests/manyloc/keineschweine/lib/sg_packets.nim b/tests/manyloc/keineschweine/lib/sg_packets.nim index 601054b47..d84bf72fc 100644 --- a/tests/manyloc/keineschweine/lib/sg_packets.nim +++ b/tests/manyloc/keineschweine/lib/sg_packets.nim @@ -33,7 +33,7 @@ defPacket(Poing, tuple[id: int32, time: float32]) type ChatType* = enum CPub = 0'i8, CPriv, CSystem, CError forwardPacketT(ChatType, int8) -idPacket(Chat, 'C', +idPacket(Chat, 'C', tuple[kind: ChatType = CPub; fromPlayer: string = ""; text: string = ""], tuple[target: string = ""; text: string = ""]) @@ -65,8 +65,8 @@ defPacket(ScSpawn, tuple[ type TAssetType* = enum - FDummy, - FZoneCfg, FGraphics, FSound + FDummy, + FZoneCfg, FGraphics, FSound forwardPacketT(TAssetType, int8) forwardPacket(MD5Digest, array[0..15, int8]) @@ -93,7 +93,7 @@ let HVerifyClient* = 'v' defPacket(SdVerifyClient, tuple[session: ScLogin]) when isMainModule: - + var buf = newBuffer(100) var m = toMd5("hello there") echo(repr(m)) @@ -101,7 +101,7 @@ when isMainModule: echo(repr(buf.data)) echo(len(buf.data)) - + buf.reset() var x = buf.readMD5Digest() diff --git a/tests/manyloc/keineschweine/lib/vehicles.nim b/tests/manyloc/keineschweine/lib/vehicles.nim index 4b11856c6..94ebf9f57 100644 --- a/tests/manyloc/keineschweine/lib/vehicles.nim +++ b/tests/manyloc/keineschweine/lib/vehicles.nim @@ -1,5 +1,5 @@ import - sfml, chipmunk, + sfml, chipmunk, sg_assets, sfml_stuff, keineschweine diff --git a/tests/manyloc/keineschweine/lib/wingl.nim b/tests/manyloc/keineschweine/lib/wingl.nim index 7ed78f970..5bd199911 100644 --- a/tests/manyloc/keineschweine/lib/wingl.nim +++ b/tests/manyloc/keineschweine/lib/wingl.nim @@ -1,9 +1,9 @@ -import +import gl, windows -proc wglGetExtensionsStringARB*(hdc: HDC): cstring{.dynlib: dllname, +proc wglGetExtensionsStringARB*(hdc: HDC): cstring{.dynlib: dllname, importc: "wglGetExtensionsStringARB".} -const +const WGL_FRONT_COLOR_BUFFER_BIT_ARB* = 0x00000001 WGL_BACK_COLOR_BUFFER_BIT_ARB* = 0x00000002 WGL_DEPTH_BUFFER_BIT_ARB* = 0x00000004 @@ -13,21 +13,21 @@ proc WinChoosePixelFormat*(DC: HDC, p2: PPixelFormatDescriptor): int{. dynlib: "gdi32", importc: "ChoosePixelFormat".} proc wglCreateBufferRegionARB*(hDC: HDC, iLayerPlane: TGLint, uType: TGLuint): THandle{. dynlib: dllname, importc: "wglCreateBufferRegionARB".} -proc wglDeleteBufferRegionARB*(hRegion: THandle){.dynlib: dllname, +proc wglDeleteBufferRegionARB*(hRegion: THandle){.dynlib: dllname, importc: "wglDeleteBufferRegionARB".} -proc wglSaveBufferRegionARB*(hRegion: THandle, x: TGLint, y: TGLint, +proc wglSaveBufferRegionARB*(hRegion: THandle, x: TGLint, y: TGLint, width: TGLint, height: TGLint): BOOL{. dynlib: dllname, importc: "wglSaveBufferRegionARB".} -proc wglRestoreBufferRegionARB*(hRegion: THandle, x: TGLint, y: TGLint, - width: TGLint, height: TGLint, xSrc: TGLint, - ySrc: TGLint): BOOL{.dynlib: dllname, +proc wglRestoreBufferRegionARB*(hRegion: THandle, x: TGLint, y: TGLint, + width: TGLint, height: TGLint, xSrc: TGLint, + ySrc: TGLint): BOOL{.dynlib: dllname, importc: "wglRestoreBufferRegionARB".} -proc wglAllocateMemoryNV*(size: TGLsizei, readFrequency: TGLfloat, +proc wglAllocateMemoryNV*(size: TGLsizei, readFrequency: TGLfloat, writeFrequency: TGLfloat, priority: TGLfloat): PGLvoid{. dynlib: dllname, importc: "wglAllocateMemoryNV".} -proc wglFreeMemoryNV*(pointer: PGLvoid){.dynlib: dllname, +proc wglFreeMemoryNV*(pointer: PGLvoid){.dynlib: dllname, importc: "wglFreeMemoryNV".} -const +const WGL_IMAGE_BUFFER_MIN_ACCESS_I3D* = 0x00000001 WGL_IMAGE_BUFFER_LOCK_I3D* = 0x00000002 @@ -35,30 +35,30 @@ proc wglCreateImageBufferI3D*(hDC: HDC, dwSize: DWORD, uFlags: UINT): PGLvoid{. dynlib: dllname, importc: "wglCreateImageBufferI3D".} proc wglDestroyImageBufferI3D*(hDC: HDC, pAddress: PGLvoid): BOOL{. dynlib: dllname, importc: "wglDestroyImageBufferI3D".} -proc wglAssociateImageBufferEventsI3D*(hdc: HDC, pEvent: PHandle, - pAddress: PGLvoid, pSize: PDWORD, - count: UINT): BOOL{.dynlib: dllname, +proc wglAssociateImageBufferEventsI3D*(hdc: HDC, pEvent: PHandle, + pAddress: PGLvoid, pSize: PDWORD, + count: UINT): BOOL{.dynlib: dllname, importc: "wglAssociateImageBufferEventsI3D".} proc wglReleaseImageBufferEventsI3D*(hdc: HDC, pAddress: PGLvoid, count: UINT): BOOL{. dynlib: dllname, importc: "wglReleaseImageBufferEventsI3D".} -proc wglEnableFrameLockI3D*(): BOOL{.dynlib: dllname, +proc wglEnableFrameLockI3D*(): BOOL{.dynlib: dllname, importc: "wglEnableFrameLockI3D".} -proc wglDisableFrameLockI3D*(): BOOL{.dynlib: dllname, +proc wglDisableFrameLockI3D*(): BOOL{.dynlib: dllname, importc: "wglDisableFrameLockI3D".} -proc wglIsEnabledFrameLockI3D*(pFlag: PBOOL): BOOL{.dynlib: dllname, +proc wglIsEnabledFrameLockI3D*(pFlag: PBOOL): BOOL{.dynlib: dllname, importc: "wglIsEnabledFrameLockI3D".} -proc wglQueryFrameLockMasterI3D*(pFlag: PBOOL): BOOL{.dynlib: dllname, +proc wglQueryFrameLockMasterI3D*(pFlag: PBOOL): BOOL{.dynlib: dllname, importc: "wglQueryFrameLockMasterI3D".} -proc wglGetFrameUsageI3D*(pUsage: PGLfloat): BOOL{.dynlib: dllname, +proc wglGetFrameUsageI3D*(pUsage: PGLfloat): BOOL{.dynlib: dllname, importc: "wglGetFrameUsageI3D".} -proc wglBeginFrameTrackingI3D*(): BOOL{.dynlib: dllname, +proc wglBeginFrameTrackingI3D*(): BOOL{.dynlib: dllname, importc: "wglBeginFrameTrackingI3D".} -proc wglEndFrameTrackingI3D*(): BOOL{.dynlib: dllname, +proc wglEndFrameTrackingI3D*(): BOOL{.dynlib: dllname, importc: "wglEndFrameTrackingI3D".} -proc wglQueryFrameTrackingI3D*(pFrameCount: PDWORD, pMissedFrames: PDWORD, +proc wglQueryFrameTrackingI3D*(pFrameCount: PDWORD, pMissedFrames: PDWORD, pLastMissedUsage: PGLfloat): BOOL{. dynlib: dllname, importc: "wglQueryFrameTrackingI3D".} -const +const WGL_NUMBER_PIXEL_FORMATS_ARB* = 0x00002000 WGL_DRAW_TO_WINDOW_ARB* = 0x00002001 WGL_DRAW_TO_BITMAP_ARB* = 0x00002002 @@ -109,27 +109,27 @@ const WGL_TYPE_RGBA_ARB* = 0x0000202B WGL_TYPE_COLORINDEX_ARB* = 0x0000202C -proc wglGetPixelFormatAttribivARB*(hdc: HDC, iPixelFormat: TGLint, - iLayerPlane: TGLint, nAttributes: TGLuint, +proc wglGetPixelFormatAttribivARB*(hdc: HDC, iPixelFormat: TGLint, + iLayerPlane: TGLint, nAttributes: TGLuint, piAttributes: PGLint, piValues: PGLint): BOOL{. dynlib: dllname, importc: "wglGetPixelFormatAttribivARB".} -proc wglGetPixelFormatAttribfvARB*(hdc: HDC, iPixelFormat: TGLint, - iLayerPlane: TGLint, nAttributes: TGLuint, +proc wglGetPixelFormatAttribfvARB*(hdc: HDC, iPixelFormat: TGLint, + iLayerPlane: TGLint, nAttributes: TGLuint, piAttributes: PGLint, pfValues: PGLfloat): BOOL{. dynlib: dllname, importc: "wglGetPixelFormatAttribfvARB".} -proc wglChoosePixelFormatARB*(hdc: HDC, piAttribIList: PGLint, - pfAttribFList: PGLfloat, nMaxFormats: TGLuint, +proc wglChoosePixelFormatARB*(hdc: HDC, piAttribIList: PGLint, + pfAttribFList: PGLfloat, nMaxFormats: TGLuint, piFormats: PGLint, nNumFormats: PGLuint): BOOL{. dynlib: dllname, importc: "wglChoosePixelFormatARB".} -const +const WGL_ERROR_INVALID_PIXEL_TYPE_ARB* = 0x00002043 WGL_ERROR_INCOMPATIBLE_DEVICE_CONTEXTS_ARB* = 0x00002054 proc wglMakeContextCurrentARB*(hDrawDC: HDC, hReadDC: HDC, hglrc: HGLRC): BOOL{. dynlib: dllname, importc: "wglMakeContextCurrentARB".} -proc wglGetCurrentReadDCARB*(): HDC{.dynlib: dllname, +proc wglGetCurrentReadDCARB*(): HDC{.dynlib: dllname, importc: "wglGetCurrentReadDCARB".} -const +const WGL_DRAW_TO_PBUFFER_ARB* = 0x0000202D # WGL_DRAW_TO_PBUFFER_ARB { already defined } WGL_MAX_PBUFFER_PIXELS_ARB* = 0x0000202E WGL_MAX_PBUFFER_WIDTH_ARB* = 0x0000202F @@ -139,22 +139,22 @@ const WGL_PBUFFER_HEIGHT_ARB* = 0x00002035 WGL_PBUFFER_LOST_ARB* = 0x00002036 -proc wglCreatePbufferARB*(hDC: HDC, iPixelFormat: TGLint, iWidth: TGLint, +proc wglCreatePbufferARB*(hDC: HDC, iPixelFormat: TGLint, iWidth: TGLint, iHeight: TGLint, piAttribList: PGLint): THandle{. dynlib: dllname, importc: "wglCreatePbufferARB".} -proc wglGetPbufferDCARB*(hPbuffer: THandle): HDC{.dynlib: dllname, +proc wglGetPbufferDCARB*(hPbuffer: THandle): HDC{.dynlib: dllname, importc: "wglGetPbufferDCARB".} proc wglReleasePbufferDCARB*(hPbuffer: THandle, hDC: HDC): TGLint{. dynlib: dllname, importc: "wglReleasePbufferDCARB".} -proc wglDestroyPbufferARB*(hPbuffer: THandle): BOOL{.dynlib: dllname, +proc wglDestroyPbufferARB*(hPbuffer: THandle): BOOL{.dynlib: dllname, importc: "wglDestroyPbufferARB".} proc wglQueryPbufferARB*(hPbuffer: THandle, iAttribute: TGLint, piValue: PGLint): BOOL{. dynlib: dllname, importc: "wglQueryPbufferARB".} -proc wglSwapIntervalEXT*(interval: TGLint): BOOL{.dynlib: dllname, +proc wglSwapIntervalEXT*(interval: TGLint): BOOL{.dynlib: dllname, importc: "wglSwapIntervalEXT".} -proc wglGetSwapIntervalEXT*(): TGLint{.dynlib: dllname, +proc wglGetSwapIntervalEXT*(): TGLint{.dynlib: dllname, importc: "wglGetSwapIntervalEXT".} -const +const WGL_BIND_TO_TEXTURE_RGB_ARB* = 0x00002070 WGL_BIND_TO_TEXTURE_RGBA_ARB* = 0x00002071 WGL_TEXTURE_FORMAT_ARB* = 0x00002072 @@ -195,13 +195,13 @@ proc wglReleaseTexImageARB*(hPbuffer: THandle, iBuffer: TGLint): BOOL{. dynlib: dllname, importc: "wglReleaseTexImageARB".} proc wglSetPbufferAttribARB*(hPbuffer: THandle, piAttribList: PGLint): BOOL{. dynlib: dllname, importc: "wglSetPbufferAttribARB".} -proc wglGetExtensionsStringEXT*(): cstring{.dynlib: dllname, +proc wglGetExtensionsStringEXT*(): cstring{.dynlib: dllname, importc: "wglGetExtensionsStringEXT".} proc wglMakeContextCurrentEXT*(hDrawDC: HDC, hReadDC: HDC, hglrc: HGLRC): BOOL{. dynlib: dllname, importc: "wglMakeContextCurrentEXT".} -proc wglGetCurrentReadDCEXT*(): HDC{.dynlib: dllname, +proc wglGetCurrentReadDCEXT*(): HDC{.dynlib: dllname, importc: "wglGetCurrentReadDCEXT".} -const +const WGL_DRAW_TO_PBUFFER_EXT* = 0x0000202D WGL_MAX_PBUFFER_PIXELS_EXT* = 0x0000202E WGL_MAX_PBUFFER_WIDTH_EXT* = 0x0000202F @@ -212,18 +212,18 @@ const WGL_PBUFFER_WIDTH_EXT* = 0x00002034 WGL_PBUFFER_HEIGHT_EXT* = 0x00002035 -proc wglCreatePbufferEXT*(hDC: HDC, iPixelFormat: TGLint, iWidth: TGLint, +proc wglCreatePbufferEXT*(hDC: HDC, iPixelFormat: TGLint, iWidth: TGLint, iHeight: TGLint, piAttribList: PGLint): THandle{. dynlib: dllname, importc: "wglCreatePbufferEXT".} -proc wglGetPbufferDCEXT*(hPbuffer: THandle): HDC{.dynlib: dllname, +proc wglGetPbufferDCEXT*(hPbuffer: THandle): HDC{.dynlib: dllname, importc: "wglGetPbufferDCEXT".} proc wglReleasePbufferDCEXT*(hPbuffer: THandle, hDC: HDC): TGLint{. dynlib: dllname, importc: "wglReleasePbufferDCEXT".} -proc wglDestroyPbufferEXT*(hPbuffer: THandle): BOOL{.dynlib: dllname, +proc wglDestroyPbufferEXT*(hPbuffer: THandle): BOOL{.dynlib: dllname, importc: "wglDestroyPbufferEXT".} proc wglQueryPbufferEXT*(hPbuffer: THandle, iAttribute: TGLint, piValue: PGLint): BOOL{. dynlib: dllname, importc: "wglQueryPbufferEXT".} -const +const WGL_NUMBER_PIXEL_FORMATS_EXT* = 0x00002000 WGL_DRAW_TO_WINDOW_EXT* = 0x00002001 WGL_DRAW_TO_BITMAP_EXT* = 0x00002002 @@ -270,47 +270,47 @@ const WGL_TYPE_RGBA_EXT* = 0x0000202B WGL_TYPE_COLORINDEX_EXT* = 0x0000202C -proc wglGetPixelFormatAttribivEXT*(hdc: HDC, iPixelFormat: TGLint, - iLayerPlane: TGLint, nAttributes: TGLuint, +proc wglGetPixelFormatAttribivEXT*(hdc: HDC, iPixelFormat: TGLint, + iLayerPlane: TGLint, nAttributes: TGLuint, piAttributes: PGLint, piValues: PGLint): BOOL{. dynlib: dllname, importc: "wglGetPixelFormatAttribivEXT".} -proc wglGetPixelFormatAttribfvEXT*(hdc: HDC, iPixelFormat: TGLint, - iLayerPlane: TGLint, nAttributes: TGLuint, +proc wglGetPixelFormatAttribfvEXT*(hdc: HDC, iPixelFormat: TGLint, + iLayerPlane: TGLint, nAttributes: TGLuint, piAttributes: PGLint, pfValues: PGLfloat): BOOL{. dynlib: dllname, importc: "wglGetPixelFormatAttribfvEXT".} -proc wglChoosePixelFormatEXT*(hdc: HDC, piAttribIList: PGLint, - pfAttribFList: PGLfloat, nMaxFormats: TGLuint, +proc wglChoosePixelFormatEXT*(hdc: HDC, piAttribIList: PGLint, + pfAttribFList: PGLfloat, nMaxFormats: TGLuint, piFormats: PGLint, nNumFormats: PGLuint): BOOL{. dynlib: dllname, importc: "wglChoosePixelFormatEXT".} -const +const WGL_DIGITAL_VIDEO_CURSOR_ALPHA_FRAMEBUFFER_I3D* = 0x00002050 WGL_DIGITAL_VIDEO_CURSOR_ALPHA_VALUE_I3D* = 0x00002051 WGL_DIGITAL_VIDEO_CURSOR_INCLUDED_I3D* = 0x00002052 WGL_DIGITAL_VIDEO_GAMMA_CORRECTED_I3D* = 0x00002053 -proc wglGetDigitalVideoParametersI3D*(hDC: HDC, iAttribute: TGLint, - piValue: PGLint): BOOL{.dynlib: dllname, +proc wglGetDigitalVideoParametersI3D*(hDC: HDC, iAttribute: TGLint, + piValue: PGLint): BOOL{.dynlib: dllname, importc: "wglGetDigitalVideoParametersI3D".} -proc wglSetDigitalVideoParametersI3D*(hDC: HDC, iAttribute: TGLint, - piValue: PGLint): BOOL{.dynlib: dllname, +proc wglSetDigitalVideoParametersI3D*(hDC: HDC, iAttribute: TGLint, + piValue: PGLint): BOOL{.dynlib: dllname, importc: "wglSetDigitalVideoParametersI3D".} -const +const WGL_GAMMA_TABLE_SIZE_I3D* = 0x0000204E WGL_GAMMA_EXCLUDE_DESKTOP_I3D* = 0x0000204F -proc wglGetGammaTableParametersI3D*(hDC: HDC, iAttribute: TGLint, - piValue: PGLint): BOOL{.dynlib: dllname, +proc wglGetGammaTableParametersI3D*(hDC: HDC, iAttribute: TGLint, + piValue: PGLint): BOOL{.dynlib: dllname, importc: "wglGetGammaTableParametersI3D".} -proc wglSetGammaTableParametersI3D*(hDC: HDC, iAttribute: TGLint, - piValue: PGLint): BOOL{.dynlib: dllname, +proc wglSetGammaTableParametersI3D*(hDC: HDC, iAttribute: TGLint, + piValue: PGLint): BOOL{.dynlib: dllname, importc: "wglSetGammaTableParametersI3D".} -proc wglGetGammaTableI3D*(hDC: HDC, iEntries: TGLint, puRed: PGLUSHORT, +proc wglGetGammaTableI3D*(hDC: HDC, iEntries: TGLint, puRed: PGLUSHORT, puGreen: PGLUSHORT, puBlue: PGLUSHORT): BOOL{. dynlib: dllname, importc: "wglGetGammaTableI3D".} -proc wglSetGammaTableI3D*(hDC: HDC, iEntries: TGLint, puRed: PGLUSHORT, +proc wglSetGammaTableI3D*(hDC: HDC, iEntries: TGLint, puRed: PGLUSHORT, puGreen: PGLUSHORT, puBlue: PGLUSHORT): BOOL{. dynlib: dllname, importc: "wglSetGammaTableI3D".} -const +const WGL_GENLOCK_SOURCE_MULTIVIEW_I3D* = 0x00002044 WGL_GENLOCK_SOURCE_EXTERNAL_SYNC_I3D* = 0x00002045 WGL_GENLOCK_SOURCE_EXTERNAL_FIELD_I3D* = 0x00002046 @@ -330,21 +330,21 @@ const WGL_TEXTURE_FLOAT_RGB_NV* = 0x000020B7 WGL_TEXTURE_FLOAT_RGBA_NV* = 0x000020B8 -proc wglEnableGenlockI3D*(hDC: HDC): BOOL{.dynlib: dllname, +proc wglEnableGenlockI3D*(hDC: HDC): BOOL{.dynlib: dllname, importc: "wglEnableGenlockI3D".} -proc wglDisableGenlockI3D*(hDC: HDC): BOOL{.dynlib: dllname, +proc wglDisableGenlockI3D*(hDC: HDC): BOOL{.dynlib: dllname, importc: "wglDisableGenlockI3D".} -proc wglIsEnabledGenlockI3D*(hDC: HDC, pFlag: PBOOL): BOOL{.dynlib: dllname, +proc wglIsEnabledGenlockI3D*(hDC: HDC, pFlag: PBOOL): BOOL{.dynlib: dllname, importc: "wglIsEnabledGenlockI3D".} -proc wglGenlockSourceI3D*(hDC: HDC, uSource: TGLuint): BOOL{.dynlib: dllname, +proc wglGenlockSourceI3D*(hDC: HDC, uSource: TGLuint): BOOL{.dynlib: dllname, importc: "wglGenlockSourceI3D".} -proc wglGetGenlockSourceI3D*(hDC: HDC, uSource: PGLUINT): BOOL{.dynlib: dllname, +proc wglGetGenlockSourceI3D*(hDC: HDC, uSource: PGLUINT): BOOL{.dynlib: dllname, importc: "wglGetGenlockSourceI3D".} -proc wglGenlockSourceEdgeI3D*(hDC: HDC, uEdge: TGLuint): BOOL{.dynlib: dllname, +proc wglGenlockSourceEdgeI3D*(hDC: HDC, uEdge: TGLuint): BOOL{.dynlib: dllname, importc: "wglGenlockSourceEdgeI3D".} proc wglGetGenlockSourceEdgeI3D*(hDC: HDC, uEdge: PGLUINT): BOOL{. dynlib: dllname, importc: "wglGetGenlockSourceEdgeI3D".} -proc wglGenlockSampleRateI3D*(hDC: HDC, uRate: TGLuint): BOOL{.dynlib: dllname, +proc wglGenlockSampleRateI3D*(hDC: HDC, uRate: TGLuint): BOOL{.dynlib: dllname, importc: "wglGenlockSampleRateI3D".} proc wglGetGenlockSampleRateI3D*(hDC: HDC, uRate: PGLUINT): BOOL{. dynlib: dllname, importc: "wglGetGenlockSampleRateI3D".} @@ -352,15 +352,15 @@ proc wglGenlockSourceDelayI3D*(hDC: HDC, uDelay: TGLuint): BOOL{. dynlib: dllname, importc: "wglGenlockSourceDelayI3D".} proc wglGetGenlockSourceDelayI3D*(hDC: HDC, uDelay: PGLUINT): BOOL{. dynlib: dllname, importc: "wglGetGenlockSourceDelayI3D".} -proc wglQueryGenlockMaxSourceDelayI3D*(hDC: HDC, uMaxLineDelay: PGLUINT, +proc wglQueryGenlockMaxSourceDelayI3D*(hDC: HDC, uMaxLineDelay: PGLUINT, uMaxPixelDelay: PGLUINT): BOOL{. dynlib: dllname, importc: "wglQueryGenlockMaxSourceDelayI3D".} -const +const WGL_BIND_TO_TEXTURE_RECTANGLE_RGB_NV* = 0x000020A0 WGL_BIND_TO_TEXTURE_RECTANGLE_RGBA_NV* = 0x000020A1 WGL_TEXTURE_RECTANGLE_NV* = 0x000020A2 -const +const WGL_RGBA_FLOAT_MODE_ATI* = 0x00008820 WGL_COLOR_CLEAR_UNCLAMPED_VALUE_ATI* = 0x00008835 WGL_TYPE_RGBA_FLOAT_ATI* = 0x000021A0 diff --git a/tests/manyloc/keineschweine/lib/zlib_helpers.nim b/tests/manyloc/keineschweine/lib/zlib_helpers.nim index fcd0e8d24..5241a77c0 100644 --- a/tests/manyloc/keineschweine/lib/zlib_helpers.nim +++ b/tests/manyloc/keineschweine/lib/zlib_helpers.nim @@ -18,7 +18,7 @@ proc uncompress*(source: string, destLen: var int): string = var res = zlib.uncompress(cstring(result), addr destLen, cstring(source), source.len) if res != Z_OK: echo "Error occurred: ", res - + when isMainModule: import strutils @@ -37,4 +37,4 @@ when isMainModule: ln = s.len rr = uncompress(r, ln) echo r.len, " -> ", rr.len - assert rr == s \ No newline at end of file + assert rr == s diff --git a/tests/manyloc/keineschweine/server/old_dirserver.nim b/tests/manyloc/keineschweine/server/old_dirserver.nim index 897fc7d32..202dc6fe7 100644 --- a/tests/manyloc/keineschweine/server/old_dirserver.nim +++ b/tests/manyloc/keineschweine/server/old_dirserver.nim @@ -17,7 +17,7 @@ var ## I was high. clients = initTable[TupAddress, PClient](16) alias2client = initTable[string, PClient](32) - allClients: seq[PClient] = @[] + allClients: seq[PClient] = @[] proc findClient*(host: string; port: int16): PClient = let addy: TupAddress = (host, port) @@ -37,7 +37,7 @@ proc loginZone(client: PClient; login: SdZoneLogin): bool = result = true break -proc sendZoneList(client: PClient) = +proc sendZoneList(client: PClient) = echo(">> zonelist ", client, ' ', HZoneList) client.send(HZonelist, zonelist) proc forwardPrivate(rcv: PClient; sender: PClient; txt: string) = @@ -93,7 +93,7 @@ proc sendServMsg(client: PClient; msg: string) = var m = newDsMsg(msg) client.send HDsMsg, m handlers[HZoneLogin] = proc(client: PClient; stream: PStream) = - var + var login = readSdZoneLogin(stream) if not client.loginZone(login): client.sendServMsg "Invalid login" @@ -110,7 +110,7 @@ handlers[HFileChallenge] = proc(client: PClient; stream: PStream) = var chg = readScFileChallenge(stream) proc handlePkt(s: PClient; stream: PStream) = - while not stream.atEnd: + while not stream.atEnd: var typ = readChar(stream) if not handlers.hasKey(typ): break @@ -128,7 +128,7 @@ var clientIndex = 0 var incoming = newIncomingBuffer() proc poll*(timeout: int = 250) = if server.isNil: return - var + var reads = @[server] writes = @[server] if select(reads, timeout) > 0: @@ -163,7 +163,7 @@ when isMainModule: case kind of cmdShortOption, cmdLongOption: case key - of "f", "file": + of "f", "file": if existsFile(val): cfgFile = val else: @@ -177,14 +177,14 @@ when isMainModule: zonelist.network = jsonSettings["network"].str for slot in jsonSettings["zones"].items: zoneSlots.add((slot["name"].str, slot["key"].str)) - + createServer(port) echo("Listening on port ", port, "...") var pubChatTimer = cpuTime() #newClock() const PubChatDelay = 1000/1000 while true: poll(15) - ## TODO sort this type of thing VV into a queue api + ## TODO sort this type of thing VV into a queue api if cpuTime() - pubChatTimer > PubChatDelay: #.getElapsedTime.asMilliseconds > 100: pubChatTimer -= pubChatDelay if pubChatQueue.getPosition > 0: diff --git a/tests/manyloc/keineschweine/server/old_server_utils.nim b/tests/manyloc/keineschweine/server/old_server_utils.nim index af9a1b01e..d0fd39ae0 100644 --- a/tests/manyloc/keineschweine/server/old_server_utils.nim +++ b/tests/manyloc/keineschweine/server/old_server_utils.nim @@ -1,4 +1,4 @@ -import +import streams, md5, sockets, unsigned, sg_packets, zlib_helpers, idgen type @@ -54,7 +54,7 @@ proc newClient*(addy: TupAddress): PClient = new(result, free) result.addy = addy result.outputBuf = newStringStream("") - result.outputBuf.flushImpl = proc(stream: PStream) = + result.outputBuf.flushImpl = proc(stream: PStream) = stream.setPosition 0 PStringStream(stream).data.setLen 0 diff --git a/tests/manyloc/keineschweine/server/old_sg_server.nim b/tests/manyloc/keineschweine/server/old_sg_server.nim index 1e57c12a1..c326720fe 100644 --- a/tests/manyloc/keineschweine/server/old_sg_server.nim +++ b/tests/manyloc/keineschweine/server/old_sg_server.nim @@ -9,13 +9,13 @@ var ## I was high. clients = initTable[TupAddress, PClient](16) alias2client = initTable[string, PClient](32) - allClients: seq[PClient] = @[] - zonePlayers: seq[PClient] = @[] + allClients: seq[PClient] = @[] + zonePlayers: seq[PClient] = @[] const PubChatDelay = 100/1000 #100 ms import hashes -proc hash*(x: uint16): THash {.inline.} = +proc hash*(x: uint16): THash {.inline.} = result = int32(x) proc findClient*(host: string; port: int16): PClient = @@ -27,7 +27,7 @@ proc findClient*(host: string; port: int16): PClient = allClients.add(result) -proc sendZoneList(client: PClient) = +proc sendZoneList(client: PClient) = echo(">> zonelist ", client) #client.send(HZonelist, zonelist) @@ -83,7 +83,7 @@ handlers[HZoneQuery] = proc(client: PClient; stream: PStream) = handlers[HZoneJoinReq] = proc(client: PClient; stream: PStream) = var req = readCsZoneJoinReq(stream) - echo "Join zone request from (",req.session.id,") ", req.session.alias + echo "Join zone request from (",req.session.id,") ", req.session.alias if client.auth and client.kind == CPlayer: echo "Client is authenticated, verifying filez" client.startVerifyingFiles() @@ -97,7 +97,7 @@ handlers[HZoneJoinReq] = proc(client: PClient; stream: PStream) = proc handlePkt(s: PClient; stream: PStream) = - while not stream.atEnd: + while not stream.atEnd: var typ = readChar(stream) if not handlers.hasKey(typ): break @@ -114,7 +114,7 @@ var clientIndex = 0 var incoming = newIncomingBuffer() proc poll*(timeout: int = 250) = if server.isNil: return - var + var reads = @[server] writes = @[server] if select(reads, timeout) > 0: @@ -148,7 +148,7 @@ when isMainModule: case kind of cmdShortOption, cmdLongOption: case key - of "f", "file": + of "f", "file": if existsFile(val): zoneCfgFile = val else: @@ -158,45 +158,45 @@ when isMainModule: else: echo("Unknown option: ", key, " ", val) var jsonSettings = parseFile(zoneCfgFile) - let + let host = jsonSettings["host"].str port = TPort(jsonSettings["port"].num) zoneFile = jsonSettings["settings"].str dirServerInfo = jsonSettings["dirserver"] - + var path = getAppDir()/../"data"/zoneFile if not existsFile(path): echo("Zone settings file does not exist: ../data/", zoneFile) echo(path) quit(1) - + ## Test file block: - var + var TestFile: FileChallengePair contents = repeat("abcdefghijklmnopqrstuvwxyz", 2) - testFile.challenge = newScFileChallenge("foobar.test", FZoneCfg, contents.len.int32) + testFile.challenge = newScFileChallenge("foobar.test", FZoneCfg, contents.len.int32) testFile.file = checksumStr(contents) myAssets.add testFile - + setCurrentDir getAppDir().parentDir() block: let zonesettings = readFile(path) - var + var errors: seq[string] = @[] if not loadSettings(zoneSettings, errors): echo("You have errors in your zone settings:") for e in errors: echo("**", e) quit(1) errors.setLen 0 - + var pair: FileChallengePair pair.challenge.file = zoneFile pair.challenge.assetType = FZoneCfg pair.challenge.fullLen = zoneSettings.len.int32 pair.file = checksumStr(zoneSettings) myAssets.add pair - + allAssets: if not load(asset): echo "Invalid or missing file ", file @@ -208,10 +208,10 @@ when isMainModule: expandPath(assetType, file)).int32 pair.file = asset.contents myAssets.add pair - + echo "Zone has ", myAssets.len, " associated assets" - - + + dirServer = newServerConnection(dirServerInfo[0].str, dirServerInfo[1].num.TPort) dirServer.handlers[HDsMsg] = proc(serv: PServer; stream: PStream) = var m = readDsMsg(stream) @@ -221,18 +221,18 @@ when isMainModule: if loggedIn: dirServerConnected = true dirServer.writePkt HZoneLogin, login - + thisZone.name = jsonSettings["name"].str thisZone.desc = jsonSettings["desc"].str thisZone.ip = "localhost" thisZone.port = port var login = newSdZoneLogin( dirServerInfo[2].str, dirServerInfo[3].str, - thisZone) + thisZone) #echo "MY LOGIN: ", $login - - - + + + createServer(port) echo("Listening on port ", port, "...") var pubChatTimer = cpuTime()#newClock() @@ -240,7 +240,7 @@ when isMainModule: discard dirServer.pollServer(15) poll(15) ## TODO sort this type of thing VV into a queue api - #let now = cpuTime() + #let now = cpuTime() if cpuTime() - pubChatTimer > PubChatDelay: #.getElapsedTime.asMilliseconds > 100: pubChatTimer -= pubChatDelay #.restart() if pubChatQueue.getPosition > 0: @@ -250,5 +250,5 @@ when isMainModule: c.outputBuf.writeData(addr pubChatQueue.data[0], sizePubChat) pubChatQueue.flush() - - \ No newline at end of file + + diff --git a/tests/manyloc/keineschweine/server/sg_lobby.nim b/tests/manyloc/keineschweine/server/sg_lobby.nim index 042d72337..f130e1b54 100644 --- a/tests/manyloc/keineschweine/server/sg_lobby.nim +++ b/tests/manyloc/keineschweine/server/sg_lobby.nim @@ -1,7 +1,7 @@ import - sockets, streams, tables, times, math, strutils, json, os, md5, - sfml, sfml_vector, sfml_colors, + sockets, streams, tables, times, math, strutils, json, os, md5, + sfml, sfml_vector, sfml_colors, streams_enh, input_helpers, zlib_helpers, client_helpers, sg_packets, sg_assets, sg_gui type TClientSettings = object @@ -33,7 +33,7 @@ var downloadProgress: PButton connectionButtons: seq[PButton] #buttons that depend on connection to function -template dispmessage(m: expr): stmt = +template dispmessage(m: expr): stmt = messageArea.add(m) proc connectZone(host: string; port: TPort) proc connectToDirserv() @@ -63,7 +63,7 @@ proc handleChat(serv: PServer; s: PStream) = proc connectToDirserv() = if dirServer.isNil: dirServer = newServerConnection(clientSettings.dirserver.host, clientSettings.dirserver.port) - dirServer.handlers[HHello] = proc(serv: PServer; s: PStream) = + dirServer.handlers[HHello] = proc(serv: PServer; s: PStream) = let msg = readScHello(s) dispMessage(msg.resp) setConnected(true) @@ -71,7 +71,7 @@ proc connectToDirserv() = mySession = readScLogin(s) ##do something here dirServer.handlers[HZonelist] = proc(serv: PServer; s: PStream) = - var + var info = readScZonelist(s) zones = info.zones if zones.len > 0: @@ -87,11 +87,11 @@ proc connectToDirserv() = var z = zones[i] zonelist.newButton( text = z.name, position = pos, - onClick = proc(b: PButton) = + onClick = proc(b: PButton) = setActiveZone(i, z)) pos.y += 20 showZonelist = true - dirServer.handlers[HPoing] = proc(serv: PServer; s: PStream) = + dirServer.handlers[HPoing] = proc(serv: PServer; s: PStream) = var ping = readPoing(s) dispmessage("Ping: "& $ping.time) ping.time = epochTime().float32 @@ -108,19 +108,19 @@ proc zoneListReq() = writePkt HZonelist, pkt ##key handlers -keyClient.registerHandler(MouseMiddle, down, proc() = +keyClient.registerHandler(MouseMiddle, down, proc() = gui.setPosition(getMousePos())) -keyClient.registerHandler(KeyO, down, proc() = +keyClient.registerHandler(KeyO, down, proc() = if keyPressed(KeyRShift): echo(repr(outgoing))) keyClient.registerHandler(KeyTab, down, proc() = activeInput = (activeInput + 1) mod 2) #does this work? -keyClient.registerHandler(MouseLeft, down, proc() = +keyClient.registerHandler(MouseLeft, down, proc() = let p = getMousePos() gui.click(p) if showZonelist: zonelist.click(p)) var mptext = newText("", guiFont, 16) -keyClient.registerHandler(MouseRight, down, proc() = +keyClient.registerHandler(MouseRight, down, proc() = let p = getMousePos() mptext.setPosition(p) mptext.setString("($1,$2)"%[$p.x.int,$p.y.int])) @@ -133,15 +133,15 @@ proc connectZone(host: string, port: TPort) = zone.handlers[HFileChallenge] = handleFileChallenge zone.handlers[HChallengeResult] = handleFileChallengeResult zone.handlers[HFileTransfer] = handleFileTransfer - zone.handlers[HChat] = handleChat + zone.handlers[HChat] = handleChat else: zone.sock.connect(host, port) var hello = newCsHello() zone.writePkt HHello, hello - -proc lobbyReady*() = + +proc lobbyReady*() = keyClient.setActive() gui.setActive(u_alias) @@ -186,27 +186,27 @@ proc lobbyInit*() = clientSettings.website = s["website"].str zonelist.setPosition(vec2f(200.0, 100.0)) connectionButtons = @[] - + downloadProgress = gui.newButton( - text = "", position = vec2f(10, 130), onClick = nil) + text = "", position = vec2f(10, 130), onClick = nil) downloadProgress.bg.setFillColor(color(34, 139, 34)) downloadProgress.bg.setSize(vec2f(0, 0)) - + var pos = vec2f(10, 10) u_alias = gui.newTextEntry( - if s.existsKey("alias"): s["alias"].str else: "alias", + if s.existsKey("alias"): s["alias"].str else: "alias", pos) pos.y += 20 u_passwd = gui.newTextEntry("buzz", pos) pos.y += 20 connectionButtons.add(gui.newButton( - text = "Login", + text = "Login", position = pos, onClick = tryLogin, startEnabled = false)) pos.y += 20 fpsText.setPosition(pos) - + playBtn = gui.newButton( text = "Play", position = vec2f(680.0, 8.0), @@ -227,7 +227,7 @@ proc lobbyInit*() = connectionButtons.add(gui.newButton( text = "Test Chat", position = vec2f(10.0, 110.0), - onClick = (proc(b: PButton) = + onClick = (proc(b: PButton) = var pkt = newCsChat(text = "ohai") writePkt HChat, pkt), startEnabled = false)) @@ -239,15 +239,15 @@ proc lobbyInit*() = gui.newButton(text = "Scrollback + 1", position = vec2f(185, 10), onClick = proc(b: PButton) = messageArea.scrollBack += 1 update(messageArea)) - gui.newButton(text = "Scrollback - 1", position = vec2f(185+160, 10), onClick = proc(b: PButton) = + gui.newButton(text = "Scrollback - 1", position = vec2f(185+160, 10), onClick = proc(b: PButton) = messageArea.scrollBack -= 1 update(messageArea)) gui.newButton(text = "Flood msg area", position = vec2f(185, 30), onClick = proc(b: PButton) = - for i in 0.. <30: + for i in 0.. <30: dispMessage($i)) var i = 0 -proc lobbyUpdate*(dt: float) = +proc lobbyUpdate*(dt: float) = #let res = disp.poll() gui.update(dt) i = (i + 1) mod 60 diff --git a/tests/manyloc/nake/nake.nim b/tests/manyloc/nake/nake.nim index 04b745003..1e88fa73b 100644 --- a/tests/manyloc/nake/nake.nim +++ b/tests/manyloc/nake/nake.nim @@ -3,7 +3,7 @@ DO AS THOU WILST PUBLIC LICENSE Whoever should stumble upon this document is henceforth and forever entitled to DO AS THOU WILST with aforementioned document and the -contents thereof. +contents thereof. As said in the Olde Country, `Keepe it Gangster'.""" @@ -14,7 +14,7 @@ type desc*: string action*: TTaskFunction TTaskFunction* = proc() {.closure.} -var +var tasks* = initTable[string, PTask](16) proc newTask*(desc: string; action: TTaskFunction): PTask @@ -61,7 +61,7 @@ when isMainModule: quit(shell("nim", "c", "-r", "nakefile.nim", args)) else: addQuitProc(proc() {.noconv.} = - var + var task: string printTaskList: bool for kind, key, val in getOpt(): @@ -70,7 +70,7 @@ else: case key.tolower of "tasks", "t": printTaskList = true - else: + else: echo "Unknown option: ", key, ": ", val of cmdArgument: task = key diff --git a/tests/manyloc/nake/nakefile.nim b/tests/manyloc/nake/nakefile.nim index d1d712964..6dc453e8d 100644 --- a/tests/manyloc/nake/nakefile.nim +++ b/tests/manyloc/nake/nakefile.nim @@ -4,7 +4,7 @@ nakeImports randomize() -const +const GameAssets = "http://dl.dropbox.com/u/37533467/data-08-01-2012.7z" BinLibs = "http://dl.dropbox.com/u/37533467/libs-2012-09-12.zip" ExeName = "keineschweine" @@ -60,7 +60,7 @@ task "release", "release build": quit 1 else: runTask "clean" - ## zip up all the files and such or something useful here + ## zip up all the files and such or something useful here task "testskel", "create skeleton test dir for testing": let dirname = "test-"& $random(5000) @@ -103,7 +103,7 @@ task "download", "download game assets": echo "Downloading to ", path downloadFile GameAssets, path echo "Download finished" - + let targetDir = parentDir(parentDir(path)) when defined(linux): let z7 = findExe("7z") @@ -117,7 +117,7 @@ task "download", "download game assets": else: echo "I do not know how to unpack the data on this system. Perhaps you could ", "fill this part in?" - + echo "Download binary libs? Only libs for linux are available currently, enjoy the irony.\n", "[Y]es [N]o Source: ", BinLibs case stdin.readline.toLower @@ -126,11 +126,11 @@ task "download", "download game assets": else: return path = extractFilename(BinLibs) - downloadFile BinLibs, path + downloadFile BinLibs, path echo "Downloaded dem libs ", path when true: echo "Unpack it yourself, sorry." else: ## this crashes, dunno why - var + var z: TZipArchive destDir = getCurrentDir()/("unzip"& $random(5000)) if not z.open(path, fmRead): @@ -152,4 +152,4 @@ task "zip-lib", "zip up the libs dir": echo "adding file ", file z.addFile(file) z.close() - echo "Great success!" \ No newline at end of file + echo "Great success!" diff --git a/tests/metatype/tbindtypedesc.nim b/tests/metatype/tbindtypedesc.nim index 84527362f..4f027407b 100644 --- a/tests/metatype/tbindtypedesc.nim +++ b/tests/metatype/tbindtypedesc.nim @@ -9,7 +9,7 @@ TFoo TFoo''' import typetraits -type +type TFoo = object x, y: int @@ -25,7 +25,7 @@ template reject(e: expr) = proc genericParamRepeated[T: typedesc](a: T, b: T) = static: echo a.name, " ", b.name - + accept genericParamRepeated(int, int) accept genericParamRepeated(float, float) diff --git a/tests/metatype/tconstraints.nim b/tests/metatype/tconstraints.nim index 7aef0d645..76e738a85 100644 --- a/tests/metatype/tconstraints.nim +++ b/tests/metatype/tconstraints.nim @@ -1,6 +1,6 @@ -proc myGenericProc[T: object|tuple|int|ptr|ref|distinct](x: T): string = +proc myGenericProc[T: object|tuple|int|ptr|ref|distinct](x: T): string = result = $x type diff --git a/tests/metatype/tmatrix.nim b/tests/metatype/tmatrix.nim index 90dfde959..5acd4389e 100644 --- a/tests/metatype/tmatrix.nim +++ b/tests/metatype/tmatrix.nim @@ -11,7 +11,7 @@ type template `|`(x, y: int): expr = y * m.fWidth + x -proc createMatrix*(width, height: int): TMatrix = +proc createMatrix*(width, height: int): TMatrix = result.fWidth = width result.fHeight = height newSeq(result.data, width*height) @@ -24,7 +24,7 @@ proc `[]`*(m: TMatrix, x, y: int): float {.inline.} = proc `[]=`*(m: var TMatrix, x, y: int, val: float) {.inline.} = m.data[x|y] = val - + proc `-|`*(m: TMatrix): TMatrix = ## transposes a matrix result = createMatrix(m.height, m.width) diff --git a/tests/metatype/tmatrix1.nim b/tests/metatype/tmatrix1.nim index 0adf30b57..0f325a17b 100644 --- a/tests/metatype/tmatrix1.nim +++ b/tests/metatype/tmatrix1.nim @@ -3,7 +3,7 @@ discard """ """ type - TMatrixNM*[M, N, T] = object + TMatrixNM*[M, N, T] = object aij*: array[M, array[N, T]] TMatrix2x2*[T] = TMatrixNM[range[0..1], range[0..1], T] TMatrix3x3*[T] = TMatrixNM[range[0..2], range[0..2], T] @@ -12,7 +12,7 @@ proc test*[T] (matrix: TMatrix2x2[T]) = echo "wrong proc called" proc test*[T] (matrix: TMatrix3x3[T]) = - echo "right proc called" + echo "right proc called" var matrix: TMatrix3x3[float] diff --git a/tests/metatype/tmatrix2.nim b/tests/metatype/tmatrix2.nim index 82990f1a5..bad021390 100644 --- a/tests/metatype/tmatrix2.nim +++ b/tests/metatype/tmatrix2.nim @@ -3,7 +3,7 @@ discard """ """ type - TMatrixNM*[M, N, T] = object + TMatrixNM*[M, N, T] = object aij*: T TVectorN*[N, T] = TMatrixNM[range[0..0], N, T] TVector3*[T] = TVectorN[range[0..2], T] @@ -13,7 +13,7 @@ proc coeffRef*[M, N, T] (matrix: var TMatrixNM[M, N, T], a: M, b: N): var T = proc coeffRef*[N, T] (vector: var TVectorN[N, T], i: N): var T = vector.aij -var +var testVar: TVector3[float] testVar.aij = 2.0 diff --git a/tests/metatype/tstaticparammacro.nim b/tests/metatype/tstaticparammacro.nim index e577efc56..5c7c5e6af 100644 --- a/tests/metatype/tstaticparammacro.nim +++ b/tests/metatype/tstaticparammacro.nim @@ -5,9 +5,9 @@ bb numbers 11 22 -AST a +AST a [(11, 22), (33, 44)] -AST b +AST b (e: [55, 66], f: [77, 88]) 55 10 diff --git a/tests/metatype/tstaticparams.nim b/tests/metatype/tstaticparams.nim index 7fc5f479b..11653e563 100644 --- a/tests/metatype/tstaticparams.nim +++ b/tests/metatype/tstaticparams.nim @@ -3,7 +3,7 @@ discard """ output: "abracadabra\ntest\n3\n15\n4\n2\nfloat\n3\nfloat\nyin\nyang" """ -type +type TFoo[T; Val: static[string]] = object data: array[4, T] @@ -121,7 +121,7 @@ foo_3.yinOrYang # bug 1859 -type +type TypeWith2Params[N, M: static[int]] = object proc bindBothParams[N](x: TypeWith2Params[N, N]) = discard diff --git a/tests/metatype/ttypedesc1.nim b/tests/metatype/ttypedesc1.nim index 0c6f5dce4..19072d966 100644 --- a/tests/metatype/ttypedesc1.nim +++ b/tests/metatype/ttypedesc1.nim @@ -1,6 +1,6 @@ import unittest, typetraits -type +type TFoo[T, U] = object x: T y: U @@ -21,17 +21,17 @@ proc foo(T: typedesc[int or bool]): string = template foo(T: typedesc[seq]): expr = "seq" test "types can be used as proc params": - # XXX: `check` needs to know that TFoo[int, float] is a type and + # XXX: `check` needs to know that TFoo[int, float] is a type and # cannot be assigned for a local variable for later inspection check ((string.getTypeName == "string")) check ((getTypeName(int) == "int")) - + check ((foo(TFoo[int, float], 1000) == "TFoo 1000")) - + var f = 10.0 check ((foo(float, "long string") == "float true")) check ((foo(type(f), [1, 2, 3]) == "float false")) - + check ((foo(int) == "int or bool 10")) check ((foo(seq[int]) == "seq")) diff --git a/tests/metatype/ttypeselectors.nim b/tests/metatype/ttypeselectors.nim index cca643e1f..c29fd15ce 100644 --- a/tests/metatype/ttypeselectors.nim +++ b/tests/metatype/ttypeselectors.nim @@ -10,7 +10,7 @@ template simpleTypeTempl: typeDesc = string macro typeFromMacro: typedesc = string - + proc t1*(x: int): simpleTypeTempl() = result = "test" diff --git a/tests/metatype/ttypetraits.nim b/tests/metatype/ttypetraits.nim index 4c3ad9e0b..106257828 100644 --- a/tests/metatype/ttypetraits.nim +++ b/tests/metatype/ttypetraits.nim @@ -42,18 +42,18 @@ const TypeList = [int, string, seq[int]] macro selectType(inType: typedesc): typedesc = var typeSeq = @[float, TBar[int]] - + for t in TypeList: typeSeq.add(t) typeSeq.add(inType) typeSeq.add(type(10)) - + var typeSeq2: seq[typedesc] = @[] typeSeq2 = typeSeq result = typeSeq2[5] - + var xvar: selectType(string) xvar = "proba" echo xvar.type.name diff --git a/tests/method/tmethods1.nim b/tests/method/tmethods1.nim index 43a260bca..461e2cb5e 100644 --- a/tests/method/tmethods1.nim +++ b/tests/method/tmethods1.nim @@ -11,7 +11,7 @@ type PNodeFoo* = ref object of TNode - TSomethingElse = object + TSomethingElse = object PSomethingElse = ref TSomethingElse method foo(a: PNode, b: PSomethingElse) = discard diff --git a/tests/method/tmultim1.nim b/tests/method/tmultim1.nim index 7f551aa64..c7027f4c0 100644 --- a/tests/method/tmultim1.nim +++ b/tests/method/tmultim1.nim @@ -10,7 +10,7 @@ type x: int PlusExpr = ref object of Expression a, b: Expression - + method eval(e: Expression): int = quit "to override!" method eval(e: Literal): int = return e.x method eval(e: PlusExpr): int = return eval(e.a) + eval(e.b) @@ -18,7 +18,7 @@ method eval(e: PlusExpr): int = return eval(e.a) + eval(e.b) proc newLit(x: int): Literal = new(result) result.x = x - + proc newPlus(a, b: Expression): PlusExpr = new(result) result.a = a diff --git a/tests/method/tmultim2.nim b/tests/method/tmultim2.nim index c5fb568a0..e695dd19b 100644 --- a/tests/method/tmultim2.nim +++ b/tests/method/tmultim2.nim @@ -13,10 +13,10 @@ type x: int TParticle = object of TThing a, b: int - + method collide(a, b: TThing) {.inline.} = echo "collide: thing, thing" - + method collide(a: TThing, b: TUnit) {.inline.} = echo "collide: thing, unit" diff --git a/tests/method/tmultim4.nim b/tests/method/tmultim4.nim index d824086b2..54630fb41 100644 --- a/tests/method/tmultim4.nim +++ b/tests/method/tmultim4.nim @@ -26,7 +26,7 @@ var s:ref Test = newTest() for z in 1..4: s.doMethod() break - + #works #for z in 1..4: # s.doProc() diff --git a/tests/method/tmultim6.nim b/tests/method/tmultim6.nim index 5f45f572a..6c21f80d2 100644 --- a/tests/method/tmultim6.nim +++ b/tests/method/tmultim6.nim @@ -9,10 +9,10 @@ type x: T TParticle = object of TThing a, b: int - + method collide(a, b: TThing) {.inline.} = quit "to override!" - + method collide[T](a: TThing, b: TUnit[T]) {.inline.} = write stdout, "collide: thing, unit | " diff --git a/tests/misc/minit.nim b/tests/misc/minit.nim index 75fcebb77..513f46af5 100644 --- a/tests/misc/minit.nim +++ b/tests/misc/minit.nim @@ -1,2 +1,2 @@ -# Test the new initialization for modules -write(stdout, "Hello from module! ") +# Test the new initialization for modules +write(stdout, "Hello from module! ") diff --git a/tests/misc/mvarious.nim b/tests/misc/mvarious.nim index c0a8add73..d1587faec 100644 --- a/tests/misc/mvarious.nim +++ b/tests/misc/mvarious.nim @@ -1,6 +1,6 @@ -# Test a submodule - -#type -# TStringArr = array [0.. *] of string - -proc exportme* = discard +# Test a submodule + +#type +# TStringArr = array [0.. *] of string + +proc exportme* = discard diff --git a/tests/misc/t99bott.nim b/tests/misc/t99bott.nim index b3b30d296..62ccfbe16 100644 --- a/tests/misc/t99bott.nim +++ b/tests/misc/t99bott.nim @@ -25,7 +25,7 @@ proc GetBottleNumber(n: int): string = for bn in countdown(99, 1): const cur = GetBottleNumber(bn) echo(cur, " on the wall, ", cur, ".") - echo("Take one down and pass it around, ", GetBottleNumber(bn-1), + echo("Take one down and pass it around, ", GetBottleNumber(bn-1), " on the wall.\n") echo "No more bottles of beer on the wall, no more bottles of beer." diff --git a/tests/misc/tack.nim b/tests/misc/tack.nim index 680ff567e..a0afab9e8 100644 --- a/tests/misc/tack.nim +++ b/tests/misc/tack.nim @@ -2,20 +2,20 @@ discard """ file: "tack.nim" output: "125" """ -# the Ackermann function - -proc ack(x, y: int): int = - if x != 0: - if y != 0: - return ack(x-1, ack(x, y-1)) - return ack(x-1, 1) - else: - return y + 1 -# if x == 0: return y + 1 -# elif y == 0: return ack(x-1, 1) -# else: return ack(x-1, ack(x, y-1)) - -# echo(ack(0, 0)) -write(stdout, ack(3, 4)) #OUT 125 +# the Ackermann function + +proc ack(x, y: int): int = + if x != 0: + if y != 0: + return ack(x-1, ack(x, y-1)) + return ack(x-1, 1) + else: + return y + 1 +# if x == 0: return y + 1 +# elif y == 0: return ack(x-1, 1) +# else: return ack(x-1, ack(x, y-1)) + +# echo(ack(0, 0)) +write(stdout, ack(3, 4)) #OUT 125 diff --git a/tests/misc/tatomic.nim b/tests/misc/tatomic.nim index 1fa0cff8d..f3c56ffe3 100644 --- a/tests/misc/tatomic.nim +++ b/tests/misc/tatomic.nim @@ -3,9 +3,9 @@ discard """ line: 7 errormsg: "identifier expected, but found 'keyword atomic'" """ -var +var atomic: int - + echo atomic diff --git a/tests/misc/tcolonisproc.nim b/tests/misc/tcolonisproc.nim index af4077284..665e9e604 100644 --- a/tests/misc/tcolonisproc.nim +++ b/tests/misc/tcolonisproc.nim @@ -7,7 +7,7 @@ when false: p(1, 3): echo 1 echo 3 - + p(1, 1, proc() = echo 1 echo 2) diff --git a/tests/misc/tdllvar.nim b/tests/misc/tdllvar.nim index 5a31dfbbb..1c1238e8d 100644 --- a/tests/misc/tdllvar.nim +++ b/tests/misc/tdllvar.nim @@ -1,6 +1,6 @@ import os -proc getDllName: string = +proc getDllName: string = result = "mylib.dll" if fileExists(result): return result = "mylib2.dll" diff --git a/tests/misc/temit.nim b/tests/misc/temit.nim index e2a9eaff1..c83235659 100644 --- a/tests/misc/temit.nim +++ b/tests/misc/temit.nim @@ -2,14 +2,14 @@ discard """ file: "temit.nim" output: "509" """ -# Test the new ``emit`` pragma: +# Test the new ``emit`` pragma: {.emit: """ static int cvariable = 420; """.} -proc embedsC() = +proc embedsC() = var nimVar = 89 {.emit: """printf("%d\n", cvariable + (int)`nimVar`);""".} diff --git a/tests/misc/teventemitter.nim b/tests/misc/teventemitter.nim index c1cc3d3a9..32cc81be4 100644 --- a/tests/misc/teventemitter.nim +++ b/tests/misc/teventemitter.nim @@ -13,7 +13,7 @@ proc emit*(emitter: EventEmitter, event: string, args: EventArgs) = for fn in nodes(emitter.events[event]): fn.value(args) #call function with args. -proc on*(emitter: var EventEmitter, event: string, +proc on*(emitter: var EventEmitter, event: string, fn: proc(e: EventArgs) {.nimcall.}) = if not hasKey(emitter.events, event): var list: DoublyLinkedList[proc(e: EventArgs) {.nimcall.}] @@ -21,10 +21,10 @@ proc on*(emitter: var EventEmitter, event: string, append(emitter.events.mget(event), fn) proc initEmitter(emitter: var EventEmitter) = - emitter.events = initTable[string, + emitter.events = initTable[string, DoublyLinkedList[proc(e: EventArgs) {.nimcall.}]]() -var +var ee: EventEmitter args: EventArgs initEmitter(ee) diff --git a/tests/misc/tevents.nim b/tests/misc/tevents.nim index fb94b1f79..5f2169f29 100644 --- a/tests/misc/tevents.nim +++ b/tests/misc/tevents.nim @@ -13,11 +13,11 @@ type proc handleprintevent*(e: TEventArgs) = write(stdout, "HandlePrintEvent: Output -> Handled print event\n") - + proc handleprintevent2*(e: TEventArgs) = var args: TPrintEventArgs = TPrintEventArgs(e) write(stdout, "HandlePrintEvent2: Output -> printing for " & args.user) - + var ee = initEventEmitter() var eventargs: TPrintEventArgs diff --git a/tests/misc/tfib.nim b/tests/misc/tfib.nim index 09a4d5038..34fe0dcf9 100644 --- a/tests/misc/tfib.nim +++ b/tests/misc/tfib.nim @@ -1,8 +1,8 @@ -iterator fibonacci(): int = +iterator fibonacci(): int = var a = 0 var b = 1 - while true: + while true: yield a var c = b b = a diff --git a/tests/misc/tgetstartmilsecs.nim b/tests/misc/tgetstartmilsecs.nim index 5a3368e0f..bf508dd54 100644 --- a/tests/misc/tgetstartmilsecs.nim +++ b/tests/misc/tgetstartmilsecs.nim @@ -1,4 +1,4 @@ -# +# import times, os var start = epochTime() diff --git a/tests/misc/theaproots.nim b/tests/misc/theaproots.nim index aec140f42..77d0207b0 100644 --- a/tests/misc/theaproots.nim +++ b/tests/misc/theaproots.nim @@ -1,7 +1,7 @@ -type +type Bar = object x: int - + Foo = object rheap: ref Bar rmaybe: ref Bar @@ -31,7 +31,7 @@ proc test(maybeFoo: var Foo, maybeFoo.list[3] = bb maybeFoo.listarr[3] = bb acc(maybeFoo) = bb - + var localFoo: Foo localFoo.rstack = bb localFoo.list[3] = bb diff --git a/tests/misc/thintoff.nim b/tests/misc/thintoff.nim index 807ff44f3..95318ce9b 100644 --- a/tests/misc/thintoff.nim +++ b/tests/misc/thintoff.nim @@ -6,7 +6,7 @@ discard """ {.hint[XDeclaredButNotUsed]: off.} var x: int - + echo x #OUT 0 diff --git a/tests/misc/tinit.nim b/tests/misc/tinit.nim index 5c75567ec..02607909b 100644 --- a/tests/misc/tinit.nim +++ b/tests/misc/tinit.nim @@ -2,11 +2,11 @@ discard """ file: "tinit.nim" output: "Hello from module! Hello from main module!" """ -# Test the new init section in modules - -import minit - -write(stdout, "Hello from main module!\n") -#OUT Hello from module! Hello from main module! +# Test the new init section in modules + +import minit + +write(stdout, "Hello from main module!\n") +#OUT Hello from module! Hello from main module! diff --git a/tests/misc/tinout.nim b/tests/misc/tinout.nim index 4e5908428..0b2a54d9f 100644 --- a/tests/misc/tinout.nim +++ b/tests/misc/tinout.nim @@ -3,14 +3,14 @@ discard """ line: 12 errormsg: "type mismatch: got (int literal(3))" """ -# Test in out checking for parameters - -proc abc(x: var int) = - x = 0 - -proc b() = - abc(3) #ERROR - -b() +# Test in out checking for parameters + +proc abc(x: var int) = + x = 0 + +proc b() = + abc(3) #ERROR + +b() diff --git a/tests/misc/tinvalidnewseq.nim b/tests/misc/tinvalidnewseq.nim index 957a25560..89083d8b2 100644 --- a/tests/misc/tinvalidnewseq.nim +++ b/tests/misc/tinvalidnewseq.nim @@ -14,12 +14,12 @@ proc parseURL(url: string): TURL = var m: array[0..6, string] #Array with the matches newSeq(m, 7) #ERROR discard regexprs.match(url, re(pattern), m) - - result = (protocol: m[1], subdomain: m[2], domain: m[3] & m[4], + + result = (protocol: m[1], subdomain: m[2], domain: m[3] & m[4], port: m[5], path: m[6].split('/')) - + var r: TUrl - + r = parseUrl(r"http://google.com/search?var=bleahdhsad") echo(r.domain) diff --git a/tests/misc/tlastmod.nim b/tests/misc/tlastmod.nim index 857164022..538b5e656 100644 --- a/tests/misc/tlastmod.nim +++ b/tests/misc/tlastmod.nim @@ -1,18 +1,18 @@ -# test the new LastModificationTime() proc - -import - os, times, strutils - -proc main() = - var - a, b: TTime - a = getLastModificationTime(paramStr(1)) - b = getLastModificationTime(paramStr(2)) - writeLine(stdout, $a) - writeLine(stdout, $b) - if a < b: - write(stdout, "$2 is newer than $1\n" % [paramStr(1), paramStr(2)]) - else: - write(stdout, "$1 is newer than $2\n" % [paramStr(1), paramStr(2)]) - -main() +# test the new LastModificationTime() proc + +import + os, times, strutils + +proc main() = + var + a, b: TTime + a = getLastModificationTime(paramStr(1)) + b = getLastModificationTime(paramStr(2)) + writeLine(stdout, $a) + writeLine(stdout, $b) + if a < b: + write(stdout, "$2 is newer than $1\n" % [paramStr(1), paramStr(2)]) + else: + write(stdout, "$1 is newer than $2\n" % [paramStr(1), paramStr(2)]) + +main() diff --git a/tests/misc/tlocals.nim b/tests/misc/tlocals.nim index af8a54946..3e240d3c8 100644 --- a/tests/misc/tlocals.nim +++ b/tests/misc/tlocals.nim @@ -2,10 +2,10 @@ discard """ output: "(x: string here, a: 1)" """ -proc simple[T](a: T) = +proc simple[T](a: T) = var x = "string here" echo locals() - + simple(1) diff --git a/tests/misc/tloops.nim b/tests/misc/tloops.nim index 1aada0298..b160500af 100644 --- a/tests/misc/tloops.nim +++ b/tests/misc/tloops.nim @@ -76,7 +76,7 @@ proc main[T]() = b = (1, 2, 3) myType = b echo myType - + var myType2: MyType2 var c: MyType2 c = (1.0, 2.0) diff --git a/tests/misc/tmissingnilcheck.nim b/tests/misc/tmissingnilcheck.nim index c2f23ae87..461fb18f4 100644 --- a/tests/misc/tmissingnilcheck.nim +++ b/tests/misc/tmissingnilcheck.nim @@ -14,7 +14,7 @@ proc newConnection = proc cb {.closure.} = discard - + first.callback = cb newConnection() diff --git a/tests/misc/tnew.nim b/tests/misc/tnew.nim index 6527541a2..88e8bd02c 100644 --- a/tests/misc/tnew.nim +++ b/tests/misc/tnew.nim @@ -1,49 +1,49 @@ -# Test the implementation of the new operator -# and the code generation for gc walkers -# (and the garbage collector): - -type - PNode = ref TNode - TNode = object - data: int - str: string - le, ri: PNode - - TStressTest = ref array [0..45, array [1..45, TNode]] - -proc finalizer(n: PNode) = - write(stdout, n.data) - write(stdout, " is now freed\n") - -proc newNode(data: int, le, ri: PNode): PNode = - new(result, finalizer) - result.le = le - result.ri = ri - result.data = data - -# now loop and build a tree -proc main() = - var - i = 0 - p: TStressTest - while i < 1000: - var n: PNode - - n = newNode(i, nil, newNode(i + 10000, nil, nil)) - inc(i) - new(p) - - write(stdout, "Simple tree node allocation worked!\n") - i = 0 - while i < 1000: - var m = newNode(i + 20000, nil, nil) - var k = newNode(i + 30000, nil, nil) - m.le = m - m.ri = k - k.le = m - k.ri = k - inc(i) - - write(stdout, "Simple cycle allocation worked!\n") - -main() +# Test the implementation of the new operator +# and the code generation for gc walkers +# (and the garbage collector): + +type + PNode = ref TNode + TNode = object + data: int + str: string + le, ri: PNode + + TStressTest = ref array [0..45, array [1..45, TNode]] + +proc finalizer(n: PNode) = + write(stdout, n.data) + write(stdout, " is now freed\n") + +proc newNode(data: int, le, ri: PNode): PNode = + new(result, finalizer) + result.le = le + result.ri = ri + result.data = data + +# now loop and build a tree +proc main() = + var + i = 0 + p: TStressTest + while i < 1000: + var n: PNode + + n = newNode(i, nil, newNode(i + 10000, nil, nil)) + inc(i) + new(p) + + write(stdout, "Simple tree node allocation worked!\n") + i = 0 + while i < 1000: + var m = newNode(i + 20000, nil, nil) + var k = newNode(i + 30000, nil, nil) + m.le = m + m.ri = k + k.le = m + k.ri = k + inc(i) + + write(stdout, "Simple cycle allocation worked!\n") + +main() diff --git a/tests/misc/tnewderef.nim b/tests/misc/tnewderef.nim index 89dc4c8d1..3394dbddf 100644 --- a/tests/misc/tnewderef.nim +++ b/tests/misc/tnewderef.nim @@ -7,5 +7,5 @@ var x: ref int new(x) x[] = 3 -echo x[] +echo x[] diff --git a/tests/misc/tnewsets.nim b/tests/misc/tnewsets.nim index 415fe8f7e..f239d4aa2 100644 --- a/tests/misc/tnewsets.nim +++ b/tests/misc/tnewsets.nim @@ -1,6 +1,6 @@ -# new test for sets: - -const elem = ' ' - -var s: set[char] = {elem} -assert(elem in s and 'a' not_in s and 'c' not_in s ) +# new test for sets: + +const elem = ' ' + +var s: set[char] = {elem} +assert(elem in s and 'a' not_in s and 'c' not_in s ) diff --git a/tests/misc/tnewuns.nim b/tests/misc/tnewuns.nim index 267c73f5b..d6bae4fb1 100644 --- a/tests/misc/tnewuns.nim +++ b/tests/misc/tnewuns.nim @@ -1,12 +1,12 @@ -# test the new unsigned operations: - -import - strutils - -var - x, y: int - -x = 1 -y = high(int) - -writeLine(stdout, $ ( x +% y ) ) +# test the new unsigned operations: + +import + strutils + +var + x, y: int + +x = 1 +y = high(int) + +writeLine(stdout, $ ( x +% y ) ) diff --git a/tests/misc/tnoinst.nim b/tests/misc/tnoinst.nim index 4c8d9d1aa..25ebe8dfc 100644 --- a/tests/misc/tnoinst.nim +++ b/tests/misc/tnoinst.nim @@ -11,7 +11,7 @@ proc wrap[T]() = var x: proc (x, y: T): int x = notConcrete - + wrap[int]() diff --git a/tests/misc/tnot.nim b/tests/misc/tnot.nim index 6193e21e1..60d23c035 100644 --- a/tests/misc/tnot.nim +++ b/tests/misc/tnot.nim @@ -5,10 +5,10 @@ discard """ """ # BUG: following compiles, but should not: -proc nodeOfDegree(x: int): bool = +proc nodeOfDegree(x: int): bool = result = false -proc main = +proc main = for j in 0..2: for i in 0..10: if not nodeOfDegree(1) >= 0: #ERROR_MSG type mismatch diff --git a/tests/misc/tparedef.nim b/tests/misc/tparedef.nim index dedebf6b7..83c2651ff 100644 --- a/tests/misc/tparedef.nim +++ b/tests/misc/tparedef.nim @@ -1,4 +1,4 @@ -# This test is now superfluous: - -proc a(a: int) = - return +# This test is now superfluous: + +proc a(a: int) = + return diff --git a/tests/misc/tpos.nim b/tests/misc/tpos.nim index 5560ef050..bedb62e62 100644 --- a/tests/misc/tpos.nim +++ b/tests/misc/tpos.nim @@ -2,34 +2,34 @@ discard """ file: "tpos.nim" output: "6" """ -# test this particular function - -proc mypos(sub, s: string, start: int = 0): int = - var - i, j, M, N: int - M = sub.len - N = s.len - i = start - j = 0 - if i >= N: - result = -1 - else: - while true: - if s[i] == sub[j]: - inc(i) - inc(j) - else: - i = i - j + 1 - j = 0 - if (j >= M) or (i >= N): break - if j >= M: - result = i - M - else: - result = -1 - -var sub = "hello" -var s = "world hello" -write(stdout, mypos(sub, s)) -#OUT 6 +# test this particular function + +proc mypos(sub, s: string, start: int = 0): int = + var + i, j, M, N: int + M = sub.len + N = s.len + i = start + j = 0 + if i >= N: + result = -1 + else: + while true: + if s[i] == sub[j]: + inc(i) + inc(j) + else: + i = i - j + 1 + j = 0 + if (j >= M) or (i >= N): break + if j >= M: + result = i - M + else: + result = -1 + +var sub = "hello" +var s = "world hello" +write(stdout, mypos(sub, s)) +#OUT 6 diff --git a/tests/misc/tquicksort.nim b/tests/misc/tquicksort.nim index 6706a185e..0867a3769 100644 --- a/tests/misc/tquicksort.nim +++ b/tests/misc/tquicksort.nim @@ -9,17 +9,17 @@ proc QuickSort(list: seq[int]): seq[int] = left.add(list[i]) elif list[i] > pivot: right.add(list[i]) - result = QuickSort(left) & - pivot & + result = QuickSort(left) & + pivot & QuickSort(right) - + proc echoSeq(a: seq[int]) = for i in low(a)..high(a): echo(a[i]) var list: seq[int] - + list = QuickSort(@[89,23,15,23,56,123,356,12,7,1,6,2,9,4,3]) echoSeq(list) diff --git a/tests/misc/tradix.nim b/tests/misc/tradix.nim index 311aa9ccd..36a4f39f6 100644 --- a/tests/misc/tradix.nim +++ b/tests/misc/tradix.nim @@ -1,7 +1,7 @@ # implements and tests an efficient radix tree -## another method to store an efficient array of pointers: -## We use a radix tree with node compression. +## another method to store an efficient array of pointers: +## We use a radix tree with node compression. ## There are two node kinds: const BitsPerUnit = 8*sizeof(int) @@ -15,7 +15,7 @@ type len: int8 keys: array [0..31, int8] vals: array [0..31, PRadixNode] - + TRadixNodeFull = object of TRadixNode b: array [0..255, PRadixNode] TRadixNodeLeafBits = object of TRadixNode @@ -27,43 +27,43 @@ type var root: PRadixNode -proc searchInner(r: PRadixNode, a: int): PRadixNode = +proc searchInner(r: PRadixNode, a: int): PRadixNode = case r.kind of rnLinear: var x = cast[ptr TRadixNodeLinear](r) - for i in 0..ze(x.len)-1: + for i in 0..ze(x.len)-1: if ze(x.keys[i]) == a: return x.vals[i] - of rnFull: + of rnFull: var x = cast[ptr TRadixNodeFull](r) return x.b[a] else: assert(false) -proc testBit(w, i: int): bool {.inline.} = +proc testBit(w, i: int): bool {.inline.} = result = (w and (1 shl (i %% BitsPerUnit))) != 0 -proc setBit(w: var int, i: int) {.inline.} = +proc setBit(w: var int, i: int) {.inline.} = w = w or (1 shl (i %% BitsPerUnit)) -proc resetBit(w: var int, i: int) {.inline.} = +proc resetBit(w: var int, i: int) {.inline.} = w = w and not (1 shl (i %% BitsPerUnit)) -proc testOrSetBit(w: var int, i: int): bool {.inline.} = +proc testOrSetBit(w: var int, i: int): bool {.inline.} = var x = (1 shl (i %% BitsPerUnit)) if (w and x) != 0: return true w = w or x -proc searchLeaf(r: PRadixNode, a: int): bool = +proc searchLeaf(r: PRadixNode, a: int): bool = case r.kind of rnLeafBits: var x = cast[ptr TRadixNodeLeafBits](r) return testBit(x.b[a /% BitsPerUnit], a) of rnLeafLinear: var x = cast[ptr TRadixNodeLeafLinear](r) - for i in 0..ze(x.len)-1: + for i in 0..ze(x.len)-1: if ze(x.keys[i]) == a: return true else: assert(false) -proc exclLeaf(r: PRadixNode, a: int) = +proc exclLeaf(r: PRadixNode, a: int) = case r.kind of rnLeafBits: var x = cast[ptr TRadixNodeLeafBits](r) @@ -71,8 +71,8 @@ proc exclLeaf(r: PRadixNode, a: int) = of rnLeafLinear: var x = cast[ptr TRadixNodeLeafLinear](r) var L = ze(x.len) - for i in 0..L-1: - if ze(x.keys[i]) == a: + for i in 0..L-1: + if ze(x.keys[i]) == a: x.keys[i] = x.keys[L-1] dec(x.len) return @@ -98,7 +98,7 @@ proc excl*(r: PRadixNode, a: ByteAddress): bool = if x == nil: return false exclLeaf(x, a and 0xff) -proc addLeaf(r: var PRadixNode, a: int): bool = +proc addLeaf(r: var PRadixNode, a: int): bool = if r == nil: # a linear node: var x = cast[ptr TRadixNodeLinear](alloc(sizeof(TRadixNodeLinear))) @@ -107,23 +107,23 @@ proc addLeaf(r: var PRadixNode, a: int): bool = x.keys[0] = toU8(a) r = x return false # not already in set - case r.kind - of rnLeafBits: + case r.kind + of rnLeafBits: var x = cast[ptr TRadixNodeLeafBits](r) return testOrSetBit(x.b[a /% BitsPerUnit], a) - of rnLeafLinear: + of rnLeafLinear: var x = cast[ptr TRadixNodeLeafLinear](r) var L = ze(x.len) - for i in 0..L-1: + for i in 0..L-1: if ze(x.keys[i]) == a: return true if L <= high(x.keys): x.keys[L] = toU8(a) inc(x.len) - else: + else: # transform into a full node: var y = cast[ptr TRadixNodeLeafBits](alloc0(sizeof(TRadixNodeLeafBits))) y.kind = rnLeafBits - for i in 0..ze(x.len)-1: + for i in 0..ze(x.len)-1: var u = ze(x.keys[i]) setBit(y.b[u /% BitsPerUnit], u) setBit(y.b[a /% BitsPerUnit], a) @@ -131,8 +131,8 @@ proc addLeaf(r: var PRadixNode, a: int): bool = r = y else: assert(false) -proc addInner(r: var PRadixNode, a: int, d: int): bool = - if d == 0: +proc addInner(r: var PRadixNode, a: int, d: int): bool = + if d == 0: return addLeaf(r, a and 0xff) var k = a shr d and 0xff if r == nil: @@ -147,14 +147,14 @@ proc addInner(r: var PRadixNode, a: int, d: int): bool = of rnLinear: var x = cast[ptr TRadixNodeLinear](r) var L = ze(x.len) - for i in 0..L-1: + for i in 0..L-1: if ze(x.keys[i]) == k: # already exists return addInner(x.vals[i], a, d-8) if L <= high(x.keys): x.keys[L] = toU8(k) inc(x.len) return addInner(x.vals[L], a, d-8) - else: + else: # transform into a full node: var y = cast[ptr TRadixNodeFull](alloc0(sizeof(TRadixNodeFull))) y.kind = rnFull @@ -162,55 +162,55 @@ proc addInner(r: var PRadixNode, a: int, d: int): bool = dealloc(r) r = y return addInner(y.b[k], a, d-8) - of rnFull: + of rnFull: var x = cast[ptr TRadixNodeFull](r) return addInner(x.b[k], a, d-8) else: assert(false) -proc incl*(r: var PRadixNode, a: ByteAddress) {.inline.} = +proc incl*(r: var PRadixNode, a: ByteAddress) {.inline.} = discard addInner(r, a, 24) - -proc testOrIncl*(r: var PRadixNode, a: ByteAddress): bool {.inline.} = + +proc testOrIncl*(r: var PRadixNode, a: ByteAddress): bool {.inline.} = return addInner(r, a, 24) - -iterator innerElements(r: PRadixNode): tuple[prefix: int, n: PRadixNode] = + +iterator innerElements(r: PRadixNode): tuple[prefix: int, n: PRadixNode] = if r != nil: - case r.kind - of rnFull: + case r.kind + of rnFull: var r = cast[ptr TRadixNodeFull](r) for i in 0..high(r.b): - if r.b[i] != nil: + if r.b[i] != nil: yield (i, r.b[i]) - of rnLinear: + of rnLinear: var r = cast[ptr TRadixNodeLinear](r) - for i in 0..ze(r.len)-1: + for i in 0..ze(r.len)-1: yield (ze(r.keys[i]), r.vals[i]) else: assert(false) -iterator leafElements(r: PRadixNode): int = +iterator leafElements(r: PRadixNode): int = if r != nil: case r.kind - of rnLeafBits: + of rnLeafBits: var r = cast[ptr TRadixNodeLeafBits](r) # iterate over any bit: - for i in 0..high(r.b): + for i in 0..high(r.b): if r.b[i] != 0: # test all bits for zero - for j in 0..BitsPerUnit-1: - if testBit(r.b[i], j): + for j in 0..BitsPerUnit-1: + if testBit(r.b[i], j): yield i*BitsPerUnit+j - of rnLeafLinear: + of rnLeafLinear: var r = cast[ptr TRadixNodeLeafLinear](r) - for i in 0..ze(r.len)-1: + for i in 0..ze(r.len)-1: yield ze(r.keys[i]) else: assert(false) - -iterator elements*(r: PRadixNode): ByteAddress {.inline.} = - for p1, n1 in innerElements(r): + +iterator elements*(r: PRadixNode): ByteAddress {.inline.} = + for p1, n1 in innerElements(r): for p2, n2 in innerElements(n1): for p3, n3 in innerElements(n2): - for p4 in leafElements(n3): + for p4 in leafElements(n3): yield p1 shl 24 or p2 shl 16 or p3 shl 8 or p4 - + proc main() = const numbers = [128, 1, 2, 3, 4, 255, 17, -8, 45, 19_000] @@ -224,31 +224,31 @@ main() when false: - proc traverse(r: PRadixNode, prefix: int, d: int) = + proc traverse(r: PRadixNode, prefix: int, d: int) = if r == nil: return - case r.kind - of rnLeafBits: + case r.kind + of rnLeafBits: assert(d == 0) var x = cast[ptr TRadixNodeLeafBits](r) # iterate over any bit: - for i in 0..high(x.b): + for i in 0..high(x.b): if x.b[i] != 0: # test all bits for zero - for j in 0..BitsPerUnit-1: - if testBit(x.b[i], j): + for j in 0..BitsPerUnit-1: + if testBit(x.b[i], j): visit(prefix or i*BitsPerUnit+j) - of rnLeafLinear: + of rnLeafLinear: assert(d == 0) var x = cast[ptr TRadixNodeLeafLinear](r) - for i in 0..ze(x.len)-1: + for i in 0..ze(x.len)-1: visit(prefix or ze(x.keys[i])) - of rnFull: + of rnFull: var x = cast[ptr TRadixNodeFull](r) for i in 0..high(r.b): - if r.b[i] != nil: + if r.b[i] != nil: traverse(r.b[i], prefix or (i shl d), d-8) - of rnLinear: + of rnLinear: var x = cast[ptr TRadixNodeLinear](r) - for i in 0..ze(x.len)-1: + for i in 0..ze(x.len)-1: traverse(x.vals[i], prefix or (ze(x.keys[i]) shl d), d-8) type @@ -261,59 +261,59 @@ when false: i.r = r i.x = 0 i.p = 0 - - proc nextr(i: var TRadixIter): PRadixNode = + + proc nextr(i: var TRadixIter): PRadixNode = if i.r == nil: return nil - case i.r.kind - of rnFull: + case i.r.kind + of rnFull: var r = cast[ptr TRadixNodeFull](i.r) while i.x <= high(r.b): - if r.b[i.x] != nil: + if r.b[i.x] != nil: i.p = i.x return r.b[i.x] inc(i.x) - of rnLinear: + of rnLinear: var r = cast[ptr TRadixNodeLinear](i.r) - if i.x < ze(r.len): + if i.x < ze(r.len): i.p = ze(r.keys[i.x]) result = r.vals[i.x] inc(i.x) else: assert(false) - proc nexti(i: var TRadixIter): int = + proc nexti(i: var TRadixIter): int = result = -1 - case i.r.kind - of rnLeafBits: + case i.r.kind + of rnLeafBits: var r = cast[ptr TRadixNodeLeafBits](i.r) - # iterate over any bit: - for i in 0..high(r.b): + # iterate over any bit: + for i in 0..high(r.b): if x.b[i] != 0: # test all bits for zero - for j in 0..BitsPerUnit-1: - if testBit(x.b[i], j): + for j in 0..BitsPerUnit-1: + if testBit(x.b[i], j): visit(prefix or i*BitsPerUnit+j) - of rnLeafLinear: + of rnLeafLinear: var r = cast[ptr TRadixNodeLeafLinear](i.r) - if i.x < ze(r.len): + if i.x < ze(r.len): result = ze(r.keys[i.x]) inc(i.x) - iterator elements(r: PRadixNode): ByteAddress {.inline.} = + iterator elements(r: PRadixNode): ByteAddress {.inline.} = var a, b, c, d: TRadixIter init(a, r) - while true: + while true: var x = nextr(a) - if x != nil: + if x != nil: init(b, x) - while true: + while true: var y = nextr(b) - if y != nil: + if y != nil: init(c, y) while true: var z = nextr(c) - if z != nil: + if z != nil: init(d, z) while true: var q = nexti(d) - if q != -1: + if q != -1: yield a.p shl 24 or b.p shl 16 or c.p shl 8 or q diff --git a/tests/misc/trawstr.nim b/tests/misc/trawstr.nim index ab2aae159..55e508acc 100644 --- a/tests/misc/trawstr.nim +++ b/tests/misc/trawstr.nim @@ -3,10 +3,10 @@ discard """ line: 10 errormsg: "closing \" expected" """ -# Test the new raw strings: - -const - xxx = r"This is a raw string!" - yyy = "This not\" #ERROR +# Test the new raw strings: + +const + xxx = r"This is a raw string!" + yyy = "This not\" #ERROR diff --git a/tests/misc/tromans.nim b/tests/misc/tromans.nim index fa6a63595..132c73ddd 100644 --- a/tests/misc/tromans.nim +++ b/tests/misc/tromans.nim @@ -32,7 +32,7 @@ proc RomanToDecimal(romanVal: string): int = of 'C', 'c': val = 100 of 'D', 'd': val = 500 of 'M', 'm': val = 1000 - else: raiseInvalidValue("Incorrect character in roman numeral! (" & + else: raiseInvalidValue("Incorrect character in roman numeral! (" & $romanVal[i] & ")") if val >= prevVal: inc(result, val) @@ -49,7 +49,7 @@ proc DecimalToRoman(decValParam: int): string = ("M", 1000), ("CM", 900), ("D", 500), ("CD", 400), ("C", 100), ("XC", 90), ("L", 50), ("XL", 40), ("X", 10), ("IX", 9), - ("V", 5), ("IV", 4), ("I", 1)] + ("V", 5), ("IV", 4), ("I", 1)] if decValParam < 1 or decValParam > 3999: raiseInvalidValue("number not representable") result = "" @@ -64,7 +64,7 @@ for i in 1..100: for i in items([1238, 1777, 3830, 2401, 379, 33, 940, 3973]): if RomanToDecimal(DecimalToRoman(i)) != i: quit "BUG" - + echo "success" #OUT success diff --git a/tests/misc/tsimplesort.nim b/tests/misc/tsimplesort.nim index c282b3445..9c6ad1207 100644 --- a/tests/misc/tsimplesort.nim +++ b/tests/misc/tsimplesort.nim @@ -1,7 +1,7 @@ discard """ output: '''true''' """ - + import hashes, math {.pragma: myShallow.} @@ -112,7 +112,7 @@ proc initTable*[A, B](initialSize=64): TTable[A, B] = result.counter = 0 newSeq(result.data, initialSize) -proc toTable*[A, B](pairs: openarray[tuple[key: A, +proc toTable*[A, B](pairs: openarray[tuple[key: A, val: B]]): TTable[A, B] = ## creates a new hash table that contains the given `pairs`. result = initTable[A, B](nextPowerOfTwo(pairs.len+10)) @@ -214,7 +214,7 @@ proc `$`*[A](t: TCountTable[A]): string = ## The `$` operator for count tables. dollarImpl() -proc inc*[A](t: var TCountTable[A], key: A, val = 1) = +proc inc*[A](t: var TCountTable[A], key: A, val = 1) = ## increments `t[key]` by `val`. var index = RawGet(t, key) if index >= 0: diff --git a/tests/misc/tsimtych.nim b/tests/misc/tsimtych.nim index dd969958c..27a922f6a 100644 --- a/tests/misc/tsimtych.nim +++ b/tests/misc/tsimtych.nim @@ -3,10 +3,10 @@ discard """ line: 10 errormsg: "type mismatch: got (bool) but expected \'string\'" """ -# Test 2 -# Simple type checking - -var a: string -a = false #ERROR +# Test 2 +# Simple type checking + +var a: string +a = false #ERROR diff --git a/tests/misc/tsizeof.nim b/tests/misc/tsizeof.nim index f7b70dd4d..4afd48472 100644 --- a/tests/misc/tsizeof.nim +++ b/tests/misc/tsizeof.nim @@ -1,10 +1,10 @@ -# Test the sizeof proc - -type - TMyRecord {.final.} = object - x, y: int - b: bool - r: float - s: string - -write(stdout, sizeof(TMyRecord)) +# Test the sizeof proc + +type + TMyRecord {.final.} = object + x, y: int + b: bool + r: float + s: string + +write(stdout, sizeof(TMyRecord)) diff --git a/tests/misc/tsortdev.nim b/tests/misc/tsortdev.nim index d7d42d22c..f360d9646 100644 --- a/tests/misc/tsortdev.nim +++ b/tests/misc/tsortdev.nim @@ -37,17 +37,17 @@ proc cmpPlatforms(a, b: string): int = else: return system.cmp(a, b) -proc sorted[T](a: openArray[T]): bool = +proc sorted[T](a: openArray[T]): bool = result = true for i in 0 .. < a.high: - if cmpPlatforms(a[i], a[i+1]) > 0: + if cmpPlatforms(a[i], a[i+1]) > 0: echo "Out of order: ", a[i], " ", a[i+1] result = false proc main() = - var testData = @["netbsd-x86_64", "windows-x86", "linux-x86_64", "linux-x86", + var testData = @["netbsd-x86_64", "windows-x86", "linux-x86_64", "linux-x86", "linux-ppc64", "macosx-x86-1058", "macosx-x86-1068"] - + sort(testData, cmpPlatforms) doAssert sorted(testData) diff --git a/tests/misc/tstrace.nim b/tests/misc/tstrace.nim index 3032a34a3..23590d958 100644 --- a/tests/misc/tstrace.nim +++ b/tests/misc/tstrace.nim @@ -1,16 +1,16 @@ -# Test the new stacktraces (great for debugging!) - -{.push stack_trace: on.} - -proc recTest(i: int) = - # enter - if i < 10: - recTest(i+1) - else: # should printStackTrace() - var p: ptr int = nil - p[] = 12 - # leave - -{.pop.} - -recTest(0) +# Test the new stacktraces (great for debugging!) + +{.push stack_trace: on.} + +proc recTest(i: int) = + # enter + if i < 10: + recTest(i+1) + else: # should printStackTrace() + var p: ptr int = nil + p[] = 12 + # leave + +{.pop.} + +recTest(0) diff --git a/tests/misc/tstrange.nim b/tests/misc/tstrange.nim index 8742011bb..fee0f44e4 100644 --- a/tests/misc/tstrange.nim +++ b/tests/misc/tstrange.nim @@ -4,23 +4,23 @@ discard """ 1 2''' """ -# test for extremely strange bug - -proc ack(x: int, y: int): int = - if x != 0: - if y != 5: - return y - return x - return x+y - -proc gen[T](a: T) = - write(stdout, a) - - -gen("hallo") -write(stdout, ack(5, 4)) -#OUT hallo4 - +# test for extremely strange bug + +proc ack(x: int, y: int): int = + if x != 0: + if y != 5: + return y + return x + return x+y + +proc gen[T](a: T) = + write(stdout, a) + + +gen("hallo") +write(stdout, ack(5, 4)) +#OUT hallo4 + # bug #1442 let h=3 for x in 0.. ".}: cint - + proc mmap(adr: pointer, len: int, prot, flags, fildes: cint, off: int): pointer {.header: "".} proc munmap(adr: pointer, len: int) {.header: "".} -proc osAllocPages(size: int): pointer {.inline.} = - result = mmap(nil, size, PROT_READ or PROT_WRITE, +proc osAllocPages(size: int): pointer {.inline.} = + result = mmap(nil, size, PROT_READ or PROT_WRITE, MAP_PRIVATE or MAP_ANONYMOUS, -1, 0) if result == nil or result == cast[pointer](-1): quit 1 - cfprintf(c_stdout, "allocated pages %p..%p\n", result, + cfprintf(c_stdout, "allocated pages %p..%p\n", result, cast[int](result) + size) - + proc osDeallocPages(p: pointer, size: int) {.inline} = cfprintf(c_stdout, "freed pages %p..%p\n", p, cast[int](p) + size) munmap(p, size-1) diff --git a/tests/modules/mnamspc1.nim b/tests/modules/mnamspc1.nim index da13c5f24..91f4d1566 100644 --- a/tests/modules/mnamspc1.nim +++ b/tests/modules/mnamspc1.nim @@ -1,2 +1,2 @@ -import mnamspc2 - +import mnamspc2 + diff --git a/tests/modules/mnamspc2.nim b/tests/modules/mnamspc2.nim index 84ef8533e..899ef27ea 100644 --- a/tests/modules/mnamspc2.nim +++ b/tests/modules/mnamspc2.nim @@ -1,3 +1,3 @@ -# export an identifier: -var - global*: int +# export an identifier: +var + global*: int diff --git a/tests/modules/mopaque.nim b/tests/modules/mopaque.nim index 7eee4bd96..2129bdaf2 100644 --- a/tests/modules/mopaque.nim +++ b/tests/modules/mopaque.nim @@ -1,7 +1,7 @@ -type - TLexer* {.final.} = object - line*: int - filename*: string - buffer: cstring +type + TLexer* {.final.} = object + line*: int + filename*: string + buffer: cstring proc noProcVar*(): int = 18 diff --git a/tests/modules/mrecmod.nim b/tests/modules/mrecmod.nim index fab9654d5..ce8fa3d64 100644 --- a/tests/modules/mrecmod.nim +++ b/tests/modules/mrecmod.nim @@ -1 +1 @@ -import trecmod +import trecmod diff --git a/tests/modules/mrecmod2.nim b/tests/modules/mrecmod2.nim index 9557ce729..31fac6e4d 100644 --- a/tests/modules/mrecmod2.nim +++ b/tests/modules/mrecmod2.nim @@ -1,9 +1,9 @@ # Module B -import trecmod2 +import trecmod2 proc p*(x: trecmod2.T1): trecmod2.T1 = # this works because the compiler has already # added T1 to trecmod2's interface symbol table return x + 1 - + diff --git a/tests/modules/texport.nim b/tests/modules/texport.nim index 9515f9060..0890fb369 100644 --- a/tests/modules/texport.nim +++ b/tests/modules/texport.nim @@ -7,7 +7,7 @@ import mexporta # bug #1029: from rawsockets import accept -# B.TMyObject has been imported implicitly here: +# B.TMyObject has been imported implicitly here: var x: TMyObject echo($x, q(0), q"0") diff --git a/tests/modules/tnamspc.nim b/tests/modules/tnamspc.nim index 1e2049cec..2f488644c 100644 --- a/tests/modules/tnamspc.nim +++ b/tests/modules/tnamspc.nim @@ -3,10 +3,10 @@ discard """ line: 10 errormsg: "undeclared identifier: \'global\'" """ -# Test17 - test correct handling of namespaces - -import mnamspc1 - -global = 9 #ERROR +# Test17 - test correct handling of namespaces + +import mnamspc1 + +global = 9 #ERROR diff --git a/tests/modules/trecmod.nim b/tests/modules/trecmod.nim index 9d39d3ff7..d567e293b 100644 --- a/tests/modules/trecmod.nim +++ b/tests/modules/trecmod.nim @@ -1,2 +1,2 @@ -# recursive module -import mrecmod +# recursive module +import mrecmod diff --git a/tests/namedparams/tnamedparams.nim b/tests/namedparams/tnamedparams.nim index 9397fea4a..9a8bd0c2e 100644 --- a/tests/namedparams/tnamedparams.nim +++ b/tests/namedparams/tnamedparams.nim @@ -6,9 +6,9 @@ discard """ import pegs discard parsePeg( - input = "input", - filename = "filename", - line = 1, + input = "input", + filename = "filename", + line = 1, col = 23) diff --git a/tests/namedparams/tnamedparams2.nim b/tests/namedparams/tnamedparams2.nim index 4b0cd5361..fcbbd32da 100644 --- a/tests/namedparams/tnamedparams2.nim +++ b/tests/namedparams/tnamedparams2.nim @@ -1,8 +1,8 @@ import pegs discard parsePeg( - pattern = "input", - filename = "filename", - line = 1, + pattern = "input", + filename = "filename", + line = 1, col = 23) diff --git a/tests/notnil/tnotnil.nim b/tests/notnil/tnotnil.nim index fba7fa917..f65634ed6 100644 --- a/tests/notnil/tnotnil.nim +++ b/tests/notnil/tnotnil.nim @@ -7,7 +7,7 @@ type PObj = ref TObj not nil TObj = object x: int - + MyString = string not nil #var x: PObj = nil diff --git a/tests/notnil/tnotnil1.nim b/tests/notnil/tnotnil1.nim index 863fe45f8..73472752c 100644 --- a/tests/notnil/tnotnil1.nim +++ b/tests/notnil/tnotnil1.nim @@ -18,7 +18,7 @@ proc q(s: superstring) = echo s proc p2() = - var a: string = "I am not nil" + var a: string = "I am not nil" q(a) # but this should and does not p2() @@ -30,7 +30,7 @@ proc p() = var x: pointer if not x.isNil: q(x) - + let y = x if not y.isNil: q(y) diff --git a/tests/notnil/tnotnil_in_generic.nim b/tests/notnil/tnotnil_in_generic.nim index 1e2d8b940..357ab2c7c 100644 --- a/tests/notnil/tnotnil_in_generic.nim +++ b/tests/notnil/tnotnil_in_generic.nim @@ -9,14 +9,14 @@ type x: int ud: T -proc good[T](p: A[T]) = +proc good[T](p: A[T]) = discard -proc bad[T](p: A[T] not nil) = +proc bad[T](p: A[T] not nil) = discard -proc go() = +proc go() = let s = A[int](x: 1) good(s) diff --git a/tests/objects/tobjcov.nim b/tests/objects/tobjcov.nim index 8391727f2..cf2e5becf 100644 --- a/tests/objects/tobjcov.nim +++ b/tests/objects/tobjcov.nim @@ -5,10 +5,10 @@ type a: int TB = object of TA b: array[0..5000_000, int] - + proc ap(x: var TA) = x.a = -1 proc bp(x: var TB) = x.b[high(x.b)] = -1 - + # in Nim proc (x: TB) is compatible to proc (x: TA), # but this is not type safe: var f = cast[proc (x: var TA) {.nimcall.}](bp) diff --git a/tests/objects/tobject.nim b/tests/objects/tobject.nim index 5fec84441..cdb8f80db 100644 --- a/tests/objects/tobject.nim +++ b/tests/objects/tobject.nim @@ -3,7 +3,7 @@ import unittest type Obj = object foo: int -proc makeObj(x: int): Obj = +proc makeObj(x: int): Obj = result.foo = x suite "object basic methods": diff --git a/tests/objects/tobject3.nim b/tests/objects/tobject3.nim index 85cf1cfe3..2d9c8d023 100644 --- a/tests/objects/tobject3.nim +++ b/tests/objects/tobject3.nim @@ -4,7 +4,7 @@ type TFoo = ref object of RootObj - Data: int + Data: int TBar = ref object of TFoo nil TBar2 = ref object of TBar diff --git a/tests/objects/tobjects.nim b/tests/objects/tobjects.nim index 06fa15583..2f46b46b5 100644 --- a/tests/objects/tobjects.nim +++ b/tests/objects/tobjects.nim @@ -18,7 +18,7 @@ type of 0: arg: char of 1: s: string else: wtf: bool - + var x: TMyObject diff --git a/tests/objects/tobjpragma.nim b/tests/objects/tobjpragma.nim index dda8057b6..0a6cc893b 100644 --- a/tests/objects/tobjpragma.nim +++ b/tests/objects/tobjpragma.nim @@ -12,7 +12,7 @@ discard """ # Disabled since some versions of GCC ignore the 'packed' attribute -# Test +# Test type Foo {.packed.} = object @@ -21,12 +21,12 @@ type Bar {.packed.} = object a: int8 - b: int16 - + b: int16 + Daz {.packed.} = object a: int32 - b: int8 - c: int32 + b: int8 + c: int32 var f = Foo(a: 1, b: 1) diff --git a/tests/objects/tofopr.nim b/tests/objects/tofopr.nim index 961d81bd3..ab2854571 100644 --- a/tests/objects/tofopr.nim +++ b/tests/objects/tofopr.nim @@ -8,12 +8,12 @@ type TMyType = object {.inheritable.} len: int data: string - + TOtherType = object of TMyType - -proc p(x: TMyType): bool = + +proc p(x: TMyType): bool = return x of TOtherType - + var m: TMyType n: TOtherType diff --git a/tests/objects/toop.nim b/tests/objects/toop.nim index 0b42c2c22..ebc59f637 100644 --- a/tests/objects/toop.nim +++ b/tests/objects/toop.nim @@ -5,13 +5,13 @@ discard """ type TA = object of TObject x, y: int - + TB = object of TA z: int - + TC = object of TB whatever: string - + proc p(a: var TA) = echo "a" proc p(b: var TB) = echo "b" diff --git a/tests/objvariant/tcheckedfield1.nim b/tests/objvariant/tcheckedfield1.nim index 1963ceb8d..56d784a2b 100644 --- a/tests/objvariant/tcheckedfield1.nim +++ b/tests/objvariant/tcheckedfield1.nim @@ -15,7 +15,7 @@ type case k: TNodeKind of nkBinary, nkTernary: a, b: PNode of nkStr: s: string - + PList = ref object data: string next: PList @@ -52,7 +52,7 @@ proc toString3(x: PNode): string = proc p() = var x: PNode = PNode(k: nkStr, s: "abc") - + let y = x if not y.isNil: echo toString(y), " ", toString2(y) diff --git a/tests/osproc/ta.nim b/tests/osproc/ta.nim index 6c1495590..5ebcc7f14 100644 --- a/tests/osproc/ta.nim +++ b/tests/osproc/ta.nim @@ -1,3 +1,3 @@ import strutils let x = stdin.readLine() -echo x.parseInt + 5 \ No newline at end of file +echo x.parseInt + 5 diff --git a/tests/overflw/tovfint.nim b/tests/overflw/tovfint.nim index f0b1ccaa6..f775d2e1c 100644 --- a/tests/overflw/tovfint.nim +++ b/tests/overflw/tovfint.nim @@ -2,22 +2,22 @@ discard """ file: "tovfint.nim" output: "works!" """ -# this tests the new overflow literals - -var - i: int -i = int(0xffffffff'i32) -when defined(cpu64): - if i == -1: - write(stdout, "works!\n") - else: - write(stdout, "broken!\n") -else: - if i == -1: - write(stdout, "works!\n") - else: - write(stdout, "broken!\n") - -#OUT works! +# this tests the new overflow literals + +var + i: int +i = int(0xffffffff'i32) +when defined(cpu64): + if i == -1: + write(stdout, "works!\n") + else: + write(stdout, "broken!\n") +else: + if i == -1: + write(stdout, "works!\n") + else: + write(stdout, "broken!\n") + +#OUT works! diff --git a/tests/overload/toverl2.nim b/tests/overload/toverl2.nim index ea0249e9f..54714ac1b 100644 --- a/tests/overload/toverl2.nim +++ b/tests/overload/toverl2.nim @@ -9,9 +9,9 @@ import strutils proc toverl2(x: int): string = return $x proc toverl2(x: bool): string = return $x -iterator toverl2(x: int): int = +iterator toverl2(x: int): int = var res = 0 - while res < x: + while res < x: yield res inc(res) @@ -20,7 +20,7 @@ var stdout.write(pp(true)) -for x in toverl2(3): +for x in toverl2(3): stdout.write(toverl2(x)) block: diff --git a/tests/overload/toverl3.nim b/tests/overload/toverl3.nim index b3e0f2fa7..92cfc150d 100644 --- a/tests/overload/toverl3.nim +++ b/tests/overload/toverl3.nim @@ -4,8 +4,8 @@ discard """ tup1''' """ -# Tests more specific generic match: - +# Tests more specific generic match: + proc m[T](x: T) = echo "m2" proc m[T](x: var ref T) = echo "m1" @@ -15,6 +15,6 @@ proc tup[S, T](x: tuple[a: S, b: T]) = echo "tup2" var obj: ref int tu: tuple[a: int, b: ref bool] - + m(obj) tup(tu) diff --git a/tests/overload/toverl4.nim b/tests/overload/toverl4.nim index 6bb3a53d1..b63265bdf 100644 --- a/tests/overload/toverl4.nim +++ b/tests/overload/toverl4.nim @@ -74,4 +74,4 @@ proc add*[TKey, TData](root: var PElement[TKey, TData], key: TKey, data: TData) var tree = PElement[int, int](kind: ElementKind.inner, key: 0, left: nil, right: nil) let result = add(tree, 1, 1) -echo(result) \ No newline at end of file +echo(result) diff --git a/tests/overload/toverwr.nim b/tests/overload/toverwr.nim index 32d50faaa..5945a6149 100644 --- a/tests/overload/toverwr.nim +++ b/tests/overload/toverwr.nim @@ -1,13 +1,13 @@ -discard """ - file: "toverwr.nim" - output: "hello" -""" -# Test the overloading resolution in connection with a qualifier - -proc write(t: TFile, s: string) = - discard # a nop - -system.write(stdout, "hello") -#OUT hello - - +discard """ + file: "toverwr.nim" + output: "hello" +""" +# Test the overloading resolution in connection with a qualifier + +proc write(t: TFile, s: string) = + discard # a nop + +system.write(stdout, "hello") +#OUT hello + + diff --git a/tests/parallel/treadafterwrite.nim b/tests/parallel/treadafterwrite.nim index f59ad5ae0..12eb31402 100644 --- a/tests/parallel/treadafterwrite.nim +++ b/tests/parallel/treadafterwrite.nim @@ -12,7 +12,7 @@ type BoxedFloat = object value: float -proc term(k: float): ptr BoxedFloat = +proc term(k: float): ptr BoxedFloat = var temp = 4 * math.pow(-1, k) / (2*k + 1) result = cast[ptr BoxedFloat](allocShared(sizeof(BoxedFloat))) result.value = temp diff --git a/tests/parallel/tuseafterdef.nim b/tests/parallel/tuseafterdef.nim index 95123e886..833c72a0a 100644 --- a/tests/parallel/tuseafterdef.nim +++ b/tests/parallel/tuseafterdef.nim @@ -7,11 +7,11 @@ discard """ import strutils, math, threadpool -type +type BoxedFloat = object value: float -proc term(k: float): ptr BoxedFloat = +proc term(k: float): ptr BoxedFloat = var temp = 4 * math.pow(-1, k) / (2*k + 1) result = cast[ptr BoxedFloat](allocShared(sizeof(BoxedFloat))) result.value = temp diff --git a/tests/parser/tdomulttest.nim b/tests/parser/tdomulttest.nim index 4ee6de128..418192ac8 100644 --- a/tests/parser/tdomulttest.nim +++ b/tests/parser/tdomulttest.nim @@ -14,4 +14,4 @@ do (x: int) -> int: echo("multi lines") return x -echo("end") \ No newline at end of file +echo("end") diff --git a/tests/parser/tinvwhen.nim b/tests/parser/tinvwhen.nim index 5ff94cc6c..99701bdf5 100644 --- a/tests/parser/tinvwhen.nim +++ b/tests/parser/tinvwhen.nim @@ -3,13 +3,13 @@ discard """ line: 11 errormsg: "invalid indentation" """ -# This was parsed even though it should not! - -proc chdir(path: cstring): cint {.importc: "chdir", header: "dirHeader".} - -proc getcwd(buf: cstring, buflen: cint): cstring - when defined(unix): {.importc: "getcwd", header: "".} #ERROR_MSG invalid indentation - elif defined(windows): {.importc: "getcwd", header: ""} - else: {.error: "os library not ported to your OS. Please help!".} +# This was parsed even though it should not! + +proc chdir(path: cstring): cint {.importc: "chdir", header: "dirHeader".} + +proc getcwd(buf: cstring, buflen: cint): cstring + when defined(unix): {.importc: "getcwd", header: "".} #ERROR_MSG invalid indentation + elif defined(windows): {.importc: "getcwd", header: ""} + else: {.error: "os library not ported to your OS. Please help!".} diff --git a/tests/parser/toprprec.nim b/tests/parser/toprprec.nim index ce33934b5..2c22f5b80 100644 --- a/tests/parser/toprprec.nim +++ b/tests/parser/toprprec.nim @@ -2,7 +2,7 @@ discard """ file: "toprprec.nim" output: "done" """ -# Test operator precedence: +# Test operator precedence: template `@` (x: expr): expr {.immediate.} = self.x template `@!` (x: expr): expr {.immediate.} = x @@ -12,7 +12,7 @@ type TO = object x: int TA = tuple[a, b: int, obj: TO] - + proc init(self: var TA): string = @a = 3 === @b = 4 @@ -22,10 +22,10 @@ proc init(self: var TA): string = assert 3+5*5-2 == 28- -26-28 -proc `^-` (x, y: int): int = +proc `^-` (x, y: int): int = # now right-associative! result = x - y - + assert 34 ^- 6 ^- 2 == 30 assert 34 - 6 - 2 == 26 diff --git a/tests/pragmas/tpush.nim b/tests/pragmas/tpush.nim index 5fb411a79..5ecfe9704 100644 --- a/tests/pragmas/tpush.nim +++ b/tests/pragmas/tpush.nim @@ -1,15 +1,15 @@ -# test the new pragmas - -{.push warnings: off, hints: off.} -proc noWarning() = - var - x: int - echo(x) - -{.pop.} - -proc WarnMe() = - var - x: int - echo(x) - +# test the new pragmas + +{.push warnings: off, hints: off.} +proc noWarning() = + var + x: int + echo(x) + +{.pop.} + +proc WarnMe() = + var + x: int + echo(x) + diff --git a/tests/proc/tnestprc.nim b/tests/proc/tnestprc.nim index c10ad6abf..9b3c33d5e 100644 --- a/tests/proc/tnestprc.nim +++ b/tests/proc/tnestprc.nim @@ -4,12 +4,12 @@ discard """ """ # Test nested procs without closures -proc Add3(x: int): int = - proc add(x, y: int): int {.noconv.} = +proc Add3(x: int): int = + proc add(x, y: int): int {.noconv.} = result = x + y - + result = add(x, 3) - + echo Add3(7) #OUT 10 diff --git a/tests/procvar/tprocvar.nim b/tests/procvar/tprocvar.nim index 56f76c613..f523aa391 100644 --- a/tests/procvar/tprocvar.nim +++ b/tests/procvar/tprocvar.nim @@ -13,6 +13,6 @@ proc huh(x, y: var int) = proc so(c: TCallback) = c(2, 4) - + so(huh) diff --git a/tests/procvar/tprocvar2.nim b/tests/procvar/tprocvar2.nim index 237e2ef7a..a590bc4bd 100644 --- a/tests/procvar/tprocvar2.nim +++ b/tests/procvar/tprocvar2.nim @@ -2,7 +2,7 @@ discard """ file: "tprocvar.nim" output: "papbpcpdpe7" """ -# test variables of type proc +# test variables of type proc proc pa() {.cdecl.} = write(stdout, "pa") proc pb() {.cdecl.} = write(stdout, "pb") @@ -12,21 +12,21 @@ proc pe() {.cdecl.} = write(stdout, "pe") const algos = [pa, pb, pc, pd, pe] - -var - x: proc (a, b: int): int {.cdecl.} - -proc ha(c, d: int): int {.cdecl.} = - echo(c + d) - result = c + d + +var + x: proc (a, b: int): int {.cdecl.} + +proc ha(c, d: int): int {.cdecl.} = + echo(c + d) + result = c + d for a in items(algos): a() - -x = ha -discard x(3, 4) - -#OUT papbpcpdpe7 - + +x = ha +discard x(3, 4) + +#OUT papbpcpdpe7 + diff --git a/tests/range/tbug499771.nim b/tests/range/tbug499771.nim index 682148422..1504a2ad7 100644 --- a/tests/range/tbug499771.nim +++ b/tests/range/tbug499771.nim @@ -3,11 +3,11 @@ discard """ output: '''TSubRange: 5 from 1 to 10 true true true''' """ -type +type TSubRange = range[1 .. 10] TEnum = enum A, B, C var sr: TSubRange = 5 -echo("TSubRange: " & $sr & " from " & $low(TSubRange) & " to " & +echo("TSubRange: " & $sr & " from " & $low(TSubRange) & " to " & $high(TSubRange)) const cset = {A} + {B} diff --git a/tests/range/tcolors.nim b/tests/range/tcolors.nim index 9d1034405..ab5b3e199 100644 --- a/tests/range/tcolors.nim +++ b/tests/range/tcolors.nim @@ -3,7 +3,7 @@ import strutils type TColor = distinct int32 -proc rgb(r, g, b: range[0..255]): TColor = +proc rgb(r, g, b: range[0..255]): TColor = result = TColor(r or g shl 8 or b shl 16) proc `$`(c: TColor): string = @@ -15,25 +15,25 @@ when false: type TColor = distinct int32 TColorComponent = distinct int8 - - proc red(a: TColor): TColorComponent = + + proc red(a: TColor): TColorComponent = result = TColorComponent(int32(a) and 0xff'i32) - - proc green(a: TColor): TColorComponent = + + proc green(a: TColor): TColorComponent = result = TColorComponent(int32(a) shr 8'i32 and 0xff'i32) - - proc blue(a: TColor): TColorComponent = + + proc blue(a: TColor): TColorComponent = result = TColorComponent(int32(a) shr 16'i32 and 0xff'i32) - - proc rgb(r, g, b: range[0..255]): TColor = + + proc rgb(r, g, b: range[0..255]): TColor = result = TColor(r or g shl 8 or b shl 8) - - proc `+!` (a, b: TColorComponent): TColorComponent = + + proc `+!` (a, b: TColorComponent): TColorComponent = ## saturated arithmetic: result = TColorComponent(min(ze(int8(a)) + ze(int8(b)), 255)) - - proc `+` (a, b: TColor): TColor = + + proc `+` (a, b: TColor): TColor = ## saturated arithmetic for colors makes sense, I think: return rgb(red(a) +! red(b), green(a) +! green(b), blue(a) +! blue(b)) - + rgb(34, 55, 255) diff --git a/tests/range/tmatrix3.nim b/tests/range/tmatrix3.nim index 80d38d63d..fe666b0d8 100644 --- a/tests/range/tmatrix3.nim +++ b/tests/range/tmatrix3.nim @@ -10,11 +10,11 @@ discard """ include compilehelpers type - Matrix*[M, N, T] = object + Matrix*[M, N, T] = object aij*: array[M, array[N, T]] - + Matrix2*[T] = Matrix[range[0..1], range[0..1], T] - + Matrix3*[T] = Matrix[range[0..2], range[0..2], T] proc mn(x: Matrix): Matrix.T = x.aij[0][0] @@ -23,7 +23,7 @@ proc m2(x: Matrix2): Matrix2.T = x.aij[0][0] proc m3(x: Matrix3): auto = x.aij[0][0] -var +var matn: Matrix[range[0..3], range[0..2], int] mat2: Matrix2[int] mat3: Matrix3[float] diff --git a/tests/range/tsubrange.nim b/tests/range/tsubrange.nim index b4a333bf3..6f88c5a22 100644 --- a/tests/range/tsubrange.nim +++ b/tests/range/tsubrange.nim @@ -5,10 +5,10 @@ discard """ type TRange = range[0..40] - + proc p(r: TRange) = nil - + var r: TRange y = 50 @@ -18,4 +18,4 @@ p y const myConst: TRange = 60 - + diff --git a/tests/range/tsubrange2.nim b/tests/range/tsubrange2.nim index 759d16b9c..7097faed2 100644 --- a/tests/range/tsubrange2.nim +++ b/tests/range/tsubrange2.nim @@ -6,12 +6,12 @@ discard """ type TRange = range[0..40] - + proc p(r: TRange) = discard - + var r: TRange y = 50 p y - + diff --git a/tests/range/tsubrange3.nim b/tests/range/tsubrange3.nim index 600161cfd..f5bb2f161 100644 --- a/tests/range/tsubrange3.nim +++ b/tests/range/tsubrange3.nim @@ -6,10 +6,10 @@ discard """ type TRange = range[0..40] - + proc p(r: TRange) = discard - + var r: TRange y = 50 diff --git a/tests/rectest.nim b/tests/rectest.nim index f08306cfd..54815e1f6 100644 --- a/tests/rectest.nim +++ b/tests/rectest.nim @@ -1,6 +1,6 @@ -# Test the error message - -proc main() = - main() - -main() +# Test the error message + +proc main() = + main() + +main() diff --git a/tests/rodfiles/amethods.nim b/tests/rodfiles/amethods.nim index c51d27d24..ecd36d491 100644 --- a/tests/rodfiles/amethods.nim +++ b/tests/rodfiles/amethods.nim @@ -4,7 +4,7 @@ type proc newBaseClass*: ref TBaseClass = new result - + method echoType*(x: ref TBaseClass) = echo "base class" diff --git a/tests/rodfiles/bmethods.nim b/tests/rodfiles/bmethods.nim index 995942ad6..c77941e4a 100644 --- a/tests/rodfiles/bmethods.nim +++ b/tests/rodfiles/bmethods.nim @@ -12,7 +12,7 @@ type proc newDerivedClass: ref TDerivedClass = new result - + method echoType*(x: ref TDerivedClass) = echo "derived class" diff --git a/tests/rodfiles/bmethods2.nim b/tests/rodfiles/bmethods2.nim index ac24a2201..c9d25eee4 100644 --- a/tests/rodfiles/bmethods2.nim +++ b/tests/rodfiles/bmethods2.nim @@ -12,7 +12,7 @@ type proc newDerivedClass: ref TDerivedClass = new result - + method echoType*(x: ref TDerivedClass) = echo "derived class 2" diff --git a/tests/rodfiles/deadg.nim b/tests/rodfiles/deadg.nim index 97bfbed4f..587608e14 100644 --- a/tests/rodfiles/deadg.nim +++ b/tests/rodfiles/deadg.nim @@ -3,8 +3,8 @@ proc p1*(x, y: int): int = result = x + y - + proc p2*(x, y: string): string = result = x & y - + diff --git a/tests/rodfiles/gtkex1.nim b/tests/rodfiles/gtkex1.nim index 8f4db4a40..156ba5322 100644 --- a/tests/rodfiles/gtkex1.nim +++ b/tests/rodfiles/gtkex1.nim @@ -1,14 +1,14 @@ -import - cairo, glib2, gtk2 - -proc destroy(widget: pWidget, data: pgpointer) {.cdecl.} = - main_quit() - -var - window: pWidget -nimrod_init() -window = window_new(WINDOW_TOPLEVEL) -discard signal_connect(window, "destroy", - SIGNAL_FUNC(gtkex1.destroy), nil) -show(window) -main() +import + cairo, glib2, gtk2 + +proc destroy(widget: pWidget, data: pgpointer) {.cdecl.} = + main_quit() + +var + window: pWidget +nimrod_init() +window = window_new(WINDOW_TOPLEVEL) +discard signal_connect(window, "destroy", + SIGNAL_FUNC(gtkex1.destroy), nil) +show(window) +main() diff --git a/tests/rodfiles/gtkex2.nim b/tests/rodfiles/gtkex2.nim index 3d181ba12..70926bd50 100644 --- a/tests/rodfiles/gtkex2.nim +++ b/tests/rodfiles/gtkex2.nim @@ -1,11 +1,11 @@ -import +import glib2, gtk2 -proc destroy(widget: pWidget, data: pgpointer){.cdecl.} = +proc destroy(widget: pWidget, data: pgpointer){.cdecl.} = main_quit() -var +var window: PWidget button: PWidget @@ -14,7 +14,7 @@ window = window_new(WINDOW_TOPLEVEL) button = button_new("Click me") set_border_width(PContainer(Window), 5) add(PContainer(window), button) -discard signal_connect(window, "destroy", +discard signal_connect(window, "destroy", SIGNAL_FUNC(gtkex2.destroy), nil) show(button) show(window) diff --git a/tests/rodfiles/hallo2.nim b/tests/rodfiles/hallo2.nim index a4b3957ec..40fe64cfd 100644 --- a/tests/rodfiles/hallo2.nim +++ b/tests/rodfiles/hallo2.nim @@ -12,6 +12,6 @@ type proc newNode(data: string): ref TNode = new(result) result.data = data - + echo newNode("Hello World").data diff --git a/tests/seq/tseq2.nim b/tests/seq/tseq2.nim index e1271964c..5de9402ec 100644 --- a/tests/seq/tseq2.nim +++ b/tests/seq/tseq2.nim @@ -1,10 +1,10 @@ -proc `*` *(a, b: seq[int]): seq[int] = +proc `*` *(a, b: seq[int]): seq[int] = # allocate a new sequence: newSeq(result, len(a)) # multiply two int sequences: for i in 0..len(a)-1: result[i] = a[i] * b[i] -when isMainModule: +when isMainModule: # test the new ``*`` operator for sequences: assert(@[1, 2, 3] * @[1, 2, 3] == @[1, 4, 9]) diff --git a/tests/seq/tseqcon.nim b/tests/seq/tseqcon.nim index 6e0a5b56d..902ac3485 100644 --- a/tests/seq/tseqcon.nim +++ b/tests/seq/tseqcon.nim @@ -2,50 +2,50 @@ discard """ file: "tseqcon.nim" output: "Hithere, what\'s your name?Hathere, what\'s your name?" """ -# Test the add proc for sequences and strings - -const - nestedFixed = true - -type - TRec {.final.} = object - x, y: int - s: string - seq: seq[string] - TRecSeq = seq[TRec] - -proc test() = - var s, b: seq[string] - s = @[] - add(s, "Hi") - add(s, "there, ") - add(s, "what's your name?") - - b = s # deep copying here! - b[0][1] = 'a' - - for i in 0 .. len(s)-1: - write(stdout, s[i]) - for i in 0 .. len(b)-1: - write(stdout, b[i]) - - -when nestedFixed: - proc nested() = - var - s: seq[seq[string]] - for i in 0..10_000: # test if the garbage collector - # now works with sequences - s = @[ - @["A", "B", "C", "D"], - @["E", "F", "G", "H"], - @["I", "J", "K", "L"], - @["M", "N", "O", "P"]] - -test() -when nestedFixed: - nested() - -#OUT Hithere, what's your name?Hathere, what's your name? +# Test the add proc for sequences and strings + +const + nestedFixed = true + +type + TRec {.final.} = object + x, y: int + s: string + seq: seq[string] + TRecSeq = seq[TRec] + +proc test() = + var s, b: seq[string] + s = @[] + add(s, "Hi") + add(s, "there, ") + add(s, "what's your name?") + + b = s # deep copying here! + b[0][1] = 'a' + + for i in 0 .. len(s)-1: + write(stdout, s[i]) + for i in 0 .. len(b)-1: + write(stdout, b[i]) + + +when nestedFixed: + proc nested() = + var + s: seq[seq[string]] + for i in 0..10_000: # test if the garbage collector + # now works with sequences + s = @[ + @["A", "B", "C", "D"], + @["E", "F", "G", "H"], + @["I", "J", "K", "L"], + @["M", "N", "O", "P"]] + +test() +when nestedFixed: + nested() + +#OUT Hithere, what's your name?Hathere, what's your name? diff --git a/tests/seq/tseqtuple.nim b/tests/seq/tseqtuple.nim index 7ef92f7f1..a0102c9ef 100644 --- a/tests/seq/tseqtuple.nim +++ b/tests/seq/tseqtuple.nim @@ -6,7 +6,7 @@ discard """ type TMsg = tuple[ file: string, - line: int, + line: int, msg: string, err: bool] diff --git a/tests/seq/ttoseq.nim b/tests/seq/ttoseq.nim index 34cc4824b..33de59538 100644 --- a/tests/seq/ttoseq.nim +++ b/tests/seq/ttoseq.nim @@ -4,9 +4,9 @@ discard """ import sequtils -for x in toSeq(countup(2, 6)): +for x in toSeq(countup(2, 6)): stdout.write(x) -for x in items(toSeq(countup(2, 6))): +for x in items(toSeq(countup(2, 6))): stdout.write(x) import strutils diff --git a/tests/sets/tsets.nim b/tests/sets/tsets.nim index 2d37e893d..53a955af8 100644 --- a/tests/sets/tsets.nim +++ b/tests/sets/tsets.nim @@ -1,204 +1,204 @@ -discard """ - file: "tsets.nim" - output: '''Ha ein F ist in s! -false''' -""" -# Test the handling of sets - -import - strutils - -proc testSets(s: var set[char]) = - s = {'A', 'B', 'C', 'E'..'G'} + {'Z'} + s - -# test sets if the first element is different from 0: -type - TAZ = range['a'..'z'] - TAZset = set[TAZ] - - TTokType* = enum - tkInvalid, tkEof, - tkSymbol, - tkAddr, tkAnd, tkAs, tkAsm, tkBlock, tkBreak, tkCase, tkCast, tkConst, - tkContinue, tkConverter, tkDiscard, tkDiv, tkElif, tkElse, tkEnd, tkEnum, - tkExcept, tkException, tkFinally, tkFor, tkFrom, tkGeneric, tkIf, tkImplies, - tkImport, tkIn, tkInclude, tkIs, tkIsnot, tkIterator, tkLambda, tkMacro, - tkMethod, tkMod, tkNil, tkNot, tkNotin, tkObject, tkOf, tkOr, tkOut, tkProc, - tkPtr, tkRaise, tkRecord, tkRef, tkReturn, tkShl, tkShr, tkTemplate, tkTry, - tkType, tkVar, tkWhen, tkWhere, tkWhile, tkWith, tkWithout, tkXor, tkYield, - tkIntLit, tkInt8Lit, tkInt16Lit, tkInt32Lit, tkInt64Lit, tkFloatLit, - tkFloat32Lit, tkFloat64Lit, tkStrLit, tkRStrLit, tkTripleStrLit, tkCharLit, - tkRCharLit, tkParLe, tkParRi, tkBracketLe, tkBracketRi, tkCurlyLe, - tkCurlyRi, tkBracketDotLe, tkBracketDotRi, - tkCurlyDotLe, tkCurlyDotRi, - tkParDotLe, tkParDotRi, - tkComma, tkSemiColon, tkColon, tkEquals, tkDot, tkDotDot, tkHat, tkOpr, - tkComment, tkAccent, tkInd, tkSad, tkDed, - tkSpaces, tkInfixOpr, tkPrefixOpr, tkPostfixOpr - TTokTypeRange = range[tkSymbol..tkDed] - TTokTypes* = set[TTokTypeRange] - -const - toktypes: TTokTypes = {TTokTypeRange(tkSymbol)..pred(tkIntLit), - tkStrLit..tkTripleStrLit} - -var - s: set[char] - a: TAZset -s = {'0'..'9'} -testSets(s) -if 'F' in s: write(stdout, "Ha ein F ist in s!\n") -else: write(stdout, "BUG: F ist nicht in s!\n") -a = {} #{'a'..'z'} -for x in low(TAZ) .. high(TAZ): - incl(a, x) - if x in a: discard - else: write(stdout, "BUG: something not in a!\n") - -for x in low(TTokTypeRange) .. high(TTokTypeRange): - if x in tokTypes: - discard - #writeLine(stdout, "the token '$1' is in the set" % repr(x)) - -#OUT Ha ein F ist in s! - - -type - TMsgKind* = enum - errUnknown, errIllFormedAstX, errInternal, errCannotOpenFile, errGenerated, - errXCompilerDoesNotSupportCpp, errStringLiteralExpected, - errIntLiteralExpected, errInvalidCharacterConstant, - errClosingTripleQuoteExpected, errClosingQuoteExpected, - errTabulatorsAreNotAllowed, errInvalidToken, errLineTooLong, - errInvalidNumber, errNumberOutOfRange, errNnotAllowedInCharacter, - errClosingBracketExpected, errMissingFinalQuote, errIdentifierExpected, - errNewlineExpected, - errInvalidModuleName, - errOperatorExpected, errTokenExpected, errStringAfterIncludeExpected, - errRecursiveDependencyX, errOnOrOffExpected, errNoneSpeedOrSizeExpected, - errInvalidPragma, errUnknownPragma, errInvalidDirectiveX, - errAtPopWithoutPush, errEmptyAsm, errInvalidIndentation, - errExceptionExpected, errExceptionAlreadyHandled, - errYieldNotAllowedHere, errYieldNotAllowedInTryStmt, - errInvalidNumberOfYieldExpr, errCannotReturnExpr, errAttemptToRedefine, - errStmtInvalidAfterReturn, errStmtExpected, errInvalidLabel, - errInvalidCmdLineOption, errCmdLineArgExpected, errCmdLineNoArgExpected, - errInvalidVarSubstitution, errUnknownVar, errUnknownCcompiler, - errOnOrOffExpectedButXFound, errNoneBoehmRefcExpectedButXFound, - errNoneSpeedOrSizeExpectedButXFound, errGuiConsoleOrLibExpectedButXFound, - errUnknownOS, errUnknownCPU, errGenOutExpectedButXFound, - errArgsNeedRunOption, errInvalidMultipleAsgn, errColonOrEqualsExpected, - errExprExpected, errUndeclaredIdentifier, errUseQualifier, errTypeExpected, - errSystemNeeds, errExecutionOfProgramFailed, errNotOverloadable, - errInvalidArgForX, errStmtHasNoEffect, errXExpectsTypeOrValue, - errXExpectsArrayType, errIteratorCannotBeInstantiated, errExprXAmbiguous, - errConstantDivisionByZero, errOrdinalTypeExpected, - errOrdinalOrFloatTypeExpected, errOverOrUnderflow, - errCannotEvalXBecauseIncompletelyDefined, errChrExpectsRange0_255, - errDynlibRequiresExportc, errUndeclaredFieldX, errNilAccess, - errIndexOutOfBounds, errIndexTypesDoNotMatch, errBracketsInvalidForType, - errValueOutOfSetBounds, errFieldInitTwice, errFieldNotInit, - errExprXCannotBeCalled, errExprHasNoType, errExprXHasNoType, - errCastNotInSafeMode, errExprCannotBeCastedToX, errCommaOrParRiExpected, - errCurlyLeOrParLeExpected, errSectionExpected, errRangeExpected, - errMagicOnlyInSystem, errPowerOfTwoExpected, - errStringMayNotBeEmpty, errCallConvExpected, errProcOnlyOneCallConv, - errSymbolMustBeImported, errExprMustBeBool, errConstExprExpected, - errDuplicateCaseLabel, errRangeIsEmpty, errSelectorMustBeOfCertainTypes, - errSelectorMustBeOrdinal, errOrdXMustNotBeNegative, errLenXinvalid, - errWrongNumberOfVariables, errExprCannotBeRaised, errBreakOnlyInLoop, - errTypeXhasUnknownSize, errConstNeedsConstExpr, errConstNeedsValue, - errResultCannotBeOpenArray, errSizeTooBig, errSetTooBig, - errBaseTypeMustBeOrdinal, errInheritanceOnlyWithNonFinalObjects, - errInheritanceOnlyWithEnums, errIllegalRecursionInTypeX, - errCannotInstantiateX, errExprHasNoAddress, errXStackEscape, - errVarForOutParamNeeded, - errPureTypeMismatch, errTypeMismatch, errButExpected, errButExpectedX, - errAmbiguousCallXYZ, errWrongNumberOfArguments, - errXCannotBePassedToProcVar, - errXCannotBeInParamDecl, errPragmaOnlyInHeaderOfProc, errImplOfXNotAllowed, - errImplOfXexpected, errNoSymbolToBorrowFromFound, errDiscardValueX, - errInvalidDiscard, errIllegalConvFromXtoY, errCannotBindXTwice, - errInvalidOrderInArrayConstructor, - errInvalidOrderInEnumX, errEnumXHasHoles, errExceptExpected, errInvalidTry, - errOptionExpected, errXisNoLabel, errNotAllCasesCovered, - errUnknownSubstitionVar, errComplexStmtRequiresInd, errXisNotCallable, - errNoPragmasAllowedForX, errNoGenericParamsAllowedForX, - errInvalidParamKindX, errDefaultArgumentInvalid, errNamedParamHasToBeIdent, - errNoReturnTypeForX, errConvNeedsOneArg, errInvalidPragmaX, - errXNotAllowedHere, errInvalidControlFlowX, - errXisNoType, errCircumNeedsPointer, errInvalidExpression, - errInvalidExpressionX, errEnumHasNoValueX, errNamedExprExpected, - errNamedExprNotAllowed, errXExpectsOneTypeParam, - errArrayExpectsTwoTypeParams, errInvalidVisibilityX, errInitHereNotAllowed, - errXCannotBeAssignedTo, errIteratorNotAllowed, errXNeedsReturnType, - errNoReturnTypeDeclared, - errInvalidCommandX, errXOnlyAtModuleScope, - errXNeedsParamObjectType, - errTemplateInstantiationTooNested, errInstantiationFrom, - errInvalidIndexValueForTuple, errCommandExpectsFilename, - errMainModuleMustBeSpecified, - errXExpected, - errTIsNotAConcreteType, - errInvalidSectionStart, errGridTableNotImplemented, errGeneralParseError, - errNewSectionExpected, errWhitespaceExpected, errXisNoValidIndexFile, - errCannotRenderX, errVarVarTypeNotAllowed, errInstantiateXExplicitly, - errOnlyACallOpCanBeDelegator, errUsingNoSymbol, - errMacroBodyDependsOnGenericTypes, - errDestructorNotGenericEnough, - errInlineIteratorsAsProcParams, - errXExpectsTwoArguments, - errXExpectsObjectTypes, errXcanNeverBeOfThisSubtype, errTooManyIterations, - errCannotInterpretNodeX, errFieldXNotFound, errInvalidConversionFromTypeX, - errAssertionFailed, errCannotGenerateCodeForX, errXRequiresOneArgument, - errUnhandledExceptionX, errCyclicTree, errXisNoMacroOrTemplate, - errXhasSideEffects, errIteratorExpected, errLetNeedsInit, - errThreadvarCannotInit, errWrongSymbolX, errIllegalCaptureX, - errXCannotBeClosure, errXMustBeCompileTime, - errCannotInferTypeOfTheLiteral, - errCannotInferReturnType, - errGenericLambdaNotAllowed, - errCompilerDoesntSupportTarget, - errUser, - warnCannotOpenFile, - warnOctalEscape, warnXIsNeverRead, warnXmightNotBeenInit, - warnDeprecated, warnConfigDeprecated, - warnSmallLshouldNotBeUsed, warnUnknownMagic, warnRedefinitionOfLabel, - warnUnknownSubstitutionX, warnLanguageXNotSupported, - warnFieldXNotSupported, warnCommentXIgnored, - warnNilStatement, warnTypelessParam, - warnDifferentHeaps, warnWriteToForeignHeap, warnUnsafeCode, - warnEachIdentIsTuple, warnShadowIdent, - warnProveInit, warnProveField, warnProveIndex, warnGcUnsafe, warnGcUnsafe2, - warnUninit, warnGcMem, warnDestructor, warnLockLevel, warnResultShadowed, - warnUser, - hintSuccess, hintSuccessX, - hintLineTooLong, hintXDeclaredButNotUsed, hintConvToBaseNotNeeded, - hintConvFromXtoItselfNotNeeded, hintExprAlwaysX, hintQuitCalled, - hintProcessing, hintCodeBegin, hintCodeEnd, hintConf, hintPath, - hintConditionAlwaysTrue, hintName, hintPattern, - hintUser - -const - fatalMin* = errUnknown - fatalMax* = errInternal - errMin* = errUnknown - errMax* = errUser - warnMin* = warnCannotOpenFile - warnMax* = pred(hintSuccess) - hintMin* = hintSuccess - hintMax* = high(TMsgKind) - -type - TNoteKind* = range[warnMin..hintMax] # "notes" are warnings or hints - TNoteKinds* = set[TNoteKind] - -var - gNotes*: TNoteKinds = {low(TNoteKind)..high(TNoteKind)} - - {warnShadowIdent, warnUninit, - warnProveField, warnProveIndex, warnGcUnsafe} - - -#import compiler.msgs - -echo warnUninit in gNotes +discard """ + file: "tsets.nim" + output: '''Ha ein F ist in s! +false''' +""" +# Test the handling of sets + +import + strutils + +proc testSets(s: var set[char]) = + s = {'A', 'B', 'C', 'E'..'G'} + {'Z'} + s + +# test sets if the first element is different from 0: +type + TAZ = range['a'..'z'] + TAZset = set[TAZ] + + TTokType* = enum + tkInvalid, tkEof, + tkSymbol, + tkAddr, tkAnd, tkAs, tkAsm, tkBlock, tkBreak, tkCase, tkCast, tkConst, + tkContinue, tkConverter, tkDiscard, tkDiv, tkElif, tkElse, tkEnd, tkEnum, + tkExcept, tkException, tkFinally, tkFor, tkFrom, tkGeneric, tkIf, tkImplies, + tkImport, tkIn, tkInclude, tkIs, tkIsnot, tkIterator, tkLambda, tkMacro, + tkMethod, tkMod, tkNil, tkNot, tkNotin, tkObject, tkOf, tkOr, tkOut, tkProc, + tkPtr, tkRaise, tkRecord, tkRef, tkReturn, tkShl, tkShr, tkTemplate, tkTry, + tkType, tkVar, tkWhen, tkWhere, tkWhile, tkWith, tkWithout, tkXor, tkYield, + tkIntLit, tkInt8Lit, tkInt16Lit, tkInt32Lit, tkInt64Lit, tkFloatLit, + tkFloat32Lit, tkFloat64Lit, tkStrLit, tkRStrLit, tkTripleStrLit, tkCharLit, + tkRCharLit, tkParLe, tkParRi, tkBracketLe, tkBracketRi, tkCurlyLe, + tkCurlyRi, tkBracketDotLe, tkBracketDotRi, + tkCurlyDotLe, tkCurlyDotRi, + tkParDotLe, tkParDotRi, + tkComma, tkSemiColon, tkColon, tkEquals, tkDot, tkDotDot, tkHat, tkOpr, + tkComment, tkAccent, tkInd, tkSad, tkDed, + tkSpaces, tkInfixOpr, tkPrefixOpr, tkPostfixOpr + TTokTypeRange = range[tkSymbol..tkDed] + TTokTypes* = set[TTokTypeRange] + +const + toktypes: TTokTypes = {TTokTypeRange(tkSymbol)..pred(tkIntLit), + tkStrLit..tkTripleStrLit} + +var + s: set[char] + a: TAZset +s = {'0'..'9'} +testSets(s) +if 'F' in s: write(stdout, "Ha ein F ist in s!\n") +else: write(stdout, "BUG: F ist nicht in s!\n") +a = {} #{'a'..'z'} +for x in low(TAZ) .. high(TAZ): + incl(a, x) + if x in a: discard + else: write(stdout, "BUG: something not in a!\n") + +for x in low(TTokTypeRange) .. high(TTokTypeRange): + if x in tokTypes: + discard + #writeLine(stdout, "the token '$1' is in the set" % repr(x)) + +#OUT Ha ein F ist in s! + + +type + TMsgKind* = enum + errUnknown, errIllFormedAstX, errInternal, errCannotOpenFile, errGenerated, + errXCompilerDoesNotSupportCpp, errStringLiteralExpected, + errIntLiteralExpected, errInvalidCharacterConstant, + errClosingTripleQuoteExpected, errClosingQuoteExpected, + errTabulatorsAreNotAllowed, errInvalidToken, errLineTooLong, + errInvalidNumber, errNumberOutOfRange, errNnotAllowedInCharacter, + errClosingBracketExpected, errMissingFinalQuote, errIdentifierExpected, + errNewlineExpected, + errInvalidModuleName, + errOperatorExpected, errTokenExpected, errStringAfterIncludeExpected, + errRecursiveDependencyX, errOnOrOffExpected, errNoneSpeedOrSizeExpected, + errInvalidPragma, errUnknownPragma, errInvalidDirectiveX, + errAtPopWithoutPush, errEmptyAsm, errInvalidIndentation, + errExceptionExpected, errExceptionAlreadyHandled, + errYieldNotAllowedHere, errYieldNotAllowedInTryStmt, + errInvalidNumberOfYieldExpr, errCannotReturnExpr, errAttemptToRedefine, + errStmtInvalidAfterReturn, errStmtExpected, errInvalidLabel, + errInvalidCmdLineOption, errCmdLineArgExpected, errCmdLineNoArgExpected, + errInvalidVarSubstitution, errUnknownVar, errUnknownCcompiler, + errOnOrOffExpectedButXFound, errNoneBoehmRefcExpectedButXFound, + errNoneSpeedOrSizeExpectedButXFound, errGuiConsoleOrLibExpectedButXFound, + errUnknownOS, errUnknownCPU, errGenOutExpectedButXFound, + errArgsNeedRunOption, errInvalidMultipleAsgn, errColonOrEqualsExpected, + errExprExpected, errUndeclaredIdentifier, errUseQualifier, errTypeExpected, + errSystemNeeds, errExecutionOfProgramFailed, errNotOverloadable, + errInvalidArgForX, errStmtHasNoEffect, errXExpectsTypeOrValue, + errXExpectsArrayType, errIteratorCannotBeInstantiated, errExprXAmbiguous, + errConstantDivisionByZero, errOrdinalTypeExpected, + errOrdinalOrFloatTypeExpected, errOverOrUnderflow, + errCannotEvalXBecauseIncompletelyDefined, errChrExpectsRange0_255, + errDynlibRequiresExportc, errUndeclaredFieldX, errNilAccess, + errIndexOutOfBounds, errIndexTypesDoNotMatch, errBracketsInvalidForType, + errValueOutOfSetBounds, errFieldInitTwice, errFieldNotInit, + errExprXCannotBeCalled, errExprHasNoType, errExprXHasNoType, + errCastNotInSafeMode, errExprCannotBeCastedToX, errCommaOrParRiExpected, + errCurlyLeOrParLeExpected, errSectionExpected, errRangeExpected, + errMagicOnlyInSystem, errPowerOfTwoExpected, + errStringMayNotBeEmpty, errCallConvExpected, errProcOnlyOneCallConv, + errSymbolMustBeImported, errExprMustBeBool, errConstExprExpected, + errDuplicateCaseLabel, errRangeIsEmpty, errSelectorMustBeOfCertainTypes, + errSelectorMustBeOrdinal, errOrdXMustNotBeNegative, errLenXinvalid, + errWrongNumberOfVariables, errExprCannotBeRaised, errBreakOnlyInLoop, + errTypeXhasUnknownSize, errConstNeedsConstExpr, errConstNeedsValue, + errResultCannotBeOpenArray, errSizeTooBig, errSetTooBig, + errBaseTypeMustBeOrdinal, errInheritanceOnlyWithNonFinalObjects, + errInheritanceOnlyWithEnums, errIllegalRecursionInTypeX, + errCannotInstantiateX, errExprHasNoAddress, errXStackEscape, + errVarForOutParamNeeded, + errPureTypeMismatch, errTypeMismatch, errButExpected, errButExpectedX, + errAmbiguousCallXYZ, errWrongNumberOfArguments, + errXCannotBePassedToProcVar, + errXCannotBeInParamDecl, errPragmaOnlyInHeaderOfProc, errImplOfXNotAllowed, + errImplOfXexpected, errNoSymbolToBorrowFromFound, errDiscardValueX, + errInvalidDiscard, errIllegalConvFromXtoY, errCannotBindXTwice, + errInvalidOrderInArrayConstructor, + errInvalidOrderInEnumX, errEnumXHasHoles, errExceptExpected, errInvalidTry, + errOptionExpected, errXisNoLabel, errNotAllCasesCovered, + errUnknownSubstitionVar, errComplexStmtRequiresInd, errXisNotCallable, + errNoPragmasAllowedForX, errNoGenericParamsAllowedForX, + errInvalidParamKindX, errDefaultArgumentInvalid, errNamedParamHasToBeIdent, + errNoReturnTypeForX, errConvNeedsOneArg, errInvalidPragmaX, + errXNotAllowedHere, errInvalidControlFlowX, + errXisNoType, errCircumNeedsPointer, errInvalidExpression, + errInvalidExpressionX, errEnumHasNoValueX, errNamedExprExpected, + errNamedExprNotAllowed, errXExpectsOneTypeParam, + errArrayExpectsTwoTypeParams, errInvalidVisibilityX, errInitHereNotAllowed, + errXCannotBeAssignedTo, errIteratorNotAllowed, errXNeedsReturnType, + errNoReturnTypeDeclared, + errInvalidCommandX, errXOnlyAtModuleScope, + errXNeedsParamObjectType, + errTemplateInstantiationTooNested, errInstantiationFrom, + errInvalidIndexValueForTuple, errCommandExpectsFilename, + errMainModuleMustBeSpecified, + errXExpected, + errTIsNotAConcreteType, + errInvalidSectionStart, errGridTableNotImplemented, errGeneralParseError, + errNewSectionExpected, errWhitespaceExpected, errXisNoValidIndexFile, + errCannotRenderX, errVarVarTypeNotAllowed, errInstantiateXExplicitly, + errOnlyACallOpCanBeDelegator, errUsingNoSymbol, + errMacroBodyDependsOnGenericTypes, + errDestructorNotGenericEnough, + errInlineIteratorsAsProcParams, + errXExpectsTwoArguments, + errXExpectsObjectTypes, errXcanNeverBeOfThisSubtype, errTooManyIterations, + errCannotInterpretNodeX, errFieldXNotFound, errInvalidConversionFromTypeX, + errAssertionFailed, errCannotGenerateCodeForX, errXRequiresOneArgument, + errUnhandledExceptionX, errCyclicTree, errXisNoMacroOrTemplate, + errXhasSideEffects, errIteratorExpected, errLetNeedsInit, + errThreadvarCannotInit, errWrongSymbolX, errIllegalCaptureX, + errXCannotBeClosure, errXMustBeCompileTime, + errCannotInferTypeOfTheLiteral, + errCannotInferReturnType, + errGenericLambdaNotAllowed, + errCompilerDoesntSupportTarget, + errUser, + warnCannotOpenFile, + warnOctalEscape, warnXIsNeverRead, warnXmightNotBeenInit, + warnDeprecated, warnConfigDeprecated, + warnSmallLshouldNotBeUsed, warnUnknownMagic, warnRedefinitionOfLabel, + warnUnknownSubstitutionX, warnLanguageXNotSupported, + warnFieldXNotSupported, warnCommentXIgnored, + warnNilStatement, warnTypelessParam, + warnDifferentHeaps, warnWriteToForeignHeap, warnUnsafeCode, + warnEachIdentIsTuple, warnShadowIdent, + warnProveInit, warnProveField, warnProveIndex, warnGcUnsafe, warnGcUnsafe2, + warnUninit, warnGcMem, warnDestructor, warnLockLevel, warnResultShadowed, + warnUser, + hintSuccess, hintSuccessX, + hintLineTooLong, hintXDeclaredButNotUsed, hintConvToBaseNotNeeded, + hintConvFromXtoItselfNotNeeded, hintExprAlwaysX, hintQuitCalled, + hintProcessing, hintCodeBegin, hintCodeEnd, hintConf, hintPath, + hintConditionAlwaysTrue, hintName, hintPattern, + hintUser + +const + fatalMin* = errUnknown + fatalMax* = errInternal + errMin* = errUnknown + errMax* = errUser + warnMin* = warnCannotOpenFile + warnMax* = pred(hintSuccess) + hintMin* = hintSuccess + hintMax* = high(TMsgKind) + +type + TNoteKind* = range[warnMin..hintMax] # "notes" are warnings or hints + TNoteKinds* = set[TNoteKind] + +var + gNotes*: TNoteKinds = {low(TNoteKind)..high(TNoteKind)} - + {warnShadowIdent, warnUninit, + warnProveField, warnProveIndex, warnGcUnsafe} + + +#import compiler.msgs + +echo warnUninit in gNotes diff --git a/tests/sets/tsets2.nim b/tests/sets/tsets2.nim index 7f313e14f..9c73dbe03 100644 --- a/tests/sets/tsets2.nim +++ b/tests/sets/tsets2.nim @@ -28,7 +28,7 @@ block tableTest1: for x in 0..1: for y in 0..1: assert((x,y) in t) - #assert($t == + #assert($t == # "{(x: 0, y: 0), (x: 0, y: 1), (x: 1, y: 0), (x: 1, y: 1)}") block setTest2: @@ -37,16 +37,16 @@ block setTest2: t.incl("111") t.incl("123") t.excl("111") - + t.incl("012") t.incl("123") # test duplicates - + assert "123" in t assert "111" notin t # deleted - + for key in items(data): t.incl(key) for key in items(data): assert key in t - + block orderedSetTest1: var t = data.toOrderedSet diff --git a/tests/showoff/thtml1.nim b/tests/showoff/thtml1.nim index cd95c7971..c7a083c21 100644 --- a/tests/showoff/thtml1.nim +++ b/tests/showoff/thtml1.nim @@ -4,7 +4,7 @@ discard """ template htmlTag(tag: expr) {.immediate.} = proc tag(): string = "<" & astToStr(tag) & ">" - + htmlTag(br) htmlTag(html) diff --git a/tests/stckovfl.nim b/tests/stckovfl.nim index eeb499bed..cbc893d2e 100644 --- a/tests/stckovfl.nim +++ b/tests/stckovfl.nim @@ -1,10 +1,10 @@ # To test stack overflow message -proc over(a: int): int = +proc over(a: int): int = if a >= 10: assert false return result = over(a+1)+5 - + Echo($over(0)) diff --git a/tests/stdlib/nre/captures.nim b/tests/stdlib/nre/captures.nim index 4f3f15444..19c344a8d 100644 --- a/tests/stdlib/nre/captures.nim +++ b/tests/stdlib/nre/captures.nim @@ -3,7 +3,7 @@ include nre suite "captures": test "map capture names to numbers": - check(getNameToNumberTable(re("(?1(?2(?3))(?'v4'4))()")) == + check(getNameToNumberTable(re("(?1(?2(?3))(?'v4'4))()")) == { "v1" : 0, "v2" : 1, "v3" : 2, "v4" : 3 }.toTable()) test "capture bounds are correct": diff --git a/tests/stdlib/talgorithm.nim b/tests/stdlib/talgorithm.nim index 3ca425fbc..f200e54c5 100644 --- a/tests/stdlib/talgorithm.nim +++ b/tests/stdlib/talgorithm.nim @@ -8,4 +8,4 @@ doAssert product(@[@[1,2], @[3,4], @[5,6]]) == @[@[2,4,6],@[1,4,6],@[2,3,6],@[1, doAssert product(@[@[1,2], @[]]) == newSeq[seq[int]](), "two elements, but one empty" doAssert lowerBound([1,2,4], 3, system.cmp[int]) == 2 doAssert lowerBound([1,2,2,3], 4, system.cmp[int]) == 4 -doAssert lowerBound([1,2,3,10], 11) == 4 \ No newline at end of file +doAssert lowerBound([1,2,3,10], 11) == 4 diff --git a/tests/stdlib/tcritbits.nim b/tests/stdlib/tcritbits.nim index fb447b80b..8280ec881 100644 --- a/tests/stdlib/tcritbits.nim +++ b/tests/stdlib/tcritbits.nim @@ -22,7 +22,7 @@ when isMainModule: for w in r.items: echo w - + for w in r.itemsWithPrefix("de"): echo w diff --git a/tests/stdlib/tformat.nim b/tests/stdlib/tformat.nim index 92c0c16f5..160ab0fd5 100644 --- a/tests/stdlib/tformat.nim +++ b/tests/stdlib/tformat.nim @@ -2,11 +2,11 @@ discard """ file: "tformat.nim" output: "Hi Andreas! How do you feel, Rumpf?" """ -# Tests the new format proc (including the & and &= operators) - -import strutils - -echo("Hi $1! How do you feel, $2?\n" % ["Andreas", "Rumpf"]) -#OUT Hi Andreas! How do you feel, Rumpf? +# Tests the new format proc (including the & and &= operators) + +import strutils + +echo("Hi $1! How do you feel, $2?\n" % ["Andreas", "Rumpf"]) +#OUT Hi Andreas! How do you feel, Rumpf? diff --git a/tests/stdlib/tio.nim b/tests/stdlib/tio.nim index dcb6bd54f..ebf2d70f3 100644 --- a/tests/stdlib/tio.nim +++ b/tests/stdlib/tio.nim @@ -1,7 +1,7 @@ -# test the file-IO - -proc main() = - for line in lines("thello.nim"): - writeLine(stdout, line) - -main() +# test the file-IO + +proc main() = + for line in lines("thello.nim"): + writeLine(stdout, line) + +main() diff --git a/tests/stdlib/tlists.nim b/tests/stdlib/tlists.nim index 7d5379945..4caa05c90 100644 --- a/tests/stdlib/tlists.nim +++ b/tests/stdlib/tlists.nim @@ -11,14 +11,14 @@ block SinglyLinkedListTest1: var L: TSinglyLinkedList[int] for d in items(data): L.prepend(d) assert($L == "[6, 5, 4, 3, 2, 1]") - + assert(4 in L) block SinglyLinkedListTest2: var L: TSinglyLinkedList[string] for d in items(data): L.prepend($d) assert($L == "[6, 5, 4, 3, 2, 1]") - + assert("4" in L) @@ -28,7 +28,7 @@ block DoublyLinkedListTest1: for d in items(data): L.append(d) L.remove(L.find(1)) assert($L == "[6, 5, 4, 3, 2, 1, 2, 3, 4, 5, 6]") - + assert(4 in L) block SinglyLinkedRingTest1: @@ -39,7 +39,7 @@ block SinglyLinkedRingTest1: assert($L == "[4, 4]") assert(4 in L) - + block DoublyLinkedRingTest1: var L: TDoublyLinkedRing[int] @@ -49,7 +49,7 @@ block DoublyLinkedRingTest1: assert($L == "[4, 4]") assert(4 in L) - + L.append(3) L.append(5) assert($L == "[4, 4, 3, 5]") @@ -60,7 +60,7 @@ block DoublyLinkedRingTest1: L.remove(L.find(4)) assert($L == "[]") assert(4 notin L) - + echo "true" diff --git a/tests/stdlib/tmarshal.nim b/tests/stdlib/tmarshal.nim index a778d2f77..4c0c10360 100644 --- a/tests/stdlib/tmarshal.nim +++ b/tests/stdlib/tmarshal.nim @@ -25,7 +25,7 @@ type help: string else: discard - + PNode = ref TNode TNode = object next, prev: PNode diff --git a/tests/stdlib/tmath.nim b/tests/stdlib/tmath.nim index fc9486093..1ac9c8092 100644 --- a/tests/stdlib/tmath.nim +++ b/tests/stdlib/tmath.nim @@ -23,13 +23,13 @@ suite "random int": rand = random(100..1000) check rand < 1000 check rand >= 100 - test "randomize() again gives new numbers": + test "randomize() again gives new numbers": randomize() var rand1 = random(1000000) randomize() var rand2 = random(1000000) check rand1 != rand2 - + suite "random float": test "there might be some randomness": @@ -52,7 +52,7 @@ suite "random float": rand = random(100.0..1000.0) check rand < 1000.0 check rand >= 100.0 - test "randomize() again gives new numbers": + test "randomize() again gives new numbers": randomize() var rand1:float = random(1000000.0) randomize() diff --git a/tests/stdlib/tmath2.nim b/tests/stdlib/tmath2.nim index 88d96c80a..84a49efa9 100644 --- a/tests/stdlib/tmath2.nim +++ b/tests/stdlib/tmath2.nim @@ -1,85 +1,85 @@ -# tests for the interpreter - -proc loops(a: var int) = - discard - #var - # b: int - #b = glob - #while b != 0: - # b = b + 1 - #a = b - -proc mymax(a, b: int): int = - #loops(result) - result = a - if b > a: result = b - -proc test(a, b: int) = - var - x, y: int - x = 0 - y = 7 - if x == a + b * 3 - 7 or - x == 8 or - x == y and y > -56 and y < 699: - y = 0 - elif y == 78 and x == 0: - y = 1 - elif y == 0 and x == 0: - y = 2 - else: - y = 3 - -type - TTokType = enum - tkNil, tkType, tkConst, tkVar, tkSymbol, tkIf, - tkWhile, tkFor, tkLoop, tkCase, tkLabel, tkGoto - -proc testCase(t: TTokType): int = - case t - of tkNil, tkType, tkConst: result = 0 - of tkVar: result = 1 - of tkSymbol: result = 2 - of tkIf..tkFor: result = 3 - of tkLoop: result = 56 - else: result = -1 - test(0, 9) # test the call - -proc TestLoops() = - var - i, j: int - - while i >= 0: - if i mod 3 == 0: - break - i = i + 1 - while j == 13: - j = 13 - break - break - - while true: - break - - -var - glob: int - a: array [0..5, int] - -proc main() = - #glob = 0 - #loops( glob ) - var - res: int - s: string - #write(stdout, mymax(23, 45)) - write(stdout, "Hallo! Wie heisst du? ") - s = readLine(stdin) - # test the case statement - case s - of "Andreas": write(stdout, "Du bist mein Meister!\n") - of "Rumpf": write(stdout, "Du bist in der Familie meines Meisters!\n") - else: write(stdout, "ich kenne dich nicht!\n") - write(stdout, "Du heisst " & s & "\n") - -main() +# tests for the interpreter + +proc loops(a: var int) = + discard + #var + # b: int + #b = glob + #while b != 0: + # b = b + 1 + #a = b + +proc mymax(a, b: int): int = + #loops(result) + result = a + if b > a: result = b + +proc test(a, b: int) = + var + x, y: int + x = 0 + y = 7 + if x == a + b * 3 - 7 or + x == 8 or + x == y and y > -56 and y < 699: + y = 0 + elif y == 78 and x == 0: + y = 1 + elif y == 0 and x == 0: + y = 2 + else: + y = 3 + +type + TTokType = enum + tkNil, tkType, tkConst, tkVar, tkSymbol, tkIf, + tkWhile, tkFor, tkLoop, tkCase, tkLabel, tkGoto + +proc testCase(t: TTokType): int = + case t + of tkNil, tkType, tkConst: result = 0 + of tkVar: result = 1 + of tkSymbol: result = 2 + of tkIf..tkFor: result = 3 + of tkLoop: result = 56 + else: result = -1 + test(0, 9) # test the call + +proc TestLoops() = + var + i, j: int + + while i >= 0: + if i mod 3 == 0: + break + i = i + 1 + while j == 13: + j = 13 + break + break + + while true: + break + + +var + glob: int + a: array [0..5, int] + +proc main() = + #glob = 0 + #loops( glob ) + var + res: int + s: string + #write(stdout, mymax(23, 45)) + write(stdout, "Hallo! Wie heisst du? ") + s = readLine(stdin) + # test the case statement + case s + of "Andreas": write(stdout, "Du bist mein Meister!\n") + of "Rumpf": write(stdout, "Du bist in der Familie meines Meisters!\n") + else: write(stdout, "ich kenne dich nicht!\n") + write(stdout, "Du heisst " & s & "\n") + +main() diff --git a/tests/stdlib/tos.nim b/tests/stdlib/tos.nim index ebe577b00..cae388792 100644 --- a/tests/stdlib/tos.nim +++ b/tests/stdlib/tos.nim @@ -2,9 +2,9 @@ import os -proc walkDirTree(root: string) = +proc walkDirTree(root: string) = for k, f in walkDir(root): - case k + case k of pcFile, pcLinkToFile: echo(f) of pcDir: walkDirTree(f) of pcLinkToDir: discard diff --git a/tests/stdlib/tosprocterminate.nim b/tests/stdlib/tosprocterminate.nim index fd044414c..7fc6c5d85 100644 --- a/tests/stdlib/tosprocterminate.nim +++ b/tests/stdlib/tosprocterminate.nim @@ -14,7 +14,7 @@ var TimeToWait = 5000 while process.running() and TimeToWait > 0: sleep(100) TimeToWait = TimeToWait - 100 - + if process.running(): echo("FAILED") else: diff --git a/tests/stdlib/tparscfg.nim b/tests/stdlib/tparscfg.nim index 618ecadd6..4c11ccf61 100644 --- a/tests/stdlib/tparscfg.nim +++ b/tests/stdlib/tparscfg.nim @@ -1,7 +1,7 @@ import os, parsecfg, strutils, streams - + var f = newFileStream(paramStr(1), fmRead) if f != nil: var p: TCfgParser @@ -9,7 +9,7 @@ if f != nil: while true: var e = next(p) case e.kind - of cfgEof: + of cfgEof: echo("EOF!") break of cfgSectionStart: ## a ``[section]`` has been parsed diff --git a/tests/stdlib/tquit.nim b/tests/stdlib/tquit.nim index d4dc1522d..d18b468c8 100644 --- a/tests/stdlib/tquit.nim +++ b/tests/stdlib/tquit.nim @@ -1,6 +1,6 @@ -# Test the new beforeQuit variable: - -proc myExit() {.noconv.} = - write(stdout, "just exiting...\n") - -addQuitProc(myExit) +# Test the new beforeQuit variable: + +proc myExit() {.noconv.} = + write(stdout, "just exiting...\n") + +addQuitProc(myExit) diff --git a/tests/stdlib/tregex.nim b/tests/stdlib/tregex.nim index bb4695f02..ae6714de1 100644 --- a/tests/stdlib/tregex.nim +++ b/tests/stdlib/tregex.nim @@ -2,30 +2,30 @@ discard """ file: "tregex.nim" output: "key: keyAYes!" """ -# Test the new regular expression module -# which is based on the PCRE library +# Test the new regular expression module +# which is based on the PCRE library when defined(powerpc64): # cheat as our powerpc test machine has no PCRE installed: echo "key: keyAYes!" -else: - import - re - - if "keyA = valueA" =~ re"\s*(\w+)\s*\=\s*(\w+)": - write(stdout, "key: ", matches[0]) - elif "# comment!" =~ re.re"\s*(\#.*)": - # test re.re"" syntax - echo("comment: ", matches[0]) - else: - echo("Bug!") - - if "Username".match(re"[A-Za-z]+"): - echo("Yes!") - else: - echo("Bug!") - - #OUT key: keyAYes! +else: + import + re + + if "keyA = valueA" =~ re"\s*(\w+)\s*\=\s*(\w+)": + write(stdout, "key: ", matches[0]) + elif "# comment!" =~ re.re"\s*(\#.*)": + # test re.re"" syntax + echo("comment: ", matches[0]) + else: + echo("Bug!") + + if "Username".match(re"[A-Za-z]+"): + echo("Yes!") + else: + echo("Bug!") + + #OUT key: keyAYes! diff --git a/tests/stdlib/treguse.nim b/tests/stdlib/treguse.nim index a610ad725..3d09eb731 100644 --- a/tests/stdlib/treguse.nim +++ b/tests/stdlib/treguse.nim @@ -2,26 +2,26 @@ discard """ file: "treguse.nim" output: "055this should be the casehugh" """ -# Test the register usage of the virtual machine and -# the blocks in var statements - -proc main(a, b: int) = - var x = 0 - write(stdout, x) - if x == 0: - var y = 55 - write(stdout, y) - write(stdout, "this should be the case") - var input = "" - if input == "Andreas": - write(stdout, "wow") - else: - write(stdout, "hugh") - else: - var z = 66 - write(stdout, z) # "bug!") - -main(45, 1000) -#OUT 055this should be the casehugh +# Test the register usage of the virtual machine and +# the blocks in var statements + +proc main(a, b: int) = + var x = 0 + write(stdout, x) + if x == 0: + var y = 55 + write(stdout, y) + write(stdout, "this should be the case") + var input = "" + if input == "Andreas": + write(stdout, "wow") + else: + write(stdout, "hugh") + else: + var z = 66 + write(stdout, z) # "bug!") + +main(45, 1000) +#OUT 055this should be the casehugh diff --git a/tests/stdlib/trepr.nim b/tests/stdlib/trepr.nim index 8d1353173..18fe7e054 100644 --- a/tests/stdlib/trepr.nim +++ b/tests/stdlib/trepr.nim @@ -6,7 +6,7 @@ discard """ type TEnum = enum a, b - + var val = {a, b} stdout.write(repr(val)) stdout.writeLine(repr({'a'..'z', 'A'..'Z'})) diff --git a/tests/stdlib/trepr2.nim b/tests/stdlib/trepr2.nim index b7c2bd152..a92024851 100644 --- a/tests/stdlib/trepr2.nim +++ b/tests/stdlib/trepr2.nim @@ -1,32 +1,32 @@ -# test the new "repr" built-in proc - -type - TEnum = enum - en1, en2, en3, en4, en5, en6 - - TPoint {.final.} = object - x, y, z: int - s: array [0..1, string] - e: TEnum - -var - p: TPoint - q: ref TPoint - s: seq[ref TPoint] - -p.x = 0 -p.y = 13 -p.z = 45 -p.s[0] = "abc" -p.s[1] = "xyz" -p.e = en6 - -new(q) -q[] = p - -s = @[q, q, q, q] - -writeLine(stdout, repr(p)) -writeLine(stdout, repr(q)) -writeLine(stdout, repr(s)) -writeLine(stdout, repr(en4)) +# test the new "repr" built-in proc + +type + TEnum = enum + en1, en2, en3, en4, en5, en6 + + TPoint {.final.} = object + x, y, z: int + s: array [0..1, string] + e: TEnum + +var + p: TPoint + q: ref TPoint + s: seq[ref TPoint] + +p.x = 0 +p.y = 13 +p.z = 45 +p.s[0] = "abc" +p.s[1] = "xyz" +p.e = en6 + +new(q) +q[] = p + +s = @[q, q, q, q] + +writeLine(stdout, repr(p)) +writeLine(stdout, repr(q)) +writeLine(stdout, repr(s)) +writeLine(stdout, repr(en4)) diff --git a/tests/stdlib/tsplit.nim b/tests/stdlib/tsplit.nim index 25bad33e2..5a1cd2f5f 100644 --- a/tests/stdlib/tsplit.nim +++ b/tests/stdlib/tsplit.nim @@ -13,7 +13,7 @@ if s == "#abc#xy#z": echo "true" else: echo "false" - + #OUT true diff --git a/tests/stdlib/tstrset.nim b/tests/stdlib/tstrset.nim index 9cdb5ed35..15024c3f1 100644 --- a/tests/stdlib/tstrset.nim +++ b/tests/stdlib/tstrset.nim @@ -8,7 +8,7 @@ type TRadixNodeLinear = object of TRadixNode len: int8 keys: array [0..31, char] - vals: array [0..31, PRadixNode] + vals: array [0..31, PRadixNode] TRadixNodeFull = object of TRadixNode b: array [char, PRadixNode] TRadixNodeLeaf = object of TRadixNode @@ -16,7 +16,7 @@ type PRadixNodeLinear = ref TRadixNodeLinear PRadixNodeFull = ref TRadixNodeFull PRadixNodeLeaf = ref TRadixNodeLeaf - + proc search(r: PRadixNode, s: string): PRadixNode = var r = r var i = 0 @@ -52,7 +52,7 @@ proc contains*(r: PRadixNode, s: string): bool = proc testOrincl*(r: var PRadixNode, s: string): bool = nil - + proc incl*(r: var PRadixNode, s: string) = discard testOrIncl(r, s) proc excl*(r: var PRadixNode, s: string) = diff --git a/tests/stdlib/tstrtabs.nim b/tests/stdlib/tstrtabs.nim index 8404a6c88..a248cc3b2 100644 --- a/tests/stdlib/tstrtabs.nim +++ b/tests/stdlib/tstrtabs.nim @@ -4,7 +4,7 @@ var tab = newStringTable({"key1": "val1", "key2": "val2"}, modeStyleInsensitive) for i in 0..80: tab["key_" & $i] = "value" & $i - + for key, val in pairs(tab): writeLine(stdout, key, ": ", val) writeLine(stdout, "length of table ", $tab.len) diff --git a/tests/stdlib/ttime.nim b/tests/stdlib/ttime.nim index bad818816..859f0abdd 100644 --- a/tests/stdlib/ttime.nim +++ b/tests/stdlib/ttime.nim @@ -1,6 +1,6 @@ -# test the new time module - -import - times - -write(stdout, $getTime()) +# test the new time module + +import + times + +write(stdout, $getTime()) diff --git a/tests/stdlib/twalker.nim b/tests/stdlib/twalker.nim index aad0fa786..91c97df01 100644 --- a/tests/stdlib/twalker.nim +++ b/tests/stdlib/twalker.nim @@ -1,13 +1,13 @@ -# iterate over all files with a given filter: - -import - "../../lib/pure/os.nim", ../../ lib / pure / times - -proc main(filter: string) = - for filename in walkFiles(filter): - writeLine(stdout, filename) - - for key, val in envPairs(): - writeLine(stdout, key & '=' & val) - -main("*.nim") +# iterate over all files with a given filter: + +import + "../../lib/pure/os.nim", ../../ lib / pure / times + +proc main(filter: string) = + for filename in walkFiles(filter): + writeLine(stdout, filename) + + for key, val in envPairs(): + writeLine(stdout, key & '=' & val) + +main("*.nim") diff --git a/tests/system/io.nim b/tests/system/io.nim index ec9a1ed70..b0ccfda9f 100644 --- a/tests/system/io.nim +++ b/tests/system/io.nim @@ -13,7 +13,7 @@ proc echoLoop(str: string): string = discard process.waitForExit while not output.atEnd: result.add(output.readLine) - + suite "io": suite "readAll": test "stdin": diff --git a/tests/template/annotate.nim b/tests/template/annotate.nim index fa58030dc..5f395557b 100644 --- a/tests/template/annotate.nim +++ b/tests/template/annotate.nim @@ -110,4 +110,4 @@ when isMainModule: echo styles echo body echo info - echo shader \ No newline at end of file + echo shader diff --git a/tests/template/mtempl5.nim b/tests/template/mtempl5.nim index 51e8461b8..3c2881764 100644 --- a/tests/template/mtempl5.nim +++ b/tests/template/mtempl5.nim @@ -1,10 +1,10 @@ -var +var gx = 88 gy = 44 - + template templ*(): int = bind gx, gy gx + gy - + diff --git a/tests/template/otests.nim b/tests/template/otests.nim index c885e23df..120146343 100644 --- a/tests/template/otests.nim +++ b/tests/template/otests.nim @@ -1,219 +1,219 @@ -# Fields -const x = 5 - - -# Test substring -static: - assert "test".substring(3) == "t" - assert "test".substring(2,1) == "s" - assert "test".substring(3,2) == "t" - assert "test".substring(1,2) == "es" - - -# Various parsing tests -when true: - - block: #no_substitution - proc actual: string = tmpli html""" -

    Test!

    - """ - const expected = html""" -

    Test!

    - """ - doAssert actual() == expected - - block: #basic - proc actual: string = tmpli html""" -

    Test $$x

    - $x - """ - const expected = html""" -

    Test $x

    - 5 - """ - doAssert actual() == expected - - block: #expression - proc actual: string = tmpli html""" -

    Test $$(x * 5)

    - $(x * 5) - """ - const expected = html""" -

    Test $(x * 5)

    - 25 - """ - doAssert actual() == expected - - block: #escape - proc actual: string = tmpli js""" - [{ - "hello world" - }] - """ - const expected = js""" - [{ - "hello world" - }] - """ - doAssert actual() == expected - - block: #forIn - proc actual: string = tmpli html""" -

    Test for

    -
      - $for y in 0..2 { -
    • $y
    • - } -
    - """ - const expected = html""" -

    Test for

    -
      -
    • 0
    • -
    • 1
    • -
    • 2
    • -
    - """ - doAssert actual() == expected - - block: #while - proc actual: string = tmpli html""" -

    Test while/stmt

    -
      - ${ var y = 0 } - $while y < 4 { -
    • $y
    • - ${ inc(y) } - } -
    - """ - const expected = html""" -

    Test while/stmt

    -
      -
    • 0
    • -
    • 1
    • -
    • 2
    • -
    • 3
    • -
    - """ - doAssert actual() == expected - - block: #ifElifElse - proc actual: string = tmpli html""" -

    Test if/elif/else

    - $if x == 8 { -
    x is 8!
    - } - $elif x == 7 { -
    x is 7!
    - } - $else { -
    x is neither!
    - } - """ - const expected = html""" -

    Test if/elif/else

    -
    x is neither!
    - """ - doAssert actual() == expected - - block: #multiLineStatements - proc actual: string = tmpli html""" -

    Test multiline statements

    - ${ - var x = 5 - var y = 7 - } - $x$y - """ - const expected = html""" -

    Test multiline statements

    - 57 - """ - doAssert actual() == expected - - block: #caseOfElse - proc actual: string = tmpli html""" -

    Test case

    - $case x - $of 5 { -
    x == 5
    - } - $of 6 { -
    x == 6
    - } - $else {} - """ - const expected = html""" -

    Test case

    -
    x == 5
    - """ - doAssert actual() == expected - - - -when true: #embeddingTest - proc no_substitution: string = tmpli html""" -

    Template test!

    - """ - - # # Single variable substitution - proc substitution(who = "nobody"): string = tmpli html""" -
    hello $who!
    - """ - - # Expression template - proc test_expression(nums: openarray[int] = []): string = - var i = 2 - tmpli html""" - $(no_substitution()) - $(substitution("Billy")) -
    Age: $($nums[i] & "!!")
    - """ - - proc test_statements(nums: openarray[int] = []): string = - tmpli html""" - $(test_expression(nums)) - $if true { -
      - $for i in nums { -
    • $(i * 2)
    • - } -
    - } - """ - - var actual = test_statements([0,1,2]) - const expected = html""" -

    Template test!

    -
    hello Billy!
    -
    Age: 2!!
    -
      -
    • 0
    • -
    • 2
    • -
    • 4
    • -
    - """ - doAssert actual == expected - - -when defined(future): - block: #tryCatch - proc actual: string = tmpli html""" -

    Test try/catch

    -
    - $try { -
    Lets try this!
    - } - $except { -
    Uh oh!
    - } -
    - """ - const expected = html""" -

    Test try/catch

    -
    -
    Lets try this!
    -
    - """ - doAssert actual() == expected \ No newline at end of file +# Fields +const x = 5 + + +# Test substring +static: + assert "test".substring(3) == "t" + assert "test".substring(2,1) == "s" + assert "test".substring(3,2) == "t" + assert "test".substring(1,2) == "es" + + +# Various parsing tests +when true: + + block: #no_substitution + proc actual: string = tmpli html""" +

    Test!

    + """ + const expected = html""" +

    Test!

    + """ + doAssert actual() == expected + + block: #basic + proc actual: string = tmpli html""" +

    Test $$x

    + $x + """ + const expected = html""" +

    Test $x

    + 5 + """ + doAssert actual() == expected + + block: #expression + proc actual: string = tmpli html""" +

    Test $$(x * 5)

    + $(x * 5) + """ + const expected = html""" +

    Test $(x * 5)

    + 25 + """ + doAssert actual() == expected + + block: #escape + proc actual: string = tmpli js""" + [{ + "hello world" + }] + """ + const expected = js""" + [{ + "hello world" + }] + """ + doAssert actual() == expected + + block: #forIn + proc actual: string = tmpli html""" +

    Test for

    +
      + $for y in 0..2 { +
    • $y
    • + } +
    + """ + const expected = html""" +

    Test for

    +
      +
    • 0
    • +
    • 1
    • +
    • 2
    • +
    + """ + doAssert actual() == expected + + block: #while + proc actual: string = tmpli html""" +

    Test while/stmt

    +
      + ${ var y = 0 } + $while y < 4 { +
    • $y
    • + ${ inc(y) } + } +
    + """ + const expected = html""" +

    Test while/stmt

    +
      +
    • 0
    • +
    • 1
    • +
    • 2
    • +
    • 3
    • +
    + """ + doAssert actual() == expected + + block: #ifElifElse + proc actual: string = tmpli html""" +

    Test if/elif/else

    + $if x == 8 { +
    x is 8!
    + } + $elif x == 7 { +
    x is 7!
    + } + $else { +
    x is neither!
    + } + """ + const expected = html""" +

    Test if/elif/else

    +
    x is neither!
    + """ + doAssert actual() == expected + + block: #multiLineStatements + proc actual: string = tmpli html""" +

    Test multiline statements

    + ${ + var x = 5 + var y = 7 + } + $x$y + """ + const expected = html""" +

    Test multiline statements

    + 57 + """ + doAssert actual() == expected + + block: #caseOfElse + proc actual: string = tmpli html""" +

    Test case

    + $case x + $of 5 { +
    x == 5
    + } + $of 6 { +
    x == 6
    + } + $else {} + """ + const expected = html""" +

    Test case

    +
    x == 5
    + """ + doAssert actual() == expected + + + +when true: #embeddingTest + proc no_substitution: string = tmpli html""" +

    Template test!

    + """ + + # # Single variable substitution + proc substitution(who = "nobody"): string = tmpli html""" +
    hello $who!
    + """ + + # Expression template + proc test_expression(nums: openarray[int] = []): string = + var i = 2 + tmpli html""" + $(no_substitution()) + $(substitution("Billy")) +
    Age: $($nums[i] & "!!")
    + """ + + proc test_statements(nums: openarray[int] = []): string = + tmpli html""" + $(test_expression(nums)) + $if true { +
      + $for i in nums { +
    • $(i * 2)
    • + } +
    + } + """ + + var actual = test_statements([0,1,2]) + const expected = html""" +

    Template test!

    +
    hello Billy!
    +
    Age: 2!!
    +
      +
    • 0
    • +
    • 2
    • +
    • 4
    • +
    + """ + doAssert actual == expected + + +when defined(future): + block: #tryCatch + proc actual: string = tmpli html""" +

    Test try/catch

    +
    + $try { +
    Lets try this!
    + } + $except { +
    Uh oh!
    + } +
    + """ + const expected = html""" +

    Test try/catch

    +
    +
    Lets try this!
    +
    + """ + doAssert actual() == expected diff --git a/tests/template/thygienictempl.nim b/tests/template/thygienictempl.nim index 3cdbac40e..5e4f534f8 100644 --- a/tests/template/thygienictempl.nim +++ b/tests/template/thygienictempl.nim @@ -1,7 +1,7 @@ - + var e = "abc" - + raise newException(EIO, e & "ha!") template t() = echo(foo) diff --git a/tests/template/tmodulealias.nim b/tests/template/tmodulealias.nim index a7d155e51..6681379fb 100644 --- a/tests/template/tmodulealias.nim +++ b/tests/template/tmodulealias.nim @@ -8,10 +8,10 @@ else: import posix when defined(Windows): - template orig: expr = + template orig: expr = winlean else: - template orig: expr = + template orig: expr = posix proc socket(domain, typ, protocol: int): int = diff --git a/tests/template/tstempl.nim b/tests/template/tstempl.nim index f8e57abbb..649082041 100644 --- a/tests/template/tstempl.nim +++ b/tests/template/tstempl.nim @@ -6,7 +6,7 @@ levB''' # tstempl.nim import strutils -type +type TLev = enum levA, levB diff --git a/tests/template/ttempl.nim b/tests/template/ttempl.nim index 2c4785325..5f1341990 100644 --- a/tests/template/ttempl.nim +++ b/tests/template/ttempl.nim @@ -15,10 +15,10 @@ const var i = 0 -for item in items(tabs): +for item in items(tabs): var content = $i var file: TFile - if open(file, changeFileExt(item[1], "html"), fmWrite): + if open(file, changeFileExt(item[1], "html"), fmWrite): write(file, sunsetTemplate(current=item[1], ticker="", content=content, tabs=tabs)) close(file) diff --git a/tests/template/ttempl3.nim b/tests/template/ttempl3.nim index c5d78d414..56daf9fe6 100644 --- a/tests/template/ttempl3.nim +++ b/tests/template/ttempl3.nim @@ -11,18 +11,18 @@ template withOpenFile(f: expr, filename: string, mode: TFileMode, close(f) else: quit("cannot open for writing: " & filename) - + withOpenFile(txt, "ttempl3.txt", fmWrite): writeLine(txt, "line 1") txt.writeLine("line 2") - + var myVar: array[0..1, int] -# Test zero argument template: +# Test zero argument template: template ha: expr = myVar[0] - -ha = 1 + +ha = 1 echo(ha) @@ -37,7 +37,7 @@ template typedef(name: expr, typ: typeDesc) {.immediate, dirty.} = type `T name`* = typ `P name`* = ref `T name` - + typedef(myint, int) var x: PMyInt diff --git a/tests/template/twrongopensymchoice.nim b/tests/template/twrongopensymchoice.nim index 5a02a813c..360c92037 100644 --- a/tests/template/twrongopensymchoice.nim +++ b/tests/template/twrongopensymchoice.nim @@ -4,11 +4,11 @@ discard """ # bug #940 -type - Foo* = ref object +type + Foo* = ref object b*: int -proc new*(this: var Foo) = +proc new*(this: var Foo) = assert this != nil this.b = 10 diff --git a/tests/testament/backend.nim b/tests/testament/backend.nim index 11743c337..e2e2e2dd5 100644 --- a/tests/testament/backend.nim +++ b/tests/testament/backend.nim @@ -81,34 +81,34 @@ proc getCommit(db: TDbConn): CommitId = let hash = "git log -n 1"()[commLen..commLen+10] let branch = "git symbolic-ref --short HEAD"() if hash.len == 0 or branch.len == 0: quit "cannot determine git HEAD" - + let id = db.getValue(sql"select id from [Commit] where hash = ? and branch = ?", hash, branch) if id.len > 0: result = id.parseInt.CommitId else: - result = db.insertId(sql"insert into [Commit](hash, branch) values (?, ?)", + result = db.insertId(sql"insert into [Commit](hash, branch) values (?, ?)", hash, branch).CommitId -proc writeTestResult*(name, category, target, +proc writeTestResult*(name, category, target, action, result, expected, given: string) = - let id = db.getValue(sql"""select id from TestResult + let id = db.getValue(sql"""select id from TestResult where name = ? and category = ? and target = ? and - machine = ? and [commit] = ?""", + machine = ? and [commit] = ?""", name, category, target, thisMachine, thisCommit) if id.len > 0: db.exec(sql"""update TestResult - set action = ?, result = ?, expected = ?, given = ? + set action = ?, result = ?, expected = ?, given = ? where id = ?""", action, result, expected, given, id) else: - db.exec(sql"""insert into TestResult(name, category, target, - action, + db.exec(sql"""insert into TestResult(name, category, target, + action, result, expected, given, [commit], machine) - values (?,?,?,?,?,?,?,?,?) """, name, category, target, + values (?,?,?,?,?,?,?,?,?) """, name, category, target, action, - result, expected, given, + result, expected, given, thisCommit, thisMachine) proc open*() = diff --git a/tests/testament/tester.nim b/tests/testament/tester.nim index 704d7e76e..b138c9909 100644 --- a/tests/testament/tester.nim +++ b/tests/testament/tester.nim @@ -286,8 +286,8 @@ proc testSpec(r: var TResults, test: TTest) = if exitCode != expected.exitCode: r.addResult(test, "exitcode: " & $expected.exitCode, - "exitcode: " & $exitCode & "\n\nOutput:\n" & - analyzeAndConsolidateOutput(bufB), + "exitcode: " & $exitCode & "\n\nOutput:\n" & + analyzeAndConsolidateOutput(bufB), reExitCodesDiffer) return diff --git a/tests/threads/tactors2.nim b/tests/threads/tactors2.nim index 5683f98ba..b011ef140 100644 --- a/tests/threads/tactors2.nim +++ b/tests/threads/tactors2.nim @@ -16,7 +16,7 @@ proc main() = createActorPool(actorPool, 1) var some_data: some_type - + var inchannel = spawn(actorPool, some_data, thread_proc) var recv_data = ^inchannel close(inchannel[]) diff --git a/tests/threads/threadex.nim b/tests/threads/threadex.nim index 0360c8c04..545d1f0cc 100644 --- a/tests/threads/threadex.nim +++ b/tests/threads/threadex.nim @@ -32,7 +32,7 @@ proc produce() {.thread.} = close(input) m.k = mEof chan.send(m) - + open(chan) createThread[void](consumer, consume) createThread[void](producer, produce) diff --git a/tests/threads/tthreadanalysis.nim b/tests/threads/tthreadanalysis.nim index b222f15a9..6ef4de0bf 100644 --- a/tests/threads/tthreadanalysis.nim +++ b/tests/threads/tthreadanalysis.nim @@ -36,9 +36,9 @@ proc echoLeTree(n: PNode) = echo it.data it = it.le -proc threadFunc(interval: tuple[a, b: int]) {.thread.} = +proc threadFunc(interval: tuple[a, b: int]) {.thread.} = doNothing() - for i in interval.a..interval.b: + for i in interval.a..interval.b: var r = buildTree(i) echoLeTree(r) # for local data echoLeTree(root) # and the same for foreign data :-) diff --git a/tests/threads/tthreadanalysis2.nim b/tests/threads/tthreadanalysis2.nim index d5b2cd430..07d77028b 100644 --- a/tests/threads/tthreadanalysis2.nim +++ b/tests/threads/tthreadanalysis2.nim @@ -34,9 +34,9 @@ proc echoLeTree(n: PNode) = echo it.data it = it.le -proc threadFunc(interval: tuple[a, b: int]) {.thread.} = +proc threadFunc(interval: tuple[a, b: int]) {.thread.} = doNothing() - for i in interval.a..interval.b: + for i in interval.a..interval.b: var r = buildTree(i) echoLeTree(r) # for local data root = buildTree(2) # BAD! diff --git a/tests/threads/tthreadheapviolation1.nim b/tests/threads/tthreadheapviolation1.nim index 94e1b64db..02ce7878a 100644 --- a/tests/threads/tthreadheapviolation1.nim +++ b/tests/threads/tthreadheapviolation1.nim @@ -4,7 +4,7 @@ discard """ cmd: "nim $target --hints:on --threads:on $options $file" """ -var +var global: string = "test string" t: TThread[void] diff --git a/tests/threads/ttryrecv.nim b/tests/threads/ttryrecv.nim index acccf182c..28529b5ac 100644 --- a/tests/threads/ttryrecv.nim +++ b/tests/threads/ttryrecv.nim @@ -31,5 +31,5 @@ while true: echo "Finished listening" -joinThread(thr) +joinThread(thr) close(chan) diff --git a/tests/trmacros/tcse.nim b/tests/trmacros/tcse.nim index ff04f7d83..023a8f298 100644 --- a/tests/trmacros/tcse.nim +++ b/tests/trmacros/tcse.nim @@ -6,7 +6,7 @@ template cse{f(a, a, x)}(a: expr{(nkDotExpr|call|nkBracketExpr)&noSideEffect}, f: expr, x: varargs[expr]): expr = let aa = a f(aa, aa, x)+4 - + var a: array[0..10, int] i = 3 diff --git a/tests/trmacros/tmatrix.nim b/tests/trmacros/tmatrix.nim index c825a7792..f409434c5 100644 --- a/tests/trmacros/tmatrix.nim +++ b/tests/trmacros/tmatrix.nim @@ -24,6 +24,6 @@ macro optOps{ (`+`|`-`|`*`) ** a }(a: TMat): expr = var x, y, z: TMat -echo x + y * z - x +echo x + y * z - x #echo x + y + z diff --git a/tests/trmacros/tstar.nim b/tests/trmacros/tstar.nim index 8443268f4..536289ff0 100644 --- a/tests/trmacros/tstar.nim +++ b/tests/trmacros/tstar.nim @@ -4,7 +4,7 @@ discard """ var calls = 0 - + proc `&&`(s: varargs[string]): string = result = s[0] for i in 1..len(s)-1: result.add s[i] diff --git a/tests/typerel/tno_int_in_bool_context.nim b/tests/typerel/tno_int_in_bool_context.nim index 755a02c0c..557759169 100644 --- a/tests/typerel/tno_int_in_bool_context.nim +++ b/tests/typerel/tno_int_in_bool_context.nim @@ -3,6 +3,6 @@ discard """ errormsg: "type mismatch: got (int literal(1)) but expected 'bool'" """ -if 1: +if 1: echo "wtf?" - + diff --git a/tests/typerel/trectuples.nim b/tests/typerel/trectuples.nim index a74e4859c..af9ba2dbb 100644 --- a/tests/typerel/trectuples.nim +++ b/tests/typerel/trectuples.nim @@ -7,7 +7,7 @@ type Node = tuple[left: ref Node] proc traverse(root: ref Node) = if root.left != nil: traverse(root.left) - + type A = tuple[B: ptr A] proc C(D: ptr A) = C(D.B) diff --git a/tests/typerel/trefs.nim b/tests/typerel/trefs.nim index b157ca2b5..d4383c562 100644 --- a/tests/typerel/trefs.nim +++ b/tests/typerel/trefs.nim @@ -3,21 +3,21 @@ discard """ line: 20 errormsg: "type mismatch" """ -# test for ref types (including refs to procs) - -type - TProc = proc (a, b: int): int {.stdcall.} - -proc foo(c, d: int): int {.stdcall.} = - return 0 - -proc wrongfoo(c, e: int): int {.inline.} = - return 0 - -var p: TProc -p = foo -write(stdout, "success!") -p = wrongfoo #ERROR_MSG type mismatch - +# test for ref types (including refs to procs) + +type + TProc = proc (a, b: int): int {.stdcall.} + +proc foo(c, d: int): int {.stdcall.} = + return 0 + +proc wrongfoo(c, e: int): int {.inline.} = + return 0 + +var p: TProc +p = foo +write(stdout, "success!") +p = wrongfoo #ERROR_MSG type mismatch + diff --git a/tests/typerel/tregionptrs.nim b/tests/typerel/tregionptrs.nim index 07387fed8..69a93a107 100644 --- a/tests/typerel/tregionptrs.nim +++ b/tests/typerel/tregionptrs.nim @@ -8,7 +8,7 @@ type APtr = RegionA ptr int RegionB = object BPtr = RegionB ptr int - + var x,xx: APtr var y: BPtr x = nil diff --git a/tests/typerel/tregionptrs2.nim b/tests/typerel/tregionptrs2.nim index 3b32ff93d..7fe758c8e 100644 --- a/tests/typerel/tregionptrs2.nim +++ b/tests/typerel/tregionptrs2.nim @@ -8,14 +8,14 @@ type next: ThingyPtr name: string -proc iname(t: ThingyPtr) = +proc iname(t: ThingyPtr) = var x = t while not x.isNil: echo x.name x = x.next -proc go() = +proc go() = var athing : ThingyPtr iname(athing) diff --git a/tests/typerel/tsecondarrayproperty.nim b/tests/typerel/tsecondarrayproperty.nim index 07fdac1c4..3a6879b16 100644 --- a/tests/typerel/tsecondarrayproperty.nim +++ b/tests/typerel/tsecondarrayproperty.nim @@ -14,7 +14,7 @@ proc `[]=` (self: var TFoo, x, y: int) = proc second(self: var TFoo): var TSecond = return TSecond(self) -proc `[]`(self: var TSecond, x: int): var int = +proc `[]`(self: var TSecond, x: int): var int = return TFoo(self).data[2*x] var f: TFoo diff --git a/tests/typerel/ttuple1.nim b/tests/typerel/ttuple1.nim index 5787cc309..d5c80800c 100644 --- a/tests/typerel/ttuple1.nim +++ b/tests/typerel/ttuple1.nim @@ -12,5 +12,5 @@ for key, val in items(romanNumbers): proc PrintBiTuple(t: tuple[k: string, v: int]): int = stdout.write(t.k & "=" & $t.v & ", ") return 0 - + diff --git a/tests/typerel/ttypenoval.nim b/tests/typerel/ttypenoval.nim index 214b35e29..d5b91fbca 100644 --- a/tests/typerel/ttypenoval.nim +++ b/tests/typerel/ttypenoval.nim @@ -11,7 +11,7 @@ type TBinHeap[T] = object heap: seq[TNode[T]] last: int - + PBinHeap[T] = ref TBinHeap[T] proc newBinHeap*[T](heap: var PBinHeap[T], size: int) = @@ -19,7 +19,7 @@ proc newBinHeap*[T](heap: var PBinHeap[T], size: int) = heap.last = 0 newSeq(heap.heap, size) #newSeq(heap.seq, size) - + proc parent(elem: int): int {.inline.} = return (elem-1) div 2 diff --git a/tests/typerel/tvoid.nim b/tests/typerel/tvoid.nim index d31936217..1e46d016e 100644 --- a/tests/typerel/tvoid.nim +++ b/tests/typerel/tvoid.nim @@ -16,14 +16,14 @@ proc nothing(x, y: void): void = echo "ha" proc callProc[T](p: proc (x: T) {.nimcall.}, x: T) = - when T is void: + when T is void: p() else: p(x) proc intProc(x: int) = echo x - + proc emptyProc() = echo "empty" diff --git a/tests/typerel/typalias.nim b/tests/typerel/typalias.nim index 55dcb9fa6..e85f1f664 100644 --- a/tests/typerel/typalias.nim +++ b/tests/typerel/typalias.nim @@ -3,13 +3,13 @@ type TMyObj = TYourObj TYourObj = object of RootObj x, y: int - + proc init: TYourObj = result.x = 0 result.y = -1 - + proc f(x: var TYourObj) = discard - + var m: TMyObj = init() f(m) diff --git a/tests/types/tfinalobj.nim b/tests/types/tfinalobj.nim index 1cd7fae28..2fda73363 100644 --- a/tests/types/tfinalobj.nim +++ b/tests/types/tfinalobj.nim @@ -3,9 +3,9 @@ discard """ """ type - TA = object {.pure, final.} + TA = object {.pure, final.} x: string - + var a: TA a.x = "abc" diff --git a/tests/types/tforwty.nim b/tests/types/tforwty.nim index 0f1d3697f..626abd5ef 100644 --- a/tests/types/tforwty.nim +++ b/tests/types/tforwty.nim @@ -1,9 +1,9 @@ -# Test 13: forward types - -type - PSym = ref TSym - - TSym = object - next: PSym - -var s: PSym +# Test 13: forward types + +type + PSym = ref TSym + + TSym = object + next: PSym + +var s: PSym diff --git a/tests/types/tforwty2.nim b/tests/types/tforwty2.nim index 52af1c7dd..6449e25bc 100644 --- a/tests/types/tforwty2.nim +++ b/tests/types/tforwty2.nim @@ -1,22 +1,22 @@ -# Test for a hard to fix internal error -# occurred in the SDL library - -{.push dynlib: "SDL.dll", callconv: cdecl.} - -type - PSDL_semaphore = ptr TSDL_semaphore - TSDL_semaphore {.final.} = object - sem: pointer #PSem_t; - when not defined(USE_NAMED_SEMAPHORES): - sem_data: int - when defined(BROKEN_SEMGETVALUE): - # This is a little hack for MacOS X - - # It's not thread-safe, but it's better than nothing - sem_value: cint - -type - PSDL_Sem = ptr TSDL_Sem - TSDL_Sem = TSDL_Semaphore - -proc SDL_CreateSemaphore(initial_value: int32): PSDL_Sem {. - importc: "SDL_CreateSemaphore".} +# Test for a hard to fix internal error +# occurred in the SDL library + +{.push dynlib: "SDL.dll", callconv: cdecl.} + +type + PSDL_semaphore = ptr TSDL_semaphore + TSDL_semaphore {.final.} = object + sem: pointer #PSem_t; + when not defined(USE_NAMED_SEMAPHORES): + sem_data: int + when defined(BROKEN_SEMGETVALUE): + # This is a little hack for MacOS X - + # It's not thread-safe, but it's better than nothing + sem_value: cint + +type + PSDL_Sem = ptr TSDL_Sem + TSDL_Sem = TSDL_Semaphore + +proc SDL_CreateSemaphore(initial_value: int32): PSDL_Sem {. + importc: "SDL_CreateSemaphore".} diff --git a/tests/types/tillegaltyperecursion.nim b/tests/types/tillegaltyperecursion.nim index ebdbc1d13..bace2dfc8 100644 --- a/tests/types/tillegaltyperecursion.nim +++ b/tests/types/tillegaltyperecursion.nim @@ -18,7 +18,7 @@ type MessageReceivedHandler*: TEventHandler Socket: TSocket Thread: TThread[TIRC] - + proc initIRC*(): TIRC = result.Socket = socket() result.EventEmitter = initEventEmitter() @@ -26,8 +26,8 @@ proc initIRC*(): TIRC = proc IsConnected*(irc: var TIRC): bool = return running(irc.Thread) - - + + proc sendRaw*(irc: var TIRC, message: string) = irc.Socket.send(message & "\r\L") proc handleData(irc: TIRC) {.thread.} = @@ -40,14 +40,14 @@ proc handleData(irc: TIRC) {.thread.} = if len(tup) == 1: #Connected connected = True - + #Parse data here - + else: #Disconnected connected = False return - + proc Connect*(irc: var TIRC, nick: string, host: string, port: int = 6667) = connect(irc.Socket ,host ,TPort(port),TDomain.AF_INET) send(irc.Socket,"USER " & nick & " " & nick & " " & nick & " " & nick &"\r\L") @@ -57,8 +57,8 @@ proc Connect*(irc: var TIRC, nick: string, host: string, port: int = 6667) = irc.Thread = thread - - + + when isMainModule: var irc = initIRC() irc.Connect("AmryBot[Nim]","irc.freenode.net",6667) diff --git a/tests/types/tinheritref.nim b/tests/types/tinheritref.nim index e5de6a4be..ecd62a06f 100644 --- a/tests/types/tinheritref.nim +++ b/tests/types/tinheritref.nim @@ -21,7 +21,7 @@ type TTreeIterator* [T,D] = ref object {.inheritable.} TKeysIterator* [T,D] = ref object of TTreeIterator[T,D] #this not - + var it: TKeysIterator[int, string] = nil diff --git a/tests/types/tisop.nim b/tests/types/tisop.nim index 05c6a1a06..d0b7c32b2 100644 --- a/tests/types/tisop.nim +++ b/tests/types/tisop.nim @@ -6,7 +6,7 @@ import typetraits type TRecord = (tuple) or (object) - + TFoo[T, U] = object x: int diff --git a/tests/varres/tvarres1.nim b/tests/varres/tvarres1.nim index de4a505d3..849805768 100644 --- a/tests/varres/tvarres1.nim +++ b/tests/varres/tvarres1.nim @@ -7,10 +7,10 @@ discard """ var g = 5 -proc p(): var int = +proc p(): var int = var bla: int result = bla - + p() = 45 echo g diff --git a/tests/varres/tvarres2.nim b/tests/varres/tvarres2.nim index 165e4a36e..53a57d882 100644 --- a/tests/varres/tvarres2.nim +++ b/tests/varres/tvarres2.nim @@ -7,9 +7,9 @@ discard """ var g = 5 -proc p(): var int = +proc p(): var int = result = 89 - + p() = 45 echo g diff --git a/tests/varres/tvarres3.nim b/tests/varres/tvarres3.nim index a48c961df..9fcd79bfc 100644 --- a/tests/varres/tvarres3.nim +++ b/tests/varres/tvarres3.nim @@ -5,10 +5,10 @@ discard """ var g = 5 -proc p(): var int = +proc p(): var int = var bla = addr(g) #: array [0..7, int] result = bla[] - + p() = 45 echo g diff --git a/tests/varres/tvartup.nim b/tests/varres/tvartup.nim index f885cdf37..20a4156e6 100644 --- a/tests/varres/tvartup.nim +++ b/tests/varres/tvartup.nim @@ -6,7 +6,7 @@ discard """ proc divmod(a, b: int): tuple[di, mo: int] = return (a div b, a mod b) - + var (x, y) = divmod(15, 6) stdout.write(x) stdout.write(" ") diff --git a/tests/varstmt/tlet.nim b/tests/varstmt/tlet.nim index 138f34433..9c2d9706d 100644 --- a/tests/varstmt/tlet.nim +++ b/tests/varstmt/tlet.nim @@ -11,7 +11,7 @@ proc main = echo("Very funny, your name is name.") else: echo("Hi, ", name, "!") - + let (x, y) = ("abc", name) echo y, x diff --git a/tests/varstmt/tvardecl.nim b/tests/varstmt/tvardecl.nim index 5cc6f4960..a6b508295 100644 --- a/tests/varstmt/tvardecl.nim +++ b/tests/varstmt/tvardecl.nim @@ -2,14 +2,14 @@ discard """ file: "tvardecl.nim" output: "44" """ -# Test the new variable declaration syntax - -var - x = 0 - s = "Hallo" - a, b: int = 4 - -write(stdout, a) -write(stdout, b) #OUT 44 +# Test the new variable declaration syntax + +var + x = 0 + s = "Hallo" + a, b: int = 4 + +write(stdout, a) +write(stdout, b) #OUT 44 diff --git a/tests/vm/tarrayboundeval.nim b/tests/vm/tarrayboundeval.nim index 07aac4c4e..af9e33339 100644 --- a/tests/vm/tarrayboundeval.nim +++ b/tests/vm/tarrayboundeval.nim @@ -15,12 +15,12 @@ type echo FU.high -type +type PKeyboard* = ptr object TKeyboardState* = object display*: pointer internal: array[int((KeyMax + 31)/32), cuint] - + echo myconst, " ", int((KeyMax + 31) / 32) #bug 1304 or something: diff --git a/tests/vm/tasmparser.nim b/tests/vm/tasmparser.nim index 67313c858..fbacdbc87 100644 --- a/tests/vm/tasmparser.nim +++ b/tests/vm/tasmparser.nim @@ -79,23 +79,23 @@ proc asmx64 () {.compileTime} = case state: of leading: - + echo "b100 ", start start += code.skipWhile (leadingWhiteSpace, start) echo "b200 ", start let ch = code [start] if ch in endOfLine: inc (line) - #echo "c100 ", start, ' ', code + #echo "c100 ", start, ' ', code start += code.skipWhile (endOfline, start) - #echo "c200 ", start, ' ', code + #echo "c200 ", start, ' ', code continue elif ch in symbolStart: state = mnemonic elif ch in eolComment: state = skipToEndOfLine elif ch in passthrough_start: - get_passthrough () + get_passthrough () echo "d100 ", start start += code.parseUntil (token, end_or_symbol_or_comment_or_passthrough, start) echo "d200 ", start @@ -124,7 +124,7 @@ proc asmx64 () {.compileTime} = if codeLen <= start: state = endCmd continue - + let ch = code [start] if ch in passthrough_start: get_passthrough () @@ -148,7 +148,7 @@ proc asmx64 () {.compileTime} = of endCmd: cpp.add ");\n" state = skipToEndOfLine - + of skipToEndOfLine: echo "a100 ", start start += code.skipUntil (endOfLine, start) diff --git a/tests/vm/tconsteval.nim b/tests/vm/tconsteval.nim index 4459931c5..f4260495a 100644 --- a/tests/vm/tconsteval.nim +++ b/tests/vm/tconsteval.nim @@ -24,7 +24,7 @@ Possible Commands: csource [options] builds the C sources for installation zip builds the installation ZIP package inno builds the Inno Setup installer -""" % [NimVersion & spaces(44-len(NimVersion)), +""" % [NimVersion & spaces(44-len(NimVersion)), CompileDate, CompileTime] echo HelpText diff --git a/tests/vm/teval1.nim b/tests/vm/teval1.nim index cdb4ad8e2..1d3a68a0d 100644 --- a/tests/vm/teval1.nim +++ b/tests/vm/teval1.nim @@ -13,7 +13,7 @@ when true: const x = testProc() - + echo "##", x, "##" # bug #1310 diff --git a/tests/vm/tldconst.nim b/tests/vm/tldconst.nim index 9eabb7525..7df3143c9 100644 --- a/tests/vm/tldconst.nim +++ b/tests/vm/tldconst.nim @@ -11,4 +11,4 @@ proc foobar(): int = discard 0 -const x = foobar() \ No newline at end of file +const x = foobar() diff --git a/tests/vm/trgba.nim b/tests/vm/trgba.nim index 22eec4d6e..da1a2d0c5 100644 --- a/tests/vm/trgba.nim +++ b/tests/vm/trgba.nim @@ -8,19 +8,19 @@ discard """ type TAggRgba8* = array[4, byte] -template R*(self: TAggRgba8): byte = self[0] -template G*(self: TAggRgba8): byte = self[1] -template B*(self: TAggRgba8): byte = self[2] -template A*(self: TAggRgba8): byte = self[3] +template R*(self: TAggRgba8): byte = self[0] +template G*(self: TAggRgba8): byte = self[1] +template B*(self: TAggRgba8): byte = self[2] +template A*(self: TAggRgba8): byte = self[3] -template `R=`*(self: TAggRgba8, val: byte) = - self[0] = val -template `G=`*(self: TAggRgba8, val: byte) = - self[1] = val -template `B=`*(self: TAggRgba8, val: byte) = - self[2] = val -template `A=`*(self: TAggRgba8, val: byte) = - self[3] = val +template `R=`*(self: TAggRgba8, val: byte) = + self[0] = val +template `G=`*(self: TAggRgba8, val: byte) = + self[1] = val +template `B=`*(self: TAggRgba8, val: byte) = + self[2] = val +template `A=`*(self: TAggRgba8, val: byte) = + self[3] = val proc ABGR* (val: int| int64): TAggRgba8 = var V = val @@ -32,5 +32,5 @@ proc ABGR* (val: int| int64): TAggRgba8 = result.A = (V shr 8) and 0xFF const - c1 = ABGR(0xFF007F7F) + c1 = ABGR(0xFF007F7F) echo ABGR(0xFF007F7F).repr, c1.repr diff --git a/tests/vm/tslurp.nim b/tests/vm/tslurp.nim index fc3dc6f0a..027db45d6 100644 --- a/tests/vm/tslurp.nim +++ b/tests/vm/tslurp.nim @@ -6,7 +6,7 @@ template getScriptDir(): string = const relRes = slurp"../../readme.txt" absRes = slurp(parentDir(parentDir(getScriptDir())) / "readme.txt") - + echo relRes echo absRes From 5d80548cce84ea62dc8b85c10375f70d037ea4f8 Mon Sep 17 00:00:00 2001 From: Adam Strzelecki Date: Fri, 4 Sep 2015 23:05:22 +0200 Subject: [PATCH 0901/1263] examples: Trim .nim files trailing whitespace via OSX: find . -name '*.nim' -exec sed -i '' -E 's/[[:space:]]+$//' {} + --- examples/allany.nim | 4 +- examples/c++iface/irrlichtex.nim | 6 +- .../cross_calculator/nim_backend/backend.nim | 10 +- examples/curlex.nim | 4 +- examples/filterex.nim | 4 +- examples/htmlrefs.nim | 18 +-- examples/htmltitle.nim | 8 +- examples/httpserver2.nim | 6 +- examples/maximum.nim | 12 +- examples/parsecfgex.nim | 4 +- examples/sdlex.nim | 104 +++++++++--------- examples/statcsv.nim | 2 +- examples/talk/tags.nim | 2 +- examples/tunit.nim | 94 ++++++++-------- web/snippets/snippet1.nim | 4 +- 15 files changed, 141 insertions(+), 141 deletions(-) diff --git a/examples/allany.nim b/examples/allany.nim index de36a1d9b..52a794204 100644 --- a/examples/allany.nim +++ b/examples/allany.nim @@ -18,9 +18,9 @@ template any(container, cond: expr): expr {.immediate.} = break result -if all("mystring", {'a'..'z'}.contains) and any("myohmy", 'y'.`==`): +if all("mystring", {'a'..'z'}.contains) and any("myohmy", 'y'.`==`): echo "works" -else: +else: echo "does not work" diff --git a/examples/c++iface/irrlichtex.nim b/examples/c++iface/irrlichtex.nim index 4dd1d79ee..373a78ce7 100644 --- a/examples/c++iface/irrlichtex.nim +++ b/examples/c++iface/irrlichtex.nim @@ -18,13 +18,13 @@ type TDimension2d {.final, header: irr, importc: "dimension2d".} = object Tvector3df {.final, header: irr, importc: "vector3df".} = object TColor {.final, header: irr, importc: "SColor".} = object - + TIrrlichtDevice {.final, header: irr, importc: "IrrlichtDevice".} = object TIVideoDriver {.final, header: irr, importc: "IVideoDriver".} = object TISceneManager {.final, header: irr, importc: "ISceneManager".} = object TIGUIEnvironment {.final, header: irr, importc: "IGUIEnvironment".} = object TIAnimatedMesh {.final, header: irr, importc: "IAnimatedMesh".} = object - TIAnimatedMeshSceneNode {.final, header: irr, + TIAnimatedMeshSceneNode {.final, header: irr, importc: "IAnimatedMeshSceneNode".} = object TITexture {.final, header: irr, importc: "ITexture".} = object @@ -100,7 +100,7 @@ var node = smgr.addAnimatedMeshSceneNode(mesh) if node != nil: #node->setMaterialFlag(EMF_LIGHTING, false) #node->setMD2Animation(scene::EMAT_STAND) - node.setMaterialTexture(0, + node.setMaterialTexture(0, driver.getTexture( "/home/andreas/download/irrlicht-1.7.2/media/media/sydney.bmp")) diff --git a/examples/cross_calculator/nim_backend/backend.nim b/examples/cross_calculator/nim_backend/backend.nim index ffa4311f9..c8684581c 100644 --- a/examples/cross_calculator/nim_backend/backend.nim +++ b/examples/cross_calculator/nim_backend/backend.nim @@ -1,5 +1,5 @@ -# Backend for the different user interfaces. - -proc myAdd*(x, y: int): int {.cdecl, exportc.} = - result = x + y - +# Backend for the different user interfaces. + +proc myAdd*(x, y: int): int {.cdecl, exportc.} = + result = x + y + diff --git a/examples/curlex.nim b/examples/curlex.nim index 017956818..21786a6ee 100644 --- a/examples/curlex.nim +++ b/examples/curlex.nim @@ -1,8 +1,8 @@ -import +import libcurl var hCurl = easy_init() -if hCurl != nil: +if hCurl != nil: discard easy_setopt(hCurl, OPT_VERBOSE, true) discard easy_setopt(hCurl, OPT_URL, "http://nim-lang.org/") discard easy_perform(hCurl) diff --git a/examples/filterex.nim b/examples/filterex.nim index 3713f4b64..d9bfb6782 100644 --- a/examples/filterex.nim +++ b/examples/filterex.nim @@ -1,6 +1,6 @@ #! stdtmpl | standard #proc generateHTMLPage(title, currentTab, content: string, -# tabs: openArray[string]): string = +# tabs: openArray[string]): string = # result = "" $title @@ -8,7 +8,7 @@