source: webkit/trunk/JavaScriptCore/kjs/testkjs.cpp@ 27215

Last change on this file since 27215 was 27031, checked in by eseidel, 18 years ago

2007-10-25 Eric Seidel <[email protected]>

Reviewed by Maciej.


More preparation work before adding long-running mode to testkjs.

  • kjs/testkjs.cpp: (TestFunctionImp::callAsFunction): (prettyPrintScript): (runWithScripts): (parseArguments): (kjsmain): (fillBufferWithContentsOfFile):
  • Property svn:eol-style set to native
File size: 10.3 KB
Line 
1// -*- c-basic-offset: 2 -*-
2/*
3 * Copyright (C) 1999-2000 Harri Porten ([email protected])
4 * Copyright (C) 2004-2007 Apple Inc.
5 * Copyright (C) 2006 Bjoern Graf ([email protected])
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Library General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
11 *
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Library General Public License for more details.
16 *
17 * You should have received a copy of the GNU Library General Public License
18 * along with this library; see the file COPYING.LIB. If not, write to
19 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
20 * Boston, MA 02110-1301, USA.
21 *
22 */
23
24#include "config.h"
25
26#include "JSLock.h"
27#include "Parser.h"
28#include "collector.h"
29#include "JSGlobalObject.h"
30#include "object.h"
31#include "protect.h"
32#include <math.h>
33#include <stdio.h>
34#include <string.h>
35#include <wtf/Assertions.h>
36#include <wtf/HashTraits.h>
37
38#if HAVE(SYS_TIME_H)
39#include <sys/time.h>
40#endif
41
42#if PLATFORM(WIN_OS)
43#include <crtdbg.h>
44#include <windows.h>
45#endif
46
47#if PLATFORM(QT)
48#include <QDateTime>
49#endif
50
51using namespace KJS;
52using namespace WTF;
53
54static void testIsInteger();
55static bool fillBufferWithContentsOfFile(const UString& fileName, Vector<char>& buffer);
56
57class StopWatch
58{
59public:
60 void start();
61 void stop();
62 long getElapsedMS(); // call stop() first
63
64private:
65#if PLATFORM(QT)
66 uint m_startTime;
67 uint m_stopTime;
68#elif PLATFORM(WIN_OS)
69 DWORD m_startTime;
70 DWORD m_stopTime;
71#else
72 // Windows does not have timeval, disabling this class for now (bug 7399)
73 timeval m_startTime;
74 timeval m_stopTime;
75#endif
76};
77
78void StopWatch::start()
79{
80#if PLATFORM(QT)
81 QDateTime t = QDateTime::currentDateTime();
82 m_startTime = t.toTime_t() * 1000 + t.time().msec();
83#elif PLATFORM(WIN_OS)
84 m_startTime = timeGetTime();
85#else
86 gettimeofday(&m_startTime, 0);
87#endif
88}
89
90void StopWatch::stop()
91{
92#if PLATFORM(QT)
93 QDateTime t = QDateTime::currentDateTime();
94 m_stopTime = t.toTime_t() * 1000 + t.time().msec();
95#elif PLATFORM(WIN_OS)
96 m_stopTime = timeGetTime();
97#else
98 gettimeofday(&m_stopTime, 0);
99#endif
100}
101
102long StopWatch::getElapsedMS()
103{
104#if PLATFORM(WIN_OS) || PLATFORM(QT)
105 return m_stopTime - m_startTime;
106#else
107 timeval elapsedTime;
108 timersub(&m_stopTime, &m_startTime, &elapsedTime);
109
110 return elapsedTime.tv_sec * 1000 + lroundf(elapsedTime.tv_usec / 1000.0f);
111#endif
112}
113
114class GlobalImp : public JSGlobalObject {
115public:
116 virtual UString className() const { return "global"; }
117};
118
119class TestFunctionImp : public JSObject {
120public:
121 enum TestFunctionType { Print, Debug, Quit, GC, Version, Run, Load };
122
123 TestFunctionImp(TestFunctionType i, int length);
124 virtual bool implementsCall() const { return true; }
125 virtual JSValue* callAsFunction(ExecState* exec, JSObject* thisObj, const List &args);
126
127private:
128 TestFunctionType m_type;
129};
130
131TestFunctionImp::TestFunctionImp(TestFunctionType i, int length)
132 : JSObject()
133 , m_type(i)
134{
135 putDirect(Identifier("length"), length, DontDelete | ReadOnly | DontEnum);
136}
137
138JSValue* TestFunctionImp::callAsFunction(ExecState* exec, JSObject*, const List &args)
139{
140 switch (m_type) {
141 case Print:
142 printf("%s\n", args[0]->toString(exec).UTF8String().c_str());
143 return jsUndefined();
144 case Debug:
145 fprintf(stderr, "--> %s\n", args[0]->toString(exec).UTF8String().c_str());
146 return jsUndefined();
147 case GC:
148 {
149 JSLock lock;
150 Collector::collect();
151 return jsUndefined();
152 }
153 case Version:
154 // We need this function for compatibility with the Mozilla JS tests but for now
155 // we don't actually do any version-specific handling
156 return jsUndefined();
157 case Run:
158 {
159 StopWatch stopWatch;
160 UString fileName = args[0]->toString(exec);
161 Vector<char> script;
162 if (!fillBufferWithContentsOfFile(fileName, script))
163 return throwError(exec, GeneralError, "Could not open file.");
164
165 stopWatch.start();
166 exec->dynamicInterpreter()->evaluate(fileName, 0, script.data());
167 stopWatch.stop();
168
169 return jsNumber(stopWatch.getElapsedMS());
170 }
171 case Load:
172 {
173 UString fileName = args[0]->toString(exec);
174 Vector<char> script;
175 if (!fillBufferWithContentsOfFile(fileName, script))
176 return throwError(exec, GeneralError, "Could not open file.");
177
178 exec->dynamicInterpreter()->evaluate(fileName, 0, script.data());
179
180 return jsUndefined();
181 }
182 case Quit:
183 exit(0);
184 default:
185 abort();
186 }
187 return 0;
188}
189
190// Use SEH for Release builds only to get rid of the crash report dialog
191// (luckily the same tests fail in Release and Debug builds so far). Need to
192// be in a separate main function because the kjsmain function requires object
193// unwinding.
194
195#if PLATFORM(WIN_OS) && !defined(_DEBUG)
196#define TRY __try {
197#define EXCEPT(x) } __except (EXCEPTION_EXECUTE_HANDLER) { x; }
198#else
199#define TRY
200#define EXCEPT(x)
201#endif
202
203int kjsmain(int argc, char** argv);
204
205int main(int argc, char** argv)
206{
207#if defined(_DEBUG) && PLATFORM(WIN_OS)
208 _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
209 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
210 _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
211 _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
212 _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
213 _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
214#endif
215
216 int res = 0;
217 TRY
218 res = kjsmain(argc, argv);
219 EXCEPT(res = 3)
220 return res;
221}
222
223static PassRefPtr<Interpreter> setupInterpreter()
224{
225 GlobalImp* global = new GlobalImp();
226 RefPtr<Interpreter> interp = new Interpreter(global);
227 // add debug() function
228 global->put(interp->globalExec(), "debug", new TestFunctionImp(TestFunctionImp::Debug, 1));
229 // add "print" for compatibility with the mozilla js shell
230 global->put(interp->globalExec(), "print", new TestFunctionImp(TestFunctionImp::Print, 1));
231 // add "quit" for compatibility with the mozilla js shell
232 global->put(interp->globalExec(), "quit", new TestFunctionImp(TestFunctionImp::Quit, 0));
233 // add "gc" for compatibility with the mozilla js shell
234 global->put(interp->globalExec(), "gc", new TestFunctionImp(TestFunctionImp::GC, 0));
235 // add "version" for compatibility with the mozilla js shell
236 global->put(interp->globalExec(), "version", new TestFunctionImp(TestFunctionImp::Version, 1));
237 global->put(interp->globalExec(), "run", new TestFunctionImp(TestFunctionImp::Run, 1));
238 global->put(interp->globalExec(), "load", new TestFunctionImp(TestFunctionImp::Load, 1));
239
240 Interpreter::setShouldPrintExceptions(true);
241 return interp.release();
242}
243
244static bool prettyPrintScript(const UString& fileName, const Vector<char>& script)
245{
246 int errLine = 0;
247 UString errMsg;
248 UString s = Parser::prettyPrint(script.data(), &errLine, &errMsg);
249 if (s.isNull()) {
250 fprintf(stderr, "%s:%d: %s.\n", fileName.UTF8String().c_str(), errLine, errMsg.UTF8String().c_str());
251 return false;
252 }
253
254 printf("%s\n", s.UTF8String().c_str());
255 return true;
256}
257
258static bool runWithScripts(const Vector<UString>& fileNames, bool prettyPrint)
259{
260 RefPtr<Interpreter> interp = setupInterpreter();
261 Vector<char> script;
262
263 bool success = true;
264
265 for (size_t i = 0; i < fileNames.size(); i++) {
266 UString fileName = fileNames[i];
267
268 if (!fillBufferWithContentsOfFile(fileName, script))
269 return false; // fail early so we can catch missing files
270
271 if (prettyPrint)
272 prettyPrintScript(fileName, script);
273 else {
274 Completion completion = interp->evaluate(fileName, 0, script.data());
275 success = success && completion.complType() != Throw;
276 }
277 }
278 return success;
279}
280
281static void parseArguments(int argc, char** argv, Vector<UString>& fileNames, bool& prettyPrint)
282{
283 if (argc < 2) {
284 fprintf(stderr, "Usage: testkjs file1 [file2...]\n");
285 exit(-1);
286 }
287
288 for (int i = 1; i < argc; i++) {
289 const char* fileName = argv[i];
290 if (strcmp(fileName, "-f") == 0) // mozilla test driver script uses "-f" prefix for files
291 continue;
292 if (strcmp(fileName, "-p") == 0) {
293 prettyPrint = true;
294 continue;
295 }
296 fileNames.append(fileName);
297 }
298}
299
300int kjsmain(int argc, char** argv)
301{
302 testIsInteger();
303
304 JSLock lock;
305
306 bool prettyPrint = false;
307 Vector<UString> fileNames;
308 parseArguments(argc, argv, fileNames, prettyPrint);
309
310 bool success = runWithScripts(fileNames, prettyPrint);
311
312#ifndef NDEBUG
313 Collector::collect();
314#endif
315
316#ifdef KJS_DEBUG_MEM
317 Interpreter::finalCheck();
318#endif
319 return success ? 0 : 3;
320}
321
322static void testIsInteger()
323{
324 // Unit tests for WTF::IsInteger. Don't have a better place for them now.
325 // FIXME: move these once we create a unit test directory for WTF.
326
327 ASSERT(IsInteger<bool>::value);
328 ASSERT(IsInteger<char>::value);
329 ASSERT(IsInteger<signed char>::value);
330 ASSERT(IsInteger<unsigned char>::value);
331 ASSERT(IsInteger<short>::value);
332 ASSERT(IsInteger<unsigned short>::value);
333 ASSERT(IsInteger<int>::value);
334 ASSERT(IsInteger<unsigned int>::value);
335 ASSERT(IsInteger<long>::value);
336 ASSERT(IsInteger<unsigned long>::value);
337 ASSERT(IsInteger<long long>::value);
338 ASSERT(IsInteger<unsigned long long>::value);
339
340 ASSERT(!IsInteger<char*>::value);
341 ASSERT(!IsInteger<const char* >::value);
342 ASSERT(!IsInteger<volatile char* >::value);
343 ASSERT(!IsInteger<double>::value);
344 ASSERT(!IsInteger<float>::value);
345 ASSERT(!IsInteger<GlobalImp>::value);
346}
347
348static bool fillBufferWithContentsOfFile(const UString& fileName, Vector<char>& buffer)
349{
350 FILE* f = fopen(fileName.UTF8String().c_str(), "r");
351 if (!f) {
352 fprintf(stderr, "Could not open file: %s\n", fileName.UTF8String().c_str());
353 return false;
354 }
355
356 size_t buffer_size = 0;
357 size_t buffer_capacity = 1024;
358
359 buffer.resize(buffer_capacity);
360
361 while (!feof(f) && !ferror(f)) {
362 buffer_size += fread(buffer.data() + buffer_size, 1, buffer_capacity - buffer_size, f);
363 if (buffer_size == buffer_capacity) { // guarantees space for trailing '\0'
364 buffer_capacity *= 2;
365 buffer.resize(buffer_capacity);
366 }
367 }
368 fclose(f);
369 buffer[buffer_size] = '\0';
370
371 return true;
372}
Note: See TracBrowser for help on using the repository browser.