Where Online Learning is simpler!
The C and C++ Include Header Files
cat -n /usr/include/nodejs/deps/v8/include/v8-script.h
1 // Copyright 2021 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 #ifndef INCLUDE_V8_SCRIPT_H_ 6 #define INCLUDE_V8_SCRIPT_H_ 7 8 #include <stddef.h> 9 #include <stdint.h> 10 11 #include <memory> 12 #include <tuple> 13 #include <vector> 14 15 #include "v8-callbacks.h" // NOLINT(build/include_directory) 16 #include "v8-data.h" // NOLINT(build/include_directory) 17 #include "v8-local-handle.h" // NOLINT(build/include_directory) 18 #include "v8-maybe.h" // NOLINT(build/include_directory) 19 #include "v8-memory-span.h" // NOLINT(build/include_directory) 20 #include "v8-message.h" // NOLINT(build/include_directory) 21 #include "v8config.h" // NOLINT(build/include_directory) 22 23 namespace v8 { 24 25 class Function; 26 class Message; 27 class Object; 28 class PrimitiveArray; 29 class Script; 30 31 namespace internal { 32 class BackgroundDeserializeTask; 33 struct ScriptStreamingData; 34 } // namespace internal 35 36 /** 37 * A container type that holds relevant metadata for module loading. 38 * 39 * This is passed back to the embedder as part of 40 * HostImportModuleDynamicallyCallback for module loading. 41 */ 42 class V8_EXPORT ScriptOrModule { 43 public: 44 /** 45 * The name that was passed by the embedder as ResourceName to the 46 * ScriptOrigin. This can be either a v8::String or v8::Undefined. 47 */ 48 Local<Value> GetResourceName(); 49 50 /** 51 * The options that were passed by the embedder as HostDefinedOptions to 52 * the ScriptOrigin. 53 */ 54 Local<Data> HostDefinedOptions(); 55 }; 56 57 /** 58 * A compiled JavaScript script, not yet tied to a Context. 59 */ 60 class V8_EXPORT UnboundScript : public Data { 61 public: 62 /** 63 * Binds the script to the currently entered context. 64 */ 65 Local<Script> BindToCurrentContext(); 66 67 int GetId() const; 68 Local<Value> GetScriptName(); 69 70 /** 71 * Data read from magic sourceURL comments. 72 */ 73 Local<Value> GetSourceURL(); 74 /** 75 * Data read from magic sourceMappingURL comments. 76 */ 77 Local<Value> GetSourceMappingURL(); 78 79 /** 80 * Returns zero based line number of the code_pos location in the script. 81 * -1 will be returned if no information available. 82 */ 83 int GetLineNumber(int code_pos = 0); 84 85 /** 86 * Returns zero based column number of the code_pos location in the script. 87 * -1 will be returned if no information available. 88 */ 89 int GetColumnNumber(int code_pos = 0); 90 91 static const int kNoScriptId = 0; 92 }; 93 94 /** 95 * A compiled JavaScript module, not yet tied to a Context. 96 */ 97 class V8_EXPORT UnboundModuleScript : public Data { 98 public: 99 /** 100 * Data read from magic sourceURL comments. 101 */ 102 Local<Value> GetSourceURL(); 103 /** 104 * Data read from magic sourceMappingURL comments. 105 */ 106 Local<Value> GetSourceMappingURL(); 107 }; 108 109 /** 110 * A location in JavaScript source. 111 */ 112 class V8_EXPORT Location { 113 public: 114 int GetLineNumber() { return line_number_; } 115 int GetColumnNumber() { return column_number_; } 116 117 Location(int line_number, int column_number) 118 : line_number_(line_number), column_number_(column_number) {} 119 120 private: 121 int line_number_; 122 int column_number_; 123 }; 124 125 class V8_EXPORT ModuleRequest : public Data { 126 public: 127 /** 128 * Returns the module specifier for this ModuleRequest. 129 */ 130 Local<String> GetSpecifier() const; 131 132 /** 133 * Returns the source code offset of this module request. 134 * Use Module::SourceOffsetToLocation to convert this to line/column numbers. 135 */ 136 int GetSourceOffset() const; 137 138 /** 139 * Contains the import attributes for this request in the form: 140 * [key1, value1, source_offset1, key2, value2, source_offset2, ...]. 141 * The keys and values are of type v8::String, and the source offsets are of 142 * type Int32. Use Module::SourceOffsetToLocation to convert the source 143 * offsets to Locations with line/column numbers. 144 * 145 * All attributes present in the module request will be supplied in this 146 * list, regardless of whether they are supported by the host. Per 147 * https://tc39.es/proposal-import-attributes/#sec-hostgetsupportedimportattributes, 148 * hosts are expected to throw for attributes that they do not support (as 149 * opposed to, for example, ignoring them). 150 */ 151 Local<FixedArray> GetImportAttributes() const; 152 153 V8_DEPRECATE_SOON("Use GetImportAttributes instead") 154 Local<FixedArray> GetImportAssertions() const { 155 return GetImportAttributes(); 156 } 157 158 V8_INLINE static ModuleRequest* Cast(Data* data); 159 160 private: 161 static void CheckCast(Data* obj); 162 }; 163 164 /** 165 * A compiled JavaScript module. 166 */ 167 class V8_EXPORT Module : public Data { 168 public: 169 /** 170 * The different states a module can be in. 171 * 172 * This corresponds to the states used in ECMAScript except that "evaluated" 173 * is split into kEvaluated and kErrored, indicating success and failure, 174 * respectively. 175 */ 176 enum Status { 177 kUninstantiated, 178 kInstantiating, 179 kInstantiated, 180 kEvaluating, 181 kEvaluated, 182 kErrored 183 }; 184 185 /** 186 * Returns the module's current status. 187 */ 188 Status GetStatus() const; 189 190 /** 191 * For a module in kErrored status, this returns the corresponding exception. 192 */ 193 Local<Value> GetException() const; 194 195 /** 196 * Returns the ModuleRequests for this module. 197 */ 198 Local<FixedArray> GetModuleRequests() const; 199 200 /** 201 * For the given source text offset in this module, returns the corresponding 202 * Location with line and column numbers. 203 */ 204 Location SourceOffsetToLocation(int offset) const; 205 206 /** 207 * Returns the identity hash for this object. 208 */ 209 int GetIdentityHash() const; 210 211 using ResolveModuleCallback = MaybeLocal<Module> (*)( 212 Local<Context> context, Local<String> specifier, 213 Local<FixedArray> import_assertions, Local<Module> referrer); 214 215 /** 216 * Instantiates the module and its dependencies. 217 * 218 * Returns an empty Maybe<bool> if an exception occurred during 219 * instantiation. (In the case where the callback throws an exception, that 220 * exception is propagated.) 221 */ 222 V8_WARN_UNUSED_RESULT Maybe<bool> InstantiateModule( 223 Local<Context> context, ResolveModuleCallback callback); 224 225 /** 226 * Evaluates the module and its dependencies. 227 * 228 * If status is kInstantiated, run the module's code and return a Promise 229 * object. On success, set status to kEvaluated and resolve the Promise with 230 * the completion value; on failure, set status to kErrored and reject the 231 * Promise with the error. 232 * 233 * If IsGraphAsync() is false, the returned Promise is settled. 234 */ 235 V8_WARN_UNUSED_RESULT MaybeLocal<Value> Evaluate(Local<Context> context); 236 237 /** 238 * Returns the namespace object of this module. 239 * 240 * The module's status must be at least kInstantiated. 241 */ 242 Local<Value> GetModuleNamespace(); 243 244 /** 245 * Returns the corresponding context-unbound module script. 246 * 247 * The module must be unevaluated, i.e. its status must not be kEvaluating, 248 * kEvaluated or kErrored. 249 */ 250 Local<UnboundModuleScript> GetUnboundModuleScript(); 251 252 /** 253 * Returns the underlying script's id. 254 * 255 * The module must be a SourceTextModule and must not have a kErrored status. 256 */ 257 int ScriptId() const; 258 259 /** 260 * Returns whether this module or any of its requested modules is async, 261 * i.e. contains top-level await. 262 * 263 * The module's status must be at least kInstantiated. 264 */ 265 bool IsGraphAsync() const; 266 267 /** 268 * Returns whether the module is a SourceTextModule. 269 */ 270 bool IsSourceTextModule() const; 271 272 /** 273 * Returns whether the module is a SyntheticModule. 274 */ 275 bool IsSyntheticModule() const; 276 277 /* 278 * Callback defined in the embedder. This is responsible for setting 279 * the module's exported values with calls to SetSyntheticModuleExport(). 280 * The callback must return a resolved Promise to indicate success (where no 281 * exception was thrown) and return an empy MaybeLocal to indicate falure 282 * (where an exception was thrown). 283 */ 284 using SyntheticModuleEvaluationSteps = 285 MaybeLocal<Value> (*)(Local<Context> context, Local<Module> module); 286 287 /** 288 * Creates a new SyntheticModule with the specified export names, where 289 * evaluation_steps will be executed upon module evaluation. 290 * export_names must not contain duplicates. 291 * module_name is used solely for logging/debugging and doesn't affect module 292 * behavior. 293 */ 294 static Local<Module> CreateSyntheticModule( 295 Isolate* isolate, Local<String> module_name, 296 const MemorySpan<const Local<String>>& export_names, 297 SyntheticModuleEvaluationSteps evaluation_steps); 298 299 /** 300 * Set this module's exported value for the name export_name to the specified 301 * export_value. This method must be called only on Modules created via 302 * CreateSyntheticModule. An error will be thrown if export_name is not one 303 * of the export_names that were passed in that CreateSyntheticModule call. 304 * Returns Just(true) on success, Nothing<bool>() if an error was thrown. 305 */ 306 V8_WARN_UNUSED_RESULT Maybe<bool> SetSyntheticModuleExport( 307 Isolate* isolate, Local<String> export_name, Local<Value> export_value); 308 309 /** 310 * Search the modules requested directly or indirectly by the module for 311 * any top-level await that has not yet resolved. If there is any, the 312 * returned pair of vectors (of equal size) contain the unresolved module 313 * and corresponding message with the pending top-level await. 314 * An embedder may call this before exiting to improve error messages. 315 */ 316 std::pair<LocalVector<Module>, LocalVector<Message>> 317 GetStalledTopLevelAwaitMessages(Isolate* isolate); 318 319 V8_INLINE static Module* Cast(Data* data); 320 321 private: 322 static void CheckCast(Data* obj); 323 }; 324 325 /** 326 * A compiled JavaScript script, tied to a Context which was active when the 327 * script was compiled. 328 */ 329 class V8_EXPORT Script : public Data { 330 public: 331 /** 332 * A shorthand for ScriptCompiler::Compile(). 333 */ 334 static V8_WARN_UNUSED_RESULT MaybeLocal<Script> Compile( 335 Local<Context> context, Local<String> source, 336 ScriptOrigin* origin = nullptr); 337 338 /** 339 * Runs the script returning the resulting value. It will be run in the 340 * context in which it was created (ScriptCompiler::CompileBound or 341 * UnboundScript::BindToCurrentContext()). 342 */ 343 V8_WARN_UNUSED_RESULT MaybeLocal<Value> Run(Local<Context> context); 344 V8_WARN_UNUSED_RESULT MaybeLocal<Value> Run(Local<Context> context, 345 Local<Data> host_defined_options); 346 347 /** 348 * Returns the corresponding context-unbound script. 349 */ 350 Local<UnboundScript> GetUnboundScript(); 351 352 /** 353 * The name that was passed by the embedder as ResourceName to the 354 * ScriptOrigin. This can be either a v8::String or v8::Undefined. 355 */ 356 Local<Value> GetResourceName(); 357 358 /** 359 * If the script was compiled, returns the positions of lazy functions which 360 * were eventually compiled and executed. 361 */ 362 std::vector<int> GetProducedCompileHints() const; 363 }; 364 365 enum class ScriptType { kClassic, kModule }; 366 367 /** 368 * For compiling scripts. 369 */ 370 class V8_EXPORT ScriptCompiler { 371 public: 372 class ConsumeCodeCacheTask; 373 374 /** 375 * Compilation data that the embedder can cache and pass back to speed up 376 * future compilations. The data is produced if the CompilerOptions passed to 377 * the compilation functions in ScriptCompiler contains produce_data_to_cache 378 * = true. The data to cache can then can be retrieved from 379 * UnboundScript. 380 */ 381 struct V8_EXPORT CachedData { 382 enum BufferPolicy { BufferNotOwned, BufferOwned }; 383 384 CachedData() 385 : data(nullptr), 386 length(0), 387 rejected(false), 388 buffer_policy(BufferNotOwned) {} 389 390 // If buffer_policy is BufferNotOwned, the caller keeps the ownership of 391 // data and guarantees that it stays alive until the CachedData object is 392 // destroyed. If the policy is BufferOwned, the given data will be deleted 393 // (with delete[]) when the CachedData object is destroyed. 394 CachedData(const uint8_t* data, int length, 395 BufferPolicy buffer_policy = BufferNotOwned); 396 ~CachedData(); 397 398 enum CompatibilityCheckResult { 399 // Don't change order/existing values of this enum since it keys into the 400 // `code_cache_reject_reason` histogram. Append-only! 401 kSuccess = 0, 402 kMagicNumberMismatch = 1, 403 kVersionMismatch = 2, 404 kSourceMismatch = 3, 405 kFlagsMismatch = 5, 406 kChecksumMismatch = 6, 407 kInvalidHeader = 7, 408 kLengthMismatch = 8, 409 kReadOnlySnapshotChecksumMismatch = 9, 410 411 // This should always point at the last real enum value. 412 kLast = kReadOnlySnapshotChecksumMismatch 413 }; 414 415 // Check if the CachedData can be loaded in the given isolate. 416 CompatibilityCheckResult CompatibilityCheck(Isolate* isolate); 417 418 // TODO(marja): Async compilation; add constructors which take a callback 419 // which will be called when V8 no longer needs the data. 420 const uint8_t* data; 421 int length; 422 bool rejected; 423 BufferPolicy buffer_policy; 424 425 // Prevent copying. 426 CachedData(const CachedData&) = delete; 427 CachedData& operator=(const CachedData&) = delete; 428 }; 429 430 enum class InMemoryCacheResult { 431 // V8 did not attempt to find this script in its in-memory cache. 432 kNotAttempted, 433 434 // V8 found a previously compiled copy of this script in its in-memory 435 // cache. Any data generated by a streaming compilation or background 436 // deserialization was abandoned. 437 kHit, 438 439 // V8 didn't have any previously compiled data for this script. 440 kMiss, 441 442 // V8 had some previously compiled data for an identical script, but the 443 // data was incomplete. 444 kPartial, 445 }; 446 447 // Details about what happened during a compilation. 448 struct CompilationDetails { 449 InMemoryCacheResult in_memory_cache_result = 450 InMemoryCacheResult::kNotAttempted; 451 452 static constexpr int64_t kTimeNotMeasured = -1; 453 int64_t foreground_time_in_microseconds = kTimeNotMeasured; 454 int64_t background_time_in_microseconds = kTimeNotMeasured; 455 }; 456 457 /** 458 * Source code which can be then compiled to a UnboundScript or Script. 459 */ 460 class Source { 461 public: 462 // Source takes ownership of both CachedData and CodeCacheConsumeTask. 463 // The caller *must* ensure that the cached data is from a trusted source. 464 V8_INLINE Source(Local<String> source_string, const ScriptOrigin& origin, 465 CachedData* cached_data = nullptr, 466 ConsumeCodeCacheTask* consume_cache_task = nullptr); 467 // Source takes ownership of both CachedData and CodeCacheConsumeTask. 468 V8_INLINE explicit Source( 469 Local<String> source_string, CachedData* cached_data = nullptr, 470 ConsumeCodeCacheTask* consume_cache_task = nullptr); 471 V8_INLINE Source(Local<String> source_string, const ScriptOrigin& origin, 472 CompileHintCallback callback, void* callback_data); 473 V8_INLINE ~Source() = default; 474 475 // Ownership of the CachedData or its buffers is *not* transferred to the 476 // caller. The CachedData object is alive as long as the Source object is 477 // alive. 478 V8_INLINE const CachedData* GetCachedData() const; 479 480 V8_INLINE const ScriptOriginOptions& GetResourceOptions() const; 481 482 V8_INLINE const CompilationDetails& GetCompilationDetails() const; 483 484 private: 485 friend class ScriptCompiler; 486 487 Local<String> source_string; 488 489 // Origin information 490 Local<Value> resource_name; 491 int resource_line_offset = -1; 492 int resource_column_offset = -1; 493 ScriptOriginOptions resource_options; 494 Local<Value> source_map_url; 495 Local<Data> host_defined_options; 496 497 // Cached data from previous compilation (if a kConsume*Cache flag is 498 // set), or hold newly generated cache data (kProduce*Cache flags) are 499 // set when calling a compile method. 500 std::unique_ptr<CachedData> cached_data; 501 std::unique_ptr<ConsumeCodeCacheTask> consume_cache_task; 502 503 // For requesting compile hints from the embedder. 504 CompileHintCallback compile_hint_callback = nullptr; 505 void* compile_hint_callback_data = nullptr; 506 507 // V8 writes this data and never reads it. It exists only to be informative 508 // to the embedder. 509 CompilationDetails compilation_details; 510 }; 511 512 /** 513 * For streaming incomplete script data to V8. The embedder should implement a 514 * subclass of this class. 515 */ 516 class V8_EXPORT ExternalSourceStream { 517 public: 518 virtual ~ExternalSourceStream() = default; 519 520 /** 521 * V8 calls this to request the next chunk of data from the embedder. This 522 * function will be called on a background thread, so it's OK to block and 523 * wait for the data, if the embedder doesn't have data yet. Returns the 524 * length of the data returned. When the data ends, GetMoreData should 525 * return 0. Caller takes ownership of the data. 526 * 527 * When streaming UTF-8 data, V8 handles multi-byte characters split between 528 * two data chunks, but doesn't handle multi-byte characters split between 529 * more than two data chunks. The embedder can avoid this problem by always 530 * returning at least 2 bytes of data. 531 * 532 * When streaming UTF-16 data, V8 does not handle characters split between 533 * two data chunks. The embedder has to make sure that chunks have an even 534 * length. 535 * 536 * If the embedder wants to cancel the streaming, they should make the next 537 * GetMoreData call return 0. V8 will interpret it as end of data (and most 538 * probably, parsing will fail). The streaming task will return as soon as 539 * V8 has parsed the data it received so far. 540 */ 541 virtual size_t GetMoreData(const uint8_t** src) = 0; 542 }; 543 544 /** 545 * Source code which can be streamed into V8 in pieces. It will be parsed 546 * while streaming and compiled after parsing has completed. StreamedSource 547 * must be kept alive while the streaming task is run (see ScriptStreamingTask 548 * below). 549 */ 550 class V8_EXPORT StreamedSource { 551 public: 552 enum Encoding { ONE_BYTE, TWO_BYTE, UTF8, WINDOWS_1252 }; 553 554 StreamedSource(std::unique_ptr<ExternalSourceStream> source_stream, 555 Encoding encoding); 556 ~StreamedSource(); 557 558 internal::ScriptStreamingData* impl() const { return impl_.get(); } 559 560 // Prevent copying. 561 StreamedSource(const StreamedSource&) = delete; 562 StreamedSource& operator=(const StreamedSource&) = delete; 563 564 CompilationDetails& compilation_details() { return compilation_details_; } 565 566 private: 567 std::unique_ptr<internal::ScriptStreamingData> impl_; 568 569 // V8 writes this data and never reads it. It exists only to be informative 570 // to the embedder. 571 CompilationDetails compilation_details_; 572 }; 573 574 /** 575 * A streaming task which the embedder must run on a background thread to 576 * stream scripts into V8. Returned by ScriptCompiler::StartStreaming. 577 */ 578 class V8_EXPORT ScriptStreamingTask final { 579 public: 580 void Run(); 581 582 private: 583 friend class ScriptCompiler; 584 585 explicit ScriptStreamingTask(internal::ScriptStreamingData* data) 586 : data_(data) {} 587 588 internal::ScriptStreamingData* data_; 589 }; 590 591 /** 592 * A task which the embedder must run on a background thread to 593 * consume a V8 code cache. Returned by 594 * ScriptCompiler::StartConsumingCodeCache. 595 */ 596 class V8_EXPORT ConsumeCodeCacheTask final { 597 public: 598 ~ConsumeCodeCacheTask(); 599 600 void Run(); 601 602 /** 603 * Provides the source text string and origin information to the consumption 604 * task. May be called before, during, or after Run(). This step checks 605 * whether the script matches an existing script in the Isolate's 606 * compilation cache. To check whether such a script was found, call 607 * ShouldMergeWithExistingScript. 608 * 609 * The Isolate provided must be the same one used during 610 * StartConsumingCodeCache and must be currently entered on the thread that 611 * calls this function. The source text and origin provided in this step 612 * must precisely match those used later in the ScriptCompiler::Source that 613 * will contain this ConsumeCodeCacheTask. 614 */ 615 void SourceTextAvailable(Isolate* isolate, Local<String> source_text, 616 const ScriptOrigin& origin); 617 618 /** 619 * Returns whether the embedder should call MergeWithExistingScript. This 620 * function may be called from any thread, any number of times, but its 621 * return value is only meaningful after SourceTextAvailable has completed. 622 */ 623 bool ShouldMergeWithExistingScript() const; 624 625 /** 626 * Merges newly deserialized data into an existing script which was found 627 * during SourceTextAvailable. May be called only after Run() has completed. 628 * Can execute on any thread, like Run(). 629 */ 630 void MergeWithExistingScript(); 631 632 private: 633 friend class ScriptCompiler; 634 635 explicit ConsumeCodeCacheTask( 636 std::unique_ptr<internal::BackgroundDeserializeTask> impl); 637 638 std::unique_ptr<internal::BackgroundDeserializeTask> impl_; 639 }; 640 641 enum CompileOptions { 642 kNoCompileOptions = 0, 643 kConsumeCodeCache, 644 kEagerCompile, 645 kProduceCompileHints, 646 kConsumeCompileHints 647 }; 648 649 /** 650 * The reason for which we are not requesting or providing a code cache. 651 */ 652 enum NoCacheReason { 653 kNoCacheNoReason = 0, 654 kNoCacheBecauseCachingDisabled, 655 kNoCacheBecauseNoResource, 656 kNoCacheBecauseInlineScript, 657 kNoCacheBecauseModule, 658 kNoCacheBecauseStreamingSource, 659 kNoCacheBecauseInspector, 660 kNoCacheBecauseScriptTooSmall, 661 kNoCacheBecauseCacheTooCold, 662 kNoCacheBecauseV8Extension, 663 kNoCacheBecauseExtensionModule, 664 kNoCacheBecausePacScript, 665 kNoCacheBecauseInDocumentWrite, 666 kNoCacheBecauseResourceWithNoCacheHandler, 667 kNoCacheBecauseDeferredProduceCodeCache 668 }; 669 670 /** 671 * Compiles the specified script (context-independent). 672 * Cached data as part of the source object can be optionally produced to be 673 * consumed later to speed up compilation of identical source scripts. 674 * 675 * Note that when producing cached data, the source must point to NULL for 676 * cached data. When consuming cached data, the cached data must have been 677 * produced by the same version of V8, and the embedder needs to ensure the 678 * cached data is the correct one for the given script. 679 * 680 * \param source Script source code. 681 * \return Compiled script object (context independent; for running it must be 682 * bound to a context). 683 */ 684 static V8_WARN_UNUSED_RESULT MaybeLocal<UnboundScript> CompileUnboundScript( 685 Isolate* isolate, Source* source, 686 CompileOptions options = kNoCompileOptions, 687 NoCacheReason no_cache_reason = kNoCacheNoReason); 688 689 /** 690 * Compiles the specified script (bound to current context). 691 * 692 * \param source Script source code. 693 * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile() 694 * using pre_data speeds compilation if it's done multiple times. 695 * Owned by caller, no references are kept when this function returns. 696 * \return Compiled script object, bound to the context that was active 697 * when this function was called. When run it will always use this 698 * context. 699 */ 700 static V8_WARN_UNUSED_RESULT MaybeLocal<Script> Compile( 701 Local<Context> context, Source* source, 702 CompileOptions options = kNoCompileOptions, 703 NoCacheReason no_cache_reason = kNoCacheNoReason); 704 705 /** 706 * Returns a task which streams script data into V8, or NULL if the script 707 * cannot be streamed. The user is responsible for running the task on a 708 * background thread and deleting it. When ran, the task starts parsing the 709 * script, and it will request data from the StreamedSource as needed. When 710 * ScriptStreamingTask::Run exits, all data has been streamed and the script 711 * can be compiled (see Compile below). 712 * 713 * This API allows to start the streaming with as little data as possible, and 714 * the remaining data (for example, the ScriptOrigin) is passed to Compile. 715 */ 716 static ScriptStreamingTask* StartStreaming( 717 Isolate* isolate, StreamedSource* source, 718 ScriptType type = ScriptType::kClassic, 719 CompileOptions options = kNoCompileOptions, 720 CompileHintCallback compile_hint_callback = nullptr, 721 void* compile_hint_callback_data = nullptr); 722 723 static ConsumeCodeCacheTask* StartConsumingCodeCache( 724 Isolate* isolate, std::unique_ptr<CachedData> source); 725 726 /** 727 * Compiles a streamed script (bound to current context). 728 * 729 * This can only be called after the streaming has finished 730 * (ScriptStreamingTask has been run). V8 doesn't construct the source string 731 * during streaming, so the embedder needs to pass the full source here. 732 */ 733 static V8_WARN_UNUSED_RESULT MaybeLocal<Script> Compile( 734 Local<Context> context, StreamedSource* source, 735 Local<String> full_source_string, const ScriptOrigin& origin); 736 737 /** 738 * Return a version tag for CachedData for the current V8 version & flags. 739 * 740 * This value is meant only for determining whether a previously generated 741 * CachedData instance is still valid; the tag has no other meaing. 742 * 743 * Background: The data carried by CachedData may depend on the exact 744 * V8 version number or current compiler flags. This means that when 745 * persisting CachedData, the embedder must take care to not pass in 746 * data from another V8 version, or the same version with different 747 * features enabled. 748 * 749 * The easiest way to do so is to clear the embedder's cache on any 750 * such change. 751 * 752 * Alternatively, this tag can be stored alongside the cached data and 753 * compared when it is being used. 754 */ 755 static uint32_t CachedDataVersionTag(); 756 757 /** 758 * Compile an ES module, returning a Module that encapsulates 759 * the compiled code. 760 * 761 * Corresponds to the ParseModule abstract operation in the 762 * ECMAScript specification. 763 */ 764 static V8_WARN_UNUSED_RESULT MaybeLocal<Module> CompileModule( 765 Isolate* isolate, Source* source, 766 CompileOptions options = kNoCompileOptions, 767 NoCacheReason no_cache_reason = kNoCacheNoReason); 768 769 /** 770 * Compiles a streamed module script. 771 * 772 * This can only be called after the streaming has finished 773 * (ScriptStreamingTask has been run). V8 doesn't construct the source string 774 * during streaming, so the embedder needs to pass the full source here. 775 */ 776 static V8_WARN_UNUSED_RESULT MaybeLocal<Module> CompileModule( 777 Local<Context> context, StreamedSource* v8_source, 778 Local<String> full_source_string, const ScriptOrigin& origin); 779 780 /** 781 * Compile a function for a given context. This is equivalent to running 782 * 783 * with (obj) { 784 * return function(args) { ... } 785 * } 786 * 787 * It is possible to specify multiple context extensions (obj in the above 788 * example). 789 */ 790 V8_DEPRECATED("Use CompileFunction") 791 static V8_WARN_UNUSED_RESULT MaybeLocal<Function> CompileFunctionInContext( 792 Local<Context> context, Source* source, size_t arguments_count, 793 Local<String> arguments[], size_t context_extension_count, 794 Local<Object> context_extensions[], 795 CompileOptions options = kNoCompileOptions, 796 NoCacheReason no_cache_reason = kNoCacheNoReason, 797 Local<ScriptOrModule>* script_or_module_out = nullptr); 798 799 static V8_WARN_UNUSED_RESULT MaybeLocal<Function> CompileFunction( 800 Local<Context> context, Source* source, size_t arguments_count = 0, 801 Local<String> arguments[] = nullptr, size_t context_extension_count = 0, 802 Local<Object> context_extensions[] = nullptr, 803 CompileOptions options = kNoCompileOptions, 804 NoCacheReason no_cache_reason = kNoCacheNoReason); 805 806 /** 807 * Creates and returns code cache for the specified unbound_script. 808 * This will return nullptr if the script cannot be serialized. The 809 * CachedData returned by this function should be owned by the caller. 810 */ 811 static CachedData* CreateCodeCache(Local<UnboundScript> unbound_script); 812 813 /** 814 * Creates and returns code cache for the specified unbound_module_script. 815 * This will return nullptr if the script cannot be serialized. The 816 * CachedData returned by this function should be owned by the caller. 817 */ 818 static CachedData* CreateCodeCache( 819 Local<UnboundModuleScript> unbound_module_script); 820 821 /** 822 * Creates and returns code cache for the specified function that was 823 * previously produced by CompileFunction. 824 * This will return nullptr if the script cannot be serialized. The 825 * CachedData returned by this function should be owned by the caller. 826 */ 827 static CachedData* CreateCodeCacheForFunction(Local<Function> function); 828 829 private: 830 static V8_WARN_UNUSED_RESULT MaybeLocal<UnboundScript> CompileUnboundInternal( 831 Isolate* isolate, Source* source, CompileOptions options, 832 NoCacheReason no_cache_reason); 833 834 static V8_WARN_UNUSED_RESULT MaybeLocal<Function> CompileFunctionInternal( 835 Local<Context> context, Source* source, size_t arguments_count, 836 Local<String> arguments[], size_t context_extension_count, 837 Local<Object> context_extensions[], CompileOptions options, 838 NoCacheReason no_cache_reason, 839 Local<ScriptOrModule>* script_or_module_out); 840 }; 841 842 ScriptCompiler::Source::Source(Local<String> string, const ScriptOrigin& origin, 843 CachedData* data, 844 ConsumeCodeCacheTask* consume_cache_task) 845 : source_string(string), 846 resource_name(origin.ResourceName()), 847 resource_line_offset(origin.LineOffset()), 848 resource_column_offset(origin.ColumnOffset()), 849 resource_options(origin.Options()), 850 source_map_url(origin.SourceMapUrl()), 851 host_defined_options(origin.GetHostDefinedOptions()), 852 cached_data(data), 853 consume_cache_task(consume_cache_task) {} 854 855 ScriptCompiler::Source::Source(Local<String> string, CachedData* data, 856 ConsumeCodeCacheTask* consume_cache_task) 857 : source_string(string), 858 cached_data(data), 859 consume_cache_task(consume_cache_task) {} 860 861 ScriptCompiler::Source::Source(Local<String> string, const ScriptOrigin& origin, 862 CompileHintCallback callback, 863 void* callback_data) 864 : source_string(string), 865 resource_name(origin.ResourceName()), 866 resource_line_offset(origin.LineOffset()), 867 resource_column_offset(origin.ColumnOffset()), 868 resource_options(origin.Options()), 869 source_map_url(origin.SourceMapUrl()), 870 host_defined_options(origin.GetHostDefinedOptions()), 871 compile_hint_callback(callback), 872 compile_hint_callback_data(callback_data) {} 873 874 const ScriptCompiler::CachedData* ScriptCompiler::Source::GetCachedData() 875 const { 876 return cached_data.get(); 877 } 878 879 const ScriptOriginOptions& ScriptCompiler::Source::GetResourceOptions() const { 880 return resource_options; 881 } 882 883 const ScriptCompiler::CompilationDetails& 884 ScriptCompiler::Source::GetCompilationDetails() const { 885 return compilation_details; 886 } 887 888 ModuleRequest* ModuleRequest::Cast(Data* data) { 889 #ifdef V8_ENABLE_CHECKS 890 CheckCast(data); 891 #endif 892 return reinterpret_cast<ModuleRequest*>(data); 893 } 894 895 Module* Module::Cast(Data* data) { 896 #ifdef V8_ENABLE_CHECKS 897 CheckCast(data); 898 #endif 899 return reinterpret_cast<Module*>(data); 900 } 901 902 } // namespace v8 903 904 #endif // INCLUDE_V8_SCRIPT_H_