1 // Copyright 2011 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "src/parsing/scanner-character-streams.h"
6
7 #include "include/v8.h"
8 #include "src/globals.h"
9 #include "src/handles.h"
10 #include "src/objects-inl.h"
11 #include "src/parsing/scanner.h"
12 #include "src/unicode-inl.h"
13
14 namespace v8 {
15 namespace internal {
16
17 namespace {
18 const unibrow::uchar kUtf8Bom = 0xfeff;
19 } // namespace
20
21 // ----------------------------------------------------------------------------
22 // BufferedUtf16CharacterStreams
23 //
24 // A buffered character stream based on a random access character
25 // source (ReadBlock can be called with pos() pointing to any position,
26 // even positions before the current).
27 class BufferedUtf16CharacterStream : public Utf16CharacterStream {
28 public:
29 BufferedUtf16CharacterStream();
30
31 protected:
32 static const size_t kBufferSize = 512;
33
34 bool ReadBlock() override;
35
36 // FillBuffer should read up to kBufferSize characters at position and store
37 // them into buffer_[0..]. It returns the number of characters stored.
38 virtual size_t FillBuffer(size_t position) = 0;
39
40 // Fixed sized buffer that this class reads from.
41 // The base class' buffer_start_ should always point to buffer_.
42 uc16 buffer_[kBufferSize];
43 };
44
BufferedUtf16CharacterStream()45 BufferedUtf16CharacterStream::BufferedUtf16CharacterStream()
46 : Utf16CharacterStream(buffer_, buffer_, buffer_, 0) {}
47
ReadBlock()48 bool BufferedUtf16CharacterStream::ReadBlock() {
49 DCHECK_EQ(buffer_start_, buffer_);
50
51 size_t position = pos();
52 buffer_pos_ = position;
53 buffer_cursor_ = buffer_;
54 buffer_end_ = buffer_ + FillBuffer(position);
55 DCHECK_EQ(pos(), position);
56 DCHECK_LE(buffer_end_, buffer_start_ + kBufferSize);
57 return buffer_cursor_ < buffer_end_;
58 }
59
60 // ----------------------------------------------------------------------------
61 // GenericStringUtf16CharacterStream.
62 //
63 // A stream w/ a data source being a (flattened) Handle<String>.
64
65 class GenericStringUtf16CharacterStream : public BufferedUtf16CharacterStream {
66 public:
67 GenericStringUtf16CharacterStream(Handle<String> data, size_t start_position,
68 size_t end_position);
69
70 protected:
71 size_t FillBuffer(size_t position) override;
72
73 Handle<String> string_;
74 size_t length_;
75 };
76
GenericStringUtf16CharacterStream(Handle<String> data,size_t start_position,size_t end_position)77 GenericStringUtf16CharacterStream::GenericStringUtf16CharacterStream(
78 Handle<String> data, size_t start_position, size_t end_position)
79 : string_(data), length_(end_position) {
80 DCHECK_GE(end_position, start_position);
81 DCHECK_GE(static_cast<size_t>(string_->length()),
82 end_position - start_position);
83 buffer_pos_ = start_position;
84 }
85
FillBuffer(size_t from_pos)86 size_t GenericStringUtf16CharacterStream::FillBuffer(size_t from_pos) {
87 if (from_pos >= length_) return 0;
88
89 size_t length = i::Min(kBufferSize, length_ - from_pos);
90 String::WriteToFlat<uc16>(*string_, buffer_, static_cast<int>(from_pos),
91 static_cast<int>(from_pos + length));
92 return length;
93 }
94
95 // ----------------------------------------------------------------------------
96 // ExternalTwoByteStringUtf16CharacterStream.
97 //
98 // A stream whose data source is a Handle<ExternalTwoByteString>. It avoids
99 // all data copying.
100
101 class ExternalTwoByteStringUtf16CharacterStream : public Utf16CharacterStream {
102 public:
103 ExternalTwoByteStringUtf16CharacterStream(Handle<ExternalTwoByteString> data,
104 size_t start_position,
105 size_t end_position);
106
107 private:
108 bool ReadBlock() override;
109
110 const uc16* raw_data_; // Pointer to the actual array of characters.
111 size_t start_pos_;
112 size_t end_pos_;
113 };
114
115 ExternalTwoByteStringUtf16CharacterStream::
ExternalTwoByteStringUtf16CharacterStream(Handle<ExternalTwoByteString> data,size_t start_position,size_t end_position)116 ExternalTwoByteStringUtf16CharacterStream(
117 Handle<ExternalTwoByteString> data, size_t start_position,
118 size_t end_position)
119 : raw_data_(data->GetTwoByteData(static_cast<int>(start_position))),
120 start_pos_(start_position),
121 end_pos_(end_position) {
122 buffer_start_ = raw_data_;
123 buffer_cursor_ = raw_data_;
124 buffer_end_ = raw_data_ + (end_pos_ - start_pos_);
125 buffer_pos_ = start_pos_;
126 }
127
ReadBlock()128 bool ExternalTwoByteStringUtf16CharacterStream::ReadBlock() {
129 size_t position = pos();
130 bool have_data = start_pos_ <= position && position < end_pos_;
131 if (have_data) {
132 buffer_pos_ = start_pos_;
133 buffer_cursor_ = raw_data_ + (position - start_pos_),
134 buffer_end_ = raw_data_ + (end_pos_ - start_pos_);
135 } else {
136 buffer_pos_ = position;
137 buffer_cursor_ = raw_data_;
138 buffer_end_ = raw_data_;
139 }
140 return have_data;
141 }
142
143 // ----------------------------------------------------------------------------
144 // ExternalOneByteStringUtf16CharacterStream
145 //
146 // A stream whose data source is a Handle<ExternalOneByteString>.
147
148 class ExternalOneByteStringUtf16CharacterStream
149 : public BufferedUtf16CharacterStream {
150 public:
151 ExternalOneByteStringUtf16CharacterStream(Handle<ExternalOneByteString> data,
152 size_t start_position,
153 size_t end_position);
154
155 // For testing:
156 ExternalOneByteStringUtf16CharacterStream(const char* data, size_t length);
157
158 protected:
159 size_t FillBuffer(size_t position) override;
160
161 const uint8_t* raw_data_; // Pointer to the actual array of characters.
162 size_t length_;
163 };
164
165 ExternalOneByteStringUtf16CharacterStream::
ExternalOneByteStringUtf16CharacterStream(Handle<ExternalOneByteString> data,size_t start_position,size_t end_position)166 ExternalOneByteStringUtf16CharacterStream(
167 Handle<ExternalOneByteString> data, size_t start_position,
168 size_t end_position)
169 : raw_data_(data->GetChars()), length_(end_position) {
170 DCHECK(end_position >= start_position);
171 buffer_pos_ = start_position;
172 }
173
174 ExternalOneByteStringUtf16CharacterStream::
ExternalOneByteStringUtf16CharacterStream(const char * data,size_t length)175 ExternalOneByteStringUtf16CharacterStream(const char* data, size_t length)
176 : raw_data_(reinterpret_cast<const uint8_t*>(data)), length_(length) {}
177
FillBuffer(size_t from_pos)178 size_t ExternalOneByteStringUtf16CharacterStream::FillBuffer(size_t from_pos) {
179 if (from_pos >= length_) return 0;
180
181 size_t length = Min(kBufferSize, length_ - from_pos);
182 i::CopyCharsUnsigned(buffer_, raw_data_ + from_pos, length);
183 return length;
184 }
185
186 // ----------------------------------------------------------------------------
187 // Utf8ExternalStreamingStream - chunked streaming of Utf-8 data.
188 //
189 // This implementation is fairly complex, since data arrives in chunks which
190 // may 'cut' arbitrarily into utf-8 characters. Also, seeking to a given
191 // character position is tricky because the byte position cannot be dericed
192 // from the character position.
193
194 class Utf8ExternalStreamingStream : public BufferedUtf16CharacterStream {
195 public:
Utf8ExternalStreamingStream(ScriptCompiler::ExternalSourceStream * source_stream)196 Utf8ExternalStreamingStream(
197 ScriptCompiler::ExternalSourceStream* source_stream)
198 : current_({0, {0, 0, unibrow::Utf8::Utf8IncrementalBuffer(0)}}),
199 source_stream_(source_stream) {}
~Utf8ExternalStreamingStream()200 ~Utf8ExternalStreamingStream() override {
201 for (size_t i = 0; i < chunks_.size(); i++) delete[] chunks_[i].data;
202 }
203
204 protected:
205 size_t FillBuffer(size_t position) override;
206
207 private:
208 // A position within the data stream. It stores:
209 // - The 'physical' position (# of bytes in the stream),
210 // - the 'logical' position (# of ucs-2 characters, also within the stream),
211 // - a possibly incomplete utf-8 char at the current 'physical' position.
212 struct StreamPosition {
213 size_t bytes;
214 size_t chars;
215 unibrow::Utf8::Utf8IncrementalBuffer incomplete_char;
216 };
217
218 // Position contains a StreamPosition and the index of the chunk the position
219 // points into. (The chunk_no could be derived from pos, but that'd be
220 // an expensive search through all chunks.)
221 struct Position {
222 size_t chunk_no;
223 StreamPosition pos;
224 };
225
226 // A chunk in the list of chunks, containing:
227 // - The chunk data (data pointer and length), and
228 // - the position at the first byte of the chunk.
229 struct Chunk {
230 const uint8_t* data;
231 size_t length;
232 StreamPosition start;
233 };
234
235 // Within the current chunk, skip forward from current_ towards position.
236 bool SkipToPosition(size_t position);
237 // Within the current chunk, fill the buffer_ (while it has capacity).
238 void FillBufferFromCurrentChunk();
239 // Fetch a new chunk (assuming current_ is at the end of the current data).
240 bool FetchChunk();
241 // Search through the chunks and set current_ to point to the given position.
242 // (This call is potentially expensive.)
243 void SearchPosition(size_t position);
244
245 std::vector<Chunk> chunks_;
246 Position current_;
247 ScriptCompiler::ExternalSourceStream* source_stream_;
248 };
249
SkipToPosition(size_t position)250 bool Utf8ExternalStreamingStream::SkipToPosition(size_t position) {
251 DCHECK_LE(current_.pos.chars, position); // We can only skip forward.
252
253 // Already there? Then return immediately.
254 if (current_.pos.chars == position) return true;
255
256 const Chunk& chunk = chunks_[current_.chunk_no];
257 DCHECK(current_.pos.bytes >= chunk.start.bytes);
258
259 unibrow::Utf8::Utf8IncrementalBuffer incomplete_char =
260 chunk.start.incomplete_char;
261 size_t it = current_.pos.bytes - chunk.start.bytes;
262 size_t chars = chunk.start.chars;
263 while (it < chunk.length && chars < position) {
264 unibrow::uchar t =
265 unibrow::Utf8::ValueOfIncremental(chunk.data[it], &incomplete_char);
266 if (t == kUtf8Bom && current_.pos.chars == 0) {
267 // BOM detected at beginning of the stream. Don't copy it.
268 } else if (t != unibrow::Utf8::kIncomplete) {
269 chars++;
270 if (t > unibrow::Utf16::kMaxNonSurrogateCharCode) chars++;
271 }
272 it++;
273 }
274
275 current_.pos.bytes += it;
276 current_.pos.chars = chars;
277 current_.pos.incomplete_char = incomplete_char;
278 current_.chunk_no += (it == chunk.length);
279
280 return current_.pos.chars == position;
281 }
282
FillBufferFromCurrentChunk()283 void Utf8ExternalStreamingStream::FillBufferFromCurrentChunk() {
284 DCHECK_LT(current_.chunk_no, chunks_.size());
285 DCHECK_EQ(buffer_start_, buffer_cursor_);
286 DCHECK_LT(buffer_end_ + 1, buffer_start_ + kBufferSize);
287
288 const Chunk& chunk = chunks_[current_.chunk_no];
289
290 // The buffer_ is writable, but buffer_*_ members are const. So we get a
291 // non-const pointer into buffer that points to the same char as buffer_end_.
292 uint16_t* cursor = buffer_ + (buffer_end_ - buffer_start_);
293 DCHECK_EQ(cursor, buffer_end_);
294
295 // If the current chunk is the last (empty) chunk we'll have to process
296 // any left-over, partial characters.
297 if (chunk.length == 0) {
298 unibrow::uchar t =
299 unibrow::Utf8::ValueOfIncrementalFinish(¤t_.pos.incomplete_char);
300 if (t != unibrow::Utf8::kBufferEmpty) {
301 DCHECK(t < unibrow::Utf16::kMaxNonSurrogateCharCode);
302 *cursor = static_cast<uc16>(t);
303 buffer_end_++;
304 current_.pos.chars++;
305 }
306 return;
307 }
308
309 unibrow::Utf8::Utf8IncrementalBuffer incomplete_char =
310 current_.pos.incomplete_char;
311 size_t it;
312 for (it = current_.pos.bytes - chunk.start.bytes;
313 it < chunk.length && cursor + 1 < buffer_start_ + kBufferSize; it++) {
314 unibrow::uchar t =
315 unibrow::Utf8::ValueOfIncremental(chunk.data[it], &incomplete_char);
316 if (t == unibrow::Utf8::kIncomplete) continue;
317 if (V8_LIKELY(t < kUtf8Bom)) {
318 *(cursor++) = static_cast<uc16>(t); // The by most frequent case.
319 } else if (t == kUtf8Bom && current_.pos.bytes + it == 2) {
320 // BOM detected at beginning of the stream. Don't copy it.
321 } else if (t <= unibrow::Utf16::kMaxNonSurrogateCharCode) {
322 *(cursor++) = static_cast<uc16>(t);
323 } else {
324 *(cursor++) = unibrow::Utf16::LeadSurrogate(t);
325 *(cursor++) = unibrow::Utf16::TrailSurrogate(t);
326 }
327 }
328
329 current_.pos.bytes = chunk.start.bytes + it;
330 current_.pos.chars += (cursor - buffer_end_);
331 current_.pos.incomplete_char = incomplete_char;
332 current_.chunk_no += (it == chunk.length);
333
334 buffer_end_ = cursor;
335 }
336
FetchChunk()337 bool Utf8ExternalStreamingStream::FetchChunk() {
338 DCHECK_EQ(current_.chunk_no, chunks_.size());
339 DCHECK(chunks_.empty() || chunks_.back().length != 0);
340
341 const uint8_t* chunk = nullptr;
342 size_t length = source_stream_->GetMoreData(&chunk);
343 chunks_.push_back({chunk, length, current_.pos});
344 return length > 0;
345 }
346
SearchPosition(size_t position)347 void Utf8ExternalStreamingStream::SearchPosition(size_t position) {
348 // If current_ already points to the right position, we're done.
349 //
350 // This is expected to be the common case, since we typically call
351 // FillBuffer right after the current buffer.
352 if (current_.pos.chars == position) return;
353
354 // No chunks. Fetch at least one, so we can assume !chunks_.empty() below.
355 if (chunks_.empty()) {
356 DCHECK_EQ(current_.chunk_no, 0u);
357 DCHECK_EQ(current_.pos.bytes, 0u);
358 DCHECK_EQ(current_.pos.chars, 0u);
359 FetchChunk();
360 }
361
362 // Search for the last chunk whose start position is less or equal to
363 // position.
364 size_t chunk_no = chunks_.size() - 1;
365 while (chunk_no > 0 && chunks_[chunk_no].start.chars > position) {
366 chunk_no--;
367 }
368
369 // Did we find the terminating (zero-length) chunk? Then we're seeking
370 // behind the end of the data, and position does not exist.
371 // Set current_ to point to the terminating chunk.
372 if (chunks_[chunk_no].length == 0) {
373 current_ = {chunk_no, chunks_[chunk_no].start};
374 return;
375 }
376
377 // Did we find the non-last chunk? Then our position must be within chunk_no.
378 if (chunk_no + 1 < chunks_.size()) {
379 // Fancy-pants optimization for ASCII chunks within a utf-8 stream.
380 // (Many web sites declare utf-8 encoding, but use only (or almost only) the
381 // ASCII subset for their JavaScript sources. We can exploit this, by
382 // checking whether the # bytes in a chunk are equal to the # chars, and if
383 // so avoid the expensive SkipToPosition.)
384 bool ascii_only_chunk =
385 (chunks_[chunk_no + 1].start.bytes - chunks_[chunk_no].start.bytes) ==
386 (chunks_[chunk_no + 1].start.chars - chunks_[chunk_no].start.chars);
387 if (ascii_only_chunk) {
388 size_t skip = position - chunks_[chunk_no].start.chars;
389 current_ = {chunk_no,
390 {chunks_[chunk_no].start.bytes + skip,
391 chunks_[chunk_no].start.chars + skip,
392 unibrow::Utf8::Utf8IncrementalBuffer(0)}};
393 } else {
394 current_ = {chunk_no, chunks_[chunk_no].start};
395 SkipToPosition(position);
396 }
397
398 // Since position was within the chunk, SkipToPosition should have found
399 // something.
400 DCHECK_EQ(position, current_.pos.chars);
401 return;
402 }
403
404 // What's left: We're in the last, non-terminating chunk. Our position
405 // may be in the chunk, but it may also be in 'future' chunks, which we'll
406 // have to obtain.
407 DCHECK_EQ(chunk_no, chunks_.size() - 1);
408 current_ = {chunk_no, chunks_[chunk_no].start};
409 bool have_more_data = true;
410 bool found = SkipToPosition(position);
411 while (have_more_data && !found) {
412 DCHECK_EQ(current_.chunk_no, chunks_.size());
413 have_more_data = FetchChunk();
414 found = have_more_data && SkipToPosition(position);
415 }
416
417 // We'll return with a postion != the desired position only if we're out
418 // of data. In that case, we'll point to the terminating chunk.
419 DCHECK_EQ(found, current_.pos.chars == position);
420 DCHECK_EQ(have_more_data, chunks_.back().length != 0);
421 DCHECK_IMPLIES(!found, !have_more_data);
422 DCHECK_IMPLIES(!found, current_.chunk_no == chunks_.size() - 1);
423 }
424
FillBuffer(size_t position)425 size_t Utf8ExternalStreamingStream::FillBuffer(size_t position) {
426 buffer_cursor_ = buffer_;
427 buffer_end_ = buffer_;
428
429 SearchPosition(position);
430 bool out_of_data = current_.chunk_no != chunks_.size() &&
431 chunks_[current_.chunk_no].length == 0;
432 if (out_of_data) return 0;
433
434 // Fill the buffer, until we have at least one char (or are out of data).
435 // (The embedder might give us 1-byte blocks within a utf-8 char, so we
436 // can't guarantee progress with one chunk. Thus we iterate.)
437 while (!out_of_data && buffer_cursor_ == buffer_end_) {
438 // At end of current data, but there might be more? Then fetch it.
439 if (current_.chunk_no == chunks_.size()) {
440 out_of_data = !FetchChunk();
441 }
442 FillBufferFromCurrentChunk();
443 }
444
445 DCHECK_EQ(current_.pos.chars - position,
446 static_cast<size_t>(buffer_end_ - buffer_cursor_));
447 return buffer_end_ - buffer_cursor_;
448 }
449
450 // ----------------------------------------------------------------------------
451 // Chunks - helper for One- + TwoByteExternalStreamingStream
452 namespace {
453
454 struct Chunk {
455 const uint8_t* data;
456 size_t byte_length;
457 size_t byte_pos;
458 };
459
460 typedef std::vector<struct Chunk> Chunks;
461
DeleteChunks(Chunks & chunks)462 void DeleteChunks(Chunks& chunks) {
463 for (size_t i = 0; i < chunks.size(); i++) delete[] chunks[i].data;
464 }
465
466 // Return the chunk index for the chunk containing position.
467 // If position is behind the end of the stream, the index of the last,
468 // zero-length chunk is returned.
FindChunk(Chunks & chunks,ScriptCompiler::ExternalSourceStream * source_,size_t position)469 size_t FindChunk(Chunks& chunks, ScriptCompiler::ExternalSourceStream* source_,
470 size_t position) {
471 size_t end_pos =
472 chunks.empty() ? 0 : (chunks.back().byte_pos + chunks.back().byte_length);
473
474 // Get more data if needed. We usually won't enter the loop body.
475 bool out_of_data = !chunks.empty() && chunks.back().byte_length == 0;
476 while (!out_of_data && end_pos <= position + 1) {
477 const uint8_t* chunk = nullptr;
478 size_t len = source_->GetMoreData(&chunk);
479
480 chunks.push_back({chunk, len, end_pos});
481 end_pos += len;
482 out_of_data = (len == 0);
483 }
484
485 // Here, we should always have at least one chunk, and we either have the
486 // chunk we were looking for, or we're out of data. Also, out_of_data and
487 // end_pos are current (and designate whether we have exhausted the stream,
488 // and the length of data received so far, respectively).
489 DCHECK(!chunks.empty());
490 DCHECK_EQ(end_pos, chunks.back().byte_pos + chunks.back().byte_length);
491 DCHECK_EQ(out_of_data, chunks.back().byte_length == 0);
492 DCHECK(position < end_pos || out_of_data);
493
494 // Edge case: position is behind the end of stream: Return the last (length 0)
495 // chunk to indicate the end of the stream.
496 if (position >= end_pos) {
497 DCHECK(out_of_data);
498 return chunks.size() - 1;
499 }
500
501 // We almost always 'stream', meaning we want data from the last chunk, so
502 // let's look at chunks back-to-front.
503 size_t chunk_no = chunks.size() - 1;
504 while (chunks[chunk_no].byte_pos > position) {
505 DCHECK_NE(chunk_no, 0u);
506 chunk_no--;
507 }
508 DCHECK_LE(chunks[chunk_no].byte_pos, position);
509 DCHECK_LT(position, chunks[chunk_no].byte_pos + chunks[chunk_no].byte_length);
510 return chunk_no;
511 }
512
513 } // anonymous namespace
514
515 // ----------------------------------------------------------------------------
516 // OneByteExternalStreamingStream
517 //
518 // A stream of latin-1 encoded, chunked data.
519
520 class OneByteExternalStreamingStream : public BufferedUtf16CharacterStream {
521 public:
OneByteExternalStreamingStream(ScriptCompiler::ExternalSourceStream * source)522 explicit OneByteExternalStreamingStream(
523 ScriptCompiler::ExternalSourceStream* source)
524 : source_(source) {}
~OneByteExternalStreamingStream()525 ~OneByteExternalStreamingStream() override { DeleteChunks(chunks_); }
526
527 protected:
528 size_t FillBuffer(size_t position) override;
529
530 private:
531 Chunks chunks_;
532 ScriptCompiler::ExternalSourceStream* source_;
533 };
534
FillBuffer(size_t position)535 size_t OneByteExternalStreamingStream::FillBuffer(size_t position) {
536 const Chunk& chunk = chunks_[FindChunk(chunks_, source_, position)];
537 if (chunk.byte_length == 0) return 0;
538
539 size_t start_pos = position - chunk.byte_pos;
540 size_t len = i::Min(kBufferSize, chunk.byte_length - start_pos);
541 i::CopyCharsUnsigned(buffer_, chunk.data + start_pos, len);
542 return len;
543 }
544
545 #if !(V8_TARGET_ARCH_MIPS || V8_TARGET_ARCH_MIPS64)
546 // ----------------------------------------------------------------------------
547 // TwoByteExternalStreamingStream
548 //
549 // A stream of ucs-2 data, delivered in chunks. Chunks may be 'cut' into the
550 // middle of characters (or even contain only one byte), which adds a bit
551 // of complexity. This stream avoid all data copying, except for characters
552 // that cross chunk boundaries.
553
554 class TwoByteExternalStreamingStream : public Utf16CharacterStream {
555 public:
556 explicit TwoByteExternalStreamingStream(
557 ScriptCompiler::ExternalSourceStream* source);
558 ~TwoByteExternalStreamingStream() override;
559
560 protected:
561 bool ReadBlock() override;
562
563 Chunks chunks_;
564 ScriptCompiler::ExternalSourceStream* source_;
565 uc16 one_char_buffer_;
566 };
567
TwoByteExternalStreamingStream(ScriptCompiler::ExternalSourceStream * source)568 TwoByteExternalStreamingStream::TwoByteExternalStreamingStream(
569 ScriptCompiler::ExternalSourceStream* source)
570 : Utf16CharacterStream(&one_char_buffer_, &one_char_buffer_,
571 &one_char_buffer_, 0),
572 source_(source),
573 one_char_buffer_(0) {}
574
~TwoByteExternalStreamingStream()575 TwoByteExternalStreamingStream::~TwoByteExternalStreamingStream() {
576 DeleteChunks(chunks_);
577 }
578
ReadBlock()579 bool TwoByteExternalStreamingStream::ReadBlock() {
580 size_t position = pos();
581
582 // We'll search for the 2nd byte of our character, to make sure we
583 // have enough data for at least one character.
584 size_t chunk_no = FindChunk(chunks_, source_, 2 * position + 1);
585
586 // Out of data? Return 0.
587 if (chunks_[chunk_no].byte_length == 0) {
588 buffer_cursor_ = buffer_start_;
589 buffer_end_ = buffer_start_;
590 return false;
591 }
592
593 Chunk& current = chunks_[chunk_no];
594
595 // Annoying edge case: Chunks may not be 2-byte aligned, meaning that a
596 // character may be split between the previous and the current chunk.
597 // If we find such a lonely byte at the beginning of the chunk, we'll use
598 // one_char_buffer_ to hold the full character.
599 bool lonely_byte = (chunks_[chunk_no].byte_pos == (2 * position + 1));
600 if (lonely_byte) {
601 DCHECK_NE(chunk_no, 0u);
602 Chunk& previous_chunk = chunks_[chunk_no - 1];
603 #ifdef V8_TARGET_BIG_ENDIAN
604 uc16 character = current.data[0] |
605 previous_chunk.data[previous_chunk.byte_length - 1] << 8;
606 #else
607 uc16 character = previous_chunk.data[previous_chunk.byte_length - 1] |
608 current.data[0] << 8;
609 #endif
610
611 one_char_buffer_ = character;
612 buffer_pos_ = position;
613 buffer_start_ = &one_char_buffer_;
614 buffer_cursor_ = &one_char_buffer_;
615 buffer_end_ = &one_char_buffer_ + 1;
616 return true;
617 }
618
619 // Common case: character is in current chunk.
620 DCHECK_LE(current.byte_pos, 2 * position);
621 DCHECK_LT(2 * position + 1, current.byte_pos + current.byte_length);
622
623 // Determine # of full ucs-2 chars in stream, and whether we started on an odd
624 // byte boundary.
625 bool odd_start = (current.byte_pos % 2) == 1;
626 size_t number_chars = (current.byte_length - odd_start) / 2;
627
628 // Point the buffer_*_ members into the current chunk and set buffer_cursor_
629 // to point to position. Be careful when converting the byte positions (in
630 // Chunk) to the ucs-2 character positions (in buffer_*_ members).
631 buffer_start_ = reinterpret_cast<const uint16_t*>(current.data + odd_start);
632 buffer_end_ = buffer_start_ + number_chars;
633 buffer_pos_ = (current.byte_pos + odd_start) / 2;
634 buffer_cursor_ = buffer_start_ + (position - buffer_pos_);
635 DCHECK_EQ(position, pos());
636 return true;
637 }
638
639 #else
640
641 // ----------------------------------------------------------------------------
642 // TwoByteExternalBufferedStream
643 //
644 // This class is made specifically to address unaligned access to 16-bit data
645 // in MIPS and ARM architectures. It replaces class
646 // TwoByteExternalStreamingStream which in some cases does have unaligned
647 // accesse to 16-bit data
648
649 class TwoByteExternalBufferedStream : public Utf16CharacterStream {
650 public:
651 explicit TwoByteExternalBufferedStream(
652 ScriptCompiler::ExternalSourceStream* source);
653 ~TwoByteExternalBufferedStream();
654
655 protected:
656 static const size_t kBufferSize = 512;
657
658 bool ReadBlock() override;
659
660 // FillBuffer should read up to kBufferSize characters at position and store
661 // them into buffer_[0..]. It returns the number of characters stored.
662 size_t FillBuffer(size_t position, size_t chunk_no);
663
664 // Fixed sized buffer that this class reads from.
665 // The base class' buffer_start_ should always point to buffer_.
666 uc16 buffer_[kBufferSize];
667
668 Chunks chunks_;
669 ScriptCompiler::ExternalSourceStream* source_;
670 };
671
TwoByteExternalBufferedStream(ScriptCompiler::ExternalSourceStream * source)672 TwoByteExternalBufferedStream::TwoByteExternalBufferedStream(
673 ScriptCompiler::ExternalSourceStream* source)
674 : Utf16CharacterStream(buffer_, buffer_, buffer_, 0), source_(source) {}
675
~TwoByteExternalBufferedStream()676 TwoByteExternalBufferedStream::~TwoByteExternalBufferedStream() {
677 DeleteChunks(chunks_);
678 }
679
ReadBlock()680 bool TwoByteExternalBufferedStream::ReadBlock() {
681 size_t position = pos();
682 // Find chunk in which the position belongs
683 size_t chunk_no = FindChunk(chunks_, source_, 2 * position + 1);
684
685 // Out of data? Return 0.
686 if (chunks_[chunk_no].byte_length == 0) {
687 buffer_cursor_ = buffer_start_;
688 buffer_end_ = buffer_start_;
689 return false;
690 }
691
692 Chunk& current = chunks_[chunk_no];
693
694 bool odd_start = current.byte_pos % 2;
695 // Common case: character is in current chunk.
696 DCHECK_LE(current.byte_pos, 2 * position + odd_start);
697 DCHECK_LT(2 * position + 1, current.byte_pos + current.byte_length);
698
699 // If character starts on odd address copy text in buffer so there is always
700 // aligned access to characters. This is important on MIPS and ARM
701 // architectures. Otherwise read characters from memory directly.
702 if (!odd_start) {
703 buffer_start_ = reinterpret_cast<const uint16_t*>(current.data);
704 size_t number_chars = current.byte_length / 2;
705 buffer_end_ = buffer_start_ + number_chars;
706 buffer_pos_ = current.byte_pos / 2;
707 buffer_cursor_ = buffer_start_ + (position - buffer_pos_);
708 DCHECK_EQ(position, pos());
709 return true;
710 } else {
711 buffer_start_ = buffer_;
712 buffer_pos_ = position;
713 buffer_cursor_ = buffer_;
714 buffer_end_ = buffer_ + FillBuffer(position, chunk_no);
715 DCHECK_EQ(pos(), position);
716 DCHECK_LE(buffer_end_, buffer_start_ + kBufferSize);
717 return buffer_cursor_ < buffer_end_;
718 }
719 }
720
FillBuffer(size_t position,size_t chunk_no)721 size_t TwoByteExternalBufferedStream::FillBuffer(size_t position,
722 size_t chunk_no) {
723 DCHECK_EQ(chunks_[chunk_no].byte_pos % 2, 1u);
724 bool odd_start = true;
725 // Align buffer_pos_ to the size of the buffer.
726 {
727 size_t new_pos = position / kBufferSize * kBufferSize;
728 if (new_pos != position) {
729 chunk_no = FindChunk(chunks_, source_, 2 * new_pos + 1);
730 buffer_pos_ = new_pos;
731 buffer_cursor_ = buffer_start_ + (position - buffer_pos_);
732 position = new_pos;
733 odd_start = chunks_[chunk_no].byte_pos % 2;
734 }
735 }
736
737 Chunk* current = &chunks_[chunk_no];
738
739 // Annoying edge case: Chunks may not be 2-byte aligned, meaning that a
740 // character may be split between the previous and the current chunk.
741 // If we find such a lonely byte at the beginning of the chunk, we'll copy
742 // it to the first byte in buffer_.
743 size_t totalLength = 0;
744 bool lonely_byte = (current->byte_pos == (2 * position + 1));
745 if (lonely_byte) {
746 DCHECK_NE(chunk_no, 0u);
747 Chunk& previous_chunk = chunks_[chunk_no - 1];
748 *reinterpret_cast<uint8_t*>(buffer_) =
749 previous_chunk.data[previous_chunk.byte_length - 1];
750 totalLength++;
751 }
752
753 // Common case: character is in current chunk.
754 DCHECK_LE(current->byte_pos, 2 * position + odd_start);
755 DCHECK_LT(2 * position + 1, current->byte_pos + current->byte_length);
756
757 // Copy characters from current chunk starting from chunk_pos to the end of
758 // buffer or chunk.
759 size_t chunk_pos = position - current->byte_pos / 2;
760 size_t start_offset = odd_start && chunk_pos != 0;
761 size_t bytes_to_move =
762 i::Min(2 * kBufferSize - lonely_byte,
763 current->byte_length - 2 * chunk_pos + start_offset);
764 i::MemMove(reinterpret_cast<uint8_t*>(buffer_) + lonely_byte,
765 current->data + 2 * chunk_pos - start_offset, bytes_to_move);
766
767 // Fill up the rest of the buffer if there is space and data left.
768 totalLength += bytes_to_move;
769 position = (current->byte_pos + current->byte_length) / 2;
770 if (position - buffer_pos_ < kBufferSize) {
771 chunk_no = FindChunk(chunks_, source_, 2 * position + 1);
772 current = &chunks_[chunk_no];
773 odd_start = current->byte_pos % 2;
774 bytes_to_move = i::Min(2 * kBufferSize - totalLength, current->byte_length);
775 while (bytes_to_move) {
776 // Common case: character is in current chunk.
777 DCHECK_LE(current->byte_pos, 2 * position + odd_start);
778 DCHECK_LT(2 * position + 1, current->byte_pos + current->byte_length);
779
780 i::MemMove(reinterpret_cast<uint8_t*>(buffer_) + totalLength,
781 current->data, bytes_to_move);
782 totalLength += bytes_to_move;
783 position = (current->byte_pos + current->byte_length) / 2;
784 chunk_no = FindChunk(chunks_, source_, 2 * position + 1);
785 current = &chunks_[chunk_no];
786 odd_start = current->byte_pos % 2;
787 bytes_to_move =
788 i::Min(2 * kBufferSize - totalLength, current->byte_length);
789 }
790 }
791 return totalLength / 2;
792 }
793 #endif
794
795 // ----------------------------------------------------------------------------
796 // ScannerStream: Create stream instances.
797
For(Handle<String> data)798 Utf16CharacterStream* ScannerStream::For(Handle<String> data) {
799 return ScannerStream::For(data, 0, data->length());
800 }
801
For(Handle<String> data,int start_pos,int end_pos)802 Utf16CharacterStream* ScannerStream::For(Handle<String> data, int start_pos,
803 int end_pos) {
804 DCHECK(start_pos >= 0);
805 DCHECK(end_pos <= data->length());
806 if (data->IsExternalOneByteString()) {
807 return new ExternalOneByteStringUtf16CharacterStream(
808 Handle<ExternalOneByteString>::cast(data), start_pos, end_pos);
809 } else if (data->IsExternalTwoByteString()) {
810 return new ExternalTwoByteStringUtf16CharacterStream(
811 Handle<ExternalTwoByteString>::cast(data), start_pos, end_pos);
812 } else {
813 // TODO(vogelheim): Maybe call data.Flatten() first?
814 return new GenericStringUtf16CharacterStream(data, start_pos, end_pos);
815 }
816 }
817
ForTesting(const char * data)818 std::unique_ptr<Utf16CharacterStream> ScannerStream::ForTesting(
819 const char* data) {
820 return ScannerStream::ForTesting(data, strlen(data));
821 }
822
ForTesting(const char * data,size_t length)823 std::unique_ptr<Utf16CharacterStream> ScannerStream::ForTesting(
824 const char* data, size_t length) {
825 return std::unique_ptr<Utf16CharacterStream>(
826 new ExternalOneByteStringUtf16CharacterStream(data, length));
827 }
828
For(ScriptCompiler::ExternalSourceStream * source_stream,v8::ScriptCompiler::StreamedSource::Encoding encoding)829 Utf16CharacterStream* ScannerStream::For(
830 ScriptCompiler::ExternalSourceStream* source_stream,
831 v8::ScriptCompiler::StreamedSource::Encoding encoding) {
832 switch (encoding) {
833 case v8::ScriptCompiler::StreamedSource::TWO_BYTE:
834 #if !(V8_TARGET_ARCH_MIPS || V8_TARGET_ARCH_MIPS64)
835 return new TwoByteExternalStreamingStream(source_stream);
836 #else
837 return new TwoByteExternalBufferedStream(source_stream);
838 #endif
839 case v8::ScriptCompiler::StreamedSource::ONE_BYTE:
840 return new OneByteExternalStreamingStream(source_stream);
841 case v8::ScriptCompiler::StreamedSource::UTF8:
842 return new Utf8ExternalStreamingStream(source_stream);
843 }
844 UNREACHABLE();
845 return nullptr;
846 }
847
848 } // namespace internal
849 } // namespace v8
850