id
stringlengths
20
30
source
stringclasses
1 value
chunk_index
int64
0
520k
token_count
int32
154
512
content
stringlengths
185
57.5k
rust_dataset_chunk_508800
rust_dataset.txt
508,800
512
ReviewSuccess::PullRequestReviewed(_)))); } #[tokio::test] async fn non_approved_review_state_is_not_accepted() { let result = TestScenario::single_commit() .with_reviews(vec![review( "bob", ReviewState::Other, AuthorAssociation::Member, ...
rust_dataset_chunk_508801
rust_dataset.txt
508,801
512
(ReviewSuccess::ApprovingComment(_)))); } #[tokio::test] async fn comment_without_approval_pattern_is_not_accepted() { let result = TestScenario::single_commit() .with_comments(vec![comment( "bob", "looks good", AuthorAssociation::Member, ...
rust_dataset_chunk_508802
rust_dataset.txt
508,802
512
Scenario::single_commit() .with_commit_metadata_json(serde_json::json!({ "abc12345abc12345": { "author": alice_author(), "authors": { "nodes": [bob_author()] } } })) .with_commit(make_commit( "abc...
rust_dataset_chunk_508803
rust_dataset.txt
508,803
512
", ReviewState::Other, AuthorAssociation::None) .with_body("@zed-zippy approve"), ]) .run_scenario() .await; assert!(matches!(result, Err(ReviewFailure::Unreviewed))); } #[tokio::test] async fn review_with_approving_body_from_pr_author_is_reje...
rust_dataset_chunk_508804
rust_dataset.txt
508,804
512
NotSigned )) )); } #[tokio::test] async fn zippy_version_bump_with_invalid_signature_fails() { let result = TestScenario::zippy_version_bump() .with_commit_metadata_json(serde_json::json!({ "abc12345abc12345": { "author": zippy_aut...
rust_dataset_chunk_508805
rust_dataset.txt
508,805
512
)) )); } #[tokio::test] async fn zippy_version_bump_with_co_authors_fails() { let result = TestScenario::zippy_version_bump() .with_commit_metadata_json(serde_json::json!({ "abc12345abc12345": { "author": zippy_author(), "...
rust_dataset_chunk_508806
rust_dataset.txt
508,806
512
::single_commit() .with_commit(make_commit( "abc12345abc12345", "Zed Zippy", ZED_ZIPPY_EMAIL, "Some change (#1234)", "", )) .with_reviews(vec![review( "bob", ReviewState::A...
rust_dataset_chunk_508807
rust_dataset.txt
508,807
512
{ self.user.as_ref().map(|user| user.login.as_str()) } fn review_state(&self) -> Option<ReviewState> { self.state } fn body(&self) -> Option<&str> { self.body.as_deref() } fn author_association(&self) -> Option<AuthorAssociation> { self.author_association ...
rust_dataset_chunk_508808
rust_dataset.txt
508,808
512
, Clone)] pub struct CommitSignature { #[serde(rename = "isValid")] is_valid: bool, signer: Option<GithubLogin>, } impl CommitSignature { pub fn is_valid(&self) -> bool { self.is_valid } pub fn signer(&self) -> Option<&GithubLogin> { self.signer.as_ref() } } #[derive(Debug...
rust_dataset_chunk_508809
rust_dataset.txt
508,809
512
CommitSha::new(sha.to_owned()), value) }) .collect(); Ok(Self(map)) } } #[derive(Clone)] pub struct Repository<'a> { owner: Cow<'a, str>, name: Cow<'a, str>, } impl<'a> Repository<'a> { pub const ZED: Repository<'static> = Repository::new_static("zed-industries", "zed")...
rust_dataset_chunk_508810
rust_dataset.txt
508,810
512
}; use itertools::Itertools as _; use serde::Deserialize; use crate::git::CommitSha; use super::CommitMetadataBySha; #[derive(Debug, Deserialize)] pub struct GraphQLResponse<T> { pub data: Option<T>, pub errors: Option<Vec<GraphQLError>>, } impl<T> GraphQLResponse<T> ...
rust_dataset_chunk_508811
rust_dataset.txt
508,811
512
") {{ {objects} }} }}") .replace("\n", "") } } #[cfg(feature = "octo-client")] mod octo_client { use anyhow::{Context, Result}; use futures::TryStreamExt as _; use jsonwebtoken::EncodingKey; use octocrab::{ Octocrab, Page, models::{ AuthorAssociation as Octo...
rust_dataset_chunk_508812
rust_dataset.txt
508,812
512
")? .take_items(); let installation_id = installations .into_iter() .find(|installation| installation.account.login == org) .context("Could not find Zed repository in installations")? .id; let client = octocrab.ins...
rust_dataset_chunk_508813
rust_dataset.txt
508,813
512
RequestReview>> { let page = self .client .pulls(repo.owner.as_ref(), repo.name.as_ref()) .list_reviews(pr_number) .per_page(PAGE_SIZE) .send() .await?; let reviews = self.get_all(page).await?; ...
rust_dataset_chunk_508814
rust_dataset.txt
508,814
512
()) .await?; Ok(response .files .into_iter() .flatten() .map(|file| CommitFileChange { filename: file.filename, }) .collect()) } async fn check_repo_write_per...
rust_dataset_chunk_508815
rust_dataset.txt
508,815
512
o-client")] pub use octo_client::OctocrabClient; --- FILE: zed/tooling/compliance/src/git.rs --- #![allow(clippy::disallowed_methods, reason = "This is only used in xtasks")] use std::{ fmt::{self, Debug}, ops::Not, process::Command, str::FromStr, sync::LazyLock, }; use anyhow::{Context, Result, ...
rust_dataset_chunk_508816
rust_dataset.txt
508,816
512
-> Result<G::ParsedOutput> { let command_output = Command::new("git") .args(self.subcommand.args()) .output() .context("Failed to spawn command")?; if command_output.status.success() { String::from_utf8(command_output.stdout) .map_err(|_|...
rust_dataset_chunk_508817
rust_dataset.txt
508,817
512
pub fn short(&self) -> &str { self.0.as_str().split_at(8).0 } } #[derive(Debug)] pub struct CommitDetails { sha: CommitSha, author: Committer, title: String, body: String, } impl CommitDetails { pub fn new(sha: CommitSha, author: Committer, title: String, body: String) -> Self { ...
rust_dataset_chunk_508818
rust_dataset.txt
508,818
512
new(author_name, author_email), title: title.to_owned(), body: body.to_owned(), }) } pub fn pr_number(&self) -> Option<u64> { // Since we use squash merge, all commit titles end with the '(#12345)' pattern. // While we could strictly speaking index into this dire...
rust_dataset_chunk_508819
rust_dataset.txt
508,819
512
0-9]+\.[0-9]+\.x (?:stable|preview) for @([a-zA-Z0-9][a-zA-Z0-9-]*)$") .unwrap() }); VERSION_BUMP_REGEX .captures(&self.title) .and_then(|capture| capture.get(1)) .map(|r#match| (AutomatedChangeKind::VersionBump, r#match.as_str())) .or_els...
rust_dataset_chunk_508820
rust_dataset.txt
508,820
512
(mut self) -> Self { self.0.sort_by(|a, b| a.version().cmp(b.version())); self } pub fn find_previous_minor_version(&self, version_tag: &VersionTag) -> Option<&VersionTag> { self.0 .iter() .take_while(|tag| tag.version() < version_tag.version()) .coll...
rust_dataset_chunk_508821
rust_dataset.txt
508,821
512
), ] } } pub struct NoOutput; impl FromStr for NoOutput { type Err = anyhow::Error; fn from_str(_: &str) -> Result<Self, Self::Err> { Ok(NoOutput) } } #[cfg(test)] mod tests { use super::*; use indoc::indoc; #[test] fn parse_stable_version_tag() { ...
rust_dataset_chunk_508822
rust_dataset.txt
508,822
512
v0.172.9 "}; let list = VersionTagList::from_str(input).unwrap().sorted(); for window in list.0.windows(2) { assert!( window[0].version() <= window[1].version(), "{} should come before {}", window[0].to_string(), ...
rust_dataset_chunk_508823
rust_dataset.txt
508,823
512
(); assert_eq!(previous.to_string(), "v0.172.0"); } #[test] fn find_previous_minor_requires_zero_patch_version() { let input = indoc! {" v0.172.1 v0.172.9 v0.172.11 "}; let list = VersionTagList::from_str(input).unwrap().sorted(); ...
rust_dataset_chunk_508824
rust_dataset.txt
508,824
512
co_authors_parsed_from_body() { let line = format!( "abc123{d}Author Name{d}author@email.com{d}Some title", d = CommitDetails::FIELD_DELIMITER ); let body = indoc! {" Co-authored-by: Alice Smith <alice@example.com> Co-authored-by: Bob Jones <bob@e...
rust_dataset_chunk_508825
rust_dataset.txt
508,825
512
, "").unwrap(); let (kind, actor) = commit.detect_automated_change().unwrap(); assert_eq!(kind, AutomatedChangeKind::ReleaseChannelUpdate); assert_eq!(actor, "cole-miller"); } #[test] fn automated_change_detects_preview_release_channel() { let line = format!( "ab...
rust_dataset_chunk_508826
rust_dataset.txt
508,826
512
itter = Committer::new("Alice", "alice@test.com"); assert!(!committer.is_zed_zippy()); } #[test] fn parse_commit_list_from_git_log_format() { let fd = CommitDetails::FIELD_DELIMITER; let bd = CommitDetails::BODY_DELIMITER; let cd = CommitDetails::COMMIT_DELIMITER; l...
rust_dataset_chunk_508827
rust_dataset.txt
508,827
512
Details, reason: R, } impl<R> ReportEntry<R> { pub fn new(commit: CommitDetails, reason: R) -> Self { Self { commit, reason } } } impl<R: ToString> ReportEntry<R> { fn commit_cell(&self) -> String { let title = escape_markdown_link_text(self.commit.title()); match self.commit....
rust_dataset_chunk_508828
rust_dataset.txt
508,828
512
entry.commit.pr_number().is_some()) .count(), other_checked: entries .iter() .filter(|entry| entry.reason.is_ok() && entry.commit.pr_number().is_none()) .count(), not_reviewed: entries .iter() .filte...
rust_dataset_chunk_508829
rust_dataset.txt
508,829
512
) = path .parent() .filter(|parent| !parent.as_os_str().is_empty()) { fs::create_dir_all(parent).with_context(|| { format!( "Failed to create parent directory for markdown report at {}", path.display() ) ...
rust_dataset_chunk_508830
rust_dataset.txt
508,830
512
, "No unreviewed commits found.")?; } writeln!(writer)?; return Ok(()); } writeln!(writer, "| Commit | PR | Author | Outcome | Reason |")?; writeln!(writer, "| --- | --- | --- | --- | --- |")?; for entry in issues { let issue_kind = entry.issue_kind(); writeln!(...
rust_dataset_chunk_508831
rust_dataset.txt
508,831
512
: &str, body: &str, ) -> CommitDetails { let formatted = format!( "{sha}|field-delimiter|{author_name}|field-delimiter|{author_email}|field-delimiter|{title}|body-delimiter|{body}|commit-delimiter|" ); CommitList::from_str(&formatted) .expect("test commit shou...
rust_dataset_chunk_508832
rust_dataset.txt
508,832
512
report.add( make_commit("aaa", "Alice", "alice@test.com", "First (#100)", ""), Ok(reviewed()), ); report.add( make_commit("bbb", "Bob", "bob@test.com", "Second (#200)", ""), Ok(reviewed()), ); let summary = report.summary(); ...
rust_dataset_chunk_508833
rust_dataset.txt
508,833
512
_DIR").unwrap(); let _ = fs::remove_dir_all(&out_dir); let _ = fs::create_dir(&out_dir); } --- FILE: zed/tooling/corgi/patches/scratch/src/lib.rs --- //! A corgi-compatible `scratch` implementation. //! //! Upstream bakes its own OUT_DIR in at compile time (`env!`), making one //! global directory that every ...
rust_dataset_chunk_508834
rust_dataset.txt
508,834
512
-> Result<Crate>; /// Lists both user and team owners. async fn list_owners(&self, name: &CrateName) -> Result<Vec<Owner>>; /// Returns one outcome per requested owner. /// /// Requires a token with the `change-owners` endpoint scope that belongs /// to a user owner of the crate. crates.io ac...
rust_dataset_chunk_508835
rust_dataset.txt
508,835
512
Error { fn from_response(status: StatusCode, body: &str) -> Self { #[derive(Deserialize)] struct ErrorResponse { errors: Vec<ErrorDetail>, } #[derive(Deserialize)] struct ErrorDetail { detail: String, } let message = match serde_json:...
rust_dataset_chunk_508836
rust_dataset.txt
508,836
512
pub(crate) fn reserve(&self, now: Instant) -> Instant { let mut next_request_at = self.next_request_at.lock(); let send_at = next_request_at.map_or(now, |next_request_at| next_request_at.max(now)); *next_request_at = Some(send_at + MIN_REQUEST_INTERVAL); send_at } } /// The request...
rust_dataset_chunk_508837
rust_dataset.txt
508,837
512
with_context(|| format!("Failed to send crates.io request to {url}"))?; if !response.status().is_success() { let mut body = String::new(); response .body_mut() .read_to_string(&mut body) .await .with_context(|| format!("Fai...
rust_dataset_chunk_508838
rust_dataset.txt
508,838
512
an owner of crate {crate_name}"); message .split(',') .map(|sentence| { let user = sentence.strip_prefix("Crates.io user "); if let Some(username) = user.and_then(|rest| rest.strip_suffix(&invited_suffix)) { OwnerAddition::UserInvited { u...
rust_dataset_chunk_508839
rust_dataset.txt
508,839
512
pairs.append_pair("include_yanked", "no"); } } let mut crates = Vec::new(); loop { let mut page: CrateListResponse = self.request_json(Method::GET, url, None).await?; let is_full_page = page.crates.len() == MAX_PER_PAGE; crates.app...
rust_dataset_chunk_508840
rust_dataset.txt
508,840
512
async fn add_owners( &self, name: &CrateName, owners: &[OwnerLogin], ) -> Result<Vec<OwnerAddition>> { let message = self.change_owners(Method::PUT, name, owners).await?; Ok(parse_owner_additions(&message, name)) } async fn remove_owners(&self, name: &CrateName, ...
rust_dataset_chunk_508841
rust_dataset.txt
508,841
512
_io_client.rs --- use std::{collections::BTreeMap, sync::Arc}; use async_trait::async_trait; use chrono::{DateTime, Utc}; use http_client::StatusCode; use parking_lot::Mutex; use url::Url; use crate::*; pub struct SimulatedCratesIoClient { state: Mutex<CratesIoState>, } struct CratesIoState { site_metadata:...
rust_dataset_chunk_508842
rust_dataset.txt
508,842
512
_id(&mut self) -> i32 { self.latest_id += 1; self.latest_id } fn team_id(&mut self, login: &str) -> TeamId { let login = login.to_ascii_lowercase(); if let Some(id) = self.team_ids.get(&login) { return *id; } let id = TeamId(self.next_id()); s...
rust_dataset_chunk_508843
rust_dataset.txt
508,843
512
: None, }, token_user: UserId(1), crates: BTreeMap::new(), team_ids: BTreeMap::new(), github_configs: BTreeMap::new(), latest_id: 1, }), }) } pub fn token_user(&self) -> UserId { self.sta...
rust_dataset_chunk_508844
rust_dataset.txt
508,844
512
Login>> { Ok(self .state .lock() .simulated_crate(name)? .invited_owners .clone()) } /// Changes crate fields that have no dedicated helper, such as its /// keywords or download counts. pub fn update_test_crate( &self, ...
rust_dataset_chunk_508845
rust_dataset.txt
508,845
512
_ref() .filter(|keyword| !keyword.is_empty()) .map(|keyword| has_value(&krate.keywords, keyword)) .or_else(|| { query .user_id .as_ref() .map(|user_id| ...
rust_dataset_chunk_508846
rust_dataset.txt
508,846
512
pub_only { simulated_crate.krate.trustpub_only = trustpub_only; } Ok(listed(&simulated_crate.krate)) } async fn list_owners(&self, name: &CrateName) -> Result<Vec<Owner>> { let mut state = self.state.lock(); Ok(state.simulated_crate(name)?.all_owners().collect()) ...
rust_dataset_chunk_508847
rust_dataset.txt
508,847
512
let mut state = self.state.lock(); let token_user = state.token_user; let simulated_crate = state.simulated_crate(name)?; simulated_crate.require_owner_rights(token_user)?; let mut removed = Vec::new(); for login in owners { let matching = simulated_crate ...
rust_dataset_chunk_508848
rust_dataset.txt
508,848
512
_owner_id = GitHubAccountId(state.next_id()); let github_config = GitHubConfig { id, crate_name: config.crate_name.clone(), repository_owner: config.repository_owner.clone(), repository_owner_id, repository_name: config.repository_name.clone(), ...
rust_dataset_chunk_508849
rust_dataset.txt
508,849
512
(&mut body).await?; let uri = request.uri().to_string(); let (status, response_body) = respond(&uri); requests.lock().push(RecordedRequest { method: request.method().clone(), uri, headers: request.headers().clone...
rust_dataset_chunk_508850
rust_dataset.txt
508,850
512
": "second" }] }); (status, errors) }); let client = RealCratesIoClient::new(fake_http_client, ApiToken::new("secret")); smol::block_on(client.get_site_metadata()).unwrap_err() }; assert!(matches!( error_for(StatusCode::FORBIDDEN), CratesIoError::PermissionDe...
rust_dataset_chunk_508851
rust_dataset.txt
508,851
512
); assert_eq!( requests[1].uri, "https://crates.io/api/v1/crates?user_id=7&per_page=100&seek=abc" ); } #[test] fn test_team_identity_is_shared_across_ownership_assignments() -> anyhow::Result<()> { let client = SimulatedCratesIoClient::new(); let owner = client.token_user(); let...
rust_dataset_chunk_508852
rust_dataset.txt
508,852
512
), (Some(""), Some(client.token_user()), &user_owned), (Some(""), None, &team_owned), (Some("keyword"), Some(client.token_user()), &keyword_match), (Some("keyword"), None, &keyword_match), ] { let listed = smol::block_on(client.list_crates(&CrateListQuery { keywor...
rust_dataset_chunk_508853
rust_dataset.txt
508,853
512
(fake_http_client, requests) = recording_fake_http_client(|_| { ( StatusCode::OK, json!({ "crates": [crate_json("matching")], "meta": { "next_page": null }, }), ) }); let real_client = RealCratesIoClient::new(fake_http_client, ...
rust_dataset_chunk_508854
rust_dataset.txt
508,854
512
}) } #[test] fn test_github_config_requests_match_crates_io_api() { let (fake_http_client, requests) = recording_fake_http_client(|uri| { let body = if uri.contains("crate=") { json!({ "github_configs": [github_config_json(3)], "meta": { "total": 1, "next_page":...
rust_dataset_chunk_508855
rust_dataset.txt
508,855
512
collect::<Vec<_>>(); let page = json!({ "github_configs": configs, "meta": { "total": 101, "next_page": "?crate=gpui&per_page=100&seek=abc" }, }); (StatusCode::OK, page) }); let client = RealCratesIoClient::new(fake_http_client, ApiToken::new("secret")); let ...
rust_dataset_chunk_508856
rust_dataset.txt
508,856
512
GitHubUser("maxbrunsfeld".into()), OwnerLogin::GitHubTeam { organization: "zed-industries".into(), team: "crates-io".into(), }, ]; let owners = smol::block_on(client().list_owners(&gpui)).unwrap(); let additions = smol::block_on(client().add_owners(&gpui, &owner_logi...
rust_dataset_chunk_508857
rust_dataset.txt
508,857
512
let throttle = RequestThrottle::new(); let start = Instant::now(); assert_eq!(throttle.reserve(start), start); assert_eq!(throttle.reserve(start), start + MIN_REQUEST_INTERVAL); assert_eq!(throttle.reserve(start), start + 2 * MIN_REQUEST_INTERVAL); let later = start + Duration::from_secs(10); ...
rust_dataset_chunk_508858
rust_dataset.txt
508,858
512
a search and alphabetically /// otherwise. Only the first 1000 results of a search can be listed. pub search: Option<String>, /// Also matches crates in subcategories. pub category: Option<String>, pub keyword: Option<String>, pub user_id: Option<UserId>, pub team_id: Option<TeamId>, //...
rust_dataset_chunk_508859
rust_dataset.txt
508,859
512
, Serialize, Deserialize)] pub struct Team { pub id: TeamId, /// For example `github:zed-industries:crates-io`. pub login: String, pub name: Option<String>, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "kind", rename_all = "lowercase")] pub enum Owner { User(User),...
rust_dataset_chunk_508860
rust_dataset.txt
508,860
512
#[serde(rename = "crate")] pub crate_name: CrateName, pub repository_owner: String, /// Lets crates.io recognize the repository after its owner is renamed. pub repository_owner_id: GitHubAccountId, pub repository_name: String, pub workflow_filename: String, pub environment: Option<String...
rust_dataset_chunk_508861
rust_dataset.txt
508,861
512
::fs::write", "std::fs::read_dir", "std::fs::read_link", "std::fs::metadata", "std::fs::symlink_metadata", "std::fs::set_permissions", "std::fs::canonicalize", "std::fs::create_dir", "std::fs::create_dir_all", "std::fs::remove_file", "std::fs::remove_dir", "std::fs::remove_di...
rust_dataset_chunk_508862
rust_dataset.txt
508,862
512
"bind"), ("TcpListener", "accept"), ("TcpListener", "incoming"), // std::net — UDP ("UdpSocket", "send"), ("UdpSocket", "send_to"), ("UdpSocket", "recv"), ("UdpSocket", "recv_from"), ("UdpSocket", "peek"), ("UdpSocket", "peek_from"), // std::sync ("Mutex", "lock"), ("RwL...
rust_dataset_chunk_508863
rust_dataset.txt
508,863
512
false } _ => false, } } /// Returns `true` if `ty` (after peeling references) is a synchronous GPUI /// foreground type: `App`, `Context`, or `Window`. fn is_gpui_foreground_type<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { let peeled = ty.peel_refs(); let Some(adt) = peeled.ty_ad...
rust_dataset_chunk_508864
rust_dataset.txt
508,864
512
_ => {} } } false } /// Checks whether the function identified by `local_def_id` has any parameter /// whose type is a synchronous GPUI foreground type. fn owner_has_foreground_param( cx: &LateContext<'_>, local_def_id: rustc_hir::def_id::LocalDefId, ) -> bool { let def_id = local_def_id.t...
rust_dataset_chunk_508865
rust_dataset.txt
508,865
512
lead to inconsistent UI state or infinite /// render loops. pub ENTITY_UPDATE_IN_RENDER, Warn, "mutating an entity via `.update()` during render" } pub(crate) struct EntityUpdateInRender; rustc_session::impl_lint_pass!(EntityUpdateInRender => [ENTITY_UPDATE_IN_RENDER]); impl<'tcx> LateLintPass<'tcx>...
rust_dataset_chunk_508866
rust_dataset.txt
508,866
512
::{LateContext, LateLintPass}; use rustc_middle::hir::nested_filter; use rustc_middle::ty::Ty; use rustc_span::Span; mod blocking_io_on_foreground; mod entity_update_in_render; mod map_lookup_then_insert; mod notify_in_render; mod owned_string_into_shared; mod render_helpers; use blocking_io_on_foreground::BLOCKING_I...
rust_dataset_chunk_508867
rust_dataset.txt
508,867
512
String::new_static`. /// /// ### Why is this bad? /// /// `SharedString` wraps a `SmolStr`. `SmolStr::from` either copies the /// bytes into inline storage (literals ≤ 23 bytes) or allocates a fresh /// `Arc<str>` on the heap (literals > 23 bytes). `SharedString::new_static` /// does neither...
rust_dataset_chunk_508868
rust_dataset.txt
508,868
512
SMOL_STR_INLINE_CAP: usize = 23; impl<'tcx> LateLintPass<'tcx> for SharedStringFromStrLiteral { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) { // Do not descend into macro-expanded code: we'd be suggesting edits to // spans the user cannot actually touch. if exp...
rust_dataset_chunk_508869
rust_dataset.txt
508,869
512
"lit"`. fn str_literal_contents<'tcx>(expr: &'tcx Expr<'tcx>) -> Option<String> { let inner = match &expr.kind { ExprKind::AddrOf(_, _, inner) => *inner, _ => expr, }; if let ExprKind::Lit(lit) = &inner.kind && let LitKind::Str(sym, _) = lit.node { Some(sym.as_str().to_ow...
rust_dataset_chunk_508870
rust_dataset.txt
508,870
512
.as_str() == "new_static" { return false; } if !matches!(name.as_str(), "from" | "new") { return false; } if let Some(impl_id) = tcx.impl_of_assoc(def_id) { let self_ty = tcx.type_of(impl_id).skip_binder(); return is_shared_string(cx, self_ty); } if let Some(trait...
rust_dataset_chunk_508871
rust_dataset.txt
508,871
512
allocates on every call" } else { "this `SharedString` construction copies the literal on every call" }; span_lint_and_then( cx, SHARED_STRING_FROM_STR_LITERAL, call_span, primary_msg, |diag| { if over_inline { diag.note(format!( ...
rust_dataset_chunk_508872
rust_dataset.txt
508,872
512
bytes.len() { if bytes[m] == b'"' { let mut close_hashes = 0; let mut n = m + 1; while close_hashes < hashes && n < bytes.len() && bytes[n] == b'#' { close_hashes += 1; n ...
rust_dataset_chunk_508873
rust_dataset.txt
508,873
512
} rustc_session::declare_lint_pass!(AsyncBlockWithoutAwait => [ASYNC_BLOCK_WITHOUT_AWAIT]); impl<'tcx> LateLintPass<'tcx> for AsyncBlockWithoutAwait { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) { if expr.span.from_expansion() { return; } // Match ...
rust_dataset_chunk_508874
rust_dataset.txt
508,874
512
(&mut self, expr: &'tcx Expr<'tcx>) { if let ExprKind::Yield(_, YieldSource::Await { .. }) = expr.kind { if self.async_depth == 0 { self.found_await = true; return; } } let is_nested_async_block = matches!( expr.kind, ...
rust_dataset_chunk_508875
rust_dataset.txt
508,875
512
/map_lookup_then_insert.rs --- use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::visitors::{Visitable, for_each_expr_without_closures}; use clippy_utils::{SpanlessEq, expr_or_init, sym}; use rustc_hir::def_id::DefId; use rustc_hir::{Expr, ExprKind, LangItem, LetStmt, MatchSource, UnOp}; use rustc_lin...
rust_dataset_chunk_508876
rust_dataset.txt
508,876
512
alone searches once, skips /// duplicates, and returns `false` when the value was already present. /// /// Forms that Clippy already rewrites are excluded. `contains_key` or /// `contains` followed by `insert` is `map_entry` or /// `set_contains_or_insert`, and `get(..).is_some()`/`is_none()` on th...
rust_dataset_chunk_508877
rust_dataset.txt
508,877
512
if local.span.from_expansion() { return; } let Some(init) = local.init else { return; }; let Some(else_block) = local.els else { return; }; let Some(lookup) = parse_lookup(cx, init) else { return; }; ...
rust_dataset_chunk_508878
rust_dataset.txt
508,878
512
value-preserving conversions do not count as side effects. let mut key_converted = false; let peeled_key = peel_key_expr(cx, key, &mut key_converted); if map.can_have_side_effects() || peeled_key.can_have_side_effects() { return None; } Some(Lookup { map, key }) } /// Searches `node` for ...
rust_dataset_chunk_508879
rust_dataset.txt
508,879
512
side /// effects: two structurally equal side-effecting initializers (say, two /// separate `next_key()` calls) are two different key values. fn keys_match<'tcx>( cx: &LateContext<'tcx>, lookup_key: &'tcx Expr<'tcx>, insert_key: &'tcx Expr<'tcx>, ) -> Option<bool> { let mut key_converted = false; ...
rust_dataset_chunk_508880
rust_dataset.txt
508,880
512
Unary(UnOp::Deref, inner) => { expression = inner; } _ => match peel_value_preserving_conversion(cx, expression) { Some(inner) => { *key_converted = true; expression = inner; } None => return ...
rust_dataset_chunk_508881
rust_dataset.txt
508,881
512
} // UFCS forms: `Clone::clone(&key)`, `ToOwned::to_owned(&key)`, and // `String::from(key)` where `key` is a `&str`. ExprKind::Call(callee, [argument]) => { let ExprKind::Path(qpath) = &callee.kind else { return None; }; let function = cx.qpa...
rust_dataset_chunk_508882
rust_dataset.txt
508,882
512
std /// map, are not covered by Clippy and stay ours. fn clippy_covers_get_then_check(cx: &LateContext<'_>, receiver: &Expr<'_>) -> bool { let ExprKind::MethodCall(segment, map, [_], _) = &receiver.kind else { return false; }; if segment.ident.name.as_str() != "get" { return false; } ...
rust_dataset_chunk_508883
rust_dataset.txt
508,883
512
.map) .peel_refs() .ty_adt_def() .is_some_and(|definition| is_std_set(cx, definition.did())); let (message, help) = if is_set { ( "this set lookup and insertion search for the same value twice", "`insert` alone searches once, skips duplicates, and returns `fa...
rust_dataset_chunk_508884
rust_dataset.txt
508,884
512
{ return; } let ExprKind::MethodCall(segment, receiver, _args, _span) = &expr.kind else { return; }; if segment.ident.name.as_str() != "notify" { return; } let receiver_ty = cx.typeck_results().expr_ty(receiver); if !is_gpui...
rust_dataset_chunk_508885
rust_dataset.txt
508,885
512
. pub OWNED_STRING_INTO_SHARED, Warn, "an owned `String` is built from a string literal only to be converted into a refcounted string" } pub(crate) struct OwnedStringIntoShared; rustc_session::impl_lint_pass!(OwnedStringIntoShared => [OWNED_STRING_INTO_SHARED]); impl<'tcx> LateLintPass<'tcx> for OwnedStr...
rust_dataset_chunk_508886
rust_dataset.txt
508,886
512
cx.tcx.def_path_str(did); let is_str_wrapper = matches!( path.as_str(), "alloc::sync::Arc" | "std::sync::Arc" | "alloc::rc::Rc" | "std::rc::Rc" | "alloc::borrow::Cow" | "std::borrow::Cow" ); if !is_str_wrapper { return fals...
rust_dataset_chunk_508887
rust_dataset.txt
508,887
512
-literal expression, optionally wrapped /// in a single layer of reference (`&"lit"`). fn is_string_literal<'tcx>(expr: &'tcx Expr<'tcx>) -> bool { let inner = match &expr.kind { ExprKind::AddrOf(_, _, inner) => *inner, _ => expr, }; matches!( &inner.kind, ExprKind::Lit(lit) ...
rust_dataset_chunk_508888
rust_dataset.txt
508,888
512
if let rustc_hir::def::Res::Def(_, trait_def_id) = trait_ref.trait_ref.path.res { return is_gpui_render_trait(cx, trait_def_id); } } } } false } fn is_gpui_render_trait(cx: &LateContext<'_>, trait_def_id: DefId) -> bool { let crate_nam...
rust_dataset_chunk_508889
rust_dataset.txt
508,889
512
{ if ty.is_unit() { return true; } if let Some(adt) = ty.ty_adt_def() { let path = cx.tcx.def_path_str(adt.did()); if path == "core::result::Result" || path == "std::result::Result" { if let Some(substs) = ty.walk().nth(1) { if let Some(inner_ty) = substs...
rust_dataset_chunk_508890
rust_dataset.txt
508,890
512
(owned_string_into_shared): `<lit>.to_owned().into()`. pub fn shared_string_from_to_owned() -> SharedString { "label".to_owned().into() } // Should NOT fire owned_string_into_shared: the source is a non-literal `String`. pub fn shared_string_from_dynamic_string(s: String) -> SharedString { s.into() } --- FI...
rust_dataset_chunk_508891
rust_dataset.txt
508,891
512
Window; // --- Entity --- pub struct Entity<T> { _marker: PhantomData<T>, } impl<T> Entity<T> { pub fn update<R, C: AppContext>( &self, _cx: &mut C, _f: impl FnOnce(&mut T, &mut Context<T>) -> R, ) -> R { unimplemented!() } pub fn read<'a>(&self, _cx: &'a App) ->...
rust_dataset_chunk_508892
rust_dataset.txt
508,892
512
window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { self.editor.update(cx, |editor, _cx| { editor.set_text("hello"); }); () } } // Entity::update with unit-returning closure in RenderOnce::render impl RenderOnce for CounterOnce { fn render(self, _window: &mut ...
rust_dataset_chunk_508893
rust_dataset.txt
508,893
512
{ editor.update(cx, |editor, _cx| { editor.set_text("inside closure"); }); }; () } } // ============================================================ // notify_in_render — SHOULD WARN // ============================================================ struct Not...
rust_dataset_chunk_508894
rust_dataset.txt
508,894
512
await. let _f = async move { returns_42().await }; // Regular closure (not async at all). let _f = || 42; } // --- Trait impl cases --- use std::future::Future; trait AsyncWork { fn do_work(&self) -> impl Future<Output = i32>; } struct Worker; // Should NOT warn: the trait requires returning a fu...
rust_dataset_chunk_508895
rust_dataset.txt
508,895
512
_metadata_with_app(cx: &mut App) { let _ = std::fs::symlink_metadata("file.txt"); } fn set_permissions_with_app(cx: &mut App) { if let Ok(meta) = std::fs::metadata("file.txt") { let _ = std::fs::set_permissions("file.txt", meta.permissions()); } } fn copy_with_app(cx: &mut App) { let _ = std::...
rust_dataset_chunk_508896
rust_dataset.txt
508,896
512
let _ = f.metadata(); } } fn file_try_clone_with_app(cx: &mut App) { if let Ok(f) = std::fs::File::open("x") { let _ = f.try_clone(); } } // --- std::thread --- fn sleep_with_context(cx: &mut Context<'_, Editor>) { std::thread::sleep(std::time::Duration::from_millis(100)); } // --- s...
rust_dataset_chunk_508897
rust_dataset.txt
508,897
512
_app(cx: &mut App) { let _ = std::net::TcpStream::connect("127.0.0.1:80"); } fn tcp_stream_connect_timeout_with_app(cx: &mut App) { let addr = std::net::SocketAddr::from(([127, 0, 0, 1], 80)); let _ = std::net::TcpStream::connect_timeout(&addr, std::time::Duration::from_secs(1)); } fn tcp_listener_accept_...
rust_dataset_chunk_508898
rust_dataset.txt
508,898
512
let _ = rw.read(); } fn rwlock_write_with_app(cx: &mut App) { let rw = std::sync::RwLock::new(42); let _ = rw.write(); } fn barrier_wait_with_app(cx: &mut App) { let b = std::sync::Barrier::new(1); b.wait(); } fn receiver_recv_with_app(cx: &mut App) { let (_tx, rx) = std::sync::mpsc::channel::<i...
rust_dataset_chunk_508899
rust_dataset.txt
508,899
512
#![allow(unused)] extern crate gpui; use gpui::*; struct Counter { value: i32, } // ============================================================ // SHOULD WARN — .update() returning () inside Render::render // ============================================================ struct MutatingView { counter: Entit...