Pike has a builtin C-style preprocessor. It works similar to the ANSI-C preprocessor but has a few extra features. These and the default set of preprocessor macros are described here.
The preprocessor is usually accessed via
MasterObject->compile_file()
or MasterObject->compile_string()
,
but may be accessed directly by calling cpp()
.
compile()
, cpp()
, CompilerEnvironment.CPP
This is the default namespace and contains lots of global symbols.
constant
FUSE_MAJOR_VERSION
constant
FUSE_MINOR_VERSION
The version of FUSE
constant
int
HKEY_CLASSES_ROOT
constant
int
HKEY_LOCAL_MACHINE
constant
int
HKEY_CURRENT_USER
constant
int
HKEY_USERS
Root handles in the Windows registry.
These constants are only available on Win32 systems.
RegGetValue()
, RegGetValues()
, RegGetKeyNames()
program
ProxyFactory(program
p
)
Create a class that acts as a proxy for the specified program.
p
Program to generate a proxy for.
The generated class will have the same symbols (public and
private) with the same types as in p
, where accesses to
these will proxy the access to the same symbol in the proxied
(aka wrapped) object. With the following exceptions:
protected void create(object(p) obj)
Initialize the object to act as a proxy for obj
.
_sprintf(int c, mapping|void params)
Special case for c
== 'O'
, where
it will return sprintf("%O(%O)", this_program, obj)
,
and otherwise proxy the call.
void _destruct()
/void destroy()
These lfuns will not be present as the act of them being proxied would likely confuse the proxied object.
The same proxy class will be returned if this function is called with the same program multiple times.
array
(string
) RegGetKeyNames(int
hkey
, string
key
)
Get a list of value key names from the register.
hkey
One of the following:
|
|
|
|
key
A registry key.
Returns an array of value keys stored at the specified location if any.
Returns UNDEFINED
on missing key
.
Throws errors on other failures.
> RegGetKeyNames(HKEY_CURRENT_USER, "Keyboard Layout"); (1) Result: ({ "IMEtoggle", "Preload", "Substitutes", "Toggle" })
This function is only available on Win32 systems.
RegGetValue()
, RegGetValues()
string
|int
|array
(string
) RegGetValue(int
hkey
, string
key
, string
index
)
Get a single value from the register.
hkey
One of the following:
|
|
|
|
key
Registry key.
index
Value name.
Returns the value stored at the specified location in the register
if any. Returns UNDEFINED
on missing keys, throws errors
on other failures.
This function is only available on Win32 systems.
RegGetValues()
, RegGetKeyNames()
mapping
(string
:string
|int
|array
(string
)) RegGetValues(int
hkey
, string
key
)
Get multiple values from the register.
hkey
One of the following:
|
|
|
|
key
Registry key.
Returns a mapping with all the values stored at the specified location
in the register if any.
Returns UNDEFINED
on missing key
.
Throws errors on other failures.
> RegGetValues(HKEY_CURRENT_USER, "Keyboard Layout\\Preload"); (5) Result: ([ "1":"0000041d" ])
This function is only available on Win32 systems.
RegGetValue()
, RegGetKeyNames()
constant
TOKENIZE_KEEP_ESCAPES
Don't unquote backslash-sequences in quoted strings during tokenizing. This is used for bug-compatibility with Microsoft...
tokenize()
, tokenize_labled()
constant
UNDEFINED
The undefined value; ie a zero for which zero_type()
returns 1.
void
_Static_assert(int
constant_expression
, string
constant_message
)
Perform a compile-time assertion check.
If constant_expression
is false, a compiler error message
containing constant_message
will be generated.
Note that the function call compiles to the null statement, and thus does not affect the run-time.
cpp::static_assert
array
__automap__(function
(:void
) fun
, mixed
... args
)
Automap execution function.
fun
Function to call for each of the mapped arguments.
args
Arguments for fun
. Either
| Wrapper for an array to loop over. All of the arrays will be looped over in parallel. |
| All other arguments will be held constant during
the automap, and sent as is to |
This function is used by the compiler to implement the automap syntax, and should in normal circumstances never be used directly.
It may however show up during module dumping and in backtraces.
It is an error not to have any Builtin.automap_marker
s
in args
.
Builtin.automap_marker
, map()
program
__empty_program(int
|void
line
, string
|void
file
)
type
__handle_sprintf_format(string
attr
, string
fmt
, type
arg_type
, type
cont_type
)
Type attribute handler for "sprintf_format"
.
attr
Attribute to handle, either "sprintf_format"
or "strict_sprintf_format"
.
fmt
Sprintf-style formatting string to generate type information from.
arg_type
Declared type of the fmt
argument (typically string
).
cont_type
Continuation function type after the fmt
argument. This is
scanned for the type attribute "sprintf_args"
to
determine where the remaining arguments to sprintf()
will
come from.
This function is typically called from
PikeCompiler()->apply_attribute_constant()
and is used to perform
stricter compile-time argument checking of sprintf()
-style functions.
It currently implements two operating modes depending on the value of
attr
:
| The formatting string |
| The formatting string |
Returns cont_type
with "sprintf_args"
replaced by the
arguments required by the fmt
formatting string, and
"sprintf_result"
replaced by the resulting string type.
PikeCompiler()->apply_attribute_constant()
, sprintf()
constant
__null_program
Program used internally by the compiler to create objects that are later modified into instances of the compiled program by the compiler.
__placeholder_object
string(8bit)
__parse_pike_type(string(8bit)
t
)
constant
__placeholder_object
Object used internally by the compiler.
__null_program
mixed
call_out(function
(:void
) f
, float
|int
delay
, mixed
... args
)
void
_do_call_outs()
int
find_call_out(function
(:void
) f
)
int
find_call_out(mixed
id
)
int
remove_call_out(function
(:void
) f
)
int
remove_call_out(function
(:void
) id
)
array
(array
) call_out_info()
These are aliases for the corresponding functions in
Pike.DefaultBackend
.
Pike.Backend()->call_out()
, Pike.Backend()->_do_call_outs()
,
Pike.Backend()->find_call_out()
, Pike.Backend()->remove_call_out()
,
Pike.Backend()->call_out_info()
bool
_equal(mixed
o
)
void
_exit(int
returncode
)
This function does the same as exit
, but doesn't bother to clean
up the Pike interpreter before exiting. This means that no destructors
will be called, caches will not be flushed, file locks might not be
released, and databases might not be closed properly.
Use with extreme caution.
exit()
void
_gdb_breakpoint()
This function only exists so that it is possible to set a gdb breakpoint on the function pike_gdb_breakpoint.
mixed
_m_delete(mixed
key
)
m_delete callback.
array
_random(function
(:void
) random_string
, function
(:void
) random
)
Get a random entry.
An array ({ key, value })
.
object
_static_modules
This is an object containing the classes for all static (ie non-dynamic) C-modules.
In a typic Pike with support for dynamic modules the contained module classes are:
Builtin
Gmp
_Stdio
_math
_system
If the Pike binary lacks support for dynamic modules, all C-modules will show up here.
float
abs(float
f
)
int
abs(int
f
)
object
abs(object
f
)
Return the absolute value for f
. If f
is
an object it must implement lfun::`<
and
unary lfun::`-
.
float
acos(int
|float
f
)
Return the arcus cosine value for f
.
The result will be in radians.
cos()
, asin()
float
acosh(int
|float
f
)
Return the hyperbolic arcus cosine value for f
.
cosh()
, asinh()
void
add_constant(string
name
, mixed
value
)
void
add_constant(string
name
)
Add a new predefined constant.
This function is often used to add builtin functions.
All programs compiled after the add_constant()
function has been
called can access value
by the name name
.
If there is a constant called name
already, it will be replaced by
by the new definition. This will not affect already compiled programs.
Calling add_constant()
without a value will remove that name from
the list of constants. As with replacing, this will not affect already
compiled programs.
all_constants()
void
add_include_path(string
tmp
)
Add a directory to search for include files.
This is the same as the command line option -I.
Note that the added directory will only be searched when using < > to quote the included file.
remove_include_path()
void
add_module_path(string
path
, string
|void
subpath
)
Add a directory to search for modules.
This is the same as the command line option -M.
remove_module_path()
path
a string containing a path to search for Pike modules. May be a directory, or a path to a ZIP archive. If a ZIP archive path is provided, modules will be loaded from a directory, "modules" within the ZIP archive (see the subpath argument).
subpath
if path is a ZIP archive, this argument will determine the path within the archive to be searched.
void
add_program_path(string
tmp
)
Add a directory to search for programs.
This is the same as the command line option -P.
remove_program_path()
array
aggregate(mixed
... elements
)
Construct an array with the arguments as indices.
This function could be written in Pike as:
array aggregate(mixed ... elems) { return elems; }
Arrays are dynamically allocated there is no need to declare them
like int a[10]=allocate(10);
(and it isn't possible either) like
in C, just array(int) a=allocate(10);
will do.
sizeof()
, arrayp()
, allocate()
mapping
aggregate_mapping(mixed
... elems
)
Construct a mapping.
Groups the arguments together two and two in key-index pairs and
creates a mapping of those pairs. Generally, the mapping literal
syntax is handier: ([ key1:val1, key2:val2, ... ])
sizeof()
, mappingp()
, mkmapping()
multiset
aggregate_multiset(mixed
... elems
)
Construct a multiset with the arguments as indices. The multiset
will not contain any values. This method is most useful when
constructing multisets with map
or similar; generally, the
multiset literal syntax is handier: (<elem1, elem2, ...>)
With it, it's also possible to construct a multiset with values:
(<index1: value1, index2: value2, ...>)
sizeof()
, multisetp()
, mkmultiset()
int
alarm(int
seconds
)
Set an alarm clock for delivery of a signal.
alarm()
arranges for a SIGALRM signal to be delivered to the
process in seconds
seconds.
If seconds
is 0
(zero), no new alarm will be scheduled.
Any previous alarms will in any case be canceled.
Returns the number of seconds remaining until any previously scheduled alarm was due to be delivered, or zero if there was no previously scheduled alarm.
This function is only available on platforms that support signals.
ualarm()
, signal()
, call_out()
mapping
(string
:mixed
) all_constants()
Returns a mapping containing all global constants, indexed on the name of the constant, and with the value of the constant as value.
add_constant()
array
allocate(int
size
)
array
allocate(int
size
, mixed
init
)
Allocate an array of size
elements. If init
is specified
then each element is initialized by copying that value
recursively.
sizeof()
, aggregate()
, arrayp()
array
array_sscanf(string
data
, string
format
)
This function works just like sscanf()
, but returns the matched
results in an array instead of assigning them to lvalues. This is often
useful for user-defined sscanf strings.
sscanf()
, `/()
float
asin(int
|float
f
)
Return the arcus sine value for f
.
The result will be in radians.
sin()
, acos()
float
asinh(int
|float
f
)
Return the hyperbolic arcus sine value for f
.
sinh()
, acosh()
float
atan(int
|float
f
)
Returns the arcus tangent value for f
.
The result will be in radians.
tan()
, asin()
, acos()
, atan2()
float
atan2(float
f1
, float
f2
)
Returns the arcus tangent value for f1
/f2
, and uses
the signs of f1
and f2
to determine the quadrant.
The result will be in radians.
tan()
, asin()
, acos()
, atan()
float
atanh(int
|float
f
)
Returns the hyperbolic arcus tangent value for f
.
tanh()
, asinh()
, acosh()
void
atexit(function
(:void
) callback
)
This function puts the callback
in a queue of callbacks to
call when pike exits. The call order is reversed, i.e. callbacks
that have been added earlier are called after callback
.
Please note that atexit
callbacks are not called if Pike
exits abnormally.
exit()
, _exit()
mixed
atomic_get_set(mapping
|object
map
, mixed
key
, mixed
val
)
mixed
atomic_get_set(array
arr
, int
index
, mixed
val
)
Replace atomically the value for a key in a mapping or array.
map
arr
Mapping or array to alter.
key
index
Key or index to change the value for.
val
Value to change to. If value is UNDEFINED
and map
is a mapping
this function function behaves exactly as m_delete(map, key)
.
Returns the previous value for key
. If map
is a mapping and
there was no previous value UNDEFINED
is returned.
If map
is an object lfun::_m_replace()
will be called
in it.
m_delete()
array
(Pike.BacktraceFrame
) backtrace(int
|void
flags
)
Get a description of the current call stack.
flags
A bit mask of flags affecting generation of the backtrace.
Currently a single flag is defined:
| Return Note that since these values are "live", they may change or dissapear at any time unless the corresponding thread has been halted or similar. |
The description is returned as an array with one entry for each call frame on the stack.
The entries are represented by Pike.BacktraceFrame
objects.
The current call frame will be last in the array.
Please note that the frame order may be reversed in a later version of Pike to accommodate for deferred backtraces.
Note that the arguments reported in the backtrace are the current values of the variables, and not the ones that were at call-time. This can be used to hide sensitive information from backtraces (eg passwords).
In old versions of Pike the entries used to be represented by arrays of the following format:
Array | |
| A string with the filename if known, else zero. |
| An integer containing the linenumber if known, else zero. |
| The function that was called at this level. |
| The arguments that the function was called with. |
The above format is still supported by eg describe_backtrace()
.
catch()
, throw()
string
basetype(mixed
x
)
Same as sprintf("%t",x);
sprintf()
string
bkey(mixed
key
)
Render the internally used binary representation of the key into a string as a strings of '0's and '1's.
mapping
cast(string
type
)
Cast callback. Supports only cast to mapping and behaves as the inverse of create().
float
ceil(int
|float
f
)
Return the closest integer value greater or equal to f
.
ceil()
does not return an int
, merely an integer value
stored in a float
.
floor()
, round()
array
column(array
data
, mixed
index
)
Extract a column from a two-dimensional array.
This function is exactly equivalent to:
map(data, lambda(mixed x,mixed y) { return x[y]; }, index)
Except of course it is a lot shorter and faster. That is, it indices every index in the array data on the value of the argument index and returns an array with the results.
rows()
program
compile(string
source
, CompilationHandler
|void
handler
, int
|void
major
, int
|void
minor
, program
|void
target
, object
|void
placeholder
)
Compile a string to a program.
This function takes a piece of Pike code as a string and compiles it into a clonable program.
The optional argument handler
is used to specify an alternative
error handler. If it is not specified the current master object will
be used.
The optional arguments major
and minor
are used to tell the
compiler to attempt to be compatible with Pike major
.minor
.
Note that source
must contain the complete source for a program.
It is not possible to compile a single expression or statement.
Also note that compile()
does not preprocess the program.
To preprocess the program you can use compile_string()
or
call the preprocessor manually by calling cpp()
.
compile_string()
, compile_file()
, cpp()
, master()
,
CompilationHandler
, DefaultCompilerEnvironment
protected
program
compile(string
source
, object
|void
handler
, int
|void
major
, int
|void
minor
, program
|void
target
, object
|void
placeholder
)
program
compile_file(string
filename
, object
|void
handler
, void
|program
p
, void
|object
o
)
Compile the Pike code contained in the file filename
into a program.
This function will compile the file filename
to a Pike program that can
later be instantiated. It is the same as doing
.compile_string
(Stdio.read_file
(filename
), filename
)
compile()
, compile_string()
, cpp()
program
compile_string(string
source
, void
|string
filename
, object
|void
handler
, void
|program
p
, void
|object
o
, void
|int
_show_if_constant_errors
)
Compile the Pike code in the string source
into a program.
If filename
is not specified, it will default to "-"
.
Functionally equal to
.compile
(cpp
(source
, filename
))
compile()
, cpp()
, compile_file()
mixed
copy_value(mixed
value
)
Copy a value recursively.
If the result value is changed destructively (only possible for multisets, arrays and mappings) the copied value will not be changed.
The resulting value will always be equal to the copied (as tested with
the function equal()
), but they may not the the same value (as tested
with `==()
).
equal()
float
cos(int
|float
f
)
Return the cosine value for f
.
f
should be specified in radians.
acos()
, sin()
, tan()
float
cosh(int
|float
f
)
Return the hyperbolic cosine value for f
.
acosh()
, sinh()
, tanh()
string
cpp(string
data
, mapping
|string
|void
current_file
, int
|string
|void
charset
, object
|void
handler
, void
|int
compat_major
, void
|int
compat_minor
, void
|int
picky_cpp
)
Run a string through the preprocessor.
Preprocesses the string data
with Pike's builtin ANSI-C look-alike
preprocessor. If the current_file
argument has not been specified,
it will default to "-"
. charset
defaults to "ISO-10646"
.
If the second argument is a mapping, no other arguments may follow. Instead, they have to be given as members of the mapping (if wanted). The following members are recognized:
| Name of the current file. It is used for generating #line directives and for locating include files. |
| Charset to use when processing |
| Compilation handler. |
| Sets the major pike version used for compat handling. |
| Sets the minor pike version used for compat handling. |
| Generate more warnings. |
| This option keeps |
| If a prefix is given, only prefixed directives will be
processed. For example, if the prefix is |
| Mapping of predefined macros in addition to those
returned by |
compile()
protected
string
cpp(string
data
, mapping
|string
|void
current_file
, int
|string
|void
charset
, object
|void
handler
, void
|int
compat_major
, void
|int
compat_minor
, void
|int
picky_cpp
)
string
ctime(int
timestamp
)
Convert the output from a previous call to time()
into a readable
string containing the current year, month, day and time.
Like localtime
, this function might throw an error if the
ctime(2) call failed on the system. It's platform dependent what
time ranges that function can handle, e.g. Windows doesn't handle
a negative timestamp
.
strftime()
, time()
, localtime()
, gmtime()
, mktime()
mixed
decode_value(string
coded_value
, void
|Codec
codec
)
Decode a value from the string coded_value
.
This function takes a string created with encode_value()
or
encode_value_canonic()
and converts it back to the value that was
coded.
If codec
is specified, it's used as the codec for the decode.
If none is specified, then one is instantiated through
master()->Decoder()
. As a compatibility fallback, the
master itself is used if it has no Decoder
class.
encode_value()
, encode_value_canonic()
void
delay(int
|float
s
)
This function makes the thread stop for s
seconds.
Only signal handlers can interrupt the sleep. Other callbacks are not called during delay. Beware that this function uses busy-waiting to achieve the highest possible accuracy.
signal()
, sleep()
int(0..)
depth()
Calculate the depth of the tree.
string
describe_backtrace(mixed
trace
, void
|int
linewidth
)
Return a readable message that describes where the backtrace
trace
was made (by backtrace
).
It may also be an error object or array (typically caught by a
catch
), in which case the error message also is included in the
description.
Pass linewidth
-1 to disable wrapping of the output.
backtrace()
, describe_error()
, catch()
, throw()
string
describe_error(mixed
err
)
Return the error message from an error object or array (typically
caught by a catch
). The type of the error is checked, hence
err
is declared as mixed
and not object|array
.
If an error message couldn't be obtained, a fallback message
describing the failure is returned. No errors due to incorrectness
in err
are thrown.
describe_backtrace()
, get_backtrace
bool
destruct(void
|object
o
)
Mark an object as destructed.
Calls o->_destruct()
, and then clears all variables in the
object. If no argument is given, the current object is destructed.
All pointers and function pointers to this object will become zero. The destructed object will be freed from memory as soon as possible.
Returns 1
if o
has an lfun::_destruct()
that
returned 1
and inhibited destruction.
string
encode_value(mixed
value
, Codec
|void
codec
)
Code a value into a string.
This function takes a value, and converts it to a string. This string
can then be saved, sent to another Pike process, packed or used in
any way you like. When you want your value back you simply send this
string to decode_value()
and it will return the value you encoded.
Almost any value can be coded, mappings, floats, arrays, circular structures etc.
If codec
is specified, it's used as the codec for the encode.
If none is specified, then one is instantiated through
master()->Encoder()
. As a compatibility fallback, the
master itself is used if it has no Encoder
class.
If
returns UNDEFINED for an
object, codec
->nameof(o)val = o->encode_object(o)
will be called. The
returned value will be passed to o->decode_object(o, val)
when the object is decoded.
When only simple types like int, floats, strings, mappings, multisets and arrays are encoded, the produced string is very portable between pike versions. It can at least be read by any later version.
The portability when objects, programs and functions are involved depends mostly on the codec. If the byte code is encoded, i.e. when Pike programs are actually dumped in full, then the string can probably only be read by the same pike version.
decode_value()
, sprintf()
, encode_value_canonic()
string
encode_value_canonic(mixed
value
, object
|void
codec
)
Code a value into a string on canonical form.
Takes a value and converts it to a string on canonical form, much like
encode_value()
. The canonical form means that if an identical value is
encoded, it will produce exactly the same string again, even if it's
done at a later time and/or in another Pike process. The produced
string is compatible with decode_value()
.
Note that this function is more restrictive than encode_value()
with
respect to the types of values it can encode. It will throw an error
if it can't encode to a canonical form.
encode_value()
, decode_value()
array
(int
) enumerate(int
n
)
array
enumerate(int
n
, void
|mixed
step
, void
|mixed
start
, void
|function
(:void
) operator
)
Create an array with an enumeration, useful for initializing arrays
or as first argument to map()
or foreach()
.
The defaults are: step
= 1, start
= 0, operator
= `+
The resulting array is calculated like this:
array enumerate(int n, mixed step, mixed start, function operator)
{
array res = allocate(n);
for (int i=0; i < n; i++)
{
res[i] = start;
start = operator(start, step);
}
return res;
}
map()
, foreach()
int
equal(mixed
a
, mixed
b
)
This function checks if the values a
and b
are equivalent.
If either of the values is an object the (normalized) result
of calling lfun::_equal()
will be returned.
Returns 1
if both values are false (zero, destructed objects,
prototype functions, etc).
Returns 0
(zero) if the values have different types.
Otherwise depending on the type of the values:
| Returns the same as |
| The contents of Note that for objects this case is only reached if neither
|
| Returns |
copy_value()
, `==()
void
error(sprintf_format
f
, sprintf_args
... args
)
Throws an error. A more readable version of the code
throw( ({ sprintf(f, @args), backtrace() }) )
.
constant
int
is_gssapi_error
constant
string
error_type
Object recognition constants.
constant
int
is_gssapi_missing_services_error
constant
string
error_type
Object recognition constants.
int
exece(string
file
, array
(string
) args
)
int
exece(string
file
, array
(string
) args
, mapping
(string
:string
) env
)
This function transforms the Pike process into a process running
the program specified in the argument file
with the arguments args
.
If the mapping env
is present, it will completely replace all
environment variables before the new program is executed.
This function only returns if something went wrong during exece(2),
and in that case it returns 0
(zero).
The Pike driver _dies_ when this function is called. You must either
use fork()
or Process.create_process()
if you wish to execute a
program and still run the Pike runtime.
This function is not available on all platforms.
Process.create_process()
, fork()
, Stdio.File->pipe()
void
exit(int
returncode
, void
|string
fmt
, mixed
... extra
)
Exit the whole Pike program with the given returncode
.
Using exit()
with any other value than 0
(zero) indicates
that something went wrong during execution. See your system manuals
for more information about return codes.
The arguments after the returncode
will be used for a call to
werror
to output a message on stderr.
_exit()
float
exp(float
|int
f
)
Return the natural exponential of f
.
log( exp( x ) ) == x
as long as exp(x) doesn't overflow an int.
pow()
, log()
mixed
filter(mixed
arr
, void
|mixed
fun
, mixed
... extra
)
Filters the elements in arr
through fun
.
arr
is treated as a set of elements to be filtered, as
follows:
Each element is filtered with fun
. The return value is of
the same type as arr
and it contains the elements that
fun
accepted. fun
is applied in order to each element,
and that order is retained between the kept elements.
If fun
is an array, it should have the same length as
arr
. In this case, the elements in arr
are kept where
the corresponding positions in fun
are nonzero. Otherwise
fun
is used as described below.
The values are filtered with fun
, and the index/value
pairs it accepts are kept in the returned mapping.
The program is treated as a mapping containing the identifiers that are indexable from it and their values.
If there is a lfun::cast
method in the object, it's called
to try to cast the object to an array, a mapping, or a
multiset, in that order, which is then filtered as described
above.
Unless something else is mentioned above, fun
is used as
filter like this:
fun
is called for each element. It gets the current
element as the first argument and extra
as the rest. The
element is kept if it returns true, otherwise it's filtered
out.
The object is used as a function like above, i.e. the
lfun::`()
method in it is called.
fun
is indexed with each element. The element is kept if
the result is nonzero, otherwise it's filtered out.
Each element that is callable is called with extra
as
arguments. The element is kept if the result of the call is
nonzero, otherwise it's filtered out. Elements that aren't
callable are also filtered out.
Each element is indexed with the given string. If the result
of that is zero then the element is filtered out, otherwise
the result is called with extra
as arguments. The element
is kept if the return value is nonzero, otherwise it's
filtered out.
This is typically used when arr
is a collection of
objects, and fun
is the name of some predicate function
in them.
The function is never destructive on arr
.
map()
, foreach()
float
floor(int
|float
f
)
Return the closest integer value less or equal to f
.
floor()
does not return an int
, merely an integer value
stored in a float
.
ceil()
, round()
object
fork()
Fork the process in two.
Fork splits the process in two, and for the parent it returns a pid object for the child. Refer to your Unix manual for further details.
This function can cause endless bugs if used without proper care.
This function is disabled when using threads.
This function is not available on all platforms.
The most common use for fork is to start sub programs, which is
better done with Process.create_process()
.
Process.create_process()
int
gc(mapping
|array
|void
quick
)
Force garbage collection.
quick
Perform a quick garbage collection on just this value,
which must have been made weak by set_weak_flag()
.
All values that only have a single reference from
quick
will then be freed.
When quick
hasn't been specified or is UNDEFINED
,
this function checks all the memory for cyclic structures such
as arrays containing themselves and frees them if appropriate.
It also frees up destructed objects and things with only weak
references.
Normally there is no need to call this function since Pike will call it by itself every now and then. (Pike will try to predict when 20% of all arrays/object/programs in memory is 'garbage' and call this routine then.)
The amount of garbage is returned. This is the number of arrays, mappings, multisets, objects and programs that had no nonweak external references during the garbage collection. It's normally the same as the number of freed things, but there might be some difference since _destruct() functions are called during freeing, which can cause more things to be freed or allocated.
Pike.gc_parameters
, Debug.gc_status
CompilationHandler
get_active_compilation_handler()
Returns the currently active compilation compatibility handler, or 0 (zero) if none is active.
This function should only be used during a call of compile()
.
get_active_error_handler()
, compile()
,
master()->get_compilation_handler()
, CompilationHandler
CompilerEnvironment.PikeCompiler
get_active_compiler()
Returns the most recent of the currently active pike compilers,
or UNDEFINED
if none is active.
This function should only be used during a call of compile()
.
get_active_error_handler()
, compile()
,
master()->get_compilation_handler()
, CompilationHandler
CompilationHandler
get_active_error_handler()
Returns the currently active compilation error handler
(second argument to compile()
), or 0 (zero) if none
is active.
This function should only be used during a call of compile()
.
get_active_compilation_handler()
, compile()
, CompilationHandler
array
(array
(int
|string
|array
(string
))) get_all_groups()
Returns an array of arrays with all groups in the system groups source.
Each element in the returned array has the same structure as in
getgrent
function.
The groups source is system dependant. Refer to your system manuals for information about how to set the source.
Array | |
| Array with info about the group |
getgrent()
array
(array
(int
|string
)) get_all_users()
Returns an array with all users in the system.
An array with arrays of userinfo as in getpwent
.
getpwent()
getpwnam()
getpwuid()
array
get_backtrace(object
|array
err
)
Return the backtrace array from an error object or array
(typically caught by a catch
), or zero if there is none. Errors
are thrown on if there are problems retrieving the backtrace.
describe_backtrace()
, describe_error()
array
(int
) get_groups_for_user(int
|string
user
)
Gets all groups which a given user is a member of.
user
UID or loginname of the user
Array | |
| Information about all the users groups |
get_all_groups()
getgrgid()
getgrnam()
getpwuid()
getpwnam()
Iterator
get_iterator(object
|array
|mapping
|multiset
|string
data
, mixed
... args
)
Creates and returns a canonical iterator for data
.
data
can have any of the following types:
| If If |
| If |
| If |
| If |
| If |
This function is used by foreach
to get an iterator for an
object.
Iterator
, lfun::_get_iterator
mapping
(string
:string
) getenv(void
|int
force_update
)
Queries the environment variables.
force_update
A cached copy of the real environment is kept to make this
function quicker. If the optional flag force_update
is nonzero
then the real environment is queried and the cache is updated from
it. That can be necessary if the environment changes through other
means than putenv
, typically from a C-level library.
Returns the whole environment as a mapping. Destructive operations on the mapping will not affect the internal environment representation.
Variable names and values cannot be wide strings nor contain
'\0'
characters. Variable names also cannot contain
'='
characters.
On NT the environment variable name is case insensitive.
putenv()
string
getenv(string
varname
, void
|int
force_update
)
Query the value of a specific environment variable.
varname
Environment variable to query.
force_update
A cached copy of the real environment is kept to make this
function quicker. If the optional flag force_update
is nonzero
then the real environment is queried and the cache is updated from
it. That can be necessary if the environment changes through other
means than putenv
, typically from a C-level library.
Returns the value of the environment variable varname
if it exists, and 0
(zero) otherwise.
Variable names and values cannot be wide strings nor contain
'\0'
characters. Variable names also cannot contain
'='
characters.
On NT the environment variable name is case insensitive.
putenv()
array
(int
|string
|array
(string
)) getgrgid(int
gid
)
Get the group entry for the group with the id gid
using the systemfunction
getgrid(3).
gid
The id of the group
An array with the information about the group
Array | |
| Group name |
| Group password (encrypted) |
| ID of the group |
| Array with UIDs of group members |
getgrent()
getgrnam()
array
(int
|string
|array
(string
)) getgrnam(string
str
)
Get the group entry for the group with the name str
using the
systemfunction getgrnam(3).
str
The name of the group
An array with the information about the group
Array | |
| Group name |
| Group password (encrypted) |
| ID of the group |
| Array with UIDs of group members |
getgrent()
getgrgid()
int
gethrdtime(void
|int
nsec
)
Return the high resolution real time spent with threads disabled
since the Pike interpreter was started. The time is normally
returned in microseconds, but if the optional argument nsec
is nonzero it's returned in nanoseconds.
The actual accuracy on many systems is significantly less than
microseconds or nanoseconds. See System.REAL_TIME_RESOLUTION
.
_disable_threads()
, gethrtime()
int
gethrtime(void
|int
nsec
)
Return the high resolution real time since some arbitrary event in
the past. The time is normally returned in microseconds, but if
the optional argument nsec
is nonzero it's returned in
nanoseconds.
It's system dependent whether or not this time is monotonic, i.e.
if it's unaffected by adjustments of the calendaric clock in the
system. System.REAL_TIME_IS_MONOTONIC
tells what it is. Pike
tries to use monotonic time for this function if it's available.
The actual accuracy on many systems is significantly less than
microseconds or nanoseconds. See System.REAL_TIME_RESOLUTION
.
System.REAL_TIME_IS_MONOTONIC
, System.REAL_TIME_RESOLUTION
,
time()
, System.gettimeofday()
, gethrvtime()
,
Pike.implicit_gc_real_time
int
gethrvtime(void
|int
nsec
)
Return the CPU time that has been consumed by this process or
thread. -1 is returned if the system couldn't determine it. The
time is normally returned in microseconds, but if the optional
argument nsec
is nonzero it's returned in nanoseconds.
The CPU time includes both user and system time, i.e. it's
approximately the same thing you would get by adding together the
"utime" and "stime" fields returned by System.getrusage
(but
perhaps with better accuracy).
It's however system dependent whether or not it's the time
consumed in all threads or in the current one only;
System.CPU_TIME_IS_THREAD_LOCAL
tells which. If both types are
available then thread local time is preferred.
The actual accuracy on many systems is significantly less than
microseconds or nanoseconds. See System.CPU_TIME_RESOLUTION
.
The garbage collector might run automatically at any time. The
time it takes is not included in the figure returned by this
function, so that normal measurements aren't randomly clobbered
by it. Explicit calls to gc
are still included, though.
The special function gauge
is implemented with this function.
System.CPU_TIME_IS_THREAD_LOCAL
, System.CPU_TIME_RESOLUTION
,
gauge()
, System.getrusage()
, gethrtime()
int
getpid()
Returns the process ID of this process.
System.getppid()
, System.getpgrp()
array
(int
|string
) getpwnam(string
str
)
Get the user entry for login str
using the systemfunction getpwnam(3).
str
The login name of the user whos userrecord is requested.
An array with the information about the user
Array | |
| Users username (loginname) |
| User password (encrypted) |
| Users ID |
| Users primary group ID |
| Users real name an possibly some other info |
| Users home directory |
| Users shell |
getpwuid()
getpwent()
array
(int
|string
) getpwuid(int
uid
)
Get the user entry for UID uid
using the systemfunction getpwuid(3).
uid
The uid of the user whos userrecord is requested.
An array with the information about the user
Array | |
| Users username (loginname) |
| User password (encrypted) |
| Users ID |
| Users primary group ID |
| Users real name an possibly some other info |
| Users home directory |
| Users shell |
getpwnam()
getpwent()
string
getxattr(string
file
, string
attr
, void
|bool
symlink
)
Return the value of a specified attribute, or 0 if it does not exist.
bool
glob(string
glob
, string
str
)
string
glob(array
(string
) glob
, string
str
)
array
(string
) glob(string
glob
, array
(string
) str
)
array
(string
) glob(array
(string
) glob
, array
(string
) str
)
Match strings against a glob pattern.
glob
| The glob pattern. A question sign ('?') matches any character and an asterisk ('*') matches a string of arbitrary length. All other characters only match themselves. |
| the function returns the matching glob if any of the given patterns match. Otherwise 0. If the second argument is an array it will behave as if the first argument is a string (see below) |
str
|
|
| All strings in the array |
sscanf()
, Regexp
mapping
(string
:int
) gmtime(int
timestamp
)
Convert seconds since 00:00:00 UTC, Jan 1, 1970 into components.
This function works like localtime()
but the result is
not adjusted for the local time zone.
localtime()
, time()
, ctime()
, mktime()
,
strptime()
int
has_index(string
haystack
, int
index
)
int
has_index(array
haystack
, int
index
)
int
has_index(mapping
|multiset
|object
|program
haystack
, mixed
index
)
Search for index
in haystack
.
Returns 1
if index
is in the index domain of haystack
,
or 0
(zero) if not found.
This function is equivalent to (but sometimes faster than):
search(indices(haystack), index) != -1
A negative index in strings and arrays as recognized by the
index operators `[]()
and `[]=()
is not considered
a proper index by has_index()
has_value()
, has_prefix()
, has_suffix()
, indices()
,
search()
, values()
, zero_type()
int
has_prefix(string
|object
s
, string
prefix
)
Returns 1
if the string s
starts with prefix
,
returns 0
(zero) otherwise.
When s
is an object, it needs to implement
lfun::_sizeof()
and lfun::`[]
.
has_suffix()
, has_value()
, search()
int
has_suffix(string
s
, string
suffix
)
Returns 1
if the string s
ends with suffix
,
returns 0
(zero) otherwise.
has_prefix()
, has_value()
, search()
int
has_value(string
haystack
, string
value
)
int
has_value(string
haystack
, int
value
)
int
has_value(array
|mapping
|object
|program
haystack
, mixed
value
)
Search for value
in haystack
.
Returns 1
if value
is in the value domain of haystack
,
or 0
(zero) if not found.
This function is in all cases except when both arguments are strings equivalent to (but sometimes faster than):
search(values(haystack), value) != -1
If both arguments are strings, has_value()
is equivalent to:
search(haystack, value) != -1
has_index()
, indices()
, search()
, has_prefix()
,
has_suffix()
, values()
, zero_type()
int
hash(string
s
)
int
hash(string
s
, int
max
)
Return an integer derived from the string s
. The same string
always hashes to the same value, also between processes,
architectures, and Pike versions (see compatibility notes below,
though).
If max
is given, the result will be >= 0 and < max
,
otherwise the result will be >= 0 and <= 0x7fffffff.
The hash algorithm was changed in Pike 8.1. If you want a hash
that is compatible with Pike 8.0 and earlier, use hash_8_0()
.
The hash algorithm was also changed in Pike 7.5. If you want a hash
that is compatible with Pike 7.4 and earlier, use hash_7_4()
.
The difference with regards to hash_8_0()
only affects wide strings.
The hash algorithm was also changed in Pike 7.1. If you want a hash
that is compatible with Pike 7.0 and earlier, use hash_7_0()
.
This hash function differs from the one provided by hash_value()
,
in that hash_value()
returns a process specific value.
hash_7_0()
, hash_7_4()
, hash_8_0()
, hash_value
int
hash_7_0(string
s
)
int
hash_7_0(string
s
, int
max
)
Return an integer derived from the string s
. The same string
always hashes to the same value, also between processes.
If max
is given, the result will be >= 0 and < max
,
otherwise the result will be >= 0 and <= 0x7fffffff.
This function is provided for backward compatibility with code written for Pike up and including version 7.0.
This function is not NUL-safe, and is byte-order dependant.
hash()
, hash_7_4
int
hash_7_4(string
s
)
int
hash_7_4(string
s
, int
max
)
Return an integer derived from the string s
. The same string
always hashes to the same value, also between processes.
If max
is given, the result will be >= 0 and < max
,
otherwise the result will be >= 0 and <= 0x7fffffff.
This function is provided for backward compatibility with code written for Pike up and including version 7.4.
This function is byte-order dependant for wide strings.
hash_7_6()
, hash_7_0
int
hash_8_0(string
s
)
int
hash_8_0(string
s
, int
max
)
Return an integer derived from the string s
. The same string
always hashes to the same value, also between processes,
architectures, and Pike versions (see compatibility notes below,
though).
If max
is given, the result will be >= 0 and < max
,
otherwise the result will be >= 0 and <= 0x7fffffff.
Use hash_value()
for in-process hashing (eg, for implementing
lfun::_hash()
) or one of the cryptographic hash functions.
This function is really bad at hashing strings. Similar string often return similar hash values.
It is especially bad for url:s, paths and similarly formatted strings.
The hash algorithm was changed in Pike 7.5. If you want a hash
that is compatible with Pike 7.4 and earlier, use hash_7_4()
.
The difference only affects wide strings.
The hash algorithm was also changed in Pike 7.1. If you want a hash
that is compatible with Pike 7.0 and earlier, use hash_7_0()
.
This hash function differs from the one provided by hash_value()
,
in that hash_value()
returns a process specific value.
hash()
, hash_7_0()
, hash_7_4()
, hash_value
int
hash_value(mixed
value
)
Return a hash value for the argument. It's an integer in the native integer range.
The hash will be the same for the same value in the running process only (the memory address is typically used as the basis for the hash value).
If the value is an object with an lfun::__hash
, that function
is called and its result returned.
This is the hashing method used by mappings.
lfun::__hash()
int
is_absolute_path(string
p
)
Check if a path p
is fully qualified (ie not relative).
Returns 1 if the path is absolute, 0 otherwise.
constant
int
is_sql_null
SQL Null marker.
Replaced by is_val_null
.
constant
int
is_val_null
Nonzero recognition constant.
mixed
iterator_index(object
iter
)
Get the current index for iter
.
get_iterator()
bool
iterator_next(object
iter
)
Advance iter
one step.
get_iterator()
mixed
iterator_value(object
iter
)
Get the current value for iter
.
get_iterator()
bool
kill(int
pid
, int
signal
)
Send a signal to another process.
Some signals and their supposed purpose:
| Hang-up, sent to process when user logs out. |
| Interrupt, normally sent by ctrl-c. |
| Quit, sent by ctrl-\. |
| Illegal instruction. |
| Trap, mostly used by debuggers. |
| Aborts process, can be caught, used by Pike whenever something goes seriously wrong. |
| Emulation trap. |
| Floating point error (such as division by zero). |
| Really kill a process, cannot be caught. |
| Bus error. |
| Segmentation fault, caused by accessing memory where you shouldn't. Should never happen to Pike. |
| Bad system call. Should never happen to Pike. |
| Broken pipe. |
| Signal used for timer interrupts. |
| Termination signal. |
| Signal reserved for whatever you want to use it for. Note that some OSs reserve this signal for the thread library. |
| Signal reserved for whatever you want to use it for. Note that some OSs reserve this signal for the thread library. |
| Child process died. This signal is reserved for internal use by the Pike run-time. |
| Power failure or restart. |
| Window change signal. |
| Urgent socket data. |
| Pollable event. |
| Stop (suspend) process. |
| Stop (suspend) process. Sent by ctrl-z. |
| Continue suspended. |
| TTY input for background process. |
| TTY output for background process. |
| Virtual timer expired. |
| Profiling trap. |
| Out of CPU. |
| File size limit exceeded. |
| Stack fault |
| Success. |
| Failure. |
Note that you have to use signame to translate the name of a signal to its number.
Note that the kill function is not available on platforms that do not support signals. Some platforms may also have signals not listed here.
signal()
, signum()
, signame()
, fork()
int
|float
|object
limit(int
|float
|object
minval
, int
|float
|object
x
, int
|float
|object
maxval
)
Limits the value x
so that it's between minval
and maxval
.
If x
is an object, it must implement the lfun::`<
method.
max()
and min()
array
(string
) listxattr(string
file
, void
|bool
symlink
)
Return an array of all extended attributes set on the file
program
load_module(string
module_name
)
Load a binary module.
This function loads a module written in C or some other language into Pike. The module is initialized and any programs or constants defined will immediately be available.
When a module is loaded the C function pike_module_init() will be called to initialize it. When Pike exits pike_module_exit() will be called. These two functions must be available in the module.
The current working directory is normally not searched for
dynamic modules. Please use "./name.so"
instead of just
"name.so"
to load modules from the current directory.
mapping
(string
:int
) localtime(int
timestamp
)
Convert seconds since 00:00:00 UTC, 1 Jan 1970 into components.
This function returns a mapping with the following components:
| Seconds over the minute. |
| Minutes over the hour. |
| Hour of the day. |
| Day of the month. |
| Month of the year. |
| Year since 1900. |
| Day of week (0 = Sunday). |
| Day of the year. |
| Is daylight-saving time active. |
| Offset from UTC, including daylight-saving time adjustment. |
An error is thrown if the localtime(2) call failed on the system.
It's platform dependent what time ranges that function can handle,
e.g. Windows doesn't handle a negative timestamp
.
Prior to Pike 7.5 the field "timezone"
was sometimes not
present, and was sometimes not adjusted for daylight-saving time.
Calendar
, gmtime()
, time()
, ctime()
, mktime()
,
strptime()
float
log(int
|float
f
)
Return the natural logarithm of f
.
exp( log(x) ) == x
for x > 0.
pow()
, exp()
string
lower_case(string
s
)
int
lower_case(int
c
)
Convert a string or character to lower case.
Returns a copy of the string s
with all upper case characters
converted to lower case, or the character c
converted to lower
case.
Assumes the string or character to be coded according to
ISO-10646 (aka Unicode). If they are not, Charset.decoder
can
do the initial conversion for you.
Prior to Pike 7.5 this function only accepted strings.
upper_case()
, Charset.decoder
void
m_add(multiset
|object
l
, mixed
val
)
Add a member to a multiset.
m_delete()
void
m_clear(mapping
|multiset
|object
map
)
Clear the contents of a mapping or multiset.
This function clears the content of the mapping
or multiset map
so that it becomes empty.
This is an atomic operation.
If map
is an object lfun::_m_clear()
will be called
in it.
m_delete()
mixed
m_delete(object
|mapping
|multiset
map
, mixed
index
)
If map
is an object that implements lfun::_m_delete()
,
that function will be called with index
as its single argument.
Otherwise if map
is a mapping or multiset the entry with
index index
will be removed from map
destructively.
If the mapping or multiset does not have an entry with
index index
, nothing is done.
The value that was removed will be returned,
and UNDEFINED
otherwise.
Note that m_delete()
changes map
destructively.
mappingp()
mixed
map(mixed
arr
, void
|mixed
fun
, mixed
... extra
)
Applies fun
to the elements in arr
and collects the results.
arr
is treated as a set of elements, as follows:
fun
is applied in order to each element. The results are
collected, also in order, to a value of the same type as
arr
, which is returned.
fun
is applied to the values, and each result is assigned
to the same index in a new mapping, which is returned.
The program is treated as a mapping containing the identifiers that are indexable from it and their values.
If there is a lfun::cast
method in the object, it's
called to try to cast the object to an array, a mapping, or
a multiset, in that order, which is then handled as
described above.
fun
is applied in different ways depending on its type:
fun
is called for each element. It gets the current
element as the first argument and extra
as the rest. The
result of the call is collected.
fun
is used as a function like above, i.e. the
lfun::`()
method in it is called.
Each element of the fun
array will be called for each
element of arr
.
fun
is indexed with each element. The result of that is
collected.
Each element that is callable is called with extra
as
arguments. The result of the calls are collected. Elements
that aren't callable gets zero as result.
Each element is indexed with the given string. If the result
of that is zero then a zero is collected, otherwise it's
called with extra
as arguments and the result of that
call is collected.
This is typically used when arr
is a collection of
objects, and fun
is the name of some function in them.
The function is never destructive on arr
.
filter()
, enumerate()
, foreach()
object
master()
Return the current master object.
May return UNDEFINED
if no master has been loaded yet.
replace_master()
int
|float
|object
max(int
|float
|object
, int
|float
|object
... args
)
string
max(string
, string
... args
)
int(0..0)
max()
Returns the largest value among args
. Compared objects
must implement the lfun::`<
method.
min()
and limit()
int
|float
|object
min(int
|float
|object
, int
|float
|object
... args
)
string
min(string
, string
... args
)
int(0..0)
min()
Returns the smallest value among args
. Compared objects
must implement the lfun::`<
method.
max()
and limit()
mapping
mkmapping(array
ind
, array
val
)
Make a mapping from two arrays.
Makes a mapping ind[x]
:val[x]
, 0 <= x < sizeof(ind).
ind
and val
must have the same size.
This is the inverse operation of indices()
and values()
.
indices()
, values()
multiset
mkmultiset(array
a
)
This function creates a multiset from an array.
aggregate_multiset()
int
mktime(mapping
(string
:int
) tm
)
int
mktime(int
sec
, int
min
, int
hour
, int
mday
, int
mon
, int
year
, int
|void
isdst
, int
|void
tz
)
This function converts information about date and time into an integer which contains the number of seconds since 00:00:00 UTC, Jan 1, 1970.
You can either call this function with a mapping containing the following elements:
| Seconds over the minute. |
| Minutes over the hour. |
| Hour of the day. |
| Day of the month. |
| Month of the year. |
| Year since 1900. |
| Is daylight-saving time active. If omitted or set to |
| The timezone offset from UTC in seconds. If omitted, the time will be calculated in the local timezone. |
Or you can just send them all on one line as the second syntax suggests.
For proper UTC calculations ensure that isdst = 0
and
timezone = 0
; omitting either one of these parameters
will mess up the UTC calculation.
On some operating systems (notably AIX and Win32), dates before 00:00:00 UTC, Jan 1, 1970 are not supported.
On most 32-bit systems, the supported range of dates is from Dec 13, 1901 20:45:52 UTC through to Jan 19, 2038 03:14:07 UTC (inclusive).
On most 64-bit systems, the supported range of dates is expressed in 56 bits and is thus practically unlimited (at least up to 1141 milion years in the past and into the future).
time()
, ctime()
, localtime()
, gmtime()
, strftime()
string
normalize_path(string
path
)
Replaces "\" with "/" if runing on MS Windows. It is
adviced to use System.normalize_path
instead.
mixed
nth(int(0..)
n
)
Get the n
th entry in order.
An array ({ key, value })
.
bool
object_variablep(object
o
, string
var
)
Find out if an object identifier is a variable.
This function returns 1
if var
exists as a
non-protected variable in o
, and returns 0
(zero)
otherwise.
indices()
, values()
int
objectp(mixed
arg
)
Returns 1
if arg
is an object, 0
(zero) otherwise.
mappingp()
, programp()
, arrayp()
, stringp()
, functionp()
,
multisetp()
, floatp()
, intp()
int
|float
pow(float
|int
n
, float
|int
x
)
mixed
pow(object
n
, float
|int
|object
x
)
Return n
raised to the power of x
. If both n
and x
are integers the result will be an integer.
If n
is an object its pow method will be called with
x
as argument.
exp()
, log()
void
putenv(string
varname
, void
|string
value
)
Sets the environment variable varname
to value
.
If value
is omitted or zero, the environment variable
varname
is removed.
varname
and value
cannot be wide strings nor contain
'\0'
characters. varname
also cannot contain
'='
characters.
On NT the environment variable name is case insensitive.
getenv()
int
query_num_arg()
Returns the number of arguments given when the previous function was called.
This is useful for functions that take a variable number of arguments.
call_function()
array
random(mapping
m
)
float
random(float
max
)
int
random(int
max
)
mixed
random(object
o
)
mixed
random(array
|multiset
x
)
Get a random value generated by the default RandomSystem
.
RandomSystem()->random()
, random_string()
void
random_seed(int
seed
)
This function sets the initial value for the random generator.
random()
Random.Deterministic
string
random_string(int
len
)
Get a string of random characters 0..255
with the length len
from the default RandomSystem
.
RandomSystem()->random_string()
, random()
void
remove_include_path(string
tmp
)
Remove a directory to search for include files.
This function performs the reverse operation of add_include_path()
.
add_include_path()
void
remove_module_path(string
tmp
)
Remove a directory to search for modules.
This function performs the reverse operation of add_module_path()
.
add_module_path()
void
remove_program_path(string
tmp
)
Remove a directory to search for programs.
This function performs the reverse operation of add_program_path()
.
add_program_path()
void
removexattr(string
file
, string
attr
, void
|bool
symlink
)
Remove the specified extended attribute.
string
replace(string
s
, string
from
, string
to
)
string
replace(string
s
, array
(string
) from
, array
(string
) to
)
string
replace(string
s
, array
(string
) from
, string
to
)
string
replace(string
s
, mapping
(string
:string
) replacements
)
array
replace(array
a
, mixed
from
, mixed
to
)
mapping
replace(mapping
a
, mixed
from
, mixed
to
)
Generic replace function.
This function can do several kinds replacement operations, the different syntaxes do different things as follows:
If all the arguments are strings, a copy of s
with every
occurrence of from
replaced with to
will be returned.
Special case: to
will be inserted between every character in
s
if from
is the empty string.
If the first argument is a string, and the others array(string), a string
with every occurrance of from
[i] in s
replaced with
to
[i] will be returned. Instead of the arrays from
and to
a mapping equivalent to
can be
used.mkmapping
(from
, to
)
If the first argument is an array or mapping, the values of a
which
are `==()
with from
will be replaced with to
destructively.
a
will then be returned.
Note that replace()
on arrays and mappings is a destructive operation.
void
replace_master(object
o
)
Replace the master object with o
.
This will let you control many aspects of how Pike works, but beware that master.pike may be required to fill certain functions, so it is usually a good idea to have your master inherit the original master and only re-define certain functions.
FIXME: Tell how to inherit the master.
master()
string
reverse(string
s
, int
|void
start
, int
|void
end
)
array
reverse(array
a
, int
|void
start
, int
|void
end
)
int
reverse(int
i
, int
|void
start
, int
|void
end
)
mixed
reverse(object
o
, mixed
... options
)
Reverses a string, array or int.
s
String to reverse.
a
Array to reverse.
i
Integer to reverse.
o
Object to reverse.
start
Optional start index of the range to reverse.
Default: 0
(zero).
end
Optional end index of the range to reverse.
Default for strings: sizeof(s)-1
.
Default for arrays: sizeof(a)-1
.
Default for integers: Pike.get_runtime_info()->int_size - 1
.
options
Optional arguments that are to be passed to lfun::_reverse()
.
This function reverses a string, char by char, an array, value
by value or an int, bit by bit and returns the result. It's not
destructive on the input value. For objects it simply calls
lfun::_reverse()
in the object, and returns the result.
Reversing strings can be particularly useful for parsing difficult syntaxes which require scanning backwards.
sscanf()
float
round(int
|float
f
)
Return the closest integer value to f
.
round()
does not return an int
, merely an integer value
stored in a float
.
floor()
, ceil()
array
rows(mixed
data
, array
index
)
Select a set of rows from an array.
This function is en optimized equivalent to:
map(index, lambda(mixed x) { return data[x]; })
That is, it indices data on every index in the array index and returns an array with the results.
column()
int
search(string
haystack
, string
|int
needle
, int
|void
start
, int
|void
end
)
int
search(array
haystack
, mixed
needle
, int
|void
start
, int
|void
end
)
mixed
search(mapping
haystack
, mixed
needle
, mixed
|void
start
)
mixed
search(object
haystack
, mixed
needle
, mixed
|void
start
, mixed
... extra_args
)
Search for needle
in haystack
.
haystack
Item to search in. This can be one of:
| When |
| When |
| When |
| When If |
start
If the optional argument start
is present search is started at
this position. This has no effect on mappings.
end
If the optional argument end
is present, the search will terminate
at this position (exclusive) if not found earlier.
Returns the position of needle
in haystack
if found.
If not found the returned value depends on the type of haystack
:
|
|
|
|
| The value returned by |
If start
is supplied to an iterator object without an
lfun::_search()
, haystack
will need to implement
Iterator()->set_index()
.
For mappings and object UNDEFINED
will be returned when not found.
In all other cases -1
will be returned when not found.
indices()
, values()
, zero_type()
, has_value()
,
has_prefix()
, has_suffix()
int
set_priority(string
level
, int(0..)
|void
pid
)
array
|mapping
|multiset
set_weak_flag(array
|mapping
|multiset
m
, int
state
)
Set the value m
to use weak or normal references in its
indices and/or values (whatever is applicable). state
is a
bitfield built by using |
between the following flags:
| Use weak references for indices. Only applicable for multisets and mappings. |
| Use weak references for values. Only applicable for arrays and mappings. |
| Shorthand for |
If a flag is absent, the corresponding field will use normal
references. state
can also be 1
as a compatibility
measure; it's treated like Pike.WEAK
.
m
will be returned.
void
setxattr(string
file
, string
attr
, string
value
, int
flags
, void
|bool
symlink
)
Set the attribute attr
to the value value
.
The flags parameter can be used to refine the semantics of the operation.
Stdio.XATTR_CREATE
specifies a pure create, which
fails if the named attribute exists already.
Stdio.XATTR_REPLACE
specifies a pure replace operation, which
fails if the named attribute does not already exist.
By default (no flags), the extended attribute will be created if need be, or will simply replace the value if the attribute exists.
1 if successful, 0 otherwise, setting errno.
int
sgn(mixed
value
)
int
sgn(mixed
value
, mixed
zero
)
Check the sign of a value.
Returns -1
if value
is less than zero
,
1
if value
is greater than zero
and 0
(zero) otherwise.
abs()
function
(int
|void
:void
) signal(int
sig
, function
(int
|void
:void
) callback
)
function
(int
|void
:void
) signal(int
sig
)
Trap signals.
This function allows you to trap a signal and have a function called when the process receives a signal. Although it IS possible to trap SIGBUS, SIGSEGV etc, I advise you not to; Pike should not receive any such signals, and if it does, it is because of bugs in the Pike interpreter. And all bugs should be reported, no matter how trifle.
The callback will receive the signal number as its only argument.
See the documentation for kill()
for a list of signals.
If no second argument is given, the signal handler for that signal is restored to the default handler.
If the second argument is zero, the signal will be completely ignored.
Returns the previous signal function, or 0 if none had been registered.
kill()
, signame()
, signum()
string
signame(int
sig
)
Returns a string describing the signal sig
.
kill()
, signum()
, signal()
int
signum(string
sig
)
Get a signal number given a descriptive string.
This function is the inverse of signame()
.
signame()
, kill()
, signal()
float
sin(int
|float
f
)
Returns the sine value for f
.
f
should be specified in radians.
asin()
, cos()
, tan()
float
sinh(int
|float
f
)
Returns the hyperbolic sine value for f
.
asinh()
, cosh()
, tanh()
int
sizeof(string
arg
)
int
sizeof(array
arg
)
int
sizeof(mapping
arg
)
int
sizeof(multiset
arg
)
int
sizeof(object
arg
)
Size query.
The result will be as follows:
arg
can have any of the following types:
| The number of characters in |
| The number of elements in |
| The number of key-value pairs in |
| If |
lfun::_sizeof()
void
sleep(int
|float
s
, void
|int
abort_on_signal
)
This function makes the thread stop for s
seconds.
Only signal handlers can interrupt the sleep, and only when
abort_on_signal
is set. If more than one thread is running
the signal must be sent to the sleeping thread. Other callbacks
are not called during sleep.
If s
is zero then this thread will yield to other threads but
not sleep otherwise. Note that Pike yields internally at regular
intervals so it's normally not necessary to do this.
signal()
, delay()
array
sort(array
(mixed
) index
, array
(mixed
) ... data
)
Sort arrays destructively.
This function sorts the array index
destructively. That means
that the array itself is changed and returned, no copy is created.
If extra arguments are given, they are supposed to be arrays of the
same size as index
. Each of these arrays will be modified in the
same way as index
. I.e. if index 3 is moved to position 0 in index
index 3 will be moved to position 0 in all the other arrays as well.
The sort order is as follows:
Integers and floats are sorted in ascending order.
Strings are sorted primarily on the first characters that are different, and secondarily with shorter strings before longer. Different characters are sorted in ascending order on the character value. Thus the sort order is not locale dependent.
Arrays are sorted recursively on the first element. Empty arrays are sorted before nonempty ones.
Multisets are sorted recursively on the first index. Empty multisets are sorted before nonempty ones.
Objects are sorted in ascending order according to `<()
,
`>()
and `==()
.
Other types aren't reordered.
Different types are sorted in this order: Arrays, mappings,
multisets, objects, functions, programs, strings, types,
integers and floats. Note however that objects can control
their ordering wrt other types with `<
, `>
and `==
,
so this ordering of types only applies to objects without
those functions.
The first argument is returned.
The sort is stable, i.e. elements that are compare-wise equal aren't reordered.
Array.sort_array
, reverse()
string
sprintf(strict_sprintf_format
format
, sprintf_args
... args
)
Print formated output to string.
The format
string is a string containing a description of how to
output the data in args
. This string should generally speaking
have one %<modifiers><operator> format specifier
(examples: %s, %0d, %-=20s) for each of the arguments.
The following modifiers are supported:
| Zero pad numbers (implies right justification). | ||||||||
| Toggle truncation. | ||||||||
| Pad positive integers with a space. | ||||||||
| Pad positive integers with a plus sign. | ||||||||
| Left adjust within field size (default is right). | ||||||||
| Centered within field size. | ||||||||
| Column mode if strings are greater than field width. Breaks
between words (possibly skipping or adding spaces). Can not be
used together with | ||||||||
| Column mode with rough line break (break at exactly field width
instead of between words). Can not be used together with | ||||||||
| Table mode, print a list of | ||||||||
| Inverse table mode (left-to-right order). | ||||||||
| (Where n is a number or *) field width specifier. | ||||||||
| |||||||||
| Precision specifier. | ||||||||
| Column width specifier. | ||||||||
| If n is a * then next argument is used for precision/field
size. The argument may either be an integer, or a modifier mapping
as received by
| ||||||||
| Set a pad string. ' cannot be a part of the pad string (yet). | ||||||||
| Get pad string from argument list. | ||||||||
| Use same argument again. | ||||||||
| Repeat this on every line produced. | ||||||||
| Repeat this format for each element in the argument array. | ||||||||
| Put the string at the bottom end of column instead of top. | ||||||||
| Set width to the length of data. | ||||||||
| Select argument number n. Use * to use the next
argument as selector. The arguments are numbered starting from
|
The following operators are supported:
| Percent. |
| Signed binary integer. |
| Signed decimal integer. |
| Unsigned decimal integer. |
| Signed octal integer. |
| Lowercase signed hexadecimal integer. |
| Uppercase signed hexadecimal integer. |
| Character. If a fieldsize has been specified this will output the low-order bytes of the integer in network (big endian) byte order. To get little endian byte order, negate the field size. |
| Float. (Locale dependent formatting.) |
| Heuristically chosen representation of float. (Locale dependent formatting.) |
| Like %g, but uses uppercase E for exponent. |
| Exponential notation float. (Locale dependent output.) |
| Like %e, but uses uppercase E for exponent. |
| Binary IEEE representation of float (%4F gives single precision, %8F gives double precision) in network (big endian) byte order. To get little endian byte order, negate the field size. |
| String. |
| Quoted string. Escapes all control and non-8-bit characters, as well as the quote characters '\\' and '\"'. |
| Any value, debug style. Do not rely on the exact formatting;
how the result looks can vary depending on locale, phase of
the moon or anything else the |
| Hexadecimal representation of the memory address of the object. Integers and floats have no address, and are printed as themselves. |
| Binary Hollerith string. Equivalent to |
| No argument. Same as |
| Type of the argument. |
| Perform the enclosed format for every element of the argument array. |
|
Most modifiers and operators are combinable in any fashion, but some combinations may render strange results.
If an argument is an object that implements lfun::_sprintf()
, that
callback will be called with the operator as the first argument, and
the current modifiers as the second. The callback is expected to return
a string.
sprintf-style formatting is applied by many formatting functions, such
write()
and werror()
. It is also possible to get sprintf-style
compile-time argument checking by using the type-attributes
sprintf_format
or strict_sprintf_format
in combination
with sprintf_args
.
The 'q'
operator was added in Pike 7.7.
Support for specifying modifiers via a mapping was added in Pike 7.8.
This support can be tested for with the constant
String.__HAVE_SPRINTF_STAR_MAPPING__
.
Support for specifying little endian byte order to 'F'
was added in Pike 7.8. This support can be tested for with the
constant String.__HAVE_SPRINTF_NEGATIVE_F__
.
Pike v7.8 release 263 running Hilfe v3.5 (Incremental Pike Frontend) > sprintf("The unicode character %c has character code %04X.", 'A', 'A'); (1) Result: "The unicode character A has character code 0041." > sprintf("#%@02X is the HTML code for purple.", Image.Color.purple->rgb()); (2) Result: "#A020F0 is the HTML code for purple." > int n=4711; > sprintf("%d = hexadecimal %x = octal %o = %b binary", n, n, n, n); (3) Result: "4711 = hexadecimal 1267 = octal 11147 = 1001001100111 binary" > write(#"Formatting examples: Left adjusted [%-10d] Centered [%|10d] Right adjusted [%10d] Zero padded [%010d] ", n, n, n, n); Formatting examples: Left adjusted [4711 ] Centered [ 4711 ] Right adjusted [ 4711] Zero padded [0000004711] (5) Result: 142 int screen_width=70; > write("%-=*s\n", screen_width, >> "This will wordwrap the specified string within the "+ >> "specified field size, this is useful say, if you let "+ >> "users specify their screen size, then the room "+ >> "descriptions will automagically word-wrap as appropriate.\n"+ >> "slosh-n's will of course force a new-line when needed.\n"); This will wordwrap the specified string within the specified field size, this is useful say, if you let users specify their screen size, then the room descriptions will automagically word-wrap as appropriate. slosh-n's will of course force a new-line when needed. (6) Result: 355 > write("%-=*s %-=*s\n", screen_width/2, >> "Two columns next to each other (any number of columns will "+ >> "of course work) independantly word-wrapped, can be useful.", >> screen_width/2-1, >> "The - is to specify justification, this is in addherence "+ >> "to std sprintf which defaults to right-justification, "+ >> "this version also supports centre and right justification."); Two columns next to each other (any The - is to specify justification, number of columns will of course this is in addherence to std work) independantly word-wrapped, sprintf which defaults to can be useful. right-justification, this version also supports centre and right justification. (7) Result: 426 > write("%-$*s\n", screen_width, >> "Given a\nlist of\nslosh-n\nseparated\n'words',\nthis option\n"+ >> "creates a\ntable out\nof them\nthe number of\ncolumns\n"+ >> "be forced\nby specifying a\npresision.\nThe most obvious\n"+ >> "use is for\nformatted\nls output."); Given a list of slosh-n separated 'words', this option creates a table out of them the number of columns be forced by specifying a presision. The most obvious use is for formatted ls output. (8) Result: 312 > write("%-#*s\n", screen_width, >> "Given a\nlist of\nslosh-n\nseparated\n'words',\nthis option\n"+ >> "creates a\ntable out\nof them\nthe number of\ncolumns\n"+ >> "be forced\nby specifying a\npresision.\nThe most obvious\n"+ >> "use is for\nformatted\nls output."); Given a creates a by specifying a list of table out presision. slosh-n of them The most obvious separated the number of use is for 'words', columns formatted this option be forced ls output. (9) Result: 312 > sample = ([ "align":"left", "valign":"middle" ]); (10) Result: ([ /* 2 elements */ "align":"left", "valign":"middle" ]) > write("<td%{ %s='%s'%}>\n", (array)sample); <td valign='middle' align='left
lfun::_sprintf()
, strict_sprintf_format
, sprintf_format
,
sprintf_args
, String.__HAVE_SPRINTF_STAR_MAPPING__
,
String.__HAVE_SPRINTF_NEGATIVE_F__
.
constant
sprintf_args
Type constant used for typing extra arguments that are
sent to sprintf()
.
strict_sprintf_format
, sprintf_format
, sprintf()
constant
sprintf_format
Type constant used for typing arguments that are optionally
sent to sprintf()
depending on the presence of extra arguments.
strict_sprintf_format
, sprintf_args
, sprintf()
constant
sprintf_result
Type constant used for typing the return value from sprintf()
.
strict_sprintf_format
, sprintf_format
, sprintf()
float
sqrt(float
f
)
int
sqrt(int
i
)
mixed
sqrt(object
o
)
Returns the square root of f
, or in the integer case, the square root
truncated to the closest lower integer. If the argument is an object,
the lfun _sqrt in the object will be called.
pow()
, log()
, exp()
, floor()
, lfun::_sqrt
int
sscanf(string
data
, string
format
, mixed
... lvalues
)
The purpose of sscanf is to match a string data
against a format
string and place the matching results into a list of variables. The list
of lvalues
are destructively modified (which is only possible because
sscanf really is a special form, rather than a pike function) with the values
extracted from the data
according to the format
specification. Only
the variables up to the last matching directive of the format string are
touched.
The format
string may contain strings separated by special matching
directives like %d, %s %c and %f. Every such
directive corresponds to one of the lvalues
, in the order they are listed.
An lvalue is the name of a variable, a name of a local variable, an index
into an array, mapping or object. It is because of these lvalues that sscanf
can not be implemented as a normal function.
Whenever a percent character is found in the format string, a match is performed, according to which operator and modifiers follow it:
| Reads a binary integer ( |
| Reads a decimal integer ( |
| Reads an octal integer ( |
| Reads a hexadecimal integer ( |
| Reads an integer that is either octal (leading zero),
hexadecimal (leading |
| Reads one character and returns it as an integer
( |
| Returns the current character offset in |
| Reads a float ("0101" makes 101.0). |
| Reads a float encoded according to the IEEE single precision
binary format ( |
| Reads a string. If followed by %d, %s will only read non-numerical characters. If followed by a %[], %s will only read characters not present in the set. If followed by normal text, %s will match all characters up to but not including the first occurrence of that text. |
| Reads a Hollerith-encoded string, i.e. first reads the length
of the string and then that number of characters. The size and
byte order of the length descriptor can be modified in the
same way as %c. As an example |
| Matches a string containing a given set of characters (those given
inside the brackets). Ranges of characters can be defined by using
a minus character between the first and the last character to be
included in the range. Example: |
| Repeatedly matches 'format' as many times as possible and assigns an array of arrays with the results to the lvalue. |
| Match a Pike constant, such as string or integer (currently only integer, string and character constants are functional). |
| Match a single percent character (hence this is how you quote the % character to just match, and not start an lvalue matcher directive). |
Similar to sprintf
, you may supply modifiers between the % character
and the operator, to slightly change its behaviour from the default:
| The operator will only match its argument, without assigning any variable. |
| You may define a field width by supplying a numeric modifier.
This means that the format should match that number of
characters in the input data; be it a number characters
long string, integer or otherwise ( |
| Supplying a minus sign toggles the decoding to read the data encoded in little-endian byte order, rather than the default network (big-endian) byte order. |
| Interpret the data as a signed entity. In other words,
|
| Ignore the matched characters with respect to any following
|
Sscanf does not use backtracking. Sscanf simply looks at the format string up to the next % and tries to match that with the string. It then proceeds to look at the next part. If a part does not match, sscanf immediately returns how many % were matched. If this happens, the lvalues for % that were not matched will not be changed.
// a will be assigned "oo" and 1 will be returned sscanf("foo", "f%s", a); // a will be 4711 and b will be "bar", 2 will be returned sscanf("4711bar", "%d%s", a, b); // a will be 4711, 2 will be returned sscanf("bar4711foo", "%*s%d", a); // a will become "test", 2 will be returned sscanf(" \t test", "%*[ \t]%s", a); // Remove "the " from the beginning of a string // If 'str' does not begin with "the " it will not be changed sscanf(str, "the %s", str); // It is also possible to declare a variable directly in the sscanf call; // another reason for sscanf not to be an ordinary function: sscanf("abc def", "%s %s", string a, string b);
The number of directives matched in the format string. Note that a string directive (%s or %[]) counts as a match even when matching just the empty string (which either may do).
sprintf
, array_sscanf
string(1..255)
strftime(string(1..255)
format
, mapping
(string
:int
) tm
)
Convert the structure to a string.
The abbreviated weekday name according to the current locale
The full weekday name according to the current locale.
The abbreviated month name according to the current locale.
The full month name according to the current locale.
The preferred date and time representation for the current locale.
The century number (year/100) as a 2-digit integer.
The day of the month as a decimal number (range 01 to 31).
Equivalent to %m/%d/%y
. (for Americans only.
Americans should note that in other countries %d/%m/%y
is rather common. This means that in international context
this format is ambiguous and should not be used.)
Like %d
, the day of the month as a decimal number,
but a leading zero is replaced by a space.
Modifier: use alternative format, see below.
Equivalent to %Y-%m-%d (the ISO 8601 date format). (C99)
The ISO 8601 week-based year (see NOTES) with century as a
decimal number. The 4-digit year corresponding to the ISO
week number (see %V
). This has the same format and
value as %Y
, except that if the ISO week number
belongs to the previous or next year, that year is used instead.
Like %G
, but without century, that is,
with a 2-digit year (00-99). (TZ)
Equivalent to %b.
The hour as a decimal number using a 24-hour clock (range 00 to 23).
The hour as a decimal number using a 12-hour clock (range 01 to 12).
The day of the year as a decimal number (range 001 to 366).
The month as a decimal number (range 01 to 12).
The minute as a decimal number (range 00 to 59).
A newline character. (SU)
Modifier: use alternative format, see below. (SU)
Either "AM"
or "PM"
according to the given time
value, or the corresponding strings for the current locale.
Noon is treated as "PM"
and midnight as "AM"
.
Like %p
but in lowercase: "am"
or "pm"
or a corresponding string for the current locale.
The time in a.m. or p.m. notation. In the POSIX locale this is
equivalent to %I:%M:%S %p
.
The time in 24-hour notation (%H:%M
). (SU)
For a version including the seconds, see %T
below.
The number of seconds since the Epoch, 1970-01-01 00:00:00 +0000 (UTC). (TZ)
The second as a decimal number (range 00 to 60). (The range is up to 60 to allow for occasional leap seconds.)
A tab character. (SU)
The time in 24-hour notation (%H:%M:%S
). (SU)
The day of the week as a decimal, range 1 to 7, Monday being 1.
See also %w
. (SU)
The week number of the current year as a decimal number,
range 00 to 53, starting with the first Sunday as the first
day of week 01. See also %V
and %W
.
The ISO 8601 week number of the current year as a decimal number,
range 01 to 53, where week 1 is the first week that has at least
4 days in the new year. See also %U
and %W
.
The day of the week as a decimal, range 0 to 6, Sunday being 0.
See also %u
.
ctime()
, mktime()
, strptime()
, Gettext.setlocale
constant
strict_sprintf_format
Type constant used for typing arguments that are always
sent to sprintf()
regardless of the presence of extra arguments.
sprintf_format
, sprintf_args
, sprintf()
string(1..)
string_filter_non_unicode(string
s
)
Replace the most obviously non-unicode characters from s
with
the unicode replacement character.
This will replace characters outside the ranges
0x00000000-0x0000d7ff
and 0x0000e000-0x0010ffff
with 0xffea (the replacement character).
Charset.encoder()
, string_to_unicode()
,
unicode_to_string()
, utf8_to_string()
, string_to_utf8()
string(8bit)
string_to_unicode(string
s
, int(0..2)
|void
byteorder
)
Converts a string into an UTF16 compliant byte-stream.
s
String to convert to UTF16.
byteorder
Byte-order for the output. One of:
| Network (aka big-endian) byte-order (default). |
| Little-endian byte-order. |
| Native byte-order. |
Throws an error if characters not legal in an UTF16 stream are encountered. Valid characters are in the range 0x00000 - 0x10ffff, except for characters 0xfffe and 0xffff.
Characters in range 0x010000 - 0x10ffff are encoded using surrogates.
Charset.decoder()
, string_to_utf8()
, unicode_to_string()
,
utf8_to_string()
utf8_string
string_to_utf8(string
s
)
utf8_string
string_to_utf8(string
s
, int
extended
)
Convert a string into a UTF-8 compliant byte-stream.
s
String to encode into UTF-8.
extended
Bitmask with extension options.
| Accept and encode the characters outside the valid ranges using the same algorithm. Such encoded characters are however not UTF-8 compliant. |
| Encode characters outside the BMP with UTF-8 encoded UTF-16 (ie split them into surrogate pairs and encode). |
Throws an error if characters not valid in an UTF-8 stream are
encountered. Valid characters are in the ranges
0x00000000-0x0000d7ff
and 0x0000e000-0x0010ffff
.
Charset.encoder()
, string_to_unicode()
,
unicode_to_string()
, utf8_to_string()
int
stringp(mixed
arg
)
Returns 1
if arg
is a string, 0
(zero) otherwise.
intp()
, programp()
, arrayp()
, multisetp()
, objectp()
,
mappingp()
, floatp()
, functionp()
mapping
(string
:int
) strptime(string(1..255)
data
, string(1..255)
format
)
Parse the given data
using the format in format
as a date.
The % character.
The weekday name according to the C locale, in abbreviated form or the full name.
The month name according to the C locale, in abbreviated form or the full name.
The date and time representation for the C locale.
The century number (0-99).
The day of month (1-31).
Equivalent to %m/%d/%y.
The hour (0-23).
The hour on a 12-hour clock (1-12).
The day number in the year (1-366).
The month number (1-12).
The minute (0-59).
Arbitrary whitespace.
The C locale's equivalent of AM or PM.
Equivalent to %H:%M.
The second (0-60; 60 may occur for leap seconds; earlier also 61 was allowed).
Arbitrary whitespace.
Equivalent to %H:%M:%S.
The week number with Sunday the first day of the week (0-53).
The weekday number (0-6) with Sunday = 0.
The week number with Monday the first day of the week (0-53).
The date, using the C locale's date format.
The time, using the C locale's time format.
The year within century (0-99). When a century is not otherwise specified, values in the range 69-99 refer to years in the twentieth century (1969-1999); values in the range 00-68 refer to years in the twenty-first century (2000-2068).
The year, including century (for example, 1991).
localtime()
, gmtime()
, strftime()
float
tan(int
|float
f
)
Returns the tangent value for f
.
f
should be specified in radians.
atan()
, sin()
, cos()
float
tanh(int
|float
f
)
Returns the hyperbolic tangent value for f
.
atanh()
, sinh()
, cosh()
constant
this
Builtin read only variable that evaluates to the current object.
this_program
, this_object()
constant
this_function
Builtin constant that evaluates to the current function.
this
, this_object()
object
this_object(void
|int
level
)
Returns the object we are currently evaluating in.
level
level
may be used to access the object of a surrounding
class: The object at level 0 is the current object, the object
at level 1 is the one belonging to the class that surrounds
the class that the object comes from, and so on.
As opposed to a qualified this
reference such as
global::this
, this function doesn't always access the
objects belonging to the lexically surrounding classes. If the
class containing the call has been inherited then the objects
surrounding the inheriting class are accessed.
constant
this_program
Builtin constant that evaluates to the current program.
this
, this_object()
mixed
|void
throw(mixed
value
)
Throw value
to a waiting catch
.
If no catch
is waiting the global error handling will send the
value to master()->handle_error()
.
If you throw an array with where the first index contains an error
message and the second index is a backtrace, (the output from
backtrace()
) then it will be treated exactly like a real error
by overlying functions.
catch
int
time()
int
time(int(1..1)
one
)
float
time(int(2..)
t
)
This function returns the number of seconds since 00:00:00 UTC, 1 Jan 1970.
The second syntax does not query the system for the current
time, instead the last time value used by the pike process is returned
again. It avoids a system call, and thus is slightly faster,
but can be wildly inaccurate. Pike
queries the time internally when a thread has waited for
something, typically in sleep
or in a backend (see
Pike.Backend
).
The third syntax can be used to measure time more precisely than one
second. It returns how many seconds have passed since t
. The precision
of this function varies from system to system.
ctime()
, localtime()
, mktime()
, gmtime()
,
System.gettimeofday()
, gethrtime()
int
trace(int
level
, void
|string
facility
, void
|int
all_threads
)
This function changes the trace level for the subsystem identified
by facility
to level
. If facility
is zero or left out, it
changes the global trace level which affects all subsystems.
Enabling tracing causes messages to be printed to stderr. A higher trace level includes the output from all lower levels. The lowest level is zero which disables all trace messages.
See the -t command-line option for more information.
level
If facility
is specified then there is typically only one
trace level for it, i.e. it's an on-or-off toggle. The global
trace levels, when facility
isn't specified, are:
| Trace calls to Pike functions and garbage collector runs. |
| Trace calls to builtin functions. |
| Trace every interpreted opcode. |
| Also trace the opcode arguments. |
facility
Valid facilities are:
| Trace the doings of the garbage collector. The setting is
never thread local.
|
all_threads
Trace levels are normally thread local, so changes affect only the current thread. To change the level in all threads, pass a nonzero value in this argument.
The old trace level in the current thread is returned.
int
ualarm(int
useconds
)
Set an alarm clock for delivery of a signal.
alarm()
arranges for a SIGALRM signal to be delivered to the
process in useconds
microseconds.
If useconds
is 0
(zero), no new alarm will be scheduled.
Any previous alarms will in any case be canceled.
Returns the number of microseconds remaining until any previously scheduled alarm was due to be delivered, or zero if there was no previously scheduled alarm.
This function is only available on platforms that support signals.
alarm()
, signal()
, call_out()
string
unicode_to_string(string(8bit)
s
, int(0..2)
|void
byteorder
)
Converts an UTF16 byte-stream into a string.
s
String to convert to UTF16.
byteorder
Default input byte-order. One of:
| Network (aka big-endian) byte-order (default). |
| Little-endian byte-order. |
| Native byte-order. |
Note that this argument is disregarded if s
starts with a BOM.
Charset.decoder()
, string_to_unicode()
, string_to_utf8()
,
utf8_to_string()
string
upper_case(string
s
)
int
upper_case(int
c
)
Convert a string or character to upper case.
Returns a copy of the string s
with all lower case characters
converted to upper case, or the character c
converted to upper
case.
Assumes the string or character to be coded according to
ISO-10646 (aka Unicode). If they are not, Charset.decoder
can
do the initial conversion for you.
Prior to Pike 7.5 this function only accepted strings.
lower_case()
, Charset.decoder
string
utf8_to_string(utf8_string
s
)
string
utf8_to_string(utf8_string
s
, int
extended
)
Converts an UTF-8 byte-stream into a string.
s
String of UTF-8 encoded data to decode.
extended
Bitmask with extension options.
| Accept and decode the extension used by |
| Accept and decode UTF-8 encoded UTF-16 (ie accept and decode valid surrogates). |
Throws an error if the stream is not a legal UTF-8 byte-stream.
In conformance with RFC 3629 and Unicode 3.1 and later, non-shortest forms are not decoded. An error is thrown instead.
Charset.encoder()
, string_to_unicode()
, string_to_utf8()
,
unicode_to_string()
, validate_utf8()
bool
validate_utf8(utf8_string
s
)
bool
validate_utf8(utf8_string
s
, int
extended
)
Checks whether a string is a valid UTF-8 byte-stream.
s
String of UTF-8 encoded data to validate.
extended
Bitmask with extension options.
| Accept the extension used by |
| Accept UTF-8 encoded UTF-16 (ie accept valid surrogate-pairs). |
Returns 0
(zero) if the stream is not a legal
UTF-8 byte-stream, and 1
if it is.
In conformance with RFC 3629 and Unicode 3.1 and later, non-shortest forms are considered invalid.
Charset.encoder()
, string_to_unicode()
, string_to_utf8()
,
unicode_to_string()
, utf8_to_string()
string
version()
Report the version of Pike. Does the same as
sprintf("Pike v%d.%d release %d", __REAL_VERSION__,
__REAL_MINOR__, __REAL_BUILD__);
__VERSION__
, __MINOR__
, __BUILD__
,
__REAL_VERSION__
, __REAL_MINOR__
, __REAL_BUILD__
,
int
werror(string
fmt
, mixed
... args
)
Writes a string on stderr. Works just like Stdio.File.write
on Stdio.stderr
.
int
write(string
fmt
, mixed
... args
)
Writes a string on stdout. Works just like Stdio.File.write
on Stdio.stdout
.
typedef
int(0..0)
zero
Zero datatype.
Boolean datatype.
constant
false
constant
true
An Encoder
and a Decoder
lumped into a single instance which
can be used for both encoding and decoding.
inherit Decoder : Decoder
inherit Encoder : Encoder
Objects used by the compiler to handle references to global symbols, modules, external files, etc.
There can be up to three compilation handlers active at the same time during a compilation. They are in order of precedence:
The error handler
This is the object passed to compile()
as
the second argument (if any). This object is returned by
get_active_error_handler()
during a compilation.
The compatibility handler
This is the object returned by
master()->get_compilation_handler()
(if any), which
the compiler calls when it sees #pike-directives,
or expressions using the version scope
(eg 7.4::rusage
). This object is returned by
get_active_compilation_handler()
during a compilation.
The master object.
This is returned by master()
at any time.
Any of the objects may implement a subset of the CompilationHandler
functions, and the first object that implements a function will be
used. The error handler object can thus be used to block certain
functionality (eg to restrict the number of available functions).
master()->get_compilation_handler()
, get_active_error_handler()
,
get_active_compilation_handler()
, compile()
void
compile_error(string
filename
, int
line
, string
msg
)
Called by compile()
and cpp()
when they encounter
errors in the code they compile.
filename
File where the error was detected.
line
Line where the error was detected.
msg
Description of error.
compile_warning()
.
void
compile_exception(mixed
exception
)
Called by compile()
and cpp()
if they trigger
exceptions.
void
compile_warning(string
filename
, int
line
, string
msg
)
Called by compile()
to report warnings.
filename
File which triggered the warning.
line
Line which triggered the warning.
msg
Warning message.
compile_error()
mapping
(string
:mixed
)|object
get_default_module()
Returns the default module from which global symbols will be fetched.
Returns the default module, or 0
(zero).
If 0
(zero) is returned the compiler use the mapping
returned by all_constants()
as fallback.
get_predefines()
mapping
(string
:mixed
) get_predefines()
Called by cpp()
to get the set of global symbols.
Returns a mapping from symbol name to symbol value. Returns zero on failure.
resolv()
, get_default_module()
mixed
handle_import(string
path
, string
filename
, CompilationHandler
handler
)
Called by compile()
and cpp()
to handle import
directives specifying specific paths.
Returns the resolved value, or UNDEFINED
on failure.
string
handle_include(string
header_file
, string
current_file
, bool
is_local_ref
)
Called by cpp()
to resolv #include
and #string
directives.
header_file
File that was requested for inclusion.
current_file
File where the directive was found.
is_local_ref
Specifies reference method.
| Directive was |
| Directive was |
Returns the filename to pass to read_include()
if found,
and 0
(zero) on failure.
read_include()
string
read_include(string
filename
)
Called by cpp()
to read included files.
filename
Filename as returned by handle_include()
.
Returns a string with the content of the header file on success,
and 0
(zero) on failure.
handle_include()
mixed
resolv(string
symbol
, string
filename
, CompilationHandler
handler
)
Called by compile()
and cpp()
to resolv
module references.
Returns the resolved value, or UNDEFINED
on failure.
get_predefines()
predef::CompilerEnvironment
that supports handlers.
The compiler environment.
By inheriting this class and overloading the functions, it is possible to make a custom Pike compiler.
Prior to Pike 7.8 this sort of customization has to be done
either via custom master objects, or via CompilationHandler
s.
CompilationHandler
, MasterObject
, master()
, replace_master()
program
compile(string
source
, object
|void
handler
, int
|void
major
, int
|void
minor
, program
|void
target
, object
|void
placeholder
)
program
compile(string
source
, CompilationHandler
|void
handler
, int
|void
major
, int
|void
minor
, program
|void
target
, object
|void
placeholder
)
Compile a string to a program.
This function takes a piece of Pike code as a string and compiles it into a clonable program.
The optional argument handler
is used to specify an alternative
error handler. If it is not specified the current master object will
be used.
The optional arguments major
and minor
are used to tell the
compiler to attempt to be compatible with Pike major
.minor
.
This function essentially performs
program compile(mixed ... args)
{
return PikeCompiler(@args)->compile();
}
Note that source
must contain the complete source for a program.
It is not possible to compile a single expression or statement.
Also note that compile()
does not preprocess the program.
To preprocess the program you can use compile_string()
or
call the preprocessor manually by calling cpp()
.
compile_string()
, compile_file()
, cpp()
, master()
,
CompilationHandler
int
compile_exception(mixed
err
)
string
format_exception(mixed
err
)
object
get_compilation_handler(int
major
, int
minor
)
Get compatibility handler for Pike major
.minor
.
The default implementation calls the corresponding function in the master object.
This function is typically called by
PikeCompiler()->get_compilation_handler()
.
MasterObject()->get_compilation_handler()
.
mapping
(string
:mixed
)|object
get_default_module()
Get the default module for the current compatibility level
(ie typically the value returned by predef::all_constants()
).
The default implementation calls the corresponding function in the master object.
| Constant table to use. |
| Use the builtin constant table. |
This function is typically called by
Pike_compiler()->get_default_module()
.
MasterObject()->get_default_module()
.
program
handle_import(string
module
, string
current_file
, object
|void
handler
)
Look up an import module
.
The default implementation calls the corresponding function in the master object.
MasterObject()->handle_import()
.
program
handle_import(string
module
, string
current_file
, object
|void
handler
, object
|void
compat_handler
)
program
handle_inherit(string
inh
, string
current_file
, object
|void
handler
)
Look up an inherit inh
.
The default implementation calls the corresponding function in the master object.
MasterObject()->handle_inherit()
.
program
handle_inherit(string
inh
, string
current_file
, object
|void
handler
, object
|void
compat_handler
)
inherit predef::CompilerEnvironment : OrigCompilerEnvironment
inherit Reporter : Reporter
Implements the Reporter
API.
Reporter()->report()
, Reporter()->SeverityLevel
mixed
resolv(string
identifier
, string
filename
, object
|void
handler
, object
|void
compat_handler
)
mixed
resolv(string
identifier
, string
filename
, object
|void
handler
, object
|void
compat_handler
)
Look up identifier
in the current context.
The default implementation calls the corresponding function in the handlers (if any), falling back to the master object.
Returns the value of the identifier
if found, and
UNDEFINED
if not.
The state for an instance of the preprocessor.
predef::cpp()
protected
mixed
apply_handler(string
fun
, mixed
... args
)
void
change_cpp_compatibility(int
major
, int
minor
)
void
change_cpp_compatibility(int
major
, int
minor
)
Change the pike compatibility level for this preprocessor to the specified version of Pike.
major
Major version of Pike to attempt to be compatible with.
Specifying a major version of -1
is a short hand
for specifying __REAL_MAJOR__
and __REAL_MINOR__
.
minor
Minor version of Pike to attempt to be compatible with.
This function is called by the preprocessor to set the compatibility level.
The default implementation performs some normalization, and
then sets compat_major
and compat_minor
to their
respective values (which in turn affects symbols such as
__MAJOR__
and __MINOR__
).
void
clear_macros()
Clear the set of macros.
It is recomended to call this function when the CPP
object
is no longer to be used.
define_macro()
object
CompilerEnvironment.CPP.handler
object
CompilerEnvironment.CPP.compat_handler
int
compile_exception(mixed
err
)
void
cpp_error(sprintf_format
msg
, sprintf_args
... arguments
)
Convenience function for reporting a cpp error at the current position.
This function calls report()
with the same arguments,
but prefixed with suitable defaults.
report()
CompilerEnvironment.CPP CompilerEnvironment.CPP(
string
|void
current_file
, int
|string
|void
charset
, object
|void
handler
, void
|int
compat_major
, void
|int
compat_minor
, void
|int
picky_cpp
)
CompilerEnvironment.CPP CompilerEnvironment.CPP(
mapping
(string
:mixed
) options
)
Initialize the preprocessor.
options
If the first argument is a mapping, no other arguments may follow. Instead, they have to be given as members of the mapping (if wanted). The following members are then recognized:
| Name of the current file. It is used for generating #line directives and for locating include files. |
| Charset to use when processing |
| Compilation handler. |
| Sets the major pike version used for compat handling. |
| Sets the minor pike version used for compat handling. |
| Generate more warnings. |
| This option keeps |
| If a prefix is given, only prefixed directives will be
processed. For example, if the prefix is |
current_file
If the current_file
argument has not been specified,
it will default to "-"
.
charset
Turn on automatic character set detection if 1
, otherwise
specifies the character set used by the input.
Defaults to "ISO-10646"
.
compile()
CompilerEnvironment.CPP CompilerEnvironment.CPP(
string
|void
current_file
, int
|string
|void
charset
, object
|void
handler
, void
|int
compat_major
, void
|int
compat_minor
, void
|int
picky_cpp
)
CompilerEnvironment.CPP CompilerEnvironment.CPP(
mapping
(string
:mixed
) options
)
Initialize the preprocessor.
options
If the first argument is a mapping, no other arguments may follow. Instead, they have to be given as members of the mapping (if wanted). The following members are then recognized:
| Name of the current file. It is used for generating #line directives and for locating include files. |
| Charset to use when processing |
| Compilation handler. |
| Sets the major pike version used for compat handling. |
| Sets the minor pike version used for compat handling. |
| Generate more warnings. |
| This option keeps |
| If a prefix is given, only prefixed directives will be
processed. For example, if the prefix is |
| Mapping of predefined macros in addition to those
returned by |
current_file
If the current_file
argument has not been specified,
it will default to "-"
.
charset
Turn on automatic character set detection if 1
, otherwise
specifies the character set used by the input.
Defaults to "ISO-10646"
.
compile()
void
define_ansi_macros()
Adds some cpp macros defined by the ANSI-C standards,
such as __FILE__
, __LINE__
, etc.
define_macro()
, define_pike_macros()
void
define_macro(string
name
, string
|object
|array
|function
(:void
)|void
value
, int(-1..)
|void
numargs
, int(2bit)
|void
flags
)
Define a cpp macro.
name
Name of macro to define. Ending the name with "()"
changes the defaults for numargs
and flags
to
0
and 3
respectively.
value
Macro definition. Defaults to "1"
.
numargs
Number of required arguments to a function-style macro.
-1
indicates not function-style.
Defaults to -1
.
flags
Bit-wise or of flags affecting the macro behavior:
| Function style macro with a variable number of arguments.
Invalid if |
| Keep newlines emitted by the macro. |
Defaults to 0
.
define_multiple_macros()
void
define_multiple_macros(mapping
(string
:string
|function
(:void
)|object
)|void
predefs
)
Define multiple macros in one operation.
predefs
Macros to define.
define_macro()
, CompilationHandler()->get_predefines()
,
_take_over_initial_predefines()
void
define_pike_macros()
Adds some pike-specific cpp macros,
such as __DIR__
, __VERSION__
, [__PIKE__], etc.
define_macro()
, define_ansi_macros()
string
format_exception(mixed
err
)
string
format_exception(mixed
err
)
Format an exception caught by cpp as a suitable cpp error message.
err
Caught value.
Returns one of:
| Generate a cpp error using the default format (ie call
|
| Cpp error message to |
The default implementation just returns 0
.
object
get_compilation_handler(int
major
, int
minor
)
mapping
(string
:string
|function
(:void
)|object
) get_predefines()
mapping
(string
:string
|function
(:void
)|object
) get_predefines()
Get the predefined macros for this preprocessor.
This function is called by init_pike_cpp()
to
retrieve the set of macros to define at initialization.
The default implementation returns the internal set of
predefined macros unless _take_over_initial_predefines()
has been called, in which case it instead calls the
corresponding function in the master.
This function does NOT return the set of currently defined macros.
init_pike_cpp()
, define_multiple_macros()
,
_take_over_initial_predefines()
string
handle_include(string
header_file
, string
current_file
, bool
is_local_ref
)
inherit ::this_program : this_program
void
init_pike_cpp()
Convenience function for initializing the preprocessor to Pike defaults.
The default implementation is essentially:
{
define_ansi_macros();
define_pike_macros();
define_multiple_macros(get_predefines());
}
string
read_include(string
filename
)
void
report(SeverityLevel
severity
, string
filename
, int(1..)
linenumber
, string
subsystem
, sprintf_format
message
, sprintf_args
... extra_args
)
Report a diagnostic from the preprocessor.
severity
The severity of the diagnostic.
filename
linenumber
Location which triggered the diagnostic.
subsystem
Typically "cpp"
.
message
String with the diagnostic message, with optional
sprintf()
-style formatting (if any extra_args
).
extra_args
Extra arguments to sprintf()
.
The default implementation does the following:
If there's a handler which implements Reporter()->report()
,
call it with the same arguments.
Otherwise if there's a handler which implements
compile_warning()
or compile_error()
that matches
severity
, call it with suitable arguments.
Otherwise if there's a compat handler, use it in the same manner as the handler.
Otherwise fall back to calling ::report()
with the
same arguments.
In Pike 8.0 and earlier MasterObject()->report()
was not called.
Reporter()->report()
void
report(SeverityLevel
severity
, string
filename
, int(1..)
linenumber
, string
subsystem
, string
message
, mixed
... extra_args
)
Report a diagnostic from the preprocessor.
severity
The severity of the diagnostic.
filename
linenumber
Location which triggered the diagnostic.
subsystem
Always "cpp"
.
message
String with the diagnostic message, with optional
sprintf()
-style formatting (if any extra_args
).
extra_args
Extra arguments to sprintf()
.
The default implementation just calls
CompilerEnviroment::report()
in the parent with the
same arguments.
Reporter()->report()
, cpp_error()
mixed
resolv(string
sym
)
mixed
resolv(string
sym
)
Attempt to resolve a symbol.
The default implementation calls CompilerEnvironment()->resolv()
in the parent object, with the remaining arguments taken from the
current CPP
context.
Returns the value of sym
if found, and UNDEFINED
if not.
The Pike compiler.
An object of this class compiles a single string of Pike code.
type
apply_attribute_constant(string
attr
, mixed
value
, type
arg_type
, void
cont_type
)
Handle constant arguments to attributed function argument types.
attr
Attribute that arg_type
had.
value
Constant value sent as parameter.
arg_type
Declared type of the function argument.
cont_type
Continuation function type after the current argument.
This function is called when a function is called
with the constant value value
and it has been
successfully matched against arg_type
,
and arg_type
had the type attribute attr
.
This function is typically used to perform specialized
argument checking and to allow for a strengthening
of the function type based on value
.
The default implementation implements the "sprintf_format"
,
"sscanf_format"
and "sscanf_76_format"
attributes.
Returns a continuation type if it succeeded in strengthening the type.
Returns UNDEFINED otherwise (this is not an error indication).
pop_type_attribute()
, push_type_attribute()
protected
mixed
apply_handler(string
fun
, mixed
... args
)
bool
apply_type_attribute(string
attribute
, type
a
, type
|void
b
)
Type attribute handler.
attribute
Attribute that a
had.
a
Type of the value being called.
b
Type of the first argument in the call, or
UNDEFINED
if no more arguments.
Called during type checking when a
has been successfully
had a partial evaluation with the argument b
and
a
had the type attribute attribute
before the
evaluation.
The default implementation implements the "deprecated" attribute.
Returns 1
if the type check should be allowed
(ie __attribute__(attribute, a)(b)
) is valid,
and 0
(zero) otherwise.
pop_type_attribute()
, push_type_attribute()
void
change_compiler_compatibility(int
major
, int
minor
)
void
change_compiler_compatibility(int
major
, int
minor
)
Change compiler to attempt to be compatible with Pike major
.minor
.
object
CompilerEnvironment.PikeCompiler.handler
object
CompilerEnvironment.PikeCompiler.compat_handler
program
compile()
Compile the current source into a program.
This function compiles the current Pike source code into a clonable program.
compile_string()
, compile_file()
, cpp()
, master()
,
CompilationHandler
, create()
CompilerEnvironment.PikeCompiler CompilerEnvironment.PikeCompiler(
string
|void
source
, CompilationHandler
|void
handler
, int
|void
major
, int
|void
minor
, program
|void
target
, object
|void
placeholder
)
Create a PikeCompiler object for a source string.
This function takes a piece of Pike code as a string and initializes a compiler object accordingly.
source
Source code to compile.
handler
The optional argument handler
is used to specify an alternative
error handler. If it is not specified the current master object
at compile time will be used.
major
minor
The optional arguments major
and minor
are used to tell the
compiler to attempt to be compatible with Pike major
.minor
.
target
__empty_program()
program to fill in. The virgin program
returned by __empty_program()
will be modified and returned
by compile()
on success.
placeholder
__null_program()
placeholder object to fill in. The object
will be modified into an instance of the resulting program
on successfull compile. Note that lfun::create()
in the
program will be called without any arguments.
Note that source
must contain the complete source for a program.
It is not possible to compile a single expression or statement.
Also note that no preprocessing is performed.
To preprocess the program you can use compile_string()
or
call the preprocessor manually by calling cpp()
.
Note that all references to target
and placeholder
should
removed if compile()
failes. On failure the placeholder
object will be destructed.
compile_string()
, compile_file()
, cpp()
, master()
,
CompilationHandler
CompilerEnvironment.PikeCompiler CompilerEnvironment.PikeCompiler(
string
|void
source
, object
|void
handler
, int
|void
major
, int
|void
minor
, program
|void
target
, object
|void
placeholder
)
string
CompilerEnvironment.PikeCompiler.current_file
The name of the file currently being compiled (during an active compilation).
int
CompilerEnvironment.PikeCompiler.current_line
The current line number (during an active compilation).
object
get_compilation_handler(int
major
, int
minor
)
object
get_compilation_handler(int
major
, int
minor
)
Get compatibility handler for Pike major
.minor
.
This function is called by change_compiler_compatibility()
.
mapping
(string
:mixed
)|object
get_default_module()
mapping
(string
:mixed
)|object
get_default_module()
Get the default module for the current compatibility level
(ie typically the value returned by predef::all_constants()
).
The default implementation calls the corresponding function
in the current handler, the current compatibility handler
or in the parent CompilerEnvironment
in that order.
| Constant table to use. |
| Use the builtin constant table. |
This function is called by change_compiler_compatibility()
.
program
handle_import(string
module
)
program
handle_import(string
module
)
Look up an import module
.
program
handle_inherit(string
inh
)
program
handle_inherit(string
inh
)
Look up an inherit inh
in the current program.
bool
index_type_attribute(string
attribute
, type
a
, type
i
)
Type attribute handler.
Called during type checking when a value of the type a
is
indexed with a value of type i
and a
had the type
attribute attribute
before the comparison.
The default implementation implements the "deprecated" attribute.
Returns 1
if the type check should be allowed
(ie __attribute__(attribute, a)[i]
), and
0
(zero) otherwise.
pop_type_attribute()
, push_type_attribute()
inherit ::this_program : this_program
bool
pop_type_attribute(string
attribute
, type
a
, type
b
)
Type attribute handler.
Called during type checking when a <= b
and
a
had the type attribute attribute
before the
comparison.
The default implementation implements the "deprecated" attribute.
Returns 1
if the type check should be allowed
(ie __attribute__(attribute, a) <= b
), and
0
(zero) otherwise.
push_type_attribute()
, index_type_attribute()
bool
push_type_attribute(string
attribute
, type
a
, type
b
)
Type attribute handler.
Called during type checking when a <= b
and
b
had the type attribute attribute
before the
comparison.
The default implementation implements the "deprecated" attribute.
Returns 1
if the type check should be allowed
(ie a <= __attribute__(attribute, b)
), and
0
(zero) otherwise.
pop_type_attribute()
, index_type_attribute()
void
report(SeverityLevel
severity
, string
filename
, int
linenumber
, string
subsystem
, string
message
, mixed
... extra_args
)
void
report(SeverityLevel
severity
, string
filename
, int
linenumber
, string
subsystem
, string
message
, mixed
... extra_args
)
Report a diagnostic from the compiler.
The default implementation attempts to call the first corresponding function in the active handlers in priority order:
Call handler->report().
Call handler->compile_warning() or handler->compile_error()
depending on severity
.
Call compat->report().
Call compat->compile_warning() or compat->compile_error()
depending on severity
.
Fallback: Call CompilerEnvironment()->report()
in the parent object.
The arguments will be as follows:
The report() function will be called with the same arguments as this function.
Depending on the severity
either compile_warning()
or compile_error() will be called.
They will be called with the filename
, linenumber
and formatted message
as arguments.
Note that these will not be called for the NOTICE
severity,
and that compile_error() will be used for both ERROR
and
FATAL
.
In Pike 7.8 and earlier the report() function was not called in the handlers.
CompilerEnvironment()->report()
mixed
resolv(string
identifier
)
mixed
resolv(string
identifier
)
Resolve the symbol identifier
.
The default implementation calls CompilerEnvironment()->resolv()
in the parent object, with the remaining arguments taken from the
current PikeCompiler
context.
Returns the value of sym
if found, and UNDEFINED
if not.
bool
suppress_deprecation_warnings()
Allows to query whether (during an active compilation) deprecation warnings are supposed to be suppressed.
1
if deprecation warnings should be suppressed,
0
otherwise.
Keeps the state of a single program/class during compilation.
Not in use yet!
string
res = CompilerEnvironment.define()
()
arguments
Array of arguments to the macro. Zero if no parenthesis.
context
CPP context we are evaluating in.
Returns the expansion of the macro on success, and 0
(zero)
on failure (typically due to invalid arguments
).
This class acts as a lock against other threads accessing the compiler.
The lock is released when the object is destructed.
Codec used by decode_value()
to decode objects, functions and
programs which have been encoded by Encoder.nameof
in the
corresponding Encoder
object.
object
__register_new_program(program
p
)
Called to register the program that is being decoded. Might get called repeatedly with several other programs that are being decoded recursively. The only safe assumption is that when the top level thing being decoded is a program, then the first call will be with the unfinished embryo that will later become that program.
Returns either zero or a placeholder object. A placeholder
object must be a clone of __null_program
. When the program is
finished, the placeholder object will be converted to a clone of
it. This is used for pike module objects.
function
(:void
) functionof(string
data
)
Decode function encoded in data
.
This function is called by decode_value()
when it encounters
encoded functions.
data
Encoding of some function as returned by Encoder.nameof()
.
Returns the decoded function.
objectof()
, programof()
object
objectof(string
data
)
Decode object encoded in data
.
This function is called by decode_value()
when it encounters
encoded objects.
data
Encoding of some object as returned by Encoder.nameof()
.
Returns the decoded object.
functionof()
, programof()
program
programof(string
data
)
Decode program encoded in data
.
This function is called by decode_value()
when it encounters
encoded programs.
data
Encoding of some program as returned by Encoder.nameof()
.
Returns the decoded program.
functionof()
, objectof()
Codec used by encode_value()
to encode objects, functions and
programs. Its purpose is to look up some kind of identifier for
them, so they can be mapped back to the corresponding instance
by decode_value()
, rather than creating a new copy.
mixed
nameof(object
|function
(:void
)|program
x
)
Called by encode_value()
to encode objects, functions and programs.
Returns something encodable on success, typically a string.
The returned value will be passed to the corresponding
objectof()
, functionof()
or programof()
by
decode_value()
.
If it returns UNDEFINED
then encode_value
starts to encode
the thing recursively, so that decode_value
later will
rebuild a copy.
encode_value()
has fallbacks for some classes of objects,
functions and programs.
Decoder.objectof()
, Decoder.functionof()
,
Decoder.objectof()
This is the interface for iterator objects. They implement an interface to a collection or stream of data items and a cursor that can be used to iterate over and examine individual items in the data set.
Iterators are typically created to access a data set in some
specific object, array, mapping, multiset or string. An object can
have several iterators that access different data sets in it, or
the same in different ways. E.g. strings have both an iterator for
access char-by-char (String.Iterator
), and another for access
over splitted substrings (String.SplitIterator
).
lfun::_get_iterator
may be defined in an object to get an
instance of the canonical iterator type for it. It's used by e.g.
foreach
to iterate over objects conveniently.
It's not an error to advance an iterator past the beginning or end
of the data set; `!()
will only return true then, and _iterator_index
and _iterator_value
will return UNDEFINED
. An iterator in that state
need not keep track of positions, so it's undefined what happens
if it's "moved back" into the set of items.
Backward movement for iterators is optional. It's supported if and
only if `-()
is defined, but even then it's undefined how far
back the iterator can move. Therefore iterators may support only a
limited amount of backward movement, e.g. when they access a
stream through a limited buffer. If such an iterator is moved back
past the limit then it'll behave as if it's pointing entirely
outside the data set (see above).
An iterator that doesn't support backward movement at all should throw an error if it's attempted.
predef::get_iterator
, lfun::_get_iterator
,
Array.Iterator
, Mapping.Iterator
, Multiset.Iterator
,
String.Iterator
, String.SplitIterator
.
mixed
_iterator_index()
Returns the current index, or UNDEFINED
if the iterator
doesn't point to any item.
If there's no obvious index set then the index is the current
position in the data set, counting from 0
(zero).
int
_iterator_next()
If this function is defined it should advance the iterator one
step, just like
would do.`+=
(1)
This is the preferred way to advance the iterator, since it reduces the overhead.
This function was optional in Pike 7.6 and earlier.
Returns 1 if it succeeded in advancing, and 0 (zero) if it has reached the end of the iterator.
`+
, `+=
, `-
mixed
_iterator_value()
Returns the current value, or UNDEFINED
if the iterator
doesn't point to any item.
void
random( Iterator arg )
If this function is defined then it sets the iterator to point
to a random item in the accessible set. The random distribution
should be rectangular within that set, and the pseudorandom
sequence provided by random
should be used.
int
sizeof( Iterator arg )
Returns the total number of items in the data set according to this iterator. If the size of the data set is unlimited or unknown then this function shouldn't be defined.
bool
res = !Iterator()
Returns 0
(zero) when the iterator points to an item,
1
otherwise.
Iterator
res = Iterator()
+ steps
Returns a clone of this iterator which is advanced the specified number of steps. The amount may be negative to move backwards. If the iterator doesn't support backward movement it should throw an exception in that case.
_iterator_next
, `+=
, `-
Iterator()
+= steps
Advance this iterator the specified number of steps and return it. The amount may be negative to move backwards. If the iterator doesn't support backward movement it should throw an exception in that case.
foreach
calls this function with a step value of 1
if _iterator_next()
doesn't exist for compatibility with Pike 7.6
and earlier.
foreach
will call this function even when the the
iterator has more than one reference. If you want to
loop over a copy of the iterator, you can create a
copy by adding 0
(zero) to it:
Iterator iterator;
...
foreach(iterator+0; mixed index; mixed value) {
...
}
Even though this function is sufficient for foreach
to
advance the iterator, _iterator_next()
is the preferred API.
_iterator_next
, `+
, `-
Iterator
res = Iterator()
- steps
This lfun should be defined if and only if the iterator supports backward movement to some degree. It should back up the specified number of steps. The amount may be negative to move forward.
_iterator_next
, `+
, `+=
Iterator Iterator(
void
|mixed
data
)
Initialize this iterator to access a data set in data
. The
type of data
is specific to the iterator implementation. An
iterator may also access some implicit data set, in which case
data
isn't specified at all.
The iterator initially points to the first item in the data set, if there is any.
The iterator does not need to support being reused, so this
function is typically declared protected
.
optional
bool
first()
If this function is defined then it resets the iterator to point to the first item.
Returns zero if there are no items at all in the data set, one otherwise.
It's not enough to set the iterator to the earliest accessible item. If the iterator doesn't support backing up to the original start position then this function should not be implemented.
optional
void
set_index(zero
index
)
If this function is defined it should set the iterator at the specified index.
It should be possible to set the index at the end of the iterator.
Master control program for Pike.
predef::master()
, predef::replace_master()
program
MasterObject.Decoder
This program in the master is cloned and used as codec by
decode_value
if it wasn't given any codec. An instance is only
created on-demand the first time decode_value
encounters
something for which it needs a codec, i.e. the result of a call to
Pike.Encoder.nameof
.
Decoder
, Pike.Decoder
program
MasterObject.Encoder
This program in the master is cloned and used as codec by
encode_value
if it wasn't given any codec. An instance is only
created on-demand the first time encode_value
encounters
something for which it needs a codec, i.e. an object, program, or
function.
Encoder
, Pike.Encoder
void
_main(array
(string(8bit)
) orig_argv
)
This function is called when all the driver is done with all setup of modules, efuns, tables etc. etc. and is ready to start executing _real_ programs. It receives the arguments not meant for the driver.
string
MasterObject._pike_file_name
string
MasterObject._master_file_name
These are useful if you want to start other Pike processes with the same options as this one was started with.
mixed
add_filesystem_handler(string
mountpoint
, object
filesystem
)
mount a filesystem handler to be used by the resolver. on its own does noting,
but may be used with add_module_path
and friends to enable modules to be loaded
from Filesystem objects.
mountpoint
the location in the filesystem to mount the handler
filesystem
a filesystem object that will handle requests for the given mountpoint.
master()->add_filesystem_handler("/foo/bar.zip", Filesystem.Zip("/foo/bar.zip")); master()->add_module_path("/foo/bar.zip/lib");
find_handler_for_path()
bool
asyncp()
Returns 1 if we're in async-mode, e.g. if the main method has returned a negative number.
object
backend_thread()
The backend_thread() function is useful to determine if you are the backend thread - important when doing async/sync protocols. This method is only available if thread_create is present.
constant
int
MasterObject.bt_max_string_len
This constant contains the maximum length of a function entry in a backtrace. Defaults to 200 if no BT_MAX_STRING_LEN define has been given.
object
cast_to_object(string
oname
, string
current_file
, object
|void
current_handler
)
This function is called when the drivers wants to cast a string to an object because of an implict or explicit cast. This function may also receive more arguments in the future.
object
cast_to_object(string
str
, string
|void
current_file
)
Called by the Pike runtime to cast strings to objects.
str
String to cast to object.
current_file
Filename of the file that attempts to perform the cast.
Returns the resulting object.
cast_to_program()
program
cast_to_program(string
pname
, string
current_file
, object
|void
handler
)
This function is called when the driver wants to cast a string to a program, this might be because of an explicit cast, an inherit or a implict cast. In the future it might receive more arguments, to aid the master finding the right program.
program
cast_to_program(string
str
, string
|void
current_file
)
Called by the Pike runtime to cast strings to programs.
str
String to cast to object.
current_file
Filename of the file that attempts to perform the cast.
Returns the resulting program.
cast_to_object()
string
MasterObject.cflags
Flags suitable for use when compiling Pike C modules
int
MasterObject.compat_major
Major pike version to emulate.
This is typically set via the option "-V"
.
compat_minor
int
MasterObject.compat_minor
Minor pike version to emulate.
This is typically set via the option "-V"
.
compat_major
void
compile_error(string
file
, int
line
, string
err
)
This function is called whenever a compile error occurs. line
is zero for errors that aren't associated with any specific line.
err
is not newline terminated.
compile_warning()
, compile_exception()
,
get_inhibit_compile_errors()
, set_inhibit_compile_errors()
,
int
compile_exception(array
|object
trace
)
This function is called when an exception is caught during
compilation. Its message is also reported to compile_error
if
this function returns zero.
compile_error()
, compile_warning()
,
get_inhibit_compile_errors()
, set_inhibit_compile_errors()
,
void
compile_warning(string
file
, int
line
, string
err
)
This function is called whenever a compile warning occurs. line
is zero for warnings that aren't associated with any specific
line. err
is not newline terminated.
compile_error()
, compile_exception()
,
get_inhibit_compile_errors()
, set_inhibit_compile_errors()
,
Version
MasterObject.currentversion
Version information about the current Pike version.
string
decode_charset(string
data
, string
charset
)
This function is called by cpp() when it wants to do character code conversion.
string
decode_charset(string
raw
, string
charset
)
Convert raw
from encoding charset
to UNICODE.
This function is called by cpp()
when it encounters
#charset
directives.
raw
String to convert.
charset
Name of encoding that raw
uses.
raw
decoded to UNICODE, or 0
(zero) if the decoding failed.
Charset
string
describe_backtrace(mixed
exception
)
Called by various routines to format a readable description of an exception.
exception
Something that was thrown. Usually an Error.Generic
object, or
an array with the following content:
Array | |
| Error message. |
| Backtrace to the point where the exception occurred. |
Returns a string describing the exeception.
Usually added by the initialization code the global name space
with add_constant()
.
predef::describe_backtrace()
string
describe_function(function
(:void
) f
)
Function called by describe_backtrace()
to describe
functions in the backtrace.
string
describe_module(object
|program
mod
, array
(object
)|void
ret_obj
)
Describe the path to the module mod
.
mod
If mod
is a program, attempt to describe the path
to a clone of mod
.
ret_obj
If an instance of mod
is found, it will be returned
by changing element 0
of ret_obj
.
The a description of the path.
The returned description will end with a proper indexing method
currently either "."
or "->"
.
string
describe_object(object
o
)
Function called by sprintf("%O")
for objects that don't
have an lfun::_sprintf()
, or have one that returns UNDEFINED
.
string
describe_program(program
|function
(:void
) p
)
Function called by sprintf("%O")
for programs.
string
MasterObject.doc_prefix
Prefix for autodoc files.
mapping
(string
:program
|NoValue
) MasterObject.programs
mapping
(program
:object
) MasterObject.documentation
mapping
(program
:string
) MasterObject.source_cache
Mapping containing the cache of currently compiled files.
This mapping currently has the following structure:
|
The filename path separator is / on both NT and UNIX.
Special cases: The current master program is available under the
name "/master"
, and the program containing the main
function under "/main"
.
void
enable_source_cache()
Enable caching of sources from compile_string()
string
fc_reverse_lookup(object
obj
)
Returns the path for obj
in fc
, if it got any.
string
find_handler_for_path(string
file
)
Return the mountpoint for the filesystem handler handling the
file
(if any).
add_filesystem_handler()
object
get_compat_master(int
major
, int
minor
)
Return a master object compatible with the specified version of Pike.
This function is used to implement the various compatibility versions
of master()
.
get_compilation_handler()
, master()
CompilationHandler
get_compilation_handler(int
major
, int
minor
)
Get compilation handler for simulation of Pike vmajor
.minor
.
This function is called by cpp()
when it encounters
#pike
directives.
major
Major version.
minor
Minor version.
Returns a compilation handler for Pike >= major
.minor
.
mixed
get_inhibit_compile_errors()
Get the current compile error, warning and exception behaviour.
See set_inhibit_compile_errors()
for details.
set_inhibit_compile_errors()
int
get_precompiled_mtime(string
id
)
Given an identifier returned by query_precompiled_names, returns the mtime of the precompiled entry. Returns -1 if there is no entry.
optional
bool
handle_attribute(mixed
value
, string
attribute
)
This function is called in runtime check_types mode (-rt), when encountering a soft cast to an attributed type.
value
Value that is about to receive the attribute.
attribute
Type attribute to validate.
Returns one of:
| If the attribute is valid for the value. |
| If the attribute is not valid for the value. |
| If the attribute is unsupported. |
The default master implements validation of the "utf8"
attribute.
void
handle_error(mixed
exception
)
Called by the Pike runtime if an exception isn't caught.
exception
Value that was throw()
'n.
describe_backtrace()
void
handle_error(array
|object
trace
)
This function is called when an error occurs that is not caught with catch().
program
handle_inherit(string
pname
, string
current_file
, object
|void
handler
)
This function is called whenever a inherit is called for. It is supposed to return the program to inherit. The first argument is the argument given to inherit, and the second is the file name of the program currently compiling. Note that the file name can be changed with #line, or set by compile_string, so it can not be 100% trusted to be a filename. previous_object(), can be virtually anything in this function, as it is called from the compiler.
string
MasterObject.include_prefix
Prefix for Pike-related C header files.
inherit Codec : Codec
inherit CompatResolver : CompatResolver
inherit CompilationHandler : CompilationHandler
The master object acts as fallback compilation handler for
compile()
and cpp()
.
protected
inherit Pike_8_0_master : Pike_8_0_master
Namespaces for compat masters.
This inherit is used to provide compatibility namespaces
for get_compat_master()
.
get_compat_master()
int
MasterObject.is_pike_master
This integer variable should exist in any object that aspires to be the master. It gets set to 1 when the master is installed, and is therefore set in any object that is or has been the master. That makes the Encoder class encode references to the master and all ex-masters as references to the current master object.
string
MasterObject.ldflags
Flags suitable for use when linking Pike C modules
string
master_read_file(string
file
)
Read a file from the master filesystem.
The master filesystem defaults to the system filesystem,
but additional mountpoints may be added via
add_filesystem_handler()
.
All file I/O performed by the MasterObject
is performed
via this function and its related functions.
add_filesystem_handler()
, find_handler_for_path()
,
master_get_dir()
, master_file_stat()
array
(string
) module_defined(object
|program
mod
)
Find the files in which mod
is defined, as they may be hidden away in
joinnodes and dirnodes
mod
The module we are looking for.
An array of strings with filenames. (one for each file in a joinnode, or just one otherwise)
program
objects_reverse_lookup(object
obj
)
Returns the program for obj
, if known to the master.
constant
int
MasterObject.out_of_date_warning
Should Pike complain about out of date compiled files. 1 means yes and 0 means no. Controlled by the OUT_OF_DATE_WARNING define.
string
program_path_to_name(string
path
, void
|string
module_prefix
, void
|string
module_suffix
, void
|string
object_suffix
)
Converts a module path on the form "Foo.pmod/Bar.pmod"
or
"/path/to/pike/lib/modules/Foo.pmod/Bar.pmod"
to a module
identifier on the form "Foo.Bar"
.
If module_prefix
or module_suffix
are given, they are
prepended and appended, respectively, to the returned string if
it's a module file (i.e. ends with ".pmod"
or
".so"
). If object_suffix
is given, it's appended to the
returned string if it's an object file (i.e. ends with
".pike"
).
string
programs_reverse_lookup(program
prog
)
Returns the path for prog
in programs
, if it got any.
array
(string
) query_precompiled_names(string
fname
)
Returns identifiers (e.g. file names) of potentially precompiled files in priority order.
string
read_precompiled(string
id
)
Given an identifier returned by query_precompiled_names, returns the precompiled entry. Can assume the entry exists.
void
runtime_warning(string
subsystem
, string
msg
, mixed
|void
data
)
Called by the Pike runtime to warn about data inconsistencies.
subsystem
Runtime subsystem where the warning was generated. Currently the following subsystems may call this function:
| The garbage collector. |
msg
Warning message. Currently the following messages may be generated:
| A cycle where the destruction order isn't deterministic was detected by the garbage collector. |
data
Optional data that further describes the warning specified by msg
.
void
runtime_warning(string
where
, string
what
, mixed
... args
)
Called for every runtime warning. The first argument identifies where the warning comes from, the second identifies the specific message, and the rest depends on that. See code below for currently implemented warnings.
void
set_inhibit_compile_errors(mixed
behaviour
)
Set the compile error, warning and exception behaviour.
behaviour
The desired behaviour. One of:
| Output compilation errors and warnings to stderr. This is the default behaviour. |
| Inhibit output of compilator diagnostics. |
| Function to call for compilation errors. Compilation warnings and exceptions are inhibited. The function will be called with the same arguments
as those passed to |
| Compilation handler to use for diagnostics. |
Note that the behaviour is thread local, and is not copied to new threads when they are created.
get_inhibit_compile_errors()
object
show_doc(program
|object
|function
(:void
) obj
)
Show documentation for the item obj
obj
The object for which the documentation should be shown
an AutoDoc object
int
MasterObject.show_if_constant_errors
Show compilation warnings from compilation of cpp()
#if constant()
expressions.
This is typically set via the option "--picky-cpp"
.
void
thread_quanta_exceeded(Thread.Thread
thread
, int
ns
)
Function called when a thread has exceeded the thread quanta.
thread
Thread that exceeded the thread quanta.
ns
Number of nanoseconds that the thread executed before allowing other threads to run.
The default master prints a diagnostic and the thread backtrace
to Stdio.stderr
.
This function runs in a signal handler context, and should thus avoid handling of mutexes, etc.
get_thread_quanta()
, set_thread_quanta()
void
unregister(program
p
)
Unregister a program that was only partially compiled.
Called by compile()
to clean up references to partially compiled
programs.
p
Partially compiled program that should no longer be referenced.
Shouldn't this function be in the compilation handler?
int
MasterObject.want_warnings
If not zero compilation warnings will be written out on stderr.
Encoder
and Decoder
rolled into one. This is for mainly
compatibility; there's typically no use combining encoding and
decoding into the same object.
MasterObject.Codec MasterObject.Codec(
void
|mixed
encoded
)
The optional argument is the thing to encode; it's passed on to
Encoder
.
inherit Decoder : Decoder
inherit Encoder : Encoder
Resolver of symbols not located in the program being compiled.
void
add_include_path(string
tmp
)
Add a directory to search for include files.
This is the same as the command line option -I.
Note that the added directory will only be searched when using < > to quote the included file.
remove_include_path()
void
add_module_path(string
path
, string
|void
subpath
)
Add a directory to search for modules.
This is the same as the command line option -M.
remove_module_path()
path
a string containing a path to search for Pike modules. May be a directory, or a path to a ZIP archive. If a ZIP archive path is provided, modules will be loaded from a directory, "modules" within the ZIP archive (see the subpath argument).
subpath
if path is a ZIP archive, this argument will determine the path within the archive to be searched.
void
add_predefine(string
name
, mixed
value
)
Add a define (without arguments) which will be implicitly
defined in cpp
calls.
void
add_program_path(string
tmp
)
Add a directory to search for programs.
This is the same as the command line option -P.
remove_program_path()
MasterObject.CompatResolver MasterObject.CompatResolver(
mixed
version
, CompatResolver
|void
fallback_resolver
)
The CompatResolver is initialized with a value that can be casted into a "%d.%d" string, e.g. a version object.
It can also optionally be initialized with a fallback resolver.
CompatResolver
MasterObject.CompatResolver.fallback_resolver
If we fail to resolv, try the fallback.
Typical configuration:
0.6->7.0->7.2-> ... ->master
mapping
get_default_module()
Return the default module for the CompatResolver
.
This is the mapping that corresponds to the predef::
name space for the compatibility level, and is the
value returned by all_constants()
for the same.
mapping
get_predefines()
Returns a mapping with the current predefines.
string
handle_include(string
f
, string
current_file
, int
local_include
)
This function is called whenever an #include directive is encountered. It receives the argument for #include and should return the file name of the file to include.
read_include()
mapping
(object
:joinnode
) MasterObject.CompatResolver.handler_root_modules
Lookup from handler module to corresponding root_module.
protected
mapping
(string
:mixed
) instantiate_static_modules(object
|mapping
static_modules
)
Instantiate static modules in the same way that dynamic modules are instantiated.
array
(string
) MasterObject.CompatResolver.pike_include_path
The complete include search path
array
(string
) MasterObject.CompatResolver.pike_module_path
The complete module search path
array
(string
) MasterObject.CompatResolver.pike_program_path
The complete program search path
string
read_include(string
f
)
Read the file specified by handle_include()
.
handle_include()
void
remove_include_path(string
tmp
)
Remove a directory to search for include files.
This function performs the reverse operation of add_include_path()
.
add_include_path()
void
remove_module_path(string
tmp
)
Remove a directory to search for modules.
This function performs the reverse operation of add_module_path()
.
add_module_path()
void
remove_predefine(string
name
)
Remove a define from the set that are implicitly defined in
cpp
calls.
void
remove_program_path(string
tmp
)
Remove a directory to search for programs.
This function performs the reverse operation of add_program_path()
.
add_program_path()
mixed
resolv(string
identifier
, string
|void
current_file
, object
|void
current_handler
, object
|void
current_compat_handler
)
Resolve the identifier
expression.
Returns the value of the identifier
if it exists,
and UNDEFINED
otherwise.
mixed
resolv_base(string
identifier
, string
|void
current_file
, object
|void
current_handler
, object
|void
current_compat_handler
)
Look up identifier
in the root module.
mixed
resolv_or_error(string
identifier
, string
|void
current_file
, void
|object
current_handler
)
Same as resolv
, but throws an error instead of returning
UNDEFINED
if the resolv failed.
joinnode
MasterObject.CompatResolver.root_module
Join node of the root modules for this resolver.
array
(string
) MasterObject.CompatResolver.system_module_path
The pike system module path, not including any set by the user.
Codec for use with decode_value
. This is the decoder
corresponding to Encoder
. See that one for more details.
MasterObject.Decoder MasterObject.Decoder(
void
|string
fname
, void
|int
mkobj
, void
|object
handler
)
array
(mixed
) decode_object(object
o
, mixed
data
)
Restore the state of an encoded object.
o
Object to modify.
data
State information from Encoder()->encode_object()
.
The default implementation calls o->_decode(data)
if the object has an _decode()
, otherwise if
data
is an array, returns it to indicate that lfun::create()
should be called.
This function is called before lfun::create()
in the object has been called, but after lfun::__INIT()
has been called.
Returns an array to indicate to the caller that
lfun::create()
should be called with the elements
of the array as arguments.
Returns 0
(zero) to inhibit calling of lfun::create()
.
Encoder()->encode_object()
void
|string
MasterObject.Decoder.fname
void
|int
MasterObject.Decoder.mkobj
void
|object
MasterObject.Decoder.handler
Class used by describe_backtrace()
to describe values in backtraces.
inherit _static_modules.Builtin.DestructImmediate : DestructImmediate
Codec for use with encode_value
. It understands all the
standard references to builtin functions, pike modules, and the
main program script.
The format of the produced identifiers are documented here to allow extension of this class:
The produced names are either strings or arrays. The string variant specifies the thing to look up according to the first character:
'c' Look up in all_constants(). 's' Look up in _static_modules. 'r' Look up with resolv(). 'p' Look up in programs. 'o' Look up in programs, then look up the result in objects. 'f' Look up in fc.
In the array format, the first element is a string as above and the rest specify a series of things to do with the result:
A string Look up this string in the result. 'm' Get module object in dirnode. 'p' Do object_program(result).
All lowercase letters and the symbols ':', '/' and '.' are reserved for internal use in both cases where characters are used above.
MasterObject.Encoder MasterObject.Encoder(
void
|mixed
encoded
)
Creates an encoder instance. If encoded
is specified, it's
encoded instead of being reverse resolved to a name. That's
necessary to encode programs.
string
|array
nameof(mixed
what
, void
|array
(object
) module_object
)
When module_object
is set and the name would end with an
object_program
step (i.e. 'p'
), then drop that
step so that the name corresponds to the object instead.
will receive the found object.module_object
[0]
Pike 7.8 master compatibility interface.
Most of the interface is implemented via mixin, or overloading by more recent masters.
This interface is used for compatibility with Pike 7.8.
Replaced by predef::MasterObject
.
get_compat_master()
, master()
, predef::MasterObject
Pike 8.0 master compatibility interface.
Most of the interface is implemented via mixin, or overloading by more recent masters.
This interface is used for compatibility with Pike 8.0.
Replaced by predef::MasterObject
.
get_compat_master()
, master()
, predef::MasterObject
inherit Pike_7_8_master : Pike_7_8_master
Contains version information about a Pike version.
int
res = MasterObject.Version()
< v
int
res = MasterObject.Version()
> v
int
res = MasterObject.Version()
== v
int
hash_value( MasterObject.Version arg )
Methods define so that version objects can be compared and ordered.
(int)MasterObject.Version()
(float)MasterObject.Version()
(string)MasterObject.Version()
(array)MasterObject.Version()
(mapping)MasterObject.Version()
(multiset)MasterObject.Version()
The version object can be casted into a string.
MasterObject.Version MasterObject.Version(
int
major
, int
minor
)
Set the version in the object.
int
MasterObject.Version.major
int
MasterObject.Version.minor
The major and minor parts of the version.
Module node representing a single directory.
joinnode
string
MasterObject.dirnode.dirname
object
|void
MasterObject.dirnode.compilation_handler
string
|void
MasterObject.dirnode.name
MasterObject.dirnode MasterObject.dirnode(
string
dirname
, object
|void
compilation_handler
, string
|void
name
)
Module node holding possibly multiple directories, and optionally falling back to another level.
dirnode
array
(object
|mapping
) MasterObject.joinnode.joined_modules
object
|void
MasterObject.joinnode.compilation_handler
joinnode
|mapping
(mixed
:int(0..0)
)|void
MasterObject.joinnode.fallback_module
string
|void
MasterObject.joinnode.name
MasterObject.joinnode MasterObject.joinnode(
array
(object
|mapping
) joined_modules
, object
|void
compilation_handler
, joinnode
|mapping
(mixed
:int(0..0)
)|void
fallback_module
, string
|void
name
)
array
random(mapping
m
)
Returns a random index-value pair from the mapping.
Array | |
| The index of the mapping entry. |
| The value f the mapping entry. |
Throws an exception if the mapping is empty.
float
random(float
max
)
This function returns a random number in the range
0 ..
.max
-É›
Random
int
random(int
max
)
This function returns a random number in the range
0 ..
.max
-1
Random
mixed
random(object
o
)
If random is called with an object, lfun::_random
will be
called in the object.
Throws an exception if the object doesn't have a _random method.
lfun::_random()
mixed
random(array
|multiset
x
)
Returns a random element from x
.
Throws an exception if the array or multiset is empty.
string(8bit)
random_string(int(0..)
)
Prototype for the randomness generating function.
Override this symbol to implement a usable class.
inherit RandomInterface : RandomInterface
string(8bit)
random_string(int(0..)
len
)
Return a string of random data from the system randomness pool.
On POSIX platforms this reads random data from /dev/urandom on other platforms it may use other methods.
May throw errors on unexpected state.
API for reporting parse errors and similar.
void
report(SeverityLevel
severity
, string
filename
, int(1..)
linenumber
, string
subsystem
, string
message
, mixed
... extra_args
)
Report a diagnostic from the compiler.
severity
The severity of the diagnostic.
filename
linenumber
Location which triggered the diagnostic.
subsystem
Compiler subsystem that generated the diagnostic.
message
sprintf()
-style formatting string with the diagnostic message.
extra_args
Extra arguments to sprintf()
.
The default implementation does the following:
If there's a MasterObject()->report()
, call it
with the same arguments as ourselves.
Otherwise depending on severity
:
| Ignored. |
| Calls |
| Calls |
|
If there's no master object yet, the diagnostic is output to
Stdio.stderr
.
In Pike 7.8 and earlier MasterObject()->report()
was not called.
PikeCompiler()->report()
Message severity level. { NOTICE, WARNING, ERROR, FATAL }
report()
constant
Reporter.NOTICE
constant
Reporter.WARNING
constant
Reporter.ERROR
constant
Reporter.FATAL
inherit MasterObject.dirnode : dirnode
inherit MasterObject.joinnode : joinnode
mapping
(string
:array
(array
(Parser.C.Token
))) parse(array
(Parser.C.Token
) tokens
)
Returns a mapping from symbol to a tuple of return type and parameters.
mklibpike.C_Include_Handler mklibpike.C_Include_Handler(
array
(string
) search_path
)
array
(string
) mklibpike.C_Include_Handler.search_path
int
res = string_assignment()
[ i
]
String index operator.
string_assignment()
[ i
] = j
String assign index operator.
Support for the Apple Keychain format.
This is used for the files in eg /System/Library/Keychains.
Argument parsing module
This module supports two rather different methods of argument parsing. The first is suitable quick argument parsing without much in the way of checking:
int main( int c, array(string) argv )
{
mapping arguments = Arg.parse(argv);
array files = arguments[Arg.REST];
if( arguments->help ) print_help();
...
}
The Arg.parse
method will return a mapping from argument name
to the argument value, if any.
Non-option arguments will be placed in the index Arg.REST
The second way to use this module is to inherit the Options class and add supported arguments.
class MyArguments {
inherit Arg.Options;
string help_pre = "Usage: somecommand";
Opt verbose = NoOpt("-v")|NoOpt("--verbose");
string verbose_help = "Turn on verbose output";
Opt help = MaybeOpt("--help");
Opt output = HasOpt("--output")|HasOpt("-o");
string output_help = "Determine where output goes to";
string help_post = "Command aborted";
};
Then, in main:
MyArguments args = MyArguments(argv);
See the documentation for OptLibrary
for details about the various
Opt classes.
constant
Arg.APP
Constant used to represent the name of the application from the
command line. Can be used when indexing an Options
object.
constant
Arg.PATH
Constant used to represent the full path of the application from
the command line. Can be used when indexing an Options
object.
constant
Arg.REST
Constant used to represent command line arguments not identified
as options. Can be used both in the response mapping from parse
and when indexing an Options
object.
mapping
(string
:string
|int(1..)
) parse(array
(string
) argv
)
Convenience function for simple argument parsing.
Handles the most common cases.
The return value is a mapping from option name to the option value.
The special index Arg.REST will be set to the remaining arguments after all options have been parsed.
The following argument syntaxes are supported:
--foo -> "foo":1
--foo=bar -> "foo":"bar"
-bar -> "b":1,"a":1,"r":1
-bar=foo -> "b":1,"a":1,"r":"foo" (?)
--foo --bar -> "foo":1,"bar":1
--foo - --bar -> "foo":1
--foo x --bar -> "foo":1 (?)
-foo -> "f":1,"o":2
-x -x -x -> "x":3
void main(int n, array argv) { mapping opts = Arg.parse(argv); argv = opts[Arg.REST]; if( opts->help ) /*... */ }
protected
string
Arg.LowOptions.application
protected
array
(string
) Arg.LowOptions.argv
(int)Arg.LowOptions()
(float)Arg.LowOptions()
(string)Arg.LowOptions()
(array)Arg.LowOptions()
(mapping)Arg.LowOptions()
(multiset)Arg.LowOptions()
Arg.LowOptions Arg.LowOptions(
array
(string
) _argv
, void
|mapping
(string
:string
) env
)
protected
inherit OptLibrary : OptLibrary
protected
mapping
(string
:Opt
) Arg.LowOptions.opts
protected
bool
unhandled_argument(array
(string
) argv
, mapping
(string
:string
) env
)
protected
mapping
(string
:int(1..1)
|string
) Arg.LowOptions.values
This class contains a library of parser for different type of options.
Default value for a setting.
Opt output = HasOpt("-o")|Default("a.out");
inherit Opt : Opt
Environment fallback for an option. Can of course be used as only Opt source.
Opt debug = NoOpt("--debug")|Env("MY_DEBUG");
inherit Opt : Opt
Parses an option that has a parameter. --foo=bar, -x
bar and -x=bar will set the variable to bar
.
Opt user = HasOpt("--user")|HasOpt("-u");
inherit NoOpt : NoOpt
Wrapper class that converts the option argument to an integer.
Opt foo = Int(HasOpt("--foo")|Default(4711));
Arg.OptLibrary.Int Arg.OptLibrary.Int(
Opt
opt
)
inherit Opt : Opt
Opt
Arg.OptLibrary.Int.opt
Parses an option that may have a parameter. --foo,
-x and x in a sequence like -axb will set the
variable to 1
. --foo=bar, -x bar and
-x=bar will set the variable to bar
.
Opt debug = MaybeOpt("--debug");
inherit NoOpt : NoOpt
Wrapper class that allows multiple instances of an option.
Opt filter = Multiple(HasOpt("--filter"));
Arg.OptLibrary.Multiple Arg.OptLibrary.Multiple(
Opt
opt
)
inherit Opt : Opt
Opt
Arg.OptLibrary.Multiple.opt
Parses an option without parameter, such as --help, -x or "x" from -axb.
Opt verbose = NoOpt("-v")|NoOpt("--verbose");
inherit Opt : Opt
Base class for parsing an argument. Inherit this class to create custom made option types.
protected
string
__sprintf()
This function will be called by _sprintf
, which
handles formatting of chaining between objects.
array
(string
) get_opts()
Should return a list of options that are parsed. To properly
chain argument parsers, return your_opts +
::get_opts()
.
mixed
get_value(array
(string
) argv
, mapping
(string
:string
) env
, mixed
previous
)
The overloading method should calculate the value of the
option and return it. Methods processing argv
should only
look at argv[0] and if it matches, set it to 0. Returning
UNDEFINED
means the option was not set (or
matched). To properly chain arguments parsers, return
::get_value(argv, env, previous)
instead of
UNDEFINED
, unless you want to explicitly stop the
chain and not set this option.
The option parser class that contains all the argument objects.
Opt
Arg.Options.help
protected
string
Arg.Options.help_help
Options that trigger help output.
inherit LowOptions : LowOptions
protected
bool
unhandled_argument(array
(string
) argv
, mapping
(string
:string
) env
)
Options parser with a unhandled_argument implementation that parses most common argument formats.
inherit LowOptions : LowOptions
bool
unhandled_argument(array
(string
) argv
, mapping
(string
:string
) env
)
Handles arguments as described in Arg.parse
Decoder object.
It needs _Ffmpeg.ffmpeg
module for real work.
Audio.Codec.decoder Audio.Codec.decoder(
string
|void
codecname
, object
|void
_codec
)
Creates decoder object
codecnum
Some of supported codec, like _Ffmpeg.CODEC_ID_*
_codec
The low level object will be used for decoder.
By default _Ffmpeg.ffmpeg
object will be used.
Until additional library is implemented the second
parameter _codec
hasn't effect.
_Ffmpeg.ffmpeg
, _Ffmpeg.CODEC_ID_MP2
mapping
|int
decode(int
|void
partial
)
Decodes audio data
partial
Only one frame will be decoded per call.
If successfull a mapping with decoded data and byte number of used input data is returned, 0 otherwise.
this_program
from_file(Audio.Format.ANY
file
)
Set codec type from file
It uses Audio.Format.ANY
's method get_map()
to determine which codec should be used.
file
The object Audio.Format.ANY
.
mapping
get_status()
Returns decoder status
Audio data format handling
API remains marked "unstable".
int
check_format()
Check if data are correctly formated.
string
get_data()
Returns data only.
The operation is destructive. Ie. current data cursor is moved over.
get_frame
, get_sample
string
get_frame()
Returns frame for current position and moves cursor forward.
The operation is destructive. Ie. current data cursor is moved over.
get_data
, get_sample
mapping
get_map()
mapping
get_sample()
Returns sample for current position and moves cursor forward.
The operation is destructive. Ie. current data cursor is moved over.
get_frame
, get_data
this_program
read_file(string
filename
, int
|void
nocheck
)
Reads data from file
read_streamed
this_program
read_streamed(string
filename
, int
|void
nocheck
)
Reads data from stream
Ie. for packetized data source the beggining of data is searched.
read_file
this_program
read_string(string
data
, int
|void
nocheck
)
Reads data from string
A MP3 file parser with ID3 tag support.
mapping
|int
get_frame()
Gets next frame from file
Frame is represented by the following mapping. It contains from parsed frame headers and frame data itself.
([ "bitrate": int "copyright": int(0..1), "data": frame_data, "emphasis": emphasis, "extension": "channels":0, "id":1, "layer":3, "original": int(0..1), "padding": int(0..1), "private": int(0..1), "sampling": int ])
inherit .module.ANY : ANY
function
(mixed_void
:void
) _get_setter(object
o
, string
varname
)
Get a setter for the variable named varname
in object o
.
Returns a Setter()->`()()
for the variable if it exists,
and UNDEFINED
otherwise.
object_variablep()
mapping
(string
:mixed
) _take_over_initial_predefines()
Returns a mapping containing the set of predefined macros. These are typically the macros defined via the -D option when starting Pike.
This function is typically called by the MasterObject
at
initialization, and may only be called once. After it has been called,
cpp()
will start calling CompilationHandler->get_predefines()
to
retrieve the set of predefined macros.
[cpp()], CompilationHandler->get_predefines()
This class is used to implement the low-level aspects of Val.Null
.
This class should typically not be used directly. Use
Val.Null
instead.
This class was previously available as Sql.Null
. Any such use
should be replaced with Val.Null
.
Replaced by Val.Null
.
Val.Null
, Val.null
string
encode_json()
Defined for use with Standards.JSON.encode
, so that it
formats NULL as null
.
Internal class for implementing setters.
This class is used by _get_setter()
.
_get_setter()
void
res = Builtin.Setter()
()
Set the variable for the setter to val
.
This is the function returned by _get_setter()
.
This is an internal class used by __automap__()
.
It may show up during module dumping or in backtraces and the like.
It should in normal circumstances never be used directly.
__automap__()
, map()
Builtin.automap_marker Builtin.automap_marker(
array
arr
, int
depth
)
arr
Array that __automap__()
is to loop over.
depth
Recursion depth of arr
where the loop will be.
Common Caching implementation
This module serves as a front-end to different kinds of caching systems. It uses two helper objects to actually store data, and to determine expiration policies.
To create a new cache, do Cache.cache
( Cache.Storage.Base
storage_type, Cache.Policy.Base
expiration_policy )
The cache store instances of Cache.Data
.
Base stored object for the cache system.
int
Cache.Data.atime
last-access time.
float
Cache.Data.cost
relative preciousness scale
Cache.Data Cache.Data(
void
|mixed
value
, void
|int
expire_time
, void
|float
preciousness
)
expire_time is relative and in seconds.
int
Cache.Data.ctime
creation-time
mixed
data()
A method in order to allow for lazy computation
int
Cache.Data.etime
expiry-time (if supplied). 0 otherwise
int
recursive_low_size(mixed
whatfor
)
Attempts a wild guess of an object's size. It's left here as a common utility. Some classes won't even need it.
int
size()
A method in order to allow for lazy computation. Used by some Policy Managers
This module serves as a front-end to different kinds of caching systems. It uses two helper objects to actually store data, and to determine expiration policies. Mechanisms to allow for distributed caching systems will be added in time, or at least that is the plan.
void
alookup(string
key
, function
(string
, mixed
, mixed
... :void
) callback
, int
|float
timeout
, mixed
... args
)
Asynchronously look the cache up. The callback will be given as arguments the key, the value, and then any user-supplied arguments. If the timeout (in seconds) expires before any data could be retrieved, the callback is called anyways, with 0 as value.
void
async_cleanup_cache()
Cache.cache Cache.cache(
Cache.Storage.Base
storage_mgr
, Cache.Policy.Base
policy_mgr
, void
|int
cleanup_cycle_delay
)
Creates a new cache object. Required are a storage manager, and an expiration policy object.
void
delete(string
key
, void
|bool
hard
)
Forcibly removes some key.
If the 'hard' parameter is supplied and true, deleted objects will also
have their lfun::_destruct
method called upon removal by some
backends (i.e. memory)
mixed
lookup(string
key
)
Looks in the cache for an element with the given key and, if available, returns it. Returns 0 if the element is not available
void
start_cleanup_cycle()
void
store(string
key
, mixed
value
, void
|int
max_life
, void
|float
preciousness
, void
|multiset
(string
) dependants
)
Sets some value in the cache. Notice that the actual set operation might even not happen at all if the set data doesn't make sense. For instance, storing an object or a program in an SQL-based backend will not be done, and no error will be given about the operation not being performed.
Notice that while max_life will most likely be respected (objects will be garbage-collected at pre-determined intervals anyways), the preciousness . is to be seen as advisory only for the garbage collector If some data was stored with the same key, it gets returned. Also notice that max_life is relative and in seconds. dependants are not fully implemented yet. They are implemented after a request by Martin Stjerrholm, and their purpose is to have some weak form of referential integrity. Simply speaking, they are a list of keys which (if present) will be deleted when the stored entry is deleted (either forcibly or not). They must be handled by the storage manager.
void
threaded_cleanup_cycle()
Base class for cache expiration policies.
void
expire(Cache.Storage.Base
storage
)
Expire callback.
This function is called to expire parts
of storage
.
All Storage.Policy classes must MUST implement this method.
A multiple-policies expiration policy manager.
Thanks to Francesco Chemolli <kinkie@roxen.com> for the contribution.
Cache.Policy.Multiple Cache.Policy.Multiple(
Cache.Policy.Base
... policies
)
void
expire(Cache.Storage.Base
storage
)
This expire function calls the expire functions in all of the sub-policies in turn.
inherit Cache.Policy.Base : Base
Null policy-manager for the generic Caching system
This is a policy manager that doesn't actually expire anything. It is useful in multilevel and/or network-based caches.
Thanks to Francesco Chemolli <kinkie@roxen.com> for the contribution.
void
expire(Cache.Storage.Base
storage
)
This is an expire function that does nothing.
inherit Cache.Policy.Base : Base
An LRU, size-constrained expiration policy manager.
Thanks to Francesco Chemolli <kinkie@roxen.com> for the contribution.
Cache.Policy.Sized Cache.Policy.Sized(
int
max
, void
|int
min
)
void
expire(Cache.Storage.Base
storage
)
inherit Cache.Policy.Base : Base
An access-time-based expiration policy manager.
inherit Cache.Policy.Base : Base
Base class for cache storage managers.
All Cache.Storage
managers must provide these methods.
void
aget(string
key
, function
(string
, int(0..0)
|Cache.Data
, mixed
... :void
) callback
, mixed
... extra_callback_args
)
Fetch some data from the cache asynchronously.
callback()
will get as first argument key
, and as second
argument 0 (cache miss) or an Cache.Data
object, plus any
additional argument that the user may have supplied.
mixed
delete(string
key
, void
|bool
hard
)
Delete the entry specified by key
from the cache (if present).
If hard
is 1, some backends may force a destruct()
on the deleted value.
Dependants (if present) are automatically deleted.
Returns the deleted entry.
int(0..0)
|string
first()
int(0..0)
|string
next()
These two functions are an iterator over the cache. There is an
internal cursor, which is reset by each call to first()
. Subsequent
calls to next()
will iterate over all the contents of the cache.
These functions are not meant to be exported to the user, but are solely for the policy managers' benefit.
int(0..0)
|Cache.Data
get(string
key
, void
|bool
notouch
)
Fetch some data from the cache synchronously.
Be careful, as with some storage managers it might block the calling thread for some time.
void
set(string
key
, mixed
value
, void
|int
max_life
, void
|float
preciousness
, void
|multiset
(string
) dependants
)
Data-object creation is performed here if necessary, or in get()
depending on the backend.
This allows the storage managers to have their own data class implementation.
A GBM-based storage manager.
This storage manager provides the means to save data to memory. In this manager I'll add reference documentation as comments to interfaces. It will be organized later in a more comprehensive format
Settings will be added later.
Thanks to Francesco Chemolli <kinkie@roxen.com> for the contribution.
Cache.Storage.Gdbm Cache.Storage.Gdbm(
string
path
)
A GDBM storage-manager must be hooked to a GDBM Database.
inherit Cache.Storage.Base : Base
inherit Cache.Data : Data
A RAM-based storage manager.
This storage manager provides the means to save data to memory. In this manager I'll add reference documentation as comments to interfaces. It will be organized later in a more comprehensive format
Settings will be added later.
Thanks to Francesco Chemolli <kinkie@roxen.com> for the contribution.
int(0..0)
|Cache.Data
get(string
key
, void
|int
notouch
)
Fetches some data from the cache. If notouch is set, don't touch the data from the cache (meant to be used by the storage manager only)
inherit Cache.Storage.Base : Base
inherit Cache.Data : Data
An SQL-based storage manager
This storage manager provides the means to save data to an SQL-based backend.
For now it's mysql only, dialectization will be added at a later time. Serialization should be taken care of by the low-level SQL drivers.
An administrator is supposed to create the database and give the user enough privileges to write to it. It will be care of this driver to create the database tables itself.
Thanks to Francesco Chemolli <kinkie@roxen.com> for the contribution.
Cache.Storage.MySQL Cache.Storage.MySQL(
string
sql_url
)
inherit Cache.Storage.Base : Base
Database manipulation is done externally. This class only returns values, with some lazy decoding.
inherit Cache.Data : Data
A Yabu-based storage manager.
Settings will be added later.
Thanks to Francesco Chemolli <kinkie@roxen.com> for the contribution.
Cache.Storage.Yabu Cache.Storage.Yabu(
string
path
)
inherit Cache.Storage.Base : Base
inherit Cache.Data : Data
Time and day system
Q: I need to parse some date in a non-strict format, like
the one in the HTTP or mail protocol, or from a user web
form.
A: Calendar.dwim_day, or Calendar.dwim_time, should solve
your problem.
> Calendar.dwim_day("1/2/3");
Result: Day(Thu 2 Jan 2003)
> Calendar.dwim_day("1 aug 2001");
Result: Day(Wed 1 Aug 2001)
> Calendar.dwim_time("1 aug 2001 23:14 EDT");
Result: Minute(Wed 1 Aug 2001 23:14 EDT)
> Calendar.dwim_time("2001 2 3 23:14:23 UTC+9");
Result: Second(Sat 3 Feb 2001 23:14:23 UTC+9)
If it doesn't, and it should, report the problem to me
and I'll see what I can do. Note that the timezones
are rather unpredictable - if it doesn't get it, you
will get the default (local) timezone.
-------------------------------------------------------------------------
Q: The dwim_* functions are too slow.
A: They are not written to be fast, but to do good guessing.
If you know the format, you should use the Calendar.parse
function:
> Calendar.parse("%Y-%M-%D %h:%m","2040-11-08 2:46");
Result: Minute(Thu 8 Nov 2040 2:46 CET)
> Calendar.parse("%Y w%W %e %h:%m %p %z","1913 w4 monday 2:14 pm CET");
Result: Minute(Mon 20 Jan 1913 14:14 CET)
These are the format characters:
%Y absolute year
%y dwim year (70-99 is 1970-1999, 0-69 is 2000-2069)
%M month (number, name or short name) (needs %y)
%W week (needs %y)
%D date (needs %y, %m)
%d short date (20000304, 000304)
%a day (needs %y)
%e weekday (needs %y, %w)
%h hour (needs %d, %D or %W)
%m minute (needs %h)
%s second (needs %m)
%f fraction of a second (needs %s)
%t short time (205314, 2053)
%z zone
%p "am" or "pm"
%n empty string (to be put at the end of formats)
and you can also use "%*[....]" to skip some characters,
as in sscanf().
If this is too slow, there is currently no solution in Pike
to do this faster, except possibly sscanf and manual calculations/
time object creation.
-------------------------------------------------------------------------
Q: How do I get from unix time (time(2)) to a unit and back?
A: Calendar.Unit("unix",time())
unit->unix_time()
> Calendar.Day("unix",987654321);
Result: Day(Thu 19 Apr 2001)
> Calendar.Second("unix",987654321);
Result: Second(Thu 19 Apr 2001 6:25:21 CEST)
> Calendar.Day()->unix_time();
Result: 979081200
Note that you will get the time for the start of the unit.
Unix time is timezone independant.
The day-of-time units (seconds, hours, etc) uses this
as internal representation of time.
-------------------------------------------------------------------------
Q: I'm a mad astronomer, how do I do the same conversions with
julian day numbers?
A: Julian day numbers are used as the internal representation
for the day, and for most other bigger-than-time-of-day calculations.
> Calendar.Day("julian",2454545);
Result: Day(Wed 19 Mar 2008)
> Calendar.Second("julian",2430122.0);
Result: Second(Tue 6 May 1941 13:00:00 CET)
Julian day numbers from day units and bigger are integers,
representing the new julian number on that day. Julian day
numbers from time of day units are represented in floats.
> Calendar.Day()->julian_day();
Result: 2451920
> Calendar.Second()->julian_day();
Result: 2451919.949595
Watch out for the float precision, though. If you haven't
compiled your Pike with --with-double-precision, this gives
you awkwardly low precision - 6 hours.
-------------------------------------------------------------------------
Q: How do I convert a "Second(Sat 3 Feb 2001 23:14:23 UTC+9)" object
to my timezone?
A: ->set_timezone(your timezone)
> Calendar.dwim_time("2001 2 3 23:14:23 PST")
->set_timezone("Europe/Stockholm");
Result: Second(Sun 4 Feb 2001 8:14:23 CET)
> Calendar.dwim_time("2001 2 3 23:14:23 PST")
->set_timezone("locale");
Result: Second(Sun 4 Feb 2001 8:14:23 CET)
-------------------------------------------------------------------------
Q: How do I print my time object?
A: ->format_xxx();
You can either print it unit-sensitive,
> Calendar.dwim_time("2001 2 3 23:14:23 PST")->format_nice();
Result: "3 Feb 2001 23:14:23"
> Calendar.Week()->format_nice();
Result: "w2 2001"
> Calendar.now()->format_nicez();
Result: "10 Jan 10:51:15.489603 CET"
or in a format not depending on the unit,
> Calendar.Week()->format_ymd();
Result: "2001-01-08"
> Calendar.Day()->format_time();
Result: "2001-01-10 00:00:00"
This is all the formats:
format_ext_time "Wednesday, 10 January 2001 10:49:57"
format_ext_time_short "Wed, 10 Jan 2001 10:49:57 CET"
format_ext_ymd "Wednesday, 10 January 2001"
format_iso_time "2001-01-10 (Jan) -W02-3 (Wed) 10:49:57 UTC+1"
format_iso_ymd "2001-01-10 (Jan) -W02-3 (Wed)"
format_mod "10:49"
format_month "2001-01"
format_month_short "200101"
format_mtime "2001-01-10 10:49"
format_time "2001-01-10 10:49:57"
format_time_short "20010110 10:49:57"
format_time_xshort "010110 10:49:57"
format_tod "10:49:57"
format_tod_short "104957"
format_todz "10:49:57 CET"
format_todz_iso "10:49:57 UTC+1"
format_week "2001-w2"
format_week_short "2001w2"
format_iso_week "2001-W02"
format_iso_week_short "200102"
format_xtime "2001-01-10 10:49:57.539198"
format_xtod "10:49:57.539658"
format_ymd "2001-01-10"
format_ymd_short "20010110"
format_ymd_xshort "010110"
format_ctime "Wed Jan 10 10:49:57 2001\n"
format_smtp "Wed, 10 Jan 2001 10:49:57 +0100"
format_http "Wed, 10 Jan 2001 09:49:57 GMT"
-------------------------------------------------------------------------
Q: How old am I?
A: First, you need to create the time period representing your age.
> object t=Calendar.dwim_time("1638 dec 23 7:02 pm")
->distance(Calendar.now());
Result: Fraction(Thu 23 Dec 1638 19:02:00.000000 LMT -
Wed 10 Jan 2001 10:53:33.032856 CET)
Now, you can ask for instance how many years this is:
> t->how_many(Calendar.Year);
Result: 362
Or how many 17 seconds it is:
> t->how_many(Calendar.Second()*17);
Result: 672068344
A note here is to use ->distance, and not ->range, since that
will include the destination unit too:
> Calendar.dwim_day("00-01-02")->range(Calendar.Week(2000,2))
->how_many(Calendar.Day());
Result: 15
> Calendar.dwim_day("00-01-02")->distance(Calendar.Week(2000,2))
->how_many(Calendar.Day());
Result: 8
-------------------------------------------------------------------------
Q: In 983112378 days, what weekday will it be?
A: (this weekday + 983112378) % 7 ;)
or take this day, add the number, and ask the object:
> (Calendar.Day()+983112378)->week_day_name();
Result: "Saturday"
"+int" will add this number of the unit to the unit;
this means that Calendar.Year()+2 will move two years
forward, but Calendar.now()+2 will not move at all
- since now has zero size.
To add a number of another time unit, simply do that:
> Calendar.Day()+3*Calendar.Year();
Result: Day(Sat 10 Jan 2004)
> Calendar.Day()+3*Calendar.Minute()*134;
Result: Minute(Wed 10 Jan 2001 6:42 CET - Thu 11 Jan 2001 6:42 CET)
The last result here is because the resulting time still will
be as long as the first.
-------------------------------------------------------------------------
Q: Are there other calendars?
A: Yes.
Calendar.Day is really a shortcut to Calendar.ISO.Day.
There is currently:
Gregorian
This is the base module for Julian style calendars;
despite the name. Most calendars of today are in sync
with the Gregorian calendar.
ISO
This inherits the Gregorian calendar to tweak it to
conform to the ISO standards. Most affected are weeks,
which starts on Monday in the ISO calendar.
This is also the default calendar.
Discordian
The Discordian calendar as described in Principia Discordia
is in sync with the Gregorian calendar (although some claim
that it should be the Julian - I go with what I can read
from my Principia Discordia). The module inherits and
tweaks the Gregorian module.
Coptic
The Coptic calendar is by some sources ("St. Marks'
Coptic Orthodox Church" web pages) is for now on in sync with
the Gregorian Calendar, so this module too inherits
and tweaks the Gregorian module. It needs to be
adjusted for historical use.
Julian
This is the Julian calendar, with the small changes
to the Gregorian calendar (leap years).
Badi (Baha'i)
The Badi calendar used by the Baha'i religion is based on the
solar year. For the time being it is in sync with the Gregorian
calendar.
Islamic
This is the Islamic calendar, using the 'Calendrical
Calculations' rules for new moon. It is based
directly on the YMD module.
Stardate
This is the (TNG) Stardate calendar, which consists
of one time unit only, the Tick (1000 Tick is one earth year).
It is based directly on TimeRanges.
-------------------------------------------------------------------------
Q: How do I convert between the calendars?
A: You give the unit to be converted to the constructor of
the unit you want it to be.
> Calendar.Coptic.Day(Calendar.dwim_day("14 feb 1983"));
Result: Day(Mon 7 Ams 1699)
> Calendar.Islamic.Minute(Calendar.dwim_day("14 feb 1983"));
Result: Minute(aha 29 Rebîul-âchir 1403 AH 13:00 CET -
ith 1 Djumâda'l-ûla 1403 AH 13:00 CET)
> Calendar.Day(Calendar.Stardate.Tick(4711));
Result: Day(Sat 17 Sep 2327 0:00 sharp)
-------------------------------------------------------------------------
Q: Isn't there a <my country> calendar?
A: <your country> uses the ISO calendar, with just different
names for the months. Language is a parameter to the
calendar units, as well as the timezone.
You set the language by using ->set_language(yourlanguage).
> t->set_language("pt")->format_ext_ymd();
Result: "Quarta-feira, 10 Janeiro 2001"
> t->set_language("roman")->format_ext_ymd();
Result: "Mercurii dies, X Ianuarius MMDCCLIII ab urbe condita"
Note that all languages aren't supported. If you miss your
favourite language or I got it all wrong (or have some time over
to help me out), look in the Language.pmod file and send me an
update.
Or send me a list of the weekdays and month names
(please start with Monday and January).
Currently, these languages are supported:
name code
-------------------------------
ISO (default, aka English)
Afrikaans af afr (South Africa),
Austrian de_AT
Basque eu eus (Spain)
Catalan ca cat (Catalonia)
Croatian hr hrv
Danish da dan
Dutch nl nld
English en eng
Estonian et est
Faroese fo fao
Finnish fi fin
French fr fra
Galician gl glg (Spain)
German de deu
Greenlandic kl kal
Hungarian hu hun
Icelandic is isl
Irish ga gle (Gaelic)
Italian it ita
Latvian lv lav
Lithuanian lt lit
Norwegian no nor
Persian fa fas (Iran)
Polish pl pol
Portugese pt por
Romanian ro ron
Serbian sr srp (Yugoslavia)
Slovenian sl slv
Spanish es spa
Swedish sv swe
Turkish tr
Welsh cy cym
Latin la lat
Roman (Roman Latin)
-------------------------------------------------------------------------
Q: Isn't there a <whatever> calendar?
A: Not if it isn't listed above. I'll appreciate any
implementation help if you happen to have the time over
to implement some calendar.
I know I miss these:
Chinese
Jewish or Hebreic
Maya
Of these, the two first are based on astronomical events,
which I haven't had the time to look into yet, but the
last - Maya - is totally numeric.
-------------------------------------------------------------------------
Q: I don't like that weeks starts on Mondays.
Every school kids knows that weeks start on Sundays.
A: According to the ISO 8601 standard, weeks start on mondays.
If you don't like it, use Calendar.Gregorian.Day, etc.
-------------------------------------------------------------------------
Q: How do I find out which days are red in a specific region?
A: Events.<region>
- contains the events for the region, as a SuperEvent.
You can ask this object to filter out the holidays,
Events.se->holidays();
which will be a superevent containing only holidays.
To use this information, you can for instance use ->scan,
here in an example to see what red days there are in Sweden
the current month:
> Calendar.Events.se->filter_flag("h")->scan(Calendar.Month());
Result: ({ /* 6 elements */
Day(Sun 7 Jan 2001),
Day(Sun 14 Jan 2001),
Day(Sun 21 Jan 2001),
Day(Sun 28 Jan 2001),
Day(Sat 6 Jan 2001),
Day(Mon 1 Jan 2001)
})
-------------------------------------------------------------------------
Q: How accurate are the events information?
A: For some regions, very. For most regions, not very.
The first reason is lack of information of this kind on
the web, especially sorted into useful rules (like "the
third monday after 23 dec", not "8 jan").
The second reason is lack of time and interest to do
research, which is a rather tedious job.
If you want to help, the check your region in the
events/regions file and send us <pike@roxen.com> a patch.
Don't send me "the x region is all wrong!" mails without
telling me what it should look like.
-------------------------------------------------------------------------
Q: My timezone says it's DST. It's wrong.
A: No it isn't. But:
o The local timezone detector failed to find your timezone by
itself, or found the wrong timezone.
o or you use the wrong timezone.
To make sure the right timezone is used, use the standard
timezone names. Those aren't "CET" or "PST", but
"Europe/Amsterdam" or "America/Dawson".
OR this may be in the future and you have a changed DST
rule and uses an old Pike. Then you can either download
a new version or download new timezone data files from
the ftp address below (if the internet still is there).
This needs to be reformatted as documentation.
constant
Calendar.nulltimerange
= TimeRange
This represents the null time range,
which, to differ from the zero time range
(the zero-length time range), isn't placed
in time. This is the result of for instance
`&
between two strict non-overlapping
timeranges - no time at all.
It has a constant, is_nulltimerange, which is non-zero. `! on this timerange is true.
This is the base class of the calendars.
Calendar.TimeRanges.TimeRange
now()
Give the zero-length time period of the current time.
This is the container class for rules.
bool
res = Calendar.Ruleset()
== other
this_program
clone()
this_program
set_abbr2zone(mapping
(string
:string
) abbr2zone
)
Sets the guess-mapping for timezones. Default is the mapping:
Abbreviation | Interpretation | UTC |
AMT | America/Manaus | UTC-4 |
AST | America/Curacao | UTC-4 |
CDT | America/Costa_Rica | UTC-5 |
CST | America/El Salvador | UTC-6 |
EST | America/Panama | UTC-5 |
GST | Asia/Dubai | UTC+4 |
IST | Asia/Jerusalem | UTC+2 |
WST | Australia/Perth | UTC+8 |
YMD.parse
this_program
set_language(string
|Calendar.Rule.Language
lang
)
this_program
set_rule(Calendar.Rule.Language
|Calendar.Rule.Timezone
rule
)
this_program
set_timezone(string
|Calendar.Rule.Timezone
t
)
This class handles the cases where you have a time period with holes. These can be created by the ^ or | operators on time ranges.
Calendar.SuperTimeRange Calendar.SuperTimeRange(
array
(TimeRange
) parts
)
A SuperTimeRange must have at least two parts, two time ranges. Otherwise, it's either not a time period at all or a normal time period.
inherit TimeRange : TimeRange
Same as the ISO
calendar,
but with austrian as the default language.
This calendar exist only for backwards compatible purposes.
inherit Calendar.ISO : ISO
This is the Badi calendar, used in the Baha'i religion.
int
daystart_offset()
Returns the offset to the start of the time range object
inherit Calendar.YMD : YMD
inherit YMD : YMD
Year
year()
Year
year(int
n
)
Year
year(string
name
)
Return a year in the vahid by number or name:
vahid->year("Alif")
This is the Coptic Orthodox Church calendar, that starts the 11th or 12th September and has 13 months.
The (default) names of the months are different then other the emacs calendar; I do not know which ones are used - the difference seem to be only the transcription of the phonetic sounds (B <-> P, etc).
I do not know for how long back the calendar is valid,
either. My sources claim that the calendar is synchronized
with the Gregorian
calendar, which is odd.
inherit Calendar.Gregorian : Gregorian
The Discordian calendar, as described on page 34 in the fourth edition of Principia Discordia.
Chaotic enough, it's quite simpler then the Gregorian
calendar;
weeks are 5 days, and evens up on a year. Months are 73 days.
The leap day is inserted at the 60th day of the first month (Chaos), giving the first month 74 days. The description of the calendar is a "perpetual date converter from the gregorian to the POEE calendar", so the leap years are the same as the gregorians.
The Principia calls months "seasons", but for simplicity I call them months in this calendar.
If anyone know more about how to treat the leap day - now it is inserted in the month and week where it lands, rather then being separated from month and weeks, I'm interested to know.
- Mirar, Pope of POEE.
inherit Calendar.Gregorian : Gregorian
This class represents the event of a given gregorian date. For instance, Event.Date(12,10)->next(Day()) finds the next 12 of October.
Calendar.Event.Date Calendar.Event.Date(
int(1..31)
month_day
, int(1..12)
month
)
The event is created by a given month day and a month number (1=January, 12=December).
inherit Day_Event : Day_Event
This class represents the event that a given gregorian date appears a given weekday. For instance, Event.Date_Weekday(12,10,5)->next(Day()) finds the next 12 of October that is a friday.
Calendar.Event.Date_Weekday Calendar.Event.Date_Weekday(
int
month_day
, int
month
, int
weekday
)
The event is created by a given month day, a month number (1=January, 12=December), and a weekday number (1=Monday, 7=Sunday).
The week day numbers used are the same as the day of week in
the ISO
calendar - the Gregorian
calendar has 1=Sunday,
7=Saturday.
inherit Day_Event : Day_Event
Day_Event
is an abstract class, extending Event
for events
that are single days, using julian day numbers for the calculations.
constant
int
Calendar.Event.Day_Event.NODAY
Returned from scan_jd
if the even searched for did not
exist.
inherit Event : Event
constant
int
Calendar.Event.Day_Event.is_day_event
This constant may be used to identify Day_Event
objects.
Calendar.TimeRanges.TimeRange
next(void
|Calendar.TimeRanges.TimeRange
from
, void
|bool
including
)
Uses the virtual method scan_jd
.
Event.next
Calendar.TimeRanges.TimeRange
previous(void
|Calendar.TimeRanges.TimeRange
from
, void
|bool
including
)
Uses the virtual method scan_jd
.
Event.previous
int
scan_jd(Calendar.Calendar
realm
, int
jd
, int(-1..-1)
|int(1..1)
direction
)
This method has to be defined, and is what really does some work.
direction
| Forward (next), |
| Backward (previous). |
It should return the next or previous
julian day (>jd) when the event occurs,
or the constant NODAY
if it doesn't.
This class represents an easter.
Calendar.Event.Easter Calendar.Event.Easter(
void
|int
shift
)
shift
is the year to shift from old to new style easter
calculation. Default is 1582.
int
easter_yd(int
y
, int
yjd
, int
leap
)
Calculates the year day for the easter.
inherit Day_Event : Day_Event
This class represents an easter relative event.
Calendar.Event.Easter_Relative Calendar.Event.Easter_Relative(
string
id
, string
name
, int
offset
)
inherit Easter : Easter
Event is an abstract class, defining what methods an Event need to have.
SuperEvent
res = Calendar.Event.Event()
| with
SuperEvent
res = with
| Calendar.Event.Event()
Joins several events into one SuperEvent
.
string
describe()
Returns a description of the event.
constant
int
Calendar.Event.Event.is_event
This constant may be used to identify an event object.
Calendar.TimeRanges.TimeRange
next(void
|Calendar.TimeRanges.TimeRange
from
, void
|bool
including
)
Calendar.TimeRanges.TimeRange
previous(void
|Calendar.TimeRanges.TimeRange
from
, void
|bool
including
)
This calculates the next or previous occurance of the event, from the given timerange's start, including any event occuring at the start if that flag is set.
It returns zero if there is no next event.
These methods are virtual in the base class.
array
(Calendar.TimeRanges.TimeRange
) scan(Calendar.TimeRanges.TimeRange
in
)
This calculates the eventual events that is contained or
overlapped by the given timerange. scan
uses next
, if not
overloaded.
Calendar.Event.Easter()->scan(Calendar.Year(2000)) => ({ Day(Sun 23 Apr 2000) })
scan
can return an array of overlapping timeranges.
This method must use in->calendar_object->type to create the returned timeranges, and must keep the ruleset.
mapping
(Calendar.TimeRanges.TimeRange
:Event
) scan_events(Calendar.TimeRanges.TimeRange
in
)
Returns a mapping with time ranges mapped to events.
A set date of year, counting leap day in February, used for the Gregorian fixed events in the events list.
Julian_Fixed
Calendar.Event.Gregorian_Fixed Calendar.Event.Gregorian_Fixed(
string
id
, string
name
, int(1..31)
month_day
, int(1..12)
month
, int
extra
)
inherit Day_Event : Day_Event
constant
int
Calendar.Event.Gregorian_Fixed.is_fixed
This constant may be used to identify Gregorian_Fixed
objects.
A set date of year, counting leap day in February, used for the Gregorian fixed events in the events list.
Gregorian_Fixed
inherit Gregorian_Fixed : Gregorian_Fixed
constant
int
Calendar.Event.Julian_Fixed.is_julian_fixed
This constant may be used to identify Julian_Fixed
objects.
This class represents the event that a given gregorian day of month appears a given weekday. For instance, Event.Monthday_Weekday(13,5)->next(Day()) finds the next friday the 13th.
Calendar.Event.Monthday_Weekday Calendar.Event.Monthday_Weekday(
int
month_day
, int
weekday
)
The event is created by a given month day, and a weekday number (1=Monday, 7=Sunday).
The week day numbers used are the same as the day of week in
the ISO
calendar - the Gregorian
calendar has 1=Sunday,
7=Saturday.
inherit Day_Event : Day_Event
This class represents a monthday weekday relative event or n:th special weekday event, e.g. "fourth sunday before 24 dec" => md=24,mn=12,wd=7,n=-4
Calendar.Event.Monthday_Weekday_Relative Calendar.Event.Monthday_Weekday_Relative(
string
id
, string
name
, int(1..31)
md
, int(1..12)
mn
, int(1..7)
_wd
, int
_n
, void
|bool
_inclusive
)
inherit Gregorian_Fixed : Gregorian_Fixed
This is created by the Namedays
classes
to represent an event for a name.
inherit Day_Event : Day_Event
constant
int
Calendar.Event.Nameday.is_nameday
This constant may be used to identify Nameday
objects.
This contains a ruleset about namedays.
inherit Event : Event
constant
int
Calendar.Event.Namedays.is_namedays
This constant may be used to identify Namedays
.
mapping
(Calendar.TimeRanges.TimeRange
:array
(string
)) namedays(Calendar.TimeRanges.TimeRange
t
)
Gives back an table of days with names that occur during the time period. Note that days without names will not appear in the returned mapping.
array
(string
) names(Calendar.TimeRanges.TimeRange
t
)
Gives back an array of names that occur during the time period, in no particular order.
A non-event.
inherit Event : Event
constant
int
Calendar.Event.NullEvent.is_nullevent
This constant may be used to identify a NullEvent.
This class represents an orthodox easter relative event.
Calendar.Event.Orthodox_Easter_Relative Calendar.Event.Orthodox_Easter_Relative(
string
id
, string
name
, int
offset
)
inherit Easter_Relative : Easter_Relative
This class represents a solar event as observed from Earth.
The event_type
is one of
| Northern hemisphere spring equinox. |
| Northern hemisphere summer solstice. |
| Northern hemisphere autumn equinox. |
| Northern hemisphere winter solstice. |
Calendar.Event.Solar Calendar.Event.Solar(
int
|void
event_type
)
int
|void
Calendar.Event.Solar.event_type
inherit Day_Event : Day_Event
Calendar.Event.Solar.protected
constantperiodic_table
Array | |||||||||
|
|
Calendar.TimeRanges.TimeRange
previous(void
|Calendar.TimeRanges.TimeRange
from
, void
|bool
including
)
Uses the virtual method scan_jd
.
Event.previous
int
scan_jd(Calendar.Calendar
realm
, int
jd
, int(1..1)
|int(-1..-1)
direction
)
Returns unixtime in UTC to avoid losing the decimals!
array
(int
|float
) solar_event(int
y
)
Calculate the next event.
Based on Meeus Astronomical Algorithms Chapter 27.
This class holds any number of events, and adds the functionality of event flags.
Scanning (scan_events,next,etc) will drop flag information.
Dig out what you need with holidays
et al first.
SuperEvent
filter_flag(string
flag
)
SuperEvent
holidays()
SuperEvent
flagdays()
Filter out the events that has a certain flag set. Holidays (flag "h") are the days that are marked red in the calendar (non-working days), Flagdays (flag "f") are the days that the flag should be visible in (only some countries).
inherit Event : Event
Container for merged Namedays
objects. Presumes non-overlapping
namedays
Calendar.Event.SuperNamedays Calendar.Event.SuperNamedays(
array
(Nameday
) namedayss
, string
id
)
array
(Nameday
) Calendar.Event.SuperNamedays.namedayss
string
Calendar.Event.SuperNamedays.id
inherit Event : Event
Event containing information about when a timezone is changed.
inherit Event : Event
protected
Calendar.TimeRanges.TimeRange
scan_history(Calendar.Rule.Timezone
tz
, Calendar.TimeRanges.TimeRange
from
, int
direction
, bool
including
)
protected
Calendar.TimeRanges.TimeRange
scan_rule(Calendar.Rule.Timezone
tz
, Calendar.TimeRanges.TimeRange
from
, int
direction
, int
including
)
protected
Calendar.TimeRanges.TimeRange
scan_shift(Calendar.Rule.Timezone
tz
, Calendar.TimeRanges.TimeRange
from
, int
direction
, int
including
)
This class represents any given weekday. For instance, Event.Weekday(5)->next(Day()) finds the next friday.
These are also available as the pre-defined events Events.monday
,
Events.tuesday
, Events.wednesday
, Events.thursday
,
Events.friday
, Events.saturday
and Events.sunday
.
Calendar.Event.Weekday Calendar.Event.Weekday(
int
weekday
, void
|string
id
)
The event is created by a given weekday number (1=Monday, 7=Sunday).
The week day numbers used are the same as the day of week in
the ISO
calendar - the Gregorian
calendar has 1=Sunday,
7=Saturday.
inherit Day_Event : Day_Event
The Event system
Q: How do I find out which days are red in a specific region?
A: Events.<region>
- contains the events for the region, as a SuperEvent. You can ask this object to filter out the holidays,
Events.se.holidays();
Which will be a superevent containing only holidays.
To use this information, you can for instance use ->scan, here in an example to see what red days there were in Sweden in 2001
> Calendar.Events.se->filter_flag("h")->scan(Calendar.Month());
Result: ({ /* 6 elements */
Day(Sun 7 Jan 2001),
Day(Sun 14 Jan 2001),
Day(Sun 21 Jan 2001),
Day(Sun 28 Jan 2001),
Day(Sat 6 Jan 2001),
Day(Mon 1 Jan 2001)
Event.Event
`[](string
region
)
Event.Event
`->(string
region
)
return the Event object for the specified region or the specified named event.
This is the standard conservative christian calendar,
used regularly in some countries - USA, for instance - and
which derivate - the ISO
calendar - is used in most of
Europe.
inherit Calendar.YMD : YMD
This is the standard western calendar, which is a derivate of the Gregorian calendar, but with weeks that starts on Monday instead of Sunday.
inherit Calendar.Gregorian : Gregorian
This is the islamic calendar. Due to some sources, they decide the first day of the new months on a month-to-month basis (sightings of the new moon), so it's probably not that accurate. If someone can confirm (or deny) accuracy better than that, please contact me so I can change this statement.
It's vaugely based on rules presented in algorithms by Dershowitz, Reingold and Clamen, 'Calendrical Calculations'. It is the same that's used in Emacs calendar mode.
I have currently no idea how the arabic countries
count the week. Follow the same rules as ISO
for now... The time is also suspicious; the day
really starts at sunset and not midnight,
the hours of the day is not correct. Also don't know
what to call years before 1 - go for "BH"; positive
years are "AH", anno Hegirac.
inherit Calendar.YMD : YMD
This is the Julian calendar, conjured up by the old Romans when their calendar were just too weird. It was used by the christians as so far as the 18th century in some parts of the world. (Especially the protestantic and orthodox parts.)
Don't confuse the julian day with the Julian calendar. The former is just a linear numbering of days, used in the Calendar module as a common unit for absolute time.
inherit Calendar.Gregorian : Gregorian
Contains a time zone.
Calendar.Rule.Timezone Calendar.Rule.Timezone(
int
offset
, string
name
)
offset
Offset to UTC, not counting DST.
name
The name of the time zone.
int
raw_utc_offset()
Returns the offset to UTC, not counting DST.
array
tz_jd(int
julian_day
)
This method takes one integer argument, ignores it and returns an array with the UTC offset and the timezone name.
array
tz_ux(int
unixtime
)
This method takes one integer argument, ignores it and returns an array with the UTC offset and the timezone name.
This implements TNG stardates.
cTick
now()
Give the zero-length time period of the current time.
Calendar.Stardate.cTick Calendar.Stardate.cTick(
mixed
... args
)
Calendar.Stardate.cTick Calendar.Stardate.cTick(
int
|float
date
)
Calendar.Stardate.cTick Calendar.Stardate.cTick()
Apart from the standard creation methods (julian day, etc), you can create a stardate from the stardate number. The length of the period will then be zero.
You can also omit any arguments to create now.
Since the precision is limited to the float type of Pike you can get non-precise results:
> Calendar.Second(Calendar.Stardate.Day(Calendar.Year()));
Result: Second(Fri 31 Dec 1999 23:59:18 CET - Sun 31 Dec 2000 23:59:18 CET)
string
format_long(void
|int
precision
)
string
format_short(void
|int
precision
)
string
format_vshort(void
|int
precision
)
Format the stardate tick nicely. Precision is the number of decimals. Defaults to 3.
long | "-322537.312" | |
short | "77463.312" | (w/o >100000-component) |
vshort | "7463.312" | (w/o >10000-component) |
inherit Calendar.TimeRange : TimeRange
int
number_of_days()
This gives back the Gregorian/Earth/ISO number of days, for convinience and conversion to other calendars.
int
number_of_seconds()
This gives back the Gregorian/Earth/ISO number of seconds, for convinience and conversion to other calendars.
float
tic()
This gives back the start of the stardate period, as a float.
float
tics()
This gives back the number of stardate tics in the period.
Same as the ISO
calendar, but with Swedish as the default language.
This calendar exist only for backwards compatible purposes.
inherit Calendar.ISO : ISO
This module contains listnings of available timezones, in some different ways
string
_zone_tab()
array
(array
) zone_tab()
This returns the raw respectively parsed zone tab file from the timezone data files.
The parsed format is an array of zone tab line arrays,
({ string country_code, string position, string zone_name, string comment })
To convert the position to a Geography.Position, simply feed it to the constructor.
constant
Calendar.TZnames.abbr2zones
= mapping
(string
:array
(string
))
This mapping is used to look up abbreviation to the possible regional zones.
It looks like this:
([ "CET": ({ "Europe/Stockholm", <i>[...]</i> }), "CST": ({ "America/Chicago", "Australia/Adelaide", <i>[...]</i> }), <i>[...]</i> }),
Note this: Just because it's noted "CST" doesn't mean it's a unique timezone. There is about 7 *different* timezones that uses "CST" as abbreviation; not at the same time, though, so the DWIM routines checks this before it's satisfied. Same with some other timezones.
For most timezones, there is a number of region timezones that for the given time are equal. This is because region timezones include rules about local summer time shifts and possible historic shifts.
The YMD.parse
functions can handle timezone abbreviations
by guessing.
array
(string
) zonenames()
This reads the zone.tab file and returns name of all standard timezones, like "Europe/Belgrade".
constant
Calendar.TZnames.zones
= mapping
(string
:array
(string
))
This constant is a mapping that can be used to loop over to get all the region-based timezones.
It looks like this:
([ "America": ({ "Los_Angeles", "Chicago", <i>[...]</i> }), "Europe": ({ "Stockholm", <i>[...]</i> }), <i>[...]</i> }),
Please note that loading all the timezones can take some time, since they are generated and compiled on the fly.
Base for time of day in calendars, ie calendars with hours, minutes, seconds
This module can't be used by itself, but
is inherited by other modules (ISO
by YMD
,
for instance).
inherit TimeRanges : TimeRanges
A Fraction is a part of a second, and/or a time period with higher resolution then a second.
It contains everything that is possible to do with a
Second
, and also some methods of grabbing
the time period with higher resolution.
Internally, the fraction time period is measured in nanoseconds. A shorter or more precise time period then in nanoseconds is not possible within the current Fraction class.
Calendar.Time.Fraction Calendar.Time.Fraction()
Calendar.Time.Fraction Calendar.Time.Fraction(
"unix"
, int
|float
unixtime
)
Calendar.Time.Fraction Calendar.Time.Fraction(
"unix"
, int
|float
unixtime
, int
|float
len
)
Calendar.Time.Fraction Calendar.Time.Fraction(
int
y
, int
m
, int
d
, int
h
, int
m
, int
s
, int
ns
)
It is possible to create a Fraction in three ways, either "now" with no arguments or from a unix time (as from time(2)), or the convenience way from ymd-hms integers.
If created from unix time, both the start of the period and the size of the period can be given in floats, both representing seconds. Note that the default float precision in pike is rather low (same as 'float' in C, the 32 bit floating point precision, normally about 7 digits), so beware that the resolution might bite you. (Internally in a Fraction, the representation is an integer.)
If created without explicit length, the fraction will always be of zero length.
inherit Second : Second
TimeofDay
now()
Give the zero-length time period of the current time.
Calendar
set_ruleset(Ruleset
r
)
Ruleset
ruleset()
Set or read the ruleset for the calendar.
set_ruleset
returns a new calendar object,
but with the new ruleset.
Calendar
set_timezone(Timezone
tz
)
Calendar
set_timezone(string
|Timezone
tz
)
TimeZone
timezone()
Set or get the current timezone (including dst) rule.
set_timezone
returns a new calendar object,
as the called calendar but with another set of rules.
Example:
> Calendar.now(); Result: Fraction(Fri 2 Jun 2000 18:03:22.010300 CET) > Calendar.set_timezone(Calendar.Timezone.UTC)->now(); Result: Fraction(Fri 2 Jun 2000 16:03:02.323912 UTC)
inherit TimeofDay : TimeofDay
inherit TimeofDay : TimeofDay
inherit TimeofDay : TimeofDay
Second
second()
Second
second(int
n
)
array
(Second
) seconds()
array
(Second
) seconds(int
first
, int
last
)
int
number_of_seconds()
Minute
minute()
Minute
minute(int
n
)
array
(Minute
) minutes()
array
(Minute
) minutes(int
first
, int
last
)
int
number_of_minutes()
Hour
hour()
Hour
hour(int
n
)
array
(Hour
) hours()
array
(Hour
) hours(int
first
, int
last
)
int
number_of_hours()
Similar to TimeofDay
, the Time::SuperTimeRange
has a number of methods for digging out time parts of the
range. Since a SuperTimeRange
is a bit more
complex - the major reason for its existance it that it
contains holes, this calculation is a bit more advanced too.
If a range contains the seconds, say, 1..2 and 4..5, the third second (number 2, since we start from 0) in the range would be number 4, like this:
no means this second 0 1 1 2 2 4 <- second three is missing, 3 5 as we don't have it in the example range
number_of_seconds
() will in this example
therefore also report 4, not 5, even if the time from
start of the range to the end of the range is 5 seconds.
inherit TimeRanges.SuperTimeRange : SuperTimeRange
Virtual class used by e.g. Hour.
void
call_out(function
(:void
) fun
, mixed
...args
)
Creates a call_out to this point in time.
Calendar.Time.TimeofDay Calendar.Time.TimeofDay()
Calendar.Time.TimeofDay Calendar.Time.TimeofDay(
int
unixtime
)
In addition to the wide range of construction arguments
for a normal TimeRange (see TimeRange.create
),
a time of day can also be constructed with unixtime
as single argument consisting of the unix time
- as returned from time(2) - of the time unit start.
It can also be constructed without argument, which then means "now", as in "this minute".
mapping
datetime()
This gives back a mapping with the relevant time information (representing the start of the period);
([ "year": int // year number (2000 AD=2000, 1 BC==0) "month": int(1..) // month of year "day": int(1..) // day of month "yearday": int(1..) // day of year "week": int(1..) // week of year "week_day": int(1..) // day of week (depending on calendar) "hour": int(0..) // hour of day, including dst "minute": int(0..59) // minute of hour "second": int(0..59) // second of minute "fraction": float // fraction of second "timezone": int // offset to utc, including dst "unix": int // unix time "julian": float // julian day ]);
string
format_iso_ymd()
string
format_ymd()
string
format_ymd_short()
string
format_ymd_xshort()
string
format_iso_week()
string
format_iso_week_short()
string
format_week()
string
format_week_short()
string
format_month()
string
format_month_short()
string
format_iso_time()
string
format_time()
string
format_time_short()
string
format_iso_short()
string
format_time_xshort()
string
format_mtime()
string
format_xtime()
string
format_tod()
string
format_xtod()
string
format_mod()
string
format_nice()
string
format_nicez()
Format the object into nice strings;
iso_ymd "2000-06-02 (Jun) -W22-5 (Fri)" [2] ext_ymd "Friday, 2 June 2000" [2] ymd "2000-06-02" ymd_short "20000602" ymd_xshort "000602" [1] iso_week "2000-W22" iso_week_short "2000W22" week "2000-w22" [2] week_short "2000w22" [2] month "2000-06" month_short "200006" [1] iso_time "2000-06-02 (Jun) -W22-5 (Fri) 20:53:14 UTC+1" [2] ext_time "Friday, 2 June 2000, 20:53:14" [2] ctime "Fri Jun 4 20:53:14 2000\n" [2] [3] http "Fri, 02 Jun 2000 19:53:14 GMT" [4] time "2000-06-02 20:53:14" time_short "20000602 20:53:14" time_xshort "000602 20:53:14" iso_short "20000602T20:53:14" mtime "2000-06-02 20:53" xtime "2000-06-02 20:53:14.000000" todz "20:53:14 CET" todz_iso "20:53:14 UTC+1" tod "20:53:14" tod_short "205314" xtod "20:53:14.000000" mod "20:53" nice "2 Jun 20:53", "2 Jun 2000 20:53:14" [2][5] nicez "2 Jun 20:53 CET" [2][5] smtp "Fri, 2 Jun 2000 20:53:14 +0100" [6] commonlog "02/Jun/2000:20:53:14 +0100" [2][1] note conflict (think 1 February 2003)
int
hour_no()
int
minute_no()
int
second_no()
float
fraction_no()
This gives back the number of the time unit, on this day. Fraction is a float number, 0<=fraction<1.
Hour
hour()
Hour
hour(int
n
)
array
(Hour
) hours()
array
(Hour
) hours(int
first
, int
last
)
int
number_of_hours()
hour
() gives back the timerange representing the
first or nth Hour of the called object.
Note that hours normally starts to count at zero,
so ->hour(2) gives the third hour within
the range.
An Hour is in the Calendar perspective as any other time range not only 60 minutes, but also one of the (normally) 24 hours of the day, precisely.
hours
() give back an array of all the hours
containing the time periods called. With arguments,
it will give back a range of those hours, in the
same enumeration as the n to hour
().
number_of_hours
() simple counts the
number of hours containing the called time period.
Note: The called object doesn't have to *fill* all the hours it will send back, it's enough if it exist in those hours:
> object h=Calendar.Time.Hour(); Result: Hour(265567) > h->hours(); Result: ({ /* 1 element */ Hour(265567) }) > h+=Calendar.Time.Minute(); Result: Minute(265567:01+60m) > h->hours(); Result: ({ /* 2 elements */ Hour(265567), Hour(265568) })
inherit TimeRange : TimeRange
float
julian_day()
This calculates the corresponding julian day, from the time range. Note that the calculated day is the beginning of the period, and is a float - julian day standard says .00 is midday, 12:00 pm.
Normal pike (ie, 32 bit) floats (without --with-double-precision) has a limit of about 7 digits, and since we are about julian day 2500000, the precision on time of day is very limited.
Minute
minute()
Minute
minute(int
n
)
array
(Minute
) minutes()
array
(Minute
) minutes(int
first
, int
last
)
int
number_of_minutes()
minute
() gives back the timerange representing the
first or nth Minute of the called object.
Note that minutes normally starts to count at zero,
so ->minute(2) gives the third minute within
the range.
An Minute is in the Calendar perspective as any other
time range not only 60 seconds, but also one
of the (normally) 60 minutes of the Hour
, precisely.
minutes
() give back an array of all the minutes
containing the time periods called. With arguments,
it will give back a range of those minutes, in the
same enumeration as the n to minute
().
number_of_minutes
() simple counts the
number of minutes containing the called time period.
TimeRange
move_seconds(int
seconds
)
TimeRange
move_ns(int
nanoseconds
)
These two methods gives back the time range called moved the specified amount of time, with the length intact.
The motion is relative to the original position in time; 10 seconds ahead of 10:42:32 is 10:42:42, etc.
Second
second()
Second
second(int
n
)
array
(Second
) seconds()
array
(Second
) seconds(int
first
, int
last
)
int
number_of_seconds()
second
() gives back the timerange representing the
first or nth Second of the called object.
Note that seconds normally starts to count at zero,
so ->second(2) gives the third second within
the range.
seconds
() give back an array of all the seconds
containing the time periods called. With arguments,
it will give back a range of those seconds, in the
same enumeration as the n to second
().
number_of_seconds
() simple counts the
number of seconds containing the called time period.
TimeRange
set_size_seconds(int
seconds
)
TimeRange
set_size_ns(int
nanoseconds
)
These two methods allows the time range to be edited by size of specific units.
int
unix_time()
This calculates the corresponding unix time, - as returned from time(2) - from the time range. Note that the calculated unix time is the beginning of the period.
This is the base class (usually implemented by e.g. Calendar subclasses like Calendar.Second) for any time measurement and calendrar information. It defines all the things you can do with a time range or any time period.
A TimeRange doubles as both a fixed period in time, and an amount of time. For instance, a week plus a day moves the week-period one day ahead (unaligning it with the week period, and thereby reducing it to just 7 days), no matter when in time the actual day were.
bool
res = Calendar.TimeRanges.TimeRange()
== compared_to
bool
equal(Calendar.TimeRanges.TimeRange from, TimeRange
compared_to
)
These two overloads the operator `== and the result of the equal function.
a==b is considered true if the two timeranges are of the same type, have the same rules (language, timezone, etc) and are the same timerange.
equal(a,b) are considered
true if a and b are the same timerange, exactly the same
as the equals
method.
The __hash method is also present, to make timeranges possible to use as keys in mappings.
known bugs: _equal is not currently possible to overload, due to weird bugs, so equal uses `== for now.
TimeRange
res = Calendar.TimeRanges.TimeRange()
& with
Gives the cut on the called time period with another time period. The result is zero if the two periods doesn't overlap.
>- the past the future -< |-------called-------| |-------other--------| >----- cut -----<
TimeRange
res = Calendar.TimeRanges.TimeRange()
* n
This changes the amount of time in
the time period. t*17 is
the same as doing t->set_size
(t,17).
TimeRange
res = Calendar.TimeRanges.TimeRange()
+ n
TimeRange
res = Calendar.TimeRanges.TimeRange()
+ offset
TimeRange
res = Calendar.TimeRanges.TimeRange()
- m
TimeRange
res = Calendar.TimeRanges.TimeRange()
- x
This calculates the (promoted) time period
either n step away or with a given offset.
These functions does use add
to really
do the job:
t+n t->add(n) t is a time period t-n t->add(-n) offset is a time period t+offset t->add(1,offset) n is an integer t-offset t->add(-1,offset) n+t t->add(n) n-t illegal offset+t offset->add(1,t) | note this! offset-t offset->add(-1,t) |
Mathematic rules:
x+(t-x) == t x is an integer or a time period (x+t)-x == t t is a time period (t+x)-x == t o-(o-t) == t o is a time period t++ == t+1 t-- == t-1
a-b does not give the distance between the start of a and b.
Use the distance
() function to calculate that.
The integer used to `+, `- and add are the number of steps the motion will be. It does never represent any fixed amount of time, like seconds or days.
array
(TimeRange
) res = Calendar.TimeRanges.TimeRange()
/ n
array
(TimeRange
) split(int
|float
n
, object
void|TimeRangewith
)
This divides the called timerange into n pieces. The returned timerange type is not necessarily of the same type as the called one. If the optional timerange is specified then the resulting timeranges will be multiples of that range (except for the last one).
known bugs:
These are currently not defined for
supertimeranges
.
int
res = Calendar.TimeRanges.TimeRange()
/ with
int
how_many(TimeRange
with
)
This calculates how many instances of the given timerange has passed during the called timerange.
For instance, to figure out your age,
create the timerange of your lifespan, and divide
with the instance of a Year
.
bool
res = Calendar.TimeRanges.TimeRange()
< compared_to
bool
res = Calendar.TimeRanges.TimeRange()
> compared_to
These operators sorts roughty on the periods place in time. The major use might be to get multiset to work, besides sorting events clearly defined in time.
TimeRange
res = Calendar.TimeRanges.TimeRange()
^ with
Gives the exclusive-or on the called time period and another time period, ie the union without the cut. The result is zero if the two periods were the same.
>- the past the future -< |-------called-------| |-------other--------| <----| |----> - exclusive or
TimeRange
res = Calendar.TimeRanges.TimeRange()
| with
Gives the union on the called time period and another time period.
>- the past the future -< |-------called-------| |-------other--------| <----------union---------->
TimeRange
add(int
n
, void
|TimeRange
step
)
calculates the (promoted) time period n steps away; if no step is given, the step's length is of the same length as the called time period.
It is not recommended to loop by adding the increment time period to a shorter period; this can cause faults, if the shorter time period doesn't exist in the incremented period. (Like week 53, day 31 of a month or the leap day of a year.)
Recommended use are like this:
// loop over the 5th of the next 10 months TimeRange month=Month()+1; TimeRange orig_day=month()->day(5); for (int i=0; i<10; i++) { month++; TimeRange day=month->place(orig_day); <i>...use day...</i> }
TimeRange
beginning()
TimeRange
end()
This gives back the zero-sized beginning or end of the called time period.
rule: range(t->beginning(),t->end())==t
Calendar
calendar()
Simply gives back the calendar in use, for instance Calendar.ISO or Calendar.Discordian.
bool
strictly_preceeds(TimeRange
what
)
bool
preceeds(TimeRange
what
)
bool
is_previous_to(TimeRange
what
)
bool
overlaps(TimeRange
what
)
bool
contains(TimeRange
what
)
bool
equals(TimeRange
what
)
bool
is_next_to(TimeRange
what
)
bool
succeeds(TimeRange
what
)
bool
strictly_succeeds(TimeRange
what
)
These methods exists to compare two periods of time on the timeline.
case predicates <-- past future -> |----A----| A strictly preceeds B, |----B----| A preceeds B |----A----| A strictly preceeds B, A preceeds B, |----B----| A is previous to B, A touches B |----A----| A preceeds B, |----B----| A overlaps B, A touches B |-------A-------| A preceeds B, A ends with B |----B----| A overlaps B, A contains B, A touches B, |-------A-------| A preceeds B, A succeeds B, |---B---| A overlaps B, A contains B, A touches B |----A----| A overlaps B, A touches B, A contains B |----B----| A equals B, A starts with B, A ends with B |-------A-------| A succeeds B, A starts with B |----B----| A overlaps B, A contains B, A touches B |----A----| A succeeds B, |----B----| A overlaps B, A touches B |----A----| A strictly succeeds B, A succeeds B |----B----| A is next to B, A touches B |----A----| A strictly succeeds B, |----B----| A succeeds B
These methods only check the range of the first to the
last time in the period;
use of combined time periods (SuperTimeRange
s)
might not give you the result you want.
`&
Calendar.TimeRanges.TimeRange Calendar.TimeRanges.TimeRange(
TimeRange
from
)
Create the timerange from another timerange.
This is useful when converting objects from
one calendar to another. Note that the ruleset will be
transferred to the new object, so this method
can't be used to convert between timezones
or languges - use set_timezone
,
set_language
or set_ruleset
to achieve this.
The size of the new object may be inexact; a Month object can't comprehend seconds, for instance.
Calendar.TimeRanges.TimeRange Calendar.TimeRanges.TimeRange(
"julian"
, int
|float
julian_day
)
Create the timerange from a julian day, the standardized method of counting days. If the timerange is more then a day, it will at least enclose the day.
Calendar.TimeRanges.TimeRange Calendar.TimeRanges.TimeRange(
"unix"
, int
unixtime
)
Calendar.TimeRanges.TimeRange Calendar.TimeRanges.TimeRange(
"unix"
, int
unixtime
, int
seconds_len
)
Create the timerange from unix time (as given by time(2)), with eventually the size of the time range in the same unit, seconds.
TimeRange
range(TimeRange
other
)
TimeRange
space(TimeRange
other
)
TimeRange
distance(TimeRange
other
)
Derives different time periods in between the called timerange and the parameter timerange.
>- the past the future -< |--called--| |--other--| >------------ range -----------< >--space--< >----- distance -----<
See also: add, TimeRanges.range, TimeRanges.space, TimeRanges.distance
TimeRange
set_language(Rule.Language
lang
)
TimeRange
set_language(string
lang
)
Language
language()
Set or get the current language rule.
TimeRange
next()
TimeRange
prev()
Next and prev are compatible and convinience functions; a->next() is exactly the same as a+1; a=a->next() is a++.
int
offset_to(TimeRange
x
)
Calculates offset to x; this compares two timeranges and gives the integer offset between the two starting points.
This is true for suitable a and b: a+a->offset_to(b)==b
By suitable means that a and b are of the same type and size. This is obviously true only if a+n has b as a possible result for any n.
TimeRange
place(TimeRange
this
)
TimeRange
place(TimeRange
this
, bool
force
)
This will place the given timerange in this timerange, for instance, day 37 in the year - Year(1934)->place(Day(1948 d37)) => Day(1934 d37).
The rules how to place things in different timeranges can be somewhat 'dwim'.
TimeRange
set_ruleset(Ruleset
r
)
TimeRange
ruleset(Ruleset
r
)
Set or get the current ruleset.
this may include timezone shanges, and change the time of day.
TimeRange
set_size(TimeRange
size
)
TimeRange
set_size(int
n
, TimeRange
size
)
Gives back a new (or the same, if the size matches) timerange with the new size. If n are given, the resulting size will be n amounts of the given size.
A negative size is not permitted; a zero one are.
TimeRange
set_timezone(Timezone
tz
)
TimeRange
set_timezone(string
tz
)
TimeZone
timezone()
Set or get the current timezone (including dst) rule.
The time-of-day may very well change when you change timezone.
To get the time of day for a specified timezone, select the timezone before getting the time of day:
Year(2003)->...->set_timezone(TimeZone.CET)->...->hour(14)->...
TimeRange
subtract(TimeRange
what
)
This subtracts a period of time from another;
>- the past the future -< |-------called-------| |-------other--------| <----> <- called->subtract(other) |-------called-------| |---third---| <----> <---> <- called->subtract(third)
This module contains all the predefined timezones. Index it with whatever timezone you want to use.
Example: Calendar.Calendar my_cal= Calendar.ISO->set_timezone(Calendar.Timezone["Europe/Stockholm"]);
A simpler way of selecting timezones might be
to just give the string to
set_timezone
;
it
indexes by itself:
Calendar.Calendar my_cal= Calendar.ISO->set_timezone("Europe/Stockholm");
Do not confuse this module with Ruleset.Timezone
,
which is the base class of a timezone object.
"CET" and some other standard abbreviations work too, but not all of them (due to more then one country using them).
Do not call set_timezone
too often, but remember the result if possible. It might take
some time to initialize a timezone object.
There are about 504 timezones with 127 different daylight saving rules. Most of them historic.
The timezone information comes from ftp://elsie.nci.nih.gov/pub/ and are not made up from scratch. Timezone bugs may be reported to the timezone mailing list, tz@elsie.nci.nih.gov, preferable with a cc to mirar+pike@mirar.org. /Mirar
TZnames
constant
Calendar.Timezone.locale
= Rule.Timezone
This contains the local timezone, found from various parts of the system, if possible.
constant
Calendar.Timezone.localtime
= Rule.Timezone
This is a special timezone, that uses localtime
()
and tzname
to find out what current offset and timezone string to use.
locale
uses this if there is no other
way of finding a better timezone to use.
This timezone is limited by localtime
and
libc to the range of time_t,
which is a MAXINT on most systems - 13 Dec 1901 20:45:52
to 19 Jan 2038 3:14:07, UTC.
base for all Roman-kind of Calendars, ie, one with years, months, weeks and days
mapping
(string
:int
) datetime(int
|void
unix_time
)
Replacement for localtime; gives back a mapping:
([ "year": int // year number (2000 AD=2000, 1 BC==0) "month": int(1..) // month of year "day": int(1..) // day of month "yearday": int(1..) // day of year "week": int(1..) // week of year "week_day": int(1..) // day of week (depending on calendar) "unix": int // unix time "julian": float // julian day "hour": int(0..) // hour of day, including dst "minute": int(0..59) // minute of hour "second": int(0..59) // second of minute "fraction": float // fraction of second "timezone": int // offset to utc, including dst ]);This is the same as calling
Second
()->datetime
().
string
datetime_name(int
|void
unix_time
)
string
datetime_short_name(int
|void
unix_time
)
Compat functions; same as format_iso
and format_iso_short
.
float
deltat(int
unadjusted_utc
)
Terrestrial Dynamical Time difference from standard time.
An approximation of the difference between TDT and UTC in fractional seconds at the specified time.
The zero point is 1901-06-25T14:23:01 UTC (unix time -2162281019), ie the accumulated number of leap seconds since then is returned.
The function is based on polynomials provided by NASA, and the result may differ from actual for dates after 2004.
Day
dwim_day(string
date
)
Day
dwim_day(string
date
, TimeRange
context
)
Tries a number of different formats on the given date (in order):
<ref>parse</ref> format as in "%y-%M-%D (%M) -W%W-%e (%e)" "2000-03-20 (Mar) -W12-1 (Mon)" "%y-%M-%D" "2000-03-20", "00-03-20" "%M%/%D/%y" "3/20/2000" "%D%*[ /]%M%*[ /-,]%y" "20/3/2000" "20 mar 2000" "20/3 -00" "%e%*[ ]%D%*[ /]%M%*[ /-,]%y" "Mon 20 Mar 2000" "Mon 20/3 2000" "-%y%*[ /]%D%*[ /]%M" "-00 20/3" "-00 20 mar" "-%y%*[ /]%M%*[ /]%D" "-00 3/20" "-00 march 20" "%y%*[ /]%D%*[ /]%M" "00 20 mar" "2000 20/3" "%y%*[ /]%M%*[ /]%D" "2000 march 20" "%D%.%M.%y" "20.3.2000" "%D%*[ -/]%M" "20/3" "20 mar" "20-03" "%M%*[ -/]%D" "3/20" "march 20" "%M-%D-%y" "03-20-2000" "%D-%M-%y" "20-03-2000" "%e%*[- /]%D%*[- /]%M" "mon 20 march" "%e%*[- /]%M%*[- /]%D" "mon/march/20" "%e%*[ -/wv]%W%*[ -/]%y" "mon w12 -00" "1 w12 2000" "%e%*[ -/wv]%W" "mon w12" "%d" "20000320", "000320" "today" "today" "last %e" "last monday" "next %e" "next monday"
Casts exception if it fails to dwim out a day. "dwim" means do-what-i-mean.
Day
dwim_time(string
date_time
)
Day
dwim_time(string
date_time
, object
TimeRangecontext
)
Tries a number of different formats on the given date_time.
Casts exception if it fails to dwim out a time. "dwim" means do-what-i-mean.
string
format_iso(void
|int
unix_time
)
string
format_iso_short(void
|int
unix_time
)
string
format_iso_tod(void
|int
unix_time
)
string
format_day_iso(void
|int
unix_time
)
string
format_day_iso_short(void
|int
unix_time
)
Format the object into nice strings;
iso "2000-06-02 (Jun) -W22-5 (Fri) 11:57:18 CEST" iso_short "2000-06-02 11:57:18" iso_tod "11:57:18"
inherit Time : Time
TimeRange
parse(string
fmt
, string
arg
)
parse a date, create relevant object fmt is in the format "abc%xdef..." where abc and def is matched, and %x is one of those time units:
%Y absolute year %y dwim year (70-99 is 1970-1999, 0-69 is 2000-2069) %M month (number, name or short name) (needs %y) %W week (needs %y) %D date (needs %y, %m) %d short date (20000304, 000304) %a day (needs %y) %e weekday (needs %y, %w) %h hour (needs %d, %D or %W) %m minute (needs %h) %s second (needs %m) %S seconds since the Epoch (only combines with %f) %f fraction of a second (needs %s or %S) %t short time (205314, 2053) %z zone %p "am" or "pm" %n empty string (to be put at the end of formats)
0 if format doesn't match data, or the appropriate time object.
The zone will be a guess if it doesn't state an exact regional timezone (like "Europe/Stockholm") - most zone abbriviations (like "CET") are used by more then one region with it's own daylight saving rules. Also beware that for instance CST can be up to four different zones, central Australia or America being the most common.
Abbreviation Interpretation AMT America/Manaus [UTC-4] AST America/Curacao [UTC-4] CDT America/Costa_Rica [UTC-6] CST America/El Salvador [UTC-6] EST America/Panama [UTC-5] GST Asia/Dubai [UTC+4] IST Asia/Jerusalem [UTC+2] WST Australia/Perth [UTC+8]
This mapping is modifiable in the ruleset, see
Ruleset.set_abbr2zone
.
Calendar.YMD.Day Calendar.YMD.Day(
"unix"
, int
unix_time
)
Calendar.YMD.Day Calendar.YMD.Day(
"julian"
, int
|float
julian_day
)
Calendar.YMD.Day Calendar.YMD.Day(
int
year
, int
month
, int
day
)
Calendar.YMD.Day Calendar.YMD.Day(
int
year
, int
year_day
)
Calendar.YMD.Day Calendar.YMD.Day(
int
julian_day
)
It's possible to create the day by using five different methods; either the normal way - from standard unix time or the julian day, and also, for more practical use, from year, month and day, from year and day of year, and from julian day without extra fuzz.
inherit YMD : YMD
inherit Time.Fraction : Fraction
inherit YMD : YMD
inherit Time.Hour : Hour
inherit YMD : YMD
inherit Time.Minute : Minute
inherit YMD : YMD
inherit YMD : YMD
inherit Time.Second : Second
inherit YMD : YMD
inherit Time.SuperTimeRange : SuperTimeRange
The Calendar week represents a standard time period of a week. In the Gregorian calendar, the standard week starts on a sunday and ends on a saturday; in the ISO calendar, it starts on a monday and ends on a sunday.
The week are might not be aligned to the year, and thus the week may cross year borders and the year of the week might not be the same as the year of all the days in the week. The basic rule is that the week year is the year that has the most days in the week, but since week number only is specified in the ISO calendar - and derivates - the week number of most calendars is the week number of most of the days in the ISO calendar, which modifies this rule for the Gregorian calendar; the week number and year is the same as for the ISO calendar, except for the sundays.
When adding, moving and subtracting months to a week, it falls back to using days.
When adding, moving or subtracting years, if tries to place the moved week in the resulting year.
Calendar.YMD.Week Calendar.YMD.Week(
"unix"
, int
unix_time
)
Calendar.YMD.Week Calendar.YMD.Week(
"julian"
, int
|float
julian_day
)
Calendar.YMD.Week Calendar.YMD.Week(
int
year
, int
week
)
It's possible to create the standard week by using three different methods; either the normal way - from standard unix time or the julian day, and also, for more practical use, from year and week number.
Can be less than 1 for the first week of the year if it begins in the previous year.
Day
day()
Day
day(int
n
)
Day
day(string
name
)
The Week type overloads the day() method, so it is possible to get a specified weekday by string:
week->day("sunday")
The integer and no argument behavior is inherited
from YMD
().
the weekday-from-string routine is language dependent.
inherit YMD : YMD
Base (virtual) time period of the Roman-kind of calendar.
mapping
datetime()
This gives back a mapping with the relevant time information (representing the start of the period);
([ "year": int // year number (2000 AD=2000, 1 BC==0) "month": int(1..) // month of year "day": int(1..) // day of month "yearday": int(0..) // day of year "week": int(1..) // week of year "week_day": int(0..) // day of week "timezone": int // offset to utc, including dst "unix": int // unix time "julian": int // julian day // for compatibility: "hour": 0 // hour of day, including dst "minute": 0 // minute of hour "second": 0 // second of minute "fraction": 0.0 // fraction of second ]);
Day of week is compatible with old versions, ie, 0 is sunday, 6 is saturday, so it shouldn't be used to calculate the day of the week with the given week number. Year day is also backwards compatible, ie, one (1) less then from the year_day() function.
If this function is called in a Week object that begins with the first week of a year, it returns the previous year if that is where the week starts. To keep the representation unambiguous, the returned week number is then one more than the number of weeks in that year.
E.g. Week(2008,1)->datetime() will return year 2007 and week 53 since the first week of 2008 starts in 2007.
Day
day()
Day
day(int
n
)
Get day number n in the current range.
If n is negative, it is counted from the end of the range.
array
(Day
) days(int
|void
from
, object
int|voidto
)
Get the days in the current range.
string
format_iso_ymd()
string
format_ymd()
string
format_ymd_short()
string
format_ymd_xshort()
string
format_mdy()
string
format_iso_week()
string
format_iso_week_short()
string
format_week()
string
format_week_short()
string
format_month()
string
format_month_short()
string
format_iso_time()
string
format_time()
string
format_time_short()
string
format_time_xshort()
string
format_mtime()
string
format_xtime()
string
format_tod()
string
format_todz()
string
format_xtod()
string
format_mod()
Format the object into nice strings;
iso_ymd "2000-06-02 (Jun) -W22-5 (Fri)" [2] ext_ymd "Friday, 2 June 2000" [2] ymd "2000-06-02" ymd_short "20000602" ymd_xshort "000602" [1] iso_week "2000-W22" iso_week_short "2000W22" week "2000-w22" [2] week_short "2000w22" [2] month "2000-06" month_short "200006" [1] iso_time "2000-06-02 (Jun) -W22-5 (Fri) 00:00:00 UTC+1" [2] ext_time "Friday, 2 June 2000, 00:00:00" [2] ctime "Fri Jun 2 00:00:00 2000\n" [2] [3] http "Fri, 02 Jun 2000 00:00:00 GMT" [4] time "2000-06-02 00:00:00" time_short "20000602 00:00:00" time_xshort "000602 00:00:00" iso_short "2000-06-02T00:00:00" mtime "2000-06-02 00:00" xtime "2000-06-02 00:00:00.000000" tod "00:00:00" tod_short "000000" todz "00:00:00 CET" todz_iso "00:00:00 UTC+1" xtod "00:00:00.000000" mod "00:00"[1] note conflict (think 1 February 2003)
The iso variants aim to be compliant with ISO-8601.
float
fraction_no()
int
hour_no()
int
julian_day()
int
leap_year()
int
minute_no()
int
month_day()
int
month_days()
int
month_no()
int
second_no()
int
utc_offset()
int
week_day()
int
week_no()
int
year_day()
int
year_no()
string
month_name()
string
month_shortname()
string
month_day_name()
string
week_day_name()
string
week_day_shortname()
string
week_name()
string
year_name()
string
tzname()
string
tzname_iso()
int
unix_time()
Returns the unix time integer corresponding to the start of the time range object. (An unix time integer is UTC.)
Second
second()
Second
second(int
n
)
Minute
minute(int
hour
, int
minute
, int
second
)
array
(Second
) seconds()
array
(Second
) seconds(int
first
, int
last
)
int
number_of_seconds()
Minute
minute()
Minute
minute(int
n
)
Minute
minute(int
hour
, int
minute
)
array
(Minute
) minutes()
array
(Minute
) minutes(int
first
, int
last
)
int
number_of_minutes()
Hour
hour()
Hour
hour(int
n
)
array
(Hour
) hours()
array
(Hour
) hours(int
first
, int
last
)
int
number_of_hours()
inherit TimeRange : TimeRange
int
number_of_days()
Get the number of days in the current range.
This is the time period of a year.
Calendar.YMD.Year Calendar.YMD.Year(
"unix"
, int
unix_time
)
Calendar.YMD.Year Calendar.YMD.Year(
"julian"
, int
|float
julian_day
)
Calendar.YMD.Year Calendar.YMD.Year(
int
year
)
Calendar.YMD.Year Calendar.YMD.Year(
string
year
)
Calendar.YMD.Year Calendar.YMD.Year(
TimeRange
range
)
It's possible to create the standard year by using three different methods; either the normal way - from standard unix time or the julian day, and also, for more practical use, from the year number.
inherit TimeRange : TimeRange
inherit YMD : YMD
Month
month()
Month
month(int
n
)
Month
month(string
name
)
The Year type overloads the month() method, so it is possible to get a specified month by string:
year->month("April")
The integer and no argument behavior is inherited
from YMD
().
Week
week()
Week
week(int
n
)
Week
week(string
name
)
The Year type overloads the week() method, so it is possible to get a specified week by name:
year->week("17") year->week("w17")
The integer and no argument behavior is inherited
from YMD
().
This is useful, since the first week of a year not always (about half the years, in the ISO calendar) is numbered '1'.
The Charset module supports a wide variety of different character sets, and
it is flexible in regard of the names of character sets it accepts. The
character case is ignored, as are the most common non-alaphanumeric
characters appearing in character set names. E.g. "iso-8859-1"
works just as well as "ISO_8859_1"
. All encodings specified in
RFC 1345 are supported.
First of all the Charset module is capable of handling the following encodings of Unicode:
UTF encodings
Most, if not all, of the relevant code pages are represented, as the following list shows. Prefix the numbers as noted in the list to get the wanted codec:
These may be prefixed with "cp"
, "ibm"
or
"ms"
.
These may be prefixed with "cp"
, "ibm"
,
"ms"
or "windows"
The default charset in MySQL, similar to cp1252
.
+359 more.
In Pike 7.8 and earlier this module was named Locale.Charset
.
void
decode_error(string
err_str
, int
err_pos
, string
charset
, void
|string
reason
, void
|mixed
... args
)
Throws a DecodeError
exception. See DecodeError.create
for
details about the arguments. If args
is given then the error
reason is formatted using sprintf(
.reason
, @args
)
Decoder
decoder(string
name
)
Returns a charset decoder object.
name
The name of the character set to decode from. Supported charsets include (not all supported charsets are enumerable): "iso_8859-1:1987", "iso_8859-1:1998", "iso-8859-1", "iso-ir-100", "latin1", "l1", "ansi_x3.4-1968", "iso_646.irv:1991", "iso646-us", "iso-ir-6", "us", "us-ascii", "ascii", "cp367", "ibm367", "cp819", "ibm819", "iso-2022" (of various kinds), "utf-7", "utf-8" and various encodings as described by RFC 1345.
If the asked-for name
was not supported, an error is thrown.
Decoder
decoder_from_mib(int
mib
)
Returns a decoder for the encoding schema denoted by MIB mib
.
void
encode_error(string
err_str
, int
err_pos
, string
charset
, void
|string
reason
, void
|mixed
... args
)
Throws an EncodeError
exception. See EncodeError.create
for
details about the arguments. If args
is given then the error
reason is formatted using sprintf(
.reason
, @args
)
Encoder
encoder(string
name
, string
|void
replacement
, function
(string
:string
)|void
repcb
)
Returns a charset encoder object.
name
The name of the character set to encode to. Supported charsets include (not all supported charsets are enumerable): "iso_8859-1:1987", "iso_8859-1:1998", "iso-8859-1", "iso-ir-100", "latin1", "l1", "ansi_x3.4-1968", "iso_646.irv:1991", "iso646-us", "iso-ir-6", "us", "us-ascii", "ascii", "cp367", "ibm367", "cp819", "ibm819", "iso-2022" (of various kinds), "utf-7", "utf-8" and various encodings as described by RFC 1345.
replacement
The string to use for characters that cannot be represented in
the charset. It's used when repcb
is not given or when it returns
zero. If no replacement string is given then an error is thrown
instead.
repcb
A function to call for every character that cannot be
represented in the charset. If specified it's called with one
argument - a string containing the character in question. If it
returns a string then that one will replace the character in the
output. If it returns something else then the replacement
argument will be used to decide what to do.
If the asked-for name
was not supported, an error is thrown.
Encoder
encoder_from_mib(int
mib
, string
|void
replacement
, function
(string
:string
)|void
repcb
)
Returns an encoder for the encoding schema denoted by MIB mib
.
string
normalize(string
in
)
All character set names are normalized through this function before compared.
void
set_decoder(string
name
, Decoder
decoder
)
Adds a custom defined character set decoder. The name is
normalized through the use of normalize
.
void
set_encoder(string
name
, Encoder
encoder
)
Adds a custom defined character set encoder. The name is
normalized through the use of normalize
.
Error thrown when decode fails (and no replacement char or replacement callback has been registered).
This error class is not actually used by this module yet - decode errors are still thrown as untyped error arrays. At this point it exists only for use by other modules.
string
Charset.DecodeError.charset
The decoding charset, typically as known to
Charset.decoder
.
Other code may produce errors of this type. In that case this
name is something that Charset.decoder
does not accept
(unless it implements exactly the same charset), and it should
be reasonably certain that Charset.decoder
never accepts that
name in the future (unless it is extended to implement exactly
the same charset).
int
Charset.DecodeError.err_pos
The failing position in err_str
.
string
Charset.DecodeError.err_str
The string that failed to be decoded.
inherit Error.Generic : Generic
Virtual base class for charset decoders.
string win1252_to_string( string data ) { return Charset.decoder("windows-1252")->feed( data )->drain(); }
string
Charset.Decoder.charset
Name of the charset - giving this name to decoder
returns an
instance of the same class as this object.
This is not necessarily the same name that was actually given to
decoder
to produce this object.
this_program
clear()
Clear buffers, and reset all state.
Returns the current object to allow for chaining of calls.
string
drain()
Get the decoded data, and reset buffers.
Returns the decoded string.
this_program
feed(string
s
)
Feeds a string to the decoder.
s
String to be decoded.
Returns the current object, to allow for chaining of calls.
Error thrown when encode fails (and no replacement char or replacement callback has been registered).
This error class is not actually used by this module yet - encode errors are still thrown as untyped error arrays. At this point it exists only for use by other modules.
string
Charset.EncodeError.charset
The encoding charset, typically as known to
Charset.encoder
.
Other code may produce errors of this type. In that case this
name is something that Charset.encoder
does not accept
(unless it implements exactly the same charset), and it should
be reasonably certain that Charset.encoder
never accepts that
name in the future (unless it is extended to implement exactly
the same charset).
int
Charset.EncodeError.err_pos
The failing position in err_str
.
string
Charset.EncodeError.err_str
The string that failed to be encoded.
inherit Error.Generic : Generic
Virtual base class for charset encoders.
string
Charset.Encoder.charset
Name of the charset - giving this name to encoder
returns
an instance of the same class as this one.
This is not necessarily the same name that was actually given to
encoder
to produce this object.
inherit Decoder : Decoder
An encoder only differs from a decoder in that it has an extra function.
this_program
set_replacement_callback(function
(string
:string
) rc
)
Change the replacement callback function.
rc
Function that is called to encode characters outside the current character encoding.
Returns the current object to allow for chaining of calls.
Codec for the ISO-8859-1 character encoding.
array
(int(8bit)
) cmyk_to_rgb(array
(int(0..100)
) cmyk
)
array
(int(8bit)
) cmyk_to_rgb(int(0..100)
c
, int(0..100)
m
, int(0..100)
y
, int(0..100)
k
)
This function return the RGB value of the color describe by the provided CMYK value. It is essentially calling Image.Color.cmyk(c,m,y,k)->rgb()
Colors.rgb_to_cmyk()
Image.Color.cmyk()
string
color_name(array
(int(8bit)
) rgb
)
Tries to find a name to color described by the provided RGB
values. Partially an inverse function to Colors.parse_color()
,
although it can not find all the names that Colors.parse_color()
can find RGB values for. Returns the colors rgb hex value prepended
with "#" upon failure.
array
(int(8bit)
) hsv_to_rgb(array
(int(8bit)
) hsv
)
array
(int(8bit)
) hsv_to_rgb(int(8bit)
h
, int(8bit)
s
, int(8bit)
v
)
This function returns the RGB value of the color described by the provided HSV value. It is essentially calling Image.Color.hsv(h,s,v)->rgb().
Colors.rgb_to_hsv()
Image.Color.hsv()
array
(int(8bit)
) parse_color(string
name
, void
|array
(int
) def
)
This function returns the RGB values that corresponds to the
color that is provided by name to the function. It is
essentially calling Image.Color.guess()
, but returns the
default value (or black if none is provided) if it failes.
array
(int(0..100)
) rgb_to_cmyk(array
(int(8bit)
) rgb
)
array
(int(0..100)
) rgb_to_cmyk(int(8bit)
r
, int(8bit)
g
, int(8bit)
b
)
This function returns the CMYK value of the color described by the provided RGB value. It is essentially calling Image.Color.rgb(r,g,b)->cmyk().
Colors.cmyk_to_rgb()
Image.Color.Color.cmyk()
array
(int(8bit)
) rgb_to_hsv(array
(int(8bit)
) rgb
)
array
(int(8bit)
) rgb_to_hsv(int(8bit)
r
, int(8bit)
g
, int(8bit)
b
)
This function returns the HSV value of the color described by the provided RGB value. It is essentially calling Image.Color.rgb(r,g,b)->hsv().
Colors.hsv_to_rgb()
Image.Color.Color.hsv()
The CommonLog module is used to parse the lines in a www server's logfile, which must be in "common log" format -- such as used by default for the access log by Roxen, Caudium, Apache et al.
int
read(function
(array
(int
|string
), int
:void
) callback
, Stdio.File
|string
logfile
, void
|int
offset
)
Reads the log file and calls the callback function for every parsed line. For lines that fails to be parsed the callback is not called not is any error thrown. The number of bytes read are returned.
callback
The callbacks first argument is an array with the different parts of the log entry.
Array | |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| One of "GET", "POST", "HEAD" etc. |
| |
| E.g. "HTTP/1.0" |
| One of 200, 404 etc. |
|
The second callback argument is the current offset to the end of the current line.
offset
The position in the file where the parser should begin.
Module for handling multiple concurrent events.
The Future
and Promise
API was inspired by
https://github.com/couchdeveloper/FutureLib.
local
variant
Future
all(array
(Future
) futures
)
local
variant
Future
all(Future
... futures
)
JavaScript Promise API equivalent of results()
.
The returned Future
does NOT have any state (eg backend)
propagated from the futures
. This must be done by hand.
results()
, Promise.depend()
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
variant
Future
first_completed(array
(Future
) futures
)
variant
local
Future
first_completed(Future
... futures
)
A Future
that represents the first
of the futures
that completes.
The returned Future
does NOT have any state (eg backend)
propagated from the futures
. This must be done by hand.
race()
, Promise.first_completed()
Future
fold(array
(Future
) futures
, mixed
initial
, function
(mixed
, mixed
, mixed
... :mixed
) fun
, mixed
... extra
)
Return a Future
that represents the accumulated results of
applying fun
to the results of the futures
in turn.
initial
Initial value of the accumulator.
fun
Function to apply. The first argument is the result of
one of the futures
, the second the current accumulated
value, and any further from extra
.
If fun
throws an error it will fail the Future
.
fun
may be called in any order, and will be called
once for every Future
in futures
, unless one of
calls fails in which case no further calls will be
performed.
The returned Future
does NOT have any state (eg backend)
propagated from the futures
. This must be done by hand.
void
on_failure(function
(mixed
:void
) f
)protected
function
(mixed
:void
) Concurrent.global_on_failure
Global failure callback, called when a promise without failure callback fails. This is useful to log exceptions, so they are not just silently caught and ignored.
variant
local
Future
race(array
(Future
) futures
)
variant
local
Future
race(Future
... futures
)
JavaScript Promise API equivalent of first_completed()
.
The returned Future
does NOT have any state (eg backend)
propagated from the futures
. This must be done by hand.
first_completed()
, Promise.first_completed()
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
Future
reject(mixed
reason
)
A new Future
that has already failed for the specified reason
.
The returned Future
does NOT have a backend set.
Future.on_failure()
, Promise.failure()
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
Future
resolve(mixed
value
)
A new Future
that has already been fulfilled with value
as result. If value
is an object which already
has on_failure
and on_success
methods, return it unchanged.
This function can be used to ensure values are futures.
The returned Future
does NOT have a backend set.
Future.on_success()
, Promise.success()
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
variant
Future
results(array
(Future
) futures
)
local
variant
Future
results(Future
... futures
)
A Future
that represents the array of all the completed futures
.
The returned Future
does NOT have any state (eg backend)
propagated from the futures
. This must be done by hand.
all()
, Promise.depend()
Future
traverse(array
(Future
) futures
, function
(mixed
, mixed
... :mixed
) fun
, mixed
... extra
)
Return a Future
that represents the array of mapping fun
over the results of the completed futures
.
The returned Future
does NOT have any state (eg backend)
propagated from the futures
. This must be done by hand.
final
void
use_backend(int
enable
)
enable
| A |
| A |
Be very careful about running in the backend disabled mode, as it may cause unlimited recursion and reentrancy issues.
As long as the backend hasn't started, it will default to false
.
Upon startup of the backend, it will change to true
unless you
explicitly called use_backend()
before that.
(Un)setting this typically alters the order in which some callbacks are called (depending on what happens in a callback).
Future()->set_backend()
, Future()->call_callback()
Promise to provide an aggregated Future
value.
Objects of this class are typically kept internal to the
code that provides the Future
value. The only thing
that is directly returned to the user is the return
value from future()
.
It is currently possible to use this class as a normal Promise
(ie without aggregation), but those functions may get removed
in a future version of Pike. Functions to avoid include
success()
and try_success()
. If you do not need aggregation
use Promise
.
Future
, future()
, Promise
, first_completed()
,
race()
, results()
, all()
, fold()
protected
void
aggregate_cb(mixed
value
, int
idx
, mapping
(int
:mixed
) results
)
Callback used to aggregate the results from dependencies.
value
Value received from the dependency.
idx
Identification number for the dependency.
results
Either of the mappings in dependency_results
depending on
whether this was a success or a failure callback.
The function may also be called with all arguments set to
UNDEFINED
in order to poll the current state. This is
typically done via a call to start()
.
start()
this_program
any_results()
Sets the number of failures to be accepted in the list of futures
this promise
depends upon to unlimited. It is equivalent to max_failures(-1)
.
The new Promise
.
depend()
, max_failures()
this_program
depend(array
(Future
) futures
)
local
variant
this_program
depend(Future
... futures
)
variant
this_program
depend()
Add futures to the list of futures which the current object depends upon.
If called without arguments it will produce a new Future
from a new Promise
which is implictly added to the dependency list.
futures
The list of futures
we want to add to the list we depend upon.
The new Promise
.
Can be called multiple times to add more.
Once the promise has been materialised (when either on_success()
,
on_failure()
or get()
has been called on this object), it is
not possible to call depend()
anymore.
fold()
, first_completed()
, max_failures()
, min_failures()
,
any_results()
, Concurrent.results()
, Concurrent.all()
protected
array
(mapping
(int
:mixed
)) Concurrent.AggregatedPromise.dependency_results
Array | |
| Successful results. |
| Failed results. |
this_program
first_completed()
It evaluates to the first future that completes of the list of futures it depends upon.
The new Promise
.
depend()
, Concurrent.first_completed()
this_program
fold(mixed
initial
, function
(mixed
, mixed
, mixed
... :mixed
) fun
, mixed
... extra
)
initial
Initial value of the accumulator.
fun
Function to apply. The first argument is the result of
one of the futures
. The second argument is the current value
of the accumulator.
extra
Any extra context needed for fun
. They will be provided
as arguments three and onwards when fun
is called.
The new Promise
.
If fun
throws an error it will fail the Future
.
fun
may be called in any order, and will be called
once for every Future
it depends upon, unless one of the
calls fails in which case no further calls will be
performed.
depend()
, Concurrent.fold()
inherit Promise : Promise
this_program
max_failures(int(-1..)
max
)
max
Specifies the maximum number of failures to be accepted in the list of futures this promise depends upon.
-1
means unlimited.
Defaults to 0
.
The new Promise
.
depend()
, min_failures()
, any_results()
this_program
min_failures(int(0..)
min
)
min
Specifies the minimum number of failures to be required in
the list of futures this promise depends upon. Defaults
to 0
.
The new Promise
.
depend()
, max_failures()
protected
void
start()
Start the aggregation of values from dependencies.
This function is called from several functions. These
include on_success()
, on_failure()
, wait()
,
get()
, fold()
and first_completed()
.
After this function has been called, several functions
may no longer be called. These include depend()
,
fold()
, first_completed()
, max_failures()
,
min_failures()
, any_results()
.
Value that will be provided asynchronously sometime in the
future. A Future object is typically produced from a Promise
object by calling its future()
method.
Promise
protected
void
apply(mixed
val
, Promise
p
, function
(mixed
, mixed
... :mixed
) fun
, array
(mixed
) ctx
)
Apply fun
with val
followed by the contents of ctx
,
and update p
with the result.
protected
void
apply_filter(mixed
val
, Promise
p
, function
(mixed
, mixed
... :bool
) fun
, array
(mixed
) ctx
)
Apply fun
with val
followed by the contents of ctx
,
and update p
with val
if fun
didn't return false.
If fun
returned false, fail p
with 0
as result.
protected
void
apply_flat(mixed
val
, Promise
p
, function
(mixed
, mixed
... :Future
) fun
, array
(mixed
) ctx
)
Apply fun
with val
followed by the contents of ctx
,
and update p
with the eventual result.
protected
void
apply_smart(mixed
val
, Promise
p
, function
(mixed
, mixed
... :mixed
|Future
) fun
, array
(mixed
) ctx
)
Apply fun
with val
followed by the contents of ctx
,
and update p
with the eventual result.
protected
void
call_callback(function
(:void
) cb
, mixed
... args
)
Call a callback function.
cb
Callback function to call.
args
Arguments to call cb
with.
The default implementation calls cb
via the
backend set via set_backend()
(if any), and
otherwise falls back the the mode set by
use_backend()
.
set_backend()
, use_backend()
this_program
delay(int
|float
seconds
)
Return a Future
that will be fulfilled with the fulfilled
result of this Future
, but not until at least seconds
have passed.
this_program
filter(function
(mixed
, mixed
... :bool
) fun
, mixed
... extra
)
This specifies a callback that is only called on success, and allows you to selectively alter the future into a failure.
fun
Function to be called. The first argument will be the
success result of this Future
.
If the return value is true
, the future succeeds with
the original success result.
If the return value is false
, the future fails with
an UNDEFINED
result.
extra
Any extra context needed for
fun
. They will be provided
as arguments two and onwards when the callback is called.
The new Future
.
transform()
local
this_program
flat_map(function
(mixed
, mixed
... :this_program
) fun
, mixed
... extra
)
This is an alias for map_with()
.
map_with()
mixed
get()
Wait for fulfillment and return the value.
Throws on rejection.
wait()
, try_get()
Pike.Backend
get_backend()
Get the backend (if any) used to call any callbacks.
This returns the value set by set_backend()
.
set_backend()
this_program
map(function
(mixed
, mixed
... :mixed
) fun
, mixed
... extra
)
This specifies a callback that is only called on success, and allows you to alter the future.
fun
Function to be called. The first argument will be the
success result of this Future
.
The return value will be the success result of the new Future
.
extra
Any extra context needed for
fun
. They will be provided
as arguments two and onwards when the callback is called.
The new Future
.
This method is used if your fun
returns a regular value (i.e.
not a Future
).
map_with()
, transform()
, recover()
this_program
map_with(function
(mixed
, mixed
... :this_program
) fun
, mixed
... extra
)
This specifies a callback that is only called on success, and allows you to alter the future.
fun
Function to be called. The first argument will be the
success result of this Future
.
The return value must be a Future
that promises
the new result.
extra
Any extra context needed for
fun
. They will be provided
as arguments two and onwards when the callback is called.
The new Future
.
This method is used if your fun
returns a Future
again.
map()
, transform_with()
, recover_with()
, flat_map
this_program
on_failure(function
(mixed
, mixed
... :void
) cb
, mixed
... extra
)
Register a callback that is to be called on failure.
cb
Function to be called. The first argument will be the
failure result of the Future
.
extra
Any extra context needed for cb
. They will be provided
as arguments two and onwards when cb
is called.
cb
will always be called from the main backend.
on_success()
, query_failure_callbacks()
this_program
on_success(function
(mixed
, mixed
... :void
) cb
, mixed
... extra
)
Register a callback that is to be called on fulfillment.
cb
Function to be called. The first argument will be the
result of the Future
.
extra
Any extra context needed for cb
. They will be provided
as arguments two and onwards when cb
is called.
cb
will always be called from the main backend.
on_failure()
, query_success_callbacks()
Promise
promise_factory()
Create a new Promise
with the same base settings
as the current object.
Overload this function if you need to propagate more state
to new Promise
objects.
The default implementation copies the backend
setting set with set_backend()
to the new Promise
.
Promise
, set_backend()
array
(function
(:void
)) query_failure_callbacks()
Query the set of active failure callbacks.
Returns an array with callback functions.
on_failure()
, query_success_callbacks()
array
(function
(:void
)) query_success_callbacks()
Query the set of active success callbacks.
Returns an array with callback functions.
on_success()
, query_failure_callbacks()
this_program
recover(function
(mixed
, mixed
... :mixed
) fun
, mixed
... extra
)
This specifies a callback that is only called on failure, and allows you to alter the future into a success.
fun
Function to be called. The first argument will be the
failure result of this Future
.
The return value will be the success result of the new Future
.
extra
Any extra context needed for
fun
. They will be provided
as arguments two and onwards when the callback is called.
The new Future
.
This method is used if your callbacks return a regular value (i.e.
not a Future
).
recover_with()
, map()
, transform()
this_program
recover_with(function
(mixed
, mixed
... :this_program
) fun
, mixed
... extra
)
This specifies a callback that is only called on failure, and allows you to alter the future into a success.
fun
Function to be called. The first argument will be the
failure result of this Future
.
The return value must be a Future
that promises
the new success result.
extra
Any extra context needed for
fun
. They will be provided
as arguments two and onwards when the callback is called.
The new Future
.
This method is used if your callbacks return a Future
again.
recover()
, map_with()
, transform_with()
void
set_backend(Pike.Backend
backend
)
Set the backend to use for calling any callbacks.
This overides the mode set by use_backend()
.
get_backend()
, use_backend()
this_program
then(void
|function
(mixed
, mixed
... :mixed
) onfulfilled
, void
|function
(mixed
, mixed
... :mixed
) onrejected
, mixed
... extra
)
JavaScript Promise API close but not identical equivalent
of a combined transform()
and transform_with()
.
onfulfilled
Function to be called on fulfillment. The first argument will be the
result of this Future
.
The return value will be the result of the new Future
.
If the return value already is a Future
, pass it as-is.
onrejected
Function to be called on failure. The first argument will be the
failure result of this Future
.
The return value will be the failure result of the new Future
.
If the return value already is a Future
, pass it as-is.
extra
Any extra context needed for onfulfilled
and
onrejected
. They will be provided
as arguments two and onwards when the callbacks are called.
The new Future
.
transform()
, transform_with()
, thencatch()
,
on_success()
, Promise.success()
,
on_failure()
, Promise.failure()
,
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
local
this_program
thencatch(function
(mixed
, mixed
... :mixed
) onrejected
, mixed
... extra
)
JavaScript Promise API equivalent of a combination of recover()
and recover_with()
.
onrejected
Function to be called. The first argument will be the
failure result of this Future
.
The return value will the failure result of the new Future
.
If the return value already is a Future
, pass it as-is.
extra
Any extra context needed for
onrejected
. They will be provided
as arguments two and onwards when the callback is called.
The new Future
.
recover()
, recover_with()
, then()
, on_failure()
,
Promise.failure()
,
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
this_program
timeout(int
|float
seconds
)
Return a Future
that will either be fulfilled with the fulfilled
result of this Future
, or be failed after seconds
have expired.
this_program
transform(function
(mixed
, mixed
... :mixed
) success
, function
(mixed
, mixed
... :mixed
)|void
failure
, mixed
... extra
)
This specifies callbacks that allow you to alter the future.
success
Function to be called. The first argument will be the
success result of this Future
.
The return value will be the success result of the new Future
.
failure
Function to be called. The first argument will be the
failure result of this Future
.
The return value will be the success result of the new Future
.
If this callback is omitted, it will default to the same callback as
success
.
extra
Any extra context needed for
success
and failure
. They will be provided
as arguments two and onwards when the callbacks are called.
The new Future
.
This method is used if your callbacks return a regular value (i.e.
not a Future
).
transform_with()
, map()
, recover()
this_program
transform_with(function
(mixed
, mixed
... :this_program
) success
, function
(mixed
, mixed
... :this_program
)|void
failure
, mixed
... extra
)
This specifies callbacks that allow you to alter the future.
success
Function to be called. The first argument will be the
success result of this Future
.
The return value must be a Future
that promises
the new result.
failure
Function to be called. The first argument will be the
failure result of this Future
.
The return value must be a Future
that promises
the new success result.
If this callback is omitted, it will default to the same callback as
success
.
extra
Any extra context needed for
success
and failure
. They will be provided
as arguments two and onwards when the callbacks are called.
The new Future
.
This method is used if your callbacks return a Future
again.
transform()
, map_with()
, recover_with
mixed
try_get()
Return the value if available.
Returns UNDEFINED
if the Future
is not yet fulfilled.
Throws on rejection.
wait()
this_program
wait()
Wait for fulfillment.
get()
, try_get()
this_program
zip(array
(this_program
) others
)
local
variant
this_program
zip(this_program
... others
)
others
The other futures (results) you want to append.
A new Future
that will be fulfilled with an
array of the fulfilled result of this object followed
by the fulfilled results of other futures.
results()
Promise to provide a Future
value.
Objects of this class are typically kept internal to the
code that provides the Future
value. The only thing
that is directly returned to the user is the return
value from future()
.
Future
, future()
Concurrent.Promise Concurrent.Promise(
void
|function
(function
(mixed
:void
), function
(mixed
:void
), mixed
... :void
) executor
, mixed
... extra
)
Creates a new promise, optionally initialised from a traditional callback
driven method via executor(success, failure, @extra)
.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
this_program
failure(mixed
value
)
Reject the Future
value.
value
Failure result of the Future
.
Throws an error if the Future
already has been fulfilled
or failed.
Mark the Future
as failed, and schedule the on_failure()
callbacks to be called as soon as possible.
try_failure()
, success()
, on_failure()
Future
future()
The future value that we promise.
inherit Future : Future
this_program
success(mixed
value
)
Fulfill the Future
.
value
Result of the Future
.
Throws an error if the Future
already has been fulfilled
or failed.
Mark the Future
as fulfilled, and schedule the on_success()
callbacks to be called as soon as possible.
try_success()
, try_failure()
, failure()
, on_success()
local
this_program
try_failure(mixed
value
)
Maybe reject the Future
value.
value
Failure result of the Future
.
Mark the Future
as failed if it hasn't already been fulfilled,
and in that case schedule the on_failure()
callbacks to be
called as soon as possible.
failure()
, success()
, on_failure()
local
this_program
try_success(mixed
value
)
Fulfill the Future
if it hasn't been fulfilled or failed already.
value
Result of the Future
.
Mark the Future
as fulfilled if it hasn't already been fulfilled
or failed, and in that case schedule the on_success()
callbacks
to be called as soon as possible.
success()
, try_failure()
, failure()
, on_success()
Implements Digital Video Broadcasting interface
Only Linux version is supported.
Object for controlling an audio subsystem on full featured cards.
DVB.Audio DVB.Audio(
int
card_number
)
DVB.Audio DVB.Audio()
Create a Audio object.
card_number
The number of card equipment.
int
mixer(int
left
, int
right
)
int
mixer(int
both
)
Sets output level on DVB audio device.
mute()
int
mute(int
mute
)
int
mute()
Mute or unmute audio device.
mixer()
mapping
status()
Returns mapping of current audio device status.
Represents an elementary data stream (PES).
int
_destruct()
Purge a stream reader.
DVB.dvb()->stream()
, read()
void
close()
Closes an open stream.
read()
string
|int
read()
Read data from a stream. It reads up to read buffer size data.
Read buffer size is 4096 by default.
DVB.dvb()->stream()
, close()
int
set_buffer(int
len
)
Sets stream's internal buffer.
The size is 4096 by default.
read()
Main class.
mapping
analyze_pat()
Return mapping of all PMT.
sid:prognum
array
(mapping
)|int
analyze_pmt(int
sid
, int
prognum
)
Parse PMT table.
analyze_pat()
DVB.dvb DVB.dvb(
int
card_number
)
Create a DVB object.
card_number
The number of card equipment.
The number specifies which device will be opened. Ie. /dev/ost/demux0, /dev/ost/demux1 ... for DVB v0.9.4 or /dev/dvb/demux0, /dev/dvb/demux1 ... for versions 2.0+
mapping
fe_info()
Return info of a frondend device.
The information heavily depends on driver. Many fields contain dumb values.
mapping
|int
fe_status()
Return status of a DVB object's frondend device.
The resulting mapping contains the following fields:
| If 1 the frontend is powered up and is ready to be used. |
| If 1 the frontend detects a signal above a normal noise level |
| If 1 the frontend successfully locked to a DVB signal |
| If 1 carrier dectected in signal |
| If 1 then lock at viterbi state |
| If 1 then TS sync byte detected |
| If 1 then tuner has a frequency lock |
mapping
|int
get_pids()
Returns mapping with info of currently tuned program's pids.
tune()
DVB.Stream
stream(int
pid
, int
|function
(:void
) rcb
, int
ptype
)
DVB.Stream
stream(int
pid
, int
|function
(:void
) rcb
)
DVB.Stream
stream(int
pid
)
Create a new stream reader object for PID.
pid
PID of stream.
rcb
Callback function called whenever there is the data to read from stream. Only for nonblocking mode.
ptype
Type of payload data to read. By default, audio data is fetched.
Setting async callback doesn't set the object to nonblocking state.
DVB.Stream()->read()
int
tune(int(2bit)
lnb
, int
freq
, bool
|string
pol
, int
sr
)
Tunes to apropriate transponder's parameters.
lnb
DiSeQc number of LNB.
freq
Frequency divided by 1000.
pol
Polarization. 0
or "v"
for vertical type,
1
or "h"
for horizontal one.
sr
The service rate parameter.
void
add_to_perf_map(program
p
)
Updates the perf map file with new program p
.
generate_perf_map()
Expects generate_perf_map()
to have been called before.
int(0..)
assembler_debug(int(0..)
level
)
Set the assembler debug level.
The old assembler debug level will be returned.
This function is only available if the Pike runtime has been compiled with RTL debug.
int(0..)
compiler_trace(int(0..)
level
)
Set the compiler trace level.
The old compiler trace level will be returned.
This function is only available if the Pike runtime has been compiled with RTL debug.
mapping
(string
:int
) count_objects()
Returns the number of objects of every kind in memory.
int(0..)
debug(int(0..)
level
)
Set the run-time debug level.
The old debug level will be returned.
This function is only available if the Pike runtime has been compiled with RTL debug.
mixed
describe(mixed
x
)
Prints out a description of the thing x
to standard error.
The description contains various internal info associated with
x
.
This function only exists if the Pike runtime has been compiled with RTL debug.
int
describe_encoded_value(string
data
)
Describe the contents of an encode_value()
string.
Returns the number of encoding errors that were detected (if any).
array
(array
(int
|string
|type
)) describe_program(program
p
)
Debug function for showing the symbol table of a program.
Returns an array of arrays with the following information
for each symbol in p
:
Array | |
| Bitfield with the modifiers for the symbol. |
| Name of the symbol. |
| Value type for the symbol. |
| Type of symbol. |
| Offset into the code or data area for the symbol. |
| Offset in the inherit table to the inherit containing the symbol. |
| Depth in the inherit tree for the inherit containing the symbol. |
The API for this function is not fixed, and has changed since Pike 7.6. In particular it would make sense to return an array of objects instead, and more information about the symbols might be added.
void
disassemble(function
(:void
) fun
)
Disassemble a Pike function to Stdio.stderr
.
This function is only available if the Pike runtime has been compiled with debug enabled.
void
dmalloc_set_name()
Only available when compiled with dmalloc.
void
dmalloc_set_name(string
filename
, int(1..)
linenumber
)
Only available when compiled with dmalloc.
void
dump_backlog()
Dumps the 1024 latest executed opcodes, along with the source
code lines, to standard error. The backlog is only collected on
debug level 1 or higher, set with _debug
or with the -d
argument on the command line.
This function only exists if the Pike runtime has been compiled with RTL debug.
void
dump_dmalloc_locations(string
|array
|mapping
|multiset
|function
(:void
)|object
|program
|type
o
)
Only available when compiled with dmalloc.
void
dump_program_tables(program
p
, int(0..)
|void
indent
)
Dumps the internal tables for the program p
on stderr.
p
Program to dump.
indent
Number of spaces to indent the output.
array
(object
) find_all_clones(program
p
, bool
|void
include_subclasses
)
Return an array with all objects that are clones of p
.
p
Program that the objects should be a clone of.
include_subclasses
If true, include also objects that are clones of programs
that have inherited p
. Note that this adds significant
overhead.
This function is only intended to be used for debug purposes.
map_all_objects()
void
gc_set_watch(array
|multiset
|mapping
|object
|function
(:void
)|program
|string
x
)
Sets a watch on the given thing, so that the gc will print a message whenever it's encountered. Intended to be used together with breakpoints to debug the garbage collector.
This function only exists if the Pike runtime has been compiled with RTL debug.
mapping
(string
:int
|float
) gc_status()
Get statistics from the garbage collector.
A mapping with the following content will be returned:
| Number of arrays, mappings, multisets, objects and programs. |
| Number of memory allocations since the last gc run. |
| Threshold for "num_allocs" when another automatic gc run is scheduled. |
| Estimation of the current amount of garbage. |
| Decaying average over the number of allocated objects between gc runs. |
| Decaying average over the number of freed objects in each gc run. |
| Garbage ratio in the last gc run. |
| Decaying average over the interval between gc runs, measured in real time nanoseconds. |
| Decaying average over the length of the gc runs, measured in real time nanoseconds. |
| The garbage accumulation goal that the gc aimed for when
setting "alloc_threshold" in the last run. The value is
either "garbage_ratio_low", "garbage_ratio_high" or
"garbage_max_interval". The first two correspond to the gc
parameters with the same names in |
| Time when the garbage-collector last ran. |
| The total amount of CPU time that has been consumed in implicit GC runs, in nanoseconds. 0 on systems where Pike lacks support for CPU time measurement. |
| The total amount of real time that has been spent in implicit GC runs, in nanoseconds. |
gc()
, Pike.gc_parameters()
, Pike.implicit_gc_real_time
void
generate_perf_map()
Generates a perf
map file of all Pike code and writes it to
/tmp/perf-<pid>.map
. This is useful only if pike has been
compiled with machine code support. It allows the linux perf tool to
determine the correct name of Pike functions that were compiled to
machine code by pike.
mapping
(string
:int
) get_program_layout(program
p
)
Returns a mapping which describes the layout of compiled machine
code in the program p
. The indices of the returned mapping
are function names, the values the starting address of the compiled
function. The total size of the program code is stored with index
0
.
mapping
Debug.globals
Can be custom filled from within your program in order to
have global references to explore live datastructures using
Inspect
; comes preinitialised with the empty mapping, ready for use.
void
hexdump(string(8bit)
raw
)
Write a hexadecimal dump of the contents of raw
to Stdio.stderr
.
inherit _Debug : _Debug
void
list_open_fds()
Only available when compiled with dmalloc.
mixed
locate_references(string
|array
|mapping
|multiset
|function
(:void
)|object
|program
|type
o
)
This function is mostly intended for debugging. It will search through
all data structures in Pike looking for o
and print the
locations on stderr. o
can be anything but int
or
float
.
This function only exists if the Pike runtime has been compiled with RTL debug.
int(0..)
map_all_objects(function
(object
:void
) cb
)
Call cb for all objects that currently exist. The callback will not be called with destructed objects as it's argument.
Objects might be missed if cb
creates new objects or destroys
old ones.
This function is only intended to be used for debug purposes.
The total number of objects
next_object()
, find_all_clones()
int(0..)
map_all_programs(function
(program
:void
) cb
)
Call cb for all programs that currently exist.
Programs might be missed if cb
creates new programs.
This function is only intended to be used for debug purposes.
The total number of programs
map_all_objects()
int(0..)
map_all_strings(function
(string
:void
) cb
)
Call cb for all strings that currently exist.
strings might be missed if cb
creates new strings or destroys
old ones.
This function is only intended to be used for debug purposes.
The total number of strings
next_object()
mapping
(string
:int
) memory_usage()
Check memory usage.
This function is mostly intended for debugging. It delivers a mapping with information about how many arrays/mappings/strings etc. there are currently allocated and how much memory they use.
The entries in the mapping are typically paired, with one
named "num_" + SYMBOL + "s"
containing a count,
and the other named SYMBOL + "_bytes"
containing
a best effort approximation of the size in bytes.
Exactly what fields this function returns is version dependant.
_verify_internals()
mixed
next(mixed
x
)
Find the next object/array/mapping/multiset/program or string.
All objects, arrays, mappings, multisets, programs and strings are stored in linked lists inside Pike. This function returns the next item on the corresponding list. It is mainly meant for debugging the Pike runtime, but can also be used to control memory usage.
next_object()
, prev()
object
next_object(object
o
)
object
next_object()
Returns the next object from the list of all objects.
All objects are stored in a linked list.
If no arguments have been given next_object()
will return the first
object from the list.
If o
has been specified the object after o
on the list will be
returned.
This function is not recomended to use.
destruct()
int(0..)
optimizer_debug(int(0..)
level
)
Set the optimizer debug level.
The old optimizer debug level will be returned.
This function is only available if the Pike runtime has been compiled with RTL debug.
string
pp_memory_usage()
Returns a pretty printed version of the
output from memory_usage
.
string
pp_object_usage()
Returns a pretty printed version of the output from
count_objects
(with added estimated RAM usage)
mixed
prev(mixed
x
)
Find the previous object/array/mapping/multiset or program.
All objects, arrays, mappings, multisets and programs are stored in linked lists inside Pike. This function returns the previous item on the corresponding list. It is mainly meant for debugging the Pike runtime, but can also be used to control memory usage.
Unlike next()
this function does not work on strings.
next_object()
, next()
int
refs(string
|array
|mapping
|multiset
|function
(:void
)|object
|program
o
)
Return the number of references o
has.
It is mainly meant for debugging the Pike runtime, but can also be used to control memory usage.
Note that the number of references will always be at least one since the value is located on the stack when this function is executed.
next()
, prev()
void
remove_from_perf_map(program
p
)
Removed p
from the perf map file.
void
reset_dmalloc()
Only available when compiled with dmalloc.
int
size_object(object
o
)
Return the aproximate size of the object, in bytes. This might not work very well for native objects
The function tries to estimate the memory usage of variables belonging to the object.
It will not, however, include the size of objects assigned to variables in the object.
If the object has a lfun::_size_object()
it will be called
without arguments, and the return value will be added to the final
size. It is primarily intended to be used by C-objects that
allocate memory that is not normally visible to pike.
lfun::_size_object()
, sizeof()
void
verify_internals()
Perform sanity checks.
This function goes through most of the internal Pike structures and generates a fatal error if one of them is found to be out of order. It is only used for debugging.
This function does a more thorough check if the Pike runtime has been compiled with RTL debug.
Debug.Decoder Debug.Decoder(
Stdio.Buffer
input
)
Stdio.Buffer
Debug.Decoder.input
Allows for interactive debugging and live data structure inspection
in both single- and multi-threaded programs.
Creates an independent background thread that every pollinterval
will show a list of running threads.
Optionally, a triggersignal
can be specified which allows the dump to
be triggered by a signal.
Example: In the program you'd like to inspect, insert the following one-liner:
Debug.Inspect("/tmp/test.pike");
Then start the program and keep it running. Next you create a /tmp/test.pike with the following content:
void create() {
werror("Only once per modification of test.pike\n");
}
int main() {
werror("This will run every iteration\n");
werror("By returning 1 here, we disable the stacktrace dumps\n");
return 0;
}
void _destruct() {
werror("_destruct() runs just as often as create()\n");
}
Whenever you edit /tmp/test.pike, it will automatically reload the file.
string
|function
(void
:void
) Debug.Inspect._callback
Either the callback function which is invoked on each iteration, or the name of a file which contains a class which is (re)compiled automatically and called on each iteration.
create
Thread.Thread
Debug.Inspect._loopthread
The inspect-thread. It will not appear in the displayed thread-list.
Debug.Inspect Debug.Inspect(
string
|function
(void
:void
)|void
cb
)
Starts up the background thread.
cb
Specifies either the callback function which is invoked on each iteration,
or the
name of a file which contains a class which is (re)compiled automatically
with an optional main()
method, which will be called on each
iteration.
If the main()
method returns 0, new stacktraces will be dumped
every iteration; if it returns 1, stacktrace dumping will be suppressed.
The compilation and the running of the callback is guarded by a catch(), so that failures (to compile) in that section will not interfere with the running program.
If the list of running threads did not change, displaying the list again will be suppressed.
triggersignal
, pollinterval
, _loopthread
, _callback
,
Debug.globals
void
inspect()
The internal function which does all the work each pollinterval. Run it directly to force a thread-dump.
int
Debug.Inspect.pollinterval
The polling interval in seconds, defaults to 4.
int
Debug.Inspect.triggersignal
If assigned to, it will allow the diagnostics inspection to be triggered by this signal.
Allows for rapid collection of logdata, which is then fed to the real werror() at idle moments. This allows for logging to occur with minimal timing interference.
void
werror(string
format
, mixed
... args
)
Overloads the predef::werror()
function
to allow floods of logentries while introducing minimal latency.
Logs are buffered, and periodically flushed from another thread.
If the arrival rate of logs is excessive, it simply skips
part of the logs to keep up.
When parts are skipped, records are skipped in whole and will never be split up.
werror_options()
void
werror_options(int
options
, void
|int
pollinterval
, void
|int
drainrate
, void
|int
maxbufentries
)
options
Defaults to 0
, reserved for future enhancements.
pollinterval
Pollinterval in seconds for the log-flush thread; defaults to 1
.
Logs will only be flushed out, if during the last pollinterval
no new logs have been added.
drainrate
Maximum number of lines per second that will be dumped to stderr.
Defaults to 10
.
maxbufentries
Maximum number of buffered logrecords which have not been flushed to stderr
yet. If this number is exceeded, the oldest maxbufentries/2
entries
will be skipped; a notice to that effect is logged to stderr.
werror()
This is a probe subject which you can send in somewhere to get probed (not to be confused with a probe object, which does some active probing). All calls to LFUNs will be printed to stderr. It is possible to name the subject by passing a string as the first and only argument when creating the subject object.
> object s = Debug.Subject(); create() > random(s); _random() (1) Result: 0 > abs(s); `<(0) _sprintf(79, ([ ])) (2) Result: Debug.Subject > abs(class { inherit Debug.Subject; int `<(mixed ... args) { return 1; } }()); create() `-() _destruct() (3) Result: 0 > pow(s,2); `[]("pow") Attempt to call the NULL-value Unknown program: 0(2)
A class that when instatiated will turn on trace, and when it's destroyed will turn it off again.
Debug.Tracer Debug.Tracer(
int
level
)
Sets the level of debug trace to level
.
This wrapper can be placed around another object to get printouts about what is happening to it. Only a few LFUNs are currently supported.
> object x=Debug.Wrapper(Crypto.MD5()); Debug.Wrapper is proxying ___Nettle.MD5_State() > x->name(); ___Nettle.MD5_State()->name (1) Result: "md5" > !x; !___Nettle.MD5_State() (2) Result: 0
array
indices( Debug.Wrapper arg )
int
sizeof( Debug.Wrapper arg )
string sprintf(string format, ... Debug.Wrapper arg ... )
array
values( Debug.Wrapper arg )
bool
res = !Debug.Wrapper()
mixed
res = Debug.Wrapper()
->X
mixed
res = Debug.Wrapper()
[ x
]
Debug.Wrapper Debug.Wrapper(
object
x
)
void
display(int
|void
num
, string
|array
(string
)|void
pattern
, string
|array
(string
)|void
exclude
)
Show profiling information in a more-or-less readable manner. This only works if pike has been compiled with profiling support.
The function will print to stderr using werror.
This is mainly here for use from the Debug.Watchdog
class, if
you want to do your own formatting or output to some other channel
use get_prof_info
instead.
array
(array
(string
|float
|int
)) get_prof_info(string
|array
(string
)|void
include
, string
|array
(string
)|void
exclude
)
Collect profiling data.
This will return the CPU usage, by function, since the last time the function was called.
The returned array contains the following entries per entry:
Array | |
| The name of the function. |
| The number of calls. |
| Total self CPU time in milliseconds. |
| Total self CPU time in milliseconds, including children. |
| Average self CPU time in microseconds. |
| Average self CPU time in microseconds, including children. |
| The self CPU time as percentage of total time. |
| The self CPU time, including children, as percentage of total time. |
| Function's definition source location. |
The CompilerEnvironment
object that is used
for loading C-modules and by predef::compile()
.
predef::compile()
is essentially an alias for the
CompilerEnvironment()->compile()
in this object.
CompilerEnvironment
, predef::compile()
inherit CompilerEnvironment : CompilerEnvironment
object
mkerror(mixed
error
)
Returns an Error object for any argument it receives. If the argument already is an Error object or is empty, it does nothing.
Class for exception objects for errors of unspecified type.
bool
res = is_type(Error.Generic()
)
Claims that the error object is an array, for compatibility with old style error handling code.
string sprintf(string format, ... Error.Generic arg ... )
array
|string
res = Error.Generic()
[ index
]
Index operator.
Simulates an array
Array | |
| Error message as returned by |
| Backtrace as returned by |
The error message is always terminated with a newline.
backtrace()
array
backtrace()
Return the backtrace where the error occurred. Normally simply
returns error_backtrace
.
predef::backtrace()
(
array
)Error.Generic()
Cast operator.
The only supported type to cast to is "array"
, which
generates an old-style error ({
.message
(),
backtrace
()})
Error.Generic Error.Generic(
string
message
, void
|array
(backtrace_frame
|array
(mixed
)) backtrace
)
string
describe()
Return a readable error report that includes the backtrace.
array
(backtrace_frame
|array
(mixed
)) Error.Generic.error_backtrace
The backtrace as returned by backtrace
where the error
occurred.
Code that catches and rethrows errors should ensure that this remains the same in the rethrown error.
string
Error.Generic.error_message
The error message. It always ends with a newline ('\n'
)
character and it might be more than one line.
Code that catches and rethrows errors may extend this with more error information.
string
message()
Return a readable message describing the error. Normally simply
returns error_message
.
If you override this function then you should ensure that
error_message
is included in the returned message, since there
might be code that catches your error objects, extends
error_message
with more info, and rethrows the error.
protected
function
(:void
) `()(void
|string
path
)
FIXME: Document this function
program
get_filesystem(string
what
)
FIXME: Document this function
int
parse_mode(int
old
, int
|string
mode
)
FIXME: Document this function
Baseclass that can be extended to create new filesystems. Is used by the Tar and System filesystem classes.
int
apply()
FIXME: Document this function
Base
cd(string
|void
directory
)
Change directory within the filesystem. Returns a new filesystem object with the given directory as cwd.
void
chmod(string
filename
, int
|string
mode
)
Change mode of a file or directory.
void
chown(string
filename
, int
|object
owner
, int
|object
group
)
Change ownership of the file or directory
Base
chroot(void
|string
directory
)
Change the root of the filesystem.
string
cwd()
Returns the current working directory within the filesystem.
array
find(void
|function
(Stat
:int
) mask
, mixed
... extra
)
FIXME: Document this function
array
(string
) get_dir(void
|string
directory
, void
|string
|array
glob
)
Returns an array of all files and directories within a given directory.
directory
Directory where the search should be made within the filesystem. CWD is assumed if none (or 0) is given.
glob
Return only files and dirs matching the glob (if given).
[get_stats]
array
(Stat
) get_stats(void
|string
directory
, void
|string
|array
glob
)
Returns stat-objects for the files and directories matching the given glob within the given directory.
[get_dir]
int
mkdir(string
directory
, void
|int
|string
mode
)
Create a new directory
Stdio.File
open(string
filename
, string
mode
)
Open a file within the filesystem
A Stdio.File object.
int
rm(string
filename
)
Remove a file from the filesystem.
Stat
stat(string
file
, int
|void
lstat
)
Return a stat-object for a file or a directory within the filesystem.
Describes the stat of a file
void
attach_statarray(array
(int
) a
)
Fills the stat-object with data from a Stdio.File.stat() call.
object
cd()
Change to the stated directory.
the directory if the stated object was a directory, 0 otherwise.
bool
Filesystem.Stat.isblk
Is the file a FIFO?
Is the file a character device?
Is the file (?) a directory?
Is the file a block device?
Is the file a regular file?
Is the file a link to some other file or directory?
Is the file a socket?
FIXME: Document this function.
1 if the file is of a specific type 0 if the file is not.
[set_type]
Read only
bool
Filesystem.Stat.ischr
Is the file a FIFO?
Is the file a character device?
Is the file (?) a directory?
Is the file a block device?
Is the file a regular file?
Is the file a link to some other file or directory?
Is the file a socket?
FIXME: Document this function.
1 if the file is of a specific type 0 if the file is not.
[set_type]
Read only
bool
Filesystem.Stat.isdir
Is the file a FIFO?
Is the file a character device?
Is the file (?) a directory?
Is the file a block device?
Is the file a regular file?
Is the file a link to some other file or directory?
Is the file a socket?
FIXME: Document this function.
1 if the file is of a specific type 0 if the file is not.
[set_type]
Read only
bool
Filesystem.Stat.isdoor
Is the file a FIFO?
Is the file a character device?
Is the file (?) a directory?
Is the file a block device?
Is the file a regular file?
Is the file a link to some other file or directory?
Is the file a socket?
FIXME: Document this function.
1 if the file is of a specific type 0 if the file is not.
[set_type]
Read only
bool
Filesystem.Stat.isfifo
Is the file a FIFO?
Is the file a character device?
Is the file (?) a directory?
Is the file a block device?
Is the file a regular file?
Is the file a link to some other file or directory?
Is the file a socket?
FIXME: Document this function.
1 if the file is of a specific type 0 if the file is not.
[set_type]
Read only
bool
Filesystem.Stat.islnk
Is the file a FIFO?
Is the file a character device?
Is the file (?) a directory?
Is the file a block device?
Is the file a regular file?
Is the file a link to some other file or directory?
Is the file a socket?
FIXME: Document this function.
1 if the file is of a specific type 0 if the file is not.
[set_type]
Read only
bool
Filesystem.Stat.isreg
Is the file a FIFO?
Is the file a character device?
Is the file (?) a directory?
Is the file a block device?
Is the file a regular file?
Is the file a link to some other file or directory?
Is the file a socket?
FIXME: Document this function.
1 if the file is of a specific type 0 if the file is not.
[set_type]
Read only
bool
Filesystem.Stat.issock
Is the file a FIFO?
Is the file a character device?
Is the file (?) a directory?
Is the file a block device?
Is the file a regular file?
Is the file a link to some other file or directory?
Is the file a socket?
FIXME: Document this function.
1 if the file is of a specific type 0 if the file is not.
[set_type]
Read only
string
nice_date()
Returns the date of the stated object as cleartext.
Stdio.File
open(string
mode
)
Open the stated file within the filesystem
a [Stdio.File] object
[Stdio.File]
void
set_type(string
x
)
Set a type for the stat-object.
This call doesnot change the filetype in the underlaying filesystem.
x
Type to set. Type is one of the following:
[isfifo], [ischr], [isdir], [isblk], [isreg], [islnk], [issock], [isdoor]
Implements an abstraction of the normal filesystem.
Filesystem.System Filesystem.System(
void
|string
directory
, void
|string
root
, void
|int
fast
, void
|Filesystem.Base
parent
)
Instanciate a new object representing the filesystem.
directory
The directory (in the real filesystem) that should become the root of the filesystemobject.
root
Internal
fast
Internal
parent
Internal
inherit Filesystem.Base : Base
Iterator object that traverses a directory tree and returns files as values and paths as indices. Example that uses the iterator to create a really simple sort of make:
object i=Filesystem.Traversion("."); foreach(i; string dir; string file) { if(!has_suffix(file, ".c")) continue; file = dir+file; string ofile = file; ofile[-1]='o'; object s=file_stat(ofile); if(s && i->stat()->mtime<s->mtime) continue; // compile file }
Filesystem.Traversion Filesystem.Traversion(
string
path
, void
|bool
symlink
, void
|bool
ignore_errors
, void
|function
(array
:array
) sort_fun
)
path
The root path from which to traverse.
symlink
Don't traverse symlink directories.
ignore_errors
Ignore directories that can not be accessed.
sort_fun
Sort function to be applied to directory entries before traversing. Can also be a filter function.
float
progress(void
|float
share
)
Returns the current progress of the traversion as a value between 0.0 and 1.0. Note that this value isn't based on the number of files, but the directory structure.
Stdio.Stat
stat()
Returns the stat for the current index-value-pair.
Basic filesystem monitor.
This module is intended to be used for incremental scanning of a filesystem.
Supports FSEvents on MacOS X and Inotify on Linux to provide low overhead monitoring; other systems use a less efficient polling approach.
Filesystem.Monitor.symlinks
, System.FSEvents
, System.Inotify
protected
void
adjust_monitor(Monitor
m
)
Update the position in the monitor_queue
for the monitor m
to account for an updated next_poll value.
void
attr_changed(string
path
, Stdio.Stat
st
)
File attribute changed callback.
path
Path of the file or directory which has changed attributes.
st
Status information for path
as obtained by file_stat(path, 1)
.
This function is called when a change has been detected for an attribute for a monitored file or directory.
Called by check()
and check_monitor()
.
If there is a data_changed()
callback, it may supersede this
callback if the file content also has changed.
Overload this to do something useful.
protected
Pike.Backend
Filesystem.Monitor.basic.backend
Backend to use.
If 0
(zero) - use the default backend.
protected
void
backend_check()
Backend check callback function.
This function is intended to be called from a backend,
and performs a check()
followed by rescheduling
itself via a call to set_nonblocking()
.
check()
, set_nonblocking()
protected
string
canonic_path(string
path
)
Canonicalize a path.
path
Path to canonicalize.
The default implementation returns combine_path(path, ".")
,
i.e. no trailing slashes.
int
check(int
|void
max_wait
, int
|void
max_cnt
, mapping
(string
:int
)|void
ret_stats
)
Check for changes.
max_wait
Maximum time in seconds to wait for changes. -1
for infinite wait.
max_cnt
Maximum number of paths to check in this call. 0
(zero) for unlimited.
ret_stats
Optional mapping that will be filled with statistics (see below).
A suitable subset of the monitored files will be checked for changes.
The function returns when either a change has been detected
or when max_wait
has expired. The returned value indicates
the number of seconds until the next call of check()
.
If ret_stats
has been provided, it will be filled with
the following entries:
| The total number of active monitors when the scan completed. |
| The number of monitors that were scanned for updates during the call. |
| The number of monitors that were updated during the call. |
| The number of seconds that the call slept. |
Any callbacks will be called from the same thread as the one
calling check()
.
check_all()
, monitor()
void
check_all(mapping
(string
:int
)|void
ret_stats
)
Check all monitors for changes.
ret_stats
Optional mapping that will be filled with statistics (see below).
All monitored paths will be checked for changes.
You typically don't want to call this function, but instead
check()
.
Any callbacks will be called from the same thread as the one
calling check()
.
check()
, monitor()
protected
bool
check_monitor(Monitor
m
, MonitorFlags
|void
flags
)
Check a single Monitor
for changes.
m
Monitor
to check.
flags
| Don't recurse. |
| Check all monitors for the entire subtree rooted in |
This function is called by check()
for the Monitor
s
it considers need checking. If it detects any changes an
appropriate callback will be called.
Returns 1
if a change was detected and 0
(zero)
otherwise.
Any callbacks will be called from the same thread as the one
calling check_monitor()
.
The return value can not be trusted to return 1
for all
detected changes in recursive mode.
check()
, data_changed()
, attr_changed()
, file_created()
,
file_deleted()
, stable_data_change()
void
clear()
Clear the set of monitored files and directories.
Due to circular datastructures, it's recomended to call this function prior to discarding the object.
protected
mixed
Filesystem.Monitor.basic.co_id
Call-out identifier for backend_check()
if in
nonblocking mode.
set_nonblocking()
, set_blocking()
Filesystem.Monitor.basic Filesystem.Monitor.basic(
int
|void
max_dir_check_interval
, int
|void
file_interval_factor
, int
|void
stable_time
)
Create a new monitor.
max_dir_check_interval
Override of default_max_dir_check_interval
.
file_interval_factor
Override of default_file_interval_factor
.
stable_time
Override of default_stable_time
.
void
data_changed(string
path
)
File content changed callback.
path
Path of the file which has had content changed.
This function is called when a change has been detected for a monitored file.
Called by check()
and check_monitor()
.
Overload this to do something useful.
protected
constantint
Filesystem.Monitor.basic.default_file_interval_factor
The default factor to multiply default_max_dir_check_interval
with to get the maximum number of seconds between checks of files.
The value can be changed by calling create()
.
The value can be overridden for individual files or directories
by calling monitor()
.
Overload this constant to change the default.
protected
constantint
Filesystem.Monitor.basic.default_max_dir_check_interval
The default maximum number of seconds between checks of directories in seconds.
This value is multiplied with default_file_interval_factor
to
get the corresponding default maximum number of seconds for files.
The value can be changed by calling create()
.
The value can be overridden for individual files or directories
by calling monitor()
.
Overload this constant to change the default.
protected
constantint
Filesystem.Monitor.basic.default_stable_time
The default minimum number of seconds without changes for a change
to be regarded as stable (see stable_data_change()
.
void
file_created(string
path
, Stdio.Stat
st
)
File creation callback.
path
Path of the new file or directory.
st
Status information for path
as obtained by file_stat(path, 1)
.
This function is called when either a monitored path has started existing, or when a new file or directory has been added to a monitored directory.
Called by check()
and check_monitor()
.
Overload this to do something useful.
This callback has similar semantics to file_exists()
, but
is called at run time.
file_exists()
, file_deleted()
, stable_data_change()
void
file_deleted(string
path
)
File deletion callback.
path
Path of the new file or directory that has been deleted.
This function is called when either a monitored path has stopped to exist, or when a file or directory has been deleted from a monitored directory.
Called by check()
and check_monitor()
.
Overload this to do something useful.
file_created()
, file_exists()
, stable_data_change()
void
file_exists(string
path
, Stdio.Stat
st
)
File existance callback.
path
Path of the file or directory.
st
Status information for path
as obtained by file_stat(path, 1)
.
This function is called during initialization for all monitored paths, and subpaths for monitored directories. It represents the initial state for the monitor.
For directories, file_exists()
will be called for the subpaths
before the call for the directory itself. This can be used to detect
when the initialization for a directory is finished.
Called by check()
and check_monitor()
the first time a monitored
path is checked (and only if it exists).
Overload this to do something useful.
This callback has similar semantics to file_created()
, but
is called at initialization time.
file_created()
, file_deleted()
, stable_data_change()
protected
void
inotify_event(int
wd
, int
event
, int
cookie
, string(8bit)
path
)
Event callback for Inotify.
bool
is_monitored(string
path
)
Check whether a path is monitored or not.
path
Path to check.
Returns 1
if there is a monitor on path
,
and 0
(zero) otherwise.
monitor()
, release()
protected
void
low_eventstream_callback(string
path
, int
flags
, int
event_id
)
This function is called when the FSEvents EventStream detects a change in one of the monitored directories.
Monitor
|void
monitor(string
path
, MonitorFlags
|void
flags
, int(0..)
|void
max_dir_check_interval
, int(0..)
|void
file_interval_factor
, int(0..)
|void
stable_time
)
Register a path
for monitoring.
path
Path to monitor.
flags
| Don't recurse. |
| Monitor the entire subtree, and any directories or files that may appear later. |
| Monitor the entire subtree, and any directories
or files that may appear later. Remove the monitor
automatically when |
max_dir_check_interval
Override of default_max_dir_check_interval
for this path
or subtree.
file_interval_factor
Override of default_file_interval_factor
for this path
or subtree.
stable_time
Override of default_stable_time
for this path
or subtree.
release()
protected
DefaultMonitor
monitor_factory(string
path
, MonitorFlags
|void
flags
, int(0..)
|void
max_dir_check_interval
, int(0..)
|void
file_interval_factor
, int(0..)
|void
stable_time
)
Create a new Monitor
for a path
.
This function is called by monitor()
to create a new Monitor
object.
The default implementation just calls DefaultMonitor
with the
same arguments.
monitor()
, DefaultMonitor
protected
Thread.Mutex
Filesystem.Monitor.basic.monitor_mutex
Mutex controlling access to monitor_queue
.
protected
ADT.Heap
Filesystem.Monitor.basic.monitor_queue
Heap containing active Monitor
s that need polling.
The heap is sorted on Monitor()->next_poll
.
protected
mapping
(string
:Monitor
) Filesystem.Monitor.basic.monitors
Mapping from monitored path to corresponding Monitor
.
The paths are normalized to canonic_path(path)
,
All filesystems are handled as if case-sensitive. This should not be a problem for case-insensitive filesystems as long as case is maintained.
void
release(string
path
, MonitorFlags
|void
flags
)
Release a path
from monitoring.
path
Path to stop monitoring.
flags
| Don't recurse. |
| Release the entire subtree. |
| Release the entire subtree, but only those paths that were added automatically by a recursive monitor. |
monitor()
protected
void
release_monitor(Monitor
m
)
Release a single Monitor
from monitoring.
release()
protected
void
report(SeverityLevel
level
, string(7bit)
fun
, sprintf_format
format
, sprintf_args
... args
)
Event tracing callback.
level
Severity level of the event.
fun
Name of the function that called report()
.
format
sprintf()
formatting string describing the event.
args
Optional extra arguments for the format
string.
This function is called in various places to provide granular tracing of the monitor state.
The default implementation calls werror()
with
format
and args
if level
is ERROR
or higher,
or if FILESYSTEM_MONITOR_DEBUG has been defined.
protected
void
reschedule_backend_check(int
|void
suggested_t
)
Reschedule beckend check.
suggested_t
Suggested time in seconds until next call of check()
.
Register suitable callbacks with the backend to automatically
call check()
.
check()
and thus all the callbacks will be called from the
backend thread.
void
set_backend(Pike.Backend
|void
backend
)
Change backend.
backend
Backend to use. 0
(zero) for the default backend.
void
set_blocking()
Turn off nonblocking mode.
set_nonblocking()
void
set_file_interval_factor(int
file_interval_factor
)
Set the file_interval_factor
.
void
set_max_dir_check_interval(int
max_dir_check_interval
)
Set the max_dir_check_interval
.
void
set_nonblocking(int
|void
suggested_t
)
Turn on nonblocking mode.
suggested_t
Suggested time in seconds until next call of check()
.
Register suitable callbacks with the backend to automatically
call check()
.
check()
and thus all the callbacks will be called from the
backend thread.
If nonblocking mode is already active, this function will be a noop.
set_blocking()
, check()
.
void
set_stable_time(int
stable_time
)
Set the stable_time
.
void
stable_data_change(string
path
, Stdio.Stat
st
)
Stable change callback.
path
Path of the file or directory that has stopped changing.
st
Status information for path
as obtained by file_stat(path, 1)
.
This function is called when previous changes to path
are
considered "stable".
"Stable" in this case means that there have been no detected
changes for at lease stable_time
seconds.
Called by check()
and check_monitor()
.
Overload this to do something useful.
This callback being called does not mean that the contents
or inode has changed, just that they don't seem to change any
more. In particular it is called for paths found during
initialization after stable_time
seconds have passed.
file_created()
, file_exists()
, file_deleted()
Flags for Monitor
s.
constant
Filesystem.Monitor.basic.MF_RECURSE
constant
Filesystem.Monitor.basic.MF_AUTO
constant
Filesystem.Monitor.basic.MF_INITED
constant
Filesystem.Monitor.basic.MF_HARD
This symbol evaluates to the Monitor
class used by
the default implementation of monitor_factory()
.
It is currently one of the values Monitor
, EventStreamMonitor
or InotifyMonitor
.
monitor_factory()
inherit Monitor : Monitor
FSEvents EventStream-accelerated Monitor
.
inherit Monitor : Monitor
Inotify-accelerated Monitor
.
inherit Monitor : Monitor
Monitoring information for a single filesystem path.
monitor()
protected
void
attr_changed(string
path
, Stdio.Stat
st
)
File attribute or content changed callback.
st
Status information for path
as obtained by
file_stat(path, 1)
.
This function is called when a change has been detected for an attribute for a monitored file or directory.
Called by check()
and check_monitor()
.
The default implementation calls global::attr_changed()
or
global::data_changed()
depending on the state.
If there is a data_changed()
callback, it may supersede this
callback if the file content also has changed.
void
bump(MonitorFlags
|void
flags
, int
|void
seconds
)
Bump the monitor to an earlier scan time.
flags
| Don't recurse. |
| Check all monitors for the entire subtree. |
seconds
Number of seconds from now to run next scan. Defaults to half of the remaining interval.
protected
void
call_callback(function
(string
, Stdio.Stat
|void
:void
) cb
, string
path
, Stdio.Stat
|void
st
)
Call a notification callback.
cb
Callback to call or UNDEFINED
for no operation.
path
Path to notify on.
st
Stat for the path
.
bool
check(MonitorFlags
|void
flags
)
Check for changes.
flags
| Don't recurse. |
| Check all monitors for the entire subtree rooted in |
This function is called by check()
for the Monitor
s
it considers need checking. If it detects any changes an
appropriate callback will be called.
Returns 1
if a change was detected and 0
(zero)
otherwise.
Any callbacks will be called from the same thread as the one
calling check_monitor()
.
The return value can not be trusted to return 1
for all
detected changes in recursive mode.
check()
, data_changed()
, attr_changed()
, file_created()
,
file_deleted()
, stable_data_change()
void
check_for_release(int
mask
, int
flags
)
Check if this monitor should be removed automatically.
Filesystem.Monitor.basic.Monitor Filesystem.Monitor.basic.Monitor(
string
path
, MonitorFlags
flags
, int
max_dir_check_interval
, int
file_interval_factor
, int
stable_time
)
protected
void
file_created(string
path
, Stdio.Stat
st
)
File creation callback.
st
Status information for path
as obtained by
file_stat(path, 1)
.
This function is called when either a monitored path has started existing, or when a new file or directory has been added to a monitored directory.
Called by check()
and check_monitor()
.
The default implementation registers the path, and
calls global::file_deleted()
.
This callback has similar semantics to file_exists()
, but
is called at run time.
file_exists()
, file_deleted()
, stable_data_change()
protected
void
file_deleted(string
path
, Stdio.Stat
|void
old_st
)
File deletion callback.
path
Path of the new file or directory that has been deleted.
old_st
Stat for the file prior to deletion (if known). Note that this argument is not passed along to top level function.
This function is called when either a monitored path has stopped to exist, or when a file or directory has been deleted from a monitored directory.
Called by check()
and check_monitor()
.
The default implementation unregisters the path, and
calls global::file_deleted()
.
file_created()
, file_exists()
, stable_data_change()
protected
void
file_exists(string
path
, Stdio.Stat
st
)
File existance callback.
st
Status information for path
as obtained by
file_stat(path, 1)
.
This function is called during initialization for all monitored paths, and subpaths for monitored directories. It represents the initial state for the monitor.
For directories, file_created()
will be called for the subpaths
before the call for the directory itself. This can be used to detect
when the initialization for a directory is finished.
Called by check()
and check_monitor()
the first time a monitored
path is checked (and only if it exists).
The default implementation registers the path, and
calls global::file_exists()
.
This callback has similar semantics to file_created()
, but
is called at initialization time.
file_created()
, file_deleted()
, stable_data_change()
string
Filesystem.Monitor.basic.Monitor.path
MonitorFlags
Filesystem.Monitor.basic.Monitor.flags
int
Filesystem.Monitor.basic.Monitor.max_dir_check_interval
int
Filesystem.Monitor.basic.Monitor.file_interval_factor
int
Filesystem.Monitor.basic.Monitor.stable_time
inherit ADT.Heap.Element : Element
protected
void
monitor(string
path
, int
flags
, int
max_dir_interval
, int
file_interval_factor
, int
stable_time
)
Called to create a sub monitor.
this_program
parent()
Returns the parent monitor, or UNDEFINED if no such monitor exists.
protected
void
register_path(int
|void
initial
)
Register the Monitor
with the monitoring system.
initial
Indicates that the Monitor
is newly created.
protected
void
report(SeverityLevel
level
, string(7bit)
fun
, sprintf_format
format
, sprintf_args
... args
)
Event tracing callback.
level
Severity level of the event.
fun
Name of the function that called report()
.
format
sprintf()
formatting string describing the event.
args
Optional extra arguments for the format
string.
This function is called in various places to provide granular tracing of the monitor state.
The default implementation just calls global::report()
with the same arguments.
protected
void
stable_data_change(string
path
, Stdio.Stat
st
)
Stable change callback.
st
Status information for path
as obtained by
file_stat(path, 1)
.
This function is called when previous changes to path
are
considered "stable".
"Stable" in this case means that there have been no detected
changes for at lease stable_time
seconds.
Called by check()
and check_monitor()
.
The default implementation calls global::stable_data_change()
.
This callback being called does not mean that the contents
or inode has changed, just that they don't seem to change any
more. In particular it is called for paths found during
initialization after stable_time
seconds have passed.
file_created()
, file_exists()
, file_deleted()
protected
bool
status_change(Stdio.Stat
old_st
, Stdio.Stat
st
, int
orig_flags
, int
flags
)
Called when the status has changed for an existing file.
void
submonitor_released(this_program
submon
)
To be called when a (direct) submonitor is released.
protected
void
unregister_path(int
|void
dying
)
Unregister the Monitor
from the monitoring system.
dying
Indicates that the Monitor
is being destructed.
It is the destruction cause value offset by one.
protected
void
update(Stdio.Stat
st
)
Calculate and set a suitable time for the next poll of this monitor.
st
New stat for the monitor.
This function is called by check()
to schedule the
next check.
Debugging filesystem monitor.
This module behaves as symlinks
, but has default implementations
of all callbacks that call report()
, as well as an implementation
of [report()] that logs everything to Stdio.stderr
.
Filesystem.Monitor.basic
, Filesystem.Monitor.symlinks
mapping
(string
:Monitor
) get_monitors()
Return the set of active monitors.
inherit "symlinks.pike" : "symlinks.pike"
Filesystem monitor with support for symbolic links.
This module extends Filesystem.Monitor.basic
with
support for symbolic links.
For operating systems where symbolic links aren't supported,
this module will behave exactly like Filesystem.Monitor.basic
.
Filesystem.Monitor.basic
protected
int
allocate_symlink(string
sym
)
Allocates a symlink id for the link sym
.
void
attr_changed(string
path
, Stdio.Stat
st
)
File attribute changed callback.
path
Path of the file or directory which has changed attributes.
st
Status information for path
as obtained by file_stat(path)
.
This function is called when a change has been detected for an attribute for a monitored file or directory.
Called by check()
and check_monitor()
.
If there is a data_changed()
callback, it may supersede this
callback if the file content also has changed.
It differs from the Filesystem.Monitor.basic
version in that
symbolic links have the st
of their targets.
Overload this to do something useful.
protected
int
Filesystem.Monitor.symlinks.available_ids
Bitmask of all unallocated symlink ids.
void
file_created(string
path
, Stdio.Stat
st
)
File creation callback.
path
Path of the new file or directory.
st
Status information for path
as obtained by file_stat(path)
.
This function is called when either a monitored path has started existing, or when a new file or directory has been added to a monitored directory.
It differs from the Filesystem.Monitor.basic
version in that
symbolic links have the st
of their targets.
Called by check()
and check_monitor()
.
Overload this to do something useful.
void
file_exists(string
path
, Stdio.Stat
st
)
File existance callback.
path
Path of the file or directory.
st
Status information for path
as obtained by file_stat(path)
.
This function is called during initialization for all monitored paths, and subpaths for monitored directories. It represents the initial state for the monitor.
For directories, file_created()
will be called for the subpaths
before the call for the directory itself. This can be used to detect
when the initialization for a directory is finished.
It differs from the Filesystem.Monitor.basic
version in that
symbolic links have the st
of their targets.
Called by check()
and check_monitor()
the first time a monitored
path is checked (and only if it exists).
Overload this to do something useful.
inherit Filesystem.Monitor.basic : basic
void
stable_data_change(string
path
, Stdio.Stat
st
)
Stable change callback.
path
Path of the file or directory that has stopped changing.
st
Status information for path
as obtained by file_stat(path)
.
This function is called when previous changes to path
are
considered "stable".
"Stable" in this case means that there have been no detected
changes for at lease stable_time
seconds.
It differs from the Filesystem.Monitor.basic
version in that
symbolic links have the st
of their targets.
Called by check()
and check_monitor()
.
Overload this to do something useful.
protected
mapping
(string
:int
) Filesystem.Monitor.symlinks.symlink_ids
Mapping from symlink name to symlink id.
protected
mapping
(string
:string
) Filesystem.Monitor.symlinks.symlink_targets
Mapping from symlink name to symlink target.
Monitoring information for a single filesystem path.
With support for expansion of symbolic links.
monitor()
protected
void
attr_changed(string
path
, Stdio.Stat
st
)
File attribute or content changed callback.
st
Status information for path
as obtained by
file_stat(path, 1)
.
This function is called when a change has been detected for an attribute for a monitored file or directory.
Called by check()
and check_monitor()
.
If there is a data_changed()
callback, it may supersede this
callback if the file content also has changed.
protected
void
call_callback(function
(string
, mixed
... :void
) cb
, string
path
, Stdio.Stat
|void
st
)
Call a notification callback and handle symlink expansion.
cb
Callback to call or UNDEFINED
for no operation.
extras
Extra arguments after the path
argument to cb
.
void
check_for_release(int
mask
, int
flags
)
Check if this monitor should be removed automatically.
protected
void
check_symlink(string
path
, Stdio.Stat
st
, int
|void
inhibit_notify
)
Check whether a symlink has changed.
protected
void
file_created(string
path
, Stdio.Stat
st
)
File creation callback.
st
Status information for path
as obtained by
file_stat(path, 1)
.
This function is called when either a monitored path has started existing, or when a new file or directory has been added to a monitored directory.
Called by check()
and check_monitor()
.
protected
void
file_deleted(string
path
, Stdio.Stat
old_st
)
File deletion callback.
path
Path of the new file or directory that has been deleted.
This function is called when either a monitored path has stopped to exist, or when a file or directory has been deleted from a monitored directory.
Called by check()
and check_monitor()
.
protected
void
file_exists(string
path
, Stdio.Stat
st
)
File existance callback.
st
Status information for path
as obtained by
file_stat(path, 1)
.
This function is called during initialization for all monitored paths, and subpaths for monitored directories. It represents the initial state for the monitor.
For directories, file_created()
will be called for the subpaths
before the call for the directory itself. This can be used to detect
when the initialization for a directory is finished.
Called by check()
and check_monitor()
the first time a monitored
path is checked (and only if it exists).
inherit basic::DefaultMonitor : DefaultMonitor
Based on Filesystem.Monitor.basic.DefaultMonitor
.
void
low_call_callback(function
(string
, mixed
... :void
) cb
, mapping
(string
:int
) state
, mapping
(string
:string
) symlink_targets
, string
path
, Stdio.Stat
|void
st
, string
|void
symlink
)
Call a notification callback and handle symlink expansion.
cb
Callback to call or UNDEFINED
for no operation.
state
State mapping to avoid multiple notification and infinite loops. Call with an empty mapping.
symlinks
Symlinks that have not been expanded yet.
path
Path to notify on.
extras
Extra arguments to cb
.
symlink
Symbolic link that must have been followed for the callback to be called.
protected
void
monitor(string
path
, int
flags
, int
max_dir_interval
, int
file_interval_factor
, int
stable_time
)
Called to create a sub monitor.
protected
void
stable_data_change(string
path
, Stdio.Stat
st
)
Stable change callback.
st
Status information for path
as obtained by
file_stat(path, 1)
.
This function is called when previous changes to path
are
considered "stable".
"Stable" in this case means that there have been no detected
changes for at lease stable_time
seconds.
Called by check()
and check_monitor()
.
protected
bool
status_change(Stdio.Stat
old_st
, Stdio.Stat
st
, int
orig_flags
, int
flags
)
Called when the status has changed for an existing file.
int
Filesystem.Monitor.symlinks.DefaultMonitor.symlinks
Mask of symlink ids that can reach this monitor.
protected
void
zap_symlink(string
path
)
Called when the symlink path
is no more.
Filesystem which can be used to mount a Tar file.
Two kinds of extended tar file records are supported:
| POSIX ustar (Version 0?). |
|