1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
|
/*
* Copyright (c) 2002-2006 Samit Basu
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include "Array.hpp"
#include "Interpreter.hpp"
#include "Scanner.hpp"
#include "Parser.hpp"
#include "System.hpp"
#include <QtCore>
#include "Algorithms.hpp"
#include "PathSearch.hpp"
//!
//@Module SIMKEYS Simulate Keypresses from the User
//@@Section FREEMAT
//@@Usage
//This routine simulates keystrokes from the user on FreeMat.
//The general syntax for its use is
//@[
// otext = simkeys(text)
//@]
//where @|text| is a string to simulate as input to the console.
//The output of the commands are captured and returned in the
//string @|otext|. This is primarily used by the testing
//infrastructure.
//@@Signature
//sfunction simkeys SimKeysFunction
//inputs itext
//outputs otext
//!
ArrayVector SimKeysFunction(int nargout, const ArrayVector& arg,
Interpreter* eval) {
if (arg.size() == 0)
throw Exception("simkeys requires at least one argument (the cell array of strings to simulate)");
ParentScopeLocker lock(eval->getContext());
eval->clearCaptureString();
eval->setCaptureState(true);
if (arg[0].dataClass() != CellArray)
throw Exception("simkeys requires a cell array of strings");
const BasicArray<Array> &dp(arg[0].constReal<Array>());
for (index_t i=1;i<=dp.length();i++) {
QString txt(dp[i].asString());
if ((txt.size() > 0) && (!txt.endsWith('\n')))
txt.push_back('\n');
eval->ExecuteLine(txt);
}
eval->ExecuteLine("quit\n");
try {
while(1)
eval->evalCLI();
} catch (InterpreterContinueException& e) {
} catch (InterpreterBreakException& e) {
} catch (InterpreterReturnException& e) {
} catch (InterpreterRetallException& e) {
} catch (InterpreterQuitException& e) {
}
eval->setCaptureState(false);
return ArrayVector(Array(eval->getCaptureString()));
}
//!
//@Module DIARY Create a Log File of Console
//@@Section FREEMAT
//@@Usage
//The @|diary| function controls the creation of a log file that duplicates
//the text that would normally appear on the console.
//The simplest syntax for the command is simply:
//@[
// diary
//@]
//which toggles the current state of the diary command. You can also explicitly
//set the state of the diary command via the syntax
//@[
// diary off
//@]
//or
//@[
// diary on
//@]
//To specify a filename for the log (other than the default of @|diary|), you
//can use the form:
//@[
// diary filename
//@]
//or
//@[
// diary('filename')
//@]
//which activates the diary with an output filename of @|filename|. Note that the
//@|diary| command is thread specific, but that the output is appended to a given
//file. That means that if you call @|diary| with the same filename on multiple
//threads, their outputs will be intermingled in the log file (just as on the console).
//Because the @|diary| state is tied to individual threads, you cannot retrieve the
//current diary state using the @|get(0,'Diary')| syntax from MATLAB. Instead, you
//must call the @|diary| function with no inputs and one output:
//@[
// state = diary
//@]
//which returns a logical @|1| if the output of the current thread is currently going to
//a diary, and a logical @|0| if not.
//@@Signature
//sfunction diary DiaryFunction
//inputs x
//outputs state
//!
ArrayVector DiaryFunction(int nargout, const ArrayVector& arg, Interpreter* eval) {
if (nargout == 1) {
if (arg.size() > 0)
throw Exception("diary function with an assigned return value (i.e, 'x=diary') does not support any arguments");
return ArrayVector(Array(bool(eval->getDiaryState())));
}
if (arg.size() == 0) {
eval->setDiaryState(!eval->getDiaryState());
return ArrayVector();
}
QString diaryString(arg[0].asString());
if (diaryString.toLower() == "on")
eval->setDiaryState(true);
else if (diaryString.toLower() == "off")
eval->setDiaryState(false);
else {
eval->setDiaryFilename(diaryString);
eval->setDiaryState(true);
}
return ArrayVector();
}
//!
//@Module QUIET Control the Verbosity of the Interpreter
//@@Section FREEMAT
//@@Usage
//The @|quiet| function controls how verbose the interpreter
//is when executing code. The syntax for the function is
//@[
// quiet flag
//@]
//where @|flag| is one of
//\begin{itemize}
//\item @|'normal'| - normal output from the interpreter
//\item @|'quiet'| - only intentional output (e.g. @|printf| calls and
//@|disp| calls) is printed. The output of expressions that are not
//terminated in semicolons are not printed.
//\item @|'silent'| - nothing is printed to the output.
//\end{itemize}
//The @|quiet| command also returns the current quiet flag.
//@@Signature
//sfunction quiet QuietFunction
//inputs mode
//outputs mode
//!
ArrayVector QuietFunction(int nargout, const ArrayVector& arg, Interpreter* eval) {
if (arg.size() > 0) {
QString qtype(arg[0].asString().toUpper());
if (qtype == "NORMAL")
eval->setQuietLevel(0);
else if (qtype == "QUIET")
eval->setQuietLevel(1);
else if (qtype == "SILENT")
eval->setQuietLevel(2);
else
throw Exception("quiet function takes one argument - the quiet level (normal, quiet, or silent) as a string");
}
QString rtype;
if (eval->getQuietLevel() == 0)
rtype = "normal";
else if (eval->getQuietLevel() == 1)
rtype = "quiet";
else if (eval->getQuietLevel() == 2)
rtype = "silent";
return ArrayVector(Array(rtype));
}
//!
//@Module SOURCE Execute an Arbitrary File
//@@Section FREEMAT
//@@Usage
//The @|source| function executes the contents of the given
//filename one line at a time (as if it had been typed at
//the @|-->| prompt). The @|source| function syntax is
//@[
// source(filename)
//@]
//where @|filename| is a @|string| containing the name of
//the file to process.
//@@Example
//First, we write some commands to a file (note that it does
//not end in the usual @|.m| extension):
//@{ source_test
//a = 32;
//b = a;
//printf('a is %d and b is %d\n',a,b);
//@}
//Now we source the resulting file.
//@<
//clear a b
//source source_test
//@>
//@@Tests
//@{ source_test_script.m
//n = 1;
//n = n + 1;
//@}
//@{ test_source.m
//% Check that the source function does not double-execute the last line of the script
//function test_val = test_source
//myloc = which('test_source');
//[path,name,sfx] = fileparts(myloc);
//source([path '/source_test_script.m'])
//test_val = test(n == 2);
//@}
//@@Signature
//sfunction source SourceFunction
//inputs filename
//outputs none
//!
ArrayVector SourceFunction(int nargout, const ArrayVector& arg, Interpreter* eval) {
if (arg.size() != 1)
throw Exception("source function takes exactly one argument - the filename of the script to execute");
QString filename = arg[0].asString();
QFile fp(filename);
if (!fp.open(QFile::ReadOnly))
throw Exception("unable to open file " + filename + " for reading");
QTextStream fstr(&fp);
QString scriptText(fstr.readAll());
if (!scriptText.endsWith("\n")) scriptText += "\n";
Scanner S(scriptText,filename);
Parser P(S);
Tree pcode(P.process());
if (pcode.is(TOK_FUNCTION_DEFS))
throw Exception("only scripts can be source-ed, not functions");
Tree code = pcode.first();
ParentScopeLocker lock(eval->getContext());
eval->block(code);
return ArrayVector();
}
//!
//@Module TYPE Type
//@@Section FREEMAT
//@@Usage
//Displays the content of a m-script file or an ascii file.
//The type function takes one argument:
//@[
// type filename
// type ('filename')
//@]
//This command will first look for filename in FreeMat search path,
//if not found it will look for m-script file by adding '.m' to filename
//@@Signature
//sfunction type TypeFunction
//inputs function
//outputs none
//!
ArrayVector TypeFunction(int nargout, const ArrayVector& arg, Interpreter* eval)
{
PathSearcher psearch(eval->getTotalPath());
if (arg.size() != 1)
throw Exception("type function requires a single argument (m-script name or ascii file name)");
QString fname = arg[0].asString();
bool isFun;
FuncPtr val;
QString filename = psearch.ResolvePath(fname);
if( filename.isNull() ){
isFun = eval->getContext()->lookupFunction(fname,val);
if (isFun && (val->type() == FM_M_FUNCTION)) {
MFunctionDef *mptr;
mptr = (MFunctionDef *) val;
if( mptr )
filename = mptr->fileName;
else
throw Exception(fname + " does not exist");
}
else
throw Exception(fname + " does not exist");
}
QFile fp(filename);
if (!fp.open(QIODevice::ReadOnly))
throw Exception("Cannot open " + fname);
QTextStream io(&fp);
while (!io.atEnd()) {
QString cp = io.readLine();
eval->outputMessage(cp);
eval->outputMessage("\n");
}
return ArrayVector();
}
//!
//@Module BUILTIN Evaulate Builtin Function
//@@Section FREEMAT
//@@Usage
//The @|builtin| function evaluates a built in function
//with the given name, bypassing any overloaded functions.
//The syntax of @|builtin| is
//@[
// [y1,y2,...,yn] = builtin(fname,x1,x2,...,xm)
//@]
//where @|fname| is the name of the function to call. Apart
//from the fact that @|fname| must be a string, and that @|builtin|
//always calls the non-overloaded method, it operates exactly like
//@|feval|. Note that unlike MATLAB, @|builtin| does not force
//evaluation to an actual compiled function. It simply subverts
//the activation of overloaded method calls.
//@@Tests
//@{ test_builtin1.m
//function test_val = test_builtin1
// a = -1;
// b = builtin('abs',a);
// test_val = (b == 1);
//end
//function y = abs(x)
// y = x;
//end
//@}
//@@Signature
//sfunction builtin BuiltinFunction
//inputs fname varargin
//outputs varargout
//!
ArrayVector BuiltinFunction(int nargout, const ArrayVector& arg,Interpreter* eval){
if (arg.size() == 0)
throw Exception("builtin function requires at least one argument");
if (!(arg[0].isString()))
throw Exception("first argument to builtin must be the name of a function (i.e., a string)");
FuncPtr funcDef;
QString fname = arg[0].asString();
Context *context = eval->getContext();
if (!context->lookupFunction(fname,funcDef))
throw Exception("function " + fname + " undefined!");
funcDef->updateCode(eval);
if (funcDef->scriptFlag)
throw Exception("cannot use feval on a script");
ArrayVector newarg(arg);
newarg.pop_front();
bool flagsave = eval->getStopOverload();
eval->setStopOverload(true);
ArrayVector tmp(eval->doFunction(funcDef,newarg,nargout));
eval->setStopOverload(flagsave);
return tmp;
}
//!
//@Module STARTUP Startup Script
//@@Section FREEMAT
//@@Usage
//Upon starting, FreeMat searches for a script names @|startup.m|, and
//if it finds it, it executes it. This script can be in the current
//directory, or on the FreeMat path (set using @|setpath|). The contents
//of startup.m must be a valid script (not a function).
//!
//!
//@Module DOCLI Start a Command Line Interface
//@@Section FREEMAT
//@@Usage
//The @|docli| function is the main function that you interact with
//when you run FreeMat. I am not sure why you would want to use
//it, but hey - its there if you want to use it.
//@@Signature
//sfunction docli DoCLIFunction
//inputs none
//outputs none
//!
ArrayVector DoCLIFunction(int nargout, const ArrayVector& arg, Interpreter* eval) {
Context *context = eval->getContext();
context->deactivateCurrentScope();
FuncPtr funcDef;
if (eval->lookupFunction("startup",funcDef)) {
funcDef->updateCode(eval);
if (funcDef->scriptFlag) {
try {
eval->block(((MFunctionDef*)funcDef)->code);
} catch (Exception& e) {
eval->errorMessage("Startup script error:\n" + e.msg());
}
} else {
eval->outputMessage(QString("startup.m must be a script"));
}
}
eval->doCLI();
return ArrayVector();
}
//!
//@Module SYSTEM Call an External Program
//@@Section OS
//@@Usage
//The @|system| function allows you to call an external
//program from within FreeMat, and capture the output.
//The syntax of the @|system| function is
//@[
// y = system(cmd)
//@]
//where @|cmd| is the command to execute. The return
//array @|y| is of type @|cell-array|, where each entry
//in the array corresponds to a line from the output.
//@@Example
//Here is an example of calling the @|ls| function (the
//list files function under Un*x-like operating system).
//@<
//y = system('ls')
//y{1}
//@>
//@@Signature
//function system SystemFunction
//inputs cmd
//outputs results
//!
ArrayVector SystemFunction(int nargout, const ArrayVector& arg) {
if (arg.size() != 1)
throw Exception("System function takes one string argument");
QString systemArg(arg[0].asString());
if (systemArg.size() == 0)
return ArrayVector();
StringVector cp(DoSystemCallCaptured(systemArg));
return CellArrayFromStringVector(cp);
}
|