### Setup development environment on Debian or Ubuntu Source: https://github.com/carbon-language/carbon-lang/blob/trunk/docs/project/contribution_tools.md Installs required system packages, tools, and initializes the repository for Debian-based systems. ```shell # Update apt. sudo apt update # Check that the `clang` version is at least 19, our minimum version. That needs # the number of the `:` in the output to be over 19. For example, `1:19.0-1`. apt-cache show clang | grep 'Version:' # Install tools. sudo apt install \ clang \ gh \ libc++-dev \ libc++abi-dev \ lld \ lldb # Install `uv` for Python scripts. curl -LsSf https://astral.sh/uv/install.sh | sh # Install `prek` for Git hooks. cargo install --locked prek # Set up git. # If you don't already have a fork: gh repo fork --clone carbon-language/carbon-lang cd carbon-lang prek install # Run tests. ./scripts/run_bazelisk.py test //...:all ``` -------------------------------- ### Setup development environment on macOS Source: https://github.com/carbon-language/carbon-lang/blob/trunk/docs/project/contribution_tools.md Installs Homebrew, necessary dependencies, and initializes the repository on macOS. ```shell # Install Homebrew. /bin/bash -c "$(curl -fsSL \ https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" # IMPORTANT: Make sure `brew` is added to the PATH! # Install Homebrew tools. brew install \ bazelisk \ gh \ llvm \ uv \ prek # IMPORTANT: Make sure `llvm` is added to the PATH! It's separate from `brew`. # Set up git. gh repo fork --clone carbon-language/carbon-lang cd carbon-lang prek install # Run tests. Note homebrew makes `bazel` an alias to `bazelisk`. bazel test //...:all ``` -------------------------------- ### Library Z Setup Source: https://github.com/carbon-language/carbon-lang/blob/trunk/proposals/p007140-orphan-rule-for-scopes.md The base library interface used for the following examples. ```carbon library "z"; interface Z {} ``` -------------------------------- ### Build and install extension Source: https://github.com/carbon-language/carbon-lang/blob/trunk/utils/vscode/development.md Commands to build the VSIX package and install it in various environments. ```bash npm install && vsce package -o carbon.vsix && code --install-extension carbon.vsix ``` ```bash npm install && vsce package -o carbon.vsix && ~/.vscode-server/cli/servers/Stable-*/server/bin/code-server --install-extension carbon.vsix ``` ```bash npm install && vsce package -o carbon.vsix && realpath carbon.vsix ``` -------------------------------- ### Install Tree-sitter CLI Source: https://github.com/carbon-language/carbon-lang/blob/trunk/utils/tree_sitter/README.md Installs the Tree-sitter CLI globally using npm. ```bash npm install -g tree-sitter-cli ``` -------------------------------- ### Example Library and Interface Declarations Source: https://github.com/carbon-language/carbon-lang/blob/trunk/proposals/p003980-singular-extern-declarations.md A set of examples demonstrating library and interface declarations across different files to illustrate declaration placement concerns. ```carbon library "i"; interface I {} ``` ```carbon library "e"; import library "i"; extern library "o" class C; extern library "o" impl C as I; ``` ```carbon library "o"; import library "e"; extern class C { } extern impl C as I; ``` ```carbon impl library "o"; extern impl C as I { } ``` -------------------------------- ### Package Directive Example Source: https://github.com/carbon-language/carbon-lang/blob/trunk/docs/design/code_and_name_organization/README.md Example of an implementation file declaration for a specific library within a package. ```carbon impl package Geometry library "Objects/FourSides"; ``` -------------------------------- ### Define Scrutinee and Pattern Matching Example Source: https://github.com/carbon-language/carbon-lang/blob/trunk/docs/design/pattern_matching.md Example demonstrating a tuple initialization that triggers multiple implicit function calls and conversions. ```carbon fn MakeA() -> A; fn MakeB() -> B; var cd: (C, D) = (MakeA(), MakeB()); ``` -------------------------------- ### Library Directive Example Source: https://github.com/carbon-language/carbon-lang/blob/trunk/docs/design/code_and_name_organization/README.md Example of an implementation file declaration for a library within the Main package. ```carbon impl library "PrimeGenerator"; ``` -------------------------------- ### Install rumdl formatter Source: https://github.com/carbon-language/carbon-lang/blob/trunk/docs/project/contribution_tools.md Installation commands for the rumdl Markdown formatter. ```bash cargo install --locked rumdl ``` ```bash brew install rumdl ``` -------------------------------- ### SemIR instruction examples Source: https://github.com/carbon-language/carbon-lang/blob/trunk/toolchain/docs/check/README.md Examples of formatted SemIR instruction lines. ```text %N: i32 = assoc_const_decl N [template] ``` ```text adapt_decl %SomeClass ``` ```text return %N to %return.param ``` -------------------------------- ### Syntactic Matching Examples Source: https://github.com/carbon-language/carbon-lang/blob/trunk/proposals/p003980-singular-extern-declarations.md Examples illustrating semantic versus syntactic matching in cross-library extern declarations. ```carbon library "a"; class A {} namespace NS; extern library "c" fn NS.F() -> A; ``` ```carbon library "b"; namespace NS; class A {} ``` ```carbon library "c"; import library "a" import library "b" extern fn NS.F() -> NS.A {} ``` ```carbon library "d"; class D {} namespace NS; extern library "e" fn NS.G() -> D; ``` ```carbon library "e"; namespace NS; alias NS.D = D; extern fn NS.G() -> D {} ``` -------------------------------- ### Install Carbon Syntax Highlighting for Vim Source: https://github.com/carbon-language/carbon-lang/blob/trunk/utils/vim/README.md Run these commands from the utils/vim directory to manually install the syntax and filetype detection files for Vim. ```bash mkdir -p ~/.vim/syntax && cp syntax/carbon.vim ~/.vim/syntax/ mkdir -p ~/.vim/ftdetect && cp ftdetect/carbon.vim ~/.vim/ftdetect/ ``` -------------------------------- ### Install Build Dependencies Source: https://github.com/carbon-language/carbon-lang/blob/trunk/README.md Installs the necessary tools for building the Carbon toolchain from source on Debian or Ubuntu systems. ```shell # Update apt. sudo apt update # Install tools. sudo apt install \ clang \ libc++-dev \ libc++abi-dev \ lld # Download Carbon's code. $ git clone https://github.com/carbon-language/carbon-lang $ cd carbon-lang ``` -------------------------------- ### Numeric Literal Usage Examples Source: https://github.com/carbon-language/carbon-lang/blob/trunk/docs/design/expressions/literals.md Various examples demonstrating variable initialization, generic function constraints, and literal-specific function parameters. ```carbon // This is OK: the initializer is of the integer literal type with value // -2147483648 despite being written as a unary `-` applied to a literal. var x: i32 = -2147483648; // This initializes y to 2^60. var y: i64 = 1 << 60; // This forms a rational literal whose value is one third, and converts it to // the nearest representable value of type `f64`. var z: f64 = 1.0 / 3.0; // This is an error: 300 cannot be represented in type `i8`. var c: i8 = 300; fn F[template T: type](v: T) { var x: i32 = v * 2; } // OK: x = 2_000_000_000. F(1_000_000_000); // Error: 4_000_000_000 can't be represented in type `i32`. F(2_000_000_000); // No storage required for the bound when it's of integer literal type. struct Span(template T: type, template BoundT: type) { var begin: T*; var bound: BoundT; } // Returns 1, because 1.3 can implicitly convert to f32, even though conversion // to f64 might be a more exact match. fn G() -> i32 { match (1.3) { case _: f32 => { return 1; } case _: f64 => { return 2; } } } // Can only be called with a literal 0. fn PassMeZero(_: Core.IntLiteral(0)); // Can only be called with integer literals in the given range. fn ConvertToByte[template N: Core.BigInt](_: Core.IntLiteral(N)) -> i8 if N >= -128 and N <= 127 { return N as i8; } // Given any int literal, produces a literal whose value is one higher. fn OneHigher(L: Core.IntLiteral(template _: Core.BigInt)) -> auto { return L + 1; } // Error: 256 can't be represented in type `i8`. var v: i8 = OneHigher(255); ``` -------------------------------- ### Install VS Code extension tools Source: https://github.com/carbon-language/carbon-lang/blob/trunk/utils/vscode/development.md Install the required vsce and ovsx tools globally via npm. ```bash npm install -g @vscode/vsce ovsx ``` -------------------------------- ### Import a package Source: https://github.com/carbon-language/carbon-lang/blob/trunk/proposals/p003938-exporting-imported-names.md Example of importing a package that contains re-exports. ```carbon package Wiz; import Bar; ``` -------------------------------- ### Configure CodeLLDB Source Mapping Source: https://github.com/carbon-language/carbon-lang/blob/trunk/toolchain/docs/debugging.md Example launch.json configuration for CodeLLDB to correctly map source files. ```json { "version": "0.2.0", "configurations": [ { "name": "explorer", "type": "lldb", "request": "launch", "program": "${workspaceRoot}/bazel-bin/explorer/explorer", "args": [], "cwd": "${workspaceRoot}", "sourceMap": { ".": "${workspaceRoot}" } } ] } ``` -------------------------------- ### Pattern Normal Form Examples Source: https://github.com/carbon-language/carbon-lang/blob/trunk/docs/design/variadics.md Examples of patterns that are not in normal form versus those that are. ```text [__N: Arity](... each x: Vector(«i32; __N»)) ``` ```text [__N: Arity](... each x: «Vector(i32); __N») ``` -------------------------------- ### Main Package Usage Example Source: https://github.com/carbon-language/carbon-lang/blob/trunk/proposals/p001088-generic-details-10-interface-implemented-requirements.md Demonstrates an attempt to use the defined packages to satisfy interface requirements for class C. ```Carbon package Main; import Interfaces; import Param; import Class; fn F[V:! Interfaces.B(Param.P)](x: V); fn Run() { var c: Class.C = {}; // Does Class.C implement Interfaces.B(Param.P)? F(c); } ``` -------------------------------- ### Launch LLDB with Local Configuration Source: https://github.com/carbon-language/carbon-lang/blob/trunk/toolchain/docs/debugging.md Starts LLDB with the repository's preset configuration, enabling features like the dump command. ```shell lldb --local-lldbinit bazel-bin/toolchain/carbon ``` -------------------------------- ### Lambda Expression Syntax Examples Source: https://github.com/carbon-language/carbon-lang/blob/trunk/proposals/p003848-lambdas.md Examples of lambda expressions used in an expression context. ```carbon // Lambdas (all the following are in an expression context and are // themselves expressions) fn => A1 fn [B, C] => A1 fn (D) => A2 fn [B, C](D) => A2 fn { E1; } fn -> F { E2; } fn [B, C] { E1; } fn [B, C] -> F { E2; } fn (D) { E3; } fn (D) -> F { E4; } fn [B, C](D) { E3; } fn [B, C](D) -> F { E4; } ``` -------------------------------- ### Run Toolchain Help Source: https://github.com/carbon-language/carbon-lang/blob/trunk/README.md Executes the toolchain's help command using the Bazel wrapper script. ```shell # Build and run the toolchain's help to get documentation on the command line. $ ./scripts/run_bazelisk.py run //toolchain -- help ``` -------------------------------- ### Pattern Canonical Form Example Source: https://github.com/carbon-language/carbon-lang/blob/trunk/docs/design/variadics.md Example demonstrating the canonical form of a full pattern. ```text [__N: Arity](... each x: «i32; __N», y: i32) ``` ```text [__N: Arity](... each __args: «i32; __N+1») ``` -------------------------------- ### Starting the generic definition region Source: https://github.com/carbon-language/carbon-lang/blob/trunk/toolchain/docs/check/associated_constant.md The generic definition region is started if an initializer is present. ```carbon let NAME:! TYPE = INITIALIZER ; ^ ``` -------------------------------- ### Member Access Syntax Examples Source: https://github.com/carbon-language/carbon-lang/blob/trunk/docs/design/expressions/member_access.md Demonstrates various member access patterns including simple field access, method calls, and compound member access using parentheses. ```carbon namespace Widgets; interface Widgets.Widget { fn Grow(ref self, factor: f64); } class Widgets.Cog { var size: i32; fn Make(size: i32) -> Self; extend impl as Widgets.Widget; } fn Widgets.GrowSomeCogs() { var cog1: Cog = Cog.Make(1); var cog2: Cog = cog1.Make(2); var cog_pointer: Cog* = &cog2; let cog1_size: i32 = cog1.size; cog1.Grow(1.5); cog2.(Cog.Grow)(cog1_size as f64); cog1.(Widget.Grow)(1.1); cog2.(Widgets.Cog.(Widgets.Widget.Grow))(1.9); cog_pointer->Grow(0.75); cog_pointer->(Widget.Grow)(1.2); } ``` -------------------------------- ### Alternative Syntax for Static and Dynamic Access Source: https://github.com/carbon-language/carbon-lang/blob/trunk/proposals/p000989-member-access-expressions.md Example demonstrating the use of double colons for static lookup and dots for instance binding. ```carbon var x: Package::Namespace::Class; Class::Function(); x.field = x.Function(); x.(Interface::Method)(); ``` -------------------------------- ### Start of associated constant declaration Source: https://github.com/carbon-language/carbon-lang/blob/trunk/toolchain/docs/check/associated_constant.md The start of an interface-scope let declaration triggers StartAssociatedConstant. ```carbon let NAME:! TYPE [= INITIALIZER] ; ^ ``` -------------------------------- ### Extern Type Re-exporting Examples Source: https://github.com/carbon-language/carbon-lang/blob/trunk/proposals/p003980-singular-extern-declarations.md Examples demonstrating the interaction between libraries and extern class definitions. ```carbon library "a" extern library "b" class A; ``` ```carbon library "b" import library "a" extern class A {} // B re-exports A so that it's complete on use. class B { var a: A; } ``` ```carbon library "c" import library "b" // Importing this function declaration gets B, which again, re-exports A so that // it's complete on use. fn F() -> B { ... } ``` ```carbon library "d" // This import loads the incomplete name for A. import library "a" // This import loads F, which loads B, which loads the definition of A. import library "c" // Because of the import behaviors, this is valid. var a: A; ``` -------------------------------- ### Interface and Implementation Member Access Source: https://github.com/carbon-language/carbon-lang/blob/trunk/docs/design/expressions/member_access.md Example demonstrating interface definition, implementation, and member resolution for both static and instance members. ```carbon interface Addable { // #1 fn Add(self, other: Self) -> Self; // #2 default fn Sum[Seq: Iterable where .ValueType = Self](seq: Seq) -> Self { // ... } alias AliasForSum = Sum; } class Integer { extend impl as Addable { // #3 fn Add(self, other: Self) -> Self; // #4, generated from default implementation for #2. // fn Sum[...](...); } alias AliasForAdd = Addable.Add; } ``` -------------------------------- ### Function Declaration Syntax Examples Source: https://github.com/carbon-language/carbon-lang/blob/trunk/proposals/p003848-lambdas.md Examples of function declarations used as statements or declarations in scopes. ```carbon // Function Declarations (all the following are allowed as statements in a // function body or as declarations in other scopes) fn G => A1; fn G[B, C] => A1; fn G(D) => A2; fn G[B, C](D) => A2; fn G { E1; } fn G -> F { E2; } fn G[B, C] { E1; } fn G[B, C] -> F { E2; } fn G(D) { E3; } fn G(D) -> F { E4; } fn G[B, C](D) { E3; } fn G[B, C](D) -> F { E4; } ``` -------------------------------- ### Example of implementations in an impl file Source: https://github.com/carbon-language/carbon-lang/blob/trunk/proposals/p000752-api-file-default-public.md Shows how functions are implemented in an impl file, including private and public visibility contexts. ```carbon fn Foo.Bar() { ...impl... } private fn Foo.Wiz() { ...impl... } fn Baz() { ...impl... } ``` -------------------------------- ### Proposed Digit Separator Examples Source: https://github.com/carbon-language/carbon-lang/blob/trunk/proposals/p001983-weaken-digit-separator-placement-rules.md Examples of the proposed flexible digit separator placement rules. ```text 1_2_3 ``` ```text 0xA_B_C ``` ```text 1_2.3_4e5_6 ``` -------------------------------- ### Floating-point literal examples Source: https://github.com/carbon-language/carbon-lang/blob/trunk/proposals/p000866-allow-ties-in-floating-literals.md Examples of floating-point literals that currently trigger tie-related errors in the compiler. ```carbon var v: f32 = 9.0e9; ``` ```carbon // Error, half way between two exactly representable values. var w: f64 = 5.0e22; ``` -------------------------------- ### Build project toolchain Source: https://github.com/carbon-language/carbon-lang/blob/trunk/utils/vscode/development.md Build the project toolchain from the root directory. ```bash bazel build //toolchain ``` -------------------------------- ### Integer and Real-number Literal Syntax Source: https://github.com/carbon-language/carbon-lang/blob/trunk/docs/design/lexical_conventions/numeric_literals.md Basic syntax examples for various integer bases and real-number formats. ```text 12345 0x1FE 0o755 0b1010 123.456 123.456e789 0x1.2p123 ``` -------------------------------- ### Unicode Escape Sequence Examples Source: https://github.com/carbon-language/carbon-lang/blob/trunk/proposals/p000199-string-literals.md Examples of Unicode escape sequence notations considered for the language. ```text \uNNNN ``` ```text \u{NNNN} ``` -------------------------------- ### Compile and Run a Carbon Program Source: https://github.com/carbon-language/carbon-lang/blob/trunk/README.md Downloads the nightly toolchain, creates a simple Carbon source file, compiles it to an object file, links it, and executes the resulting binary. ```shell # A variable with the nightly version from yesterday: VERSION="$(date -d yesterday +0.0.0-0.nightly.%Y.%m.%d)" # Get the release wget https://github.com/carbon-language/carbon-lang/releases/download/v${VERSION}/carbon_toolchain-${VERSION}.tar.gz # Unpack the toolchain: tar -xvf carbon_toolchain-${VERSION}.tar.gz # Create a simple Carbon source file: echo "import Core library \"io\"; fn Run() { Core.Print(42); }" > forty_two.carbon # Compile to an object file: ./carbon_toolchain-${VERSION}/bin/carbon compile \ --output=forty_two.o forty_two.carbon # Install minimal system libraries used for linking. Note that installing `gcc` # or `g++` for compiling C/C++ code with GCC will also be sufficient, these are # just the specific system libraries Carbon linking still uses. sudo apt install libgcc-11-dev # Link to an executable: ./carbon_toolchain-${VERSION}/bin/carbon link \ --output=forty_two forty_two.o # Run it: ./forty_two ``` -------------------------------- ### Alternative Digit Grouping Examples Source: https://github.com/carbon-language/carbon-lang/blob/trunk/proposals/p000143-numeric-literals.md Examples of flexible digit grouping for dates and time values. ```carbon var Date: d = 01_12_1983; ``` ```carbon var Int64: time_in_microseconds = 123456_000000; ``` -------------------------------- ### Current Carbon Package and Import Syntax Source: https://github.com/carbon-language/carbon-lang/blob/trunk/proposals/p000107-code-and-name-organization.md Demonstrates the existing syntax for declaring packages and importing libraries using the 'library' keyword. ```carbon package Math library "Median" api; package Math library "Median" namespace Stats api; import Math library "Median"; ``` -------------------------------- ### Initialization via return Source: https://github.com/carbon-language/carbon-lang/blob/trunk/docs/design/control_flow/return.md Shows how return expressions initialize variables directly without copies. ```carbon fn CreateMyObject() -> MyType { return ; } var x: MyType = CreateMyObject(); ``` ```carbon var x: MyType = ; ``` -------------------------------- ### Constraint Resolution Examples Source: https://github.com/carbon-language/carbon-lang/blob/trunk/proposals/p002173-associated-constant-assignment-versus-equality.md Examples demonstrating valid and invalid constraint resolutions involving associated constants. ```carbon // ✅ `.T` in `.U = .T` is rewritten to `i32` when initially // forming the facet type. // Nothing to do during constraint resolution. fn InOrder[A:! C where .T = i32 and .U = .T]() {} // ✅ Facet type has `.T = .U` before constraint resolution. // That rewrite is resolved to `.T = i32`. fn Reordered[A:! C where .T = .U and .U = i32]() {} // ✅ Facet type has `.U = .T` before constraint resolution. // That rewrite is resolved to `.U = i32`. fn ReorderedIndirect[A:! (C where .T = i32) & (C where .U = .T)]() {} // ❌ Constraint resolution fails because // no fixed point of rewrites exists. fn Cycle[A:! C where .T = .U and .U = .T]() {} ``` -------------------------------- ### Launch LLDB for Carbon Source: https://github.com/carbon-language/carbon-lang/blob/trunk/toolchain/docs/debugging.md Basic command to start an LLDB session with a built Carbon binary. ```shell lldb bazel-bin/toolchain/carbon ``` -------------------------------- ### Indirect recursion examples Source: https://github.com/carbon-language/carbon-lang/blob/trunk/proposals/p000826-function-return-type-inference.md Examples showing valid indirect recursion and invalid name lookup scenarios. ```carbon fn ExplicitReturn() -> i32; fn AutoReturn() -> auto { return ExplicitReturn(); } fn ExplicitReturn() -> i32 { return AutoReturn(); } ``` ```carbon fn A() -> auto { return B(); } fn B() -> auto { return A(); } ``` -------------------------------- ### Direct recursion examples Source: https://github.com/carbon-language/carbon-lang/blob/trunk/proposals/p000826-function-return-type-inference.md Examples of direct recursion that are rejected due to complexities in return type inference. ```carbon // In the return statement. fn Factorial(x: i32) -> auto { return (if x == 1 then x else x * Factorial(x - 1)); } // Before the return statement, but affecting the return type. fn Factorial(x: i32) -> auto { var x: auto = (if x == 1 then x else x * Factorial(x - 1)); return x; } ``` -------------------------------- ### Compare let and var binding patterns Source: https://github.com/carbon-language/carbon-lang/blob/trunk/docs/design/values.md Illustrates the difference between value bindings (let) and variable patterns (var) regarding mutability and address-taking. ```carbon fn MutateThing(ptr: i64*); fn Example() { // `1` starts as a value expression, which is what a value binding expects. let x: i64 = 1; // `2` also starts as a value expression, but the variable pattern requires it // to be converted to an ephemeral entire reference expression by using the // value `2` to initialize temporary storage, which the variable pattern // takes ownership of. The reference binding pattern is then bound to a // durable reference to the newly-initialized object. var y: i64 = 2; // Allowed to take the address and mutate `y` as it is a durable reference // expression. MutateThing(&y); // ❌ This would be an error though due to trying to take the address of the // value expression `x`. MutateThing(&x); } ``` -------------------------------- ### Workaround examples for floating-point ties Source: https://github.com/carbon-language/carbon-lang/blob/trunk/proposals/p000866-allow-ties-in-floating-literals.md Examples of workarounds for floating-point ties that are currently required but considered cumbersome. ```carbon var v: f32 = 5 * 1.0e22; ``` ```carbon var v1: f32 = 5.0e22 + 1.0; var v2: f32 = 5.0e22 - 1.0; ``` -------------------------------- ### Well-shaped pack expansion examples Source: https://github.com/carbon-language/carbon-lang/blob/trunk/docs/design/variadics.md Examples of well-shaped expressions involving pack literals and arity coercions. ```text ⟬each X, Y⟭: «Z; N+1» ``` ```text (⟬each X, Y⟭, «Z; N+1») ``` -------------------------------- ### API and Implementation File Shadowing Example Source: https://github.com/carbon-language/carbon-lang/blob/trunk/proposals/p003763-matching-redeclarations.md Demonstrates a scenario where shadowing a class in an implementation file after it has been used in an API file results in an error. ```carbon library "foo" api; namespace N; class A {} fn N.F(x: A); ``` ```carbon library "foo" impl; // ❌ Shadows `class A`. Cannot declare `N.A` after we already // looked for it in the declaration of `N.F`. class N.A {} fn N.F(x: A) {} ``` -------------------------------- ### Interface and Class Impl Lookup Examples Source: https://github.com/carbon-language/carbon-lang/blob/trunk/proposals/p002360-types-are-values-of-type-type.md Demonstrates various scenarios for impl lookup using interfaces, classes, and derived classes in Carbon. ```carbon interface Iface { fn Static(); fn Method[me: Self](); } impl type as Iface { ... } fn F[T:! Iface](x: T) { // ✅ Uses `T as Iface`. x.Static(); T.Static(); // ❌ Uses `T as Iface`, but method call is missing an instance. T.Method(); // ✅ OK, instance is provided. Uses `T as Iface`. x.Method(); x.(T.Method)(); // ❌ Would use `(x as Iface).Static`. // Error because `x` is not a symbolic constant. x.(Iface.Static)(); // ✅ Uses `(T as Iface).Static`. T.(Iface.Static)(); // ✅ Uses `(type as Iface).Static`. type.(Iface.Static)(); // ✅ Uses `(T as Iface).Method`, with `me = x`. x.(Iface.Method)(); // ✅ Uses `(type as Iface).Method`, with `me = T`. T.(Iface.Method)(); } base class Base { fn Static(); fn Method[me: Self](); alias IfaceStatic = Iface.Static; alias IfaceMethod = Iface.Method; } external impl Base as Iface { ... } fn G(b: Base) { // ✅ OK b.Static(); Base.Static(); // ❌ Uses `Base as Iface`, but method call is missing an instance. Base.Method(); // ✅ OK b.Method(); b.(Base.Method)(); // ✅ OK, same as `(Base as Iface).Static()`. b.IfaceStatic(); Base.IfaceStatic(); // ❌ Uses `Base as Iface`, but method call is missing an instance. Base.IfaceMethod(); // ✅ OK, uses `Base as Iface`. b.IfaceMethod(); b.(Base.IfaceMethod)(); b.((Base as Iface).Method)(); b.(Iface.Method)(); } class Derived extends Base {} external impl Derived as Iface { ... } fn H(d: Derived) { // ✅ OK, calls `Base.Static`. d.Static(); Derived.Static(); // ❌ Uses `Derived as Iface`, but method call is missing an instance. Derived.Method(); // ✅ OK, calls `Base.Method`. d.Method(); d.(Base.Method)(); d.(Derived.Method)(); // ✅ OK, same as `(Derived as Iface).Static()`. d.IfaceStatic(); Derived.IfaceStatic(); // ❌ Uses `Derived as Iface`, but method call is missing an instance. Derived.IfaceMethod(); // ✅ OK, uses `Derived as Iface`. d.IfaceMethod(); d.(Derived.IfaceMethod)(); d.((Derived as Iface).Method)(); d.(Iface.Method)(); // ✅ OK, uses `Base as Iface`. d.(Base.IfaceMethod)(); d.((Base as Iface).Method)(); } ``` -------------------------------- ### Demonstrate inconsistent behavior in Trouble package Source: https://github.com/carbon-language/carbon-lang/blob/trunk/docs/design/generics/appendix-coherence.md Shows how importing different implementations leads to unexpected lookup failures. ```carbon package Trouble; import SongLib; import SongHashAppleMusicURL; import Containers; import SongUtil; fn SomethingWeirdHappens() { var unchained_melody: SongLib.Song = ...; var song_set: auto = Containers.HashSet(SongLib.Song).Make(); song_set.Add(unchained_melody); // Either this is a compile error or does something unexpected. if (SongUtil.IsInHashSet(unchained_melody, &song_set)) { Print("This is expected, but doesn't happen."); } else { Print("This is what happens even though it is unexpected."); } } ``` -------------------------------- ### Illegal ad hoc specialization example Source: https://github.com/carbon-language/carbon-lang/blob/trunk/proposals/p002200-template-generics.md An example of an illegal specialization attempt that would break type checking. ```carbon // ❌ Not legal Carbon, no ad hoc specialization class Vector(bool) { // `let p: T* = vec->GetPointer(0)` won't type check // in `SetFirst` with `T == bool`. fn GetPointer[addr me: Self*](index: i32) -> BitProxy; // ... } ``` -------------------------------- ### Implementation Comments Example Source: https://github.com/carbon-language/carbon-lang/blob/trunk/proposals/p000198-comments.md Shows short comments used to explain intent or summarize behavior within function bodies. ```carbon void WidgetAssembly::decorate(bool repaint_all) { // ... // Paint all the widgets that have been changed since last time. for (auto &w : widgets) { if (repaint_all || w.modified > last_foo) w.paint(); } last_decorate = now(); // ... } ``` -------------------------------- ### Legacy Digit Separator Examples Source: https://github.com/carbon-language/carbon-lang/blob/trunk/proposals/p001983-weaken-digit-separator-placement-rules.md Examples of strict digit separator placement rules as defined in Proposal #143. ```text 2_147_483_648 ``` ```text 0x7FFF_FFFF ``` ```text 2_147.483648e12_345 ``` ```text 0x1_00CA.FEF00Dp+24 ``` ```text 0b1_000_101_11 ``` -------------------------------- ### Interface and Implementation Access Patterns Source: https://github.com/carbon-language/carbon-lang/blob/trunk/proposals/p000989-member-access-expressions.md Demonstrates various member access scenarios involving interfaces, classes, and their implementations to illustrate the proposed syntax rules. ```carbon interface MyInterface { fn F(); fn G[me: Self](); } class MyClass { alias InterfaceAlias = MyInterface; impl as MyInterface { fn F(); fn G[me: Self](); } } fn G(x: MyClass) { // OK with this proposal and the alternative. MyClass.(MyInterface.F)(); // Error with this proposal, OK with the alternative. MyClass.(MyInterface).F(); // Names the interface with this proposal. // Names the `impl` with the alternative. alias AnotherInterfaceAlias = MyClass.InterfaceAlias; // Error with this proposal, OK with the alternative. MyClass.InterfaceAlias.F(); // OK with this proposal, error with the alternative. MyClass.(MyClass.InterfaceAlias.F)(); // Error under this proposal, OK with the alternative. x.MyInterface.F(); // Error under both this proposal. // Also error under the alternative, unless we introduce // a notion of a "bound `impl`" so that `x.MyInterface` // remembers its receiver object. x.MyInterface.G(); // OK under this proposal and the alternative. x.(MyInterface.G)(); } ``` -------------------------------- ### Whitespace-sensitive operator examples Source: https://github.com/carbon-language/carbon-lang/blob/trunk/proposals/p000601-operator-tokens.md Examples illustrating potential whitespace requirements for binary operators followed by brackets or braces. ```carbon fn F() -> Int*{ return Null; } var n: Int = pointer_to_array^[i]; ``` -------------------------------- ### ANSI Terminal Escape Sequence Example Source: https://github.com/carbon-language/carbon-lang/blob/trunk/proposals/p000199-string-literals.md Example of using an escape sequence for ANSI terminal color formatting. ```text "\e[32mgreen text\e[0m" ``` -------------------------------- ### Documentation Comments Example Source: https://github.com/carbon-language/carbon-lang/blob/trunk/proposals/p000198-comments.md Demonstrates the use of triple-slash syntax for API documentation attached to class and member declarations. ```carbon /// A container for a collection of connected widgets. class WidgetAssembly { /// Improve the appearance of the assembly if possible. void decorate(bool repaint_all = false); // ... }; ``` -------------------------------- ### Compile and link Carbon files Source: https://github.com/carbon-language/carbon-lang/blob/trunk/proposals/p006333-cli-and-separate-compilation.md Demonstrates the basic workflow for compiling a Carbon source file to an object file and linking it into an executable. ```sh carbon compile foo.carbon -o foo.o carbon link foo.o -o program ``` -------------------------------- ### Hexadecimal Escape Sequence Examples Source: https://github.com/carbon-language/carbon-lang/blob/trunk/proposals/p000199-string-literals.md Examples of hexadecimal escape sequences, including the proposed fixed-length and variable-length syntax. ```text \xAB\ C ``` ```text \x{ABCD} ``` -------------------------------- ### Variadic implementation comparison Source: https://github.com/carbon-language/carbon-lang/blob/trunk/docs/design/generics/details.md Conceptual example of using variadics to generalize implementation comparisons. ```carbon fn CombinedCompare[T: type] (a: T, b: T, ... generic each CompareT: CompatibleWith(T) & Ordered) -> CompareResult { ... block { let result: CompareResult = (a as each CompareT).Compare(b as each CompareT); if (result != CompareResult.Equal) { return result; } } return CompareResult.Equal; } assert(CombinedCompare(s1, s2, SongByArtist, SongByTitle) == CompareResult.Less); ``` -------------------------------- ### Designator type conversion example Source: https://github.com/carbon-language/carbon-lang/blob/trunk/proposals/p000157-design-direction-for-sum-types.md Example of treating bare designators as types that implicitly convert to sum types. ```carbon .Some(42) ```