Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code

Side by Side Diff: compiled/bindings.h

Issue 29333474: Issue 4125 - [emscripten] Convert filter classes to C++ (Closed)
Patch Set: Addressed comments, made String class slightly more sane, slightly cleaned up bindings.cpp Created Feb. 2, 2016, 5:48 p.m.
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments.
Jump to:
View unified diff | Download patch
« no previous file with comments | « compiled/WhitelistFilter.cpp ('k') | compiled/bindings.cpp » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 #ifndef ADBLOCK_PLUS_TOOLS_H
2 #define ADBLOCK_PLUS_TOOLS_H
3
4 #include <cstdio>
5 #include <cstdlib>
6 #include <cstring>
7 #include <exception>
8 #include <map>
9 #include <string>
10 #include <type_traits>
11 #include <utility>
12 #include <vector>
13
14 #include <emscripten.h>
15
16 #include "String.h"
17 #include "intrusive_ptr.h"
18
19 typedef void* TYPEID;
20
21 enum class TypeCategory
22 {
23 UNKNOWN,
24 VOID,
25 INT,
26 STRING,
27 STRING_REF,
28 CLASS_PTR
29 };
30
31 template<typename T>
32 struct TypeInfo
33 {
34 static char c;
35 constexpr operator TYPEID() const
36 {
37 return &c;
38 }
39
40 constexpr operator TypeCategory() const
41 {
42 if (std::is_void<T>())
43 return TypeCategory::VOID;
44
45 if (std::is_integral<T>() || std::is_enum<T>())
46 return TypeCategory::INT;
47
48 if (std::is_same<String,T>() || std::is_same<const String,T>())
49 return TypeCategory::STRING;
50
51 if (std::is_same<String&,T>() || std::is_same<const String&,T>())
52 return TypeCategory::STRING_REF;
53
54 if (std::is_pointer<T>() && std::is_class<typename std::remove_pointer<T>::t ype>())
55 return TypeCategory::CLASS_PTR;
56
57 return TypeCategory::UNKNOWN;
58 }
59
60 TYPEID pointer_type() const
61 {
62 if (std::is_pointer<T>())
63 return TypeInfo<typename std::remove_pointer<T>::type>();
64 else
65 return nullptr;
66 }
67 };
68
69 template<typename T>
70 char TypeInfo<T>::c;
71
72 struct FunctionInfo
73 {
74 TypeCategory returnType;
75 TYPEID pointerType;
76 std::vector<TypeCategory> args;
77 bool instance_function;
78 int effectiveArgs;
79 TypeCategory effectiveReturnType;
80 char name[1024];
81
82 FunctionInfo()
83 {
84 name[0] = 0;
85 }
86
87 FunctionInfo(TypeCategory returnType, TYPEID pointerType,
88 std::initializer_list<TypeCategory> argTypes, bool instance_function,
89 void* function)
90 : returnType(returnType), pointerType(pointerType),
91 instance_function(instance_function)
92 {
93 name[0] = 0;
94 if (!*reinterpret_cast<int*>(function))
95 return;
96
97 for (auto it = argTypes.begin(); it != argTypes.end(); ++it)
98 {
99 if (*it != TypeCategory::INT && *it != TypeCategory::STRING_REF &&
100 *it != TypeCategory::CLASS_PTR)
101 {
102 throw std::runtime_error("Unexpected function argument type");
103 }
104 args.push_back(*it);
105 }
106
107 if (returnType != TypeCategory::VOID && returnType != TypeCategory::INT &&
108 returnType != TypeCategory::STRING &&
109 returnType != TypeCategory::CLASS_PTR)
110 {
111 throw std::runtime_error("Unexpected function return type");
112 }
113
114 effectiveArgs = args.size();
115 effectiveReturnType = returnType;
116 if (instance_function)
117 effectiveArgs++;
118
119 if (returnType == TypeCategory::STRING)
120 {
121 effectiveArgs++;
122 effectiveReturnType = TypeCategory::VOID;
123 }
124
125 get_function_name(function, effectiveArgs,
126 effectiveReturnType == TypeCategory::VOID);
127 }
128
129 template<typename ReturnType, typename... Args>
130 FunctionInfo(ReturnType (*function)(Args...))
131 : FunctionInfo(TypeInfo<ReturnType>(),
132 TypeInfo<ReturnType>().pointer_type(), { TypeInfo<Args>()... }, false,
133 &function)
134 {
135 }
136
137 template<typename ClassType, typename ReturnType, typename... Args>
138 FunctionInfo(ReturnType (ClassType::*function)(Args...))
139 : FunctionInfo(TypeInfo<ReturnType>(),
140 TypeInfo<ReturnType>().pointer_type(), { TypeInfo<Args>()... }, true,
141 &function)
142 {
143 }
144
145 template<typename ClassType, typename ReturnType, typename... Args>
146 FunctionInfo(ReturnType (ClassType::*function)(Args...) const)
147 : FunctionInfo(TypeInfo<ReturnType>(),
148 TypeInfo<ReturnType>().pointer_type(), { TypeInfo<Args>()... }, true,
149 &function)
150 {
151 }
152
153 bool empty() const
154 {
155 return name[0] == 0;
156 }
157
158 void get_function_name(void* ptr, int numArgs, bool voidResult)
159 {
160 // This is a hack, C++ won't let us get the mangled function name. JavaScrip t
161 // is more dynamic so we pass the pointer to our function there. With that
162 // and the function signature we can call the function - with intentionally
163 // invalid parameters so that we will cause a segmentation fault (pointers
164 // cannot be negative). Sometimes the function we are calling will also be
165 // missing from the build. The result is the same: abort() is called. By
166 // replacing abort() we get access to the call stack and search it for the
167 // name of our function.
168
169 EM_ASM_ARGS({
170 var signature = $3 ? "v" : "i";
171 var args = [];
172 for (var i = 0; i < $2; i++)
173 {
174 signature += "i";
175 args.push(-10000);
176 }
177
178 var oldPrintErr = Module.printErr;
179 var oldAbort = abort;
180 Module.printErr = function(){};
181 abort = function()
182 {
183 var stack = [];
184 for (var f = arguments.callee.caller; f; f = f.caller)
185 {
186 if (f.name)
187 {
188 if (f.name.indexOf("dynCall") == 0)
189 break;
190 else
191 stack.push(f.name);
192 }
193 }
194
195 result = stack[stack.length - 1];
196 if (result && result.indexOf("__wrapper") >= 0)
197 result = stack[stack.length - 2];
198 throw result;
199 };
200
201 try
202 {
203 Runtime.dynCall(signature, HEAP32[$1 >> 2], args);
204 }
205 catch(e)
206 {
207 Module.stringToAscii(e, $0);
208 }
209 finally
210 {
211 Module.printErr = oldPrintErr;
212 abort = oldAbort;
213 }
214 }, name, ptr, numArgs, voidResult);
215 }
216 };
217
218 class NoBaseClass
219 {
220 };
221
222 struct PropertyInfo
223 {
224 std::string name;
225 FunctionInfo getter;
226 FunctionInfo setter;
227 std::string jsValue;
228 };
229
230 struct MethodInfo
231 {
232 std::string name;
233 FunctionInfo call;
234 };
235
236 struct DifferentiatorInfo
237 {
238 FunctionInfo call;
239 std::vector<std::pair<int,std::string>> mapping;
240 };
241
242 struct ClassInfo
243 {
244 ClassInfo* baseClass;
245 std::string name;
246 std::vector<PropertyInfo> properties;
247 std::vector<MethodInfo> methods;
248 std::vector<FunctionInfo> initializers;
249 DifferentiatorInfo subclass_differentiator;
250 };
251
252 std::map<TYPEID,ClassInfo> classes;
253
254 void register_class(const char* name, TYPEID classID, TYPEID baseClassID)
255 {
256 auto it = classes.find(classID);
257 if (it != classes.end())
258 throw std::runtime_error(std::string("Duplicate definition for class ") + na me);
259
260 ClassInfo* baseClass = nullptr;
261 if (baseClassID != TypeInfo<NoBaseClass>())
262 {
263 it = classes.find(baseClassID);
264 if (it == classes.end())
265 throw std::runtime_error(std::string("Unknown base class defined for class ") + name);
266 baseClass = &(it->second);
267 }
268
269 ClassInfo classInfo;
270 classInfo.baseClass = baseClass;
271 classInfo.name = name;
272 classes[classID] = classInfo;
273 }
274
275 void register_property(TYPEID classID, const char* name,
276 const FunctionInfo& getter, const FunctionInfo& setter,
277 const char* jsValue = "")
278 {
279 auto it = classes.find(classID);
280 if (it == classes.end())
281 throw std::runtime_error(std::string("Property defined on unknown class: ") + name);
282
283 PropertyInfo propertyInfo;
284 propertyInfo.name = name;
285 propertyInfo.getter = getter;
286 propertyInfo.setter = setter;
287 propertyInfo.jsValue = jsValue;
288 it->second.properties.push_back(propertyInfo);
289 }
290
291 void register_method(TYPEID classID, const char* name,
292 const FunctionInfo& call)
293 {
294 auto it = classes.find(classID);
295 if (it == classes.end())
296 throw std::runtime_error(std::string("Method defined on unknown class: ") + name);
297
298 MethodInfo methodInfo;
299 methodInfo.name = name;
300 methodInfo.call = call;
301 it->second.methods.push_back(methodInfo);
302 }
303
304 void register_initializer(TYPEID classID, const FunctionInfo& call)
305 {
306 auto it = classes.find(classID);
307 if (it == classes.end())
308 throw std::runtime_error("Initializer defined on unknown class");
309
310 it->second.initializers.push_back(call);
311 }
312
313 void register_differentiator(TYPEID classID, const FunctionInfo& call,
314 std::vector<std::pair<int,std::string>>& mapping)
315 {
316 auto it = classes.find(classID);
317 if (it == classes.end())
318 throw std::runtime_error("Subclass differentiator defined on unknown class") ;
319
320 if (!it->second.subclass_differentiator.call.empty())
321 throw std::runtime_error("More than one subclass differentiator defined for class " + it->second.name);
322
323 DifferentiatorInfo differentiatorInfo;
324 differentiatorInfo.call = call;
325 differentiatorInfo.mapping = mapping;
326 it->second.subclass_differentiator = differentiatorInfo;
327 }
328
329 const std::string generateCall(const FunctionInfo& call,
330 std::vector<std::string>& params)
331 {
332 if (call.returnType == TypeCategory::STRING)
333 params.insert(params.begin(), "string");
334
335 std::string call_str(call.name);
336 call_str += "(";
337 for (int i = 0; i < params.size(); i++)
338 {
339 if (i > 0)
340 call_str += ", ";
341 call_str += params[i];
342 }
343 call_str += ")";
344
345 if (call.returnType == TypeCategory::VOID)
346 return " " + call_str + ";\n";
347 if (call.returnType == TypeCategory::INT)
348 return " var result = " + call_str + ";\n";
349 else if (call.returnType == TypeCategory::STRING)
350 {
351 std::string result;
352 result += " var string = createString();\n";
353 result += " " + call_str + ";\n";
354 result += " var result = getStringData(string);\n";
355 result += " Module._DestroyString(string);\n";
356 return result;
357 }
358 else if (call.returnType == TypeCategory::CLASS_PTR)
359 {
360 std::string result;
361 result += " var pointer = " + call_str + ";\n";
362 result += " Module._AddRef(pointer);";
363
364 auto it = classes.find(call.pointerType);
365 if (it == classes.end())
366 throw std::runtime_error("Function " + std::string(call.name) + " returns pointer to unknown class");
367
368 const ClassInfo& cls = it->second;
369 if (cls.subclass_differentiator.call.empty())
370 result += " var result = " + cls.name + "(pointer);\n";
371 else
372 {
373 result += " var type = " +
374 std::string(cls.subclass_differentiator.call.name) + "(pointer);\n";
375 result += " if (type in " + cls.name + "_mapping)\n";
376 result += " var result = new (exports[" + cls.name + "_mapping[type]])( pointer);\n";
377 result += " else\n";
378 result += " throw new Error('Unexpected " + cls.name + " type: ' + type );\n";
379 }
380 return result;
381 }
382 else
383 throw std::runtime_error("Unexpected return type for " + std::string(call.na me));
384 }
385
386 const std::string wrapCall(const FunctionInfo& call)
387 {
388 char buffer[20];
389 bool hasStringArgs = false;
390 std::vector<std::string> params;
391 std::string prefix = "function(";
392 for (int i = 0; i < call.args.size(); i++)
393 {
394 sprintf(buffer, "arg%i", i);
395 if (i > 0)
396 prefix += ", ";
397 prefix += buffer;
398
399
400 if (call.args[i] == TypeCategory::STRING_REF)
401 {
402 hasStringArgs = true;
403 params.push_back(std::string("createString(") + buffer + ")");
404 }
405 else
406 params.push_back(buffer);
407 }
408 prefix += ")\n{\n";
409
410 std::string suffix = "}";
411 if (call.returnType != TypeCategory::VOID)
412 suffix = " return result;\n" + suffix;
413
414 if (call.returnType == TypeCategory::STRING or hasStringArgs)
415 {
416 prefix += " var sp = Runtime.stackSave();\n";
417 suffix = " Runtime.stackRestore(sp);\n" + suffix;
418 }
419
420 if (call.instance_function)
421 params.insert(params.begin(), "this._pointer");
422
423 return prefix + generateCall(call, params) + suffix;
424 }
425
426 const std::string generatePropertyDescriptor(const PropertyInfo& property)
427 {
428 if (!property.jsValue.empty())
429 return "value: " + property.jsValue;
430
431 std::string result("get: " + wrapCall(property.getter));
432 if (!property.setter.empty())
433 result += ", set: " + wrapCall(property.setter);
434 return result;
435 }
436
437 void printHelpers()
438 {
439 printf("var sizeofString = %i\n", sizeof(String));
440
441 puts(R"(
442 function copyString(str, buffer)
443 {
444 var length = str.length;
445 for (var i = 0, pointer = (buffer >> 1); i < length; i++, pointer++)
446 HEAP16[pointer] = str.charCodeAt(i);
447 return length;
448 }
449
450 function createString(str)
451 {
452 var length = 0;
453 var buffer = 0;
454 if (str)
455 {
456 buffer = Runtime.stackAlloc(str.length * 2);
457 length = copyString(str, buffer);
458 }
459
460 var result = Module.Runtime.stackAlloc(sizeofString);
461 Module._InitString(result, buffer, length);
462 return result;
463 }
464
465 function getStringData(str)
466 {
467 var length = Module._GetStringLength(str);
468 var pointer = Module._GetStringData(str) >> 1;
469 return String.fromCharCode.apply(String, HEAP16.slice(pointer, pointer + lengt h));
470 }
471
472 function createClass(superclass)
473 {
474 var result = function(pointer)
475 {
476 this._pointer = pointer;
477 };
478 if (superclass)
479 result.prototype = Object.create(superclass.prototype);
480 result.prototype.delete = function()
481 {
482 Module._ReleaseRef(this._pointer);
483 };
484 return result;
485 })");
486 }
487
488 void printClass(ClassInfo& cls)
489 {
490 DifferentiatorInfo differentiator = cls.subclass_differentiator;
491 if (!differentiator.call.empty())
492 {
493 printf("var %s_mapping = \n", cls.name.c_str());
494 puts("{");
495 for (auto it = differentiator.mapping.begin(); it != differentiator.mapping. end(); ++it)
496 printf(" %i: '%s',\n", it->first, it->second.c_str());
497 puts("};");
498 }
499
500 printf("exports.%s = createClass(%s);\n", cls.name.c_str(),
501 (cls.baseClass ? ("exports." + cls.baseClass->name).c_str() : ""));
502
503 for (auto it = cls.properties.begin(); it != cls.properties.end(); ++it)
504 {
505 printf("Object.defineProperty(exports.%s.prototype, '%s', {%s});\n",
506 cls.name.c_str(), it->name.c_str(),
507 generatePropertyDescriptor(*it).c_str());
508 }
509
510 for (auto it = cls.methods.begin(); it != cls.methods.end(); ++it)
511 {
512 std::string obj("exports." + cls.name);
513 if (it->call.instance_function)
514 obj += ".prototype";
515 printf("%s.%s = %s;\n", obj.c_str(), it->name.c_str(),
516 wrapCall(it->call).c_str());
517 }
518
519 for (auto it = cls.initializers.begin(); it != cls.initializers.end(); ++it)
520 printf("%s()\n", it->name);
521 }
522
523 void printBindings()
524 {
525 printHelpers();
526
527 for (auto it = classes.begin(); it != classes.end(); ++it)
528 printClass(it->second);
529 }
530
531 #if defined(PRINT_BINDINGS)
532 // Bindings generation step: collect bindings information and print
533 // corresponding JS code.
534 #define EMSCRIPTEN_BINDINGS \
535 static struct BindingsInitializer {\
536 BindingsInitializer();\
537 BindingsInitializer(bool dummy)\
538 {\
539 try\
540 {\
541 BindingsInitializer();\
542 printBindings();\
543 }\
544 catch (const std::exception& e)\
545 {\
546 EM_ASM_ARGS(\
547 console.error("Error occurred generating JavaScript bindings: " +\
548 Module.AsciiToString($0)), e.what()\
549 );\
550 abort();\
551 }\
552 }\
553 } BindingsInitializer_instance(true);\
554 BindingsInitializer::BindingsInitializer()
555 #else
556 // Actual compilation step: ignore bindings information but define some
557 // exported helper functions necessary for the bindings.
558 #define EMSCRIPTEN_BINDINGS \
559 extern "C"\
560 {\
561 void EMSCRIPTEN_KEEPALIVE InitString(String* str,\
562 String::value_type* data, String::size_type len)\
563 {\
564 /* String is already allocated on stack, we merely need to call*/\
565 /* constructor.*/\
566 new (str) String(data, len);\
567 }\
568 void EMSCRIPTEN_KEEPALIVE DestroyString(String* str)\
569 {\
570 /* Stack memory will be freed automatically, we need to call*/\
571 /* destructor explicitly however.*/\
572 str->~String();\
573 }\
574 String::size_type EMSCRIPTEN_KEEPALIVE GetStringLength(\
575 const String& str)\
576 {\
577 return str.length();\
578 }\
579 const String::value_type* EMSCRIPTEN_KEEPALIVE GetStringData(\
580 const String& str)\
581 {\
582 return str.data();\
583 }\
584 void EMSCRIPTEN_KEEPALIVE AddRef(ref_counted* ptr)\
585 {\
586 ptr->AddRef();\
587 }\
588 void EMSCRIPTEN_KEEPALIVE ReleaseRef(ref_counted* ptr)\
589 {\
590 ptr->ReleaseRef();\
591 }\
592 }\
593 void BindingsInitializer_dummy()
594 #endif
595
596 template<typename ClassType, typename BaseClass = NoBaseClass,
597 typename std::enable_if<std::is_base_of<ref_counted, ClassType>::value>::typ e* = nullptr>
598 class class_
599 {
600 public:
601 class_(const char* name)
602 {
603 register_class(name, TypeInfo<ClassType>(), TypeInfo<BaseClass>());
604 }
605
606 template<typename FieldType>
607 const class_& property(const char* name,
608 FieldType (ClassType::*getter)() const,
609 void (ClassType::*setter)(FieldType) = 0) const
610 {
611 register_property(TypeInfo<ClassType>(), name, getter, setter);
612 return *this;
613 }
614
615 const class_& class_property(const char* name,
616 const char* jsValue) const
617 {
618 register_property(TypeInfo<ClassType>(), name, FunctionInfo(),
619 FunctionInfo(), jsValue);
620 return *this;
621 }
622
623 template<typename ReturnType, typename... Args>
624 const class_& function(const char* name, ReturnType (ClassType::*method)(Args. ..)) const
625 {
626 register_method(TypeInfo<ClassType>(), name, method);
627 return *this;
628 }
629
630 template<typename ReturnType, typename... Args>
631 const class_& function(const char* name, ReturnType (ClassType::*method)(Args. ..) const) const
632 {
633 register_method(TypeInfo<ClassType>(), name, method);
634 return *this;
635 }
636
637 template<typename ReturnType, typename... Args>
638 const class_& class_function(const char* name, ReturnType (*method)(Args...)) const
639 {
640 register_method(TypeInfo<ClassType>(), name, method);
641 return *this;
642 }
643
644 const class_& class_initializer(void (*function)()) const
645 {
646 register_initializer(TypeInfo<ClassType>(), function);
647 return *this;
648 }
649
650 template<typename ReturnType,
651 typename std::enable_if<std::is_convertible<ReturnType, int>::value>::type * = nullptr>
652 const class_& subclass_differentiator(ReturnType (*function)(ClassType*),
653 std::initializer_list<std::pair<ReturnType,const char*>> list) const
654 {
655 std::vector<std::pair<int,std::string>> mapping;
656 for (auto it = list.begin(); it != list.end(); ++it)
657 mapping.push_back(std::pair<int,std::string>(it->first, it->second));
658
659 register_differentiator(TypeInfo<ClassType>(), function, mapping);
660 return *this;
661 }
662 };
663
664 #endif
OLDNEW
« no previous file with comments | « compiled/WhitelistFilter.cpp ('k') | compiled/bindings.cpp » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld