source: webkit/trunk/Source/JavaScriptCore/jsc.cpp@ 111129

Last change on this file since 111129 was 111129, checked in by [email protected], 13 years ago

Strength reduction, RegExp.exec -> RegExp.test
https://bugs.webkit.org/show_bug.cgi?id=81459

Reviewed by Sam Weinig.

RegExp.prototype.exec & RegExp.prototype.test can both be used to test a regular
expression for a match against a string - however exec is more expensive, since
it allocates a matches array object. In cases where the result is consumed in a
boolean context the allocation of the matches array can be trivially elided.

For example:

function f()
{

for (i =0; i < 10000000; ++i)

if(!/a/.exec("a"))

err = true;

}

This is a 2.5x speedup on this example microbenchmark loop.

In a more advanced form of this optimization, we may be able to avoid allocating
the array where access to the array can be observed.

  • create_hash_table:
  • dfg/DFGAbstractState.cpp:

(JSC::DFG::AbstractState::execute):

  • dfg/DFGByteCodeParser.cpp:

(JSC::DFG::ByteCodeParser::handleIntrinsic):

  • dfg/DFGNode.h:

(JSC::DFG::Node::hasHeapPrediction):

  • dfg/DFGNodeType.h:

(DFG):

  • dfg/DFGOperations.cpp:
  • dfg/DFGOperations.h:
  • dfg/DFGPredictionPropagationPhase.cpp:

(JSC::DFG::PredictionPropagationPhase::propagate):

  • dfg/DFGSpeculativeJIT.cpp:

(JSC::DFG::SpeculativeJIT::compileRegExpExec):
(DFG):

  • dfg/DFGSpeculativeJIT.h:

(JSC::DFG::SpeculativeJIT::callOperation):

  • dfg/DFGSpeculativeJIT32_64.cpp:

(JSC::DFG::SpeculativeJIT::compile):

  • dfg/DFGSpeculativeJIT64.cpp:

(JSC::DFG::SpeculativeJIT::compile):

  • jsc.cpp:

(GlobalObject::addConstructableFunction):

  • runtime/Intrinsic.h:
  • runtime/JSFunction.cpp:

(JSC::JSFunction::create):
(JSC):

  • runtime/JSFunction.h:

(JSFunction):

  • runtime/Lookup.cpp:

(JSC::setUpStaticFunctionSlot):

  • runtime/RegExpObject.cpp:

(JSC::RegExpObject::exec):
(JSC::RegExpObject::match):

  • runtime/RegExpObject.h:

(RegExpObject):

  • runtime/RegExpPrototype.cpp:

(JSC::regExpProtoFuncTest):
(JSC::regExpProtoFuncExec):

  • Property svn:eol-style set to native
File size: 22.8 KB
Line 
1/*
2 * Copyright (C) 1999-2000 Harri Porten ([email protected])
3 * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
4 * Copyright (C) 2006 Bjoern Graf ([email protected])
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Library General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Library General Public License for more details.
15 *
16 * You should have received a copy of the GNU Library General Public License
17 * along with this library; see the file COPYING.LIB. If not, write to
18 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
19 * Boston, MA 02110-1301, USA.
20 *
21 */
22
23#include "config.h"
24
25#include "BytecodeGenerator.h"
26#include "Completion.h"
27#include "CurrentTime.h"
28#include "ExceptionHelpers.h"
29#include "InitializeThreading.h"
30#include "Interpreter.h"
31#include "JSArray.h"
32#include "JSCTypedArrayStubs.h"
33#include "JSFunction.h"
34#include "JSLock.h"
35#include "JSString.h"
36#include "MainThread.h"
37#include "SamplingTool.h"
38#include <math.h>
39#include <stdio.h>
40#include <stdlib.h>
41#include <string.h>
42
43#if !OS(WINDOWS)
44#include <unistd.h>
45#endif
46
47#if HAVE(READLINE)
48// readline/history.h has a Function typedef which conflicts with the WTF::Function template from WTF/Forward.h
49// We #define it to something else to avoid this conflict.
50#define Function ReadlineFunction
51#include <readline/history.h>
52#include <readline/readline.h>
53#undef Function
54#endif
55
56#if HAVE(SYS_TIME_H)
57#include <sys/time.h>
58#endif
59
60#if HAVE(SIGNAL_H)
61#include <signal.h>
62#endif
63
64#if COMPILER(MSVC) && !OS(WINCE)
65#include <crtdbg.h>
66#include <mmsystem.h>
67#include <windows.h>
68#endif
69
70#if PLATFORM(QT)
71#include <QCoreApplication>
72#include <QDateTime>
73#endif
74
75using namespace JSC;
76using namespace WTF;
77
78static void cleanupGlobalData(JSGlobalData*);
79static bool fillBufferWithContentsOfFile(const UString& fileName, Vector<char>& buffer);
80
81static EncodedJSValue JSC_HOST_CALL functionPrint(ExecState*);
82static EncodedJSValue JSC_HOST_CALL functionDebug(ExecState*);
83static EncodedJSValue JSC_HOST_CALL functionJSCStack(ExecState*);
84static EncodedJSValue JSC_HOST_CALL functionGC(ExecState*);
85#ifndef NDEBUG
86static EncodedJSValue JSC_HOST_CALL functionReleaseExecutableMemory(ExecState*);
87#endif
88static EncodedJSValue JSC_HOST_CALL functionVersion(ExecState*);
89static EncodedJSValue JSC_HOST_CALL functionRun(ExecState*);
90static EncodedJSValue JSC_HOST_CALL functionLoad(ExecState*);
91static EncodedJSValue JSC_HOST_CALL functionCheckSyntax(ExecState*);
92static EncodedJSValue JSC_HOST_CALL functionReadline(ExecState*);
93static EncodedJSValue JSC_HOST_CALL functionPreciseTime(ExecState*);
94static NO_RETURN_WITH_VALUE EncodedJSValue JSC_HOST_CALL functionQuit(ExecState*);
95
96#if ENABLE(SAMPLING_FLAGS)
97static EncodedJSValue JSC_HOST_CALL functionSetSamplingFlags(ExecState*);
98static EncodedJSValue JSC_HOST_CALL functionClearSamplingFlags(ExecState*);
99#endif
100
101struct Script {
102 bool isFile;
103 char* argument;
104
105 Script(bool isFile, char *argument)
106 : isFile(isFile)
107 , argument(argument)
108 {
109 }
110};
111
112struct CommandLine {
113 CommandLine()
114 : interactive(false)
115 , dump(false)
116 {
117 }
118
119 bool interactive;
120 bool dump;
121 Vector<Script> scripts;
122 Vector<UString> arguments;
123};
124
125static const char interactivePrompt[] = "> ";
126
127class StopWatch {
128public:
129 void start();
130 void stop();
131 long getElapsedMS(); // call stop() first
132
133private:
134 double m_startTime;
135 double m_stopTime;
136};
137
138void StopWatch::start()
139{
140 m_startTime = currentTime();
141}
142
143void StopWatch::stop()
144{
145 m_stopTime = currentTime();
146}
147
148long StopWatch::getElapsedMS()
149{
150 return static_cast<long>((m_stopTime - m_startTime) * 1000);
151}
152
153class GlobalObject : public JSGlobalObject {
154private:
155 GlobalObject(JSGlobalData&, Structure*);
156
157public:
158 typedef JSGlobalObject Base;
159
160 static GlobalObject* create(JSGlobalData& globalData, Structure* structure, const Vector<UString>& arguments)
161 {
162 GlobalObject* object = new (NotNull, allocateCell<GlobalObject>(globalData.heap)) GlobalObject(globalData, structure);
163 object->finishCreation(globalData, arguments);
164 return object;
165 }
166
167 static const ClassInfo s_info;
168
169 static Structure* createStructure(JSGlobalData& globalData, JSValue prototype)
170 {
171 return Structure::create(globalData, 0, prototype, TypeInfo(GlobalObjectType, StructureFlags), &s_info);
172 }
173
174protected:
175 void finishCreation(JSGlobalData& globalData, const Vector<UString>& arguments)
176 {
177 Base::finishCreation(globalData);
178
179 addFunction(globalData, "debug", functionDebug, 1);
180 addFunction(globalData, "print", functionPrint, 1);
181 addFunction(globalData, "quit", functionQuit, 0);
182 addFunction(globalData, "gc", functionGC, 0);
183#ifndef NDEBUG
184 addFunction(globalData, "releaseExecutableMemory", functionReleaseExecutableMemory, 0);
185#endif
186 addFunction(globalData, "version", functionVersion, 1);
187 addFunction(globalData, "run", functionRun, 1);
188 addFunction(globalData, "load", functionLoad, 1);
189 addFunction(globalData, "checkSyntax", functionCheckSyntax, 1);
190 addFunction(globalData, "jscStack", functionJSCStack, 1);
191 addFunction(globalData, "readline", functionReadline, 0);
192 addFunction(globalData, "preciseTime", functionPreciseTime, 0);
193#if ENABLE(SAMPLING_FLAGS)
194 addFunction(globalData, "setSamplingFlags", functionSetSamplingFlags, 1);
195 addFunction(globalData, "clearSamplingFlags", functionClearSamplingFlags, 1);
196#endif
197
198#if ENABLE(COMMANDLINE_TYPEDARRAYS)
199 addConstructableFunction(globalData, "Uint8Array", constructJSUint8Array, 1);
200 addConstructableFunction(globalData, "Uint16Array", constructJSUint16Array, 1);
201 addConstructableFunction(globalData, "Uint32Array", constructJSUint32Array, 1);
202 addConstructableFunction(globalData, "Int8Array", constructJSInt8Array, 1);
203 addConstructableFunction(globalData, "Int16Array", constructJSInt16Array, 1);
204 addConstructableFunction(globalData, "Int32Array", constructJSInt32Array, 1);
205 addConstructableFunction(globalData, "Float32Array", constructJSFloat32Array, 1);
206 addConstructableFunction(globalData, "Float64Array", constructJSFloat64Array, 1);
207#endif
208
209 JSArray* array = constructEmptyArray(globalExec());
210 for (size_t i = 0; i < arguments.size(); ++i)
211 array->putDirectIndex(globalExec(), i, jsString(globalExec(), arguments[i]), false);
212 putDirect(globalData, Identifier(globalExec(), "arguments"), array);
213 }
214
215 void addFunction(JSGlobalData& globalData, const char* name, NativeFunction function, unsigned arguments)
216 {
217 Identifier identifier(globalExec(), name);
218 putDirect(globalData, identifier, JSFunction::create(globalExec(), this, arguments, identifier, function));
219 }
220
221 void addConstructableFunction(JSGlobalData& globalData, const char* name, NativeFunction function, unsigned arguments)
222 {
223 Identifier identifier(globalExec(), name);
224 putDirect(globalData, identifier, JSFunction::create(globalExec(), this, arguments, identifier, function, NoIntrinsic, function));
225 }
226};
227COMPILE_ASSERT(!IsInteger<GlobalObject>::value, WTF_IsInteger_GlobalObject_false);
228ASSERT_CLASS_FITS_IN_CELL(GlobalObject);
229
230const ClassInfo GlobalObject::s_info = { "global", &JSGlobalObject::s_info, 0, ExecState::globalObjectTable, CREATE_METHOD_TABLE(GlobalObject) };
231
232GlobalObject::GlobalObject(JSGlobalData& globalData, Structure* structure)
233 : JSGlobalObject(globalData, structure)
234{
235}
236
237static inline SourceCode jscSource(const char* utf8, const UString& filename)
238{
239 // Find the the first non-ascii character, or nul.
240 const char* pos = utf8;
241 while (*pos > 0)
242 pos++;
243 size_t asciiLength = pos - utf8;
244
245 // Fast case - string is all ascii.
246 if (!*pos)
247 return makeSource(UString(utf8, asciiLength), filename);
248
249 // Slow case - contains non-ascii characters, use fromUTF8WithLatin1Fallback.
250 ASSERT(*pos < 0);
251 ASSERT(strlen(utf8) == asciiLength + strlen(pos));
252 String source = String::fromUTF8WithLatin1Fallback(utf8, asciiLength + strlen(pos));
253 return makeSource(source.impl(), filename);
254}
255
256EncodedJSValue JSC_HOST_CALL functionPrint(ExecState* exec)
257{
258 for (unsigned i = 0; i < exec->argumentCount(); ++i) {
259 if (i)
260 putchar(' ');
261
262 printf("%s", exec->argument(i).toString(exec)->value(exec).utf8().data());
263 }
264
265 putchar('\n');
266 fflush(stdout);
267 return JSValue::encode(jsUndefined());
268}
269
270EncodedJSValue JSC_HOST_CALL functionDebug(ExecState* exec)
271{
272 fprintf(stderr, "--> %s\n", exec->argument(0).toString(exec)->value(exec).utf8().data());
273 return JSValue::encode(jsUndefined());
274}
275
276EncodedJSValue JSC_HOST_CALL functionJSCStack(ExecState* exec)
277{
278 String trace = "--> Stack trace:\n";
279 Vector<StackFrame> stackTrace;
280 Interpreter::getStackTrace(&exec->globalData(), -1, stackTrace);
281 int i = 0;
282
283 for (Vector<StackFrame>::iterator iter = stackTrace.begin(); iter < stackTrace.end(); iter++) {
284 StackFrame level = *iter;
285 trace += String::format(" %i %s\n", i, level.toString(exec).utf8().data());
286 i++;
287 }
288 fprintf(stderr, "%s", trace.utf8().data());
289 return JSValue::encode(jsUndefined());
290}
291
292EncodedJSValue JSC_HOST_CALL functionGC(ExecState* exec)
293{
294 JSLock lock(SilenceAssertionsOnly);
295 exec->heap()->collectAllGarbage();
296 return JSValue::encode(jsUndefined());
297}
298
299#ifndef NDEBUG
300EncodedJSValue JSC_HOST_CALL functionReleaseExecutableMemory(ExecState* exec)
301{
302 JSLock lock(SilenceAssertionsOnly);
303 exec->globalData().releaseExecutableMemory();
304 return JSValue::encode(jsUndefined());
305}
306#endif
307
308EncodedJSValue JSC_HOST_CALL functionVersion(ExecState*)
309{
310 // We need this function for compatibility with the Mozilla JS tests but for now
311 // we don't actually do any version-specific handling
312 return JSValue::encode(jsUndefined());
313}
314
315EncodedJSValue JSC_HOST_CALL functionRun(ExecState* exec)
316{
317 UString fileName = exec->argument(0).toString(exec)->value(exec);
318 Vector<char> script;
319 if (!fillBufferWithContentsOfFile(fileName, script))
320 return JSValue::encode(throwError(exec, createError(exec, "Could not open file.")));
321
322 GlobalObject* globalObject = GlobalObject::create(exec->globalData(), GlobalObject::createStructure(exec->globalData(), jsNull()), Vector<UString>());
323
324 StopWatch stopWatch;
325 stopWatch.start();
326 evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), jscSource(script.data(), fileName));
327 stopWatch.stop();
328
329 return JSValue::encode(jsNumber(stopWatch.getElapsedMS()));
330}
331
332EncodedJSValue JSC_HOST_CALL functionLoad(ExecState* exec)
333{
334 UString fileName = exec->argument(0).toString(exec)->value(exec);
335 Vector<char> script;
336 if (!fillBufferWithContentsOfFile(fileName, script))
337 return JSValue::encode(throwError(exec, createError(exec, "Could not open file.")));
338
339 JSGlobalObject* globalObject = exec->lexicalGlobalObject();
340
341 JSValue evaluationException;
342 JSValue result = evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), jscSource(script.data(), fileName), JSValue(), &evaluationException);
343 if (evaluationException)
344 throwError(exec, evaluationException);
345 return JSValue::encode(result);
346}
347
348EncodedJSValue JSC_HOST_CALL functionCheckSyntax(ExecState* exec)
349{
350 UString fileName = exec->argument(0).toString(exec)->value(exec);
351 Vector<char> script;
352 if (!fillBufferWithContentsOfFile(fileName, script))
353 return JSValue::encode(throwError(exec, createError(exec, "Could not open file.")));
354
355 JSGlobalObject* globalObject = exec->lexicalGlobalObject();
356
357 StopWatch stopWatch;
358 stopWatch.start();
359
360 JSValue syntaxException;
361 bool validSyntax = checkSyntax(globalObject->globalExec(), jscSource(script.data(), fileName), &syntaxException);
362 stopWatch.stop();
363
364 if (!validSyntax)
365 throwError(exec, syntaxException);
366 return JSValue::encode(jsNumber(stopWatch.getElapsedMS()));
367}
368
369#if ENABLE(SAMPLING_FLAGS)
370EncodedJSValue JSC_HOST_CALL functionSetSamplingFlags(ExecState* exec)
371{
372 for (unsigned i = 0; i < exec->argumentCount(); ++i) {
373 unsigned flag = static_cast<unsigned>(exec->argument(i).toNumber(exec));
374 if ((flag >= 1) && (flag <= 32))
375 SamplingFlags::setFlag(flag);
376 }
377 return JSValue::encode(jsNull());
378}
379
380EncodedJSValue JSC_HOST_CALL functionClearSamplingFlags(ExecState* exec)
381{
382 for (unsigned i = 0; i < exec->argumentCount(); ++i) {
383 unsigned flag = static_cast<unsigned>(exec->argument(i).toNumber(exec));
384 if ((flag >= 1) && (flag <= 32))
385 SamplingFlags::clearFlag(flag);
386 }
387 return JSValue::encode(jsNull());
388}
389#endif
390
391EncodedJSValue JSC_HOST_CALL functionReadline(ExecState* exec)
392{
393 Vector<char, 256> line;
394 int c;
395 while ((c = getchar()) != EOF) {
396 // FIXME: Should we also break on \r?
397 if (c == '\n')
398 break;
399 line.append(c);
400 }
401 line.append('\0');
402 return JSValue::encode(jsString(exec, line.data()));
403}
404
405EncodedJSValue JSC_HOST_CALL functionPreciseTime(ExecState*)
406{
407 return JSValue::encode(jsNumber(currentTime()));
408}
409
410EncodedJSValue JSC_HOST_CALL functionQuit(ExecState* exec)
411{
412 // Technically, destroying the heap in the middle of JS execution is a no-no,
413 // but we want to maintain compatibility with the Mozilla test suite, so
414 // we pretend that execution has terminated to avoid ASSERTs, then tear down the heap.
415 exec->globalData().dynamicGlobalObject = 0;
416
417 cleanupGlobalData(&exec->globalData());
418 exit(EXIT_SUCCESS);
419
420#if COMPILER(MSVC) && OS(WINCE)
421 // Without this, Visual Studio will complain that this method does not return a value.
422 return JSValue::encode(jsUndefined());
423#endif
424}
425
426// Use SEH for Release builds only to get rid of the crash report dialog
427// (luckily the same tests fail in Release and Debug builds so far). Need to
428// be in a separate main function because the jscmain function requires object
429// unwinding.
430
431#if COMPILER(MSVC) && !COMPILER(INTEL) && !defined(_DEBUG) && !OS(WINCE)
432#define TRY __try {
433#define EXCEPT(x) } __except (EXCEPTION_EXECUTE_HANDLER) { x; }
434#else
435#define TRY
436#define EXCEPT(x)
437#endif
438
439int jscmain(int argc, char** argv, JSGlobalData*);
440
441int main(int argc, char** argv)
442{
443#if OS(WINDOWS)
444#if !OS(WINCE)
445 // Cygwin calls ::SetErrorMode(SEM_FAILCRITICALERRORS), which we will inherit. This is bad for
446 // testing/debugging, as it causes the post-mortem debugger not to be invoked. We reset the
447 // error mode here to work around Cygwin's behavior. See <http://webkit.org/b/55222>.
448 ::SetErrorMode(0);
449#endif
450
451#if defined(_DEBUG)
452 _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
453 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
454 _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
455 _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
456 _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
457 _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
458#endif
459
460 timeBeginPeriod(1);
461#endif
462
463#if PLATFORM(QT)
464 QCoreApplication app(argc, argv);
465#endif
466
467 // Initialize JSC before getting JSGlobalData.
468#if ENABLE(SAMPLING_REGIONS)
469 WTF::initializeMainThread();
470#endif
471 JSC::initializeThreading();
472
473 // We can't use destructors in the following code because it uses Windows
474 // Structured Exception Handling
475 int res = 0;
476 JSGlobalData* globalData = JSGlobalData::create(ThreadStackTypeLarge, LargeHeap).leakRef();
477 TRY
478 res = jscmain(argc, argv, globalData);
479 EXCEPT(res = 3)
480
481 cleanupGlobalData(globalData);
482 return res;
483}
484
485static void cleanupGlobalData(JSGlobalData* globalData)
486{
487 JSLock lock(SilenceAssertionsOnly);
488 globalData->clearBuiltinStructures();
489 globalData->heap.destroy();
490 globalData->deref();
491}
492
493static bool runWithScripts(GlobalObject* globalObject, const Vector<Script>& scripts, bool dump)
494{
495 const char* script;
496 UString fileName;
497 Vector<char> scriptBuffer;
498
499 if (dump)
500 BytecodeGenerator::setDumpsGeneratedCode(true);
501
502 JSGlobalData& globalData = globalObject->globalData();
503
504#if ENABLE(SAMPLING_FLAGS)
505 SamplingFlags::start();
506#endif
507
508 bool success = true;
509 for (size_t i = 0; i < scripts.size(); i++) {
510 if (scripts[i].isFile) {
511 fileName = scripts[i].argument;
512 if (!fillBufferWithContentsOfFile(fileName, scriptBuffer))
513 return false; // fail early so we can catch missing files
514 script = scriptBuffer.data();
515 } else {
516 script = scripts[i].argument;
517 fileName = "[Command Line]";
518 }
519
520 globalData.startSampling();
521
522 JSValue evaluationException;
523 JSValue returnValue = evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), jscSource(script, fileName), JSValue(), &evaluationException);
524 success = success && !evaluationException;
525 if (dump) {
526 if (evaluationException)
527 printf("Exception: %s\n", evaluationException.toString(globalObject->globalExec())->value(globalObject->globalExec()).utf8().data());
528 else
529 printf("End: %s\n", returnValue.toString(globalObject->globalExec())->value(globalObject->globalExec()).utf8().data());
530 }
531
532 globalData.stopSampling();
533 globalObject->globalExec()->clearException();
534 }
535
536#if ENABLE(SAMPLING_FLAGS)
537 SamplingFlags::stop();
538#endif
539#if ENABLE(SAMPLING_REGIONS)
540 SamplingRegion::dump();
541#endif
542 globalData.dumpSampleData(globalObject->globalExec());
543#if ENABLE(SAMPLING_COUNTERS)
544 AbstractSamplingCounter::dump();
545#endif
546#if ENABLE(REGEXP_TRACING)
547 globalData.dumpRegExpTrace();
548#endif
549 return success;
550}
551
552#define RUNNING_FROM_XCODE 0
553
554static void runInteractive(GlobalObject* globalObject)
555{
556 UString interpreterName("Interpreter");
557
558 while (true) {
559#if HAVE(READLINE) && !RUNNING_FROM_XCODE
560 char* line = readline(interactivePrompt);
561 if (!line)
562 break;
563 if (line[0])
564 add_history(line);
565 JSValue evaluationException;
566 JSValue returnValue = evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), jscSource(line, interpreterName), JSValue(), &evaluationException);
567 free(line);
568#else
569 printf("%s", interactivePrompt);
570 Vector<char, 256> line;
571 int c;
572 while ((c = getchar()) != EOF) {
573 // FIXME: Should we also break on \r?
574 if (c == '\n')
575 break;
576 line.append(c);
577 }
578 if (line.isEmpty())
579 break;
580 line.append('\0');
581
582 JSValue evaluationException;
583 JSValue returnValue = evaluate(globalObject->globalExec(), globalObject->globalScopeChain(), jscSource(line.data(), interpreterName), JSValue(), &evaluationException);
584#endif
585 if (evaluationException)
586 printf("Exception: %s\n", evaluationException.toString(globalObject->globalExec())->value(globalObject->globalExec()).utf8().data());
587 else
588 printf("%s\n", returnValue.toString(globalObject->globalExec())->value(globalObject->globalExec()).utf8().data());
589
590 globalObject->globalExec()->clearException();
591 }
592 printf("\n");
593}
594
595static NO_RETURN void printUsageStatement(JSGlobalData* globalData, bool help = false)
596{
597 fprintf(stderr, "Usage: jsc [options] [files] [-- arguments]\n");
598 fprintf(stderr, " -d Dumps bytecode (debug builds only)\n");
599 fprintf(stderr, " -e Evaluate argument as script code\n");
600 fprintf(stderr, " -f Specifies a source file (deprecated)\n");
601 fprintf(stderr, " -h|--help Prints this help message\n");
602 fprintf(stderr, " -i Enables interactive mode (default if no files are specified)\n");
603#if HAVE(SIGNAL_H)
604 fprintf(stderr, " -s Installs signal handlers that exit on a crash (Unix platforms only)\n");
605#endif
606
607 cleanupGlobalData(globalData);
608 exit(help ? EXIT_SUCCESS : EXIT_FAILURE);
609}
610
611static void parseArguments(int argc, char** argv, CommandLine& options, JSGlobalData* globalData)
612{
613 int i = 1;
614 for (; i < argc; ++i) {
615 const char* arg = argv[i];
616 if (!strcmp(arg, "-f")) {
617 if (++i == argc)
618 printUsageStatement(globalData);
619 options.scripts.append(Script(true, argv[i]));
620 continue;
621 }
622 if (!strcmp(arg, "-e")) {
623 if (++i == argc)
624 printUsageStatement(globalData);
625 options.scripts.append(Script(false, argv[i]));
626 continue;
627 }
628 if (!strcmp(arg, "-i")) {
629 options.interactive = true;
630 continue;
631 }
632 if (!strcmp(arg, "-d")) {
633 options.dump = true;
634 continue;
635 }
636 if (!strcmp(arg, "-s")) {
637#if HAVE(SIGNAL_H)
638 signal(SIGILL, _exit);
639 signal(SIGFPE, _exit);
640 signal(SIGBUS, _exit);
641 signal(SIGSEGV, _exit);
642#endif
643 continue;
644 }
645 if (!strcmp(arg, "--")) {
646 ++i;
647 break;
648 }
649 if (!strcmp(arg, "-h") || !strcmp(arg, "--help"))
650 printUsageStatement(globalData, true);
651 options.scripts.append(Script(true, argv[i]));
652 }
653
654 if (options.scripts.isEmpty())
655 options.interactive = true;
656
657 for (; i < argc; ++i)
658 options.arguments.append(argv[i]);
659}
660
661int jscmain(int argc, char** argv, JSGlobalData* globalData)
662{
663 JSLock lock(SilenceAssertionsOnly);
664
665 CommandLine options;
666 parseArguments(argc, argv, options, globalData);
667
668 GlobalObject* globalObject = GlobalObject::create(*globalData, GlobalObject::createStructure(*globalData, jsNull()), options.arguments);
669 bool success = runWithScripts(globalObject, options.scripts, options.dump);
670 if (options.interactive && success)
671 runInteractive(globalObject);
672
673 return success ? 0 : 3;
674}
675
676static bool fillBufferWithContentsOfFile(const UString& fileName, Vector<char>& buffer)
677{
678 FILE* f = fopen(fileName.utf8().data(), "r");
679 if (!f) {
680 fprintf(stderr, "Could not open file: %s\n", fileName.utf8().data());
681 return false;
682 }
683
684 size_t bufferSize = 0;
685 size_t bufferCapacity = 1024;
686
687 buffer.resize(bufferCapacity);
688
689 while (!feof(f) && !ferror(f)) {
690 bufferSize += fread(buffer.data() + bufferSize, 1, bufferCapacity - bufferSize, f);
691 if (bufferSize == bufferCapacity) { // guarantees space for trailing '\0'
692 bufferCapacity *= 2;
693 buffer.resize(bufferCapacity);
694 }
695 }
696 fclose(f);
697 buffer[bufferSize] = '\0';
698
699 if (buffer[0] == '#' && buffer[1] == '!')
700 buffer[0] = buffer[1] = '/';
701
702 return true;
703}
Note: See TracBrowser for help on using the repository browser.