Home
kScript 2.5 User Manual PhilipT. Keenan
Contents
1. This x appears on the screen The output is kS 0 set int O traceLevel 1 kS 0 End set kS 0 Begin define xS 0 defining double 0 x kS 0 set double 0 x 3 14 kS 0 End define kS 0 Begin echo This 3 14 appears on the screen kS 0 End echo kS 0 Begin set kS 0 set double 0 x 2 14 kS 0 End set kS 0 Begin echo This 2 14 appears on the screen kS 0 End echo It is also possible to redirect output and input using stream objects This can be used for example to write different kinds of information to different files or to control a multi run simulation in which each run s output is sent to a numbered file Moreover using the transcript command line option one can get a complete transcript of the input commands and their output in one file this is useful for debugging and for preserving the content of interactive sessions The following script demonstrates output redirection stream stdout outStream stream myfile open file my out for writing echo This appears on the screen outStream myfile echo This is written to the file my out outStream stdout echo This once again appears on the screen 10 The output is This appears on the screen This once again appears on the screen In addition a file called my out was also created and it contains the following line This is
2. lt stream f gt lt mathExpr width gt Function This sets a new width and returns the old one It can only be used with application defined output streams 3 5 4 Arrays dimensions lt nameExpr arrayName gt Function This returns the number of dimensions in the array firstIndex lt nameExpr arrayName gt lt mathExpr d gt Function This returns the first valid index in dimension d of the array lastIndex lt nameExpr arrayName gt lt mathExpr d gt Function This returns the last valid index in dimension d of the array resize lt nameExpr arrayName gt lt stringExpr dimList gt optional base lt stringExpr baseList gt required row col Command This allows an array to be resized using the same syntax as an array definition inputArray lt nameExpr arrayName gt Command Input literal values no math expressions into a one dimensional int or double array using any of 6 syntax options including 22 N 3 di se dN N di dN di dN end di AN N from filename from filename where filename is expected to hold N double precision numbers only one array per file When N is not known this reads to the end of the file This routine resizes the array but preserves it s base index sort lt nameExpr inputArray gt lt nameExpr outputArray gt optional perm lt nameExpr outputPermutation gt Command Sort a one dimensional array The outputPermutation is stored in an intAr ray such that
3. an cmdInterpreter amp operator gt gt cmdInterpreter amp lt type gt amp function The cmdGen kScript user interface generator assumes such an operator is defined for all argument types it encounters The define and set commands can be used to create and modify variables of any AScript type The core kScript built in type names are listed below The command describe types produces this same list on line Types are arranged in a hierarchy Some entries in this list like keywordType represent col lections of types rather than individual types The list command will list all objects matching a given type or descended from it in the type hierarchy For instance the command list category will list all objects variables of type category while the command list keywordType will list all objects of any keyword type including the category type and the command list all will list all symbol names in kScript whether defining objects commands or functions all This keyword is the root of the type hierarchy The command list all lists all global symbols regardless of type command Commands are defined using the following pattern define command Name Description for Online Help Typei FormalArgiName Type2 FormalArg2Name Script to Execute The task description string must use the curly brace syntax for string expressions Square brackets in the list of formal arguments can enclose a single optional preposition which is ignor
4. inputArray output Permutation i outputArrayli arithMean lt nameExpr inputArray gt Function Returns the arithmetic mean of a one dimensional array of numbers variance lt nameExpr inputArray gt Function Returns the variance of a one dimensional array of numbers 3 5 5 Bit bitShift lt intMathExpr i gt by lt intMathExpr n gt Function Shift bits of an integer left for n gt 0 right for n lt 0 bitAnd lt intMathExpr i1 gt lt intMathExpr i2 gt Function Bitwise AND of two integers bitOr lt intMathExpr il gt lt intMathExpr i2 gt Function Bitwise OR of two integers bitNot lt intMathExpr i gt Function Bitwise NOT of an integer bitXor lt intMathExpr i1 gt lt intMathExpr i2 gt Function Bitwise XOR of two integers 3 5 6 Utility type lt nameExpr n gt Function This function returns the type of the given symbol as a literal value from the keyword collection kType as listed by the command describe types If n has type name it s value is examined and if it is a symbol name that symbol s type is returned instead new lt keyword typeName kType gt lt nameExpr name gt lt nameExpr parent gt lt stringExpr documentation gt Command This defines a new literal value in the specified keyword collection type The parent literal from the same collection is optional Use keywordType as the type name to create a new keyword collection type 23 isDef lt nam
5. is a double nd command show_string string ns 1 echo this is a string ns command show a demo OOP command name n string t lt typen eval show_ t n show s show d This script prints the following this is a string hi there this is a double 3 14 4 1 2 Defining new types using string lists kScript allows advanced users to define new data types at the scripting level The following simple example illustrates a point type consisting of two numeric fields x and y coordinates 25 5 o double px double py ul o command getPoint Put coords into px py string p stream f open string p for reading name k int state lt read f k px py if lt strCmp k point echo not a point k command printPoint Print a point name n getPoint n echo Point n x px y py string pi point 0 5 0 7 string p2 point 0 66 0 9 printPoint pi printPoint p2 The output is Point pi x 0 5 y 0 7 Point p2 x 0 66 y 0 9 4 1 3 Defining new types using associative arrays llere is another way to define a new type this time using associative arrays rather than string lists The following input script again defines a point class and produces the same output as in the previous example new keywordType pointField A point class stores 2 doubles x and y new pointField x The x coordinate new pointField y The y coordinate fu
6. it is not found The character can be surrounded by curly braces to represent special characters like spaces and braces 21 strRevPosn lt stringExpr sourceString gt lt char marker gt Function This function returns the position of the marker character in the string starting from the end or 0 if it is not found strLeft lt mathExpr n gt lt stringExpr sourceString gt Function This function returns the leftmost n characters of a string strRight lt mathExpr n gt lt stringExpr sourceString gt Function This function returns the rightmost n characters of a string strMid lt mathExpr first gt lt mathExpr last gt from lt stringExpr sourceString gt Function This function returns the indicated substring an inclusive range of characters counted from 1 today Function This function returns the current date as a string 3 5 3 Streams read lt stream s gt sequence lt nameExpr symbolName gt Function This reads one or more values from the stream into the indicated variables For each symbol name the command determines the type of the variable and reads a literal or expression of that type If the end of the file is encountered unexpectedly the function prints an error message and returns 1 Otherwise it returns 0 Note one can only read into plain variable names not into math expressions string expressions or array expressions close lt stream f gt Command This closes the indicated file streamWidth
7. or function it creates a local variable whose scope is the remainder of that command or function If there is a global variable of the same name the local variable hides the global one and can have a different type The left arrow syntax can be used to store the return value of a kScript function in the newly defined variable set lt lvalue name gt required lt typedExpression expr gt lt lt typedFunctionExpr fexpr gt Command This changes the value of a variable of type T The word set is optional An lvalue is usually an object name but with arrays for instance it can be an item within the array The expression syntax must be appropriate for an object of type T The left arrow syntax can be used to store the value returned by a kScript function beginComment Command Begin an extended comment which lasts until a matching endComment 19 Extended comments may be nested echo lt stringExpr expr gt Command Print the value of an object or string expression on the standard output stream followed by a newline echo lt stringExpr expr gt Command Print the value of an object or string expression on the standard output stream error lt stringExpr expr gt Command Print the value of an object or string expression on the standard error stream shell lt stringExpr expr gt Function Have the UNIX shell evaluate the expanded string This function returns the shell s result code The shell s sta
8. the public domain and its use is subject to the terms of the kScript copy right notice provided with the distribution and reprinted below in this manual However for non commercial users the terms are not restrictive Documentation and promotional materials for applications built with Script must cite this User Manual and developers must notify Dr Keenan e mail to keenan ticam utexas edu that they have adopted kSeript in an application In par ticular the more people let us know they are using kScript the more we will be able to justify allocating resources to supporting maintaining and improving kScript in the future kScript is superficially similar to TCL because both languages evolved over a period of many years from experiments with C interpreters However Script was developed independently of TCL and has certain advantages over TCL as a programming language Script was designed with scientific applications in mind rather than system level programming In particular e kScriptis strongly typed In TCL everything is a string and numerical computation is slow and can give incorrect answers for instance multiply two large integers In kScr pt numbers are numbers and are stored internally in double precision Moreover kScript supports a wide and extendible variety of other types of objects including strings arrays and files streams e In kScript variables are either global in scope or local to a user defined procedure In TCL t
9. written to the file my out If the above script is saved in a file script k and is run using the transcript option as with the command kScript transcript t script k then a transcript file named t is also created which contains the following summary of the run The kScript version 2 Interpreter by Philip T Keenan stream k example stream stdout outStream stream myfile open file my out for writing echo This appears on the screen This appears on the screen outStream myfile echo This is written to the file my out outStream stdout echo This once again appears on the screen This once again appears on the screen 2 8 Using Keyword Collections Frequently a scientific application will require the user to select a feature from a finite list of alternatives lor example a differential equation solver might support several numerical methods such as Euler and Runge Kutta Rather than use an integer variable and assign meaningless integer code values to the list of alternatives one can define a keyword collection and refer to the alternatives with symbolic names One could do the same thing by defining integer constants but in kScript collections represent new types so that the user interface can warn you if you supply an invalid option The category collection is a built in keyword collection with literal values such as Core Stream String and Array Each Script command function or object belongs to a
10. Logical operators return for true and 0 for false The if command treats 0 as false and non zero as true Parentheses override the standard operator precedences In addition many standard mathematical functions can be called as listed in Table 3 2 Four of these take two arguments 2 y instead of one The expression pow x y returns t random x y returns a uniformly distributed random number in the range x y normal x y returns a normal variate with mean x and variance y and mod x y returns 2 mod y defined to 16 Operator Interpretation addition subtraction multiplication division exponentiation is less than E is less than or equal to is greater than VVAA Il is greater than or equal to is equal to is not and pa or Table 3 1 Math Expression Operators abs round sqrt exp log sin cos tan atan msec pow random normal floor ceiling mod Table 3 2 Mathematical Functions Construction Expansion hh Y without counting toward nesting 4 without counting toward nesting YnX n repetitions of character X ZAn newline YNt tab Ut generates no text this acts as a concatenation operator Y followed by newline the newline is suppressed 7 pI Table 3 3 String Expression Expansions 17 be non negative as long as y is The underlying random number generator can be re seeded with the seed command The msec function takes no arguments and returns the value of an int
11. RMR SS SOE a Soe SER 18 A AE A RN ere ED 18 A AA TN 21 O OM A ARA ad Baw S oe 22 E ATLAS Aa a A Shao 22 OO DA RA A as EP ta ia 23 O DU AAA RE Rew ee AR A AA Olea Med wee 23 A MN A EIA EA A A e S a A 24 4 Extending the Script Programming Language 25 4 1 Extensions at the stripting levels w sice y dacii m a ee eo eS Oe eS 25 4 1 1 Overloading command names by type 0 0200008 25 4 1 2 Defining new types using string lists 0 o 25 4 1 3 Defining new types using associative arrays o oo 4 26 4 2 Extensions at the C source code level o ee ees 27 Chapter 1 Introduction This is the user manual for version 2 5 of Script a powerful and flexible application scripting language 1 1 What is Script Application scripting languages like Microsoft s Visual Basic Apple Computer s AppleScript and the UNIX freeware package TCL are interpreted programming languages which can be embedded inside other applications providing users with a high level way to control or seript the behavior of the application Like these other languages AScript can be used as a stand alone interpreted programming language or embedded inside a larger application Unlike Visual Basic and AppleScript kScript is not a commercial product and the complete source code for it is available on the World Wide Web at http www ticam utexas edu users keenan kScript htm kScript is not in
12. TICAM REPORT 96 08 February 1996 kScript 2 5 User Manual Philip T Keenan kScript 2 5 User Manual Philip T Keenan February 5 1996 l This research was supported in part by the Department of Energy the State of Texas Governor s Energy Office and project grants from the National Science Foundation The author was also supported in part by an NSF Postdoctoral Fellowship 2Texas Institute for Computational and Applied Mathematics The University of Texas at Austin Taylor Hall 2 400 Austin Texas 78712 http www ticam utexas edu users keenan kScript html Contents 1 Introduction 2 SL What de ROGER A ARO OA e dors 2 1 2 Geperient and Disclaimer mesiras a Wie 0 eld BOR AAA AAA 2 Tutorial 5 2 1 Getting Started with ASCHE sai ssw a eek eae ARA RA 5 DA A Simple Script o TERRA AAA eS ae tee a AA Oe 6 2 3 Command Line Arguments eee ee ee ee 7 2 4 Physical Units for Scientific Applications 0 0 2 0 02000 0008 7 LS Using Array Objets oo oe 5 ee bw RA ARA re ey ee eS 8 LE Sting Fincoeur wee ee A RS 6 ee oe SR ERED A 9 2 7 Tracing redirecting output and generating session transcripts 10 2 3 Using Keyword Collections se odes dar BS GS 44 8S SELES Be ss 11 3 Reference Manual 13 DL QUIENES an EA ee AREA AA 13 32 Funcions via eras Wrens Ara a 14 Dee LINDOS mira rr oe ee AAA ECE 14 Sat AE noa e s gy Soe Oe ae Od ee RARA E 16 BO MOCADIUATY bs 2 05 ko Es eo
13. acknowledgment this software uses kScript an application scripting language developed by Philip T Keenan and cite the kScript User Manual TICAM Tech Report The University of Texas at Austin 1996 and the kScript World Wide Web page http www ticam utexas edu users keenan kScript html If the kScript source code is modified a disclaimer stating the nature of the modifications must also be added to both the source code the documentation and any descriptions of the user interface For instance if your program uses kScript or a derivative of it then in any formal setting in which you mention the user interface to your program you must acknowledge its use of kScript For instance a press release conference presentation or paper about your code which mentions the flexible nature of the user interface as a positive feature of your code MUST CREDIT and site kScript as the basis for that feature You MAY NOT claim explicitly or implicitly that this flexible scripting language was your invention The kScript source code the manuals and executable programs incorporating kScript are for NON COMMERCIAL USE only and may not be marketed for profit without a prior written licens ing agreement from the author If you would like to use kScript as part of a research project contact Mary F Wheeler Director of the Center for Subsurface Modeling TICAM at the University of Texas at Austin for distribution and collaboration information The author
14. ame kType category gt Command Alphabetically list all globally defined names of the given type or in the given category Object type names can be further qualified to list just constant or variable objects For convenience the list command recognizes singular and plural forms of type names and the special forms list variables and list constants can be used to list objects of type numeric Note that category names are usually capitalized For instance try list strings to see the string variables used in the program or list Strings to see the commands and functions related to string handling For a complete list of type names use describe typeNames and for a complete list of category names use describe category describe lt nameExpr name gt Command Provides an online description of a command function object or type name For a command or function this prints the syntax and task description For an object it prints the type value and description For a type name it prints the syntax for literals and expressions For a keyword type in particular it lists all currently de fined literal values You can also use describe types describe typeNames and describe keywordTypes for special listings 18 quit Command Stop parsing the current input file here halt Command Exit the program now Command This command does nothing It can be used to terminate interactively typed command
15. as the form open file filename for writing Other variations include reading and appending Alternatively one can open a string for reading with 15 open string stringVariableName for reading array Any type of array can be defined with any number of dimensions and with any base indices For instance the command doubleArray a 4 5 base 1 1 col defines a 2 D column major array of double precision numbers with 4 rows and 5 columns each indexed from as in Fortran For instance a 1 1 is the first element The command intArray a 4 5 6 row makes a 3 D row major array of integers with each component indexed from 0 as in C doubleArray An array of double precision numbers intArray An array of integers stringArray An array of strings assocArray An associative array is an array indexed by keyword collection names the array automat ically grows if new literal values are added to the collections indexing it The constructor syntax follows the pattern doubleAssocArray a collection Access to entries uses the syntax a literal doubleAssocArray An associative array of double precision numbers intAssocArray An associative array of integers stringAssocArray An associative array of strings 3 4 Expressions Many commands take math or string expressions as arguments Math expressions can mix numbers arithmetic and logical operators and symbolic names Math operators are listed in Table 3 1
16. e n gt Function Returns true if the name is defined in the current scope isLit lt name n gt of lt keyword typeName kType gt Function Returns true if the name is a literal of the given keyword collection isConst lt name n gt Function Returns true if the named variable is actually a read only constant 3 5 7 Misc internalStats Command Prints information about the hash table monitorMemory int Set this to a non zero value to check for memory leaks maxSyntaxErrors int The maximum number of syntax errors allowed before the program halts Set this to 1 if you do not ever want the program to stop because of syntax errors 24 Chapter 4 Extending the kScript Programming Language This chapter contains advanced material and may be skipped by beginning users 4 1 Extensions at the scripting level 4 1 1 Overloading command names by type kScriptis designed to be very easy to extend To begin with at the scripting level user defined com mands are very flexible The eval command allows evaluating data a string as code commands much like in LISP and related languages This means users can design new control structures directly in kScript without access to the C implementation For instance one can set up type based overloading of function names as in C by scripting functions along the lines of the following example double d 3 14 string s hi there command show_double double nd echo this
17. ed if encountered when the command is used function A function definition is just like a command definition except that it must use the return command in its script to return a value object The describe command can show the type and value of any object The list command can list all objects or all variables or all constants string String expressions consist of literal text inside curly braces The percent sign signals a special construct or the substitution of the value of a variable name A name argument can be a string literal in curly braces which evaluates to a single word with no internal white space or a single space delimited name numeric Arithmetic expressions cannot contain spaces They can contain literal numbers and numeric variable names as well as various functions like sin and cos connected by all the usual math operators like and either or for exponentiation Use parentheses for grouping to override the usual operator precedences int An integer is a whole number double A double precision number can be written as an integer or a decimal number or in scientific notation keywordType A keyword type has literal values which may be viewed using the describe command Additional literal values may be created using the new command category Categories collect groups of related commands functions and objects to make the list on line help command easier to use stream A stream literal h
18. enerator seed The seed should be a positive integer compare lt nameExpr ni gt lt nameExpr n2 gt Function This function compares two objects of the same type in a type specific way and returns a type specific value For instance comparison on numbers returns negative 0 or positive for less than equals or greater than Comparison on strings also returns on of these three results based on lexicographical ordering For most other types comparison returns 0 for equality and non zero for differences 20 return lt nameExpr symbolName gt Command This returns a value from a user defined function Note that the argument must be the name of an object rather than a math or string expression continue Command This ends the current iteration of an iterative command such as while repeat or for break Command This exits an iterative command such as while repeat or for for each sequence lt nameExpr varName gt in lt stringExpr sourceList gt do lt stringExpr commandList gt Command Iteration command There are three variations of the for command The most general version reads a sequence of already defined variable names then reads values for them from the source list If there are N names and N S items in the source list then the commandList is executed S times once for each set of values For instance for each i s in 1 hi 2 there do In the keyword version instead of a sequence of names a
19. ernal timer in milliseconds String expressions consist of arbitrary text enclosed in curly braces Inside curly braces internal white space is not ignored unless the final right brace is followed by a Curly braces may be nested Within the top level of curly braces one can expand references to other objects values by preceding their names with a percent sign Several other combinations are recognized as well as shown in Table 3 3 In addition formatted conversion is possible For instance strings can be formatted with left center or right justification in a field of a given width Thus replacing 4s with 10c s will center the text of s in a field 10 characters wide 1 and r give left and right justification For numbers use printf formatting codes for instance 4 10 5g x prints x with 5 significant digits in a 10 wide field 3 5 Vocabulary The following subsections list the basic vocabulary of commands functions and objects built into kScript version 2 5 Any program which uses kScript as its application scripting language will automatically support them Such applications typically will define additional vocabulary related to their own subject area these should be documented in the individual applications manuals 3 5 1 Core help Command Provides an overview of the on line help facilities copyright Command Prints the copyright notice and version information list optional variable constant lt keyword n
20. he scope of local variables is not restricted to the body of the function in which they are defined leading to subtle bug possibilities because the interpretation of a function depends upon the complete calling sequence in which it is executed e The kScript interpreter accepts a safe command line argument which disables writing to files and access to the UNIX shell This is intended to make Script safe for use over networks whether coordinating a parallel computation or providing a Web accessible service This is an experimental feature and the author is interested in constructive feedback regarding it e kScript is implemented in C using Object Oriented Programming techniques which make it easy to extend the language In particular the cmdGen user interface compiler converts a text description of an application into a IATpXuser manual and into C source code which is linked with the AScript library to yield a complete user interface for the application For more detailed information about the limitations of TCL see the WWW page AScript is not a little language AScript is a complete programming language with at least as much expressive power as Fortran 77 which is hardly little Script includes comments typed variables such as numbers and strings control structures such as looping and branching and user defined functions and commands Applications can define additional commands functions types and objects which enrich
21. kScripl is ready for you to type a command To exit AScript type quit You can experiment with AScript following this example The echo command prints its argument the text in curly braces on the screen The include command reads in additional commands from the specified file The quit command exits the program There is also a help command that explains the on line help system which you can use to learn about additional commands and objects Just type help with no arguments to get started 2 2 A Simple Script Iere is a slightly more interesting script which shows how you can define and use objects such as numeric variables It will print a simple table of squares and square roots a sample script define command table Print a simple table int first int last int i first double square 0 double square_root 0 echo 4 5r N 4 5r N 2 4 10r sqrt N while i lt last square i i square_root sqrt i echo 1 5 3g i 5 3g square 10 4f square_root i itl table 1 5 echo table 2 4 This script has defined a new command called table which takes two integer arguments first and last It loops over the specified range using echo to print computed values in a formatted table Lines beginning with the pound sign are comments Spaces tabs and new lines matter only within string literals which are delimited by curly braces The syntax and semantics are much like in C and C except
22. keyword collection type name and a variable name are given and the source list is omitted The keyword version executes the commandList once for each literal value in the keyword collection the literal values are assigned to the variable name in the same order in which they are listed by the describe command namely newest to oldest definitions The iteration variable is created local to the scope of the command list For instance for each category c do The third version is for arithmetic progressions The syntax is for lt name gt from lt mathExpr first gt to lt mathExpr last gt optional step lt mathExpr step gt The named variable must be a previously defined numeric object which is set to be the values from first to last inclusive stepping by 1 if no other step is specified 3 5 2 Strings strLen lt stringExpr str gt Function This function returns the length of the string strCmp lt stringExpr stri gt lt stringExpr str2 gt Function This function returns negative zero or positive values as strl precedes equals or or follows str2 alphabetically Unlike the generic compare command this applies only to strings so literal strings are allowed as well as string variables In particular one can compare keyword variables and literals this way as strings strPosn lt stringExpr sourceString gt lt char marker gt Function This function returns the position of the marker character in the string or 0 if
23. makes NO REPRESENTATIONS OR WARRANTIES about the correctness of any source code or documentation nor about the correctness of any executable program or its suitability for any purpose and is in no way liable for any damages resulting from its use or misuse IN NO EVENT SHALL THE AUTHOR S OR DISTRIBUTOR S BE LIABLE TO ANY PARTY FOR DIRECT INDIRECT SPECIAL INCIDENTAL OR CONSEQUENTIAL DAM AGES ARISING OUT OF THE USE OF THIS SOFTWARE ITS DOCUMENTATION OR ANY DERIVATIVES THEREOF EVEN IF THE AUTHOR S HAVE BEEN ADVISED OF THE POS SIBILITY OF SUCH DAMAGE THE AUTHOR S AND DISTRIBUTOR S SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABIL ITY FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT THIS SOFT WARE IS PROVIDED ON AN AS IS BASIS AND THE AUTHOR S AND DISTRIBUTOR S HAVE NO OBLIGATION TO PROVIDE MAINTENANCE SUPPORT UPDATES ENHANCE MENTS OR MODIFICATIONS Chapter 2 Tutorial 2 1 Getting Started with Script To start with here is a very simple script echo Hello World Type this into a file called hello k and then run the command kScript hello k You should see the following output Hello World You can also use Script interactively Run kScript and type the echo command listed above or type include hello k In either case the Hello World message should appear Notice that when running AScript inter actively a kS gt prompt appears when A
24. nction point Evaluate return string to define a new point name n double xv double yv string ret doubleAssocArray n pointField n x xv n y 1 yv 26 return ret F command printPoint Print a point name n eval double xv n x eval double yv n y echo Point wn x xv y yv F string temp lt point pi 0 5 0 7 eval temp temp lt point p2 0 66 0 9 eval temp printPoint p1 printPoint p2 4 2 Extensions at the C source code level Programmers can extend AScript by connecting it to a scientific application using cmdGen The cmdGen program is a user interface compiler It provides an easy way to build AScript user inter faces to application programs A cmdGen script defines the commands objects and type names that will be used in the interface The cmdGen program converts this script to the C source code needed to implement the specified application interface and also creates a IAT X manual docu menting the interface The program understands very general command and function descriptions in which there can be optional arguments or repeated sequences of arguments kScript is a context sensitive language Unlike traditional context free languages argument parsing is under the control of individual commands This makes left context sensitivity easy to implement morcover the command interpreter class can handle one object look ahead making limited right context sensitivity also st
25. ndard output is redirected to the file temp_sys 1log so any redirection requested within expr should be followed by a semicolon shellStr lt stringExpr expr gt Function Have the UNIX shell evaluate the expanded string This function returns the shell s output as a string eval lt stringExpr expr gt Command Evaluate the expanded string as if reading commands from an include file if lt mathExpr expr gt then lt stringExpr thenCommands gt optional else lt stringExpr elseCommands gt Command Branching command if the math expression evaluates to a non zero value execute the commands in the string expression following then otherwise execute the commands in the string expression following else if an else clause is present Alterna tively one can replace the math expression by a function call by using the syntax if lt functionName arguments repeat lt mathExpr repetitions gt times lt stringExpr commandList gt Command Simple Looping command repeat the commands in the string expression repetitions times while lt mathExpr condition gt do lt stringExpr commandList gt Command General Looping command repeat the commands in the string expression as long as the condition is non zero alias lt nameExpr newName gt means lt nameExpr oldName gt Command Define an abbreviation or alternative name for any existing command type or object name seed int The random number g
26. omplicated script files or when running codes in interactive mode as it records all the command you issue and the output that results eval commands This evaluates the supplied commands after reading ks k but before reading the main input file safe This runs AScript in SAFE mode in which the shell command and file output are disabled These options are followed by the name of an input script file and finally by an output file name these default to the keyboard and screen if not specified 2 4 Physical Units for Scientific Applications One application of kScript is to implement systems of physical units in scientific applications Users can create include files containing definitions for the units of interest to them after selecting a set of consistent base units in which output will be displayed For instance one can define CGS units with a script such as the following define define define define define define define define define constant constant constant constant constant constant constant constant constant cm 1 m 100 cm km 107 3x m gm 1 kg 10 3 gm Si min 60 s hr 60 min day 24 hr An application which defined a time step and a domain volume could then be controlled by statements such as set theTimeStep to 4 day 2 hr set theDomainVolume to 4 5xkm 3 which are much easier to read and understand than the input files of many scientific applications Similarly one can define a command p
27. omputa tional grid defining coefficients and taking one or more time steps Other scientific computing applications might define objects such as the time step or an error measurement In this case kScript would allow the user to implement an adaptive time step selection algorithm and exper iment with modifications of it all without need to understand or even access the source code for the application Chapter 2 is a tutorial introduction to scripting with kScript Chapter 3 is the kScript Reference Manual It discusses those commands functions types and objects defined by the core kScript language and hence available in all applications which support AScript Finally Chapter 4 describes how programmers can extend the Script language by making variables and procedures within their application known to kScript thereby giving the user detailed control over the execution of the application 1 2 Copyright and Disclaimer Copyright C Philip Thomas Keenan 1990 1996 The following terms apply to all printed documents and computer files distributed with the kScript software package The source code and manuals for kScript are COPYRIGHTED but they may be freely copied as long as all copyright notices are retained verbatim in all copies In addition if the source code or derivatives of it are incorporated into another software package the source code the documentation and any descriptions of the user interface for that package must contain the
28. or one may be chosen The sequence keyword introduces an argument pattern which may be repeated multiple times A sequence argument can be an empty string 13 a curly brace delimited list of one or more instances of the pattern or a single instance without the surrounding curly braces In kScript a space delimited sharp or pound symbol comments out the rest of the line on which it occurs Mathematical expressions must be written with no internal spaces String literals must be enclosed in curly braces not quote marks The curly braces can be nested and within them only the percent sign 4 is special all other text is recorded verbatim In all other contexts white space spaces tabs line breaks and so on serves only to delimit commands and their arguments 3 2 Functions Functions are commands that return a value If they are invoked like a command the value is printed on the screen but they can also be invoked using the syntax set variableName lt functionName arguments in which case the return value is stored in the indicated variable 3 3 Types The formal argument types in command descriptions generally correspond to C classes The actual argument must be in the correct format for the specified type For an online explanation of the syntax for a particular type T use the command describe T Applications can define new C types and use them as arguments to commands by defining a text representation and providing
29. particular category The online help system can list all members of a given category using the list command For instance list Strings produces a list of all the string related built in functions such as strCmp strLeft etc which are explained in detail in Section 3 5 2 This differs from the command list strings 11 which lists all objects of string type such as the string variables directory and includeDir For a complete list of category names use the command describe category which can also be used to list the literal values in any keyword collection kScript has many additional features which you can learn about by browsing the reference section of this manual and trying out your own scripts Enjoy 12 Chapter 3 Reference Manual For complete and up to date lists of all commands functions types and objects known to a par ticular application run the program and access on line help Type help to get started This reference manual describes the core features of kScript found in any kScriptable program Individual programs can define additional commands functions types and objects as described in Chapter 4 which extend the functionality of kScript 3 1 Commands kScript reads commands from the keyboard or an input script file and executes them as they are read rather than storing them for later batch mode execution This allows the user to have interactive control over scientific applications provided those a
30. pplications are written in an event driven style rather than in a batch processing style In the reference sections that follow each command s name is followed by a list of arguments Most arguments consist of a type name and a descriptive formal argument name grouped as a pair in angled brackets These represent required arguments to the command the actual supplied argument will be parsed according to the syntax rules for the specified type Arguments enclosed in square brackets are optional literal strings typically prepositions They can be used to create English sentence like scripts which are easy to read or they can be omitted with no change in the meaning of the script Sometimes several alternatives are listed separated by a vertical bar For example the syntax of the set command is set diameExpr nan tol Expression expr Both the name set and the equals sign are optional so the five commands set x to 3 14 set x 3 14 x 3 14 set x 3 14 x 3 14 all assign the same value to a variable named x but the first three versions are easier for a human reader to understand 13 The keywords optional and required introduce alternative sets of arguments Each set begins with a string literal which if encountered while parsing the command signals that the remainder of that clause will follow Multiple cases can be separated by a vertical bar In the required case one alternative must be selected in the optional case zero
31. raightforward to use cmdGen takes the place of a traditional parser generator like yace or bison allowing programmers to quickly and easily define and implement new commands complete with automatically generated on line help The user manual for cmdGen contains further information on how programmers can connect applications to kScript Bibliography 1 Keenan P T emdGen 2 5 User Manual Texas Institute for Computational and Applied Mathematics University of Texas at Austin February 1996 2 Keenan P T TUF 2 5 User Manual The Texas Unstructured Flow Code Texas Institute for Computational and Applied Mathematics University of Texas at Austin February 1996 3 Keenan P T RUF 1 0 User Manual The Rice Unstructured Flow Code Dept of Computa tional and Applied Mathematics Tech Report 94 30 Rice University 1994 4 Keenan P T kScript 1 0 User Manual Dept of Computational and Applied Mathematics Tech Report 3495 02 Rice University 1995 5 Keenan P T C and FORTRAN Timing Comparisons Dept of Computational and Ap plied Mathematics Tech Report 93 03 Rice University 1993 28
32. rint for output with units so that print theTimeStep in days prints for instance 4 083 day Moreover none of this requires reprogramming or even recompi lation of the executable program users can do this by editing a AScript text file 2 5 Using Array Objects Ilere is a simple script which declares a two dimensional array fills it with values and prints it in 1 D aud 2 D formats As in other languages one can use use while loops or for loops for the arithmetic progression of the indices in the iterations In kScript however for loops can also provide iteration over an enumerated list either an explicit one or one implied by a keyword collection described in the next section Use while loops to iterate over numeric ranges that are not simple arithmetic progressions doubleArray bb 3 4 base 1 2 row int i 0 int j 0 for i from 1 to 3 do for j from 2 to 5 do bb i j i 1 j 2 2 describe bb echo Value bb echo The 1 4 entry is bb 1 4 the 1 5 one is bb 1 5 string temp echo temp for iintf 123 do for jin12345 do 4 temp temp bb i j echo temp temp The output from this script is Description of doubleArray bb 2 dimensions row major storage size first last 3 1 3 4 2 5 Value 014912510236 11 The 1 4 entry is 4 the 1 5 one is 9 0149 12510 2 3 6 11 2 6 String Functions In Script commands produce actions but do not re
33. s that would otherwise look for optional arguments lt nameExpr name gt Command This command prints the value of the named object This is primarily for interactive use use the echo command for formatted output For convenience can also print the value of a math expression debug Command Enter the interactive kScript debugger A subsequent quit command will return processing to the main script include file lt nameExpr filename gt Command Read commands from a script file directory string The current directory path for file names such as those used by the include command includeDir string The directory path used for include files not found in directory This variable is initially set to the value of the shell environment variable KSCRIPT_INC_DIR traceLevel int When this number is positive kScript prints tracing messages for this many levels of nested commands When negative tracing is turned on for all commands regardless of how deeply nested When zero tracing is off define lt keyword typeName kType gt optional constant lt nameExpr name gt required lt typedExpression expr gt lt lt typedFunctionExpr fexpr gt Command Define a new variable or constant of some type T The define can be omitted if a type name is given If no type is given double is used The expression syntax must be appropriate for an object of type T If define is used inside a command
34. that lines do not end in semi colons All of the commands are explained in more detail in the reference section of this manual When run this script produces the following output N N2 sqrt N 1 1 1 0000 2 4 1 4142 3 9 1 7321 4 16 2 0000 5 25 2 2361 N N2 sqrt N 2 4 1 4142 3 9 1 7321 4 16 2 0000 In addition to the square root function sqrt AScript contains a number of other mathemati cal functions including exponential and trigonometric functions as well as uniform and Gaussian random number generators as listed in Table 3 2 2 3 Command Line Arguments The kScript interpreter uses the environment variable KSCRIPT_INC_DIR to initialize the includeDir string variable The include command looks in this directory if it cannot find the specified file in the current directory Note that the directory variable can be examined and modified to change the current directory The kScript interpreter starts by including a file named ks k if one can be found in the current directory or the include directory then it evaluates any supplied eval arguments in the command line and finally it reads the supplied input script directing output to the supplied output file The kScript program accepts the following command line arguments on UNIX platforms usage This prints the usage message transcript wfilename This causes a transcript of the current kScript session to be written to the specified file This can be useful when debugging c
35. the vocabulary and power of kScript AScript has online help and if applications are built using cmdGen both the online and hardcopy help are automatically consistent with the actual behavior of the application Scripts in kScript are similar to UNIX shell scripts indeed the shel1Cmd command and the eval command combine to let kScript interact with the UNIX shell in very general ways thereby enabling powerful extended features like interactive inter application communication across net works Script is also similar to MATLAB it provides an interactive environment for numeric computation However the full potential of kSeript only becomes apparent when applications de fine additional commands and objects which enrich the language with actions and concepts specific to the application domain For example my kplot graphics program extends kScript by defining additional commands for plotting lines triangles rectangles and polygons It uses objects to represent color and font palettes and to control the coordinate system Moreover since amp Script lets users write their own subroutines and functions it can even be extended with commands to create custom axis tic mark patterns and labels without any knowledge of the internals of the program or any need to recompile it As another example the Rice Unstructured Flow code RUF solves elliptic partial differential equation on general geometries It extends kSeript with commands for specifying the c
36. turn values Functions are commands that also return values They can be entered by themselves like commands in which case the return value is printed as output or the return value can be assigned to a variable using the lt syntax variation of the set command kScriptincludes several built in functions for manipulating strings some of which are illustrated in the following script function strRest Return the rest of the string after the leftmost n characters int n string input int len lt strLen input string rest lt strRight len n input return rest F Example string a window frame strLeft 4 a strRest 4 a strRight 4 a The point is that although AScript has built in functions for returning the n leftmost or rightmost characters of a string it lacks a builtin function for returning the rest of a string after the leftmost n characters However this lack is easily remedied since one can define a function to do precisely this as shown above The output from running the script is wind ow frame rame 2 7 Tracing redirecting output and generating session tran scripts When scripts become long and start calling lots of user defined commands and functions it can be helpful to trace their execution especially when they do not execute as you expected The following simple script demonstrates turning on tracing traceLevel 1 double x 3 14 echo This 4x appears on the screen x x 1 echo
Download Pdf Manuals
Related Search
Related Contents
MAGNETICALLY DRIVEN CHEMICAL PUMP Croplands Operators Manual View PDF - Rice Lake Retail Solutions 7.2. 本業務に従事する要員の条件 Allegato 10 - Specifica Tecnica 2 assi_Lotto 3 - rev 28 05 IC-E91 SERVICE MANUAL here - Frank`s Hospital Workshop Copyright © All rights reserved.
Failed to retrieve file