CodeSampleX

Exemple

quote 1.0.47: quote::ToTokens

Échantillon vérifié pour cargo quote 1.0.47: quote::ToTokens. Le contrat s'est exécuté sur rust 1 · linux alpine/x64 · docker et a réussi.

sha256:6398cd28a39823a4bd7345150c8a9f1072ffb6eed5021f78d54c7217620c6917

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
1
Clés de signature qui l’ont compilé
1
Environnement déclaré linux · musl x64 cargo

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
rust 1 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · cargo@1rust:1-alpine@sha256:a10e64dd139b…
2026-09-14

Cas

HOW
Objectif
verify quote::ToTokens in pkg:cargo/quote@1.0.47
Paquets
Symboles
  • quote::ToTokens
Créé
2026-09-14T07:09:20Z

Contrat

  1. assert custom struct implements ToTokens to append visibility, identifier, and type tokens into TokenStream
  2. assert to_token_stream and into_token_stream convert ToTokens implementors directly into TokenStream
  3. assert Option<T> implements ToTokens by emitting inner tokens when Some and emitting nothing when None
  4. assert bool implements ToTokens by emitting boolean ident rather than a literal
  5. assert integer and string types implement ToTokens by emitting typed literals
  6. assert pointer wrappers Box, Rc, Arc, and references transparently delegate ToTokens

Fichiers

  • Cargo.lock
  • Cargo.toml
  • NOTES.md
  • PROMPT.md
  • csx.json
  • spec.json
  • src/main.rs

Télécharger l’artefact source (tar.gz)

Code source

Cargo.lock
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4

[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
 "unicode-ident",
]

[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
 "proc-macro2",
]

[[package]]
name = "quote-to-tokens"
version = "0.1.0"
dependencies = [
 "proc-macro2",
 "quote",
]

[[package]]
name = "unicode-ident"
version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
Cargo.toml
[package]
name = "quote-to-tokens"
version = "0.1.0"
edition = "2021"
license = "MIT-0"

[dependencies]
quote = "1.0.47"
proc-macro2 = "1.0.107"
NOTES.md
# CSX Sample Notes: `quote::ToTokens` Trait Implementation, TokenStream Conversion, and Primitive Interpolation

## Search Known Solution Result
- `search_known_solution` returned `NO_SAFE_MATCH` for `quote::ToTokens` in `pkg:cargo/quote@1.0.47`.
- **Why this sample is distinct**: Demonstrates the contract and behaviors of `quote::ToTokens`, which powers Rust quasi-quoting (`quote!`). Specifically proves custom trait implementation via `TokenStreamExt::append_all`, direct conversion methods `to_token_stream` and `into_token_stream`, wrapper type delegation (`Box`, `Rc`, `Arc`, `Cow`, references), `Option<T>` conditional token emission (emitting empty stream on `None`), and primitive tokenization (e.g., `bool` emitting `Ident` vs numeric literals emitting suffixed `Literal`).

## What a Model Would Have Written Instead
A model might assume `bool` produces a boolean literal rather than an `Ident`, or assume that converting a type to tokens requires manual string formatting rather than leveraging the `ToTokens` trait contract with `TokenStreamExt` and `to_token_stream()`.

## How the Wrong Version Fails
Manual string interpolation loses span information, hygiene, and macro token tree hierarchy. Furthermore, expecting `None` in `Option<T>` to produce a syntax error or a placeholder token rather than vanishing cleanly leads to incorrect AST generation in procedural macros.
PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify quote::ToTokens in pkg:cargo/quote@1.0.47
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:cargo/quote@1.0.47
Demonstrate these symbols/APIs:
  - quote::ToTokens

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:8053ce4b6f5e369c481973af573535b27920ef20e3ae9457e800d26b9ce6849b","contract":["assert custom struct implements ToTokens to append visibility, identifier, and type tokens into TokenStream","assert to_token_stream and into_token_stream convert ToTokens implementors directly into TokenStream","assert Option\u003cT\u003e implements ToTokens by emitting inner tokens when Some and emitting nothing when None","assert bool implements ToTokens by emitting boolean ident rather than a literal","assert integer and string types implement ToTokens by emitting typed literals","assert pointer wrappers Box, Rc, Arc, and references transparently delegate ToTokens"],"goal":"verify quote::ToTokens in pkg:cargo/quote@1.0.47","kind":"HOW","packages":["pkg:cargo/quote@1.0.47"],"schemaVersion":1,"symbols":["quote::ToTokens"]},"contractCommand":["cargo","run","--offline"],"environment":{"arch":"x64","ecosystem":"cargo","libc":"musl","os":"linux","packageManager":"cargo","schemaVersion":1},"license":"MIT-0","packages":["pkg:cargo/quote@1.0.47"],"schemaVersion":1,"subject":"pkg:cargo/quote@1.0.47","symbols":["quote::ToTokens"],"verifierAdapter":"cargo@1"}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify quote::ToTokens in pkg:cargo/quote@1.0.47",
  "kind": "HOW",
  "packages": [
    "pkg:cargo/quote@1.0.47"
  ],
  "symbols": [
    "quote::ToTokens"
  ]
}
src/main.rs
use std::borrow::Cow;
use std::rc::Rc;
use std::sync::Arc;
use proc_macro2::{Ident, Span, TokenStream};
use quote::{quote, ToTokens, TokenStreamExt};

pub struct FieldDef {
    pub name: &'static str,
    pub ty: &'static str,
    pub is_pub: bool,
}

impl ToTokens for FieldDef {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let vis = if self.is_pub {
            quote!(pub)
        } else {
            quote!()
        };
        let ident = Ident::new(self.name, Span::call_site());
        let ty_ident = Ident::new(self.ty, Span::call_site());
        tokens.append_all(quote! {
            #vis #ident: #ty_ident
        });
    }
}

fn run_contract_assertions() {
    // 1. Custom struct implements ToTokens to append visibility, identifier, and type tokens
    let public_field = FieldDef {
        name: "count",
        ty: "usize",
        is_pub: true,
    };
    let private_field = FieldDef {
        name: "secret",
        ty: "String",
        is_pub: false,
    };

    let pub_tokens = public_field.to_token_stream();
    assert_eq!(pub_tokens.to_string(), "pub count : usize");

    let priv_tokens = private_field.to_token_stream();
    assert_eq!(priv_tokens.to_string(), "secret : String");

    // 2. to_token_stream and into_token_stream convert ToTokens implementors directly
    let stream_from_ref = (&public_field).to_token_stream();
    assert_eq!(stream_from_ref.to_string(), "pub count : usize");

    let stream_from_into = public_field.into_token_stream();
    assert_eq!(stream_from_into.to_string(), "pub count : usize");

    // 3. Option<T> emits inner tokens when Some, emits nothing when None
    let some_val: Option<i32> = Some(42);
    let none_val: Option<i32> = None;

    let some_stream = quote!(value: #some_val);
    assert_eq!(some_stream.to_string(), "value : 42i32");

    let none_stream = quote!(value: #none_val);
    assert_eq!(none_stream.to_string(), "value :");

    // 4. bool emits boolean Ident rather than a literal
    let true_val = true;
    let false_val = false;
    let bool_tokens = quote!(#true_val, #false_val);
    assert_eq!(bool_tokens.to_string(), "true , false");

    // 5. Integer and string types emit typed literals
    let num: i32 = 100;
    let s: &str = "hello";
    let lit_tokens = quote!(#num, #s);
    assert_eq!(lit_tokens.to_string(), "100i32 , \"hello\"");

    // 6. Pointer wrappers Box, Rc, Arc, and Cow transparently delegate ToTokens
    let boxed = Box::new(private_field);
    let rc = Rc::new(boxed);
    let arc = Arc::new(rc);
    let cow: Cow<'static, str> = Cow::Borrowed("borrowed");

    let wrapped_tokens = quote!(#arc, #cow);
    assert_eq!(wrapped_tokens.to_string(), "secret : String , \"borrowed\"");
}

fn main() {
    run_contract_assertions();
    println!("All quote::ToTokens contract assertions passed.");
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_to_tokens_contract() {
        run_contract_assertions();
    }
}

Seeder d'origine

anonyme