From b22a3e8237c5b482050b3437baa93b35b21a422e Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Wed, 7 Jan 2015 17:48:43 -0500 Subject: [PATCH 001/280] 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 b36ba634a687c762fa8062ec0c5296b6f19986c1 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Fri, 9 Jan 2015 16:27:45 -0500 Subject: [PATCH 002/280] 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 003/280] 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 004/280] 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 005/280] 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 006/280] 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 007/280] 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 008/280] 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 009/280] 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 010/280] 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 011/280] 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 012/280] 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 013/280] 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 014/280] 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 015/280] 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 016/280] 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 017/280] 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 018/280] 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 019/280] 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 020/280] 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 021/280] 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 022/280] 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 023/280] 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 024/280] 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 025/280] 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 026/280] 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 027/280] 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 028/280] 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 029/280] 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 030/280] 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 031/280] 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 032/280] 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 033/280] 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 034/280] 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 035/280] 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 036/280] 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 037/280] 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 038/280] 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 039/280] 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 040/280] 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 041/280] 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 042/280] 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 043/280] 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 044/280] 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 045/280] 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 046/280] 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 047/280] 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 048/280] 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 049/280] 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 050/280] 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 051/280] 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 052/280] 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 053/280] 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 054/280] 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 055/280] 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 056/280] 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 057/280] 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 058/280] 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 059/280] 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 060/280] 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 061/280] 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 062/280] 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 063/280] 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 064/280] 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 065/280] 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 066/280] 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 067/280] 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 068/280] 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 069/280] 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 070/280] 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 071/280] 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 072/280] 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 073/280] 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 074/280] 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 075/280] 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 076/280] 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 077/280] 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 078/280] 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 079/280] 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 080/280] 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 081/280] 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 082/280] 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 083/280] 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 084/280] 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 085/280] 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 086/280] 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 087/280] 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 088/280] 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 089/280] 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 090/280] 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 091/280] 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 092/280] 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 093/280] 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 094/280] 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 095/280] 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 096/280] 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 097/280] 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 098/280] 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 099/280] 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 100/280] 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 101/280] 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 102/280] 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 103/280] 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 104/280] 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 105/280] 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 106/280] 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 107/280] 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 108/280] 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 109/280] 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 110/280] 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: Mon, 30 Mar 2015 19:39:06 -0400 Subject: [PATCH 111/280] 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 bdd8567f50ceb27efa3cc15b6682444a6ba4a4c6 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Thu, 9 Apr 2015 16:02:42 -0400 Subject: [PATCH 112/280] 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 113/280] 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 114/280] 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 115/280] 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 116/280] 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 117/280] 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 118/280] 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 119/280] 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 120/280] 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 121/280] 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 122/280] 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 123/280] 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 124/280] 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 02c6e7306f5ab6454136e9cbd7a2a1187e2e2902 Mon Sep 17 00:00:00 2001 From: Oleh Prypin Date: Sun, 12 Apr 2015 15:18:16 +0300 Subject: [PATCH 125/280] 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 126/280] 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 127/280] 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 c31870d31116db562b03e2a3c148c0843dc14ca8 Mon Sep 17 00:00:00 2001 From: Oleh Prypin Date: Sun, 12 Apr 2015 22:21:44 +0300 Subject: [PATCH 128/280] 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 e6dbb350a9def15fad3b3161749989f4c1ff88a4 Mon Sep 17 00:00:00 2001 From: Oleh Prypin Date: Sun, 12 Apr 2015 22:22:56 +0300 Subject: [PATCH 129/280] 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 7fb5932b9bad02cd9b056cd3a11e514acc94d781 Mon Sep 17 00:00:00 2001 From: Stephen Sugden Date: Sun, 3 May 2015 00:16:22 +0200 Subject: [PATCH 130/280] 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 131/280] 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 ba0b9e26c6fb98dc8bd76fbe5783f5487454619a Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Mon, 4 May 2015 16:47:31 -0400 Subject: [PATCH 132/280] 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 fef21e90031557bc00af80e3d2da98b28780ee2b Mon Sep 17 00:00:00 2001 From: def Date: Fri, 8 May 2015 03:58:44 +0200 Subject: [PATCH 133/280] 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 a75cfc98871b07e7670f7dc0bec45012ccbffdf6 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Mon, 11 May 2015 15:45:57 -0400 Subject: [PATCH 134/280] 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 7a2dce80126dd9397eed8c4461e1aefa33cb3185 Mon Sep 17 00:00:00 2001 From: Koala Zen Date: Fri, 8 May 2015 09:55:57 -0700 Subject: [PATCH 135/280] 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 188bba2b3cd3106e0c615e712b8f5fdd995137bb Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 23 May 2015 12:59:15 -0400 Subject: [PATCH 136/280] 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 137/280] 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 e9516e6308687d3c92564ac54fc63f19470ccf2b Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 23 May 2015 14:34:11 -0400 Subject: [PATCH 138/280] 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 139/280] 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 9576bc087d20e8e5cacb9cd92c635d3f9efaf0a7 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Tue, 26 May 2015 18:18:11 -0400 Subject: [PATCH 140/280] 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 0527e1f9fe00642207d78213f7d1436f8aa5ef0d Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Tue, 26 May 2015 19:14:04 -0400 Subject: [PATCH 141/280] 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 142/280] 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 143/280] 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 e65ccfb8f5123988ce3a1c204fc72a98c76fce34 Mon Sep 17 00:00:00 2001 From: yglukhov Date: Thu, 28 May 2015 11:24:39 +0300 Subject: [PATCH 144/280] 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 c5f7d553e969bd90223570059c199c8459b16a54 Mon Sep 17 00:00:00 2001 From: yglukhov Date: Wed, 27 May 2015 16:48:10 +0300 Subject: [PATCH 145/280] 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 146/280] 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 147/280] 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 148/280] 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 149/280] 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 150/280] 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 151/280] 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 152/280] 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 3f78f754839a7a00df3944d3fcdbc33bc4430401 Mon Sep 17 00:00:00 2001 From: x2f Date: Sun, 31 May 2015 21:06:23 -0400 Subject: [PATCH 153/280] 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 dd30bab480f59e4bb4ab8fad5aabd13c08aa1b11 Mon Sep 17 00:00:00 2001 From: Oscar Campbell Date: Mon, 1 Jun 2015 23:49:04 +0200 Subject: [PATCH 154/280] 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 155/280] 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 79c92603f505c388d370c5ef0dd8890e4e17e4e0 Mon Sep 17 00:00:00 2001 From: Araq Date: Tue, 2 Jun 2015 16:32:41 +0200 Subject: [PATCH 156/280] 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 157/280] 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 158/280] 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 159/280] 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 160/280] 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 161/280] 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 162/280] 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 163/280] 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 164/280] 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 165/280] 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 166/280] 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 167/280] 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 168/280] 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 169/280] 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 170/280] 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 171/280] 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 172/280] 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 173/280] 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 174/280] 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 175/280] 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 176/280] 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 177/280] 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 178/280] 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 179/280] 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 180/280] 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 181/280] 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 182/280] 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 183/280] 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 184/280] 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 185/280] 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 186/280] 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 187/280] 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 188/280] 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 189/280] 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 190/280] 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 191/280] 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 192/280] 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 193/280] 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 194/280] 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 195/280] 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 196/280] 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 197/280] 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 198/280] 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 199/280] 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 200/280] 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 201/280] 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 202/280] 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 203/280] 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 204/280] 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 205/280] 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 206/280] 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 207/280] 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 208/280] 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 209/280] 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 210/280] 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 211/280] 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 212/280] 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 213/280] 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 214/280] 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 215/280] 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 216/280] 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 217/280] 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 218/280] 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 219/280] 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 220/280] 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 221/280] 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 222/280] 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 223/280] 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 224/280] 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 225/280] 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 226/280] 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 227/280] 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 228/280] 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 229/280] 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 230/280] 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 231/280] 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 232/280] 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 233/280] 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 234/280] 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 235/280] 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 236/280] 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 237/280] 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 238/280] 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 239/280] 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 d152ccc1e2ae07cff4685a9d1b8146297fffba38 Mon Sep 17 00:00:00 2001 From: Spencer Stirling Date: Tue, 9 Jun 2015 11:59:26 -0600 Subject: [PATCH 240/280] 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 241/280] 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 242/280] 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 243/280] 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 244/280] 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 245/280] 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 246/280] 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 247/280] 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 248/280] 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 249/280] 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 250/280] 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 251/280] 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 252/280] 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 253/280] 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 254/280] 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 255/280] 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 256/280] 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 257/280] 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 258/280] 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 259/280] 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 260/280] 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 261/280] 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 262/280] 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 263/280] 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 264/280] 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 265/280] 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 266/280] 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 267/280] 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 a723362d85c077e572240d55301e715ff6dbcf64 Mon Sep 17 00:00:00 2001 From: Oscar Campbell Date: Tue, 9 Jun 2015 14:38:54 +0200 Subject: [PATCH 268/280] 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 269/280] 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 270/280] 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 271/280] 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 272/280] 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 273/280] 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 274/280] 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 275/280] 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 276/280] 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 277/280] 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 278/280] 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 279/280] 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 280/280] 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.