source: trunk/FACT++/src/InterpreterV8.cc@ 14068

Last change on this file since 14068 was 14068, checked in by tbretz, 12 years ago
Added V8 disposal to destructor.
File size: 9.6 KB
Line 
1#include "InterpreterV8.h"
2
3InterpreterV8 *InterpreterV8::This = 0;
4
5#ifdef HAVE_V8
6
7#include <v8.h>
8#include <fstream>
9#include <sstream>
10#include <iomanip>
11
12using namespace std;
13using namespace v8;
14
15bool InterpreterV8::ReportException(TryCatch* try_catch)
16{
17 const HandleScope handle_scope;
18
19 const String::Utf8Value exception(try_catch->Exception());
20
21 if (*exception && string(*exception)=="exit")
22 return true;
23
24 const Handle<Message> message = try_catch->Message();
25
26 // Print (filename):(line number): (message).
27 const String::Utf8Value filename(message->GetScriptResourceName());
28
29 ostringstream out;
30
31 if (*filename)
32 out << *filename;
33 if (!message.IsEmpty())
34 out << ": l." << message->GetLineNumber();
35 if (*exception)
36 out << ": " << *exception;
37
38 JsException(out.str());
39
40 if (message.IsEmpty())
41 return false;
42
43 // Print line of source code.
44 const String::Utf8Value sourceline(message->GetSourceLine());
45 if (*sourceline)
46 JsException(*sourceline);
47
48 // Print wavy underline (GetUnderline is deprecated).
49 const int start = message->GetStartColumn();
50 const int end = message->GetEndColumn();
51
52 out.str("");
53 if (start>0)
54 out << setfill(' ') << setw(start) << ' ';
55 out << setfill('^') << setw(end-start) << '^';
56
57 JsException(out.str());
58
59 String::Utf8Value stack_trace(try_catch->StackTrace());
60 if (stack_trace.length()<=0)
61 return false;
62
63 //if (*stack_trace)
64 // JsException(string("\n")+*stack_trace);
65
66 return false;
67}
68
69// Executes a string within the current v8 context.
70bool InterpreterV8::ExecuteStringNT(const Handle<String> &code, const Handle<Value> &file)
71{
72 if (code.IsEmpty())
73 return true;
74
75 const HandleScope handle_scope;
76
77 const Handle<Script> script = Script::Compile(code, file);
78 if (script.IsEmpty())
79 return false;
80
81 const Handle<Value> result = script->Run();
82 if (result.IsEmpty())
83 return false;
84
85 // If all went well and the result wasn't undefined then print
86 // the returned value.
87 if (!result->IsUndefined())
88 JsResult(*String::Utf8Value(result));
89
90 return true;
91}
92
93bool InterpreterV8::ExecuteCode(const Handle<String> &code, const Handle<Value> &file)
94{
95 TryCatch exception;
96
97 const bool rc = ExecuteStringNT(code, file);
98
99 if (!exception.CanContinue())
100 return false;
101
102 if (exception.HasCaught())
103 return ReportException(&exception);
104
105 return rc;
106}
107
108bool InterpreterV8::ExecuteCode(const string &code, const string &file)
109{
110 return ExecuteCode(String::New(code.c_str(), code.size()),
111 String::New(file.c_str()));
112}
113
114bool InterpreterV8::ExecuteFile(const string &name)
115{
116 ifstream fin(name.c_str());
117 if (!fin)
118 {
119 JsException("Error - Could not open file '"+name+"'");
120 return false;
121 }
122
123 string buffer;
124 if (!getline(fin, buffer, '\0'))
125 return true;
126
127 if (fin.fail())
128 {
129 JsException("Error - reading file.");
130 return false;
131 }
132
133 return ExecuteCode(buffer, name);
134}
135
136Handle<Value> InterpreterV8::FuncWait(const Arguments& args)
137{
138 if (args.Length()!=2 && args.Length()!=3)
139 return ThrowException(String::New("Number of arguments must be 2 or 3."));
140
141 if (!args[0]->IsString())
142 return ThrowException(String::New("Argument 1 not a string."));
143
144 if (!args[1]->IsInt32())
145 return ThrowException(String::New("Argument 2 not an int32."));
146
147 if (args.Length()==3 && !args[2]->IsUint32())
148 return ThrowException(String::New("Argument 3 not an uint32."));
149
150 const string server = *String::Utf8Value(args[0]);
151 const int32_t state = args[1]->Int32Value();
152 const uint32_t millisec = args.Length()==3 ? args[2]->Int32Value() : 0;
153
154 const int rc = JsWait(server, state, millisec);
155
156 if (rc==0 || rc==1)
157 return Boolean::New(rc);
158
159 return ThrowException(String::New(("Waitig for state "+to_string(state)+" of server '"+server+"' failed.").c_str()));
160}
161
162Handle<Value> InterpreterV8::FuncSend(const Arguments& args)
163{
164 if (args.Length()==0)
165 return ThrowException(String::New("Number of arguments must be at least 1."));
166
167 if (!args[0]->IsString())
168 return ThrowException(String::New("Argument 1 must be a string."));
169
170 const HandleScope handle_scope;
171
172 const String::Utf8Value str(args[0]);
173
174 string command = *str;
175
176 for (int i=1; i<args.Length(); i++)
177 {
178 const String::Utf8Value arg(args[i]);
179 command += " \""+string(*arg)+"\"";
180 }
181
182 return Boolean::New(JsSend(command));
183}
184
185Handle<Value> InterpreterV8::FuncSleep(const Arguments& args)
186{
187 if (args.Length()!=1)
188 return ThrowException(String::New("Number of arguments must be exactly 1."));
189
190 if (!args[0]->IsUint32())
191 return ThrowException(String::New("Argument 1 must be an uint32."));
192
193 JsSleep(args[0]->Int32Value());
194
195 return Undefined();
196}
197
198Handle<Value> InterpreterV8::FuncState(const Arguments& args)
199{
200 if (args.Length()!=1)
201 return ThrowException(String::New("Number of arguments must be exactly 1."));
202
203 if (!args[0]->IsString())
204 return ThrowException(String::New("Argument 1 must be a string."));
205
206 const HandleScope handle_scope;
207
208 const String::Utf8Value str(args[0]);
209 return Integer::New(JsState(*str));
210}
211
212Handle<Value> InterpreterV8::FuncName(const Arguments& args)
213{
214 if (args.Length()!=1)
215 return ThrowException(String::New("Number of arguments must be exactly 1."));
216
217 if (!args[0]->IsString())
218 return ThrowException(String::New("Argument 1 must be a string."));
219
220 const HandleScope handle_scope;
221
222 const String::Utf8Value str(args[0]);
223 return String::New(JsName(*str).c_str());
224}
225
226Handle<Value> InterpreterV8::FuncExit(const Arguments &)
227{
228 v8::V8::TerminateExecution(fThreadId);
229 return ThrowException(String::New("exit"));
230/*
231 if (args.Length()!=1)
232 return ThrowException(String::New("Number of arguments must be exactly 1."));
233
234 if (!args[0]->IsUint32())
235 return ThrowException(String::New("Argument 1 must be an uint32."));
236
237 const HandleScope handle_scope;
238
239 JsSleep(args[0]->Int32Value());
240*/
241 return Undefined();
242}
243
244// The callback that is invoked by v8 whenever the JavaScript 'print'
245// function is called. Prints its arguments on stdout separated by
246// spaces and ending with a newline.
247Handle<Value> InterpreterV8::FuncPrint(const Arguments& args)
248{
249 for (int i=0; i<args.Length(); i++)
250 {
251 const HandleScope handle_scope;
252
253 const String::Utf8Value str(args[i]);
254 if (*str)
255 JsPrint(*str);
256 }
257 return Undefined();
258}
259
260// The callback that is invoked by v8 whenever the JavaScript 'load'
261// function is called. Loads, compiles and executes its argument
262// JavaScript file.
263Handle<Value> InterpreterV8::FuncInclude(const Arguments& args)
264{
265 for (int i = 0; i<args.Length(); i++)
266 {
267 const HandleScope handle_scope;
268
269 const String::Utf8Value file(args[i]);
270 if (*file == NULL)
271 return ThrowException(String::New(("Error loading file '"+string(*file)+"'").c_str()));
272
273 if (!ExecuteFile(*file))
274 return ThrowException(String::New(("Execution of '"+string(*file)+"' failed").c_str()));
275 }
276 return Undefined();
277}
278
279Handle<Value> InterpreterV8::FuncVersion(const Arguments&)
280{
281 return String::New(V8::GetVersion());
282}
283
284#include <iostream>
285
286bool InterpreterV8::JsRun(const string &filename, const map<string, string> &map)
287{
288 v8::Locker locker;
289 fThreadId = V8::GetCurrentThreadId();
290
291 JsLoad(filename);
292
293 HandleScope handle_scope;
294
295 // Create a template for the global object.
296 Handle<ObjectTemplate> dim = ObjectTemplate::New();
297 dim->Set(String::New("print"), FunctionTemplate::New(WrapPrint), ReadOnly);
298 dim->Set(String::New("wait"), FunctionTemplate::New(WrapWait), ReadOnly);
299 dim->Set(String::New("send"), FunctionTemplate::New(WrapSend), ReadOnly);
300 dim->Set(String::New("state"), FunctionTemplate::New(WrapState), ReadOnly);
301 dim->Set(String::New("name"), FunctionTemplate::New(WrapName), ReadOnly);
302 dim->Set(String::New("sleep"), FunctionTemplate::New(WrapSleep), ReadOnly);
303
304 Handle<ObjectTemplate> global = ObjectTemplate::New();
305 global->Set(String::New("dim"), dim, ReadOnly);
306 global->Set(String::New("include"), FunctionTemplate::New(WrapInclude), ReadOnly);
307 global->Set(String::New("exit"), FunctionTemplate::New(WrapExit), ReadOnly);
308 global->Set(String::New("version"), FunctionTemplate::New(InterpreterV8::FuncVersion), ReadOnly);
309
310 // Persistent
311 Handle<Context> context = Context::New(NULL, global);
312 if (context.IsEmpty())
313 {
314 //printf("Error creating context\n");
315 return false;
316 }
317
318 v8::Context::Scope scope(context);
319
320 Local<Array> args = Array::New(map.size());
321 for (auto it=map.begin(); it!=map.end(); it++)
322 args->Set(String::New(it->first.c_str()), String::New(it->second.c_str()));
323 context->Global()->Set(String::New("$"), args);
324 context->Global()->Set(String::New("arg"), args);
325
326 JsStart(filename);
327
328 //context->Enter();
329 v8::Locker::StartPreemption(10);
330 const bool rc = ExecuteFile(filename);
331 v8::Locker::StopPreemption();
332 //context->Exit();
333
334 JsEnd(filename);
335
336 return rc;
337}
338
339void InterpreterV8::JsStop()
340{
341 v8::Locker locker;
342 //cout << "Terminate " << fThreadId << endl;
343 if (This->fThreadId>=0)
344 v8::V8::TerminateExecution(This->fThreadId);
345 //cout << "Terminate " << fThreadId << endl;
346 v8::Unlocker unlocker;
347}
348
349#endif
Note: See TracBrowser for help on using the repository browser.