Qore Programming Language Reference Manual  0.8.11.1
Qore::Program Class Reference

Program objects allow Qore programs to support subprograms with the option to restrict capabilities, for example, to support user-defined logic for application actions. More...

Public Member Functions

any callFunction (string name,...)
 Calls a function in the program object and returns the return value. More...
 
any callFunctionArgs (string name, *softlist vargs)
 Calls a function in the program object giving the arguments to the function as a list and returns the return value. More...
 
 constructor (softint po=PO_DEFAULT)
 Creates the program object and optionally sets program capabilities (parse options) More...
 
 copy ()
 Throws an exception to prevent objects of this class from being copied. More...
 
nothing define (string def, any val)
 Sets a parse define for the current Program. More...
 
 destructor ()
 Waits for all threads to finish executing, then deletes all global variables, dereferences the internal Program object and deletes the Qore object.
 
nothing disableParseOptions (softint opt)
 Removes the given parse options to the current parse option mask. More...
 
bool existsFunction (string name)
 Checks if a user function exists in the program object. More...
 
any getDefine (string def)
 Retrieves the value of the given parse define in the current Program. More...
 
any getGlobalVariable (string varname, *reference rexists)
 Returns a the value of the global variable identified by the first string argument. More...
 
int getParseOptions ()
 Returns the current binary-or'ed parse option mask for the Program object. More...
 
*string getScriptDir ()
 Returns the current script directory as a string or NOTHING if not set. More...
 
*string getScriptName ()
 Returns the current script name as a string or NOTHING if not set. More...
 
*string getScriptPath ()
 Returns the current script directory and filename if known, otherwise returns NOTHING. More...
 
TimeZone getTimeZone ()
 Returns the default local time zone for the object. More...
 
list getUserFunctionList ()
 Returns a list of strings of all user functions defined in the program object. More...
 
nothing importClass (string cls)
 Imports a class into the program object's space; any calls to the imported class's code will run with the parent Program object's permissions. More...
 
nothing importFunction (string func)
 Imports a function into the program object's space; any calls to the imported function will run with the parent Program object's permissions. More...
 
nothing importFunction (string func, string new_name)
 Imports a function into the program object's space and gives it a new name; any calls to the imported function will run with the parent Program object's permissions. More...
 
nothing importGlobalVariable (string varname, bool readonly=False)
 Imports a global variable into the program object's space. More...
 
bool isDefined (string def)
 Returns True if the given parse define is defined in the current Program (does not have to have a value defined to return True), False if not. More...
 
 loadModule (string name)
 Loads a Qore module into the Program object at run-time. More...
 
nothing lockOptions ()
 Locks parse options so that they cannot be changed. More...
 
*hash parse (string code, string label, *softint warning_mask, *string source, *softint offset, softbool format_label=True)
 Parses the string argument and adds the code to the Program object. More...
 
nothing parseCommit ()
 Commits and pending code processed with Program::parsePending() to the Program object after resolving all outstanding references in the pending code. More...
 
*hash parseCommit (int warning_mask)
 Commits and pending code processed with Program::parsePending() to the Program object after resolving all outstanding references in the pending code. More...
 
*hash parsePending (string code, string label, *softint warning_mask, *string source, *softint offset, softbool format_label=True)
 Parses the text passed to pending lists in the Program object; does not resolve all references or commit the code to the Program object. More...
 
nothing parseRollback ()
 Rolls back any pending code processed with Program::parsePending() that has not yet been committed to the Program object with Program::parseCommit() More...
 
nothing replaceParseOptions (softint opt)
 Replaces the parse options for the Program object. More...
 
any run ()
 Runs the program and optionally returns a value if the top-level code exits with a return statement. More...
 
nothing setParseOptions (softint opt=PO_DEFAULT)
 Sets parse options in the parse option mask for the Program object. More...
 
nothing setScriptPath (*string path)
 Sets (or clears) the script path (directory and filename) for the object. More...
 
nothing setTimeZone (TimeZone zone)
 Sets the default local time zone for the object. More...
 
nothing setTimeZoneRegion (string region)
 Sets the default local time zone for the object from a path to a zoneinfo time zone region file. More...
 
nothing setTimeZoneUTCOffset (softint seconds_east)
 Sets the default time zone for the Program object based on the number of seconds east of UTC; for zones west of UTC, use negative numbers. More...
 
nothing undefine (string def)
 Unsets a parse define for the current Program. More...
 

Detailed Description

Program objects allow Qore programs to support subprograms with the option to restrict capabilities, for example, to support user-defined logic for application actions.

Parsing in Qore happens in two steps; first all code is parsed to pending data structures, and then in the second stage, all references are resolved, and, if there are no errors, then all changes are committed to the Program object. Note that all parse actions (Program::parse(), Program::parsePending(), Program::parseCommit(), and Program::parseRollback()) are atomic; there is a thread lock on each Program object to ensure atomicity, and if any parse errors occur in any stage of parsing, any pending changes to the Program object are automatically rolled back. However parse actions that affect only one stage of the two stages of parsing (Program::parsePending(), Program::parseCommit() and Program::parseRollback()) are atomic within themselves, but not between calls, so one thread may inadvertently commit changes to a Program object if two or more threads are trying to perform transaction-safe two-stage parsing on a Program object without explicit user locking.

Parse option constants can be used to limit the capabilities of a Program object. These options should be binary-OR'ed together and passed to the Program object's constructor. Also see qore Executable Command-Line Processing for equivalent command-line options, and Parse Directives for equivalent parse directives.

Note that a program can provide controlled access to functionality otherwise restricted by parse options by exporting a custom API into the child program object using either the Program::importFunction() or Program::importGlobalVariable() method. This is possible because code (functions or object methods) imported into and called from a subprogram will run in the parent's space and therefore with the parent's capabilities.

Classes, constants, namespaces, functions, and global variables are only inherited into child Program objects if they are declared public and no parse options prohibit it.

Symbols can also be imported into Program objects singly using methods such as Program::importClass() and Program::importGlobalVariable(), etc.

Member Function Documentation

any Qore::Program::callFunction ( string  name,
  ... 
)

Calls a function in the program object and returns the return value.

The function runs with the permissions of the Program object containing the function.

Parameters
nameThe name of the function to call
...The remaining arguments passed to the method are passed to the function to be called
Returns
Depends on the function being called
Example:
my any $result = $pgm.callFunction("func_name", $arg1, $arg2);
Exceptions
INVALID-FUNCTION-ACCESSParse options do not allow this builtin function to be called
NO-FUNCTIONThe function does not exist
ENCODING-CONVERSION-ERRORthe function name could not be converted to the default character encoding
Note
The function called could also cause other exceptions to be thrown
any Qore::Program::callFunctionArgs ( string  name,
*softlist  vargs 
)

Calls a function in the program object giving the arguments to the function as a list and returns the return value.

The function runs with the permissions of the Program object containing the function.

Parameters
nameThe name of the function to call
vargsThe arguments to the function to be called
Returns
Depends on the function being called
Example:
my any $result = $pgm.callFunctionArgs("func_name", ($arg1, $arg2));
Exceptions
INVALID-FUNCTION-ACCESSParse options do not allow this builtin function to be called
NO-FUNCTIONThe function does not exist
ENCODING-CONVERSION-ERRORthe function name could not be converted to the default character encoding
Note
The function called could also cause other exceptions to be thrown
Qore::Program::constructor ( softint  po = PO_DEFAULT)

Creates the program object and optionally sets program capabilities (parse options)

Note that if PO_NO_CHILD_PO_RESTRICTIONS is not set in the parent Program when the new Program object is created, then the created Program object will have the parent's parse options added to its parse options as given by the argument to the constructor.

In other words, if PO_NO_CHILD_PO_RESTRICTIONS is not set, it's not possible to create a child Program object with fewer restrictions than the parent Program object (any attempt to do so will be silently ignored).

However, if PO_NO_CHILD_PO_RESTRICTIONS is set in the parent Program object, then the parse option argument to the constructor will be applied literally to the child object.

Restrictions:
Qore::PO_NO_EMBEDDED_LOGIC
Parameters
poA binary OR'ed product of parse options
Example:
my Program $pgm();
Exceptions
PROGRAM-OPTION-ERRORinvalid parse options used
Qore::Program::copy ( )

Throws an exception to prevent objects of this class from being copied.

Exceptions
PROGRAM-COPY-ERRORcopying Program objects is currently unsupported
nothing Qore::Program::define ( string  def,
any  val 
)

Sets a parse define for the current Program.

Parameters
defThe parse define to assign
valThe value to assign to the define
Example:
$pgm.define("PRODUCTION", True);
nothing Qore::Program::disableParseOptions ( softint  opt)

Removes the given parse options to the current parse option mask.

An OPTIONS-LOCKED exception is thrown if parse options have been locked (for example with Program::lockOptions())

Parameters
optA single parse option or binary-or'ed combination of parse options to unset in the parse option mask for the object; any bit set in this argument will be unset (ie zeroed out or combined with inverse binary and) in the Program's parse option mask
Example:
# allow threading and GUI operations
$pgm.disableParseOptions(PO_NO_THREADS | PO_NO_GUI);
Exceptions
OPTIONS-LOCKEDParse options have been locked and cannot be changed
PROGRAM-OPTION-ERRORinvalid parse options used
See also
Program::setParseOptions() for a reciprocal method that enables parse options; also see Program::replaceParseOptions()
bool Qore::Program::existsFunction ( string  name)

Checks if a user function exists in the program object.

Code Flags:
RET_VALUE_ONLY
Parameters
nameThe name of the function to check
Returns
True if the function exists, False if not
Example:
if ($pgm.existsFunction("my_func"))
printf("my_func() exists in the Program\n");
Exceptions
ENCODING-CONVERSION-ERRORthe function name could not be converted to the default character encoding
any Qore::Program::getDefine ( string  def)

Retrieves the value of the given parse define in the current Program.

Returns
the value of the given parse define in the current Program
Example:
my any $val = $pgm.getDefine("PRODUCTION");
Note
A parse define may be defined with no value; use Program::isDefined to check if a parse define is actually defined or not
any Qore::Program::getGlobalVariable ( string  varname,
*reference  rexists 
)

Returns a the value of the global variable identified by the first string argument.

Parameters
varnameThe string name of the global variable to find, not including the leading "$" character
rexistsAn lvalue reference to a bool to determine if the global variable exists (because this method could return NOTHING when the variable exists as well as when it does not)
Returns
the value of the global variable identified by the first string argument giving the name of the variable (without any leading "$" symbol)
Example:
my bool $exists;
my any $val = $pgm.getGlobalVariable("error_count", \$exists);
int Qore::Program::getParseOptions ( )

Returns the current binary-or'ed parse option mask for the Program object.

Returns
the current binary-or'ed parse option mask for the Program object
Example:
my int $mask = $pgm.getParseOptions();
*string Qore::Program::getScriptDir ( )

Returns the current script directory as a string or NOTHING if not set.

Gets the script directory set with Program::setScriptPath(). This is the same value that will be returned in the Qore program code with the get_script_dir() function if called from within the Program.

Returns
Returns the current script directory as a string or NOTHING if not set; if a string is returned, it should normally include the trailing directory separator character ("/" on UNIX, "\\" on Windows)
Example:
my *string $dir = $pgm.getScriptDir();
*string Qore::Program::getScriptName ( )

Returns the current script name as a string or NOTHING if not set.

Gets the script filename set with Program::setScriptPath(). This is the same value that will be returned in the Qore program code with the get_script_name() function if called from within the Program.

Returns
the current script name as a string or NOTHING if not set
Example:
my *string $name = $pgm.getScriptName();
*string Qore::Program::getScriptPath ( )

Returns the current script directory and filename if known, otherwise returns NOTHING.

Gets the script directory and filename set with Program::setScriptPath(). This is the same value that will be returned in the Qore program code with the get_script_path() function if called from within the Program.

Returns
the current script directory and filename if known, otherwise returns NOTHING
Example:
my *string $path = $pgm.getScriptPath();
TimeZone Qore::Program::getTimeZone ( )

Returns the default local time zone for the object.

Returns
the default local time zone for the object
Example:
my TimeZone $tz = $pgm.getTimeZone();
list Qore::Program::getUserFunctionList ( )

Returns a list of strings of all user functions defined in the program object.

Returns
a list of strings of all user functions defined in the program object
Example:
my list $l = $pgm.getUserFunctionList();
nothing Qore::Program::importClass ( string  cls)

Imports a class into the program object's space; any calls to the imported class's code will run with the parent Program object's permissions.

This allows a user-defined API with greater capabilities than the embedded Program object to be imported into the embedded code.

Parameters
clsthe name of the class to import into the Program object
Example:
$pgm.importClass("MyNamespace::MyClass");
Exceptions
CLASS-IMPORT-ERRORCannot import a class into the same Program object; class or namespace with this name already exists or the source class does not exist
ENCODING-CONVERSION-ERRORthe class name could not be converted to the default character encoding
Since
Qore 0.8.7
nothing Qore::Program::importFunction ( string  func)

Imports a function into the program object's space; any calls to the imported function will run with the parent Program object's permissions.

This allows a user-defined API with greater capabilities than the embedded Program object to be imported into the embedded code.

Parameters
functhe name of the function to import into the Program object
Example:
$pgm.importFunction("log");
Exceptions
FUNCTION-IMPORT-ERRORCannot import a function into the same Program object; function with this name already exists
PROGRAM-IMPORTFUNCTION-NO-FUNCTIONThe function does not exist
ENCODING-CONVERSION-ERRORthe function name could not be converted to the default character encoding
Since
Qore 0.8.4 the function name can include a namespace path (ex "Namespace::func")
nothing Qore::Program::importFunction ( string  func,
string  new_name 
)

Imports a function into the program object's space and gives it a new name; any calls to the imported function will run with the parent Program object's permissions.

This allows a user-defined API with greater capabilities than the embedded Program object to be imported into the embedded code.

Parameters
functhe name of the function to import into the Program object
new_namethe name of the function as it will be known in the Program object once imported
Example:
$pgm.importFunction("service_log", "log");
Exceptions
FUNCTION-IMPORT-ERRORCannot import a function into the same Program object; function with this name already exists; target namespace does not exist
PROGRAM-IMPORTFUNCTION-NO-FUNCTIONThe function does not exist
ENCODING-CONVERSION-ERRORthe function name could not be converted to the default character encoding
Since
Qore 0.8.4 the function name can include a namespace path (ex "Namespace::func")
nothing Qore::Program::importGlobalVariable ( string  varname,
bool  readonly = False 
)

Imports a global variable into the program object's space.

If the variable is an object, then any methods called from the subprogram will run in the parent's space

Parameters
varnameThe name of the global variable without the "$"
readonlyIf this argument is True, then the variable will be imported read-only, and cannot be changed by the subprogram (note that if the imported
Example:
$pgm.importGlobalVariable("var");
Exceptions
PROGRAM-IMPORTGLOBALVARIABLE-EXCEPTIONThe global variable does not exist in the source program, or the target variable already exists
ENCODING-CONVERSION-ERRORthe global variablt name could not be converted to the default character encoding
bool Qore::Program::isDefined ( string  def)

Returns True if the given parse define is defined in the current Program (does not have to have a value defined to return True), False if not.

Parameters
defThe name of the define to check
Returns
True if the given parse define is defined in the current Program (does not have to have a value defined to return True), False if not
Example:
my bool $b = $pgm.isDefined("PRODUCTION");
Qore::Program::loadModule ( string  name)

Loads a Qore module into the Program object at run-time.

If a feature with the same name already exists, then this feature's code is imported into the current Program object if necessary and no further action is taken.

Note that modules providing objects resolved at parse time (classes, constants, functions, etc) must be loaded prior to parsing.

Restrictions:
Qore::PO_NO_MODULES
Parameters
nameeither a feature name (a module will be searched with this feature name) or a path to a module to load
Example:
$pgm.loadModule("mysql");
Exceptions
LOAD-MODULE-ERRORmodule cannot be loaded: API incompatibility, module defines symbols already defined in the target object, etc
See also
getModuleHash(), getFeatureList()
Since
Qore 0.8.7
nothing Qore::Program::lockOptions ( )

Locks parse options so that they cannot be changed.

Example:
$pgm.lockOptions();
*hash Qore::Program::parse ( string  code,
string  label,
*softint  warning_mask,
*string  source,
*softint  offset,
softbool  format_label = True 
)

Parses the string argument and adds the code to the Program object.

This method causes both stages of parsing to be executed; if this method is successful, then the code parsed is committed to the Program object. This method is equivalent to calling Program::parsePending() and Program::parseCommit() in one atomic call.

If an exception occurs in this method, all pending code is backed out, not just code parsed by this method (for example, in case uncommitted code added by Program::parsePending() also exists in the Program object before calling this method).

Restrictions:
Qore::PO_NO_EMBEDDED_LOGIC
Parameters
codeThe code to parse into the Program object
labelThe label for the code; this label will be given if any parse or run-time errors are raised for the code given
warning_maskAn optional warning mask; see Warning Constants for values to combine by binary-or; if this argument is 0 or not given then no warnings will be checked or issued and the return value will always be NOTHING
sourceAn optional source file name for the code being parsed; this is useful if sections of a file are parsed
offsetAn optional line offset for use with the source parameter; this gives the line offset in the file to the code being parsed
format_labelIf this argument is True, then the label is formatted as "<run-time-loaded: label>"; if False, then it is passed as-is
Returns
If warning included in the warning mask are raised during parsing, this method will return an exception hash with warning information, otherwise NOTHING is returned
Example:
my *hash $wh = $pgm.parse($code, "label", WARN_DEFAULT);
while ($wh) {
printf("warning: %s:%d: %s: %s\n", $wh.file, $wh.line, $wh.err, $wh.desc);
$wh = $wh.next;
}
Note
This method could throw many parse exceptions which are not enumerated here; any parse errors will result in an appropriate exception.
See also
Since
Qore 0.8.7 the source, offset, and format_label arguments were added
nothing Qore::Program::parseCommit ( )

Commits and pending code processed with Program::parsePending() to the Program object after resolving all outstanding references in the pending code.

An exception in this method causes all pending code to be rolled back immediately.

Example:
$pgm.parseCommit();
Note
This method could throw many parse exceptions related to resolving references which are not enumerated here; any parse errors will result in an appropriate exception.
See also
*hash Qore::Program::parseCommit ( int  warning_mask)

Commits and pending code processed with Program::parsePending() to the Program object after resolving all outstanding references in the pending code.

An exception in this method causes all pending code to be rolled back immediately.

Example:
my *hash $wh = $pgm.parseCommit(WARN_DEFAULT);
while (exists $wh) {
printf("warning: %s:%d: %s: %s\n", $wh.file, $wh.line, $wh.err, $wh.desc);
$wh = $wh.next;
}
Note
This method could throw many parse exceptions related to resolving references which are not enumerated here; any parse errors will result in an appropriate exception.
See also
*hash Qore::Program::parsePending ( string  code,
string  label,
*softint  warning_mask,
*string  source,
*softint  offset,
softbool  format_label = True 
)

Parses the text passed to pending lists in the Program object; does not resolve all references or commit the code to the Program object.

References are resolved in the Program::parseCommit() method.

Program::parseCommit() must be called to resolve all references and commit the code to the Program object; until Program::parseCommit() is called, none of the code parsed by this method will be available for execution in the Program object.

If an exception occurs in this method, all pending code is backed out, not just code parsed by this method.

Restrictions:
Qore::PO_NO_EMBEDDED_LOGIC
Parameters
codeThe code to parse into the Program object
labelThe label for the code; this label will be given if any parse or run-time errors are raised for the code given
warning_maskAn optional warning mask; see Warning Constants for values to combine by binary-or; if this argument is 0 or not given then no warnings will be checked or issued and the return value will always be NOTHING
sourceAn optional source file name for the code being parsed; this is useful if sections of a file are parsed
offsetAn optional line offset for use with the source parameter; this gives the line offset in the file to the code being parsed
format_labelIf this argument is True, then the label is formatted as "<run-time-loaded: label>"; if False, then it is passed as-is
Returns
If warning included in the warning mask are raised during parsing, this method will return an exception hash with warning information, otherwise NOTHING is returned
Example:
my *hash $wh = $pgm.parsePending($code, "label", WARN_DEFAULT);
while ($wh) {
printf("warning: %s:%d: %s: %s\n", $wh.file, $wh.line, $wh.err, $wh.desc);
$wh = $wh.next;
}
$pgm.parseCommit();
Note
This method could throw many parse exceptions which are not enumerated here; any parse errors will result in an appropriate exception.
See also
Since
Qore 0.8.7 the source, offset, and format_label arguments were added
nothing Qore::Program::parseRollback ( )

Rolls back any pending code processed with Program::parsePending() that has not yet been committed to the Program object with Program::parseCommit()

Example:
$pgm.parseRollback();
See also
nothing Qore::Program::replaceParseOptions ( softint  opt)

Replaces the parse options for the Program object.

An OPTION-ERROR exception is thrown if the calling Program object does not have PO_NO_CHILD_PO_RESTRICTIONS set.

Parameters
optA single parse option or binary-or'ed combination of parse options to unset in the parse option mask for the object
Example:
# disallow threading and GUI operations
$pgm.replaceParseOptions(PO_NO_THREADS | PO_NO_GUI);
Exceptions
OPTION-ERRORThe calling Program does not have the PO_NO_CHILD_PO_RESTRICTIONS option set, and therefore cannot call Program::replaceParseOptions()
See also
Program::setParseOptions() and Program::disableParseOptions().
any Qore::Program::run ( )

Runs the program and optionally returns a value if the top-level code exits with a return statement.

Returns
the value given to the return statement at the top-level, if any, otherwise NOTHING
Example:
$pgm.run();
nothing Qore::Program::setParseOptions ( softint  opt = PO_DEFAULT)

Sets parse options in the parse option mask for the Program object.

An OPTIONS-LOCKED exception is thrown if parse options have been locked (for example with Program::lockOptions())

Parameters
optA single parse option or binary-or'ed combination of parse options to set in the parse option mask for the object; the given argument will be combined with binary or with the existing parse option mask
Example:
# disable threading and GUI operations
$pgm.setParseOptions(PO_NO_THREADS | PO_NO_GUI);
Exceptions
OPTIONS-LOCKEDParse options have been locked and cannot be changed
PROGRAM-OPTION-ERRORinvalid parse options used
See also
Program::disableParseOptions() for a reciprocal method that disables parse options; also see Program::replaceParseOptions()
nothing Qore::Program::setScriptPath ( *string  path)

Sets (or clears) the script path (directory and filename) for the object.

Parameters
pathThe path (directory and filename) for the current script; if the directory component is missing, then the current directory is assumed
Example:
$pgm.setScriptPath("/users/test/test.q");
nothing Qore::Program::setTimeZone ( TimeZone  zone)

Sets the default local time zone for the object.

Example:
my TimeZone $tz("Europe/Prague");
$pgm.setTimeZone($tz);
See also
TimeZone::set()
nothing Qore::Program::setTimeZoneRegion ( string  region)

Sets the default local time zone for the object from a path to a zoneinfo time zone region file.

If there are errors opening, reading, or parsing the file (or the Windows registry entry, depending on the platform), an exception is thrown

Parameters
regionThe path to the zoneinfo file for the time zone region to set as the local time zone for the Program object
Example:
$pgm.setTimeZoneRegion("Europe/Prague");
Exceptions
TZINFO-ERRORUnable to read zoneinfo file; invalid file magic; error parsing zoneinfo file, etc
nothing Qore::Program::setTimeZoneUTCOffset ( softint  seconds_east)

Sets the default time zone for the Program object based on the number of seconds east of UTC; for zones west of UTC, use negative numbers.

Time zones set with this method cannot have any daylight savings time information; to set a zone with daylight savings time information, use Program::setTimeZoneRegion() instead

Parameters
seconds_eastThe number of seconds east of UTC; for zones west of UTC, use negative numbers
Example:
The following examples are all equivalent, setting the time zone to +02 UTC:
$pgm.setTimeZoneUTCOffset(7200);
$pgm.setTimeZoneUTCOffset(2h);
$pgm.setTimeZoneUTCOffset(PT2H);
See also
TimeZone::setUTCOffset()
nothing Qore::Program::undefine ( string  def)

Unsets a parse define for the current Program.

Parameters
defThe name of the define to undefine; if the given define is not defined anyway, the operation is ignored
Example:
$pgm.undefine("PRODUCTION");