Breakpoints condition
[scilab.git] / scilab / modules / ast / src / cpp / ast / debuggervisitor.cpp
1 /*
2  *  Scilab ( http://www.scilab.org/ ) - This file is part of Scilab
3  *  Copyright (C) 2015 - Scilab Enterprises - Antoine ELIAS
4  *
5  * Copyright (C) 2012 - 2016 - Scilab Enterprises
6  *
7  * This file is hereby licensed under the terms of the GNU GPL v2.0,
8  * pursuant to article 5.3.4 of the CeCILL v.2.1.
9  * This file was originally licensed under the terms of the CeCILL v2.1,
10  * and continues to be available under such terms.
11  * For more information, see the COPYING file which you should have received
12  * along with this program.
13  *
14  */
15
16 #include "debuggervisitor.hxx"
17 #include "debugmanager.hxx"
18 #include "printvisitor.hxx"
19 #include "execvisitor.hxx"
20 #include "threadId.hxx"
21 #include "macrofile.hxx"
22 #include "commentexp.hxx"
23 #include "UTF8.hxx"
24 #include "runner.hxx"
25
26 extern "C"
27 {
28 #include "filemanager_interface.h"
29 #include "FileExist.h"
30 }
31
32 static bool getMacroSourceFile(std::string* filename = nullptr);
33
34 namespace ast
35 {
36 void DebuggerVisitor::visit(const SeqExp  &e)
37 {
38     std::list<Exp *>::const_iterator itExp;
39
40     debugger::DebuggerManager* manager = debugger::DebuggerManager::getInstance();
41     if(manager->isAborted())
42     {
43         // abort a running execution
44         throw ast::InternalAbort();
45     }
46
47     for (const auto & exp : e.getExps())
48     {
49         if (exp->isCommentExp())
50         {
51             continue;
52         }
53
54         if (e.isBreakable())
55         {
56             exp->resetBreak();
57             exp->setBreakable();
58         }
59
60         if (e.isContinuable())
61         {
62             exp->resetContinue();
63             exp->setContinuable();
64         }
65
66         if (e.isReturnable())
67         {
68             exp->setReturnable();
69         }
70
71         //debugger check !
72         int iBreakPoint = -1;
73         if (ConfigVariable::getEnableDebug())
74         {
75             bool stopExecution = false;
76             if (manager->isStepIn())
77             {
78                 manager->resetStepIn();
79                 stopExecution = true;
80                 if(getMacroSourceFile() == false)
81                 {
82                     stopExecution = false;
83                     manager->setStepIn();
84                 }
85             }
86             else if (manager->isStepNext())
87             {
88                 manager->resetStepNext();
89                 stopExecution = true;
90                 if(getMacroSourceFile() == false)
91                 {
92                     stopExecution = false;
93                     manager->setStepOut();
94                 }
95             }
96             else
97             {
98                 const std::vector<ConfigVariable::WhereEntry>& lWhereAmI = ConfigVariable::getWhere();
99                 //set information from debugger commands
100                 if (lWhereAmI.size() != 0 && manager->getBreakPointCount() != 0)
101                 {
102                     debugger::Breakpoints& bps = manager->getAllBreakPoint();
103
104                     int i = -1;
105                     for (const auto & bp : bps)
106                     {
107                         ++i;
108                         if (bp->isEnable() == false)
109                         {
110                             continue;
111                         }
112
113                         // look for a breakpoint on this line and update breakpoint information when possible
114                         int iLine = exp->getLocation().first_line - ConfigVariable::getMacroFirstLines();
115                         if (bp->hasMacro())
116                         {
117                             char* functionName = wide_string_to_UTF8(lWhereAmI.back().call->getName().data());
118                             if (bp->getFunctioName().compare(functionName) == 0)
119                             {
120                                 if (bp->getMacroLine() == 0)
121                                 {
122                                     //first pass in macro.
123                                     //update first line with real value
124                                     bp->setMacroLine(iLine);
125                                 }
126
127                                 stopExecution = bp->getMacroLine() == iLine;
128                             }
129
130                             FREE(functionName);
131                         }
132                         else if (bp->hasFile())
133                         {
134                             if (bp->getFileLine() == exp->getLocation().first_line)
135                             {
136                                 std::string pFileName;
137                                 bool hasSource = getMacroSourceFile(&pFileName);
138                                 if (hasSource && bp->getFileName() == pFileName)
139                                 {
140                                     stopExecution = true;
141                                     // set function information
142                                     if (lWhereAmI.back().call->getFirstLine())
143                                     {
144                                         bp->setFunctionName(scilab::UTF8::toUTF8(lWhereAmI.back().call->getName()));
145                                         bp->setMacroLine(iLine);
146                                     }
147                                 }
148                             }
149                         }
150
151                         if(stopExecution == false)
152                         {
153                             // no breakpoint for this line
154                             continue;
155                         }
156
157                         // Set the begin of line if not yet done
158                         if(bp->getBeginLine() == 0)
159                         {
160                             bp->setBeginLine(exp->getLocation().first_column);
161                         }
162                         // check if this exp is at the begin of the breakpoint line
163                         else if(bp->getBeginLine() != exp->getLocation().first_column)
164                         {
165                             // stop only if we are at the line begins
166                             stopExecution = false;
167                             continue;
168                         }
169
170                         //check condition
171                         if (bp->getConditionExp() != NULL)
172                         {
173                             //do not use debuggervisitor !
174                             symbol::Context* pCtx = symbol::Context::getInstance();
175                             try
176                             {
177                                 ExecVisitor execCond;
178                                 //protect current env during condition execution
179                                 pCtx->scope_begin();
180                                 bp->getConditionExp()->accept(execCond);
181                                 types::InternalType* pIT = pCtx->getCurrentLevel(symbol::Symbol(L"ans"));
182                                 if (pIT == NULL)
183                                 {
184                                     // no result ie: assignation
185                                     char pcError[256];
186                                     sprintf(pcError, _("Wrong breakpoint condition: A result expected.\n"));
187                                     bp->setConditionError(pcError);
188                                 }
189                                 else if(pIT->isTrue() == false)
190                                 {
191                                     // bool scalar false
192                                     pCtx->scope_end();
193                                     stopExecution = false;
194                                     continue;
195                                 }
196
197                                 // condition is invalid or true
198                             }
199                             catch (ast::ScilabException& e)
200                             {
201                                 //not work !
202                                 //invalid breakpoint
203                                 if(ConfigVariable::isError())
204                                 {
205                                     bp->setConditionError(scilab::UTF8::toUTF8(ConfigVariable::getLastErrorMessage()));
206                                     ConfigVariable::clearLastError();
207                                     ConfigVariable::resetError();
208                                 }
209                                 else
210                                 {
211                                     bp->setConditionError(scilab::UTF8::toUTF8(e.GetErrorMessage()));
212                                 }
213                             }
214
215                             pCtx->scope_end();
216                         }
217
218                         //we have a breakpoint !
219                         //stop execution and wait signal from debugger to restart
220                         iBreakPoint = i;
221
222                         //only one breakpoint can be "call" on same exp
223                         break;
224                     }
225                 }
226             }
227
228             if(stopExecution)
229             {
230                 manager->stop(exp, iBreakPoint);
231                 if (manager->isAborted())
232                 {
233                     throw ast::InternalAbort();
234                 }
235             }
236         }
237
238         // interrupt me to execute a prioritary command
239         while (StaticRunner_isRunnerAvailable() == 1 && StaticRunner_isInterruptibleCommand() == 1)
240         {
241             StaticRunner_launch();
242         }
243
244         //copy from runvisitor::seqexp
245         try
246         {
247             //reset default values
248             setResult(NULL);
249             int iExpectedSize = getExpectedSize();
250             setExpectedSize(-1);
251             exp->accept(*this);
252             setExpectedSize(iExpectedSize);
253             types::InternalType * pIT = getResult();
254
255             // In case of exec file, set the file name in the Macro to store where it is defined.
256             int iFileID = ConfigVariable::getExecutedFileID();
257             if (iFileID && exp->isFunctionDec())
258             {
259                 types::InternalType* pITMacro = symbol::Context::getInstance()->get(exp->getAs<ast::FunctionDec>()->getSymbol());
260                 if (pITMacro)
261                 {
262                     types::Macro* pMacro = pITMacro->getAs<types::Macro>();
263                     const wchar_t* filename = getfile_filename(iFileID);
264                     // scilab.quit is not open with mopen
265                     // in this case filename is NULL because FileManager have not been filled.
266                     if (filename)
267                     {
268                         pMacro->setFileName(filename);
269                     }
270                 }
271             }
272
273             if (pIT != NULL)
274             {
275                 bool bImplicitCall = false;
276                 if (pIT->isCallable()) //to manage call without ()
277                 {
278                     types::Callable *pCall = pIT->getAs<types::Callable>();
279                     types::typed_list out;
280                     types::typed_list in;
281                     types::optional_list opt;
282
283                     try
284                     {
285                         //in this case of calling, we can return only one value
286                         int iSaveExpectedSize = getExpectedSize();
287                         setExpectedSize(1);
288
289                         pCall->invoke(in, opt, getExpectedSize(), out, *exp);
290                         setExpectedSize(iSaveExpectedSize);
291
292                         if (out.size() == 0)
293                         {
294                             setResult(NULL);
295                         }
296                         else
297                         {
298                             setResult(out[0]);
299                         }
300
301                         bImplicitCall = true;
302                     }
303                     catch (const InternalError& ie)
304                     {
305                         if (ConfigVariable::getLastErrorFunction() == L"")
306                         {
307                             ConfigVariable::setLastErrorFunction(pCall->getName());
308                             ConfigVariable::setLastErrorLine(e.getLocation().first_line);
309                         }
310
311                         throw ie;
312                     }
313                 }
314
315                 //don't output Simplevar and empty result
316                 if (getResult() != NULL && (!exp->isSimpleVar() || bImplicitCall))
317                 {
318                     //symbol::Context::getInstance()->put(symbol::Symbol(L"ans"), *execMe.getResult());
319                     types::InternalType* pITAns = getResult();
320                     symbol::Context::getInstance()->put(m_pAns, pITAns);
321                     if (exp->isVerbose() && ConfigVariable::isPrintOutput())
322                     {
323                         //TODO manage multiple returns
324                         scilabWriteW(L" ans  =\n\n");
325                         std::wostringstream ostrName;
326                         ostrName << L"ans";
327                         types::VariableToString(pITAns, ostrName.str().c_str());
328                     }
329                 }
330
331                 pIT->killMe();
332             }
333
334             if ((&e)->isBreakable() && exp->isBreak())
335             {
336                 const_cast<SeqExp *>(&e)->setBreak();
337                 exp->resetBreak();
338                 break;
339             }
340
341             if ((&e)->isContinuable() && exp->isContinue())
342             {
343                 const_cast<SeqExp *>(&e)->setContinue();
344                 exp->resetContinue();
345                 break;
346             }
347
348             if ((&e)->isReturnable() && exp->isReturn())
349             {
350                 const_cast<SeqExp *>(&e)->setReturn();
351                 exp->resetReturn();
352                 break;
353             }
354
355             // Stop execution at the end of the seqexp of the caller
356             // Do it at the end of the seqexp will make the debugger stop
357             // even if the caller is at the last line
358             // ie: the caller is followed by endfunction
359             if(manager->isStepOut())
360             {
361                 manager->resetStepOut();
362                 if(getMacroSourceFile() == false)
363                 {
364                     // no sources
365                     manager->setStepOut();
366                 }
367                 else
368                 {
369                     manager->stop(exp, iBreakPoint);
370                 }
371
372                 if (manager->isAborted())
373                 {
374                     throw ast::InternalAbort();
375                 }
376             }
377
378         }
379         catch (const InternalError& ie)
380         {
381             ConfigVariable::fillWhereError(ie.GetErrorLocation().first_line);
382
383             const std::vector<ConfigVariable::WhereEntry>& lWhereAmI = ConfigVariable::getWhere();
384
385             //where can be empty on last stepout, on first calling expression
386             if (lWhereAmI.size())
387             {
388                 const std::wstring* filename = lWhereAmI.back().m_file_name;
389
390                 if (filename == nullptr)
391                 {
392                     //error in a console script
393                     std::wstring functionName = lWhereAmI.back().call->getName();
394                     manager->errorInScript(functionName, exp);
395                 }
396                 else
397                 {
398                     manager->errorInFile(*filename, exp);
399                 }
400
401                 // Debugger just restart after been stopped on an error.
402                 if (manager->isAborted())
403                 {
404                     throw ast::InternalAbort();
405                 }
406             }
407
408             throw ie;
409         }
410
411         // If something other than NULL is given to setResult, then that would imply
412         // to make a cleanup in visit(ForExp) for example (e.getBody().accept(*this);)
413         setResult(NULL);
414
415     }
416
417     if (e.getParent() == NULL && e.getExecFrom() == SeqExp::SCRIPT && (manager->isStepNext() || manager->isStepIn()))
418     {
419         const std::vector<ConfigVariable::WhereEntry>& lWhereAmI = ConfigVariable::getWhere();
420         if (lWhereAmI.size())
421         {
422             std::wstring functionName = lWhereAmI.back().call->getName();
423             types::InternalType* pIT = symbol::Context::getInstance()->get(symbol::Symbol(functionName));
424             if (pIT && (pIT->isMacro() || pIT->isMacroFile()))
425             {
426                 types::Macro* m = nullptr;
427                 if (pIT->isMacroFile())
428                 {
429                     types::MacroFile* mf = pIT->getAs<types::MacroFile>();
430                     m = mf->getMacro();
431                 }
432                 else
433                 {
434                     m = pIT->getAs<types::Macro>();
435                 }
436
437                 //create a fake exp to represente end/enfunction
438
439                 //will be deleted by CommentExp
440                 std::wstring* comment = new std::wstring(L"end of function");
441                 Location loc(m->getLastLine(), m->getLastLine(), 0, 0);
442                 CommentExp fakeExp(loc, comment);
443                 manager->stop(&fakeExp, -1);
444
445                 if (manager->isAborted())
446                 {
447                     throw ast::InternalAbort();
448                 }
449
450                 //transform stepnext after endfunction as a stepout to show line marker on current statement
451                 if (manager->isStepNext())
452                 {
453                     manager->resetStepNext();
454                     manager->setStepOut();
455                 }
456                 else if (manager->isStepIn())
457                 {
458                     manager->resetStepIn();
459                     manager->setStepOut();
460                 }
461             }
462         }
463     }
464 }
465 }
466
467 // return false if a file .sci of a file .bin doesn't exists
468 // return true for others files or existing .sci
469 bool getMacroSourceFile(std::string* filename)
470 {
471     const std::vector<ConfigVariable::WhereEntry>& lWhereAmI = ConfigVariable::getWhere();
472     // "Where" can be empty at the end of script execution
473     // this function is called when the script ends after a step out
474     if(lWhereAmI.empty())
475     {
476         return false;
477     }
478
479     std::string file = scilab::UTF8::toUTF8(*lWhereAmI.back().m_file_name);
480     if (file.rfind(".bin") != std::string::npos)
481     {
482         file.replace(file.size() - 4, 4, ".sci");
483         // stop on bp only if the file exist
484         if (!FileExist(file.data()))
485         {
486             return false;
487         }
488     }
489
490     if(filename != nullptr)
491     {
492         filename->assign(file);
493     }
494
495     return true;
496 }