Initializing help system before first use

mmsystem

The mmsystem module provides a set of procedures and functions related to the operating system. Note that the behavior of these operators may vary between systems. To use this module, the following line must be included in the header of the Mosel model file:

 uses 'mmsystem'

New functionality for the Mosel language

The type text

This module provides the type text for text manipulation. Like the Mosel basic type string, this new type may be generated from all objects that can be converted to a text representation and supports the usual string operations (like concatenation or formatting). In addition, text objects can be generated from structured entities (like arrays or lists); altered (one can get and change a single as well as a sequence of characters in a text); offer a wider set of operations (like insertion/deletion/search of substrings) and, as all module types, are passed by reference to subroutines. Note that this type supports implicit conversion from string: a routine expecting a text as parameter may be used with a string instead (in this case the compiler creates a temporary text from the provided string). When creating a text object from a structured type it is possible to specify a limit on the size of the generated string. For instance if S is a set, text(S,128) will produce a textual representation of S of at most 128 characters.

The type date

As the name suggests, the type date is used to represent a calendar date. Internally, a date is stored as three independent integers for representing the year (-32768 to 32767), the month (-128 to 127) and the day in the month (-128 to 127). The validity of a date can be checked using the function isvalid. A date object can be initialized by a text string, a single or three numerical values. In the first case, the conversion is processed using a predefined date format (see datefmt); in the second case, the integer is interpreted as the number of days elapsed since 1/1/1970; finally, if three integers are used, they are respectively interpreted as the year, month and day for the date. The constant SYS_NOW may also be used to initialize a date: date(SYS_NOW) is the current date. This type also supports assignment, comparison as well as difference (returned in number of days) and addition/subtraction of an integer (number of days).

The type time

The type time is used to represent a time during the day. Internally, a time object is stored as an integer representing a number of milliseconds. A time object can be initialized by a text string or one to four numerical values. In the first case, the conversion is processed using a predefined time format (see timefmt); in the second case, the integer is interpreted as a number of milliseconds. When two to four integers are used, they are understood as the hours, minutes, seconds and milliseconds. The constant SYS_NOW may also be used to initialize a time: time(SYS_NOW) is the current time. This type also supports assignment, comparison as well as difference (returned in number of milliseconds) and addition/subtraction of an integer (number of milliseconds).

The type datetime

The type datetime is used to represent a timestamp by combining a date and a time. A datetime object can be initialized by a text string, a pair date and time or a numerical value. In the first case, the conversion is processed using a predefined time format (see datetimefmt); in the third case, the number is interpreted as the number of seconds elapsed since 1/1/1970 at midnight. If the provided number is a real value, the fractional part is stored as a number of milliseconds. The constant SYS_NOW may also be used to initialize a datetime: datetime(SYS_NOW) is the current date and time. This type also supports assignment, comparison as well as difference (returned in number of seconds) and addition/subtraction of a numerical value (number of seconds).

The type parsectx

This module publishes a set of routines for parsing input text strings (for instance parseint or nextfield). These routines use several module parameters for both their configuration and as a way to record their internal state: a variable of type parsectx may be used as a replacement for these module parameters in order to implement parsing procedures independent of the rest of the program. A single parsectx object integrates endparse (see sys_endparse), sepchar (see sys_sepchar), trim (see sys_trim) and qtype (see sys_qtype). The current value of each of these components can be accessed using the corresponding set and get routine (for instance getendparse).

The type textarea

The textarea type is used by the regular expression matching function regmatch to return locations in the input string. Each text area is defined by a starting position (that is an offset in the original string) and an ending position characterised by the offset of the character following the region to be considered. Functions getstart and getsucc can be used to retrieve these properties.

For instance, the following statement displays the region ta of the text txt:

writeln(copytext(txt,ta.start,ta.succ-1))

This can also be written as follows:

writeln(copytext(txt,ta))

Control parameters

Via the getparam function and the setparam procedure it is possible to access the following control parameters of module mmsystem (the reader is reminded that parameters may be spelled with lower or upper case letters or a mix of both):

datefmt
Date text format.
datetimefmt
Date and time text format.
monthnames
List of month names.
sys_endparse
End of parsing position.
sys_fillchar
Padding character for text resize.
sys_pid
Process identification.
sys_qtype
Text quoting convention.
sys_regcache
Number of regular expressions in cache.
sys_sepchar
Separator character.
sys_trim
Whether to trim spaces in text parsing.
sys_txtmem
Size of the text block.
timefmt
Time text format.

Procedures and functions

In general, the procedures and functions of mmsystem do not fail but set a status variable that can be read with getsysstat. To make sure the operation has been performed correctly, check the value of this variable after each system call.

addmonths
Add a number of months to a date or datetime.
copytext
Copy a part of a text or string.
cuttext
Cut a part of a text returning a copy of the deleted string.
deltext
Delete a part of a text.
endswith
Check whether a text or string ends with a given string.
expandpath
Expand a path or file name.
fcopy
Copy a file.
fdelete
Delete a file.
findfiles
Search for files according to file name patterns.
findtext
Search for a string in a text or string.
fmove
Rename or move a file.
formattext
Create a text from a format string and its parameters.
getasnumber
Convert a date, time or datetime into a number.
getchar
Get a character in a string or text.
getcwd
Get the current working directory.
getdate
Get the date part of a datetime.
getday
Get the day number in the month of a date or datetime.
getdaynum
Get the day number in the year of a date or datetime.
getdays
Get the number of days of a month.
getdirsep
Get the directory separator of the running operating system.
getendparse, setendparse
Get and set endparse property of a parser context.
getenv
Get the value of an environment variable.
getfsize
Get the size of a file.
getfstat
Get the status of a file or directory.
getftime
Get time information of a file.
gethour
Get the hour part of a time or datetime.
getminute
Get the minute part of a time or datetime.
getmonth
Get the month number of a date or datetime.
getmsec
Get the millisecond part of a time or datetime.
getpathsep
Get the path separator of the running operating system.
getqtype, setqtype
Get and set qtype property of a parser context.
getsecond
Get the second part of a time or datetime.
getsepchar, setsepchar
Get and set sepchar property of a parser context.
getsize
Get the size of a text.
getstart, setstart
Get and set start property of a text area.
getsucc, setsucc
Get and set succ (position of successor character) property of a text area.
getsysinfo
Get information about the running operating system.
getsysstat
Get the system status.
gettime
Get a time measure or the time part of a datetime.
gettmpdir
Get the temporary directory as a text object.
gettrim, settrim
Get and set trim property of a parser context.
getweekday
Compute the day of the week for a date or datetime.
getyear
Get the year part of a date or datetime.
inserttext
Paste a text or string into a text.
isvalid
Check whether a date, time or datetime is valid.
makedir
Create a new directory in the given file system.
makepath
Create a new directory including its parents if necessary.
newtar
Create a Unix tar archive from a list of files.
newzip
Create a Zip archive from a list of files.
nextfield
Advance to next field in a structured text string.
openpipe
Start an external process for bidirectional communication.
parseextn
Initialise an object of a module type from a text.
parseint
Convert a text into an integer.
parsereal
Convert a text into a real.
parsetext
Extract a text from a text.
pastetext
Paste a text or string into a text.
pathmatch
Check whether a file name matches a given pattern.
pathsplit
Split a path into its components.
qsort
Sort a list or an array or (a subset of) the indices of an array.
quote
Quote and encode a text string.
readtextline
Read a line of text from the current input stream.
regmatch
Compare text strings using a regular expression.
regreplace
Replace portions of a text string based on a regular expression.
removedir
Remove a directory.
removefiles
Remove files selected using file name patterns.
setchar
Set a character in a text.
setdate
Set the date part of a datetime.
setday
Set the day number of a date or datetime.
setenv
Set the value of an environment variable.
sethour
Set the hour part of a time or datetime.
setminute
Set the minute part of a time or datetime.
setmonth
Set the month number of a date or datetime.
setmsec
Set the millisecond part of a time or datetime.
setsecond
Set the second part of a time or datetime.
settime
Set the time part of a datetime.
setyear
Set the year part of a date or datetime.
sleep
Suspend execution for a fixed amount of time.
startswith
Check whether a text or string starts with a given string.
system
Execute an external program.
tarlist
Get the list of files included in a Unix tar archive.
textfmt
Create a formatted text from a string, a text or a number.
tolower
Generate the lowercase version of the provided text.
toupper
Generate the uppercase version of the provided text.
trim
Remove blank characters at the beginning and/or end of a text string.
untar
Extract files from a Unix tar archive.
unzip
Extract files from a Zip archive.
ziplist
Get the list of files included in a Zip archive.

I/O drivers

The mmsystem module provides two IO drivers: the first one allows to use a string or text object as a file and the second connects a Mosel input or output stream to a program started in a different process. Using this driver, it is possible to get the output of an external program (for instance the result of a preprocessor to feed the Mosel compiler) or implement a basic bidirectional inter process communication thanks to the openpipe procedure (which relies on this IO driver).

Driver text

text:ident

This driver uses a model variable of type string or text as its input or output media. The ident argument it requires is therefore the name of this variable that must be declared globally public to the model or have been published with publish (such that it can always be found independently of the compiler settings).String objects can only be accessed for reading while text entities can be used for both reading and writing.

In the following example the constant string "T" is used as the initialization file for variable "A":

declarations
 public T="A:123"
 A:integer
end-declarations
initializations from "text:T"
 A
end-initializations

Driver pipe

pipe:program [options...]

The file name for this driver is an external program with its options. Options are separated by spaces or tabulations and may be quoted using either single or double quotes. A quoted option may contain any kind of character except the quote used to delimit the string.

When the system opens a pipe, a new process is started for executing the given program and default input and output streams are directed to system pipes. If the file is open for reading (resp. writing), the default ouput stream (resp. input stream) of the new process becomes the current input stream (resp. output stream) of the model. To locate the program to be executed, the system relies on the PATH environment variable. Detection of error (typically the program cannot be found or is not executable) differs depending on the operating system: under Windows, the error is reported immediately and the pipe is not open. With Posix systems, no error is reported but following IO operations fail.

When the file is closed, both input and output streams of the external process are closed then the system waits for its termination: in order to avoid a lock up of the Mosel program one must make sure that the external program ends its execution when default input and output streams are closed.

Example: the following command could be used with Mosel Console for compiling the model mymod.mos after it has been processed by the C preprocessor. Note that we have to provide an output file name since the compiler cannot deduce it from the source file name.

For a Posix systems:

compile 'mmsystem.pipe:cpp mymod.mos' '' mymod.bim

For Windows (with MSVC):

compile 'mmsystem.pipe:cl /E mymod.mos' '' mymod.bim

When Mosel is running in restricted mode (see Section mosel command: restricted mode), this driver behaves like the system procedure.

Published library functions

The module mmsystem publishes its implementation of getenv, setenv and system as well as the functions gettxtsize, gettxtbuf and txtresize for text access via the service IMCI for use by other modules (see the Mosel Native Interface Reference Manual for more detail about services). The list of published functions is contained in the interface structure mmsystem_imci that is defined in the module header file mmsystem.h.

From another module, the context of mmsystem and its communication interface can be obtained using functions of the Mosel Native Interface as shown in the following example.

static XPRMnifct mm;
XPRMcontext mmctx;
XPRMdsolib dso;
mmsystem_imci mmsys;
void *sysctx;

dso=mm->finddso("mmsystem");          /* Retrieve the mmsystem module*/
sysctx=*(mm->getdsoctx(mmctx, dso, (void **)(&mmsys)));
                                      /* Get the module context and the
                                         communication interface of mmsystem */

Typically, a module calling functions that are provided by mmsystem will include this module into its list of dependencies in order to make sure that mmsystem will be loaded by Mosel at the same time as the calling module. The ``dependency'' service of the Mosel Native Interface has to be used to set the list of module dependencies:

static const char *deplist[]={"mmsystem",NULL}; /* Module dependency list */

static XPRMdsoserv tabserv[]=                   /* Table of services */
    {
     {XPRM_SRV_DEPLST, (void *)deplist}
    };

Using these functions a module may access and modify the environment of the calling model and execute an external program with automatic redirection of default streams:

mmsys->setenv(ctx,sysctx,"MYVAR","A_VALUE");
rts=mmsys->system(ctx,sysctx,"myprogram arg1 arg2");

Description of the library functions

getdate
Get the date of a date object.
getdatetime
Get the date and time of a datetime object.
gettime
Get the time of a time object.
gettxtbuf
Get a reference to the character buffer of a text object.
gettxtsize
Get the size of a text object.
setdate
Set the date of a date object.
setdatetime
Set the date and time of a datetime object.
settime
Set the time of a time object.
txtresize
Resize a text object.