@@ -50,6 +50,28 @@ jobject asJvmBuffer(uast::Buffer buf) {
50
50
return env->NewDirectByteBuffer (buf.ptr , buf.size );
51
51
}
52
52
53
+ // Checks if a given object is of Node/JNode class
54
+ bool isContext (jobject obj, JNIEnv *env) {
55
+ if (!obj) return false ;
56
+
57
+ jclass ctxCls = env->FindClass (CLS_CTX);
58
+ checkJvmException (" failed to find class " + std::string (CLS_CTX));
59
+
60
+ return env->IsInstanceOf (obj, ctxCls);
61
+ }
62
+
63
+ bool assertNotContext (jobject obj) {
64
+ JNIEnv *env = getJNIEnv ();
65
+ if (isContext (obj, env)) {
66
+ auto reCls = env->FindClass (CLS_RE);
67
+ checkJvmException (" failed to find class " + std::string (CLS_RE));
68
+
69
+ env->ThrowNew (reCls, " cannot use UAST Context as a Node" );
70
+ return false ;
71
+ }
72
+ return true ;
73
+ }
74
+
53
75
// ==========================================
54
76
// External UAST Context (managed by libuast)
55
77
// ==========================================
@@ -76,7 +98,9 @@ class ContextExt {
76
98
checkJvmException (" failed to find class " + std::string (CLS_NODE));
77
99
78
100
if (!env->IsInstanceOf (obj, cls)) {
79
- const char *err = " ContextExt.toHandle() called not on Node type" ;
101
+ auto err = std::string (" ContextExt.toHandle() called not on" )
102
+ .append (CLS_NODE)
103
+ .append (" type" );
80
104
ctx->SetError (err);
81
105
return 0 ;
82
106
}
@@ -103,7 +127,7 @@ class ContextExt {
103
127
// Encode serializes the external UAST.
104
128
// Borrows the reference.
105
129
jobject Encode (jobject node, UastFormat format) {
106
- // if (!assertNotContext(node)) return nullptr;
130
+ if (!assertNotContext (node)) return nullptr ;
107
131
108
132
uast::Buffer data = ctx->Encode (toHandle (node), format);
109
133
return asJvmBuffer (data);
@@ -358,7 +382,7 @@ class Interface : public uast::NodeCreator<Node *> {
358
382
// toJ returns a JVM object associated with a node.
359
383
// Returns a new reference.
360
384
jobject toJ (Node *node) {
361
- if (node == nullptr ) return nullptr ;
385
+ if (! node) return nullptr ;
362
386
jobject obj = getJNIEnv ()->NewGlobalRef (node->obj );
363
387
return obj;
364
388
}
@@ -420,7 +444,7 @@ class Context {
420
444
// toJ returns a JVM object associated with a node.
421
445
// Returns a new reference.
422
446
jobject toJ (Node *node) {
423
- if (node == nullptr ) return nullptr ;
447
+ if (! node) return nullptr ;
424
448
return iface->toJ (node);
425
449
}
426
450
// toNode returns a node associated with a JVM object.
@@ -452,7 +476,7 @@ class Context {
452
476
// Encode serializes UAST.
453
477
// Creates a new reference.
454
478
jobject Encode (jobject node, UastFormat format) {
455
- // if (!assertNotContext(node)) return nullptr;
479
+ if (!assertNotContext (node)) return nullptr ;
456
480
457
481
Node *n = toNode (node);
458
482
uast::Buffer data = ctx->Encode (n, format);
0 commit comments