-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
MacroFunctionDef.cpp
510 lines (500 loc) · 19.3 KB
/
MacroFunctionDef.cpp
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
//=============================================================================
// Copyright (c) 2016-present Allan CORNET (Nelson)
//=============================================================================
// This file is part of the Nelson.
//=============================================================================
// LICENCE_BLOCK_BEGIN
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// Alternatively, 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program. If not, see <http://www.gnu.org/licenses/>.
// LICENCE_BLOCK_END
//=============================================================================
#include <boost/format.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem.hpp>
#include "MacroFunctionDef.hpp"
#include "Context.hpp"
#include "FileParser.hpp"
#include "ParserInterface.hpp"
#include "Warning.hpp"
#include "Evaluator.hpp"
#include "characters_encoding.hpp"
#include "Profiler.hpp"
#include "ProfilerHelpers.hpp"
//=============================================================================
namespace Nelson {
//=============================================================================
MacroFunctionDef::MacroFunctionDef()
{
this->setTimestamp(0);
this->localFunction = false;
this->nextFunction = nullptr;
this->prevFunction = nullptr;
this->code = nullptr;
this->ptrAstCodeAsVector.clear();
this->isScript = false;
this->withWatcher = false;
}
//=============================================================================
MacroFunctionDef::MacroFunctionDef(const std::wstring& filename, bool withWatcher)
{
this->localFunction = false;
this->nextFunction = nullptr;
this->prevFunction = nullptr;
this->code = nullptr;
this->setFilename(filename);
this->setTimestamp(0);
updateCode();
this->withWatcher = withWatcher;
}
//=============================================================================
MacroFunctionDef::~MacroFunctionDef()
{
if (nextFunction != nullptr) {
delete nextFunction;
nextFunction = nullptr;
}
AbstractSyntaxTree::deleteReferences(ptrAstCodeAsVector);
code = nullptr;
localFunction = false;
isScript = false;
withWatcher = false;
}
//=============================================================================
int
MacroFunctionDef::nargin()
{
if (arguments.empty()) {
return 0;
}
if (arguments[arguments.size() - 1] == "varargin") {
return -static_cast<int>(arguments.size());
}
return static_cast<int>(arguments.size());
}
//=============================================================================
int
MacroFunctionDef::inputArgCount()
{
if (arguments.empty()) {
return 0;
}
if (arguments[arguments.size() - 1] == "varargin") {
return -1;
}
return static_cast<int>(arguments.size());
}
//=============================================================================
int
MacroFunctionDef::nargout()
{
if (returnVals.empty()) {
return 0;
}
if (returnVals[returnVals.size() - 1] == "varargout") {
return -static_cast<int>(returnVals.size());
}
return static_cast<int>(returnVals.size());
}
//=============================================================================
int
MacroFunctionDef::outputArgCount()
{
if (returnVals.empty()) {
return 0;
}
if (returnVals[returnVals.size() - 1] == "varargout") {
return -1;
}
return static_cast<int>(returnVals.size());
}
//=============================================================================
ArrayOfVector
MacroFunctionDef::evaluateMFunction(Evaluator* eval, const ArrayOfVector& inputs, int nargout)
{
ArrayOfVector outputs;
size_t minCount = 0;
Context* context = eval->getContext();
context->pushScope(this->getName());
std::string filenameUtf8 = wstring_to_utf8(this->getFilename());
eval->callstack.pushDebug(filenameUtf8, this->getName());
// Push our local functions onto the function scope
MacroFunctionDef* cp = this;
while (cp->prevFunction != nullptr) {
cp = cp->prevFunction;
}
cp = cp->nextFunction;
while (cp != nullptr) {
context->insertMacroFunctionLocally((FunctionDefPtr)cp);
cp = cp->nextFunction;
}
// When the function is called, the number of inputs is
// at sometimes less than the number of arguments requested.
// Check the argument count. If this is a non-varargin
// argument function, then use the following logic:
minCount = 0;
if (inputArgCount() != -1) {
if (inputs.size() > arguments.size()) {
context->popScope();
eval->callstack.popDebug();
Error(ERROR_WRONG_NUMBERS_INPUT_ARGS);
}
minCount = (inputs.size() < arguments.size()) ? inputs.size() : arguments.size();
for (size_t i = 0; i < minCount; i++) {
std::string arg(arguments[i]);
context->insertVariableLocally(arg, inputs[i]);
}
context->getCurrentScope()->setNargIn(static_cast<int>(minCount));
} else {
// Count the number of supplied arguments
size_t inputCount = inputs.size();
size_t nbArgumentsWithoutVarArgIn = arguments.size();
if (arguments[arguments.size() - 1] == "varargin") {
nbArgumentsWithoutVarArgIn = nbArgumentsWithoutVarArgIn - 1;
}
if (inputCount < nbArgumentsWithoutVarArgIn) {
context->popScope();
eval->callstack.popDebug();
Error(ERROR_WRONG_NUMBERS_INPUT_ARGS);
}
context->getCurrentScope()->setNargIn(static_cast<int>(inputCount));
// Get the number of explicit arguments
int explicitCount = static_cast<int>(arguments.size()) - 1;
// For each explicit argument (that we have an input for),
// insert it into the scope.
minCount = (explicitCount < static_cast<int>(inputCount))
? static_cast<size_t>(explicitCount)
: inputCount;
size_t i;
for (i = 0; i < minCount; i++) {
std::string arg(arguments[i]);
context->insertVariableLocally(arg, inputs[i]);
}
inputCount -= minCount;
// Put minCount...inputCount
ArrayOf varg(NLS_CELL_ARRAY);
varg.vectorResize(inputCount);
auto* dp = static_cast<ArrayOf*>(varg.getReadWriteDataPointer());
for (i = 0; i < inputCount; i++) {
dp[i] = inputs[i + minCount];
}
varg.name("varargin");
context->insertVariableLocally("varargin", varg);
}
context->getCurrentScope()->setNargOut(nargout);
uint64 tic = 0;
try {
uint64 tic = Profiler::getInstance()->tic();
eval->block(code);
if (tic != 0) {
internalProfileFunction stack
= computeProfileStack(eval, getCompleteName(), this->getFilename(), false);
Profiler::getInstance()->toc(tic, stack);
}
State state(eval->getState());
if (state < NLS_STATE_QUIT) {
eval->resetState();
}
if (state == NLS_STATE_ABORT) {
return scalarArrayOfToArrayOfVector(ArrayOf::emptyConstructor());
}
bool warningIssued = false;
if (outputArgCount() != -1) {
outputs.resize(returnVals.size());
ArrayOf a;
for (size_t i = 0; i < returnVals.size(); i++) {
if (!context->lookupVariableLocally(returnVals[i], a)) {
if (!warningIssued) {
std::wstring message = str(boost::wformat(_W("Function : '%s'."))
% utf8_to_wstring(this->getName()));
message = message + L"\n" + WARNING_OUTPUTS_NOT_ASSIGNED;
Warning(message);
warningIssued = true;
}
a = ArrayOf::emptyConstructor();
}
outputs[i] = a;
}
} else {
ArrayOf varargout;
bool haveVarargout = context->lookupVariableLocally("varargout", varargout);
if (haveVarargout) {
if (varargout.getDataClass() != NLS_CELL_ARRAY) {
context->popScope();
eval->callstack.popDebug();
Error(_W("The special variable 'varargout' was not defined as a "
"cell-array."));
}
}
indexType varlen = varargout.getElementCount();
int explicitCount = static_cast<int>(returnVals.size()) - 1;
bool noArgs = (explicitCount == 0 && varlen == 0);
if (!noArgs && !haveVarargout) {
context->popScope();
eval->callstack.popDebug();
Error(_W("The special variable 'varargout' was not defined as expected."));
}
if (explicitCount == 0 && varlen > 0 && nargout < 2) {
indexType toFill = 1;
outputs.resize(toFill);
const ArrayOf* dp = (static_cast<const ArrayOf*>(varargout.getDataPointer()));
// Get the length
if (static_cast<indexType>(toFill)
> static_cast<indexType>(varargout.getElementCount())) {
Error(_W("Not enough outputs in varargout to satisfy call."));
}
outputs[0] = dp[0];
} else {
outputs.resize(nargout);
// For each explicit argument (that we have), insert it
// into the scope.
ArrayOf a;
for (int i = 0; i < explicitCount; i++) {
if (!context->lookupVariableLocally(returnVals[i], a)) {
if (!warningIssued) {
Warning(_W("one or more outputs not assigned in call."));
warningIssued = true;
}
a = ArrayOf::emptyConstructor();
}
outputs[i] = a;
}
// Are there any outputs not yet filled?
if (nargout > explicitCount) {
// Get the data pointer
const ArrayOf* dp = (static_cast<const ArrayOf*>(varargout.getDataPointer()));
// Get the length
int toFill = nargout - explicitCount;
if (static_cast<double>(toFill) > static_cast<double>(varlen)) {
Error(_W("Not enough outputs in varargout to satisfy call."));
}
for (int i = 0; i < toFill; i++) {
outputs[explicitCount + i] = dp[i];
}
}
}
}
context->popScope();
eval->callstack.popDebug();
} catch (const Exception&) {
if (tic != 0) {
internalProfileFunction stack
= computeProfileStack(eval, getCompleteName(), this->getFilename(), false);
Profiler::getInstance()->toc(tic, stack);
}
context->popScope();
eval->callstack.popDebug();
throw;
}
return outputs;
}
//=============================================================================
ArrayOfVector
MacroFunctionDef::evaluateMScript(Evaluator* eval, const ArrayOfVector& inputs, int nargout)
{
ArrayOfVector outputs;
Context* context = eval->getContext();
std::string filenameUtf8 = wstring_to_utf8(this->getFilename());
eval->callstack.pushDebug(filenameUtf8, this->getName());
context->getCurrentScope()->setNargIn(0);
context->getCurrentScope()->setNargOut(0);
uint64 tic = 0;
try {
uint64 tic = Profiler::getInstance()->tic();
eval->block(code);
if (tic != 0) {
internalProfileFunction stack
= computeProfileStack(eval, getCompleteName(), this->getFilename(), false);
Profiler::getInstance()->toc(tic, stack);
}
State state(eval->getState());
if (state < NLS_STATE_QUIT) {
eval->resetState();
}
if (state == NLS_STATE_ABORT) {
return scalarArrayOfToArrayOfVector(ArrayOf::emptyConstructor());
}
eval->callstack.popDebug();
} catch (const Exception&) {
if (tic != 0) {
internalProfileFunction stack
= computeProfileStack(eval, getCompleteName(), this->getFilename(), false);
Profiler::getInstance()->toc(tic, stack);
}
eval->callstack.popDebug();
throw;
}
return outputs;
}
//=============================================================================
ArrayOfVector
MacroFunctionDef::evaluateFunction(Evaluator* eval, const ArrayOfVector& inputs, int nargout)
{
updateCode();
if (isScript) {
return evaluateMScript(eval, inputs, nargout);
}
return evaluateMFunction(eval, inputs, nargout);
}
//=============================================================================
std::string
MacroFunctionDef::getCompleteName()
{
if (this->localFunction) {
MacroFunctionDef* pF = this->prevFunction;
while (pF != nullptr) {
if (!pF->localFunction) {
return pF->getName() + ">" + this->getName();
}
pF = pF->prevFunction;
}
}
return this->getName();
}
//=============================================================================
bool
MacroFunctionDef::updateCode()
{
bool forceUpdate = this->code == nullptr;
bool doUpdate = (forceUpdate || withWatcher) && (!this->localFunction);
if (!doUpdate) {
return false;
}
try {
time_t currentFileTimestamp = boost::filesystem::last_write_time(this->getFilename());
if (currentFileTimestamp == this->getTimestamp() && !forceUpdate) {
return false;
}
this->setTimestamp(currentFileTimestamp);
} catch (const boost::filesystem::filesystem_error&) {
return false;
}
if (code != nullptr) {
for (auto ptr : this->ptrAstCodeAsVector) {
delete ptr;
}
ptrAstCodeAsVector.clear();
code = nullptr;
}
FILE* fr;
#ifdef _MSC_VER
fr = _wfopen(this->getFilename().c_str(), L"rt");
#else
fr = fopen(wstring_to_utf8(this->getFilename()).c_str(), "r");
#endif
if (fr == nullptr) {
int errnum = errno;
std::string msg1 = str(boost::format(_("Value of errno: %d")) % errno);
std::string msg2 = str(boost::format(_("Error opening file: %s")) % strerror(errnum));
Error(_W("Cannot open:") + L" " + this->getFilename() + L"\n" + utf8_to_wstring(msg1)
+ L"\n" + utf8_to_wstring(msg2));
}
ParserState pstate = ParserState::ParseError;
AbstractSyntaxTree::clearReferences();
AbstractSyntaxTreePtrVector ptAstCode;
try {
pstate = parseFile(fr, wstring_to_utf8(this->getFilename()));
ptAstCode = AbstractSyntaxTree::getReferences();
} catch (const Exception&) {
AbstractSyntaxTree::deleteReferences();
if (fr != nullptr) {
fclose(fr);
}
throw;
}
if (fr != nullptr) {
fclose(fr);
}
if (pstate == ParserState::ParseError) {
AbstractSyntaxTree::deleteReferences(ptAstCode);
AbstractSyntaxTree::clearReferences();
Error(_W("a valid function definition expected.") + std::wstring(L"\n")
+ this->getFilename());
}
try {
if (pstate == ParserState::FuncDef) {
MacroFunctionDef* macroFunctionDef = getParsedFunctionDef();
this->setIsScript(false);
if (macroFunctionDef == nullptr) {
boost::filesystem::path pathFunction(this->getFilename());
this->setName(pathFunction.stem().generic_string());
} else {
this->code = macroFunctionDef->code;
this->arguments = macroFunctionDef->arguments;
this->localFunction = macroFunctionDef->localFunction;
this->nextFunction = macroFunctionDef->nextFunction;
this->prevFunction = macroFunctionDef->prevFunction;
this->returnVals = macroFunctionDef->returnVals;
this->ptrAstCodeAsVector = macroFunctionDef->ptrAstCodeAsVector;
this->setName(macroFunctionDef->getName());
}
} else {
this->code = getParsedScriptBlock();
this->arguments.clear();
this->localFunction = false;
this->nextFunction = nullptr;
this->prevFunction = nullptr;
this->returnVals.clear();
this->setIsScript(true);
boost::filesystem::path pathFunction(this->getFilename());
this->setName(pathFunction.stem().generic_string());
}
this->setWithWatcher(withWatcher);
} catch (const Exception&) {
Error(_W("a valid function definition expected.") + std::wstring(L"\n")
+ this->getFilename());
}
this->ptrAstCodeAsVector = std::move(ptAstCode);
AbstractSyntaxTree::clearReferences();
if (!this->getIsScript()) {
stringVector functionNamesInFile;
MacroFunctionDef* cp = this->nextFunction;
functionNamesInFile.push_back(this->getName());
while (cp != nullptr) {
functionNamesInFile.push_back(cp->getName());
cp = cp->nextFunction;
}
auto it = std::unique(functionNamesInFile.begin(), functionNamesInFile.end());
bool isUnique = (it == functionNamesInFile.end());
if (!isUnique) {
std::string msg
= str(boost::format(_("Function '%s' has already been declared within this scope."))
% it->c_str());
Error(msg);
}
boost::filesystem::path pathFunction(this->getFilename());
const std::string functionNameFromFile = pathFunction.stem().generic_string();
if (this->getName() != functionNameFromFile) {
if (std::find(
functionNamesInFile.begin(), functionNamesInFile.end(), functionNameFromFile)
!= functionNamesInFile.end()) {
this->setName(functionNameFromFile);
}
}
if (this->getName() != functionNameFromFile) {
std::string name = this->getName();
std::string msg
= str(boost::format(_("Filename and function name are not same (%s vs %s).")) % name
% functionNameFromFile);
Error(msg);
}
}
return true;
}
//=============================================================================
} // namespace Nelson
//=============================================================================