Skip to content

Implement Value.TypeOf() #104

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

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added

- Add support for `Value.TypeOf()` corresponding to JavaScript `typeof` operator.

### Changed

## [v0.33.0] - 2025-05-15
Expand Down
7 changes: 7 additions & 0 deletions errors.cc
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#include <stdlib.h>
#include <sstream>

#include "deps/include/v8-exception.h"
Expand Down Expand Up @@ -48,3 +49,9 @@ RtnError ExceptionError(TryCatch& try_catch, Isolate* iso, Local<Context> ctx) {

return rtn;
}

void ErrorRelease(RtnError err) {
free((void*)err.msg);
free((void*)err.location);
free((void*)err.stack);
}
2 changes: 2 additions & 0 deletions errors.h
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ typedef struct {
RtnError error;
} RtnValue;

void ErrorRelease(RtnError err);

#ifdef __cplusplus
}
#endif
Expand Down
42 changes: 34 additions & 8 deletions value.cc
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
#include "value.h"
#include <stdlib.h>
#include "context.h"
#include "deps/include/v8-context.h"
#include "deps/include/v8-exception.h"
#include "errors.h"
#include "isolate-macros.h"
#include "utils.h"
#include "value-macros.h"

#define ISOLATE_SCOPE_INTERNAL_CONTEXT(iso) \
Expand All @@ -11,6 +13,29 @@

using namespace v8;

RtnString StringToRtnString(v8::Isolate* iso, Local<String> val) {
RtnString res = {};
Copy link
Owner

Choose a reason for hiding this comment

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

I don't think the {} initialization does anything (the original code had {0} with no purpose there).

RtnString and RtnError should have constructors (or default initializers) to ensure values are cleared.

Copy link
Author

Choose a reason for hiding this comment

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

{} zeros the fields. But I don't know the difference between that and {0}.

However, these two types RtnString and RtnError are exposed to Go code, i.e. Go code actually looks up the field - so I don't think you can add constructors? Because then it would be a C++ type, not a C type?

You could make them "anonymous" (don't know the correct term), like m_ctx where Go code just has pointer values it can pass back to C functions - and then add functions to look up values, but that also seems somewhat cumbersome.

Copy link
Owner

Choose a reason for hiding this comment

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

As long as you don't add a vtable, it's just compile-time syntactic sugar for running a function every time a value is created.

Relying on a destructor might be dangerous, since the cgo code wouldn't run it.

Copy link
Author

Choose a reason for hiding this comment

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

I'm not sure I what you mean. But this works - but it generates warnings.

struct RtnError {
  const char* msg;
  const char* location;
  const char* stack;
#ifdef __cplusplus
  RtnError() : msg(0), location(0), stack(0) {};
#endif
};

To get "methods" on the type, I changed from typedef struct { ... } RtnError to struct RtnError { }.

This caused compilation errors, both in .h and .go files.

  • In .h files, extern RtnValue SomeFunction(...); had to be changed to extern struct RtnValue SomeFunction(...)
  • In .go files, C.RtnValue had to be changed to C.struct_RtnValue.

I could avoid those changes by adding typedef struct RtnError RtnError; though I probably shouldn't use the same identifier?

The warnings are:

./context.h:80:17: warning: 'RunScript' has C-linkage specified, but returns user-defined type 'RtnValue' which is incompatible with C [-Wreturn-type-c-linkage]

But if I remove the initializer from some function creating a RtnError, all tests are still passing, and if I then remove the constructor, it fails at runtime.

But I had the impression from your comments that there is a simpler way?

Copy link
Owner

@tommie tommie May 22, 2025

Choose a reason for hiding this comment

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

Oh, I see, this needs to compile in C mode. Of course it does. My bad.

Ok, helper function it is...

Edit The helper function was about another comment... (Does it show there's too much going on for me to keep track. ;)

Copy link
Owner

Choose a reason for hiding this comment

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

But here: still need to add back the zero into the intializer to make it do something. https://stackoverflow.com/a/10828333

res.length = val->Utf8LengthV2(iso);
res.data = (char*)(malloc(res.length));
val->WriteUtf8V2(iso, (char*)res.data, res.length);
Copy link
Owner

Choose a reason for hiding this comment

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

I suggest sticking to either C- or C++-style casts in one function. :)

Copy link
Author

Choose a reason for hiding this comment

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

I agree :)

return res;
}

RtnString ExceptionToRtnString(TryCatch& try_catch,
v8::Isolate* iso,
Local<Context> ctx) {
RtnString res = {};
res.error = ExceptionError(try_catch, iso, ctx);
return res;
}

void RtnStringRelease(RtnString rtnString) {
if (rtnString.data) {
free((void*)rtnString.data);
}
ErrorRelease(rtnString.error);
}

void ValueRelease(ValuePtr ptr) {
if (ptr == nullptr) {
return;
Expand Down Expand Up @@ -223,16 +248,11 @@ double ValueToNumber(ValuePtr ptr) {

RtnString ValueToDetailString(ValuePtr ptr) {
LOCAL_VALUE(ptr);
RtnString rtn = {0};
Local<String> str;
if (!value->ToDetailString(local_ctx).ToLocal(&str)) {
rtn.error = ExceptionError(try_catch, iso, local_ctx);
return rtn;
return ExceptionToRtnString(try_catch, iso, local_ctx);
}
String::Utf8Value ds(iso, str);
rtn.data = CopyString(ds);
rtn.length = ds.length();
return rtn;
return StringToRtnString(iso, str);
}

RtnString ValueToString(ValuePtr ptr) {
Expand Down Expand Up @@ -565,3 +585,9 @@ int ValueIsModuleNamespaceObject(ValuePtr ptr) {
LOCAL_VALUE(ptr);
return value->IsModuleNamespaceObject();
}

RtnString ValueTypeOf(ValuePtr ptr) {
LOCAL_VALUE(ptr);
Local<String> result = value->TypeOf(iso);
return StringToRtnString(iso, result);
}
10 changes: 8 additions & 2 deletions value.go
Original file line number Diff line number Diff line change
Expand Up @@ -240,8 +240,8 @@ func (v *Value) Object() *Object {
// are returned as-is, objects will return `[object Object]` and functions will
// print their definition.
func (v *Value) String() string {
s := C.ValueToString(v.ptr)
defer C.free(unsafe.Pointer(s.data))
var s C.RtnString = C.ValueToString(v.ptr)
Copy link
Owner

Choose a reason for hiding this comment

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

Normally := is preferred. Why this change?

defer C.RtnStringRelease(s)
return C.GoStringN(s.data, C.int(s.length))
}

Expand Down Expand Up @@ -614,3 +614,9 @@ func (v *Value) SharedArrayBufferGetContents() ([]byte, func(), error) {

return byte_slice, release, nil
}

func (v *Value) TypeOf() string {
var s C.RtnString = C.ValueTypeOf(v.ptr)
defer C.RtnStringRelease(s)
return C.GoStringN(s.data, C.int(s.length))
}
3 changes: 3 additions & 0 deletions value.h
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,9 @@ typedef struct {
} RtnString;

void ValueRelease(ValuePtr ptr);
void RtnStringRelease(RtnString rtnString);
extern RtnString ValueToString(ValuePtr ptr);
extern RtnString ValueTypeOf(ValuePtr ptr);
const uint32_t* ValueToArrayIndex(ValuePtr ptr);
int ValueToBoolean(ValuePtr ptr);
int32_t ValueToInt32(ValuePtr ptr);
Expand Down Expand Up @@ -163,5 +165,6 @@ extern BackingStorePtr SharedArrayBufferGetBackingStore(ValuePtr ptr);

#ifdef __cplusplus
}

#endif
#endif
28 changes: 28 additions & 0 deletions value_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -817,3 +817,31 @@ func TestValueArrayBufferContents(t *testing.T) {
t.Fatalf("Expected an error trying call SharedArrayBufferGetContents on value of incorrect type")
}
}

func TestValueTypeOf(t *testing.T) {
t.Parallel()
iso := v8.NewIsolate()
defer iso.Dispose()
ctx := v8.NewContext(iso)
defer ctx.Close()

str1, _ := v8.NewValue(iso, "String")
if got := str1.TypeOf(); got != "string" {
t.Errorf(`NewValue("String"): expected string, got %s`, got)
}

str2, _ := ctx.RunScript("'string'", "")
if got := str2.TypeOf(); got != "string" {
t.Errorf("TypeOf('string'): expected string, got %s", got)
}

num1, _ := v8.NewValue(iso, 0.01)
if got := num1.TypeOf(); got != "number" {
t.Errorf(`NewValue(0.01): expected number, got %s`, got)
}

num2, _ := ctx.RunScript("0.01", "")
if got := num2.TypeOf(); got != "number" {
t.Errorf("TypeOf(0.01): expected number, got %s", got)
}
}