polserver/pol-core/bscript/executor.h

624 lines
19 KiB
C
Raw Permalink Normal View History

/** @file
*
* @par History
* - 2009/09/05 Turley: Added struct .? and .- as shortcut for .exists() and .erase()
*/
2016-02-11 22:54:43 +01:00
#ifndef __EXECUTOR_H
#define __EXECUTOR_H
#include <pol_global_config.h>
2016-02-11 22:54:43 +01:00
#include "bscript/bobject.h"
#include "bscript/exectype.h"
2016-02-11 22:54:43 +01:00
#include <exception>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <string>
#include <utility>
#include <vector>
2016-02-11 22:54:43 +01:00
#include "bscript/bapplicobj.h"
#include "bscript/bobject.h"
#include "bscript/eprog.h"
#include "bscript/executortype.h"
#include "clib/refptr.h"
#include "clib/spinlock.h"
#ifdef ESCRIPT_PROFILE
#include "clib/timer.h"
#include <map>
#endif
2016-02-11 22:54:43 +01:00
namespace Pol
{
namespace Core
{
class UOExecutor;
void list_script( UOExecutor* uoexec );
} // namespace Core
namespace Bscript
{
class BContinuation;
class BFunctionRef;
class Executor;
class ExecutorModule;
class ModuleFunction;
class String;
2018-01-01 21:49:30 +01:00
class Token;
2016-02-11 22:54:43 +01:00
Introduce DAP Debugger (#608) * Add cppdap debugger library and simple server (#508) * Add cppdap library * Add cppdap server * fixup cmake scripts for windows * Enable caching of cppdap on GitHub actions * Fix CMake for cppdap target * Wait 1s for session close before thread ends * Address review comments - Remove unnecessary use of wait_for - Fix wait_for method * Do not use SocketClientThread for cppdap clients * Address review comments - Cleanup object ownership * Add authorization and event handling (#510) * Add authorization and event handling [WIP] * Use std::weak_ptr; Only allow one debugger conn * Only attach debugger if dbg file exists * Cleanup weak_ptr; Fix listeners; Add handler stubs * Address review comments - PolLock on uoexec and weakptr access - Use make_shared when creating client thread * Add ExecutorDebugListener on_destroy callback * Use cppdap sockets instead of clib sockets * Update cppdap repository to 2703cf4 * Implement server address binding * Update cppdap repository to eeca5ce * Fix warnings * Use weak_from_this * Fix stalled executors on disconnect * Fix stalled executors on re-attach * Clear uoexec weakptr on all debugger detaches * Move server to gamestate * move DapDebugServer into Network namespace * move DapDebugServer into GameState for storage * Move DapDebugServer into NetworkManager * Fix missing memory include * Add more events (#513) * Add more events * Implement dbg_step_out * Fix breakpoint clearing * Add even more events (#515) * add launch request * Add custom `processes` command * fixup loop * Refactoring to move handlers to member functions * Add VariablesRequest and ScopesRequest * use std::varaint for Handles * add pollocks * refactor Handles to new file * move custom messages to proto.h * move clientthread * some formatting / cleanup * Add missing PolLock * move dap variables creation to Handles * appobj members * rename ClientThread to DebugClientThread * rename LaunchRequest args to arg * Fix compiler error on size_t * Add support for EvaluateRequest and SetVariableRequest (#519) * Update grammar for evaluateUnit * Cleanup various compiler code * Add support for EvaluateRequest Only supports values, variables, element access, member access * Add report clearing to reinitialize state * Add support for SetVariableRequest * Fix CI build errors * Move ExpressionEvaluator to Bscript * Fix formatting * Fix include * Refactor global and frame variable references * Encapsulate Executor debugging environment; Fix step over (#524) * Fix step over * Some cleanup of executor - Remove unused debug states - Rename members for consistency * move debugging environment to new class * Move instruction inspection to class * Cleanup slashes on Windows; Add Executor state to processes response (#527) * Fix backspaces in script names on Windows * Fix compilation warnings with data loss * Use boost::icontains for string comparison * Add Executor state to processes response * Updates for libfmt * Fix tests; Fix cppdap build for Mac universal binary (#607) * fix tests * fix cppdap build for mac universal binary * Update cppdap to 2a4c7cf * Add tests; Modify launch behavior to not stop at entry (redo) (#609) * Remove unused setExceptionBreakpoints handler * Add debugger tests * Launching a script should not set attaching state * Add launch tests * Do not check for connection in debugger tests * Rename `program` to `script` in protocol structs * Fix launch stopAtEntry; quote string var values * Fix compilation error on Windows * Add configfiles doc entry * Various fixes for finishing touches; Add core-changes (#610) * switch cmake projects * simple docs * cmake move make_directory * Fix launch request with relative, absolute, package paths * make relative paths as absolute in source request * Add true, false, uninit to ExpressionEvaluator * Re-add setExceptionBreakpoints to avoid unhandled message errors * Better debug thread logging with instance numbers * launched scripts should terminate on disconnect (according to DAP spec) * Properly handle exited event in client thread * Add core-changes * Address Discord comments - Mention vscode-escript in core-changes - Re-add "cppdap already built" in cmake * change cmake escriptgrammarlib visibility to public
2024-01-28 15:49:55 +07:00
class ExecutorDebugListener
{
public:
virtual void on_halt() {};
virtual void on_destroy() {};
virtual void on_print( const std::string& /*str*/ ) {};
Introduce DAP Debugger (#608) * Add cppdap debugger library and simple server (#508) * Add cppdap library * Add cppdap server * fixup cmake scripts for windows * Enable caching of cppdap on GitHub actions * Fix CMake for cppdap target * Wait 1s for session close before thread ends * Address review comments - Remove unnecessary use of wait_for - Fix wait_for method * Do not use SocketClientThread for cppdap clients * Address review comments - Cleanup object ownership * Add authorization and event handling (#510) * Add authorization and event handling [WIP] * Use std::weak_ptr; Only allow one debugger conn * Only attach debugger if dbg file exists * Cleanup weak_ptr; Fix listeners; Add handler stubs * Address review comments - PolLock on uoexec and weakptr access - Use make_shared when creating client thread * Add ExecutorDebugListener on_destroy callback * Use cppdap sockets instead of clib sockets * Update cppdap repository to 2703cf4 * Implement server address binding * Update cppdap repository to eeca5ce * Fix warnings * Use weak_from_this * Fix stalled executors on disconnect * Fix stalled executors on re-attach * Clear uoexec weakptr on all debugger detaches * Move server to gamestate * move DapDebugServer into Network namespace * move DapDebugServer into GameState for storage * Move DapDebugServer into NetworkManager * Fix missing memory include * Add more events (#513) * Add more events * Implement dbg_step_out * Fix breakpoint clearing * Add even more events (#515) * add launch request * Add custom `processes` command * fixup loop * Refactoring to move handlers to member functions * Add VariablesRequest and ScopesRequest * use std::varaint for Handles * add pollocks * refactor Handles to new file * move custom messages to proto.h * move clientthread * some formatting / cleanup * Add missing PolLock * move dap variables creation to Handles * appobj members * rename ClientThread to DebugClientThread * rename LaunchRequest args to arg * Fix compiler error on size_t * Add support for EvaluateRequest and SetVariableRequest (#519) * Update grammar for evaluateUnit * Cleanup various compiler code * Add support for EvaluateRequest Only supports values, variables, element access, member access * Add report clearing to reinitialize state * Add support for SetVariableRequest * Fix CI build errors * Move ExpressionEvaluator to Bscript * Fix formatting * Fix include * Refactor global and frame variable references * Encapsulate Executor debugging environment; Fix step over (#524) * Fix step over * Some cleanup of executor - Remove unused debug states - Rename members for consistency * move debugging environment to new class * Move instruction inspection to class * Cleanup slashes on Windows; Add Executor state to processes response (#527) * Fix backspaces in script names on Windows * Fix compilation warnings with data loss * Use boost::icontains for string comparison * Add Executor state to processes response * Updates for libfmt * Fix tests; Fix cppdap build for Mac universal binary (#607) * fix tests * fix cppdap build for mac universal binary * Update cppdap to 2a4c7cf * Add tests; Modify launch behavior to not stop at entry (redo) (#609) * Remove unused setExceptionBreakpoints handler * Add debugger tests * Launching a script should not set attaching state * Add launch tests * Do not check for connection in debugger tests * Rename `program` to `script` in protocol structs * Fix launch stopAtEntry; quote string var values * Fix compilation error on Windows * Add configfiles doc entry * Various fixes for finishing touches; Add core-changes (#610) * switch cmake projects * simple docs * cmake move make_directory * Fix launch request with relative, absolute, package paths * make relative paths as absolute in source request * Add true, false, uninit to ExpressionEvaluator * Re-add setExceptionBreakpoints to avoid unhandled message errors * Better debug thread logging with instance numbers * launched scripts should terminate on disconnect (according to DAP spec) * Properly handle exited event in client thread * Add core-changes * Address Discord comments - Mention vscode-escript in core-changes - Re-add "cppdap already built" in cmake * change cmake escriptgrammarlib visibility to public
2024-01-28 15:49:55 +07:00
};
// FIXME: how to make this a nested struct in Executor?
struct ReturnContext
{
struct External
{
External( ref_ptr<EScriptProgram> program, std::vector<ExecutorModule*> modules,
std::shared_ptr<BObjectRefVec> globals )
: Program( std::move( program ) ),
Modules( std::move( modules ) ),
Globals( std::move( globals ) )
{
}
ref_ptr<EScriptProgram> Program;
std::vector<ExecutorModule*> Modules;
std::shared_ptr<BObjectRefVec> Globals;
};
unsigned PC;
unsigned ValueStackDepth;
BObjectRef Continuation = BObjectRef();
std::optional<External> ExternalContext;
};
2016-02-11 22:54:43 +01:00
struct BackupStruct
{
std::unique_ptr<BObjectRefVec> Locals;
ValueStackCont ValueStack;
unsigned PC;
};
2016-02-11 22:54:43 +01:00
enum class ExecutorType
{
Testsuite reorganization, new feature to call exported functions (#237) * restructured pol testscripts pkg based (dedicated pkgroot) runs per pkg: setup.ecl if exists all scripts starting with "test" cleanup.ecl if exists return 1 for success everything else is an error * Scripts can now be loaded and exported functions called adapted testscripts to use this feature critical script handling missing * added support for used in critical scripts * use weakptr instead of pid moved keep_alive flag to uoexecutor * Function and nethod accept now a argument list * added docs * missing docs * faster shutdown time * fixed typo * fixed weird cornercase * shorter test functions names, the length is limited, renamed loadexported test script to have a dedicated testscript * generate tiledata/multi for small boat added generate scripts for generation.. adapted testdata set * boat tests * extended scripttests scheduler will now always know about the loaded script secured scheduler api * cleanuo scripts for boat and npc * shorter function for error return fixed cleanup: npcs have gravestones, chars was one off and scripted create of a char made it permanent logged in (until next restart), which also means that it cannot be deleted * bypass windows specific ecompile.cfg logic * fix for parallel execution * on windows its called .exe .. * use target binary directly, so cmake can replace it with the actual path use absolute path to testsuite disabled temporary the copy of ecompile * configure ecompile.cfg to add absolute path * early sleepms calls can lead to endless waiting * Code coverage (#260) * play with coverage reports * fix yml * use 0 as default for gcov cmake var * fixed used cov version, hopefully fixed now cmake * demangle function names * removed debug msg * added a few polcore tests (basically just for coverage) first set executor to noncritical before blocking * added https://coveralls.io/github/polserver/polserver * added a stackable item added a few backpack insert tests do coverage build only on push events not also for PR merge builds * added storage tests.. docs need fixes, the Imps are not working at all * fixed storage test to really move items * added a house corrected static/dynamic flag created a few house tests * updated yml file to new github api * corrected coverage discord job name * always put to runlist even if not necessary * extended aos prop tests * equip/unequip aos mod * extra ci step for shard test fixtures and activated verbose shard test * use extra ci step for all build configs, sorted testscripts for execution * fixed sorting * added param to syslog to not print the context (cleaner testscript visualization) * added build targets for tests * sleep api cleanup * more aos property tests * build for coveralls also on pullrequest * readded debug state reset on schedule * updated checkout ci action * updated checkout in all ci runs
2020-12-16 18:56:10 +01:00
EXECUTOR,
POL
};
Introduce DAP Debugger (#608) * Add cppdap debugger library and simple server (#508) * Add cppdap library * Add cppdap server * fixup cmake scripts for windows * Enable caching of cppdap on GitHub actions * Fix CMake for cppdap target * Wait 1s for session close before thread ends * Address review comments - Remove unnecessary use of wait_for - Fix wait_for method * Do not use SocketClientThread for cppdap clients * Address review comments - Cleanup object ownership * Add authorization and event handling (#510) * Add authorization and event handling [WIP] * Use std::weak_ptr; Only allow one debugger conn * Only attach debugger if dbg file exists * Cleanup weak_ptr; Fix listeners; Add handler stubs * Address review comments - PolLock on uoexec and weakptr access - Use make_shared when creating client thread * Add ExecutorDebugListener on_destroy callback * Use cppdap sockets instead of clib sockets * Update cppdap repository to 2703cf4 * Implement server address binding * Update cppdap repository to eeca5ce * Fix warnings * Use weak_from_this * Fix stalled executors on disconnect * Fix stalled executors on re-attach * Clear uoexec weakptr on all debugger detaches * Move server to gamestate * move DapDebugServer into Network namespace * move DapDebugServer into GameState for storage * Move DapDebugServer into NetworkManager * Fix missing memory include * Add more events (#513) * Add more events * Implement dbg_step_out * Fix breakpoint clearing * Add even more events (#515) * add launch request * Add custom `processes` command * fixup loop * Refactoring to move handlers to member functions * Add VariablesRequest and ScopesRequest * use std::varaint for Handles * add pollocks * refactor Handles to new file * move custom messages to proto.h * move clientthread * some formatting / cleanup * Add missing PolLock * move dap variables creation to Handles * appobj members * rename ClientThread to DebugClientThread * rename LaunchRequest args to arg * Fix compiler error on size_t * Add support for EvaluateRequest and SetVariableRequest (#519) * Update grammar for evaluateUnit * Cleanup various compiler code * Add support for EvaluateRequest Only supports values, variables, element access, member access * Add report clearing to reinitialize state * Add support for SetVariableRequest * Fix CI build errors * Move ExpressionEvaluator to Bscript * Fix formatting * Fix include * Refactor global and frame variable references * Encapsulate Executor debugging environment; Fix step over (#524) * Fix step over * Some cleanup of executor - Remove unused debug states - Rename members for consistency * move debugging environment to new class * Move instruction inspection to class * Cleanup slashes on Windows; Add Executor state to processes response (#527) * Fix backspaces in script names on Windows * Fix compilation warnings with data loss * Use boost::icontains for string comparison * Add Executor state to processes response * Updates for libfmt * Fix tests; Fix cppdap build for Mac universal binary (#607) * fix tests * fix cppdap build for mac universal binary * Update cppdap to 2a4c7cf * Add tests; Modify launch behavior to not stop at entry (redo) (#609) * Remove unused setExceptionBreakpoints handler * Add debugger tests * Launching a script should not set attaching state * Add launch tests * Do not check for connection in debugger tests * Rename `program` to `script` in protocol structs * Fix launch stopAtEntry; quote string var values * Fix compilation error on Windows * Add configfiles doc entry * Various fixes for finishing touches; Add core-changes (#610) * switch cmake projects * simple docs * cmake move make_directory * Fix launch request with relative, absolute, package paths * make relative paths as absolute in source request * Add true, false, uninit to ExpressionEvaluator * Re-add setExceptionBreakpoints to avoid unhandled message errors * Better debug thread logging with instance numbers * launched scripts should terminate on disconnect (according to DAP spec) * Properly handle exited event in client thread * Add core-changes * Address Discord comments - Mention vscode-escript in core-changes - Re-add "cppdap already built" in cmake * change cmake escriptgrammarlib visibility to public
2024-01-28 15:49:55 +07:00
enum class ExecutorDebugState
{
ATTACHING,
ATTACHED,
INS_TRACE,
RUN,
BREAK_INTO,
STEP_INTO,
STEPPING_INTO,
STEP_OVER,
STEPPING_OVER,
STEP_OUT,
};
class ExecutorDebugEnvironment
{
public:
ExecutorDebugEnvironment( std::weak_ptr<ExecutorDebugListener> listener, bool set_attaching );
// Return `false` to skip the instruction from executing.
bool on_instruction( Executor& );
size_t sizeEstimate() const;
ExecutorDebugState debug_state;
std::set<unsigned> breakpoints;
std::set<unsigned> tmpbreakpoints;
struct
{
unsigned line;
size_t control;
} break_on_linechange_from;
unsigned bp_skip;
std::weak_ptr<ExecutorDebugListener> listener;
};
class Executor
{
public:
static Clib::SpinLock _executor_lock;
virtual size_t sizeEstimate() const;
2016-02-11 22:54:43 +01:00
friend void Core::list_script( Core::UOExecutor* uoexec );
int done;
void seterror( bool err );
bool error() const;
bool error_;
bool halt_;
bool run_ok_;
2016-02-11 22:54:43 +01:00
Testsuite reorganization, new feature to call exported functions (#237) * restructured pol testscripts pkg based (dedicated pkgroot) runs per pkg: setup.ecl if exists all scripts starting with "test" cleanup.ecl if exists return 1 for success everything else is an error * Scripts can now be loaded and exported functions called adapted testscripts to use this feature critical script handling missing * added support for used in critical scripts * use weakptr instead of pid moved keep_alive flag to uoexecutor * Function and nethod accept now a argument list * added docs * missing docs * faster shutdown time * fixed typo * fixed weird cornercase * shorter test functions names, the length is limited, renamed loadexported test script to have a dedicated testscript * generate tiledata/multi for small boat added generate scripts for generation.. adapted testdata set * boat tests * extended scripttests scheduler will now always know about the loaded script secured scheduler api * cleanuo scripts for boat and npc * shorter function for error return fixed cleanup: npcs have gravestones, chars was one off and scripted create of a char made it permanent logged in (until next restart), which also means that it cannot be deleted * bypass windows specific ecompile.cfg logic * fix for parallel execution * on windows its called .exe .. * use target binary directly, so cmake can replace it with the actual path use absolute path to testsuite disabled temporary the copy of ecompile * configure ecompile.cfg to add absolute path * early sleepms calls can lead to endless waiting * Code coverage (#260) * play with coverage reports * fix yml * use 0 as default for gcov cmake var * fixed used cov version, hopefully fixed now cmake * demangle function names * removed debug msg * added a few polcore tests (basically just for coverage) first set executor to noncritical before blocking * added https://coveralls.io/github/polserver/polserver * added a stackable item added a few backpack insert tests do coverage build only on push events not also for PR merge builds * added storage tests.. docs need fixes, the Imps are not working at all * fixed storage test to really move items * added a house corrected static/dynamic flag created a few house tests * updated yml file to new github api * corrected coverage discord job name * always put to runlist even if not necessary * extended aos prop tests * equip/unequip aos mod * extra ci step for shard test fixtures and activated verbose shard test * use extra ci step for all build configs, sorted testscripts for execution * fixed sorting * added param to syslog to not print the context (cleaner testscript visualization) * added build targets for tests * sleep api cleanup * more aos property tests * build for coveralls also on pullrequest * readded debug state reset on schedule * updated checkout ci action * updated checkout in all ci runs
2020-12-16 18:56:10 +01:00
virtual ExecutorType type() { return ExecutorType::EXECUTOR; }
enum DEBUG_LEVEL
{
NONE,
SOURCELINES,
INSTRUCTIONS
};
DEBUG_LEVEL debug_level;
unsigned PC; // program counter
2016-02-11 22:54:43 +01:00
bool AttachFunctionalityModules();
2016-02-11 22:54:43 +01:00
bool setProgram( EScriptProgram* prog );
2016-02-11 22:54:43 +01:00
std::shared_ptr<BObjectRefVec> Globals2;
2016-02-11 22:54:43 +01:00
std::vector<BObjectRefVec*> upperLocals2;
2016-02-11 22:54:43 +01:00
std::vector<ReturnContext> ControlStack;
2016-02-11 22:54:43 +01:00
BObjectRefVec* Locals2;
2016-02-11 22:54:43 +01:00
static UninitObject* m_SharedUninitObject;
2016-02-11 22:54:43 +01:00
ValueStackCont ValueStack;
2016-02-11 22:54:43 +01:00
static ExecInstrFunc GetInstrFunc( const Token& token );
2016-02-11 22:54:43 +01:00
/*
These must both be deleted. instr references _symbols, so it should be deleted first.
FIXME: there should be a separate object, called EProgram or something,
that owns both the instructions and the symbols. It should be ref_counted,
so a code repository can store programs that multiple Executors use.
That means debugger stuff has to come out of Instruction.
*/
unsigned nLines;
std::vector<BObjectRef> fparams;
friend class ExecutorModule;
void setFunctionResult( BObjectImp* imp );
protected:
int getParams( unsigned howMany );
void expandParams();
void cleanParams();
public:
// Creates a new continuation object to call `funcref` with arguments `args`,
// calling a core `callback` with the return value.
//
// Responsible for moving the arguments to the `ValueStack` stack,
// expanding/shrinking as needed. The executor, when seeing a `BContinuation`
// inside `ins_call_method_id`, will "translate" it to a `BFunctionRef` to
// call. The handling of `BFunctionRef`s _inside_ `ins_call_method_id`
// requires arguments to be on `ValueStack`.
//
// Since this runs inside `ins_call_method_id`, it can **only** be used in
// `<object>.<method>` calls. Extending where this is called will require
// changing implementation.
//
// Returns `BContinuation*` on success, `BError*` on failure (if provided
// funcref is not a BFunctionRef).
template <typename Callback>
Add support for regular expressions (#818) * implementation * tests * maybe fix windows compilation? * undo change of match_flag_type * switch to boost regex * move flags to BRegExp object * fix tests due to cmake 4 update * update grammar * update prettifier * move flag parsing to BRegExp ctor * add AST nodes, update instr generation and execution * copy tests but use regular expression literals * fix grammar for handling division correctly * modify return values a bit, update tests - string.match: make groups hold structs of matched, offset - string.match: add offset - string.replace: use a groups array like string.match vs individual arguments * bundle of changes - standardize error messages - add more tests for coverage - move BRegExp creation to static method: previous implementation had ctor throwing, which was no good inside executor since it didn't have a try/catch * more tests; add OT_REGEXP to basic.em * move string regex stuff to bregexp and support regex/wregex via std::visit * maybe fix compilation errors? * add unicode escape sequence handling * really maybe fix compilation error? * fix compiler warnings * refactor a bit to remove duplicate code * address discord comments - just return wstring, no need for vector<wchar_t> method * Add string.split by string and regexp * Use Max_Split instead of Limit This makes it match basic::SplitWords * add support for empty string delim in SplitWords * remove duplicate code across string.split and mf_SplitWords * Squashed commit of the following: commit b3148e069f4c4bad041b36144d312f375c028a6c Author: turleypol <turley@polserver.com> Date: Sat Sep 27 17:02:22 2025 +0200 memorylocation of input string is not allowed to changed, switched back to uniqueptr commit 5a4d1c8fcb2d8239ba0b693644dd20d9a5a167bb Author: turleypol <turley@polserver.com> Date: Sat Sep 27 10:18:01 2025 +0200 no need to use ptr for input commit 90fa0edc66034db77a43222612b4981bf09081a5 Author: turleypol <turley@polserver.com> Date: Sat Sep 27 09:56:29 2025 +0200 fixed typo commit bed4ff3ac9de88fb9e91350125339c8ab04c2da3 Author: turleypol <turley@polserver.com> Date: Sat Sep 27 09:47:36 2025 +0200 make Callback for BContinuation move only * use uninit when group isn't matched * fix multiline flag handling; add test * add docs and doc example tests * some cleanup * address review comments - allow move assignment * add core-changes
2025-11-17 18:02:45 +01:00
BObjectImp* makeContinuation( BObjectRef funcref, Callback&& callback, BObjectRefVec args = {} );
// Runs the existing continuation object with arguments `args`.
//
// Responsible for moving the arguments to the `fparams` stack. The handling
// of `BFunctionRef`s _outside_ `ins_call_method_id` requires arguments to be
// on `fparams` (as they are moved to `ValueStack` in `ins_call_method_id`).
BContinuation* withContinuation( BContinuation* continuation, BObjectRefVec args = {} );
// Runs `callback( unsigned int PC )` for every frame in the call stack.
template <typename Callback>
Add support for regular expressions (#818) * implementation * tests * maybe fix windows compilation? * undo change of match_flag_type * switch to boost regex * move flags to BRegExp object * fix tests due to cmake 4 update * update grammar * update prettifier * move flag parsing to BRegExp ctor * add AST nodes, update instr generation and execution * copy tests but use regular expression literals * fix grammar for handling division correctly * modify return values a bit, update tests - string.match: make groups hold structs of matched, offset - string.match: add offset - string.replace: use a groups array like string.match vs individual arguments * bundle of changes - standardize error messages - add more tests for coverage - move BRegExp creation to static method: previous implementation had ctor throwing, which was no good inside executor since it didn't have a try/catch * more tests; add OT_REGEXP to basic.em * move string regex stuff to bregexp and support regex/wregex via std::visit * maybe fix compilation errors? * add unicode escape sequence handling * really maybe fix compilation error? * fix compiler warnings * refactor a bit to remove duplicate code * address discord comments - just return wstring, no need for vector<wchar_t> method * Add string.split by string and regexp * Use Max_Split instead of Limit This makes it match basic::SplitWords * add support for empty string delim in SplitWords * remove duplicate code across string.split and mf_SplitWords * Squashed commit of the following: commit b3148e069f4c4bad041b36144d312f375c028a6c Author: turleypol <turley@polserver.com> Date: Sat Sep 27 17:02:22 2025 +0200 memorylocation of input string is not allowed to changed, switched back to uniqueptr commit 5a4d1c8fcb2d8239ba0b693644dd20d9a5a167bb Author: turleypol <turley@polserver.com> Date: Sat Sep 27 10:18:01 2025 +0200 no need to use ptr for input commit 90fa0edc66034db77a43222612b4981bf09081a5 Author: turleypol <turley@polserver.com> Date: Sat Sep 27 09:56:29 2025 +0200 fixed typo commit bed4ff3ac9de88fb9e91350125339c8ab04c2da3 Author: turleypol <turley@polserver.com> Date: Sat Sep 27 09:47:36 2025 +0200 make Callback for BContinuation move only * use uninit when group isn't matched * fix multiline flag handling; add test * add docs and doc example tests * some cleanup * address review comments - allow move assignment * add core-changes
2025-11-17 18:02:45 +01:00
void walkCallStack( Callback&& callback );
int makeString( unsigned param );
bool hasParams( unsigned howmany ) const { return ( fparams.size() >= howmany ); }
size_t numParams() const { return fparams.size(); }
BObjectImp* getParamImp( unsigned param );
BObjectImp* getParamImp( unsigned param, BObjectImp::BObjectType type );
BObjectImp* getParamImp2( unsigned param, BObjectImp::BObjectType type );
BObject* getParamObj( unsigned param );
const String* getStringParam( unsigned param );
const BLong* getLongParam( unsigned param );
bool getStringParam( unsigned param, const String*& pstr );
bool getUnicodeStringParam( unsigned param, const String*& pstr ); // accepts also BLong array
bool getParam( unsigned param, int& value );
bool getParam( unsigned param, int& value, int maxval );
bool getParam( unsigned param, int& value, int minval, int maxval );
bool getRealParam( unsigned param, double& value );
bool getObjArrayParam( unsigned param, ObjArray*& pobjarr );
bool getParam( unsigned param, unsigned& value );
bool getParam( unsigned param, unsigned short& value );
bool getParam( unsigned param, unsigned short& value, unsigned short maxval );
bool getParam( unsigned param, unsigned short& value, unsigned short minval,
unsigned short maxval );
bool getParam( unsigned param, short& value );
bool getParam( unsigned param, short& value, short maxval );
bool getParam( unsigned param, short& value, short minval, short maxval );
bool getParam( unsigned param, signed char& value );
bool getParam( unsigned param, bool& value );
BApplicObjBase* getApplicObjParam( unsigned param, const BApplicObjType* object_type );
const char* paramAsString( unsigned param );
double paramAsDouble( unsigned param );
int paramAsLong( unsigned param );
protected:
int makeDouble( unsigned param );
BObject* getParam( unsigned param );
BObject getValue();
BObjectRef getObjRef();
public:
int getToken( Token& token, unsigned position );
BObjectRef& LocalVar( unsigned int varnum );
BObjectRef& GlobalVar( unsigned int varnum );
int makeGlobal( const Token& token );
void popParam( const Token& token );
void popParamByRef( const Token& token );
void getArg( const Token& token );
void pushArg( BObjectImp* arg );
void pushArg( const BObjectRef& ref );
static BObjectRef addmember( BObject& left, const BObject& right );
static BObjectRef removemember( BObject& left, const BObject& right );
static BObjectRef checkmember( BObject& left, const BObject& right );
void addmember2( BObject& left, const BObject& right );
static bool builtinMethodForced( const char*& methodname );
// execmodules: modules associated with the current program. References modules owned by
// availmodules.
std::vector<ExecutorModule*> execmodules;
std::vector<ExecutorModule*> availmodules; // owns
public:
Executor();
virtual ~Executor();
Executor( const Executor& exec ) = delete;
Executor& operator=( const Executor& exec ) = delete;
void addModule( ExecutorModule* module ); // NOTE, executor deletes its modules when done
ExecutorModule* findModule( const std::string& name );
ModuleFunction* current_module_function;
// NOTE: the debugger code expects these to be virtual..
void execFunc( const Token& token );
void execInstr();
void ins_nop( const Instruction& ins );
void ins_jmpiftrue( const Instruction& ins );
void ins_jmpiffalse( const Instruction& ins );
void ins_skipiftrue_else_consume( const Instruction& ins );
void ins_globalvar( const Instruction& ins );
void ins_localvar( const Instruction& ins );
void ins_makeLocal( const Instruction& ins );
void ins_declareArray( const Instruction& ins );
void ins_bool( const Instruction& ins );
void ins_long( const Instruction& ins );
void ins_double( const Instruction& ins );
void ins_classinst( const Instruction& ins );
void ins_string( const Instruction& ins );
Add support for regular expressions (#818) * implementation * tests * maybe fix windows compilation? * undo change of match_flag_type * switch to boost regex * move flags to BRegExp object * fix tests due to cmake 4 update * update grammar * update prettifier * move flag parsing to BRegExp ctor * add AST nodes, update instr generation and execution * copy tests but use regular expression literals * fix grammar for handling division correctly * modify return values a bit, update tests - string.match: make groups hold structs of matched, offset - string.match: add offset - string.replace: use a groups array like string.match vs individual arguments * bundle of changes - standardize error messages - add more tests for coverage - move BRegExp creation to static method: previous implementation had ctor throwing, which was no good inside executor since it didn't have a try/catch * more tests; add OT_REGEXP to basic.em * move string regex stuff to bregexp and support regex/wregex via std::visit * maybe fix compilation errors? * add unicode escape sequence handling * really maybe fix compilation error? * fix compiler warnings * refactor a bit to remove duplicate code * address discord comments - just return wstring, no need for vector<wchar_t> method * Add string.split by string and regexp * Use Max_Split instead of Limit This makes it match basic::SplitWords * add support for empty string delim in SplitWords * remove duplicate code across string.split and mf_SplitWords * Squashed commit of the following: commit b3148e069f4c4bad041b36144d312f375c028a6c Author: turleypol <turley@polserver.com> Date: Sat Sep 27 17:02:22 2025 +0200 memorylocation of input string is not allowed to changed, switched back to uniqueptr commit 5a4d1c8fcb2d8239ba0b693644dd20d9a5a167bb Author: turleypol <turley@polserver.com> Date: Sat Sep 27 10:18:01 2025 +0200 no need to use ptr for input commit 90fa0edc66034db77a43222612b4981bf09081a5 Author: turleypol <turley@polserver.com> Date: Sat Sep 27 09:56:29 2025 +0200 fixed typo commit bed4ff3ac9de88fb9e91350125339c8ab04c2da3 Author: turleypol <turley@polserver.com> Date: Sat Sep 27 09:47:36 2025 +0200 make Callback for BContinuation move only * use uninit when group isn't matched * fix multiline flag handling; add test * add docs and doc example tests * some cleanup * address review comments - allow move assignment * add core-changes
2025-11-17 18:02:45 +01:00
void ins_regexp( const Instruction& ins );
void ins_error( const Instruction& ins );
void ins_struct( const Instruction& ins );
void ins_spread( const Instruction& ins );
void ins_array( const Instruction& ins );
void ins_dictionary( const Instruction& ins );
void ins_uninit( const Instruction& ins );
void ins_ident( const Instruction& ins );
void ins_unminus( const Instruction& ins );
void ins_unplusplus( const Instruction& ins );
void ins_unminusminus( const Instruction& ins );
2019-09-22 00:34:14 +02:00
void ins_unplusplus_post( const Instruction& ins );
void ins_unminusminus_post( const Instruction& ins );
void ins_logical_and( const Instruction& ins );
void ins_logical_or( const Instruction& ins );
void ins_logical_not( const Instruction& ins );
void ins_bitwise_not( const Instruction& ins );
void ins_set_member( const Instruction& ins );
void ins_set_member_consume( const Instruction& ins );
void ins_get_member( const Instruction& ins );
void ins_get_member_id( const Instruction& ins ); // test id
void ins_set_member_id( const Instruction& ins ); // test id
void ins_set_member_id_consume( const Instruction& ins ); // test id
void ins_set_member_id_consume_plusequal( const Instruction& ins ); // test id
void ins_set_member_id_consume_minusequal( const Instruction& ins ); // test id
void ins_set_member_id_consume_timesequal( const Instruction& ins ); // test id
void ins_set_member_id_consume_divideequal( const Instruction& ins ); // test id
void ins_set_member_id_consume_modulusequal( const Instruction& ins ); // test id
void ins_set_member_id_unplusplus( const Instruction& ins ); // test id
void ins_set_member_id_unminusminus( const Instruction& ins ); // test id
void ins_set_member_id_unplusplus_post( const Instruction& ins ); // test id
void ins_set_member_id_unminusminus_post( const Instruction& ins ); // test id
void ins_assign_localvar( const Instruction& ins );
void ins_assign_globalvar( const Instruction& ins );
void ins_assign_consume( const Instruction& ins );
void ins_consume( const Instruction& ins );
void ins_assign( const Instruction& ins );
void ins_array_assign( const Instruction& ins );
void ins_array_assign_consume( const Instruction& ins );
void ins_multisubscript_assign( const Instruction& ins );
void ins_multisubscript_assign_consume( const Instruction& ins );
void ins_multisubscript( const Instruction& ins );
void ins_unpack_sequence( const Instruction& ins );
void ins_unpack_indices( const Instruction& ins );
void ins_take_local( const Instruction& ins );
void ins_take_global( const Instruction& ins );
void ins_add( const Instruction& ins );
void ins_subtract( const Instruction& ins );
void ins_mult( const Instruction& ins );
void ins_div( const Instruction& ins );
void ins_modulus( const Instruction& ins );
void ins_is( const Instruction& ins );
Add support for interpolated strings ("interstrings") (#369) * Update grammar to support interpolated strings * Struct initializers, case switchs are regular strings * Initial stub for interpolated string in AST This splits the previous STRING_LITERAL terminal into a production, stringLiteral, to handle REGULAR_STRING terminal and interpolatedString production. * Change interpolated strings to expressions * Fix mode handling in grammar * Grammar fixes - Fix mode handling in lexer - Interpolated strings only have one expression * Can successfully parse, stub compile interstrings $"He {there + print("hello")}"; * Add formatting string to grammar * Fix tests, and add test stubs * Rename curleys to brace; better AST generation * initial work interstring instruction * Initial work on formatted string instruction: emit * Formatted string instruction: execution * Add simple formatted string test * Add formatted string test src * Review changes #1 - Rename `FormattedString` to `FormatExpression` - Rename overloaded `try_to_format()` to `get_formatted()` * Review changes part 2 - Rename `InterpolatedString` ast node to `InterpolateString` * Review changes part 3 - Modify `ins_interpolate_string` * Review changes part 4 - Remove unused formal parameter * Add negative tests * Spruce up positive tests * Fix braces, escape chars inside interstring * Fix, add tests for escaped char and double brace * Address differences for new lines in tests * Update Escript version * Make empty expression an error * Add documentation for interpolated strings * Quick touchup on docs
2021-03-11 22:48:16 +01:00
void ins_interpolate_string( const Instruction& ins );
void ins_format_expression( const Instruction& ins );
void ins_insert_into( const Instruction& ins );
void ins_plusequal( const Instruction& ins );
void ins_minusequal( const Instruction& ins );
void ins_timesequal( const Instruction& ins );
void ins_divideequal( const Instruction& ins );
void ins_modulusequal( const Instruction& ins );
void ins_bitshift_right( const Instruction& ins );
void ins_bitshift_left( const Instruction& ins );
void ins_bitwise_and( const Instruction& ins );
void ins_bitwise_xor( const Instruction& ins );
void ins_bitwise_or( const Instruction& ins );
void ins_equal( const Instruction& ins );
void ins_notequal( const Instruction& ins );
void ins_lessthan( const Instruction& ins );
void ins_lessequal( const Instruction& ins );
void ins_greaterthan( const Instruction& ins );
void ins_greaterequal( const Instruction& ins );
void ins_goto( const Instruction& ins );
void ins_arraysubscript( const Instruction& ins );
void ins_func( const Instruction& ins );
void ins_call_method( const Instruction& ins );
void ins_call_method_id( const Instruction& ins );
void ins_statementbegin( const Instruction& ins );
void ins_progend( const Instruction& ins );
void ins_makelocal( const Instruction& ins );
void ins_check_mro( const Instruction& ins );
void ins_jsr_userfunc( const Instruction& ins );
void ins_pop_param( const Instruction& ins );
void ins_pop_param_byref( const Instruction& ins );
void ins_get_arg( const Instruction& ins );
void ins_leave_block( const Instruction& ins );
void ins_gosub( const Instruction& ins );
void ins_return( const Instruction& ins );
void ins_exit( const Instruction& ins );
void ins_member( const Instruction& ins );
void ins_addmember( const Instruction& ins );
void ins_removemember( const Instruction& ins );
void ins_checkmember( const Instruction& ins );
void ins_dictionary_addmember( const Instruction& ins );
void ins_addmember2( const Instruction& ins );
void ins_addmember_assign( const Instruction& ins );
void ins_in( const Instruction& ins );
void ins_initforeach( const Instruction& ins );
void ins_stepforeach( const Instruction& ins );
void ins_casejmp( const Instruction& ins );
void ins_initfor( const Instruction& ins );
void ins_nextfor( const Instruction& ins );
void ins_funcref( const Instruction& ins );
Add compiler support for function expressions (#671) * initial poc of function expressions - update grammar - mock AST builder to return BBoolean(true) for a func expr - update prettifier for skeleton implementation * more skeleton work create AST class FunctionExpression mimicking boolean value * create ast UserFunction, add to workspace from functexpr * can generate instructions * reorg tests; add test for instructions * can track FunctionDepth in Variable * can get captures for funcexprs inside funcs.. tbd if this way of nesting works * Implement create-functor instruction - Move function depth from Variable to Variables - Introduce stacking of `Variables` for function expresions via `FunctionVariableScope` - Add `TOK_FUNCTOR` instruction for 'create-functor' - Handle emitting a `FunctionExpression` AST node - Update `emit.declare_variable` and `emit.access_variable` to account for function captures - Remove `in_function` from instruction generator, as it is tracked via `UserFunction` stack - Update tests * Address Discord comments - Swap pop param order * Bubble up captured variables through nested functions * Improve testing infrastructure; add some test cases * Fix compilation error * prepend captures to function parameters in funcref mth_call * update tests * move from function{} to @{} * implementation fix * some more tests * update docs * Some cleanup * fix CI annotation warning - 'argument': conversion from 'size_t' to 'VariableIndex', possible loss of data * Address review comments - Add `passert_always` - Use better example in docs * Some cleanup - Remove unused functions
2024-07-29 22:30:52 +02:00
void ins_functor( const Instruction& ins );
void ins_logical_jump( const Instruction& ins );
void ins_logical_convert( const Instruction& ins );
static int ins_casejmp_findlong( const Token& token, BLong* blong );
static int ins_casejmp_findbool( const Token& token, BBoolean* bbool );
static int ins_casejmp_findstring( const Token& token, String* bstringimp );
static int ins_casejmp_finduninit( const Token& token );
static int ins_casejmp_finddefault( const Token& token );
bool running_to_completion() const;
void set_running_to_completion( bool to_completion );
bool runnable() const;
void calcrunnable();
bool halt() const;
void sethalt( bool halt );
// Takes ownership of `continuation`. If `funcref` is present, checks if jump
// is "external" (ie. current program is different than funcref's), and if so,
// sets up members (Globals2, nLines, prog_, execmodules) accordingly.
void jump( int target_PC, BContinuation* continuation, BFunctionRef* funcref );
// Returns the current execution stack of this executor. The returned object
// is either a string containing a line for each stack frame, or an array of
// objects representing each stack frame.
//
// Will load the debug symbols for the current program. If debug symbols are
// not available, only program counter information will be available, and
// filename+line+function name will be empty.
BObjectImp* get_stacktrace( bool as_array );
Introduce DAP Debugger (#608) * Add cppdap debugger library and simple server (#508) * Add cppdap library * Add cppdap server * fixup cmake scripts for windows * Enable caching of cppdap on GitHub actions * Fix CMake for cppdap target * Wait 1s for session close before thread ends * Address review comments - Remove unnecessary use of wait_for - Fix wait_for method * Do not use SocketClientThread for cppdap clients * Address review comments - Cleanup object ownership * Add authorization and event handling (#510) * Add authorization and event handling [WIP] * Use std::weak_ptr; Only allow one debugger conn * Only attach debugger if dbg file exists * Cleanup weak_ptr; Fix listeners; Add handler stubs * Address review comments - PolLock on uoexec and weakptr access - Use make_shared when creating client thread * Add ExecutorDebugListener on_destroy callback * Use cppdap sockets instead of clib sockets * Update cppdap repository to 2703cf4 * Implement server address binding * Update cppdap repository to eeca5ce * Fix warnings * Use weak_from_this * Fix stalled executors on disconnect * Fix stalled executors on re-attach * Clear uoexec weakptr on all debugger detaches * Move server to gamestate * move DapDebugServer into Network namespace * move DapDebugServer into GameState for storage * Move DapDebugServer into NetworkManager * Fix missing memory include * Add more events (#513) * Add more events * Implement dbg_step_out * Fix breakpoint clearing * Add even more events (#515) * add launch request * Add custom `processes` command * fixup loop * Refactoring to move handlers to member functions * Add VariablesRequest and ScopesRequest * use std::varaint for Handles * add pollocks * refactor Handles to new file * move custom messages to proto.h * move clientthread * some formatting / cleanup * Add missing PolLock * move dap variables creation to Handles * appobj members * rename ClientThread to DebugClientThread * rename LaunchRequest args to arg * Fix compiler error on size_t * Add support for EvaluateRequest and SetVariableRequest (#519) * Update grammar for evaluateUnit * Cleanup various compiler code * Add support for EvaluateRequest Only supports values, variables, element access, member access * Add report clearing to reinitialize state * Add support for SetVariableRequest * Fix CI build errors * Move ExpressionEvaluator to Bscript * Fix formatting * Fix include * Refactor global and frame variable references * Encapsulate Executor debugging environment; Fix step over (#524) * Fix step over * Some cleanup of executor - Remove unused debug states - Rename members for consistency * move debugging environment to new class * Move instruction inspection to class * Cleanup slashes on Windows; Add Executor state to processes response (#527) * Fix backspaces in script names on Windows * Fix compilation warnings with data loss * Use boost::icontains for string comparison * Add Executor state to processes response * Updates for libfmt * Fix tests; Fix cppdap build for Mac universal binary (#607) * fix tests * fix cppdap build for mac universal binary * Update cppdap to 2a4c7cf * Add tests; Modify launch behavior to not stop at entry (redo) (#609) * Remove unused setExceptionBreakpoints handler * Add debugger tests * Launching a script should not set attaching state * Add launch tests * Do not check for connection in debugger tests * Rename `program` to `script` in protocol structs * Fix launch stopAtEntry; quote string var values * Fix compilation error on Windows * Add configfiles doc entry * Various fixes for finishing touches; Add core-changes (#610) * switch cmake projects * simple docs * cmake move make_directory * Fix launch request with relative, absolute, package paths * make relative paths as absolute in source request * Add true, false, uninit to ExpressionEvaluator * Re-add setExceptionBreakpoints to avoid unhandled message errors * Better debug thread logging with instance numbers * launched scripts should terminate on disconnect (according to DAP spec) * Properly handle exited event in client thread * Add core-changes * Address Discord comments - Mention vscode-escript in core-changes - Re-add "cppdap already built" in cmake * change cmake escriptgrammarlib visibility to public
2024-01-28 15:49:55 +07:00
bool attach_debugger( std::weak_ptr<ExecutorDebugListener> listener = {},
bool set_attaching = true );
void detach_debugger();
void print_to_debugger( const std::string& message );
std::string dbg_get_instruction( size_t atPC ) const;
void dbg_get_instruction( size_t atPC, std::string& os ) const;
void dbg_ins_trace();
void dbg_step_into();
void dbg_step_over();
Introduce DAP Debugger (#608) * Add cppdap debugger library and simple server (#508) * Add cppdap library * Add cppdap server * fixup cmake scripts for windows * Enable caching of cppdap on GitHub actions * Fix CMake for cppdap target * Wait 1s for session close before thread ends * Address review comments - Remove unnecessary use of wait_for - Fix wait_for method * Do not use SocketClientThread for cppdap clients * Address review comments - Cleanup object ownership * Add authorization and event handling (#510) * Add authorization and event handling [WIP] * Use std::weak_ptr; Only allow one debugger conn * Only attach debugger if dbg file exists * Cleanup weak_ptr; Fix listeners; Add handler stubs * Address review comments - PolLock on uoexec and weakptr access - Use make_shared when creating client thread * Add ExecutorDebugListener on_destroy callback * Use cppdap sockets instead of clib sockets * Update cppdap repository to 2703cf4 * Implement server address binding * Update cppdap repository to eeca5ce * Fix warnings * Use weak_from_this * Fix stalled executors on disconnect * Fix stalled executors on re-attach * Clear uoexec weakptr on all debugger detaches * Move server to gamestate * move DapDebugServer into Network namespace * move DapDebugServer into GameState for storage * Move DapDebugServer into NetworkManager * Fix missing memory include * Add more events (#513) * Add more events * Implement dbg_step_out * Fix breakpoint clearing * Add even more events (#515) * add launch request * Add custom `processes` command * fixup loop * Refactoring to move handlers to member functions * Add VariablesRequest and ScopesRequest * use std::varaint for Handles * add pollocks * refactor Handles to new file * move custom messages to proto.h * move clientthread * some formatting / cleanup * Add missing PolLock * move dap variables creation to Handles * appobj members * rename ClientThread to DebugClientThread * rename LaunchRequest args to arg * Fix compiler error on size_t * Add support for EvaluateRequest and SetVariableRequest (#519) * Update grammar for evaluateUnit * Cleanup various compiler code * Add support for EvaluateRequest Only supports values, variables, element access, member access * Add report clearing to reinitialize state * Add support for SetVariableRequest * Fix CI build errors * Move ExpressionEvaluator to Bscript * Fix formatting * Fix include * Refactor global and frame variable references * Encapsulate Executor debugging environment; Fix step over (#524) * Fix step over * Some cleanup of executor - Remove unused debug states - Rename members for consistency * move debugging environment to new class * Move instruction inspection to class * Cleanup slashes on Windows; Add Executor state to processes response (#527) * Fix backspaces in script names on Windows * Fix compilation warnings with data loss * Use boost::icontains for string comparison * Add Executor state to processes response * Updates for libfmt * Fix tests; Fix cppdap build for Mac universal binary (#607) * fix tests * fix cppdap build for mac universal binary * Update cppdap to 2a4c7cf * Add tests; Modify launch behavior to not stop at entry (redo) (#609) * Remove unused setExceptionBreakpoints handler * Add debugger tests * Launching a script should not set attaching state * Add launch tests * Do not check for connection in debugger tests * Rename `program` to `script` in protocol structs * Fix launch stopAtEntry; quote string var values * Fix compilation error on Windows * Add configfiles doc entry * Various fixes for finishing touches; Add core-changes (#610) * switch cmake projects * simple docs * cmake move make_directory * Fix launch request with relative, absolute, package paths * make relative paths as absolute in source request * Add true, false, uninit to ExpressionEvaluator * Re-add setExceptionBreakpoints to avoid unhandled message errors * Better debug thread logging with instance numbers * launched scripts should terminate on disconnect (according to DAP spec) * Properly handle exited event in client thread * Add core-changes * Address Discord comments - Mention vscode-escript in core-changes - Re-add "cppdap already built" in cmake * change cmake escriptgrammarlib visibility to public
2024-01-28 15:49:55 +07:00
void dbg_step_out();
void dbg_run();
void dbg_break();
void dbg_setbp( unsigned atPC );
void dbg_clrbp( unsigned atPC );
Introduce DAP Debugger (#608) * Add cppdap debugger library and simple server (#508) * Add cppdap library * Add cppdap server * fixup cmake scripts for windows * Enable caching of cppdap on GitHub actions * Fix CMake for cppdap target * Wait 1s for session close before thread ends * Address review comments - Remove unnecessary use of wait_for - Fix wait_for method * Do not use SocketClientThread for cppdap clients * Address review comments - Cleanup object ownership * Add authorization and event handling (#510) * Add authorization and event handling [WIP] * Use std::weak_ptr; Only allow one debugger conn * Only attach debugger if dbg file exists * Cleanup weak_ptr; Fix listeners; Add handler stubs * Address review comments - PolLock on uoexec and weakptr access - Use make_shared when creating client thread * Add ExecutorDebugListener on_destroy callback * Use cppdap sockets instead of clib sockets * Update cppdap repository to 2703cf4 * Implement server address binding * Update cppdap repository to eeca5ce * Fix warnings * Use weak_from_this * Fix stalled executors on disconnect * Fix stalled executors on re-attach * Clear uoexec weakptr on all debugger detaches * Move server to gamestate * move DapDebugServer into Network namespace * move DapDebugServer into GameState for storage * Move DapDebugServer into NetworkManager * Fix missing memory include * Add more events (#513) * Add more events * Implement dbg_step_out * Fix breakpoint clearing * Add even more events (#515) * add launch request * Add custom `processes` command * fixup loop * Refactoring to move handlers to member functions * Add VariablesRequest and ScopesRequest * use std::varaint for Handles * add pollocks * refactor Handles to new file * move custom messages to proto.h * move clientthread * some formatting / cleanup * Add missing PolLock * move dap variables creation to Handles * appobj members * rename ClientThread to DebugClientThread * rename LaunchRequest args to arg * Fix compiler error on size_t * Add support for EvaluateRequest and SetVariableRequest (#519) * Update grammar for evaluateUnit * Cleanup various compiler code * Add support for EvaluateRequest Only supports values, variables, element access, member access * Add report clearing to reinitialize state * Add support for SetVariableRequest * Fix CI build errors * Move ExpressionEvaluator to Bscript * Fix formatting * Fix include * Refactor global and frame variable references * Encapsulate Executor debugging environment; Fix step over (#524) * Fix step over * Some cleanup of executor - Remove unused debug states - Rename members for consistency * move debugging environment to new class * Move instruction inspection to class * Cleanup slashes on Windows; Add Executor state to processes response (#527) * Fix backspaces in script names on Windows * Fix compilation warnings with data loss * Use boost::icontains for string comparison * Add Executor state to processes response * Updates for libfmt * Fix tests; Fix cppdap build for Mac universal binary (#607) * fix tests * fix cppdap build for mac universal binary * Update cppdap to 2a4c7cf * Add tests; Modify launch behavior to not stop at entry (redo) (#609) * Remove unused setExceptionBreakpoints handler * Add debugger tests * Launching a script should not set attaching state * Add launch tests * Do not check for connection in debugger tests * Rename `program` to `script` in protocol structs * Fix launch stopAtEntry; quote string var values * Fix compilation error on Windows * Add configfiles doc entry * Various fixes for finishing touches; Add core-changes (#610) * switch cmake projects * simple docs * cmake move make_directory * Fix launch request with relative, absolute, package paths * make relative paths as absolute in source request * Add true, false, uninit to ExpressionEvaluator * Re-add setExceptionBreakpoints to avoid unhandled message errors * Better debug thread logging with instance numbers * launched scripts should terminate on disconnect (according to DAP spec) * Properly handle exited event in client thread * Add core-changes * Address Discord comments - Mention vscode-escript in core-changes - Re-add "cppdap already built" in cmake * change cmake escriptgrammarlib visibility to public
2024-01-28 15:49:55 +07:00
void dbg_clrbps( const std::set<unsigned>& PCs );
void dbg_clrallbp();
bool exec();
void reinitExec();
void initForFnCall( unsigned in_PC );
void show_context( unsigned atPC );
void show_context( std::string& os, unsigned atPC );
void call_function_reference( BFunctionRef* funcref, BContinuation* continuation,
const Instruction& jmp );
int getDebugLevel() { return debug_level; }
void setDebugLevel( DEBUG_LEVEL level ) { debug_level = level; }
void setViewMode( bool vm ) { viewmode_ = vm; }
const std::string& scriptname() const;
bool empty_scriptname();
const EScriptProgram* prog() const;
virtual unsigned int pid() const { return 0; };
private:
ref_ptr<EScriptProgram> prog_;
bool prog_ok_;
bool viewmode_;
bool runs_to_completion_;
Introduce DAP Debugger (#608) * Add cppdap debugger library and simple server (#508) * Add cppdap library * Add cppdap server * fixup cmake scripts for windows * Enable caching of cppdap on GitHub actions * Fix CMake for cppdap target * Wait 1s for session close before thread ends * Address review comments - Remove unnecessary use of wait_for - Fix wait_for method * Do not use SocketClientThread for cppdap clients * Address review comments - Cleanup object ownership * Add authorization and event handling (#510) * Add authorization and event handling [WIP] * Use std::weak_ptr; Only allow one debugger conn * Only attach debugger if dbg file exists * Cleanup weak_ptr; Fix listeners; Add handler stubs * Address review comments - PolLock on uoexec and weakptr access - Use make_shared when creating client thread * Add ExecutorDebugListener on_destroy callback * Use cppdap sockets instead of clib sockets * Update cppdap repository to 2703cf4 * Implement server address binding * Update cppdap repository to eeca5ce * Fix warnings * Use weak_from_this * Fix stalled executors on disconnect * Fix stalled executors on re-attach * Clear uoexec weakptr on all debugger detaches * Move server to gamestate * move DapDebugServer into Network namespace * move DapDebugServer into GameState for storage * Move DapDebugServer into NetworkManager * Fix missing memory include * Add more events (#513) * Add more events * Implement dbg_step_out * Fix breakpoint clearing * Add even more events (#515) * add launch request * Add custom `processes` command * fixup loop * Refactoring to move handlers to member functions * Add VariablesRequest and ScopesRequest * use std::varaint for Handles * add pollocks * refactor Handles to new file * move custom messages to proto.h * move clientthread * some formatting / cleanup * Add missing PolLock * move dap variables creation to Handles * appobj members * rename ClientThread to DebugClientThread * rename LaunchRequest args to arg * Fix compiler error on size_t * Add support for EvaluateRequest and SetVariableRequest (#519) * Update grammar for evaluateUnit * Cleanup various compiler code * Add support for EvaluateRequest Only supports values, variables, element access, member access * Add report clearing to reinitialize state * Add support for SetVariableRequest * Fix CI build errors * Move ExpressionEvaluator to Bscript * Fix formatting * Fix include * Refactor global and frame variable references * Encapsulate Executor debugging environment; Fix step over (#524) * Fix step over * Some cleanup of executor - Remove unused debug states - Rename members for consistency * move debugging environment to new class * Move instruction inspection to class * Cleanup slashes on Windows; Add Executor state to processes response (#527) * Fix backspaces in script names on Windows * Fix compilation warnings with data loss * Use boost::icontains for string comparison * Add Executor state to processes response * Updates for libfmt * Fix tests; Fix cppdap build for Mac universal binary (#607) * fix tests * fix cppdap build for mac universal binary * Update cppdap to 2a4c7cf * Add tests; Modify launch behavior to not stop at entry (redo) (#609) * Remove unused setExceptionBreakpoints handler * Add debugger tests * Launching a script should not set attaching state * Add launch tests * Do not check for connection in debugger tests * Rename `program` to `script` in protocol structs * Fix launch stopAtEntry; quote string var values * Fix compilation error on Windows * Add configfiles doc entry * Various fixes for finishing touches; Add core-changes (#610) * switch cmake projects * simple docs * cmake move make_directory * Fix launch request with relative, absolute, package paths * make relative paths as absolute in source request * Add true, false, uninit to ExpressionEvaluator * Re-add setExceptionBreakpoints to avoid unhandled message errors * Better debug thread logging with instance numbers * launched scripts should terminate on disconnect (according to DAP spec) * Properly handle exited event in client thread * Add core-changes * Address Discord comments - Mention vscode-escript in core-changes - Re-add "cppdap already built" in cmake * change cmake escriptgrammarlib visibility to public
2024-01-28 15:49:55 +07:00
std::unique_ptr<ExecutorDebugEnvironment> dbg_env_;
BObjectImp* func_result_;
void printStack( const std::string& message );
protected:
friend class BClassInstance;
void cleanup();
struct ClassMethodKey
{
ref_ptr<EScriptProgram> prog;
unsigned index;
std::string method_name;
bool operator<( const ClassMethodKey& other ) const;
};
std::map<ClassMethodKey, BObjectRef /*function ref*/> class_methods;
};
inline const std::string& Executor::scriptname() const
{
return prog_->name;
}
inline bool Executor::empty_scriptname()
{
return prog_->name.get().empty();
}
inline const EScriptProgram* Executor::prog() const
{
return prog_.get();
}
inline bool Executor::runnable() const
{
return run_ok_;
}
inline void Executor::calcrunnable()
{
run_ok_ = !error_ && !halt_;
}
inline void Executor::seterror( bool err )
{
error_ = err;
calcrunnable();
}
inline bool Executor::error() const
{
return error_;
}
inline bool Executor::halt() const
{
return halt_;
}
inline bool Executor::running_to_completion() const
{
return runs_to_completion_;
}
inline void Executor::set_running_to_completion( bool to_completion )
{
runs_to_completion_ = to_completion;
}
#ifdef ESCRIPT_PROFILE
class EscriptProfiler
{
public:
EscriptProfiler( ExecutorModule* em, const ModuleFunction* modfunc,
const std::vector<BObjectRef>& fparams );
EscriptProfiler( const Instruction& ins, const BObjectRef& leftref,
const std::vector<BObjectRef>& fparams );
EscriptProfiler( const Instruction& ins, const BObjectImp* callee, const char* method_name,
const std::vector<BObjectRef>& fparams );
~EscriptProfiler();
static std::string result();
private:
Tools::HighPerfTimer timer_{};
std::string name_{};
struct profile_instr
{
int64_t sum;
int64_t max;
int64_t min;
int64_t count;
};
static std::map<std::string, profile_instr> escript_profile_map_;
};
#define ESCRIPT_PROFILER EscriptProfiler escript_profiler
#else
#define ESCRIPT_PROFILER( ... )
#endif
} // namespace Bscript
} // namespace Pol
2016-02-11 22:54:43 +01:00
#endif