Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add class support and function wrappers #7

Merged
merged 8 commits into from
Dec 15, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -67,3 +67,9 @@ Credits

The initial work on the JerryScript library for Sming was done as part of the `U:Kit project <https://github.com/attachix/ukit>`_.


API Documentation
-----------------

.. doxygennamespace:: Jerryscript
:members:
19 changes: 11 additions & 8 deletions component.mk
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@ COMPONENT_SRCDIRS := \
$(call ListAllSubDirs,$(JERRYSCRIPT_ROOT)/jerry-core)

COMPONENT_INCDIRS := \
src/include jerryscript \
src/include \
$(JERRYSCRIPT_ROOT)/jerry-core \
$(COMPONENT_SRCDIRS)

COMPONENT_DOCFILES := jerryscript/docs/img/engines_high_level_design.png
COMPONENT_DOXYGEN_INPUT := src/include

# The size of the JerryScript engine heap. The size in kilobytes is allocated once and defined at compile time.
COMPONENT_VARS := JERRY_GLOBAL_HEAP_SIZE
Expand All @@ -29,9 +30,6 @@ JERRY_COMPILER_FLAGS := \
JERRY_BUILTINS=0 \
JERRY_ESNEXT=0 \
JERRY_UNICODE_CASE_CONVERSION=0
# Just for library
COMPONENT_CFLAGS += \
-DJERRY_NUMBER_TYPE_FLOAT64=0
else
JERRY_PROFILE := es.next
endif
Expand All @@ -44,9 +42,15 @@ COMPONENT_CFLAGS += \
-DJERRY_LCACHE=0 \
-DJERRY_PARSER=0 \
-DJERRY_SNAPSHOT_EXEC=1 \
-DJERRY_NDEBUG \
$(addprefix -D,$(JERRY_COMPILER_FLAGS))

ifndef SMING_RELEASE
COMPONENT_CFLAGS += \
-DJERRY_NDEBUG \
-DJERRY_LOGGING=1 \
-DJERRY_MEM_STATS=1
endif

# Build version of tool compatible with library
DEBUG_VARS += JERRY_SNAPSHOT_TOOL
JERRY_BUILD_DIR := $(COMPONENT_PATH)/jerryscript/out/$(call CalculateVariantHash,JERRY_COMPILER_FLAGS)
Expand All @@ -56,9 +60,8 @@ ifeq ($(UNAME),Windows)
JERRY_CMAKE_PARAMS := \
--cmake-param "-GMSYS Makefiles" \
--compile-flag "-I $(JERRYSCRIPT_ROOT)/../src/include" \
--compile-flag "-std=gnu11 " \
--compile-flag "-Wno-error=unused-parameter " \
--compile-flag "-D_POSIX_C_SOURCE=1 "
--compile-flag "-D_POSIX_C_SOURCE=1 -U__STRICT_ANSI__"
endif

$(JERRY_SNAPSHOT_TOOL):
Expand Down Expand Up @@ -89,7 +92,7 @@ COMPONENT_PREREQUISITES := $(APP_JS_SNAP_FILES)

$(APP_JS_SNAP_FILES): $(JERRY_SNAPSHOT_TOOL) $(addprefix $(APP_JS_SOURCE_DIR)/,$(APP_JS_SOURCE_FILES)) | $(APP_JS_SNAP_DIR)
$(Q) $(JERRY_SNAPSHOT_TOOL) generate $(APP_JS_SOURCE_DIR)/$(@F:.snap=) -o $@
$(APP_JS_SNAP_UPDATED)
$(Q) $(APP_JS_SNAP_UPDATED)

$(APP_JS_SNAP_DIR):
mkdir -p $@
Expand Down
39 changes: 39 additions & 0 deletions jerryscript.patch
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,42 @@ index 13e3fd65..32444cd6 100644

ecma_extended_object_t *ext_object_p = (ecma_extended_object_t *) object_p;

diff --git a/jerry-core/jmem/jmem-heap.c b/jerry-core/jmem/jmem-heap.c
index 152909a6..200f61d7 100644
--- a/jerry-core/jmem/jmem-heap.c
+++ b/jerry-core/jmem/jmem-heap.c
@@ -734,6 +734,7 @@ jmem_heap_get_stats (jmem_heap_stats_t *out_heap_stats_p) /**< [out] heap stats
void
jmem_heap_stats_print (void)
{
+#if 0
jmem_heap_stats_t *heap_stats = &JERRY_CONTEXT (jmem_heap_stats);

JERRY_DEBUG_MSG ("Heap stats:\n");
@@ -764,6 +765,7 @@ jmem_heap_stats_print (void)
heap_stats->peak_object_bytes,
heap_stats->property_bytes,
heap_stats->peak_property_bytes);
+#endif
} /* jmem_heap_stats_print */

/**
diff --git a/jerry-core/jrt/jrt.h b/jerry-core/jrt/jrt.h
index ffd4bde3..e119b2c8 100644
--- a/jerry-core/jrt/jrt.h
+++ b/jerry-core/jrt/jrt.h
@@ -120,10 +120,10 @@ void JERRY_ATTR_NORETURN jerry_fatal (jerry_fatal_code_t code);
* Logging
*/
#if JERRY_LOGGING
-#define JERRY_ERROR_MSG(...) jerry_port_log (JERRY_LOG_LEVEL_ERROR, __VA_ARGS__)
-#define JERRY_WARNING_MSG(...) jerry_port_log (JERRY_LOG_LEVEL_WARNING, __VA_ARGS__)
-#define JERRY_DEBUG_MSG(...) jerry_port_log (JERRY_LOG_LEVEL_DEBUG, __VA_ARGS__)
-#define JERRY_TRACE_MSG(...) jerry_port_log (JERRY_LOG_LEVEL_TRACE, __VA_ARGS__)
+#define JERRY_ERROR_MSG(fmt, ...) jerry_port_log (JERRY_LOG_LEVEL_ERROR, _F(fmt), __VA_ARGS__)
+#define JERRY_WARNING_MSG(fmt, ...) jerry_port_log (JERRY_LOG_LEVEL_WARNING, _F(fmt), __VA_ARGS__)
+#define JERRY_DEBUG_MSG(fmt, ...) jerry_port_log (JERRY_LOG_LEVEL_DEBUG, _F(fmt), __VA_ARGS__)
+#define JERRY_TRACE_MSG(fmt, ...) jerry_port_log (JERRY_LOG_LEVEL_TRACE, _F(fmt), __VA_ARGS__)
#else /* !JERRY_LOGGING */
#define JERRY_ERROR_MSG(...) \
do \
22 changes: 11 additions & 11 deletions samples/Advanced_Jsvm/app/application.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
#include <MultipartParser.h>
#include <HttpMultipartResource.h>
#include <Data/Stream/FileStream.h>
#include <JsvmTask.h>
#include <Jerryscript.h>

#ifndef WIFI_SSID
#define WIFI_SSID "PleaseEnterSSID"
Expand All @@ -11,23 +11,23 @@

namespace
{
Jsvm jsVm;
JsvmTask jsTask(jsVm);
JS::VirtualMachine vm;
JS::Task task(vm);

HttpServer webServer;

constexpr char MAIN_JS_FILE[]{"main.js.snap"};
DEFINE_FSTR(MAIN_JS_FILE, "main.js.snap");

void startJsvm()
{
// Load the snapshot file
if(!jsVm.loadFromFile(MAIN_JS_FILE)) {
debug_e("Failed executing the following script: %s", MAIN_JS_FILE);
if(!vm.loadFromFile(MAIN_JS_FILE)) {
debug_e("Failed executing the following script: %s", String(MAIN_JS_FILE).c_str());
return;
}

// Now you can initialize your script by calling a setup() JavaScript function
if(!jsVm.runFunction("setup")) {
if(!vm.runFunction("setup")) {
debug_e("Failed executing the setup function.");
}

Expand All @@ -39,7 +39,7 @@ void onIndex(HttpRequest& request, HttpResponse& response)
if(request.method == HTTP_POST) {
debug_d("Successful post request...");
}
response.sendFile("index.html");
response.sendFile(F("index.html"));
}

void onTask(HttpRequest& request, HttpResponse& response)
Expand All @@ -52,10 +52,10 @@ void onTask(HttpRequest& request, HttpResponse& response)

if(runTask == "0") {
body = F("{\"status\": \"stopped\"}");
jsTask.suspend();
task.suspend();
} else {
body = F("{\"status\": \"running\"}");
jsTask.resume();
task.resume();
}

response.headers[HTTP_HEADER_CONTENT_TYPE] = toString(MIME_JSON);
Expand Down Expand Up @@ -90,7 +90,7 @@ int onUpload(HttpServerConnection& connection, HttpRequest& request, HttpRespons
String body = F("{\"status\": \"failed\"}");
if(response.isSuccess()) {
body = F("{\"status\": \"ok\"}");
jsTask.suspend();
task.suspend();
}
response.headers[HTTP_HEADER_CONTENT_TYPE] = toString(MIME_JSON);
response.sendString(body);
Expand Down
12 changes: 6 additions & 6 deletions samples/Basic_Jsvm/app/application.cpp
Original file line number Diff line number Diff line change
@@ -1,27 +1,27 @@
#include <SmingCore.h>
#include <JsvmTask.h>
#include <Jerryscript.h>

namespace
{
Jsvm jsVm;
JsvmTask jsTask(jsVm);
JS::VirtualMachine vm;
JS::Task task(vm);

IMPORT_FSTR(main_snap, PROJECT_DIR "/out/jerryscript/main.js.snap")

void startJsvm()
{
if(!jsVm.load(main_snap)) {
if(!vm.load(main_snap)) {
debug_e("Failed to load snapshot");
return;
}

// Now you can initialize your script by calling a setup() JavaScript function
if(!jsVm.runFunction("setup")) {
if(!vm.runFunction("setup")) {
debug_e("Failed executing the setup function.");
}

// And run the loop JavaScript function in the background as a Sming task.
jsTask.resume();
task.resume();
}

} // namespace
Expand Down
92 changes: 80 additions & 12 deletions samples/Event_Jsvm/app/application.cpp
Original file line number Diff line number Diff line change
@@ -1,41 +1,109 @@
#include <SmingCore.h>
#include <Jsvm.h>
#include <vm_functions.h>
#include <Jerryscript.h>

namespace
{

Jsvm jsVm;
Timer tempTimer;
JS::VirtualMachine vm;
SimpleTimer timer;
HashMap<String, JS::Callable::List> events;

IMPORT_FSTR(main_snap, PROJECT_DIR "/out/jerryscript/main.js.snap")

namespace JS
{
using namespace Jerryscript;

/**
* @brief Function to register event listeners
* @code {.javascript}
*
* event = {
* name => "TEMP_CHANGE",
* params = {
* },
* "origin" => "The\Creator\Of\The\Event"
* };
*
Comment on lines +16 to +26
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The "origin" property sticks out a bit here. Weird value too! Purpose?

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There idea is the following: If you have two or more temperature sensors may be you would like to know which one sent the event. And the "origin" property can be used to provide that information. The value of the property is free text so it can be just temp1 or cpu/temp and extern/temp1.

* addEventListener("TEMP_CHANGE", function(event) {
* console.log("Got Event" + event.name);
* });
*
* @endcode
*
*/
Value addEventListener(const CallInfo& callInfo, Value& eventName, Callable& function)
{
if(!eventName.isString() || !function.isCallable()) {
return ArgumentError(__FUNCTION__);
}

events[eventName].add(function);
return true;
}

} // namespace JS

JS_DEFINE_FUNCTION(addEventListener, 2)

/*
* Dispatch an event to all registered listeners
*
* Event = {
* name: "eventName"
* params: {
* "property1": value1,
* "property2": value2,
* ...
* }
* }
*/
bool triggerEvent(const String& name, const JS::Object& params)
{
if(!events.contains(name)) {
debug_e("%s: Unknown event '%s'", __FUNCTION__, name.c_str());
return false;
}

// Build the event object...
JS::Object event;
event["name"] = name;
event["params"] = params;

auto realm = JS::global();
for(auto& listener : events[name]) {
listener.call(realm, event);
}

return true;
}

void startJsvm()
{
/*
* This is how we register a new function in JavaScript
* that will communicate directly with our C/C++ code.
*/
jsVm.registerFunction("addEventListener", addEventListener);
vm.registerFunction("addEventListener", addEventListener);
Comment on lines -19 to +86
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As above, this could translate into JS::global().registerFunction(...)

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's have it as suggested.


if(!jsVm.load(main_snap)) {
if(!vm.load(main_snap)) {
Comment on lines -21 to +88
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

JS::loadSnapshot(...)

Copy link
Owner

@slaff slaff Dec 15, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed.

debug_e("Failed to load snapshot");
return;
}

// Now you can initialize your script by calling the init() JavaScript function
if(!jsVm.runFunction("init")) {
if(!vm.runFunction("init")) {
Comment on lines -27 to +94
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

JS::global().runFunction(...)

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed too.

debug_e("Failed executing the init function.");
}

/*
* Here we trigger every 2 seconds an event inside the JavaScript code.
*/
tempTimer.initializeMs(2000, TimerDelegate([](){
JsEventData params;
params["temp"]="20";
timer.initializeMs<2000>([]() {
JS::Object params;
params["temp"] = 20;
triggerEvent("EVENT_TEMP", params);
})).start();
});
timer.start();
}

} // namespace
Expand Down
2 changes: 2 additions & 0 deletions samples/Event_Jsvm/component.mk
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,5 @@ APP_JS_SNAP_UPDATED := touch app/application.cpp

# We need more heap to run this sample. The default heap is 1Kilobyte, we will use 2K
JERRY_GLOBAL_HEAP_SIZE := 2

DISABLE_NETWORK := 1
45 changes: 0 additions & 45 deletions samples/Event_Jsvm/src/include/vm_functions.h

This file was deleted.

Loading