### Proxy Construction and Trap Execution Example Source: https://github.com/v8/v8.dev/blob/main/src/blog/optimizing-proxies.md Illustrates the setup for a proxy with an `apply` trap, which is invoked when the proxy is called as a function. This code is used to demonstrate runtime performance improvements. ```javascript function foo(…) { … } const g = new Proxy({ … }, { apply: foo, }); g(1, 2); ``` -------------------------------- ### Install Dependencies Source: https://github.com/v8/v8.dev/blob/main/README.md Run this command after cloning the repository to install all necessary project dependencies. ```bash npm install ``` -------------------------------- ### Install and Build cquery Source: https://github.com/v8/v8.dev/blob/main/src/docs/ide-setup.md Clone the cquery repository, update submodules, and build it with CMake. Ensure to set the build type to 'release' and enable command export. This setup is for a *nix system. ```bash git clone https://github.com/cquery-project/cquery "$CQUERY_DIR" cd "$CQUERY_DIR" git submodule update --init mkdir build cd build cmake .. -DCMAKE_BUILD_TYPE=release -DCMAKE_INSTALL_PREFIX=release -DCMAKE_EXPORT_COMPILE_COMMANDS=YES make install -j8 ``` -------------------------------- ### Example Code Snippet for Debugging Source: https://github.com/v8/v8.dev/blob/main/src/docs/debug-arm.md This C++ code snippet demonstrates how to use Debug() to start and stop tracing for a specific section of code. ```cpp // Start tracing and log disassembly and register values. __ Debug("start tracing", 42, TRACE_ENABLE | LOG_ALL); int64_t bad_frame_pointer = -1L; // Bad frame pointer, should fail if it is used. __ Mov(x13, bad_frame_pointer); __ Mov(x12, StackFrame::TypeToMarker(type)); __ Mov(x11, ExternalReference::Create(IsolateAddressId::kCEntryFPAddress, masm->isolate())); __ Ldr(x10, MemOperand(x11)); __ Push(x13, x12, xzr, x10); // Stop tracing. __ Debug("stop tracing", 42, TRACE_DISABLE); ``` -------------------------------- ### RegExp Execution Example Source: https://github.com/v8/v8.dev/blob/main/src/blog/regexp-tier-up.md This example demonstrates a simple regular expression and its execution on a string, illustrating the matching behavior. ```javascript const re = /[^_]*/; const str = 'a0b*c_ef'; re.exec(str); // → matches 'a0b*c' ``` -------------------------------- ### Install perf Dependencies Source: https://github.com/v8/v8.dev/blob/main/src/docs/linux-perf.md Install necessary development libraries required for building the linux-perf tool from source. ```bash sudo apt-get install libdw-dev libunwind8-dev systemtap-sdt-dev libaudit-dev \ libslang2-dev binutils-dev liblzma-dev; ``` -------------------------------- ### Install Node.js Version Source: https://github.com/v8/v8.dev/blob/main/README.md Use this command to switch to the Node.js version specified in the project's .nvmrc file. ```bash nvm use ``` -------------------------------- ### Get Node Sources and Set Up Remotes Source: https://github.com/v8/v8.dev/blob/main/src/docs/node-integration.md Clone the Node.js fork and add both V8's and your personal fork as Git remotes. ```bash cd node git remote add v8 http://github.com/v8/node git remote add git@github.com:/node.git git fetch v8 git checkout v8/node-ci- export BRANCH_NAME=`date +"%Y-%m-%d"`_fix_name git checkout -b $BRANCH_NAME ``` -------------------------------- ### Install and Activate Emscripten Latest Source: https://github.com/v8/v8.dev/blob/main/src/features/simd.md Installs and activates the latest Emscripten SDK distribution, which is required for using WebAssembly SIMD features. ```bash ./emsdk install latest ./emsdk activate latest ``` -------------------------------- ### Async Stack Trace Example Source: https://github.com/v8/v8.dev/blob/main/src/docs/stack-trace-api.md Example of a stack trace enriched with async frames, marked with 'async'. This is enabled by default since V8 v7.3. ```text ReferenceError: FAIL is not defined at bar () at async foo () ``` -------------------------------- ### Example Stack Trace Format Source: https://github.com/v8/v8.dev/blob/main/src/docs/stack-trace-api.md A typical formatted stack trace string from a V8 error. ```text ReferenceError: FAIL is not defined at Constraint.execute (deltablue.js:525:2) at Constraint.recalculate (deltablue.js:424:21) at Planner.addPropagate (deltablue.js:701:6) at Constraint.satisfy (deltablue.js:184:15) at Planner.incrementalAdd (deltablue.js:591:21) at Constraint.addConstraint (deltablue.js:162:10) at Constraint.BinaryConstraint (deltablue.js:346:7) at Constraint.EqualityConstraint (deltablue.js:515:38) at chainTest (deltablue.js:807:6) at deltaBlue (deltablue.js:879:2) ``` -------------------------------- ### Install and activate latest upstream Emscripten Source: https://github.com/v8/v8.dev/blob/main/src/blog/emscripten-llvm-wasm.md Use these commands to install and activate the latest Emscripten version that includes the upstream LLVM WebAssembly backend. This is recommended for testing the new backend. ```bash emsdk install latest-upstream emsdk activate latest-upstream ``` -------------------------------- ### JavaScript Example for Optimization Source: https://github.com/v8/v8.dev/blob/main/src/docs/debug-arm.md This JavaScript code prepares a function for optimization and forces optimization to test breakpoint insertion in optimized code. ```js // Our optimized function. function add(a, b) { return a + b; } // Typical cheat code enabled by --allow-natives-syntax. %PrepareFunctionForOptimization(add); // Give the optimizing compiler type feedback so it'll speculate `a` and `b` are // numbers. add(1, 3); // And force it to optimize. %OptimizeFunctionOnNextCall(add); add(5, 7); ``` -------------------------------- ### Start Local HTTP Server Source: https://github.com/v8/v8.dev/blob/main/README.md Launches a local HTTP server to preview the website, typically serving files from the 'dist' directory. ```bash npm start ``` -------------------------------- ### Get Script Names in English Source: https://github.com/v8/v8.dev/blob/main/src/features/intl-displaynames.md This example shows how to get script names in English using ISO-15924 4-letter script codes. The type is set to 'script'. ```javascript const scriptNames = new Intl.DisplayNames(['en'], { type: 'script' }); scriptNames.of('Latn'); // → 'Latin' scriptNames.of('Arab'); // → 'Arabic' scriptNames.of('Kana'); // → 'Katakana' ``` -------------------------------- ### Regular Expression Literal Example Source: https://github.com/v8/v8.dev/blob/main/src/blog/understanding-ecmascript-part-3.md Illustrates the start of a RegExp literal '/' in ECMAScript. ```javascript const r = /foo/; ``` -------------------------------- ### Initialize depot_tools Source: https://github.com/v8/v8.dev/blob/main/src/docs/source-code.md Run `gclient` to initialize or update the depot_tools environment. This is a prerequisite for fetching V8 and other Chromium-related projects. ```bash gclient ``` -------------------------------- ### Build the Site Source: https://github.com/v8/v8.dev/blob/main/README.md Executes the build process, outputting the static site files into the 'dist' directory. ```bash npm run build ``` -------------------------------- ### Demonstrate String.prototype.trimStart() and trimEnd() Source: https://github.com/v8/v8.dev/blob/main/src/blog/v8-release-66.md Shows the usage of the new String.prototype.trimStart() and String.prototype.trimEnd() methods for removing whitespace from the beginning and end of a string, respectively. Also includes trim() for comparison. ```javascript const string = ' hello world '; string.trimStart(); // → 'hello world ' string.trimEnd(); // → ' hello world' string.trim(); // → 'hello world' ``` -------------------------------- ### Add Logging to Property Access with Proxies Source: https://github.com/v8/v8.dev/blob/main/src/blog/optimizing-proxies.md Use a Proxy to intercept property access and add custom behavior like logging. This example demonstrates the basic usage of the `get` trap. ```javascript const target = {}; const callTracer = new Proxy(target, { get: (target, name, receiver) => { console.log(`get was called for: ${name}`); return target[name]; } }); callTracer.property = 'value'; console.log(callTracer.property); // get was called for: property // value ``` -------------------------------- ### Minimal Test Case Setup for Compile Hints Source: https://github.com/v8/v8.dev/blob/main/src/blog/explicit-compile-hints.md This HTML file includes two JavaScript files to demonstrate compile hints. Ensure Chrome is run with a clean user data directory for accurate observation. ```html ``` -------------------------------- ### ES2015 Default Parameters Source: https://github.com/v8/v8.dev/blob/main/src/blog/v8-release-49.md ES2015 allows default values to be directly assigned to function parameters, simplifying function definitions. This example shows a default for 'start' and 'end', with 'end' depending on 'list.length'. ```javascript function sublist(list, start = 0, end = list.length) { … } sublist([1, 2, 3], 1); // sublist([1, 2, 3], 1, 3) ``` -------------------------------- ### Getting Declaration Position with RegExp Source: https://github.com/v8/v8.dev/blob/main/src/features/regexp-match-indices.md Extracts the starting index of a variable declaration (let, const, var) from a source string using a regular expression. This function returns the index of the entire match, not capture groups. ```javascript function getDeclarationPosition(source) { const re = /(let|const|var)\s+([a-zA-Z_$][0-9a-zA-Z_$]*)/; const match = re.exec(source); if (!match) return -1; return match.index; } ``` -------------------------------- ### Initialize and Fetch V8 Source Code Source: https://github.com/v8/v8.dev/blob/main/src/docs/source-code.md Use these commands to create a directory, navigate into it, and fetch the V8 source code along with its dependencies. This is the primary method for obtaining the V8 codebase for local development. ```bash mkdir ~/v8 cd ~/v8 fetch v8 cd v8 ``` -------------------------------- ### Embed V8 in C++: Hello World Source: https://context7.com/v8/v8.dev/llms.txt A minimal C++ example demonstrating the V8 embedding lifecycle: initializing V8, creating an Isolate and Context, compiling and running a JavaScript string, and retrieving the result. Ensure correct build flags and linked libraries when compiling. ```cpp #include "include/v8.h" #include "include/libplatform/libplatform.h" #include int main(int argc, char* argv[]) { // Initialize V8 (call once per process) v8::V8::InitializeICUDefaultLocation(argv[0]); v8::V8::InitializeExternalStartupData(argv[0]); std::unique_ptr platform = v8::platform::NewDefaultPlatform(); v8::V8::InitializePlatform(platform.get()); v8::V8::Initialize(); // Create a new Isolate (independent VM instance with its own heap) v8::Isolate::CreateParams create_params; create_params.array_buffer_allocator = v8::ArrayBuffer::Allocator::NewDefaultAllocator(); v8::Isolate* isolate = v8::Isolate::New(create_params); { v8::Isolate::Scope isolate_scope(isolate); v8::HandleScope handle_scope(isolate); // manages local handle lifetimes // Create a Context (JS execution environment / global scope) v8::Local context = v8::Context::New(isolate); v8::Context::Scope context_scope(context); // Compile and run a JavaScript string v8::Local source = v8::String::NewFromUtf8Literal(isolate, "'Hello' + ', World!'"); v8::Local script = v8::Script::Compile(context, source).ToLocalChecked(); v8::Local result = script->Run(context).ToLocalChecked(); // Convert result to a C++ string and print v8::String::Utf8Value utf8(isolate, result); std::cout << *utf8 << std::endl; // prints: Hello, World! } isolate->Dispose(); v8::V8::Dispose(); v8::V8::DisposePlatform(); delete create_params.array_buffer_allocator; return 0; } // Build: // tools/dev/v8gen.py x64.release.sample // ninja -C out.gn/x64.release.sample v8_monolith // g++ -I. -Iinclude samples/hello-world.cc -o hello_world \ // -fno-rtti -fuse-ld=lld -lv8_monolith -lv8_libbase -lv8_libplatform \ // -ldl -Lout.gn/x64.release.sample/obj/ -pthread -std=c++20 \ // -DV8_COMPRESS_POINTERS -DV8_ENABLE_SANDBOX ``` -------------------------------- ### Get Capture Group Indices with RegExp 'd' Flag Source: https://github.com/v8/v8.dev/blob/main/src/features/regexp-match-indices.md Use the 'd' flag in a regular expression to enable the `indices` property on the match result. This allows you to retrieve the start and end positions of capture groups, useful for pinpointing specific parts of a matched string. ```javascript function getVariablePosition(source) { // Notice the `d` flag, which enables `match.indices` const re = /(let|const|var)\s+([a-zA-Z_$][0-9a-zA-Z_$]*)/d; const match = re.exec(source); if (!match) return undefined; return match.indices[2]; } getVariablePosition('let foo'); // → [4, 7] ``` -------------------------------- ### Enable Profiling on Other Platforms Source: https://github.com/v8/v8.dev/blob/main/src/docs/profile.md Use the --prof option with the d8 shell to start profiling. Replace 'ia32' with 'x64' if profiling the x64 build. This generates a v8.log file. ```bash out/ia32.release/d8 --prof script.js ``` -------------------------------- ### Generate build files with gn and command-line arguments Source: https://github.com/v8/v8.dev/blob/main/src/docs/build-gn.md Generate build files for a specific output directory by passing GN arguments directly on the command line. This example configures a build for the arm64 simulator in release mode. ```bash gn gen out/foo --args='is_debug=false target_cpu="x64" v8_target_cpu="arm64"' ``` -------------------------------- ### Torque Abstract Type Examples Source: https://github.com/v8/v8.dev/blob/main/src/docs/torque.md Examples of abstract type declarations in Torque, specifying generation and constexpr types. ```torque type int32 generates 'TNode' constexpr 'int32_t'; type int31 extends int32 generates 'TNode' constexpr 'int31_t'; ``` -------------------------------- ### Run hello_world executable Source: https://github.com/v8/v8.dev/blob/main/src/docs/embed.md Execute the compiled hello_world program. It should print 'Hello, World!' to standard output. ```bash ./hello_world ``` -------------------------------- ### Torque Class Definition Example Source: https://github.com/v8/v8.dev/blob/main/src/docs/torque.md An example of an 'extern' class definition in Torque for JSProxy, extending JSReceiver and defining fields. ```torque extern class JSProxy extends JSReceiver { target: JSReceiver|Null; handler: JSReceiver|Null; } ``` -------------------------------- ### V8 Retaining Path Output Example Source: https://github.com/v8/v8.dev/blob/main/src/docs/memory-leaks.md Example output from `%DebugTrackRetainingPath` showing the retaining path of an object, including its distance from the root. ```text ################################################# Retaining path for 0x245c59f0c1a1: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Distance from root 6: 0x245c59f0c1a1 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Distance from root 5: 0x245c59f0c169 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Distance from root 4: 0x245c59f0c219 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Distance from root 3: 0x1fbb02e2d679 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Distance from root 2: 0x245c59f0c139 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Distance from root 1: 0x1fbb02e03d91 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Root: (Isolate) ------------------------------------------------- ``` -------------------------------- ### Compile hello-world.cc with V8 static library Source: https://github.com/v8/v8.dev/blob/main/src/docs/embed.md Compile the hello-world C++ file, linking against the V8 static libraries. Ensure correct include and library paths are specified. ```bash g++ -I. -Iinclude samples/hello-world.cc -o hello_world -fno-rtti -fuse-ld=lld -lv8_monolith -lv8_libbase -lv8_libplatform -ldl -Lout.gn/x64.release.sample/obj/ -pthread -std=c++20 -DV8_COMPRESS_POINTERS -DV8_ENABLE_SANDBOX ``` -------------------------------- ### JavaScript Function Example for Coverage Source: https://github.com/v8/v8.dev/blob/main/src/blog/javascript-code-coverage.md This example demonstrates a simple JavaScript function and its invocation, used to illustrate code coverage concepts. ```javascript function f() { console.log('Hello World'); } f(); ``` -------------------------------- ### List available configurations with v8gen Source: https://github.com/v8/v8.dev/blob/main/src/docs/build-gn.md Use the `v8gen list` command to display all available build configurations, which can correspond to bots on a master build server. This helps in selecting the correct build target. ```bash v8gen list ``` -------------------------------- ### Watch for Changes and Build Source: https://github.com/v8/v8.dev/blob/main/README.md Builds the site and continuously monitors for file changes, automatically rebuilding the 'dist' directory upon modification. ```bash npm run watch ``` -------------------------------- ### ECMAScript [[Get]] Internal Method Definition Source: https://github.com/v8/v8.dev/blob/main/src/blog/understanding-ecmascript-part-2.md This defines the [[Get]] internal method for objects. It delegates the property lookup to the OrdinaryGet abstract operation. ```ecmascript-algorithm > **[`[[Get]] ( P, Receiver )`](https://tc39.es/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots-get-p-receiver)** > > When the `[[Get]]` internal method of `O` is called with property key `P` and ECMAScript language value `Receiver`, the following steps are taken: > > 1. Return `? OrdinaryGet(O, P, Receiver)`. ``` -------------------------------- ### Build V8 static library Source: https://github.com/v8/v8.dev/blob/main/src/docs/embed.md Configure and build the V8 static library using the provided helper scripts and ninja. ```bash tools/dev/v8gen.py x64.release.sample ``` ```bash gn args out.gn/x64.release.sample ``` ```bash ninja -C out.gn/x64.release.sample v8_monolith ``` -------------------------------- ### Start V8 Debugger with Stop at Instruction Source: https://github.com/v8/v8.dev/blob/main/src/docs/debug-arm.md Use the `--stop_sim_at` flag to halt execution at a specific instruction count when starting the V8 debugger. ```bash out/arm64.debug/d8 --stop_sim_at # Or out/arm.debug/d8 for a 32-bit build. ``` -------------------------------- ### Install Linux build dependencies Source: https://github.com/v8/v8.dev/blob/main/src/docs/build.md Install additional build dependencies required for V8 compilation on Linux systems. This script should be executed from the V8 source directory. ```bash ./build/install-build-deps.sh ``` -------------------------------- ### Enable Profiling on Windows Source: https://github.com/v8/v8.dev/blob/main/src/docs/profile.md Use the --prof option with the d8 shell to start profiling. This will generate a v8.log file containing profiling data. ```bash build\Release\d8 --prof script.js ``` -------------------------------- ### Internal Await Mechanism Example Source: https://github.com/v8/v8.dev/blob/main/src/blog/fast-async.md This example illustrates the internal handling of await: the parameter is wrapped in a Promise, execution is suspended, and resumed upon Promise fulfillment. ```javascript async function foo(v) { const w = await v; return w; } ``` -------------------------------- ### Dynamic Import Example Source: https://github.com/v8/v8.dev/blob/main/src/features/modules.md Load modules on demand using dynamic import(). This can be used in regular scripts to improve initial load times. ```javascript import {shout} from './lib.mjs'; // ^^^^^^^^^^^ ``` ```javascript ``` -------------------------------- ### JavaScript Proxy with Custom Get Trap Source: https://github.com/v8/v8.dev/blob/main/src/blog/v8-release-49.md Illustrates creating a Proxy object with a custom 'get' trap to intercept property access and return a default value. ```javascript const target = {} const handler = { get(target, name='world') { return `Hello, ${name}!`; } }; const foo = new Proxy(target, handler); foo.bar; // → 'Hello, bar!' ``` -------------------------------- ### Fetch data with loading spinner using `async`/`await` and `finally` Source: https://github.com/v8/v8.dev/blob/main/src/features/promise-finally.md This example shows the equivalent functionality using `async`/`await` syntax with a `try...catch...finally` block. This is the recommended approach for modern JavaScript. ```javascript const fetchAndDisplay = async ({ url, element }) => { showLoadingSpinner(); try { const response = await fetch(url); const text = await response.text(); element.textContent = text; } catch (error) { element.textContent = error.message; } finally { hideLoadingSpinner(); } }; ``` -------------------------------- ### Install Linux Kernel LTS Source: https://github.com/v8/v8.dev/blob/main/src/docs/linux-perf.md Install the Long Term Support (LTS) Linux kernel, which may be required for building a compatible version of linux-perf with JIT support. ```bash sudo apt-get install linux-generic-lts-wily; ``` -------------------------------- ### Async Function Example Source: https://github.com/v8/v8.dev/blob/main/src/blog/fast-async.md Demonstrates the modern async function syntax, which allows asynchronous code to be written in a style that closely resembles synchronous code. ```javascript async function handler() { await validateParams(); const dbResults = await dbQuery(); const results = await serviceCall(dbResults); console.log(results); return results; } ``` -------------------------------- ### Install Sourcery G++ Lite for ARM Source: https://github.com/v8/v8.dev/blob/main/src/docs/cross-compile-arm.md Installs the Sourcery G++ Lite package for ARM cross-compilation into /opt/codesourcery. Ensure you have the necessary permissions and download the correct package. ```bash #!/bin/sh sudo mkdir /opt/codesourcery cd /opt/codesourcery sudo chown "$USERNAME" . chmod g+ws . umask 2 wget http://www.codesourcery.com/sgpp/lite/arm/portal/package4571/public/arm-none-linux-gnueabi/arm-2009q1-203-arm-none-linux-gnueabi-i686-pc-linux-gnu.tar.bz2 tar -xvf arm-2009q1-203-arm-none-linux-gnueabi-i686-pc-linux-gnu.tar.bz2 ``` -------------------------------- ### For-In Loop Preparation and Iteration in V8 Source: https://github.com/v8/v8.dev/blob/main/src/blog/fast-for-in.md This pseudo-C++ code illustrates the initial steps of a for-in loop in V8, including preparing the keys to iterate over using the EnumCache and handling objects with or without elements. ```js // For-In Prepare: FixedArray* keys = nullptr; Map* original_map = object->map(); if (original_map->HasEnumCache()) { if (object->HasNoElements()) { keys = original_map->GetCachedEnumKeys(); } else { keys = object->GetCachedEnumKeysWithElements(); } } else { keys = object->GetEnumKeys(); } // For-In Body: for (size_t i = 0; i < keys->length(); i++) { // For-In Next: String* key = keys[i]; if (!object->HasProperty(key)) continue; EVALUATE_FOR_IN_BODY(); } ``` -------------------------------- ### Resource Initialization with Top-level await Source: https://github.com/v8/v8.dev/blob/main/src/features/top-level-await.md Initialize resources like database connections directly within a module, allowing modules to represent and manage their own dependencies. ```javascript const connection = await dbConnector(); ``` -------------------------------- ### Get Region Names in English Source: https://github.com/v8/v8.dev/blob/main/src/features/intl-displaynames.md Use this snippet to get region names in English using ISO-3166 2-letter country codes. Ensure the locale is set to 'en'. ```javascript const regionNames = new Intl.DisplayNames(['en'], { type: 'region' }); regionNames.of('US'); // → 'United States' regionNames.of('BA'); // → 'Bosnia & Herzegovina' regionNames.of('MM'); // → 'Myanmar (Burma)' ``` -------------------------------- ### Example Profiling Output Source: https://github.com/v8/v8.dev/blob/main/src/docs/profile.md This is an example of the statistical profiling results generated after processing a v8.log file. It includes breakdowns for shared libraries, JavaScript, C++, GC, and a bottom-up profile. ```text Statistical profiling result from benchmarks\v8.log, (4192 ticks, 0 unaccounted, 0 excluded). [Shared libraries]: ticks total nonlib name 9 0.2% 0.0% C:\WINDOWS\system32\ntdll.dll 2 0.0% 0.0% C:\WINDOWS\system32\kernel32.dll [JavaScript]: ticks total nonlib name 741 17.7% 17.7% LazyCompile: am3 crypto.js:108 113 2.7% 2.7% LazyCompile: Scheduler.schedule richards.js:188 103 2.5% 2.5% LazyCompile: rewrite_nboyer earley-boyer.js:3604 103 2.5% 2.5% LazyCompile: TaskControlBlock.run richards.js:324 96 2.3% 2.3% Builtin: JSConstructCall ... [C++]: ticks total nonlib name 94 2.2% 2.2% v8::internal::ScavengeVisitor::VisitPointers 33 0.8% 0.8% v8::internal::SweepSpace 32 0.8% 0.8% v8::internal::Heap::MigrateObject 30 0.7% 0.7% v8::internal::Heap::AllocateArgumentsObject ... [GC]: ticks total nonlib name 458 10.9% [Bottom up (heavy) profile]: Note: percentage shows a share of a particular caller in the total amount of its parent calls. Callers occupying less than 2.0% are not shown. ticks parent name 741 17.7% LazyCompile: am3 crypto.js:108 449 60.6% LazyCompile: montReduce crypto.js:583 393 87.5% LazyCompile: montSqrTo crypto.js:603 212 53.9% LazyCompile: bnpExp crypto.js:621 212 100.0% LazyCompile: bnModPowInt crypto.js:634 212 100.0% LazyCompile: RSADoPublic crypto.js:1521 181 46.1% LazyCompile: bnModPow crypto.js:1098 181 100.0% LazyCompile: RSADoPrivate crypto.js:1628 ... ``` -------------------------------- ### JavaScript Examples Demonstrating CPEAAPL Usage Source: https://github.com/v8/v8.dev/blob/main/src/blog/understanding-ecmascript-part-4.md These JavaScript examples illustrate how CPEAAPL is used in practice within an AssignmentExpression. The comments highlight the CPEAAPL and the subsequent token that influences parsing. ```javascript let x = (a, b) => { return a + b; }; // ^^^^^^ // CPEAAPL // ^^ // The token following the CPEAAPL ``` ```javascript let x = (a, 3); // ^^^^^^ // CPEAAPL // ^ // The token following the CPEAAPL ``` -------------------------------- ### Examples of Valid CPEAAPL Constructs Source: https://github.com/v8/v8.dev/blob/main/src/blog/understanding-ecmascript-part-4.md Provides examples of JavaScript code that are valid under the `CPEAAPL` symbol, illustrating constructs that can be either a parenthesized expression or an arrow function parameter list. ```javascript // Valid ParenthesizedExpression and ArrowParameterList: (a, b) (a, b = 1) // Valid ParenthesizedExpression: (1, 2, 3) (function foo() { }) // Valid ArrowParameterList: () (a, b,) (a, ...b) // Not valid either, but still a CPEAAPL: (1, ...b) (1, ) ``` -------------------------------- ### Sync V8 dependencies Source: https://github.com/v8/v8.dev/blob/main/src/docs/build.md Download all necessary build dependencies for V8. This command should be run from the V8 source directory. ```bash gclient sync ``` -------------------------------- ### Example Function Call in V8 Source: https://github.com/v8/v8.dev/blob/main/src/blog/adaptor-frame.md This JavaScript code demonstrates a simple function call within V8. It serves as a basic example to illustrate the execution flow during a function invocation. ```javascript function add42(x) { return x + 42; } add42(3); ``` -------------------------------- ### Run V8 Hooks and Build Source: https://github.com/v8/v8.dev/blob/main/src/docs/node-integration.md Execute gclient hooks and compile V8 with parallel jobs after applying changes. ```bash gclient runhooks JOBS=`nproc` make test ``` -------------------------------- ### Get matching substrings with `String#match` Source: https://github.com/v8/v8.dev/blob/main/src/features/string-matchall.md Use `String#match` with a global regex to get an array of matching substrings. This method does not provide match indices or capturing groups. ```javascript const string = 'Magic hex numbers: DEADBEEF CAFE'; const regex = /\b\p{ASCII_Hex_Digit}+\b/gu; for (const match of string.match(regex)) { console.log(match); } // Output: // // 'DEADBEEF' // 'CAFE' ``` -------------------------------- ### Inspecting the Initial Map of a Constructor Source: https://github.com/v8/v8.dev/blob/main/src/blog/slack-tracking.md Demonstrates how to use %DebugPrint on a constructor function to find its initial map, which is crucial for understanding slack tracking behavior. ```javascript > %DebugPrint(Peak); d8> %DebugPrint(Peak) DebugPrint: 0x31c12561: [Function] in OldSpace - map: 0x2a2821f5 [FastProperties] - prototype: 0x31c034b5 - elements: 0x28c821a1 [HOLEY_ELEMENTS] - function prototype: 0x37449c89 - initial_map: 0x46f07295 // Here's the initial map. - shared_info: 0x31c12495 - name: 0x31c12405 … ``` -------------------------------- ### V8 Source Checkout and Contribution Workflow Source: https://context7.com/v8/v8.dev/llms.txt Commands for setting up the V8 development environment, fetching the source code, and initiating the contribution process using depot_tools and gclient. ```bash # One-time setup: install depot_tools and fetch V8 gclient # update depot_tools mkdir ~/v8 && cd ~/v8 fetch v8 # clone V8 and all DEPS cd v8 ``` -------------------------------- ### Precise Coverage Result Example Source: https://github.com/v8/v8.dev/blob/main/src/blog/javascript-code-coverage.md Example of precise coverage data returned, showing function name, block granularity, source ranges with offsets and counts, script ID, and URL. ```json { "id": 32, "result": { "result": [{ "functions": [ { "functionName": "fib", "isBlockCoverage": true, // Block granularity. "ranges": [ // An array of nested ranges. { "startOffset": 50, // Byte offset, inclusive. "endOffset": 224, // Byte offset, exclusive. "count": 1 }, { "startOffset": 97, "endOffset": 107, "count": 0 }, { "startOffset": 134, "endOffset": 144, "count": 0 }, { "startOffset": 192, "endOffset": 223, "count": 0 }, ]}, "scriptId": "199", "url": "file:///coverage-fib.html" } ] }}} ``` -------------------------------- ### Configure Isolate with Custom Startup Snapshot Source: https://github.com/v8/v8.dev/blob/main/src/blog/custom-startup-snapshots.md Initialize a new V8 isolate to use a custom startup snapshot. Contexts created within this isolate will be exact copies of the snapshot, providing immediate access to its defined functions. ```c++ v8::Isolate::CreateParams params; params.snapshot_blob = snapshot_blob; v8::Isolate* isolate = v8::Isolate::New(params); ``` -------------------------------- ### Service Worker Install Event: Build Cache Source: https://github.com/v8/v8.dev/blob/main/src/blog/code-caching-for-devs.md The 'install' event handler in a service worker is used to open a cache and add essential resources. This pre-caches assets for offline use and enables a 'full' code cache for JavaScript. ```javascript // sw.js self.addEventListener('install', (event) => { async function buildCache() { const cache = await caches.open(cacheName); return cache.addAll([ '/main.css', '/main.mjs', '/offline.html', ]); } event.waitUntil(buildCache()); }); ``` -------------------------------- ### List available gn arguments Source: https://github.com/v8/v8.dev/blob/main/src/docs/build-gn.md Display a comprehensive list of all available GN arguments for a given output directory. This is useful for understanding and configuring build options. ```bash gn args out/foo --list ```