28 #ifndef V8_JSON_PARSER_H_
29 #define V8_JSON_PARSER_H_
43 template <
bool seq_ascii>
47 return JsonParser().ParseJson(source, zone);
50 static const int kEndOfString = -1;
56 inline void Advance() {
58 if (position_ >= source_length_) {
60 }
else if (seq_ascii) {
61 c0_ = seq_source_->SeqAsciiStringGet(position_);
63 c0_ = source_->Get(position_);
71 inline void AdvanceSkipWhitespace() {
74 }
while (c0_ ==
' ' || c0_ ==
'\t' || c0_ ==
'\n' || c0_ ==
'\r');
77 inline void SkipWhitespace() {
78 while (c0_ ==
' ' || c0_ ==
'\t' || c0_ ==
'\n' || c0_ ==
'\r') {
83 inline uc32 AdvanceGetChar() {
90 inline bool MatchSkipWhiteSpace(
uc32 c) {
92 AdvanceSkipWhitespace();
102 Handle<String> ParseJsonString() {
103 return ScanJsonString<false>();
105 Handle<String> ParseJsonSymbol() {
106 return ScanJsonString<true>();
108 template <
bool is_symbol>
109 Handle<String> ScanJsonString();
113 template <
typename StringType,
typename SinkChar>
114 Handle<String> SlowScanJsonString(Handle<String> prefix,
int start,
int end);
122 Handle<Object> ParseJsonNumber();
127 Handle<Object> ParseJsonValue();
135 Handle<Object> ParseJsonObject();
142 Handle<Object> ParseJsonArray();
147 inline Handle<Object> ReportUnexpectedCharacter() {
151 inline Isolate* isolate() {
return isolate_; }
152 inline Factory* factory() {
return factory_; }
153 inline Handle<JSFunction> object_constructor() {
return object_constructor_; }
154 inline Zone* zone()
const {
return zone_; }
156 static const int kInitialSpecialStringLength = 1024;
160 Handle<String> source_;
162 Handle<SeqAsciiString> seq_source_;
166 Handle<JSFunction> object_constructor_;
172 template <
bool seq_ascii>
173 Handle<Object> JsonParser<seq_ascii>::ParseJson(Handle<String> source,
175 isolate_ = source->map()->GetHeap()->isolate();
176 factory_ = isolate_->factory();
177 object_constructor_ =
178 Handle<JSFunction>(isolate()->native_context()->object_function());
182 source_length_ = source_->length();
192 AdvanceSkipWhitespace();
193 Handle<Object> result = ParseJsonValue();
194 if (result.is_null() || c0_ != kEndOfString) {
198 Factory* factory = this->factory();
199 Handle<JSArray> array;
203 message =
"unexpected_eos";
204 array = factory->NewJSArray(0);
217 message =
"unexpected_token_number";
218 array = factory->NewJSArray(0);
221 message =
"unexpected_token_string";
222 array = factory->NewJSArray(0);
225 message =
"unexpected_token";
227 Handle<FixedArray> element = factory->NewFixedArray(1);
228 element->set(0, *name);
229 array = factory->NewJSArrayWithElements(element);
233 MessageLocation location(factory->NewScript(source),
236 Handle<Object> result = factory->NewSyntaxError(message, array);
237 isolate()->Throw(*result, &location);
245 template <
bool seq_ascii>
246 Handle<Object> JsonParser<seq_ascii>::ParseJsonValue() {
247 if (c0_ ==
'"')
return ParseJsonString();
248 if ((c0_ >=
'0' && c0_ <=
'9') || c0_ ==
'-')
return ParseJsonNumber();
249 if (c0_ ==
'{')
return ParseJsonObject();
250 if (c0_ ==
'[')
return ParseJsonArray();
252 if (AdvanceGetChar() ==
'a' && AdvanceGetChar() ==
'l' &&
253 AdvanceGetChar() ==
's' && AdvanceGetChar() ==
'e') {
254 AdvanceSkipWhitespace();
255 return factory()->false_value();
257 return ReportUnexpectedCharacter();
260 if (AdvanceGetChar() ==
'r' && AdvanceGetChar() ==
'u' &&
261 AdvanceGetChar() ==
'e') {
262 AdvanceSkipWhitespace();
263 return factory()->true_value();
265 return ReportUnexpectedCharacter();
268 if (AdvanceGetChar() ==
'u' && AdvanceGetChar() ==
'l' &&
269 AdvanceGetChar() ==
'l') {
270 AdvanceSkipWhitespace();
271 return factory()->null_value();
273 return ReportUnexpectedCharacter();
275 return ReportUnexpectedCharacter();
280 template <
bool seq_ascii>
281 Handle<Object> JsonParser<seq_ascii>::ParseJsonObject() {
282 Handle<Object> prototype;
283 Handle<JSObject> json_object =
284 factory()->NewJSObject(object_constructor());
287 AdvanceSkipWhitespace();
290 if (c0_ !=
'"')
return ReportUnexpectedCharacter();
292 int start_position = position_;
296 while (c0_ >=
'0' && c0_ <=
'9') {
298 if (index > 429496729
U - ((d > 5) ? 1 : 0))
break;
299 index = (index * 10) + d;
303 if (position_ != start_position + 1 && c0_ ==
'"') {
304 AdvanceSkipWhitespace();
306 if (c0_ !=
':')
return ReportUnexpectedCharacter();
307 AdvanceSkipWhitespace();
308 Handle<Object> value = ParseJsonValue();
309 if (value.is_null())
return ReportUnexpectedCharacter();
313 position_ = start_position;
318 Handle<String> key = ParseJsonSymbol();
319 if (key.is_null() || c0_ !=
':')
return ReportUnexpectedCharacter();
321 AdvanceSkipWhitespace();
322 Handle<Object> value = ParseJsonValue();
323 if (value.is_null())
return ReportUnexpectedCharacter();
325 if (key->Equals(isolate()->heap()->Proto_symbol())) {
329 int index = json_object->LastAddedFieldIndex();
330 json_object->FastPropertyAtPut(index, *value);
333 json_object, key, value,
NONE);
337 }
while (MatchSkipWhiteSpace(
','));
339 return ReportUnexpectedCharacter();
341 if (!prototype.is_null())
SetPrototype(json_object, prototype);
343 AdvanceSkipWhitespace();
348 template <
bool seq_ascii>
349 Handle<Object> JsonParser<seq_ascii>::ParseJsonArray() {
351 ZoneList<Handle<Object> > elements(4, zone());
354 AdvanceSkipWhitespace();
357 Handle<Object> element = ParseJsonValue();
358 if (element.is_null())
return ReportUnexpectedCharacter();
359 elements.Add(element, zone());
360 }
while (MatchSkipWhiteSpace(
','));
362 return ReportUnexpectedCharacter();
365 AdvanceSkipWhitespace();
367 Handle<FixedArray> fast_elements =
368 factory()->NewFixedArray(elements.length());
369 for (
int i = 0, n = elements.length(); i < n; i++) {
370 fast_elements->set(i, *elements[i]);
372 return factory()->NewJSArrayWithElements(fast_elements);
376 template <
bool seq_ascii>
377 Handle<Object> JsonParser<seq_ascii>::ParseJsonNumber() {
379 int beg_pos = position_;
388 if (
'0' <= c0_ && c0_ <=
'9')
return ReportUnexpectedCharacter();
392 if (c0_ < '1' || c0_ >
'9')
return ReportUnexpectedCharacter();
394 i = i * 10 + c0_ -
'0';
397 }
while (c0_ >=
'0' && c0_ <=
'9');
398 if (c0_ !=
'.' && c0_ !=
'e' && c0_ !=
'E' && digits < 10) {
400 return Handle<Smi>(
Smi::FromInt((negative ? -i : i)), isolate());
405 if (c0_ < '0' || c0_ >
'9')
return ReportUnexpectedCharacter();
408 }
while (c0_ >=
'0' && c0_ <=
'9');
412 if (c0_ ==
'-' || c0_ ==
'+') Advance();
413 if (c0_ < '0' || c0_ >
'9')
return ReportUnexpectedCharacter();
416 }
while (c0_ >=
'0' && c0_ <=
'9');
418 int length = position_ - beg_pos;
421 Vector<const char> chars(seq_source_->GetChars() + beg_pos, length);
429 Vector<const char> result =
430 Vector<const char>(
reinterpret_cast<const char*
>(buffer.start()),
439 return factory()->NewNumber(number);
443 template <
typename StringType>
448 seq_str->SeqTwoByteStringSet(i, c);
453 seq_str->SeqAsciiStringSet(i, c);
456 template <
typename StringType>
473 template <
bool seq_ascii>
474 template <
typename StringType,
typename SinkChar>
477 int count = end - start;
478 int max_length = count + source_length_ - position_;
479 int length = Min(max_length, Max(kInitialSpecialStringLength, 2 * count));
482 SinkChar* dest = seq_str->GetChars();
488 if (count >= length) {
490 return SlowScanJsonString<StringType, SinkChar>(seq_str, 0, count);
504 return SlowScanJsonString<SeqTwoByteString, uc16>(seq_str, 0, count);
531 for (
int i = 0; i < 4; i++) {
537 value = value * 16 + digit;
546 return SlowScanJsonString<SeqTwoByteString, uc16>(seq_str,
558 if (isolate()->heap()->InNewSpace(*seq_str)) {
559 isolate()->heap()->new_space()->
560 template ShrinkStringAtAllocationBoundary<StringType>(
563 int string_size = StringType::SizeFor(count);
564 int allocated_string_size = StringType::SizeFor(length);
565 int delta = allocated_string_size - string_size;
566 Address start_filler_object = seq_str->address() + string_size;
567 seq_str->set_length(count);
568 isolate()->heap()->CreateFillerObjectAt(start_filler_object, delta);
572 AdvanceSkipWhitespace();
577 template <
bool seq_ascii>
578 template <
bool is_symbol>
579 Handle<String> JsonParser<seq_ascii>::ScanJsonString() {
583 AdvanceSkipWhitespace();
584 return Handle<String>(isolate()->heap()->empty_string());
587 if (seq_ascii && is_symbol) {
591 uint32_t running_hash = isolate()->heap()->HashSeed();
592 int position = position_;
597 int beg_pos = position_;
598 position_ = position;
599 return SlowScanJsonString<SeqAsciiString, char>(source_,
604 running_hash = StringHasher::AddCharacterCore(running_hash, c0);
607 c0 = seq_source_->SeqAsciiStringGet(position);
609 int length = position - position_;
611 ? StringHasher::GetHashCore(running_hash) : length;
612 Vector<const char> string_vector(
613 seq_source_->GetChars() + position_, length);
614 SymbolTable* symbol_table = isolate()->heap()->symbol_table();
615 uint32_t capacity = symbol_table->Capacity();
619 Object* element = symbol_table->KeyAt(entry);
620 if (element == isolate()->heap()->raw_unchecked_undefined_value()) {
624 if (element != isolate()->heap()->raw_unchecked_the_hole_value() &&
627 position_ = position;
629 AdvanceSkipWhitespace();
636 int beg_pos = position_;
645 return SlowScanJsonString<SeqTwoByteString, uc16>(source_,
650 return SlowScanJsonString<SeqAsciiString, char>(source_,
654 }
while (c0_ !=
'"');
655 int length = position_ - beg_pos;
656 Handle<String> result;
657 if (seq_ascii && is_symbol) {
658 result = factory()->LookupAsciiSymbol(seq_source_,
662 result = factory()->NewRawAsciiString(length);
668 AdvanceSkipWhitespace();
674 #endif // V8_JSON_PARSER_H_
void FlattenString(Handle< String > string)
static String * cast(Object *obj)
static Smi * FromInt(int value)
Handle< SeqAsciiString > NewRawAsciiString(int length, PretenureFlag pretenure=NOT_TENURED)
static Handle< T > cast(Handle< S > that)
static const int kMaxHashCalcLength
int AsciiAlphaToLower(uc32 c)
static bool TryTransitionToField(Handle< JSObject > object, Handle< String > key)
static Handle< Object > SetOwnElement(Handle< JSObject > object, uint32_t index, Handle< Object > value, StrictModeFlag strict_mode)
double StringToDouble(UnicodeCache *unicode_cache, const char *str, int flags, double empty_string_val)
static Handle< Object > Parse(Handle< String > source, Zone *zone)
Handle< SeqTwoByteString > NewRawTwoByteString(int length, PretenureFlag pretenure=NOT_TENURED)
Handle< Object > LookupSingleCharacterStringFromCode(uint32_t index)
static SeqAsciiString * cast(Object *obj)
static Handle< Object > SetLocalPropertyIgnoreAttributes(Handle< JSObject > object, Handle< String > key, Handle< Object > value, PropertyAttributes attributes)
static Vector< T > New(int length)
static void WriteToFlat(String *source, sinkchar *sink, int from, int to)
static double nan_value()
static Handle< T > null()
#define ASSERT_EQ(v1, v2)
Handle< StringType > NewRawString(Factory *factory, int length)
activate correct semantics for inheriting readonliness enable harmony semantics for typeof enable harmony enable harmony proxies enable all harmony harmony_scoping harmony_proxies harmony_scoping tracks arrays with only smi values automatically unbox arrays of doubles use crankshaft use hydrogen range analysis use hydrogen global value numbering use function inlining maximum number of AST nodes considered for a single inlining loop invariant code motion print statistics for hydrogen trace generated IR for specified phases trace register allocator trace range analysis trace representation types environment for every instruction put a break point before deoptimizing polymorphic inlining perform array bounds checks elimination use dead code elimination trace on stack replacement optimize closures cache optimized code for closures functions with arguments object loop weight for representation inference allow uint32 values on optimize frames if they are used only in safe operations track parallel recompilation enable all profiler experiments number of stack frames inspected by the profiler call recompile stub directly when self optimizing trigger profiler ticks based on counting instead of timing weight back edges by jump distance for interrupt triggering percentage of ICs that must have type info to allow optimization watch_ic_patching retry_self_opt interrupt_at_exit extra verbose compilation tracing generate extra emit comments in code disassembly enable use of SSE3 instructions if available enable use of CMOV instruction if available enable use of SAHF instruction if enable use of VFP3 instructions if available this implies enabling ARMv7 and VFP2 enable use of VFP2 instructions if available enable use of SDIV and UDIV instructions if enable loading bit constant by means of movw movt instruction enable unaligned accesses for enable use of MIPS FPU instructions if expose natives in global object expose gc extension number of stack frames to capture disable builtin natives files print a stack trace if an assertion failure occurs use random jit cookie to mask large constants trace lazy optimization use adaptive optimizations prepare for turning on always opt minimum length for automatic enable preparsing maximum number of optimization attempts before giving up cache prototype transitions automatically set the debug break flag when debugger commands are in the queue always cause a debug break before aborting maximum length of function source code printed in a stack trace max size of the new max size of the old max size of executable always perform global GCs print one trace line following each garbage collection do not print trace line after scavenger collection print more details following each garbage collection print amount of external allocated memory after each time it is adjusted flush code that we expect not to use again before full gc do incremental marking steps track object counts and memory usage use caching Perform compaction on every full GC Never perform compaction on full GC testing only Compact code space on full incremental collections Default seed for initializing random allows verbose printing trace parsing and preparsing Check icache flushes in ARM and MIPS simulator Stack alingment in bytes in print stack trace when throwing exceptions randomize hashes to avoid predictable hash Fixed seed to use to hash property activate a timer that switches between V8 threads testing_bool_flag float flag Seed used for threading test randomness A filename with extra code to be included in the Print usage message
static uint32_t NextProbe(uint32_t last, uint32_t number, uint32_t size)
Handle< Object > SetPrototype(Handle< JSFunction > function, Handle< Object > prototype)
static uint32_t FirstProbe(uint32_t hash, uint32_t size)
void SeqStringSet(Handle< StringType > seq_str, int i, uc32 c)
const uc32 kMaxAsciiCharCode