Google Chromeの特にV8あたりを使ってみる
Google先生がChromeとかいうのを出したようなので、使うのはそっちのけ、というかWindowsとか無いのでJavaScript engineであるV8のソースコード引っ張ってきた。
v8.hとかをincludeする事は出来るけども、肝心のJavaScriptのinterpretというかcompileが出来ない。
http://code.google.com/apis/v8/
sconsとかが分からんので、testとかsampleが上手くコンパイル出来ない。
V8 compiles and executes JavaScript source code, handles memory allocation for objects, and garbage collects objects it no longer needs. V8's stop-the-world, generational, accurate garbage collector is one of the keys to V8's performance. You can learn about this and other performance aspects in V8 Design Elements.
とは書いてるけれども・・・。
V8を多分使って、JSをintepret
#include <stdlib.h> #include <v8.h> #include <compiler.h> #include <execution.h> #include <factory.h> #include <platform.h> #include <top.h> #include <iostream> using namespace v8::internal; using namespace std; static v8::Persistent<v8::Context> env; static void InitializeVM() { if (env.IsEmpty()) { v8::HandleScope scope; const char* extensions[] = { "v8/print", "v8/gc" }; v8::ExtensionConfiguration config(2, extensions); env = v8::Context::New(&config); } v8::HandleScope scope; env->Enter(); } static Object* GetGlobalProperty(const char* name) { Handle<String> symbol = Factory::LookupAsciiSymbol(name); return Top::context()->global()->GetProperty(*symbol); } static Handle<JSFunction> Compile(const char* source) { Handle<String> source_code(Factory::NewStringFromUtf8(CStrVector(source))); Handle<JSFunction> boilerplate = Compiler::Compile(source_code, Handle<String>(), 0, 0, NULL, NULL); return Factory::NewFunctionFromBoilerplate(boilerplate, Top::global_context()); } int main() { InitializeVM(); v8::HandleScope scope; string src,tmp; src = "function assertEquals(l,r){\n" "if(l == r){print(\"assertEquals OK\");}\n" "else{print(\"assertEquals Bad!\");}\n" "}\n"; src += "function assertTrue(exp){\n" "if(exp == true){print(\"assertTrue OK\");}\n" "else{print(\"assertTrue Bad!\");}\n" "}\n"; for(;!cin.eof();) { getline(cin,tmp); src += tmp+"\n"; } const char* source = src.c_str(); Handle<JSFunction> fun = Compile(source); CHECK(!fun.is_null()); bool has_pending_exception; Handle<JSObject> global(Top::context()->global()); Execution::Call(fun, global, 0, NULL, &has_pending_exception); return 0; }
このコード別に私が泥の様にソースコード読んだんじゃなくて、test/cctest/test-compiler.ccから取ってきたものを、まぁ簡略化した感じです。
ここ中心に使う側から攻められそうですね。
V8 Engineで最適化
とか、Compileする時に出来ないのかなーみたいな。
そんなのコード読めって話でしょうけどね。